fyrox_graph/
lib.rs

1// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in all
11// copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21#![allow(clippy::type_complexity)]
22
23//! Graph utilities and common algorithms.
24
25pub mod constructor;
26
27pub mod prelude {
28    pub use crate::{AbstractSceneGraph, BaseSceneGraph, SceneGraph};
29}
30
31use fxhash::FxHashMap;
32use fyrox_core::pool::{ErasedHandle, ObjectOrVariant, PayloadContainer};
33use fyrox_core::reflect::ReflectHandle;
34use fyrox_core::{
35    log::{Log, MessageKind},
36    pool::Handle,
37    reflect::prelude::*,
38    variable::{self, InheritableVariable},
39    ComponentProvider, NameProvider,
40};
41use fyrox_resource::{untyped::UntypedResource, Resource, TypedResourceData};
42use std::any::Any;
43use std::cmp::Ordering;
44use std::fmt::{Debug, Formatter};
45use std::{
46    any::TypeId,
47    ops::{Deref, DerefMut},
48};
49
50#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Reflect)]
51#[repr(u32)]
52pub enum NodeMapping {
53    UseNames = 0,
54    UseHandles = 1,
55}
56
57/// A `OriginalHandle -> CopyHandle` map. It is used to map handles to nodes after copying.
58///
59/// For example, scene nodes have lots of cross references, the simplest cross reference is a handle
60/// to parent node, and a set of handles to children nodes. Skinned meshes also store handles to
61/// scenes nodes that serve as bones. When you copy a node, you need handles of the copy to point
62/// to respective copies. This map allows you to do this.
63///
64/// Mapping could fail if you do a partial copy of some hierarchy that does not have respective
65/// copies of nodes that must be remapped. For example you can copy just a skinned mesh, but not
66/// its bones - in this case mapping will fail, but you still can use old handles even it does not
67/// make any sense.
68pub struct NodeHandleMap<N> {
69    pub(crate) map: FxHashMap<Handle<N>, Handle<N>>,
70}
71
72impl<N> Debug for NodeHandleMap<N> {
73    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
74        for (from, to) in self.map.iter() {
75            writeln!(f, "{from} -> {to}")?;
76        }
77        Ok(())
78    }
79}
80
81impl<N> Default for NodeHandleMap<N> {
82    fn default() -> Self {
83        Self {
84            map: Default::default(),
85        }
86    }
87}
88
89impl<N> Clone for NodeHandleMap<N> {
90    fn clone(&self) -> Self {
91        Self {
92            map: self.map.clone(),
93        }
94    }
95}
96
97impl<N> NodeHandleMap<N>
98where
99    N: Reflect + NameProvider,
100{
101    /// Adds new `original -> copy` handle mapping.
102    #[inline]
103    pub fn insert(
104        &mut self,
105        original_handle: Handle<N>,
106        copy_handle: Handle<N>,
107    ) -> Option<Handle<N>> {
108        self.map.insert(original_handle, copy_handle)
109    }
110
111    /// Maps a handle to a handle of its origin, or sets it to [Handle::NONE] if there is no such node.
112    /// It should be used when you are sure that respective origin exists.
113    #[inline]
114    pub fn map(&self, handle: &mut Handle<N>) -> &Self {
115        *handle = self.map.get(handle).cloned().unwrap_or_default();
116        self
117    }
118
119    /// Maps each handle in the slice to a handle of its origin, or sets it to [Handle::NONE] if there is no such node.
120    /// It should be used when you are sure that respective origin exists.
121    #[inline]
122    pub fn map_slice<T>(&self, handles: &mut [T]) -> &Self
123    where
124        T: Deref<Target = Handle<N>> + DerefMut,
125    {
126        for handle in handles {
127            self.map(handle);
128        }
129        self
130    }
131
132    /// Tries to map a handle to a handle of its origin. If it exists, the method returns true or false otherwise.
133    /// It should be used when you not sure that respective origin exists.
134    #[inline]
135    pub fn try_map(&self, handle: &mut Handle<N>) -> bool {
136        if let Some(new_handle) = self.map.get(handle) {
137            *handle = *new_handle;
138            true
139        } else {
140            false
141        }
142    }
143
144    /// Tries to map a handle to a handle of its origin. If it exists, the method returns true or false otherwise.
145    /// It should be used when you not sure that respective origin exists.
146    #[inline]
147    pub fn try_map_reflect(&self, reflect_handle: &mut dyn ReflectHandle) -> bool {
148        let handle = Handle::new(
149            reflect_handle.reflect_index(),
150            reflect_handle.reflect_generation(),
151        );
152        if let Some(new_handle) = self.map.get(&handle) {
153            reflect_handle.reflect_set_index(new_handle.index());
154            reflect_handle.reflect_set_generation(new_handle.generation());
155            true
156        } else {
157            false
158        }
159    }
160
161    /// Tries to map each handle in the slice to a handle of its origin. If it exists, the method returns true or false otherwise.
162    /// It should be used when you not sure that respective origin exists.
163    #[inline]
164    pub fn try_map_slice<T>(&self, handles: &mut [T]) -> bool
165    where
166        T: Deref<Target = Handle<N>> + DerefMut,
167    {
168        let mut success = true;
169        for handle in handles {
170            success &= self.try_map(handle);
171        }
172        success
173    }
174
175    /// Tries to silently map (without setting `modified` flag) a templated handle to a handle of its origin.
176    /// If it exists, the method returns true or false otherwise. It should be used when you not sure that respective
177    /// origin exists.
178    #[inline]
179    pub fn try_map_silent(&self, inheritable_handle: &mut InheritableVariable<Handle<N>>) -> bool {
180        if let Some(new_handle) = self.map.get(inheritable_handle) {
181            inheritable_handle.set_value_silent(*new_handle);
182            true
183        } else {
184            false
185        }
186    }
187
188    /// Returns a shared reference to inner map.
189    #[inline]
190    pub fn inner(&self) -> &FxHashMap<Handle<N>, Handle<N>> {
191        &self.map
192    }
193
194    /// Returns inner map.
195    #[inline]
196    pub fn into_inner(self) -> FxHashMap<Handle<N>, Handle<N>> {
197        self.map
198    }
199
200    /// Tries to remap handles to nodes in a given entity using reflection. It finds all supported fields recursively
201    /// (`Handle<Node>`, `Vec<Handle<Node>>`, `InheritableVariable<Handle<Node>>`, `InheritableVariable<Vec<Handle<Node>>>`)
202    /// and automatically maps old handles to new.
203    #[inline]
204    pub fn remap_handles(&self, node: &mut N, ignored_types: &[TypeId]) {
205        let name = node.name().to_string();
206        node.as_reflect_mut(&mut |node| self.remap_handles_internal(node, &name, ignored_types));
207    }
208
209    fn remap_handles_internal(
210        &self,
211        entity: &mut dyn Reflect,
212        node_name: &str,
213        ignored_types: &[TypeId],
214    ) {
215        if ignored_types.contains(&(*entity).type_id()) {
216            return;
217        }
218
219        let mut mapped = false;
220
221        entity.downcast_mut::<Handle<N>>(&mut |handle| {
222            if let Some(handle) = handle {
223                if handle.is_some() && !self.try_map(handle) {
224                    Log::warn(format!(
225                        "Failed to remap handle {} of node {}!",
226                        *handle, node_name
227                    ));
228                }
229                mapped = true;
230            }
231        });
232
233        if mapped {
234            return;
235        }
236
237        // Handle derived entities handles.
238        entity.as_handle_mut(&mut |handle| {
239            if let Some(handle) = handle {
240                if handle.query_derived_types().contains(&TypeId::of::<N>())
241                    && handle.reflect_is_some()
242                    && !self.try_map_reflect(handle)
243                {
244                    Log::warn(format!(
245                        "Failed to remap handle {}:{} of node {}!",
246                        handle.reflect_index(),
247                        handle.reflect_generation(),
248                        node_name
249                    ));
250                }
251                mapped = true;
252            }
253        });
254
255        if mapped {
256            return;
257        }
258
259        entity.as_inheritable_variable_mut(&mut |inheritable| {
260            if let Some(inheritable) = inheritable {
261                // In case of inheritable variable we must take inner value and do not mark variables as modified.
262                self.remap_handles_internal(
263                    inheritable.inner_value_mut(),
264                    node_name,
265                    ignored_types,
266                );
267
268                mapped = true;
269            }
270        });
271
272        if mapped {
273            return;
274        }
275
276        entity.as_array_mut(&mut |array| {
277            if let Some(array) = array {
278                // Look in every array item.
279                for i in 0..array.reflect_len() {
280                    // Sparse arrays (like Pool) could have empty entries.
281                    if let Some(item) = array.reflect_index_mut(i) {
282                        self.remap_handles_internal(item, node_name, ignored_types);
283                    }
284                }
285                mapped = true;
286            }
287        });
288
289        if mapped {
290            return;
291        }
292
293        entity.as_hash_map_mut(&mut |hash_map| {
294            if let Some(hash_map) = hash_map {
295                for i in 0..hash_map.reflect_len() {
296                    if let Some(item) = hash_map.reflect_get_nth_value_mut(i) {
297                        self.remap_handles_internal(item, node_name, ignored_types);
298                    }
299                }
300                mapped = true;
301            }
302        });
303
304        if mapped {
305            return;
306        }
307
308        // Continue remapping recursively for every compound field.
309        entity.fields_mut(&mut |fields| {
310            for field_info_mut in fields {
311                field_info_mut
312                    .value
313                    .field_value_as_reflect_mut()
314                    .as_reflect_mut(&mut |field| {
315                        self.remap_handles_internal(field, node_name, ignored_types)
316                    })
317            }
318        })
319    }
320
321    #[inline]
322    pub fn remap_inheritable_handles(&self, node: &mut N, ignored_types: &[TypeId]) {
323        let name = node.name().to_string();
324        node.as_reflect_mut(&mut |node| {
325            self.remap_inheritable_handles_internal(node, &name, false, ignored_types)
326        });
327    }
328
329    fn remap_inheritable_handles_internal(
330        &self,
331        entity: &mut dyn Reflect,
332        node_name: &str,
333        do_map: bool,
334        ignored_types: &[TypeId],
335    ) {
336        if ignored_types.contains(&(*entity).type_id()) {
337            return;
338        }
339
340        let mut mapped = false;
341
342        entity.as_inheritable_variable_mut(&mut |result| {
343            if let Some(inheritable) = result {
344                // In case of inheritable variable we must take inner value and do not mark variables as modified.
345                if !inheritable.is_modified() {
346                    self.remap_inheritable_handles_internal(
347                        inheritable.inner_value_mut(),
348                        node_name,
349                        // Raise mapping flag, any handle in inner value will be mapped. The flag is propagated
350                        // to unlimited depth.
351                        true,
352                        ignored_types,
353                    );
354                }
355                mapped = true;
356            }
357        });
358
359        if mapped {
360            return;
361        }
362
363        entity.downcast_mut::<Handle<N>>(&mut |result| {
364            if let Some(handle) = result {
365                if do_map && handle.is_some() && !self.try_map(handle) {
366                    Log::warn(format!(
367                        "Failed to remap handle {} of node {}!",
368                        *handle, node_name
369                    ));
370                }
371                mapped = true;
372            }
373        });
374
375        if mapped {
376            return;
377        }
378
379        // Handle derived entities handles.
380        entity.as_handle_mut(&mut |handle| {
381            if let Some(handle) = handle {
382                if do_map
383                    && handle.query_derived_types().contains(&TypeId::of::<N>())
384                    && handle.reflect_is_some()
385                    && !self.try_map_reflect(handle)
386                {
387                    Log::warn(format!(
388                        "Failed to remap handle {}:{} of node {}!",
389                        handle.reflect_index(),
390                        handle.reflect_generation(),
391                        node_name
392                    ));
393                }
394                mapped = true;
395            }
396        });
397
398        if mapped {
399            return;
400        }
401
402        entity.as_array_mut(&mut |result| {
403            if let Some(array) = result {
404                // Look in every array item.
405                for i in 0..array.reflect_len() {
406                    // Sparse arrays (like Pool) could have empty entries.
407                    if let Some(item) = array.reflect_index_mut(i) {
408                        self.remap_inheritable_handles_internal(
409                            item,
410                            node_name,
411                            // Propagate mapping flag - it means that we're inside inheritable variable. In this
412                            // case we will map handles.
413                            do_map,
414                            ignored_types,
415                        );
416                    }
417                }
418                mapped = true;
419            }
420        });
421
422        if mapped {
423            return;
424        }
425
426        entity.as_hash_map_mut(&mut |result| {
427            if let Some(hash_map) = result {
428                for i in 0..hash_map.reflect_len() {
429                    if let Some(item) = hash_map.reflect_get_nth_value_mut(i) {
430                        self.remap_inheritable_handles_internal(
431                            item,
432                            node_name,
433                            // Propagate mapping flag - it means that we're inside inheritable variable. In this
434                            // case we will map handles.
435                            do_map,
436                            ignored_types,
437                        );
438                    }
439                }
440                mapped = true;
441            }
442        });
443
444        if mapped {
445            return;
446        }
447
448        // Continue remapping recursively for every compound field.
449        entity.fields_mut(&mut |fields| {
450            for field_info_mut in fields {
451                self.remap_inheritable_handles_internal(
452                    field_info_mut.value.field_value_as_reflect_mut(),
453                    node_name,
454                    // Propagate mapping flag - it means that we're inside inheritable variable. In this
455                    // case we will map handles.
456                    do_map,
457                    ignored_types,
458                );
459            }
460        })
461    }
462}
463
464fn reset_property_modified_flag(entity: &mut dyn Reflect, path: &str) {
465    entity.as_reflect_mut(&mut |entity| {
466        entity.resolve_path_mut(path, &mut |result| {
467            variable::mark_inheritable_properties_non_modified(
468                result.unwrap(),
469                &[TypeId::of::<UntypedResource>()],
470            );
471        })
472    })
473}
474
475pub trait AbstractSceneNode: ComponentProvider + Reflect + NameProvider {}
476
477impl<T: SceneGraphNode> AbstractSceneNode for T {}
478
479pub trait SceneGraphNode: AbstractSceneNode + Clone + 'static {
480    type Base: Clone;
481    type SceneGraph: SceneGraph<Node = Self>;
482    type ResourceData: PrefabData<Graph = Self::SceneGraph>;
483
484    fn base(&self) -> &Self::Base;
485    fn set_base(&mut self, base: Self::Base);
486    fn is_resource_instance_root(&self) -> bool;
487    fn original_handle_in_resource(&self) -> Handle<Self>;
488    fn set_original_handle_in_resource(&mut self, handle: Handle<Self>);
489    fn resource(&self) -> Option<Resource<Self::ResourceData>>;
490    fn self_handle(&self) -> Handle<Self>;
491    fn parent(&self) -> Handle<Self>;
492    fn children(&self) -> &[Handle<Self>];
493    fn children_mut(&mut self) -> &mut [Handle<Self>];
494
495    /// Puts the given `child` handle to the given position `pos`, by swapping positions.
496    #[inline]
497    fn swap_child_position(&mut self, child: Handle<Self>, pos: usize) -> Option<usize> {
498        let children = self.children_mut();
499
500        if pos >= children.len() {
501            return None;
502        }
503
504        if let Some(current_position) = children.iter().position(|c| *c == child) {
505            children.swap(current_position, pos);
506
507            Some(current_position)
508        } else {
509            None
510        }
511    }
512
513    #[inline]
514    fn set_child_position(&mut self, child: Handle<Self>, dest_pos: usize) -> Option<usize> {
515        let children = self.children_mut();
516
517        if dest_pos >= children.len() {
518            return None;
519        }
520
521        if let Some(mut current_position) = children.iter().position(|c| *c == child) {
522            let prev_position = current_position;
523
524            match current_position.cmp(&dest_pos) {
525                Ordering::Less => {
526                    while current_position != dest_pos {
527                        let next = current_position.saturating_add(1);
528                        children.swap(current_position, next);
529                        current_position = next;
530                    }
531                }
532                Ordering::Equal => {}
533                Ordering::Greater => {
534                    while current_position != dest_pos {
535                        let prev = current_position.saturating_sub(1);
536                        children.swap(current_position, prev);
537                        current_position = prev;
538                    }
539                }
540            }
541
542            Some(prev_position)
543        } else {
544            None
545        }
546    }
547
548    #[inline]
549    fn child_position(&self, child: Handle<Self>) -> Option<usize> {
550        self.children().iter().position(|c| *c == child)
551    }
552
553    #[inline]
554    fn has_child(&self, child: Handle<Self>) -> bool {
555        self.children().contains(&child)
556    }
557
558    fn revert_inheritable_property(&mut self, path: &str) -> Option<Box<dyn Reflect>> {
559        let mut previous_value = None;
560
561        // Revert only if there's parent resource (the node is an instance of some resource).
562        if let Some(resource) = self.resource().as_ref() {
563            let resource_data = resource.data_ref();
564            let parent = &resource_data
565                .graph()
566                .node(self.original_handle_in_resource());
567
568            let mut parent_value = None;
569
570            // Find and clone parent's value first.
571            parent.as_reflect(&mut |parent| {
572                parent.resolve_path(path, &mut |result| match result {
573                    Ok(parent_field) => parent_field.as_inheritable_variable(&mut |parent_field| {
574                        if let Some(parent_inheritable) = parent_field {
575                            parent_value = Some(parent_inheritable.clone_value_box());
576                        }
577                    }),
578                    Err(e) => Log::err(format!(
579                        "Failed to resolve parent path {path}. Reason: {e:?}"
580                    )),
581                })
582            });
583
584            // Check whether the child's field is inheritable and modified.
585            let mut need_revert = false;
586
587            self.as_reflect_mut(&mut |child| {
588                child.resolve_path_mut(path, &mut |result| match result {
589                    Ok(child_field) => {
590                        child_field.as_inheritable_variable_mut(&mut |child_inheritable| {
591                            if let Some(child_inheritable) = child_inheritable {
592                                need_revert = child_inheritable.is_modified();
593                            } else {
594                                Log::err(format!("Property {path} is not inheritable!"))
595                            }
596                        })
597                    }
598                    Err(e) => Log::err(format!(
599                        "Failed to resolve child path {path}. Reason: {e:?}"
600                    )),
601                });
602            });
603
604            // Try to apply it to the child.
605            if need_revert {
606                if let Some(parent_value) = parent_value {
607                    let mut was_set = false;
608
609                    let mut parent_value = Some(parent_value);
610                    self.as_reflect_mut(&mut |child| {
611                        child.set_field_by_path(
612                            path,
613                            parent_value.take().unwrap(),
614                            &mut |result| match result {
615                                Ok(old_value) => {
616                                    previous_value = Some(old_value);
617
618                                    was_set = true;
619                                }
620                                Err(_) => Log::err(format!(
621                                    "Failed to revert property {path}. Reason: no such property!"
622                                )),
623                            },
624                        );
625                    });
626
627                    if was_set {
628                        // Reset modified flag.
629                        reset_property_modified_flag(self, path);
630                    }
631                }
632            }
633        }
634
635        previous_value
636    }
637
638    /// Tries to borrow a component of given type.
639    #[inline]
640    fn component_ref<T: Any>(&self) -> Option<&T> {
641        ComponentProvider::query_component_ref(self, TypeId::of::<T>())
642            .and_then(|c| c.downcast_ref())
643    }
644
645    /// Tries to borrow a component of given type.
646    #[inline]
647    fn component_mut<T: Any>(&mut self) -> Option<&mut T> {
648        ComponentProvider::query_component_mut(self, TypeId::of::<T>())
649            .and_then(|c| c.downcast_mut())
650    }
651
652    /// Checks if the node has a component of given type.
653    #[inline]
654    fn has_component<T: Any>(&self) -> bool {
655        self.component_ref::<T>().is_some()
656    }
657}
658
659pub trait PrefabData: TypedResourceData + 'static {
660    type Graph: SceneGraph;
661
662    fn graph(&self) -> &Self::Graph;
663    fn mapping(&self) -> NodeMapping;
664}
665
666#[derive(Debug)]
667pub struct LinkScheme<N> {
668    pub root: Handle<N>,
669    pub links: Vec<(Handle<N>, Handle<N>)>,
670}
671
672impl<N> Default for LinkScheme<N> {
673    fn default() -> Self {
674        Self {
675            root: Default::default(),
676            links: Default::default(),
677        }
678    }
679}
680
681pub trait AbstractSceneGraph: 'static {
682    fn try_get_node_untyped(&self, handle: ErasedHandle) -> Option<&dyn AbstractSceneNode>;
683    fn try_get_node_untyped_mut(
684        &mut self,
685        handle: ErasedHandle,
686    ) -> Option<&mut dyn AbstractSceneNode>;
687}
688
689/// BaseSceneGraph is a dyn-compatible trait for all scene graphs to implement.
690/// Methods that would not be dyn-compatible are available through the
691/// [`SceneGraph`] trait.
692pub trait BaseSceneGraph: AbstractSceneGraph {
693    type Prefab: PrefabData<Graph = Self>;
694    type NodeContainer: PayloadContainer<Element = Self::Node>;
695    type Node: SceneGraphNode<SceneGraph = Self, ResourceData = Self::Prefab>;
696
697    /// Generate a string that briefly summarizes the content of the graph for debugging.
698    fn summary(&self) -> String;
699
700    /// Returns actual type id of the node.
701    fn actual_type_id(&self, handle: Handle<Self::Node>) -> Option<TypeId>;
702
703    /// Returns actual type name of the node.
704    fn actual_type_name(&self, handle: Handle<Self::Node>) -> Option<&'static str>;
705
706    /// Returns a list of derived type ids of the node.
707    fn derived_type_ids(&self, handle: Handle<Self::Node>) -> Option<Vec<TypeId>>;
708
709    /// Returns a handle of the root node of the graph.
710    fn root(&self) -> Handle<Self::Node>;
711
712    /// Sets the new root of the graph. If used incorrectly, it may create isolated sub-graphs.
713    fn set_root(&mut self, root: Handle<Self::Node>);
714
715    /// Tries to borrow a node, returns Some(node) if the handle is valid, None - otherwise.
716    fn try_get_node(&self, handle: Handle<Self::Node>) -> Option<&Self::Node>;
717
718    /// Tries to borrow a node, returns Some(node) if the handle is valid, None - otherwise.
719    fn try_get_node_mut(&mut self, handle: Handle<Self::Node>) -> Option<&mut Self::Node>;
720
721    /// Checks whether the given node handle is valid or not.
722    fn is_valid_handle(&self, handle: Handle<Self::Node>) -> bool;
723
724    /// Adds a new node to the graph.
725    fn add_node(&mut self, node: Self::Node) -> Handle<Self::Node>;
726
727    /// Destroys the node and its children recursively.
728    fn remove_node(&mut self, node_handle: Handle<Self::Node>);
729
730    /// Links specified child with specified parent.
731    fn link_nodes(&mut self, child: Handle<Self::Node>, parent: Handle<Self::Node>);
732
733    /// Unlinks specified node from its parent and attaches it to root graph node.
734    fn unlink_node(&mut self, node_handle: Handle<Self::Node>);
735
736    /// Detaches the node from its parent, making the node unreachable from any other node in the
737    /// graph.
738    fn isolate_node(&mut self, node_handle: Handle<Self::Node>);
739
740    /// Borrows a node by its handle.
741    fn node(&self, handle: Handle<Self::Node>) -> &Self::Node {
742        self.try_get_node(handle)
743            .expect("The handle must be valid!")
744    }
745
746    /// Borrows a node by its handle.
747    fn node_mut(&mut self, handle: Handle<Self::Node>) -> &mut Self::Node {
748        self.try_get_node_mut(handle)
749            .expect("The handle must be valid!")
750    }
751
752    /// Reorders the node hierarchy so the `new_root` becomes the root node for the entire hierarchy
753    /// under the `prev_root` node. For example, if we have this hierarchy and want to set `C` as
754    /// the new root:
755    ///
756    /// ```text
757    /// Root_
758    ///      |_A_
759    ///          |_B
760    ///          |_C_
761    ///             |_D
762    /// ```
763    ///
764    /// The new hierarchy will become:
765    ///
766    /// ```text
767    /// C_
768    ///   |_D
769    ///   |_A_
770    ///   |   |_B
771    ///   |_Root
772    /// ```
773    ///
774    /// This method returns an instance of [`LinkScheme`], that could be used to revert the hierarchy
775    /// back to its original. See [`Self::apply_link_scheme`] for more info.
776    #[inline]
777    #[allow(clippy::unnecessary_to_owned)] // False-positive
778    fn change_hierarchy_root(
779        &mut self,
780        prev_root: Handle<Self::Node>,
781        new_root: Handle<Self::Node>,
782    ) -> LinkScheme<Self::Node> {
783        let mut scheme = LinkScheme::default();
784
785        if prev_root == new_root {
786            return scheme;
787        }
788
789        scheme
790            .links
791            .push((prev_root, self.node(prev_root).parent()));
792
793        scheme.links.push((new_root, self.node(new_root).parent()));
794
795        self.isolate_node(new_root);
796
797        for prev_root_child in self.node(prev_root).children().to_vec() {
798            self.link_nodes(prev_root_child, new_root);
799            scheme.links.push((prev_root_child, prev_root));
800        }
801
802        self.link_nodes(prev_root, new_root);
803
804        if prev_root == self.root() {
805            self.set_root(new_root);
806            scheme.root = prev_root;
807        } else {
808            scheme.root = self.root();
809        }
810
811        scheme
812    }
813
814    /// Applies the given link scheme to the graph, basically reverting graph structure to the one
815    /// that was before the call of [`Self::change_hierarchy_root`].
816    #[inline]
817    fn apply_link_scheme(&mut self, mut scheme: LinkScheme<Self::Node>) {
818        for (child, parent) in scheme.links.drain(..) {
819            if parent.is_some() {
820                self.link_nodes(child, parent);
821            } else {
822                self.isolate_node(child);
823            }
824        }
825        if scheme.root.is_some() {
826            self.set_root(scheme.root);
827        }
828    }
829
830    /// Removes all the nodes from the given slice.
831    #[inline]
832    fn remove_nodes(&mut self, nodes: &[Handle<Self::Node>]) {
833        for &node in nodes {
834            if self.is_valid_handle(node) {
835                self.remove_node(node)
836            }
837        }
838    }
839}
840
841/// SceneGraph is a non-dyn-compatible trait for all scene graphs to implement.
842/// To use a scene graph as a dyn object, use `dyn BaseSceneGraph` because
843/// [`BaseSceneGraph`] is dyn-compatible.
844pub trait SceneGraph: BaseSceneGraph {
845    type ObjectType: Sized;
846    /// Creates new iterator that iterates over internal collection giving (handle; node) pairs.
847    fn pair_iter(&self) -> impl Iterator<Item = (Handle<Self::Node>, &Self::Node)>;
848
849    /// Creates an iterator that has linear iteration order over internal collection
850    /// of nodes. It does *not* perform any tree traversal!
851    fn linear_iter(&self) -> impl Iterator<Item = &Self::Node>;
852
853    /// Creates an iterator that has linear iteration order over internal collection
854    /// of nodes. It does *not* perform any tree traversal!
855    fn linear_iter_mut(&mut self) -> impl Iterator<Item = &mut Self::Node>;
856
857    fn try_get<U: ObjectOrVariant<Self::ObjectType>>(&self, handle: Handle<U>) -> Option<&U>;
858
859    fn try_get_mut<U: ObjectOrVariant<Self::ObjectType>>(
860        &mut self,
861        handle: Handle<U>,
862    ) -> Option<&mut U>;
863
864    /// Tries to borrow a node and fetch its component of specified type.
865    #[inline]
866    fn try_get_of_type<T>(&self, handle: Handle<Self::Node>) -> Option<&T>
867    where
868        T: 'static,
869    {
870        self.try_get_node(handle)
871            .and_then(|n| n.query_component_ref(TypeId::of::<T>()))
872            .and_then(|c| c.downcast_ref())
873    }
874
875    /// Tries to mutably borrow a node and fetch its component of specified type.
876    #[inline]
877    fn try_get_mut_of_type<T>(&mut self, handle: Handle<Self::Node>) -> Option<&mut T>
878    where
879        T: 'static,
880    {
881        self.try_get_node_mut(handle)
882            .and_then(|n| n.query_component_mut(TypeId::of::<T>()))
883            .and_then(|c| c.downcast_mut())
884    }
885
886    /// Tries to borrow a node by the given handle and checks if it has a component of the specified
887    /// type.
888    #[inline]
889    fn has_component<T>(&self, handle: Handle<Self::Node>) -> bool
890    where
891        T: 'static,
892    {
893        self.try_get_of_type::<T>(handle).is_some()
894    }
895
896    /// Searches for a node down the tree starting from the specified node using the specified closure. Returns a tuple
897    /// with a handle and a reference to the mapped value. If nothing is found, it returns [`None`].
898    #[inline]
899    fn find_map<C, T>(
900        &self,
901        root_node: Handle<Self::Node>,
902        cmp: &mut C,
903    ) -> Option<(Handle<Self::Node>, &T)>
904    where
905        C: FnMut(&Self::Node) -> Option<&T>,
906        T: ?Sized,
907    {
908        self.try_get_node(root_node).and_then(|root| {
909            if let Some(x) = cmp(root) {
910                Some((root_node, x))
911            } else {
912                root.children().iter().find_map(|c| self.find_map(*c, cmp))
913            }
914        })
915    }
916
917    /// Searches for a node up the tree starting from the specified node using the specified closure. Returns a tuple
918    /// with a handle and a reference to the found node. If nothing is found, it returns [`None`].
919    #[inline]
920    fn find_up<C>(
921        &self,
922        root_node: Handle<Self::Node>,
923        cmp: &mut C,
924    ) -> Option<(Handle<Self::Node>, &Self::Node)>
925    where
926        C: FnMut(&Self::Node) -> bool,
927    {
928        let mut handle = root_node;
929        while let Some(node) = self.try_get_node(handle) {
930            if cmp(node) {
931                return Some((handle, node));
932            }
933            handle = node.parent();
934        }
935        None
936    }
937
938    /// The same as [`Self::find_up`], but only returns node handle which will be [`Handle::NONE`]
939    /// if nothing is found.
940    #[inline]
941    fn find_handle_up<C>(&self, root_node: Handle<Self::Node>, cmp: &mut C) -> Handle<Self::Node>
942    where
943        C: FnMut(&Self::Node) -> bool,
944    {
945        self.find_up(root_node, cmp)
946            .map(|(h, _)| h)
947            .unwrap_or_default()
948    }
949
950    #[inline]
951    fn find_component_up<T>(
952        &self,
953        node_handle: Handle<Self::Node>,
954    ) -> Option<(Handle<Self::Node>, &T)>
955    where
956        T: 'static,
957    {
958        self.find_up_map(node_handle, &mut |node| {
959            node.query_component_ref(TypeId::of::<T>())
960        })
961        .and_then(|(handle, c)| c.downcast_ref::<T>().map(|typed| (handle, typed)))
962    }
963
964    #[inline]
965    fn find_component<T>(&self, node_handle: Handle<Self::Node>) -> Option<(Handle<Self::Node>, &T)>
966    where
967        T: 'static,
968    {
969        self.find_map(node_handle, &mut |node| {
970            node.query_component_ref(TypeId::of::<T>())
971        })
972        .and_then(|(handle, c)| c.downcast_ref::<T>().map(|typed| (handle, typed)))
973    }
974
975    /// Searches for a node up the tree starting from the specified node using the specified closure. Returns a tuple
976    /// with a handle and a reference to the mapped value. If nothing is found, it returns [`None`].
977    #[inline]
978    fn find_up_map<C, T>(
979        &self,
980        root_node: Handle<Self::Node>,
981        cmp: &mut C,
982    ) -> Option<(Handle<Self::Node>, &T)>
983    where
984        C: FnMut(&Self::Node) -> Option<&T>,
985        T: ?Sized,
986    {
987        let mut handle = root_node;
988        while let Some(node) = self.try_get_node(handle) {
989            if let Some(x) = cmp(node) {
990                return Some((handle, x));
991            }
992            handle = node.parent();
993        }
994        None
995    }
996
997    /// Searches for a node with the specified name down the tree starting from the specified node. Returns a tuple with
998    /// a handle and a reference to the found node. If nothing is found, it returns [`None`].
999    #[inline]
1000    fn find_by_name(
1001        &self,
1002        root_node: Handle<Self::Node>,
1003        name: &str,
1004    ) -> Option<(Handle<Self::Node>, &Self::Node)> {
1005        self.find(root_node, &mut |node| node.name() == name)
1006    }
1007
1008    /// Searches for a node with the specified name up the tree starting from the specified node. Returns a tuple with a
1009    /// handle and a reference to the found node. If nothing is found, it returns [`None`].
1010    #[inline]
1011    fn find_up_by_name(
1012        &self,
1013        root_node: Handle<Self::Node>,
1014        name: &str,
1015    ) -> Option<(Handle<Self::Node>, &Self::Node)> {
1016        self.find_up(root_node, &mut |node| node.name() == name)
1017    }
1018
1019    /// Searches for a node with the specified name down the tree starting from the graph root. Returns a tuple with a
1020    /// handle and a reference to the found node. If nothing is found, it returns [`None`].
1021    #[inline]
1022    fn find_by_name_from_root(&self, name: &str) -> Option<(Handle<Self::Node>, &Self::Node)> {
1023        self.find_by_name(self.root(), name)
1024    }
1025
1026    #[inline]
1027    fn find_handle_by_name_from_root(&self, name: &str) -> Handle<Self::Node> {
1028        self.find_by_name(self.root(), name)
1029            .map(|(h, _)| h)
1030            .unwrap_or_default()
1031    }
1032
1033    /// Searches node using specified compare closure starting from root. Returns a tuple with a handle and
1034    /// a reference to the found node. If nothing is found, it returns [`None`].
1035    #[inline]
1036    fn find_from_root<C>(&self, cmp: &mut C) -> Option<(Handle<Self::Node>, &Self::Node)>
1037    where
1038        C: FnMut(&Self::Node) -> bool,
1039    {
1040        self.find(self.root(), cmp)
1041    }
1042
1043    /// Searches for a node down the tree starting from the specified node using the specified closure.
1044    /// Returns a tuple with a handle and a reference to the found node. If nothing is found, it
1045    /// returns [`None`].
1046    #[inline]
1047    fn find<C>(
1048        &self,
1049        root_node: Handle<Self::Node>,
1050        cmp: &mut C,
1051    ) -> Option<(Handle<Self::Node>, &Self::Node)>
1052    where
1053        C: FnMut(&Self::Node) -> bool,
1054    {
1055        self.try_get_node(root_node).and_then(|root| {
1056            if cmp(root) {
1057                Some((root_node, root))
1058            } else {
1059                root.children().iter().find_map(|c| self.find(*c, cmp))
1060            }
1061        })
1062    }
1063
1064    /// The same as [`Self::find`], but only returns node handle which will be [`Handle::NONE`]
1065    /// if nothing is found.
1066    #[inline]
1067    fn find_handle<C>(&self, root_node: Handle<Self::Node>, cmp: &mut C) -> Handle<Self::Node>
1068    where
1069        C: FnMut(&Self::Node) -> bool,
1070    {
1071        self.find(root_node, cmp)
1072            .map(|(h, _)| h)
1073            .unwrap_or_default()
1074    }
1075
1076    /// Returns position of the node in its parent children list and the handle to the parent. Adds
1077    /// given `offset` to the position. For example, if you have the following hierarchy:
1078    ///
1079    /// ```text
1080    /// A_
1081    ///  |B
1082    ///  |C
1083    /// ```
1084    ///
1085    /// Calling this method with a handle of `C` will return `Some((handle_of(A), 1))`. The returned
1086    /// value will be clamped in the `0..parent_child_count` range. `None` will be returned only if
1087    /// the given handle is invalid, or it is the root node.
1088    #[inline]
1089    fn relative_position(
1090        &self,
1091        child: Handle<Self::Node>,
1092        offset: isize,
1093    ) -> Option<(Handle<Self::Node>, usize)> {
1094        let parents_parent_handle = self.try_get_node(child)?.parent();
1095        let parents_parent_ref = self.try_get_node(parents_parent_handle)?;
1096        let position = parents_parent_ref.child_position(child)?;
1097        Some((
1098            parents_parent_handle,
1099            ((position as isize + offset) as usize).clamp(0, parents_parent_ref.children().len()),
1100        ))
1101    }
1102
1103    /// Create a graph depth traversal iterator.
1104    #[inline]
1105    fn traverse_iter(
1106        &self,
1107        from: Handle<Self::Node>,
1108    ) -> impl Iterator<Item = (Handle<Self::Node>, &Self::Node)> {
1109        self.try_get_node(from).expect("Handle must be valid!");
1110        GraphTraverseIterator {
1111            graph: self,
1112            stack: vec![from],
1113        }
1114    }
1115
1116    /// Create a graph depth traversal iterator.
1117    #[inline]
1118    fn traverse_handle_iter(
1119        &self,
1120        from: Handle<Self::Node>,
1121    ) -> impl Iterator<Item = Handle<Self::Node>> {
1122        self.traverse_iter(from).map(|(handle, _)| handle)
1123    }
1124
1125    /// This method checks integrity of the graph and restores it if needed. For example, if a node
1126    /// was added in a parent asset, then it must be added in the graph. Alternatively, if a node was
1127    /// deleted in a parent asset, then its instance must be deleted in the graph.
1128    fn restore_integrity<F>(
1129        &mut self,
1130        mut instantiate: F,
1131    ) -> Vec<(Handle<Self::Node>, Resource<Self::Prefab>)>
1132    where
1133        F: FnMut(
1134            Resource<Self::Prefab>,
1135            &Self::Prefab,
1136            Handle<Self::Node>,
1137            &mut Self,
1138        ) -> (Handle<Self::Node>, NodeHandleMap<Self::Node>),
1139    {
1140        Log::writeln(MessageKind::Information, "Checking integrity...");
1141
1142        let instances = self
1143            .pair_iter()
1144            .filter_map(|(h, n)| {
1145                if n.is_resource_instance_root() {
1146                    Some((h, n.resource().unwrap()))
1147                } else {
1148                    None
1149                }
1150            })
1151            .collect::<Vec<_>>();
1152
1153        let instance_count = instances.len();
1154        let mut restored_count = 0;
1155
1156        for (instance_root, resource) in instances.iter().cloned() {
1157            // Step 1. Find and remove orphaned nodes.
1158            let mut nodes_to_delete = Vec::new();
1159            for (_, node) in self.traverse_iter(instance_root) {
1160                if let Some(resource) = node.resource() {
1161                    if let Some(model) = resource.state().data() {
1162                        if !model
1163                            .graph()
1164                            .is_valid_handle(node.original_handle_in_resource())
1165                        {
1166                            nodes_to_delete.push(node.self_handle());
1167
1168                            Log::warn(format!(
1169                                "Node {} ({}:{}) and its children will be deleted, because it \
1170                    does not exist in the parent asset!",
1171                                node.name(),
1172                                node.self_handle().index(),
1173                                node.self_handle().generation(),
1174                            ))
1175                        }
1176                    } else {
1177                        Log::warn(format!(
1178                            "Node {} ({}:{}) and its children will be deleted, because its \
1179                    parent asset failed to load!",
1180                            node.name(),
1181                            node.self_handle().index(),
1182                            node.self_handle().generation(),
1183                        ))
1184                    }
1185                }
1186            }
1187
1188            for node_to_delete in nodes_to_delete {
1189                if self.is_valid_handle(node_to_delete) {
1190                    self.remove_node(node_to_delete);
1191                }
1192            }
1193
1194            // Step 2. Look for missing nodes and create appropriate instances for them.
1195            let mut model = resource.state();
1196            let model_kind = model.kind();
1197            if let Some(data) = model.data() {
1198                let resource_graph = data.graph();
1199
1200                let resource_instance_root = self.node(instance_root).original_handle_in_resource();
1201
1202                if resource_instance_root.is_none() {
1203                    let instance = self.node(instance_root);
1204                    Log::writeln(
1205                        MessageKind::Warning,
1206                        format!(
1207                            "There is an instance of resource {} \
1208                    but original node {} cannot be found!",
1209                            model_kind,
1210                            instance.name()
1211                        ),
1212                    );
1213
1214                    continue;
1215                }
1216
1217                let mut traverse_stack = vec![resource_instance_root];
1218                while let Some(resource_node_handle) = traverse_stack.pop() {
1219                    let resource_node = resource_graph.node(resource_node_handle);
1220
1221                    // Root of the resource is not belongs to resource, it is just a convenient way of
1222                    // consolidation all descendants under a single node.
1223                    let mut compare =
1224                        |n: &Self::Node| n.original_handle_in_resource() == resource_node_handle;
1225
1226                    if resource_node_handle != resource_graph.root()
1227                        && self.find(instance_root, &mut compare).is_none()
1228                    {
1229                        Log::writeln(
1230                            MessageKind::Warning,
1231                            format!(
1232                                "Instance of node {} is missing. Restoring integrity...",
1233                                resource_node.name()
1234                            ),
1235                        );
1236
1237                        // Instantiate missing node.
1238                        let (copy, old_to_new_mapping) =
1239                            instantiate(resource.clone(), data, resource_node_handle, self);
1240
1241                        restored_count += old_to_new_mapping.inner().len();
1242
1243                        // Link it with existing node.
1244                        if resource_node.parent().is_some() {
1245                            let parent = self.find(instance_root, &mut |n| {
1246                                n.original_handle_in_resource() == resource_node.parent()
1247                            });
1248
1249                            if let Some((parent_handle, _)) = parent {
1250                                self.link_nodes(copy, parent_handle);
1251                            } else {
1252                                // Fail-safe route - link with root of instance.
1253                                self.link_nodes(copy, instance_root);
1254                            }
1255                        } else {
1256                            // Fail-safe route - link with root of instance.
1257                            self.link_nodes(copy, instance_root);
1258                        }
1259                    }
1260
1261                    traverse_stack.extend_from_slice(resource_node.children());
1262                }
1263            }
1264        }
1265
1266        Log::writeln(
1267            MessageKind::Information,
1268            format!(
1269                "Integrity restored for {instance_count} instances! {restored_count} new nodes were added!"
1270            ),
1271        );
1272
1273        instances
1274    }
1275
1276    // Iterate through every node and try to find a corresponding node in the parent resource for that node.
1277    // If a node has a parent resource but no correspoding node in the parent resource, then delete the node.
1278    // Otherwise, use reflection to make the unmodified variables of the node match the values in the corresponding node.
1279    fn restore_original_handles_and_inherit_properties<F>(
1280        &mut self,
1281        ignored_types: &[TypeId],
1282        mut before_inherit: F,
1283    ) where
1284        F: FnMut(&Self::Node, &mut Self::Node),
1285    {
1286        let mut ignored_types = ignored_types.to_vec();
1287        // Do not try to inspect resources, because it most likely cause a deadlock.
1288        ignored_types.push(TypeId::of::<UntypedResource>());
1289
1290        // Iterate over each node in the graph and resolve original handles. Original handle is a handle
1291        // to a node in resource from which a node was instantiated from. Also sync inheritable properties
1292        // if needed.
1293        for node in self.linear_iter_mut() {
1294            if let Some(model) = node.resource() {
1295                let mut header = model.state();
1296                let model_kind = header.kind();
1297                if let Some(data) = header.data() {
1298                    let resource_graph = data.graph();
1299
1300                    let resource_node = match data.mapping() {
1301                        NodeMapping::UseNames => {
1302                            // For some models we can resolve it only by names of nodes, but this is not
1303                            // reliable way of doing this, because some editors allow nodes to have same
1304                            // names for objects, but here we'll assume that modellers will not create
1305                            // models with duplicated names and user of the engine reads log messages.
1306                            resource_graph
1307                                .pair_iter()
1308                                .find_map(|(handle, resource_node)| {
1309                                    if resource_node.name() == node.name() {
1310                                        Some((resource_node, handle))
1311                                    } else {
1312                                        None
1313                                    }
1314                                })
1315                        }
1316                        NodeMapping::UseHandles => {
1317                            // Use original handle directly.
1318                            resource_graph
1319                                .try_get_node(node.original_handle_in_resource())
1320                                .map(|resource_node| {
1321                                    (resource_node, node.original_handle_in_resource())
1322                                })
1323                        }
1324                    };
1325
1326                    if let Some((resource_node, original)) = resource_node {
1327                        node.set_original_handle_in_resource(original);
1328
1329                        before_inherit(resource_node, node);
1330
1331                        // Check if the actual node types (this and parent's) are equal, and if not - copy the
1332                        // node and replace its base.
1333                        let mut types_match = true;
1334                        node.as_reflect(&mut |node_reflect| {
1335                            resource_node.as_reflect(&mut |resource_node_reflect| {
1336                                types_match =
1337                                    node_reflect.type_id() == resource_node_reflect.type_id();
1338
1339                                if !types_match {
1340                                    Log::warn(format!(
1341                                        "Node {}({}:{}) instance \
1342                                        have different type than in the respective parent \
1343                                        asset {}. The type will be fixed.",
1344                                        node.name(),
1345                                        node.self_handle().index(),
1346                                        node.self_handle().generation(),
1347                                        model_kind
1348                                    ));
1349                                }
1350                            })
1351                        });
1352                        if !types_match {
1353                            let base = node.base().clone();
1354                            let mut resource_node_clone = resource_node.clone();
1355                            variable::mark_inheritable_properties_non_modified(
1356                                &mut resource_node_clone as &mut dyn Reflect,
1357                                &ignored_types,
1358                            );
1359                            resource_node_clone.set_base(base);
1360                            *node = resource_node_clone;
1361                        }
1362
1363                        // Then try to inherit properties.
1364                        node.as_reflect_mut(&mut |node_reflect| {
1365                            resource_node.as_reflect(&mut |resource_node_reflect| {
1366                                Log::verify(variable::try_inherit_properties(
1367                                    node_reflect,
1368                                    resource_node_reflect,
1369                                    &ignored_types,
1370                                ));
1371                            })
1372                        })
1373                    } else {
1374                        Log::warn(format!(
1375                            "Unable to find original handle for node {}. The node will be removed!",
1376                            node.name(),
1377                        ))
1378                    }
1379                }
1380            }
1381        }
1382
1383        Log::writeln(MessageKind::Information, "Original handles resolved!");
1384    }
1385
1386    /// Maps handles in properties of instances after property inheritance. It is needed, because when a
1387    /// property contains node handle, the handle cannot be used directly after inheritance. Instead, it
1388    /// must be mapped to respective instance first.
1389    ///
1390    /// To do so, we at first, build node handle mapping (original handle -> instance handle) starting from
1391    /// instance root. Then we must find all inheritable properties and try to remap them to instance handles.
1392    fn remap_handles(&mut self, instances: &[(Handle<Self::Node>, Resource<Self::Prefab>)]) {
1393        for (instance_root, resource) in instances {
1394            // Prepare old -> new handle mapping first by walking over the graph
1395            // starting from instance root.
1396            let mut old_new_mapping = NodeHandleMap::default();
1397            let mut traverse_stack = vec![*instance_root];
1398            while let Some(node_handle) = traverse_stack.pop() {
1399                let node = self.node(node_handle);
1400                if let Some(node_resource) = node.resource().as_ref() {
1401                    // We're interested only in instance nodes.
1402                    if node_resource == resource {
1403                        let previous_mapping =
1404                            old_new_mapping.insert(node.original_handle_in_resource(), node_handle);
1405                        // There should be no such node.
1406                        if previous_mapping.is_some() {
1407                            Log::warn(format!(
1408                                "There are multiple original nodes for {:?}! Previous was {:?}. \
1409                                This can happen if a respective node was deleted.",
1410                                node_handle,
1411                                node.original_handle_in_resource()
1412                            ))
1413                        }
1414                    }
1415                }
1416
1417                traverse_stack.extend_from_slice(node.children());
1418            }
1419
1420            // Lastly, remap handles. We can't do this in single pass because there could
1421            // be cross references.
1422            for (_, handle) in old_new_mapping.inner().iter() {
1423                old_new_mapping.remap_inheritable_handles(
1424                    self.node_mut(*handle),
1425                    &[TypeId::of::<UntypedResource>()],
1426                );
1427            }
1428        }
1429    }
1430}
1431
1432/// Iterator that traverses tree in depth and returns shared references to nodes.
1433pub struct GraphTraverseIterator<'a, G: ?Sized, N> {
1434    graph: &'a G,
1435    stack: Vec<Handle<N>>,
1436}
1437
1438impl<'a, G: ?Sized, N> Iterator for GraphTraverseIterator<'a, G, N>
1439where
1440    G: SceneGraph<Node = N>,
1441    N: SceneGraphNode,
1442{
1443    type Item = (Handle<N>, &'a N);
1444
1445    #[inline]
1446    fn next(&mut self) -> Option<Self::Item> {
1447        if let Some(handle) = self.stack.pop() {
1448            let node = self.graph.node(handle);
1449
1450            for child_handle in node.children() {
1451                self.stack.push(*child_handle);
1452            }
1453
1454            return Some((handle, node));
1455        }
1456
1457        None
1458    }
1459}
1460
1461#[cfg(test)]
1462mod test {
1463    use crate::{
1464        AbstractSceneGraph, AbstractSceneNode, BaseSceneGraph, NodeHandleMap, NodeMapping,
1465        PrefabData, SceneGraph, SceneGraphNode,
1466    };
1467    use fyrox_core::pool::{ObjectOrVariant, ObjectOrVariantHelper};
1468    use fyrox_core::{
1469        define_as_any_trait,
1470        pool::{ErasedHandle, Handle, PayloadContainer, Pool},
1471        reflect::prelude::*,
1472        type_traits::prelude::*,
1473        visitor::prelude::*,
1474        NameProvider,
1475    };
1476    use fyrox_resource::{untyped::UntypedResource, Resource, ResourceData};
1477    use std::marker::PhantomData;
1478    use std::{
1479        any::{Any, TypeId},
1480        error::Error,
1481        fmt::Debug,
1482        ops::{Deref, DerefMut, Index, IndexMut},
1483        path::Path,
1484    };
1485
1486    #[derive(Default, Visit, Reflect, Debug, Clone)]
1487    pub struct Base {
1488        name: String,
1489        self_handle: Handle<Node>,
1490        is_resource_instance_root: bool,
1491        original_handle_in_resource: Handle<Node>,
1492        resource: Option<Resource<Graph>>,
1493        parent: Handle<Node>,
1494        children: Vec<Handle<Node>>,
1495    }
1496
1497    /// A set of useful methods that is possible to auto-implement.
1498    pub trait BaseNodeTrait: Any + Debug + Deref<Target = Base> + DerefMut + Send {
1499        /// This method creates raw copy of a node, it should never be called in normal circumstances
1500        /// because internally nodes may (and most likely will) contain handles to other nodes. To
1501        /// correctly clone a node you have to use [copy_node](struct.Graph.html#method.copy_node).
1502        fn clone_box(&self) -> Node;
1503    }
1504
1505    impl<T> BaseNodeTrait for T
1506    where
1507        T: Clone + NodeTrait + 'static,
1508    {
1509        fn clone_box(&self) -> Node {
1510            Node(Box::new(self.clone()))
1511        }
1512    }
1513
1514    define_as_any_trait!(NodeAsAny => NodeTrait);
1515
1516    pub trait NodeTrait: BaseNodeTrait + Reflect + Visit + ComponentProvider + NodeAsAny {}
1517
1518    // Essentially implements ObjectOrVariant for NodeTrait types.
1519    // See ObjectOrVariantHelper for the cause of the indirection.
1520    impl<T: NodeTrait> ObjectOrVariantHelper<Node, T> for PhantomData<T> {
1521        fn convert_to_dest_type_helper(node: &Node) -> Option<&T> {
1522            NodeAsAny::as_any(node.0.deref()).downcast_ref()
1523        }
1524        fn convert_to_dest_type_helper_mut(node: &mut Node) -> Option<&mut T> {
1525            NodeAsAny::as_any_mut(node.0.deref_mut()).downcast_mut()
1526        }
1527    }
1528
1529    #[derive(ComponentProvider, Debug)]
1530    pub struct Node(Box<dyn NodeTrait>);
1531
1532    impl Clone for Node {
1533        fn clone(&self) -> Self {
1534            self.0.clone_box()
1535        }
1536    }
1537
1538    impl Node {
1539        fn new(node: impl NodeTrait) -> Self {
1540            Self(Box::new(node))
1541        }
1542    }
1543
1544    impl Visit for Node {
1545        fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult {
1546            self.0.visit(name, visitor)
1547        }
1548    }
1549
1550    impl Reflect for Node {
1551        fn source_path() -> &'static str {
1552            file!()
1553        }
1554
1555        fn type_name(&self) -> &'static str {
1556            self.0.deref().type_name()
1557        }
1558
1559        fn doc(&self) -> &'static str {
1560            self.0.deref().doc()
1561        }
1562
1563        fn assembly_name(&self) -> &'static str {
1564            self.0.deref().assembly_name()
1565        }
1566
1567        fn type_assembly_name() -> &'static str {
1568            env!("CARGO_PKG_NAME")
1569        }
1570
1571        fn fields_ref(&self, func: &mut dyn FnMut(&[FieldRef])) {
1572            self.0.deref().fields_ref(func)
1573        }
1574
1575        fn fields_mut(&mut self, func: &mut dyn FnMut(&mut [FieldMut])) {
1576            self.0.deref_mut().fields_mut(func)
1577        }
1578
1579        fn into_any(self: Box<Self>) -> Box<dyn Any> {
1580            Reflect::into_any(self.0)
1581        }
1582
1583        fn as_any(&self, func: &mut dyn FnMut(&dyn Any)) {
1584            Reflect::as_any(self.0.deref(), func)
1585        }
1586
1587        fn as_any_mut(&mut self, func: &mut dyn FnMut(&mut dyn Any)) {
1588            Reflect::as_any_mut(self.0.deref_mut(), func)
1589        }
1590
1591        fn as_reflect(&self, func: &mut dyn FnMut(&dyn Reflect)) {
1592            self.0.deref().as_reflect(func)
1593        }
1594
1595        fn as_reflect_mut(&mut self, func: &mut dyn FnMut(&mut dyn Reflect)) {
1596            self.0.deref_mut().as_reflect_mut(func)
1597        }
1598
1599        fn set(&mut self, value: Box<dyn Reflect>) -> Result<Box<dyn Reflect>, Box<dyn Reflect>> {
1600            self.0.deref_mut().set(value)
1601        }
1602
1603        fn set_field(
1604            &mut self,
1605            field: &str,
1606            value: Box<dyn Reflect>,
1607            func: &mut dyn FnMut(Result<Box<dyn Reflect>, SetFieldError>),
1608        ) {
1609            self.0.deref_mut().set_field(field, value, func)
1610        }
1611
1612        fn field(&self, name: &str, func: &mut dyn FnMut(Option<&dyn Reflect>)) {
1613            self.0.deref().field(name, func)
1614        }
1615
1616        fn field_mut(&mut self, name: &str, func: &mut dyn FnMut(Option<&mut dyn Reflect>)) {
1617            self.0.deref_mut().field_mut(name, func)
1618        }
1619
1620        fn derived_types() -> &'static [TypeId] {
1621            &[]
1622        }
1623
1624        fn query_derived_types(&self) -> &'static [TypeId] {
1625            Self::derived_types()
1626        }
1627
1628        fn try_clone_box(&self) -> Option<Box<dyn Reflect>> {
1629            Some(Box::new(self.clone()))
1630        }
1631    }
1632
1633    impl NameProvider for Node {
1634        fn name(&self) -> &str {
1635            &self.name
1636        }
1637    }
1638
1639    impl Deref for Node {
1640        type Target = Base;
1641
1642        fn deref(&self) -> &Self::Target {
1643            self.0.deref()
1644        }
1645    }
1646
1647    impl DerefMut for Node {
1648        fn deref_mut(&mut self) -> &mut Self::Target {
1649            self.0.deref_mut()
1650        }
1651    }
1652
1653    /// A wrapper for node pool record that allows to define custom visit method to have full
1654    /// control over instantiation process at deserialization.
1655    #[derive(Debug, Default, Clone, Reflect)]
1656    pub struct NodeContainer(Option<Node>);
1657
1658    impl Visit for NodeContainer {
1659        fn visit(&mut self, _name: &str, _visitor: &mut Visitor) -> VisitResult {
1660            // Dummy impl.
1661            Ok(())
1662        }
1663    }
1664
1665    impl PayloadContainer for NodeContainer {
1666        type Element = Node;
1667
1668        fn new_empty() -> Self {
1669            Self(None)
1670        }
1671
1672        fn new(element: Self::Element) -> Self {
1673            Self(Some(element))
1674        }
1675
1676        fn is_some(&self) -> bool {
1677            self.0.is_some()
1678        }
1679
1680        fn as_ref(&self) -> Option<&Self::Element> {
1681            self.0.as_ref()
1682        }
1683
1684        fn as_mut(&mut self) -> Option<&mut Self::Element> {
1685            self.0.as_mut()
1686        }
1687
1688        fn replace(&mut self, element: Self::Element) -> Option<Self::Element> {
1689            self.0.replace(element)
1690        }
1691
1692        fn take(&mut self) -> Option<Self::Element> {
1693            self.0.take()
1694        }
1695    }
1696
1697    impl SceneGraphNode for Node {
1698        type Base = Base;
1699        type SceneGraph = Graph;
1700        type ResourceData = Graph;
1701
1702        #[allow(clippy::explicit_auto_deref)] // False-positive
1703        fn base(&self) -> &Self::Base {
1704            &**self
1705        }
1706
1707        fn set_base(&mut self, base: Self::Base) {
1708            **self = base;
1709        }
1710
1711        fn is_resource_instance_root(&self) -> bool {
1712            self.is_resource_instance_root
1713        }
1714
1715        fn original_handle_in_resource(&self) -> Handle<Self> {
1716            self.original_handle_in_resource
1717        }
1718
1719        fn set_original_handle_in_resource(&mut self, handle: Handle<Self>) {
1720            self.original_handle_in_resource = handle;
1721        }
1722
1723        fn resource(&self) -> Option<Resource<Self::ResourceData>> {
1724            self.resource.clone()
1725        }
1726
1727        fn self_handle(&self) -> Handle<Self> {
1728            self.self_handle
1729        }
1730
1731        fn parent(&self) -> Handle<Self> {
1732            self.parent
1733        }
1734
1735        fn children(&self) -> &[Handle<Self>] {
1736            &self.children
1737        }
1738
1739        fn children_mut(&mut self) -> &mut [Handle<Self>] {
1740            &mut self.children
1741        }
1742    }
1743
1744    #[derive(Default, Clone, TypeUuidProvider, Visit, Reflect, Debug)]
1745    #[type_uuid(id = "fc887063-7780-44af-8710-5e0bcf9a83fd")]
1746    pub struct Graph {
1747        root: Handle<Node>,
1748        nodes: Pool<Node, NodeContainer>,
1749    }
1750
1751    impl ResourceData for Graph {
1752        fn type_uuid(&self) -> Uuid {
1753            <Graph as TypeUuidProvider>::type_uuid()
1754        }
1755
1756        fn save(&mut self, _path: &Path) -> Result<(), Box<dyn Error>> {
1757            Ok(())
1758        }
1759
1760        fn can_be_saved(&self) -> bool {
1761            false
1762        }
1763
1764        fn try_clone_box(&self) -> Option<Box<dyn ResourceData>> {
1765            Some(Box::new(self.clone()))
1766        }
1767    }
1768
1769    impl PrefabData for Graph {
1770        type Graph = Graph;
1771
1772        fn graph(&self) -> &Self::Graph {
1773            self
1774        }
1775
1776        fn mapping(&self) -> NodeMapping {
1777            NodeMapping::UseHandles
1778        }
1779    }
1780
1781    impl Index<Handle<Node>> for Graph {
1782        type Output = Node;
1783
1784        #[inline]
1785        fn index(&self, index: Handle<Node>) -> &Self::Output {
1786            &self.nodes[index]
1787        }
1788    }
1789
1790    impl IndexMut<Handle<Node>> for Graph {
1791        #[inline]
1792        fn index_mut(&mut self, index: Handle<Node>) -> &mut Self::Output {
1793            &mut self.nodes[index]
1794        }
1795    }
1796
1797    impl AbstractSceneGraph for Graph {
1798        fn try_get_node_untyped(&self, handle: ErasedHandle) -> Option<&dyn AbstractSceneNode> {
1799            self.nodes
1800                .try_borrow(handle.into())
1801                .map(|n| n as &dyn AbstractSceneNode)
1802        }
1803
1804        fn try_get_node_untyped_mut(
1805            &mut self,
1806            handle: ErasedHandle,
1807        ) -> Option<&mut dyn AbstractSceneNode> {
1808            self.nodes
1809                .try_borrow_mut(handle.into())
1810                .map(|n| n as &mut dyn AbstractSceneNode)
1811        }
1812    }
1813
1814    impl BaseSceneGraph for Graph {
1815        type Prefab = Graph;
1816        type NodeContainer = NodeContainer;
1817        type Node = Node;
1818
1819        fn summary(&self) -> String {
1820            "Summary".to_string()
1821        }
1822
1823        fn root(&self) -> Handle<Self::Node> {
1824            self.root
1825        }
1826
1827        fn set_root(&mut self, root: Handle<Self::Node>) {
1828            self.root = root;
1829        }
1830
1831        fn is_valid_handle(&self, handle: Handle<Self::Node>) -> bool {
1832            self.nodes.is_valid_handle(handle)
1833        }
1834
1835        fn add_node(&mut self, mut node: Self::Node) -> Handle<Self::Node> {
1836            let children = node.children.clone();
1837            node.children.clear();
1838            let handle = self.nodes.spawn(node);
1839
1840            if self.root.is_none() {
1841                self.root = handle;
1842            } else {
1843                self.link_nodes(handle, self.root);
1844            }
1845
1846            for child in children {
1847                self.link_nodes(child, handle);
1848            }
1849
1850            let node = &mut self.nodes[handle];
1851            node.self_handle = handle;
1852            handle
1853        }
1854
1855        fn remove_node(&mut self, node_handle: Handle<Self::Node>) {
1856            self.isolate_node(node_handle);
1857            let mut stack = vec![node_handle];
1858            while let Some(handle) = stack.pop() {
1859                stack.extend_from_slice(self.nodes[handle].children());
1860                self.nodes.free(handle);
1861            }
1862        }
1863
1864        fn link_nodes(&mut self, child: Handle<Self::Node>, parent: Handle<Self::Node>) {
1865            self.isolate_node(child);
1866            self.nodes[child].parent = parent;
1867            self.nodes[parent].children.push(child);
1868        }
1869
1870        fn unlink_node(&mut self, node_handle: Handle<Self::Node>) {
1871            self.isolate_node(node_handle);
1872            self.link_nodes(node_handle, self.root);
1873        }
1874
1875        fn isolate_node(&mut self, node_handle: Handle<Self::Node>) {
1876            let parent_handle =
1877                std::mem::replace(&mut self.nodes[node_handle].parent, Handle::NONE);
1878
1879            if let Some(parent) = self.nodes.try_borrow_mut(parent_handle) {
1880                if let Some(i) = parent.children().iter().position(|h| *h == node_handle) {
1881                    parent.children.remove(i);
1882                }
1883            }
1884        }
1885
1886        fn try_get_node(&self, handle: Handle<Self::Node>) -> Option<&Self::Node> {
1887            self.nodes.try_borrow(handle)
1888        }
1889
1890        fn try_get_node_mut(&mut self, handle: Handle<Self::Node>) -> Option<&mut Self::Node> {
1891            self.nodes.try_borrow_mut(handle)
1892        }
1893
1894        fn actual_type_id(&self, handle: Handle<Self::Node>) -> Option<TypeId> {
1895            self.nodes
1896                .try_borrow(handle)
1897                .map(|n| NodeAsAny::as_any(n.0.deref()).type_id())
1898        }
1899
1900        fn derived_type_ids(&self, handle: Handle<Self::Node>) -> Option<Vec<TypeId>> {
1901            self.nodes
1902                .try_borrow(handle)
1903                .map(|n| n.0.deref().query_derived_types().to_vec())
1904        }
1905
1906        fn actual_type_name(&self, handle: Handle<Self::Node>) -> Option<&'static str> {
1907            self.nodes
1908                .try_borrow(handle)
1909                .map(|n| n.0.deref().type_name())
1910        }
1911    }
1912
1913    impl SceneGraph for Graph {
1914        type ObjectType = Node;
1915        fn pair_iter(&self) -> impl Iterator<Item = (Handle<Self::Node>, &Self::Node)> {
1916            self.nodes.pair_iter()
1917        }
1918
1919        fn linear_iter(&self) -> impl Iterator<Item = &Self::Node> {
1920            self.nodes.iter()
1921        }
1922
1923        fn linear_iter_mut(&mut self) -> impl Iterator<Item = &mut Self::Node> {
1924            self.nodes.iter_mut()
1925        }
1926
1927        fn try_get<U: ObjectOrVariant<Node>>(&self, handle: Handle<U>) -> Option<&U> {
1928            self.nodes.try_get(handle)
1929        }
1930
1931        fn try_get_mut<U: ObjectOrVariant<Node>>(&mut self, handle: Handle<U>) -> Option<&mut U> {
1932            self.nodes.try_get_mut(handle)
1933        }
1934    }
1935
1936    fn remap_handles(old_new_mapping: &NodeHandleMap<Node>, dest_graph: &mut Graph) {
1937        // Iterate over instantiated nodes and remap handles.
1938        for (_, &new_node_handle) in old_new_mapping.inner().iter() {
1939            old_new_mapping.remap_handles(
1940                &mut dest_graph.nodes[new_node_handle],
1941                &[TypeId::of::<UntypedResource>()],
1942            );
1943        }
1944    }
1945
1946    fn clear_links(mut node: Node) -> Node {
1947        node.children.clear();
1948        node.parent = Handle::NONE;
1949        node
1950    }
1951
1952    impl Graph {
1953        #[inline]
1954        pub fn copy_node(
1955            &self,
1956            node_handle: Handle<Node>,
1957            dest_graph: &mut Graph,
1958        ) -> (Handle<Node>, NodeHandleMap<Node>) {
1959            let mut old_new_mapping = NodeHandleMap::default();
1960            let root_handle = self.copy_node_raw(node_handle, dest_graph, &mut old_new_mapping);
1961
1962            remap_handles(&old_new_mapping, dest_graph);
1963
1964            (root_handle, old_new_mapping)
1965        }
1966        fn copy_node_raw(
1967            &self,
1968            root_handle: Handle<Node>,
1969            dest_graph: &mut Graph,
1970            old_new_mapping: &mut NodeHandleMap<Node>,
1971        ) -> Handle<Node> {
1972            let src_node = &self.nodes[root_handle];
1973            let dest_node = clear_links(src_node.clone());
1974            let dest_copy_handle = dest_graph.add_node(dest_node);
1975            old_new_mapping.insert(root_handle, dest_copy_handle);
1976            for &src_child_handle in src_node.children() {
1977                let dest_child_handle =
1978                    self.copy_node_raw(src_child_handle, dest_graph, old_new_mapping);
1979                if !dest_child_handle.is_none() {
1980                    dest_graph.link_nodes(dest_child_handle, dest_copy_handle);
1981                }
1982            }
1983            dest_copy_handle
1984        }
1985    }
1986
1987    #[derive(Clone, Reflect, Visit, Default, Debug, ComponentProvider)]
1988    #[reflect(derived_type = "Node")]
1989    pub struct Pivot {
1990        base: Base,
1991    }
1992
1993    impl NodeTrait for Pivot {}
1994
1995    impl Deref for Pivot {
1996        type Target = Base;
1997
1998        fn deref(&self) -> &Self::Target {
1999            &self.base
2000        }
2001    }
2002
2003    impl DerefMut for Pivot {
2004        fn deref_mut(&mut self) -> &mut Self::Target {
2005            &mut self.base
2006        }
2007    }
2008
2009    #[derive(Clone, Reflect, Visit, Default, Debug, ComponentProvider)]
2010    #[reflect(derived_type = "Node")]
2011    pub struct RigidBody {
2012        base: Base,
2013    }
2014
2015    impl NodeTrait for RigidBody {}
2016
2017    impl Deref for RigidBody {
2018        type Target = Base;
2019
2020        fn deref(&self) -> &Self::Target {
2021            &self.base
2022        }
2023    }
2024
2025    impl DerefMut for RigidBody {
2026        fn deref_mut(&mut self) -> &mut Self::Target {
2027            &mut self.base
2028        }
2029    }
2030
2031    #[derive(Clone, Reflect, Visit, Default, Debug, ComponentProvider)]
2032    #[reflect(derived_type = "Node")]
2033    pub struct Joint {
2034        base: Base,
2035        connected_body1: Handle<RigidBody>,
2036        connected_body2: Handle<RigidBody>,
2037    }
2038
2039    impl NodeTrait for Joint {}
2040
2041    impl Deref for Joint {
2042        type Target = Base;
2043
2044        fn deref(&self) -> &Self::Target {
2045            &self.base
2046        }
2047    }
2048
2049    impl DerefMut for Joint {
2050        fn deref_mut(&mut self) -> &mut Self::Target {
2051            &mut self.base
2052        }
2053    }
2054
2055    #[test]
2056    fn test_set_child_position() {
2057        let mut graph = Graph::default();
2058
2059        let root = graph.add_node(Node::new(Pivot::default()));
2060        let a = graph.add_node(Node::new(Pivot::default()));
2061        let b = graph.add_node(Node::new(Pivot::default()));
2062        let c = graph.add_node(Node::new(Pivot::default()));
2063        let d = graph.add_node(Node::new(Pivot::default()));
2064        graph.link_nodes(a, root);
2065        graph.link_nodes(b, root);
2066        graph.link_nodes(c, root);
2067        graph.link_nodes(d, root);
2068
2069        let root_ref = &mut graph[root];
2070        assert_eq!(root_ref.set_child_position(a, 0), Some(0));
2071        assert_eq!(root_ref.set_child_position(b, 1), Some(1));
2072        assert_eq!(root_ref.set_child_position(c, 2), Some(2));
2073        assert_eq!(root_ref.set_child_position(d, 3), Some(3));
2074        assert_eq!(root_ref.children[0], a);
2075        assert_eq!(root_ref.children[1], b);
2076        assert_eq!(root_ref.children[2], c);
2077        assert_eq!(root_ref.children[3], d);
2078
2079        let initial_pos = root_ref.set_child_position(a, 3);
2080        assert_eq!(initial_pos, Some(0));
2081        assert_eq!(root_ref.children[0], b);
2082        assert_eq!(root_ref.children[1], c);
2083        assert_eq!(root_ref.children[2], d);
2084        assert_eq!(root_ref.children[3], a);
2085
2086        let prev_pos = root_ref.set_child_position(a, initial_pos.unwrap());
2087        assert_eq!(prev_pos, Some(3));
2088        assert_eq!(root_ref.children[0], a);
2089        assert_eq!(root_ref.children[1], b);
2090        assert_eq!(root_ref.children[2], c);
2091        assert_eq!(root_ref.children[3], d);
2092
2093        assert_eq!(root_ref.set_child_position(d, 1), Some(3));
2094        assert_eq!(root_ref.children[0], a);
2095        assert_eq!(root_ref.children[1], d);
2096        assert_eq!(root_ref.children[2], b);
2097        assert_eq!(root_ref.children[3], c);
2098
2099        assert_eq!(root_ref.set_child_position(d, 0), Some(1));
2100        assert_eq!(root_ref.children[0], d);
2101        assert_eq!(root_ref.children[1], a);
2102        assert_eq!(root_ref.children[2], b);
2103        assert_eq!(root_ref.children[3], c);
2104    }
2105
2106    #[test]
2107    fn test_derived_handles_mapping() {
2108        let mut prefab_graph = Graph::default();
2109
2110        prefab_graph.add_node(Node::new(Pivot::default()));
2111        let rigid_body = prefab_graph.add_node(Node::new(RigidBody::default()));
2112        let rigid_body2 = prefab_graph.add_node(Node::new(RigidBody::default()));
2113        let joint = prefab_graph.add_node(Node::new(Joint {
2114            base: Base::default(),
2115            connected_body1: rigid_body.transmute(),
2116            connected_body2: rigid_body2.transmute(),
2117        }));
2118
2119        let mut scene_graph = Graph::default();
2120        let root = scene_graph.add_node(Node::new(Pivot::default()));
2121
2122        let (_, mapping) = prefab_graph.copy_node(root, &mut scene_graph);
2123        let rigid_body_copy = mapping
2124            .inner()
2125            .get(&rigid_body)
2126            .cloned()
2127            .unwrap()
2128            .transmute::<RigidBody>();
2129        let rigid_body2_copy = mapping
2130            .inner()
2131            .get(&rigid_body2)
2132            .cloned()
2133            .unwrap()
2134            .transmute::<RigidBody>();
2135        let joint_copy = mapping.inner().get(&joint).cloned().unwrap();
2136        Reflect::as_any(&scene_graph.nodes[joint_copy], &mut |any| {
2137            let joint_copy_ref = any.downcast_ref::<Joint>().unwrap();
2138            assert_eq!(joint_copy_ref.connected_body1, rigid_body_copy);
2139            assert_eq!(joint_copy_ref.connected_body2, rigid_body2_copy);
2140        });
2141    }
2142
2143    #[test]
2144    fn test_change_root() {
2145        let mut graph = Graph::default();
2146
2147        // Root_
2148        //      |_A_
2149        //          |_B
2150        //          |_C_
2151        //             |_D
2152        let root = graph.add_node(Node::new(Pivot::default()));
2153        let d = graph.add_node(Node::new(Pivot::default()));
2154        let c = graph.add_node(Node::new(Pivot {
2155            base: Base {
2156                children: vec![d],
2157                ..Default::default()
2158            },
2159        }));
2160        let b = graph.add_node(Node::new(Pivot::default()));
2161        let a = graph.add_node(Node::new(Pivot {
2162            base: Base {
2163                children: vec![b, c],
2164                ..Default::default()
2165            },
2166        }));
2167        graph.link_nodes(a, root);
2168
2169        dbg!(root, a, b, c, d);
2170
2171        let link_scheme = graph.change_hierarchy_root(root, c);
2172
2173        // C_
2174        //   |_D
2175        //   |_A_
2176        //       |_B
2177        //   |_Root
2178        assert_eq!(graph.root, c);
2179
2180        assert_eq!(graph[graph.root].parent, Handle::NONE);
2181        assert_eq!(graph[graph.root].children.len(), 3);
2182
2183        assert_eq!(graph[graph.root].children[0], d);
2184        assert_eq!(graph[d].parent, graph.root);
2185        assert!(graph[d].children.is_empty());
2186
2187        assert_eq!(graph[graph.root].children[1], a);
2188        assert_eq!(graph[a].parent, graph.root);
2189
2190        assert_eq!(graph[graph.root].children[2], root);
2191        assert_eq!(graph[root].parent, graph.root);
2192
2193        assert_eq!(graph[a].children.len(), 1);
2194        assert_eq!(graph[a].children[0], b);
2195        assert_eq!(graph[b].parent, a);
2196
2197        assert!(graph[b].children.is_empty());
2198
2199        // Revert
2200        graph.apply_link_scheme(link_scheme);
2201
2202        assert_eq!(graph.root, root);
2203        assert_eq!(graph[graph.root].parent, Handle::NONE);
2204        assert_eq!(graph[graph.root].children, vec![a]);
2205
2206        assert_eq!(graph[a].parent, root);
2207        assert_eq!(graph[a].children, vec![b, c]);
2208
2209        assert_eq!(graph[b].parent, a);
2210        assert_eq!(graph[b].children, vec![]);
2211
2212        assert_eq!(graph[c].parent, a);
2213        assert_eq!(graph[c].children, vec![d]);
2214    }
2215}