bevy_ecs/
component.rs

1//! Types for declaring and storing [`Component`]s.
2
3use crate::{
4    self as bevy_ecs,
5    archetype::ArchetypeFlags,
6    bundle::BundleInfo,
7    change_detection::MAX_CHANGE_AGE,
8    entity::Entity,
9    query::DebugCheckedUnwrap,
10    storage::{SparseSetIndex, SparseSets, Storages, Table, TableRow},
11    system::{Local, Resource, SystemParam},
12    world::{DeferredWorld, FromWorld, World},
13};
14use alloc::{borrow::Cow, sync::Arc};
15pub use bevy_ecs_macros::Component;
16use bevy_ptr::{OwningPtr, UnsafeCellDeref};
17#[cfg(feature = "bevy_reflect")]
18use bevy_reflect::Reflect;
19use bevy_utils::{HashMap, HashSet, TypeIdMap};
20#[cfg(feature = "track_change_detection")]
21use core::panic::Location;
22use core::{
23    alloc::Layout,
24    any::{Any, TypeId},
25    cell::UnsafeCell,
26    fmt::Debug,
27    marker::PhantomData,
28    mem::needs_drop,
29};
30use derive_more::derive::{Display, Error};
31
32/// A data type that can be used to store data for an [entity].
33///
34/// `Component` is a [derivable trait]: this means that a data type can implement it by applying a `#[derive(Component)]` attribute to it.
35/// However, components must always satisfy the `Send + Sync + 'static` trait bounds.
36///
37/// [entity]: crate::entity
38/// [derivable trait]: https://doc.rust-lang.org/book/appendix-03-derivable-traits.html
39///
40/// # Examples
41///
42/// 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.
43/// The following examples show how components are laid out in code.
44///
45/// ```
46/// # use bevy_ecs::component::Component;
47/// # struct Color;
48/// #
49/// // A component can contain data...
50/// #[derive(Component)]
51/// struct LicensePlate(String);
52///
53/// // ... but it can also be a zero-sized marker.
54/// #[derive(Component)]
55/// struct Car;
56///
57/// // Components can also be structs with named fields...
58/// #[derive(Component)]
59/// struct VehiclePerformance {
60///     acceleration: f32,
61///     top_speed: f32,
62///     handling: f32,
63/// }
64///
65/// // ... or enums.
66/// #[derive(Component)]
67/// enum WheelCount {
68///     Two,
69///     Three,
70///     Four,
71/// }
72/// ```
73///
74/// # Component and data access
75///
76/// See the [`entity`] module level documentation to learn how to add or remove components from an entity.
77///
78/// See the documentation for [`Query`] to learn how to access component data from a system.
79///
80/// [`entity`]: crate::entity#usage
81/// [`Query`]: crate::system::Query
82///
83/// # Choosing a storage type
84///
85/// Components can be stored in the world using different strategies with their own performance implications.
86/// By default, components are added to the [`Table`] storage, which is optimized for query iteration.
87///
88/// Alternatively, components can be added to the [`SparseSet`] storage, which is optimized for component insertion and removal.
89/// This is achieved by adding an additional `#[component(storage = "SparseSet")]` attribute to the derive one:
90///
91/// ```
92/// # use bevy_ecs::component::Component;
93/// #
94/// #[derive(Component)]
95/// #[component(storage = "SparseSet")]
96/// struct ComponentA;
97/// ```
98///
99/// [`Table`]: crate::storage::Table
100/// [`SparseSet`]: crate::storage::SparseSet
101///
102/// # Required Components
103///
104/// Components can specify Required Components. If some [`Component`] `A` requires [`Component`] `B`,  then when `A` is inserted,
105/// `B` will _also_ be initialized and inserted (if it was not manually specified).
106///
107/// The [`Default`] constructor will be used to initialize the component, by default:
108///
109/// ```
110/// # use bevy_ecs::prelude::*;
111/// #[derive(Component)]
112/// #[require(B)]
113/// struct A;
114///
115/// #[derive(Component, Default, PartialEq, Eq, Debug)]
116/// struct B(usize);
117///
118/// # let mut world = World::default();
119/// // This will implicitly also insert B with the Default constructor
120/// let id = world.spawn(A).id();
121/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
122///
123/// // This will _not_ implicitly insert B, because it was already provided
124/// world.spawn((A, B(11)));
125/// ```
126///
127/// Components can have more than one required component:
128///
129/// ```
130/// # use bevy_ecs::prelude::*;
131/// #[derive(Component)]
132/// #[require(B, C)]
133/// struct A;
134///
135/// #[derive(Component, Default, PartialEq, Eq, Debug)]
136/// #[require(C)]
137/// struct B(usize);
138///
139/// #[derive(Component, Default, PartialEq, Eq, Debug)]
140/// struct C(u32);
141///
142/// # let mut world = World::default();
143/// // This will implicitly also insert B and C with their Default constructors
144/// let id = world.spawn(A).id();
145/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
146/// assert_eq!(&C(0), world.entity(id).get::<C>().unwrap());
147/// ```
148///
149/// You can also define a custom constructor function or closure:
150///
151/// ```
152/// # use bevy_ecs::prelude::*;
153/// #[derive(Component)]
154/// #[require(C(init_c))]
155/// struct A;
156///
157/// #[derive(Component, PartialEq, Eq, Debug)]
158/// #[require(C(|| C(20)))]
159/// struct B;
160///
161/// #[derive(Component, PartialEq, Eq, Debug)]
162/// struct C(usize);
163///
164/// fn init_c() -> C {
165///     C(10)
166/// }
167///
168/// # let mut world = World::default();
169/// // This will implicitly also insert C with the init_c() constructor
170/// let id = world.spawn(A).id();
171/// assert_eq!(&C(10), world.entity(id).get::<C>().unwrap());
172///
173/// // This will implicitly also insert C with the `|| C(20)` constructor closure
174/// let id = world.spawn(B).id();
175/// assert_eq!(&C(20), world.entity(id).get::<C>().unwrap());
176/// ```
177///
178/// Required components are _recursive_. This means, if a Required Component has required components,
179/// those components will _also_ be inserted if they are missing:
180///
181/// ```
182/// # use bevy_ecs::prelude::*;
183/// #[derive(Component)]
184/// #[require(B)]
185/// struct A;
186///
187/// #[derive(Component, Default, PartialEq, Eq, Debug)]
188/// #[require(C)]
189/// struct B(usize);
190///
191/// #[derive(Component, Default, PartialEq, Eq, Debug)]
192/// struct C(u32);
193///
194/// # let mut world = World::default();
195/// // This will implicitly also insert B and C with their Default constructors
196/// let id = world.spawn(A).id();
197/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
198/// assert_eq!(&C(0), world.entity(id).get::<C>().unwrap());
199/// ```
200///
201/// Note that cycles in the "component require tree" will result in stack overflows when attempting to
202/// insert a component.
203///
204/// This "multiple inheritance" pattern does mean that it is possible to have duplicate requires for a given type
205/// at different levels of the inheritance tree:
206///
207/// ```
208/// # use bevy_ecs::prelude::*;
209/// #[derive(Component)]
210/// struct X(usize);
211///
212/// #[derive(Component, Default)]
213/// #[require(X(|| X(1)))]
214/// struct Y;
215///
216/// #[derive(Component)]
217/// #[require(
218///     Y,
219///     X(|| X(2)),
220/// )]
221/// struct Z;
222///
223/// # let mut world = World::default();
224/// // In this case, the x2 constructor is used for X
225/// let id = world.spawn(Z).id();
226/// assert_eq!(2, world.entity(id).get::<X>().unwrap().0);
227/// ```
228///
229/// In general, this shouldn't happen often, but when it does the algorithm for choosing the constructor from the tree is simple and predictable:
230/// 1. A constructor from a direct `#[require()]`, if one exists, is selected with priority.
231/// 2. Otherwise, perform a Depth First Search on the tree of requirements and select the first one found.
232///
233/// From a user perspective, just think about this as the following:
234/// 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.
235/// 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.
236///
237/// ## Registering required components at runtime
238///
239/// In most cases, required components should be registered using the `require` attribute as shown above.
240/// However, in some cases, it may be useful to register required components at runtime.
241///
242/// This can be done through [`World::register_required_components`] or  [`World::register_required_components_with`]
243/// for the [`Default`] and custom constructors respectively:
244///
245/// ```
246/// # use bevy_ecs::prelude::*;
247/// #[derive(Component)]
248/// struct A;
249///
250/// #[derive(Component, Default, PartialEq, Eq, Debug)]
251/// struct B(usize);
252///
253/// #[derive(Component, PartialEq, Eq, Debug)]
254/// struct C(u32);
255///
256/// # let mut world = World::default();
257/// // Register B as required by A and C as required by B.
258/// world.register_required_components::<A, B>();
259/// world.register_required_components_with::<B, C>(|| C(2));
260///
261/// // This will implicitly also insert B with its Default constructor
262/// // and C with the custom constructor defined by B.
263/// let id = world.spawn(A).id();
264/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
265/// assert_eq!(&C(2), world.entity(id).get::<C>().unwrap());
266/// ```
267///
268/// Similar rules as before apply to duplicate requires fer a given type at different levels
269/// of the inheritance tree. `A` requiring `C` directly would take precedence over indirectly
270/// requiring it through `A` requiring `B` and `B` requiring `C`.
271///
272/// Unlike with the `require` attribute, directly requiring the same component multiple times
273/// for the same component will result in a panic. This is done to prevent conflicting constructors
274/// and confusing ordering dependencies.
275///
276/// Note that requirements must currently be registered before the requiring component is inserted
277/// into the world for the first time. Registering requirements after this will lead to a panic.
278///
279/// # Adding component's hooks
280///
281/// See [`ComponentHooks`] for a detailed explanation of component's hooks.
282///
283/// Alternatively to the example shown in [`ComponentHooks`]' documentation, hooks can be configured using following attributes:
284/// - `#[component(on_add = on_add_function)]`
285/// - `#[component(on_insert = on_insert_function)]`
286/// - `#[component(on_replace = on_replace_function)]`
287/// - `#[component(on_remove = on_remove_function)]`
288///
289/// ```
290/// # use bevy_ecs::component::Component;
291/// # use bevy_ecs::world::DeferredWorld;
292/// # use bevy_ecs::entity::Entity;
293/// # use bevy_ecs::component::ComponentId;
294/// #
295/// #[derive(Component)]
296/// #[component(on_add = my_on_add_hook)]
297/// #[component(on_insert = my_on_insert_hook)]
298/// // Another possible way of configuring hooks:
299/// // #[component(on_add = my_on_add_hook, on_insert = my_on_insert_hook)]
300/// //
301/// // We don't have a replace or remove hook, so we can leave them out:
302/// // #[component(on_replace = my_on_replace_hook, on_remove = my_on_remove_hook)]
303/// struct ComponentA;
304///
305/// fn my_on_add_hook(world: DeferredWorld, entity: Entity, id: ComponentId) {
306///     // ...
307/// }
308///
309/// // You can also omit writing some types using generics.
310/// fn my_on_insert_hook<T1, T2>(world: DeferredWorld, _: T1, _: T2) {
311///     // ...
312/// }
313/// ```
314///
315/// # Implementing the trait for foreign types
316///
317/// 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.
318/// This means that it is not possible to directly have a type defined in a third party library as a component.
319/// This important limitation can be easily worked around using the [newtype pattern]:
320/// this makes it possible to locally define and implement `Component` for a tuple struct that wraps the foreign type.
321/// The following example gives a demonstration of this pattern.
322///
323/// ```
324/// // `Component` is defined in the `bevy_ecs` crate.
325/// use bevy_ecs::component::Component;
326///
327/// // `Duration` is defined in the `std` crate.
328/// use std::time::Duration;
329///
330/// // It is not possible to implement `Component` for `Duration` from this position, as they are
331/// // both foreign items, defined in an external crate. However, nothing prevents to define a new
332/// // `Cooldown` type that wraps `Duration`. As `Cooldown` is defined in a local crate, it is
333/// // possible to implement `Component` for it.
334/// #[derive(Component)]
335/// struct Cooldown(Duration);
336/// ```
337///
338/// [orphan rule]: https://doc.rust-lang.org/book/ch10-02-traits.html#implementing-a-trait-on-a-type
339/// [newtype pattern]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#using-the-newtype-pattern-to-implement-external-traits-on-external-types
340///
341/// # `!Sync` Components
342/// A `!Sync` type cannot implement `Component`. However, it is possible to wrap a `Send` but not `Sync`
343/// type in [`SyncCell`] or the currently unstable [`Exclusive`] to make it `Sync`. This forces only
344/// having mutable access (`&mut T` only, never `&T`), but makes it safe to reference across multiple
345/// threads.
346///
347/// This will fail to compile since `RefCell` is `!Sync`.
348/// ```compile_fail
349/// # use std::cell::RefCell;
350/// # use bevy_ecs::component::Component;
351/// #[derive(Component)]
352/// struct NotSync {
353///    counter: RefCell<usize>,
354/// }
355/// ```
356///
357/// This will compile since the `RefCell` is wrapped with `SyncCell`.
358/// ```
359/// # use std::cell::RefCell;
360/// # use bevy_ecs::component::Component;
361/// use bevy_utils::synccell::SyncCell;
362///
363/// // This will compile.
364/// #[derive(Component)]
365/// struct ActuallySync {
366///    counter: SyncCell<RefCell<usize>>,
367/// }
368/// ```
369///
370/// [`SyncCell`]: bevy_utils::synccell::SyncCell
371/// [`Exclusive`]: https://doc.rust-lang.org/nightly/std/sync/struct.Exclusive.html
372#[diagnostic::on_unimplemented(
373    message = "`{Self}` is not a `Component`",
374    label = "invalid `Component`",
375    note = "consider annotating `{Self}` with `#[derive(Component)]`"
376)]
377pub trait Component: Send + Sync + 'static {
378    /// A constant indicating the storage type used for this component.
379    const STORAGE_TYPE: StorageType;
380
381    /// Called when registering this component, allowing mutable access to its [`ComponentHooks`].
382    fn register_component_hooks(_hooks: &mut ComponentHooks) {}
383
384    /// Registers required components.
385    fn register_required_components(
386        _component_id: ComponentId,
387        _components: &mut Components,
388        _storages: &mut Storages,
389        _required_components: &mut RequiredComponents,
390        _inheritance_depth: u16,
391    ) {
392    }
393}
394
395/// The storage used for a specific component type.
396///
397/// # Examples
398/// The [`StorageType`] for a component is configured via the derive attribute
399///
400/// ```
401/// # use bevy_ecs::{prelude::*, component::*};
402/// #[derive(Component)]
403/// #[component(storage = "SparseSet")]
404/// struct A;
405/// ```
406#[derive(Debug, Copy, Clone, Default, Eq, PartialEq)]
407pub enum StorageType {
408    /// Provides fast and cache-friendly iteration, but slower addition and removal of components.
409    /// This is the default storage type.
410    #[default]
411    Table,
412    /// Provides fast addition and removal of components, but slower iteration.
413    SparseSet,
414}
415
416/// The type used for [`Component`] lifecycle hooks such as `on_add`, `on_insert` or `on_remove`
417pub type ComponentHook = for<'w> fn(DeferredWorld<'w>, Entity, ComponentId);
418
419/// [`World`]-mutating functions that run as part of lifecycle events of a [`Component`].
420///
421/// Hooks are functions that run when a component is added, overwritten, or removed from an entity.
422/// These are intended to be used for structural side effects that need to happen when a component is added or removed,
423/// and are not intended for general-purpose logic.
424///
425/// For example, you might use a hook to update a cached index when a component is added,
426/// to clean up resources when a component is removed,
427/// or to keep hierarchical data structures across entities in sync.
428///
429/// This information is stored in the [`ComponentInfo`] of the associated component.
430///
431/// There is two ways of configuring hooks for a component:
432/// 1. Defining the [`Component::register_component_hooks`] method (see [`Component`])
433/// 2. Using the [`World::register_component_hooks`] method
434///
435/// # Example 2
436///
437/// ```
438/// use bevy_ecs::prelude::*;
439/// use bevy_utils::HashSet;
440///
441/// #[derive(Component)]
442/// struct MyTrackedComponent;
443///
444/// #[derive(Resource, Default)]
445/// struct TrackedEntities(HashSet<Entity>);
446///
447/// let mut world = World::new();
448/// world.init_resource::<TrackedEntities>();
449///
450/// // No entities with `MyTrackedComponent` have been added yet, so we can safely add component hooks
451/// let mut tracked_component_query = world.query::<&MyTrackedComponent>();
452/// assert!(tracked_component_query.iter(&world).next().is_none());
453///
454/// world.register_component_hooks::<MyTrackedComponent>().on_add(|mut world, entity, _component_id| {
455///    let mut tracked_entities = world.resource_mut::<TrackedEntities>();
456///   tracked_entities.0.insert(entity);
457/// });
458///
459/// world.register_component_hooks::<MyTrackedComponent>().on_remove(|mut world, entity, _component_id| {
460///   let mut tracked_entities = world.resource_mut::<TrackedEntities>();
461///   tracked_entities.0.remove(&entity);
462/// });
463///
464/// let entity = world.spawn(MyTrackedComponent).id();
465/// let tracked_entities = world.resource::<TrackedEntities>();
466/// assert!(tracked_entities.0.contains(&entity));
467///
468/// world.despawn(entity);
469/// let tracked_entities = world.resource::<TrackedEntities>();
470/// assert!(!tracked_entities.0.contains(&entity));
471/// ```
472#[derive(Debug, Clone, Default)]
473pub struct ComponentHooks {
474    pub(crate) on_add: Option<ComponentHook>,
475    pub(crate) on_insert: Option<ComponentHook>,
476    pub(crate) on_replace: Option<ComponentHook>,
477    pub(crate) on_remove: Option<ComponentHook>,
478}
479
480impl ComponentHooks {
481    /// Register a [`ComponentHook`] that will be run when this component is added to an entity.
482    /// An `on_add` hook will always run before `on_insert` hooks. Spawning an entity counts as
483    /// adding all of its components.
484    ///
485    /// # Panics
486    ///
487    /// Will panic if the component already has an `on_add` hook
488    pub fn on_add(&mut self, hook: ComponentHook) -> &mut Self {
489        self.try_on_add(hook)
490            .expect("Component already has an on_add hook")
491    }
492
493    /// Register a [`ComponentHook`] that will be run when this component is added (with `.insert`)
494    /// or replaced.
495    ///
496    /// An `on_insert` hook always runs after any `on_add` hooks (if the entity didn't already have the component).
497    ///
498    /// # Warning
499    ///
500    /// The hook won't run if the component is already present and is only mutated, such as in a system via a query.
501    /// As a result, this is *not* an appropriate mechanism for reliably updating indexes and other caches.
502    ///
503    /// # Panics
504    ///
505    /// Will panic if the component already has an `on_insert` hook
506    pub fn on_insert(&mut self, hook: ComponentHook) -> &mut Self {
507        self.try_on_insert(hook)
508            .expect("Component already has an on_insert hook")
509    }
510
511    /// Register a [`ComponentHook`] that will be run when this component is about to be dropped,
512    /// such as being replaced (with `.insert`) or removed.
513    ///
514    /// If this component is inserted onto an entity that already has it, this hook will run before the value is replaced,
515    /// allowing access to the previous data just before it is dropped.
516    /// This hook does *not* run if the entity did not already have this component.
517    ///
518    /// An `on_replace` hook always runs before any `on_remove` hooks (if the component is being removed from the entity).
519    ///
520    /// # Warning
521    ///
522    /// The hook won't run if the component is already present and is only mutated, such as in a system via a query.
523    /// As a result, this is *not* an appropriate mechanism for reliably updating indexes and other caches.
524    ///
525    /// # Panics
526    ///
527    /// Will panic if the component already has an `on_replace` hook
528    pub fn on_replace(&mut self, hook: ComponentHook) -> &mut Self {
529        self.try_on_replace(hook)
530            .expect("Component already has an on_replace hook")
531    }
532
533    /// Register a [`ComponentHook`] that will be run when this component is removed from an entity.
534    /// Despawning an entity counts as removing all of its components.
535    ///
536    /// # Panics
537    ///
538    /// Will panic if the component already has an `on_remove` hook
539    pub fn on_remove(&mut self, hook: ComponentHook) -> &mut Self {
540        self.try_on_remove(hook)
541            .expect("Component already has an on_remove hook")
542    }
543
544    /// Attempt to register a [`ComponentHook`] that will be run when this component is added to an entity.
545    ///
546    /// This is a fallible version of [`Self::on_add`].
547    ///
548    /// Returns `None` if the component already has an `on_add` hook.
549    pub fn try_on_add(&mut self, hook: ComponentHook) -> Option<&mut Self> {
550        if self.on_add.is_some() {
551            return None;
552        }
553        self.on_add = Some(hook);
554        Some(self)
555    }
556
557    /// Attempt to register a [`ComponentHook`] that will be run when this component is added (with `.insert`)
558    ///
559    /// This is a fallible version of [`Self::on_insert`].
560    ///
561    /// Returns `None` if the component already has an `on_insert` hook.
562    pub fn try_on_insert(&mut self, hook: ComponentHook) -> Option<&mut Self> {
563        if self.on_insert.is_some() {
564            return None;
565        }
566        self.on_insert = Some(hook);
567        Some(self)
568    }
569
570    /// Attempt to register a [`ComponentHook`] that will be run when this component is replaced (with `.insert`) or removed
571    ///
572    /// This is a fallible version of [`Self::on_replace`].
573    ///
574    /// Returns `None` if the component already has an `on_replace` hook.
575    pub fn try_on_replace(&mut self, hook: ComponentHook) -> Option<&mut Self> {
576        if self.on_replace.is_some() {
577            return None;
578        }
579        self.on_replace = Some(hook);
580        Some(self)
581    }
582
583    /// Attempt to register a [`ComponentHook`] that will be run when this component is removed from an entity.
584    ///
585    /// This is a fallible version of [`Self::on_remove`].
586    ///
587    /// Returns `None` if the component already has an `on_remove` hook.
588    pub fn try_on_remove(&mut self, hook: ComponentHook) -> Option<&mut Self> {
589        if self.on_remove.is_some() {
590            return None;
591        }
592        self.on_remove = Some(hook);
593        Some(self)
594    }
595}
596
597/// Stores metadata for a type of component or resource stored in a specific [`World`].
598#[derive(Debug, Clone)]
599pub struct ComponentInfo {
600    id: ComponentId,
601    descriptor: ComponentDescriptor,
602    hooks: ComponentHooks,
603    required_components: RequiredComponents,
604    required_by: HashSet<ComponentId>,
605}
606
607impl ComponentInfo {
608    /// Returns a value uniquely identifying the current component.
609    #[inline]
610    pub fn id(&self) -> ComponentId {
611        self.id
612    }
613
614    /// Returns the name of the current component.
615    #[inline]
616    pub fn name(&self) -> &str {
617        &self.descriptor.name
618    }
619
620    /// Returns the [`TypeId`] of the underlying component type.
621    /// Returns `None` if the component does not correspond to a Rust type.
622    #[inline]
623    pub fn type_id(&self) -> Option<TypeId> {
624        self.descriptor.type_id
625    }
626
627    /// Returns the layout used to store values of this component in memory.
628    #[inline]
629    pub fn layout(&self) -> Layout {
630        self.descriptor.layout
631    }
632
633    #[inline]
634    /// Get the function which should be called to clean up values of
635    /// the underlying component type. This maps to the
636    /// [`Drop`] implementation for 'normal' Rust components
637    ///
638    /// Returns `None` if values of the underlying component type don't
639    /// need to be dropped, e.g. as reported by [`needs_drop`].
640    pub fn drop(&self) -> Option<unsafe fn(OwningPtr<'_>)> {
641        self.descriptor.drop
642    }
643
644    /// Returns a value indicating the storage strategy for the current component.
645    #[inline]
646    pub fn storage_type(&self) -> StorageType {
647        self.descriptor.storage_type
648    }
649
650    /// Returns `true` if the underlying component type can be freely shared between threads.
651    /// If this returns `false`, then extra care must be taken to ensure that components
652    /// are not accessed from the wrong thread.
653    #[inline]
654    pub fn is_send_and_sync(&self) -> bool {
655        self.descriptor.is_send_and_sync
656    }
657
658    /// Create a new [`ComponentInfo`].
659    pub(crate) fn new(id: ComponentId, descriptor: ComponentDescriptor) -> Self {
660        ComponentInfo {
661            id,
662            descriptor,
663            hooks: Default::default(),
664            required_components: Default::default(),
665            required_by: Default::default(),
666        }
667    }
668
669    /// Update the given flags to include any [`ComponentHook`] registered to self
670    #[inline]
671    pub(crate) fn update_archetype_flags(&self, flags: &mut ArchetypeFlags) {
672        if self.hooks().on_add.is_some() {
673            flags.insert(ArchetypeFlags::ON_ADD_HOOK);
674        }
675        if self.hooks().on_insert.is_some() {
676            flags.insert(ArchetypeFlags::ON_INSERT_HOOK);
677        }
678        if self.hooks().on_replace.is_some() {
679            flags.insert(ArchetypeFlags::ON_REPLACE_HOOK);
680        }
681        if self.hooks().on_remove.is_some() {
682            flags.insert(ArchetypeFlags::ON_REMOVE_HOOK);
683        }
684    }
685
686    /// Provides a reference to the collection of hooks associated with this [`Component`]
687    pub fn hooks(&self) -> &ComponentHooks {
688        &self.hooks
689    }
690
691    /// Retrieves the [`RequiredComponents`] collection, which contains all required components (and their constructors)
692    /// needed by this component. This includes _recursive_ required components.
693    pub fn required_components(&self) -> &RequiredComponents {
694        &self.required_components
695    }
696}
697
698/// A value which uniquely identifies the type of a [`Component`] or [`Resource`] within a
699/// [`World`].
700///
701/// Each time a new `Component` type is registered within a `World` using
702/// e.g. [`World::register_component`] or [`World::register_component_with_descriptor`]
703/// or a Resource with e.g. [`World::init_resource`],
704/// a corresponding `ComponentId` is created to track it.
705///
706/// While the distinction between `ComponentId` and [`TypeId`] may seem superficial, breaking them
707/// into two separate but related concepts allows components to exist outside of Rust's type system.
708/// Each Rust type registered as a `Component` will have a corresponding `ComponentId`, but additional
709/// `ComponentId`s may exist in a `World` to track components which cannot be
710/// represented as Rust types for scripting or other advanced use-cases.
711///
712/// A `ComponentId` is tightly coupled to its parent `World`. Attempting to use a `ComponentId` from
713/// one `World` to access the metadata of a `Component` in a different `World` is undefined behavior
714/// and must not be attempted.
715///
716/// Given a type `T` which implements [`Component`], the `ComponentId` for `T` can be retrieved
717/// from a `World` using [`World::component_id()`] or via [`Components::component_id()`]. Access
718/// to the `ComponentId` for a [`Resource`] is available via [`Components::resource_id()`].
719#[derive(Debug, Copy, Clone, Hash, Ord, PartialOrd, Eq, PartialEq)]
720#[cfg_attr(
721    feature = "bevy_reflect",
722    derive(Reflect),
723    reflect(Debug, Hash, PartialEq)
724)]
725pub struct ComponentId(usize);
726
727impl ComponentId {
728    /// Creates a new [`ComponentId`].
729    ///
730    /// The `index` is a unique value associated with each type of component in a given world.
731    /// Usually, this value is taken from a counter incremented for each type of component registered with the world.
732    #[inline]
733    pub const fn new(index: usize) -> ComponentId {
734        ComponentId(index)
735    }
736
737    /// Returns the index of the current component.
738    #[inline]
739    pub fn index(self) -> usize {
740        self.0
741    }
742}
743
744impl SparseSetIndex for ComponentId {
745    #[inline]
746    fn sparse_set_index(&self) -> usize {
747        self.index()
748    }
749
750    #[inline]
751    fn get_sparse_set_index(value: usize) -> Self {
752        Self(value)
753    }
754}
755
756/// A value describing a component or resource, which may or may not correspond to a Rust type.
757#[derive(Clone)]
758pub struct ComponentDescriptor {
759    name: Cow<'static, str>,
760    // SAFETY: This must remain private. It must match the statically known StorageType of the
761    // associated rust component type if one exists.
762    storage_type: StorageType,
763    // SAFETY: This must remain private. It must only be set to "true" if this component is
764    // actually Send + Sync
765    is_send_and_sync: bool,
766    type_id: Option<TypeId>,
767    layout: Layout,
768    // SAFETY: this function must be safe to call with pointers pointing to items of the type
769    // this descriptor describes.
770    // None if the underlying type doesn't need to be dropped
771    drop: Option<for<'a> unsafe fn(OwningPtr<'a>)>,
772}
773
774// We need to ignore the `drop` field in our `Debug` impl
775impl Debug for ComponentDescriptor {
776    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
777        f.debug_struct("ComponentDescriptor")
778            .field("name", &self.name)
779            .field("storage_type", &self.storage_type)
780            .field("is_send_and_sync", &self.is_send_and_sync)
781            .field("type_id", &self.type_id)
782            .field("layout", &self.layout)
783            .finish()
784    }
785}
786
787impl ComponentDescriptor {
788    /// # Safety
789    ///
790    /// `x` must point to a valid value of type `T`.
791    unsafe fn drop_ptr<T>(x: OwningPtr<'_>) {
792        // SAFETY: Contract is required to be upheld by the caller.
793        unsafe {
794            x.drop_as::<T>();
795        }
796    }
797
798    /// Create a new `ComponentDescriptor` for the type `T`.
799    pub fn new<T: Component>() -> Self {
800        Self {
801            name: Cow::Borrowed(core::any::type_name::<T>()),
802            storage_type: T::STORAGE_TYPE,
803            is_send_and_sync: true,
804            type_id: Some(TypeId::of::<T>()),
805            layout: Layout::new::<T>(),
806            drop: needs_drop::<T>().then_some(Self::drop_ptr::<T> as _),
807        }
808    }
809
810    /// Create a new `ComponentDescriptor`.
811    ///
812    /// # Safety
813    /// - the `drop` fn must be usable on a pointer with a value of the layout `layout`
814    /// - the component type must be safe to access from any thread (Send + Sync in rust terms)
815    pub unsafe fn new_with_layout(
816        name: impl Into<Cow<'static, str>>,
817        storage_type: StorageType,
818        layout: Layout,
819        drop: Option<for<'a> unsafe fn(OwningPtr<'a>)>,
820    ) -> Self {
821        Self {
822            name: name.into(),
823            storage_type,
824            is_send_and_sync: true,
825            type_id: None,
826            layout,
827            drop,
828        }
829    }
830
831    /// Create a new `ComponentDescriptor` for a resource.
832    ///
833    /// The [`StorageType`] for resources is always [`StorageType::Table`].
834    pub fn new_resource<T: Resource>() -> Self {
835        Self {
836            name: Cow::Borrowed(core::any::type_name::<T>()),
837            // PERF: `SparseStorage` may actually be a more
838            // reasonable choice as `storage_type` for resources.
839            storage_type: StorageType::Table,
840            is_send_and_sync: true,
841            type_id: Some(TypeId::of::<T>()),
842            layout: Layout::new::<T>(),
843            drop: needs_drop::<T>().then_some(Self::drop_ptr::<T> as _),
844        }
845    }
846
847    fn new_non_send<T: Any>(storage_type: StorageType) -> Self {
848        Self {
849            name: Cow::Borrowed(core::any::type_name::<T>()),
850            storage_type,
851            is_send_and_sync: false,
852            type_id: Some(TypeId::of::<T>()),
853            layout: Layout::new::<T>(),
854            drop: needs_drop::<T>().then_some(Self::drop_ptr::<T> as _),
855        }
856    }
857
858    /// Returns a value indicating the storage strategy for the current component.
859    #[inline]
860    pub fn storage_type(&self) -> StorageType {
861        self.storage_type
862    }
863
864    /// Returns the [`TypeId`] of the underlying component type.
865    /// Returns `None` if the component does not correspond to a Rust type.
866    #[inline]
867    pub fn type_id(&self) -> Option<TypeId> {
868        self.type_id
869    }
870
871    /// Returns the name of the current component.
872    #[inline]
873    pub fn name(&self) -> &str {
874        self.name.as_ref()
875    }
876}
877
878/// Stores metadata associated with each kind of [`Component`] in a given [`World`].
879#[derive(Debug, Default)]
880pub struct Components {
881    components: Vec<ComponentInfo>,
882    indices: TypeIdMap<ComponentId>,
883    resource_indices: TypeIdMap<ComponentId>,
884}
885
886impl Components {
887    /// Registers a [`Component`] of type `T` with this instance.
888    /// If a component of this type has already been registered, this will return
889    /// the ID of the pre-existing component.
890    ///
891    /// # See also
892    ///
893    /// * [`Components::component_id()`]
894    /// * [`Components::register_component_with_descriptor()`]
895    #[inline]
896    pub fn register_component<T: Component>(&mut self, storages: &mut Storages) -> ComponentId {
897        let mut registered = false;
898        let id = {
899            let Components {
900                indices,
901                components,
902                ..
903            } = self;
904            let type_id = TypeId::of::<T>();
905            *indices.entry(type_id).or_insert_with(|| {
906                let id = Components::register_component_inner(
907                    components,
908                    storages,
909                    ComponentDescriptor::new::<T>(),
910                );
911                registered = true;
912                id
913            })
914        };
915        if registered {
916            let mut required_components = RequiredComponents::default();
917            T::register_required_components(id, self, storages, &mut required_components, 0);
918            let info = &mut self.components[id.index()];
919            T::register_component_hooks(&mut info.hooks);
920            info.required_components = required_components;
921        }
922        id
923    }
924
925    /// Registers a component described by `descriptor`.
926    ///
927    /// # Note
928    ///
929    /// If this method is called multiple times with identical descriptors, a distinct [`ComponentId`]
930    /// will be created for each one.
931    ///
932    /// # See also
933    ///
934    /// * [`Components::component_id()`]
935    /// * [`Components::register_component()`]
936    pub fn register_component_with_descriptor(
937        &mut self,
938        storages: &mut Storages,
939        descriptor: ComponentDescriptor,
940    ) -> ComponentId {
941        Components::register_component_inner(&mut self.components, storages, descriptor)
942    }
943
944    #[inline]
945    fn register_component_inner(
946        components: &mut Vec<ComponentInfo>,
947        storages: &mut Storages,
948        descriptor: ComponentDescriptor,
949    ) -> ComponentId {
950        let component_id = ComponentId(components.len());
951        let info = ComponentInfo::new(component_id, descriptor);
952        if info.descriptor.storage_type == StorageType::SparseSet {
953            storages.sparse_sets.get_or_insert(&info);
954        }
955        components.push(info);
956        component_id
957    }
958
959    /// Returns the number of components registered with this instance.
960    #[inline]
961    pub fn len(&self) -> usize {
962        self.components.len()
963    }
964
965    /// Returns `true` if there are no components registered with this instance. Otherwise, this returns `false`.
966    #[inline]
967    pub fn is_empty(&self) -> bool {
968        self.components.len() == 0
969    }
970
971    /// Gets the metadata associated with the given component.
972    ///
973    /// 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.
974    #[inline]
975    pub fn get_info(&self, id: ComponentId) -> Option<&ComponentInfo> {
976        self.components.get(id.0)
977    }
978
979    /// Returns the name associated with the given component.
980    ///
981    /// 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.
982    #[inline]
983    pub fn get_name(&self, id: ComponentId) -> Option<&str> {
984        self.get_info(id).map(ComponentInfo::name)
985    }
986
987    /// Gets the metadata associated with the given component.
988    /// # Safety
989    ///
990    /// `id` must be a valid [`ComponentId`]
991    #[inline]
992    pub unsafe fn get_info_unchecked(&self, id: ComponentId) -> &ComponentInfo {
993        debug_assert!(id.index() < self.components.len());
994        // SAFETY: The caller ensures `id` is valid.
995        unsafe { self.components.get_unchecked(id.0) }
996    }
997
998    #[inline]
999    pub(crate) fn get_hooks_mut(&mut self, id: ComponentId) -> Option<&mut ComponentHooks> {
1000        self.components.get_mut(id.0).map(|info| &mut info.hooks)
1001    }
1002
1003    #[inline]
1004    pub(crate) fn get_required_components_mut(
1005        &mut self,
1006        id: ComponentId,
1007    ) -> Option<&mut RequiredComponents> {
1008        self.components
1009            .get_mut(id.0)
1010            .map(|info| &mut info.required_components)
1011    }
1012
1013    /// Registers the given component `R` and [required components] inherited from it as required by `T`.
1014    ///
1015    /// When `T` is added to an entity, `R` will also be added if it was not already provided.
1016    /// The given `constructor` will be used for the creation of `R`.
1017    ///
1018    /// [required components]: Component#required-components
1019    ///
1020    /// # Safety
1021    ///
1022    /// The given component IDs `required` and `requiree` must be valid.
1023    ///
1024    /// # Errors
1025    ///
1026    /// Returns a [`RequiredComponentsError`] if the `required` component is already a directly required component for the `requiree`.
1027    ///
1028    /// Indirect requirements through other components are allowed. In those cases, the more specific
1029    /// registration will be used.
1030    pub(crate) unsafe fn register_required_components<R: Component>(
1031        &mut self,
1032        requiree: ComponentId,
1033        required: ComponentId,
1034        constructor: fn() -> R,
1035    ) -> Result<(), RequiredComponentsError> {
1036        // SAFETY: The caller ensures that the `requiree` is valid.
1037        let required_components = unsafe {
1038            self.get_required_components_mut(requiree)
1039                .debug_checked_unwrap()
1040        };
1041
1042        // Cannot directly require the same component twice.
1043        if required_components
1044            .0
1045            .get(&required)
1046            .is_some_and(|c| c.inheritance_depth == 0)
1047        {
1048            return Err(RequiredComponentsError::DuplicateRegistration(
1049                requiree, required,
1050            ));
1051        }
1052
1053        // Register the required component for the requiree.
1054        // This is a direct requirement with a depth of `0`.
1055        required_components.register_by_id(required, constructor, 0);
1056
1057        // Add the requiree to the list of components that require the required component.
1058        // SAFETY: The component is in the list of required components, so it must exist already.
1059        let required_by = unsafe { self.get_required_by_mut(required).debug_checked_unwrap() };
1060        required_by.insert(requiree);
1061
1062        // SAFETY: The caller ensures that the `requiree` and `required` components are valid.
1063        let inherited_requirements =
1064            unsafe { self.register_inherited_required_components(requiree, required) };
1065
1066        // Propagate the new required components up the chain to all components that require the requiree.
1067        if let Some(required_by) = self.get_required_by(requiree).cloned() {
1068            // `required` is now required by anything that `requiree` was required by.
1069            self.get_required_by_mut(required)
1070                .unwrap()
1071                .extend(required_by.iter().copied());
1072            for &required_by_id in required_by.iter() {
1073                // SAFETY: The component is in the list of required components, so it must exist already.
1074                let required_components = unsafe {
1075                    self.get_required_components_mut(required_by_id)
1076                        .debug_checked_unwrap()
1077                };
1078
1079                // Register the original required component in the "parent" of the requiree.
1080                // The inheritance depth is 1 deeper than the `requiree` wrt `required_by_id`.
1081                let depth = required_components.0.get(&requiree).expect("requiree is required by required_by_id, so its required_components must include requiree").inheritance_depth;
1082                required_components.register_by_id(required, constructor, depth + 1);
1083
1084                for (component_id, component) in inherited_requirements.iter() {
1085                    // Register the required component.
1086                    // The inheritance depth of inherited components is whatever the requiree's
1087                    // depth is relative to `required_by_id`, plus the inheritance depth of the
1088                    // inherited component relative to the requiree, plus 1 to account for the
1089                    // requiree in between.
1090                    // SAFETY: Component ID and constructor match the ones on the original requiree.
1091                    //         The original requiree is responsible for making sure the registration is safe.
1092                    unsafe {
1093                        required_components.register_dynamic(
1094                            *component_id,
1095                            component.constructor.clone(),
1096                            component.inheritance_depth + depth + 1,
1097                        );
1098                    };
1099                }
1100            }
1101        }
1102
1103        Ok(())
1104    }
1105
1106    /// Registers the components inherited from `required` for the given `requiree`,
1107    /// returning the requirements in a list.
1108    ///
1109    /// # Safety
1110    ///
1111    /// The given component IDs `requiree` and `required` must be valid.
1112    unsafe fn register_inherited_required_components(
1113        &mut self,
1114        requiree: ComponentId,
1115        required: ComponentId,
1116    ) -> Vec<(ComponentId, RequiredComponent)> {
1117        // Get required components inherited from the `required` component.
1118        // SAFETY: The caller ensures that the `required` component is valid.
1119        let required_component_info = unsafe { self.get_info(required).debug_checked_unwrap() };
1120        let inherited_requirements: Vec<(ComponentId, RequiredComponent)> = required_component_info
1121            .required_components()
1122            .0
1123            .iter()
1124            .map(|(component_id, required_component)| {
1125                (
1126                    *component_id,
1127                    RequiredComponent {
1128                        constructor: required_component.constructor.clone(),
1129                        // Add `1` to the inheritance depth since this will be registered
1130                        // for the component that requires `required`.
1131                        inheritance_depth: required_component.inheritance_depth + 1,
1132                    },
1133                )
1134            })
1135            .collect();
1136
1137        // Register the new required components.
1138        for (component_id, component) in inherited_requirements.iter().cloned() {
1139            // SAFETY: The caller ensures that the `requiree` is valid.
1140            let required_components = unsafe {
1141                self.get_required_components_mut(requiree)
1142                    .debug_checked_unwrap()
1143            };
1144
1145            // Register the required component for the requiree.
1146            // SAFETY: Component ID and constructor match the ones on the original requiree.
1147            unsafe {
1148                required_components.register_dynamic(
1149                    component_id,
1150                    component.constructor,
1151                    component.inheritance_depth,
1152                );
1153            };
1154
1155            // Add the requiree to the list of components that require the required component.
1156            // SAFETY: The caller ensures that the required components are valid.
1157            let required_by = unsafe {
1158                self.get_required_by_mut(component_id)
1159                    .debug_checked_unwrap()
1160            };
1161            required_by.insert(requiree);
1162        }
1163
1164        inherited_requirements
1165    }
1166
1167    // NOTE: This should maybe be private, but it is currently public so that `bevy_ecs_macros` can use it.
1168    //       We can't directly move this there either, because this uses `Components::get_required_by_mut`,
1169    //       which is private, and could be equally risky to expose to users.
1170    /// Registers the given component `R` and [required components] inherited from it as required by `T`,
1171    /// and adds `T` to their lists of requirees.
1172    ///
1173    /// The given `inheritance_depth` determines how many levels of inheritance deep the requirement is.
1174    /// A direct requirement has a depth of `0`, and each level of inheritance increases the depth by `1`.
1175    /// Lower depths are more specific requirements, and can override existing less specific registrations.
1176    ///
1177    /// This method does *not* register any components as required by components that require `T`.
1178    ///
1179    /// Only use this method if you know what you are doing. In most cases, you should instead use [`World::register_required_components`],
1180    /// or the equivalent method in `bevy_app::App`.
1181    ///
1182    /// [required component]: Component#required-components
1183    #[doc(hidden)]
1184    pub fn register_required_components_manual<T: Component, R: Component>(
1185        &mut self,
1186        storages: &mut Storages,
1187        required_components: &mut RequiredComponents,
1188        constructor: fn() -> R,
1189        inheritance_depth: u16,
1190    ) {
1191        let requiree = self.register_component::<T>(storages);
1192        let required = self.register_component::<R>(storages);
1193
1194        // SAFETY: We just created the components.
1195        unsafe {
1196            self.register_required_components_manual_unchecked::<R>(
1197                requiree,
1198                required,
1199                required_components,
1200                constructor,
1201                inheritance_depth,
1202            );
1203        }
1204    }
1205
1206    /// Registers the given component `R` and [required components] inherited from it as required by `T`,
1207    /// and adds `T` to their lists of requirees.
1208    ///
1209    /// The given `inheritance_depth` determines how many levels of inheritance deep the requirement is.
1210    /// A direct requirement has a depth of `0`, and each level of inheritance increases the depth by `1`.
1211    /// Lower depths are more specific requirements, and can override existing less specific registrations.
1212    ///
1213    /// This method does *not* register any components as required by components that require `T`.
1214    ///
1215    /// [required component]: Component#required-components
1216    ///
1217    /// # Safety
1218    ///
1219    /// The given component IDs `required` and `requiree` must be valid.
1220    pub(crate) unsafe fn register_required_components_manual_unchecked<R: Component>(
1221        &mut self,
1222        requiree: ComponentId,
1223        required: ComponentId,
1224        required_components: &mut RequiredComponents,
1225        constructor: fn() -> R,
1226        inheritance_depth: u16,
1227    ) {
1228        // Components cannot require themselves.
1229        if required == requiree {
1230            return;
1231        }
1232
1233        // Register the required component `R` for the requiree.
1234        required_components.register_by_id(required, constructor, inheritance_depth);
1235
1236        // Add the requiree to the list of components that require `R`.
1237        // SAFETY: The caller ensures that the component ID is valid.
1238        //         Assuming it is valid, the component is in the list of required components, so it must exist already.
1239        let required_by = unsafe { self.get_required_by_mut(required).debug_checked_unwrap() };
1240        required_by.insert(requiree);
1241
1242        // Register the inherited required components for the requiree.
1243        let required: Vec<(ComponentId, RequiredComponent)> = self
1244            .get_info(required)
1245            .unwrap()
1246            .required_components()
1247            .0
1248            .iter()
1249            .map(|(id, component)| (*id, component.clone()))
1250            .collect();
1251
1252        for (id, component) in required {
1253            // Register the inherited required components for the requiree.
1254            // The inheritance depth is increased by `1` since this is a component required by the original required component.
1255            required_components.register_dynamic(
1256                id,
1257                component.constructor.clone(),
1258                component.inheritance_depth + 1,
1259            );
1260            self.get_required_by_mut(id).unwrap().insert(requiree);
1261        }
1262    }
1263
1264    #[inline]
1265    pub(crate) fn get_required_by(&self, id: ComponentId) -> Option<&HashSet<ComponentId>> {
1266        self.components.get(id.0).map(|info| &info.required_by)
1267    }
1268
1269    #[inline]
1270    pub(crate) fn get_required_by_mut(
1271        &mut self,
1272        id: ComponentId,
1273    ) -> Option<&mut HashSet<ComponentId>> {
1274        self.components
1275            .get_mut(id.0)
1276            .map(|info| &mut info.required_by)
1277    }
1278
1279    /// Type-erased equivalent of [`Components::component_id()`].
1280    #[inline]
1281    pub fn get_id(&self, type_id: TypeId) -> Option<ComponentId> {
1282        self.indices.get(&type_id).copied()
1283    }
1284
1285    /// Returns the [`ComponentId`] of the given [`Component`] type `T`.
1286    ///
1287    /// The returned `ComponentId` is specific to the `Components` instance
1288    /// it was retrieved from and should not be used with another `Components`
1289    /// instance.
1290    ///
1291    /// Returns [`None`] if the `Component` type has not
1292    /// yet been initialized using [`Components::register_component()`].
1293    ///
1294    /// ```
1295    /// use bevy_ecs::prelude::*;
1296    ///
1297    /// let mut world = World::new();
1298    ///
1299    /// #[derive(Component)]
1300    /// struct ComponentA;
1301    ///
1302    /// let component_a_id = world.register_component::<ComponentA>();
1303    ///
1304    /// assert_eq!(component_a_id, world.components().component_id::<ComponentA>().unwrap())
1305    /// ```
1306    ///
1307    /// # See also
1308    ///
1309    /// * [`Components::get_id()`]
1310    /// * [`Components::resource_id()`]
1311    /// * [`World::component_id()`]
1312    #[inline]
1313    pub fn component_id<T: Component>(&self) -> Option<ComponentId> {
1314        self.get_id(TypeId::of::<T>())
1315    }
1316
1317    /// Type-erased equivalent of [`Components::resource_id()`].
1318    #[inline]
1319    pub fn get_resource_id(&self, type_id: TypeId) -> Option<ComponentId> {
1320        self.resource_indices.get(&type_id).copied()
1321    }
1322
1323    /// Returns the [`ComponentId`] of the given [`Resource`] type `T`.
1324    ///
1325    /// The returned `ComponentId` is specific to the `Components` instance
1326    /// it was retrieved from and should not be used with another `Components`
1327    /// instance.
1328    ///
1329    /// Returns [`None`] if the `Resource` type has not
1330    /// yet been initialized using [`Components::register_resource()`].
1331    ///
1332    /// ```
1333    /// use bevy_ecs::prelude::*;
1334    ///
1335    /// let mut world = World::new();
1336    ///
1337    /// #[derive(Resource, Default)]
1338    /// struct ResourceA;
1339    ///
1340    /// let resource_a_id = world.init_resource::<ResourceA>();
1341    ///
1342    /// assert_eq!(resource_a_id, world.components().resource_id::<ResourceA>().unwrap())
1343    /// ```
1344    ///
1345    /// # See also
1346    ///
1347    /// * [`Components::component_id()`]
1348    /// * [`Components::get_resource_id()`]
1349    #[inline]
1350    pub fn resource_id<T: Resource>(&self) -> Option<ComponentId> {
1351        self.get_resource_id(TypeId::of::<T>())
1352    }
1353
1354    /// Registers a [`Resource`] of type `T` with this instance.
1355    /// If a resource of this type has already been registered, this will return
1356    /// the ID of the pre-existing resource.
1357    ///
1358    /// # See also
1359    ///
1360    /// * [`Components::resource_id()`]
1361    /// * [`Components::register_resource_with_descriptor()`]
1362    #[inline]
1363    pub fn register_resource<T: Resource>(&mut self) -> ComponentId {
1364        // SAFETY: The [`ComponentDescriptor`] matches the [`TypeId`]
1365        unsafe {
1366            self.get_or_register_resource_with(TypeId::of::<T>(), || {
1367                ComponentDescriptor::new_resource::<T>()
1368            })
1369        }
1370    }
1371
1372    /// Registers a [`Resource`] described by `descriptor`.
1373    ///
1374    /// # Note
1375    ///
1376    /// If this method is called multiple times with identical descriptors, a distinct [`ComponentId`]
1377    /// will be created for each one.
1378    ///
1379    /// # See also
1380    ///
1381    /// * [`Components::resource_id()`]
1382    /// * [`Components::register_resource()`]
1383    pub fn register_resource_with_descriptor(
1384        &mut self,
1385        descriptor: ComponentDescriptor,
1386    ) -> ComponentId {
1387        Components::register_resource_inner(&mut self.components, descriptor)
1388    }
1389
1390    /// Registers a [non-send resource](crate::system::NonSend) of type `T` with this instance.
1391    /// If a resource of this type has already been registered, this will return
1392    /// the ID of the pre-existing resource.
1393    #[inline]
1394    pub fn register_non_send<T: Any>(&mut self) -> ComponentId {
1395        // SAFETY: The [`ComponentDescriptor`] matches the [`TypeId`]
1396        unsafe {
1397            self.get_or_register_resource_with(TypeId::of::<T>(), || {
1398                ComponentDescriptor::new_non_send::<T>(StorageType::default())
1399            })
1400        }
1401    }
1402
1403    /// # Safety
1404    ///
1405    /// The [`ComponentDescriptor`] must match the [`TypeId`]
1406    #[inline]
1407    unsafe fn get_or_register_resource_with(
1408        &mut self,
1409        type_id: TypeId,
1410        func: impl FnOnce() -> ComponentDescriptor,
1411    ) -> ComponentId {
1412        let components = &mut self.components;
1413        *self.resource_indices.entry(type_id).or_insert_with(|| {
1414            let descriptor = func();
1415            Components::register_resource_inner(components, descriptor)
1416        })
1417    }
1418
1419    #[inline]
1420    fn register_resource_inner(
1421        components: &mut Vec<ComponentInfo>,
1422        descriptor: ComponentDescriptor,
1423    ) -> ComponentId {
1424        let component_id = ComponentId(components.len());
1425        components.push(ComponentInfo::new(component_id, descriptor));
1426        component_id
1427    }
1428
1429    /// Gets an iterator over all components registered with this instance.
1430    pub fn iter(&self) -> impl Iterator<Item = &ComponentInfo> + '_ {
1431        self.components.iter()
1432    }
1433}
1434
1435/// A value that tracks when a system ran relative to other systems.
1436/// This is used to power change detection.
1437///
1438/// *Note* that a system that hasn't been run yet has a `Tick` of 0.
1439#[derive(Copy, Clone, Default, Debug, Eq, Hash, PartialEq)]
1440#[cfg_attr(
1441    feature = "bevy_reflect",
1442    derive(Reflect),
1443    reflect(Debug, Hash, PartialEq)
1444)]
1445pub struct Tick {
1446    tick: u32,
1447}
1448
1449impl Tick {
1450    /// The maximum relative age for a change tick.
1451    /// The value of this is equal to [`MAX_CHANGE_AGE`].
1452    ///
1453    /// Since change detection will not work for any ticks older than this,
1454    /// ticks are periodically scanned to ensure their relative values are below this.
1455    pub const MAX: Self = Self::new(MAX_CHANGE_AGE);
1456
1457    /// Creates a new [`Tick`] wrapping the given value.
1458    #[inline]
1459    pub const fn new(tick: u32) -> Self {
1460        Self { tick }
1461    }
1462
1463    /// Gets the value of this change tick.
1464    #[inline]
1465    pub const fn get(self) -> u32 {
1466        self.tick
1467    }
1468
1469    /// Sets the value of this change tick.
1470    #[inline]
1471    pub fn set(&mut self, tick: u32) {
1472        self.tick = tick;
1473    }
1474
1475    /// Returns `true` if this `Tick` occurred since the system's `last_run`.
1476    ///
1477    /// `this_run` is the current tick of the system, used as a reference to help deal with wraparound.
1478    #[inline]
1479    pub fn is_newer_than(self, last_run: Tick, this_run: Tick) -> bool {
1480        // This works even with wraparound because the world tick (`this_run`) is always "newer" than
1481        // `last_run` and `self.tick`, and we scan periodically to clamp `ComponentTicks` values
1482        // so they never get older than `u32::MAX` (the difference would overflow).
1483        //
1484        // The clamp here ensures determinism (since scans could differ between app runs).
1485        let ticks_since_insert = this_run.relative_to(self).tick.min(MAX_CHANGE_AGE);
1486        let ticks_since_system = this_run.relative_to(last_run).tick.min(MAX_CHANGE_AGE);
1487
1488        ticks_since_system > ticks_since_insert
1489    }
1490
1491    /// Returns a change tick representing the relationship between `self` and `other`.
1492    #[inline]
1493    pub(crate) fn relative_to(self, other: Self) -> Self {
1494        let tick = self.tick.wrapping_sub(other.tick);
1495        Self { tick }
1496    }
1497
1498    /// Wraps this change tick's value if it exceeds [`Tick::MAX`].
1499    ///
1500    /// Returns `true` if wrapping was performed. Otherwise, returns `false`.
1501    #[inline]
1502    pub(crate) fn check_tick(&mut self, tick: Tick) -> bool {
1503        let age = tick.relative_to(*self);
1504        // This comparison assumes that `age` has not overflowed `u32::MAX` before, which will be true
1505        // so long as this check always runs before that can happen.
1506        if age.get() > Self::MAX.get() {
1507            *self = tick.relative_to(Self::MAX);
1508            true
1509        } else {
1510            false
1511        }
1512    }
1513}
1514
1515/// Interior-mutable access to the [`Tick`]s for a single component or resource.
1516#[derive(Copy, Clone, Debug)]
1517pub struct TickCells<'a> {
1518    /// The tick indicating when the value was added to the world.
1519    pub added: &'a UnsafeCell<Tick>,
1520    /// The tick indicating the last time the value was modified.
1521    pub changed: &'a UnsafeCell<Tick>,
1522}
1523
1524impl<'a> TickCells<'a> {
1525    /// # Safety
1526    /// All cells contained within must uphold the safety invariants of [`UnsafeCellDeref::read`].
1527    #[inline]
1528    pub(crate) unsafe fn read(&self) -> ComponentTicks {
1529        ComponentTicks {
1530            // SAFETY: The callers uphold the invariants for `read`.
1531            added: unsafe { self.added.read() },
1532            // SAFETY: The callers uphold the invariants for `read`.
1533            changed: unsafe { self.changed.read() },
1534        }
1535    }
1536}
1537
1538/// Records when a component or resource was added and when it was last mutably dereferenced (or added).
1539#[derive(Copy, Clone, Debug)]
1540#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug))]
1541pub struct ComponentTicks {
1542    /// Tick recording the time this component or resource was added.
1543    pub added: Tick,
1544
1545    /// Tick recording the time this component or resource was most recently changed.
1546    pub changed: Tick,
1547}
1548
1549impl ComponentTicks {
1550    /// Returns `true` if the component or resource was added after the system last ran
1551    /// (or the system is running for the first time).
1552    #[inline]
1553    pub fn is_added(&self, last_run: Tick, this_run: Tick) -> bool {
1554        self.added.is_newer_than(last_run, this_run)
1555    }
1556
1557    /// Returns `true` if the component or resource was added or mutably dereferenced after the system last ran
1558    /// (or the system is running for the first time).
1559    #[inline]
1560    pub fn is_changed(&self, last_run: Tick, this_run: Tick) -> bool {
1561        self.changed.is_newer_than(last_run, this_run)
1562    }
1563
1564    /// Creates a new instance with the same change tick for `added` and `changed`.
1565    pub fn new(change_tick: Tick) -> Self {
1566        Self {
1567            added: change_tick,
1568            changed: change_tick,
1569        }
1570    }
1571
1572    /// Manually sets the change tick.
1573    ///
1574    /// This is normally done automatically via the [`DerefMut`](std::ops::DerefMut) implementation
1575    /// on [`Mut<T>`](crate::change_detection::Mut), [`ResMut<T>`](crate::change_detection::ResMut), etc.
1576    /// However, components and resources that make use of interior mutability might require manual updates.
1577    ///
1578    /// # Example
1579    /// ```no_run
1580    /// # use bevy_ecs::{world::World, component::ComponentTicks};
1581    /// let world: World = unimplemented!();
1582    /// let component_ticks: ComponentTicks = unimplemented!();
1583    ///
1584    /// component_ticks.set_changed(world.read_change_tick());
1585    /// ```
1586    #[inline]
1587    pub fn set_changed(&mut self, change_tick: Tick) {
1588        self.changed = change_tick;
1589    }
1590}
1591
1592/// A [`SystemParam`] that provides access to the [`ComponentId`] for a specific component type.
1593///
1594/// # Example
1595/// ```
1596/// # use bevy_ecs::{system::Local, component::{Component, ComponentId, ComponentIdFor}};
1597/// #[derive(Component)]
1598/// struct Player;
1599/// fn my_system(component_id: ComponentIdFor<Player>) {
1600///     let component_id: ComponentId = component_id.get();
1601///     // ...
1602/// }
1603/// ```
1604#[derive(SystemParam)]
1605pub struct ComponentIdFor<'s, T: Component>(Local<'s, InitComponentId<T>>);
1606
1607impl<T: Component> ComponentIdFor<'_, T> {
1608    /// Gets the [`ComponentId`] for the type `T`.
1609    #[inline]
1610    pub fn get(&self) -> ComponentId {
1611        **self
1612    }
1613}
1614
1615impl<T: Component> core::ops::Deref for ComponentIdFor<'_, T> {
1616    type Target = ComponentId;
1617    fn deref(&self) -> &Self::Target {
1618        &self.0.component_id
1619    }
1620}
1621
1622impl<T: Component> From<ComponentIdFor<'_, T>> for ComponentId {
1623    #[inline]
1624    fn from(to_component_id: ComponentIdFor<T>) -> ComponentId {
1625        *to_component_id
1626    }
1627}
1628
1629/// Initializes the [`ComponentId`] for a specific type when used with [`FromWorld`].
1630struct InitComponentId<T: Component> {
1631    component_id: ComponentId,
1632    marker: PhantomData<T>,
1633}
1634
1635impl<T: Component> FromWorld for InitComponentId<T> {
1636    fn from_world(world: &mut World) -> Self {
1637        Self {
1638            component_id: world.register_component::<T>(),
1639            marker: PhantomData,
1640        }
1641    }
1642}
1643
1644/// An error returned when the registration of a required component fails.
1645#[derive(Error, Display, Debug)]
1646#[non_exhaustive]
1647pub enum RequiredComponentsError {
1648    /// The component is already a directly required component for the requiree.
1649    #[display("Component {0:?} already directly requires component {_1:?}")]
1650    #[error(ignore)]
1651    DuplicateRegistration(ComponentId, ComponentId),
1652    /// An archetype with the component that requires other components already exists
1653    #[display(
1654        "An archetype with the component {_0:?} that requires other components already exists"
1655    )]
1656    #[error(ignore)]
1657    ArchetypeExists(ComponentId),
1658}
1659
1660/// A Required Component constructor. See [`Component`] for details.
1661#[cfg(feature = "track_change_detection")]
1662#[derive(Clone)]
1663pub struct RequiredComponentConstructor(
1664    pub Arc<dyn Fn(&mut Table, &mut SparseSets, Tick, TableRow, Entity, &'static Location<'static>)>,
1665);
1666
1667/// A Required Component constructor. See [`Component`] for details.
1668#[cfg(not(feature = "track_change_detection"))]
1669#[derive(Clone)]
1670pub struct RequiredComponentConstructor(
1671    pub Arc<dyn Fn(&mut Table, &mut SparseSets, Tick, TableRow, Entity)>,
1672);
1673
1674impl RequiredComponentConstructor {
1675    /// # Safety
1676    /// This is intended to only be called in the context of [`BundleInfo::write_components`] to initialized required components.
1677    /// Calling it _anywhere else_ should be considered unsafe.
1678    ///
1679    /// `table_row` and `entity` must correspond to a valid entity that currently needs a component initialized via the constructor stored
1680    /// on this [`RequiredComponentConstructor`]. The stored constructor must correspond to a component on `entity` that needs initialization.
1681    /// `table` and `sparse_sets` must correspond to storages on a world where `entity` needs this required component initialized.
1682    ///
1683    /// Again, don't call this anywhere but [`BundleInfo::write_components`].
1684    pub(crate) unsafe fn initialize(
1685        &self,
1686        table: &mut Table,
1687        sparse_sets: &mut SparseSets,
1688        change_tick: Tick,
1689        table_row: TableRow,
1690        entity: Entity,
1691        #[cfg(feature = "track_change_detection")] caller: &'static Location<'static>,
1692    ) {
1693        (self.0)(
1694            table,
1695            sparse_sets,
1696            change_tick,
1697            table_row,
1698            entity,
1699            #[cfg(feature = "track_change_detection")]
1700            caller,
1701        );
1702    }
1703}
1704
1705/// Metadata associated with a required component. See [`Component`] for details.
1706#[derive(Clone)]
1707pub struct RequiredComponent {
1708    /// The constructor used for the required component.
1709    pub constructor: RequiredComponentConstructor,
1710
1711    /// The depth of the component requirement in the requirement hierarchy for this component.
1712    /// This is used for determining which constructor is used in cases where there are duplicate requires.
1713    ///
1714    /// For example, consider the inheritance tree `X -> Y -> Z`, where `->` indicates a requirement.
1715    /// `X -> Y` and `Y -> Z` are direct requirements with a depth of 0, while `Z` is only indirectly
1716    /// required for `X` with a depth of `1`.
1717    ///
1718    /// In cases where there are multiple conflicting requirements with the same depth, a higher priority
1719    /// will be given to components listed earlier in the `require` attribute, or to the latest added requirement
1720    /// if registered at runtime.
1721    pub inheritance_depth: u16,
1722}
1723
1724/// The collection of metadata for components that are required for a given component.
1725///
1726/// For more information, see the "Required Components" section of [`Component`].
1727#[derive(Default, Clone)]
1728pub struct RequiredComponents(pub(crate) HashMap<ComponentId, RequiredComponent>);
1729
1730impl Debug for RequiredComponents {
1731    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1732        f.debug_tuple("RequiredComponents")
1733            .field(&self.0.keys())
1734            .finish()
1735    }
1736}
1737
1738impl RequiredComponents {
1739    /// Registers a required component.
1740    ///
1741    /// If the component is already registered, it will be overwritten if the given inheritance depth
1742    /// is smaller than the depth of the existing registration. Otherwise, the new registration will be ignored.
1743    ///
1744    /// # Safety
1745    ///
1746    /// `component_id` must match the type initialized by `constructor`.
1747    /// `constructor` _must_ initialize a component for `component_id` in such a way that
1748    /// matches the storage type of the component. It must only use the given `table_row` or `Entity` to
1749    /// initialize the storage for `component_id` corresponding to the given entity.
1750    pub unsafe fn register_dynamic(
1751        &mut self,
1752        component_id: ComponentId,
1753        constructor: RequiredComponentConstructor,
1754        inheritance_depth: u16,
1755    ) {
1756        self.0
1757            .entry(component_id)
1758            .and_modify(|component| {
1759                if component.inheritance_depth > inheritance_depth {
1760                    // New registration is more specific than existing requirement
1761                    component.constructor = constructor.clone();
1762                    component.inheritance_depth = inheritance_depth;
1763                }
1764            })
1765            .or_insert(RequiredComponent {
1766                constructor,
1767                inheritance_depth,
1768            });
1769    }
1770
1771    /// Registers a required component.
1772    ///
1773    /// If the component is already registered, it will be overwritten if the given inheritance depth
1774    /// is smaller than the depth of the existing registration. Otherwise, the new registration will be ignored.
1775    pub fn register<C: Component>(
1776        &mut self,
1777        components: &mut Components,
1778        storages: &mut Storages,
1779        constructor: fn() -> C,
1780        inheritance_depth: u16,
1781    ) {
1782        let component_id = components.register_component::<C>(storages);
1783        self.register_by_id(component_id, constructor, inheritance_depth);
1784    }
1785
1786    /// Registers the [`Component`] with the given ID as required if it exists.
1787    ///
1788    /// If the component is already registered, it will be overwritten if the given inheritance depth
1789    /// is smaller than the depth of the existing registration. Otherwise, the new registration will be ignored.
1790    pub fn register_by_id<C: Component>(
1791        &mut self,
1792        component_id: ComponentId,
1793        constructor: fn() -> C,
1794        inheritance_depth: u16,
1795    ) {
1796        let erased: RequiredComponentConstructor = RequiredComponentConstructor(Arc::new(
1797            move |table,
1798                  sparse_sets,
1799                  change_tick,
1800                  table_row,
1801                  entity,
1802                  #[cfg(feature = "track_change_detection")] caller| {
1803                OwningPtr::make(constructor(), |ptr| {
1804                    // SAFETY: This will only be called in the context of `BundleInfo::write_components`, which will
1805                    // pass in a valid table_row and entity requiring a C constructor
1806                    // C::STORAGE_TYPE is the storage type associated with `component_id` / `C`
1807                    // `ptr` points to valid `C` data, which matches the type associated with `component_id`
1808                    unsafe {
1809                        BundleInfo::initialize_required_component(
1810                            table,
1811                            sparse_sets,
1812                            change_tick,
1813                            table_row,
1814                            entity,
1815                            component_id,
1816                            C::STORAGE_TYPE,
1817                            ptr,
1818                            #[cfg(feature = "track_change_detection")]
1819                            caller,
1820                        );
1821                    }
1822                });
1823            },
1824        ));
1825        // SAFETY:
1826        // `component_id` matches the type initialized by the `erased` constructor above.
1827        // `erased` initializes a component for `component_id` in such a way that
1828        // matches the storage type of the component. It only uses the given `table_row` or `Entity` to
1829        // initialize the storage corresponding to the given entity.
1830        unsafe { self.register_dynamic(component_id, erased, inheritance_depth) };
1831    }
1832
1833    /// Iterates the ids of all required components. This includes recursive required components.
1834    pub fn iter_ids(&self) -> impl Iterator<Item = ComponentId> + '_ {
1835        self.0.keys().copied()
1836    }
1837
1838    /// Removes components that are explicitly provided in a given [`Bundle`]. These components should
1839    /// be logically treated as normal components, not "required components".
1840    ///
1841    /// [`Bundle`]: crate::bundle::Bundle
1842    pub(crate) fn remove_explicit_components(&mut self, components: &[ComponentId]) {
1843        for component in components {
1844            self.0.remove(component);
1845        }
1846    }
1847
1848    // Merges `required_components` into this collection. This only inserts a required component
1849    // if it _did not already exist_.
1850    pub(crate) fn merge(&mut self, required_components: &RequiredComponents) {
1851        for (id, constructor) in &required_components.0 {
1852            self.0.entry(*id).or_insert_with(|| constructor.clone());
1853        }
1854    }
1855}