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): a controller is a STACK of machines, not one

esenginee1653d426ffe
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index e998db0dc..a7027c068 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 114,
"beta": 101,
- "experimental": 1847,
+ "experimental": 1854,
"deprecated": 3
},
- "total": 2062,
+ "total": 2069,
"subsystems": [
{
"id": "ecs",
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 67a3eb48d..b5fa37ef3 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -16,6 +16,11 @@
"type": "string",
"default": "empty"
},
+ {
+ "key": "layerStates",
+ "type": "array",
+ "default": "empty"
+ },
{
"key": "enabled",
"type": "boolean",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index d26297254..ae77fe06e 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: 114 public · 94 beta · 1686 experimental · 3 deprecated
+Symbols: 114 public · 94 beta · 1693 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -13,6 +13,11 @@ Symbols: 114 public · 94 beta · 1686 experimental · 3 deprecated
readonly AnchorAxis[]
```
+## ANIMATOR_FORMAT_VERSION — const @experimental
+```
+2
+```
+
## ANIM_CLIP_FORMAT_VERSION — const @experimental
```
"1.5"
@@ -483,8 +488,10 @@ static prototype: AnimatorControllerAPI
```
anyStateTransitions: AnimatorTransition[] | undefined
initialState: string
+layers: AnimatorLayer[] | undefined
parameters: AnimatorParam[]
states: AnimatorState[]
+version: number | undefined
```
## AnimatorData — interface @beta
@@ -492,6 +499,7 @@ states: AnimatorState[]
controller: string
currentState: string
enabled: boolean
+layerStates: string[]
```
## AnimatorEdge — type @experimental
@@ -527,6 +535,21 @@ value: number
send: (event: AnimatorEventPayload) => void
```
+## AnimatorLayer — interface @experimental
+```
+anyStateTransitions: AnimatorTransition[] | undefined
+blend: AnimatorLayerBlend | undefined
+initialState: string
+name: string
+states: AnimatorState[]
+weight: number | undefined
+```
+
+## AnimatorLayerBlend — type @experimental
+```
+'override' | 'additive'
+```
+
## AnimatorMotion — type @experimental
```
| AnimatorClipMotion | AnimatorBlend1DMotion | AnimatorBlend2DMotion
@@ -10727,6 +10750,16 @@ AnimationPlugin
(def: AnimatorControllerDef): AnimatorEdge[]
```
+## animatorLayer — function @experimental
+```
+(def: AnimatorControllerDef, index: number): AnimatorScope | null
+```
+
+## animatorLayerCount — function @experimental
+```
+(def: AnimatorControllerDef): number
+```
+
## applyAreasToGrid — function @experimental
```
(grid: NavGrid, areas: ReadonlyArray<NavAreaBox & { cost: number; }>): void
@@ -11674,12 +11707,12 @@ DragPlugin
## evaluateAnimatorPath — function @experimental
```
-(def: AnimatorControllerDef, currentPath: string, params: AnimatorParamValues, triggers: ReadonlySet<string>, clipFinished?: boolean): AnimatorPathEvalResult
+(def: AnimatorScope, currentPath: string, params: AnimatorParamValues, triggers: ReadonlySet<string>, clipFinished?: boolean): AnimatorPathEvalResult
```
## evaluateAnimatorTransitions — function @experimental
```
-(def: AnimatorControllerDef, currentState: string, params: AnimatorParamValues, triggers: ReadonlySet<string>, clipFinished?: boolean): AnimatorEvalResult
+(def: AnimatorScope, currentState: string, params: AnimatorParamValues, triggers: ReadonlySet<string>, clipFinished?: boolean): AnimatorEvalResult
```
## evaluateChannel — function @experimental
@@ -12282,9 +12315,14 @@ InputRouter
(layer: number, ySortMask: number, depthMask: number): LayerOrder
```
+## layerState — function @experimental
+```
+(a: AnimatorData, index: number): string
+```
+
## leafStateOf — function @experimental
```
-(def: AnimatorControllerDef, path: string): AnimatorState | null
+(def: AnimatorScope, path: string): AnimatorState | null
```
## lifecyclePlugin — const @experimental
@@ -13387,6 +13425,11 @@ ServicesPlugin
(def: FsmDefinition, name: string): FsmDefinition
```
+## setLayerState — function @experimental
+```
+(a: AnimatorData, index: number, path: string): void
+```
+
## setLogLevel — function @experimental
```
(level: LogLevel): void
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 4c31d723c..84cca8061 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.native
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 114 public · 99 beta · 1705 experimental · 3 deprecated
+Symbols: 114 public · 99 beta · 1712 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -13,6 +13,11 @@ Symbols: 114 public · 99 beta · 1705 experimental · 3 deprecated
readonly AnchorAxis[]
```
+## ANIMATOR_FORMAT_VERSION — const @experimental
+```
+2
+```
+
## ANIM_CLIP_FORMAT_VERSION — const @experimental
```
"1.5"
@@ -483,8 +488,10 @@ static prototype: AnimatorControllerAPI
```
anyStateTransitions: AnimatorTransition[] | undefined
initialState: string
+layers: AnimatorLayer[] | undefined
parameters: AnimatorParam[]
states: AnimatorState[]
+version: number | undefined
```
## AnimatorData — interface @beta
@@ -492,6 +499,7 @@ states: AnimatorState[]
controller: string
currentState: string
enabled: boolean
+layerStates: string[]
```
## AnimatorEdge — type @experimental
@@ -527,6 +535,21 @@ value: number
send: (event: AnimatorEventPayload) => void
```
+## AnimatorLayer — interface @experimental
+```
+anyStateTransitions: AnimatorTransition[] | undefined
+blend: AnimatorLayerBlend | undefined
+initialState: string
+name: string
+states: AnimatorState[]
+weight: number | undefined
+```
+
+## AnimatorLayerBlend — type @experimental
+```
+'override' | 'additive'
+```
+
## AnimatorMotion — type @experimental
```
| AnimatorClipMotion | AnimatorBlend1DMotion | AnimatorBlend2DMotion
@@ -10920,6 +10943,16 @@ AnimationPlugin
(def: AnimatorControllerDef): AnimatorEdge[]
```
+## animatorLayer — function @experimental
+```
+(def: AnimatorControllerDef, index: number): AnimatorScope | null
+```
+
+## animatorLayerCount — function @experimental
+```
+(def: AnimatorControllerDef): number
+```
+
## applyAreasToGrid — function @experimental
```
(grid: NavGrid, areas: ReadonlyArray<NavAreaBox & { cost: number; }>): void
@@ -11907,12 +11940,12 @@ DragPlugin
## evaluateAnimatorPath — function @experimental
```
-(def: AnimatorControllerDef, currentPath: string, params: AnimatorParamValues, triggers: ReadonlySet<string>, clipFinished?: boolean): AnimatorPathEvalResult
+(def: AnimatorScope, currentPath: string, params: AnimatorParamValues, triggers: ReadonlySet<string>, clipFinished?: boolean): AnimatorPathEvalResult
```
## evaluateAnimatorTransitions — function @experimental
```
-(def: AnimatorControllerDef, currentState: string, params: AnimatorParamValues, triggers: ReadonlySet<string>, clipFinished?: boolean): AnimatorEvalResult
+(def: AnimatorScope, currentState: string, params: AnimatorParamValues, triggers: ReadonlySet<string>, clipFinished?: boolean): AnimatorEvalResult
```
## evaluateChannel — function @experimental
@@ -12525,9 +12558,14 @@ InputRouter
(layer: number, ySortMask: number, depthMask: number): LayerOrder
```
+## layerState — function @experimental
+```
+(a: AnimatorData, index: number): string
+```
+
## leafStateOf — function @experimental
```
-(def: AnimatorControllerDef, path: string): AnimatorState | null
+(def: AnimatorScope, path: string): AnimatorState | null
```
## lifecyclePlugin — const @experimental
@@ -13630,6 +13668,11 @@ ServicesPlugin
(def: FsmDefinition, name: string): FsmDefinition
```
+## setLayerState — function @experimental
+```
+(a: AnimatorData, index: number, path: string): void
+```
+
## setLogLevel — function @experimental
```
(level: LogLevel): void
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 8dd8b54ea..752a267ce 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,13 +1,18 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 114 public · 96 beta · 1685 experimental · 3 deprecated
+Symbols: 114 public · 96 beta · 1692 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
readonly AnchorAxis[]
```
+## ANIMATOR_FORMAT_VERSION — const @experimental
+```
+2
+```
+
## ANIM_CLIP_FORMAT_VERSION — const @experimental
```
"1.5"
@@ -478,8 +483,10 @@ static prototype: AnimatorControllerAPI
```
anyStateTransitions: AnimatorTransition[] | undefined
initialState: string
+layers: AnimatorLayer[] | undefined
parameters: AnimatorParam[]
states: AnimatorState[]
+version: number | undefined
```
## AnimatorData — interface @beta
@@ -487,6 +494,7 @@ states: AnimatorState[]
controller: string
currentState: string
enabled: boolean
+layerStates: string[]
```
## AnimatorEdge — type @experimental
@@ -522,6 +530,21 @@ value: number
send: (event: AnimatorEventPayload) => void
```
+## AnimatorLayer — interface @experimental
+```
+anyStateTransitions: AnimatorTransition[] | undefined
+blend: AnimatorLayerBlend | undefined
+initialState: string
+name: string
+states: AnimatorState[]
+weight: number | undefined
+```
+
+## AnimatorLayerBlend — type @experimental
+```
+'override' | 'additive'
+```
+
## AnimatorMotion — type @experimental
```
| AnimatorClipMotion | AnimatorBlend1DMotion | AnimatorBlend2DMotion
@@ -10722,6 +10745,16 @@ AnimationPlugin
(def: AnimatorControllerDef): AnimatorEdge[]
```
+## animatorLayer — function @experimental
+```
+(def: AnimatorControllerDef, index: number): AnimatorScope | null
+```
+
+## animatorLayerCount — function @experimental
+```
+(def: AnimatorControllerDef): number
+```
+
## applyAreasToGrid — function @experimental
```
(grid: NavGrid, areas: ReadonlyArray<NavAreaBox & { cost: number; }>): void
@@ -11669,12 +11702,12 @@ DragPlugin
## evaluateAnimatorPath — function @experimental
```
-(def: AnimatorControllerDef, currentPath: string, params: AnimatorParamValues, triggers: ReadonlySet<string>, clipFinished?: boolean): AnimatorPathEvalResult
+(def: AnimatorScope, currentPath: string, params: AnimatorParamValues, triggers: ReadonlySet<string>, clipFinished?: boolean): AnimatorPathEvalResult
```
## evaluateAnimatorTransitions — function @experimental
```
-(def: AnimatorControllerDef, currentState: string, params: AnimatorParamValues, triggers: ReadonlySet<string>, clipFinished?: boolean): AnimatorEvalResult
+(def: AnimatorScope, currentState: string, params: AnimatorParamValues, triggers: ReadonlySet<string>, clipFinished?: boolean): AnimatorEvalResult
```
## evaluateChannel — function @experimental
@@ -12277,9 +12310,14 @@ InputRouter
(layer: number, ySortMask: number, depthMask: number): LayerOrder
```
+## layerState — function @experimental
+```
+(a: AnimatorData, index: number): string
+```
+
## leafStateOf — function @experimental
```
-(def: AnimatorControllerDef, path: string): AnimatorState | null
+(def: AnimatorScope, path: string): AnimatorState | null
```
## lifecyclePlugin — const @experimental
@@ -13392,6 +13430,11 @@ ServicesPlugin
(def: FsmDefinition, name: string): FsmDefinition
```
+## setLayerState — function @experimental
+```
+(a: AnimatorData, index: number, path: string): void
+```
+
## setLogLevel — function @experimental
```
(level: LogLevel): void
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index b85533fd8..45ce4a877 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,13 +1,18 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 114 public · 94 beta · 1707 experimental · 3 deprecated
+Symbols: 114 public · 94 beta · 1714 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
readonly AnchorAxis[]
```
+## ANIMATOR_FORMAT_VERSION — const @experimental
+```
+2
+```
+
## ANIM_CLIP_FORMAT_VERSION — const @experimental
```
"1.5"
@@ -478,8 +483,10 @@ static prototype: AnimatorControllerAPI
```
anyStateTransitions: AnimatorTransition[] | undefined
initialState: string
+layers: AnimatorLayer[] | undefined
parameters: AnimatorParam[]
states: AnimatorState[]
+version: number | undefined
```
## AnimatorData — interface @beta
@@ -487,6 +494,7 @@ states: AnimatorState[]
controller: string
currentState: string
enabled: boolean
+layerStates: string[]
```
## AnimatorEdge — type @experimental
@@ -522,6 +530,21 @@ value: number
send: (event: AnimatorEventPayload) => void
```
+## AnimatorLayer — interface @experimental
+```
+anyStateTransitions: AnimatorTransition[] | undefined
+blend: AnimatorLayerBlend | undefined
+initialState: string
+name: string
+states: AnimatorState[]
+weight: number | undefined
+```
+
+## AnimatorLayerBlend — type @experimental
+```
+'override' | 'additive'
+```
+
## AnimatorMotion — type @experimental
```
| AnimatorClipMotion | AnimatorBlend1DMotion | AnimatorBlend2DMotion
@@ -10976,6 +10999,16 @@ AnimationPlugin
(def: AnimatorControllerDef): AnimatorEdge[]
```
+## animatorLayer — function @experimental
+```
+(def: AnimatorControllerDef, index: number): AnimatorScope | null
+```
+
+## animatorLayerCount — function @experimental
+```
+(def: AnimatorControllerDef): number
+```
+
## applyAreasToGrid — function @experimental
```
(grid: NavGrid, areas: ReadonlyArray<NavAreaBox & { cost: number; }>): void
@@ -11928,12 +11961,12 @@ DragPlugin
## evaluateAnimatorPath — function @experimental
```
-(def: AnimatorControllerDef, currentPath: string, params: AnimatorParamValues, triggers: ReadonlySet<string>, clipFinished?: boolean): AnimatorPathEvalResult
+(def: AnimatorScope, currentPath: string, params: AnimatorParamValues, triggers: ReadonlySet<string>, clipFinished?: boolean): AnimatorPathEvalResult
```
## evaluateAnimatorTransitions — function @experimental
```
-(def: AnimatorControllerDef, currentState: string, params: AnimatorParamValues, triggers: ReadonlySet<string>, clipFinished?: boolean): AnimatorEvalResult
+(def: AnimatorScope, currentState: string, params: AnimatorParamValues, triggers: ReadonlySet<string>, clipFinished?: boolean): AnimatorEvalResult
```
## evaluateChannel — function @experimental
@@ -12546,9 +12579,14 @@ InputRouter
(layer: number, ySortMask: number, depthMask: number): LayerOrder
```
+## layerState — function @experimental
+```
+(a: AnimatorData, index: number): string
+```
+
## leafStateOf — function @experimental
```
-(def: AnimatorControllerDef, path: string): AnimatorState | null
+(def: AnimatorScope, path: string): AnimatorState | null
```
## lifecyclePlugin — const @experimental
@@ -13651,6 +13689,11 @@ ServicesPlugin
(def: FsmDefinition, name: string): FsmDefinition
```
+## setLayerState — function @experimental
+```
+(a: AnimatorData, index: number, path: string): void
+```
+
## setLogLevel — function @experimental
```
(level: LogLevel): void
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index e07a83d4f..5331fcf65 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -1,13 +1,18 @@
# API surface — esengine/wechat
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 114 public · 94 beta · 1697 experimental · 3 deprecated
+Symbols: 114 public · 94 beta · 1704 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
readonly AnchorAxis[]
```
+## ANIMATOR_FORMAT_VERSION — const @experimental
+```
+2
+```
+
## ANIM_CLIP_FORMAT_VERSION — const @experimental
```
"1.5"
@@ -478,8 +483,10 @@ static prototype: AnimatorControllerAPI
```
anyStateTransitions: AnimatorTransition[] | undefined
initialState: string
+layers: AnimatorLayer[] | undefined
parameters: AnimatorParam[]
states: AnimatorState[]
+version: number | undefined
```
## AnimatorData — interface @beta
@@ -487,6 +494,7 @@ states: AnimatorState[]
controller: string
currentState: string
enabled: boolean
+layerStates: string[]
```
## AnimatorEdge — type @experimental
@@ -522,6 +530,21 @@ value: number
send: (event: AnimatorEventPayload) => void
```
+## AnimatorLayer — interface @experimental
+```
+anyStateTransitions: AnimatorTransition[] | undefined
+blend: AnimatorLayerBlend | undefined
+initialState: string
+name: string
+states: AnimatorState[]
+weight: number | undefined
+```
+
+## AnimatorLayerBlend — type @experimental
+```
+'override' | 'additive'
+```
+
## AnimatorMotion — type @experimental
```
| AnimatorClipMotion | AnimatorBlend1DMotion | AnimatorBlend2DMotion
@@ -10750,6 +10773,16 @@ AnimationPlugin
(def: AnimatorControllerDef): AnimatorEdge[]
```
+## animatorLayer — function @experimental
+```
+(def: AnimatorControllerDef, index: number): AnimatorScope | null
+```
+
+## animatorLayerCount — function @experimental
+```
+(def: AnimatorControllerDef): number
+```
+
## applyAreasToGrid — function @experimental
```
(grid: NavGrid, areas: ReadonlyArray<NavAreaBox & { cost: number; }>): void
@@ -11697,12 +11730,12 @@ DragPlugin
## evaluateAnimatorPath — function @experimental
```
-(def: AnimatorControllerDef, currentPath: string, params: AnimatorParamValues, triggers: ReadonlySet<string>, clipFinished?: boolean): AnimatorPathEvalResult
+(def: AnimatorScope, currentPath: string, params: AnimatorParamValues, triggers: ReadonlySet<string>, clipFinished?: boolean): AnimatorPathEvalResult
```
## evaluateAnimatorTransitions — function @experimental
```
-(def: AnimatorControllerDef, currentState: string, params: AnimatorParamValues, triggers: ReadonlySet<string>, clipFinished?: boolean): AnimatorEvalResult
+(def: AnimatorScope, currentState: string, params: AnimatorParamValues, triggers: ReadonlySet<string>, clipFinished?: boolean): AnimatorEvalResult
```
## evaluateChannel — function @experimental
@@ -12310,9 +12343,14 @@ InputRouter
(layer: number, ySortMask: number, depthMask: number): LayerOrder
```
+## layerState — function @experimental
+```
+(a: AnimatorData, index: number): string
+```
+
## leafStateOf — function @experimental
```
-(def: AnimatorControllerDef, path: string): AnimatorState | null
+(def: AnimatorScope, path: string): AnimatorState | null
```
## lifecyclePlugin — const @experimental
@@ -13415,6 +13453,11 @@ ServicesPlugin
(def: FsmDefinition, name: string): FsmDefinition
```
+## setLayerState — function @experimental
+```
+(a: AnimatorData, index: number, path: string): void
+```
+
## setLogLevel — function @experimental
```
(level: LogLevel): void
diff --git a/sdk/src/animation/Animator.ts b/sdk/src/animation/Animator.ts
index c38b817af..330dd72fe 100644
--- a/sdk/src/animation/Animator.ts
+++ b/sdk/src/animation/Animator.ts
@@ -30,6 +30,7 @@ import {
import { SPRITE_MOTION, spriteMotionDriver } from './spriteMotion';
import { Pose } from './pose';
import { mixPoses } from './poseMix';
+import { overlayPose, addPoseOver } from './layerStack';
import { AnimatorRootMotion, type AnimatorRootMotionData } from './animatorRootMotion';
import type { AnimatorEventSink } from './animatorEvent';
import { Transform, type TransformData } from '../ecs/component';
@@ -154,20 +155,74 @@ export interface AnimatorState {
y?: number;
}
+/** How a layer's pose meets what the layers under it already said. */
+export type AnimatorLayerBlend = 'override' | 'additive';
+
+/**
+ * A layer over the base one: a state machine of its own, and how much of what it
+ * says survives. Neither `weight` nor `blend` exists on the base layer, both
+ * being statements about what is underneath and nothing being.
+ */
+export interface AnimatorLayer extends AnimatorScope {
+ name: string;
+ /** 0 leaves the layers below untouched, 1 states this layer whole. */
+ weight?: number;
+ blend?: AnimatorLayerBlend;
+}
+
+/** What a `.esanimator` this build writes claims. */
+export const ANIMATOR_FORMAT_VERSION = 2;
+
export interface AnimatorControllerDef {
+ /**
+ * Absent is 1, the shape before layers. A file claiming a version this build
+ * does not know is refused rather than read for the parts it recognises,
+ * which would drop a layer silently and animate the wrong character.
+ */
+ version?: number;
parameters: AnimatorParam[];
states: AnimatorState[];
initialState: string;
/** Transitions evaluated from every state, before the current state's own. */
anyStateTransitions?: AnimatorTransition[];
+ /** Layers over the base one, laid down in order. */
+ layers?: AnimatorLayer[];
}
/**
- * The shape shared by the top-level controller and every nested machine: a set of
- * states, an entry point, and machine-wide any-state transitions.
+ * The shape shared by the top-level controller, every layer and every nested
+ * machine: a set of states, an entry point, and machine-wide any-state
+ * transitions.
*/
export type AnimatorScope = Pick<AnimatorControllerDef, 'states' | 'initialState' | 'anyStateTransitions'>;
+/** How many state machines run on one entity: the base layer and those over it. */
+export function animatorLayerCount(def: AnimatorControllerDef): number {
+ return 1 + (def.layers?.length ?? 0);
+}
+
+/**
+ * Layer `index`'s active state. Read and written through here so each layer's
+ * state has one home: the base layer's is `currentState`, which is what a
+ * single-layer controller has always had and what every reader of one expects.
+ */
+export function layerState(a: AnimatorData, index: number): string {
+ return index === 0 ? a.currentState : (a.layerStates?.[index - 1] ?? '');
+}
+
+export function setLayerState(a: AnimatorData, index: number, path: string): void {
+ if (index === 0) { a.currentState = path; return; }
+ if (!a.layerStates) a.layerStates = [];
+ while (a.layerStates.length < index) a.layerStates.push('');
+ a.layerStates[index - 1] = path;
+}
+
+/** Layer `index`, the base one at 0. Null for an index the controller has not got. */
+export function animatorLayer(def: AnimatorControllerDef, index: number): AnimatorScope | null {
+ if (index === 0) return def;
+ return def.layers?.[index - 1] ?? null;
+}
+
// =============================================================================
// Pure transition evaluator (no World, no side effects → unit-testable)
// =============================================================================
@@ -226,7 +281,7 @@ function firstReady(
* triggers a fired transition consumed. Pure.
*/
export function evaluateAnimatorTransitions(
- def: AnimatorControllerDef,
+ def: AnimatorScope,
currentState: string,
params: AnimatorParamValues,
triggers: ReadonlySet<string>,
@@ -299,7 +354,7 @@ export interface AnimatorPathEvalResult {
* initial state when needed). `clipFinished` reflects the leaf clip. Pure.
*/
export function evaluateAnimatorPath(
- def: AnimatorControllerDef,
+ def: AnimatorScope,
currentPath: string,
params: AnimatorParamValues,
triggers: ReadonlySet<string>,
@@ -338,7 +393,7 @@ export function evaluateAnimatorPath(
}
/** The leaf (motion-bearing) state of a resolved path, or null if unresolvable. */
-export function leafStateOf(def: AnimatorControllerDef, path: string): AnimatorState | null {
+export function leafStateOf(def: AnimatorScope, path: string): AnimatorState | null {
const resolved = resolveStatePath(def, path ? path.split(STATE_PATH_SEP) : []);
return resolved ? resolved.states[resolved.states.length - 1] : null;
}
@@ -434,8 +489,12 @@ export function resolveParams(
export interface AnimatorData {
/** Registered controller name (see AnimatorControllerAPI.registerController). */
controller: string;
- /** Active state; empty until the first update seeds it from initialState. */
+ /** The base layer's active state; empty until the first update seeds it. */
currentState: string;
+ /** The active state of each layer ABOVE the base one, by that layer's index
+ * minus one — the base layer's is {@link currentState}, for the same reason
+ * the base layer has no weight. */
+ layerStates: string[];
enabled: boolean;
}
@@ -449,6 +508,7 @@ export interface AnimatorData {
export const Animator: ComponentDef<AnimatorData> = defineComponent('Animator', {
controller: '',
currentState: '',
+ layerStates: [] as string[],
enabled: true,
}, {
assetFields: [{ field: 'controller', type: 'animatorcontroller' }],
@@ -642,59 +702,131 @@ export class AnimatorControllerAPI {
const def = this.getController(a.controller);
if (!def || def.states.length === 0) continue;
- // Seed / repair the active state path. The path descends into a
- // sub-machine's initial state when the entry point is a container.
- let fromPath = a.currentState;
- let leaf = fromPath ? leafStateOf(def, fromPath) : null;
- if (!leaf) {
- fromPath = enterStatePath(def, def.initialState).join(STATE_PATH_SEP);
- leaf = leafStateOf(def, fromPath);
- if (!leaf) continue;
- }
-
+ const count = animatorLayerCount(def);
const params = resolveParams(def, this.params.get(entity) ?? EMPTY_PARAMS);
- const triggerSet = this.triggers.get(entity);
const ctx = this.motions_.context(world, entity, params);
- const rt = this.runtimeFor(entity);
- // Advance BEFORE asking whether the motion ran out: judging the clip
- // on the previous frame's clock holds every exit-time transition one
- // frame past the clip it was waiting for.
- this.advance(rt, dt);
- const leafMotion = motionOf(leaf);
- const clipFinished = leafMotion !== null && this.motionEnded(ctx, leafMotion, rt.time);
-
- const { nextPath, consumedTriggers, fadeDuration } = evaluateAnimatorPath(
- def, fromPath, params, triggerSet ?? EMPTY_TRIGGERS, clipFinished,
- );
- if (triggerSet) for (const t of consumedTriggers) triggerSet.delete(t);
-
- const target = nextPath ?? fromPath;
- const stateChanged = target !== a.currentState;
- if (stateChanged) {
- a.currentState = target;
- world.insert(entity, Animator, a);
- }
- const targetLeaf = nextPath ? leafStateOf(def, target) : leaf;
- if (!targetLeaf) continue;
- // Drive the active leaf every frame: a blend's selection can change as
- // its parameter crosses a threshold without any state change. A driver
- // is a no-op in steady state, which is what keeps that cheap.
- const motion = targetLeaf === leaf ? leafMotion : motionOf(targetLeaf);
-
- if (stateChanged) {
- this.beginState(rt, leafMotion, leaf.rootMotion === true, motion, fadeDuration);
+ const rt = this.runtimeFor(entity, count);
+ rt.composed.reset();
+
+ let wrote = false;
+ this.spentTriggers_.length = 0;
+ for (let index = 0; index < count; index++) {
+ wrote = this.stepLayer(world, entity, a, def, index, ctx, rt, dt, events) || wrote;
}
- const drivesRoot = targetLeaf.rootMotion === true;
- if (motion) this.driveMotion(ctx, world, rt, motion, drivesRoot, stateChanged);
-
- // What the state's own clock covered this frame. Empty on the frame it
- // was entered, and closed there rather than half-open: an event
- // authored at the very start of a clip happens on that frame or never.
- const span: MotionSpan = {
- from: rt.prevTime, to: rt.time, inclusiveStart: rt.entered,
- };
- if (motion && events) this.emitEvents(ctx, entity, motion, span, events);
- this.publishRootMotion(world, entity, ctx, motion, span, drivesRoot);
+ // Consumed after EVERY layer has been asked, not as each fires: one
+ // trigger is one event every layer is told about, so an attack both
+ // machines answer cannot depend on which was stepped first.
+ const triggers = this.triggers.get(entity);
+ if (triggers) for (const t of this.spentTriggers_) triggers.delete(t);
+ // One write for the whole stack: a layer states values, and what the
+ // entity ends up as is the stack's answer, not the topmost writer's.
+ if (wrote) rt.composed.applyTo(world);
+ }
+ }
+
+ /**
+ * Run one layer: its own clock, its own transitions, its own pose — laid over
+ * what the layers under it already put in `rt.composed`. Answers whether it
+ * left anything there, a layer driving a sprite sheet having written the
+ * entity directly instead.
+ */
+ private stepLayer(
+ world: World, entity: Entity, a: AnimatorData, def: AnimatorControllerDef,
+ index: number, ctx: MotionContext, rt: AnimatorRuntime, dt: number,
+ events: AnimatorEventSink | undefined,
+ ): boolean {
+ const scope = animatorLayer(def, index);
+ if (!scope || scope.states.length === 0) return false;
+
+ // Seed / repair the active state path. The path descends into a
+ // sub-machine's initial state when the entry point is a container.
+ let fromPath = layerState(a, index);
+ let leaf = fromPath ? leafStateOf(scope, fromPath) : null;
+ if (!leaf) {
+ fromPath = enterStatePath(scope, scope.initialState).join(STATE_PATH_SEP);
+ leaf = leafStateOf(scope, fromPath);
+ if (!leaf) return false;
+ }
+
+ const params = ctx.params;
+ const triggerSet = this.triggers.get(entity);
+ const lrt = rt.layers[index]!;
+ // Advance BEFORE asking whether the motion ran out: judging the clip
+ // on the previous frame's clock holds every exit-time transition one
+ // frame past the clip it was waiting for.
+ this.advance(lrt, dt);
+ const leafMotion = motionOf(leaf);
+ const clipFinished = leafMotion !== null && this.motionEnded(ctx, leafMotion, lrt.time);
+
+ const { nextPath, consumedTriggers, fadeDuration } = evaluateAnimatorPath(
+ scope, fromPath, params, triggerSet ?? EMPTY_TRIGGERS, clipFinished,
+ );
+ for (const t of consumedTriggers) this.spentTriggers_.push(t);
+
+ const target = nextPath ?? fromPath;
+ // Also true on the frame a layer is SEEDED, its recorded state being
+ // empty and the entry point what it is about to start playing.
+ const stateChanged = target !== layerState(a, index);
+ if (stateChanged) {
+ setLayerState(a, index, target);
+ world.insert(entity, Animator, a);
+ }
+ const targetLeaf = nextPath ? leafStateOf(scope, target) : leaf;
+ if (!targetLeaf) return false;
+ // Drive the active leaf every frame: a blend's selection can change as
+ // its parameter crosses a threshold without any state change. A driver
+ // is a no-op in steady state, which is what keeps that cheap.
+ const motion = targetLeaf === leaf ? leafMotion : motionOf(targetLeaf);
+
+ if (stateChanged) {
+ this.beginState(lrt, leafMotion, leaf.rootMotion === true, motion, fadeDuration);
+ }
+ // Where the character GOES has one author. A layer states how it is
+ // posed; taking displacement from more than one would have two answers
+ // to a question the character controller asks once.
+ const drivesRoot = index === 0 && targetLeaf.rootMotion === true;
+ const posed = motion !== null
+ && this.poseLayer(world, ctx, lrt, motion, drivesRoot, stateChanged);
+
+ if (posed) this.compose(world, ctx, def, index, rt, posed, motion!);
+
+ // What the state's own clock covered this frame. Empty on the frame it
+ // was entered, and closed there rather than half-open: an event
+ // authored at the very start of a clip happens on that frame or never.
+ const span: MotionSpan = {
+ from: lrt.prevTime, to: lrt.time, inclusiveStart: lrt.entered,
+ };
+ if (motion && events) this.emitEvents(ctx, entity, motion, span, events);
+ if (index === 0) this.publishRootMotion(world, entity, ctx, motion, span, drivesRoot);
+ return posed !== null;
+ }
+
+ /**
+ * Put `pose` into the stack. The base layer states it outright; a layer over
+ * it leans the stack toward what it says, or adds what it says beyond its own
+ * rest pose — neither of which commutes, which is the whole difference
+ * between this and the pose mixer a crossfade uses.
+ */
+ private compose(
+ world: World, ctx: MotionContext, def: AnimatorControllerDef, index: number,
+ rt: AnimatorRuntime, pose: Pose, motion: AnimatorMotion,
+ ): void {
+ if (index === 0) {
+ overlayPose(rt.composed, pose, 1, world, null);
+ return;
+ }
+ const layer = def.layers![index - 1]!;
+ const weight = layer.weight ?? 1;
+ if (layer.blend !== 'additive') {
+ overlayPose(rt.composed, pose, weight, world, null);
+ return;
+ }
+ rt.rest.reset();
+ ctx.extractRootMotion = false;
+ // The clip's own first frame is its rest: an additive clip says "from
+ // where this motion starts", so nothing else has to be authored for it.
+ if (ctx.sample(motion, 0, rt.rest)) {
+ addPoseOver(rt.composed, pose, rt.rest, weight, world, null);
}
}
@@ -759,7 +891,7 @@ export class AnimatorControllerAPI {
* motion has no partial state to hold, so a fade over one would be a pause.
*/
private beginState(
- rt: AnimatorRuntime,
+ rt: LayerRuntime,
leaving: AnimatorMotion | null, leavingDrivesRoot: boolean,
entering: AnimatorMotion | null, fadeDuration: number,
): void {
@@ -780,7 +912,7 @@ export class AnimatorControllerAPI {
}
/** Advance the state's clock, and the fade's if one is running. */
- private advance(rt: AnimatorRuntime, dt: number): void {
+ private advance(rt: LayerRuntime, dt: number): void {
rt.prevTime = rt.time;
rt.entered = false;
rt.time += dt;
@@ -791,13 +923,15 @@ export class AnimatorControllerAPI {
}
/**
- * Put the motion on the entity. Through a pose where it can be sampled - two
- * composed while a fade runs - so what lands does not depend on sample order.
+ * What this layer's motion says, as a pose for the stack to compose — two
+ * composed here already when a fade is running, mixing being the operation
+ * that does not care which was sampled first. Null for a motion that can only
+ * be driven, a sprite sheet writing the entity itself and joining no stack.
*/
- private driveMotion(
- ctx: MotionContext, world: World, rt: AnimatorRuntime,
+ private poseLayer(
+ world: World, ctx: MotionContext, rt: LayerRuntime,
motion: AnimatorMotion, drivesRoot: boolean, enter: boolean,
- ): void {
+ ): Pose | null {
if (rt.fadeFrom !== null) {
rt.poseFrom.reset();
rt.poseTo.reset();
@@ -812,19 +946,16 @@ export class AnimatorControllerAPI {
[{ pose: rt.poseFrom, weight: 1 - t }, { pose: rt.poseTo, weight: t }],
rt.mixed, world,
);
- rt.mixed.applyTo(world);
- return;
+ return rt.mixed;
}
rt.fadeFrom = null;
}
rt.poseTo.reset();
ctx.extractRootMotion = drivesRoot;
- if (ctx.sample(motion, rt.time, rt.poseTo)) {
- rt.poseTo.applyTo(world);
- return;
- }
+ if (ctx.sample(motion, rt.time, rt.poseTo)) return rt.poseTo;
ctx.drive(motion, enter);
+ return null;
}
/** Whether a motion has run out. A clip whose length the driver states is
@@ -839,20 +970,32 @@ export class AnimatorControllerAPI {
return this.motions_.driverFor(motion)?.sample !== undefined;
}
- private runtimeFor(entity: Entity): AnimatorRuntime {
+ /**
+ * This entity's clocks, grown to the controller it is now running. Grown and
+ * not rebuilt: a controller swapped for one with more layers keeps the base
+ * layer mid-clip, which is what the entity is visibly doing.
+ */
+ private runtimeFor(entity: Entity, layers: number): AnimatorRuntime {
let rt = this.runtimes_.get(entity);
if (!rt) {
- rt = {
+ rt = { layers: [], composed: new Pose(), rest: new Pose() };
+ this.runtimes_.set(entity, rt);
+ }
+ while (rt.layers.length < layers) {
+ rt.layers.push({
time: 0, prevTime: 0, entered: true,
fadeFrom: null, fadeFromRoot: false,
fadeFromTime: 0, fadeElapsed: 0, fadeDuration: 0,
poseFrom: new Pose(), poseTo: new Pose(), mixed: new Pose(),
- };
- this.runtimes_.set(entity, rt);
+ });
}
return rt;
}
+ /** What this entity's layers used up this frame, spent once they have all
+ * been asked. */
+ private readonly spentTriggers_: string[] = [];
+
/** Reused across entities and frames: a steady animation states no events,
* and an array per animated entity per frame would be the only allocation. */
private readonly eventScratch_: MotionEvent[] = [];
@@ -868,6 +1011,16 @@ const IDENTITY_QUAT = { w: 1, x: 0, y: 0, z: 0 };
/** One entity's playback state: transient, so it lives here and not on the
* component, which is what a scene saves and an inspector shows. */
interface AnimatorRuntime {
+ /** One per layer, the base layer at 0. */
+ layers: LayerRuntime[];
+ /** What the whole stack came to, written to the world once. */
+ composed: Pose;
+ /** An additive layer's own resting pose, which is what its clip departs from. */
+ rest: Pose;
+}
+
+/** One layer's clock and the poses it composes from. */
+interface LayerRuntime {
/** Seconds the current state's motion has been playing. */
time: number;
/** What {@link time} was before this frame's advance — the other end of the
diff --git a/sdk/src/animation/animatorGraph.ts b/sdk/src/animation/animatorGraph.ts
index 9296bed43..2d43be987 100644
--- a/sdk/src/animation/animatorGraph.ts
+++ b/sdk/src/animation/animatorGraph.ts
@@ -13,6 +13,7 @@
* runtime AnimatorControllerDef, so there is no separate editor model.
*/
+import { ANIMATOR_FORMAT_VERSION } from './Animator';
import type {
AnimatorControllerDef,
AnimatorState,
@@ -49,7 +50,12 @@ export function animatorEdges(def: AnimatorControllerDef): AnimatorEdge[] {
/** A blank controller with one initial state and no parameters. */
export function emptyAnimatorController(): AnimatorControllerDef {
- return { parameters: [], states: [{ name: 'Idle', x: 80, y: 80, transitions: [] }], initialState: 'Idle' };
+ return {
+ version: ANIMATOR_FORMAT_VERSION,
+ parameters: [],
+ states: [{ name: 'Idle', x: 80, y: 80, transitions: [] }],
+ initialState: 'Idle',
+ };
}
export function addState(def: AnimatorControllerDef, name: string, x = 0, y = 0): AnimatorControllerDef {
diff --git a/sdk/src/animation/animatorMigrate.ts b/sdk/src/animation/animatorMigrate.ts
new file mode 100644
index 000000000..93d03f956
--- /dev/null
+++ b/sdk/src/animation/animatorMigrate.ts
@@ -0,0 +1,86 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file animatorMigrate.ts
+ * @brief Bringing a parsed `.esanimator` to the version this build writes.
+ *
+ * @details A version is a property of the FILE, not of a controller: one built in
+ * code never passes through here, having no older spelling to be read
+ * from. What the guard buys is the other direction — a file from a later
+ * build is refused rather than read for the parts this one recognises,
+ * because layers it cannot see would animate a visibly wrong character
+ * and nothing would say so.
+ */
+
+import {
+ ANIMATOR_FORMAT_VERSION,
+ type AnimatorControllerDef, type AnimatorLayer,
+} from './Animator';
+
+/** What a pass over a controller blob came to. */
+export interface AnimatorMigration {
+ def: AnimatorControllerDef;
+ /** Whether anything was upgraded; a caller may ask the author to re-save. */
+ migrated: boolean;
+ /** The version the file claimed — 1 for one written before layers existed. */
+ fromVersion: number;
+}
+
+/** The version a file with no `version` field was written at. */
+const UNVERSIONED = 1;
+
+function isScope(value: unknown): boolean {
+ if (typeof value !== 'object' || value === null) return false;
+ const o = value as Record<string, unknown>;
+ return Array.isArray(o['states']) && typeof o['initialState'] === 'string';
+}
+
+/**
+ * Total and idempotent: already-current data comes back with `migrated: false`.
+ * Throws for a shape that cannot be reconciled, and for a version this build does
+ * not know.
+ */
+export function migrateAnimatorController(raw: unknown): AnimatorMigration {
+ if (typeof raw !== 'object' || raw === null) {
+ throw new Error('Animator controller data must be an object');
+ }
+ const obj = raw as Record<string, unknown>;
+ if (!isScope(obj)) {
+ throw new Error('Animator controller must have a "states" array and an "initialState"');
+ }
+
+ const claimed = obj['version'];
+ if (claimed !== undefined && (typeof claimed !== 'number' || !Number.isInteger(claimed))) {
+ throw new Error('Animator controller "version" must be an integer');
+ }
+ const fromVersion = (claimed as number | undefined) ?? UNVERSIONED;
+ if (fromVersion > ANIMATOR_FORMAT_VERSION) {
+ throw new Error(
+ `Animator controller is version ${fromVersion}; this build reads up to `
+ + `${ANIMATOR_FORMAT_VERSION}. Update the engine rather than opening it here.`,
+ );
+ }
+ if (obj['layers'] !== undefined) {
+ if (!Array.isArray(obj['layers'])) {
+ throw new Error('Animator controller "layers" must be an array');
+ }
+ for (const layer of obj['layers'] as AnimatorLayer[]) {
+ if (!isScope(layer) || typeof layer.name !== 'string') {
+ throw new Error('Every animator layer needs a name, states and an initialState');
+ }
+ }
+ }
+
+ const def = obj as unknown as AnimatorControllerDef;
+ if (fromVersion === ANIMATOR_FORMAT_VERSION) {
+ return { def, migrated: false, fromVersion };
+ }
+ // Version 1 is version 2 without layers, which reads correctly as a stack of
+ // one. Stamping it is the whole upgrade, and it is what makes a re-save land
+ // on a file the guard above will recognise.
+ return {
+ def: { ...def, version: ANIMATOR_FORMAT_VERSION },
+ migrated: true,
+ fromVersion,
+ };
+}
diff --git a/sdk/src/animation/index.ts b/sdk/src/animation/index.ts
index d1ad7a483..18ad99f6b 100644
--- a/sdk/src/animation/index.ts
+++ b/sdk/src/animation/index.ts
@@ -51,6 +51,11 @@ export {
evaluateAnimatorPath,
enterStatePath,
leafStateOf,
+ animatorLayerCount,
+ animatorLayer,
+ layerState,
+ setLayerState,
+ ANIMATOR_FORMAT_VERSION,
resolveParams,
selectBlendClip,
motionOf,
@@ -62,6 +67,8 @@ export {
type AnimatorSpineMotion,
type AnimatorSubMachine,
type AnimatorScope,
+ type AnimatorLayer,
+ type AnimatorLayerBlend,
type SpineAnimationDriver,
type AnimatorParam,
type AnimatorParamType,
@@ -134,6 +141,17 @@ export {
type AnimClipSizing,
} from './AnimClipLoader';
+export {
+ migrateAnimatorController,
+ type AnimatorMigration,
+} from './animatorMigrate';
+
+export {
+ overlayPose,
+ addPoseOver,
+ type LayerReach,
+} from './layerStack';
+
export {
MotionRegistry,
selectBlendStop,
diff --git a/sdk/src/animation/layerStack.ts b/sdk/src/animation/layerStack.ts
new file mode 100644
index 000000000..b3363b1ef
--- /dev/null
+++ b/sdk/src/animation/layerStack.ts
@@ -0,0 +1,174 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file layerStack.ts
+ * @brief Laying one layer's pose over what the layers under it already said.
+ *
+ * @details This is the operation {@link file://./poseMix.ts} is NOT. Mixing is a
+ * weighted average over the motions that wrote a field, and it commutes
+ * — which is what a crossfade and a blend tree need, and why the answer
+ * cannot depend on sample order. A layer stack is ordered: the aim layer
+ * at weight 0.3 means "three tenths of the way from whatever is under me
+ * to what I say", and swapping two layers is a different character.
+ *
+ * So the two are kept apart rather than parameterized into one function.
+ * A field the layer wrote but nothing under it did still interpolates —
+ * against the world's own value, reached by seeding the accumulator the
+ * way any pose is seeded. That is the other half of the difference:
+ * mixing gives a lone writer its field whole, a layer never does.
+ */
+
+import type { Pose, PoseTrack, PoseWorld } from './pose';
+
+interface Quat { w: number; x: number; y: number; z: number }
+
+function isQuat(v: unknown): v is Quat {
+ if (v === null || typeof v !== 'object') return false;
+ const o = v as Record<string, unknown>;
+ return typeof o.w === 'number' && typeof o.x === 'number'
+ && typeof o.y === 'number' && typeof o.z === 'number';
+}
+
+function isNumericObject(v: unknown): v is Record<string, number> {
+ if (v === null || typeof v !== 'object' || Array.isArray(v)) return false;
+ const keys = Object.keys(v as object);
+ return keys.length > 0 && keys.every(k => typeof (v as Record<string, unknown>)[k] === 'number');
+}
+
+function normalize(q: Quat): void {
+ const len = Math.hypot(q.w, q.x, q.y, q.z);
+ if (len <= 0) { q.w = 1; q.x = 0; q.y = 0; q.z = 0; return; }
+ q.w /= len; q.x /= len; q.y /= len; q.z /= len;
+}
+
+/**
+ * Move `dst` a `weight` share of the way to `src`. Aligned to the near hemisphere
+ * first: {q} and {-q} name the same rotation, and averaged as written they cancel
+ * toward the long way round.
+ */
+function leanQuat(dst: Quat, src: Quat, weight: number): void {
+ const dot = dst.w * src.w + dst.x * src.x + dst.y * src.y + dst.z * src.z;
+ const s = dot < 0 ? -weight : weight;
+ const keep = 1 - weight;
+ dst.w = dst.w * keep + src.w * s;
+ dst.x = dst.x * keep + src.x * s;
+ dst.y = dst.y * keep + src.y * s;
+ dst.z = dst.z * keep + src.z * s;
+ normalize(dst);
+}
+
+/** `dst` turned further by the rotation `from` → `to`, a `weight` share of it. */
+function turnQuat(dst: Quat, from: Quat, to: Quat, weight: number): void {
+ // The delta is `to * from⁻¹` in the clip's own frame; leaning the identity
+ // toward it is what scales a rotation, there being nothing to scale linearly.
+ const dw = to.w * from.w + to.x * from.x + to.y * from.y + to.z * from.z;
+ const dx = to.x * from.w - to.w * from.x - to.y * from.z + to.z * from.y;
+ const dy = to.y * from.w - to.w * from.y - to.z * from.x + to.x * from.z;
+ const dz = to.z * from.w - to.w * from.z - to.x * from.y + to.y * from.x;
+ const part: Quat = { w: 1, x: 0, y: 0, z: 0 };
+ leanQuat(part, { w: dw, x: dx, y: dy, z: dz }, weight);
+ const w = part.w * dst.w - part.x * dst.x - part.y * dst.y - part.z * dst.z;
+ const x = part.w * dst.x + part.x * dst.w + part.y * dst.z - part.z * dst.y;
+ const y = part.w * dst.y - part.x * dst.z + part.y * dst.w + part.z * dst.x;
+ const z = part.w * dst.z + part.x * dst.y - part.y * dst.x + part.z * dst.w;
+ dst.w = w; dst.x = x; dst.y = y; dst.z = z;
+ normalize(dst);
+}
+
+/** Which tracks of `layer` this stack lets through; null admits every one. */
+export interface LayerReach {
+ admits(track: PoseTrack): boolean;
+}
+
+function leanField(
+ dst: Record<string, unknown>, src: Record<string, unknown>, field: string, weight: number,
+): void {
+ const from = dst[field];
+ const to = src[field];
+ if (isQuat(to)) {
+ if (isQuat(from)) leanQuat(from, to, weight);
+ else dst[field] = { w: to.w, x: to.x, y: to.y, z: to.z };
+ } else if (typeof to === 'number') {
+ dst[field] = typeof from === 'number' ? from + (to - from) * weight : to;
+ } else if (isNumericObject(to)) {
+ if (isNumericObject(from)) {
+ for (const axis of Object.keys(to)) {
+ const a = from[axis];
+ from[axis] = typeof a === 'number' ? a + (to[axis]! - a) * weight : to[axis]!;
+ }
+ } else dst[field] = { ...to };
+ } else if (weight >= 1) {
+ // A string or a flag has no halfway. It arrives only where the layer is
+ // fully on, rather than switching at some threshold nobody declared.
+ dst[field] = to;
+ }
+}
+
+function addField(
+ dst: Record<string, unknown>, src: Record<string, unknown>,
+ ref: Record<string, unknown>, field: string, weight: number,
+): void {
+ const from = dst[field];
+ const to = src[field];
+ const base = ref[field];
+ if (isQuat(to) && isQuat(base)) {
+ if (isQuat(from)) turnQuat(from, base, to, weight);
+ } else if (typeof to === 'number' && typeof base === 'number') {
+ if (typeof from === 'number') dst[field] = from + (to - base) * weight;
+ } else if (isNumericObject(to) && isNumericObject(base) && isNumericObject(from)) {
+ for (const axis of Object.keys(to)) {
+ const a = from[axis];
+ if (typeof a === 'number') from[axis] = a + ((to[axis] ?? 0) - (base[axis] ?? 0)) * weight;
+ }
+ }
+}
+
+/**
+ * Lay `layer` over `acc`: every field the layer wrote moves a `weight` share of
+ * the way from what is already there to what the layer says. Where the layer is
+ * the first to write a field, "already there" is the world's own value.
+ */
+export function overlayPose(
+ acc: Pose, layer: Pose, weight: number, world: PoseWorld, reach: LayerReach | null,
+): void {
+ if (weight <= 0) return;
+ for (const src of layer.tracks) {
+ if (src.touched.size === 0) continue;
+ if (reach && !reach.admits(src)) continue;
+ const dst = acc.track(world, src.entity, src.def);
+ if (!dst) continue;
+ for (const field of src.touched) {
+ leanField(dst.data, src.data, field, weight);
+ dst.touched.add(field);
+ }
+ }
+}
+
+/**
+ * Add what `layer` says BEYOND `reference` onto `acc` — a flinch or a lean stated
+ * as a departure from its own resting pose, so it reads the same over a walk as
+ * over a run. Measured against the layer's own start and not against `acc`, which
+ * would make the same clip mean something different under every base state.
+ */
+export function addPoseOver(
+ acc: Pose, layer: Pose, reference: Pose, weight: number,
+ world: PoseWorld, reach: LayerReach | null,
+): void {
+ if (weight <= 0) return;
+ const rest = new Map<string, PoseTrack>();
+ for (const track of reference.tracks) rest.set(`${track.entity} ${track.def._name}`, track);
+
+ for (const src of layer.tracks) {
+ if (src.touched.size === 0) continue;
+ if (reach && !reach.admits(src)) continue;
+ const ref = rest.get(`${src.entity} ${src.def._name}`);
+ if (!ref) continue;
+ const dst = acc.track(world, src.entity, src.def);
+ if (!dst) continue;
+ for (const field of src.touched) {
+ if (!ref.touched.has(field)) continue;
+ addField(dst.data, src.data, ref.data, field, weight);
+ dst.touched.add(field);
+ }
+ }
+}
diff --git a/sdk/src/asset/loaders/AnimatorControllerAssetLoader.ts b/sdk/src/asset/loaders/AnimatorControllerAssetLoader.ts
index ac4027903..6593fdc90 100644
--- a/sdk/src/asset/loaders/AnimatorControllerAssetLoader.ts
+++ b/sdk/src/asset/loaders/AnimatorControllerAssetLoader.ts
@@ -14,6 +14,7 @@ import type {
import type { RegistryEra } from '../registryAssets';
import type { AnimatorControllerDef, AnimatorState } from '../../animation/Animator';
import { isBlend1D, isBlend2D, type AnimatorMotion } from '../../animation/motion';
+import { migrateAnimatorController } from '../../animation/animatorMigrate';
import { resolveDocumentRef } from '../documentRef';
/**
@@ -49,7 +50,7 @@ export class AnimatorControllerAssetLoader implements AssetLoader<AnimatorContro
readonly registry: RegistryAssetLoader<AnimatorControllerResult> = {
prepare: async (path: string, ctx: LoadContext): Promise<RegistryEra<AnimatorControllerResult>> => {
const text = await ctx.loadText(ctx.catalog.getBuildPath(path));
- const def = JSON.parse(text) as AnimatorControllerDef;
+ const { def } = migrateAnimatorController(JSON.parse(text));
await acquireMotionAssets(def, path, ctx);
return {
published: def,
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 027c5107a..ba88a98ec 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -463,9 +463,16 @@ export {
evaluateAnimatorPath,
enterStatePath,
leafStateOf,
+ animatorLayerCount,
+ animatorLayer,
+ layerState,
+ setLayerState,
+ ANIMATOR_FORMAT_VERSION,
STATE_PATH_SEP,
type AnimatorSubMachine,
type AnimatorScope,
+ type AnimatorLayer,
+ type AnimatorLayerBlend,
type AnimatorPathEvalResult,
emptyAnimatorController,
animatorEdges,
diff --git a/sdk/tests/animatorLayers.test.ts b/sdk/tests/animatorLayers.test.ts
new file mode 100644
index 000000000..7723edc04
--- /dev/null
+++ b/sdk/tests/animatorLayers.test.ts
@@ -0,0 +1,388 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * The claim: layers compose in ORDER. Mixing commutes and a stack does not, so
+ * swapping two layers is a different character, and a layer at weight w is w of
+ * the way from what is under it — never that field handed over whole.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ Animator, AnimatorControllerAPI, animatorLayerCount, layerState,
+ migrateAnimatorController, ANIMATOR_FORMAT_VERSION,
+ type AnimatorData, type AnimatorControllerDef, type AnimatorLayer,
+} from '../src/animation';
+import { createTimelineMotionDriver, TIMELINE_MOTION } from '../src/timeline';
+import { TimelineAPI } from '../src/timeline/TimelineControl';
+import { defineComponent } from '../src/ecs/component';
+import { WrapMode, TrackType, InterpType, type TimelineAsset } from '../src/timeline/TimelineTypes';
+
+const E = 1;
+
+const probe = () => defineComponent('LayerProbe', {
+ lift: 0, turn: 0, rot: { w: 1, x: 0, y: 0, z: 0 },
+});
+
+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, d: unknown) { mapOf(c).set(e, d); },
+ get(e: number, c: unknown) { return mapOf(c).get(e); },
+ has(e: number, c: unknown) { return mapOf(c).has(e); },
+ set(e: number, c: unknown, d: unknown) { mapOf(c).set(e, d); },
+ tryGet(e: number, c: unknown) { return mapOf(c).get(e) ?? null; },
+ update(e: number, c: unknown, edit: (d: any) => void) {
+ const d = mapOf(c).get(e);
+ edit(d); mapOf(c).set(e, d);
+ },
+ getEntitiesWithComponents(comps: unknown[]) {
+ const [first, ...rest] = comps;
+ return [...mapOf(first).keys()].filter(e => rest.every(c => mapOf(c).has(e)));
+ },
+ } as any;
+}
+
+function seedWorld() {
+ const world = makeWorld();
+ world.insert(E, probe(), { lift: 0, turn: 0, rot: { w: 1, x: 0, y: 0, z: 0 } });
+ return world;
+}
+
+const read = (world: any) => world.get(E, probe()) as {
+ lift: number; turn: number; rot: { w: number; x: number; y: number; z: number };
+};
+
+/** A clip holding the named fields for ten seconds. */
+function hold(values: Record<string, number>): TimelineAsset {
+ return {
+ version: '1.2', type: 'timeline', duration: 10, wrapMode: WrapMode.Loop,
+ tracks: [{
+ type: TrackType.Property, component: 'LayerProbe', childPath: '', name: 't',
+ channels: Object.entries(values).map(([property, value]) => ({
+ property,
+ keyframes: [{
+ time: 0, value, inTangent: 0, outTangent: 0,
+ interpolation: InterpType.Linear,
+ }],
+ })),
+ }],
+ } as TimelineAsset;
+}
+
+/** A clip ramping `property` from `from` to `to` over ten seconds. */
+function ramp(property: string, from: number, to: number): TimelineAsset {
+ const key = (time: number, value: number) => ({
+ time, value, inTangent: 0, outTangent: 0, interpolation: InterpType.Linear,
+ });
+ return {
+ version: '1.2', type: 'timeline', duration: 10, wrapMode: WrapMode.Loop,
+ tracks: [{
+ type: TrackType.Property, component: 'LayerProbe', childPath: '', name: 't',
+ channels: [{ property, keyframes: [key(0, from), key(10, to)] }],
+ }],
+ } as TimelineAsset;
+}
+
+const clip = (name: string) => ({ kind: TIMELINE_MOTION, clip: name });
+
+/** One state named `Hold` playing `name`. */
+const oneState = (name: string) => ({
+ states: [{ name: 'Hold', motion: clip(name), transitions: [] }],
+ initialState: 'Hold',
+});
+
+function build(
+ assets: Record<string, TimelineAsset>,
+ base: string,
+ layers: AnimatorLayer[],
+ parameters: AnimatorControllerDef['parameters'] = [],
+): AnimatorControllerAPI {
+ const timeline = new TimelineAPI();
+ for (const [name, asset] of Object.entries(assets)) timeline.registerAsset(name, asset);
+ const ctrl = new AnimatorControllerAPI();
+ ctrl.registerMotionDriver(TIMELINE_MOTION, createTimelineMotionDriver(timeline));
+ ctrl.registerController('rig', { parameters, ...oneState(base), layers });
+ return ctrl;
+}
+
+function attach(world: any): void {
+ world.insert(E, Animator, {
+ controller: 'rig', currentState: '', layerStates: [], enabled: true,
+ } as AnimatorData);
+}
+
+const over = (name: string, patch: Partial<AnimatorLayer> = {}): AnimatorLayer =>
+ ({ name: `over-${name}`, ...oneState(name), ...patch });
+
+describe('a stack of layers', () => {
+ const assets = {
+ 'low.estimeline': hold({ lift: 0 }),
+ 'high.estimeline': hold({ lift: 100 }),
+ };
+
+ it('counts the base layer as one of them', () => {
+ const def: AnimatorControllerDef = {
+ parameters: [], ...oneState('low.estimeline'), layers: [over('high.estimeline')],
+ };
+ expect(animatorLayerCount(def)).toBe(2);
+ expect(animatorLayerCount({ parameters: [], ...oneState('low.estimeline') })).toBe(1);
+ });
+
+ it('lets a layer at full weight state the field outright', () => {
+ const world = seedWorld();
+ const ctrl = build(assets, 'low.estimeline', [over('high.estimeline')]);
+ attach(world);
+
+ ctrl.update(world, 0.016);
+
+ expect(read(world).lift).toBeCloseTo(100, 4);
+ });
+
+ it('leans the stack partway at a partial weight', () => {
+ const world = seedWorld();
+ const ctrl = build(assets, 'low.estimeline', [over('high.estimeline', { weight: 0.25 })]);
+ attach(world);
+
+ ctrl.update(world, 0.016);
+
+ // Not 100 (handed over) and not 0 (ignored): a quarter of the way.
+ expect(read(world).lift).toBeCloseTo(25, 4);
+ });
+
+ it('leaves what is under it alone at weight zero', () => {
+ const world = seedWorld();
+ const ctrl = build(assets, 'low.estimeline', [over('high.estimeline', { weight: 0 })]);
+ attach(world);
+
+ ctrl.update(world, 0.016);
+
+ expect(read(world).lift).toBeCloseTo(0, 6);
+ });
+
+ it('is a DIFFERENT character when the two layers are swapped', () => {
+ // The property that separates a stack from a mix. If this passes with the
+ // order reversed, composition has collapsed into an average and every
+ // other claim in this file is trivially satisfied.
+ const stacked = (base: string, top: string) => {
+ const world = seedWorld();
+ const ctrl = build(assets, base, [over(top, { weight: 0.25 })]);
+ attach(world);
+ ctrl.update(world, 0.016);
+ return read(world).lift;
+ };
+
+ expect(stacked('low.estimeline', 'high.estimeline')).toBeCloseTo(25, 4);
+ expect(stacked('high.estimeline', 'low.estimeline')).toBeCloseTo(75, 4);
+ });
+
+ it('writes the world once, as the stack rather than as the top layer', () => {
+ // The base states `turn` and nothing above it does. A layer overwriting
+ // the entity on its own would leave `turn` at the world's value.
+ const world = seedWorld();
+ const ctrl = build({
+ 'low.estimeline': hold({ lift: 0, turn: 42 }),
+ 'high.estimeline': hold({ lift: 100 }),
+ }, 'low.estimeline', [over('high.estimeline')]);
+ attach(world);
+
+ ctrl.update(world, 0.016);
+
+ expect(read(world).lift).toBeCloseTo(100, 4);
+ expect(read(world).turn).toBeCloseTo(42, 4);
+ });
+});
+
+describe('an additive layer', () => {
+ const assets = {
+ 'walk.estimeline': hold({ lift: 10 }),
+ 'run.estimeline': hold({ lift: 200 }),
+ // Departs from 0 and reaches 50 — what it ADDS is 0 at the start.
+ 'lean.estimeline': ramp('lift', 0, 50),
+ };
+
+ it('adds what its clip departed from its own start, not from the layer below', () => {
+ const world = seedWorld();
+ const ctrl = build(assets, 'walk.estimeline',
+ [over('lean.estimeline', { blend: 'additive' })]);
+ attach(world);
+ ctrl.update(world, 0);
+ ctrl.update(world, 5); // half of the ramp: it has departed by 25
+
+ expect(read(world).lift).toBeCloseTo(35, 3);
+ });
+
+ it('means the same thing over a different base', () => {
+ // The point of additive: the same lean over a run is the same departure.
+ // Measured against what is underneath instead, it would land at 25.
+ const world = seedWorld();
+ const ctrl = build(assets, 'run.estimeline',
+ [over('lean.estimeline', { blend: 'additive' })]);
+ attach(world);
+ ctrl.update(world, 0);
+ ctrl.update(world, 5);
+
+ expect(read(world).lift).toBeCloseTo(225, 3);
+ });
+
+ it('scales the departure by the layer weight', () => {
+ const world = seedWorld();
+ const ctrl = build(assets, 'walk.estimeline',
+ [over('lean.estimeline', { blend: 'additive', weight: 0.5 })]);
+ attach(world);
+ ctrl.update(world, 0);
+ ctrl.update(world, 5);
+
+ expect(read(world).lift).toBeCloseTo(22.5, 3);
+ });
+});
+
+describe('each layer runs its own machine', () => {
+ const assets = {
+ 'idle.estimeline': hold({ lift: 0 }),
+ 'walk.estimeline': hold({ lift: 100 }),
+ 'calm.estimeline': hold({ turn: 0 }),
+ 'wave.estimeline': hold({ turn: 90 }),
+ };
+
+ /** Base: idle → walk on `moving`. Upper: calm → wave on the `greet` trigger. */
+ function twoMachines(): AnimatorControllerAPI {
+ const timeline = new TimelineAPI();
+ for (const [name, asset] of Object.entries(assets)) timeline.registerAsset(name, asset);
+ const ctrl = new AnimatorControllerAPI();
+ ctrl.registerMotionDriver(TIMELINE_MOTION, createTimelineMotionDriver(timeline));
+ ctrl.registerController('rig', {
+ parameters: [
+ { name: 'moving', type: 'bool', default: false },
+ { name: 'greet', type: 'trigger' },
+ ],
+ initialState: 'Idle',
+ states: [
+ {
+ name: 'Idle', motion: clip('idle.estimeline'),
+ transitions: [{ to: 'Walk', conditions: [{ param: 'moving', op: 'true' }] }],
+ },
+ { name: 'Walk', motion: clip('walk.estimeline'), transitions: [] },
+ ],
+ layers: [{
+ name: 'arms',
+ initialState: 'Calm',
+ states: [
+ {
+ name: 'Calm', motion: clip('calm.estimeline'),
+ transitions: [{ to: 'Wave', conditions: [{ param: 'greet', op: 'trigger' }] }],
+ },
+ { name: 'Wave', motion: clip('wave.estimeline'), transitions: [] },
+ ],
+ }],
+ });
+ return ctrl;
+ }
+
+ it('moves one layer without moving the other', () => {
+ const world = seedWorld();
+ const ctrl = twoMachines();
+ attach(world);
+ ctrl.update(world, 0.016);
+
+ ctrl.setBool(E, 'moving', true);
+ ctrl.update(world, 0.016);
+
+ const a = world.get(E, Animator) as AnimatorData;
+ expect(layerState(a, 0)).toBe('Walk');
+ expect(layerState(a, 1)).toBe('Calm');
+ expect(read(world).lift).toBeCloseTo(100, 4);
+ expect(read(world).turn).toBeCloseTo(0, 4);
+ });
+
+ it('keeps each layer’s state in one place', () => {
+ const world = seedWorld();
+ const ctrl = twoMachines();
+ attach(world);
+ ctrl.update(world, 0.016);
+ ctrl.setTrigger(E, 'greet');
+ ctrl.update(world, 0.016);
+
+ const a = world.get(E, Animator) as AnimatorData;
+ expect(a.currentState).toBe('Idle');
+ expect(a.layerStates[0]).toBe('Wave');
+ expect(read(world).turn).toBeCloseTo(90, 4);
+ });
+
+ it('tells every layer about a trigger, not whichever was stepped first', () => {
+ // Both machines answer `greet`. Consumed as each layer fires, the base
+ // would eat it and the arms would never wave.
+ const world = seedWorld();
+ const timeline = new TimelineAPI();
+ for (const [name, asset] of Object.entries(assets)) timeline.registerAsset(name, asset);
+ const ctrl = new AnimatorControllerAPI();
+ ctrl.registerMotionDriver(TIMELINE_MOTION, createTimelineMotionDriver(timeline));
+ const answersGreet = (from: string, to: string, a: string, b: string) => ({
+ initialState: from,
+ states: [
+ {
+ name: from, motion: clip(a),
+ transitions: [{ to, conditions: [{ param: 'greet', op: 'trigger' as const }] }],
+ },
+ { name: to, motion: clip(b), transitions: [] },
+ ],
+ });
+ ctrl.registerController('rig', {
+ parameters: [{ name: 'greet', type: 'trigger' }],
+ ...answersGreet('Idle', 'Walk', 'idle.estimeline', 'walk.estimeline'),
+ layers: [{ name: 'arms', ...answersGreet('Calm', 'Wave', 'calm.estimeline', 'wave.estimeline') }],
+ });
+ attach(world);
+ ctrl.update(world, 0.016);
+
+ ctrl.setTrigger(E, 'greet');
+ ctrl.update(world, 0.016);
+
+ const a = world.get(E, Animator) as AnimatorData;
+ expect(a.currentState).toBe('Walk');
+ expect(a.layerStates[0]).toBe('Wave');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// What a file is allowed to claim
+// ---------------------------------------------------------------------------
+
+describe('the controller format guard', () => {
+ const v1 = () => ({
+ parameters: [], initialState: 'Idle',
+ states: [{ name: 'Idle', transitions: [] }],
+ });
+
+ it('reads a file written before layers existed as a stack of one', () => {
+ const { def, migrated, fromVersion } = migrateAnimatorController(v1());
+ expect(fromVersion).toBe(1);
+ expect(migrated).toBe(true);
+ expect(def.version).toBe(ANIMATOR_FORMAT_VERSION);
+ expect(animatorLayerCount(def)).toBe(1);
+ });
+
+ it('leaves a current file alone, however many times it is asked', () => {
+ const current = { ...v1(), version: ANIMATOR_FORMAT_VERSION };
+ const once = migrateAnimatorController(current);
+ const twice = migrateAnimatorController(once.def);
+ expect(once.migrated).toBe(false);
+ expect(twice.def).toEqual(once.def);
+ });
+
+ it('refuses a file from a later build instead of reading half of it', () => {
+ // The whole point of the stamp: a controller whose layers this build
+ // cannot see animates a visibly wrong character and reports nothing.
+ expect(() => migrateAnimatorController({ ...v1(), version: ANIMATOR_FORMAT_VERSION + 1 }))
+ .toThrow(/version/);
+ });
+
+ it('refuses a layer that is not a machine', () => {
+ expect(() => migrateAnimatorController({ ...v1(), layers: [{ name: 'arms' }] }))
+ .toThrow(/layer/);
+ expect(() => migrateAnimatorController({ ...v1(), layers: {} })).toThrow(/layers/);
+ });
+});