# base/fsm (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/base/fsm/

Finite state machine. (FiniteStateMachine of the original base/fsm.js)
- Standardizes the "string state + switch statement + manual transitions" that many games each built on their own.
- Register enter / tick / exit handling for each state and transition with change_state().
- set_transition_guard() can block disallowed transitions.
- The original's state names are strings. The Rust version lets you pick the state name type. (String by default; enums or &'static str also work)
  The original's null state (no state yet) is None.
- The original handlers object { enter?, tick?, exit? } is the StateHandlers struct. Callbacks are `Box<dyn FnMut>`, so
  to change game state, capture `Rc<Cell>` / `Rc<RefCell>`.
- The original calls the same machine's change_state right there inside a handler. In the Rust version a handler cannot borrow the machine, so
  capture the handle (StateChangeRequester) received from get_state_change_requester in the handler and request through its change_state.
  The machine transitions in request order after that handler ends. (the same as the original calling change_state at the very end of a handler)
  Whether the request succeeds is not returned right there. A request made outside a handler transitions on the next tick or change_state.

## StateEnterHandler (type)

Called when entering the state. (previous state name, None the first time)

```rust
pub type StateEnterHandler<StateName> = Box<dyn FnMut(Option<&StateName>)>
```

## StateTickHandler (type)

Called on every tick while staying in the state. (time_delta, seconds spent in this state)

```rust
pub type StateTickHandler = Box<dyn FnMut(f64, f64)>
```

## StateExitHandler (type)

Called when leaving the state. (next state name)

```rust
pub type StateExitHandler<StateName> = Box<dyn FnMut(&StateName)>
```

## TransitionGuard (type)

Transition guard. (previous state name, next state name) → whether allowed

```rust
pub type TransitionGuard<StateName> = Box<dyn FnMut(Option<&StateName>, &StateName) -> bool>
```

## TransitionEvent (type)

Transition notification. (previous state name, next state name) Called after exit and before enter.

```rust
pub type TransitionEvent<StateName> = Box<dyn FnMut(Option<&StateName>, &StateName)>
```

## StateHandlers (struct) (Default)

