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(animation): animation state machine on the sprite channel (T2)
yhh305895724cd8
diff --git a/sdk/src/animation/AnimationPlugin.ts b/sdk/src/animation/AnimationPlugin.tsindex 62b39c271..9d57b2d61 100644--- a/sdk/src/animation/AnimationPlugin.ts+++ b/sdk/src/animation/AnimationPlugin.ts@@ -13,6 +13,7 @@ import type { Entity } from '../types';import type { ESEngineModule, CppRegistry } from '../wasm';import { Tween, TweenAPI } from './Tween';import { SpriteAnimation, SpriteAnimationApi } from './SpriteAnimator';+import { AnimatorController, AnimatorControllerApi } from './Animator';import { playModeOnly } from '../env';import { SystemLabel } from '../systemLabels';@@ -26,11 +27,14 @@ export class AnimationPlugin implements Plugin {app.insertResource(Tween, tween);const anim = new SpriteAnimationApi();app.insertResource(SpriteAnimation, anim);+ const animator = new AnimatorControllerApi();+ app.insertResource(AnimatorController, animator);const world = app.world;world.onDespawn((entity: Entity) => {tween.cancelAll(entity);anim.removeEntityListeners(entity);+ animator.removeEntity(entity);});app.addSystemToSchedule(Schedule.Update, defineSystem(@@ -41,13 +45,23 @@ export class AnimationPlugin implements Plugin {{ name: 'TweenSystem' }), { runIf: playModeOnly });+ // The state machine runs before the sprite animator so a transition's+ // clip switch applies the same frame it fires.+ app.addSystemToSchedule(Schedule.Update, defineSystem(+ [Res(AnimatorController)],+ (ctrl: AnimatorControllerApi) => {+ ctrl.update(world);+ },+ { name: 'AnimatorSystem' }+ ), { runAfter: [SystemLabel.Tween], runIf: playModeOnly });+app.addSystemToSchedule(Schedule.Update, defineSystem([Res(Time), Res(SpriteAnimation)],(time: TimeData, animApi: SpriteAnimationApi) => {animApi.update(world, time.delta);},{ name: 'SpriteAnimatorSystem' }- ), { runAfter: [SystemLabel.Tween], runIf: playModeOnly });+ ), { runAfter: [SystemLabel.Tween, SystemLabel.Animator], runIf: playModeOnly });}}diff --git a/sdk/src/animation/Animator.ts b/sdk/src/animation/Animator.tsnew file mode 100644index 000000000..78a2424a1--- /dev/null+++ b/sdk/src/animation/Animator.ts@@ -0,0 +1,300 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Animator.ts+ * @brief Animation state machine (pure TypeScript), built on the existing+ * sprite-animation channel.+ *+ * Design (per REARCH_2D_PARITY.md T2): the state machine is a *strategy layer*+ * over the existing animation channels — it does not run its own clip playback.+ * A state names a sprite clip; when a transition fires, the Animator switches the+ * entity's {@link SpriteAnimator}.clip. Frame playback stays the single+ * responsibility of {@link SpriteAnimationApi}. Parameters/triggers drive+ * transitions, mirroring the Unity Animator's SetFloat/SetBool/SetTrigger model.+ *+ * The transition evaluator ({@link evaluateAnimatorTransitions}) is pure — no+ * World, no side effects — so it is fully unit-testable.+ */++import { defineComponent, type ComponentDef } from '../component';+import { defineResource } from '../resource';+import type { Entity } from '../types';+import type { World } from '../world';+import { SpriteAnimator, type SpriteAnimatorData } from './SpriteAnimator';++// =============================================================================+// Controller definition (the graph data)+// =============================================================================++export type AnimatorParamType = 'float' | 'bool' | 'trigger';++export interface AnimatorParam {+ name: string;+ type: AnimatorParamType;+ /** Default value for float (number) / bool (boolean). Triggers default off. */+ default?: number | boolean;+}++/**+ * A transition condition. Numeric comparisons (`gt`/`lt`/`eq`/`neq`) carry a+ * `value`; `true`/`false` test a bool param; `trigger` fires when the named+ * trigger is set (and consumes it).+ */+export type AnimatorCondition =+ | { param: string; op: 'gt' | 'lt' | 'eq' | 'neq'; value: number }+ | { param: string; op: 'true' | 'false' | 'trigger' };++export interface AnimatorTransition {+ /** Target state name. */+ to: string;+ /** All conditions must hold (AND). Empty = unconditional. */+ conditions: AnimatorCondition[];+}++export interface AnimatorState {+ name: string;+ /** Sprite clip name this state plays (registered with SpriteAnimation). */+ clip: string;+ speed?: number;+ loop?: boolean;+ transitions: AnimatorTransition[];+}++export interface AnimatorControllerDef {+ parameters: AnimatorParam[];+ states: AnimatorState[];+ initialState: string;+ /** Transitions evaluated from every state, before the current state's own. */+ anyStateTransitions?: AnimatorTransition[];+}++// =============================================================================+// Pure transition evaluator (no World, no side effects → unit-testable)+// =============================================================================++export type AnimatorParamValues = Readonly<Record<string, number | boolean>>;++export interface AnimatorEvalResult {+ /** Target state if a transition fired, else null (stay). */+ next: string | null;+ /** Trigger params a fired transition consumed (caller resets them). */+ consumedTriggers: string[];+}++function conditionHolds(+ c: AnimatorCondition,+ params: AnimatorParamValues,+ triggers: ReadonlySet<string>,+): boolean {+ switch (c.op) {+ case 'gt': return Number(params[c.param] ?? 0) > c.value;+ case 'lt': return Number(params[c.param] ?? 0) < c.value;+ case 'eq': return Number(params[c.param] ?? 0) === c.value;+ case 'neq': return Number(params[c.param] ?? 0) !== c.value;+ case 'true': return params[c.param] === true;+ case 'false': return params[c.param] === false;+ case 'trigger': return triggers.has(c.param);+ }+}++/** First transition in `list` whose conditions all hold, with the triggers it used. */+function firstReady(+ list: readonly AnimatorTransition[],+ params: AnimatorParamValues,+ triggers: ReadonlySet<string>,+): { to: string; usedTriggers: string[] } | null {+ for (const t of list) {+ const used: string[] = [];+ let ok = true;+ for (const c of t.conditions) {+ if (!conditionHolds(c, params, triggers)) { ok = false; break; }+ if (c.op === 'trigger') used.push(c.param);+ }+ if (ok) return { to: t.to, usedTriggers: used };+ }+ return null;+}++/**+ * Evaluate one step of the state machine. Any-state transitions are checked+ * before the current state's. Returns the next state (or null to stay) and the+ * triggers a fired transition consumed. Pure.+ */+export function evaluateAnimatorTransitions(+ def: AnimatorControllerDef,+ currentState: string,+ params: AnimatorParamValues,+ triggers: ReadonlySet<string>,+): AnimatorEvalResult {+ const fromAny = firstReady(def.anyStateTransitions ?? [], params, triggers);+ const current = def.states.find((s) => s.name === currentState);+ const fired = fromAny ?? firstReady(current?.transitions ?? [], params, triggers);+ return fired+ ? { next: fired.to, consumedTriggers: fired.usedTriggers }+ : { next: null, consumedTriggers: [] };+}++/** Merge a controller's declared parameter defaults with per-entity overrides. */+export function resolveParams(+ def: AnimatorControllerDef,+ overrides: ReadonlyMap<string, number | boolean>,+): Record<string, number | boolean> {+ const out: Record<string, number | boolean> = {};+ for (const p of def.parameters) {+ if (p.type === 'trigger') continue;+ out[p.name] = p.default ?? (p.type === 'bool' ? false : 0);+ }+ for (const [k, v] of overrides) out[k] = v;+ return out;+}++// =============================================================================+// Animator component+// =============================================================================++export interface AnimatorData {+ /** Registered controller name (see AnimatorControllerApi.registerController). */+ controller: string;+ /** Active state; empty until the first update seeds it from initialState. */+ currentState: string;+ enabled: boolean;+}++export const Animator: ComponentDef<AnimatorData> = defineComponent('Animator', {+ controller: '',+ currentState: '',+ enabled: true,+});++// =============================================================================+// AnimatorController — per-App registry + parameters + driving system+// =============================================================================++/**+ * Owns one App's animator-controller registry and per-entity parameter/trigger+ * values, evaluates each Animator's state machine, and drives the entity's+ * SpriteAnimator clip on state changes. Published as the {@link AnimatorController}+ * resource; read it as `app.getResource(AnimatorController)`.+ */+export class AnimatorControllerApi {+ private readonly controllers = new Map<string, AnimatorControllerDef>();+ private readonly params = new Map<Entity, Map<string, number | boolean>>();+ private readonly triggers = new Map<Entity, Set<string>>();++ // -- controller registry --------------------------------------------------++ registerController(name: string, def: AnimatorControllerDef): void {+ this.controllers.set(name, def);+ }++ unregisterController(name: string): void {+ this.controllers.delete(name);+ }++ getController(name: string): AnimatorControllerDef | undefined {+ return this.controllers.get(name);+ }++ clearControllers(): void {+ this.controllers.clear();+ }++ // -- parameters / triggers ------------------------------------------------++ setFloat(entity: Entity, name: string, value: number): void {+ this.paramStore(entity).set(name, value);+ }++ setBool(entity: Entity, name: string, value: boolean): void {+ this.paramStore(entity).set(name, value);+ }++ setTrigger(entity: Entity, name: string): void {+ this.triggerStore(entity).add(name);+ }++ resetTrigger(entity: Entity, name: string): void {+ this.triggers.get(entity)?.delete(name);+ }++ getFloat(entity: Entity, name: string): number {+ return Number(this.params.get(entity)?.get(name) ?? 0);+ }++ getBool(entity: Entity, name: string): boolean {+ return this.params.get(entity)?.get(name) === true;+ }++ /** Drop an entity's parameter/trigger state (wire to world.onDespawn). */+ removeEntity(entity: Entity): void {+ this.params.delete(entity);+ this.triggers.delete(entity);+ }++ private paramStore(entity: Entity): Map<string, number | boolean> {+ let m = this.params.get(entity);+ if (!m) { m = new Map(); this.params.set(entity, m); }+ return m;+ }++ private triggerStore(entity: Entity): Set<string> {+ let s = this.triggers.get(entity);+ if (!s) { s = new Set(); this.triggers.set(entity, s); }+ return s;+ }++ // -- per-frame system -----------------------------------------------------++ update(world: World): void {+ const entities = world.getEntitiesWithComponents([Animator]);+ for (const entity of entities) {+ const a = world.get(entity, Animator) as AnimatorData;+ if (!a.enabled) continue;++ const def = this.controllers.get(a.controller);+ if (!def || def.states.length === 0) continue;++ // Seed / repair the active state.+ const known = a.currentState && def.states.some((s) => s.name === a.currentState);+ const fromState = known ? a.currentState : def.initialState;++ const params = resolveParams(def, this.params.get(entity) ?? EMPTY_PARAMS);+ const triggerSet = this.triggers.get(entity);+ const { next, consumedTriggers } = evaluateAnimatorTransitions(+ def, fromState, params, triggerSet ?? EMPTY_TRIGGERS,+ );+ if (triggerSet) for (const t of consumedTriggers) triggerSet.delete(t);++ const target = next ?? fromState;+ if (target !== a.currentState) {+ a.currentState = target;+ this.applyState(world, entity, def, target);+ world.insert(entity, Animator, a);+ }+ }+ }++ /** Switch the entity's SpriteAnimator to the state's clip (restart from frame 0). */+ private applyState(world: World, entity: Entity, def: AnimatorControllerDef, stateName: string): void {+ const st = def.states.find((s) => s.name === stateName);+ if (!st || !world.has(entity, SpriteAnimator)) return;+ const sp = world.get(entity, SpriteAnimator) as SpriteAnimatorData;+ sp.clip = st.clip;+ sp.speed = st.speed ?? 1.0;+ sp.loop = st.loop ?? true;+ sp.currentFrame = 0;+ sp.frameTimer = 0;+ sp.playing = true;+ sp.enabled = true;+ world.insert(entity, SpriteAnimator, sp);+ }+}++const EMPTY_PARAMS: ReadonlyMap<string, number | boolean> = new Map();+const EMPTY_TRIGGERS: ReadonlySet<string> = new Set();++/**+ * Per-App animator resource (controller registry + per-entity parameters),+ * published by `AnimationPlugin`. Read as `app.getResource(AnimatorController)`.+ */+export const AnimatorController = defineResource<AnimatorControllerApi>(null!, 'AnimatorController');diff --git a/sdk/src/animation/index.ts b/sdk/src/animation/index.tsindex 659dd311f..ddfb9828c 100644--- a/sdk/src/animation/index.ts+++ b/sdk/src/animation/index.ts@@ -40,6 +40,23 @@ export {type SpriteAnimEventHandler,} from './SpriteAnimator';+export {+ Animator,+ AnimatorController,+ AnimatorControllerApi,+ evaluateAnimatorTransitions,+ resolveParams,+ type AnimatorData,+ type AnimatorParam,+ type AnimatorParamType,+ type AnimatorCondition,+ type AnimatorTransition,+ type AnimatorState,+ type AnimatorControllerDef,+ type AnimatorParamValues,+ type AnimatorEvalResult,+} from './Animator';+export {AnimationPlugin,animationPlugin,diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 93e87a53d..a57d91fe2 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -212,6 +212,20 @@ export {SpriteAnimator,SpriteAnimation,SpriteAnimationApi,+ Animator,+ AnimatorController,+ AnimatorControllerApi,+ evaluateAnimatorTransitions,+ resolveParams,+ type AnimatorData,+ type AnimatorParam,+ type AnimatorParamType,+ type AnimatorCondition,+ type AnimatorTransition,+ type AnimatorState,+ type AnimatorControllerDef,+ type AnimatorParamValues,+ type AnimatorEvalResult,AnimationPlugin,animationPlugin,type TweenOptions,diff --git a/sdk/src/systemLabels.ts b/sdk/src/systemLabels.tsindex d78219a22..4798ecfff 100644--- a/sdk/src/systemLabels.ts+++ b/sdk/src/systemLabels.ts@@ -26,4 +26,6 @@ export const SystemLabel = {Text: 'TextSystem',Focus: 'FocusSystem',Tween: 'TweenSystem',+ Animator: 'AnimatorSystem',+ SpriteAnimator: 'SpriteAnimatorSystem',} as const;diff --git a/sdk/tests/animator.test.ts b/sdk/tests/animator.test.tsnew file mode 100644index 000000000..ed2e9bb44--- /dev/null+++ b/sdk/tests/animator.test.ts@@ -0,0 +1,198 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import {+ Animator,+ AnimatorControllerApi,+ evaluateAnimatorTransitions,+ resolveParams,+ type AnimatorControllerDef,+ type AnimatorData,+} from '../src/animation/Animator';+import { SpriteAnimator, type SpriteAnimatorData } from '../src/animation/SpriteAnimator';++function heroController(): AnimatorControllerDef {+ return {+ parameters: [+ { name: 'speed', type: 'float', default: 0 },+ { name: 'grounded', type: 'bool', default: true },+ { name: 'jump', type: 'trigger' },+ ],+ initialState: 'idle',+ states: [+ { name: 'idle', clip: 'idle_clip', transitions: [+ { to: 'run', conditions: [{ param: 'speed', op: 'gt', value: 0.1 }] },+ ] },+ { name: 'run', clip: 'run_clip', speed: 1.5, loop: true, transitions: [+ { to: 'idle', conditions: [{ param: 'speed', op: 'lt', value: 0.1 }] },+ ] },+ { name: 'jump', clip: 'jump_clip', transitions: [+ { to: 'idle', conditions: [{ param: 'grounded', op: 'true' }] },+ ] },+ ],+ anyStateTransitions: [+ { to: 'jump', conditions: [{ param: 'jump', op: 'trigger' }] },+ ],+ };+}++// ---------------------------------------------------------------------------+// Pure evaluator+// ---------------------------------------------------------------------------++describe('evaluateAnimatorTransitions', () => {+ const def = heroController();++ it('fires a float-gt transition', () => {+ const r = evaluateAnimatorTransitions(def, 'idle', { speed: 5, grounded: true }, new Set());+ expect(r.next).toBe('run');+ expect(r.consumedTriggers).toEqual([]);+ });++ it('stays when no condition holds', () => {+ expect(evaluateAnimatorTransitions(def, 'idle', { speed: 0 }, new Set()).next).toBeNull();+ });++ it('fires the reverse float-lt transition', () => {+ expect(evaluateAnimatorTransitions(def, 'run', { speed: 0 }, new Set()).next).toBe('idle');+ });++ it('checks bool true/false', () => {+ expect(evaluateAnimatorTransitions(def, 'jump', { grounded: true }, new Set()).next).toBe('idle');+ expect(evaluateAnimatorTransitions(def, 'jump', { grounded: false }, new Set()).next).toBeNull();+ });++ it('any-state transition takes precedence over the current state', () => {+ // speed=5 would fire idle->run, but the any-state jump trigger wins.+ const r = evaluateAnimatorTransitions(def, 'idle', { speed: 5 }, new Set(['jump']));+ expect(r.next).toBe('jump');+ expect(r.consumedTriggers).toEqual(['jump']);+ });++ it('fires a trigger transition and reports it consumed', () => {+ const r = evaluateAnimatorTransitions(def, 'idle', { speed: 0 }, new Set(['jump']));+ expect(r.next).toBe('jump');+ expect(r.consumedTriggers).toEqual(['jump']);+ });++ it('eq / neq comparisons', () => {+ const d: AnimatorControllerDef = {+ parameters: [{ name: 'phase', type: 'float', default: 0 }],+ initialState: 'a',+ states: [+ { name: 'a', clip: 'a', transitions: [{ to: 'b', conditions: [{ param: 'phase', op: 'eq', value: 2 }] }] },+ { name: 'b', clip: 'b', transitions: [{ to: 'a', conditions: [{ param: 'phase', op: 'neq', value: 2 }] }] },+ ],+ };+ expect(evaluateAnimatorTransitions(d, 'a', { phase: 2 }, new Set()).next).toBe('b');+ expect(evaluateAnimatorTransitions(d, 'a', { phase: 1 }, new Set()).next).toBeNull();+ expect(evaluateAnimatorTransitions(d, 'b', { phase: 1 }, new Set()).next).toBe('a');+ });+});++describe('resolveParams', () => {+ const def = heroController();+ it('seeds declared defaults, excludes triggers', () => {+ expect(resolveParams(def, new Map())).toEqual({ speed: 0, grounded: true });+ });+ it('applies per-entity overrides', () => {+ expect(resolveParams(def, new Map<string, number | boolean>([['speed', 9]]))).toEqual({ speed: 9, grounded: true });+ });+});++// ---------------------------------------------------------------------------+// AnimatorControllerApi.update drives SpriteAnimator (mock World)+// ---------------------------------------------------------------------------++function makeWorld() {+ const store = new Map<unknown, Map<number, unknown>>();+ const mapOf = (c: unknown) => {+ let m = store.get(c);+ if (!m) { m = new Map(); store.set(c, m); }+ return m;+ };+ return {+ insert(e: number, c: unknown, data: unknown) { mapOf(c).set(e, data); },+ get(e: number, c: unknown) { return mapOf(c).get(e); },+ has(e: number, c: unknown) { return mapOf(c).has(e); },+ getEntitiesWithComponents(comps: unknown[]) {+ const [first, ...rest] = comps;+ return [...mapOf(first).keys()].filter((e) => rest.every((c) => mapOf(c).has(e)));+ },+ } as any;+}++function spriteData(over: Partial<SpriteAnimatorData> = {}): SpriteAnimatorData {+ return { clip: '', speed: 1, playing: false, loop: true, enabled: true, currentFrame: 5, frameTimer: 0.3, ...over };+}++describe('AnimatorControllerApi.update', () => {+ const E = 1;++ function setup() {+ const ctrl = new AnimatorControllerApi();+ ctrl.registerController('hero', heroController());+ const world = makeWorld();+ world.insert(E, Animator, { controller: 'hero', currentState: '', enabled: true } as AnimatorData);+ world.insert(E, SpriteAnimator, spriteData());+ return { ctrl, world };+ }++ it('seeds the initial state and applies its clip on first update', () => {+ const { ctrl, world } = setup();+ ctrl.update(world);+ expect((world.get(E, Animator) as AnimatorData).currentState).toBe('idle');+ const sp = world.get(E, SpriteAnimator) as SpriteAnimatorData;+ expect(sp.clip).toBe('idle_clip');+ expect(sp.currentFrame).toBe(0);+ expect(sp.frameTimer).toBe(0);+ expect(sp.playing).toBe(true);+ });++ it('transitions on a float parameter and switches the clip (with state speed/loop)', () => {+ const { ctrl, world } = setup();+ ctrl.update(world); // → idle+ ctrl.setFloat(E, 'speed', 5);+ ctrl.update(world); // → run+ expect((world.get(E, Animator) as AnimatorData).currentState).toBe('run');+ const sp = world.get(E, SpriteAnimator) as SpriteAnimatorData;+ expect(sp.clip).toBe('run_clip');+ expect(sp.speed).toBe(1.5);+ });++ it('transitions back when the parameter reverses', () => {+ const { ctrl, world } = setup();+ ctrl.update(world);+ ctrl.setFloat(E, 'speed', 5); ctrl.update(world);+ ctrl.setFloat(E, 'speed', 0); ctrl.update(world);+ expect((world.get(E, Animator) as AnimatorData).currentState).toBe('idle');+ });++ it('any-state trigger jumps, consumes the trigger, then returns', () => {+ const { ctrl, world } = setup();+ ctrl.update(world); // idle+ ctrl.setTrigger(E, 'jump');+ ctrl.update(world); // → jump (trigger consumed)+ expect((world.get(E, Animator) as AnimatorData).currentState).toBe('jump');+ // grounded defaults true → next update returns to idle, and the trigger+ // was consumed so it does not re-fire.+ ctrl.update(world);+ expect((world.get(E, Animator) as AnimatorData).currentState).toBe('idle');+ });++ it('disabled animator does not change state', () => {+ const { ctrl, world } = setup();+ world.insert(E, Animator, { controller: 'hero', currentState: 'run', enabled: false } as AnimatorData);+ ctrl.setFloat(E, 'speed', 0);+ ctrl.update(world);+ expect((world.get(E, Animator) as AnimatorData).currentState).toBe('run');+ });++ it('removeEntity drops parameter state', () => {+ const { ctrl } = setup();+ ctrl.setFloat(E, 'speed', 9);+ expect(ctrl.getFloat(E, 'speed')).toBe(9);+ ctrl.removeEntity(E);+ expect(ctrl.getFloat(E, 'speed')).toBe(0);+ });+});