From fb5f61beace6b8d89041605447ddc002ad0bdbe2 Mon Sep 17 00:00:00 2001 From: CoderGamester Date: Wed, 5 Aug 2026 01:27:19 +0100 Subject: [PATCH 01/17] ci: update release-preflight check --- .github/workflows/release-preflight.yml | 55 +++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 4 deletions(-) diff --git a/.github/workflows/release-preflight.yml b/.github/workflows/release-preflight.yml index 005ac2f..fb96068 100644 --- a/.github/workflows/release-preflight.yml +++ b/.github/workflows/release-preflight.yml @@ -35,6 +35,7 @@ name: release-preflight on: pull_request: branches: [master] + types: [opened, synchronize, reopened, closed] permissions: contents: read @@ -45,6 +46,7 @@ concurrency: jobs: preflight: + if: github.event.action != 'closed' runs-on: ubuntu-latest steps: # `lfs: true` is load-bearing, not a nicety. The default (false) leaves every @@ -53,7 +55,7 @@ jobs: # FETCHABLE from the remote — the exact failure that hit uiservice, where the # working tree held stubs while the published 1.2.1 had real content. - name: Check out the package - uses: actions/checkout@v4 + uses: actions/checkout@v7 with: fetch-depth: 0 lfs: true @@ -65,16 +67,22 @@ jobs: # yet — omitting it fails with "No such file or directory". Retarget this to # master once the skill is merged there. - name: Check out the release tooling - uses: actions/checkout@v4 + uses: actions/checkout@v7 with: repository: CoderGamester/Frameworks - ref: develop + # Immutable tooling snapshot. Update intentionally through + # `release.py install-preflight`, never by following a moving branch. + ref: be8c1474ae2ab772fae76a29f07bd520abc3b3ac path: .release-tooling sparse-checkout: .claude/skills/unity-package-release/scripts persist-credentials: false + - name: Assert the release tooling checkout + run: | + test -f .release-tooling/.claude/skills/unity-package-release/scripts/release.py + - name: Set up Python - uses: actions/setup-python@v5 + uses: actions/setup-python@v7 with: python-version: "3.12" @@ -82,3 +90,42 @@ jobs: run: | python3 .release-tooling/.claude/skills/unity-package-release/scripts/release.py \ preflight-pr --path . --base "origin/${{ github.base_ref }}" + + # GITHUB_TOKEN cannot dispatch into another repository. Add a fine-grained + # FRAMEWORKS_DISPATCH_TOKEN secret (Contents: read/write on Frameworks) to each + # package repository to activate this hand-off. A missing token is reported as + # a warning rather than turning an already-merged release PR red. + notify-release: + if: github.event.action == 'closed' && github.event.pull_request.merged == true + runs-on: ubuntu-latest + steps: + - name: Notify the host release workflow + env: + DISPATCH_TOKEN: ${{ secrets.FRAMEWORKS_DISPATCH_TOKEN }} + PACKAGE_REPOSITORY: ${{ github.event.repository.name }} + run: | + if [ -z "$DISPATCH_TOKEN" ]; then + echo "::warning::FRAMEWORKS_DISPATCH_TOKEN is not configured; skipping host release notification." + exit 0 + fi + + case "$PACKAGE_REPOSITORY" in + Unity-GameData) package=gamedata ;; + Unity-GoogleSheet-Importer) package=googlesheetimporter ;; + Unity-MobileServices) package=mobileservices ;; + Unity-Services) package=services ;; + Statechart-HFSM) package=statechart ;; + Unity-UiService) package=uiservice ;; + *) + echo "::error::Unknown package repository: $PACKAGE_REPOSITORY" + exit 1 + ;; + esac + + payload=$(printf '{"event_type":"upm-release","client_payload":{"package":"%s","phase":"status"}}' "$package") + curl --fail-with-body --location --request POST \ + --url https://api.github.com/repos/CoderGamester/Frameworks/dispatches \ + --header "Accept: application/vnd.github+json" \ + --header "Authorization: Bearer $DISPATCH_TOKEN" \ + --header "X-GitHub-Api-Version: 2022-11-28" \ + --data "$payload" From 05025115002d2fccd60cf9b5201f3a05ef128e8b Mon Sep 17 00:00:00 2001 From: CoderGamester Date: Wed, 5 Aug 2026 01:29:08 +0100 Subject: [PATCH 02/17] ci: update release-preflight check --- .github/workflows/release-preflight.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release-preflight.yml b/.github/workflows/release-preflight.yml index fb96068..d8225c4 100644 --- a/.github/workflows/release-preflight.yml +++ b/.github/workflows/release-preflight.yml @@ -72,7 +72,7 @@ jobs: repository: CoderGamester/Frameworks # Immutable tooling snapshot. Update intentionally through # `release.py install-preflight`, never by following a moving branch. - ref: be8c1474ae2ab772fae76a29f07bd520abc3b3ac + ref: be8c147f3d12d94a4055d556ffdc0a26e077e5ec path: .release-tooling sparse-checkout: .claude/skills/unity-package-release/scripts persist-credentials: false From 36b60d22b95dc1bdb274412f10cddbb7c74ec60f Mon Sep 17 00:00:00 2001 From: CoderGamester Date: Wed, 5 Aug 2026 01:30:31 +0100 Subject: [PATCH 03/17] ci: update release-preflight check --- .github/workflows/release-preflight.yml | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/.github/workflows/release-preflight.yml b/.github/workflows/release-preflight.yml index d8225c4..0a2b01c 100644 --- a/.github/workflows/release-preflight.yml +++ b/.github/workflows/release-preflight.yml @@ -62,10 +62,9 @@ jobs: persist-credentials: false # The gate logic is shared rather than vendored into six repos, so there is - # one source of truth. `ref` is explicit: actions/checkout defaults to the - # target repo's DEFAULT branch (master), where the tooling does not exist - # yet — omitting it fails with "No such file or directory". Retarget this to - # master once the skill is merged there. + # one source of truth. Pinning its full commit keeps an unchanged package PR + # reproducible when Frameworks/develop advances; the installer performs + # intentional snapshot updates across all package repositories. - name: Check out the release tooling uses: actions/checkout@v7 with: From 6b79a0a1be7267fd74ea22c101432f7ca45ac634 Mon Sep 17 00:00:00 2001 From: CoderGamester Date: Mon, 10 Aug 2026 10:41:12 +0300 Subject: [PATCH 04/17] style: wrap long XML summaries --- Runtime/Internal/LeaveState.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Runtime/Internal/LeaveState.cs b/Runtime/Internal/LeaveState.cs index 8d3e467..65478ec 100644 --- a/Runtime/Internal/LeaveState.cs +++ b/Runtime/Internal/LeaveState.cs @@ -10,7 +10,9 @@ internal class LeaveState : StateInternal, ILeaveState { private readonly IList _onEnter = new List(); - /// The transition this leave state hands back to the parent region, set when the state is configured. + /// + /// The transition this leave state hands back to the parent region, set when the state is configured. + /// internal ITransitionInternal LeaveTransition { get; private set; } public LeaveState(string name, IStateFactoryInternal factory) : base(name, factory) From f09dc68d929d477674bcc7558b944132b310f6e9 Mon Sep 17 00:00:00 2001 From: CoderGamester Date: Mon, 10 Aug 2026 18:00:00 +0300 Subject: [PATCH 05/17] fix: correct case of two .meta filenames to match their assets `GameLovers.StateChart.Editor.Tests.asmdef.meta` and `StateChartChoiceTest.cs.meta` carried a capital C while the asmdef and test file they describe are lowercase `Statechart`. macOS's case-insensitive filesystem hides this, but on a case-sensitive one Unity sees each .meta as orphaned and reassigns the asset a fresh GUID, breaking references. Rename only -- both GUIDs are unchanged (b0400479..., 51310419...). Surfaced while re-attesting the 0.9.4 release: the repack would have shipped .meta names that do not match their assets, because the published tarball happens to carry the correctly-paired lowercase names. --- ...asmdef.meta => GameLovers.Statechart.Editor.Tests.asmdef.meta} | 0 ...{StateChartChoiceTest.cs.meta => StatechartChoiceTest.cs.meta} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename Tests/Editor/{GameLovers.StateChart.Editor.Tests.asmdef.meta => GameLovers.Statechart.Editor.Tests.asmdef.meta} (100%) rename Tests/Editor/{StateChartChoiceTest.cs.meta => StatechartChoiceTest.cs.meta} (100%) diff --git a/Tests/Editor/GameLovers.StateChart.Editor.Tests.asmdef.meta b/Tests/Editor/GameLovers.Statechart.Editor.Tests.asmdef.meta similarity index 100% rename from Tests/Editor/GameLovers.StateChart.Editor.Tests.asmdef.meta rename to Tests/Editor/GameLovers.Statechart.Editor.Tests.asmdef.meta diff --git a/Tests/Editor/StateChartChoiceTest.cs.meta b/Tests/Editor/StatechartChoiceTest.cs.meta similarity index 100% rename from Tests/Editor/StateChartChoiceTest.cs.meta rename to Tests/Editor/StatechartChoiceTest.cs.meta From b9c50ade2b96cb092cc411db499a090bb9be1b00 Mon Sep 17 00:00:00 2001 From: CoderGamester Date: Wed, 12 Aug 2026 20:32:06 +0300 Subject: [PATCH 06/17] docs: modernize statechart guidance --- AGENTS.md | 2 +- CHANGELOG.md | 7 ++- README.md | 129 +++++++++++++++++++++++---------------------------- package.json | 6 +-- 4 files changed, 68 insertions(+), 76 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 2c00760..409c08c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,7 @@ ## 1. Package Overview - **Package**: `com.gamelovers.statechart` -- **Unity**: 2022.3+ (the only package in the family with a floor below 6000.0 — verify before assuming 6000.0-only APIs are safe here) +- **Unity**: minimum 6000.0; compatibility reference streams 6000.0.x, 6000.3.x, and 6000.5.x. Reference editors: 6000.0.81f1, 6000.3.21f1, 6000.5.7f1 (primary). Do not call a stream validated without current matrix artifacts. - **Dependencies** (see `package.json`) - `com.cysharp.unitask` (2.5.10): `ITaskWaitState.WaitingFor(Func)` overload diff --git a/CHANGELOG.md b/CHANGELOG.md index a234b42..7142cdc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,12 @@ All notable changes to this package will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) -and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). +and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +**Changed**: +- Declared Unity 6000.0 as the package minimum and documented 6000.0.x, 6000.3.x, and 6000.5.x as compatibility reference streams. ## [0.9.5] - 2026-08-04 diff --git a/README.md b/README.md index cf3de76..9eadcb8 100644 --- a/README.md +++ b/README.md @@ -1,103 +1,90 @@ # GameLovers Statechart -[![Unity Version](https://img.shields.io/badge/Unity-2022.3%2B-blue.svg)](https://unity3d.com/get-unity/download) -[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE.md) - -A Hierarchical Finite State Machine (Statechart / HFSM) for Unity — states can nest into sub-regions, split into parallel regions, and block on async waits, all defined once in a single setup closure with no runtime mutation of the chart's shape. - -## Why Use This Package? - -Plain FSMs get unwieldy once a game state has sub-states of its own (a "Playing" state that is itself "Loading" → "Countdown" → "InProgress"), or needs two things happening at once (an animation playing while input is disabled). A Statechart — per the [UML spec](http://www.omg.org/spec/UML) and the broader [statecharts model](https://statecharts.github.io/what-is-a-statechart.html) — solves both by letting a state open its own nested region (`Nest`) or two parallel regions (`Split`), instead of flattening everything into one state graph. - -### Key Features -- **10 state types** covering the common Statechart vocabulary: `Initial`, `Final`, `State` (event-blocking), `Transition` (pass-through), `Choice` (conditional branch), `Wait` (activity-blocking), `TaskWait` (async-blocking), `Nest` (sequential sub-region), `Split` (parallel sub-regions), `Leave` (early exit to a parent region). -- **Fluent setup** — one constructor closure defines the entire chart; no separate registration step. -- **Async-aware waiting** — `TaskWait` states block on a `Task` or `UniTask` directly. -- **Editor-time validation** — malformed setups (missing initial state, transition with no target, transition loops) throw immediately at construction in the Editor / Debug builds. +Hierarchical statecharts for Unity 6 with nested and parallel regions, event transitions, choices, and async waits. -## System Requirements +[![Unity](https://img.shields.io/badge/Unity-6000.0%20%7C%206000.3%20%7C%206000.5-blue.svg)](https://unity.com/download) +[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE.md) -- **[Unity](https://unity.com/download)** (v2022.3+) — the only package in the GameLovers family that doesn't require Unity 6 -- **[UniTask](https://github.com/Cysharp/UniTask)** (v2.5.10+) — for the `ITaskWaitState.WaitingFor(Func)` overload +## When to use it -Dependencies are automatically resolved when installing via Unity Package Manager. +Use Statechart when a flat FSM cannot express hierarchical behavior, concurrent regions, or controlled async waits clearly. The package is pipeline-neutral and requires UniTask for its `UniTask` wait overloads. -## Installation +## Unity compatibility -### Via Unity Package Manager (Recommended) +| Item | Current policy | +| --- | --- | +| Minimum Unity version | `6000.0` | +| Reference streams | `6000.0.x`, `6000.3.x`, `6000.5.x` | +| Reference editors | `6000.0.81f1`, `6000.3.21f1`, `6000.5.7f1` (primary) | +| Render pipeline | Pipeline-neutral | +| Validation status | Compatibility target; consult fresh matrix artifacts before claiming validation. | -1. Open Unity Package Manager (`Window` → `Package Manager`) -2. Click `+` → `Add package from git URL` -3. Enter: `https://github.com/CoderGamester/Statechart-HFSM.git` +## Install -### Via manifest.json +Add UniTask explicitly when installing from Git: ```json { "dependencies": { - "com.gamelovers.statechart": "https://github.com/CoderGamester/Statechart-HFSM.git" + "com.cysharp.unitask": "https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask#2.5.10", + "com.gamelovers.statechart": "https://github.com/CoderGamester/Statechart-HFSM.git#0.9.5" } } ``` -## Key Components - -| Type | Purpose | -|---|---| -| `Statechart` | The chart itself — `Run()` / `Pause()` / `Trigger(event)` / `Reset()` | -| `IStateFactory` | Passed into the setup closure; one factory method per state type (`Initial`, `Final`, `State`, `Transition`, `Choice`, `Wait`, `TaskWait`, `Nest`, `Split`, `Leave`) | -| `ITransition` / `ITransitionCondition` | `.OnTransition(action).Target(state)`; `Choice` transitions add `.Condition(() => bool)` | -| `IStatechartEvent` / `StatechartEvent` | Event identity is per-instance — keep one instance per logical event | -| `IWaitActivity` | Passed into a `Wait` state's `WaitingFor(...)`; call `.Complete()` to unblock, or `.Split()` to fan out | +## First success -## Quick Start +Keep events as fields: statechart event identity is by object instance, not by its display name. ```csharp using GameLovers.StatechartMachine; using UnityEngine; -var jumpEvent = new StatechartEvent("Jump"); - -var statechart = new Statechart(factory => +public sealed class PlayerStatechart : MonoBehaviour { - var initial = factory.Initial("Initial"); - var idle = factory.State("Idle"); - var jumping = factory.State("Jumping"); - var final = factory.Final("Final"); - - initial.Transition().Target(idle); - - idle.Event(jumpEvent).OnTransition(() => Debug.Log("Jumping!")).Target(jumping); - idle.OnEnter(() => Debug.Log("Entered Idle")); - - jumping.OnEnter(() => Debug.Log("Entered Jumping")); - jumping.Event(jumpEvent).Target(final); // second Jump ends the chart - - final.OnEnter(() => Debug.Log("Done")); -}); - -statechart.Run(); -statechart.Trigger(jumpEvent); // Idle -> Jumping -statechart.Trigger(jumpEvent); // Jumping -> Final + private readonly StatechartEvent jump = new("Jump"); + private Statechart chart; + + private void Awake() + { + chart = new Statechart(factory => + { + var initial = factory.Initial("Initial"); + var idle = factory.State("Idle"); + var jumping = factory.State("Jumping"); + initial.Transition().Target(idle); + idle.Event(jump).Target(jumping); + jumping.Event(jump).Target(idle); + }); + chart.Run(); + } + + public void Jump() => chart.Trigger(jump); +} ``` -Every state is created via the `factory` passed into the constructor closure — there is no separate registration call, and the chart's shape cannot be changed after construction. See [AGENTS.md](AGENTS.md) for nested regions (`Nest`), parallel regions (`Split`), async waits (`TaskWait`), and the full state-type reference. - -## Related docs - -| Document | Purpose | -|---|---| -| [AGENTS.md](AGENTS.md) | Contributor/agent guide — full state-type reference, architecture, gotchas | -| [CHANGELOG.md](CHANGELOG.md) | Version history | +```mermaid +stateDiagram-v2 + [*] --> Idle + Idle --> Jumping: jump event + Jumping --> Idle: jump event +``` -## Contributing +## Runtime semantics -Contributions are welcome! See [AGENTS.md](AGENTS.md) for architecture details, coding standards, and common workflows. +| Concept | Behavior | +| --- | --- | +| `Trigger` | Ignored until `Run()` and while the chart is paused | +| `Choice` | Takes the first true transition; define a fallback deliberately | +| Action-only transition | Valid when it has no target and exists for its action | +| `Wait` | Resumes when its wait activity completes; can receive configured events | +| `TaskWait` | Waits on a `Task` or `UniTask`; it does not receive events while waiting | +| `Nest` / `Split` | Create sequential nested regions / concurrent regions | -## Support +Missing top-level initial configuration is rejected in all builds. Other setup validation has build-dependent editor/debug behavior; write and test the behavior you require instead of relying on broad “all invalid graphs fail immediately” assumptions. -- **Issues**: [Report bugs or request features](https://github.com/CoderGamester/Statechart-HFSM/issues) +## Recipes and support -## License +The public API supports `Nest`, `Split`, `Choice`, `Wait`, and `TaskWait`; add a small package sample before treating any recipe as a supported end-to-end workflow. Until then, use the source tests as the executable reference. -MIT — see [LICENSE.md](LICENSE.md). +See [CHANGELOG.md](CHANGELOG.md) and file an [issue](https://github.com/CoderGamester/Statechart-HFSM/issues). `AGENTS.md` is contributor guidance, not end-user API documentation. diff --git a/package.json b/package.json index 1217e54..a613845 100644 --- a/package.json +++ b/package.json @@ -3,12 +3,12 @@ "displayName": "Statechart", "author": "Miguel Tomas", "version": "0.9.5", - "unity": "2022.3", + "unity": "6000.0", "license": "MIT", - "description": "This package allows the use of Statecharts (Hierarchichal State Machine) within an Unity project.\n\nThe primary feature of Statecharts is that states can be organized in a hierarchy.\nA Statecharts is a state machine where each state in the state machine may define its own subordinate state machines, called substates.\nThose states can again define substates.\n\nFor more information: https://statecharts.github.io/what-is-a-statechart.html", + "description": "Hierarchical statecharts with nested and parallel regions, event transitions, choices, and async waits.", "type": "library", "hideInEditor": false, "dependencies": { "com.cysharp.unitask": "2.5.10" } -} \ No newline at end of file +} From a6a06aee8b75d9fcbc7d4dd79f1ddb3ea21ab936 Mon Sep 17 00:00:00 2001 From: CoderGamester Date: Thu, 13 Aug 2026 22:06:21 +0300 Subject: [PATCH 07/17] docs: focus agent guidance on durable rules --- AGENTS.md | 110 +++++----------- Tests/AGENTS.md | 334 ++++++++---------------------------------------- 2 files changed, 81 insertions(+), 363 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 409c08c..2c5db66 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,90 +1,38 @@ -# GameLovers.Statechart - AI Agent Guide +# GameLovers Statechart — Agent Guide -> **Companion files**: `CLAUDE.md` wraps this file for Claude Code — edit `AGENTS.md`, not `CLAUDE.md`. `README.md` is the user-facing entry point. +This guide adds package-specific rules to the host repository guide. Consumer usage belongs in `README.md`. -## 1. Package Overview -- **Package**: `com.gamelovers.statechart` -- **Unity**: minimum 6000.0; compatibility reference streams 6000.0.x, 6000.3.x, and 6000.5.x. Reference editors: 6000.0.81f1, 6000.3.21f1, 6000.5.7f1 (primary). Do not call a stream validated without current matrix artifacts. -- **Dependencies** (see `package.json`) - - `com.cysharp.unitask` (2.5.10): `ITaskWaitState.WaitingFor(Func)` overload +## Scope -Hierarchical State Machine (HFSM / Statechart, per the [UML spec](http://www.omg.org/spec/UML) and [statecharts.github.io](https://statecharts.github.io/what-is-a-statechart.html)) — states can nest, split into parallel regions, and run async waits, all defined once in a constructor setup closure with no further runtime mutation. Smallest package in the family: no `Editor/` assembly, no `Samples~/`, single `Runtime/` assembly. +- Package: `com.gamelovers.statechart`; minimum Unity version and dependencies are authoritative in `package.json`. +- One runtime assembly implements hierarchical statecharts with nested and parallel regions, events, choices, callback waits, and Task/UniTask waits. +- There is no Editor assembly or package sample. This package is render-pipeline-neutral. +- Public contracts live at `Runtime/`; implementations under `Runtime/Internal/` remain internal. -## 2. Runtime Architecture (high level) +## Statechart invariants -### The chart itself -- **`Statechart`** (`Runtime/Statechart.cs`, implements `IStatechart : IStateMachineDebug`) is the entry point. Construct with `new Statechart(Action setup)` — the setup closure runs immediately and defines every state and transition; there is no API to add states after construction. Throws `MissingMemberException` if the setup never calls `factory.Initial(...)`. - - `Run()` — starts/resumes execution from wherever the chart is anchored. No-op if already running. - - `Trigger(IStatechartEvent trigger)` — processes an event with run-to-completion semantics. **No-op if the chart isn't running** (`Pause()`d or never `Run()` called) — a common "my event did nothing" cause. - - `Pause()` — stops processing; `Run()` resumes from the same point. - - `Reset()` — jumps back to the initial state. Does **not** implicitly pause or resume; if the chart was waiting on an event, it needs a fresh `Run()` to continue after reset. - - `LogsEnabled` (from `IStateMachineDebug`) — per-chart debug logging toggle; `IState.LogsEnabled` is the same toggle per-state. - - `CurrentState` (string name) is exposed **only under `#if UNITY_EDITOR`** — do not reference it from a runtime code path that also needs to compile for a player build. - - In `#if UNITY_EDITOR || DEBUG`, every state's `Validate()` runs once at construction — this is where the "missing transition target" / "transition loop" exceptions below come from. -- **`IStateFactory`** (`Runtime/IStateFactory.cs`) is passed into the setup closure — one factory instance per region (top-level chart, and one more per `Nest`/`Split` sub-region). Each factory method takes a `name` string (debug-only identity) and returns the state's own narrow interface: +- A `Statechart` is fully defined by its constructor setup closure. Runtime mutation of the state graph is unsupported, and every region requires exactly one initial state. +- `Trigger` is a no-op until `Run()` and while paused. `Pause()` preserves the active position. `Reset()` returns to the initial state without changing the run/pause state. +- Statechart events compare by generated instance id, not by name. Reuse one event instance for one logical event. +- Every transition must name a target. A choice with no satisfied condition remains in the choice state. +- `Nest` completes one sequential child region. `Split` completes only after all parallel child regions finish. +- `NestedStateData` separately controls whether leaving a nested region executes the parent nest state's exit callback and the child final state's enter callback. The plain setup-closure overload enables both; preserve the distinction when changing leave/completion behavior. +- `Leave` exits exactly one region layer and bypasses the current nest/split completion transition. +- `IWaitState` may process events and uses `IWaitActivity` completion. `ITaskWaitState` cannot process events while awaiting its Task/UniTask; ancestor exit waits for it and queues intervening events. +- When an active callback wait is abandoned by an ancestor region exit, complete its outstanding inner activities rather than leaving them dangling. Task waits instead delay the exit until the task completes. +- Validation runs only under `UNITY_EDITOR || DEBUG`. Do not treat release-build absence of validation as a supported malformed graph. +- `CurrentState` is Editor-only. Runtime game logic must not depend on it. - | Factory method | Returns | Purpose | - |---|---|---| - | `Initial(name)` | `IInitialState` | Entry point of the region. Exactly one per region. | - | `Final(name)` | `IFinalState` | Marks the region complete. | - | `State(name)` | `ISimpleState` | Blocks until an `Event(...)` transition fires. | - | `Transition(name)` | `ITransitionState` | Non-blocking; falls through to its target immediately. | - | `Nest(name)` | `INestState` | Opens one new nested (sequential) region. | - | `Choice(name)` | `IChoiceState` | Non-blocking; picks among `Transition().Condition(...)` branches. | - | `Wait(name)` | `IWaitState` | Blocks on `IWaitActivity` completion (and/or an event). | - | `TaskWait(name)` | `ITaskWaitState` | Blocks on a `Task`/`UniTask`; cannot process events while waiting. | - | `Split(name)` | `ISplitState` | Opens two-or-more new nested **parallel** regions. | - | `Leave(name)` | `ILeaveState` | Like `Final`, but its transition targets a state in an **ancestor** region, jumping out of the current `Nest`/`Split` by exactly one layer. | +## Change placement -### State capability interfaces (`Runtime/IState.cs`) -Every concrete state interface above is composed from these narrower capability interfaces — check which ones a state implements to know what it can do: -- `IStateEnter.OnEnter(Action)` / `IStateExit.OnExit(Action)` — lifecycle callbacks. -- `IStateTransition.Transition()` → `ITransition` — unconditional transition (used by `Initial`/`Transition`/`Leave` states). -- `IStateEvent.Event(IStatechartEvent)` → `ITransition` — event-triggered transition (used by `State`/`Nest`/`Wait`/`Split` states). -- `ITransition.OnTransition(Action)` (chainable) + `.Target(IState)` (terminal — every transition must call this or `Statechart`'s validation throws). -- `ITransitionCondition : ITransition` adds `.Condition(Func)` — used exclusively by `IChoiceState.Transition()`; a choice with a failing condition does not transition (evaluate carefully — a choice state with no satisfied condition stalls the chart there). +- A new state type requires a public capability-composed interface, an internal implementation, a factory method on `IStateFactory`, and the matching `StateFactory` implementation. +- Keep the public surface expressed through narrow capability interfaces in `Runtime/IState.cs`; consumers should not depend on internal concrete states. +- Preserve the existing Task and UniTask overloads when changing async waiting. +- Before changing anything under `Tests/`, read `Tests/AGENTS.md`. -### Nesting and parallelism -- **`INestState.Nest(Action | NestedStateData)`** opens a new sequential sub-region; its returned `ITransition` fires once that sub-region reaches its `Final`. The `NestedStateData` overload (`Setup` + `ExecuteExit` + `ExecuteFinal` bools) controls whether the *parent* nest state's own `OnExit` and the *sub-region's* `IFinalState.OnEnter` actually run when leaving via a `Leave` state from inside vs. via normal completion — the plain `Action` overload defaults both to `true`. -- **`ISplitState.Split(params Action[] | NestedStateData[])`** opens N parallel sub-regions simultaneously; its `ITransition` fires only once **all** sub-regions reach their own `Final`. -- **`ILeaveState`** exits a `Nest`/`Split` region early, targeting a state in the parent region directly — bypasses the nest/split's own completion transition. Can only jump one region layer (an inner `Leave` inside a doubly-nested region still only reaches its immediate parent, not the top level). +## Verification and documentation -### Waiting states -- **`IWaitState.WaitingFor(Action)`** — the action receives an `IWaitActivity` (`Runtime/IWaitActivity.cs`); call `.Complete()` when the awaited work finishes, or `.Split()` first to fan out into multiple sub-activities whose *own* `.Complete()` calls all must return true before the parent completes. A `Wait` state also still processes `Event(...)` transitions (checked after `WaitingFor` since concurrency needs `WaitingFor` resolved first) — the doc comment on `IWaitState` explicitly notes this ordering. If a wait state is the active state when an ancestor `Nest`/`Split` exits, it force-completes itself and all inner activities rather than leaving them dangling. -- **`ITaskWaitState.WaitingFor(Func | Func)`** — blocks on true async work. Unlike `IWaitState`, **cannot process `Event(...)` transitions while waiting** (no `IStateEvent` in its interface composition) — if an ancestor region exits mid-wait, the exit itself is paused and any events that arrive during the wait are queued rather than dropped, to avoid a concurrency bottleneck. - -### Events -- **`IStatechartEvent`** (`Runtime/StatechartEvent.cs`) — equality is by an auto-incrementing `uint Id` assigned at construction, **not** by `Name`. Two `new StatechartEvent("Jump")` instances are never equal to each other; keep one instance per logical event and reuse it across every `.Event(theSameInstance)` call site that should respond to it. - -## 3. Key Directories / Files -- **Public interfaces** (root of `Runtime/`): `IState.cs` (all state-capability + concrete-state interfaces + `NestedStateData`), `ITransition.cs`, `IStateFactory.cs`, `IWaitActivity.cs`, `Statechart.cs` (+ `IStatechart`/`IStateMachineDebug`), `StatechartEvent.cs` (+ `IStatechartEvent`). -- **`Runtime/Internal/*`** — concrete state implementations (`InitialState`, `FinalState`, `SimpleState`, `TransitionState`, `NestState`, `SplitState`, `ChoiceState`, `WaitState`, `TaskWaitState`, `LeaveState`), `StateFactory`, `Transition`, `InnerStateData`, `StatechartUtils`. All `internal` — not part of the public surface; consumers only ever see the interfaces above. -- **Tests**: `Tests/Editor/*` (one asmdef, `GameLovers.Statechart.Editor.Tests`) — `StatechartTest.cs` (core lifecycle + validation-exception coverage), `StatechartStateTest.cs`, `StatechartTransitionTest.cs`, `StatechartChoiceTest.cs`, `StatechartNestTest.cs`, `StatechartSplitTest.cs`, `StatechartWaitTest.cs`, `StatechartTaskWaitTest.cs`, `StatechartLeaveTest.cs`, `StatechartNestSplit_IntegrationTest.cs`, `IMockCaler.cs` (mocked-callback interface used across the suite via NSubstitute). Before reading, editing, or creating any file in `Tests/`, you **MUST** read [`Tests/AGENTS.md`](Tests/AGENTS.md) first. -- **No `Editor/` assembly, no `Samples~/`, no `docs/`** — this package's entire surface is the interfaces above; there is no editor tooling and nothing to import as a sample. - -## 4. Important Behaviors / Gotchas -- **Setup-time validation, not always-on**: the exceptions below (`MissingMemberException`, `InvalidOperationException`) only fire from the `#if UNITY_EDITOR || DEBUG` validation pass in the `Statechart` constructor — a malformed chart in a release build without `DEBUG` defined will not be caught the same way. Always validate in-editor / in tests before shipping a chart's setup. -- **`Trigger` is a no-op unless running**: calling `Trigger(...)` before the first `Run()`, or after `Pause()`, silently does nothing — it does not queue the event for later. -- **Event identity is per-instance, not per-name**: see `IStatechartEvent` above — a fresh `new StatechartEvent("X")` never equals a previously created `"X"` event. Store event instances as fields/constants, not locals recreated per call. -- **`ITaskWaitState` cannot receive events while waiting**; `IWaitState` can, but only after its `WaitingFor` activities resolve first in a concurrent scenario. Picking the wrong one of these two for a state that needs to react to an event mid-wait is a common design mistake. -- **`ILeaveState` only jumps one region layer** — from inside a doubly-nested region, a `Leave` still only reaches the immediate parent, not further up. -- **`CurrentState` is Editor/DEBUG-only surface** on `Statechart` — don't wire game logic to it. - -## 5. Coding Standards (Unity 6 / C# 9.0) -- **C#**: C# 9.0 syntax; explicit namespaces (`GameLovers.StatechartMachine` for Runtime, `GameLoversEditor.StatechartMachine.Tests` for Tests); no global usings. -- **Assemblies**: `Runtime/GameLovers.Statechart.asmdef` has no Editor/UnityEditor reference — this package has no Editor assembly at all. Keep everything under `Runtime/Internal/` truly `internal`; the public surface is exactly the interfaces in section 2/3. -- **Async**: `Cysharp.Threading.Tasks` (UniTask) only appears in `ITaskWaitState.WaitingFor(Func)` — the plain-`Task` overload exists for consumers who don't want the UniTask dependency in their own state-setup code (the package dependency itself is unconditional either way). - -## 6. External Package Sources (for API lookups) -- UniTask: `Library/PackageCache/com.cysharp.unitask/` - -## 7. Common change workflows -- **Add a new state type**: define its public capability-composed interface in `Runtime/IState.cs`, add the corresponding `internal` implementation under `Runtime/Internal/`, and add the factory method to `IStateFactory` + `Runtime/Internal/StateFactory.cs`. Add test coverage under `Tests/Editor/` following the existing `StatechartTest.cs` naming. -- **Change validation behavior**: the per-state `Validate()` calls happen in `Statechart`'s constructor under `#if UNITY_EDITOR || DEBUG` — keep new validation failures as exceptions thrown from state `Validate()` implementations under `Runtime/Internal/`, matching the existing `MissingMemberException`/`InvalidOperationException` pattern. - -## 8. Update Policy -Update this file when: -- Public API changes (`IStatechart`, any state-capability interface in `IState.cs`, `IStateFactory`, `ITransition`, `IWaitActivity`, `IStatechartEvent`) -- Validation/exception behavior changes in the `Statechart` constructor's setup pass -- Nesting/splitting/leaving semantics change (region completion rules, `NestedStateData` flag behavior) -- Dependencies in `package.json` change (cross-check this file and `README.md` for stale references) +- Test lifecycle, transition target validation, nested/split completion, leave depth, and waiting/event ordering when those areas change. +- Validation tests must run with Editor or DEBUG behavior enabled and must not imply equivalent release-build enforcement. +- Prefer the local UniTask package source under `Library/PackageCache/` for external API questions. +- Update `README.md` for public statechart semantics and this guide only for durable invariants or test conventions. diff --git a/Tests/AGENTS.md b/Tests/AGENTS.md index 96b2024..7780ec1 100644 --- a/Tests/AGENTS.md +++ b/Tests/AGENTS.md @@ -1,312 +1,82 @@ -# GameLovers.Statechart Tests — AI Agent Guide +# GameLovers Statechart Tests — Agent Guide -This file contains testing conventions for the `com.gamelovers.statechart` package. It is the source of truth when reading, editing, or creating test files under `Tests/`. +This guide adds test-only rules to the package and host guides. -For runtime architecture, gotchas, and package-level context, see the parent [`AGENTS.md`](../AGENTS.md). +## Shared test rules -§1 and §2 are shared verbatim across every GameLovers package. A change to either must be applied to all six `Tests/AGENTS.md` files in the same working session, one commit per submodule. + +### Admission -## 1. ADMIT — Test Admission Test +A new test is admitted only when all six answers are yes: -A proposed test is admitted only if all five answers are YES. Record the first two -as comments on the test itself. - -| | Question | +| Check | Requirement | |---|---| -| **A1 DEFECT** | Can you name the defect in one sentence, referencing a production file and symbol? "It could break" is not a defect. | -| **A2 RED** | Can you name the exact production edit — one line or one branch, identified by `file` + `symbol` — that makes this test fail? If no such single edit exists, the test pins nothing. | -| **A3 PACKAGE** | Does every assertion read a value this package computed? Reject assertions on `new X() != new X()`, `!= null` on a freshly constructed object, default struct/enum values, or anything the C# spec or the Unity engine already guarantees. | -| **A4 CHEAPEST** | Is this the cheapest tier that covers the defect? EditMode beats PlayMode; a `[TestCase]` row on an existing fixture beats a new `[Test]`; a new `[Test]` beats a new fixture. Grep before writing. | -| **A5 UNIQUE** | Does no existing test already fail on the A2 edit? Grep the symbol under test across `Tests/` first. | -| **A6 ENVIRONMENT** | Would this assertion's outcome change if project configuration changed — a renderer feature installed or removed, an Addressables catalog built, a sample imported, a quality tier switched? If yes, the test must **read** that state, not assume one value of it. | - -**A6 in practice.** A6 is not A3. A3 asks whether the package computed the value; A6 -asks whether the test assumed which value it would be. A test can satisfy A3 and still -fail A6 — reading a package-computed flag is fine, hard-coding the expectation that the -flag is `false` is not. - -The concrete instance: `UiBackdropBlurPresenterFeatureTests` unconditionally expected -the "no renderer feature installed" error. Production only logs it when -`UiBackdropBlurRendererFeature.IsInstalled` is false. Batchmode never instantiates the -URP renderer, so the flag was false and all five tests passed; in the Editor the feature -registers from the project's renderer asset, the flag is true, production correctly stays -silent, and all five failed. The fixture was really asserting *"this project has no blur -renderer feature"* — a fact about the repo, not about the code under test. - -The fix shape is always the same: branch the expectation on the state instead of assuming -it, and leave the assertions that are actually the subject untouched. - -```csharp -if (UiBackdropBlurRendererFeature.IsInstalled) return; // production logs nothing -LogAssert.Expect(LogType.Error, ...); -``` - -If a test genuinely needs one specific value of ambient state, it must establish that -state itself in `[SetUp]` and restore it in `[TearDown]` — never inherit it. +| **A1 Defect** | Name the production file/symbol and the incorrect behavior in one sentence. “It could break” is not a defect. | +| **A2 Red** | Name a plausible production edit that should make the assertion fail. Prefer one line/branch; shared-path integration mutations are allowed when isolation is dishonest. | +| **A3 Package-owned** | Every assertion must read behavior this package computes, not C# defaults, fresh-object non-nullness, or Unity guarantees. | +| **A4 Cheapest** | Use the cheapest honest tier: a test case before a new test, EditMode before PlayMode, and an existing fixture before a new fixture. | +| **A5 Unique** | Grep the symbol, derived/wrapper types, and paired setup fields. Do not add a test already reddened by the same narrow defect. | +| **A6 Environment** | Control ambient renderer, Addressables, sample, static, and project state, or branch the expectation on the state actually observed. | -**A5-bis — inherited-type coverage.** Before proposing a fixture for a type that -derives from or wraps another tested type, grep `Tests/` for the derived type's -name and for paired `[SetUp]` fields. Base-and-derived pairs are tested jointly in -the base's fixture unless the derived type adds new public surface. +Two additional rejects apply: -**Two mechanical disqualifiers** — violate one and the test is rejected: +- **D1 Tautology:** a lone `DoesNotThrow`, freshly-created non-null assertion, language default, or input-derived substring match pins no package behavior unless used by a named harness sentinel. +- **D2 Name/body mismatch:** deleting or bypassing the behavior promised by the test name must not leave the test green. Strengthen the assertion or rename the test to its actual claim. -- **D1 — tautology.** If the only assertion is `Assert.DoesNotThrow`, - `Assert.IsNotNull`, or a disjunction of `Contains(...)` substrings, the test - fails A2 unless you write down what *would* throw, be null, or not match. A - substring disjunction that includes a string the input itself embeds is - unfalsifiable by construction. -- **D2 — name/body contract.** The test name is a claim. If deleting the - production feature the name mentions leaves the test green, the name is a lie. +Fixtures under `Smoke/` are exempt from A1/A2 and may assert construction/bootstrap viability. The exemption is directory-scoped, not permission to use smoke assertions in Unit or Integration fixtures. -**Smoke exemption, by directory.** Fixtures under `Smoke/` are exempt from A1 and -A2 and may assert construction-without-throwing only. Their defect class is "the -assembly no longer loads / bootstrap regressed", which is real and not expressible -otherwise. The exemption is by directory, not by assertion shape — a Unit test -that only asserts `IsNotNull` is still rejected. +### Revert and Confirm Red (RCR) -## 2. RCR — Revert and Confirm Red +Every new or strengthened behavioral test must be observed failing once against a plausible production mutation before commit: -> Every new or strengthened test must be observed failing, once, against a -> one-line production revert, before it is committed. +1. Run the new test against normal production code and observe GREEN. +2. Preserve the exact working patch or use an isolated worktree; then apply the A2 mutation. Never restore a dirty file from `HEAD`. +3. Run the smallest attributable filter. RED must come from the intended assertion with a diagnostic failure, not a compile error or unrelated `NullReferenceException`. +4. Restore the saved production state, confirm the mutation is gone without losing other edits, and observe GREEN again. +5. Record the observation on the test using `file + symbol`, never a line number. -Line coverage proves a line executed. It does not prove any test would notice if -that line were wrong. RCR is the cheap substitute for mutation testing, and it is -what makes a coverage number trustworthy. - -**Procedure** (~90 seconds per test): - -1. Write the test. Run it. Green. -2. Apply the A2 edit — invert the comparison, delete the guard clause, return - early, comment out the one line. **One line only**: a broad deletion proves - nothing, because it would also "fail" a tautological test via a compile error. -3. Run only that test. It must be **RED**, and the failure message must name the - thing you broke. A red-by-`NullReferenceException` does not count — that is the - test crashing, not asserting. -4. `git checkout -- `. Re-run. Green. -5. Record the mutation in the test's header comment. - -**Recording format** — on the test, not in a separate ledger. A ledger rots the -moment a test is renamed; a comment travels with the test, appears in every diff -that touches it, and lets a reviewer re-run the mutation in 30 seconds. +Use this compact form, targeting four lines and never exceeding six: ```csharp [Test] -// ADMIT: -// RCR: — → RED (). +// ADMIT: +// RCR: — → RED (). public void Method_Condition_ExpectedResult() ``` -**Anchor on `file` + `symbol`, never `file:line`.** Line numbers rot on the first -unrelated edit above them — a stale `:474` pointing at a method that moved to `:464` -sends the next reader to the wrong code and quietly destroys the comment's value. - -**Budget: four lines is the target, six is the ceiling.** One sentence of ADMIT, -one of RCR, wrapped. This obeys the repo-wide rule in the root `AGENTS.md` -(§ Code comments): *"One sentence usually suffices. Multi-paragraph rationale is a -smell."* Anything past the ceiling belongs in the commit body or `docs/`, not on the -test. Two things in particular must NOT appear here: -- **Change narration.** *"An earlier version of this test was a tautology"* is diff - context; the root `AGENTS.md` forbids it outright. A comment states the code's - permanent condition, not its history. Put it in the commit message. -- **Investigation transcript.** The empirical detail that convinced *you* is not - what the next reader needs. They need the mutation and the expected failure. +Do not narrate investigation history in the test. A nearby mutation that looked valid but stayed green may be recorded when that negative result prevents repeated work. -The one extension worth its lines is a **negative** result: naming a nearby edit -that looks like a valid mutation but is NOT one (because it is already guarded, or -because it reddens a sibling test instead). That stops the next reader repeating a -dead end, and it cannot be recovered from the code. +When a test resists an isolated mutation, classify it before acting: -Also add one line per new test to the commit body: `RCR: ← `. -That makes `git log --grep=RCR` the audit surface. - -**UNFALSIFIABLE — the one honest exemption.** Some correct tests provably have no -one-line mutation. The commonest case is **double-guarded validation**: an -unconfigured object trips two independent guards, so disabling either leaves the -other throwing. Deleting such a test would lose real coverage, so it is exempt — -but only on the same terms as §13, never as a shrug: - -```csharp -// RCR: none exists — trips both and ; disabling either -// leaves the other throwing (verified). Double-covered, not single-line falsifiable. -``` - -The reason must be falsifiable and must record that a mutation was actually tried -and observed green. "Couldn't find one" is not a reason — that is an unfinished RCR, -not an exemption. - -**Verdicts for a test that resists mutation.** Work out which of four it is; they -have different answers: - -| Finding | Test | Action | +| Verdict | Meaning | Action | |---|---|---| -| **A3 reject** — no line in `Runtime/` or `Editor/` participates; the assertion is C#- or Unity-guaranteed | pins nothing, ever | **Delete** | -| **A5 duplicate** — the only mutation that reddens it already belongs to a sibling | pins nothing new | **Delete**, naming the surviving sibling in the commit body | -| **D2 overclaim** — the name promises behaviour the body cannot detect | name is a lie | **Strengthen the assertion**, or rename to what it actually checks | -| **UNFALSIFIABLE** — real behaviour, but double-guarded or otherwise unbreakable one line at a time | valid | **Keep**, with the exemption comment above | -| **SHARED-PATH** — no unique one-line pin, but the test was *observed* reddening under a broader mutation | valid | **Keep**, recording the covering mutation and its blast radius | - -**SHARED-PATH exists because blast radius measures specificity, not value.** A test that -only reddens under a broad mutation still catches that regression — an integration test -that dies when `UiService.CloseUi` is gutted is doing its job, even though no single line -is *its* line. Without this row the table offers only delete-or-strengthen, and such tests -get deleted for the crime of being integration tests. - -```csharp -// ADMIT: exercises 's ; no unique one-line pin. -// RCR: no isolated mutation — reddens under 's mutation (radius N, verified). -// Shared-path coverage, not a duplicate. -``` - -The radius must be a **recorded observation**, not an estimate. This is also the row most -easily abused: "some mutation somewhere reddened it" is not the standard. Distinguish it -from A5 by asking what the covering mutation actually broke — if it broke the one narrow -guard the sibling owns, this is a duplicate; if it broke a path both tests legitimately -traverse, this is shared-path coverage. - -A cluster of tests that all die to the same broad mutation is **over-provisioned, not -individually worthless**. Thinning it is a deliberate editorial decision made by a human -looking at what each assertion adds — never an automatic consequence of the verdict pass. - -**A3 is checked first, and it is the commonest way the exemption gets abused.** -UNFALSIFIABLE is for behaviour this package genuinely owns but cannot be broken one -line at a time. It is *never* for behaviour the package does not own. The tell is in -the reason itself: if you find yourself writing "no line in Runtime/ participates", -"the only edit is a compile error", or "these are C#'s zero-init values", you have -found an A3 reject and the verdict is **delete** — a field-only struct's assignment -and default values are the language's guarantees, not yours. Writing that sentence -under an UNFALSIFIABLE heading launders a test §1 would never have admitted. - -Prove the class before acting. An A5 duplicate is confirmed when the sibling's -mutation is observed reddening both; a D2 overclaim is confirmed when the mutation -the name implies leaves the test green; an A3 reject is confirmed when no production -symbol appears anywhere in the causal chain behind the assertion. - -**Two consequences, stated so RCR does not become theatre:** - -- A test with no `// RCR:` line — and no UNFALSIFIABLE exemption — is not trusted - coverage. In an audit it is a suspect by default. **`Smoke/` is exempt here too**, on the - same directory basis as §1: its defect class is "the assembly no longer loads", which has - no one-line mutation, so demanding an RCR line there flags those fixtures forever. The - exemption is the directory, not the assertion shape. -- **"Unannotated" is three states, not one, and they need different actions.** A test with no - `// RCR:` line may have been (a) observed RED with the write-back lost, (b) seen reddening - only as collateral inside another test's blast radius, or (c) never probed. Only (c) needs a - probe; (a) needs the recorded observation written back; (b) is SHARED-PATH evidence, not a - unique pin. Check `.test-all/rcr/` before probing, and never write prepared annotation text - without a matching `RED-OK` for that test — prepared text also exists for tests that were - never probed, and writing it fabricates a verified claim. -- **Benchmarks are included, inverted:** a performance test must be observed - *changing its number* when the measured operation is removed from the measured - body. A benchmark whose measured region does not contain the workload is a - tautology in `Measure` clothing. - -## 3. Placement Rules - -Not yet documented — this package has not been through a test audit. There is a -single `Tests/Editor/` assembly and no PlayMode tests today. See the parent -[`AGENTS.md`](../AGENTS.md) for runtime architecture until this section is filled in. - -## 4. Namespace and Suppression - -Not yet documented — see existing files under `Tests/Editor/` for the current -(unaudited) convention. - -## 5. Naming - -Not yet documented. - -## 6. Mock / Helper Types - -Not yet documented. Note: NSubstitute is referenced in this package's test asmdef. - -## 7. Black-Box / Reflection Policy - -Not yet documented. Note: there is no `InternalsVisibleTo` grant from `Runtime/` -to the test assembly in this package as of this writing — verify before assuming -internal access is available. - -## 8. Fields and Setup - -Not yet documented. - -## 9. Assertion Style - -Not yet documented. - -## 10. PlayMode Test Cleanup - -None — this package has no PlayMode assembly. - -## 11. Performance Tests - -Not yet documented. No dedicated performance fixtures exist today. - -## 12. Test Directory Layout - -| Directory | Contents | -|---|---| -| `Tests/Editor/` | The package's entire automated suite (EditMode only) | - -## 13. Coverage Register - -**Baseline — runtime assembly: 84.0% (862/1025), measured 2026-08-04.** -This package has no Editor assembly. -Repo-wide runtime coverage is **74.1% (6609/8922)** across all 11 assemblies. - -Regenerate with `Tools/coverage.sh`, which prints the runtime/Editor split. Steer by -the **runtime** figure: Editor code is ~48% of coverable lines and accepted-untestable, -so the combined number (41.1%) can never meaningfully move. Sanity-check any rerun by -confirming `MathfloatP` reports ~1002 coverable lines — a smaller figure means -`-debugCodeOptimization` was missing and the denominator silently shrank ~40%. - - -Every untested symbol worth naming is ACCEPTED (justified — do not re-report), -OPEN (a real gap, owed a test), or CLOSED (the gap was filled). An untested symbol -in none of the three is an audit finding. - -**A CLOSED row must name the commit AND the observation that closed it, including the -environment the observation came from.** A row closed on "the fix landed" is still OPEN: -the fix is the edit, the closure is the evidence. This is what kept the uiservice A6 row -open until the Editor half ran — the edit was in and batchmode was green, and neither of -those was the thing in doubt. - -**Closing a row means re-deriving its claim against current source, never reading the -commit that claimed to fix it.** Re-check every symbol and fixture the row names. A partial -fix and a complete one produce the same green suite and the same confident commit message, -so the commit cannot be the evidence for its own completeness. Recorded instance: the -mobileservices editor-static row nearly closed on a commit that genuinely did stop fixtures -inheriting statics — for two of the three fixtures the row named. The third was found by -grepping which fixtures touch each static, and it was passing only because its siblings -happened to restore the static in their `finally` blocks. +| **A3 reject** | No package production behavior participates. | Delete the test. | +| **A5 duplicate** | The same narrow mutation already belongs to a sibling. | Delete it and name the surviving sibling in review/commit context. | +| **D2 overclaim** | The mutation implied by the name leaves the body green. | Strengthen or rename. | +| **UNFALSIFIABLE** | Real package behavior is double-guarded or cannot be broken by a safe isolated edit. | Keep only after attempted mutations are recorded with the specific reason. | +| **SHARED-PATH** | A broader mutation reddens this legitimate integration path together with siblings. | Keep, recording the observed mutation and blast radius. | -An ACCEPTED row needs one of exactly three falsifiable reasons: -- **(i) no branching** — zero conditionals, so there is no behaviour to pin. -- **(ii) engine-owned** — the assertion would target Unity/OS behaviour - (`[DllImport]`, `AndroidJavaObject`, Addressables statics). -- **(iii) harness-impossible** — the state cannot be fabricated in EditMode or - PlayMode, **with the specific blocker named**. +Unannotated tests have three possible histories: observed RED with lost write-back, collateral RED under another test's mutation, or never probed. Check `.test-all/rcr/` before probing and never write prepared annotation text without matching observed evidence. Mutation records stay under `.test-all/rcr/`, not `/tmp`. -"Low value", "hard to test", and "covered by manual QA" are NOT valid reasons. If -none of the three applies, the row is OPEN. +Benchmarks use the inverted check: removing the workload from the measured body must materially change the result. Run the actual test assembly; a plain Unity open does not compile assemblies constrained by `UNITY_INCLUDE_TESTS`. + -ACCEPTED is dated and **expires on edit**: if the symbol's file changes, the -reason is re-checked in that PR. A `(i) no branching` row is void the moment -someone adds an `if`. +## Current suite -OPEN is the only place a deletion may park coverage. A test removed for weakness -either had a stronger sibling (named in the commit body) or leaves an OPEN row. -The count of OPEN rows is the honest coverage-debt number. +- All tests live under `Tests/Editor/` in `GameLovers.Statechart.Editor.Tests`; there is no PlayMode or performance assembly. +- The test assembly references Statechart, UniTask, NUnit, and NSubstitute. +- There is no runtime `InternalsVisibleTo` grant. Test through the public statechart interfaces unless an intentional assembly-boundary change adds one. -| Symbol (file:line) | State | Reason / Owed | Recorded | -| 8 production edits reddening only collaterally (`Runtime/**State.cs`) | OPEN | Measured 2026-08-04 from `.test-all/rcr/unowned-edits.json`: 8 edits produced RED but never an `isolated` verdict, spread thinly (`LeaveState.cs` 2, `SplitState.cs` 2, `WaitState.cs` 1). Low enough to be noise rather than a pattern; recorded for completeness so the number is not rediscovered as a finding. | 2026-08-04 | -|---|---|---|---| +## Package conventions -Empty — this package has not yet been through a coverage audit. Do not assume an -untested symbol here is accepted; it is simply unreviewed. +- Use the existing `GameLoversEditor.StatechartMachine.Tests` namespace and singular `{Subject}Test` fixture names. +- Callback collaborators use the shared `IMockCaler`/NSubstitute pattern. Avoid new helper abstractions when a local callback counter is sufficient. +- Setup graphs must reuse event instances; do not accidentally test name equality with freshly constructed events. +- Tests for validation exceptions run in the Editor configuration where validation is compiled. They must not imply release-build enforcement. +- Async waiting tests distinguish `IWaitState` event behavior from `ITaskWaitState` queue/exit behavior. -## 14. Update Policy +## Verification -Update this file when this package is next audited for test coverage, and when -§1/§2 change upstream (propagate to all six `Tests/AGENTS.md` files in the same -session). +- Run the Editor test assembly after changes to transitions, nesting, split completion, waits, leave behavior, or validation. +- Add PlayMode only if a new production behavior genuinely requires frames or Unity object lifecycle; do not create it for organizational symmetry. +- Update this guide only when the assembly, placement, helper, or stable test convention changes. From f22d348920da09d9e9ae9a0521104e5ff0d091d9 Mon Sep 17 00:00:00 2001 From: CoderGamester Date: Thu, 27 Aug 2026 10:26:06 +0300 Subject: [PATCH 08/17] docs: slim CLAUDE wrappers to @AGENTS.md --- CLAUDE.md | 11 ----------- Tests/CLAUDE.md | 11 ----------- 2 files changed, 22 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index f642129..43c994c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,12 +1 @@ -# Claude Code Guide — Statechart - -This package's contributor/agent guide lives in `AGENTS.md`. -Claude Code will automatically import it below. - @AGENTS.md - -## Claude-Specific Notes - -- Treat `AGENTS.md` as the source of truth. -- If anything in this file appears to conflict with `AGENTS.md`, prefer `AGENTS.md`. -- For user-facing usage, see `README.md`. diff --git a/Tests/CLAUDE.md b/Tests/CLAUDE.md index dc2dc03..43c994c 100644 --- a/Tests/CLAUDE.md +++ b/Tests/CLAUDE.md @@ -1,12 +1 @@ -# Claude Code Guide — GameLovers Statechart Tests - -This folder's testing conventions live in `AGENTS.md`. -Claude Code will automatically import it below. - @AGENTS.md - -## Claude-Specific Notes - -- Treat `AGENTS.md` as the source of truth. -- If anything in this file appears to conflict with `AGENTS.md`, prefer `AGENTS.md`. -- For package-level architecture and runtime gotchas, see `../AGENTS.md`. From 3088fd07943f17e815db53f60dc4fe7a500e38a8 Mon Sep 17 00:00:00 2001 From: CoderGamester Date: Mon, 14 Sep 2026 13:00:44 +0300 Subject: [PATCH 09/17] fix(tests): re-point the RCR anchors at the production symbol A whole-file rename prefixed this fixture's activity field with an underscore and carried the prefix into two RCR anchors and a lambda parameter. The anchors named `if (!_activity.IsCompleted)`, which occurs nowhere in production: Runtime/Internal/WaitActivity.cs AreInnerCompleted reads `if (!activity.IsCompleted)` over its inner activities. A lambda parameter is its own scope, and its siblings in this file already use waitActivity. The shared block now says the harness already prints the fixture count, that the post-fix observation is one re-run of the same probe, and that correcting an existing ADMIT or RCR line is itself a claim about production which must be read and re-checked. Edited identically in all six packages; Tools/lint-agent-guides.py fails if they diverge. Co-Authored-By: Claude Opus 5 --- Tests/AGENTS.md | 5 +++-- Tests/Editor/StatechartWaitTest.cs | 6 +++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/Tests/AGENTS.md b/Tests/AGENTS.md index 7780ec1..b9b303f 100644 --- a/Tests/AGENTS.md +++ b/Tests/AGENTS.md @@ -29,11 +29,12 @@ Fixtures under `Smoke/` are exempt from A1/A2 and may assert construction/bootst Every new or strengthened behavioral test must be observed failing once against a plausible production mutation before commit: -1. Run the new test against normal production code and observe GREEN. +1. Run the new test against normal production code and observe GREEN. The harness prints `baseline green: N test cases`; that line is the fixture count, not a reason to run it again. 2. Preserve the exact working patch or use an isolated worktree; then apply the A2 mutation. Never restore a dirty file from `HEAD`. 3. Run the smallest attributable filter. RED must come from the intended assertion with a diagnostic failure, not a compile error or unrelated `NullReferenceException`. -4. Restore the saved production state, confirm the mutation is gone without losing other edits, and observe GREEN again. +4. Restore the saved production state, confirm the mutation is gone without losing other edits, and observe GREEN again as one re-run of the same filtered probe. 5. Record the observation on the test using `file + symbol`, never a line number. +6. Correcting an existing `ADMIT`/`RCR` line is itself a claim about production: read the symbol it names, re-run the mutation when the claim is about RED, and run `python3 Tools/rcr-anchor-check.py` before committing. Use this compact form, targeting four lines and never exceeding six: diff --git a/Tests/Editor/StatechartWaitTest.cs b/Tests/Editor/StatechartWaitTest.cs index a03b76b..4a6422c 100644 --- a/Tests/Editor/StatechartWaitTest.cs +++ b/Tests/Editor/StatechartWaitTest.cs @@ -53,7 +53,7 @@ public async Task SimpleTest() [Test] // ADMIT: WaitActivity.AreInnerCompleted requires EVERY split child to report IsCompleted before the // parent _activity counts as done, so completing both children releases the wait. - // RCR: WaitActivity.cs AreInnerCompleted — change `if (!_activity.IsCompleted)` to `if (true)` (no + // RCR: WaitActivity.cs AreInnerCompleted — change `if (!activity.IsCompleted)` to `if (true)` (no // child ever counts as complete) → RED (the chart never advances even with both completed). The // on-hold sibling stays green: it expects no advance either way. public async Task SplitActivity_CompleteBoth_Success() @@ -92,7 +92,7 @@ public async Task SplitActivity_CompleteBoth_Success() [Test] // ADMIT: WaitActivity.IsCompleted ANDs the parent's own _completed flag with AreInnerCompleted(), so // one finished child out of two leaves the chart waiting rather than advancing early. - // RCR: WaitActivity.cs AreInnerCompleted — change `if (!_activity.IsCompleted)` to `if (false)` so + // RCR: WaitActivity.cs AreInnerCompleted — change `if (!activity.IsCompleted)` to `if (false)` so // every child counts as done → RED (the chart advances with one child still outstanding). Dropping // the inner term from IsCompleted instead does NOT redden this: the parent's own _completed is what // the surviving term reads, and Complete() has already set it. @@ -167,7 +167,7 @@ public void WaitState_EventTriggerWithoutTarget_OnlyEvokesOnTransition() var final = SetupSimpleFlow(factory, waiting); waiting.OnEnter(() => _caller.StateOnEnterCall(0)); - waiting.WaitingFor(_activity => {}).OnTransition(() => _caller.OnTransitionCall(1)).Target(final); + waiting.WaitingFor(waitActivity => { }).OnTransition(() => _caller.OnTransitionCall(1)).Target(final); waiting.Event(_event).OnTransition(() => _caller.OnTransitionCall(2)); waiting.OnExit(() => _caller.StateOnExitCall(0)); }); From 65338a3d011339120cc02b8f35cda22a5e0ca7cb Mon Sep 17 00:00:00 2001 From: CoderGamester Date: Mon, 16 Nov 2026 18:13:53 +0200 Subject: [PATCH 10/17] feat: add the Statechart Debugger, observability API and Game Flow sample - Run-to-completion event queue; Pause stops mid-chain; Reset and Dispose abandon queued events, pending waits and tasks, and cancel token-aware tasks. - TaskWait faults complete the state; task completions resume on the main thread. - Split action-only events keep inner waits running. - New read-only topology (RootRegion), GetActiveStates, Traced trace stream, Name, Dispose, and Mermaid/active-path export. CurrentState is removed. - Statechart Debugger window with three side-by-side views: live nested chart, Graph Toolkit graph (6000.6+), and state tree with trace history. - Game Flow sample covering every state kind. - Deterministic tests without frame yields, plus lifecycle and observability suites. - UniTask 2.5.11 and the UIElements module are declared dependencies. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 33 +- CHANGELOG.md | 307 ++++++++++-------- Editor.meta | 8 + Editor/AGENTS.md | 16 + Editor/AGENTS.md.meta | 7 + Editor/AssemblyInfo.cs | 4 + Editor/AssemblyInfo.cs.meta | 2 + Editor/CLAUDE.md | 1 + Editor/CLAUDE.md.meta | 7 + Editor/GameLovers.Statechart.Editor.asmdef | 18 + .../GameLovers.Statechart.Editor.asmdef.meta | 7 + Editor/GraphToolkit.meta | 8 + ...vers.Statechart.Editor.GraphToolkit.asmdef | 21 ++ ...Statechart.Editor.GraphToolkit.asmdef.meta | 7 + Editor/GraphToolkit/StatechartDebugGraph.cs | 37 +++ .../GraphToolkit/StatechartDebugGraph.cs.meta | 11 + Editor/GraphToolkit/StatechartGraphView.cs | 280 ++++++++++++++++ .../GraphToolkit/StatechartGraphView.cs.meta | 11 + Editor/LiveChartView.cs | 159 +++++++++ Editor/LiveChartView.cs.meta | 2 + Editor/StatechartDebugger.uss | 167 ++++++++++ Editor/StatechartDebugger.uss.meta | 12 + Editor/StatechartDebuggerWindow.cs | 296 +++++++++++++++++ Editor/StatechartDebuggerWindow.cs.meta | 2 + Editor/TreeTraceView.cs | 144 ++++++++ Editor/TreeTraceView.cs.meta | 2 + README.md | 110 +++++-- Runtime/AssemblyInfo.cs | 5 + Runtime/AssemblyInfo.cs.meta | 11 + Runtime/IState.cs | 22 +- Runtime/Internal/ChoiceState.cs | 18 +- Runtime/Internal/FinalState.cs | 11 +- Runtime/Internal/InitialState.cs | 13 +- Runtime/Internal/LeaveState.cs | 11 +- Runtime/Internal/NestState.cs | 3 + Runtime/Internal/SimpleState.cs | 18 +- Runtime/Internal/SplitState.cs | 33 +- Runtime/Internal/StateFactory.cs | 2 +- Runtime/Internal/StateInternal.cs | 163 ++++++---- Runtime/Internal/StatechartRegistry.cs | 129 ++++++++ Runtime/Internal/StatechartRegistry.cs.meta | 11 + Runtime/Internal/StatechartTopologyBuilder.cs | 95 ++++++ .../StatechartTopologyBuilder.cs.meta | 11 + Runtime/Internal/StatechartUtils.cs | 22 +- Runtime/Internal/TaskWaitState.cs | 111 +++++-- Runtime/Internal/Transition.cs | 6 +- Runtime/Internal/TransitionState.cs | 13 +- Runtime/Internal/WaitState.cs | 48 +-- Runtime/Statechart.cs | 271 +++++++++++++++- Runtime/StatechartExport.cs | 171 ++++++++++ Runtime/StatechartExport.cs.meta | 11 + Runtime/StatechartTopology.cs | 180 ++++++++++ Runtime/StatechartTopology.cs.meta | 11 + Runtime/StatechartTrace.cs | 90 +++++ Runtime/StatechartTrace.cs.meta | 11 + Samples~/GameFlow/GameFlow.unity | 279 ++++++++++++++++ Samples~/GameFlow/GameFlow.unity.meta | 7 + Samples~/GameFlow/README.md | 25 ++ Samples~/GameFlow/README.md.meta | 7 + Samples~/GameFlow/Scripts.meta | 8 + Samples~/GameFlow/Scripts/GameFlowSample.cs | 237 ++++++++++++++ .../GameFlow/Scripts/GameFlowSample.cs.meta | 2 + ...eLovers.Statechart.Samples.GameFlow.asmdef | 17 + ...rs.Statechart.Samples.GameFlow.asmdef.meta | 7 + Samples~/GameFlow/UI.meta | 8 + Samples~/GameFlow/UI/GameFlow.uss | 114 +++++++ Samples~/GameFlow/UI/GameFlow.uss.meta | 12 + Samples~/GameFlow/UI/GameFlow.uxml | 28 ++ Samples~/GameFlow/UI/GameFlow.uxml.meta | 10 + .../GameFlow/UI/GameFlowPanelSettings.asset | 54 +++ .../UI/GameFlowPanelSettings.asset.meta | 8 + Samples~/GameFlow/UI/GameFlowTheme.tss | 1 + Samples~/GameFlow/UI/GameFlowTheme.tss.meta | 12 + Tests/AGENTS.md | 7 +- .../Editor/{IMockCaler.cs => IMockCaller.cs} | 0 ...IMockCaler.cs.meta => IMockCaller.cs.meta} | 0 Tests/Editor/StatechartLifecycleTest.cs | 275 ++++++++++++++++ Tests/Editor/StatechartLifecycleTest.cs.meta | 11 + .../StatechartNestSplit_IntegrationTest.cs | 43 +-- Tests/Editor/StatechartObservabilityTest.cs | 174 ++++++++++ .../StatechartObservabilityTest.cs.meta | 11 + Tests/Editor/StatechartTaskWaitTest.cs | 68 +--- Tests/Editor/StatechartTest.cs | 12 +- Tests/Editor/StatechartWaitTest.cs | 10 +- package.json | 14 +- 85 files changed, 4187 insertions(+), 454 deletions(-) create mode 100644 Editor.meta create mode 100644 Editor/AGENTS.md create mode 100644 Editor/AGENTS.md.meta create mode 100644 Editor/AssemblyInfo.cs create mode 100644 Editor/AssemblyInfo.cs.meta create mode 100644 Editor/CLAUDE.md create mode 100644 Editor/CLAUDE.md.meta create mode 100644 Editor/GameLovers.Statechart.Editor.asmdef create mode 100644 Editor/GameLovers.Statechart.Editor.asmdef.meta create mode 100644 Editor/GraphToolkit.meta create mode 100644 Editor/GraphToolkit/GameLovers.Statechart.Editor.GraphToolkit.asmdef create mode 100644 Editor/GraphToolkit/GameLovers.Statechart.Editor.GraphToolkit.asmdef.meta create mode 100644 Editor/GraphToolkit/StatechartDebugGraph.cs create mode 100644 Editor/GraphToolkit/StatechartDebugGraph.cs.meta create mode 100644 Editor/GraphToolkit/StatechartGraphView.cs create mode 100644 Editor/GraphToolkit/StatechartGraphView.cs.meta create mode 100644 Editor/LiveChartView.cs create mode 100644 Editor/LiveChartView.cs.meta create mode 100644 Editor/StatechartDebugger.uss create mode 100644 Editor/StatechartDebugger.uss.meta create mode 100644 Editor/StatechartDebuggerWindow.cs create mode 100644 Editor/StatechartDebuggerWindow.cs.meta create mode 100644 Editor/TreeTraceView.cs create mode 100644 Editor/TreeTraceView.cs.meta create mode 100644 Runtime/AssemblyInfo.cs create mode 100644 Runtime/AssemblyInfo.cs.meta create mode 100644 Runtime/Internal/StatechartRegistry.cs create mode 100644 Runtime/Internal/StatechartRegistry.cs.meta create mode 100644 Runtime/Internal/StatechartTopologyBuilder.cs create mode 100644 Runtime/Internal/StatechartTopologyBuilder.cs.meta create mode 100644 Runtime/StatechartExport.cs create mode 100644 Runtime/StatechartExport.cs.meta create mode 100644 Runtime/StatechartTopology.cs create mode 100644 Runtime/StatechartTopology.cs.meta create mode 100644 Runtime/StatechartTrace.cs create mode 100644 Runtime/StatechartTrace.cs.meta create mode 100644 Samples~/GameFlow/GameFlow.unity create mode 100644 Samples~/GameFlow/GameFlow.unity.meta create mode 100644 Samples~/GameFlow/README.md create mode 100644 Samples~/GameFlow/README.md.meta create mode 100644 Samples~/GameFlow/Scripts.meta create mode 100644 Samples~/GameFlow/Scripts/GameFlowSample.cs create mode 100644 Samples~/GameFlow/Scripts/GameFlowSample.cs.meta create mode 100644 Samples~/GameFlow/Scripts/GameLovers.Statechart.Samples.GameFlow.asmdef create mode 100644 Samples~/GameFlow/Scripts/GameLovers.Statechart.Samples.GameFlow.asmdef.meta create mode 100644 Samples~/GameFlow/UI.meta create mode 100644 Samples~/GameFlow/UI/GameFlow.uss create mode 100644 Samples~/GameFlow/UI/GameFlow.uss.meta create mode 100644 Samples~/GameFlow/UI/GameFlow.uxml create mode 100644 Samples~/GameFlow/UI/GameFlow.uxml.meta create mode 100644 Samples~/GameFlow/UI/GameFlowPanelSettings.asset create mode 100644 Samples~/GameFlow/UI/GameFlowPanelSettings.asset.meta create mode 100644 Samples~/GameFlow/UI/GameFlowTheme.tss create mode 100644 Samples~/GameFlow/UI/GameFlowTheme.tss.meta rename Tests/Editor/{IMockCaler.cs => IMockCaller.cs} (100%) rename Tests/Editor/{IMockCaler.cs.meta => IMockCaller.cs.meta} (100%) create mode 100644 Tests/Editor/StatechartLifecycleTest.cs create mode 100644 Tests/Editor/StatechartLifecycleTest.cs.meta create mode 100644 Tests/Editor/StatechartObservabilityTest.cs create mode 100644 Tests/Editor/StatechartObservabilityTest.cs.meta diff --git a/AGENTS.md b/AGENTS.md index 2c5db66..c2b4fb3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,35 +4,44 @@ This guide adds package-specific rules to the host repository guide. Consumer us ## Scope -- Package: `com.gamelovers.statechart`; minimum Unity version and dependencies are authoritative in `package.json`. -- One runtime assembly implements hierarchical statecharts with nested and parallel regions, events, choices, callback waits, and Task/UniTask waits. -- There is no Editor assembly or package sample. This package is render-pipeline-neutral. -- Public contracts live at `Runtime/`; implementations under `Runtime/Internal/` remain internal. +- Package: `com.gamelovers.statechart`; minimum Unity version and dependencies are authoritative in `package.json`. Supported streams are 6000.0, 6000.3 and 6000.6. +- `GameLovers.Statechart` (runtime) implements hierarchical statecharts with nested and parallel regions, events, choices, callback waits, Task/UniTask waits, and the read-only topology, active-state and trace API. +- `GameLovers.Statechart.Editor` holds the Statechart Debugger; `GameLovers.Statechart.Editor.GraphToolkit` holds view B and compiles only on 6000.6+. +- `Samples~/GameFlow` is the single package sample. This package is render-pipeline-neutral. +- Public contracts live at `Runtime/`; implementations under `Runtime/Internal/` remain internal. `Runtime/AssemblyInfo.cs` grants internals to the Editor, Graph Toolkit and Editor test assemblies only. +- Before reading, editing, or creating any file in `Editor/`, you **MUST** read [Editor/AGENTS.md](Editor/AGENTS.md) first. ## Statechart invariants -- A `Statechart` is fully defined by its constructor setup closure. Runtime mutation of the state graph is unsupported, and every region requires exactly one initial state. -- `Trigger` is a no-op until `Run()` and while paused. `Pause()` preserves the active position. `Reset()` returns to the initial state without changing the run/pause state. +- A `Statechart` is fully defined by its constructor setup closure. Runtime mutation of the state graph is unsupported, and every region requires exactly one initial state. The public topology (`RootRegion`) is built once at the end of the constructor. +- `Trigger` is a no-op until `Run()` and while paused. `Pause()` preserves the active position and stops a chain of automatic transitions mid-way when called from a callback. +- Events are processed run to completion: an event triggered while `MoveNext` is processing is queued and drained after the current step. Do not reintroduce re-entrant processing. +- `Reset()` returns to the initial state without exit callbacks or a run/pause change. It increments the chart generation, drops queued events and cancels the chart token, so stale wait or task completions are ignored. `Dispose()` does the same, then stops the chart for good and unregisters it. - Statechart events compare by generated instance id, not by name. Reuse one event instance for one logical event. -- Every transition must name a target. A choice with no satisfied condition remains in the choice state. +- Event transitions on simple, wait, nest and split states may omit a target to run an action only; such an event leaves inner waits running. Initial, transition, choice, leave and completion transitions need a target. A choice with no satisfied condition remains in the choice state. - `Nest` completes one sequential child region. `Split` completes only after all parallel child regions finish. - `NestedStateData` separately controls whether leaving a nested region executes the parent nest state's exit callback and the child final state's enter callback. The plain setup-closure overload enables both; preserve the distinction when changing leave/completion behavior. - `Leave` exits exactly one region layer and bypasses the current nest/split completion transition. -- `IWaitState` may process events and uses `IWaitActivity` completion. `ITaskWaitState` cannot process events while awaiting its Task/UniTask; ancestor exit waits for it and queues intervening events. +- `IWaitState` may process events and uses `IWaitActivity` completion. `ITaskWaitState` cannot process events while awaiting its task; ancestor exit waits for it and queues intervening events. +- A faulted task completes its `TaskWait` state after the fault is reported. Task completions resume on the main thread, and a `Task` completing on the main thread resumes inline; keep `AwaitTask` rather than `AsUniTask`, which posts to a later frame. - When an active callback wait is abandoned by an ancestor region exit, complete its outstanding inner activities rather than leaving them dangling. Task waits instead delay the exit until the task completes. +- Every observable step goes through `StateInternal.Trace` / `Statechart.Emit`. `LogsEnabled` formats those traces; do not add separate `Debug.Log` paths. With no `Traced` subscriber and logs off, nothing is formatted. +- `StatechartRegistry` is Editor-only, holds charts weakly and records trace history without a chart reference. Runtime game logic must not depend on it. - Validation runs only under `UNITY_EDITOR || DEBUG`. Do not treat release-build absence of validation as a supported malformed graph. -- `CurrentState` is Editor-only. Runtime game logic must not depend on it. ## Change placement -- A new state type requires a public capability-composed interface, an internal implementation, a factory method on `IStateFactory`, and the matching `StateFactory` implementation. +- A new state type requires a public capability-composed interface, an internal implementation with a `StateKind` value and `CollectTransitions`, a factory method on `IStateFactory`, and the matching `StateFactory` implementation. Update `StatechartExport` and the debugger views if the kind needs special drawing. - Keep the public surface expressed through narrow capability interfaces in `Runtime/IState.cs`; consumers should not depend on internal concrete states. -- Preserve the existing Task and UniTask overloads when changing async waiting. +- Preserve the existing Task and UniTask overloads, with and without a `CancellationToken`, when changing async waiting. +- Tools read the chart only through `RootRegion`, `GetActiveStates` and `Traced`. Do not add view-specific hooks to the runtime. +- Sample code stays in `Samples~/GameFlow` with its own asmdef; package assemblies never reference it. After changing `Samples~`, refresh and validate the imported copy as the host guide requires. - Before changing anything under `Tests/`, read `Tests/AGENTS.md`. ## Verification and documentation -- Test lifecycle, transition target validation, nested/split completion, leave depth, and waiting/event ordering when those areas change. +- Test lifecycle, run-to-completion ordering, transition target validation, nested/split completion, leave depth, waiting/event ordering, and trace order when those areas change. - Validation tests must run with Editor or DEBUG behavior enabled and must not imply equivalent release-build enforcement. +- Debugger and sample changes need a fresh Play-mode capture with the sample running and the affected view visible; green tests do not prove the views. - Prefer the local UniTask package source under `Library/PackageCache/` for external API questions. - Update `README.md` for public statechart semantics and this guide only for durable invariants or test conventions. diff --git a/CHANGELOG.md b/CHANGELOG.md index 7142cdc..0c0d281 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,148 +1,169 @@ -# Changelog -All notable changes to this package will be documented in this file. - -The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) +# Changelog +All notable changes to this package will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). ## [Unreleased] +**New**: +- Added the Statechart Debugger (*Tools > GameLovers > Statechart Debugger*) with three live views of a running chart: A, nested boxes; B, a Graph Toolkit graph on Unity 6000.6 and newer; and C, a state tree and trace log. +- Added a read-only topology (`IStatechart.RootRegion`, `StateNode`, `RegionNode`, `TransitionEdge`), `GetActiveStates`, `IsActive`, `Name` and `IsRunning` to `IStatechart`. +- Added `IStatechart.Traced`, which publishes every event, exit, transition, enter, fault and lifecycle step in execution order, and `StatechartExport.ToMermaid` / `ToActivePaths` text exports. +- Added a `Statechart(string name, Action setup)` constructor and `IDisposable` support. +- Added `ITaskWaitState.WaitingFor` overloads that receive a `CancellationToken`, cancelled by `Reset()` and `Dispose()`. +- Added the **Game Flow** sample, which uses every state kind. + **Changed**: -- Declared Unity 6000.0 as the package minimum and documented 6000.0.x, 6000.3.x, and 6000.5.x as compatibility reference streams. - -## [0.9.5] - 2026-08-04 - -**Changed**: -- Replaced the Unity Package Starter Kit README with accurate Statechart usage and API guidance based on the package's actual runtime surface. -- Improved public API documentation and automated coverage of existing state creation, transition, nested/split, waiting, and validation behavior; this release does not change runtime behavior. - -## [0.9.4] - 2026-06-26 - -**Fixed** -- Added guard in *Statechart.MoveNext* to halt chained state transitions when the State Chart is paused - -**Changed** -- Removed *openai.yml* GitHub Actions workflow - -## [0.9.3] - 2024-11-13 - -**New** -- Added new *ITaskWaitState.WaitingFor(Func)* method to allow *TaskWaitStates* to hold on *UniTask* type calls - -**Fixed** -- Added *UniTask* to the package to allow the *Statechart* run on WebGL - -## [0.9.2] - 2024-10-25 - -**Fixed** -- Changed the try/catch exceptions to Debug.LogException with a Debug.LogError, to properly show the issues in the Unity console - -## [0.9.1] - 2023-09-04 - -**Fixed** -- Added missing documentation to describe the purpose of the *InnerStateData* and *StateFactoryData* classes. - -## [0.9.0] - 2023-09-02 - -**New** -- Introduced unique identifiers for *IWaitActivity* instances to differentiate between different activities -- Enhanced the *TaskWaitState* class with a new event queuing mechanism to handle events after task completion -- Improved the *SplitState* class to allow pausing/resuming of inner state transitions - -**Changed** -- Updated exception handling across various classes, replacing *MissingMemberException* with *InvalidOperationException* for more appropriate error representation - -## [0.8.0] - 2023-08-03 - -**Changed** -- Change the main class name from *Statemachine* to *Statechart* Change namespace to avoid conflicts to StatechartMachine -- Changed both *ISplitState* and *INestedState* to receive a single parameterized *NestedStateData* to make calls less verbose and ready for future scalability - -## [0.7.0] - 2021-05-04 - -**New** -- Improved State documentations -- Improved State debug logs - -**Changed** -- Removed redundant *SplitFinal* & *SplitExitFinal* methods from *ISplitState*. Now the *Split* method incorporates all possible cases to simplify implementation - -**Fixed** -- Fixed reference checks for *WaitState* -- Fixed *StatechartTaskWaitTest* to work also when multiple tests run in parallel -- Fixed *TaskWaitState* racing condition bug on chained states -- Fixed bug on *WaitState* that when finished instantaneously would execute state transitions multiple times - -## [0.6.0] - 2020-09-29 - -**Changed** -- Renamed *Statechart* to *StateMachine* to avoid namespace conflicts - -**Fixed** -- Fixed *ITaskWaitState* bad tests - -## [0.5.2] - 2020-09-27 - -**New** -- Added *IStatechartEvent* data to the logs -- Added logs to all possible trigger cases -- Added logs to the *ITaskWaitState* and *IWaitState* waiting call method -- Added exception catch to the *ITaskWaitState* and *IWaitState* waiting call method -- Added the possibility to enable logs individually to each *IState* - -## [0.5.1] - 2020-09-24 - -**Fixed** -- Fixed *ITaskWaitState* execution crash - -## [0.5.0] - 2020-09-24 - -**New** -- Added new *ITransitionState* that acts as a non-blocker state between 2 different states - -**Changed** -- Added *IStateEvent* to *ITaskWaitState* to allow event evocation - -**Fixed** -- Fixed potential issue when *ITaskWaitState* & *WaitState* would execute it's flow multiple times when a *INestState* or *ISplitState* would trigger an outside exit event - -## [0.4.0] - 2020-09-22 - -**New** -- Added the possibility to not execute *IStateExit.OnExit* on the current active state when leaving *IStateNest* or *IStateSplit*. -- Added the new *ITaskWaitState* to have a waiter for Task async methods. This state cannot have event triggers, for that use *IWaitState* - -**Changed** -- Separated *IStateSplit.Split* into new method *IStateSplit.SplitFinal* - -## [0.3.0] - 2020-09-06 - -**New** -- Added the possibility to trigger events without a target state. Only *InitialState*, *ChoiceState* & *LeaveState* don't allow it due to the nature of their behaviour. - -## [0.2.0] - 2020-08-27 - -**New** -- Added the possibility to always execute the *FinalState* of a *NestState* and * *SplitState* - -**Changed** -- Splitted the Unit tests in different files to help organization and readability. Now each state has it's own file with only it's set of tests - -**Fixed** -- Now *NestState* and * *SplitState* properly execute their inner *OnExit* calls when they are setup in a chain of nested states - -## [0.1.3] - 2020-01-06 - -**Fixed** -- Removed package dependency - -## [0.1.2] - 2020-01-06 - -**New** -- Added NSubstitute dependency for the Unit Tests - -**Fixed** -- Removed Preview label out of the package version - -## [0.1.0] - 2020-01-05 - -- Initial submission for package distribution +- Declared Unity 6000.0 as the package minimum and 6000.0.x, 6000.3.x and 6000.6.x as the supported streams. +- Raised the UniTask dependency to 2.5.11, the first version whose Editor code compiles on Unity 6000.6, and declared the built-in UIElements module used by the debugger and the sample. +- Events triggered while another event is being processed, for example from an enter callback, are now queued and processed right after it (run to completion) instead of running against the previous state. +- `Reset()` now drops queued events and abandons pending waits and tasks, so their late completion no longer moves the chart. +- `LogsEnabled` now writes one trace line per step, such as `[Statechart 'Player'] Idle -> Jumping on 'Jump'`. +- Null arguments now throw `ArgumentNullException`, and a setup without an initial state throws `InvalidOperationException` instead of `MissingMemberException`. +- **Breaking**: removed the Editor-only `Statechart.CurrentState`; use `GetActiveStates` or the Statechart Debugger instead. + +**Fixed**: +- A `TaskWait` state whose task throws no longer blocks the chart and its parent splits forever; the fault is logged and the state completes. +- `TaskWait` states now resume the chart on the main thread, and a `Task` completing on the main thread resumes it in the same frame. +- Pausing the chart from a callback now stops a chain of automatic transitions until the next `Run()`. +- An action-only event on a nest or split state no longer force-completes the waits inside it. +- Creation stack traces in error logs now start at the code that declared the failing state, and enter-callback errors no longer report themselves as exit errors. + +## [0.9.5] - 2026-08-04 + +**Changed**: +- Replaced the Unity Package Starter Kit README with accurate Statechart usage and API guidance based on the package's actual runtime surface. +- Improved public API documentation and automated coverage of existing state creation, transition, nested/split, waiting, and validation behavior; this release does not change runtime behavior. + +## [0.9.4] - 2026-06-26 + +**Fixed** +- Added guard in *Statechart.MoveNext* to halt chained state transitions when the State Chart is paused + +**Changed** +- Removed *openai.yml* GitHub Actions workflow + +## [0.9.3] - 2024-11-13 + +**New** +- Added new *ITaskWaitState.WaitingFor(Func)* method to allow *TaskWaitStates* to hold on *UniTask* type calls + +**Fixed** +- Added *UniTask* to the package to allow the *Statechart* run on WebGL + +## [0.9.2] - 2024-10-25 + +**Fixed** +- Changed the try/catch exceptions to Debug.LogException with a Debug.LogError, to properly show the issues in the Unity console + +## [0.9.1] - 2023-09-04 + +**Fixed** +- Added missing documentation to describe the purpose of the *InnerStateData* and *StateFactoryData* classes. + +## [0.9.0] - 2023-09-02 + +**New** +- Introduced unique identifiers for *IWaitActivity* instances to differentiate between different activities +- Enhanced the *TaskWaitState* class with a new event queuing mechanism to handle events after task completion +- Improved the *SplitState* class to allow pausing/resuming of inner state transitions + +**Changed** +- Updated exception handling across various classes, replacing *MissingMemberException* with *InvalidOperationException* for more appropriate error representation + +## [0.8.0] - 2023-08-03 + +**Changed** +- Change the main class name from *Statemachine* to *Statechart* Change namespace to avoid conflicts to StatechartMachine +- Changed both *ISplitState* and *INestedState* to receive a single parameterized *NestedStateData* to make calls less verbose and ready for future scalability + +## [0.7.0] - 2021-05-04 + +**New** +- Improved State documentations +- Improved State debug logs + +**Changed** +- Removed redundant *SplitFinal* & *SplitExitFinal* methods from *ISplitState*. Now the *Split* method incorporates all possible cases to simplify implementation + +**Fixed** +- Fixed reference checks for *WaitState* +- Fixed *StatechartTaskWaitTest* to work also when multiple tests run in parallel +- Fixed *TaskWaitState* racing condition bug on chained states +- Fixed bug on *WaitState* that when finished instantaneously would execute state transitions multiple times + +## [0.6.0] - 2020-09-29 + +**Changed** +- Renamed *Statechart* to *StateMachine* to avoid namespace conflicts + +**Fixed** +- Fixed *ITaskWaitState* bad tests + +## [0.5.2] - 2020-09-27 + +**New** +- Added *IStatechartEvent* data to the logs +- Added logs to all possible trigger cases +- Added logs to the *ITaskWaitState* and *IWaitState* waiting call method +- Added exception catch to the *ITaskWaitState* and *IWaitState* waiting call method +- Added the possibility to enable logs individually to each *IState* + +## [0.5.1] - 2020-09-24 + +**Fixed** +- Fixed *ITaskWaitState* execution crash + +## [0.5.0] - 2020-09-24 + +**New** +- Added new *ITransitionState* that acts as a non-blocker state between 2 different states + +**Changed** +- Added *IStateEvent* to *ITaskWaitState* to allow event evocation + +**Fixed** +- Fixed potential issue when *ITaskWaitState* & *WaitState* would execute it's flow multiple times when a *INestState* or *ISplitState* would trigger an outside exit event + +## [0.4.0] - 2020-09-22 + +**New** +- Added the possibility to not execute *IStateExit.OnExit* on the current active state when leaving *IStateNest* or *IStateSplit*. +- Added the new *ITaskWaitState* to have a waiter for Task async methods. This state cannot have event triggers, for that use *IWaitState* + +**Changed** +- Separated *IStateSplit.Split* into new method *IStateSplit.SplitFinal* + +## [0.3.0] - 2020-09-06 + +**New** +- Added the possibility to trigger events without a target state. Only *InitialState*, *ChoiceState* & *LeaveState* don't allow it due to the nature of their behaviour. + +## [0.2.0] - 2020-08-27 + +**New** +- Added the possibility to always execute the *FinalState* of a *NestState* and * *SplitState* + +**Changed** +- Splitted the Unit tests in different files to help organization and readability. Now each state has it's own file with only it's set of tests + +**Fixed** +- Now *NestState* and * *SplitState* properly execute their inner *OnExit* calls when they are setup in a chain of nested states + +## [0.1.3] - 2020-01-06 + +**Fixed** +- Removed package dependency + +## [0.1.2] - 2020-01-06 + +**New** +- Added NSubstitute dependency for the Unit Tests + +**Fixed** +- Removed Preview label out of the package version + +## [0.1.0] - 2020-01-05 + +- Initial submission for package distribution diff --git a/Editor.meta b/Editor.meta new file mode 100644 index 0000000..8e5b539 --- /dev/null +++ b/Editor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3377c39247f77450990dc4ac28d425e5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/AGENTS.md b/Editor/AGENTS.md new file mode 100644 index 0000000..af9f053 --- /dev/null +++ b/Editor/AGENTS.md @@ -0,0 +1,16 @@ +# GameLovers Statechart Editor — Agent Guide + +This guide adds Editor-only rules to the package and host guides. + +## Statechart Debugger + +- `StatechartDebuggerWindow` is a UI Toolkit `EditorWindow` under `Tools/GameLovers/Statechart Debugger`. Its toolbar acts on the selected live chart (Run, Pause, Reset); it never builds a throwaway chart. +- Views A (`LiveChartView`), B (`GraphToolkit/StatechartGraphView`) and C (`TreeTraceView`) read the same three sources: `IStatechart.RootRegion`, `GetActiveStates`, and `StatechartRegistry.Entry.History`. Keep them side-by-side comparable; a view must not need its own runtime data. +- The window refreshes on a 100 ms schedule and repaints views only when `StatechartRegistry.Version` changes. Keep per-refresh work proportional to the chart size and free of allocations beyond the active list. +- Styles live in `StatechartDebugger.uss`, loaded by package path. Use colors that read in both Editor themes. + +## View B and Graph Toolkit + +- `GameLovers.Statechart.Editor.GraphToolkit` is constrained by `UNITY_6000_6_OR_NEWER`, so it is absent on 6000.0 and 6000.3. The window only reaches it through `StatechartDebuggerWindow.GraphViewOpener`; never reference Graph Toolkit types from `GameLovers.Statechart.Editor`. +- Use only the public `Unity.GraphToolkit.Editor` API. Graph Toolkit is a built-in module from 6000.4; do not add `com.unity.graphtoolkit` to any manifest. +- The generated `.statechartdebug` asset under `Assets/StatechartDebugger/` is display-only and regenerated on every open. Live highlighting writes `Node.DefaultColor` and `Wire.WidthOverride` on the open window's graph inside one `UndoBeginRecordGraph`/`UndoEndRecordGraph` pair, only when `StatechartRegistry.Version` changes. On 6000.6.6f1 the window did not redraw `GraphVisualization` fills or unbracketed model changes; re-check that before switching channels. diff --git a/Editor/AGENTS.md.meta b/Editor/AGENTS.md.meta new file mode 100644 index 0000000..fdfda6b --- /dev/null +++ b/Editor/AGENTS.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 259bdb97f2909400293f46a2fa5c7b0a +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/AssemblyInfo.cs b/Editor/AssemblyInfo.cs new file mode 100644 index 0000000..c20d33d --- /dev/null +++ b/Editor/AssemblyInfo.cs @@ -0,0 +1,4 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("GameLovers.Statechart.Editor.GraphToolkit")] +[assembly: InternalsVisibleTo("GameLovers.Statechart.Editor.Tests")] diff --git a/Editor/AssemblyInfo.cs.meta b/Editor/AssemblyInfo.cs.meta new file mode 100644 index 0000000..1ce21dd --- /dev/null +++ b/Editor/AssemblyInfo.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 825824ca165c841a099cf52dc1cae66c \ No newline at end of file diff --git a/Editor/CLAUDE.md b/Editor/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/Editor/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/Editor/CLAUDE.md.meta b/Editor/CLAUDE.md.meta new file mode 100644 index 0000000..42e6aa3 --- /dev/null +++ b/Editor/CLAUDE.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 10586422dbf348ec961d9c877b2b4b21 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/GameLovers.Statechart.Editor.asmdef b/Editor/GameLovers.Statechart.Editor.asmdef new file mode 100644 index 0000000..b17d3a2 --- /dev/null +++ b/Editor/GameLovers.Statechart.Editor.asmdef @@ -0,0 +1,18 @@ +{ + "name": "GameLovers.Statechart.Editor", + "rootNamespace": "", + "references": [ + "GameLovers.Statechart" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} diff --git a/Editor/GameLovers.Statechart.Editor.asmdef.meta b/Editor/GameLovers.Statechart.Editor.asmdef.meta new file mode 100644 index 0000000..4822ee2 --- /dev/null +++ b/Editor/GameLovers.Statechart.Editor.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: e2c76c534fbf148a287d5c3443b4c5f2 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/GraphToolkit.meta b/Editor/GraphToolkit.meta new file mode 100644 index 0000000..dbdd9eb --- /dev/null +++ b/Editor/GraphToolkit.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4b93c97e00e96434385c1629a239e83a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/GraphToolkit/GameLovers.Statechart.Editor.GraphToolkit.asmdef b/Editor/GraphToolkit/GameLovers.Statechart.Editor.GraphToolkit.asmdef new file mode 100644 index 0000000..89af578 --- /dev/null +++ b/Editor/GraphToolkit/GameLovers.Statechart.Editor.GraphToolkit.asmdef @@ -0,0 +1,21 @@ +{ + "name": "GameLovers.Statechart.Editor.GraphToolkit", + "rootNamespace": "", + "references": [ + "GameLovers.Statechart", + "GameLovers.Statechart.Editor" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": false, + "defineConstraints": [ + "UNITY_6000_6_OR_NEWER" + ], + "versionDefines": [], + "noEngineReferences": false +} diff --git a/Editor/GraphToolkit/GameLovers.Statechart.Editor.GraphToolkit.asmdef.meta b/Editor/GraphToolkit/GameLovers.Statechart.Editor.GraphToolkit.asmdef.meta new file mode 100644 index 0000000..223f27e --- /dev/null +++ b/Editor/GraphToolkit/GameLovers.Statechart.Editor.GraphToolkit.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: af46b14a12c1e47e48e21f4d027f6a61 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/GraphToolkit/StatechartDebugGraph.cs b/Editor/GraphToolkit/StatechartDebugGraph.cs new file mode 100644 index 0000000..b3f7370 --- /dev/null +++ b/Editor/GraphToolkit/StatechartDebugGraph.cs @@ -0,0 +1,37 @@ +using System; +using Unity.GraphToolkit.Editor; + +// ReSharper disable CheckNamespace + +namespace GameLovers.StatechartMachine.Editor.GraphToolkit +{ + /// + /// Graph Toolkit asset that mirrors a live statechart's topology for view B. It is generated from code and only + /// used for display; editing it has no effect on the statechart. + /// + [Graph(AssetExtension)] + [Serializable] + internal class StatechartDebugGraph : Graph + { + internal const string AssetExtension = "statechartdebug"; + } + + /// + /// One statechart state. "Out" wires show transitions; dashed "Regions" wires lead to nested regions. + /// + [Serializable] + internal class StatechartStateNode : Node + { + internal const string InPort = "In"; + internal const string OutPort = "Out"; + internal const string RegionsPort = "Regions"; + + /// Declares the In, Out and Regions ports. + protected override void OnDefinePorts(IPortDefinitionContext context) + { + context.AddInputPort(InPort).WithConnectorUI(PortConnectorUI.Arrowhead).Build(); + context.AddOutputPort(OutPort).WithConnectorUI(PortConnectorUI.Arrowhead).Build(); + context.AddOutputPort(RegionsPort).Build(); + } + } +} diff --git a/Editor/GraphToolkit/StatechartDebugGraph.cs.meta b/Editor/GraphToolkit/StatechartDebugGraph.cs.meta new file mode 100644 index 0000000..156d8d8 --- /dev/null +++ b/Editor/GraphToolkit/StatechartDebugGraph.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: a27ccda684964b4ea1999f279d184e7d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/GraphToolkit/StatechartGraphView.cs b/Editor/GraphToolkit/StatechartGraphView.cs new file mode 100644 index 0000000..0810f1b --- /dev/null +++ b/Editor/GraphToolkit/StatechartGraphView.cs @@ -0,0 +1,280 @@ +using System.Collections.Generic; +using System.IO; +using System.Linq; +using GameLovers.StatechartMachine.Internal; +using Unity.GraphToolkit.Editor; +using UnityEditor; +using UnityEngine; + +// ReSharper disable CheckNamespace + +namespace GameLovers.StatechartMachine.Editor.GraphToolkit +{ + /// + /// View B: generates a Graph Toolkit graph from a live chart, opens it, and while the chart runs paints active + /// states bright green and thickens taken transitions. + /// + [InitializeOnLoad] + internal static class StatechartGraphView + { + internal const string AssetFolder = "Assets/StatechartDebugger"; + + private const float ColumnWidth = 260f; + private const float RowHeight = 150f; + private const float WireWidth = 5f; + private const float InactiveDim = 0.45f; + + private static readonly Color _activeColor = new Color(0.25f, 0.95f, 0.45f); + + private static Session _session; + + private sealed class Session + { + public StatechartRegistry.Entry Entry; + public Hash128 GraphId; + public double LastRecordTime = -1; + public int AppliedVersion = -1; + public readonly Dictionary Nodes = new Dictionary(); + public readonly Dictionary States = new Dictionary(); + public readonly List Active = new List(); + } + + private readonly struct NodeIds + { + public readonly Hash128 Node; + public readonly Hash128 In; + public readonly Hash128 Out; + + public NodeIds(Hash128 node, Hash128 inPort, Hash128 outPort) + { + Node = node; + In = inPort; + Out = outPort; + } + } + + static StatechartGraphView() + { + StatechartDebuggerWindow.GraphViewOpener = (chart, entry) => Open(chart, entry); + EditorApplication.update += Update; + } + + /// Generates (or regenerates) the graph asset for and opens it. + internal static string Open(IStatechart chart, StatechartRegistry.Entry entry) + { + var path = $"{AssetFolder}/{Sanitize(chart.Name)}.{StatechartDebugGraph.AssetExtension}"; + + Directory.CreateDirectory(AssetFolder); + _session = new Session { Entry = entry }; + + var graph = GraphDatabase.LoadGraph(path) ?? GraphDatabase.CreateGraph(path); + + graph.UndoBeginRecordGraph("Generate statechart graph"); + + foreach (var node in graph.GetNodes().ToList()) + { + graph.RemoveNode(node); + } + + var nodes = new Dictionary(); + + LayoutRegion(graph, chart.RootRegion, 0f, 0f, nodes); + ConnectTransitions(graph, nodes); + GraphDatabase.SaveGraph(graph); + graph.UndoEndRecordGraph(); + + foreach (var pair in nodes) + { + _session.Nodes[pair.Key] = new NodeIds(pair.Value.ID, + pair.Value.GetInputPortByName(StatechartStateNode.InPort).ID, + pair.Value.GetOutputPortByName(StatechartStateNode.OutPort).ID); + _session.States[pair.Value.ID] = pair.Key; + } + + _session.GraphId = graph.ID; + AssetDatabase.OpenAsset(AssetDatabase.LoadMainAssetAtPath(path)); + + return path; + } + + private static float LayoutRegion(StatechartDebugGraph graph, RegionNode region, float x, float y, + Dictionary nodes) + { + var column = x; + + foreach (var state in region.States) + { + var node = new StatechartStateNode { Position = new Vector2(column, y) }; + + graph.AddNode(node); + node.Title = state.Name; + node.Subtitle = state.Kind.ToString(); + node.Tooltip = state.Path; + node.DefaultColor = ColorFor(state.Kind); + nodes[state] = node; + column += ColumnWidth; + } + + var nextY = y + RowHeight; + + foreach (var state in region.States) + { + foreach (var child in state.Regions) + { + nextY = LayoutRegion(graph, child, nodes[state].Position.x + ColumnWidth * 0.5f, nextY, nodes); + } + } + + return nextY; + } + + private static void ConnectTransitions(StatechartDebugGraph graph, Dictionary nodes) + { + foreach (var pair in nodes) + { + var output = pair.Value.GetOutputPortByName(StatechartStateNode.OutPort); + + foreach (var edge in pair.Key.Transitions) + { + if (edge.Target != null) + { + graph.Connect(output, nodes[edge.Target].GetInputPortByName(StatechartStateNode.InPort)); + } + } + + var regions = pair.Value.GetOutputPortByName(StatechartStateNode.RegionsPort); + + foreach (var region in pair.Key.Regions) + { + if (region.Initial == null) + { + continue; + } + + var input = nodes[region.Initial].GetInputPortByName(StatechartStateNode.InPort); + + graph.Connect(regions, input); + graph.GetWire(regions, input).IsDashed = true; + } + } + } + + private static void Update() + { + if (_session == null || _session.AppliedVersion == StatechartRegistry.Version || + !_session.Entry.TryGetChart(out var chart)) + { + return; + } + + var graph = FindOpenGraph(_session.GraphId); + + if (graph == null) + { + return; + } + + var nodes = new Dictionary(); + + foreach (var node in graph.GetNodes()) + { + if (node is StatechartStateNode stateNode && _session.States.TryGetValue(stateNode.ID, out var state)) + { + nodes[state] = stateNode; + } + } + + chart.GetActiveStates(_session.Active); + + // The graph window redraws authoring changes made inside an undo record; GraphVisualization fills did not + // render on Unity 6000.6, so the highlight is written to the display-only graph itself. + graph.UndoBeginRecordGraph("Statechart Debugger highlight"); + + foreach (var pair in nodes) + { + var color = _session.Active.Contains(pair.Key) ? _activeColor : Dim(ColorFor(pair.Key.Kind)); + + if (pair.Value.DefaultColor != color) + { + pair.Value.DefaultColor = color; + } + } + + foreach (var record in _session.Entry.History) + { + if (record.Time <= _session.LastRecordTime) + { + continue; + } + + _session.LastRecordTime = record.Time; + + if (record.Kind == StatechartTraceKind.Transition && record.State != null && record.Target != null && + nodes.TryGetValue(record.State, out var source) && nodes.TryGetValue(record.Target, out var target)) + { + // Taken transitions stay thick, so the path the chart walked remains visible. + var wire = graph.GetWire(source.GetOutputPortByName(StatechartStateNode.OutPort), + target.GetInputPortByName(StatechartStateNode.InPort)); + + if (wire != null) + { + wire.WidthOverride = WireWidth; + } + } + } + + graph.UndoEndRecordGraph(); + _session.AppliedVersion = StatechartRegistry.Version; + } + + private static Graph FindOpenGraph(Hash128 graphId) + { + foreach (var window in Resources.FindObjectsOfTypeAll()) + { + if (window is IGraphWindow graphWindow && graphWindow.Graph != null && graphWindow.Graph.ID == graphId) + { + return graphWindow.Graph; + } + } + + return null; + } + + private static Color ColorFor(StateKind kind) + { + switch (kind) + { + case StateKind.Initial: + case StateKind.Final: + return new Color(0.55f, 0.55f, 0.55f); + case StateKind.Nest: + case StateKind.Split: + return new Color(0.45f, 0.4f, 0.85f); + case StateKind.Wait: + case StateKind.TaskWait: + return new Color(0.9f, 0.6f, 0.2f); + case StateKind.Choice: + case StateKind.Transition: + case StateKind.Leave: + return new Color(0.2f, 0.65f, 0.75f); + default: + return new Color(0.24f, 0.7f, 0.37f); + } + } + + private static Color Dim(Color color) + { + return new Color(color.r * InactiveDim, color.g * InactiveDim, color.b * InactiveDim); + } + + private static string Sanitize(string name) + { + foreach (var invalid in Path.GetInvalidFileNameChars()) + { + name = name.Replace(invalid, '_'); + } + + return name; + } + } +} diff --git a/Editor/GraphToolkit/StatechartGraphView.cs.meta b/Editor/GraphToolkit/StatechartGraphView.cs.meta new file mode 100644 index 0000000..28800c8 --- /dev/null +++ b/Editor/GraphToolkit/StatechartGraphView.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 067818b5911c448582a49f1bd3a6b235 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Editor/LiveChartView.cs b/Editor/LiveChartView.cs new file mode 100644 index 0000000..4ec9b6f --- /dev/null +++ b/Editor/LiveChartView.cs @@ -0,0 +1,159 @@ +using System.Collections.Generic; +using GameLovers.StatechartMachine.Internal; +using UnityEngine; +using UnityEngine.UIElements; + +// ReSharper disable CheckNamespace + +namespace GameLovers.StatechartMachine.Editor +{ + /// + /// View A: the chart drawn as nested boxes. Nest and split states contain their regions, split regions sit side + /// by side as dashed lanes, and every active state is highlighted. + /// + internal sealed class LiveChartView : VisualElement + { + private const double RecentSeconds = 0.8; + + private readonly Dictionary _elements = new Dictionary(); + private readonly ScrollView _scroll; + + internal LiveChartView() + { + AddToClassList("sc-pane"); + AddToClassList("sc-pane-live"); + + var header = new Label("A · Live chart"); + header.AddToClassList("sc-pane-header"); + Add(header); + + // Vertical only: a bounded width lets each region's boxes wrap onto new rows. + _scroll = new ScrollView(ScrollViewMode.Vertical); + _scroll.AddToClassList("sc-pane-content"); + Add(_scroll); + } + + /// Rebuilds the boxes for , or clears them when null. + internal void SetChart(IStatechart chart) + { + _elements.Clear(); + _scroll.Clear(); + + if (chart != null) + { + _scroll.Add(BuildRegion(chart.RootRegion, false)); + } + } + + /// Highlights states and briefly flashes recently entered ones. + internal void UpdateActive(List active, IReadOnlyCollection history) + { + var recent = new HashSet(); + var now = Time.realtimeSinceStartupAsDouble; + + foreach (var record in history) + { + if (record.Kind == StatechartTraceKind.StateEntered && now - record.Time < RecentSeconds) + { + recent.Add(record.State); + } + } + + foreach (var pair in _elements) + { + pair.Value.EnableInClassList("sc-active", active.Contains(pair.Key)); + pair.Value.EnableInClassList("sc-recent", recent.Contains(pair.Key)); + } + } + + private VisualElement BuildRegion(RegionNode region, bool isLane) + { + var container = new VisualElement(); + + container.AddToClassList("sc-region"); + container.EnableInClassList("sc-lane", isLane); + + foreach (var state in region.States) + { + container.Add(BuildState(state)); + } + + return container; + } + + private VisualElement BuildState(StateNode state) + { + var box = new VisualElement { tooltip = $"{state.Path}\n{state.Kind}" }; + + box.AddToClassList("sc-state"); + box.AddToClassList($"sc-kind-{state.Kind.ToString().ToLowerInvariant()}"); + _elements[state] = box; + + if (state.Kind == StateKind.Initial || state.Kind == StateKind.Final) + { + box.AddToClassList("sc-pseudo"); + box.Add(new Label(state.Kind == StateKind.Initial ? "●" : "◉")); + return box; + } + + var title = new VisualElement(); + title.AddToClassList("sc-state-title"); + title.Add(new Label(state.Name) { name = "name" }); + + if (state.Kind != StateKind.Simple) + { + var badge = new Label(state.Kind.ToString()); + badge.AddToClassList("sc-badge"); + title.Add(badge); + } + + box.Add(title); + + if (state.Regions.Count > 0) + { + var regions = new VisualElement(); + + regions.AddToClassList("sc-regions"); + regions.EnableInClassList("sc-regions-split", state.Kind == StateKind.Split); + + foreach (var region in state.Regions) + { + regions.Add(BuildRegion(region, state.Kind == StateKind.Split)); + } + + box.Add(regions); + } + + foreach (var edge in state.Transitions) + { + if (edge.Kind == TransitionKind.Automatic && edge.Target != null) + { + continue; + } + + var chip = new Label($"{EdgeLabel(edge)} → {edge.Target?.Name ?? "action"}"); + chip.AddToClassList("sc-edge"); + box.Add(chip); + } + + return box; + } + + private static string EdgeLabel(TransitionEdge edge) + { + switch (edge.Kind) + { + case TransitionKind.Event: + return edge.Event.Name; + case TransitionKind.Choice: + return edge.HasCondition ? "if" : "else"; + case TransitionKind.Completion: + return "done"; + case TransitionKind.Leave: + return "leave"; + default: + return "auto"; + } + } + } +} diff --git a/Editor/LiveChartView.cs.meta b/Editor/LiveChartView.cs.meta new file mode 100644 index 0000000..116ddba --- /dev/null +++ b/Editor/LiveChartView.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: d5eb4c35f6a2f429686f0f5d376897dd \ No newline at end of file diff --git a/Editor/StatechartDebugger.uss b/Editor/StatechartDebugger.uss new file mode 100644 index 0000000..e2c21d5 --- /dev/null +++ b/Editor/StatechartDebugger.uss @@ -0,0 +1,167 @@ +.sc-root { + flex-grow: 1; +} + +.sc-chart-menu { + min-width: 160px; +} + +.sc-status { + -unity-text-align: middle-left; + padding: 0 8px; + color: rgb(230, 160, 60); +} + +.sc-status-running { + color: rgb(80, 190, 110); +} + +.sc-empty { + margin: 24px; + white-space: normal; + color: rgba(128, 128, 128, 1); +} + +.sc-body { + flex-grow: 1; + flex-direction: row; +} + +.sc-pane { + flex-grow: 1; + flex-basis: 0; + border-right-width: 1px; + border-right-color: rgba(0, 0, 0, 0.3); +} + +.sc-pane-live { + flex-grow: 2; +} + +.sc-pane-header { + -unity-font-style: bold; + padding: 4px 8px; + background-color: rgba(128, 128, 128, 0.15); +} + +.sc-pane-content { + flex-grow: 1; + padding: 8px; +} + +.sc-region { + flex-direction: row; + flex-wrap: wrap; + align-items: flex-start; +} + +.sc-regions { + flex-direction: column; + margin-top: 4px; +} + +.sc-regions-split { + flex-direction: row; +} + +.sc-lane { + flex-grow: 1; + border-width: 1px; + border-color: rgba(128, 128, 128, 0.6); + border-radius: 4px; + padding: 4px; + margin: 2px; +} + +.sc-state { + border-width: 1px; + border-color: rgba(128, 128, 128, 0.7); + border-radius: 6px; + padding: 4px 6px; + margin: 3px; + min-width: 70px; + background-color: rgba(128, 128, 128, 0.08); +} + +.sc-state-title { + flex-direction: row; + align-items: center; +} + +.sc-state-title > #name { + -unity-font-style: bold; +} + +.sc-badge { + font-size: 9px; + margin-left: 4px; + padding: 0 4px; + border-radius: 3px; + background-color: rgba(128, 128, 128, 0.25); +} + +.sc-edge { + font-size: 10px; + color: rgba(128, 128, 128, 1); +} + +.sc-pseudo { + min-width: 0; + border-radius: 10px; + padding: 0 4px; + align-self: center; +} + +.sc-state.sc-active { + border-width: 2px; + border-color: rgb(60, 180, 95); + background-color: rgba(60, 180, 95, 0.18); +} + +.sc-state.sc-recent { + border-color: rgb(255, 200, 60); +} + +.sc-tree { + flex-grow: 1; + flex-basis: 0; + padding: 4px 0; +} + +.sc-tree-row { + color: rgba(128, 128, 128, 1); +} + +.sc-tree-row.sc-active { + color: rgb(60, 180, 95); + -unity-font-style: bold; +} + +.sc-tree-lane { + font-size: 9px; + color: rgba(128, 128, 128, 0.8); + -unity-font-style: italic; +} + +.sc-trace { + flex-grow: 1; + flex-basis: 0; +} + +.sc-trace-row { + font-size: 11px; + padding-left: 6px; + -unity-text-align: middle-left; +} + +.sc-trace-event { + color: rgb(255, 200, 60); +} + +.sc-trace-enter { + color: rgb(60, 180, 95); +} + +.sc-trace-fault { + color: rgb(230, 80, 80); +} diff --git a/Editor/StatechartDebugger.uss.meta b/Editor/StatechartDebugger.uss.meta new file mode 100644 index 0000000..09c006e --- /dev/null +++ b/Editor/StatechartDebugger.uss.meta @@ -0,0 +1,12 @@ +fileFormatVersion: 2 +guid: 5ae4d79bb23a74f1398d278a1219f301 +ScriptedImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 2 + userData: + assetBundleName: + assetBundleVariant: + script: {fileID: 12385, guid: 0000000000000000e000000000000000, type: 0} + disableValidation: 0 + unsupportedSelectorAction: 0 diff --git a/Editor/StatechartDebuggerWindow.cs b/Editor/StatechartDebuggerWindow.cs new file mode 100644 index 0000000..d59eab3 --- /dev/null +++ b/Editor/StatechartDebuggerWindow.cs @@ -0,0 +1,296 @@ +using System; +using System.Collections.Generic; +using GameLovers.StatechartMachine.Internal; +using UnityEditor; +using UnityEditor.UIElements; +using UnityEngine; +using UnityEngine.UIElements; + +// ReSharper disable CheckNamespace + +namespace GameLovers.StatechartMachine.Editor +{ + /// + /// Live debugger for every running . Shows the selected chart through three views that + /// read the same topology, active states and trace history: A (nested boxes), B (Graph Toolkit graph, Unity 6.6+) + /// and C (state tree and trace log). + /// + public class StatechartDebuggerWindow : EditorWindow + { + private const string StyleSheetPath = "Packages/com.gamelovers.statechart/Editor/StatechartDebugger.uss"; + private const long RefreshIntervalMs = 100; + + [SerializeField] private string _selectedChartName; + [SerializeField] private bool _showLiveChart = true; + [SerializeField] private bool _showTreeTrace = true; + + private readonly List _activeStates = new List(); + + private StatechartRegistry.Entry _selected; + private IStatechart _selectedChart; + private int _renderedVersion = -1; + private ToolbarMenu _chartMenu; + private Label _statusLabel; + private ToolbarToggle _graphToggle; + private VisualElement _body; + private Label _emptyLabel; + private LiveChartView _liveChartView; + private TreeTraceView _treeTraceView; + + /// + /// Set by the Graph Toolkit assembly on Unity 6.6+ to open view B for a chart; null on older editors. + /// + internal static Action GraphViewOpener { get; set; } + + /// + /// The chart currently selected in any open debugger window, read by view B to follow the selection. + /// + internal static IStatechart SelectedChart { get; private set; } + + [MenuItem("Tools/GameLovers/Statechart Debugger", priority = 100)] + private static void Open() + { + var window = GetWindow(); + + window.titleContent = new GUIContent("Statechart Debugger"); + window.minSize = new Vector2(480, 320); + window.Show(); + } + + private void CreateGUI() + { + var styleSheet = AssetDatabase.LoadAssetAtPath(StyleSheetPath); + + if (styleSheet != null) + { + rootVisualElement.styleSheets.Add(styleSheet); + } + + rootVisualElement.AddToClassList("sc-root"); + rootVisualElement.Add(BuildToolbar()); + + _emptyLabel = new Label("No live statecharts. Enter Play mode, or create a Statechart from code."); + _emptyLabel.AddToClassList("sc-empty"); + rootVisualElement.Add(_emptyLabel); + + _body = new VisualElement(); + _body.AddToClassList("sc-body"); + rootVisualElement.Add(_body); + + _liveChartView = new LiveChartView(); + _treeTraceView = new TreeTraceView(); + _body.Add(_liveChartView); + _body.Add(_treeTraceView); + + StatechartRegistry.Changed += OnRegistryChanged; + rootVisualElement.RegisterCallback(_ => StatechartRegistry.Changed -= OnRegistryChanged); + rootVisualElement.schedule.Execute(Refresh).Every(RefreshIntervalMs); + + ApplyViewVisibility(); + SelectChart(null); + } + + private Toolbar BuildToolbar() + { + var toolbar = new Toolbar(); + + _chartMenu = new ToolbarMenu { text = "Select chart" }; + _chartMenu.AddToClassList("sc-chart-menu"); + _chartMenu.RegisterCallback(_ => PopulateChartMenu(), TrickleDown.TrickleDown); + toolbar.Add(_chartMenu); + + _statusLabel = new Label(); + _statusLabel.AddToClassList("sc-status"); + toolbar.Add(_statusLabel); + + toolbar.Add(new ToolbarButton(() => _selectedChart?.Run()) { text = "Run", tooltip = "Run or resume the chart" }); + toolbar.Add(new ToolbarButton(() => _selectedChart?.Pause()) { text = "Pause" }); + toolbar.Add(new ToolbarButton(() => _selectedChart?.Reset()) { text = "Reset", tooltip = "Reset to the initial state" }); + toolbar.Add(new ToolbarSpacer { flex = true }); + + toolbar.Add(CreateViewToggle("A Live chart", _showLiveChart, value => _showLiveChart = value)); + + _graphToggle = new ToolbarToggle { text = "B Graph", value = false }; + _graphToggle.SetEnabled(GraphViewOpener != null); + _graphToggle.tooltip = GraphViewOpener != null + ? "Open the chart as a Graph Toolkit graph with live highlighting" + : "Requires Unity 6.6 or newer (Graph Toolkit)"; + _graphToggle.RegisterValueChangedCallback(evt => + { + _graphToggle.SetValueWithoutNotify(false); + + if (_selectedChart != null) + { + GraphViewOpener?.Invoke(_selectedChart, _selected); + } + }); + toolbar.Add(_graphToggle); + + toolbar.Add(CreateViewToggle("C Tree + trace", _showTreeTrace, value => _showTreeTrace = value)); + + var copyMenu = new ToolbarMenu { text = "Copy" }; + copyMenu.menu.AppendAction("Mermaid diagram", _ => Copy(StatechartExport.ToMermaid), + _ => _selectedChart != null ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled); + copyMenu.menu.AppendAction("Active state paths", _ => Copy(StatechartExport.ToActivePaths), + _ => _selectedChart != null ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled); + copyMenu.menu.AppendAction("Trace history", _ => CopyTrace(), + _ => _selected != null ? DropdownMenuAction.Status.Normal : DropdownMenuAction.Status.Disabled); + toolbar.Add(copyMenu); + + return toolbar; + } + + private ToolbarToggle CreateViewToggle(string label, bool initial, Action setter) + { + var toggle = new ToolbarToggle { text = label, value = initial }; + + toggle.RegisterValueChangedCallback(evt => + { + setter(evt.newValue); + ApplyViewVisibility(); + }); + + return toggle; + } + + private void ApplyViewVisibility() + { + _liveChartView.style.display = _showLiveChart ? DisplayStyle.Flex : DisplayStyle.None; + _treeTraceView.style.display = _showTreeTrace ? DisplayStyle.Flex : DisplayStyle.None; + } + + private void PopulateChartMenu() + { + var menu = _chartMenu.menu; + + menu.ClearItems(); + + foreach (var entry in StatechartRegistry.GetEntries()) + { + var captured = entry; + + menu.AppendAction(entry.Name, _ => SelectChart(captured), + _ => captured == _selected ? DropdownMenuAction.Status.Checked : DropdownMenuAction.Status.Normal); + } + + if (StatechartRegistry.GetEntries().Count == 0) + { + menu.AppendAction("No live statecharts", null, DropdownMenuAction.Status.Disabled); + } + } + + private void OnRegistryChanged() + { + if (_selected == null || !_selected.TryGetChart(out _) || !Contains(StatechartRegistry.GetEntries(), _selected)) + { + SelectChart(null); + } + } + + private void SelectChart(StatechartRegistry.Entry entry) + { + var entries = StatechartRegistry.GetEntries(); + + if (entry == null) + { + // Prefer the last selected name so the window survives domain reloads and play mode restarts. + foreach (var candidate in entries) + { + if (candidate.Name == _selectedChartName) + { + entry = candidate; + break; + } + } + + entry ??= entries.Count > 0 ? entries[entries.Count - 1] : null; + } + + _selected = entry; + _selectedChart = null; + entry?.TryGetChart(out _selectedChart); + SelectedChart = _selectedChart; + _selectedChartName = entry?.Name ?? _selectedChartName; + _renderedVersion = -1; + + _chartMenu.text = entry?.Name ?? "Select chart"; + _emptyLabel.style.display = _selectedChart == null ? DisplayStyle.Flex : DisplayStyle.None; + _body.style.display = _selectedChart == null ? DisplayStyle.None : DisplayStyle.Flex; + + _liveChartView.SetChart(_selectedChart); + _treeTraceView.SetChart(_selectedChart); + Refresh(); + } + + private void Refresh() + { + if (_selected != null && !_selected.TryGetChart(out _)) + { + SelectChart(null); + return; + } + + if (_selectedChart == null) + { + if (StatechartRegistry.GetEntries().Count > 0) + { + SelectChart(null); + } + + return; + } + + SelectedChart = _selectedChart; + _statusLabel.text = _selectedChart.IsRunning ? "Running" : "Paused"; + _statusLabel.EnableInClassList("sc-status-running", _selectedChart.IsRunning); + + if (_renderedVersion == StatechartRegistry.Version) + { + return; + } + + _renderedVersion = StatechartRegistry.Version; + _selectedChart.GetActiveStates(_activeStates); + _liveChartView.UpdateActive(_activeStates, _selected.History); + _treeTraceView.UpdateActive(_activeStates, _selected.History); + } + + private void Copy(Func export) + { + if (_selectedChart != null) + { + EditorGUIUtility.systemCopyBuffer = export(_selectedChart); + } + } + + private void CopyTrace() + { + if (_selected == null) + { + return; + } + + var lines = new List(); + + foreach (var record in _selected.History) + { + lines.Add($"#{record.Frame} {record.Message}"); + } + + EditorGUIUtility.systemCopyBuffer = string.Join("\n", lines); + } + + private static bool Contains(IReadOnlyList entries, StatechartRegistry.Entry entry) + { + for (var i = 0; i < entries.Count; i++) + { + if (entries[i] == entry) + { + return true; + } + } + + return false; + } + } +} diff --git a/Editor/StatechartDebuggerWindow.cs.meta b/Editor/StatechartDebuggerWindow.cs.meta new file mode 100644 index 0000000..b6d4c2e --- /dev/null +++ b/Editor/StatechartDebuggerWindow.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: 83401716ef65c444e8089150d477da78 \ No newline at end of file diff --git a/Editor/TreeTraceView.cs b/Editor/TreeTraceView.cs new file mode 100644 index 0000000..04479d8 --- /dev/null +++ b/Editor/TreeTraceView.cs @@ -0,0 +1,144 @@ +using System.Collections.Generic; +using GameLovers.StatechartMachine.Internal; +using UnityEngine.UIElements; + +// ReSharper disable CheckNamespace + +namespace GameLovers.StatechartMachine.Editor +{ + /// + /// View C: an indented tree of every state with the active ones marked, above a scrolling trace log. + /// + internal sealed class TreeTraceView : VisualElement + { + private readonly Dictionary _rows = new Dictionary(); + private readonly List _records = new List(); + private readonly ScrollView _tree; + private readonly ListView _trace; + + internal TreeTraceView() + { + AddToClassList("sc-pane"); + AddToClassList("sc-pane-tree"); + + var treeHeader = new Label("C · State tree"); + treeHeader.AddToClassList("sc-pane-header"); + Add(treeHeader); + + _tree = new ScrollView(); + _tree.AddToClassList("sc-tree"); + Add(_tree); + + var traceHeader = new Label("Trace (newest last)"); + traceHeader.AddToClassList("sc-pane-header"); + Add(traceHeader); + + _trace = new ListView(_records, 18, MakeTraceRow, BindTraceRow) + { + selectionType = SelectionType.None + }; + _trace.AddToClassList("sc-trace"); + Add(_trace); + } + + /// Rebuilds the tree for , or clears it when null. + internal void SetChart(IStatechart chart) + { + _rows.Clear(); + _tree.Clear(); + _records.Clear(); + _trace.RefreshItems(); + + if (chart != null) + { + AddRegion(chart.RootRegion); + } + } + + /// Marks states and shows the latest . + internal void UpdateActive(List active, IReadOnlyCollection history) + { + foreach (var pair in _rows) + { + var isActive = active.Contains(pair.Key); + + pair.Value.text = $"{(isActive ? "●" : "○")} {pair.Key.Name}"; + pair.Value.EnableInClassList("sc-active", isActive); + } + + _records.Clear(); + _records.AddRange(history); + _trace.RefreshItems(); + + if (_records.Count > 0) + { + _trace.ScrollToItem(_records.Count - 1); + } + } + + private void AddRegion(RegionNode region) + { + if (region.Owner != null && region.Owner.Kind == StateKind.Split) + { + var lane = new Label($"region {region.Index + 1}"); + lane.AddToClassList("sc-tree-lane"); + lane.style.paddingLeft = region.Depth * 14; + _tree.Add(lane); + } + + foreach (var state in region.States) + { + var row = new Label { tooltip = $"{state.Path} ({state.Kind})" }; + + row.AddToClassList("sc-tree-row"); + row.style.paddingLeft = state.Depth * 14 + 4; + _rows[state] = row; + _tree.Add(row); + + foreach (var child in state.Regions) + { + AddRegion(child); + } + } + } + + private static VisualElement MakeTraceRow() + { + var label = new Label(); + + label.AddToClassList("sc-trace-row"); + + return label; + } + + private void BindTraceRow(VisualElement element, int index) + { + var record = _records[index]; + var label = (Label) element; + + label.text = $"#{record.Frame} {Describe(record)}"; + label.EnableInClassList("sc-trace-event", record.Kind == StatechartTraceKind.EventTriggered); + label.EnableInClassList("sc-trace-fault", record.Kind == StatechartTraceKind.Faulted); + label.EnableInClassList("sc-trace-enter", record.Kind == StatechartTraceKind.StateEntered); + } + + private static string Describe(StatechartTraceRecord record) + { + switch (record.Kind) + { + case StatechartTraceKind.EventTriggered: + return $"⚡ {record.EventName}"; + case StatechartTraceKind.StateEntered: + return $"→ enter {record.State?.Path}"; + case StatechartTraceKind.StateExited: + return $"← exit {record.State?.Path}"; + case StatechartTraceKind.Transition: + return $" {record.State?.Name} ⟶ {record.Target?.Name ?? "(action)"}"; + case StatechartTraceKind.Faulted: + return $"✖ fault in {record.State?.Path}"; + default: + return record.Kind.ToString(); + } + } + } +} diff --git a/Editor/TreeTraceView.cs.meta b/Editor/TreeTraceView.cs.meta new file mode 100644 index 0000000..d144a60 --- /dev/null +++ b/Editor/TreeTraceView.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f0c5c27682ea24eea9d881b58f5e8ba8 \ No newline at end of file diff --git a/README.md b/README.md index 9eadcb8..1f7bc67 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # GameLovers Statechart -Hierarchical statecharts for Unity 6 with nested and parallel regions, event transitions, choices, and async waits. +Hierarchical statecharts for Unity 6 with nested and parallel regions, event transitions, choices, async waits, a live debugger, and a playable sample. -[![Unity](https://img.shields.io/badge/Unity-6000.0%20%7C%206000.3%20%7C%206000.5-blue.svg)](https://unity.com/download) +[![Unity](https://img.shields.io/badge/Unity-6000.0%20%7C%206000.3%20%7C%206000.6-blue.svg)](https://unity.com/download) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE.md) ## When to use it @@ -14,19 +14,19 @@ Use Statechart when a flat FSM cannot express hierarchical behavior, concurrent | Item | Current policy | | --- | --- | | Minimum Unity version | `6000.0` | -| Reference streams | `6000.0.x`, `6000.3.x`, `6000.5.x` | -| Reference editors | `6000.0.81f1`, `6000.3.21f1`, `6000.5.7f1` (primary) | +| Supported streams | `6000.0.x`, `6000.3.x`, `6000.6.x` (LTS) | +| Statechart Debugger views A and C | All supported streams | +| Statechart Debugger view B (Graph Toolkit) | `6000.6` and newer; the view's assembly is compiled out on older editors | | Render pipeline | Pipeline-neutral | -| Validation status | Compatibility target; consult fresh matrix artifacts before claiming validation. | ## Install -Add UniTask explicitly when installing from Git: +Add UniTask explicitly when installing from Git. Use UniTask 2.5.11 or newer: 2.5.10's Editor code does not compile on Unity 6000.6. ```json { "dependencies": { - "com.cysharp.unitask": "https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask#2.5.10", + "com.cysharp.unitask": "https://github.com/Cysharp/UniTask.git?path=src/UniTask/Assets/Plugins/UniTask#2.5.11", "com.gamelovers.statechart": "https://github.com/CoderGamester/Statechart-HFSM.git#0.9.5" } } @@ -34,7 +34,7 @@ Add UniTask explicitly when installing from Git: ## First success -Keep events as fields: statechart event identity is by object instance, not by its display name. +Keep events as fields: statechart event identity is by object instance, not by its display name. Give the chart a name so logs and the debugger can tell charts apart, and dispose it with its owner. ```csharp using GameLovers.StatechartMachine; @@ -42,24 +42,27 @@ using UnityEngine; public sealed class PlayerStatechart : MonoBehaviour { - private readonly StatechartEvent jump = new("Jump"); - private Statechart chart; + private readonly StatechartEvent _jump = new("Jump"); + private IStatechart _chart; private void Awake() { - chart = new Statechart(factory => + _chart = new Statechart("Player", factory => { var initial = factory.Initial("Initial"); var idle = factory.State("Idle"); var jumping = factory.State("Jumping"); + initial.Transition().Target(idle); - idle.Event(jump).Target(jumping); - jumping.Event(jump).Target(idle); + idle.Event(_jump).Target(jumping); + jumping.Event(_jump).Target(idle); }); - chart.Run(); + _chart.Run(); } - public void Jump() => chart.Trigger(jump); + private void OnDestroy() => _chart.Dispose(); + + public void Jump() => _chart.Trigger(_jump); } ``` @@ -70,21 +73,78 @@ stateDiagram-v2 Jumping --> Idle: jump event ``` +## State kinds + +| Factory method | Kind | Behavior | +| --- | --- | --- | +| `Initial` | Initial | Entry point of a region; exactly one per region | +| `Final` | Final | Completes its region | +| `State` | Simple | Waits for events; event transitions may omit a target to run an action only | +| `Transition` | Transition | Passes straight through to its target, running its callbacks | +| `Choice` | Choice | Takes the first transition whose condition is true, otherwise the one without a condition | +| `Wait` | Wait | Resumes when its `IWaitActivity` completes; still reacts to configured events | +| `TaskWait` | TaskWait | Awaits a `Task` or `UniTask`; ignores events while waiting | +| `Nest` | Nest | One nested region; completes when that region reaches its final state | +| `Split` | Split | Two or more parallel regions; completes when all of them finish | +| `Leave` | Leave | Leaves the enclosing nest or split from inside a region | + ## Runtime semantics -| Concept | Behavior | +| Topic | Behavior | | --- | --- | -| `Trigger` | Ignored until `Run()` and while the chart is paused | -| `Choice` | Takes the first true transition; define a fallback deliberately | -| Action-only transition | Valid when it has no target and exists for its action | -| `Wait` | Resumes when its wait activity completes; can receive configured events | -| `TaskWait` | Waits on a `Task` or `UniTask`; it does not receive events while waiting | -| `Nest` / `Split` | Create sequential nested regions / concurrent regions | +| `Trigger` | Ignored until `Run()` and while paused | +| Run to completion | An event triggered while another one is processed (for example from `OnEnter`) is queued and processed right after it | +| `Pause()` | Stops the chart, also mid-chain when called from a callback; `Run()` resumes from the same states | +| `Reset()` | Returns to the initial state without exit callbacks; drops queued events and abandons pending waits and tasks | +| `Dispose()` | Stops the chart for good, cancels token-aware tasks and removes it from the debugger; `Run()` then throws `ObjectDisposedException` | +| `TaskWait` faults | A task that throws is logged and still completes the state, so the chart and parent splits never wait forever | +| `TaskWait` threads | The chart always resumes on the main thread, even if the awaited task completes on a worker thread | +| Cancellation | `WaitingFor(Func)` and the `Task` variant receive a token cancelled by `Reset()` and `Dispose()` | +| Callback exceptions | Enter, exit and transition exceptions are logged with the stack trace of the code that declared the failing state, and the chart keeps going | + +The constructor rejects a setup without an initial state in every build. Other setup validation (missing targets, self loops, malformed choices, leave depth) runs only in the Editor and in `DEBUG` builds. + +## Observe a running chart + +Every chart exposes its structure and its live state, so tools, tests and logs read the same data: + +```csharp +// Read-only topology, built once at construction. +foreach (var state in chart.RootRegion.States) +{ + Debug.Log($"{state.Path} ({state.Kind}) with {state.Transitions.Count} transitions"); +} + +// Active states, parents before children. +var active = new List(); +chart.GetActiveStates(active); + +// Every step in execution order: events, exits, transitions, enters, faults, lifecycle. +chart.Traced += trace => Debug.Log(trace); + +// Text exports for bug reports or AI agents. +var mermaid = StatechartExport.ToMermaid(chart); +var paths = StatechartExport.ToActivePaths(chart); +``` + +Set `chart.LogsEnabled = true` (or `LogsEnabled` on a single state) to write the same trace lines to the console, for example `[Statechart 'Player'] Idle -> Jumping on 'Jump'`. Nothing is formatted or published while no one subscribes and logs are off. + +## Statechart Debugger + +Open **Tools > GameLovers > Statechart Debugger** in Play mode. Pick a chart from the toolbar; Run, Pause and Reset act on that chart. Three views read the same data and can be shown side by side: + +| View | What it shows | Unity | +| --- | --- | --- | +| **A · Live chart** | Nested boxes: nest and split states contain their regions, split regions are dashed lanes, active states are green and newly entered ones flash | All | +| **B · Graph** | A Graph Toolkit graph generated from the chart: active states get a bright green accent bar and taken transitions stay thick | 6000.6+ | +| **C · Tree + trace** | An indented tree with the active states marked, and the latest 256 trace steps | All | + +View B writes a generated, display-only `.statechartdebug` asset to `Assets/StatechartDebugger/` and opens it in the Graph Toolkit window; dock that window next to the debugger. Its highlights are recorded as undo steps of that graph and mark it as modified; there is nothing to save. Delete the folder or add it to your `.gitignore` if you do not want to keep it. The **Copy** menu puts the Mermaid diagram, the active state paths or the trace history on the clipboard. -Missing top-level initial configuration is rejected in all builds. Other setup validation has build-dependent editor/debug behavior; write and test the behavior you require instead of relying on broad “all invalid graphs fail immediately” assumptions. +## Samples -## Recipes and support +Import **Game Flow** from the Package Manager's Samples tab. One statechart runs a small game loop that uses every state kind: a nested boot sequence with cancellable task waits, a menu, a split gameplay state (a player region and a waves region), a choice, leave states and results. It has on-screen buttons and an activity log, and is meant to be watched with the Statechart Debugger open. See the sample's `README.md`. -The public API supports `Nest`, `Split`, `Choice`, `Wait`, and `TaskWait`; add a small package sample before treating any recipe as a supported end-to-end workflow. Until then, use the source tests as the executable reference. +## Support See [CHANGELOG.md](CHANGELOG.md) and file an [issue](https://github.com/CoderGamester/Statechart-HFSM/issues). `AGENTS.md` is contributor guidance, not end-user API documentation. diff --git a/Runtime/AssemblyInfo.cs b/Runtime/AssemblyInfo.cs new file mode 100644 index 0000000..476fe4e --- /dev/null +++ b/Runtime/AssemblyInfo.cs @@ -0,0 +1,5 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("GameLovers.Statechart.Editor")] +[assembly: InternalsVisibleTo("GameLovers.Statechart.Editor.GraphToolkit")] +[assembly: InternalsVisibleTo("GameLovers.Statechart.Editor.Tests")] diff --git a/Runtime/AssemblyInfo.cs.meta b/Runtime/AssemblyInfo.cs.meta new file mode 100644 index 0000000..5848ea0 --- /dev/null +++ b/Runtime/AssemblyInfo.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5f40afdb30bd4a39a76d3f6c22775184 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/IState.cs b/Runtime/IState.cs index 61d6e23..5830fd5 100644 --- a/Runtime/IState.cs +++ b/Runtime/IState.cs @@ -1,5 +1,6 @@ using Cysharp.Threading.Tasks; using System; +using System.Threading; using System.Threading.Tasks; // ReSharper disable CheckNamespace @@ -159,12 +160,29 @@ public interface ITaskWaitState : IStateEnter, IStateExit { /// /// Blocks the state behaviour until the given async is completed. - /// It will return the created that will triggered as soon as the state is unblocked + /// It will return the created that will triggered as soon as the state is unblocked. + /// A task that throws is logged and still completes the state, so the chart never waits forever; handle + /// errors inside the task when a failure needs a different path. The chart resumes on the main thread. /// + /// The async work to await each time the state is entered. + /// The transition taken when the task completes. + /// Thrown when is null. ITransition WaitingFor(Func taskAwaitAction); - /// + /// ITransition WaitingFor(Func taskAwaitAction); + + /// + /// Same as , but passes a token that is cancelled when the statechart is + /// reset or disposed, so long-running work can stop with the chart. + /// + /// The async work to await each time the state is entered. + /// The transition taken when the task completes. + /// Thrown when is null. + ITransition WaitingFor(Func taskAwaitAction); + + /// + ITransition WaitingFor(Func taskAwaitAction); } /// diff --git a/Runtime/Internal/ChoiceState.cs b/Runtime/Internal/ChoiceState.cs index 59db0a1..be3a2f7 100644 --- a/Runtime/Internal/ChoiceState.cs +++ b/Runtime/Internal/ChoiceState.cs @@ -16,6 +16,9 @@ public ChoiceState(string name, IStateFactoryInternal factory) : base(name, fact { } + /// + public override StateKind Kind => StateKind.Choice; + /// public override void Enter() { @@ -77,7 +80,7 @@ public override void Validate() if (noTransitionConditionCount > 1) { UnityEngine.Debug.LogWarning($"Choice state {Name} has multiple transition without a condition defined." + - "This will lead to improper behaviour and will pick a random transition"); + "Only the last one declared is used as the fallback"); } #endif } @@ -87,7 +90,7 @@ public void OnEnter(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnEnter action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnEnter action"); } _onEnter.Add(action); @@ -98,7 +101,7 @@ public void OnExit(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnExit action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnExit action"); } _onExit.Add(action); @@ -114,6 +117,15 @@ public ITransitionCondition Transition() return transition; } + /// + public override void CollectTransitions(List results) + { + foreach (var transition in _transitions) + { + results.Add(new TransitionInfo(transition, null, TransitionKind.Choice)); + } + } + /// protected override ITransitionInternal OnTrigger(IStatechartEvent statechartEvent) { diff --git a/Runtime/Internal/FinalState.cs b/Runtime/Internal/FinalState.cs index f43ca53..2781bd7 100644 --- a/Runtime/Internal/FinalState.cs +++ b/Runtime/Internal/FinalState.cs @@ -14,6 +14,9 @@ public FinalState(string name, IStateFactoryInternal factory) : base(name, facto { } + /// + public override StateKind Kind => StateKind.Final; + /// public override void Enter() { @@ -35,6 +38,12 @@ public override void Validate() // Do nothing on the final state } + /// + public override void CollectTransitions(List results) + { + + } + /// protected override ITransitionInternal OnTrigger(IStatechartEvent statechartEvent) { @@ -46,7 +55,7 @@ public void OnEnter(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnEnter action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnEnter action"); } _onEnter.Add(action); diff --git a/Runtime/Internal/InitialState.cs b/Runtime/Internal/InitialState.cs index 9238939..0d3c494 100644 --- a/Runtime/Internal/InitialState.cs +++ b/Runtime/Internal/InitialState.cs @@ -16,6 +16,9 @@ public InitialState(string name, IStateFactoryInternal factory) : base(name, fac { } + /// + public override StateKind Kind => StateKind.Initial; + /// public override void Enter() { @@ -37,7 +40,7 @@ public override void Validate() #if UNITY_EDITOR || DEBUG if (_transition?.TargetState == null) { - throw new MissingMemberException($"Initial state {Name} doesn't have a transition defined, so nothing will happen"); + throw new InvalidOperationException($"Initial state {Name} doesn't have a transition defined, so nothing will happen"); } if (_transition.TargetState.Id == Id) @@ -65,12 +68,18 @@ public void OnExit(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnExit action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnExit action"); } _onExit.Add(action); } + /// + public override void CollectTransitions(List results) + { + results.Add(new TransitionInfo(_transition, null, TransitionKind.Automatic)); + } + /// protected override ITransitionInternal OnTrigger(IStatechartEvent statechartEvent) { diff --git a/Runtime/Internal/LeaveState.cs b/Runtime/Internal/LeaveState.cs index 65478ec..b0a288c 100644 --- a/Runtime/Internal/LeaveState.cs +++ b/Runtime/Internal/LeaveState.cs @@ -19,6 +19,9 @@ public LeaveState(string name, IStateFactoryInternal factory) : base(name, facto { } + /// + public override StateKind Kind => StateKind.Leave; + /// public override void Enter() { @@ -50,6 +53,12 @@ public override void Validate() #endif } + /// + public override void CollectTransitions(List results) + { + results.Add(new TransitionInfo(LeaveTransition, null, TransitionKind.Leave)); + } + /// protected override ITransitionInternal OnTrigger(IStatechartEvent statechartEvent) { @@ -61,7 +70,7 @@ public void OnEnter(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnEnter action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnEnter action"); } _onEnter.Add(action); diff --git a/Runtime/Internal/NestState.cs b/Runtime/Internal/NestState.cs index 12509e6..e41f01e 100644 --- a/Runtime/Internal/NestState.cs +++ b/Runtime/Internal/NestState.cs @@ -12,6 +12,9 @@ public NestState(string name, IStateFactoryInternal factory) : base(name, factor { } + /// + public override StateKind Kind => StateKind.Nest; + /// public override void Validate() { diff --git a/Runtime/Internal/SimpleState.cs b/Runtime/Internal/SimpleState.cs index d45a1fa..41e6d14 100644 --- a/Runtime/Internal/SimpleState.cs +++ b/Runtime/Internal/SimpleState.cs @@ -16,6 +16,9 @@ public SimpleState(string name, IStateFactoryInternal factory) : base(name, fact { } + /// + public override StateKind Kind => StateKind.Simple; + /// public override void Enter() { @@ -53,7 +56,7 @@ public void OnEnter(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnEnter action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnEnter action"); } _onEnter.Add(action); @@ -64,7 +67,7 @@ public void OnExit(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnExit action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnExit action"); } _onExit.Add(action); @@ -75,7 +78,7 @@ public ITransition Event(IStatechartEvent statechartEvent) { if (statechartEvent == null) { - throw new NullReferenceException($"The state {Name} cannot have a null event"); + throw new ArgumentNullException(nameof(statechartEvent), $"The state {Name} cannot have a null event"); } var transition = new Transition(); @@ -85,6 +88,15 @@ public ITransition Event(IStatechartEvent statechartEvent) return transition; } + /// + public override void CollectTransitions(List results) + { + foreach (var pair in _events) + { + results.Add(new TransitionInfo(pair.Value, pair.Key, TransitionKind.Event)); + } + } + /// protected override ITransitionInternal OnTrigger(IStatechartEvent statechartEvent) { diff --git a/Runtime/Internal/SplitState.cs b/Runtime/Internal/SplitState.cs index 62a22d8..a4952b5 100644 --- a/Runtime/Internal/SplitState.cs +++ b/Runtime/Internal/SplitState.cs @@ -16,10 +16,16 @@ internal class SplitState : StateInternal, ISplitState private bool _isPaused; private ITransitionInternal _transition; + /// The nested regions of this state and their current inner state. + internal IList Regions => _innerStatesData; + public SplitState(string name, IStateFactoryInternal factory) : base(name, factory) { } + /// + public override StateKind Kind => StateKind.Split; + /// public override void Enter() { @@ -51,12 +57,12 @@ public override void Exit() if (innerState.ExecuteExit) { - innerState.CurrenState.Exit(); + innerState.CurrenState.ExitSafely(null); } if (innerState.ExecuteFinal && !(innerState.CurrenState is FinalState) && !(innerState.CurrenState is LeaveState)) { - innerState.NestedFactory.FinalState?.Enter(); + innerState.NestedFactory.FinalState?.EnterSafely(null); } } @@ -118,7 +124,7 @@ public void OnEnter(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnEnter action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnEnter action"); } _onEnter.Add(action); @@ -129,7 +135,7 @@ public void OnExit(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnExit action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnExit action"); } _onExit.Add(action); @@ -140,7 +146,7 @@ public ITransition Event(IStatechartEvent statechartEvent) { if (statechartEvent == null) { - throw new NullReferenceException($"The state {Name} cannot have a null event"); + throw new ArgumentNullException(nameof(statechartEvent), $"The state {Name} cannot have a null event"); } var transition = new Transition(); @@ -193,6 +199,17 @@ public ITransition Split(params NestedStateData[] data) return _transition; } + /// + public override void CollectTransitions(List results) + { + foreach (var pair in _events) + { + results.Add(new TransitionInfo(pair.Value, pair.Key, TransitionKind.Event)); + } + + results.Add(new TransitionInfo(_transition, null, TransitionKind.Completion)); + } + /// protected override ITransitionInternal OnTrigger(IStatechartEvent statechartEvent) { @@ -206,6 +223,12 @@ protected override ITransitionInternal OnTrigger(IStatechartEvent statechartEven if (statechartEvent != null && _events.TryGetValue(statechartEvent, out var transition)) { + // An action-only event keeps this state active, so its inner waits must keep running. + if (transition.TargetState == null) + { + return transition; + } + // Delay the completion of this state while some tasks are running return !isUnpausing && DelayForceComplete(statechartEvent) ? null : transition; } diff --git a/Runtime/Internal/StateFactory.cs b/Runtime/Internal/StateFactory.cs index 296f324..ab99a06 100644 --- a/Runtime/Internal/StateFactory.cs +++ b/Runtime/Internal/StateFactory.cs @@ -11,7 +11,7 @@ namespace GameLovers.StatechartMachine.Internal internal struct StateFactoryData { public Action StateChartMoveNextCall; - public IStatechart Statechart; + public Statechart Statechart; } /// diff --git a/Runtime/Internal/StateInternal.cs b/Runtime/Internal/StateInternal.cs index 42410d1..a619054 100644 --- a/Runtime/Internal/StateInternal.cs +++ b/Runtime/Internal/StateInternal.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using UnityEngine; // ReSharper disable CheckNamespace @@ -17,14 +18,26 @@ internal interface IStateInternal : IState, IEquatable /// string Name { get; } /// + /// The kind of state, as exposed by the public topology + /// + StateKind Kind { get; } + /// /// The layer in the nested setup this state is in. If in the root then the value will be 0 /// uint RegionLayer { get; } /// + /// The factory that created this state, identifying its region + /// + IStateFactoryInternal Factory { get; } + /// + /// The public description of this state, assigned once the statechart topology is built + /// + StateNode Node { get; set; } + /// /// The stack trace when this setup was created. Relevant for debugging purposes /// string CreationStackTrace { get; } - + /// /// Triggers the given as input to the and returns /// the processed as an output @@ -39,10 +52,22 @@ internal interface IStateInternal : IState, IEquatable /// void Exit(); /// + /// Traces and runs , reporting any exception instead of throwing it + /// + void EnterSafely(IStatechartEvent statechartEvent); + /// + /// Traces and runs , reporting any exception instead of throwing it + /// + void ExitSafely(IStatechartEvent statechartEvent); + /// /// Validates this state to any potential bad setup schemes. Relevant to debug purposes. /// It requires the to run at runtime. /// void Validate(); + /// + /// Adds every outgoing transition of this state to + /// + void CollectTransitions(List results); } /// @@ -59,12 +84,18 @@ internal abstract class StateInternal : IStateInternal /// public string Name { get; } /// + public abstract StateKind Kind { get; } + /// public uint RegionLayer => _stateFactory.RegionLayer; /// + public IStateFactoryInternal Factory => _stateFactory; + /// + public StateNode Node { get; set; } + /// public string CreationStackTrace { get; } - /// True when either this state or its owning statechart has logging switched on. - protected bool IsStateLogsEnabled => LogsEnabled || _stateFactory.Data.Statechart.LogsEnabled; + /// The statechart that owns this state. + protected Statechart Chart => _stateFactory.Data.Statechart; protected StateInternal(string name, IStateFactoryInternal stateFactory) { @@ -85,11 +116,6 @@ public IStateInternal Trigger(IStatechartEvent statechartEvent) if (transition == null) { - if (IsStateLogsEnabled) - { - Debug.Log($"({GetType().UnderlyingSystemType.Name}) - '{statechartEvent?.Name}' : ## STOP ## '{Name}'"); - } - return null; } @@ -97,29 +123,53 @@ public IStateInternal Trigger(IStatechartEvent statechartEvent) if (Equals(nextState)) { - if (IsStateLogsEnabled) - { - Debug.Log($"({GetType().UnderlyingSystemType.Name}) - '{statechartEvent?.Name}' : " + - $"'{Name}' -> '{Name}' because => {GetType().UnderlyingSystemType.Name}"); - } - return nextState; } if (nextState == null) { - TriggerTransition(transition, statechartEvent?.Name); + TriggerTransition(transition, statechartEvent); return null; } - TriggerExit(); - TriggerTransition(transition, statechartEvent?.Name); - TriggerEnter(nextState); + ExitSafely(statechartEvent); + TriggerTransition(transition, statechartEvent); + nextState.EnterSafely(statechartEvent); return nextState; } + /// + public void EnterSafely(IStatechartEvent statechartEvent) + { + Trace(StatechartTraceKind.StateEntered, null, statechartEvent); + + try + { + Enter(); + } + catch (Exception e) + { + ReportFault(e, $"Exception in the state '{Name}', OnEnter() actions.", CreationStackTrace); + } + } + + /// + public void ExitSafely(IStatechartEvent statechartEvent) + { + Trace(StatechartTraceKind.StateExited, null, statechartEvent); + + try + { + Exit(); + } + catch (Exception e) + { + ReportFault(e, $"Exception in the state '{Name}', OnExit() actions.", CreationStackTrace); + } + } + /// public bool Equals(IStateInternal stateInternal) { @@ -150,81 +200,56 @@ public override string ToString() public abstract void Exit(); /// public abstract void Validate(); + /// + public abstract void CollectTransitions(List results); /// /// Returns the transition this state takes for the given event, or null when it does not handle it. /// protected abstract ITransitionInternal OnTrigger(IStatechartEvent statechartEvent); - private void TriggerEnter(IStateInternal state) + /// + /// Publishes a trace about this state when the chart has a listener or this state's logs are enabled. + /// + protected void Trace(StatechartTraceKind kind, StateNode target, IStatechartEvent statechartEvent, + Exception exception = null) { - try + var chart = Chart; + + if (!chart.HasTraceListeners && !LogsEnabled) { - if (IsStateLogsEnabled) - { - Debug.Log($"({state.GetType().UnderlyingSystemType.Name}) - Entering '{state.Name}'"); - } - state.Enter(); + return; } - catch (Exception e) - { - var finalMessage = ""; -#if UNITY_EDITOR || DEBUG - finalMessage = $"\nStackTrace log of '{state.Name}' state creation bellow.\n{CreationStackTrace}"; -#endif - Debug.LogError($"Exception in the state '{state.Name}', OnExit() actions.\n" + - $"-->> Check the exception log after this one for more details <<-- {finalMessage}"); - Debug.LogException(e); - } + chart.Emit(new StatechartTrace(chart, kind, Node, target, statechartEvent, exception), LogsEnabled); } - private void TriggerExit() + /// + /// Logs a user-code exception with the setup stack trace that declared the failing element, and traces it. + /// + protected void ReportFault(Exception exception, string message, string creationStackTrace) { - try - { - if(IsStateLogsEnabled) - { - Debug.LogFormat($"({GetType().UnderlyingSystemType.Name}) - Exiting '{Name}'"); - } - Exit(); - } - catch(Exception e) - { - var finalMessage = ""; + var finalMessage = ""; #if UNITY_EDITOR || DEBUG - finalMessage = $"\nStackTrace log of '{Name}' state creation bellow.\n{CreationStackTrace}"; + finalMessage = $"\nStackTrace log of the failing element's creation below.\n{creationStackTrace}"; #endif - - Debug.LogError($"Exception in the state '{Name}', OnExit() actions.\n" + - $"-->> Check the exception log after this one for more details <<-- {finalMessage}"); - Debug.LogException(e); - } + Debug.LogError($"{message}\n-->> Check the exception log after this one for more details <<-- {finalMessage}"); + Debug.LogException(exception); + Trace(StatechartTraceKind.Faulted, null, null, exception); } - private void TriggerTransition(ITransitionInternal transition, string eventName) + private void TriggerTransition(ITransitionInternal transition, IStatechartEvent statechartEvent) { + Trace(StatechartTraceKind.Transition, transition.TargetState?.Node, statechartEvent); + try { - if (IsStateLogsEnabled) - { - var targetState = transition.TargetState?.Name ?? "only invokes OnTransition()"; - - Debug.Log($"({GetType().UnderlyingSystemType.Name}) - '{eventName}' : '{Name}' -> '{targetState}'"); - } - transition.TriggerTransition(); } catch (Exception e) { - var finalMessage = ""; -#if UNITY_EDITOR || DEBUG - finalMessage = $"\nStackTrace log of this transition creation bellow.\n{transition.CreationStackTrace}"; -#endif - - Debug.LogError($"Exception in the transition '{Name}' -> '{transition.TargetState?.Name}'" + - $"-->> Check the exception log after this one for more details <<-- {finalMessage}"); - Debug.LogException(e); + ReportFault(e, $"Exception in the transition '{Name}' -> '{transition.TargetState?.Name}'.", + transition.CreationStackTrace); } } } diff --git a/Runtime/Internal/StatechartRegistry.cs b/Runtime/Internal/StatechartRegistry.cs new file mode 100644 index 0000000..274d138 --- /dev/null +++ b/Runtime/Internal/StatechartRegistry.cs @@ -0,0 +1,129 @@ +#if UNITY_EDITOR +using System; +using System.Collections.Generic; +using UnityEngine; + +// ReSharper disable CheckNamespace + +namespace GameLovers.StatechartMachine.Internal +{ + /// + /// A trace step copied without a reference to its statechart, so recorded history never keeps a chart alive. + /// + internal readonly struct StatechartTraceRecord + { + public readonly double Time; + public readonly int Frame; + public readonly StatechartTraceKind Kind; + public readonly StateNode State; + public readonly StateNode Target; + public readonly string EventName; + public readonly string Message; + + public StatechartTraceRecord(in StatechartTrace trace, double time, int frame) + { + Time = time; + Frame = frame; + Kind = trace.Kind; + State = trace.State; + Target = trace.Target; + EventName = trace.Event?.Name; + Message = trace.ToString(); + } + } + + /// + /// Editor-only list of live statecharts and their recent trace history, read by the Statechart Debugger. + /// Charts are held weakly, so a chart that is never disposed still disappears once it is collected. + /// + internal static class StatechartRegistry + { + internal const int HistoryCapacity = 256; + + private static readonly List _entries = new List(); + + /// Raised on the main thread after a chart is added or removed. + internal static event Action Changed; + + /// Increments on every recorded trace of any chart, so views can repaint only on change. + internal static int Version { get; private set; } + + /// + /// One registered chart and its recent trace history, oldest first. + /// + internal sealed class Entry + { + private readonly WeakReference _chart; + private readonly Queue _history = new Queue(); + + /// The chart name captured at registration. + internal string Name { get; } + /// The recent trace steps, oldest first, capped at . + internal IReadOnlyCollection History => _history; + + internal Entry(IStatechart chart) + { + _chart = new WeakReference(chart); + Name = chart.Name; + } + + /// Returns the chart while it is still alive. + internal bool TryGetChart(out IStatechart chart) + { + return _chart.TryGetTarget(out chart); + } + + /// Appends a copy of , dropping the oldest step when full. + internal void Record(StatechartTrace trace) + { + if (_history.Count == HistoryCapacity) + { + _history.Dequeue(); + } + + _history.Enqueue(new StatechartTraceRecord(trace, Time.realtimeSinceStartupAsDouble, Time.frameCount)); + Version++; + } + } + + /// + /// Returns the live entries, dropping charts that were collected. + /// + internal static IReadOnlyList GetEntries() + { + if (_entries.RemoveAll(entry => !entry.TryGetChart(out _)) > 0) + { + Changed?.Invoke(); + } + + return _entries; + } + + /// Adds and starts recording its traces. + internal static void Register(IStatechart chart) + { + var entry = new Entry(chart); + + chart.Traced += entry.Record; + _entries.RemoveAll(e => !e.TryGetChart(out _)); + _entries.Add(entry); + Changed?.Invoke(); + } + + /// Removes and any collected entries. + internal static void Unregister(IStatechart chart) + { + _entries.RemoveAll(e => !e.TryGetChart(out var c) || ReferenceEquals(c, chart)); + Changed?.Invoke(); + } + + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] + private static void ResetOnPlay() + { + // Keeps entries from a previous play session out when domain reload is disabled. + _entries.Clear(); + Changed?.Invoke(); + } + } +} +#endif diff --git a/Runtime/Internal/StatechartRegistry.cs.meta b/Runtime/Internal/StatechartRegistry.cs.meta new file mode 100644 index 0000000..9018a00 --- /dev/null +++ b/Runtime/Internal/StatechartRegistry.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 10c96eacee9943a18ed8f36477030720 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Internal/StatechartTopologyBuilder.cs b/Runtime/Internal/StatechartTopologyBuilder.cs new file mode 100644 index 0000000..02a6f4e --- /dev/null +++ b/Runtime/Internal/StatechartTopologyBuilder.cs @@ -0,0 +1,95 @@ +using System.Collections.Generic; + +// ReSharper disable CheckNamespace + +namespace GameLovers.StatechartMachine.Internal +{ + /// + /// Describes one outgoing transition of an internal state for the public topology. + /// + internal readonly struct TransitionInfo + { + public readonly ITransitionInternal Transition; + public readonly IStatechartEvent Event; + public readonly TransitionKind Kind; + + public TransitionInfo(ITransitionInternal transition, IStatechartEvent statechartEvent, TransitionKind kind) + { + Transition = transition; + Event = statechartEvent; + Kind = kind; + } + } + + /// + /// Builds the immutable public topology from a validated state factory. + /// + internal static class StatechartTopologyBuilder + { + /// + /// Builds the root region and assigns every internal state its . + /// + public static RegionNode Build(IStateFactoryInternal rootFactory) + { + var states = new List(); + var root = BuildRegion(rootFactory, null, 0, states); + var transitions = new List(); + + foreach (var state in states) + { + transitions.Clear(); + state.CollectTransitions(transitions); + + foreach (var info in transitions) + { + if (info.Transition == null) + { + continue; + } + + state.Node._transitions.Add(new TransitionEdge(state.Node, info.Transition.TargetState?.Node, + info.Event, info.Kind, info.Transition.HasCondition)); + } + } + + return root; + } + + private static RegionNode BuildRegion(IStateFactoryInternal factory, StateNode owner, int index, + List allStates) + { + var region = new RegionNode(owner, index, (int) factory.RegionLayer); + + foreach (var state in factory.States) + { + if (state.Factory != factory) + { + continue; + } + + var node = new StateNode(state.Id, state.Name, state.Kind, region); + + state.Node = node; + region._states.Add(node); + allStates.Add(state); + + if (ReferenceEquals(state, factory.InitialState)) + { + region.Initial = node; + } + + if (state is not SplitState split) + { + continue; + } + + for (var i = 0; i < split.Regions.Count; i++) + { + node._regions.Add(BuildRegion(split.Regions[i].NestedFactory, node, i, allStates)); + } + } + + return region; + } + } +} diff --git a/Runtime/Internal/StatechartTopologyBuilder.cs.meta b/Runtime/Internal/StatechartTopologyBuilder.cs.meta new file mode 100644 index 0000000..1baf482 --- /dev/null +++ b/Runtime/Internal/StatechartTopologyBuilder.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 0edfee1e406c40eba9f7181d38e19e20 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/Internal/StatechartUtils.cs b/Runtime/Internal/StatechartUtils.cs index 5669420..c45ec44 100644 --- a/Runtime/Internal/StatechartUtils.cs +++ b/Runtime/Internal/StatechartUtils.cs @@ -8,19 +8,27 @@ namespace GameLovers.StatechartMachine.Internal internal static class StatechartUtils { /// - /// Cleans ups the given of unnecessary string data + /// Removes the leading stack frames that belong to and to this package, so the + /// trace starts at the user code that declared the state or transition. /// public static string RemoveGarbageFromStackTrace(string stackTrace) { - var lineIdx = stackTrace.IndexOf('\n') + 1; - do + var lines = stackTrace.Split('\n'); + var first = 0; + + while (first < lines.Length && IsPackageFrame(lines[first])) { - stackTrace = stackTrace.Remove(0, lineIdx); - lineIdx = stackTrace.IndexOf('\n') + 1; + first++; } - while (stackTrace.Substring(0, lineIdx).Contains("StateMachine.Internal")); - return stackTrace + "\n"; + return string.Join("\n", lines, first, lines.Length - first) + "\n"; + } + + private static bool IsPackageFrame(string line) + { + return line.Contains("System.Environment") || + line.Contains("GameLovers.StatechartMachine.Internal.") || + line.Contains("GameLovers.StatechartMachine.Statechart"); } } } diff --git a/Runtime/Internal/TaskWaitState.cs b/Runtime/Internal/TaskWaitState.cs index 2d84a2a..7764e84 100644 --- a/Runtime/Internal/TaskWaitState.cs +++ b/Runtime/Internal/TaskWaitState.cs @@ -1,8 +1,8 @@ using Cysharp.Threading.Tasks; using System; using System.Collections.Generic; +using System.Threading; using System.Threading.Tasks; -using UnityEngine; // ReSharper disable CheckNamespace @@ -12,9 +12,10 @@ namespace GameLovers.StatechartMachine.Internal internal class TaskWaitState : StateInternal, ITaskWaitState { private ITransitionInternal _transition; - private Func _taskAwaitAction; + private Func _taskAwaitAction; private IStatechartEvent _eventQueued; private bool _triggered; + private int _enterCount; private readonly IList _onEnter = new List(); private readonly IList _onExit = new List(); @@ -38,11 +39,15 @@ public void EnqueuEvent(IStatechartEvent statechartEvent) _eventQueued ??= statechartEvent; } + /// + public override StateKind Kind => StateKind.TaskWait; + /// public override void Enter() { _eventQueued = null; _triggered = false; + _enterCount++; Completed = false; for (int i = 0; i < _onEnter.Count; i++) @@ -88,7 +93,7 @@ public void OnEnter(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnEnter action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnEnter action"); } _onEnter.Add(action); @@ -99,7 +104,7 @@ public void OnExit(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnExit action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnExit action"); } _onExit.Add(action); @@ -108,24 +113,39 @@ public void OnExit(Action action) /// public ITransition WaitingFor(Func taskAwaitAction) { - if (taskAwaitAction == null) - { - throw new NullReferenceException($"The state {Name} cannot have a null wait action"); - } - - _taskAwaitAction = () => taskAwaitAction().AsUniTask(); - _transition = new Transition(); + ThrowIfNull(taskAwaitAction); - return _transition; + return SetAwaitAction(_ => AwaitTask(taskAwaitAction())); } /// public ITransition WaitingFor(Func taskAwaitAction) { - _taskAwaitAction = taskAwaitAction ?? throw new NullReferenceException($"The state {Name} cannot have a null wait action"); - _transition = new Transition(); + ThrowIfNull(taskAwaitAction); - return _transition; + return SetAwaitAction(_ => taskAwaitAction()); + } + + /// + public ITransition WaitingFor(Func taskAwaitAction) + { + ThrowIfNull(taskAwaitAction); + + return SetAwaitAction(token => AwaitTask(taskAwaitAction(token))); + } + + /// + public ITransition WaitingFor(Func taskAwaitAction) + { + ThrowIfNull(taskAwaitAction); + + return SetAwaitAction(taskAwaitAction); + } + + /// + public override void CollectTransitions(List results) + { + results.Add(new TransitionInfo(_transition, null, TransitionKind.Completion)); } /// @@ -134,40 +154,63 @@ protected override ITransitionInternal OnTrigger(IStatechartEvent statechartEven if (!_triggered) { _triggered = true; - _ = InnerTaskAwait(statechartEvent?.Name); + InnerTaskAwait(_enterCount, Chart.Generation, Chart.CancellationToken).Forget(); } return Completed ? _transition : null; } - private async UniTask InnerTaskAwait(string eventName) + private void ThrowIfNull(Delegate taskAwaitAction) { - try + if (taskAwaitAction == null) { - if (IsStateLogsEnabled) - { - Debug.Log($"TaskWait - '{eventName}' : '{_taskAwaitAction.Target}.{_taskAwaitAction.Method.Name}()' => '{Name}'"); - } + throw new ArgumentNullException(nameof(taskAwaitAction), $"The state {Name} cannot have a null wait action"); + } + } + + private ITransition SetAwaitAction(Func taskAwaitAction) + { + _taskAwaitAction = taskAwaitAction; + _transition = new Transition(); - //await Task.Yield(); - await _taskAwaitAction(); + return _transition; + } - Completed = true; + private static async UniTask AwaitTask(Task task) + { + // Awaiting the Task directly resumes inline when it completes on the main thread; AsUniTask would always + // post the continuation to a later frame. + await task; + } - _stateFactory.Data.StateChartMoveNextCall(_eventQueued); + private async UniTaskVoid InnerTaskAwait(int enterCount, int generation, CancellationToken token) + { + try + { + await _taskAwaitAction(token); + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + // Cancelled by Reset or Dispose: the state was abandoned, so there is nothing left to complete. + return; } catch (Exception e) { - var finalMessage = ""; -#if UNITY_EDITOR || DEBUG - finalMessage = $"\nStackTrace log of '{Name}' state creation bellow.\n{CreationStackTrace}"; -#endif + // A faulted task still completes the state; otherwise the chart and any parent split would wait forever. + ReportFault(e, $"Exception in the state '{Name}', when awaiting the task wait action.", CreationStackTrace); + } + + // Task continuations may resume on a worker thread; the chart and its callbacks only run on the main thread. + await UniTask.SwitchToMainThread(); - Debug.LogError($"Exception in the state '{Name}', when calling the task wait action" + - $"'{_taskAwaitAction.Target}.{_taskAwaitAction.Method.Name}()'.\n" + - $"-->> Check the exception log after this one for more details <<-- {finalMessage}"); - Debug.LogException(e); + if (enterCount != _enterCount || generation != Chart.Generation) + { + return; } + + Completed = true; + + _stateFactory.Data.StateChartMoveNextCall(_eventQueued); } } } diff --git a/Runtime/Internal/Transition.cs b/Runtime/Internal/Transition.cs index 4e2f00e..d128795 100644 --- a/Runtime/Internal/Transition.cs +++ b/Runtime/Internal/Transition.cs @@ -72,7 +72,7 @@ public ITransition Condition(Func condition) { if(condition == null) { - throw new NullReferenceException("The transition cannot have a null condition"); + throw new ArgumentNullException(nameof(condition), "The transition cannot have a null condition"); } #if UNITY_EDITOR || DEBUG @@ -89,7 +89,7 @@ public ITransition OnTransition(Action action) { if (action == null) { - throw new NullReferenceException("The transition cannot have a null OnTransition action"); + throw new ArgumentNullException(nameof(action), "The transition cannot have a null OnTransition action"); } #if UNITY_EDITOR || DEBUG @@ -106,7 +106,7 @@ public void Target(IState state) { if (state == null) { - throw new NullReferenceException("The transition cannot have a null target state"); + throw new ArgumentNullException(nameof(state), "The transition cannot have a null target state"); } TargetState = (IStateInternal) state; diff --git a/Runtime/Internal/TransitionState.cs b/Runtime/Internal/TransitionState.cs index fb0a81e..8eed663 100644 --- a/Runtime/Internal/TransitionState.cs +++ b/Runtime/Internal/TransitionState.cs @@ -16,6 +16,9 @@ public TransitionState(string name, IStateFactoryInternal factory) : base(name, { } + /// + public override StateKind Kind => StateKind.Transition; + /// public override void Enter() { @@ -68,7 +71,7 @@ public void OnEnter(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnEnter action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnEnter action"); } _onEnter.Add(action); @@ -79,12 +82,18 @@ public void OnExit(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnExit action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnExit action"); } _onExit.Add(action); } + /// + public override void CollectTransitions(List results) + { + results.Add(new TransitionInfo(_transition, null, TransitionKind.Automatic)); + } + /// protected override ITransitionInternal OnTrigger(IStatechartEvent statechartEvent) { diff --git a/Runtime/Internal/WaitState.cs b/Runtime/Internal/WaitState.cs index 62331e9..e621423 100644 --- a/Runtime/Internal/WaitState.cs +++ b/Runtime/Internal/WaitState.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using UnityEngine; // ReSharper disable CheckNamespace @@ -13,6 +12,7 @@ internal class WaitState : StateInternal, IWaitState private IWaitActivityInternal _waitingActivity; private Action _waitAction; private bool _triggered; + private int _generation; private readonly IList _onEnter = new List(); private readonly IList _onExit = new List(); @@ -32,12 +32,16 @@ public void ForceComplete() _waitingActivity.ForceComplete(); } + /// + public override StateKind Kind => StateKind.Wait; + /// public override void Enter() { // It needs to create a new activity everytime on to make sure old activities don't override new ones _waitingActivity = new WaitActivity(OnActivityComplete); _triggered = false; + _generation = Chart.Generation; for (int i = 0; i < _onEnter.Count; i++) { @@ -89,7 +93,7 @@ public void OnEnter(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnEnter action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnEnter action"); } _onEnter.Add(action); @@ -100,7 +104,7 @@ public void OnExit(Action action) { if (action == null) { - throw new NullReferenceException($"The state {Name} cannot have a null OnExit action"); + throw new ArgumentNullException(nameof(action), $"The state {Name} cannot have a null OnExit action"); } _onExit.Add(action); @@ -111,7 +115,7 @@ public ITransition Event(IStatechartEvent statechartEvent) { if (statechartEvent == null) { - throw new NullReferenceException($"The state {Name} cannot have a null event"); + throw new ArgumentNullException(nameof(statechartEvent), $"The state {Name} cannot have a null event"); } var transition = new Transition(); @@ -124,7 +128,7 @@ public ITransition Event(IStatechartEvent statechartEvent) /// public ITransition WaitingFor(Action waitAction) { - _waitAction = waitAction ?? throw new NullReferenceException($"The state {Name} cannot have a null wait action"); + _waitAction = waitAction ?? throw new ArgumentNullException(nameof(waitAction), $"The state {Name} cannot have a null wait action"); _transition = new Transition(); return _transition; @@ -132,12 +136,24 @@ public ITransition WaitingFor(Action waitAction) private void OnActivityComplete(uint id) { - if (id == _waitingActivity.Id) + // A completion that arrives after the chart was reset or disposed belongs to an abandoned wait. + if (id == _waitingActivity.Id && _generation == Chart.Generation) { _stateFactory.Data.StateChartMoveNextCall(null); } } + /// + public override void CollectTransitions(List results) + { + foreach (var pair in _events) + { + results.Add(new TransitionInfo(pair.Value, pair.Key, TransitionKind.Event)); + } + + results.Add(new TransitionInfo(_transition, null, TransitionKind.Completion)); + } + /// protected override ITransitionInternal OnTrigger(IStatechartEvent statechartEvent) { @@ -154,34 +170,22 @@ protected override ITransitionInternal OnTrigger(IStatechartEvent statechartEven if (!_triggered) { _triggered = true; - InnerWait(statechartEvent?.Name); + InnerWait(); } return _waitingActivity.IsCompleted ? _transition : null; } - private void InnerWait(string eventName) + private void InnerWait() { try { - if (IsStateLogsEnabled) - { - Debug.Log($"'{eventName}' event triggers the wait method '{_waitAction.Method.Name}'" + - $"from the object {_waitAction.Target} in the state {Name}"); - } _waitAction(_waitingActivity); } catch (Exception e) { - var finalMessage = ""; -#if UNITY_EDITOR || DEBUG - finalMessage = $"\nStackTrace log of '{Name}' state creation bellow.\n{CreationStackTrace}"; -#endif - - Debug.LogError($"Exception in the state '{Name}', when calling the wait action {_waitAction.Method.Name}" + - $" from the object {_waitAction.Target}.\n" + - $"-->> Check the exception log after this one for more details <<-- {finalMessage}"); - Debug.LogException(e); + ReportFault(e, $"Exception in the state '{Name}', when calling the wait action " + + $"{_waitAction.Method.Name} from the object {_waitAction.Target}.", CreationStackTrace); } } } diff --git a/Runtime/Statechart.cs b/Runtime/Statechart.cs index 9bf451f..07028b8 100644 --- a/Runtime/Statechart.cs +++ b/Runtime/Statechart.cs @@ -1,5 +1,8 @@ using System; +using System.Collections.Generic; +using System.Threading; using GameLovers.StatechartMachine.Internal; +using UnityEngine; // ReSharper disable CheckNamespace @@ -11,7 +14,7 @@ namespace GameLovers.StatechartMachine public interface IStateMachineDebug { /// - /// Allows to show logs in the console to help debugging possible errors in the states & transitions + /// Writes every of this chart to the Unity console. /// bool LogsEnabled { get; set; } } @@ -19,20 +22,42 @@ public interface IStateMachineDebug /// /// The main object which represents the State Chart and drives it forward. /// The State Chart schematics are defined in the constructor setup action and cannot be modified during runtime. - /// See for Semantics. + /// Events are processed with run-to-completion semantics: an event triggered while another one is being processed, + /// for example from an enter or transition callback, is queued and processed right after the current one. /// - public interface IStatechart : IStateMachineDebug + public interface IStatechart : IStateMachineDebug, IDisposable { /// - /// Processes the event for the State Chart with run-to-completion paradigm. - /// Triggers only work if the State Chart is not paused. + /// The name used by logs, traces and debugging tools. + /// + string Name { get; } + + /// + /// True after until or . + /// + bool IsRunning { get; } + + /// + /// The read-only topology of the chart, starting at its root region. + /// + RegionNode RootRegion { get; } + + /// + /// Publishes every observable step of the chart in execution order. + /// No trace is allocated or published while nothing subscribes and logs are disabled. + /// + event Action Traced; + + /// + /// Processes the event for the State Chart with run-to-completion paradigm. + /// Triggers only work if the State Chart is running. /// void Trigger(IStatechartEvent trigger); /// /// Start/Resume the control of the State Chart from where is anchored. - /// Does nothing if already running. /// + /// Thrown when the chart was disposed. void Run(); /// @@ -42,33 +67,73 @@ public interface IStatechart : IStateMachineDebug void Pause(); /// - /// Resets the State Chart to it's initial starting point. - /// This call doesn't pause or resume the control of the State Chart. If the State Chart is in waiting - /// mode for an event or paused, it will require a call to resume it. + /// Resets the State Chart to it's initial starting point without running any exit callback. + /// Pending events are dropped and outstanding waits and tasks are abandoned: their completion no longer moves + /// the chart, and tasks awaited with a are cancelled. + /// This call doesn't pause or resume the control of the State Chart. /// void Reset(); + + /// + /// Fills with every active state, parents before their children. + /// Before the only active state is the root initial state. + /// + void GetActiveStates(List results); + + /// + /// Returns true when is currently active. + /// + bool IsActive(StateNode state); } /// public class Statechart : IStatechart { + private static uint _idRef; + private bool _isRunning; + private bool _isProcessing; + private bool _isDisposed; + private int _generation; private IStateInternal _currentState; + private CancellationTokenSource _cancellation = new CancellationTokenSource(); private readonly IStateFactoryInternal _stateFactory; + private readonly Queue _pendingEvents = new Queue(); + private readonly List _activeBuffer = new List(); /// public bool LogsEnabled { get; set; } + /// + public string Name { get; } + /// + public bool IsRunning => _isRunning; + /// + public RegionNode RootRegion { get; } -#if UNITY_EDITOR - /// Name of the state currently active. Editor-only, for debugging. - public string CurrentState => _currentState.Name; -#endif + /// + public event Action Traced; + + /// Changes on every Reset/Dispose so stale wait and task completions can be ignored. + internal int Generation => _generation; + /// Cancelled on Reset/Dispose; passed to token-aware task waits. + internal CancellationToken CancellationToken => _cancellation.Token; + /// True when a trace would reach a subscriber or the console. + internal bool HasTraceListeners => Traced != null || LogsEnabled; - private Statechart() {} + public Statechart(Action setup) : this(null, setup) + { + } - public Statechart(Action setup) + public Statechart(string name, Action setup) { + if (setup == null) + { + throw new ArgumentNullException(nameof(setup)); + } + + Name = string.IsNullOrEmpty(name) ? $"Statechart {++_idRef}" : name; + var stateFactory = new StateFactory(0, new StateFactoryData { Statechart = this, StateChartMoveNextCall = MoveNext }); setup(stateFactory); @@ -77,7 +142,7 @@ public Statechart(Action setup) if (_stateFactory.InitialState == null) { - throw new MissingMemberException("State chart doesn't have initial state"); + throw new InvalidOperationException($"State chart {Name} doesn't have initial state"); } _currentState = _stateFactory.InitialState; @@ -87,6 +152,11 @@ public Statechart(Action setup) { _stateFactory.States[i].Validate(); } +#endif + RootRegion = StatechartTopologyBuilder.Build(_stateFactory); + +#if UNITY_EDITOR + StatechartRegistry.Register(this); #endif } @@ -104,21 +174,143 @@ public void Trigger(IStatechartEvent trigger) /// public void Run() { + if (_isDisposed) + { + throw new ObjectDisposedException(Name); + } + _isRunning = true; + Emit(new StatechartTrace(this, StatechartTraceKind.Started)); MoveNext(null); } /// public void Pause() { + if (!_isRunning) + { + return; + } + _isRunning = false; + + Emit(new StatechartTrace(this, StatechartTraceKind.Paused)); } /// public void Reset() { + if (_isDisposed) + { + return; + } + + AbandonPendingWork(); + _cancellation = new CancellationTokenSource(); _currentState = _stateFactory.InitialState; + + Emit(new StatechartTrace(this, StatechartTraceKind.Reset)); + } + + /// + /// Stops the chart for good: pauses it, abandons pending waits and tasks, cancels token-aware tasks and + /// unregisters it from debugging tools. Calling it again does nothing. + /// + public void Dispose() + { + if (_isDisposed) + { + return; + } + + _isRunning = false; + _isDisposed = true; + + AbandonPendingWork(); + Emit(new StatechartTrace(this, StatechartTraceKind.Disposed)); + + Traced = null; + +#if UNITY_EDITOR + StatechartRegistry.Unregister(this); +#endif + } + + /// + public void GetActiveStates(List results) + { + if (results == null) + { + throw new ArgumentNullException(nameof(results)); + } + + results.Clear(); + AddActive(_currentState, results); + } + + /// + public bool IsActive(StateNode state) + { + if (state == null) + { + return false; + } + + GetActiveStates(_activeBuffer); + + return _activeBuffer.Contains(state); + } + + /// + public override string ToString() + { + return Name; + } + + /// Publishes to subscribers and, when logging is on, the console. + internal void Emit(in StatechartTrace trace, bool forceLog = false) + { + Traced?.Invoke(trace); + + if (trace.Kind == StatechartTraceKind.Faulted) + { + // Faults are always reported by the throwing site; repeating them here would double every error. + return; + } + + if (LogsEnabled || forceLog) + { + Debug.Log(trace.ToString()); + } + } + + private static void AddActive(IStateInternal state, List results) + { + results.Add(state.Node); + + if (state is not SplitState split) + { + return; + } + + for (var i = 0; i < split.Regions.Count; i++) + { + var current = split.Regions[i].CurrenState; + + if (current != null) + { + AddActive(current, results); + } + } + } + + private void AbandonPendingWork() + { + _generation++; + _pendingEvents.Clear(); + _cancellation.Cancel(); + _cancellation.Dispose(); } private void MoveNext(IStatechartEvent trigger) @@ -128,10 +320,55 @@ private void MoveNext(IStatechartEvent trigger) return; } + if (_isProcessing) + { + // Several completions can request a re-evaluation in one step; one queued null trigger covers them all. + if (trigger != null || !_pendingEvents.Contains(null)) + { + _pendingEvents.Enqueue(trigger); + } + + return; + } + + _isProcessing = true; + + try + { + Process(trigger); + + while (_isRunning && _pendingEvents.Count > 0) + { + Process(_pendingEvents.Dequeue()); + } + } + finally + { + _isProcessing = false; + } + } + + private void Process(IStatechartEvent trigger) + { + var generation = _generation; + + if (trigger != null) + { + Emit(new StatechartTrace(this, StatechartTraceKind.EventTriggered, _currentState.Node, null, trigger)); + } + var nextState = _currentState.Trigger(trigger); - while (nextState != null) + + while (nextState != null && generation == _generation) { _currentState = nextState; + + if (!_isRunning) + { + // Paused from a callback: the entered state is processed again on the next Run(). + return; + } + nextState = _currentState.Trigger(null); } } diff --git a/Runtime/StatechartExport.cs b/Runtime/StatechartExport.cs new file mode 100644 index 0000000..754574c --- /dev/null +++ b/Runtime/StatechartExport.cs @@ -0,0 +1,171 @@ +using System; +using System.Collections.Generic; +using System.Text; + +// ReSharper disable CheckNamespace + +namespace GameLovers.StatechartMachine +{ + /// + /// Text exports of a statechart's topology and active states, for logs, bug reports and AI agents. + /// + public static class StatechartExport + { + /// + /// Returns a Mermaid stateDiagram-v2 of , with active states marked by the + /// active class. Initial and final states map to Mermaid's [*] markers. + /// + /// The chart to export. + /// The Mermaid source text. + /// Thrown when is null. + public static string ToMermaid(IStatechart statechart) + { + if (statechart == null) + { + throw new ArgumentNullException(nameof(statechart)); + } + + var builder = new StringBuilder(); + var active = new List(); + + statechart.GetActiveStates(active); + builder.AppendLine("stateDiagram-v2"); + AppendRegion(builder, statechart.RootRegion, 1, new List()); + builder.AppendLine(" classDef active fill:#9be7b0,stroke:#1d7a3d,stroke-width:2px"); + + var activeIds = new List(); + + foreach (var state in active) + { + if (state.Kind != StateKind.Initial && state.Kind != StateKind.Final) + { + activeIds.Add(Id(state)); + } + } + + if (activeIds.Count > 0) + { + builder.Append(" class ").Append(string.Join(",", activeIds)).AppendLine(" active"); + } + + return builder.ToString(); + } + + /// + /// Returns the active states of as one path per line, for example + /// Gameplay/Player/Idle, parents before children. + /// + /// The chart to describe. + /// The active state paths. + /// Thrown when is null. + public static string ToActivePaths(IStatechart statechart) + { + if (statechart == null) + { + throw new ArgumentNullException(nameof(statechart)); + } + + var active = new List(); + var builder = new StringBuilder(); + + statechart.GetActiveStates(active); + + foreach (var state in active) + { + builder.AppendLine(state.Path); + } + + return builder.ToString(); + } + + private static void AppendRegion(StringBuilder builder, RegionNode region, int depth, List leaveEdges) + { + var indent = new string(' ', depth * 2); + + foreach (var state in region.States) + { + if (state.Kind == StateKind.Initial || state.Kind == StateKind.Final) + { + continue; + } + + if (state.Regions.Count == 0) + { + builder.Append(indent).Append(Id(state)).Append(" : ").AppendLine(Label(state)); + continue; + } + + builder.Append(indent).Append("state \"").Append(Label(state)).Append("\" as ").Append(Id(state)) + .AppendLine(" {"); + + var innerLeaves = new List(); + + for (var i = 0; i < state.Regions.Count; i++) + { + if (i > 0) + { + builder.Append(indent).AppendLine(" --"); + } + + AppendRegion(builder, state.Regions[i], depth + 1, innerLeaves); + } + + builder.Append(indent).AppendLine("}"); + + // Mermaid cannot draw an edge out of a composite from inside it, so a leave is drawn from its owner. + foreach (var leave in innerLeaves) + { + builder.Append(indent).Append(Id(state)).Append(" --> ").Append(Endpoint(leave.Target)) + .Append(" : leave ").AppendLine(leave.Source.Name.Replace(":", " ")); + } + } + + foreach (var state in region.States) + { + foreach (var edge in state.Transitions) + { + if (edge.Target == null) + { + continue; + } + + if (edge.Kind == TransitionKind.Leave) + { + leaveEdges.Add(edge); + continue; + } + + var label = edge.Event?.Name ?? (edge.HasCondition ? "[condition]" : null); + + builder.Append(indent).Append(Endpoint(edge.Source)).Append(" --> ").Append(Endpoint(edge.Target)); + + if (label != null) + { + builder.Append(" : ").Append(label.Replace(":", " ")); + } + + builder.AppendLine(); + } + } + } + + private static string Endpoint(StateNode state) + { + return state.Kind == StateKind.Initial || state.Kind == StateKind.Final ? "[*]" : Id(state); + } + + private static string Id(StateNode state) + { + return $"s{state.Id}"; + } + + private static string Label(StateNode state) + { + var name = state.Name.Replace("\"", "'").Replace(":", " "); + + return state.Kind == StateKind.Simple || state.Kind == StateKind.Nest || state.Kind == StateKind.Split + ? name + : $"{name} ({state.Kind})"; + } + } +} diff --git a/Runtime/StatechartExport.cs.meta b/Runtime/StatechartExport.cs.meta new file mode 100644 index 0000000..cd1bcb0 --- /dev/null +++ b/Runtime/StatechartExport.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 58160ead0971451abe547f2f3e680129 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/StatechartTopology.cs b/Runtime/StatechartTopology.cs new file mode 100644 index 0000000..5aca67e --- /dev/null +++ b/Runtime/StatechartTopology.cs @@ -0,0 +1,180 @@ +using System.Collections.Generic; + +// ReSharper disable CheckNamespace + +namespace GameLovers.StatechartMachine +{ + /// + /// The kind of state a describes, matching the method that + /// created it. + /// + public enum StateKind + { + Initial, // Created by IStateFactory.Initial + Final, // Created by IStateFactory.Final + Simple, // Created by IStateFactory.State + Transition, // Created by IStateFactory.Transition + Choice, // Created by IStateFactory.Choice + Wait, // Created by IStateFactory.Wait + TaskWait, // Created by IStateFactory.TaskWait + Nest, // Created by IStateFactory.Nest + Split, // Created by IStateFactory.Split + Leave // Created by IStateFactory.Leave + } + + /// + /// What causes a to be taken. + /// + public enum TransitionKind + { + Event, // Taken when its event is triggered + Automatic, // Taken as soon as the source state is processed (initial and transition states) + Choice, // A choice branch, conditional or the fallback + Completion, // Taken when the source's wait, task or nested regions complete + Leave // Leaves the enclosing region from a leave state + } + + /// + /// Read-only description of one state in a . + /// The topology is built once when the statechart is constructed and never changes afterwards. + /// + public sealed class StateNode + { + /// + /// Unique id of the state within the running application. + /// + public uint Id { get; } + /// + /// The name given to the state in the setup. + /// + public string Name { get; } + /// + /// The kind of state. + /// + public StateKind Kind { get; } + /// + /// The region that contains this state. + /// + public RegionNode Region { get; } + /// + /// The nest or split state that owns , or null for root states. + /// + public StateNode Parent => Region.Owner; + /// + /// The nesting depth; root states have depth 0. + /// + public int Depth => Region.Depth; + /// + /// The slash-separated names from the root to this state, for example Gameplay/Idle. + /// + public string Path { get; } + /// + /// The nested regions of a nest (one) or split (two or more) state; empty for every other kind. + /// + public IReadOnlyList Regions => _regions; + /// + /// The outgoing transitions of this state. + /// + public IReadOnlyList Transitions => _transitions; + + internal readonly List _regions = new List(); + internal readonly List _transitions = new List(); + + internal StateNode(uint id, string name, StateKind kind, RegionNode region) + { + Id = id; + Name = name; + Kind = kind; + Region = region; + Path = region.Owner == null ? name : $"{region.Owner.Path}/{name}"; + } + + /// + public override string ToString() + { + return Path; + } + } + + /// + /// Read-only description of one region: a sequential group of states with a single initial state. + /// + public sealed class RegionNode + { + /// + /// The nest or split state that owns this region, or null for the root region. + /// + public StateNode Owner { get; } + /// + /// The position of this region among its owner's regions. + /// + public int Index { get; } + /// + /// The nesting depth of the states in this region; the root region has depth 0. + /// + public int Depth { get; } + /// + /// The states declared in this region, in declaration order. + /// + public IReadOnlyList States => _states; + /// + /// The initial state of this region. + /// + public StateNode Initial { get; internal set; } + + internal readonly List _states = new List(); + + internal RegionNode(StateNode owner, int index, int depth) + { + Owner = owner; + Index = index; + Depth = depth; + } + } + + /// + /// Read-only description of one transition between two states. + /// + public sealed class TransitionEdge + { + /// + /// The state that owns the transition. + /// + public StateNode Source { get; } + /// + /// The state the transition moves to, or null for an action-only event transition. + /// + public StateNode Target { get; } + /// + /// The event that triggers the transition, or null when is not + /// . + /// + public IStatechartEvent Event { get; } + /// + /// What causes the transition. + /// + public TransitionKind Kind { get; } + /// + /// True when the transition has at least one guard condition. + /// + public bool HasCondition { get; } + + internal TransitionEdge(StateNode source, StateNode target, IStatechartEvent statechartEvent, + TransitionKind kind, bool hasCondition) + { + Source = source; + Target = target; + Event = statechartEvent; + Kind = kind; + HasCondition = hasCondition; + } + + /// + public override string ToString() + { + var label = Event?.Name ?? Kind.ToString(); + + return $"{Source.Name} -({label})-> {Target?.Name ?? "(action only)"}"; + } + } +} diff --git a/Runtime/StatechartTopology.cs.meta b/Runtime/StatechartTopology.cs.meta new file mode 100644 index 0000000..0580f1c --- /dev/null +++ b/Runtime/StatechartTopology.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2bc40ac7ac4a46f18524cacc8c05d1b5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Runtime/StatechartTrace.cs b/Runtime/StatechartTrace.cs new file mode 100644 index 0000000..06efb51 --- /dev/null +++ b/Runtime/StatechartTrace.cs @@ -0,0 +1,90 @@ +using System; + +// ReSharper disable CheckNamespace + +namespace GameLovers.StatechartMachine +{ + /// + /// The kind of step a records. + /// + public enum StatechartTraceKind + { + Started, // Run() started or resumed the chart + Paused, // Pause() stopped the chart + Reset, // Reset() moved the chart back to its initial state + Disposed, // Dispose() released the chart + EventTriggered, // An event started processing + StateExited, // A state is about to run its exit callbacks + Transition, // A transition is about to run its transition callbacks + StateEntered, // A state is about to run its enter callbacks + Faulted // A user callback, wait action or awaited task threw + } + + /// + /// One observable step of a running , published through + /// in execution order. + /// + public readonly struct StatechartTrace + { + /// + /// The statechart that produced this step. + /// + public IStatechart Statechart { get; } + /// + /// What happened. + /// + public StatechartTraceKind Kind { get; } + /// + /// The state the step is about: the exited, entered or faulted state, or a transition's source. + /// + public StateNode State { get; } + /// + /// The target of a ; null for action-only transitions and for + /// every other kind. + /// + public StateNode Target { get; } + /// + /// The event being processed when the step happened, or null when the chart moved on its own. + /// + public IStatechartEvent Event { get; } + /// + /// The exception of a step; null otherwise. + /// + public Exception Exception { get; } + + internal StatechartTrace(IStatechart statechart, StatechartTraceKind kind, StateNode state = null, + StateNode target = null, IStatechartEvent statechartEvent = null, + Exception exception = null) + { + Statechart = statechart; + Kind = kind; + State = state; + Target = target; + Event = statechartEvent; + Exception = exception; + } + + /// + public override string ToString() + { + var prefix = $"[Statechart '{Statechart?.Name}']"; + var eventSuffix = Event == null ? "" : $" on '{Event.Name}'"; + + switch (Kind) + { + case StatechartTraceKind.EventTriggered: + return $"{prefix} event '{Event?.Name}'"; + case StatechartTraceKind.StateExited: + return $"{prefix} exit {State?.Path}"; + case StatechartTraceKind.StateEntered: + return $"{prefix} enter {State?.Path}"; + case StatechartTraceKind.Transition: + return $"{prefix} {State?.Path} -> {Target?.Path ?? "(action only)"}{eventSuffix}"; + case StatechartTraceKind.Faulted: + return $"{prefix} fault in {State?.Path}: {Exception?.GetType().Name} {Exception?.Message}"; + default: + return $"{prefix} {Kind}"; + } + } + } +} diff --git a/Runtime/StatechartTrace.cs.meta b/Runtime/StatechartTrace.cs.meta new file mode 100644 index 0000000..be024d1 --- /dev/null +++ b/Runtime/StatechartTrace.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9e243932bbdd4fb6acaf8f9f2e3261ef +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Samples~/GameFlow/GameFlow.unity b/Samples~/GameFlow/GameFlow.unity new file mode 100644 index 0000000..6474702 --- /dev/null +++ b/Samples~/GameFlow/GameFlow.unity @@ -0,0 +1,279 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!29 &1 +OcclusionCullingSettings: + m_ObjectHideFlags: 0 + serializedVersion: 2 + m_OcclusionBakeSettings: + smallestOccluder: 5 + smallestHole: 0.25 + backfaceThreshold: 100 + m_SceneGUID: 00000000000000000000000000000000 + m_OcclusionCullingData: {fileID: 0} +--- !u!104 &2 +RenderSettings: + m_ObjectHideFlags: 0 + serializedVersion: 10 + m_Fog: 0 + m_FogColor: {r: 0.5, g: 0.5, b: 0.5, a: 1} + m_FogMode: 3 + m_FogDensity: 0.01 + m_LinearFogStart: 0 + m_LinearFogEnd: 300 + m_AmbientSkyColor: {r: 0.212, g: 0.227, b: 0.259, a: 1} + m_AmbientEquatorColor: {r: 0.114, g: 0.125, b: 0.133, a: 1} + m_AmbientGroundColor: {r: 0.047, g: 0.043, b: 0.035, a: 1} + m_AmbientIntensity: 1 + m_AmbientMode: 0 + m_SubtractiveShadowColor: {r: 0.42, g: 0.478, b: 0.627, a: 1} + m_SkyboxMaterial: {fileID: 10304, guid: 0000000000000000f000000000000000, type: 0} + m_HaloStrength: 0.5 + m_FlareStrength: 1 + m_FlareFadeSpeed: 3 + m_HaloTexture: {fileID: 0} + m_SpotCookie: {fileID: 10001, guid: 0000000000000000e000000000000000, type: 0} + m_DefaultReflectionMode: 0 + m_DefaultReflectionResolution: 128 + m_ReflectionBounces: 1 + m_ReflectionIntensity: 1 + m_CustomReflection: {fileID: 0} + m_Sun: {fileID: 0} + m_UseRadianceAmbientProbe: 0 +--- !u!157 &3 +LightmapSettings: + m_ObjectHideFlags: 0 + serializedVersion: 13 + m_BakeOnSceneLoad: 0 + m_GISettings: + serializedVersion: 2 + m_BounceScale: 1 + m_IndirectOutputScale: 1 + m_AlbedoBoost: 1 + m_EnvironmentLightingMode: 0 + m_EnableBakedLightmaps: 1 + m_EnableRealtimeLightmaps: 0 + m_LightmapEditorSettings: + serializedVersion: 12 + m_Resolution: 2 + m_BakeResolution: 40 + m_AtlasSize: 1024 + m_AO: 0 + m_AOMaxDistance: 1 + m_CompAOExponent: 1 + m_CompAOExponentDirect: 0 + m_ExtractAmbientOcclusion: 0 + m_Padding: 2 + m_LightmapParameters: {fileID: 0} + m_LightmapsBakeMode: 1 + m_TextureCompression: 1 + m_ReflectionCompression: 2 + m_MixedBakeMode: 2 + m_BakeBackend: 2 + m_PVRSampling: 1 + m_PVRDirectSampleCount: 32 + m_PVRSampleCount: 512 + m_PVRBounces: 2 + m_PVREnvironmentSampleCount: 256 + m_PVREnvironmentReferencePointCount: 2048 + m_PVRFilteringMode: 1 + m_PVRDenoiserTypeDirect: 2 + m_PVRDenoiserTypeIndirect: 2 + m_PVRDenoiserTypeAO: 2 + m_PVRFilterTypeDirect: 0 + m_PVRFilterTypeIndirect: 0 + m_PVRFilterTypeAO: 0 + m_PVREnvironmentMIS: 1 + m_PVRCulling: 1 + m_PVRFilteringGaussRadiusDirect: 1 + m_PVRFilteringGaussRadiusIndirect: 1 + m_PVRFilteringGaussRadiusAO: 1 + m_PVRFilteringAtrousPositionSigmaDirect: 0.5 + m_PVRFilteringAtrousPositionSigmaIndirect: 2 + m_PVRFilteringAtrousPositionSigmaAO: 1 + m_ExportTrainingData: 0 + m_TrainingDataDestination: TrainingData + m_LightProbeSampleCountMultiplier: 4 + m_LightingDataAsset: {fileID: 20201, guid: 0000000000000000f000000000000000, type: 0} + m_LightingSettings: {fileID: 0} +--- !u!196 &4 +NavMeshSettings: + serializedVersion: 2 + m_ObjectHideFlags: 0 + m_BuildSettings: + serializedVersion: 3 + agentTypeID: 0 + agentRadius: 0.5 + agentHeight: 2 + agentSlope: 45 + agentClimb: 0.4 + ledgeDropHeight: 0 + maxJumpAcrossDistance: 0 + minRegionArea: 2 + manualCellSize: 0 + cellSize: 0.16666667 + manualTileSize: 0 + tileSize: 256 + buildHeightMesh: 0 + maxJobWorkers: 0 + preserveTilesOutsideBounds: 0 + debug: + m_Flags: 0 + m_NavMeshData: {fileID: 0} +--- !u!1 &609648222 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 609648225} + - component: {fileID: 609648224} + - component: {fileID: 609648223} + m_Layer: 0 + m_Name: Game Flow + m_TagString: Untagged + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!114 &609648223 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 609648222} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: c31eda84241be490c8ba644c62282f64, type: 3} + m_Name: + m_EditorClassIdentifier: GameLovers.Statechart.Samples.GameFlow::GameLovers.StatechartMachine.Samples.GameFlow.GameFlowSample + _document: {fileID: 609648224} +--- !u!114 &609648224 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 609648222} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 19102, guid: 0000000000000000e000000000000000, type: 0} + m_Name: + m_EditorClassIdentifier: UnityEngine.dll::UnityEngine.UIElements.UIDocument + m_PanelSettings: {fileID: 11400000, guid: 28ff431fcb6b34c878a226c193dfb62b, type: 2} + m_ParentUI: {fileID: 0} + sourceAsset: {fileID: 9197481963319205126, guid: e541c877dd86c4642abe51b8d4c03791, type: 3} + m_SortingOrder: 0 + m_Position: 0 + m_WorldSpaceSizeMode: 1 + m_WorldSpaceWidth: 1920 + m_WorldSpaceHeight: 1080 + m_PivotReferenceSize: 0 + m_Pivot: 0 + m_WorldSpaceCollider: {fileID: 0} +--- !u!4 &609648225 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 609648222} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 0} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1 &1017260713 +GameObject: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + serializedVersion: 6 + m_Component: + - component: {fileID: 1017260715} + - component: {fileID: 1017260714} + m_Layer: 0 + m_Name: Main Camera + m_TagString: MainCamera + m_Icon: {fileID: 0} + m_NavMeshLayer: 0 + m_StaticEditorFlags: 0 + m_IsActive: 1 +--- !u!20 &1017260714 +Camera: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1017260713} + m_Enabled: 1 + serializedVersion: 2 + m_ClearFlags: 2 + m_BackGroundColor: {r: 0.11, g: 0.12, b: 0.15, a: 1} + m_projectionMatrixMode: 1 + m_GateFitMode: 2 + m_FOVAxisMode: 0 + m_Iso: 200 + m_ShutterSpeed: 0.005 + m_Aperture: 16 + m_FocusDistance: 10 + m_FocalLength: 50 + m_BladeCount: 5 + m_Curvature: {x: 2, y: 11} + m_BarrelClipping: 0.25 + m_Anamorphism: 0 + m_SensorSize: {x: 36, y: 24} + m_LensShift: {x: 0, y: 0} + m_NormalizedViewPortRect: + serializedVersion: 2 + x: 0 + y: 0 + width: 1 + height: 1 + near clip plane: 0.3 + far clip plane: 1000 + field of view: 60 + orthographic: 0 + orthographic size: 5 + m_Depth: 0 + m_CullingMask: + serializedVersion: 2 + m_Bits: 4294967295 + m_RenderingPath: -1 + m_TargetTexture: {fileID: 0} + m_TargetDisplay: 0 + m_TargetEye: 3 + m_HDR: 1 + m_AllowMSAA: 1 + m_AllowDynamicResolution: 0 + m_ForceIntoRT: 0 + m_OcclusionCulling: 1 + m_StereoConvergence: 10 + m_StereoSeparation: 0.022 +--- !u!4 &1017260715 +Transform: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 1017260713} + serializedVersion: 2 + m_LocalRotation: {x: 0, y: 0, z: 0, w: 1} + m_LocalPosition: {x: 0, y: 0, z: 0} + m_LocalScale: {x: 1, y: 1, z: 1} + m_ConstrainProportionsScale: 0 + m_Children: [] + m_Father: {fileID: 0} + m_LocalEulerAnglesHint: {x: 0, y: 0, z: 0} +--- !u!1660057539 &9223372036854775807 +SceneRoots: + m_ObjectHideFlags: 0 + m_Roots: + - {fileID: 1017260715} + - {fileID: 609648225} diff --git a/Samples~/GameFlow/GameFlow.unity.meta b/Samples~/GameFlow/GameFlow.unity.meta new file mode 100644 index 0000000..cbbf47f --- /dev/null +++ b/Samples~/GameFlow/GameFlow.unity.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: d2aa569a0247b4dad98f3c417280a0dc +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Samples~/GameFlow/README.md b/Samples~/GameFlow/README.md new file mode 100644 index 0000000..8135ad7 --- /dev/null +++ b/Samples~/GameFlow/README.md @@ -0,0 +1,25 @@ +# Game Flow sample + +One statechart drives a small game loop. Between them, its states use every state kind: + +| State | Kind | What it shows | +| --- | --- | --- | +| Boot | Nest | A sequential nested region that completes, then moves to Menu | +| Load Config, Warm Up | TaskWait | Token-aware `UniTask` work that is cancelled if the chart resets or is disposed | +| Menu, Idle, Results | Simple | Event transitions (Play, Jump, Hit, Retry) | +| Gameplay | Split | Two parallel regions: the player and the waves | +| Airborne, Spawning | Wait | Callback waits completed by a coroutine; Airborne still reacts to Hit | +| More Waves? | Choice | A guarded branch with a fallback | +| Next Wave, Reset Score | Transition | Pass-through states that run an action | +| Defeated, Victory | Leave | Leave the split from either region and go to Results | + +## Run it + +1. Open `GameFlow.unity` and enter Play mode. +2. Open **Tools > GameLovers > Statechart Debugger** and dock it next to the Game view. +3. Use the on-screen buttons. The debugger follows the chart live: + - **A · Live chart** shows nested boxes with the active states highlighted. + - **B · Graph** (Unity 6.6 and newer) opens the chart as a Graph Toolkit graph that highlights active nodes and taken transitions. + - **C · Tree + trace** shows the state tree and the latest trace steps. + +The Activity panel in the game lists the same events and state entries from `IStatechart.Traced`. diff --git a/Samples~/GameFlow/README.md.meta b/Samples~/GameFlow/README.md.meta new file mode 100644 index 0000000..6c0bfb9 --- /dev/null +++ b/Samples~/GameFlow/README.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: cb447aa762b214ff1976c77210739163 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Samples~/GameFlow/Scripts.meta b/Samples~/GameFlow/Scripts.meta new file mode 100644 index 0000000..032056b --- /dev/null +++ b/Samples~/GameFlow/Scripts.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 26ac8dda7a47a4e2c969c4bea3151844 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Samples~/GameFlow/Scripts/GameFlowSample.cs b/Samples~/GameFlow/Scripts/GameFlowSample.cs new file mode 100644 index 0000000..c925e99 --- /dev/null +++ b/Samples~/GameFlow/Scripts/GameFlowSample.cs @@ -0,0 +1,237 @@ +using System.Collections; +using System.Collections.Generic; +using System.Threading; +using Cysharp.Threading.Tasks; +using UnityEngine; +using UnityEngine.UIElements; + +// ReSharper disable CheckNamespace + +namespace GameLovers.StatechartMachine.Samples.GameFlow +{ + /// + /// A small game loop driven by one statechart that uses every state kind: a nested boot sequence with task waits, + /// a menu, a split gameplay state with a player region and a waves region, choices, leave states and results. + /// + public class GameFlowSample : MonoBehaviour + { + private const int WaveCount = 3; + private const int ActivityLines = 14; + + [SerializeField] private UIDocument _document; + + private readonly IStatechartEvent _play = new StatechartEvent("Play"); + private readonly IStatechartEvent _jump = new StatechartEvent("Jump"); + private readonly IStatechartEvent _hit = new StatechartEvent("Hit"); + private readonly IStatechartEvent _quit = new StatechartEvent("Quit"); + private readonly IStatechartEvent _retry = new StatechartEvent("Retry"); + private readonly Queue _activity = new Queue(); + private readonly List _active = new List(); + + private IStatechart _statechart; + private int _wave; + private bool _won; + private Label _phase; + private Label _detail; + private Label _waves; + private Label _activityLog; + private VisualElement _player; + private Button _playButton; + private Button _jumpButton; + private Button _hitButton; + private Button _quitButton; + private Button _retryButton; + + private void Awake() + { + var root = _document.rootVisualElement; + + _phase = root.Q