Import a 3D Model and automatically assign and export animations
TypeScript
three.js pose() fix to better reset transforms
Scott Petrovicb0b0701c9143
diff --git a/docs/threejs-skeleton-pose-proposal.md b/docs/threejs-skeleton-pose-proposal.mdnew file mode 100644index 0000000..0157d41--- /dev/null+++ b/docs/threejs-skeleton-pose-proposal.md@@ -0,0 +1,233 @@+# Proposal: `Skeleton.pose()` should divide out non-Bone ancestor transforms++Notes toward a three.js issue / PR. Written against **three.js r185 (0.185.1)**.++## Summary++`Skeleton.pose()` does not restore the bind pose for any skeleton whose root bone has a+transformed non-`Bone` ancestor — the "Armature" node that glTF and FBX exports almost+always produce. For those rigs it writes a **world** matrix into a **local** transform, so+the ancestor's transform ends up applied twice and the entire rig comes out rotated and/or+mis-scaled.++Measured on a stock Mixamo glTF rig with a `-90°` X armature node: the root bone's local+rotation is off by exactly **90°**, and every bone in the skeleton inherits that as a single+rigid rotation.++## The defect++`src/objects/Skeleton.js`:++```js+pose() {++ // recover the bind-time world matrices+ for ( let i = 0, il = this.bones.length; i < il; i ++ ) {+ const bone = this.bones[ i ];+ if ( bone ) {+ bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();+ }+ }++ // compute the local matrices, positions, rotations and scales+ for ( let i = 0, il = this.bones.length; i < il; i ++ ) {+ const bone = this.bones[ i ];+ if ( bone ) {+ if ( bone.parent && bone.parent.isBone ) {+ bone.matrix.copy( bone.parent.matrixWorld ).invert();+ bone.matrix.multiply( bone.matrixWorld );+ } else {+ bone.matrix.copy( bone.matrixWorld ); // <-- here+ }+ bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );+ }+ }++}+```++The marked line assigns a world matrix to `bone.matrix`, which is a **local** matrix.++## Why this is a bug rather than a documented limitation++`pose()` is meant to be the inverse of `calculateInverses()`, and `calculateInverses()`+records **full world** matrices:++```js+calculateInverses() {+ this.boneInverses.length = 0;+ for ( let i = 0, il = this.bones.length; i < il; i ++ ) {+ const inverse = new Matrix4();+ if ( this.bones[ i ] ) {+ inverse.copy( this.bones[ i ].matrixWorld ).invert(); // world space+ }+ this.boneInverses.push( inverse );+ }+}+```++So `boneInverses[i]⁻¹` is `bone.matrixWorld` at bind time, which includes *every* ancestor —+bones and non-bones alike.++The second loop is internally inconsistent about that:++| root bone's parent | what `pose()` computes | correct? |+| --- | --- | --- |+| a `Bone` | `bindParentWorld⁻¹ · bindWorld` | yes — the ancestor chain is divided out |+| anything else (`Object3D`, `Group`) | `bindWorld` | **no** — the ancestor chain is left in |++Writing `A · L₀` into a bone whose parent still contributes `A` yields a rendered world+transform of `A · A · L₀`. The `Bone` branch already establishes that dividing out the+parent is the intended behavior; the `else` branch just skips it.++## Impact++- **`SkinnedMesh.pose()`** (`src/objects/SkinnedMesh.js:254`) delegates straight to this.+- **`SkeletonUtils.retarget()`** (`examples/jsm/utils/SkeletonUtils.js:64`) calls+ `target.skeleton.pose()` to reset the target before retargeting, so three.js's own bundled+ retargeting helper is affected.+- Anyone writing custom retargeting, pose-mixing, or bind-pose-reset code on loaded assets.++The trigger is extremely common in practice:++- Blender's glTF exporter emits an `Armature` node, frequently with a `-90°` X rotation for+ Z-up source scenes.+- FBX rigs authored in centimetres arrive with a `0.01` scale on the root node.+- Any application that positions, rotates, or scales a loaded rig's container before+ `pose()` runs.++Rigs whose armature node happens to be identity are unaffected, which is why this goes+unnoticed — it looks like a per-asset problem rather than a library one.++## Minimal reproduction++```js+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';++const gltf = await new GLTFLoader().loadAsync( 'mixamo-rig.glb' );+const scene = gltf.scene;++// author the rig the way a Z-up tool exports it+const armature = scene.children.find( ( c ) => c.name.includes( 'Armature' ) );+armature.rotation.x = - Math.PI / 2;+scene.updateMatrixWorld( true );++let skinnedMesh;+scene.traverse( ( c ) => { if ( c.isSkinnedMesh ) skinnedMesh = c; } );+const skeleton = skinnedMesh.skeleton;++// a rig actually authored this way has the armature transform baked into its inverse bind+// matrices, because glTF inverseBindMatrices are expressed in scene space+skeleton.calculateInverses();++const before = skeleton.bones.map( ( b ) => b.quaternion.clone() );++skeleton.pose(); // should be a no-op: the rig is already in its bind pose++skeleton.bones.forEach( ( bone, i ) => {+ const delta = before[ i ].clone().invert().multiply( bone.quaternion );+ const deg = 2 * Math.acos( Math.min( 1, Math.abs( delta.w ) ) ) * 180 / Math.PI;+ if ( deg > 0.5 ) console.log( bone.name, deg.toFixed( 2 ), 'deg' );+} );+// -> mixamorigHips 90.00 deg+```++`pose()` on a skeleton already in its bind pose must be a no-op. It is not.++## Measured results++Stock Mixamo glTF rig, 65 bones. "off by" is the largest deviation from the true bind pose+across all bones, after calling `pose()` on a skeleton that was already in its bind pose:++| armature node transform | shipped `pose()` | proposed `pose()` |+| --- | --- | --- |+| `rotation.x = -90°` | **90.000° / 1.4748 units** | 0.030° / 0.0000 units |+| `scale = 0.01` | 0.030° / **1.0324 units** | 0.030° / 0.0000 units |+| identity (control) | 0.030° / 0.0000 units | 0.030° / 0.0000 units |++Two things worth noting:++- The `0.030°` floor appears in **every** row including the control, so it is float32+ quantization in the asset plus `Matrix4.decompose` round-tripping — not attributable to+ either implementation.+- The scale case corrupts **position only**, leaving rotation clean. That is the familiar+ "model renders at 1/100th the size its bounding box reports" symptom, which suggests some+ existing scale-related bug reports may share this root cause.++## Proposed fix++Divide out the non-`Bone` parent, mirroring what the `Bone` branch already does:++```diff+ } else {++ bone.matrix.copy( bone.matrixWorld );+++ if ( bone.parent !== null ) {++++ // bone.matrixWorld is a world matrix, so any non-Bone ancestor chain++ // (an Armature node, a scaled container) has to be divided out too++ _offsetMatrix.copy( bone.parent.matrixWorld ).invert();++ bone.matrix.premultiply( _offsetMatrix );++++ }+++ }+```++`_offsetMatrix` is already declared at module scope (`Skeleton.js:11`) so no new allocation+is needed — it is otherwise only used by `update()`, which never interleaves with `pose()`.+Do not reuse `_identityMatrix` on line 12; it is a shared constant. Verified against the+table above.++### Backward compatibility++When the non-`Bone` ancestor chain is identity, `parent.matrixWorld⁻¹` is the identity+matrix and the added line is a no-op — see the control row. Behavior changes **only** for+rigs that are currently broken.++### Caveat a maintainer will want to weigh++The `Bone` branch divides by the **bind-time** parent world (loop 1 overwrote+`parent.matrixWorld` with it). The patch above divides by the ancestor's **current** world+matrix, because the bind-time transform of a non-`Bone` ancestor is not stored anywhere on+`Skeleton`.++These coincide whenever the armature has not moved since bind time, which covers essentially+all real usage — a loaded asset gets `pose()` called on it in the same place it was bound.+They diverge only if the armature is transformed *between* binding and `pose()`, and in that+case the patch preserves the bind-time **world** pose while the ideal would preserve the+bind-time **local** pose. Both are defensible; today's behavior is neither.++If that divergence matters, the fully correct alternative is to have `calculateInverses()`+record the root's bind-time ancestor transform in a new field (analogous to how+`SkinnedMesh` already stores `bindMatrix` / `bindMatrixInverse` for exactly this reason) and+have `pose()` divide by that instead. It is more correct but adds API surface and a+serialization concern, so it is probably a follow-up rather than the first PR.++### Also worth fixing while in here++`pose()` reads `bone.parent.matrixWorld` without updating it, so it inherits the same+undocumented precondition as `calculateInverses()`: the caller must have run+`updateMatrixWorld()` first. Worth stating in the docstring either way, and it becomes+load-bearing once the patch above starts reading the parent's matrix.++## Workaround for anyone hitting this today++Restore the rest pose from a snapshot captured at load time rather than calling `pose()`, or+post-process the root bones:++```js+const inverse = new Matrix4();+skeleton.pose();+for ( const bone of skeleton.bones ) {+ if ( bone.parent && ! bone.parent.isBone ) {+ bone.matrix.premultiply( inverse.copy( bone.parent.matrixWorld ).invert() );+ bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );+ }+}+```++Note that recovering the rest pose from `boneInverses` this way divides by the ancestor's+*current* world matrix, so it will also divide out any scale or rotation the application+applied to the container after load. If that applies, prefer the snapshot approach.diff --git a/src/retarget/AnimationRetargetService.ts b/src/retarget/AnimationRetargetService.tsindex 62460c3..2dbdd22 100644--- a/src/retarget/AnimationRetargetService.ts+++ b/src/retarget/AnimationRetargetService.ts@@ -3,12 +3,13 @@ import {VectorKeyframeTrack, Scene, Group, type SkinnedMesh,type Skeleton} from 'three'-import { RetargetUtils, type TrackNameParts } from './RetargetUtils.ts'+import { RetargetUtils, type TrackNameParts, type BoneRestTransform } from './RetargetUtils.ts'import { TargetBoneMappingType } from './steps/StepBoneMapping.ts'import { SkeletonType } from '../lib/enums/SkeletonType.ts'import { Retargeter } from './human-retargeting/Retargeter.ts'import { Rig } from './human-retargeting/Rig.ts'import { HumanChainConfig } from './human-retargeting/HumanChainConfig.ts'+import { RetargetDiagnostics, type RestPoseSnapshot } from './RetargetDiagnostics.ts'// AnimationRetargetService - Shared service for retargeting animations from one skeleton to another// Used by both RetargetAnimationPreview and RetargetAnimationListing@@ -25,6 +26,11 @@ export class AnimationRetargetService {private target_armature: Scene = new Scene()private target_skinned_meshes: SkinnedMesh[] = []++ // rest pose of the target skeleton, captured at load time. The retargeting working copy+ // is restored to this instead of using native Skeleton.pose() - see clone_skeleton+ private target_rest_transforms: BoneRestTransform[] = []+private target_mapping_type: TargetBoneMappingType = TargetBoneMappingType.Customprivate bone_mappings: Map<string, string> = new Map<string, string>()@@ -75,6 +81,14 @@ export class AnimationRetargetService {this.target_skinned_meshes.push(child as SkinnedMesh)}})++ // Capture the rest pose now, while the model is freshly loaded and nothing has played+ // it. This is the only reliable moment: once a preview animation runs, the bone locals+ // are gone and they cannot be recovered from boneInverses without also reintroducing+ // the import scale applied in StepLoadTargetModel.+ this.target_rest_transforms = this.target_skinned_meshes.length > 0+ ? RetargetUtils.capture_bone_rest_transforms(this.target_skinned_meshes[0].skeleton)+ : []}public get_target_skinned_meshes (): SkinnedMesh[] {@@ -206,9 +220,17 @@ export class AnimationRetargetService {return source_clip.clone()}+ // snapshot the REAL target rest pose before anything clones or drives it. Every+ // consistency check below is measured against this reference+ const target_rest_snapshot: RestPoseSnapshot =+ RetargetDiagnostics.capture_rest_snapshot(this.target_skinned_meshes[0].skeleton, this.target_rest_transforms)+ const source_rest_snapshot: RestPoseSnapshot =+ RetargetDiagnostics.capture_rest_snapshot(source_skeleton)+// we don't want to mutate/modify the original target skeleton since it is shared// across the app and will create issues as we change animations for retargeting later.- const detached_target_skeleton: Skeleton = RetargetUtils.clone_skeleton(this.target_skinned_meshes[0].skeleton)+ const detached_target_skeleton: Skeleton = RetargetUtils.clone_skeleton(+ this.target_skinned_meshes[0].skeleton, this.target_rest_transforms)// create a custom "Rig" for the source and the target skeletonsconst source_rig: Rig = new Rig(source_skeleton)@@ -229,6 +251,14 @@ export class AnimationRetargetService {target_rig.fromConfig(custom_target_config)}+ // instrumentation. Runs before the retargeter drives anything, so the rigs are still+ // holding the rest pose they captured. See RetargetDiagnostics for why each check exists+ RetargetDiagnostics.report_skeleton_structure('TARGET', this.target_skinned_meshes[0].skeleton)+ RetargetDiagnostics.report_skeleton_structure('SOURCE', source_skeleton)+ RetargetDiagnostics.report_pose_fidelity('TARGET', target_rest_snapshot, target_rig)+ RetargetDiagnostics.report_pose_fidelity('SOURCE', source_rest_snapshot, source_rig)+ RetargetDiagnostics.report_source_consistency(source_rig, source_skeleton)+const retargeter: Retargeter = new Retargeter(source_rig, target_rig, source_clip)// apply any global rig correction the user has set (fixes tilted rigs that@@ -248,6 +278,10 @@ export class AnimationRetargetService {// 30 fps for input animations is usually sufficient for nowconst retargeted_tracks: Array<QuaternionKeyframeTrack | VectorKeyframeTrack> = retargeter.bake_animation_to_tracks(30)+ // the decisive check: any UNMAPPED bone that moves off its rest pose on frame 0 is+ // carrying a corrupted rest pose out of the cloned skeleton+ RetargetDiagnostics.report_baked_frame_zero(retargeted_tracks, target_rest_snapshot, target_rig)+// Create and return the new retargeted animation clipconst retargeted_clip = new AnimationClip(`${source_clip.name} RT`, // RT means retargeteddiff --git a/src/retarget/RetargetDiagnostics.harness.test.ts b/src/retarget/RetargetDiagnostics.harness.test.tsnew file mode 100644index 0000000..7ded819--- /dev/null+++ b/src/retarget/RetargetDiagnostics.harness.test.ts@@ -0,0 +1,119 @@+// TEMPORARY harness. Exercises RetargetDiagnostics against the two known-good sample+// rigs so we can confirm the instrumentation runs and reports "clean" before pointing it+// at the rig that actually misbehaves. Delete once the real bug is found.+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { Object3D, Quaternion, SkinnedMesh, type Skeleton } from 'three'+import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'+import { RetargetUtils } from './RetargetUtils.ts'+import { RetargetDiagnostics, type RestPoseSnapshot } from './RetargetDiagnostics.ts'+import { Rig } from './human-retargeting/Rig.ts'+import { HumanChainConfig } from './human-retargeting/HumanChainConfig.ts'++async function load_glb (path: string): Promise<Object3D> {+ const buffer = readFileSync(path)++ // allocate inside this realm. A Node ArrayBuffer fails GLTFLoader's+ // `data instanceof ArrayBuffer` check under jsdom and gets parsed as JSON instead+ const array_buffer = new ArrayBuffer(buffer.byteLength)+ new Uint8Array(array_buffer).set(buffer)++ const loader = new GLTFLoader()+ return await new Promise((resolve, reject) => {+ loader.parse(array_buffer, '', (gltf) => resolve(gltf.scene), reject)+ })+}++function first_skinned_mesh (root: Object3D): SkinnedMesh {+ let found: SkinnedMesh | null = null+ root.traverse((child) => {+ if (found === null && child instanceof SkinnedMesh) found = child+ })+ if (found === null) throw new Error('no skinned mesh')+ return found+}++describe('RetargetDiagnostics against known-good rigs', () => {+ // m2m-sample-rig.glb is skipped: its embedded texture never finishes decoding under+ // jsdom, so GLTFLoader's onLoad never fires. The Mixamo rig is enough of a baseline.++ it('reports a clean rest pose for the Mixamo sample rig', async () => {+ const scene = await load_glb('static/test-files/retarget testing/mixamo-sample-rig.glb')+ scene.updateMatrixWorld(true)+ RetargetUtils.reset_skinned_mesh_to_rest_pose(scene)++ const real_skeleton: Skeleton = first_skinned_mesh(scene).skeleton+ const rest = RetargetUtils.capture_bone_rest_transforms(real_skeleton)+ const snapshot: RestPoseSnapshot = RetargetDiagnostics.capture_rest_snapshot(real_skeleton, rest)++ const clone: Skeleton = RetargetUtils.clone_skeleton(real_skeleton, rest)+ const rig: Rig = new Rig(clone).fromConfig(HumanChainConfig.mixamo_config)++ RetargetDiagnostics.report_skeleton_structure('MIXAMO-TARGET', real_skeleton)+ RetargetDiagnostics.report_pose_fidelity('MIXAMO-TARGET', snapshot, rig)++ expect(max_local_delta_degrees(snapshot, rig)).toBeLessThan(NOISE_DEGREES)+ })++ // Reproduce the condition I believe the custom rig hits: a non-identity transform on+ // the armature node above the bones. If clone_skeleton's native Skeleton.pose() folds+ // that transform into the root bone's LOCAL, the fidelity check must light up.+ it('detects a corrupted rest pose when the armature carries a rotation', async () => {+ const scene = await load_glb('static/test-files/retarget testing/mixamo-sample-rig.glb')++ // author the rig the way a Z-up tool would export it+ const armature: Object3D | undefined = scene.children.find((c) => c.name.toLowerCase().includes('armature'))+ if (armature === undefined) throw new Error('no armature node')+ armature.rotation.x = -Math.PI / 2+ scene.updateMatrixWorld(true)++ const real_skeleton: Skeleton = first_skinned_mesh(scene).skeleton++ // crucial: a rig actually authored this way has the armature transform baked into its+ // inverse bind matrices, because glTF inverseBindMatrices are in scene space. Rotating+ // the node alone leaves boneInverses stale and the bug stays hidden+ real_skeleton.calculateInverses()++ const rest = RetargetUtils.capture_bone_rest_transforms(real_skeleton)+ const snapshot: RestPoseSnapshot = RetargetDiagnostics.capture_rest_snapshot(real_skeleton, rest)++ console.log('\n=== -90 X armature, cloned WITH the rest snapshot (the fix) ===')+ const fixed: Rig = new Rig(RetargetUtils.clone_skeleton(real_skeleton, rest))+ .fromConfig(HumanChainConfig.mixamo_config)+ RetargetDiagnostics.report_skeleton_structure('ROTATED-ARMATURE', real_skeleton)+ RetargetDiagnostics.report_pose_fidelity('FIXED', snapshot, fixed)++ // and the old behaviour: native Skeleton.pose() folds the armature transform into the+ // root bone's local. Kept so the check is proven to have teeth, not passing vacuously+ console.log('\n=== same rig, restored with native Skeleton.pose() (the old bug) ===')+ const posed_clone: Skeleton = RetargetUtils.clone_skeleton(real_skeleton, rest)+ posed_clone.pose()+ const broken: Rig = new Rig(posed_clone).fromConfig(HumanChainConfig.mixamo_config)+ RetargetDiagnostics.report_pose_fidelity('NATIVE-POSE', snapshot, broken)++ expect(max_local_delta_degrees(snapshot, fixed)).toBeLessThan(NOISE_DEGREES)+ expect(max_local_delta_degrees(snapshot, broken)).toBeGreaterThan(89)+ })+})++// glTF stores rotations as float32 and Matrix4.decompose round-trips them, so a fraction+// of a degree of residual is expected. The defect this guards against is ~90 degrees+const NOISE_DEGREES = 0.5++/** Largest rest-pose local rotation error across all bones, in degrees. */+function max_local_delta_degrees (snapshot: RestPoseSnapshot, rig: Rig): number {+ let worst = 0++ rig.tpose.joints.forEach((joint, index) => {+ const reference: Quaternion | undefined = snapshot.local_rotations[index]+ if (reference === undefined) return++ const rot = joint.local.rot+ const actual = new Quaternion(rot[0], rot[1], rot[2], rot[3])+ const delta = reference.clone().invert().multiply(actual)+ const w = Math.min(1, Math.abs(delta.w))+ worst = Math.max(worst, Math.acos(w) * 2 * 180 / Math.PI)+ })++ return worst+}diff --git a/src/retarget/RetargetDiagnostics.ts b/src/retarget/RetargetDiagnostics.tsnew file mode 100644index 0000000..07cca71--- /dev/null+++ b/src/retarget/RetargetDiagnostics.ts@@ -0,0 +1,396 @@+import { Quaternion, Vector3, type Bone, type Object3D, type Skeleton, type QuaternionKeyframeTrack, type VectorKeyframeTrack } from 'three'+import { type Rig } from './human-retargeting/Rig.ts'+import { type Joint } from './human-retargeting/Joint.ts'+import { RetargetUtils, type BoneRestTransform } from './RetargetUtils.ts'++/**+ * Rest-pose snapshot of a live skeleton, taken before any cloning or retargeting+ * happens. Used as the reference every consistency check is measured against.+ */+export interface RestPoseSnapshot {+ bone_names: string[]+ local_rotations: Quaternion[]+ world_rotations: Quaternion[]+}++interface QuatDelta {+ angle_degrees: number+ axis: Vector3+}++interface DeltaRow {+ bone: string+ angle_degrees: number+ axis: string+ driven: boolean+}++/**+ * Temporary instrumentation for the swing/twist retargeting path.+ *+ * WHY THIS EXISTS+ * ---------------+ * Retargeting at rest is provably a no-op. RigItem.fromJoint stores each bone's+ * swing/twist axes as `inv(joint_rest_world_rot) * canonical_axis`, so when the source+ * sits at the rest pose that those axes were sampled from:+ *+ * source_swing = q_src_rest * inv(q_src_rest) * S = S+ * swing_direction = q_tar_rest * inv(q_tar_rest) * S = S+ * Quat.fromSwing(S, S) = identity+ *+ * The target therefore keeps its rest local rotation exactly, no matter how differently+ * the two rigs are oriented -- differing rest conventions cancel out for free. So any+ * visible offset of the target at rest is a bug, and it has to be a break in one of two+ * consistency requirements:+ *+ * (a) SOURCE: the Pose-computed rest world rotation must equal what three.js+ * getWorldQuaternion() reports for the same skeleton state, because applyChain()+ * reads the animated source through three.js but derived its axes from Pose.+ * (b) TARGET: the locals written back into the CLONED skeleton must be relative to the+ * same parent chain the REAL skeleton has, because bake_animation_to_tracks samples+ * the clone and those tracks are replayed on the real skeleton.+ *+ * Each check below isolates one way those can break. Everything reports quaternion+ * deltas as axis + angle, because the axis is what identifies the leaking transform.+ */+export class RetargetDiagnostics {+ /** Master switch. Set to false to silence all retargeting instrumentation. */+ public static readonly ENABLED: boolean = true++ /** Deltas below this are floating point noise, not findings. */+ private static readonly THRESHOLD_DEGREES: number = 0.5++ /** Rows printed per table before truncating. */+ private static readonly MAX_ROWS: number = 20++ // #region SNAPSHOT++ /**+ * Build the rest-pose reference every check is measured against.+ *+ * Pass `rest_transforms` whenever the live skeleton might be mid-animation (it usually+ * is -- stopAllAction does not restore bone locals). World rotations are then composed+ * from those rest locals up the real parent chain, with non-bone ancestors contributing+ * their actual world rotation, so the reference is a true rest pose either way.+ */+ public static capture_rest_snapshot (+ skeleton: Skeleton,+ rest_transforms: BoneRestTransform[] = []+ ): RestPoseSnapshot {+ const use_rest: boolean = rest_transforms.length === skeleton.bones.length+ const index_of = new Map<Bone, number>()+ skeleton.bones.forEach((bone, index) => index_of.set(bone, index))++ const local_of = (bone: Bone): Quaternion => {+ const index = index_of.get(bone)+ return (use_rest && index !== undefined) ? rest_transforms[index].quaternion : bone.quaternion+ }++ const snapshot: RestPoseSnapshot = {+ bone_names: skeleton.bones.map((bone) => bone.name),+ local_rotations: skeleton.bones.map((bone) => local_of(bone).clone()),+ world_rotations: []+ }++ skeleton.bones.forEach((bone) => {+ const world = new Quaternion()+ let current: Object3D | null = bone++ while (current !== null && current.type === 'Bone') {+ world.premultiply(local_of(current as Bone))+ current = current.parent+ }++ // whatever sits above the bones (the armature) contributes its live world rotation+ if (current !== null) {+ current.updateWorldMatrix(true, false)+ world.premultiply(current.getWorldQuaternion(new Quaternion()))+ }++ snapshot.world_rotations.push(world)+ })++ return snapshot+ }++ // #endregion++ // #region CHECKS++ /**+ * Structural assumptions that Pose.fromSkeleton makes about the bone array.+ * Pose derives poseOffset from bones[0].parent and links parents by name against a+ * map that only holds already-iterated bones, so bone ordering and naming matter.+ */+ public static report_skeleton_structure (label: string, skeleton: Skeleton): void {+ if (!this.ENABLED) return++ const bones: Bone[] = skeleton.bones+ const index_of = new Map<Bone, number>()+ bones.forEach((bone, index) => index_of.set(bone, index))++ // bones whose parent is not a Bone are the tops of the hierarchy. Pose can only+ // represent ONE of these, since rootOffset/poseOffset is a single shared transform+ const hierarchy_roots = bones.filter((bone) => bone.parent?.type !== 'Bone')++ // Pose.updateWorld() walks the joint array in order and assumes a parent has already+ // been resolved by the time its child is reached+ const out_of_order = bones.filter((bone) => {+ const parent_index = bone.parent !== null ? index_of.get(bone.parent as Bone) : undefined+ return parent_index !== undefined && parent_index > (index_of.get(bone) ?? 0)+ })++ // Pose links parents by NAME, so duplicates silently mis-link+ const seen = new Set<string>()+ const duplicate_names = new Set<string>()+ bones.forEach((bone) => {+ if (seen.has(bone.name)) duplicate_names.add(bone.name)+ seen.add(bone.name)+ })++ console.group(`[retarget-diag] ${label} skeleton structure (${bones.length} bones)`)+ console.log('bones[0]:', bones[0]?.name, '| parent type:', bones[0]?.parent?.type,+ '| is a hierarchy root:', bones[0]?.parent?.type !== 'Bone')+ console.log('hierarchy roots:', hierarchy_roots.map((bone) => bone.name))++ // the armature transform(s) sitting above the bones. This is the transform that gets+ // double applied when native Skeleton.pose() writes a bind WORLD matrix into a local+ const armatures = new Set(hierarchy_roots.map((bone) => bone.parent).filter((parent) => parent !== null))+ armatures.forEach((armature) => {+ armature.updateWorldMatrix(true, false)+ const rotation = armature.getWorldQuaternion(new Quaternion())+ const scale = armature.getWorldScale(new Vector3())+ const as_axis_angle = this.delta_to_axis_angle(new Quaternion(), rotation)+ console.log(`armature "${armature.name}" (${armature.type}) world rotation:`,+ `${as_axis_angle.angle_degrees.toFixed(2)} deg about ${this.format_axis(as_axis_angle.axis)}`,+ '| world scale:', `[${scale.toArray().map((v) => v.toFixed(4)).join(', ')}]`)+ })++ if (hierarchy_roots.length > 1) {+ console.warn(`FINDING: ${hierarchy_roots.length} hierarchy roots. Pose has a single ` ++ 'poseOffset and cannot represent more than one.')+ }+ if (out_of_order.length > 0) {+ console.warn('FINDING: bones listed before their own parent (Pose.fromSkeleton will ' ++ 'leave pindex = -1 and treat these as hierarchy roots):', out_of_order.map((b) => b.name))+ }+ if (duplicate_names.size > 0) {+ console.warn('FINDING: duplicate bone names (Pose links parents by name):', [...duplicate_names])+ }+ console.groupEnd()+ }++ /**+ * Does the Rig's captured T-pose actually match the live skeleton it was built from?+ *+ * A non-zero LOCAL delta confined to hierarchy-root bones, all equal to the armature's+ * world rotation, is the signature of native Skeleton.pose() writing a bind WORLD+ * matrix into a bone local without dividing out the armature transform.+ */+ public static report_pose_fidelity (label: string, snapshot: RestPoseSnapshot, rig: Rig): void {+ if (!this.ENABLED) return++ const driven: Set<number> = this.driven_bone_indices(rig)+ const local_rows: DeltaRow[] = []+ const world_rows: DeltaRow[] = []++ rig.tpose.joints.forEach((joint: Joint, index: number) => {+ const reference_local = snapshot.local_rotations[index]+ const reference_world = snapshot.world_rotations[index]+ if (reference_local === undefined || reference_world === undefined) return++ const local_delta = this.delta_to_axis_angle(reference_local, this.to_quaternion(joint.local.rot))+ const world_delta = this.delta_to_axis_angle(reference_world, this.to_quaternion(joint.world.rot))++ if (local_delta.angle_degrees > this.THRESHOLD_DEGREES) {+ local_rows.push(this.to_row(joint.name, local_delta, driven.has(index)))+ }+ if (world_delta.angle_degrees > this.THRESHOLD_DEGREES) {+ world_rows.push(this.to_row(joint.name, world_delta, driven.has(index)))+ }+ })++ console.group(`[retarget-diag] ${label} T-pose fidelity vs live skeleton`)+ this.print_rows('LOCAL rotation deltas (expected: none)', local_rows)+ this.print_rows('WORLD rotation deltas (expected: none)', world_rows)++ const pose_offset = this.delta_to_axis_angle(new Quaternion(), this.to_quaternion(rig.tpose.poseOffset.rot))+ console.log('Pose.poseOffset rotation:',+ `${pose_offset.angle_degrees.toFixed(2)} deg about ${this.format_axis(pose_offset.axis)}`,+ '| scale:', `[${Array.from(rig.tpose.poseOffset.scl).map((v) => v.toFixed(4)).join(', ')}]`)++ const orphans = rig.tpose.joints.filter((joint) => joint.pindex === -1)+ console.log('joints with pindex === -1 (treated as hierarchy roots by Pose):',+ orphans.map((joint) => joint.name))+ console.groupEnd()+ }++ /**+ * Requirement (a). applyChain() samples the animated source with three.js+ * getWorldQuaternion(), but RigItem derived the source's swing/twist axes from Pose's+ * world rotations. If those two disagree for the same skeleton state, every source+ * axis is silently rotated by the difference. Call this BEFORE the mixer runs.+ */+ public static report_source_consistency (rig: Rig, skeleton: Skeleton): void {+ if (!this.ENABLED) return++ const driven: Set<number> = this.driven_bone_indices(rig)+ const rows: DeltaRow[] = []++ rig.tpose.joints.forEach((joint: Joint, index: number) => {+ const bone: Bone | undefined = skeleton.bones[index]+ if (bone === undefined) return++ bone.updateWorldMatrix(true, false)+ const three_world = bone.getWorldQuaternion(new Quaternion())+ const delta = this.delta_to_axis_angle(three_world, this.to_quaternion(joint.world.rot))++ if (delta.angle_degrees > this.THRESHOLD_DEGREES) {+ rows.push(this.to_row(joint.name, delta, driven.has(index)))+ }+ })++ console.group('[retarget-diag] SOURCE Pose world vs three.js getWorldQuaternion')+ this.print_rows('deltas (expected: none -- any delta rotates the source swing/twist axes)', rows)+ console.groupEnd()+ }++ /**+ * End-to-end predictor of what the user actually sees. Compares frame 0 of every baked+ * quaternion track against the real skeleton's rest local rotation.+ *+ * The source clip is not exactly at rest on frame 0, so DRIVEN bones are expected to+ * show a small delta. UNDRIVEN bones must show zero: they were never retargeted, so a+ * track that moves them is carrying a corrupted rest pose out of the clone.+ */+ public static report_baked_frame_zero (+ tracks: Array<QuaternionKeyframeTrack | VectorKeyframeTrack>,+ snapshot: RestPoseSnapshot,+ rig: Rig+ ): void {+ if (!this.ENABLED) return++ const driven: Set<number> = this.driven_bone_indices(rig)+ const driven_names = new Set<string>()+ driven.forEach((index) => {+ const name = rig.tpose.joints[index]?.name+ if (name !== undefined) driven_names.add(name)+ })++ const rows: DeltaRow[] = []+ const frame_zero = new Quaternion()++ tracks.forEach((track) => {+ const parts = RetargetUtils.parse_track_name_for_metadata(track.name)+ if (parts === null || parts.property !== 'quaternion') return++ const bone_index = snapshot.bone_names.indexOf(parts.bone_name)+ const reference_local = snapshot.local_rotations[bone_index]+ if (reference_local === undefined) return++ frame_zero.fromArray(track.values as unknown as number[], 0)+ const delta = this.delta_to_axis_angle(reference_local, frame_zero)++ if (delta.angle_degrees > this.THRESHOLD_DEGREES) {+ rows.push(this.to_row(parts.bone_name, delta, driven_names.has(parts.bone_name)))+ }+ })++ const undriven_rows = rows.filter((row) => !row.driven)++ console.group('[retarget-diag] baked frame 0 vs real skeleton rest pose')+ this.print_rows('all bones that move on frame 0', rows)++ if (undriven_rows.length > 0) {+ console.warn(`FINDING: ${undriven_rows.length} UNMAPPED bone(s) are being moved off ` ++ 'their rest pose. These were never retargeted, so the offset is a corrupted rest ' ++ 'pose leaking out of the cloned skeleton. Largest:',+ `${undriven_rows[0].angle_degrees.toFixed(2)} deg about ${undriven_rows[0].axis} on "${undriven_rows[0].bone}"`)+ } else {+ console.log('No unmapped bone moves off rest. The rest-pose invariant holds.')+ }+ console.groupEnd()+ }++ // #endregion++ // #region HELPERS++ /** Quat/Vec3 in the retargeting math extend Array, so they index like [x, y, z, w]. */+ private static to_quaternion (rot: ArrayLike<number>): Quaternion {+ return new Quaternion(rot[0], rot[1], rot[2], rot[3])+ }++ /** Bone indices that are actually part of a mapped chain, so actually retargeted. */+ private static driven_bone_indices (rig: Rig): Set<number> {+ const indices = new Set<number>()+ Object.values(rig.chains).forEach((chain) => {+ chain.forEach((item) => {+ if (item.idx !== -1) indices.add(item.idx)+ })+ })+ return indices+ }++ /**+ * Rotation that takes `from` to `to`, expressed as an axis and a positive angle.+ * The axis is the useful half: it names the transform that leaked in.+ */+ private static delta_to_axis_angle (from: Quaternion, to: Quaternion): QuatDelta {+ const delta = from.clone().invert().multiply(to)++ // a quaternion and its negation are the same rotation. Pick the short way round+ if (delta.w < 0) {+ delta.set(-delta.x, -delta.y, -delta.z, -delta.w)+ }++ const half_angle = Math.acos(Math.min(1, Math.max(-1, delta.w)))+ const sin_half = Math.sin(half_angle)+ const axis = sin_half > 1e-6+ ? new Vector3(delta.x / sin_half, delta.y / sin_half, delta.z / sin_half)+ : new Vector3(0, 0, 0)++ return { angle_degrees: half_angle * 2 * 180 / Math.PI, axis }+ }++ /** Format an axis so a recognizable one (a bare X/Y/Z) is obvious at a glance. */+ private static format_axis (axis: Vector3): string {+ const formatted = `[${axis.toArray().map((v) => v.toFixed(3)).join(', ')}]`+ const named = [+ { name: '+X', vector: new Vector3(1, 0, 0) },+ { name: '-X', vector: new Vector3(-1, 0, 0) },+ { name: '+Y', vector: new Vector3(0, 1, 0) },+ { name: '-Y', vector: new Vector3(0, -1, 0) },+ { name: '+Z', vector: new Vector3(0, 0, 1) },+ { name: '-Z', vector: new Vector3(0, 0, -1) }+ ].find((candidate) => candidate.vector.distanceTo(axis) < 0.01)++ return named !== undefined ? `${named.name} ${formatted}` : formatted+ }++ private static to_row (bone: string, delta: QuatDelta, driven: boolean): DeltaRow {+ return {+ bone,+ angle_degrees: Number(delta.angle_degrees.toFixed(3)),+ axis: this.format_axis(delta.axis),+ driven+ }+ }++ private static print_rows (title: string, rows: DeltaRow[]): void {+ if (rows.length === 0) {+ console.log(`${title}: none above ${this.THRESHOLD_DEGREES} deg`)+ return+ }++ rows.sort((a, b) => b.angle_degrees - a.angle_degrees)+ console.log(`${title}: ${rows.length} bone(s), max ${rows[0].angle_degrees} deg ` ++ `about ${rows[0].axis} on "${rows[0].bone}"`)+ console.table(rows.slice(0, this.MAX_ROWS))+ if (rows.length > this.MAX_ROWS) {+ console.log(`... ${rows.length - this.MAX_ROWS} more row(s) not shown`)+ }+ }++ // #endregion+}diff --git a/src/retarget/RetargetUtils.ts b/src/retarget/RetargetUtils.tsindex 636c279..a310b4b 100644--- a/src/retarget/RetargetUtils.ts+++ b/src/retarget/RetargetUtils.ts@@ -1,4 +1,4 @@-import { type Scene, Group, Matrix4, Skeleton, type SkinnedMesh, type Bone, type Object3D } from 'three'+import { type Scene, Group, Matrix4, Skeleton, Vector3, Quaternion, type SkinnedMesh, type Bone, type Object3D } from 'three'import { ModalDialog } from '../lib/ModalDialog.ts'export interface TrackNameParts {@@ -6,6 +6,13 @@ export interface TrackNameParts {property: string}+/** A single bone's local transform, captured while the skeleton is known to be at rest. */+export interface BoneRestTransform {+ position: Vector3+ quaternion: Quaternion+ scale: Vector3+}+// eslint-disable-next-line @typescript-eslint/no-extraneous-classexport class RetargetUtils {/**@@ -50,7 +57,7 @@ export class RetargetUtils {* second time on the next updateMatrixWorld (e.g. an armature with scale 0.01* makes the model render at 1/100th the size the bounding box reports).*/- static reset_skinned_mesh_to_rest_pose (skinned_meshes_group: Scene): void {+ static reset_skinned_mesh_to_rest_pose (skinned_meshes_group: Object3D): void {// ensure non-bone parent (armature) world matrices are currentskinned_meshes_group.updateMatrixWorld(true)@@ -84,6 +91,23 @@ export class RetargetUtils {})}+ /**+ * Three.js pose() fix for calculating bone local transform from bind-time world matrix.+ * Snapshot every bone's local transform. Call this while the skeleton is known to be at+ * rest (right after load), because once an animation has played there is no longer a+ * reliable way to recover the rest pose: the bind matrices in `boneInverses` are in+ * bind-time space, so dividing them by the *current* parent world reintroduces any+ * transform the app applied afterwards (for example the import scale set in+ * StepLoadTargetModel).+ */+ static capture_bone_rest_transforms (skeleton: Skeleton): BoneRestTransform[] {+ return skeleton.bones.map((bone) => ({+ position: bone.position.clone(),+ quaternion: bone.quaternion.clone(),+ scale: bone.scale.clone()+ }))+ }+/*** Validates that the retargetable model contains SkinnedMeshes with bones* @returns true if valid SkinnedMeshes are found, false otherwise@@ -212,8 +236,13 @@ export class RetargetUtils {* - Our retargeting path needs stable non-bone root parent world transforms for pose offsets.* - This function deep-clones bone hierarchies and recreates detached non-bone root parents using* decomposed world transforms, preventing mutation of live scene bones.- */- static clone_skeleton (source_skeleton: Skeleton): Skeleton {+ *+ * @param rest_transforms rest pose to restore the clone to, from+ * `capture_bone_rest_transforms`. Required for correctness: the live skeleton is+ * usually mid-animation when this is called (stopAllAction does not restore bone+ * locals), and native `Skeleton.pose()` cannot be used to reset it -- see below.+ */+ static clone_skeleton (source_skeleton: Skeleton, rest_transforms: BoneRestTransform[] = []): Skeleton {const original_to_clone = new Map<Bone, Bone>()const root_bones = source_skeleton.bones.filter((bone) =>@@ -271,7 +300,34 @@ export class RetargetUtils {const cloned_bone_inverses = source_skeleton.boneInverses.map((inverse) => inverse.clone())const cloned_skeleton = new Skeleton(cloned_bones, cloned_bone_inverses)- cloned_skeleton.pose()++ // Three.js pose() fix for calculating bone local transform from bind-time world matrix.+ // Restore the rest pose from the snapshot rather than calling native Skeleton.pose().+ //+ // pose() recovers each bind-time WORLD matrix from boneInverses, then for any bone+ // whose parent is not a Bone it copies that world matrix straight into the bone's+ // LOCAL matrix without dividing out the parent. Our clone deliberately gives the root+ // bone a detached parent carrying the armature's full world transform (above), so that+ // transform ends up applied twice. The root bone's local picks up an extra copy of the+ // armature rotation, and since every other bone hangs off it the entire rig comes out+ // rigidly rotated -- a Z-up authored rig (armature at -90 X) lands 90 degrees off.+ // This is the same defect described on reset_skinned_mesh_to_rest_pose above.+ if (rest_transforms.length === cloned_bones.length) {+ cloned_bones.forEach((bone, index) => {+ bone.position.copy(rest_transforms[index].position)+ bone.quaternion.copy(rest_transforms[index].quaternion)+ bone.scale.copy(rest_transforms[index].scale)+ })+ } else if (rest_transforms.length > 0) {+ console.warn('RetargetUtils.clone_skeleton: rest transform count does not match bone ' ++ `count (${rest_transforms.length} vs ${cloned_bones.length}). Leaving the clone in ` ++ 'its current pose.')+ }++ // make the clone's world matrices valid so consumers reading them get real values+ cloned_bones.forEach((bone) => {+ if (bone.parent?.type !== 'Bone') bone.updateMatrixWorld(true)+ })return cloned_skeleton}