Skip to main content

fantasy_craft/core/
schedule.rs

1use std::collections::BTreeMap;
2
3use crate::core::context::Context;
4
5pub type SystemFn = fn(&mut Context);
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
8pub enum Stage {
9    StartUp,
10    Update,
11    PostUpdate,
12    Render,
13    PostRender,
14    GuiRender
15}
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
18pub enum GameState {
19    Menu,
20    Playing,
21    Paused,
22    Loading
23}
24
25pub struct System {
26    pub func: SystemFn,
27    pub active_states: Vec<GameState>
28}
29
30impl System {
31    pub fn new(func: SystemFn, active_states: Vec<GameState>) -> Self {
32        Self {
33            func,
34            active_states
35        }
36    }
37
38    pub fn is_active(&self, current_state: GameState) -> bool {
39        self.active_states.contains(&current_state)
40    }
41}
42
43pub struct Schedule {
44    systems: BTreeMap<Stage, Vec<System>>
45}
46
47impl Schedule {
48    pub fn new() -> Self {
49        Self {
50            systems: BTreeMap::new()
51        }
52    }
53
54    pub fn add_system(&mut self, stage: Stage, system: System) {
55        self.systems.entry(stage).or_default().push(system);
56    }
57
58    pub fn run_stage(&self, stage: Stage, ctx: &mut Context) {
59        if let Some(systems) = self.systems.get(&stage) {
60            for system in systems {
61                if system.is_active(ctx.game_state) {
62                    (system.func)(ctx);
63                }
64            }
65        }
66    }
67}