Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

docs(ai): four subsystems were sharing one page

yhh470971c9474f
diff --git a/docs/astro/astro.config.mjs b/docs/astro/astro.config.mjs
index d1acced3c..b1fe4e20d 100644
--- a/docs/astro/astro.config.mjs
+++ b/docs/astro/astro.config.mjs
@@ -206,7 +206,21 @@ export default defineConfig({
items: [
{ label: 'Physics', translations: { 'zh-CN': '物理' }, slug: 'gameplay/physics' },
{ label: 'Markers & Trigger Areas', translations: { 'zh-CN': '标记与触发区' }, slug: 'gameplay/markers' },
- { label: 'Gameplay AI', translations: { 'zh-CN': '游戏 AI' }, slug: 'gameplay/ai' },
+ {
+ label: 'Gameplay AI',
+ translations: { 'zh-CN': '游戏 AI' },
+ collapsed: true,
+ items: [
+ { label: 'Overview', translations: { 'zh-CN': '总览' }, slug: 'gameplay/ai' },
+ { label: 'Perception', translations: { 'zh-CN': '感知' }, slug: 'gameplay/ai-perception' },
+ { label: 'Navigation', translations: { 'zh-CN': '导航' }, slug: 'gameplay/ai-navigation' },
+ { label: 'State Machines', translations: { 'zh-CN': '状态机' }, slug: 'gameplay/ai-state-machines' },
+ { label: 'Behavior Trees', translations: { 'zh-CN': '行为树' }, slug: 'gameplay/ai-behavior-trees' },
+ { label: 'The Blackboard', translations: { 'zh-CN': '黑板' }, slug: 'gameplay/ai-blackboard' },
+ { label: 'Authoring in the Editor', translations: { 'zh-CN': '在编辑器里编排' }, slug: 'gameplay/ai-authoring' },
+ { label: 'Below the Components', translations: { 'zh-CN': '组件层之下' }, slug: 'gameplay/ai-advanced' },
+ ],
+ },
],
},
{
diff --git a/docs/astro/src/content/docs/gameplay/ai-advanced.mdx b/docs/astro/src/content/docs/gameplay/ai-advanced.mdx
new file mode 100644
index 000000000..07c3726a9
--- /dev/null
+++ b/docs/astro/src/content/docs/gameplay/ai-advanced.mdx
@@ -0,0 +1,126 @@
+---
+title: Below the components
+description: "The primitives under the component layer — pathfinding by hand, perception internals, and wiring the plugins in a bare App."
+---
+
+`Nav`, `NavAgent`, and `Perceiver` — the component layer — cover the common cases.
+The primitives beneath them are exported too, all pure TypeScript with no engine
+or wasm dependency, for when you need a path without an agent or a sight check
+without a `Perceiver`.
+
+### Pathfinding by hand
+
+`findPath` is the A\* the nav plugin uses: uniform-cost search over `NavGrid`
+cells, 4- or 8-connected, with an octile/manhattan heuristic and no corner
+cutting (a diagonal step needs both shared orthogonal cells open). Drop to it
+when you steer movement yourself, draw a path preview, or compute reachability
+for turn-based ranges — or when one grid isn't enough, since the `Nav` resource
+holds a single grid:
+
+```typescript
+import { NavGrid, findPath, pathToWorld } from 'esengine';
+
+const grid = new NavGrid({ width: 32, height: 24, cellSize: 32 });
+
+const path = findPath(
+ grid,
+ grid.worldToCell(hero.x, hero.y), // Cell — integer grid coordinates
+ grid.worldToCell(chest.x, chest.y),
+ { diagonal: false },
+);
+if (path) {
+ const waypoints = pathToWorld(grid, path); // Vec2[] — cell centers, world pixels
+}
+```
+
+`findPath(grid, start, goal, opts?)` returns the `Cell[]` path inclusive of both
+endpoints, or `null` when unreachable. A `Cell` is an integer grid coordinate
+`{ x, y }` (kept distinct from `Vec2` to flag cell space); convert with
+`grid.worldToCell` / `grid.cellToWorld`, or turn a whole path into world-space
+waypoints with `pathToWorld`.
+
+| `PathfindOptions` field | Default | Description |
+|---|---|---|
+| `diagonal` | `true` | Allow 8-connected diagonal moves. |
+| `snapRadius` | `8` | When start/goal lands on a blocked cell, snap to the nearest walkable cell within this ring radius before searching; `0` disables snapping. |
+
+`navGridFromTiles` builds the walkability mask from any tile reader — it is the
+core under `navGridFromTilemapLayer`, which just plugs in `TilemapAPI.getTile`:
+
+```typescript
+import { navGridFromTiles } from 'esengine';
+
+const grid = navGridFromTiles((x, y) => level.tiles[y][x], {
+ width: 32, height: 24, cellSize: 32,
+ blockedTileIds: [WALL_TILE, WATER_TILE],
+});
+```
+
+| `BuildNavGridOptions` field | Description |
+|---|---|
+| `width` / `height` / `cellSize` / `origin?` | Same as the `NavGrid` options (see [Building a grid](/docs/gameplay/ai-navigation/#building-a-grid)). |
+| `blockedTileIds?` | Exact set of tile ids that block movement. |
+| `isBlocked?` | Custom predicate over the tile id (`0` = empty); overrides `blockedTileIds`. With neither given, any non-empty tile blocks. |
+
+### Perception internals
+
+The perception plugin is a thin wrapper over four exported functions — useful for
+one-off sight checks from an action, custom senses (memory, hearing, multiple
+targets), or unit tests against a fake world:
+
+- **`senseTarget(ox, oy, facing, tx, ty, range, halfFov, isBlocked?)`** — the pure
+ geometry: a range check, a FOV cone check (`halfFov` is *half* the cone in
+ radians; ≥ π means omnidirectional), then the optional occlusion callback.
+- **`facingFromQuat(z, w)`** — 2D facing angle in radians from a `Transform`
+ rotation quaternion's z/w components.
+- **`makeLosCheck(physics)`** — builds the occlusion callback from a physics
+ raycast: occluded when any hit lands clearly short of the target
+ (`fraction < 0.98` — the last ~2% is the target itself).
+- **`stepPerception(world, isBlocked?)`** — the exact per-frame step the plugin
+ runs in `PreUpdate`: for every `Perceiver`, sense all `PerceptionTarget`s, keep
+ the nearest visible one, and write the `Perception` component.
+
+```typescript
+import { senseTarget, facingFromQuat, Transform, registerCondition } from 'esengine';
+
+// A one-off sight check against a POINT — no PerceptionTarget needed.
+registerCondition('seesShrine', (ctx) => {
+ const tf = ctx.get(Transform);
+ const facing = facingFromQuat(tf.rotation.z, tf.rotation.w);
+ return senseTarget(
+ tf.position.x, tf.position.y, facing,
+ SHRINE.x, SHRINE.y,
+ 300, Math.PI / 3, // 300 px range, 120° cone
+ ).visible;
+});
+```
+
+`senseTarget` returns a `SenseResult`:
+
+| `SenseResult` field | Description |
+|---|---|
+| `visible` | The target is within range, inside the cone, and not occluded. |
+| `distance` | Distance to the target — always set, even when not visible. |
+| `dirX` / `dirY` | Unit direction observer → target; `(0, 0)` when not visible. |
+
+The built-in system wires `makeLosCheck` in only when the physics module is
+loaded; otherwise sensing is range + FOV only — the AI layer has no hard physics
+dependency.
+
+## Custom app setup
+
+The perception, FSM, BT, and navigation plugins are part of the default plugin set,
+so the **editor and the `esengine` web runtime add them for you**. Only when you build
+an app from a bare `new App()` do you add them explicitly:
+
+```typescript
+import { perceptionPlugin, fsmPlugin, btPlugin, navPlugin } from 'esengine';
+
+app.addPlugin(perceptionPlugin);
+app.addPlugin(fsmPlugin);
+app.addPlugin(btPlugin);
+app.addPlugin(navPlugin);
+```
+
+Each is exported both as a ready-to-use singleton (`navPlugin`) and as a class
+(`NavPlugin`) if you need multiple instances.
diff --git a/docs/astro/src/content/docs/gameplay/ai-authoring.mdx b/docs/astro/src/content/docs/gameplay/ai-authoring.mdx
new file mode 100644
index 000000000..aa6f4ea40
--- /dev/null
+++ b/docs/astro/src/content/docs/gameplay/ai-authoring.mdx
@@ -0,0 +1,21 @@
+---
+title: Authoring in the editor
+description: "The intended workflow: register leaf logic once in code, then build and tune the graphs visually as .esfsm / .esbt assets."
+---
+
+The intended workflow is **data, not code** for the graphs themselves — you register
+the leaf logic once, then build and tune the machines/trees visually:
+
+1. In the **Content Browser**, create a **State Machine** (`.esfsm`) or **Behavior
+ Tree** (`.esbt`) asset and double-click it to open the node-graph editor.
+2. Add states/nodes, drag to connect them, and fill each leaf's **action** or
+ **condition** with one of your registered names. Set transition conditions,
+ triggers, and blackboard guards in the inspector.
+3. On the agent entity, set `StateMachineAgent.fsm` (or `BehaviorTreeAgent.bt`) to the
+ asset's path.
+
+The asset is referenced by path and **preloaded with the scene**, so the graph is
+registered before the agent first ticks — no `registerFsm`/`registerBt` call needed.
+Because both paradigms resolve leaves from the same registry, you can prototype an
+enemy as a state machine and later swap in a behavior tree (or run both) without
+touching your action/condition code.
diff --git a/docs/astro/src/content/docs/gameplay/ai-behavior-trees.mdx b/docs/astro/src/content/docs/gameplay/ai-behavior-trees.mdx
new file mode 100644
index 000000000..f0283b99a
--- /dev/null
+++ b/docs/astro/src/content/docs/gameplay/ai-behavior-trees.mdx
@@ -0,0 +1,62 @@
+---
+title: Behavior trees
+description: "Running an .esbt graph: selectors, sequences, decorators and leaves, and how a tick resolves."
+---
+
+![The behavior-tree editor — a Selector over a Sequence and a fallback action](../../../assets/guides/en/ai-bt.png)
+
+*The behavior-tree editor: a **Selector** root over a **Sequence** (Condition `seesPlayer` → Action `chase`) with a fallback `patrol` action.*
+
+A behavior tree ticks from its **root** every frame and returns a `Status`. Composite
+nodes control flow; decorators transform one child's result; leaves are your
+registered actions and conditions. Attach a `BehaviorTreeAgent`:
+
+```typescript
+import { BehaviorTreeAgent } from 'esengine';
+
+cmds.spawn()
+ .insert(NavAgent, {})
+ .insert(Perception, {})
+ .insert(BehaviorTreeAgent, { bt: 'assets/ai/enemy.esbt' }); // an editor-authored asset
+```
+
+| `BehaviorTreeAgent` field | Description |
+|---|---|
+| `bt` | Key of the tree to run: a `registerBt` name **or** an `.esbt` asset path. |
+| `status` | Last root status, written each tick (read-only). |
+
+Author the tree visually in the editor, or build it in code with `registerBt`:
+
+```typescript
+import { registerBt } from 'esengine';
+
+registerBt('guard', {
+ root: {
+ type: 'selector', // try children left→right until one succeeds
+ children: [
+ {
+ type: 'sequence', // all must succeed, in order
+ children: [
+ { type: 'condition', name: 'seesPlayer' },
+ { type: 'action', name: 'chase' },
+ ],
+ },
+ { type: 'action', name: 'patrol' },
+ ],
+ },
+});
+```
+
+Node types:
+
+| Category | Type | Behavior |
+|---|---|---|
+| Composite | `sequence` | Ticks children in order; fails on the first failure, succeeds if all succeed. |
+| | `selector` | Ticks children in order; succeeds on the first success, fails if all fail. |
+| | `parallel` | Ticks all children; `policy: 'one'` succeeds when any does, `'all'` (default) when all do. |
+| Decorator | `inverter` | Inverts its child's Success/Failure. |
+| | `succeeder` | Always reports Success. |
+| | `repeater` | Re-runs its child `count` times (`0` = forever). |
+| | `wait` | Runs for `seconds` before reporting Success. |
+| Leaf | `action` | Runs the registered action `name`; its `Status` (or `Success` on void) propagates up. |
+| | `condition` | Returns `Success` when the registered condition `name` is true, else `Failure`. |
diff --git a/docs/astro/src/content/docs/gameplay/ai-blackboard.mdx b/docs/astro/src/content/docs/gameplay/ai-blackboard.mdx
new file mode 100644
index 000000000..28f81fbda
--- /dev/null
+++ b/docs/astro/src/content/docs/gameplay/ai-blackboard.mdx
@@ -0,0 +1,27 @@
+---
+title: The blackboard
+description: "Each agent's private key/value store and one-shot event triggers — how AI state flows between leaves and feeds transition guards."
+---
+
+Every FSM/BT agent owns a **`Blackboard`** — its private key/value store plus one-shot
+event triggers. Actions and conditions reach it through `ctx.blackboard`; it's how AI
+state flows between leaves and how transition guards get their values.
+
+```typescript
+registerAction('takeDamage', (ctx) => {
+ const hp = (ctx.blackboard.get<number>('health') ?? 100) - 10;
+ ctx.blackboard.set('health', hp);
+ if (hp <= 0) ctx.blackboard.fire('died'); // a transition keyed on 'died' fires once
+});
+```
+
+| Method | Description |
+|---|---|
+| `get<T>(key)` / `set(key, value)` | Read/write a value. |
+| `has(key)` / `delete(key)` | Test / remove a key. |
+| `fire(trigger)` | Fire a one-shot event; a transition keyed on it becomes enabled until taken. |
+| `isFired(trigger)` / `consume(trigger)` | Test / clear a trigger. |
+
+Blackboard values back the `guard` comparisons on FSM transitions, and the `trigger`
+mechanism is the Unity-style edge event: fired once, consumed by the transition that
+takes it.
diff --git a/docs/astro/src/content/docs/gameplay/ai-navigation.mdx b/docs/astro/src/content/docs/gameplay/ai-navigation.mdx
new file mode 100644
index 000000000..a785beb2f
--- /dev/null
+++ b/docs/astro/src/content/docs/gameplay/ai-navigation.mdx
@@ -0,0 +1,77 @@
+---
+title: Navigation
+description: "A navigation grid and A* pathfinding — building the grid, and moving a NavAgent to any world point with replanning."
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+Navigation moves an agent to a world point along a route that avoids blocked cells,
+using A\* over a **`NavGrid`**.
+
+### Building a grid
+
+A `NavGrid` is a rectangular grid of walkable/blocked cells. Install it on the `Nav`
+resource so agents can path against it:
+
+```typescript
+import { defineSystem, Res, Nav, NavGrid } from 'esengine';
+
+export const setupNav = defineSystem([Res(Nav)], (nav) => {
+ nav.setGrid(new NavGrid({
+ width: 60, // columns
+ height: 44, // rows
+ cellSize: 20, // world pixels per cell
+ origin: { x: -600, y: -440 }, // world position of cell (0,0)'s center
+ }));
+}, { name: 'SetupNav' });
+```
+
+| `NavGrid` option | Type | Description |
+|---|---|---|
+| `width` | number | Cell columns. |
+| `height` | number | Cell rows. |
+| `cellSize` | number | World pixels per cell (square). |
+| `origin` | `Vec2` | World position of cell `(0,0)`'s center. Defaults to `(0,0)`. |
+| `walkable` | `Uint8Array` | Optional row-major `width*height` mask, `1` = walkable, `0` = blocked. Omitted → all walkable. |
+
+To derive a grid from a painted tilemap instead of hand-authoring the mask, use
+`navGridFromTilemapLayer` (which cells a layer's solid tiles block) or
+`navGridFromTiles`.
+
+<Aside type="tip">
+ The `Nav` resource also answers one-off queries directly:
+ `nav.findWorldPath(from, to)` returns an array of world-space waypoints (or
+ `null` if there's no route) without needing a `NavAgent`.
+</Aside>
+
+### Moving an agent
+
+Attach a `NavAgent`, then point it at a destination. The built-in nav plugin plans
+the path and steps the agent along it each frame — you just set the goal.
+
+```typescript
+import { NavAgent, setNavDestination, stopNavAgent } from 'esengine';
+
+cmds.spawn()
+ .insert(Transform, { position: { x: 0, y: 0, z: 0 } })
+ .insert(NavAgent, { speed: 140, arriveRadius: 8 });
+
+// From any system/action with world access — safe to call every frame:
+setNavDestination(world, entity, { x: 320, y: -120 });
+// …and to halt in place:
+stopNavAgent(world, entity);
+```
+
+| `NavAgent` field | Default | Description |
+|---|---|---|
+| `speed` | `120` | Movement speed in world pixels per second. |
+| `radius` | `12` | Agent radius (arrival tolerance / collision size). |
+| `arriveRadius` | `6` | Stop distance from the final goal. |
+| `repathInterval` | `0.5` | Seconds between replans while moving; `0` = replan only when the target changes. |
+| `hasTarget` | `false` | Whether a destination is set (managed for you). |
+| `targetX`, `targetY` | `0` | Current destination in world pixels. |
+| `arrived` | `false` | Set true the frame the agent reaches its goal. |
+
+`setNavDestination` is safe to call every frame to chase a moving target — the agent
+only replans when the target actually moves or `repathInterval` elapses. Read
+`agent.arrived` (or `Perception`) to know when to switch behavior.
diff --git a/docs/astro/src/content/docs/gameplay/ai-perception.mdx b/docs/astro/src/content/docs/gameplay/ai-perception.mdx
new file mode 100644
index 000000000..a7ece3ddb
--- /dev/null
+++ b/docs/astro/src/content/docs/gameplay/ai-perception.mdx
@@ -0,0 +1,37 @@
+---
+title: Perception
+description: "A Perceiver senses nearby targets within a sight cone and writes what it sees into a Perception component."
+---
+
+A `Perceiver` scans for the nearest visible `PerceptionTarget` each frame and writes
+the result into a `Perception` component on the same entity. Decisions read
+`Perception`; sensing is just ECS data, not a side channel.
+
+```typescript
+import { Perceiver, PerceptionTarget, Perception } from 'esengine';
+
+// The hunter senses…
+cmds.spawn()
+ .insert(Transform, { position: { x: -200, y: 0, z: 0 } })
+ .insert(Perceiver, { range: 260, fovDegrees: 120 })
+ .insert(Perception, {}); // written every frame by the perception plugin
+
+// …anything tagged as a target.
+cmds.spawn()
+ .insert(Transform, { position: { x: 100, y: 0, z: 0 } })
+ .insert(PerceptionTarget, {});
+```
+
+| Component | Field | Default | Description |
+|---|---|---|---|
+| **`Perceiver`** | `range` | `220` | Sight range in world pixels. |
+| | `fovDegrees` | `360` | Field-of-view cone in degrees (`360` = omnidirectional). |
+| **`Perception`** | `visible` | `false` | A target is currently seen. |
+| | `distance` | `0` | Distance to the seen target. |
+| | `targetX`, `targetY` | `0` | Seen target position, world pixels. |
+| | `dirX`, `dirY` | `0` | Unit direction from observer to target. |
+| **`PerceptionTarget`** | *(tag)* | — | Marks an entity as sensable by `Perceiver`s. |
+
+The FOV cone is oriented by the perceiver's `Transform` rotation. `Perception` is a
+transient, runtime-only component — the plugin rewrites it every frame, so you never
+author its values.
diff --git a/docs/astro/src/content/docs/gameplay/ai-state-machines.mdx b/docs/astro/src/content/docs/gameplay/ai-state-machines.mdx
new file mode 100644
index 000000000..c1f6195c2
--- /dev/null
+++ b/docs/astro/src/content/docs/gameplay/ai-state-machines.mdx
@@ -0,0 +1,66 @@
+---
+title: State machines
+description: "Running an .esfsm graph: states with enter/update/exit hooks, guarded transitions, and one-shot triggers."
+---
+
+![The FSM editor — Patrol and Chase states linked by guarded transitions](../../../assets/guides/en/ai-fsm.png)
+
+*The state-machine editor: states (Patrol / Chase) linked by guarded transitions (`?seesPlayer`, `?lostPlayer`).*
+
+A state machine is a set of **states** connected by guarded **transitions**. Exactly
+one state is active; each tick, its outgoing transitions are checked in order and the
+first enabled one is taken. Attach a `StateMachineAgent` and point it at a graph:
+
+```typescript
+import { StateMachineAgent } from 'esengine';
+
+cmds.spawn()
+ .insert(NavAgent, {})
+ .insert(Perceiver, { range: 240 })
+ .insert(Perception, {})
+ .insert(StateMachineAgent, { fsm: 'assets/ai/enemy.esfsm' }); // an editor-authored asset
+```
+
+| `StateMachineAgent` field | Description |
+|---|---|
+| `fsm` | Key of the machine to run: a `registerFsm` name **or** an `.esfsm` asset path. |
+| `current` | Active state name, written each tick (read-only; visible in the inspector). |
+
+The recommended path is to **author the graph in the editor** as an `.esfsm` asset
+(see [Authoring in the editor](/docs/gameplay/ai-authoring/)). The states reference your
+registered action/condition names by string. You can also build a machine in code:
+
+```typescript
+import { registerFsm } from 'esengine';
+
+registerFsm('guard', {
+ initial: 'Patrol',
+ states: [
+ {
+ name: 'Patrol',
+ onUpdate: 'patrol',
+ transitions: [{ to: 'Chase', condition: 'seesPlayer' }],
+ },
+ {
+ name: 'Chase',
+ onEnter: 'startChase',
+ onUpdate: 'chase',
+ transitions: [{ to: 'Patrol', condition: 'lostPlayer' }],
+ },
+ ],
+});
+```
+
+Each state carries up to three named hooks — `onEnter`, `onUpdate`, `onExit` — and a
+list of `transitions`. A transition is enabled when **all** of its specified
+mechanisms hold; a transition with none is unconditional:
+
+| Transition field | Description |
+|---|---|
+| `to` | Destination state name. |
+| `trigger` | A one-shot event name that must be fired (consumed when taken). |
+| `condition` | A registered condition that must return true. |
+| `guard` | One or more blackboard comparisons, AND-combined. |
+
+Guards compare a blackboard key with `==`, `!=`, `<`, `<=`, `>`, `>=`, `truthy`, or
+`falsy` — e.g. `{ key: 'health', op: '<', value: 20 }`.
diff --git a/docs/astro/src/content/docs/gameplay/ai.mdx b/docs/astro/src/content/docs/gameplay/ai.mdx
index c3a979340..7e8ea8a9f 100644
--- a/docs/astro/src/content/docs/gameplay/ai.mdx
+++ b/docs/astro/src/content/docs/gameplay/ai.mdx
@@ -3,7 +3,7 @@ title: Gameplay AI
description: The gameplay AI layer — perception, grid navigation with A* pathfinding, state machines, and behavior trees, all driven by one shared registry of named actions and conditions and authored visually in the editor.
---
-import { Aside, Card, CardGrid } from '@astrojs/starlight/components';
+import { Aside, Card, CardGrid, LinkCard } from '@astrojs/starlight/components';
Estella's AI layer turns an entity into an actor that **senses**, **decides**, and
**moves**. It is built from four cooperating pieces that share one design:
@@ -36,7 +36,7 @@ editor, not hardcoded. Perception feeds the decision; the decision drives naviga
Everything here is pure TypeScript in the `esengine` core (no WebAssembly
side-module). All four plugins — perception, FSM, BT, and navigation — are added
automatically by the editor and the web runtime. You only wire plugins yourself in
- a bare `new App()` (see [Custom app setup](#custom-app-setup)).
+ a bare `new App()` (see [Custom app setup](/docs/gameplay/ai-advanced/#custom-app-setup)).
</Aside>
## The shared registry
@@ -68,7 +68,7 @@ is the same programming model as a [`defineBehavior`](/docs/scripting/overview/)
| `ctx.dt` | `number` | Frame delta in seconds. |
| `ctx.world` | `World` | Full world access for cross-entity reads. |
| `ctx.commands` | `Commands` | Deferred spawn/despawn, safe mid-tick. |
-| `ctx.blackboard` | `Blackboard` | This agent's AI data plane (see [Blackboard](#the-blackboard)). |
+| `ctx.blackboard` | `Blackboard` | This agent's AI data plane (see [Blackboard](/docs/gameplay/ai-blackboard/)). |
| `ctx.get(Comp)` | `ComponentData` | Read another component on **this** entity. |
| `ctx.set(Comp, data)` | `void` | Write a component on **this** entity. |
| `ctx.has(Comp)` | `boolean` | Whether this entity has `Comp`. |
@@ -149,405 +149,17 @@ The [`cutscene` example](https://github.com/esengine/estella/tree/master/example
is this pattern end-to-end: an intro timeline plays on scene start, gameplay
unlocks when it completes, and R replays it — with zero registered actions.
-## Perception
+## The four pieces
-A `Perceiver` scans for the nearest visible `PerceptionTarget` each frame and writes
-the result into a `Perception` component on the same entity. Decisions read
-`Perception`; sensing is just ECS data, not a side channel.
-
-```typescript
-import { Perceiver, PerceptionTarget, Perception } from 'esengine';
-
-// The hunter senses…
-cmds.spawn()
- .insert(Transform, { position: { x: -200, y: 0, z: 0 } })
- .insert(Perceiver, { range: 260, fovDegrees: 120 })
- .insert(Perception, {}); // written every frame by the perception plugin
-
-// …anything tagged as a target.
-cmds.spawn()
- .insert(Transform, { position: { x: 100, y: 0, z: 0 } })
- .insert(PerceptionTarget, {});
-```
-
-| Component | Field | Default | Description |
-|---|---|---|---|
-| **`Perceiver`** | `range` | `220` | Sight range in world pixels. |
-| | `fovDegrees` | `360` | Field-of-view cone in degrees (`360` = omnidirectional). |
-| **`Perception`** | `visible` | `false` | A target is currently seen. |
-| | `distance` | `0` | Distance to the seen target. |
-| | `targetX`, `targetY` | `0` | Seen target position, world pixels. |
-| | `dirX`, `dirY` | `0` | Unit direction from observer to target. |
-| **`PerceptionTarget`** | *(tag)* | — | Marks an entity as sensable by `Perceiver`s. |
-
-The FOV cone is oriented by the perceiver's `Transform` rotation. `Perception` is a
-transient, runtime-only component — the plugin rewrites it every frame, so you never
-author its values.
-
-## Navigation
-
-Navigation moves an agent to a world point along a route that avoids blocked cells,
-using A\* over a **`NavGrid`**.
-
-### Building a grid
-
-A `NavGrid` is a rectangular grid of walkable/blocked cells. Install it on the `Nav`
-resource so agents can path against it:
-
-```typescript
-import { defineSystem, Res, Nav, NavGrid } from 'esengine';
-
-export const setupNav = defineSystem([Res(Nav)], (nav) => {
- nav.setGrid(new NavGrid({
- width: 60, // columns
- height: 44, // rows
- cellSize: 20, // world pixels per cell
- origin: { x: -600, y: -440 }, // world position of cell (0,0)'s center
- }));
-}, { name: 'SetupNav' });
-```
-
-| `NavGrid` option | Type | Description |
-|---|---|---|
-| `width` | number | Cell columns. |
-| `height` | number | Cell rows. |
-| `cellSize` | number | World pixels per cell (square). |
-| `origin` | `Vec2` | World position of cell `(0,0)`'s center. Defaults to `(0,0)`. |
-| `walkable` | `Uint8Array` | Optional row-major `width*height` mask, `1` = walkable, `0` = blocked. Omitted → all walkable. |
-
-To derive a grid from a painted tilemap instead of hand-authoring the mask, use
-`navGridFromTilemapLayer` (which cells a layer's solid tiles block) or
-`navGridFromTiles`.
-
-<Aside type="tip">
- The `Nav` resource also answers one-off queries directly:
- `nav.findWorldPath(from, to)` returns an array of world-space waypoints (or
- `null` if there's no route) without needing a `NavAgent`.
-</Aside>
-
-### Moving an agent
-
-Attach a `NavAgent`, then point it at a destination. The built-in nav plugin plans
-the path and steps the agent along it each frame — you just set the goal.
-
-```typescript
-import { NavAgent, setNavDestination, stopNavAgent } from 'esengine';
-
-cmds.spawn()
- .insert(Transform, { position: { x: 0, y: 0, z: 0 } })
- .insert(NavAgent, { speed: 140, arriveRadius: 8 });
-
-// From any system/action with world access — safe to call every frame:
-setNavDestination(world, entity, { x: 320, y: -120 });
-// …and to halt in place:
-stopNavAgent(world, entity);
-```
-
-| `NavAgent` field | Default | Description |
-|---|---|---|
-| `speed` | `120` | Movement speed in world pixels per second. |
-| `radius` | `12` | Agent radius (arrival tolerance / collision size). |
-| `arriveRadius` | `6` | Stop distance from the final goal. |
-| `repathInterval` | `0.5` | Seconds between replans while moving; `0` = replan only when the target changes. |
-| `hasTarget` | `false` | Whether a destination is set (managed for you). |
-| `targetX`, `targetY` | `0` | Current destination in world pixels. |
-| `arrived` | `false` | Set true the frame the agent reaches its goal. |
-
-`setNavDestination` is safe to call every frame to chase a moving target — the agent
-only replans when the target actually moves or `repathInterval` elapses. Read
-`agent.arrived` (or `Perception`) to know when to switch behavior.
-
-## State machines
-
-![The FSM editor — Patrol and Chase states linked by guarded transitions](../../../assets/guides/en/ai-fsm.png)
-
-*The state-machine editor: states (Patrol / Chase) linked by guarded transitions (`?seesPlayer`, `?lostPlayer`).*
-
-A state machine is a set of **states** connected by guarded **transitions**. Exactly
-one state is active; each tick, its outgoing transitions are checked in order and the
-first enabled one is taken. Attach a `StateMachineAgent` and point it at a graph:
-
-```typescript
-import { StateMachineAgent } from 'esengine';
-
-cmds.spawn()
- .insert(NavAgent, {})
- .insert(Perceiver, { range: 240 })
- .insert(Perception, {})
- .insert(StateMachineAgent, { fsm: 'assets/ai/enemy.esfsm' }); // an editor-authored asset
-```
-
-| `StateMachineAgent` field | Description |
-|---|---|
-| `fsm` | Key of the machine to run: a `registerFsm` name **or** an `.esfsm` asset path. |
-| `current` | Active state name, written each tick (read-only; visible in the inspector). |
-
-The recommended path is to **author the graph in the editor** as an `.esfsm` asset
-(see [Authoring in the editor](#authoring-in-the-editor)). The states reference your
-registered action/condition names by string. You can also build a machine in code:
-
-```typescript
-import { registerFsm } from 'esengine';
-
-registerFsm('guard', {
- initial: 'Patrol',
- states: [
- {
- name: 'Patrol',
- onUpdate: 'patrol',
- transitions: [{ to: 'Chase', condition: 'seesPlayer' }],
- },
- {
- name: 'Chase',
- onEnter: 'startChase',
- onUpdate: 'chase',
- transitions: [{ to: 'Patrol', condition: 'lostPlayer' }],
- },
- ],
-});
-```
-
-Each state carries up to three named hooks — `onEnter`, `onUpdate`, `onExit` — and a
-list of `transitions`. A transition is enabled when **all** of its specified
-mechanisms hold; a transition with none is unconditional:
-
-| Transition field | Description |
-|---|---|
-| `to` | Destination state name. |
-| `trigger` | A one-shot event name that must be fired (consumed when taken). |
-| `condition` | A registered condition that must return true. |
-| `guard` | One or more blackboard comparisons, AND-combined. |
-
-Guards compare a blackboard key with `==`, `!=`, `<`, `<=`, `>`, `>=`, `truthy`, or
-`falsy` — e.g. `{ key: 'health', op: '<', value: 20 }`.
-
-## Behavior trees
-
-![The behavior-tree editor — a Selector over a Sequence and a fallback action](../../../assets/guides/en/ai-bt.png)
-
-*The behavior-tree editor: a **Selector** root over a **Sequence** (Condition `seesPlayer` → Action `chase`) with a fallback `patrol` action.*
-
-A behavior tree ticks from its **root** every frame and returns a `Status`. Composite
-nodes control flow; decorators transform one child's result; leaves are your
-registered actions and conditions. Attach a `BehaviorTreeAgent`:
-
-```typescript
-import { BehaviorTreeAgent } from 'esengine';
-
-cmds.spawn()
- .insert(NavAgent, {})
- .insert(Perception, {})
- .insert(BehaviorTreeAgent, { bt: 'assets/ai/enemy.esbt' }); // an editor-authored asset
-```
-
-| `BehaviorTreeAgent` field | Description |
-|---|---|
-| `bt` | Key of the tree to run: a `registerBt` name **or** an `.esbt` asset path. |
-| `status` | Last root status, written each tick (read-only). |
-
-Author the tree visually in the editor, or build it in code with `registerBt`:
-
-```typescript
-import { registerBt } from 'esengine';
-
-registerBt('guard', {
- root: {
- type: 'selector', // try children left→right until one succeeds
- children: [
- {
- type: 'sequence', // all must succeed, in order
- children: [
- { type: 'condition', name: 'seesPlayer' },
- { type: 'action', name: 'chase' },
- ],
- },
- { type: 'action', name: 'patrol' },
- ],
- },
-});
-```
-
-Node types:
-
-| Category | Type | Behavior |
-|---|---|---|
-| Composite | `sequence` | Ticks children in order; fails on the first failure, succeeds if all succeed. |
-| | `selector` | Ticks children in order; succeeds on the first success, fails if all fail. |
-| | `parallel` | Ticks all children; `policy: 'one'` succeeds when any does, `'all'` (default) when all do. |
-| Decorator | `inverter` | Inverts its child's Success/Failure. |
-| | `succeeder` | Always reports Success. |
-| | `repeater` | Re-runs its child `count` times (`0` = forever). |
-| | `wait` | Runs for `seconds` before reporting Success. |
-| Leaf | `action` | Runs the registered action `name`; its `Status` (or `Success` on void) propagates up. |
-| | `condition` | Returns `Success` when the registered condition `name` is true, else `Failure`. |
-
-## The blackboard
-
-Every FSM/BT agent owns a **`Blackboard`** — its private key/value store plus one-shot
-event triggers. Actions and conditions reach it through `ctx.blackboard`; it's how AI
-state flows between leaves and how transition guards get their values.
-
-```typescript
-registerAction('takeDamage', (ctx) => {
- const hp = (ctx.blackboard.get<number>('health') ?? 100) - 10;
- ctx.blackboard.set('health', hp);
- if (hp <= 0) ctx.blackboard.fire('died'); // a transition keyed on 'died' fires once
-});
-```
-
-| Method | Description |
-|---|---|
-| `get<T>(key)` / `set(key, value)` | Read/write a value. |
-| `has(key)` / `delete(key)` | Test / remove a key. |
-| `fire(trigger)` | Fire a one-shot event; a transition keyed on it becomes enabled until taken. |
-| `isFired(trigger)` / `consume(trigger)` | Test / clear a trigger. |
-
-Blackboard values back the `guard` comparisons on FSM transitions, and the `trigger`
-mechanism is the Unity-style edge event: fired once, consumed by the transition that
-takes it.
-
-## Authoring in the editor
-
-The intended workflow is **data, not code** for the graphs themselves — you register
-the leaf logic once, then build and tune the machines/trees visually:
-
-1. In the **Content Browser**, create a **State Machine** (`.esfsm`) or **Behavior
- Tree** (`.esbt`) asset and double-click it to open the node-graph editor.
-2. Add states/nodes, drag to connect them, and fill each leaf's **action** or
- **condition** with one of your registered names. Set transition conditions,
- triggers, and blackboard guards in the inspector.
-3. On the agent entity, set `StateMachineAgent.fsm` (or `BehaviorTreeAgent.bt`) to the
- asset's path.
-
-The asset is referenced by path and **preloaded with the scene**, so the graph is
-registered before the agent first ticks — no `registerFsm`/`registerBt` call needed.
-Because both paradigms resolve leaves from the same registry, you can prototype an
-enemy as a state machine and later swap in a behavior tree (or run both) without
-touching your action/condition code.
-
-## Advanced: below the components
-
-`Nav`, `NavAgent`, and `Perceiver` — the component layer — cover the common cases.
-The primitives beneath them are exported too, all pure TypeScript with no engine
-or wasm dependency, for when you need a path without an agent or a sight check
-without a `Perceiver`.
-
-### Pathfinding by hand
-
-`findPath` is the A\* the nav plugin uses: uniform-cost search over `NavGrid`
-cells, 4- or 8-connected, with an octile/manhattan heuristic and no corner
-cutting (a diagonal step needs both shared orthogonal cells open). Drop to it
-when you steer movement yourself, draw a path preview, or compute reachability
-for turn-based ranges — or when one grid isn't enough, since the `Nav` resource
-holds a single grid:
-
-```typescript
-import { NavGrid, findPath, pathToWorld } from 'esengine';
-
-const grid = new NavGrid({ width: 32, height: 24, cellSize: 32 });
-
-const path = findPath(
- grid,
- grid.worldToCell(hero.x, hero.y), // Cell — integer grid coordinates
- grid.worldToCell(chest.x, chest.y),
- { diagonal: false },
-);
-if (path) {
- const waypoints = pathToWorld(grid, path); // Vec2[] — cell centers, world pixels
-}
-```
-
-`findPath(grid, start, goal, opts?)` returns the `Cell[]` path inclusive of both
-endpoints, or `null` when unreachable. A `Cell` is an integer grid coordinate
-`{ x, y }` (kept distinct from `Vec2` to flag cell space); convert with
-`grid.worldToCell` / `grid.cellToWorld`, or turn a whole path into world-space
-waypoints with `pathToWorld`.
-
-| `PathfindOptions` field | Default | Description |
-|---|---|---|
-| `diagonal` | `true` | Allow 8-connected diagonal moves. |
-| `snapRadius` | `8` | When start/goal lands on a blocked cell, snap to the nearest walkable cell within this ring radius before searching; `0` disables snapping. |
-
-`navGridFromTiles` builds the walkability mask from any tile reader — it is the
-core under `navGridFromTilemapLayer`, which just plugs in `TilemapAPI.getTile`:
-
-```typescript
-import { navGridFromTiles } from 'esengine';
-
-const grid = navGridFromTiles((x, y) => level.tiles[y][x], {
- width: 32, height: 24, cellSize: 32,
- blockedTileIds: [WALL_TILE, WATER_TILE],
-});
-```
-
-| `BuildNavGridOptions` field | Description |
-|---|---|
-| `width` / `height` / `cellSize` / `origin?` | Same as the `NavGrid` options (see [Building a grid](#building-a-grid)). |
-| `blockedTileIds?` | Exact set of tile ids that block movement. |
-| `isBlocked?` | Custom predicate over the tile id (`0` = empty); overrides `blockedTileIds`. With neither given, any non-empty tile blocks. |
-
-### Perception internals
-
-The perception plugin is a thin wrapper over four exported functions — useful for
-one-off sight checks from an action, custom senses (memory, hearing, multiple
-targets), or unit tests against a fake world:
-
-- **`senseTarget(ox, oy, facing, tx, ty, range, halfFov, isBlocked?)`** — the pure
- geometry: a range check, a FOV cone check (`halfFov` is *half* the cone in
- radians; ≥ π means omnidirectional), then the optional occlusion callback.
-- **`facingFromQuat(z, w)`** — 2D facing angle in radians from a `Transform`
- rotation quaternion's z/w components.
-- **`makeLosCheck(physics)`** — builds the occlusion callback from a physics
- raycast: occluded when any hit lands clearly short of the target
- (`fraction < 0.98` — the last ~2% is the target itself).
-- **`stepPerception(world, isBlocked?)`** — the exact per-frame step the plugin
- runs in `PreUpdate`: for every `Perceiver`, sense all `PerceptionTarget`s, keep
- the nearest visible one, and write the `Perception` component.
-
-```typescript
-import { senseTarget, facingFromQuat, Transform, registerCondition } from 'esengine';
-
-// A one-off sight check against a POINT — no PerceptionTarget needed.
-registerCondition('seesShrine', (ctx) => {
- const tf = ctx.get(Transform);
- const facing = facingFromQuat(tf.rotation.z, tf.rotation.w);
- return senseTarget(
- tf.position.x, tf.position.y, facing,
- SHRINE.x, SHRINE.y,
- 300, Math.PI / 3, // 300 px range, 120° cone
- ).visible;
-});
-```
-
-`senseTarget` returns a `SenseResult`:
-
-| `SenseResult` field | Description |
-|---|---|
-| `visible` | The target is within range, inside the cone, and not occluded. |
-| `distance` | Distance to the target — always set, even when not visible. |
-| `dirX` / `dirY` | Unit direction observer → target; `(0, 0)` when not visible. |
-
-The built-in system wires `makeLosCheck` in only when the physics module is
-loaded; otherwise sensing is range + FOV only — the AI layer has no hard physics
-dependency.
-
-## Custom app setup
-
-The perception, FSM, BT, and navigation plugins are part of the default plugin set,
-so the **editor and the `esengine` web runtime add them for you**. Only when you build
-an app from a bare `new App()` do you add them explicitly:
-
-```typescript
-import { perceptionPlugin, fsmPlugin, btPlugin, navPlugin } from 'esengine';
-
-app.addPlugin(perceptionPlugin);
-app.addPlugin(fsmPlugin);
-app.addPlugin(btPlugin);
-app.addPlugin(navPlugin);
-```
-
-Each is exported both as a ready-to-use singleton (`navPlugin`) and as a class
-(`NavPlugin`) if you need multiple instances.
+<CardGrid>
+ <LinkCard title="Perception" href="/docs/gameplay/ai-perception/" description="Sight cones, and what an agent currently sees." />
+ <LinkCard title="Navigation" href="/docs/gameplay/ai-navigation/" description="A navigation grid, A* paths, and moving an agent along one." />
+ <LinkCard title="State machines" href="/docs/gameplay/ai-state-machines/" description="States, guarded transitions, and one-shot triggers." />
+ <LinkCard title="Behavior trees" href="/docs/gameplay/ai-behavior-trees/" description="Selectors, sequences, decorators and leaves." />
+ <LinkCard title="The blackboard" href="/docs/gameplay/ai-blackboard/" description="The per-agent data plane both paradigms read and write." />
+ <LinkCard title="Authoring in the editor" href="/docs/gameplay/ai-authoring/" description="Register the leaves in code, build the graphs visually." />
+ <LinkCard title="Below the components" href="/docs/gameplay/ai-advanced/" description="Pathfinding by hand, perception internals, and bare-App wiring." />
+</CardGrid>
## Putting it together
diff --git a/docs/astro/src/content/docs/zh-cn/gameplay/ai-advanced.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/ai-advanced.mdx
new file mode 100644
index 000000000..99797594d
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/gameplay/ai-advanced.mdx
@@ -0,0 +1,117 @@
+---
+title: 组件层之下
+description: "组件层之下的原语——手动寻路、感知内幕,以及在裸 App 里自己接插件。"
+---
+
+`Nav`、`NavAgent`、`Perceiver`——组件层——覆盖了常见场景。它们底下的原语同样被导出,
+全是不依赖引擎/wasm 的纯 TypeScript,供你在不要 agent 的情况下求一条路径、
+或在没有 `Perceiver` 时做一次视线检查。
+
+### 手动寻路
+
+`findPath` 就是导航插件用的那个 A\*:在 `NavGrid` 格子上做均匀代价搜索,4 连通或
+8 连通,octile/曼哈顿启发式,且不切角(走对角线要求两个共享的正交格子都可通行)。
+当你要自己驱动移动、画路径预览、或计算可达性(回合制的移动范围)时下沉到它——
+或者当一张网格不够用时,因为 `Nav` 资源只持有一张网格:
+
+```typescript
+import { NavGrid, findPath, pathToWorld } from 'esengine';
+
+const grid = new NavGrid({ width: 32, height: 24, cellSize: 32 });
+
+const path = findPath(
+ grid,
+ grid.worldToCell(hero.x, hero.y), // Cell — integer grid coordinates
+ grid.worldToCell(chest.x, chest.y),
+ { diagonal: false },
+);
+if (path) {
+ const waypoints = pathToWorld(grid, path); // Vec2[] — cell centers, world pixels
+}
+```
+
+`findPath(grid, start, goal, opts?)` 返回含首尾两端的 `Cell[]` 路径,不可达时返回
+`null`。`Cell` 是整数网格坐标 `{ x, y }`(与 `Vec2` 刻意区分,以标示格子空间);用
+`grid.worldToCell` / `grid.cellToWorld` 互转,或用 `pathToWorld` 把整条路径转成
+世界空间路点。
+
+| `PathfindOptions` 字段 | 默认 | 说明 |
+|---|---|---|
+| `diagonal` | `true` | 允许 8 连通的对角移动。 |
+| `snapRadius` | `8` | 起点/终点落在被阻挡格子上时,先在此环半径内吸附到最近的可走格子再搜索;`0` 关闭吸附。 |
+
+`navGridFromTiles` 从任意瓦片读取器构建可走掩码——它是 `navGridFromTilemapLayer`
+底下的核心,后者只是接上了 `TilemapAPI.getTile`:
+
+```typescript
+import { navGridFromTiles } from 'esengine';
+
+const grid = navGridFromTiles((x, y) => level.tiles[y][x], {
+ width: 32, height: 24, cellSize: 32,
+ blockedTileIds: [WALL_TILE, WATER_TILE],
+});
+```
+
+| `BuildNavGridOptions` 字段 | 说明 |
+|---|---|
+| `width` / `height` / `cellSize` / `origin?` | 与 `NavGrid` 选项相同(见[构建网格](/docs/zh-cn/gameplay/ai-navigation/#构建网格))。 |
+| `blockedTileIds?` | 阻挡移动的瓦片 id 的精确集合。 |
+| `isBlocked?` | 针对瓦片 id 的自定义谓词(`0` = 空);覆盖 `blockedTileIds`。二者都不给时,任何非空瓦片都阻挡。 |
+
+### 感知内幕
+
+感知插件是四个导出函数之上的薄封装——适合在动作里做一次性视线检查、做自定义感官
+(记忆、听觉、多目标),或对着一个假 world 做单元测试:
+
+- **`senseTarget(ox, oy, facing, tx, ty, range, halfFov, isBlocked?)`**——纯几何:
+ 先查距离,再查视野锥(`halfFov` 是锥角的*一半*,弧度;≥ π 表示全向),最后走可选的
+ 遮挡回调。
+- **`facingFromQuat(z, w)`**——从 `Transform` 旋转四元数的 z/w 分量求 2D 朝向角
+ (弧度)。
+- **`makeLosCheck(physics)`**——用物理射线构建遮挡回调:任何命中明显落在目标之前
+ (`fraction < 0.98`——最后约 2% 是目标自己)即视为遮挡。
+- **`stepPerception(world, isBlocked?)`**——插件每帧在 `PreUpdate` 跑的那一步:
+ 对每个 `Perceiver`,感知全部 `PerceptionTarget`,留下最近的可见者,写入
+ `Perception` 组件。
+
+```typescript
+import { senseTarget, facingFromQuat, Transform, registerCondition } from 'esengine';
+
+// A one-off sight check against a POINT — no PerceptionTarget needed.
+registerCondition('seesShrine', (ctx) => {
+ const tf = ctx.get(Transform);
+ const facing = facingFromQuat(tf.rotation.z, tf.rotation.w);
+ return senseTarget(
+ tf.position.x, tf.position.y, facing,
+ SHRINE.x, SHRINE.y,
+ 300, Math.PI / 3, // 300 px range, 120° cone
+ ).visible;
+});
+```
+
+`senseTarget` 返回一个 `SenseResult`:
+
+| `SenseResult` 字段 | 说明 |
+|---|---|
+| `visible` | 目标在范围内、在锥内、且未被遮挡。 |
+| `distance` | 到目标的距离——即使不可见也总是被设置。 |
+| `dirX` / `dirY` | 观察者 → 目标的单位方向;不可见时为 `(0, 0)`。 |
+
+内置系统只在物理模块已加载时才接入 `makeLosCheck`;否则感知只做距离 + 视野锥——
+AI 层没有对物理的硬依赖。
+
+## 自定义应用
+
+感知、FSM、BT、导航这四个插件是默认插件集的一部分,所以**编辑器和 `esengine` Web 运行时会替你
+加上它们**。只有当你从一个裸的 `new App()` 构建应用时,才需要显式加:
+
+```typescript
+import { perceptionPlugin, fsmPlugin, btPlugin, navPlugin } from 'esengine';
+
+app.addPlugin(perceptionPlugin);
+app.addPlugin(fsmPlugin);
+app.addPlugin(btPlugin);
+app.addPlugin(navPlugin);
+```
+
+每个都同时导出为一个开箱即用的单例(`navPlugin`)和一个类(`NavPlugin`),需要多个实例时用类。
diff --git a/docs/astro/src/content/docs/zh-cn/gameplay/ai-authoring.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/ai-authoring.mdx
new file mode 100644
index 000000000..63e1c49df
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/gameplay/ai-authoring.mdx
@@ -0,0 +1,16 @@
+---
+title: 在编辑器里编排
+description: "推荐工作流:叶子逻辑在代码里注册一次,图本身在编辑器里以 .esfsm / .esbt 资产可视化搭建与调参。"
+---
+
+设想的工作流是图本身**用数据、不用代码**——你注册一次叶子逻辑,然后可视化地构建并调优机器/树:
+
+1. 在**内容浏览器**里,新建一个**状态机**(`.esfsm`)或**行为树**(`.esbt`)资产,双击它打开
+ 节点图编辑器。
+2. 添加状态/节点,拖拽连线,把每个叶子的**动作**或**条件**填成你注册的某个名字。在检视面板里
+ 设置转移的条件、触发器和黑板守卫。
+3. 在 agent 实体上,把 `StateMachineAgent.fsm`(或 `BehaviorTreeAgent.bt`)设为资产的路径。
+
+资产按路径引用并**随场景预加载**,所以图在 agent 首次 tick 之前就已注册——不需要
+`registerFsm`/`registerBt` 调用。因为两种范式都从同一份注册表解析叶子,你可以先把一个敌人
+原型成状态机,之后再换成行为树(或两者都跑),而不用动你的动作/条件代码。
diff --git a/docs/astro/src/content/docs/zh-cn/gameplay/ai-behavior-trees.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/ai-behavior-trees.mdx
new file mode 100644
index 000000000..a92648477
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/gameplay/ai-behavior-trees.mdx
@@ -0,0 +1,61 @@
+---
+title: 行为树
+description: "运行 .esbt 图:选择、序列、装饰器与叶子,以及一次 tick 如何求值。"
+---
+
+![行为树编辑器——Selector 之下是 Sequence 与一个兜底动作](../../../../assets/guides/zh/ai-bt.png)
+
+*行为树编辑器:**Selector** 根之下是一个 **Sequence**(Condition `seesPlayer` → Action `chase`),外加兜底的 `patrol` 动作。*
+
+行为树每帧从**根**开始 tick 并返回一个 `Status`。组合节点控制流程;装饰器变换其唯一子节点的
+结果;叶子是你注册的动作和条件。加一个 `BehaviorTreeAgent`:
+
+```typescript
+import { BehaviorTreeAgent } from 'esengine';
+
+cmds.spawn()
+ .insert(NavAgent, {})
+ .insert(Perception, {})
+ .insert(BehaviorTreeAgent, { bt: 'assets/ai/enemy.esbt' }); // 一个编辑器编排的资产
+```
+
+| `BehaviorTreeAgent` 字段 | 说明 |
+|---|---|
+| `bt` | 要运行的树的 key:一个 `registerBt` 名字**或**一个 `.esbt` 资产路径。 |
+| `status` | 上一次根状态,每 tick 写入(只读)。 |
+
+在编辑器里可视化编排这棵树,或用 `registerBt` 用代码构建:
+
+```typescript
+import { registerBt } from 'esengine';
+
+registerBt('guard', {
+ root: {
+ type: 'selector', // 从左到右尝试子节点,直到一个成功
+ children: [
+ {
+ type: 'sequence', // 全部按序成功
+ children: [
+ { type: 'condition', name: 'seesPlayer' },
+ { type: 'action', name: 'chase' },
+ ],
+ },
+ { type: 'action', name: 'patrol' },
+ ],
+ },
+});
+```
+
+节点类型:
+
+| 类别 | 类型 | 行为 |
+|---|---|---|
+| 组合 | `sequence` | 按序 tick 子节点;第一个失败即失败,全部成功才成功。 |
+| | `selector` | 按序 tick 子节点;第一个成功即成功,全部失败才失败。 |
+| | `parallel` | tick 全部子节点;`policy: 'one'` 任一成功即成功,`'all'`(默认)全部成功才成功。 |
+| 装饰器 | `inverter` | 反转子节点的成功/失败。 |
+| | `succeeder` | 总是报告 Success。 |
+| | `repeater` | 把子节点重跑 `count` 次(`0` = 永远)。 |
+| | `wait` | 运行 `seconds` 秒后报告 Success。 |
+| 叶子 | `action` | 运行已注册动作 `name`;它的 `Status`(void 则为 `Success`)向上传播。 |
+| | `condition` | 已注册条件 `name` 为真时返回 `Success`,否则 `Failure`。 |
diff --git a/docs/astro/src/content/docs/zh-cn/gameplay/ai-blackboard.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/ai-blackboard.mdx
new file mode 100644
index 000000000..1657806ed
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/gameplay/ai-blackboard.mdx
@@ -0,0 +1,25 @@
+---
+title: 黑板
+description: "每个 agent 私有的键值存储与一次性事件触发器——AI 状态如何在叶子之间流动、如何喂给转移守卫。"
+---
+
+每个 FSM/BT agent 拥有一块 **`Blackboard`**(黑板)——它私有的键值存储加上一次性事件触发器。
+动作和条件通过 `ctx.blackboard` 访问它;这是 AI 状态在叶子间流动的方式,也是转移守卫取值的来源。
+
+```typescript
+registerAction('takeDamage', (ctx) => {
+ const hp = (ctx.blackboard.get<number>('health') ?? 100) - 10;
+ ctx.blackboard.set('health', hp);
+ if (hp <= 0) ctx.blackboard.fire('died'); // 一条以 'died' 为键的转移被 fire 一次
+});
+```
+
+| 方法 | 说明 |
+|---|---|
+| `get<T>(key)` / `set(key, value)` | 读/写一个值。 |
+| `has(key)` / `delete(key)` | 测试 / 删除一个 key。 |
+| `fire(trigger)` | fire 一个一次性事件;以它为键的转移在被采用前保持启用。 |
+| `isFired(trigger)` / `consume(trigger)` | 测试 / 清除一个触发器。 |
+
+黑板的值支撑 FSM 转移上的 `guard` 比较,而 `trigger` 机制就是 Unity 式的边事件:fire 一次,
+被采用它的那条转移消费。
diff --git a/docs/astro/src/content/docs/zh-cn/gameplay/ai-navigation.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/ai-navigation.mdx
new file mode 100644
index 000000000..a42438016
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/gameplay/ai-navigation.mdx
@@ -0,0 +1,74 @@
+---
+title: 导航
+description: "导航网格与 A* 寻路——构建网格,以及把 NavAgent 移动到任意世界坐标并随目标重规划。"
+---
+
+import { Aside } from '@astrojs/starlight/components';
+
+导航沿着一条避开被阻挡格子的路线,把 agent 移动到某个世界坐标,底层用 A\* 在一个 **`NavGrid`**
+上寻路。
+
+### 构建网格
+
+`NavGrid` 是一个由可走/被阻挡格子构成的矩形网格。把它装到 `Nav` 资源上,agent 才能对它寻路:
+
+```typescript
+import { defineSystem, Res, Nav, NavGrid } from 'esengine';
+
+export const setupNav = defineSystem([Res(Nav)], (nav) => {
+ nav.setGrid(new NavGrid({
+ width: 60, // 列数
+ height: 44, // 行数
+ cellSize: 20, // 每格的世界像素
+ origin: { x: -600, y: -440 }, // 格子 (0,0) 中心的世界坐标
+ }));
+}, { name: 'SetupNav' });
+```
+
+| `NavGrid` 选项 | 类型 | 说明 |
+|---|---|---|
+| `width` | number | 格子列数。 |
+| `height` | number | 格子行数。 |
+| `cellSize` | number | 每格的世界像素(正方形)。 |
+| `origin` | `Vec2` | 格子 `(0,0)` 中心的世界坐标。默认 `(0,0)`。 |
+| `walkable` | `Uint8Array` | 可选的行主序 `width*height` 掩码,`1` = 可走,`0` = 阻挡。省略则全部可走。 |
+
+若想从已绘制的瓦片地图推导网格,而不是手写掩码,用 `navGridFromTilemapLayer`(把某图层的
+实心瓦片视作阻挡)或 `navGridFromTiles`。
+
+<Aside type="tip">
+ `Nav` 资源也能直接回答一次性查询:`nav.findWorldPath(from, to)` 返回一组世界空间路点
+ (没有路线时返回 `null`),无需 `NavAgent`。
+</Aside>
+
+### 移动 agent
+
+加一个 `NavAgent`,然后给它指一个目的地。内置的导航插件会规划路径并每帧沿路径推进 agent——
+你只管设目标。
+
+```typescript
+import { NavAgent, setNavDestination, stopNavAgent } from 'esengine';
+
+cmds.spawn()
+ .insert(Transform, { position: { x: 0, y: 0, z: 0 } })
+ .insert(NavAgent, { speed: 140, arriveRadius: 8 });
+
+// 从任何能访问 world 的系统/动作里——每帧调用都安全:
+setNavDestination(world, entity, { x: 320, y: -120 });
+// ……以及原地停下:
+stopNavAgent(world, entity);
+```
+
+| `NavAgent` 字段 | 默认 | 说明 |
+|---|---|---|
+| `speed` | `120` | 移动速度(世界像素/秒)。 |
+| `radius` | `12` | agent 半径(到达容差 / 碰撞尺寸)。 |
+| `arriveRadius` | `6` | 距最终目标的停止距离。 |
+| `repathInterval` | `0.5` | 移动中两次重规划的间隔秒数;`0` = 只在目标改变时重规划。 |
+| `hasTarget` | `false` | 是否已设目的地(自动管理)。 |
+| `targetX`、`targetY` | `0` | 当前目的地(世界像素)。 |
+| `arrived` | `false` | agent 到达目标的那一帧被置真。 |
+
+`setNavDestination` 每帧调用都安全,可用于追一个移动的目标——只有当目标真的移动、或
+`repathInterval` 到点时,agent 才重新规划。读 `agent.arrived`(或 `Perception`)来判断何时
+切换行为。
diff --git a/docs/astro/src/content/docs/zh-cn/gameplay/ai-perception.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/ai-perception.mdx
new file mode 100644
index 000000000..0e1faad18
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/gameplay/ai-perception.mdx
@@ -0,0 +1,35 @@
+---
+title: 感知
+description: "Perceiver 在视锥内感知附近目标,并把看到的写进 Perception 组件。"
+---
+
+`Perceiver` 每帧扫描最近的、可见的 `PerceptionTarget`,把结果写进同一实体上的 `Perception`
+组件。决策读 `Perception`;感知只是 ECS 数据,而不是一条旁路。
+
+```typescript
+import { Perceiver, PerceptionTarget, Perception } from 'esengine';
+
+// 猎手负责感知……
+cmds.spawn()
+ .insert(Transform, { position: { x: -200, y: 0, z: 0 } })
+ .insert(Perceiver, { range: 260, fovDegrees: 120 })
+ .insert(Perception, {}); // 由感知插件每帧写入
+
+// ……任何被标记为目标的实体。
+cmds.spawn()
+ .insert(Transform, { position: { x: 100, y: 0, z: 0 } })
+ .insert(PerceptionTarget, {});
+```
+
+| 组件 | 字段 | 默认 | 说明 |
+|---|---|---|---|
+| **`Perceiver`** | `range` | `220` | 视野范围(世界像素)。 |
+| | `fovDegrees` | `360` | 视野锥角度(`360` = 全向)。 |
+| **`Perception`** | `visible` | `false` | 当前是否看见一个目标。 |
+| | `distance` | `0` | 到所见目标的距离。 |
+| | `targetX`、`targetY` | `0` | 所见目标位置(世界像素)。 |
+| | `dirX`、`dirY` | `0` | 从观察者指向目标的单位方向。 |
+| **`PerceptionTarget`** | *(标签)* | — | 把实体标记为可被 `Perceiver` 感知。 |
+
+视野锥的朝向由感知者的 `Transform` 旋转决定。`Perception` 是一个瞬态、仅运行时的组件——
+插件每帧重写它,所以你从不需要手写它的值。
diff --git a/docs/astro/src/content/docs/zh-cn/gameplay/ai-state-machines.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/ai-state-machines.mdx
new file mode 100644
index 000000000..bcb2c51e7
--- /dev/null
+++ b/docs/astro/src/content/docs/zh-cn/gameplay/ai-state-machines.mdx
@@ -0,0 +1,63 @@
+---
+title: 状态机
+description: "运行 .esfsm 图:带 enter/update/exit 钩子的状态、带守卫的转移,以及一次性触发器。"
+---
+
+![状态机编辑器——Patrol 与 Chase 状态由带守卫的转移连接](../../../../assets/guides/zh/ai-fsm.png)
+
+*状态机编辑器:状态(Patrol / Chase)由带守卫的转移(`?seesPlayer`、`?lostPlayer`)连接。*
+
+状态机是一组由带守卫的**转移**连接起来的**状态**。任一时刻恰好一个状态处于激活;每个 tick,
+它的出边按顺序被检查,第一条满足条件的被采用。加一个 `StateMachineAgent` 并指向一个图:
+
+```typescript
+import { StateMachineAgent } from 'esengine';
+
+cmds.spawn()
+ .insert(NavAgent, {})
+ .insert(Perceiver, { range: 240 })
+ .insert(Perception, {})
+ .insert(StateMachineAgent, { fsm: 'assets/ai/enemy.esfsm' }); // 一个编辑器编排的资产
+```
+
+| `StateMachineAgent` 字段 | 说明 |
+|---|---|
+| `fsm` | 要运行的机器的 key:一个 `registerFsm` 名字**或**一个 `.esfsm` 资产路径。 |
+| `current` | 当前激活状态名,每 tick 写入(只读;在检视面板可见)。 |
+
+推荐做法是**在编辑器里把图编排成 `.esfsm` 资产**(见[在编辑器里编排](/docs/zh-cn/gameplay/ai-authoring/))。
+状态用字符串引用你注册的动作/条件名。你也可以用代码构建一台机器:
+
+```typescript
+import { registerFsm } from 'esengine';
+
+registerFsm('guard', {
+ initial: 'Patrol',
+ states: [
+ {
+ name: 'Patrol',
+ onUpdate: 'patrol',
+ transitions: [{ to: 'Chase', condition: 'seesPlayer' }],
+ },
+ {
+ name: 'Chase',
+ onEnter: 'startChase',
+ onUpdate: 'chase',
+ transitions: [{ to: 'Patrol', condition: 'lostPlayer' }],
+ },
+ ],
+});
+```
+
+每个状态最多带三个具名钩子——`onEnter`、`onUpdate`、`onExit`——以及一组 `transitions`。当一条
+转移所指定的机制**全部**成立时它才被启用;一条什么都不指定的转移是无条件的:
+
+| 转移字段 | 说明 |
+|---|---|
+| `to` | 目标状态名。 |
+| `trigger` | 必须被 fire 的一次性事件名(采用时消费)。 |
+| `condition` | 必须返回真的一个已注册条件。 |
+| `guard` | 一个或多个黑板比较,按 AND 组合。 |
+
+守卫用 `==`、`!=`、`<`、`<=`、`>`、`>=`、`truthy`、`falsy` 比较一个黑板 key——例如
+`{ key: 'health', op: '<', value: 20 }`。
diff --git a/docs/astro/src/content/docs/zh-cn/gameplay/ai.mdx b/docs/astro/src/content/docs/zh-cn/gameplay/ai.mdx
index e7e6846e4..0f632ff7a 100644
--- a/docs/astro/src/content/docs/zh-cn/gameplay/ai.mdx
+++ b/docs/astro/src/content/docs/zh-cn/gameplay/ai.mdx
@@ -3,7 +3,7 @@ title: 游戏 AI
description: 游戏 AI 层——感知、基于网格的 A* 寻路导航、状态机与行为树,全部由同一份具名动作/条件注册表驱动,并在编辑器里可视化编排。
---
-import { Aside, Card, CardGrid } from '@astrojs/starlight/components';
+import { Aside, Card, CardGrid, LinkCard } from '@astrojs/starlight/components';
Estella 的 AI 层把一个实体变成会**感知**、会**决策**、会**移动**的角色。它由四个协作部件
组成,而这四者共享同一套设计:
@@ -30,7 +30,7 @@ Estella 的 AI 层把一个实体变成会**感知**、会**决策**、会**移
<Aside type="note">
这里的一切都是 `esengine` 内核里的纯 TypeScript(没有 WebAssembly 侧模块)。感知、FSM、BT、
导航这四个插件都由编辑器和 Web 运行时**自动**加入。只有当你从一个裸的 `new App()` 起步时,
- 才需要自己加插件(见[自定义应用](#自定义应用))。
+ 才需要自己加插件(见[自定义应用](/docs/zh-cn/gameplay/ai-advanced/#自定义应用))。
</Aside>
## 共享注册表
@@ -60,7 +60,7 @@ registerAction('chase', (ctx) => {
| `ctx.dt` | `number` | 帧间隔(秒)。 |
| `ctx.world` | `World` | 完整世界访问,用于跨实体读取。 |
| `ctx.commands` | `Commands` | 延迟的 spawn/despawn,tick 中调用安全。 |
-| `ctx.blackboard` | `Blackboard` | 该 agent 的 AI 数据面(见[黑板](#黑板))。 |
+| `ctx.blackboard` | `Blackboard` | 该 agent 的 AI 数据面(见[黑板](/docs/zh-cn/gameplay/ai-blackboard/))。 |
| `ctx.get(Comp)` | `ComponentData` | 读取**本**实体上的另一个组件。 |
| `ctx.set(Comp, data)` | `void` | 写入**本**实体上的一个组件。 |
| `ctx.has(Comp)` | `boolean` | 本实体是否拥有 `Comp`。 |
@@ -132,380 +132,17 @@ registerFsm('intro', {
就是这个模式的完整落地:场景开始即播开场时间轴,播完解锁操作,按 R 重播——
全程零注册动作。
-## 感知
+## 四个部分
-`Perceiver` 每帧扫描最近的、可见的 `PerceptionTarget`,把结果写进同一实体上的 `Perception`
-组件。决策读 `Perception`;感知只是 ECS 数据,而不是一条旁路。
-
-```typescript
-import { Perceiver, PerceptionTarget, Perception } from 'esengine';
-
-// 猎手负责感知……
-cmds.spawn()
- .insert(Transform, { position: { x: -200, y: 0, z: 0 } })
- .insert(Perceiver, { range: 260, fovDegrees: 120 })
- .insert(Perception, {}); // 由感知插件每帧写入
-
-// ……任何被标记为目标的实体。
-cmds.spawn()
- .insert(Transform, { position: { x: 100, y: 0, z: 0 } })
- .insert(PerceptionTarget, {});
-```
-
-| 组件 | 字段 | 默认 | 说明 |
-|---|---|---|---|
-| **`Perceiver`** | `range` | `220` | 视野范围(世界像素)。 |
-| | `fovDegrees` | `360` | 视野锥角度(`360` = 全向)。 |
-| **`Perception`** | `visible` | `false` | 当前是否看见一个目标。 |
-| | `distance` | `0` | 到所见目标的距离。 |
-| | `targetX`、`targetY` | `0` | 所见目标位置(世界像素)。 |
-| | `dirX`、`dirY` | `0` | 从观察者指向目标的单位方向。 |
-| **`PerceptionTarget`** | *(标签)* | — | 把实体标记为可被 `Perceiver` 感知。 |
-
-视野锥的朝向由感知者的 `Transform` 旋转决定。`Perception` 是一个瞬态、仅运行时的组件——
-插件每帧重写它,所以你从不需要手写它的值。
-
-## 导航
-
-导航沿着一条避开被阻挡格子的路线,把 agent 移动到某个世界坐标,底层用 A\* 在一个 **`NavGrid`**
-上寻路。
-
-### 构建网格
-
-`NavGrid` 是一个由可走/被阻挡格子构成的矩形网格。把它装到 `Nav` 资源上,agent 才能对它寻路:
-
-```typescript
-import { defineSystem, Res, Nav, NavGrid } from 'esengine';
-
-export const setupNav = defineSystem([Res(Nav)], (nav) => {
- nav.setGrid(new NavGrid({
- width: 60, // 列数
- height: 44, // 行数
- cellSize: 20, // 每格的世界像素
- origin: { x: -600, y: -440 }, // 格子 (0,0) 中心的世界坐标
- }));
-}, { name: 'SetupNav' });
-```
-
-| `NavGrid` 选项 | 类型 | 说明 |
-|---|---|---|
-| `width` | number | 格子列数。 |
-| `height` | number | 格子行数。 |
-| `cellSize` | number | 每格的世界像素(正方形)。 |
-| `origin` | `Vec2` | 格子 `(0,0)` 中心的世界坐标。默认 `(0,0)`。 |
-| `walkable` | `Uint8Array` | 可选的行主序 `width*height` 掩码,`1` = 可走,`0` = 阻挡。省略则全部可走。 |
-
-若想从已绘制的瓦片地图推导网格,而不是手写掩码,用 `navGridFromTilemapLayer`(把某图层的
-实心瓦片视作阻挡)或 `navGridFromTiles`。
-
-<Aside type="tip">
- `Nav` 资源也能直接回答一次性查询:`nav.findWorldPath(from, to)` 返回一组世界空间路点
- (没有路线时返回 `null`),无需 `NavAgent`。
-</Aside>
-
-### 移动 agent
-
-加一个 `NavAgent`,然后给它指一个目的地。内置的导航插件会规划路径并每帧沿路径推进 agent——
-你只管设目标。
-
-```typescript
-import { NavAgent, setNavDestination, stopNavAgent } from 'esengine';
-
-cmds.spawn()
- .insert(Transform, { position: { x: 0, y: 0, z: 0 } })
- .insert(NavAgent, { speed: 140, arriveRadius: 8 });
-
-// 从任何能访问 world 的系统/动作里——每帧调用都安全:
-setNavDestination(world, entity, { x: 320, y: -120 });
-// ……以及原地停下:
-stopNavAgent(world, entity);
-```
-
-| `NavAgent` 字段 | 默认 | 说明 |
-|---|---|---|
-| `speed` | `120` | 移动速度(世界像素/秒)。 |
-| `radius` | `12` | agent 半径(到达容差 / 碰撞尺寸)。 |
-| `arriveRadius` | `6` | 距最终目标的停止距离。 |
-| `repathInterval` | `0.5` | 移动中两次重规划的间隔秒数;`0` = 只在目标改变时重规划。 |
-| `hasTarget` | `false` | 是否已设目的地(自动管理)。 |
-| `targetX`、`targetY` | `0` | 当前目的地(世界像素)。 |
-| `arrived` | `false` | agent 到达目标的那一帧被置真。 |
-
-`setNavDestination` 每帧调用都安全,可用于追一个移动的目标——只有当目标真的移动、或
-`repathInterval` 到点时,agent 才重新规划。读 `agent.arrived`(或 `Perception`)来判断何时
-切换行为。
-
-## 状态机
-
-![状态机编辑器——Patrol 与 Chase 状态由带守卫的转移连接](../../../../assets/guides/zh/ai-fsm.png)
-
-*状态机编辑器:状态(Patrol / Chase)由带守卫的转移(`?seesPlayer`、`?lostPlayer`)连接。*
-
-状态机是一组由带守卫的**转移**连接起来的**状态**。任一时刻恰好一个状态处于激活;每个 tick,
-它的出边按顺序被检查,第一条满足条件的被采用。加一个 `StateMachineAgent` 并指向一个图:
-
-```typescript
-import { StateMachineAgent } from 'esengine';
-
-cmds.spawn()
- .insert(NavAgent, {})
- .insert(Perceiver, { range: 240 })
- .insert(Perception, {})
- .insert(StateMachineAgent, { fsm: 'assets/ai/enemy.esfsm' }); // 一个编辑器编排的资产
-```
-
-| `StateMachineAgent` 字段 | 说明 |
-|---|---|
-| `fsm` | 要运行的机器的 key:一个 `registerFsm` 名字**或**一个 `.esfsm` 资产路径。 |
-| `current` | 当前激活状态名,每 tick 写入(只读;在检视面板可见)。 |
-
-推荐做法是**在编辑器里把图编排成 `.esfsm` 资产**(见[在编辑器里编排](#在编辑器里编排))。
-状态用字符串引用你注册的动作/条件名。你也可以用代码构建一台机器:
-
-```typescript
-import { registerFsm } from 'esengine';
-
-registerFsm('guard', {
- initial: 'Patrol',
- states: [
- {
- name: 'Patrol',
- onUpdate: 'patrol',
- transitions: [{ to: 'Chase', condition: 'seesPlayer' }],
- },
- {
- name: 'Chase',
- onEnter: 'startChase',
- onUpdate: 'chase',
- transitions: [{ to: 'Patrol', condition: 'lostPlayer' }],
- },
- ],
-});
-```
-
-每个状态最多带三个具名钩子——`onEnter`、`onUpdate`、`onExit`——以及一组 `transitions`。当一条
-转移所指定的机制**全部**成立时它才被启用;一条什么都不指定的转移是无条件的:
-
-| 转移字段 | 说明 |
-|---|---|
-| `to` | 目标状态名。 |
-| `trigger` | 必须被 fire 的一次性事件名(采用时消费)。 |
-| `condition` | 必须返回真的一个已注册条件。 |
-| `guard` | 一个或多个黑板比较,按 AND 组合。 |
-
-守卫用 `==`、`!=`、`<`、`<=`、`>`、`>=`、`truthy`、`falsy` 比较一个黑板 key——例如
-`{ key: 'health', op: '<', value: 20 }`。
-
-## 行为树
-
-![行为树编辑器——Selector 之下是 Sequence 与一个兜底动作](../../../../assets/guides/zh/ai-bt.png)
-
-*行为树编辑器:**Selector** 根之下是一个 **Sequence**(Condition `seesPlayer` → Action `chase`),外加兜底的 `patrol` 动作。*
-
-行为树每帧从**根**开始 tick 并返回一个 `Status`。组合节点控制流程;装饰器变换其唯一子节点的
-结果;叶子是你注册的动作和条件。加一个 `BehaviorTreeAgent`:
-
-```typescript
-import { BehaviorTreeAgent } from 'esengine';
-
-cmds.spawn()
- .insert(NavAgent, {})
- .insert(Perception, {})
- .insert(BehaviorTreeAgent, { bt: 'assets/ai/enemy.esbt' }); // 一个编辑器编排的资产
-```
-
-| `BehaviorTreeAgent` 字段 | 说明 |
-|---|---|
-| `bt` | 要运行的树的 key:一个 `registerBt` 名字**或**一个 `.esbt` 资产路径。 |
-| `status` | 上一次根状态,每 tick 写入(只读)。 |
-
-在编辑器里可视化编排这棵树,或用 `registerBt` 用代码构建:
-
-```typescript
-import { registerBt } from 'esengine';
-
-registerBt('guard', {
- root: {
- type: 'selector', // 从左到右尝试子节点,直到一个成功
- children: [
- {
- type: 'sequence', // 全部按序成功
- children: [
- { type: 'condition', name: 'seesPlayer' },
- { type: 'action', name: 'chase' },
- ],
- },
- { type: 'action', name: 'patrol' },
- ],
- },
-});
-```
-
-节点类型:
-
-| 类别 | 类型 | 行为 |
-|---|---|---|
-| 组合 | `sequence` | 按序 tick 子节点;第一个失败即失败,全部成功才成功。 |
-| | `selector` | 按序 tick 子节点;第一个成功即成功,全部失败才失败。 |
-| | `parallel` | tick 全部子节点;`policy: 'one'` 任一成功即成功,`'all'`(默认)全部成功才成功。 |
-| 装饰器 | `inverter` | 反转子节点的成功/失败。 |
-| | `succeeder` | 总是报告 Success。 |
-| | `repeater` | 把子节点重跑 `count` 次(`0` = 永远)。 |
-| | `wait` | 运行 `seconds` 秒后报告 Success。 |
-| 叶子 | `action` | 运行已注册动作 `name`;它的 `Status`(void 则为 `Success`)向上传播。 |
-| | `condition` | 已注册条件 `name` 为真时返回 `Success`,否则 `Failure`。 |
-
-## 黑板
-
-每个 FSM/BT agent 拥有一块 **`Blackboard`**(黑板)——它私有的键值存储加上一次性事件触发器。
-动作和条件通过 `ctx.blackboard` 访问它;这是 AI 状态在叶子间流动的方式,也是转移守卫取值的来源。
-
-```typescript
-registerAction('takeDamage', (ctx) => {
- const hp = (ctx.blackboard.get<number>('health') ?? 100) - 10;
- ctx.blackboard.set('health', hp);
- if (hp <= 0) ctx.blackboard.fire('died'); // 一条以 'died' 为键的转移被 fire 一次
-});
-```
-
-| 方法 | 说明 |
-|---|---|
-| `get<T>(key)` / `set(key, value)` | 读/写一个值。 |
-| `has(key)` / `delete(key)` | 测试 / 删除一个 key。 |
-| `fire(trigger)` | fire 一个一次性事件;以它为键的转移在被采用前保持启用。 |
-| `isFired(trigger)` / `consume(trigger)` | 测试 / 清除一个触发器。 |
-
-黑板的值支撑 FSM 转移上的 `guard` 比较,而 `trigger` 机制就是 Unity 式的边事件:fire 一次,
-被采用它的那条转移消费。
-
-## 在编辑器里编排
-
-设想的工作流是图本身**用数据、不用代码**——你注册一次叶子逻辑,然后可视化地构建并调优机器/树:
-
-1. 在**内容浏览器**里,新建一个**状态机**(`.esfsm`)或**行为树**(`.esbt`)资产,双击它打开
- 节点图编辑器。
-2. 添加状态/节点,拖拽连线,把每个叶子的**动作**或**条件**填成你注册的某个名字。在检视面板里
- 设置转移的条件、触发器和黑板守卫。
-3. 在 agent 实体上,把 `StateMachineAgent.fsm`(或 `BehaviorTreeAgent.bt`)设为资产的路径。
-
-资产按路径引用并**随场景预加载**,所以图在 agent 首次 tick 之前就已注册——不需要
-`registerFsm`/`registerBt` 调用。因为两种范式都从同一份注册表解析叶子,你可以先把一个敌人
-原型成状态机,之后再换成行为树(或两者都跑),而不用动你的动作/条件代码。
-
-## 进阶:组件层之下
-
-`Nav`、`NavAgent`、`Perceiver`——组件层——覆盖了常见场景。它们底下的原语同样被导出,
-全是不依赖引擎/wasm 的纯 TypeScript,供你在不要 agent 的情况下求一条路径、
-或在没有 `Perceiver` 时做一次视线检查。
-
-### 手动寻路
-
-`findPath` 就是导航插件用的那个 A\*:在 `NavGrid` 格子上做均匀代价搜索,4 连通或
-8 连通,octile/曼哈顿启发式,且不切角(走对角线要求两个共享的正交格子都可通行)。
-当你要自己驱动移动、画路径预览、或计算可达性(回合制的移动范围)时下沉到它——
-或者当一张网格不够用时,因为 `Nav` 资源只持有一张网格:
-
-```typescript
-import { NavGrid, findPath, pathToWorld } from 'esengine';
-
-const grid = new NavGrid({ width: 32, height: 24, cellSize: 32 });
-
-const path = findPath(
- grid,
- grid.worldToCell(hero.x, hero.y), // Cell — integer grid coordinates
- grid.worldToCell(chest.x, chest.y),
- { diagonal: false },
-);
-if (path) {
- const waypoints = pathToWorld(grid, path); // Vec2[] — cell centers, world pixels
-}
-```
-
-`findPath(grid, start, goal, opts?)` 返回含首尾两端的 `Cell[]` 路径,不可达时返回
-`null`。`Cell` 是整数网格坐标 `{ x, y }`(与 `Vec2` 刻意区分,以标示格子空间);用
-`grid.worldToCell` / `grid.cellToWorld` 互转,或用 `pathToWorld` 把整条路径转成
-世界空间路点。
-
-| `PathfindOptions` 字段 | 默认 | 说明 |
-|---|---|---|
-| `diagonal` | `true` | 允许 8 连通的对角移动。 |
-| `snapRadius` | `8` | 起点/终点落在被阻挡格子上时,先在此环半径内吸附到最近的可走格子再搜索;`0` 关闭吸附。 |
-
-`navGridFromTiles` 从任意瓦片读取器构建可走掩码——它是 `navGridFromTilemapLayer`
-底下的核心,后者只是接上了 `TilemapAPI.getTile`:
-
-```typescript
-import { navGridFromTiles } from 'esengine';
-
-const grid = navGridFromTiles((x, y) => level.tiles[y][x], {
- width: 32, height: 24, cellSize: 32,
- blockedTileIds: [WALL_TILE, WATER_TILE],
-});
-```
-
-| `BuildNavGridOptions` 字段 | 说明 |
-|---|---|
-| `width` / `height` / `cellSize` / `origin?` | 与 `NavGrid` 选项相同(见[构建网格](#构建网格))。 |
-| `blockedTileIds?` | 阻挡移动的瓦片 id 的精确集合。 |
-| `isBlocked?` | 针对瓦片 id 的自定义谓词(`0` = 空);覆盖 `blockedTileIds`。二者都不给时,任何非空瓦片都阻挡。 |
-
-### 感知内幕
-
-感知插件是四个导出函数之上的薄封装——适合在动作里做一次性视线检查、做自定义感官
-(记忆、听觉、多目标),或对着一个假 world 做单元测试:
-
-- **`senseTarget(ox, oy, facing, tx, ty, range, halfFov, isBlocked?)`**——纯几何:
- 先查距离,再查视野锥(`halfFov` 是锥角的*一半*,弧度;≥ π 表示全向),最后走可选的
- 遮挡回调。
-- **`facingFromQuat(z, w)`**——从 `Transform` 旋转四元数的 z/w 分量求 2D 朝向角
- (弧度)。
-- **`makeLosCheck(physics)`**——用物理射线构建遮挡回调:任何命中明显落在目标之前
- (`fraction < 0.98`——最后约 2% 是目标自己)即视为遮挡。
-- **`stepPerception(world, isBlocked?)`**——插件每帧在 `PreUpdate` 跑的那一步:
- 对每个 `Perceiver`,感知全部 `PerceptionTarget`,留下最近的可见者,写入
- `Perception` 组件。
-
-```typescript
-import { senseTarget, facingFromQuat, Transform, registerCondition } from 'esengine';
-
-// A one-off sight check against a POINT — no PerceptionTarget needed.
-registerCondition('seesShrine', (ctx) => {
- const tf = ctx.get(Transform);
- const facing = facingFromQuat(tf.rotation.z, tf.rotation.w);
- return senseTarget(
- tf.position.x, tf.position.y, facing,
- SHRINE.x, SHRINE.y,
- 300, Math.PI / 3, // 300 px range, 120° cone
- ).visible;
-});
-```
-
-`senseTarget` 返回一个 `SenseResult`:
-
-| `SenseResult` 字段 | 说明 |
-|---|---|
-| `visible` | 目标在范围内、在锥内、且未被遮挡。 |
-| `distance` | 到目标的距离——即使不可见也总是被设置。 |
-| `dirX` / `dirY` | 观察者 → 目标的单位方向;不可见时为 `(0, 0)`。 |
-
-内置系统只在物理模块已加载时才接入 `makeLosCheck`;否则感知只做距离 + 视野锥——
-AI 层没有对物理的硬依赖。
-
-## 自定义应用
-
-感知、FSM、BT、导航这四个插件是默认插件集的一部分,所以**编辑器和 `esengine` Web 运行时会替你
-加上它们**。只有当你从一个裸的 `new App()` 构建应用时,才需要显式加:
-
-```typescript
-import { perceptionPlugin, fsmPlugin, btPlugin, navPlugin } from 'esengine';
-
-app.addPlugin(perceptionPlugin);
-app.addPlugin(fsmPlugin);
-app.addPlugin(btPlugin);
-app.addPlugin(navPlugin);
-```
-
-每个都同时导出为一个开箱即用的单例(`navPlugin`)和一个类(`NavPlugin`),需要多个实例时用类。
+<CardGrid>
+ <LinkCard title="感知" href="/docs/zh-cn/gameplay/ai-perception/" description="视锥,以及一个 agent 此刻看到了什么。" />
+ <LinkCard title="导航" href="/docs/zh-cn/gameplay/ai-navigation/" description="导航网格、A* 路径,以及让 agent 沿路径移动。" />
+ <LinkCard title="状态机" href="/docs/zh-cn/gameplay/ai-state-machines/" description="状态、带守卫的转移,以及一次性触发器。" />
+ <LinkCard title="行为树" href="/docs/zh-cn/gameplay/ai-behavior-trees/" description="选择、序列、装饰器与叶子。" />
+ <LinkCard title="黑板" href="/docs/zh-cn/gameplay/ai-blackboard/" description="两种范式共同读写的每-agent 数据面。" />
+ <LinkCard title="在编辑器里编排" href="/docs/zh-cn/gameplay/ai-authoring/" description="叶子在代码里注册,图在编辑器里搭。" />
+ <LinkCard title="组件层之下" href="/docs/zh-cn/gameplay/ai-advanced/" description="手动寻路、感知内幕,以及裸 App 接线。" />
+</CardGrid>
## 组合起来
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index a64f5b353..22c38b2f2 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -129,12 +129,12 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
Marker: { category: 'world', summary: 'A named point or region of gameplay interest — spawn point, waypoint, trigger zone — queryable like any component.', doc: 'gameplay/markers', anchor: 'marker-component-reference', anchorZh: 'marker-组件参考' },
// ── Gameplay ───────────────────────────────────────────────────────────────
- NavAgent: { category: 'gameplay', summary: 'Steers an entity along a path found on the navigation grid.', doc: 'gameplay/ai', anchor: 'moving-an-agent', anchorZh: '移动-agent' },
- Perceiver: { category: 'gameplay', summary: 'Senses nearby perception targets within a sight cone and range.', doc: 'gameplay/ai', anchor: 'perception', anchorZh: '感知' },
- Perception: { category: 'gameplay', summary: "What a perceiver currently sees — written each frame for the entity's own logic to read.", doc: 'gameplay/ai', anchor: 'perception', anchorZh: '感知' },
- PerceptionTarget: { category: 'gameplay', summary: 'Tag: perceivers can see this entity.', doc: 'gameplay/ai', anchor: 'perception', anchorZh: '感知' },
- StateMachineAgent: { category: 'gameplay', summary: 'Runs a gameplay state machine asset, calling registry actions as states enter, update and exit.', doc: 'gameplay/ai', anchor: 'state-machines', anchorZh: '状态机' },
- BehaviorTreeAgent: { category: 'gameplay', summary: 'Ticks a behavior tree asset against a blackboard, calling registry actions at its leaves.', doc: 'gameplay/ai', anchor: 'behavior-trees', anchorZh: '行为树' },
+ NavAgent: { category: 'gameplay', summary: 'Steers an entity along a path found on the navigation grid.', doc: 'gameplay/ai-navigation' },
+ Perceiver: { category: 'gameplay', summary: 'Senses nearby perception targets within a sight cone and range.', doc: 'gameplay/ai-perception' },
+ Perception: { category: 'gameplay', summary: "What a perceiver currently sees — written each frame for the entity's own logic to read.", doc: 'gameplay/ai-perception' },
+ PerceptionTarget: { category: 'gameplay', summary: 'Tag: perceivers can see this entity.', doc: 'gameplay/ai-perception' },
+ StateMachineAgent: { category: 'gameplay', summary: 'Runs a gameplay state machine asset, calling registry actions as states enter, update and exit.', doc: 'gameplay/ai-state-machines' },
+ BehaviorTreeAgent: { category: 'gameplay', summary: 'Ticks a behavior tree asset against a blackboard, calling registry actions at its leaves.', doc: 'gameplay/ai-behavior-trees' },
EventBinding: { category: 'gameplay', summary: 'Wires an event on this entity to named actions — gameplay authored in the inspector, with no script.', doc: 'scripting/events', anchor: 'the-data', anchorZh: '数据本身' },
AudioSource: { category: 'gameplay', summary: 'Declarative playback attached to an entity, attenuated by distance when spatial.', doc: 'assets/audio', anchor: 'declarative-playback--audiosource', anchorZh: '声明式播放--audiosource' },
AudioListener: { category: 'gameplay', summary: 'The ear spatial audio is mixed relative to — usually the camera or the player.', doc: 'assets/audio', anchor: 'spatial-audio', anchorZh: '空间音频' },