Path: blob/main/crates/bevy_ecs/src/reflect/component.rs
9395 views
//! Definitions for [`Component`] reflection.1//! This allows inserting, updating, removing and generally interacting with components2//! whose types are only known at runtime.3//!4//! This module exports two types: [`ReflectComponentFns`] and [`ReflectComponent`].5//!6//! # Architecture7//!8//! [`ReflectComponent`] wraps a [`ReflectComponentFns`]. In fact, each method on9//! [`ReflectComponent`] wraps a call to a function pointer field in `ReflectComponentFns`.10//!11//! ## Who creates `ReflectComponent`s?12//!13//! When a user adds the `#[reflect(Component)]` attribute to their `#[derive(Reflect)]`14//! type, it tells the derive macro for `Reflect` to add the following single line to its15//! [`get_type_registration`] method (see the relevant code[^1]).16//!17//! ```18//! # use bevy_reflect::{FromType, Reflect};19//! # use bevy_ecs::prelude::{ReflectComponent, Component};20//! # #[derive(Default, Reflect, Component)]21//! # struct A;22//! # impl A {23//! # fn foo() {24//! # let mut registration = bevy_reflect::TypeRegistration::of::<A>();25//! registration.insert::<ReflectComponent>(FromType::<Self>::from_type());26//! # }27//! # }28//! ```29//!30//! This line adds a `ReflectComponent` to the registration data for the type in question.31//! The user can access the `ReflectComponent` for type `T` through the type registry,32//! as per the `trait_reflection.rs` example.33//!34//! The `FromType::<Self>::from_type()` in the previous line calls the `FromType<C>`35//! implementation of `ReflectComponent`.36//!37//! The `FromType<C>` impl creates a function per field of [`ReflectComponentFns`].38//! In those functions, we call generic methods on [`World`] and [`EntityWorldMut`].39//!40//! The result is a `ReflectComponent` completely independent of `C`, yet capable41//! of using generic ECS methods such as `entity.get::<C>()` to get `&dyn Reflect`42//! with underlying type `C`, without the `C` appearing in the type signature.43//!44//! ## A note on code generation45//!46//! A downside of this approach is that monomorphized code (ie: concrete code47//! for generics) is generated **unconditionally**, regardless of whether it ends48//! up used or not.49//!50//! Adding `N` fields on `ReflectComponentFns` will generate `N × M` additional51//! functions, where `M` is how many types derive `#[reflect(Component)]`.52//!53//! Those functions will increase the size of the final app binary.54//!55//! [^1]: `crates/bevy_reflect/bevy_reflect_derive/src/registration.rs`56//!57//! [`get_type_registration`]: bevy_reflect::GetTypeRegistration::get_type_registration5859use super::from_reflect_with_fallback;60use crate::{61change_detection::Mut,62component::{ComponentId, ComponentMutability},63entity::{Entity, EntityMapper},64prelude::Component,65relationship::RelationshipHookMode,66world::{67unsafe_world_cell::UnsafeEntityCell, EntityMut, EntityWorldMut, FilteredEntityMut,68FilteredEntityRef, World,69},70};71use alloc::boxed::Box;72use bevy_reflect::{FromReflect, FromType, PartialReflect, Reflect, TypePath, TypeRegistry};73use bevy_utils::prelude::DebugName;7475/// A struct used to operate on reflected [`Component`] trait of a type.76///77/// A [`ReflectComponent`] for type `T` can be obtained via78/// [`bevy_reflect::TypeRegistration::data`].79#[derive(Clone)]80pub struct ReflectComponent(ReflectComponentFns);8182/// The raw function pointers needed to make up a [`ReflectComponent`].83///84/// This is used when creating custom implementations of [`ReflectComponent`] with85/// [`ReflectComponent::new()`].86///87/// > **Note:**88/// > Creating custom implementations of [`ReflectComponent`] is an advanced feature that most users89/// > 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 types96/// at runtime, for example, for scripting implementations.97///98/// By creating a custom [`ReflectComponent`] and inserting it into a type's99/// [`TypeRegistration`][bevy_reflect::TypeRegistration],100/// you can modify the way that reflected components of that type will be inserted into the Bevy101/// world.102#[derive(Clone)]103pub struct ReflectComponentFns {104/// Function pointer implementing [`ReflectComponent::insert()`].105pub insert: fn(&mut EntityWorldMut, &dyn PartialReflect, &TypeRegistry),106/// Function pointer implementing [`ReflectComponent::apply()`].107pub apply: fn(EntityMut, &dyn PartialReflect),108/// Function pointer implementing [`ReflectComponent::apply_or_insert_mapped()`].109pub apply_or_insert_mapped: fn(110&mut EntityWorldMut,111&dyn PartialReflect,112&TypeRegistry,113&mut dyn EntityMapper,114RelationshipHookMode,115),116/// Function pointer implementing [`ReflectComponent::remove()`].117pub remove: fn(&mut EntityWorldMut),118/// Function pointer implementing [`ReflectComponent::take()`].119pub take: fn(&mut EntityWorldMut) -> Option<Box<dyn Reflect>>,120/// Function pointer implementing [`ReflectComponent::contains()`].121pub contains: fn(FilteredEntityRef) -> bool,122/// Function pointer implementing [`ReflectComponent::reflect()`].123pub reflect: for<'w> fn(FilteredEntityRef<'w, '_>) -> Option<&'w dyn Reflect>,124/// Function pointer implementing [`ReflectComponent::reflect_mut()`].125pub reflect_mut: for<'w> fn(FilteredEntityMut<'w, '_>) -> Option<Mut<'w, dyn Reflect>>,126/// Function pointer implementing [`ReflectComponent::map_entities()`].127pub map_entities: fn(&mut dyn Reflect, &mut dyn EntityMapper),128/// Function pointer implementing [`ReflectComponent::reflect_unchecked_mut()`].129///130/// # Safety131/// The function may only be called with an [`UnsafeEntityCell`] that can be used to mutably access the relevant component on the given entity.132pub reflect_unchecked_mut: unsafe fn(UnsafeEntityCell<'_>) -> Option<Mut<'_, dyn Reflect>>,133/// Function pointer implementing [`ReflectComponent::copy()`].134pub copy: fn(&World, &mut World, Entity, Entity, &TypeRegistry),135/// Function pointer implementing [`ReflectComponent::register_component()`].136pub register_component: fn(&mut World) -> ComponentId,137}138139impl ReflectComponentFns {140/// Get the default set of [`ReflectComponentFns`] for a specific component type using its141/// [`FromType`] implementation.142///143/// This is useful if you want to start with the default implementation before overriding some144/// of the functions to create a custom implementation.145pub fn new<T: Component + FromReflect + TypePath>() -> Self {146<ReflectComponent as FromType<T>>::from_type().0147}148}149150impl ReflectComponent {151/// Insert a reflected [`Component`] into the entity like [`insert()`](EntityWorldMut::insert).152pub fn insert(153&self,154entity: &mut EntityWorldMut,155component: &dyn PartialReflect,156registry: &TypeRegistry,157) {158(self.0.insert)(entity, component, registry);159}160161/// Uses reflection to set the value of this [`Component`] type in the entity to the given value.162///163/// # Panics164///165/// Panics if there is no [`Component`] of the given type.166///167/// Will also panic if [`Component`] is immutable.168pub fn apply<'a>(&self, entity: impl Into<EntityMut<'a>>, component: &dyn PartialReflect) {169(self.0.apply)(entity.into(), component);170}171172/// 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.173///174/// # Panics175///176/// Panics if [`Component`] is immutable.177pub fn apply_or_insert_mapped(178&self,179entity: &mut EntityWorldMut,180component: &dyn PartialReflect,181registry: &TypeRegistry,182map: &mut dyn EntityMapper,183relationship_hook_mode: RelationshipHookMode,184) {185(self.0.apply_or_insert_mapped)(entity, component, registry, map, relationship_hook_mode);186}187188/// Removes this [`Component`] type from the entity. Does nothing if it doesn't exist.189pub fn remove(&self, entity: &mut EntityWorldMut) {190(self.0.remove)(entity);191}192193/// Removes this [`Component`] from the entity and returns its previous value.194pub fn take(&self, entity: &mut EntityWorldMut) -> Option<Box<dyn Reflect>> {195(self.0.take)(entity)196}197198/// Returns whether entity contains this [`Component`]199pub fn contains<'w, 's>(&self, entity: impl Into<FilteredEntityRef<'w, 's>>) -> bool {200(self.0.contains)(entity.into())201}202203/// Gets the value of this [`Component`] type from the entity as a reflected reference.204pub fn reflect<'w, 's>(205&self,206entity: impl Into<FilteredEntityRef<'w, 's>>,207) -> Option<&'w dyn Reflect> {208(self.0.reflect)(entity.into())209}210211/// Gets the value of this [`Component`] type from the entity as a mutable reflected reference.212///213/// # Panics214///215/// Panics if [`Component`] is immutable.216pub fn reflect_mut<'w, 's>(217&self,218entity: impl Into<FilteredEntityMut<'w, 's>>,219) -> Option<Mut<'w, dyn Reflect>> {220(self.0.reflect_mut)(entity.into())221}222223/// # Safety224/// This method does not prevent you from having two mutable pointers to the same data,225/// violating Rust's aliasing rules. To avoid this:226/// * Only call this method with a [`UnsafeEntityCell`] that may be used to mutably access the component on the entity `entity`227/// * Don't call this method more than once in the same scope for a given [`Component`].228///229/// # Panics230///231/// Panics if [`Component`] is immutable.232pub unsafe fn reflect_unchecked_mut<'a>(233&self,234entity: UnsafeEntityCell<'a>,235) -> Option<Mut<'a, dyn Reflect>> {236// SAFETY: safety requirements deferred to caller237unsafe { (self.0.reflect_unchecked_mut)(entity) }238}239240/// 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`.241///242/// # Panics243///244/// Panics if there is no [`Component`] of the given type or either entity does not exist.245pub fn copy(246&self,247source_world: &World,248destination_world: &mut World,249source_entity: Entity,250destination_entity: Entity,251registry: &TypeRegistry,252) {253(self.0.copy)(254source_world,255destination_world,256source_entity,257destination_entity,258registry,259);260}261262/// Register the type of this [`Component`] in [`World`], returning its [`ComponentId`].263pub fn register_component(&self, world: &mut World) -> ComponentId {264(self.0.register_component)(world)265}266267/// Create a custom implementation of [`ReflectComponent`].268///269/// This is an advanced feature,270/// useful for scripting implementations,271/// that should not be used by most users272/// unless you know what you are doing.273///274/// Usually you should derive [`Reflect`] and add the `#[reflect(Component)]` component275/// to generate a [`ReflectComponent`] implementation automatically.276///277/// See [`ReflectComponentFns`] for more information.278pub fn new(fns: ReflectComponentFns) -> Self {279Self(fns)280}281282/// The underlying function pointers implementing methods on `ReflectComponent`.283///284/// This is useful when you want to keep track locally of an individual285/// function pointer.286///287/// Calling [`TypeRegistry::get`] followed by288/// [`TypeRegistration::data::<ReflectComponent>`] can be costly if done several289/// times per frame. Consider cloning [`ReflectComponent`] and keeping it290/// between frames, cloning a `ReflectComponent` is very cheap.291///292/// If you only need a subset of the methods on `ReflectComponent`,293/// use `fn_pointers` to get the underlying [`ReflectComponentFns`]294/// and copy the subset of function pointers you care about.295///296/// [`TypeRegistration::data::<ReflectComponent>`]: bevy_reflect::TypeRegistration::data297/// [`TypeRegistry::get`]: bevy_reflect::TypeRegistry::get298pub fn fn_pointers(&self) -> &ReflectComponentFns {299&self.0300}301302/// Calls a dynamic version of [`Component::map_entities`].303pub fn map_entities(&self, component: &mut dyn Reflect, func: &mut dyn EntityMapper) {304(self.0.map_entities)(component, func);305}306}307308impl<C: Component + Reflect + TypePath> FromType<C> for ReflectComponent {309fn from_type() -> Self {310// TODO: Currently we panic if a component is immutable and you use311// reflection to mutate it. Perhaps the mutation methods should be fallible?312ReflectComponent(ReflectComponentFns {313insert: |entity, reflected_component, registry| {314let component = entity.world_scope(|world| {315from_reflect_with_fallback::<C>(reflected_component, world, registry)316});317entity.insert(component);318},319apply: |mut entity, reflected_component| {320if !C::Mutability::MUTABLE {321let name = DebugName::type_name::<C>();322let name = name.shortname();323panic!("Cannot call `ReflectComponent::apply` on component {name}. It is immutable, and cannot modified through reflection");324}325326// SAFETY: guard ensures `C` is a mutable component327let mut component = unsafe { entity.get_mut_assume_mutable::<C>() }.unwrap();328component.apply(reflected_component);329},330apply_or_insert_mapped: |entity,331reflected_component,332registry,333mut mapper,334relationship_hook_mode| {335if C::Mutability::MUTABLE {336// SAFETY: guard ensures `C` is a mutable component337if let Some(mut component) = unsafe { entity.get_mut_assume_mutable::<C>() } {338component.apply(reflected_component.as_partial_reflect());339C::map_entities(&mut component, &mut mapper);340} else {341let mut component = entity.world_scope(|world| {342from_reflect_with_fallback::<C>(reflected_component, world, registry)343});344C::map_entities(&mut component, &mut mapper);345entity346.insert_with_relationship_hook_mode(component, relationship_hook_mode);347}348} else {349let mut component = entity.world_scope(|world| {350from_reflect_with_fallback::<C>(reflected_component, world, registry)351});352C::map_entities(&mut component, &mut mapper);353entity.insert_with_relationship_hook_mode(component, relationship_hook_mode);354}355},356remove: |entity| {357entity.remove::<C>();358},359take: |entity| {360entity361.take::<C>()362.map(|component| Box::new(component).into_reflect())363},364contains: |entity| entity.contains::<C>(),365copy: |source_world, destination_world, source_entity, destination_entity, registry| {366let source_component = source_world.get::<C>(source_entity).unwrap();367let destination_component =368from_reflect_with_fallback::<C>(source_component, destination_world, registry);369destination_world370.entity_mut(destination_entity)371.insert(destination_component);372},373reflect: |entity| entity.get::<C>().map(|c| c as &dyn Reflect),374reflect_mut: |entity| {375if !C::Mutability::MUTABLE {376let name = DebugName::type_name::<C>();377let name = name.shortname();378panic!("Cannot call `ReflectComponent::reflect_mut` on component {name}. It is immutable, and cannot modified through reflection");379}380381// SAFETY: guard ensures `C` is a mutable component382unsafe {383entity384.into_mut_assume_mutable::<C>()385.map(|c| c.map_unchanged(|value| value as &mut dyn Reflect))386}387},388reflect_unchecked_mut: |entity| {389if !C::Mutability::MUTABLE {390let name = DebugName::type_name::<C>();391let name = name.shortname();392panic!("Cannot call `ReflectComponent::reflect_unchecked_mut` on component {name}. It is immutable, and cannot modified through reflection");393}394395// SAFETY: reflect_unchecked_mut is an unsafe function pointer used by396// `reflect_unchecked_mut` which must be called with an UnsafeEntityCell with access to the component `C` on the `entity`397// guard ensures `C` is a mutable component398let c = unsafe { entity.get_mut_assume_mutable::<C>() };399c.map(|c| c.map_unchanged(|value| value as &mut dyn Reflect))400},401register_component: |world: &mut World| -> ComponentId {402world.register_component::<C>()403},404map_entities: |reflect: &mut dyn Reflect, mut mapper: &mut dyn EntityMapper| {405let component = reflect.downcast_mut::<C>().unwrap();406Component::map_entities(component, &mut mapper);407},408})409}410}411412413