Skip to main content

repame_sim/
state.rs

1//! Typed game states with enter/exit/transition schedules.
2//!
3//! A state set is any small value type (usually an enum) that is `Eq + Hash`;
4//! one `State<S>` resource holds the current value and one `NextState<S>`
5//! holds a pending change. Requesting a transition from any system is a write
6//! to `NextState<S>`; the sim applies it once per fixed step, *before* the
7//! step's main schedule, so a transition never interleaves with gameplay.
8//!
9//! Apply order for `A -> B` matches the reference (bevy_state):
10//!
11//! 1. `OnExit(A)`   - the `State<S>` resource still reads `A`
12//! 2. `State<S> = B`
13//! 3. `OnTransition { exited: A, entered: B }`
14//! 4. `OnEnter(B)`
15//!
16//! If an enter/exit system requests another transition, it is resolved on the
17//! same step, up to [`MAX_CHAIN`] links; beyond that the chain is dropped and
18//! the last state stands. That bound stops a self-triggering transition from
19//! spinning the step forever.
20//!
21//! Determinism: transitions run inside the fixed step and in registration
22//! order, so a replay that requests the same transitions at the same ticks
23//! resolves them identically. Do not request transitions from a thread.
24
25use std::collections::HashMap;
26use std::hash::Hash;
27
28use bevy_ecs::prelude::*;
29use bevy_ecs::schedule::{IntoScheduleConfigs, Schedule};
30use bevy_ecs::system::ScheduleSystem;
31
32/// A state set: a plain value used as a game state.
33///
34/// Usually a fieldless enum. The blanket impl covers any `Clone + Eq + Hash`
35/// value type with no `'static` borrows.
36pub trait States: Clone + Eq + Hash + Send + Sync + 'static {}
37
38impl<T> States for T where T: Clone + Eq + Hash + Send + Sync + 'static {}
39
40/// The current value of a state set.
41#[derive(Resource)]
42pub struct State<S: States>(S);
43
44impl<S: States> State<S> {
45    pub fn new(value: S) -> Self {
46        Self(value)
47    }
48
49    pub fn get(&self) -> &S {
50        &self.0
51    }
52}
53
54/// A pending transition. Writing here requests a change; the sim applies it
55/// before the next step's main schedule.
56#[derive(Resource)]
57pub struct NextState<S: States>(Option<S>);
58
59impl<S: States> NextState<S> {
60    pub fn new() -> Self {
61        Self(None)
62    }
63
64    /// Request a transition. A request equal to the current state is ignored.
65    pub fn set(&mut self, next: S) {
66        self.0 = Some(next);
67    }
68
69    /// The pending request, if any.
70    pub fn pending(&self) -> Option<&S> {
71        self.0.as_ref()
72    }
73
74    fn take(&mut self) -> Option<S> {
75        self.0.take()
76    }
77}
78
79impl<S: States> Default for NextState<S> {
80    fn default() -> Self {
81        Self(None)
82    }
83}
84
85/// Transition schedules, keyed by the state they fire for.
86#[derive(Resource)]
87pub(crate) struct StateSchedules<S: States> {
88    on_enter: HashMap<S, Schedule>,
89    on_exit: HashMap<S, Schedule>,
90    on_transition: HashMap<(S, S), Schedule>,
91}
92
93impl<S: States> Default for StateSchedules<S> {
94    fn default() -> Self {
95        Self {
96            on_enter: HashMap::new(),
97            on_exit: HashMap::new(),
98            on_transition: HashMap::new(),
99        }
100    }
101}
102
103/// Most transition links a single step resolves before giving up.
104pub const MAX_CHAIN: u32 = 8;
105
106/// Applies pending transitions. Registered once per state set; runs at the
107/// head of each fixed step.
108pub(crate) fn apply<S: States>(world: &mut World) {
109    for _ in 0..MAX_CHAIN {
110        let Some(next) = world.resource_mut::<NextState<S>>().take() else {
111            break;
112        };
113        let current = world.resource::<State<S>>().get().clone();
114        if next == current {
115            continue;
116        }
117        world.resource_scope(|world, mut schedules: Mut<StateSchedules<S>>| {
118            if let Some(schedule) = schedules.on_exit.get_mut(&current) {
119                schedule.run(world);
120            }
121            world.resource_mut::<State<S>>().0 = next.clone();
122            if let Some(schedule) = schedules.on_transition.get_mut(&(current, next.clone())) {
123                schedule.run(world);
124            }
125            if let Some(schedule) = schedules.on_enter.get_mut(&next) {
126                schedule.run(world);
127            }
128        });
129    }
130}
131
132/// Run condition: only run the configured systems while the state is `state`.
133///
134/// ```ignore
135/// sim.add_chained_systems(update_walk.run_if(in_state(Mode::Walk)));
136/// ```
137pub fn in_state<S: States>(
138    state: S,
139) -> impl FnMut(Res<State<S>>) -> bool + Clone + Send + Sync + 'static {
140    move |current: Res<State<S>>| current.get() == &state
141}
142
143pub(crate) fn init_schedules<S: States>(world: &mut World) {
144    world.insert_resource(StateSchedules::<S>::default());
145}
146
147pub(crate) fn add_enter<S, M>(
148    world: &mut World,
149    state: S,
150    systems: impl IntoScheduleConfigs<ScheduleSystem, M>,
151) where
152    S: States,
153{
154    world
155        .resource_mut::<StateSchedules<S>>()
156        .on_enter
157        .entry(state)
158        .or_default()
159        .add_systems(systems);
160}
161
162pub(crate) fn add_exit<S, M>(
163    world: &mut World,
164    state: S,
165    systems: impl IntoScheduleConfigs<ScheduleSystem, M>,
166) where
167    S: States,
168{
169    world
170        .resource_mut::<StateSchedules<S>>()
171        .on_exit
172        .entry(state)
173        .or_default()
174        .add_systems(systems);
175}
176
177pub(crate) fn add_transition<S, M>(
178    world: &mut World,
179    exited: S,
180    entered: S,
181    systems: impl IntoScheduleConfigs<ScheduleSystem, M>,
182) where
183    S: States,
184{
185    world
186        .resource_mut::<StateSchedules<S>>()
187        .on_transition
188        .entry((exited, entered))
189        .or_default()
190        .add_systems(systems);
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196
197    #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
198    enum Mode {
199        Menu,
200        Play,
201        Paused,
202    }
203
204    #[test]
205    fn transition_runs_exit_then_enter_in_order() {
206        use std::sync::{Arc, Mutex};
207
208        let log: Arc<Mutex<Vec<&'static str>>> = Arc::new(Mutex::new(Vec::new()));
209        let mut sim = crate::Sim::with_default_step();
210        sim.add_state(Mode::Menu);
211
212        let (a, b, c) = (log.clone(), log.clone(), log.clone());
213        sim.on_exit(Mode::Menu, move || a.lock().unwrap().push("exit:menu"));
214        sim.on_enter(Mode::Play, move || b.lock().unwrap().push("enter:play"));
215        sim.on_transition(Mode::Menu, Mode::Play, move || {
216            c.lock().unwrap().push("transition:menu->play")
217        });
218
219        sim.set_state(Mode::Play);
220        sim.tick();
221        assert_eq!(
222            *log.lock().unwrap(),
223            ["exit:menu", "transition:menu->play", "enter:play"]
224        );
225        assert_eq!(*sim.world.resource::<State<Mode>>().get(), Mode::Play);
226    }
227
228    #[test]
229    fn exit_sees_old_state_and_enter_sees_new_state() {
230        use std::sync::{Arc, Mutex};
231
232        let seen: Arc<Mutex<Vec<Mode>>> = Arc::new(Mutex::new(Vec::new()));
233        let mut sim = crate::Sim::with_default_step();
234        sim.add_state(Mode::Menu);
235
236        let e = seen.clone();
237        sim.on_exit(Mode::Menu, move |s: Res<State<Mode>>| {
238            e.lock().unwrap().push(*s.get())
239        });
240        let n = seen.clone();
241        sim.on_enter(Mode::Play, move |s: Res<State<Mode>>| {
242            n.lock().unwrap().push(*s.get())
243        });
244
245        sim.set_state(Mode::Play);
246        sim.tick();
247        assert_eq!(*seen.lock().unwrap(), [Mode::Menu, Mode::Play]);
248    }
249
250    #[test]
251    fn a_transition_requested_on_enter_chains_on_the_same_step() {
252        let mut sim = crate::Sim::with_default_step();
253        sim.add_state(Mode::Menu);
254        sim.on_enter(Mode::Play, |mut next: ResMut<NextState<Mode>>| {
255            next.set(Mode::Paused)
256        });
257        sim.set_state(Mode::Play);
258        sim.tick();
259        assert_eq!(*sim.world.resource::<State<Mode>>().get(), Mode::Paused);
260    }
261
262    #[test]
263    fn self_triggering_transition_is_bounded() {
264        let mut sim = crate::Sim::with_default_step();
265        sim.add_state(Mode::Menu);
266        sim.on_enter(Mode::Play, |mut next: ResMut<NextState<Mode>>| {
267            next.set(Mode::Play)
268        });
269        sim.set_state(Mode::Play);
270        sim.tick();
271        assert_eq!(*sim.world.resource::<State<Mode>>().get(), Mode::Play);
272        assert!(sim.world.resource::<NextState<Mode>>().pending().is_none());
273    }
274
275    #[test]
276    fn set_to_current_state_runs_no_schedules() {
277        use std::sync::{Arc, Mutex};
278        let fired = Arc::new(Mutex::new(false));
279        let mut sim = crate::Sim::with_default_step();
280        sim.add_state(Mode::Menu);
281        let f = fired.clone();
282        sim.on_enter(Mode::Menu, move || *f.lock().unwrap() = true);
283        sim.set_state(Mode::Menu);
284        sim.tick();
285        assert!(!*fired.lock().unwrap());
286    }
287
288    #[test]
289    fn in_state_condition_gates_systems() {
290        use std::sync::atomic::{AtomicU32, Ordering};
291        static HITS: AtomicU32 = AtomicU32::new(0);
292
293        let mut sim = crate::Sim::with_default_step();
294        sim.add_state(Mode::Menu);
295        sim.add_chained_systems(
296            (|| {
297                HITS.fetch_add(1, Ordering::SeqCst);
298            })
299            .run_if(in_state(Mode::Menu)),
300        );
301        sim.tick();
302        assert_eq!(HITS.load(Ordering::SeqCst), 1);
303        sim.set_state(Mode::Play);
304        sim.tick();
305        assert_eq!(HITS.load(Ordering::SeqCst), 1, "gated out after switching");
306    }
307}