Skip to content

Commit e68ba95

Browse files
committed
feat(ecs): Resources
1 parent e9e307a commit e68ba95

File tree

1 file changed

+29
-6
lines changed

1 file changed

+29
-6
lines changed

ecs/src/lib.rs

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,32 +2,45 @@ use std::{
22
any::{Any, TypeId},
33
cell::RefCell,
44
collections::HashMap,
5+
ops::{Deref, DerefMut},
56
rc::Rc,
67
};
78

89
/// Marker trait for ECS components
910
pub trait Component: 'static {}
1011

11-
/// Trait for ECS systems that operate on the World
12-
pub trait System {
13-
/// Execute the system with the given World
14-
fn execute(&mut self, world: &mut World);
15-
}
12+
/// Marker trait for ECS resources
13+
pub trait Resource: 'static {}
1614

1715
/// A unique identifier for an entity
1816
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1917
pub struct EntityId(pub u32);
2018

19+
impl Deref for EntityId {
20+
type Target = u32;
21+
22+
fn deref(&self) -> &Self::Target {
23+
&self.0
24+
}
25+
}
26+
27+
impl DerefMut for EntityId {
28+
fn deref_mut(&mut self) -> &mut Self::Target {
29+
&mut self.0
30+
}
31+
}
32+
2133
/// The main ECS world that holds all entities and their components
2234
pub struct World {
2335
entities: HashMap<EntityId, Entity>,
36+
resources: HashMap<TypeId, Rc<RefCell<dyn Resource>>>,
2437
next_id: u32,
2538
}
2639

2740
/// An entity is just a collection of components
2841
pub struct Entity {
2942
pub id: EntityId,
30-
components: HashMap<TypeId, Rc<RefCell<dyn Any>>>,
43+
components: HashMap<TypeId, Rc<RefCell<dyn Component>>>,
3144
}
3245

3346
impl Default for World {
@@ -40,6 +53,7 @@ impl World {
4053
pub fn new() -> Self {
4154
Self {
4255
entities: HashMap::new(),
56+
resources: HashMap::new(),
4357
next_id: 0,
4458
}
4559
}
@@ -128,4 +142,13 @@ impl World {
128142
pub fn get_all_entities(&self) -> Vec<EntityId> {
129143
self.entities.keys().copied().collect()
130144
}
145+
146+
pub fn get_resource(&self, type_id: TypeId) -> Option<Rc<RefCell<dyn Resource>>> {
147+
self.resources.get(&type_id).cloned()
148+
}
149+
150+
pub fn insert_resource<T: Resource>(&mut self, resource: T) {
151+
self.resources
152+
.insert(resource.type_id(), Rc::new(RefCell::new(resource)));
153+
}
131154
}

0 commit comments

Comments
 (0)