Path: blob/main/crates/bevy_ecs/src/reflect/component.rs
6600 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 bevy_reflect::{FromReflect, FromType, PartialReflect, Reflect, TypePath, TypeRegistry};72use bevy_utils::prelude::DebugName;7374/// A struct used to operate on reflected [`Component`] trait of a type.75///76/// A [`ReflectComponent`] for type `T` can be obtained via77/// [`bevy_reflect::TypeRegistration::data`].78#[derive(Clone)]79pub struct ReflectComponent(ReflectComponentFns);8081/// The raw function pointers needed to make up a [`ReflectComponent`].82///83/// This is used when creating custom implementations of [`ReflectComponent`] with84/// [`ReflectComponent::new()`].85///86/// > **Note:**87/// > Creating custom implementations of [`ReflectComponent`] is an advanced feature that most users88/// > will not need.89/// > Usually a [`ReflectComponent`] is created for a type by deriving [`Reflect`]90/// > and adding the `#[reflect(Component)]` attribute.91/// > After adding the component to the [`TypeRegistry`],92/// > its [`ReflectComponent`] can then be retrieved when needed.93///94/// Creating a custom [`ReflectComponent`] may be useful if you need to create new component types95/// at runtime, for example, for scripting implementations.96///97/// By creating a custom [`ReflectComponent`] and inserting it into a type's98/// [`TypeRegistration`][bevy_reflect::TypeRegistration],99/// you can modify the way that reflected components of that type will be inserted into the Bevy100/// world.101#[derive(Clone)]102pub struct ReflectComponentFns {103/// Function pointer implementing [`ReflectComponent::insert()`].104pub insert: fn(&mut EntityWorldMut, &dyn PartialReflect, &TypeRegistry),105/// Function pointer implementing [`ReflectComponent::apply()`].106pub apply: fn(EntityMut, &dyn PartialReflect),107/// Function pointer implementing [`ReflectComponent::apply_or_insert_mapped()`].108pub apply_or_insert_mapped: fn(109&mut EntityWorldMut,110&dyn PartialReflect,111&TypeRegistry,112&mut dyn EntityMapper,113RelationshipHookMode,114),115/// Function pointer implementing [`ReflectComponent::remove()`].116pub remove: fn(&mut EntityWorldMut),117/// Function pointer implementing [`ReflectComponent::contains()`].118pub contains: fn(FilteredEntityRef) -> bool,119/// Function pointer implementing [`ReflectComponent::reflect()`].120pub reflect: for<'w> fn(FilteredEntityRef<'w, '_>) -> Option<&'w dyn Reflect>,121/// Function pointer implementing [`ReflectComponent::reflect_mut()`].122pub reflect_mut: for<'w> fn(FilteredEntityMut<'w, '_>) -> Option<Mut<'w, dyn Reflect>>,123/// Function pointer implementing [`ReflectComponent::map_entities()`].124pub map_entities: fn(&mut dyn Reflect, &mut dyn EntityMapper),125/// Function pointer implementing [`ReflectComponent::reflect_unchecked_mut()`].126///127/// # Safety128/// The function may only be called with an [`UnsafeEntityCell`] that can be used to mutably access the relevant component on the given entity.129pub reflect_unchecked_mut: unsafe fn(UnsafeEntityCell<'_>) -> Option<Mut<'_, dyn Reflect>>,130/// Function pointer implementing [`ReflectComponent::copy()`].131pub copy: fn(&World, &mut World, Entity, Entity, &TypeRegistry),132/// Function pointer implementing [`ReflectComponent::register_component()`].133pub register_component: fn(&mut World) -> ComponentId,134}135136impl ReflectComponentFns {137/// Get the default set of [`ReflectComponentFns`] for a specific component type using its138/// [`FromType`] implementation.139///140/// This is useful if you want to start with the default implementation before overriding some141/// of the functions to create a custom implementation.142pub fn new<T: Component + FromReflect + TypePath>() -> Self {143<ReflectComponent as FromType<T>>::from_type().0144}145}146147impl ReflectComponent {148/// Insert a reflected [`Component`] into the entity like [`insert()`](EntityWorldMut::insert).149pub fn insert(150&self,151entity: &mut EntityWorldMut,152component: &dyn PartialReflect,153registry: &TypeRegistry,154) {155(self.0.insert)(entity, component, registry);156}157158/// Uses reflection to set the value of this [`Component`] type in the entity to the given value.159///160/// # Panics161///162/// Panics if there is no [`Component`] of the given type.163///164/// Will also panic if [`Component`] is immutable.165pub fn apply<'a>(&self, entity: impl Into<EntityMut<'a>>, component: &dyn PartialReflect) {166(self.0.apply)(entity.into(), component);167}168169/// 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.170///171/// # Panics172///173/// Panics if [`Component`] is immutable.174pub fn apply_or_insert_mapped(175&self,176entity: &mut EntityWorldMut,177component: &dyn PartialReflect,178registry: &TypeRegistry,179map: &mut dyn EntityMapper,180relationship_hook_mode: RelationshipHookMode,181) {182(self.0.apply_or_insert_mapped)(entity, component, registry, map, relationship_hook_mode);183}184185/// Removes this [`Component`] type from the entity. Does nothing if it doesn't exist.186pub fn remove(&self, entity: &mut EntityWorldMut) {187(self.0.remove)(entity);188}189190/// Returns whether entity contains this [`Component`]191pub fn contains<'w, 's>(&self, entity: impl Into<FilteredEntityRef<'w, 's>>) -> bool {192(self.0.contains)(entity.into())193}194195/// Gets the value of this [`Component`] type from the entity as a reflected reference.196pub fn reflect<'w, 's>(197&self,198entity: impl Into<FilteredEntityRef<'w, 's>>,199) -> Option<&'w dyn Reflect> {200(self.0.reflect)(entity.into())201}202203/// Gets the value of this [`Component`] type from the entity as a mutable reflected reference.204///205/// # Panics206///207/// Panics if [`Component`] is immutable.208pub fn reflect_mut<'w, 's>(209&self,210entity: impl Into<FilteredEntityMut<'w, 's>>,211) -> Option<Mut<'w, dyn Reflect>> {212(self.0.reflect_mut)(entity.into())213}214215/// # Safety216/// This method does not prevent you from having two mutable pointers to the same data,217/// violating Rust's aliasing rules. To avoid this:218/// * Only call this method with a [`UnsafeEntityCell`] that may be used to mutably access the component on the entity `entity`219/// * Don't call this method more than once in the same scope for a given [`Component`].220///221/// # Panics222///223/// Panics if [`Component`] is immutable.224pub unsafe fn reflect_unchecked_mut<'a>(225&self,226entity: UnsafeEntityCell<'a>,227) -> Option<Mut<'a, dyn Reflect>> {228// SAFETY: safety requirements deferred to caller229unsafe { (self.0.reflect_unchecked_mut)(entity) }230}231232/// 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`.233///234/// # Panics235///236/// Panics if there is no [`Component`] of the given type or either entity does not exist.237pub fn copy(238&self,239source_world: &World,240destination_world: &mut World,241source_entity: Entity,242destination_entity: Entity,243registry: &TypeRegistry,244) {245(self.0.copy)(246source_world,247destination_world,248source_entity,249destination_entity,250registry,251);252}253254/// Register the type of this [`Component`] in [`World`], returning its [`ComponentId`].255pub fn register_component(&self, world: &mut World) -> ComponentId {256(self.0.register_component)(world)257}258259/// Create a custom implementation of [`ReflectComponent`].260///261/// This is an advanced feature,262/// useful for scripting implementations,263/// that should not be used by most users264/// unless you know what you are doing.265///266/// Usually you should derive [`Reflect`] and add the `#[reflect(Component)]` component267/// to generate a [`ReflectComponent`] implementation automatically.268///269/// See [`ReflectComponentFns`] for more information.270pub fn new(fns: ReflectComponentFns) -> Self {271Self(fns)272}273274/// The underlying function pointers implementing methods on `ReflectComponent`.275///276/// This is useful when you want to keep track locally of an individual277/// function pointer.278///279/// Calling [`TypeRegistry::get`] followed by280/// [`TypeRegistration::data::<ReflectComponent>`] can be costly if done several281/// times per frame. Consider cloning [`ReflectComponent`] and keeping it282/// between frames, cloning a `ReflectComponent` is very cheap.283///284/// If you only need a subset of the methods on `ReflectComponent`,285/// use `fn_pointers` to get the underlying [`ReflectComponentFns`]286/// and copy the subset of function pointers you care about.287///288/// [`TypeRegistration::data::<ReflectComponent>`]: bevy_reflect::TypeRegistration::data289/// [`TypeRegistry::get`]: bevy_reflect::TypeRegistry::get290pub fn fn_pointers(&self) -> &ReflectComponentFns {291&self.0292}293294/// Calls a dynamic version of [`Component::map_entities`].295pub fn map_entities(&self, component: &mut dyn Reflect, func: &mut dyn EntityMapper) {296(self.0.map_entities)(component, func);297}298}299300impl<C: Component + Reflect + TypePath> FromType<C> for ReflectComponent {301fn from_type() -> Self {302// TODO: Currently we panic if a component is immutable and you use303// reflection to mutate it. Perhaps the mutation methods should be fallible?304ReflectComponent(ReflectComponentFns {305insert: |entity, reflected_component, registry| {306let component = entity.world_scope(|world| {307from_reflect_with_fallback::<C>(reflected_component, world, registry)308});309entity.insert(component);310},311apply: |mut entity, reflected_component| {312if !C::Mutability::MUTABLE {313let name = DebugName::type_name::<C>();314let name = name.shortname();315panic!("Cannot call `ReflectComponent::apply` on component {name}. It is immutable, and cannot modified through reflection");316}317318// SAFETY: guard ensures `C` is a mutable component319let mut component = unsafe { entity.get_mut_assume_mutable::<C>() }.unwrap();320component.apply(reflected_component);321},322apply_or_insert_mapped: |entity,323reflected_component,324registry,325mut mapper,326relationship_hook_mode| {327if C::Mutability::MUTABLE {328// SAFETY: guard ensures `C` is a mutable component329if let Some(mut component) = unsafe { entity.get_mut_assume_mutable::<C>() } {330component.apply(reflected_component.as_partial_reflect());331C::map_entities(&mut component, &mut mapper);332} else {333let mut component = entity.world_scope(|world| {334from_reflect_with_fallback::<C>(reflected_component, world, registry)335});336C::map_entities(&mut component, &mut mapper);337entity338.insert_with_relationship_hook_mode(component, relationship_hook_mode);339}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);345entity.insert_with_relationship_hook_mode(component, relationship_hook_mode);346}347},348remove: |entity| {349entity.remove::<C>();350},351contains: |entity| entity.contains::<C>(),352copy: |source_world, destination_world, source_entity, destination_entity, registry| {353let source_component = source_world.get::<C>(source_entity).unwrap();354let destination_component =355from_reflect_with_fallback::<C>(source_component, destination_world, registry);356destination_world357.entity_mut(destination_entity)358.insert(destination_component);359},360reflect: |entity| entity.get::<C>().map(|c| c as &dyn Reflect),361reflect_mut: |entity| {362if !C::Mutability::MUTABLE {363let name = DebugName::type_name::<C>();364let name = name.shortname();365panic!("Cannot call `ReflectComponent::reflect_mut` on component {name}. It is immutable, and cannot modified through reflection");366}367368// SAFETY: guard ensures `C` is a mutable component369unsafe {370entity371.into_mut_assume_mutable::<C>()372.map(|c| c.map_unchanged(|value| value as &mut dyn Reflect))373}374},375reflect_unchecked_mut: |entity| {376if !C::Mutability::MUTABLE {377let name = DebugName::type_name::<C>();378let name = name.shortname();379panic!("Cannot call `ReflectComponent::reflect_unchecked_mut` on component {name}. It is immutable, and cannot modified through reflection");380}381382// SAFETY: reflect_unchecked_mut is an unsafe function pointer used by383// `reflect_unchecked_mut` which must be called with an UnsafeEntityCell with access to the component `C` on the `entity`384// guard ensures `C` is a mutable component385let c = unsafe { entity.get_mut_assume_mutable::<C>() };386c.map(|c| c.map_unchanged(|value| value as &mut dyn Reflect))387},388register_component: |world: &mut World| -> ComponentId {389world.register_component::<C>()390},391map_entities: |reflect: &mut dyn Reflect, mut mapper: &mut dyn EntityMapper| {392let component = reflect.downcast_mut::<C>().unwrap();393Component::map_entities(component, &mut mapper);394},395})396}397}398399400