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;
78use crate::{
9bundle::BundleInfo,
10 change_detection::{MaybeLocation, Tick},
11 component::{Component, ComponentId, Components, ComponentsRegistrator},
12entity::Entity,
13query::DebugCheckedUnwrapas _,
14 storage::{SparseSets, Table, TableRow},
15};
1617/// 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.
21pub constructor: RequiredComponentConstructor,
22}
2324/// 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.
28Arc<dyn Fn(&mut Table, &mut SparseSets, Tick, TableRow, Entity, MaybeLocation)>,
29);
3031impl 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`.
37pub unsafe fn new<C: Component>(
38 component_id: ComponentId,
39 constructor: impl Fn() -> C + 'static,
40 ) -> Self {
41RequiredComponentConstructor({
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
4748#[cfg(not(target_has_atomic = "ptr"))]
49use alloc::boxed::Box;
5051type Constructor = dyn for<'a, 'b> Fn(
52&'a mut Table,
53&'b mut SparseSets,
54Tick,
55TableRow,
56Entity,
57MaybeLocation,
58 );
5960#[cfg(not(target_has_atomic = "ptr"))]
61type Intermediate<T> = Box<T>;
6263#[cfg(target_has_atomic = "ptr")]
64type Intermediate<T> = Arc<T>;
6566let boxed: Intermediate<Constructor> = Intermediate::new(
67move |table, sparse_sets, change_tick, table_row, entity, caller| {
68OwningPtr::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`
73unsafe {
74BundleInfo::initialize_required_component(
75table,
76sparse_sets,
77change_tick,
78table_row,
79entity,
80component_id,
81 C::STORAGE_TYPE,
82ptr,
83caller,
84 );
85 }
86 });
87 },
88 );
8990Arc::from(boxed)
91 })
92 }
9394/// # 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`].
103pub(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}
115116/// 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.
125pub(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.
134pub(crate) all: IndexMap<ComponentId, RequiredComponent, FixedHasher>,
135}
136137impl Debugfor RequiredComponents {
138fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
139f.debug_struct("RequiredComponents")
140 .field("direct", &self.direct.keys())
141 .field("all", &self.all.keys())
142 .finish()
143 }
144}
145146impl 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`.
155unsafe fn register<C: Component>(
156&mut self,
157 components: &mut ComponentsRegistrator<'_>,
158 constructor: impl Fn() -> C + 'static,
159 ) {
160let 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`.
164unsafe { self.register_by_id::<C>(id, components, constructor) };
165 }
166167/// 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`.
176unsafe 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`.
183let constructor =
184 || unsafe { RequiredComponentConstructor::new(component_id, constructor) };
185186// 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`.
190unsafe { self.register_dynamic_with(component_id, components, constructor) };
191 }
192193/// 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`.
204unsafe 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.
211let 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 };
216217// Insert into `direct`.
218let constructor = constructor();
219let required_component = RequiredComponent { constructor };
220entry.insert(required_component.clone());
221222// 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`.
226unsafe {
227Self::register_inherited_required_components_unchecked(
228&mut self.all,
229component_id,
230required_component,
231components,
232 );
233 }
234 }
235236/// Rebuild the `all` list
237 ///
238 /// # Safety
239 ///
240 /// - all components in `self` must have been registered in `components`.
241unsafe fn rebuild_inherited_required_components(&mut self, components: &Components) {
242// Clear `all`, we are re-initializing it.
243self.all.clear();
244245// Register all inherited components as if we just registered all components in `direct` one-by-one.
246for (&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.
251unsafe {
252Self::register_inherited_required_components_unchecked(
253&mut self.all,
254 required_id,
255 required_component.clone(),
256 components,
257 );
258 }
259 }
260 }
261262/// 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`.
269unsafe 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`.
276let info = unsafe { components.get_info(required_id).debug_checked_unwrap() };
277278// 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.
282if !all.contains_key(&required_id) {
283for (&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.
291all.entry(inherited_id)
292 .or_insert_with(|| inherited_required.clone());
293 }
294 }
295296// 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`.
303all.insert(required_id, required_component);
304 }
305306/// Iterates the ids of all required components. This includes recursive required components.
307pub fn iter_ids(&self) -> impl Iterator<Item = ComponentId> + '_ {
308self.all.keys().copied()
309 }
310}
311312impl 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`.
320pub(crate) unsafe fn register_required_by(
321&mut self,
322 requiree: ComponentId,
323 required_components: &RequiredComponents,
324 ) {
325for &required in required_components.all.keys() {
326// SAFETY: the caller guarantees that all components in `required_components` have been registered in `self`.
327let 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.
332required_by.insert(requiree);
333 }
334 }
335336/// 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.
356pub(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.
363364 // SAFETY: The caller ensures that the `required` is valid.
365let required_required_components = unsafe {
366self.get_required_components(required)
367 .debug_checked_unwrap()
368 };
369370// Cannot create cyclic requirements.
371if required_required_components.all.contains_key(&requiree) {
372return Err(RequiredComponentsError::CyclicRequirement(
373requiree, required,
374 ));
375 }
376377// SAFETY: The caller ensures that the `requiree` is valid.
378let required_components = unsafe {
379self.get_required_components_mut(requiree)
380 .debug_checked_unwrap()
381 };
382383// Cannot directly require the same component twice.
384if required_components.direct.contains_key(&required) {
385return Err(RequiredComponentsError::DuplicateRegistration(
386requiree, required,
387 ));
388 }
389390// Second step: register the single requirement requiree->required
391392 // Store the old count of (all) required components. This will help determine which ones are new.
393let old_required_count = required_components.all.len();
394395// SAFETY: the caller guarantees that `requiree` is valid in `self`.
396unsafe {
397self.required_components_scope(requiree, |this, required_components| {
398// SAFETY: the caller guarantees that `required` is valid for type `R` in `self`
399required_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.
403404 // Borrow again otherwise it conflicts with the `self.required_components_scope` call.
405 // SAFETY: The caller ensures that the `requiree` is valid.
406let required_components = unsafe {
407self.get_required_components_mut(requiree)
408 .debug_checked_unwrap()
409 };
410411// 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`
416let new_required_components = required_components.all[old_required_count..]
417 .keys()
418 .copied()
419 .collect::<Vec<_>>();
420421// 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.
423let requiree_required_by = unsafe { self.get_required_by(requiree).debug_checked_unwrap() };
424let new_requiree_components = [requiree]
425 .into_iter()
426 .chain(requiree_required_by.iter().copied())
427 .collect::<IndexSet<_, FixedHasher>>();
428429// 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.
437438 // Update the inherited required components of all requiree components (directly or indirectly).
439 // Skip the first one (requiree) because we already updates it.
440for &indirect_requiree in &new_requiree_components[1..] {
441// SAFETY: `indirect_requiree` comes from `self` so it must be valid.
442unsafe {
443self.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`.
446required_components.rebuild_inherited_required_components(this);
447 });
448 }
449 }
450451// Update the `required_by` of all the components that were newly required (directly or indirectly).
452for &indirect_required in &new_required_components {
453// SAFETY: `indirect_required` comes from `self`, so it must be valid.
454let required_by = unsafe {
455self.get_required_by_mut(indirect_required)
456 .debug_checked_unwrap()
457 };
458459// 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`.
464required_by.retain(|id| !new_requiree_components.contains(id));
465 required_by.extend(&new_requiree_components);
466 }
467468Ok(())
469 }
470471/// 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`
477unsafe fn required_components_scope<R>(
478&mut self,
479 component_id: ComponentId,
480 f: impl FnOnce(&mut Self, &mut RequiredComponents) -> R,
481 ) -> R {
482struct DropGuard<'a> {
483 components: &'a mut Components,
484 component_id: ComponentId,
485 required_components: RequiredComponents,
486 }
487488impl Dropfor DropGuard<'_> {
489fn drop(&mut self) {
490// SAFETY: The caller ensures that the `component_id` is valid.
491let required_components = unsafe {
492self.components
493 .get_required_components_mut(self.component_id)
494 .debug_checked_unwrap()
495 };
496497if true {
if !required_components.direct.is_empty() {
::core::panicking::panic("assertion failed: required_components.direct.is_empty()")
};
};debug_assert!(required_components.direct.is_empty());
498if true {
if !required_components.all.is_empty() {
::core::panicking::panic("assertion failed: required_components.all.is_empty()")
};
};debug_assert!(required_components.all.is_empty());
499500*required_components = core::mem::take(&mut self.required_components);
501 }
502 }
503504let mut guard = DropGuard {
505component_id,
506// SAFETY: The caller ensures that the `component_id` is valid.
507required_components: core::mem::take(unsafe {
508self.get_required_components_mut(component_id)
509 .debug_checked_unwrap()
510 }),
511 components: self,
512 };
513514f(guard.components, &mut guard.required_components)
515 }
516}
517518/// 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:?}")]
524DuplicateRegistration(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:?}")]
527CyclicRequirement(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")]
530ArchetypeExists(ComponentId),
531}
532533pub(super) fn enforce_no_required_components_recursion(
534 components: &Components,
535 recursion_check_stack: &[ComponentId],
536 required: ComponentId,
537) {
538if let Some(direct_recursion) = recursion_check_stack539 .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(" → "),
550if direct_recursion {
551format!(
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}
561562/// 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}
567568impl<'a, 'w> RequiredComponentsRegistrator<'a, 'w> {
569/// # Safety
570 ///
571 /// All components in `required_components` must have been registered in `components`
572pub(super) unsafe fn new(
573 components: &'a mut ComponentsRegistrator<'w>,
574 required_components: &'a mut RequiredComponents,
575 ) -> Self {
576Self {
577components,
578required_components,
579 }
580 }
581582/// Provides access to the current [`World`](crate::world::World)'s [`ComponentsRegistrator`]
583pub fn components_registrator(&mut self) -> &mut ComponentsRegistrator<'w> {
584self.components
585 }
586587/// 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.
591pub 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`
594unsafe {
595self.required_components
596 .register(self.components, constructor);
597 }
598 }
599600/// 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`.
608pub 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`.
616unsafe {
617self.required_components.register_by_id::<C>(
618component_id,
619self.components,
620constructor,
621 );
622 }
623 }
624625/// 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`.
635pub 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`.
644unsafe {
645self.required_components.register_dynamic_with(
646component_id,
647self.components,
648constructor,
649 );
650 }
651 }
652}
653654#[cfg(test)]
655mod tests {
656use alloc::string::{String, ToString};
657658use crate::{
659 bundle::Bundle,
660 component::{Component, RequiredComponentsError},
661 prelude::Resource,
662 world::World,
663 };
664665#[test]
666fn required_components() {
667#[derive(Component)]
668 #[require(Y)]
669struct X;
670671#[derive(Component)]
672 #[require(Z = new_z())]
673struct Y {
674 value: String,
675 }
676677#[derive(Component)]
678struct Z(u32);
679680impl Default for Y {
681fn default() -> Self {
682Self {
683 value: "hello".to_string(),
684 }
685 }
686 }
687688fn new_z() -> Z {
689 Z(7)
690 }
691692let mut world = World::new();
693let id = world.spawn(X).id();
694assert_eq!(
695"hello",
696 world.entity(id).get::<Y>().unwrap().value,
697"Y should have the default value"
698);
699assert_eq!(
7007,
701 world.entity(id).get::<Z>().unwrap().0,
702"Z should have the value provided by the constructor defined in Y"
703);
704705let id = world
706 .spawn((
707 X,
708 Y {
709 value: "foo".to_string(),
710 },
711 ))
712 .id();
713assert_eq!(
714"foo",
715 world.entity(id).get::<Y>().unwrap().value,
716"Y should have the manually provided value"
717);
718assert_eq!(
7197,
720 world.entity(id).get::<Z>().unwrap().0,
721"Z should have the value provided by the constructor defined in Y"
722);
723724let id = world.spawn((X, Z(8))).id();
725assert_eq!(
726"hello",
727 world.entity(id).get::<Y>().unwrap().value,
728"Y should have the default value"
729);
730assert_eq!(
7318,
732 world.entity(id).get::<Z>().unwrap().0,
733"Z should have the manually provided value"
734);
735 }
736737#[test]
738fn generic_required_components() {
739#[derive(Component)]
740 #[require(Y<usize>)]
741struct X;
742743#[derive(Component, Default)]
744struct Y<T> {
745 value: T,
746 }
747748let mut world = World::new();
749let id = world.spawn(X).id();
750assert_eq!(
7510,
752 world.entity(id).get::<Y<usize>>().unwrap().value,
753"Y should have the default value"
754);
755 }
756757#[test]
758fn required_components_spawn_nonexistent_hooks() {
759#[derive(Component)]
760 #[require(Y)]
761struct X;
762763#[derive(Component, Default)]
764struct Y;
765766#[derive(Resource)]
767struct A(usize);
768769#[derive(Resource)]
770struct I(usize);
771772let 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);
779780// Spawn entity and ensure Y was added
781assert!(world.spawn(X).contains::<Y>());
782783assert_eq!(world.resource::<A>().0, 1);
784assert_eq!(world.resource::<I>().0, 1);
785 }
786787#[test]
788fn required_components_insert_existing_hooks() {
789#[derive(Component)]
790 #[require(Y)]
791struct X;
792793#[derive(Component, Default)]
794struct Y;
795796#[derive(Resource)]
797struct A(usize);
798799#[derive(Resource)]
800struct I(usize);
801802let 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);
809810// Spawn entity and ensure Y was added
811assert!(world.spawn_empty().insert(X).contains::<Y>());
812813assert_eq!(world.resource::<A>().0, 1);
814assert_eq!(world.resource::<I>().0, 1);
815 }
816817#[test]
818fn required_components_take_leaves_required() {
819#[derive(Component)]
820 #[require(Y)]
821struct X;
822823#[derive(Component, Default)]
824struct Y;
825826let mut world = World::new();
827let e = world.spawn(X).id();
828let _ = world.entity_mut(e).take::<X>().unwrap();
829assert!(world.entity_mut(e).contains::<Y>());
830 }
831832#[test]
833fn required_components_retain_keeps_required() {
834#[derive(Component)]
835 #[require(Y)]
836struct X;
837838#[derive(Component, Default)]
839struct Y;
840841#[derive(Component, Default)]
842struct Z;
843844let mut world = World::new();
845let e = world.spawn((X, Z)).id();
846 world.entity_mut(e).retain::<X>();
847assert!(world.entity_mut(e).contains::<X>());
848assert!(world.entity_mut(e).contains::<Y>());
849assert!(!world.entity_mut(e).contains::<Z>());
850 }
851852#[test]
853fn required_components_spawn_then_insert_no_overwrite() {
854#[derive(Component)]
855 #[require(Y)]
856struct X;
857858#[derive(Component, Default)]
859struct Y(usize);
860861let mut world = World::new();
862let id = world.spawn((X, Y(10))).id();
863 world.entity_mut(id).insert(X);
864865assert_eq!(
86610,
867 world.entity(id).get::<Y>().unwrap().0,
868"Y should still have the manually provided value"
869);
870 }
871872#[test]
873fn dynamic_required_components() {
874#[derive(Component)]
875 #[require(Y)]
876struct X;
877878#[derive(Component, Default)]
879struct Y;
880881let mut world = World::new();
882let x_id = world.register_component::<X>();
883884let mut e = world.spawn_empty();
885886// SAFETY: x_id is a valid component id
887bevy_ptr::OwningPtr::make(X, |ptr| unsafe {
888 e.insert_by_id(x_id, ptr);
889 });
890891assert!(e.contains::<Y>());
892 }
893894#[test]
895fn remove_component_and_its_runtime_required_components() {
896#[derive(Component)]
897struct X;
898899#[derive(Component, Default)]
900struct Y;
901902#[derive(Component, Default)]
903struct Z;
904905#[derive(Component)]
906struct V;
907908let mut world = World::new();
909 world.register_required_components::<X, Y>();
910 world.register_required_components::<Y, Z>();
911912let e = world.spawn((X, V)).id();
913assert!(world.entity(e).contains::<X>());
914assert!(world.entity(e).contains::<Y>());
915assert!(world.entity(e).contains::<Z>());
916assert!(world.entity(e).contains::<V>());
917918//check that `remove` works as expected
919world.entity_mut(e).remove::<X>();
920assert!(!world.entity(e).contains::<X>());
921assert!(world.entity(e).contains::<Y>());
922assert!(world.entity(e).contains::<Z>());
923assert!(world.entity(e).contains::<V>());
924925 world.entity_mut(e).insert(X);
926assert!(world.entity(e).contains::<X>());
927assert!(world.entity(e).contains::<Y>());
928assert!(world.entity(e).contains::<Z>());
929assert!(world.entity(e).contains::<V>());
930931//remove `X` again and ensure that `Y` and `Z` was removed too
932world.entity_mut(e).remove_with_requires::<X>();
933assert!(!world.entity(e).contains::<X>());
934assert!(!world.entity(e).contains::<Y>());
935assert!(!world.entity(e).contains::<Z>());
936assert!(world.entity(e).contains::<V>());
937 }
938939#[test]
940fn remove_component_and_its_required_components() {
941#[derive(Component)]
942 #[require(Y)]
943struct X;
944945#[derive(Component, Default)]
946 #[require(Z)]
947struct Y;
948949#[derive(Component, Default)]
950struct Z;
951952#[derive(Component)]
953struct V;
954955let mut world = World::new();
956957let e = world.spawn((X, V)).id();
958assert!(world.entity(e).contains::<X>());
959assert!(world.entity(e).contains::<Y>());
960assert!(world.entity(e).contains::<Z>());
961assert!(world.entity(e).contains::<V>());
962963//check that `remove` works as expected
964world.entity_mut(e).remove::<X>();
965assert!(!world.entity(e).contains::<X>());
966assert!(world.entity(e).contains::<Y>());
967assert!(world.entity(e).contains::<Z>());
968assert!(world.entity(e).contains::<V>());
969970 world.entity_mut(e).insert(X);
971assert!(world.entity(e).contains::<X>());
972assert!(world.entity(e).contains::<Y>());
973assert!(world.entity(e).contains::<Z>());
974assert!(world.entity(e).contains::<V>());
975976//remove `X` again and ensure that `Y` and `Z` was removed too
977world.entity_mut(e).remove_with_requires::<X>();
978assert!(!world.entity(e).contains::<X>());
979assert!(!world.entity(e).contains::<Y>());
980assert!(!world.entity(e).contains::<Z>());
981assert!(world.entity(e).contains::<V>());
982 }
983984#[test]
985fn remove_bundle_and_his_required_components() {
986#[derive(Component, Default)]
987 #[require(Y)]
988struct X;
989990#[derive(Component, Default)]
991struct Y;
992993#[derive(Component, Default)]
994 #[require(W)]
995struct Z;
996997#[derive(Component, Default)]
998struct W;
9991000#[derive(Component)]
1001struct V;
10021003#[derive(Bundle, Default)]
1004struct TestBundle {
1005 x: X,
1006 z: Z,
1007 }
10081009let mut world = World::new();
1010let e = world.spawn((TestBundle::default(), V)).id();
10111012assert!(world.entity(e).contains::<X>());
1013assert!(world.entity(e).contains::<Y>());
1014assert!(world.entity(e).contains::<Z>());
1015assert!(world.entity(e).contains::<W>());
1016assert!(world.entity(e).contains::<V>());
10171018 world.entity_mut(e).remove_with_requires::<TestBundle>();
1019assert!(!world.entity(e).contains::<X>());
1020assert!(!world.entity(e).contains::<Y>());
1021assert!(!world.entity(e).contains::<Z>());
1022assert!(!world.entity(e).contains::<W>());
1023assert!(world.entity(e).contains::<V>());
1024 }
10251026#[test]
1027fn runtime_required_components() {
1028// Same as `required_components` test but with runtime registration
10291030#[derive(Component)]
1031struct X;
10321033#[derive(Component)]
1034struct Y {
1035 value: String,
1036 }
10371038#[derive(Component)]
1039struct Z(u32);
10401041impl Default for Y {
1042fn default() -> Self {
1043Self {
1044 value: "hello".to_string(),
1045 }
1046 }
1047 }
10481049let mut world = World::new();
10501051 world.register_required_components::<X, Y>();
1052 world.register_required_components_with::<Y, Z>(|| Z(7));
10531054let id = world.spawn(X).id();
10551056assert_eq!(
1057"hello",
1058 world.entity(id).get::<Y>().unwrap().value,
1059"Y should have the default value"
1060);
1061assert_eq!(
10627,
1063 world.entity(id).get::<Z>().unwrap().0,
1064"Z should have the value provided by the constructor defined in Y"
1065);
10661067let id = world
1068 .spawn((
1069 X,
1070 Y {
1071 value: "foo".to_string(),
1072 },
1073 ))
1074 .id();
1075assert_eq!(
1076"foo",
1077 world.entity(id).get::<Y>().unwrap().value,
1078"Y should have the manually provided value"
1079);
1080assert_eq!(
10817,
1082 world.entity(id).get::<Z>().unwrap().0,
1083"Z should have the value provided by the constructor defined in Y"
1084);
10851086let id = world.spawn((X, Z(8))).id();
1087assert_eq!(
1088"hello",
1089 world.entity(id).get::<Y>().unwrap().value,
1090"Y should have the default value"
1091);
1092assert_eq!(
10938,
1094 world.entity(id).get::<Z>().unwrap().0,
1095"Z should have the manually provided value"
1096);
1097 }
10981099#[test]
1100fn runtime_required_components_override_1() {
1101#[derive(Component)]
1102struct X;
11031104#[derive(Component, Default)]
1105struct Y;
11061107#[derive(Component)]
1108struct Z(u32);
11091110let mut world = World::new();
11111112// - 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)
1115world.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));
11181119let id = world.spawn(X).id();
11201121assert_eq!(
11227,
1123 world.entity(id).get::<Z>().unwrap().0,
1124"Z should have the value provided by the constructor defined in X"
1125);
1126 }
11271128#[test]
1129fn runtime_required_components_override_2() {
1130// Same as `runtime_required_components_override_1` test but with different registration order
11311132#[derive(Component)]
1133struct X;
11341135#[derive(Component, Default)]
1136struct Y;
11371138#[derive(Component)]
1139struct Z(u32);
11401141let mut world = World::new();
11421143// - 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
1146world.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));
11491150let id = world.spawn(X).id();
11511152assert_eq!(
11537,
1154 world.entity(id).get::<Z>().unwrap().0,
1155"Z should have the value provided by the constructor defined in X"
1156);
1157 }
11581159#[test]
1160fn runtime_required_components_propagate_up() {
1161// `A` requires `B` directly.
1162#[derive(Component)]
1163 #[require(B)]
1164struct A;
11651166#[derive(Component, Default)]
1167struct B;
11681169#[derive(Component, Default)]
1170struct C;
11711172let mut world = World::new();
11731174// `B` requires `C` with a runtime registration.
1175 // `A` should also require `C` because it requires `B`.
1176world.register_required_components::<B, C>();
11771178let id = world.spawn(A).id();
11791180assert!(world.entity(id).get::<C>().is_some());
1181 }
11821183#[test]
1184fn runtime_required_components_propagate_up_even_more() {
1185#[derive(Component)]
1186struct A;
11871188#[derive(Component, Default)]
1189struct B;
11901191#[derive(Component, Default)]
1192struct C;
11931194#[derive(Component, Default)]
1195struct D;
11961197let mut world = World::new();
11981199 world.register_required_components::<A, B>();
1200 world.register_required_components::<B, C>();
1201 world.register_required_components::<C, D>();
12021203let id = world.spawn(A).id();
12041205assert!(world.entity(id).get::<D>().is_some());
1206 }
12071208#[test]
1209fn runtime_required_components_deep_require_does_not_override_shallow_require() {
1210#[derive(Component)]
1211struct A;
1212#[derive(Component, Default)]
1213struct B;
1214#[derive(Component, Default)]
1215struct C;
1216#[derive(Component)]
1217struct Counter(i32);
1218#[derive(Component, Default)]
1219struct D;
12201221let mut world = World::new();
12221223 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.
1229world.register_required_components_with::<C, Counter>(|| Counter(1));
12301231let id = world.spawn(A).id();
12321233// The "shallower" of the two components is used.
1234assert_eq!(world.entity(id).get::<Counter>().unwrap().0, 1);
1235 }
12361237#[test]
1238fn runtime_required_components_deep_require_does_not_override_shallow_require_deep_subtree_after_shallow(
1239 ) {
1240#[derive(Component)]
1241struct A;
1242#[derive(Component, Default)]
1243struct B;
1244#[derive(Component, Default)]
1245struct C;
1246#[derive(Component, Default)]
1247struct D;
1248#[derive(Component, Default)]
1249struct E;
1250#[derive(Component)]
1251struct Counter(i32);
1252#[derive(Component, Default)]
1253struct F;
12541255let mut world = World::new();
12561257 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>();
12641265let id = world.spawn(A).id();
12661267// The "shallower" of the two components is used.
1268assert_eq!(world.entity(id).get::<Counter>().unwrap().0, 1);
1269 }
12701271#[test]
1272fn runtime_required_components_existing_archetype() {
1273#[derive(Component)]
1274struct X;
12751276#[derive(Component, Default)]
1277struct Y;
12781279let mut world = World::new();
12801281// Registering required components after the archetype has already been created should panic.
1282 // This may change in the future.
1283world.spawn(X);
1284assert!(matches!(
1285 world.try_register_required_components::<X, Y>(),
1286Err(RequiredComponentsError::ArchetypeExists(_))
1287 ));
1288 }
12891290#[test]
1291fn runtime_required_components_fail_with_duplicate() {
1292#[derive(Component)]
1293 #[require(Y)]
1294struct X;
12951296#[derive(Component, Default)]
1297struct Y;
12981299let mut world = World::new();
13001301// This should fail: Tried to register Y as a requirement for X, but the requirement already exists.
1302assert!(matches!(
1303 world.try_register_required_components::<X, Y>(),
1304Err(RequiredComponentsError::DuplicateRegistration(_, _))
1305 ));
1306 }
13071308#[test]
1309fn required_components_bundle_priority() {
1310#[derive(Component, PartialEq, Eq, Clone, Copy, Debug)]
1311struct MyRequired(bool);
13121313#[derive(Component, Default)]
1314 #[require(MyRequired(false))]
1315struct MiddleMan;
13161317#[derive(Component, Default)]
1318 #[require(MiddleMan)]
1319struct ConflictingRequire;
13201321#[derive(Component, Default)]
1322 #[require(MyRequired(true))]
1323struct MyComponent;
13241325let mut world = World::new();
1326let order_a = world
1327 .spawn((ConflictingRequire, MyComponent))
1328 .get::<MyRequired>()
1329 .cloned();
1330let order_b = world
1331 .spawn((MyComponent, ConflictingRequire))
1332 .get::<MyRequired>()
1333 .cloned();
13341335assert_eq!(order_a, Some(MyRequired(false)));
1336assert_eq!(order_b, Some(MyRequired(true)));
1337 }
13381339#[test]
1340 #[should_panic]
1341fn required_components_recursion_errors() {
1342#[derive(Component, Default)]
1343 #[require(B)]
1344struct A;
13451346#[derive(Component, Default)]
1347 #[require(C)]
1348struct B;
13491350#[derive(Component, Default)]
1351 #[require(B)]
1352struct C;
13531354 World::new().register_component::<A>();
1355 }
13561357#[test]
1358 #[should_panic]
1359fn required_components_self_errors() {
1360#[derive(Component, Default)]
1361 #[require(A)]
1362struct A;
13631364 World::new().register_component::<A>();
1365 }
13661367#[test]
1368fn regression_19333() {
1369#[derive(Component)]
1370struct X(usize);
13711372#[derive(Default, Component)]
1373 #[require(X(0))]
1374struct Base;
13751376#[derive(Default, Component)]
1377 #[require(X(1), Base)]
1378struct A;
13791380#[derive(Default, Component)]
1381 #[require(A, Base)]
1382struct B;
13831384#[derive(Default, Component)]
1385 #[require(B, Base)]
1386struct C;
13871388let mut w = World::new();
13891390assert_eq!(w.spawn(B).get::<X>().unwrap().0, 1);
1391assert_eq!(w.spawn(C).get::<X>().unwrap().0, 1);
1392 }
13931394#[test]
1395fn required_components_depth_first_2v1() {
1396#[derive(Component)]
1397struct X(usize);
13981399#[derive(Component)]
1400 #[require(Left, Right)]
1401struct Root;
14021403#[derive(Component, Default)]
1404 #[require(LeftLeft)]
1405struct Left;
14061407#[derive(Component, Default)]
1408 #[require(X(0))] // This is at depth 2 but is more on the left of the tree
1409struct LeftLeft;
14101411#[derive(Component, Default)]
1412 #[require(X(1))] //. This is at depth 1 but is more on the right of the tree
1413struct Right;
14141415let mut world = World::new();
14161417// LeftLeft should have priority over Right
1418assert_eq!(world.spawn(Root).get::<X>().unwrap().0, 0);
1419 }
14201421#[test]
1422fn required_components_depth_first_3v1() {
1423#[derive(Component)]
1424struct X(usize);
14251426#[derive(Component)]
1427 #[require(Left, Right)]
1428struct Root;
14291430#[derive(Component, Default)]
1431 #[require(LeftLeft)]
1432struct Left;
14331434#[derive(Component, Default)]
1435 #[require(LeftLeftLeft)]
1436struct LeftLeft;
14371438#[derive(Component, Default)]
1439 #[require(X(0))] // This is at depth 3 but is more on the left of the tree
1440struct LeftLeftLeft;
14411442#[derive(Component, Default)]
1443 #[require(X(1))] //. This is at depth 1 but is more on the right of the tree
1444struct Right;
14451446let mut world = World::new();
14471448// LeftLeftLeft should have priority over Right
1449assert_eq!(world.spawn(Root).get::<X>().unwrap().0, 0);
1450 }
14511452#[test]
1453fn runtime_required_components_depth_first_2v1() {
1454#[derive(Component)]
1455struct X(usize);
14561457#[derive(Component)]
1458struct Root;
14591460#[derive(Component, Default)]
1461struct Left;
14621463#[derive(Component, Default)]
1464struct LeftLeft;
14651466#[derive(Component, Default)]
1467struct Right;
14681469// Register bottom up: registering higher level components should pick up lower level ones.
1470let 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>();
1476assert_eq!(world.spawn(Root).get::<X>().unwrap().0, 0);
14771478// Register top down: registering lower components should propagate to higher ones
1479let mut world = World::new();
1480 world.register_required_components::<Root, Left>(); // Note: still register Left before Right
1481world.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));
1485assert_eq!(world.spawn(Root).get::<X>().unwrap().0, 0);
14861487// Register top down again, but this time LeftLeft before Right
1488let 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));
1494assert_eq!(world.spawn(Root).get::<X>().unwrap().0, 0);
1495 }
14961497#[test]
1498fn runtime_required_components_propagate_metadata_alternate() {
1499#[derive(Component, Default)]
1500 #[require(L1)]
1501struct L0;
15021503#[derive(Component, Default)]
1504struct L1;
15051506#[derive(Component, Default)]
1507 #[require(L3)]
1508struct L2;
15091510#[derive(Component, Default)]
1511struct L3;
15121513#[derive(Component, Default)]
1514 #[require(L5)]
1515struct L4;
15161517#[derive(Component, Default)]
1518struct L5;
15191520// Try to piece the 3 requirements together
1521let mut world = World::new();
1522 world.register_required_components::<L1, L2>();
1523 world.register_required_components::<L3, L4>();
1524let e = world.spawn(L0).id();
1525assert!(world
1526 .query::<(&L0, &L1, &L2, &L3, &L4, &L5)>()
1527 .get(&world, e)
1528 .is_ok());
15291530// Repeat but in the opposite order
1531let mut world = World::new();
1532 world.register_required_components::<L3, L4>();
1533 world.register_required_components::<L1, L2>();
1534let e = world.spawn(L0).id();
1535assert!(world
1536 .query::<(&L0, &L1, &L2, &L3, &L4, &L5)>()
1537 .get(&world, e)
1538 .is_ok());
1539 }
15401541#[test]
1542fn runtime_required_components_propagate_metadata_chain() {
1543#[derive(Component, Default)]
1544 #[require(L1)]
1545struct L0;
15461547#[derive(Component, Default)]
1548struct L1;
15491550#[derive(Component, Default)]
1551struct L2;
15521553#[derive(Component, Default)]
1554 #[require(L4)]
1555struct L3;
15561557#[derive(Component, Default)]
1558struct L4;
15591560// Try to piece the 3 requirements together
1561let mut world = World::new();
1562 world.register_required_components::<L1, L2>();
1563 world.register_required_components::<L2, L3>();
1564let e = world.spawn(L0).id();
1565assert!(world
1566 .query::<(&L0, &L1, &L2, &L3, &L4)>()
1567 .get(&world, e)
1568 .is_ok());
15691570// Repeat but in the opposite order
1571let mut world = World::new();
1572 world.register_required_components::<L2, L3>();
1573 world.register_required_components::<L1, L2>();
1574let e = world.spawn(L0).id();
1575assert!(world
1576 .query::<(&L0, &L1, &L2, &L3, &L4)>()
1577 .get(&world, e)
1578 .is_ok());
1579 }
15801581#[test]
1582fn runtime_required_components_cyclic() {
1583#[derive(Component, Default)]
1584 #[require(B)]
1585struct A;
15861587#[derive(Component, Default)]
1588struct B;
15891590#[derive(Component, Default)]
1591struct C;
15921593let mut world = World::new();
15941595assert!(world.try_register_required_components::<B, C>().is_ok());
1596assert!(matches!(
1597 world.try_register_required_components::<C, A>(),
1598Err(RequiredComponentsError::CyclicRequirement(_, _))
1599 ));
1600 }
1601}