Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_ecs/src/reflect/component.rs
9395 views
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
60
use super::from_reflect_with_fallback;
61
use crate::{
62
change_detection::Mut,
63
component::{ComponentId, ComponentMutability},
64
entity::{Entity, EntityMapper},
65
prelude::Component,
66
relationship::RelationshipHookMode,
67
world::{
68
unsafe_world_cell::UnsafeEntityCell, EntityMut, EntityWorldMut, FilteredEntityMut,
69
FilteredEntityRef, World,
70
},
71
};
72
use alloc::boxed::Box;
73
use bevy_reflect::{FromReflect, FromType, PartialReflect, Reflect, TypePath, TypeRegistry};
74
use bevy_utils::prelude::DebugName;
75
76
/// A struct used to operate on reflected [`Component`] trait of a type.
77
///
78
/// A [`ReflectComponent`] for type `T` can be obtained via
79
/// [`bevy_reflect::TypeRegistration::data`].
80
#[derive(Clone)]
81
pub struct ReflectComponent(ReflectComponentFns);
82
83
/// The raw function pointers needed to make up a [`ReflectComponent`].
84
///
85
/// This is used when creating custom implementations of [`ReflectComponent`] with
86
/// [`ReflectComponent::new()`].
87
///
88
/// > **Note:**
89
/// > Creating custom implementations of [`ReflectComponent`] is an advanced feature that most users
90
/// > will not need.
91
/// > Usually a [`ReflectComponent`] is created for a type by deriving [`Reflect`]
92
/// > and adding the `#[reflect(Component)]` attribute.
93
/// > After adding the component to the [`TypeRegistry`],
94
/// > its [`ReflectComponent`] can then be retrieved when needed.
95
///
96
/// Creating a custom [`ReflectComponent`] may be useful if you need to create new component types
97
/// at runtime, for example, for scripting implementations.
98
///
99
/// By creating a custom [`ReflectComponent`] and inserting it into a type's
100
/// [`TypeRegistration`][bevy_reflect::TypeRegistration],
101
/// you can modify the way that reflected components of that type will be inserted into the Bevy
102
/// world.
103
#[derive(Clone)]
104
pub struct ReflectComponentFns {
105
/// Function pointer implementing [`ReflectComponent::insert()`].
106
pub insert: fn(&mut EntityWorldMut, &dyn PartialReflect, &TypeRegistry),
107
/// Function pointer implementing [`ReflectComponent::apply()`].
108
pub apply: fn(EntityMut, &dyn PartialReflect),
109
/// Function pointer implementing [`ReflectComponent::apply_or_insert_mapped()`].
110
pub apply_or_insert_mapped: fn(
111
&mut EntityWorldMut,
112
&dyn PartialReflect,
113
&TypeRegistry,
114
&mut dyn EntityMapper,
115
RelationshipHookMode,
116
),
117
/// Function pointer implementing [`ReflectComponent::remove()`].
118
pub remove: fn(&mut EntityWorldMut),
119
/// Function pointer implementing [`ReflectComponent::take()`].
120
pub take: fn(&mut EntityWorldMut) -> Option<Box<dyn Reflect>>,
121
/// Function pointer implementing [`ReflectComponent::contains()`].
122
pub contains: fn(FilteredEntityRef) -> bool,
123
/// Function pointer implementing [`ReflectComponent::reflect()`].
124
pub reflect: for<'w> fn(FilteredEntityRef<'w, '_>) -> Option<&'w dyn Reflect>,
125
/// Function pointer implementing [`ReflectComponent::reflect_mut()`].
126
pub reflect_mut: for<'w> fn(FilteredEntityMut<'w, '_>) -> Option<Mut<'w, dyn Reflect>>,
127
/// Function pointer implementing [`ReflectComponent::map_entities()`].
128
pub map_entities: fn(&mut dyn Reflect, &mut dyn EntityMapper),
129
/// Function pointer implementing [`ReflectComponent::reflect_unchecked_mut()`].
130
///
131
/// # Safety
132
/// The function may only be called with an [`UnsafeEntityCell`] that can be used to mutably access the relevant component on the given entity.
133
pub reflect_unchecked_mut: unsafe fn(UnsafeEntityCell<'_>) -> Option<Mut<'_, dyn Reflect>>,
134
/// Function pointer implementing [`ReflectComponent::copy()`].
135
pub copy: fn(&World, &mut World, Entity, Entity, &TypeRegistry),
136
/// Function pointer implementing [`ReflectComponent::register_component()`].
137
pub register_component: fn(&mut World) -> ComponentId,
138
}
139
140
impl ReflectComponentFns {
141
/// Get the default set of [`ReflectComponentFns`] for a specific component type using its
142
/// [`FromType`] implementation.
143
///
144
/// This is useful if you want to start with the default implementation before overriding some
145
/// of the functions to create a custom implementation.
146
pub fn new<T: Component + FromReflect + TypePath>() -> Self {
147
<ReflectComponent as FromType<T>>::from_type().0
148
}
149
}
150
151
impl ReflectComponent {
152
/// Insert a reflected [`Component`] into the entity like [`insert()`](EntityWorldMut::insert).
153
pub fn insert(
154
&self,
155
entity: &mut EntityWorldMut,
156
component: &dyn PartialReflect,
157
registry: &TypeRegistry,
158
) {
159
(self.0.insert)(entity, component, registry);
160
}
161
162
/// Uses reflection to set the value of this [`Component`] type in the entity to the given value.
163
///
164
/// # Panics
165
///
166
/// Panics if there is no [`Component`] of the given type.
167
///
168
/// Will also panic if [`Component`] is immutable.
169
pub fn apply<'a>(&self, entity: impl Into<EntityMut<'a>>, component: &dyn PartialReflect) {
170
(self.0.apply)(entity.into(), component);
171
}
172
173
/// 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.
174
///
175
/// # Panics
176
///
177
/// Panics if [`Component`] is immutable.
178
pub fn apply_or_insert_mapped(
179
&self,
180
entity: &mut EntityWorldMut,
181
component: &dyn PartialReflect,
182
registry: &TypeRegistry,
183
map: &mut dyn EntityMapper,
184
relationship_hook_mode: RelationshipHookMode,
185
) {
186
(self.0.apply_or_insert_mapped)(entity, component, registry, map, relationship_hook_mode);
187
}
188
189
/// Removes this [`Component`] type from the entity. Does nothing if it doesn't exist.
190
pub fn remove(&self, entity: &mut EntityWorldMut) {
191
(self.0.remove)(entity);
192
}
193
194
/// Removes this [`Component`] from the entity and returns its previous value.
195
pub fn take(&self, entity: &mut EntityWorldMut) -> Option<Box<dyn Reflect>> {
196
(self.0.take)(entity)
197
}
198
199
/// Returns whether entity contains this [`Component`]
200
pub fn contains<'w, 's>(&self, entity: impl Into<FilteredEntityRef<'w, 's>>) -> bool {
201
(self.0.contains)(entity.into())
202
}
203
204
/// Gets the value of this [`Component`] type from the entity as a reflected reference.
205
pub fn reflect<'w, 's>(
206
&self,
207
entity: impl Into<FilteredEntityRef<'w, 's>>,
208
) -> Option<&'w dyn Reflect> {
209
(self.0.reflect)(entity.into())
210
}
211
212
/// Gets the value of this [`Component`] type from the entity as a mutable reflected reference.
213
///
214
/// # Panics
215
///
216
/// Panics if [`Component`] is immutable.
217
pub fn reflect_mut<'w, 's>(
218
&self,
219
entity: impl Into<FilteredEntityMut<'w, 's>>,
220
) -> Option<Mut<'w, dyn Reflect>> {
221
(self.0.reflect_mut)(entity.into())
222
}
223
224
/// # Safety
225
/// This method does not prevent you from having two mutable pointers to the same data,
226
/// violating Rust's aliasing rules. To avoid this:
227
/// * Only call this method with a [`UnsafeEntityCell`] that may be used to mutably access the component on the entity `entity`
228
/// * Don't call this method more than once in the same scope for a given [`Component`].
229
///
230
/// # Panics
231
///
232
/// Panics if [`Component`] is immutable.
233
pub unsafe fn reflect_unchecked_mut<'a>(
234
&self,
235
entity: UnsafeEntityCell<'a>,
236
) -> Option<Mut<'a, dyn Reflect>> {
237
// SAFETY: safety requirements deferred to caller
238
unsafe { (self.0.reflect_unchecked_mut)(entity) }
239
}
240
241
/// 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`.
242
///
243
/// # Panics
244
///
245
/// Panics if there is no [`Component`] of the given type or either entity does not exist.
246
pub fn copy(
247
&self,
248
source_world: &World,
249
destination_world: &mut World,
250
source_entity: Entity,
251
destination_entity: Entity,
252
registry: &TypeRegistry,
253
) {
254
(self.0.copy)(
255
source_world,
256
destination_world,
257
source_entity,
258
destination_entity,
259
registry,
260
);
261
}
262
263
/// Register the type of this [`Component`] in [`World`], returning its [`ComponentId`].
264
pub fn register_component(&self, world: &mut World) -> ComponentId {
265
(self.0.register_component)(world)
266
}
267
268
/// Create a custom implementation of [`ReflectComponent`].
269
///
270
/// This is an advanced feature,
271
/// useful for scripting implementations,
272
/// that should not be used by most users
273
/// unless you know what you are doing.
274
///
275
/// Usually you should derive [`Reflect`] and add the `#[reflect(Component)]` component
276
/// to generate a [`ReflectComponent`] implementation automatically.
277
///
278
/// See [`ReflectComponentFns`] for more information.
279
pub fn new(fns: ReflectComponentFns) -> Self {
280
Self(fns)
281
}
282
283
/// The underlying function pointers implementing methods on `ReflectComponent`.
284
///
285
/// This is useful when you want to keep track locally of an individual
286
/// function pointer.
287
///
288
/// Calling [`TypeRegistry::get`] followed by
289
/// [`TypeRegistration::data::<ReflectComponent>`] can be costly if done several
290
/// times per frame. Consider cloning [`ReflectComponent`] and keeping it
291
/// between frames, cloning a `ReflectComponent` is very cheap.
292
///
293
/// If you only need a subset of the methods on `ReflectComponent`,
294
/// use `fn_pointers` to get the underlying [`ReflectComponentFns`]
295
/// and copy the subset of function pointers you care about.
296
///
297
/// [`TypeRegistration::data::<ReflectComponent>`]: bevy_reflect::TypeRegistration::data
298
/// [`TypeRegistry::get`]: bevy_reflect::TypeRegistry::get
299
pub fn fn_pointers(&self) -> &ReflectComponentFns {
300
&self.0
301
}
302
303
/// Calls a dynamic version of [`Component::map_entities`].
304
pub fn map_entities(&self, component: &mut dyn Reflect, func: &mut dyn EntityMapper) {
305
(self.0.map_entities)(component, func);
306
}
307
}
308
309
impl<C: Component + Reflect + TypePath> FromType<C> for ReflectComponent {
310
fn from_type() -> Self {
311
// TODO: Currently we panic if a component is immutable and you use
312
// reflection to mutate it. Perhaps the mutation methods should be fallible?
313
ReflectComponent(ReflectComponentFns {
314
insert: |entity, reflected_component, registry| {
315
let component = entity.world_scope(|world| {
316
from_reflect_with_fallback::<C>(reflected_component, world, registry)
317
});
318
entity.insert(component);
319
},
320
apply: |mut entity, reflected_component| {
321
if !C::Mutability::MUTABLE {
322
let name = DebugName::type_name::<C>();
323
let name = name.shortname();
324
panic!("Cannot call `ReflectComponent::apply` on component {name}. It is immutable, and cannot modified through reflection");
325
}
326
327
// SAFETY: guard ensures `C` is a mutable component
328
let mut component = unsafe { entity.get_mut_assume_mutable::<C>() }.unwrap();
329
component.apply(reflected_component);
330
},
331
apply_or_insert_mapped: |entity,
332
reflected_component,
333
registry,
334
mut mapper,
335
relationship_hook_mode| {
336
if C::Mutability::MUTABLE {
337
// SAFETY: guard ensures `C` is a mutable component
338
if let Some(mut component) = unsafe { entity.get_mut_assume_mutable::<C>() } {
339
component.apply(reflected_component.as_partial_reflect());
340
C::map_entities(&mut component, &mut mapper);
341
} else {
342
let mut component = entity.world_scope(|world| {
343
from_reflect_with_fallback::<C>(reflected_component, world, registry)
344
});
345
C::map_entities(&mut component, &mut mapper);
346
entity
347
.insert_with_relationship_hook_mode(component, relationship_hook_mode);
348
}
349
} else {
350
let mut component = entity.world_scope(|world| {
351
from_reflect_with_fallback::<C>(reflected_component, world, registry)
352
});
353
C::map_entities(&mut component, &mut mapper);
354
entity.insert_with_relationship_hook_mode(component, relationship_hook_mode);
355
}
356
},
357
remove: |entity| {
358
entity.remove::<C>();
359
},
360
take: |entity| {
361
entity
362
.take::<C>()
363
.map(|component| Box::new(component).into_reflect())
364
},
365
contains: |entity| entity.contains::<C>(),
366
copy: |source_world, destination_world, source_entity, destination_entity, registry| {
367
let source_component = source_world.get::<C>(source_entity).unwrap();
368
let destination_component =
369
from_reflect_with_fallback::<C>(source_component, destination_world, registry);
370
destination_world
371
.entity_mut(destination_entity)
372
.insert(destination_component);
373
},
374
reflect: |entity| entity.get::<C>().map(|c| c as &dyn Reflect),
375
reflect_mut: |entity| {
376
if !C::Mutability::MUTABLE {
377
let name = DebugName::type_name::<C>();
378
let name = name.shortname();
379
panic!("Cannot call `ReflectComponent::reflect_mut` on component {name}. It is immutable, and cannot modified through reflection");
380
}
381
382
// SAFETY: guard ensures `C` is a mutable component
383
unsafe {
384
entity
385
.into_mut_assume_mutable::<C>()
386
.map(|c| c.map_unchanged(|value| value as &mut dyn Reflect))
387
}
388
},
389
reflect_unchecked_mut: |entity| {
390
if !C::Mutability::MUTABLE {
391
let name = DebugName::type_name::<C>();
392
let name = name.shortname();
393
panic!("Cannot call `ReflectComponent::reflect_unchecked_mut` on component {name}. It is immutable, and cannot modified through reflection");
394
}
395
396
// SAFETY: reflect_unchecked_mut is an unsafe function pointer used by
397
// `reflect_unchecked_mut` which must be called with an UnsafeEntityCell with access to the component `C` on the `entity`
398
// guard ensures `C` is a mutable component
399
let c = unsafe { entity.get_mut_assume_mutable::<C>() };
400
c.map(|c| c.map_unchanged(|value| value as &mut dyn Reflect))
401
},
402
register_component: |world: &mut World| -> ComponentId {
403
world.register_component::<C>()
404
},
405
map_entities: |reflect: &mut dyn Reflect, mut mapper: &mut dyn EntityMapper| {
406
let component = reflect.downcast_mut::<C>().unwrap();
407
Component::map_entities(component, &mut mapper);
408
},
409
})
410
}
411
}
412
413