bevy_ecs/component/
mod.rs

1//! Types for declaring and storing [`Component`]s.
2
3mod clone;
4mod info;
5mod register;
6mod required;
7
8pub use clone::*;
9pub use info::*;
10pub use register::*;
11pub use required::*;
12
13use crate::{
14    entity::EntityMapper,
15    lifecycle::ComponentHook,
16    relationship::ComponentRelationshipAccessor,
17    system::{Local, SystemParam},
18    world::{FromWorld, World},
19};
20pub use bevy_ecs_macros::Component;
21use core::{fmt::Debug, marker::PhantomData, ops::Deref};
22
23/// A data type that can be used to store data for an [entity].
24///
25/// `Component` is a [derivable trait]: this means that a data type can implement it by applying a `#[derive(Component)]` attribute to it.
26/// However, components must always satisfy the `Send + Sync + 'static` trait bounds.
27///
28/// [entity]: crate::entity
29/// [derivable trait]: https://doc.rust-lang.org/book/appendix-03-derivable-traits.html
30///
31/// # Examples
32///
33/// 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.
34/// The following examples show how components are laid out in code.
35///
36/// ```
37/// # use bevy_ecs::component::Component;
38/// # struct Color;
39/// #
40/// // A component can contain data...
41/// #[derive(Component)]
42/// struct LicensePlate(String);
43///
44/// // ... but it can also be a zero-sized marker.
45/// #[derive(Component)]
46/// struct Car;
47///
48/// // Components can also be structs with named fields...
49/// #[derive(Component)]
50/// struct VehiclePerformance {
51///     acceleration: f32,
52///     top_speed: f32,
53///     handling: f32,
54/// }
55///
56/// // ... or enums.
57/// #[derive(Component)]
58/// enum WheelCount {
59///     Two,
60///     Three,
61///     Four,
62/// }
63/// ```
64///
65/// # Component and data access
66///
67/// Components can be marked as immutable by adding the `#[component(immutable)]`
68/// attribute when using the derive macro.
69/// See the documentation for [`ComponentMutability`] for more details around this
70/// feature.
71///
72/// See the [`entity`] module level documentation to learn how to add or remove components from an entity.
73///
74/// See the documentation for [`Query`] to learn how to access component data from a system.
75///
76/// [`entity`]: crate::entity#usage
77/// [`Query`]: crate::system::Query
78/// [`ComponentMutability`]: crate::component::ComponentMutability
79///
80/// # Choosing a storage type
81///
82/// Components can be stored in the world using different strategies with their own performance implications.
83/// By default, components are added to the [`Table`] storage, which is optimized for query iteration.
84///
85/// Alternatively, components can be added to the [`SparseSet`] storage, which is optimized for component insertion and removal.
86/// This is achieved by adding an additional `#[component(storage = "SparseSet")]` attribute to the derive one:
87///
88/// ```
89/// # use bevy_ecs::component::Component;
90/// #
91/// #[derive(Component)]
92/// #[component(storage = "SparseSet")]
93/// struct ComponentA;
94/// ```
95///
96/// [`Table`]: crate::storage::Table
97/// [`SparseSet`]: crate::storage::SparseSet
98///
99/// # Required Components
100///
101/// Components can specify Required Components. If some [`Component`] `A` requires [`Component`] `B`,  then when `A` is inserted,
102/// `B` will _also_ be initialized and inserted (if it was not manually specified).
103///
104/// The [`Default`] constructor will be used to initialize the component, by default:
105///
106/// ```
107/// # use bevy_ecs::prelude::*;
108/// #[derive(Component)]
109/// #[require(B)]
110/// struct A;
111///
112/// #[derive(Component, Default, PartialEq, Eq, Debug)]
113/// struct B(usize);
114///
115/// # let mut world = World::default();
116/// // This will implicitly also insert B with the Default constructor
117/// let id = world.spawn(A).id();
118/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
119///
120/// // This will _not_ implicitly insert B, because it was already provided
121/// world.spawn((A, B(11)));
122/// ```
123///
124/// Components can have more than one required component:
125///
126/// ```
127/// # use bevy_ecs::prelude::*;
128/// #[derive(Component)]
129/// #[require(B, C)]
130/// struct A;
131///
132/// #[derive(Component, Default, PartialEq, Eq, Debug)]
133/// #[require(C)]
134/// struct B(usize);
135///
136/// #[derive(Component, Default, PartialEq, Eq, Debug)]
137/// struct C(u32);
138///
139/// # let mut world = World::default();
140/// // This will implicitly also insert B and C with their Default constructors
141/// let id = world.spawn(A).id();
142/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
143/// assert_eq!(&C(0), world.entity(id).get::<C>().unwrap());
144/// ```
145///
146/// You can define inline component values that take the following forms:
147/// ```
148/// # use bevy_ecs::prelude::*;
149/// #[derive(Component)]
150/// #[require(
151///     B(1), // tuple structs
152///     C { // named-field structs
153///         x: 1,
154///         ..Default::default()
155///     },
156///     D::One, // enum variants
157///     E::ONE, // associated consts
158///     F::new(1) // constructors
159/// )]
160/// struct A;
161///
162/// #[derive(Component, PartialEq, Eq, Debug)]
163/// struct B(u8);
164///
165/// #[derive(Component, PartialEq, Eq, Debug, Default)]
166/// struct C {
167///     x: u8,
168///     y: u8,
169/// }
170///
171/// #[derive(Component, PartialEq, Eq, Debug)]
172/// enum D {
173///    Zero,
174///    One,
175/// }
176///
177/// #[derive(Component, PartialEq, Eq, Debug)]
178/// struct E(u8);
179///
180/// impl E {
181///     pub const ONE: Self = Self(1);
182/// }
183///
184/// #[derive(Component, PartialEq, Eq, Debug)]
185/// struct F(u8);
186///
187/// impl F {
188///     fn new(value: u8) -> Self {
189///         Self(value)
190///     }
191/// }
192///
193/// # let mut world = World::default();
194/// let id = world.spawn(A).id();
195/// assert_eq!(&B(1), world.entity(id).get::<B>().unwrap());
196/// assert_eq!(&C { x: 1, y: 0 }, world.entity(id).get::<C>().unwrap());
197/// assert_eq!(&D::One, world.entity(id).get::<D>().unwrap());
198/// assert_eq!(&E(1), world.entity(id).get::<E>().unwrap());
199/// assert_eq!(&F(1), world.entity(id).get::<F>().unwrap());
200/// ````
201///
202///
203/// You can also define arbitrary expressions by using `=`
204///
205/// ```
206/// # use bevy_ecs::prelude::*;
207/// #[derive(Component)]
208/// #[require(C = init_c())]
209/// struct A;
210///
211/// #[derive(Component, PartialEq, Eq, Debug)]
212/// #[require(C = C(20))]
213/// struct B;
214///
215/// #[derive(Component, PartialEq, Eq, Debug)]
216/// struct C(usize);
217///
218/// fn init_c() -> C {
219///     C(10)
220/// }
221///
222/// # let mut world = World::default();
223/// // This will implicitly also insert C with the init_c() constructor
224/// let id = world.spawn(A).id();
225/// assert_eq!(&C(10), world.entity(id).get::<C>().unwrap());
226///
227/// // This will implicitly also insert C with the `|| C(20)` constructor closure
228/// let id = world.spawn(B).id();
229/// assert_eq!(&C(20), world.entity(id).get::<C>().unwrap());
230/// ```
231///
232/// Required components are _recursive_. This means, if a Required Component has required components,
233/// those components will _also_ be inserted if they are missing:
234///
235/// ```
236/// # use bevy_ecs::prelude::*;
237/// #[derive(Component)]
238/// #[require(B)]
239/// struct A;
240///
241/// #[derive(Component, Default, PartialEq, Eq, Debug)]
242/// #[require(C)]
243/// struct B(usize);
244///
245/// #[derive(Component, Default, PartialEq, Eq, Debug)]
246/// struct C(u32);
247///
248/// # let mut world = World::default();
249/// // This will implicitly also insert B and C with their Default constructors
250/// let id = world.spawn(A).id();
251/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
252/// assert_eq!(&C(0), world.entity(id).get::<C>().unwrap());
253/// ```
254///
255/// Note that cycles in the "component require tree" will result in stack overflows when attempting to
256/// insert a component.
257///
258/// This "multiple inheritance" pattern does mean that it is possible to have duplicate requires for a given type
259/// at different levels of the inheritance tree:
260///
261/// ```
262/// # use bevy_ecs::prelude::*;
263/// #[derive(Component)]
264/// struct X(usize);
265///
266/// #[derive(Component, Default)]
267/// #[require(X(1))]
268/// struct Y;
269///
270/// #[derive(Component)]
271/// #[require(
272///     Y,
273///     X(2),
274/// )]
275/// struct Z;
276///
277/// # let mut world = World::default();
278/// // In this case, the x2 constructor is used for X
279/// let id = world.spawn(Z).id();
280/// assert_eq!(2, world.entity(id).get::<X>().unwrap().0);
281/// ```
282///
283/// In general, this shouldn't happen often, but when it does the algorithm for choosing the constructor from the tree is simple and predictable:
284/// 1. A constructor from a direct `#[require()]`, if one exists, is selected with priority.
285/// 2. Otherwise, perform a Depth First Search on the tree of requirements and select the first one found.
286///
287/// From a user perspective, just think about this as the following:
288/// 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.
289/// 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.
290///
291/// ## Registering required components at runtime
292///
293/// In most cases, required components should be registered using the `require` attribute as shown above.
294/// However, in some cases, it may be useful to register required components at runtime.
295///
296/// This can be done through [`World::register_required_components`] or  [`World::register_required_components_with`]
297/// for the [`Default`] and custom constructors respectively:
298///
299/// ```
300/// # use bevy_ecs::prelude::*;
301/// #[derive(Component)]
302/// struct A;
303///
304/// #[derive(Component, Default, PartialEq, Eq, Debug)]
305/// struct B(usize);
306///
307/// #[derive(Component, PartialEq, Eq, Debug)]
308/// struct C(u32);
309///
310/// # let mut world = World::default();
311/// // Register B as required by A and C as required by B.
312/// world.register_required_components::<A, B>();
313/// world.register_required_components_with::<B, C>(|| C(2));
314///
315/// // This will implicitly also insert B with its Default constructor
316/// // and C with the custom constructor defined by B.
317/// let id = world.spawn(A).id();
318/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
319/// assert_eq!(&C(2), world.entity(id).get::<C>().unwrap());
320/// ```
321///
322/// Similar rules as before apply to duplicate requires fer a given type at different levels
323/// of the inheritance tree. `A` requiring `C` directly would take precedence over indirectly
324/// requiring it through `A` requiring `B` and `B` requiring `C`.
325///
326/// Unlike with the `require` attribute, directly requiring the same component multiple times
327/// for the same component will result in a panic. This is done to prevent conflicting constructors
328/// and confusing ordering dependencies.
329///
330/// Note that requirements must currently be registered before the requiring component is inserted
331/// into the world for the first time. Registering requirements after this will lead to a panic.
332///
333/// # Relationships between Entities
334///
335/// Sometimes it is useful to define relationships between entities.  A common example is the
336/// parent / child relationship. Since Components are how data is stored for Entities, one might
337/// naturally think to create a Component which has a field of type [`Entity`].
338///
339/// To facilitate this pattern, Bevy provides the [`Relationship`](`crate::relationship::Relationship`)
340/// trait. You can derive the [`Relationship`](`crate::relationship::Relationship`) and
341/// [`RelationshipTarget`](`crate::relationship::RelationshipTarget`) traits in addition to the
342/// Component trait in order to implement data driven relationships between entities, see the trait
343/// docs for more details.
344///
345/// In addition, Bevy provides canonical implementations of the parent / child relationship via the
346/// [`ChildOf`](crate::hierarchy::ChildOf) [`Relationship`](crate::relationship::Relationship) and
347/// the [`Children`](crate::hierarchy::Children)
348/// [`RelationshipTarget`](crate::relationship::RelationshipTarget).
349///
350/// # Adding component's hooks
351///
352/// See [`ComponentHooks`] for a detailed explanation of component's hooks.
353///
354/// Alternatively to the example shown in [`ComponentHooks`]' documentation, hooks can be configured using following attributes:
355/// - `#[component(on_add = on_add_function)]`
356/// - `#[component(on_insert = on_insert_function)]`
357/// - `#[component(on_replace = on_replace_function)]`
358/// - `#[component(on_remove = on_remove_function)]`
359///
360/// ```
361/// # use bevy_ecs::component::Component;
362/// # use bevy_ecs::lifecycle::HookContext;
363/// # use bevy_ecs::world::DeferredWorld;
364/// # use bevy_ecs::entity::Entity;
365/// # use bevy_ecs::component::ComponentId;
366/// # use core::panic::Location;
367/// #
368/// #[derive(Component)]
369/// #[component(on_add = my_on_add_hook)]
370/// #[component(on_insert = my_on_insert_hook)]
371/// // Another possible way of configuring hooks:
372/// // #[component(on_add = my_on_add_hook, on_insert = my_on_insert_hook)]
373/// //
374/// // We don't have a replace or remove hook, so we can leave them out:
375/// // #[component(on_replace = my_on_replace_hook, on_remove = my_on_remove_hook)]
376/// struct ComponentA;
377///
378/// fn my_on_add_hook(world: DeferredWorld, context: HookContext) {
379///     // ...
380/// }
381///
382/// // You can also destructure items directly in the signature
383/// fn my_on_insert_hook(world: DeferredWorld, HookContext { caller, .. }: HookContext) {
384///     // ...
385/// }
386/// ```
387///
388/// This also supports function calls that yield closures
389///
390/// ```
391/// # use bevy_ecs::component::Component;
392/// # use bevy_ecs::lifecycle::HookContext;
393/// # use bevy_ecs::world::DeferredWorld;
394/// #
395/// #[derive(Component)]
396/// #[component(on_add = my_msg_hook("hello"))]
397/// #[component(on_despawn = my_msg_hook("yoink"))]
398/// struct ComponentA;
399///
400/// // a hook closure generating function
401/// fn my_msg_hook(message: &'static str) -> impl Fn(DeferredWorld, HookContext) {
402///     move |_world, _ctx| {
403///         println!("{message}");
404///     }
405/// }
406///
407/// ```
408///
409/// A hook's function path can be elided if it is `Self::on_add`, `Self::on_insert` etc.
410/// ```
411/// # use bevy_ecs::lifecycle::HookContext;
412/// # use bevy_ecs::prelude::*;
413/// # use bevy_ecs::world::DeferredWorld;
414/// #
415/// #[derive(Component, Debug)]
416/// #[component(on_add)]
417/// struct DoubleOnSpawn(usize);
418///
419/// impl DoubleOnSpawn {
420///     fn on_add(mut world: DeferredWorld, context: HookContext) {
421///         let mut entity = world.get_mut::<Self>(context.entity).unwrap();
422///         entity.0 *= 2;
423///     }
424/// }
425/// #
426/// # let mut world = World::new();
427/// # let entity = world.spawn(DoubleOnSpawn(2));
428/// # assert_eq!(entity.get::<DoubleOnSpawn>().unwrap().0, 4);
429/// ```
430///
431/// # Setting the clone behavior
432///
433/// You can specify how the [`Component`] is cloned when deriving it.
434///
435/// Your options are the functions and variants of [`ComponentCloneBehavior`]
436/// See [Clone Behaviors section of `EntityCloner`](crate::entity::EntityCloner#clone-behaviors) to understand how this affects handler priority.
437/// ```
438/// # use bevy_ecs::prelude::*;
439///
440/// #[derive(Component)]
441/// #[component(clone_behavior = Ignore)]
442/// struct MyComponent;
443///
444/// ```
445///
446/// # Implementing the trait for foreign types
447///
448/// 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.
449/// This means that it is not possible to directly have a type defined in a third party library as a component.
450/// This important limitation can be easily worked around using the [newtype pattern]:
451/// this makes it possible to locally define and implement `Component` for a tuple struct that wraps the foreign type.
452/// The following example gives a demonstration of this pattern.
453///
454/// ```
455/// // `Component` is defined in the `bevy_ecs` crate.
456/// use bevy_ecs::component::Component;
457///
458/// // `Duration` is defined in the `std` crate.
459/// use std::time::Duration;
460///
461/// // It is not possible to implement `Component` for `Duration` from this position, as they are
462/// // both foreign items, defined in an external crate. However, nothing prevents to define a new
463/// // `Cooldown` type that wraps `Duration`. As `Cooldown` is defined in a local crate, it is
464/// // possible to implement `Component` for it.
465/// #[derive(Component)]
466/// struct Cooldown(Duration);
467/// ```
468///
469/// [orphan rule]: https://doc.rust-lang.org/book/ch10-02-traits.html#implementing-a-trait-on-a-type
470/// [newtype pattern]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#using-the-newtype-pattern-to-implement-external-traits-on-external-types
471///
472/// # `!Sync` Components
473/// A `!Sync` type cannot implement `Component`. However, it is possible to wrap a `Send` but not `Sync`
474/// type in [`SyncCell`] or the currently unstable [`Exclusive`] to make it `Sync`. This forces only
475/// having mutable access (`&mut T` only, never `&T`), but makes it safe to reference across multiple
476/// threads.
477///
478/// This will fail to compile since `RefCell` is `!Sync`.
479/// ```compile_fail
480/// # use std::cell::RefCell;
481/// # use bevy_ecs::component::Component;
482/// #[derive(Component)]
483/// struct NotSync {
484///    counter: RefCell<usize>,
485/// }
486/// ```
487///
488/// This will compile since the `RefCell` is wrapped with `SyncCell`.
489/// ```
490/// # use std::cell::RefCell;
491/// # use bevy_ecs::component::Component;
492/// use bevy_platform::cell::SyncCell;
493///
494/// // This will compile.
495/// #[derive(Component)]
496/// struct ActuallySync {
497///    counter: SyncCell<RefCell<usize>>,
498/// }
499/// ```
500///
501/// [`SyncCell`]: bevy_platform::cell::SyncCell
502/// [`Exclusive`]: https://doc.rust-lang.org/nightly/std/sync/struct.Exclusive.html
503/// [`ComponentHooks`]: crate::lifecycle::ComponentHooks
504#[diagnostic::on_unimplemented(
505    message = "`{Self}` is not a `Component`",
506    label = "invalid `Component`",
507    note = "consider annotating `{Self}` with `#[derive(Component)]`"
508)]
509pub trait Component: Send + Sync + 'static {
510    /// A constant indicating the storage type used for this component.
511    const STORAGE_TYPE: StorageType;
512
513    /// A marker type to assist Bevy with determining if this component is
514    /// mutable, or immutable. Mutable components will have [`Component<Mutability = Mutable>`],
515    /// while immutable components will instead have [`Component<Mutability = Immutable>`].
516    ///
517    /// * For a component to be mutable, this type must be [`Mutable`].
518    /// * For a component to be immutable, this type must be [`Immutable`].
519    type Mutability: ComponentMutability;
520
521    /// Gets the `on_add` [`ComponentHook`] for this [`Component`] if one is defined.
522    fn on_add() -> Option<ComponentHook> {
523        None
524    }
525
526    /// Gets the `on_insert` [`ComponentHook`] for this [`Component`] if one is defined.
527    fn on_insert() -> Option<ComponentHook> {
528        None
529    }
530
531    /// Gets the `on_replace` [`ComponentHook`] for this [`Component`] if one is defined.
532    fn on_replace() -> Option<ComponentHook> {
533        None
534    }
535
536    /// Gets the `on_remove` [`ComponentHook`] for this [`Component`] if one is defined.
537    fn on_remove() -> Option<ComponentHook> {
538        None
539    }
540
541    /// Gets the `on_despawn` [`ComponentHook`] for this [`Component`] if one is defined.
542    fn on_despawn() -> Option<ComponentHook> {
543        None
544    }
545
546    /// Registers required components.
547    ///
548    /// # Safety
549    ///
550    /// - `_required_components` must only contain components valid in `_components`.
551    fn register_required_components(
552        _component_id: ComponentId,
553        _required_components: &mut RequiredComponentsRegistrator,
554    ) {
555    }
556
557    /// Called when registering this component, allowing to override clone function (or disable cloning altogether) for this component.
558    ///
559    /// See [Clone Behaviors section of `EntityCloner`](crate::entity::EntityCloner#clone-behaviors) to understand how this affects handler priority.
560    #[inline]
561    fn clone_behavior() -> ComponentCloneBehavior {
562        ComponentCloneBehavior::Default
563    }
564
565    /// Maps the entities on this component using the given [`EntityMapper`]. This is used to remap entities in contexts like scenes and entity cloning.
566    /// When deriving [`Component`], this is populated by annotating fields containing entities with `#[entities]`
567    ///
568    /// ```
569    /// # use bevy_ecs::{component::Component, entity::Entity};
570    /// #[derive(Component)]
571    /// struct Inventory {
572    ///     #[entities]
573    ///     items: Vec<Entity>
574    /// }
575    /// ```
576    ///
577    /// Fields with `#[entities]` must implement [`MapEntities`](crate::entity::MapEntities).
578    ///
579    /// Bevy provides various implementations of [`MapEntities`](crate::entity::MapEntities), so that arbitrary combinations like these are supported with `#[entities]`:
580    ///
581    /// ```rust
582    /// # use bevy_ecs::{component::Component, entity::Entity};
583    /// #[derive(Component)]
584    /// struct Inventory {
585    ///     #[entities]
586    ///     items: Vec<Option<Entity>>
587    /// }
588    /// ```
589    ///
590    /// You might need more specialized logic. A likely cause of this is your component contains collections of entities that
591    /// don't implement [`MapEntities`](crate::entity::MapEntities). In that case, you can annotate your component with
592    /// `#[component(map_entities)]`. Using this attribute, you must implement `MapEntities` for the
593    /// component itself, and this method will simply call that implementation.
594    ///
595    /// ```
596    /// # use bevy_ecs::{component::Component, entity::{Entity, MapEntities, EntityMapper}};
597    /// # use std::collections::HashMap;
598    /// #[derive(Component)]
599    /// #[component(map_entities)]
600    /// struct Inventory {
601    ///     items: HashMap<Entity, usize>
602    /// }
603    ///
604    /// impl MapEntities for Inventory {
605    ///   fn map_entities<M: EntityMapper>(&mut self, entity_mapper: &mut M) {
606    ///      self.items = self.items
607    ///          .drain()
608    ///          .map(|(id, count)|(entity_mapper.get_mapped(id), count))
609    ///          .collect();
610    ///   }
611    /// }
612    /// # let a = Entity::from_bits(0x1_0000_0001);
613    /// # let b = Entity::from_bits(0x1_0000_0002);
614    /// # let mut inv = Inventory { items: Default::default() };
615    /// # inv.items.insert(a, 10);
616    /// # <Inventory as Component>::map_entities(&mut inv, &mut (a,b));
617    /// # assert_eq!(inv.items.get(&b), Some(&10));
618    /// ````
619    ///
620    /// Alternatively, you can specify the path to a function with `#[component(map_entities = function_path)]`, similar to component hooks.
621    /// In this case, the inputs of the function should mirror the inputs to this method, with the second parameter being generic.
622    ///
623    /// ```
624    /// # use bevy_ecs::{component::Component, entity::{Entity, MapEntities, EntityMapper}};
625    /// # use std::collections::HashMap;
626    /// #[derive(Component)]
627    /// #[component(map_entities = map_the_map)]
628    /// // Also works: map_the_map::<M> or map_the_map::<_>
629    /// struct Inventory {
630    ///     items: HashMap<Entity, usize>
631    /// }
632    ///
633    /// fn map_the_map<M: EntityMapper>(inv: &mut Inventory, entity_mapper: &mut M) {
634    ///    inv.items = inv.items
635    ///        .drain()
636    ///        .map(|(id, count)|(entity_mapper.get_mapped(id), count))
637    ///        .collect();
638    /// }
639    /// # let a = Entity::from_bits(0x1_0000_0001);
640    /// # let b = Entity::from_bits(0x1_0000_0002);
641    /// # let mut inv = Inventory { items: Default::default() };
642    /// # inv.items.insert(a, 10);
643    /// # <Inventory as Component>::map_entities(&mut inv, &mut (a,b));
644    /// # assert_eq!(inv.items.get(&b), Some(&10));
645    /// ````
646    ///
647    /// You can use the turbofish (`::<A,B,C>`) to specify parameters when a function is generic, using either M or _ for the type of the mapper parameter.
648    #[inline]
649    fn map_entities<E: EntityMapper>(_this: &mut Self, _mapper: &mut E) {}
650
651    /// Returns [`ComponentRelationshipAccessor`] required for working with relationships in dynamic contexts.
652    ///
653    /// If component is not a [`Relationship`](crate::relationship::Relationship) or [`RelationshipTarget`](crate::relationship::RelationshipTarget), this should return `None`.
654    fn relationship_accessor() -> Option<ComponentRelationshipAccessor<Self>> {
655        None
656    }
657}
658
659mod private {
660    pub trait Seal {}
661}
662
663/// The mutability option for a [`Component`]. This can either be:
664/// * [`Mutable`]
665/// * [`Immutable`]
666///
667/// This is controlled through either [`Component::Mutability`] or `#[component(immutable)]`
668/// when using the derive macro.
669///
670/// Immutable components are guaranteed to never have an exclusive reference,
671/// `&mut ...`, created while inserted onto an entity.
672/// In all other ways, they are identical to mutable components.
673/// This restriction allows hooks to observe all changes made to an immutable
674/// component, effectively turning the `Insert` and `Replace` hooks into a
675/// `OnMutate` hook.
676/// This is not practical for mutable components, as the runtime cost of invoking
677/// a hook for every exclusive reference created would be far too high.
678///
679/// # Examples
680///
681/// ```rust
682/// # use bevy_ecs::component::Component;
683/// #
684/// #[derive(Component)]
685/// #[component(immutable)]
686/// struct ImmutableFoo;
687/// ```
688pub trait ComponentMutability: private::Seal + 'static {
689    /// Boolean to indicate if this mutability setting implies a mutable or immutable
690    /// component.
691    const MUTABLE: bool;
692}
693
694/// Parameter indicating a [`Component`] is immutable.
695///
696/// See [`ComponentMutability`] for details.
697pub struct Immutable;
698
699impl private::Seal for Immutable {}
700
701impl ComponentMutability for Immutable {
702    const MUTABLE: bool = false;
703}
704
705/// Parameter indicating a [`Component`] is mutable.
706///
707/// See [`ComponentMutability`] for details.
708pub struct Mutable;
709
710impl private::Seal for Mutable {}
711
712impl ComponentMutability for Mutable {
713    const MUTABLE: bool = true;
714}
715
716/// The storage used for a specific component type.
717///
718/// # Examples
719/// The [`StorageType`] for a component is configured via the derive attribute
720///
721/// ```
722/// # use bevy_ecs::{prelude::*, component::*};
723/// #[derive(Component)]
724/// #[component(storage = "SparseSet")]
725/// struct A;
726/// ```
727#[derive(Debug, Copy, Clone, Default, Eq, PartialEq)]
728pub enum StorageType {
729    /// Provides fast and cache-friendly iteration, but slower addition and removal of components.
730    /// This is the default storage type.
731    #[default]
732    Table,
733    /// Provides fast addition and removal of components, but slower iteration.
734    SparseSet,
735}
736
737/// A [`SystemParam`] that provides access to the [`ComponentId`] for a specific component type.
738///
739/// # Example
740/// ```
741/// # use bevy_ecs::{system::Local, component::{Component, ComponentId, ComponentIdFor}};
742/// #[derive(Component)]
743/// struct Player;
744/// fn my_system(component_id: ComponentIdFor<Player>) {
745///     let component_id: ComponentId = component_id.get();
746///     // ...
747/// }
748/// ```
749#[derive(SystemParam)]
750pub struct ComponentIdFor<'s, T: Component>(Local<'s, InitComponentId<T>>);
751
752impl<T: Component> ComponentIdFor<'_, T> {
753    /// Gets the [`ComponentId`] for the type `T`.
754    #[inline]
755    pub fn get(&self) -> ComponentId {
756        **self
757    }
758}
759
760impl<T: Component> Deref for ComponentIdFor<'_, T> {
761    type Target = ComponentId;
762    fn deref(&self) -> &Self::Target {
763        &self.0.component_id
764    }
765}
766
767impl<T: Component> From<ComponentIdFor<'_, T>> for ComponentId {
768    #[inline]
769    fn from(to_component_id: ComponentIdFor<T>) -> ComponentId {
770        *to_component_id
771    }
772}
773
774/// Initializes the [`ComponentId`] for a specific type when used with [`FromWorld`].
775struct InitComponentId<T: Component> {
776    component_id: ComponentId,
777    marker: PhantomData<T>,
778}
779
780impl<T: Component> FromWorld for InitComponentId<T> {
781    fn from_world(world: &mut World) -> Self {
782        Self {
783            component_id: world.register_component::<T>(),
784            marker: PhantomData,
785        }
786    }
787}