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(animation): a state names a motion, and something else knows how to play it

esengined07e181b3ba4
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 9ac725cde..cdbe6cbb1 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: 113 public · 84 beta · 1521 experimental · 3 deprecated
+Symbols: 113 public · 84 beta · 1537 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -398,6 +398,19 @@ parameter: string
thresholds: AnimatorBlendThreshold[]
```
+## AnimatorBlend1DMotion — interface @experimental
+```
+kind: "blend1d"
+parameter: string
+thresholds: AnimatorBlendStop[]
+```
+
+## AnimatorBlendStop — interface @experimental
+```
+motion: AnimatorMotion
+value: number
+```
+
## AnimatorBlendThreshold — interface @experimental
```
clip: string
@@ -406,6 +419,14 @@ speed: number | undefined
value: number
```
+## AnimatorClipMotion — interface @experimental
+```
+clip: string
+kind: string
+loop: boolean | undefined
+speed: number | undefined
+```
+
## AnimatorCondition — type @experimental
```
| { param: string; op: 'gt' | 'lt' | 'eq' | 'neq'; value: number }
@@ -424,7 +445,9 @@ clearControllers: () => void
getBool: (entity: Entity, name: string) => boolean
getController: (name: string) => AnimatorControllerDef | undefined
getFloat: (entity: Entity, name: string) => number
+hasMotionDriver: (kind: string) => boolean
registerController: (name: string, def: AnimatorControllerDef) => void
+registerMotionDriver: <M extends AnimatorMotion>(kind: M["kind"], driver: MotionDriver<M>) => void
removeEntity: (entity: Entity) => void
resetTrigger: (entity: Entity, name: string) => void
setBool: (entity: Entity, name: string, value: boolean) => void
@@ -467,6 +490,11 @@ consumedTriggers: string[]
next: string | null
```
+## AnimatorMotion — type @experimental
+```
+AnimatorClipMotion | AnimatorBlend1DMotion
+```
+
## AnimatorParam — interface @experimental
```
default: number | boolean | undefined
@@ -506,6 +534,7 @@ loop: boolean | undefined
blend: AnimatorBlend1D | undefined
clip: string | undefined
loop: boolean | undefined
+motion: AnimatorMotion | undefined
name: string
speed: number | undefined
spine: AnimatorSpineMotion | undefined
@@ -4805,6 +4834,32 @@ meta: boolean
shift: boolean
```
+## MotionContext — interface @experimental
+```
+drive: (motion: AnimatorMotion, enter: boolean) => void
+entity: number
+finished: (motion: AnimatorMotion) => boolean
+params: Readonly<Record<string, number | boolean>>
+world: World
+```
+
+## MotionDriver — interface @experimental
+```
+apply: (ctx: MotionContext, motion: M, enter: boolean) => void
+isFinished: (ctx: MotionContext, motion: M) => boolean
+```
+
+## MotionRegistry — class @experimental
+```
+context: (world: World, entity: Entity, params: MotionParams) => MotionContext
+driverFor: (motion: AnimatorMotion) => MotionDriver | undefined
+has: (kind: string) => boolean
+register: <M extends AnimatorMotion>(kind: M["kind"], driver: MotionDriver<M>) => void
+unregister: (kind: string) => void
+static new (): MotionRegistry
+static prototype: MotionRegistry
+```
+
## MotorJoint2D — const @experimental
```
ComponentDef<MotorJoint2DData>
@@ -6803,11 +6858,21 @@ ComponentDef<{}>
Record<BuiltinSideModuleId, SideModuleDescriptor>
```
+## SPINE_MOTION — const @experimental
+```
+"spine"
+```
+
## SPINE_VERSIONS — const @experimental
```
readonly SpineVersion[]
```
+## SPRITE_MOTION — const @experimental
+```
+"sprite"
+```
+
## STATE_PATH_SEP — const @experimental
```
"/"
@@ -8014,6 +8079,11 @@ number
"1.2"
```
+## TIMELINE_MOTION — const @experimental
+```
+"timeline"
+```
+
## TParams — type @experimental
```
Record<string, string | number>
@@ -9910,6 +9980,11 @@ AudioPlugin
<C extends object, K extends keyof C>(world: World, events: UIEventQueue, entity: Entity, component: ComponentDef<C>, field: K, signal: Signal<C[K]>, payloadKey?: string): () => void
```
+## blend1DMotionDriver — const @experimental
+```
+MotionDriver<AnimatorBlend1DMotion>
+```
+
## btEdges — function @experimental
```
(def: BtDefinition): BtEdge[]
@@ -10335,6 +10410,11 @@ Plugin
(texture: string, tileWidth?: number, tileHeight?: number, columns?: number): TilesetAsset
```
+## createTimelineMotionDriver — function @experimental
+```
+(timeline: TimelineAPI): MotionDriver<AnimatorClipMotion>
+```
+
## createToggle — function @experimental
```
(opts: ToggleOptions): ToggleHandle
@@ -11365,6 +11445,11 @@ MeshRendererPlugin
(mode: AssetGroupMode): BundleMode
```
+## motionOf — function @experimental
+```
+(st: AnimatorState): AnimatorMotion | null
+```
+
## moveAnimatorState — function @experimental
```
(def: AnimatorControllerDef, name: string, x: number, y: number): AnimatorControllerDef
@@ -12115,6 +12200,11 @@ Plugin
(blend: AnimatorBlend1D, value: number): AnimatorBlendThreshold
```
+## selectBlendStop — function @experimental
+```
+(blend: AnimatorBlend1DMotion, value: number): AnimatorBlendStop | null
+```
+
## selectPluralForm — function @experimental
```
(forms: PluralForms, count: number, selector: PluralSelector): string
@@ -12170,6 +12260,11 @@ ServicesPlugin
(def: AnimatorControllerDef, name: string, clip: string): AnimatorControllerDef
```
+## setAnimatorStateMotion — function @experimental
+```
+(def: AnimatorControllerDef, name: string, motion: AnimatorMotion | null): AnimatorControllerDef
+```
+
## setAnimatorStateProps — function @experimental
```
(def: AnimatorControllerDef, name: string, patch: { speed?: number; loop?: boolean; }): AnimatorControllerDef
@@ -12380,6 +12475,11 @@ ServicesPlugin
(version: SpineVersion): SideModuleId
```
+## spriteMotionDriver — const @experimental
+```
+MotionDriver<AnimatorClipMotion>
+```
+
## stackOf — function @experimental
```
(error: unknown): string | undefined
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index ec0cdd2ee..b4053ec1f 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: 113 public · 89 beta · 1540 experimental · 3 deprecated
+Symbols: 113 public · 89 beta · 1556 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -398,6 +398,19 @@ parameter: string
thresholds: AnimatorBlendThreshold[]
```
+## AnimatorBlend1DMotion — interface @experimental
+```
+kind: "blend1d"
+parameter: string
+thresholds: AnimatorBlendStop[]
+```
+
+## AnimatorBlendStop — interface @experimental
+```
+motion: AnimatorMotion
+value: number
+```
+
## AnimatorBlendThreshold — interface @experimental
```
clip: string
@@ -406,6 +419,14 @@ speed: number | undefined
value: number
```
+## AnimatorClipMotion — interface @experimental
+```
+clip: string
+kind: string
+loop: boolean | undefined
+speed: number | undefined
+```
+
## AnimatorCondition — type @experimental
```
| { param: string; op: 'gt' | 'lt' | 'eq' | 'neq'; value: number }
@@ -424,7 +445,9 @@ clearControllers: () => void
getBool: (entity: Entity, name: string) => boolean
getController: (name: string) => AnimatorControllerDef | undefined
getFloat: (entity: Entity, name: string) => number
+hasMotionDriver: (kind: string) => boolean
registerController: (name: string, def: AnimatorControllerDef) => void
+registerMotionDriver: <M extends AnimatorMotion>(kind: M["kind"], driver: MotionDriver<M>) => void
removeEntity: (entity: Entity) => void
resetTrigger: (entity: Entity, name: string) => void
setBool: (entity: Entity, name: string, value: boolean) => void
@@ -467,6 +490,11 @@ consumedTriggers: string[]
next: string | null
```
+## AnimatorMotion — type @experimental
+```
+AnimatorClipMotion | AnimatorBlend1DMotion
+```
+
## AnimatorParam — interface @experimental
```
default: number | boolean | undefined
@@ -506,6 +534,7 @@ loop: boolean | undefined
blend: AnimatorBlend1D | undefined
clip: string | undefined
loop: boolean | undefined
+motion: AnimatorMotion | undefined
name: string
speed: number | undefined
spine: AnimatorSpineMotion | undefined
@@ -4818,6 +4847,32 @@ meta: boolean
shift: boolean
```
+## MotionContext — interface @experimental
+```
+drive: (motion: AnimatorMotion, enter: boolean) => void
+entity: number
+finished: (motion: AnimatorMotion) => boolean
+params: Readonly<Record<string, number | boolean>>
+world: World
+```
+
+## MotionDriver — interface @experimental
+```
+apply: (ctx: MotionContext, motion: M, enter: boolean) => void
+isFinished: (ctx: MotionContext, motion: M) => boolean
+```
+
+## MotionRegistry — class @experimental
+```
+context: (world: World, entity: Entity, params: MotionParams) => MotionContext
+driverFor: (motion: AnimatorMotion) => MotionDriver | undefined
+has: (kind: string) => boolean
+register: <M extends AnimatorMotion>(kind: M["kind"], driver: MotionDriver<M>) => void
+unregister: (kind: string) => void
+static new (): MotionRegistry
+static prototype: MotionRegistry
+```
+
## MotorJoint2D — const @experimental
```
ComponentDef<MotorJoint2DData>
@@ -6996,11 +7051,21 @@ ComponentDef<{}>
Record<BuiltinSideModuleId, SideModuleDescriptor>
```
+## SPINE_MOTION — const @experimental
+```
+"spine"
+```
+
## SPINE_VERSIONS — const @experimental
```
readonly SpineVersion[]
```
+## SPRITE_MOTION — const @experimental
+```
+"sprite"
+```
+
## STATE_PATH_SEP — const @experimental
```
"/"
@@ -8207,6 +8272,11 @@ number
"1.2"
```
+## TIMELINE_MOTION — const @experimental
+```
+"timeline"
+```
+
## TParams — type @experimental
```
Record<string, string | number>
@@ -10118,6 +10188,11 @@ AudioPlugin
<C extends object, K extends keyof C>(world: World, events: UIEventQueue, entity: Entity, component: ComponentDef<C>, field: K, signal: Signal<C[K]>, payloadKey?: string): () => void
```
+## blend1DMotionDriver — const @experimental
+```
+MotionDriver<AnimatorBlend1DMotion>
+```
+
## btEdges — function @experimental
```
(def: BtDefinition): BtEdge[]
@@ -10568,6 +10643,11 @@ Plugin
(texture: string, tileWidth?: number, tileHeight?: number, columns?: number): TilesetAsset
```
+## createTimelineMotionDriver — function @experimental
+```
+(timeline: TimelineAPI): MotionDriver<AnimatorClipMotion>
+```
+
## createToggle — function @experimental
```
(opts: ToggleOptions): ToggleHandle
@@ -11608,6 +11688,11 @@ MeshRendererPlugin
(mode: AssetGroupMode): BundleMode
```
+## motionOf — function @experimental
+```
+(st: AnimatorState): AnimatorMotion | null
+```
+
## moveAnimatorState — function @experimental
```
(def: AnimatorControllerDef, name: string, x: number, y: number): AnimatorControllerDef
@@ -12358,6 +12443,11 @@ Plugin
(blend: AnimatorBlend1D, value: number): AnimatorBlendThreshold
```
+## selectBlendStop — function @experimental
+```
+(blend: AnimatorBlend1DMotion, value: number): AnimatorBlendStop | null
+```
+
## selectPluralForm — function @experimental
```
(forms: PluralForms, count: number, selector: PluralSelector): string
@@ -12413,6 +12503,11 @@ ServicesPlugin
(def: AnimatorControllerDef, name: string, clip: string): AnimatorControllerDef
```
+## setAnimatorStateMotion — function @experimental
+```
+(def: AnimatorControllerDef, name: string, motion: AnimatorMotion | null): AnimatorControllerDef
+```
+
## setAnimatorStateProps — function @experimental
```
(def: AnimatorControllerDef, name: string, patch: { speed?: number; loop?: boolean; }): AnimatorControllerDef
@@ -12623,6 +12718,11 @@ ServicesPlugin
(version: SpineVersion): SideModuleId
```
+## spriteMotionDriver — const @experimental
+```
+MotionDriver<AnimatorClipMotion>
+```
+
## stackOf — function @experimental
```
(error: unknown): string | undefined
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 08ff740bb..5f58feafa 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: 113 public · 86 beta · 1520 experimental · 3 deprecated
+Symbols: 113 public · 86 beta · 1536 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -393,6 +393,19 @@ parameter: string
thresholds: AnimatorBlendThreshold[]
```
+## AnimatorBlend1DMotion — interface @experimental
+```
+kind: "blend1d"
+parameter: string
+thresholds: AnimatorBlendStop[]
+```
+
+## AnimatorBlendStop — interface @experimental
+```
+motion: AnimatorMotion
+value: number
+```
+
## AnimatorBlendThreshold — interface @experimental
```
clip: string
@@ -401,6 +414,14 @@ speed: number | undefined
value: number
```
+## AnimatorClipMotion — interface @experimental
+```
+clip: string
+kind: string
+loop: boolean | undefined
+speed: number | undefined
+```
+
## AnimatorCondition — type @experimental
```
| { param: string; op: 'gt' | 'lt' | 'eq' | 'neq'; value: number }
@@ -419,7 +440,9 @@ clearControllers: () => void
getBool: (entity: Entity, name: string) => boolean
getController: (name: string) => AnimatorControllerDef | undefined
getFloat: (entity: Entity, name: string) => number
+hasMotionDriver: (kind: string) => boolean
registerController: (name: string, def: AnimatorControllerDef) => void
+registerMotionDriver: <M extends AnimatorMotion>(kind: M["kind"], driver: MotionDriver<M>) => void
removeEntity: (entity: Entity) => void
resetTrigger: (entity: Entity, name: string) => void
setBool: (entity: Entity, name: string, value: boolean) => void
@@ -462,6 +485,11 @@ consumedTriggers: string[]
next: string | null
```
+## AnimatorMotion — type @experimental
+```
+AnimatorClipMotion | AnimatorBlend1DMotion
+```
+
## AnimatorParam — interface @experimental
```
default: number | boolean | undefined
@@ -501,6 +529,7 @@ loop: boolean | undefined
blend: AnimatorBlend1D | undefined
clip: string | undefined
loop: boolean | undefined
+motion: AnimatorMotion | undefined
name: string
speed: number | undefined
spine: AnimatorSpineMotion | undefined
@@ -4800,6 +4829,32 @@ meta: boolean
shift: boolean
```
+## MotionContext — interface @experimental
+```
+drive: (motion: AnimatorMotion, enter: boolean) => void
+entity: number
+finished: (motion: AnimatorMotion) => boolean
+params: Readonly<Record<string, number | boolean>>
+world: World
+```
+
+## MotionDriver — interface @experimental
+```
+apply: (ctx: MotionContext, motion: M, enter: boolean) => void
+isFinished: (ctx: MotionContext, motion: M) => boolean
+```
+
+## MotionRegistry — class @experimental
+```
+context: (world: World, entity: Entity, params: MotionParams) => MotionContext
+driverFor: (motion: AnimatorMotion) => MotionDriver | undefined
+has: (kind: string) => boolean
+register: <M extends AnimatorMotion>(kind: M["kind"], driver: MotionDriver<M>) => void
+unregister: (kind: string) => void
+static new (): MotionRegistry
+static prototype: MotionRegistry
+```
+
## MotorJoint2D — const @experimental
```
ComponentDef<MotorJoint2DData>
@@ -6798,11 +6853,21 @@ ComponentDef<{}>
Record<BuiltinSideModuleId, SideModuleDescriptor>
```
+## SPINE_MOTION — const @experimental
+```
+"spine"
+```
+
## SPINE_VERSIONS — const @experimental
```
readonly SpineVersion[]
```
+## SPRITE_MOTION — const @experimental
+```
+"sprite"
+```
+
## STATE_PATH_SEP — const @experimental
```
"/"
@@ -8009,6 +8074,11 @@ number
"1.2"
```
+## TIMELINE_MOTION — const @experimental
+```
+"timeline"
+```
+
## TParams — type @experimental
```
Record<string, string | number>
@@ -9905,6 +9975,11 @@ AudioPlugin
<C extends object, K extends keyof C>(world: World, events: UIEventQueue, entity: Entity, component: ComponentDef<C>, field: K, signal: Signal<C[K]>, payloadKey?: string): () => void
```
+## blend1DMotionDriver — const @experimental
+```
+MotionDriver<AnimatorBlend1DMotion>
+```
+
## btEdges — function @experimental
```
(def: BtDefinition): BtEdge[]
@@ -10330,6 +10405,11 @@ Plugin
(texture: string, tileWidth?: number, tileHeight?: number, columns?: number): TilesetAsset
```
+## createTimelineMotionDriver — function @experimental
+```
+(timeline: TimelineAPI): MotionDriver<AnimatorClipMotion>
+```
+
## createToggle — function @experimental
```
(opts: ToggleOptions): ToggleHandle
@@ -11365,6 +11445,11 @@ MeshRendererPlugin
(mode: AssetGroupMode): BundleMode
```
+## motionOf — function @experimental
+```
+(st: AnimatorState): AnimatorMotion | null
+```
+
## moveAnimatorState — function @experimental
```
(def: AnimatorControllerDef, name: string, x: number, y: number): AnimatorControllerDef
@@ -12120,6 +12205,11 @@ Plugin
(blend: AnimatorBlend1D, value: number): AnimatorBlendThreshold
```
+## selectBlendStop — function @experimental
+```
+(blend: AnimatorBlend1DMotion, value: number): AnimatorBlendStop | null
+```
+
## selectPluralForm — function @experimental
```
(forms: PluralForms, count: number, selector: PluralSelector): string
@@ -12175,6 +12265,11 @@ ServicesPlugin
(def: AnimatorControllerDef, name: string, clip: string): AnimatorControllerDef
```
+## setAnimatorStateMotion — function @experimental
+```
+(def: AnimatorControllerDef, name: string, motion: AnimatorMotion | null): AnimatorControllerDef
+```
+
## setAnimatorStateProps — function @experimental
```
(def: AnimatorControllerDef, name: string, patch: { speed?: number; loop?: boolean; }): AnimatorControllerDef
@@ -12385,6 +12480,11 @@ ServicesPlugin
(version: SpineVersion): SideModuleId
```
+## spriteMotionDriver — const @experimental
+```
+MotionDriver<AnimatorClipMotion>
+```
+
## stackOf — function @experimental
```
(error: unknown): string | undefined
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 182f31a52..68e20fac0 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/minigame
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 113 public · 84 beta · 1542 experimental · 3 deprecated
+Symbols: 113 public · 84 beta · 1558 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -393,6 +393,19 @@ parameter: string
thresholds: AnimatorBlendThreshold[]
```
+## AnimatorBlend1DMotion — interface @experimental
+```
+kind: "blend1d"
+parameter: string
+thresholds: AnimatorBlendStop[]
+```
+
+## AnimatorBlendStop — interface @experimental
+```
+motion: AnimatorMotion
+value: number
+```
+
## AnimatorBlendThreshold — interface @experimental
```
clip: string
@@ -401,6 +414,14 @@ speed: number | undefined
value: number
```
+## AnimatorClipMotion — interface @experimental
+```
+clip: string
+kind: string
+loop: boolean | undefined
+speed: number | undefined
+```
+
## AnimatorCondition — type @experimental
```
| { param: string; op: 'gt' | 'lt' | 'eq' | 'neq'; value: number }
@@ -419,7 +440,9 @@ clearControllers: () => void
getBool: (entity: Entity, name: string) => boolean
getController: (name: string) => AnimatorControllerDef | undefined
getFloat: (entity: Entity, name: string) => number
+hasMotionDriver: (kind: string) => boolean
registerController: (name: string, def: AnimatorControllerDef) => void
+registerMotionDriver: <M extends AnimatorMotion>(kind: M["kind"], driver: MotionDriver<M>) => void
removeEntity: (entity: Entity) => void
resetTrigger: (entity: Entity, name: string) => void
setBool: (entity: Entity, name: string, value: boolean) => void
@@ -462,6 +485,11 @@ consumedTriggers: string[]
next: string | null
```
+## AnimatorMotion — type @experimental
+```
+AnimatorClipMotion | AnimatorBlend1DMotion
+```
+
## AnimatorParam — interface @experimental
```
default: number | boolean | undefined
@@ -501,6 +529,7 @@ loop: boolean | undefined
blend: AnimatorBlend1D | undefined
clip: string | undefined
loop: boolean | undefined
+motion: AnimatorMotion | undefined
name: string
speed: number | undefined
spine: AnimatorSpineMotion | undefined
@@ -5046,6 +5075,32 @@ meta: boolean
shift: boolean
```
+## MotionContext — interface @experimental
+```
+drive: (motion: AnimatorMotion, enter: boolean) => void
+entity: number
+finished: (motion: AnimatorMotion) => boolean
+params: Readonly<Record<string, number | boolean>>
+world: World
+```
+
+## MotionDriver — interface @experimental
+```
+apply: (ctx: MotionContext, motion: M, enter: boolean) => void
+isFinished: (ctx: MotionContext, motion: M) => boolean
+```
+
+## MotionRegistry — class @experimental
+```
+context: (world: World, entity: Entity, params: MotionParams) => MotionContext
+driverFor: (motion: AnimatorMotion) => MotionDriver | undefined
+has: (kind: string) => boolean
+register: <M extends AnimatorMotion>(kind: M["kind"], driver: MotionDriver<M>) => void
+unregister: (kind: string) => void
+static new (): MotionRegistry
+static prototype: MotionRegistry
+```
+
## MotorJoint2D — const @experimental
```
ComponentDef<MotorJoint2DData>
@@ -7044,11 +7099,21 @@ ComponentDef<{}>
Record<BuiltinSideModuleId, SideModuleDescriptor>
```
+## SPINE_MOTION — const @experimental
+```
+"spine"
+```
+
## SPINE_VERSIONS — const @experimental
```
readonly SpineVersion[]
```
+## SPRITE_MOTION — const @experimental
+```
+"sprite"
+```
+
## STATE_PATH_SEP — const @experimental
```
"/"
@@ -8255,6 +8320,11 @@ number
"1.2"
```
+## TIMELINE_MOTION — const @experimental
+```
+"timeline"
+```
+
## TParams — type @experimental
```
Record<string, string | number>
@@ -10157,6 +10227,11 @@ AudioPlugin
<C extends object, K extends keyof C>(world: World, events: UIEventQueue, entity: Entity, component: ComponentDef<C>, field: K, signal: Signal<C[K]>, payloadKey?: string): () => void
```
+## blend1DMotionDriver — const @experimental
+```
+MotionDriver<AnimatorBlend1DMotion>
+```
+
## btEdges — function @experimental
```
(def: BtDefinition): BtEdge[]
@@ -10587,6 +10662,11 @@ Plugin
(texture: string, tileWidth?: number, tileHeight?: number, columns?: number): TilesetAsset
```
+## createTimelineMotionDriver — function @experimental
+```
+(timeline: TimelineAPI): MotionDriver<AnimatorClipMotion>
+```
+
## createToggle — function @experimental
```
(opts: ToggleOptions): ToggleHandle
@@ -11627,6 +11707,11 @@ MeshRendererPlugin
(mode: AssetGroupMode): BundleMode
```
+## motionOf — function @experimental
+```
+(st: AnimatorState): AnimatorMotion | null
+```
+
## moveAnimatorState — function @experimental
```
(def: AnimatorControllerDef, name: string, x: number, y: number): AnimatorControllerDef
@@ -12377,6 +12462,11 @@ Plugin
(blend: AnimatorBlend1D, value: number): AnimatorBlendThreshold
```
+## selectBlendStop — function @experimental
+```
+(blend: AnimatorBlend1DMotion, value: number): AnimatorBlendStop | null
+```
+
## selectPluralForm — function @experimental
```
(forms: PluralForms, count: number, selector: PluralSelector): string
@@ -12432,6 +12522,11 @@ ServicesPlugin
(def: AnimatorControllerDef, name: string, clip: string): AnimatorControllerDef
```
+## setAnimatorStateMotion — function @experimental
+```
+(def: AnimatorControllerDef, name: string, motion: AnimatorMotion | null): AnimatorControllerDef
+```
+
## setAnimatorStateProps — function @experimental
```
(def: AnimatorControllerDef, name: string, patch: { speed?: number; loop?: boolean; }): AnimatorControllerDef
@@ -12642,6 +12737,11 @@ ServicesPlugin
(version: SpineVersion): SideModuleId
```
+## spriteMotionDriver — const @experimental
+```
+MotionDriver<AnimatorClipMotion>
+```
+
## stackOf — function @experimental
```
(error: unknown): string | undefined
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 1e3ea1005..cc727ead8 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: 113 public · 84 beta · 1532 experimental · 3 deprecated
+Symbols: 113 public · 84 beta · 1548 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -393,6 +393,19 @@ parameter: string
thresholds: AnimatorBlendThreshold[]
```
+## AnimatorBlend1DMotion — interface @experimental
+```
+kind: "blend1d"
+parameter: string
+thresholds: AnimatorBlendStop[]
+```
+
+## AnimatorBlendStop — interface @experimental
+```
+motion: AnimatorMotion
+value: number
+```
+
## AnimatorBlendThreshold — interface @experimental
```
clip: string
@@ -401,6 +414,14 @@ speed: number | undefined
value: number
```
+## AnimatorClipMotion — interface @experimental
+```
+clip: string
+kind: string
+loop: boolean | undefined
+speed: number | undefined
+```
+
## AnimatorCondition — type @experimental
```
| { param: string; op: 'gt' | 'lt' | 'eq' | 'neq'; value: number }
@@ -419,7 +440,9 @@ clearControllers: () => void
getBool: (entity: Entity, name: string) => boolean
getController: (name: string) => AnimatorControllerDef | undefined
getFloat: (entity: Entity, name: string) => number
+hasMotionDriver: (kind: string) => boolean
registerController: (name: string, def: AnimatorControllerDef) => void
+registerMotionDriver: <M extends AnimatorMotion>(kind: M["kind"], driver: MotionDriver<M>) => void
removeEntity: (entity: Entity) => void
resetTrigger: (entity: Entity, name: string) => void
setBool: (entity: Entity, name: string, value: boolean) => void
@@ -462,6 +485,11 @@ consumedTriggers: string[]
next: string | null
```
+## AnimatorMotion — type @experimental
+```
+AnimatorClipMotion | AnimatorBlend1DMotion
+```
+
## AnimatorParam — interface @experimental
```
default: number | boolean | undefined
@@ -501,6 +529,7 @@ loop: boolean | undefined
blend: AnimatorBlend1D | undefined
clip: string | undefined
loop: boolean | undefined
+motion: AnimatorMotion | undefined
name: string
speed: number | undefined
spine: AnimatorSpineMotion | undefined
@@ -4807,6 +4836,32 @@ meta: boolean
shift: boolean
```
+## MotionContext — interface @experimental
+```
+drive: (motion: AnimatorMotion, enter: boolean) => void
+entity: number
+finished: (motion: AnimatorMotion) => boolean
+params: Readonly<Record<string, number | boolean>>
+world: World
+```
+
+## MotionDriver — interface @experimental
+```
+apply: (ctx: MotionContext, motion: M, enter: boolean) => void
+isFinished: (ctx: MotionContext, motion: M) => boolean
+```
+
+## MotionRegistry — class @experimental
+```
+context: (world: World, entity: Entity, params: MotionParams) => MotionContext
+driverFor: (motion: AnimatorMotion) => MotionDriver | undefined
+has: (kind: string) => boolean
+register: <M extends AnimatorMotion>(kind: M["kind"], driver: MotionDriver<M>) => void
+unregister: (kind: string) => void
+static new (): MotionRegistry
+static prototype: MotionRegistry
+```
+
## MotorJoint2D — const @experimental
```
ComponentDef<MotorJoint2DData>
@@ -6805,11 +6860,21 @@ ComponentDef<{}>
Record<BuiltinSideModuleId, SideModuleDescriptor>
```
+## SPINE_MOTION — const @experimental
+```
+"spine"
+```
+
## SPINE_VERSIONS — const @experimental
```
readonly SpineVersion[]
```
+## SPRITE_MOTION — const @experimental
+```
+"sprite"
+```
+
## STATE_PATH_SEP — const @experimental
```
"/"
@@ -8016,6 +8081,11 @@ number
"1.2"
```
+## TIMELINE_MOTION — const @experimental
+```
+"timeline"
+```
+
## TParams — type @experimental
```
Record<string, string | number>
@@ -9933,6 +10003,11 @@ AudioPlugin
<C extends object, K extends keyof C>(world: World, events: UIEventQueue, entity: Entity, component: ComponentDef<C>, field: K, signal: Signal<C[K]>, payloadKey?: string): () => void
```
+## blend1DMotionDriver — const @experimental
+```
+MotionDriver<AnimatorBlend1DMotion>
+```
+
## btEdges — function @experimental
```
(def: BtDefinition): BtEdge[]
@@ -10358,6 +10433,11 @@ Plugin
(texture: string, tileWidth?: number, tileHeight?: number, columns?: number): TilesetAsset
```
+## createTimelineMotionDriver — function @experimental
+```
+(timeline: TimelineAPI): MotionDriver<AnimatorClipMotion>
+```
+
## createToggle — function @experimental
```
(opts: ToggleOptions): ToggleHandle
@@ -11393,6 +11473,11 @@ MeshRendererPlugin
(mode: AssetGroupMode): BundleMode
```
+## motionOf — function @experimental
+```
+(st: AnimatorState): AnimatorMotion | null
+```
+
## moveAnimatorState — function @experimental
```
(def: AnimatorControllerDef, name: string, x: number, y: number): AnimatorControllerDef
@@ -12143,6 +12228,11 @@ Plugin
(blend: AnimatorBlend1D, value: number): AnimatorBlendThreshold
```
+## selectBlendStop — function @experimental
+```
+(blend: AnimatorBlend1DMotion, value: number): AnimatorBlendStop | null
+```
+
## selectPluralForm — function @experimental
```
(forms: PluralForms, count: number, selector: PluralSelector): string
@@ -12198,6 +12288,11 @@ ServicesPlugin
(def: AnimatorControllerDef, name: string, clip: string): AnimatorControllerDef
```
+## setAnimatorStateMotion — function @experimental
+```
+(def: AnimatorControllerDef, name: string, motion: AnimatorMotion | null): AnimatorControllerDef
+```
+
## setAnimatorStateProps — function @experimental
```
(def: AnimatorControllerDef, name: string, patch: { speed?: number; loop?: boolean; }): AnimatorControllerDef
@@ -12408,6 +12503,11 @@ ServicesPlugin
(version: SpineVersion): SideModuleId
```
+## spriteMotionDriver — const @experimental
+```
+MotionDriver<AnimatorClipMotion>
+```
+
## stackOf — function @experimental
```
(error: unknown): string | undefined
diff --git a/sdk/src/ai/builtins.ts b/sdk/src/ai/builtins.ts
index 57e170145..f145ea576 100644
--- a/sdk/src/ai/builtins.ts
+++ b/sdk/src/ai/builtins.ts
@@ -15,7 +15,7 @@
import { aiRegistry, type AiContext } from './fsm/AiContext';
import type { AiAction, AiActionInput, AiCondition, AiParamValue, AiTouches } from './fsm/registry';
-import { TimelinePlayer } from '../timeline/TimelinePlugin';
+import { TimelinePlayer } from '../timeline/TimelinePlayerComponent';
import { SpriteAnimator } from '../animation/SpriteAnimator';
import { setEntityProperty } from '../ecs/propertyPath';
diff --git a/sdk/src/animation/Animator.ts b/sdk/src/animation/Animator.ts
index ff988c130..5ce7ff678 100644
--- a/sdk/src/animation/Animator.ts
+++ b/sdk/src/animation/Animator.ts
@@ -2,15 +2,15 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file Animator.ts
- * @brief Animation state machine (pure TypeScript), built on the existing
- * sprite-animation channel.
+ * @brief Animation state machine (pure TypeScript) over motions of any kind.
*
* Design (per REARCH_2D_PARITY.md T2): the state machine is a *strategy layer*
- * over the existing animation channels — it does not run its own clip playback.
- * A state names a sprite clip; when a transition fires, the Animator switches the
- * entity's {@link SpriteAnimator}.clip. Frame playback stays the single
- * responsibility of {@link SpriteAnimationAPI}. Parameters/triggers drive
- * transitions, mirroring the Unity Animator's SetFloat/SetBool/SetTrigger model.
+ * over the engine's animation channels — it does not run its own clip playback.
+ * A state names a MOTION; a {@link MotionDriver} registered for that motion's
+ * kind is what plays it, so the graph is the same whether the entity is a sprite
+ * sheet or a skinned model, and a new kind of animation is a registration rather
+ * than another branch through here. Parameters/triggers drive transitions,
+ * mirroring the Unity Animator's SetFloat/SetBool/SetTrigger model.
*
* The transition evaluator ({@link evaluateAnimatorTransitions}) is pure — no
* World, no side effects — so it is fully unit-testable.
@@ -21,7 +21,12 @@ import { defineResource } from '../ecs/resource';
import { isUuidRef } from '../asset/AssetRegistry';
import type { Entity } from '../types';
import type { World } from '../ecs/world';
-import { SpriteAnimator, type SpriteAnimatorData } from './SpriteAnimator';
+import {
+ MotionRegistry, blend1DMotionDriver,
+ type AnimatorMotion, type AnimatorClipMotion, type AnimatorBlend1DMotion,
+ type MotionContext, type MotionDriver,
+} from './motion';
+import { SPRITE_MOTION, spriteMotionDriver } from './spriteMotion';
// =============================================================================
// Controller definition (the graph data)
@@ -107,6 +112,12 @@ export interface AnimatorSubMachine {
export interface AnimatorState {
name: string;
+ /**
+ * What this state plays, of any registered kind (`sprite`, `timeline`, a
+ * blend over either). Takes precedence over the single-kind fields below,
+ * which are the same thing spelled for one kind and are migrated to this.
+ */
+ motion?: AnimatorMotion;
/** Single sprite clip this state plays. Mutually exclusive with `blend`/`spine`/`stateMachine`. */
clip?: string;
/** 1D blend selection. Mutually exclusive with `clip`/`spine`/`stateMachine`. */
@@ -322,6 +333,58 @@ export function selectBlendClip(blend: AnimatorBlend1D, value: number): Animator
return chosen;
}
+/** Motion kind for a Spine animation; the spine module registers its driver. */
+export const SPINE_MOTION = 'spine';
+
+/**
+ * Migrated motions, keyed by the state that spelled one the single-kind way.
+ * A controller's states are stable objects, so this converts once rather than
+ * every frame — and keeps `motionOf` free to return a fresh shape without
+ * allocating one per tick.
+ */
+const migratedMotions = new WeakMap<AnimatorState, AnimatorMotion | null>();
+
+/** A legacy 1D blend over sprite clips, as the equivalent blend over motions.
+ * A stop's own speed/loop wins over the state's, which is what it did before. */
+function spriteBlendMotion(st: AnimatorState, blend: AnimatorBlend1D): AnimatorBlend1DMotion {
+ return {
+ kind: 'blend1d',
+ parameter: blend.parameter,
+ thresholds: blend.thresholds.map(t => ({
+ value: t.value,
+ motion: {
+ kind: SPRITE_MOTION,
+ clip: t.clip,
+ speed: t.speed ?? st.speed,
+ loop: t.loop ?? st.loop,
+ } satisfies AnimatorClipMotion,
+ })),
+ };
+}
+
+/**
+ * What a state plays, whichever way it was authored: `motion`, or the
+ * `clip`/`blend`/`spine` fields every controller written before motions used.
+ * Read here rather than rewritten on load, so those keep working untouched.
+ * Null for a state with no motion of its own (a container).
+ */
+export function motionOf(st: AnimatorState): AnimatorMotion | null {
+ const cached = migratedMotions.get(st);
+ if (cached !== undefined) return cached;
+
+ let motion: AnimatorMotion | null = null;
+ if (st.motion) motion = st.motion;
+ else if (st.spine) {
+ motion = { kind: SPINE_MOTION, clip: st.spine.animation, loop: st.spine.loop };
+ } else if (st.blend) motion = spriteBlendMotion(st, st.blend);
+ else if (st.clip) {
+ motion = { kind: SPRITE_MOTION, clip: st.clip, speed: st.speed, loop: st.loop };
+ }
+
+ migratedMotions.set(st, motion);
+ return motion;
+}
+
/** Merge a controller's declared parameter defaults with per-entity overrides. */
export function resolveParams(
def: AnimatorControllerDef,
@@ -413,12 +476,50 @@ export class AnimatorControllerAPI {
private readonly controllers = new Map<string, AnimatorControllerDef>();
private readonly params = new Map<Entity, Map<string, number | boolean>>();
private readonly triggers = new Map<Entity, Set<string>>();
- private spineDriver_: SpineAnimationDriver | null = null;
+ private readonly motions_ = new MotionRegistry();
+
+ constructor() {
+ // The kinds the animation core itself can play. Everything else — a
+ // timeline, a spine track — is registered by the module that owns it,
+ // which is what keeps this file from importing them.
+ this.motions_.register(SPRITE_MOTION, spriteMotionDriver);
+ this.motions_.register('blend1d', blend1DMotionDriver);
+ }
+
+ /**
+ * Teach this animator a kind of motion. Called by the plugin that owns the
+ * kind (TimelinePlugin, SpinePlugin); a state naming an unregistered kind is
+ * inert rather than an error, since a scene may be authored against a module
+ * this build does not load.
+ */
+ registerMotionDriver<M extends AnimatorMotion>(
+ kind: M['kind'], driver: MotionDriver<M>,
+ ): void {
+ this.motions_.register(kind, driver);
+ }
+
+ /** Whether some driver can play `kind` here. */
+ hasMotionDriver(kind: string): boolean {
+ return this.motions_.has(kind);
+ }
/** Inject the Spine driver (SpinePlugin wires SpineManager here). Optional —
* without it, spine-targeting states are inert. */
setSpineDriver(driver: SpineAnimationDriver | null): void {
- this.spineDriver_ = driver;
+ if (!driver) {
+ this.motions_.unregister(SPINE_MOTION);
+ return;
+ }
+ this.motions_.register<AnimatorClipMotion>(SPINE_MOTION, {
+ // On entry only: SpineManager owns track playback and mixing, and
+ // re-setting the animation every frame would restart it every frame.
+ apply: (ctx: MotionContext, motion: AnimatorClipMotion, enter: boolean) => {
+ if (enter) driver.setAnimation(ctx.entity, motion.clip, motion.loop ?? true);
+ },
+ // Track completion lives in SpineManager, which this seam does not
+ // read; an exit-time transition out of a spine state needs a condition.
+ isFinished: () => false,
+ });
}
// -- controller registry --------------------------------------------------
@@ -518,16 +619,12 @@ export class AnimatorControllerAPI {
const params = resolveParams(def, this.params.get(entity) ?? EMPTY_PARAMS);
const triggerSet = this.triggers.get(entity);
- // The leaf clip has finished when its SpriteAnimator is playing exactly
- // that clip and has stopped — not merely stopped (also true before the
- // clip is ever applied, e.g. the frame a state is entered). Only a
- // sprite leaf reports this; a spine leaf's completion is SpineManager's.
- const spNow = world.has(entity, SpriteAnimator)
- ? (world.get(entity, SpriteAnimator) as SpriteAnimatorData)
- : null;
- const expectedClip = !leaf.spine ? this.motionClipOf(leaf, params).clip : '';
- const clipFinished = expectedClip !== '' && spNow != null
- && spNow.clip === expectedClip && !spNow.playing;
+ const ctx = this.motions_.context(world, entity, params);
+ // Whether the motion has ended is the motion's to answer. A leaf with
+ // none (or whose kind has no driver here) reports false, so an
+ // exit-time transition waits rather than firing on nothing.
+ const leafMotion = motionOf(leaf);
+ const clipFinished = leafMotion !== null && ctx.finished(leafMotion);
const { nextPath, consumedTriggers } = evaluateAnimatorPath(
def, fromPath, params, triggerSet ?? EMPTY_TRIGGERS, clipFinished,
@@ -541,54 +638,14 @@ export class AnimatorControllerAPI {
world.insert(entity, Animator, a);
}
const targetLeaf = nextPath ? leafStateOf(def, target) : leaf;
- // Apply the active leaf's motion every frame: a 1D-blend leaf's selected
- // clip can change as its parameter crosses a threshold without any state
- // change. A single-clip leaf in steady state is a no-op (cheap).
- if (targetLeaf) this.applyMotion(world, entity, targetLeaf, params, stateChanged);
+ 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 (motion) ctx.drive(motion, stateChanged);
}
}
-
- /**
- * Drive the entity's SpriteAnimator from a leaf state's motion (single clip or
- * 1D-blend selection). Writes only when the desired clip differs or the state
- * just changed — restarting from frame 0 on a switch.
- */
- private applyMotion(
- world: World, entity: Entity, st: AnimatorState,
- params: AnimatorParamValues, forceRestart: boolean,
- ): void {
- // Spine state: set the skeletal animation on entry (SpineManager owns the
- // track playback/mixing); don't re-set every frame or touch SpriteAnimator.
- if (st.spine) {
- if (forceRestart && this.spineDriver_) {
- this.spineDriver_.setAnimation(entity, st.spine.animation, st.spine.loop ?? true);
- }
- return;
- }
-
- if (!world.has(entity, SpriteAnimator)) return;
- const sel = this.motionClipOf(st, params);
- const sp = world.get(entity, SpriteAnimator) as SpriteAnimatorData;
- if (sp.clip === sel.clip && !forceRestart) return;
-
- sp.clip = sel.clip;
- sp.speed = sel.speed ?? st.speed ?? 1.0;
- sp.loop = sel.loop ?? st.loop ?? true;
- sp.currentFrame = 0;
- sp.frameTimer = 0;
- sp.playing = true;
- sp.finished = false;
- sp.enabled = true;
- world.insert(entity, SpriteAnimator, sp);
- }
-
- /** The clip (and its speed/loop) a state would play for the given params:
- * the single clip, or the 1D-blend selection. */
- private motionClipOf(st: AnimatorState, params: AnimatorParamValues): AnimatorBlendThreshold {
- return st.blend
- ? selectBlendClip(st.blend, Number(params[st.blend.parameter] ?? 0))
- : { value: 0, clip: st.clip ?? '', speed: st.speed, loop: st.loop };
- }
}
const EMPTY_PARAMS: ReadonlyMap<string, number | boolean> = new Map();
diff --git a/sdk/src/animation/animatorGraph.ts b/sdk/src/animation/animatorGraph.ts
index 01d96524f..15d2f9269 100644
--- a/sdk/src/animation/animatorGraph.ts
+++ b/sdk/src/animation/animatorGraph.ts
@@ -21,6 +21,7 @@ import type {
AnimatorParam,
AnimatorParamType,
} from './Animator';
+import type { AnimatorMotion } from './motion';
import {
type GraphSpec, type GraphEdge,
graphEdges, addGraphState, removeGraphState, moveGraphState, renameGraphState,
@@ -80,15 +81,39 @@ export function setInitial(def: AnimatorControllerDef, name: string): AnimatorCo
return setGraphInitial(spec, def, name);
}
-/** Set the state's motion to a single sprite clip (clears blend/spine/nested). */
+/**
+ * What a state plays, of any kind. Rebuilt rather than merged: a state names ONE
+ * motion, so the fields spelling every other way of naming one have to go, or a
+ * state would carry two and the reader would have to rank them.
+ */
+function withMotion(s: AnimatorState, motion: Partial<AnimatorState>): AnimatorState {
+ return {
+ name: s.name, x: s.x, y: s.y,
+ transitions: s.transitions, speed: s.speed, loop: s.loop,
+ ...motion,
+ };
+}
+
+/** Set the state's motion to a single sprite clip (clears any other motion). */
export function setStateClip(def: AnimatorControllerDef, name: string, clip: string): AnimatorControllerDef {
return {
...def,
states: def.states.map((s) =>
- s.name === name
- ? { name: s.name, x: s.x, y: s.y, transitions: s.transitions, speed: s.speed, loop: s.loop, ...(clip ? { clip } : {}) }
- : s,
- ),
+ s.name === name ? withMotion(s, clip ? { clip } : {}) : s),
+ };
+}
+
+/**
+ * Point the state at a motion of any registered kind — a timeline, a blend over
+ * either. Null clears it, leaving a state that plays nothing.
+ */
+export function setStateMotion(
+ def: AnimatorControllerDef, name: string, motion: AnimatorMotion | null,
+): AnimatorControllerDef {
+ return {
+ ...def,
+ states: def.states.map((s) =>
+ s.name === name ? withMotion(s, motion ? { motion } : {}) : s),
};
}
diff --git a/sdk/src/animation/index.ts b/sdk/src/animation/index.ts
index 08f2c17e6..a4869aec4 100644
--- a/sdk/src/animation/index.ts
+++ b/sdk/src/animation/index.ts
@@ -53,7 +53,9 @@ export {
leafStateOf,
resolveParams,
selectBlendClip,
+ motionOf,
STATE_PATH_SEP,
+ SPINE_MOTION,
type AnimatorData,
type AnimatorBlend1D,
type AnimatorBlendThreshold,
@@ -81,6 +83,7 @@ export {
renameState as renameAnimatorState,
setInitial as setAnimatorInitial,
setStateClip as setAnimatorStateClip,
+ setStateMotion as setAnimatorStateMotion,
setStateProps as setAnimatorStateProps,
addTransition as addAnimatorTransition,
removeTransition as removeAnimatorTransition,
@@ -130,3 +133,22 @@ export {
type AnimClipVec2,
type AnimClipSizing,
} from './AnimClipLoader';
+
+export {
+ MotionRegistry,
+ selectBlendStop,
+ blend1DMotionDriver,
+ isBlend1D,
+ type AnimatorMotion,
+ type AnimatorClipMotion,
+ type AnimatorBlend1DMotion,
+ type AnimatorBlendStop,
+ type MotionContext,
+ type MotionDriver,
+ type MotionParams,
+} from './motion';
+
+export {
+ SPRITE_MOTION,
+ spriteMotionDriver,
+} from './spriteMotion';
diff --git a/sdk/src/animation/motion.ts b/sdk/src/animation/motion.ts
new file mode 100644
index 000000000..3149b526b
--- /dev/null
+++ b/sdk/src/animation/motion.ts
@@ -0,0 +1,186 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file motion.ts
+ * @brief What an animator state plays, and the seam that knows how to play it.
+ *
+ * @details The state machine owns states, time and transitions; a MOTION owns
+ * "this stretch of animation, sampled onto this entity". Keeping the two
+ * apart is what lets one graph drive a sprite sheet on one entity and a
+ * skeletal `.estimeline` on another without the graph naming either —
+ * the alternative grows a branch per animation technology in the three
+ * places the animator touches a motion (enter, per-frame, has-it-ended).
+ *
+ * A motion is DATA (`kind` + its own fields); a {@link MotionDriver} is
+ * the code for one kind, registered per App. So a new kind of animation
+ * is a registration, and this file never learns about it. Drivers for
+ * kinds the engine ships in a separate module (timeline, spine) are
+ * registered by THAT module's plugin, which is also what keeps the
+ * animation core from importing it.
+ */
+
+import type { Entity } from '../types';
+import type { World } from '../ecs/world';
+
+/** Parameter values a graph exposes to its motions (floats and bools). */
+export type MotionParams = Readonly<Record<string, number | boolean>>;
+
+/** A single authored clip, played by whichever driver owns `kind`. */
+export interface AnimatorClipMotion {
+ /** Which driver plays this. `sprite` and `timeline` ship with the engine. */
+ kind: string;
+ /** What to play: a registered clip name, or an asset ref the driver resolves. */
+ clip: string;
+ speed?: number;
+ loop?: boolean;
+}
+
+/** One stop on a 1D blend: at or above `value`, play `motion`. */
+export interface AnimatorBlendStop {
+ value: number;
+ motion: AnimatorMotion;
+}
+
+/**
+ * Parameter-driven selection among motions. A blend is itself a motion, so a stop
+ * may hold another blend or any other kind — the nesting is what makes a
+ * locomotion tree expressible without the graph gaining a second vocabulary.
+ */
+export interface AnimatorBlend1DMotion {
+ kind: 'blend1d';
+ /** Float parameter that drives the selection. */
+ parameter: string;
+ thresholds: AnimatorBlendStop[];
+}
+
+export type AnimatorMotion = AnimatorClipMotion | AnimatorBlend1DMotion;
+
+export function isBlend1D(m: AnimatorMotion): m is AnimatorBlend1DMotion {
+ return m.kind === 'blend1d';
+}
+
+// =============================================================================
+// Driver seam
+// =============================================================================
+
+/**
+ * What a driver is given to act on. `drive`/`finished` re-enter the registry, so
+ * a composite motion (a blend) delegates to its chosen child without holding the
+ * registry itself — and therefore without caring what kind that child is.
+ */
+export interface MotionContext {
+ world: World;
+ entity: Entity;
+ params: MotionParams;
+ /** Play a nested motion. `enter` restarts it from the top. */
+ drive(motion: AnimatorMotion, enter: boolean): void;
+ /** Whether a nested motion has run to its end. */
+ finished(motion: AnimatorMotion): boolean;
+}
+
+export interface MotionDriver<M extends AnimatorMotion = AnimatorMotion> {
+ /**
+ * Drive `motion` on the context's entity. Called every frame the state is
+ * active, so a driver must be idempotent in steady state; `enter` is true
+ * only on the frame the state was entered, and means restart from the top.
+ */
+ apply(ctx: MotionContext, motion: M, enter: boolean): void;
+ /**
+ * Whether the motion has run to its end — what gates a `hasExitTime`
+ * transition. A looping motion never finishes. A driver that cannot tell
+ * answers false: an exit-time transition that never fires is visible in the
+ * graph's behaviour, whereas one that fires early looks like a timing bug.
+ */
+ isFinished(ctx: MotionContext, motion: M): boolean;
+}
+
+/**
+ * The drivers one App knows. Per App and not global because a driver reaches
+ * live per-App state (the timeline's player flags, spine's manager), which a
+ * second App in the same process must not share.
+ */
+export class MotionRegistry {
+ private readonly drivers_ = new Map<string, MotionDriver<never>>();
+
+ register<M extends AnimatorMotion>(kind: M['kind'], driver: MotionDriver<M>): void {
+ this.drivers_.set(kind, driver as MotionDriver<never>);
+ }
+
+ unregister(kind: string): void {
+ this.drivers_.delete(kind);
+ }
+
+ has(kind: string): boolean {
+ return this.drivers_.has(kind);
+ }
+
+ driverFor(motion: AnimatorMotion): MotionDriver | undefined {
+ return this.drivers_.get(motion.kind) as MotionDriver | undefined;
+ }
+
+ /**
+ * The context for driving `entity` this tick, REUSED across entities: the
+ * alternative is an object and three closures per animated entity per frame.
+ * A driver must not keep it — it describes only the call it was handed to.
+ */
+ context(world: World, entity: Entity, params: MotionParams): MotionContext {
+ const ctx = this.ctx_;
+ ctx.world = world;
+ ctx.entity = entity;
+ ctx.params = params;
+ return ctx;
+ }
+
+ private readonly ctx_: MotionContext = {
+ world: null!,
+ entity: 0 as Entity,
+ params: {},
+ drive: (motion, enter) => { this.driverFor(motion)?.apply(this.ctx_, motion, enter); },
+ finished: (motion) => this.driverFor(motion)?.isFinished(this.ctx_, motion) ?? false,
+ };
+}
+
+// =============================================================================
+// 1D blend — a motion in its own right, so it composes with every other kind
+// =============================================================================
+
+/**
+ * The stop a 1D blend selects for `value`: the greatest threshold at or below it,
+ * clamped up to the first when the parameter sits under them all. Pure.
+ */
+export function selectBlendStop(
+ blend: AnimatorBlend1DMotion, value: number,
+): AnimatorBlendStop | null {
+ let atOrBelow: AnimatorBlendStop | null = null;
+ let lowest: AnimatorBlendStop | null = null;
+ for (const stop of blend.thresholds) {
+ if (lowest === null || stop.value < lowest.value) lowest = stop;
+ if (stop.value <= value && (atOrBelow === null || stop.value > atOrBelow.value)) {
+ atOrBelow = stop;
+ }
+ }
+ return atOrBelow ?? lowest;
+}
+
+/** The motion a blend is currently selecting, or null when it has no stops. */
+function blendSelection(
+ ctx: MotionContext, blend: AnimatorBlend1DMotion,
+): AnimatorMotion | null {
+ return selectBlendStop(blend, Number(ctx.params[blend.parameter] ?? 0))?.motion ?? null;
+}
+
+/**
+ * Selection, not weighted mixing: a 1D blend picks the stop its parameter names
+ * and plays it whole. Crossfading between neighbouring stops is the pose mixer's
+ * to add, and lands here without the graph or any other driver changing.
+ */
+export const blend1DMotionDriver: MotionDriver<AnimatorBlend1DMotion> = {
+ apply(ctx, blend, enter) {
+ const selected = blendSelection(ctx, blend);
+ if (selected) ctx.drive(selected, enter);
+ },
+ isFinished(ctx, blend) {
+ const selected = blendSelection(ctx, blend);
+ return selected ? ctx.finished(selected) : false;
+ },
+};
diff --git a/sdk/src/animation/spriteMotion.ts b/sdk/src/animation/spriteMotion.ts
new file mode 100644
index 000000000..3db631906
--- /dev/null
+++ b/sdk/src/animation/spriteMotion.ts
@@ -0,0 +1,44 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file spriteMotion.ts
+ * @brief The `sprite` motion kind: an animator state driving a sprite clip.
+ *
+ * @details Playback itself stays SpriteAnimationAPI's — this only points the
+ * entity's SpriteAnimator at a clip and reads back whether it ended, so
+ * there is still exactly one thing advancing sprite frames.
+ */
+
+import type { MotionDriver, AnimatorClipMotion } from './motion';
+import { SpriteAnimator, type SpriteAnimatorData } from './SpriteAnimator';
+
+export const SPRITE_MOTION = 'sprite';
+
+export const spriteMotionDriver: MotionDriver<AnimatorClipMotion> = {
+ apply({ world, entity }, motion, enter) {
+ if (!world.has(entity, SpriteAnimator)) return;
+ const current = world.get(entity, SpriteAnimator) as SpriteAnimatorData;
+ // Steady state is a no-op: rewriting the clip every frame would hold it
+ // on frame 0 forever.
+ if (current.clip === motion.clip && !enter) return;
+
+ world.update(entity, SpriteAnimator, (sp: SpriteAnimatorData) => {
+ sp.clip = motion.clip;
+ sp.speed = motion.speed ?? 1.0;
+ sp.loop = motion.loop ?? true;
+ sp.currentFrame = 0;
+ sp.frameTimer = 0;
+ sp.playing = true;
+ sp.finished = false;
+ sp.enabled = true;
+ });
+ },
+
+ isFinished({ world, entity }, motion) {
+ if (!world.has(entity, SpriteAnimator)) return false;
+ const sp = world.get(entity, SpriteAnimator) as SpriteAnimatorData;
+ // Playing THIS clip and stopped — not merely stopped, which is also true
+ // on the frame before the clip has been applied at all.
+ return sp.clip === motion.clip && sp.clip !== '' && !sp.playing;
+ },
+};
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 25f719c03..39ac61b0c 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -359,6 +359,19 @@ export {
evaluateAnimatorTransitions,
resolveParams,
selectBlendClip,
+ motionOf,
+ selectBlendStop,
+ MotionRegistry,
+ blend1DMotionDriver,
+ spriteMotionDriver,
+ SPRITE_MOTION,
+ SPINE_MOTION,
+ type AnimatorMotion,
+ type AnimatorClipMotion,
+ type AnimatorBlend1DMotion,
+ type AnimatorBlendStop,
+ type MotionContext,
+ type MotionDriver,
type AnimatorData,
type AnimatorBlend1D,
type AnimatorBlendThreshold,
@@ -387,6 +400,7 @@ export {
renameAnimatorState,
setAnimatorInitial,
setAnimatorStateClip,
+ setAnimatorStateMotion,
setAnimatorStateProps,
addAnimatorTransition,
removeAnimatorTransition,
@@ -855,6 +869,8 @@ export {
Timeline,
TimelineAPI,
TimelinePlayer,
+ TIMELINE_MOTION,
+ createTimelineMotionDriver,
type TimelinePlayerData,
} from './timeline';
// Authoring + pure-TS evaluation surface for the editor Sequencer.
diff --git a/sdk/src/timeline/TimelinePlayerComponent.ts b/sdk/src/timeline/TimelinePlayerComponent.ts
new file mode 100644
index 000000000..e8d531166
--- /dev/null
+++ b/sdk/src/timeline/TimelinePlayerComponent.ts
@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file TimelinePlayerComponent.ts
+ * @brief What plays a timeline on an entity: the component, and the one rule
+ * for reading its wrap mode.
+ *
+ * @details Separate from the plugin that advances it because it is DATA — the
+ * plugin, the animator's timeline motion, and the AI conditions all
+ * read this shape, and a component living inside the system that ticks
+ * it makes every other reader depend on that system.
+ */
+
+import { defineComponent } from '../ecs/component';
+import { wrapModeFromName, isWrapModeName, type WrapMode } from './TimelineTypes';
+
+export interface TimelinePlayerData {
+ timeline: string;
+ playing: boolean;
+ speed: number;
+ /** Overrides the wrap mode the CLIP declares; empty means the clip's own. */
+ wrapMode: string;
+ /**
+ * Latched true when a Once clip completes; cleared when `playing` is raised
+ * again (which replays from the top). Runtime-observable — don't author it.
+ */
+ finished: boolean;
+}
+
+/**
+ * Which wrap mode a playing clip runs under: the CLIP's, unless the player names
+ * one to override it with. A string that is not a wrap mode name is a typo, not
+ * a choice, and leaves the clip's own mode standing.
+ */
+export function resolveWrapMode(playerWrapMode: string, assetWrapMode: WrapMode): WrapMode {
+ return isWrapModeName(playerWrapMode) ? wrapModeFromName(playerWrapMode) : assetWrapMode;
+}
+
+export const TimelinePlayer = defineComponent<TimelinePlayerData>('TimelinePlayer', {
+ timeline: '',
+ playing: false,
+ speed: 1.0,
+ wrapMode: '',
+ finished: false,
+}, {
+ assetFields: [{ field: 'timeline', type: 'timeline' }],
+ fields: {
+ wrapMode: { tooltip: "Override the clip's own wrap mode: once, loop or pingPong. Empty uses what the clip declares." },
+ finished: { advanced: true, tooltip: 'Clip completed (runtime, read-only). Raise Playing to replay.' },
+ },
+});
diff --git a/sdk/src/timeline/TimelinePlugin.ts b/sdk/src/timeline/TimelinePlugin.ts
index ae51c14cc..38aa17234 100644
--- a/sdk/src/timeline/TimelinePlugin.ts
+++ b/sdk/src/timeline/TimelinePlugin.ts
@@ -4,55 +4,23 @@ import type { App, Plugin } from '../app/app';
import { defineSystem, Schedule } from '../ecs/system';
import { Res } from '../ecs/resource';
import { Time, type TimeData } from '../ecs/resource';
-import { defineComponent, getComponent } from '../ecs/component';
+import { getComponent } from '../ecs/component';
import { playModeOnly } from '../ecs/env';
import { Assets } from '../asset/AssetPlugin';
import { Audio, type AudioAPI } from '../audio/Audio';
-import { wrapModeFromName, isWrapModeName, TrackType, WrapMode, type TimelineAsset,
+import { TrackType, type TimelineAsset,
type AnimFramesTrack, type PublishedTimeline } from './TimelineTypes';
+import { TimelinePlayer, resolveWrapMode, type TimelinePlayerData } from './TimelinePlayerComponent';
import { Timeline, TimelineAPI } from './TimelineControl';
+import { AnimatorController } from '../animation/Animator';
+import { TIMELINE_MOTION, createTimelineMotionDriver } from './timelineMotion';
import { resolveChildEntity } from './TimelineRuntime';
import { advanceTimelineTS, applyPlayerFlags, latchPlayerFinish } from './TimelineDrive';
import type { SampleDeps } from './TimelineEvaluator';
import type { Entity } from '../types';
export { setNestedProperty } from './TimelineRuntime';
-
-export interface TimelinePlayerData {
- timeline: string;
- playing: boolean;
- speed: number;
- /** Overrides the wrap mode the CLIP declares; empty means the clip's own. */
- wrapMode: string;
- /**
- * Latched true when a Once clip completes; cleared when `playing` is raised
- * again (which replays from the top). Runtime-observable — don't author it.
- */
- finished: boolean;
-}
-
-/**
- * Which wrap mode a playing clip runs under: the CLIP's, unless the player names
- * one to override it with. A string that is not a wrap mode name is a typo, not
- * a choice, and leaves the clip's own mode standing.
- */
-export function resolveWrapMode(playerWrapMode: string, assetWrapMode: WrapMode): WrapMode {
- return isWrapModeName(playerWrapMode) ? wrapModeFromName(playerWrapMode) : assetWrapMode;
-}
-
-export const TimelinePlayer = defineComponent<TimelinePlayerData>('TimelinePlayer', {
- timeline: '',
- playing: false,
- speed: 1.0,
- wrapMode: '',
- finished: false,
-}, {
- assetFields: [{ field: 'timeline', type: 'timeline' }],
- fields: {
- wrapMode: { tooltip: "Override the clip's own wrap mode: once, loop or pingPong. Empty uses what the clip declares." },
- finished: { advanced: true, tooltip: 'Clip completed (runtime, read-only). Raise Playing to replay.' },
- },
-});
+export { TimelinePlayer, resolveWrapMode, type TimelinePlayerData } from './TimelinePlayerComponent';
interface AnimFramesState {
tracks: AnimFramesTrack[];
@@ -90,6 +58,15 @@ export class TimelinePlugin implements Plugin {
: undefined),
);
+ // Let an animator state play a timeline. Guarded rather than assumed:
+ // the animation plugin is registered before this one in every plugin set,
+ // and a build without it still plays timelines through TimelinePlayer.
+ if (app.hasResource(AnimatorController)) {
+ app.getResource(AnimatorController).registerMotionDriver(
+ TIMELINE_MOTION, createTimelineMotionDriver(app.getResource(Timeline)),
+ );
+ }
+
this.offDespawn_ = world.onDespawn((entity: Entity) => {
app.getResource(Timeline).removeState(entity);
this.animFramesStates_.delete(entity);
diff --git a/sdk/src/timeline/index.ts b/sdk/src/timeline/index.ts
index f8ef88cc7..69017c208 100644
--- a/sdk/src/timeline/index.ts
+++ b/sdk/src/timeline/index.ts
@@ -78,7 +78,16 @@ export {
export {
TimelinePlugin,
timelinePlugin,
+} from './TimelinePlugin';
+
+export {
TimelinePlayer,
+ resolveWrapMode,
type TimelinePlayerData,
-} from './TimelinePlugin';
+} from './TimelinePlayerComponent';
+
+export {
+ TIMELINE_MOTION,
+ createTimelineMotionDriver,
+} from './timelineMotion';
diff --git a/sdk/src/timeline/timelineMotion.ts b/sdk/src/timeline/timelineMotion.ts
new file mode 100644
index 000000000..a843d682a
--- /dev/null
+++ b/sdk/src/timeline/timelineMotion.ts
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file timelineMotion.ts
+ * @brief The `timeline` motion kind: an animator state driving an `.estimeline`.
+ *
+ * @details This is what lets one animator graph animate a skinned model. A
+ * skeletal clip IS a timeline — property tracks writing each joint
+ * entity's Transform — so the driver only points the entity's
+ * TimelinePlayer at a clip and reads back whether it ended. Sampling,
+ * and therefore the single path from joint Transform to MeshSkin, stays
+ * TimelinePlugin's: the animator adds no second owner of a bone pose.
+ */
+
+import type { MotionDriver, AnimatorClipMotion, MotionContext } from '../animation/motion';
+import { TimelinePlayer, type TimelinePlayerData } from './TimelinePlayerComponent';
+import type { TimelineAPI } from './TimelineControl';
+
+export const TIMELINE_MOTION = 'timeline';
+
+/** Which wrap mode a motion asks for; empty leaves the clip's own standing. */
+function wrapModeFor(loop: boolean | undefined): string {
+ return loop === undefined ? '' : loop ? 'loop' : 'once';
+}
+
+/**
+ * The driver, over the app's own {@link TimelineAPI} — the clock a clip runs on
+ * is per App, so this is built per App rather than being a module-level value.
+ */
+export function createTimelineMotionDriver(timeline: TimelineAPI): MotionDriver<AnimatorClipMotion> {
+ return {
+ apply({ world, entity }: MotionContext, motion, enter) {
+ if (!world.has(entity, TimelinePlayer)) return;
+ const current = world.get(entity, TimelinePlayer) as TimelinePlayerData;
+ if (current.timeline === motion.clip && !enter) return;
+
+ world.update(entity, TimelinePlayer, (p: TimelinePlayerData) => {
+ p.timeline = motion.clip;
+ p.speed = motion.speed ?? 1.0;
+ p.wrapMode = wrapModeFor(motion.loop);
+ p.playing = true;
+ p.finished = false;
+ });
+ // The clock lives beside the component, not in it, and a clip that
+ // replaces another must start at its own beginning rather than
+ // wherever the previous one had got to.
+ const state = timeline.getState(entity);
+ if (state) {
+ state.time = 0;
+ state.prevTime = 0;
+ state.spineClipIndices = {};
+ }
+ },
+
+ isFinished({ world, entity }: MotionContext, motion) {
+ if (!world.has(entity, TimelinePlayer)) return false;
+ const p = world.get(entity, TimelinePlayer) as TimelinePlayerData;
+ // Playing THIS clip and latched finished. A looping clip never
+ // latches, so an exit-time transition out of one never fires — which
+ // is what it means for the clip to have no end.
+ return p.timeline === motion.clip && p.finished;
+ },
+ };
+}
diff --git a/sdk/tests/animator.test.ts b/sdk/tests/animator.test.ts
index e51fbd435..aa275a7d1 100644
--- a/sdk/tests/animator.test.ts
+++ b/sdk/tests/animator.test.ts
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
-import { describe, it, expect, beforeEach } from 'vitest';
+import { describe, it, expect, beforeEach, vi } from 'vitest';
import {
Animator,
AnimatorControllerAPI,
@@ -171,6 +171,12 @@ function makeWorld() {
return {
insert(e: number, c: unknown, data: unknown) { mapOf(c).set(e, data); },
get(e: number, c: unknown) { return mapOf(c).get(e); },
+ update(e: number, c: unknown, edit: (draft: any) => void) {
+ const draft = mapOf(c).get(e);
+ if (draft === undefined) throw new Error('update: entity does not carry it');
+ edit(draft);
+ mapOf(c).set(e, draft);
+ },
has(e: number, c: unknown) { return mapOf(c).has(e); },
getEntitiesWithComponents(comps: unknown[]) {
const [first, ...rest] = comps;
diff --git a/sdk/tests/animatorMotion.test.ts b/sdk/tests/animatorMotion.test.ts
new file mode 100644
index 000000000..4d26245ff
--- /dev/null
+++ b/sdk/tests/animatorMotion.test.ts
@@ -0,0 +1,302 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * The claim: one graph drives a sprite sheet on one entity and an `.estimeline`
+ * on another, the motion each state names being the only difference.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ Animator, AnimatorControllerAPI, SpriteAnimator, motionOf,
+ type AnimatorData, type AnimatorControllerDef, type AnimatorMotion,
+ type AnimatorState, type SpriteAnimatorData,
+} from '../src/animation';
+import { TimelinePlayer, createTimelineMotionDriver, TIMELINE_MOTION,
+ type TimelinePlayerData } from '../src/timeline';
+import { TimelineAPI } from '../src/timeline/TimelineControl';
+
+const E = 1;
+
+function makeWorld() {
+ const store = new Map<unknown, Map<number, unknown>>();
+ const mapOf = (c: unknown) => {
+ let m = store.get(c);
+ if (!m) { m = new Map(); store.set(c, m); }
+ return m;
+ };
+ return {
+ insert(e: number, c: unknown, data: unknown) { mapOf(c).set(e, data); },
+ get(e: number, c: unknown) { return mapOf(c).get(e); },
+ has(e: number, c: unknown) { return mapOf(c).has(e); },
+ update(e: number, c: unknown, edit: (draft: any) => void) {
+ const draft = mapOf(c).get(e);
+ if (draft === undefined) throw new Error('update: entity does not carry it');
+ edit(draft);
+ mapOf(c).set(e, draft);
+ },
+ getEntitiesWithComponents(comps: unknown[]) {
+ const [first, ...rest] = comps;
+ return [...mapOf(first).keys()].filter((e) => rest.every((c) => mapOf(c).has(e)));
+ },
+ } as any;
+}
+
+const spriteData = (): SpriteAnimatorData => ({
+ clip: '', currentFrame: 0, frameTimer: 0, speed: 1,
+ loop: true, playing: false, finished: false, enabled: true,
+} as SpriteAnimatorData);
+
+const timelineData = (): TimelinePlayerData => ({
+ timeline: '', playing: false, speed: 1, wrapMode: '', finished: false,
+});
+
+/**
+ * ONE graph, built over whatever motion the caller names for a state. The state
+ * machine below is written once; both runs in this file use it verbatim, so a
+ * behavioural difference between them can only come from the motions.
+ */
+function locomotionGraph(motionFor: (state: string) => AnimatorMotion): AnimatorControllerDef {
+ return {
+ parameters: [{ name: 'speed', type: 'float', default: 0 }],
+ initialState: 'Idle',
+ states: [
+ {
+ name: 'Idle',
+ motion: motionFor('idle'),
+ transitions: [{ to: 'Run', conditions: [{ param: 'speed', op: 'gt', value: 0 }] }],
+ },
+ {
+ name: 'Run',
+ motion: motionFor('run'),
+ transitions: [{ to: 'Idle', conditions: [{ param: 'speed', op: 'lt', value: 0.1 }] }],
+ },
+ ],
+ };
+}
+
+const spriteMotionFor = (name: string): AnimatorMotion => ({ kind: 'sprite', clip: name });
+const timelineMotionFor = (name: string): AnimatorMotion =>
+ ({ kind: TIMELINE_MOTION, clip: `${name}.estimeline` });
+
+/** A controller that can play timelines, as the plugins wire it at runtime. */
+function makeController(): AnimatorControllerAPI {
+ const ctrl = new AnimatorControllerAPI();
+ ctrl.registerMotionDriver(TIMELINE_MOTION, createTimelineMotionDriver(new TimelineAPI()));
+ return ctrl;
+}
+
+function seed(world: any, controller: string): void {
+ world.insert(E, Animator, { controller, currentState: '', enabled: true } as AnimatorData);
+}
+
+describe('one graph, either kind of motion', () => {
+ it('runs the same state machine over sprite clips', () => {
+ const world = makeWorld();
+ const ctrl = makeController();
+ ctrl.registerController('loco', locomotionGraph(spriteMotionFor));
+ seed(world, 'loco');
+ world.insert(E, SpriteAnimator, spriteData());
+
+ ctrl.update(world);
+ expect((world.get(E, Animator) as AnimatorData).currentState).toBe('Idle');
+ expect((world.get(E, SpriteAnimator) as SpriteAnimatorData).clip).toBe('idle');
+
+ ctrl.setFloat(E, 'speed', 5);
+ ctrl.update(world);
+ expect((world.get(E, Animator) as AnimatorData).currentState).toBe('Run');
+ expect((world.get(E, SpriteAnimator) as SpriteAnimatorData).clip).toBe('run');
+ });
+
+ it('runs that same state machine over timelines', () => {
+ const world = makeWorld();
+ const ctrl = makeController();
+ ctrl.registerController('loco', locomotionGraph(timelineMotionFor));
+ seed(world, 'loco');
+ world.insert(E, TimelinePlayer, timelineData());
+
+ ctrl.update(world);
+ expect((world.get(E, Animator) as AnimatorData).currentState).toBe('Idle');
+ expect((world.get(E, TimelinePlayer) as TimelinePlayerData).timeline)
+ .toBe('idle.estimeline');
+
+ ctrl.setFloat(E, 'speed', 5);
+ ctrl.update(world);
+ expect((world.get(E, Animator) as AnimatorData).currentState).toBe('Run');
+ expect((world.get(E, TimelinePlayer) as TimelinePlayerData).timeline)
+ .toBe('run.estimeline');
+ });
+
+ it('takes the same path through the graph, and drives its motion, either way', () => {
+ const run = (
+ motionFor: (s: string) => AnimatorMotion,
+ component: unknown, initial: () => unknown,
+ targetOf: (data: any) => string,
+ ): { states: string[]; targets: string[] } => {
+ const world = makeWorld();
+ const ctrl = makeController();
+ ctrl.registerController('loco', locomotionGraph(motionFor));
+ seed(world, 'loco');
+ world.insert(E, component, initial());
+
+ const states: string[] = [];
+ const targets: string[] = [];
+ for (const speed of [0, 0, 3, 3, 0]) {
+ ctrl.setFloat(E, 'speed', speed);
+ ctrl.update(world);
+ states.push((world.get(E, Animator) as AnimatorData).currentState);
+ targets.push(targetOf(world.get(E, component)));
+ }
+ return { states, targets };
+ };
+
+ const sprite = run(spriteMotionFor, SpriteAnimator, spriteData,
+ (d: SpriteAnimatorData) => d.clip);
+ const timeline = run(timelineMotionFor, TimelinePlayer, timelineData,
+ (d: TimelinePlayerData) => d.timeline);
+
+ // Same graph, same walk through it.
+ expect(sprite.states).toEqual(['Idle', 'Idle', 'Run', 'Run', 'Idle']);
+ expect(timeline.states).toEqual(sprite.states);
+ // And each kind was actually driven — a graph that walks correctly while
+ // playing nothing would otherwise satisfy the comparison above.
+ expect(sprite.targets).toEqual(['idle', 'idle', 'run', 'run', 'idle']);
+ expect(timeline.targets).toEqual([
+ 'idle.estimeline', 'idle.estimeline',
+ 'run.estimeline', 'run.estimeline', 'idle.estimeline',
+ ]);
+ });
+});
+
+describe('exit time is the motion’s answer, whatever kind it is', () => {
+ const oneShot = (motion: AnimatorMotion): AnimatorControllerDef => ({
+ parameters: [],
+ initialState: 'Attack',
+ states: [
+ { name: 'Attack', motion, transitions: [{ to: 'Idle', conditions: [], hasExitTime: true }] },
+ { name: 'Idle', motion, transitions: [] },
+ ],
+ });
+
+ it('waits for a sprite clip to stop', () => {
+ const world = makeWorld();
+ const ctrl = makeController();
+ ctrl.registerController('atk', oneShot({ kind: 'sprite', clip: 'attack', loop: false }));
+ seed(world, 'atk');
+ world.insert(E, SpriteAnimator, spriteData());
+
+ ctrl.update(world);
+ expect((world.get(E, Animator) as AnimatorData).currentState).toBe('Attack');
+
+ // Still playing: the exit-time transition must not fire.
+ ctrl.update(world);
+ expect((world.get(E, Animator) as AnimatorData).currentState).toBe('Attack');
+
+ world.update(E, SpriteAnimator, (sp: SpriteAnimatorData) => { sp.playing = false; });
+ ctrl.update(world);
+ expect((world.get(E, Animator) as AnimatorData).currentState).toBe('Idle');
+ });
+
+ it('waits for a timeline to latch finished', () => {
+ const world = makeWorld();
+ const ctrl = makeController();
+ ctrl.registerController('atk', oneShot({ kind: TIMELINE_MOTION, clip: 'attack.estimeline', loop: false }));
+ seed(world, 'atk');
+ world.insert(E, TimelinePlayer, timelineData());
+
+ ctrl.update(world);
+ expect((world.get(E, Animator) as AnimatorData).currentState).toBe('Attack');
+
+ ctrl.update(world);
+ expect((world.get(E, Animator) as AnimatorData).currentState).toBe('Attack');
+
+ world.update(E, TimelinePlayer, (p: TimelinePlayerData) => { p.finished = true; });
+ ctrl.update(world);
+ expect((world.get(E, Animator) as AnimatorData).currentState).toBe('Idle');
+ });
+});
+
+describe('a blend is a motion, so it composes with any kind', () => {
+ it('selects among timeline motions by a parameter', () => {
+ const world = makeWorld();
+ const ctrl = makeController();
+ ctrl.registerController('loco', {
+ parameters: [{ name: 'speed', type: 'float', default: 0 }],
+ initialState: 'Move',
+ states: [{
+ name: 'Move',
+ motion: {
+ kind: 'blend1d',
+ parameter: 'speed',
+ thresholds: [
+ { value: 0, motion: { kind: TIMELINE_MOTION, clip: 'walk.estimeline' } },
+ { value: 5, motion: { kind: TIMELINE_MOTION, clip: 'run.estimeline' } },
+ ],
+ },
+ transitions: [],
+ }],
+ });
+ seed(world, 'loco');
+ world.insert(E, TimelinePlayer, timelineData());
+
+ ctrl.update(world);
+ expect((world.get(E, TimelinePlayer) as TimelinePlayerData).timeline).toBe('walk.estimeline');
+
+ // Crossing a threshold re-aims the motion without any state change.
+ ctrl.setFloat(E, 'speed', 7);
+ ctrl.update(world);
+ expect((world.get(E, TimelinePlayer) as TimelinePlayerData).timeline).toBe('run.estimeline');
+ expect((world.get(E, Animator) as AnimatorData).currentState).toBe('Move');
+ });
+});
+
+describe('graphs authored before motions existed', () => {
+ it('reads a sprite clip field as a sprite motion', () => {
+ const st: AnimatorState = { name: 'Idle', clip: 'idle', speed: 2, loop: false, transitions: [] };
+ expect(motionOf(st)).toEqual({ kind: 'sprite', clip: 'idle', speed: 2, loop: false });
+ });
+
+ it('reads a spine field as a spine motion', () => {
+ const st: AnimatorState = { name: 'Run', spine: { animation: 'run', loop: true }, transitions: [] };
+ expect(motionOf(st)).toEqual({ kind: 'spine', clip: 'run', loop: true });
+ });
+
+ it('reads a legacy blend as a blend over sprite motions, keeping stop overrides', () => {
+ const st: AnimatorState = {
+ name: 'Move', speed: 3, loop: true,
+ blend: {
+ parameter: 'speed',
+ thresholds: [
+ { value: 0, clip: 'walk' },
+ { value: 5, clip: 'run', speed: 9, loop: false },
+ ],
+ },
+ transitions: [],
+ };
+ expect(motionOf(st)).toEqual({
+ kind: 'blend1d',
+ parameter: 'speed',
+ thresholds: [
+ { value: 0, motion: { kind: 'sprite', clip: 'walk', speed: 3, loop: true } },
+ { value: 5, motion: { kind: 'sprite', clip: 'run', speed: 9, loop: false } },
+ ],
+ });
+ });
+
+ it('has no motion for a container state', () => {
+ expect(motionOf({ name: 'Combat', stateMachine: { states: [], initialState: '' }, transitions: [] }))
+ .toBeNull();
+ });
+});
+
+describe('a kind this build cannot play', () => {
+ it('is inert rather than an error', () => {
+ const world = makeWorld();
+ const ctrl = new AnimatorControllerAPI(); // no timeline driver registered
+ ctrl.registerController('loco', locomotionGraph(timelineMotionFor));
+ seed(world, 'loco');
+ world.insert(E, TimelinePlayer, timelineData());
+
+ expect(() => ctrl.update(world)).not.toThrow();
+ expect((world.get(E, TimelinePlayer) as TimelinePlayerData).timeline).toBe('');
+ expect(ctrl.hasMotionDriver(TIMELINE_MOTION)).toBe(false);
+ });
+});