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, ComponentId},
64 entity::Entity,
65 world::{
66 unsafe_world_cell::UnsafeEntityCell, EntityMut, EntityWorldMut, FilteredEntityMut,
67 FilteredEntityRef, World,
68 },
69};
70use bevy_reflect::{FromReflect, FromType, PartialReflect, Reflect, TypePath, 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 PartialReflect, &TypeRegistry),
103 /// Function pointer implementing [`ReflectComponent::apply()`].
104 pub apply: fn(EntityMut, &dyn PartialReflect),
105 /// Function pointer implementing [`ReflectComponent::apply_or_insert()`].
106 pub apply_or_insert: fn(&mut EntityWorldMut, &dyn PartialReflect, &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 /// Function pointer implementing [`ReflectComponent::register_component()`].
123 pub register_component: fn(&mut World) -> ComponentId,
124}
125
126impl ReflectComponentFns {
127 /// Get the default set of [`ReflectComponentFns`] for a specific component type using its
128 /// [`FromType`] implementation.
129 ///
130 /// This is useful if you want to start with the default implementation before overriding some
131 /// of the functions to create a custom implementation.
132 pub fn new<T: Component + FromReflect + TypePath>() -> Self {
133 <ReflectComponent as FromType<T>>::from_type().0
134 }
135}
136
137impl ReflectComponent {
138 /// Insert a reflected [`Component`] into the entity like [`insert()`](EntityWorldMut::insert).
139 pub fn insert(
140 &self,
141 entity: &mut EntityWorldMut,
142 component: &dyn PartialReflect,
143 registry: &TypeRegistry,
144 ) {
145 (self.0.insert)(entity, component, registry);
146 }
147
148 /// Uses reflection to set the value of this [`Component`] type in the entity to the given value.
149 ///
150 /// # Panics
151 ///
152 /// Panics if there is no [`Component`] of the given type.
153 pub fn apply<'a>(&self, entity: impl Into<EntityMut<'a>>, component: &dyn PartialReflect) {
154 (self.0.apply)(entity.into(), component);
155 }
156
157 /// 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.
158 pub fn apply_or_insert(
159 &self,
160 entity: &mut EntityWorldMut,
161 component: &dyn PartialReflect,
162 registry: &TypeRegistry,
163 ) {
164 (self.0.apply_or_insert)(entity, component, registry);
165 }
166
167 /// Removes this [`Component`] type from the entity. Does nothing if it doesn't exist.
168 pub fn remove(&self, entity: &mut EntityWorldMut) {
169 (self.0.remove)(entity);
170 }
171
172 /// Returns whether entity contains this [`Component`]
173 pub fn contains<'a>(&self, entity: impl Into<FilteredEntityRef<'a>>) -> bool {
174 (self.0.contains)(entity.into())
175 }
176
177 /// Gets the value of this [`Component`] type from the entity as a reflected reference.
178 pub fn reflect<'a>(&self, entity: impl Into<FilteredEntityRef<'a>>) -> Option<&'a dyn Reflect> {
179 (self.0.reflect)(entity.into())
180 }
181
182 /// Gets the value of this [`Component`] type from the entity as a mutable reflected reference.
183 pub fn reflect_mut<'a>(
184 &self,
185 entity: impl Into<FilteredEntityMut<'a>>,
186 ) -> Option<Mut<'a, dyn Reflect>> {
187 (self.0.reflect_mut)(entity.into())
188 }
189
190 /// # Safety
191 /// This method does not prevent you from having two mutable pointers to the same data,
192 /// violating Rust's aliasing rules. To avoid this:
193 /// * Only call this method with a [`UnsafeEntityCell`] that may be used to mutably access the component on the entity `entity`
194 /// * Don't call this method more than once in the same scope for a given [`Component`].
195 pub unsafe fn reflect_unchecked_mut<'a>(
196 &self,
197 entity: UnsafeEntityCell<'a>,
198 ) -> Option<Mut<'a, dyn Reflect>> {
199 // SAFETY: safety requirements deferred to caller
200 unsafe { (self.0.reflect_unchecked_mut)(entity) }
201 }
202
203 /// 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`.
204 ///
205 /// # Panics
206 ///
207 /// Panics if there is no [`Component`] of the given type or either entity does not exist.
208 pub fn copy(
209 &self,
210 source_world: &World,
211 destination_world: &mut World,
212 source_entity: Entity,
213 destination_entity: Entity,
214 registry: &TypeRegistry,
215 ) {
216 (self.0.copy)(
217 source_world,
218 destination_world,
219 source_entity,
220 destination_entity,
221 registry,
222 );
223 }
224
225 /// Register the type of this [`Component`] in [`World`], returning its [`ComponentId`].
226 pub fn register_component(&self, world: &mut World) -> ComponentId {
227 (self.0.register_component)(world)
228 }
229
230 /// Create a custom implementation of [`ReflectComponent`].
231 ///
232 /// This is an advanced feature,
233 /// useful for scripting implementations,
234 /// that should not be used by most users
235 /// unless you know what you are doing.
236 ///
237 /// Usually you should derive [`Reflect`] and add the `#[reflect(Component)]` component
238 /// to generate a [`ReflectComponent`] implementation automatically.
239 ///
240 /// See [`ReflectComponentFns`] for more information.
241 pub fn new(fns: ReflectComponentFns) -> Self {
242 Self(fns)
243 }
244
245 /// The underlying function pointers implementing methods on `ReflectComponent`.
246 ///
247 /// This is useful when you want to keep track locally of an individual
248 /// function pointer.
249 ///
250 /// Calling [`TypeRegistry::get`] followed by
251 /// [`TypeRegistration::data::<ReflectComponent>`] can be costly if done several
252 /// times per frame. Consider cloning [`ReflectComponent`] and keeping it
253 /// between frames, cloning a `ReflectComponent` is very cheap.
254 ///
255 /// If you only need a subset of the methods on `ReflectComponent`,
256 /// use `fn_pointers` to get the underlying [`ReflectComponentFns`]
257 /// and copy the subset of function pointers you care about.
258 ///
259 /// [`TypeRegistration::data::<ReflectComponent>`]: bevy_reflect::TypeRegistration::data
260 /// [`TypeRegistry::get`]: bevy_reflect::TypeRegistry::get
261 pub fn fn_pointers(&self) -> &ReflectComponentFns {
262 &self.0
263 }
264}
265
266impl<C: Component + Reflect + TypePath> FromType<C> for ReflectComponent {
267 fn from_type() -> Self {
268 ReflectComponent(ReflectComponentFns {
269 insert: |entity, reflected_component, registry| {
270 let component = entity.world_scope(|world| {
271 from_reflect_with_fallback::<C>(reflected_component, world, registry)
272 });
273 entity.insert(component);
274 },
275 apply: |mut entity, reflected_component| {
276 let mut component = entity.get_mut::<C>().unwrap();
277 component.apply(reflected_component);
278 },
279 apply_or_insert: |entity, reflected_component, registry| {
280 if let Some(mut component) = entity.get_mut::<C>() {
281 component.apply(reflected_component.as_partial_reflect());
282 } else {
283 let component = entity.world_scope(|world| {
284 from_reflect_with_fallback::<C>(reflected_component, world, registry)
285 });
286 entity.insert(component);
287 }
288 },
289 remove: |entity| {
290 entity.remove::<C>();
291 },
292 contains: |entity| entity.contains::<C>(),
293 copy: |source_world, destination_world, source_entity, destination_entity, registry| {
294 let source_component = source_world.get::<C>(source_entity).unwrap();
295 let destination_component =
296 from_reflect_with_fallback::<C>(source_component, destination_world, registry);
297 destination_world
298 .entity_mut(destination_entity)
299 .insert(destination_component);
300 },
301 reflect: |entity| entity.get::<C>().map(|c| c as &dyn Reflect),
302 reflect_mut: |entity| {
303 entity
304 .into_mut::<C>()
305 .map(|c| c.map_unchanged(|value| value as &mut dyn Reflect))
306 },
307 reflect_unchecked_mut: |entity| {
308 // SAFETY: reflect_unchecked_mut is an unsafe function pointer used by
309 // `reflect_unchecked_mut` which must be called with an UnsafeEntityCell with access to the component `C` on the `entity`
310 let c = unsafe { entity.get_mut::<C>() };
311 c.map(|c| c.map_unchanged(|value| value as &mut dyn Reflect))
312 },
313 register_component: |world: &mut World| -> ComponentId {
314 world.register_component::<C>()
315 },
316 })
317 }
318}