create SimpleSystem

This commit is contained in:
SeanOMik 2023-06-03 13:36:39 -04:00
parent da4297b462
commit 35eb2842fb
3 changed files with 62 additions and 6 deletions

View File

@ -1 +1,57 @@
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>,
world: Arc<Mutex<World>>,
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<ControlFlow> {