@margoengine/rigging 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1443 -2
  4. package/dist/anatomy-data-ansur2.d.ts +63 -0
  5. package/dist/anatomy-data-cdc.d.ts +16 -0
  6. package/dist/anatomy-data-deleva.d.ts +86 -0
  7. package/dist/anatomy-human.d.ts +67 -0
  8. package/dist/anatomy-human.js +2229 -0
  9. package/dist/anatomy.d.ts +638 -0
  10. package/dist/anatomy.js +1112 -0
  11. package/dist/autorig.d.ts +50 -0
  12. package/dist/autorig.js +663 -0
  13. package/dist/bar-grip.d.ts +7 -0
  14. package/dist/body-volumes-DTym0RVY.js +56 -0
  15. package/dist/body-volumes.d.ts +19 -0
  16. package/dist/checks.d.ts +50 -0
  17. package/dist/contact.d.ts +186 -0
  18. package/dist/contact.js +746 -0
  19. package/dist/correctives.d.ts +92 -0
  20. package/dist/correctives.js +162 -0
  21. package/dist/coupling.d.ts +57 -0
  22. package/dist/coupling.js +330 -0
  23. package/dist/errors-D8rc8kzg.js +7 -0
  24. package/dist/face.d.ts +93 -0
  25. package/dist/face.js +144 -0
  26. package/dist/hands.d.ts +209 -0
  27. package/dist/hands.js +510 -0
  28. package/dist/heat.d.ts +38 -0
  29. package/dist/hinged-contact.d.ts +7 -0
  30. package/dist/hulls.d.ts +54 -0
  31. package/dist/hulls.js +134 -0
  32. package/dist/ik.d.ts +162 -0
  33. package/dist/ik.js +561 -0
  34. package/dist/index.d.ts +6 -0
  35. package/dist/index.js +390 -0
  36. package/dist/joint-limits.d.ts +44 -0
  37. package/dist/joint-limits.js +74 -0
  38. package/dist/limb-collision.d.ts +99 -0
  39. package/dist/loading-CZaYr1N7.js +67 -0
  40. package/dist/mesh-CyvLHNp0.js +142 -0
  41. package/dist/mesh.d.ts +47 -0
  42. package/dist/mtoon-data.d.ts +118 -0
  43. package/dist/mtoon-legacy.d.ts +17 -0
  44. package/dist/mtoon-shader.d.ts +4 -0
  45. package/dist/mtoon.d.ts +84 -0
  46. package/dist/mtoon.js +990 -0
  47. package/dist/paint.d.ts +82 -0
  48. package/dist/pose-tracking.d.ts +117 -0
  49. package/dist/pose-tracking.js +488 -0
  50. package/dist/retarget.d.ts +78 -0
  51. package/dist/retarget.js +375 -0
  52. package/dist/rig-BawZ5OLb.js +127 -0
  53. package/dist/rig.d.ts +65 -0
  54. package/dist/shared/gltf.d.ts +257 -0
  55. package/dist/shared/layers.d.ts +16 -0
  56. package/dist/springs.d.ts +180 -0
  57. package/dist/springs.js +458 -0
  58. package/dist/strand-springs.d.ts +46 -0
  59. package/dist/strand-springs.js +168 -0
  60. package/dist/swim.d.ts +55 -0
  61. package/dist/swim.js +167 -0
  62. package/dist/transfer.d.ts +41 -0
  63. package/dist/transfer.js +136 -0
  64. package/dist/validate.d.ts +188 -0
  65. package/dist/validate.js +440 -0
  66. package/dist/voxel-weights-48ok-Dax.js +255 -0
  67. package/dist/voxel-weights.d.ts +42 -0
  68. package/dist/voxel-weights.js +1 -0
  69. package/dist/voxels.d.ts +36 -0
  70. package/dist/vrm-constraints.d.ts +60 -0
  71. package/dist/vrm-constraints.js +261 -0
  72. package/dist/vrm-first-person.d.ts +115 -0
  73. package/dist/vrm-first-person.js +618 -0
  74. package/dist/vrm-presets-CU4V4yq6.js +47 -0
  75. package/dist/vrm-presets.d.ts +1 -0
  76. package/dist/vrm.d.ts +303 -0
  77. package/dist/vrm.js +574 -0
  78. package/dist/vrm0.d.ts +134 -0
  79. package/dist/vrm0.js +377 -0
  80. package/dist/vrma.d.ts +90 -0
  81. package/dist/vrma.js +315 -0
  82. package/dist/weight-map-D8cAONQQ.js +92 -0
  83. package/dist/weight-map.d.ts +58 -0
  84. package/package.json +189 -4
