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
//! State of a state machine and Hierarchical state machine.
//!
//! You want to use a [`NestedMachine`] to manage an individual
//! instance of a hierarchical finite state machine (HFSM), the
//! [`NestedMachine::update`] method does all the magic of managing the
//! state machine

use crate::{Behavior, Error, SHandle, SmHandle, StateData, Target, Transition};

#[derive(Debug)]
pub enum Complete {
    Done,
    Running,
}

/// Data for individual state
struct State {
    handle: SHandle,
    behavior: StateData,
    transitions: Option<Vec<StateData>>,
}
impl State {
    fn new(handle: SHandle) -> Self {
        State {
            handle,
            behavior: Box::new(()),
            transitions: None,
        }
    }
    fn update<'w, 's, 'ww, 'ss, B, Trs, Wrd, Updt>(
        &mut self,
        state: &crate::State<B, Trs>,
        commands: &mut Updt,
        world: &Wrd,
    ) -> Target
    where
        B: Behavior<Update<'w, 's> = Updt, World<'ww, 'ss> = Wrd>,
        Trs: Transition<World<'ww, 'ss> = Wrd>,
    {
        state.behavior.update(&mut self.behavior, commands, world);
        if self.transitions.is_none() {
            let mut transitions: Vec<StateData> = Vec::with_capacity(state.transitions.len());
            for _ in state.transitions.iter() {
                transitions.push(Box::new(()));
            }
            self.transitions = Some(transitions);
        }
        let trans_data = &mut self.transitions.iter_mut().flatten();
        for (transition, data) in state.transitions.iter().zip(trans_data) {
            let target = transition.decide(data, world);
            if !matches!(target, Target::Continue) {
                return target;
            }
        }
        Target::Continue
    }
}

/// Data for individual machines
struct Machine {
    handle: SmHandle,
    state: State,
}
impl Machine {
    fn new(handle: SmHandle) -> Self {
        Machine {
            handle,
            state: State::new(SHandle::INITIAL),
        }
    }

    fn update<'w, 's, 'ww, 'ss, B, Trs, Wrd, Updt>(
        &mut self,
        machine: &crate::StateMachine<B, Trs>,
        commands: &mut Updt,
        world: &Wrd,
    ) -> Result<Target, Error>
    where
        B: Behavior<Update<'w, 's> = Updt, World<'ww, 'ss> = Wrd> + 'static,
        Trs: Transition<World<'ww, 'ss> = Wrd> + 'static,
    {
        let state = machine
            .state(&self.state.handle)
            .ok_or(Error::BadStateName)?;
        let target = self.state.update(state, commands, world);
        if let Target::Goto(ref new_state_handle) = target {
            self.state = State::new(new_state_handle.clone());
        };
        Ok(target)
    }
}

/// The managed state of a Hierarchical Finite State Machine (HFSM)
///
/// This contains the state pointers of innactive state machines that entered a
/// nested machine, and the state `Data` of those machines.
pub struct NestedMachine {
    stack: Vec<Machine>,
}
impl Default for NestedMachine {
    fn default() -> Self {
        Self::new()
    }
}
impl NestedMachine {
    /// Initialize a `NestedMachine` without any active state
    pub fn new() -> Self {
        NestedMachine {
            stack: Vec::with_capacity(1),
        }
    }
    /// Initialize a `NestedMachine` with the first `State` of the first
    /// `Machine` activated.
    pub fn new_active() -> Self {
        let stack = vec![Machine::new(SmHandle(0))];
        NestedMachine { stack }
    }
    /// Enter the nested state described by [`SmHandle`]
    pub fn enter(&mut self, machine: &SmHandle) {
        self.stack.push(Machine::new(machine.clone()));
    }
    pub fn stack_len(&self) -> usize {
        self.stack.len()
    }
    pub fn current_state_name<'a, B, T>(
        &self,
        machines: &'a crate::StateMachines<B, T>,
    ) -> Option<&'a str> {
        let machine = self.stack.last()?;
        machines.state_name(&machine.handle, &machine.state.handle)
    }

    pub fn current_machine_name<'a, B, T>(
        &self,
        machines: &'a crate::StateMachines<B, T>,
    ) -> Option<&'a str> {
        let machine = self.stack.last()?;
        machines.machine_name(&machine.handle)
    }

    pub fn update<'w, 's, 'ww, 'ss, B, Trs, Wrd, Updt>(
        &mut self,
        machines: &crate::StateMachines<B, Trs>,
        commands: &mut Updt,
        world: &Wrd,
    ) -> Result<Complete, Error>
    where
        B: Behavior<Update<'w, 's> = Updt, World<'ww, 'ss> = Wrd> + 'static,
        Trs: Transition<World<'ww, 'ss> = Wrd> + 'static,
    {
        use Complete::{Done, Running};

        let current = self.stack.last_mut().ok_or(Error::EmptyStack)?;
        let machine = machines
            .machine(&current.handle)
            .ok_or(Error::BadMachineName)?;
        let target = current.update(machine, commands, world)?;
        match target {
            Target::Enter(nested_machine) => {
                self.enter(&nested_machine);
                Ok(Running)
            }
            Target::Complete => {
                self.stack.pop();
                let empty = self.stack.is_empty();
                Ok(if empty { Done } else { Running })
            }
            Target::Continue | Target::Goto(_) => Ok(Running),
        }
    }
}