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 resource_instance_root = self.node(instance_root).original_handle_in_resource();
1248
1249                if resource_instance_root.is_none() {
1250                    let instance = self.node(instance_root);
1251                    Log::writeln(
1252                        MessageKind::Warning,
1253                        format!(
1254                            "There is an instance of resource {} \
1255                    but original node {} cannot be found!",
1256                            model_kind,
1257                            instance.name()
1258                        ),
1259                    );
1260
1261                    continue;
1262                }
1263
1264                let mut traverse_stack = vec![resource_instance_root];
1265                while let Some(resource_node_handle) = traverse_stack.pop() {
1266                    let resource_node = resource_graph.node(resource_node_handle);
1267
1268                    // Root of the resource is not belongs to resource, it is just a convenient way of
1269                    // consolidation all descendants under a single node.
1270                    let mut compare =
1271                        |n: &Self::Node| n.original_handle_in_resource() == resource_node_handle;
1272
1273                    if resource_node_handle != resource_graph.root()
1274                        && self.find(instance_root, &mut compare).is_none()
1275                    {
1276                        Log::writeln(
1277                            MessageKind::Warning,
1278                            format!(
1279                                "Instance of node {} is missing. Restoring integrity...",
1280                                resource_node.name()
1281                            ),
1282                        );
1283
1284                        // Instantiate missing node.
1285                        let (copy, old_to_new_mapping) =
1286                            instantiate(resource.clone(), data, resource_node_handle, self);
1287
1288                        restored_count += old_to_new_mapping.inner().len();
1289
1290                        // Link it with existing node.
1291                        if resource_node.parent().is_some() {
1292                            let parent = self.find(instance_root, &mut |n| {
1293                                n.original_handle_in_resource() == resource_node.parent()
1294                            });
1295
1296                            if let Some((parent_handle, _)) = parent {
1297                                self.link_nodes(copy, parent_handle);
1298                            } else {
1299                                // Fail-safe route - link with root of instance.
1300                                self.link_nodes(copy, instance_root);
1301                            }
1302                        } else {
1303                            // Fail-safe route - link with root of instance.
1304                            self.link_nodes(copy, instance_root);
1305                        }
1306                    }
1307
1308                    traverse_stack.extend_from_slice(resource_node.children());
1309                }
1310            }
1311        }
1312
1313        Log::writeln(
1314            MessageKind::Information,
1315            format!(
1316                "Integrity restored for {instance_count} instances! {restored_count} new nodes were added!"
1317            ),
1318        );
1319
1320        instances
1321    }
1322
1323    // Iterate through every node and try to find a corresponding node in the parent resource for that node.
1324    // If a node has a parent resource but no correspoding node in the parent resource, then delete the node.
1325    // Otherwise, use reflection to make the unmodified variables of the node match the values in the corresponding node.
1326    fn restore_original_handles_and_inherit_properties<F>(
1327        &mut self,
1328        ignored_types: &[TypeId],
1329        mut before_inherit: F,
1330    ) where
1331        F: FnMut(&Self::Node, &mut Self::Node),
1332    {
1333        let mut ignored_types = ignored_types.to_vec();
1334        // Do not try to inspect resources, because it most likely cause a deadlock.
1335        ignored_types.push(TypeId::of::<UntypedResource>());
1336
1337        // Iterate over each node in the graph and resolve original handles. Original handle is a handle
1338        // to a node in resource from which a node was instantiated from. Also sync inheritable properties
1339        // if needed.
1340        for node in self.linear_iter_mut() {
1341            if let Some(model) = node.resource() {
1342                let mut header = model.state();
1343                let model_kind = header.kind();
1344                if let Some(data) = header.data() {
1345                    let resource_graph = data.graph();
1346
1347                    let resource_node = match data.mapping() {
1348                        NodeMapping::UseNames => {
1349                            // For some models we can resolve it only by names of nodes, but this is not
1350                            // reliable way of doing this, because some editors allow nodes to have same
1351                            // names for objects, but here we'll assume that modellers will not create
1352                            // models with duplicated names and user of the engine reads log messages.
1353                            resource_graph
1354                                .pair_iter()
1355                                .find_map(|(handle, resource_node)| {
1356                                    if resource_node.name() == node.name() {
1357                                        Some((resource_node, handle))
1358                                    } else {
1359                                        None
1360                                    }
1361                                })
1362                        }
1363                        NodeMapping::UseHandles => {
1364                            // Use original handle directly.
1365                            resource_graph
1366                                .try_get_node(node.original_handle_in_resource())
1367                                .map(|resource_node| {
1368                                    (resource_node, node.original_handle_in_resource())
1369                                })
1370                                .ok()
1371                        }
1372                    };
1373
1374                    if let Some((resource_node, original)) = resource_node {
1375                        node.set_original_handle_in_resource(original);
1376
1377                        before_inherit(resource_node, node);
1378
1379                        // Check if the actual node types (this and parent's) are equal, and if not - copy the
1380                        // node and replace its base.
1381                        let mut types_match = true;
1382                        node.as_reflect(&mut |node_reflect| {
1383                            resource_node.as_reflect(&mut |resource_node_reflect| {
1384                                types_match =
1385                                    node_reflect.type_id() == resource_node_reflect.type_id();
1386
1387                                if !types_match {
1388                                    Log::warn(format!(
1389                                        "Node {}({}:{}) instance \
1390                                        have different type than in the respective parent \
1391                                        asset {}. The type will be fixed.",
1392                                        node.name(),
1393                                        node.self_handle().index(),
1394                                        node.self_handle().generation(),
1395                                        model_kind
1396                                    ));
1397                                }
1398                            })
1399                        });
1400                        if !types_match {
1401                            let base = node.base().clone();
1402                            let mut resource_node_clone = resource_node.clone();
1403                            variable::mark_inheritable_properties_non_modified(
1404                                &mut resource_node_clone as &mut dyn Reflect,
1405                                &ignored_types,
1406                            );
1407                            resource_node_clone.set_base(base);
1408                            *node = resource_node_clone;
1409                        }
1410
1411                        // Then try to inherit properties.
1412                        node.as_reflect_mut(&mut |node_reflect| {
1413                            resource_node.as_reflect(&mut |resource_node_reflect| {
1414                                Log::verify(variable::try_inherit_properties(
1415                                    node_reflect,
1416                                    resource_node_reflect,
1417                                    &ignored_types,
1418                                ));
1419                            })
1420                        })
1421                    } else {
1422                        Log::warn(format!(
1423                            "Unable to find original handle for node {}. The node will be removed!",
1424                            node.name(),
1425                        ))
1426                    }
1427                }
1428            }
1429        }
1430
1431        Log::writeln(MessageKind::Information, "Original handles resolved!");
1432    }
1433
1434    /// Maps handles in properties of instances after property inheritance. It is needed, because when a
1435    /// property contains node handle, the handle cannot be used directly after inheritance. Instead, it
1436    /// must be mapped to respective instance first.
1437    ///
1438    /// To do so, we at first, build node handle mapping (original handle -> instance handle) starting from
1439    /// instance root. Then we must find all inheritable properties and try to remap them to instance handles.
1440    fn remap_handles(&mut self, instances: &[(Handle<Self::Node>, Resource<Self::Prefab>)]) {
1441        for (instance_root, resource) in instances {
1442            // Prepare old -> new handle mapping first by walking over the graph
1443            // starting from instance root.
1444            let mut old_new_mapping = NodeHandleMap::default();
1445            let mut traverse_stack = vec![*instance_root];
1446            while let Some(node_handle) = traverse_stack.pop() {
1447                let node = self.node(node_handle);
1448                if let Some(node_resource) = node.resource().as_ref() {
1449                    // We're interested only in instance nodes.
1450                    if node_resource == resource {
1451                        let previous_mapping =
1452                            old_new_mapping.insert(node.original_handle_in_resource(), node_handle);
1453                        // There should be no such node.
1454                        if previous_mapping.is_some() {
1455                            Log::warn(format!(
1456                                "There are multiple original nodes for {:?}! Previous was {:?}. \
1457                                This can happen if a respective node was deleted.",
1458                                node_handle,
1459                                node.original_handle_in_resource()
1460                            ))
1461                        }
1462                    }
1463                }
1464
1465                traverse_stack.extend_from_slice(node.children());
1466            }
1467
1468            // Lastly, remap handles. We can't do this in single pass because there could
1469            // be cross references.
1470            for (_, handle) in old_new_mapping.inner().iter() {
1471                old_new_mapping.remap_inheritable_handles(
1472                    self.node_mut(*handle),
1473                    &[TypeId::of::<UntypedResource>()],
1474                );
1475            }
1476        }
1477    }
1478}
1479
1480/// Iterator that traverses tree in depth and returns shared references to nodes.
1481pub struct GraphTraverseIterator<'a, G: ?Sized, N> {
1482    graph: &'a G,
1483    stack: Vec<Handle<N>>,
1484}
1485
1486impl<'a, G: ?Sized, N> Iterator for GraphTraverseIterator<'a, G, N>
1487where
1488    G: SceneGraph<Node = N>,
1489    N: SceneGraphNode,
1490{
1491    type Item = (Handle<N>, &'a N);
1492
1493    #[inline]
1494    fn next(&mut self) -> Option<Self::Item> {
1495        if let Some(handle) = self.stack.pop() {
1496            let node = self.graph.node(handle);
1497
1498            for child_handle in node.children() {
1499                self.stack.push(*child_handle);
1500            }
1501
1502            return Some((handle, node));
1503        }
1504
1505        None
1506    }
1507}
1508
1509#[cfg(test)]
1510mod test {
1511    use crate::{NodeHandleMap, NodeMapping, PrefabData, SceneGraph, SceneGraphNode};
1512    use fyrox_core::pool::{ObjectOrVariant, ObjectOrVariantHelper, PoolError};
1513    use fyrox_core::{
1514        define_as_any_trait,
1515        pool::{Handle, PayloadContainer, Pool},
1516        reflect::prelude::*,
1517        type_traits::prelude::*,
1518        visitor::prelude::*,
1519        NameProvider,
1520    };
1521    use fyrox_resource::{untyped::UntypedResource, Resource, ResourceData};
1522    use std::marker::PhantomData;
1523    use std::{
1524        any::{Any, TypeId},
1525        error::Error,
1526        fmt::Debug,
1527        ops::{Deref, DerefMut, Index, IndexMut},
1528        path::Path,
1529    };
1530
1531    #[derive(Visit, Reflect, Debug, Clone)]
1532    pub struct Base {
1533        name: String,
1534        self_handle: Handle<Node>,
1535        is_resource_instance_root: bool,
1536        original_handle_in_resource: Handle<Node>,
1537        resource: Option<Resource<Graph>>,
1538        parent: Handle<Node>,
1539        children: Vec<Handle<Node>>,
1540        instance_id: Uuid,
1541    }
1542
1543    impl Default for Base {
1544        fn default() -> Self {
1545            Self {
1546                name: Default::default(),
1547                self_handle: Default::default(),
1548                is_resource_instance_root: Default::default(),
1549                original_handle_in_resource: Default::default(),
1550                resource: Default::default(),
1551                parent: Default::default(),
1552                children: Default::default(),
1553                instance_id: Uuid::new_v4(),
1554            }
1555        }
1556    }
1557
1558    /// A set of useful methods that is possible to auto-implement.
1559    pub trait BaseNodeTrait: Any + Debug + Deref<Target = Base> + DerefMut + Send {
1560        /// This method creates raw copy of a node, it should never be called in normal circumstances
1561        /// because internally nodes may (and most likely will) contain handles to other nodes. To
1562        /// correctly clone a node you have to use [copy_node](struct.Graph.html#method.copy_node).
1563        fn clone_box(&self) -> Node;
1564    }
1565
1566    impl<T> BaseNodeTrait for T
1567    where
1568        T: Clone + NodeTrait + 'static,
1569    {
1570        fn clone_box(&self) -> Node {
1571            Node(Box::new(self.clone()))
1572        }
1573    }
1574
1575    define_as_any_trait!(NodeAsAny => NodeTrait);
1576
1577    pub trait NodeTrait: BaseNodeTrait + Reflect + Visit + ComponentProvider + NodeAsAny {}
1578
1579    // Essentially implements ObjectOrVariant for NodeTrait types.
1580    // See ObjectOrVariantHelper for the cause of the indirection.
1581    impl<T: NodeTrait> ObjectOrVariantHelper<Node, T> for PhantomData<T> {
1582        fn convert_to_dest_type_helper(node: &Node) -> Option<&T> {
1583            NodeAsAny::as_any(node.0.deref()).downcast_ref()
1584        }
1585        fn convert_to_dest_type_helper_mut(node: &mut Node) -> Option<&mut T> {
1586            NodeAsAny::as_any_mut(node.0.deref_mut()).downcast_mut()
1587        }
1588    }
1589
1590    #[derive(ComponentProvider, Debug)]
1591    pub struct Node(Box<dyn NodeTrait>);
1592
1593    impl Clone for Node {
1594        fn clone(&self) -> Self {
1595            self.0.clone_box()
1596        }
1597    }
1598
1599    impl Node {
1600        fn new(node: impl NodeTrait) -> Self {
1601            Self(Box::new(node))
1602        }
1603    }
1604
1605    impl Visit for Node {
1606        fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult {
1607            self.0.visit(name, visitor)
1608        }
1609    }
1610
1611    impl Reflect for Node {
1612        fn source_path() -> &'static str {
1613            file!()
1614        }
1615
1616        fn type_name(&self) -> &'static str {
1617            self.0.deref().type_name()
1618        }
1619
1620        fn doc(&self) -> &'static str {
1621            self.0.deref().doc()
1622        }
1623
1624        fn assembly_name(&self) -> &'static str {
1625            self.0.deref().assembly_name()
1626        }
1627
1628        fn type_assembly_name() -> &'static str {
1629            env!("CARGO_PKG_NAME")
1630        }
1631
1632        fn fields_ref(&self, func: &mut dyn FnMut(&[FieldRef])) {
1633            self.0.deref().fields_ref(func)
1634        }
1635
1636        fn fields_mut(&mut self, func: &mut dyn FnMut(&mut [FieldMut])) {
1637            self.0.deref_mut().fields_mut(func)
1638        }
1639
1640        fn into_any(self: Box<Self>) -> Box<dyn Any> {
1641            Reflect::into_any(self.0)
1642        }
1643
1644        fn as_any(&self, func: &mut dyn FnMut(&dyn Any)) {
1645            Reflect::as_any(self.0.deref(), func)
1646        }
1647
1648        fn as_any_mut(&mut self, func: &mut dyn FnMut(&mut dyn Any)) {
1649            Reflect::as_any_mut(self.0.deref_mut(), func)
1650        }
1651
1652        fn as_reflect(&self, func: &mut dyn FnMut(&dyn Reflect)) {
1653            self.0.deref().as_reflect(func)
1654        }
1655
1656        fn as_reflect_mut(&mut self, func: &mut dyn FnMut(&mut dyn Reflect)) {
1657            self.0.deref_mut().as_reflect_mut(func)
1658        }
1659
1660        fn set(&mut self, value: Box<dyn Reflect>) -> Result<Box<dyn Reflect>, Box<dyn Reflect>> {
1661            self.0.deref_mut().set(value)
1662        }
1663
1664        fn set_field(
1665            &mut self,
1666            field: &str,
1667            value: Box<dyn Reflect>,
1668            func: &mut dyn FnMut(Result<Box<dyn Reflect>, SetFieldError>),
1669        ) {
1670            self.0.deref_mut().set_field(field, value, func)
1671        }
1672
1673        fn field(&self, name: &str, func: &mut dyn FnMut(Option<&dyn Reflect>)) {
1674            self.0.deref().field(name, func)
1675        }
1676
1677        fn field_mut(&mut self, name: &str, func: &mut dyn FnMut(Option<&mut dyn Reflect>)) {
1678            self.0.deref_mut().field_mut(name, func)
1679        }
1680
1681        fn derived_types() -> &'static [TypeId] {
1682            &[]
1683        }
1684
1685        fn query_derived_types(&self) -> &'static [TypeId] {
1686            Self::derived_types()
1687        }
1688
1689        fn try_clone_box(&self) -> Option<Box<dyn Reflect>> {
1690            Some(Box::new(self.clone()))
1691        }
1692    }
1693
1694    impl NameProvider for Node {
1695        fn name(&self) -> &str {
1696            &self.name
1697        }
1698    }
1699
1700    impl Deref for Node {
1701        type Target = Base;
1702
1703        fn deref(&self) -> &Self::Target {
1704            self.0.deref()
1705        }
1706    }
1707
1708    impl DerefMut for Node {
1709        fn deref_mut(&mut self) -> &mut Self::Target {
1710            self.0.deref_mut()
1711        }
1712    }
1713
1714    /// A wrapper for node pool record that allows to define custom visit method to have full
1715    /// control over instantiation process at deserialization.
1716    #[derive(Debug, Default, Clone, Reflect)]
1717    pub struct NodeContainer(Option<Node>);
1718
1719    impl Visit for NodeContainer {
1720        fn visit(&mut self, _name: &str, _visitor: &mut Visitor) -> VisitResult {
1721            // Dummy impl.
1722            Ok(())
1723        }
1724    }
1725
1726    impl PayloadContainer for NodeContainer {
1727        type Element = Node;
1728
1729        fn new_empty() -> Self {
1730            Self(None)
1731        }
1732
1733        fn new(element: Self::Element) -> Self {
1734            Self(Some(element))
1735        }
1736
1737        fn is_some(&self) -> bool {
1738            self.0.is_some()
1739        }
1740
1741        fn as_ref(&self) -> Option<&Self::Element> {
1742            self.0.as_ref()
1743        }
1744
1745        fn as_mut(&mut self) -> Option<&mut Self::Element> {
1746            self.0.as_mut()
1747        }
1748
1749        fn replace(&mut self, element: Self::Element) -> Option<Self::Element> {
1750            self.0.replace(element)
1751        }
1752
1753        fn take(&mut self) -> Option<Self::Element> {
1754            self.0.take()
1755        }
1756    }
1757
1758    impl SceneGraphNode for Node {
1759        type Base = Base;
1760        type SceneGraph = Graph;
1761        type ResourceData = Graph;
1762
1763        #[allow(clippy::explicit_auto_deref)] // False-positive
1764        fn base(&self) -> &Self::Base {
1765            &**self
1766        }
1767
1768        fn set_base(&mut self, base: Self::Base) {
1769            **self = base;
1770        }
1771
1772        fn is_resource_instance_root(&self) -> bool {
1773            self.is_resource_instance_root
1774        }
1775
1776        fn original_handle_in_resource(&self) -> Handle<Self> {
1777            self.original_handle_in_resource
1778        }
1779
1780        fn set_original_handle_in_resource(&mut self, handle: Handle<Self>) {
1781            self.original_handle_in_resource = handle;
1782        }
1783
1784        fn resource(&self) -> Option<Resource<Self::ResourceData>> {
1785            self.resource.clone()
1786        }
1787
1788        fn self_handle(&self) -> Handle<Self> {
1789            self.self_handle
1790        }
1791
1792        fn parent(&self) -> Handle<Self> {
1793            self.parent
1794        }
1795
1796        fn children(&self) -> &[Handle<Self>] {
1797            &self.children
1798        }
1799
1800        fn children_mut(&mut self) -> &mut [Handle<Self>] {
1801            &mut self.children
1802        }
1803
1804        fn instance_id(&self) -> Uuid {
1805            self.instance_id
1806        }
1807    }
1808
1809    #[derive(Default, Clone, TypeUuidProvider, Visit, Reflect, Debug)]
1810    #[type_uuid(id = "fc887063-7780-44af-8710-5e0bcf9a83fd")]
1811    pub struct Graph {
1812        root: Handle<Node>,
1813        nodes: Pool<Node, NodeContainer>,
1814    }
1815
1816    impl ResourceData for Graph {
1817        fn type_uuid(&self) -> Uuid {
1818            <Graph as TypeUuidProvider>::type_uuid()
1819        }
1820
1821        fn save(&mut self, _path: &Path) -> Result<(), Box<dyn Error>> {
1822            Ok(())
1823        }
1824
1825        fn can_be_saved(&self) -> bool {
1826            false
1827        }
1828
1829        fn try_clone_box(&self) -> Option<Box<dyn ResourceData>> {
1830            Some(Box::new(self.clone()))
1831        }
1832    }
1833
1834    impl PrefabData for Graph {
1835        type Graph = Graph;
1836
1837        fn graph(&self) -> &Self::Graph {
1838            self
1839        }
1840
1841        fn mapping(&self) -> NodeMapping {
1842            NodeMapping::UseHandles
1843        }
1844    }
1845
1846    impl Index<Handle<Node>> for Graph {
1847        type Output = Node;
1848
1849        #[inline]
1850        fn index(&self, index: Handle<Node>) -> &Self::Output {
1851            &self.nodes[index]
1852        }
1853    }
1854
1855    impl IndexMut<Handle<Node>> for Graph {
1856        #[inline]
1857        fn index_mut(&mut self, index: Handle<Node>) -> &mut Self::Output {
1858            &mut self.nodes[index]
1859        }
1860    }
1861
1862    impl SceneGraph for Graph {
1863        type Prefab = Graph;
1864        type NodeContainer = NodeContainer;
1865        type Node = Node;
1866
1867        fn summary(&self) -> String {
1868            "Summary".to_string()
1869        }
1870
1871        fn root(&self) -> Handle<Self::Node> {
1872            self.root
1873        }
1874
1875        fn set_root(&mut self, root: Handle<Self::Node>) {
1876            self.root = root;
1877        }
1878
1879        fn is_valid_handle(&self, handle: Handle<impl ObjectOrVariant<Self::Node>>) -> bool {
1880            self.nodes.is_valid_handle(handle)
1881        }
1882
1883        fn add_node(&mut self, node: Self::Node) -> Handle<Self::Node> {
1884            let handle = self.nodes.next_free_handle();
1885            self.add_node_at_handle(node, handle);
1886            handle
1887        }
1888
1889        fn add_node_at_handle(&mut self, mut node: Self::Node, handle: Handle<Self::Node>) {
1890            let children = node.children.clone();
1891            node.children.clear();
1892            let handle = self
1893                .nodes
1894                .spawn_at_handle(handle, node)
1895                .expect("The handle must be valid");
1896
1897            if self.root.is_none() {
1898                self.root = handle;
1899            } else {
1900                self.link_nodes(handle, self.root);
1901            }
1902
1903            for child in children {
1904                self.link_nodes(child, handle);
1905            }
1906
1907            let node = &mut self.nodes[handle];
1908            node.self_handle = handle;
1909        }
1910
1911        fn remove_node(&mut self, node_handle: Handle<impl ObjectOrVariant<Self::Node>>) {
1912            let node_handle = node_handle.to_base();
1913            self.isolate_node(node_handle);
1914            let mut stack = vec![node_handle];
1915            while let Some(handle) = stack.pop() {
1916                stack.extend_from_slice(self.nodes[handle].children());
1917                self.nodes.free(handle);
1918            }
1919        }
1920
1921        fn link_nodes(
1922            &mut self,
1923            child: Handle<impl ObjectOrVariant<Self::Node>>,
1924            parent: Handle<impl ObjectOrVariant<Self::Node>>,
1925        ) {
1926            let child = child.to_base();
1927            let parent = parent.to_base();
1928            self.isolate_node(child);
1929            self.nodes[child].parent = parent;
1930            self.nodes[parent].children.push(child);
1931        }
1932
1933        fn unlink_node(&mut self, node_handle: Handle<impl ObjectOrVariant<Self::Node>>) {
1934            self.isolate_node(node_handle);
1935            self.link_nodes(node_handle, self.root);
1936        }
1937
1938        fn isolate_node(&mut self, node_handle: Handle<impl ObjectOrVariant<Self::Node>>) {
1939            let node_handle = node_handle.to_base();
1940
1941            let parent_handle =
1942                std::mem::replace(&mut self.nodes[node_handle].parent, Handle::NONE);
1943
1944            if let Ok(parent) = self.nodes.try_borrow_mut(parent_handle) {
1945                if let Some(i) = parent.children().iter().position(|h| *h == node_handle) {
1946                    parent.children.remove(i);
1947                }
1948            }
1949        }
1950
1951        fn try_get_node(&self, handle: Handle<Self::Node>) -> Result<&Self::Node, PoolError> {
1952            self.nodes.try_borrow(handle)
1953        }
1954
1955        fn try_get_node_mut(
1956            &mut self,
1957            handle: Handle<Self::Node>,
1958        ) -> Result<&mut Self::Node, PoolError> {
1959            self.nodes.try_borrow_mut(handle)
1960        }
1961
1962        fn actual_type_id(&self, handle: Handle<Self::Node>) -> Result<TypeId, PoolError> {
1963            self.nodes
1964                .try_borrow(handle)
1965                .map(|n| NodeAsAny::as_any(n.0.deref()).type_id())
1966        }
1967
1968        fn derived_type_ids(&self, handle: Handle<Self::Node>) -> Result<Vec<TypeId>, PoolError> {
1969            self.nodes
1970                .try_borrow(handle)
1971                .map(|n| n.0.deref().query_derived_types().to_vec())
1972        }
1973
1974        fn actual_type_name(&self, handle: Handle<Self::Node>) -> Result<&'static str, PoolError> {
1975            self.nodes
1976                .try_borrow(handle)
1977                .map(|n| n.0.deref().type_name())
1978        }
1979
1980        fn pair_iter(&self) -> impl Iterator<Item = (Handle<Self::Node>, &Self::Node)> {
1981            self.nodes.pair_iter()
1982        }
1983
1984        fn linear_iter(&self) -> impl Iterator<Item = &Self::Node> {
1985            self.nodes.iter()
1986        }
1987
1988        fn linear_iter_mut(&mut self) -> impl Iterator<Item = &mut Self::Node> {
1989            self.nodes.iter_mut()
1990        }
1991
1992        fn try_get<U: ObjectOrVariant<Node>>(&self, handle: Handle<U>) -> Result<&U, PoolError> {
1993            self.nodes.try_get(handle)
1994        }
1995
1996        fn try_get_mut<U: ObjectOrVariant<Node>>(
1997            &mut self,
1998            handle: Handle<U>,
1999        ) -> Result<&mut U, PoolError> {
2000            self.nodes.try_get_mut(handle)
2001        }
2002    }
2003
2004    fn remap_handles(old_new_mapping: &NodeHandleMap<Node>, dest_graph: &mut Graph) {
2005        // Iterate over instantiated nodes and remap handles.
2006        for (_, &new_node_handle) in old_new_mapping.inner().iter() {
2007            old_new_mapping.remap_handles(
2008                &mut dest_graph.nodes[new_node_handle],
2009                &[TypeId::of::<UntypedResource>()],
2010            );
2011        }
2012    }
2013
2014    fn clear_links(mut node: Node) -> Node {
2015        node.children.clear();
2016        node.parent = Handle::NONE;
2017        node
2018    }
2019
2020    impl Graph {
2021        #[inline]
2022        pub fn copy_node(
2023            &self,
2024            node_handle: Handle<Node>,
2025            dest_graph: &mut Graph,
2026        ) -> (Handle<Node>, NodeHandleMap<Node>) {
2027            let mut old_new_mapping = NodeHandleMap::default();
2028            let root_handle = self.copy_node_raw(node_handle, dest_graph, &mut old_new_mapping);
2029
2030            remap_handles(&old_new_mapping, dest_graph);
2031
2032            (root_handle, old_new_mapping)
2033        }
2034        fn copy_node_raw(
2035            &self,
2036            root_handle: Handle<Node>,
2037            dest_graph: &mut Graph,
2038            old_new_mapping: &mut NodeHandleMap<Node>,
2039        ) -> Handle<Node> {
2040            let src_node = &self.nodes[root_handle];
2041            let dest_node = clear_links(src_node.clone());
2042            let dest_copy_handle = dest_graph.add_node(dest_node);
2043            old_new_mapping.insert(root_handle, dest_copy_handle);
2044            for &src_child_handle in src_node.children() {
2045                let dest_child_handle =
2046                    self.copy_node_raw(src_child_handle, dest_graph, old_new_mapping);
2047                if !dest_child_handle.is_none() {
2048                    dest_graph.link_nodes(dest_child_handle, dest_copy_handle);
2049                }
2050            }
2051            dest_copy_handle
2052        }
2053    }
2054
2055    #[derive(Clone, Reflect, Visit, Default, Debug, ComponentProvider)]
2056    #[reflect(derived_type = "Node")]
2057    pub struct Pivot {
2058        base: Base,
2059    }
2060
2061    impl NodeTrait for Pivot {}
2062
2063    impl Deref for Pivot {
2064        type Target = Base;
2065
2066        fn deref(&self) -> &Self::Target {
2067            &self.base
2068        }
2069    }
2070
2071    impl DerefMut for Pivot {
2072        fn deref_mut(&mut self) -> &mut Self::Target {
2073            &mut self.base
2074        }
2075    }
2076
2077    #[derive(Clone, Reflect, Visit, Default, Debug, ComponentProvider)]
2078    #[reflect(derived_type = "Node")]
2079    pub struct RigidBody {
2080        base: Base,
2081    }
2082
2083    impl NodeTrait for RigidBody {}
2084
2085    impl Deref for RigidBody {
2086        type Target = Base;
2087
2088        fn deref(&self) -> &Self::Target {
2089            &self.base
2090        }
2091    }
2092
2093    impl DerefMut for RigidBody {
2094        fn deref_mut(&mut self) -> &mut Self::Target {
2095            &mut self.base
2096        }
2097    }
2098
2099    #[derive(Clone, Reflect, Visit, Default, Debug, ComponentProvider)]
2100    #[reflect(derived_type = "Node")]
2101    pub struct Joint {
2102        base: Base,
2103        connected_body1: Handle<RigidBody>,
2104        connected_body2: Handle<RigidBody>,
2105    }
2106
2107    impl NodeTrait for Joint {}
2108
2109    impl Deref for Joint {
2110        type Target = Base;
2111
2112        fn deref(&self) -> &Self::Target {
2113            &self.base
2114        }
2115    }
2116
2117    impl DerefMut for Joint {
2118        fn deref_mut(&mut self) -> &mut Self::Target {
2119            &mut self.base
2120        }
2121    }
2122
2123    #[test]
2124    fn test_set_child_position() {
2125        let mut graph = Graph::default();
2126
2127        let root = graph.add_node(Node::new(Pivot::default()));
2128        let a = graph.add_node(Node::new(Pivot::default()));
2129        let b = graph.add_node(Node::new(Pivot::default()));
2130        let c = graph.add_node(Node::new(Pivot::default()));
2131        let d = graph.add_node(Node::new(Pivot::default()));
2132        graph.link_nodes(a, root);
2133        graph.link_nodes(b, root);
2134        graph.link_nodes(c, root);
2135        graph.link_nodes(d, root);
2136
2137        let root_ref = &mut graph[root];
2138        assert_eq!(root_ref.set_child_position(a, 0), Some(0));
2139        assert_eq!(root_ref.set_child_position(b, 1), Some(1));
2140        assert_eq!(root_ref.set_child_position(c, 2), Some(2));
2141        assert_eq!(root_ref.set_child_position(d, 3), Some(3));
2142        assert_eq!(root_ref.children[0], a);
2143        assert_eq!(root_ref.children[1], b);
2144        assert_eq!(root_ref.children[2], c);
2145        assert_eq!(root_ref.children[3], d);
2146
2147        let initial_pos = root_ref.set_child_position(a, 3);
2148        assert_eq!(initial_pos, Some(0));
2149        assert_eq!(root_ref.children[0], b);
2150        assert_eq!(root_ref.children[1], c);
2151        assert_eq!(root_ref.children[2], d);
2152        assert_eq!(root_ref.children[3], a);
2153
2154        let prev_pos = root_ref.set_child_position(a, initial_pos.unwrap());
2155        assert_eq!(prev_pos, Some(3));
2156        assert_eq!(root_ref.children[0], a);
2157        assert_eq!(root_ref.children[1], b);
2158        assert_eq!(root_ref.children[2], c);
2159        assert_eq!(root_ref.children[3], d);
2160
2161        assert_eq!(root_ref.set_child_position(d, 1), Some(3));
2162        assert_eq!(root_ref.children[0], a);
2163        assert_eq!(root_ref.children[1], d);
2164        assert_eq!(root_ref.children[2], b);
2165        assert_eq!(root_ref.children[3], c);
2166
2167        assert_eq!(root_ref.set_child_position(d, 0), Some(1));
2168        assert_eq!(root_ref.children[0], d);
2169        assert_eq!(root_ref.children[1], a);
2170        assert_eq!(root_ref.children[2], b);
2171        assert_eq!(root_ref.children[3], c);
2172    }
2173
2174    #[test]
2175    fn test_derived_handles_mapping() {
2176        let mut prefab_graph = Graph::default();
2177
2178        prefab_graph.add_node(Node::new(Pivot::default()));
2179        let rigid_body = prefab_graph.add_node(Node::new(RigidBody::default()));
2180        let rigid_body2 = prefab_graph.add_node(Node::new(RigidBody::default()));
2181        let joint = prefab_graph.add_node(Node::new(Joint {
2182            base: Base::default(),
2183            connected_body1: rigid_body.transmute(),
2184            connected_body2: rigid_body2.transmute(),
2185        }));
2186
2187        let mut scene_graph = Graph::default();
2188        let root = scene_graph.add_node(Node::new(Pivot::default()));
2189
2190        let (_, mapping) = prefab_graph.copy_node(root, &mut scene_graph);
2191        let rigid_body_copy = mapping
2192            .inner()
2193            .get(&rigid_body)
2194            .cloned()
2195            .unwrap()
2196            .transmute::<RigidBody>();
2197        let rigid_body2_copy = mapping
2198            .inner()
2199            .get(&rigid_body2)
2200            .cloned()
2201            .unwrap()
2202            .transmute::<RigidBody>();
2203        let joint_copy = mapping.inner().get(&joint).cloned().unwrap();
2204        Reflect::as_any(&scene_graph.nodes[joint_copy], &mut |any| {
2205            let joint_copy_ref = any.downcast_ref::<Joint>().unwrap();
2206            assert_eq!(joint_copy_ref.connected_body1, rigid_body_copy);
2207            assert_eq!(joint_copy_ref.connected_body2, rigid_body2_copy);
2208        });
2209    }
2210
2211    #[test]
2212    fn test_change_root() {
2213        let mut graph = Graph::default();
2214
2215        // Root_
2216        //      |_A_
2217        //          |_B
2218        //          |_C_
2219        //             |_D
2220        let root = graph.add_node(Node::new(Pivot::default()));
2221        let d = graph.add_node(Node::new(Pivot::default()));
2222        let c = graph.add_node(Node::new(Pivot {
2223            base: Base {
2224                children: vec![d],
2225                ..Default::default()
2226            },
2227        }));
2228        let b = graph.add_node(Node::new(Pivot::default()));
2229        let a = graph.add_node(Node::new(Pivot {
2230            base: Base {
2231                children: vec![b, c],
2232                ..Default::default()
2233            },
2234        }));
2235        graph.link_nodes(a, root);
2236
2237        dbg!(root, a, b, c, d);
2238
2239        let link_scheme = graph.change_hierarchy_root(root, c);
2240
2241        // C_
2242        //   |_D
2243        //   |_A_
2244        //       |_B
2245        //   |_Root
2246        assert_eq!(graph.root, c);
2247
2248        assert_eq!(graph[graph.root].parent, Handle::<Node>::NONE);
2249        assert_eq!(graph[graph.root].children.len(), 3);
2250
2251        assert_eq!(graph[graph.root].children[0], d);
2252        assert_eq!(graph[d].parent, graph.root);
2253        assert!(graph[d].children.is_empty());
2254
2255        assert_eq!(graph[graph.root].children[1], a);
2256        assert_eq!(graph[a].parent, graph.root);
2257
2258        assert_eq!(graph[graph.root].children[2], root);
2259        assert_eq!(graph[root].parent, graph.root);
2260
2261        assert_eq!(graph[a].children.len(), 1);
2262        assert_eq!(graph[a].children[0], b);
2263        assert_eq!(graph[b].parent, a);
2264
2265        assert!(graph[b].children.is_empty());
2266
2267        // Revert
2268        graph.apply_link_scheme(link_scheme);
2269
2270        assert_eq!(graph.root, root);
2271        assert_eq!(graph[graph.root].parent, Handle::<Node>::NONE);
2272        assert_eq!(graph[graph.root].children, vec![a]);
2273
2274        assert_eq!(graph[a].parent, root);
2275        assert_eq!(graph[a].children, vec![b, c]);
2276
2277        assert_eq!(graph[b].parent, a);
2278        assert_eq!(graph[b].children, Vec::<Handle<Node>>::new());
2279
2280        assert_eq!(graph[c].parent, a);
2281        assert_eq!(graph[c].children, vec![d]);
2282    }
2283}