bevy_ecs/reflect/
component.rs

1//! Definitions for [`Component`] reflection.
2//! This allows inserting, updating, removing and generally interacting with components
3//! whose types are only known at runtime.
4//!
5//! This module exports two types: [`ReflectComponentFns`] and [`ReflectComponent`].
6//!
7//! # Architecture
8//!
9//! [`ReflectComponent`] wraps a [`ReflectComponentFns`]. In fact, each method on
10//! [`ReflectComponent`] wraps a call to a function pointer field in `ReflectComponentFns`.
11//!
12//! ## Who creates `ReflectComponent`s?
13//!
14//! When a user adds the `#[reflect(Component)]` attribute to their `#[derive(Reflect)]`
15//! type, it tells the derive macro for `Reflect` to add the following single line to its
16//! [`get_type_registration`] method (see the relevant code[^1]).
17//!
18//! ```
19//! # use bevy_reflect::{FromType, Reflect};
20//! # use bevy_ecs::prelude::{ReflectComponent, Component};
21//! # #[derive(Default, Reflect, Component)]
22//! # struct A;
23//! # impl A {
24//! #   fn foo() {
25//! # let mut registration = bevy_reflect::TypeRegistration::of::<A>();
26//! registration.insert::<ReflectComponent>(FromType::<Self>::from_type());
27//! #   }
28//! # }
29//! ```
30//!
31//! This line adds a `ReflectComponent` to the registration data for the type in question.
32//! The user can access the `ReflectComponent` for type `T` through the type registry,
33//! as per the `trait_reflection.rs` example.
34//!
35//! The `FromType::<Self>::from_type()` in the previous line calls the `FromType<C>`
36//! implementation of `ReflectComponent`.
37//!
38//! The `FromType<C>` impl creates a function per field of [`ReflectComponentFns`].
39//! In those functions, we call generic methods on [`World`] and [`EntityWorldMut`].
40//!
41//! The result is a `ReflectComponent` completely independent of `C`, yet capable
42//! of using generic ECS methods such as `entity.get::<C>()` to get `&dyn Reflect`
43//! with underlying type `C`, without the `C` appearing in the type signature.
44//!
45//! ## A note on code generation
46//!
47//! A downside of this approach is that monomorphized code (ie: concrete code
48//! for generics) is generated **unconditionally**, regardless of whether it ends
49//! up used or not.
50//!
51//! Adding `N` fields on `ReflectComponentFns` will generate `N × M` additional
52//! functions, where `M` is how many types derive `#[reflect(Component)]`.
53//!
54//! Those functions will increase the size of the final app binary.
55//!
56//! [^1]: `crates/bevy_reflect/bevy_reflect_derive/src/registration.rs`
57//!
58//! [`get_type_registration`]: bevy_reflect::GetTypeRegistration::get_type_registration
59
60use super::from_reflect_with_fallback;
61use crate::{
62    change_detection::Mut,
63    component::Component,
64    entity::Entity,
65    world::{
66        unsafe_world_cell::UnsafeEntityCell, EntityMut, EntityWorldMut, FilteredEntityMut,
67        FilteredEntityRef, World,
68    },
69};
70use bevy_reflect::{FromReflect, FromType, Reflect, TypeRegistry};
71
72/// A struct used to operate on reflected [`Component`] trait of a type.
73///
74/// A [`ReflectComponent`] for type `T` can be obtained via
75/// [`bevy_reflect::TypeRegistration::data`].
76#[derive(Clone)]
77pub struct ReflectComponent(ReflectComponentFns);
78
79/// The raw function pointers needed to make up a [`ReflectComponent`].
80///
81/// This is used when creating custom implementations of [`ReflectComponent`] with
82/// [`ReflectComponent::new()`].
83///
84/// > **Note:**
85/// > Creating custom implementations of [`ReflectComponent`] is an advanced feature that most users
86/// > will not need.
87/// > Usually a [`ReflectComponent`] is created for a type by deriving [`Reflect`]
88/// > and adding the `#[reflect(Component)]` attribute.
89/// > After adding the component to the [`TypeRegistry`],
90/// > its [`ReflectComponent`] can then be retrieved when needed.
91///
92/// Creating a custom [`ReflectComponent`] may be useful if you need to create new component types
93/// at runtime, for example, for scripting implementations.
94///
95/// By creating a custom [`ReflectComponent`] and inserting it into a type's
96/// [`TypeRegistration`][bevy_reflect::TypeRegistration],
97/// you can modify the way that reflected components of that type will be inserted into the Bevy
98/// world.
99#[derive(Clone)]
100pub struct ReflectComponentFns {
101    /// Function pointer implementing [`ReflectComponent::insert()`].
102    pub insert: fn(&mut EntityWorldMut, &dyn Reflect, &TypeRegistry),
103    /// Function pointer implementing [`ReflectComponent::apply()`].
104    pub apply: fn(EntityMut, &dyn Reflect),
105    /// Function pointer implementing [`ReflectComponent::apply_or_insert()`].
106    pub apply_or_insert: fn(&mut EntityWorldMut, &dyn Reflect, &TypeRegistry),
107    /// Function pointer implementing [`ReflectComponent::remove()`].
108    pub remove: fn(&mut EntityWorldMut),
109    /// Function pointer implementing [`ReflectComponent::contains()`].
110    pub contains: fn(FilteredEntityRef) -> bool,
111    /// Function pointer implementing [`ReflectComponent::reflect()`].
112    pub reflect: fn(FilteredEntityRef) -> Option<&dyn Reflect>,
113    /// Function pointer implementing [`ReflectComponent::reflect_mut()`].
114    pub reflect_mut: fn(FilteredEntityMut) -> Option<Mut<dyn Reflect>>,
115    /// Function pointer implementing [`ReflectComponent::reflect_unchecked_mut()`].
116    ///
117    /// # Safety
118    /// The function may only be called with an [`UnsafeEntityCell`] that can be used to mutably access the relevant component on the given entity.
119    pub reflect_unchecked_mut: unsafe fn(UnsafeEntityCell<'_>) -> Option<Mut<'_, dyn Reflect>>,
120    /// Function pointer implementing [`ReflectComponent::copy()`].
121    pub copy: fn(&World, &mut World, Entity, Entity, &TypeRegistry),
122}
123
124impl ReflectComponentFns {
125    /// Get the default set of [`ReflectComponentFns`] for a specific component type using its
126    /// [`FromType`] implementation.
127    ///
128    /// This is useful if you want to start with the default implementation before overriding some
129    /// of the functions to create a custom implementation.
130    pub fn new<T: Component + Reflect + FromReflect>() -> Self {
131        <ReflectComponent as FromType<T>>::from_type().0
132    }
133}
134
135impl ReflectComponent {
136    /// Insert a reflected [`Component`] into the entity like [`insert()`](EntityWorldMut::insert).
137    pub fn insert(
138        &self,
139        entity: &mut EntityWorldMut,
140        component: &dyn Reflect,
141        registry: &TypeRegistry,
142    ) {
143        (self.0.insert)(entity, component, registry);
144    }
145
146    /// Uses reflection to set the value of this [`Component`] type in the entity to the given value.
147    ///
148    /// # Panics
149    ///
150    /// Panics if there is no [`Component`] of the given type.
151    pub fn apply<'a>(&self, entity: impl Into<EntityMut<'a>>, component: &dyn Reflect) {
152        (self.0.apply)(entity.into(), component);
153    }
154
155    /// Uses reflection to set the value of this [`Component`] type in the entity to the given value or insert a new one if it does not exist.
156    pub fn apply_or_insert(
157        &self,
158        entity: &mut EntityWorldMut,
159        component: &dyn Reflect,
160        registry: &TypeRegistry,
161    ) {
162        (self.0.apply_or_insert)(entity, component, registry);
163    }
164
165    /// Removes this [`Component`] type from the entity. Does nothing if it doesn't exist.
166    pub fn remove(&self, entity: &mut EntityWorldMut) {
167        (self.0.remove)(entity);
168    }
169
170    /// Returns whether entity contains this [`Component`]
171    pub fn contains<'a>(&self, entity: impl Into<FilteredEntityRef<'a>>) -> bool {
172        (self.0.contains)(entity.into())
173    }
174
175    /// Gets the value of this [`Component`] type from the entity as a reflected reference.
176    pub fn reflect<'a>(&self, entity: impl Into<FilteredEntityRef<'a>>) -> Option<&'a dyn Reflect> {
177        (self.0.reflect)(entity.into())
178    }
179
180    /// Gets the value of this [`Component`] type from the entity as a mutable reflected reference.
181    pub fn reflect_mut<'a>(
182        &self,
183        entity: impl Into<FilteredEntityMut<'a>>,
184    ) -> Option<Mut<'a, dyn Reflect>> {
185        (self.0.reflect_mut)(entity.into())
186    }
187
188    /// # Safety
189    /// This method does not prevent you from having two mutable pointers to the same data,
190    /// violating Rust's aliasing rules. To avoid this:
191    /// * Only call this method with a [`UnsafeEntityCell`] that may be used to mutably access the component on the entity `entity`
192    /// * Don't call this method more than once in the same scope for a given [`Component`].
193    pub unsafe fn reflect_unchecked_mut<'a>(
194        &self,
195        entity: UnsafeEntityCell<'a>,
196    ) -> Option<Mut<'a, dyn Reflect>> {
197        // SAFETY: safety requirements deferred to caller
198        unsafe { (self.0.reflect_unchecked_mut)(entity) }
199    }
200
201    /// Gets the value of this [`Component`] type from entity from `source_world` and [applies](Self::apply()) it to the value of this [`Component`] type in entity in `destination_world`.
202    ///
203    /// # Panics
204    ///
205    /// Panics if there is no [`Component`] of the given type or either entity does not exist.
206    pub fn copy(
207        &self,
208        source_world: &World,
209        destination_world: &mut World,
210        source_entity: Entity,
211        destination_entity: Entity,
212        registry: &TypeRegistry,
213    ) {
214        (self.0.copy)(
215            source_world,
216            destination_world,
217            source_entity,
218            destination_entity,
219            registry,
220        );
221    }
222
223    /// Create a custom implementation of [`ReflectComponent`].
224    ///
225    /// This is an advanced feature,
226    /// useful for scripting implementations,
227    /// that should not be used by most users
228    /// unless you know what you are doing.
229    ///
230    /// Usually you should derive [`Reflect`] and add the `#[reflect(Component)]` component
231    /// to generate a [`ReflectComponent`] implementation automatically.
232    ///
233    /// See [`ReflectComponentFns`] for more information.
234    pub fn new(fns: ReflectComponentFns) -> Self {
235        Self(fns)
236    }
237
238    /// The underlying function pointers implementing methods on `ReflectComponent`.
239    ///
240    /// This is useful when you want to keep track locally of an individual
241    /// function pointer.
242    ///
243    /// Calling [`TypeRegistry::get`] followed by
244    /// [`TypeRegistration::data::<ReflectComponent>`] can be costly if done several
245    /// times per frame. Consider cloning [`ReflectComponent`] and keeping it
246    /// between frames, cloning a `ReflectComponent` is very cheap.
247    ///
248    /// If you only need a subset of the methods on `ReflectComponent`,
249    /// use `fn_pointers` to get the underlying [`ReflectComponentFns`]
250    /// and copy the subset of function pointers you care about.
251    ///
252    /// [`TypeRegistration::data::<ReflectComponent>`]: bevy_reflect::TypeRegistration::data
253    /// [`TypeRegistry::get`]: bevy_reflect::TypeRegistry::get
254    pub fn fn_pointers(&self) -> &ReflectComponentFns {
255        &self.0
256    }
257}
258
259impl<C: Component + Reflect> FromType<C> for ReflectComponent {
260    fn from_type() -> Self {
261        ReflectComponent(ReflectComponentFns {
262            insert: |entity, reflected_component, registry| {
263                let component = entity.world_scope(|world| {
264                    from_reflect_with_fallback::<C>(reflected_component, world, registry)
265                });
266                entity.insert(component);
267            },
268            apply: |mut entity, reflected_component| {
269                let mut component = entity.get_mut::<C>().unwrap();
270                component.apply(reflected_component);
271            },
272            apply_or_insert: |entity, reflected_component, registry| {
273                if let Some(mut component) = entity.get_mut::<C>() {
274                    component.apply(reflected_component);
275                } else {
276                    let component = entity.world_scope(|world| {
277                        from_reflect_with_fallback::<C>(reflected_component, world, registry)
278                    });
279                    entity.insert(component);
280                }
281            },
282            remove: |entity| {
283                entity.remove::<C>();
284            },
285            contains: |entity| entity.contains::<C>(),
286            copy: |source_world, destination_world, source_entity, destination_entity, registry| {
287                let source_component = source_world.get::<C>(source_entity).unwrap();
288                let destination_component =
289                    from_reflect_with_fallback::<C>(source_component, destination_world, registry);
290                destination_world
291                    .entity_mut(destination_entity)
292                    .insert(destination_component);
293            },
294            reflect: |entity| entity.get::<C>().map(|c| c as &dyn Reflect),
295            reflect_mut: |entity| {
296                entity.into_mut::<C>().map(|c| Mut {
297                    value: c.value as &mut dyn Reflect,
298                    ticks: c.ticks,
299                })
300            },
301            reflect_unchecked_mut: |entity| {
302                // SAFETY: reflect_unchecked_mut is an unsafe function pointer used by
303                // `reflect_unchecked_mut` which must be called with an UnsafeEntityCell with access to the component `C` on the `entity`
304                unsafe {
305                    entity.get_mut::<C>().map(|c| Mut {
306                        value: c.value as &mut dyn Reflect,
307                        ticks: c.ticks,
308                    })
309                }
310            },
311        })
312    }
313}