@margoengine/rigging 0.0.0-stage → 0.1.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 (71) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +969 -3
  4. package/dist/autorig.d.ts +50 -0
  5. package/dist/autorig.js +660 -0
  6. package/dist/bar-grip.d.ts +7 -0
  7. package/dist/checks.d.ts +50 -0
  8. package/dist/contact.d.ts +175 -0
  9. package/dist/contact.js +739 -0
  10. package/dist/correctives.d.ts +92 -0
  11. package/dist/correctives.js +162 -0
  12. package/dist/errors-D8rc8kzg.js +7 -0
  13. package/dist/face.d.ts +93 -0
  14. package/dist/face.js +144 -0
  15. package/dist/hands.d.ts +209 -0
  16. package/dist/hands.js +510 -0
  17. package/dist/heat.d.ts +38 -0
  18. package/dist/hinged-contact.d.ts +7 -0
  19. package/dist/hulls.d.ts +54 -0
  20. package/dist/hulls.js +134 -0
  21. package/dist/ik.d.ts +109 -0
  22. package/dist/ik.js +358 -0
  23. package/dist/index.d.ts +6 -0
  24. package/dist/index.js +390 -0
  25. package/dist/joint-limits.d.ts +44 -0
  26. package/dist/joint-limits.js +74 -0
  27. package/dist/limb-collision.d.ts +99 -0
  28. package/dist/loading-CZaYr1N7.js +67 -0
  29. package/dist/mesh-CyvLHNp0.js +142 -0
  30. package/dist/mesh.d.ts +47 -0
  31. package/dist/mtoon-data.d.ts +118 -0
  32. package/dist/mtoon-legacy.d.ts +17 -0
  33. package/dist/mtoon-shader.d.ts +4 -0
  34. package/dist/mtoon.d.ts +84 -0
  35. package/dist/mtoon.js +990 -0
  36. package/dist/paint.d.ts +82 -0
  37. package/dist/pose-tracking.d.ts +117 -0
  38. package/dist/pose-tracking.js +488 -0
  39. package/dist/retarget.d.ts +71 -0
  40. package/dist/retarget.js +351 -0
  41. package/dist/rig-BawZ5OLb.js +127 -0
  42. package/dist/rig.d.ts +65 -0
  43. package/dist/shared/gltf.d.ts +257 -0
  44. package/dist/shared/layers.d.ts +16 -0
  45. package/dist/springs.d.ts +180 -0
  46. package/dist/springs.js +458 -0
  47. package/dist/strand-springs.d.ts +46 -0
  48. package/dist/strand-springs.js +168 -0
  49. package/dist/swim.d.ts +55 -0
  50. package/dist/swim.js +167 -0
  51. package/dist/transfer.d.ts +41 -0
  52. package/dist/transfer.js +136 -0
  53. package/dist/voxel-weights-48ok-Dax.js +255 -0
  54. package/dist/voxel-weights.d.ts +42 -0
  55. package/dist/voxel-weights.js +1 -0
  56. package/dist/voxels.d.ts +36 -0
  57. package/dist/vrm-constraints.d.ts +60 -0
  58. package/dist/vrm-constraints.js +261 -0
  59. package/dist/vrm-first-person.d.ts +115 -0
  60. package/dist/vrm-first-person.js +618 -0
  61. package/dist/vrm-presets-CU4V4yq6.js +47 -0
  62. package/dist/vrm-presets.d.ts +1 -0
  63. package/dist/vrm.d.ts +298 -0
  64. package/dist/vrm.js +574 -0
  65. package/dist/vrm0.d.ts +134 -0
  66. package/dist/vrm0.js +377 -0
  67. package/dist/vrma.d.ts +90 -0
  68. package/dist/vrma.js +315 -0
  69. package/dist/weight-map-D8cAONQQ.js +92 -0
  70. package/dist/weight-map.d.ts +58 -0
  71. package/package.json +175 -6
