create SimpleSystem

This commit is contained in:
SeanOMik 2023-06-03 13:36:39 -04:00
parent f11c175db1
commit 7063f57a7b
Signed by: SeanOMik
GPG Key ID: 568F326C7EB33ACB
3 changed files with 62 additions and 6 deletions

View File

@ -1,3 +1,3 @@
pub struct Controls { pub struct Controls {
} }

View File

@ -1 +1,57 @@
pub mod components; 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<String, Box<SystemFn>>,
}
impl SystemFnExecutor {
pub fn new() -> Self {
Self {
systems: HashMap::new(),
}
}
pub fn with_systems(systems: HashMap<String, Box<SystemFn>>) -> Self {
Self {
systems,
}
}
pub fn add_system(&mut self, system_label: &str, system: Box<SystemFn>) {
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(())
}
}

View File

@ -75,6 +75,7 @@ struct GameLoop {
renderer: Box<dyn Renderer>, renderer: Box<dyn Renderer>,
world: Arc<Mutex<World>>, world: Arc<Mutex<World>>,
system_fn_executor: SystemFnExecutor,
fps_counter: TickCounter, fps_counter: TickCounter,
} }
@ -85,6 +86,7 @@ impl GameLoop {
renderer: Box::new(BasicRenderer::create_with_window(window).await), renderer: Box::new(BasicRenderer::create_with_window(window).await),
world, world,
system_fn_executor: SystemFnExecutor::new(),
fps_counter: TickCounter::new(), fps_counter: TickCounter::new(),
} }
} }
@ -98,10 +100,8 @@ impl GameLoop {
} }
async fn update(&mut self) { async fn update(&mut self) {
/* let world = self.world.lock().await; let mut world = self.world.lock().await;
for dispatcher in self.system_dispatchers.iter_mut() { self.system_fn_executor.execute_mut(&mut world).unwrap(); // always returns Ok(())
dispatcher.dispatch(&world);
} */
} }
async fn input_update(&mut self, event: &InputEvent) -> Option<ControlFlow> { async fn input_update(&mut self, event: &InputEvent) -> Option<ControlFlow> {