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(ai): actions take an argument; spriteAnim.* builtins drive flipbooks code-free
esengine7dfb51b4e8fd
diff --git a/desktop/src/components/aiSuggest.ts b/desktop/src/components/aiSuggest.tsindex 317a23fb8..f57a689b8 100644--- a/desktop/src/components/aiSuggest.ts+++ b/desktop/src/components/aiSuggest.ts@@ -18,6 +18,10 @@ const BUILTIN_DESC: Record<string, () => string> = {'timeline.play': () => t('ai.desc.timelinePlay'),'timeline.pause': () => t('ai.desc.timelinePause'),'timeline.finished': () => t('ai.desc.timelineFinished'),+ 'spriteAnim.play': () => t('ai.desc.spriteAnimPlay'),+ 'spriteAnim.restart': () => t('ai.desc.spriteAnimRestart'),+ 'spriteAnim.stop': () => t('ai.desc.spriteAnimStop'),+ 'spriteAnim.finished': () => t('ai.desc.spriteAnimFinished'),};const decorate = (names: string[]): SuggestItem[] =>diff --git a/desktop/src/i18n/messages/nodegraph.ts b/desktop/src/i18n/messages/nodegraph.tsindex 62ce5ac63..7cf2b9772 100644--- a/desktop/src/i18n/messages/nodegraph.ts+++ b/desktop/src/i18n/messages/nodegraph.ts@@ -15,6 +15,8 @@ export const nodegraphMessages = defineMessages({'ng.deleteSelected': { en: 'Delete selected', zh: '删除所选' },'ng.name': { en: 'Name', zh: '名称' },'ng.phActionName': { en: 'action name', zh: '动作名称' },+ 'ng.actionArg': { en: 'Argument', zh: '参数' },+ 'ng.phActionArg': { en: 'optional argument (e.g. a clip path)', zh: '可选参数(如剪辑路径)' },'ng.phConditionName': { en: 'condition name', zh: '条件名称' },'ng.inPortTip': { en: 'Edges land here', zh: '连线在此接入' },'ng.outPortTip': { en: 'Drag to another node to connect', zh: '拖到另一个节点以连接' },@@ -38,6 +40,19 @@ export const nodegraphMessages = defineMessages({'ai.desc.timelinePlay': { en: "Play the agent entity's TimelinePlayer", zh: '播放代理实体的 TimelinePlayer' },'ai.desc.timelinePause': { en: "Pause the agent entity's TimelinePlayer", zh: '暂停代理实体的 TimelinePlayer' },'ai.desc.timelineFinished': { en: 'True once the timeline has finished', zh: 'Timeline 播完后为真' },+ 'ai.desc.spriteAnimPlay': {+ en: "Play the agent's sprite flipbook; the argument switches to that clip",+ zh: '播放代理实体的精灵翻页动画;参数可切换到指定剪辑',+ },+ 'ai.desc.spriteAnimRestart': {+ en: 'Rewind the sprite flipbook to frame 0 and play (argument switches clip)',+ zh: '将精灵翻页动画回卷到第 0 帧并播放(参数可切换剪辑)',+ },+ 'ai.desc.spriteAnimStop': { en: 'Pause the sprite flipbook', zh: '暂停精灵翻页动画' },+ 'ai.desc.spriteAnimFinished': {+ en: 'True once a one-shot sprite clip has finished',+ zh: '一次性精灵剪辑播完后为真',+ },'fsm.inspStateTitle': { en: 'State', zh: '状态' },'fsm.inspTransitionTitle': { en: 'Transition', zh: '转移' },'fsm.target': { en: 'Target', zh: '目标' },diff --git a/desktop/src/panels/BtTreeEditor.tsx b/desktop/src/panels/BtTreeEditor.tsxindex e6029e8a6..fc146907b 100644--- a/desktop/src/panels/BtTreeEditor.tsx+++ b/desktop/src/panels/BtTreeEditor.tsx@@ -178,6 +178,13 @@ export function BtTreeEditor() {onCommit={v => patch(selNode.id, { name: v || undefined })} /></label>)}+ {selNode.type === 'action' && (+ <label className="ng-field">{t('ng.actionArg')}+ <input className="ng-input" defaultValue={selNode.arg ?? ''} key={`${selNode.id}-arg`}+ placeholder={t('ng.phActionArg')} spellCheck={false}+ onBlur={e => { const v = e.target.value.trim(); if (v !== (selNode.arg ?? '')) patch(selNode.id, { arg: v || undefined }); }} />+ </label>+ )}{selNode.type === 'repeater' && (<label className="ng-field">{t('bt.count')}<input className="ng-input" type="number" min={0} defaultValue={selNode.count ?? 0} key={`${selNode.id}-count`}diff --git a/desktop/src/panels/StateMachineEditor.tsx b/desktop/src/panels/StateMachineEditor.tsxindex 7675a09e4..47c12821b 100644--- a/desktop/src/panels/StateMachineEditor.tsx+++ b/desktop/src/panels/StateMachineEditor.tsx@@ -17,7 +17,7 @@ import { useRef, useState, useSyncExternalStore } from 'react';import { Plus, Trash2, Save } from 'lucide-react';import {fsmEdges, addState, removeState, moveState, renameState, setStateHook, setInitial,- addTransition, removeTransition, updateTransition,+ addTransition, removeTransition, updateTransition, actionRefName, actionRefArg,type FsmDefinition, type FsmState, type FsmEdge, type CompareOp,} from 'esengine';import { FsmGraphDocument } from '@/fsm/FsmGraphDocument';@@ -128,7 +128,12 @@ export function StateMachineEditor() {renderEdgeLabel={e => <>{edgeSummary(e.transition)}</>}renderNode={(n, sel) => {const isInitial = def.initial === n.name;- const setHooks = HOOKS.filter(h => n[h]).map(h => `${h[2].toUpperCase()}:${n[h]}`).join(' ');+ const setHooks = HOOKS.filter(h => actionRefName(n[h]))+ .map(h => {+ const arg = actionRefArg(n[h]);+ return `${h[2].toUpperCase()}:${actionRefName(n[h])}${arg ? `(${arg})` : ''}`;+ })+ .join(' ');return (<div className={`ng-node-box${sel ? ' sel' : ''}`} style={!sel && isInitial ? { borderColor: 'var(--run)' } : undefined}><div className="ng-node-head">@@ -168,13 +173,22 @@ function StateInspector({ def, state, onRename }: { def: FsmDefinition; state: FonChange={() => FsmGraphDocument.edit('Set initial', (d) => Object.assign(d, setInitial(d, state.name)))} />{t('fsm.initialState')}</label>- {HOOKS.map((h) => (- <label className="ng-field" key={h}>{h}- <SuggestInput items={actions} defaultValue={state[h] ?? ''} key={`${state.name}-${h}-${state[h] ?? ''}`}- placeholder={t('ng.phActionName')}- onCommit={(v) => { if (v !== (state[h] ?? '')) FsmGraphDocument.edit(`Set ${h}`, (d) => Object.assign(d, setStateHook(d, state.name, h, v))); }} />- </label>- ))}+ {HOOKS.map((h) => {+ const name = actionRefName(state[h]);+ const arg = actionRefArg(state[h]) ?? '';+ return (+ <label className="ng-field" key={h}>{h}+ <SuggestInput items={actions} defaultValue={name} key={`${state.name}-${h}-${name}`}+ placeholder={t('ng.phActionName')}+ onCommit={(v) => { if (v !== name) FsmGraphDocument.edit(`Set ${h}`, (d) => Object.assign(d, setStateHook(d, state.name, h, v, arg || undefined))); }} />+ {name && (+ <input className="ng-input" defaultValue={arg} key={`${state.name}-${h}-arg-${arg}`}+ placeholder={t('ng.phActionArg')} spellCheck={false}+ onBlur={(e) => { const v = e.target.value.trim(); if (v !== arg) FsmGraphDocument.edit(`Set ${h} argument`, (d) => Object.assign(d, setStateHook(d, state.name, h, name, v || undefined))); }} />+ )}+ </label>+ );+ })}</div>);}diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex ce71a0e4c..f3f8fbda5 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1141 stable · 17 beta · 1 deprecated+Symbols: 1144 stable · 17 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -90,7 +90,7 @@ labels: string[]## AiAction — type```-(ctx: Ctx, bb: Blackboard) => void | Status+(ctx: Ctx, bb: Blackboard, arg?: string) => void | Status```## AiBt — const@@ -916,6 +916,7 @@ to: string## BtNode — interface```+arg: string | undefinedchildren: BtNode[] | undefinedcount: number | undefinedid: string | undefined@@ -2534,6 +2535,11 @@ text: numbertriangles: number```+## FsmActionRef — type+```+string | { name: string; arg?: string }+```+## FsmDefinition — interface```initial: string@@ -2567,9 +2573,9 @@ previous: string | null## FsmState — interface```name: string-onEnter: string | undefined-onExit: string | undefined-onUpdate: string | undefined+onEnter: FsmActionRef | undefined+onExit: FsmActionRef | undefined+onUpdate: FsmActionRef | undefinedtransitions: FsmTransition[] | undefinedx: number | undefinedy: number | undefined@@ -5536,6 +5542,7 @@ ComponentDef<SpriteAnimatorData>clip: stringcurrentFrame: numberenabled: boolean+finished: booleanframeTimer: numberloop: booleanplaying: boolean@@ -7014,6 +7021,16 @@ TransformData(typeof WrapMode)[keyof typeof WrapMode]```+## actionRefArg — function+```+(ref: FsmActionRef | undefined): string | undefined+```++## actionRefName — function+```+(ref: FsmActionRef | undefined): string+```+## addBtChild — function```(def: BtDefinition, parentId: string, type: BtNodeType, x?: number, y?: number): BtDefinition@@ -8631,7 +8648,7 @@ Plugin## setStateHook — function```-(def: FsmDefinition, name: string, hook: "onEnter" | "onUpdate" | "onExit", action: string): FsmDefinition+(def: FsmDefinition, name: string, hook: "onEnter" | "onUpdate" | "onExit", action: string, arg?: string): FsmDefinition```## setTextureBudget — functiondiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 939e635a0..773bfb812 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1140 stable · 19 beta · 1 deprecated+Symbols: 1143 stable · 19 beta · 1 deprecated## ANCHOR_AXES — const```@@ -85,7 +85,7 @@ labels: string[]## AiAction — type```-(ctx: Ctx, bb: Blackboard) => void | Status+(ctx: Ctx, bb: Blackboard, arg?: string) => void | Status```## AiBt — const@@ -911,6 +911,7 @@ to: string## BtNode — interface```+arg: string | undefinedchildren: BtNode[] | undefinedcount: number | undefinedid: string | undefined@@ -2529,6 +2530,11 @@ text: numbertriangles: number```+## FsmActionRef — type+```+string | { name: string; arg?: string }+```+## FsmDefinition — interface```initial: string@@ -2562,9 +2568,9 @@ previous: string | null## FsmState — interface```name: string-onEnter: string | undefined-onExit: string | undefined-onUpdate: string | undefined+onEnter: FsmActionRef | undefined+onExit: FsmActionRef | undefined+onUpdate: FsmActionRef | undefinedtransitions: FsmTransition[] | undefinedx: number | undefinedy: number | undefined@@ -5531,6 +5537,7 @@ ComponentDef<SpriteAnimatorData>clip: stringcurrentFrame: numberenabled: boolean+finished: booleanframeTimer: numberloop: booleanplaying: boolean@@ -7009,6 +7016,16 @@ TransformData(typeof WrapMode)[keyof typeof WrapMode]```+## actionRefArg — function+```+(ref: FsmActionRef | undefined): string | undefined+```++## actionRefName — function+```+(ref: FsmActionRef | undefined): string+```+## addBtChild — function```(def: BtDefinition, parentId: string, type: BtNodeType, x?: number, y?: number): BtDefinition@@ -8636,7 +8653,7 @@ Plugin## setStateHook — function```-(def: FsmDefinition, name: string, hook: "onEnter" | "onUpdate" | "onExit", action: string): FsmDefinition+(def: FsmDefinition, name: string, hook: "onEnter" | "onUpdate" | "onExit", action: string, arg?: string): FsmDefinition```## setTextureBudget — functiondiff --git a/sdk/src/ai/bt/BtRunner.ts b/sdk/src/ai/bt/BtRunner.tsindex b87b1b249..3d5d36d98 100644--- a/sdk/src/ai/bt/BtRunner.ts+++ b/sdk/src/ai/bt/BtRunner.ts@@ -51,7 +51,7 @@ function tickNode<Ctx>(case 'action': {const fn = registry.getAction(node.name ?? '');if (!fn) return Status.Failure;- const r = fn(ctx, bb);+ const r = fn(ctx, bb, node.arg);// A void-returning (one-shot FSM-style) action completes as Success.return r === undefined ? Status.Success : r;}diff --git a/sdk/src/ai/bt/types.ts b/sdk/src/ai/bt/types.tsindex 56cb5c641..9505630e1 100644--- a/sdk/src/ai/bt/types.ts+++ b/sdk/src/ai/bt/types.ts@@ -23,6 +23,8 @@ export interface BtNode {id?: string;/** Registry name for a leaf (`action`/`condition`). */name?: string;+ /** Optional string argument an `action` leaf passes to its registry fn. */+ arg?: string;/** Children: many for a composite, one for a decorator. */children?: BtNode[];/** `repeater`: iterations before Success; 0 = forever. */diff --git a/sdk/src/ai/builtins.ts b/sdk/src/ai/builtins.tsindex b847c33b7..d766d5a1e 100644--- a/sdk/src/ai/builtins.ts+++ b/sdk/src/ai/builtins.ts@@ -16,6 +16,7 @@import { aiRegistry, type AiContext } from './fsm/AiContext';import type { AiAction, AiCondition } from './fsm/registry';import { TimelinePlayer } from '../timeline/TimelinePlugin';+import { SpriteAnimator } from '../animation/SpriteAnimator';/*** Register the engine's built-in actions/conditions. Idempotent (and safe after@@ -50,6 +51,57 @@ export function ensureBuiltinAiRegistrations(): void {const player = ctx.get(TimelinePlayer);return player.finished && !player.playing;});++ // `arg` is the clip to play (a `.esanim` ref/path); without it the action+ // resumes/replays the animator's current clip. Same-clip play while already+ // playing is a no-op, so `onUpdate: spriteAnim.play` is safe.+ action('spriteAnim.play', (ctx, _bb, arg) => {+ if (!ctx.has(SpriteAnimator)) return;+ const sp = ctx.get(SpriteAnimator);+ const switching = !!arg && arg !== sp.clip;+ if (!switching && sp.playing) return;+ if (switching) {+ sp.clip = arg!;+ sp.currentFrame = 0;+ sp.frameTimer = 0;+ sp.finished = false;+ }+ // Raising the flag on a finished one-shot replays it from the top —+ // the SpriteAnimator flag contract (mirrors TimelinePlayer's).+ sp.playing = true;+ ctx.set(SpriteAnimator, sp);+ });++ // Unconditional rewind + play (re-trigger a one-shot mid-flight), with the+ // same optional clip arg.+ action('spriteAnim.restart', (ctx, _bb, arg) => {+ if (!ctx.has(SpriteAnimator)) return;+ const sp = ctx.get(SpriteAnimator);+ if (arg) sp.clip = arg;+ sp.currentFrame = 0;+ sp.frameTimer = 0;+ sp.finished = false;+ sp.playing = true;+ ctx.set(SpriteAnimator, sp);+ });++ action('spriteAnim.stop', ctx => {+ if (!ctx.has(SpriteAnimator)) return;+ const sp = ctx.get(SpriteAnimator);+ if (!sp.playing) return;+ sp.playing = false;+ ctx.set(SpriteAnimator, sp);+ });++ // Latched only when a one-shot clip completes (same shape as+ // timeline.finished): false before and while playing, so+ // `onEnter: spriteAnim.play` + a `spriteAnim.finished` transition is a+ // self-contained attack/one-shot state.+ condition('spriteAnim.finished', ctx => {+ if (!ctx.has(SpriteAnimator)) return false;+ const sp = ctx.get(SpriteAnimator);+ return sp.finished && !sp.playing;+ });}function action(name: string, fn: AiAction<AiContext>): void {diff --git a/sdk/src/ai/fsm/FsmRunner.ts b/sdk/src/ai/fsm/FsmRunner.tsindex d1720d4ad..f7781f8b7 100644--- a/sdk/src/ai/fsm/FsmRunner.ts+++ b/sdk/src/ai/fsm/FsmRunner.ts@@ -10,7 +10,7 @@* `onUpdate` on ticks where no transition fires.*/-import type { FsmDefinition, FsmState, FsmTransition } from './types';+import { actionRefName, actionRefArg, type FsmActionRef, type FsmDefinition, type FsmState, type FsmTransition } from './types';import { Blackboard, evalGuards } from './Blackboard';import type { AiRegistry } from './registry';@@ -89,10 +89,11 @@ function transitionEnabled<Ctx>(function runAction<Ctx>(registry: AiRegistry<Ctx>,- name: string | undefined,+ ref: FsmActionRef | undefined,ctx: Ctx,bb: Blackboard,): void {+ const name = actionRefName(ref);if (!name) return;- registry.getAction(name)?.(ctx, bb);+ registry.getAction(name)?.(ctx, bb, actionRefArg(ref));}diff --git a/sdk/src/ai/fsm/fsmGraph.ts b/sdk/src/ai/fsm/fsmGraph.tsindex 9dc295065..ccb30c3cc 100644--- a/sdk/src/ai/fsm/fsmGraph.ts+++ b/sdk/src/ai/fsm/fsmGraph.ts@@ -84,10 +84,12 @@ export function setStateHook(name: string,hook: 'onEnter' | 'onUpdate' | 'onExit',action: string,+ arg?: string,): FsmDefinition {+ const ref = action ? (arg ? { name: action, arg } : action) : undefined;return {...def,- states: def.states.map(s => (s.name === name ? { ...s, [hook]: action || undefined } : s)),+ states: def.states.map(s => (s.name === name ? { ...s, [hook]: ref } : s)),};}diff --git a/sdk/src/ai/fsm/index.ts b/sdk/src/ai/fsm/index.tsindex 4865cd390..9e4584463 100644--- a/sdk/src/ai/fsm/index.ts+++ b/sdk/src/ai/fsm/index.ts@@ -11,7 +11,9 @@ export type {FsmTransition,FsmState,FsmDefinition,+ FsmActionRef,} from './types';+export { actionRefName, actionRefArg } from './types';export { Blackboard, evalGuard, evalGuards } from './Blackboard';export { AiRegistry, type AiAction, type AiCondition } from './registry';export {diff --git a/sdk/src/ai/fsm/registry.ts b/sdk/src/ai/fsm/registry.tsindex d1ddf3bc5..430c63ad9 100644--- a/sdk/src/ai/fsm/registry.ts+++ b/sdk/src/ai/fsm/registry.ts@@ -16,7 +16,9 @@ import type { Status } from '../status';// 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;+// `arg` is the optional per-reference string the authored data carries+// (FsmActionRef / BtNode.arg); argument-free actions simply ignore it.+export type AiAction<Ctx> = (ctx: Ctx, bb: Blackboard, arg?: string) => void | Status;export type AiCondition<Ctx> = (ctx: Ctx, bb: Blackboard) => boolean;export class AiRegistry<Ctx = unknown> {diff --git a/sdk/src/ai/fsm/types.ts b/sdk/src/ai/fsm/types.tsindex 84e37f559..aca2c6527 100644--- a/sdk/src/ai/fsm/types.ts+++ b/sdk/src/ai/fsm/types.ts@@ -35,14 +35,30 @@ export interface FsmTransition {guard?: BlackboardGuard | BlackboardGuard[];}+/**+ * A hook/leaf action reference: a bare registry name, or a name plus a string+ * argument the action receives (e.g. `spriteAnim.play` with a clip ref).+ */+export type FsmActionRef = string | { name: string; arg?: string };++/** Registry name of an action ref ('' for none). */+export function actionRefName(ref: FsmActionRef | undefined): string {+ return typeof ref === 'string' ? ref : ref?.name ?? '';+}++/** Argument of an action ref, if any. */+export function actionRefArg(ref: FsmActionRef | undefined): string | undefined {+ return typeof ref === 'object' && ref !== null ? ref.arg : undefined;+}+export interface FsmState {name: string;/** Named action run once when the state becomes active. */- onEnter?: string;+ onEnter?: FsmActionRef;/** Named action run every tick the state is active (and no transition fired). */- onUpdate?: string;+ onUpdate?: FsmActionRef;/** Named action run once when the state is left. */- onExit?: string;+ onExit?: FsmActionRef;/** Outgoing edges, evaluated in order; the first enabled one is taken. */transitions?: FsmTransition[];/** Editor-only canvas position; ignored by the interpreter. */diff --git a/sdk/src/animation/Animator.ts b/sdk/src/animation/Animator.tsindex 65ac7d8c6..1ac14bc43 100644--- a/sdk/src/animation/Animator.ts+++ b/sdk/src/animation/Animator.ts@@ -516,6 +516,7 @@ export class AnimatorControllerApi {sp.currentFrame = 0;sp.frameTimer = 0;sp.playing = true;+ sp.finished = false;sp.enabled = true;world.insert(entity, SpriteAnimator, sp);}diff --git a/sdk/src/animation/SpriteAnimator.ts b/sdk/src/animation/SpriteAnimator.tsindex 4b9c6890b..ee7ea05d9 100644--- a/sdk/src/animation/SpriteAnimator.ts+++ b/sdk/src/animation/SpriteAnimator.ts@@ -155,6 +155,14 @@ export class SpriteAnimationApi {const clip = this.clips.get(animator.clip);if (!clip || clip.frames.length === 0) continue;+ // playing raised on a finished one-shot = replay from the top+ // (TimelinePlayer's flag contract).+ if (animator.finished) {+ animator.finished = false;+ animator.currentFrame = 0;+ animator.frameTimer = 0;+ }+const currentFrame = clip.frames[animator.currentFrame];const frameDuration = currentFrame?.duration ?? 1.0 / (clip.fps * animator.speed);@@ -174,6 +182,7 @@ export class SpriteAnimationApi {} else {animator.currentFrame = clip.frames.length - 1;animator.playing = false;+ animator.finished = true;}}@@ -210,6 +219,7 @@ export class SpriteAnimationApi {animator.currentFrame = Math.max(0, Math.min(frameIndex, clip.frames.length - 1));animator.frameTimer = 0;animator.playing = andPlay;+ animator.finished = false;}gotoLabel(animator: SpriteAnimatorData, label: string, andPlay: boolean = true): void {@@ -241,6 +251,10 @@ export interface SpriteAnimatorData {enabled: boolean;currentFrame: number;frameTimer: number;+ /** Latched when a one-shot clip completes; runtime-only, do not author.+ * Raising `playing` on a finished animator replays from frame 0 — the+ * same flag contract as TimelinePlayer. */+ finished: boolean;}export const SpriteAnimator: ComponentDef<SpriteAnimatorData> = defineComponent('SpriteAnimator', {@@ -251,6 +265,7 @@ export const SpriteAnimator: ComponentDef<SpriteAnimatorData> = defineComponent(enabled: true,currentFrame: 0,frameTimer: 0,+ finished: false,}, {assetFields: [{ field: 'clip', type: 'anim-clip' }],});diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 461547e52..50ef95047 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -493,6 +493,9 @@ export {moveState,renameState,setStateHook,+ actionRefName,+ actionRefArg,+ type FsmActionRef,setInitial,addTransition,removeTransition,diff --git a/sdk/tests/fsm-sprite-anim.test.ts b/sdk/tests/fsm-sprite-anim.test.tsnew file mode 100644index 000000000..e453a24dd--- /dev/null+++ b/sdk/tests/fsm-sprite-anim.test.ts@@ -0,0 +1,150 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * The FSM → SpriteAnimator drive channel: the built-in `spriteAnim.*` actions+ * and `spriteAnim.finished` condition, the action-argument plumbing+ * (FsmActionRef / BtNode.arg → AiAction's third parameter), and the animator's+ * finished-latch flag contract (raising `playing` on a finished one-shot+ * replays from frame 0).+ */+import { describe, it, expect, beforeEach } from 'vitest';+import { aiRegistry, type AiContext } from '../src/ai/fsm/AiContext';+import { ensureBuiltinAiRegistrations } from '../src/ai/builtins';+import { compileFsm, createFsmRunState, stepFsm } from '../src/ai/fsm/FsmRunner';+import { Blackboard } from '../src/ai/fsm/Blackboard';+import { createBtRunState, tickBt } from '../src/ai/bt/BtRunner';+import type { BtDefinition } from '../src/ai/bt/types';+import type { FsmDefinition } from '../src/ai/fsm/types';+import {+ SpriteAnimator, SpriteAnimationApi, type SpriteAnimatorData, type SpriteAnimClip,+} from '../src/animation/SpriteAnimator';+import type { World } from '../src/world';++/** A one-entity AiContext over a plain component store. */+function makeCtx(components: Map<string, unknown>): AiContext {+ return {+ entity: 1 as never,+ dt: 1 / 60,+ blackboard: new Blackboard(),+ world: {} as never,+ commands: {} as never,+ get: (c: { _name: string }) => structuredClone(components.get(c._name)) as never,+ set: (c: { _name: string }, data: unknown) => void components.set(c._name, data),+ has: (c: { _name: string }) => components.has(c._name),+ } as AiContext;+}++function animator(over: Partial<SpriteAnimatorData> = {}): SpriteAnimatorData {+ return SpriteAnimator.create(over) as SpriteAnimatorData;+}++const sp = (m: Map<string, unknown>) => m.get('SpriteAnimator') as SpriteAnimatorData;++beforeEach(() => {+ aiRegistry.clear();+ ensureBuiltinAiRegistrations();+});++describe('spriteAnim builtins', () => {+ it('play with an arg switches the clip and rewinds', () => {+ const comps = new Map<string, unknown>([+ ['SpriteAnimator', animator({ clip: 'idle.esanim', currentFrame: 3, frameTimer: 0.05, playing: true })],+ ]);+ aiRegistry.getAction('spriteAnim.play')!(makeCtx(comps), new Blackboard(), 'run.esanim');+ expect(sp(comps).clip).toBe('run.esanim');+ expect(sp(comps).currentFrame).toBe(0);+ expect(sp(comps).playing).toBe(true);+ });++ it('play without an arg resumes without rewinding, and is a no-op while playing', () => {+ const comps = new Map<string, unknown>([+ ['SpriteAnimator', animator({ clip: 'idle.esanim', currentFrame: 3, playing: false })],+ ]);+ aiRegistry.getAction('spriteAnim.play')!(makeCtx(comps), new Blackboard());+ expect(sp(comps).playing).toBe(true);+ expect(sp(comps).currentFrame).toBe(3);+ });++ it('restart rewinds even mid-flight', () => {+ const comps = new Map<string, unknown>([+ ['SpriteAnimator', animator({ clip: 'attack.esanim', currentFrame: 2, playing: true })],+ ]);+ aiRegistry.getAction('spriteAnim.restart')!(makeCtx(comps), new Blackboard());+ expect(sp(comps).currentFrame).toBe(0);+ expect(sp(comps).playing).toBe(true);+ });++ it('finished is latched only after a one-shot completes', () => {+ const comps = new Map<string, unknown>([+ ['SpriteAnimator', animator({ clip: 'attack.esanim', playing: true })],+ ]);+ const cond = aiRegistry.getCondition('spriteAnim.finished')!;+ expect(cond(makeCtx(comps), new Blackboard())).toBe(false);+ comps.set('SpriteAnimator', animator({ clip: 'attack.esanim', playing: false, finished: true, currentFrame: 1 }));+ expect(cond(makeCtx(comps), new Blackboard())).toBe(true);+ });+});++describe('action argument plumbing', () => {+ it('FSM hooks pass FsmActionRef.arg to the action', () => {+ const seen: (string | undefined)[] = [];+ aiRegistry.registerAction('capture', (_ctx, _bb, arg) => void seen.push(arg));+ const def: FsmDefinition = {+ initial: 'a',+ states: [{ name: 'a', onEnter: { name: 'capture', arg: 'hello' }, onUpdate: 'capture' }],+ };+ const ctx = makeCtx(new Map());+ const compiled = compileFsm(def);+ const run = createFsmRunState(compiled);+ stepFsm(compiled, run, ctx, new Blackboard(), aiRegistry);+ expect(seen).toEqual(['hello', undefined]);+ });++ it('BT action leaves pass node.arg', () => {+ let seen: string | undefined;+ aiRegistry.registerAction('capture', (_ctx, _bb, arg) => void (seen = arg));+ const def: BtDefinition = { root: { type: 'action', name: 'capture', arg: 'clips/run.esanim' } };+ tickBt(def, makeCtx(new Map()), new Blackboard(), aiRegistry, createBtRunState(), 1 / 60);+ expect(seen).toBe('clips/run.esanim');+ });+});++describe('finished-latch flag contract (system side)', () => {+ /** Minimal World for SpriteAnimationApi.update: one entity, two components.+ * `get` returns the live object (the real World's semantic — frame-timer+ * accrual persists between ticks without an insert). */+ function makeWorld(comps: Map<string, unknown>): World {+ return {+ getEntitiesWithComponents: () => [1],+ get: (_e: number, c: { _name: string }) => comps.get(c._name),+ has: (_e: number, c: { _name: string }) => comps.has(c._name),+ insert: (_e: number, c: { _name: string }, data: unknown) => void comps.set(c._name, data),+ } as unknown as World;+ }++ const clip: SpriteAnimClip = {+ name: 'attack.esanim', fps: 10, loop: false,+ frames: [{ texture: 1 }, { texture: 2 }],+ };++ it('one-shot completion latches finished; raising playing replays from frame 0', () => {+ const api = new SpriteAnimationApi();+ api.registerClip(clip);+ const comps = new Map<string, unknown>([+ ['SpriteAnimator', animator({ clip: 'attack.esanim', loop: false, playing: true })],+ ]);+ const world = makeWorld(comps);+ // 2 frames at 10fps = 0.2s; overshoot to complete.+ for (let i = 0; i < 5; i++) api.update(world, 0.06);+ expect(sp(comps).playing).toBe(false);+ expect(sp(comps).finished).toBe(true);+ expect(sp(comps).currentFrame).toBe(1);++ // The FSM raises the flag (replay) — the system rewinds and clears the latch.+ aiRegistry.getAction('spriteAnim.play')!(makeCtx(comps), new Blackboard());+ api.update(world, 0.01);+ expect(sp(comps).finished).toBe(false);+ expect(sp(comps).currentFrame).toBe(0);+ expect(sp(comps).playing).toBe(true);+ });+});diff --git a/sdk/tests/sprite-animator.test.ts b/sdk/tests/sprite-animator.test.tsindex fcca2d445..949815580 100644--- a/sdk/tests/sprite-animator.test.ts+++ b/sdk/tests/sprite-animator.test.ts@@ -74,6 +74,7 @@ describe('SpriteAnimator', () => {enabled: true,currentFrame: 0,frameTimer: 0,+ finished: false,});});