Skip to main content

bevy_ecs/
hierarchy.rs

1//! The canonical "parent-child" [`Relationship`] for entities, driven by
2//! the [`ChildOf`] [`Relationship`] and the [`Children`] [`RelationshipTarget`].
3//!
4//! See [`ChildOf`] for a full description of the relationship and how to use it.
5//!
6//! [`Relationship`]: crate::relationship::Relationship
7//! [`RelationshipTarget`]: crate::relationship::RelationshipTarget
8
9#[cfg(feature = "bevy_reflect")]
10use crate::reflect::{ReflectComponent, ReflectFromWorld};
11use crate::{
12    bundle::Bundle,
13    component::Component,
14    entity::Entity,
15    relationship::{RelatedSpawner, RelatedSpawnerCommands},
16    system::EntityCommands,
17    template::FromTemplate,
18    world::{EntityWorldMut, FromWorld, World},
19};
20use alloc::vec::Vec;
21#[cfg(feature = "bevy_reflect")]
22use bevy_reflect::std_traits::ReflectDefault;
23#[cfg(all(feature = "serialize", feature = "bevy_reflect"))]
24use bevy_reflect::{ReflectDeserialize, ReflectSerialize};
25use core::ops::Deref;
26use core::slice;
27
28/// Stores the parent entity of this child entity with this component.
29///
30/// This is a [`Relationship`] component, and creates the canonical
31/// "parent / child" hierarchy. This is the "source of truth" component, and it pairs with
32/// the [`Children`] [`RelationshipTarget`](crate::relationship::RelationshipTarget).
33///
34/// This relationship should be used for things like:
35///
36/// 1. Organizing entities in a scene
37/// 2. Propagating configuration or data inherited from a parent, such as "visibility" or "world-space global transforms".
38/// 3. Ensuring a hierarchy is despawned when an entity is despawned.
39///
40/// [`ChildOf`] contains a single "target" [`Entity`]. When [`ChildOf`] is inserted on a "source" entity,
41/// the "target" entity will automatically (and immediately, via a component hook) have a [`Children`]
42/// component inserted, and the "source" entity will be added to that [`Children`] instance.
43///
44/// If the [`ChildOf`] component is replaced with a different "target" entity, the old target's [`Children`]
45/// will be automatically (and immediately, via a component hook) be updated to reflect that change.
46///
47/// Likewise, when the [`ChildOf`] component is removed, the "source" entity will be removed from the old
48/// target's [`Children`]. If this results in [`Children`] being empty, [`Children`] will be automatically removed.
49///
50/// When a parent is despawned, all children (and their descendants) will _also_ be despawned.
51///
52/// You can create parent-child relationships in a variety of ways. The most direct way is to insert a [`ChildOf`] component:
53///
54/// ```
55/// # use bevy_ecs::prelude::*;
56/// # let mut world = World::new();
57/// let root = world.spawn_empty().id();
58/// let child1 = world.spawn(ChildOf(root)).id();
59/// let child2 = world.spawn(ChildOf(root)).id();
60/// let grandchild = world.spawn(ChildOf(child1)).id();
61///
62/// assert_eq!(&**world.entity(root).get::<Children>().unwrap(), &[child1, child2]);
63/// assert_eq!(&**world.entity(child1).get::<Children>().unwrap(), &[grandchild]);
64///
65/// world.entity_mut(child2).remove::<ChildOf>();
66/// assert_eq!(&**world.entity(root).get::<Children>().unwrap(), &[child1]);
67///
68/// world.entity_mut(root).despawn();
69/// assert!(world.get_entity(root).is_err());
70/// assert!(world.get_entity(child1).is_err());
71/// assert!(world.get_entity(grandchild).is_err());
72/// ```
73///
74/// However if you are spawning many children, you might want to use the [`EntityWorldMut::with_children`] helper instead:
75///
76/// ```
77/// # use bevy_ecs::prelude::*;
78/// # let mut world = World::new();
79/// let mut child1 = Entity::PLACEHOLDER;
80/// let mut child2 = Entity::PLACEHOLDER;
81/// let mut grandchild = Entity::PLACEHOLDER;
82/// let root = world.spawn_empty().with_children(|p| {
83///     child1 = p.spawn_empty().with_children(|p| {
84///         grandchild = p.spawn_empty().id();
85///     }).id();
86///     child2 = p.spawn_empty().id();
87/// }).id();
88///
89/// assert_eq!(&**world.entity(root).get::<Children>().unwrap(), &[child1, child2]);
90/// assert_eq!(&**world.entity(child1).get::<Children>().unwrap(), &[grandchild]);
91/// ```
92///
93/// [`Relationship`]: crate::relationship::Relationship
94#[derive(Component, FromTemplate, Clone, PartialEq, Eq, Debug)]
95#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
96#[cfg_attr(
97    feature = "bevy_reflect",
98    reflect(Component, PartialEq, Debug, FromWorld, Clone)
99)]
100#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
101#[cfg_attr(
102    all(feature = "serialize", feature = "bevy_reflect"),
103    reflect(Serialize, Deserialize)
104)]
105#[relationship(relationship_target = Children)]
106#[doc(alias = "IsChild", alias = "Parent")]
107pub struct ChildOf(#[entities] pub Entity);
108
109impl ChildOf {
110    /// The parent entity of this child entity.
111    #[inline]
112    pub fn parent(&self) -> Entity {
113        self.0
114    }
115}
116
117// TODO: We need to impl either FromWorld or Default so ChildOf can be registered as Reflect.
118// This is because Reflect deserialize by creating an instance and apply a patch on top.
119// However ChildOf should only ever be set with a real user-defined entity.  Its worth looking into
120// better ways to handle cases like this.
121impl FromWorld for ChildOf {
122    #[inline(always)]
123    fn from_world(_world: &mut World) -> Self {
124        ChildOf(Entity::PLACEHOLDER)
125    }
126}
127
128/// Tracks which entities are children of this parent entity.
129///
130/// A [`RelationshipTarget`] collection component that is populated
131/// with entities that "target" this entity with the [`ChildOf`] [`Relationship`] component.
132///
133/// Together, these components form the "canonical parent-child hierarchy". See the [`ChildOf`] component for the full
134/// description of this relationship and instructions on how to use it.
135///
136/// # Usage
137///
138/// Like all [`RelationshipTarget`] components, this data should not be directly manipulated to avoid desynchronization.
139/// Instead, modify the [`ChildOf`] components on the "source" entities.
140///
141/// To access the children of an entity, you can iterate over the [`Children`] component,
142/// using the [`IntoIterator`] trait.
143/// For more complex access patterns, see the [`RelationshipTarget`] trait.
144///
145/// [`Relationship`]: crate::relationship::Relationship
146/// [`RelationshipTarget`]: crate::relationship::RelationshipTarget
147#[derive(Component, Default, Debug, PartialEq, Eq)]
148#[relationship_target(relationship = ChildOf, linked_spawn)]
149#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
150#[cfg_attr(feature = "bevy_reflect", reflect(Component, FromWorld, Default))]
151#[doc(alias = "IsParent")]
152pub struct Children(Vec<Entity>);
153
154impl Children {
155    /// Swaps the child at `a_index` with the child at `b_index`.
156    #[inline]
157    pub fn swap(&mut self, a_index: usize, b_index: usize) {
158        self.0.swap(a_index, b_index);
159    }
160
161    /// Sorts children [stably](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability)
162    /// in place using the provided comparator function.
163    ///
164    /// For the underlying implementation, see [`slice::sort_by`].
165    ///
166    /// For the unstable version, see [`sort_unstable_by`](Children::sort_unstable_by).
167    ///
168    /// See also [`sort_by_key`](Children::sort_by_key), [`sort_by_cached_key`](Children::sort_by_cached_key).
169    #[inline]
170    pub fn sort_by<F>(&mut self, compare: F)
171    where
172        F: FnMut(&Entity, &Entity) -> core::cmp::Ordering,
173    {
174        self.0.sort_by(compare);
175    }
176
177    /// Sorts children [stably](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability)
178    /// in place using the provided key extraction function.
179    ///
180    /// For the underlying implementation, see [`slice::sort_by_key`].
181    ///
182    /// For the unstable version, see [`sort_unstable_by_key`](Children::sort_unstable_by_key).
183    ///
184    /// See also [`sort_by`](Children::sort_by), [`sort_by_cached_key`](Children::sort_by_cached_key).
185    #[inline]
186    pub fn sort_by_key<K, F>(&mut self, compare: F)
187    where
188        F: FnMut(&Entity) -> K,
189        K: Ord,
190    {
191        self.0.sort_by_key(compare);
192    }
193
194    /// Sorts children [stably](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability)
195    /// in place using the provided key extraction function. Only evaluates each key at most
196    /// once per sort, caching the intermediate results in memory.
197    ///
198    /// For the underlying implementation, see [`slice::sort_by_cached_key`].
199    ///
200    /// See also [`sort_by`](Children::sort_by), [`sort_by_key`](Children::sort_by_key).
201    #[inline]
202    pub fn sort_by_cached_key<K, F>(&mut self, compare: F)
203    where
204        F: FnMut(&Entity) -> K,
205        K: Ord,
206    {
207        self.0.sort_by_cached_key(compare);
208    }
209
210    /// Sorts children [unstably](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability)
211    /// in place using the provided comparator function.
212    ///
213    /// For the underlying implementation, see [`slice::sort_unstable_by`].
214    ///
215    /// For the stable version, see [`sort_by`](Children::sort_by).
216    ///
217    /// See also [`sort_unstable_by_key`](Children::sort_unstable_by_key).
218    #[inline]
219    pub fn sort_unstable_by<F>(&mut self, compare: F)
220    where
221        F: FnMut(&Entity, &Entity) -> core::cmp::Ordering,
222    {
223        self.0.sort_unstable_by(compare);
224    }
225
226    /// Sorts children [unstably](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability)
227    /// in place using the provided key extraction function.
228    ///
229    /// For the underlying implementation, see [`slice::sort_unstable_by_key`].
230    ///
231    /// For the stable version, see [`sort_by_key`](Children::sort_by_key).
232    ///
233    /// See also [`sort_unstable_by`](Children::sort_unstable_by).
234    #[inline]
235    pub fn sort_unstable_by_key<K, F>(&mut self, compare: F)
236    where
237        F: FnMut(&Entity) -> K,
238        K: Ord,
239    {
240        self.0.sort_unstable_by_key(compare);
241    }
242}
243
244impl<'a> IntoIterator for &'a Children {
245    type Item = <Self::IntoIter as Iterator>::Item;
246
247    type IntoIter = slice::Iter<'a, Entity>;
248
249    #[inline(always)]
250    fn into_iter(self) -> Self::IntoIter {
251        self.0.iter()
252    }
253}
254
255impl Deref for Children {
256    type Target = [Entity];
257
258    fn deref(&self) -> &Self::Target {
259        &self.0
260    }
261}
262
263/// A type alias over [`RelatedSpawner`] used to spawn child entities containing a [`ChildOf`] relationship.
264pub type ChildSpawner<'w> = RelatedSpawner<'w, ChildOf>;
265
266/// A type alias over [`RelatedSpawnerCommands`] used to spawn child entities containing a [`ChildOf`] relationship.
267pub type ChildSpawnerCommands<'w> = RelatedSpawnerCommands<'w, ChildOf>;
268
269impl<'w> EntityWorldMut<'w> {
270    /// Spawns children of this entity (with a [`ChildOf`] relationship) by taking a function that operates on a [`ChildSpawner`].
271    /// See also [`with_related`](Self::with_related).
272    pub fn with_children(&mut self, func: impl FnOnce(&mut ChildSpawner)) -> &mut Self {
273        self.with_related_entities(func);
274        self
275    }
276
277    /// Adds the given children to this entity.
278    /// See also [`add_related`](Self::add_related).
279    pub fn add_children(&mut self, children: &[Entity]) -> &mut Self {
280        self.add_related::<ChildOf>(children)
281    }
282
283    /// Removes all the children from this entity.
284    /// See also [`detach_all_related`](Self::detach_all_related)
285    #[deprecated = "Use detach_all_children() instead"]
286    pub fn clear_children(&mut self) -> &mut Self {
287        self.detach_all_children()
288    }
289
290    /// Removes all the parent-child relationships from this entity.
291    /// To despawn the child entities, instead use [`EntityWorldMut::despawn_children`](EntityWorldMut::despawn_children).
292    /// See also [`detach_all_related`](Self::detach_all_related)
293    pub fn detach_all_children(&mut self) -> &mut Self {
294        self.detach_all_related::<ChildOf>()
295    }
296
297    /// Insert children at specific index.
298    /// See also [`insert_related`](Self::insert_related).
299    pub fn insert_children(&mut self, index: usize, children: &[Entity]) -> &mut Self {
300        self.insert_related::<ChildOf>(index, children)
301    }
302
303    /// Insert child at specific index.
304    /// See also [`insert_related`](Self::insert_related).
305    pub fn insert_child(&mut self, index: usize, child: Entity) -> &mut Self {
306        self.insert_related::<ChildOf>(index, &[child])
307    }
308
309    /// Adds the given child to this entity.
310    /// See also [`add_related`](Self::add_related).
311    pub fn add_child(&mut self, child: Entity) -> &mut Self {
312        self.add_related::<ChildOf>(&[child])
313    }
314
315    /// Removes the relationship between this entity and the given entities.
316    #[deprecated = "Use detach_children() instead"]
317    pub fn remove_children(&mut self, children: &[Entity]) -> &mut Self {
318        self.detach_children(children)
319    }
320
321    /// Removes the parent-child relationship between this entity and the given entities.
322    /// Does not despawn the children.
323    pub fn detach_children(&mut self, children: &[Entity]) -> &mut Self {
324        self.remove_related::<ChildOf>(children)
325    }
326
327    /// Removes the relationship between this entity and the given entity.
328    #[deprecated = "Use detach_child() instead"]
329    pub fn remove_child(&mut self, child: Entity) -> &mut Self {
330        self.detach_child(child)
331    }
332
333    /// Removes the parent-child relationship between this entity and the given entity.
334    /// Does not despawn the child.
335    pub fn detach_child(&mut self, child: Entity) -> &mut Self {
336        self.remove_related::<ChildOf>(&[child])
337    }
338
339    /// Replaces all the related children with a new set of children.
340    pub fn replace_children(&mut self, children: &[Entity]) -> &mut Self {
341        self.replace_related::<ChildOf>(children)
342    }
343
344    /// Replaces all the related children with a new set of children.
345    ///
346    /// # Warning
347    ///
348    /// Failing to maintain the functions invariants may lead to erratic engine behavior including random crashes.
349    /// Refer to [`Self::replace_related_with_difference`] for a list of these invariants.
350    ///
351    /// # Panics
352    ///
353    /// Panics when debug assertions are enabled if an invariant is broken and the command is executed.
354    pub fn replace_children_with_difference(
355        &mut self,
356        entities_to_unrelate: &[Entity],
357        entities_to_relate: &[Entity],
358        newly_related_entities: &[Entity],
359    ) -> &mut Self {
360        self.replace_related_with_difference::<ChildOf>(
361            entities_to_unrelate,
362            entities_to_relate,
363            newly_related_entities,
364        )
365    }
366
367    /// Spawns the passed bundle and adds it to this entity as a child.
368    ///
369    /// For efficient spawning of multiple children, use [`with_children`].
370    ///
371    /// [`with_children`]: EntityWorldMut::with_children
372    pub fn with_child(&mut self, bundle: impl Bundle) -> &mut Self {
373        let parent = self.id();
374        self.world_scope(|world| {
375            world.spawn((bundle, ChildOf(parent)));
376        });
377        self
378    }
379}
380
381impl<'a> EntityCommands<'a> {
382    /// Spawns children of this entity (with a [`ChildOf`] relationship) by taking a function that operates on a [`ChildSpawner`].
383    pub fn with_children(
384        &mut self,
385        func: impl FnOnce(&mut RelatedSpawnerCommands<ChildOf>),
386    ) -> &mut Self {
387        self.with_related_entities(func);
388        self
389    }
390
391    /// Adds the given children to this entity.
392    pub fn add_children(&mut self, children: &[Entity]) -> &mut Self {
393        self.add_related::<ChildOf>(children)
394    }
395
396    /// Removes all the children from this entity.
397    /// See also [`detach_all_related`](Self::detach_all_related)
398    #[deprecated = "Use detach_all_children() instead"]
399    pub fn clear_children(&mut self) -> &mut Self {
400        self.detach_all_children()
401    }
402
403    /// Removes all the parent-child relationships from this entity.
404    /// To despawn the child entities, instead use [`EntityWorldMut::despawn_children`](EntityWorldMut::despawn_children).
405    /// See also [`detach_all_related`](Self::detach_all_related)
406    pub fn detach_all_children(&mut self) -> &mut Self {
407        self.detach_all_related::<ChildOf>()
408    }
409
410    /// Insert children at specific index.
411    /// See also [`insert_related`](Self::insert_related).
412    pub fn insert_children(&mut self, index: usize, children: &[Entity]) -> &mut Self {
413        self.insert_related::<ChildOf>(index, children)
414    }
415
416    /// Insert children at specific index.
417    /// See also [`insert_related`](Self::insert_related).
418    pub fn insert_child(&mut self, index: usize, child: Entity) -> &mut Self {
419        self.insert_related::<ChildOf>(index, &[child])
420    }
421
422    /// Adds the given child to this entity.
423    pub fn add_child(&mut self, child: Entity) -> &mut Self {
424        self.add_related::<ChildOf>(&[child])
425    }
426
427    /// Removes the relationship between this entity and the given entities.
428    #[deprecated = "Use detach_children() instead"]
429    pub fn remove_children(&mut self, children: &[Entity]) -> &mut Self {
430        self.detach_children(children)
431    }
432
433    /// Removes the parent-child relationship between this entity and the given entities.
434    /// Does not despawn the children.
435    pub fn detach_children(&mut self, children: &[Entity]) -> &mut Self {
436        self.remove_related::<ChildOf>(children)
437    }
438
439    /// Removes the relationship between this entity and the given entity.
440    #[deprecated = "Use detach_child() instead"]
441    pub fn remove_child(&mut self, child: Entity) -> &mut Self {
442        self.detach_child(child)
443    }
444
445    /// Removes the parent-child relationship between this entity and the given entity.
446    /// Does not despawn the child.
447    pub fn detach_child(&mut self, child: Entity) -> &mut Self {
448        self.remove_related::<ChildOf>(&[child])
449    }
450
451    /// Replaces the children on this entity with a new list of children.
452    pub fn replace_children(&mut self, children: &[Entity]) -> &mut Self {
453        self.replace_related::<ChildOf>(children)
454    }
455
456    /// Replaces all the related entities with a new set of entities.
457    ///
458    /// # Warning
459    ///
460    /// Failing to maintain the functions invariants may lead to erratic engine behavior including random crashes.
461    /// Refer to [`EntityWorldMut::replace_related_with_difference`] for a list of these invariants.
462    ///
463    /// # Panics
464    ///
465    /// Panics when debug assertions are enabled if an invariant is broken and the command is executed.
466    pub fn replace_children_with_difference(
467        &mut self,
468        entities_to_unrelate: &[Entity],
469        entities_to_relate: &[Entity],
470        newly_related_entities: &[Entity],
471    ) -> &mut Self {
472        self.replace_related_with_difference::<ChildOf>(
473            entities_to_unrelate,
474            entities_to_relate,
475            newly_related_entities,
476        )
477    }
478
479    /// Spawns the passed bundle and adds it to this entity as a child.
480    ///
481    /// For efficient spawning of multiple children, use [`with_children`].
482    ///
483    /// [`with_children`]: EntityCommands::with_children
484    pub fn with_child(&mut self, bundle: impl Bundle) -> &mut Self {
485        self.with_related::<ChildOf>(bundle);
486        self
487    }
488}
489
490/// Returns a [`SpawnRelatedBundle`] that will insert the [`Children`] component, spawn a [`SpawnableList`] of entities with given bundles that
491/// relate to the [`Children`] entity via the [`ChildOf`] component, and reserve space in the [`Children`] for each spawned entity.
492///
493/// Any additional arguments will be interpreted as bundles to be spawned.
494///
495/// Also see [`related`](crate::related) for a version of this that works with any [`RelationshipTarget`] type.
496///
497/// ```
498/// # use bevy_ecs::hierarchy::Children;
499/// # use bevy_ecs::name::Name;
500/// # use bevy_ecs::world::World;
501/// # use bevy_ecs::children;
502/// let mut world = World::new();
503/// world.spawn((
504///     Name::new("Root"),
505///     children![
506///         Name::new("Child1"),
507///         (
508///             Name::new("Child2"),
509///             children![Name::new("Grandchild")]
510///         )
511///     ]
512/// ));
513/// ```
514///
515/// [`RelationshipTarget`]: crate::relationship::RelationshipTarget
516/// [`SpawnRelatedBundle`]: crate::spawn::SpawnRelatedBundle
517/// [`SpawnableList`]: crate::spawn::SpawnableList
518#[macro_export]
519macro_rules! children {
520    [$($child:expr),*$(,)?] => {
521        $crate::related!($crate::hierarchy::Children [$($child),*])
522    };
523}
524
525#[cfg(test)]
526mod tests {
527    use crate::{
528        entity::Entity,
529        hierarchy::{ChildOf, Children},
530        relationship::{RelationshipHookMode, RelationshipTarget},
531        spawn::{Spawn, SpawnRelated},
532        world::World,
533    };
534    use alloc::{vec, vec::Vec};
535
536    #[derive(PartialEq, Eq, Debug)]
537    struct Node {
538        entity: Entity,
539        children: Vec<Node>,
540    }
541
542    impl Node {
543        fn new(entity: Entity) -> Self {
544            Self {
545                entity,
546                children: Vec::new(),
547            }
548        }
549
550        fn new_with(entity: Entity, children: Vec<Node>) -> Self {
551            Self { entity, children }
552        }
553    }
554
555    fn get_hierarchy(world: &World, entity: Entity) -> Node {
556        Node {
557            entity,
558            children: world
559                .entity(entity)
560                .get::<Children>()
561                .map_or_else(Default::default, |c| {
562                    c.iter().map(|e| get_hierarchy(world, e)).collect()
563                }),
564        }
565    }
566
567    #[test]
568    fn hierarchy() {
569        let mut world = World::new();
570        let root = world.spawn_empty().id();
571        let child1 = world.spawn(ChildOf(root)).id();
572        let grandchild = world.spawn(ChildOf(child1)).id();
573        let child2 = world.spawn(ChildOf(root)).id();
574
575        // Spawn
576        let hierarchy = get_hierarchy(&world, root);
577        assert_eq!(
578            hierarchy,
579            Node::new_with(
580                root,
581                vec![
582                    Node::new_with(child1, vec![Node::new(grandchild)]),
583                    Node::new(child2)
584                ]
585            )
586        );
587
588        // Removal
589        world.entity_mut(child1).remove::<ChildOf>();
590        let hierarchy = get_hierarchy(&world, root);
591        assert_eq!(hierarchy, Node::new_with(root, vec![Node::new(child2)]));
592
593        // Insert
594        world.entity_mut(child1).insert(ChildOf(root));
595        let hierarchy = get_hierarchy(&world, root);
596        assert_eq!(
597            hierarchy,
598            Node::new_with(
599                root,
600                vec![
601                    Node::new(child2),
602                    Node::new_with(child1, vec![Node::new(grandchild)])
603                ]
604            )
605        );
606
607        // Recursive Despawn
608        world.entity_mut(root).despawn();
609        assert!(world.get_entity(root).is_err());
610        assert!(world.get_entity(child1).is_err());
611        assert!(world.get_entity(child2).is_err());
612        assert!(world.get_entity(grandchild).is_err());
613    }
614
615    #[test]
616    fn with_children() {
617        let mut world = World::new();
618        let mut child1 = Entity::PLACEHOLDER;
619        let mut child2 = Entity::PLACEHOLDER;
620        let root = world
621            .spawn_empty()
622            .with_children(|p| {
623                child1 = p.spawn_empty().id();
624                child2 = p.spawn_empty().id();
625            })
626            .id();
627
628        let hierarchy = get_hierarchy(&world, root);
629        assert_eq!(
630            hierarchy,
631            Node::new_with(root, vec![Node::new(child1), Node::new(child2)])
632        );
633    }
634
635    #[test]
636    fn add_children() {
637        let mut world = World::new();
638        let child1 = world.spawn_empty().id();
639        let child2 = world.spawn_empty().id();
640        let root = world.spawn_empty().add_children(&[child1, child2]).id();
641
642        let hierarchy = get_hierarchy(&world, root);
643        assert_eq!(
644            hierarchy,
645            Node::new_with(root, vec![Node::new(child1), Node::new(child2)])
646        );
647    }
648
649    #[test]
650    fn insert_children() {
651        let mut world = World::new();
652        let child1 = world.spawn_empty().id();
653        let child2 = world.spawn_empty().id();
654        let child3 = world.spawn_empty().id();
655        let child4 = world.spawn_empty().id();
656
657        let mut entity_world_mut = world.spawn_empty();
658
659        let first_children = entity_world_mut.add_children(&[child1, child2]);
660
661        let root = first_children.insert_children(1, &[child3, child4]).id();
662
663        let hierarchy = get_hierarchy(&world, root);
664        assert_eq!(
665            hierarchy,
666            Node::new_with(
667                root,
668                vec![
669                    Node::new(child1),
670                    Node::new(child3),
671                    Node::new(child4),
672                    Node::new(child2)
673                ]
674            )
675        );
676    }
677
678    #[test]
679    fn insert_child() {
680        let mut world = World::new();
681        let child1 = world.spawn_empty().id();
682        let child2 = world.spawn_empty().id();
683        let child3 = world.spawn_empty().id();
684
685        let mut entity_world_mut = world.spawn_empty();
686
687        let first_children = entity_world_mut.add_children(&[child1, child2]);
688
689        let root = first_children.insert_child(1, child3).id();
690
691        let hierarchy = get_hierarchy(&world, root);
692        assert_eq!(
693            hierarchy,
694            Node::new_with(
695                root,
696                vec![Node::new(child1), Node::new(child3), Node::new(child2)]
697            )
698        );
699    }
700
701    // regression test for https://github.com/bevyengine/bevy/pull/19134
702    #[test]
703    fn insert_children_index_bound() {
704        let mut world = World::new();
705        let child1 = world.spawn_empty().id();
706        let child2 = world.spawn_empty().id();
707        let child3 = world.spawn_empty().id();
708        let child4 = world.spawn_empty().id();
709
710        let mut entity_world_mut = world.spawn_empty();
711
712        let first_children = entity_world_mut.add_children(&[child1, child2]).id();
713        let hierarchy = get_hierarchy(&world, first_children);
714        assert_eq!(
715            hierarchy,
716            Node::new_with(first_children, vec![Node::new(child1), Node::new(child2)])
717        );
718
719        let root = world
720            .entity_mut(first_children)
721            .insert_children(usize::MAX, &[child3, child4])
722            .id();
723        let hierarchy = get_hierarchy(&world, root);
724        assert_eq!(
725            hierarchy,
726            Node::new_with(
727                root,
728                vec![
729                    Node::new(child1),
730                    Node::new(child2),
731                    Node::new(child3),
732                    Node::new(child4),
733                ]
734            )
735        );
736    }
737
738    #[test]
739    fn detach_children() {
740        let mut world = World::new();
741        let child1 = world.spawn_empty().id();
742        let child2 = world.spawn_empty().id();
743        let child3 = world.spawn_empty().id();
744        let child4 = world.spawn_empty().id();
745
746        let mut root = world.spawn_empty();
747        root.add_children(&[child1, child2, child3, child4]);
748        root.detach_children(&[child2, child3]);
749        let root = root.id();
750
751        let hierarchy = get_hierarchy(&world, root);
752        assert_eq!(
753            hierarchy,
754            Node::new_with(root, vec![Node::new(child1), Node::new(child4)])
755        );
756    }
757
758    #[test]
759    fn detach_child() {
760        let mut world = World::new();
761        let child1 = world.spawn_empty().id();
762        let child2 = world.spawn_empty().id();
763        let child3 = world.spawn_empty().id();
764
765        let mut root = world.spawn_empty();
766        root.add_children(&[child1, child2, child3]);
767        root.detach_child(child2);
768        let root = root.id();
769
770        let hierarchy = get_hierarchy(&world, root);
771        assert_eq!(
772            hierarchy,
773            Node::new_with(root, vec![Node::new(child1), Node::new(child3)])
774        );
775    }
776
777    #[test]
778    fn self_parenting_invalid() {
779        let mut world = World::new();
780        let id = world.spawn_empty().id();
781        world.entity_mut(id).insert(ChildOf(id));
782        assert!(
783            world.entity(id).get::<ChildOf>().is_none(),
784            "invalid ChildOf relationships should self-remove"
785        );
786    }
787
788    #[test]
789    fn missing_parent_invalid() {
790        let mut world = World::new();
791        let parent = world.spawn_empty().id();
792        world.entity_mut(parent).despawn();
793        let id = world.spawn(ChildOf(parent)).id();
794        assert!(
795            world.entity(id).get::<ChildOf>().is_none(),
796            "invalid ChildOf relationships should self-remove"
797        );
798    }
799
800    #[test]
801    fn reinsert_same_parent() {
802        let mut world = World::new();
803        let parent = world.spawn_empty().id();
804        let id = world.spawn(ChildOf(parent)).id();
805        world.entity_mut(id).insert(ChildOf(parent));
806        assert_eq!(
807            Some(&ChildOf(parent)),
808            world.entity(id).get::<ChildOf>(),
809            "ChildOf should still be there"
810        );
811    }
812
813    #[test]
814    fn spawn_children() {
815        let mut world = World::new();
816        let id = world.spawn(Children::spawn((Spawn(()), Spawn(())))).id();
817        assert_eq!(world.entity(id).get::<Children>().unwrap().len(), 2,);
818    }
819
820    #[test]
821    fn spawn_many_children() {
822        let mut world = World::new();
823
824        // ensure an empty set can be mentioned
825        world.spawn(children![]);
826
827        // 12 children should result in a flat tuple
828        let id = world
829            .spawn(children![(), (), (), (), (), (), (), (), (), (), (), ()])
830            .id();
831
832        assert_eq!(world.entity(id).get::<Children>().unwrap().len(), 12,);
833
834        // 13 will start nesting, but should nonetheless produce a flat hierarchy
835        let id = world
836            .spawn(children![
837                (),
838                (),
839                (),
840                (),
841                (),
842                (),
843                (),
844                (),
845                (),
846                (),
847                (),
848                (),
849                (),
850            ])
851            .id();
852
853        assert_eq!(world.entity(id).get::<Children>().unwrap().len(), 13,);
854    }
855
856    #[test]
857    fn replace_children() {
858        let mut world = World::new();
859        let parent = world.spawn(Children::spawn((Spawn(()), Spawn(())))).id();
860        let &[child_a, child_b] = &world.entity(parent).get::<Children>().unwrap().0[..] else {
861            panic!("Tried to spawn 2 children on an entity and didn't get 2 children");
862        };
863
864        let child_c = world.spawn_empty().id();
865
866        world
867            .entity_mut(parent)
868            .replace_children(&[child_a, child_c]);
869
870        let children = world.entity(parent).get::<Children>().unwrap();
871
872        assert!(children.contains(&child_a));
873        assert!(children.contains(&child_c));
874        assert!(!children.contains(&child_b));
875
876        assert_eq!(
877            world.entity(child_a).get::<ChildOf>().unwrap(),
878            &ChildOf(parent)
879        );
880        assert_eq!(
881            world.entity(child_c).get::<ChildOf>().unwrap(),
882            &ChildOf(parent)
883        );
884        assert!(world.entity(child_b).get::<ChildOf>().is_none());
885    }
886
887    #[test]
888    fn replace_children_with_nothing() {
889        let mut world = World::new();
890        let parent = world.spawn_empty().id();
891        let child_a = world.spawn_empty().id();
892        let child_b = world.spawn_empty().id();
893
894        world.entity_mut(parent).add_children(&[child_a, child_b]);
895
896        assert_eq!(world.entity(parent).get::<Children>().unwrap().len(), 2);
897
898        world.entity_mut(parent).replace_children(&[]);
899
900        assert!(world.entity(child_a).get::<ChildOf>().is_none());
901        assert!(world.entity(child_b).get::<ChildOf>().is_none());
902    }
903
904    #[test]
905    fn insert_same_child_twice() {
906        let mut world = World::new();
907
908        let parent = world.spawn_empty().id();
909        let child = world.spawn_empty().id();
910
911        world.entity_mut(parent).add_child(child);
912        world.entity_mut(parent).add_child(child);
913
914        let children = world.get::<Children>(parent).unwrap();
915        assert_eq!(children.0, [child]);
916        assert_eq!(
917            world.entity(child).get::<ChildOf>().unwrap(),
918            &ChildOf(parent)
919        );
920    }
921
922    #[test]
923    fn replace_with_difference() {
924        let mut world = World::new();
925
926        let parent = world.spawn_empty().id();
927        let child_a = world.spawn_empty().id();
928        let child_b = world.spawn_empty().id();
929        let child_c = world.spawn_empty().id();
930        let child_d = world.spawn_empty().id();
931
932        // Test inserting new relations
933        world.entity_mut(parent).replace_children_with_difference(
934            &[],
935            &[child_a, child_b],
936            &[child_a, child_b],
937        );
938
939        assert_eq!(
940            world.entity(child_a).get::<ChildOf>().unwrap(),
941            &ChildOf(parent)
942        );
943        assert_eq!(
944            world.entity(child_b).get::<ChildOf>().unwrap(),
945            &ChildOf(parent)
946        );
947        assert_eq!(
948            world.entity(parent).get::<Children>().unwrap().0,
949            [child_a, child_b]
950        );
951
952        // Test replacing relations and changing order
953        world.entity_mut(parent).replace_children_with_difference(
954            &[child_b],
955            &[child_d, child_c, child_a],
956            &[child_c, child_d],
957        );
958        assert_eq!(
959            world.entity(child_a).get::<ChildOf>().unwrap(),
960            &ChildOf(parent)
961        );
962        assert_eq!(
963            world.entity(child_c).get::<ChildOf>().unwrap(),
964            &ChildOf(parent)
965        );
966        assert_eq!(
967            world.entity(child_d).get::<ChildOf>().unwrap(),
968            &ChildOf(parent)
969        );
970        assert_eq!(
971            world.entity(parent).get::<Children>().unwrap().0,
972            [child_d, child_c, child_a]
973        );
974        assert!(!world.entity(child_b).contains::<ChildOf>());
975
976        // Test removing relationships
977        world.entity_mut(parent).replace_children_with_difference(
978            &[child_a, child_d, child_c],
979            &[],
980            &[],
981        );
982        assert!(!world.entity(parent).contains::<Children>());
983        assert!(!world.entity(child_a).contains::<ChildOf>());
984        assert!(!world.entity(child_b).contains::<ChildOf>());
985        assert!(!world.entity(child_c).contains::<ChildOf>());
986        assert!(!world.entity(child_d).contains::<ChildOf>());
987    }
988
989    #[test]
990    fn replace_with_difference_on_empty() {
991        let mut world = World::new();
992
993        let parent = world.spawn_empty().id();
994        let child_a = world.spawn_empty().id();
995
996        world
997            .entity_mut(parent)
998            .replace_children_with_difference(&[child_a], &[], &[]);
999
1000        assert!(!world.entity(parent).contains::<Children>());
1001        assert!(!world.entity(child_a).contains::<ChildOf>());
1002    }
1003
1004    #[test]
1005    fn replace_with_difference_totally_new_children() {
1006        let mut world = World::new();
1007
1008        let parent = world.spawn_empty().id();
1009        let child_a = world.spawn_empty().id();
1010        let child_b = world.spawn_empty().id();
1011        let child_c = world.spawn_empty().id();
1012        let child_d = world.spawn_empty().id();
1013
1014        // Test inserting new relations
1015        world.entity_mut(parent).replace_children_with_difference(
1016            &[],
1017            &[child_a, child_b],
1018            &[child_a, child_b],
1019        );
1020
1021        assert_eq!(
1022            world.entity(child_a).get::<ChildOf>().unwrap(),
1023            &ChildOf(parent)
1024        );
1025        assert_eq!(
1026            world.entity(child_b).get::<ChildOf>().unwrap(),
1027            &ChildOf(parent)
1028        );
1029        assert_eq!(
1030            world.entity(parent).get::<Children>().unwrap().0,
1031            [child_a, child_b]
1032        );
1033
1034        // Test replacing relations and changing order
1035        world.entity_mut(parent).replace_children_with_difference(
1036            &[child_b, child_a],
1037            &[child_d, child_c],
1038            &[child_c, child_d],
1039        );
1040        assert_eq!(
1041            world.entity(child_c).get::<ChildOf>().unwrap(),
1042            &ChildOf(parent)
1043        );
1044        assert_eq!(
1045            world.entity(child_d).get::<ChildOf>().unwrap(),
1046            &ChildOf(parent)
1047        );
1048        assert_eq!(
1049            world.entity(parent).get::<Children>().unwrap().0,
1050            [child_d, child_c]
1051        );
1052        assert!(!world.entity(child_a).contains::<ChildOf>());
1053        assert!(!world.entity(child_b).contains::<ChildOf>());
1054    }
1055
1056    #[test]
1057    fn replace_children_order() {
1058        let mut world = World::new();
1059
1060        let parent = world.spawn_empty().id();
1061        let child_a = world.spawn_empty().id();
1062        let child_b = world.spawn_empty().id();
1063        let child_c = world.spawn_empty().id();
1064        let child_d = world.spawn_empty().id();
1065
1066        let initial_order = [child_a, child_b, child_c, child_d];
1067        world.entity_mut(parent).add_children(&initial_order);
1068
1069        assert_eq!(
1070            world.entity_mut(parent).get::<Children>().unwrap().0,
1071            initial_order
1072        );
1073
1074        let new_order = [child_d, child_b, child_a, child_c];
1075        world.entity_mut(parent).replace_children(&new_order);
1076
1077        assert_eq!(world.entity(parent).get::<Children>().unwrap().0, new_order);
1078    }
1079
1080    #[test]
1081    #[should_panic]
1082    #[cfg_attr(
1083        not(debug_assertions),
1084        ignore = "we don't check invariants if debug assertions are off"
1085    )]
1086    fn replace_diff_invariant_overlapping_unrelate_with_relate() {
1087        let mut world = World::new();
1088
1089        let parent = world.spawn_empty().id();
1090        let child_a = world.spawn_empty().id();
1091
1092        world
1093            .entity_mut(parent)
1094            .replace_children_with_difference(&[], &[child_a], &[child_a]);
1095
1096        // This should panic
1097        world
1098            .entity_mut(parent)
1099            .replace_children_with_difference(&[child_a], &[child_a], &[]);
1100    }
1101
1102    #[test]
1103    #[should_panic]
1104    #[cfg_attr(
1105        not(debug_assertions),
1106        ignore = "we don't check invariants if debug assertions are off"
1107    )]
1108    fn replace_diff_invariant_overlapping_unrelate_with_newly() {
1109        let mut world = World::new();
1110
1111        let parent = world.spawn_empty().id();
1112        let child_a = world.spawn_empty().id();
1113        let child_b = world.spawn_empty().id();
1114
1115        world
1116            .entity_mut(parent)
1117            .replace_children_with_difference(&[], &[child_a], &[child_a]);
1118
1119        // This should panic
1120        world.entity_mut(parent).replace_children_with_difference(
1121            &[child_b],
1122            &[child_a, child_b],
1123            &[child_b],
1124        );
1125    }
1126
1127    #[test]
1128    #[should_panic]
1129    #[cfg_attr(
1130        not(debug_assertions),
1131        ignore = "we don't check invariants if debug assertions are off"
1132    )]
1133    fn replace_diff_invariant_newly_not_subset() {
1134        let mut world = World::new();
1135
1136        let parent = world.spawn_empty().id();
1137        let child_a = world.spawn_empty().id();
1138        let child_b = world.spawn_empty().id();
1139
1140        // This should panic
1141        world.entity_mut(parent).replace_children_with_difference(
1142            &[],
1143            &[child_a, child_b],
1144            &[child_a],
1145        );
1146    }
1147
1148    #[test]
1149    fn child_replace_hook_skip() {
1150        let mut world = World::new();
1151        let parent = world.spawn_empty().id();
1152        let other = world.spawn_empty().id();
1153        let child = world.spawn(ChildOf(parent)).id();
1154        world
1155            .entity_mut(child)
1156            .insert_with_relationship_hook_mode(ChildOf(other), RelationshipHookMode::Skip);
1157        assert_eq!(
1158            &**world.entity(parent).get::<Children>().unwrap(),
1159            &[child],
1160            "Children should still have the old value, as on_insert/on_discard didn't run"
1161        );
1162    }
1163}