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
fix(anim): a blend weights its displacement the way it weights its pose
esenginea99de6d9b2f9
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 3e7eea646..4d930f92a 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -5191,6 +5191,7 @@ shift: boolean## MotionContext — interface @experimental```+borrowDelta: () => RootMotionDeltaborrowMix: () => WeightedPose[]borrowPose: () => Posedrive: (motion: AnimatorMotion, enter: boolean) => void@@ -5201,6 +5202,7 @@ extractRootMotion: booleanfinished: (motion: AnimatorMotion) => booleanloops: (motion: AnimatorMotion) => booleanparams: Readonly<Record<string, number | boolean>>+releaseDelta: (delta: RootMotionDelta) => voidreleaseMix: (mix: WeightedPose[]) => voidreleasePose: (pose: Pose) => voidrootDelta: (motion: AnimatorMotion, span: MotionSpan, out: RootMotionDelta) => booleandiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 6fc41793c..fdacf1eb3 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -5204,6 +5204,7 @@ shift: boolean## MotionContext — interface @experimental```+borrowDelta: () => RootMotionDeltaborrowMix: () => WeightedPose[]borrowPose: () => Posedrive: (motion: AnimatorMotion, enter: boolean) => void@@ -5214,6 +5215,7 @@ extractRootMotion: booleanfinished: (motion: AnimatorMotion) => booleanloops: (motion: AnimatorMotion) => booleanparams: Readonly<Record<string, number | boolean>>+releaseDelta: (delta: RootMotionDelta) => voidreleaseMix: (mix: WeightedPose[]) => voidreleasePose: (pose: Pose) => voidrootDelta: (motion: AnimatorMotion, span: MotionSpan, out: RootMotionDelta) => booleandiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 145ce888c..141c70199 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -5186,6 +5186,7 @@ shift: boolean## MotionContext — interface @experimental```+borrowDelta: () => RootMotionDeltaborrowMix: () => WeightedPose[]borrowPose: () => Posedrive: (motion: AnimatorMotion, enter: boolean) => void@@ -5196,6 +5197,7 @@ extractRootMotion: booleanfinished: (motion: AnimatorMotion) => booleanloops: (motion: AnimatorMotion) => booleanparams: Readonly<Record<string, number | boolean>>+releaseDelta: (delta: RootMotionDelta) => voidreleaseMix: (mix: WeightedPose[]) => voidreleasePose: (pose: Pose) => voidrootDelta: (motion: AnimatorMotion, span: MotionSpan, out: RootMotionDelta) => booleandiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex d8d405a25..e93ff3dc1 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -5434,6 +5434,7 @@ shift: boolean## MotionContext — interface @experimental```+borrowDelta: () => RootMotionDeltaborrowMix: () => WeightedPose[]borrowPose: () => Posedrive: (motion: AnimatorMotion, enter: boolean) => void@@ -5444,6 +5445,7 @@ extractRootMotion: booleanfinished: (motion: AnimatorMotion) => booleanloops: (motion: AnimatorMotion) => booleanparams: Readonly<Record<string, number | boolean>>+releaseDelta: (delta: RootMotionDelta) => voidreleaseMix: (mix: WeightedPose[]) => voidreleasePose: (pose: Pose) => voidrootDelta: (motion: AnimatorMotion, span: MotionSpan, out: RootMotionDelta) => booleandiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 6efa46bfc..e7a0fcf38 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -5193,6 +5193,7 @@ shift: boolean## MotionContext — interface @experimental```+borrowDelta: () => RootMotionDeltaborrowMix: () => WeightedPose[]borrowPose: () => Posedrive: (motion: AnimatorMotion, enter: boolean) => void@@ -5203,6 +5204,7 @@ extractRootMotion: booleanfinished: (motion: AnimatorMotion) => booleanloops: (motion: AnimatorMotion) => booleanparams: Readonly<Record<string, number | boolean>>+releaseDelta: (delta: RootMotionDelta) => voidreleaseMix: (mix: WeightedPose[]) => voidreleasePose: (pose: Pose) => voidrootDelta: (motion: AnimatorMotion, span: MotionSpan, out: RootMotionDelta) => booleandiff --git a/sdk/src/animation/Animator.ts b/sdk/src/animation/Animator.tsindex 667f339d2..633d5f439 100644--- a/sdk/src/animation/Animator.ts+++ b/sdk/src/animation/Animator.ts@@ -29,7 +29,7 @@ import {} from './motion';import { SPRITE_MOTION, spriteMotionDriver } from './spriteMotion';import { Pose } from './pose';-import { mixPoses } from './poseMix';+import { mixPoses, type WeightedPose } from './poseMix';import { overlayPose, addPoseOver } from './layerStack';import { MaskReach, type AnimatorMask } from './animatorMask';import { AnimatorRootMotion, type AnimatorRootMotionData } from './animatorRootMotion';@@ -966,10 +966,9 @@ export class AnimatorControllerAPI {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.fade[0].pose = rt.poseFrom; rt.fade[0].weight = 1 - t;+ rt.fade[1].pose = rt.poseTo; rt.fade[1].weight = t;+ mixPoses(rt.fade, rt.mixed, world, 2);return rt.mixed;}rt.fadeFrom = null;@@ -1011,6 +1010,7 @@ export class AnimatorControllerAPI {fadeFrom: null, fadeFromRoot: false,fadeFromTime: 0, fadeElapsed: 0, fadeDuration: 0,poseFrom: new Pose(), poseTo: new Pose(), mixed: new Pose(),+ fade: [{ pose: null!, weight: 0 }, { pose: null!, weight: 0 }],});}return rt;@@ -1063,6 +1063,10 @@ interface LayerRuntime {poseFrom: Pose;poseTo: Pose;mixed: Pose;+ /** The two-slot list a crossfade mixes from. Owned rather than borrowed: a+ * layer fades once per frame and never inside itself, which is exactly the+ * case the pools exist for and this is not. */+ fade: [WeightedPose, WeightedPose];/** This layer's mask, resolved against the rig it is running on. */reach?: MaskReach;}diff --git a/sdk/src/animation/layerStack.ts b/sdk/src/animation/layerStack.tsindex b3363b1ef..8d1a2c200 100644--- a/sdk/src/animation/layerStack.ts+++ b/sdk/src/animation/layerStack.ts@@ -19,60 +19,32 @@*/import type { Pose, PoseTrack, PoseWorld } from './pose';--interface Quat { w: number; x: number; y: number; z: number }--function isQuat(v: unknown): v is Quat {- if (v === null || typeof v !== 'object') return false;- const o = v as Record<string, unknown>;- return typeof o.w === 'number' && typeof o.x === 'number'- && typeof o.y === 'number' && typeof o.z === 'number';-}+import {+ deltaQuat, isQuatLike as isQuat, leanQuat, turnByQuat, type QuatLike as Quat,+} from './quatMix';function isNumericObject(v: unknown): v is Record<string, number> {if (v === null || typeof v !== 'object' || Array.isArray(v)) return false;const keys = Object.keys(v as object);- return keys.length > 0 && keys.every(k => typeof (v as Record<string, unknown>)[k] === 'number');+ if (keys.length === 0) return false;+ return keys.every(k => typeof (v as Record<string, unknown>)[k] === 'number');}-function normalize(q: Quat): void {- const len = Math.hypot(q.w, q.x, q.y, q.z);- if (len <= 0) { q.w = 1; q.x = 0; q.y = 0; q.z = 0; return; }- q.w /= len; q.x /= len; q.y /= len; q.z /= len;-}+/** Scratch for one additive field; this runs on one track at a time and does+ * not re-enter. */+const DELTA: Quat = { w: 1, x: 0, y: 0, z: 0 };+const PART: Quat = { w: 1, x: 0, y: 0, z: 0 };/**- * Move `dst` a `weight` share of the way to `src`. Aligned to the near hemisphere- * first: {q} and {-q} name the same rotation, and averaged as written they cancel- * toward the long way round.+ * `dst` turned further by the rotation `from` → `to`, a `weight` share of it.+ * Leaning the identity toward the delta is what SCALES a rotation, there being+ * nothing to scale linearly; the turn is then applied on top.*/-function leanQuat(dst: Quat, src: Quat, weight: number): void {- const dot = dst.w * src.w + dst.x * src.x + dst.y * src.y + dst.z * src.z;- const s = dot < 0 ? -weight : weight;- const keep = 1 - weight;- dst.w = dst.w * keep + src.w * s;- dst.x = dst.x * keep + src.x * s;- dst.y = dst.y * keep + src.y * s;- dst.z = dst.z * keep + src.z * s;- normalize(dst);-}--/** `dst` turned further by the rotation `from` → `to`, a `weight` share of it. */function turnQuat(dst: Quat, from: Quat, to: Quat, weight: number): void {- // The delta is `to * from⁻¹` in the clip's own frame; leaning the identity- // toward it is what scales a rotation, there being nothing to scale linearly.- const dw = to.w * from.w + to.x * from.x + to.y * from.y + to.z * from.z;- const dx = to.x * from.w - to.w * from.x - to.y * from.z + to.z * from.y;- const dy = to.y * from.w - to.w * from.y - to.z * from.x + to.x * from.z;- const dz = to.z * from.w - to.w * from.z - to.x * from.y + to.y * from.x;- const part: Quat = { w: 1, x: 0, y: 0, z: 0 };- leanQuat(part, { w: dw, x: dx, y: dy, z: dz }, weight);- const w = part.w * dst.w - part.x * dst.x - part.y * dst.y - part.z * dst.z;- const x = part.w * dst.x + part.x * dst.w + part.y * dst.z - part.z * dst.y;- const y = part.w * dst.y - part.x * dst.z + part.y * dst.w + part.z * dst.x;- const z = part.w * dst.z + part.x * dst.y - part.y * dst.x + part.z * dst.w;- dst.w = w; dst.x = x; dst.y = y; dst.z = z;- normalize(dst);+ deltaQuat(DELTA, from, to);+ PART.w = 1; PART.x = 0; PART.y = 0; PART.z = 0;+ leanQuat(PART, DELTA, weight);+ turnByQuat(dst, PART);}/** Which tracks of `layer` this stack lets through; null admits every one. */diff --git a/sdk/src/animation/motion.ts b/sdk/src/animation/motion.tsindex de516f88c..dc672adc3 100644--- a/sdk/src/animation/motion.ts+++ b/sdk/src/animation/motion.ts@@ -23,6 +23,7 @@ import type { Entity, Quat, Vec3 } from '../types';import type { World } from '../ecs/world';import { Pose } from './pose';import { mixPoses, type WeightedPose } from './poseMix';+import { accumulateQuat, leanQuat, normalizeQuat } from './quatMix';/** Parameter values a graph exposes to its motions (floats and bools). */export type MotionParams = Readonly<Record<string, number | boolean>>;@@ -160,6 +161,9 @@ export interface MotionContext {*/borrowMix(): WeightedPose[];releaseMix(mix: WeightedPose[]): void;+ /** Borrow a displacement to combine nested ones into; hand it back. */+ borrowDelta(): RootMotionDelta;+ releaseDelta(delta: RootMotionDelta): 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@@ -225,6 +229,7 @@ export class MotionRegistry {* nesting decides how many are live at once, and only the stack knows that. */private readonly posePool_: Pose[] = [];private readonly mixPool_: WeightedPose[][] = [];+ private readonly deltaPool_: RootMotionDelta[] = [];register<M extends AnimatorMotion>(kind: M['kind'], driver: MotionDriver<M>): void {this.drivers_.set(kind, driver as MotionDriver<never>);@@ -276,6 +281,10 @@ export class MotionRegistry {releasePose: (pose) => { this.posePool_.push(pose); },borrowMix: () => this.mixPool_.pop() ?? [],releaseMix: (mix) => { this.mixPool_.push(mix); },+ borrowDelta: () => this.deltaPool_.pop() ?? {+ position: { x: 0, y: 0, z: 0 }, rotation: { w: 1, x: 0, y: 0, z: 0 },+ },+ releaseDelta: (delta) => { this.deltaPool_.push(delta); },};}@@ -433,12 +442,73 @@ export const blend1DMotionDriver: MotionDriver<AnimatorBlend1DMotion> = {const selected = blendSelection(ctx, blend);if (selected) ctx.events(selected, span, out);},+ /**+ * Weighted like the pose. Picking makes a character crossing run's threshold+ * jump its speed in one frame, the one thing a locomotion tree prevents. A+ * stop stating no displacement does not push the character, so the other end+ * keeps only its share rather than answering whole.+ */rootMotion(ctx, blend, span, out) {- const selected = blendSelection(ctx, blend);- return selected !== null && ctx.rootDelta(selected, span, out);+ const { lower, upper, t } = blend1DPair(blend, blendValue(ctx, blend));+ if (!lower) return false;+ if (!upper) return ctx.rootDelta(lower.motion, span, out);++ const other = ctx.borrowDelta();+ try {+ const from = ctx.rootDelta(lower.motion, span, out);+ const to = ctx.rootDelta(upper.motion, span, other);+ if (from && to) { leanDelta(out, other, t); return true; }+ if (from) { scaleDelta(out, 1 - t); return true; }+ if (to) { copyDelta(out, other); scaleDelta(out, t); return true; }+ return false;+ } finally {+ ctx.releaseDelta(other);+ }},};+/** Displacement arithmetic. A rotation is not scaled linearly, so a share of one+ * is the identity leaned toward it — the same rule the layer stack uses. */+function scaleDelta(out: RootMotionDelta, weight: number): void {+ out.position.x *= weight; out.position.y *= weight; out.position.z *= weight;+ IDENTITY_TURN.w = 1; IDENTITY_TURN.x = 0; IDENTITY_TURN.y = 0; IDENTITY_TURN.z = 0;+ leanQuat(IDENTITY_TURN, out.rotation, weight);+ out.rotation.w = IDENTITY_TURN.w; out.rotation.x = IDENTITY_TURN.x;+ out.rotation.y = IDENTITY_TURN.y; out.rotation.z = IDENTITY_TURN.z;+}++function copyDelta(out: RootMotionDelta, src: RootMotionDelta): void {+ out.position.x = src.position.x; out.position.y = src.position.y; out.position.z = src.position.z;+ out.rotation.w = src.rotation.w; out.rotation.x = src.rotation.x;+ out.rotation.y = src.rotation.y; out.rotation.z = src.rotation.z;+}++function zeroDelta(out: RootMotionDelta): void {+ out.position.x = 0; out.position.y = 0; out.position.z = 0;+ out.rotation.w = 0; out.rotation.x = 0; out.rotation.y = 0; out.rotation.z = 0;+}++/** Move `out` a `weight` share of the way to `src`. */+function leanDelta(out: RootMotionDelta, src: RootMotionDelta, weight: number): void {+ out.position.x += (src.position.x - out.position.x) * weight;+ out.position.y += (src.position.y - out.position.y) * weight;+ out.position.z += (src.position.z - out.position.z) * weight;+ leanQuat(out.rotation, src.rotation, weight);+}++/** Accumulate `src * weight` into a zeroed `out`; the caller normalizes at the end. */+function addDelta(out: RootMotionDelta, src: RootMotionDelta, weight: number): void {+ out.position.x += src.position.x * weight;+ out.position.y += src.position.y * weight;+ out.position.z += src.position.z * weight;+ accumulateQuat(out.rotation, HEMISPHERE, src.rotation, weight);+}++const IDENTITY_TURN = { w: 1, x: 0, y: 0, z: 0 };+/** Every contribution aligns to the identity, which is the rotation a motion+ * stating no turn already has — so the reference is never absent. */+const HEMISPHERE = { w: 1, x: 0, y: 0, z: 0 };+// =============================================================================// 2D blend — the same mixing, over a plane instead of a line// =============================================================================@@ -611,7 +681,28 @@ export const blend2DMotionDriver: MotionDriver<AnimatorBlend2DMotion> = {if (dominant) ctx.events(dominant, span, out);},rootMotion(ctx, blend, span, out) {- const dominant = dominantOf(ctx, blend);- return dominant !== null && ctx.rootDelta(dominant, span, out);+ const points = blend.points;+ if (points.length === 0) return false;+ const mix = ctx.borrowMix();+ const part = ctx.borrowDelta();+ try {+ mixCapacity(mix, points.length);+ const { x, y } = blend2DAt(ctx, blend);+ blend2DWeights(blend, x, y, mix);+ zeroDelta(out);+ let stated = false;+ for (let i = 0; i < points.length; i++) {+ const weight = mix[i]!.weight;+ if (weight <= 0) continue;+ if (!ctx.rootDelta(points[i]!.motion, span, part)) continue;+ addDelta(out, part, weight);+ stated = true;+ }+ if (stated) normalizeQuat(out.rotation);+ return stated;+ } finally {+ ctx.releaseDelta(part);+ ctx.releaseMix(mix);+ }},};diff --git a/sdk/src/animation/poseMix.ts b/sdk/src/animation/poseMix.tsindex 66c3ddda4..b84d40d14 100644--- a/sdk/src/animation/poseMix.ts+++ b/sdk/src/animation/poseMix.ts@@ -17,6 +17,10 @@*/import type { Pose, PoseTrack, PoseWorld } from './pose';+import {+ accumulateQuat, canonicalizeQuat, isQuatLike as isQuat, normalizeQuat,+ type QuatLike as Quat,+} from './quatMix';/** A pose and how much of it the result is made of. */export interface WeightedPose {@@ -24,15 +28,6 @@ export interface WeightedPose {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);@@ -40,42 +35,6 @@ function isNumericObject(v: unknown): v is Record<string, number> {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;@@ -95,7 +54,7 @@ function mixQuaternionField(field: string, parts: Contribution[], into: Record<s}if (ref === null) return;normalizeQuat(acc);- canonicalize(acc);+ canonicalizeQuat(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.diff --git a/sdk/src/animation/quatMix.ts b/sdk/src/animation/quatMix.tsnew file mode 100644index 000000000..4c52b110b--- /dev/null+++ b/sdk/src/animation/quatMix.ts@@ -0,0 +1,87 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file quatMix.ts+ * @brief Averaging rotations, for everything in the animator that averages one.+ *+ * @details {q} and {-q} name the same rotation, so a naive average of two that+ * are written a turn apart cancels toward the long way round instead of+ * meeting them halfway. Every consumer here has to align hemispheres+ * first, and three of them had written that out separately — the pose+ * mixer, the layer stack and a blend's displacement. The rule is easy to+ * get subtly right in one place and subtly wrong in the next, which is+ * the kind of thing that belongs in one.+ */++export interface QuatLike { w: number; x: number; y: number; z: number }++export function isQuatLike(v: unknown): v is QuatLike {+ 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';+}++export function normalizeQuat(out: QuatLike): 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 representative of the pair {q, -q}. Applied to a RESULT this is what makes+ * a mix order-independent: aligning b to a or a to b differs only in overall+ * sign, and collapsing that leaves one answer.+ */+export function canonicalizeQuat(out: QuatLike): 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. */+export function accumulateQuat(+ acc: QuatLike, ref: QuatLike, q: QuatLike, 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;+}++/** Move `dst` a `weight` share of the way to `src`, the short way round. */+export function leanQuat(dst: QuatLike, src: QuatLike, weight: number): void {+ const dot = dst.w * src.w + dst.x * src.x + dst.y * src.y + dst.z * src.z;+ const s = dot < 0 ? -weight : weight;+ const keep = 1 - weight;+ dst.w = dst.w * keep + src.w * s;+ dst.x = dst.x * keep + src.x * s;+ dst.y = dst.y * keep + src.y * s;+ dst.z = dst.z * keep + src.z * s;+ normalizeQuat(dst);+}++/** `to` relative to `from`, written into `out` — the turn one states over the other. */+export function deltaQuat(out: QuatLike, from: QuatLike, to: QuatLike): void {+ out.w = to.w * from.w + to.x * from.x + to.y * from.y + to.z * from.z;+ out.x = to.x * from.w - to.w * from.x - to.y * from.z + to.z * from.y;+ out.y = to.y * from.w - to.w * from.y - to.z * from.x + to.x * from.z;+ out.z = to.z * from.w - to.w * from.z - to.x * from.y + to.y * from.x;+}++/** `dst = by * dst`, turning `dst` further by `by`. */+export function turnByQuat(dst: QuatLike, by: QuatLike): void {+ const w = by.w * dst.w - by.x * dst.x - by.y * dst.y - by.z * dst.z;+ const x = by.w * dst.x + by.x * dst.w + by.y * dst.z - by.z * dst.y;+ const y = by.w * dst.y - by.x * dst.z + by.y * dst.w + by.z * dst.x;+ const z = by.w * dst.z + by.x * dst.y - by.y * dst.x + by.z * dst.w;+ dst.w = w; dst.x = x; dst.y = y; dst.z = z;+ normalizeQuat(dst);+}diff --git a/sdk/tests/animatorBlendTree.test.ts b/sdk/tests/animatorBlendTree.test.tsindex 6d7d5ecfa..f27c07681 100644--- a/sdk/tests/animatorBlendTree.test.ts+++ b/sdk/tests/animatorBlendTree.test.ts@@ -14,7 +14,7 @@ import {} from '../src/animation';import { createTimelineMotionDriver, TIMELINE_MOTION } from '../src/timeline';import { TimelineAPI } from '../src/timeline/TimelineControl';-import { defineComponent } from '../src/ecs/component';+import { defineComponent, Transform } from '../src/ecs/component';import { WrapMode, TrackType, InterpType, type TimelineAsset } from '../src/timeline/TimelineTypes';const E = 1;@@ -417,3 +417,76 @@ describe('a 2D blend through the animator', () => {expect(liftOf(world)).toBeCloseTo(125, 4);});});++// ---------------------------------------------------------------------------+// Displacement follows the same weights the pose does+// ---------------------------------------------------------------------------++/** A clip that walks `metres` along +Z over its whole length, as root motion. */+function travel(metres: number): TimelineAsset {+ const key = (time: number, value: number) => ({+ time, value, inTangent: 0, outTangent: 0, interpolation: InterpType.Linear,+ });+ return {+ version: '1.2', type: 'timeline', duration: 1, wrapMode: WrapMode.Loop,+ tracks: [{+ type: TrackType.Property, component: 'Transform', childPath: '', name: 'root',+ channels: [{ property: 'position.z', keyframes: [key(0, 0), key(1, metres)] }],+ }],+ } as TimelineAsset;+}++describe('a blend’s displacement', () => {+ const locomotion: AnimatorBlend1DMotion = {+ kind: 'blend1d', parameter: 'speed',+ thresholds: [+ { value: 0, motion: clip('walk.estimeline') },+ { value: 1, motion: clip('run.estimeline') },+ ],+ };++ /** How far the blend asks to move over one whole second at `speed`. */+ function asked(speed: number): number {+ const world = seedWorld();+ world.insert(E, Transform, {+ position: { x: 0, y: 0, z: 0 }, rotation: { w: 1, x: 0, y: 0, z: 0 },+ scale: { x: 1, y: 1, z: 1 },+ });++ const timeline = new TimelineAPI();+ timeline.registerAsset('walk.estimeline', travel(100));+ timeline.registerAsset('run.estimeline', travel(400));+ const ctrl = new AnimatorControllerAPI();+ ctrl.registerMotionDriver(TIMELINE_MOTION, createTimelineMotionDriver(timeline));++ const anyCtrl = ctrl as unknown as {+ motions_: {+ context(w: unknown, e: number, p: unknown): {+ rootDelta(m: unknown, s: unknown, o: { position: { z: number } }): boolean;+ };+ };+ };+ const ctx = anyCtrl.motions_.context(world, E, { speed });+ const out = { position: { x: 0, y: 0, z: 0 }, rotation: { w: 1, x: 0, y: 0, z: 0 } };+ const stated = ctx.rootDelta(locomotion, { from: 0, to: 1, inclusiveStart: true }, out);+ return stated ? out.position.z : NaN;+ }++ it('is weighted, not picked', () => {+ // Picking makes a character crossing run's threshold jump from 100 to 400+ // in one frame — the one thing a locomotion tree exists to prevent.+ expect(asked(0)).toBeCloseTo(100, 3);+ expect(asked(1)).toBeCloseTo(400, 3);+ expect(asked(0.5)).toBeCloseTo(250, 3);+ expect(asked(0.25)).toBeCloseTo(175, 3);+ });++ it('climbs without a step anywhere across the range', () => {+ let previous = asked(0);+ for (let speed = 0.05; speed <= 1.0001; speed += 0.05) {+ const here = asked(speed);+ expect(here - previous).toBeCloseTo(15, 3);+ previous = here;+ }+ });+});