Skip to main content

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