intuicio_framework_ecs/
resources.rs1use crate::{
2 archetype::ArchetypeColumnInfo,
3 bundle::{Bundle, BundleColumns},
4 query::{TypedQueryFetch, TypedQueryIter},
5 world::{World, WorldChanges, WorldError},
6 Component, ComponentRef, ComponentRefMut,
7};
8use intuicio_data::type_hash::TypeHash;
9use std::{error::Error, sync::RwLockReadGuard};
10
11#[derive(Default)]
12pub struct Resources {
13 world: World,
14}
15
16impl Resources {
17 pub fn add(&mut self, bundle: impl Bundle) -> Result<(), Box<dyn Error>> {
18 let entity = self.world.entities().next();
19 if let Some(entity) = entity {
20 WorldError::allow(
21 self.world.insert(entity, bundle),
22 [WorldError::EmptyColumnSet],
23 (),
24 )?;
25 } else {
26 self.world.spawn(bundle)?;
27 }
28 Ok(())
29 }
30
31 pub fn remove<T: BundleColumns>(&mut self) -> Result<(), Box<dyn Error>> {
32 let entity = self.world.entities().next();
33 if let Some(entity) = entity {
34 self.world.remove::<T>(entity)?;
35 }
36 Ok(())
37 }
38
39 pub fn remove_raw(&mut self, columns: Vec<ArchetypeColumnInfo>) -> Result<(), Box<dyn Error>> {
40 let entity = self.world.entities().next();
41 if let Some(entity) = entity {
42 self.world.remove_raw(entity, columns)?;
43 }
44 Ok(())
45 }
46
47 pub fn clear(&mut self) {
48 self.world.clear();
49 }
50
51 pub fn clear_changes(&mut self) {
52 self.world.clear_changes();
53 }
54
55 pub fn added(&self) -> &WorldChanges {
56 self.world.added()
57 }
58
59 pub fn removed(&self) -> &WorldChanges {
60 self.world.removed()
61 }
62
63 pub fn updated(&self) -> Option<RwLockReadGuard<'_, WorldChanges>> {
64 self.world.updated()
65 }
66
67 pub fn did_changed<T: Component>(&self) -> bool {
68 self.world.component_did_changed::<T>()
69 }
70
71 pub fn did_changed_raw(&self, type_hash: TypeHash) -> bool {
72 self.world.component_did_changed_raw(type_hash)
73 }
74
75 pub fn get<const LOCKING: bool, T: Component>(
76 &self,
77 ) -> Result<ComponentRef<LOCKING, T>, Box<dyn Error>> {
78 let entity = self.world.entities().next().unwrap_or_default();
79 Ok(self.world.component(entity)?)
80 }
81
82 pub fn get_mut<const LOCKING: bool, T: Component>(
83 &self,
84 ) -> Result<ComponentRefMut<LOCKING, T>, Box<dyn Error>> {
85 let entity = self.world.entities().next().unwrap_or_default();
86 Ok(self.world.component_mut(entity)?)
87 }
88
89 pub fn query<'a, const LOCKING: bool, Fetch: TypedQueryFetch<'a, LOCKING>>(
90 &'a self,
91 ) -> TypedQueryIter<'a, LOCKING, Fetch> {
92 self.world.query::<LOCKING, Fetch>()
93 }
94}