1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
//! Utilities for game state management.

use asset_manager::AssetManager;
use engine::event::WindowEvent;
use renderer::Pipeline;
use ecs::World;

/// Types of state transitions.
pub enum Trans {
    /// Continue as normal.
    None,
    /// Remove the active state and resume the next state on the stack or stop
    /// if there are none.
    Pop,
    /// Pause the active state and push a new state onto the stack.
    Push(Box<State>),
    /// Remove the current state on the stack and insert a different one.
    Switch(Box<State>),
    /// Stop and remove all states and shut down the engine.
    Quit,
}

/// A trait which defines game states that can be used by the state machine.
pub trait State {
    /// Executed when the game state begins.
    fn on_start(&mut self, _world: &mut World, _assets: &mut AssetManager, _pipe: &mut Pipeline) {}

    /// Executed when the game state exits.
    fn on_stop(&mut self, _world: &mut World, _assets: &mut AssetManager, _pipe: &mut Pipeline) {}

    /// Executed when a different game state is pushed onto the stack.
    fn on_pause(&mut self, _world: &mut World, _assets: &mut AssetManager, _pipe: &mut Pipeline) {}

    /// Executed when the application returns to this game state once again.
    fn on_resume(&mut self, _world: &mut World, _assets: &mut AssetManager, _pipe: &mut Pipeline) {}

    /// Executed on every frame before updating, for use in reacting to events.
    fn handle_events(&mut self,
                     _events: &[WindowEvent],
                     _world: &mut World,
                     _assets: &mut AssetManager,
                     _pipe: &mut Pipeline)
                     -> Trans {
        Trans::None
    }

    /// Executed repeatedly at stable, predictable intervals (1/60th of a second
    /// by default).
    fn fixed_update(&mut self,
                    _world: &mut World,
                    _assets: &mut AssetManager,
                    _pipe: &mut Pipeline)
                    -> Trans {
        Trans::None
    }

    /// Executed on every frame immediately, as fast as the engine will allow.
    fn update(&mut self,
              _world: &mut World,
              _assets: &mut AssetManager,
              _pipe: &mut Pipeline)
              -> Trans {
        Trans::None
    }
}

/// A simple stack-based state machine (pushdown automaton).
pub struct StateMachine {
    running: bool,
    state_stack: Vec<Box<State>>,
}

impl StateMachine {
    /// Creates a new state machine with the given initial state.
    pub fn new<T>(initial_state: T) -> StateMachine
        where T: State + 'static
    {
        StateMachine {
            running: false,
            state_stack: vec![Box::new(initial_state)],
        }
    }

    /// Checks whether the state machine is running.
    pub fn is_running(&self) -> bool {
        self.running
    }

    /// Initializes the state machine.
    ///
    /// # Panics
    /// Panics if no states are present in the stack.
    pub fn start(&mut self, world: &mut World, assets: &mut AssetManager, pipe: &mut Pipeline) {
        if !self.running {
            let state = self.state_stack.last_mut().unwrap();
            state.on_start(world, assets, pipe);
            self.running = true;
        }
    }

    /// Passes a vector of events to the active state to handle.
    pub fn handle_events(&mut self,
                         events: &[WindowEvent],
                         world: &mut World,
                         assets: &mut AssetManager,
                         pipe: &mut Pipeline) {
        if self.running {
            let trans = match self.state_stack.last_mut() {
                Some(state) => state.handle_events(events, world, assets, pipe),
                None => Trans::None,
            };

            self.transition(trans, world, assets, pipe);
        }
    }

    /// Updates the currently active state at a steady, fixed interval.
    pub fn fixed_update(&mut self,
                        world: &mut World,
                        assets: &mut AssetManager,
                        pipe: &mut Pipeline) {
        if self.running {
            let trans = match self.state_stack.last_mut() {
                Some(state) => state.fixed_update(world, assets, pipe),
                None => Trans::None,
            };

            self.transition(trans, world, assets, pipe);
        }
    }

    /// Updates the currently active state immediately.
    pub fn update(&mut self, world: &mut World, assets: &mut AssetManager, pipe: &mut Pipeline) {
        if self.running {
            let trans = match self.state_stack.last_mut() {
                Some(state) => state.update(world, assets, pipe),
                None => Trans::None,
            };

            self.transition(trans, world, assets, pipe);
        }
    }

    /// Performs a state transition, if requested by either update() or
    /// fixed_update().
    fn transition(&mut self,
                  request: Trans,
                  world: &mut World,
                  assets: &mut AssetManager,
                  pipe: &mut Pipeline) {
        if self.running {
            match request {
                Trans::None => (),
                Trans::Pop => self.pop(world, assets, pipe),
                Trans::Push(state) => self.push(state, world, assets, pipe),
                Trans::Switch(state) => self.switch(state, world, assets, pipe),
                Trans::Quit => self.stop(world, assets, pipe),
            }
        }
    }

    /// Removes the current state on the stack and inserts a different one.
    fn switch(&mut self,
              state: Box<State>,
              world: &mut World,
              assets: &mut AssetManager,
              pipe: &mut Pipeline) {
        if self.running {
            if let Some(mut state) = self.state_stack.pop() {
                state.on_stop(world, assets, pipe);
            }

            self.state_stack.push(state);
            let state = self.state_stack.last_mut().unwrap();
            state.on_start(world, assets, pipe);
        }
    }

    /// Pauses the active state and pushes a new state onto the state stack.
    fn push(&mut self,
            state: Box<State>,
            world: &mut World,
            assets: &mut AssetManager,
            pipe: &mut Pipeline) {
        if self.running {
            if let Some(state) = self.state_stack.last_mut() {
                state.on_pause(world, assets, pipe);
            }

            self.state_stack.push(state);
            let state = self.state_stack.last_mut().unwrap();
            state.on_start(world, assets, pipe);
        }
    }

    /// Stops and removes the active state and un-pauses the next state on the
    /// stack (if any).
    fn pop(&mut self, world: &mut World, assets: &mut AssetManager, pipe: &mut Pipeline) {
        if self.running {
            if let Some(mut state) = self.state_stack.pop() {
                state.on_stop(world, assets, pipe);
            }

            if let Some(mut state) = self.state_stack.last_mut() {
                state.on_resume(world, assets, pipe);
            } else {
                self.running = false;
            }
        }
    }

    /// Shuts the state machine down.
    fn stop(&mut self, world: &mut World, assets: &mut AssetManager, pipe: &mut Pipeline) {
        if self.running {
            while let Some(mut state) = self.state_stack.pop() {
                state.on_stop(world, assets, pipe);
            }

            self.running = false;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    struct State1(u8);
    struct State2;

    impl State for State1 {
        fn update(&mut self, _: &mut World, _: &mut AssetManager, _: &mut Pipeline) -> Trans {
            if self.0 > 0 {
                self.0 -= 1;
                Trans::None
            } else {
                Trans::Switch(Box::new(State2))
            }
        }
    }

    impl State for State2 {
        fn update(&mut self, _: &mut World, _: &mut AssetManager, _: &mut Pipeline) -> Trans {
            Trans::Pop
        }
    }

    #[test]
    fn switch_pop() {
        let mut assets = AssetManager::new();
        let mut pipe = Pipeline::new();
        let mut world = World::new();

        let mut sm = StateMachine::new(State1(7));
        sm.start(&mut world, &mut assets, &mut pipe);

        for _ in 0..8 {
            sm.update(&mut world, &mut assets, &mut pipe);
            assert!(sm.is_running());
        }

        sm.update(&mut world, &mut assets, &mut pipe);
        assert!(!sm.is_running());
    }
}