Skip to main content

bevy_ecs/reflect/
bundle.rs

1//! Definitions for [`Bundle`] reflection.
2//! This allows inserting, updating and/or removing bundles whose type is only known at runtime.
3//!
4//! This module exports two types: [`ReflectBundleFns`] and [`ReflectBundle`].
5//!
6//! Same as [`component`](`super::component`), but for bundles.
7use alloc::boxed::Box;
8use bevy_utils::prelude::DebugName;
9use core::any::{Any, TypeId};
10
11use crate::{
12    bundle::BundleFromComponents,
13    entity::EntityMapper,
14    prelude::Bundle,
15    relationship::RelationshipHookMode,
16    world::{EntityMut, EntityWorldMut},
17};
18use bevy_reflect::{
19    FromReflect, FromType, PartialReflect, Reflect, ReflectRef, TypePath, TypeRegistry,
20};
21
22use super::{from_reflect_with_fallback, ReflectComponent};
23
24/// A struct used to operate on reflected [`Bundle`] trait of a type.
25///
26/// A [`ReflectBundle`] for type `T` can be obtained via
27/// [`bevy_reflect::TypeRegistration::data`].
28#[derive(Clone)]
29pub struct ReflectBundle(ReflectBundleFns);
30
31/// The raw function pointers needed to make up a [`ReflectBundle`].
32///
33/// The also [`ReflectComponentFns`](`super::component::ReflectComponentFns`).
34#[derive(Clone)]
35pub struct ReflectBundleFns {
36    /// Function pointer implementing [`ReflectBundle::insert`].
37    pub insert: fn(&mut EntityWorldMut, &dyn PartialReflect, &TypeRegistry),
38    /// Function pointer implementing [`ReflectBundle::apply`].
39    pub apply: fn(EntityMut, &dyn PartialReflect, &TypeRegistry),
40    /// Function pointer implementing [`ReflectBundle::apply_or_insert_mapped`].
41    pub apply_or_insert_mapped: fn(
42        &mut EntityWorldMut,
43        &dyn PartialReflect,
44        &TypeRegistry,
45        &mut dyn EntityMapper,
46        RelationshipHookMode,
47    ),
48    /// Function pointer implementing [`ReflectBundle::remove`].
49    pub remove: fn(&mut EntityWorldMut),
50    /// Function pointer implementing [`ReflectBundle::take`].
51    pub take: fn(&mut EntityWorldMut) -> Option<Box<dyn Reflect>>,
52}
53
54impl ReflectBundleFns {
55    /// Get the default set of [`ReflectBundleFns`] for a specific bundle type using its
56    /// [`FromType`] implementation.
57    ///
58    /// This is useful if you want to start with the default implementation before overriding some
59    /// of the functions to create a custom implementation.
60    pub fn new<T: Bundle + FromReflect + TypePath + BundleFromComponents>() -> Self {
61        <ReflectBundle as FromType<T>>::from_type().0
62    }
63}
64
65impl ReflectBundle {
66    /// Insert a reflected [`Bundle`] into the entity like [`insert()`](EntityWorldMut::insert).
67    pub fn insert(
68        &self,
69        entity: &mut EntityWorldMut,
70        bundle: &dyn PartialReflect,
71        registry: &TypeRegistry,
72    ) {
73        (self.0.insert)(entity, bundle, registry);
74    }
75
76    /// Uses reflection to set the value of this [`Bundle`] type in the entity to the given value.
77    ///
78    /// # Panics
79    ///
80    /// Panics if there is no [`Bundle`] of the given type.
81    pub fn apply<'a>(
82        &self,
83        entity: impl Into<EntityMut<'a>>,
84        bundle: &dyn PartialReflect,
85        registry: &TypeRegistry,
86    ) {
87        (self.0.apply)(entity.into(), bundle, registry);
88    }
89
90    /// Uses reflection to set the value of this [`Bundle`] type in the entity to the given value or insert a new one if it does not exist.
91    pub fn apply_or_insert_mapped(
92        &self,
93        entity: &mut EntityWorldMut,
94        bundle: &dyn PartialReflect,
95        registry: &TypeRegistry,
96        mapper: &mut dyn EntityMapper,
97        relationship_hook_mode: RelationshipHookMode,
98    ) {
99        (self.0.apply_or_insert_mapped)(entity, bundle, registry, mapper, relationship_hook_mode);
100    }
101
102    /// Removes this [`Bundle`] type from the entity. Does nothing if it doesn't exist.
103    pub fn remove(&self, entity: &mut EntityWorldMut) -> &ReflectBundle {
104        (self.0.remove)(entity);
105        self
106    }
107
108    /// Removes all components in the [`Bundle`] from the entity and returns their previous values.
109    ///
110    /// **Note:** If the entity does not have every component in the bundle, this method will not remove any of them.
111    #[must_use]
112    pub fn take(&self, entity: &mut EntityWorldMut) -> Option<Box<dyn Reflect>> {
113        (self.0.take)(entity)
114    }
115
116    /// Create a custom implementation of [`ReflectBundle`].
117    ///
118    /// This is an advanced feature,
119    /// useful for scripting implementations,
120    /// that should not be used by most users
121    /// unless you know what you are doing.
122    ///
123    /// Usually you should derive [`Reflect`] and add the `#[reflect(Bundle)]` bundle
124    /// to generate a [`ReflectBundle`] implementation automatically.
125    ///
126    /// See [`ReflectBundleFns`] for more information.
127    pub fn new(fns: ReflectBundleFns) -> Self {
128        Self(fns)
129    }
130
131    /// The underlying function pointers implementing methods on `ReflectBundle`.
132    ///
133    /// This is useful when you want to keep track locally of an individual
134    /// function pointer.
135    ///
136    /// Calling [`TypeRegistry::get`] followed by
137    /// [`TypeRegistration::data::<ReflectBundle>`] can be costly if done several
138    /// times per frame. Consider cloning [`ReflectBundle`] and keeping it
139    /// between frames, cloning a `ReflectBundle` is very cheap.
140    ///
141    /// If you only need a subset of the methods on `ReflectBundle`,
142    /// use `fn_pointers` to get the underlying [`ReflectBundleFns`]
143    /// and copy the subset of function pointers you care about.
144    ///
145    /// [`TypeRegistration::data::<ReflectBundle>`]: bevy_reflect::TypeRegistration::data
146    pub fn fn_pointers(&self) -> &ReflectBundleFns {
147        &self.0
148    }
149}
150
151impl<B: Bundle + Reflect + TypePath + BundleFromComponents> FromType<B> for ReflectBundle {
152    fn from_type() -> Self {
153        ReflectBundle(ReflectBundleFns {
154            insert: |entity, reflected_bundle, registry| {
155                let bundle = entity.world_scope(|world| {
156                    from_reflect_with_fallback::<B>(reflected_bundle, world, registry)
157                });
158                entity.insert(bundle);
159            },
160            apply: |mut entity, reflected_bundle, registry| {
161                if let Some(reflect_component) =
162                    registry.get_type_data::<ReflectComponent>(TypeId::of::<B>())
163                {
164                    reflect_component.apply(entity, reflected_bundle);
165                } else {
166                    match reflected_bundle.reflect_ref() {
167                        ReflectRef::Struct(bundle) => bundle
168                            .iter_fields()
169                            .for_each(|(_, field)| apply_field(&mut entity, field, registry)),
170                        ReflectRef::Tuple(bundle) => bundle
171                            .iter_fields()
172                            .for_each(|field| apply_field(&mut entity, field, registry)),
173                        _ => panic!(
174                            "expected bundle `{}` to be named struct or tuple",
175                            // FIXME: once we have unique reflect, use `TypePath`.
176                            DebugName::type_name::<B>(),
177                        ),
178                    }
179                }
180            },
181            apply_or_insert_mapped: |entity,
182                                     reflected_bundle,
183                                     registry,
184                                     mapper,
185                                     relationship_hook_mode| {
186                if let Some(reflect_component) =
187                    registry.get_type_data::<ReflectComponent>(TypeId::of::<B>())
188                {
189                    reflect_component.apply_or_insert_mapped(
190                        entity,
191                        reflected_bundle,
192                        registry,
193                        mapper,
194                        relationship_hook_mode,
195                    );
196                } else {
197                    match reflected_bundle.reflect_ref() {
198                        ReflectRef::Struct(bundle) => {
199                            bundle.iter_fields().for_each(|(_, field)| {
200                                apply_or_insert_field_mapped(
201                                    entity,
202                                    field,
203                                    registry,
204                                    mapper,
205                                    relationship_hook_mode,
206                                );
207                            });
208                        }
209                        ReflectRef::Tuple(bundle) => bundle.iter_fields().for_each(|field| {
210                            apply_or_insert_field_mapped(
211                                entity,
212                                field,
213                                registry,
214                                mapper,
215                                relationship_hook_mode,
216                            );
217                        }),
218                        _ => panic!(
219                            "expected bundle `{}` to be a named struct or tuple",
220                            // FIXME: once we have unique reflect, use `TypePath`.
221                            DebugName::type_name::<B>(),
222                        ),
223                    }
224                }
225            },
226            remove: |entity| {
227                entity.remove::<B>();
228            },
229            take: |entity| {
230                entity
231                    .take::<B>()
232                    .map(|bundle| Box::new(bundle).into_reflect())
233            },
234        })
235    }
236}
237
238fn apply_field(entity: &mut EntityMut, field: &dyn PartialReflect, registry: &TypeRegistry) {
239    let Some(type_id) = field.try_as_reflect().map(Any::type_id) else {
240        panic!(
241            "`{}` did not implement `Reflect`",
242            field.reflect_type_path()
243        );
244    };
245    if let Some(reflect_component) = registry.get_type_data::<ReflectComponent>(type_id) {
246        reflect_component.apply(entity.reborrow(), field);
247    } else if let Some(reflect_bundle) = registry.get_type_data::<ReflectBundle>(type_id) {
248        reflect_bundle.apply(entity.reborrow(), field, registry);
249    } else {
250        panic!(
251            "no `ReflectComponent` nor `ReflectBundle` registration found for `{}`",
252            field.reflect_type_path()
253        );
254    }
255}
256
257fn apply_or_insert_field_mapped(
258    entity: &mut EntityWorldMut,
259    field: &dyn PartialReflect,
260    registry: &TypeRegistry,
261    mapper: &mut dyn EntityMapper,
262    relationship_hook_mode: RelationshipHookMode,
263) {
264    let Some(type_id) = field.try_as_reflect().map(Any::type_id) else {
265        panic!(
266            "`{}` did not implement `Reflect`",
267            field.reflect_type_path()
268        );
269    };
270
271    if let Some(reflect_component) = registry.get_type_data::<ReflectComponent>(type_id) {
272        reflect_component.apply_or_insert_mapped(
273            entity,
274            field,
275            registry,
276            mapper,
277            relationship_hook_mode,
278        );
279    } else if let Some(reflect_bundle) = registry.get_type_data::<ReflectBundle>(type_id) {
280        reflect_bundle.apply_or_insert_mapped(
281            entity,
282            field,
283            registry,
284            mapper,
285            relationship_hook_mode,
286        );
287    } else {
288        let is_component = entity.world().components().get_id(type_id).is_some();
289
290        if is_component {
291            panic!(
292                "no `ReflectComponent` registration found for `{}`",
293                field.reflect_type_path(),
294            );
295        } else {
296            panic!(
297                "no `ReflectBundle` registration found for `{}`",
298                field.reflect_type_path(),
299            )
300        }
301    }
302}