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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(sdk): behavior trees - the third declarative AI sibling (AI3)
esengineb3fedf092e70
diff --git a/sdk/src/ai/bt/BehaviorTreeAgent.ts b/sdk/src/ai/bt/BehaviorTreeAgent.tsnew file mode 100644index 000000000..c788df093--- /dev/null+++ b/sdk/src/ai/bt/BehaviorTreeAgent.ts@@ -0,0 +1,54 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file BehaviorTreeAgent.ts+ * @brief BehaviorTreeAgent component + the tree store.+ *+ * The authorable half: which behavior tree to run (a registered name or a+ * `.esbt` asset path) plus the observable last root status. `*Agent` naming,+ * pure TS, mirroring StateMachineAgent.+ */++import { defineComponent } from '../../component';+import type { BtDefinition } from './types';++export interface BehaviorTreeAgentData {+ /** Key of the tree to run: a `registerBt` name or a `.esbt` asset path. */+ bt: string;+ /** Last root status, written by the system each tick (observable). */+ status: string;+}++export const BehaviorTreeAgent = defineComponent<BehaviorTreeAgentData>('BehaviorTreeAgent', {+ bt: '',+ status: '',+}, {+ assetFields: [{ field: 'bt', type: 'behaviortree' }],+ // Preload a `.esbt` reference with the scene; a plain registerBt name is left alone.+ discoverAssets: data => {+ const bt = data.bt;+ return typeof bt === 'string' && bt.endsWith('.esbt')+ ? [{ type: 'behaviortree', path: bt }]+ : [];+ },+ fields: {+ status: { advanced: true, tooltip: 'Last root status (runtime, read-only).' },+ },+});++/** Behavior trees keyed by registration name or `.esbt` asset path. A tree IS its definition — no compile. */+const btStore = new Map<string, BtDefinition>();++export function registerBt(key: string, def: BtDefinition): BtDefinition {+ btStore.set(key, def);+ return def;+}++export function getBt(key: string): BtDefinition | undefined {+ return btStore.get(key);+}++/** Drop all registered trees (tests / hot-reload). */+export function clearBtStore(): void {+ btStore.clear();+}diff --git a/sdk/src/ai/bt/BtPlugin.ts b/sdk/src/ai/bt/BtPlugin.tsnew file mode 100644index 000000000..378c13cc2--- /dev/null+++ b/sdk/src/ai/bt/BtPlugin.ts@@ -0,0 +1,142 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file BtPlugin.ts+ * @brief Ticks BehaviorTreeAgents against the shared runtime + registry.+ *+ * Per-entity blackboard + tree run-state live in a closure Map (the+ * `defineBehavior` pattern); the component stays serializable. Reuses the same+ * `aiRegistry` and `AiContext` as FSM, so a tree's leaves and an FSM's actions+ * are the same named-registry entries. `stepBehaviorTrees` is extracted to+ * unit-test against a fake world. Gated to play mode; runs before nav follow.+ */++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 '../fsm/Blackboard';+import { aiRegistry, type AiContext } from '../fsm/AiContext';+import { tickBt, createBtRunState, type BtRunState } from './BtRunner';+import { BehaviorTreeAgent, getBt } from './BehaviorTreeAgent';++interface BtAgentState {+ bb: Blackboard;+ rs: BtRunState;+ btKey: string | null;+ status: string;+}++/** The slice of `World` the BT step needs — lets tests inject a fake. */+export interface AiWorldView {+ 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 early. */+export function agentBtBlackboard(states: Map<Entity, BtAgentState>, entity: Entity): Blackboard {+ let st = states.get(entity);+ if (!st) {+ st = { bb: new Blackboard(), rs: createBtRunState(), btKey: null, status: '' };+ states.set(entity, st);+ }+ return st.bb;+}++/** Advance every BehaviorTreeAgent one tick. `states` carries per-entity runtime across frames. */+export function stepBehaviorTrees(+ world: AiWorldView,+ commands: CommandsInstance,+ dt: number,+ states: Map<Entity, BtAgentState>,+): 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([BehaviorTreeAgent])) {+ const agent = world.get(entity, BehaviorTreeAgent);+ if (!agent.bt) continue;+ const def = getBt(agent.bt);+ if (!def) continue;++ let st = states.get(entity);+ if (!st) {+ st = { bb: new Blackboard(), rs: createBtRunState(), btKey: null, status: '' };+ states.set(entity, st);+ }+ // A changed tree resets the run-state (Running memory would be stale).+ if (st.btKey !== agent.bt) {+ st.rs = createBtRunState();+ st.btKey = agent.bt;+ }++ ctx.entity = entity;+ ctx.dt = dt;+ ctx.blackboard = st.bb;+ const status = tickBt(def, ctx, st.bb, aiRegistry, st.rs, dt);++ st.status = status;+ if (agent.status !== status) {+ agent.status = status;+ world.set(entity, BehaviorTreeAgent, agent);+ }+ }+}++/** Resource for game code to reach an agent's blackboard / last status. */+export class BehaviorTrees {+ constructor(private states: Map<Entity, BtAgentState>) {}++ blackboard(entity: Entity): Blackboard {+ return agentBtBlackboard(this.states, entity);+ }++ status(entity: Entity): string | null {+ return this.states.get(entity)?.status ?? null;+ }+}++export const AiBt = defineResource<BehaviorTrees>(null!, 'AiBt');++export class BtPlugin implements Plugin {+ name = 'bt';++ build(app: App): void {+ const states = new Map<Entity, BtAgentState>();+ app.world.onDespawn((entity: Entity) => states.delete(entity));+ app.insertResource(AiBt, new BehaviorTrees(states));++ app.addSystemToSchedule(+ Schedule.Update,+ defineSystem(+ [Res(Time), Commands(), GetWorld()],+ (time: TimeData, commands: CommandsInstance, world) => {+ stepBehaviorTrees(world as AiWorldView, commands, time.delta, states);+ },+ { name: 'BehaviorTreeSystem' },+ ),+ { runIf: playModeOnly },+ );+ }+}++export const btPlugin = new BtPlugin();diff --git a/sdk/src/ai/bt/BtRunner.ts b/sdk/src/ai/bt/BtRunner.tsnew file mode 100644index 000000000..b87b1b249--- /dev/null+++ b/sdk/src/ai/bt/BtRunner.ts@@ -0,0 +1,159 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file BtRunner.ts+ * @brief The behavior-tree interpreter — pure, generic, unit-testable.+ *+ * One `tickBt` per frame walks the tree; each node returns a {@link Status}.+ * Composites are reactive (UE-style): each tick re-evaluates children from the+ * start, so a higher-priority branch whose condition just became true preempts a+ * lower-priority branch that was Running. Only decorators with intrinsic timing+ * (`wait`/`repeater`) keep per-node state, keyed by node path ("0.1.2"). `dt` is+ * passed explicitly (only `wait` uses it) so the core stays free of any+ * engine/context type.+ */++import type { Blackboard } from '../fsm/Blackboard';+import type { AiRegistry } from '../fsm/registry';+import { Status } from '../status';+import type { BtDefinition, BtNode } from './types';++interface NodeState {+ /** Repeater: completed iterations. */+ n?: number;+ /** Wait: elapsed seconds. */+ elapsed?: number;+}++export type BtRunState = Map<string, NodeState>;++export function createBtRunState(): BtRunState {+ return new Map();+}++/** Advance the tree one tick, returning the root's status. */+export function tickBt<Ctx>(+ def: BtDefinition,+ ctx: Ctx,+ bb: Blackboard,+ registry: AiRegistry<Ctx>,+ rs: BtRunState,+ dt: number,+): Status {+ return tickNode(def.root, '0', ctx, bb, registry, rs, dt);+}++function tickNode<Ctx>(+ node: BtNode, path: string, ctx: Ctx, bb: Blackboard,+ registry: AiRegistry<Ctx>, rs: BtRunState, dt: number,+): Status {+ switch (node.type) {+ case 'action': {+ const fn = registry.getAction(node.name ?? '');+ if (!fn) return Status.Failure;+ const r = fn(ctx, bb);+ // A void-returning (one-shot FSM-style) action completes as Success.+ return r === undefined ? Status.Success : r;+ }+ case 'condition': {+ const fn = registry.getCondition(node.name ?? '');+ return fn && fn(ctx, bb) ? Status.Success : Status.Failure;+ }+ case 'inverter': {+ const s = tickOnly(node, path, ctx, bb, registry, rs, dt);+ if (s === Status.Running) return s;+ return s === Status.Success ? Status.Failure : Status.Success;+ }+ case 'succeeder': {+ const s = tickOnly(node, path, ctx, bb, registry, rs, dt);+ return s === Status.Running ? Status.Running : Status.Success;+ }+ case 'repeater': {+ const s = tickOnly(node, path, ctx, bb, registry, rs, dt);+ if (s === Status.Running) return Status.Running;+ // Child finished (success or failure) = one iteration.+ const st = rs.get(path) ?? {};+ st.n = (st.n ?? 0) + 1;+ rs.set(path, st);+ const count = node.count ?? 0;+ if (count > 0 && st.n >= count) {+ rs.delete(path);+ return Status.Success;+ }+ return Status.Running; // repeat next tick+ }+ case 'wait': {+ const st = rs.get(path) ?? {};+ st.elapsed = (st.elapsed ?? 0) + dt;+ rs.set(path, st);+ if (st.elapsed >= (node.seconds ?? 0)) {+ rs.delete(path);+ return Status.Success;+ }+ return Status.Running;+ }+ case 'sequence':+ return tickCompound(node, path, ctx, bb, registry, rs, dt, false);+ case 'selector':+ return tickCompound(node, path, ctx, bb, registry, rs, dt, true);+ case 'parallel':+ return tickParallel(node, path, ctx, bb, registry, rs, dt);+ default:+ return Status.Failure;+ }+}++/** A decorator's single child. */+function tickOnly<Ctx>(+ node: BtNode, path: string, ctx: Ctx, bb: Blackboard,+ registry: AiRegistry<Ctx>, rs: BtRunState, dt: number,+): Status {+ const child = node.children?.[0];+ if (!child) return Status.Failure;+ return tickNode(child, `${path}.0`, ctx, bb, registry, rs, dt);+}++/**+ * Sequence (isSelector=false): run children in order; a child Failure fails the+ * whole node, all-Success succeeds. Selector (isSelector=true) is the dual: a+ * child Success succeeds, all-Failure fails. Reactive: re-evaluated from the+ * first child each tick, so a higher-priority child that starts succeeding+ * preempts a lower-priority one that was Running.+ */+function tickCompound<Ctx>(+ node: BtNode, path: string, ctx: Ctx, bb: Blackboard,+ registry: AiRegistry<Ctx>, rs: BtRunState, dt: number, isSelector: boolean,+): Status {+ const children = node.children ?? [];+ const stopStatus = isSelector ? Status.Success : Status.Failure;+ for (let i = 0; i < children.length; i++) {+ const s = tickNode(children[i], `${path}.${i}`, ctx, bb, registry, rs, dt);+ if (s === Status.Running) return Status.Running;+ if (s === stopStatus) return stopStatus;+ // otherwise advance to the next child+ }+ return isSelector ? Status.Failure : Status.Success;+}++/** Tick all children each frame; resolve by the success policy. */+function tickParallel<Ctx>(+ node: BtNode, path: string, ctx: Ctx, bb: Blackboard,+ registry: AiRegistry<Ctx>, rs: BtRunState, dt: number,+): Status {+ const children = node.children ?? [];+ let successes = 0;+ let failures = 0;+ for (let i = 0; i < children.length; i++) {+ const s = tickNode(children[i], `${path}.${i}`, ctx, bb, registry, rs, dt);+ if (s === Status.Success) successes++;+ else if (s === Status.Failure) failures++;+ }+ if ((node.policy ?? 'all') === 'one') {+ if (successes > 0) return Status.Success;+ if (failures === children.length) return Status.Failure;+ } else {+ if (failures > 0) return Status.Failure;+ if (successes === children.length) return Status.Success;+ }+ return Status.Running;+}diff --git a/sdk/src/ai/bt/index.ts b/sdk/src/ai/bt/index.tsnew file mode 100644index 000000000..46854d680--- /dev/null+++ b/sdk/src/ai/bt/index.ts@@ -0,0 +1,9 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file index.ts+ * @brief Behavior-tree core barrel (pure runtime; engine binding is separate).+ */++export type { BtNodeType, BtNode, BtDefinition } from './types';+export { tickBt, createBtRunState, type BtRunState } from './BtRunner';diff --git a/sdk/src/ai/bt/types.ts b/sdk/src/ai/bt/types.tsnew file mode 100644index 000000000..98a499d8d--- /dev/null+++ b/sdk/src/ai/bt/types.ts@@ -0,0 +1,39 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file types.ts+ * @brief Behavior-tree data model — the serializable shape of a `.esbt`.+ *+ * A tree is pure data; leaf `name`s resolve to real logic through the shared+ * AiRegistry at runtime (the same registry FSM actions/conditions use), so the+ * data embeds no code — matching `.esfsm` and the input maps.+ */++export type BtNodeType =+ // composites (many children)+ | 'sequence' | 'selector' | 'parallel'+ // decorators (one child)+ | 'inverter' | 'succeeder' | 'repeater' | 'wait'+ // leaves+ | 'action' | 'condition';++export interface BtNode {+ type: BtNodeType;+ /** Registry name for a leaf (`action`/`condition`). */+ name?: string;+ /** Children: many for a composite, one for a decorator. */+ children?: BtNode[];+ /** `repeater`: iterations before Success; 0 = forever. */+ count?: number;+ /** `parallel`: succeed when `one` child succeeds, or when `all` do (default). */+ policy?: 'all' | 'one';+ /** `wait`: seconds to run before Success. */+ seconds?: number;+ /** Editor-only canvas position; ignored by the interpreter. */+ x?: number;+ y?: number;+}++export interface BtDefinition {+ root: BtNode;+}diff --git a/sdk/src/ai/fsm/registry.ts b/sdk/src/ai/fsm/registry.tsindex ad8b62750..d1ddf3bc5 100644--- a/sdk/src/ai/fsm/registry.ts+++ b/sdk/src/ai/fsm/registry.ts@@ -12,8 +12,11 @@*/import type { Blackboard } from './Blackboard';+import type { Status } from '../status';-export type AiAction<Ctx> = (ctx: Ctx, bb: Blackboard) => void;+// Returns Status (a BT leaf that may run across frames) or nothing (a one-shot+// FSM action). FSM ignores the return; BT reads it, treating void as Success.+export type AiAction<Ctx> = (ctx: Ctx, bb: Blackboard) => void | Status;export type AiCondition<Ctx> = (ctx: Ctx, bb: Blackboard) => boolean;export class AiRegistry<Ctx = unknown> {diff --git a/sdk/src/ai/index.ts b/sdk/src/ai/index.tsindex 1357e98f2..5f258b0f9 100644--- a/sdk/src/ai/index.ts+++ b/sdk/src/ai/index.ts@@ -33,3 +33,26 @@ export {agentBlackboard,type FsmWorldView,} from './fsm/FsmPlugin';++// Shared AI task status (FSM actions + BT nodes).+export { Status } from './status';++// Behavior trees: pure core (types + interpreter)…+export * from './bt';+// …plus the engine binding (component, store, plugin).+export {+ BehaviorTreeAgent,+ registerBt,+ getBt,+ clearBtStore,+ type BehaviorTreeAgentData,+} from './bt/BehaviorTreeAgent';+export {+ BtPlugin,+ btPlugin,+ BehaviorTrees,+ AiBt,+ stepBehaviorTrees,+ agentBtBlackboard,+ type AiWorldView,+} from './bt/BtPlugin';diff --git a/sdk/src/ai/status.ts b/sdk/src/ai/status.tsnew file mode 100644index 000000000..cb2de9fe9--- /dev/null+++ b/sdk/src/ai/status.ts@@ -0,0 +1,17 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file status.ts+ * @brief Shared AI task status — the return type that unifies FSM actions and+ * behavior-tree nodes.+ *+ * A registered action may return a Status (a BT leaf that can run across frames)+ * or nothing (a one-shot FSM action). BT treats a `void` return as `Success`;+ * FSM ignores the return entirely. One registry, two consumers.+ */++export enum Status {+ Success = 'success',+ Failure = 'failure',+ Running = 'running',+}diff --git a/sdk/src/asset/AssetFieldRegistry.ts b/sdk/src/asset/AssetFieldRegistry.tsindex 0a5562246..7d7abd717 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' | 'statemachine';+export type AssetFieldType = 'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree';export interface AssetFieldDescriptor {field: string;diff --git a/sdk/src/asset/AssetLoader.ts b/sdk/src/asset/AssetLoader.tsindex 961639ea2..f422f4313 100644--- a/sdk/src/asset/AssetLoader.ts+++ b/sdk/src/asset/AssetLoader.ts@@ -54,6 +54,10 @@ export interface FsmResult {fsmId: string;}+export interface BtResult {+ btId: string;+}+export interface PrefabResult {data: unknown;}diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex 4f0e658fc..355e68587 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -25,6 +25,7 @@ import { TilesetAssetLoader } from './loaders/TilesetAssetLoader';import { TimelineAssetLoader } from './loaders/TimelineAssetLoader';import { PrefabAssetLoader } from './loaders/PrefabAssetLoader';import { FsmAssetLoader } from './loaders/FsmAssetLoader';+import { BtAssetLoader } from './loaders/BtAssetLoader';import type { SpineModuleController } from '../spine/SpineController';import { getAssetFields } from './AssetFieldRegistry';import { getComponentDefaults } from '../component';@@ -880,6 +881,7 @@ export class Assets {this.register(new TimelineAssetLoader());this.register(new PrefabAssetLoader());this.register(new FsmAssetLoader());+ this.register(new BtAssetLoader());}private textureCacheKey_(path: string, flip: boolean): string {diff --git a/sdk/src/asset/loaders/BtAssetLoader.ts b/sdk/src/asset/loaders/BtAssetLoader.tsnew file mode 100644index 000000000..fb7666de3--- /dev/null+++ b/sdk/src/asset/loaders/BtAssetLoader.ts@@ -0,0 +1,30 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file BtAssetLoader.ts+ * @brief Loads a `.esbt` and registers it under its path in the tree store,+ * so a BehaviorTreeAgent whose `bt` is that path resolves at runtime.+ * A `.esbt` payload IS a runtime BtDefinition (plus optional editor-only+ * layout on each node, which the interpreter ignores) — no compile step.+ */++import type { AssetLoader, LoadContext, BtResult } from '../AssetLoader';+import { registerBt } from '../../ai/bt/BehaviorTreeAgent';+import type { BtDefinition } from '../../ai/bt/types';++export class BtAssetLoader implements AssetLoader<BtResult> {+ readonly type = 'behaviortree';+ readonly extensions = ['.esbt'];++ async load(path: string, ctx: LoadContext): Promise<BtResult> {+ const buildPath = ctx.catalog.getBuildPath(path);+ const text = await ctx.loadText(buildPath);+ const def = JSON.parse(text) as BtDefinition;+ registerBt(path, def);+ return { btId: path };+ }++ unload(): void {+ // Trees are registered globally in the shared store.+ }+}diff --git a/sdk/src/assetTypes.ts b/sdk/src/assetTypes.tsindex 79a789fac..431a8596b 100644--- a/sdk/src/assetTypes.ts+++ b/sdk/src/assetTypes.ts@@ -47,6 +47,8 @@ const ASSET_TYPE_REGISTRY: readonly AssetTypeEntry[] = [{ 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 },+ // Behavior tree (registerBt / BtAssetLoader) — data-driven BT definition.+ { extensions: ['esbt'], contentType: 'json', editorType: 'json', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: false },];const MIME_MAP: Record<string, string> = {@@ -73,6 +75,7 @@ const MIME_MAP: Record<string, string> = {esanim: 'application/json',estimeline: 'application/json',esfsm: 'application/json',+ esbt: 'application/json',bmfont: 'application/json',fnt: 'text/plain',};diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 740e50685..8de907640 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -467,3 +467,27 @@ export {type AiContext,type StateMachineAgentData,} from './ai';++// =============================================================================+// AI — Behavior trees (pure-TS interpreter, .esbt data + shared registry)+// =============================================================================++export {+ Status,+ tickBt,+ createBtRunState,+ BehaviorTreeAgent,+ registerBt,+ getBt,+ clearBtStore,+ BtPlugin,+ btPlugin,+ BehaviorTrees,+ AiBt,+ agentBtBlackboard,+ type BtNodeType,+ type BtNode,+ type BtDefinition,+ type BtRunState,+ type BehaviorTreeAgentData,+} from './ai';diff --git a/sdk/src/scene.ts b/sdk/src/scene.tsindex 702dea53d..f8e8466a9 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' | 'statemachine';+export type AssetFieldType = 'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree';// =============================================================================// Component Query Helpers (read from self-describing ComponentDef)diff --git a/sdk/src/webAppFactory.ts b/sdk/src/webAppFactory.tsindex 78221417e..2b37b552c 100644--- a/sdk/src/webAppFactory.ts+++ b/sdk/src/webAppFactory.ts@@ -12,7 +12,7 @@ import { postProcessPlugin } from './postprocess';import { timelinePlugin } from './timeline';import { timerPlugin } from './timer';import { lifecyclePlugin } from './lifecycle';-import { navPlugin, fsmPlugin } from './ai';+import { navPlugin, fsmPlugin, btPlugin } from './ai';import { SpinePlugin } from './spine';import { createFetchSideModuleHost, type SideModuleHost } from './sideModules';@@ -58,7 +58,7 @@ export interface CreateWebAppOptions extends WebAppOptions {wasmBaseUrl?: string;}-const basePlugins = [timerPlugin, lifecyclePlugin(), animationPlugin, audioPlugin, particlePlugin, tilemapPlugin, postProcessPlugin, timelinePlugin, fsmPlugin, navPlugin];+const basePlugins = [timerPlugin, lifecyclePlugin(), animationPlugin, audioPlugin, particlePlugin, tilemapPlugin, postProcessPlugin, timelinePlugin, fsmPlugin, btPlugin, navPlugin];export function createWebApp(module: ESEngineModule, options?: CreateWebAppOptions): App {const sideModules: SideModuleHost | undefined = options?.sideModulesdiff --git a/sdk/tests/bt-agent.test.ts b/sdk/tests/bt-agent.test.tsnew file mode 100644index 000000000..22d2604d7--- /dev/null+++ b/sdk/tests/bt-agent.test.ts@@ -0,0 +1,109 @@+// 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 { BehaviorTreeAgent, registerBt, clearBtStore } from '../src/ai/bt/BehaviorTreeAgent';+import { aiRegistry, registerAction, registerCondition } from '../src/ai/fsm/AiContext';+import { stepBehaviorTrees, agentBtBlackboard, BehaviorTrees, type AiWorldView } from '../src/ai/bt/BtPlugin';+import { Status } from '../src/ai/status';+import type { BtDefinition } from '../src/ai/bt/types';++class FakeWorld implements AiWorldView {+ private store = new Map<string, unknown>();+ private next = 1;+ private entities: Entity[] = [];++ spawn(bt: string): Entity {+ const e = this.next++ as Entity;+ this.store.set(`${e}:BehaviorTreeAgent`, BehaviorTreeAgent.create({ bt }));+ 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 patrolChaseTree: BtDefinition = {+ root: {+ type: 'selector',+ children: [+ { type: 'sequence', children: [{ type: 'condition', name: 'seesPlayer' }, { type: 'action', name: 'chase' }] },+ { type: 'action', name: 'patrol' },+ ],+ },+};++describe('stepBehaviorTrees', () => {+ let acted: string[];+ beforeEach(() => {+ aiRegistry.clear();+ clearBtStore();+ acted = [];+ registerCondition('seesPlayer', (_c, bb) => bb.get('seesPlayer') === true);+ registerAction('chase', () => { acted.push('chase'); return Status.Running; });+ registerAction('patrol', () => { acted.push('patrol'); return Status.Running; });+ });++ it('runs a tree, writes root status back, and switches branch off the blackboard', () => {+ registerBt('enemy', patrolChaseTree);+ const world = new FakeWorld();+ const states = new Map();+ const e = world.spawn('enemy');++ stepBehaviorTrees(world, NO_COMMANDS, 0.1, states);+ expect(acted).toEqual(['patrol']); // no player → patrol fallback+ expect(world.get(e, BehaviorTreeAgent).status).toBe(Status.Running);++ agentBtBlackboard(states, e).set('seesPlayer', true);+ acted = [];+ stepBehaviorTrees(world, NO_COMMANDS, 0.1, states);+ expect(acted).toEqual(['chase']); // sees player → chase branch+ });++ it('is a no-op when the tree key is unregistered', () => {+ const world = new FakeWorld();+ const states = new Map();+ const e = world.spawn('missing');+ stepBehaviorTrees(world, NO_COMMANDS, 0.1, states);+ expect(world.get(e, BehaviorTreeAgent).status).toBe(''); // untouched+ });++ it('exposes entity/get/has on the leaf context', () => {+ let seen: { entity: Entity; has: boolean; bt: string } | null = null;+ registerAction('probe', ctx => {+ seen = { entity: ctx.entity, has: ctx.has(BehaviorTreeAgent), bt: ctx.get(BehaviorTreeAgent).bt };+ });+ registerBt('probe', { root: { type: 'action', name: 'probe' } });+ const world = new FakeWorld();+ const states = new Map();+ const e = world.spawn('probe');+ stepBehaviorTrees(world, NO_COMMANDS, 0.1, states);+ expect(seen).toEqual({ entity: e, has: true, bt: 'probe' });+ });++ it('BehaviorTrees resource reports blackboard and last status', () => {+ registerBt('enemy', patrolChaseTree);+ const world = new FakeWorld();+ const states = new Map();+ const res = new BehaviorTrees(states);+ const e = world.spawn('enemy');+ stepBehaviorTrees(world, NO_COMMANDS, 0.1, states);+ expect(res.status(e)).toBe(Status.Running);+ res.blackboard(e).set('seesPlayer', true);+ expect(res.blackboard(e).get('seesPlayer')).toBe(true);+ });+});diff --git a/sdk/tests/bt.test.ts b/sdk/tests/bt.test.tsnew file mode 100644index 000000000..295072497--- /dev/null+++ b/sdk/tests/bt.test.ts@@ -0,0 +1,138 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect, beforeEach } from 'vitest';+import { AiRegistry } from '../src/ai/fsm/registry';+import { Blackboard } from '../src/ai/fsm/Blackboard';+import { Status } from '../src/ai/status';+import { tickBt, createBtRunState, type BtRunState } from '../src/ai/bt/BtRunner';+import type { BtDefinition } from '../src/ai/bt/types';++describe('tickBt', () => {+ let reg: AiRegistry<unknown>;+ let bb: Blackboard;+ let rs: BtRunState;++ beforeEach(() => {+ reg = new AiRegistry<unknown>();+ bb = new Blackboard();+ rs = createBtRunState();+ reg.registerAction('ok', () => Status.Success);+ reg.registerAction('fail', () => Status.Failure);+ reg.registerAction('run', () => Status.Running);+ reg.registerAction('void', () => { /* one-shot */ });+ reg.registerCondition('yes', () => true);+ reg.registerCondition('no', () => false);+ });++ const tick = (def: BtDefinition, dt = 0.1) => tickBt(def, {}, bb, reg, rs, dt);++ it('treats a void action as Success and passes Status through', () => {+ expect(tick({ root: { type: 'action', name: 'void' } })).toBe(Status.Success);+ expect(tick({ root: { type: 'action', name: 'run' } })).toBe(Status.Running);+ expect(tick({ root: { type: 'action', name: 'fail' } })).toBe(Status.Failure);+ expect(tick({ root: { type: 'action', name: 'missing' } })).toBe(Status.Failure);+ });++ it('maps conditions to Success/Failure', () => {+ expect(tick({ root: { type: 'condition', name: 'yes' } })).toBe(Status.Success);+ expect(tick({ root: { type: 'condition', name: 'no' } })).toBe(Status.Failure);+ });++ it('sequence: all-success succeeds, first failure fails, running propagates', () => {+ expect(tick({ root: { type: 'sequence', children: [{ type: 'action', name: 'ok' }, { type: 'action', name: 'ok' }] } })).toBe(Status.Success);+ expect(tick({ root: { type: 'sequence', children: [{ type: 'action', name: 'ok' }, { type: 'action', name: 'fail' }] } })).toBe(Status.Failure);+ expect(tick({ root: { type: 'sequence', children: [{ type: 'action', name: 'ok' }, { type: 'action', name: 'run' }] } })).toBe(Status.Running);+ });++ it('selector: first success succeeds, all-failure fails, running propagates', () => {+ expect(tick({ root: { type: 'selector', children: [{ type: 'action', name: 'fail' }, { type: 'action', name: 'ok' }] } })).toBe(Status.Success);+ expect(tick({ root: { type: 'selector', children: [{ type: 'action', name: 'fail' }, { type: 'action', name: 'fail' }] } })).toBe(Status.Failure);+ expect(tick({ root: { type: 'selector', children: [{ type: 'action', name: 'fail' }, { type: 'action', name: 'run' }] } })).toBe(Status.Running);+ });++ it('inverter flips Success/Failure but not Running', () => {+ expect(tick({ root: { type: 'inverter', children: [{ type: 'action', name: 'ok' }] } })).toBe(Status.Failure);+ expect(tick({ root: { type: 'inverter', children: [{ type: 'action', name: 'fail' }] } })).toBe(Status.Success);+ expect(tick({ root: { type: 'inverter', children: [{ type: 'action', name: 'run' }] } })).toBe(Status.Running);+ });++ it('succeeder forces Success unless Running', () => {+ expect(tick({ root: { type: 'succeeder', children: [{ type: 'action', name: 'fail' }] } })).toBe(Status.Success);+ expect(tick({ root: { type: 'succeeder', children: [{ type: 'action', name: 'run' }] } })).toBe(Status.Running);+ });++ it('re-evaluates from the top each tick so a higher-priority branch preempts (reactive)', () => {+ let low = 0;+ let high = 0;+ reg.registerAction('low', () => { low++; return Status.Running; });+ reg.registerAction('high', () => { high++; return Status.Running; });+ reg.registerCondition('alert', (_c, b) => b.get('alert') === true);+ const def: BtDefinition = {+ root: {+ type: 'selector',+ children: [+ { type: 'sequence', children: [{ type: 'condition', name: 'alert' }, { type: 'action', name: 'high' }] },+ { type: 'action', name: 'low' },+ ],+ },+ };++ tick(def); // not alert → falls through to low+ expect(low).toBe(1);+ expect(high).toBe(0);+ bb.set('alert', true);+ tick(def); // alert → high branch preempts the running low, no manual reset+ expect(high).toBe(1);+ expect(low).toBe(1); // low was not ticked this frame+ });++ it('repeater runs its child a fixed number of times then succeeds', () => {+ const def: BtDefinition = { root: { type: 'repeater', count: 3, children: [{ type: 'action', name: 'ok' }] } };+ expect(tick(def)).toBe(Status.Running); // iter 1+ expect(tick(def)).toBe(Status.Running); // iter 2+ expect(tick(def)).toBe(Status.Success); // iter 3 → done+ });++ it('repeater with count 0 loops forever', () => {+ const def: BtDefinition = { root: { type: 'repeater', count: 0, children: [{ type: 'action', name: 'ok' }] } };+ for (let i = 0; i < 5; i++) expect(tick(def)).toBe(Status.Running);+ });++ it('wait succeeds after accumulating dt', () => {+ const def: BtDefinition = { root: { type: 'wait', seconds: 0.25 } };+ expect(tick(def, 0.1)).toBe(Status.Running); // 0.1+ expect(tick(def, 0.1)).toBe(Status.Running); // 0.2+ expect(tick(def, 0.1)).toBe(Status.Success); // 0.3 ≥ 0.25+ });++ it('parallel resolves by success policy', () => {+ expect(tick({ root: { type: 'parallel', children: [{ type: 'action', name: 'ok' }, { type: 'action', name: 'ok' }] } })).toBe(Status.Success);+ expect(tick({ root: { type: 'parallel', children: [{ type: 'action', name: 'ok' }, { type: 'action', name: 'fail' }] } })).toBe(Status.Failure);+ expect(tick({ root: { type: 'parallel', children: [{ type: 'action', name: 'ok' }, { type: 'action', name: 'run' }] } })).toBe(Status.Running);+ expect(tick({ root: { type: 'parallel', policy: 'one', children: [{ type: 'action', name: 'fail' }, { type: 'action', name: 'ok' }] } })).toBe(Status.Success);+ expect(tick({ root: { type: 'parallel', policy: 'one', children: [{ type: 'action', name: 'fail' }, { type: 'action', name: 'fail' }] } })).toBe(Status.Failure);+ });++ it('drives a patrol/chase tree off the blackboard', () => {+ // Selector: [ Sequence(seesPlayer? -> chase), patrol ]+ reg.registerCondition('seesPlayer', (_c, b) => b.get('seesPlayer') === true);+ const chased: string[] = [];+ reg.registerAction('chase', () => { chased.push('chase'); return Status.Running; });+ reg.registerAction('patrol', () => { chased.push('patrol'); return Status.Running; });+ const def: BtDefinition = {+ root: {+ type: 'selector',+ children: [+ { type: 'sequence', children: [{ type: 'condition', name: 'seesPlayer' }, { type: 'action', name: 'chase' }] },+ { type: 'action', name: 'patrol' },+ ],+ },+ };++ tick(def);+ expect(chased).toEqual(['patrol']); // no player → fall through to patrol+ bb.set('seesPlayer', true);+ tick(def); // reactive: chase preempts patrol next tick, no reset needed+ expect(chased).toEqual(['patrol', 'chase']); // sees player → chase branch+ });+});