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(anim): load .esanimator controllers by path at runtime

esengine3359497083b1
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index d5141014d..fcc240712 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -850,6 +850,8 @@ class ProjectStoreImpl {
return assets.loadStateMachine(path);
case 'behaviortree':
return assets.loadBehaviorTree(path);
+ case 'animatorcontroller':
+ return assets.loadAnimatorController(path);
default:
return Promise.reject(new Error(`no live loader for asset slot type "${fieldType}"`));
}
diff --git a/examples/sprite-animation/assets/animations/player.esanimator b/examples/sprite-animation/assets/animations/player.esanimator
index 1172fa0bd..88ab4b80c 100644
--- a/examples/sprite-animation/assets/animations/player.esanimator
+++ b/examples/sprite-animation/assets/animations/player.esanimator
@@ -1,13 +1,46 @@
{
"parameters": [
- { "name": "Speed", "type": "float" },
- { "name": "Jump", "type": "trigger" }
- ],
- "states": [
- { "name": "Idle", "x": 120, "y": 130, "clip": "assets/animations/idle.esanim", "loop": true, "transitions": [ { "to": "Run", "conditions": [ { "param": "Speed", "op": "gt", "value": 0.1 } ] } ] },
- { "name": "Run", "x": 380, "y": 130, "clip": "assets/animations/walk.esanim", "loop": true, "transitions": [ { "to": "Idle", "conditions": [ { "param": "Speed", "op": "lt", "value": 0.1 } ] } ] },
- { "name": "Jump", "x": 250, "y": 320, "transitions": [ { "to": "Idle", "hasExitTime": true, "conditions": [] } ] }
+ { "name": "speed", "type": "float", "default": 0 },
+ { "name": "hop", "type": "trigger" }
],
"initialState": "Idle",
- "anyStateTransitions": [ { "to": "Jump", "conditions": [ { "param": "Jump", "op": "trigger" } ] } ]
+ "states": [
+ {
+ "name": "Idle",
+ "x": 140,
+ "y": 140,
+ "clip": "assets/animations/idle.esanim",
+ "loop": true,
+ "transitions": [
+ { "to": "Move", "conditions": [ { "param": "speed", "op": "gt", "value": 20 } ] },
+ { "to": "Hop", "conditions": [ { "param": "hop", "op": "trigger" } ] }
+ ]
+ },
+ {
+ "name": "Move",
+ "x": 420,
+ "y": 140,
+ "blend": {
+ "parameter": "speed",
+ "thresholds": [
+ { "value": 0, "clip": "assets/animations/walk.esanim", "speed": 1.0 },
+ { "value": 150, "clip": "assets/animations/walk.esanim", "speed": 1.9 }
+ ]
+ },
+ "transitions": [
+ { "to": "Idle", "conditions": [ { "param": "speed", "op": "lt", "value": 15 } ] },
+ { "to": "Hop", "conditions": [ { "param": "hop", "op": "trigger" } ] }
+ ]
+ },
+ {
+ "name": "Hop",
+ "x": 280,
+ "y": 340,
+ "clip": "hop",
+ "loop": false,
+ "transitions": [
+ { "to": "Idle", "hasExitTime": true, "conditions": [] }
+ ]
+ }
+ ]
}
diff --git a/examples/sprite-animation/assets/scenes/main.esscene b/examples/sprite-animation/assets/scenes/main.esscene
index 492d61a5a..f64d4e1b4 100644
--- a/examples/sprite-animation/assets/scenes/main.esscene
+++ b/examples/sprite-animation/assets/scenes/main.esscene
@@ -101,7 +101,7 @@
{
"type": "Animator",
"data": {
- "controller": "alien"
+ "controller": "assets/animations/player.esanimator"
}
},
{
diff --git a/examples/sprite-animation/src/config.ts b/examples/sprite-animation/src/config.ts
index 9db99267d..008d9476f 100644
--- a/examples/sprite-animation/src/config.ts
+++ b/examples/sprite-animation/src/config.ts
@@ -5,21 +5,14 @@ export const CLIP_IDLE = 'assets/animations/idle.esanim';
export const CLIP_WALK = 'assets/animations/walk.esanim';
// The hop clip is registered from code at startup (see systems/setup.ts) —
// the second authoring path: a SpriteAnimClip built out of already-loaded frames.
+// The state machine's own tuning (blend threshold, Idle↔Move hysteresis) lives
+// in the authored controller, assets/animations/player.esanimator.
export const CLIP_HOP = 'hop';
-// The controller name the scene's Animator component references.
-export const CONTROLLER = 'alien';
-
-// Movement (world px). `speed` is also the Animator's float parameter, so the
-// blend threshold below is in the same unit.
+// Movement (world px). `speed` is also the Animator's float parameter.
export const WALK_SPEED = 110;
export const RUN_SPEED = 210;
export const ACCEL = 900;
-/** Above this |speed| the Move blend selects the fast (run) row. */
-export const RUN_BLEND_AT = 150;
-/** Idle↔Move hysteresis thresholds on the `speed` parameter. */
-export const MOVE_ENTER = 20;
-export const MOVE_EXIT = 15;
/** How far the player may roam from the centre. */
export const RANGE_X = 180;
diff --git a/examples/sprite-animation/src/systems/setup.ts b/examples/sprite-animation/src/systems/setup.ts
index a7436da5c..7eb3dd7c4 100644
--- a/examples/sprite-animation/src/systems/setup.ts
+++ b/examples/sprite-animation/src/systems/setup.ts
@@ -1,64 +1,18 @@
import {
defineSystem, Res,
- AnimatorController, AnimatorControllerAPI, type AnimatorControllerDef,
SpriteAnimation, SpriteAnimationAPI,
} from 'esengine';
-import {
- CLIP_IDLE, CLIP_WALK, CLIP_HOP, CONTROLLER,
- MOVE_ENTER, MOVE_EXIT, RUN_BLEND_AT,
-} from '../config';
+import { CLIP_IDLE, CLIP_WALK, CLIP_HOP } from '../config';
import { footsteps } from '../components';
-// The character's state machine (Unity Animator model): a float `speed`
-// parameter drives Idle↔Move, Move is a 1D blend that re-selects its clip as
-// `speed` crosses a threshold (same walk clip, faster playback = run), and a
-// `hop` trigger fires a non-looping clip whose end (exit time) auto-returns
-// to Idle. The scene's Animator component references this by name.
-const alienController: AnimatorControllerDef = {
- parameters: [
- { name: 'speed', type: 'float', default: 0 },
- { name: 'hop', type: 'trigger' },
- ],
- initialState: 'Idle',
- states: [
- {
- name: 'Idle',
- clip: CLIP_IDLE,
- transitions: [
- { to: 'Move', conditions: [{ param: 'speed', op: 'gt', value: MOVE_ENTER }] },
- { to: 'Hop', conditions: [{ param: 'hop', op: 'trigger' }] },
- ],
- },
- {
- name: 'Move',
- blend: {
- parameter: 'speed',
- thresholds: [
- { value: 0, clip: CLIP_WALK, speed: 1.0 },
- { value: RUN_BLEND_AT, clip: CLIP_WALK, speed: 1.9 },
- ],
- },
- transitions: [
- { to: 'Idle', conditions: [{ param: 'speed', op: 'lt', value: MOVE_EXIT }] },
- { to: 'Hop', conditions: [{ param: 'hop', op: 'trigger' }] },
- ],
- },
- {
- name: 'Hop',
- clip: CLIP_HOP,
- loop: false,
- // No conditions + exit time = advance when the clip finishes.
- transitions: [{ to: 'Idle', conditions: [], hasExitTime: true }],
- },
- ],
-};
-
-// One-time wiring that needs no assets: the controller (pure data) and the
-// footstep listener (inert until events are attached below).
+// The character's state machine (Idle↔Move 1D blend + a `hop` trigger) is
+// authored in the editor and lives on disk as `player.esanimator`; the scene's
+// Animator references it BY PATH, and the runtime asset loader registers it
+// before the first tick — so there is no code-registered controller here. This
+// system only wires the footstep listener (inert until events attach below).
export const setupSystem = defineSystem(
- [Res(AnimatorController), Res(SpriteAnimation)],
- (ctrl: AnimatorControllerAPI, anim: SpriteAnimationAPI) => {
- ctrl.registerController(CONTROLLER, alienController);
+ [Res(SpriteAnimation)],
+ (anim: SpriteAnimationAPI) => {
anim.onEventGlobal((event) => {
if (event.name === 'footstep') footsteps.pending++;
});
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 855a18ae1..7f907c3f7 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: 1292 stable · 17 beta · 0 deprecated
+Symbols: 1295 stable · 17 beta · 0 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -286,7 +286,7 @@ setFloat: (entity: Entity, name: string, value: number) => void
setSpineDriver: (driver: SpineAnimationDriver | null) => void
setTrigger: (entity: Entity, name: string) => void
unregisterController: (name: string) => void
-update: (world: World) => void
+update: (world: World, resolveKey?: (ref: string) => string) => void
static new (): AnimatorControllerAPI
static prototype: AnimatorControllerAPI
```
@@ -493,7 +493,7 @@ static prototype: ArrayDataSource<any>
## AssetFieldType — type
```
-'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree'
+'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'animatorcontroller'
```
## AssetPlugin — class
@@ -8030,6 +8030,11 @@ BtPlugin
(): void
```
+## clearAnimatorControllerStore — function
+```
+(): void
+```
+
## clearBtStore — function
```
(): void
@@ -8660,6 +8665,11 @@ FsmPlugin
(): PlatformAdapter["name"] | null
```
+## getRegisteredAnimatorController — function
+```
+(key: string): AnimatorControllerDef | undefined
+```
+
## getReplicatedFields — function
```
(name: string): readonly string[]
@@ -9250,6 +9260,11 @@ PrefabsPlugin
(name: string, fn: AiAction<AiContext>): void
```
+## registerAnimatorController — function
+```
+(key: string, def: AnimatorControllerDef): void
+```
+
## registerAssetBuildTransform — function
```
(editorType: EditorAssetType, transform: AssetBuildTransform): void
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 640050f71..00b3b3726 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: 1291 stable · 19 beta · 0 deprecated
+Symbols: 1294 stable · 19 beta · 0 deprecated
## ANCHOR_AXES — const
```
@@ -281,7 +281,7 @@ setFloat: (entity: Entity, name: string, value: number) => void
setSpineDriver: (driver: SpineAnimationDriver | null) => void
setTrigger: (entity: Entity, name: string) => void
unregisterController: (name: string) => void
-update: (world: World) => void
+update: (world: World, resolveKey?: (ref: string) => string) => void
static new (): AnimatorControllerAPI
static prototype: AnimatorControllerAPI
```
@@ -488,7 +488,7 @@ static prototype: ArrayDataSource<any>
## AssetFieldType — type
```
-'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree'
+'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'animatorcontroller'
```
## AssetPlugin — class
@@ -8025,6 +8025,11 @@ BtPlugin
(): void
```
+## clearAnimatorControllerStore — function
+```
+(): void
+```
+
## clearBtStore — function
```
(): void
@@ -8655,6 +8660,11 @@ FsmPlugin
(): PlatformAdapter["name"] | null
```
+## getRegisteredAnimatorController — function
+```
+(key: string): AnimatorControllerDef | undefined
+```
+
## getReplicatedFields — function
```
(name: string): readonly string[]
@@ -9255,6 +9265,11 @@ PrefabsPlugin
(name: string, fn: AiAction<AiContext>): void
```
+## registerAnimatorController — function
+```
+(key: string, def: AnimatorControllerDef): void
+```
+
## registerAssetBuildTransform — function
```
(editorType: EditorAssetType, transform: AssetBuildTransform): void
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 3d80a0498..a97ce2dfe 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1302 stable · 17 beta · 0 deprecated
+Symbols: 1305 stable · 17 beta · 0 deprecated
## ANCHOR_AXES — const
```
@@ -281,7 +281,7 @@ setFloat: (entity: Entity, name: string, value: number) => void
setSpineDriver: (driver: SpineAnimationDriver | null) => void
setTrigger: (entity: Entity, name: string) => void
unregisterController: (name: string) => void
-update: (world: World) => void
+update: (world: World, resolveKey?: (ref: string) => string) => void
static new (): AnimatorControllerAPI
static prototype: AnimatorControllerAPI
```
@@ -488,7 +488,7 @@ static prototype: ArrayDataSource<any>
## AssetFieldType — type
```
-'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree'
+'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'animatorcontroller'
```
## AssetPlugin — class
@@ -8049,6 +8049,11 @@ BtPlugin
(): void
```
+## clearAnimatorControllerStore — function
+```
+(): void
+```
+
## clearBtStore — function
```
(): void
@@ -8679,6 +8684,11 @@ FsmPlugin
(): PlatformAdapter["name"] | null
```
+## getRegisteredAnimatorController — function
+```
+(key: string): AnimatorControllerDef | undefined
+```
+
## getReplicatedFields — function
```
(name: string): readonly string[]
@@ -9274,6 +9284,11 @@ PrefabsPlugin
(name: string, fn: AiAction<AiContext>): void
```
+## registerAnimatorController — function
+```
+(key: string, def: AnimatorControllerDef): void
+```
+
## registerAssetBuildTransform — function
```
(editorType: EditorAssetType, transform: AssetBuildTransform): void
diff --git a/sdk/src/animation/AnimationPlugin.ts b/sdk/src/animation/AnimationPlugin.ts
index 9ff90e062..5fc228e25 100644
--- a/sdk/src/animation/AnimationPlugin.ts
+++ b/sdk/src/animation/AnimationPlugin.ts
@@ -14,6 +14,8 @@ import type { ESEngineModule, CppRegistry } from '../wasm';
import { Tween, TweenAPI } from './Tween';
import { SpriteAnimation, SpriteAnimationAPI } from './SpriteAnimator';
import { AnimatorController, AnimatorControllerAPI } from './Animator';
+import { Assets } from '../asset/AssetPlugin';
+import { resolveAssetKey } from '../asset/resolveAssetKey';
import { playModeOnly } from '../env';
import { SystemLabel } from '../systemLabels';
@@ -46,12 +48,19 @@ export class AnimationPlugin implements Plugin {
{ name: 'TweenSystem' }
), { runIf: playModeOnly });
+ // Resolve a `.esanimator` controller ref to the load path its loader keyed
+ // the store with (an `estella://…` URL in the play realm), matching the FSM
+ // plugin — without it, an Animator referencing a controller BY PATH resolves
+ // to nothing at runtime and silently never seeds a state.
+ const resolveKey = (ref: string): string =>
+ resolveAssetKey(app.hasResource(Assets) ? app.getResource(Assets) : null, ref);
+
// 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);
+ ctrl.update(world, resolveKey);
},
{ name: 'AnimatorSystem' }
), { runAfter: [SystemLabel.Tween], runIf: playModeOnly });
diff --git a/sdk/src/animation/Animator.ts b/sdk/src/animation/Animator.ts
index 1d2fbdebb..f5a0feba4 100644
--- a/sdk/src/animation/Animator.ts
+++ b/sdk/src/animation/Animator.ts
@@ -18,6 +18,7 @@
import { defineComponent, type ComponentDef } from '../component';
import { defineResource } from '../resource';
+import { isUuidRef } from '../asset/AssetRegistry';
import type { Entity } from '../types';
import type { World } from '../world';
import { SpriteAnimator, type SpriteAnimatorData } from './SpriteAnimator';
@@ -351,8 +352,45 @@ export const Animator: ComponentDef<AnimatorData> = defineComponent('Animator',
controller: '',
currentState: '',
enabled: true,
+}, {
+ assetFields: [{ field: 'controller', type: 'animatorcontroller' }],
+ // Preload a `.esanimator` path (or an editor-serialized uuid ref) with the
+ // scene so the controller is registered before the first tick. A plain
+ // `registerController` name (code path) is left alone — this callback is the
+ // discovery authority; the assetField above only drives the editor picker.
+ discoverAssets: data => {
+ const c = data.controller;
+ return typeof c === 'string' && (c.endsWith('.esanimator') || isUuidRef(c))
+ ? [{ type: 'animatorcontroller', path: c }]
+ : [];
+ },
});
+/**
+ * Global controller store keyed by `.esanimator` asset path — the runtime twin of
+ * the per-App {@link AnimatorControllerAPI.registerController} name registry. The
+ * asset loader registers a disk controller here (the App resource isn't reachable
+ * from a `LoadContext`), and {@link AnimatorControllerAPI} falls back to it when an
+ * Animator's `controller` is a path rather than a code-registered name. Mirrors the
+ * FSM store in {@link file://./ai/fsm/StateMachineAgent.ts}.
+ */
+const animatorControllerStore = new Map<string, AnimatorControllerDef>();
+
+/** Register a controller under `key` (an asset path); the loader and any code
+ * path that keys by path share this store. */
+export function registerAnimatorController(key: string, def: AnimatorControllerDef): void {
+ animatorControllerStore.set(key, def);
+}
+
+export function getRegisteredAnimatorController(key: string): AnimatorControllerDef | undefined {
+ return animatorControllerStore.get(key);
+}
+
+/** Drop all path-registered controllers (tests / hot-reload). */
+export function clearAnimatorControllerStore(): void {
+ animatorControllerStore.clear();
+}
+
// =============================================================================
// AnimatorController — per-App registry + parameters + driving system
// =============================================================================
@@ -386,7 +424,9 @@ export class AnimatorControllerAPI {
}
getController(name: string): AnimatorControllerDef | undefined {
- return this.controllers.get(name);
+ // A code-registered name wins; otherwise fall back to a controller the
+ // asset loader registered under its `.esanimator` path.
+ return this.controllers.get(name) ?? getRegisteredAnimatorController(name);
}
clearControllers(): void {
@@ -439,13 +479,19 @@ export class AnimatorControllerAPI {
// -- per-frame system -----------------------------------------------------
- update(world: World): void {
+ update(world: World, resolveKey?: (ref: string) => string): 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);
+ // A code-registered NAME wins; otherwise the controller was loaded from
+ // a `.esanimator` asset and lives in the path store under its RESOLVED
+ // load path (e.g. `estella://…` in the play realm). Resolve the ref the
+ // same way the loader keyed it before falling back to the raw ref.
+ const def = this.controllers.get(a.controller)
+ ?? getRegisteredAnimatorController(resolveKey ? resolveKey(a.controller) : a.controller)
+ ?? getRegisteredAnimatorController(a.controller);
if (!def || def.states.length === 0) continue;
// Seed / repair the active state path. The path descends into a
diff --git a/sdk/src/animation/index.ts b/sdk/src/animation/index.ts
index 938a16edb..f6cb4aa66 100644
--- a/sdk/src/animation/index.ts
+++ b/sdk/src/animation/index.ts
@@ -44,6 +44,9 @@ export {
Animator,
AnimatorController,
AnimatorControllerAPI,
+ registerAnimatorController,
+ getRegisteredAnimatorController,
+ clearAnimatorControllerStore,
evaluateAnimatorTransitions,
evaluateAnimatorPath,
enterStatePath,
diff --git a/sdk/src/asset/AssetFieldRegistry.ts b/sdk/src/asset/AssetFieldRegistry.ts
index 212886825..0e275213c 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' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree';
+export type AssetFieldType = 'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'animatorcontroller';
export interface AssetFieldDescriptor {
field: string;
diff --git a/sdk/src/asset/AssetLoader.ts b/sdk/src/asset/AssetLoader.ts
index dc0c637ec..da3ba66e8 100644
--- a/sdk/src/asset/AssetLoader.ts
+++ b/sdk/src/asset/AssetLoader.ts
@@ -59,6 +59,10 @@ export interface FsmResult {
fsmId: string;
}
+export interface AnimatorControllerResult {
+ controllerId: string;
+}
+
export interface LocaleResult {
/** The locale the table's entries were merged into. */
locale: string;
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index 7ee0aa757..2c1b63084 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -8,7 +8,7 @@ import type {
AssetLoader, LoadContext, TextureResult, SpineResult,
MaterialResult, FontResult, AudioResult, AnimClipResult,
TilemapResult, TilesetResult, TimelineResult, PrefabResult,
- LocaleResult, FsmResult, BtResult,
+ LocaleResult, FsmResult, BtResult, AnimatorControllerResult,
} from './AssetLoader';
import { AsyncCache } from './AsyncCache';
import type { ESEngineModule } from '../wasm';
@@ -26,6 +26,7 @@ import { TilesetAssetLoader } from './loaders/TilesetAssetLoader';
import { TimelineAssetLoader } from './loaders/TimelineAssetLoader';
import { PrefabAssetLoader } from './loaders/PrefabAssetLoader';
import { FsmAssetLoader } from './loaders/FsmAssetLoader';
+import { AnimatorControllerAssetLoader } from './loaders/AnimatorControllerAssetLoader';
import { BtAssetLoader } from './loaders/BtAssetLoader';
import { LocaleAssetLoader } from './loaders/LocaleAssetLoader';
import type { SpineModuleController } from '../spine/SpineController';
@@ -370,6 +371,12 @@ export class Assets {
return this.loadTyped('behaviortree', ref);
}
+ /** Load a `.esanimator` controller into the shared animator store, keyed by
+ * its asset path — the ref an Animator's `controller` field resolves. */
+ async loadAnimatorController(ref: string): Promise<AnimatorControllerResult> {
+ return this.loadTyped('animatorcontroller', ref);
+ }
+
async loadPrefab(ref: string): Promise<PrefabResult> {
return this.loadTyped('prefab', ref);
}
@@ -711,6 +718,7 @@ export class Assets {
const timelinePaths = discovered.byType.get('timeline') ?? new Set<string>();
const fsmPaths = discovered.byType.get('statemachine') ?? new Set<string>();
const btPaths = discovered.byType.get('behaviortree') ?? new Set<string>();
+ const animatorPaths = discovered.byType.get('animatorcontroller') ?? new Set<string>();
const spinePairs = discovered.spines;
const textureHandles = new Map<string, number>();
@@ -787,6 +795,7 @@ export class Assets {
// fsm/bt is that path resolves once the scene finishes preloading.
pushFireAndForget(fsmPaths, p => this.loadTyped('statemachine', p), 'statemachine');
pushFireAndForget(btPaths, p => this.loadTyped('behaviortree', p), 'behaviortree');
+ pushFireAndForget(animatorPaths, p => this.loadTyped('animatorcontroller', p), 'animatorcontroller');
const totalCount = tasks.length;
onProgress?.(0, totalCount);
@@ -1176,6 +1185,7 @@ export class Assets {
this.register(new TimelineAssetLoader());
this.register(new PrefabAssetLoader());
this.register(new FsmAssetLoader());
+ this.register(new AnimatorControllerAssetLoader());
this.register(new BtAssetLoader());
this.register(new LocaleAssetLoader());
}
diff --git a/sdk/src/asset/loaders/AnimatorControllerAssetLoader.ts b/sdk/src/asset/loaders/AnimatorControllerAssetLoader.ts
new file mode 100644
index 000000000..94bad0179
--- /dev/null
+++ b/sdk/src/asset/loaders/AnimatorControllerAssetLoader.ts
@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file AnimatorControllerAssetLoader.ts
+ * @brief Loads a `.esanimator` and registers it under its path in the global
+ * animator-controller store, so an Animator whose `controller` is that
+ * path resolves at runtime.
+ *
+ * The `.esanimator` payload IS a runtime AnimatorControllerDef (plus editor-only
+ * canvas positions on each state, which the interpreter ignores) — no compile
+ * step. Mirrors {@link file://./FsmAssetLoader.ts}.
+ */
+
+import type { AssetLoader, LoadContext, AnimatorControllerResult } from '../AssetLoader';
+import { registerAnimatorController } from '../../animation/Animator';
+import type { AnimatorControllerDef } from '../../animation/Animator';
+
+export class AnimatorControllerAssetLoader implements AssetLoader<AnimatorControllerResult> {
+ readonly type = 'animatorcontroller';
+ readonly extensions = ['.esanimator'];
+
+ async load(path: string, ctx: LoadContext): Promise<AnimatorControllerResult> {
+ const buildPath = ctx.catalog.getBuildPath(path);
+ const text = await ctx.loadText(buildPath);
+ const def = JSON.parse(text) as AnimatorControllerDef;
+ registerAnimatorController(path, def);
+ return { controllerId: path };
+ }
+
+ unload(): void {
+ // Controllers are registered globally in the shared store.
+ }
+}
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index e07015aad..ff37de94d 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -247,6 +247,9 @@ export {
Animator,
AnimatorController,
AnimatorControllerAPI,
+ registerAnimatorController,
+ getRegisteredAnimatorController,
+ clearAnimatorControllerStore,
evaluateAnimatorTransitions,
resolveParams,
selectBlendClip,
diff --git a/sdk/src/scene.ts b/sdk/src/scene.ts
index bf6045ac9..e0176fcd8 100644
--- a/sdk/src/scene.ts
+++ b/sdk/src/scene.ts
@@ -106,7 +106,7 @@ export class MissingAssetsError extends Error {
// Asset Field Types
// =============================================================================
-export type AssetFieldType = 'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree';
+export type AssetFieldType = 'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'animatorcontroller';
// =============================================================================
// Component Query Helpers (read from self-describing ComponentDef)
diff --git a/sdk/tests/animator.test.ts b/sdk/tests/animator.test.ts
index 0a56abdcb..e8e32e641 100644
--- a/sdk/tests/animator.test.ts
+++ b/sdk/tests/animator.test.ts
@@ -1,9 +1,12 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, beforeEach } from 'vitest';
import {
Animator,
AnimatorControllerAPI,
+ registerAnimatorController,
+ getRegisteredAnimatorController,
+ clearAnimatorControllerStore,
evaluateAnimatorTransitions,
resolveParams,
selectBlendClip,
@@ -12,6 +15,8 @@ import {
type AnimatorData,
} from '../src/animation/Animator';
import { SpriteAnimator, type SpriteAnimatorData } from '../src/animation/SpriteAnimator';
+import { AnimatorControllerAssetLoader } from '../src/asset/loaders/AnimatorControllerAssetLoader';
+import type { LoadContext } from '../src/asset/AssetLoader';
function heroController(): AnimatorControllerDef {
return {
@@ -361,3 +366,69 @@ describe('AnimatorControllerAPI.update', () => {
expect((world.get(E, SpriteAnimator) as SpriteAnimatorData).clip).toBe('idle');
});
});
+
+// ---------------------------------------------------------------------------
+// Runtime load-by-path: the .esanimator loader + global store + API fallback.
+// Closes the gap where a controller was editable but a Play-time Animator whose
+// `controller` is an asset path resolved to nothing and silently did nothing.
+// ---------------------------------------------------------------------------
+
+describe('AnimatorController runtime load-by-path', () => {
+ const E = 1;
+ const PATH = 'assets/animations/player.esanimator';
+
+ beforeEach(() => clearAnimatorControllerStore());
+
+ it('the global store round-trips and clears', () => {
+ expect(getRegisteredAnimatorController(PATH)).toBeUndefined();
+ registerAnimatorController(PATH, heroController());
+ expect(getRegisteredAnimatorController(PATH)?.initialState).toBe('idle');
+ clearAnimatorControllerStore();
+ expect(getRegisteredAnimatorController(PATH)).toBeUndefined();
+ });
+
+ it('getController falls back to the path store when the name is not code-registered', () => {
+ const ctrl = new AnimatorControllerAPI();
+ expect(ctrl.getController(PATH)).toBeUndefined();
+ registerAnimatorController(PATH, heroController());
+ expect(ctrl.getController(PATH)?.initialState).toBe('idle');
+ });
+
+ it('update() drives an Animator whose controller is ONLY in the path store', () => {
+ const ctrl = new AnimatorControllerAPI(); // nothing registered by name
+ registerAnimatorController(PATH, heroController());
+ const world = makeWorld();
+ world.insert(E, Animator, { controller: PATH, currentState: '', enabled: true } as AnimatorData);
+ world.insert(E, SpriteAnimator, spriteData());
+
+ ctrl.update(world); // seeds from the path-loaded controller
+ expect((world.get(E, Animator) as AnimatorData).currentState).toBe('idle');
+ expect((world.get(E, SpriteAnimator) as SpriteAnimatorData).clip).toBe('idle_clip');
+
+ ctrl.setFloat(E, 'speed', 5); ctrl.update(world);
+ expect((world.get(E, SpriteAnimator) as SpriteAnimatorData).clip).toBe('run_clip');
+ });
+
+ it('a code-registered name wins over a path store entry of the same key', () => {
+ const ctrl = new AnimatorControllerAPI();
+ ctrl.registerController(PATH, { ...heroController(), initialState: 'run' });
+ registerAnimatorController(PATH, heroController()); // initialState 'idle'
+ expect(ctrl.getController(PATH)?.initialState).toBe('run'); // code path wins
+ });
+
+ it('the .esanimator loader parses the payload and registers it under its path', async () => {
+ const loader = new AnimatorControllerAssetLoader();
+ expect(loader.type).toBe('animatorcontroller');
+ expect(loader.extensions).toEqual(['.esanimator']);
+
+ const payload = JSON.stringify(heroController());
+ const ctx = {
+ catalog: { getBuildPath: (p: string) => p },
+ loadText: async () => payload,
+ } as unknown as LoadContext;
+
+ const result = await loader.load(PATH, ctx);
+ expect(result.controllerId).toBe(PATH);
+ expect(getRegisteredAnimatorController(PATH)?.initialState).toBe('idle');
+ });
+});