diff --git a/src/controls.rs b/src/controls.rs index 5f0aed2..2196778 100755 --- a/src/controls.rs +++ b/src/controls.rs @@ -1,3 +1,3 @@ pub struct Controls { - + } \ No newline at end of file diff --git a/src/ecs/mod.rs b/src/ecs/mod.rs index 20cf8f7..f117d71 100755 --- a/src/ecs/mod.rs +++ b/src/ecs/mod.rs @@ -1 +1,57 @@ -pub mod components; \ No newline at end of file +use std::collections::HashMap; + +use async_trait::async_trait; +use hecs::World; +use tracing::warn; + +pub mod components; + +/// A trait that represents a simple system +pub trait SimpleSystem { + // todo: make async? + fn execute_mut(&mut self, world: &mut World) -> anyhow::Result<()>; +} + +pub type SystemFn = dyn Fn(&mut World) -> anyhow::Result<()>; + +pub struct SystemFnExecutor { + systems: HashMap>, +} + +impl SystemFnExecutor { + pub fn new() -> Self { + Self { + systems: HashMap::new(), + } + } + + pub fn with_systems(systems: HashMap>) -> Self { + Self { + systems, + } + } + + pub fn add_system(&mut self, system_label: &str, system: Box) { + self.systems.insert(system_label.to_string(), system); + } + + pub fn remove_system(&mut self, system_label: &str) { + self.systems.remove(&system_label.to_string()); + } +} + +impl SimpleSystem for SystemFnExecutor { + fn execute_mut(&mut self, world: &mut World) -> anyhow::Result<()> { + for system in self.systems.iter() { + let system_fn = system.1.as_ref(); + let res = system_fn(world); + + // log an error returned by the system + if let Err(e) = res { + warn!("System execution of {} resulted in an error! '{}'", system.0, e); + } + } + + Ok(()) + } +} \ No newline at end of file diff --git a/src/game.rs b/src/game.rs index 66291bd..aac1542 100755 --- a/src/game.rs +++ b/src/game.rs @@ -75,6 +75,7 @@ struct GameLoop { renderer: Box, world: Arc>, + system_fn_executor: SystemFnExecutor, fps_counter: TickCounter, } @@ -85,6 +86,7 @@ impl GameLoop { renderer: Box::new(BasicRenderer::create_with_window(window).await), world, + system_fn_executor: SystemFnExecutor::new(), fps_counter: TickCounter::new(), } } @@ -98,10 +100,8 @@ impl GameLoop { } async fn update(&mut self) { - /* let world = self.world.lock().await; - for dispatcher in self.system_dispatchers.iter_mut() { - dispatcher.dispatch(&world); - } */ + let mut world = self.world.lock().await; + self.system_fn_executor.execute_mut(&mut world).unwrap(); // always returns Ok(()) } async fn input_update(&mut self, event: &InputEvent) -> Option {