Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(anim): the posed skeleton can be made to reach something

esengine730e735a6d07
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index e0141692a..54ea4d2b6 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 114,
"beta": 101,
- "experimental": 1867,
+ "experimental": 1870,
"deprecated": 3
},
- "total": 2082,
+ "total": 2085,
"subsystems": [
{
"id": "ecs",
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index ac3d31478..786045e67 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 · 1706 experimental · 3 deprecated
+Symbols: 114 public · 94 beta · 1709 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -487,6 +487,7 @@ static prototype: AnimatorControllerAPI
## AnimatorControllerDef — interface @experimental
```
anyStateTransitions: AnimatorTransition[] | undefined
+ik: AnimatorIK[] | undefined
initialState: string
layers: AnimatorLayer[] | undefined
parameters: AnimatorParam[]
@@ -535,6 +536,22 @@ value: number
send: (event: AnimatorEventPayload) => void
```
+## AnimatorIK — interface @experimental
+```
+axis: "x" | "y" | "z" | undefined
+kind: AnimatorIKKind
+parameter: string | undefined
+pole: string | undefined
+target: string
+tip: string
+weight: number | undefined
+```
+
+## AnimatorIKKind — type @experimental
+```
+'two-bone' | 'look-at'
+```
+
## AnimatorLayer — interface @experimental
```
anyStateTransitions: AnimatorTransition[] | undefined
@@ -13653,6 +13670,11 @@ ServicesPlugin
(raw: number): TileStamp
```
+## solveAnimatorIK — function @experimental
+```
+(world: World, rigRoot: Entity, pose: Pose, constraints: readonly AnimatorIK[], params: MotionParams): void
+```
+
## spatialDistance — function @experimental
```
(source: Vec3, listener: Vec3): number
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 84e388d97..c8e155c5a 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 · 1725 experimental · 3 deprecated
+Symbols: 114 public · 99 beta · 1728 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -487,6 +487,7 @@ static prototype: AnimatorControllerAPI
## AnimatorControllerDef — interface @experimental
```
anyStateTransitions: AnimatorTransition[] | undefined
+ik: AnimatorIK[] | undefined
initialState: string
layers: AnimatorLayer[] | undefined
parameters: AnimatorParam[]
@@ -535,6 +536,22 @@ value: number
send: (event: AnimatorEventPayload) => void
```
+## AnimatorIK — interface @experimental
+```
+axis: "x" | "y" | "z" | undefined
+kind: AnimatorIKKind
+parameter: string | undefined
+pole: string | undefined
+target: string
+tip: string
+weight: number | undefined
+```
+
+## AnimatorIKKind — type @experimental
+```
+'two-bone' | 'look-at'
+```
+
## AnimatorLayer — interface @experimental
```
anyStateTransitions: AnimatorTransition[] | undefined
@@ -13896,6 +13913,11 @@ ServicesPlugin
(raw: number): TileStamp
```
+## solveAnimatorIK — function @experimental
+```
+(world: World, rigRoot: Entity, pose: Pose, constraints: readonly AnimatorIK[], params: MotionParams): void
+```
+
## spatialDistance — function @experimental
```
(source: Vec3, listener: Vec3): number
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 581a6b862..f0646996d 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 · 1705 experimental · 3 deprecated
+Symbols: 114 public · 96 beta · 1708 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -482,6 +482,7 @@ static prototype: AnimatorControllerAPI
## AnimatorControllerDef — interface @experimental
```
anyStateTransitions: AnimatorTransition[] | undefined
+ik: AnimatorIK[] | undefined
initialState: string
layers: AnimatorLayer[] | undefined
parameters: AnimatorParam[]
@@ -530,6 +531,22 @@ value: number
send: (event: AnimatorEventPayload) => void
```
+## AnimatorIK — interface @experimental
+```
+axis: "x" | "y" | "z" | undefined
+kind: AnimatorIKKind
+parameter: string | undefined
+pole: string | undefined
+target: string
+tip: string
+weight: number | undefined
+```
+
+## AnimatorIKKind — type @experimental
+```
+'two-bone' | 'look-at'
+```
+
## AnimatorLayer — interface @experimental
```
anyStateTransitions: AnimatorTransition[] | undefined
@@ -13658,6 +13675,11 @@ ServicesPlugin
(raw: number): TileStamp
```
+## solveAnimatorIK — function @experimental
+```
+(world: World, rigRoot: Entity, pose: Pose, constraints: readonly AnimatorIK[], params: MotionParams): void
+```
+
## spatialDistance — function @experimental
```
(source: Vec3, listener: Vec3): number
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 6b3972f58..19db19dc0 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 · 1727 experimental · 3 deprecated
+Symbols: 114 public · 94 beta · 1730 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -482,6 +482,7 @@ static prototype: AnimatorControllerAPI
## AnimatorControllerDef — interface @experimental
```
anyStateTransitions: AnimatorTransition[] | undefined
+ik: AnimatorIK[] | undefined
initialState: string
layers: AnimatorLayer[] | undefined
parameters: AnimatorParam[]
@@ -530,6 +531,22 @@ value: number
send: (event: AnimatorEventPayload) => void
```
+## AnimatorIK — interface @experimental
+```
+axis: "x" | "y" | "z" | undefined
+kind: AnimatorIKKind
+parameter: string | undefined
+pole: string | undefined
+target: string
+tip: string
+weight: number | undefined
+```
+
+## AnimatorIKKind — type @experimental
+```
+'two-bone' | 'look-at'
+```
+
## AnimatorLayer — interface @experimental
```
anyStateTransitions: AnimatorTransition[] | undefined
@@ -13917,6 +13934,11 @@ ServicesPlugin
(raw: number): TileStamp
```
+## solveAnimatorIK — function @experimental
+```
+(world: World, rigRoot: Entity, pose: Pose, constraints: readonly AnimatorIK[], params: MotionParams): void
+```
+
## spatialDistance — function @experimental
```
(source: Vec3, listener: Vec3): number
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index e8eac65df..094c0afad 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 · 1717 experimental · 3 deprecated
+Symbols: 114 public · 94 beta · 1720 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -482,6 +482,7 @@ static prototype: AnimatorControllerAPI
## AnimatorControllerDef — interface @experimental
```
anyStateTransitions: AnimatorTransition[] | undefined
+ik: AnimatorIK[] | undefined
initialState: string
layers: AnimatorLayer[] | undefined
parameters: AnimatorParam[]
@@ -530,6 +531,22 @@ value: number
send: (event: AnimatorEventPayload) => void
```
+## AnimatorIK — interface @experimental
+```
+axis: "x" | "y" | "z" | undefined
+kind: AnimatorIKKind
+parameter: string | undefined
+pole: string | undefined
+target: string
+tip: string
+weight: number | undefined
+```
+
+## AnimatorIKKind — type @experimental
+```
+'two-bone' | 'look-at'
+```
+
## AnimatorLayer — interface @experimental
```
anyStateTransitions: AnimatorTransition[] | undefined
@@ -13681,6 +13698,11 @@ ServicesPlugin
(raw: number): TileStamp
```
+## solveAnimatorIK — function @experimental
+```
+(world: World, rigRoot: Entity, pose: Pose, constraints: readonly AnimatorIK[], params: MotionParams): void
+```
+
## spatialDistance — function @experimental
```
(source: Vec3, listener: Vec3): number
diff --git a/sdk/src/animation/Animator.ts b/sdk/src/animation/Animator.ts
index 633d5f439..214eb10e2 100644
--- a/sdk/src/animation/Animator.ts
+++ b/sdk/src/animation/Animator.ts
@@ -32,6 +32,7 @@ import { Pose } from './pose';
import { mixPoses, type WeightedPose } from './poseMix';
import { overlayPose, addPoseOver } from './layerStack';
import { MaskReach, type AnimatorMask } from './animatorMask';
+import { solveAnimatorIK, type AnimatorIK } from './animatorIK';
import { AnimatorRootMotion, type AnimatorRootMotionData } from './animatorRootMotion';
import type { AnimatorEventSink } from './animatorEvent';
import { Transform, type TransformData } from '../ecs/component';
@@ -190,6 +191,12 @@ export interface AnimatorControllerDef {
anyStateTransitions?: AnimatorTransition[];
/** Layers over the base one, laid down in order. */
layers?: AnimatorLayer[];
+ /**
+ * Constraints applied to the stack's answer, in order. Not per layer: a layer
+ * answers who is speaking, and a foot belongs on the ground whichever one
+ * decided how the leg swings.
+ */
+ ik?: AnimatorIK[];
}
/**
@@ -731,6 +738,12 @@ export class AnimatorControllerAPI {
// machines answer cannot depend on which was stepped first.
const triggers = this.triggers.get(entity);
if (triggers) for (const t of this.spentTriggers_) triggers.delete(t);
+ // Constraints read the stack's answer and bend it, so they run
+ // between composing and writing — on the pose this frame stated,
+ // never on the world's record of the last one.
+ if (wrote && def.ik?.length) {
+ solveAnimatorIK(world, entity, rt.composed, def.ik, params);
+ }
// One write for the whole stack: a layer states values, and what the
// entity ends up as is the stack's answer, not the topmost writer's.
if (wrote) rt.composed.applyTo(world);
diff --git a/sdk/src/animation/animatorIK.ts b/sdk/src/animation/animatorIK.ts
new file mode 100644
index 000000000..806c8d9a9
--- /dev/null
+++ b/sdk/src/animation/animatorIK.ts
@@ -0,0 +1,328 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file animatorIK.ts
+ * @brief Bending the posed skeleton to reach something the clips did not know about.
+ *
+ * @details Three decisions shape this.
+ *
+ * IK belongs to the CONTROLLER, not to a layer. A layer answers "who is
+ * speaking"; IK is the constraint reality puts on what was said — a foot
+ * belongs on the ground whichever layer decided how the leg swings — so
+ * it runs once, on the stack's answer, rather than once per layer.
+ *
+ * It solves in the RIG's own space, reading the pose this frame just
+ * stated. `Transform.worldPosition` is last frame's, computed before the
+ * animator wrote anything, so a solver reading it plants the foot against
+ * a character that has already moved on.
+ *
+ * The chain is derived from the tip. A two-bone solve is BY DEFINITION
+ * the tip and the two joints above it, so naming three would be three
+ * chances to name them inconsistently.
+ */
+
+import type { Entity } from '../types';
+import type { World } from '../ecs/world';
+import { Parent, Transform, type TransformData } from '../ecs/component';
+import { resolveChildEntity } from '../ecs/childPath';
+import { q } from '../math/quat';
+import { leanQuat } from './quatMix';
+import type { Pose } from './pose';
+import type { MotionParams } from './motion';
+
+/** What an IK constraint does to the joint it names. */
+export type AnimatorIKKind = 'two-bone' | 'look-at';
+
+export interface AnimatorIK {
+ kind: AnimatorIKKind;
+ /** The joint the chain ends at, by the childPath a clip names it with. */
+ tip: string;
+ /** What it should reach, or look at, named the same way. */
+ target: string;
+ /** 0 leaves the pose alone, 1 puts the tip on the target. */
+ weight?: number;
+ /** A float parameter scaling `weight` — how a game fades a constraint in. */
+ parameter?: string;
+ /** two-bone: a joint the middle one bends towards. Absent keeps its own bend. */
+ pole?: string;
+ /** look-at: the tip's own axis that ends up pointing at the target. */
+ axis?: 'x' | 'y' | 'z';
+}
+
+interface Vec3 { x: number; y: number; z: number }
+interface Quat { w: number; x: number; y: number; z: number }
+
+/** A joint placed in the rig's space, with the parent rotation that put it there. */
+interface Placed {
+ position: Vec3;
+ rotation: Quat;
+ parentRotation: Quat;
+}
+
+const AXIS: Record<'x' | 'y' | 'z', Vec3> = {
+ x: { x: 1, y: 0, z: 0 }, y: { x: 0, y: 1, z: 0 }, z: { x: 0, y: 0, z: 1 },
+};
+
+const sub = (a: Vec3, b: Vec3): Vec3 => ({ x: a.x - b.x, y: a.y - b.y, z: a.z - b.z });
+const add = (a: Vec3, b: Vec3): Vec3 => ({ x: a.x + b.x, y: a.y + b.y, z: a.z + b.z });
+const len = (v: Vec3): number => Math.hypot(v.x, v.y, v.z);
+const cross = (a: Vec3, b: Vec3): Vec3 => ({
+ x: a.y * b.z - a.z * b.y, y: a.z * b.x - a.x * b.z, z: a.x * b.y - a.y * b.x,
+});
+const dot = (a: Vec3, b: Vec3): number => a.x * b.x + a.y * b.y + a.z * b.z;
+
+function axisAngle(axis: Vec3, radians: number): Quat {
+ const l = len(axis);
+ if (l < 1e-9 || !Number.isFinite(radians)) return { w: 1, x: 0, y: 0, z: 0 };
+ const h = radians / 2;
+ const s = Math.sin(h) / l;
+ return { w: Math.cos(h), x: axis.x * s, y: axis.y * s, z: axis.z * s };
+}
+
+/** Any direction perpendicular to `v`. Seeded off the component `v` leans on
+ * LEAST, so the cross never collapses. */
+function perpendicular(v: Vec3): Vec3 {
+ const seed = Math.abs(v.x) < Math.abs(v.y) && Math.abs(v.x) < Math.abs(v.z)
+ ? AXIS.x
+ : (Math.abs(v.y) < Math.abs(v.z) ? AXIS.y : AXIS.z);
+ return cross(v, seed);
+}
+
+/**
+ * The first candidate that can actually bend `bone`. A hinge PARALLEL to the bone
+ * turns it not at all, so a straight limb — where the bend plane is undefined and
+ * every axis derived from the reach can land along the bone — needs the check,
+ * not just a non-zero vector.
+ */
+function pickAxis(bone: Vec3, candidates: (Vec3 | null)[]): Vec3 {
+ for (const c of candidates) {
+ if (!c || len(c) < 1e-6) continue;
+ if (len(cross(c, bone)) < 1e-6) continue;
+ return c;
+ }
+ return perpendicular(bone);
+}
+
+/** The angle between two vectors, clamped out of the range acos rejects. */
+function angleBetween(a: Vec3, b: Vec3): number {
+ const d = len(a) * len(b);
+ if (d < 1e-9) return 0;
+ return Math.acos(Math.min(1, Math.max(-1, dot(a, b) / d)));
+}
+
+/**
+ * A joint's local transform THIS frame: what the pose stated, or what the world
+ * holds where no motion touched it. Reading the world alone would use values the
+ * layers have already replaced.
+ */
+function localOf(world: World, pose: Pose, entity: Entity): TransformData | null {
+ for (const track of pose.tracks) {
+ if (track.entity === entity && track.def === Transform) {
+ return track.data as unknown as TransformData;
+ }
+ }
+ return world.has(entity, Transform) ? world.get(entity, Transform) as TransformData : null;
+}
+
+/** The joints from `rigRoot` down to `joint`, `rigRoot` excluded. Null when the
+ * joint is not under the rig at all. */
+function chainTo(world: World, rigRoot: Entity, joint: Entity): Entity[] | null {
+ const up: Entity[] = [];
+ let at = joint;
+ for (let guard = 0; guard < 64; guard++) {
+ if (at === rigRoot) return up.reverse();
+ up.push(at);
+ const parent = parentOf(world, at);
+ if (parent === null) return null;
+ at = parent;
+ }
+ return null;
+}
+
+function parentOf(world: World, entity: Entity): Entity | null {
+ const data = world.tryGet(entity, Parent) as { entity?: number } | null;
+ return data && typeof data.entity === 'number' ? data.entity as Entity : null;
+}
+
+/**
+ * Place `joint` in the rig's space by composing the pose down the chain. Rotation
+ * only — a rig scaled per joint is a different problem, and silently folding a
+ * scale in here would answer it wrongly rather than not at all.
+ */
+function place(world: World, pose: Pose, rigRoot: Entity, joint: Entity): Placed | null {
+ const chain = chainTo(world, rigRoot, joint);
+ if (!chain) return null;
+ let position: Vec3 = { x: 0, y: 0, z: 0 };
+ let rotation: Quat = { w: 1, x: 0, y: 0, z: 0 };
+ let parentRotation: Quat = rotation;
+ for (const link of chain) {
+ const local = localOf(world, pose, link);
+ if (!local) return null;
+ parentRotation = rotation;
+ position = add(position, q.rotate(rotation, local.position));
+ rotation = q.normalize(q.mul(rotation, local.rotation));
+ }
+ return { position, rotation, parentRotation };
+}
+
+/** Write `worldRotation` back as the local rotation it implies under `parent`. */
+function setLocalRotation(
+ world: World, pose: Pose, entity: Entity, parentRotation: Quat, rotation: Quat,
+): void {
+ const track = pose.track(world, entity, Transform);
+ if (!track) return;
+ const local = q.normalize(q.mul(q.conjugate(parentRotation), rotation));
+ track.data.rotation = { w: local.w, x: local.x, y: local.y, z: local.z };
+ track.touched.add('rotation');
+}
+
+/** How much of this constraint applies, the parameter scaling what was authored. */
+function weightOf(ik: AnimatorIK, params: MotionParams): number {
+ const authored = ik.weight ?? 1;
+ const scale = ik.parameter ? Number(params[ik.parameter] ?? 0) : 1;
+ return Math.min(1, Math.max(0, authored * scale));
+}
+
+/**
+ * Move `joint`'s LOCAL rotation `weight` of the way to what the solve wants. The
+ * weight is a share of the answer, exactly as a layer's is — not a share of a
+ * correction applied joint by joint, which compounds down a chain and leaves a
+ * half-weight limb in a pose no solve ever produced.
+ */
+function leanJoint(
+ world: World, pose: Pose, joint: Entity,
+ parentRotation: Quat, wanted: Quat, weight: number,
+): Quat {
+ const local = q.normalize(q.mul(q.conjugate(parentRotation), wanted));
+ const current = localOf(world, pose, joint)?.rotation ?? { w: 1, x: 0, y: 0, z: 0 };
+ const blended = { w: current.w, x: current.x, y: current.y, z: current.z };
+ if (weight >= 1) { blended.w = local.w; blended.x = local.x; blended.y = local.y; blended.z = local.z; }
+ else leanQuat(blended, local, weight);
+
+ const track = pose.track(world, joint, Transform);
+ if (track) {
+ track.data.rotation = { w: blended.w, x: blended.x, y: blended.y, z: blended.z };
+ track.touched.add('rotation');
+ }
+ return q.normalize(q.mul(parentRotation, blended));
+}
+
+/** `v` with everything along `axis` taken out — the part of it that is a
+ * direction the limb can actually bend towards. */
+function orthogonal(v: Vec3, axis: Vec3): Vec3 {
+ const k = dot(v, axis);
+ return { x: v.x - axis.x * k, y: v.y - axis.y * k, z: v.z - axis.z * k };
+}
+
+const normalized = (v: Vec3): Vec3 => {
+ const l = len(v);
+ return l < 1e-9 ? { x: 0, y: 0, z: 0 } : { x: v.x / l, y: v.y / l, z: v.z / l };
+};
+
+const scale = (v: Vec3, k: number): Vec3 => ({ x: v.x * k, y: v.y * k, z: v.z * k });
+
+/**
+ * Two-bone IK — the tip and the two joints above it — CONSTRUCTED, not corrected.
+ * The elbow lies on a circle about the root-to-target line; the law of cosines
+ * fixes where along it and how far off, and the pole picks the point. Nudging by
+ * angle differences cannot reach the circle's far side: the axis lies along a bone.
+ */
+function solveTwoBone(
+ world: World, pose: Pose, rigRoot: Entity, ik: AnimatorIK, weight: number,
+): boolean {
+ const tip = resolveChildEntity(world, rigRoot, ik.tip);
+ const target = resolveChildEntity(world, rigRoot, ik.target);
+ if (tip === null || target === null) return false;
+ const mid = parentOf(world, tip);
+ const root = mid === null ? null : parentOf(world, mid);
+ if (mid === null || root === null) return false;
+
+ const pTip = place(world, pose, rigRoot, tip);
+ const pMid = place(world, pose, rigRoot, mid);
+ const pRoot = place(world, pose, rigRoot, root);
+ const pTarget = place(world, pose, rigRoot, target);
+ if (!pTip || !pMid || !pRoot || !pTarget) return false;
+
+ const upper = sub(pMid.position, pRoot.position);
+ const lower = sub(pTip.position, pMid.position);
+ const reach = sub(pTarget.position, pRoot.position);
+ const a = len(upper);
+ const b = len(lower);
+ if (a < 1e-6 || b < 1e-6 || len(reach) < 1e-6) return false;
+ const c = Math.min(Math.max(len(reach), Math.abs(a - b) + 1e-5), a + b - 1e-5);
+ const along = normalized(reach);
+
+ // Which way the elbow leaves the line. A pole names it; without one the limb
+ // keeps the bend it already has; and a limb that is dead straight has no bend
+ // to keep, so any direction off the line will do.
+ const pole = ik.pole ? resolveChildEntity(world, rigRoot, ik.pole) : null;
+ const poleAt = pole === null ? null : place(world, pose, rigRoot, pole);
+ const bendTowards = pickBend(along, [
+ poleAt ? orthogonal(sub(poleAt.position, pRoot.position), along) : null,
+ orthogonal(upper, along),
+ ]);
+
+ // The triangle: how far along the line the elbow sits, and how far off it.
+ const cosRoot = Math.min(1, Math.max(-1, (a * a + c * c - b * b) / (2 * a * c)));
+ const newMid = add(pRoot.position,
+ add(scale(along, a * cosRoot),
+ scale(bendTowards, a * Math.sqrt(Math.max(0, 1 - cosRoot * cosRoot)))));
+ const newTip = add(pRoot.position, scale(along, c));
+
+ const rootWanted = q.normalize(q.mul(
+ q.rotationTo(upper, sub(newMid, pRoot.position)), pRoot.rotation));
+ // The lower bone as the root's new orientation leaves it, before the elbow
+ // turns: measured in the frame the mid joint will actually be in.
+ const carried = q.normalize(q.mul(rootWanted, q.conjugate(pRoot.rotation)));
+ const midWanted = q.normalize(q.mul(
+ q.rotationTo(q.rotate(carried, lower), sub(newTip, newMid)),
+ q.mul(carried, pMid.rotation)));
+
+ const rootActual = leanJoint(world, pose, root, pRoot.parentRotation, rootWanted, weight);
+ leanJoint(world, pose, mid, rootActual, midWanted, weight);
+ return true;
+}
+
+/** The first direction that leaves the line; any will do for a straight limb. */
+function pickBend(along: Vec3, candidates: (Vec3 | null)[]): Vec3 {
+ for (const c of candidates) {
+ if (c && len(c) > 1e-6) return normalized(c);
+ }
+ return normalized(perpendicular(along));
+}
+
+/** Look-at: the tip turns so its own `axis` points at the target. */
+function solveLookAt(
+ world: World, pose: Pose, rigRoot: Entity, ik: AnimatorIK, weight: number,
+): boolean {
+ const tip = resolveChildEntity(world, rigRoot, ik.tip);
+ const target = resolveChildEntity(world, rigRoot, ik.target);
+ if (tip === null || target === null) return false;
+ const pTip = place(world, pose, rigRoot, tip);
+ const pTarget = place(world, pose, rigRoot, target);
+ if (!pTip || !pTarget) return false;
+
+ const facing = q.rotate(pTip.rotation, AXIS[ik.axis ?? 'z']);
+ const toward = sub(pTarget.position, pTip.position);
+ if (len(toward) < 1e-6) return false;
+ const wanted = q.normalize(q.mul(q.rotationTo(facing, toward), pTip.rotation));
+ leanJoint(world, pose, tip, pTip.parentRotation, wanted, weight);
+ return true;
+}
+
+/**
+ * Apply every constraint to the stack's answer, in the order they are declared:
+ * one can move a joint another then reads, and an author who wrote them in an
+ * order meant it.
+ */
+export function solveAnimatorIK(
+ world: World, rigRoot: Entity, pose: Pose,
+ constraints: readonly AnimatorIK[], params: MotionParams,
+): void {
+ for (const ik of constraints) {
+ const weight = weightOf(ik, params);
+ if (weight <= 0) continue;
+ if (ik.kind === 'look-at') solveLookAt(world, pose, rigRoot, ik, weight);
+ else solveTwoBone(world, pose, rigRoot, ik, weight);
+ }
+}
diff --git a/sdk/src/animation/index.ts b/sdk/src/animation/index.ts
index cc97f0005..113d15aca 100644
--- a/sdk/src/animation/index.ts
+++ b/sdk/src/animation/index.ts
@@ -146,6 +146,12 @@ export {
type AnimClipSizing,
} from './AnimClipLoader';
+export {
+ solveAnimatorIK,
+ type AnimatorIK,
+ type AnimatorIKKind,
+} from './animatorIK';
+
export {
MaskReach,
type AnimatorMask,
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index cb6912ef9..fd3d716f0 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -472,6 +472,7 @@ export {
ANIMATOR_FORMAT_VERSION,
migrateAnimatorController,
MaskReach,
+ solveAnimatorIK,
overlayPose,
addPoseOver,
STATE_PATH_SEP,
@@ -480,6 +481,8 @@ export {
type AnimatorLayer,
type AnimatorLayerBlend,
type AnimatorMask,
+ type AnimatorIK,
+ type AnimatorIKKind,
type AnimatorMigration,
type LayerReach,
type AnimatorPathEvalResult,
diff --git a/sdk/tests/animatorIK.test.ts b/sdk/tests/animatorIK.test.ts
new file mode 100644
index 000000000..8da2796ba
--- /dev/null
+++ b/sdk/tests/animatorIK.test.ts
@@ -0,0 +1,292 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * The claim: a constraint puts the joint it names WHERE it names, measured as a
+ * distance rather than as "the limb looks bent". It reads the pose this frame
+ * stated, not the world's record of the last one.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ Animator, AnimatorControllerAPI, solveAnimatorIK, Pose,
+ type AnimatorData, type AnimatorControllerDef, type AnimatorIK,
+} from '../src/animation';
+import { Parent, Children, Name, Transform } from '../src/ecs/component';
+import { q } from '../src/math/quat';
+import { createTimelineMotionDriver, TIMELINE_MOTION } from '../src/timeline';
+import { TimelineAPI } from '../src/timeline/TimelineControl';
+import { WrapMode, TrackType, InterpType, type TimelineAsset } from '../src/timeline/TimelineTypes';
+
+interface Vec3 { x: number; y: number; z: number }
+
+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;
+}
+
+const RIG = 1;
+const identity = () => ({ w: 1, x: 0, y: 0, z: 0 });
+
+/**
+ * A straight arm along +X: rig → upper → fore → hand, each one unit out, plus a
+ * target the game moves. Straight on purpose — a limb already bent would hide a
+ * solver that only ever keeps the bend it found.
+ */
+function arm(world: any, targetAt: Vec3) {
+ const ids = { rig: RIG, upper: 2, fore: 3, hand: 4, target: 5, pole: 6 };
+ const node = (id: number, parent: number | null, name: string, at: Vec3) => {
+ world.insert(id, Name, { value: name });
+ world.insert(id, Transform, { position: at, rotation: identity(), scale: { x: 1, y: 1, z: 1 } });
+ if (parent !== null) {
+ world.insert(id, Parent, { entity: parent });
+ const held = world.tryGet(parent, Children) as { entities: number[] } | null;
+ world.insert(parent, Children, { entities: [...(held?.entities ?? []), id] });
+ }
+ };
+ node(ids.rig, null, 'Rig', { x: 0, y: 0, z: 0 });
+ node(ids.upper, ids.rig, 'Upper', { x: 1, y: 0, z: 0 });
+ node(ids.fore, ids.upper, 'Fore', { x: 1, y: 0, z: 0 });
+ node(ids.hand, ids.fore, 'Hand', { x: 1, y: 0, z: 0 });
+ node(ids.target, ids.rig, 'Target', targetAt);
+ node(ids.pole, ids.rig, 'Pole', { x: 1, y: 0, z: 2 });
+ return ids;
+}
+
+/** Where `childPath` ends up in rig space once `pose` is written to the world. */
+function placeOf(world: any, path: string): Vec3 {
+ const names = path.split('/');
+ let at = { x: 0, y: 0, z: 0 };
+ let rot = identity();
+ let entity = RIG;
+ for (const name of names) {
+ const children = (world.tryGet(entity, Children) as { entities: number[] } | null)?.entities ?? [];
+ const found = children.find((c) => (world.tryGet(c, Name) as { value: string }).value === name);
+ entity = found!;
+ const t = world.get(entity, Transform) as { position: Vec3; rotation: any };
+ const offset = q.rotate(rot, t.position);
+ at = { x: at.x + offset.x, y: at.y + offset.y, z: at.z + offset.z };
+ rot = q.normalize(q.mul(rot, t.rotation));
+ }
+ return at;
+}
+
+const dist = (a: Vec3, b: Vec3) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
+
+/** Solve `ik` against a fresh straight arm reaching for `targetAt`. */
+function reach(targetAt: Vec3, ik: Partial<AnimatorIK> = {}): { world: any; hand: Vec3 } {
+ const world = makeWorld();
+ arm(world, targetAt);
+ const pose = new Pose();
+ pose.reset();
+ solveAnimatorIK(world, RIG, pose, [{
+ kind: 'two-bone', tip: 'Upper/Fore/Hand', target: 'Target', ...ik,
+ } as AnimatorIK], {});
+ pose.applyTo(world);
+ return { world, hand: placeOf(world, 'Upper/Fore/Hand') };
+}
+
+describe('two-bone IK', () => {
+ it('puts the tip on a target inside its reach', () => {
+ // The arm is 2 units long and the target is 1.5 away: a triangle exists,
+ // so the hand lands ON it, not near it.
+ const target = { x: 1.0, y: 1.118033988, z: 0 };
+ const { hand } = reach(target);
+ expect(dist(hand, target)).toBeLessThan(1e-3);
+ });
+
+ it('reaches as far as it can toward one it cannot get to', () => {
+ // Five units from a two-unit arm. The hand cannot arrive, so the limb
+ // straightens ALONG the line instead — a solver that quietly gave up
+ // would leave it where the clip put it.
+ const shoulder = { x: 1, y: 0, z: 0 };
+ const target = { x: 0, y: 5, z: 0 };
+ const { hand } = reach(target);
+ expect(dist(hand, shoulder)).toBeCloseTo(2, 2);
+
+ const unit = (a: Vec3, b: Vec3) => {
+ const d = { x: a.x - b.x, y: a.y - b.y, z: a.z - b.z };
+ const l = Math.hypot(d.x, d.y, d.z);
+ return { x: d.x / l, y: d.y / l, z: d.z / l };
+ };
+ const went = unit(hand, shoulder);
+ const wanted = unit(target, shoulder);
+ expect(went.x).toBeCloseTo(wanted.x, 3);
+ expect(went.y).toBeCloseTo(wanted.y, 3);
+ });
+
+ it('leaves the pose alone at weight zero', () => {
+ const { hand } = reach({ x: 1, y: 1, z: 0 }, { weight: 0 });
+ expect(hand).toEqual({ x: 3, y: 0, z: 0 });
+ });
+
+ it('goes part of the way at a partial weight', () => {
+ // Not "somewhere between": closer than untouched and further than solved,
+ // which is what makes this different from having no weight at all.
+ const target = { x: 1.0, y: 1.118033988, z: 0 };
+ const full = dist(reach(target).hand, target);
+ const half = dist(reach(target, { weight: 0.5 }).hand, target);
+ const none = dist(reach(target, { weight: 0 }).hand, target);
+ expect(full).toBeLessThan(half);
+ expect(half).toBeLessThan(none);
+ });
+
+ it('scales the authored weight by the parameter a game drives', () => {
+ const world = makeWorld();
+ arm(world, { x: 1.0, y: 1.118033988, z: 0 });
+ const pose = new Pose();
+ pose.reset();
+ solveAnimatorIK(world, RIG, pose, [{
+ kind: 'two-bone', tip: 'Upper/Fore/Hand', target: 'Target', parameter: 'plant',
+ }], { plant: 0 });
+ pose.applyTo(world);
+ expect(placeOf(world, 'Upper/Fore/Hand')).toEqual({ x: 3, y: 0, z: 0 });
+ });
+
+ it('bends toward the pole it was given', () => {
+ // The same target, two poles: the elbow has to end up on opposite sides,
+ // or the pole is a field nothing reads.
+ const target = { x: 1.0, y: 1.118033988, z: 0 };
+ const front = reach(target, { pole: 'Pole' });
+ const elbowFront = placeOf(front.world, 'Upper/Fore');
+
+ const world = makeWorld();
+ const ids = arm(world, target);
+ world.update(ids.pole, Transform, (t: any) => { t.position = { x: 1, y: 0, z: -2 }; });
+ const pose = new Pose();
+ pose.reset();
+ solveAnimatorIK(world, RIG, pose, [{
+ kind: 'two-bone', tip: 'Upper/Fore/Hand', target: 'Target', pole: 'Pole',
+ }], {});
+ pose.applyTo(world);
+ const elbowBack = placeOf(world, 'Upper/Fore');
+
+ expect(Math.sign(elbowFront.z)).not.toBe(Math.sign(elbowBack.z));
+ expect(Math.abs(elbowFront.z)).toBeGreaterThan(0.1);
+ });
+
+ it('states nothing for a joint that is not under the rig', () => {
+ const world = makeWorld();
+ arm(world, { x: 1, y: 1, z: 0 });
+ const pose = new Pose();
+ pose.reset();
+ solveAnimatorIK(world, RIG, pose, [{
+ kind: 'two-bone', tip: 'Upper/Nothing/Here', target: 'Target',
+ }], {});
+ expect(pose.tracks.filter((t) => t.touched.size > 0)).toHaveLength(0);
+ });
+});
+
+describe('look-at IK', () => {
+ it('turns the joint so its own axis points at the target', () => {
+ const world = makeWorld();
+ arm(world, { x: 1, y: 0, z: 3 });
+ const pose = new Pose();
+ pose.reset();
+ solveAnimatorIK(world, RIG, pose, [{
+ kind: 'look-at', tip: 'Upper/Fore/Hand', target: 'Target', axis: 'x',
+ }], {});
+ pose.applyTo(world);
+
+ // The hand sits at (3,0,0) and the target at (1,0,3): its +X must end up
+ // along (-2, 0, 3) normalized.
+ const hand = world.get(4, Transform) as { rotation: { w: number; x: number; y: number; z: number } };
+ const rot = hand.rotation;
+ const { w, x, y, z } = rot;
+ const facing = {
+ x: 1 - 2 * (y * y + z * z), y: 2 * (x * y + w * z), z: 2 * (x * z - w * y),
+ };
+ const want = { x: -2 / Math.hypot(2, 3), y: 0, z: 3 / Math.hypot(2, 3) };
+ expect(facing.x).toBeCloseTo(want.x, 3);
+ expect(facing.z).toBeCloseTo(want.z, 3);
+ });
+});
+
+describe('a constraint through the animator', () => {
+ /**
+ * A rig with a joint ABOVE the chain: Rig → Spine → Upper → Fore → Hand. What
+ * the spine does moves the shoulder, so where the arm can reach depends on the
+ * pose this frame — which is the only geometry where reading the world instead
+ * gives a different answer at all.
+ */
+ function spined(world: any, targetAt: Vec3) {
+ const node = (id: number, parent: number | null, name: string, at: Vec3) => {
+ world.insert(id, Name, { value: name });
+ world.insert(id, Transform, { position: at, rotation: identity(), scale: { x: 1, y: 1, z: 1 } });
+ if (parent !== null) {
+ world.insert(id, Parent, { entity: parent });
+ const held = world.tryGet(parent, Children) as { entities: number[] } | null;
+ world.insert(parent, Children, { entities: [...(held?.entities ?? []), id] });
+ }
+ };
+ node(RIG, null, 'Rig', { x: 0, y: 0, z: 0 });
+ node(2, RIG, 'Spine', { x: 0, y: 1, z: 0 });
+ node(3, 2, 'Upper', { x: 1, y: 0, z: 0 });
+ node(4, 3, 'Fore', { x: 1, y: 0, z: 0 });
+ node(5, 4, 'Hand', { x: 1, y: 0, z: 0 });
+ node(6, RIG, 'Target', targetAt);
+ }
+
+ /** A clip turning the spine a quarter turn about Z, every frame. */
+ function turnsSpine(): 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: 'Transform', childPath: 'Spine', name: 's',
+ channels: [
+ { property: 'rotation.x', keyframes: key(0) },
+ { property: 'rotation.y', keyframes: key(0) },
+ { property: 'rotation.z', keyframes: key(-Math.SQRT1_2) },
+ { property: 'rotation.w', keyframes: key(Math.SQRT1_2) },
+ ],
+ }],
+ } as TimelineAsset;
+ }
+
+ it('bends the pose the layers just stated, not the world before them', () => {
+ // Spine turned: the shoulder is at the origin, the target 1.5 away and
+ // reachable. Read from the world, where it has not turned yet, the
+ // shoulder is at (1,1,0) and the target 2.7 away — out of reach.
+ const world = makeWorld();
+ const target = { x: 0, y: -1.5, z: 0 };
+ spined(world, target);
+
+ const timeline = new TimelineAPI();
+ timeline.registerAsset('turn.estimeline', turnsSpine());
+ const ctrl = new AnimatorControllerAPI();
+ ctrl.registerMotionDriver(TIMELINE_MOTION, createTimelineMotionDriver(timeline));
+ ctrl.registerController('rig', {
+ version: 2, parameters: [], initialState: 'Turn',
+ states: [{
+ name: 'Turn', transitions: [],
+ motion: { kind: TIMELINE_MOTION, clip: 'turn.estimeline', loop: true },
+ }],
+ ik: [{ kind: 'two-bone', tip: 'Spine/Upper/Fore/Hand', target: 'Target' }],
+ } as AnimatorControllerDef);
+ world.insert(RIG, Animator, {
+ controller: 'rig', currentState: '', layerStates: [], enabled: true,
+ } as AnimatorData);
+
+ ctrl.update(world, 0.016);
+ expect(dist(placeOf(world, 'Spine/Upper/Fore/Hand'), target)).toBeLessThan(1e-3);
+ });
+});