State handler set. (the original addState's handlers: { enter?, tick?, exit? })

Example: Only a tick handler, the rest default

```rust
use std::cell::Cell;
use std::rc::Rc;
use vanilla::{FiniteStateMachine, StateHandlers};

let total_seconds = Rc::new(Cell::new(0.0f64));
let total_seconds_in_tick = total_seconds.clone();
let mut state_machine: FiniteStateMachine<&'static str> = FiniteStateMachine::new();
state_machine.add_state("play", StateHandlers {
	tick: Some(Box::new(move |time_delta: f64, _state_seconds: f64| {
		total_seconds_in_tick.set(total_seconds_in_tick.get() + time_delta);
	})),
	..StateHandlers::default()
});
state_machine.change_state("play", false);
state_machine.tick(0.25);
state_machine.tick(0.25);
assert_eq!(total_seconds.get(), 0.5);
```

- `pub enter: Option<StateEnterHandler<StateName>>` (field, since 0.3.2): Function called when entering the state. (takes the previous state name, None the first time) Not called if None.
  - returns Option<StateEnterHandler<StateName>>
- `pub tick: Option<StateTickHandler>` (field, since 0.3.2): Function called on every tick while staying in the state. (time_delta seconds, seconds spent in this state) Not called if None.
  - returns Option<StateTickHandler>
- `pub exit: Option<StateExitHandler<StateName>>` (field, since 0.3.2): Function called when leaving the state. (takes the next state name) Not called if None.
  - returns Option<StateExitHandler<StateName>>

## StateChangeRequester (struct) (Clone)

Handle for requesting transitions inside a handler. (given by FiniteStateMachine::get_state_change_requester; clone it and capture it in handlers)

Example: Request the next state from the tick handler after staying 1 second

```rust
use vanilla::{FiniteStateMachine, StateHandlers};

let mut state_machine: FiniteStateMachine<&'static str> = FiniteStateMachine::new();
let state_change_requester = state_machine.get_state_change_requester();
state_machine.add_state("countdown", StateHandlers {
	tick: Some(Box::new(move |_time_delta: f64, state_seconds: f64| {
		if state_seconds >= 1.0 {
			state_change_requester.change_state("play", false);
		}
	})),
	..StateHandlers::default()
});
state_machine.add_state("play", StateHandlers::default());
state_machine.change_state("countdown", false);
state_machine.tick(0.5);
assert_eq!(state_machine.get_state_name(), Some(&"countdown"));
state_machine.tick(0.5);
assert_eq!(state_machine.get_state_name(), Some(&"play"));
```

- `pub fn change_state(&self, next_state_name: StateName, is_forced: bool)` (method, since 0.4.0): Requests a state transition. (change_state inside an original handler; the machine transitions in order after the current handler ends)
  - `next_state_name` StateName: Name of the state to move to. (the machine does not transition for an unregistered name)
  - `is_forced` bool: If true, transitions again even to the same state. (the transition guard is still checked)

## FiniteStateMachine (struct) (Default)

Finite state machine.

Example: Register enum states, update and transition

```rust
use std::cell::RefCell;
use std::rc::Rc;
use vanilla::{FiniteStateMachine, StateHandlers};

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum PlayerState {
	Idle,
	Run,
}

let record_list = Rc::new(RefCell::new(Vec::<String>::new()));
let enter_record_list = record_list.clone();
let exit_record_list = record_list.clone();
let mut state_machine = FiniteStateMachine::<PlayerState>::new();
state_machine.add_state(PlayerState::Idle, StateHandlers {
	exit: Some(Box::new(move |next_state_name: &PlayerState| {
		exit_record_list.borrow_mut().push(format!("idle exit to {:?}", next_state_name));
	})),
	..StateHandlers::default()
});
state_machine.add_state(PlayerState::Run, StateHandlers {
	enter: Some(Box::new(move |previous_state_name: Option<&PlayerState>| {
		enter_record_list.borrow_mut().push(format!("run enter from {:?}", previous_state_name));
	})),
	..StateHandlers::default()
});
assert_eq!(state_machine.get_state_name(), None);
assert!(state_machine.change_state(PlayerState::Idle, false));
state_machine.tick(0.5);
assert_eq!(state_machine.get_state_seconds(), 0.5);
assert!(state_machine.change_state(PlayerState::Run, false));
assert_eq!(state_machine.get_state_name(), Some(&PlayerState::Run));
assert_eq!(state_machine.get_state_seconds(), 0.0);
assert_eq!(*record_list.borrow(), vec!["idle exit to Run", "run enter from Some(Idle)"]);
```

- `pub fn new() -> FiniteStateMachine<StateName>` (constructor, since 0.3.2): Constructor. (no registered states, no current state)
  - returns FiniteStateMachine<StateName>: An empty state machine. (current state None, time spent 0, no guard or transition notification)
- `pub fn get_state_change_requester(&self) -> StateChangeRequester<StateName>` (method, since 0.4.0): Handle for requesting transitions inside a handler. (clone it and capture it in handlers)
  - returns StateChangeRequester<StateName>: Handle sharing this machine's request list. (points to the same machine however many times it is taken)

  Example: A request made outside a handler transitions on the next tick

  ```rust
  use vanilla::{FiniteStateMachine, StateHandlers};
  
  let mut state_machine: FiniteStateMachine<&'static str> = FiniteStateMachine::new();
  state_machine.add_state("title", StateHandlers::default());
  state_machine.add_state("play", StateHandlers::default());
  state_machine.change_state("title", false);
  let state_change_requester = state_machine.get_state_change_requester();
  state_change_requester.change_state("play", false);
  assert_eq!(state_machine.get_state_name(), Some(&"title"));
  state_machine.tick(0.0);
  assert_eq!(state_machine.get_state_name(), Some(&"play"));
  ```

- `pub fn add_state(&mut self, state_name: StateName, handlers: StateHandlers<StateName>)` (method, since 0.3.2): Registers a state. (replaces the handlers if the same name exists)
  - `state_name` StateName: State name.
  - `handlers` StateHandlers<StateName>: Handler set of that state. (all may be None, StateHandlers::default())
- `pub fn change_state(&mut self, next_state_name: StateName, is_forced: bool) -> bool` (method, since 0.3.2): State transition. (returns whether the transition succeeded)
  - Does not go to an unregistered state.
  - Transitions to the same state are ignored by default. (if is_forced is true, exit / enter are called again)
  - Does not transition if the transition guard returns false.
  - Order: previous state exit → change state and reset time spent to 0 → transition notification → next state enter.
  - Transitions requested by handlers in the meantime happen in order after this transition ends.
  - `next_state_name` StateName: Name of the state to move to.
  - `is_forced` bool: If true, transitions again even to the same state. (the transition guard is still checked)
  - returns bool: true if this transition happened. false for an unregistered state, the same state (is_forced false), or when the guard blocked it. (does not include whether the requested transitions that followed succeeded)

  Example: Missing state, same state, forced transition

  ```rust
  use vanilla::{FiniteStateMachine, StateHandlers};
  
  let mut state_machine: FiniteStateMachine<&'static str> = FiniteStateMachine::new();
  state_machine.add_state("idle", StateHandlers::default());
  assert!(!state_machine.change_state("missing", false));
  assert!(state_machine.change_state("idle", false));
  assert!(!state_machine.change_state("idle", false));
  assert!(state_machine.change_state("idle", true));
  ```

- `pub fn tick(&mut self, time_delta: f64)` (method, since 0.3.2): Update. (performs requested transitions first, increases the time spent and calls the current state's tick. Transitions requested by tick happen after that)
  - `time_delta` f64: Interval since the last frame. (seconds, added to the time spent and passed to the current state's tick. Not added if there is no current state)
- `pub fn get_state_name(&self) -> Option<&StateName>` (method, since 0.3.2): Returns the current state name. (None if not in any state yet)
  - returns Option<&StateName>: Current state name. (None if no transition has happened yet)
- `pub fn get_state_seconds(&self) -> f64` (method, since 0.3.2): Returns the time spent in the current state. (seconds)
  - returns f64: Time spent. (seconds, reset to 0 on transition)
- `pub fn has_state(&self, state_name: &StateName) -> bool` (method, since 0.3.2): Whether the state exists.
  - `state_name` &StateName: State name to find.
  - returns bool: true if the state is registered.
- `pub fn set_transition_guard(&mut self, transition_guard: Option<TransitionGuard<StateName>>)` (method, since 0.3.2): Sets the transition guard. (previous, next) → bool, no guard if None
  - `transition_guard` Option<TransitionGuard<StateName>>: Function that takes (previous state name, next state name) and returns whether it is allowed. (does not transition if false, also blocks is_forced transitions) No guard if None.

  Example: Block transitions after death

  ```rust
  use vanilla::{FiniteStateMachine, StateHandlers};
  
  #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
  enum PlayerState {
  	Idle,
  	Dead,
  }
  
  let mut state_machine = FiniteStateMachine::<PlayerState>::new();
  state_machine.add_state(PlayerState::Idle, StateHandlers::default());
  state_machine.add_state(PlayerState::Dead, StateHandlers::default());
  state_machine.set_transition_guard(Some(Box::new(|previous_state_name: Option<&PlayerState>, _next_state_name: &PlayerState| {
  	previous_state_name != Some(&PlayerState::Dead)
  })));
  assert!(state_machine.change_state(PlayerState::Dead, false));
  assert!(!state_machine.change_state(PlayerState::Idle, true));
  state_machine.set_transition_guard(None);
  assert!(state_machine.change_state(PlayerState::Idle, false));
  ```

- `pub fn set_transition_event(&mut self, transition_event: Option<TransitionEvent<StateName>>)` (method, since 0.3.2): Sets the transition notification. (previous, next), called after exit and before enter. No notification if None
  - `transition_event` Option<TransitionEvent<StateName>>: Function that takes (previous state name, next state name). (None if there is no previous state) Not called if None.

  Example: Record transitions with string state names (default type String)

  ```rust
  use std::cell::RefCell;
  use std::rc::Rc;
  use vanilla::{FiniteStateMachine, StateHandlers};
  
  let transition_list = Rc::new(RefCell::new(Vec::<String>::new()));
  let transition_list_in_event = transition_list.clone();
  let mut state_machine: FiniteStateMachine = FiniteStateMachine::new();
  state_machine.add_state(String::from("title"), StateHandlers::default());
  state_machine.add_state(String::from("play"), StateHandlers::default());
  state_machine.set_transition_event(Some(Box::new(move |previous_state_name: Option<&String>, next_state_name: &String| {
  	transition_list_in_event.borrow_mut().push(format!("{:?} -> {}", previous_state_name, next_state_name));
  })));
  state_machine.change_state(String::from("title"), false);
  state_machine.change_state(String::from("play"), false);
  assert_eq!(*transition_list.borrow(), vec!["None -> title", "Some(\"title\") -> play"]);
  ```