package/README.md CHANGED
@@ -1,3 +1,1444 @@
1
- # Temporary Holding Version
1
+ # @margoengine/rigging
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Import `margoengine/rigging` from the `margoengine` package, or `@margoengine/rigging` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
+
5
+ Rigging and animation authoring for characters made in Margo or anywhere else: smooth automatic skin weights, weight painting with undo, the skin checks game engines need before export, IK chains with poles and retarget presets that play Mixamo, Godot and Roblox clips on any humanoid. Everything here is plain data in, plain data out: no engine, renderer or GPU is needed, core is never imported, and an app that does not import this package ships none of it.
6
+
7
+ ## Automatic weights (bone heat)
8
+
9
+ `boneHeatWeights(mesh, joints)` gives every vertex smooth weights from a rest skeleton, by bone heat diffusion (I. Baran and J. Popović, "Automatic rigging and animation of 3D characters", SIGGRAPH 2007). Each joint moves the vertices around its bone, the segment from the joint to each child (a point at a leaf joint), and weights blend smoothly across joints. Weights are 0 or more and sum to 1 per vertex. Heat only reaches a vertex from bones it can see, so an arm's weight does not leak into the hip it hangs beside.
10
+
11
+ ```ts
12
+ import { boneHeatWeights, checkSkin, type RigJoint } from 'margoengine/rigging';
13
+
14
+ // Any triangle mesh (positions xyz, optional indices) and a rest skeleton in the same space.
15
+ const positions = new Float32Array([0, 0, 0, 1, 0, 0, 0, 2, 0, 1, 2, 0]);
16
+ const indices = new Uint32Array([0, 1, 2, 2, 1, 3]);
17
+ const joints: RigJoint[] = [
18
+ { name: 'hips', parent: -1, position: [0.5, 0, 0] },
19
+ { name: 'spine', parent: 0, position: [0.5, 1, 0] },
20
+ { name: 'head', parent: 1, position: [0.5, 2, 0] },
21
+ ];
22
+ const weights = await boneHeatWeights({ positions, indices }, joints, { visibility: false });
23
+ const { joints: JOINTS_0, weights: WEIGHTS_0 } = weights.toInfluences(4); // glTF's four strongest per vertex
24
+ console.log(JOINTS_0.length, WEIGHTS_0.length); // 16 16
25
+ console.log(checkSkin({ weights: weights.toInfluences(4), joints }).ok); // true
26
+ ```
27
+
28
+ Options, each with its default:
29
+
30
+ | Option | Default | Meaning |
31
+ | --- | --- | --- |
32
+ | `skip` | `[]` | Joints (indices or names) that move no vertices, such as a root at the feet. |
33
+ | `visibility` | `true` | Heat only from visible bones; uses `@margoengine/bvh`, loaded on first use. `false` takes the nearest bone (faster; fine for convex parts). Or pass `(from, to) => boolean`. |
34
+ | `heat` | `1` | Heat constant c in H = c / d². Larger keeps vertices closer to their nearest bone. |
35
+ | `weld` | `1e-6` | Vertices closer than this fraction of the mesh size are one point, so weights cross UV seams and split faces. |
36
+ | `tolerance` | `1e-6` | Largest weight error per vertex when a bone's solve stops. |
37
+ | `maxIterations` | `2000` | Conjugate-gradient iterations per bone; a `MargoError` with code `failed` when not enough. |
38
+ | `threshold` | `1e-4` | Weights below this share are dropped before renormalising. |
39
+ | `signal` | none | `AbortSignal`; the promise rejects with its reason. The solve yields to the event loop every 30 ms. |
40
+
41
+ Vertices at one position always get the same weights. Pass `joints` from `@margoengine/exporters/skin`'s `humanoidJoints()`, or turn any glTF skeleton into joints with `rigJoints(retargetRig(model))`.
42
+
43
+ ## Weight painting
44
+
45
+ `WeightPainter` paints a `WeightMap` with brush dabs: `add`, `subtract`, `replace` (toward `value`) and `smooth` (toward the neighbours' average). Each dab keeps every vertex it touches summing to 1: when one bone gains or loses weight, the other unlocked bones on that vertex make up the difference. Locked bones never change. Every stroke returns its undo.
46
+
47
+ ```ts
48
+ import { WeightMap, WeightPainter } from 'margoengine/rigging';
49
+
50
+ const mesh = { positions: new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]), indices: new Uint32Array([0, 1, 2]) };
51
+ const map = new WeightMap(3, 2, [1, 0, 1, 0, 1, 0]);
52
+ const painter = new WeightPainter(map, mesh, { parents: [-1, 0], locked: [] });
53
+ const stroke = painter.stroke({ mode: 'add', bone: 1, center: [0, 1, 0], radius: 0.8, strength: 0.5, falloff: 'smooth' });
54
+ painter.smoothAll({ iterations: 2, strength: 0.5 });
55
+ stroke.undo(); // undo strokes newest first
56
+ painter.normalize();
57
+ ```
58
+
59
+ | Stroke field | Default | Meaning |
60
+ | --- | --- | --- |
61
+ | `mode` | required | `add`, `subtract`, `replace` or `smooth`. |
62
+ | `bone` | required except for `smooth` | The bone painted. |
63
+ | `center`, `radius` | required | Brush sphere in mesh space. |
64
+ | `strength` | `0.5` | Amount at the centre (0-1). |
65
+ | `value` | `1` | `replace`'s target weight. |
66
+ | `falloff` | `smooth` | `smooth` (smoothstep), `linear` or `constant`. |
67
+
68
+ Subtracting from a vertex whose other bones hold nothing passes the weight to the bone's parent (pass `parents`); with no unlocked parent the vertex keeps it, so a vertex never ends up unweighted. `WeightMap` is dense (`values[vertex * boneCount + bone]`); `toInfluences(4)` returns the strongest four per vertex, renormalised, and `WeightMap.fromInfluences({joints, weights})` reads them back.
69
+
70
+ ## Skin checks before export
71
+
72
+ `checkSkin` reports what Unity, Unreal, Godot, Roblox and glTF validators reject or render wrongly: unweighted vertices, more than four influences, weights that don't sum to 1, negative or non-finite weights, joint indices outside the skin (in any slot, weighted or not), one joint in two weighted slots of a vertex (`duplicate-joint`; glTF 2.0 3.7.3.3 forbids both), and degenerate bones (each counted once) (a joint on its parent, or a non-invertible inverse bind matrix). `assertSkin` throws a `RangeError` naming each fault and its fix.
73
+
74
+ ```ts
75
+ import { WeightMap, assertSkin, checkSkin } from 'margoengine/rigging';
76
+
77
+ const weights = new WeightMap(2, 2, [0.6, 0.6, 0, 0]);
78
+ const report = checkSkin({ weights, maxInfluences: 4, tolerance: 1e-3 });
79
+ for (const issue of report.issues) console.log(issue.code, issue.count, issue.vertices, issue.message);
80
+ // not-normalized 1 [0] "1 vertex(es) have weights that don't sum to 1; call normalize()"
81
+ // unweighted 1 [1] "1 vertex(es) have no weight; paint them or run boneHeatWeights"
82
+ weights.normalize();
83
+ try {
84
+ assertSkin({ weights });
85
+ } catch (error) {
86
+ console.log((error as RangeError).message); // still names vertex 1 as unweighted
87
+ }
88
+ ```
89
+
90
+ Input is a `WeightMap` or per-vertex influences (`{joints, weights, influences?}`, glTF's JOINTS_0 / WEIGHTS_0 at the default width 4); add `joints` (the rest skeleton) or `inverseBindMatrices` to check bones too. Defaults: `maxInfluences` 4, `tolerance` 1e-3.
91
+
92
+ ## IK chains with pole targets (`margoengine/rigging/ik`)
93
+
94
+ FABRIK (A. Aristidou and J. Lasenby, 2011) chains of any length with a pole: the joints move so the last one reaches the target, every bone keeps its length, and the bend faces the pole (a knee or elbow hint). Solve on an Animator every frame, on a `Skeleton` while authoring a pose, or on raw joint positions.
95
+
96
+ ```ts
97
+ import { EngineKernel } from 'margoengine/core';
98
+ import { loadGLTF } from 'margoengine/gltf/pbr';
99
+ import { Animation } from 'margoengine/animation';
100
+ import { Animator } from 'margoengine/animator';
101
+ import { addIKChain, type AnimatorIKChain } from 'margoengine/rigging/ik';
102
+ import { detectSkeleton, humanoidBones } from 'margoengine/rigging/retarget';
103
+
104
+ const engine = await EngineKernel.create(document.querySelector<HTMLCanvasElement>('#viewport')!, { backend: 'webgpu' });
105
+ const model = await loadGLTF(engine, '/character.glb');
106
+ const animator = Animator.attach(Animation.attach(model), { initial: 'idle', states: { idle: 'Idle' } });
107
+ // Bones by name: Mixamo (any mixamorig prefix), Godot, Roblox R15 or humanoid names, whichever the rig uses.
108
+ const names = model.asset.doc.nodes!.map((n) => n.name ?? '');
109
+ const bone = humanoidBones(names, detectSkeleton(names)?.preset ?? 'humanoid'); // humanoid bone -> node index
110
+ const reach: AnimatorIKChain = {
111
+ joints: [bone.get('leftUpperArm')!, bone.get('leftLowerArm')!, bone.get('leftHand')!], // each the child of the one before
112
+ target: [0.4, 1.3, 0.5], // world space; write into it every frame
113
+ pole: [0.3, 1.2, -0.6], // the elbow bends toward this point
114
+ weight: 1, // 0 keeps the animated pose
115
+ iterations: 32, // default 32
116
+ tolerance: 1e-4, // default 1e-4, world units
117
+ };
118
+ const remove = addIKChain(animator, reach);
119
+ engine.start();
120
+ remove(); // when done
121
+ ```
122
+
123
+ For joint limits use `addCCDChain` from `margoengine/animator`. While authoring (no engine), `solveSkeletonIK(skeleton, {joints, target, pole})` poses an `@margoengine/animation` `Skeleton` by bone names or indices, `solvePoseIK({parents, local}, chain)` solves on a local pose array (10 numbers per bone, as `retargetRig` makes), and `solveFABRIK(points, target, {pole})` moves raw joint positions:
124
+
125
+ ```ts
126
+ import { Skeleton } from 'margoengine/animation';
127
+ import { solveFABRIK, solveSkeletonIK } from 'margoengine/rigging/ik';
128
+
129
+ const leg = new Skeleton([
130
+ { name: 'hip', parent: -1 },
131
+ { name: 'knee', parent: 0, translation: [0, -0.45, 0] },
132
+ { name: 'ankle', parent: 1, translation: [0, -0.42, 0] },
133
+ ]);
134
+ const result = solveSkeletonIK(leg, { joints: ['hip', 'knee', 'ankle'], target: [0.1, -0.7, 0.2], pole: [0, -0.4, 1] });
135
+ console.log(result.reached, result.distance, result.iterations);
136
+
137
+ const points = new Float64Array([0, 0, 0, 0, 1, 0, 0, 2, 0]); // xyz per joint, the first one fixed
138
+ solveFABRIK(points, [1, 1, 0], { pole: [2, 0, 0], iterations: 32, tolerance: 1e-4 });
139
+ ```
140
+
141
+ Unreachable targets straighten the chain toward them (`reached` false, `distance` the gap). A straight chain starts bending toward the pole (or, with none, a fixed side).
142
+
143
+ `keepBend` (default `true`) keeps an elbow or knee that is already bent more than 2 degrees on the side it is bent to, so a pole on the far side cannot fold it backward: the joint goes to the nearest place on its own side instead, with both bone lengths kept. Pass `keepBend: false` to let the pole fold a joint either way. `addIKChain` takes the same option. Every solve also turns each bone about its own length so its bend axis follows the new bend, so an elbow or knee changes only by a rotation about one axis fixed in the upper bone, as a real hinge does, and the skin never shows a forearm swung sideways (Tolani, Goswami and Badler, *Real-time inverse kinematics techniques for anthropomorphic limbs*, 2000):
144
+
145
+ ```ts
146
+ import { solvePoseIK } from 'margoengine/rigging/ik';
147
+
148
+ const parents = [-1, 0, 1];
149
+ const local = new Float64Array([
150
+ 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
151
+ 0, -0.3, 0, -0.0998, 0, 0, 0.995, 1, 1, 1, // the forearm starts bent forward
152
+ 0, -0.28, 0, 0, 0, 0, 1, 1, 1, 1,
153
+ ]);
154
+ const result = solvePoseIK({ parents, local }, { joints: [0, 1, 2], target: [0, -0.5, 0], pole: [0, -0.3, 1] });
155
+ console.log(result.reached); // the elbow stays behind although the pole is in front
156
+ ```
157
+
158
+ **With `@margoengine/kinematics-constraints`.** `elbowEvaluator(upperLength, lowerLength, pole)` is the `ElbowEvaluator` an `AvoidanceSolver` needs: the elbow of a two-bone arm reaching from the shoulder to the target, turned `poleAngle` about the shoulder-target line from the pole's side. The solver then searches that angle for an elbow that clears the body's capsules and spheres:
159
+
160
+ ```ts
161
+ import { AvoidanceSolver, CapsuleVolume } from 'margoengine/kinematics-constraints';
162
+ import { elbowEvaluator } from 'margoengine/rigging/ik';
163
+
164
+ const torso = new CapsuleVolume({ start: [0, 0.9, 0], end: [0, 1.5, 0], radius: 0.18 });
165
+ const avoid = new AvoidanceSolver([torso], { minClearance: 0.01, targetRadius: 0.04 });
166
+ const evaluate = elbowEvaluator(0.3, 0.28, [0.2, 1.2, -0.5]); // upper arm, forearm, pole
167
+ const shoulder = new Float32Array([0.2, 1.4, 0]), hand = new Float32Array([0.5, 1.2, 0.2]);
168
+ const solved = avoid.solve(shoulder, hand, [-0.1, 1.2, 0.35], 0.3, 0.28, 0.05, 0.04, 1 / 60, evaluate);
169
+ console.log(solved.status, solved.elbow, solved.target);
170
+ ```
171
+
172
+ ### IK on a fitted body: limbs that obey anatomy
173
+
174
+ Give a pose, a `Skeleton` or an Animator its fitted body (`body` on the pose or the chain, or `setAnatomy(owner, body)` of `margoengine/animator/ik` once) and every IK solve on it obeys the body's joint ranges. This is on by default wherever a body is present.
175
+
176
+ - An arm or a leg (a shoulder or hip, a hinge, an end) is solved in closed form by its swivel angle (Tolani, Goswami and Badler 2000). The elbow or knee turns only about its own axis, the anatomical way, between straight and its stop, so a straight limb bends the right way and never folds backwards.
177
+ - The pole only picks the limb's swivel inside the shoulder's or hip's reach and twist. With no pole, a limb that is bent in the pose keeps its side, and a straight one takes the swivel that leaves the shoulder or hip nearest neutral: elbow down, knee forward, whatever pose the rig rests in.
178
+ - A longer chain is solved by FABRIK and each joint is held to the nearest rotation in its range, a trunk or neck the chain runs along as a whole too. A chain that ends in an arm or a leg finishes with the closed-form limb.
179
+ - A target the ranges do not allow is approached as far as they allow, and the result says `held`.
180
+ - An arm or leg stays out of the rest of the body: the swivel is the nearest to the wanted one that keeps the limb's two capsules (the table's measured girths, the same volumes `checkPose` tests) clear of the trunk, the other thigh and the shanks, as it keeps the shoulder or hip in range. An arm reaching across the chest lifts its elbow forward instead of dropping it into the belly.
181
+ - An arm ends with a relaxed hand: the forearm at its anatomical zero (HAnim's neutral, palm toward the thigh when the arm hangs) and the hand at the body's neutral, whatever turn the playing clip held. `hand: 'keep'` keeps the pose's forearm and hand.
182
+
183
+ ```ts
184
+ import type { RigJoint } from 'margoengine/rigging';
185
+ import { fitAnatomy, jointAngles } from 'margoengine/rigging/anatomy';
186
+ import { human } from 'margoengine/rigging/anatomy/human';
187
+ import { type IKPose, solvePoseIK } from 'margoengine/rigging/ik';
188
+
189
+ const rig: RigJoint[] = [
190
+ { name: 'Hips', parent: -1, position: [0, 1, 0] },
191
+ { name: 'Spine', parent: 0, position: [0, 1.1, 0] },
192
+ { name: 'Head', parent: 1, position: [0, 1.6, 0] },
193
+ { name: 'LeftUpLeg', parent: 0, position: [0.1, 0.95, 0] },
194
+ { name: 'RightUpLeg', parent: 0, position: [-0.1, 0.95, 0] },
195
+ { name: 'LeftArm', parent: 1, position: [0.2, 1.45, 0] },
196
+ { name: 'LeftForeArm', parent: 5, position: [0.48, 1.45, 0] },
197
+ { name: 'LeftHand', parent: 6, position: [0.74, 1.45, 0] },
198
+ ];
199
+ const body = fitAnatomy(rig, { species: human });
200
+ // The left hand to a point in front of the chest. The pole sits above and behind the shoulder, where no elbow can
201
+ // point: the elbow goes as far that way as the shoulder allows and still bends forward.
202
+ const pose: IKPose = { parents: body.parents, local: body.rest.slice(), body };
203
+ const result = solvePoseIK(pose, { joints: [5, 6, 7], target: [0.25, 1.3, 0.35], pole: [0.2, 3, -3] });
204
+ console.log(result.reached, jointAngles(body, pose.local).l_elbow.flexion > 0); // true true
205
+ ```
206
+
207
+ | Option | Default | What it does |
208
+ |---|---|---|
209
+ | `body` (chain or pose) | the body `setAnatomy` gave the pose, `Skeleton` or Animator, else none | The fitted body the chain obeys. |
210
+ | `limits` | `true` | `false` solves as if there were no body: FABRIK and the pole alone. |
211
+ | `soft` | `0` | Share of an arm's or leg's length (0 to 0.5) over which the reach eases in before full stretch, so an elbow or knee does not snap straight. At 0 the end meets every target in reach exactly. |
212
+ | `hand` | `'natural'` | On an arm: `natural` turns the forearm to its anatomical zero and leaves the hand at the body's neutral; `keep` keeps the pose's forearm twist and hand. |
213
+
214
+ `solvePoseIK`, `solveSkeletonIK` and `addIKChain` take these; `solveContactIK` takes `body` and reads its ranges as the default for `limits` (pass `body: null`, or your own `limits`, to leave the body out). `setAnatomy` and `anatomyOf` come from `margoengine/animator/ik`, which owns them with the limb solver `solveLimbIK`. Proof: `packages/rigging/tests/ik-anatomy.test.js` (10,000 reaches all around the body for an arm and for a leg, on T, A and arms-down rigs, rolled and mirrored: no hinge reversed, no joint past its stop), `ik-anatomy-animator.test.js`, `ik-reach-across.test.js` (an arm across the chest stays out of the trunk with its palm not up; without the volumes the same reach passes through it), the reach sheet `ik-reach-sheet.browser.mjs` (front, three-quarter and side, with the free solve beside it) and `ik-blender-check.mjs`, which has Blender's own bones and IK solver agree on which way flexion turns and on every hinge angle.
215
+
216
+ Two fits a Character Creator or Unreal body needs are read from the rig itself. The wrist's roll comes from the knuckle line of the index and middle fingers first (they are the fixed part of the hand's arch; the ring and little metacarpals move, Kapandji, *The Physiology of the Joints*, vol. 1), so a cupped hand at rest does not read as a twisted wrist. A forearm twist bone (a bone hanging under the forearm along it, as `CC_Base_L_ForearmTwist01` does) means the rig turns the hand itself for pronation and spreads the turn along the skin: the wrist's twist range then takes the forearm's pronation as well, and nothing spills into the forearm bone, which would twist the skin a second time.
217
+
218
+ Root motion and look-at / aim constraints live with the Animator: `addRootMotion`, `addLookAt` and `addAimConstraint` in [`@margoengine/animator`](../animator/README.md).
219
+
220
+ ## Hand and foot contacts (`margoengine/rigging/contact`)
221
+
222
+ `solveContactIK` puts the point on the hand, shoe or hoof that actually touches the surface at a chosen position and orientation. The chain runs through the wrist, ankle or hoof. `anchor` is the palm, sole or other landmark in the final joint's own coordinates. Read `locked` before applying a grip pose or firing a contact sound. The solve measures the actual landmark after posing and returns its position, angular error and remaining gap. Approaching with `weight` below 1 blends the landmark and wrist toward the contact. A pole selects the bend side. Calibrate each limited joint's neutral rotation and axes from the rig. A hinge gives an elbow, knee or hock one bounded axis. A cone limits wrist or ball-joint swing and signed twist independently. Per-axis limits suit a joint with separate rotation controls.
223
+
224
+ ```ts
225
+ import { solveContactIK } from 'margoengine/rigging/contact';
226
+
227
+ const parents = [-1, 0, 1];
228
+ const local = new Float64Array([
229
+ 0, 0, 0, 0, 0, 0, 1, 1, 1, 1,
230
+ 0.3, 0, 0, 0, 0, 0, 1, 1, 1, 1,
231
+ 0.26, 0, 0, 0, 0, 0, 1, 1, 1, 1,
232
+ ]);
233
+ const contact = solveContactIK({ parents, local }, {
234
+ joints: [0, 1, 2],
235
+ point: [0.46, 0.16 * Math.sqrt(3), 0],
236
+ rotation: [0, 0, 0.5, Math.sqrt(3) / 2],
237
+ anchor: [0.06, 0, 0],
238
+ pole: [0.3, 0, 0],
239
+ reach: 'hinged',
240
+ limits: [
241
+ { joint: 1, neutral: [0, 0, 0, 1], limit: { type: 'hinge', axis: [0, 0, 1], min: 0, max: 2.35 } },
242
+ { joint: 2, neutral: [0, 0, 0, 1], limit: { type: 'cone', axis: [1, 0, 0], angle: 0.85, twist: [-0.35, 0.35] } },
243
+ ],
244
+ tolerance: 0.002,
245
+ });
246
+ console.log(contact.locked, contact.distance);
247
+ ```
248
+
249
+ Pose and contact points use skeleton space and the same units. Ancestor scales must be uniform and positive. The end joint can have different positive scales along its axes. Default tolerances are 0.0001 scene units and 0.02 radians. Each solve uses up to 64 CCD sweeps by default. The chain can contain 2–256 joints inside a larger rig. `checkRig` accepts up to 65,536 joints, the number of joint indices representable by glTF unsigned shorts. A weight of 0 measures the input pose exactly. A gap or orientation outside either tolerance leaves `locked` false. Start from the sampled animation pose each frame so corrections cannot accumulate.
250
+
251
+ Use `reach: 'hinged'` with an explicit pole to keep the elbow or knee on one authored bend plane across samples.
252
+ The final three joints form the two links and the penultimate joint needs a hinge whose axis is perpendicular to
253
+ both links in its neutral pose. An optional hinge twist axis follows the lower link. Earlier joints carry the reach
254
+ and retain their sampled pose within their limits. Animate the pole smoothly off the reach axis. Unreachable goals
255
+ clamp to the calibrated reach, and a collision rejects the sample without choosing a different bend plane.
256
+ `PalmContactRig` accepts the same option on a target with calibrated elbow and `elbowPole`.
257
+
258
+ The contact landmark follows [*Footskate Cleanup for Motion Capture Editing*, Kovar, Gleicher and Schreiner (2002)](https://research.cs.wisc.edu/graphics/Papers/Gleicher/Mocap/cleanup.pdf). The chain solve uses the Animator's constrained CCD solver. [*Parametrization and Range of Motion of the Ball-and-Socket Joint*, Baerlocher and Boulic (2000)](https://infoscience.epfl.ch/bitstreams/949101d1-ec81-4e38-91d8-c414ee95c8fc/download) describes swing and twist boundaries. Position error is at the surface landmark because the joint origin and the surface point differ, as in the hand and foot annotations of [*CIMI4D*, Yan et al. (2023)](https://openaccess.thecvf.com/content/CVPR2023/papers/Yan_CIMI4D_A_Large_Multimodal_Climbing_Motion_Dataset_Under_Human-Scene_Interactions_CVPR_2023_paper.pdf).
259
+
260
+ ### Human palm and cylindrical grips
261
+
262
+ `PalmContactRig` measures the palm and digits from the rig's bind pose, aligns a palm pad to a contact point and its
263
+ surface normal, and closes the fingers in proportion to the actual contact. Arm reach and finger closure are separate
264
+ inputs. While a reach is active, the contact layer owns the digits, including any earlier keyed grip. Closure eases to
265
+ zero when the palm is farther away or more misaligned than its tolerance. A reversed palm cannot engage the grip.
266
+ `addPalmContact` evaluates this same solve after the Animator's pose and earlier solvers.
267
+
268
+ ```ts
269
+ import type { Animator } from 'margoengine/animator';
270
+ import { addPalmContact, type PalmContactTarget } from 'margoengine/rigging/contact';
271
+
272
+ export function attachRailGrip(animator: Animator, upperArm: number, elbow: number, wrist: number) {
273
+ let target: PalmContactTarget | undefined;
274
+ const dispose = addPalmContact(animator, {
275
+ side: 'right',
276
+ preset: 'mixamo',
277
+ joints: [upperArm, elbow, wrist],
278
+ elbow: { joint: elbow, flexDirection: [0, 0, 1] },
279
+ }, () => target);
280
+ return {
281
+ reach(point: PalmContactTarget['point']) {
282
+ target = { point, normal: [0, 0, 1], towardsFingers: [0, 1, 0], diameter: 0.035 };
283
+ },
284
+ release() { target = undefined; },
285
+ dispose,
286
+ };
287
+ }
288
+ ```
289
+
290
+ Use node indices from the avatar and directions in its skeleton space. Supply a custom humanoid `bones` map for
291
+ an unfamiliar naming scheme. For offline posing, construct `new PalmContactRig(rig, calibration)` and call
292
+ `solve(sampledLocal, target)` once per sample. Both routes report the achieved position, distance, angle, contact
293
+ state and `gripWeight`. Resolve moving holds into model space at the sample time. Supply `close` to animate
294
+ release and `weight` to blend the reach. Return `undefined` to give control to the underlying animation.
295
+
296
+ Default registration tolerances are 3 mm on metre-scale rigs and 5 degrees. With elbow calibration, the forearm
297
+ bends about its measured flexion axis, defaults to −0.035 to 2.55 radians relative to bind and rolls ±1.25 radians
298
+ about its length. Use `roll: false` for a separately authored twist joint. The measured wrist defaults to 1.15
299
+ radians of swing and ±0.22 radians of axial twist. Use `limits` to set per-character bounds and `anchor` for a
300
+ measured palm-pad point in wrist-local coordinates. The default anchor starts at 56% of the wrist-to-middle-knuckle
301
+ distance. A forward thumb base can move it up to 88% to keep the bar away from the thumb web. The outward pad offset
302
+ is 8.5% of palm length. Cylindrical poses use the measured digit lengths and a diameter
303
+ above 0 and below 1 m. The solver measures palm registration, and per-digit skin collision requires its own
304
+ geometry and verification.
305
+
306
+ The grip model draws on [*The Computer Animation of Human Hand Grasping*, Rijpkema and Girard (1991)](https://doi.org/10.1145/127719.127748)
307
+ and [*Handrix*, ElKoura and Singh (2003)](https://doi.org/10.2312/SCA03/110-119).
308
+ The wrist also checks the angle between the forearm and the measured palm frame, with defaults of 1.12 radians
309
+ of flexion, 1.0 of extension, and 0.46 of sideways deviation. Calibrate these through `wrist` for the character
310
+ and action. A compatible custom constraint can take over this check with `wrist: false`. The cylindrical fit
311
+ uses the same diameter as the palm target. It chooses a pose for each digit from its measured lengths, fits the
312
+ thumb on the opposing side, and checks for proxy intersections from the open approach through six stages of
313
+ closure. The anchor's clearance from the thumb base leaves room to oppose and curl the thumb together.
314
+ A second search tests coupled thumb flexion along the same bar when a base turn alone leaves the joints rigid.
315
+ A hand with very short
316
+ digits or an oversized bar can still have a gap. Check the final deformed skin against the production geometry.
317
+
318
+ The independent forearm and wrist controls follow the distinct axes described in
319
+ [*From Skin to Skeleton*, Keller et al. (2023)](https://doi.org/10.1145/3618381) and
320
+ [*In Vivo Analysis of the Mechanical Axes of the Wrist During Dynamic Motion*, Crisco et al. (2011)](https://pmc.ncbi.nlm.nih.gov/articles/PMC3016043/).
321
+ The functional ranges measured by [Ryu, Cooney, Askew, An and Chao (1991)](https://pubmed.ncbi.nlm.nih.gov/1861019/)
322
+ guide the additional pose check. The opposing thumb follows the grip observations in
323
+ [*The GRASP Taxonomy of Human Grasp Types*, Feix et al. (2016)](https://www.eng.yale.edu/grablab/pubs/Feix_THMS2016.pdf)
324
+ and [*In Vivo Kinematics of the Thumb Carpometacarpal Joint During Three Isometric Functional Tasks*, Halilaj et al. (2014)](https://pmc.ncbi.nlm.nih.gov/articles/PMC3940759/).
325
+ These are rig-space defaults that can be calibrated to the actor's proportions, bind orientation and authored controls.
326
+
327
+ ### Character self-collision during contact
328
+
329
+ `LimbCollisionRig` attaches capsules and spheres to a human or animal skeleton. Configure a chain of limb links,
330
+ the body volumes it can hit, and optional joint directions relative to bones such as the chest or pelvis. Capsule
331
+ radii are in skeleton units. Measure them with clothing or fur included, then trim shared segments at the shoulder
332
+ or hip to allow the intended attachment. The same API works for a quadruped foreleg, a wing, or a tail when given
333
+ the corresponding landmarks and joint slots.
334
+
335
+ ```ts
336
+ import { LimbCollisionRig, type PalmContactTarget } from 'margoengine/rigging/contact';
337
+
338
+ export function guardReach(parents: readonly number[], lowerSpine: number, chest: number) {
339
+ const guard = new LimbCollisionRig(parents, [
340
+ { start: { joint: lowerSpine }, end: { joint: chest }, radius: 0.12 },
341
+ ], [
342
+ { start: 0, end: 1, radius: 0.04, range: [0.35, 1] },
343
+ { start: 1, end: 2, radius: 0.035 },
344
+ ], [
345
+ { start: 0, end: 1, reference: chest, forward: [0, 0, 1] },
346
+ ]);
347
+ return (local: Float64Array, target: PalmContactTarget): PalmContactTarget => {
348
+ guard.setBodyPose(local);
349
+ return { ...target, clearance: guard.clearance };
350
+ };
351
+ }
352
+ ```
353
+
354
+ Pass the resulting target to `PalmContactRig.solve` with the same three chain slots ordered shoulder, elbow and
355
+ wrist. `solveContactIK` also accepts the clearance callback. Negative values reject the candidate. The solver
356
+ tries alternate elbow directions when the preferred pose is blocked, and leaves the input arm pose in place if it
357
+ finds no clear solution. Check `blocked` and choose a reachable hold or a safe fallback pose. The result's `clearance`
358
+ combines proxy separation and the margin to the configured joint directions and wrist range.
359
+
360
+ Use `snapshot` for the accepted limb at two consecutive poses and `sweep` to test the intervening proxy motion
361
+ and direction limits. Capsule endpoints and the vectors between the configured limb joints are linearly
362
+ interpolated. Each reference axis follows a short spherical arc as the torso turns. Include intermediate poses for curved joint motion or opposite reference
363
+ axes. A sweep that cannot certify clearance returns `clear: false` and `exhausted: true`. Legacy snapshots without
364
+ the direction channel still check capsule motion. Use the same snapshot format at both ends.
365
+
366
+ ```ts
367
+ import { LimbCollisionRig } from 'margoengine/rigging/contact';
368
+
369
+ export function checkShoulderTravel(before: number[], after: number[]) {
370
+ const guard = new LimbCollisionRig(
371
+ [-1],
372
+ [{ start: { joint: 0 }, radius: 0.16 }],
373
+ [{ start: 0, end: 1, radius: 0.04 }],
374
+ [{ start: 0, end: 1, reference: 0, forward: [0, 0, 1] }],
375
+ );
376
+ guard.setBodyPose([0, 0, 0, 0, 0, 0, 1, 1, 1, 1]);
377
+ return guard.sweep(guard.snapshot(before), guard.snapshot(after));
378
+ }
379
+ ```
380
+
381
+ The alternate elbow search draws on [*Real-Time Inverse Kinematics Techniques for Anthropomorphic Limbs*, Tolani,
382
+ Goswami and Badler (2000)](https://www.ambarish.com/paper/Tolani_Goswami_Badler_IK.pdf) and [*Analytical Inverse
383
+ Kinematics with Body Posture Control*, Kallmann (2008)](https://mkallmann.github.io/papers/08-cavw-bodyik.pdf).
384
+ The explicit-pole mode uses the analytical elbow circle described by Tolani, Goswami and Badler. Keeping the bend
385
+ plane on a continuous authored curve follows the use of smooth pose corrections in [*A Hierarchical Approach to
386
+ Interactive Motion Editing for Human-like Figures*, Jehee Lee and Sung Yong Shin (1999)](https://doi.org/10.1145/311535.311539).
387
+ Capsule gaps use the segment-distance construction in [*On Fast Computation of Distance Between Line Segments*,
388
+ Lumelsky (1985)](https://doi.org/10.1016/0020-0190(85)90032-8). The continuous check adapts conservative advancement
389
+ to straight proxy paths, following [*Fast Continuous Collision Detection for Articulated Models*, Redon, Lin and
390
+ Manocha (2004)](https://diglib.eg.org/items/13aac165-e652-4c78-a0a6-0b42305f0753).
391
+ The direction limit uses a body-relative axis, as in [*Parametrization and Range of Motion of the Ball-and-Socket
392
+ Joint*, Paolo Baerlocher and Ronan Boulic (2000)](https://infoscience.epfl.ch/bitstreams/949101d1-ec81-4e38-91d8-c414ee95c8fc/download).
393
+ The sweep uses the angular speed of that axis and the linear speed of the limb vector
394
+ to bound gap changes. See [*Animating Rotation with Quaternion Curves*, Ken Shoemake (1985)](https://doi.org/10.1145/325334.325242)
395
+ for spherical interpolation and [*Continuous Collision Detection for Articulated Models Using Taylor Models
396
+ and Temporal Culling*, Zhang, Redon, Lee and Kim (2007)](https://doi.org/10.1145/1239451.1239466) for
397
+ angular motion bounds in conservative advancement.
398
+
399
+ ## Joint hulls (`margoengine/rigging/hulls`)
400
+
401
+ `jointHulls(model, options)` finds the convex hull of the vertices each joint carries, from a skinned mesh in its bind pose. A hull is a short list of corners, so a clearance or collision test can use the real shape of a torso, head or forearm instead of a sphere or capsule. Run it once at load. It uses `@margoengine/geometry`'s quickhull, and only this entry imports it.
402
+
403
+ ```ts
404
+ import { jointHulls } from 'margoengine/rigging/hulls';
405
+
406
+ // A column of four rings of box corners; the lower two rings follow joint 0, the upper two follow joint 1.
407
+ const positions: number[] = [];
408
+ const joints: number[] = [];
409
+ for (let ring = 0; ring < 4; ring++)
410
+ for (const x of [-0.5, 0.5])
411
+ for (const z of [-0.5, 0.5]) {
412
+ positions.push(x, ring, z);
413
+ joints.push(ring < 2 ? 0 : 1);
414
+ }
415
+ const skin = { joints: Uint16Array.from(joints), weights: new Float32Array(joints.length).fill(1), influences: 1 };
416
+
417
+ // Joint 1 sits at y = 2 in the bind pose; its inverse bind matrix (glTF column-major) moves the world down by 2.
418
+ const translateDown = (y: number) => [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, -y, 0, 1];
419
+ const inverseBindMatrices = [...translateDown(0), ...translateDown(2)];
420
+ for (const hull of jointHulls({ positions, skin }, { inverseBindMatrices }))
421
+ console.log(hull.joint, hull.vertexCount, hull.points.length / 3); // 0 8 8, then 1 8 8
422
+ ```
423
+
424
+ | Option | Default | Meaning |
425
+ | --- | --- | --- |
426
+ | `minWeight` | `0.5` | A vertex counts toward a joint when the joint carries at least this much of it (0 to 1). The default gives each vertex to its main joint, so neighbouring hulls meet without overlapping; lower it so blended vertices (an elbow) reach into both. |
427
+ | `maxPoints` | `64` | Most corners a hull keeps (8-1,024). Larger hulls keep the corners that reach farthest in directions spread over the sphere; every kept point is still a corner of the full hull, so the reduced hull lies inside it. |
428
+ | `inverseBindMatrices` | none | 16 numbers per joint. With them each hull is in its joint's own space, so the joint's world matrix places it; without them the corners stay in mesh space. |
429
+
430
+ The model is `{positions, skin}`: bind-pose `positions` (xyz per vertex) and `skin` as a `WeightMap` or per-vertex influences (`{joints, weights, influences?}`). A joint repeated in several slots of one vertex counts its weights together. Joints that own fewer than four vertices, or whose vertices lie on a line or plane, have no hull and are left out of the result. Positions or weights that are not finite, a skin whose vertex count differs from the positions, and a joint with no inverse bind matrix throw a `RangeError` that names the fix.
431
+
432
+ ## Spring bones and jiggle (`margoengine/rigging/springs`)
433
+
434
+ Secondary motion for hair, tails, cloth strips and accessories with no physics world: `addSpringBones(animator, options)` swings chains of bones after the frame's animation, against sphere and capsule colliders. The settings mean what `VRMC_springBone` 1.0's mean, so a VRM's values work as authored. Tails follow the animated pose, so a clip keeps its say and the chain settles back on it. The step is corrected for time: the same character swings the same at 30, 60 or 144 frames a second.
435
+
436
+ ```ts
437
+ import { SpringBones } from 'margoengine/rigging/springs';
438
+
439
+ // Plain data: a bone at the top and a rope of two bones hanging from it.
440
+ const parents = [-1, 0, 1];
441
+ const bone = (y: number) => [0, y, 0, 0, 0, 0, 1, 1, 1, 1];
442
+ const springs = new SpringBones(parents, {
443
+ chains: [{ joints: [0, 1, 2], stiffness: 1, drag: 0.4, gravity: 0.5, radius: 0.02 }],
444
+ colliders: [{ offset: [0.4, -1, 0], radius: 0.25 }],
445
+ });
446
+ for (let frame = 0; frame < 60; frame++) {
447
+ const local = Float64Array.from([...bone(0), ...bone(-1), ...bone(-1)]); // this frame's animated pose
448
+ local[0] = frame * 0.02;
449
+ springs.stepPose({ parents, local }, 1 / 60); // rotations swing in place
450
+ }
451
+ ```
452
+
453
+ On a character, joints and collider nodes are glTF node indices; find them by name:
454
+
455
+ ```ts
456
+ import {Engine} from 'margoengine/core';
457
+ import {loadGLTF} from 'margoengine/gltf/pbr';
458
+ import {Animation} from 'margoengine/animation';
459
+ import {Animator} from 'margoengine/animator';
460
+ import { detectSkeleton, humanoidBones } from 'margoengine/rigging/retarget';
461
+ import { addSpringBones } from 'margoengine/rigging/springs';
462
+ const engine = await Engine.create(document.querySelector('canvas')!);
463
+ const model = await loadGLTF(engine, '/character.glb');
464
+ const animator = Animator.attach(Animation.attach(model), {initial: 'walk', states: {walk: 'Walk'}});
465
+ const names = model.asset.doc.nodes!.map((n) => n.name ?? '');
466
+ const bone = humanoidBones(names, detectSkeleton(names)?.preset ?? 'humanoid'); // head, chest and the rest
467
+ const node = (name: string) => names.indexOf(name); // the model's own extra bones
468
+ const head = bone.get('head')!;
469
+ const hair = addSpringBones(animator, {
470
+ chains: [
471
+ { joints: [node('Hair1'), node('Hair2'), node('Hair3')], stiffness: 1.5, drag: 0.4, gravity: 0.3, center: head }, // measured against the head
472
+ { joints: [node('LeftEarring')], tail: [0, -0.06, 0], stiffness: 0.8 }, // an earring: one joint and an end point
473
+ ],
474
+ colliders: [{ node: head, radius: 0.09 }, { node: bone.get('upperChest')!, tail: [0, 0.3, 0], radius: 0.12 }],
475
+ jiggles: [{ joint: node('Belly'), frequency: 3, damping: 0.3, limit: 0.03 }], // lags and wobbles in place
476
+ });
477
+ hair.reset(); // after moving the character by hand
478
+ hair[Symbol.dispose]();
479
+ ```
480
+
481
+ `options` is kept and read every frame, so settings change live. `SpringBones` runs without an engine: `stepPose` for plain data, `stepSkeleton` for a `Skeleton` from `@margoengine/animation`, `step` for your own bones.
482
+
483
+ | Chain field | Default | Meaning |
484
+ | --- | --- | --- |
485
+ | `joints` | required | Bones root to tip, each an ancestor of the next (up to 256). Bones left out ride along. The last is only a tail and does not turn, unless `tail` is set. A joint belongs to one chain. |
486
+ | `stiffness` | `1` | Pull back toward the animated direction, 0 or more. |
487
+ | `drag` | `0.5` | Share of the speed lost each 1/60 s, 0 to 1. |
488
+ | `gravity` | `0` | Strength of gravity on the tail. |
489
+ | `gravityDirection` | `[0, -1, 0]` | World direction of gravity. |
490
+ | `radius` | `0` | Size of the tail against colliders. |
491
+ | `settings` | none | Any of the five above per joint, by position in `joints`. |
492
+ | `tail` | none | End point past the last joint, in its local space, so that joint turns too. |
493
+ | `center` | none | `joints[0]` or an ancestor: motion of this bone does not swing the chain. Gravity stays in world space. |
494
+ | `colliders` | all | Indices into `options.colliders` this chain hits. |
495
+
496
+ | Option | Default | Meaning |
497
+ | --- | --- | --- |
498
+ | `chains`, `colliders`, `jiggles` | none | What to simulate. A collider is `{node, offset, tail, radius}`: a sphere, or a capsule when `tail` is set; with no `node` its points are world points. |
499
+ | `force` | none | Extra world force on every tail, such as wind, in `gravity` units. |
500
+ | `weight` | `1` | Blend from the animated pose (0) to the simulated one (1). |
501
+ | `teleportSpeed` | `100` | World speed in units a second above which a chain restarts from the animated pose instead of whipping across the gap. |
502
+
503
+ | Jiggle field | Default | Meaning |
504
+ | --- | --- | --- |
505
+ | `joint` | required | The bone. Its position trails the animated one on a damped spring, solved exactly each step (stable at any frequency and damping); steady motion leaves no lag. |
506
+ | `frequency` | `4` | Wobbles a second, up to 15. |
507
+ | `damping` | `0.35` | Share of critical damping: 1 stops without a wobble. |
508
+ | `limit` | `0.05` | Farthest the bone strays from its animated position. |
509
+ | `amount` | `1` | Share of the movement shown. |
510
+
511
+ A model scaled up swings the same, only larger: forces, `radius`, collider radii and `limit` follow the bones' world scale. Joints and their ancestors need positive scales; a scale a little off uniform, as exported rigs often have, reads as its mean. A `delta` of 0 holds the motion, and a long frame takes at most 8 steps of 1/60 s, so a stall slows the swing and cannot blow it up. Spring bones run after other solvers in the order they were added.
512
+
513
+ ## VRM avatars (`margoengine/rigging/vrm`)
514
+
515
+ VRM 1.0 avatars from any tool that writes them. `readVRM` takes a `.vrm` file's bytes and gives the avatar's data; `addVRM` puts it to work on the model: the 18 preset expressions and any custom ones, the look-at, the spring bones and a mouth and blink channel for your own lip sync. `writeVRM` puts an avatar back into a `.vrm`, and `createVRM` makes one from any rigged glTF.
516
+
517
+ ```ts
518
+ import { loadGLTF } from 'margoengine/gltf/pbr';
519
+ import { Animation } from 'margoengine/animation';
520
+ import { addVRM, readVRM } from 'margoengine/rigging/vrm';
521
+ import {Engine} from 'margoengine/core';
522
+ const engine = await Engine.create(document.querySelector('canvas')!);
523
+ const url = 'Seed-san.vrm';
524
+ const avatar = readVRM(new Uint8Array(await (await fetch(url)).arrayBuffer()));
525
+ console.log(avatar.meta.name, avatar.meta.authors, avatar.meta.commercialUsage); // what its author allows
526
+
527
+ const model = await loadGLTF(engine, url); // a .vrm is a binary glTF
528
+ const animation = new Animation(model);
529
+ const vrm = addVRM(animation, avatar);
530
+ vrm.expressions.set('happy', 1); // 0 to 1, shown from the next frame
531
+ vrm.lookAtTarget = [0, 1.5, 2]; // the eyes follow this world point
532
+ console.log(vrm.unsupported); // MToon-only colour binds, shown only with MToon (below)
533
+ vrm[Symbol.dispose](); // back to neutral
534
+ ```
535
+
536
+ Read `avatar.meta` before you use someone's avatar: it is the author's own statement of what may be done with it (`avatarPermission`, `commercialUsage`, `allowRedistribution` and the rest), and the licence named in `licenseUrl` applies. Margo reads it and keeps it; it enforces nothing.
537
+
538
+ Pass an `Animator` from `margoengine/animator` as `animator` and the avatar runs inside its frame, after your clips, in the order the specification recommends: look-at, expressions, then spring bones. With none, it runs by itself as an engine plugin. `update(delta)` runs one frame by hand. Dispose the avatar before its `Animation`; disposing the model stops the avatar by itself.
539
+
540
+ ```ts
541
+ import { splitGLB } from 'margoengine/exporters';
542
+ import { detectSkeleton, humanoidBones } from 'margoengine/rigging/retarget';
543
+ import { createVRM, readVRM, writeVRM } from 'margoengine/rigging/vrm';
544
+ const rigged = new Uint8Array(await (await fetch('/rigged.glb')).arrayBuffer()); // any .glb with a skin
545
+ const { json } = splitGLB(rigged);
546
+ const nodes = json.nodes as { name?: string; mesh?: number }[],
547
+ meshes = json.meshes as { extras?: { targetNames?: string[] } }[];
548
+ const names = nodes.map((n) => n.name ?? '');
549
+ const face = names.indexOf('Face'); // the node of the mesh with the face shapes
550
+ const blink = meshes[nodes[face].mesh!].extras?.targetNames?.indexOf('eyeBlinkLeft') ?? -1;
551
+ const out = writeVRM(
552
+ rigged,
553
+ createVRM({
554
+ name: 'Scout',
555
+ authors: ['Sam'],
556
+ bones: humanoidBones(names, detectSkeleton(names)?.preset ?? 'humanoid'), // every humanoid bone the names give
557
+ expressions: { preset: { blink: { morphTargetBinds: [{ node: face, index: blink, weight: 1 }] } } },
558
+ }),
559
+ ); // a .vrm
560
+ console.log(readVRM(out).humanoid.humanBones.head?.node === names.indexOf('mixamorig:Head')); // true for a Mixamo rig
561
+ ```
562
+
563
+ | Name | Meaning |
564
+ | --- | --- |
565
+ | `readVRM(bytes or doc)` | The avatar: `meta`, `humanoid`, `expressions`, `lookAt`, `firstPerson`, `springBone`, as the file's own JSON, so nothing is lost. Refuses VRM 0.x and a file with no `VRMC_vrm`. |
566
+ | `checkVRM(avatar, doc)` | Problems as strings: a missing required bone, a node or morph index out of range. Empty when sound. |
567
+ | `writeVRM(glb, avatar)` | A new `.vrm`: the glTF's own bytes and extensions kept, with the avatar in place of any earlier one. |
568
+ | `createVRM(options)` | An avatar from a bone map; `licenseUrl` defaults to VRM Public License 1.0, `lookAt`, `expressions` and `springBone` are optional. |
569
+ | `vrmSprings(avatar)` | The file's spring bones as `addSpringBones` options. |
570
+ | `VRMExpressions` | The expression rules with no engine: `set`, `get`, `resolve`, `evaluate`, `names`; `isBinary` and the `override*` blocks act as the specification says. |
571
+ | `vrmGaze`, `vrmEyeAngles`, `vrmLookWeights` | The look-at maths: yaw and pitch from the head to a point, then bone angles or expression weights through the file's range maps. |
572
+
573
+ | `addVRM` option | Default | Meaning |
574
+ | --- | --- | --- |
575
+ | `animator` | none | Run inside this `Animator`; with none, run as an engine plugin. |
576
+ | `springs` | `true` | Run the file's spring bones. |
577
+ | `mouth`, `blink`, `lookAt` | none | Custom expression names that an expression's `overrideMouth`, `overrideBlink` or `overrideLookAt` also holds back, beside the presets the specification names. |
578
+
579
+ Expressions drive morph targets, `color` and `emissionColor` of materials, and texture moves. The other colour binds exist only in MToon and land in `unsupported`, because without `MToon` (below) Margo draws MToon materials by their plain glTF fallback: no toon shading or outlines. `VRMC_node_constraint` data stays in the file through `writeVRM` and does not run.
580
+
581
+ With `MToon` from `@margoengine/rigging/mtoon` attached, MToon UV animation is computed in float64 and sent as small phases, so a scrolling or turning texture keeps its 1/60 s steps after days of running; [details and limits](../../docs/rigging-mtoon.md).
582
+
583
+ ## Toon shading (`margoengine/rigging/mtoon`)
584
+
585
+ `MToon.attach(model, { expressions })` draws a loaded model's `VRMC_materials_mtoon` materials (and the VRM 0.x
586
+ records kept by `loadVRM0`) with MToon's lit and shade colours, rim, matcap, outlines and UV animation, on native
587
+ WebGPU and on the WebGL2 compatibility layer. Pass the `expressions` of `addVRM` so expression binds to `shadeColor`,
588
+ `rimColor`, `matcapColor` and `outlineColor` take effect; these are the binds `addVRM` lists in `unsupported` when no
589
+ MToon is attached. The defaults and ranges of every control are in [docs/rigging-mtoon.md](../../docs/rigging-mtoon.md).
590
+
591
+ ```ts
592
+ import { Engine } from 'margoengine/core';
593
+ import { loadGLTF } from 'margoengine/gltf/pbr';
594
+ import { Animation } from 'margoengine/animation';
595
+ import { addVRM, readVRM } from 'margoengine/rigging/vrm';
596
+ import { MToon } from 'margoengine/rigging/mtoon';
597
+
598
+ const engine = await Engine.create(document.querySelector('canvas')!);
599
+ const url = 'Seed-san.vrm';
600
+ const model = await loadGLTF(engine, url);
601
+ const vrm = addVRM(new Animation(model), readVRM(new Uint8Array(await (await fetch(url)).arrayBuffer())));
602
+ using toon = MToon.attach(model, { expressions: vrm.expressions });
603
+ console.log(toon.materials.size > 0); // true: one definition per MToon material, keyed by glTF material index
604
+ engine.render({ delta: 1 / 60 });
605
+ // Leaving scope (or toon.dispose()) puts every original material record back on the model.
606
+ ```
607
+
608
+ - A model may mix MToon with ordinary glTF PBR and unlit materials, as VRM allows. Those primitives keep drawing with
609
+ their own material in their own opaque, MASK or BLEND queue while the MToon body and outline layers run, and each
610
+ primitive is drawn once.
611
+ - Within a model, opaque, MASK, depth-writing blend and plain blend groups draw in authored order, and primitives in
612
+ the same transparent queue keep the engine's distance sort. `renderQueueOffsetNumber` (-9 to 9) orders blended
613
+ MToon queues and is ignored on OPAQUE and MASK, as the specification says; VRM 0.x explicit queues (0 to 5000, -1
614
+ for the mode's default) are kept as authored. Queues order primitives inside one model, never across models.
615
+ - The material records are swapped only while each queue draws and restored synchronously after it, so code that
616
+ reads `primitive.material` between frames sees the model's own records. `dispose()`, `Symbol.dispose` or disposing
617
+ the model restores them exactly; `toon.disposed` reports it.
618
+ - The model stays yours; attach on the engine that loaded it. Importing the entry registers nothing.
619
+ - `toon.advanceTime(delta)` moves the UV animation clock (`toon.time`, in seconds), which the frame update also runs.
620
+
621
+ ## VRM first person (`margoengine/rigging/vrm-first-person`)
622
+
623
+ A VRM 1.0 file says which meshes the wearer sees through their own eyes (`firstPerson.meshAnnotations`): `thirdPersonOnly` meshes (the head, the hair) stay out of the first-person view, `firstPersonOnly` meshes appear only in it, `both` show everywhere, and `auto` (also a mesh with no annotation) means "cut the head off for me". `loadVRM` makes that cut before the model loads: each `auto` skinned mesh is split into the triangles weighted to the head bone or a bone below it, drawn in third person only, and the rest. `addVRMFirstPerson` then puts each mesh on a render layer and gives you the two view masks, so every camera, mirror, probe and XR eye filters the avatar the way the file asks.
624
+
625
+ ```ts
626
+ import { Engine } from 'margoengine/core';
627
+ import { Reflector } from 'margoengine/environment/reflector';
628
+ import { addVRMFirstPerson, loadVRM } from 'margoengine/rigging/vrm-first-person';
629
+ const engine = await Engine.create(document.querySelector('canvas')!);
630
+ const model = await loadVRM(engine, 'Seed-san.vrm'); // `auto` meshes come back split into head and body
631
+ const fp = addVRMFirstPerson(model, { firstPersonCameras: [engine.camera] }); // this camera looks through the eyes
632
+ engine.render({ delta: 0 }); // world matrices, so viewpoint() reads the posed head
633
+ const eye = fp.viewpoint();
634
+ engine.camera.position = eye;
635
+ engine.camera.target = [eye[0], eye[1], eye[2] + 1]; // a VRM 1.0 avatar faces +Z
636
+ const mirror = Reflector.attach(engine, { width: 2, height: 2, layers: fp.thirdPersonLayers }); // the mirror shows the head
637
+ mirror.node.setPosition([0, eye[1], 1]).setRotation([0, Math.PI, 0]);
638
+ engine.start();
639
+ // In a headset: xr.layers = fp.firstPersonLayers (margoengine/xr) hides the head in both eyes.
640
+ ```
641
+
642
+ | Name | Meaning |
643
+ | --- | --- |
644
+ | `loadVRM(engine, url or bytes, options)` | Fetches (at most `maxDownloadBytes`, 64 MiB by default), splits and loads a VRM 1.0 file as a gltf/pbr `PBRModel`. Takes gltf/pbr's load options, `threshold` and `signal`. For VRM 0.x, run `convertVRM0Bytes` from `margoengine/rigging/vrm0` first. |
645
+ | `splitVRMFirstPerson(glb, options)` | The split alone, bytes in and bytes out: no `auto` left, every other byte of the file kept. A second split changes nothing. |
646
+ | `addVRMFirstPerson(model, options)` | Applies the annotations through render layers and returns the handle below. Throws a coded `state` error when a mesh is still `auto` (load it with `loadVRM`). |
647
+ | `fp.firstPersonLayers`, `fp.thirdPersonLayers` | View masks: every layer but the third-person one, and every layer but the first-person one. Give the second to any mirror, probe or outside camera. |
648
+ | `fp.viewpoint(out?)` | World position of the eyes: `lookAt.offsetFromHeadBone` on the head bone. |
649
+ | `fp.meshAnnotations` | Each mesh node and the type it resolved to. |
650
+ | `fp.dispose()` | Puts every mask back as it was (also `using`). |
651
+
652
+ | Option | Default | Meaning |
653
+ | --- | --- | --- |
654
+ | `threshold` (`loadVRM`, `splitVRMFirstPerson`) | `0` | Skin weight a vertex must pass on the head to count as head. 0 is the specification's rule; raise it when a stray head weight pulls collar triangles out of first person. |
655
+ | `firstPersonOnlyLayer`, `thirdPersonOnlyLayer` | `29`, `30` | The layers the two kinds of mesh go on (`FIRST_PERSON_ONLY_LAYER`, `THIRD_PERSON_ONLY_LAYER`). |
656
+ | `firstPersonCameras` | none | Cameras that get `firstPersonLayers`. |
657
+ | `thirdPersonCameras` | the engine camera | Cameras that get `thirdPersonLayers`, only when the file has a `firstPersonOnly` mesh. |
658
+
659
+ A camera, mirror or probe with no mask draws every layer, so it shows `firstPersonOnly` meshes until you give it `fp.thirdPersonLayers`. Shadows are not filtered: the avatar casts its whole shadow, head included, in every view, which is what you want when you look down at your own shadow. Draco and meshopt compressed meshes are read through `margoengine/decoders`, loaded only for a file that needs them. Limits and the measured GPU checks: [VRM first person](../../docs/rigging-vrm-first-person.md).
660
+
661
+ ## Voxel weights (`margoengine/rigging/voxel-weights`)
662
+
663
+ Automatic skin weights for meshes bone heat cannot solve: holes, doubled or flipped faces, non-manifold edges, loose parts, and shells inside shells, such as a coat modelled over a body. The mesh is voxelized, the bones are burned into the grid, and each bone's distance is measured through the solid. Two limbs close together stay apart as long as the grid can see the gap.
664
+
665
+ ```ts
666
+ import type { RigJoint } from 'margoengine/rigging';
667
+ import { voxelWeights } from 'margoengine/rigging/voxel-weights';
668
+
669
+ const positions = new Float32Array([0, 0, 0.1, 0.1, 0, -0.1, -0.1, 0, -0.1, 0, 2, 0]);
670
+ const joints: RigJoint[] = [
671
+ { name: 'base', parent: -1, position: [0, 0, 0] },
672
+ { name: 'tip', parent: 0, position: [0, 2, 0] },
673
+ ];
674
+ const { weights, unreached } = await voxelWeights(
675
+ { positions, indices: [0, 1, 3, 1, 2, 3, 2, 0, 3] }, // the bottom face is missing
676
+ joints,
677
+ );
678
+ console.log(weights.toInfluences(), unreached); // JOINTS_0 and WEIGHTS_0
679
+ ```
680
+
681
+ | Option | Default | Meaning |
682
+ | --- | --- | --- |
683
+ | `resolution` | `96` | Voxels along the longest side, 8 to 512. Parts closer than about one voxel join. |
684
+ | `skip` | none | Joints that move no vertices, such as a root at the feet. |
685
+ | `falloff`, `curve` | `4`, `0.75` | The weight of a bone at distance d voxels is `((1 - curve) * d + curve * d * d) ** -falloff`: a larger `falloff` keeps vertices closer to their nearest bone. |
686
+ | `influences` | `4` | Most bones per vertex. |
687
+ | `closing` | `0` | Closes gaps up to this many voxels before filling. Parts closer than twice this fuse. |
688
+ | `weld` | `1e-6` | Welding tolerance as a fraction of the mesh's size. |
689
+ | `signal` | none | Cancels the solve between bones. |
690
+
691
+ The result also gives `grid`, `voxels` and `unreached`: vertices no bone reached through the solid, such as a hat that floats clear of the head, which take the same falloff from straight-line distances. Where a hole lets the outside into the mesh, the fill grows from the bones through voxels with surface on at least four of the six axis directions. Pick bone heat for clean, closed meshes: it is faster and its weights flow along the surface.
692
+
693
+ ## Automatic rig (`margoengine/rigging/autorig`)
694
+
695
+ Places a humanoid skeleton inside a mesh nobody rigged, then weights it. Give it a figure standing in a T or A pose, in any units, turned any way about `up`; the mesh may be broken or in many parts. Joints carry VRM humanoid names, so `margoengine/rigging/retarget` reads them as they are, and `joints` and `weights` go straight to `margoengine/exporters/skin`. The shoulder fit uses the upper-arm cross-section to keep each shoulder beside the chest on figures with thick upper arms. Here the figure is made of boxes, so the example runs by itself:
696
+
697
+ ```ts
698
+ import { autoRig } from 'margoengine/rigging/autorig';
699
+
700
+ const positions: number[] = [];
701
+ const indices: number[] = [];
702
+ const box = (x0: number, y0: number, z0: number, x1: number, y1: number, z1: number) => {
703
+ const first = positions.length / 3;
704
+ for (const z of [z0, z1]) for (const y of [y0, y1]) for (const x of [x0, x1]) positions.push(x, y, z);
705
+ for (const [a, b, c, d] of [[0, 2, 3, 1], [4, 5, 7, 6], [0, 1, 5, 4], [2, 6, 7, 3], [0, 4, 6, 2], [1, 3, 7, 5]])
706
+ indices.push(first + a, first + b, first + c, first + a, first + c, first + d);
707
+ };
708
+ box(-0.17, 0.85, -0.1, 0.17, 1.42, 0.1); // trunk
709
+ box(-0.06, 1.4, -0.05, 0.06, 1.5, 0.05); // neck
710
+ box(-0.1, 1.48, -0.1, 0.1, 1.74, 0.1); // head
711
+ for (const side of [-1, 1]) {
712
+ box(side * 0.1 - 0.06, 0.05, -0.06, side * 0.1 + 0.06, 0.9, 0.06); // leg
713
+ box(side * 0.1 - 0.06, 0, -0.06, side * 0.1 + 0.06, 0.08, 0.2); // foot
714
+ const [near, far] = [side * 0.15, side * 0.85].sort((p, q) => p - q);
715
+ box(near, 1.32, -0.04, far, 1.4, 0.04); // arm
716
+ }
717
+
718
+ const rig = await autoRig({ positions, indices });
719
+ console.log(rig.joints[rig.humanoid.leftHand].position, rig.forward); // on +x, facing +z
720
+ console.log(rig.weights?.toInfluences()); // JOINTS_0 and WEIGHTS_0
721
+ ```
722
+
723
+ | Option | Default | Meaning |
724
+ | --- | --- | --- |
725
+ | `resolution` | `128` | Voxels along the longest side, 32 to 384. Thin arms need more. |
726
+ | `up` | `[0, 1, 0]` | The mesh's up direction. |
727
+ | `forward` | read from the feet | The way the figure faces, which says which side is its left. A forward along `up` is a `RangeError`. |
728
+ | `closing` | `1` | Closes gaps up to this many voxels before filling, joining parts that nearly touch. |
729
+ | `symmetric` | `true` | Evens left and right joints across the body's centre when they already nearly agree. |
730
+ | `weights` | `'voxel'` | `'voxel'` weights with `voxelWeights`; with `'none'`, pass `joints` to `boneHeatWeights` or any other solver. |
731
+ | `weld` | `1e-6` | Welding tolerance as a fraction of the mesh's size. |
732
+ | `signal` | none | Cancels the fit between stages and the weights between bones. |
733
+
734
+ The result gives `joints`, `humanoid` (each bone's index, by name), `pose` (the same skeleton as local transforms), `weights`, `forward`, `facingFound` and `voxels`. When `facingFound` is false the feet showed no clear front, +z was assumed and left and right may be swapped: pass `forward`. A figure with no head, two feet and two hands to find fails with a `MargoError` of code `failed`. Fingers are not placed. On real files the joints land about 2 to 4 percent of the figure's height from where people put them; the limits are in [docs/limits.md](../../docs/limits.md).
735
+
736
+ ## Corrective shapes (`margoengine/rigging/correctives`)
737
+
738
+ Linear skinning collapses elbows, knees and shoulders. A corrective is a blend shape sculpted to fix that, and this entry drives it from the joint's rotation: full at the pose you sculpted it for, off at rest. `addCorrectives` runs after the pose and after any IK added before it.
739
+
740
+ ```ts
741
+ import {Engine} from 'margoengine/core';
742
+ import {loadGLTF} from 'margoengine/gltf/pbr';
743
+ import {Animation} from 'margoengine/animation';
744
+ import {Animator} from 'margoengine/animator';
745
+ import { addCorrectives } from 'margoengine/rigging/correctives';
746
+ import { detectSkeleton, humanoidBones } from 'margoengine/rigging/retarget';
747
+ const engine = await Engine.create(document.querySelector('canvas')!);
748
+ const model = await loadGLTF(engine, '/character.glb');
749
+ const animator = Animator.attach(Animation.attach(model), {initial: 'walk', states: {walk: 'Walk'}});
750
+ // The mesh node, its sculpted morph target and the elbow joint, all by name.
751
+ const doc = model.asset.doc,
752
+ names = doc.nodes!.map((n) => n.name ?? '');
753
+ const body = names.indexOf('Body');
754
+ const target = (doc.meshes![doc.nodes![body].mesh!].extras as { targetNames: string[] }).targetNames.indexOf('LeftElbowFix');
755
+ const joint = humanoidBones(names, detectSkeleton(names)?.preset ?? 'humanoid').get('leftLowerArm')!;
756
+ const s = Math.sin(1);
757
+ const elbow = addCorrectives(animator, {
758
+ shapes: [{ node: body, target, joint, pose: [s, 0, 0, Math.cos(1)], curve: 'smooth' }], // full at two radians
759
+ });
760
+ elbow.dispose(); // shapes back to 0
761
+ ```
762
+
763
+ A joint that swings every way, a shoulder, needs several sculpted poses. Give them as a pose space: each sample holds exactly its own weights, and rotations between them blend. Include the rest pose with zero weights, or the shapes stay on away from every sample.
764
+
765
+ ```ts
766
+ import { Correctives } from 'margoengine/rigging/correctives';
767
+
768
+ const r = Math.SQRT1_2;
769
+ const shoulder = new Correctives({
770
+ spaces: [
771
+ {
772
+ joint: 7,
773
+ shapes: [
774
+ { node: 2, target: 4 }, // arm raised
775
+ { node: 2, target: 5 }, // arm forward
776
+ ],
777
+ samples: [
778
+ { rotation: [0, 0, 0, 1], weights: [0, 0] },
779
+ { rotation: [0, 0, r, r], weights: [1, 0] },
780
+ { rotation: [r, 0, 0, r], weights: [0, 1] },
781
+ ],
782
+ },
783
+ ],
784
+ });
785
+ console.log(shoulder.evaluate(() => [0, 0, r, r])); // [{ node: 2, target: 4, weight: 1 }, { node: 2, target: 5, weight: 0 }]
786
+ ```
787
+
788
+ | Shape field | Default | Meaning |
789
+ | --- | --- | --- |
790
+ | `node`, `target` | required | The mesh's glTF node and the morph target. |
791
+ | `joint` | required | The bone that drives it. |
792
+ | `pose` | required | The joint's local rotation where the shape is full. |
793
+ | `rest` | the joint's rest | The joint's local rotation where the shape is off. |
794
+ | `cone` | none | Radians off the line from `rest` to `pose` at which the shape has faded out. With none only the bend along that line counts, so a hinge's twist does nothing. |
795
+ | `start` | `0` | Reading where the shape starts: `0.5` keeps it off for the first half of the bend. |
796
+ | `curve` | `'linear'` | `'smooth'` eases in and out. |
797
+ | `amount` | `1` | Weight at full bend. |
798
+
799
+ Shapes on one target add up, then clamp to 0 to 1. `width` on a pose space sets the Gaussian width in radians; the default is the mean angle from each sample to its nearest neighbour. Pose spaces are solved once when made. `Correctives` is plain data, so `evaluate(rotationOf, restOf)` runs with no engine. A driven morph target belongs to the correctives: a clip's track on it is overwritten.
800
+
801
+ ## Weight transfer (`margoengine/rigging/transfer`)
802
+
803
+ Copies skin weights from a rigged mesh to clothing, or to any mesh around it. Each vertex takes the weights at the closest point of the source's surface, read across that triangle. A match counts only when it is near and the two surfaces lie alike, so a sleeve vertex next to the torso does not take the torso's weights; those vertices are filled in from the matched ones around them, over the target's own surface.
804
+
805
+ ```ts
806
+ import { WeightMap } from 'margoengine/rigging';
807
+ import { transferWeights } from 'margoengine/rigging/transfer';
808
+
809
+ // A rigged triangle with one bone per corner, and a smaller one 1 cm in front of it.
810
+ const positions = new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0]);
811
+ const body = { positions, indices: [0, 1, 2], weights: new WeightMap(3, 3, [1, 0, 0, 0, 1, 0, 0, 0, 1]) };
812
+ const shirt = { positions: new Float32Array([0.1, 0.1, 0.01, 0.5, 0.1, 0.01, 0.1, 0.5, 0.01]), indices: [0, 1, 2] };
813
+ const { weights, matched, filled } = await transferWeights(body, shirt);
814
+ console.log(weights.toInfluences(), matched, filled);
815
+ ```
816
+
817
+ `weights` on the source is a `WeightMap`, or `{ joints, weights }` as JOINTS_0 and WEIGHTS_0 hold them. Both meshes share one space, so pose them alike first.
818
+
819
+ | Option | Default | Meaning |
820
+ | --- | --- | --- |
821
+ | `maxDistance` | `0.05` | Farthest a match may be, as a fraction of the source's size. |
822
+ | `maxAngle` | `60` | Largest angle between the two surfaces at a match, degrees. Either facing counts, because cloth is often one layer with its normals any way round. |
823
+ | `iterations` | `1000` | Most conjugate-gradient steps of the fill per bone; it stops once the harmonic system's residual is 1e-10 of where it started. |
824
+ | `threshold` | `1e-4` | Weights below this are dropped before renormalising. |
825
+ | `boneCount` | the source's | Bones in the result, for influences that do not use the last ones. |
826
+ | `weld` | `1e-6` | Welding tolerance of the target as a fraction of its size. |
827
+ | `signal` | none | Cancels the transfer. |
828
+
829
+ `matched` and `filled` count target points. A part of the target with no match at all, such as a hat clear of the head, keeps the closest weights as they are.
830
+
831
+ ## Face tracking (`margoengine/rigging/face`)
832
+
833
+ Puts a tracked face on a character. Face trackers report the same 52 values from 0 to 1, one per facial movement: Apple's ARKit, Google's MediaPipe Face Landmarker and Live Link Face all do. `addFace` reads a frame in any of their shapes, smooths it and drives the model's morph targets, found by name, or a VRM avatar's expressions.
834
+
835
+ ```ts
836
+ import { loadGLTF } from 'margoengine/gltf/pbr';
837
+ import { Animation } from 'margoengine/animation';
838
+ import { addFace } from 'margoengine/rigging/face';
839
+ import {Engine} from 'margoengine/core';
840
+ const engine = await Engine.create(document.querySelector('canvas')!);
841
+ const animation = new Animation(await loadGLTF(engine, 'character.glb'));
842
+ const face = addFace(animation, { mirror: true }); // a selfie camera: swap sides
843
+ console.log(face.matched, face.missing); // which of the 52 this model can show
844
+
845
+ // Call this with each tracker frame, at the tracker's own rate.
846
+ face.push({ jawOpen: 0.4, eyeBlinkLeft: 1 });
847
+ face.push(null); // tracking lost: back to neutral
848
+ face.dispose();
849
+ ```
850
+
851
+ A frame is a record of names to values, or a list of `{ categoryName, score }`, so MediaPipe's `result.faceBlendshapes[0].categories` goes straight in. Names are matched by `faceShapeOf`, which ignores case, separators and any prefix and knows `_L` and `_R`: `EyeBlinkLeft`, `eye_blink_left`, `eyeBlink_L` and `ARKit_eyeBlinkLeft` all read as `eyeBlinkLeft`. Model morph targets are read from `extras.targetNames` on every mesh, so head, teeth and lashes move together. For other names, pass `map`:
852
+
853
+ ```ts
854
+ import { addFace } from 'margoengine/rigging/face';
855
+ import { addVRM, readVRM } from 'margoengine/rigging/vrm';
856
+ import { Animation } from 'margoengine/animation';
857
+ import { loadGLTF } from 'margoengine/gltf/pbr';
858
+ import { Engine } from 'margoengine/core';
859
+ const engine = await Engine.create(document.querySelector('canvas')!);
860
+ const url = '/avatar.vrm';
861
+ const animation = Animation.attach(await loadGLTF(engine, url));
862
+ const avatar = addVRM(animation, readVRM(new Uint8Array(await (await fetch(url)).arrayBuffer())));
863
+ const byName = addFace(animation, { map: { jawOpen: 'Mouth_Open', eyeBlinkLeft: ['Blink_L', 'Lash_L'] } });
864
+ byName.dispose(); // one face per model: dispose it before adding another
865
+ addFace(animation, { vrm: avatar }); // or a VRM avatar: drives its preset expressions
866
+ ```
867
+
868
+ | `addFace` option | Default | Meaning |
869
+ | --- | --- | --- |
870
+ | `smoothing` | `0.05` | Time constant in seconds; 0 follows the tracker exactly. The same at any frame rate. |
871
+ | `gain` | `1` | Multiplies values before they clamp to 0 to 1: one number, or per shape. |
872
+ | `mirror` | `false` | Swaps left and right, for a mirrored camera. |
873
+ | `map` | none | Morph target names for shapes the names alone do not find. |
874
+ | `vrm` | none | Drive this avatar's expressions rather than morph targets. |
875
+ | `animator` | none | Run inside this `Animator`; with none, run as an engine plugin. |
876
+
877
+ `FaceMapper` is the same thing as plain data, with no engine: `push(frame)`, `update(delta)`, `get(shape)`, `values`. `vrmFaceExpressions(get)` gives the VRM presets: what both eyes share goes to `blink` and the rest to `blinkLeft` and `blinkRight`, the eyes' mean to the look presets, `jawOpen`, `mouthPucker`, `mouthFunnel`, the mouth's lower lip and stretch to `aa`, `ou`, `oh`, `ih`, `ee`, and smile, frown, brow and wide eyes to `happy`, `sad`, `angry` and `surprised`. No tracker value stands for `relaxed`. A driven morph target belongs to the face: a clip's track on it is overwritten. A model has one face at a time: a second `addFace` throws `MargoError` code `state` until the first is disposed.
878
+
879
+ ARKit is a trademark of Apple Inc. MediaPipe is a trademark of Google LLC. Live Link Face is a product of Epic Games, Inc. Margo is not affiliated with them. The 52 names are Apple's published `ARFaceAnchor.BlendShapeLocation` identifiers.
880
+
881
+ ## Retarget presets (`margoengine/rigging/retarget`)
882
+
883
+ Clips made for one skeleton play on another: `prepareRetarget(source, target)` recognises each rig's naming (Mixamo with any `mixamorig` prefix, Godot's humanoid profile, Roblox R15, MPFB (MakeHuman's default rig), Character Creator's CC3+ skeleton (`CC_Base_Hip`, `CC_Base_L_Upperarm`, ...; its twist and share bones stay at rest and follow their limb through the skin), the joints of `@margoengine/exporters/skin`'s `humanoidJoints()`, or the 55 humanoid bone names themselves), maps every target bone to its source bone, and by default turns the target's reference pose so each bone points the way the source's does at rest (an A-pose character driven by T-pose clips). Pass the result to `@margoengine/animation`'s `Retarget`:
884
+
885
+ ```ts
886
+ import { Animation, applyKeyframeClip } from 'margoengine/animation';
887
+ import { Retarget, retargetRig } from 'margoengine/animation/skeleton-utils';
888
+ import { createStage } from 'margoengine';
889
+ import { loadGLTF } from 'margoengine/gltf/pbr';
890
+ import { detectSkeleton, prepareRetarget } from 'margoengine/rigging/retarget';
891
+ const stage = await createStage('#viewport', { backend: 'webgpu' });
892
+ const [mixamoModel, godotHero] = await Promise.all(
893
+ ['/mixamo-walk.glb', '/godot-hero.glb'].map((url) => loadGLTF(stage.engine, url)),
894
+ );
895
+ const source = retargetRig(mixamoModel), target = retargetRig(godotHero);
896
+ console.log(detectSkeleton(source.names)); // { preset: 'mixamo', bones: (humanoid bones found) }, or null
897
+ const prepared = prepareRetarget(source, target); // or { from: 'mixamo', to: 'godot', alignRest: true }
898
+ console.log(prepared.from, prepared.to, prepared.hip, prepared.unmapped); // mixamo godot Hips [...]
899
+ const retarget = new Retarget(source, prepared.target, prepared); // names and hip come from prepared
900
+ const walk = retarget.clip({ animation: Animation.attach(mixamoModel), clip: 'Walk' }, { fps: 30 });
901
+ applyKeyframeClip(walk, Animation.attach(godotHero), 0.5);
902
+ ```
903
+
904
+ | Option | Default | Meaning |
905
+ | --- | --- | --- |
906
+ | `from` | detected | The source's naming: `mixamo`, `godot`, `roblox`, `margo`, `mpfb`, `characterCreator`, `cmu` (CMU motion capture, as `@margoengine/loaders/mocap` `parseASF` names its joints) or `humanoid`. |
907
+ | `to` | detected | The target's naming. |
908
+ | `alignRest` | `true` | Turn the target's limbs (arms, hands, fingers, legs, feet) to point as the source's do at rest, so a T-pose source drives an A-pose target. The trunk, neck and collarbones keep the target's own rest: their directions are body layout, and aiming them along a motion-capture skeleton's would hunch and shrug the target. `false` keeps the target's whole rest pose (both rigs already stand alike). |
909
+
910
+ Rest alignment matches palm roll when both rigs map the wrist and the bases of the middle, index and little fingers. The wrist-to-middle direction sets the aim, and the direction across the knuckles sets the roll about that aim. With missing or collinear landmarks, the wrist uses the aim alone. This uses the humanoid landmarks from [VRM 1.0](https://github.com/vrm-c/vrm-specification/blob/master/specification/VRMC_vrm-1.0/humanoid.md) and draws on the use of anatomical frames in [*Semantics2Hands*, Ye et al. (2023)](https://arxiv.org/abs/2308.05920). Rest alignment prepares the skeleton for motion transfer. Maintaining hand or foot contact with a surface during a clip requires a separate constraint, as described in [*Retargeting Motion to New Characters*, Gleicher (1998)](https://graphics.cs.wisc.edu/Papers/1998/Gle98/).
911
+
912
+ A source hand with no finger bones below it, such as a BVH wrist that ends in an End Site (Xsens, the 100STYLE captures) or an ASF hand segment, is one rigid segment. Rest alignment then lays the target's hand and its index, middle, ring and little finger bones straight along that segment, in line with the source forearm when the source has no finger base, and lists the unmapped ones it turned in `prepared.hold`. `Retarget` reads `hold` and keeps those bones at the aligned rest, so they stop holding the target's own bind pose, which for most authored characters is a fanned, curled hand. Thumbs keep the target's rest. A source with one finger segment (CMU's `lfingers`, mapped to the middle finger) drives all four long fingers. This is the intermediate-skeleton idea of [Monzani, Baerlocher, Boulic and Thalmann (2000), *Using an Intermediate Skeleton and Inverse Kinematics for Motion Retargeting*](https://doi.org/10.1111/1467-8659.00393): a target bone the source does not have takes its rest from the source segment that holds it.
913
+
914
+ ```js
915
+ import { prepareRetarget } from 'margoengine/rigging/retarget';
916
+
917
+ const fingerless = { names: ['hips', 'leftLowerArm', 'leftHand'], parents: [-1, 0, 1], rest: Float64Array.from([0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0.3, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0.26, 0, 0, 0, 0, 0, 1, 1, 1, 1]) };
918
+ const fingered = { names: ['hips', 'leftLowerArm', 'leftHand', 'leftIndexProximal', 'leftIndexIntermediate'], parents: [-1, 0, 1, 2, 3], rest: Float64Array.from([0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0.3, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0.26, 0, 0, 0, 0, 0.6, 0.8, 1, 1, 1, 0.09, 0, 0.02, 0, 0, 0, 1, 1, 1, 1, 0.03, 0, 0, 0, 0, 0, 1, 1, 1, 1]) };
919
+ const { hold } = prepareRetarget(fingerless, fingered, { from: 'humanoid', to: 'humanoid' });
920
+ console.log(hold); // ['leftIndexProximal']: the index finger now rests straight along the hand
921
+ ```
922
+
923
+ Target bones with no source bone (a Godot `Root`, Roblox's `HumanoidRootPart`, fingers a source lacks) map to `''` and stay at rest; the humanoid bones among them are listed in `unmapped`. Roblox R15 has no neck, shoulders, toes or fingers, so clips from it leave those at rest; its `UpperTorso` maps to `spine`, which VRM 1.0 requires (chest is optional). Both rigs' model spaces must face the same way (glTF: +z forward, the figure's left at +x). `humanoidBones(names, preset)` gives the humanoid bone -> index map for your own tools, and `HUMANOID_BONES` lists every humanoid bone, parents first. An unrecognised naming throws a `RangeError` that asks for `from` or `to`.
924
+
925
+ ## Hands (`margoengine/rigging/hands`)
926
+
927
+ Named hand poses and a per-hand layer on an `@margoengine/animator` Animator. Body clips often carry flat or no finger
928
+ tracks, which read as dead hands; `addHands` blends a relaxed rest pose into every clip whose finger tracks stay under
929
+ 15 degrees on average, cross-faded with the Animator's own transitions, and leaves clips that key their fingers alone.
930
+ Each hand also takes keyed poses over time: `relaxed()`, `fist()`, `flat()`, `point()`, `pinch()`, `grip(diameter)`
931
+ (a power grip solved for a bar of that diameter in metres) or `handPose(table)` with your own joint angles. The
932
+ fingers are found through the retarget presets: Mixamo, VRM, MPFB (MakeHuman), Godot and the humanoid names.
933
+
934
+ ```ts
935
+ import { Animation } from 'margoengine/animation';
936
+ import { Animator } from 'margoengine/animator';
937
+ import { createStage } from 'margoengine';
938
+ import { loadGLTF } from 'margoengine/gltf/pbr';
939
+ import { addHands, grip, relaxed } from 'margoengine/rigging/hands';
940
+ const stage = await createStage('#viewport', { backend: 'webgpu' });
941
+ const model = await loadGLTF(stage.engine, '/mixamo-walk.glb');
942
+ const animator = Animator.attach(Animation.attach(model), { initial: 'walk', states: { walk: 'Walk' } });
943
+ const hands = addHands(animator); // relaxed fingers on every clip with flat finger tracks
944
+ console.log(hands.flat.left); // the clips whose flat fingers get the relaxed pose
945
+ hands.right.set(grip(0.035), { blend: 0.3 }); // close the right hand on a 35 mm rail over 0.3 s
946
+ hands.right.set(relaxed()); // and open it again later
947
+ hands.dispose(); // the clips play as authored again
948
+ ```
949
+
950
+ | Option | Default | What it does |
951
+ | --- | --- | --- |
952
+ | `left`, `right` | null | A pose each hand takes from the start; null leaves the hand to the clip (and the relaxed default). |
953
+ | `auto` | true | Blend `rest` into clips whose finger tracks stay under `threshold`. |
954
+ | `threshold` | 15 | Mean finger turn from rest, degrees, under which a clip counts as having flat fingers. |
955
+ | `rest` | `relaxed()` | The pose `auto` blends in. |
956
+ | `preset`, `bones` | detected | The rig's naming, or your own humanoid bone map, when detection cannot tell. |
957
+
958
+ `hands.left.keys` and `hands.right.keys` are plain `{time, pose, blend, weight}` lists, so a film can write them ahead
959
+ of time; with `hands.time` set the hands are a pure function of time and a seek gives what playing gives. A key with
960
+ `pose: null` hands the hand back to the clip over its blend. A digit a pose leaves out (the relaxed pose leaves out the
961
+ thumb, which a bind pose splays away from the palm) keeps the clip's own rotation and fades back to it.
962
+
963
+ The poses follow the grasp literature: fingers close joint by joint until they meet the bar, the tip joint at 2/3 of
964
+ the middle one (Rijpkema and Girard 1991), flexion grows from the index to the little finger (Santello, Flanders and
965
+ Soechting 1998), the grip and rest classes of Feix et al. 2016, and the rest posture's ranges after Wheatland et al.
966
+ 2015. Without the engine, `measureHands(rig)`, `poseTable(pose, hand)`, `handRotations(hand, table)` and
967
+ `gripFinger(lengths, diameter)` give the same numbers as plain data:
968
+
969
+ ```ts
970
+ import { gripFinger } from 'margoengine/rigging/hands';
971
+ const index = gripFinger([0.045, 0.026, 0.019], 0.035); // phalanx lengths in metres, a 35 mm bar
972
+ console.log(index.flex.map(Math.round), index.tipGap < 0.0005); // joint angles in degrees; the tip meets the bar
973
+ ```
974
+
975
+ ## Joint-space limits (`margoengine/rigging/joint-limits`)
976
+
977
+ Calibrate a hinge or swing-and-twist cone in the joint's local frame. `PoseJointLimits` projects packed local TRS
978
+ samples in place and preserves translations and scales. Use it after clip blending, or install the same projection as a
979
+ final Animator solver with `addPoseJointLimits(animator, limits)`. `redistributeJointTwist` can move excessive axial
980
+ rotation from a joint to its parent while preserving that joint's attachment and world orientation.
981
+
982
+ ```ts
983
+ import { PoseJointLimits } from 'margoengine/rigging/joint-limits';
984
+ const elbowPose = new Float64Array([0, 0, 0, 0, 0, 0, 1, 1, 1, 1]);
985
+ const limit = new PoseJointLimits(1, [
986
+ { joint: 0, neutral: [0, 0, 0, 1], limit: { type: 'hinge', axis: [0, 0, 1], min: 0, max: 2.35 } },
987
+ ]);
988
+ limit.apply(elbowPose);
989
+ console.log(elbowPose[6]);
990
+ ```
991
+
992
+ Author these axes for the skeleton's bind pose. For human limbs, the limits are per-rig constraints on permitted
993
+ motion rather than an estimate of anatomy from a bone name. See [Akhter and Black, Pose-Conditioned Joint Angle
994
+ Limits for 3D Human Pose Reconstruction (2015)](https://openaccess.thecvf.com/content_cvpr_2015/html/Akhter_Pose-Conditioned_Joint_Angle_2015_CVPR_paper.html)
995
+ and [Crisco et al., The Mechanical Axes of the Wrist Are Oriented Obliquely to the Anatomical Axes (2011)](https://pmc.ncbi.nlm.nih.gov/articles/PMC3016043/).
996
+
997
+ ## Anatomy: the body every solver reads (`margoengine/rigging/anatomy`)
998
+
999
+ `fitAnatomy(rig, { species })` gives a rig a body: which bone is which joint, which way each joint bends, how far, and
1000
+ where each number comes from. Every joint's frame is built from landmarks (the rig's joint positions and the way its
1001
+ feet point), never from bone axes or the rest pose. So a T pose, an A pose and an arms-down pose of one body, with any
1002
+ bone roll, read the same clinical angles, and a straight elbow or knee still knows which way it bends. Limits are on by
1003
+ default; `limits: false` turns them off by name.
1004
+
1005
+ The human table is its own entry, `margoengine/rigging/anatomy/human`, so a scene of horses ships no human numbers.
1006
+ Any species uses the same table format through `defineSpecies`.
1007
+
1008
+ ```ts
1009
+ import type { RigJoint } from 'margoengine/rigging';
1010
+ import { type ClampIssue, clampPose, fitAnatomy, jointAngles, poseFromAngles } from 'margoengine/rigging/anatomy';
1011
+ import { human } from 'margoengine/rigging/anatomy/human';
1012
+
1013
+ // Any rig, as joint positions or as { names, parents, rest }. Bones are found by name: Mixamo style here.
1014
+ const rig: RigJoint[] = [
1015
+ { name: 'Hips', parent: -1, position: [0, 1, 0] },
1016
+ { name: 'Spine', parent: 0, position: [0, 1.1, 0] },
1017
+ { name: 'Head', parent: 1, position: [0, 1.6, 0] },
1018
+ { name: 'LeftUpLeg', parent: 0, position: [0.1, 0.95, 0] },
1019
+ { name: 'RightUpLeg', parent: 0, position: [-0.1, 0.95, 0] },
1020
+ { name: 'LeftArm', parent: 1, position: [0.2, 1.45, 0] },
1021
+ { name: 'LeftForeArm', parent: 5, position: [0.48, 1.45, 0] },
1022
+ { name: 'LeftHand', parent: 6, position: [0.74, 1.45, 0] },
1023
+ ];
1024
+ const body = fitAnatomy(rig, { species: human });
1025
+ console.log(body.preset, body.restPose); // segments T
1026
+
1027
+ // A pose with the elbow folded 30 degrees the wrong way is brought back to the stop, and says so.
1028
+ const pose = poseFromAngles(body, { l_elbow: { flexion: -30 } });
1029
+ const issues: ClampIssue[] = [];
1030
+ clampPose(body, pose, { issues });
1031
+ console.log(issues[0].joint, issues[0].motion, Math.round(issues[0].limit)); // l_elbow hyperextension -5
1032
+ console.log(jointAngles(body, pose).l_elbow.flexion.toFixed(1)); // -5.0
1033
+ ```
1034
+
1035
+ What the entry gives:
1036
+
1037
+ | Function | What it does |
1038
+ | --- | --- |
1039
+ | `fitAnatomy(rig, { species, preset?, map?, limits?, forward?, roll?, drop?, vertical? })` | The `AnatomicalRig`: body frame, stature, rest pose (`T`, `A`, `arms-down`), and per joint its bone, kind, anatomical axes in the bone's own frame, neutral rotation, rest angles and ranges. |
1040
+ | `jointAngles(body, pose)`, `readJointAngles(body, pose, out)` | Clinical angles in degrees per joint: the two parts of the swing (flexion and abduction for most joints) and the twist. The second form fills a flat array and allocates nothing. |
1041
+ | `poseFromAngles(body, angles, base?)` | The pose that has those angles: the inverse. |
1042
+ | `regionAngles(body, pose)` | The head against the chest and the chest against the pelvis, whatever number of spine bones the rig has. |
1043
+ | `clampPose(body, pose, { tier?, issues? })` | Brings a pose inside the ranges, in place, and reports each motion it changed with its limit and source. |
1044
+ | `addAnatomyLimits(animator, body, { tier?, onClamp? })` | The same every frame on an Animator. |
1045
+ | `hingeRolls(body, poses)` | Reads from motion how a straight limb is rolled, to fit again with `roll`. |
1046
+ | `rhythmDrops(body, poses)` | Reads from motion how far a collarbone drops from the rest pose where the arm hangs, to fit again with `drop`. |
1047
+ | `poseLimits`, `ikLimits`, `ragdollJoints`, `kinematicsLimits` | The limits in the forms `PoseJointLimits`, IK chains, ragdoll profiles and `JointLimitSet` take. |
1048
+ | `defineSpecies(table)`, `bound(allowance, ...rows)`, `mirrorJoint(spec, rename)` | Build and check a species table. |
1049
+
1050
+ How angles are measured. The body frame is x to the body's left, y up, z forward, read from the trunk: a body that
1051
+ stands stooped in its rest pose leans `body.frame.up` forward with its trunk. Heights, the stature and the pose
1052
+ checker's ground tests are measured along `body.frame.vertical` instead, the world's up: the rig's axis nearest the
1053
+ trunk's up when the rest feet stand level on it, or `vertical` as passed. Each joint has a long axis (its
1054
+ segment at neutral) and three motions: two swings across it and the twist about it. The swing is read as one rotation
1055
+ vector whose two parts are the clinical angles, so flexion and abduction are exact for a single-plane motion and stay
1056
+ well defined up to 180 degrees; the twist is what is left about the segment. Neutral for a human is the standing pose
1057
+ of ISO/IEC 19774 (HAnim): arms down, palms to the thighs. A shoulder and a hip are measured from that pose in the
1058
+ trunk's frame, an elbow, knee, wrist or finger joint from its straight position, and a collarbone, spine joint, ankle
1059
+ or toe from the rig's own rest pose. A collarbone rides on its arm (the table's `rhythm`, from bone pins, Ludewig et
1060
+ al. 2009: 5.9 degrees up and 19.2 back with the arm at the side, 11 to 17 up and 23 to 39 back from 30 to 120 degrees
1061
+ of arm elevation), so a rest that holds the arms out and its collarbones raised past the direction at the side reads
1062
+ that rise, never more than the rhythm gives for its arms' lift, as one swing with no twist; a rig whose collarbone
1063
+ stays put as its arms rise keeps its rest as zero.
1064
+
1065
+ Two tiers. `normal` is the clinical range, where a validator should warn. `structural` is the stop no body passes,
1066
+ and what `clampPose` holds by default: an elbow or a knee stops 5 degrees past straight. A swing range that differs by
1067
+ direction (a shoulder reaches 180 degrees forward and 75 back) is an ellipse per quadrant, and a pose outside goes to
1068
+ the nearest point of it, so a bent knee with sideways noise keeps its bend. A straight knee does not twist: its
1069
+ rotation opens with flexion. Twist past a wrist's own small range moves into the forearm, which turns with the hand, so
1070
+ the hand stays where it was. A spine region (neck, trunk) is one budget: each bone may use any part of it, and the
1071
+ head stays within the neck's range against the chest whatever number of bones the rig spends.
1072
+
1073
+ A rig bone stands for every table joint of its region nearest to it: one spine bone for five vertebrae carries their
1074
+ summed range, and a head bone with no neck bone carries the whole neck.
1075
+
1076
+ ### The human table (`margoengine/rigging/anatomy/human`)
1077
+
1078
+ `human` holds the 139 joints of the body in ISO/IEC 19774-1:2019 names from `humanoid_root` (level of articulation 4
1079
+ without the 7 joints of the face), each with its kind, axes, ranges, and the source of every number.
1080
+
1081
+ ```ts
1082
+ import { human, humanTable } from 'margoengine/rigging/anatomy/human';
1083
+
1084
+ const elbow = human.joints.find((joint) => joint.id === 'l_elbow')!;
1085
+ const flexion = elbow.dofs![0];
1086
+ console.log(flexion.positive, flexion.max.normal, flexion.max.structural); // flexion 150 160
1087
+ console.log(flexion.negative, flexion.min.normal, flexion.min.structural); // hyperextension 4.7 5
1088
+ const row = flexion.max.rows[0];
1089
+ console.log(row.source, row.provenance, row.what); // cdc2011 dataset elbow flexion, women 20-44 years, mean
1090
+ // A table for one group: girls of 2 to 8 years bend further past straight.
1091
+ const girl = humanTable({ sex: 'female', age: 6 });
1092
+ console.log(girl.joints.find((joint) => joint.id === 'l_elbow')!.dofs![0].min.normal); // 6.8
1093
+ ```
1094
+
1095
+ Where the numbers come from. Every number is a row with its source, the page it was read on, and how it was checked:
1096
+ `dataset` (read from a measured dataset held in a data file of this repository), `online` (read on the page named),
1097
+ `recalled` (from memory, to be confirmed in print) or `print`. Today 98 numbers are `dataset`, 145 `online`, 92
1098
+ `recalled` and none `print`; `packages/rigging/tests/anatomy-human.test.js` holds a second copy of each.
1099
+
1100
+ - The limb motions the CDC Normal Joint Range of Motion Study measured (hip, knee, ankle, shoulder flexion, elbow,
1101
+ forearm rotation) come from that dataset: adults of 20 to 44 years, the larger mean of the two sexes
1102
+ (`anatomy-data-cdc.ts`). `humanTable({ sex, age })` reads another group.
1103
+ - Every other range is the AAOS 1965 value as a readable page reproduces it, with the AMA Guides (5th edition) value
1104
+ beside it. The stop of a motion is its largest source value rounded up to 5 degrees plus a stated allowance: 15 for
1105
+ the swing or twist of a ball, saddle or condyloid joint and for a spine region, 10 for a hinge's flexion, none for
1106
+ the straight side of a hinge.
1107
+ - A spine region's clinical range is shared among its levels by per-level weights: lumbar levels from Pearcy and
1108
+ Tibrewal 1984 and White and Panjabi 1990 as open pages give them; thoracic and cervical levels are White and
1109
+ Panjabi's representative values from recall (61 of the 92 recalled numbers), with the thoracic levels scaled to that
1110
+ book's thoracic totals. The other recalled numbers are toe joints, the collarbone's split, knee rotation, the wrist's
1111
+ own twist, the thumb's base and the small joints of the palm.
1112
+ - Proportions (`human.proportions`) are shares of stature from the ANSUR II summary statistics, both sexes
1113
+ (`anatomy-data-ansur2.ts`), with the Drillis and Contini figure beside them. Segment masses and centres of mass
1114
+ (`human.segments`) are de Leva 1996 (`anatomy-data-deleva.ts`). `human.couplings` lists the motions joints share
1115
+ (shoulder girdle rhythm, carrying angle, forearm rotation, knee rotation, knee screw-home, spine share, limb twist,
1116
+ finger curl, head rotation) with their numbers and sources, for the coupling solver (`margoengine/rigging/coupling`).
1117
+
1118
+ Bones are found by name under these conventions, the best match winning: `hanim` (the standard's own names and the
1119
+ HAnim 1.x names of renamed joints), `segments` (Mixamo style, and the BVH form of the CMU captures), `joints` (the
1120
+ 100STYLE captures and other files that name a bone for its joint), `unreal` and `unreal5` (Unreal mannequin names,
1121
+ `pelvis`, `spine_01`, `upperarm_l`, `thigh_l`, with three or five spine bones; the Quaternius animation library uses
1122
+ the three-bone form), `kaykit` (KayKit characters, `hips`, `chest`, `upperarm.l`, `wrist.l`, `upperleg.l`), and the
1123
+ presets of `margoengine/rigging/retarget` (Character Creator, the CMU ASF skeleton, MPFB, Godot, Roblox R15, VRM
1124
+ humanoid names). `map` adds or overrides one bone at a time.
1125
+
1126
+ ```ts
1127
+ import type { RigJoint } from 'margoengine/rigging';
1128
+ import { fitAnatomy, hingeRolls, poseFromAngles, poseLimits } from 'margoengine/rigging/anatomy';
1129
+ import { fitHuman, human } from 'margoengine/rigging/anatomy/human';
1130
+ import { PoseJointLimits } from 'margoengine/rigging/joint-limits';
1131
+
1132
+ const rig: RigJoint[] = [
1133
+ { name: 'Hips', parent: -1, position: [0, 1, 0] },
1134
+ { name: 'Spine', parent: 0, position: [0, 1.1, 0] },
1135
+ { name: 'Head', parent: 1, position: [0, 1.6, 0] },
1136
+ { name: 'LeftUpLeg', parent: 0, position: [0.1, 0.95, 0] },
1137
+ { name: 'RightUpLeg', parent: 0, position: [-0.1, 0.95, 0] },
1138
+ { name: 'LeftArm', parent: 1, position: [0.2, 1.45, 0] },
1139
+ { name: 'LeftForeArm', parent: 5, position: [0.48, 1.45, 0] },
1140
+ { name: 'LeftHand', parent: 6, position: [0.74, 1.45, 0] },
1141
+ ];
1142
+ const body = fitHuman(rig);
1143
+ // The same limits in the form PoseJointLimits holds: exact for hinges.
1144
+ const older = new PoseJointLimits(rig.length, poseLimits(body).filter((limit) => limit.limit.type === 'hinge'));
1145
+ const pose = poseFromAngles(body, { l_elbow: { flexion: 175 } });
1146
+ older.apply(pose);
1147
+ // A capture's frames show how its straight limbs are rolled; fit again with what they show.
1148
+ const frames = [30, 60, 90].map((flexion) => poseFromAngles(body, { l_elbow: { flexion } }));
1149
+ const calibrated = fitAnatomy(rig, { species: human, roll: hingeRolls(body, frames) });
1150
+ console.log(Object.keys(hingeRolls(body, frames)), calibrated.joints.length); // [ 'l_shoulder' ] 8
1151
+ ```
1152
+
1153
+ An A pose rest holds the collarbone raised with the arm, so its rest is not the collarbone's zero. A rig bone does
1154
+ not always lie along the collarbone (a Character Creator clavicle bone aims at the shoulder joint's centre, below the
1155
+ collarbone), so the rest direction alone cannot show it; the motion can. `rhythmDrops` reads, over the frames that
1156
+ hang the arm within 30 degrees of the side, how far the collarbone drops from the rest, less what the rhythm still
1157
+ gives for that lift (Ludewig et al. 2009), and `drop` takes the zero back by it, never past the rhythm between the
1158
+ rest arm's lift and the side. `addPerson` in `@margoengine/humans` does this from a model's clips by default.
1159
+
1160
+ ```ts
1161
+ import type { RigJoint } from 'margoengine/rigging';
1162
+ import { fitAnatomy, jointAngles, poseFromAngles, rhythmDrops } from 'margoengine/rigging/anatomy';
1163
+ import { fitHuman, human } from 'margoengine/rigging/anatomy/human';
1164
+
1165
+ const s = Math.SQRT1_2;
1166
+ const rig: RigJoint[] = [
1167
+ { name: 'Hips', parent: -1, position: [0, 0.93, 0] },
1168
+ { name: 'Spine', parent: 0, position: [0, 1.03, 0] },
1169
+ { name: 'Spine1', parent: 1, position: [0, 1.18, 0] },
1170
+ { name: 'Spine2', parent: 2, position: [0, 1.33, 0] },
1171
+ { name: 'Neck', parent: 3, position: [0, 1.5, 0] },
1172
+ { name: 'Head', parent: 4, position: [0, 1.6, 0] },
1173
+ { name: 'LeftUpLeg', parent: 0, position: [0.09, 0.9, 0] },
1174
+ { name: 'LeftLeg', parent: 6, position: [0.09, 0.49, 0] },
1175
+ { name: 'LeftFoot', parent: 7, position: [0.09, 0.07, 0] },
1176
+ { name: 'LeftToeBase', parent: 8, position: [0.09, 0.01, 0.13] },
1177
+ { name: 'RightUpLeg', parent: 0, position: [-0.09, 0.9, 0] },
1178
+ { name: 'RightLeg', parent: 10, position: [-0.09, 0.49, 0] },
1179
+ { name: 'RightFoot', parent: 11, position: [-0.09, 0.07, 0] },
1180
+ { name: 'RightToeBase', parent: 12, position: [-0.09, 0.01, 0.13] },
1181
+ { name: 'LeftShoulder', parent: 3, position: [0.03, 1.44, 0] },
1182
+ { name: 'LeftArm', parent: 14, position: [0.18, 1.44, 0] },
1183
+ { name: 'LeftForeArm', parent: 15, position: [0.18 + 0.28 * s, 1.44 - 0.28 * s, 0] },
1184
+ { name: 'LeftHand', parent: 16, position: [0.18 + 0.54 * s, 1.44 - 0.54 * s, 0] },
1185
+ ];
1186
+ const first = fitHuman(rig);
1187
+ // A clip frame that hangs the arm 10 degrees out and drops the collarbone 6 degrees from the A pose rest.
1188
+ const hang = poseFromAngles(first, {
1189
+ l_shoulder: { flexion: 0, abduction: 10, rotation: 0 },
1190
+ l_sternoclavicular: { flexion: -6, abduction: 4, rotation: 0 },
1191
+ });
1192
+ const drop = rhythmDrops(first, [hang]);
1193
+ const body = fitAnatomy(rig, { species: human, drop });
1194
+ console.log(drop.l_sternoclavicular.map(Math.round), Math.round(jointAngles(body).l_sternoclavicular.flexion)); // [ 8, 5 ] 6
1195
+ ```
1196
+
1197
+ Limits of the fit, stated plainly:
1198
+
1199
+ - A straight limb with no bent joint and no knuckle bones shows no roll in its joint positions. The fit then takes the
1200
+ limb as unrolled (in a T pose with the palms down the elbow bends forward). Motion capture skeletons are often
1201
+ rolled: read from the clips in this repository, the CMU skeleton's upper arms are rolled 15.7 to 18.8 degrees, and
1202
+ without that its elbows seem to bend up to 38 degrees sideways. `hingeRolls` reads the roll from the motion.
1203
+ - A joint whose zero is a direction in the body (shoulder, hip, thumb base) needs the joint at the far end of its
1204
+ segment mapped. Without it the joint is left unlimited rather than guessed.
1205
+ - A modelled bend of under 5 degrees is read as straight; from 5 to 20 degrees it sets the hinge side only when it is
1206
+ within 60 degrees of the anatomical side; from 20 degrees it always does.
1207
+ - When the left and right names disagree with the way the feet point, the feet win and `body.mirrored` is true.
1208
+ - `poseLimits`, `ikLimits`, `ragdollJoints` and `kinematicsLimits` give a joint that reaches further one way than the
1209
+ other the nearest cone the older forms can hold; `clampPose` holds the exact reach.
1210
+ - The species is passed as its table (`species: human`), not by name, so the core entry loads no table.
1211
+
1212
+ Sources: ISO/IEC 19774-1:2019 (HAnim); Wu et al. 2002 and 2005 (ISB joint coordinate systems); Grood and Suntay 1983;
1213
+ Baerlocher 2001 and Dobrowolski 2015 (swing and twist); Grassia 1998; Wilhelms and Van Gelder 2001 (reach limits);
1214
+ Akhter and Black 2015 (pose-conditioned limits, the idea only); Soucie et al. 2011 (CDC); AAOS 1965 and the AMA
1215
+ Guides, 5th edition, through the pages each row names; Paraskevas et al. 2004; Inman, Saunders and Abbott 1944;
1216
+ Ludewig et al. 2009; White and Panjabi 1990; Pearcy and Tibrewal 1984; Gordon et al., ANSUR II; de Leva 1996; Drillis
1217
+ and Contini 1966 through Winter 2009. Full citations are in `human.sources` and [docs/clean-room.md](../../docs/clean-room.md).
1218
+
1219
+ ## Pose checks (`margoengine/rigging/validate`)
1220
+
1221
+ The pose checker tells an artist what is wrong with a pose or a clip before anyone has to see it by eye. It works on
1222
+ any body fitted by `fitAnatomy` or `fitHuman`, so it reads Character Creator, Mixamo, CMU, VRM and the other named rigs
1223
+ the same way. Every issue names the joint and its bone, the motion, the value against its limit, how far past it is,
1224
+ the limit's source row (CDC 2011, AAOS 1965 and so on), the frame time in a clip and a help link.
1225
+
1226
+ ```ts
1227
+ import type { RigJoint } from 'margoengine/rigging';
1228
+ import { poseFromAngles } from 'margoengine/rigging/anatomy';
1229
+ import { fitHuman } from 'margoengine/rigging/anatomy/human';
1230
+ import { checkClip, checkPose, formatPoseReport } from 'margoengine/rigging/validate';
1231
+
1232
+ const rig: RigJoint[] = [
1233
+ { name: 'Hips', parent: -1, position: [0, 1, 0] },
1234
+ { name: 'Spine', parent: 0, position: [0, 1.1, 0] },
1235
+ { name: 'Head', parent: 1, position: [0, 1.6, 0] },
1236
+ { name: 'LeftUpLeg', parent: 0, position: [0.1, 0.95, 0] },
1237
+ { name: 'RightUpLeg', parent: 0, position: [-0.1, 0.95, 0] },
1238
+ { name: 'LeftArm', parent: 1, position: [0.2, 1.45, 0] },
1239
+ { name: 'LeftForeArm', parent: 5, position: [0.48, 1.45, 0] },
1240
+ { name: 'LeftHand', parent: 6, position: [0.74, 1.45, 0] },
1241
+ ];
1242
+ const body = fitHuman(rig);
1243
+ // An elbow folded 30 degrees back: past its 5 degree stop, so an error.
1244
+ const report = checkPose(body, poseFromAngles(body, { l_elbow: { flexion: -30 } }));
1245
+ console.log(report.passed, formatPoseReport(report));
1246
+ // A whole take, frame by frame: one row per fault with its frames, its worst frame and a total.
1247
+ const frames = [0, 40, 80, 120].map((flexion) => poseFromAngles(body, { l_elbow: { flexion } }));
1248
+ const clip = checkClip(body, frames, { fps: 30 });
1249
+ console.log(clip.passed, clip.summary.length);
1250
+ ```
1251
+
1252
+ `checkPose(body, pose, options)` returns `{ passed, errors, warnings, issues }`; `checkClip(body, frames, options)`
1253
+ takes an array (or any iterable) of local poses, or a sampler `(time, out) => void` with `duration`; every issue
1254
+ carries its `frame` and `time`, and the report adds a `summary` row per joint, motion and fault (how many frames, the
1255
+ first and last time, the worst issue), errors first, and the clip's `frames` and `fps`. `assertPose` and `assertClip` throw a coded `failed` error carrying the report for a
1256
+ test or an export step. `checkProportions(body)` checks the fitted rest shape itself. `formatPoseReport` prints any
1257
+ report, one line per issue.
1258
+
1259
+ | Code | Severity | What it means |
1260
+ | --- | --- | --- |
1261
+ | `out-of-range` | error past the stop, warning past the clinical range | A swing past the table's range. |
1262
+ | `hinge-reversed` | error past the stop, warning past straight | An elbow or knee bent the wrong way. |
1263
+ | `hinge-sideways` | as above | A hinge turned off its plane (a knee bent sideways). |
1264
+ | `twist-out-of-range` | as above | A bone twisted about its own length past its range. |
1265
+ | `bone-stretch` | error | A bone longer or shorter than at rest by more than `stretch` (1 percent), or a scaled bone. |
1266
+ | `ground-penetration` | error past `sink` | A joint or a skin point (`points`) under `ground`. |
1267
+ | `floating` | warning | A named support (`supports`) more than `float` (6 percent of stature) above `ground`. |
1268
+ | `self-penetration` | error | Two body volumes (the trunk and the limb segments, from ANSUR II girths, shrunk by `shrink`) overlap. |
1269
+ | `foot-slide` | error | A planted foot moving sideways faster than `slide` (clip only). |
1270
+ | `pop` | error | A joint turning faster than `maxSpeed`, a one-frame step or a one-frame blip (clip only). |
1271
+ | `proportion` | error | A rest segment outside its ANSUR II band (`checkProportions`). |
1272
+ | `asymmetry` | warning | Left and right segments differ by more than 5 percent (`checkProportions`). |
1273
+
1274
+ Options, with their defaults:
1275
+
1276
+ - `tier`: `'both'` reports errors past the stops and warnings past the clinical range; `'structural'` or `'normal'`
1277
+ reports one tier.
1278
+ - `tolerance`: 0.5 degrees a joint may pass a limit before it is reported.
1279
+ - `ground`: null, no ground check; a number is the floor height along the body's up axis.
1280
+ - `points`: none; skin or mesh points in world units, checked against the ground.
1281
+ - `supports`: none; joint ids that should touch the ground (a seated pose names its pelvis or feet).
1282
+ - `float`: 0.06 of stature; `sink`: 0.002 of stature.
1283
+ - `volumes`: true; `shrink`: 0.7 of each measured radius, so clothes and soft tissue are not read as a collision.
1284
+ - `stretch`: 0.01, the share a bone may change length.
1285
+ - In a clip: `fps` 30, `start` 0, `duration` (needed for a sampler), `velocity` (the root's speed, for clips played in
1286
+ place), `maxSpeed` 9,000 degrees per second (Fleisig 2017, a pitcher's shoulder, the mean plus three standard
1287
+ deviations), `contact` 0.02 of stature, `slide` 0.1 of stature per second.
1288
+
1289
+ Limits of the checks, stated plainly:
1290
+
1291
+ - The volume check is capsules, not the mesh: it catches an arm through the chest or one leg through the other, not a
1292
+ finger through a sleeve. Same-side arm against thigh is left out, because a hanging arm rests on it.
1293
+ - A foot is read as planted when it stays within `contact` of its lowest height for three frames (Kovar 2002), so a
1294
+ clip whose feet never come near their lowest point is not checked for sliding.
1295
+ - An elbow or knee is reported past straight from 0.5 degrees, even though its clinical range allows a little more
1296
+ (CDC 2011 lists 4.7 degrees for the elbow): a mesh elbow past straight looks broken, so the checker warns and the stop decides
1297
+ the error.
1298
+
1299
+ Sources: Gordon et al., ANSUR II (girths, depths and breadths); Ericson 2005, section 5.1.9 (segment closest points);
1300
+ Kovar, Schreiner and Gleicher 2002 (footskate); Fleisig et al. 2017 (peak joint speeds); and the anatomy table's
1301
+ sources above. Full citations are in [docs/clean-room.md](../../docs/clean-room.md).
1302
+
1303
+ ## Coupled motion (`margoengine/rigging/coupling`)
1304
+
1305
+ In a real body some joints move with another one. The collarbone and shoulder blade rise with the arm (the
1306
+ scapulohumeral rhythm), the skin of the forearm twists along its length with the hand, the last joint of a finger
1307
+ curls with the middle one, a trunk or neck bend is shared by its levels, and a straightening knee screws home.
1308
+ `couplePose` drives those followers on any fitted body from the numbers in the species table (`human.couplings`), so
1309
+ a clip, an IK solve or a retarget that only turns the arm still gets a moving shoulder girdle.
1310
+
1311
+ ```ts
1312
+ import type { RigJoint } from 'margoengine/rigging';
1313
+ import { jointAngles, poseFromAngles } from 'margoengine/rigging/anatomy';
1314
+ import { fitHuman } from 'margoengine/rigging/anatomy/human';
1315
+ import { type CouplingIssue, couplePose, twistBones } from 'margoengine/rigging/coupling';
1316
+
1317
+ const rig: RigJoint[] = [
1318
+ { name: 'Hips', parent: -1, position: [0, 1, 0] },
1319
+ { name: 'Spine', parent: 0, position: [0, 1.1, 0] },
1320
+ { name: 'Neck', parent: 1, position: [0, 1.5, 0] },
1321
+ { name: 'Head', parent: 2, position: [0, 1.6, 0] },
1322
+ { name: 'LeftUpLeg', parent: 0, position: [0.1, 0.95, 0] },
1323
+ { name: 'RightUpLeg', parent: 0, position: [-0.1, 0.95, 0] },
1324
+ { name: 'LeftShoulder', parent: 1, position: [0.03, 1.44, 0.02] },
1325
+ { name: 'LeftArm', parent: 6, position: [0.2, 1.45, 0] },
1326
+ { name: 'LeftForeArm', parent: 7, position: [0.48, 1.45, 0] },
1327
+ { name: 'LeftHand', parent: 8, position: [0.74, 1.45, 0] },
1328
+ ];
1329
+ const body = fitHuman(rig);
1330
+ // The arm raised 170 degrees to the side; the collarbone is left where the pose had it.
1331
+ const pose = poseFromAngles(body, { l_shoulder: { abduction: 170 } });
1332
+ const driven: CouplingIssue[] = [];
1333
+ couplePose(body, pose, {}, driven);
1334
+ const angles = jointAngles(body, pose);
1335
+ // The collarbone has risen about 11 degrees, drawn back about 20 and turned back about 28; the arm still reads 170.
1336
+ console.log(driven, angles.l_sternoclavicular, angles.l_shoulder.abduction);
1337
+ console.log(twistBones(body)); // this rig has no twist bones
1338
+ ```
1339
+
1340
+ A rule fills in only what the pose leaves out: a follower the pose holds at its rest or at its anatomical neutral is
1341
+ driven by its driver's change from the same base, so the rest pose stays the rest pose, and a clip that animates the
1342
+ collarbone or a finger tip itself keeps its own motion. The shoulder's angles are read against the thorax, so the arm
1343
+ points where the pose put it while the girdle under it moves. `CouplingOptions` switches each rule off on its own:
1344
+ `girdle`, `twist`, `fingers`, `spine` and `knee`, all `true` by default.
1345
+
1346
+ | Rule | Follower | Numbers and source |
1347
+ | --- | --- | --- |
1348
+ | `shoulder-girdle` | collarbone, then shoulder blade | Elevation and retraction from Ludewig 2009 (bone pins) at 0, 30 and 120 degrees of arm elevation, held past 120; 31 degrees of posterior clavicle rotation from 90 to 180 degrees (Ludewig 2009, the late turn Inman 1944 describes); the scapula's 11 degrees of upward rotation, 8 of internal rotation and 19 of posterior tilt on the clavicle from 30 to 120 degrees (Ludewig 2009, McClure 2001) |
1349
+ | `limb-twist` | twist bones of the upper arm, forearm, thigh and shin | Each carries the share of its place along the segment (Kapandji); found from the rig, no naming needed (`twistBones`) |
1350
+ | `finger-curl` | distal finger joints | Two thirds of the middle joint (Rijpkema and Girard 1991) |
1351
+ | `spine-share` | the trunk and neck levels | A bend one level holds is shared by every level by the table's level weights (White and Panjabi 1990); the top of the run keeps its world turn |
1352
+ | `screw-home` | the knee's axial turn | The tibia turns out 11.5 degrees over the last 20 degrees of extension (the RSA range Kim 2015 reports) |
1353
+
1354
+ `addCoupling(animator, body, options)` runs `couplePose` on an Animator every frame, after its clips and the solvers
1355
+ added before it, and returns the remover. `addPerson` in `@margoengine/humans` adds it by default before the anatomy
1356
+ limits (`anatomy: {coupling: false}` leaves it off). An IK solver added after it moves the arm after the coupling, so
1357
+ the collarbone follows the clip's arm, not the IK's.
1358
+
1359
+ Wrist and finger tenodesis (fingers that curl as the wrist extends) is not coupled: no measured open source for its
1360
+ ratio was found, see `KB-RIG-TENODESIS1` in `docs/known-bugs.md`.
1361
+
1362
+ ## Swimming (`margoengine/rigging/swim`)
1363
+
1364
+ `createSwimRig` creates a head-to-tail chain in metres, with +Y up and +Z forward. A shark or reef fish sweeps laterally.
1365
+ A dolphin or humpback flexes in the vertical plane and feathers its flukes. The ray profile supplies fin hinges by
1366
+ default. Custom fin hinges may include a distal joint to introduce a delayed second bend. Use arbitrary
1367
+ increasing station fractions to match measured landmark spacing, or choose a uniform segment count. Feed the local
1368
+ TRS frames to your skin or bake quaternion keys into an animation. Update the caller's world path independently.
1369
+
1370
+ ```ts
1371
+ import { createSwimRig, sampleSwimPose, swimCadence } from 'margoengine/rigging/swim';
1372
+ const rig = createSwimRig('reef-shark', { length: 1.4, segments: 28 });
1373
+ const phase = 0.25 * swimCadence(rig, 0.9);
1374
+ const pose = sampleSwimPose(rig, { phase, effort: 0.8, turn: 0.1 });
1375
+ console.log(rig.names.length, pose.length);
1376
+ ```
1377
+
1378
+ With variable speed, accumulate phase across steps or sample a continuous phase curve. Fade effort to zero while
1379
+ coasting. `swimCadence` estimates cruising frequency from speed and the profile's peak-to-peak tail or fin excursion.
1380
+ The profiles are kinematic. They illustrate tail and fin mechanics and leave thrust, buoyancy, ecological behaviour
1381
+ and model-specific skin weights to the caller. The travelling wave and constant-length spine draw on [Lighthill,
1382
+ Large-Amplitude Elongated-Body Theory of Fish Locomotion (1971)](https://doi.org/10.1098/rspb.1971.0085),
1383
+ [Wilga and Lauder, Function of the Heterocercal Tail in Sharks (2002)](https://bpb-us-e1.wpmucdn.com/sites.harvard.edu/dist/6/58/files/2022/03/WilgaLauder2002.pdf),
1384
+ [Fish, Power Output and Propulsive Efficiency of Swimming Bottlenose Dolphins (1993)](https://doi.org/10.1242/jeb.185.1.179),
1385
+ [Gazzola, Argentina and Mahadevan, Scaling Macroscopic Aquatic Locomotion (2014)](https://doi.org/10.1038/nphys3078),
1386
+ [Smits, Undulatory and Oscillatory Swimming (2019)](https://doi.org/10.1017/jfm.2019.284),
1387
+ [Segre et al., A Hydrodynamically Active Flipper-Stroke in Humpback Whales (2017)](https://pubmed.ncbi.nlm.nih.gov/28697357/),
1388
+ and [Blevins and Lauder, Rajiform Locomotion in the Freshwater Stingray Potamotrygon orbignyi (2012)](https://bpb-us-e1.wpmucdn.com/sites.harvard.edu/dist/6/58/files/2022/03/Blevins.Lauder.2012.pdf).
1389
+
1390
+ ## Test character
1391
+
1392
+ The examples above run as written against an original test character the README runner makes
1393
+ (`scripts/support/readme-humanoid.mjs`): a skinned figure of boxes with Mixamo-named bones (`/character.glb`,
1394
+ `/rigged.glb`, `/mixamo-walk.glb`) or Godot humanoid-profile names (`/godot-hero.glb`), the 52 ARKit face shapes,
1395
+ elbow and shoulder correctives, `Hair1` to `Hair3`, `LeftEarring` and `Belly` bones, and `Idle` and `Walk` clips;
1396
+ `/avatar.vrm` is the same figure as a VRM 1.0 avatar with face shapes under other names (`Mouth_Open`, `Blink_L`,
1397
+ `Blink_R`, `Lash_L`). Mixamo is a trademark of Adobe Inc. and Godot of the Godot Foundation; Margo is not affiliated
1398
+ with them and uses only their published bone names.
1399
+
1400
+ ## Sources
1401
+
1402
+ Written clean room from the published papers listed in [docs/clean-room.md](../../docs/clean-room.md#rigging-margoenginerigging).
1403
+
1404
+ ## Film time
1405
+
1406
+ `MToon.advanceTime(delta)` moves the UV scroll and rotation clock (`mtoon.time`); the frame update runs it, so `seek` from `@margoengine/cutscene/seek` starts a film scene on the UV phase a continuous run shows.
1407
+
1408
+ ## Physical strand spring bones
1409
+
1410
+ The optional strand rig binds weighted bones to an SI fibre model with gravity, drag,
1411
+ ground, and body contact. Load it through the existing `SpringAccess` or attach it after
1412
+ an `Animator` pose with `addStrandSpringRig(animator, options)`.
1413
+
1414
+ ```ts
1415
+ import { Engine } from 'margoengine';
1416
+ import { StrandSpringRig } from 'margoengine/rigging/strand-springs';
1417
+ import { springAccess } from 'margoengine/rigging/springs';
1418
+
1419
+ const engine = await Engine.create(document.querySelector('canvas')!);
1420
+ const scalp = engine.createMesh().setPosition([0, 1.72, 0]);
1421
+ const root = engine.createMesh().setParent(scalp).setPosition([0, 0, -0.12]);
1422
+ const tip = engine.createMesh().setParent(root).setPosition([0, -0.24, -0.02]);
1423
+ const rig = await StrandSpringRig.load(springAccess({ root: scalp, nodes: [scalp, root, tip] }), {
1424
+ chains: [{ joints: [1, 2], radius: 0.006, dragWidth: 0.025 }],
1425
+ });
1426
+ scalp.setPosition([0.08, 1.72, 0]);
1427
+ rig.advance(20); // 20 frames on the 240 Hz world clock
1428
+ console.log(rig.solver.sample(0, 1).position);
1429
+ ```
1430
+
1431
+ Pass the chain's ordered glTF indices in `joints`. A single attached earring or antenna
1432
+ also takes a `tip` in its bone's local metres. Bone and ancestor transforms require positive
1433
+ uniform scales. Each bundle can override its native radius, density, material and drag
1434
+ width. The physics controls are the same as in the physics package's strand guide entry.
1435
+ Set the same `wind` and `bed` fields as the surrounding scene. Each `colliders` entry can
1436
+ be world-space or attached to a glTF node and moves with that node.
1437
+
1438
+ For a VRM avatar, get the authored joint and collider lists from `vrmSprings(avatar)`.
1439
+ Use `addVRM(animation, avatar, { animator, springs: false })` with the physical attachment
1440
+ and supply the matching collider list. The physical rig takes its own fibre properties
1441
+ in metres and pascals. A pure per-chain `anchor(time)` gives exact replay across display
1442
+ rates and a `seek(frame)` from the initial snapshot. The default live bone attachments
1443
+ sample the current animation pose. To replay those, evaluate the same animation frames in
1444
+ the same order. Call `dispose()` on the Animator attachment to stop its updates.