From 8f966f14ff82972dda3bfedd4b598387e99ec9f9 Mon Sep 17 00:00:00 2001 From: rubenmarcus Date: Mon, 9 Nov 2026 03:10:03 +0000 Subject: [PATCH 01/31] Add optional named clips to the character pack contract Characters may now declare an animations.extra map of named clips beyond the states: fixed vocabulary names (locomotion, weapon handling, damage reactions, melee, round outcomes) or an emote_ prefix with a suffix. Keys match ^[a-z][a-z0-9_]{1,40}$; each entry carries file, duration, loop, rootMotion and source. Extra files are declared in files under the animations.extra. role, so duplicates, missing paths and the byte budget (extras included) are enforced before any payload is hashed, and each extra GLB must contain an animation named exactly as its key. Agent: Claude Code Signed-off-by: rubenmarcus --- docs/character-pack.md | 25 ++++++++++++---- schemas/asset-pack.schema.json | 18 +++++++++++- tools/lib/character-pack.mjs | 53 ++++++++++++++++++++++++++++++++-- 3 files changed, 88 insertions(+), 8 deletions(-) diff --git a/docs/character-pack.md b/docs/character-pack.md index a4778aa..8b05b00 100644 --- a/docs/character-pack.md +++ b/docs/character-pack.md @@ -10,13 +10,13 @@ On top of the common fields (`schemaVersion`, `kind`, `id`, `version`, `source`, | --- | --- | | `model` | One package path ending in `.glb`: the rigged, skinned character. | | `skeleton` | `"meshy-28"` (see below). | -| `animations` | Object keyed by state. Required: `idle`, `walk`, `run`, `shoot`, `death`, `crouch`, `crouchwalk`, `jump`. Optional: `idle1h`, `walk1h`, `walkfire`. No other keys. Each value is a distinct `.glb` path. | +| `animations` | Object keyed by state. Required: `idle`, `walk`, `run`, `shoot`, `death`, `crouch`, `crouchwalk`, `jump`. Optional: `idle1h`, `walk1h`, `walkfire`, plus one optional `extra` map of named clips (see below). No other keys. Each state value is a distinct `.glb` path. | | `previews` | At least one portrait image path (`.png`, `.jpg`, `.jpeg` or `.webp`). | | `rights` | `{ "status": "original" \| "public-domain" \| "political-satire", "basis": "", "references": ["", ...] }`; `references` is optional. | | `budgets` | `{ "triangles": , "bytes": }`. `triangles` bounds the model; `bytes` bounds the sum of every `files[].bytes`. | | `evidence` | Optional extra paths (for example a provenance sidecar). | -Every file in `files` must be declared by exactly one role (`model`, `animations.`, `previews`, `evidence`) and every declared path must appear in `files`. +Every file in `files` must be declared by exactly one role (`model`, `animations.`, `animations.extra.`, `previews`, `evidence`) and every declared path must appear in `files`. Extra-clip files count toward `budgets.bytes` like any other file. ```json { @@ -28,7 +28,8 @@ Every file in `files` must be declared by exactly one role (`model`, `animations "files": [{ "path": "model/capitao-caveira.glb", "sha256": "…", "bytes": 1 }], "model": "model/capitao-caveira.glb", "skeleton": "meshy-28", - "animations": { "idle": "animations/idle.glb", "walk": "animations/walk.glb", "…": "…" }, + "animations": { "idle": "animations/idle.glb", "walk": "animations/walk.glb", "…": "…", + "extra": { "strafe_left": { "file": "animations/extra/strafe-left.glb", "duration": 0.9, "loop": true, "rootMotion": false, "source": "Mixamo Strafe Left retargeted to meshy-28" } } }, "previews": ["previews/portrait.jpg"], "rights": { "status": "original", "basis": "Invented character; concept prompt forbids likeness of real people and existing characters." }, "budgets": { "triangles": 6000, "bytes": 8388608 } @@ -42,9 +43,23 @@ Every file in `files` must be declared by exactly one role (`model`, `animations - The model is a GLB 2 container with in-bounds buffer views and accessors, finite positions and in-range indices. Every primitive is a triangle list (mode 4), and the triangle count must not exceed `budgets.triangles`. - The model has exactly one skin, and `inverseBindMatrices` holds one float `MAT4` per joint. Every skinned primitive has a `JOINTS_0` unsigned byte/short `VEC4` and a float or normalized `WEIGHTS_0` `VEC4` per vertex, and every joint index stays inside the skin. - The skin is exactly meshy-28: 28 joints whose (name, nearest joint ancestor) pairs match the list below as a multiset. -- Each animation GLB contains an animation named exactly as its state that drives at least one meshy-28 bone through a `translation`, `rotation` or `scale` channel. A `weights` channel must target a mesh with morph targets. Every sampler has at least one float keyframe time and the output type and count that match its interpolation (and, for `weights`, the number of morph targets). +- Each animation GLB contains an animation named exactly as its state that drives at least one meshy-28 bone through a `translation`, `rotation` or `scale` channel. A `weights` channel must target a mesh with morph targets. Every sampler has at least one float keyframe time and the output type and count that match its interpolation (and, for `weights`, the number of morph targets). The same rules apply to every `animations.extra` clip, with the animation named exactly as its key. - Each preview starts with the PNG, JPEG or WebP signature for its extension. + +## Optional clips (`animations.extra`) + +`animations.extra` is an optional map of named clips beyond the states, for movement set, weapon handling, damage reactions, melee, round outcomes and emotes. Keys match `^[a-z][a-z0-9_]{1,40}$` and must be either a name from the fixed vocabulary below or an `emote_` prefix followed by at least one character. Anything else — including state names and the bare `emote_` prefix — is rejected. The vocabulary is `extraClipNames`/`extraClipPrefixes` in `tools/lib/character-pack.mjs`; the client mirrors it in `public/js/data/content-releases.js`. + +- Locomotion: `strafe_left`, `strafe_right`, `walk_back`, `run_back`, `strafe_left_pistol`, `strafe_right_pistol`, `walk_back_pistol` +- Weapon handling: `reload_rifle`, `reload_pistol`, `draw_rifle`, `holster_rifle`, `draw_pistol`, `holster_pistol` +- Damage reactions: `hit_front`, `hit_back`, `hit_left`, `hit_right`, `hit_head` +- Melee and utility: `grenade_throw`, `knife_idle`, `knife_stab` +- Round outcomes: `victory`, `defeat` +- Emotes: any key starting with `emote_` (for example `emote_danca`) + +Each entry is an object with exactly five fields: `file` (a distinct `.glb` package path, declared in `files`), `duration` (seconds, positive), `loop` (boolean), `rootMotion` (boolean) and `source` (provenance string, for example the source animation and rig pipeline). `duration`, `loop` and `rootMotion` are declared metadata for the runtime; the GLB itself still carries the authoritative keyframes. A missing `extra` map is valid — optional means absent, not empty promises. + ## meshy-28 The shared Meshy humanoid skeleton the runtime clips are baked against, taken from the client donor `public/models/characters/mst.glb` and identical in all 37 offline-rigged Creepypasta Season characters. Skin joint order, with the nearest joint ancestor in parentheses: @@ -63,7 +78,7 @@ Photos of real people never enter either repository. ## Checks -`npm run check` builds a synthetic character pack (a programmatic 12-triangle skinned GLB and eleven one-channel clips, no real asset bytes), validates it, and requires each contract mutant to be rejected for its stated reason: missing states, unknown state, misnamed clip, clip driving no meshy-28 bone, clip channel without a path, clip without keyframes or with mismatched output, wrong skeleton id, renamed, reparented or missing bone, missing skin or weights, missing, mistyped or out-of-skin `JOINTS_0`, triangle strips, bad GLB magic or version, triangle and byte budgets (including the byte budget before hashing), bad rights, missing or invalid previews, undeclared files, and hash or size mutations. +`npm run check` builds a synthetic character pack (a programmatic 12-triangle skinned GLB, one-channel state clips and two extra clips, no real asset bytes), validates it, and requires each contract mutant to be rejected for its stated reason: missing states, unknown state, misnamed clip, clip driving no meshy-28 bone, clip channel without a path, clip without keyframes or with mismatched output, wrong skeleton id, renamed, reparented or missing bone, missing skin or weights, missing, mistyped or out-of-skin `JOINTS_0`, triangle strips, bad GLB magic or version, triangle and byte budgets (including the byte budget before hashing), bad rights, missing or invalid previews, undeclared files, hash or size mutations, and the extra-clip rules: unknown, pattern-violating, state-colliding or bare-prefix names, entries with missing or mistyped fields, non-GLB files, missing, duplicate or misnamed clip files, and extras pushing the pack over its byte budget. ## Concept generation diff --git a/schemas/asset-pack.schema.json b/schemas/asset-pack.schema.json index 725e51d..4652c9b 100644 --- a/schemas/asset-pack.schema.json +++ b/schemas/asset-pack.schema.json @@ -109,7 +109,23 @@ "jump": { "$ref": "#/$defs/glbPath" }, "idle1h": { "$ref": "#/$defs/glbPath" }, "walk1h": { "$ref": "#/$defs/glbPath" }, - "walkfire": { "$ref": "#/$defs/glbPath" } + "walkfire": { "$ref": "#/$defs/glbPath" }, + "extra": { + "type": "object", + "propertyNames": { "pattern": "^[a-z][a-z0-9_]{1,40}$" }, + "additionalProperties": { + "type": "object", + "required": ["file", "duration", "loop", "rootMotion", "source"], + "properties": { + "file": { "$ref": "#/$defs/glbPath" }, + "duration": { "type": "number", "exclusiveMinimum": 0 }, + "loop": { "type": "boolean" }, + "rootMotion": { "type": "boolean" }, + "source": { "type": "string", "minLength": 1 } + }, + "additionalProperties": false + } + } }, "additionalProperties": false }, diff --git a/tools/lib/character-pack.mjs b/tools/lib/character-pack.mjs index 2bef959..01c3fdb 100644 --- a/tools/lib/character-pack.mjs +++ b/tools/lib/character-pack.mjs @@ -4,6 +4,24 @@ import { inspectGlb, readAccessorComponent, readGlb } from './glb-inspect.mjs'; export const requiredCharacterStates = Object.freeze(['idle', 'walk', 'run', 'shoot', 'death', 'crouch', 'crouchwalk', 'jump']); export const optionalCharacterStates = Object.freeze(['idle1h', 'walk1h', 'walkfire']); +// Optional named clips a pack may carry beyond the states, as `animations.extra` entries. +// Fixed names for locomotion, weapon handling, damage reactions, melee and round outcomes, +// plus free-form emotes under the `emote_` prefix (at least one character after the prefix). +// State names are never valid extra names, so the two key spaces stay disjoint. +export const extraClipNames = Object.freeze([ + 'strafe_left', 'strafe_right', 'walk_back', 'run_back', + 'strafe_left_pistol', 'strafe_right_pistol', 'walk_back_pistol', + 'reload_rifle', 'reload_pistol', 'draw_rifle', 'holster_rifle', 'draw_pistol', 'holster_pistol', + 'hit_front', 'hit_back', 'hit_left', 'hit_right', 'hit_head', + 'grenade_throw', 'knife_idle', 'knife_stab', 'victory', 'defeat', +]); +export const extraClipPrefixes = Object.freeze(['emote_']); + +export function isExtraClipName(name) { + return extraClipNames.includes(name) + || extraClipPrefixes.some(prefix => name.length > prefix.length && name.startsWith(prefix)); +} + // The shared Meshy humanoid skeleton every runtime clip is baked against: skin joint order // and the nearest joint ancestor of each joint (null for the root). Derived from the client // donor `public/models/characters/mst.glb` and the 37 offline-rigged lote30 characters; the @@ -29,13 +47,32 @@ const imageMagic = [ export function characterRoleEntries(manifest) { if (manifest.kind !== 'character') return []; const entries = [{ role: 'model', path: manifest.model }]; - for (const [state, file] of Object.entries(manifest.animations || {})) entries.push({ role: `animations.${state}`, path: file }); + for (const [state, file] of Object.entries(manifest.animations || {})) { + if (state === 'extra') continue; + entries.push({ role: `animations.${state}`, path: file }); + } + entries.push(...characterExtraEntries(manifest)); for (const role of ['previews', 'evidence']) { for (const file of manifest[role] || []) entries.push({ role, path: file }); } return entries; } +// Extra-clip role entries. This is also the structural gate that rejects names outside the +// vocabulary (bare prefixes, state names, anything else) during validateManifestStructure, +// before any payload is hashed. +export function characterExtraEntries(manifest) { + const extras = manifest.animations?.extra; + if (extras === undefined) return []; + if (typeof extras !== 'object' || Array.isArray(extras)) throw new Error('animations.extra must be an object keyed by extra clip name'); + const entries = []; + for (const [name, entry] of Object.entries(extras)) { + if (!isExtraClipName(name)) throw new Error(`animations.extra has an unknown clip name: ${name}`); + entries.push({ role: `animations.extra.${name}`, path: entry?.file }); + } + return entries; +} + const pairKey = ([name, parent]) => `${name}<${parent ?? ''}`; function multiset(pairs) { @@ -179,9 +216,21 @@ export async function validateCharacterPack(manifest, absolutes) { } for (const [state, file] of Object.entries(manifest.animations)) { + if (state === 'extra') continue; const { document } = await readGlb(absolutes.get(file), file); assertStateAnimation(document, state, file); } + for (const [name, entry] of Object.entries(manifest.animations.extra || {})) { + const { document } = await readGlb(absolutes.get(entry.file), entry.file); + assertStateAnimation(document, name, entry.file); + } for (const file of manifest.previews) await assertImage(file, absolutes.get(file)); - return { triangles: model.triangles, bytes: characterDeclaredBytes(manifest), joints: meshy28Joints.length, animations: Object.keys(manifest.animations).length }; + const states = Object.keys(manifest.animations).filter(key => key !== 'extra').length; + return { + triangles: model.triangles, + bytes: characterDeclaredBytes(manifest), + joints: meshy28Joints.length, + animations: states, + extraClips: Object.keys(manifest.animations.extra || {}).length, + }; } From 011b058954f070e57c3e8a06c275a566771a2455 Mon Sep 17 00:00:00 2001 From: rubenmarcus Date: Mon, 9 Nov 2026 03:10:08 +0000 Subject: [PATCH 02/31] Require every extra-clip rule with synthetic mutants The valid fixture now ships two extra clips (a vocabulary name and an emote_ name) and a no-extras pack stays valid. Twelve new mutants cover the contract: unknown, state-colliding, bare-prefix and pattern-violating names; missing, duplicated, shared, non-GLB and misnamed clip files; entries with missing or mistyped fields; and extras pushing the pack over its byte budget. Agent: Claude Code Signed-off-by: rubenmarcus --- tools/checks/character-pack-check.mjs | 65 +++++++++++++++++++++++++-- 1 file changed, 61 insertions(+), 4 deletions(-) diff --git a/tools/checks/character-pack-check.mjs b/tools/checks/character-pack-check.mjs index 15524c9..e90ac50 100755 --- a/tools/checks/character-pack-check.mjs +++ b/tools/checks/character-pack-check.mjs @@ -127,6 +127,8 @@ const allStates = [...requiredCharacterStates, ...optionalCharacterStates]; function validFiles() { const files = { 'model/fixture-character.glb': modelGlb(), 'previews/portrait.png': png }; for (const state of allStates) files[`animations/${state}.glb`] = clipGlb(state); + files['animations/extra/strafe-left.glb'] = clipGlb('strafe_left'); + files['animations/extra/emote-danca.glb'] = clipGlb('emote_danca'); return files; } @@ -140,7 +142,13 @@ function manifestFor(files) { files: Object.entries(files).map(([file, bytes]) => ({ path: file, sha256: sha256(bytes), bytes: bytes.length })), model: 'model/fixture-character.glb', skeleton: 'meshy-28', - animations: Object.fromEntries(allStates.map(state => [state, `animations/${state}.glb`])), + animations: { + ...Object.fromEntries(allStates.map(state => [state, `animations/${state}.glb`])), + extra: { + strafe_left: { file: 'animations/extra/strafe-left.glb', duration: 0.8, loop: true, rootMotion: false, source: 'Synthetic strafe-left fixture clip' }, + emote_danca: { file: 'animations/extra/emote-danca.glb', duration: 2.5, loop: false, rootMotion: false, source: 'Synthetic emote fixture clip' }, + }, + }, previews: ['previews/portrait.png'], rights: { status: 'original', basis: 'Invented synthetic test character with no likeness or third-party design.' }, budgets: { triangles: 100, bytes: 1048576 }, @@ -177,11 +185,18 @@ const dropState = state => manifest => { manifest.files = manifest.files.filter(file => file.path !== `animations/${state}.glb`); }; +const dropExtras = manifest => { + for (const entry of Object.values(manifest.animations.extra || {})) { + manifest.files = manifest.files.filter(file => file.path !== entry.file); + } + delete manifest.animations.extra; +}; + try { const valid = await validateCase(); - console.log(`PASS Valid synthetic character pack (${valid.character.triangles} triangles, ${valid.character.joints} meshy-28 joints, ${valid.character.animations} state clips)`); - const requiredOnly = await validateCase({ mutate: manifest => optionalCharacterStates.forEach(state => dropState(state)(manifest)) }); - console.log(`PASS Valid character pack with only the ${requiredOnly.character.animations} required states`); + console.log(`PASS Valid synthetic character pack (${valid.character.triangles} triangles, ${valid.character.joints} meshy-28 joints, ${valid.character.animations} state clips, ${valid.character.extraClips} extra clips)`); + const requiredOnly = await validateCase({ mutate: manifest => { optionalCharacterStates.forEach(state => dropState(state)(manifest)); dropExtras(manifest); } }); + console.log(`PASS Valid character pack with only the ${requiredOnly.character.animations} required states and ${requiredOnly.character.extraClips} extra clips`); await validateCase({ replace: { 'animations/idle.glb': clipGlb('idle', { morph: 'valid' }) } }); console.log('PASS Valid clip with a bone channel plus a morph-weights channel'); @@ -201,6 +216,48 @@ try { await expectRejection('Clip without keyframes', /animation "death" has no keyframes/, { replace: { 'animations/death.glb': clipGlb('death', { keyframes: 0 }) } }); await expectRejection('Clip output count differs from keyframes', /output values that do not match its rotation keyframes/, { replace: { 'animations/crouch.glb': clipGlb('crouch', { keyframes: 2, outputValues: 1 }) } }); await expectRejection('Same clip declared for two states', /Duplicate declared path/, { mutate: manifest => { manifest.animations.walk = manifest.animations.idle; } }); + await expectRejection('Unknown extra clip name', /animations\.extra has an unknown clip name: moonwalk/, { + replace: { 'animations/extra/moonwalk.glb': clipGlb('moonwalk') }, + mutate: manifest => { manifest.animations.extra.moonwalk = { file: 'animations/extra/moonwalk.glb', duration: 1, loop: false, rootMotion: false, source: 'Not in the vocabulary' }; }, + }); + await expectRejection('Extra clip name equal to a state', /unknown clip name: idle/, { + mutate: manifest => { manifest.animations.extra.idle = manifest.animations.extra.strafe_left; }, + }); + await expectRejection('Bare emote prefix as an extra clip name', /unknown clip name: emote_/, { + replace: { 'animations/extra/emote-puro.glb': clipGlb('emote_') }, + mutate: manifest => { manifest.animations.extra.emote_ = { file: 'animations/extra/emote-puro.glb', duration: 1, loop: false, rootMotion: false, source: 'Bare prefix' }; }, + }); + await expectRejection('Extra clip name outside the key pattern', /\/animations\/extra must match pattern "\^\[a-z\]\[a-z0-9_\]\{1,40\}\$"/, { + replace: { 'animations/extra/Strafe-left.glb': clipGlb('strafe_left') }, + mutate: manifest => { manifest.animations.extra.Strafe_left = { file: 'animations/extra/Strafe-left.glb', duration: 1, loop: true, rootMotion: false, source: 'Uppercase key' }; }, + }); + await expectRejection('Extra clip file missing from files', /Declared path is missing from files: animations\/extra\/strafe-left\.glb/, { + mutate: manifest => { manifest.files = manifest.files.filter(file => file.path !== 'animations/extra/strafe-left.glb'); }, + }); + await expectRejection('Extra clip file shared with a state', /Duplicate declared path: animations\/idle\.glb \(animations\.idle and animations\.extra\.strafe_left\)/, { + mutate: manifest => { manifest.animations.extra.strafe_left.file = manifest.animations.idle; }, + }); + await expectRejection('Extras counted in the byte budget', /over its \d+-byte budget/, { + mutate: manifest => { + const extraBytes = manifest.files.filter(file => file.path.startsWith('animations/extra/')).reduce((sum, file) => sum + file.bytes, 0); + manifest.budgets.bytes = manifest.files.reduce((sum, file) => sum + file.bytes, 0) - extraBytes; + }, + }); + await expectRejection('Extra clip misnamed inside its GLB', /animations\/extra\/strafe-left\.glb: no animation named "strafe_left"/, { + replace: { 'animations/extra/strafe-left.glb': clipGlb('Strafe') }, + }); + await expectRejection('Extra clip file is not a GLB', /animations\/extra\/strafe_left\/file must match pattern/, { + mutate: manifest => { manifest.animations.extra.strafe_left.file = 'animations/extra/strafe-left.gltf'; }, + }); + await expectRejection('Extra entry missing a required field', /animations\/extra\/strafe_left must have required property 'duration'/, { + mutate: manifest => { delete manifest.animations.extra.strafe_left.duration; }, + }); + await expectRejection('Extra entry with a mistyped loop', /animations\/extra\/strafe_left\/loop must be boolean/, { + mutate: manifest => { manifest.animations.extra.strafe_left.loop = 'yes'; }, + }); + await expectRejection('Extra entry with a non-numeric duration', /animations\/extra\/strafe_left\/duration must be number/, { + mutate: manifest => { manifest.animations.extra.strafe_left.duration = '0.8'; }, + }); await expectRejection('Wrong skeleton id', /\/skeleton must be equal to constant/, { mutate: manifest => { manifest.skeleton = 'mixamo-65'; } }); const renamed = meshy28Joints.map(([name, parent]) => [name === 'LeftForeArm' ? 'LeftElbow' : name, parent === 'LeftForeArm' ? 'LeftElbow' : parent]); From 76ab7f734cb4068571164836be0c042f3a4431b5 Mon Sep 17 00:00:00 2001 From: rubenmarcus Date: Mon, 9 Nov 2026 03:34:39 +0000 Subject: [PATCH 03/31] Share the synthetic humanoid and let the pose test measure any clip The tube humanoid moves out of character-rig-check into tools/checks/lib so the animation check can skin clips on it (it also takes another joint layout). rig-pose-test gains --states and --samples, so a QA gate can run it on clips other than the 11 state clips. Agent: Claude Code Signed-off-by: rubenmarcus --- tools/characters/rig-pose-test.mjs | 17 ++-- tools/checks/character-rig-check.mjs | 111 +--------------------- tools/checks/lib/synthetic-humanoid.mjs | 118 ++++++++++++++++++++++++ 3 files changed, 130 insertions(+), 116 deletions(-) create mode 100644 tools/checks/lib/synthetic-humanoid.mjs diff --git a/tools/characters/rig-pose-test.mjs b/tools/characters/rig-pose-test.mjs index de99e52..bf161ac 100755 --- a/tools/characters/rig-pose-test.mjs +++ b/tools/characters/rig-pose-test.mjs @@ -1,12 +1,13 @@ #!/usr/bin/env node // Numeric pose test of a skinned meshy-28 GLB (docs/character-rig.md). // -// node tools/characters/rig-pose-test.mjs [--clips=] [--out=] -// [--label=] [--strict] [--bake=[@]:]... +// node tools/characters/rig-pose-test.mjs [--clips=] [--states=] [--samples=] +// [--out=] [--label=] [--strict] [--bake=[@]:]... // // Skins the mesh on the CPU exactly like three.js and measures, for five synthetic poses // (arms up 90°, arms forward 60°, a step with each leg, head turned 60°) and, with --clips, for -// 8 instants of each of the 11 state clips (use the clips retargeted to this model): the +// 8 instants (--samples) of each of the 11 state clips (use the clips retargeted to this model; +// --states measures other clips of the directory, e.g. --states=reload,grenade-throw): the // longest edge stretch versus the bind pose, the 99th percentile, the upper-back and hand // regions, how far welded seam vertices drift apart, and the 10 worst vertices with their // bones. --strict exits 1 when tools/lib/character-rig.mjs#POSE_THRESHOLDS fail. @@ -25,11 +26,13 @@ const args = process.argv.slice(2); const flag = (name) => args.find((a) => a.startsWith(`--${name}=`))?.slice(name.length + 3); const model = args.find((a) => !a.startsWith('--')); if (!model) { - console.error('usage: rig-pose-test.mjs [--clips=] [--out=] [--label=] [--strict] [--bake=[@]:]'); + console.error('usage: rig-pose-test.mjs [--clips=] [--states=] [--samples=] [--out=] [--label=] [--strict] [--bake=[@]:]'); process.exit(1); } const io = new NodeIO().registerExtensions(ALL_EXTENSIONS); const clipsDir = flag('clips'); +const states = flag('states') ? flag('states').split(',').filter(Boolean) : CLIP_STATES; +const samples = Math.max(2, Number(flag('samples') || CLIP_SAMPLES)); const rig = loadRig(await io.read(model)); const setup = measureSetup(rig); const poses = []; @@ -39,14 +42,14 @@ for (const pose of SYNTHETIC_POSES) { poses.push({ kind: 'synthetic', name: pose.name, ...measurePose(rig, setup, skinPositions(rig, syntheticOverrides(rig, pose))) }); } if (clipsDir) { - for (const state of CLIP_STATES) { + for (const state of states) { const file = path.join(clipsDir, `${state}.glb`); if (!existsSync(file)) throw new Error(`missing clip ${file}`); const sampler = clipSampler(await io.read(file)); if (!sampler) throw new Error(`${file}: no animation`); samplers.set(state, sampler); - for (let k = 0; k < CLIP_SAMPLES; k += 1) { - const fraction = k / (CLIP_SAMPLES - 1); + for (let k = 0; k < samples; k += 1) { + const fraction = k / (samples - 1); const time = +(sampler.duration * fraction).toFixed(4); poses.push({ kind: 'clip', name: state, time, ...measurePose(rig, setup, skinPositions(rig, clipOverrides(rig, sampler, time))) }); } diff --git a/tools/checks/character-rig-check.mjs b/tools/checks/character-rig-check.mjs index f6052a6..3611ad5 100755 --- a/tools/checks/character-rig-check.mjs +++ b/tools/checks/character-rig-check.mjs @@ -14,9 +14,10 @@ import { Document } from '@gltf-transform/core'; import * as THREE from 'three'; import { meshy28Joints } from '../lib/character-pack.mjs'; import { - ALIGNED_BONES, MESHY28_REST_WORLD, SYNTHETIC_POSES, assembleMeshy28Model, buildMeshy28Skeleton, deformJointNames, evaluatePoseReport, + ALIGNED_BONES, MESHY28_REST_WORLD, SYNTHETIC_POSES, assembleMeshy28Model, deformJointNames, evaluatePoseReport, loadRig, measurePose, measureSetup, skinPositions, summarize, syntheticOverrides, uniqueJointNames, validateJoints, } from '../lib/character-rig.mjs'; +import { J, TIPS, synthBody, synthDocument } from './lib/synthetic-humanoid.mjs'; const root = fileURLToPath(new URL('../../', import.meta.url)); let failures = 0; @@ -67,116 +68,8 @@ clause('R1 the Blender steps use the contract meshy-28 list', () => { }); // ------------------------------------------------------------------------------ synthetic body -// glTF space: +Y up, faces +Z, character left is +X. Joints follow the donor layout. -const J = { - Hips: [0, 0.83, -0.02], LeftUpLeg: [0.08, 0.75, -0.01], LeftLeg: [0.1, 0.42, 0.03], LeftFoot: [0.11, 0.1, 0], LeftToeBase: [0.13, 0.04, 0.11], - RightUpLeg: [-0.08, 0.75, -0.01], RightLeg: [-0.1, 0.42, 0.03], RightFoot: [-0.11, 0.1, 0], RightToeBase: [-0.13, 0.04, 0.11], - Spine02: [0, 0.96, 0], Spine01: [0, 1.09, 0], Spine: [0, 1.22, 0], - LeftShoulder: [0.035, 1.25, 0], LeftArm: [0.17, 1.25, 0], LeftForeArm: [0.4, 1.25, 0], LeftHand: [0.62, 1.25, 0], - RightShoulder: [-0.035, 1.25, 0], RightArm: [-0.17, 1.25, 0], RightForeArm: [-0.4, 1.25, 0], RightHand: [-0.62, 1.25, 0], - neck: [0, 1.32, 0], Head: [0, 1.39, 0], head_end: [0, 1.7, 0], headfront: [0, 1.39, 0.12], Curl_R: [-0.62, 1.25, 0], Curl_L: [0.62, 1.25, 0], -}; -const TIPS = { LeftHandTip: [0.72, 1.25, 0], RightHandTip: [-0.72, 1.25, 0] }; const cleanJoints = Object.fromEntries(Object.entries(J).map(([n, [x, y, z]]) => [n, [x, -z, y]])); -/** Tubes along joint chains; each ring is weighted by a smoothstep blend around every joint. */ -function synthBody({ mutant = null } = {}) { - const positions = [], joints = [], weights = [], indices = []; - const slot = new Map(meshy28Joints.map(([name], i) => [name, i]).reverse()); - const tube = (chain, radius, step = 0.02, sides = 8, blend = 0.05) => { - const points = chain.map((n) => new THREE.Vector3(...(Array.isArray(n) ? n : J[n]))); - const names = chain.map((n) => (Array.isArray(n) ? null : n)); - const total = points.slice(1).reduce((s, p, i) => s + p.distanceTo(points[i]), 0); - const rings = Math.max(2, Math.round(total / step) + 1); - const start = positions.length / 3; - const segLen = points.slice(1).map((p, i) => p.distanceTo(points[i])); - for (let r = 0; r < rings; r += 1) { - let d = (r / (rings - 1)) * total, seg = 0; - while (seg < segLen.length - 1 && d > segLen[seg]) { d -= segLen[seg]; seg += 1; } - const a = points[seg], b = points[seg + 1]; - const centre = a.clone().lerp(b, Math.min(1, d / segLen[seg])); - const axis = b.clone().sub(a).normalize(); - const u = Math.abs(axis.y) < 0.9 ? new THREE.Vector3(0, 1, 0).cross(axis).normalize() : new THREE.Vector3(1, 0, 0).cross(axis).normalize(); - const v = axis.clone().cross(u); - // Bone owning this ring: the chain joint at the segment start. Within `blend` of a - // joint the ring is shared with the bone across it, 50/50 exactly at the joint. - const own = names[seg] ?? names[seg + 1]; - const next = names[seg + 1]; - const prev = seg > 0 ? names[seg - 1] : null; - const toNext = segLen[seg] - d; - let other = null, w = 0; - if (next && next !== own && toNext < blend) { other = next; w = 0.5 * (1 - toNext / blend); } - else if (prev && prev !== own && d < blend) { other = prev; w = 0.5 * (1 - d / blend); } - if (mutant === 'hard-step') w = 0; - for (let k = 0; k < sides; k += 1) { - const ang = (k / sides) * Math.PI * 2; - const p = centre.clone().addScaledVector(u, Math.cos(ang) * radius).addScaledVector(v, Math.sin(ang) * radius); - positions.push(p.x, p.y, p.z); - joints.push(slot.get(own), other ? slot.get(other) : 0, 0, 0); - weights.push(1 - w, w, 0, 0); - } - if (r > 0) for (let k = 0; k < sides; k += 1) { - const a0 = start + (r - 1) * sides + k, a1 = start + (r - 1) * sides + ((k + 1) % sides); - const b0 = start + r * sides + k, b1 = start + r * sides + ((k + 1) % sides); - indices.push(a0, b0, a1, a1, b0, b1); - } - } - }; - tube(['Hips', 'Spine02', 'Spine01', 'Spine', 'neck', 'Head', 'head_end'], 0.12); - tube(['LeftShoulder', 'LeftArm', 'LeftForeArm', 'LeftHand', [0.72, 1.25, 0]], 0.045); - tube(['RightShoulder', 'RightArm', 'RightForeArm', 'RightHand', [-0.72, 1.25, 0]], 0.045); - tube(['LeftUpLeg', 'LeftLeg', 'LeftFoot', 'LeftToeBase', [0.14, 0.03, 0.2]], 0.06); - tube(['RightUpLeg', 'RightLeg', 'RightFoot', 'RightToeBase', [-0.14, 0.03, 0.2]], 0.06); - if (mutant === 'arm-weight-on-torso') { - // Upper-back vertices of the spine tube take 60% LeftArm (the defect the part rules forbid). - for (let i = 0; i < positions.length / 3; i += 1) { - const [x, y, z] = positions.slice(i * 3, i * 3 + 3); - if (y > 1.1 && y < 1.3 && z < -0.05 && Math.abs(x) < 0.15 && joints[i * 4] !== slot.get('LeftArm')) { - joints[i * 4 + 1] = slot.get('LeftArm'); weights[i * 4] = 0.4; weights[i * 4 + 1] = 0.6; - } - } - } - if (mutant === 'split-seam') { - // Duplicate one spine-ring vertex (a UV seam) and weight the copy to the left arm. - const v = 40; - positions.push(...positions.slice(v * 3, v * 3 + 3)); - joints.push(slot.get('LeftArm'), 0, 0, 0); - weights.push(1, 0, 0, 0); - indices.push(v, positions.length / 3 - 1, v + 1); - } - if (mutant === 'hand-on-spine') { - // Every other ring of the left hand is skinned to Spine: lifting the arm tears the hand. - for (let i = 0; i < positions.length / 3; i += 1) { - const [x, y] = positions.slice(i * 3, i * 3 + 2); - if (x > 0.63 && Math.abs(y - 1.25) < 0.06 && Math.round((x - 0.62) / 0.02) % 2 === 1) { - joints.splice(i * 4, 4, slot.get('Spine'), 0, 0, 0); - weights.splice(i * 4, 4, 1, 0, 0, 0); - } - } - } - return { positions, joints, weights, indices }; -} - -function synthDocument(options = {}) { - const doc = new Document(); - const buffer = doc.createBuffer(); - const body = synthBody(options); - const prim = doc.createPrimitive() - .setAttribute('POSITION', doc.createAccessor().setType('VEC3').setArray(new Float32Array(body.positions)).setBuffer(buffer)) - .setAttribute('JOINTS_0', doc.createAccessor().setType('VEC4').setArray(new Uint16Array(body.joints)).setBuffer(buffer)) - .setAttribute('WEIGHTS_0', doc.createAccessor().setType('VEC4').setArray(new Float32Array(body.weights)).setBuffer(buffer)) - .setIndices(doc.createAccessor().setType('SCALAR').setArray(new Uint32Array(body.indices)).setBuffer(buffer)); - const meshNode = doc.createNode('Body').setMesh(doc.createMesh('Body').addPrimitive(prim)); - const skeleton = buildMeshy28Skeleton(doc, { ...J, ...TIPS }); - if (options.mutant === 'stale-ibm') skeleton.joints[13].setTranslation(skeleton.joints[13].getTranslation().map((v, i) => v + (i === 1 ? 5 : 0))); - const skin = doc.createSkin('meshy-28').setSkeleton(skeleton.joints[0]) - .setInverseBindMatrices(doc.createAccessor().setType('MAT4').setArray(skeleton.inverseBindMatrices).setBuffer(buffer)); - for (const node of skeleton.joints) skin.addJoint(node); - meshNode.setSkin(skin); - doc.createScene('scene').addChild(meshNode).addChild(skeleton.armature); - return doc; -} - function poseReport(doc) { const rig = loadRig(doc); const setup = measureSetup(rig); diff --git a/tools/checks/lib/synthetic-humanoid.mjs b/tools/checks/lib/synthetic-humanoid.mjs new file mode 100644 index 0000000..69af734 --- /dev/null +++ b/tools/checks/lib/synthetic-humanoid.mjs @@ -0,0 +1,118 @@ +// Synthetic meshy-28 humanoid for the Studio checks (no real asset bytes): tubes along the +// joint chains of the donor layout, skinned with smoothstep blends at each joint, on the +// skeleton tools/lib/character-rig.mjs#buildMeshy28Skeleton builds. Mutants inject the rig +// defects the pose test must catch. +import { Document } from '@gltf-transform/core'; +import * as THREE from 'three'; +import { meshy28Joints } from '../../lib/character-pack.mjs'; +import { buildMeshy28Skeleton } from '../../lib/character-rig.mjs'; + +// glTF space: +Y up, faces +Z, character left is +X. Joints follow the donor layout. +export const J = { + Hips: [0, 0.83, -0.02], LeftUpLeg: [0.08, 0.75, -0.01], LeftLeg: [0.1, 0.42, 0.03], LeftFoot: [0.11, 0.1, 0], LeftToeBase: [0.13, 0.04, 0.11], + RightUpLeg: [-0.08, 0.75, -0.01], RightLeg: [-0.1, 0.42, 0.03], RightFoot: [-0.11, 0.1, 0], RightToeBase: [-0.13, 0.04, 0.11], + Spine02: [0, 0.96, 0], Spine01: [0, 1.09, 0], Spine: [0, 1.22, 0], + LeftShoulder: [0.035, 1.25, 0], LeftArm: [0.17, 1.25, 0], LeftForeArm: [0.4, 1.25, 0], LeftHand: [0.62, 1.25, 0], + RightShoulder: [-0.035, 1.25, 0], RightArm: [-0.17, 1.25, 0], RightForeArm: [-0.4, 1.25, 0], RightHand: [-0.62, 1.25, 0], + neck: [0, 1.32, 0], Head: [0, 1.39, 0], head_end: [0, 1.7, 0], headfront: [0, 1.39, 0.12], Curl_R: [-0.62, 1.25, 0], Curl_L: [0.62, 1.25, 0], +}; +export const TIPS = { LeftHandTip: [0.72, 1.25, 0], RightHandTip: [-0.72, 1.25, 0] }; + +/** Tubes along joint chains (`joints`: another layout, same names); each ring is weighted by a + smoothstep blend around every joint. */ +export function synthBody({ mutant = null, joints: layout = J } = {}) { + const positions = [], joints = [], weights = [], indices = []; + const slot = new Map(meshy28Joints.map(([name], i) => [name, i]).reverse()); + const tube = (chain, radius, step = 0.02, sides = 8, blend = 0.05) => { + const points = chain.map((n) => new THREE.Vector3(...(Array.isArray(n) ? n : layout[n]))); + const names = chain.map((n) => (Array.isArray(n) ? null : n)); + const total = points.slice(1).reduce((s, p, i) => s + p.distanceTo(points[i]), 0); + const rings = Math.max(2, Math.round(total / step) + 1); + const start = positions.length / 3; + const segLen = points.slice(1).map((p, i) => p.distanceTo(points[i])); + for (let r = 0; r < rings; r += 1) { + let d = (r / (rings - 1)) * total, seg = 0; + while (seg < segLen.length - 1 && d > segLen[seg]) { d -= segLen[seg]; seg += 1; } + const a = points[seg], b = points[seg + 1]; + const centre = a.clone().lerp(b, Math.min(1, d / segLen[seg])); + const axis = b.clone().sub(a).normalize(); + const u = Math.abs(axis.y) < 0.9 ? new THREE.Vector3(0, 1, 0).cross(axis).normalize() : new THREE.Vector3(1, 0, 0).cross(axis).normalize(); + const v = axis.clone().cross(u); + // Bone owning this ring: the chain joint at the segment start. Within `blend` of a + // joint the ring is shared with the bone across it, 50/50 exactly at the joint. + const own = names[seg] ?? names[seg + 1]; + const next = names[seg + 1]; + const prev = seg > 0 ? names[seg - 1] : null; + const toNext = segLen[seg] - d; + let other = null, w = 0; + if (next && next !== own && toNext < blend) { other = next; w = 0.5 * (1 - toNext / blend); } + else if (prev && prev !== own && d < blend) { other = prev; w = 0.5 * (1 - d / blend); } + if (mutant === 'hard-step') w = 0; + for (let k = 0; k < sides; k += 1) { + const ang = (k / sides) * Math.PI * 2; + const p = centre.clone().addScaledVector(u, Math.cos(ang) * radius).addScaledVector(v, Math.sin(ang) * radius); + positions.push(p.x, p.y, p.z); + joints.push(slot.get(own), other ? slot.get(other) : 0, 0, 0); + weights.push(1 - w, w, 0, 0); + } + if (r > 0) for (let k = 0; k < sides; k += 1) { + const a0 = start + (r - 1) * sides + k, a1 = start + (r - 1) * sides + ((k + 1) % sides); + const b0 = start + r * sides + k, b1 = start + r * sides + ((k + 1) % sides); + indices.push(a0, b0, a1, a1, b0, b1); + } + } + }; + tube(['Hips', 'Spine02', 'Spine01', 'Spine', 'neck', 'Head', 'head_end'], 0.12); + tube(['LeftShoulder', 'LeftArm', 'LeftForeArm', 'LeftHand', [0.72, 1.25, 0]], 0.045); + tube(['RightShoulder', 'RightArm', 'RightForeArm', 'RightHand', [-0.72, 1.25, 0]], 0.045); + tube(['LeftUpLeg', 'LeftLeg', 'LeftFoot', 'LeftToeBase', [0.14, 0.03, 0.2]], 0.06); + tube(['RightUpLeg', 'RightLeg', 'RightFoot', 'RightToeBase', [-0.14, 0.03, 0.2]], 0.06); + if (mutant === 'arm-weight-on-torso') { + // Upper-back vertices of the spine tube take 60% LeftArm (the defect the part rules forbid). + for (let i = 0; i < positions.length / 3; i += 1) { + const [x, y, z] = positions.slice(i * 3, i * 3 + 3); + if (y > 1.1 && y < 1.3 && z < -0.05 && Math.abs(x) < 0.15 && joints[i * 4] !== slot.get('LeftArm')) { + joints[i * 4 + 1] = slot.get('LeftArm'); weights[i * 4] = 0.4; weights[i * 4 + 1] = 0.6; + } + } + } + if (mutant === 'split-seam') { + // Duplicate one spine-ring vertex (a UV seam) and weight the copy to the left arm. + const v = 40; + positions.push(...positions.slice(v * 3, v * 3 + 3)); + joints.push(slot.get('LeftArm'), 0, 0, 0); + weights.push(1, 0, 0, 0); + indices.push(v, positions.length / 3 - 1, v + 1); + } + if (mutant === 'hand-on-spine') { + // Every other ring of the left hand is skinned to Spine: lifting the arm tears the hand. + for (let i = 0; i < positions.length / 3; i += 1) { + const [x, y] = positions.slice(i * 3, i * 3 + 2); + if (x > 0.63 && Math.abs(y - 1.25) < 0.06 && Math.round((x - 0.62) / 0.02) % 2 === 1) { + joints.splice(i * 4, 4, slot.get('Spine'), 0, 0, 0); + weights.splice(i * 4, 4, 1, 0, 0, 0); + } + } + } + return { positions, joints, weights, indices }; +} + +export function synthDocument(options = {}) { + const doc = new Document(); + const buffer = doc.createBuffer(); + const body = synthBody(options); + const prim = doc.createPrimitive() + .setAttribute('POSITION', doc.createAccessor().setType('VEC3').setArray(new Float32Array(body.positions)).setBuffer(buffer)) + .setAttribute('JOINTS_0', doc.createAccessor().setType('VEC4').setArray(new Uint16Array(body.joints)).setBuffer(buffer)) + .setAttribute('WEIGHTS_0', doc.createAccessor().setType('VEC4').setArray(new Float32Array(body.weights)).setBuffer(buffer)) + .setIndices(doc.createAccessor().setType('SCALAR').setArray(new Uint32Array(body.indices)).setBuffer(buffer)); + const meshNode = doc.createNode('Body').setMesh(doc.createMesh('Body').addPrimitive(prim)); + const skeleton = buildMeshy28Skeleton(doc, { ...(options.joints || J), ...TIPS }); + if (options.mutant === 'stale-ibm') skeleton.joints[13].setTranslation(skeleton.joints[13].getTranslation().map((v, i) => v + (i === 1 ? 5 : 0))); + const skin = doc.createSkin('meshy-28').setSkeleton(skeleton.joints[0]) + .setInverseBindMatrices(doc.createAccessor().setType('MAT4').setArray(skeleton.inverseBindMatrices).setBuffer(buffer)); + for (const node of skeleton.joints) skin.addJoint(node); + meshNode.setSkin(skin); + doc.createScene('scene').addChild(meshNode).addChild(skeleton.armature); + return doc; +} From 208f9fbfbaccd2c403cfadc80ffe537317de1b89 Mon Sep 17 00:00:00 2001 From: rubenmarcus Date: Mon, 9 Nov 2026 03:34:41 +0000 Subject: [PATCH 04/31] Convert Mixamo and UAL clips to meshy-28 and bake them per character One retarget core for both steps: world-rotation deltas with rest-direction alignment of arms and legs, hips displacement scaled by hips height with straight-line root motion extracted into metadata, ground contact on the lowest foot joint, two-bone foot IK inside the source's contact windows (loop-aware), 30 fps resampling, trim and facing correction. Mixamo maps its spine anatomically (Spine->Spine02, Spine2->Spine), UAL follows the UE mannequin names. Bake ports the client's retarget-glb rules (absolute arms, Curl_* untouched, refuse unmapped rigs) and adds a mesh-aware toe floor clamp. Clips carry extras.clip metadata with the studio-assets catalog id. Agent: Claude Code Signed-off-by: rubenmarcus --- tools/animations/bake-character.mjs | 64 ++ tools/animations/convert-clips.mjs | 101 +++ .../animations/manifests/pilot-20261109.json | 11 + tools/lib/animation-retarget.mjs | 662 ++++++++++++++++++ tools/lib/animation-sources.mjs | 87 +++ 5 files changed, 925 insertions(+) create mode 100755 tools/animations/bake-character.mjs create mode 100755 tools/animations/convert-clips.mjs create mode 100644 tools/animations/manifests/pilot-20261109.json create mode 100644 tools/lib/animation-retarget.mjs create mode 100644 tools/lib/animation-sources.mjs diff --git a/tools/animations/bake-character.mjs b/tools/animations/bake-character.mjs new file mode 100755 index 0000000..b52a927 --- /dev/null +++ b/tools/animations/bake-character.mjs @@ -0,0 +1,64 @@ +#!/usr/bin/env node +// Bake meshy-28 reference clips onto one character's meshy-28 rig (docs/animation-conversion.md). +// +// node tools/animations/bake-character.mjs --model= --clips= --out= [--states=] +// +// Port of the client's tools/retarget-glb.mjs: legs, spine, clavicles, neck and head take the +// clip's world-rotation DELTAS (they keep the character's own rest offsets, so bone lengths +// and a crouched or bent rest pose survive); LeftArm/ForeArm/Hand and their right twins copy +// the clip's ABSOLUTE world rotation (an A-pose rig would otherwise hold every clip 30-40° +// off); Curl_* are never animated (the client writes the grip curl there). The Hips track is +// the clip's displacement scaled by the hips-height ratio; the reference clip is already in +// place, so its sway is kept and its root-motion metadata (velocity, contactSlide) is scaled +// the same way. Leg directions follow the reference's (rest alignment), the hips height keeps +// the lowest foot joint where the clip has it, two-bone IK pins the ankles inside the clip's +// contact windows (extras.clip.contacts), and a mesh-aware clamp pitches toes that would sink +// below the floor (docs/animation-conversion.md). --no-foot-contact, --no-foot-ik, +// --no-toe-clamp and --no-limb-align switch those off. Works on clips without metadata too +// (the client's shared pack): contacts are then detected on the clip itself. +import { NodeIO } from '@gltf-transform/core'; +import { ALL_EXTENSIONS } from '@gltf-transform/extensions'; +import { mkdirSync, readdirSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { CLIP_FPS, clampToesToFloor, clipMetadata, gltfPoseSource, retargetClip, skeletonGraph, writeClipDocument } from '../lib/animation-retarget.mjs'; +import { RIG_MAPS } from '../lib/animation-sources.mjs'; +import { loadRig } from '../lib/character-rig.mjs'; + +const args = process.argv.slice(2); +const flag = (name) => args.find((a) => a.startsWith(`--${name}=`))?.slice(name.length + 3); +const model = flag('model'), clipsDir = flag('clips'), outDir = flag('out'); +if (!model || !clipsDir || !outDir) { + console.error('usage: bake-character.mjs --model= --clips= --out= [--states=] [--no-foot-contact] [--no-foot-ik] [--no-toe-clamp] [--no-limb-align]'); + process.exit(1); +} +mkdirSync(outDir, { recursive: true }); +const io = new NodeIO().registerExtensions(ALL_EXTENSIONS); +const modelDoc = await io.read(model); +const target = skeletonGraph(modelDoc); +const rig = loadRig(modelDoc); +const states = flag('states')?.split(',').filter(Boolean) + || readdirSync(clipsDir).filter((f) => f.endsWith('.glb')).map((f) => f.slice(0, -4)).sort(); + +const baked = []; +for (const state of states) { + const doc = await io.read(path.join(clipsDir, `${state}.glb`)); + const animation = doc.getRoot().listAnimations()[0]; + if (!animation) throw new Error(`${state}: no animation`); + const meta = clipMetadata(doc); + const source = gltfPoseSource(doc, animation, RIG_MAPS['meshy-28']); + const result = retargetClip(source, target, { fps: meta.fps || CLIP_FPS, rootMotion: 'keep', absoluteArms: true, footContact: !args.includes('--no-foot-contact'), footIk: !args.includes('--no-foot-ik'), contacts: meta.contacts || null, loop: Boolean(meta.loop), alignLimbs: args.includes('--no-limb-align') ? [] : undefined }); + const toeClamp = args.includes('--no-toe-clamp') ? null : clampToesToFloor(rig, result); + const scale = (v) => +(v * result.hipsScale).toFixed(4); + const rm = meta.rootMotion; + const frames = result.times.length; + const extras = { + ...meta, fps: meta.fps || CLIP_FPS, frames, duration: +result.times[frames - 1].toFixed(4), + contactSlide: meta.contactSlide != null ? scale(meta.contactSlide) : undefined, + rootMotion: rm ? { ...rm, displacement: rm.displacement.map(scale), velocity: rm.velocity.map(scale), speed: scale(rm.speed) } : undefined, + bakedFor: { model: path.basename(model), hipsScale: +result.hipsScale.toFixed(6), joints: result.mapped.length, footContact: result.contactCorrection, footIk: result.ik, toeClamp, alignedLimbs: result.aligned }, + }; + await io.write(path.join(outDir, `${state}.glb`), writeClipDocument(target, result, state, extras)); + baked.push({ name: state, frames, duration: extras.duration, joints: result.mapped.length, hipsScale: extras.bakedFor.hipsScale, rootSpeed: extras.rootMotion?.speed ?? null }); + console.log(`ok ${state}: ${frames} f, ${extras.duration}s, ${result.mapped.length} joints, hips scale ${extras.bakedFor.hipsScale}`); +} +writeFileSync(path.join(outDir, 'manifest.json'), `${JSON.stringify({ model: path.basename(model), clips: baked }, null, 2)}\n`); diff --git a/tools/animations/convert-clips.mjs b/tools/animations/convert-clips.mjs new file mode 100755 index 0000000..ebd0d42 --- /dev/null +++ b/tools/animations/convert-clips.mjs @@ -0,0 +1,101 @@ +#!/usr/bin/env node +// Convert source animations to meshy-28 reference clips (docs/animation-conversion.md). +// +// node tools/animations/convert-clips.mjs --manifest= --out= [--catalog=/animations/catalog.json] +// [--sources=] [--reference=] +// node tools/animations/convert-clips.mjs --out= [--name=] [--id=] [--action=] [--take=] +// [--loop] [--hold=rifle|pistol|knife|none] [--airborne] [--start=] [--end=] +// [--root-motion=in-place|keep|strip] [--rig=mixamo|ual|meshy-28] [--reference=] [--no-foot-contact] [--no-foot-ik] [--no-limb-align] +// node tools/animations/convert-clips.mjs --list +// +// Sources: Mixamo FBX (mixamorig rig, with or without skin, any frame rate), Quaternius UAL +// glTF (one action per clip, --action) and meshy-28 clips. Output: one `.glb` per clip +// on the meshy-28 reference skeleton (MESHY28_REFERENCE_JOINTS, or the skeleton of +// --reference), resampled to 30 fps, plus `manifest.json`. Metadata (loop, hold, root motion, +// source) is stored in the animation's `extras.clip`. +// Manifest: { "clips": [{ "name", "id"?, "source"?, "action"?, "take"?, "loop"?, "hold"?, "airborne"?, +// "start"?, "end"?, "rootMotion"? }] }. `id` is the private corosolto/studio-assets animation +// catalog id (provenance, recorded in extras.clip.source.id); with --catalog it also resolves +// the source file. Otherwise `source` is relative to --sources (default: the manifest's folder). +import { NodeIO } from '@gltf-transform/core'; +import { ALL_EXTENSIONS } from '@gltf-transform/extensions'; +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { + CLIP_FPS, ROOT_MOTION_MODES, referenceSkeletonDocument, retargetClip, skeletonGraph, writeClipDocument, +} from '../lib/animation-retarget.mjs'; +import { listActions, openSource } from '../lib/animation-sources.mjs'; + +const args = process.argv.slice(2); +const flag = (name) => args.find((a) => a.startsWith(`--${name}=`))?.slice(name.length + 3); +const has = (name) => args.includes(`--${name}`); +const positional = args.filter((a) => !a.startsWith('--')); +const usage = 'usage: convert-clips.mjs --manifest= --out= | --out= [--name= --action= --loop --hold= --start= --end= --root-motion=] | --list'; + +if (has('list')) { + if (!positional[0]) { console.error(usage); process.exit(1); } + for (const a of await listActions(positional[0])) console.log(`${a.name}\t${a.duration}s`); + process.exit(0); +} +const outDir = flag('out'); +if (!outDir || (!flag('manifest') && !positional[0])) { console.error(usage); process.exit(1); } +mkdirSync(outDir, { recursive: true }); + +const io = new NodeIO().registerExtensions(ALL_EXTENSIONS); +const referenceDoc = flag('reference') ? await io.read(flag('reference')) : referenceSkeletonDocument(); +const target = skeletonGraph(referenceDoc); +const slug = (text) => String(text).toLowerCase().replace(/\.[a-z0-9]+$/, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, ''); + +let entries, sourcesDir; +if (flag('manifest')) { + const manifestFile = path.resolve(flag('manifest')); + entries = JSON.parse(readFileSync(manifestFile, 'utf8')).clips; + sourcesDir = path.resolve(flag('sources') || path.dirname(manifestFile)); +} else { + sourcesDir = process.cwd(); + entries = [{ + name: flag('name'), id: flag('id'), source: positional[0], action: flag('action'), take: flag('take'), rig: flag('rig'), + loop: has('loop') ? true : undefined, hold: flag('hold'), airborne: has('airborne'), + start: flag('start') != null ? Number(flag('start')) : undefined, end: flag('end') != null ? Number(flag('end')) : undefined, + rootMotion: flag('root-motion'), + }]; +} + +const catalog = flag('catalog') ? JSON.parse(readFileSync(flag('catalog'), 'utf8')) : null; +// Catalog `file` paths are relative to the studio-assets repository root (catalog: animations/catalog.json). +const catalogRoot = catalog ? path.dirname(path.dirname(path.resolve(flag('catalog')))) : null; +const sourceFile = (entry) => { + if (catalog && entry.id) { + const hit = catalog.clips.find((c) => c.id === entry.id); + if (!hit) throw new Error(`catalog has no clip ${entry.id}`); + return path.join(catalogRoot, hit.file); + } + if (!entry.source) throw new Error(`${entry.name || entry.id}: no source (pass --catalog for catalog ids)`); + return path.resolve(sourcesDir, entry.source); +}; + +const results = []; +for (const entry of entries) { + const file = sourceFile(entry); + const opened = await openSource(file, { action: entry.action, take: entry.take, rig: entry.rig }); + const name = entry.name || slug(entry.action || path.basename(file)); + const loop = entry.loop ?? /_Loop$/.test(entry.action || ''); + const rootMotion = entry.rootMotion || 'in-place'; + if (!ROOT_MOTION_MODES.includes(rootMotion)) throw new Error(`${name}: rootMotion must be one of ${ROOT_MOTION_MODES.join(', ')}`); + const start = entry.start ?? 0, end = entry.end ?? opened.source.duration; + const result = retargetClip(opened.source, target, { fps: CLIP_FPS, start, end, rootMotion, footContact: !has('no-foot-contact'), footIk: !has('no-foot-ik'), loop, alignLimbs: has('no-limb-align') ? [] : undefined }); + const frames = result.times.length; + const meta = { + fps: CLIP_FPS, frames, duration: +result.times[frames - 1].toFixed(4), loop, hold: entry.hold || 'none', airborne: Boolean(entry.airborne), + rootMotion: result.rootMotion, hipsScale: +result.hipsScale.toFixed(6), footContact: result.contactCorrection, footIk: result.ik, contacts: result.contacts, contactSlide: result.sourceSlide, sourceHipsRatio: result.sourceHipsRatio, alignedLimbs: result.aligned, + source: { + id: entry.id || null, rig: opened.rig, file: path.basename(file), take: opened.take, nativeFps: opened.source.nativeFps, + duration: +opened.source.duration.toFixed(4), start: +start.toFixed(4), end: +end.toFixed(4), + }, + reference: flag('reference') ? path.basename(flag('reference')) : 'meshy-28 reference (MESHY28_REFERENCE_JOINTS)', + }; + await io.write(path.join(outDir, `${name}.glb`), writeClipDocument(target, result, name, meta)); + results.push({ name, mappedJoints: result.mapped.length, ...meta }); + console.log(`ok ${name}: ${opened.rig} ${path.basename(file)}${opened.take ? ` [${opened.take}]` : ''} ${meta.source.nativeFps ?? '?'} fps -> ${frames} f @ ${CLIP_FPS} fps, ${meta.duration}s, ${result.mapped.length} joints, root ${rootMotion} ${result.rootMotion.speed} m/s${loop ? ', loop' : ''}`); +} +writeFileSync(path.join(outDir, 'manifest.json'), `${JSON.stringify({ skeleton: 'meshy-28', fps: CLIP_FPS, clips: results }, null, 2)}\n`); diff --git a/tools/animations/manifests/pilot-20261109.json b/tools/animations/manifests/pilot-20261109.json new file mode 100644 index 0000000..b821ba1 --- /dev/null +++ b/tools/animations/manifests/pilot-20261109.json @@ -0,0 +1,11 @@ +{ + "description": "P1 pilot (2026-11-09): six Mixamo clips owner-downloaded to ~/Downloads. `id` is the corosolto/studio-assets animation catalog id (animations/catalog.json, resolved with --catalog); 'walk left'/'walk right' come from 'Rifle 8-Way Locomotion Pack.zip', byte-identical to the Pro Rifle Pack copies. Source files are private.", + "clips": [ + { "name": "reload", "id": "mixamo/loose/reload", "hold": "none" }, + { "name": "grenade-throw", "id": "mixamo/loose/grenade-throw", "hold": "none" }, + { "name": "knife-idle", "id": "mixamo/loose/knife-idle", "loop": true, "hold": "knife" }, + { "name": "rifle-pull-out", "id": "mixamo/loose/rifle-pull-out", "hold": "none" }, + { "name": "rifle-walk-left", "id": "mixamo/pro-rifle-pack/walk-left", "loop": true, "hold": "rifle" }, + { "name": "rifle-walk-right", "id": "mixamo/pro-rifle-pack/walk-right", "loop": true, "hold": "rifle" } + ] +} diff --git a/tools/lib/animation-retarget.mjs b/tools/lib/animation-retarget.mjs new file mode 100644 index 0000000..47da835 --- /dev/null +++ b/tools/lib/animation-retarget.mjs @@ -0,0 +1,662 @@ +// Animation conversion onto the meshy-28 skeleton (docs/animation-conversion.md). +// +// One retarget core serves both stages: +// convert source rig (Mixamo FBX, Quaternius UAL glTF) -> meshy-28 REFERENCE clip, by +// world-rotation deltas (every bone, any rest-frame convention); +// bake meshy-28 reference clip -> one character's meshy-28 rig (the client's +// tools/retarget-glb.mjs rules: deltas, except Arm/ForeArm/Hand which copy the +// clip's absolute world rotation; Curl_* never animated). +// For a mapped bone and frame: delta = srcWorld · srcRestWorld⁻¹ (turned into the target's +// facing), desiredWorld = delta · tgtRestWorld, tgtLocal = tgtParentWorld⁻¹ · desiredWorld. +// Hips: the world displacement from the source rest, scaled by the hips-height ratio. Its +// horizontal drift (root motion) is extracted and recorded as metadata; the clip keeps the +// sway around it. +import { Document } from '@gltf-transform/core'; +import * as THREE from 'three'; +import { buildMeshy28Skeleton, skinPositions, worldMatrices } from './character-rig.mjs'; + +export const CLIP_FPS = 30; +export const CLIP_SCHEMA = 'coro-solto/clip@1'; +/** Runtime-only joints: the client writes the grip curl on them; clips never carry them. */ +export const RUNTIME_ONLY_JOINT = /^Curl_/; +/** Bones that bake copies as absolute world rotations (client retarget-glb.mjs rule). */ +export const ABSOLUTE_ARM_JOINT = /Arm|Hand/; +export const ROOT_MOTION_MODES = Object.freeze(['in-place', 'keep', 'strip']); + +/* Mixamo -> meshy-28. Names without the `mixamorig:` prefix (FBXLoader drops the colon, + some exports carry `mixamorig1:` or no prefix; mixamoBaseName() normalises all of them). + The spine follows the anatomy: Mixamo Spine (just above the hips) is meshy Spine02 (child + of Hips), Spine2 (chest) is meshy Spine (parent of neck and clavicles). The client's + retarget-mixamo.mjs maps them by name (Spine->Spine, Spine2->Spine02), which puts the + chest's bend on the lowest spine joint. Fingers, HeadTop_End and toe ends have no + meshy-28 counterpart; head_end and headfront stay at rest. */ +export const MIXAMO_TO_MESHY28 = Object.freeze({ + Hips: 'Hips', Spine: 'Spine02', Spine1: 'Spine01', Spine2: 'Spine', Neck: 'neck', Head: 'Head', + LeftShoulder: 'LeftShoulder', LeftArm: 'LeftArm', LeftForeArm: 'LeftForeArm', LeftHand: 'LeftHand', + RightShoulder: 'RightShoulder', RightArm: 'RightArm', RightForeArm: 'RightForeArm', RightHand: 'RightHand', + LeftUpLeg: 'LeftUpLeg', LeftLeg: 'LeftLeg', LeftFoot: 'LeftFoot', LeftToeBase: 'LeftToeBase', + RightUpLeg: 'RightUpLeg', RightLeg: 'RightLeg', RightFoot: 'RightFoot', RightToeBase: 'RightToeBase', +}); + +/* Quaternius Universal Animation Library (UAL1/UAL2, CC0; UE5-mannequin naming) -> meshy-28. + `root` carries root motion in the _RM files and is not a body bone; fingers and *_leaf + bones have no meshy-28 counterpart. */ +export const UAL_TO_MESHY28 = Object.freeze({ + pelvis: 'Hips', spine_01: 'Spine02', spine_02: 'Spine01', spine_03: 'Spine', neck_01: 'neck', Head: 'Head', + clavicle_l: 'LeftShoulder', upperarm_l: 'LeftArm', lowerarm_l: 'LeftForeArm', hand_l: 'LeftHand', + clavicle_r: 'RightShoulder', upperarm_r: 'RightArm', lowerarm_r: 'RightForeArm', hand_r: 'RightHand', + thigh_l: 'LeftUpLeg', calf_l: 'LeftLeg', foot_l: 'LeftFoot', ball_l: 'LeftToeBase', + thigh_r: 'RightUpLeg', calf_r: 'RightLeg', foot_r: 'RightFoot', ball_r: 'RightToeBase', +}); + +export const mixamoBaseName = (name) => String(name).replace(/^mixamorig\d*:?/, ''); + +/* World joint positions (glTF metres, +Y up, facing +Z, left +X) of the meshy-28 donor + (client public/models/characters/mst.glb, measured 2026-11-09). With the donor rest frames + of MESHY28_REST_WORLD they define the reference skeleton every reference clip is baked + against; per-character bake then moves the clips onto each rig. */ +export const MESHY28_REFERENCE_JOINTS = Object.freeze({ + Hips: [-0.0005, 0.8246, -0.0232], + LeftUpLeg: [0.0745, 0.7423, -0.0084], LeftLeg: [0.1047, 0.413, 0.0507], LeftFoot: [0.1157, 0.0993, 0.0076], LeftToeBase: [0.1379, 0.0431, 0.119], + RightUpLeg: [-0.0757, 0.7433, -0.0082], RightLeg: [-0.1067, 0.418, 0.0517], RightFoot: [-0.1114, 0.1118, -0.0048], RightToeBase: [-0.1357, 0.0428, 0.1128], + Spine02: [-0.0004, 0.9564, 0.0031], Spine01: [-0.0004, 1.0882, 0.0293], Spine: [-0.0003, 1.22, 0.0556], + LeftShoulder: [0.0331, 1.2462, 0.0554], LeftArm: [0.1665, 1.2462, 0.0552], LeftForeArm: [0.3904, 1.2306, -0.0244], LeftHand: [0.6313, 1.2209, -0.0254], + RightShoulder: [-0.033, 1.2446, 0.0554], RightArm: [-0.1641, 1.2446, 0.0552], RightForeArm: [-0.3956, 1.2243, -0.0244], RightHand: [-0.6271, 1.2156, -0.0251], + neck: [-0.0001, 1.3215, 0.0758], Head: [0, 1.3895, 0.0893], head_end: [0.0005, 1.7044, 0.0733], headfront: [0, 1.3895, 0.2065], + Curl_R: [-0.6272, 1.2157, -0.0258], Curl_L: [0.6314, 1.221, -0.0261], +}); + +/** Document holding only the meshy-28 reference skeleton (an `Armature` node, scale 0.01). */ +export function referenceSkeletonDocument() { + const doc = new Document(); + const { armature } = buildMeshy28Skeleton(doc, MESHY28_REFERENCE_JOINTS); + doc.createScene('scene').addChild(armature); + return doc; +} + +// ------------------------------------------------------------------------------------------ +// glTF skeleton graphs. + +const composeTrs = (t, r, s) => new THREE.Matrix4().compose(new THREE.Vector3(...t), new THREE.Quaternion(...r), new THREE.Vector3(...s)); + +/** + * Skeleton of a glTF document: the subtree under the root ancestor of `rootJoint`, in + * depth-first order (parents first). Names may repeat (meshy-28's Curl pairs); `byName` + * keeps the first occurrence. + */ +export function skeletonGraph(doc, rootJoint = 'Hips') { + const nodes = doc.getRoot().listNodes(); + const parentOf = new Map(); + for (const n of nodes) for (const c of n.listChildren()) parentOf.set(c, n); + const anchor = nodes.find((n) => n.getName() === rootJoint); + if (!anchor) throw new Error(`skeleton has no ${rootJoint} node`); + let root = anchor; + while (parentOf.get(root)) root = parentOf.get(root); + const order = []; + const index = new Map(); + const visit = (node, parent) => { + const entry = { + node, name: node.getName(), parent, + t: node.getTranslation(), r: node.getRotation(), s: node.getScale(), + }; + index.set(node, entry); + order.push(entry); + for (const c of node.listChildren()) visit(c, entry); + }; + visit(root, null); + for (const e of order) { + e.restLocal = composeTrs(e.t, e.r, e.s); + e.restWorld = e.parent ? e.parent.restWorld.clone().multiply(e.restLocal) : e.restLocal.clone(); + e.restWorldQ = e.parent ? e.parent.restWorldQ.clone().multiply(new THREE.Quaternion(...e.r)) : new THREE.Quaternion(...e.r); + e.restWorldP = new THREE.Vector3().setFromMatrixPosition(e.restWorld); + } + const byName = new Map(); + for (const e of order) if (!byName.has(e.name)) byName.set(e.name, e); + return { doc, root: order[0], order, byName, index }; +} + +/** Value of one glTF animation channel at time t (LINEAR/STEP/CUBICSPLINE value part). */ +function channelValue(c, t) { + const T = c.times; + const last = T.length - 1; + let i = 0; + if (t >= T[last]) i = last; + else while (i < last - 1 && T[i + 1] <= t) i += 1; + const at = (k) => { const base = c.cubic ? (k * 3 + 1) * c.n : k * c.n; return Array.from(c.values.slice(base, base + c.n)); }; + if (i === last || c.step || t <= T[0]) return at(i); + const f = Math.min(1, Math.max(0, (t - T[i]) / ((T[i + 1] - T[i]) || 1))); + const a = at(i), b = at(i + 1); + if (c.n === 4) return new THREE.Quaternion().fromArray(a).slerp(new THREE.Quaternion().fromArray(b), f).toArray(); + return a.map((x, k) => x + (b[k] - x) * f); +} + +/** Native key rate: the most common key interval over all tracks (keys per second; null when none). */ +function keyRate(trackTimes) { + const counts = new Map(); + for (const T of trackTimes) { + for (let k = 1; k < T.length; k += 1) { + const dt = Math.round((T[k] - T[k - 1]) * 1e5); + if (dt > 0) counts.set(dt, (counts.get(dt) || 0) + 1); + } + } + if (!counts.size) return null; + const [dt] = [...counts].sort((a, b) => b[1] - a[1] || a[0] - b[0])[0]; + const rate = 1e5 / dt; + return Math.abs(rate - Math.round(rate)) < 0.05 ? Math.round(rate) : +rate.toFixed(2); +} + +/** + * Pose source over a glTF animation: `map` names source nodes -> meshy-28 names (identity for + * meshy-28 clips). World poses include every ancestor (UAL's Z-up `root`, the 0.01 Armature). + */ +export function gltfPoseSource(doc, animation, map, { rootJoint } = {}) { + const sourceRoot = rootJoint || Object.keys(map).find((k) => map[k] === 'Hips'); + const graph = skeletonGraph(doc, sourceRoot); + const channels = []; + const keyTimes = []; + for (const ch of animation.listChannels()) { + const target = ch.getTargetNode(), s = ch.getSampler(), path = ch.getTargetPath(); + const entry = target && graph.index.get(target); + if (!entry || !s || !['translation', 'rotation', 'scale'].includes(path)) continue; + const times = s.getInput().getArray(); + keyTimes.push(times); + channels.push({ entry, key: path === 'translation' ? 't' : path === 'rotation' ? 'r' : 's', times, values: s.getOutput().getArray(), n: path === 'rotation' ? 4 : 3, cubic: s.getInterpolation() === 'CUBICSPLINE', step: s.getInterpolation() === 'STEP' }); + } + const startTime = Math.min(...channels.map((c) => c.times[0])); + const duration = Math.max(0, ...channels.map((c) => c.times[c.times.length - 1])) - (Number.isFinite(startTime) ? startTime : 0); + const joints = new Map(); + for (const [from, to] of Object.entries(map)) { + const entry = graph.byName.get(from); + if (entry && !joints.has(to)) joints.set(to, entry); + } + const worldOf = (overrides) => { + const cache = new Map(); + const world = (e) => { + if (cache.has(e)) return cache.get(e); + const o = overrides.get(e); + const local = o ? composeTrs(o.t || e.t, o.r || e.r, o.s || e.s) : e.restLocal; + const m = e.parent ? world(e.parent).clone().multiply(local) : local.clone(); + cache.set(e, m); + return m; + }; + return world; + }; + const pose = (world) => { + const out = new Map(); + for (const [name, e] of joints) { + const p = new THREE.Vector3(), q = new THREE.Quaternion(), s = new THREE.Vector3(); + world(e).decompose(p, q, s); + out.set(name, { p, q }); + } + return out; + }; + const restPose = pose(worldOf(new Map())); + return { + kind: 'gltf', duration, nativeFps: keyRate(keyTimes), + joints: new Set(joints.keys()), + rest: () => restPose, + sample(t) { + const overrides = new Map(); + for (const c of channels) { + const o = overrides.get(c.entry) || {}; + o[c.key] = channelValue(c, (Number.isFinite(startTime) ? startTime : 0) + t); + overrides.set(c.entry, o); + } + return pose(worldOf(overrides)); + }, + }; +} + +/** + * Pose source over a three.js object tree and AnimationClip (what FBXLoader returns). Bones + * are resolved like the AnimationMixer resolves track names (PropertyBinding.findNode), so + * the leaf duplicates FBXLoader creates for skinned Mixamo files are never picked. The rest + * pose is the tree as loaded (Mixamo: the T-pose). + */ +export function objectPoseSource(group, clip, map, { baseName = mixamoBaseName } = {}) { + const names = new Set(); + group.traverse((o) => names.add(o.name)); + const joints = new Map(); + for (const name of names) { + const meshy = map[baseName(name)]; + if (!meshy || joints.has(meshy)) continue; + const node = THREE.PropertyBinding.findNode(group, name); + if (node) joints.set(meshy, node); + } + const read = () => { + group.updateMatrixWorld(true); + const out = new Map(); + for (const [name, node] of joints) { + const p = new THREE.Vector3(), q = new THREE.Quaternion(), s = new THREE.Vector3(); + node.matrixWorld.decompose(p, q, s); + out.set(name, { p, q }); + } + return out; + }; + const restPose = read(); + const mixer = new THREE.AnimationMixer(group); + const action = mixer.clipAction(clip); + // LoopOnce + clamp: setTime(duration) holds the last frame instead of wrapping to frame 0. + action.setLoop(THREE.LoopOnce, 1); + action.clampWhenFinished = true; + action.play(); + return { + kind: 'object', duration: clip.duration, nativeFps: keyRate(clip.tracks.map((t) => t.times)), + joints: new Set(joints.keys()), + rest: () => restPose, + sample(t) { mixer.setTime(Math.min(clip.duration, Math.max(0, t))); return read(); }, + }; +} + +// ------------------------------------------------------------------------------------------ +// Retarget core. + +const UP = new THREE.Vector3(0, 1, 0); + +/** Rotation about +Y that turns the source's facing onto the target's (from the hip line). */ +export function facingYaw(sourceRest, target) { + const srcL = sourceRest.get('LeftUpLeg')?.p, srcR = sourceRest.get('RightUpLeg')?.p; + const tgtL = target.byName.get('LeftUpLeg')?.restWorldP, tgtR = target.byName.get('RightUpLeg')?.restWorldP; + if (!srcL || !srcR || !tgtL || !tgtR) return new THREE.Quaternion(); + const s = srcL.clone().sub(srcR), t = tgtL.clone().sub(tgtR); + const angle = Math.atan2(s.z, s.x) - Math.atan2(t.z, t.x); + return new THREE.Quaternion().setFromAxisAngle(UP, angle); +} + +/** Joints whose height above their rest height defines ground contact (heel/ankle and ball). */ +export const FOOT_CONTACT_JOINTS = Object.freeze(['LeftFoot', 'LeftToeBase', 'RightFoot', 'RightToeBase']); + +/* Source contact detection (reference metres): a foot joint is planted where it is within + CONTACT_HEIGHT of its rest height and moves slower than CONTACT_SPEED horizontally in the + source's world (root motion included). Windows shorter than CONTACT_MIN_FRAMES are dropped. + The windows travel with the clip (extras.clip.contacts) so the QA gate measures a baked + character's slide exactly where the motion capture plants the foot. */ +export const CONTACT_HEIGHT = 0.03; +export const CONTACT_SPEED = 0.25; +export const CONTACT_MIN_FRAMES = 3; + +/** Planted frame windows per foot joint: { LeftFoot: [[first, last], ...], ... } (frame indices). */ +export function footContacts(tracks, times) { + const out = {}; + for (const [name, track] of Object.entries(tracks)) { + const windows = []; + let open = -1; + for (let i = 0; i <= track.length; i += 1) { + let planted = false; + if (i < track.length) { + const a = track[Math.max(0, i - 1)], b = track[Math.min(track.length - 1, i + 1)]; + const dt = times[Math.min(track.length - 1, i + 1)] - times[Math.max(0, i - 1)]; + const speed = dt > 0 ? Math.hypot(b.x - a.x, b.z - a.z) / dt : 0; + planted = track[i].clear <= CONTACT_HEIGHT && speed <= CONTACT_SPEED; + } + if (planted && open < 0) open = i; + if (!planted && open >= 0) { + if (i - open >= CONTACT_MIN_FRAMES) windows.push([open, i - 1]); + open = -1; + } + } + out[name] = windows; + } + return out; +} + +/** Leg chains for foot IK: hip joint, knee joint, ankle joint, the ankle's contact joints. */ +export const LEG_CHAINS = Object.freeze([ + { side: 'Left', hip: 'LeftUpLeg', knee: 'LeftLeg', ankle: 'LeftFoot', contacts: ['LeftFoot', 'LeftToeBase'] }, + { side: 'Right', hip: 'RightUpLeg', knee: 'RightLeg', ankle: 'RightFoot', contacts: ['RightFoot', 'RightToeBase'] }, +]); +/** Frames over which foot IK blends in before and out after a contact window. */ +export const IK_BLEND_FRAMES = 4; + +/* Limb bones aligned to the source's rest direction (bone -> the child it points at). Feet + are not: ankle-to-ball slopes differ with foot shape, and both rests stand flat. */ +export const LIMB_ALIGNMENT = Object.freeze([ + ['LeftArm', 'LeftForeArm'], ['LeftForeArm', 'LeftHand'], ['RightArm', 'RightForeArm'], ['RightForeArm', 'RightHand'], + ['LeftUpLeg', 'LeftLeg'], ['LeftLeg', 'LeftFoot'], ['RightUpLeg', 'RightLeg'], ['RightLeg', 'RightFoot'], +]); + +/** + * Per-frame IK weight of one leg from its contact windows (1 inside, smooth ramp outside). + * In a loop the last frame is the first frame again, so ramps wrap around the seam. + */ +function ikWeights(windows, frames, loop = false) { + const w = new Float32Array(frames); + const period = frames - 1; + for (const [a, b] of windows) { + for (let i = a - IK_BLEND_FRAMES; i <= b + IK_BLEND_FRAMES; i += 1) { + const outside = i < a ? a - i : i > b ? i - b : 0; + const x = 1 - outside / (IK_BLEND_FRAMES + 1); + const k = loop ? ((i % period) + period) % period : i; + if (k < 0 || k >= frames) continue; + w[k] = Math.max(w[k], x * x * (3 - 2 * x)); + } + } + if (loop) { w[0] = Math.max(w[0], w[period]); w[period] = w[0]; } + return w; +} + +/** + * Two-bone IK in world space: bend the knee to the length hip→goal (law of cosines, about the + * current bend axis, else `fallbackAxis`), then swing the hip so the ankle lands on the goal. + * Returns the new world rotations { hip, knee } (the ankle keeps its world rotation). + */ +export function solveTwoBone(H, K, A, goal, hipQ, kneeQ, fallbackAxis) { + const a = K.distanceTo(H), b = A.distanceTo(K); + const u = H.clone().sub(K), v = A.clone().sub(K); + let axis = u.clone().cross(v); + if (axis.lengthSq() < 1e-12) axis = fallbackAxis.clone(); + axis.normalize(); + const d = THREE.MathUtils.clamp(goal.distanceTo(H), Math.abs(a - b) + 1e-6, a + b - 1e-6); + const current = u.angleTo(v); + const wanted = Math.acos(THREE.MathUtils.clamp((a * a + b * b - d * d) / (2 * a * b), -1, 1)); + const bend = new THREE.Quaternion().setFromAxisAngle(axis, wanted - current); + const ankle = K.clone().add(v.clone().applyQuaternion(bend)); + const swing = new THREE.Quaternion().setFromUnitVectors(ankle.sub(H).normalize(), goal.clone().sub(H).normalize()); + return { hip: swing.clone().multiply(hipQ), knee: swing.clone().multiply(bend).multiply(kneeQ) }; +} + +/** + * Retarget `source` (gltfPoseSource/objectPoseSource) onto `target` (skeletonGraph). + * options: fps, start, end (source seconds), rootMotion ('in-place' | 'keep' | 'strip'), + * absoluteArms (bake rule), footContact, footIk, contacts (windows to use instead of the + * detected ones, e.g. a reference clip's extras.clip.contacts), loop (IK ramps wrap the seam), + * minJoints. + * footContact (default on): the Hips height is corrected per frame so the target's lowest + * foot joint (relative to its rest height) is as far above its rest height as the source's, + * scaled. Without it, a target whose legs are proportioned differently from the source floats + * or sinks whenever the knees bend (the hips-height ratio alone is only exact standing). + * footIk (default on): inside the source's foot contact windows (ramped over IK_BLEND_FRAMES) + * the ankle is pinned by two-bone IK to the source ankle's displacement from its rest, scaled + * and added to the target ankle's rest; this is where the root velocity (the same scaled + * source drift) keeps it still. Without it, different leg proportions make planted feet slide. + * Returns { times, rotations: Map(name -> Float32Array xyzw), hips: Float32Array local xyz, + * rootMotion, hipsScale, mapped, contacts, contactCorrection: {min, max} (m), ik }. + */ +export function retargetClip(source, target, { + fps = CLIP_FPS, start = 0, end = source.duration, rootMotion = 'in-place', absoluteArms = false, + footContact = true, footIk = true, alignLimbs = LIMB_ALIGNMENT, contacts: givenContacts = null, loop = false, minJoints = 8, +} = {}) { + if (!ROOT_MOTION_MODES.includes(rootMotion)) throw new Error(`rootMotion must be one of ${ROOT_MOTION_MODES.join(', ')}`); + const mapped = target.order.filter((e) => source.joints.has(e.name) && !RUNTIME_ONLY_JOINT.test(e.name) && target.byName.get(e.name) === e); + if (mapped.length < minJoints) { + throw new Error(`only ${mapped.length} target joints map onto the source (minimum ${minJoints}); target root ${target.root.name}, source joints ${[...source.joints].join(',') || 'none'}`); + } + const mappedSet = new Set(mapped); + const srcRest = source.rest(); + const yaw = facingYaw(srcRest, target), yawInv = yaw.clone().invert(); + const hipsT = target.byName.get('Hips'); + const srcHips = srcRest.get('Hips'); + if (!hipsT || !srcHips) throw new Error('both skeletons need Hips'); + const hipsScale = hipsT.restWorldP.y / (srcHips.p.y || 1); + const hipsWorldScale = new THREE.Vector3(); + hipsT.restWorld.decompose(new THREE.Vector3(), new THREE.Quaternion(), hipsWorldScale); + const feet = FOOT_CONTACT_JOINTS.map((n) => target.byName.get(n)).filter((e) => e && mappedSet.has(e) && srcRest.has(e.name)); + const contact = footContact && feet.length > 0; + const t0 = Math.max(0, start), t1 = Math.min(source.duration, end); + if (!(t1 > t0)) throw new Error(`empty time range ${t0}..${t1}`); + const length = t1 - t0; + const frames = Math.max(2, Math.round(length * fps) + 1); + const times = new Float32Array(frames); + for (let i = 0; i < frames; i += 1) times[i] = i === frames - 1 ? length : Math.min(length, i / fps); + const displacement = []; + const correction = { min: Infinity, max: -Infinity }; + const footTracks = {}; + const states = []; + const sourceHips = { min: Infinity, max: -Infinity }; + const srcRestInv = new Map([...srcRest].map(([name, v]) => [name, v.q.clone().invert()])); + // Rest-direction alignment: the target bone's rest frame turned (shortest arc) so the bone + // points like the source's rest bone. World deltas then reproduce the source's limb + // directions even where the two rest poses differ (a bent rest knee, arms swept back). + const restAlign = new Map(); + for (const [bone, child] of alignLimbs) { + const e = target.byName.get(bone), c = target.byName.get(child); + if (!e || !c || !mappedSet.has(e) || (absoluteArms && ABSOLUTE_ARM_JOINT.test(bone)) || !srcRest.has(bone) || !srcRest.has(child)) continue; + const tgtDir = c.restWorldP.clone().sub(e.restWorldP); + const srcDir = srcRest.get(child).p.clone().sub(srcRest.get(bone).p).applyQuaternion(yaw); + if (tgtDir.lengthSq() < 1e-12 || srcDir.lengthSq() < 1e-12) continue; + restAlign.set(e, new THREE.Quaternion().setFromUnitVectors(tgtDir.normalize(), srcDir.normalize()).multiply(e.restWorldQ)); + } + // World matrices below the Hips for one frame's local rotations. + const forward = (localQ, hipsPos, worldQ) => { + const cache = new Map([[hipsT, new THREE.Matrix4().compose(hipsPos, worldQ.get(hipsT), hipsWorldScale)]]); + const worldOf = (e) => { + if (!cache.has(e)) cache.set(e, worldOf(e.parent).clone().multiply(composeTrs(e.t, localQ.get(e).toArray(), e.s))); + return cache.get(e); + }; + return (e) => new THREE.Vector3().setFromMatrixPosition(worldOf(e)); + }; + + // Pass 1: rotations by world deltas, hips displacement, ground contact, source foot tracks. + for (let i = 0; i < frames; i += 1) { + const pose = source.sample(t0 + times[i]); + const worldQ = new Map(), localQ = new Map(); + for (const e of target.order) { + const parentQ = e.parent ? worldQ.get(e.parent) : new THREE.Quaternion(); + if (!mappedSet.has(e)) { + localQ.set(e, new THREE.Quaternion(...e.r)); + worldQ.set(e, parentQ.clone().multiply(localQ.get(e))); + continue; + } + const src = pose.get(e.name).q; + const desired = absoluteArms && ABSOLUTE_ARM_JOINT.test(e.name) + ? yaw.clone().multiply(src) + : yaw.clone().multiply(src).multiply(srcRestInv.get(e.name)).multiply(yawInv).multiply(restAlign.get(e) || e.restWorldQ); + worldQ.set(e, desired); + localQ.set(e, parentQ.clone().invert().multiply(desired).normalize()); + } + const d = pose.get('Hips').p.clone().sub(srcHips.p).applyQuaternion(yaw).multiplyScalar(hipsScale); + const hipsRatio = pose.get('Hips').p.y / srcHips.p.y; + sourceHips.min = Math.min(sourceHips.min, hipsRatio); + sourceHips.max = Math.max(sourceHips.max, hipsRatio); + if (contact) { + // Heights do not depend on the horizontal offset. + const at = forward(localQ, hipsT.restWorldP.clone().add(d), worldQ); + let srcClear = Infinity, tgtClear = Infinity; + for (const e of feet) { + srcClear = Math.min(srcClear, (pose.get(e.name).p.y - srcRest.get(e.name).p.y) * hipsScale); + tgtClear = Math.min(tgtClear, at(e).y - e.restWorldP.y); + } + const dy = srcClear - tgtClear; + d.y += dy; + correction.min = Math.min(correction.min, dy); + correction.max = Math.max(correction.max, dy); + } + const goals = {}; + for (const name of FOOT_CONTACT_JOINTS) { + const p = pose.get(name)?.p, r = srcRest.get(name)?.p; + if (!p || !r) continue; + const delta = p.clone().sub(r).applyQuaternion(yaw).multiplyScalar(hipsScale); + goals[name] = delta; + (footTracks[name] ||= []).push({ x: delta.x, z: delta.z, clear: delta.y }); + } + states.push({ worldQ, localQ, goals }); + displacement.push(d); + } + const contacts = givenContacts || footContacts(footTracks, times); + // The source's own slide inside its contact windows (scaled): the floor of what any retarget can reach. + let sourceSlide = 0; + for (const [name, windows] of Object.entries(contacts)) { + const track = footTracks[name] || []; + for (const [a, b] of windows) { + for (let k = a; k <= Math.min(b, track.length - 1); k += 1) sourceSlide = Math.max(sourceSlide, Math.hypot(track[k].x - track[a].x, track[k].z - track[a].z)); + } + } + + // Pass 2: foot IK inside the contact windows. + const ik = { legs: 0, maxCorrection: 0 }; + if (footIk) { + for (const leg of LEG_CHAINS) { + const [hip, knee, ankle] = [leg.hip, leg.knee, leg.ankle].map((n) => target.byName.get(n)); + if (![hip, knee, ankle].every((e) => e && mappedSet.has(e)) || ankle.parent !== knee || knee.parent !== hip || !states[0].goals[leg.ankle]) continue; + const windows = leg.contacts.flatMap((n) => contacts[n] || []); + if (!windows.length) continue; + ik.legs += 1; + const weights = ikWeights(windows, frames, loop); + // Bend axis for a straight leg: the rest bend plane, carried by the hip's rotation. + const restAxisLocal = hip.restWorldP.clone().sub(knee.restWorldP).cross(ankle.restWorldP.clone().sub(knee.restWorldP)); + if (restAxisLocal.lengthSq() < 1e-12) restAxisLocal.set(1, 0, 0); else restAxisLocal.normalize(); + restAxisLocal.applyQuaternion(hip.restWorldQ.clone().invert()); + for (let i = 0; i < frames; i += 1) { + if (!(weights[i] > 0)) continue; + const { worldQ, localQ, goals } = states[i]; + const at = forward(localQ, hipsT.restWorldP.clone().add(displacement[i]), worldQ); + const H = at(hip), K = at(knee), A = at(ankle); + const goal = A.clone().lerp(ankle.restWorldP.clone().add(goals[leg.ankle]), weights[i]); + ik.maxCorrection = Math.max(ik.maxCorrection, goal.distanceTo(A)); + const solved = solveTwoBone(H, K, A, goal, worldQ.get(hip), worldQ.get(knee), restAxisLocal.clone().applyQuaternion(worldQ.get(hip))); + const ankleW = worldQ.get(ankle); + worldQ.set(hip, solved.hip); + worldQ.set(knee, solved.knee); + localQ.set(hip, worldQ.get(hip.parent).clone().invert().multiply(solved.hip).normalize()); + localQ.set(knee, solved.hip.clone().invert().multiply(solved.knee).normalize()); + localQ.set(ankle, solved.knee.clone().invert().multiply(ankleW).normalize()); + } + } + } + + const rotations = new Map(mapped.map((e) => [e.name, new Float32Array(frames * 4)])); + states.forEach(({ localQ }, i) => { + for (const e of mapped) { + const q = localQ.get(e), out = rotations.get(e.name); + // Keep consecutive keys in the same hemisphere so LINEAR slerp never takes the long way. + if (i > 0 && out[(i - 1) * 4] * q.x + out[(i - 1) * 4 + 1] * q.y + out[(i - 1) * 4 + 2] * q.z + out[(i - 1) * 4 + 3] * q.w < 0) q.set(-q.x, -q.y, -q.z, -q.w); + out.set([q.x, q.y, q.z, q.w], i * 4); + } + }); + // Root motion: the straight line from the first to the last hips position (horizontal). + const first = displacement[0], last = displacement[frames - 1]; + const drift = new THREE.Vector3(last.x - first.x, 0, last.z - first.z); + for (let i = 0; i < frames; i += 1) { + const d = displacement[i]; + if (rootMotion === 'in-place') d.addScaledVector(drift, -times[i] / length); + else if (rootMotion === 'strip') { d.x = 0; d.z = 0; } + } + const parentWorldInv = hipsT.parent ? hipsT.parent.restWorld.clone().invert() : new THREE.Matrix4(); + const hips = new Float32Array(frames * 3); + displacement.forEach((d, i) => { + const local = hipsT.restWorldP.clone().add(d).applyMatrix4(parentWorldInv); + hips.set([local.x, local.y, local.z], i * 3); + }); + const round = (v) => +v.toFixed(4); + return { + times, rotations, hips, hipsScale, mapped: mapped.map((e) => e.name), contacts, + contactCorrection: contact ? { min: round(correction.min), max: round(correction.max) } : null, sourceSlide: round(sourceSlide), + sourceHipsRatio: [round(sourceHips.min), round(sourceHips.max)], aligned: [...restAlign.keys()].map((e) => e.name), + ik: footIk ? { legs: ik.legs, maxCorrection: round(ik.maxCorrection) } : null, + rootMotion: { + mode: rootMotion, extracted: rootMotion !== 'keep', + displacement: [round(drift.x), round(drift.z)], + velocity: [round(drift.x / length), round(drift.z / length)], + speed: round(Math.hypot(drift.x, drift.z) / length), + }, + }; +} + +/** Penetration below the bind floor tolerated before the toe clamp acts (m). */ +export const TOE_CLAMP_TOLERANCE = 0.005; + +/** + * Bake-time, mesh-aware floor clamp for the toes (`rig`: loadRig of the character). Per frame, + * the vertices whose dominant joint is a ToeBase are skinned; when the lowest sinks below the + * bind floor, that ToeBase is pitched up about the horizontal axis across the toe lever until + * it clears (at most 3 iterations, 45° per step). Rewrites `result.rotations` in place. + * The toes of a character with a longer or differently pitched foot than the source would + * otherwise push through the floor at heel-off. Returns { frames, maxDeg }. + */ +export function clampToesToFloor(rig, result, { iterations = 3 } = {}) { + const bind = skinPositions(rig); + let floor = Infinity; + for (const b of bind) for (let v = 1; v < b.length; v += 3) floor = Math.min(floor, b[v]); + const node = (name) => rig.byName.get(name)?.[0]; + const sides = ['LeftToeBase', 'RightToeBase'].filter((n) => node(n) && result.rotations.has(n)).map((name) => { + const slot = new Set(rig.names.map((n, i) => (n === name ? i : -1)).filter((i) => i >= 0)); + const verts = []; + rig.prims.forEach((p, pi) => { + for (let v = 0; v < p.count; v += 1) { + let best = 0; + for (let k = 1; k < 4; k += 1) if (p.W[v * 4 + k] > p.W[v * 4 + best]) best = k; + if (slot.has(p.J[v * 4 + best])) verts.push([pi, v]); + } + }); + return { name, node: node(name), verts }; + }).filter((s) => s.verts.length); + const stats = { frames: 0, maxDeg: 0 }; + if (!sides.length) return stats; + const hipsNode = node('Hips'); + const frames = result.times.length; + for (let i = 0; i < frames; i += 1) { + const overrides = new Map(); + for (const [name, arr] of result.rotations) { + const n = node(name); + if (n) overrides.set(n, { ...rig.trs.get(n), r: Array.from(arr.slice(i * 4, i * 4 + 4)) }); + } + overrides.set(hipsNode, { ...overrides.get(hipsNode), t: Array.from(result.hips.slice(i * 3, i * 3 + 3)) }); + let touched = false; + for (let it = 0; it < iterations; it += 1) { + const skinned = skinPositions(rig, overrides); + const world = worldMatrices(rig, overrides); + let moved = false; + for (const side of sides) { + let low = Infinity, at = null; + for (const [pi, v] of side.verts) if (skinned[pi][v * 3 + 1] < low) { low = skinned[pi][v * 3 + 1]; at = [pi, v]; } + if (low >= floor - TOE_CLAMP_TOLERANCE) continue; + const V = new THREE.Vector3().fromArray(skinned[at[0]], at[1] * 3); + const P = new THREE.Vector3().setFromMatrixPosition(world(side.node)); + const lever = V.clone().sub(P); + const axis = lever.clone().cross(new THREE.Vector3(0, 1, 0)); + if (axis.lengthSq() < 1e-10 || lever.length() < 1e-4) continue; + const angle = Math.min(Math.PI / 4, Math.asin(Math.min(1, (floor - low) / lever.length())) + 1e-3); + const toeQ = new THREE.Quaternion(), parentQ = new THREE.Quaternion(); + world(side.node).decompose(new THREE.Vector3(), toeQ, new THREE.Vector3()); + world(rig.parent.get(side.node)).decompose(new THREE.Vector3(), parentQ, new THREE.Vector3()); + const turned = new THREE.Quaternion().setFromAxisAngle(axis.normalize(), angle).multiply(toeQ); + const local = parentQ.invert().multiply(turned).normalize(); + const prev = result.rotations.get(side.name).slice(i * 4, i * 4 + 4); + if (prev[0] * local.x + prev[1] * local.y + prev[2] * local.z + prev[3] * local.w < 0) local.set(-local.x, -local.y, -local.z, -local.w); + result.rotations.get(side.name).set(local.toArray(), i * 4); + overrides.set(side.node, { ...overrides.get(side.node), r: local.toArray() }); + stats.maxDeg = Math.max(stats.maxDeg, THREE.MathUtils.radToDeg(angle)); + moved = touched = true; + } + if (!moved) break; + } + if (touched) stats.frames += 1; + } + stats.maxDeg = +stats.maxDeg.toFixed(2); + return stats; +} + +/** + * Clip GLB: the target skeleton (no mesh) and one animation, LINEAR, rotations for every + * mapped joint plus the Hips translation. `extras` lands on the animation (`extras.clip`). + */ +export function writeClipDocument(target, result, name, extras = {}) { + const doc = new Document(); + const buffer = doc.createBuffer(); + const scene = doc.createScene('scene'); + const nodeOf = new Map(); + const firstByName = new Map(); + for (const e of target.order) { + const node = doc.createNode(e.name).setTranslation([...e.t]).setRotation([...e.r]).setScale([...e.s]); + nodeOf.set(e, node); + if (!firstByName.has(e.name)) firstByName.set(e.name, node); + if (e.parent) nodeOf.get(e.parent).addChild(node); else scene.addChild(node); + } + const animation = doc.createAnimation(name); + const input = doc.createAccessor().setType('SCALAR').setBuffer(buffer).setArray(Float32Array.from(result.times)); + const track = (node, path, type, array) => { + const sampler = doc.createAnimationSampler().setInput(input).setInterpolation('LINEAR') + .setOutput(doc.createAccessor().setType(type).setBuffer(buffer).setArray(array)); + animation.addSampler(sampler); + animation.addChannel(doc.createAnimationChannel().setTargetNode(node).setTargetPath(path).setSampler(sampler)); + }; + for (const [joint, array] of result.rotations) track(firstByName.get(joint), 'rotation', 'VEC4', array); + track(firstByName.get('Hips'), 'translation', 'VEC3', result.hips); + animation.setExtras({ clip: { schema: CLIP_SCHEMA, skeleton: 'meshy-28', ...extras } }); + return doc; +} + +/** `extras.clip` of a clip document's first animation ({} when absent). */ +export function clipMetadata(doc) { + return doc.getRoot().listAnimations()[0]?.getExtras()?.clip || {}; +} diff --git a/tools/lib/animation-sources.mjs b/tools/lib/animation-sources.mjs new file mode 100644 index 0000000..04033be --- /dev/null +++ b/tools/lib/animation-sources.mjs @@ -0,0 +1,87 @@ +// Source loaders for the animation conversion (docs/animation-conversion.md): Mixamo FBX +// (three.js FBXLoader, with or without skin), Quaternius UAL glTF and meshy-28 clip GLBs. +import { NodeIO } from '@gltf-transform/core'; +import { ALL_EXTENSIONS } from '@gltf-transform/extensions'; +import { readFileSync } from 'node:fs'; +import path from 'node:path'; +import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader.js'; +import { uniqueJointNames } from './character-rig.mjs'; +import { MIXAMO_TO_MESHY28, UAL_TO_MESHY28, gltfPoseSource, mixamoBaseName, objectPoseSource } from './animation-retarget.mjs'; + +export const RIG_MAPS = Object.freeze({ + mixamo: MIXAMO_TO_MESHY28, + ual: UAL_TO_MESHY28, + 'meshy-28': Object.freeze(Object.fromEntries(uniqueJointNames.map((n) => [n, n]))), +}); + +/** Which source rig a list of bone names belongs to (null when none matches). */ +export function detectRig(names) { + const set = new Set(names); + const base = new Set(names.map(mixamoBaseName)); + if (names.some((n) => /^mixamorig/.test(n)) || (base.has('Spine2') && base.has('LeftUpLeg'))) return 'mixamo'; + if (set.has('pelvis') && set.has('spine_01') && set.has('upperarm_l')) return 'ual'; + if (set.has('Hips') && set.has('Spine02') && set.has('LeftUpLeg')) return 'meshy-28'; + return null; +} + +/** The longest non-empty take of an FBX/three.js group (Mixamo files add an empty "Take 001"). */ +export function pickClip(animations, take) { + if (take) { + const named = animations.find((a) => a.name === take); + if (!named) throw new Error(`take ${take} not found (have ${animations.map((a) => a.name).join(', ')})`); + return named; + } + return [...animations].filter((a) => a.tracks.length).sort((a, b) => b.duration * b.tracks.length - a.duration * a.tracks.length)[0] || null; +} + +/** Parse an FBX file with three's FBXLoader (embedded textures are irrelevant and silenced). */ +export function parseFbx(file) { + const bytes = readFileSync(file); + const warn = console.warn; + console.warn = () => {}; + try { + return new FBXLoader().parse(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength), ''); + } finally { + console.warn = warn; + } +} + +const io = new NodeIO().registerExtensions(ALL_EXTENSIONS); + +/** + * Open one source clip: { source (pose source), rig, take, file }. + * FBX: Mixamo rig. glTF/GLB: UAL or meshy-28 rig, `action` selects the animation by name + * (default: the first). `rig` overrides detection. + */ +export async function openSource(file, { action, take, rig } = {}) { + const ext = path.extname(file).toLowerCase(); + if (ext === '.fbx') { + const group = parseFbx(file); + const names = []; + group.traverse((o) => names.push(o.name)); + const kind = rig || detectRig(names); + if (!RIG_MAPS[kind]) throw new Error(`${file}: unknown source rig (bones ${names.slice(0, 6).join(', ')}…)`); + const clip = pickClip(group.animations, take); + if (!clip) throw new Error(`${file}: no animation`); + return { file, rig: kind, take: clip.name, source: objectPoseSource(group, clip, RIG_MAPS[kind]) }; + } + if (ext === '.glb' || ext === '.gltf') { + const doc = await io.read(file); + const kind = rig || detectRig(doc.getRoot().listNodes().map((n) => n.getName())); + if (!RIG_MAPS[kind]) throw new Error(`${file}: unknown source rig`); + const animations = doc.getRoot().listAnimations(); + const animation = action ? animations.find((a) => a.getName() === action) : animations[0]; + if (!animation) throw new Error(`${file}: animation ${action ?? '(first)'} not found${action ? ` (have ${animations.length})` : ''}`); + return { file, rig: kind, take: animation.getName(), doc, source: gltfPoseSource(doc, animation, RIG_MAPS[kind]) }; + } + throw new Error(`${file}: unsupported source format ${ext}`); +} + +/** Animation names of a glTF/GLB source with durations (for --list). */ +export async function listActions(file) { + const doc = await io.read(file); + return doc.getRoot().listAnimations().map((a) => ({ + name: a.getName(), + duration: +Math.max(0, ...a.listSamplers().map((s) => s.getInput().getMax([])[0])).toFixed(3), + })); +} From a5ddd114ffd2cbadc6524bed3741bde7195a0159 Mon Sep 17 00:00:00 2001 From: rubenmarcus Date: Mon, 9 Nov 2026 03:34:41 +0000 Subject: [PATCH 05/31] Add the clip QA gate and contact sheets clip-qa skins every frame on the character and gates foot slide inside contact windows (root motion added back, relative to the source's own slide), floor penetration, floating, hips height, loop seams, two-hand grip stability and skin stretch through rig-pose-test --clips. clip-sheet renders evenly spaced instants from a fixed camera over a 10 cm floor grid. Agent: Claude Code Signed-off-by: rubenmarcus --- tools/animations/clip-qa.mjs | 72 +++++++++++ tools/animations/clip-sheet.mjs | 59 +++++++++ tools/blender/render_clip_frames.py | 109 +++++++++++++++++ tools/lib/clip-qa.mjs | 183 ++++++++++++++++++++++++++++ 4 files changed, 423 insertions(+) create mode 100755 tools/animations/clip-qa.mjs create mode 100755 tools/animations/clip-sheet.mjs create mode 100644 tools/blender/render_clip_frames.py create mode 100644 tools/lib/clip-qa.mjs diff --git a/tools/animations/clip-qa.mjs b/tools/animations/clip-qa.mjs new file mode 100755 index 0000000..1139f6b --- /dev/null +++ b/tools/animations/clip-qa.mjs @@ -0,0 +1,72 @@ +#!/usr/bin/env node +// Clip QA gate (docs/animation-conversion.md): foot slide while planted, lowest vertex against +// the floor, hips height range, loop seam, two-hand grip stability and skin stretch (through +// tools/characters/rig-pose-test.mjs --clips) for meshy-28 clips baked onto one character. +// +// node tools/animations/clip-qa.mjs --model= --clips= [--states=] +// [--out=] [--label=] [--samples=] [--no-stretch] [--strict] +// +// Clip metadata (extras.clip: loop, hold, airborne, rootMotion) selects the gates that apply. +// --strict exits 1 when any clip fails tools/lib/clip-qa.mjs#CLIP_QA_THRESHOLDS. +import { NodeIO } from '@gltf-transform/core'; +import { ALL_EXTENSIONS } from '@gltf-transform/extensions'; +import { execFileSync } from 'node:child_process'; +import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { clipMetadata } from '../lib/animation-retarget.mjs'; +import { clipSampler, loadRig } from '../lib/character-rig.mjs'; +import { CLIP_QA_THRESHOLDS, evaluateClip, measureClip, stretchFromPoseReport } from '../lib/clip-qa.mjs'; + +const args = process.argv.slice(2); +const flag = (name) => args.find((a) => a.startsWith(`--${name}=`))?.slice(name.length + 3); +const model = flag('model'), clipsDir = flag('clips'); +if (!model || !clipsDir) { + console.error('usage: clip-qa.mjs --model= --clips= [--states=] [--out=] [--label=] [--samples=] [--no-stretch] [--strict]'); + process.exit(1); +} +const io = new NodeIO().registerExtensions(ALL_EXTENSIONS); +const states = flag('states')?.split(',').filter(Boolean) + || readdirSync(clipsDir).filter((f) => f.endsWith('.glb')).map((f) => f.slice(0, -4)).sort(); + +let poseReport = null; +if (!args.includes('--no-stretch')) { + const scratch = mkdtempSync(path.join(tmpdir(), 'clip-qa-')); + const reportFile = path.join(scratch, 'pose-test.json'); + const poseTest = fileURLToPath(new URL('../characters/rig-pose-test.mjs', import.meta.url)); + execFileSync(process.execPath, [poseTest, model, `--clips=${clipsDir}`, `--states=${states.join(',')}`, `--samples=${flag('samples') || 12}`, `--out=${reportFile}`], { stdio: 'pipe' }); + poseReport = JSON.parse(readFileSync(reportFile, 'utf8')); + rmSync(scratch, { recursive: true, force: true }); +} + +const rig = loadRig(await io.read(model)); +const clips = []; +for (const state of states) { + const doc = await io.read(path.join(clipsDir, `${state}.glb`)); + const meta = clipMetadata(doc); + const sampler = clipSampler(doc); + if (!sampler) throw new Error(`${state}: no animation`); + const metrics = measureClip(rig, sampler, meta); + metrics.stretch = poseReport ? stretchFromPoseReport(poseReport, state) : null; + const failures = evaluateClip(metrics, meta); + clips.push({ name: state, loop: Boolean(meta.loop), hold: meta.hold || 'none', airborne: Boolean(meta.airborne), rootMotion: meta.rootMotion || null, metrics, failures }); +} +const report = { + model: path.resolve(model), label: flag('label') || path.basename(model, '.glb'), clips: path.resolve(clipsDir), + thresholds: CLIP_QA_THRESHOLDS, + synthetic: poseReport ? poseReport.summary.synthetic : null, + clipCount: clips.length, failing: clips.filter((c) => c.failures.length).map((c) => c.name), + results: clips, +}; +if (flag('out')) writeFileSync(flag('out'), `${JSON.stringify(report, null, 2)}\n`); + +const v = (x) => (x == null ? '—' : x); +console.log(`${report.label}: ${clips.length} clips, ${report.failing.length} failing`); +console.log(' clip slide(src) cm low min/max cm hips ratio (source) seam cm/° hands med±dev cm stretch max/back/hL/hR'); +for (const c of clips) { + const m = c.metrics, s = m.stretch; + console.log(` ${c.name.padEnd(20)} ${`${m.footSlide.maxCm}${m.footSlide.sourceCm != null ? `(${m.footSlide.sourceCm})` : ''}`.padStart(11)} ${`${m.lowestVertex.minCm}/${m.lowestVertex.maxCm}`.padStart(14)} ${`${m.hips.minRatio}–${m.hips.maxRatio}${m.hips.sourceRatio ? `(${m.hips.sourceRatio.map((x) => x.toFixed(2)).join('–')})` : ''}`.padStart(22)} ${(m.loopSeam ? `${m.loopSeam.positionCm}/${m.loopSeam.rotationDeg}` : '—').padStart(11)} ${(m.hands ? `${m.hands.medianCm}±${m.hands.maxDeviationCm}` : '—').padStart(16)} ${s ? `${v(s.maxEdge?.value)}/${v(s.backMaxEdge?.value)}/${v(s.handMaxEdgeL?.value)}/${v(s.handMaxEdgeR?.value)}` : '—'}`); + for (const f of c.failures) console.log(` FAIL ${f}`); +} +if (args.includes('--strict') && report.failing.length) process.exit(1); diff --git a/tools/animations/clip-sheet.mjs b/tools/animations/clip-sheet.mjs new file mode 100755 index 0000000..ed62cb9 --- /dev/null +++ b/tools/animations/clip-sheet.mjs @@ -0,0 +1,59 @@ +#!/usr/bin/env node +// Contact sheet of meshy-28 clips on one character (docs/animation-conversion.md). +// +// node tools/animations/clip-sheet.mjs --model= --clips= --out= +// [--states=] [--frames=6] [--view=front34|side] [--title=] [--work=] +// [--blender=] +// +// One row per clip, --frames evenly spaced instants (first to last frame). Each instant is +// skinned on the CPU (tools/lib/character-rig.mjs) into a static GLB, rendered by Blender from +// one fixed camera over a 10 cm floor grid (tools/blender/render_clip_frames.py), and the tiles +// are assembled by tools/characters/rig-review.mjs sheet. +import { NodeIO } from '@gltf-transform/core'; +import { ALL_EXTENSIONS } from '@gltf-transform/extensions'; +import { execFileSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, readdirSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { bakePosedDocument, clipOverrides, clipSampler, loadRig, skinPositions } from '../lib/character-rig.mjs'; + +const args = process.argv.slice(2); +const flag = (name) => args.find((a) => a.startsWith(`--${name}=`))?.slice(name.length + 3); +const model = flag('model'), clipsDir = flag('clips'), out = flag('out'); +if (!model || !clipsDir || !out) { + console.error('usage: clip-sheet.mjs --model= --clips= --out= [--states=] [--frames=6] [--view=front34|side] [--title=] [--work=] [--blender=]'); + process.exit(1); +} +const count = Math.max(2, Number(flag('frames') || 6)); +const view = flag('view') || 'front34'; +const blender = flag('blender') || process.env.BLENDER || '/Applications/Blender.app/Contents/MacOS/Blender'; +const work = flag('work') || mkdtempSync(path.join(tmpdir(), 'clip-sheet-')); +mkdirSync(work, { recursive: true }); +const io = new NodeIO().registerExtensions(ALL_EXTENSIONS); +const states = flag('states')?.split(',').filter(Boolean) + || readdirSync(clipsDir).filter((f) => f.endsWith('.glb')).map((f) => f.slice(0, -4)).sort(); + +const posed = [], labels = []; +let height = 0; +for (const state of states) { + const sampler = clipSampler(await io.read(path.join(clipsDir, `${state}.glb`))); + for (let k = 0; k < count; k += 1) { + const t = +(sampler.duration * (k / (count - 1))).toFixed(4); + const rig = loadRig(await io.read(model)); + if (!height) { + let lo = Infinity, hi = -Infinity; + for (const b of skinPositions(rig)) for (let v = 1; v < b.length; v += 3) { lo = Math.min(lo, b[v]); hi = Math.max(hi, b[v]); } + height = hi - lo; + } + const file = path.join(work, `${state}@${String(k).padStart(2, '0')}.glb`); + await io.write(file, bakePosedDocument(rig, skinPositions(rig, clipOverrides(rig, sampler, t)))); + posed.push(file); + labels.push(`${state} ${t}s`); + } +} +const renders = path.join(work, `renders-${view}`); +execFileSync(blender, ['-b', '--factory-startup', '--python', fileURLToPath(new URL('../blender/render_clip_frames.py', import.meta.url)), '--', renders, String(height), view, ...posed], { stdio: 'pipe', maxBuffer: 64 * 1024 * 1024 }); +const tiles = posed.map((file, i) => `${labels[i]}=${path.join(renders, `${path.basename(file, '.glb')}.png`)}`); +const title = flag('title') || `${path.basename(model, '.glb')} — ${path.basename(path.resolve(clipsDir))} (${view}, 10 cm floor grid, red line = origin x)`; +execFileSync(process.execPath, [fileURLToPath(new URL('../characters/rig-review.mjs', import.meta.url)), 'sheet', out, String(count), title, ...tiles], { stdio: 'inherit' }); diff --git a/tools/blender/render_clip_frames.py b/tools/blender/render_clip_frames.py new file mode 100644 index 0000000..8cea819 --- /dev/null +++ b/tools/blender/render_clip_frames.py @@ -0,0 +1,109 @@ +"""Render posed (static) character GLBs for animation contact sheets. + +Blender -b --factory-startup --python tools/blender/render_clip_frames.py -- ... + +Every frame uses the same camera, framed on a character of standing at the origin +(glTF +Z forward is Blender -Y), so motion, crouch depth and floor contact compare across +frames and clips. is `front34` (front three-quarter) or `side` (from the character's +left). The floor is a translucent plane at z = 0 with a 10 cm grid and a red horizon line +through the origin, so feet below the floor and sliding feet are visible. +""" +import math +import os +import sys + +import bpy +from mathutils import Vector + + +def reset_scene(): + bpy.ops.wm.read_factory_settings(use_empty=True) + + +def look_at(obj, target): + obj.rotation_euler = (Vector(target) - obj.location).to_track_quat('-Z', 'Y').to_euler() + + +def grid_material(): + mat = bpy.data.materials.new('clip_floor') + mat.use_nodes = True + nodes, links = mat.node_tree.nodes, mat.node_tree.links + bsdf = nodes['Principled BSDF'] + bsdf.inputs['Roughness'].default_value = 0.9 + coord = nodes.new('ShaderNodeTexCoord') + mapping = nodes.new('ShaderNodeMapping') + mapping.inputs['Scale'].default_value = (10, 10, 10) # one checker cell = 10 cm + checker = nodes.new('ShaderNodeTexChecker') + checker.inputs['Scale'].default_value = 1.0 + checker.inputs['Color1'].default_value = (0.075, 0.08, 0.09, 1) + checker.inputs['Color2'].default_value = (0.04, 0.045, 0.055, 1) + links.new(coord.outputs['Object'], mapping.inputs['Vector']) + links.new(mapping.outputs['Vector'], checker.inputs['Vector']) + links.new(checker.outputs['Color'], bsdf.inputs['Base Color']) + bsdf.inputs['Alpha'].default_value = 0.82 + if hasattr(mat, 'surface_render_method'): + mat.surface_render_method = 'BLENDED' + return mat + + +def setup(height, view): + bpy.ops.mesh.primitive_plane_add(size=6, location=(0, 0, 0)) + floor = bpy.context.object + floor.name = 'clip_floor' + floor.data.materials.append(grid_material()) + bpy.ops.mesh.primitive_cube_add(size=1, location=(0, 0, 0.0005)) + line = bpy.context.object + line.scale = (3, 0.002, 0.0005) + red = bpy.data.materials.new('origin_line') + red.diffuse_color = (0.9, 0.1, 0.1, 1) + red.use_nodes = True + red.node_tree.nodes['Principled BSDF'].inputs['Base Color'].default_value = (0.9, 0.1, 0.1, 1) + line.data.materials.append(red) + centre = Vector((0, 0, height * 0.46)) + distance = height * 1.75 + if view == 'side': + cam_loc = centre + Vector((distance, 0, height * 0.12)) + else: + cam_loc = centre + Vector((distance * 0.62, -distance * 0.78, height * 0.25)) + bpy.ops.object.camera_add(location=cam_loc) + camera = bpy.context.object + look_at(camera, centre) + camera.data.lens = 50 + bpy.context.scene.camera = camera + for location, energy, color in (((-2, -3, 4), 900, (1.0, 0.9, 0.8)), ((3, 2, 2.5), 500, (0.6, 0.75, 1.0))): + bpy.ops.object.light_add(type='AREA', location=location) + lamp = bpy.context.object + lamp.data.energy = energy + lamp.data.size = 2.5 + lamp.data.color = color + look_at(lamp, centre) + scene = bpy.context.scene + scene.render.engine = 'BLENDER_EEVEE' + scene.render.resolution_x = 360 + scene.render.resolution_y = 440 + scene.render.image_settings.file_format = 'PNG' + scene.world = bpy.data.worlds.new('clip_world') if scene.world is None else scene.world + scene.world.color = (0.03, 0.035, 0.045) + scene.view_settings.look = 'AgX - Medium High Contrast' + scene.view_settings.exposure = 0.6 + + +def render(src, out_dir): + before = set(bpy.context.scene.objects) + bpy.ops.import_scene.gltf(filepath=src) + imported = [o for o in bpy.context.scene.objects if o not in before] + scene = bpy.context.scene + scene.render.filepath = os.path.join(out_dir, os.path.basename(src).rsplit('.', 1)[0] + '.png') + bpy.ops.render.render(write_still=True) + for obj in imported: + bpy.data.objects.remove(obj, do_unlink=True) + print(f'RENDER {scene.render.filepath}') + + +args = sys.argv[sys.argv.index('--') + 1:] +out, height, view = os.path.abspath(args[0]), float(args[1]), args[2] +os.makedirs(out, exist_ok=True) +reset_scene() +setup(height, view) +for asset in args[3:]: + render(os.path.abspath(asset), out) diff --git a/tools/lib/clip-qa.mjs b/tools/lib/clip-qa.mjs new file mode 100644 index 0000000..32b75c3 --- /dev/null +++ b/tools/lib/clip-qa.mjs @@ -0,0 +1,183 @@ +// Clip QA metrics for meshy-28 clips on a skinned character (docs/animation-conversion.md). +// Every frame of the clip is skinned on the CPU (tools/lib/character-rig.mjs, same maths as +// three.js) and measured against the floor (y = lowest vertex of the bind pose): +// footSlide horizontal travel of a planted foot joint (ankle or ball) in the world, i.e. +// with the clip's extracted root motion added back (cm), inside the source's +// contact windows; the limit rises to the source's own slide + 1 cm; +// lowestVertex lowest skinned vertex per frame: the minimum (penetration when negative) +// and the maximum (the whole body floats) (cm); +// hips Hips height range against the bind pose; +// loopSeam first versus last frame for loop clips: joint positions (cm) and local +// rotations (degrees); +// hands LeftHand–RightHand distance; gated for two-handed weapon holds (rifle); +// stretch filled from tools/characters/rig-pose-test.mjs --clips (skin stretch). +import * as THREE from 'three'; +import { FOOT_CONTACT_JOINTS, footContacts } from './animation-retarget.mjs'; +import { POSE_THRESHOLDS, clipOverrides, skinPositions, worldMatrices } from './character-rig.mjs'; + +export const CLIP_QA_THRESHOLDS = Object.freeze({ + footSlideCm: 4, // planted-foot travel within one contact window + footSlideOverSourceCm: 1, // ...or at most this much above the source's own slide (extras.clip.contactSlide) + penetrationCm: 2, // lowest vertex may sink at most this far below the floor + floatCm: 3, // the per-frame lowest vertex may rise at most this far (grounded clips) + hipsMaxRatio: 1.08, // hips above the bind height (grounded clips): legs over-extended + loopSeamCm: 1.5, + loopSeamDeg: 5, + twoHandDeviationCm: 3, // |hand distance − median| for two-handed holds + stretch: POSE_THRESHOLDS.clip, +}); +export const TWO_HAND_HOLDS = Object.freeze(['rifle']); +const FOOT_JOINTS = FOOT_CONTACT_JOINTS; + +const cm = (m) => +(m * 100).toFixed(2); +/** Joint name carrying the largest skin weight of vertex [primitive, vertex]. */ +function dominantBone(rig, at) { + if (!at) return null; + const p = rig.prims[at[0]]; + let best = 0; + for (let k = 1; k < 4; k += 1) if (p.W[at[1] * 4 + k] > p.W[at[1] * 4 + best]) best = k; + return rig.names[p.J[at[1] * 4 + best]]; +} + +/** + * Measure one clip (`sampler` from clipSampler) with metadata `meta` (extras.clip) on `rig`. + * Returns the metric object; evaluateClip() applies the thresholds. + */ +export function measureClip(rig, sampler, meta = {}, { fps = meta.fps || 30 } = {}) { + const duration = sampler.duration; + const frames = Math.max(2, Math.round(duration * fps) + 1); + const bind = skinPositions(rig); + let floor = Infinity; + for (const b of bind) for (let v = 1; v < b.length; v += 3) floor = Math.min(floor, b[v]); + const restWorld = worldMatrices(rig); + const node = (name) => rig.byName.get(name)?.[0]; + const pos = (world, name) => (node(name) ? new THREE.Vector3().setFromMatrixPosition(world(node(name))) : null); + const restHeight = Object.fromEntries([...FOOT_JOINTS, 'Hips'].map((n) => [n, pos(restWorld, n)?.y])); + const rm = meta.rootMotion; + const velocity = rm && rm.extracted && rm.mode === 'in-place' ? new THREE.Vector3(rm.velocity[0], 0, rm.velocity[1]) : new THREE.Vector3(); + const deform = rig.joints.filter((j, i) => rig.joints.findIndex((k) => k.getName() === j.getName()) === i && !/^Curl_|^head_end$|^headfront$/.test(j.getName())); + + const lowest = [], lowestBone = [], hipsY = [], hands = [], feet = Object.fromEntries(FOOT_JOINTS.map((n) => [n, []])); + const firstLast = []; + for (let f = 0; f < frames; f += 1) { + const t = f === frames - 1 ? duration : Math.min(duration, f / fps); + const overrides = clipOverrides(rig, sampler, t); + const world = worldMatrices(rig, overrides); + let low = Infinity, lowAt = null; + skinPositions(rig, overrides).forEach((p, pi) => { for (let v = 1; v < p.length; v += 3) if (p[v] < low) { low = p[v]; lowAt = [pi, (v - 1) / 3]; } }); + lowest.push(low - floor); + lowestBone.push(lowAt); + hipsY.push(pos(world, 'Hips').y); + const l = pos(world, 'LeftHand'), r = pos(world, 'RightHand'); + if (l && r) hands.push(l.distanceTo(r)); + for (const n of FOOT_JOINTS) { + const p = pos(world, n); + if (p) feet[n].push({ t, y: p.y, x: p.x + velocity.x * t, z: p.z + velocity.z * t }); + } + if (f === 0 || f === frames - 1) { + firstLast.push({ + positions: deform.map((j) => new THREE.Vector3().setFromMatrixPosition(world(j))), + rotations: deform.map((j) => new THREE.Quaternion(...((overrides.get(j) || rig.trs.get(j)).r))), + }); + } + } + + // Foot slide: world travel of each foot joint inside its planted windows: the source's + // contacts carried by the clip (extras.clip.contacts), else detected on this character with + // the same height/speed rule (footContacts). + const fromClip = Boolean(meta.contacts); + const times = feet[FOOT_JOINTS.find((n) => feet[n].length)]?.map((s) => s.t) || []; + const windows = fromClip ? meta.contacts : footContacts(Object.fromEntries(FOOT_JOINTS.filter((n) => feet[n].length && restHeight[n] != null) + .map((n) => [n, feet[n].map((s) => ({ x: s.x, z: s.z, clear: s.y - restHeight[n] }))])), times); + const slide = { maxCm: 0, joint: null, window: null, contacts: fromClip ? 'clip' : 'detected', sourceCm: meta.contactSlide != null ? cm(meta.contactSlide) : null, plantedShare: 0 }; + let plantedFrames = 0, footFrames = 0; + for (const n of FOOT_JOINTS) { + const track = feet[n]; + footFrames += track.length; + for (const [a, b] of windows[n] || []) { + const w = track.slice(a, Math.min(b, track.length - 1) + 1); + plantedFrames += w.length; + let travel = 0; + for (const s of w) travel = Math.max(travel, Math.hypot(s.x - w[0].x, s.z - w[0].z)); + if (w.length && travel > slide.maxCm / 100) Object.assign(slide, { maxCm: cm(travel), joint: n, window: [+w[0].t.toFixed(3), +w[w.length - 1].t.toFixed(3)] }); + } + } + slide.plantedShare = footFrames ? +(plantedFrames / footFrames).toFixed(3) : 0; + + let seam = null; + if (meta.loop) { + const [a, b] = firstLast; + let posMax = 0, rotMax = 0, posJoint = null, rotJoint = null; + deform.forEach((j, i) => { + const d = a.positions[i].distanceTo(b.positions[i]); + if (d > posMax) { posMax = d; posJoint = j.getName(); } + const angle = THREE.MathUtils.radToDeg(a.rotations[i].angleTo(b.rotations[i])); + if (angle > rotMax) { rotMax = angle; rotJoint = j.getName(); } + }); + seam = { positionCm: cm(posMax), positionJoint: posJoint, rotationDeg: +rotMax.toFixed(2), rotationJoint: rotJoint }; + } + + const sorted = [...hands].sort((x, y) => x - y); + const median = sorted.length ? sorted[Math.floor(sorted.length / 2)] : null; + const minLowest = Math.min(...lowest), maxLowest = Math.max(...lowest); + return { + frames, duration: +duration.toFixed(4), fps, + footSlide: slide, + lowestVertex: { + minCm: cm(minLowest), minAt: +(lowest.indexOf(minLowest) / fps).toFixed(3), minBone: dominantBone(rig, lowestBone[lowest.indexOf(minLowest)]), + maxCm: cm(maxLowest), maxAt: +(lowest.indexOf(maxLowest) / fps).toFixed(3), floorY: +floor.toFixed(4), + }, + hips: { + restHeight: +restHeight.Hips.toFixed(4), min: +Math.min(...hipsY).toFixed(4), max: +Math.max(...hipsY).toFixed(4), + minRatio: +(Math.min(...hipsY) / restHeight.Hips).toFixed(3), maxRatio: +(Math.max(...hipsY) / restHeight.Hips).toFixed(3), + sourceRatio: meta.sourceHipsRatio || null, + }, + loopSeam: seam, + hands: median == null ? null : { + medianCm: cm(median), minCm: cm(sorted[0]), maxCm: cm(sorted[sorted.length - 1]), + maxDeviationCm: cm(Math.max(median - sorted[0], sorted[sorted.length - 1] - median)), + }, + }; +} + +/** Per-clip stretch summary from a rig-pose-test report (clip poses of that name). */ +export function stretchFromPoseReport(report, name) { + const poses = (report?.poses || []).filter((p) => p.kind === 'clip' && p.name === name); + if (!poses.length) return null; + const max = (get) => poses.reduce((best, p) => { const v = get(p); return v != null && (!best || v > best.value) ? { value: v, time: p.time } : best; }, null); + return { + samples: poses.length, + maxEdge: max((p) => p.maxEdge), backMaxEdge: max((p) => p.backMaxEdge), + handMaxEdgeL: max((p) => p.handMaxEdge?.L), handMaxEdgeR: max((p) => p.handMaxEdge?.R), + seamGapMax: max((p) => p.seamGapMax), + }; +} + +/** Threshold failures of one clip's metrics (empty when it passes). */ +export function evaluateClip(metrics, meta = {}, thresholds = CLIP_QA_THRESHOLDS) { + const failures = []; + const grounded = !meta.airborne; + const slideLimit = Math.max(thresholds.footSlideCm, (metrics.footSlide.sourceCm ?? -Infinity) + thresholds.footSlideOverSourceCm); + if (metrics.footSlide.maxCm > slideLimit) failures.push(`foot slide ${metrics.footSlide.maxCm} cm (${metrics.footSlide.joint} ${metrics.footSlide.window?.join('–')}s) > ${+slideLimit.toFixed(2)}`); + if (metrics.lowestVertex.minCm < -thresholds.penetrationCm) failures.push(`floor penetration ${metrics.lowestVertex.minCm} cm @${metrics.lowestVertex.minAt}s < -${thresholds.penetrationCm}`); + if (grounded && metrics.lowestVertex.maxCm > thresholds.floatCm) failures.push(`floats ${metrics.lowestVertex.maxCm} cm @${metrics.lowestVertex.maxAt}s > ${thresholds.floatCm}`); + if (grounded && metrics.hips.maxRatio > thresholds.hipsMaxRatio) failures.push(`hips rise to ${metrics.hips.maxRatio}× bind height > ${thresholds.hipsMaxRatio}`); + if (meta.loop && metrics.loopSeam) { + if (metrics.loopSeam.positionCm > thresholds.loopSeamCm) failures.push(`loop seam ${metrics.loopSeam.positionCm} cm (${metrics.loopSeam.positionJoint}) > ${thresholds.loopSeamCm}`); + if (metrics.loopSeam.rotationDeg > thresholds.loopSeamDeg) failures.push(`loop seam ${metrics.loopSeam.rotationDeg}° (${metrics.loopSeam.rotationJoint}) > ${thresholds.loopSeamDeg}`); + } + if (TWO_HAND_HOLDS.includes(meta.hold) && metrics.hands && metrics.hands.maxDeviationCm > thresholds.twoHandDeviationCm) { + failures.push(`two-hand grip drifts ${metrics.hands.maxDeviationCm} cm from ${metrics.hands.medianCm} cm > ${thresholds.twoHandDeviationCm}`); + } + const s = metrics.stretch, lim = thresholds.stretch; + if (s) { + if (s.maxEdge?.value > lim.maxEdge) failures.push(`skin stretch ${s.maxEdge.value}× @${s.maxEdge.time}s > ${lim.maxEdge}`); + if (s.backMaxEdge?.value > lim.backMaxEdge) failures.push(`back stretch ${s.backMaxEdge.value}× @${s.backMaxEdge.time}s > ${lim.backMaxEdge}`); + for (const side of ['L', 'R']) { + const v = s[`handMaxEdge${side}`]; + if (v?.value > lim.handMaxEdge) failures.push(`hand ${side} stretch ${v.value}× @${v.time}s > ${lim.handMaxEdge}`); + } + if (s.seamGapMax?.value > lim.seamGapMax) failures.push(`seam opens ${s.seamGapMax.value} m > ${lim.seamGapMax}`); + } + return failures; +} From bf3ce1c7c12e55d802d22964382d0e0ffda54690 Mon Sep 17 00:00:00 2001 From: rubenmarcus Date: Mon, 9 Nov 2026 03:34:42 +0000 Subject: [PATCH 06/31] Check the animation conversion on synthetic skeletons Mixamo-like bone trees with scrambled rest frames, duplicate leaves and three name prefixes, a Z-up UAL-like glTF and the synthetic skinned body cover the maps, delta transfer, spine order, root motion, resampling, facing, contact and IK, rest alignment, bake rules and every QA gate with one mutant each. Runs in npm run check without any Mixamo or UAL bytes. Agent: Claude Code Signed-off-by: rubenmarcus --- tools/checks/animation-conversion-check.mjs | 552 ++++++++++++++++++++ tools/studio-check.mjs | 9 +- 2 files changed, 560 insertions(+), 1 deletion(-) create mode 100755 tools/checks/animation-conversion-check.mjs diff --git a/tools/checks/animation-conversion-check.mjs b/tools/checks/animation-conversion-check.mjs new file mode 100755 index 0000000..de6f854 --- /dev/null +++ b/tools/checks/animation-conversion-check.mjs @@ -0,0 +1,552 @@ +#!/usr/bin/env node +// Deterministic check of the animation conversion pipeline (docs/animation-conversion.md). +// No Mixamo or UAL bytes: every source is a synthetic skeleton built here (a three.js bone +// tree shaped like FBXLoader's Mixamo output, a glTF tree shaped like Quaternius UAL) with +// deliberately scrambled rest frames, so only convention-independent maths can pass. +// A convert: bone maps and hierarchy, rig detection, identity, world-delta transfer, spine +// order, root motion modes, resampling/trim, facing, FBXLoader duplicate bones, UAL, +// ground contact + foot IK on different leg proportions; +// B bake: absolute arms, Curl_* untouched, hips scale, metadata round trip, unmapped rigs; +// Q clip QA: a clean synthetic clip passes and each mutant fails on its own clause, and the +// clip-qa CLI (with rig-pose-test.mjs --clips) gates skin stretch end to end. +import { Document, NodeIO } from '@gltf-transform/core'; +import { ALL_EXTENSIONS } from '@gltf-transform/extensions'; +import { execFileSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import * as THREE from 'three'; +import { meshy28Joints } from '../lib/character-pack.mjs'; +import { clipSampler, deformJointNames, loadRig } from '../lib/character-rig.mjs'; +import { + MESHY28_REFERENCE_JOINTS, MIXAMO_TO_MESHY28, UAL_TO_MESHY28, clampToesToFloor, clipMetadata, gltfPoseSource, mixamoBaseName, + objectPoseSource, referenceSkeletonDocument, retargetClip, skeletonGraph, writeClipDocument, +} from '../lib/animation-retarget.mjs'; +import { RIG_MAPS, detectRig } from '../lib/animation-sources.mjs'; +import { evaluateClip, measureClip } from '../lib/clip-qa.mjs'; +import { J, synthDocument } from './lib/synthetic-humanoid.mjs'; + +let failures = 0; +const clause = async (name, fn) => { + try { const note = await fn(); console.log(`PASS ${name}${note ? `: ${note}` : ''}`); } + catch (error) { failures += 1; console.error(`FAIL ${name}: ${error.message}`); } +}; +const assert = (ok, message) => { if (!ok) throw new Error(message); }; +const V = (a) => new THREE.Vector3(...a); +const Q = (axis, deg) => new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(...axis).normalize(), THREE.MathUtils.degToRad(deg)); +const X = [1, 0, 0], Y = [0, 1, 0], Z = [0, 0, 1]; + +// ----------------------------------------------------------------------------- source rigs +const MIXAMO_PARENTS = { + Hips: null, Spine: 'Hips', Spine1: 'Spine', Spine2: 'Spine1', Neck: 'Spine2', Head: 'Neck', + LeftShoulder: 'Spine2', LeftArm: 'LeftShoulder', LeftForeArm: 'LeftArm', LeftHand: 'LeftForeArm', + RightShoulder: 'Spine2', RightArm: 'RightShoulder', RightForeArm: 'RightArm', RightHand: 'RightForeArm', + LeftUpLeg: 'Hips', LeftLeg: 'LeftUpLeg', LeftFoot: 'LeftLeg', LeftToeBase: 'LeftFoot', + RightUpLeg: 'Hips', RightLeg: 'RightUpLeg', RightFoot: 'RightLeg', RightToeBase: 'RightFoot', + HeadTop_End: 'Head', LeftHandIndex1: 'LeftHand', +}; +const UAL_PARENTS = { + root: null, pelvis: 'root', spine_01: 'pelvis', spine_02: 'spine_01', spine_03: 'spine_02', neck_01: 'spine_03', Head: 'neck_01', + clavicle_l: 'spine_03', upperarm_l: 'clavicle_l', lowerarm_l: 'upperarm_l', hand_l: 'lowerarm_l', index_01_l: 'hand_l', + clavicle_r: 'spine_03', upperarm_r: 'clavicle_r', lowerarm_r: 'upperarm_r', hand_r: 'lowerarm_r', + thigh_l: 'pelvis', calf_l: 'thigh_l', foot_l: 'calf_l', ball_l: 'foot_l', ball_leaf_l: 'ball_l', + thigh_r: 'pelvis', calf_r: 'thigh_r', foot_r: 'calf_r', ball_r: 'foot_r', +}; +const meshyParent = new Map(meshy28Joints.map(([n, p]) => [n, p])); +const invert = (map) => Object.fromEntries(Object.entries(map).map(([k, v]) => [v, k])); + +/* Source joint layout in metres (glTF frame) from a meshy-28 layout; unmapped helpers offset. */ +function sourceLayout(map, parents, layout) { + const inv = invert(map); + const out = {}; + for (const name of Object.keys(parents)) { + if (map[name]) out[name] = layout[map[name]]; + else if (parents[name] && out[parents[name]]) out[name] = out[parents[name]].map((v, i) => v + (i === 1 ? 0.08 : 0.01)); + else out[name] = [0, 0, 0]; + } + for (const [meshy, src] of Object.entries(inv)) out[src] = layout[meshy]; + return out; +} +// A scrambled but deterministic rest frame per bone: conventions must not matter. +const scrambled = (i) => new THREE.Quaternion().setFromEuler(new THREE.Euler(0.7 * i + 0.3, 1.3 * i + 0.1, 0.4 * i - 0.2)); + +/** + * World pose function -> per-bone world rotations: `deltas[name]` rotates that joint (world + * axes) and everything below it, composed down the chain. + */ +function worldPose(parents, restWorld, deltas) { + const D = new Map(), W = new Map(); + const order = []; + const visit = (n) => { order.push(n); for (const [c, p] of Object.entries(parents)) if (p === n) visit(c); }; + for (const [n, p] of Object.entries(parents)) if (!p) visit(n); + for (const n of order) { + const parentD = parents[n] ? D.get(parents[n]) : new THREE.Quaternion(); + D.set(n, deltas[n] ? deltas[n].clone().multiply(parentD) : parentD.clone()); + W.set(n, D.get(n).clone().multiply(restWorld.get(n))); + } + return { D, W, order }; +} + +/** + * Mixamo-like three.js source in centimetres, as FBXLoader returns it (names `mixamorigX`). + * frames(t) -> { deltas, hips: [x,y,z] world displacement in metres }. + */ +function mixamoSource({ layout = MESHY28_REFERENCE_JOINTS, frames, duration = 1, fps = 30, prefix = 'mixamorig', dupLeaves = false, yaw = 0, unit = 100 }) { + const parents = MIXAMO_PARENTS; + const pts = sourceLayout(MIXAMO_TO_MESHY28, parents, layout); + const names = Object.keys(parents); + const restWorld = new Map(names.map((n, i) => [n, scrambled(i)])); + const group = new THREE.Group(); + group.rotation.y = yaw; + const bones = new Map(); + for (const n of names) { + const bone = new THREE.Bone(); + bone.name = `${prefix}${n}`; + bones.set(n, bone); + } + if (dupLeaves) { + // Skinned Mixamo FBX: FBXLoader adds a same-named leaf as the first child of each bone; the + // animated bone is the outer one and the leaf must never be picked. + for (const [n, bone] of bones) { + const dup = new THREE.Bone(); + dup.name = bone.name; + dup.quaternion.copy(Q([1, 1, 0], 70)); + bone.add(dup); + } + } + for (const n of names) { + const p = parents[n]; + const bone = bones.get(n); + const worldPos = V(pts[n]).multiplyScalar(unit); + if (p) { + const pq = restWorld.get(p), pp = V(pts[p]).multiplyScalar(unit); + bone.position.copy(worldPos.sub(pp).applyQuaternion(pq.clone().invert())); + bone.quaternion.copy(pq.clone().invert().multiply(restWorld.get(n))); + bones.get(p).add(bone); + } else { + bone.position.copy(worldPos); + bone.quaternion.copy(restWorld.get(n)); + group.add(bone); + } + } + const count = Math.round(duration * fps) + 1; + const times = Array.from({ length: count }, (_, i) => Math.min(duration, i / fps)); + const values = new Map(names.map((n) => [n, []])); + const hips = []; + for (const t of times) { + const f = frames(t); + const { W } = worldPose(parents, restWorld, Object.fromEntries(Object.entries(f.deltas || {}).map(([meshy, q]) => [invert(MIXAMO_TO_MESHY28)[meshy] || meshy, q]))); + for (const n of names) { + const local = parents[n] ? W.get(parents[n]).clone().invert().multiply(W.get(n)) : W.get(n); + values.get(n).push(...local.toArray()); + } + hips.push(...V(pts.Hips).add(V(f.hips || [0, 0, 0])).multiplyScalar(unit).toArray()); + } + const tracks = names.map((n) => new THREE.QuaternionKeyframeTrack(`${prefix}${n}.quaternion`, times, values.get(n))); + tracks.push(new THREE.VectorKeyframeTrack(`${prefix}Hips.position`, times, hips)); + const clip = new THREE.AnimationClip('mixamo.com', duration, tracks); + return objectPoseSource(group, clip, MIXAMO_TO_MESHY28); +} + +/** UAL-like glTF source: Z-up `root` (−90° about X) holding the pelvis tree, metres. */ +function ualSource({ frames, duration = 1, fps = 30 }) { + const parents = UAL_PARENTS; + const pts = sourceLayout(UAL_TO_MESHY28, parents, MESHY28_REFERENCE_JOINTS); + const names = Object.keys(parents); + const rootQ = new THREE.Quaternion(-Math.SQRT1_2, 0, 0, Math.SQRT1_2); + const restWorld = new Map(names.map((n, i) => [n, n === 'root' ? rootQ.clone() : scrambled(i + 3)])); + pts.root = [0, 0, 0]; + const doc = new Document(); + const buffer = doc.createBuffer(); + const nodes = new Map(); + for (const n of names) { + const p = parents[n]; + const pq = p ? restWorld.get(p) : new THREE.Quaternion(); + const pp = p ? V(pts[p]) : new THREE.Vector3(); + const node = doc.createNode(n).setTranslation(V(pts[n]).sub(pp).applyQuaternion(pq.clone().invert()).toArray()) + .setRotation(pq.clone().invert().multiply(restWorld.get(n)).toArray()); + nodes.set(n, node); + if (p) nodes.get(p).addChild(node); + } + doc.createScene('s').addChild(doc.createNode('Armature').addChild(nodes.get('root'))); + const count = Math.round(duration * fps) + 1; + const times = Float32Array.from({ length: count }, (_, i) => Math.min(duration, i / fps)); + const rot = new Map(names.map((n) => [n, []])); + const pelvis = []; + for (const t of times) { + const f = frames(t); + const { W } = worldPose(parents, restWorld, Object.fromEntries(Object.entries(f.deltas || {}).map(([meshy, q]) => [invert(UAL_TO_MESHY28)[meshy] || meshy, q]))); + for (const n of names) rot.get(n).push(...(parents[n] ? W.get(parents[n]).clone().invert().multiply(W.get(n)) : W.get(n)).toArray()); + pelvis.push(...V(pts.pelvis).add(V(f.hips || [0, 0, 0])).applyQuaternion(rootQ.clone().invert()).toArray()); + } + const anim = doc.createAnimation('Synthetic_Loop'); + const input = doc.createAccessor().setType('SCALAR').setArray(times).setBuffer(buffer); + const add = (n, pathName, type, arr) => { + const s = doc.createAnimationSampler().setInput(input).setOutput(doc.createAccessor().setType(type).setArray(Float32Array.from(arr)).setBuffer(buffer)).setInterpolation('LINEAR'); + anim.addSampler(s).addChannel(doc.createAnimationChannel().setTargetNode(nodes.get(n)).setTargetPath(pathName).setSampler(s)); + }; + for (const n of names) add(n, 'rotation', 'VEC4', rot.get(n)); + add('pelvis', 'translation', 'VEC3', pelvis); + return gltfPoseSource(doc, anim, UAL_TO_MESHY28); +} + +// ----------------------------------------------------------------------------- target FK +/** World joint positions of `graph` at frame i of a retarget result. */ +function fk(graph, result, i) { + const out = new Map(), world = new Map(); + for (const e of graph.order) { + const r = result.rotations.get(e.name) && graph.byName.get(e.name) === e ? Array.from(result.rotations.get(e.name).slice(i * 4, i * 4 + 4)) : e.r; + const t = e.name === 'Hips' ? Array.from(result.hips.slice(i * 3, i * 3 + 3)) : e.t; + const local = new THREE.Matrix4().compose(V(t), new THREE.Quaternion(...r), V(e.s)); + const m = e.parent ? world.get(e.parent).clone().multiply(local) : local; + world.set(e, m); + if (!out.has(e.name)) out.set(e.name, new THREE.Vector3().setFromMatrixPosition(m)); + } + return out; +} +const restPos = (graph, name) => graph.byName.get(name).restWorldP.clone(); +const reference = skeletonGraph(referenceSkeletonDocument()); +const still = () => ({ deltas: {} }); + +// ----------------------------------------------------------------------------- A convert +await clause('A1 Mixamo and UAL maps cover the 22 deforming meshy-28 joints once and keep the hierarchy', () => { + for (const [label, map, parents] of [['mixamo', MIXAMO_TO_MESHY28, MIXAMO_PARENTS], ['ual', UAL_TO_MESHY28, UAL_PARENTS]]) { + const targets = Object.values(map); + assert(new Set(targets).size === targets.length, `${label}: a meshy-28 joint is mapped twice`); + assert(JSON.stringify([...targets].sort()) === JSON.stringify([...deformJointNames].sort()), `${label}: maps ${targets.length} joints, expected exactly ${deformJointNames.join(',')}`); + for (const [src, meshy] of Object.entries(map)) { + let p = parents[src]; + while (p && !map[p]) p = parents[p]; + assert((p ? map[p] : null) === meshyParent.get(meshy), `${label}: ${src}->${meshy} sits under ${p ? map[p] : 'nothing'}, meshy-28 parent is ${meshyParent.get(meshy)}`); + } + } + return 'spine order Spine->Spine02, Spine1->Spine01, Spine2->Spine (Mixamo); spine_01->Spine02 (UAL)'; +}); + +await clause('A2 rig detection and Mixamo prefix normalisation', () => { + assert(detectRig(['mixamorigHips', 'mixamorigSpine2']) === 'mixamo', 'FBXLoader names'); + assert(detectRig(['Hips', 'Spine2', 'LeftUpLeg']) === 'mixamo', 'unprefixed Unity export'); + assert(detectRig(['root', 'pelvis', 'spine_01', 'upperarm_l']) === 'ual', 'UAL'); + assert(detectRig(['Armature', 'Hips', 'Spine02', 'LeftUpLeg']) === 'meshy-28', 'meshy-28'); + assert(detectRig(['Bip01', 'Bip01 Pelvis']) === null, 'unknown rig must not be guessed'); + for (const n of ['mixamorig:LeftArm', 'mixamorigLeftArm', 'mixamorig1:LeftArm', 'LeftArm']) assert(mixamoBaseName(n) === 'LeftArm', n); +}); + +await clause('A3 a source at rest yields the reference rest pose (scrambled source frames)', () => { + const result = retargetClip(mixamoSource({ frames: still }), reference); + let worst = 0; + const at = fk(reference, result, 0); + for (const name of deformJointNames) worst = Math.max(worst, at.get(name).distanceTo(restPos(reference, name))); + assert(worst < 1e-4, `joints move ${worst} m away from rest`); + assert(result.mapped.length === 22 && !result.rotations.has('Curl_R'), `mapped ${result.mapped.length}`); + return `${result.mapped.length} joints, worst ${worst.toExponential(1)} m`; +}); + +const armUpKneeHead = (t) => ({ deltas: { LeftArm: Q(Z, 90 * t), RightLeg: Q(X, 60 * t), Head: Q(Y, 30 * t) } }); +await clause('A4 world-rotation deltas transfer onto the reference (arm up 90°, knee 60°, head 30°)', () => { + const result = retargetClip(mixamoSource({ frames: armUpKneeHead }), reference, { footIk: false }); + const at = fk(reference, result, result.times.length - 1); + const pivot = (joint, child, q) => restPos(reference, joint).add(restPos(reference, child).sub(restPos(reference, joint)).applyQuaternion(q)); + const hand = pivot('LeftArm', 'LeftHand', Q(Z, 90)).sub(restPos(reference, 'LeftArm')); + const got = at.get('LeftHand').clone().sub(at.get('LeftArm')); + assert(got.distanceTo(hand) < 1e-3, `left hand off by ${got.distanceTo(hand)} m`); + const ankle = restPos(reference, 'RightFoot').sub(restPos(reference, 'RightLeg')).applyQuaternion(Q(X, 60)); + const gotAnkle = at.get('RightFoot').clone().sub(at.get('RightLeg')); + assert(gotAnkle.distanceTo(ankle) < 1e-3, `right ankle off by ${gotAnkle.distanceTo(ankle)} m`); + const front = at.get('headfront').clone().sub(at.get('Head')); + const wantFront = restPos(reference, 'headfront').sub(restPos(reference, 'Head')).applyQuaternion(Q(Y, 30)); + assert(front.distanceTo(wantFront) < 1e-3, `head turn off by ${front.distanceTo(wantFront)} m`); + return 'hand, ankle and head-front within 1 mm'; +}); + +await clause('A5 Mixamo chest bend lands on meshy Spine, not on Spine02', () => { + const result = retargetClip(mixamoSource({ frames: (t) => ({ deltas: { Spine: Q(X, 30 * t) } }) }), reference, { footIk: false }); + const i = result.times.length - 1; + const at = fk(reference, result, i); + const angle = (a, b) => THREE.MathUtils.radToDeg(at.get(b).clone().sub(at.get(a)).angleTo(restPos(reference, b).sub(restPos(reference, a)))); + const low = angle('Spine02', 'Spine01'), top = angle('Spine', 'neck'); + assert(low < 0.05 && Math.abs(top - 30) < 0.05, `Spine02 segment turned ${low}°, Spine segment ${top}° (expected 0 and 30)`); + return `Spine02 ${low.toFixed(3)}°, Spine ${top.toFixed(2)}°`; +}); + +const walking = (t) => ({ deltas: {}, hips: [0.03 * Math.sin(2 * Math.PI * t), 0, 1.2 * t] }); +await clause('A6 root motion: in-place keeps sway and records velocity; keep and strip', () => { + const src = () => mixamoSource({ frames: walking }); + const scale = reference.byName.get('Hips').restWorldP.y / (MESHY28_REFERENCE_JOINTS.Hips[1] * 100); + const inPlace = retargetClip(src(), reference, { footIk: false }); + const n = inPlace.times.length; + const hipsX = (r, i) => fk(reference, r, i).get('Hips'); + const first = hipsX(inPlace, 0), last = hipsX(inPlace, n - 1), quarter = hipsX(inPlace, Math.round((n - 1) / 4)); + assert(first.distanceTo(last) < 1e-4, `in-place hips drift ${first.distanceTo(last)} m`); + assert(Math.abs(quarter.x - first.x - 0.03 * scale * 100) < 1e-3, `sway ${quarter.x - first.x} m, expected ${0.03 * scale * 100}`); + assert(Math.abs(inPlace.rootMotion.velocity[1] - 1.2 * scale * 100) < 1e-3 && inPlace.rootMotion.extracted, `velocity ${inPlace.rootMotion.velocity}`); + const keep = retargetClip(src(), reference, { rootMotion: 'keep', footIk: false }); + assert(Math.abs(hipsX(keep, n - 1).z - hipsX(keep, 0).z - 1.2 * scale * 100) < 1e-3, 'keep must leave the drift in the clip'); + const strip = retargetClip(src(), reference, { rootMotion: 'strip', footIk: false }); + const rest = restPos(reference, 'Hips'); + assert(Math.abs(hipsX(strip, n - 1).x - rest.x) < 1e-5 && Math.abs(hipsX(strip, n - 1).z - rest.z) < 1e-5, 'strip must pin hips XZ to rest'); + return `velocity ${inPlace.rootMotion.velocity[1]} m/s (scaled ${(scale * 100).toFixed(4)})`; +}); + +await clause('A7 resampling to 30 fps and trimming', () => { + const sweep = (t) => ({ deltas: { LeftArm: Q(Z, 90 * t) } }); + const r = retargetClip(mixamoSource({ frames: sweep, fps: 24 }), reference, { footIk: false }); + assert(r.times.length === 31 && Math.abs(r.times[30] - 1) < 1e-6, `24 fps source gave ${r.times.length} frames ending ${r.times.at(-1)}`); + const trimmed = retargetClip(mixamoSource({ frames: sweep, fps: 24 }), reference, { start: 0.25, end: 0.75, footIk: false }); + assert(trimmed.times.length === 16 && Math.abs(trimmed.times.at(-1) - 0.5) < 1e-6, `trim gave ${trimmed.times.length} frames`); + const at = fk(reference, trimmed, 0); + const want = restPos(reference, 'LeftHand').sub(restPos(reference, 'LeftArm')).applyQuaternion(Q(Z, 22.5)); + assert(at.get('LeftHand').clone().sub(at.get('LeftArm')).distanceTo(want) < 2e-3, 'trimmed frame 0 is not the source pose at 0.25 s'); +}); + +await clause('A8 a source facing -Z converts like one facing +Z', () => { + const a = retargetClip(mixamoSource({ frames: armUpKneeHead }), reference, { footIk: false }); + const b = retargetClip(mixamoSource({ frames: armUpKneeHead, yaw: Math.PI }), reference, { footIk: false }); + let worst = 0; + for (const i of [0, 15, 30]) { const pa = fk(reference, a, i), pb = fk(reference, b, i); for (const n of deformJointNames) worst = Math.max(worst, pa.get(n).distanceTo(pb.get(n))); } + assert(worst < 1e-4, `facing changes the result by ${worst} m`); +}); + +await clause('A9 FBXLoader duplicate leaf bones and Mixamo prefixes do not change the result', () => { + const a = retargetClip(mixamoSource({ frames: armUpKneeHead }), reference, { footIk: false }); + for (const [label, options] of [['duplicates', { dupLeaves: true }], ['mixamorig1 prefix', { prefix: 'mixamorig1' }], ['no prefix', { prefix: '' }]]) { + const b = retargetClip(mixamoSource({ frames: armUpKneeHead, ...options }), reference, { footIk: false }); + let worst = 0; + for (const [name, arr] of a.rotations) for (let k = 0; k < arr.length; k += 1) worst = Math.max(worst, Math.abs(arr[k] - b.rotations.get(name)[k])); + assert(worst < 1e-5, `${label}: rotations differ by ${worst}`); + } +}); + +await clause('A10 UAL glTF source (Z-up root) converts through UAL_TO_MESHY28', () => { + const result = retargetClip(ualSource({ frames: armUpKneeHead }), reference, { footIk: false }); + const at = fk(reference, result, result.times.length - 1); + const hand = restPos(reference, 'LeftHand').sub(restPos(reference, 'LeftArm')).applyQuaternion(Q(Z, 90)); + const err = at.get('LeftHand').clone().sub(at.get('LeftArm')).distanceTo(hand); + assert(result.mapped.length === 22 && err < 1e-3, `mapped ${result.mapped.length}, hand off by ${err} m`); + return `hand within ${err.toExponential(1)} m`; +}); + +/* Different proportions: the source's shins are 20% shorter (legs mirrored left to right). It squats (thighs forward, + shins back) with the hips lowered so both source ankles stay planted. */ +const shortShins = Object.fromEntries(Object.entries(MESHY28_REFERENCE_JOINTS).map(([n, p]) => [n, [...p]])); +const leftKnee = V(shortShins.LeftLeg); +for (const n of ['LeftFoot', 'LeftToeBase']) shortShins[n] = V(shortShins[n]).sub(leftKnee).multiplyScalar(0.8).add(leftKnee).toArray(); +// Mirror the left leg so both source ankles stay exactly planted under one hips path. +for (const n of ['UpLeg', 'Leg', 'Foot', 'ToeBase']) shortShins[`Right${n}`] = [-shortShins[`Left${n}`][0], shortShins[`Left${n}`][1], shortShins[`Left${n}`][2]]; +const squat = (layout, angle = (t) => 50 * Math.sin(Math.PI * t)) => { + const thigh = V(layout.LeftLeg).sub(V(layout.LeftUpLeg)), shin = V(layout.LeftFoot).sub(V(layout.LeftLeg)); + return (t) => { + const a = angle(t); + // Hips offset that keeps the ankle where it stands: minus the change of hip→ankle. + const moved = thigh.clone().applyQuaternion(Q(X, -a)).add(shin.clone().applyQuaternion(Q(X, a))).sub(thigh).sub(shin); + return { deltas: { LeftUpLeg: Q(X, -a), RightUpLeg: Q(X, -a), LeftLeg: Q(X, 2 * a), RightLeg: Q(X, 2 * a), LeftFoot: Q(X, -a), RightFoot: Q(X, -a) }, hips: moved.negate().toArray() }; + }; +}; + +await clause('A11 ground contact + foot IK keep planted feet still on different leg proportions', () => { + const run = (options) => { + const r = retargetClip(mixamoSource({ layout: shortShins, frames: squat(shortShins) }), reference, options); + let slide = 0, sink = 0; + for (let i = 0; i < r.times.length; i += 1) { + const at = fk(reference, r, i); + for (const n of ['LeftFoot', 'RightFoot']) { + const d = at.get(n).clone().sub(restPos(reference, n)); + slide = Math.max(slide, Math.hypot(d.x, d.z)); + sink = Math.max(sink, Math.abs(d.y)); + } + } + return { slide, sink, r }; + }; + const fixed = run({}); + assert(fixed.slide < 0.005 && fixed.sink < 0.005, `ankles move ${fixed.slide} m / ${fixed.sink} m with contact + IK`); + assert(Object.values(fixed.r.contacts).some((w) => w.length), 'source contacts not detected'); + const raw = run({ footContact: false, footIk: false }); + assert(raw.slide > 0.02 || raw.sink > 0.02, `without contact + IK the mismatch should show (${raw.slide}, ${raw.sink})`); + return `with: ${(fixed.slide * 100).toFixed(2)} cm slide / ${(fixed.sink * 100).toFixed(2)} cm height; without: ${(raw.slide * 100).toFixed(1)} / ${(raw.sink * 100).toFixed(1)} cm`; +}); + +await clause('A11 foot IK ramps wrap the seam of a loop (first frame == last frame)', () => { + // A periodic half squat whose only contact window ends 2 frames before the seam. + const frames = squat(shortShins, (t) => 30 + 15 * Math.sin(2 * Math.PI * t)); + const run = (loop) => retargetClip(mixamoSource({ layout: shortShins, frames }), reference, { contacts: { LeftFoot: [[22, 28]] }, loop }); + const seam = (r) => { + let worst = 0; + for (const arr of r.rotations.values()) for (let k = 0; k < 4; k += 1) worst = Math.max(worst, Math.abs(Math.abs(arr[k]) - Math.abs(arr[(r.times.length - 1) * 4 + k]))); + return worst; + }; + const looped = seam(run(true)), open = seam(run(false)); + assert(looped < 1e-5, `loop seam opens by ${looped} (quaternion component)`); + assert(open > 1e-3, `a non-loop retarget should differ at the ends here (${open})`); + return `seam ${looped.toExponential(1)} (non-loop ramp would leave ${open.toFixed(3)})`; +}); + +await clause('A12 limbs follow the source rest directions where the rests differ (straight vs bent knees)', () => { + // Source legs and arms are straight lines (knees and elbows on the hip-ankle / shoulder-wrist + // lines); the reference rests with bent knees and swept-back forearms. + const straight = Object.fromEntries(Object.entries(MESHY28_REFERENCE_JOINTS).map(([n, p]) => [n, [...p]])); + for (const [a, mid, b] of [['LeftUpLeg', 'LeftLeg', 'LeftFoot'], ['RightUpLeg', 'RightLeg', 'RightFoot'], ['LeftArm', 'LeftForeArm', 'LeftHand'], ['RightArm', 'RightForeArm', 'RightHand']]) { + straight[mid] = V(straight[a]).lerp(V(straight[b]), 0.5).toArray(); + } + const bend = (r, a, mid, b) => { const at = fk(reference, r, 0); return THREE.MathUtils.radToDeg(at.get(mid).clone().sub(at.get(a)).angleTo(at.get(b).clone().sub(at.get(mid)))); }; + const aligned = retargetClip(mixamoSource({ layout: straight, frames: still }), reference, { footIk: false }); + const raw = retargetClip(mixamoSource({ layout: straight, frames: still }), reference, { footIk: false, alignLimbs: [] }); + const knee = bend(aligned, 'LeftUpLeg', 'LeftLeg', 'LeftFoot'), elbow = bend(aligned, 'LeftArm', 'LeftForeArm', 'LeftHand'); + const rawKnee = bend(raw, 'LeftUpLeg', 'LeftLeg', 'LeftFoot'); + assert(knee < 0.1 && elbow < 0.1, `aligned knee ${knee}°, elbow ${elbow}° (expected straight like the source)`); + assert(rawKnee > 5, `without alignment the reference's bent rest knee should remain (${rawKnee}°)`); + return `knee ${knee.toFixed(3)}°, elbow ${elbow.toFixed(3)}° (unaligned knee ${rawKnee.toFixed(1)}°)`; +}); + +// ----------------------------------------------------------------------------- B bake +const io = new NodeIO().registerExtensions(ALL_EXTENSIONS); +/* A character with longer legs and A-pose arms (40° down): absolute arms, delta legs. */ +const aPose = Object.fromEntries(Object.entries(J).map(([n, p]) => [n, [...p]])); +for (const [side, sx] of [['Left', 1], ['Right', -1]]) { + const shoulder = V(aPose[`${side}Arm`]); + for (const n of [`${side}ForeArm`, `${side}Hand`, `Curl_${side[0]}`]) aPose[n] = V(aPose[n]).sub(shoulder).applyAxisAngle(new THREE.Vector3(0, 0, 1), THREE.MathUtils.degToRad(-40 * sx)).add(shoulder).toArray(); +} +const character = () => synthDocument({ joints: aPose }); +const armsForwardWalk = (t) => ({ deltas: { LeftArm: Q(Y, -70), RightArm: Q(Y, 70), LeftUpLeg: Q(X, -20 * Math.sin(2 * Math.PI * t)), RightUpLeg: Q(X, 20 * Math.sin(2 * Math.PI * t)) } }); +const referenceClip = (frames = armsForwardWalk, meta = {}) => { + const r = retargetClip(mixamoSource({ frames }), reference, { footIk: false }); + return writeClipDocument(reference, r, 'clip', { fps: 30, loop: true, hold: 'rifle', rootMotion: r.rootMotion, contacts: r.contacts, ...meta }); +}; + +await clause('B1 bake copies absolute arm directions, keeps legs as deltas, never animates Curl_*', async () => { + const clipDoc = await io.readBinary(await io.writeBinary(referenceClip())); + const source = gltfPoseSource(clipDoc, clipDoc.getRoot().listAnimations()[0], RIG_MAPS['meshy-28']); + const target = skeletonGraph(character()); + const r = retargetClip(source, target, { rootMotion: 'keep', absoluteArms: true, footIk: false }); + assert(!r.rotations.has('Curl_R') && !r.rotations.has('Curl_L'), 'Curl_* animated'); + const i = 7; + const refAt = fk(reference, retargetClip(gltfPoseSource(clipDoc, clipDoc.getRoot().listAnimations()[0], RIG_MAPS['meshy-28']), reference, { rootMotion: 'keep', footIk: false, footContact: false }), i); + const at = fk(target, r, i); + const dir = (m, a, b) => m.get(b).clone().sub(m.get(a)).normalize(); + const armErr = THREE.MathUtils.radToDeg(dir(at, 'LeftArm', 'LeftForeArm').angleTo(dir(refAt, 'LeftArm', 'LeftForeArm'))); + assert(armErr < 0.5, `A-pose character's arm points ${armErr}° away from the clip's`); + const hipsScale = target.byName.get('Hips').restWorldP.y / reference.byName.get('Hips').restWorldP.y; + assert(Math.abs(r.hipsScale - hipsScale) < 1e-9, `hips scale ${r.hipsScale}`); + return `arm direction error ${armErr.toFixed(3)}°, hips scale ${hipsScale.toFixed(4)}`; +}); + +await clause('B2 clip metadata round-trips through the GLB and unmapped rigs are refused', async () => { + const doc = await io.readBinary(await io.writeBinary(referenceClip())); + const meta = clipMetadata(doc); + assert(meta.schema === 'coro-solto/clip@1' && meta.skeleton === 'meshy-28' && meta.loop === true && meta.hold === 'rifle' && meta.rootMotion?.mode === 'in-place', JSON.stringify(meta).slice(0, 200)); + const stranger = new Document(); + stranger.createScene('s').addChild(stranger.createNode('Hips').addChild(stranger.createNode('Bip01 Spine'))); + let message = ''; + try { retargetClip(gltfPoseSource(doc, doc.getRoot().listAnimations()[0], RIG_MAPS['meshy-28']), skeletonGraph(stranger)); } catch (error) { message = error.message; } + assert(/only 1 target joints map/.test(message), `expected a refusal, got ${message || 'success'}`); +}); + +// ----------------------------------------------------------------------------- Q clip QA +const body = synthDocument(); +const bodyGraph = skeletonGraph(body); +const bodyRig = loadRig(body); +/** A meshy-28 clip on the synthetic body straight from world deltas (no retarget rules). */ +function bodyClip(frames, meta, { duration = 1, fps = 30 } = {}) { + const parents = Object.fromEntries(bodyGraph.order.filter((e) => e === bodyGraph.byName.get(e.name)).map((e) => [e.name, e.parent ? e.parent.name : null])); + const restWorld = new Map(bodyGraph.order.map((e) => [e.name, e.restWorldQ])); + const n = Math.round(duration * fps) + 1; + const times = Float32Array.from({ length: n }, (_, i) => Math.min(duration, i / fps)); + const names = deformJointNames; + const rotations = new Map(names.map((name) => [name, new Float32Array(n * 4)])); + const hips = new Float32Array(n * 3); + const hipsE = bodyGraph.byName.get('Hips'); + const parentInv = hipsE.parent.restWorld.clone().invert(); + times.forEach((t, i) => { + const f = frames(t, i, n); + const { W } = worldPose(parents, restWorld, f.deltas || {}); + for (const name of names) rotations.get(name).set((parents[name] ? W.get(parents[name]).clone().invert().multiply(W.get(name)) : W.get(name)).toArray(), i * 4); + hips.set(hipsE.restWorldP.clone().add(V(f.hips || [0, 0, 0])).applyMatrix4(parentInv).toArray(), i * 3); + }); + return writeClipDocument(bodyGraph, { times, rotations, hips }, 'q', { fps, ...meta }); +} +const qa = async (doc) => { + const reread = await io.readBinary(await io.writeBinary(doc)); + const meta = clipMetadata(reread); + const metrics = measureClip(bodyRig, clipSampler(reread), meta); + return { metrics, failures: evaluateClip(metrics, meta) }; +}; +const rifleHold = { LeftArm: Q(Y, -60), RightArm: Q(Y, 60) }; +const goodClip = (extra = () => ({})) => (t, i, n) => { + const e = extra(t, i, n); + return { deltas: { ...rifleHold, ...(e.deltas || {}) }, hips: e.hips || [0, -0.004 * Math.sin(Math.PI * t) ** 2, 0] }; +}; +const loopMeta = { loop: true, hold: 'rifle' }; + +await clause('Q1 a clean synthetic rifle loop passes every clip gate', async () => { + const { metrics, failures: f } = await qa(bodyClip(goodClip(), loopMeta)); + assert(!f.length, f.join('; ')); + return `slide ${metrics.footSlide.maxCm} cm, lowest ${metrics.lowestVertex.minCm}/${metrics.lowestVertex.maxCm} cm, seam ${metrics.loopSeam.positionCm} cm, grip ±${metrics.hands.maxDeviationCm} cm`; +}); +await clause('Q1 in-place root motion is added back before measuring slide', async () => { + // The body drifts backwards at 0.12 m/s in the clip; the declared root velocity cancels it. + const meta = { ...loopMeta, loop: false, rootMotion: { mode: 'in-place', extracted: true, velocity: [0, 0.12], speed: 0.12 } }; + const { failures: f } = await qa(bodyClip(goodClip((t) => ({ hips: [0, 0, -0.12 * t] })), meta)); + assert(!f.length, f.join('; ')); +}); +const mutants = [ + ['planted feet slide 10 cm', goodClip((t) => ({ hips: [0.1 * t, 0, 0] })), { ...loopMeta, loop: false }, /foot slide/], + ['feet sink 6 cm into the floor', goodClip(() => ({ hips: [0, -0.06, 0] })), loopMeta, /floor penetration/], + ['body floats 6 cm', goodClip(() => ({ hips: [0, 0.06, 0] })), loopMeta, /floats/], + ['hips over-extended', goodClip(() => ({ hips: [0, 0.1, 0] })), loopMeta, /hips rise/], + ['loop seam breaks', goodClip((t, i, n) => ({ deltas: i === n - 1 ? { LeftArm: Q(Y, -30) } : {} })), loopMeta, /loop seam/], + ['two-hand grip drifts', goodClip((t) => ({ deltas: { RightArm: Q(Y, 60 + 25 * Math.sin(2 * Math.PI * t)) } })), loopMeta, /two-hand grip/], + ['contacts from the clip are honoured', goodClip((t) => ({ hips: [0.1 * t, 0, 0] })), { ...loopMeta, loop: false, contacts: { LeftFoot: [[0, 30]] } }, /foot slide .*LeftFoot/], +]; +for (const [label, frames, meta, expected] of mutants) { + await clause(`Q2 clip QA mutant rejected: ${label}`, async () => { + const { failures: f } = await qa(bodyClip(frames, meta)); + assert(f.some((x) => expected.test(x)), `expected ${expected}, got ${f.join('; ') || 'a pass'}`); + return f.find((x) => expected.test(x)); + }); +} +await clause('Q2 airborne clips are exempt from the float and hips gates', async () => { + const { failures: f } = await qa(bodyClip(goodClip(() => ({ hips: [0, 0.1, 0] })), { ...loopMeta, airborne: true })); + assert(!f.some((x) => /floats|hips rise/.test(x)), f.join('; ')); +}); + +await clause('Q3 clip-qa CLI gates skin stretch through rig-pose-test --clips (and --strict)', async () => { + const dir = mkdtempSync(path.join(tmpdir(), 'anim-check-')); + try { + const cli = fileURLToPath(new URL('../animations/clip-qa.mjs', import.meta.url)); + await io.write(path.join(dir, 'body.glb'), synthDocument()); + await io.write(path.join(dir, 'torn.glb'), synthDocument({ mutant: 'hand-on-spine' })); + mkdirSync(path.join(dir, 'clips')); + await io.write(path.join(dir, 'clips', 'rifle-loop.glb'), bodyClip(goodClip(), loopMeta)); + const run = (model) => { + const out = path.join(dir, `${path.basename(model)}.json`); + let code = 0; + try { execFileSync(process.execPath, [cli, `--model=${model}`, `--clips=${path.join(dir, 'clips')}`, `--out=${out}`, '--samples=6', '--strict'], { stdio: 'pipe' }); } catch (error) { code = error.status; } + return { code, report: JSON.parse(readFileSync(out, 'utf8')) }; + }; + const good = run(path.join(dir, 'body.glb')); + assert(good.code === 0 && !good.report.failing.length, `clean body failed: ${good.report.results[0].failures.join('; ')}`); + const torn = run(path.join(dir, 'torn.glb')); + assert(torn.code === 1 && torn.report.results[0].failures.some((x) => /hand L stretch/.test(x)), `torn hand not caught: ${torn.report.results[0].failures.join('; ')}`); + return `clean ${good.report.results[0].metrics.stretch.maxEdge.value}×, torn hand ${torn.report.results[0].metrics.stretch.handMaxEdgeL.value}×`; + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +await clause('Q4 the bake-time toe clamp lifts toes pushed through the floor', async () => { + const doc = bodyClip(() => ({ deltas: { LeftToeBase: Q(X, 35), RightToeBase: Q(X, 35) } }), { loop: false }); + const graph = skeletonGraph(doc); + const anim = doc.getRoot().listAnimations()[0]; + const r = retargetClip(gltfPoseSource(doc, anim, RIG_MAPS['meshy-28']), bodyGraph, { rootMotion: 'keep', footIk: false, footContact: false }); + const before = measureClip(bodyRig, clipSampler(await io.readBinary(await io.writeBinary(writeClipDocument(graph, r, 'a', {})))), {}); + const stats = clampToesToFloor(bodyRig, r); + const after = measureClip(bodyRig, clipSampler(await io.readBinary(await io.writeBinary(writeClipDocument(graph, r, 'b', {})))), {}); + assert(before.lowestVertex.minCm < -1 && after.lowestVertex.minCm >= -0.6 && stats.frames > 0, `toes ${before.lowestVertex.minCm} -> ${after.lowestVertex.minCm} cm (${JSON.stringify(stats)})`); + return `lowest toe ${before.lowestVertex.minCm} -> ${after.lowestVertex.minCm} cm, ${stats.frames} frames, ≤${stats.maxDeg}°`; +}); + +if (failures) { + console.error(`FAIL animation conversion: ${failures} clause(s)`); + process.exit(1); +} +console.log('PASS animation conversion (maps, convert maths, root motion, contact/IK, bake rules, clip QA gates and mutants)'); diff --git a/tools/studio-check.mjs b/tools/studio-check.mjs index 335f975..2c6d36a 100755 --- a/tools/studio-check.mjs +++ b/tools/studio-check.mjs @@ -25,6 +25,13 @@ const requiredFiles = [ 'tools/lib/character-rig.mjs', 'tools/checks/character-rig-check.mjs', 'docs/character-rig.md', + 'tools/lib/animation-retarget.mjs', + 'tools/animations/manifests/pilot-20261109.json', + 'tools/lib/animation-sources.mjs', + 'tools/lib/clip-qa.mjs', + 'tools/checks/animation-conversion-check.mjs', + 'tools/checks/lib/synthetic-humanoid.mjs', + 'docs/animation-conversion.md', 'maps/lajes/gauntlet/fixtures/scene-report.valid.json', ]; for (const file of requiredFiles) { @@ -46,6 +53,6 @@ const scripts = walk(path.join(root, 'tools')).filter(file => file.endsWith('.mj for (const script of scripts) execFileSync(process.execPath, ['--check', script], { stdio: 'pipe' }); console.log(`PASS Studio structure, JSON, public asset boundary and ${scripts.length} Node tool syntax checks`); // Contract checks that use synthetic fixtures only; they never call paid generation APIs. -for (const check of ['tools/checks/character-pack-check.mjs', 'tools/checks/character-concept-prompt-check.mjs', 'tools/checks/character-rig-check.mjs']) { +for (const check of ['tools/checks/character-pack-check.mjs', 'tools/checks/character-concept-prompt-check.mjs', 'tools/checks/character-rig-check.mjs', 'tools/checks/animation-conversion-check.mjs']) { execFileSync(process.execPath, [path.join(root, check)], { stdio: 'inherit' }); } From ced4e4f97bd9fabdfbaa09aa7d2722c47662bcb7 Mon Sep 17 00:00:00 2001 From: rubenmarcus Date: Mon, 9 Nov 2026 03:34:42 +0000 Subject: [PATCH 07/31] Document the animation conversion pipeline and the pilot Bone maps, method, clip metadata, QA thresholds, the three gauntlet rounds on capitao-caveira and mst, and the residual issues. Agent: Claude Code Signed-off-by: rubenmarcus --- docs/animation-conversion.md | 196 +++++++++++++++++++++++++++++++++++ docs/character-pack.md | 2 +- docs/character-rig.md | 4 +- tools/README.md | 12 ++- 4 files changed, 209 insertions(+), 5 deletions(-) create mode 100644 docs/animation-conversion.md diff --git a/docs/animation-conversion.md b/docs/animation-conversion.md new file mode 100644 index 0000000..bb04374 --- /dev/null +++ b/docs/animation-conversion.md @@ -0,0 +1,196 @@ +# Animation conversion (Mixamo / UAL → meshy-28) + +Turns third-party character animations into clips for the shared **meshy-28** skeleton (see [character-pack.md](character-pack.md)) in three steps: + +1. **convert** a source clip (Adobe Mixamo FBX, Quaternius Universal Animation Library glTF) into a **reference clip** on the meshy-28 reference skeleton; +2. **bake** reference clips onto one character's meshy-28 rig (for example a [Blender rig](character-rig.md)); +3. **QA** the baked clips on that character's skinned mesh, and look at a contact sheet. + +Everything runs locally in Node (Blender only renders contact sheets). CI runs `tools/checks/animation-conversion-check.mjs` (part of `npm run check`) on synthetic skeletons and a synthetic skinned body only. + +## Licensing and where files live + +- **Mixamo** animations may be used in commercial games, but the raw files must not be redistributed standalone. Raw FBX files live only in the private `corosolto/studio-assets` repository (Git LFS, `animations/sources/`, indexed by `animations/catalog.json`). This public repository holds no FBX, GLB or clip bytes (`npm run check` rejects `.fbx`/`.glb`); converted clips ship only inside game packs. +- **Quaternius UAL 1 and 2** are CC0 1.0. The conversion still records the source in the clip metadata. +- Work directories (reference clips, baked clips, QA reports, sheets) stay outside this repository. +- Clips record their provenance in `extras.clip.source.id`: the studio-assets catalog id (for example `mixamo/loose/reload`). + +## Run + +```bash +# 1. convert: a manifest of catalog ids (sources resolved through the private catalog) +node tools/animations/convert-clips.mjs \ + --manifest=tools/animations/manifests/pilot-20261109.json \ + --catalog=/animations/catalog.json --out=/reference + +# or one file; UAL needs --action (list them with --list) +node tools/animations/convert-clips.mjs --out=/reference --name=reload --id=mixamo/loose/reload +node tools/animations/convert-clips.mjs --list +node tools/animations/convert-clips.mjs --action=Walk_Loop --out=/reference + +# 2. bake onto a character +node tools/animations/bake-character.mjs --model= --clips=/reference --out=/ + +# 3. QA gate (JSON report; --strict exits 1 on any failure) and contact sheet +node tools/animations/clip-qa.mjs --model= --clips=/ --out=/qa-.json --strict +node tools/animations/clip-sheet.mjs --model= --clips=/ --out=/.png [--view=side] +``` + +Manifest entries: `{ "name", "id"?, "source"?, "action"?, "take"?, "loop"?, "hold"?, "airborne"?, "start"?, "end"?, "rootMotion"? }`. `hold` is `rifle` (two-handed; the grip gate applies), `pistol`, `knife` or `none`. `airborne` exempts jumps from the float and hips gates. `start`/`end` trim in source seconds. UAL actions ending in `_Loop` default to `loop: true`; Mixamo loops must be declared. + +Use the UAL `_RM` files (`UAL1_Standard_RM.glb`): their `root` carries the root motion, which the conversion extracts into metadata. The `UAL*_Standard.glb` files are already in place, so locomotion keeps no speed and the QA cannot locate planted feet. + +## Bone maps + +Both maps cover the 22 deforming meshy-28 joints once each; `head_end`, `headfront` and the `Curl_*` helpers are never animated (the client writes the grip curl on `Curl_*`). The check (clause A1) proves that each mapped source bone sits under the source bone mapped to its meshy-28 parent. + +### Mixamo → meshy-28 (`MIXAMO_TO_MESHY28`) + +Mixamo names appear as `mixamorig:Hips` (FBX), `mixamorigHips` (three's FBXLoader drops the colon), `mixamorig1:Hips` or `Hips` (Unity re-exports); all are normalised to the base name. + +| Mixamo | meshy-28 | | Mixamo | meshy-28 | +| --- | --- | --- | --- | --- | +| Hips | Hips | | LeftUpLeg | LeftUpLeg | +| Spine | **Spine02** | | LeftLeg | LeftLeg | +| Spine1 | Spine01 | | LeftFoot | LeftFoot | +| Spine2 | **Spine** | | LeftToeBase | LeftToeBase | +| Neck | neck | | RightUpLeg | RightUpLeg | +| Head | Head | | RightLeg | RightLeg | +| LeftShoulder | LeftShoulder | | RightFoot | RightFoot | +| LeftArm | LeftArm | | RightToeBase | RightToeBase | +| LeftForeArm | LeftForeArm | | RightShoulder | RightShoulder | +| LeftHand | LeftHand | | RightArm | RightArm | +| | | | RightForeArm | RightForeArm | +| | | | RightHand | RightHand | + +Not mapped: `HeadTop_End`, `LeftToe_End`/`RightToe_End`, every finger bone. + +The spine follows the anatomy: Mixamo `Spine` (just above the hips) is meshy `Spine02` (child of `Hips`), and `Spine2` (the chest, parent of neck and clavicles) is meshy `Spine`. The client's `tools/retarget-mixamo.mjs` (and `retarget-ue2.mjs`) map these by name (`Spine`→`Spine`, `Spine2`→`Spine02`), which puts the chest's bend on the lowest spine joint (check clause A5). + +### Quaternius UAL → meshy-28 (`UAL_TO_MESHY28`) + +UAL 1 and 2 use the UE5-mannequin naming; the glTF puts the skeleton under a `root` node rotated −90° about X (Z-up inside), which the world-space maths absorbs. + +| UAL | meshy-28 | | UAL | meshy-28 | +| --- | --- | --- | --- | --- | +| pelvis | Hips | | thigh_l | LeftUpLeg | +| spine_01 | Spine02 | | calf_l | LeftLeg | +| spine_02 | Spine01 | | foot_l | LeftFoot | +| spine_03 | Spine | | ball_l | LeftToeBase | +| neck_01 | neck | | thigh_r | RightUpLeg | +| Head | Head | | calf_r | RightLeg | +| clavicle_l | LeftShoulder | | foot_r | RightFoot | +| upperarm_l | LeftArm | | ball_r | RightToeBase | +| lowerarm_l | LeftForeArm | | clavicle_r | RightShoulder | +| hand_l | LeftHand | | upperarm_r | RightArm | +| | | | lowerarm_r | RightForeArm | +| | | | hand_r | RightHand | + +Not mapped: `root` (root motion only), `*_leaf_*`, every finger bone (`index_*`, `middle_*`, `ring_*`, `pinky_*`, `thumb_*`). + +## Method (`tools/lib/animation-retarget.mjs`) + +One core, `retargetClip(source, target, options)`, does both convert and bake. The source is a pose source (`objectPoseSource` over FBXLoader's bone tree and AnimationClip, or `gltfPoseSource` over a glTF node tree); the target a `skeletonGraph` of a glTF document. + +**Reference skeleton.** The donor's joint positions (`MESHY28_REFERENCE_JOINTS`, measured from the client's `mst.glb`) with the donor rest frames (`buildMeshy28Skeleton`). Convert writes every clip against it; bake moves clips onto each character. + +**Rotations: world deltas.** Per bone and frame: `delta = srcWorld · srcRestWorld⁻¹`, `desiredWorld = delta · tgtRestWorld`, `tgtLocal = tgtParentWorld⁻¹ · desiredWorld`. No bone axis convention matters: the check builds its sources with scrambled rest frames. The source's facing is measured from its hip line and turned onto the target's (a source facing −Z converts like one facing +Z). Consecutive quaternion keys are kept in the same hemisphere so LINEAR slerp never takes the long way. + +**Rest alignment (`LIMB_ALIGNMENT`).** Upper arm, forearm, thigh and shin: before the delta is applied, the target's rest frame is turned by the shortest arc that makes the bone point like the source's rest bone. Mixamo and UAL rest with straight arms and legs; the donor rests with bent knees (18°) and forearms swept back, which plain deltas would add to every pose (crouched walks, rifle hands pulled back). Feet are not aligned: both rests stand flat, and ankle-to-ball slopes differ with foot shape. + +**Bake rule (port of the client's `retarget-glb.mjs`).** `LeftArm`/`LeftForeArm`/`LeftHand` and the right twins copy the clip's absolute world rotation (`absoluteArms`): an A-pose rig would otherwise hold every clip 30–40° off. The Blender rigs align those frames to the bones, so absolute frames point the bones where the clip points. Everything else uses deltas plus rest alignment on the legs. `Curl_*` are never animated. A target with fewer than 8 matching joints is refused (the client tool once wrote 11 empty clips and reported success). + +**Hips.** The hips' world displacement from the source rest, turned into the target's facing and scaled by the hips-height ratio. Root motion (`rootMotion`): + +- `in-place` (default): the straight line from the first to the last hips position (horizontal) is removed. Sway around it stays, a loop closes, and the line is recorded as `rootMotion: { displacement, velocity, speed }` in metres at the clip's scale (bake scales it again for each character), so the runtime can move the character, or set the playback rate, at the speed that keeps the feet planted; +- `keep`: horizontal motion stays in the clip; +- `strip`: hips XZ pinned to rest (the client's old behaviour; loses sway). + +**Ground contact (`footContact`).** Per frame the hips height is corrected so the target's lowest foot joint (ankle or ball, relative to its rest height) is as far above its rest height as the source's, scaled. The hips-height ratio alone is only right standing: with different leg proportions the target floated up to 8 cm on bent knees (pilot round 1). + +**Contacts and foot IK (`footIk`).** A source foot joint is planted where it is within 3 cm of its rest height and moves slower than 0.25 m/s in the source's world (root motion included), for at least 3 frames (`footContacts`). The windows travel with the clip (`extras.clip.contacts`, frame indices) and bake reuses them. Inside a window (ramped over 4 frames; ramps wrap the seam of a loop) two-bone IK (`solveTwoBone`: knee bend by the law of cosines about the current bend plane, then a hip swing) pins the ankle to the source ankle's displacement from its rest, scaled, added to the target ankle's rest. With the root velocity added back, that position is where the source keeps the foot, so planted feet stop sliding on characters whose legs differ from the source's. `contactSlide` records the source's own slide inside its windows. + +**Toe clamp (bake, `clampToesToFloor`).** Bake knows the character's mesh: per frame it skins the vertices that belong to each `ToeBase` and, when the lowest sinks more than 5 mm below the bind floor, pitches that toe up about the horizontal axis across the toe lever (at most 3 iterations of ≤45°). Longer or differently pitched feet otherwise pushed the toes 2.1–5.5 cm through the floor at heel-off (pilot round 2). + +**Sampling.** Output is resampled to 30 fps (`CLIP_FPS`) by sampling the source at `i/30` s, with the last frame exactly at the end (`frames = round(length · 30) + 1`). The FBX path samples through a `THREE.AnimationMixer` with `LoopOnce` + clamp (so the last frame is the real end pose); the glTF path samples LINEAR/STEP/CUBICSPLINE channels. FBXLoader adds a same-named leaf under each bone of a skinned Mixamo file; bones are resolved like the mixer resolves track names, so the animated bone is used (clause A9). The native key rate (most common key interval) is recorded as `source.nativeFps`. + +## Clip metadata (`extras.clip` on the animation) + +| Key | Meaning | +| --- | --- | +| `schema`, `skeleton` | `coro-solto/clip@1`, `meshy-28`. | +| `fps`, `frames`, `duration` | Output sampling. | +| `loop`, `hold`, `airborne` | From the manifest; select QA gates. | +| `rootMotion` | `{ mode, extracted, displacement: [x, z], velocity: [x, z], speed }` (m, m/s), scaled per character by bake. | +| `contacts`, `contactSlide` | Source contact windows per foot joint (frame indices) and the source's own slide inside them (m, scaled per character). | +| `hipsScale`, `footContact`, `footIk`, `alignedLimbs`, `sourceHipsRatio` | Conversion facts: hips-height ratio, hips correction range (m), IK legs and largest ankle correction (m), aligned bones, the source's hips height range as a fraction of its rest height. | +| `source` | `{ id, rig, file, take, nativeFps, duration, start, end }`. | +| `bakedFor` | Bake facts: `{ model, hipsScale, joints, footContact, footIk, toeClamp: { frames, maxDeg }, alignedLimbs }`. | + +The client loads these GLBs like its shared clips (skeleton nodes plus one animation, LINEAR); `extras` is ignored by three.js. + +## QA gate (`tools/animations/clip-qa.mjs`, `tools/lib/clip-qa.mjs`) + +Every frame of every clip is skinned on the CPU (same maths as three.js) on the character's mesh. The floor is the lowest vertex of the bind pose. + +| Gate | Measure | Limit (`CLIP_QA_THRESHOLDS`) | +| --- | --- | --- | +| Foot slide | Horizontal travel of each foot joint inside its contact windows, in the world (the clip's in-place root velocity added back). Windows come from `extras.clip.contacts`, else they are detected on the character with the same rule. | ≤ 4 cm, or ≤ the source's own slide + 1 cm | +| Floor penetration | Lowest skinned vertex over the clip (reports the dominant bone). | ≥ −2 cm | +| Floating | Highest of the per-frame lowest vertices (not for `airborne`). | ≤ 3 cm | +| Hips height | Hips height range / bind height; the source's range is reported next to it. | max ≤ 1.08 (not for `airborne`) | +| Loop seam | First versus last frame (loops): joint positions and local rotations. | ≤ 1.5 cm, ≤ 5° | +| Two-hand grip | `LeftHand`–`RightHand` distance, maximum deviation from its median (`hold: rifle`). | ≤ 3 cm | +| Skin stretch | `tools/characters/rig-pose-test.mjs --clips= --states= --samples=12`: per clip, the worst edge, upper back and hands. | `POSE_THRESHOLDS.clip`: 3.5×, 3.5×, 2.5×, seams 5 mm | + +The limits were set before the pilot from the client's gates (stretch, hands) and common foot-skating tolerances and were not loosened; round 3 added the source-relative slide allowance, because a motion-capture take can slide on its own (Grenade Throw: 3.5 cm over 8 s in the source) and no retarget can do better than its source. + +`tools/animations/clip-sheet.mjs` renders `--frames` evenly spaced instants of each clip (one row per clip) from a fixed camera over a 10 cm floor grid with Blender (`tools/blender/render_clip_frames.py`), assembled by `rig-review.mjs sheet`. + +## Check (`npm run check`) + +`tools/checks/animation-conversion-check.mjs` builds Mixamo-like bone trees (FBXLoader naming, scrambled rest frames, optional duplicate leaves, three prefixes, −Z facing) and a UAL-like glTF (Z-up `root`) in code, and a synthetic skinned body (`tools/checks/lib/synthetic-humanoid.mjs`, shared with the rig check). Clauses: maps and hierarchy (A1), rig detection (A2), rest identity (A3), world-delta transfer within 1 mm (A4), spine order (A5), root-motion modes (A6), 24 → 30 fps resampling and trim (A7), facing (A8), FBX duplicates and prefixes (A9), UAL (A10), ground contact + IK on shorter shins (A11: 0.00 cm with, 4.5 cm slide / 2.9 cm height without), loop-wrapped IK ramps (A11), rest alignment (A12: knee straight with, 18° without), bake rules (B1, B2), and the QA gates on a clean clip plus one mutant per gate, the CLI end to end with `--strict` and a torn-hand body, and the toe clamp (Q1–Q4). + +## Pilot (2026-11-09) + +Six Mixamo clips owner-downloaded (`tools/animations/manifests/pilot-20261109.json`): `Reload`, `Grenade Throw`, `Knife Idle`, `Rifle Pull Out`, and `walk left`/`walk right` from the Rifle 8-Way Locomotion pack (byte-identical to Pro Rifle). Baked onto `capitao-caveira` (Blender rig from [character-rig.md](character-rig.md)) and onto the legacy donor `mst`. Work directory (private): `csbrasil/local/anim-conv-20261109/` (`r1`, `r2`, `r3` rounds, `sheets/`, `ual/`). + +Gauntlet (all QA numbers measured with the final gate): + +- **Round 1**, the straight port of the client tools: feet float 5.7–8.1 cm on capitao-caveira (every clip but one) and penetrate up to 3.3 cm on mst, because the hips-height ratio is not the leg-length ratio when knees bend. 5/6 clips fail on capitao-caveira, 5/6 on mst. +- **Round 2**: ground contact, source contact windows, foot IK. Floating gone; slide inside source contacts at the source's own level. Remaining: toes through the floor at heel-off (mst −3.6 to −5.5 cm, capitao −2.1 cm), and crouched postures (hips 0.74–0.83 of rest against the source's 0.79–0.87) from the donor's bent rest knees. +- **Round 3**: rest alignment of arms and legs, bake-time toe clamp, slide limit relative to the source's own slide. capitao-caveira passes 6/6, mst 5/6. + +Round 3 QA (slide: measured (source's own); low: lowest vertex min/max; hips: ratio to bind (source); seam: position/rotation; grip: median ± max deviation; stretch: body/back/hand L/hand R): + +| capitao-caveira | slide cm | low cm | hips | seam cm/° | grip cm | stretch × | result | +| --- | --- | --- | --- | --- | --- | --- | --- | +| reload | 3.45 (3.31) | −1.35 / −0.03 | 0.94–0.98 (0.90–0.95) | — | 32.3 ± 12.6 | 2.09 / 1.67 / 1.22 / 1.17 | pass | +| grenade-throw | 4.04 (4.05) | −0.48 / 0.18 | 0.54–0.69 (0.48–0.61) | — | 50.4 ± 52.9 | 2.84 / 2.63 / 1.08 / 1.12 | pass | +| knife-idle (loop) | 0.66 (0.66) | 1.27 / 1.44 | 0.89–0.93 (0.85–0.90) | 0.00 / 0.04 | 49.9 ± 1.9 | 2.00 / 1.37 / 1.09 / 1.09 | pass | +| rifle-pull-out | 0.86 (0.87) | −0.12 / −0.02 | 1.00–1.01 (0.97–0.98) | — | 44.3 ± 12.5 | 2.20 / 1.66 / 1.19 / 1.25 | pass | +| rifle-walk-left (loop, rifle) | 1.79 (1.85) | −1.18 / 0.55 | 0.83–0.92 (0.79–0.87) | 0.03 / 0.07 | 29.9 ± 0.08 | 2.13 / 1.80 / 1.09 / 1.05 | pass | +| rifle-walk-right (loop, rifle) | 1.37 (1.44) | −1.05 / 0.14 | 0.87–0.95 (0.83–0.92) | 0.01 / 0.03 | 30.4 ± 0.41 | 2.12 / 1.94 / 1.10 / 1.05 | pass | + +| mst | slide cm | low cm | hips | seam cm/° | grip cm | stretch × | result | +| --- | --- | --- | --- | --- | --- | --- | --- | +| reload | 3.03 (2.90) | −1.29 / −0.03 | 0.91–0.97 (0.90–0.95) | — | 31.7 ± 16.8 | 3.02 / 3.02 / 1.66 / 1.30 | pass | +| grenade-throw | 3.55 (3.55) | **−5.48** / −0.16 | 0.50–0.64 (0.48–0.61) | — | 55.3 ± 69.8 | 3.19 / 2.70 / 1.14 / 1.14 | fail: right hand 5.5 cm into the floor at 2.93 s | +| knife-idle (loop) | 0.58 (0.58) | 1.12 / 1.25 | 0.87–0.91 (0.85–0.90) | 0.00 / 0.04 | 54.8 ± 2.5 | 2.15 / 2.15 / 1.23 / 1.14 | pass | +| rifle-pull-out | 0.76 (0.76) | −0.54 / −0.19 | 0.99 (0.97–0.98) | — | 49.1 ± 17.4 | 2.94 / 2.94 / 1.67 / 1.35 | pass | +| rifle-walk-left (loop, rifle) | 1.62 (1.62) | −1.36 / 0.31 | 0.82–0.90 (0.79–0.87) | 0.04 / 0.06 | 29.2 ± 0.31 | 2.70 / 2.70 / 1.18 / 1.04 | pass | +| rifle-walk-right (loop, rifle) | 1.61 (1.26) | −1.34 / 0.09 | 0.86–0.94 (0.83–0.92) | 0.02 / 0.03 | 29.3 ± 0.55 | 2.89 / 2.89 / 1.23 / 1.03 | pass | + +Root speed of the strafe walks: 1.53 m/s on the reference skeleton, 1.74 m/s baked on capitao-caveira (hips scale 1.14). Reload walks forward at 0.79 m/s (reference). + +A UAL 1 sample (`_RM` file: `Idle_Loop`, `Pistol_Reload`, `Walk_Loop`) passes on capitao-caveira; on mst `Walk_Loop` reaches −2.08 cm under `LeftFoot` (limit −2). + +## Limits and residual issues + +- **Hands and knees are not ground-constrained.** Only the feet have contact handling. In `grenade-throw` the donor's longer arms put the right hand 5.5 cm into the floor while kneeling; a hand-contact IK (or an arm-length-aware clamp like the toe clamp) is the next step. +- **Heel penetration** of up to 2.1 cm remains where the foot itself (not the toes) pitches below the floor; the toe clamp handles `ToeBase` vertices only. +- **Hips sit 0.02–0.08 of the bind height above the source's** (ratio columns above): the reference skeleton's thigh/shin proportions differ from Mixamo's, and the contact correction keeps the feet, not the hips height, faithful. +- **Grip distance is set by proportions.** `rifle` holds are stable over time (±0.1–0.6 cm) but the hands sit 29–30 cm apart; a weapon of a different length needs the client's hand IK or a per-weapon arm adjustment. +- **Root motion is a straight line.** Turning clips, curved paths and yaw are not extracted (hips yaw stays in the clip). +- **Contacts need root motion.** In-place sources (UAL `*_Standard.glb`) yield no contact windows for locomotion, so their foot slide is not measured; use the `_RM` files. +- The mesh-aware toe clamp runs only in bake (the reference skeleton has no mesh); reference clips may still have toes below the floor on other feet. diff --git a/docs/character-pack.md b/docs/character-pack.md index 3fa88f9..e1929ce 100644 --- a/docs/character-pack.md +++ b/docs/character-pack.md @@ -65,7 +65,7 @@ Photos of real people never enter either repository. `npm run check` builds a synthetic character pack (a programmatic 12-triangle skinned GLB and eleven one-channel clips, no real asset bytes), validates it, and requires each contract mutant to be rejected for its stated reason: missing states, unknown state, misnamed clip, clip driving no meshy-28 bone, clip channel without a path, clip without keyframes or with mismatched output, wrong skeleton id, renamed, reparented or missing bone, missing skin or weights, missing, mistyped or out-of-skin `JOINTS_0`, triangle strips, bad GLB magic or version, triangle and byte budgets (including the byte budget before hashing), bad rights, missing or invalid previews, undeclared files, and hash or size mutations. -`npm run check` also runs `tools/checks/character-rig-check.mjs`, the deterministic half of the Blender rig pipeline that produces these models (configs, `joints.json` validation, meshy-28 assembly and the pose test on a synthetic humanoid); see [character-rig.md](character-rig.md). +`npm run check` also runs `tools/checks/character-rig-check.mjs`, the deterministic half of the Blender rig pipeline that produces these models (configs, `joints.json` validation, meshy-28 assembly and the pose test on a synthetic humanoid); see [character-rig.md](character-rig.md). It also runs `tools/checks/animation-conversion-check.mjs`, the deterministic half of the clip conversion that produces the `animations` of a pack ([animation-conversion.md](animation-conversion.md)). ## Concept generation diff --git a/docs/character-rig.md b/docs/character-rig.md index e0aa71a..07636bd 100644 --- a/docs/character-rig.md +++ b/docs/character-rig.md @@ -64,7 +64,7 @@ Coordinates are clean-space metres: +Z up, the character faces −Y, its left is ## Pose test -`node tools/characters/rig-pose-test.mjs --clips= --out= [--strict] [--bake=[@]:]` skins on the CPU exactly like three.js (`Σ w · jointWorld · IBM · v`) and measures five synthetic poses (arms up 90°, arms forward 60°, a step with each leg, head turned 60°) and 8 instants of each of the 11 state clips (pass the clips retargeted to that model). Per pose: the longest edge stretch versus the bind pose, the 99th percentile, the upper-back region (between `Hips` and `neck`, behind `Spine01`), each hand (edges touching ≥ 25% hand weight, the client's `rig-maos-check` rule), the largest gap between vertices welded in the bind pose (UV seams), and the 10 worst vertices with their bones. `--bake` writes a static posed copy for renders (`tools/blender/character_rig/render_poses.py`, front/back/three-quarter with identical framing; `rig-review.mjs sheet` makes contact sheets). +`node tools/characters/rig-pose-test.mjs --clips= [--states=] [--samples=] --out= [--strict] [--bake=[@]:]` skins on the CPU exactly like three.js (`Σ w · jointWorld · IBM · v`) and measures five synthetic poses (arms up 90°, arms forward 60°, a step with each leg, head turned 60°) and 8 instants (`--samples`) of each of the 11 state clips (pass the clips retargeted to that model; `--states` measures other clips, which is how the [animation QA gate](animation-conversion.md) checks skin stretch). Per pose: the longest edge stretch versus the bind pose, the 99th percentile, the upper-back region (between `Hips` and `neck`, behind `Spine01`), each hand (edges touching ≥ 25% hand weight, the client's `rig-maos-check` rule), the largest gap between vertices welded in the bind pose (UV seams), and the 10 worst vertices with their bones. `--bake` writes a static posed copy for renders (`tools/blender/character_rig/render_poses.py`, front/back/three-quarter with identical framing; `rig-review.mjs sheet` makes contact sheets). Thresholds (`POSE_THRESHOLDS`): body and upper back ≤ 3.5× (the donor reaches 3.04× on its own clips), hands ≤ 2.5× (the client hand gate), seams ≤ 5 mm, bind error ≤ 2 mm. `--strict` exits 1 on any failure. @@ -112,6 +112,6 @@ The plush mascot keeps human-like clip motion: idle, walk, run, crouch, crouchwa - The estimator assumes a T-pose (arms clearly away from the body in the front view). A-pose meshes need a `joints.json` override. - Joint positions are a first estimate: always look at `joints-review.png` and `parts-review.png`. - Heat weighting can fail on non-manifold meshes; the voxel proxy covers it, but check `weights.json` (`method`, `heat.unweightedVertices`). -- Hips translation and in-place motion come from `retarget-glb.mjs`; this pipeline does not author clips. +- This pipeline does not author clips: Mixamo and UAL clips are converted and baked onto a rig by [animation-conversion.md](animation-conversion.md) (`tools/animations/`). - `Curl_L`/`Curl_R` carry no skin (hands are 100% `Hand`), as in the rigs from `rig-from-donor.mjs`: the client's grip curl rotates those bones but the fingers do not close around the weapon. - The pipeline run (`rig-character.mjs`) fails when the pose test fails (`--strict`); `--no-clips` limits it to the synthetic poses. diff --git a/tools/README.md b/tools/README.md index ee9d9b7..ee2e88c 100644 --- a/tools/README.md +++ b/tools/README.md @@ -20,14 +20,22 @@ The public repository must not contain `.blend`, `.blend1`, `.glb`, `.fbx`, `.md ## Commands ```bash -# Structure, JSON, public asset boundary, tool syntax, and the synthetic character pack -# and concept prompt contracts (tools/checks/character-*-check.mjs) +# Structure, JSON, public asset boundary, tool syntax, and the synthetic character pack, +# concept prompt, rig and animation conversion contracts (tools/checks/*-check.mjs) npm run check # Source contracts without API calls npm run check:asset-gen npm run check:pistol-source +# Animation conversion (docs/animation-conversion.md): Mixamo FBX / UAL glTF -> meshy-28 +# reference clips, bake onto a character, QA gate and contact sheet (private bytes stay outside) +node tools/animations/convert-clips.mjs --manifest=tools/animations/manifests/pilot-20261109.json \ + --catalog=/path/to/studio-assets/animations/catalog.json --out=/path/to/work/reference +node tools/animations/bake-character.mjs --model=/path/to/character.glb --clips=/path/to/work/reference --out=/path/to/work/character +node tools/animations/clip-qa.mjs --model=/path/to/character.glb --clips=/path/to/work/character --out=/path/to/work/qa.json --strict +node tools/animations/clip-sheet.mjs --model=/path/to/character.glb --clips=/path/to/work/character --out=/path/to/work/sheet.png + # Valid-package, builder and mutant smoke tests (synthetic fixtures only) npm run smoke:pack From 6fbdf7815b72a0a0f3edd9a5ba28389ba55f7bed Mon Sep 17 00:00:00 2001 From: rubenmarcus Date: Mon, 9 Nov 2026 03:35:43 +0000 Subject: [PATCH 08/31] Spell out ranges in the animation conversion notes Agent: Claude Code Signed-off-by: rubenmarcus --- docs/animation-conversion.md | 40 ++++++++++++++++++------------------ 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/docs/animation-conversion.md b/docs/animation-conversion.md index bb04374..414dac7 100644 --- a/docs/animation-conversion.md +++ b/docs/animation-conversion.md @@ -98,7 +98,7 @@ One core, `retargetClip(source, target, options)`, does both convert and bake. T **Rest alignment (`LIMB_ALIGNMENT`).** Upper arm, forearm, thigh and shin: before the delta is applied, the target's rest frame is turned by the shortest arc that makes the bone point like the source's rest bone. Mixamo and UAL rest with straight arms and legs; the donor rests with bent knees (18°) and forearms swept back, which plain deltas would add to every pose (crouched walks, rifle hands pulled back). Feet are not aligned: both rests stand flat, and ankle-to-ball slopes differ with foot shape. -**Bake rule (port of the client's `retarget-glb.mjs`).** `LeftArm`/`LeftForeArm`/`LeftHand` and the right twins copy the clip's absolute world rotation (`absoluteArms`): an A-pose rig would otherwise hold every clip 30–40° off. The Blender rigs align those frames to the bones, so absolute frames point the bones where the clip points. Everything else uses deltas plus rest alignment on the legs. `Curl_*` are never animated. A target with fewer than 8 matching joints is refused (the client tool once wrote 11 empty clips and reported success). +**Bake rule (port of the client's `retarget-glb.mjs`).** `LeftArm`/`LeftForeArm`/`LeftHand` and the right twins copy the clip's absolute world rotation (`absoluteArms`): an A-pose rig would otherwise hold every clip 30 to 40° off. The Blender rigs align those frames to the bones, so absolute frames point the bones where the clip points. Everything else uses deltas plus rest alignment on the legs. `Curl_*` are never animated. A target with fewer than 8 matching joints is refused (the client tool once wrote 11 empty clips and reported success). **Hips.** The hips' world displacement from the source rest, turned into the target's facing and scaled by the hips-height ratio. Root motion (`rootMotion`): @@ -110,7 +110,7 @@ One core, `retargetClip(source, target, options)`, does both convert and bake. T **Contacts and foot IK (`footIk`).** A source foot joint is planted where it is within 3 cm of its rest height and moves slower than 0.25 m/s in the source's world (root motion included), for at least 3 frames (`footContacts`). The windows travel with the clip (`extras.clip.contacts`, frame indices) and bake reuses them. Inside a window (ramped over 4 frames; ramps wrap the seam of a loop) two-bone IK (`solveTwoBone`: knee bend by the law of cosines about the current bend plane, then a hip swing) pins the ankle to the source ankle's displacement from its rest, scaled, added to the target ankle's rest. With the root velocity added back, that position is where the source keeps the foot, so planted feet stop sliding on characters whose legs differ from the source's. `contactSlide` records the source's own slide inside its windows. -**Toe clamp (bake, `clampToesToFloor`).** Bake knows the character's mesh: per frame it skins the vertices that belong to each `ToeBase` and, when the lowest sinks more than 5 mm below the bind floor, pitches that toe up about the horizontal axis across the toe lever (at most 3 iterations of ≤45°). Longer or differently pitched feet otherwise pushed the toes 2.1–5.5 cm through the floor at heel-off (pilot round 2). +**Toe clamp (bake, `clampToesToFloor`).** Bake knows the character's mesh: per frame it skins the vertices that belong to each `ToeBase` and, when the lowest sinks more than 5 mm below the bind floor, pitches that toe up about the horizontal axis across the toe lever (at most 3 iterations of ≤45°). Longer or differently pitched feet otherwise pushed the toes 2.1 to 5.5 cm through the floor at heel-off (pilot round 2). **Sampling.** Output is resampled to 30 fps (`CLIP_FPS`) by sampling the source at `i/30` s, with the last frame exactly at the end (`frames = round(length · 30) + 1`). The FBX path samples through a `THREE.AnimationMixer` with `LoopOnce` + clamp (so the last frame is the real end pose); the glTF path samples LINEAR/STEP/CUBICSPLINE channels. FBXLoader adds a same-named leaf under each bone of a skinned Mixamo file; bones are resolved like the mixer resolves track names, so the animated bone is used (clause A9). The native key rate (most common key interval) is recorded as `source.nativeFps`. @@ -140,7 +140,7 @@ Every frame of every clip is skinned on the CPU (same maths as three.js) on the | Floating | Highest of the per-frame lowest vertices (not for `airborne`). | ≤ 3 cm | | Hips height | Hips height range / bind height; the source's range is reported next to it. | max ≤ 1.08 (not for `airborne`) | | Loop seam | First versus last frame (loops): joint positions and local rotations. | ≤ 1.5 cm, ≤ 5° | -| Two-hand grip | `LeftHand`–`RightHand` distance, maximum deviation from its median (`hold: rifle`). | ≤ 3 cm | +| Two-hand grip | `LeftHand` to `RightHand` distance, maximum deviation from its median (`hold: rifle`). | ≤ 3 cm | | Skin stretch | `tools/characters/rig-pose-test.mjs --clips= --states= --samples=12`: per clip, the worst edge, upper back and hands. | `POSE_THRESHOLDS.clip`: 3.5×, 3.5×, 2.5×, seams 5 mm | The limits were set before the pilot from the client's gates (stretch, hands) and common foot-skating tolerances and were not loosened; round 3 added the source-relative slide allowance, because a motion-capture take can slide on its own (Grenade Throw: 3.5 cm over 8 s in the source) and no retarget can do better than its source. @@ -149,7 +149,7 @@ The limits were set before the pilot from the client's gates (stretch, hands) an ## Check (`npm run check`) -`tools/checks/animation-conversion-check.mjs` builds Mixamo-like bone trees (FBXLoader naming, scrambled rest frames, optional duplicate leaves, three prefixes, −Z facing) and a UAL-like glTF (Z-up `root`) in code, and a synthetic skinned body (`tools/checks/lib/synthetic-humanoid.mjs`, shared with the rig check). Clauses: maps and hierarchy (A1), rig detection (A2), rest identity (A3), world-delta transfer within 1 mm (A4), spine order (A5), root-motion modes (A6), 24 → 30 fps resampling and trim (A7), facing (A8), FBX duplicates and prefixes (A9), UAL (A10), ground contact + IK on shorter shins (A11: 0.00 cm with, 4.5 cm slide / 2.9 cm height without), loop-wrapped IK ramps (A11), rest alignment (A12: knee straight with, 18° without), bake rules (B1, B2), and the QA gates on a clean clip plus one mutant per gate, the CLI end to end with `--strict` and a torn-hand body, and the toe clamp (Q1–Q4). +`tools/checks/animation-conversion-check.mjs` builds Mixamo-like bone trees (FBXLoader naming, scrambled rest frames, optional duplicate leaves, three prefixes, −Z facing) and a UAL-like glTF (Z-up `root`) in code, and a synthetic skinned body (`tools/checks/lib/synthetic-humanoid.mjs`, shared with the rig check). Clauses: maps and hierarchy (A1), rig detection (A2), rest identity (A3), world-delta transfer within 1 mm (A4), spine order (A5), root-motion modes (A6), 24 → 30 fps resampling and trim (A7), facing (A8), FBX duplicates and prefixes (A9), UAL (A10), ground contact + IK on shorter shins (A11: 0.00 cm with, 4.5 cm slide / 2.9 cm height without), loop-wrapped IK ramps (A11), rest alignment (A12: knee straight with, 18° without), bake rules (B1, B2), and the QA gates on a clean clip plus one mutant per gate, the CLI end to end with `--strict` and a torn-hand body, and the toe clamp (Q1 to Q4). ## Pilot (2026-11-09) @@ -157,29 +157,29 @@ Six Mixamo clips owner-downloaded (`tools/animations/manifests/pilot-20261109.js Gauntlet (all QA numbers measured with the final gate): -- **Round 1**, the straight port of the client tools: feet float 5.7–8.1 cm on capitao-caveira (every clip but one) and penetrate up to 3.3 cm on mst, because the hips-height ratio is not the leg-length ratio when knees bend. 5/6 clips fail on capitao-caveira, 5/6 on mst. -- **Round 2**: ground contact, source contact windows, foot IK. Floating gone; slide inside source contacts at the source's own level. Remaining: toes through the floor at heel-off (mst −3.6 to −5.5 cm, capitao −2.1 cm), and crouched postures (hips 0.74–0.83 of rest against the source's 0.79–0.87) from the donor's bent rest knees. +- **Round 1**, the straight port of the client tools: feet float 5.7 to 8.1 cm on capitao-caveira (every clip but one) and penetrate up to 3.3 cm on mst, because the hips-height ratio is not the leg-length ratio when knees bend. 5/6 clips fail on capitao-caveira, 5/6 on mst. +- **Round 2**: ground contact, source contact windows, foot IK. Floating gone; slide inside source contacts at the source's own level. Remaining: toes through the floor at heel-off (mst −3.6 to −5.5 cm, capitao −2.1 cm), and crouched postures (hips 0.74 to 0.83 of rest against the source's 0.79 to 0.87) from the donor's bent rest knees. - **Round 3**: rest alignment of arms and legs, bake-time toe clamp, slide limit relative to the source's own slide. capitao-caveira passes 6/6, mst 5/6. Round 3 QA (slide: measured (source's own); low: lowest vertex min/max; hips: ratio to bind (source); seam: position/rotation; grip: median ± max deviation; stretch: body/back/hand L/hand R): | capitao-caveira | slide cm | low cm | hips | seam cm/° | grip cm | stretch × | result | | --- | --- | --- | --- | --- | --- | --- | --- | -| reload | 3.45 (3.31) | −1.35 / −0.03 | 0.94–0.98 (0.90–0.95) | — | 32.3 ± 12.6 | 2.09 / 1.67 / 1.22 / 1.17 | pass | -| grenade-throw | 4.04 (4.05) | −0.48 / 0.18 | 0.54–0.69 (0.48–0.61) | — | 50.4 ± 52.9 | 2.84 / 2.63 / 1.08 / 1.12 | pass | -| knife-idle (loop) | 0.66 (0.66) | 1.27 / 1.44 | 0.89–0.93 (0.85–0.90) | 0.00 / 0.04 | 49.9 ± 1.9 | 2.00 / 1.37 / 1.09 / 1.09 | pass | -| rifle-pull-out | 0.86 (0.87) | −0.12 / −0.02 | 1.00–1.01 (0.97–0.98) | — | 44.3 ± 12.5 | 2.20 / 1.66 / 1.19 / 1.25 | pass | -| rifle-walk-left (loop, rifle) | 1.79 (1.85) | −1.18 / 0.55 | 0.83–0.92 (0.79–0.87) | 0.03 / 0.07 | 29.9 ± 0.08 | 2.13 / 1.80 / 1.09 / 1.05 | pass | -| rifle-walk-right (loop, rifle) | 1.37 (1.44) | −1.05 / 0.14 | 0.87–0.95 (0.83–0.92) | 0.01 / 0.03 | 30.4 ± 0.41 | 2.12 / 1.94 / 1.10 / 1.05 | pass | +| reload | 3.45 (3.31) | −1.35 / −0.03 | 0.94 to 0.98 (0.90 to 0.95) | n/a | 32.3 ± 12.6 | 2.09 / 1.67 / 1.22 / 1.17 | pass | +| grenade-throw | 4.04 (4.05) | −0.48 / 0.18 | 0.54 to 0.69 (0.48 to 0.61) | n/a | 50.4 ± 52.9 | 2.84 / 2.63 / 1.08 / 1.12 | pass | +| knife-idle (loop) | 0.66 (0.66) | 1.27 / 1.44 | 0.89 to 0.93 (0.85 to 0.90) | 0.00 / 0.04 | 49.9 ± 1.9 | 2.00 / 1.37 / 1.09 / 1.09 | pass | +| rifle-pull-out | 0.86 (0.87) | −0.12 / −0.02 | 1.00 to 1.01 (0.97 to 0.98) | n/a | 44.3 ± 12.5 | 2.20 / 1.66 / 1.19 / 1.25 | pass | +| rifle-walk-left (loop, rifle) | 1.79 (1.85) | −1.18 / 0.55 | 0.83 to 0.92 (0.79 to 0.87) | 0.03 / 0.07 | 29.9 ± 0.08 | 2.13 / 1.80 / 1.09 / 1.05 | pass | +| rifle-walk-right (loop, rifle) | 1.37 (1.44) | −1.05 / 0.14 | 0.87 to 0.95 (0.83 to 0.92) | 0.01 / 0.03 | 30.4 ± 0.41 | 2.12 / 1.94 / 1.10 / 1.05 | pass | | mst | slide cm | low cm | hips | seam cm/° | grip cm | stretch × | result | | --- | --- | --- | --- | --- | --- | --- | --- | -| reload | 3.03 (2.90) | −1.29 / −0.03 | 0.91–0.97 (0.90–0.95) | — | 31.7 ± 16.8 | 3.02 / 3.02 / 1.66 / 1.30 | pass | -| grenade-throw | 3.55 (3.55) | **−5.48** / −0.16 | 0.50–0.64 (0.48–0.61) | — | 55.3 ± 69.8 | 3.19 / 2.70 / 1.14 / 1.14 | fail: right hand 5.5 cm into the floor at 2.93 s | -| knife-idle (loop) | 0.58 (0.58) | 1.12 / 1.25 | 0.87–0.91 (0.85–0.90) | 0.00 / 0.04 | 54.8 ± 2.5 | 2.15 / 2.15 / 1.23 / 1.14 | pass | -| rifle-pull-out | 0.76 (0.76) | −0.54 / −0.19 | 0.99 (0.97–0.98) | — | 49.1 ± 17.4 | 2.94 / 2.94 / 1.67 / 1.35 | pass | -| rifle-walk-left (loop, rifle) | 1.62 (1.62) | −1.36 / 0.31 | 0.82–0.90 (0.79–0.87) | 0.04 / 0.06 | 29.2 ± 0.31 | 2.70 / 2.70 / 1.18 / 1.04 | pass | -| rifle-walk-right (loop, rifle) | 1.61 (1.26) | −1.34 / 0.09 | 0.86–0.94 (0.83–0.92) | 0.02 / 0.03 | 29.3 ± 0.55 | 2.89 / 2.89 / 1.23 / 1.03 | pass | +| reload | 3.03 (2.90) | −1.29 / −0.03 | 0.91 to 0.97 (0.90 to 0.95) | n/a | 31.7 ± 16.8 | 3.02 / 3.02 / 1.66 / 1.30 | pass | +| grenade-throw | 3.55 (3.55) | **−5.48** / −0.16 | 0.50 to 0.64 (0.48 to 0.61) | n/a | 55.3 ± 69.8 | 3.19 / 2.70 / 1.14 / 1.14 | fail: right hand 5.5 cm into the floor at 2.93 s | +| knife-idle (loop) | 0.58 (0.58) | 1.12 / 1.25 | 0.87 to 0.91 (0.85 to 0.90) | 0.00 / 0.04 | 54.8 ± 2.5 | 2.15 / 2.15 / 1.23 / 1.14 | pass | +| rifle-pull-out | 0.76 (0.76) | −0.54 / −0.19 | 0.99 (0.97 to 0.98) | n/a | 49.1 ± 17.4 | 2.94 / 2.94 / 1.67 / 1.35 | pass | +| rifle-walk-left (loop, rifle) | 1.62 (1.62) | −1.36 / 0.31 | 0.82 to 0.90 (0.79 to 0.87) | 0.04 / 0.06 | 29.2 ± 0.31 | 2.70 / 2.70 / 1.18 / 1.04 | pass | +| rifle-walk-right (loop, rifle) | 1.61 (1.26) | −1.34 / 0.09 | 0.86 to 0.94 (0.83 to 0.92) | 0.02 / 0.03 | 29.3 ± 0.55 | 2.89 / 2.89 / 1.23 / 1.03 | pass | Root speed of the strafe walks: 1.53 m/s on the reference skeleton, 1.74 m/s baked on capitao-caveira (hips scale 1.14). Reload walks forward at 0.79 m/s (reference). @@ -189,8 +189,8 @@ A UAL 1 sample (`_RM` file: `Idle_Loop`, `Pistol_Reload`, `Walk_Loop`) passes on - **Hands and knees are not ground-constrained.** Only the feet have contact handling. In `grenade-throw` the donor's longer arms put the right hand 5.5 cm into the floor while kneeling; a hand-contact IK (or an arm-length-aware clamp like the toe clamp) is the next step. - **Heel penetration** of up to 2.1 cm remains where the foot itself (not the toes) pitches below the floor; the toe clamp handles `ToeBase` vertices only. -- **Hips sit 0.02–0.08 of the bind height above the source's** (ratio columns above): the reference skeleton's thigh/shin proportions differ from Mixamo's, and the contact correction keeps the feet, not the hips height, faithful. -- **Grip distance is set by proportions.** `rifle` holds are stable over time (±0.1–0.6 cm) but the hands sit 29–30 cm apart; a weapon of a different length needs the client's hand IK or a per-weapon arm adjustment. +- **Hips sit 0.02 to 0.08 of the bind height above the source's** (ratio columns above): the reference skeleton's thigh/shin proportions differ from Mixamo's, and the contact correction keeps the feet, not the hips height, faithful. +- **Grip distance is set by proportions.** `rifle` holds are stable over time (±0.1 to 0.6 cm) but the hands sit 29 to 30 cm apart; a weapon of a different length needs the client's hand IK or a per-weapon arm adjustment. - **Root motion is a straight line.** Turning clips, curved paths and yaw are not extracted (hips yaw stays in the clip). - **Contacts need root motion.** In-place sources (UAL `*_Standard.glb`) yield no contact windows for locomotion, so their foot slide is not measured; use the `_RM` files. - The mesh-aware toe clamp runs only in bake (the reference skeleton has no mesh); reference clips may still have toes below the floor on other feet. From 5f8c0568424f46ba78233876c2950927378ea111 Mon Sep 17 00:00:00 2001 From: rubenmarcus Date: Mon, 9 Nov 2026 03:43:20 +0000 Subject: [PATCH 09/31] Keep heels, toes, hands and knees above the floor at bake time The toe clamp becomes a floor clamp over body regions: heels pitch at the ankle, toes at the ball, hands at the elbow then the shoulder, knees lift the hips, and a foot whose heel and toes both sink is raised by leg IK. The QA gate reports the lowest vertex per region and holds heels to 1 cm. Pilot: mst grenade-throw hand -5.48 -> -0.50 cm, heels at most -0.6 cm; 12/12 pilot clips pass. Agent: Claude Code Signed-off-by: rubenmarcus --- tools/animations/bake-character.mjs | 14 +- tools/checks/animation-conversion-check.mjs | 44 +++-- tools/lib/animation-retarget.mjs | 198 +++++++++++++++----- tools/lib/clip-qa.mjs | 20 +- 4 files changed, 203 insertions(+), 73 deletions(-) diff --git a/tools/animations/bake-character.mjs b/tools/animations/bake-character.mjs index b52a927..a24f363 100755 --- a/tools/animations/bake-character.mjs +++ b/tools/animations/bake-character.mjs @@ -12,15 +12,15 @@ // place, so its sway is kept and its root-motion metadata (velocity, contactSlide) is scaled // the same way. Leg directions follow the reference's (rest alignment), the hips height keeps // the lowest foot joint where the clip has it, two-bone IK pins the ankles inside the clip's -// contact windows (extras.clip.contacts), and a mesh-aware clamp pitches toes that would sink -// below the floor (docs/animation-conversion.md). --no-foot-contact, --no-foot-ik, -// --no-toe-clamp and --no-limb-align switch those off. Works on clips without metadata too +// contact windows (extras.clip.contacts), and a mesh-aware floor clamp keeps heels, toes, hands +// and knees above the floor (docs/animation-conversion.md). --no-foot-contact, --no-foot-ik, +// --no-floor-clamp and --no-limb-align switch those off. Works on clips without metadata too // (the client's shared pack): contacts are then detected on the clip itself. import { NodeIO } from '@gltf-transform/core'; import { ALL_EXTENSIONS } from '@gltf-transform/extensions'; import { mkdirSync, readdirSync, writeFileSync } from 'node:fs'; import path from 'node:path'; -import { CLIP_FPS, clampToesToFloor, clipMetadata, gltfPoseSource, retargetClip, skeletonGraph, writeClipDocument } from '../lib/animation-retarget.mjs'; +import { CLIP_FPS, clampToFloor, clipMetadata, gltfPoseSource, retargetClip, skeletonGraph, writeClipDocument } from '../lib/animation-retarget.mjs'; import { RIG_MAPS } from '../lib/animation-sources.mjs'; import { loadRig } from '../lib/character-rig.mjs'; @@ -28,7 +28,7 @@ const args = process.argv.slice(2); const flag = (name) => args.find((a) => a.startsWith(`--${name}=`))?.slice(name.length + 3); const model = flag('model'), clipsDir = flag('clips'), outDir = flag('out'); if (!model || !clipsDir || !outDir) { - console.error('usage: bake-character.mjs --model= --clips= --out= [--states=] [--no-foot-contact] [--no-foot-ik] [--no-toe-clamp] [--no-limb-align]'); + console.error('usage: bake-character.mjs --model= --clips= --out= [--states=] [--no-foot-contact] [--no-foot-ik] [--no-floor-clamp] [--no-limb-align]'); process.exit(1); } mkdirSync(outDir, { recursive: true }); @@ -47,7 +47,7 @@ for (const state of states) { const meta = clipMetadata(doc); const source = gltfPoseSource(doc, animation, RIG_MAPS['meshy-28']); const result = retargetClip(source, target, { fps: meta.fps || CLIP_FPS, rootMotion: 'keep', absoluteArms: true, footContact: !args.includes('--no-foot-contact'), footIk: !args.includes('--no-foot-ik'), contacts: meta.contacts || null, loop: Boolean(meta.loop), alignLimbs: args.includes('--no-limb-align') ? [] : undefined }); - const toeClamp = args.includes('--no-toe-clamp') ? null : clampToesToFloor(rig, result); + const floorClamp = args.includes('--no-floor-clamp') ? null : clampToFloor(rig, result); const scale = (v) => +(v * result.hipsScale).toFixed(4); const rm = meta.rootMotion; const frames = result.times.length; @@ -55,7 +55,7 @@ for (const state of states) { ...meta, fps: meta.fps || CLIP_FPS, frames, duration: +result.times[frames - 1].toFixed(4), contactSlide: meta.contactSlide != null ? scale(meta.contactSlide) : undefined, rootMotion: rm ? { ...rm, displacement: rm.displacement.map(scale), velocity: rm.velocity.map(scale), speed: scale(rm.speed) } : undefined, - bakedFor: { model: path.basename(model), hipsScale: +result.hipsScale.toFixed(6), joints: result.mapped.length, footContact: result.contactCorrection, footIk: result.ik, toeClamp, alignedLimbs: result.aligned }, + bakedFor: { model: path.basename(model), hipsScale: +result.hipsScale.toFixed(6), joints: result.mapped.length, footContact: result.contactCorrection, footIk: result.ik, floorClamp, alignedLimbs: result.aligned }, }; await io.write(path.join(outDir, `${state}.glb`), writeClipDocument(target, result, state, extras)); baked.push({ name: state, frames, duration: extras.duration, joints: result.mapped.length, hipsScale: extras.bakedFor.hipsScale, rootSpeed: extras.rootMotion?.speed ?? null }); diff --git a/tools/checks/animation-conversion-check.mjs b/tools/checks/animation-conversion-check.mjs index de6f854..06bb032 100755 --- a/tools/checks/animation-conversion-check.mjs +++ b/tools/checks/animation-conversion-check.mjs @@ -20,7 +20,7 @@ import * as THREE from 'three'; import { meshy28Joints } from '../lib/character-pack.mjs'; import { clipSampler, deformJointNames, loadRig } from '../lib/character-rig.mjs'; import { - MESHY28_REFERENCE_JOINTS, MIXAMO_TO_MESHY28, UAL_TO_MESHY28, clampToesToFloor, clipMetadata, gltfPoseSource, mixamoBaseName, + FLOOR_CLAMP_REGIONS, MESHY28_REFERENCE_JOINTS, MIXAMO_TO_MESHY28, UAL_TO_MESHY28, clampToFloor, clipMetadata, gltfPoseSource, mixamoBaseName, objectPoseSource, referenceSkeletonDocument, retargetClip, skeletonGraph, writeClipDocument, } from '../lib/animation-retarget.mjs'; import { RIG_MAPS, detectRig } from '../lib/animation-sources.mjs'; @@ -504,6 +504,13 @@ for (const [label, frames, meta, expected] of mutants) { return f.find((x) => expected.test(x)); }); } +await clause('Q2 clip QA mutant rejected: heel sinks past the stricter heel limit', async () => { + const { metrics } = await qa(bodyClip(goodClip(), loopMeta)); + const sunk = { ...metrics, lowestVertex: { ...metrics.lowestVertex, byRegionCm: { ...metrics.lowestVertex.byRegionCm, heel: -1.5 } } }; + const f = evaluateClip(sunk, loopMeta); + assert(f.some((x) => /heel sinks -1.5 cm/.test(x)) && !evaluateClip(metrics, loopMeta).length, f.join('; ')); + return f.find((x) => /heel/.test(x)); +}); await clause('Q2 airborne clips are exempt from the float and hips gates', async () => { const { failures: f } = await qa(bodyClip(goodClip(() => ({ hips: [0, 0.1, 0] })), { ...loopMeta, airborne: true })); assert(!f.some((x) => /floats|hips rise/.test(x)), f.join('; ')); @@ -533,17 +540,30 @@ await clause('Q3 clip-qa CLI gates skin stretch through rig-pose-test --clips (a } }); -await clause('Q4 the bake-time toe clamp lifts toes pushed through the floor', async () => { - const doc = bodyClip(() => ({ deltas: { LeftToeBase: Q(X, 35), RightToeBase: Q(X, 35) } }), { loop: false }); - const graph = skeletonGraph(doc); - const anim = doc.getRoot().listAnimations()[0]; - const r = retargetClip(gltfPoseSource(doc, anim, RIG_MAPS['meshy-28']), bodyGraph, { rootMotion: 'keep', footIk: false, footContact: false }); - const before = measureClip(bodyRig, clipSampler(await io.readBinary(await io.writeBinary(writeClipDocument(graph, r, 'a', {})))), {}); - const stats = clampToesToFloor(bodyRig, r); - const after = measureClip(bodyRig, clipSampler(await io.readBinary(await io.writeBinary(writeClipDocument(graph, r, 'b', {})))), {}); - assert(before.lowestVertex.minCm < -1 && after.lowestVertex.minCm >= -0.6 && stats.frames > 0, `toes ${before.lowestVertex.minCm} -> ${after.lowestVertex.minCm} cm (${JSON.stringify(stats)})`); - return `lowest toe ${before.lowestVertex.minCm} -> ${after.lowestVertex.minCm} cm, ${stats.frames} frames, ≤${stats.maxDeg}°`; -}); +/* Bake-time floor clamp: each case sinks one body region through the floor; the clamp must + bring every region back within 6 mm and report the lever it used. */ +const floorCases = [ + ['toes bent down', () => ({ deltas: { LeftToeBase: Q(X, 35), RightToeBase: Q(X, 35) } }), 'toe', 'toe'], + ['heels sunk with the toes raised', () => ({ deltas: { LeftFoot: Q(X, -50), RightFoot: Q(X, -50) }, hips: [0, -0.09, 0] }), 'heel', 'heel'], + ['whole feet below the floor (ankle lift)', () => ({ deltas: {}, hips: [0, -0.04, 0] }), 'heel', 'ankleLift'], + // Bent over with the arms reaching forward-down; only the hand regions are clamped here. + ['hands pushed into the ground', () => ({ deltas: { Spine02: Q(X, 90), LeftArm: Q(X, 45).multiply(Q(Z, -90)), RightArm: Q(X, 45).multiply(Q(Z, 90)) }, hips: [0, -0.62, 0] }), 'hand', 'hand', ['hand']], +]; +for (const [label, frames, region, lever, only] of floorCases) { + await clause(`Q4 the bake-time floor clamp lifts ${label}`, async () => { + const doc = bodyClip(frames, { loop: false }, { duration: 0.2 }); + const graph = skeletonGraph(doc); + const r = retargetClip(gltfPoseSource(doc, doc.getRoot().listAnimations()[0], RIG_MAPS['meshy-28']), bodyGraph, { rootMotion: 'keep', footIk: false, footContact: false, alignLimbs: [] }); + const measure = async (name) => measureClip(bodyRig, clipSampler(await io.readBinary(await io.writeBinary(writeClipDocument(graph, r, name, {})))), {}).lowestVertex; + const before = await measure('a'); + const stats = clampToFloor(bodyRig, r, only ? { regions: FLOOR_CLAMP_REGIONS.filter((x) => only.includes(x.name)) } : {}); + const after = await measure('b'); + assert(before.byRegionCm[region] < -1, `fixture does not sink the ${region} (${before.byRegionCm[region]} cm)`); + const low = only ? Math.min(...only.map((n) => after.byRegionCm[n])) : after.minCm; + assert(low >= -0.6 && stats[lever].frames > 0, `${region} ${before.byRegionCm[region]} -> ${low} cm (${JSON.stringify(stats)})`); + return `${region} ${before.byRegionCm[region]} -> ${only ? `${region} ${low}` : `lowest ${low}`} cm via ${lever} (max ${stats[lever].max})`; + }); +} if (failures) { console.error(`FAIL animation conversion: ${failures} clause(s)`); diff --git a/tools/lib/animation-retarget.mjs b/tools/lib/animation-retarget.mjs index 47da835..4b97bf8 100644 --- a/tools/lib/animation-retarget.mjs +++ b/tools/lib/animation-retarget.mjs @@ -552,37 +552,66 @@ export function retargetClip(source, target, { }; } -/** Penetration below the bind floor tolerated before the toe clamp acts (m). */ -export const TOE_CLAMP_TOLERANCE = 0.005; +/** Penetration below the bind floor tolerated before the floor clamp acts (m). */ +export const FLOOR_CLAMP_TOLERANCE = 0.005; + +/* Body regions the bake-time floor clamp keeps above the floor, in the order it treats them. + A vertex belongs to the region of its dominant joint. `pivots` are tried in order: the + first whose lever to the sinking vertex is not vertical turns about the horizontal axis + across that lever (heel: the ankle pitches the foot; toes: the ball; hands: the elbow, then + the shoulder). When the heel and the toes of one foot both sink, no pitch can help (the + ankle itself is too low for this foot's shape): two-bone IK on `leg` raises that ankle by + the shallower depth first. `lift` regions (knees) raise the hips instead: a kneeling thigh + is vertical, so no rotation lifts the knee. */ +export const FLOOR_CLAMP_REGIONS = Object.freeze([ + { name: 'heel', bones: ['LeftFoot'], pivots: ['LeftFoot'], leg: ['LeftUpLeg', 'LeftLeg', 'LeftFoot'] }, + { name: 'heel', bones: ['RightFoot'], pivots: ['RightFoot'], leg: ['RightUpLeg', 'RightLeg', 'RightFoot'] }, + { name: 'toe', bones: ['LeftToeBase'], pivots: ['LeftToeBase'], leg: ['LeftUpLeg', 'LeftLeg', 'LeftFoot'] }, + { name: 'toe', bones: ['RightToeBase'], pivots: ['RightToeBase'], leg: ['RightUpLeg', 'RightLeg', 'RightFoot'] }, + { name: 'hand', bones: ['LeftHand', 'Curl_L'], pivots: ['LeftForeArm', 'LeftArm'] }, + { name: 'hand', bones: ['RightHand', 'Curl_R'], pivots: ['RightForeArm', 'RightArm'] }, + { name: 'knee', bones: ['LeftLeg'], lift: true }, + { name: 'knee', bones: ['RightLeg'], lift: true }, +]); + +/** Region name of every vertex of `rig` (dominant joint), or null outside FLOOR_CLAMP_REGIONS. */ +export function vertexRegions(rig, regions = FLOOR_CLAMP_REGIONS) { + return rig.prims.map((p) => { + const out = new Array(p.count).fill(null); + for (let v = 0; v < p.count; v += 1) { + let best = 0; + for (let k = 1; k < 4; k += 1) if (p.W[v * 4 + k] > p.W[v * 4 + best]) best = k; + const name = rig.names[p.J[v * 4 + best]]; + const region = regions.findIndex((r) => r.bones.includes(name)); + out[v] = region < 0 ? null : region; + } + return out; + }); +} /** - * Bake-time, mesh-aware floor clamp for the toes (`rig`: loadRig of the character). Per frame, - * the vertices whose dominant joint is a ToeBase are skinned; when the lowest sinks below the - * bind floor, that ToeBase is pitched up about the horizontal axis across the toe lever until - * it clears (at most 3 iterations, 45° per step). Rewrites `result.rotations` in place. - * The toes of a character with a longer or differently pitched foot than the source would - * otherwise push through the floor at heel-off. Returns { frames, maxDeg }. + * Bake-time, mesh-aware floor clamp (`rig`: loadRig of the character). Per frame the mesh is + * skinned; when a region's lowest vertex sinks more than FLOOR_CLAMP_TOLERANCE below the bind + * floor, the region's pivot turns it up about the horizontal axis across the lever (at most 45° + * per step), a foot whose heel and toes both sink is raised by leg IK, and `lift` regions + * raise the hips by the depth. Up to 6 passes per frame. + * Rewrites `result.rotations` and `result.hips` in place. Returns per-region { frames, max } + * (degrees for pivots, metres for lifts; `ankleLift` for the leg IK) and the frames still + * below the tolerance. */ -export function clampToesToFloor(rig, result, { iterations = 3 } = {}) { +export function clampToFloor(rig, result, { regions = FLOOR_CLAMP_REGIONS, passes = 6 } = {}) { const bind = skinPositions(rig); let floor = Infinity; for (const b of bind) for (let v = 1; v < b.length; v += 3) floor = Math.min(floor, b[v]); const node = (name) => rig.byName.get(name)?.[0]; - const sides = ['LeftToeBase', 'RightToeBase'].filter((n) => node(n) && result.rotations.has(n)).map((name) => { - const slot = new Set(rig.names.map((n, i) => (n === name ? i : -1)).filter((i) => i >= 0)); - const verts = []; - rig.prims.forEach((p, pi) => { - for (let v = 0; v < p.count; v += 1) { - let best = 0; - for (let k = 1; k < 4; k += 1) if (p.W[v * 4 + k] > p.W[v * 4 + best]) best = k; - if (slot.has(p.J[v * 4 + best])) verts.push([pi, v]); - } - }); - return { name, node: node(name), verts }; - }).filter((s) => s.verts.length); - const stats = { frames: 0, maxDeg: 0 }; - if (!sides.length) return stats; + const membership = vertexRegions(rig, regions); + const active = regions.map((r, i) => membership.some((m) => m.includes(i)) && (r.lift || r.pivots.some((p) => node(p) && result.rotations.has(p)))); + const stats = {}; + for (const r of regions) stats[r.name] ||= { frames: 0, max: 0 }; + stats.ankleLift = { frames: 0, max: 0 }; + let unresolved = 0; const hipsNode = node('Hips'); + const parentWorldInv = rig.parent.get(hipsNode) ? null : new THREE.Matrix4(); const frames = result.times.length; for (let i = 0; i < frames; i += 1) { const overrides = new Map(); @@ -590,40 +619,107 @@ export function clampToesToFloor(rig, result, { iterations = 3 } = {}) { const n = node(name); if (n) overrides.set(n, { ...rig.trs.get(n), r: Array.from(arr.slice(i * 4, i * 4 + 4)) }); } - overrides.set(hipsNode, { ...overrides.get(hipsNode), t: Array.from(result.hips.slice(i * 3, i * 3 + 3)) }); - let touched = false; - for (let it = 0; it < iterations; it += 1) { + overrides.set(hipsNode, { ...(overrides.get(hipsNode) || rig.trs.get(hipsNode)), t: Array.from(result.hips.slice(i * 3, i * 3 + 3)) }); + const touched = new Set(); + let sinking = false; + for (let pass = 0; pass < passes; pass += 1) { const skinned = skinPositions(rig, overrides); const world = worldMatrices(rig, overrides); + const low = regions.map(() => ({ y: Infinity, at: null })); + membership.forEach((m, pi) => m.forEach((region, v) => { + if (region == null || !active[region]) return; + const y = skinned[pi][v * 3 + 1]; + if (y < low[region].y) low[region] = { y, at: [pi, v] }; + })); let moved = false; - for (const side of sides) { - let low = Infinity, at = null; - for (const [pi, v] of side.verts) if (skinned[pi][v * 3 + 1] < low) { low = skinned[pi][v * 3 + 1]; at = [pi, v]; } - if (low >= floor - TOE_CLAMP_TOLERANCE) continue; - const V = new THREE.Vector3().fromArray(skinned[at[0]], at[1] * 3); - const P = new THREE.Vector3().setFromMatrixPosition(world(side.node)); - const lever = V.clone().sub(P); - const axis = lever.clone().cross(new THREE.Vector3(0, 1, 0)); - if (axis.lengthSq() < 1e-10 || lever.length() < 1e-4) continue; - const angle = Math.min(Math.PI / 4, Math.asin(Math.min(1, (floor - low) / lever.length())) + 1e-3); - const toeQ = new THREE.Quaternion(), parentQ = new THREE.Quaternion(); - world(side.node).decompose(new THREE.Vector3(), toeQ, new THREE.Vector3()); - world(rig.parent.get(side.node)).decompose(new THREE.Vector3(), parentQ, new THREE.Vector3()); - const turned = new THREE.Quaternion().setFromAxisAngle(axis.normalize(), angle).multiply(toeQ); - const local = parentQ.invert().multiply(turned).normalize(); - const prev = result.rotations.get(side.name).slice(i * 4, i * 4 + 4); - if (prev[0] * local.x + prev[1] * local.y + prev[2] * local.z + prev[3] * local.w < 0) local.set(-local.x, -local.y, -local.z, -local.w); - result.rotations.get(side.name).set(local.toArray(), i * 4); - overrides.set(side.node, { ...overrides.get(side.node), r: local.toArray() }); - stats.maxDeg = Math.max(stats.maxDeg, THREE.MathUtils.radToDeg(angle)); - moved = touched = true; - } + sinking = false; + // Whole foot below the floor: raise that ankle by leg IK (same leg chain on heel and toe). + const legs = new Map(); + regions.forEach((region, ri) => { + const depth = floor - low[ri].y; + if (!region.leg || !active[ri] || depth <= FLOOR_CLAMP_TOLERANCE) return; + const key = region.leg.join(); + const entry = legs.get(key) || { leg: region.leg, depths: [] }; + entry.depths.push(depth); + legs.set(key, entry); + }); + const liftAnkle = (leg, lift) => { + const [hip, knee, ankle] = leg.map(node); + if (![hip, knee, ankle].every((n) => n && result.rotations.has(n.getName()))) return false; + const pos = (n) => new THREE.Vector3().setFromMatrixPosition(world(n)); + const rot = (n) => { const q = new THREE.Quaternion(); world(n).decompose(new THREE.Vector3(), q, new THREE.Vector3()); return q; }; + const H = pos(hip), K = pos(knee), A = pos(ankle); + const fallback = new THREE.Vector3(1, 0, 0).applyQuaternion(rot(hip)); + const solved = solveTwoBone(H, K, A, A.clone().add(new THREE.Vector3(0, lift, 0)), rot(hip), rot(knee), fallback); + const locals = [ + [hip, rot(rig.parent.get(hip)).invert().multiply(solved.hip)], + [knee, solved.hip.clone().invert().multiply(solved.knee)], + [ankle, solved.knee.clone().invert().multiply(rot(ankle))], + ]; + for (const [n, q] of locals) { + q.normalize(); + const track = result.rotations.get(n.getName()); + const prev = track.slice(i * 4, i * 4 + 4); + if (prev[0] * q.x + prev[1] * q.y + prev[2] * q.z + prev[3] * q.w < 0) q.set(-q.x, -q.y, -q.z, -q.w); + track.set(q.toArray(), i * 4); + overrides.set(n, { ...overrides.get(n), r: q.toArray() }); + } + stats.ankleLift.max = Math.max(stats.ankleLift.max, lift); + touched.add('ankleLift'); + return true; + }; + for (const { leg, depths } of legs.values()) if (depths.length > 1 && liftAnkle(leg, Math.min(...depths))) moved = true; + if (moved) continue; // re-skin before pitching + regions.forEach((region, ri) => { + const depth = floor - low[ri].y; + if (!active[ri] || depth <= FLOOR_CLAMP_TOLERANCE) return; + sinking = true; + if (moved && region.lift) return; // re-measure after rotations before lifting the body + if (region.lift) { + const parent = rig.parent.get(hipsNode); + const toLocal = parent ? world(parent).clone().invert() : parentWorldInv; + const hipsWorld = new THREE.Vector3().setFromMatrixPosition(world(hipsNode)).add(new THREE.Vector3(0, depth, 0)); + const local = hipsWorld.applyMatrix4(toLocal).toArray(); + overrides.set(hipsNode, { ...overrides.get(hipsNode), t: local }); + result.hips.set(local, i * 3); + stats[region.name].max = Math.max(stats[region.name].max, depth); + touched.add(region.name); + moved = true; + return; + } + const V = new THREE.Vector3().fromArray(skinned[low[ri].at[0]], low[ri].at[1] * 3); + for (const pivotName of region.pivots) { + const pivot = node(pivotName); + if (!pivot || !result.rotations.has(pivotName)) continue; + const P = new THREE.Vector3().setFromMatrixPosition(world(pivot)); + const lever = V.clone().sub(P); + const axis = lever.clone().cross(new THREE.Vector3(0, 1, 0)); + if (lever.length() < 1e-4 || axis.length() < 0.2 * lever.length()) continue; // lever (near) vertical + const angle = Math.min(Math.PI / 4, Math.asin(Math.min(1, depth / lever.length())) + 1e-3); + const pivotQ = new THREE.Quaternion(), parentQ = new THREE.Quaternion(); + world(pivot).decompose(new THREE.Vector3(), pivotQ, new THREE.Vector3()); + world(rig.parent.get(pivot)).decompose(new THREE.Vector3(), parentQ, new THREE.Vector3()); + const local = parentQ.invert().multiply(new THREE.Quaternion().setFromAxisAngle(axis.normalize(), angle).multiply(pivotQ)).normalize(); + const track = result.rotations.get(pivotName); + const prev = track.slice(i * 4, i * 4 + 4); + if (prev[0] * local.x + prev[1] * local.y + prev[2] * local.z + prev[3] * local.w < 0) local.set(-local.x, -local.y, -local.z, -local.w); + track.set(local.toArray(), i * 4); + overrides.set(pivot, { ...overrides.get(pivot), r: local.toArray() }); + stats[region.name].max = Math.max(stats[region.name].max, THREE.MathUtils.radToDeg(angle)); + touched.add(region.name); + moved = true; + return; + } + // No pivot can lift it (lever vertical: the heel right under the ankle): raise the ankle. + if (region.leg && liftAnkle(region.leg, depth)) moved = true; + }); if (!moved) break; } - if (touched) stats.frames += 1; + for (const name of touched) stats[name].frames += 1; + if (sinking) unresolved += 1; } - stats.maxDeg = +stats.maxDeg.toFixed(2); - return stats; + for (const v of Object.values(stats)) v.max = +v.max.toFixed(4); + return { ...stats, unresolvedFrames: unresolved }; } /** diff --git a/tools/lib/clip-qa.mjs b/tools/lib/clip-qa.mjs index 32b75c3..af0b7b7 100644 --- a/tools/lib/clip-qa.mjs +++ b/tools/lib/clip-qa.mjs @@ -5,20 +5,22 @@ // with the clip's extracted root motion added back (cm), inside the source's // contact windows; the limit rises to the source's own slide + 1 cm; // lowestVertex lowest skinned vertex per frame: the minimum (penetration when negative) -// and the maximum (the whole body floats) (cm); +// and the maximum (the whole body floats) (cm), and the minimum per body +// region (heel, toe, hand, knee, body) with a stricter heel limit; // hips Hips height range against the bind pose; // loopSeam first versus last frame for loop clips: joint positions (cm) and local // rotations (degrees); // hands LeftHand–RightHand distance; gated for two-handed weapon holds (rifle); // stretch filled from tools/characters/rig-pose-test.mjs --clips (skin stretch). import * as THREE from 'three'; -import { FOOT_CONTACT_JOINTS, footContacts } from './animation-retarget.mjs'; +import { FLOOR_CLAMP_REGIONS, FOOT_CONTACT_JOINTS, footContacts, vertexRegions } from './animation-retarget.mjs'; import { POSE_THRESHOLDS, clipOverrides, skinPositions, worldMatrices } from './character-rig.mjs'; export const CLIP_QA_THRESHOLDS = Object.freeze({ footSlideCm: 4, // planted-foot travel within one contact window footSlideOverSourceCm: 1, // ...or at most this much above the source's own slide (extras.clip.contactSlide) penetrationCm: 2, // lowest vertex may sink at most this far below the floor + heelPenetrationCm: 1, // heels (vertices of the Foot joints) sink at most this far floatCm: 3, // the per-frame lowest vertex may rise at most this far (grounded clips) hipsMaxRatio: 1.08, // hips above the bind height (grounded clips): legs over-extended loopSeamCm: 1.5, @@ -57,6 +59,8 @@ export function measureClip(rig, sampler, meta = {}, { fps = meta.fps || 30 } = const velocity = rm && rm.extracted && rm.mode === 'in-place' ? new THREE.Vector3(rm.velocity[0], 0, rm.velocity[1]) : new THREE.Vector3(); const deform = rig.joints.filter((j, i) => rig.joints.findIndex((k) => k.getName() === j.getName()) === i && !/^Curl_|^head_end$|^headfront$/.test(j.getName())); + const membership = vertexRegions(rig); + const regionLow = {}; const lowest = [], lowestBone = [], hipsY = [], hands = [], feet = Object.fromEntries(FOOT_JOINTS.map((n) => [n, []])); const firstLast = []; for (let f = 0; f < frames; f += 1) { @@ -64,7 +68,14 @@ export function measureClip(rig, sampler, meta = {}, { fps = meta.fps || 30 } = const overrides = clipOverrides(rig, sampler, t); const world = worldMatrices(rig, overrides); let low = Infinity, lowAt = null; - skinPositions(rig, overrides).forEach((p, pi) => { for (let v = 1; v < p.length; v += 3) if (p[v] < low) { low = p[v]; lowAt = [pi, (v - 1) / 3]; } }); + skinPositions(rig, overrides).forEach((p, pi) => { + for (let v = 1; v < p.length; v += 3) { + if (p[v] < low) { low = p[v]; lowAt = [pi, (v - 1) / 3]; } + const r = membership[pi][(v - 1) / 3]; + const name = r == null ? 'body' : FLOOR_CLAMP_REGIONS[r].name; + if (!(regionLow[name] <= p[v] - floor)) regionLow[name] = p[v] - floor; + } + }); lowest.push(low - floor); lowestBone.push(lowAt); hipsY.push(pos(world, 'Hips').y); @@ -126,6 +137,7 @@ export function measureClip(rig, sampler, meta = {}, { fps = meta.fps || 30 } = lowestVertex: { minCm: cm(minLowest), minAt: +(lowest.indexOf(minLowest) / fps).toFixed(3), minBone: dominantBone(rig, lowestBone[lowest.indexOf(minLowest)]), maxCm: cm(maxLowest), maxAt: +(lowest.indexOf(maxLowest) / fps).toFixed(3), floorY: +floor.toFixed(4), + byRegionCm: Object.fromEntries(Object.entries(regionLow).map(([k, v]) => [k, cm(v)])), }, hips: { restHeight: +restHeight.Hips.toFixed(4), min: +Math.min(...hipsY).toFixed(4), max: +Math.max(...hipsY).toFixed(4), @@ -160,6 +172,8 @@ export function evaluateClip(metrics, meta = {}, thresholds = CLIP_QA_THRESHOLDS const slideLimit = Math.max(thresholds.footSlideCm, (metrics.footSlide.sourceCm ?? -Infinity) + thresholds.footSlideOverSourceCm); if (metrics.footSlide.maxCm > slideLimit) failures.push(`foot slide ${metrics.footSlide.maxCm} cm (${metrics.footSlide.joint} ${metrics.footSlide.window?.join('–')}s) > ${+slideLimit.toFixed(2)}`); if (metrics.lowestVertex.minCm < -thresholds.penetrationCm) failures.push(`floor penetration ${metrics.lowestVertex.minCm} cm @${metrics.lowestVertex.minAt}s < -${thresholds.penetrationCm}`); + const heel = metrics.lowestVertex.byRegionCm?.heel; + if (heel != null && heel < -thresholds.heelPenetrationCm) failures.push(`heel sinks ${heel} cm < -${thresholds.heelPenetrationCm}`); if (grounded && metrics.lowestVertex.maxCm > thresholds.floatCm) failures.push(`floats ${metrics.lowestVertex.maxCm} cm @${metrics.lowestVertex.maxAt}s > ${thresholds.floatCm}`); if (grounded && metrics.hips.maxRatio > thresholds.hipsMaxRatio) failures.push(`hips rise to ${metrics.hips.maxRatio}× bind height > ${thresholds.hipsMaxRatio}`); if (meta.loop && metrics.loopSeam) { From 48c87d0c1bbca99d4b7833e7e7279660e22e5915 Mon Sep 17 00:00:00 2001 From: rubenmarcus Date: Mon, 9 Nov 2026 04:07:15 +0000 Subject: [PATCH 10/31] Close remaining floor and source-relative gaps found by the full library Floor clamp: a limb whose pivots are vertical is raised by two-bone IK (hands under a straight arm, heels under the ankle), the rest of the body lifts the hips, and a final whole-body pass lifts out of any remaining penetration or drops a character hanging above the floor where the source has a foot planted. Clips record the source's per-frame foot clearance; QA floats are measured above it, slide allows 1.25x the source's own slide + 1 cm and hips may follow the source's own height + 0.08. FBX files whose footer FBXLoader misreads are re-parsed with a padded footer, and three.js sources can be sampled again after a full LoopOnce pass. Agent: Claude Code Signed-off-by: rubenmarcus --- tools/animations/bake-character.mjs | 3 +- tools/animations/convert-clips.mjs | 2 +- tools/lib/animation-retarget.mjs | 136 ++++++++++++++++++++++------ tools/lib/animation-sources.mjs | 31 ++++++- tools/lib/clip-qa.mjs | 29 ++++-- 5 files changed, 161 insertions(+), 40 deletions(-) diff --git a/tools/animations/bake-character.mjs b/tools/animations/bake-character.mjs index a24f363..df99dac 100755 --- a/tools/animations/bake-character.mjs +++ b/tools/animations/bake-character.mjs @@ -47,13 +47,14 @@ for (const state of states) { const meta = clipMetadata(doc); const source = gltfPoseSource(doc, animation, RIG_MAPS['meshy-28']); const result = retargetClip(source, target, { fps: meta.fps || CLIP_FPS, rootMotion: 'keep', absoluteArms: true, footContact: !args.includes('--no-foot-contact'), footIk: !args.includes('--no-foot-ik'), contacts: meta.contacts || null, loop: Boolean(meta.loop), alignLimbs: args.includes('--no-limb-align') ? [] : undefined }); - const floorClamp = args.includes('--no-floor-clamp') ? null : clampToFloor(rig, result); const scale = (v) => +(v * result.hipsScale).toFixed(4); + const floorClamp = args.includes('--no-floor-clamp') ? null : clampToFloor(rig, result, { clearance: meta.footClearance?.map(scale) }); const rm = meta.rootMotion; const frames = result.times.length; const extras = { ...meta, fps: meta.fps || CLIP_FPS, frames, duration: +result.times[frames - 1].toFixed(4), contactSlide: meta.contactSlide != null ? scale(meta.contactSlide) : undefined, + footClearance: meta.footClearance ? meta.footClearance.map(scale) : undefined, rootMotion: rm ? { ...rm, displacement: rm.displacement.map(scale), velocity: rm.velocity.map(scale), speed: scale(rm.speed) } : undefined, bakedFor: { model: path.basename(model), hipsScale: +result.hipsScale.toFixed(6), joints: result.mapped.length, footContact: result.contactCorrection, footIk: result.ik, floorClamp, alignedLimbs: result.aligned }, }; diff --git a/tools/animations/convert-clips.mjs b/tools/animations/convert-clips.mjs index ebd0d42..2e0d405 100755 --- a/tools/animations/convert-clips.mjs +++ b/tools/animations/convert-clips.mjs @@ -87,7 +87,7 @@ for (const entry of entries) { const frames = result.times.length; const meta = { fps: CLIP_FPS, frames, duration: +result.times[frames - 1].toFixed(4), loop, hold: entry.hold || 'none', airborne: Boolean(entry.airborne), - rootMotion: result.rootMotion, hipsScale: +result.hipsScale.toFixed(6), footContact: result.contactCorrection, footIk: result.ik, contacts: result.contacts, contactSlide: result.sourceSlide, sourceHipsRatio: result.sourceHipsRatio, alignedLimbs: result.aligned, + rootMotion: result.rootMotion, hipsScale: +result.hipsScale.toFixed(6), footContact: result.contactCorrection, footIk: result.ik, contacts: result.contacts, contactSlide: result.sourceSlide, footClearance: result.footClearance, sourceHipsRatio: result.sourceHipsRatio, alignedLimbs: result.aligned, source: { id: entry.id || null, rig: opened.rig, file: path.basename(file), take: opened.take, nativeFps: opened.source.nativeFps, duration: +opened.source.duration.toFixed(4), start: +start.toFixed(4), end: +end.toFixed(4), diff --git a/tools/lib/animation-retarget.mjs b/tools/lib/animation-retarget.mjs index 4b97bf8..1a8105e 100644 --- a/tools/lib/animation-retarget.mjs +++ b/tools/lib/animation-retarget.mjs @@ -244,7 +244,12 @@ export function objectPoseSource(group, clip, map, { baseName = mixamoBaseName } kind: 'object', duration: clip.duration, nativeFps: keyRate(clip.tracks.map((t) => t.times)), joints: new Set(joints.keys()), rest: () => restPose, - sample(t) { mixer.setTime(Math.min(clip.duration, Math.max(0, t))); return read(); }, + sample(t) { + // A LoopOnce action that reached its end stays paused; reset so any time can be sampled again. + action.reset(); + mixer.setTime(Math.min(clip.duration, Math.max(0, t))); + return read(); + }, }; } @@ -274,6 +279,8 @@ export const FOOT_CONTACT_JOINTS = Object.freeze(['LeftFoot', 'LeftToeBase', 'Ri export const CONTACT_HEIGHT = 0.03; export const CONTACT_SPEED = 0.25; export const CONTACT_MIN_FRAMES = 3; +/** Both feet this far above their rest heights (scaled source) count as an airborne frame. */ +export const AIRBORNE_CLEARANCE = 0.08; /** Planted frame windows per foot joint: { LeftFoot: [[first, last], ...], ... } (frame indices). */ export function footContacts(tracks, times) { @@ -368,7 +375,10 @@ export function solveTwoBone(H, K, A, goal, hipQ, kneeQ, fallbackAxis) { * footIk (default on): inside the source's foot contact windows (ramped over IK_BLEND_FRAMES) * the ankle is pinned by two-bone IK to the source ankle's displacement from its rest, scaled * and added to the target ankle's rest; this is where the root velocity (the same scaled - * source drift) keeps it still. Without it, different leg proportions make planted feet slide. + * source drift) keeps it still. (Pinning the ball instead while the heel is up was measured + * and rejected: a leg proportioned differently cannot reach it at push-off, so the ball drags; + * walk-forward on mst went from 1-2 cm to 9.6 cm of slide.) + * Without it, different leg proportions make planted feet slide. * Returns { times, rotations: Map(name -> Float32Array xyzw), hips: Float32Array local xyz, * rootMotion, hipsScale, mapped, contacts, contactCorrection: {min, max} (m), ik }. */ @@ -481,6 +491,12 @@ export function retargetClip(source, target, { for (let k = a; k <= Math.min(b, track.length - 1); k += 1) sourceSlide = Math.max(sourceSlide, Math.hypot(track[k].x - track[a].x, track[k].z - track[a].z)); } } + // Frames with every foot joint more than AIRBORNE_CLEARANCE above its rest height (jumps). + const footNames = Object.keys(footTracks); + let airborneFrames = 0; + for (let i = 0; i < frames; i += 1) if (footNames.length && footNames.every((n) => footTracks[n][i].clear > AIRBORNE_CLEARANCE)) airborneFrames += 1; + // Per frame, how far the source's lowest foot joint is above its rest height (scaled, m). + const footClearance = Array.from({ length: frames }, (_, i) => (footNames.length ? +Math.min(...footNames.map((n) => footTracks[n][i].clear)).toFixed(3) : 0)); // Pass 2: foot IK inside the contact windows. const ik = { legs: 0, maxCorrection: 0 }; @@ -541,7 +557,7 @@ export function retargetClip(source, target, { return { times, rotations, hips, hipsScale, mapped: mapped.map((e) => e.name), contacts, contactCorrection: contact ? { min: round(correction.min), max: round(correction.max) } : null, sourceSlide: round(sourceSlide), - sourceHipsRatio: [round(sourceHips.min), round(sourceHips.max)], aligned: [...restAlign.keys()].map((e) => e.name), + sourceHipsRatio: [round(sourceHips.min), round(sourceHips.max)], aligned: [...restAlign.keys()].map((e) => e.name), airborneFrames, footClearance, ik: footIk ? { legs: ik.legs, maxCorrection: round(ik.maxCorrection) } : null, rootMotion: { mode: rootMotion, extracted: rootMotion !== 'keep', @@ -554,27 +570,32 @@ export function retargetClip(source, target, { /** Penetration below the bind floor tolerated before the floor clamp acts (m). */ export const FLOOR_CLAMP_TOLERANCE = 0.005; +/** Height above the floor at which a body whose source has a foot planted is dropped back (m). */ +export const FLOAT_DROP = 0.02; /* Body regions the bake-time floor clamp keeps above the floor, in the order it treats them. A vertex belongs to the region of its dominant joint. `pivots` are tried in order: the first whose lever to the sinking vertex is not vertical turns about the horizontal axis across that lever (heel: the ankle pitches the foot; toes: the ball; hands: the elbow, then the shoulder). When the heel and the toes of one foot both sink, no pitch can help (the - ankle itself is too low for this foot's shape): two-bone IK on `leg` raises that ankle by - the shallower depth first. `lift` regions (knees) raise the hips instead: a kneeling thigh - is vertical, so no rotation lifts the knee. */ + ankle itself is too low for this foot's shape): two-bone IK on `limb` raises that ankle by + the shallower depth first; the same IK raises a wrist or an ankle whose levers are all + vertical (a hand planted under a straight arm). `lift` regions raise the hips instead: + knees (a kneeling thigh is vertical, so no rotation lifts the knee) and the rest of the + body (`bones: null`: torso, head, upper limbs lying on the floor). */ export const FLOOR_CLAMP_REGIONS = Object.freeze([ - { name: 'heel', bones: ['LeftFoot'], pivots: ['LeftFoot'], leg: ['LeftUpLeg', 'LeftLeg', 'LeftFoot'] }, - { name: 'heel', bones: ['RightFoot'], pivots: ['RightFoot'], leg: ['RightUpLeg', 'RightLeg', 'RightFoot'] }, - { name: 'toe', bones: ['LeftToeBase'], pivots: ['LeftToeBase'], leg: ['LeftUpLeg', 'LeftLeg', 'LeftFoot'] }, - { name: 'toe', bones: ['RightToeBase'], pivots: ['RightToeBase'], leg: ['RightUpLeg', 'RightLeg', 'RightFoot'] }, - { name: 'hand', bones: ['LeftHand', 'Curl_L'], pivots: ['LeftForeArm', 'LeftArm'] }, - { name: 'hand', bones: ['RightHand', 'Curl_R'], pivots: ['RightForeArm', 'RightArm'] }, + { name: 'heel', bones: ['LeftFoot'], pivots: ['LeftFoot'], limb: ['LeftUpLeg', 'LeftLeg', 'LeftFoot'] }, + { name: 'heel', bones: ['RightFoot'], pivots: ['RightFoot'], limb: ['RightUpLeg', 'RightLeg', 'RightFoot'] }, + { name: 'toe', bones: ['LeftToeBase'], pivots: ['LeftToeBase'], limb: ['LeftUpLeg', 'LeftLeg', 'LeftFoot'] }, + { name: 'toe', bones: ['RightToeBase'], pivots: ['RightToeBase'], limb: ['RightUpLeg', 'RightLeg', 'RightFoot'] }, + { name: 'hand', bones: ['LeftHand', 'Curl_L'], pivots: ['LeftForeArm', 'LeftArm'], limb: ['LeftArm', 'LeftForeArm', 'LeftHand'] }, + { name: 'hand', bones: ['RightHand', 'Curl_R'], pivots: ['RightForeArm', 'RightArm'], limb: ['RightArm', 'RightForeArm', 'RightHand'] }, { name: 'knee', bones: ['LeftLeg'], lift: true }, { name: 'knee', bones: ['RightLeg'], lift: true }, + { name: 'body', bones: null, lift: true }, ]); -/** Region name of every vertex of `rig` (dominant joint), or null outside FLOOR_CLAMP_REGIONS. */ +/** Region index of every vertex of `rig` (dominant joint; a `bones: null` region takes the rest). */ export function vertexRegions(rig, regions = FLOOR_CLAMP_REGIONS) { return rig.prims.map((p) => { const out = new Array(p.count).fill(null); @@ -582,7 +603,8 @@ export function vertexRegions(rig, regions = FLOOR_CLAMP_REGIONS) { let best = 0; for (let k = 1; k < 4; k += 1) if (p.W[v * 4 + k] > p.W[v * 4 + best]) best = k; const name = rig.names[p.J[v * 4 + best]]; - const region = regions.findIndex((r) => r.bones.includes(name)); + let region = regions.findIndex((r) => r.bones?.includes(name)); + if (region < 0) region = regions.findIndex((r) => r.bones === null); out[v] = region < 0 ? null : region; } return out; @@ -593,13 +615,16 @@ export function vertexRegions(rig, regions = FLOOR_CLAMP_REGIONS) { * Bake-time, mesh-aware floor clamp (`rig`: loadRig of the character). Per frame the mesh is * skinned; when a region's lowest vertex sinks more than FLOOR_CLAMP_TOLERANCE below the bind * floor, the region's pivot turns it up about the horizontal axis across the lever (at most 45° - * per step), a foot whose heel and toes both sink is raised by leg IK, and `lift` regions - * raise the hips by the depth. Up to 6 passes per frame. + * per step), a foot whose heel and toes both sink (or a limb no pivot can lift) is raised by + * two-bone IK, and `lift` regions raise the hips by the depth. Up to 8 passes per frame; then + * the whole body is lifted out of any remaining penetration, or dropped back to the floor when + * the source has a foot planted (`clearance`: extras.clip.footClearance, scaled) and this + * character hangs more than FLOAT_DROP above it. * Rewrites `result.rotations` and `result.hips` in place. Returns per-region { frames, max } - * (degrees for pivots, metres for lifts; `ankleLift` for the leg IK) and the frames still + * (degrees for pivots, metres for lifts; `limbLift` for the IK) and the frames still * below the tolerance. */ -export function clampToFloor(rig, result, { regions = FLOOR_CLAMP_REGIONS, passes = 6 } = {}) { +export function clampToFloor(rig, result, { regions = FLOOR_CLAMP_REGIONS, passes = 8, clearance = null } = {}) { const bind = skinPositions(rig); let floor = Infinity; for (const b of bind) for (let v = 1; v < b.length; v += 3) floor = Math.min(floor, b[v]); @@ -608,7 +633,8 @@ export function clampToFloor(rig, result, { regions = FLOOR_CLAMP_REGIONS, passe const active = regions.map((r, i) => membership.some((m) => m.includes(i)) && (r.lift || r.pivots.some((p) => node(p) && result.rotations.has(p)))); const stats = {}; for (const r of regions) stats[r.name] ||= { frames: 0, max: 0 }; - stats.ankleLift = { frames: 0, max: 0 }; + stats.limbLift = { frames: 0, max: 0 }; + stats.bodyShift = { frames: 0, max: 0 }; let unresolved = 0; const hipsNode = node('Hips'); const parentWorldInv = rig.parent.get(hipsNode) ? null : new THREE.Matrix4(); @@ -633,18 +659,18 @@ export function clampToFloor(rig, result, { regions = FLOOR_CLAMP_REGIONS, passe })); let moved = false; sinking = false; - // Whole foot below the floor: raise that ankle by leg IK (same leg chain on heel and toe). + // Whole foot below the floor: raise that ankle by leg IK (same limb chain on heel and toe). const legs = new Map(); regions.forEach((region, ri) => { const depth = floor - low[ri].y; - if (!region.leg || !active[ri] || depth <= FLOOR_CLAMP_TOLERANCE) return; - const key = region.leg.join(); - const entry = legs.get(key) || { leg: region.leg, depths: [] }; + if (!region.limb || !active[ri] || depth <= FLOOR_CLAMP_TOLERANCE) return; + const key = region.limb.join(); + const entry = legs.get(key) || { limb: region.limb, depths: [] }; entry.depths.push(depth); legs.set(key, entry); }); - const liftAnkle = (leg, lift) => { - const [hip, knee, ankle] = leg.map(node); + const liftLimb = (limb, lift) => { + const [hip, knee, ankle] = limb.map(node); if (![hip, knee, ankle].every((n) => n && result.rotations.has(n.getName()))) return false; const pos = (n) => new THREE.Vector3().setFromMatrixPosition(world(n)); const rot = (n) => { const q = new THREE.Quaternion(); world(n).decompose(new THREE.Vector3(), q, new THREE.Vector3()); return q; }; @@ -664,11 +690,11 @@ export function clampToFloor(rig, result, { regions = FLOOR_CLAMP_REGIONS, passe track.set(q.toArray(), i * 4); overrides.set(n, { ...overrides.get(n), r: q.toArray() }); } - stats.ankleLift.max = Math.max(stats.ankleLift.max, lift); - touched.add('ankleLift'); + stats.limbLift.max = Math.max(stats.limbLift.max, lift); + touched.add('limbLift'); return true; }; - for (const { leg, depths } of legs.values()) if (depths.length > 1 && liftAnkle(leg, Math.min(...depths))) moved = true; + for (const { limb, depths } of legs.values()) if (depths.length > 1 && liftLimb(limb, Math.min(...depths))) moved = true; if (moved) continue; // re-skin before pitching regions.forEach((region, ri) => { const depth = floor - low[ri].y; @@ -710,11 +736,30 @@ export function clampToFloor(rig, result, { regions = FLOOR_CLAMP_REGIONS, passe moved = true; return; } - // No pivot can lift it (lever vertical: the heel right under the ankle): raise the ankle. - if (region.leg && liftAnkle(region.leg, depth)) moved = true; + // No pivot can lift it (levers vertical: a heel under the ankle, a hand under a straight + // arm): raise the ankle or the wrist by IK. + if (region.limb && liftLimb(region.limb, depth)) moved = true; }); if (!moved) break; } + // Whole body last: lift it out of the floor, or, where the source has a foot planted + // (clearance ≤ 1 cm) and this character hangs more than FLOAT_DROP above the floor, drop it. + let lowest = Infinity; + skinPositions(rig, overrides).forEach((p, pi) => membership[pi].forEach((region, v) => { if (region != null && active[region]) lowest = Math.min(lowest, p[v * 3 + 1]); })); + lowest -= floor; + const shift = lowest < -FLOOR_CLAMP_TOLERANCE ? -lowest + : clearance && clearance[i] != null && clearance[i] <= 0.01 && lowest > FLOAT_DROP ? -lowest : 0; + if (shift) { + const world = worldMatrices(rig, overrides); + const parent = rig.parent.get(hipsNode); + const toLocal = parent ? world(parent).clone().invert() : parentWorldInv; + const local = new THREE.Vector3().setFromMatrixPosition(world(hipsNode)).add(new THREE.Vector3(0, shift, 0)).applyMatrix4(toLocal).toArray(); + overrides.set(hipsNode, { ...overrides.get(hipsNode), t: local }); + result.hips.set(local, i * 3); + stats.bodyShift.max = Math.max(stats.bodyShift.max, Math.abs(shift)); + touched.add('bodyShift'); + sinking = false; + } for (const name of touched) stats[name].frames += 1; if (sinking) unresolved += 1; } @@ -722,6 +767,37 @@ export function clampToFloor(rig, result, { regions = FLOOR_CLAMP_REGIONS, passe return { ...stats, unresolvedFrames: unresolved }; } +/** World joint positions (first node of each name) of `target` at frame i of a retarget result. */ +export function resultJointPositions(target, result, i) { + const out = new Map(), world = new Map(); + for (const e of target.order) { + const rot = result.rotations.get(e.name); + const r = rot && target.byName.get(e.name) === e ? Array.from(rot.slice(i * 4, i * 4 + 4)) : e.r; + const t = e === target.byName.get('Hips') ? Array.from(result.hips.slice(i * 3, i * 3 + 3)) : e.t; + const m = composeTrs(t, r, e.s); + const w = e.parent ? world.get(e.parent).clone().multiply(m) : m; + world.set(e, w); + if (!out.has(e.name)) out.set(e.name, new THREE.Vector3().setFromMatrixPosition(w)); + } + return out; +} + +/** + * First versus last frame of a retarget result: largest joint position difference (m) and + * largest local rotation difference (degrees) over the animated joints. Used to detect loops. + */ +export function resultSeam(target, result) { + const last = result.times.length - 1; + const a = resultJointPositions(target, result, 0), b = resultJointPositions(target, result, last); + let position = 0, rotation = 0; + for (const [name, arr] of result.rotations) { + position = Math.max(position, a.get(name).distanceTo(b.get(name))); + const qa = new THREE.Quaternion().fromArray(arr, 0), qb = new THREE.Quaternion().fromArray(arr, last * 4); + rotation = Math.max(rotation, THREE.MathUtils.radToDeg(qa.angleTo(qb))); + } + return { position, rotation }; +} + /** * Clip GLB: the target skeleton (no mesh) and one animation, LINEAR, rotations for every * mapped joint plus the Hips translation. `extras` lands on the animation (`extras.clip`). diff --git a/tools/lib/animation-sources.mjs b/tools/lib/animation-sources.mjs index 04033be..4f04f64 100644 --- a/tools/lib/animation-sources.mjs +++ b/tools/lib/animation-sources.mjs @@ -34,13 +34,40 @@ export function pickClip(animations, take) { return [...animations].filter((a) => a.tracks.length).sort((a, b) => b.duration * b.tracks.length - a.duration * a.tracks.length)[0] || null; } -/** Parse an FBX file with three's FBXLoader (embedded textures are irrelevant and silenced). */ +/** + * Byte offset where the top-level node list of a binary FBX ends (before its null record), or + * null for ASCII files. Each node record: end offset, property count, property bytes (u32, or + * u64 from version 7500), a name length byte and the name; a zero end offset closes a list. + */ +export function fbxNodeListEnd(bytes) { + if (bytes.subarray(0, 18).toString('latin1') !== 'Kaydara FBX Binary') return null; + const big = bytes.readUInt32LE(23) >= 7500; + let pos = 27; + for (;;) { + const end = big ? Number(bytes.readBigUInt64LE(pos)) : bytes.readUInt32LE(pos); + if (end === 0 || end > bytes.length) return pos; + pos = end; + } +} + +/** + * Parse an FBX file with three's FBXLoader (embedded textures are irrelevant and silenced). + * FBXLoader decides where the node list stops from the footer size (the last 160 + 16 bytes); + * some Mixamo exports carry a different footer and it then reads the footer as a node + * ("Unknown property type"). Those are re-parsed with the footer replaced by 176 zero bytes + * right after the last top-level node, which is what the loader's heuristic expects. + */ export function parseFbx(file) { const bytes = readFileSync(file); const warn = console.warn; console.warn = () => {}; + const parse = (b) => new FBXLoader().parse(b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength), ''); try { - return new FBXLoader().parse(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength), ''); + return parse(bytes); + } catch (error) { + const end = /Unknown property type/.test(error.message) ? fbxNodeListEnd(bytes) : null; + if (end == null) throw error; + return parse(Buffer.concat([bytes.subarray(0, end), Buffer.alloc(176)])); } finally { console.warn = warn; } diff --git a/tools/lib/clip-qa.mjs b/tools/lib/clip-qa.mjs index af0b7b7..bbe4eb0 100644 --- a/tools/lib/clip-qa.mjs +++ b/tools/lib/clip-qa.mjs @@ -18,11 +18,13 @@ import { POSE_THRESHOLDS, clipOverrides, skinPositions, worldMatrices } from './ export const CLIP_QA_THRESHOLDS = Object.freeze({ footSlideCm: 4, // planted-foot travel within one contact window - footSlideOverSourceCm: 1, // ...or at most this much above the source's own slide (extras.clip.contactSlide) + footSlideOverSourceCm: 1, // ...or the source's own slide (extras.clip.contactSlide) x footSlideSourceRatio + 1 cm + footSlideSourceRatio: 1.25, // a pivoting ball/heel travels with foot length, up to ~1.2x between characters penetrationCm: 2, // lowest vertex may sink at most this far below the floor heelPenetrationCm: 1, // heels (vertices of the Foot joints) sink at most this far - floatCm: 3, // the per-frame lowest vertex may rise at most this far (grounded clips) - hipsMaxRatio: 1.08, // hips above the bind height (grounded clips): legs over-extended + floatCm: 3, // the per-frame lowest vertex may rise at most this far above the source's own foot clearance + hipsMaxRatio: 1.08, // hips above the bind height (grounded clips): legs over-extended... + hipsOverSourceRatio: 0.08, // ...unless the source's own hips go that high (+ this margin, its reference offset) loopSeamCm: 1.5, loopSeamDeg: 5, twoHandDeviationCm: 3, // |hand distance − median| for two-handed holds @@ -32,6 +34,18 @@ export const TWO_HAND_HOLDS = Object.freeze(['rifle']); const FOOT_JOINTS = FOOT_CONTACT_JOINTS; const cm = (m) => +(m * 100).toFixed(2); +/** + * Floating measured against the source: per frame, the lowest vertex minus the source's own + * lowest-foot clearance (extras.clip.footClearance, scaled; a jump's flight or a handstand's + * raised feet are not the retarget's fault). Absent clearance: no entry (the raw max applies). + */ +function floatOverSource(lowest, clearance, fps) { + if (!Array.isArray(clearance) || clearance.length !== lowest.length) return {}; + let worst = -Infinity, at = 0; + lowest.forEach((y, f) => { const excess = y - Math.max(0, clearance[f]); if (excess > worst) { worst = excess; at = f; } }); + return { floatOverSourceCm: cm(worst), floatAt: +(at / fps).toFixed(3) }; +} + /** Joint name carrying the largest skin weight of vertex [primitive, vertex]. */ function dominantBone(rig, at) { if (!at) return null; @@ -138,6 +152,7 @@ export function measureClip(rig, sampler, meta = {}, { fps = meta.fps || 30 } = minCm: cm(minLowest), minAt: +(lowest.indexOf(minLowest) / fps).toFixed(3), minBone: dominantBone(rig, lowestBone[lowest.indexOf(minLowest)]), maxCm: cm(maxLowest), maxAt: +(lowest.indexOf(maxLowest) / fps).toFixed(3), floorY: +floor.toFixed(4), byRegionCm: Object.fromEntries(Object.entries(regionLow).map(([k, v]) => [k, cm(v)])), + ...floatOverSource(lowest, meta.footClearance, fps), }, hips: { restHeight: +restHeight.Hips.toFixed(4), min: +Math.min(...hipsY).toFixed(4), max: +Math.max(...hipsY).toFixed(4), @@ -169,13 +184,15 @@ export function stretchFromPoseReport(report, name) { export function evaluateClip(metrics, meta = {}, thresholds = CLIP_QA_THRESHOLDS) { const failures = []; const grounded = !meta.airborne; - const slideLimit = Math.max(thresholds.footSlideCm, (metrics.footSlide.sourceCm ?? -Infinity) + thresholds.footSlideOverSourceCm); + const slideLimit = Math.max(thresholds.footSlideCm, (metrics.footSlide.sourceCm ?? -Infinity) * thresholds.footSlideSourceRatio + thresholds.footSlideOverSourceCm); if (metrics.footSlide.maxCm > slideLimit) failures.push(`foot slide ${metrics.footSlide.maxCm} cm (${metrics.footSlide.joint} ${metrics.footSlide.window?.join('–')}s) > ${+slideLimit.toFixed(2)}`); if (metrics.lowestVertex.minCm < -thresholds.penetrationCm) failures.push(`floor penetration ${metrics.lowestVertex.minCm} cm @${metrics.lowestVertex.minAt}s < -${thresholds.penetrationCm}`); const heel = metrics.lowestVertex.byRegionCm?.heel; if (heel != null && heel < -thresholds.heelPenetrationCm) failures.push(`heel sinks ${heel} cm < -${thresholds.heelPenetrationCm}`); - if (grounded && metrics.lowestVertex.maxCm > thresholds.floatCm) failures.push(`floats ${metrics.lowestVertex.maxCm} cm @${metrics.lowestVertex.maxAt}s > ${thresholds.floatCm}`); - if (grounded && metrics.hips.maxRatio > thresholds.hipsMaxRatio) failures.push(`hips rise to ${metrics.hips.maxRatio}× bind height > ${thresholds.hipsMaxRatio}`); + const float = metrics.lowestVertex.floatOverSourceCm ?? metrics.lowestVertex.maxCm; + if (grounded && float > thresholds.floatCm) failures.push(`floats ${float} cm above the source's feet @${metrics.lowestVertex.floatAt ?? metrics.lowestVertex.maxAt}s > ${thresholds.floatCm}`); + const hipsLimit = Math.max(thresholds.hipsMaxRatio, (metrics.hips.sourceRatio?.[1] ?? -Infinity) + thresholds.hipsOverSourceRatio); + if (grounded && metrics.hips.maxRatio > hipsLimit) failures.push(`hips rise to ${metrics.hips.maxRatio}× bind height > ${+hipsLimit.toFixed(3)}`); if (meta.loop && metrics.loopSeam) { if (metrics.loopSeam.positionCm > thresholds.loopSeamCm) failures.push(`loop seam ${metrics.loopSeam.positionCm} cm (${metrics.loopSeam.positionJoint}) > ${thresholds.loopSeamCm}`); if (metrics.loopSeam.rotationDeg > thresholds.loopSeamDeg) failures.push(`loop seam ${metrics.loopSeam.rotationDeg}° (${metrics.loopSeam.rotationJoint}) > ${thresholds.loopSeamDeg}`); From d397c8bb90d4c838fbb43c6fe59445170246a46c Mon Sep 17 00:00:00 2001 From: rubenmarcus Date: Mon, 9 Nov 2026 04:07:16 +0000 Subject: [PATCH 11/31] Build the animation library from the studio-assets catalog build-library converts every catalog clip except T-poses, rig files, swimming and repeated takes, detects loops from the seam and airborne clips from the source's feet, and writes index.json with the pack key each clip proposes: runtime state, contract extra name, emote_ name or a proposed name (8-way diagonals, sprint, turns, jump phases, death variants). library-report folds clip-qa verdicts into the index with a per-category table. The check covers the plan rules, the floor clamp lifts and drops, and the FBX footer fallback. Agent: Claude Code Signed-off-by: rubenmarcus --- tools/animations/build-library.mjs | 81 ++++++++++ tools/animations/library-report.mjs | 52 +++++++ tools/checks/animation-conversion-check.mjs | 100 ++++++++++++- tools/lib/animation-library.mjs | 158 ++++++++++++++++++++ 4 files changed, 385 insertions(+), 6 deletions(-) create mode 100755 tools/animations/build-library.mjs create mode 100755 tools/animations/library-report.mjs create mode 100644 tools/lib/animation-library.mjs diff --git a/tools/animations/build-library.mjs b/tools/animations/build-library.mjs new file mode 100755 index 0000000..ebfd9a5 --- /dev/null +++ b/tools/animations/build-library.mjs @@ -0,0 +1,81 @@ +#!/usr/bin/env node +// Convert every catalog clip of the private studio-assets animation catalog into meshy-28 +// reference clips (docs/animation-conversion.md#library). +// +// node tools/animations/build-library.mjs --catalog=/animations/catalog.json --out= +// [--only=] [--ids=] +// +// Writes /reference/.glb and /index.json: per clip the pack key it proposes +// (tools/lib/animation-library.mjs), catalog id, duration, loop (detected from the seam where +// the category allows it), airborne (both feet off the ground in the source), speed (m/s at +// reference scale) and the skipped catalog clips with their reason. Bake and QA per character +// with bake-character.mjs and clip-qa.mjs; library-report.mjs folds the verdicts back in. +import { NodeIO } from '@gltf-transform/core'; +import { ALL_EXTENSIONS } from '@gltf-transform/extensions'; +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { CLIP_FPS, referenceSkeletonDocument, resultSeam, retargetClip, skeletonGraph, writeClipDocument } from '../lib/animation-retarget.mjs'; +import { LOOP_SEAM, PROPOSED_EXTRA_NAMES, planLibrary } from '../lib/animation-library.mjs'; +import { openSource } from '../lib/animation-sources.mjs'; + +const args = process.argv.slice(2); +const flag = (name) => args.find((a) => a.startsWith(`--${name}=`))?.slice(name.length + 3); +const catalogFile = flag('catalog'), outDir = flag('out'); +if (!catalogFile || !outDir) { + console.error('usage: build-library.mjs --catalog= --out= [--only=] [--ids=]'); + process.exit(1); +} +const catalog = JSON.parse(readFileSync(catalogFile, 'utf8')); +const root = path.dirname(path.dirname(path.resolve(catalogFile))); +const plan = planLibrary(catalog); +const only = flag('only')?.split(','), ids = flag('ids')?.split(','); +const todo = plan.clips.filter((c) => (!only || only.includes(c.category)) && (!ids || ids.includes(c.id))); +mkdirSync(path.join(outDir, 'reference'), { recursive: true }); +const io = new NodeIO().registerExtensions(ALL_EXTENSIONS); +const target = skeletonGraph(referenceSkeletonDocument()); +const round = (v, d = 4) => +v.toFixed(d); + +const entries = [], errors = []; +for (const [n, c] of todo.entries()) { + const file = path.join(root, c.file); + try { + const src = c.action + ? await openSource(file, { action: c.action, rig: 'ual' }) + : await openSource(file); + const draft = retargetClip(src.source, target, { fps: CLIP_FPS, rootMotion: 'in-place', loop: c.loop === true }); + const seam = resultSeam(target, draft); + const loop = c.loop === 'auto' ? seam.position <= LOOP_SEAM.position && seam.rotation <= LOOP_SEAM.rotation : c.loop; + // Loops re-run so foot IK ramps wrap the seam. + const result = loop && c.loop !== true ? retargetClip(src.source, target, { fps: CLIP_FPS, rootMotion: 'in-place', loop: true }) : draft; + const frames = result.times.length; + const airborne = result.airborneFrames >= 2; + const meta = { + fps: CLIP_FPS, frames, duration: round(result.times[frames - 1]), loop, hold: c.hold, airborne, + rootMotion: result.rootMotion, hipsScale: round(result.hipsScale, 6), footContact: result.contactCorrection, footIk: result.ik, + contacts: result.contacts, contactSlide: result.sourceSlide, footClearance: result.footClearance, sourceHipsRatio: result.sourceHipsRatio, alignedLimbs: result.aligned, + source: { id: c.id, rig: src.rig, file: path.basename(file), take: src.take, nativeFps: src.source.nativeFps, duration: round(src.source.duration), start: 0, end: round(src.source.duration) }, + library: { key: c.key, keyStatus: c.keyStatus, primary: c.primary, category: c.category }, + reference: 'meshy-28 reference (MESHY28_REFERENCE_JOINTS)', + }; + await io.write(path.join(outDir, 'reference', `${c.name}.glb`), writeClipDocument(target, result, c.name, meta)); + entries.push({ + name: c.name, key: c.key, keyStatus: c.keyStatus, primary: c.primary, id: c.id, category: c.category, pack: c.pack, + weapon: c.weapon, hold: c.hold, loop, loopSeam: { position: round(seam.position), rotation: round(seam.rotation, 2) }, airborne, + duration: meta.duration, frames, speed: result.rootMotion.speed, velocity: result.rootMotion.velocity, + file: `reference/${c.name}.glb`, source: { file: c.file, action: c.action }, + }); + console.log(`[${n + 1}/${todo.length}] ${c.name} ${c.key ? `${c.key} (${c.keyStatus}${c.primary ? ', primary' : ''})` : ''} ${meta.duration}s${loop ? ' loop' : ''}${airborne ? ' airborne' : ''} ${result.rootMotion.speed} m/s`); + } catch (error) { + errors.push({ id: c.id, error: error.message }); + console.error(`[${n + 1}/${todo.length}] FAILED ${c.id}: ${error.message}`); + } +} +const index = { + schema: 'coro-solto/animation-library@1', skeleton: 'meshy-28', fps: CLIP_FPS, catalog: catalog.schema, + counts: { catalog: catalog.clips.length, converted: entries.length, skipped: plan.skipped.length, failed: errors.length }, + proposedExtraNames: PROPOSED_EXTRA_NAMES, + clips: entries, skipped: plan.skipped, failed: errors, +}; +writeFileSync(path.join(outDir, 'index.json'), `${JSON.stringify(index, null, 2)}\n`); +console.log(`library: ${entries.length} converted, ${plan.skipped.length} skipped, ${errors.length} failed -> ${path.join(outDir, 'index.json')}`); +if (errors.length) process.exit(1); diff --git a/tools/animations/library-report.mjs b/tools/animations/library-report.mjs new file mode 100755 index 0000000..dd6c29b --- /dev/null +++ b/tools/animations/library-report.mjs @@ -0,0 +1,52 @@ +#!/usr/bin/env node +// Fold clip-qa reports into a library index and summarise them per catalog category +// (docs/animation-conversion.md#library). +// +// node tools/animations/library-report.mjs --index=/index.json --qa=