bevy_ecs/
component.rs

1//! Types for declaring and storing [`Component`]s.
2
3use crate::{
4    archetype::ArchetypeFlags,
5    bundle::BundleInfo,
6    change_detection::{MaybeLocation, MAX_CHANGE_AGE},
7    entity::{ComponentCloneCtx, Entity, EntityMapper, SourceComponent},
8    query::DebugCheckedUnwrap,
9    relationship::RelationshipHookMode,
10    resource::Resource,
11    storage::{SparseSetIndex, SparseSets, Table, TableRow},
12    system::{Local, SystemParam},
13    world::{DeferredWorld, FromWorld, World},
14};
15use alloc::boxed::Box;
16use alloc::{borrow::Cow, format, vec::Vec};
17pub use bevy_ecs_macros::Component;
18use bevy_platform_support::sync::Arc;
19use bevy_platform_support::{
20    collections::{HashMap, HashSet},
21    sync::PoisonError,
22};
23use bevy_ptr::{OwningPtr, UnsafeCellDeref};
24#[cfg(feature = "bevy_reflect")]
25use bevy_reflect::Reflect;
26use bevy_utils::TypeIdMap;
27use core::{
28    alloc::Layout,
29    any::{Any, TypeId},
30    cell::UnsafeCell,
31    fmt::Debug,
32    marker::PhantomData,
33    mem::needs_drop,
34    ops::{Deref, DerefMut},
35};
36use disqualified::ShortName;
37use smallvec::SmallVec;
38use thiserror::Error;
39
40/// A data type that can be used to store data for an [entity].
41///
42/// `Component` is a [derivable trait]: this means that a data type can implement it by applying a `#[derive(Component)]` attribute to it.
43/// However, components must always satisfy the `Send + Sync + 'static` trait bounds.
44///
45/// [entity]: crate::entity
46/// [derivable trait]: https://doc.rust-lang.org/book/appendix-03-derivable-traits.html
47///
48/// # Examples
49///
50/// Components can take many forms: they are usually structs, but can also be of every other kind of data type, like enums or zero sized types.
51/// The following examples show how components are laid out in code.
52///
53/// ```
54/// # use bevy_ecs::component::Component;
55/// # struct Color;
56/// #
57/// // A component can contain data...
58/// #[derive(Component)]
59/// struct LicensePlate(String);
60///
61/// // ... but it can also be a zero-sized marker.
62/// #[derive(Component)]
63/// struct Car;
64///
65/// // Components can also be structs with named fields...
66/// #[derive(Component)]
67/// struct VehiclePerformance {
68///     acceleration: f32,
69///     top_speed: f32,
70///     handling: f32,
71/// }
72///
73/// // ... or enums.
74/// #[derive(Component)]
75/// enum WheelCount {
76///     Two,
77///     Three,
78///     Four,
79/// }
80/// ```
81///
82/// # Component and data access
83///
84/// Components can be marked as immutable by adding the `#[component(immutable)]`
85/// attribute when using the derive macro.
86/// See the documentation for [`ComponentMutability`] for more details around this
87/// feature.
88///
89/// See the [`entity`] module level documentation to learn how to add or remove components from an entity.
90///
91/// See the documentation for [`Query`] to learn how to access component data from a system.
92///
93/// [`entity`]: crate::entity#usage
94/// [`Query`]: crate::system::Query
95/// [`ComponentMutability`]: crate::component::ComponentMutability
96///
97/// # Choosing a storage type
98///
99/// Components can be stored in the world using different strategies with their own performance implications.
100/// By default, components are added to the [`Table`] storage, which is optimized for query iteration.
101///
102/// Alternatively, components can be added to the [`SparseSet`] storage, which is optimized for component insertion and removal.
103/// This is achieved by adding an additional `#[component(storage = "SparseSet")]` attribute to the derive one:
104///
105/// ```
106/// # use bevy_ecs::component::Component;
107/// #
108/// #[derive(Component)]
109/// #[component(storage = "SparseSet")]
110/// struct ComponentA;
111/// ```
112///
113/// [`Table`]: crate::storage::Table
114/// [`SparseSet`]: crate::storage::SparseSet
115///
116/// # Required Components
117///
118/// Components can specify Required Components. If some [`Component`] `A` requires [`Component`] `B`,  then when `A` is inserted,
119/// `B` will _also_ be initialized and inserted (if it was not manually specified).
120///
121/// The [`Default`] constructor will be used to initialize the component, by default:
122///
123/// ```
124/// # use bevy_ecs::prelude::*;
125/// #[derive(Component)]
126/// #[require(B)]
127/// struct A;
128///
129/// #[derive(Component, Default, PartialEq, Eq, Debug)]
130/// struct B(usize);
131///
132/// # let mut world = World::default();
133/// // This will implicitly also insert B with the Default constructor
134/// let id = world.spawn(A).id();
135/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
136///
137/// // This will _not_ implicitly insert B, because it was already provided
138/// world.spawn((A, B(11)));
139/// ```
140///
141/// Components can have more than one required component:
142///
143/// ```
144/// # use bevy_ecs::prelude::*;
145/// #[derive(Component)]
146/// #[require(B, C)]
147/// struct A;
148///
149/// #[derive(Component, Default, PartialEq, Eq, Debug)]
150/// #[require(C)]
151/// struct B(usize);
152///
153/// #[derive(Component, Default, PartialEq, Eq, Debug)]
154/// struct C(u32);
155///
156/// # let mut world = World::default();
157/// // This will implicitly also insert B and C with their Default constructors
158/// let id = world.spawn(A).id();
159/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
160/// assert_eq!(&C(0), world.entity(id).get::<C>().unwrap());
161/// ```
162///
163/// You can define inline component values that take the following forms:
164/// ```
165/// # use bevy_ecs::prelude::*;
166/// #[derive(Component)]
167/// #[require(
168///     B(1), // tuple structs
169///     C { value: 1 }, // named-field structs
170///     D::One, // enum variants
171///     E::ONE, // associated consts
172///     F::new(1) // constructors
173/// )]
174/// struct A;
175///
176/// #[derive(Component, PartialEq, Eq, Debug)]
177/// struct B(u8);
178///
179/// #[derive(Component, PartialEq, Eq, Debug)]
180/// struct C {
181///     value: u8
182/// }
183///
184/// #[derive(Component, PartialEq, Eq, Debug)]
185/// enum D {
186///    Zero,
187///    One,
188/// }
189///
190/// #[derive(Component, PartialEq, Eq, Debug)]
191/// struct E(u8);
192///
193/// impl E {
194///     pub const ONE: Self = Self(1);
195/// }
196///
197/// #[derive(Component, PartialEq, Eq, Debug)]
198/// struct F(u8);
199///
200/// impl F {
201///     fn new(value: u8) -> Self {
202///         Self(value)
203///     }
204/// }
205///
206/// # let mut world = World::default();
207/// let id = world.spawn(A).id();
208/// assert_eq!(&B(1), world.entity(id).get::<B>().unwrap());
209/// assert_eq!(&C { value: 1 }, world.entity(id).get::<C>().unwrap());
210/// assert_eq!(&D::One, world.entity(id).get::<D>().unwrap());
211/// assert_eq!(&E(1), world.entity(id).get::<E>().unwrap());
212/// assert_eq!(&F(1), world.entity(id).get::<F>().unwrap());
213/// ````
214///
215///
216/// You can also define arbitrary expressions by using `=`
217///
218/// ```
219/// # use bevy_ecs::prelude::*;
220/// #[derive(Component)]
221/// #[require(C = init_c())]
222/// struct A;
223///
224/// #[derive(Component, PartialEq, Eq, Debug)]
225/// #[require(C = C(20))]
226/// struct B;
227///
228/// #[derive(Component, PartialEq, Eq, Debug)]
229/// struct C(usize);
230///
231/// fn init_c() -> C {
232///     C(10)
233/// }
234///
235/// # let mut world = World::default();
236/// // This will implicitly also insert C with the init_c() constructor
237/// let id = world.spawn(A).id();
238/// assert_eq!(&C(10), world.entity(id).get::<C>().unwrap());
239///
240/// // This will implicitly also insert C with the `|| C(20)` constructor closure
241/// let id = world.spawn(B).id();
242/// assert_eq!(&C(20), world.entity(id).get::<C>().unwrap());
243/// ```
244///
245/// Required components are _recursive_. This means, if a Required Component has required components,
246/// those components will _also_ be inserted if they are missing:
247///
248/// ```
249/// # use bevy_ecs::prelude::*;
250/// #[derive(Component)]
251/// #[require(B)]
252/// struct A;
253///
254/// #[derive(Component, Default, PartialEq, Eq, Debug)]
255/// #[require(C)]
256/// struct B(usize);
257///
258/// #[derive(Component, Default, PartialEq, Eq, Debug)]
259/// struct C(u32);
260///
261/// # let mut world = World::default();
262/// // This will implicitly also insert B and C with their Default constructors
263/// let id = world.spawn(A).id();
264/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
265/// assert_eq!(&C(0), world.entity(id).get::<C>().unwrap());
266/// ```
267///
268/// Note that cycles in the "component require tree" will result in stack overflows when attempting to
269/// insert a component.
270///
271/// This "multiple inheritance" pattern does mean that it is possible to have duplicate requires for a given type
272/// at different levels of the inheritance tree:
273///
274/// ```
275/// # use bevy_ecs::prelude::*;
276/// #[derive(Component)]
277/// struct X(usize);
278///
279/// #[derive(Component, Default)]
280/// #[require(X(1))]
281/// struct Y;
282///
283/// #[derive(Component)]
284/// #[require(
285///     Y,
286///     X(2),
287/// )]
288/// struct Z;
289///
290/// # let mut world = World::default();
291/// // In this case, the x2 constructor is used for X
292/// let id = world.spawn(Z).id();
293/// assert_eq!(2, world.entity(id).get::<X>().unwrap().0);
294/// ```
295///
296/// In general, this shouldn't happen often, but when it does the algorithm for choosing the constructor from the tree is simple and predictable:
297/// 1. A constructor from a direct `#[require()]`, if one exists, is selected with priority.
298/// 2. Otherwise, perform a Depth First Search on the tree of requirements and select the first one found.
299///
300/// From a user perspective, just think about this as the following:
301/// 1. Specifying a required component constructor for Foo directly on a spawned component Bar will result in that constructor being used (and overriding existing constructors lower in the inheritance tree). This is the classic "inheritance override" behavior people expect.
302/// 2. For cases where "multiple inheritance" results in constructor clashes, Components should be listed in "importance order". List a component earlier in the requirement list to initialize its inheritance tree earlier.
303///
304/// ## Registering required components at runtime
305///
306/// In most cases, required components should be registered using the `require` attribute as shown above.
307/// However, in some cases, it may be useful to register required components at runtime.
308///
309/// This can be done through [`World::register_required_components`] or  [`World::register_required_components_with`]
310/// for the [`Default`] and custom constructors respectively:
311///
312/// ```
313/// # use bevy_ecs::prelude::*;
314/// #[derive(Component)]
315/// struct A;
316///
317/// #[derive(Component, Default, PartialEq, Eq, Debug)]
318/// struct B(usize);
319///
320/// #[derive(Component, PartialEq, Eq, Debug)]
321/// struct C(u32);
322///
323/// # let mut world = World::default();
324/// // Register B as required by A and C as required by B.
325/// world.register_required_components::<A, B>();
326/// world.register_required_components_with::<B, C>(|| C(2));
327///
328/// // This will implicitly also insert B with its Default constructor
329/// // and C with the custom constructor defined by B.
330/// let id = world.spawn(A).id();
331/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
332/// assert_eq!(&C(2), world.entity(id).get::<C>().unwrap());
333/// ```
334///
335/// Similar rules as before apply to duplicate requires fer a given type at different levels
336/// of the inheritance tree. `A` requiring `C` directly would take precedence over indirectly
337/// requiring it through `A` requiring `B` and `B` requiring `C`.
338///
339/// Unlike with the `require` attribute, directly requiring the same component multiple times
340/// for the same component will result in a panic. This is done to prevent conflicting constructors
341/// and confusing ordering dependencies.
342///
343/// Note that requirements must currently be registered before the requiring component is inserted
344/// into the world for the first time. Registering requirements after this will lead to a panic.
345///
346/// # Relationships between Entities
347///
348/// Sometimes it is useful to define relationships between entities.  A common example is the
349/// parent / child relationship. Since Components are how data is stored for Entities, one might
350/// naturally think to create a Component which has a field of type [`Entity`].
351///
352/// To facilitate this pattern, Bevy provides the [`Relationship`](`crate::relationship::Relationship`)
353/// trait. You can derive the [`Relationship`](`crate::relationship::Relationship`) and
354/// [`RelationshipTarget`](`crate::relationship::RelationshipTarget`) traits in addition to the
355/// Component trait in order to implement data driven relationships between entities, see the trait
356/// docs for more details.
357///
358/// In addition, Bevy provides canonical implementations of the parent / child relationship via the
359/// [`ChildOf`](crate::hierarchy::ChildOf) [`Relationship`](crate::relationship::Relationship) and
360/// the [`Children`](crate::hierarchy::Children)
361/// [`RelationshipTarget`](crate::relationship::RelationshipTarget).
362///
363/// # Adding component's hooks
364///
365/// See [`ComponentHooks`] for a detailed explanation of component's hooks.
366///
367/// Alternatively to the example shown in [`ComponentHooks`]' documentation, hooks can be configured using following attributes:
368/// - `#[component(on_add = on_add_function)]`
369/// - `#[component(on_insert = on_insert_function)]`
370/// - `#[component(on_replace = on_replace_function)]`
371/// - `#[component(on_remove = on_remove_function)]`
372///
373/// ```
374/// # use bevy_ecs::component::{Component, HookContext};
375/// # use bevy_ecs::world::DeferredWorld;
376/// # use bevy_ecs::entity::Entity;
377/// # use bevy_ecs::component::ComponentId;
378/// # use core::panic::Location;
379/// #
380/// #[derive(Component)]
381/// #[component(on_add = my_on_add_hook)]
382/// #[component(on_insert = my_on_insert_hook)]
383/// // Another possible way of configuring hooks:
384/// // #[component(on_add = my_on_add_hook, on_insert = my_on_insert_hook)]
385/// //
386/// // We don't have a replace or remove hook, so we can leave them out:
387/// // #[component(on_replace = my_on_replace_hook, on_remove = my_on_remove_hook)]
388/// struct ComponentA;
389///
390/// fn my_on_add_hook(world: DeferredWorld, context: HookContext) {
391///     // ...
392/// }
393///
394/// // You can also destructure items directly in the signature
395/// fn my_on_insert_hook(world: DeferredWorld, HookContext { caller, .. }: HookContext) {
396///     // ...
397/// }
398/// ```
399///
400/// This also supports function calls that yield closures
401///
402/// ```
403/// # use bevy_ecs::component::{Component, HookContext};
404/// # use bevy_ecs::world::DeferredWorld;
405/// #
406/// #[derive(Component)]
407/// #[component(on_add = my_msg_hook("hello"))]
408/// #[component(on_despawn = my_msg_hook("yoink"))]
409/// struct ComponentA;
410///
411/// // a hook closure generating function
412/// fn my_msg_hook(message: &'static str) -> impl Fn(DeferredWorld, HookContext) {
413///     move |_world, _ctx| {
414///         println!("{message}");
415///     }
416/// }
417/// ```
418///
419/// # Implementing the trait for foreign types
420///
421/// As a consequence of the [orphan rule], it is not possible to separate into two different crates the implementation of `Component` from the definition of a type.
422/// This means that it is not possible to directly have a type defined in a third party library as a component.
423/// This important limitation can be easily worked around using the [newtype pattern]:
424/// this makes it possible to locally define and implement `Component` for a tuple struct that wraps the foreign type.
425/// The following example gives a demonstration of this pattern.
426///
427/// ```
428/// // `Component` is defined in the `bevy_ecs` crate.
429/// use bevy_ecs::component::Component;
430///
431/// // `Duration` is defined in the `std` crate.
432/// use std::time::Duration;
433///
434/// // It is not possible to implement `Component` for `Duration` from this position, as they are
435/// // both foreign items, defined in an external crate. However, nothing prevents to define a new
436/// // `Cooldown` type that wraps `Duration`. As `Cooldown` is defined in a local crate, it is
437/// // possible to implement `Component` for it.
438/// #[derive(Component)]
439/// struct Cooldown(Duration);
440/// ```
441///
442/// [orphan rule]: https://doc.rust-lang.org/book/ch10-02-traits.html#implementing-a-trait-on-a-type
443/// [newtype pattern]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#using-the-newtype-pattern-to-implement-external-traits-on-external-types
444///
445/// # `!Sync` Components
446/// A `!Sync` type cannot implement `Component`. However, it is possible to wrap a `Send` but not `Sync`
447/// type in [`SyncCell`] or the currently unstable [`Exclusive`] to make it `Sync`. This forces only
448/// having mutable access (`&mut T` only, never `&T`), but makes it safe to reference across multiple
449/// threads.
450///
451/// This will fail to compile since `RefCell` is `!Sync`.
452/// ```compile_fail
453/// # use std::cell::RefCell;
454/// # use bevy_ecs::component::Component;
455/// #[derive(Component)]
456/// struct NotSync {
457///    counter: RefCell<usize>,
458/// }
459/// ```
460///
461/// This will compile since the `RefCell` is wrapped with `SyncCell`.
462/// ```
463/// # use std::cell::RefCell;
464/// # use bevy_ecs::component::Component;
465/// use bevy_utils::synccell::SyncCell;
466///
467/// // This will compile.
468/// #[derive(Component)]
469/// struct ActuallySync {
470///    counter: SyncCell<RefCell<usize>>,
471/// }
472/// ```
473///
474/// [`SyncCell`]: bevy_utils::synccell::SyncCell
475/// [`Exclusive`]: https://doc.rust-lang.org/nightly/std/sync/struct.Exclusive.html
476#[diagnostic::on_unimplemented(
477    message = "`{Self}` is not a `Component`",
478    label = "invalid `Component`",
479    note = "consider annotating `{Self}` with `#[derive(Component)]`"
480)]
481pub trait Component: Send + Sync + 'static {
482    /// A constant indicating the storage type used for this component.
483    const STORAGE_TYPE: StorageType;
484
485    /// A marker type to assist Bevy with determining if this component is
486    /// mutable, or immutable. Mutable components will have [`Component<Mutability = Mutable>`],
487    /// while immutable components will instead have [`Component<Mutability = Immutable>`].
488    ///
489    /// * For a component to be mutable, this type must be [`Mutable`].
490    /// * For a component to be immutable, this type must be [`Immutable`].
491    type Mutability: ComponentMutability;
492
493    /// Called when registering this component, allowing mutable access to its [`ComponentHooks`].
494    #[deprecated(
495        since = "0.16.0",
496        note = "Use the individual hook methods instead (e.g., `Component::on_add`, etc.)"
497    )]
498    fn register_component_hooks(hooks: &mut ComponentHooks) {
499        hooks.update_from_component::<Self>();
500    }
501
502    /// Gets the `on_add` [`ComponentHook`] for this [`Component`] if one is defined.
503    fn on_add() -> Option<ComponentHook> {
504        None
505    }
506
507    /// Gets the `on_insert` [`ComponentHook`] for this [`Component`] if one is defined.
508    fn on_insert() -> Option<ComponentHook> {
509        None
510    }
511
512    /// Gets the `on_replace` [`ComponentHook`] for this [`Component`] if one is defined.
513    fn on_replace() -> Option<ComponentHook> {
514        None
515    }
516
517    /// Gets the `on_remove` [`ComponentHook`] for this [`Component`] if one is defined.
518    fn on_remove() -> Option<ComponentHook> {
519        None
520    }
521
522    /// Gets the `on_despawn` [`ComponentHook`] for this [`Component`] if one is defined.
523    fn on_despawn() -> Option<ComponentHook> {
524        None
525    }
526
527    /// Registers required components.
528    fn register_required_components(
529        _component_id: ComponentId,
530        _components: &mut ComponentsRegistrator,
531        _required_components: &mut RequiredComponents,
532        _inheritance_depth: u16,
533        _recursion_check_stack: &mut Vec<ComponentId>,
534    ) {
535    }
536
537    /// Called when registering this component, allowing to override clone function (or disable cloning altogether) for this component.
538    ///
539    /// See [Handlers section of `EntityClonerBuilder`](crate::entity::EntityClonerBuilder#handlers) to understand how this affects handler priority.
540    #[inline]
541    fn clone_behavior() -> ComponentCloneBehavior {
542        ComponentCloneBehavior::Default
543    }
544
545    /// Maps the entities on this component using the given [`EntityMapper`]. This is used to remap entities in contexts like scenes and entity cloning.
546    /// When deriving [`Component`], this is populated by annotating fields containing entities with `#[entities]`
547    ///
548    /// ```
549    /// # use bevy_ecs::{component::Component, entity::Entity};
550    /// #[derive(Component)]
551    /// struct Inventory {
552    ///     #[entities]
553    ///     items: Vec<Entity>
554    /// }
555    /// ```
556    ///
557    /// Fields with `#[entities]` must implement [`MapEntities`](crate::entity::MapEntities).
558    #[inline]
559    fn map_entities<E: EntityMapper>(_this: &mut Self, _mapper: &mut E) {}
560}
561
562mod private {
563    pub trait Seal {}
564}
565
566/// The mutability option for a [`Component`]. This can either be:
567/// * [`Mutable`]
568/// * [`Immutable`]
569///
570/// This is controlled through either [`Component::Mutability`] or `#[component(immutable)]`
571/// when using the derive macro.
572///
573/// Immutable components are guaranteed to never have an exclusive reference,
574/// `&mut ...`, created while inserted onto an entity.
575/// In all other ways, they are identical to mutable components.
576/// This restriction allows hooks to observe all changes made to an immutable
577/// component, effectively turning the `OnInsert` and `OnReplace` hooks into a
578/// `OnMutate` hook.
579/// This is not practical for mutable components, as the runtime cost of invoking
580/// a hook for every exclusive reference created would be far too high.
581///
582/// # Examples
583///
584/// ```rust
585/// # use bevy_ecs::component::Component;
586/// #
587/// #[derive(Component)]
588/// #[component(immutable)]
589/// struct ImmutableFoo;
590/// ```
591pub trait ComponentMutability: private::Seal + 'static {
592    /// Boolean to indicate if this mutability setting implies a mutable or immutable
593    /// component.
594    const MUTABLE: bool;
595}
596
597/// Parameter indicating a [`Component`] is immutable.
598///
599/// See [`ComponentMutability`] for details.
600pub struct Immutable;
601
602impl private::Seal for Immutable {}
603impl ComponentMutability for Immutable {
604    const MUTABLE: bool = false;
605}
606
607/// Parameter indicating a [`Component`] is mutable.
608///
609/// See [`ComponentMutability`] for details.
610pub struct Mutable;
611
612impl private::Seal for Mutable {}
613impl ComponentMutability for Mutable {
614    const MUTABLE: bool = true;
615}
616
617/// The storage used for a specific component type.
618///
619/// # Examples
620/// The [`StorageType`] for a component is configured via the derive attribute
621///
622/// ```
623/// # use bevy_ecs::{prelude::*, component::*};
624/// #[derive(Component)]
625/// #[component(storage = "SparseSet")]
626/// struct A;
627/// ```
628#[derive(Debug, Copy, Clone, Default, Eq, PartialEq)]
629pub enum StorageType {
630    /// Provides fast and cache-friendly iteration, but slower addition and removal of components.
631    /// This is the default storage type.
632    #[default]
633    Table,
634    /// Provides fast addition and removal of components, but slower iteration.
635    SparseSet,
636}
637
638/// The type used for [`Component`] lifecycle hooks such as `on_add`, `on_insert` or `on_remove`.
639pub type ComponentHook = for<'w> fn(DeferredWorld<'w>, HookContext);
640
641/// Context provided to a [`ComponentHook`].
642#[derive(Clone, Copy, Debug)]
643pub struct HookContext {
644    /// The [`Entity`] this hook was invoked for.
645    pub entity: Entity,
646    /// The [`ComponentId`] this hook was invoked for.
647    pub component_id: ComponentId,
648    /// The caller location is `Some` if the `track_caller` feature is enabled.
649    pub caller: MaybeLocation,
650    /// Configures how relationship hooks will run
651    pub relationship_hook_mode: RelationshipHookMode,
652}
653
654/// [`World`]-mutating functions that run as part of lifecycle events of a [`Component`].
655///
656/// Hooks are functions that run when a component is added, overwritten, or removed from an entity.
657/// These are intended to be used for structural side effects that need to happen when a component is added or removed,
658/// and are not intended for general-purpose logic.
659///
660/// For example, you might use a hook to update a cached index when a component is added,
661/// to clean up resources when a component is removed,
662/// or to keep hierarchical data structures across entities in sync.
663///
664/// This information is stored in the [`ComponentInfo`] of the associated component.
665///
666/// There is two ways of configuring hooks for a component:
667/// 1. Defining the [`Component::register_component_hooks`] method (see [`Component`])
668/// 2. Using the [`World::register_component_hooks`] method
669///
670/// # Example 2
671///
672/// ```
673/// use bevy_ecs::prelude::*;
674/// use bevy_platform_support::collections::HashSet;
675///
676/// #[derive(Component)]
677/// struct MyTrackedComponent;
678///
679/// #[derive(Resource, Default)]
680/// struct TrackedEntities(HashSet<Entity>);
681///
682/// let mut world = World::new();
683/// world.init_resource::<TrackedEntities>();
684///
685/// // No entities with `MyTrackedComponent` have been added yet, so we can safely add component hooks
686/// let mut tracked_component_query = world.query::<&MyTrackedComponent>();
687/// assert!(tracked_component_query.iter(&world).next().is_none());
688///
689/// world.register_component_hooks::<MyTrackedComponent>().on_add(|mut world, context| {
690///    let mut tracked_entities = world.resource_mut::<TrackedEntities>();
691///   tracked_entities.0.insert(context.entity);
692/// });
693///
694/// world.register_component_hooks::<MyTrackedComponent>().on_remove(|mut world, context| {
695///   let mut tracked_entities = world.resource_mut::<TrackedEntities>();
696///   tracked_entities.0.remove(&context.entity);
697/// });
698///
699/// let entity = world.spawn(MyTrackedComponent).id();
700/// let tracked_entities = world.resource::<TrackedEntities>();
701/// assert!(tracked_entities.0.contains(&entity));
702///
703/// world.despawn(entity);
704/// let tracked_entities = world.resource::<TrackedEntities>();
705/// assert!(!tracked_entities.0.contains(&entity));
706/// ```
707#[derive(Debug, Clone, Default)]
708pub struct ComponentHooks {
709    pub(crate) on_add: Option<ComponentHook>,
710    pub(crate) on_insert: Option<ComponentHook>,
711    pub(crate) on_replace: Option<ComponentHook>,
712    pub(crate) on_remove: Option<ComponentHook>,
713    pub(crate) on_despawn: Option<ComponentHook>,
714}
715
716impl ComponentHooks {
717    pub(crate) fn update_from_component<C: Component + ?Sized>(&mut self) -> &mut Self {
718        if let Some(hook) = C::on_add() {
719            self.on_add(hook);
720        }
721        if let Some(hook) = C::on_insert() {
722            self.on_insert(hook);
723        }
724        if let Some(hook) = C::on_replace() {
725            self.on_replace(hook);
726        }
727        if let Some(hook) = C::on_remove() {
728            self.on_remove(hook);
729        }
730        if let Some(hook) = C::on_despawn() {
731            self.on_despawn(hook);
732        }
733
734        self
735    }
736
737    /// Register a [`ComponentHook`] that will be run when this component is added to an entity.
738    /// An `on_add` hook will always run before `on_insert` hooks. Spawning an entity counts as
739    /// adding all of its components.
740    ///
741    /// # Panics
742    ///
743    /// Will panic if the component already has an `on_add` hook
744    pub fn on_add(&mut self, hook: ComponentHook) -> &mut Self {
745        self.try_on_add(hook)
746            .expect("Component already has an on_add hook")
747    }
748
749    /// Register a [`ComponentHook`] that will be run when this component is added (with `.insert`)
750    /// or replaced.
751    ///
752    /// An `on_insert` hook always runs after any `on_add` hooks (if the entity didn't already have the component).
753    ///
754    /// # Warning
755    ///
756    /// The hook won't run if the component is already present and is only mutated, such as in a system via a query.
757    /// As a result, this is *not* an appropriate mechanism for reliably updating indexes and other caches.
758    ///
759    /// # Panics
760    ///
761    /// Will panic if the component already has an `on_insert` hook
762    pub fn on_insert(&mut self, hook: ComponentHook) -> &mut Self {
763        self.try_on_insert(hook)
764            .expect("Component already has an on_insert hook")
765    }
766
767    /// Register a [`ComponentHook`] that will be run when this component is about to be dropped,
768    /// such as being replaced (with `.insert`) or removed.
769    ///
770    /// If this component is inserted onto an entity that already has it, this hook will run before the value is replaced,
771    /// allowing access to the previous data just before it is dropped.
772    /// This hook does *not* run if the entity did not already have this component.
773    ///
774    /// An `on_replace` hook always runs before any `on_remove` hooks (if the component is being removed from the entity).
775    ///
776    /// # Warning
777    ///
778    /// The hook won't run if the component is already present and is only mutated, such as in a system via a query.
779    /// As a result, this is *not* an appropriate mechanism for reliably updating indexes and other caches.
780    ///
781    /// # Panics
782    ///
783    /// Will panic if the component already has an `on_replace` hook
784    pub fn on_replace(&mut self, hook: ComponentHook) -> &mut Self {
785        self.try_on_replace(hook)
786            .expect("Component already has an on_replace hook")
787    }
788
789    /// Register a [`ComponentHook`] that will be run when this component is removed from an entity.
790    /// Despawning an entity counts as removing all of its components.
791    ///
792    /// # Panics
793    ///
794    /// Will panic if the component already has an `on_remove` hook
795    pub fn on_remove(&mut self, hook: ComponentHook) -> &mut Self {
796        self.try_on_remove(hook)
797            .expect("Component already has an on_remove hook")
798    }
799
800    /// Register a [`ComponentHook`] that will be run for each component on an entity when it is despawned.
801    ///
802    /// # Panics
803    ///
804    /// Will panic if the component already has an `on_despawn` hook
805    pub fn on_despawn(&mut self, hook: ComponentHook) -> &mut Self {
806        self.try_on_despawn(hook)
807            .expect("Component already has an on_despawn hook")
808    }
809
810    /// Attempt to register a [`ComponentHook`] that will be run when this component is added to an entity.
811    ///
812    /// This is a fallible version of [`Self::on_add`].
813    ///
814    /// Returns `None` if the component already has an `on_add` hook.
815    pub fn try_on_add(&mut self, hook: ComponentHook) -> Option<&mut Self> {
816        if self.on_add.is_some() {
817            return None;
818        }
819        self.on_add = Some(hook);
820        Some(self)
821    }
822
823    /// Attempt to register a [`ComponentHook`] that will be run when this component is added (with `.insert`)
824    ///
825    /// This is a fallible version of [`Self::on_insert`].
826    ///
827    /// Returns `None` if the component already has an `on_insert` hook.
828    pub fn try_on_insert(&mut self, hook: ComponentHook) -> Option<&mut Self> {
829        if self.on_insert.is_some() {
830            return None;
831        }
832        self.on_insert = Some(hook);
833        Some(self)
834    }
835
836    /// Attempt to register a [`ComponentHook`] that will be run when this component is replaced (with `.insert`) or removed
837    ///
838    /// This is a fallible version of [`Self::on_replace`].
839    ///
840    /// Returns `None` if the component already has an `on_replace` hook.
841    pub fn try_on_replace(&mut self, hook: ComponentHook) -> Option<&mut Self> {
842        if self.on_replace.is_some() {
843            return None;
844        }
845        self.on_replace = Some(hook);
846        Some(self)
847    }
848
849    /// Attempt to register a [`ComponentHook`] that will be run when this component is removed from an entity.
850    ///
851    /// This is a fallible version of [`Self::on_remove`].
852    ///
853    /// Returns `None` if the component already has an `on_remove` hook.
854    pub fn try_on_remove(&mut self, hook: ComponentHook) -> Option<&mut Self> {
855        if self.on_remove.is_some() {
856            return None;
857        }
858        self.on_remove = Some(hook);
859        Some(self)
860    }
861
862    /// Attempt to register a [`ComponentHook`] that will be run for each component on an entity when it is despawned.
863    ///
864    /// This is a fallible version of [`Self::on_despawn`].
865    ///
866    /// Returns `None` if the component already has an `on_despawn` hook.
867    pub fn try_on_despawn(&mut self, hook: ComponentHook) -> Option<&mut Self> {
868        if self.on_despawn.is_some() {
869            return None;
870        }
871        self.on_despawn = Some(hook);
872        Some(self)
873    }
874}
875
876/// Stores metadata for a type of component or resource stored in a specific [`World`].
877#[derive(Debug, Clone)]
878pub struct ComponentInfo {
879    id: ComponentId,
880    descriptor: ComponentDescriptor,
881    hooks: ComponentHooks,
882    required_components: RequiredComponents,
883    required_by: HashSet<ComponentId>,
884}
885
886impl ComponentInfo {
887    /// Returns a value uniquely identifying the current component.
888    #[inline]
889    pub fn id(&self) -> ComponentId {
890        self.id
891    }
892
893    /// Returns the name of the current component.
894    #[inline]
895    pub fn name(&self) -> &str {
896        &self.descriptor.name
897    }
898
899    /// Returns `true` if the current component is mutable.
900    #[inline]
901    pub fn mutable(&self) -> bool {
902        self.descriptor.mutable
903    }
904
905    /// Returns [`ComponentCloneBehavior`] of the current component.
906    #[inline]
907    pub fn clone_behavior(&self) -> &ComponentCloneBehavior {
908        &self.descriptor.clone_behavior
909    }
910
911    /// Returns the [`TypeId`] of the underlying component type.
912    /// Returns `None` if the component does not correspond to a Rust type.
913    #[inline]
914    pub fn type_id(&self) -> Option<TypeId> {
915        self.descriptor.type_id
916    }
917
918    /// Returns the layout used to store values of this component in memory.
919    #[inline]
920    pub fn layout(&self) -> Layout {
921        self.descriptor.layout
922    }
923
924    #[inline]
925    /// Get the function which should be called to clean up values of
926    /// the underlying component type. This maps to the
927    /// [`Drop`] implementation for 'normal' Rust components
928    ///
929    /// Returns `None` if values of the underlying component type don't
930    /// need to be dropped, e.g. as reported by [`needs_drop`].
931    pub fn drop(&self) -> Option<unsafe fn(OwningPtr<'_>)> {
932        self.descriptor.drop
933    }
934
935    /// Returns a value indicating the storage strategy for the current component.
936    #[inline]
937    pub fn storage_type(&self) -> StorageType {
938        self.descriptor.storage_type
939    }
940
941    /// Returns `true` if the underlying component type can be freely shared between threads.
942    /// If this returns `false`, then extra care must be taken to ensure that components
943    /// are not accessed from the wrong thread.
944    #[inline]
945    pub fn is_send_and_sync(&self) -> bool {
946        self.descriptor.is_send_and_sync
947    }
948
949    /// Create a new [`ComponentInfo`].
950    pub(crate) fn new(id: ComponentId, descriptor: ComponentDescriptor) -> Self {
951        ComponentInfo {
952            id,
953            descriptor,
954            hooks: Default::default(),
955            required_components: Default::default(),
956            required_by: Default::default(),
957        }
958    }
959
960    /// Update the given flags to include any [`ComponentHook`] registered to self
961    #[inline]
962    pub(crate) fn update_archetype_flags(&self, flags: &mut ArchetypeFlags) {
963        if self.hooks().on_add.is_some() {
964            flags.insert(ArchetypeFlags::ON_ADD_HOOK);
965        }
966        if self.hooks().on_insert.is_some() {
967            flags.insert(ArchetypeFlags::ON_INSERT_HOOK);
968        }
969        if self.hooks().on_replace.is_some() {
970            flags.insert(ArchetypeFlags::ON_REPLACE_HOOK);
971        }
972        if self.hooks().on_remove.is_some() {
973            flags.insert(ArchetypeFlags::ON_REMOVE_HOOK);
974        }
975        if self.hooks().on_despawn.is_some() {
976            flags.insert(ArchetypeFlags::ON_DESPAWN_HOOK);
977        }
978    }
979
980    /// Provides a reference to the collection of hooks associated with this [`Component`]
981    pub fn hooks(&self) -> &ComponentHooks {
982        &self.hooks
983    }
984
985    /// Retrieves the [`RequiredComponents`] collection, which contains all required components (and their constructors)
986    /// needed by this component. This includes _recursive_ required components.
987    pub fn required_components(&self) -> &RequiredComponents {
988        &self.required_components
989    }
990}
991
992/// A value which uniquely identifies the type of a [`Component`] or [`Resource`] within a
993/// [`World`].
994///
995/// Each time a new `Component` type is registered within a `World` using
996/// e.g. [`World::register_component`] or [`World::register_component_with_descriptor`]
997/// or a Resource with e.g. [`World::init_resource`],
998/// a corresponding `ComponentId` is created to track it.
999///
1000/// While the distinction between `ComponentId` and [`TypeId`] may seem superficial, breaking them
1001/// into two separate but related concepts allows components to exist outside of Rust's type system.
1002/// Each Rust type registered as a `Component` will have a corresponding `ComponentId`, but additional
1003/// `ComponentId`s may exist in a `World` to track components which cannot be
1004/// represented as Rust types for scripting or other advanced use-cases.
1005///
1006/// A `ComponentId` is tightly coupled to its parent `World`. Attempting to use a `ComponentId` from
1007/// one `World` to access the metadata of a `Component` in a different `World` is undefined behavior
1008/// and must not be attempted.
1009///
1010/// Given a type `T` which implements [`Component`], the `ComponentId` for `T` can be retrieved
1011/// from a `World` using [`World::component_id()`] or via [`Components::component_id()`]. Access
1012/// to the `ComponentId` for a [`Resource`] is available via [`Components::resource_id()`].
1013#[derive(Debug, Copy, Clone, Hash, Ord, PartialOrd, Eq, PartialEq)]
1014#[cfg_attr(
1015    feature = "bevy_reflect",
1016    derive(Reflect),
1017    reflect(Debug, Hash, PartialEq, Clone)
1018)]
1019pub struct ComponentId(usize);
1020
1021impl ComponentId {
1022    /// Creates a new [`ComponentId`].
1023    ///
1024    /// The `index` is a unique value associated with each type of component in a given world.
1025    /// Usually, this value is taken from a counter incremented for each type of component registered with the world.
1026    #[inline]
1027    pub const fn new(index: usize) -> ComponentId {
1028        ComponentId(index)
1029    }
1030
1031    /// Returns the index of the current component.
1032    #[inline]
1033    pub fn index(self) -> usize {
1034        self.0
1035    }
1036}
1037
1038impl SparseSetIndex for ComponentId {
1039    #[inline]
1040    fn sparse_set_index(&self) -> usize {
1041        self.index()
1042    }
1043
1044    #[inline]
1045    fn get_sparse_set_index(value: usize) -> Self {
1046        Self(value)
1047    }
1048}
1049
1050/// A value describing a component or resource, which may or may not correspond to a Rust type.
1051#[derive(Clone)]
1052pub struct ComponentDescriptor {
1053    name: Cow<'static, str>,
1054    // SAFETY: This must remain private. It must match the statically known StorageType of the
1055    // associated rust component type if one exists.
1056    storage_type: StorageType,
1057    // SAFETY: This must remain private. It must only be set to "true" if this component is
1058    // actually Send + Sync
1059    is_send_and_sync: bool,
1060    type_id: Option<TypeId>,
1061    layout: Layout,
1062    // SAFETY: this function must be safe to call with pointers pointing to items of the type
1063    // this descriptor describes.
1064    // None if the underlying type doesn't need to be dropped
1065    drop: Option<for<'a> unsafe fn(OwningPtr<'a>)>,
1066    mutable: bool,
1067    clone_behavior: ComponentCloneBehavior,
1068}
1069
1070// We need to ignore the `drop` field in our `Debug` impl
1071impl Debug for ComponentDescriptor {
1072    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1073        f.debug_struct("ComponentDescriptor")
1074            .field("name", &self.name)
1075            .field("storage_type", &self.storage_type)
1076            .field("is_send_and_sync", &self.is_send_and_sync)
1077            .field("type_id", &self.type_id)
1078            .field("layout", &self.layout)
1079            .field("mutable", &self.mutable)
1080            .field("clone_behavior", &self.clone_behavior)
1081            .finish()
1082    }
1083}
1084
1085impl ComponentDescriptor {
1086    /// # Safety
1087    ///
1088    /// `x` must point to a valid value of type `T`.
1089    unsafe fn drop_ptr<T>(x: OwningPtr<'_>) {
1090        // SAFETY: Contract is required to be upheld by the caller.
1091        unsafe {
1092            x.drop_as::<T>();
1093        }
1094    }
1095
1096    /// Create a new `ComponentDescriptor` for the type `T`.
1097    pub fn new<T: Component>() -> Self {
1098        Self {
1099            name: Cow::Borrowed(core::any::type_name::<T>()),
1100            storage_type: T::STORAGE_TYPE,
1101            is_send_and_sync: true,
1102            type_id: Some(TypeId::of::<T>()),
1103            layout: Layout::new::<T>(),
1104            drop: needs_drop::<T>().then_some(Self::drop_ptr::<T> as _),
1105            mutable: T::Mutability::MUTABLE,
1106            clone_behavior: T::clone_behavior(),
1107        }
1108    }
1109
1110    /// Create a new `ComponentDescriptor`.
1111    ///
1112    /// # Safety
1113    /// - the `drop` fn must be usable on a pointer with a value of the layout `layout`
1114    /// - the component type must be safe to access from any thread (Send + Sync in rust terms)
1115    pub unsafe fn new_with_layout(
1116        name: impl Into<Cow<'static, str>>,
1117        storage_type: StorageType,
1118        layout: Layout,
1119        drop: Option<for<'a> unsafe fn(OwningPtr<'a>)>,
1120        mutable: bool,
1121        clone_behavior: ComponentCloneBehavior,
1122    ) -> Self {
1123        Self {
1124            name: name.into(),
1125            storage_type,
1126            is_send_and_sync: true,
1127            type_id: None,
1128            layout,
1129            drop,
1130            mutable,
1131            clone_behavior,
1132        }
1133    }
1134
1135    /// Create a new `ComponentDescriptor` for a resource.
1136    ///
1137    /// The [`StorageType`] for resources is always [`StorageType::Table`].
1138    pub fn new_resource<T: Resource>() -> Self {
1139        Self {
1140            name: Cow::Borrowed(core::any::type_name::<T>()),
1141            // PERF: `SparseStorage` may actually be a more
1142            // reasonable choice as `storage_type` for resources.
1143            storage_type: StorageType::Table,
1144            is_send_and_sync: true,
1145            type_id: Some(TypeId::of::<T>()),
1146            layout: Layout::new::<T>(),
1147            drop: needs_drop::<T>().then_some(Self::drop_ptr::<T> as _),
1148            mutable: true,
1149            clone_behavior: ComponentCloneBehavior::Default,
1150        }
1151    }
1152
1153    fn new_non_send<T: Any>(storage_type: StorageType) -> Self {
1154        Self {
1155            name: Cow::Borrowed(core::any::type_name::<T>()),
1156            storage_type,
1157            is_send_and_sync: false,
1158            type_id: Some(TypeId::of::<T>()),
1159            layout: Layout::new::<T>(),
1160            drop: needs_drop::<T>().then_some(Self::drop_ptr::<T> as _),
1161            mutable: true,
1162            clone_behavior: ComponentCloneBehavior::Default,
1163        }
1164    }
1165
1166    /// Returns a value indicating the storage strategy for the current component.
1167    #[inline]
1168    pub fn storage_type(&self) -> StorageType {
1169        self.storage_type
1170    }
1171
1172    /// Returns the [`TypeId`] of the underlying component type.
1173    /// Returns `None` if the component does not correspond to a Rust type.
1174    #[inline]
1175    pub fn type_id(&self) -> Option<TypeId> {
1176        self.type_id
1177    }
1178
1179    /// Returns the name of the current component.
1180    #[inline]
1181    pub fn name(&self) -> &str {
1182        self.name.as_ref()
1183    }
1184
1185    /// Returns whether this component is mutable.
1186    #[inline]
1187    pub fn mutable(&self) -> bool {
1188        self.mutable
1189    }
1190}
1191
1192/// Function type that can be used to clone an entity.
1193pub type ComponentCloneFn = fn(&SourceComponent, &mut ComponentCloneCtx);
1194
1195/// The clone behavior to use when cloning a [`Component`].
1196#[derive(Clone, Debug, Default, PartialEq, Eq)]
1197pub enum ComponentCloneBehavior {
1198    /// Uses the default behavior (which is passed to [`ComponentCloneBehavior::resolve`])
1199    #[default]
1200    Default,
1201    /// Do not clone this component.
1202    Ignore,
1203    /// Uses a custom [`ComponentCloneFn`].
1204    Custom(ComponentCloneFn),
1205}
1206
1207impl ComponentCloneBehavior {
1208    /// Set clone handler based on `Clone` trait.
1209    ///
1210    /// If set as a handler for a component that is not the same as the one used to create this handler, it will panic.
1211    pub fn clone<C: Component + Clone>() -> Self {
1212        Self::Custom(component_clone_via_clone::<C>)
1213    }
1214
1215    /// Set clone handler based on `Reflect` trait.
1216    #[cfg(feature = "bevy_reflect")]
1217    pub fn reflect() -> Self {
1218        Self::Custom(component_clone_via_reflect)
1219    }
1220
1221    /// Returns the "global default"
1222    pub fn global_default_fn() -> ComponentCloneFn {
1223        #[cfg(feature = "bevy_reflect")]
1224        return component_clone_via_reflect;
1225        #[cfg(not(feature = "bevy_reflect"))]
1226        return component_clone_ignore;
1227    }
1228
1229    /// Resolves the [`ComponentCloneBehavior`] to a [`ComponentCloneFn`]. If [`ComponentCloneBehavior::Default`] is
1230    /// specified, the given `default` function will be used.
1231    pub fn resolve(&self, default: ComponentCloneFn) -> ComponentCloneFn {
1232        match self {
1233            ComponentCloneBehavior::Default => default,
1234            ComponentCloneBehavior::Ignore => component_clone_ignore,
1235            ComponentCloneBehavior::Custom(custom) => *custom,
1236        }
1237    }
1238}
1239
1240/// A queued component registration.
1241struct QueuedRegistration {
1242    registrator: Box<dyn FnOnce(&mut ComponentsRegistrator, ComponentId)>,
1243    id: ComponentId,
1244}
1245
1246impl QueuedRegistration {
1247    /// Creates the [`QueuedRegistration`].
1248    ///
1249    /// # Safety
1250    ///
1251    /// [`ComponentId`] must be unique.
1252    unsafe fn new(
1253        id: ComponentId,
1254        func: impl FnOnce(&mut ComponentsRegistrator, ComponentId) + 'static,
1255    ) -> Self {
1256        Self {
1257            registrator: Box::new(func),
1258            id,
1259        }
1260    }
1261
1262    /// Performs the registration, returning the now valid [`ComponentId`].
1263    fn register(self, registrator: &mut ComponentsRegistrator) -> ComponentId {
1264        (self.registrator)(registrator, self.id);
1265        self.id
1266    }
1267}
1268
1269/// Allows queuing components to be registered.
1270#[derive(Default)]
1271pub struct QueuedComponents {
1272    components: TypeIdMap<QueuedRegistration>,
1273    resources: TypeIdMap<QueuedRegistration>,
1274    dynamic_registrations: Vec<QueuedRegistration>,
1275}
1276
1277impl Debug for QueuedComponents {
1278    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1279        let components = self
1280            .components
1281            .iter()
1282            .map(|(type_id, queued)| (type_id, queued.id))
1283            .collect::<Vec<_>>();
1284        let resources = self
1285            .resources
1286            .iter()
1287            .map(|(type_id, queued)| (type_id, queued.id))
1288            .collect::<Vec<_>>();
1289        let dynamic_registrations = self
1290            .dynamic_registrations
1291            .iter()
1292            .map(|queued| queued.id)
1293            .collect::<Vec<_>>();
1294        write!(f, "components: {components:?}, resources: {resources:?}, dynamic_registrations: {dynamic_registrations:?}")
1295    }
1296}
1297
1298/// Generates [`ComponentId`]s.
1299#[derive(Debug, Default)]
1300pub struct ComponentIds {
1301    next: bevy_platform_support::sync::atomic::AtomicUsize,
1302}
1303
1304impl ComponentIds {
1305    /// Peeks the next [`ComponentId`] to be generated without generating it.
1306    pub fn peek(&self) -> ComponentId {
1307        ComponentId(
1308            self.next
1309                .load(bevy_platform_support::sync::atomic::Ordering::Relaxed),
1310        )
1311    }
1312
1313    /// Generates and returns the next [`ComponentId`].
1314    pub fn next(&self) -> ComponentId {
1315        ComponentId(
1316            self.next
1317                .fetch_add(1, bevy_platform_support::sync::atomic::Ordering::Relaxed),
1318        )
1319    }
1320
1321    /// Peeks the next [`ComponentId`] to be generated without generating it.
1322    pub fn peek_mut(&mut self) -> ComponentId {
1323        ComponentId(*self.next.get_mut())
1324    }
1325
1326    /// Generates and returns the next [`ComponentId`].
1327    pub fn next_mut(&mut self) -> ComponentId {
1328        let id = self.next.get_mut();
1329        let result = ComponentId(*id);
1330        *id += 1;
1331        result
1332    }
1333
1334    /// Returns the number of [`ComponentId`]s generated.
1335    pub fn len(&self) -> usize {
1336        self.peek().0
1337    }
1338
1339    /// Returns true if and only if no ids have been generated.
1340    pub fn is_empty(&self) -> bool {
1341        self.len() == 0
1342    }
1343}
1344
1345/// A type that enables queuing registration in [`Components`].
1346///
1347/// # Note
1348///
1349/// These queued registrations return [`ComponentId`]s.
1350/// These ids are not yet valid, but they will become valid
1351/// when either [`ComponentsRegistrator::apply_queued_registrations`] is called or the same registration is made directly.
1352/// In either case, the returned [`ComponentId`]s will be correct, but they are not correct yet.
1353///
1354/// Generally, that means these [`ComponentId`]s can be safely used for read-only purposes.
1355/// Modifying the contents of the world through these [`ComponentId`]s directly without waiting for them to be fully registered
1356/// and without then confirming that they have been fully registered is not supported.
1357/// Hence, extra care is needed with these [`ComponentId`]s to ensure all safety rules are followed.
1358///
1359/// As a rule of thumb, if you have mutable access to [`ComponentsRegistrator`], prefer to use that instead.
1360/// Use this only if you need to know the id of a component but do not need to modify the contents of the world based on that id.
1361pub struct ComponentsQueuedRegistrator<'w> {
1362    components: &'w Components,
1363    ids: &'w ComponentIds,
1364}
1365
1366impl Deref for ComponentsQueuedRegistrator<'_> {
1367    type Target = Components;
1368
1369    fn deref(&self) -> &Self::Target {
1370        self.components
1371    }
1372}
1373
1374impl<'w> ComponentsQueuedRegistrator<'w> {
1375    /// Constructs a new [`ComponentsQueuedRegistrator`].
1376    ///
1377    /// # Safety
1378    ///
1379    /// The [`Components`] and [`ComponentIds`] must match.
1380    /// For example, they must be from the same world.
1381    pub unsafe fn new(components: &'w Components, ids: &'w ComponentIds) -> Self {
1382        Self { components, ids }
1383    }
1384
1385    /// Queues this function to run as a component registrator.
1386    ///
1387    /// # Safety
1388    ///
1389    /// The [`TypeId`] must not already be registered or queued as a component.
1390    unsafe fn force_register_arbitrary_component(
1391        &self,
1392        type_id: TypeId,
1393        func: impl FnOnce(&mut ComponentsRegistrator, ComponentId) + 'static,
1394    ) -> ComponentId {
1395        let id = self.ids.next();
1396        self.components
1397            .queued
1398            .write()
1399            .unwrap_or_else(PoisonError::into_inner)
1400            .components
1401            .insert(
1402                type_id,
1403                // SAFETY: The id was just generated.
1404                unsafe { QueuedRegistration::new(id, func) },
1405            );
1406        id
1407    }
1408
1409    /// Queues this function to run as a resource registrator.
1410    ///
1411    /// # Safety
1412    ///
1413    /// The [`TypeId`] must not already be registered or queued as a resource.
1414    unsafe fn force_register_arbitrary_resource(
1415        &self,
1416        type_id: TypeId,
1417        func: impl FnOnce(&mut ComponentsRegistrator, ComponentId) + 'static,
1418    ) -> ComponentId {
1419        let id = self.ids.next();
1420        self.components
1421            .queued
1422            .write()
1423            .unwrap_or_else(PoisonError::into_inner)
1424            .resources
1425            .insert(
1426                type_id,
1427                // SAFETY: The id was just generated.
1428                unsafe { QueuedRegistration::new(id, func) },
1429            );
1430        id
1431    }
1432
1433    /// Queues this function to run as a dynamic registrator.
1434    fn force_register_arbitrary_dynamic(
1435        &self,
1436        func: impl FnOnce(&mut ComponentsRegistrator, ComponentId) + 'static,
1437    ) -> ComponentId {
1438        let id = self.ids.next();
1439        self.components
1440            .queued
1441            .write()
1442            .unwrap_or_else(PoisonError::into_inner)
1443            .dynamic_registrations
1444            .push(
1445                // SAFETY: The id was just generated.
1446                unsafe { QueuedRegistration::new(id, func) },
1447            );
1448        id
1449    }
1450
1451    /// This is a queued version of [`ComponentsRegistrator::register_component`].
1452    /// This will reserve an id and queue the registration.
1453    /// These registrations will be carried out at the next opportunity.
1454    ///
1455    /// # Note
1456    ///
1457    /// Technically speaking, the returned [`ComponentId`] is not valid, but it will become valid later.
1458    /// See type level docs for details.
1459    #[inline]
1460    pub fn queue_register_component<T: Component>(&self) -> ComponentId {
1461        self.component_id::<T>().unwrap_or_else(|| {
1462            // SAFETY: We just checked that this type was not in the queue.
1463            unsafe {
1464                self.force_register_arbitrary_component(TypeId::of::<T>(), |registrator, id| {
1465                    // SAFETY: We just checked that this is not currently registered or queued, and if it was registered since, this would have been dropped from the queue.
1466                    #[expect(unused_unsafe, reason = "More precise to specify.")]
1467                    unsafe {
1468                        registrator.register_component_unchecked::<T>(&mut Vec::new(), id);
1469                    }
1470                })
1471            }
1472        })
1473    }
1474
1475    /// This is a queued version of [`ComponentsRegistrator::register_component_with_descriptor`].
1476    /// This will reserve an id and queue the registration.
1477    /// These registrations will be carried out at the next opportunity.
1478    ///
1479    /// # Note
1480    ///
1481    /// Technically speaking, the returned [`ComponentId`] is not valid, but it will become valid later.
1482    /// See type level docs for details.
1483    #[inline]
1484    pub fn queue_register_component_with_descriptor(
1485        &self,
1486        descriptor: ComponentDescriptor,
1487    ) -> ComponentId {
1488        self.force_register_arbitrary_dynamic(|registrator, id| {
1489            // SAFETY: Id uniqueness handled by caller.
1490            unsafe {
1491                registrator.register_component_inner(id, descriptor);
1492            }
1493        })
1494    }
1495
1496    /// This is a queued version of [`ComponentsRegistrator::register_resource`].
1497    /// This will reserve an id and queue the registration.
1498    /// These registrations will be carried out at the next opportunity.
1499    ///
1500    /// # Note
1501    ///
1502    /// Technically speaking, the returned [`ComponentId`] is not valid, but it will become valid later.
1503    /// See type level docs for details.
1504    #[inline]
1505    pub fn queue_register_resource<T: Resource>(&self) -> ComponentId {
1506        let type_id = TypeId::of::<T>();
1507        self.get_resource_id(type_id).unwrap_or_else(|| {
1508            // SAFETY: We just checked that this type was not in the queue.
1509            unsafe {
1510                self.force_register_arbitrary_resource(type_id, move |registrator, id| {
1511                    // SAFETY: We just checked that this is not currently registered or queued, and if it was registered since, this would have been dropped from the queue.
1512                    // SAFETY: Id uniqueness handled by caller, and the type_id matches descriptor.
1513                    #[expect(unused_unsafe, reason = "More precise to specify.")]
1514                    unsafe {
1515                        registrator.register_resource_unchecked_with(type_id, id, || {
1516                            ComponentDescriptor::new_resource::<T>()
1517                        });
1518                    }
1519                })
1520            }
1521        })
1522    }
1523
1524    /// This is a queued version of [`ComponentsRegistrator::register_non_send`].
1525    /// This will reserve an id and queue the registration.
1526    /// These registrations will be carried out at the next opportunity.
1527    ///
1528    /// # Note
1529    ///
1530    /// Technically speaking, the returned [`ComponentId`] is not valid, but it will become valid later.
1531    /// See type level docs for details.
1532    #[inline]
1533    pub fn queue_register_non_send<T: Any>(&self) -> ComponentId {
1534        let type_id = TypeId::of::<T>();
1535        self.get_resource_id(type_id).unwrap_or_else(|| {
1536            // SAFETY: We just checked that this type was not in the queue.
1537            unsafe {
1538                self.force_register_arbitrary_resource(type_id, move |registrator, id| {
1539                    // SAFETY: We just checked that this is not currently registered or queued, and if it was registered since, this would have been dropped from the queue.
1540                    // SAFETY: Id uniqueness handled by caller, and the type_id matches descriptor.
1541                    #[expect(unused_unsafe, reason = "More precise to specify.")]
1542                    unsafe {
1543                        registrator.register_resource_unchecked_with(type_id, id, || {
1544                            ComponentDescriptor::new_non_send::<T>(StorageType::default())
1545                        });
1546                    }
1547                })
1548            }
1549        })
1550    }
1551
1552    /// This is a queued version of [`ComponentsRegistrator::register_resource_with_descriptor`].
1553    /// This will reserve an id and queue the registration.
1554    /// These registrations will be carried out at the next opportunity.
1555    ///
1556    /// # Note
1557    ///
1558    /// Technically speaking, the returned [`ComponentId`] is not valid, but it will become valid later.
1559    /// See type level docs for details.
1560    #[inline]
1561    pub fn queue_register_resource_with_descriptor(
1562        &self,
1563        descriptor: ComponentDescriptor,
1564    ) -> ComponentId {
1565        self.force_register_arbitrary_dynamic(|registrator, id| {
1566            // SAFETY: Id uniqueness handled by caller.
1567            unsafe {
1568                registrator.register_component_inner(id, descriptor);
1569            }
1570        })
1571    }
1572}
1573
1574/// A [`Components`] wrapper that enables additional features, like registration.
1575pub struct ComponentsRegistrator<'w> {
1576    components: &'w mut Components,
1577    ids: &'w mut ComponentIds,
1578}
1579
1580impl Deref for ComponentsRegistrator<'_> {
1581    type Target = Components;
1582
1583    fn deref(&self) -> &Self::Target {
1584        self.components
1585    }
1586}
1587
1588impl DerefMut for ComponentsRegistrator<'_> {
1589    fn deref_mut(&mut self) -> &mut Self::Target {
1590        self.components
1591    }
1592}
1593
1594impl<'w> ComponentsRegistrator<'w> {
1595    /// Constructs a new [`ComponentsRegistrator`].
1596    ///
1597    /// # Safety
1598    ///
1599    /// The [`Components`] and [`ComponentIds`] must match.
1600    /// For example, they must be from the same world.
1601    pub unsafe fn new(components: &'w mut Components, ids: &'w mut ComponentIds) -> Self {
1602        Self { components, ids }
1603    }
1604
1605    /// Converts this [`ComponentsRegistrator`] into a [`ComponentsQueuedRegistrator`].
1606    /// This is intended for use to pass this value to a function that requires [`ComponentsQueuedRegistrator`].
1607    /// It is generally not a good idea to queue a registration when you can instead register directly on this type.
1608    pub fn as_queued(&self) -> ComponentsQueuedRegistrator<'_> {
1609        // SAFETY: ensured by the caller that created self.
1610        unsafe { ComponentsQueuedRegistrator::new(self.components, self.ids) }
1611    }
1612
1613    /// Applies every queued registration.
1614    /// This ensures that every valid [`ComponentId`] is registered,
1615    /// enabling retrieving [`ComponentInfo`], etc.
1616    pub fn apply_queued_registrations(&mut self) {
1617        if !self.any_queued_mut() {
1618            return;
1619        }
1620
1621        // Note:
1622        //
1623        // This is not just draining the queue. We need to empty the queue without removing the information from `Components`.
1624        // If we drained directly, we could break invariance.
1625        //
1626        // For example, say `ComponentA` and `ComponentB` are queued, and `ComponentA` requires `ComponentB`.
1627        // If we drain directly, and `ComponentA` was the first to be registered, then, when `ComponentA`
1628        // registers `ComponentB` in `Component::register_required_components`,
1629        // `Components` will not know that `ComponentB` was queued
1630        // (since it will have been drained from the queue.)
1631        // If that happened, `Components` would assign a new `ComponentId` to `ComponentB`
1632        // which would be *different* than the id it was assigned in the queue.
1633        // Then, when the drain iterator gets to `ComponentB`,
1634        // it would be unsafely registering `ComponentB`, which is already registered.
1635        //
1636        // As a result, we need to pop from each queue one by one instead of draining.
1637
1638        // components
1639        while let Some(registrator) = {
1640            let queued = self
1641                .components
1642                .queued
1643                .get_mut()
1644                .unwrap_or_else(PoisonError::into_inner);
1645            queued.components.keys().next().copied().map(|type_id| {
1646                // SAFETY: the id just came from a valid iterator.
1647                unsafe { queued.components.remove(&type_id).debug_checked_unwrap() }
1648            })
1649        } {
1650            registrator.register(self);
1651        }
1652
1653        // resources
1654        while let Some(registrator) = {
1655            let queued = self
1656                .components
1657                .queued
1658                .get_mut()
1659                .unwrap_or_else(PoisonError::into_inner);
1660            queued.resources.keys().next().copied().map(|type_id| {
1661                // SAFETY: the id just came from a valid iterator.
1662                unsafe { queued.resources.remove(&type_id).debug_checked_unwrap() }
1663            })
1664        } {
1665            registrator.register(self);
1666        }
1667
1668        // dynamic
1669        let queued = &mut self
1670            .components
1671            .queued
1672            .get_mut()
1673            .unwrap_or_else(PoisonError::into_inner);
1674        if !queued.dynamic_registrations.is_empty() {
1675            for registrator in core::mem::take(&mut queued.dynamic_registrations) {
1676                registrator.register(self);
1677            }
1678        }
1679    }
1680
1681    /// Registers a [`Component`] of type `T` with this instance.
1682    /// If a component of this type has already been registered, this will return
1683    /// the ID of the pre-existing component.
1684    ///
1685    /// # See also
1686    ///
1687    /// * [`Components::component_id()`]
1688    /// * [`ComponentsRegistrator::register_component_with_descriptor()`]
1689    #[inline]
1690    pub fn register_component<T: Component>(&mut self) -> ComponentId {
1691        self.register_component_checked::<T>(&mut Vec::new())
1692    }
1693
1694    /// Same as [`Self::register_component_unchecked`] but keeps a checks for safety.
1695    #[inline]
1696    fn register_component_checked<T: Component>(
1697        &mut self,
1698        recursion_check_stack: &mut Vec<ComponentId>,
1699    ) -> ComponentId {
1700        let type_id = TypeId::of::<T>();
1701        if let Some(id) = self.indices.get(&type_id) {
1702            return *id;
1703        }
1704
1705        if let Some(registrator) = self
1706            .components
1707            .queued
1708            .get_mut()
1709            .unwrap_or_else(PoisonError::into_inner)
1710            .components
1711            .remove(&type_id)
1712        {
1713            // If we are trying to register something that has already been queued, we respect the queue.
1714            // Just like if we are trying to register something that already is, we respect the first registration.
1715            return registrator.register(self);
1716        }
1717
1718        let id = self.ids.next_mut();
1719        // SAFETY: The component is not currently registered, and the id is fresh.
1720        unsafe {
1721            self.register_component_unchecked::<T>(recursion_check_stack, id);
1722        }
1723        id
1724    }
1725
1726    /// # Safety
1727    ///
1728    /// Neither this component, nor its id may be registered or queued. This must be a new registration.
1729    #[inline]
1730    unsafe fn register_component_unchecked<T: Component>(
1731        &mut self,
1732        recursion_check_stack: &mut Vec<ComponentId>,
1733        id: ComponentId,
1734    ) {
1735        // SAFETY: ensured by caller.
1736        unsafe {
1737            self.register_component_inner(id, ComponentDescriptor::new::<T>());
1738        }
1739        let type_id = TypeId::of::<T>();
1740        let prev = self.indices.insert(type_id, id);
1741        debug_assert!(prev.is_none());
1742
1743        let mut required_components = RequiredComponents::default();
1744        T::register_required_components(
1745            id,
1746            self,
1747            &mut required_components,
1748            0,
1749            recursion_check_stack,
1750        );
1751        // SAFETY: we just inserted it in `register_component_inner`
1752        let info = unsafe {
1753            &mut self
1754                .components
1755                .components
1756                .get_mut(id.0)
1757                .debug_checked_unwrap()
1758                .as_mut()
1759                .debug_checked_unwrap()
1760        };
1761
1762        #[expect(
1763            deprecated,
1764            reason = "need to use this method until it is removed to ensure user defined components register hooks correctly"
1765        )]
1766        // TODO: Replace with `info.hooks.update_from_component::<T>();` once `Component::register_component_hooks` is removed
1767        T::register_component_hooks(&mut info.hooks);
1768
1769        info.required_components = required_components;
1770    }
1771
1772    /// Registers a component described by `descriptor`.
1773    ///
1774    /// # Note
1775    ///
1776    /// If this method is called multiple times with identical descriptors, a distinct [`ComponentId`]
1777    /// will be created for each one.
1778    ///
1779    /// # See also
1780    ///
1781    /// * [`Components::component_id()`]
1782    /// * [`ComponentsRegistrator::register_component()`]
1783    #[inline]
1784    pub fn register_component_with_descriptor(
1785        &mut self,
1786        descriptor: ComponentDescriptor,
1787    ) -> ComponentId {
1788        let id = self.ids.next_mut();
1789        // SAFETY: The id is fresh.
1790        unsafe {
1791            self.register_component_inner(id, descriptor);
1792        }
1793        id
1794    }
1795
1796    // NOTE: This should maybe be private, but it is currently public so that `bevy_ecs_macros` can use it.
1797    //       We can't directly move this there either, because this uses `Components::get_required_by_mut`,
1798    //       which is private, and could be equally risky to expose to users.
1799    /// Registers the given component `R` and [required components] inherited from it as required by `T`,
1800    /// and adds `T` to their lists of requirees.
1801    ///
1802    /// The given `inheritance_depth` determines how many levels of inheritance deep the requirement is.
1803    /// A direct requirement has a depth of `0`, and each level of inheritance increases the depth by `1`.
1804    /// Lower depths are more specific requirements, and can override existing less specific registrations.
1805    ///
1806    /// The `recursion_check_stack` allows checking whether this component tried to register itself as its
1807    /// own (indirect) required component.
1808    ///
1809    /// This method does *not* register any components as required by components that require `T`.
1810    ///
1811    /// Only use this method if you know what you are doing. In most cases, you should instead use [`World::register_required_components`],
1812    /// or the equivalent method in `bevy_app::App`.
1813    ///
1814    /// [required component]: Component#required-components
1815    #[doc(hidden)]
1816    pub fn register_required_components_manual<T: Component, R: Component>(
1817        &mut self,
1818        required_components: &mut RequiredComponents,
1819        constructor: fn() -> R,
1820        inheritance_depth: u16,
1821        recursion_check_stack: &mut Vec<ComponentId>,
1822    ) {
1823        let requiree = self.register_component_checked::<T>(recursion_check_stack);
1824        let required = self.register_component_checked::<R>(recursion_check_stack);
1825
1826        // SAFETY: We just created the components.
1827        unsafe {
1828            self.register_required_components_manual_unchecked::<R>(
1829                requiree,
1830                required,
1831                required_components,
1832                constructor,
1833                inheritance_depth,
1834            );
1835        }
1836    }
1837
1838    /// Registers a [`Resource`] of type `T` with this instance.
1839    /// If a resource of this type has already been registered, this will return
1840    /// the ID of the pre-existing resource.
1841    ///
1842    /// # See also
1843    ///
1844    /// * [`Components::resource_id()`]
1845    /// * [`ComponentsRegistrator::register_resource_with_descriptor()`]
1846    #[inline]
1847    pub fn register_resource<T: Resource>(&mut self) -> ComponentId {
1848        // SAFETY: The [`ComponentDescriptor`] matches the [`TypeId`]
1849        unsafe {
1850            self.register_resource_with(TypeId::of::<T>(), || {
1851                ComponentDescriptor::new_resource::<T>()
1852            })
1853        }
1854    }
1855
1856    /// Registers a [non-send resource](crate::system::NonSend) of type `T` with this instance.
1857    /// If a resource of this type has already been registered, this will return
1858    /// the ID of the pre-existing resource.
1859    #[inline]
1860    pub fn register_non_send<T: Any>(&mut self) -> ComponentId {
1861        // SAFETY: The [`ComponentDescriptor`] matches the [`TypeId`]
1862        unsafe {
1863            self.register_resource_with(TypeId::of::<T>(), || {
1864                ComponentDescriptor::new_non_send::<T>(StorageType::default())
1865            })
1866        }
1867    }
1868
1869    /// Same as [`Components::register_resource_unchecked_with`] but handles safety.
1870    ///
1871    /// # Safety
1872    ///
1873    /// The [`ComponentDescriptor`] must match the [`TypeId`].
1874    #[inline]
1875    unsafe fn register_resource_with(
1876        &mut self,
1877        type_id: TypeId,
1878        descriptor: impl FnOnce() -> ComponentDescriptor,
1879    ) -> ComponentId {
1880        if let Some(id) = self.resource_indices.get(&type_id) {
1881            return *id;
1882        }
1883
1884        if let Some(registrator) = self
1885            .components
1886            .queued
1887            .get_mut()
1888            .unwrap_or_else(PoisonError::into_inner)
1889            .resources
1890            .remove(&type_id)
1891        {
1892            // If we are trying to register something that has already been queued, we respect the queue.
1893            // Just like if we are trying to register something that already is, we respect the first registration.
1894            return registrator.register(self);
1895        }
1896
1897        let id = self.ids.next_mut();
1898        // SAFETY: The resource is not currently registered, the id is fresh, and the [`ComponentDescriptor`] matches the [`TypeId`]
1899        unsafe {
1900            self.register_resource_unchecked_with(type_id, id, descriptor);
1901        }
1902        id
1903    }
1904
1905    /// Registers a [`Resource`] described by `descriptor`.
1906    ///
1907    /// # Note
1908    ///
1909    /// If this method is called multiple times with identical descriptors, a distinct [`ComponentId`]
1910    /// will be created for each one.
1911    ///
1912    /// # See also
1913    ///
1914    /// * [`Components::resource_id()`]
1915    /// * [`ComponentsRegistrator::register_resource()`]
1916    #[inline]
1917    pub fn register_resource_with_descriptor(
1918        &mut self,
1919        descriptor: ComponentDescriptor,
1920    ) -> ComponentId {
1921        let id = self.ids.next_mut();
1922        // SAFETY: The id is fresh.
1923        unsafe {
1924            self.register_component_inner(id, descriptor);
1925        }
1926        id
1927    }
1928}
1929
1930/// Stores metadata associated with each kind of [`Component`] in a given [`World`].
1931#[derive(Debug, Default)]
1932pub struct Components {
1933    components: Vec<Option<ComponentInfo>>,
1934    indices: TypeIdMap<ComponentId>,
1935    resource_indices: TypeIdMap<ComponentId>,
1936    // This is kept internal and local to verify that no deadlocks can occor.
1937    queued: bevy_platform_support::sync::RwLock<QueuedComponents>,
1938}
1939
1940impl Components {
1941    /// This registers any descriptor, component or resource.
1942    ///
1943    /// # Safety
1944    ///
1945    /// The id must have never been registered before. This must be a fresh registration.
1946    #[inline]
1947    unsafe fn register_component_inner(
1948        &mut self,
1949        id: ComponentId,
1950        descriptor: ComponentDescriptor,
1951    ) {
1952        let info = ComponentInfo::new(id, descriptor);
1953        let least_len = id.0 + 1;
1954        if self.components.len() < least_len {
1955            self.components.resize_with(least_len, || None);
1956        }
1957        // SAFETY: We just extended the vec to make this index valid.
1958        let slot = unsafe { self.components.get_mut(id.0).debug_checked_unwrap() };
1959        // Caller ensures id is unique
1960        debug_assert!(slot.is_none());
1961        *slot = Some(info);
1962    }
1963
1964    /// Returns the number of components registered or queued with this instance.
1965    #[inline]
1966    pub fn len(&self) -> usize {
1967        self.num_queued() + self.num_registered()
1968    }
1969
1970    /// Returns `true` if there are no components registered or queued with this instance. Otherwise, this returns `false`.
1971    #[inline]
1972    pub fn is_empty(&self) -> bool {
1973        self.len() == 0
1974    }
1975
1976    /// Returns the number of components registered with this instance.
1977    #[inline]
1978    pub fn num_queued(&self) -> usize {
1979        let queued = self.queued.read().unwrap_or_else(PoisonError::into_inner);
1980        queued.components.len() + queued.dynamic_registrations.len() + queued.resources.len()
1981    }
1982
1983    /// Returns `true` if there are any components registered with this instance. Otherwise, this returns `false`.
1984    #[inline]
1985    pub fn any_queued(&self) -> bool {
1986        self.num_queued() > 0
1987    }
1988
1989    /// A faster version of [`Self::num_queued`].
1990    #[inline]
1991    pub fn num_queued_mut(&mut self) -> usize {
1992        let queued = self
1993            .queued
1994            .get_mut()
1995            .unwrap_or_else(PoisonError::into_inner);
1996        queued.components.len() + queued.dynamic_registrations.len() + queued.resources.len()
1997    }
1998
1999    /// A faster version of [`Self::any_queued`].
2000    #[inline]
2001    pub fn any_queued_mut(&mut self) -> bool {
2002        self.num_queued_mut() > 0
2003    }
2004
2005    /// Returns the number of components registered with this instance.
2006    #[inline]
2007    pub fn num_registered(&self) -> usize {
2008        self.components.len()
2009    }
2010
2011    /// Returns `true` if there are any components registered with this instance. Otherwise, this returns `false`.
2012    #[inline]
2013    pub fn any_registered(&self) -> bool {
2014        self.num_registered() > 0
2015    }
2016
2017    /// Gets the metadata associated with the given component, if it is registered.
2018    /// This will return `None` if the id is not regiserted or is queued.
2019    ///
2020    /// This will return an incorrect result if `id` did not come from the same world as `self`. It may return `None` or a garbage value.
2021    #[inline]
2022    pub fn get_info(&self, id: ComponentId) -> Option<&ComponentInfo> {
2023        self.components.get(id.0).and_then(|info| info.as_ref())
2024    }
2025
2026    /// Returns the name associated with the given component, if it is registered.
2027    /// This will return `None` if the id is not regiserted or is queued.
2028    ///
2029    /// This will return an incorrect result if `id` did not come from the same world as `self`. It may return `None` or a garbage value.
2030    #[inline]
2031    pub fn get_name(&self, id: ComponentId) -> Option<&str> {
2032        self.get_info(id).map(ComponentInfo::name)
2033    }
2034
2035    /// Gets the metadata associated with the given component.
2036    /// # Safety
2037    ///
2038    /// `id` must be a valid and fully registered [`ComponentId`].
2039    #[inline]
2040    pub unsafe fn get_info_unchecked(&self, id: ComponentId) -> &ComponentInfo {
2041        // SAFETY: The caller ensures `id` is valid.
2042        unsafe {
2043            self.components
2044                .get(id.0)
2045                .debug_checked_unwrap()
2046                .as_ref()
2047                .debug_checked_unwrap()
2048        }
2049    }
2050
2051    #[inline]
2052    pub(crate) fn get_hooks_mut(&mut self, id: ComponentId) -> Option<&mut ComponentHooks> {
2053        self.components
2054            .get_mut(id.0)
2055            .and_then(|info| info.as_mut().map(|info| &mut info.hooks))
2056    }
2057
2058    #[inline]
2059    pub(crate) fn get_required_components_mut(
2060        &mut self,
2061        id: ComponentId,
2062    ) -> Option<&mut RequiredComponents> {
2063        self.components
2064            .get_mut(id.0)
2065            .and_then(|info| info.as_mut().map(|info| &mut info.required_components))
2066    }
2067
2068    /// Registers the given component `R` and [required components] inherited from it as required by `T`.
2069    ///
2070    /// When `T` is added to an entity, `R` will also be added if it was not already provided.
2071    /// The given `constructor` will be used for the creation of `R`.
2072    ///
2073    /// [required components]: Component#required-components
2074    ///
2075    /// # Safety
2076    ///
2077    /// The given component IDs `required` and `requiree` must be valid.
2078    ///
2079    /// # Errors
2080    ///
2081    /// Returns a [`RequiredComponentsError`] if the `required` component is already a directly required component for the `requiree`.
2082    ///
2083    /// Indirect requirements through other components are allowed. In those cases, the more specific
2084    /// registration will be used.
2085    pub(crate) unsafe fn register_required_components<R: Component>(
2086        &mut self,
2087        requiree: ComponentId,
2088        required: ComponentId,
2089        constructor: fn() -> R,
2090    ) -> Result<(), RequiredComponentsError> {
2091        // SAFETY: The caller ensures that the `requiree` is valid.
2092        let required_components = unsafe {
2093            self.get_required_components_mut(requiree)
2094                .debug_checked_unwrap()
2095        };
2096
2097        // Cannot directly require the same component twice.
2098        if required_components
2099            .0
2100            .get(&required)
2101            .is_some_and(|c| c.inheritance_depth == 0)
2102        {
2103            return Err(RequiredComponentsError::DuplicateRegistration(
2104                requiree, required,
2105            ));
2106        }
2107
2108        // Register the required component for the requiree.
2109        // This is a direct requirement with a depth of `0`.
2110        required_components.register_by_id(required, constructor, 0);
2111
2112        // Add the requiree to the list of components that require the required component.
2113        // SAFETY: The component is in the list of required components, so it must exist already.
2114        let required_by = unsafe { self.get_required_by_mut(required).debug_checked_unwrap() };
2115        required_by.insert(requiree);
2116
2117        let mut required_components_tmp = RequiredComponents::default();
2118        // SAFETY: The caller ensures that the `requiree` and `required` components are valid.
2119        let inherited_requirements = unsafe {
2120            self.register_inherited_required_components(
2121                requiree,
2122                required,
2123                &mut required_components_tmp,
2124            )
2125        };
2126
2127        // SAFETY: The caller ensures that the `requiree` is valid.
2128        let required_components = unsafe {
2129            self.get_required_components_mut(requiree)
2130                .debug_checked_unwrap()
2131        };
2132        required_components.0.extend(required_components_tmp.0);
2133
2134        // Propagate the new required components up the chain to all components that require the requiree.
2135        if let Some(required_by) = self
2136            .get_required_by(requiree)
2137            .map(|set| set.iter().copied().collect::<SmallVec<[ComponentId; 8]>>())
2138        {
2139            // `required` is now required by anything that `requiree` was required by.
2140            self.get_required_by_mut(required)
2141                .unwrap()
2142                .extend(required_by.iter().copied());
2143            for &required_by_id in required_by.iter() {
2144                // SAFETY: The component is in the list of required components, so it must exist already.
2145                let required_components = unsafe {
2146                    self.get_required_components_mut(required_by_id)
2147                        .debug_checked_unwrap()
2148                };
2149
2150                // Register the original required component in the "parent" of the requiree.
2151                // The inheritance depth is 1 deeper than the `requiree` wrt `required_by_id`.
2152                let depth = required_components.0.get(&requiree).expect("requiree is required by required_by_id, so its required_components must include requiree").inheritance_depth;
2153                required_components.register_by_id(required, constructor, depth + 1);
2154
2155                for (component_id, component) in inherited_requirements.iter() {
2156                    // Register the required component.
2157                    // The inheritance depth of inherited components is whatever the requiree's
2158                    // depth is relative to `required_by_id`, plus the inheritance depth of the
2159                    // inherited component relative to the requiree, plus 1 to account for the
2160                    // requiree in between.
2161                    // SAFETY: Component ID and constructor match the ones on the original requiree.
2162                    //         The original requiree is responsible for making sure the registration is safe.
2163                    unsafe {
2164                        required_components.register_dynamic_with(
2165                            *component_id,
2166                            component.inheritance_depth + depth + 1,
2167                            || component.constructor.clone(),
2168                        );
2169                    };
2170                }
2171            }
2172        }
2173
2174        Ok(())
2175    }
2176
2177    /// Registers the components inherited from `required` for the given `requiree`,
2178    /// returning the requirements in a list.
2179    ///
2180    /// # Safety
2181    ///
2182    /// The given component IDs `requiree` and `required` must be valid.
2183    unsafe fn register_inherited_required_components(
2184        &mut self,
2185        requiree: ComponentId,
2186        required: ComponentId,
2187        required_components: &mut RequiredComponents,
2188    ) -> Vec<(ComponentId, RequiredComponent)> {
2189        // Get required components inherited from the `required` component.
2190        // SAFETY: The caller ensures that the `required` component is valid.
2191        let required_component_info = unsafe { self.get_info(required).debug_checked_unwrap() };
2192        let inherited_requirements: Vec<(ComponentId, RequiredComponent)> = required_component_info
2193            .required_components()
2194            .0
2195            .iter()
2196            .map(|(component_id, required_component)| {
2197                (
2198                    *component_id,
2199                    RequiredComponent {
2200                        constructor: required_component.constructor.clone(),
2201                        // Add `1` to the inheritance depth since this will be registered
2202                        // for the component that requires `required`.
2203                        inheritance_depth: required_component.inheritance_depth + 1,
2204                    },
2205                )
2206            })
2207            .collect();
2208
2209        // Register the new required components.
2210        for (component_id, component) in inherited_requirements.iter() {
2211            // Register the required component for the requiree.
2212            // SAFETY: Component ID and constructor match the ones on the original requiree.
2213            unsafe {
2214                required_components.register_dynamic_with(
2215                    *component_id,
2216                    component.inheritance_depth,
2217                    || component.constructor.clone(),
2218                );
2219            };
2220
2221            // Add the requiree to the list of components that require the required component.
2222            // SAFETY: The caller ensures that the required components are valid.
2223            let required_by = unsafe {
2224                self.get_required_by_mut(*component_id)
2225                    .debug_checked_unwrap()
2226            };
2227            required_by.insert(requiree);
2228        }
2229
2230        inherited_requirements
2231    }
2232
2233    /// Registers the given component `R` and [required components] inherited from it as required by `T`,
2234    /// and adds `T` to their lists of requirees.
2235    ///
2236    /// The given `inheritance_depth` determines how many levels of inheritance deep the requirement is.
2237    /// A direct requirement has a depth of `0`, and each level of inheritance increases the depth by `1`.
2238    /// Lower depths are more specific requirements, and can override existing less specific registrations.
2239    ///
2240    /// This method does *not* register any components as required by components that require `T`.
2241    ///
2242    /// [required component]: Component#required-components
2243    ///
2244    /// # Safety
2245    ///
2246    /// The given component IDs `required` and `requiree` must be valid.
2247    pub(crate) unsafe fn register_required_components_manual_unchecked<R: Component>(
2248        &mut self,
2249        requiree: ComponentId,
2250        required: ComponentId,
2251        required_components: &mut RequiredComponents,
2252        constructor: fn() -> R,
2253        inheritance_depth: u16,
2254    ) {
2255        // Components cannot require themselves.
2256        if required == requiree {
2257            return;
2258        }
2259
2260        // Register the required component `R` for the requiree.
2261        required_components.register_by_id(required, constructor, inheritance_depth);
2262
2263        // Add the requiree to the list of components that require `R`.
2264        // SAFETY: The caller ensures that the component ID is valid.
2265        //         Assuming it is valid, the component is in the list of required components, so it must exist already.
2266        let required_by = unsafe { self.get_required_by_mut(required).debug_checked_unwrap() };
2267        required_by.insert(requiree);
2268
2269        self.register_inherited_required_components(requiree, required, required_components);
2270    }
2271
2272    #[inline]
2273    pub(crate) fn get_required_by(&self, id: ComponentId) -> Option<&HashSet<ComponentId>> {
2274        self.components
2275            .get(id.0)
2276            .and_then(|info| info.as_ref().map(|info| &info.required_by))
2277    }
2278
2279    #[inline]
2280    pub(crate) fn get_required_by_mut(
2281        &mut self,
2282        id: ComponentId,
2283    ) -> Option<&mut HashSet<ComponentId>> {
2284        self.components
2285            .get_mut(id.0)
2286            .and_then(|info| info.as_mut().map(|info| &mut info.required_by))
2287    }
2288
2289    /// Returns true if the [`ComponentId`] is fully registered and valid.
2290    /// Ids may be invalid if they are still queued to be registered.
2291    /// Those ids are still correct, but they are not usable in every context yet.
2292    #[inline]
2293    pub fn is_id_valid(&self, id: ComponentId) -> bool {
2294        self.components.get(id.0).is_some_and(Option::is_some)
2295    }
2296
2297    /// Type-erased equivalent of [`Components::valid_component_id()`].
2298    #[inline]
2299    pub fn get_valid_id(&self, type_id: TypeId) -> Option<ComponentId> {
2300        self.indices.get(&type_id).copied()
2301    }
2302
2303    /// Returns the [`ComponentId`] of the given [`Component`] type `T` if it is fully registered.
2304    /// If you want to include queued registration, see [`Components::component_id()`].
2305    ///
2306    /// ```
2307    /// use bevy_ecs::prelude::*;
2308    ///
2309    /// let mut world = World::new();
2310    ///
2311    /// #[derive(Component)]
2312    /// struct ComponentA;
2313    ///
2314    /// let component_a_id = world.register_component::<ComponentA>();
2315    ///
2316    /// assert_eq!(component_a_id, world.components().valid_component_id::<ComponentA>().unwrap())
2317    /// ```
2318    ///
2319    /// # See also
2320    ///
2321    /// * [`Components::get_valid_id()`]
2322    /// * [`Components::valid_resource_id()`]
2323    /// * [`World::component_id()`]
2324    #[inline]
2325    pub fn valid_component_id<T: Component>(&self) -> Option<ComponentId> {
2326        self.get_id(TypeId::of::<T>())
2327    }
2328
2329    /// Type-erased equivalent of [`Components::valid_resource_id()`].
2330    #[inline]
2331    pub fn get_valid_resource_id(&self, type_id: TypeId) -> Option<ComponentId> {
2332        self.resource_indices.get(&type_id).copied()
2333    }
2334
2335    /// Returns the [`ComponentId`] of the given [`Resource`] type `T` if it is fully registered.
2336    /// If you want to include queued registration, see [`Components::resource_id()`].
2337    ///
2338    /// ```
2339    /// use bevy_ecs::prelude::*;
2340    ///
2341    /// let mut world = World::new();
2342    ///
2343    /// #[derive(Resource, Default)]
2344    /// struct ResourceA;
2345    ///
2346    /// let resource_a_id = world.init_resource::<ResourceA>();
2347    ///
2348    /// assert_eq!(resource_a_id, world.components().valid_resource_id::<ResourceA>().unwrap())
2349    /// ```
2350    ///
2351    /// # See also
2352    ///
2353    /// * [`Components::valid_component_id()`]
2354    /// * [`Components::get_resource_id()`]
2355    #[inline]
2356    pub fn valid_resource_id<T: Resource>(&self) -> Option<ComponentId> {
2357        self.get_resource_id(TypeId::of::<T>())
2358    }
2359
2360    /// Type-erased equivalent of [`Components::component_id()`].
2361    #[inline]
2362    pub fn get_id(&self, type_id: TypeId) -> Option<ComponentId> {
2363        self.indices.get(&type_id).copied().or_else(|| {
2364            self.queued
2365                .read()
2366                .unwrap_or_else(PoisonError::into_inner)
2367                .components
2368                .get(&type_id)
2369                .map(|queued| queued.id)
2370        })
2371    }
2372
2373    /// Returns the [`ComponentId`] of the given [`Component`] type `T`.
2374    ///
2375    /// The returned `ComponentId` is specific to the `Components` instance
2376    /// it was retrieved from and should not be used with another `Components`
2377    /// instance.
2378    ///
2379    /// Returns [`None`] if the `Component` type has not
2380    /// yet been initialized using [`ComponentsRegistrator::register_component()`] or [`ComponentsQueuedRegistrator::queue_register_component()`].
2381    ///
2382    /// ```
2383    /// use bevy_ecs::prelude::*;
2384    ///
2385    /// let mut world = World::new();
2386    ///
2387    /// #[derive(Component)]
2388    /// struct ComponentA;
2389    ///
2390    /// let component_a_id = world.register_component::<ComponentA>();
2391    ///
2392    /// assert_eq!(component_a_id, world.components().component_id::<ComponentA>().unwrap())
2393    /// ```
2394    ///
2395    /// # See also
2396    ///
2397    /// * [`Components::get_id()`]
2398    /// * [`Components::resource_id()`]
2399    /// * [`World::component_id()`]
2400    #[inline]
2401    pub fn component_id<T: Component>(&self) -> Option<ComponentId> {
2402        self.get_id(TypeId::of::<T>())
2403    }
2404
2405    /// Type-erased equivalent of [`Components::resource_id()`].
2406    #[inline]
2407    pub fn get_resource_id(&self, type_id: TypeId) -> Option<ComponentId> {
2408        self.resource_indices.get(&type_id).copied().or_else(|| {
2409            self.queued
2410                .read()
2411                .unwrap_or_else(PoisonError::into_inner)
2412                .resources
2413                .get(&type_id)
2414                .map(|queued| queued.id)
2415        })
2416    }
2417
2418    /// Returns the [`ComponentId`] of the given [`Resource`] type `T`.
2419    ///
2420    /// The returned `ComponentId` is specific to the `Components` instance
2421    /// it was retrieved from and should not be used with another `Components`
2422    /// instance.
2423    ///
2424    /// Returns [`None`] if the `Resource` type has not
2425    /// yet been initialized using [`ComponentsRegistrator::register_resource()`] or [`ComponentsQueuedRegistrator::queue_register_resource()`].
2426    ///
2427    /// ```
2428    /// use bevy_ecs::prelude::*;
2429    ///
2430    /// let mut world = World::new();
2431    ///
2432    /// #[derive(Resource, Default)]
2433    /// struct ResourceA;
2434    ///
2435    /// let resource_a_id = world.init_resource::<ResourceA>();
2436    ///
2437    /// assert_eq!(resource_a_id, world.components().resource_id::<ResourceA>().unwrap())
2438    /// ```
2439    ///
2440    /// # See also
2441    ///
2442    /// * [`Components::component_id()`]
2443    /// * [`Components::get_resource_id()`]
2444    #[inline]
2445    pub fn resource_id<T: Resource>(&self) -> Option<ComponentId> {
2446        self.get_resource_id(TypeId::of::<T>())
2447    }
2448
2449    /// # Safety
2450    ///
2451    /// The [`ComponentDescriptor`] must match the [`TypeId`].
2452    /// The [`ComponentId`] must be unique.
2453    /// The [`TypeId`] and [`ComponentId`] must not be registered or queued.
2454    #[inline]
2455    unsafe fn register_resource_unchecked_with(
2456        &mut self,
2457        type_id: TypeId,
2458        component_id: ComponentId,
2459        func: impl FnOnce() -> ComponentDescriptor,
2460    ) {
2461        // SAFETY: ensured by caller
2462        unsafe {
2463            self.register_component_inner(component_id, func());
2464        }
2465        let prev = self.resource_indices.insert(type_id, component_id);
2466        debug_assert!(prev.is_none());
2467    }
2468
2469    /// Gets an iterator over all components fully registered with this instance.
2470    pub fn iter_registered(&self) -> impl Iterator<Item = &ComponentInfo> + '_ {
2471        self.components.iter().filter_map(Option::as_ref)
2472    }
2473}
2474
2475/// A value that tracks when a system ran relative to other systems.
2476/// This is used to power change detection.
2477///
2478/// *Note* that a system that hasn't been run yet has a `Tick` of 0.
2479#[derive(Copy, Clone, Default, Debug, Eq, Hash, PartialEq)]
2480#[cfg_attr(
2481    feature = "bevy_reflect",
2482    derive(Reflect),
2483    reflect(Debug, Hash, PartialEq, Clone)
2484)]
2485pub struct Tick {
2486    tick: u32,
2487}
2488
2489impl Tick {
2490    /// The maximum relative age for a change tick.
2491    /// The value of this is equal to [`MAX_CHANGE_AGE`].
2492    ///
2493    /// Since change detection will not work for any ticks older than this,
2494    /// ticks are periodically scanned to ensure their relative values are below this.
2495    pub const MAX: Self = Self::new(MAX_CHANGE_AGE);
2496
2497    /// Creates a new [`Tick`] wrapping the given value.
2498    #[inline]
2499    pub const fn new(tick: u32) -> Self {
2500        Self { tick }
2501    }
2502
2503    /// Gets the value of this change tick.
2504    #[inline]
2505    pub const fn get(self) -> u32 {
2506        self.tick
2507    }
2508
2509    /// Sets the value of this change tick.
2510    #[inline]
2511    pub fn set(&mut self, tick: u32) {
2512        self.tick = tick;
2513    }
2514
2515    /// Returns `true` if this `Tick` occurred since the system's `last_run`.
2516    ///
2517    /// `this_run` is the current tick of the system, used as a reference to help deal with wraparound.
2518    #[inline]
2519    pub fn is_newer_than(self, last_run: Tick, this_run: Tick) -> bool {
2520        // This works even with wraparound because the world tick (`this_run`) is always "newer" than
2521        // `last_run` and `self.tick`, and we scan periodically to clamp `ComponentTicks` values
2522        // so they never get older than `u32::MAX` (the difference would overflow).
2523        //
2524        // The clamp here ensures determinism (since scans could differ between app runs).
2525        let ticks_since_insert = this_run.relative_to(self).tick.min(MAX_CHANGE_AGE);
2526        let ticks_since_system = this_run.relative_to(last_run).tick.min(MAX_CHANGE_AGE);
2527
2528        ticks_since_system > ticks_since_insert
2529    }
2530
2531    /// Returns a change tick representing the relationship between `self` and `other`.
2532    #[inline]
2533    pub(crate) fn relative_to(self, other: Self) -> Self {
2534        let tick = self.tick.wrapping_sub(other.tick);
2535        Self { tick }
2536    }
2537
2538    /// Wraps this change tick's value if it exceeds [`Tick::MAX`].
2539    ///
2540    /// Returns `true` if wrapping was performed. Otherwise, returns `false`.
2541    #[inline]
2542    pub(crate) fn check_tick(&mut self, tick: Tick) -> bool {
2543        let age = tick.relative_to(*self);
2544        // This comparison assumes that `age` has not overflowed `u32::MAX` before, which will be true
2545        // so long as this check always runs before that can happen.
2546        if age.get() > Self::MAX.get() {
2547            *self = tick.relative_to(Self::MAX);
2548            true
2549        } else {
2550            false
2551        }
2552    }
2553}
2554
2555/// Interior-mutable access to the [`Tick`]s for a single component or resource.
2556#[derive(Copy, Clone, Debug)]
2557pub struct TickCells<'a> {
2558    /// The tick indicating when the value was added to the world.
2559    pub added: &'a UnsafeCell<Tick>,
2560    /// The tick indicating the last time the value was modified.
2561    pub changed: &'a UnsafeCell<Tick>,
2562}
2563
2564impl<'a> TickCells<'a> {
2565    /// # Safety
2566    /// All cells contained within must uphold the safety invariants of [`UnsafeCellDeref::read`].
2567    #[inline]
2568    pub(crate) unsafe fn read(&self) -> ComponentTicks {
2569        ComponentTicks {
2570            // SAFETY: The callers uphold the invariants for `read`.
2571            added: unsafe { self.added.read() },
2572            // SAFETY: The callers uphold the invariants for `read`.
2573            changed: unsafe { self.changed.read() },
2574        }
2575    }
2576}
2577
2578/// Records when a component or resource was added and when it was last mutably dereferenced (or added).
2579#[derive(Copy, Clone, Debug)]
2580#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Clone))]
2581pub struct ComponentTicks {
2582    /// Tick recording the time this component or resource was added.
2583    pub added: Tick,
2584
2585    /// Tick recording the time this component or resource was most recently changed.
2586    pub changed: Tick,
2587}
2588
2589impl ComponentTicks {
2590    /// Returns `true` if the component or resource was added after the system last ran
2591    /// (or the system is running for the first time).
2592    #[inline]
2593    pub fn is_added(&self, last_run: Tick, this_run: Tick) -> bool {
2594        self.added.is_newer_than(last_run, this_run)
2595    }
2596
2597    /// Returns `true` if the component or resource was added or mutably dereferenced after the system last ran
2598    /// (or the system is running for the first time).
2599    #[inline]
2600    pub fn is_changed(&self, last_run: Tick, this_run: Tick) -> bool {
2601        self.changed.is_newer_than(last_run, this_run)
2602    }
2603
2604    /// Creates a new instance with the same change tick for `added` and `changed`.
2605    pub fn new(change_tick: Tick) -> Self {
2606        Self {
2607            added: change_tick,
2608            changed: change_tick,
2609        }
2610    }
2611
2612    /// Manually sets the change tick.
2613    ///
2614    /// This is normally done automatically via the [`DerefMut`] implementation
2615    /// on [`Mut<T>`](crate::change_detection::Mut), [`ResMut<T>`](crate::change_detection::ResMut), etc.
2616    /// However, components and resources that make use of interior mutability might require manual updates.
2617    ///
2618    /// # Example
2619    /// ```no_run
2620    /// # use bevy_ecs::{world::World, component::ComponentTicks};
2621    /// let world: World = unimplemented!();
2622    /// let component_ticks: ComponentTicks = unimplemented!();
2623    ///
2624    /// component_ticks.set_changed(world.read_change_tick());
2625    /// ```
2626    #[inline]
2627    pub fn set_changed(&mut self, change_tick: Tick) {
2628        self.changed = change_tick;
2629    }
2630}
2631
2632/// A [`SystemParam`] that provides access to the [`ComponentId`] for a specific component type.
2633///
2634/// # Example
2635/// ```
2636/// # use bevy_ecs::{system::Local, component::{Component, ComponentId, ComponentIdFor}};
2637/// #[derive(Component)]
2638/// struct Player;
2639/// fn my_system(component_id: ComponentIdFor<Player>) {
2640///     let component_id: ComponentId = component_id.get();
2641///     // ...
2642/// }
2643/// ```
2644#[derive(SystemParam)]
2645pub struct ComponentIdFor<'s, T: Component>(Local<'s, InitComponentId<T>>);
2646
2647impl<T: Component> ComponentIdFor<'_, T> {
2648    /// Gets the [`ComponentId`] for the type `T`.
2649    #[inline]
2650    pub fn get(&self) -> ComponentId {
2651        **self
2652    }
2653}
2654
2655impl<T: Component> Deref for ComponentIdFor<'_, T> {
2656    type Target = ComponentId;
2657    fn deref(&self) -> &Self::Target {
2658        &self.0.component_id
2659    }
2660}
2661
2662impl<T: Component> From<ComponentIdFor<'_, T>> for ComponentId {
2663    #[inline]
2664    fn from(to_component_id: ComponentIdFor<T>) -> ComponentId {
2665        *to_component_id
2666    }
2667}
2668
2669/// Initializes the [`ComponentId`] for a specific type when used with [`FromWorld`].
2670struct InitComponentId<T: Component> {
2671    component_id: ComponentId,
2672    marker: PhantomData<T>,
2673}
2674
2675impl<T: Component> FromWorld for InitComponentId<T> {
2676    fn from_world(world: &mut World) -> Self {
2677        Self {
2678            component_id: world.register_component::<T>(),
2679            marker: PhantomData,
2680        }
2681    }
2682}
2683
2684/// An error returned when the registration of a required component fails.
2685#[derive(Error, Debug)]
2686#[non_exhaustive]
2687pub enum RequiredComponentsError {
2688    /// The component is already a directly required component for the requiree.
2689    #[error("Component {0:?} already directly requires component {1:?}")]
2690    DuplicateRegistration(ComponentId, ComponentId),
2691    /// An archetype with the component that requires other components already exists
2692    #[error("An archetype with the component {0:?} that requires other components already exists")]
2693    ArchetypeExists(ComponentId),
2694}
2695
2696/// A Required Component constructor. See [`Component`] for details.
2697#[derive(Clone)]
2698pub struct RequiredComponentConstructor(
2699    pub Arc<dyn Fn(&mut Table, &mut SparseSets, Tick, TableRow, Entity, MaybeLocation)>,
2700);
2701
2702impl RequiredComponentConstructor {
2703    /// # Safety
2704    /// This is intended to only be called in the context of [`BundleInfo::write_components`] to initialized required components.
2705    /// Calling it _anywhere else_ should be considered unsafe.
2706    ///
2707    /// `table_row` and `entity` must correspond to a valid entity that currently needs a component initialized via the constructor stored
2708    /// on this [`RequiredComponentConstructor`]. The stored constructor must correspond to a component on `entity` that needs initialization.
2709    /// `table` and `sparse_sets` must correspond to storages on a world where `entity` needs this required component initialized.
2710    ///
2711    /// Again, don't call this anywhere but [`BundleInfo::write_components`].
2712    pub(crate) unsafe fn initialize(
2713        &self,
2714        table: &mut Table,
2715        sparse_sets: &mut SparseSets,
2716        change_tick: Tick,
2717        table_row: TableRow,
2718        entity: Entity,
2719        caller: MaybeLocation,
2720    ) {
2721        (self.0)(table, sparse_sets, change_tick, table_row, entity, caller);
2722    }
2723}
2724
2725/// Metadata associated with a required component. See [`Component`] for details.
2726#[derive(Clone)]
2727pub struct RequiredComponent {
2728    /// The constructor used for the required component.
2729    pub constructor: RequiredComponentConstructor,
2730
2731    /// The depth of the component requirement in the requirement hierarchy for this component.
2732    /// This is used for determining which constructor is used in cases where there are duplicate requires.
2733    ///
2734    /// For example, consider the inheritance tree `X -> Y -> Z`, where `->` indicates a requirement.
2735    /// `X -> Y` and `Y -> Z` are direct requirements with a depth of 0, while `Z` is only indirectly
2736    /// required for `X` with a depth of `1`.
2737    ///
2738    /// In cases where there are multiple conflicting requirements with the same depth, a higher priority
2739    /// will be given to components listed earlier in the `require` attribute, or to the latest added requirement
2740    /// if registered at runtime.
2741    pub inheritance_depth: u16,
2742}
2743
2744/// The collection of metadata for components that are required for a given component.
2745///
2746/// For more information, see the "Required Components" section of [`Component`].
2747#[derive(Default, Clone)]
2748pub struct RequiredComponents(pub(crate) HashMap<ComponentId, RequiredComponent>);
2749
2750impl Debug for RequiredComponents {
2751    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2752        f.debug_tuple("RequiredComponents")
2753            .field(&self.0.keys())
2754            .finish()
2755    }
2756}
2757
2758impl RequiredComponents {
2759    /// Registers a required component.
2760    ///
2761    /// If the component is already registered, it will be overwritten if the given inheritance depth
2762    /// is smaller than the depth of the existing registration. Otherwise, the new registration will be ignored.
2763    ///
2764    /// # Safety
2765    ///
2766    /// `component_id` must match the type initialized by `constructor`.
2767    /// `constructor` _must_ initialize a component for `component_id` in such a way that
2768    /// matches the storage type of the component. It must only use the given `table_row` or `Entity` to
2769    /// initialize the storage for `component_id` corresponding to the given entity.
2770    pub unsafe fn register_dynamic_with(
2771        &mut self,
2772        component_id: ComponentId,
2773        inheritance_depth: u16,
2774        constructor: impl FnOnce() -> RequiredComponentConstructor,
2775    ) {
2776        let entry = self.0.entry(component_id);
2777        match entry {
2778            bevy_platform_support::collections::hash_map::Entry::Occupied(mut occupied) => {
2779                let current = occupied.get_mut();
2780                if current.inheritance_depth > inheritance_depth {
2781                    *current = RequiredComponent {
2782                        constructor: constructor(),
2783                        inheritance_depth,
2784                    }
2785                }
2786            }
2787            bevy_platform_support::collections::hash_map::Entry::Vacant(vacant) => {
2788                vacant.insert(RequiredComponent {
2789                    constructor: constructor(),
2790                    inheritance_depth,
2791                });
2792            }
2793        }
2794    }
2795
2796    /// Registers a required component.
2797    ///
2798    /// If the component is already registered, it will be overwritten if the given inheritance depth
2799    /// is smaller than the depth of the existing registration. Otherwise, the new registration will be ignored.
2800    pub fn register<C: Component>(
2801        &mut self,
2802        components: &mut ComponentsRegistrator,
2803        constructor: fn() -> C,
2804        inheritance_depth: u16,
2805    ) {
2806        let component_id = components.register_component::<C>();
2807        self.register_by_id(component_id, constructor, inheritance_depth);
2808    }
2809
2810    /// Registers the [`Component`] with the given ID as required if it exists.
2811    ///
2812    /// If the component is already registered, it will be overwritten if the given inheritance depth
2813    /// is smaller than the depth of the existing registration. Otherwise, the new registration will be ignored.
2814    pub fn register_by_id<C: Component>(
2815        &mut self,
2816        component_id: ComponentId,
2817        constructor: fn() -> C,
2818        inheritance_depth: u16,
2819    ) {
2820        let erased = || {
2821            RequiredComponentConstructor({
2822                // `portable-atomic-util` `Arc` is not able to coerce an unsized
2823                // type like `std::sync::Arc` can. Creating a `Box` first does the
2824                // coercion.
2825                //
2826                // This would be resolved by https://github.com/rust-lang/rust/issues/123430
2827
2828                #[cfg(not(target_has_atomic = "ptr"))]
2829                use alloc::boxed::Box;
2830
2831                type Constructor = dyn for<'a, 'b> Fn(
2832                    &'a mut Table,
2833                    &'b mut SparseSets,
2834                    Tick,
2835                    TableRow,
2836                    Entity,
2837                    MaybeLocation,
2838                );
2839
2840                #[cfg(not(target_has_atomic = "ptr"))]
2841                type Intermediate<T> = Box<T>;
2842
2843                #[cfg(target_has_atomic = "ptr")]
2844                type Intermediate<T> = Arc<T>;
2845
2846                let boxed: Intermediate<Constructor> = Intermediate::new(
2847                    move |table, sparse_sets, change_tick, table_row, entity, caller| {
2848                        OwningPtr::make(constructor(), |ptr| {
2849                            // SAFETY: This will only be called in the context of `BundleInfo::write_components`, which will
2850                            // pass in a valid table_row and entity requiring a C constructor
2851                            // C::STORAGE_TYPE is the storage type associated with `component_id` / `C`
2852                            // `ptr` points to valid `C` data, which matches the type associated with `component_id`
2853                            unsafe {
2854                                BundleInfo::initialize_required_component(
2855                                    table,
2856                                    sparse_sets,
2857                                    change_tick,
2858                                    table_row,
2859                                    entity,
2860                                    component_id,
2861                                    C::STORAGE_TYPE,
2862                                    ptr,
2863                                    caller,
2864                                );
2865                            }
2866                        });
2867                    },
2868                );
2869
2870                Arc::from(boxed)
2871            })
2872        };
2873
2874        // SAFETY:
2875        // `component_id` matches the type initialized by the `erased` constructor above.
2876        // `erased` initializes a component for `component_id` in such a way that
2877        // matches the storage type of the component. It only uses the given `table_row` or `Entity` to
2878        // initialize the storage corresponding to the given entity.
2879        unsafe { self.register_dynamic_with(component_id, inheritance_depth, erased) };
2880    }
2881
2882    /// Iterates the ids of all required components. This includes recursive required components.
2883    pub fn iter_ids(&self) -> impl Iterator<Item = ComponentId> + '_ {
2884        self.0.keys().copied()
2885    }
2886
2887    /// Removes components that are explicitly provided in a given [`Bundle`]. These components should
2888    /// be logically treated as normal components, not "required components".
2889    ///
2890    /// [`Bundle`]: crate::bundle::Bundle
2891    pub(crate) fn remove_explicit_components(&mut self, components: &[ComponentId]) {
2892        for component in components {
2893            self.0.remove(component);
2894        }
2895    }
2896
2897    /// Merges `required_components` into this collection. This only inserts a required component
2898    /// if it _did not already exist_ *or* if the required component is more specific than the existing one
2899    /// (in other words, if the inheritance depth is smaller).
2900    ///
2901    /// See [`register_dynamic_with`](Self::register_dynamic_with) for details.
2902    pub(crate) fn merge(&mut self, required_components: &RequiredComponents) {
2903        for (
2904            component_id,
2905            RequiredComponent {
2906                constructor,
2907                inheritance_depth,
2908            },
2909        ) in required_components.0.iter()
2910        {
2911            // SAFETY: This exact registration must have been done on `required_components`, so safety is ensured by that caller.
2912            unsafe {
2913                self.register_dynamic_with(*component_id, *inheritance_depth, || {
2914                    constructor.clone()
2915                });
2916            }
2917        }
2918    }
2919}
2920
2921// NOTE: This should maybe be private, but it is currently public so that `bevy_ecs_macros` can use it.
2922// This exists as a standalone function instead of being inlined into the component derive macro so as
2923// to reduce the amount of generated code.
2924#[doc(hidden)]
2925pub fn enforce_no_required_components_recursion(
2926    components: &Components,
2927    recursion_check_stack: &[ComponentId],
2928) {
2929    if let Some((&requiree, check)) = recursion_check_stack.split_last() {
2930        if let Some(direct_recursion) = check
2931            .iter()
2932            .position(|&id| id == requiree)
2933            .map(|index| index == check.len() - 1)
2934        {
2935            panic!(
2936                "Recursive required components detected: {}\nhelp: {}",
2937                recursion_check_stack
2938                    .iter()
2939                    .map(|id| format!("{}", ShortName(components.get_name(*id).unwrap())))
2940                    .collect::<Vec<_>>()
2941                    .join(" → "),
2942                if direct_recursion {
2943                    format!(
2944                        "Remove require({}).",
2945                        ShortName(components.get_name(requiree).unwrap())
2946                    )
2947                } else {
2948                    "If this is intentional, consider merging the components.".into()
2949                }
2950            );
2951        }
2952    }
2953}
2954
2955/// Component [clone handler function](ComponentCloneFn) implemented using the [`Clone`] trait.
2956/// Can be [set](Component::clone_behavior) as clone handler for the specific component it is implemented for.
2957/// It will panic if set as handler for any other component.
2958///
2959pub fn component_clone_via_clone<C: Clone + Component>(
2960    source: &SourceComponent,
2961    ctx: &mut ComponentCloneCtx,
2962) {
2963    if let Some(component) = source.read::<C>() {
2964        ctx.write_target_component(component.clone());
2965    }
2966}
2967
2968/// Component [clone handler function](ComponentCloneFn) implemented using reflect.
2969/// Can be [set](Component::clone_behavior) as clone handler for any registered component,
2970/// but only reflected components will be cloned.
2971///
2972/// To clone a component using this handler, the following must be true:
2973/// - World has [`AppTypeRegistry`](crate::reflect::AppTypeRegistry)
2974/// - Component has [`TypeId`]
2975/// - Component is registered
2976/// - Component has [`ReflectFromPtr`](bevy_reflect::ReflectFromPtr) registered
2977/// - Component can be cloned via [`PartialReflect::reflect_clone`] _or_ has one of the following registered: [`ReflectFromReflect`](bevy_reflect::ReflectFromReflect),
2978///   [`ReflectDefault`](bevy_reflect::std_traits::ReflectDefault), [`ReflectFromWorld`](crate::reflect::ReflectFromWorld)
2979///
2980/// If any of the conditions is not satisfied, the component will be skipped.
2981///
2982/// See [`EntityClonerBuilder`](crate::entity::EntityClonerBuilder) for details.
2983///
2984/// [`PartialReflect::reflect_clone`]: bevy_reflect::PartialReflect::reflect_clone
2985#[cfg(feature = "bevy_reflect")]
2986pub fn component_clone_via_reflect(source: &SourceComponent, ctx: &mut ComponentCloneCtx) {
2987    let Some(app_registry) = ctx.type_registry().cloned() else {
2988        return;
2989    };
2990    let registry = app_registry.read();
2991    let Some(source_component_reflect) = source.read_reflect(&registry) else {
2992        return;
2993    };
2994    let component_info = ctx.component_info();
2995    // checked in read_source_component_reflect
2996    let type_id = component_info.type_id().unwrap();
2997
2998    // Try to clone using `reflect_clone`
2999    if let Ok(mut component) = source_component_reflect.reflect_clone() {
3000        if let Some(reflect_component) =
3001            registry.get_type_data::<crate::reflect::ReflectComponent>(type_id)
3002        {
3003            reflect_component.map_entities(&mut *component, ctx.entity_mapper());
3004        }
3005        drop(registry);
3006
3007        ctx.write_target_component_reflect(component);
3008        return;
3009    }
3010
3011    // Try to clone using ReflectFromReflect
3012    if let Some(reflect_from_reflect) =
3013        registry.get_type_data::<bevy_reflect::ReflectFromReflect>(type_id)
3014    {
3015        if let Some(mut component) =
3016            reflect_from_reflect.from_reflect(source_component_reflect.as_partial_reflect())
3017        {
3018            if let Some(reflect_component) =
3019                registry.get_type_data::<crate::reflect::ReflectComponent>(type_id)
3020            {
3021                reflect_component.map_entities(&mut *component, ctx.entity_mapper());
3022            }
3023            drop(registry);
3024
3025            ctx.write_target_component_reflect(component);
3026            return;
3027        }
3028    }
3029    // Else, try to clone using ReflectDefault
3030    if let Some(reflect_default) =
3031        registry.get_type_data::<bevy_reflect::std_traits::ReflectDefault>(type_id)
3032    {
3033        let mut component = reflect_default.default();
3034        component.apply(source_component_reflect.as_partial_reflect());
3035        drop(registry);
3036        ctx.write_target_component_reflect(component);
3037        return;
3038    }
3039    // Otherwise, try to clone using ReflectFromWorld
3040    if let Some(reflect_from_world) =
3041        registry.get_type_data::<crate::reflect::ReflectFromWorld>(type_id)
3042    {
3043        let reflect_from_world = reflect_from_world.clone();
3044        let source_component_cloned = source_component_reflect.to_dynamic();
3045        let component_layout = component_info.layout();
3046        let target = ctx.target();
3047        let component_id = ctx.component_id();
3048        drop(registry);
3049        ctx.queue_deferred(move |world: &mut World, mapper: &mut dyn EntityMapper| {
3050            let mut component = reflect_from_world.from_world(world);
3051            assert_eq!(type_id, (*component).type_id());
3052            component.apply(source_component_cloned.as_partial_reflect());
3053            if let Some(reflect_component) = app_registry
3054                .read()
3055                .get_type_data::<crate::reflect::ReflectComponent>(type_id)
3056            {
3057                reflect_component.map_entities(&mut *component, mapper);
3058            }
3059            // SAFETY:
3060            // - component_id is from the same world as target entity
3061            // - component is a valid value represented by component_id
3062            unsafe {
3063                let raw_component_ptr =
3064                    core::ptr::NonNull::new_unchecked(Box::into_raw(component).cast::<u8>());
3065                world
3066                    .entity_mut(target)
3067                    .insert_by_id(component_id, OwningPtr::new(raw_component_ptr));
3068
3069                if component_layout.size() > 0 {
3070                    // Ensure we don't attempt to deallocate zero-sized components
3071                    alloc::alloc::dealloc(raw_component_ptr.as_ptr(), component_layout);
3072                }
3073            }
3074        });
3075    }
3076}
3077
3078/// Noop implementation of component clone handler function.
3079///
3080/// See [`EntityClonerBuilder`](crate::entity::EntityClonerBuilder) for details.
3081pub fn component_clone_ignore(_source: &SourceComponent, _ctx: &mut ComponentCloneCtx) {}
3082
3083/// Wrapper for components clone specialization using autoderef.
3084#[doc(hidden)]
3085pub struct DefaultCloneBehaviorSpecialization<T>(PhantomData<T>);
3086
3087impl<T> Default for DefaultCloneBehaviorSpecialization<T> {
3088    fn default() -> Self {
3089        Self(PhantomData)
3090    }
3091}
3092
3093/// Base trait for components clone specialization using autoderef.
3094#[doc(hidden)]
3095pub trait DefaultCloneBehaviorBase {
3096    fn default_clone_behavior(&self) -> ComponentCloneBehavior;
3097}
3098impl<C> DefaultCloneBehaviorBase for DefaultCloneBehaviorSpecialization<C> {
3099    fn default_clone_behavior(&self) -> ComponentCloneBehavior {
3100        ComponentCloneBehavior::Default
3101    }
3102}
3103
3104/// Specialized trait for components clone specialization using autoderef.
3105#[doc(hidden)]
3106pub trait DefaultCloneBehaviorViaClone {
3107    fn default_clone_behavior(&self) -> ComponentCloneBehavior;
3108}
3109impl<C: Clone + Component> DefaultCloneBehaviorViaClone for &DefaultCloneBehaviorSpecialization<C> {
3110    fn default_clone_behavior(&self) -> ComponentCloneBehavior {
3111        ComponentCloneBehavior::clone::<C>()
3112    }
3113}