Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add spring bones for secondary motion on hair, tails and soft parts (#981)

Nguyen Xuan An3ccdc854fba1
diff --git a/changes/981.md b/changes/981.md
new file mode 100644
index 00000000..0b3f095e
--- /dev/null
+++ b/changes/981.md
@@ -0,0 +1 @@
+- Spring bones: `motion.springs` makes hair, tails and soft parts lag behind the animated pose, swing and settle (VRM spring bone model with sphere and capsule colliders), deterministic at a fixed 1/60 s step in the live scene, imported assets and `bake-motion` ([before and after](https://raw.githubusercontent.com/codepawl/67.js/981-spring-bones/docs/spring-bones-comparison.jpg)) (#981)
diff --git a/changes/981.size.md b/changes/981.size.md
new file mode 100644
index 00000000..a8b668bf
--- /dev/null
+++ b/changes/981.size.md
@@ -0,0 +1,3 @@
+- scene:agent-scene: spring bones need a loader entry and marker for the on-demand solver, a 10-line custom-solver hook in skeleton-pose and one capability topic; the solver itself loads only for a recipe with `springs`, so the 217 bytes are the whole cost for a scene without them.
+- scene:agent-scene+lazy: the lazy total counts the new on-demand module (spring-bones.js, about 3.5 KB gzip), which a scene without springs never loads.
+- goal:agent-scene: the core grows 217 bytes gzip so an agent can add springs; the solver is a separate on-demand chunk.
diff --git a/docs/spring-bones-comparison.jpg b/docs/spring-bones-comparison.jpg
new file mode 100644
index 00000000..9157c0e7
Binary files /dev/null and b/docs/spring-bones-comparison.jpg differ
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index bd94ae3d..a6276426 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -585,6 +585,7 @@ const ikSolver = z.discriminatedUnion('type', [
const motion = z.strictObject({
duration: z.number().min(0.1).max(30),
ik: z.array(ikSolver).max(16).optional().describe('Inverse kinematics run after the tracks and any selected clip, in order, on recipes and imported assets. IDs are recipe node IDs or an asset\'s node-N IDs; find them with scene_inspect kind hierarchy. scene_inspect reports motionIk: whether each solver reaches its target across the clip.'),
+ springs: z.record(z.string(), z.unknown()).optional().describe('Spring bones for hair, tails and soft parts, VRM model: { chains: [{ bones, stiffness, dragForce, gravityPower, gravityDir, hitRadius, colliders }], colliders: [{ id, bone, type, offset, radius }] }. scene_capabilities springBones has the ranges.'),
constraints: z.array(constraint).max(32).optional().describe('Blender-style node constraints, run in order after the tracks, drivers and IK, each on the pose the one before left: copy_location, copy_rotation, copy_scale, limit_location, limit_rotation, track_to, child_of, floor. Euler angles are XYZ in degrees; space defaults to world. Same result at any time, so seeking equals playing.'),
drivers: z.array(driver).max(32).optional().describe('Drive one node component or material property from a bounded expression over time and other nodes\' values. A driven property cannot also have a track.'),
loop: z.boolean().optional(),
diff --git a/scripts/proof-spring-bones.mjs b/scripts/proof-spring-bones.mjs
new file mode 100644
index 00000000..34150c76
--- /dev/null
+++ b/scripts/proof-spring-bones.mjs
@@ -0,0 +1,129 @@
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { chmod, copyFile, mkdir, mkdtemp, readFile, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join, resolve } from 'node:path';
+import { spawnSync } from 'node:child_process';
+import { Client } from '@modelcontextprotocol/client';
+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
+
+// Visual proof for spring bones (#981): a fox turns and stops, once with its tail on springs and once without. Both clips
+// are rendered through the MCP render jobs (frames are sampled in order, so the springs swing and settle), and the same
+// frame of each is joined into one comparison still. Usage: node scripts/proof-spring-bones.mjs <output folder>
+// Environment: PROOF_BACKEND gpu|cpu (default gpu), PROOF_CHROME_FLAGS extra Chrome flags, PROOF_INSPECT=1 to print the tail bones only.
+// Model: Fox by PixelMannen (CC0), rigged and animated by tomkranis (CC BY 4.0), from the Khronos glTF sample assets.
+
+const FOX_URL = 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Fox/glTF-Binary/Fox.glb';
+const outputDirectory = resolve(process.argv[2] ?? 'artifacts/981');
+const backend = process.env.PROOF_BACKEND ?? 'gpu';
+const WIDTH = 640;
+const HEIGHT = 360;
+const FPS = 24;
+const DURATION = 4;
+const COMPARISON_TIME = Number(process.env.PROOF_COMPARISON_TIME ?? 1.25);
+
+const workDirectory = await mkdtemp(join(tmpdir(), '67js-springs-'));
+const assets = join(workDirectory, 'assets');
+const jobs = join(workDirectory, 'jobs');
+await mkdir(assets);
+await mkdir(outputDirectory, { recursive: true });
+
+const foxBytes = Buffer.from(await (await fetch(FOX_URL)).arrayBuffer());
+assert.equal(foxBytes.subarray(0, 4).toString(), 'glTF', 'the download is not a GLB');
+const assetId = createHash('sha256').update(foxBytes).digest('hex');
+await writeFile(join(assets, 'fox.glb'), foxBytes);
+
+let browserPath = process.env.CHROME_PATH;
+if (browserPath && process.env.PROOF_CHROME_FLAGS) {
+ const wrapper = join(workDirectory, 'chrome-with-flags.sh');
+ await writeFile(wrapper, `#!/bin/sh\nexec "${browserPath}" ${process.env.PROOF_CHROME_FLAGS} "$@"\n`);
+ await chmod(wrapper, 0o755);
+ browserPath = wrapper;
+}
+
+const serverArguments = [
+ resolve('bin/67js-mcp.mjs'), '--backend', backend, '--memory', '192', '--jobs', jobs, '--assets', assets,
+ ...(browserPath ? ['--browser', browserPath] : []),
+];
+const transport = new StdioClientTransport({ command: process.execPath, args: serverArguments, cwd: workDirectory, stderr: 'pipe' });
+let diagnostics = '';
+transport.stderr.on('data', bytes => { diagnostics = (diagnostics + bytes).slice(-8192); });
+const client = new Client({ name: '67js-spring-proof', version: '1' });
+
+async function call(name, argumentsValue = {}, timeout = 120000) {
+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout });
+ assert.equal(result.isError, undefined, result.content?.find(item => item.type === 'text')?.text);
+ return result.structuredContent ?? result;
+}
+
+async function waitForJob(jobId) {
+ for (let attempt = 0; attempt < 600; attempt++) {
+ const record = await call('scene_render_status', { jobId });
+ if (['completed', 'failed', 'cancelled'].includes(record.state)) {
+ assert.equal(record.state, 'completed', JSON.stringify(record));
+ return record;
+ }
+ await new Promise(resolveWait => setTimeout(resolveWait, 500));
+ }
+ throw new Error(`render job ${jobId} did not finish`);
+}
+
+function ffmpeg(...argumentsList) {
+ const run = spawnSync('ffmpeg', ['-y', '-loglevel', 'error', ...argumentsList], { encoding: 'utf8' });
+ assert.equal(run.status, 0, run.stderr);
+}
+
+try {
+ await client.connect(transport);
+ const probeRecipe = { format: '67js.asset', schemaVersion: 1, assetId, motion: { duration: DURATION, loop: false, layers: [{ clip: 0 }] } };
+ const probe = await call('scene_create_asset', { recipe: probeRecipe }, 240000);
+ const hierarchy = await call('scene_inspect', { sessionId: probe.sessionId, kind: 'hierarchy', limit: 128 });
+ const nodes = hierarchy.nodes ?? hierarchy.hierarchy ?? [];
+ const tailBones = nodes.filter(node => /tail/i.test(node.name ?? '')).map(node => ({ id: node.id, name: node.name, parent: node.parent }));
+ console.log(JSON.stringify({ nodeCount: nodes.length, tailBones, firstNodes: nodes.slice(0, 6) }, null, 1));
+ await call('scene_dispose', { sessionId: probe.sessionId });
+ if (process.env.PROOF_INSPECT) process.exit(0);
+ assert.ok(tailBones.length >= 2, 'no tail bones found');
+
+ // The fox stands, turns sharply to one side, stops, then turns back: the tail has to lag, swing and settle twice.
+ const yaw = degrees => [0, Math.sin(degrees * Math.PI / 360), 0, Math.cos(degrees * Math.PI / 360)];
+ const turnTracks = [{
+ kind: 'node', id: 'node-0', property: 'rotation', interpolation: 'SMOOTH',
+ keyframes: [
+ { time: 0, value: yaw(0) }, { time: 0.5, value: yaw(0) }, { time: 0.9, value: yaw(80) },
+ { time: 2.2, value: yaw(80) }, { time: 2.6, value: yaw(-60) }, { time: 4, value: yaw(-60) },
+ ],
+ }];
+ const springs = {
+ chains: [{ bones: tailBones.map(bone => bone.id), stiffness: 0.6, dragForce: 0.12, gravityPower: 0.3, hitRadius: 0.03 }],
+ };
+
+ async function renderClip(name, withSprings) {
+ const motion = { duration: DURATION, loop: false, layers: [{ clip: Number(process.env.PROOF_CLIP ?? 0), loop: true }], tracks: turnTracks, ...(withSprings ? { springs } : {}) };
+ const created = await call('scene_create_asset', { recipe: { format: '67js.asset', schemaVersion: 1, assetId, motion } }, 240000);
+ const submitted = await call('scene_render_submit', { sessionId: created.sessionId, expectedRevision: created.revision ?? 0, settings: {
+ kind: 'video', width: WIDTH, height: HEIGHT, fps: FPS, duration: DURATION, motion: { start: 0 },
+ } }, 240000);
+ await waitForJob(submitted.jobId);
+ const result = await call('scene_render_result', { jobId: submitted.jobId });
+ await copyFile(result.artifacts[0].path, join(outputDirectory, `${name}.mp4`));
+ await call('scene_dispose', { sessionId: created.sessionId });
+ }
+
+ await renderClip('spring-bones-off', false);
+ await renderClip('spring-bones-on', true);
+
+ const frame = name => ['-ss', String(COMPARISON_TIME), '-i', join(outputDirectory, `${name}.mp4`), '-frames:v', '1'];
+ ffmpeg(...frame('spring-bones-off'), join(workDirectory, 'off.png'));
+ ffmpeg(...frame('spring-bones-on'), join(workDirectory, 'on.png'));
+ ffmpeg(
+ '-i', join(workDirectory, 'off.png'), '-i', join(workDirectory, 'on.png'),
+ '-filter_complex', 'hstack=inputs=2', '-frames:v', '1', '-q:v', '3', join(outputDirectory, 'spring-bones-comparison.jpg'),
+ );
+ console.log(`wrote ${outputDirectory}`);
+} catch (error) {
+ console.error(diagnostics);
+ throw error;
+} finally {
+ await client.close().catch(() => {});
+}
diff --git a/src/agent-asset.js b/src/agent-asset.js
index 67a392fa..58fd3342 100644
--- a/src/agent-asset.js
+++ b/src/agent-asset.js
@@ -549,8 +549,8 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
if (meshEdits.length) {
result.meshEdits = meshEdits;
}
- if ((candidate.motion?.ik?.length || candidate.motion?.footLock) && Math.max(...result.root.scale) - Math.min(...result.root.scale) > 1e-3 * Math.max(...result.root.scale)) {
- throw invalidField('root.scale', result.root.scale, 'the same number on every axis, such as [1, 1, 1], because motion ik and footLock need a uniform asset root scale');
+ if ((candidate.motion?.ik?.length || candidate.motion?.springs || candidate.motion?.footLock) && Math.max(...result.root.scale) - Math.min(...result.root.scale) > 1e-3 * Math.max(...result.root.scale)) {
+ throw invalidField('root.scale', result.root.scale, 'the same number on every axis, such as [1, 1, 1], because motion ik, springs and footLock need a uniform asset root scale');
}
result.motion = agentMotion.normalizeAgentMotion(candidate.motion, motionRecipe(result));
if (candidate.physics !== undefined && candidate.physics !== null) {
diff --git a/src/agent-motion-bake.js b/src/agent-motion-bake.js
index 1e097dc2..d50998c3 100644
--- a/src/agent-motion-bake.js
+++ b/src/agent-motion-bake.js
@@ -209,6 +209,7 @@ function dropLiveSources(candidate, idList) {
requireWholeGroup(joints, `${solver.type} IK solver`, 'its joints bake together', ids);
return false;
});
+ const springs = bakedSprings(motion.springs, ids);
const remaining = {
ik: solvers,
constraints: (motion.constraints ?? []).filter(constraint => !ids.has(constraint.node)),
@@ -218,10 +219,25 @@ function dropLiveSources(candidate, idList) {
if (list.length) motion[field] = list;
else delete motion[field];
}
+ if (springs) motion.springs = springs;
+ else delete motion.springs;
+}
+
+/** The spring chains that stay live. A chain moves its bones together, so a bake that takes one must take all of them. */
+function bakedSprings(springs, ids) {
+ if (!springs) return null;
+ const chains = springs.chains.filter(chain => {
+ if (!chain.bones.some(id => ids.has(id))) return true;
+ requireWholeGroup(chain.bones, 'spring chain', 'its bones bake together', ids);
+ return false;
+ });
+ if (!chains.length) return null;
+ const used = new Set(chains.flatMap(chain => chain.colliders));
+ return { chains, colliders: springs.colliders.filter(collider => used.has(collider.id)) };
}
function motionHasContent(motion) {
- return Boolean(motion.tracks.length || motion.layers?.length || motion.ik?.length || motion.constraints?.length || motion.drivers?.length || motion.drive);
+ return Boolean(motion.tracks.length || motion.layers?.length || motion.ik?.length || motion.springs || motion.constraints?.length || motion.drivers?.length || motion.drive);
}
/**
diff --git a/src/agent-motion.js b/src/agent-motion.js
index 9aaf4f23..2229a87f 100644
--- a/src/agent-motion.js
+++ b/src/agent-motion.js
@@ -398,11 +398,24 @@ function normalizeIkSolver(input, position, nodes, visibleNodes, duration) {
}
function solverNodes(solver) {
+ if (solver.type === 'spring') return solver.nodes;
if (solver.type === 'two-bone') return [solver.root, solver.middle, solver.end];
if (solver.type === 'aim') return solver.joints;
return solver.chain ?? [solver.root, solver.end];
}
+/** One stand-in solver per spring chain, so rigs, scale checks and the IK evaluator treat chains like any other solver. */
+function springSolvers(springs, recipe) {
+ const module = agentSceneModule('springs');
+ const hierarchy = ikHierarchy(recipe);
+ return springs.chains.map(chain => ({
+ type: 'spring',
+ nodes: module.springChainNodeIds(chain, springs.colliders, hierarchy),
+ weight: 1,
+ definition: { type: 'custom', create: module.springChainSolver(chain, springs.colliders) },
+ }));
+}
+
function pointNodes(solver) {
const points = [solver.target, solver.pole].filter(point => point?.node).map(point => point.node);
return solver.curve?.nodes ? [...points, ...solver.curve.nodes] : points;
@@ -478,7 +491,7 @@ export function normalizeAgentMotion(input, recipe) {
if (input === null || input === undefined) {
return null;
}
- knownKeys(input, ['duration', 'loop', 'tracks', 'ik', 'constraints', 'drivers', 'properties', 'layers', 'footLock', 'drive'], 'motion');
+ knownKeys(input, ['duration', 'loop', 'tracks', 'ik', 'constraints', 'drivers', 'properties', 'layers', 'footLock', 'drive', 'springs'], 'motion');
const drive = input.drive === undefined ? null : normalizedDrive(input.drive, recipe);
// A drive knows how long its path takes, so the motion may leave the duration out.
const duration = bounded(input.duration === undefined && drive ? Math.ceil(drive.built.duration * 1000) / 1000 : input.duration, 0.1, 30, 'motion.duration');
@@ -488,7 +501,7 @@ export function normalizeAgentMotion(input, recipe) {
}
const inputTracks = input.tracks ?? [];
denseArray(inputTracks, 128, 'Motion tracks');
- if (!inputTracks.length && !input.layers?.length && !input.ik?.length && !input.constraints?.length && !input.drivers?.length && !drive) {
+ if (!inputTracks.length && !input.layers?.length && !input.ik?.length && !input.springs && !input.constraints?.length && !input.drivers?.length && !drive) {
throw invalidField('motion', input, 'at least one track, IK solver, constraint or driver, such as { "duration": 1, "tracks": [...] }; use null to clear it');
}
const nodes = new Set((recipe.nodes ?? []).map(node => node.id));
@@ -569,6 +582,10 @@ export function normalizeAgentMotion(input, recipe) {
}
}
const visibleIds = new Set(ikHierarchy(recipe).map(node => node.id));
+ if (input.springs !== undefined) {
+ result.springs = agentSceneModule('springs').normalizeSpringBones(input.springs, { movable: nodes, visible: visibleIds, hierarchy: ikHierarchy(recipe) });
+ checkIkScales(springSolvers(result.springs, recipe), tracks, recipe);
+ }
if (input.properties !== undefined) {
result.properties = normalizeProperties(input.properties, duration, visibleIds);
}
@@ -638,8 +655,9 @@ function ikChannelClip(ik, duration, loop) {
/** Solve a motion's IK on top of its sampled node tracks. Returns staged rotations per node ID. */
function createIkEvaluator(motion, recipe, stagedNodeTracks) {
- const rig = ikRig(motion.ik, recipe);
- const clip = ikChannelClip(motion.ik, motion.duration, motion.loop);
+ const solvers = [...(motion.ik ?? []), ...(motion.springs ? springSolvers(motion.springs, recipe) : [])];
+ const rig = ikRig(solvers, recipe);
+ const clip = ikChannelClip(solvers, motion.duration, motion.loop);
const channelSampler = clip ? compileAnimationSampler(clip) : null;
const channelOutput = name => channelSampler.tracks.find(track => track.target === name).output;
let pose = null;
@@ -649,7 +667,8 @@ function createIkEvaluator(motion, recipe, stagedNodeTracks) {
const output = channelOutput(name);
return () => output;
};
- const definitions = motion.ik.map((solver, position) => {
+ const definitions = solvers.map((solver, position) => {
+ if (solver.type === 'spring') return solver.definition;
const weightOutput = solver.weight.keyframes ? channelOutput(`weight ${position}`) : null;
const weight = weightOutput ? () => Math.min(1, Math.max(0, weightOutput[0])) : solver.weight;
if (solver.type === 'spline') {
@@ -685,7 +704,7 @@ function createIkEvaluator(motion, recipe, stagedNodeTracks) {
const indexById = new Map(rig.joints.map((joint, index) => [joint.name, index]));
const baseBindings = rig.joints.map((joint, index) => ({ index, tracks: stagedNodeTracks.get(joint.name) }));
const skippedEnds = new Set(
- motion.ik
+ solvers
.filter(solver => (solver.type === 'two-bone' || solver.type === 'chain') && solver.keepEndRotation === false)
.map(solver => solver.end ?? solver.chain[solver.chain.length - 1])
);
@@ -849,7 +868,7 @@ export function compileAgentMotion(input, recipe) {
if (!stagedNodeTracks.has(track.id)) stagedNodeTracks.set(track.id, {});
stagedNodeTracks.get(track.id)[track.property] = staged;
}
- const ikEvaluator = motion.ik?.length ? createIkEvaluator(motion, recipe, stagedNodeTracks) : null;
+ const ikEvaluator = motion.ik?.length || motion.springs ? createIkEvaluator(motion, recipe, stagedNodeTracks) : null;
const constraintEvaluator = createNodeConstraintEvaluator({
hierarchy: ikHierarchy(recipe), rootMatrix: recipe.ikRootMatrix,
constraints: motion.constraints, drivers: motion.drivers, materials: recipe.materials ?? [], properties: motion.properties,
@@ -966,7 +985,7 @@ export function compileAgentMotion(input, recipe) {
*/
sweepIk(stagedPoseAt) {
if (!ikEvaluator) return [];
- const worst = motion.ik.map(solver => ({ type: solver.type, reached: true, worstError: 0, atTime: 0, warnings: [], limited: [] }));
+ const worst = (motion.ik ?? []).map(solver => ({ type: solver.type, reached: true, worstError: 0, atTime: 0, warnings: [], limited: [] }));
for (let sample = 0; sample < IK_SWEEP_SAMPLES; sample++) {
const time = motion.duration * sample / (IK_SWEEP_SAMPLES - 1);
sampler.sample(time);
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 553097fb..4e4eab2f 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -345,6 +345,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
motionModifiers: 'Track extrapolation constant|linear; modifiers [{type: cycles|stepped|noise|generator|limits|envelope, ...}], 8 at most; cycles and stepped remap time first.',
motionLimits: Object.freeze({ maxTracks: 128, maxKeyframesPerTrack: 64, maxKeyframes: 2048, maxDuration: 30 }),
motionBake: 'scene_apply bake-motion { nodes (32 at most), start 0, end (motion or physics duration), step 1/30 (512 samples), tolerance { position m, angle deg, scale } }: samples tracks, IK, constraints, drivers and physics into LINEAR tracks and removes those sources (an IK solver or the physics world only when all its nodes are baked). tolerance drops keys within it; without it a track keeps every sample, 64 keys at most. Procedural scenes only.',
+ springBones: 'motion.springs { chains: [{ bones: [node IDs root to tip, each the child of the one before, 16 per chain, 64 in all], stiffness 0-4 (1), dragForce 0-1 (0.4), gravityPower 0-2 (0), gravityDir [0,-1,0], hitRadius (0.02), tipLength (0.07), colliders: [ids] }] (16 at most), colliders: [{ id, bone, type sphere|capsule, offset, radius, tail }] }: VRM spring bones for hair and tails; fixed 1/60 s steps, sample times in increasing order; bake-motion bakes whole chains; needs loadAgentSceneModules.',
});
/** Degrees between faces above which a mesh geometry keeps a hard edge, as Blender's auto smooth does. */
diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.js
index 802d9a6f..8d84677f 100644
--- a/src/agent-scene-modules.js
+++ b/src/agent-scene-modules.js
@@ -9,6 +9,7 @@ const MODULE_LOADERS = {
text: () => import('./text-geometry.js'),
motion: () => import('./agent-motion.js'),
motionBake: () => import('./agent-motion-bake.js'),
+ springs: () => import('./spring-bones.js'),
settle: () => import('./agent-settle.js'),
drive: () => import('./agent-drive.js'),
physics: () => import('./agent-physics.js'),
@@ -56,6 +57,7 @@ const MODULE_MARKERS = {
text: ['"type":"text"'],
motion: ['"motion":{', '"bake-motion"'],
motionBake: ['"bake-motion"'],
+ springs: ['"springs":{'],
settle: ['"type":"settle"'],
drive: ['"drive":{'],
physics: ['"physics":{', '"fracture-node"'],
diff --git a/src/skeleton-pose.js b/src/skeleton-pose.js
index 3b6f29c5..abc85dfa 100644
--- a/src/skeleton-pose.js
+++ b/src/skeleton-pose.js
@@ -321,6 +321,10 @@ function bendWarnings(solver, state, prepared) {
function createSolver(definition, position, prepared, resolveJoint) {
const label = `IK ${position}`;
const weight = weightFunction(definition?.weight ?? 1, `${label} weight`);
+ if (definition?.type === 'custom') {
+ if (typeof definition.create !== 'function') throw new TypeError(`${label} type custom needs create(prepared, resolveJoint, label) => { joints, solve(time, context, weight) }.`);
+ return { type: 'custom', label, weight, ...definition.create(prepared, resolveJoint, label) };
+ }
const solverType = definition?.type === 'ik' ? 'chain' : definition?.type === 'spline_ik' ? 'spline' : definition?.type;
if (solverType !== 'spline' && typeof definition?.target !== 'function') checkedVector(definition?.target, `${label} target`);
if (definition.type === 'two-bone') {
@@ -719,7 +723,12 @@ function solveSpline(solver, time, context) {
return { reached: error <= Math.max(table.totalLength, totalBoneLength) * 1e-2 + 1e-4, error };
}
-const SOLVERS = { 'two-bone': solveTwoBone, aim: solveAim, chain: solveChain, spline: solveSpline };
+// A custom solver (spring bones) brings its own `solve`; it keeps its own state between calls.
+function solveCustom(solver, time, context) {
+ return solver.solve(time, context, checkedWeight(solver.weight, time, `${solver.label} weight`));
+}
+
+const SOLVERS = { 'two-bone': solveTwoBone, aim: solveAim, chain: solveChain, spline: solveSpline, custom: solveCustom };
const GLTF_TRACK_PROPERTIES = { position: 'translation', quaternion: 'rotation', scale: 'scale' };
const GLTF_STEP_INTERPOLATION = 2300;
diff --git a/src/spring-bones.js b/src/spring-bones.js
new file mode 100644
index 00000000..718109d6
--- /dev/null
+++ b/src/spring-bones.js
@@ -0,0 +1,305 @@
+// Spring bones: secondary motion for hair, tails, ears, straps and other soft parts. The model is the VRM spring bone
+// (stiffness, drag, gravity power and direction, hit radius, sphere and capsule colliders on other bones), so settings
+// made in VRoid or Blender's Wiggle Bones carry over. Each bone's tail is a point that follows the animated pose like a
+// weight on a spring, keeps the bone's length and stays outside the colliders; the bone then turns to aim at it.
+//
+// The simulation is a Verlet step at a fixed 1/60 s. It remembers the last time it was asked for, so ask for times in
+// increasing order (a render or bake does). A step back in time, or a gap over half a second, restarts the chain from
+// the animated pose. The same sequence of times gives the same pose, bit for bit.
+
+import { quat, vec3 } from 'gl-matrix';
+import { invalidField } from './field-error.js';
+import { bounded, denseArray, knownKeys, valueFrom } from './motion-validation.js';
+
+export const SPRING_STEP_SECONDS = 1 / 60;
+export const MAX_SPRING_CHAINS = 16;
+export const MAX_SPRING_CHAIN_BONES = 16;
+export const MAX_SPRING_BONES = 64;
+export const MAX_SPRING_COLLIDERS = 16;
+const MAX_CATCH_UP_STEPS = 30;
+const STEP_ROUNDING = 1e-3;
+const NEAR_ZERO = 1e-9;
+const DEFAULT_GRAVITY_DIRECTION = Object.freeze([0, -1, 0]);
+
+const CHAIN_FIELDS = ['bones', 'stiffness', 'dragForce', 'gravityPower', 'gravityDir', 'hitRadius', 'tipLength', 'colliders'];
+const COLLIDER_FIELDS = ['id', 'bone', 'type', 'offset', 'radius', 'tail'];
+
+function nodeIdIn(value, nodes, label) {
+ if (typeof value !== 'string' || !nodes.has(value)) {
+ throw invalidField(label, value, 'a node ID in this recipe, such as "tail1"');
+ }
+ return value;
+}
+
+function normalizeCollider(input, position, movableAndVisible) {
+ const label = `motion.springs.colliders[${position}]`;
+ knownKeys(input, COLLIDER_FIELDS, label);
+ if (typeof input.id !== 'string' || !/^[A-Za-z0-9_.-]{1,64}$/.test(input.id)) {
+ throw invalidField(`${label}.id`, input.id, 'a name of 1 to 64 letters, digits, dots, dashes or underscores that chains list in colliders, such as "head"');
+ }
+ const type = input.type ?? 'sphere';
+ if (type !== 'sphere' && type !== 'capsule') {
+ throw invalidField(`${label}.type`, type, 'sphere or capsule');
+ }
+ if (type === 'sphere' && input.tail !== undefined) {
+ throw invalidField(`${label}.tail`, input.tail, 'a field left out on a sphere, since only a capsule has a second end; set type to capsule or drop tail');
+ }
+ if (type === 'capsule' && input.tail === undefined) {
+ throw invalidField(`${label}.tail`, input.tail, 'the capsule\'s second end as [x, y, z] in the bone\'s own space, such as [0, 0.2, 0]');
+ }
+ const collider = {
+ id: input.id,
+ bone: nodeIdIn(input.bone, movableAndVisible, `${label}.bone`),
+ type,
+ offset: input.offset === undefined ? [0, 0, 0] : valueFrom(input.offset, 3, `${label}.offset`),
+ radius: bounded(input.radius ?? 0.05, 0.0001, 100, `${label}.radius`),
+ };
+ if (type === 'capsule') collider.tail = valueFrom(input.tail, 3, `${label}.tail`);
+ return collider;
+}
+
+function normalizeChain(input, position, nodes, colliderIds) {
+ const label = `motion.springs.chains[${position}]`;
+ knownKeys(input, CHAIN_FIELDS, label);
+ denseArray(input.bones, MAX_SPRING_CHAIN_BONES, `${label}.bones`);
+ if (!input.bones.length) {
+ throw invalidField(`${label}.bones`, input.bones, 'one to 16 node IDs from the root of the chain to its tip, such as ["tail1", "tail2", "tail3"]');
+ }
+ const bones = input.bones.map((id, slot) => nodeIdIn(id, nodes, `${label}.bones[${slot}]`));
+ if (new Set(bones).size !== bones.length) {
+ throw invalidField(`${label}.bones`, bones, 'each bone once');
+ }
+ const gravityDir = input.gravityDir === undefined ? [...DEFAULT_GRAVITY_DIRECTION] : valueFrom(input.gravityDir, 3, `${label}.gravityDir`);
+ if (Math.hypot(...gravityDir) < 1e-6) {
+ throw invalidField(`${label}.gravityDir`, gravityDir, 'a direction that is not zero, such as [0, -1, 0]');
+ }
+ const colliders = input.colliders === undefined ? [] : denseArray(input.colliders, MAX_SPRING_COLLIDERS, `${label}.colliders`);
+ for (const id of colliders) {
+ if (typeof id !== 'string' || !colliderIds.has(id)) {
+ throw invalidField(`${label}.colliders`, id, `an ID listed in motion.springs.colliders${colliderIds.size ? `, such as "${[...colliderIds][0]}"` : ', which is empty: add a collider first'}`);
+ }
+ }
+ return {
+ bones,
+ stiffness: bounded(input.stiffness ?? 1, 0, 4, `${label}.stiffness`),
+ dragForce: bounded(input.dragForce ?? 0.4, 0, 1, `${label}.dragForce`),
+ gravityPower: bounded(input.gravityPower ?? 0, 0, 2, `${label}.gravityPower`),
+ gravityDir,
+ hitRadius: bounded(input.hitRadius ?? 0.02, 0, 10, `${label}.hitRadius`),
+ tipLength: bounded(input.tipLength ?? 0.07, 0.001, 100, `${label}.tipLength`),
+ colliders: [...colliders],
+ };
+}
+
+/**
+ * Check and complete a `motion.springs` object: { chains: [{ bones, stiffness, dragForce, gravityPower, gravityDir,
+ * hitRadius, tipLength, colliders }], colliders: [{ id, bone, type, offset, radius, tail }] }. `movable` holds the node IDs a
+ * chain may rotate, `visible` every node a collider may ride on. Returns plain data with every default filled in.
+ */
+export function normalizeSpringBones(input, { movable, visible, hierarchy }) {
+ knownKeys(input, ['chains', 'colliders'], 'motion.springs');
+ denseArray(input.chains, MAX_SPRING_CHAINS, 'motion.springs.chains');
+ if (!input.chains.length) {
+ throw invalidField('motion.springs.chains', input.chains, 'one to 16 chains, such as [{ "bones": ["tail1", "tail2"], "stiffness": 1 }]');
+ }
+ const colliderInput = input.colliders === undefined ? [] : denseArray(input.colliders, MAX_SPRING_COLLIDERS, 'motion.springs.colliders');
+ const colliders = colliderInput.map((collider, position) => normalizeCollider(collider, position, visible));
+ const colliderIds = new Set(colliders.map(collider => collider.id));
+ if (colliderIds.size !== colliders.length) {
+ throw invalidField('motion.springs.colliders', colliders.map(collider => collider.id), 'a different id on each collider');
+ }
+ const chains = input.chains.map((chain, position) => normalizeChain(chain, position, movable, colliderIds));
+ const boneCount = chains.reduce((total, chain) => total + chain.bones.length, 0);
+ if (boneCount > MAX_SPRING_BONES) {
+ throw invalidField('motion.springs.chains', boneCount, `at most ${MAX_SPRING_BONES} bones in all chains, so shorten or drop chains`);
+ }
+ const claimed = new Set();
+ const parentOf = new Map(hierarchy.map(node => [node.id, node.parent ?? null]));
+ chains.forEach((chain, position) => {
+ chain.bones.forEach((bone, slot) => {
+ if (claimed.has(bone)) {
+ throw invalidField(`motion.springs.chains[${position}].bones[${slot}]`, bone, 'a bone that no other chain uses');
+ }
+ claimed.add(bone);
+ if (slot > 0 && parentOf.get(bone) !== chain.bones[slot - 1]) {
+ throw invalidField(`motion.springs.chains[${position}].bones[${slot}]`, bone, `the child of ${chain.bones[slot - 1]}, since a chain lists bones from its root to its tip, each parented to the one before`);
+ }
+ });
+ });
+ return { chains, colliders };
+}
+
+/** Node IDs a spring chain needs in the rig: its bones, the first child of its tip and the nodes colliders ride on. */
+export function springChainNodeIds(chain, colliders, hierarchy) {
+ const tip = chain.bones[chain.bones.length - 1];
+ const tipChild = hierarchy.find(node => node.parent === tip);
+ const ids = [...chain.bones];
+ if (tipChild) ids.push(tipChild.id);
+ for (const id of chain.colliders) ids.push(colliders.find(collider => collider.id === id).bone);
+ return ids;
+}
+
+function restDirectionOfJoint(prepared, index) {
+ const offset = prepared.restTranslations[index];
+ const direction = vec3.normalize(new Float64Array(3), offset);
+ if (vec3.length(offset) < NEAR_ZERO) vec3.set(direction, 0, 1, 0);
+ return direction;
+}
+
+/** The `create` function of a custom solver for one spring chain: createSkeletonPose({ ik: [{ type: 'custom', create }] }). */
+export function springChainSolver(chain, colliders) {
+ return function create(prepared, resolveJoint, label) {
+ const joints = chain.bones.map(name => resolveJoint(name, label));
+ joints.slice(1).forEach((joint, slot) => {
+ if (prepared.joints[joint].parent !== joints[slot]) {
+ throw new RangeError(`${label}: bone ${chain.bones[slot + 1]} must be the child of ${chain.bones[slot]}; list a spring chain from its root to its tip.`);
+ }
+ });
+ const gravityDirection = vec3.normalize(new Float64Array(3), chain.gravityDir);
+ const tailJoints = joints.map((joint, slot) => {
+ if (slot < joints.length - 1) return joints[slot + 1];
+ const child = prepared.joints.findIndex(candidate => candidate.parent === joint);
+ return child;
+ });
+ // Where each tail sits in its bone's own frame, and how far from the head, at rest.
+ const axes = joints.map((joint, slot) => {
+ if (tailJoints[slot] >= 0) return vec3.normalize(new Float64Array(3), prepared.restTranslations[tailJoints[slot]]);
+ const parentFrame = restDirectionOfJoint(prepared, joint);
+ return vec3.transformQuat(new Float64Array(3), parentFrame, quat.invert(new Float64Array(4), prepared.restRotations[joint]));
+ });
+ const localLengths = joints.map((joint, slot) => (tailJoints[slot] >= 0 ? vec3.length(prepared.restTranslations[tailJoints[slot]]) : null));
+ const colliderBones = chain.colliders.map(id => {
+ const collider = colliders.find(candidate => candidate.id === id);
+ return { ...collider, joint: resolveJoint(collider.bone, label) };
+ });
+
+ const tails = joints.map(() => new Float64Array(3));
+ const previousTails = joints.map(() => new Float64Array(3));
+ const animatedTails = joints.map(() => new Float64Array(3));
+ const animatedRotations = joints.map(() => new Float64Array(4));
+ const scratch = {
+ center: new Float64Array(3), end: new Float64Array(3), axis: new Float64Array(3),
+ offset: new Float64Array(3), nearest: new Float64Array(3), next: new Float64Array(3),
+ direction: new Float64Array(3), animatedDirection: new Float64Array(3), rotation: new Float64Array(4), turn: new Float64Array(4),
+ };
+ let lastStep = null;
+
+ function lengthOf(slot, state) {
+ return localLengths[slot] === null ? chain.tipLength : localLengths[slot] * state.scales[joints[slot]];
+ }
+
+ function readAnimatedTails(state) {
+ joints.forEach((joint, slot) => {
+ if (tailJoints[slot] >= 0) {
+ animatedTails[slot].set(state.positions[tailJoints[slot]]);
+ return;
+ }
+ const direction = vec3.transformQuat(new Float64Array(3), axes[slot], state.rotations[joint]);
+ vec3.scaleAndAdd(animatedTails[slot], state.positions[joint], direction, lengthOf(slot, state));
+ });
+ }
+
+ function pushOutOfColliders(point, head, state) {
+ for (const collider of colliderBones) {
+ const scale = state.scales[collider.joint];
+ const rotation = state.rotations[collider.joint];
+ const center = vec3.transformQuat(scratch.center, collider.offset, rotation);
+ vec3.scaleAndAdd(center, state.positions[collider.joint], center, scale);
+ const radius = collider.radius * scale + chain.hitRadius;
+ let nearest = center;
+ if (collider.type === 'capsule') {
+ const end = vec3.transformQuat(scratch.end, collider.tail, rotation);
+ vec3.scaleAndAdd(end, state.positions[collider.joint], end, scale);
+ vec3.subtract(scratch.axis, end, center);
+ const lengthSquared = vec3.squaredLength(scratch.axis);
+ vec3.subtract(scratch.offset, point, center);
+ const along = lengthSquared < NEAR_ZERO ? 0 : Math.min(1, Math.max(0, vec3.dot(scratch.offset, scratch.axis) / lengthSquared));
+ nearest = vec3.scaleAndAdd(scratch.nearest, center, scratch.axis, along);
+ }
+ vec3.subtract(scratch.offset, point, nearest);
+ const distance = vec3.length(scratch.offset);
+ if (distance >= radius) continue;
+ if (distance < NEAR_ZERO) {
+ vec3.subtract(scratch.offset, point, head);
+ }
+ vec3.normalize(scratch.offset, scratch.offset);
+ vec3.scaleAndAdd(point, nearest, scratch.offset, radius);
+ }
+ }
+
+ function stepChain(stepSeconds, context, weight) {
+ const { state, prepared: rig, update, setWorldRotation, localRotations } = context;
+ joints.forEach((joint, slot) => {
+ localRotations[joint].set(animatedRotations[slot]);
+ });
+ update();
+ joints.forEach((joint, slot) => {
+ const head = state.positions[joint];
+ const parent = rig.joints[joint].parent;
+ const parentRotation = parent >= 0 ? state.rotations[parent] : rig.rootRotation;
+ const animatedWorld = quat.multiply(scratch.rotation, parentRotation, animatedRotations[slot]);
+ const animatedDirection = vec3.transformQuat(scratch.animatedDirection, axes[slot], animatedWorld);
+ const length = lengthOf(slot, state);
+ const next = scratch.next;
+ if (stepSeconds > 0) {
+ const current = tails[slot];
+ const previous = previousTails[slot];
+ const inertia = 1 - chain.dragForce;
+ for (let axis = 0; axis < 3; axis++) {
+ next[axis] = current[axis]
+ + (current[axis] - previous[axis]) * inertia
+ + animatedDirection[axis] * chain.stiffness * stepSeconds
+ + gravityDirection[axis] * chain.gravityPower * stepSeconds;
+ }
+ } else {
+ next.set(tails[slot]);
+ }
+ const keepLength = point => {
+ vec3.subtract(scratch.direction, point, head);
+ if (vec3.length(scratch.direction) < NEAR_ZERO) vec3.copy(scratch.direction, animatedDirection);
+ vec3.normalize(scratch.direction, scratch.direction);
+ vec3.scaleAndAdd(point, head, scratch.direction, length);
+ };
+ keepLength(next);
+ if (colliderBones.length) {
+ pushOutOfColliders(next, head, state);
+ keepLength(next);
+ }
+ if (stepSeconds > 0) previousTails[slot].set(tails[slot]);
+ tails[slot].set(next);
+ vec3.subtract(scratch.direction, next, head);
+ vec3.normalize(scratch.direction, scratch.direction);
+ const turn = quat.rotationTo(scratch.turn, animatedDirection, scratch.direction);
+ const worldRotation = quat.multiply(new Float64Array(4), turn, animatedWorld);
+ setWorldRotation(joint, quat.normalize(worldRotation, worldRotation), weight);
+ });
+ }
+
+ function solve(time, context, weight) {
+ const { state, localRotations, update } = context;
+ joints.forEach((joint, slot) => animatedRotations[slot].set(localRotations[joint]));
+ readAnimatedTails(state);
+ // Time counts in whole steps, so frame times that differ by rounding do not change how many steps run.
+ const stepIndex = Math.floor(time / SPRING_STEP_SECONDS + STEP_ROUNDING);
+ const steps = lastStep === null ? Number.NaN : stepIndex - lastStep;
+ const restart = !(steps >= 0 && steps <= MAX_CATCH_UP_STEPS);
+ lastStep = stepIndex;
+ if (restart) {
+ animatedTails.forEach((tail, slot) => {
+ tails[slot].set(tail);
+ previousTails[slot].set(tail);
+ });
+ return { reached: true, error: 0, warnings: [], limited: [] };
+ }
+ if (steps === 0) {
+ stepChain(0, context, weight);
+ } else {
+ for (let step = 0; step < steps; step++) stepChain(SPRING_STEP_SECONDS, context, weight);
+ }
+ update();
+ return { reached: true, error: 0, warnings: [], limited: [] };
+ }
+
+ return { joints, solve };
+ };
+}
diff --git a/tests/agent-motion-springs.test.js b/tests/agent-motion-springs.test.js
new file mode 100644
index 00000000..52bd49a4
--- /dev/null
+++ b/tests/agent-motion-springs.test.js
@@ -0,0 +1,101 @@
+import './support/load-agent-scene-modules.mjs';
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { mat4 } from 'gl-matrix';
+import { createAgentScene, loadAgentSceneModules } from '../src/agent-scene.js';
+import { AGENT_SCENE_CAPABILITIES } from '../src/agent-scene-capabilities.js';
+
+const FRAME = 1 / 30;
+
+/** A hips node that slides along X, with a tail of three bones along -Z. Each bone carries a small box to read its position. */
+function tailRecipe(springs, extraMotion = {}) {
+ const bone = (id, parent) => ({ id, parent, translation: [0, 0, -0.3] });
+ const marker = (id, parent) => ({ id: `${id}-mesh`, parent, geometry: 'box', material: 'paint', scale: [0.02, 0.02, 0.02] });
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'box', type: 'box', bevel: 0 }],
+ materials: [{ id: 'paint', color: [0.6, 0.6, 0.6] }],
+ nodes: [
+ { id: 'hips', translation: [0, 1, 0] },
+ bone('tail1', 'hips'), bone('tail2', 'tail1'), bone('tail3', 'tail2'), bone('tailEnd', 'tail3'),
+ marker('tail3', 'tail3'), marker('tailEnd', 'tailEnd'),
+ { id: 'body', parent: 'hips' },
+ ],
+ motion: {
+ duration: 6, loop: false,
+ tracks: [{ kind: 'node', id: 'hips', property: 'translation', interpolation: 'LINEAR', keyframes: [
+ { time: 0, value: [0, 1, 0] }, { time: 0.5, value: [0, 1, 0] }, { time: 0.75, value: [1, 1, 0] }, { time: 6, value: [1, 1, 0] },
+ ] }],
+ springs,
+ ...extraMotion,
+ },
+ };
+}
+
+const CHAIN = { bones: ['tail1', 'tail2', 'tail3'], stiffness: 2, dragForce: 0.05 };
+
+function tipAt(scene, time) {
+ scene.sampleMotion(time);
+ const part = scene.parts.find(candidate => candidate.name === 'tailEnd-mesh');
+ return Array.from(mat4.getTranslation(new Float64Array(3), part.matrix));
+}
+
+function playTip(scene, seconds) {
+ const tips = [];
+ for (let frame = 0; frame * FRAME <= seconds + 1e-9; frame++) tips.push(tipAt(scene, frame * FRAME));
+ return tips;
+}
+
+test('a recipe tail lags the sliding hips, overshoots and settles, the same on every run', async () => {
+ const recipe = tailRecipe({ chains: [CHAIN] });
+ await loadAgentSceneModules(recipe);
+ const first = playTip(createAgentScene(recipe), 6);
+ const second = playTip(createAgentScene(recipe), 6);
+ assert.deepEqual(second, first);
+ const hipsX = time => Math.min(1, Math.max(0, (time - 0.5) / 0.25));
+ const lag = first[Math.round(0.7 / FRAME)][0] - hipsX(0.7);
+ assert.ok(lag < -0.05, `the tip trails the hips by ${lag}`);
+ assert.ok(Math.max(...first.map(tip => tip[0])) > 1.02, 'the tip swings past the hips');
+ assert.ok(Math.abs(first[first.length - 1][0] - 1) < 0.01, 'the tip settles under the hips');
+});
+
+test('the exported recipe keeps every default so a bake or an agent reads the same springs', async () => {
+ const recipe = tailRecipe({ chains: [CHAIN], colliders: [{ id: 'ball', bone: 'body', radius: 0.2 }] });
+ await loadAgentSceneModules(recipe);
+ const exported = createAgentScene(recipe).exportRecipe().motion.springs;
+ assert.deepEqual(exported.chains[0], {
+ bones: ['tail1', 'tail2', 'tail3'], stiffness: 2, dragForce: 0.05, gravityPower: 0, gravityDir: [0, -1, 0], hitRadius: 0.02, tipLength: 0.07, colliders: [],
+ });
+ assert.deepEqual(exported.colliders[0], { id: 'ball', bone: 'body', type: 'sphere', offset: [0, 0, 0], radius: 0.2 });
+});
+
+test('a motion with only springs is valid, and a bad chain says which field to fix', async () => {
+ const recipe = tailRecipe({ chains: [CHAIN] });
+ recipe.motion.tracks = [];
+ await loadAgentSceneModules(recipe);
+ assert.doesNotThrow(() => createAgentScene(recipe));
+ const bad = tailRecipe({ chains: [{ ...CHAIN, bones: ['tail1', 'tail3'] }] });
+ assert.throws(() => createAgentScene(bad), /motion\.springs\.chains\[0\]\.bones\[1\]: got "tail3"; expected the child of tail1/);
+});
+
+test('a bake turns whole chains into keys that match the live springs', async () => {
+ const recipe = tailRecipe({ chains: [CHAIN] });
+ await loadAgentSceneModules(recipe);
+ const live = createAgentScene(recipe);
+ const liveTips = playTip(live, 1.9);
+ const baked = createAgentScene(recipe);
+ assert.throws(
+ () => baked.apply([{ type: 'bake-motion', nodes: ['tail1', 'tail2'], step: FRAME }], { expectedRevision: baked.revision }),
+ /spring chain.*tail3/,
+ );
+ baked.apply([{ type: 'bake-motion', nodes: ['tail1', 'tail2', 'tail3'], start: 0, end: 1.9, step: FRAME }], { expectedRevision: baked.revision });
+ assert.equal(baked.exportRecipe().motion.springs, undefined, 'the chain is gone once its result is keys');
+ const bakedTips = playTip(baked, 1.9);
+ bakedTips.forEach((tip, index) => {
+ for (let axis = 0; axis < 3; axis++) assert.ok(Math.abs(tip[axis] - liveTips[index][axis]) < 0.01, `frame ${index} axis ${axis}: ${tip[axis]} vs ${liveTips[index][axis]}`);
+ });
+});
+
+test('springs are listed in scene_capabilities', () => {
+ assert.match(AGENT_SCENE_CAPABILITIES.springBones, /motion\.springs/);
+});
diff --git a/tests/spring-bones.test.js b/tests/spring-bones.test.js
new file mode 100644
index 00000000..62b45a33
--- /dev/null
+++ b/tests/spring-bones.test.js
@@ -0,0 +1,167 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createSkeletonPose } from '../src/skeleton-pose.js';
+import {
+ MAX_SPRING_CHAINS, SPRING_STEP_SECONDS, normalizeSpringBones, springChainSolver,
+} from '../src/spring-bones.js';
+
+const FRAME = 1 / 30;
+
+// A hips joint with a tail of four bones along -Z, 0.3 long each, plus a body joint for colliders to ride on.
+function tailRig() {
+ const joint = (name, parent, translation) => ({ name, parent, translation, rotation: [0, 0, 0, 1] });
+ return {
+ mapping: {},
+ joints: [
+ joint('hips', -1, [0, 1, 0]),
+ joint('tail1', 0, [0, 0, -0.3]),
+ joint('tail2', 1, [0, 0, -0.3]),
+ joint('tail3', 2, [0, 0, -0.3]),
+ joint('tailEnd', 3, [0, 0, -0.3]),
+ joint('body', 0, [0, 0, 0]),
+ ],
+ };
+}
+
+const NODES = ['hips', 'tail1', 'tail2', 'tail3', 'tailEnd', 'body'];
+const RIG = tailRig();
+const HIERARCHY = RIG.joints.map(entry => ({ id: entry.name, parent: entry.parent < 0 ? null : RIG.joints[entry.parent].name }));
+const OPTIONS = { movable: new Set(NODES), visible: new Set(NODES), hierarchy: HIERARCHY };
+
+function springs(overrides = {}, colliders = []) {
+ return normalizeSpringBones({ chains: [{ bones: ['tail1', 'tail2', 'tail3'], ...overrides }], colliders }, OPTIONS);
+}
+
+function poseWith(normalized) {
+ return createSkeletonPose({
+ rig: tailRig(),
+ ik: normalized.chains.map(chain => ({ type: 'custom', create: springChainSolver(chain, normalized.colliders) })),
+ });
+}
+
+// The hips slide 1 m along +X between 0.5 s and 0.75 s, then stand still.
+function hipsX(time) {
+ return Math.min(1, Math.max(0, (time - 0.5) / 0.25));
+}
+
+function playTail(normalized, seconds, hipPath = hipsX) {
+ const pose = poseWith(normalized);
+ const frames = [];
+ for (let frame = 0; frame * FRAME <= seconds + 1e-9; frame++) {
+ const time = frame * FRAME;
+ pose.apply(time, (rotations, translations) => {
+ translations[0][0] = hipPath(time);
+ });
+ frames.push({
+ time,
+ hips: pose.jointWorld('hips').position,
+ tip: pose.jointWorld('tailEnd').position,
+ points: ['tail2', 'tail3', 'tailEnd'].map(name => pose.jointWorld(name).position),
+ });
+ }
+ return frames;
+}
+
+test('a tail lags the hips, overshoots, then settles on the animated pose', () => {
+ const frames = playTail(springs({ stiffness: 2, dragForce: 0.05 }), 8);
+ const lagging = frames.find(frame => frame.time > 0.6 && frame.time < 0.8);
+ assert.ok(lagging.tip[0] < lagging.hips[0] - 0.05, `tip at ${lagging.tip[0]} should trail the hips at ${lagging.hips[0]}`);
+ const overshoot = Math.max(...frames.map(frame => frame.tip[0] - frame.hips[0]));
+ assert.ok(overshoot > 0.02, `tip should swing past the hips, got ${overshoot}`);
+ const last = frames[frames.length - 1];
+ assert.ok(Math.abs(last.tip[0] - last.hips[0]) < 0.01, `tip should settle under the hips, off by ${last.tip[0] - last.hips[0]}`);
+ assert.ok(Math.abs(last.tip[2] + 1.2) < 0.01, 'the tail keeps its length');
+});
+
+test('the same times give the same pose, bit for bit', () => {
+ const first = playTail(springs({ stiffness: 1.5, dragForce: 0.2, gravityPower: 0.5 }), 3);
+ const second = playTail(springs({ stiffness: 1.5, dragForce: 0.2, gravityPower: 0.5 }), 3);
+ assert.deepEqual(second, first);
+});
+
+test('a still root does not make the tail drift', () => {
+ const frames = playTail(springs({ stiffness: 1, dragForce: 0.4 }), 4, () => 0);
+ for (const frame of frames) {
+ assert.ok(Math.abs(frame.tip[0]) < 1e-12 && Math.abs(frame.tip[1] - 1) < 1e-12 && Math.abs(frame.tip[2] + 1.2) < 1e-9, `drifted to ${frame.tip}`);
+ }
+});
+
+test('gravity bends the tail down and the bones keep their length', () => {
+ const frames = playTail(springs({ stiffness: 0.5, gravityPower: 1 }), 4, () => 0);
+ const last = frames[frames.length - 1];
+ assert.ok(last.tip[1] < 0.9, `gravity should lower the tip, got y ${last.tip[1]}`);
+ const [second, third, tip] = last.points;
+ const gap = (from, to) => Math.hypot(to[0] - from[0], to[1] - from[1], to[2] - from[2]);
+ assert.ok(Math.abs(gap(second, third) - 0.3) < 1e-9 && Math.abs(gap(third, tip) - 0.3) < 1e-9, 'each bone keeps its length');
+});
+
+test('a sphere collider keeps the sagging tail outside it', () => {
+ const colliders = [{ id: 'ball', bone: 'body', type: 'sphere', offset: [0, -0.55, -0.3], radius: 0.4 }];
+ const free = playTail(springs({ stiffness: 0.2, gravityPower: 1.5 }), 4, () => 0);
+ const blocked = playTail(springs({ stiffness: 0.2, gravityPower: 1.5, hitRadius: 0.05, colliders: ['ball'] }, colliders), 4, () => 0);
+ const clearance = point => Math.hypot(point[0], point[1] - 0.45, point[2] + 0.3);
+ assert.ok(free[free.length - 1].points.every(point => clearance(point) < 0.4), 'without the collider the tail hangs through the ball');
+ for (const frame of blocked.slice(10)) {
+ for (const point of frame.points) assert.ok(clearance(point) >= 0.45 - 0.02, `point ${point} is inside the collider`);
+ }
+});
+
+test('a capsule collider keeps the tail outside along its whole length', () => {
+ const colliders = [{ id: 'log', bone: 'body', type: 'capsule', offset: [-0.5, -0.6, -0.3], tail: [0.5, -0.6, -0.3], radius: 0.15 }];
+ const blocked = playTail(springs({ stiffness: 0.2, gravityPower: 1.5, hitRadius: 0, colliders: ['log'] }, colliders), 4, () => 0);
+ for (const frame of blocked.slice(10)) {
+ for (const point of frame.points) {
+ assert.ok(Math.hypot(point[1] - 0.4, point[2] + 0.3) >= 0.15 - 0.01, `point ${point} is inside the capsule`);
+ }
+ }
+});
+
+test('going back in time or a long gap restarts from the animated pose', () => {
+ const pose = poseWith(springs({ stiffness: 2, dragForce: 0.05 }));
+ const tipAt = time => {
+ pose.apply(time, (rotations, translations) => {
+ translations[0][0] = hipsX(time);
+ });
+ return pose.jointWorld('tailEnd').position;
+ };
+ for (let frame = 0; frame * FRAME < 0.7; frame++) tipAt(frame * FRAME);
+ assert.ok(tipAt(0.7)[0] < 0.65, 'the tip trails the hips');
+ assert.ok(Math.abs(tipAt(0.2)[0]) < 1e-12, 'a step back restarts at the animated pose');
+ assert.ok(Math.abs(tipAt(5)[0] - 1) < 1e-12, 'a gap over half a second restarts at the animated pose');
+});
+
+test('the step is fixed at 1/60 s', () => {
+ assert.equal(SPRING_STEP_SECONDS, 1 / 60);
+});
+
+test('a chain must list its bones from root to tip', () => {
+ assert.throws(() => springs({ bones: ['tail1', 'tail3'] }), /motion\.springs\.chains\[0\]\.bones\[1\]: got "tail3"; expected the child of tail1/);
+ assert.throws(() => springs({ bones: ['tail2', 'tail1'] }), /expected the child of tail2/);
+});
+
+test('fields are bounded and errors name the field and what to pass', () => {
+ assert.throws(() => springs({ stiffness: 9 }), /motion\.springs\.chains\[0\]\.stiffness: got 9; expected a number from 0 to 4/);
+ assert.throws(() => springs({ dragForce: -1 }), /dragForce: got -1; expected a number from 0 to 1/);
+ assert.throws(() => springs({ gravityDir: [0, 0, 0] }), /gravityDir: got \[0,0,0\]; expected a direction that is not zero/);
+ assert.throws(() => springs({ bones: [] }), /bones: got \[\]; expected one to 16 node IDs/);
+ assert.throws(() => springs({ bones: ['nowhere'] }), /bones\[0\]: got "nowhere"; expected a node ID in this recipe/);
+ assert.throws(() => springs({ colliders: ['missing'] }), /colliders: got "missing"; expected an ID listed in motion\.springs\.colliders/);
+ assert.throws(() => springs({ speed: 1 }), /Unknown or unsupported motion\.springs\.chains\[0\] field: speed/);
+ assert.throws(() => springs({}, [{ id: 'a b', bone: 'body', radius: 1 }]), /colliders\[0\]\.id: got "a b"/);
+ assert.throws(() => springs({}, [{ id: 'cap', bone: 'body', type: 'capsule', radius: 1 }]), /colliders\[0\]\.tail: got undefined; expected the capsule's second end/);
+ assert.throws(() => springs({}, [{ id: 'ball', bone: 'body', radius: 0 }]), /colliders\[0\]\.radius: got 0; expected a number from 0\.0001 to 100/);
+});
+
+test('chain counts, bones in total and duplicate bones are bounded', () => {
+ const chains = Array.from({ length: MAX_SPRING_CHAINS + 1 }, () => ({ bones: ['tail1'] }));
+ assert.throws(() => normalizeSpringBones({ chains }, OPTIONS), /motion\.springs\.chains must be a bounded dense array/);
+ assert.throws(() => normalizeSpringBones({ chains: [{ bones: ['tail1'] }, { bones: ['tail1'] }] }, OPTIONS), /chains\[1\]\.bones\[0\]: got "tail1"; expected a bone that no other chain uses/);
+ assert.throws(() => normalizeSpringBones({ chains: [] }, OPTIONS), /chains: got \[\]; expected one to 16 chains/);
+ const longChain = { bones: Array.from({ length: 17 }, (_, index) => `bone${index}`) };
+ assert.throws(() => normalizeSpringBones({ chains: [longChain] }, OPTIONS), /bones must be a bounded dense array/);
+});
+
+test('a bone with no child uses a virtual tip of tipLength and stays still at rest', () => {
+ const frames = playTail(springs({ bones: ['tailEnd'], tipLength: 0.5, stiffness: 1 }), 1, () => 0);
+ assert.deepEqual(frames[frames.length - 1].tip, frames[0].tip);
+});