@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
@@ -0,0 +1,78 @@
1
+ /** Humanoid bones, by the names this package maps every preset to. */
2
+ export type HumanoidBone = 'hips' | 'spine' | 'chest' | 'upperChest' | 'neck' | 'head' | 'jaw' | `${'left' | 'right'}${'Eye' | 'Shoulder' | 'UpperArm' | 'LowerArm' | 'Hand' | 'UpperLeg' | 'LowerLeg' | 'Foot' | 'Toes' | `${'Thumb'}${'Metacarpal' | 'Proximal' | 'Distal'}` | `${'Index' | 'Middle' | 'Ring' | 'Little'}${'Proximal' | 'Intermediate' | 'Distal'}`}`;
3
+ /** Skeleton naming conventions with a preset. */
4
+ export type SkeletonPreset = 'mixamo' | 'godot' | 'roblox' | 'margo' | 'cmu' | 'mpfb' | 'characterCreator' | 'humanoid';
5
+ /** Every humanoid bone, parents before children. */
6
+ export declare const HUMANOID_BONES: readonly HumanoidBone[];
7
+ /**
8
+ * Which humanoid bone each of `names` is under `preset`, as bone -> index into `names`. Matching ignores case and rig
9
+ * prefixes (`mixamorig:`, `mixamorig1_`, `Armature|`); names the preset does not know are left out, and the first of
10
+ * two names for one bone wins.
11
+ * @throws TypeError unless `names` is an array; RangeError for an unknown preset.
12
+ */
13
+ export declare function humanoidBones(names: readonly string[], preset: SkeletonPreset): Map<HumanoidBone, number>;
14
+ /** {@link detectSkeleton}'s result. */
15
+ export interface SkeletonMatch {
16
+ /** The preset whose names match best. */
17
+ readonly preset: SkeletonPreset;
18
+ /** Humanoid bones found under it. */
19
+ readonly bones: number;
20
+ }
21
+ /**
22
+ * The preset whose bone names match the most of `names` (Mixamo with any `mixamorig` prefix, Godot's humanoid profile,
23
+ * Roblox R15, Margo's humanoidJoints, the CMU motion capture skeleton, MPFB, Character Creator's CC3+ skeleton, or the humanoid names themselves), or null when none finds hips and a head.
24
+ */
25
+ export declare function detectSkeleton(names: readonly string[]): SkeletonMatch | null;
26
+ /** A rig as `@margoengine/animation`'s `retargetRig` makes it: names, parents and a local rest pose (10 per bone). */
27
+ export interface RetargetRigData {
28
+ /** Bone names; a bone's index is its position here. */
29
+ readonly names: readonly string[];
30
+ /** Parent bone per bone, -1 at the top. */
31
+ readonly parents: readonly number[];
32
+ /** Local rest pose, 10 numbers per bone: translation xyz, rotation quaternion xyzw, scale xyz. */
33
+ readonly rest: Float64Array;
34
+ }
35
+ /** Options for {@link prepareRetarget}. */
36
+ export interface PrepareRetargetOptions {
37
+ /** The source's naming; detected from its bone names when omitted. */
38
+ from?: SkeletonPreset;
39
+ /** The target's naming; detected when omitted. */
40
+ to?: SkeletonPreset;
41
+ /**
42
+ * Turn the target's reference pose so each mapped limb bone (arms, hands, fingers, legs, feet) points the way its source
43
+ * bone does at rest (default true): a T-pose source then drives an A-pose target into the same T-pose. The trunk, neck
44
+ * and collarbones keep the target's own rest, since their directions are body layout, not pose. A source hand with no
45
+ * finger bones below it (a BVH End Site, an ASF or Xsens hand segment) is one rigid segment, so the target's hand and
46
+ * long fingers are laid straight along it, in line with the source forearm when the source has no finger base at all;
47
+ * thumbs keep the target's rest. False keeps the target's whole rest pose.
48
+ */
49
+ alignRest?: boolean;
50
+ }
51
+ /** {@link prepareRetarget}'s result: what `new Retarget(source, target, {names, hip})` takes. */
52
+ export interface PreparedRetarget {
53
+ /** The target rig to pass to Retarget: the given one, or with its reference pose aligned to the source's. */
54
+ readonly target: RetargetRigData;
55
+ /** Target bone name -> source bone name; '' leaves a target bone at rest. */
56
+ readonly names: Record<string, string>;
57
+ /** The target's hip bone name, when both have hips. */
58
+ readonly hip?: string;
59
+ /** The source's naming, given or detected. */
60
+ readonly from: SkeletonPreset;
61
+ /** The target's naming, given or detected. */
62
+ readonly to: SkeletonPreset;
63
+ /** Humanoid bones the target has but the source does not (they stay at rest). */
64
+ readonly unmapped: readonly HumanoidBone[];
65
+ /**
66
+ * Unmapped target bone names whose rest the alignment turned (fingers laid along a fingerless source hand). Retarget
67
+ * reads this as its `hold` option and keeps them at the aligned rest, so they do not stay in the target's own pose.
68
+ */
69
+ readonly hold: readonly string[];
70
+ }
71
+ /**
72
+ * Maps a source skeleton's bones onto a target's by their presets (detected from the names unless given) and, by
73
+ * default, aligns the target's reference pose to the source's. Pass the result to `@margoengine/animation`'s
74
+ * `Retarget`: `new Retarget(source, prepared.target, prepared)`. Both rigs' model spaces must face the same way.
75
+ * @throws TypeError for a rig without names and parents; RangeError for a bad rest pose or parent, a naming that is
76
+ * not recognised (pass `from` / `to`) or presets that map no bones.
77
+ */
78
+ export declare function prepareRetarget(source: RetargetRigData, target: RetargetRigData, options?: PrepareRetargetOptions): PreparedRetarget;
@@ -0,0 +1,375 @@
1
+ import { r as e, s as t } from "./rig-BawZ5OLb.js";
2
+ import { rotationBetween as n } from "./ik.js";
3
+ import { axisAngleToQuaternion as r, multiplyQuaternions as i, normalizeQuaternion as a, rotateByQuaternion as o } from "@margoengine/math/quat";
4
+ import { cross as s, dot as c, length as l, normalize as u, scale as d, sub as f } from "@margoengine/math/vec3";
5
+ //#region src/retarget.ts
6
+ var p = ["left", "right"], m = [
7
+ "Index",
8
+ "Middle",
9
+ "Ring",
10
+ "Little"
11
+ ], h = [
12
+ "Proximal",
13
+ "Intermediate",
14
+ "Distal"
15
+ ], g = (e) => e[0].toUpperCase() + e.slice(1), _ = [
16
+ "hips",
17
+ "spine",
18
+ "chest",
19
+ "upperChest",
20
+ "neck",
21
+ "head",
22
+ "jaw",
23
+ "leftEye",
24
+ "rightEye",
25
+ ...p.flatMap((e) => [
26
+ "Shoulder",
27
+ "UpperArm",
28
+ "LowerArm",
29
+ "Hand",
30
+ "ThumbMetacarpal",
31
+ "ThumbProximal",
32
+ "ThumbDistal"
33
+ ].map((t) => `${e}${t}`).concat(m.flatMap((t) => h.map((n) => `${e}${t}${n}`)))),
34
+ ...p.flatMap((e) => [
35
+ "UpperLeg",
36
+ "LowerLeg",
37
+ "Foot",
38
+ "Toes"
39
+ ].map((t) => `${e}${t}`))
40
+ ], v = {
41
+ hips: ["spine"],
42
+ spine: [
43
+ "chest",
44
+ "upperChest",
45
+ "neck"
46
+ ],
47
+ chest: ["upperChest", "neck"],
48
+ upperChest: ["neck"],
49
+ neck: ["head"],
50
+ ...Object.fromEntries(p.flatMap((e) => [
51
+ [`${e}Shoulder`, [`${e}UpperArm`]],
52
+ [`${e}UpperArm`, [`${e}LowerArm`]],
53
+ [`${e}LowerArm`, [`${e}Hand`]],
54
+ [`${e}Hand`, [`${e}MiddleProximal`]],
55
+ [`${e}ThumbMetacarpal`, [`${e}ThumbProximal`]],
56
+ [`${e}ThumbProximal`, [`${e}ThumbDistal`]],
57
+ ...m.flatMap((t) => [[`${e}${t}Proximal`, [`${e}${t}Intermediate`]], [`${e}${t}Intermediate`, [`${e}${t}Distal`]]]),
58
+ [`${e}UpperLeg`, [`${e}LowerLeg`]],
59
+ [`${e}LowerLeg`, [`${e}Foot`]],
60
+ [`${e}Foot`, [`${e}Toes`]]
61
+ ]))
62
+ }, y = /* @__PURE__ */ new Set([
63
+ "hips",
64
+ "spine",
65
+ "chest",
66
+ "upperChest",
67
+ "neck",
68
+ "leftShoulder",
69
+ "rightShoulder"
70
+ ]), b = {
71
+ humanoid: Object.fromEntries(_.map((e) => [e, e])),
72
+ mixamo: Object.fromEntries([
73
+ ["hips", "Hips"],
74
+ ["spine", "Spine"],
75
+ ["chest", "Spine1"],
76
+ ["upperChest", "Spine2"],
77
+ ["neck", "Neck"],
78
+ ["head", "Head"],
79
+ ...p.flatMap((e) => {
80
+ let t = g(e);
81
+ return [
82
+ [`${e}Eye`, `${t}Eye`],
83
+ [`${e}Shoulder`, `${t}Shoulder`],
84
+ [`${e}UpperArm`, `${t}Arm`],
85
+ [`${e}LowerArm`, `${t}ForeArm`],
86
+ [`${e}Hand`, `${t}Hand`],
87
+ [`${e}ThumbMetacarpal`, `${t}HandThumb1`],
88
+ [`${e}ThumbProximal`, `${t}HandThumb2`],
89
+ [`${e}ThumbDistal`, `${t}HandThumb3`],
90
+ ...m.flatMap((n) => h.map((r, i) => [`${e}${n}${r}`, `${t}Hand${n === "Little" ? "Pinky" : n}${i + 1}`])),
91
+ [`${e}UpperLeg`, `${t}UpLeg`],
92
+ [`${e}LowerLeg`, `${t}Leg`],
93
+ [`${e}Foot`, `${t}Foot`],
94
+ [`${e}Toes`, `${t}ToeBase`]
95
+ ];
96
+ })
97
+ ]),
98
+ godot: Object.fromEntries(_.map((e) => [e, g(e)])),
99
+ roblox: Object.fromEntries([
100
+ ["hips", "LowerTorso"],
101
+ ["spine", "UpperTorso"],
102
+ ["head", "Head"],
103
+ ...p.flatMap((e) => {
104
+ let t = g(e);
105
+ return [
106
+ [`${e}UpperArm`, `${t}UpperArm`],
107
+ [`${e}LowerArm`, `${t}LowerArm`],
108
+ [`${e}Hand`, `${t}Hand`],
109
+ [`${e}UpperLeg`, `${t}UpperLeg`],
110
+ [`${e}LowerLeg`, `${t}LowerLeg`],
111
+ [`${e}Foot`, `${t}Foot`]
112
+ ];
113
+ })
114
+ ]),
115
+ cmu: Object.fromEntries([
116
+ ["hips", "root"],
117
+ ["spine", "lowerback"],
118
+ ["chest", "upperback"],
119
+ ["upperChest", "thorax"],
120
+ ["neck", "lowerneck"],
121
+ ["head", "head"],
122
+ ...p.flatMap((e) => {
123
+ let t = e[0];
124
+ return [
125
+ [`${e}Shoulder`, `${t}clavicle`],
126
+ [`${e}UpperArm`, `${t}humerus`],
127
+ [`${e}LowerArm`, `${t}radius`],
128
+ [`${e}Hand`, `${t}wrist`],
129
+ [`${e}MiddleProximal`, `${t}fingers`],
130
+ [`${e}UpperLeg`, `${t}femur`],
131
+ [`${e}LowerLeg`, `${t}tibia`],
132
+ [`${e}Foot`, `${t}foot`],
133
+ [`${e}Toes`, `${t}toes`]
134
+ ];
135
+ })
136
+ ]),
137
+ mpfb: Object.fromEntries([
138
+ ["hips", "root"],
139
+ ["spine", "spine05"],
140
+ ["chest", "spine03"],
141
+ ["upperChest", "spine01"],
142
+ ["neck", "neck01"],
143
+ ["head", "head"],
144
+ ...p.flatMap((e) => {
145
+ let t = e === "left" ? "L" : "R";
146
+ return [
147
+ [`${e}Shoulder`, `clavicle.${t}`],
148
+ [`${e}UpperArm`, `upperarm01.${t}`],
149
+ [`${e}LowerArm`, `lowerarm01.${t}`],
150
+ [`${e}Hand`, `wrist.${t}`],
151
+ [`${e}ThumbMetacarpal`, `finger1-1.${t}`],
152
+ [`${e}ThumbProximal`, `finger1-2.${t}`],
153
+ [`${e}ThumbDistal`, `finger1-3.${t}`],
154
+ ...m.flatMap((n, r) => h.map((i, a) => [`${e}${n}${i}`, `finger${r + 2}-${a + 1}.${t}`])),
155
+ [`${e}UpperLeg`, `upperleg01.${t}`],
156
+ [`${e}LowerLeg`, `lowerleg01.${t}`],
157
+ [`${e}Foot`, `foot.${t}`],
158
+ [`${e}Toes`, `toe1-1.${t}`]
159
+ ];
160
+ })
161
+ ]),
162
+ characterCreator: Object.fromEntries([
163
+ ["hips", "CC_Base_Hip"],
164
+ ["spine", "CC_Base_Waist"],
165
+ ["chest", "CC_Base_Spine01"],
166
+ ["upperChest", "CC_Base_Spine02"],
167
+ ["neck", "CC_Base_NeckTwist01"],
168
+ ["head", "CC_Base_Head"],
169
+ ["jaw", "CC_Base_JawRoot"],
170
+ ...p.flatMap((e) => {
171
+ let t = `CC_Base_${e === "left" ? "L" : "R"}_`;
172
+ return [
173
+ [`${e}Eye`, `${t}Eye`],
174
+ [`${e}Shoulder`, `${t}Clavicle`],
175
+ [`${e}UpperArm`, `${t}Upperarm`],
176
+ [`${e}LowerArm`, `${t}Forearm`],
177
+ [`${e}Hand`, `${t}Hand`],
178
+ [`${e}ThumbMetacarpal`, `${t}Thumb1`],
179
+ [`${e}ThumbProximal`, `${t}Thumb2`],
180
+ [`${e}ThumbDistal`, `${t}Thumb3`],
181
+ ...m.flatMap((n) => h.map((r, i) => [`${e}${n}${r}`, `${t}${n === "Little" ? "Pinky" : n === "Middle" ? "Mid" : n}${i + 1}`])),
182
+ [`${e}UpperLeg`, `${t}Thigh`],
183
+ [`${e}LowerLeg`, `${t}Calf`],
184
+ [`${e}Foot`, `${t}Foot`],
185
+ [`${e}Toes`, `${t}ToeBase`]
186
+ ];
187
+ })
188
+ ]),
189
+ margo: Object.fromEntries([
190
+ ["hips", "hips"],
191
+ ["spine", "spine"],
192
+ ["chest", "chest"],
193
+ ["neck", "neck"],
194
+ ["head", "head"],
195
+ ...p.flatMap((e) => [
196
+ [`${e}UpperArm`, `${e}Shoulder`],
197
+ [`${e}LowerArm`, `${e}Elbow`],
198
+ [`${e}Hand`, `${e}Wrist`],
199
+ [`${e}UpperLeg`, `${e}Hip`],
200
+ [`${e}LowerLeg`, `${e}Knee`],
201
+ [`${e}Foot`, `${e}Ankle`]
202
+ ])
203
+ ])
204
+ }, x = (e) => e.replace(/^.*[:|]/, "").replace(/^mixamorig\d*_?/i, ""), S = (e) => new Map(Object.entries(b[e]).map(([e, t]) => [x(t).toLowerCase(), e]));
205
+ function C(e, t) {
206
+ if (!Array.isArray(e)) throw TypeError("humanoidBones needs the skeleton bone names");
207
+ if (!Object.hasOwn(b, t)) throw RangeError(`Skeleton preset ${String(t)} must be one of ${Object.keys(b).join(", ")}`);
208
+ let n = S(t), r = /* @__PURE__ */ new Map();
209
+ return e.forEach((e, t) => {
210
+ let i = typeof e == "string" ? n.get(x(e).toLowerCase()) : void 0;
211
+ i && !r.has(i) && r.set(i, t);
212
+ }), r;
213
+ }
214
+ function w(e, t, n) {
215
+ let r = 0;
216
+ for (let [i, a] of n) x(e[a]) === x(b[t][i]) && r++;
217
+ return r;
218
+ }
219
+ function T(e) {
220
+ let t = null, n = -1;
221
+ for (let r of [
222
+ "mixamo",
223
+ "roblox",
224
+ "godot",
225
+ "margo",
226
+ "cmu",
227
+ "mpfb",
228
+ "characterCreator",
229
+ "humanoid"
230
+ ]) {
231
+ let i = C(e, r);
232
+ if (!i.has("hips") || !i.has("head")) continue;
233
+ let a = w(e, r, i);
234
+ (!t || i.size > t.bones || i.size === t.bones && a > n) && (t = {
235
+ preset: r,
236
+ bones: i.size
237
+ }, n = a);
238
+ }
239
+ return t;
240
+ }
241
+ function E(e, t, n = {}) {
242
+ D(e, "source"), D(t, "target");
243
+ let r = n.from ?? T(e.names)?.preset, i = n.to ?? T(t.names)?.preset;
244
+ if (!r) throw RangeError("Retarget source naming is not recognised; pass from (mixamo, godot, roblox, margo, cmu or humanoid)");
245
+ if (!i) throw RangeError("Retarget target naming is not recognised; pass to (mixamo, godot, roblox, margo, cmu or humanoid)");
246
+ let a = C(e.names, r), o = C(t.names, i), s = {}, c = [];
247
+ for (let e of t.names) s[e] = "";
248
+ for (let [n, r] of o) {
249
+ let i = /^(left|right)(Index|Ring|Little)Proximal$/.exec(n)?.[1], o = a.get(n) ?? (i ? a.get(`${i}MiddleProximal`) : void 0);
250
+ o === void 0 ? c.push(n) : s[t.names[r]] = e.names[o];
251
+ }
252
+ if (!Object.values(s).some(Boolean)) throw RangeError(`Retarget maps no bones from ${r} to ${i}; check the presets`);
253
+ let l = o.has("hips") && a.has("hips") ? t.names[o.get("hips")] : void 0, u = /* @__PURE__ */ new Set(), d = n.alignRest === !1 ? t : P(e, t, a, o, u), f = [...u].filter((e) => !s[t.names[e]]).map((e) => t.names[e]);
254
+ return {
255
+ target: d,
256
+ names: s,
257
+ ...l ? { hip: l } : {},
258
+ from: r,
259
+ to: i,
260
+ unmapped: c,
261
+ hold: f
262
+ };
263
+ }
264
+ function D(t, n) {
265
+ let r = t?.names?.length;
266
+ if (!Array.isArray(t?.names) || !Array.isArray(t.parents) || t.parents.length !== r) throw TypeError(`Retarget ${n} needs a rig with names and parents; make it with retargetRig`);
267
+ if (!(t.rest instanceof Float64Array) || t.rest.length !== r * 10 || !t.rest.every(Number.isFinite)) throw RangeError(`Retarget ${n} rest pose needs 10 finite numbers per bone`);
268
+ t.parents.forEach((e, t) => {
269
+ if (!Number.isInteger(e) || e < -1 || e >= r || e === t) throw RangeError(`Retarget ${n} bone ${t} parent ${e} is invalid; use -1 or another bone's index`);
270
+ }), e(t.parents, `Retarget ${n}`);
271
+ }
272
+ function O(n, r) {
273
+ let i = n.names.length, a = t(n.parents, r, e(n.parents, "Retarget rig")), o = Array(i), s = Array(i);
274
+ for (let e = 0; e < i; e++) o[e] = Array.from(a.rotation.subarray(e * 4, e * 4 + 4)), s[e] = Array.from(a.position.subarray(e * 3, e * 3 + 3));
275
+ return {
276
+ rotation: o,
277
+ position: s,
278
+ linear: a.linear
279
+ };
280
+ }
281
+ function k(e, t, n) {
282
+ let r = e.subarray(t * 9, t * 9 + 9), i = (e, t, n) => e[0] * (t[1] * n[2] - t[2] * n[1]) - t[0] * (e[1] * n[2] - e[2] * n[1]) + n[0] * (e[1] * t[2] - e[2] * t[1]), a = [
283
+ r[0],
284
+ r[1],
285
+ r[2]
286
+ ], o = [
287
+ r[3],
288
+ r[4],
289
+ r[5]
290
+ ], s = [
291
+ r[6],
292
+ r[7],
293
+ r[8]
294
+ ], c = i(a, o, s);
295
+ return Math.abs(c) > 1e-300 ? [
296
+ i(n, o, s) / c,
297
+ i(a, n, s) / c,
298
+ i(a, o, n) / c
299
+ ] : null;
300
+ }
301
+ function A(e, t, n) {
302
+ let r = t.get(`${e}IndexProximal`), i = t.get(`${e}LittleProximal`);
303
+ return r === void 0 || i === void 0 ? null : f(n[r], n[i]);
304
+ }
305
+ function j(e, t, n, a) {
306
+ let p = u(e), m = o(u(n), t), h = u(a), g = f(m, d(p, c(m, p))), _ = f(h, d(p, c(h, p)));
307
+ if (l(g) < 1e-9 || l(_) < 1e-9) return t;
308
+ let v = Math.atan2(c(p, s(g, _)), c(g, _));
309
+ return i(r(p, v), t);
310
+ }
311
+ var M = /^(left|right)(Hand|(Index|Middle|Ring|Little)(Proximal|Intermediate))$/;
312
+ function N(e, t, n, r) {
313
+ let i = M.exec(e)?.[1], a = v[e]?.[0];
314
+ if (!i || !a || !n.has(a)) return null;
315
+ let o = t.get(`${i}Hand`), s = t.get(`${i}MiddleProximal`), c = t.get(`${i}LowerArm`);
316
+ if (o === void 0) return null;
317
+ let [l, u] = s === void 0 ? c === void 0 ? [] : [c, o] : [o, s];
318
+ return l === void 0 || u === void 0 ? null : {
319
+ child: n.get(a),
320
+ want: [
321
+ 0,
322
+ 1,
323
+ 2
324
+ ].map((e) => r[u][e] - r[l][e])
325
+ };
326
+ }
327
+ function P(e, t, r, s, c) {
328
+ let l = new Float64Array(t.rest), u = O(e, e.rest), d = _.filter((e) => s.has(e));
329
+ for (let e of d) {
330
+ if (y.has(e)) continue;
331
+ let d = (v[e] ?? []).find((e) => s.has(e) && r.has(e)), f, p;
332
+ if (d && r.has(e)) {
333
+ let t = r.get(e), n = r.get(d);
334
+ f = s.get(d), p = [
335
+ 0,
336
+ 1,
337
+ 2
338
+ ].map((e) => u.position[n][e] - u.position[t][e]);
339
+ } else {
340
+ let t = N(e, r, s, u.position);
341
+ if (!t) continue;
342
+ f = t.child, p = t.want;
343
+ }
344
+ let m = s.get(e), h = O(t, l), g = [
345
+ 0,
346
+ 1,
347
+ 2
348
+ ].map((e) => h.position[f][e] - h.position[m][e]);
349
+ if (Math.hypot(...g) < 1e-9 || Math.hypot(...p) < 1e-9) continue;
350
+ let _ = t.parents[m], b = _ < 0 ? g : k(h.linear, _, g), x = _ < 0 ? p : k(h.linear, _, p);
351
+ if (!b || !x) continue;
352
+ let S = n(b, x);
353
+ if (e === "leftHand" || e === "rightHand") {
354
+ let t = e === "leftHand" ? "left" : "right", n = A(t, s, h.position), i = A(t, r, u.position);
355
+ if (n && i) {
356
+ let e = _ < 0 ? n : k(h.linear, _, n), t = _ < 0 ? i : k(h.linear, _, i);
357
+ e && t && (S = j(o(b, S), S, e, t));
358
+ }
359
+ }
360
+ let C = m * 10 + 3;
361
+ l.set(a(i(S, [
362
+ l[C],
363
+ l[C + 1],
364
+ l[C + 2],
365
+ l[C + 3]
366
+ ])), C), c.add(m);
367
+ }
368
+ return {
369
+ names: t.names,
370
+ parents: t.parents,
371
+ rest: l
372
+ };
373
+ }
374
+ //#endregion
375
+ export { _ as HUMANOID_BONES, T as detectSkeleton, C as humanoidBones, E as prepareRetarget };
@@ -0,0 +1,127 @@
1
+ import { multiplyQuaternions as e, rotateByQuaternion as t } from "@margoengine/math/quat";
2
+ //#region src/rig.ts
3
+ var n = 65536;
4
+ function r(e) {
5
+ if (!Array.isArray(e) || !e.length || e.length > n) throw RangeError(`A rig needs 1 to ${n} joints; pass an array of {name, parent, position}`);
6
+ let t = /* @__PURE__ */ new Set(), r = e.length;
7
+ for (let n = 0; n < r; n++) {
8
+ let i = e[n];
9
+ if (!i || typeof i.name != "string" || !i.name) throw TypeError(`Rig joint ${n} needs a unique, nonempty name; rename it`);
10
+ if (t.has(i.name)) throw TypeError(`Rig joint ${n} repeats the name ${i.name}; glTF allows that, but rig joints are found by name, so rename one`);
11
+ t.add(i.name);
12
+ let a = i.parent;
13
+ if (!Number.isInteger(a) || a < -1 || a >= r || a === n) throw RangeError(`Rig joint ${i.name} parent ${a} is invalid; use -1 or another joint's index`);
14
+ let o = i.position;
15
+ if (!o || o.length !== 3 || !Number.isFinite(o[0]) || !Number.isFinite(o[1]) || !Number.isFinite(o[2])) throw RangeError(`Rig joint ${i.name} position must be three finite numbers`);
16
+ }
17
+ return i(e.map((e) => e.parent), "Rig");
18
+ }
19
+ function i(e, t) {
20
+ let n = e.length, r = e.map(() => []);
21
+ for (let t = 0; t < n; t++) e[t] >= 0 && r[e[t]].push(t);
22
+ let i = [];
23
+ for (let t = e.flatMap((e, t) => e < 0 ? [t] : []); t.length;) {
24
+ let e = t.pop();
25
+ i.push(e);
26
+ for (let n of r[e]) t.push(n);
27
+ }
28
+ if (i.length !== n) throw RangeError(`${t} parents form a cycle; every joint must reach a root (parent -1)`);
29
+ return i;
30
+ }
31
+ function a(n, r, i) {
32
+ let a = n.length, o = new Float64Array(a * 3), s = new Float64Array(a * 4), c = new Float64Array(a * 9);
33
+ for (let a of i) {
34
+ let i = n[a], l = a * 10, u = [
35
+ r[l + 3],
36
+ r[l + 4],
37
+ r[l + 5],
38
+ r[l + 6]
39
+ ], d = [
40
+ r[l],
41
+ r[l + 1],
42
+ r[l + 2]
43
+ ], f = [
44
+ 0,
45
+ 1,
46
+ 2
47
+ ].map((e) => t([
48
+ +(e === 0),
49
+ +(e === 1),
50
+ +(e === 2)
51
+ ], u).map((t) => t * r[l + 7 + e]));
52
+ if (i < 0) {
53
+ o.set(d, a * 3), s.set(u, a * 4);
54
+ for (let e = 0; e < 3; e++) c.set(f[e], a * 9 + e * 3);
55
+ continue;
56
+ }
57
+ let p = c.subarray(i * 9, i * 9 + 9), m = (e, t, n) => {
58
+ for (let r = 0; r < 3; r++) t[n + r] = p[r] * e[0] + p[3 + r] * e[1] + p[6 + r] * e[2];
59
+ };
60
+ m(d, o, a * 3);
61
+ for (let e = 0; e < 3; e++) o[a * 3 + e] += o[i * 3 + e];
62
+ s.set(e(s.subarray(i * 4, i * 4 + 4), u), a * 4);
63
+ for (let e = 0; e < 3; e++) m(f[e], c, a * 9 + e * 3);
64
+ }
65
+ return {
66
+ position: o,
67
+ rotation: s,
68
+ linear: c
69
+ };
70
+ }
71
+ function o(e, t) {
72
+ for (let n = 0; n < e.length; n++) if (e[n].name === t) return n;
73
+ return -1;
74
+ }
75
+ function s(e, t, n) {
76
+ if (!Array.isArray(t)) throw TypeError(`${n} must be an array of joint indices or names`);
77
+ return t.map((t) => {
78
+ let r = typeof t == "string" ? o(e, t) : t;
79
+ if (!Number.isInteger(r) || r < 0 || r >= e.length) throw RangeError(`${n} names joint ${String(t)}, which the rig does not have; fix the name or index`);
80
+ return r;
81
+ });
82
+ }
83
+ function c(e) {
84
+ let { names: t, parents: n, rest: i } = e ?? {}, o = t?.length;
85
+ if (!Array.isArray(t) || !Array.isArray(n) || n.length !== o || i?.length !== o * 10) throw TypeError("rigJoints needs {names, parents, rest} with 10 rest numbers per bone (see retargetRig)");
86
+ let s = r(t.map((e, t) => ({
87
+ name: e || `bone${t}`,
88
+ parent: n[t],
89
+ position: [
90
+ 0,
91
+ 0,
92
+ 0
93
+ ]
94
+ })));
95
+ for (let e = 0; e < o; e++) for (let t = 0; t < 10; t++) if (!Number.isFinite(i[e * 10 + t])) throw RangeError(`rigJoints bone ${e} rest pose is not finite; make all 10 rest numbers finite`);
96
+ let { position: c } = a(n, i, s);
97
+ return t.map((e, t) => ({
98
+ name: e || `bone${t}`,
99
+ parent: n[t],
100
+ position: [
101
+ c[t * 3],
102
+ c[t * 3 + 1],
103
+ c[t * 3 + 2]
104
+ ]
105
+ }));
106
+ }
107
+ function l(e, t) {
108
+ let n = [], r = [], i = e.map(() => []);
109
+ return e.forEach((e, t) => {
110
+ e.parent >= 0 && i[e.parent].push(t);
111
+ }), e.forEach((a, o) => {
112
+ if (!t(o)) return;
113
+ let s = a.position, c = i[o].length ? i[o].map((t) => e[t].position) : [s];
114
+ for (let e of c) n.push(s[0], s[1], s[2], e[0], e[1], e[2]), r.push(o);
115
+ }), {
116
+ points: Float64Array.from(n),
117
+ owners: Int32Array.from(r)
118
+ };
119
+ }
120
+ function u(e, t, n, r, i, a) {
121
+ let o = t * 6, s = e[o], c = e[o + 1], l = e[o + 2], u = e[o + 3] - s, d = e[o + 4] - c, f = e[o + 5] - l, p = u * u + d * d + f * f, m = p > 0 ? ((n - s) * u + (r - c) * d + (i - l) * f) / p : 0;
122
+ m = m < 0 ? 0 : m > 1 ? 1 : m;
123
+ let h = s + u * m, g = c + d * m, _ = l + f * m;
124
+ return a && (a[0] = h, a[1] = g, a[2] = _), (n - h) ** 2 + (r - g) ** 2 + (i - _) ** 2;
125
+ }
126
+ //#endregion
127
+ export { c as a, s as i, r as n, u as o, i as r, a as s, l as t };
package/dist/rig.d.ts ADDED
@@ -0,0 +1,65 @@
1
+ import type { Vec3 } from '@margoengine/math';
2
+ /**
3
+ * A joint of a rest skeleton: the same shape as `@margoengine/exporters/skin`'s `SkinJoint`, so one array serves both.
4
+ * Positions are in the mesh's space (the space of the vertices being weighted).
5
+ */
6
+ export interface RigJoint {
7
+ /** Unique, nonempty. */
8
+ readonly name: string;
9
+ /** Index of the parent joint, or -1 for a root. */
10
+ readonly parent: number;
11
+ /** Rest position. */
12
+ readonly position: Vec3;
13
+ }
14
+ /** A bone hierarchy with local rest transforms, as `@margoengine/animation`'s `retargetRig` makes it. */
15
+ export interface RigPose {
16
+ /** Bone names; a bone's index is its position here. */
17
+ readonly names: readonly string[];
18
+ /** Parent bone per bone, -1 at the top. */
19
+ readonly parents: readonly number[];
20
+ /** Local rest pose, 10 numbers per bone: translation xyz, rotation quaternion xyzw, scale xyz. */
21
+ readonly rest: ArrayLike<number>;
22
+ }
23
+ /**
24
+ * Checks a joint array (1-65,536 joints, unique nonempty names, finite positions, parents that reach a root without a
25
+ * cycle) and returns its parent-before-child order.
26
+ * @throws TypeError for a malformed joint, RangeError for a bad parent or position.
27
+ */
28
+ export declare function checkRig(joints: readonly RigJoint[]): number[];
29
+ /**
30
+ * The parent-before-child order of a bone hierarchy (each parent -1 or another bone's index, checked by the caller).
31
+ * @throws RangeError when the parents form a cycle, so no bone on it reaches a root.
32
+ */
33
+ export declare function parentOrder(parents: readonly number[], label: string): number[];
34
+ /**
35
+ * World frames of a bone hierarchy from local transforms (10 numbers per bone: translation, rotation xyzw, scale), in
36
+ * `order` (parents first). Positions compose full matrices as glTF 2.0 (3.5.3) does, M = M_parent * T * R * S, so a
37
+ * parent's uneven scale stretches a turned child's offset along the parent's axes; `linear` is each bone's 3x3 part
38
+ * (column-major) and `rotation` the product of the local rotations.
39
+ */
40
+ export declare function worldFrames(parents: readonly number[], local: ArrayLike<number>, order: readonly number[]): {
41
+ position: Float64Array;
42
+ rotation: Float64Array;
43
+ linear: Float64Array;
44
+ };
45
+ /** Resolves joint references (indices or names) to indices. @throws RangeError for an unknown one. */
46
+ export declare function resolveJoints(joints: readonly RigJoint[], list: readonly (number | string)[], label: string): number[];
47
+ /**
48
+ * World rest positions of a {@link RigPose} (glTF nodes, a `Skeleton` or `retargetRig` output) as {@link RigJoint}s.
49
+ * Unnamed bones are named `bone<index>`. Names must be unique (rig joints are found by name, though glTF allows
50
+ * repeats): rename repeated ones first.
51
+ */
52
+ export declare function rigJoints(rig: RigPose): RigJoint[];
53
+ /**
54
+ * The bone segments the weight solvers measure distance to: per deforming joint, a segment from it to each child (a
55
+ * point at a leaf). Six numbers per segment (start xyz, end xyz) and the owning joint per segment.
56
+ */
57
+ export declare function boneSegments(joints: readonly RigJoint[], deforms: (joint: number) => boolean): {
58
+ points: Float64Array;
59
+ owners: Int32Array;
60
+ };
61
+ /**
62
+ * Squared distance from (x, y, z) to segment `s` of `points` (six numbers per segment); writes the closest point to
63
+ * `out` when given.
64
+ */
65
+ export declare function segmentDistance2(points: Float64Array, s: number, x: number, y: number, z: number, out?: Float64Array): number;