A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(anim): a 1D blend mixes its neighbours instead of picking one
esenginea1906fd6f653
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 54d22ee5c..48a00655e 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 114 public · 94 beta · 1679 experimental · 3 deprecated+Symbols: 114 public · 94 beta · 1680 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -5128,6 +5128,7 @@ shift: boolean## MotionContext — interface @experimental```+borrowPose: () => Posedrive: (motion: AnimatorMotion, enter: boolean) => voidduration: (motion: AnimatorMotion) => numberentity: number@@ -5136,6 +5137,7 @@ extractRootMotion: booleanfinished: (motion: AnimatorMotion) => booleanloops: (motion: AnimatorMotion) => booleanparams: Readonly<Record<string, number | boolean>>+releasePose: (pose: Pose) => voidrootDelta: (motion: AnimatorMotion, span: MotionSpan, out: RootMotionDelta) => booleansample: (motion: AnimatorMotion, time: number, pose: Pose) => booleanworld: World@@ -10819,6 +10821,11 @@ AudioPluginMotionDriver<AnimatorBlend1DMotion>```+## blend1DPair — function @experimental+```+(blend: AnimatorBlend1DMotion, value: number): Readonly<Blend1DPair>+```+## btEdges — function @experimental```(def: BtDefinition): BtEdge[]diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 4a9a8049a..67843b099 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 114 public · 99 beta · 1698 experimental · 3 deprecated+Symbols: 114 public · 99 beta · 1699 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -5141,6 +5141,7 @@ shift: boolean## MotionContext — interface @experimental```+borrowPose: () => Posedrive: (motion: AnimatorMotion, enter: boolean) => voidduration: (motion: AnimatorMotion) => numberentity: number@@ -5149,6 +5150,7 @@ extractRootMotion: booleanfinished: (motion: AnimatorMotion) => booleanloops: (motion: AnimatorMotion) => booleanparams: Readonly<Record<string, number | boolean>>+releasePose: (pose: Pose) => voidrootDelta: (motion: AnimatorMotion, span: MotionSpan, out: RootMotionDelta) => booleansample: (motion: AnimatorMotion, time: number, pose: Pose) => booleanworld: World@@ -11027,6 +11029,11 @@ AudioPluginMotionDriver<AnimatorBlend1DMotion>```+## blend1DPair — function @experimental+```+(blend: AnimatorBlend1DMotion, value: number): Readonly<Blend1DPair>+```+## btEdges — function @experimental```(def: BtDefinition): BtEdge[]diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 155c9f158..6181f6f73 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: 114 public · 96 beta · 1678 experimental · 3 deprecated+Symbols: 114 public · 96 beta · 1679 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -5123,6 +5123,7 @@ shift: boolean## MotionContext — interface @experimental```+borrowPose: () => Posedrive: (motion: AnimatorMotion, enter: boolean) => voidduration: (motion: AnimatorMotion) => numberentity: number@@ -5131,6 +5132,7 @@ extractRootMotion: booleanfinished: (motion: AnimatorMotion) => booleanloops: (motion: AnimatorMotion) => booleanparams: Readonly<Record<string, number | boolean>>+releasePose: (pose: Pose) => voidrootDelta: (motion: AnimatorMotion, span: MotionSpan, out: RootMotionDelta) => booleansample: (motion: AnimatorMotion, time: number, pose: Pose) => booleanworld: World@@ -10814,6 +10816,11 @@ AudioPluginMotionDriver<AnimatorBlend1DMotion>```+## blend1DPair — function @experimental+```+(blend: AnimatorBlend1DMotion, value: number): Readonly<Blend1DPair>+```+## btEdges — function @experimental```(def: BtDefinition): BtEdge[]diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 5c5726e77..ecc9526f2 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: 114 public · 94 beta · 1700 experimental · 3 deprecated+Symbols: 114 public · 94 beta · 1701 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -5371,6 +5371,7 @@ shift: boolean## MotionContext — interface @experimental```+borrowPose: () => Posedrive: (motion: AnimatorMotion, enter: boolean) => voidduration: (motion: AnimatorMotion) => numberentity: number@@ -5379,6 +5380,7 @@ extractRootMotion: booleanfinished: (motion: AnimatorMotion) => booleanloops: (motion: AnimatorMotion) => booleanparams: Readonly<Record<string, number | boolean>>+releasePose: (pose: Pose) => voidrootDelta: (motion: AnimatorMotion, span: MotionSpan, out: RootMotionDelta) => booleansample: (motion: AnimatorMotion, time: number, pose: Pose) => booleanworld: World@@ -11068,6 +11070,11 @@ AudioPluginMotionDriver<AnimatorBlend1DMotion>```+## blend1DPair — function @experimental+```+(blend: AnimatorBlend1DMotion, value: number): Readonly<Blend1DPair>+```+## btEdges — function @experimental```(def: BtDefinition): BtEdge[]diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 7cd253edb..e4f80674b 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: 114 public · 94 beta · 1690 experimental · 3 deprecated+Symbols: 114 public · 94 beta · 1691 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -5130,6 +5130,7 @@ shift: boolean## MotionContext — interface @experimental```+borrowPose: () => Posedrive: (motion: AnimatorMotion, enter: boolean) => voidduration: (motion: AnimatorMotion) => numberentity: number@@ -5138,6 +5139,7 @@ extractRootMotion: booleanfinished: (motion: AnimatorMotion) => booleanloops: (motion: AnimatorMotion) => booleanparams: Readonly<Record<string, number | boolean>>+releasePose: (pose: Pose) => voidrootDelta: (motion: AnimatorMotion, span: MotionSpan, out: RootMotionDelta) => booleansample: (motion: AnimatorMotion, time: number, pose: Pose) => booleanworld: World@@ -10842,6 +10844,11 @@ AudioPluginMotionDriver<AnimatorBlend1DMotion>```+## blend1DPair — function @experimental+```+(blend: AnimatorBlend1DMotion, value: number): Readonly<Blend1DPair>+```+## btEdges — function @experimental```(def: BtDefinition): BtEdge[]diff --git a/sdk/src/animation/index.ts b/sdk/src/animation/index.tsindex 7eeb765d8..bf29256ef 100644--- a/sdk/src/animation/index.ts+++ b/sdk/src/animation/index.ts@@ -137,12 +137,14 @@ export {export {MotionRegistry,selectBlendStop,+ blend1DPair,blend1DMotionDriver,isBlend1D,type AnimatorMotion,type AnimatorClipMotion,type AnimatorBlend1DMotion,type AnimatorBlendStop,+ type Blend1DPair,type MotionContext,type MotionDriver,type MotionParams,diff --git a/sdk/src/animation/motion.ts b/sdk/src/animation/motion.tsindex 289443633..1143e2368 100644--- a/sdk/src/animation/motion.ts+++ b/sdk/src/animation/motion.ts@@ -21,7 +21,8 @@import type { Entity, Quat, Vec3 } from '../types';import type { World } from '../ecs/world';-import type { Pose } from './pose';+import { Pose } from './pose';+import { mixPoses, type WeightedPose } from './poseMix';/** Parameter values a graph exposes to its motions (floats and bools). */export type MotionParams = Readonly<Record<string, number | boolean>>;@@ -122,6 +123,13 @@ export interface MotionContext {events(motion: AnimatorMotion, span: MotionSpan, out: MotionEvent[]): void;/** A nested motion's displacement over `span`; false when it states none. */rootDelta(motion: AnimatorMotion, span: MotionSpan, out: RootMotionDelta): boolean;+ /**+ * Borrow scratch for composing nested samples; hand it back with+ * {@link releasePose}. Pooled rather than owned by a driver, because a blend+ * nested inside a blend samples while its parent's scratch is still live.+ */+ borrowPose(): Pose;+ releasePose(pose: Pose): void;/*** Whether the animator is taking this motion's root track as DISPLACEMENT.* A driver that can state a root pose must then leave the root's position and@@ -183,6 +191,10 @@ export interface MotionDriver<M extends AnimatorMotion = AnimatorMotion> {*/export class MotionRegistry {private readonly drivers_ = new Map<string, MotionDriver<never>>();+ /** Scratch poses lent to composite motions. A pool and not one buffer per+ * driver: nesting decides how many are live at once, and only the stack+ * knows that. */+ private readonly posePool_: Pose[] = [];register<M extends AnimatorMotion>(kind: M['kind'], driver: MotionDriver<M>): void {this.drivers_.set(kind, driver as MotionDriver<never>);@@ -230,6 +242,8 @@ export class MotionRegistry {},rootDelta: (motion, span, out) =>this.driverFor(motion)?.rootMotion?.(this.ctx_, motion, span, out) ?? false,+ borrowPose: () => this.posePool_.pop() ?? new Pose(),+ releasePose: (pose) => { this.posePool_.push(pose); },};}@@ -238,21 +252,55 @@ export class MotionRegistry {// =============================================================================/**- * 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.+ * Where a parameter sits among a blend's stops. `upper` is null wherever one stop+ * answers for the whole blend.+ *+ * REUSED — destructure it before anything re-enters this module: a nested blend+ * resolves into the same object while its parent's answer is still being read.*/-export function selectBlendStop(+export interface Blend1DPair {+ lower: AnimatorBlendStop | null;+ upper: AnimatorBlendStop | null;+ /** 0 at `lower`, 1 at `upper`; 0 whenever `upper` is null. */+ t: number;+}++const PAIR: Blend1DPair = { lower: null, upper: null, t: 0 };++/**+ * Divide `value` between the two stops it falls between. Under every threshold+ * the lowest stop answers whole, which is what makes a speed parameter resting+ * at zero play idle rather than nothing.+ */+export function blend1DPair(blend: AnimatorBlend1DMotion, value: number,-): AnimatorBlendStop | null {- let atOrBelow: AnimatorBlendStop | null = null;+): Readonly<Blend1DPair> {+ let lower: AnimatorBlendStop | null = null;+ let upper: 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;- }+ if (stop.value <= value && (lower === null || stop.value > lower.value)) lower = stop;+ if (stop.value > value && (upper === null || stop.value < upper.value)) upper = stop;}- return atOrBelow ?? lowest;+ if (lower === null) { lower = lowest; upper = null; }+ const span = lower !== null && upper !== null ? upper.value - lower.value : 0;+ PAIR.lower = lower;+ PAIR.upper = span > 0 ? upper : null;+ PAIR.t = span > 0 ? (value - lower!.value) / span : 0;+ return PAIR;+}++/**+ * The stop a 1D blend selects for `value`: the greatest threshold at or below it,+ * clamped up to the lowest when the parameter sits under them all. This is what a+ * motion that can only be SWITCHED to gets — a sprite sheet has no meaning+ * halfway between two clips — while one that states values is mixed instead.+ */+export function selectBlendStop(+ blend: AnimatorBlend1DMotion, value: number,+): AnimatorBlendStop | null {+ return blend1DPair(blend, value).lower;}/** The motion a blend is currently selecting, or null when it has no stops. */@@ -262,23 +310,80 @@ function blendSelection(return selectBlendStop(blend, Number(ctx.params[blend.parameter] ?? 0))?.motion ?? null;}+/** The parameter this blend reads, which is a float even when nothing set it. */+function blendValue(ctx: MotionContext, blend: AnimatorBlend1DMotion): number {+ return Number(ctx.params[blend.parameter] ?? 0);+}++/**+ * Filled only once every nested sample has returned, so a blend inside a blend+ * cannot find its parent's operands here. Reused for the same reason {@link PAIR}+ * is: mixing is the steady state of an animated entity, not an event.+ */+const MIX: [WeightedPose, WeightedPose] = [+ { pose: null!, weight: 0 }, { pose: null!, weight: 0 },+];+/**- * 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.+ * A blend states values, so it MIXES: at 0.5 between walk and run the character+ * is half of each, rather than walking until run's threshold is crossed. A+ * motion that can only be switched to still picks ({@link selectBlendStop}) —+ * `apply` is the seam for exactly those, and the two answers differ only there.*/export const blend1DMotionDriver: MotionDriver<AnimatorBlend1DMotion> = {apply(ctx, blend, enter) {const selected = blendSelection(ctx, blend);if (selected) ctx.drive(selected, enter);},+ /**+ * The stops are sampled at the same PHASE, not the same second: a 2s idle and+ * a 0.6s run share a clock only once each is measured against its own length,+ * and without that the faster clip's feet slide. Mixing then goes through the+ * pose mixer a crossfade uses — the weights differ, the operation does not.+ */sample(ctx, blend, time, pose) {- const selected = blendSelection(ctx, blend);- return selected !== null && ctx.sample(selected, time, pose);+ const { lower, upper, t } = blend1DPair(blend, blendValue(ctx, blend));+ if (!lower) return false;+ if (!upper) return ctx.sample(lower.motion, time, pose);++ const da = ctx.duration(lower.motion);+ const db = ctx.duration(upper.motion);+ const whole = da > 0 && db > 0 ? da + (db - da) * t : 0;+ const ta = whole > 0 ? time * (da / whole) : time;+ const tb = whole > 0 ? time * (db / whole) : time;++ const from = ctx.borrowPose();+ const to = ctx.borrowPose();+ try {+ from.reset();+ to.reset();+ const sampledFrom = ctx.sample(lower.motion, ta, from);+ const sampledTo = ctx.sample(upper.motion, tb, to);+ // One end that cannot be sampled leaves the other whole rather than+ // half: a pose is the only thing there is to show, and half of it+ // against the world's own values would read as the blend sinking.+ if (!sampledTo) return sampledFrom && ctx.sample(lower.motion, ta, pose);+ if (!sampledFrom) return ctx.sample(upper.motion, tb, pose);++ MIX[0].pose = from; MIX[0].weight = 1 - t;+ MIX[1].pose = to; MIX[1].weight = t;+ mixPoses(MIX, pose, ctx.world);+ return true;+ } finally {+ ctx.releasePose(to);+ ctx.releasePose(from);+ }},duration(ctx, blend) {- const selected = blendSelection(ctx, blend);- return selected ? ctx.duration(selected) : 0;+ const { lower, upper, t } = blend1DPair(blend, blendValue(ctx, blend));+ if (!lower) return 0;+ const da = ctx.duration(lower.motion);+ if (!upper) return da;+ const db = ctx.duration(upper.motion);+ // A stop that does not state its length cannot be averaged with one that+ // does — the answer would be shorter than the clip actually playing — so+ // the selected stop answers, which is what a sprite blend always got.+ return da > 0 && db > 0 ? da + (db - da) * t : da;},loops(ctx, blend) {const selected = blendSelection(ctx, blend);diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex b2da722ac..100e1d430 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -421,6 +421,7 @@ export {selectBlendClip,motionOf,selectBlendStop,+ blend1DPair,MotionRegistry,blend1DMotionDriver,spriteMotionDriver,diff --git a/sdk/tests/animatorBlendTree.test.ts b/sdk/tests/animatorBlendTree.test.tsnew file mode 100644index 000000000..d960a238d--- /dev/null+++ b/sdk/tests/animatorBlendTree.test.ts@@ -0,0 +1,273 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * The claim: a 1D blend over sampleable motions MIXES its neighbouring stops+ * rather than picking one, at a shared phase rather than a shared second.+ */+import { describe, it, expect } from 'vitest';+import {+ Animator, AnimatorControllerAPI, blend1DPair, selectBlendStop,+ type AnimatorData, type AnimatorControllerDef, type AnimatorBlend1DMotion,+} from '../src/animation';+import { createTimelineMotionDriver, TIMELINE_MOTION } from '../src/timeline';+import { TimelineAPI } from '../src/timeline/TimelineControl';+import { defineComponent } from '../src/ecs/component';+import { WrapMode, TrackType, InterpType, type TimelineAsset } from '../src/timeline/TimelineTypes';++const E = 1;++const probe = () => defineComponent('BlendProbe', { lift: 0 });++function makeWorld() {+ const store = new Map<unknown, Map<number, unknown>>();+ const mapOf = (c: unknown) => {+ let m = store.get(c);+ if (!m) { m = new Map(); store.set(c, m); }+ return m;+ };+ return {+ insert(e: number, c: unknown, d: unknown) { mapOf(c).set(e, d); },+ get(e: number, c: unknown) { return mapOf(c).get(e); },+ has(e: number, c: unknown) { return mapOf(c).has(e); },+ set(e: number, c: unknown, d: unknown) { mapOf(c).set(e, d); },+ tryGet(e: number, c: unknown) { return mapOf(c).get(e) ?? null; },+ update(e: number, c: unknown, edit: (d: any) => void) {+ const d = mapOf(c).get(e);+ edit(d); mapOf(c).set(e, d);+ },+ getEntitiesWithComponents(comps: unknown[]) {+ const [first, ...rest] = comps;+ return [...mapOf(first).keys()].filter(e => rest.every(c => mapOf(c).has(e)));+ },+ } as any;+}++function seedWorld() {+ const world = makeWorld();+ world.insert(E, probe(), { lift: 0 });+ return world;+}++const liftOf = (world: any) => (world.get(E, probe()) as { lift: number }).lift;++/** A clip holding `lift` for `duration` seconds. */+function hold(lift: number, duration: number): TimelineAsset {+ return {+ version: '1.2', type: 'timeline', duration, wrapMode: WrapMode.Loop,+ tracks: [{+ type: TrackType.Property, component: 'BlendProbe', childPath: '', name: 't',+ channels: [{+ property: 'lift',+ keyframes: [{+ time: 0, value: lift, inTangent: 0, outTangent: 0,+ interpolation: InterpType.Linear,+ }],+ }],+ }],+ } as TimelineAsset;+}++/** A clip ramping `lift` from 0 to 100 over its whole length. */+function ramp(duration: number): TimelineAsset {+ const key = (time: number, value: number) => ({+ time, value, inTangent: 0, outTangent: 0, interpolation: InterpType.Linear,+ });+ return {+ version: '1.2', type: 'timeline', duration, wrapMode: WrapMode.Loop,+ tracks: [{+ type: TrackType.Property, component: 'BlendProbe', childPath: '', name: 't',+ channels: [{ property: 'lift', keyframes: [key(0, 0), key(duration, 100)] }],+ }],+ } as TimelineAsset;+}++const clip = (name: string) => ({ kind: TIMELINE_MOTION, clip: name });++/** One state playing `motion`, driven by the float parameters named. */+function controllerOf(+ motion: AnimatorBlend1DMotion,+ assets: Record<string, TimelineAsset>,+ params: string[],+): AnimatorControllerAPI {+ const timeline = new TimelineAPI();+ for (const [name, asset] of Object.entries(assets)) timeline.registerAsset(name, asset);+ const ctrl = new AnimatorControllerAPI();+ ctrl.registerMotionDriver(TIMELINE_MOTION, createTimelineMotionDriver(timeline));++ const def: AnimatorControllerDef = {+ parameters: params.map(name => ({ name, type: 'float' as const, default: 0 })),+ initialState: 'Move',+ states: [{ name: 'Move', motion, transitions: [] }],+ };+ ctrl.registerController('loco', def);+ return ctrl;+}++function attach(world: any): void {+ world.insert(E, Animator, {+ controller: 'loco', currentState: '', enabled: true,+ } as AnimatorData);+}++describe('where a parameter sits among the stops', () => {+ const blend: AnimatorBlend1DMotion = {+ kind: 'blend1d', parameter: 'speed',+ thresholds: [+ { value: 0, motion: clip('idle') },+ { value: 1, motion: clip('walk') },+ { value: 4, motion: clip('run') },+ ],+ };++ it('divides between the two it falls between', () => {+ const { lower, upper, t } = blend1DPair(blend, 2.5);+ expect(lower?.value).toBe(1);+ expect(upper?.value).toBe(4);+ expect(t).toBeCloseTo(0.5, 6);+ });++ it('gives the top stop the whole of it past the last threshold', () => {+ const { lower, upper, t } = blend1DPair(blend, 99);+ expect(lower?.value).toBe(4);+ expect(upper).toBeNull();+ expect(t).toBe(0);+ });++ it('clamps up to the lowest stop under every threshold', () => {+ const under: AnimatorBlend1DMotion = {+ kind: 'blend1d', parameter: 'speed',+ thresholds: [{ value: 2, motion: clip('walk') }, { value: 4, motion: clip('run') }],+ };+ const { lower, upper } = blend1DPair(under, 0);+ expect(lower?.value).toBe(2);+ expect(upper).toBeNull();+ });++ it('is the same answer a switched motion selects', () => {+ // `apply` picks and `sample` mixes, but they must not disagree about+ // WHICH stop is the dominant one, or a sprite blend and a skeletal one+ // read the same parameter differently.+ expect(selectBlendStop(blend, 2.5)).toBe(blend1DPair(blend, 2.5).lower);+ expect(selectBlendStop(blend, 0)?.value).toBe(0);+ });+});++describe('a 1D blend over sampleable motions', () => {+ const twoStops: AnimatorBlend1DMotion = {+ kind: 'blend1d', parameter: 'speed',+ thresholds: [+ { value: 0, motion: clip('idle.estimeline') },+ { value: 1, motion: clip('run.estimeline') },+ ],+ };+ const held = { 'idle.estimeline': hold(0, 10), 'run.estimeline': hold(100, 10) };++ it('is half of each at the midpoint, not the stop below', () => {+ const world = seedWorld();+ const ctrl = controllerOf(twoStops, held, ['speed']);+ attach(world);++ ctrl.setFloat(E, 'speed', 0.5);+ ctrl.update(world, 0.016);++ expect(liftOf(world)).toBeCloseTo(50, 4);+ });++ it('walks the whole way across as the parameter rises', () => {+ const world = seedWorld();+ const ctrl = controllerOf(twoStops, held, ['speed']);+ attach(world);++ for (const [speed, expected] of [[0, 0], [0.25, 25], [0.75, 75], [1, 100]] as const) {+ ctrl.setFloat(E, 'speed', speed);+ ctrl.update(world, 0.016);+ expect(liftOf(world)).toBeCloseTo(expected, 4);+ }+ });++ it('samples both stops at the same phase, not the same second', () => {+ // A 2s and a 1s ramp, half and half: the blend runs 1.5s, so at 0.75s both+ // are at their own halfway point. Sampled at the same second instead, the+ // short clip is three quarters through and drags the answer to 56.25.+ const world = seedWorld();+ const ramps: AnimatorBlend1DMotion = {+ kind: 'blend1d', parameter: 'speed',+ thresholds: [+ { value: 0, motion: clip('slow.estimeline') },+ { value: 1, motion: clip('fast.estimeline') },+ ],+ };+ const ctrl = controllerOf(+ ramps, { 'slow.estimeline': ramp(2), 'fast.estimeline': ramp(1) }, ['speed'],+ );+ attach(world);+ ctrl.setFloat(E, 'speed', 0.5);+ // Entering a state restarts its clock, so the seconds have to be put on+ // a state the entity is already in.+ ctrl.update(world, 0);+ ctrl.update(world, 0.75);++ expect(liftOf(world)).toBeCloseTo(50, 3);+ });++ it('states the blended length, so an exit-time transition waits for it', () => {+ const world = seedWorld();+ const ramps: AnimatorBlend1DMotion = {+ kind: 'blend1d', parameter: 'speed',+ thresholds: [+ { value: 0, motion: clip('slow.estimeline') },+ { value: 1, motion: clip('fast.estimeline') },+ ],+ };+ const ctrl = controllerOf(+ ramps, { 'slow.estimeline': ramp(2), 'fast.estimeline': ramp(1) }, ['speed'],+ );+ attach(world);+ ctrl.setFloat(E, 'speed', 0.5);+ ctrl.update(world, 0.016);++ // Reached through the driver the animator itself asks: 2s and 1s, half+ // and half, is 1.5s — not the 2s of the stop a selection would name.+ const motion = ramps;+ const anyCtrl = ctrl as unknown as {+ motions_: { context(w: unknown, e: number, p: unknown): { duration(m: unknown): number } };+ };+ const ctx = anyCtrl.motions_.context(world, E, { speed: 0.5 });+ expect(ctx.duration(motion)).toBeCloseTo(1.5, 6);+ });+});++describe('a blend nested inside a blend', () => {+ it('keeps its own pair while the inner one resolves', () => {+ // Resolving the inner pair overwrites the shared scratch the outer one+ // just wrote, so an implementation that reads its own answer back+ // afterwards blends the wrong two clips.+ const world = seedWorld();+ const inner = (a: string, b: string): AnimatorBlend1DMotion => ({+ kind: 'blend1d', parameter: 'lean',+ thresholds: [{ value: 0, motion: clip(a) }, { value: 1, motion: clip(b) }],+ });+ const outer: AnimatorBlend1DMotion = {+ kind: 'blend1d', parameter: 'gait',+ thresholds: [+ { value: 0, motion: inner('a.estimeline', 'b.estimeline') },+ { value: 1, motion: inner('c.estimeline', 'd.estimeline') },+ ],+ };+ const ctrl = controllerOf(outer, {+ 'a.estimeline': hold(0, 10), 'b.estimeline': hold(100, 10),+ 'c.estimeline': hold(200, 10), 'd.estimeline': hold(300, 10),+ }, ['gait', 'lean']);+ attach(world);++ // The two parameters differ on purpose: at the same value the inner+ // blend's answer and the outer one's are the same number, and reading+ // one for the other would pass.+ ctrl.setFloat(E, 'gait', 0.25);+ ctrl.setFloat(E, 'lean', 0.75);+ ctrl.update(world, 0.016);++ // Inner low is 75, inner high is 275; a quarter of the way up is 125.+ expect(liftOf(world)).toBeCloseTo(125, 4);+ });+});