bones_ecs/
resources.rs

1//! World resource storage.
2
3use std::{fmt::Debug, marker::PhantomData, sync::Arc};
4
5use once_map::OnceMap;
6
7use crate::prelude::*;
8
9/// An untyped, atomic resource cell.
10pub type AtomicUntypedResource = Arc<UntypedResource>;
11
12/// An untyped resource that may be inserted into [`UntypedResources`].
13///
14/// This is fundamentally a [`Arc<AtomicCell<Option<SchemaBox>>>`] and thus represents
15/// a cell that may or may not contain a resource of it's schema.
16pub struct UntypedResource {
17    cell: AtomicCell<Option<SchemaBox>>,
18    schema: &'static Schema,
19}
20
21impl std::fmt::Debug for UntypedResource {
22    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23        f.debug_struct("UntypedResource").finish_non_exhaustive()
24    }
25}
26
27impl UntypedResource {
28    /// Initialize a new, empty [`UntypedResource`].
29    pub fn empty(schema: &'static Schema) -> Self {
30        Self {
31            cell: AtomicCell::new(None),
32            schema,
33        }
34    }
35
36    /// Creates a new [`UntypedResource`] storing the given data.
37    pub fn new(resource: SchemaBox) -> Self {
38        Self {
39            schema: resource.schema(),
40            cell: AtomicCell::new(Some(resource)),
41        }
42    }
43
44    /// Create a new [`UntypedResource`] for the given schema, initially populated with the default
45    /// value for the schema.
46    pub fn from_default(schema: &'static Schema) -> Self {
47        Self {
48            cell: AtomicCell::new(Some(SchemaBox::default(schema))),
49            schema,
50        }
51    }
52
53    /// Clone the inner data, creating a new copy instead of returning another handle the the same
54    /// data, as the normal `clone()` implementation does.
55    pub fn clone_data(&self) -> Option<SchemaBox> {
56        (*self.cell.borrow()).clone()
57    }
58
59    /// Insert resource data into the cell, returning the previous data.
60    /// # Errors
61    /// Errors if the schema of the data does not match that of this cell.
62    pub fn insert(&self, data: SchemaBox) -> Result<Option<SchemaBox>, SchemaMismatchError> {
63        self.schema.ensure_match(data.schema())?;
64        let mut data = Some(data);
65        std::mem::swap(&mut data, &mut *self.cell.borrow_mut());
66        Ok(data)
67    }
68
69    /// Remove the resource data, returning what was stored in it.
70    pub fn remove(&self) -> Option<SchemaBox> {
71        let mut data = None;
72        std::mem::swap(&mut data, &mut *self.cell.borrow_mut());
73        data
74    }
75
76    /// Borrow the resource.
77    #[track_caller]
78    pub fn borrow(&self) -> Ref<'_, Option<SchemaBox>> {
79        self.cell.borrow()
80    }
81
82    /// Mutably borrow the resource.
83    #[track_caller]
84    pub fn borrow_mut(&self) -> RefMut<'_, Option<SchemaBox>> {
85        self.cell.borrow_mut()
86    }
87
88    /// Get the schema of the resource.
89    pub fn schema(&self) -> &'static Schema {
90        self.schema
91    }
92}
93
94/// Storage for un-typed resources.
95///
96/// This is the backing data store used by [`Resources`].
97///
98/// Unless you are intending to do modding or otherwise need raw pointers to your resource data, you
99/// should use [`Resources`] instead.
100#[derive(Default)]
101pub struct UntypedResources {
102    resources: OnceMap<SchemaId, AtomicUntypedResource>,
103    shared_resources: OnceMap<SchemaId, Box<()>>,
104}
105
106impl Clone for UntypedResources {
107    fn clone(&self) -> Self {
108        let binding = self.resources.read_only_view();
109        let resources = binding.iter().map(|(_, v)| (v.schema, v));
110
111        let new_resources = OnceMap::default();
112        let new_shared_resources = OnceMap::default();
113        for (schema, resource_cell) in resources {
114            let is_shared = self.shared_resources.contains_key(&schema.id());
115
116            if !is_shared {
117                let resource = resource_cell.clone_data();
118                new_resources.map_insert(
119                    schema.id(),
120                    |_| Arc::new(UntypedResource::empty(schema)),
121                    |_, cell| {
122                        if let Some(resource) = resource {
123                            cell.insert(resource).unwrap();
124                        }
125                    },
126                );
127            } else {
128                new_shared_resources.insert(schema.id(), |_| Box::new(()));
129                new_resources.insert(schema.id(), |_| resource_cell.clone());
130            }
131        }
132        Self {
133            resources: new_resources,
134            shared_resources: new_shared_resources,
135        }
136    }
137}
138
139/// Error thrown when a resource cell cannot be inserted because it already exists.
140#[derive(Debug, Clone, Copy)]
141pub struct CellAlreadyPresentError;
142impl std::fmt::Display for CellAlreadyPresentError {
143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        f.write_str("Resource cell already present")
145    }
146}
147impl std::error::Error for CellAlreadyPresentError {}
148
149impl UntypedResources {
150    /// Create an empty [`UntypedResources`].
151    pub fn new() -> Self {
152        Self::default()
153    }
154
155    /// Check whether or not a cell for the given resource has been initialized yet.
156    pub fn contains_cell(&self, id: SchemaId) -> bool {
157        self.resources.contains_key(&id)
158    }
159
160    /// Check whether or not the resource with the given ID is present.
161    pub fn contains(&self, id: SchemaId) -> bool {
162        self.resources
163            .map_get(&id, |_, cell| cell.borrow().is_some())
164            .unwrap_or_default()
165    }
166
167    /// This is an advanced use-case function that allows you to insert a resource cell directly.
168    ///
169    /// Normally this is completely unnecessary, because cells are automatically inserted lazily as
170    /// requested.
171    ///
172    /// Inserting this manually is used internally for shared resources, by inserting the same
173    /// cell into multiple worlds.
174    ///
175    /// # Errors
176    /// This will error if there is already a cell for the resource present. You cannot add a new
177    /// cell once one has already been inserted.
178    pub fn insert_cell(&self, cell: AtomicUntypedResource) -> Result<(), CellAlreadyPresentError> {
179        let schema = cell.schema;
180        if self.resources.contains_key(&schema.id()) {
181            Err(CellAlreadyPresentError)
182        } else {
183            self.resources.insert(schema.id(), |_| cell);
184            self.shared_resources.insert(schema.id(), |_| Box::new(()));
185            Ok(())
186        }
187    }
188
189    /// Borrow the resource for the given schema.
190    pub fn get(&self, schema: &'static Schema) -> &UntypedResource {
191        self.resources
192            .insert(schema.id(), |_| Arc::new(UntypedResource::empty(schema)))
193    }
194
195    /// Get a cell for the resource with the given schema.
196    pub fn get_cell(&self, schema: &'static Schema) -> AtomicUntypedResource {
197        self.resources.map_insert(
198            schema.id(),
199            |_| Arc::new(UntypedResource::empty(schema)),
200            |_, cell| cell.clone(),
201        )
202    }
203
204    /// Iterates through owned and shared resource cells removing them if the predicate returns `false`.
205    ///
206    /// See also: [`Self::retain_owned_resources`].
207    pub fn retain_resources<F>(&self, mut predicate: F)
208    where
209        F: FnMut(SchemaId) -> bool,
210    {
211        for (schema_id, resource_cell) in self.resources.read_only_view().iter() {
212            let is_retained = predicate(*schema_id);
213            if !is_retained {
214                resource_cell.remove();
215            }
216        }
217    }
218
219    /// Iterates through resource cells removing them if the predicate returns `false`.
220    ///
221    /// Doesn't include shared resources. See also: [`Self::retain_resources`].
222    pub fn retain_owned_resources<F>(&self, mut predicate: F)
223    where
224        F: FnMut(SchemaId) -> bool,
225    {
226        for (schema_id, resource_cell) in self.resources.read_only_view().iter() {
227            let is_shared = self.shared_resources.contains_key(schema_id);
228            let is_retained = predicate(*schema_id);
229            if !is_shared && !is_retained {
230                resource_cell.remove();
231            }
232        }
233    }
234
235    /// Removes all resourcse that are not shared resources.
236    pub fn clear_owned_resources(&self) {
237        for (schema_id, resource_cell) in self.resources.read_only_view().iter() {
238            let is_shared = self.shared_resources.contains_key(schema_id);
239            if !is_shared {
240                resource_cell.remove();
241            }
242        }
243    }
244}
245
246/// A collection of resources.
247///
248/// [`Resources`] is essentially a type-map
249#[derive(Clone, Default)]
250pub struct Resources {
251    untyped: UntypedResources,
252}
253
254impl Resources {
255    /// Create an empty [`Resources`].
256    pub fn new() -> Self {
257        Self::default()
258    }
259
260    /// Insert a resource.
261    pub fn insert<T: HasSchema>(&self, resource: T) -> Option<T> {
262        self.untyped
263            .get(T::schema())
264            .insert(SchemaBox::new(resource))
265            .unwrap()
266            .map(|x| x.cast_into())
267    }
268
269    /// Check whether or not a resource is in the store.
270    ///
271    /// See [get()][Self::get]
272    pub fn contains<T: HasSchema>(&self) -> bool {
273        self.untyped.contains(T::schema().id())
274    }
275
276    /// Remove a resource from the store, if it is present.
277    pub fn remove<T: HasSchema>(&self) -> Option<T> {
278        self.untyped
279            .get(T::schema())
280            .remove()
281            // SOUND: we know the type matches because we retrieve it by it's schema.
282            .map(|x| unsafe { x.cast_into_unchecked() })
283    }
284
285    /// Borrow a resource.
286    #[track_caller]
287    pub fn get<T: HasSchema>(&self) -> Option<Ref<'_, T>> {
288        let b = self.untyped.get(T::schema()).borrow();
289        if b.is_some() {
290            Some(Ref::map(b, |b| unsafe {
291                b.as_ref().unwrap().as_ref().cast_into_unchecked()
292            }))
293        } else {
294            None
295        }
296    }
297
298    /// Borrow a resource.
299    #[track_caller]
300    pub fn get_mut<T: HasSchema>(&self) -> Option<RefMut<'_, T>> {
301        let b = self.untyped.get(T::schema()).borrow_mut();
302        if b.is_some() {
303            Some(RefMut::map(b, |b| unsafe {
304                b.as_mut().unwrap().as_mut().cast_into_mut_unchecked()
305            }))
306        } else {
307            None
308        }
309    }
310
311    /// Gets a clone of the resource cell for the resource of the given type.
312    pub fn get_cell<T: HasSchema>(&self) -> AtomicResource<T> {
313        let untyped = self.untyped.get_cell(T::schema()).clone();
314        AtomicResource {
315            untyped,
316            _phantom: PhantomData,
317        }
318    }
319
320    /// Borrow the underlying [`UntypedResources`] store.
321    pub fn untyped(&self) -> &UntypedResources {
322        &self.untyped
323    }
324
325    /// Consume [`Resources`] and extract the underlying [`UntypedResources`].
326    pub fn into_untyped(self) -> UntypedResources {
327        self.untyped
328    }
329
330    /// Removes all resources that are not shared. Shared resources are preserved.
331    pub fn clear_owned_resources(&self) {
332        self.untyped().clear_owned_resources();
333    }
334}
335
336/// A handle to a resource from a [`Resources`] collection.
337///
338/// This is not the resource itself, but a cheaply clonable handle to it.
339///
340/// To access the resource you must borrow it with either [`borrow()`][Self::borrow] or
341/// [`borrow_mut()`][Self::borrow_mut].
342#[derive(Clone)]
343pub struct AtomicResource<T: HasSchema> {
344    untyped: AtomicUntypedResource,
345    _phantom: PhantomData<T>,
346}
347impl<T: HasSchema + Debug> Debug for AtomicResource<T> {
348    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
349        f.write_str("AtomicResource(")?;
350        self.untyped
351            .cell
352            .borrow()
353            .as_ref()
354            .map(|x| x.cast_ref::<T>())
355            .fmt(f)?;
356        f.write_str(")")?;
357        Ok(())
358    }
359}
360
361impl<T: HasSchema + Default> Default for AtomicResource<T> {
362    fn default() -> Self {
363        Self {
364            untyped: Arc::new(UntypedResource::new(SchemaBox::new(T::default()))),
365            _phantom: Default::default(),
366        }
367    }
368}
369
370impl<T: HasSchema> AtomicResource<T> {
371    /// Create a new, empty resource cell.
372    pub fn empty() -> Self {
373        Self {
374            untyped: Arc::new(UntypedResource::empty(T::schema())),
375            _phantom: PhantomData,
376        }
377    }
378
379    /// Create a new resource cell with the given data.
380    pub fn new(data: T) -> Self {
381        AtomicResource {
382            untyped: Arc::new(UntypedResource::new(SchemaBox::new(data))),
383            _phantom: PhantomData,
384        }
385    }
386
387    /// Create from an [`UntypedResource`].
388    pub fn from_untyped(untyped: AtomicUntypedResource) -> Result<Self, SchemaMismatchError> {
389        T::schema().ensure_match(untyped.schema)?;
390        Ok(AtomicResource {
391            untyped,
392            _phantom: PhantomData,
393        })
394    }
395
396    /// Remove the resource from the cell, leaving the cell empty.
397    pub fn remove(&self) -> Option<T> {
398        self.untyped
399            .remove()
400            // SOUND: The untyped data of an atomic resource must always be `T`.
401            .map(|x| unsafe { x.cast_into_unchecked() })
402    }
403
404    /// Lock the resource for reading.
405    ///
406    /// This returns a read guard, very similar to an [`RwLock`][std::sync::RwLock].
407    pub fn borrow(&self) -> Option<Ref<'_, T>> {
408        let borrow = self.untyped.borrow();
409        if borrow.is_some() {
410            Some(Ref::map(borrow, |r| unsafe {
411                r.as_ref().unwrap().as_ref().cast_into_unchecked()
412            }))
413        } else {
414            None
415        }
416    }
417
418    /// Lock the resource for read-writing.
419    ///
420    /// This returns a write guard, very similar to an [`RwLock`][std::sync::RwLock].
421    pub fn borrow_mut(&self) -> Option<RefMut<'_, T>> {
422        let borrow = self.untyped.borrow_mut();
423        if borrow.is_some() {
424            Some(RefMut::map(borrow, |r| unsafe {
425                r.as_mut().unwrap().as_mut().cast_into_mut_unchecked()
426            }))
427        } else {
428            None
429        }
430    }
431
432    /// Convert into an untyped resource.
433    pub fn into_untyped(self) -> AtomicUntypedResource {
434        self.untyped
435    }
436}
437
438impl<T: HasSchema + FromWorld> AtomicResource<T> {
439    /// Initialize the resource using it's [`FromWorld`] implementation, if it is not present.
440    pub fn init(&self, world: &World) {
441        let mut borrow = self.untyped.borrow_mut();
442        if unlikely(borrow.is_none()) {
443            *borrow = Some(SchemaBox::new(T::from_world(world)))
444        }
445    }
446
447    /// Borrow the resource, initializing it if it doesn't exist.
448    #[track_caller]
449    pub fn init_borrow(&self, world: &World) -> Ref<'_, T> {
450        let map_borrow = |borrow| {
451            // SOUND: we know the schema matches.
452            Ref::map(borrow, |b: &Option<SchemaBox>| unsafe {
453                b.as_ref().unwrap().as_ref().cast_into_unchecked()
454            })
455        };
456        let borrow = self.untyped.borrow();
457        if unlikely(borrow.is_none()) {
458            drop(borrow);
459            {
460                let mut borrow_mut = self.untyped.borrow_mut();
461                *borrow_mut = Some(SchemaBox::new(T::from_world(world)));
462            }
463
464            map_borrow(self.untyped.borrow())
465        } else {
466            map_borrow(borrow)
467        }
468    }
469
470    /// Borrow the resource, initializing it if it doesn't exist.
471    #[track_caller]
472    pub fn init_borrow_mut(&self, world: &World) -> RefMut<'_, T> {
473        let mut borrow = self.untyped.borrow_mut();
474        if unlikely(borrow.is_none()) {
475            *borrow = Some(SchemaBox::new(T::from_world(world)));
476        }
477        RefMut::map(borrow, |b| unsafe {
478            b.as_mut().unwrap().as_mut().cast_into_mut_unchecked()
479        })
480    }
481}
482
483/// Utility container for storing set of [`UntypedResource`].
484/// Cloning
485#[derive(Default)]
486pub struct UntypedResourceSet {
487    resources: Vec<UntypedResource>,
488}
489
490impl Clone for UntypedResourceSet {
491    fn clone(&self) -> Self {
492        Self {
493            resources: self
494                .resources
495                .iter()
496                .map(|res| {
497                    if let Some(clone) = res.clone_data() {
498                        UntypedResource::new(clone)
499                    } else {
500                        UntypedResource::empty(res.schema())
501                    }
502                })
503                .collect(),
504        }
505    }
506}
507
508impl UntypedResourceSet {
509    /// Insert a startup resource. On stage / session startup (first step), will be inserted into [`World`].
510    ///
511    /// If already exists, will be overwritten.
512    pub fn insert_resource<T: HasSchema>(&mut self, resource: T) {
513        // Update an existing resource of the same type.
514        for r in &mut self.resources {
515            if r.schema() == T::schema() {
516                let mut borrow = r.borrow_mut();
517
518                if let Some(b) = borrow.as_mut() {
519                    *b.cast_mut() = resource;
520                } else {
521                    *borrow = Some(SchemaBox::new(resource))
522                }
523                return;
524            }
525        }
526
527        // Or insert a new resource if we couldn't find one
528        self.resources
529            .push(UntypedResource::new(SchemaBox::new(resource)))
530    }
531
532    /// Init resource with default, and return mutable ref for modification.
533    /// If already exists, returns mutable ref to existing resource.
534    pub fn init_resource<T: HasSchema + Default>(&mut self) -> RefMut<'_, T> {
535        if !self.resources.iter().any(|x| x.schema() == T::schema()) {
536            self.insert_resource(T::default());
537        }
538        self.resource_mut::<T>().unwrap()
539    }
540
541    /// Get mutable reference to startup resource if found.
542    #[track_caller]
543    pub fn resource_mut<T: HasSchema>(&self) -> Option<RefMut<'_, T>> {
544        let res = self.resources.iter().find(|x| x.schema() == T::schema())?;
545        let borrow = res.borrow_mut();
546
547        if borrow.is_some() {
548            // SOUND: We know the type matches T
549            Some(RefMut::map(borrow, |b| unsafe {
550                b.as_mut().unwrap().as_mut().cast_into_mut_unchecked()
551            }))
552        } else {
553            None
554        }
555    }
556
557    /// Insert an [`UntypedResource`] with empty cell for [`Schema`] of `T`.
558    /// If resource already exists for this schema, overwrite it with empty.
559    pub fn insert_empty<T: HasSchema>(&mut self) {
560        for r in &mut self.resources {
561            if r.schema() == T::schema() {
562                let mut borrow = r.borrow_mut();
563                *borrow = None;
564                return;
565            }
566        }
567
568        // Or insert a new empty resource if we couldn't find one
569        self.resources.push(UntypedResource::empty(T::schema()));
570    }
571
572    /// Get immutable ref to Vec of resources
573    pub fn resources(&self) -> &Vec<UntypedResource> {
574        &self.resources
575    }
576
577    /// Insert resources in world. If resource already exists, overwrites it.
578    ///
579    /// If `remove_empty` is set, if resource cell is empty, it will remove the
580    /// resource from cell on world.
581    pub fn insert_on_world(&self, world: &World, remove_empty: bool) {
582        for resource in self.resources.iter() {
583            let resource_cell = world.resources.untyped().get_cell(resource.schema());
584
585            // Deep copy resource and insert into world.
586            if let Some(resource_copy) = resource.clone_data() {
587                resource_cell
588                    .insert(resource_copy)
589                    .expect("Schema mismatch error");
590            } else if remove_empty {
591                // Remove the resource on world
592                resource_cell.remove();
593            }
594        }
595    }
596}
597
598#[cfg(test)]
599mod test {
600    use std::sync::Arc;
601
602    use crate::prelude::*;
603    #[derive(HasSchema, Clone, Debug, Default)]
604    #[repr(C)]
605    struct A(String);
606
607    #[derive(HasSchema, Clone, Debug, Default)]
608    #[repr(C)]
609    struct B(u32);
610
611    #[test]
612    fn sanity_check() {
613        let r1 = Resources::new();
614
615        r1.insert(A(String::from("hi")));
616        let r1a = r1.get_cell::<A>();
617        assert_eq!(r1a.borrow().unwrap().0, "hi");
618
619        let r2 = r1.clone();
620
621        r1.insert(A(String::from("bye")));
622        r1.insert(A(String::from("world")));
623        assert_eq!(r1a.borrow().unwrap().0, "world");
624
625        let r2a = r2.get_cell::<A>();
626        assert_eq!(r2a.borrow().unwrap().0, "hi");
627
628        r1.insert(B(1));
629        let r1b = r1.get_cell::<B>();
630        assert_eq!(r1b.borrow().unwrap().0, 1);
631        r1.insert(B(2));
632        assert_eq!(r1b.borrow().unwrap().0, 2);
633        assert_eq!(r1a.borrow().unwrap().0, "world");
634    }
635
636    #[test]
637    fn resources_clear_owned_values() {
638        let r = Resources::new();
639
640        // insert A as non-shared resource
641        r.insert(A(String::from("foo")));
642
643        // Insert B as shared resource
644        r.untyped
645            .insert_cell(Arc::new(UntypedResource::new(SchemaBox::new(B(1)))))
646            .unwrap();
647
648        // Should only clear non-shared resources
649        r.clear_owned_resources();
650
651        // Verify non-shared was removed
652        let res_a = r.get::<A>();
653        assert!(res_a.is_none());
654
655        // Verify shared is still present
656        let res_b = r.get::<B>().unwrap();
657        assert_eq!(res_b.0, 1);
658    }
659}