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.

feat(sdk): gameplay AI runtime - navigation + state machines

esenginefd4b3338a54f
diff --git a/sdk/src/ai/fsm/AiContext.ts b/sdk/src/ai/fsm/AiContext.ts
new file mode 100644
index 000000000..a8147f5e5
--- /dev/null
+++ b/sdk/src/ai/fsm/AiContext.ts
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file AiContext.ts
+ * @brief The concrete leaf context + the shared action/condition registry.
+ *
+ * AiContext is a BehaviorContext superset (adds the blackboard): writing an FSM
+ * action or a BT leaf is the same programming model as a `defineBehavior.update`
+ * — same entity/world/commands access, plus `blackboard` for AI data flow. This
+ * is the engine layer, so it may reference World/Commands; the FSM/BT cores stay
+ * generic and wasm-free.
+ */
+
+import type { Entity } from '../../types';
+import type { World } from '../../world';
+import type { CommandsInstance } from '../../commands';
+import type { AnyComponentDef, ComponentData } from '../../component';
+import type { Blackboard } from './Blackboard';
+import { AiRegistry, type AiAction, type AiCondition } from './registry';
+
+export interface AiContext {
+ /** The agent entity this action/condition runs for. */
+ readonly entity: Entity;
+ /** Frame delta in seconds. */
+ readonly dt: number;
+ /** This agent's blackboard — the AI data plane. */
+ readonly blackboard: Blackboard;
+ /** The world, for cross-entity access. */
+ readonly world: World;
+ /** Deferred structural ops (spawn / despawn), safe mid-iteration. */
+ readonly commands: CommandsInstance;
+ /** Read another component on THIS entity. */
+ get<C extends AnyComponentDef>(component: C): ComponentData<C>;
+ /** Write another component on THIS entity. */
+ set<C extends AnyComponentDef>(component: C, data: ComponentData<C>): void;
+ /** Whether THIS entity has `component`. */
+ has(component: AnyComponentDef): boolean;
+}
+
+/**
+ * The process-wide AI registry. Actions/conditions are code registrations
+ * (stable like component defs), so a single shared instance is correct across
+ * App instances; `.esfsm`/`.esbt` data references resolve against it.
+ */
+export const aiRegistry = new AiRegistry<AiContext>();
+
+/** Register a named action referenced by FSM state hooks / BT leaves. */
+export function registerAction(name: string, fn: AiAction<AiContext>): void {
+ aiRegistry.registerAction(name, fn);
+}
+
+/** Register a named condition referenced by FSM transitions / BT conditions. */
+export function registerCondition(name: string, fn: AiCondition<AiContext>): void {
+ aiRegistry.registerCondition(name, fn);
+}
diff --git a/sdk/src/ai/fsm/Blackboard.ts b/sdk/src/ai/fsm/Blackboard.ts
new file mode 100644
index 000000000..f0ec6e9dd
--- /dev/null
+++ b/sdk/src/ai/fsm/Blackboard.ts
@@ -0,0 +1,84 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Blackboard.ts
+ * @brief Per-agent key/value context + one-shot event triggers.
+ *
+ * The shared data plane for the AI layer: FSM guards and BT conditions read it,
+ * actions write it, game code seeds it. Triggers are edge events (Unity-style):
+ * fired once, consumed by the transition that takes them.
+ */
+
+import type { CompareOp, BlackboardGuard } from './types';
+
+export class Blackboard {
+ private data = new Map<string, unknown>();
+ private triggers = new Set<string>();
+
+ get<T = unknown>(key: string): T | undefined {
+ return this.data.get(key) as T | undefined;
+ }
+
+ set(key: string, value: unknown): void {
+ this.data.set(key, value);
+ }
+
+ has(key: string): boolean {
+ return this.data.has(key);
+ }
+
+ delete(key: string): void {
+ this.data.delete(key);
+ }
+
+ /** Fire a one-shot event; a transition keyed on it becomes enabled until taken. */
+ fire(trigger: string): void {
+ this.triggers.add(trigger);
+ }
+
+ isFired(trigger: string): boolean {
+ return this.triggers.has(trigger);
+ }
+
+ consume(trigger: string): void {
+ this.triggers.delete(trigger);
+ }
+
+ /** Drop all pending triggers (e.g. on reset). */
+ clearTriggers(): void {
+ this.triggers.clear();
+ }
+}
+
+/** Evaluate one guard against the blackboard. Missing keys compare as undefined. */
+export function evalGuard(bb: Blackboard, guard: BlackboardGuard): boolean {
+ const actual = bb.get(guard.key);
+ switch (guard.op) {
+ case '==': return actual === guard.value;
+ case '!=': return actual !== guard.value;
+ case '<': return num(actual) < num(guard.value);
+ case '<=': return num(actual) <= num(guard.value);
+ case '>': return num(actual) > num(guard.value);
+ case '>=': return num(actual) >= num(guard.value);
+ case 'truthy': return !!actual;
+ case 'falsy': return !actual;
+ default: return assertNever(guard.op);
+ }
+}
+
+/** True when every guard passes (empty set → vacuously true). */
+export function evalGuards(bb: Blackboard, guards: BlackboardGuard | BlackboardGuard[]): boolean {
+ if (Array.isArray(guards)) {
+ for (const g of guards) if (!evalGuard(bb, g)) return false;
+ return true;
+ }
+ return evalGuard(bb, guards);
+}
+
+function num(v: unknown): number {
+ return typeof v === 'number' ? v : Number(v);
+}
+
+function assertNever(op: CompareOp): never {
+ throw new Error(`unknown compare op: ${op}`);
+}
diff --git a/sdk/src/ai/fsm/FsmPlugin.ts b/sdk/src/ai/fsm/FsmPlugin.ts
new file mode 100644
index 000000000..9b96ce314
--- /dev/null
+++ b/sdk/src/ai/fsm/FsmPlugin.ts
@@ -0,0 +1,148 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file FsmPlugin.ts
+ * @brief Ticks StateMachineAgents against the shared runtime + registry.
+ *
+ * Per-entity run state + blackboard live in a closure Map (the `defineBehavior`
+ * pattern), so the component stays serializable. The per-frame body is
+ * `stepStateMachines`, extracted to unit-test against a fake world. Gated to
+ * play mode; runs in `Update` before nav follow so an FSM action can retarget a
+ * NavAgent the same frame.
+ */
+
+import type { App, Plugin } from '../../app';
+import type { Entity } from '../../types';
+import type { World } from '../../world';
+import { defineSystem, Schedule, GetWorld } from '../../system';
+import { Res, Time, type TimeData } from '../../resource';
+import { defineResource } from '../../resource';
+import { Commands, type CommandsInstance } from '../../commands';
+import { playModeOnly } from '../../env';
+import type { AnyComponentDef, ComponentData } from '../../component';
+import { Blackboard } from './Blackboard';
+import { createFsmRunState, stepFsm, type FsmRunState } from './FsmRunner';
+import { aiRegistry, type AiContext } from './AiContext';
+import { StateMachineAgent, getFsm } from './StateMachineAgent';
+
+/** Per-entity FSM runtime: blackboard persists; run rebuilds when the FSM key changes. */
+interface AgentState {
+ bb: Blackboard;
+ run: FsmRunState | null;
+ fsmKey: string | null;
+}
+
+/** The slice of `World` the FSM step needs — lets tests inject a fake. */
+export interface FsmWorldView {
+ getEntitiesWithComponents(components: readonly AnyComponentDef[]): Entity[];
+ get<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C>;
+ set<C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentData<C>): void;
+ has(entity: Entity, component: AnyComponentDef): boolean;
+}
+
+type MutableAiContext = {
+ -readonly [K in keyof AiContext]: AiContext[K];
+};
+
+/** Get (creating if needed) an agent's blackboard — lets game code seed data / fire triggers early. */
+export function agentBlackboard(states: Map<Entity, AgentState>, entity: Entity): Blackboard {
+ let st = states.get(entity);
+ if (!st) {
+ st = { bb: new Blackboard(), run: null, fsmKey: null };
+ states.set(entity, st);
+ }
+ return st.bb;
+}
+
+/** Advance every StateMachineAgent one tick. `states` carries per-entity runtime across frames. */
+export function stepStateMachines(
+ world: FsmWorldView,
+ commands: CommandsInstance,
+ dt: number,
+ states: Map<Entity, AgentState>,
+): void {
+ if (dt <= 0) return;
+
+ const ctx: MutableAiContext = {
+ entity: 0 as Entity,
+ dt,
+ blackboard: null as unknown as Blackboard,
+ world: world as unknown as World,
+ commands,
+ get: c => world.get(ctx.entity, c),
+ set: (c, d) => world.set(ctx.entity, c, d),
+ has: c => world.has(ctx.entity, c),
+ };
+
+ for (const entity of world.getEntitiesWithComponents([StateMachineAgent])) {
+ const agent = world.get(entity, StateMachineAgent);
+ if (!agent.fsm) continue;
+ const fsm = getFsm(agent.fsm);
+ if (!fsm) continue;
+
+ let st = states.get(entity);
+ if (!st) {
+ st = { bb: new Blackboard(), run: null, fsmKey: null };
+ states.set(entity, st);
+ }
+ if (st.run === null || st.fsmKey !== agent.fsm) {
+ st.run = createFsmRunState(fsm);
+ st.fsmKey = agent.fsm;
+ }
+
+ ctx.entity = entity;
+ ctx.dt = dt;
+ ctx.blackboard = st.bb;
+ stepFsm(fsm, st.run, ctx, st.bb, aiRegistry);
+
+ if (agent.current !== st.run.current) {
+ agent.current = st.run.current;
+ world.set(entity, StateMachineAgent, agent);
+ }
+ }
+}
+
+/** Resource for game code to reach an agent's blackboard / current state. */
+export class StateMachines {
+ constructor(private states: Map<Entity, AgentState>) {}
+
+ blackboard(entity: Entity): Blackboard {
+ return agentBlackboard(this.states, entity);
+ }
+
+ /** Fire a one-shot trigger consumed by the agent's next enabled transition. */
+ fire(entity: Entity, trigger: string): void {
+ agentBlackboard(this.states, entity).fire(trigger);
+ }
+
+ /** The agent's active state name, or null before its first tick. */
+ state(entity: Entity): string | null {
+ return this.states.get(entity)?.run?.current ?? null;
+ }
+}
+
+export const AiFsm = defineResource<StateMachines>(null!, 'AiFsm');
+
+export class FsmPlugin implements Plugin {
+ name = 'fsm';
+
+ build(app: App): void {
+ const states = new Map<Entity, AgentState>();
+ app.world.onDespawn((entity: Entity) => states.delete(entity));
+ app.insertResource(AiFsm, new StateMachines(states));
+
+ app.addSystemToSchedule(
+ Schedule.Update,
+ defineSystem(
+ [Res(Time), Commands(), GetWorld()],
+ (time: TimeData, commands: CommandsInstance, world) => {
+ stepStateMachines(world as FsmWorldView, commands, time.delta, states);
+ },
+ { name: 'StateMachineSystem' },
+ ),
+ { runIf: playModeOnly },
+ );
+ }
+}
+
+export const fsmPlugin = new FsmPlugin();
diff --git a/sdk/src/ai/fsm/FsmRunner.ts b/sdk/src/ai/fsm/FsmRunner.ts
new file mode 100644
index 000000000..d1720d4ad
--- /dev/null
+++ b/sdk/src/ai/fsm/FsmRunner.ts
@@ -0,0 +1,98 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file FsmRunner.ts
+ * @brief The state-machine interpreter — pure, generic, unit-testable.
+ *
+ * `compileFsm` indexes a definition once (per loaded asset); `stepFsm` advances
+ * one runtime instance one tick. Semantics: at most one transition per tick;
+ * `onEnter` runs the tick a state becomes active, `onExit` when it is left,
+ * `onUpdate` on ticks where no transition fires.
+ */
+
+import type { FsmDefinition, FsmState, FsmTransition } from './types';
+import { Blackboard, evalGuards } from './Blackboard';
+import type { AiRegistry } from './registry';
+
+/** A definition indexed by state name for O(1) lookup during ticks. */
+export interface CompiledFsm {
+ initial: string;
+ states: Map<string, FsmState>;
+}
+
+export function compileFsm(def: FsmDefinition): CompiledFsm {
+ const states = new Map<string, FsmState>();
+ for (const s of def.states) states.set(s.name, s);
+ return { initial: def.initial, states };
+}
+
+/** Mutable per-instance runtime state. `entered` gates the one-shot `onEnter`. */
+export interface FsmRunState {
+ current: string;
+ previous: string | null;
+ entered: boolean;
+}
+
+export function createFsmRunState(fsm: CompiledFsm): FsmRunState {
+ return { current: fsm.initial, previous: null, entered: false };
+}
+
+/**
+ * Advance one tick. Returns true if a transition was taken. The new state's
+ * `onEnter` runs on the following tick (via `entered=false`), so a pass-through
+ * state cleanly enters-then-exits across two ticks rather than looping.
+ */
+export function stepFsm<Ctx>(
+ fsm: CompiledFsm,
+ run: FsmRunState,
+ ctx: Ctx,
+ bb: Blackboard,
+ registry: AiRegistry<Ctx>,
+): boolean {
+ const cur = fsm.states.get(run.current);
+ if (!cur) return false;
+
+ if (!run.entered) {
+ runAction(registry, cur.onEnter, ctx, bb);
+ run.entered = true;
+ }
+
+ for (const t of cur.transitions ?? []) {
+ if (transitionEnabled(t, ctx, bb, registry)) {
+ if (t.trigger) bb.consume(t.trigger);
+ runAction(registry, cur.onExit, ctx, bb);
+ run.previous = run.current;
+ run.current = t.to;
+ run.entered = false;
+ return true;
+ }
+ }
+
+ runAction(registry, cur.onUpdate, ctx, bb);
+ return false;
+}
+
+function transitionEnabled<Ctx>(
+ t: FsmTransition,
+ ctx: Ctx,
+ bb: Blackboard,
+ registry: AiRegistry<Ctx>,
+): boolean {
+ if (t.trigger && !bb.isFired(t.trigger)) return false;
+ if (t.condition) {
+ const cond = registry.getCondition(t.condition);
+ if (!cond || !cond(ctx, bb)) return false;
+ }
+ if (t.guard && !evalGuards(bb, t.guard)) return false;
+ return true;
+}
+
+function runAction<Ctx>(
+ registry: AiRegistry<Ctx>,
+ name: string | undefined,
+ ctx: Ctx,
+ bb: Blackboard,
+): void {
+ if (!name) return;
+ registry.getAction(name)?.(ctx, bb);
+}
diff --git a/sdk/src/ai/fsm/StateMachineAgent.ts b/sdk/src/ai/fsm/StateMachineAgent.ts
new file mode 100644
index 000000000..94840e0f8
--- /dev/null
+++ b/sdk/src/ai/fsm/StateMachineAgent.ts
@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file StateMachineAgent.ts
+ * @brief StateMachineAgent component + the compiled-FSM store.
+ *
+ * The component is the authorable half: which FSM to run (a registered name or a
+ * `.esfsm` asset key) plus the observable current state. Named `StateMachineAgent`
+ * to stay clear of the UI-owned `StateMachine` component.
+ */
+
+import { defineComponent } from '../../component';
+import type { FsmDefinition } from './types';
+import { compileFsm, type CompiledFsm } from './FsmRunner';
+
+export interface StateMachineAgentData {
+ /** Key of the FSM to run: a `registerFsm` name or a `.esfsm` asset path. */
+ fsm: string;
+ /** Active state name, written by the system each tick (observable in the inspector). */
+ current: string;
+}
+
+export const StateMachineAgent = defineComponent<StateMachineAgentData>('StateMachineAgent', {
+ fsm: '',
+ current: '',
+}, {
+ assetFields: [{ field: 'fsm', type: 'statemachine' }],
+ // Preload a `.esfsm` reference with the scene so the FSM is registered before
+ // the agent first ticks. A plain `registerFsm` name (code path) is left alone.
+ discoverAssets: data => {
+ const fsm = data.fsm;
+ return typeof fsm === 'string' && fsm.endsWith('.esfsm')
+ ? [{ type: 'statemachine', path: fsm }]
+ : [];
+ },
+ fields: {
+ current: { advanced: true, tooltip: 'Active state (runtime, read-only).' },
+ },
+});
+
+/** Compiled FSMs keyed by registration name or `.esfsm` asset path. */
+const fsmStore = new Map<string, CompiledFsm>();
+
+/** Register (compile) an FSM under `key`; code path and `.esfsm` loader share this store. */
+export function registerFsm(key: string, def: FsmDefinition): CompiledFsm {
+ const compiled = compileFsm(def);
+ fsmStore.set(key, compiled);
+ return compiled;
+}
+
+export function getFsm(key: string): CompiledFsm | undefined {
+ return fsmStore.get(key);
+}
+
+/** Drop all registered FSMs (tests / hot-reload). */
+export function clearFsmStore(): void {
+ fsmStore.clear();
+}
diff --git a/sdk/src/ai/fsm/fsmGraph.ts b/sdk/src/ai/fsm/fsmGraph.ts
new file mode 100644
index 000000000..9dc295065
--- /dev/null
+++ b/sdk/src/ai/fsm/fsmGraph.ts
@@ -0,0 +1,128 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file fsmGraph.ts
+ * @brief Immutable graph operations on an FsmDefinition — the editor's model.
+ *
+ * Pure functions returning new definitions (never mutating), so the transition-
+ * graph editor drives them through AssetDocument.edit for free undo, mirroring
+ * how the material editor calls the SDK's materialGraph ops. Since a `.esfsm`
+ * IS the runtime definition (states carry optional x/y layout the interpreter
+ * ignores), there is no separate editor model to compile.
+ */
+
+import type { FsmDefinition, FsmState, FsmTransition } from './types';
+
+/** A flattened transition edge, for the graph canvas. */
+export interface FsmEdge {
+ /** Stable id `from->to#index`. */
+ id: string;
+ from: string;
+ to: string;
+ /** Index of this transition within `from`'s transition list. */
+ index: number;
+ transition: FsmTransition;
+}
+
+/** Flatten every state's outgoing transitions into addressable edges. */
+export function fsmEdges(def: FsmDefinition): FsmEdge[] {
+ const edges: FsmEdge[] = [];
+ for (const s of def.states) {
+ (s.transitions ?? []).forEach((transition, index) => {
+ edges.push({ id: `${s.name}->${transition.to}#${index}`, from: s.name, to: transition.to, index, transition });
+ });
+ }
+ return edges;
+}
+
+/** A blank machine with one initial state. */
+export function emptyFsm(): FsmDefinition {
+ return { initial: 'Idle', states: [{ name: 'Idle', x: 80, y: 80 }] };
+}
+
+export function addState(def: FsmDefinition, name: string, x = 0, y = 0): FsmDefinition {
+ if (def.states.some(s => s.name === name)) return def;
+ const state: FsmState = { name, x, y };
+ return {
+ ...def,
+ states: [...def.states, state],
+ // The first state added to an empty machine becomes the initial one.
+ initial: def.states.length === 0 ? name : def.initial,
+ };
+}
+
+export function removeState(def: FsmDefinition, name: string): FsmDefinition {
+ const states = def.states
+ .filter(s => s.name !== name)
+ .map(s => (s.transitions?.some(t => t.to === name)
+ ? { ...s, transitions: s.transitions.filter(t => t.to !== name) }
+ : s));
+ const initial = def.initial === name ? (states[0]?.name ?? '') : def.initial;
+ return { ...def, states, initial };
+}
+
+export function moveState(def: FsmDefinition, name: string, x: number, y: number): FsmDefinition {
+ return { ...def, states: def.states.map(s => (s.name === name ? { ...s, x, y } : s)) };
+}
+
+/** Rename a state, rewiring `initial` and every transition that targets it. */
+export function renameState(def: FsmDefinition, oldName: string, newName: string): FsmDefinition {
+ if (oldName === newName || !newName) return def;
+ if (def.states.some(s => s.name === newName)) return def;
+ const states = def.states.map(s => {
+ let ns = s.name === oldName ? { ...s, name: newName } : s;
+ if (ns.transitions?.some(t => t.to === oldName)) {
+ ns = { ...ns, transitions: ns.transitions.map(t => (t.to === oldName ? { ...t, to: newName } : t)) };
+ }
+ return ns;
+ });
+ return { ...def, states, initial: def.initial === oldName ? newName : def.initial };
+}
+
+export function setStateHook(
+ def: FsmDefinition,
+ name: string,
+ hook: 'onEnter' | 'onUpdate' | 'onExit',
+ action: string,
+): FsmDefinition {
+ return {
+ ...def,
+ states: def.states.map(s => (s.name === name ? { ...s, [hook]: action || undefined } : s)),
+ };
+}
+
+export function setInitial(def: FsmDefinition, name: string): FsmDefinition {
+ return def.states.some(s => s.name === name) ? { ...def, initial: name } : def;
+}
+
+export function addTransition(def: FsmDefinition, from: string, to: string): FsmDefinition {
+ return {
+ ...def,
+ states: def.states.map(s => (s.name === from
+ ? { ...s, transitions: [...(s.transitions ?? []), { to }] }
+ : s)),
+ };
+}
+
+export function removeTransition(def: FsmDefinition, from: string, index: number): FsmDefinition {
+ return {
+ ...def,
+ states: def.states.map(s => (s.name === from && s.transitions
+ ? { ...s, transitions: s.transitions.filter((_, i) => i !== index) }
+ : s)),
+ };
+}
+
+export function updateTransition(
+ def: FsmDefinition,
+ from: string,
+ index: number,
+ patch: Partial<FsmTransition>,
+): FsmDefinition {
+ return {
+ ...def,
+ states: def.states.map(s => (s.name === from && s.transitions
+ ? { ...s, transitions: s.transitions.map((t, i) => (i === index ? { ...t, ...patch } : t)) }
+ : s)),
+ };
+}
diff --git a/sdk/src/ai/fsm/index.ts b/sdk/src/ai/fsm/index.ts
new file mode 100644
index 000000000..4865cd390
--- /dev/null
+++ b/sdk/src/ai/fsm/index.ts
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file index.ts
+ * @brief State-machine core barrel (pure runtime; engine binding is separate).
+ */
+
+export type {
+ CompareOp,
+ BlackboardGuard,
+ FsmTransition,
+ FsmState,
+ FsmDefinition,
+} from './types';
+export { Blackboard, evalGuard, evalGuards } from './Blackboard';
+export { AiRegistry, type AiAction, type AiCondition } from './registry';
+export {
+ compileFsm,
+ createFsmRunState,
+ stepFsm,
+ type CompiledFsm,
+ type FsmRunState,
+} from './FsmRunner';
+export {
+ fsmEdges,
+ emptyFsm,
+ addState,
+ removeState,
+ moveState,
+ renameState,
+ setStateHook,
+ setInitial,
+ addTransition,
+ removeTransition,
+ updateTransition,
+ type FsmEdge,
+} from './fsmGraph';
diff --git a/sdk/src/ai/fsm/registry.ts b/sdk/src/ai/fsm/registry.ts
new file mode 100644
index 000000000..ad8b62750
--- /dev/null
+++ b/sdk/src/ai/fsm/registry.ts
@@ -0,0 +1,61 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file registry.ts
+ * @brief AiRegistry — names → leaf action/condition functions.
+ *
+ * The binding between code-free AI data (`.esfsm`/`.esbt` referencing names) and
+ * real gameplay logic. Generic over the context type `Ctx` so the pure core
+ * stays wasm-free; the engine layer instantiates it with a concrete AiContext
+ * (a BehaviorContext superset) and exposes the `registerAction`/`registerCondition`
+ * free functions over a shared singleton.
+ */
+
+import type { Blackboard } from './Blackboard';
+
+export type AiAction<Ctx> = (ctx: Ctx, bb: Blackboard) => void;
+export type AiCondition<Ctx> = (ctx: Ctx, bb: Blackboard) => boolean;
+
+export class AiRegistry<Ctx = unknown> {
+ private actions = new Map<string, AiAction<Ctx>>();
+ private conditions = new Map<string, AiCondition<Ctx>>();
+
+ registerAction(name: string, fn: AiAction<Ctx>): void {
+ this.actions.set(name, fn);
+ }
+
+ registerCondition(name: string, fn: AiCondition<Ctx>): void {
+ this.conditions.set(name, fn);
+ }
+
+ getAction(name: string): AiAction<Ctx> | undefined {
+ return this.actions.get(name);
+ }
+
+ getCondition(name: string): AiCondition<Ctx> | undefined {
+ return this.conditions.get(name);
+ }
+
+ hasAction(name: string): boolean {
+ return this.actions.has(name);
+ }
+
+ hasCondition(name: string): boolean {
+ return this.conditions.has(name);
+ }
+
+ /** Registered action/condition names, for editor palettes. */
+ actionNames(): string[] {
+ return [...this.actions.keys()];
+ }
+
+ conditionNames(): string[] {
+ return [...this.conditions.keys()];
+ }
+
+ /** Drop all registrations (tests / hot-reload). */
+ clear(): void {
+ this.actions.clear();
+ this.conditions.clear();
+ }
+}
diff --git a/sdk/src/ai/fsm/types.ts b/sdk/src/ai/fsm/types.ts
new file mode 100644
index 000000000..84e37f559
--- /dev/null
+++ b/sdk/src/ai/fsm/types.ts
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file types.ts
+ * @brief State-machine data model — the serializable shape of a `.esfsm`.
+ *
+ * A definition is pure data: states carry named action hooks, transitions carry
+ * their enabling conditions (event trigger, named condition, and/or blackboard
+ * guards). Leaf logic (the action/condition names) is resolved at runtime via
+ * the AiRegistry, so the data never embeds code — matching how `.esbt` and the
+ * input maps stay code-free.
+ */
+
+export type CompareOp = '==' | '!=' | '<' | '<=' | '>' | '>=' | 'truthy' | 'falsy';
+
+/** A single blackboard comparison. `value` is unused for truthy/falsy. */
+export interface BlackboardGuard {
+ key: string;
+ op: CompareOp;
+ value?: number | string | boolean;
+}
+
+/**
+ * A directed edge to `to`. Enabled when ALL of its specified mechanisms hold:
+ * the `trigger` event is pending, the named `condition` returns true, and every
+ * `guard` compares true. A transition with none of them is unconditional.
+ */
+export interface FsmTransition {
+ to: string;
+ /** Event name (Unity-style trigger) that must be fired; consumed when taken. */
+ trigger?: string;
+ /** Named condition resolved from the registry. */
+ condition?: string;
+ /** Blackboard comparison(s), AND-combined. */
+ guard?: BlackboardGuard | BlackboardGuard[];
+}
+
+export interface FsmState {
+ name: string;
+ /** Named action run once when the state becomes active. */
+ onEnter?: string;
+ /** Named action run every tick the state is active (and no transition fired). */
+ onUpdate?: string;
+ /** Named action run once when the state is left. */
+ onExit?: string;
+ /** Outgoing edges, evaluated in order; the first enabled one is taken. */
+ transitions?: FsmTransition[];
+ /** Editor-only canvas position; ignored by the interpreter. */
+ x?: number;
+ y?: number;
+}
+
+export interface FsmDefinition {
+ /** Name of the state entered on start. */
+ initial: string;
+ states: FsmState[];
+}
diff --git a/sdk/src/ai/index.ts b/sdk/src/ai/index.ts
new file mode 100644
index 000000000..1357e98f2
--- /dev/null
+++ b/sdk/src/ai/index.ts
@@ -0,0 +1,35 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file index.ts
+ * @brief Gameplay AI layer barrel — navigation + state machines (behavior
+ * trees land here too; REARCH_GAMEPLAY_AI.md).
+ */
+
+export * from './nav';
+
+// State machines: pure core (types / Blackboard / registry / interpreter)…
+export * from './fsm';
+// …plus the engine binding (context, registry singleton, component, plugin).
+export {
+ aiRegistry,
+ registerAction,
+ registerCondition,
+ type AiContext,
+} from './fsm/AiContext';
+export {
+ StateMachineAgent,
+ registerFsm,
+ getFsm,
+ clearFsmStore,
+ type StateMachineAgentData,
+} from './fsm/StateMachineAgent';
+export {
+ FsmPlugin,
+ fsmPlugin,
+ StateMachines,
+ AiFsm,
+ stepStateMachines,
+ agentBlackboard,
+ type FsmWorldView,
+} from './fsm/FsmPlugin';
diff --git a/sdk/src/ai/nav/NavAgent.ts b/sdk/src/ai/nav/NavAgent.ts
new file mode 100644
index 000000000..3a1e80312
--- /dev/null
+++ b/sdk/src/ai/nav/NavAgent.ts
@@ -0,0 +1,82 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file NavAgent.ts
+ * @brief NavAgent component — the authorable, serializable half of a
+ * pathfinding actor (tuning knobs + destination).
+ *
+ * The transient runtime path is held by the driving system, not this component,
+ * mirroring how `defineBehavior` keeps per-entity runtime state in its system
+ * closure rather than in serialized data. Named `NavAgent` (not `Agent`) and
+ * with the `*Agent` suffix to stay clear of the UI-owned `StateMachine`.
+ */
+
+import { defineComponent } from '../../component';
+import type { World } from '../../world';
+import type { Entity, Vec2 } from '../../types';
+
+export interface NavAgentData {
+ /** Movement speed in world pixels per second. */
+ speed: number;
+ /** Agent radius in pixels (arrival tolerance + future collision size). */
+ radius: number;
+ /** Stop distance from the final goal, in pixels. */
+ arriveRadius: number;
+ /** Replan cadence in seconds while moving; 0 = replan only when the target changes. */
+ repathInterval: number;
+ /** Whether a destination is set. Cleared on arrival or `stopNavAgent`. */
+ hasTarget: boolean;
+ /** Destination in world pixels. */
+ targetX: number;
+ targetY: number;
+ /** Set true by the system the frame the agent reaches its goal. */
+ arrived: boolean;
+}
+
+export const NavAgent = defineComponent<NavAgentData>('NavAgent', {
+ speed: 120,
+ radius: 12,
+ arriveRadius: 6,
+ repathInterval: 0.5,
+ hasTarget: false,
+ targetX: 0,
+ targetY: 0,
+ arrived: false,
+}, {
+ fields: {
+ speed: { min: 0, unit: 'px/s', category: 'Navigation' },
+ radius: { min: 1, unit: 'px', category: 'Navigation' },
+ arriveRadius: { min: 0, unit: 'px', category: 'Navigation' },
+ repathInterval: {
+ min: 0, unit: 's', category: 'Navigation',
+ tooltip: 'Replan cadence while moving; 0 = only when the target changes.',
+ },
+ hasTarget: { category: 'Target' },
+ targetX: { unit: 'px', category: 'Target' },
+ targetY: { unit: 'px', category: 'Target' },
+ arrived: { category: 'Target', advanced: true },
+ },
+});
+
+/**
+ * Point a NavAgent at a world position and (re)arm it. Safe to call every frame
+ * (e.g. to chase a moving target) — the system only replans when the target
+ * actually moves or the repath timer elapses.
+ */
+export function setNavDestination(world: World, entity: Entity, target: Vec2): void {
+ if (!world.has(entity, NavAgent)) return;
+ const agent = world.get(entity, NavAgent);
+ agent.hasTarget = true;
+ agent.targetX = target.x;
+ agent.targetY = target.y;
+ agent.arrived = false;
+ world.set(entity, NavAgent, agent);
+}
+
+/** Clear a NavAgent's destination and stop it in place. */
+export function stopNavAgent(world: World, entity: Entity): void {
+ if (!world.has(entity, NavAgent)) return;
+ const agent = world.get(entity, NavAgent);
+ agent.hasTarget = false;
+ world.set(entity, NavAgent, agent);
+}
diff --git a/sdk/src/ai/nav/NavGrid.ts b/sdk/src/ai/nav/NavGrid.ts
new file mode 100644
index 000000000..2d40049f0
--- /dev/null
+++ b/sdk/src/ai/nav/NavGrid.ts
@@ -0,0 +1,116 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file NavGrid.ts
+ * @brief Uniform navigation grid — a walkability bitmap plus the affine map
+ * between grid cells and world pixels.
+ *
+ * Pure data + math, zero engine/wasm dependency, so the whole pathfinding core
+ * is unit-testable in isolation. The engine binding (build one from a tilemap
+ * layer) lives in navGridFromTilemap.ts; the A* search in pathfind.ts.
+ */
+
+import type { Vec2 } from '../../types';
+
+/** Integer grid coordinate. Kept distinct from {@link Vec2} to flag cell-space. */
+export interface Cell {
+ x: number;
+ y: number;
+}
+
+export interface NavGridOptions {
+ /** Cell columns. */
+ width: number;
+ /** Cell rows. */
+ height: number;
+ /** World pixels per cell (square). */
+ cellSize: number;
+ /** World position of cell (0,0)'s center. Defaults to origin. */
+ origin?: Vec2;
+ /**
+ * Walkability, row-major `width * height`, 1 = walkable / 0 = blocked.
+ * Defaults to fully walkable. Copied in, not retained.
+ */
+ walkable?: ArrayLike<number>;
+}
+
+/**
+ * A uniform-cost square grid with a walkability mask. `gy` increases with world
+ * +Y; a Y-down source (e.g. a tilemap) flips rows when it builds the grid, so
+ * NavGrid itself stays direction-agnostic.
+ */
+export class NavGrid {
+ readonly width: number;
+ readonly height: number;
+ readonly cellSize: number;
+ readonly originX: number;
+ readonly originY: number;
+ /** Row-major walkability, 1 = walkable. Mutable via {@link setWalkable}. */
+ readonly walkable: Uint8Array;
+
+ constructor(opts: NavGridOptions) {
+ this.width = opts.width;
+ this.height = opts.height;
+ this.cellSize = opts.cellSize;
+ this.originX = opts.origin?.x ?? 0;
+ this.originY = opts.origin?.y ?? 0;
+
+ const n = this.width * this.height;
+ this.walkable = new Uint8Array(n);
+ if (opts.walkable) {
+ this.walkable.set(opts.walkable as ArrayLike<number>, 0);
+ } else {
+ this.walkable.fill(1);
+ }
+ }
+
+ index(gx: number, gy: number): number {
+ return gy * this.width + gx;
+ }
+
+ inBounds(gx: number, gy: number): boolean {
+ return gx >= 0 && gy >= 0 && gx < this.width && gy < this.height;
+ }
+
+ isWalkable(gx: number, gy: number): boolean {
+ return this.inBounds(gx, gy) && this.walkable[gy * this.width + gx] === 1;
+ }
+
+ setWalkable(gx: number, gy: number, walkable: boolean): void {
+ if (this.inBounds(gx, gy)) this.walkable[gy * this.width + gx] = walkable ? 1 : 0;
+ }
+
+ /** Center of cell `(gx, gy)` in world pixels. */
+ cellToWorld(gx: number, gy: number): Vec2 {
+ return { x: this.originX + gx * this.cellSize, y: this.originY + gy * this.cellSize };
+ }
+
+ /** Cell containing world point `(wx, wy)`. May be out of bounds — caller checks. */
+ worldToCell(wx: number, wy: number): Cell {
+ return {
+ x: Math.round((wx - this.originX) / this.cellSize),
+ y: Math.round((wy - this.originY) / this.cellSize),
+ };
+ }
+
+ /**
+ * Nearest walkable cell to `(gx, gy)` by outward ring search, or null if the
+ * whole grid is blocked. Used to snap a start/goal that lands on a wall onto
+ * a usable cell before searching.
+ */
+ nearestWalkable(gx: number, gy: number, maxRadius = 8): Cell | null {
+ if (this.isWalkable(gx, gy)) return { x: gx, y: gy };
+ for (let r = 1; r <= maxRadius; r++) {
+ for (let dy = -r; dy <= r; dy++) {
+ for (let dx = -r; dx <= r; dx++) {
+ // Only the ring perimeter at radius r (interior already checked).
+ if (Math.max(Math.abs(dx), Math.abs(dy)) !== r) continue;
+ const cx = gx + dx;
+ const cy = gy + dy;
+ if (this.isWalkable(cx, cy)) return { x: cx, y: cy };
+ }
+ }
+ }
+ return null;
+ }
+}
diff --git a/sdk/src/ai/nav/NavPlugin.ts b/sdk/src/ai/nav/NavPlugin.ts
new file mode 100644
index 000000000..8b1ba9453
--- /dev/null
+++ b/sdk/src/ai/nav/NavPlugin.ts
@@ -0,0 +1,130 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file NavPlugin.ts
+ * @brief Drives NavAgents: plan-on-demand + kinematic path following.
+ *
+ * One system, gated to play mode. Per-entity runtime path lives in a closure
+ * Map (the `defineBehavior` pattern) so the NavAgent component stays purely
+ * authorable/serializable. The per-frame logic is `stepNavigation`, extracted
+ * so it unit-tests against a fake world. MVP integrates the Transform directly
+ * (kinematic); physics `moveCharacter` avoidance is a later stage
+ * (REARCH_GAMEPLAY_AI.md AI4) — the grid path already clears static blockers.
+ */
+
+import type { App, Plugin } from '../../app';
+import type { Entity } from '../../types';
+import { defineSystem, Schedule, GetWorld } from '../../system';
+import { Res, Time, type TimeData } from '../../resource';
+import {
+ Transform,
+ type AnyComponentDef,
+ type ComponentData,
+} from '../../component';
+import { playModeOnly } from '../../env';
+import { Navigation, Nav } from './Navigation';
+import { NavAgent } from './NavAgent';
+import { advanceAlongPath } from './follow';
+
+/** Per-entity runtime path state, owned by the driving system (not serialized). */
+export interface AgentRuntime {
+ waypoints: import('../../types').Vec2[];
+ index: number;
+ plannedX: number;
+ plannedY: number;
+ repathTimer: number;
+ reachable: boolean;
+}
+
+/** The slice of `World` the nav step needs — lets tests inject a fake. */
+export interface NavWorldView {
+ getEntitiesWithComponents(components: readonly AnyComponentDef[]): Entity[];
+ get<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C>;
+ set<C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentData<C>): void;
+}
+
+/**
+ * Advance every NavAgent one frame: (re)plan when the target moved or the
+ * repath timer elapsed, then follow the path kinematically. `runtimes` carries
+ * per-entity path state across frames.
+ */
+export function stepNavigation(
+ world: NavWorldView,
+ nav: Navigation,
+ dt: number,
+ runtimes: Map<Entity, AgentRuntime>,
+): void {
+ if (dt <= 0) return;
+
+ for (const entity of world.getEntitiesWithComponents([NavAgent, Transform])) {
+ const agent = world.get(entity, NavAgent);
+ if (!agent.hasTarget) {
+ runtimes.delete(entity);
+ continue;
+ }
+
+ const tf = world.get(entity, Transform);
+ let rt = runtimes.get(entity);
+
+ const targetMoved = !rt || rt.plannedX !== agent.targetX || rt.plannedY !== agent.targetY;
+ const timerElapsed = rt ? (rt.repathTimer -= dt) <= 0 : false;
+ if (!rt || targetMoved || (agent.repathInterval > 0 && timerElapsed)) {
+ const path = nav.findWorldPath(
+ { x: tf.position.x, y: tf.position.y },
+ { x: agent.targetX, y: agent.targetY },
+ );
+ rt = {
+ waypoints: path ?? [],
+ // Skip the start cell center to avoid backtracking toward it.
+ index: path && path.length > 1 ? 1 : 0,
+ plannedX: agent.targetX,
+ plannedY: agent.targetY,
+ repathTimer: agent.repathInterval,
+ reachable: path !== null,
+ };
+ runtimes.set(entity, rt);
+ }
+
+ // Keep an unreachable agent's runtime for throttled retry (next target
+ // change or repath timer) rather than churning it every frame.
+ if (!rt.reachable) continue;
+
+ const pos = { x: tf.position.x, y: tf.position.y };
+ rt.index = advanceAlongPath(pos, rt.waypoints, rt.index, agent.speed * dt);
+ tf.position.x = pos.x;
+ tf.position.y = pos.y;
+ world.set(entity, Transform, tf);
+
+ if (rt.index >= rt.waypoints.length) {
+ agent.arrived = true;
+ agent.hasTarget = false;
+ world.set(entity, NavAgent, agent);
+ runtimes.delete(entity);
+ }
+ }
+}
+
+export class NavPlugin implements Plugin {
+ name = 'nav';
+
+ build(app: App): void {
+ app.insertResource(Nav, new Navigation());
+
+ const runtimes = new Map<Entity, AgentRuntime>();
+ app.world.onDespawn((entity: Entity) => runtimes.delete(entity));
+
+ app.addSystemToSchedule(
+ Schedule.Update,
+ defineSystem(
+ [Res(Nav), Res(Time), GetWorld()],
+ (nav: Navigation, time: TimeData, world) => {
+ stepNavigation(world as NavWorldView, nav, time.delta, runtimes);
+ },
+ { name: 'NavAgentSystem' },
+ ),
+ { runIf: playModeOnly },
+ );
+ }
+}
+
+export const navPlugin = new NavPlugin();
diff --git a/sdk/src/ai/nav/Navigation.ts b/sdk/src/ai/nav/Navigation.ts
new file mode 100644
index 000000000..9d3e316e4
--- /dev/null
+++ b/sdk/src/ai/nav/Navigation.ts
@@ -0,0 +1,42 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Navigation.ts
+ * @brief `Nav` resource — holds the active NavGrid and world-space pathfinding.
+ *
+ * Published by NavPlugin; game code reads it as `Res(Nav)` (or
+ * `app.getResource(Nav)`) to swap the grid or query a path directly.
+ */
+
+import { defineResource } from '../../resource';
+import type { Vec2 } from '../../types';
+import { NavGrid } from './NavGrid';
+import { findPath, pathToWorld, type PathfindOptions } from './pathfind';
+
+export class Navigation {
+ /** The active navigation grid, or null until one is built and installed. */
+ grid: NavGrid | null = null;
+
+ setGrid(grid: NavGrid | null): void {
+ this.grid = grid;
+ }
+
+ hasGrid(): boolean {
+ return this.grid !== null;
+ }
+
+ /**
+ * Plan a world-space path (cell-center waypoints) between two world points,
+ * or null if there is no grid or no route.
+ */
+ findWorldPath(from: Vec2, to: Vec2, opts?: PathfindOptions): Vec2[] | null {
+ const grid = this.grid;
+ if (!grid) return null;
+ const start = grid.worldToCell(from.x, from.y);
+ const goal = grid.worldToCell(to.x, to.y);
+ const cells = findPath(grid, start, goal, opts);
+ return cells ? pathToWorld(grid, cells) : null;
+ }
+}
+
+export const Nav = defineResource<Navigation>(null!, 'Nav');
diff --git a/sdk/src/ai/nav/follow.ts b/sdk/src/ai/nav/follow.ts
new file mode 100644
index 000000000..dbb54e32f
--- /dev/null
+++ b/sdk/src/ai/nav/follow.ts
@@ -0,0 +1,46 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file follow.ts
+ * @brief Kinematic path following — pure, unit-testable movement integration.
+ */
+
+import type { Vec2 } from '../../types';
+
+/**
+ * Advance `pos` up to `distance` pixels along the waypoint chain starting at
+ * `startIndex`, snapping onto each reached waypoint so a single frame can cross
+ * several. Mutates `pos` in place. Returns the new waypoint index — a value
+ * `>= waypoints.length` means the end was reached.
+ */
+export function advanceAlongPath(
+ pos: Vec2,
+ waypoints: Vec2[],
+ startIndex: number,
+ distance: number,
+): number {
+ let index = startIndex;
+ let remaining = distance;
+ while (remaining > 0 && index < waypoints.length) {
+ const wp = waypoints[index];
+ const dx = wp.x - pos.x;
+ const dy = wp.y - pos.y;
+ const dist = Math.hypot(dx, dy);
+ if (dist === 0) {
+ // Already on this waypoint; step to the next without consuming budget.
+ index++;
+ continue;
+ }
+ if (dist <= remaining) {
+ pos.x = wp.x;
+ pos.y = wp.y;
+ remaining -= dist;
+ index++;
+ } else {
+ pos.x += (dx / dist) * remaining;
+ pos.y += (dy / dist) * remaining;
+ remaining = 0;
+ }
+ }
+ return index;
+}
diff --git a/sdk/src/ai/nav/index.ts b/sdk/src/ai/nav/index.ts
new file mode 100644
index 000000000..e271ae614
--- /dev/null
+++ b/sdk/src/ai/nav/index.ts
@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file index.ts
+ * @brief Navigation barrel — grid, A*, tilemap builder, agent, plugin.
+ */
+
+export { NavGrid, type NavGridOptions, type Cell } from './NavGrid';
+export { findPath, pathToWorld, type PathfindOptions } from './pathfind';
+export {
+ navGridFromTiles,
+ navGridFromTilemapLayer,
+ type BuildNavGridOptions,
+} from './navGridFromTilemap';
+export { Navigation, Nav } from './Navigation';
+export { NavAgent, type NavAgentData, setNavDestination, stopNavAgent } from './NavAgent';
+export { NavPlugin, navPlugin } from './NavPlugin';
diff --git a/sdk/src/ai/nav/navGridFromTilemap.ts b/sdk/src/ai/nav/navGridFromTilemap.ts
new file mode 100644
index 000000000..06f6424e5
--- /dev/null
+++ b/sdk/src/ai/nav/navGridFromTilemap.ts
@@ -0,0 +1,66 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file navGridFromTilemap.ts
+ * @brief Build a NavGrid from tilemap walkability.
+ *
+ * The core builder takes a raw `getTile(x,y)` reader so it stays wasm-free and
+ * unit-testable; the convenience wrapper reads a live tilemap layer through
+ * TilemapAPI. Cells are raw u16 (`tileId | flipBits`); the low 13 bits are the
+ * tile id, matching `mergeCollisionTiles`.
+ */
+
+import type { Entity, Vec2 } from '../../types';
+import { NavGrid } from './NavGrid';
+import { TilemapAPI } from '../../tilemap/tilemapAPI';
+
+/** Low 13 bits of a tilemap cell are the tile id; the top 3 are flip flags. */
+const TILE_ID_MASK = 0x1fff;
+
+export interface BuildNavGridOptions {
+ width: number;
+ height: number;
+ /** World pixels per cell. */
+ cellSize: number;
+ /** World position of cell (0,0)'s center. */
+ origin?: Vec2;
+ /** Exact set of tile ids that block movement. Ignored if `isBlocked` is given. */
+ blockedTileIds?: Iterable<number>;
+ /**
+ * Custom blocking predicate over the tile id (0 = empty). Overrides
+ * `blockedTileIds`. Default: with `blockedTileIds` set, only those block;
+ * otherwise any non-empty tile blocks (treats the layer as an obstacle map).
+ */
+ isBlocked?: (tileId: number) => boolean;
+}
+
+/** Build a NavGrid from a raw tile reader. `getTile(x,y)` returns a raw u16 cell. */
+export function navGridFromTiles(
+ getTile: (x: number, y: number) => number,
+ opts: BuildNavGridOptions,
+): NavGrid {
+ const { width, height } = opts;
+ const isBlocked = resolveBlocked(opts);
+ const walkable = new Uint8Array(width * height);
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const tileId = getTile(x, y) & TILE_ID_MASK;
+ walkable[y * width + x] = isBlocked(tileId) ? 0 : 1;
+ }
+ }
+ return new NavGrid({ width, height, cellSize: opts.cellSize, origin: opts.origin, walkable });
+}
+
+/** Build a NavGrid from a live tilemap layer entity via TilemapAPI. */
+export function navGridFromTilemapLayer(entity: Entity, opts: BuildNavGridOptions): NavGrid {
+ return navGridFromTiles((x, y) => TilemapAPI.getTile(entity, x, y), opts);
+}
+
+function resolveBlocked(opts: BuildNavGridOptions): (tileId: number) => boolean {
+ if (opts.isBlocked) return opts.isBlocked;
+ if (opts.blockedTileIds) {
+ const set = new Set<number>(opts.blockedTileIds);
+ return tileId => set.has(tileId);
+ }
+ return tileId => tileId !== 0;
+}
diff --git a/sdk/src/ai/nav/pathfind.ts b/sdk/src/ai/nav/pathfind.ts
new file mode 100644
index 000000000..17dffc389
--- /dev/null
+++ b/sdk/src/ai/nav/pathfind.ts
@@ -0,0 +1,192 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file pathfind.ts
+ * @brief A* over a {@link NavGrid} — pure, allocation-lean, unit-testable.
+ *
+ * Uniform-cost 4- or 8-connected search with a binary min-heap open set and
+ * octile/manhattan heuristics. Diagonal steps never cut corners (both shared
+ * orthogonal neighbours must be walkable), so an agent following the path can't
+ * clip a wall corner.
+ */
+
+import type { NavGrid, Cell } from './NavGrid';
+import type { Vec2 } from '../../types';
+
+export interface PathfindOptions {
+ /** Allow 8-connected diagonal moves. Default true. */
+ diagonal?: boolean;
+ /**
+ * When start/goal lands on a blocked cell, snap to the nearest walkable one
+ * within this ring radius before searching. 0 disables snapping. Default 8.
+ */
+ snapRadius?: number;
+}
+
+const SQRT2 = Math.SQRT2;
+
+// Neighbour offsets: first 4 orthogonal, last 4 diagonal. Diagonals are gated on
+// their two shared orthogonal cells to forbid corner-cutting.
+const ORTHO: ReadonlyArray<readonly [number, number]> = [
+ [1, 0], [-1, 0], [0, 1], [0, -1],
+];
+const DIAG: ReadonlyArray<readonly [number, number]> = [
+ [1, 1], [1, -1], [-1, 1], [-1, -1],
+];
+
+/**
+ * Find a grid path from `start` to `goal`, inclusive of both endpoints.
+ * Returns null if unreachable (or if either endpoint can't be snapped to a
+ * walkable cell). A start equal to goal yields a single-cell path.
+ */
+export function findPath(
+ grid: NavGrid,
+ start: Cell,
+ goal: Cell,
+ opts: PathfindOptions = {},
+): Cell[] | null {
+ const diagonal = opts.diagonal ?? true;
+ const snapRadius = opts.snapRadius ?? 8;
+
+ const s = resolveEndpoint(grid, start, snapRadius);
+ const g = resolveEndpoint(grid, goal, snapRadius);
+ if (!s || !g) return null;
+
+ const { width, height } = grid;
+ const n = width * height;
+ const startIdx = s.y * width + s.x;
+ const goalIdx = g.y * width + g.x;
+ if (startIdx === goalIdx) return [{ x: s.x, y: s.y }];
+
+ const gScore = new Float64Array(n).fill(Infinity);
+ const cameFrom = new Int32Array(n).fill(-1);
+ const closed = new Uint8Array(n);
+ gScore[startIdx] = 0;
+
+ const heap = new MinHeap(n);
+ heap.push(startIdx, heuristic(s.x, s.y, g.x, g.y, diagonal));
+
+ while (heap.size > 0) {
+ const current = heap.pop();
+ if (current === goalIdx) return reconstruct(cameFrom, current, width);
+ if (closed[current]) continue;
+ closed[current] = 1;
+
+ const cx = current % width;
+ const cy = (current - cx) / width;
+ const baseG = gScore[current];
+
+ for (let i = 0; i < (diagonal ? 8 : 4); i++) {
+ const [dx, dy] = i < 4 ? ORTHO[i] : DIAG[i - 4];
+ const nx = cx + dx;
+ const ny = cy + dy;
+ if (!grid.isWalkable(nx, ny)) continue;
+ // No corner-cutting: a diagonal needs both shared orthogonals open.
+ if (i >= 4 && (!grid.isWalkable(cx + dx, cy) || !grid.isWalkable(cx, cy + dy))) continue;
+
+ const nIdx = ny * width + nx;
+ if (closed[nIdx]) continue;
+
+ const step = i < 4 ? 1 : SQRT2;
+ const tentative = baseG + step;
+ if (tentative < gScore[nIdx]) {
+ gScore[nIdx] = tentative;
+ cameFrom[nIdx] = current;
+ heap.push(nIdx, tentative + heuristic(nx, ny, g.x, g.y, diagonal));
+ }
+ }
+ }
+
+ return null;
+}
+
+/** Convert a cell path to world-space waypoints (cell centers). */
+export function pathToWorld(grid: NavGrid, path: Cell[]): Vec2[] {
+ return path.map(c => grid.cellToWorld(c.x, c.y));
+}
+
+function resolveEndpoint(grid: NavGrid, c: Cell, snapRadius: number): Cell | null {
+ if (grid.isWalkable(c.x, c.y)) return c;
+ if (snapRadius <= 0) return null;
+ return grid.nearestWalkable(c.x, c.y, snapRadius);
+}
+
+function heuristic(ax: number, ay: number, bx: number, by: number, diagonal: boolean): number {
+ const dx = Math.abs(ax - bx);
+ const dy = Math.abs(ay - by);
+ // Octile for 8-connected (admissible & consistent), manhattan for 4-connected.
+ return diagonal ? (dx + dy) + (SQRT2 - 2) * Math.min(dx, dy) : dx + dy;
+}
+
+function reconstruct(cameFrom: Int32Array, goalIdx: number, width: number): Cell[] {
+ const path: Cell[] = [];
+ let node = goalIdx;
+ while (node !== -1) {
+ const x = node % width;
+ path.push({ x, y: (node - x) / width });
+ node = cameFrom[node];
+ }
+ path.reverse();
+ return path;
+}
+
+/**
+ * Binary min-heap of cell indices keyed by an f-score, backed by flat typed
+ * arrays. Lazy-deletion friendly: a cell may be pushed more than once with a
+ * lower key; the search skips already-closed pops.
+ */
+class MinHeap {
+ private nodes: Int32Array;
+ private keys: Float64Array;
+ size = 0;
+
+ constructor(capacityHint: number) {
+ const cap = Math.max(16, capacityHint);
+ this.nodes = new Int32Array(cap);
+ this.keys = new Float64Array(cap);
+ }
+
+ push(node: number, key: number): void {
+ if (this.size === this.nodes.length) this.grow();
+ let i = this.size++;
+ this.nodes[i] = node;
+ this.keys[i] = key;
+ while (i > 0) {
+ const parent = (i - 1) >> 1;
+ if (this.keys[parent] <= this.keys[i]) break;
+ this.swap(i, parent);
+ i = parent;
+ }
+ }
+
+ pop(): number {
+ const top = this.nodes[0];
+ const last = --this.size;
+ this.nodes[0] = this.nodes[last];
+ this.keys[0] = this.keys[last];
+ let i = 0;
+ for (;;) {
+ const l = i * 2 + 1;
+ const r = l + 1;
+ let smallest = i;
+ if (l < this.size && this.keys[l] < this.keys[smallest]) smallest = l;
+ if (r < this.size && this.keys[r] < this.keys[smallest]) smallest = r;
+ if (smallest === i) break;
+ this.swap(i, smallest);
+ i = smallest;
+ }
+ return top;
+ }
+
+ private swap(a: number, b: number): void {
+ const tn = this.nodes[a]; this.nodes[a] = this.nodes[b]; this.nodes[b] = tn;
+ const tk = this.keys[a]; this.keys[a] = this.keys[b]; this.keys[b] = tk;
+ }
+
+ private grow(): void {
+ const nn = new Int32Array(this.nodes.length * 2);
+ const nk = new Float64Array(this.keys.length * 2);
+ nn.set(this.nodes); nk.set(this.keys);
+ this.nodes = nn; this.keys = nk;
+ }
+}
diff --git a/sdk/src/asset/AssetFieldRegistry.ts b/sdk/src/asset/AssetFieldRegistry.ts
index da91fd4d2..0a5562246 100644
--- a/sdk/src/asset/AssetFieldRegistry.ts
+++ b/sdk/src/asset/AssetFieldRegistry.ts
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-export type AssetFieldType = 'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'tilemap' | 'tileset' | 'timeline';
+export type AssetFieldType = 'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine';
export interface AssetFieldDescriptor {
field: string;
diff --git a/sdk/src/asset/AssetLoader.ts b/sdk/src/asset/AssetLoader.ts
index 3e1873cb4..961639ea2 100644
--- a/sdk/src/asset/AssetLoader.ts
+++ b/sdk/src/asset/AssetLoader.ts
@@ -50,6 +50,10 @@ export interface TimelineResult {
timelineId: string;
}
+export interface FsmResult {
+ fsmId: string;
+}
+
export interface PrefabResult {
data: unknown;
}
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index 5f6c13bf6..4f0e658fc 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -24,6 +24,7 @@ import { TilemapAssetLoader } from './loaders/TilemapAssetLoader';
import { TilesetAssetLoader } from './loaders/TilesetAssetLoader';
import { TimelineAssetLoader } from './loaders/TimelineAssetLoader';
import { PrefabAssetLoader } from './loaders/PrefabAssetLoader';
+import { FsmAssetLoader } from './loaders/FsmAssetLoader';
import type { SpineModuleController } from '../spine/SpineController';
import { getAssetFields } from './AssetFieldRegistry';
import { getComponentDefaults } from '../component';
@@ -878,6 +879,7 @@ export class Assets {
this.register(new TilesetAssetLoader());
this.register(new TimelineAssetLoader());
this.register(new PrefabAssetLoader());
+ this.register(new FsmAssetLoader());
}
private textureCacheKey_(path: string, flip: boolean): string {
diff --git a/sdk/src/asset/loaders/FsmAssetLoader.ts b/sdk/src/asset/loaders/FsmAssetLoader.ts
new file mode 100644
index 000000000..13bccef80
--- /dev/null
+++ b/sdk/src/asset/loaders/FsmAssetLoader.ts
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file FsmAssetLoader.ts
+ * @brief Loads a `.esfsm` and registers it under its path in the FSM store,
+ * so a StateMachineAgent whose `fsm` is that path resolves at runtime.
+ *
+ * The `.esfsm` payload IS a runtime FsmDefinition (plus optional editor-only
+ * layout on each state, which the interpreter ignores) — no compile step.
+ */
+
+import type { AssetLoader, LoadContext, FsmResult } from '../AssetLoader';
+import { registerFsm } from '../../ai/fsm/StateMachineAgent';
+import type { FsmDefinition } from '../../ai/fsm/types';
+
+export class FsmAssetLoader implements AssetLoader<FsmResult> {
+ readonly type = 'statemachine';
+ readonly extensions = ['.esfsm'];
+
+ async load(path: string, ctx: LoadContext): Promise<FsmResult> {
+ const buildPath = ctx.catalog.getBuildPath(path);
+ const text = await ctx.loadText(buildPath);
+ const def = JSON.parse(text) as FsmDefinition;
+ registerFsm(path, def);
+ return { fsmId: path };
+ }
+
+ unload(): void {
+ // FSMs are registered globally in the shared store.
+ }
+}
diff --git a/sdk/src/assetTypes.ts b/sdk/src/assetTypes.ts
index d0cc900a8..79a789fac 100644
--- a/sdk/src/assetTypes.ts
+++ b/sdk/src/assetTypes.ts
@@ -45,6 +45,8 @@ const ASSET_TYPE_REGISTRY: readonly AssetTypeEntry[] = [
{ extensions: ['esanim'], contentType: 'json', editorType: 'anim-clip', addressableType: null, wechatPackInclude: true, hasTransitiveDeps: true },
{ extensions: ['tmj'], contentType: 'json', editorType: 'tilemap', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: true },
{ extensions: ['estimeline'], contentType: 'json', editorType: 'timeline', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: true },
+ // State machine (registerFsm / FsmAssetLoader) — data-driven FSM definition.
+ { extensions: ['esfsm'], contentType: 'json', editorType: 'json', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: false },
];
const MIME_MAP: Record<string, string> = {
@@ -70,6 +72,7 @@ const MIME_MAP: Record<string, string> = {
esprefab: 'application/json',
esanim: 'application/json',
estimeline: 'application/json',
+ esfsm: 'application/json',
bmfont: 'application/json',
fnt: 'text/plain',
};
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 87b7281e1..740e50685 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -394,3 +394,76 @@ export type {
CollisionHitEvent,
SensorEvent,
} from './physics';
+
+// =============================================================================
+// AI — Navigation (grid A* today; state machines / behavior trees to come)
+// =============================================================================
+
+export {
+ NavGrid,
+ findPath,
+ pathToWorld,
+ navGridFromTiles,
+ navGridFromTilemapLayer,
+ Navigation,
+ Nav,
+ NavAgent,
+ setNavDestination,
+ stopNavAgent,
+ NavPlugin,
+ navPlugin,
+ type NavGridOptions,
+ type Cell,
+ type PathfindOptions,
+ type BuildNavGridOptions,
+ type NavAgentData,
+} from './ai';
+
+// =============================================================================
+// AI — State machines (pure-TS interpreter, .esfsm data + named registry)
+// =============================================================================
+
+export {
+ Blackboard,
+ evalGuard,
+ evalGuards,
+ AiRegistry,
+ compileFsm,
+ createFsmRunState,
+ stepFsm,
+ aiRegistry,
+ registerAction,
+ registerCondition,
+ StateMachineAgent,
+ registerFsm,
+ getFsm,
+ clearFsmStore,
+ FsmPlugin,
+ fsmPlugin,
+ StateMachines,
+ AiFsm,
+ agentBlackboard,
+ fsmEdges,
+ emptyFsm,
+ addState,
+ removeState,
+ moveState,
+ renameState,
+ setStateHook,
+ setInitial,
+ addTransition,
+ removeTransition,
+ updateTransition,
+ type FsmEdge,
+ type CompareOp,
+ type BlackboardGuard,
+ type FsmTransition,
+ type FsmState,
+ type FsmDefinition,
+ type CompiledFsm,
+ type FsmRunState,
+ type AiAction,
+ type AiCondition,
+ type AiContext,
+ type StateMachineAgentData,
+} from './ai';
diff --git a/sdk/src/scene.ts b/sdk/src/scene.ts
index 56f3e9f98..702dea53d 100644
--- a/sdk/src/scene.ts
+++ b/sdk/src/scene.ts
@@ -105,7 +105,7 @@ export class MissingAssetsError extends Error {
// Asset Field Types
// =============================================================================
-export type AssetFieldType = 'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'tilemap' | 'tileset' | 'timeline';
+export type AssetFieldType = 'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine';
// =============================================================================
// Component Query Helpers (read from self-describing ComponentDef)
diff --git a/sdk/src/webAppFactory.ts b/sdk/src/webAppFactory.ts
index e2b6460c6..78221417e 100644
--- a/sdk/src/webAppFactory.ts
+++ b/sdk/src/webAppFactory.ts
@@ -12,6 +12,7 @@ import { postProcessPlugin } from './postprocess';
import { timelinePlugin } from './timeline';
import { timerPlugin } from './timer';
import { lifecyclePlugin } from './lifecycle';
+import { navPlugin, fsmPlugin } from './ai';
import { SpinePlugin } from './spine';
import { createFetchSideModuleHost, type SideModuleHost } from './sideModules';
@@ -57,7 +58,7 @@ export interface CreateWebAppOptions extends WebAppOptions {
wasmBaseUrl?: string;
}
-const basePlugins = [timerPlugin, lifecyclePlugin(), animationPlugin, audioPlugin, particlePlugin, tilemapPlugin, postProcessPlugin, timelinePlugin];
+const basePlugins = [timerPlugin, lifecyclePlugin(), animationPlugin, audioPlugin, particlePlugin, tilemapPlugin, postProcessPlugin, timelinePlugin, fsmPlugin, navPlugin];
export function createWebApp(module: ESEngineModule, options?: CreateWebAppOptions): App {
const sideModules: SideModuleHost | undefined = options?.sideModules
diff --git a/sdk/tests/ai-enemy-integration.test.ts b/sdk/tests/ai-enemy-integration.test.ts
new file mode 100644
index 000000000..f08895dbc
--- /dev/null
+++ b/sdk/tests/ai-enemy-integration.test.ts
@@ -0,0 +1,153 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ai-enemy-integration.test.ts
+ * @brief Cross-layer AI integration: an FSM whose Chase action retargets a
+ * NavAgent, driven end-to-end through the real step functions. Exercises
+ * the AI1 (nav) + AI2 (fsm) seam that unit tests cover only in isolation.
+ */
+import { describe, it, expect, beforeEach } from 'vitest';
+import { Transform } from '../src/component';
+import type { Entity } from '../src/types';
+import type { CommandsInstance } from '../src/commands';
+import type { AnyComponentDef, ComponentData } from '../src/component';
+import { NavGrid } from '../src/ai/nav/NavGrid';
+import { Navigation } from '../src/ai/nav/Navigation';
+import { NavAgent, setNavDestination } from '../src/ai/nav/NavAgent';
+import { stepNavigation, type AgentRuntime } from '../src/ai/nav/NavPlugin';
+import { StateMachineAgent, registerFsm, clearFsmStore } from '../src/ai/fsm/StateMachineAgent';
+import { aiRegistry, registerAction } from '../src/ai/fsm/AiContext';
+import { stepStateMachines, agentBlackboard } from '../src/ai/fsm/FsmPlugin';
+
+const NO_COMMANDS = {} as CommandsInstance;
+
+/** In-memory world with real component-set filtering, shared by both AI systems. */
+class FakeWorld {
+ private store = new Map<string, unknown>();
+ private next = 1;
+ private ids: Entity[] = [];
+
+ spawn(comps: Array<[AnyComponentDef, unknown]>): Entity {
+ const e = this.next++ as Entity;
+ for (const [def, data] of comps) this.store.set(`${e}:${def._name}`, data);
+ this.ids.push(e);
+ return e;
+ }
+ getEntitiesWithComponents(defs: readonly AnyComponentDef[]): Entity[] {
+ return this.ids.filter(e => defs.every(d => this.store.has(`${e}:${d._name}`)));
+ }
+ get<C extends AnyComponentDef>(e: Entity, def: C): ComponentData<C> {
+ return this.store.get(`${e}:${def._name}`) as ComponentData<C>;
+ }
+ set<C extends AnyComponentDef>(e: Entity, def: C, data: ComponentData<C>): void {
+ this.store.set(`${e}:${def._name}`, data);
+ }
+ has(e: Entity, def: AnyComponentDef): boolean {
+ return this.store.has(`${e}:${def._name}`);
+ }
+}
+
+const tf = (x: number, y: number) => ({ position: { x, y, z: 0 } });
+
+describe('enemy AI (FSM + navigation)', () => {
+ beforeEach(() => {
+ aiRegistry.clear();
+ clearFsmStore();
+ });
+
+ it('patrols while the player is far, then chases via the nav agent when sensed', () => {
+ const world = new FakeWorld();
+ const nav = new Navigation();
+ nav.setGrid(new NavGrid({ width: 40, height: 40, cellSize: 20 })); // open 800x800 grid
+ const fsmStates = new Map();
+ const navRuntimes = new Map<Entity, AgentRuntime>();
+
+ const enemy = world.spawn([
+ [StateMachineAgent, StateMachineAgent.create({ fsm: 'enemy' })],
+ [NavAgent, NavAgent.create({ speed: 200, repathInterval: 0 })],
+ [Transform, tf(100, 100)],
+ ]);
+ const player = world.spawn([[Transform, tf(600, 100)]]);
+
+ // Chase = point the nav agent at the player's current position each tick.
+ registerAction('chase', ctx => {
+ const p = world.get(player, Transform);
+ setNavDestination(ctx.world, ctx.entity, { x: p.position.x, y: p.position.y });
+ });
+ registerAction('patrol', () => { /* hold position */ });
+
+ registerFsm('enemy', {
+ initial: 'Patrol',
+ states: [
+ { name: 'Patrol', onUpdate: 'patrol', transitions: [{ to: 'Chase', guard: { key: 'seesPlayer', op: 'truthy' } }] },
+ { name: 'Chase', onUpdate: 'chase', transitions: [{ to: 'Patrol', guard: { key: 'seesPlayer', op: 'falsy' } }] },
+ ],
+ });
+
+ const SENSE_RANGE = 120;
+ const dt = 1 / 60;
+ const frame = () => {
+ // Perception: write the blackboard the FSM guard reads.
+ const e = world.get(enemy, Transform);
+ const p = world.get(player, Transform);
+ const dist = Math.hypot(p.position.x - e.position.x, p.position.y - e.position.y);
+ agentBlackboard(fsmStates, enemy).set('seesPlayer', dist < SENSE_RANGE);
+ stepStateMachines(world, NO_COMMANDS, dt, fsmStates);
+ stepNavigation(world, nav, dt, navRuntimes);
+ };
+
+ // Player far → patrol, enemy stays put.
+ for (let i = 0; i < 30; i++) frame();
+ expect(world.get(enemy, StateMachineAgent).current).toBe('Patrol');
+ expect(world.get(enemy, Transform).position).toMatchObject({ x: 100, y: 100 });
+
+ // Player walks into sensing range.
+ world.set(player, Transform, tf(190, 100));
+ const startX = world.get(enemy, Transform).position.x;
+ for (let i = 0; i < 60; i++) frame();
+
+ // Enemy switched to Chase and the nav agent carried it toward the player.
+ expect(world.get(enemy, StateMachineAgent).current).toBe('Chase');
+ const endX = world.get(enemy, Transform).position.x;
+ expect(endX).toBeGreaterThan(startX + 20); // moved toward the player
+ // Arrived near the player — the goal snaps to the nearest cell center
+ // (round(190/20)=10 → world 200), so it lands within a cell of the player.
+ expect(Math.abs(endX - 190)).toBeLessThan(35);
+ expect(world.get(enemy, Transform).position.y).toBeCloseTo(100, 0);
+ });
+
+ it('breaks off the chase and returns to patrol when the player escapes', () => {
+ const world = new FakeWorld();
+ const nav = new Navigation();
+ nav.setGrid(new NavGrid({ width: 40, height: 40, cellSize: 20 }));
+ const fsmStates = new Map();
+ const navRuntimes = new Map<Entity, AgentRuntime>();
+
+ const enemy = world.spawn([
+ [StateMachineAgent, StateMachineAgent.create({ fsm: 'enemy' })],
+ [NavAgent, NavAgent.create({ speed: 150, repathInterval: 0 })],
+ [Transform, tf(100, 100)],
+ ]);
+ world.spawn([[Transform, tf(0, 0)]]);
+
+ registerAction('chase', () => { /* not needed for this assertion */ });
+ registerFsm('enemy', {
+ initial: 'Patrol',
+ states: [
+ { name: 'Patrol', transitions: [{ to: 'Chase', guard: { key: 'seesPlayer', op: 'truthy' } }] },
+ { name: 'Chase', onUpdate: 'chase', transitions: [{ to: 'Patrol', guard: { key: 'seesPlayer', op: 'falsy' } }] },
+ ],
+ });
+
+ const dt = 1 / 60;
+ const setSeen = (v: boolean) => agentBlackboard(fsmStates, enemy).set('seesPlayer', v);
+
+ setSeen(true);
+ stepStateMachines(world, NO_COMMANDS, dt, fsmStates); // → Chase
+ expect(world.get(enemy, StateMachineAgent).current).toBe('Chase');
+
+ setSeen(false);
+ stepStateMachines(world, NO_COMMANDS, dt, fsmStates); // → Patrol
+ expect(world.get(enemy, StateMachineAgent).current).toBe('Patrol');
+ });
+});
diff --git a/sdk/tests/fsm-agent.test.ts b/sdk/tests/fsm-agent.test.ts
new file mode 100644
index 000000000..46db4f606
--- /dev/null
+++ b/sdk/tests/fsm-agent.test.ts
@@ -0,0 +1,141 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect, beforeEach } from 'vitest';
+import type { Entity } from '../src/types';
+import type { CommandsInstance } from '../src/commands';
+import { StateMachineAgent, registerFsm, clearFsmStore } from '../src/ai/fsm/StateMachineAgent';
+import { aiRegistry, registerAction } from '../src/ai/fsm/AiContext';
+import {
+ stepStateMachines,
+ agentBlackboard,
+ StateMachines,
+ type FsmWorldView,
+} from '../src/ai/fsm/FsmPlugin';
+import type { FsmDefinition } from '../src/ai/fsm/types';
+
+/** Minimal in-memory world satisfying what stepStateMachines calls. */
+class FakeWorld implements FsmWorldView {
+ private store = new Map<string, unknown>();
+ private next = 1;
+ private entities: Entity[] = [];
+
+ spawn(fsm: string): Entity {
+ const e = this.next++ as Entity;
+ this.store.set(`${e}:StateMachineAgent`, StateMachineAgent.create({ fsm }));
+ this.entities.push(e);
+ return e;
+ }
+ getEntitiesWithComponents(): Entity[] {
+ return this.entities;
+ }
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ get(entity: Entity, component: { _name: string }): any {
+ return this.store.get(`${entity}:${component._name}`);
+ }
+ set(entity: Entity, component: { _name: string }, data: unknown): void {
+ this.store.set(`${entity}:${component._name}`, data);
+ }
+ has(entity: Entity, component: { _name: string }): boolean {
+ return this.store.has(`${entity}:${component._name}`);
+ }
+}
+
+const NO_COMMANDS = {} as CommandsInstance;
+
+const patrolChase: FsmDefinition = {
+ initial: 'Patrol',
+ states: [
+ { name: 'Patrol', onUpdate: 'patrolMove', transitions: [{ to: 'Chase', guard: { key: 'seesPlayer', op: 'truthy' } }] },
+ { name: 'Chase', onEnter: 'startChase', onUpdate: 'chaseMove', transitions: [{ to: 'Patrol', guard: { key: 'seesPlayer', op: 'falsy' } }] },
+ ],
+};
+
+describe('stepStateMachines', () => {
+ let log: string[];
+ beforeEach(() => {
+ aiRegistry.clear();
+ clearFsmStore();
+ log = [];
+ for (const n of ['patrolMove', 'startChase', 'chaseMove']) {
+ registerAction(n, ctx => log.push(`${n}:${ctx.entity}`));
+ }
+ });
+
+ it('runs an agent FSM and writes the active state back to the component', () => {
+ registerFsm('pc', patrolChase);
+ const world = new FakeWorld();
+ const states = new Map();
+ const e = world.spawn('pc');
+
+ stepStateMachines(world, NO_COMMANDS, 0.1, states);
+ expect(world.get(e, StateMachineAgent).current).toBe('Patrol');
+ expect(log).toEqual([`patrolMove:${e}`]);
+
+ agentBlackboard(states, e).set('seesPlayer', true);
+ stepStateMachines(world, NO_COMMANDS, 0.1, states); // → Chase
+ expect(world.get(e, StateMachineAgent).current).toBe('Chase');
+
+ stepStateMachines(world, NO_COMMANDS, 0.1, states); // Chase onEnter + onUpdate
+ expect(log).toEqual([`patrolMove:${e}`, `startChase:${e}`, `chaseMove:${e}`]);
+
+ agentBlackboard(states, e).set('seesPlayer', false);
+ stepStateMachines(world, NO_COMMANDS, 0.1, states); // → Patrol
+ expect(world.get(e, StateMachineAgent).current).toBe('Patrol');
+ });
+
+ it('is a no-op when the FSM key is unregistered', () => {
+ const world = new FakeWorld();
+ const states = new Map();
+ const e = world.spawn('missing');
+ stepStateMachines(world, NO_COMMANDS, 0.1, states);
+ expect(world.get(e, StateMachineAgent).current).toBe(''); // untouched
+ });
+
+ it('exposes entity/get/has on the leaf context', () => {
+ registerFsm('probe', {
+ initial: 'S',
+ states: [{ name: 'S', onUpdate: 'probe' }],
+ });
+ let seen: { entity: Entity; hasAgent: boolean; fsm: string } | null = null;
+ registerAction('probe', ctx => {
+ seen = {
+ entity: ctx.entity,
+ hasAgent: ctx.has(StateMachineAgent),
+ fsm: ctx.get(StateMachineAgent).fsm,
+ };
+ });
+ const world = new FakeWorld();
+ const states = new Map();
+ const e = world.spawn('probe');
+ stepStateMachines(world, NO_COMMANDS, 0.1, states);
+ expect(seen).toEqual({ entity: e, hasAgent: true, fsm: 'probe' });
+ });
+});
+
+describe('StateMachines resource', () => {
+ beforeEach(() => {
+ aiRegistry.clear();
+ clearFsmStore();
+ });
+
+ it('fires triggers that drive a transition and reports the current state', () => {
+ registerFsm('gate', {
+ initial: 'Closed',
+ states: [
+ { name: 'Closed', transitions: [{ to: 'Open', trigger: 'open' }] },
+ { name: 'Open' },
+ ],
+ });
+ const world = new FakeWorld();
+ const states = new Map();
+ const res = new StateMachines(states);
+ const e = world.spawn('gate');
+
+ stepStateMachines(world, NO_COMMANDS, 0.1, states);
+ expect(res.state(e)).toBe('Closed');
+
+ res.fire(e, 'open');
+ stepStateMachines(world, NO_COMMANDS, 0.1, states);
+ expect(res.state(e)).toBe('Open');
+ });
+});
diff --git a/sdk/tests/fsm-graph.test.ts b/sdk/tests/fsm-graph.test.ts
new file mode 100644
index 000000000..5a624c7e1
--- /dev/null
+++ b/sdk/tests/fsm-graph.test.ts
@@ -0,0 +1,108 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import {
+ emptyFsm,
+ addState,
+ removeState,
+ moveState,
+ renameState,
+ setStateHook,
+ setInitial,
+ addTransition,
+ removeTransition,
+ updateTransition,
+ fsmEdges,
+} from '../src/ai/fsm/fsmGraph';
+import type { FsmDefinition } from '../src/ai/fsm/types';
+
+describe('fsmGraph', () => {
+ it('creates a blank machine with one initial state', () => {
+ const def = emptyFsm();
+ expect(def.initial).toBe('Idle');
+ expect(def.states).toHaveLength(1);
+ });
+
+ it('adds states without mutating the input and ignores duplicates', () => {
+ const a = emptyFsm();
+ const b = addState(a, 'Chase', 200, 40);
+ expect(a.states).toHaveLength(1); // input untouched
+ expect(b.states.map(s => s.name)).toEqual(['Idle', 'Chase']);
+ expect(addState(b, 'Chase')).toBe(b); // duplicate → same ref
+ });
+
+ it('first state added to an empty machine becomes initial', () => {
+ const empty: FsmDefinition = { initial: '', states: [] };
+ const def = addState(empty, 'Boot');
+ expect(def.initial).toBe('Boot');
+ });
+
+ it('removes a state and prunes transitions that target it', () => {
+ let def = emptyFsm();
+ def = addState(def, 'Chase');
+ def = addTransition(def, 'Idle', 'Chase');
+ def = addTransition(def, 'Chase', 'Idle');
+ def = removeState(def, 'Chase');
+ expect(def.states.map(s => s.name)).toEqual(['Idle']);
+ // Idle's transition to the removed Chase is gone.
+ expect(fsmEdges(def)).toHaveLength(0);
+ });
+
+ it('reassigns initial when the initial state is removed', () => {
+ let def = emptyFsm();
+ def = addState(def, 'Chase');
+ def = removeState(def, 'Idle');
+ expect(def.initial).toBe('Chase');
+ });
+
+ it('moves a state to new coordinates', () => {
+ const def = moveState(emptyFsm(), 'Idle', 300, 150);
+ expect(def.states[0]).toMatchObject({ x: 300, y: 150 });
+ });
+
+ it('renames a state, rewiring initial and transition targets', () => {
+ let def = emptyFsm();
+ def = addState(def, 'Chase');
+ def = addTransition(def, 'Chase', 'Idle');
+ def = renameState(def, 'Idle', 'Patrol');
+ expect(def.initial).toBe('Patrol');
+ expect(fsmEdges(def)[0].to).toBe('Patrol');
+ expect(renameState(def, 'Patrol', 'Chase')).toBe(def); // dup target → no-op
+ });
+
+ it('sets and clears state action hooks', () => {
+ let def = setStateHook(emptyFsm(), 'Idle', 'onUpdate', 'wander');
+ expect(def.states[0].onUpdate).toBe('wander');
+ def = setStateHook(def, 'Idle', 'onUpdate', '');
+ expect(def.states[0].onUpdate).toBeUndefined();
+ });
+
+ it('sets initial only to an existing state', () => {
+ let def = emptyFsm();
+ def = addState(def, 'Chase');
+ expect(setInitial(def, 'Chase').initial).toBe('Chase');
+ expect(setInitial(def, 'Ghost')).toBe(def); // unknown → no-op
+ });
+
+ it('adds, updates and removes transitions', () => {
+ let def = emptyFsm();
+ def = addState(def, 'Chase');
+ def = addTransition(def, 'Idle', 'Chase');
+ expect(fsmEdges(def)).toHaveLength(1);
+
+ def = updateTransition(def, 'Idle', 0, { guard: { key: 'seesPlayer', op: 'truthy' } });
+ expect(fsmEdges(def)[0].transition.guard).toEqual({ key: 'seesPlayer', op: 'truthy' });
+
+ def = removeTransition(def, 'Idle', 0);
+ expect(fsmEdges(def)).toHaveLength(0);
+ });
+
+ it('flattens transitions into addressable edges', () => {
+ let def = emptyFsm();
+ def = addState(def, 'Chase');
+ def = addTransition(def, 'Idle', 'Chase');
+ def = addTransition(def, 'Idle', 'Idle');
+ const edges = fsmEdges(def);
+ expect(edges.map(e => e.id)).toEqual(['Idle->Chase#0', 'Idle->Idle#1']);
+ });
+});
diff --git a/sdk/tests/fsm.test.ts b/sdk/tests/fsm.test.ts
new file mode 100644
index 000000000..2dfde846e
--- /dev/null
+++ b/sdk/tests/fsm.test.ts
@@ -0,0 +1,193 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import {
+ Blackboard,
+ evalGuard,
+ AiRegistry,
+ compileFsm,
+ createFsmRunState,
+ stepFsm,
+ type FsmDefinition,
+} from '../src/ai/fsm';
+
+describe('Blackboard', () => {
+ it('stores and reads typed values', () => {
+ const bb = new Blackboard();
+ expect(bb.has('hp')).toBe(false);
+ bb.set('hp', 50);
+ expect(bb.get<number>('hp')).toBe(50);
+ expect(bb.has('hp')).toBe(true);
+ bb.delete('hp');
+ expect(bb.has('hp')).toBe(false);
+ });
+
+ it('fires and consumes one-shot triggers', () => {
+ const bb = new Blackboard();
+ expect(bb.isFired('go')).toBe(false);
+ bb.fire('go');
+ expect(bb.isFired('go')).toBe(true);
+ bb.consume('go');
+ expect(bb.isFired('go')).toBe(false);
+ });
+});
+
+describe('evalGuard', () => {
+ const bb = new Blackboard();
+ bb.set('hp', 30);
+ bb.set('name', 'orc');
+ bb.set('alerted', true);
+
+ it('compares numbers and equality', () => {
+ expect(evalGuard(bb, { key: 'hp', op: '<', value: 50 })).toBe(true);
+ expect(evalGuard(bb, { key: 'hp', op: '>=', value: 30 })).toBe(true);
+ expect(evalGuard(bb, { key: 'hp', op: '>', value: 30 })).toBe(false);
+ expect(evalGuard(bb, { key: 'name', op: '==', value: 'orc' })).toBe(true);
+ expect(evalGuard(bb, { key: 'name', op: '!=', value: 'elf' })).toBe(true);
+ });
+
+ it('handles truthy/falsy and missing keys', () => {
+ expect(evalGuard(bb, { key: 'alerted', op: 'truthy' })).toBe(true);
+ expect(evalGuard(bb, { key: 'missing', op: 'falsy' })).toBe(true);
+ expect(evalGuard(bb, { key: 'missing', op: 'truthy' })).toBe(false);
+ });
+});
+
+/** A registry whose actions append their name to `log` for sequence assertions. */
+function loggingRegistry(log: string[]): AiRegistry<unknown> {
+ const reg = new AiRegistry<unknown>();
+ for (const name of ['patrolMove', 'startChase', 'chaseMove', 'attack']) {
+ reg.registerAction(name, () => log.push(name));
+ }
+ return reg;
+}
+
+const patrolChase: FsmDefinition = {
+ initial: 'Patrol',
+ states: [
+ {
+ name: 'Patrol',
+ onUpdate: 'patrolMove',
+ transitions: [{ to: 'Chase', guard: { key: 'seesPlayer', op: 'truthy' } }],
+ },
+ {
+ name: 'Chase',
+ onEnter: 'startChase',
+ onUpdate: 'chaseMove',
+ transitions: [{ to: 'Patrol', guard: { key: 'seesPlayer', op: 'falsy' } }],
+ },
+ ],
+};
+
+describe('stepFsm', () => {
+ it('runs onEnter once, onUpdate each idle tick', () => {
+ const log: string[] = [];
+ const reg = loggingRegistry(log);
+ const fsm = compileFsm({
+ initial: 'A',
+ states: [{ name: 'A', onEnter: 'startChase', onUpdate: 'patrolMove' }],
+ });
+ const run = createFsmRunState(fsm);
+ const bb = new Blackboard();
+ stepFsm(fsm, run, {}, bb, reg);
+ stepFsm(fsm, run, {}, bb, reg);
+ // onEnter once, onUpdate twice.
+ expect(log).toEqual(['startChase', 'patrolMove', 'patrolMove']);
+ });
+
+ it('drives a full patrol → chase → patrol cycle via the blackboard', () => {
+ const log: string[] = [];
+ const reg = loggingRegistry(log);
+ const fsm = compileFsm(patrolChase);
+ const run = createFsmRunState(fsm);
+ const bb = new Blackboard();
+
+ stepFsm(fsm, run, {}, bb, reg); // Patrol: onUpdate
+ expect(run.current).toBe('Patrol');
+ expect(log).toEqual(['patrolMove']);
+
+ bb.set('seesPlayer', true);
+ const t1 = stepFsm(fsm, run, {}, bb, reg); // transition → Chase
+ expect(t1).toBe(true);
+ expect(run.current).toBe('Chase');
+ expect(run.previous).toBe('Patrol');
+
+ stepFsm(fsm, run, {}, bb, reg); // Chase: onEnter + onUpdate
+ expect(log).toEqual(['patrolMove', 'startChase', 'chaseMove']);
+
+ bb.set('seesPlayer', false);
+ const t2 = stepFsm(fsm, run, {}, bb, reg); // transition → Patrol
+ expect(t2).toBe(true);
+ expect(run.current).toBe('Patrol');
+ expect(run.previous).toBe('Chase');
+ });
+
+ it('takes a trigger-based transition and consumes the event', () => {
+ const reg = new AiRegistry<unknown>();
+ const fsm = compileFsm({
+ initial: 'Idle',
+ states: [
+ { name: 'Idle', transitions: [{ to: 'Go', trigger: 'start' }] },
+ { name: 'Go' },
+ ],
+ });
+ const run = createFsmRunState(fsm);
+ const bb = new Blackboard();
+
+ expect(stepFsm(fsm, run, {}, bb, reg)).toBe(false); // no trigger yet
+ bb.fire('start');
+ expect(stepFsm(fsm, run, {}, bb, reg)).toBe(true);
+ expect(run.current).toBe('Go');
+ expect(bb.isFired('start')).toBe(false); // consumed
+ });
+
+ it('evaluates named registry conditions, ANDed with guards', () => {
+ const reg = new AiRegistry<{ inRange: boolean }>();
+ reg.registerCondition('inRange', ctx => ctx.inRange);
+ const fsm = compileFsm({
+ initial: 'Approach',
+ states: [
+ {
+ name: 'Approach',
+ transitions: [{
+ to: 'Attack',
+ condition: 'inRange',
+ guard: { key: 'hp', op: '>', value: 0 },
+ }],
+ },
+ { name: 'Attack' },
+ ],
+ });
+ const run = createFsmRunState(fsm);
+ const bb = new Blackboard();
+ bb.set('hp', 10);
+
+ // condition false → no transition even though guard passes.
+ expect(stepFsm(fsm, run, { inRange: false }, bb, reg)).toBe(false);
+ // condition true + guard true → transition.
+ expect(stepFsm(fsm, run, { inRange: true }, bb, reg)).toBe(true);
+ expect(run.current).toBe('Attack');
+ });
+
+ it('takes the first enabled transition in order', () => {
+ const reg = new AiRegistry<unknown>();
+ const fsm = compileFsm({
+ initial: 'S',
+ states: [
+ {
+ name: 'S',
+ transitions: [
+ { to: 'A', guard: { key: 'x', op: '==', value: 1 } },
+ { to: 'B', guard: { key: 'x', op: '==', value: 2 } },
+ ],
+ },
+ { name: 'A' }, { name: 'B' },
+ ],
+ });
+ const run = createFsmRunState(fsm);
+ const bb = new Blackboard();
+ bb.set('x', 2);
+ stepFsm(fsm, run, {}, bb, reg);
+ expect(run.current).toBe('B');
+ });
+});
diff --git a/sdk/tests/nav-follow.test.ts b/sdk/tests/nav-follow.test.ts
new file mode 100644
index 000000000..c4464954c
--- /dev/null
+++ b/sdk/tests/nav-follow.test.ts
@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import { advanceAlongPath } from '../src/ai/nav/follow';
+
+describe('advanceAlongPath', () => {
+ it('moves part-way toward a single waypoint', () => {
+ const pos = { x: 0, y: 0 };
+ const idx = advanceAlongPath(pos, [{ x: 10, y: 0 }], 0, 4);
+ expect(pos).toEqual({ x: 4, y: 0 });
+ expect(idx).toBe(0); // not yet reached
+ });
+
+ it('snaps onto a waypoint reached exactly', () => {
+ const pos = { x: 0, y: 0 };
+ const idx = advanceAlongPath(pos, [{ x: 10, y: 0 }], 0, 10);
+ expect(pos).toEqual({ x: 10, y: 0 });
+ expect(idx).toBe(1);
+ });
+
+ it('crosses multiple waypoints in one step', () => {
+ const pos = { x: 0, y: 0 };
+ const waypoints = [{ x: 10, y: 0 }, { x: 20, y: 0 }, { x: 30, y: 0 }];
+ const idx = advanceAlongPath(pos, waypoints, 0, 25);
+ expect(pos).toEqual({ x: 25, y: 0 });
+ expect(idx).toBe(2); // consumed wp0 and wp1, part-way to wp2
+ });
+
+ it('reports end reached when budget exceeds the whole chain', () => {
+ const pos = { x: 0, y: 0 };
+ const waypoints = [{ x: 10, y: 0 }, { x: 20, y: 0 }];
+ const idx = advanceAlongPath(pos, waypoints, 0, 1000);
+ expect(pos).toEqual({ x: 20, y: 0 });
+ expect(idx).toBe(2); // == waypoints.length → done
+ });
+
+ it('follows a diagonal correctly', () => {
+ const pos = { x: 0, y: 0 };
+ const idx = advanceAlongPath(pos, [{ x: 3, y: 4 }], 0, 5);
+ expect(pos.x).toBeCloseTo(3);
+ expect(pos.y).toBeCloseTo(4);
+ expect(idx).toBe(1);
+ });
+
+ it('skips a waypoint already at pos without looping', () => {
+ const pos = { x: 5, y: 5 };
+ const idx = advanceAlongPath(pos, [{ x: 5, y: 5 }, { x: 15, y: 5 }], 0, 4);
+ expect(pos).toEqual({ x: 9, y: 5 });
+ expect(idx).toBe(1);
+ });
+});
diff --git a/sdk/tests/nav-pathfind.test.ts b/sdk/tests/nav-pathfind.test.ts
new file mode 100644
index 000000000..ee24e318e
--- /dev/null
+++ b/sdk/tests/nav-pathfind.test.ts
@@ -0,0 +1,153 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import { NavGrid, type Cell } from '../src/ai/nav/NavGrid';
+import { findPath, pathToWorld } from '../src/ai/nav/pathfind';
+
+/**
+ * Build a grid from an ASCII map. '#' = blocked, anything else walkable.
+ * Row 0 is the top line, so `gy` increases downward here purely for test
+ * legibility — the grid itself is direction-agnostic.
+ */
+function gridFromAscii(rows: string[], cellSize = 10): NavGrid {
+ const height = rows.length;
+ const width = rows[0].length;
+ const walkable = new Uint8Array(width * height);
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ walkable[y * width + x] = rows[y][x] === '#' ? 0 : 1;
+ }
+ }
+ return new NavGrid({ width, height, cellSize, walkable });
+}
+
+function isContiguous(path: Cell[], diagonal: boolean): boolean {
+ for (let i = 1; i < path.length; i++) {
+ const dx = Math.abs(path[i].x - path[i - 1].x);
+ const dy = Math.abs(path[i].y - path[i - 1].y);
+ const step = Math.max(dx, dy);
+ if (step !== 1) return false;
+ if (!diagonal && dx + dy !== 1) return false;
+ }
+ return true;
+}
+
+describe('NavGrid', () => {
+ it('maps cells to world centers and back', () => {
+ const grid = new NavGrid({ width: 4, height: 4, cellSize: 32, origin: { x: 100, y: 200 } });
+ expect(grid.cellToWorld(0, 0)).toEqual({ x: 100, y: 200 });
+ expect(grid.cellToWorld(2, 1)).toEqual({ x: 164, y: 232 });
+ // worldToCell is the inverse of cellToWorld on cell centers.
+ expect(grid.worldToCell(164, 232)).toEqual({ x: 2, y: 1 });
+ // Points anywhere inside a cell round to that cell.
+ expect(grid.worldToCell(170, 210)).toEqual({ x: 2, y: 0 });
+ });
+
+ it('reports bounds and walkability', () => {
+ const grid = new NavGrid({ width: 3, height: 3, cellSize: 10 });
+ expect(grid.isWalkable(0, 0)).toBe(true);
+ expect(grid.inBounds(-1, 0)).toBe(false);
+ expect(grid.isWalkable(3, 3)).toBe(false);
+ grid.setWalkable(1, 1, false);
+ expect(grid.isWalkable(1, 1)).toBe(false);
+ });
+
+ it('snaps to the nearest walkable cell', () => {
+ const grid = gridFromAscii([
+ '###',
+ '#.#',
+ '###',
+ ]);
+ expect(grid.nearestWalkable(0, 0)).toEqual({ x: 1, y: 1 });
+ expect(grid.nearestWalkable(1, 1)).toEqual({ x: 1, y: 1 });
+ });
+
+ it('returns null when nothing is walkable in range', () => {
+ const grid = gridFromAscii(['###', '###', '###']);
+ expect(grid.nearestWalkable(1, 1, 4)).toBeNull();
+ });
+});
+
+describe('findPath', () => {
+ it('finds a straight path on an open grid', () => {
+ const grid = new NavGrid({ width: 5, height: 1, cellSize: 10 });
+ const path = findPath(grid, { x: 0, y: 0 }, { x: 4, y: 0 })!;
+ expect(path).not.toBeNull();
+ expect(path[0]).toEqual({ x: 0, y: 0 });
+ expect(path[path.length - 1]).toEqual({ x: 4, y: 0 });
+ expect(isContiguous(path, true)).toBe(true);
+ });
+
+ it('returns a single cell when start equals goal', () => {
+ const grid = new NavGrid({ width: 5, height: 5, cellSize: 10 });
+ expect(findPath(grid, { x: 2, y: 2 }, { x: 2, y: 2 })).toEqual([{ x: 2, y: 2 }]);
+ });
+
+ it('routes around a wall', () => {
+ // A vertical wall with a gap at the bottom row forces a detour.
+ const grid = gridFromAscii([
+ '.....',
+ '..#..',
+ '..#..',
+ '..#..',
+ '.....',
+ ]);
+ const path = findPath(grid, { x: 0, y: 2 }, { x: 4, y: 2 }, { diagonal: true })!;
+ expect(path).not.toBeNull();
+ expect(isContiguous(path, true)).toBe(true);
+ // Path must not step on any blocked cell.
+ for (const c of path) expect(grid.isWalkable(c.x, c.y)).toBe(true);
+ });
+
+ it('returns null for an unreachable goal', () => {
+ const grid = gridFromAscii([
+ '..#..',
+ '..#..',
+ '..#..',
+ '..#..',
+ '..#..',
+ ]);
+ expect(findPath(grid, { x: 0, y: 0 }, { x: 4, y: 0 }, { snapRadius: 0 })).toBeNull();
+ });
+
+ it('does not cut diagonal corners', () => {
+ // From (0,0) to (1,1) the diagonal is blocked because both shared
+ // orthogonals are walls; the only route is the long way around.
+ const grid = gridFromAscii([
+ '.#',
+ '#.',
+ ]);
+ // With a 2x2 fully pinched map there is no path at all.
+ expect(findPath(grid, { x: 0, y: 0 }, { x: 1, y: 1 }, { snapRadius: 0 })).toBeNull();
+ });
+
+ it('4-connected paths never move diagonally', () => {
+ const grid = new NavGrid({ width: 5, height: 5, cellSize: 10 });
+ const path = findPath(grid, { x: 0, y: 0 }, { x: 3, y: 2 }, { diagonal: false })!;
+ expect(path).not.toBeNull();
+ expect(isContiguous(path, false)).toBe(true);
+ // Manhattan distance 3+2=5 → 6 cells including both endpoints.
+ expect(path.length).toBe(6);
+ });
+
+ it('snaps a blocked start/goal onto walkable cells', () => {
+ const grid = gridFromAscii([
+ '#....',
+ '.....',
+ '....#',
+ ]);
+ // Start on the top-left wall, goal on the bottom-right wall.
+ const path = findPath(grid, { x: 0, y: 0 }, { x: 4, y: 2 })!;
+ expect(path).not.toBeNull();
+ expect(grid.isWalkable(path[0].x, path[0].y)).toBe(true);
+ expect(grid.isWalkable(path[path.length - 1].x, path[path.length - 1].y)).toBe(true);
+ });
+
+ it('projects a path to world waypoints at cell centers', () => {
+ const grid = new NavGrid({ width: 3, height: 1, cellSize: 20, origin: { x: 5, y: 5 } });
+ const path = findPath(grid, { x: 0, y: 0 }, { x: 2, y: 0 })!;
+ expect(pathToWorld(grid, path)).toEqual([
+ { x: 5, y: 5 }, { x: 25, y: 5 }, { x: 45, y: 5 },
+ ]);
+ });
+});
diff --git a/sdk/tests/nav-step.test.ts b/sdk/tests/nav-step.test.ts
new file mode 100644
index 000000000..a68d0471b
--- /dev/null
+++ b/sdk/tests/nav-step.test.ts
@@ -0,0 +1,178 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import { Transform } from '../src/component';
+import type { Entity } from '../src/types';
+import { NavGrid } from '../src/ai/nav/NavGrid';
+import { Navigation } from '../src/ai/nav/Navigation';
+import { NavAgent } from '../src/ai/nav/NavAgent';
+import {
+ stepNavigation,
+ type AgentRuntime,
+ type NavWorldView,
+} from '../src/ai/nav/NavPlugin';
+import { navGridFromTiles } from '../src/ai/nav/navGridFromTilemap';
+
+/** Minimal in-memory world satisfying what stepNavigation calls. */
+class FakeWorld implements NavWorldView {
+ private store = new Map<string, unknown>();
+ private next = 1;
+ readonly entities: Entity[] = [];
+
+ spawnAgent(x: number, y: number, agent: Partial<import('../src/ai/nav/NavAgent').NavAgentData>): Entity {
+ const e = this.next++ as Entity;
+ this.store.set(`${e}:NavAgent`, NavAgent.create(agent));
+ // Only position is read/written; a partial Transform is enough here.
+ this.store.set(`${e}:Transform`, { position: { x, y, z: 0 } });
+ this.entities.push(e);
+ return e;
+ }
+
+ getEntitiesWithComponents(): Entity[] {
+ return this.entities;
+ }
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ get(entity: Entity, component: { _name: string }): any {
+ return this.store.get(`${entity}:${component._name}`);
+ }
+ set(entity: Entity, component: { _name: string }, data: unknown): void {
+ this.store.set(`${entity}:${component._name}`, data);
+ }
+
+ pos(entity: Entity): { x: number; y: number } {
+ const tf = this.store.get(`${entity}:Transform`) as { position: { x: number; y: number } };
+ return { x: tf.position.x, y: tf.position.y };
+ }
+ agent(entity: Entity): import('../src/ai/nav/NavAgent').NavAgentData {
+ return this.store.get(`${entity}:NavAgent`) as import('../src/ai/nav/NavAgent').NavAgentData;
+ }
+}
+
+function openNav(width = 10, height = 3, cellSize = 10): Navigation {
+ const nav = new Navigation();
+ nav.setGrid(new NavGrid({ width, height, cellSize }));
+ return nav;
+}
+
+describe('stepNavigation', () => {
+ it('walks an agent to its target on an open grid and marks arrival', () => {
+ const nav = openNav();
+ const world = new FakeWorld();
+ const runtimes = new Map<Entity, AgentRuntime>();
+ const e = world.spawnAgent(0, 0, { speed: 100, repathInterval: 0, hasTarget: true, targetX: 90, targetY: 0 });
+
+ let frames = 0;
+ while (!world.agent(e).arrived && frames < 100) {
+ stepNavigation(world, nav, 0.1, runtimes);
+ frames++;
+ }
+
+ expect(world.agent(e).arrived).toBe(true);
+ expect(world.agent(e).hasTarget).toBe(false);
+ const p = world.pos(e);
+ expect(p.x).toBeCloseTo(90, 1);
+ expect(p.y).toBeCloseTo(0, 1);
+ // 90px at 100px/s ≈ 9 frames; guard against a runaway loop.
+ expect(frames).toBeLessThan(20);
+ });
+
+ it('routes an agent around a wall with one gap', () => {
+ // Column x=5 blocked on rows 0..1, open on row 2 → detour through the gap.
+ const nav = new Navigation();
+ const grid = new NavGrid({ width: 10, height: 3, cellSize: 10 });
+ grid.setWalkable(5, 0, false);
+ grid.setWalkable(5, 1, false);
+ nav.setGrid(grid);
+ const world = new FakeWorld();
+ const runtimes = new Map<Entity, AgentRuntime>();
+ const e = world.spawnAgent(0, 0, { speed: 150, repathInterval: 0, hasTarget: true, targetX: 90, targetY: 0 });
+
+ let frames = 0;
+ while (!world.agent(e).arrived && frames < 200) {
+ stepNavigation(world, nav, 0.05, runtimes);
+ frames++;
+ }
+ expect(world.agent(e).arrived).toBe(true);
+ expect(world.pos(e).x).toBeCloseTo(90, 1);
+ });
+
+ it('does not move an agent toward an unreachable target', () => {
+ // Full wall column with no gap.
+ const nav = new Navigation();
+ const grid = new NavGrid({ width: 10, height: 3, cellSize: 10 });
+ for (let y = 0; y < 3; y++) grid.setWalkable(5, y, false);
+ nav.setGrid(grid);
+ const world = new FakeWorld();
+ const runtimes = new Map<Entity, AgentRuntime>();
+ const e = world.spawnAgent(0, 0, { speed: 100, repathInterval: 0, hasTarget: true, targetX: 90, targetY: 0 });
+
+ stepNavigation(world, nav, 0.1, runtimes);
+ expect(world.pos(e)).toEqual({ x: 0, y: 0 });
+ expect(world.agent(e).arrived).toBe(false);
+ expect(runtimes.get(e)?.reachable).toBe(false);
+ });
+
+ it('replans when the target moves', () => {
+ const nav = openNav();
+ const world = new FakeWorld();
+ const runtimes = new Map<Entity, AgentRuntime>();
+ const e = world.spawnAgent(0, 0, { speed: 100, repathInterval: 0, hasTarget: true, targetX: 90, targetY: 0 });
+
+ stepNavigation(world, nav, 0.05, runtimes);
+ expect(runtimes.get(e)!.plannedX).toBe(90);
+
+ // Retarget mid-flight.
+ const a = world.agent(e);
+ a.targetX = 0;
+ a.targetY = 20;
+ world.set(e, NavAgent, a);
+ stepNavigation(world, nav, 0.05, runtimes);
+ expect(runtimes.get(e)!.plannedX).toBe(0);
+ expect(runtimes.get(e)!.plannedY).toBe(20);
+ });
+
+ it('is a no-op for agents without a target', () => {
+ const nav = openNav();
+ const world = new FakeWorld();
+ const runtimes = new Map<Entity, AgentRuntime>();
+ const e = world.spawnAgent(30, 0, { speed: 100, hasTarget: false });
+ stepNavigation(world, nav, 0.1, runtimes);
+ expect(world.pos(e)).toEqual({ x: 30, y: 0 });
+ });
+});
+
+describe('navGridFromTiles', () => {
+ const rows = [
+ [0, 0, 3],
+ [0, 5, 0],
+ ];
+ const getTile = (x: number, y: number) => rows[y][x];
+
+ it('treats any non-empty tile as blocked by default', () => {
+ const grid = navGridFromTiles(getTile, { width: 3, height: 2, cellSize: 16 });
+ expect(grid.isWalkable(0, 0)).toBe(true);
+ expect(grid.isWalkable(2, 0)).toBe(false); // tile 3
+ expect(grid.isWalkable(1, 1)).toBe(false); // tile 5
+ });
+
+ it('blocks only the listed tile ids', () => {
+ const grid = navGridFromTiles(getTile, { width: 3, height: 2, cellSize: 16, blockedTileIds: [5] });
+ expect(grid.isWalkable(2, 0)).toBe(true); // tile 3 no longer blocks
+ expect(grid.isWalkable(1, 1)).toBe(false); // tile 5 blocks
+ });
+
+ it('honors a custom predicate', () => {
+ const grid = navGridFromTiles(getTile, {
+ width: 3, height: 2, cellSize: 16,
+ isBlocked: id => id === 3,
+ });
+ expect(grid.isWalkable(2, 0)).toBe(false);
+ expect(grid.isWalkable(1, 1)).toBe(true);
+ });
+
+ it('ignores flip bits above the tile-id mask', () => {
+ // 3 with a flip flag set in the high bits still reads as tile id 3.
+ const grid = navGridFromTiles(() => 3 | 0x8000, { width: 1, height: 1, cellSize: 16 });
+ expect(grid.isWalkable(0, 0)).toBe(false);
+ });
+});