@@ -0,0 +1,82 @@
1
+ import type { Vec3 } from '@margoengine/math';
2
+ import { type WeightMesh } from './mesh.js';
3
+ import { type WeightMap } from './weight-map.js';
4
+ /** How a stroke changes weights. */
5
+ export type BrushMode = 'add' | 'subtract' | 'replace' | 'smooth';
6
+ /** Brush strength across its radius: `smooth` (default, smoothstep), `linear`, or `constant`. */
7
+ export type BrushFalloff = 'smooth' | 'linear' | 'constant';
8
+ /** One brush dab: {@link WeightPainter.stroke}. */
9
+ export interface BrushStroke {
10
+ /** What the brush does. `smooth` blends every unlocked bone toward the neighbours' average. */
11
+ readonly mode: BrushMode;
12
+ /** Bone painted by `add`, `subtract` and `replace` (ignored by `smooth`). */
13
+ readonly bone?: number;
14
+ /** Brush centre in mesh space. */
15
+ readonly center: Vec3;
16
+ /** Brush radius in mesh units, above 0. */
17
+ readonly radius: number;
18
+ /** 0-1 (default 0.5): the amount added or removed at the centre, or the blend toward the value or the average. */
19
+ readonly strength?: number;
20
+ /** Target weight for `replace` (default 1). */
21
+ readonly value?: number;
22
+ /** Default `smooth`. */
23
+ readonly falloff?: BrushFalloff;
24
+ }
25
+ /** The record of one stroke: which vertices it changed and how to put them back. */
26
+ export interface WeightEdit {
27
+ /** Input vertices the stroke changed. */
28
+ readonly vertices: Uint32Array;
29
+ /** Restores the weights the stroke changed. Undo strokes newest first. */
30
+ undo(): void;
31
+ }
32
+ /** Options for {@link WeightPainter}. */
33
+ export interface WeightPainterOptions {
34
+ /** Parent bone per bone (a skeleton's `parents`): weight subtracted from a vertex with no other bone goes to the parent. */
35
+ readonly parents?: readonly number[];
36
+ /** Bones whose weights strokes never change. Change it any time. */
37
+ locked?: readonly number[];
38
+ /** Welding tolerance as a fraction of the mesh's size (default 1e-6). */
39
+ readonly weld?: number;
40
+ }
41
+ /**
42
+ * Paints a {@link WeightMap} on a mesh. Every stroke leaves the vertices it touches summing to 1: when one bone gains
43
+ * or loses weight the other unlocked bones on that vertex are scaled to make up the difference (a vertex whose other
44
+ * bones hold nothing passes subtracted weight to the painted bone's parent, when `parents` is given and the parent is
45
+ * unlocked; otherwise its weight cannot drop). Locked bones keep their weights.
46
+ */
47
+ export declare class WeightPainter {
48
+ readonly weights: WeightMap;
49
+ /** Bones strokes leave alone. */
50
+ locked: readonly number[];
51
+ private readonly point;
52
+ private readonly positions;
53
+ private readonly members;
54
+ private readonly memberOffsets;
55
+ private readonly offsets;
56
+ private readonly columns;
57
+ private readonly parents?;
58
+ /**
59
+ * @param weights The weights to edit, one row per mesh vertex.
60
+ * @param mesh The mesh they belong to.
61
+ * @throws RangeError when the mesh and the weights have different vertex counts.
62
+ */
63
+ constructor(weights: WeightMap, mesh: WeightMesh, options?: WeightPainterOptions);
64
+ /**
65
+ * Applies one brush dab and returns its {@link WeightEdit} (undo). Brush strength at a vertex is `strength` times
66
+ * the falloff of its distance from `center` over `radius`.
67
+ * @throws RangeError for an invalid stroke.
68
+ */
69
+ stroke(stroke: BrushStroke): WeightEdit;
70
+ /**
71
+ * Smooths every unlocked weight over the whole mesh `iterations` times (default 1), each pass moving a vertex
72
+ * `strength` (default 0.5) of the way to its neighbours' mean, then renormalising. Returns the undo record.
73
+ */
74
+ smoothAll({ iterations, strength }?: {
75
+ iterations?: number;
76
+ strength?: number;
77
+ }): WeightEdit;
78
+ /** Normalises every vertex (see {@link WeightMap.normalize}, with this painter's locked bones). */
79
+ normalize(): this;
80
+ /** Index of the welded point an input vertex belongs to (vertices sharing it are painted together). */
81
+ pointOf(vertex: number): number;
82
+ }
@@ -0,0 +1,117 @@
1
+ // @ts-ignore optional peer: its types apply when it is installed
2
+ import type { Animation } from '@margoengine/animation';
3
+ import type { VRMAvatar, VRMHandle } from './vrm.js';
4
+ import { type HumanoidBone } from './retarget.js';
5
+ /** MediaPipe world or normalized landmark, with optional confidence. */
6
+ export interface PoseLandmark {
7
+ x: number;
8
+ y: number;
9
+ z: number;
10
+ visibility?: number;
11
+ presence?: number;
12
+ }
13
+ /** One body and up to two hands; legacy Holistic field names, with world body landmarks preferred. */
14
+ export interface PoseTrackingFrame {
15
+ poseWorldLandmarks?: readonly PoseLandmark[];
16
+ poseLandmarks?: readonly PoseLandmark[];
17
+ leftHandWorldLandmarks?: readonly PoseLandmark[];
18
+ rightHandWorldLandmarks?: readonly PoseLandmark[];
19
+ leftHandLandmarks?: readonly PoseLandmark[];
20
+ rightHandLandmarks?: readonly PoseLandmark[];
21
+ }
22
+ /** Structural MediaPipe Tasks results; no MediaPipe package is imported by this entry. */
23
+ export interface PoseTrackingResults {
24
+ pose?: {
25
+ worldLandmarks?: readonly (readonly PoseLandmark[])[];
26
+ landmarks?: readonly (readonly PoseLandmark[])[];
27
+ };
28
+ hands?: {
29
+ worldLandmarks?: readonly (readonly PoseLandmark[])[];
30
+ landmarks?: readonly (readonly PoseLandmark[])[];
31
+ handedness?: readonly (readonly {
32
+ categoryName: string;
33
+ score: number;
34
+ }[])[];
35
+ };
36
+ }
37
+ /** Adapt the first detected body and the highest-confidence hand of each side from MediaPipe Tasks. */
38
+ export declare function readPoseTrackingFrame(results: PoseTrackingResults): PoseTrackingFrame;
39
+ /** Coordinate conversion and confidence. Defaults: MediaPipe coordinates, unmirrored, minimum confidence 0.5. */
40
+ export interface PoseSolveOptions {
41
+ coordinateSpace?: 'mediapipe' | 'margo';
42
+ mirror?: boolean;
43
+ minConfidence?: number;
44
+ /** Image width / height for normalized landmarks (default 1); x and z are scaled to image-height units. */
45
+ aspect?: number;
46
+ /** Disable the leg/foot outputs, useful for seated capture (default false). */
47
+ upperBodyOnly?: boolean;
48
+ }
49
+ /** XYZW unit quaternion. */
50
+ export type PoseQuaternion = readonly [number, number, number, number];
51
+ /** A normalized humanoid pose: local rotations plus model-space orientations and per-bone confidence. */
52
+ export interface TrackedPose {
53
+ readonly rotations: Partial<Record<HumanoidBone, PoseQuaternion>>;
54
+ readonly worldRotations: Partial<Record<HumanoidBone, PoseQuaternion>>;
55
+ /** Hips centre in input world units, converted to Margo coordinates; root-centred input remains root-centred. */
56
+ readonly position: readonly [number, number, number] | null;
57
+ readonly confidence: Partial<Record<HumanoidBone, number>>;
58
+ }
59
+ /** Solve MediaPipe's 33 body landmarks into hips, spine, head, arms, wrists, legs and feet. */
60
+ export declare function solveBodyPose(input: readonly PoseLandmark[], options?: PoseSolveOptions): TrackedPose;
61
+ /** Solve 21 MediaPipe hand landmarks into wrist and all fifteen finger joints, including thumb metacarpal. */
62
+ export declare function solveHandPose(input: readonly PoseLandmark[], handedness: 'left' | 'right', options?: PoseSolveOptions): TrackedPose;
63
+ /** Smoothing and lost-input policy. Defaults: 0.05 second smoothing, 0.2 second hold then fade to neutral. */
64
+ export interface PoseTrackerOptions extends PoseSolveOptions {
65
+ smoothing?: number;
66
+ hold?: number;
67
+ }
68
+ /** Stateful body/hand solver with calibration, confidence gating, smoothing and loss recovery. No inference dependency. */
69
+ export declare class PoseTracker {
70
+ readonly options: PoseTrackerOptions;
71
+ private goal;
72
+ private readonly current;
73
+ private readonly ages;
74
+ private calibration;
75
+ private origin;
76
+ private translation;
77
+ private hasPosition;
78
+ readonly smoothing: number;
79
+ readonly hold: number;
80
+ constructor(options?: PoseTrackerOptions);
81
+ /** Take a latest frame; null signals tracking loss. Validation completes before replacing the previous goal. */
82
+ push(frame: PoseTrackingFrame | null): this;
83
+ /** Use the current goal as neutral, so arbitrary camera/hand rest orientations map to the avatar's authored rest. */
84
+ calibrate(): this;
85
+ /** Clear the neutral calibration; subsequent input uses the documented canonical T-pose. */
86
+ clearCalibration(): this;
87
+ /** Advance filtered rotations. Loss holds briefly, then returns to neutral; delta 0 never advances a fade. */
88
+ update(delta: number): TrackedPose;
89
+ /**
90
+ * A measured world rotation relative to the calibrated neutral. The camera sees the world turned by its tilt T, so
91
+ * a bone measures T A for its world rotation A, and calibration stores T N for its neutral N. Removing N alone
92
+ * (T A (T N)^-1 = T W T^-1 for the move W = A N^-1) leaves the move about the camera's tilted axes. With the hips
93
+ * calibrated, standing upright (their N is the identity), T is the hips' calibration and the move is
94
+ * T^-1 (T A) (T N)^-1 T = A N^-1 = W, in the world. A bone with no calibration of its own is only untilted.
95
+ */
96
+ private neutral;
97
+ /** Return the filter to neutral; calibration and the latest goal remain available. */
98
+ reset(): this;
99
+ }
100
+ /** Native binding options. VRM integration runs before gaze and springs; otherwise the owning scene updates it. */
101
+ export interface AddPoseTrackingOptions extends PoseTrackerOptions {
102
+ /** Abort before the optional retarget module finishes loading or before attachment. */
103
+ signal?: AbortSignal;
104
+ vrm?: VRMHandle;
105
+ autoUpdate?: boolean /** Proportional root motion scale; default target/source hips height. */;
106
+ hipScale?: number;
107
+ }
108
+ /** Running tracker binding. Dispose restores every transform written by the tracker. */
109
+ export interface PoseTrackingHandle {
110
+ readonly tracker: PoseTracker;
111
+ push(frame: PoseTrackingFrame | null): void;
112
+ update(delta: number): void;
113
+ dispose(): void;
114
+ [Symbol.dispose](): void;
115
+ }
116
+ /** Bind normalized body and hand motion to a VRM in its T-pose, absorbing the target's arbitrary rest axes. */
117
+ export declare function addPoseTracking(animation: Animation, avatar: VRMAvatar, options?: AddPoseTrackingOptions): Promise<PoseTrackingHandle>;
@@ -0,0 +1,488 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import { rotationBetween as e } from "./ik.js";
5
+ import { HUMANOID_BONES as t } from "./retarget.js";
6
+ import { MargoError as n } from "@margoengine/math/errors";
7
+ import { conjugateQuaternion as r, interpolateQuaternions as i, multiplyQuaternions as a, normalizeQuaternion as o, rotateByQuaternion as s, rotationToQuaternion as c } from "@margoengine/math/quat";
8
+ //#region src/pose-tracking.ts
9
+ function l(e) {
10
+ if (!e || typeof e != "object") throw TypeError("Tracking results must hold pose or hands Tasks results");
11
+ let t = {
12
+ poseWorldLandmarks: e.pose?.worldLandmarks?.[0],
13
+ poseLandmarks: e.pose?.landmarks?.[0]
14
+ }, n = e.hands, r = {
15
+ left: -1,
16
+ right: -1
17
+ };
18
+ for (let e = 0; e < (n?.handedness?.length ?? 0); e++) {
19
+ let i = n.handedness[e][0], a = i?.categoryName?.toLowerCase();
20
+ if (!i || !Number.isFinite(i.score) || i.score < 0 || i.score > 1 || a !== "left" && a !== "right") throw RangeError("Hand results must provide Left or Right handedness and a confidence in [0,1]");
21
+ let o = n?.worldLandmarks?.[e], s = o ?? n?.landmarks?.[e];
22
+ if (s && i.score > r[a]) {
23
+ r[a] = i.score;
24
+ let e = o ? a === "left" ? "leftHandWorldLandmarks" : "rightHandWorldLandmarks" : a === "left" ? "leftHandLandmarks" : "rightHandLandmarks";
25
+ t[e] = s.map((e) => ({
26
+ ...e,
27
+ presence: Math.min(e.presence ?? 1, i.score)
28
+ }));
29
+ }
30
+ }
31
+ return t;
32
+ }
33
+ var u = [
34
+ 0,
35
+ 0,
36
+ 0,
37
+ 1
38
+ ], d = (e, t) => [
39
+ e[0] - t[0],
40
+ e[1] - t[1],
41
+ e[2] - t[2]
42
+ ], f = (e, t) => [
43
+ e[0] * t,
44
+ e[1] * t,
45
+ e[2] * t
46
+ ], p = (e, t) => e[0] * t[0] + e[1] * t[1] + e[2] * t[2], m = (e, t) => [
47
+ e[1] * t[2] - e[2] * t[1],
48
+ e[2] * t[0] - e[0] * t[2],
49
+ e[0] * t[1] - e[1] * t[0]
50
+ ], h = (e) => {
51
+ let t = Math.hypot(...e);
52
+ return t > 1e-8 ? f(e, 1 / t) : null;
53
+ }, g = (e) => {
54
+ let t = Math.hypot(...e);
55
+ return t > 0 && Number.isFinite(t) ? f(e, 1 / t) : null;
56
+ }, _ = (e, t) => [
57
+ (e[0] + t[0]) / 2,
58
+ (e[1] + t[1]) / 2,
59
+ (e[2] + t[2]) / 2
60
+ ];
61
+ function v(e, t) {
62
+ let n = g(e), r = g(t);
63
+ if (!n || !r) return null;
64
+ let i = h(d(r, f(n, p(n, r))));
65
+ return i ? o(c([
66
+ ...n,
67
+ ...i,
68
+ ...m(n, i)
69
+ ])) : null;
70
+ }
71
+ var y = {
72
+ spine: "hips",
73
+ chest: "spine",
74
+ upperChest: "chest",
75
+ neck: "upperChest",
76
+ head: "neck",
77
+ jaw: "head"
78
+ };
79
+ for (let e of ["left", "right"]) {
80
+ Object.assign(y, {
81
+ [`${e}Shoulder`]: "upperChest",
82
+ [`${e}UpperArm`]: `${e}Shoulder`,
83
+ [`${e}LowerArm`]: `${e}UpperArm`,
84
+ [`${e}Hand`]: `${e}LowerArm`,
85
+ [`${e}UpperLeg`]: "hips",
86
+ [`${e}LowerLeg`]: `${e}UpperLeg`,
87
+ [`${e}Foot`]: `${e}LowerLeg`,
88
+ [`${e}Toes`]: `${e}Foot`
89
+ });
90
+ for (let t of [
91
+ "Thumb",
92
+ "Index",
93
+ "Middle",
94
+ "Ring",
95
+ "Little"
96
+ ]) {
97
+ let n = t === "Thumb" ? [
98
+ "Metacarpal",
99
+ "Proximal",
100
+ "Distal"
101
+ ] : [
102
+ "Proximal",
103
+ "Intermediate",
104
+ "Distal"
105
+ ];
106
+ n.forEach((r, i) => {
107
+ y[`${e}${t}${r}`] = i ? `${e}${t}${n[i - 1]}` : `${e}Hand`;
108
+ });
109
+ }
110
+ }
111
+ function b(e, n, i = null) {
112
+ let o = {};
113
+ for (let n of t) {
114
+ let t = e[n];
115
+ if (!t) continue;
116
+ let i = y[n];
117
+ for (; i && !e[i];) i = y[i];
118
+ o[n] = i ? a(r(e[i]), t) : [...t];
119
+ }
120
+ return {
121
+ rotations: o,
122
+ worldRotations: e,
123
+ position: i,
124
+ confidence: n
125
+ };
126
+ }
127
+ function x(e) {
128
+ let t = e.minConfidence ?? .5, n = e.aspect ?? 1, r = e.coordinateSpace ?? "mediapipe";
129
+ if (!Number.isFinite(t) || t < 0 || t > 1 || !Number.isFinite(n) || n <= 0 || !["mediapipe", "margo"].includes(r)) throw RangeError("Pose options must use confidence in [0,1], a positive aspect and mediapipe or margo coordinateSpace");
130
+ return {
131
+ threshold: t,
132
+ aspect: n,
133
+ space: r,
134
+ mirror: e.mirror ?? !1
135
+ };
136
+ }
137
+ function S(e, t, n) {
138
+ let { threshold: r, aspect: i, space: a, mirror: o } = x(n);
139
+ if (!Array.isArray(e) || e.length !== t) throw TypeError(`Pose landmarks must contain ${t} {x,y,z} points`);
140
+ let s = [], c = [];
141
+ for (let t of e) {
142
+ if (!t || ![
143
+ t.x,
144
+ t.y,
145
+ t.z
146
+ ].every(Number.isFinite) || [t.visibility, t.presence].some((e) => e !== void 0 && (!Number.isFinite(e) || e < 0 || e > 1))) throw RangeError("Pose landmarks must have finite coordinates and confidence from 0 to 1");
147
+ s.push([
148
+ t.x * i * (o ? -1 : 1),
149
+ t.y * (a === "mediapipe" ? -1 : 1),
150
+ t.z * i * (a === "mediapipe" ? -1 : 1)
151
+ ]), c.push(Math.min(t.visibility ?? 1, t.presence ?? 1));
152
+ }
153
+ return {
154
+ points: s,
155
+ scores: c,
156
+ threshold: r
157
+ };
158
+ }
159
+ function C(t, n = {}) {
160
+ let { points: r, scores: i, threshold: a } = S(t, 33, n);
161
+ if (n.mirror) for (let [e, t] of [
162
+ [1, 4],
163
+ [2, 5],
164
+ [3, 6],
165
+ [7, 8],
166
+ [9, 10],
167
+ [11, 12],
168
+ [13, 14],
169
+ [15, 16],
170
+ [17, 18],
171
+ [19, 20],
172
+ [21, 22],
173
+ [23, 24],
174
+ [25, 26],
175
+ [27, 28],
176
+ [29, 30],
177
+ [31, 32]
178
+ ]) [r[e], r[t]] = [r[t], r[e]], [i[e], i[t]] = [i[t], i[e]];
179
+ let o = {}, c = {}, l = (e, t, n) => {
180
+ let r = Math.min(...n.map((e) => i[e]));
181
+ t && r >= a && (o[e] = t, c[e] = r);
182
+ }, u = _(r[23], r[24]), y = d(_(r[11], r[12]), u), x = d(r[23], r[24]), C = d(r[11], r[12]);
183
+ l("hips", v(x, y), [
184
+ 23,
185
+ 24,
186
+ 11,
187
+ 12
188
+ ]);
189
+ let w = v(C, y);
190
+ for (let e of [
191
+ "spine",
192
+ "chest",
193
+ "upperChest",
194
+ "neck"
195
+ ]) l(e, w, [
196
+ 11,
197
+ 12,
198
+ 23,
199
+ 24
200
+ ]);
201
+ l("head", v(d(r[7], r[8]), m(d(r[0], _(r[7], r[8])), d(r[7], r[8]))), [
202
+ 0,
203
+ 7,
204
+ 8
205
+ ]);
206
+ for (let [t, i, a] of [[
207
+ "left",
208
+ 1,
209
+ 0
210
+ ], [
211
+ "right",
212
+ -1,
213
+ 1
214
+ ]]) {
215
+ let o = d(r[13 + a], r[11 + a]), c = d(r[15 + a], r[13 + a]), u = g(o), b = g(c), S = u && b ? h(d(b, f(u, p(b, u)))) : null, T = S ? m(S, f(o, i)) : y, E = (t) => {
216
+ let n = f(t, i);
217
+ return !h(n) || !h(C) ? null : v(n, S ? T : s(y, e(C, n)));
218
+ };
219
+ l(`${t}Shoulder`, w, [
220
+ 11,
221
+ 12,
222
+ 23,
223
+ 24
224
+ ]), l(`${t}UpperArm`, E(o), [
225
+ 11 + a,
226
+ 13 + a,
227
+ 15 + a
228
+ ]), l(`${t}LowerArm`, E(c), [
229
+ 11 + a,
230
+ 13 + a,
231
+ 15 + a
232
+ ]);
233
+ let D = f(d(_(r[17 + a], r[19 + a]), r[15 + a]), i), O = d(r[19 + a], r[17 + a]);
234
+ if (l(`${t}Hand`, v(D, m(O, D)), [
235
+ 15 + a,
236
+ 17 + a,
237
+ 19 + a
238
+ ]), !n.upperBodyOnly) {
239
+ let n = d(r[25 + a], r[23 + a]), i = d(r[27 + a], r[25 + a]), o = (t) => {
240
+ let n = h(f(t, -1));
241
+ if (!n) return null;
242
+ let r = h(d(x, f(n, p(x, n))));
243
+ return r ? v(r, n) : !h(y) || !h(x) ? null : v(s(x, e(y, n)), n);
244
+ };
245
+ l(`${t}UpperLeg`, o(n), [
246
+ 23,
247
+ 24,
248
+ 25 + a
249
+ ]), l(`${t}LowerLeg`, o(i), [
250
+ 23,
251
+ 24,
252
+ 25 + a,
253
+ 27 + a
254
+ ]);
255
+ let c = h(d(r[31 + a], r[29 + a])), u = c ? h(d(x, f(c, p(x, c)))) : null;
256
+ l(`${t}Foot`, u && c ? v(u, m(c, u)) : null, [
257
+ 23,
258
+ 24,
259
+ 29 + a,
260
+ 31 + a
261
+ ]);
262
+ }
263
+ }
264
+ return b(o, c, o.hips ? u : null);
265
+ }
266
+ function w(e, t, n = {}) {
267
+ if (t !== "left" && t !== "right") throw RangeError("Handedness must be left or right");
268
+ let { points: r, scores: i, threshold: a } = S(e, 21, n), o = n.mirror ? t === "left" ? "right" : "left" : t, c = o === "left" ? 1 : -1, l = {}, u = {}, p = f(d(r[9], r[0]), c), h = v(p, m(d(r[5], r[17]), p)), g = h ? s([
269
+ 0,
270
+ 0,
271
+ 1
272
+ ], h) : [
273
+ 0,
274
+ 0,
275
+ 0
276
+ ], _ = h ? s([
277
+ 0,
278
+ 1,
279
+ 0
280
+ ], h) : [
281
+ 0,
282
+ 0,
283
+ 0
284
+ ], y = (e, t, n) => {
285
+ let r = Math.min(...n.map((e) => i[e]));
286
+ t && r >= a && (l[e] = t, u[e] = r);
287
+ };
288
+ y(`${o}Hand`, h, [
289
+ 0,
290
+ 5,
291
+ 9,
292
+ 17
293
+ ]);
294
+ for (let [e, t] of [
295
+ ["Thumb", 1],
296
+ ["Index", 5],
297
+ ["Middle", 9],
298
+ ["Ring", 13],
299
+ ["Little", 17]
300
+ ]) {
301
+ let n = e === "Thumb" ? [
302
+ "Metacarpal",
303
+ "Proximal",
304
+ "Distal"
305
+ ] : [
306
+ "Proximal",
307
+ "Intermediate",
308
+ "Distal"
309
+ ];
310
+ for (let i = 0; i < 3; i++) {
311
+ let a = f(d(r[t + i + 1], r[t + i]), c);
312
+ y(`${o}${e}${n[i]}`, v(a, m(g, a)) ?? v(a, _), [
313
+ 0,
314
+ 5,
315
+ 17,
316
+ t + i,
317
+ t + i + 1
318
+ ]);
319
+ }
320
+ }
321
+ return b(l, u);
322
+ }
323
+ var T = class {
324
+ constructor(e = {}) {
325
+ if (this.options = e, this.goal = b({}, {}), this.current = {}, this.ages = /* @__PURE__ */ new Map(), this.calibration = {}, this.origin = [
326
+ 0,
327
+ 0,
328
+ 0
329
+ ], this.translation = [
330
+ 0,
331
+ 0,
332
+ 0
333
+ ], this.hasPosition = !1, x(e), this.smoothing = e.smoothing ?? .05, this.hold = e.hold ?? .2, !Number.isFinite(this.smoothing) || this.smoothing < 0 || !Number.isFinite(this.hold) || this.hold < 0) throw RangeError("Pose smoothing and hold must be finite, nonnegative seconds");
334
+ this.options = Object.freeze({ ...e });
335
+ }
336
+ push(e) {
337
+ let t = {}, n = {}, r = null;
338
+ if (e !== null) {
339
+ if (!e || typeof e != "object") throw TypeError("Pose frame must be a body/hand landmarks object or null");
340
+ let i = e.poseWorldLandmarks ?? e.poseLandmarks, a = [];
341
+ i && a.push(C(i, {
342
+ ...this.options,
343
+ aspect: e.poseWorldLandmarks ? 1 : this.options.aspect
344
+ }));
345
+ let o = e.leftHandWorldLandmarks ?? e.leftHandLandmarks, s = e.rightHandWorldLandmarks ?? e.rightHandLandmarks;
346
+ o && a.push(w(o, "left", {
347
+ ...this.options,
348
+ aspect: e.leftHandWorldLandmarks ? 1 : this.options.aspect
349
+ })), s && a.push(w(s, "right", {
350
+ ...this.options,
351
+ aspect: e.rightHandWorldLandmarks ? 1 : this.options.aspect
352
+ }));
353
+ for (let e of a) Object.assign(t, e.worldRotations), Object.assign(n, e.confidence), e.position && (r = [...e.position]);
354
+ }
355
+ return this.goal = b(t, n, r), this;
356
+ }
357
+ calibrate() {
358
+ return this.calibration = structuredClone(this.goal.worldRotations), this.origin = this.goal.position ? [...this.goal.position] : [
359
+ 0,
360
+ 0,
361
+ 0
362
+ ], this.reset();
363
+ }
364
+ clearCalibration() {
365
+ return this.calibration = {}, this.origin = [
366
+ 0,
367
+ 0,
368
+ 0
369
+ ], this.reset();
370
+ }
371
+ update(e) {
372
+ if (!Number.isFinite(e) || e < 0) throw RangeError("Pose delta must be finite and nonnegative seconds");
373
+ let n = this.smoothing === 0 ? 1 : 1 - Math.exp(-e / this.smoothing), a = {};
374
+ for (let r of t) {
375
+ let t = this.goal.worldRotations[r], o;
376
+ if (t) this.ages.set(r, 0), o = this.neutral(t, this.calibration[r]), a[r] = this.goal.confidence[r];
377
+ else {
378
+ let t = (this.ages.get(r) ?? 0) + e;
379
+ if (this.ages.set(r, t), !this.current[r] || t <= this.hold) continue;
380
+ o = u, a[r] = 0;
381
+ }
382
+ this.current[r] = i(this.current[r] ?? u, o, n, .9995);
383
+ }
384
+ if (this.goal.position) {
385
+ let e = this.calibration.hips, t = d([...this.goal.position], this.origin), i = e ? s(t, r(e)) : t;
386
+ for (let e = 0; e < 3; e++) this.translation[e] += (i[e] - this.translation[e]) * n;
387
+ this.hasPosition = !0;
388
+ } else if ((this.ages.get("hips") ?? 0) > this.hold) for (let e = 0; e < 3; e++) this.translation[e] *= 1 - n;
389
+ return b(structuredClone(this.current), a, this.hasPosition ? [...this.translation] : null);
390
+ }
391
+ neutral(e, t) {
392
+ let n = this.calibration.hips;
393
+ if (!n) return t ? a(e, r(t)) : e;
394
+ let i = a(r(n), e);
395
+ return t ? a(a(i, r(t)), n) : i;
396
+ }
397
+ reset() {
398
+ for (let e of Object.keys(this.current)) delete this.current[e];
399
+ return this.ages.clear(), this.translation = [
400
+ 0,
401
+ 0,
402
+ 0
403
+ ], this.hasPosition = !1, this;
404
+ }
405
+ };
406
+ async function E(e, r, i = {}) {
407
+ i.signal?.throwIfAborted();
408
+ let { Retarget: a, retargetRig: o } = await import("@margoengine/animation/skeleton-utils");
409
+ i.signal?.throwIfAborted();
410
+ let s = new T(i), c = e.model, l = o(c), u = r.humanoid.humanBones, d = l.names.map((e, t) => `target#${t}`);
411
+ for (let [e, t] of Object.entries(u)) {
412
+ if (!Number.isInteger(t.node) || t.node < 0 || t.node >= d.length) throw RangeError("Tracking bone node must name a node in this model");
413
+ d[t.node] = e;
414
+ }
415
+ let f = new Float64Array(t.length * 10);
416
+ t.forEach((e, t) => {
417
+ f[t * 10 + 6] = 1, f.fill(1, t * 10 + 7, t * 10 + 10), e === "hips" && (f[t * 10 + 1] = 1);
418
+ });
419
+ let p = new a({
420
+ names: t,
421
+ parents: t.map((e) => y[e] ? t.indexOf(y[e]) : -1),
422
+ rest: f
423
+ }, {
424
+ ...l,
425
+ names: d
426
+ }, {
427
+ hip: "hips",
428
+ hipScale: i.hipScale
429
+ }), m = f.slice(), h = l.rest.slice(), g = c.root.engine.store.transforms, _ = /* @__PURE__ */ new Map(), v = !1, b, x, S = (e) => {
430
+ if (v) throw new n("disposed", "Pose tracking is disposed; create a new binding");
431
+ let r = s.update(e);
432
+ m.set(f);
433
+ for (let [e, n] of Object.entries(r.rotations)) m.set(n, t.indexOf(e) * 10 + 3);
434
+ if (r.position) for (let e = 0; e < 3; e++) m[e] = f[e] + r.position[e];
435
+ p.pose(m, h);
436
+ for (let [e, t] of Object.entries(u)) if (r.worldRotations[e]) {
437
+ let n = t.node, i = c.nodes[n], a = i.id;
438
+ _.has(n) || _.set(n, {
439
+ q: [
440
+ g.qx[a],
441
+ g.qy[a],
442
+ g.qz[a],
443
+ g.qw[a]
444
+ ],
445
+ p: [
446
+ g.x[a],
447
+ g.y[a],
448
+ g.z[a]
449
+ ]
450
+ }), i.setQuaternion(Array.from(h.subarray(n * 10 + 3, n * 10 + 7))), e === "hips" && r.position && i.setPosition(Array.from(h.subarray(n * 10, n * 10 + 3)));
451
+ }
452
+ }, C = c.root.scene, w = `pose-tracking:${c.root.id}`, E = () => {
453
+ if (!v) {
454
+ v = !0, b?.(), x?.();
455
+ for (let [e, t] of _) c.nodes[e].setQuaternion(t.q), e === u.hips?.node && c.nodes[e].setPosition(t.p);
456
+ }
457
+ };
458
+ if (i.autoUpdate !== !1) {
459
+ if (i.vrm) b = i.vrm.addPoseSource(S);
460
+ else {
461
+ let e = {coreRequirement:/*@__PURE__*/__margoCoreRequirement("0.1.0",import.meta.url),
462
+ name: w,
463
+ setup() {},
464
+ onPreUpdate: S,
465
+ dispose: () => {
466
+ b = void 0, E();
467
+ }
468
+ };
469
+ C.use(e), b = () => {
470
+ C.plugins.get(w) === e && C.removePlugin(w);
471
+ };
472
+ }
473
+ }
474
+ return x = c.onDispose(() => {
475
+ v || (v = !0, b?.());
476
+ }), {
477
+ tracker: s,
478
+ push(e) {
479
+ if (v) throw new n("disposed", "Pose tracking is disposed; create a new binding");
480
+ s.push(e);
481
+ },
482
+ update: S,
483
+ dispose: E,
484
+ [Symbol.dispose]: E
485
+ };
486
+ }
487
+ //#endregion
488
+ export { T as PoseTracker, E as addPoseTracking, l as readPoseTrackingFrame, C as solveBodyPose, w as solveHandPose };