bevy_ecs/reflect/resource.rs
1//! Definitions for [`Resource`] reflection.
2//!
3//! # Architecture
4//!
5//! See the module doc for [`crate::reflect::component`].
6
7use crate::{
8 change_detection::Mut,
9 component::ComponentId,
10 system::Resource,
11 world::{unsafe_world_cell::UnsafeWorldCell, World},
12};
13use bevy_reflect::{FromReflect, FromType, PartialReflect, Reflect, TypePath, TypeRegistry};
14
15use super::from_reflect_with_fallback;
16
17/// A struct used to operate on reflected [`Resource`] of a type.
18///
19/// A [`ReflectResource`] for type `T` can be obtained via
20/// [`bevy_reflect::TypeRegistration::data`].
21#[derive(Clone)]
22pub struct ReflectResource(ReflectResourceFns);
23
24/// The raw function pointers needed to make up a [`ReflectResource`].
25///
26/// This is used when creating custom implementations of [`ReflectResource`] with
27/// [`ReflectResource::new()`].
28///
29/// > **Note:**
30/// > Creating custom implementations of [`ReflectResource`] is an advanced feature that most users
31/// > will not need.
32/// > Usually a [`ReflectResource`] is created for a type by deriving [`Reflect`]
33/// > and adding the `#[reflect(Resource)]` attribute.
34/// > After adding the component to the [`TypeRegistry`],
35/// > its [`ReflectResource`] can then be retrieved when needed.
36///
37/// Creating a custom [`ReflectResource`] may be useful if you need to create new resource types at
38/// runtime, for example, for scripting implementations.
39///
40/// By creating a custom [`ReflectResource`] and inserting it into a type's
41/// [`TypeRegistration`][bevy_reflect::TypeRegistration],
42/// you can modify the way that reflected resources of that type will be inserted into the bevy
43/// world.
44#[derive(Clone)]
45pub struct ReflectResourceFns {
46 /// Function pointer implementing [`ReflectResource::insert()`].
47 pub insert: fn(&mut World, &dyn PartialReflect, &TypeRegistry),
48 /// Function pointer implementing [`ReflectResource::apply()`].
49 pub apply: fn(&mut World, &dyn PartialReflect),
50 /// Function pointer implementing [`ReflectResource::apply_or_insert()`].
51 pub apply_or_insert: fn(&mut World, &dyn PartialReflect, &TypeRegistry),
52 /// Function pointer implementing [`ReflectResource::remove()`].
53 pub remove: fn(&mut World),
54 /// Function pointer implementing [`ReflectResource::reflect()`].
55 pub reflect: fn(&World) -> Option<&dyn Reflect>,
56 /// Function pointer implementing [`ReflectResource::reflect_unchecked_mut()`].
57 ///
58 /// # Safety
59 /// The function may only be called with an [`UnsafeWorldCell`] that can be used to mutably access the relevant resource.
60 pub reflect_unchecked_mut: unsafe fn(UnsafeWorldCell<'_>) -> Option<Mut<'_, dyn Reflect>>,
61 /// Function pointer implementing [`ReflectResource::copy()`].
62 pub copy: fn(&World, &mut World, &TypeRegistry),
63 /// Function pointer implementing [`ReflectResource::register_resource()`].
64 pub register_resource: fn(&mut World) -> ComponentId,
65}
66
67impl ReflectResourceFns {
68 /// Get the default set of [`ReflectResourceFns`] for a specific resource type using its
69 /// [`FromType`] implementation.
70 ///
71 /// This is useful if you want to start with the default implementation before overriding some
72 /// of the functions to create a custom implementation.
73 pub fn new<T: Resource + FromReflect + TypePath>() -> Self {
74 <ReflectResource as FromType<T>>::from_type().0
75 }
76}
77
78impl ReflectResource {
79 /// Insert a reflected [`Resource`] into the world like [`insert()`](World::insert_resource).
80 pub fn insert(
81 &self,
82 world: &mut World,
83 resource: &dyn PartialReflect,
84 registry: &TypeRegistry,
85 ) {
86 (self.0.insert)(world, resource, registry);
87 }
88
89 /// Uses reflection to set the value of this [`Resource`] type in the world to the given value.
90 ///
91 /// # Panics
92 ///
93 /// Panics if there is no [`Resource`] of the given type.
94 pub fn apply(&self, world: &mut World, resource: &dyn PartialReflect) {
95 (self.0.apply)(world, resource);
96 }
97
98 /// Uses reflection to set the value of this [`Resource`] type in the world to the given value or insert a new one if it does not exist.
99 pub fn apply_or_insert(
100 &self,
101 world: &mut World,
102 resource: &dyn PartialReflect,
103 registry: &TypeRegistry,
104 ) {
105 (self.0.apply_or_insert)(world, resource, registry);
106 }
107
108 /// Removes this [`Resource`] type from the world. Does nothing if it doesn't exist.
109 pub fn remove(&self, world: &mut World) {
110 (self.0.remove)(world);
111 }
112
113 /// Gets the value of this [`Resource`] type from the world as a reflected reference.
114 pub fn reflect<'a>(&self, world: &'a World) -> Option<&'a dyn Reflect> {
115 (self.0.reflect)(world)
116 }
117
118 /// Gets the value of this [`Resource`] type from the world as a mutable reflected reference.
119 pub fn reflect_mut<'a>(&self, world: &'a mut World) -> Option<Mut<'a, dyn Reflect>> {
120 // SAFETY: unique world access
121 unsafe { (self.0.reflect_unchecked_mut)(world.as_unsafe_world_cell()) }
122 }
123
124 /// # Safety
125 /// This method does not prevent you from having two mutable pointers to the same data,
126 /// violating Rust's aliasing rules. To avoid this:
127 /// * Only call this method with an [`UnsafeWorldCell`] which can be used to mutably access the resource.
128 /// * Don't call this method more than once in the same scope for a given [`Resource`].
129 pub unsafe fn reflect_unchecked_mut<'w>(
130 &self,
131 world: UnsafeWorldCell<'w>,
132 ) -> Option<Mut<'w, dyn Reflect>> {
133 // SAFETY: caller promises to uphold uniqueness guarantees
134 unsafe { (self.0.reflect_unchecked_mut)(world) }
135 }
136
137 /// Gets the value of this [`Resource`] type from `source_world` and [applies](Self::apply()) it to the value of this [`Resource`] type in `destination_world`.
138 ///
139 /// # Panics
140 ///
141 /// Panics if there is no [`Resource`] of the given type.
142 pub fn copy(
143 &self,
144 source_world: &World,
145 destination_world: &mut World,
146 registry: &TypeRegistry,
147 ) {
148 (self.0.copy)(source_world, destination_world, registry);
149 }
150
151 /// Register the type of this [`Resource`] in [`World`], returning the [`ComponentId`]
152 pub fn register_resource(&self, world: &mut World) -> ComponentId {
153 (self.0.register_resource)(world)
154 }
155
156 /// Create a custom implementation of [`ReflectResource`].
157 ///
158 /// This is an advanced feature,
159 /// useful for scripting implementations,
160 /// that should not be used by most users
161 /// unless you know what you are doing.
162 ///
163 /// Usually you should derive [`Reflect`] and add the `#[reflect(Resource)]` component
164 /// to generate a [`ReflectResource`] implementation automatically.
165 ///
166 /// See [`ReflectResourceFns`] for more information.
167 pub fn new(&self, fns: ReflectResourceFns) -> Self {
168 Self(fns)
169 }
170
171 /// The underlying function pointers implementing methods on `ReflectResource`.
172 ///
173 /// This is useful when you want to keep track locally of an individual
174 /// function pointer.
175 ///
176 /// Calling [`TypeRegistry::get`] followed by
177 /// [`TypeRegistration::data::<ReflectResource>`] can be costly if done several
178 /// times per frame. Consider cloning [`ReflectResource`] and keeping it
179 /// between frames, cloning a `ReflectResource` is very cheap.
180 ///
181 /// If you only need a subset of the methods on `ReflectResource`,
182 /// use `fn_pointers` to get the underlying [`ReflectResourceFns`]
183 /// and copy the subset of function pointers you care about.
184 ///
185 /// [`TypeRegistration::data::<ReflectResource>`]: bevy_reflect::TypeRegistration::data
186 /// [`TypeRegistry::get`]: bevy_reflect::TypeRegistry::get
187 pub fn fn_pointers(&self) -> &ReflectResourceFns {
188 &self.0
189 }
190}
191
192impl<R: Resource + FromReflect + TypePath> FromType<R> for ReflectResource {
193 fn from_type() -> Self {
194 ReflectResource(ReflectResourceFns {
195 insert: |world, reflected_resource, registry| {
196 let resource = from_reflect_with_fallback::<R>(reflected_resource, world, registry);
197 world.insert_resource(resource);
198 },
199 apply: |world, reflected_resource| {
200 let mut resource = world.resource_mut::<R>();
201 resource.apply(reflected_resource);
202 },
203 apply_or_insert: |world, reflected_resource, registry| {
204 if let Some(mut resource) = world.get_resource_mut::<R>() {
205 resource.apply(reflected_resource);
206 } else {
207 let resource =
208 from_reflect_with_fallback::<R>(reflected_resource, world, registry);
209 world.insert_resource(resource);
210 }
211 },
212 remove: |world| {
213 world.remove_resource::<R>();
214 },
215 reflect: |world| world.get_resource::<R>().map(|res| res as &dyn Reflect),
216 reflect_unchecked_mut: |world| {
217 // SAFETY: all usages of `reflect_unchecked_mut` guarantee that there is either a single mutable
218 // reference or multiple immutable ones alive at any given point
219 let res = unsafe { world.get_resource_mut::<R>() };
220 res.map(|res| res.map_unchanged(|value| value as &mut dyn Reflect))
221 },
222 copy: |source_world, destination_world, registry| {
223 let source_resource = source_world.resource::<R>();
224 let destination_resource =
225 from_reflect_with_fallback::<R>(source_resource, destination_world, registry);
226 destination_world.insert_resource(destination_resource);
227 },
228
229 register_resource: |world: &mut World| -> ComponentId {
230 world.register_resource::<R>()
231 },
232 })
233 }
234}