From 4632dd8e9e95a377993ef677a157202fda8072f9 Mon Sep 17 00:00:00 2001 From: Dominik Kaiser Date: Tue, 2 Jun 2026 23:23:57 +0200 Subject: Implement ECS --- src/lib.rs | 110 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 src/lib.rs (limited to 'src/lib.rs') diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..be4c2bf --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,110 @@ +pub mod bundle; +pub mod component; +pub mod query; +pub mod sparse_set; + +pub mod prelude { + pub use super::component::Component; + pub use super::component::ComponentStorage; + pub use super::sparse_set::SparseSet; + pub use super::Entity; + pub use super::bundle::ComponentBundle; + pub use super::query::Query; + pub use super::query::QueryMut; +} + +pub type Entity = usize; + +#[macro_export] +macro_rules! ecs { + ($name:ident { + context: $ctx:ty, + components: { + $($comp:ident),* $(,)? + }, + systems: { + $($sys:path),* $(,)? + }$(,)? + }) => { + #[allow(non_snake_case)] + struct $name { + next_entity: Entity, + $($comp: SparseSet<$comp>),* + } + + impl $name { + pub fn new() -> Self { + Self { + next_entity: 0, + $($comp: SparseSet::new()),* + } + } + + pub fn update(&mut self, ctx: &mut $ctx) { + $($sys(self, ctx));* + } + + pub fn insert>(&mut self, entity: Entity, bundle: T) { + bundle.insert(self, entity); + } + + pub fn spawn>(&mut self, bundle:T) -> Entity { + let e = self.next_entity; + self.next_entity += 1; + bundle.insert(self, e); + e + } + + pub fn remove(&mut self, entity: Entity) + where + Self: ComponentStorage, + { + self.storage_mut().remove(entity); + } + + pub fn delete(&mut self, entity: Entity) { + $(self.$comp.remove(entity);)* + } + + pub fn get(&self, entity: Entity) -> Option<&T> + where + Self: ComponentStorage, + { + self.storage().get(entity) + } + + pub fn get_mut(&mut self, entity: Entity) -> Option<&mut T> + where + Self: ComponentStorage, + { + self.storage_mut().get_mut(entity) + } + + } + + impl<'a> $name { + pub fn query>(&'a self) -> impl Iterator { + Q::run(self) + } + + pub fn query_mut>(&'a mut self) + -> impl Iterator { + Q::run_mut(self) + } + } + + $(impl ComponentStorage<$comp> for $name { + fn storage(&self) -> &SparseSet<$comp> { + &self.$comp + } + + fn storage_mut(&mut self) -> &mut SparseSet<$comp> { + &mut self.$comp + } + + fn storage_ptr(&mut self) -> *mut SparseSet<$comp> { + &mut self.$comp + } + })+ + }; +} -- cgit v1.2.3