1use std::cell::{RefCell, RefMut};
2
3pub struct Resources {
4 pub(crate) resource_entity: hecs::Entity,
5 cmds: RefCell<hecs::CommandBuffer>,
6}
7
8impl Resources {
9 pub fn new(world: &mut hecs::World) -> Self {
10 Self {
11 resource_entity: world.spawn(()),
12 cmds: RefCell::new(hecs::CommandBuffer::default()),
13 }
14 }
15
16 pub fn insert_resource<T>(&mut self, world: &mut hecs::World, res: T)
17 where
18 T: hecs::Component,
19 {
20 world.insert_one(self.resource_entity, res).ok();
21 }
22
23 pub fn get_resource<'a, T>(&self, world: &'a hecs::World) -> hecs::Ref<'a, T>
24 where
25 T: hecs::Component,
26 {
27 world
28 .get::<&T>(self.resource_entity)
29 .unwrap_or_else(|_| panic!("Resource not found: {}", std::any::type_name::<T>()))
30 }
31
32 pub fn get_resource_mut<'a, T>(&self, world: &'a hecs::World) -> hecs::RefMut<'a, T>
33 where
34 T: hecs::Component,
35 {
36 world
37 .get::<&mut T>(self.resource_entity)
38 .unwrap_or_else(|_| panic!("Resource not found: {}", std::any::type_name::<T>()))
39 }
40
41 pub fn has_resource<T>(&self, world: &hecs::World) -> bool
42 where
43 T: hecs::Component,
44 {
45 if let Ok(_) = world.get::<&T>(self.resource_entity) {
46 return true;
47 }
48
49 false
50 }
51
52 pub fn get_command_buffer<'a>(&'a self) -> RefMut<'a, hecs::CommandBuffer> {
53 self.cmds.borrow_mut()
54 }
55
56 pub fn try_insert<T>(&mut self, world: &mut hecs::World, res: T) -> bool
57 where
58 T: hecs::Component,
59 {
60 if self.has_resource::<T>(world) {
61 false
62 } else {
63 world.insert_one(self.resource_entity, res).ok();
64 true
65 }
66 }
67}