Skip to main content

bevy_ecs/component/
required.rs

1use alloc::{format, vec::Vec};
2use bevy_platform::{hash::FixedHasher, sync::Arc};
3use bevy_ptr::OwningPtr;
4use core::fmt::Debug;
5use indexmap::{IndexMap, IndexSet};
6use thiserror::Error;
7
8use crate::{
9    bundle::BundleInfo,
10    change_detection::{MaybeLocation, Tick},
11    component::{Component, ComponentId, Components, ComponentsRegistrator},
12    entity::Entity,
13    query::DebugCheckedUnwrap as _,
14    storage::{SparseSets, Table, TableRow},
15};
16
17/// Metadata associated with a required component. See [`Component`] for details.
18#[derive(#[automatically_derived]
impl ::core::clone::Clone for RequiredComponent {
    #[inline]
    fn clone(&self) -> RequiredComponent {
        RequiredComponent {
            constructor: ::core::clone::Clone::clone(&self.constructor),
        }
    }
}Clone)]
19pub struct RequiredComponent {
20    /// The constructor used for the required component.
21    pub constructor: RequiredComponentConstructor,
22}
23
24/// A Required Component constructor. See [`Component`] for details.
25#[derive(#[automatically_derived]
impl ::core::clone::Clone for RequiredComponentConstructor {
    #[inline]
    fn clone(&self) -> RequiredComponentConstructor {
        RequiredComponentConstructor(::core::clone::Clone::clone(&self.0))
    }
}Clone)]
26pub struct RequiredComponentConstructor(
27    // Note: this function makes `unsafe` assumptions, so it cannot be public.
28    Arc<dyn Fn(&mut Table, &mut SparseSets, Tick, TableRow, Entity, MaybeLocation)>,
29);
30
31impl RequiredComponentConstructor {
32    /// Creates a new instance of `RequiredComponentConstructor` for the given type
33    ///
34    /// # Safety
35    ///
36    /// - `component_id` must be a valid component for type `C`.
37    pub unsafe fn new<C: Component>(
38        component_id: ComponentId,
39        constructor: impl Fn() -> C + 'static,
40    ) -> Self {
41        RequiredComponentConstructor({
42            // `portable-atomic-util` `Arc` is not able to coerce an unsized
43            // type like `std::sync::Arc` can. Creating a `Box` first does the
44            // coercion.
45            //
46            // This would be resolved by https://github.com/rust-lang/rust/issues/123430
47
48            #[cfg(not(target_has_atomic = "ptr"))]
49            use alloc::boxed::Box;
50
51            type Constructor = dyn for<'a, 'b> Fn(
52                &'a mut Table,
53                &'b mut SparseSets,
54                Tick,
55                TableRow,
56                Entity,
57                MaybeLocation,
58            );
59
60            #[cfg(not(target_has_atomic = "ptr"))]
61            type Intermediate<T> = Box<T>;
62
63            #[cfg(target_has_atomic = "ptr")]
64            type Intermediate<T> = Arc<T>;
65
66            let boxed: Intermediate<Constructor> = Intermediate::new(
67                move |table, sparse_sets, change_tick, table_row, entity, caller| {
68                    OwningPtr::make(constructor(), |ptr| {
69                        // SAFETY: This will only be called in the context of `BundleInfo::write_components`, which will
70                        // pass in a valid table_row and entity requiring a C constructor
71                        // C::STORAGE_TYPE is the storage type associated with `component_id` / `C`
72                        // `ptr` points to valid `C` data, which matches the type associated with `component_id`
73                        unsafe {
74                            BundleInfo::initialize_required_component(
75                                table,
76                                sparse_sets,
77                                change_tick,
78                                table_row,
79                                entity,
80                                component_id,
81                                C::STORAGE_TYPE,
82                                ptr,
83                                caller,
84                            );
85                        }
86                    });
87                },
88            );
89
90            Arc::from(boxed)
91        })
92    }
93
94    /// # Safety
95    /// This is intended to only be called in the context of [`BundleInfo::write_components`] to initialized required components.
96    /// Calling it _anywhere else_ should be considered unsafe.
97    ///
98    /// `table_row` and `entity` must correspond to a valid entity that currently needs a component initialized via the constructor stored
99    /// on this [`RequiredComponentConstructor`]. The stored constructor must correspond to a component on `entity` that needs initialization.
100    /// `table` and `sparse_sets` must correspond to storages on a world where `entity` needs this required component initialized.
101    ///
102    /// Again, don't call this anywhere but [`BundleInfo::write_components`].
103    pub(crate) unsafe fn initialize(
104        &self,
105        table: &mut Table,
106        sparse_sets: &mut SparseSets,
107        change_tick: Tick,
108        table_row: TableRow,
109        entity: Entity,
110        caller: MaybeLocation,
111    ) {
112        (self.0)(table, sparse_sets, change_tick, table_row, entity, caller);
113    }
114}
115
116/// The collection of metadata for components that are required for a given component.
117///
118/// For more information, see the "Required Components" section of [`Component`].
119#[derive(#[automatically_derived]
impl ::core::default::Default for RequiredComponents {
    #[inline]
    fn default() -> RequiredComponents {
        RequiredComponents {
            direct: ::core::default::Default::default(),
            all: ::core::default::Default::default(),
        }
    }
}Default, #[automatically_derived]
impl ::core::clone::Clone for RequiredComponents {
    #[inline]
    fn clone(&self) -> RequiredComponents {
        RequiredComponents {
            direct: ::core::clone::Clone::clone(&self.direct),
            all: ::core::clone::Clone::clone(&self.all),
        }
    }
}Clone)]
120pub struct RequiredComponents {
121    /// The components that are directly required (i.e. excluding inherited ones), in the order of their precedence.
122    ///
123    /// # Safety
124    /// The [`RequiredComponent`] instance associated to each ID must be valid for its component.
125    pub(crate) direct: IndexMap<ComponentId, RequiredComponent, FixedHasher>,
126    /// All the components that are required (i.e. including inherited ones), in depth-first order. Most importantly,
127    /// components in this list always appear after all the components that they require.
128    ///
129    /// Note that the direct components are not necessarily at the end of this list, for example if A and C are directly
130    /// requires, and A requires B requires C, then `all` will hold [C, B, A].
131    ///
132    /// # Safety
133    /// The [`RequiredComponent`] instance associated to each ID must be valid for its component.
134    pub(crate) all: IndexMap<ComponentId, RequiredComponent, FixedHasher>,
135}
136
137impl Debug for RequiredComponents {
138    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
139        f.debug_struct("RequiredComponents")
140            .field("direct", &self.direct.keys())
141            .field("all", &self.all.keys())
142            .finish()
143    }
144}
145
146impl RequiredComponents {
147    /// Registers the [`Component`] `C` as an explicitly required component.
148    ///
149    /// If the component was not already registered as an explicit required component then it is added
150    /// as one, potentially overriding the constructor of a inherited required component, otherwise panics.
151    ///
152    /// # Safety
153    ///
154    /// - all other components in this [`RequiredComponents`] instance must have been registered in `components`.
155    unsafe fn register<C: Component>(
156        &mut self,
157        components: &mut ComponentsRegistrator<'_>,
158        constructor: impl Fn() -> C + 'static,
159    ) {
160        let id = components.register_component::<C>();
161        // SAFETY:
162        // - `id` was just registered in `components`;
163        // - the caller guarantees all other components were registered in `components`.
164        unsafe { self.register_by_id::<C>(id, components, constructor) };
165    }
166
167    /// Registers the [`Component`] with the given `component_id` ID as an explicitly required component.
168    ///
169    /// If the component was not already registered as an explicit required component then it is added
170    /// as one, potentially overriding the constructor of a inherited required component, otherwise panics.
171    ///
172    /// # Safety
173    ///
174    /// - `component_id` must be a valid component in `components` for the type `C`;
175    /// - all other components in this [`RequiredComponents`] instance must have been registered in `components`.
176    unsafe fn register_by_id<C: Component>(
177        &mut self,
178        component_id: ComponentId,
179        components: &Components,
180        constructor: impl Fn() -> C + 'static,
181    ) {
182        // SAFETY: the caller guarantees that `component_id` is valid for the type `C`.
183        let constructor =
184            || unsafe { RequiredComponentConstructor::new(component_id, constructor) };
185
186        // SAFETY:
187        // - the caller guarantees that `component_id` is valid in `components`
188        // - the caller guarantees all other components were registered in `components`;
189        // - constructor is guaranteed to create a valid constructor for the component with id `component_id`.
190        unsafe { self.register_dynamic_with(component_id, components, constructor) };
191    }
192
193    /// Registers the [`Component`] with the given `component_id` ID as an explicitly required component.
194    ///
195    /// If the component was not already registered as an explicit required component then it is added
196    /// as one, potentially overriding the constructor of a inherited required component, otherwise panics.
197    ///
198    /// # Safety
199    ///
200    /// - `component_id` must be a valid component in `components`;
201    /// - all other components in `self` must have been registered in `components`;
202    /// - `constructor` must return a [`RequiredComponentConstructor`] that constructs a valid instance for the
203    ///   component with ID `component_id`.
204    unsafe fn register_dynamic_with(
205        &mut self,
206        component_id: ComponentId,
207        components: &Components,
208        constructor: impl FnOnce() -> RequiredComponentConstructor,
209    ) {
210        // If already registered as a direct required component then bail.
211        let entry = match self.direct.entry(component_id) {
212            indexmap::map::Entry::Vacant(entry) => entry,
213            indexmap::map::Entry::Occupied(_) =>
214                {
    ::core::panicking::panic_fmt(format_args!("Error while registering required component {0:?}: already directly required",
            component_id));
}panic!("Error while registering required component {component_id:?}: already directly required"),
215        };
216
217        // Insert into `direct`.
218        let constructor = constructor();
219        let required_component = RequiredComponent { constructor };
220        entry.insert(required_component.clone());
221
222        // Register inherited required components.
223        // SAFETY:
224        // - the caller guarantees all components that were in `self` have been registered in `components`;
225        // - `component_id` has just been added, but is also guaranteed by the called to be valid in `components`.
226        unsafe {
227            Self::register_inherited_required_components_unchecked(
228                &mut self.all,
229                component_id,
230                required_component,
231                components,
232            );
233        }
234    }
235
236    /// Rebuild the `all` list
237    ///
238    /// # Safety
239    ///
240    /// - all components in `self` must have been registered in `components`.
241    unsafe fn rebuild_inherited_required_components(&mut self, components: &Components) {
242        // Clear `all`, we are re-initializing it.
243        self.all.clear();
244
245        // Register all inherited components as if we just registered all components in `direct` one-by-one.
246        for (&required_id, required_component) in &self.direct {
247            // SAFETY:
248            // - the caller guarantees that all components in this instance have been registered in `components`,
249            //   meaning both `all` and `required_id` have been registered in `components`;
250            // - `required_component` was associated to `required_id`, so it must hold a constructor valid for it.
251            unsafe {
252                Self::register_inherited_required_components_unchecked(
253                    &mut self.all,
254                    required_id,
255                    required_component.clone(),
256                    components,
257                );
258            }
259        }
260    }
261
262    /// Registers all the inherited required components from `required_id`.
263    ///
264    /// # Safety
265    ///
266    /// - all components in `all` must have been registered in `components`;
267    /// - `required_id` must have been registered in `components`;
268    /// - `required_component` must hold a valid constructor for the component with id `required_id`.
269    unsafe fn register_inherited_required_components_unchecked(
270        all: &mut IndexMap<ComponentId, RequiredComponent, FixedHasher>,
271        required_id: ComponentId,
272        required_component: RequiredComponent,
273        components: &Components,
274    ) {
275        // SAFETY: the caller guarantees that `required_id` is valid in `components`.
276        let info = unsafe { components.get_info(required_id).debug_checked_unwrap() };
277
278        // Now we need to "recursively" register the
279        // Small optimization: if the current required component was already required recursively
280        // by an earlier direct required component then all its inherited components have all already
281        // been inserted, so let's not try to reinsert them.
282        if !all.contains_key(&required_id) {
283            for (&inherited_id, inherited_required) in &info.required_components().all {
284                // This is an inherited required component: insert it only if not already present.
285                // By the invariants of `RequiredComponents`, `info.required_components().all` holds the required
286                // components in a depth-first order, and this makes us store the components in `self.all` also
287                // in depth-first order, as long as we don't overwrite existing ones.
288                //
289                // SAFETY:
290                // `inherited_required` was associated to `inherited_id`, so it must have been valid for its component.
291                all.entry(inherited_id)
292                    .or_insert_with(|| inherited_required.clone());
293            }
294        }
295
296        // For direct required components:
297        // - insert them after inherited components to follow the depth-first order;
298        // - insert them unconditionally in order to make their constructor the one that's used.
299        // Note that `insert` does not change the order of components, meaning `component_id` will still appear
300        // before any other component that requires it.
301        //
302        // SAFETY: the caller guarantees that `required_component` is valid for the component with ID `required_id`.
303        all.insert(required_id, required_component);
304    }
305
306    /// Iterates the ids of all required components. This includes recursive required components.
307    pub fn iter_ids(&self) -> impl Iterator<Item = ComponentId> + '_ {
308        self.all.keys().copied()
309    }
310}
311
312impl Components {
313    /// Registers the components in `required_components` as required by `requiree`.
314    ///
315    /// # Safety
316    ///
317    /// - `requiree` must have been registered in `self`
318    /// - all components in `required_components` must have been registered in `self`;
319    /// - this is called with `requiree` before being called on any component requiring `requiree`.
320    pub(crate) unsafe fn register_required_by(
321        &mut self,
322        requiree: ComponentId,
323        required_components: &RequiredComponents,
324    ) {
325        for &required in required_components.all.keys() {
326            // SAFETY: the caller guarantees that all components in `required_components` have been registered in `self`.
327            let required_by = unsafe { self.get_required_by_mut(required).debug_checked_unwrap() };
328            // This preserves the invariant of `required_by` because:
329            // - components requiring `required` and required by `requiree` are already initialized at this point
330            //   and hence registered in `required_by` before `requiree`;
331            // - components requiring `requiree` cannot exist yet, as this is called on `requiree` before them.
332            required_by.insert(requiree);
333        }
334    }
335
336    /// Registers the given component `R` and [required components] inherited from it as required by `T`.
337    ///
338    /// When `T` is added to an entity, `R` will also be added if it was not already provided.
339    /// The given `constructor` will be used for the creation of `R`.
340    ///
341    /// [required components]: Component#required-components
342    ///
343    /// # Safety
344    ///
345    /// - the given component IDs `required` and `requiree` must be valid in `self`;
346    /// - the given component ID `required` must be valid for the component type `R`.
347    ///
348    ///
349    /// # Errors
350    ///
351    /// Returns a [`RequiredComponentsError`] if either of these are true:
352    /// - the `required` component is already a *directly* required component for the `requiree`; indirect
353    ///   requirements through other components are allowed. In those cases, the more specific
354    ///   registration will be used.
355    /// - the `requiree` component is already a (possibly indirect) required component for the `required` component.
356    pub(crate) unsafe fn register_required_components<R: Component>(
357        &mut self,
358        requiree: ComponentId,
359        required: ComponentId,
360        constructor: fn() -> R,
361    ) -> Result<(), RequiredComponentsError> {
362        // First step: validate inputs and return errors.
363
364        // SAFETY: The caller ensures that the `required` is valid.
365        let required_required_components = unsafe {
366            self.get_required_components(required)
367                .debug_checked_unwrap()
368        };
369
370        // Cannot create cyclic requirements.
371        if required_required_components.all.contains_key(&requiree) {
372            return Err(RequiredComponentsError::CyclicRequirement(
373                requiree, required,
374            ));
375        }
376
377        // SAFETY: The caller ensures that the `requiree` is valid.
378        let required_components = unsafe {
379            self.get_required_components_mut(requiree)
380                .debug_checked_unwrap()
381        };
382
383        // Cannot directly require the same component twice.
384        if required_components.direct.contains_key(&required) {
385            return Err(RequiredComponentsError::DuplicateRegistration(
386                requiree, required,
387            ));
388        }
389
390        // Second step: register the single requirement requiree->required
391
392        // Store the old count of (all) required components. This will help determine which ones are new.
393        let old_required_count = required_components.all.len();
394
395        // SAFETY: the caller guarantees that `requiree` is valid in `self`.
396        unsafe {
397            self.required_components_scope(requiree, |this, required_components| {
398                // SAFETY: the caller guarantees that `required` is valid for type `R` in `self`
399                required_components.register_by_id(required, this, constructor);
400            });
401        }
402        // Third step: update the required components and required_by of all the indirect requirements/requirees.
403
404        // Borrow again otherwise it conflicts with the `self.required_components_scope` call.
405        // SAFETY: The caller ensures that the `requiree` is valid.
406        let required_components = unsafe {
407            self.get_required_components_mut(requiree)
408                .debug_checked_unwrap()
409        };
410
411        // Optimization: get all the new required components, i.e. those that were appended.
412        // Other components that might be inherited when requiring `required` can be safely ignored because
413        // any component requiring `requiree` will already transitively require them.
414        // Note: the only small exception is for `required` itself, for which we cannot ignore the value of the
415        // constructor. But for simplicity we will rebuild any `RequiredComponents`
416        let new_required_components = required_components.all[old_required_count..]
417            .keys()
418            .copied()
419            .collect::<Vec<_>>();
420
421        // Get all the new requiree components, i.e. `requiree` and all the components that `requiree` is required by.
422        // SAFETY: The caller ensures that the `requiree` is valid.
423        let requiree_required_by = unsafe { self.get_required_by(requiree).debug_checked_unwrap() };
424        let new_requiree_components = [requiree]
425            .into_iter()
426            .chain(requiree_required_by.iter().copied())
427            .collect::<IndexSet<_, FixedHasher>>();
428
429        // We now need to update the required and required_by components of all the components
430        // directly or indirectly involved.
431        // Important: we need to be careful about the order we do these operations in.
432        // Since computing the required components of some component depends on the required components of
433        // other components, and while we do this operations not all required components are up-to-date, we need
434        // to ensure we update components in such a way that we update a component after the components it depends on.
435        // Luckily, `new_requiree_components` comes from `ComponentInfo::required_by`, which guarantees an order
436        // with that property.
437
438        // Update the inherited required components of all requiree components (directly or indirectly).
439        // Skip the first one (requiree) because we already updates it.
440        for &indirect_requiree in &new_requiree_components[1..] {
441            // SAFETY: `indirect_requiree` comes from `self` so it must be valid.
442            unsafe {
443                self.required_components_scope(indirect_requiree, |this, required_components| {
444                    // Rebuild the inherited required components.
445                    // SAFETY: `required_components` comes from `self`, so all its components must have be valid in `self`.
446                    required_components.rebuild_inherited_required_components(this);
447                });
448            }
449        }
450
451        // Update the `required_by` of all the components that were newly required (directly or indirectly).
452        for &indirect_required in &new_required_components {
453            // SAFETY: `indirect_required` comes from `self`, so it must be valid.
454            let required_by = unsafe {
455                self.get_required_by_mut(indirect_required)
456                    .debug_checked_unwrap()
457            };
458
459            // Remove and re-add all the components in `new_requiree_components`
460            // This preserves the invariant of `required_by` because `new_requiree_components`
461            // satisfies its invariant, due to being `requiree` followed by its `required_by` components,
462            // and because any component not in `new_requiree_components` cannot require a component in it,
463            // since if that was the case it would appear in the `required_by` for `requiree`.
464            required_by.retain(|id| !new_requiree_components.contains(id));
465            required_by.extend(&new_requiree_components);
466        }
467
468        Ok(())
469    }
470
471    /// Temporarily take out the [`RequiredComponents`] of the component with id `component_id`
472    /// and runs the given closure with mutable access to `self` and the given [`RequiredComponents`].
473    ///
474    /// SAFETY:
475    ///
476    /// `component_id` is valid in `self.components`
477    unsafe fn required_components_scope<R>(
478        &mut self,
479        component_id: ComponentId,
480        f: impl FnOnce(&mut Self, &mut RequiredComponents) -> R,
481    ) -> R {
482        struct DropGuard<'a> {
483            components: &'a mut Components,
484            component_id: ComponentId,
485            required_components: RequiredComponents,
486        }
487
488        impl Drop for DropGuard<'_> {
489            fn drop(&mut self) {
490                // SAFETY: The caller ensures that the `component_id` is valid.
491                let required_components = unsafe {
492                    self.components
493                        .get_required_components_mut(self.component_id)
494                        .debug_checked_unwrap()
495                };
496
497                if true {
    if !required_components.direct.is_empty() {
        ::core::panicking::panic("assertion failed: required_components.direct.is_empty()")
    };
};debug_assert!(required_components.direct.is_empty());
498                if true {
    if !required_components.all.is_empty() {
        ::core::panicking::panic("assertion failed: required_components.all.is_empty()")
    };
};debug_assert!(required_components.all.is_empty());
499
500                *required_components = core::mem::take(&mut self.required_components);
501            }
502        }
503
504        let mut guard = DropGuard {
505            component_id,
506            // SAFETY: The caller ensures that the `component_id` is valid.
507            required_components: core::mem::take(unsafe {
508                self.get_required_components_mut(component_id)
509                    .debug_checked_unwrap()
510            }),
511            components: self,
512        };
513
514        f(guard.components, &mut guard.required_components)
515    }
516}
517
518/// An error returned when the registration of a required component fails.
519#[derive(#[allow(unused_qualifications)]
#[automatically_derived]
impl ::core::fmt::Display for RequiredComponentsError {
    fn fmt(&self, __formatter: &mut ::core::fmt::Formatter)
        -> ::core::fmt::Result {

        #[allow(unused_variables, deprecated, clippy ::
        used_underscore_binding)]
        match self {
            RequiredComponentsError::DuplicateRegistration(_0, _1) =>
                match (_0, _1) {
                    (__field0, __field1) =>
                        __formatter.write_fmt(format_args!("Component {0:?} already directly requires component {1:?}",
                                __field0, __field1)),
                },
            RequiredComponentsError::CyclicRequirement(_0, _1) =>
                match (_0, _1) {
                    (__field0, __field1) =>
                        __formatter.write_fmt(format_args!("Cyclic requirement found: the requiree component {0:?} is required by the required component {1:?}",
                                __field0, __field1)),
                },
            RequiredComponentsError::ArchetypeExists(_0) =>
                match (_0,) {
                    (__field0,) =>
                        __formatter.write_fmt(format_args!("An archetype with the component {0:?} that requires other components already exists",
                                __field0)),
                },
        }
    }
}Error, #[automatically_derived]
impl ::core::fmt::Debug for RequiredComponentsError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            RequiredComponentsError::DuplicateRegistration(__self_0, __self_1)
                =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "DuplicateRegistration", __self_0, &__self_1),
            RequiredComponentsError::CyclicRequirement(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f,
                    "CyclicRequirement", __self_0, &__self_1),
            RequiredComponentsError::ArchetypeExists(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "ArchetypeExists", &__self_0),
        }
    }
}Debug)]
520#[non_exhaustive]
521pub enum RequiredComponentsError {
522    /// The component is already a directly required component for the requiree.
523    #[error("Component {0:?} already directly requires component {1:?}")]
524    DuplicateRegistration(ComponentId, ComponentId),
525    /// Adding the given requirement would create a cycle.
526    #[error("Cyclic requirement found: the requiree component {0:?} is required by the required component {1:?}")]
527    CyclicRequirement(ComponentId, ComponentId),
528    /// An archetype with the component that requires other components already exists
529    #[error("An archetype with the component {0:?} that requires other components already exists")]
530    ArchetypeExists(ComponentId),
531}
532
533pub(super) fn enforce_no_required_components_recursion(
534    components: &Components,
535    recursion_check_stack: &[ComponentId],
536    required: ComponentId,
537) {
538    if let Some(direct_recursion) = recursion_check_stack
539        .iter()
540        .position(|&id| id == required)
541        .map(|index| index == recursion_check_stack.len() - 1)
542    {
543        {
    ::core::panicking::panic_fmt(format_args!("Recursive required components detected: {0}\nhelp: {1}",
            recursion_check_stack.iter().map(|id|
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("{0}",
                                            components.get_name(*id).unwrap().shortname()))
                                })).collect::<Vec<_>>().join(" → "),
            if direct_recursion {
                ::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("Remove require({0}).",
                                components.get_name(required).unwrap().shortname()))
                    })
            } else {
                "If this is intentional, consider merging the components.".into()
            }));
};panic!(
544            "Recursive required components detected: {}\nhelp: {}",
545            recursion_check_stack
546                .iter()
547                .map(|id| format!("{}", components.get_name(*id).unwrap().shortname()))
548                .collect::<Vec<_>>()
549                .join(" → "),
550            if direct_recursion {
551                format!(
552                    "Remove require({}).",
553                    components.get_name(required).unwrap().shortname()
554                )
555            } else {
556                "If this is intentional, consider merging the components.".into()
557            }
558        );
559    }
560}
561
562/// This is a safe handle around `ComponentsRegistrator` and `RequiredComponents` to register required components.
563pub struct RequiredComponentsRegistrator<'a, 'w> {
564    components: &'a mut ComponentsRegistrator<'w>,
565    required_components: &'a mut RequiredComponents,
566}
567
568impl<'a, 'w> RequiredComponentsRegistrator<'a, 'w> {
569    /// # Safety
570    ///
571    /// All components in `required_components` must have been registered in `components`
572    pub(super) unsafe fn new(
573        components: &'a mut ComponentsRegistrator<'w>,
574        required_components: &'a mut RequiredComponents,
575    ) -> Self {
576        Self {
577            components,
578            required_components,
579        }
580    }
581
582    /// Provides access to the current [`World`](crate::world::World)'s [`ComponentsRegistrator`]
583    pub fn components_registrator(&mut self) -> &mut ComponentsRegistrator<'w> {
584        self.components
585    }
586
587    /// Registers the [`Component`] `C` as an explicitly required component.
588    ///
589    /// If the component was not already registered as an explicit required component then it is added
590    /// as one, potentially overriding the constructor of a inherited required component, otherwise panics.
591    pub fn register_required<C: Component>(&mut self, constructor: impl Fn() -> C + 'static) {
592        // SAFETY: we internally guarantee that all components in `required_components`
593        // are registered in `components`
594        unsafe {
595            self.required_components
596                .register(self.components, constructor);
597        }
598    }
599
600    /// Registers the [`Component`] with the given `component_id` ID as an explicitly required component.
601    ///
602    /// If the component was not already registered as an explicit required component then it is added
603    /// as one, potentially overriding the constructor of a inherited required component, otherwise panics.
604    ///
605    /// # Safety
606    ///
607    /// `component_id` must be a valid [`ComponentId`] for `C` in the [`Components`] instance of `self`.
608    pub unsafe fn register_required_by_id<C: Component>(
609        &mut self,
610        component_id: ComponentId,
611        constructor: fn() -> C,
612    ) {
613        // SAFETY:
614        // - the caller guarantees `component_id` is a valid component in `components` for `C`;
615        // - we internally guarantee all other components in `required_components` are registered in `components`.
616        unsafe {
617            self.required_components.register_by_id::<C>(
618                component_id,
619                self.components,
620                constructor,
621            );
622        }
623    }
624
625    /// Registers the [`Component`] with the given `component_id` ID as an explicitly required component.
626    ///
627    /// If the component was not already registered as an explicit required component then it is added
628    /// as one, potentially overriding the constructor of a inherited required component, otherwise panics.
629    ///
630    /// # Safety
631    ///
632    /// - `component_id` must be valid in the [`Components`] instance of `self`;
633    /// - `constructor` must return a [`RequiredComponentConstructor`] that constructs a valid instance for the
634    ///   component with ID `component_id`.
635    pub unsafe fn register_required_dynamic_with(
636        &mut self,
637        component_id: ComponentId,
638        constructor: impl FnOnce() -> RequiredComponentConstructor,
639    ) {
640        // SAFETY:
641        // - the caller guarantees `component_id` is valid in `components`;
642        // - the caller guarantees `constructor` returns a valid constructor for `component_id`;
643        // - we internally guarantee all other components in `required_components` are registered in `components`.
644        unsafe {
645            self.required_components.register_dynamic_with(
646                component_id,
647                self.components,
648                constructor,
649            );
650        }
651    }
652}
653
654#[cfg(test)]
655mod tests {
656    use alloc::string::{String, ToString};
657
658    use crate::{
659        bundle::Bundle,
660        component::{Component, RequiredComponentsError},
661        prelude::Resource,
662        world::World,
663    };
664
665    #[test]
666    fn required_components() {
667        #[derive(Component)]
668        #[require(Y)]
669        struct X;
670
671        #[derive(Component)]
672        #[require(Z = new_z())]
673        struct Y {
674            value: String,
675        }
676
677        #[derive(Component)]
678        struct Z(u32);
679
680        impl Default for Y {
681            fn default() -> Self {
682                Self {
683                    value: "hello".to_string(),
684                }
685            }
686        }
687
688        fn new_z() -> Z {
689            Z(7)
690        }
691
692        let mut world = World::new();
693        let id = world.spawn(X).id();
694        assert_eq!(
695            "hello",
696            world.entity(id).get::<Y>().unwrap().value,
697            "Y should have the default value"
698        );
699        assert_eq!(
700            7,
701            world.entity(id).get::<Z>().unwrap().0,
702            "Z should have the value provided by the constructor defined in Y"
703        );
704
705        let id = world
706            .spawn((
707                X,
708                Y {
709                    value: "foo".to_string(),
710                },
711            ))
712            .id();
713        assert_eq!(
714            "foo",
715            world.entity(id).get::<Y>().unwrap().value,
716            "Y should have the manually provided value"
717        );
718        assert_eq!(
719            7,
720            world.entity(id).get::<Z>().unwrap().0,
721            "Z should have the value provided by the constructor defined in Y"
722        );
723
724        let id = world.spawn((X, Z(8))).id();
725        assert_eq!(
726            "hello",
727            world.entity(id).get::<Y>().unwrap().value,
728            "Y should have the default value"
729        );
730        assert_eq!(
731            8,
732            world.entity(id).get::<Z>().unwrap().0,
733            "Z should have the manually provided value"
734        );
735    }
736
737    #[test]
738    fn generic_required_components() {
739        #[derive(Component)]
740        #[require(Y<usize>)]
741        struct X;
742
743        #[derive(Component, Default)]
744        struct Y<T> {
745            value: T,
746        }
747
748        let mut world = World::new();
749        let id = world.spawn(X).id();
750        assert_eq!(
751            0,
752            world.entity(id).get::<Y<usize>>().unwrap().value,
753            "Y should have the default value"
754        );
755    }
756
757    #[test]
758    fn required_components_spawn_nonexistent_hooks() {
759        #[derive(Component)]
760        #[require(Y)]
761        struct X;
762
763        #[derive(Component, Default)]
764        struct Y;
765
766        #[derive(Resource)]
767        struct A(usize);
768
769        #[derive(Resource)]
770        struct I(usize);
771
772        let mut world = World::new();
773        world.insert_resource(A(0));
774        world.insert_resource(I(0));
775        world
776            .register_component_hooks::<Y>()
777            .on_add(|mut world, _| world.resource_mut::<A>().0 += 1)
778            .on_insert(|mut world, _| world.resource_mut::<I>().0 += 1);
779
780        // Spawn entity and ensure Y was added
781        assert!(world.spawn(X).contains::<Y>());
782
783        assert_eq!(world.resource::<A>().0, 1);
784        assert_eq!(world.resource::<I>().0, 1);
785    }
786
787    #[test]
788    fn required_components_insert_existing_hooks() {
789        #[derive(Component)]
790        #[require(Y)]
791        struct X;
792
793        #[derive(Component, Default)]
794        struct Y;
795
796        #[derive(Resource)]
797        struct A(usize);
798
799        #[derive(Resource)]
800        struct I(usize);
801
802        let mut world = World::new();
803        world.insert_resource(A(0));
804        world.insert_resource(I(0));
805        world
806            .register_component_hooks::<Y>()
807            .on_add(|mut world, _| world.resource_mut::<A>().0 += 1)
808            .on_insert(|mut world, _| world.resource_mut::<I>().0 += 1);
809
810        // Spawn entity and ensure Y was added
811        assert!(world.spawn_empty().insert(X).contains::<Y>());
812
813        assert_eq!(world.resource::<A>().0, 1);
814        assert_eq!(world.resource::<I>().0, 1);
815    }
816
817    #[test]
818    fn required_components_take_leaves_required() {
819        #[derive(Component)]
820        #[require(Y)]
821        struct X;
822
823        #[derive(Component, Default)]
824        struct Y;
825
826        let mut world = World::new();
827        let e = world.spawn(X).id();
828        let _ = world.entity_mut(e).take::<X>().unwrap();
829        assert!(world.entity_mut(e).contains::<Y>());
830    }
831
832    #[test]
833    fn required_components_retain_keeps_required() {
834        #[derive(Component)]
835        #[require(Y)]
836        struct X;
837
838        #[derive(Component, Default)]
839        struct Y;
840
841        #[derive(Component, Default)]
842        struct Z;
843
844        let mut world = World::new();
845        let e = world.spawn((X, Z)).id();
846        world.entity_mut(e).retain::<X>();
847        assert!(world.entity_mut(e).contains::<X>());
848        assert!(world.entity_mut(e).contains::<Y>());
849        assert!(!world.entity_mut(e).contains::<Z>());
850    }
851
852    #[test]
853    fn required_components_spawn_then_insert_no_overwrite() {
854        #[derive(Component)]
855        #[require(Y)]
856        struct X;
857
858        #[derive(Component, Default)]
859        struct Y(usize);
860
861        let mut world = World::new();
862        let id = world.spawn((X, Y(10))).id();
863        world.entity_mut(id).insert(X);
864
865        assert_eq!(
866            10,
867            world.entity(id).get::<Y>().unwrap().0,
868            "Y should still have the manually provided value"
869        );
870    }
871
872    #[test]
873    fn dynamic_required_components() {
874        #[derive(Component)]
875        #[require(Y)]
876        struct X;
877
878        #[derive(Component, Default)]
879        struct Y;
880
881        let mut world = World::new();
882        let x_id = world.register_component::<X>();
883
884        let mut e = world.spawn_empty();
885
886        // SAFETY: x_id is a valid component id
887        bevy_ptr::OwningPtr::make(X, |ptr| unsafe {
888            e.insert_by_id(x_id, ptr);
889        });
890
891        assert!(e.contains::<Y>());
892    }
893
894    #[test]
895    fn remove_component_and_its_runtime_required_components() {
896        #[derive(Component)]
897        struct X;
898
899        #[derive(Component, Default)]
900        struct Y;
901
902        #[derive(Component, Default)]
903        struct Z;
904
905        #[derive(Component)]
906        struct V;
907
908        let mut world = World::new();
909        world.register_required_components::<X, Y>();
910        world.register_required_components::<Y, Z>();
911
912        let e = world.spawn((X, V)).id();
913        assert!(world.entity(e).contains::<X>());
914        assert!(world.entity(e).contains::<Y>());
915        assert!(world.entity(e).contains::<Z>());
916        assert!(world.entity(e).contains::<V>());
917
918        //check that `remove` works as expected
919        world.entity_mut(e).remove::<X>();
920        assert!(!world.entity(e).contains::<X>());
921        assert!(world.entity(e).contains::<Y>());
922        assert!(world.entity(e).contains::<Z>());
923        assert!(world.entity(e).contains::<V>());
924
925        world.entity_mut(e).insert(X);
926        assert!(world.entity(e).contains::<X>());
927        assert!(world.entity(e).contains::<Y>());
928        assert!(world.entity(e).contains::<Z>());
929        assert!(world.entity(e).contains::<V>());
930
931        //remove `X` again and ensure that `Y` and `Z` was removed too
932        world.entity_mut(e).remove_with_requires::<X>();
933        assert!(!world.entity(e).contains::<X>());
934        assert!(!world.entity(e).contains::<Y>());
935        assert!(!world.entity(e).contains::<Z>());
936        assert!(world.entity(e).contains::<V>());
937    }
938
939    #[test]
940    fn remove_component_and_its_required_components() {
941        #[derive(Component)]
942        #[require(Y)]
943        struct X;
944
945        #[derive(Component, Default)]
946        #[require(Z)]
947        struct Y;
948
949        #[derive(Component, Default)]
950        struct Z;
951
952        #[derive(Component)]
953        struct V;
954
955        let mut world = World::new();
956
957        let e = world.spawn((X, V)).id();
958        assert!(world.entity(e).contains::<X>());
959        assert!(world.entity(e).contains::<Y>());
960        assert!(world.entity(e).contains::<Z>());
961        assert!(world.entity(e).contains::<V>());
962
963        //check that `remove` works as expected
964        world.entity_mut(e).remove::<X>();
965        assert!(!world.entity(e).contains::<X>());
966        assert!(world.entity(e).contains::<Y>());
967        assert!(world.entity(e).contains::<Z>());
968        assert!(world.entity(e).contains::<V>());
969
970        world.entity_mut(e).insert(X);
971        assert!(world.entity(e).contains::<X>());
972        assert!(world.entity(e).contains::<Y>());
973        assert!(world.entity(e).contains::<Z>());
974        assert!(world.entity(e).contains::<V>());
975
976        //remove `X` again and ensure that `Y` and `Z` was removed too
977        world.entity_mut(e).remove_with_requires::<X>();
978        assert!(!world.entity(e).contains::<X>());
979        assert!(!world.entity(e).contains::<Y>());
980        assert!(!world.entity(e).contains::<Z>());
981        assert!(world.entity(e).contains::<V>());
982    }
983
984    #[test]
985    fn remove_bundle_and_his_required_components() {
986        #[derive(Component, Default)]
987        #[require(Y)]
988        struct X;
989
990        #[derive(Component, Default)]
991        struct Y;
992
993        #[derive(Component, Default)]
994        #[require(W)]
995        struct Z;
996
997        #[derive(Component, Default)]
998        struct W;
999
1000        #[derive(Component)]
1001        struct V;
1002
1003        #[derive(Bundle, Default)]
1004        struct TestBundle {
1005            x: X,
1006            z: Z,
1007        }
1008
1009        let mut world = World::new();
1010        let e = world.spawn((TestBundle::default(), V)).id();
1011
1012        assert!(world.entity(e).contains::<X>());
1013        assert!(world.entity(e).contains::<Y>());
1014        assert!(world.entity(e).contains::<Z>());
1015        assert!(world.entity(e).contains::<W>());
1016        assert!(world.entity(e).contains::<V>());
1017
1018        world.entity_mut(e).remove_with_requires::<TestBundle>();
1019        assert!(!world.entity(e).contains::<X>());
1020        assert!(!world.entity(e).contains::<Y>());
1021        assert!(!world.entity(e).contains::<Z>());
1022        assert!(!world.entity(e).contains::<W>());
1023        assert!(world.entity(e).contains::<V>());
1024    }
1025
1026    #[test]
1027    fn runtime_required_components() {
1028        // Same as `required_components` test but with runtime registration
1029
1030        #[derive(Component)]
1031        struct X;
1032
1033        #[derive(Component)]
1034        struct Y {
1035            value: String,
1036        }
1037
1038        #[derive(Component)]
1039        struct Z(u32);
1040
1041        impl Default for Y {
1042            fn default() -> Self {
1043                Self {
1044                    value: "hello".to_string(),
1045                }
1046            }
1047        }
1048
1049        let mut world = World::new();
1050
1051        world.register_required_components::<X, Y>();
1052        world.register_required_components_with::<Y, Z>(|| Z(7));
1053
1054        let id = world.spawn(X).id();
1055
1056        assert_eq!(
1057            "hello",
1058            world.entity(id).get::<Y>().unwrap().value,
1059            "Y should have the default value"
1060        );
1061        assert_eq!(
1062            7,
1063            world.entity(id).get::<Z>().unwrap().0,
1064            "Z should have the value provided by the constructor defined in Y"
1065        );
1066
1067        let id = world
1068            .spawn((
1069                X,
1070                Y {
1071                    value: "foo".to_string(),
1072                },
1073            ))
1074            .id();
1075        assert_eq!(
1076            "foo",
1077            world.entity(id).get::<Y>().unwrap().value,
1078            "Y should have the manually provided value"
1079        );
1080        assert_eq!(
1081            7,
1082            world.entity(id).get::<Z>().unwrap().0,
1083            "Z should have the value provided by the constructor defined in Y"
1084        );
1085
1086        let id = world.spawn((X, Z(8))).id();
1087        assert_eq!(
1088            "hello",
1089            world.entity(id).get::<Y>().unwrap().value,
1090            "Y should have the default value"
1091        );
1092        assert_eq!(
1093            8,
1094            world.entity(id).get::<Z>().unwrap().0,
1095            "Z should have the manually provided value"
1096        );
1097    }
1098
1099    #[test]
1100    fn runtime_required_components_override_1() {
1101        #[derive(Component)]
1102        struct X;
1103
1104        #[derive(Component, Default)]
1105        struct Y;
1106
1107        #[derive(Component)]
1108        struct Z(u32);
1109
1110        let mut world = World::new();
1111
1112        // - X requires Y with default constructor
1113        // - Y requires Z with custom constructor
1114        // - X requires Z with custom constructor (more specific than X -> Y -> Z)
1115        world.register_required_components::<X, Y>();
1116        world.register_required_components_with::<Y, Z>(|| Z(5));
1117        world.register_required_components_with::<X, Z>(|| Z(7));
1118
1119        let id = world.spawn(X).id();
1120
1121        assert_eq!(
1122            7,
1123            world.entity(id).get::<Z>().unwrap().0,
1124            "Z should have the value provided by the constructor defined in X"
1125        );
1126    }
1127
1128    #[test]
1129    fn runtime_required_components_override_2() {
1130        // Same as `runtime_required_components_override_1` test but with different registration order
1131
1132        #[derive(Component)]
1133        struct X;
1134
1135        #[derive(Component, Default)]
1136        struct Y;
1137
1138        #[derive(Component)]
1139        struct Z(u32);
1140
1141        let mut world = World::new();
1142
1143        // - X requires Y with default constructor
1144        // - X requires Z with custom constructor (more specific than X -> Y -> Z)
1145        // - Y requires Z with custom constructor
1146        world.register_required_components::<X, Y>();
1147        world.register_required_components_with::<X, Z>(|| Z(7));
1148        world.register_required_components_with::<Y, Z>(|| Z(5));
1149
1150        let id = world.spawn(X).id();
1151
1152        assert_eq!(
1153            7,
1154            world.entity(id).get::<Z>().unwrap().0,
1155            "Z should have the value provided by the constructor defined in X"
1156        );
1157    }
1158
1159    #[test]
1160    fn runtime_required_components_propagate_up() {
1161        // `A` requires `B` directly.
1162        #[derive(Component)]
1163        #[require(B)]
1164        struct A;
1165
1166        #[derive(Component, Default)]
1167        struct B;
1168
1169        #[derive(Component, Default)]
1170        struct C;
1171
1172        let mut world = World::new();
1173
1174        // `B` requires `C` with a runtime registration.
1175        // `A` should also require `C` because it requires `B`.
1176        world.register_required_components::<B, C>();
1177
1178        let id = world.spawn(A).id();
1179
1180        assert!(world.entity(id).get::<C>().is_some());
1181    }
1182
1183    #[test]
1184    fn runtime_required_components_propagate_up_even_more() {
1185        #[derive(Component)]
1186        struct A;
1187
1188        #[derive(Component, Default)]
1189        struct B;
1190
1191        #[derive(Component, Default)]
1192        struct C;
1193
1194        #[derive(Component, Default)]
1195        struct D;
1196
1197        let mut world = World::new();
1198
1199        world.register_required_components::<A, B>();
1200        world.register_required_components::<B, C>();
1201        world.register_required_components::<C, D>();
1202
1203        let id = world.spawn(A).id();
1204
1205        assert!(world.entity(id).get::<D>().is_some());
1206    }
1207
1208    #[test]
1209    fn runtime_required_components_deep_require_does_not_override_shallow_require() {
1210        #[derive(Component)]
1211        struct A;
1212        #[derive(Component, Default)]
1213        struct B;
1214        #[derive(Component, Default)]
1215        struct C;
1216        #[derive(Component)]
1217        struct Counter(i32);
1218        #[derive(Component, Default)]
1219        struct D;
1220
1221        let mut world = World::new();
1222
1223        world.register_required_components::<A, B>();
1224        world.register_required_components::<B, C>();
1225        world.register_required_components::<C, D>();
1226        world.register_required_components_with::<D, Counter>(|| Counter(2));
1227        // This should replace the require constructor in A since it is
1228        // shallower.
1229        world.register_required_components_with::<C, Counter>(|| Counter(1));
1230
1231        let id = world.spawn(A).id();
1232
1233        // The "shallower" of the two components is used.
1234        assert_eq!(world.entity(id).get::<Counter>().unwrap().0, 1);
1235    }
1236
1237    #[test]
1238    fn runtime_required_components_deep_require_does_not_override_shallow_require_deep_subtree_after_shallow(
1239    ) {
1240        #[derive(Component)]
1241        struct A;
1242        #[derive(Component, Default)]
1243        struct B;
1244        #[derive(Component, Default)]
1245        struct C;
1246        #[derive(Component, Default)]
1247        struct D;
1248        #[derive(Component, Default)]
1249        struct E;
1250        #[derive(Component)]
1251        struct Counter(i32);
1252        #[derive(Component, Default)]
1253        struct F;
1254
1255        let mut world = World::new();
1256
1257        world.register_required_components::<A, B>();
1258        world.register_required_components::<B, C>();
1259        world.register_required_components::<C, D>();
1260        world.register_required_components::<D, E>();
1261        world.register_required_components_with::<E, Counter>(|| Counter(1));
1262        world.register_required_components_with::<F, Counter>(|| Counter(2));
1263        world.register_required_components::<E, F>();
1264
1265        let id = world.spawn(A).id();
1266
1267        // The "shallower" of the two components is used.
1268        assert_eq!(world.entity(id).get::<Counter>().unwrap().0, 1);
1269    }
1270
1271    #[test]
1272    fn runtime_required_components_existing_archetype() {
1273        #[derive(Component)]
1274        struct X;
1275
1276        #[derive(Component, Default)]
1277        struct Y;
1278
1279        let mut world = World::new();
1280
1281        // Registering required components after the archetype has already been created should panic.
1282        // This may change in the future.
1283        world.spawn(X);
1284        assert!(matches!(
1285            world.try_register_required_components::<X, Y>(),
1286            Err(RequiredComponentsError::ArchetypeExists(_))
1287        ));
1288    }
1289
1290    #[test]
1291    fn runtime_required_components_fail_with_duplicate() {
1292        #[derive(Component)]
1293        #[require(Y)]
1294        struct X;
1295
1296        #[derive(Component, Default)]
1297        struct Y;
1298
1299        let mut world = World::new();
1300
1301        // This should fail: Tried to register Y as a requirement for X, but the requirement already exists.
1302        assert!(matches!(
1303            world.try_register_required_components::<X, Y>(),
1304            Err(RequiredComponentsError::DuplicateRegistration(_, _))
1305        ));
1306    }
1307
1308    #[test]
1309    fn required_components_bundle_priority() {
1310        #[derive(Component, PartialEq, Eq, Clone, Copy, Debug)]
1311        struct MyRequired(bool);
1312
1313        #[derive(Component, Default)]
1314        #[require(MyRequired(false))]
1315        struct MiddleMan;
1316
1317        #[derive(Component, Default)]
1318        #[require(MiddleMan)]
1319        struct ConflictingRequire;
1320
1321        #[derive(Component, Default)]
1322        #[require(MyRequired(true))]
1323        struct MyComponent;
1324
1325        let mut world = World::new();
1326        let order_a = world
1327            .spawn((ConflictingRequire, MyComponent))
1328            .get::<MyRequired>()
1329            .cloned();
1330        let order_b = world
1331            .spawn((MyComponent, ConflictingRequire))
1332            .get::<MyRequired>()
1333            .cloned();
1334
1335        assert_eq!(order_a, Some(MyRequired(false)));
1336        assert_eq!(order_b, Some(MyRequired(true)));
1337    }
1338
1339    #[test]
1340    #[should_panic]
1341    fn required_components_recursion_errors() {
1342        #[derive(Component, Default)]
1343        #[require(B)]
1344        struct A;
1345
1346        #[derive(Component, Default)]
1347        #[require(C)]
1348        struct B;
1349
1350        #[derive(Component, Default)]
1351        #[require(B)]
1352        struct C;
1353
1354        World::new().register_component::<A>();
1355    }
1356
1357    #[test]
1358    #[should_panic]
1359    fn required_components_self_errors() {
1360        #[derive(Component, Default)]
1361        #[require(A)]
1362        struct A;
1363
1364        World::new().register_component::<A>();
1365    }
1366
1367    #[test]
1368    fn regression_19333() {
1369        #[derive(Component)]
1370        struct X(usize);
1371
1372        #[derive(Default, Component)]
1373        #[require(X(0))]
1374        struct Base;
1375
1376        #[derive(Default, Component)]
1377        #[require(X(1), Base)]
1378        struct A;
1379
1380        #[derive(Default, Component)]
1381        #[require(A, Base)]
1382        struct B;
1383
1384        #[derive(Default, Component)]
1385        #[require(B, Base)]
1386        struct C;
1387
1388        let mut w = World::new();
1389
1390        assert_eq!(w.spawn(B).get::<X>().unwrap().0, 1);
1391        assert_eq!(w.spawn(C).get::<X>().unwrap().0, 1);
1392    }
1393
1394    #[test]
1395    fn required_components_depth_first_2v1() {
1396        #[derive(Component)]
1397        struct X(usize);
1398
1399        #[derive(Component)]
1400        #[require(Left, Right)]
1401        struct Root;
1402
1403        #[derive(Component, Default)]
1404        #[require(LeftLeft)]
1405        struct Left;
1406
1407        #[derive(Component, Default)]
1408        #[require(X(0))] // This is at depth 2 but is more on the left of the tree
1409        struct LeftLeft;
1410
1411        #[derive(Component, Default)]
1412        #[require(X(1))] //. This is at depth 1 but is more on the right of the tree
1413        struct Right;
1414
1415        let mut world = World::new();
1416
1417        // LeftLeft should have priority over Right
1418        assert_eq!(world.spawn(Root).get::<X>().unwrap().0, 0);
1419    }
1420
1421    #[test]
1422    fn required_components_depth_first_3v1() {
1423        #[derive(Component)]
1424        struct X(usize);
1425
1426        #[derive(Component)]
1427        #[require(Left, Right)]
1428        struct Root;
1429
1430        #[derive(Component, Default)]
1431        #[require(LeftLeft)]
1432        struct Left;
1433
1434        #[derive(Component, Default)]
1435        #[require(LeftLeftLeft)]
1436        struct LeftLeft;
1437
1438        #[derive(Component, Default)]
1439        #[require(X(0))] // This is at depth 3 but is more on the left of the tree
1440        struct LeftLeftLeft;
1441
1442        #[derive(Component, Default)]
1443        #[require(X(1))] //. This is at depth 1 but is more on the right of the tree
1444        struct Right;
1445
1446        let mut world = World::new();
1447
1448        // LeftLeftLeft should have priority over Right
1449        assert_eq!(world.spawn(Root).get::<X>().unwrap().0, 0);
1450    }
1451
1452    #[test]
1453    fn runtime_required_components_depth_first_2v1() {
1454        #[derive(Component)]
1455        struct X(usize);
1456
1457        #[derive(Component)]
1458        struct Root;
1459
1460        #[derive(Component, Default)]
1461        struct Left;
1462
1463        #[derive(Component, Default)]
1464        struct LeftLeft;
1465
1466        #[derive(Component, Default)]
1467        struct Right;
1468
1469        // Register bottom up: registering higher level components should pick up lower level ones.
1470        let mut world = World::new();
1471        world.register_required_components_with::<LeftLeft, X>(|| X(0));
1472        world.register_required_components_with::<Right, X>(|| X(1));
1473        world.register_required_components::<Left, LeftLeft>();
1474        world.register_required_components::<Root, Left>();
1475        world.register_required_components::<Root, Right>();
1476        assert_eq!(world.spawn(Root).get::<X>().unwrap().0, 0);
1477
1478        // Register top down: registering lower components should propagate to higher ones
1479        let mut world = World::new();
1480        world.register_required_components::<Root, Left>(); // Note: still register Left before Right
1481        world.register_required_components::<Root, Right>();
1482        world.register_required_components::<Left, LeftLeft>();
1483        world.register_required_components_with::<Right, X>(|| X(1));
1484        world.register_required_components_with::<LeftLeft, X>(|| X(0));
1485        assert_eq!(world.spawn(Root).get::<X>().unwrap().0, 0);
1486
1487        // Register top down again, but this time LeftLeft before Right
1488        let mut world = World::new();
1489        world.register_required_components::<Root, Left>();
1490        world.register_required_components::<Root, Right>();
1491        world.register_required_components::<Left, LeftLeft>();
1492        world.register_required_components_with::<LeftLeft, X>(|| X(0));
1493        world.register_required_components_with::<Right, X>(|| X(1));
1494        assert_eq!(world.spawn(Root).get::<X>().unwrap().0, 0);
1495    }
1496
1497    #[test]
1498    fn runtime_required_components_propagate_metadata_alternate() {
1499        #[derive(Component, Default)]
1500        #[require(L1)]
1501        struct L0;
1502
1503        #[derive(Component, Default)]
1504        struct L1;
1505
1506        #[derive(Component, Default)]
1507        #[require(L3)]
1508        struct L2;
1509
1510        #[derive(Component, Default)]
1511        struct L3;
1512
1513        #[derive(Component, Default)]
1514        #[require(L5)]
1515        struct L4;
1516
1517        #[derive(Component, Default)]
1518        struct L5;
1519
1520        // Try to piece the 3 requirements together
1521        let mut world = World::new();
1522        world.register_required_components::<L1, L2>();
1523        world.register_required_components::<L3, L4>();
1524        let e = world.spawn(L0).id();
1525        assert!(world
1526            .query::<(&L0, &L1, &L2, &L3, &L4, &L5)>()
1527            .get(&world, e)
1528            .is_ok());
1529
1530        // Repeat but in the opposite order
1531        let mut world = World::new();
1532        world.register_required_components::<L3, L4>();
1533        world.register_required_components::<L1, L2>();
1534        let e = world.spawn(L0).id();
1535        assert!(world
1536            .query::<(&L0, &L1, &L2, &L3, &L4, &L5)>()
1537            .get(&world, e)
1538            .is_ok());
1539    }
1540
1541    #[test]
1542    fn runtime_required_components_propagate_metadata_chain() {
1543        #[derive(Component, Default)]
1544        #[require(L1)]
1545        struct L0;
1546
1547        #[derive(Component, Default)]
1548        struct L1;
1549
1550        #[derive(Component, Default)]
1551        struct L2;
1552
1553        #[derive(Component, Default)]
1554        #[require(L4)]
1555        struct L3;
1556
1557        #[derive(Component, Default)]
1558        struct L4;
1559
1560        // Try to piece the 3 requirements together
1561        let mut world = World::new();
1562        world.register_required_components::<L1, L2>();
1563        world.register_required_components::<L2, L3>();
1564        let e = world.spawn(L0).id();
1565        assert!(world
1566            .query::<(&L0, &L1, &L2, &L3, &L4)>()
1567            .get(&world, e)
1568            .is_ok());
1569
1570        // Repeat but in the opposite order
1571        let mut world = World::new();
1572        world.register_required_components::<L2, L3>();
1573        world.register_required_components::<L1, L2>();
1574        let e = world.spawn(L0).id();
1575        assert!(world
1576            .query::<(&L0, &L1, &L2, &L3, &L4)>()
1577            .get(&world, e)
1578            .is_ok());
1579    }
1580
1581    #[test]
1582    fn runtime_required_components_cyclic() {
1583        #[derive(Component, Default)]
1584        #[require(B)]
1585        struct A;
1586
1587        #[derive(Component, Default)]
1588        struct B;
1589
1590        #[derive(Component, Default)]
1591        struct C;
1592
1593        let mut world = World::new();
1594
1595        assert!(world.try_register_required_components::<B, C>().is_ok());
1596        assert!(matches!(
1597            world.try_register_required_components::<C, A>(),
1598            Err(RequiredComponentsError::CyclicRequirement(_, _))
1599        ));
1600    }
1601}