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 motion states a pose, and the mixer decides what the entity becomes

esengineab02006b3762
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index cdbe6cbb1..d277552f3 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -455,7 +455,7 @@ setFloat: (entity: Entity, name: string, value: number) => void
setSpineDriver: (driver: SpineAnimationDriver | null) => void
setTrigger: (entity: Entity, name: string) => void
unregisterController: (name: string) => void
-update: (world: World) => void
+update: (world: World, dt?: number) => void
static new (): AnimatorControllerAPI
static prototype: AnimatorControllerAPI
```
@@ -515,6 +515,7 @@ Readonly<Record<string, number | boolean>>
## AnimatorPathEvalResult — interface @experimental
```
consumedTriggers: string[]
+fadeDuration: number
nextPath: string | null
```
@@ -554,6 +555,7 @@ states: AnimatorState[]
## AnimatorTransition — interface @experimental
```
conditions: AnimatorCondition[]
+duration: number | undefined
hasExitTime: boolean | undefined
to: string
```
@@ -4837,16 +4839,22 @@ shift: boolean
## MotionContext — interface @experimental
```
drive: (motion: AnimatorMotion, enter: boolean) => void
+duration: (motion: AnimatorMotion) => number
entity: number
finished: (motion: AnimatorMotion) => boolean
+loops: (motion: AnimatorMotion) => boolean
params: Readonly<Record<string, number | boolean>>
+sample: (motion: AnimatorMotion, time: number, pose: Pose) => boolean
world: World
```
## MotionDriver — interface @experimental
```
-apply: (ctx: MotionContext, motion: M, enter: boolean) => void
-isFinished: (ctx: MotionContext, motion: M) => boolean
+apply: ((ctx: MotionContext, motion: M, enter: boolean) => void) | undefined
+duration: ((ctx: MotionContext, motion: M) => number) | undefined
+isFinished: ((ctx: MotionContext, motion: M) => boolean) | undefined
+loops: ((ctx: MotionContext, motion: M) => boolean) | undefined
+sample: ((ctx: MotionContext, motion: M, time: number, pose: Pose) => boolean) | undefined
```
## MotionRegistry — class @experimental
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index b4053ec1f..4da09c4d0 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -455,7 +455,7 @@ setFloat: (entity: Entity, name: string, value: number) => void
setSpineDriver: (driver: SpineAnimationDriver | null) => void
setTrigger: (entity: Entity, name: string) => void
unregisterController: (name: string) => void
-update: (world: World) => void
+update: (world: World, dt?: number) => void
static new (): AnimatorControllerAPI
static prototype: AnimatorControllerAPI
```
@@ -515,6 +515,7 @@ Readonly<Record<string, number | boolean>>
## AnimatorPathEvalResult — interface @experimental
```
consumedTriggers: string[]
+fadeDuration: number
nextPath: string | null
```
@@ -554,6 +555,7 @@ states: AnimatorState[]
## AnimatorTransition — interface @experimental
```
conditions: AnimatorCondition[]
+duration: number | undefined
hasExitTime: boolean | undefined
to: string
```
@@ -4850,16 +4852,22 @@ shift: boolean
## MotionContext — interface @experimental
```
drive: (motion: AnimatorMotion, enter: boolean) => void
+duration: (motion: AnimatorMotion) => number
entity: number
finished: (motion: AnimatorMotion) => boolean
+loops: (motion: AnimatorMotion) => boolean
params: Readonly<Record<string, number | boolean>>
+sample: (motion: AnimatorMotion, time: number, pose: Pose) => boolean
world: World
```
## MotionDriver — interface @experimental
```
-apply: (ctx: MotionContext, motion: M, enter: boolean) => void
-isFinished: (ctx: MotionContext, motion: M) => boolean
+apply: ((ctx: MotionContext, motion: M, enter: boolean) => void) | undefined
+duration: ((ctx: MotionContext, motion: M) => number) | undefined
+isFinished: ((ctx: MotionContext, motion: M) => boolean) | undefined
+loops: ((ctx: MotionContext, motion: M) => boolean) | undefined
+sample: ((ctx: MotionContext, motion: M, time: number, pose: Pose) => boolean) | undefined
```
## MotionRegistry — class @experimental
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 5f58feafa..df027b72b 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -450,7 +450,7 @@ setFloat: (entity: Entity, name: string, value: number) => void
setSpineDriver: (driver: SpineAnimationDriver | null) => void
setTrigger: (entity: Entity, name: string) => void
unregisterController: (name: string) => void
-update: (world: World) => void
+update: (world: World, dt?: number) => void
static new (): AnimatorControllerAPI
static prototype: AnimatorControllerAPI
```
@@ -510,6 +510,7 @@ Readonly<Record<string, number | boolean>>
## AnimatorPathEvalResult — interface @experimental
```
consumedTriggers: string[]
+fadeDuration: number
nextPath: string | null
```
@@ -549,6 +550,7 @@ states: AnimatorState[]
## AnimatorTransition — interface @experimental
```
conditions: AnimatorCondition[]
+duration: number | undefined
hasExitTime: boolean | undefined
to: string
```
@@ -4832,16 +4834,22 @@ shift: boolean
## MotionContext — interface @experimental
```
drive: (motion: AnimatorMotion, enter: boolean) => void
+duration: (motion: AnimatorMotion) => number
entity: number
finished: (motion: AnimatorMotion) => boolean
+loops: (motion: AnimatorMotion) => boolean
params: Readonly<Record<string, number | boolean>>
+sample: (motion: AnimatorMotion, time: number, pose: Pose) => boolean
world: World
```
## MotionDriver — interface @experimental
```
-apply: (ctx: MotionContext, motion: M, enter: boolean) => void
-isFinished: (ctx: MotionContext, motion: M) => boolean
+apply: ((ctx: MotionContext, motion: M, enter: boolean) => void) | undefined
+duration: ((ctx: MotionContext, motion: M) => number) | undefined
+isFinished: ((ctx: MotionContext, motion: M) => boolean) | undefined
+loops: ((ctx: MotionContext, motion: M) => boolean) | undefined
+sample: ((ctx: MotionContext, motion: M, time: number, pose: Pose) => boolean) | undefined
```
## MotionRegistry — class @experimental
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 68e20fac0..d5c70dab4 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -450,7 +450,7 @@ setFloat: (entity: Entity, name: string, value: number) => void
setSpineDriver: (driver: SpineAnimationDriver | null) => void
setTrigger: (entity: Entity, name: string) => void
unregisterController: (name: string) => void
-update: (world: World) => void
+update: (world: World, dt?: number) => void
static new (): AnimatorControllerAPI
static prototype: AnimatorControllerAPI
```
@@ -510,6 +510,7 @@ Readonly<Record<string, number | boolean>>
## AnimatorPathEvalResult — interface @experimental
```
consumedTriggers: string[]
+fadeDuration: number
nextPath: string | null
```
@@ -549,6 +550,7 @@ states: AnimatorState[]
## AnimatorTransition — interface @experimental
```
conditions: AnimatorCondition[]
+duration: number | undefined
hasExitTime: boolean | undefined
to: string
```
@@ -5078,16 +5080,22 @@ shift: boolean
## MotionContext — interface @experimental
```
drive: (motion: AnimatorMotion, enter: boolean) => void
+duration: (motion: AnimatorMotion) => number
entity: number
finished: (motion: AnimatorMotion) => boolean
+loops: (motion: AnimatorMotion) => boolean
params: Readonly<Record<string, number | boolean>>
+sample: (motion: AnimatorMotion, time: number, pose: Pose) => boolean
world: World
```
## MotionDriver — interface @experimental
```
-apply: (ctx: MotionContext, motion: M, enter: boolean) => void
-isFinished: (ctx: MotionContext, motion: M) => boolean
+apply: ((ctx: MotionContext, motion: M, enter: boolean) => void) | undefined
+duration: ((ctx: MotionContext, motion: M) => number) | undefined
+isFinished: ((ctx: MotionContext, motion: M) => boolean) | undefined
+loops: ((ctx: MotionContext, motion: M) => boolean) | undefined
+sample: ((ctx: MotionContext, motion: M, time: number, pose: Pose) => boolean) | undefined
```
## MotionRegistry — class @experimental
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index cc727ead8..b86f3608c 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -450,7 +450,7 @@ setFloat: (entity: Entity, name: string, value: number) => void
setSpineDriver: (driver: SpineAnimationDriver | null) => void
setTrigger: (entity: Entity, name: string) => void
unregisterController: (name: string) => void
-update: (world: World) => void
+update: (world: World, dt?: number) => void
static new (): AnimatorControllerAPI
static prototype: AnimatorControllerAPI
```
@@ -510,6 +510,7 @@ Readonly<Record<string, number | boolean>>
## AnimatorPathEvalResult — interface @experimental
```
consumedTriggers: string[]
+fadeDuration: number
nextPath: string | null
```
@@ -549,6 +550,7 @@ states: AnimatorState[]
## AnimatorTransition — interface @experimental
```
conditions: AnimatorCondition[]
+duration: number | undefined
hasExitTime: boolean | undefined
to: string
```
@@ -4839,16 +4841,22 @@ shift: boolean
## MotionContext — interface @experimental
```
drive: (motion: AnimatorMotion, enter: boolean) => void
+duration: (motion: AnimatorMotion) => number
entity: number
finished: (motion: AnimatorMotion) => boolean
+loops: (motion: AnimatorMotion) => boolean
params: Readonly<Record<string, number | boolean>>
+sample: (motion: AnimatorMotion, time: number, pose: Pose) => boolean
world: World
```
## MotionDriver — interface @experimental
```
-apply: (ctx: MotionContext, motion: M, enter: boolean) => void
-isFinished: (ctx: MotionContext, motion: M) => boolean
+apply: ((ctx: MotionContext, motion: M, enter: boolean) => void) | undefined
+duration: ((ctx: MotionContext, motion: M) => number) | undefined
+isFinished: ((ctx: MotionContext, motion: M) => boolean) | undefined
+loops: ((ctx: MotionContext, motion: M) => boolean) | undefined
+sample: ((ctx: MotionContext, motion: M, time: number, pose: Pose) => boolean) | undefined
```
## MotionRegistry — class @experimental
diff --git a/sdk/src/animation/AnimationPlugin.ts b/sdk/src/animation/AnimationPlugin.ts
index 417825e16..43adc7e96 100644
--- a/sdk/src/animation/AnimationPlugin.ts
+++ b/sdk/src/animation/AnimationPlugin.ts
@@ -67,9 +67,9 @@ export class AnimationPlugin implements Plugin {
// The state machine runs before the sprite animator so a transition's
// clip switch applies the same frame it fires.
app.addSystemToSchedule(Schedule.Update, defineSystem(
- [Res(AnimatorController)],
- (ctrl: AnimatorControllerAPI) => {
- ctrl.update(world);
+ [Res(Time), Res(AnimatorController)],
+ (time: TimeData, ctrl: AnimatorControllerAPI) => {
+ ctrl.update(world, time.delta);
},
{ name: 'AnimatorSystem' }
), { runAfter: [SystemLabel.Tween], runIf: playModeOnly });
diff --git a/sdk/src/animation/Animator.ts b/sdk/src/animation/Animator.ts
index 5ce7ff678..f9d1c1ee9 100644
--- a/sdk/src/animation/Animator.ts
+++ b/sdk/src/animation/Animator.ts
@@ -27,6 +27,8 @@ import {
type MotionContext, type MotionDriver,
} from './motion';
import { SPRITE_MOTION, spriteMotionDriver } from './spriteMotion';
+import { Pose } from './pose';
+import { mixPoses } from './poseMix';
// =============================================================================
// Controller definition (the graph data)
@@ -55,6 +57,12 @@ export interface AnimatorTransition {
to: string;
/** All conditions must hold (AND). Empty = unconditional. */
conditions: AnimatorCondition[];
+ /**
+ * Seconds to blend from the state being left into the one being entered.
+ * Absent or 0 cuts. Honoured only where both motions can be sampled: a
+ * sprite sheet is switched, having nothing to be halfway between.
+ */
+ duration?: number;
/**
* Only fire once the current state's clip has finished (a non-looping sprite
* clip reached its end). Combined with `conditions`, both must hold. With no
@@ -184,7 +192,7 @@ function firstReady(
params: AnimatorParamValues,
triggers: ReadonlySet<string>,
clipFinished: boolean,
-): { to: string; usedTriggers: string[] } | null {
+): { to: string; usedTriggers: string[]; fadeDuration: number } | null {
for (const t of list) {
if (t.hasExitTime && !clipFinished) continue;
const used: string[] = [];
@@ -193,7 +201,7 @@ function firstReady(
if (!conditionHolds(c, params, triggers)) { ok = false; break; }
if (c.op === 'trigger') used.push(c.param);
}
- if (ok) return { to: t.to, usedTriggers: used };
+ if (ok) return { to: t.to, usedTriggers: used, fadeDuration: t.duration ?? 0 };
}
return null;
}
@@ -266,6 +274,8 @@ export interface AnimatorPathEvalResult {
/** Target path if a transition fired, else null (stay). */
nextPath: string | null;
consumedTriggers: string[];
+ /** Seconds the fired transition blends over; 0 when it cuts. */
+ fadeDuration: number;
}
/**
@@ -285,7 +295,7 @@ export function evaluateAnimatorPath(
): AnimatorPathEvalResult {
const segments = currentPath ? currentPath.split(STATE_PATH_SEP) : [];
const resolved = resolveStatePath(def, segments);
- if (!resolved) return { nextPath: null, consumedTriggers: [] };
+ if (!resolved) return { nextPath: null, consumedTriggers: [], fadeDuration: 0 };
const { scopes, states } = resolved;
const depth = states.length;
@@ -305,10 +315,14 @@ export function evaluateAnimatorPath(
const fired = firstReady(entry.list, params, triggers, clipFinished);
if (fired) {
const next = [...entry.base, ...enterStatePath(entry.scope, fired.to)];
- return { nextPath: next.join(STATE_PATH_SEP), consumedTriggers: fired.usedTriggers };
+ return {
+ nextPath: next.join(STATE_PATH_SEP),
+ consumedTriggers: fired.usedTriggers,
+ fadeDuration: fired.fadeDuration,
+ };
}
}
- return { nextPath: null, consumedTriggers: [] };
+ return { nextPath: null, consumedTriggers: [], fadeDuration: 0 };
}
/** The leaf (motion-bearing) state of a resolved path, or null if unresolvable. */
@@ -476,6 +490,7 @@ 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 readonly runtimes_ = new Map<Entity, AnimatorRuntime>();
private readonly motions_ = new MotionRegistry();
constructor() {
@@ -578,10 +593,11 @@ export class AnimatorControllerAPI {
return this.params.get(entity)?.get(name) === true;
}
- /** Drop an entity's parameter/trigger state (wire to world.onDespawn). */
+ /** Drop an entity's parameter/trigger/playback state (wire to world.onDespawn). */
removeEntity(entity: Entity): void {
this.params.delete(entity);
this.triggers.delete(entity);
+ this.runtimes_.delete(entity);
}
private paramStore(entity: Entity): Map<string, number | boolean> {
@@ -598,7 +614,9 @@ export class AnimatorControllerAPI {
// -- per-frame system -----------------------------------------------------
- update(world: World): void {
+ /** `dt` seconds advance the animator's own clock, which is what a sampled
+ * motion is evaluated against and what a crossfade progresses on. */
+ update(world: World, dt: number = 0): void {
const entities = world.getEntitiesWithComponents([Animator]);
for (const entity of entities) {
const a = world.get(entity, Animator) as AnimatorData;
@@ -620,13 +638,15 @@ export class AnimatorControllerAPI {
const params = resolveParams(def, this.params.get(entity) ?? EMPTY_PARAMS);
const triggerSet = this.triggers.get(entity);
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 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 && ctx.finished(leafMotion);
+ const clipFinished = leafMotion !== null && this.motionEnded(ctx, leafMotion, rt.time);
- const { nextPath, consumedTriggers } = evaluateAnimatorPath(
+ const { nextPath, consumedTriggers, fadeDuration } = evaluateAnimatorPath(
def, fromPath, params, triggerSet ?? EMPTY_TRIGGERS, clipFinished,
);
if (triggerSet) for (const t of consumedTriggers) triggerSet.delete(t);
@@ -643,11 +663,119 @@ export class AnimatorControllerAPI {
// 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);
+
+ if (stateChanged) {
+ this.beginState(rt, leafMotion, motion, fadeDuration);
+ }
+ if (motion) this.driveMotion(ctx, world, rt, motion, stateChanged);
+ }
+ }
+
+ /**
+ * Enter a state: the clock restarts, and the motion being left keeps running
+ * as the thing to fade out of. Only when BOTH can be sampled - a switched
+ * motion has no partial state to hold, so a fade over one would be a pause.
+ */
+ private beginState(
+ rt: AnimatorRuntime,
+ leaving: AnimatorMotion | null, entering: AnimatorMotion | null, fadeDuration: number,
+ ): void {
+ const blendable = fadeDuration > 0 && leaving !== null && entering !== null
+ && this.canSample(leaving) && this.canSample(entering);
+ if (blendable) {
+ rt.fadeFrom = leaving;
+ rt.fadeFromTime = rt.time;
+ rt.fadeElapsed = 0;
+ rt.fadeDuration = fadeDuration;
+ } else {
+ rt.fadeFrom = null;
+ }
+ rt.time = 0;
+ }
+
+ /** Advance the state's clock, and the fade's if one is running. */
+ private advance(rt: AnimatorRuntime, dt: number): void {
+ rt.time += dt;
+ if (rt.fadeFrom === null) return;
+ rt.fadeFromTime += dt;
+ rt.fadeElapsed += dt;
+ if (rt.fadeElapsed >= rt.fadeDuration) rt.fadeFrom = null;
+ }
+
+ /**
+ * 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.
+ */
+ private driveMotion(
+ ctx: MotionContext, world: World, rt: AnimatorRuntime,
+ motion: AnimatorMotion, enter: boolean,
+ ): void {
+ if (rt.fadeFrom !== null) {
+ rt.poseFrom.reset();
+ rt.poseTo.reset();
+ const from = ctx.sample(rt.fadeFrom, rt.fadeFromTime, rt.poseFrom);
+ const to = ctx.sample(motion, rt.time, rt.poseTo);
+ if (from && to) {
+ const t = Math.min(rt.fadeElapsed / rt.fadeDuration, 1);
+ rt.mixed.reset();
+ mixPoses(
+ [{ pose: rt.poseFrom, weight: 1 - t }, { pose: rt.poseTo, weight: t }],
+ rt.mixed, world,
+ );
+ rt.mixed.applyTo(world);
+ return;
+ }
+ rt.fadeFrom = null;
+ }
+
+ rt.poseTo.reset();
+ if (ctx.sample(motion, rt.time, rt.poseTo)) {
+ rt.poseTo.applyTo(world);
+ return;
+ }
+ ctx.drive(motion, enter);
+ }
+
+ /** Whether a motion has run out. A clip whose length the driver states is
+ * judged against our clock; anything else answers for itself. */
+ private motionEnded(ctx: MotionContext, motion: AnimatorMotion, time: number): boolean {
+ if (ctx.loops(motion)) return false;
+ const duration = ctx.duration(motion);
+ return duration > 0 ? time >= duration : ctx.finished(motion);
+ }
+
+ private canSample(motion: AnimatorMotion): boolean {
+ return this.motions_.driverFor(motion)?.sample !== undefined;
+ }
+
+ private runtimeFor(entity: Entity): AnimatorRuntime {
+ let rt = this.runtimes_.get(entity);
+ if (!rt) {
+ rt = {
+ time: 0, fadeFrom: null, fadeFromTime: 0, fadeElapsed: 0, fadeDuration: 0,
+ poseFrom: new Pose(), poseTo: new Pose(), mixed: new Pose(),
+ };
+ this.runtimes_.set(entity, rt);
}
+ return rt;
}
}
+/** 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 {
+ /** Seconds the current state's motion has been playing. */
+ time: number;
+ /** The motion being faded out, or null when nothing is. */
+ fadeFrom: AnimatorMotion | null;
+ fadeFromTime: number;
+ fadeElapsed: number;
+ fadeDuration: number;
+ poseFrom: Pose;
+ poseTo: Pose;
+ mixed: Pose;
+}
+
const EMPTY_PARAMS: ReadonlyMap<string, number | boolean> = new Map();
const EMPTY_TRIGGERS: ReadonlySet<string> = new Set();
diff --git a/sdk/src/animation/index.ts b/sdk/src/animation/index.ts
index a4869aec4..8a0fb9442 100644
--- a/sdk/src/animation/index.ts
+++ b/sdk/src/animation/index.ts
@@ -152,3 +152,6 @@ export {
SPRITE_MOTION,
spriteMotionDriver,
} from './spriteMotion';
+
+export { Pose, type PoseTrack, type PoseWorld } from './pose';
+export { mixPoses, type WeightedPose } from './poseMix';
diff --git a/sdk/src/animation/motion.ts b/sdk/src/animation/motion.ts
index 3149b526b..7a6c5027e 100644
--- a/sdk/src/animation/motion.ts
+++ b/sdk/src/animation/motion.ts
@@ -21,6 +21,7 @@
import type { Entity } from '../types';
import type { World } from '../ecs/world';
+import type { Pose } from './pose';
/** Parameter values a graph exposes to its motions (floats and bools). */
export type MotionParams = Readonly<Record<string, number | boolean>>;
@@ -76,22 +77,45 @@ export interface MotionContext {
drive(motion: AnimatorMotion, enter: boolean): void;
/** Whether a nested motion has run to its end. */
finished(motion: AnimatorMotion): boolean;
+ /** Sample a nested motion into `pose`; false when its kind cannot be sampled. */
+ sample(motion: AnimatorMotion, time: number, pose: Pose): boolean;
+ /** One pass of a nested motion in seconds; 0 when it does not say. */
+ duration(motion: AnimatorMotion): number;
+ /** Whether a nested motion repeats, and so never ends on its own. */
+ loops(motion: AnimatorMotion): boolean;
}
+/**
+ * How one kind of motion is played. A driver supplies EITHER `sample` — stating
+ * values for something else to compose — or `apply`, for a motion that can only
+ * be switched to, a sprite sheet having no meaning halfway between two clips.
+ * Only a motion that states values without writing them can be blended.
+ */
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;
+ 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.
+ * Evaluate `motion` at `time` seconds into `pose`, writing no component;
+ * wrapping belongs here, only the driver knowing how long its clip runs.
+ * Returns whether anything was sampled — a composite whose chosen child
+ * cannot be must answer false, or the caller takes silence for a pose.
*/
- isFinished(ctx: MotionContext, motion: M): boolean;
+ sample?(ctx: MotionContext, motion: M, time: number, pose: Pose): boolean;
+ /** One pass in seconds. Absent, or 0, means the motion does not say. */
+ duration?(ctx: MotionContext, motion: M): number;
+ /** Whether the motion repeats. A looping motion never finishes. */
+ loops?(ctx: MotionContext, motion: M): boolean;
+ /**
+ * Whether the motion has ended — what gates a `hasExitTime` transition. For
+ * a driver whose end is no clock the animator keeps (a sprite clip, a spine
+ * track); one reporting a `duration` is judged on the animator's own time.
+ * Absent answers false: a transition that never fires is the visible failure.
+ */
+ isFinished?(ctx: MotionContext, motion: M): boolean;
}
/**
@@ -135,8 +159,12 @@ export class MotionRegistry {
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,
+ drive: (motion, enter) => { this.driverFor(motion)?.apply?.(this.ctx_, motion, enter); },
+ finished: (motion) => this.driverFor(motion)?.isFinished?.(this.ctx_, motion) ?? false,
+ sample: (motion, time, pose) =>
+ this.driverFor(motion)?.sample?.(this.ctx_, motion, time, pose) ?? false,
+ duration: (motion) => this.driverFor(motion)?.duration?.(this.ctx_, motion) ?? 0,
+ loops: (motion) => this.driverFor(motion)?.loops?.(this.ctx_, motion) ?? false,
};
}
@@ -179,6 +207,18 @@ export const blend1DMotionDriver: MotionDriver<AnimatorBlend1DMotion> = {
const selected = blendSelection(ctx, blend);
if (selected) ctx.drive(selected, enter);
},
+ sample(ctx, blend, time, pose) {
+ const selected = blendSelection(ctx, blend);
+ return selected !== null && ctx.sample(selected, time, pose);
+ },
+ duration(ctx, blend) {
+ const selected = blendSelection(ctx, blend);
+ return selected ? ctx.duration(selected) : 0;
+ },
+ loops(ctx, blend) {
+ const selected = blendSelection(ctx, blend);
+ return selected ? ctx.loops(selected) : false;
+ },
isFinished(ctx, blend) {
const selected = blendSelection(ctx, blend);
return selected ? ctx.finished(selected) : false;
diff --git a/sdk/src/animation/pose.ts b/sdk/src/animation/pose.ts
new file mode 100644
index 000000000..98668608d
--- /dev/null
+++ b/sdk/src/animation/pose.ts
@@ -0,0 +1,110 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file pose.ts
+ * @brief What a motion evaluates to before anything is written: component
+ * values, held so several motions can be composed into one result.
+ *
+ * @details A sampler that writes the world as it goes cannot be blended - the
+ * second motion overwrites the first, and the result depends on which
+ * ran last. Sampling into a pose separates "what this motion says at
+ * this time" from "what the entity ends up as", so composition is an
+ * operation on values and the world is written once.
+ *
+ * Runtime-internal: the buffers are reused between frames, so nothing
+ * outside the animation runtime should hold one.
+ */
+
+import type { Entity } from '../types';
+import type { AnyComponentDef } from '../ecs/component';
+
+/** The world surface a pose is seeded from and written back to. */
+export interface PoseWorld {
+ has(entity: Entity, def: AnyComponentDef): boolean;
+ get(entity: Entity, def: AnyComponentDef): Record<string, unknown>;
+ set(entity: Entity, def: AnyComponentDef, data: Record<string, unknown>): void;
+}
+
+/** One component on one entity, as some motion posed it. */
+export interface PoseTrack {
+ entity: Entity;
+ def: AnyComponentDef;
+ /** The component's values with this motion's channels written in. */
+ data: Record<string, unknown>;
+ /** Top-level fields this motion wrote; the rest of `data` is the base. */
+ touched: Set<string>;
+}
+
+interface PoseSlot {
+ track: PoseTrack;
+ /** Which generation of this pose last seeded the track. */
+ stamp: number;
+}
+
+const keyOf = (entity: Entity, def: AnyComponentDef): string => `${entity} ${def._name}`;
+
+/**
+ * Copy `src`'s values into `dst`, reusing whatever objects `dst` already holds.
+ * A pose OWNS its values: a builtin component's `get` hands back a projection
+ * the next reader may share, so two poses seeded from one entity would be the
+ * same object, and blending them would compare a value with itself.
+ */
+function copyInto(dst: Record<string, unknown>, src: Record<string, unknown>): void {
+ for (const key of Object.keys(src)) {
+ const value = src[key];
+ if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
+ const nested = (dst[key] ??= {}) as Record<string, unknown>;
+ Object.assign(nested, value);
+ } else {
+ dst[key] = value;
+ }
+ }
+}
+
+/**
+ * One motion's evaluated result. Reused across frames: {@link reset} keeps the
+ * track objects and their buffers, so a steady animation allocates nothing
+ * after its first frame.
+ */
+export class Pose {
+ private readonly slots_ = new Map<string, PoseSlot>();
+ private readonly live_: PoseTrack[] = [];
+ private stamp_ = 0;
+
+ /** Drop this frame's contents, keeping the buffers. */
+ reset(): void {
+ this.stamp_++;
+ this.live_.length = 0;
+ }
+
+ get tracks(): readonly PoseTrack[] {
+ return this.live_;
+ }
+
+ /**
+ * The track for this component, seeded from the world the first time this
+ * frame asks for it. The seed is what makes an untouched field survive: a
+ * motion animating only position must not zero the rotation beside it.
+ */
+ track(world: PoseWorld, entity: Entity, def: AnyComponentDef): PoseTrack | null {
+ const key = keyOf(entity, def);
+ const slot = this.slots_.get(key);
+ if (slot && slot.stamp === this.stamp_) return slot.track;
+ if (!world.has(entity, def)) return null;
+
+ const track = slot?.track ?? { entity, def, data: {}, touched: new Set<string>() };
+ copyInto(track.data, world.get(entity, def));
+ track.touched.clear();
+ if (slot) slot.stamp = this.stamp_;
+ else this.slots_.set(key, { track, stamp: this.stamp_ });
+ this.live_.push(track);
+ return track;
+ }
+
+ /** Write this pose's touched fields to the world. */
+ applyTo(world: PoseWorld): void {
+ for (const track of this.live_) {
+ if (track.touched.size > 0) world.set(track.entity, track.def, track.data);
+ }
+ }
+}
diff --git a/sdk/src/animation/poseMix.ts b/sdk/src/animation/poseMix.ts
new file mode 100644
index 000000000..5a926265b
--- /dev/null
+++ b/sdk/src/animation/poseMix.ts
@@ -0,0 +1,188 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file poseMix.ts
+ * @brief Composing several weighted poses into the one that gets written.
+ *
+ * @details Every field is a weighted average over the poses that WROTE it, and
+ * the weights are renormalized per field. That is what lets a motion
+ * animating only position fade against one animating only rotation:
+ * each channel is shared out among its own contributors, so a field
+ * only one motion drives arrives whole instead of fading toward the
+ * base value.
+ *
+ * Addition commutes, so the result does not depend on the order the
+ * poses were sampled or mixed - which is the property crossfade needs
+ * and the reason sampling writes here rather than into the world.
+ */
+
+import type { Pose, PoseTrack, PoseWorld } from './pose';
+
+/** A pose and how much of it the result is made of. */
+export interface WeightedPose {
+ pose: Pose;
+ weight: number;
+}
+
+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);
+ if (keys.length === 0) return false;
+ return keys.every(k => typeof (v as Record<string, unknown>)[k] === 'number');
+}
+
+/**
+ * The representative of the pair {q, -q}, which name the same rotation. Applied
+ * to the RESULT this is what makes the mix order-independent: aligning b to a or
+ * a to b differs only in overall sign, and collapsing that leaves one answer.
+ */
+function canonicalize(out: Quat): void {
+ if (out.w > 0) return;
+ if (out.w < 0 || out.x < 0
+ || (out.x === 0 && (out.y < 0 || (out.y === 0 && out.z < 0)))) {
+ out.w = -out.w; out.x = -out.x; out.y = -out.y; out.z = -out.z;
+ }
+}
+
+/**
+ * Accumulate `q * weight` into `acc`, against the hemisphere `ref` names.
+ * Without the alignment, two quaternions a full turn apart in representation
+ * cancel instead of blending - the 180-degree flip a naive average produces.
+ */
+function accumulateQuat(acc: Quat, ref: Quat, q: Quat, weight: number): void {
+ const dot = ref.w * q.w + ref.x * q.x + ref.y * q.y + ref.z * q.z;
+ const s = dot < 0 ? -weight : weight;
+ acc.w += q.w * s;
+ acc.x += q.x * s;
+ acc.y += q.y * s;
+ acc.z += q.z * s;
+}
+
+function normalizeQuat(out: Quat): void {
+ const len = Math.hypot(out.w, out.x, out.y, out.z);
+ if (len < 1e-8) {
+ out.w = 1; out.x = 0; out.y = 0; out.z = 0;
+ return;
+ }
+ out.w /= len; out.x /= len; out.y /= len; out.z /= len;
+}
+
+/** The contributors to one component, gathered once per mixed track. */
+interface Contribution {
+ track: PoseTrack;
+ weight: number;
+}
+
+function mixQuaternionField(field: string, parts: Contribution[], into: Record<string, unknown>): void {
+ // The first contributor names the hemisphere the rest align to. WHICH one it
+ // is does not change the rotation that comes out - see canonicalize.
+ let ref: Quat | null = null;
+ const acc: Quat = { w: 0, x: 0, y: 0, z: 0 };
+ for (const part of parts) {
+ const value = part.track.data[field];
+ if (!isQuat(value)) continue;
+ if (ref === null) ref = value;
+ accumulateQuat(acc, ref, value, part.weight);
+ }
+ if (ref === null) return;
+ normalizeQuat(acc);
+ canonicalize(acc);
+ // `+ 0` collapses -0 to 0. Negating a zero component leaves one, and while
+ // it compares equal it is still a trace of which hemisphere was picked -
+ // enough to make two orderings differ bit for bit.
+ const dst = (into[field] ??= {}) as Record<string, number>;
+ dst.w = acc.w + 0; dst.x = acc.x + 0; dst.y = acc.y + 0; dst.z = acc.z + 0;
+}
+
+function mixNumericObjectField(
+ field: string, parts: Contribution[], total: number, into: Record<string, unknown>,
+): void {
+ const dst = (into[field] ??= {}) as Record<string, number>;
+ const sums: Record<string, number> = {};
+ for (const part of parts) {
+ const value = part.track.data[field];
+ if (!isNumericObject(value)) continue;
+ for (const axis of Object.keys(value)) {
+ sums[axis] = (sums[axis] ?? 0) + value[axis]! * part.weight;
+ }
+ }
+ for (const axis of Object.keys(sums)) dst[axis] = sums[axis]! / total;
+}
+
+function mixScalarField(
+ field: string, parts: Contribution[], total: number, into: Record<string, unknown>,
+): void {
+ let sum = 0;
+ for (const part of parts) {
+ const value = part.track.data[field];
+ if (typeof value === 'number') sum += value * part.weight;
+ }
+ into[field] = sum / total;
+}
+
+/**
+ * Blend `sources` into `out`, then write it. Weights need not sum to one: each
+ * field divides by the weight that actually reached it.
+ *
+ * `out` is seeded from the world like any pose, so a component some motion
+ * touches only partly keeps its other fields.
+ */
+export function mixPoses(sources: readonly WeightedPose[], out: Pose, world: PoseWorld): void {
+ out.reset();
+
+ const byComponent = new Map<string, Contribution[]>();
+ for (const { pose, weight } of sources) {
+ if (weight <= 0) continue;
+ for (const track of pose.tracks) {
+ if (track.touched.size === 0) continue;
+ const key = `${track.entity} ${track.def._name}`;
+ const list = byComponent.get(key);
+ if (list) list.push({ track, weight });
+ else byComponent.set(key, [{ track, weight }]);
+ }
+ }
+
+ for (const parts of byComponent.values()) {
+ const first = parts[0]!;
+ const target = out.track(world, first.track.entity, first.track.def);
+ if (!target) continue;
+
+ // Per FIELD, not per track: the weights that count are the ones whose
+ // motion wrote this field.
+ const fields = new Set<string>();
+ for (const part of parts) for (const f of part.track.touched) fields.add(f);
+
+ for (const field of fields) {
+ const writers: Contribution[] = [];
+ let total = 0;
+ for (const part of parts) {
+ if (!part.track.touched.has(field)) continue;
+ writers.push(part);
+ total += part.weight;
+ }
+ if (total <= 0) continue;
+
+ const sample = writers[0]!.track.data[field];
+ if (isQuat(sample)) mixQuaternionField(field, writers, target.data);
+ else if (typeof sample === 'number') mixScalarField(field, writers, total, target.data);
+ else if (isNumericObject(sample)) {
+ mixNumericObjectField(field, writers, total, target.data);
+ } else {
+ // Nothing to average between (a string, a flag). Left at the base
+ // value rather than picked from one side, which would make the
+ // answer depend on which motion was sampled first.
+ continue;
+ }
+ target.touched.add(field);
+ }
+ }
+}
diff --git a/sdk/src/timeline/TimelineEvaluator.ts b/sdk/src/timeline/TimelineEvaluator.ts
index b23b8bba8..2282e1543 100644
--- a/sdk/src/timeline/TimelineEvaluator.ts
+++ b/sdk/src/timeline/TimelineEvaluator.ts
@@ -23,6 +23,7 @@
import { TrackType, InterpType, WrapMode, type TimelineAsset, type PropertyChannel } from './TimelineTypes';
import { setNestedProperty, resolveChildEntity } from './TimelineRuntime';
import { getComponent, type AnyComponentDef } from '../ecs/component';
+import type { Pose, PoseTrack, PoseWorld } from '../animation/pose';
import { q } from '../math/quat';
import type { Entity } from '../types';
import type { World } from '../ecs/world';
@@ -183,13 +184,53 @@ export interface SampleOptions {
}
/**
- * Evaluate every property track at `time` and write the results to the world.
- * P1 covers property tracks only; spine/audio/spriteAnim/activation side-effects
- * land in P3/P4. Each track touches one component on one resolved entity, so it
- * reads/writes that component once (all channels folded into a single set).
+ * Where a sampled track's values land: the world, for standalone playback and
+ * the editor preview, or a {@link Pose}, for blending — values already written
+ * cannot be weighed against each other. One traversal serves both.
*/
-export function sampleTimeline(
- asset: TimelineAsset, time: number, rootEntity: Entity, deps: SampleDeps, opts?: SampleOptions,
+export interface SampleSink {
+ /** The component data to write into, or null to skip this track. */
+ open(entity: Entity, def: AnyComponentDef): Record<string, unknown> | null;
+ /** Finish a track whose `touched` top-level fields were written. */
+ close(
+ entity: Entity, def: AnyComponentDef,
+ data: Record<string, unknown>, touched: ReadonlySet<string>,
+ ): void;
+}
+
+/** The sink that writes the world directly. */
+export function worldSink(world: SampleWorld): SampleSink {
+ return {
+ open: (entity, def) => (world.has(entity, def) ? world.get(entity, def) : null),
+ close: (entity, def, data) => { world.set(entity, def, data); },
+ };
+}
+
+/** The sink that records into a pose for later composition. */
+export function poseSink(pose: Pose, world: PoseWorld): SampleSink {
+ let current: PoseTrack | null = null;
+ return {
+ open: (entity, def) => {
+ current = pose.track(world, entity, def);
+ return current?.data ?? null;
+ },
+ close: (_entity, _def, _data, touched) => {
+ if (!current) return;
+ for (const field of touched) current.touched.add(field);
+ current = null;
+ },
+ };
+}
+
+/**
+ * Evaluate every property track at `time` into `sink`. Property tracks only —
+ * spine, audio, spriteAnim and activation carry side effects a sink cannot hold.
+ * Each track touches one component on one entity, so it opens that component
+ * once and folds every channel into a single write.
+ */
+export function sampleTimelineInto(
+ asset: TimelineAsset, time: number, rootEntity: Entity,
+ deps: SampleDeps, sink: SampleSink, opts?: SampleOptions,
): void {
for (const track of asset.tracks) {
if (track.type !== TrackType.Property) continue;
@@ -198,9 +239,11 @@ export function sampleTimeline(
if (!def) continue;
const entity = deps.resolveChild(rootEntity, track.childPath);
- if (entity == null || !deps.world.has(entity, def)) continue;
+ if (entity == null) continue;
+
+ const data = sink.open(entity, def);
+ if (!data) continue;
- const data = deps.world.get(entity, def);
let changed = false;
const touched = new Set<string>();
for (const ch of track.channels) {
@@ -214,11 +257,29 @@ export function sampleTimeline(
}
if (changed) {
finishQuaternions(data, track.component, touched);
- deps.world.set(entity, def, data);
+ sink.close(entity, def, data, touched);
}
}
}
+/** Evaluate every property track at `time` and write the results to the world. */
+export function sampleTimeline(
+ asset: TimelineAsset, time: number, rootEntity: Entity, deps: SampleDeps, opts?: SampleOptions,
+): void {
+ sampleTimelineInto(asset, time, rootEntity, deps, worldSink(deps.world), opts);
+}
+
+/**
+ * Evaluate every property track at `time` into `pose`, touching no component.
+ * What a motion says, held apart from what the entity becomes.
+ */
+export function sampleTimelineIntoPose(
+ asset: TimelineAsset, time: number, rootEntity: Entity,
+ deps: SampleDeps, pose: Pose, opts?: SampleOptions,
+): void {
+ sampleTimelineInto(asset, time, rootEntity, deps, poseSink(pose, deps.world), opts);
+}
+
/**
* Convenience wrapper binding the real SDK component registry + child resolver.
* The editor preview bridge and the runtime both call this; tests inject mocks
diff --git a/sdk/src/timeline/timelineMotion.ts b/sdk/src/timeline/timelineMotion.ts
index a843d682a..04bd72a2d 100644
--- a/sdk/src/timeline/timelineMotion.ts
+++ b/sdk/src/timeline/timelineMotion.ts
@@ -5,60 +5,69 @@
* @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.
+ * skeletal clip IS a timeline - property tracks writing each joint
+ * entity's Transform - so this driver samples the same asset with the
+ * same evaluator, and what it produces is a pose rather than a write.
+ * The path from joint Transform to MeshSkin is unchanged: the animator
+ * adds no second owner of a bone pose.
+ *
+ * It does not touch TimelinePlayer. That component carries a clip's own
+ * clock for standalone playback, and one clock cannot serve two clips
+ * at once - which crossfade needs. The animator keeps the time and
+ * hands it in; TimelinePlayer stays what a timeline plays on when no
+ * animator is involved.
*/
import type { MotionDriver, AnimatorClipMotion, MotionContext } from '../animation/motion';
-import { TimelinePlayer, type TimelinePlayerData } from './TimelinePlayerComponent';
+import type { Pose } from '../animation/pose';
+import { getComponent } from '../ecs/component';
+import { applyWrapMode, sampleTimelineIntoPose, type SampleDeps } from './TimelineEvaluator';
+import { resolveChildEntity } from './TimelineRuntime';
+import { WrapMode, type TimelineAsset } from './TimelineTypes';
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';
+/** How the motion wants the clip wrapped; unstated leaves the clip's own. */
+function wrapOf(motion: AnimatorClipMotion, asset: TimelineAsset): WrapMode {
+ if (motion.loop === undefined) return asset.wrapMode;
+ return motion.loop ? WrapMode.Loop : WrapMode.Once;
}
+const speedOf = (motion: AnimatorClipMotion): number => Math.max(motion.speed ?? 1, 1e-4);
+
/**
- * 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.
+ * The driver, over the app's own {@link TimelineAPI}: which clip a name resolves
+ * to is per App, so this is built per App rather than being a module value.
*/
export function createTimelineMotionDriver(timeline: TimelineAPI): MotionDriver<AnimatorClipMotion> {
+ // One deps record, re-aimed per call. The sampler asks it for the world and
+ // the child resolver; both are the same for every entity in a frame except
+ // the world reference, which the context supplies.
+ const deps: SampleDeps = {
+ world: null!,
+ getComponent,
+ resolveChild: (root, childPath) => resolveChildEntity(deps.world as never, root, childPath),
+ };
+
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;
+ sample(ctx: MotionContext, motion: AnimatorClipMotion, time: number, pose: Pose): boolean {
+ const asset = timeline.getAsset(motion.clip);
+ if (!asset) return false;
+ const local = applyWrapMode(time * speedOf(motion), asset.duration, wrapOf(motion, asset));
+ deps.world = ctx.world;
+ sampleTimelineIntoPose(asset, local.time, ctx.entity, deps, pose);
+ return true;
+ },
- 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 = {};
- }
+ /** In the animator's own seconds, which is why the speed divides out. */
+ duration(_ctx: MotionContext, motion: AnimatorClipMotion): number {
+ return (timeline.getAsset(motion.clip)?.duration ?? 0) / speedOf(motion);
},
- 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;
+ loops(_ctx: MotionContext, motion: AnimatorClipMotion): boolean {
+ const asset = timeline.getAsset(motion.clip);
+ return asset ? wrapOf(motion, asset) !== WrapMode.Once : false;
},
};
}
diff --git a/sdk/tests/animatorCrossfade.test.ts b/sdk/tests/animatorCrossfade.test.ts
new file mode 100644
index 000000000..eec85c8fe
--- /dev/null
+++ b/sdk/tests/animatorCrossfade.test.ts
@@ -0,0 +1,272 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * The claim: a crossfade composes poses, so what lands is one write whose value
+ * does not depend on which motion was sampled first.
+ */
+import { describe, it, expect } from 'vitest';
+import { Pose, mixPoses, Animator, AnimatorControllerAPI,
+ type AnimatorData, type AnimatorControllerDef } 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;
+
+/** Registry is per context and reset between tests, so this is taken per call. */
+const probe = () => defineComponent('MixProbe', {
+ lift: 0,
+ pos: { x: 0, y: 0, z: 0 },
+ rot: { w: 1, x: 0, y: 0, z: 0 },
+ scale: { x: 1, y: 1, z: 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, 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;
+}
+
+/** A pose stating exactly `values` for the probe component on E. */
+function poseStating(world: any, values: Record<string, unknown>): Pose {
+ const pose = new Pose();
+ pose.reset();
+ const track = pose.track(world, E, probe())!;
+ for (const [field, value] of Object.entries(values)) {
+ track.data[field] = value;
+ track.touched.add(field);
+ }
+ return pose;
+}
+
+function seedWorld() {
+ const world = makeWorld();
+ world.insert(E, probe(), {
+ lift: 0, pos: { x: 0, y: 0, z: 0 },
+ rot: { w: 1, x: 0, y: 0, z: 0 }, scale: { x: 1, y: 1, z: 1 },
+ });
+ return world;
+}
+
+const read = (world: any) => world.get(E, probe()) as {
+ lift: number;
+ pos: { x: number; y: number; z: number };
+ rot: { w: number; x: number; y: number; z: number };
+ scale: { x: number; y: number; z: number };
+};
+
+describe('the pose mixer', () => {
+ it('averages scalars and vectors by weight', () => {
+ const world = seedWorld();
+ const a = poseStating(world, { lift: 0, pos: { x: 0, y: 10, z: 0 } });
+ const b = poseStating(world, { lift: 10, pos: { x: 100, y: 20, z: 0 } });
+ const out = new Pose();
+
+ mixPoses([{ pose: a, weight: 0.25 }, { pose: b, weight: 0.75 }], out, world);
+ out.applyTo(world);
+
+ const got = read(world);
+ expect(got.lift).toBeCloseTo(7.5, 6);
+ expect(got.pos.x).toBeCloseTo(75, 6);
+ expect(got.pos.y).toBeCloseTo(17.5, 6);
+ });
+
+ it('takes the shortest arc between rotations, whichever way they are spelled', () => {
+ const world = seedWorld();
+ const identity = { w: 1, x: 0, y: 0, z: 0 };
+ // The SAME rotation as (0.7071, 0, 0, 0.7071) - a quarter turn about Z -
+ // written negated. Averaged naively this cancels toward a three-quarter
+ // turn the other way instead of meeting the identity halfway.
+ const quarterTurnNegated = { w: -Math.SQRT1_2, x: -0, y: -0, z: -Math.SQRT1_2 };
+
+ const a = poseStating(world, { rot: identity });
+ const b = poseStating(world, { rot: quarterTurnNegated });
+ const out = new Pose();
+
+ mixPoses([{ pose: a, weight: 0.5 }, { pose: b, weight: 0.5 }], out, world);
+ out.applyTo(world);
+
+ // Halfway from 0 to 90 degrees about Z is 45: (cos22.5, 0, 0, sin22.5).
+ const got = read(world).rot;
+ expect(got.w).toBeCloseTo(Math.cos(Math.PI / 8), 5);
+ expect(got.z).toBeCloseTo(Math.sin(Math.PI / 8), 5);
+ expect(Math.hypot(got.w, got.x, got.y, got.z)).toBeCloseTo(1, 6);
+ });
+
+ it('gives a field only one motion writes to that motion whole', () => {
+ const world = seedWorld();
+ // `lift` is B's alone. At weight 0.1 it must still arrive at 50, not be
+ // dragged nine tenths of the way back to the base value.
+ const a = poseStating(world, { pos: { x: 4, y: 0, z: 0 } });
+ const b = poseStating(world, { lift: 50 });
+ const out = new Pose();
+
+ mixPoses([{ pose: a, weight: 0.9 }, { pose: b, weight: 0.1 }], out, world);
+ out.applyTo(world);
+
+ expect(read(world).lift).toBeCloseTo(50, 6);
+ expect(read(world).pos.x).toBeCloseTo(4, 6);
+ });
+
+ it('is the same answer whichever order the poses arrive in', () => {
+ const run = (swap: boolean) => {
+ const world = seedWorld();
+ const a = poseStating(world, {
+ lift: 3, pos: { x: 0, y: 1, z: 2 },
+ rot: { w: 1, x: 0, y: 0, z: 0 }, scale: { x: 1, y: 1, z: 1 },
+ });
+ const b = poseStating(world, {
+ lift: 9, pos: { x: 8, y: 5, z: -3 },
+ rot: { w: -Math.SQRT1_2, x: 0, y: 0, z: -Math.SQRT1_2 },
+ scale: { x: 2, y: 3, z: 4 },
+ });
+ const sources = [{ pose: a, weight: 0.3 }, { pose: b, weight: 0.7 }];
+ const out = new Pose();
+ mixPoses(swap ? [...sources].reverse() : sources, out, world);
+ out.applyTo(world);
+ return read(world);
+ };
+
+ // Not "close to": composition is addition, and addition commutes.
+ expect(run(true)).toEqual(run(false));
+ });
+});
+
+// ---------------------------------------------------------------------------
+// End to end, through the animator
+// ---------------------------------------------------------------------------
+
+/** A clip holding the probe at a constant pose. */
+function holdPose(lift: number, rot: { w: number; x: number; y: number; z: number }): TimelineAsset {
+ const key = (value: number) => ([{
+ time: 0, value, inTangent: 0, outTangent: 0, interpolation: InterpType.Linear,
+ }]);
+ return {
+ version: '1.2', type: 'timeline', duration: 10, wrapMode: WrapMode.Loop,
+ tracks: [{
+ type: TrackType.Property, component: 'MixProbe', childPath: '', name: 't',
+ channels: [
+ { property: 'lift', keyframes: key(lift) },
+ { property: 'rot.w', keyframes: key(rot.w) },
+ { property: 'rot.x', keyframes: key(rot.x) },
+ { property: 'rot.y', keyframes: key(rot.y) },
+ { property: 'rot.z', keyframes: key(rot.z) },
+ ],
+ }],
+ } as TimelineAsset;
+}
+
+const IDENTITY = { w: 1, x: 0, y: 0, z: 0 };
+const QUARTER_Z = { w: Math.SQRT1_2, x: 0, y: 0, z: Math.SQRT1_2 };
+
+/** Idle at lift 0 / no turn, Run at lift 100 / a quarter turn, fading over 1s. */
+function fadingController(fadeSeconds: number): AnimatorControllerAPI {
+ const timeline = new TimelineAPI();
+ timeline.registerAsset('idle.estimeline', holdPose(0, IDENTITY));
+ timeline.registerAsset('run.estimeline', holdPose(100, QUARTER_Z));
+ const ctrl = new AnimatorControllerAPI();
+ ctrl.registerMotionDriver(TIMELINE_MOTION, createTimelineMotionDriver(timeline));
+
+ const def: AnimatorControllerDef = {
+ parameters: [{ name: 'speed', type: 'float', default: 0 }],
+ initialState: 'Idle',
+ states: [
+ {
+ name: 'Idle',
+ motion: { kind: TIMELINE_MOTION, clip: 'idle.estimeline' },
+ transitions: [{
+ to: 'Run',
+ conditions: [{ param: 'speed', op: 'gt', value: 0 }],
+ duration: fadeSeconds,
+ }],
+ },
+ {
+ name: 'Run',
+ motion: { kind: TIMELINE_MOTION, clip: 'run.estimeline' },
+ transitions: [],
+ },
+ ],
+ };
+ ctrl.registerController('loco', def);
+ return ctrl;
+}
+
+describe('a crossfade through the animator', () => {
+ it('is all of the outgoing motion the moment the fade begins', () => {
+ const world = seedWorld();
+ const ctrl = fadingController(1);
+ world.insert(E, Animator, { controller: 'loco', currentState: '', enabled: true } as AnimatorData);
+
+ ctrl.update(world, 0.016);
+ expect(read(world).lift).toBe(0);
+
+ // The frame the transition fires: no time has elapsed in the fade yet.
+ ctrl.setFloat(E, 'speed', 1);
+ ctrl.update(world, 0);
+ expect(read(world).lift).toBeCloseTo(0, 6);
+ expect(read(world).rot.w).toBeCloseTo(1, 6);
+ });
+
+ it('is halfway across at the midpoint, in both position and rotation', () => {
+ const world = seedWorld();
+ const ctrl = fadingController(1);
+ world.insert(E, Animator, { controller: 'loco', currentState: '', enabled: true } as AnimatorData);
+
+ ctrl.update(world, 0.016);
+ ctrl.setFloat(E, 'speed', 1);
+ ctrl.update(world, 0); // fires the transition
+ ctrl.update(world, 0.5); // half of a one-second fade
+
+ const got = read(world);
+ expect(got.lift).toBeCloseTo(50, 4);
+ // Half of a quarter turn is an eighth: cos/sin of 22.5 degrees.
+ expect(got.rot.w).toBeCloseTo(Math.cos(Math.PI / 8), 4);
+ expect(got.rot.z).toBeCloseTo(Math.sin(Math.PI / 8), 4);
+ });
+
+ it('is all of the incoming motion once the fade is over', () => {
+ const world = seedWorld();
+ const ctrl = fadingController(1);
+ world.insert(E, Animator, { controller: 'loco', currentState: '', enabled: true } as AnimatorData);
+
+ ctrl.update(world, 0.016);
+ ctrl.setFloat(E, 'speed', 1);
+ ctrl.update(world, 0);
+ ctrl.update(world, 1.2); // past the end of the fade
+
+ const got = read(world);
+ expect(got.lift).toBeCloseTo(100, 5);
+ expect(got.rot.w).toBeCloseTo(QUARTER_Z.w, 5);
+ expect(got.rot.z).toBeCloseTo(QUARTER_Z.z, 5);
+ });
+
+ it('cuts when the transition names no duration', () => {
+ const world = seedWorld();
+ const ctrl = fadingController(0);
+ world.insert(E, Animator, { controller: 'loco', currentState: '', enabled: true } as AnimatorData);
+
+ ctrl.update(world, 0.016);
+ ctrl.setFloat(E, 'speed', 1);
+ ctrl.update(world, 0);
+ expect(read(world).lift).toBeCloseTo(100, 6);
+ });
+});
diff --git a/sdk/tests/animatorMotion.test.ts b/sdk/tests/animatorMotion.test.ts
index 4d26245ff..c0e518cef 100644
--- a/sdk/tests/animatorMotion.test.ts
+++ b/sdk/tests/animatorMotion.test.ts
@@ -10,12 +10,23 @@ import {
type AnimatorData, type AnimatorControllerDef, type AnimatorMotion,
type AnimatorState, type SpriteAnimatorData,
} from '../src/animation';
-import { TimelinePlayer, createTimelineMotionDriver, TIMELINE_MOTION,
- type TimelinePlayerData } from '../src/timeline';
+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;
+/**
+ * What a timeline motion writes here, so an assertion reads "the animation
+ * reached the entity". Fetched per call: the registry is per context and reset
+ * between tests, so a definition taken at module load is not the one the
+ * sampler resolves by name.
+ */
+const probeDef = () => defineComponent('MotionProbeA', { x: 0 });
+
function makeWorld() {
const store = new Map<unknown, Map<number, unknown>>();
const mapOf = (c: unknown) => {
@@ -27,6 +38,8 @@ function makeWorld() {
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); },
+ set(e: number, c: unknown, data: unknown) { mapOf(c).set(e, data); },
+ tryGet(e: number, c: unknown) { return mapOf(c).get(e) ?? null; },
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');
@@ -45,9 +58,23 @@ const spriteData = (): SpriteAnimatorData => ({
loop: true, playing: false, finished: false, enabled: true,
} as SpriteAnimatorData);
-const timelineData = (): TimelinePlayerData => ({
- timeline: '', playing: false, speed: 1, wrapMode: '', finished: false,
-});
+/** A clip holding `MotionProbeA.x` at a constant, so which clip is playing can
+ * be read straight off the entity. */
+function holdAt(value: number, duration = 1, wrapMode: WrapMode = WrapMode.Loop): TimelineAsset {
+ return {
+ version: '1.2', type: 'timeline', duration, wrapMode,
+ tracks: [{
+ type: TrackType.Property, component: 'MotionProbeA', childPath: '',
+ name: 'probe', channels: [{
+ property: 'x',
+ keyframes: [{
+ time: 0, value, inTangent: 0, outTangent: 0,
+ interpolation: InterpType.Linear,
+ }],
+ }],
+ }],
+ } as TimelineAsset;
+}
/**
* ONE graph, built over whatever motion the caller names for a state. The state
@@ -77,10 +104,13 @@ const spriteMotionFor = (name: string): AnimatorMotion => ({ kind: 'sprite', cli
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 {
+/** Idle holds x at 1, Run at 2 - so the entity says which state is playing. */
+function timelineController(): AnimatorControllerAPI {
+ const timeline = new TimelineAPI();
+ timeline.registerAsset('idle.estimeline', holdAt(1));
+ timeline.registerAsset('run.estimeline', holdAt(2));
const ctrl = new AnimatorControllerAPI();
- ctrl.registerMotionDriver(TIMELINE_MOTION, createTimelineMotionDriver(new TimelineAPI()));
+ ctrl.registerMotionDriver(TIMELINE_MOTION, createTimelineMotionDriver(timeline));
return ctrl;
}
@@ -88,81 +118,79 @@ function seed(world: any, controller: string): void {
world.insert(E, Animator, { controller, currentState: '', enabled: true } as AnimatorData);
}
+const probeX = (world: any): number => (world.get(E, probeDef()) as { x: number }).x;
+const stateOf = (world: any): string => (world.get(E, Animator) as AnimatorData).currentState;
+
describe('one graph, either kind of motion', () => {
it('runs the same state machine over sprite clips', () => {
const world = makeWorld();
- const ctrl = makeController();
+ const ctrl = new AnimatorControllerAPI();
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');
+ ctrl.update(world, 0.016);
+ expect(stateOf(world)).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');
+ ctrl.update(world, 0.016);
+ expect(stateOf(world)).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();
+ const ctrl = timelineController();
ctrl.registerController('loco', locomotionGraph(timelineMotionFor));
seed(world, 'loco');
- world.insert(E, TimelinePlayer, timelineData());
+ world.insert(E, probeDef(), { x: 0 });
- 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.update(world, 0.016);
+ expect(stateOf(world)).toBe('Idle');
+ expect(probeX(world)).toBe(1);
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');
+ ctrl.update(world, 0.016);
+ expect(stateOf(world)).toBe('Run');
+ expect(probeX(world)).toBe(2);
});
it('takes the same path through the graph, and drives its motion, either way', () => {
const run = (
motionFor: (s: string) => AnimatorMotion,
+ ctrl: AnimatorControllerAPI,
component: unknown, initial: () => unknown,
- targetOf: (data: any) => string,
- ): { states: string[]; targets: string[] } => {
+ targetOf: (data: any) => string | number,
+ ): { states: string[]; targets: (string | number)[] } => {
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[] = [];
+ const targets: (string | number)[] = [];
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);
+ ctrl.update(world, 0.016);
+ states.push(stateOf(world));
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);
+ const sprite = run(spriteMotionFor, new AnimatorControllerAPI(), SpriteAnimator,
+ spriteData, (d: SpriteAnimatorData) => d.clip);
+ const timeline = run(timelineMotionFor, timelineController(), probeDef(),
+ () => ({ x: 0 }), (d: { x: number }) => d.x);
// 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
+ // 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',
- ]);
+ expect(timeline.targets).toEqual([1, 1, 2, 2, 1]);
});
});
@@ -176,48 +204,70 @@ describe('exit time is the motion’s answer, whatever kind it is', () => {
],
});
+ const timelineCtrl = (clip: string, asset: TimelineAsset): AnimatorControllerAPI => {
+ const timeline = new TimelineAPI();
+ timeline.registerAsset(clip, asset);
+ const ctrl = new AnimatorControllerAPI();
+ ctrl.registerMotionDriver(TIMELINE_MOTION, createTimelineMotionDriver(timeline));
+ return ctrl;
+ };
+
it('waits for a sprite clip to stop', () => {
const world = makeWorld();
- const ctrl = makeController();
+ const ctrl = new AnimatorControllerAPI();
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');
+ ctrl.update(world, 0.016);
+ expect(stateOf(world)).toBe('Attack');
// Still playing: the exit-time transition must not fire.
- ctrl.update(world);
- expect((world.get(E, Animator) as AnimatorData).currentState).toBe('Attack');
+ ctrl.update(world, 0.016);
+ expect(stateOf(world)).toBe('Attack');
world.update(E, SpriteAnimator, (sp: SpriteAnimatorData) => { sp.playing = false; });
- ctrl.update(world);
- expect((world.get(E, Animator) as AnimatorData).currentState).toBe('Idle');
+ ctrl.update(world, 0.016);
+ expect(stateOf(world)).toBe('Idle');
});
- it('waits for a timeline to latch finished', () => {
+ it('waits out a non-looping timeline on the animator’s own clock', () => {
const world = makeWorld();
- const ctrl = makeController();
- ctrl.registerController('atk', oneShot({ kind: TIMELINE_MOTION, clip: 'attack.estimeline', loop: false }));
+ const ctrl = timelineCtrl('attack.estimeline', holdAt(1, 0.5, WrapMode.Once));
+ ctrl.registerController('atk', oneShot({ kind: TIMELINE_MOTION, clip: 'attack.estimeline' }));
seed(world, 'atk');
- world.insert(E, TimelinePlayer, timelineData());
+ world.insert(E, probeDef(), { x: 0 });
- ctrl.update(world);
- expect((world.get(E, Animator) as AnimatorData).currentState).toBe('Attack');
+ ctrl.update(world, 0.1);
+ expect(stateOf(world)).toBe('Attack');
+ ctrl.update(world, 0.1);
+ expect(stateOf(world)).toBe('Attack');
- ctrl.update(world);
- expect((world.get(E, Animator) as AnimatorData).currentState).toBe('Attack');
+ // Past its half second the clip is over, and the transition may fire.
+ ctrl.update(world, 0.4);
+ expect(stateOf(world)).toBe('Idle');
+ });
+
+ it('never ends a looping timeline', () => {
+ const world = makeWorld();
+ const ctrl = timelineCtrl('run.estimeline', holdAt(1, 0.5, WrapMode.Loop));
+ ctrl.registerController('atk', oneShot({ kind: TIMELINE_MOTION, clip: 'run.estimeline' }));
+ seed(world, 'atk');
+ world.insert(E, probeDef(), { x: 0 });
- world.update(E, TimelinePlayer, (p: TimelinePlayerData) => { p.finished = true; });
- ctrl.update(world);
- expect((world.get(E, Animator) as AnimatorData).currentState).toBe('Idle');
+ for (let i = 0; i < 20; i++) ctrl.update(world, 0.1);
+ expect(stateOf(world)).toBe('Attack');
});
});
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();
+ const timeline = new TimelineAPI();
+ timeline.registerAsset('walk.estimeline', holdAt(10));
+ timeline.registerAsset('run.estimeline', holdAt(20));
+ const ctrl = new AnimatorControllerAPI();
+ ctrl.registerMotionDriver(TIMELINE_MOTION, createTimelineMotionDriver(timeline));
ctrl.registerController('loco', {
parameters: [{ name: 'speed', type: 'float', default: 0 }],
initialState: 'Move',
@@ -235,16 +285,16 @@ describe('a blend is a motion, so it composes with any kind', () => {
}],
});
seed(world, 'loco');
- world.insert(E, TimelinePlayer, timelineData());
+ world.insert(E, probeDef(), { x: 0 });
- ctrl.update(world);
- expect((world.get(E, TimelinePlayer) as TimelinePlayerData).timeline).toBe('walk.estimeline');
+ ctrl.update(world, 0.016);
+ expect(probeX(world)).toBe(10);
// 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');
+ ctrl.update(world, 0.016);
+ expect(probeX(world)).toBe(20);
+ expect(stateOf(world)).toBe('Move');
});
});
@@ -293,10 +343,10 @@ describe('a kind this build cannot play', () => {
const ctrl = new AnimatorControllerAPI(); // no timeline driver registered
ctrl.registerController('loco', locomotionGraph(timelineMotionFor));
seed(world, 'loco');
- world.insert(E, TimelinePlayer, timelineData());
+ world.insert(E, probeDef(), { x: 0 });
- expect(() => ctrl.update(world)).not.toThrow();
- expect((world.get(E, TimelinePlayer) as TimelinePlayerData).timeline).toBe('');
+ expect(() => ctrl.update(world, 0.016)).not.toThrow();
+ expect(probeX(world)).toBe(0);
expect(ctrl.hasMotionDriver(TIMELINE_MOTION)).toBe(false);
});
});