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