Add an interface for `State` to easily define and enforce legal state transitions
- Dominant language
- Rust
- Stars
- 48.2k
- Forks
- 4.8k
- Avg merge
- 3d 16h
- Merged PRs (30d)
- 171
Description
## What problem does this solve or what need does it fill?
Currently, you can define a finite state machine like the following:
```rust
#[derive(States, Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
enum NewFSM {
#[default]
Idle,
Walk,
Walk2Swim,
Swim,
Swim2Walk,
Drowning
}
```
When using this new `State` resource, transitions to all states defined are legal by default.
Below is a simple diagram of our new FSM. (excluding idle):

The arrows in the diagram represent the legal transitions between states. In this example, you would not want to ever transition from the `Walk` state to the `Drowning` state, or vice versa.
Currently, to enforce these transition rules, you have to implement this logic manually at all states' enter/exit systems. This leads to the developer writing more of an "all over the place" solution to enforce these transition rules.
## What solution would you like?
I'm actually still getting my feet wet in Rust, so I do not have a clear solution in mind.
Although, when thinking of a solution, a certain feature from `strum` does come to mind. The following sample shows how you can add custom properties to enum variants using strum:
```rust
use strum::EnumProperty;
#[derive(PartialEq, Eq, Debug, EnumProperty)]
enum Class {
#[strum(props(Teacher="Ms.Frizzle", Room="201"))]
History,
#[strum(props(Teacher="Mr.Smith"))]
#[strum(props(Room="103"))]
Mathematics,
#[strum(props(Time="2:30"))]
Science,
}
```
Possibly could have a similar solution for declaring which enum variant a certain state can transition to. Then, when requesting to transition states, Bevy can enforce these rules by checking if the transition is legal based on the rules defined by the developer.
## What alternative(s) have you considered?
As mentioned above, the current alternative solution is to manually write the necessary logic to enforce transition rules at all states' enter/exit systems.
Contributor guide
Research direction
Start by reading Bevy's State resource and the existing state enter/exit systems described in the issue. Determine how developers currently request transitions and where legal transitions could be declared and checked. Done means a documented interface lets a finite state machine define allowed transitions and prevents illegal state changes.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- game-dev
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100