@nebula-spatial/viewer 0.6.5 → 0.6.6

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.
@@ -0,0 +1,1601 @@
1
+ var tt = Object.defineProperty;
2
+ var et = (v, t, e) => t in v ? tt(v, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : v[t] = e;
3
+ var x = (v, t, e) => et(v, typeof t != "symbol" ? t + "" : t, e);
4
+ import it from "@mujoco/mujoco";
5
+ import { Quaternion as B, Vector3 as D } from "three";
6
+ import { e as st, y as U, z as ot } from "./index-DyBfusq5.js";
7
+ let rt = 0;
8
+ function nt(v, t) {
9
+ const e = `/viewer-simulation-${++rt}`;
10
+ v.mkdir(e);
11
+ const i = /* @__PURE__ */ new Set([e]), s = /* @__PURE__ */ new Set(), o = (n, a) => {
12
+ const c = n.replaceAll("\\", "/").split("/");
13
+ if (c[0] === "" || c.some((d) => d === ".." || d.includes(":"))) throw $(`Invalid package path: ${n}`, "E_SIMULATION_PATH");
14
+ const l = c.filter((d) => d && d !== ".");
15
+ if (!l.length) throw $("Package path is empty.", "E_SIMULATION_PATH");
16
+ let m = e;
17
+ for (const d of l.slice(0, -1))
18
+ m += `/${d}`, i.has(m) || (v.mkdir(m), i.add(m));
19
+ const h = `${e}/${l.join("/")}`;
20
+ return v.writeFile(h, a), s.add(h), h;
21
+ }, r = () => {
22
+ for (const n of s) v.unlink(n);
23
+ s.clear();
24
+ for (const n of [...i].reverse()) v.rmdir(n);
25
+ i.clear();
26
+ };
27
+ try {
28
+ for (const [n, a] of t) o(n, a);
29
+ return { writeEntry: (n) => o("__viewer_entry.xml", n), dispose: r };
30
+ } catch (n) {
31
+ throw r(), n;
32
+ }
33
+ }
34
+ function $(v, t) {
35
+ return Object.assign(new Error(v), { code: t });
36
+ }
37
+ function at(v, t, e, i) {
38
+ if (!(v > 0) || !Number.isFinite(v)) return Number.POSITIVE_INFINITY;
39
+ const s = 1 / v, o = [
40
+ e[0] * i[0] + e[3] * i[1] + e[6] * i[2],
41
+ e[1] * i[0] + e[4] * i[1] + e[7] * i[2],
42
+ e[2] * i[0] + e[5] * i[1] + e[8] * i[2]
43
+ ], r = [o[0] ** 2, o[1] ** 2, o[2] ** 2], n = t.map((c) => {
44
+ const l = Math.max(c, 1e-12);
45
+ return Number.isFinite(l) ? 1 / l : 0;
46
+ }), a = (r[0] + r[1] + r[2]) * (n[0] + n[1] + n[2]) - (r[0] * n[0] + r[1] * n[1] + r[2] * n[2]);
47
+ return 3 * s + Math.max(0, a);
48
+ }
49
+ function V(v, t, e, i) {
50
+ const s = at(v, t, e, i);
51
+ return Number.isFinite(s) && s > 0 ? Math.min(v, 3 / s) : 0;
52
+ }
53
+ function Y({
54
+ target: v,
55
+ point: t,
56
+ center: e,
57
+ spatialVelocity: i,
58
+ rotation: s,
59
+ mass: o,
60
+ inertia: r,
61
+ representativeInertia: n,
62
+ stiffness: a,
63
+ rotationalStiffness: c,
64
+ damping: l,
65
+ maxAcceleration: m,
66
+ maxAngularAcceleration: h,
67
+ strength: d
68
+ }) {
69
+ const f = [
70
+ t[0] - e[0],
71
+ t[1] - e[1],
72
+ t[2] - e[2]
73
+ ], g = [
74
+ i[3] + i[1] * f[2] - i[2] * f[1],
75
+ i[4] + i[2] * f[0] - i[0] * f[2],
76
+ i[5] + i[0] * f[1] - i[1] * f[0]
77
+ ], j = V(o, r, s, f);
78
+ if (!(j > 0))
79
+ return { force: [0, 0, 0], torque: [0, 0, 0], effectiveMass: 0, pointVelocity: g };
80
+ const b = Math.max(1, d), _ = Math.max(a, 1e-6) * b, u = l && l > 0 ? l : 2 * Math.sqrt(_) * j, y = [
81
+ v[0] - t[0],
82
+ v[1] - t[1],
83
+ v[2] - t[2]
84
+ ], p = [
85
+ _ * j * y[0] - u * g[0],
86
+ _ * j * y[1] - u * g[1],
87
+ _ * j * y[2] - u * g[2]
88
+ ], w = j * m * b, N = Math.hypot(p[0], p[1], p[2]);
89
+ if (N > w && N > 0) {
90
+ const q = w / N;
91
+ p[0] *= q, p[1] *= q, p[2] *= q;
92
+ }
93
+ const M = [
94
+ f[1] * p[2] - f[2] * p[1],
95
+ f[2] * p[0] - f[0] * p[2],
96
+ f[0] * p[1] - f[1] * p[0]
97
+ ], O = Math.min(b, 2), E = Math.max(n, 1e-12) * h * O, T = Math.hypot(M[0], M[1], M[2]);
98
+ if (T > E && T > 0) {
99
+ const q = E / T;
100
+ M[0] *= q, M[1] *= q, M[2] *= q;
101
+ }
102
+ const A = Math.sqrt(Math.max(c, 1e-6) * O) * Math.max(n, 1e-12), G = [
103
+ M[0] - A * i[0],
104
+ M[1] - A * i[1],
105
+ M[2] - A * i[2]
106
+ ];
107
+ return { force: p, torque: G, effectiveMass: j, pointVelocity: g };
108
+ }
109
+ class ct {
110
+ constructor(t, e, i) {
111
+ x(this, "pairs", []);
112
+ x(this, "activePairs", []);
113
+ this.mujoco = t, this.model = e;
114
+ const s = new Set(Array.from(e.exclude_signature)), o = /* @__PURE__ */ new Set();
115
+ for (let r = 0; r < e.npair; r++)
116
+ o.add(this.geomPairKey(e.pair_geom1[r], e.pair_geom2[r]));
117
+ for (let r = 0; r < e.ngeom; r++)
118
+ if (this.isCollider(r))
119
+ for (let n = r + 1; n < e.ngeom; n++) {
120
+ if (!this.isCollider(n)) continue;
121
+ const a = e.geom_bodyid[r], c = e.geom_bodyid[n];
122
+ if (a === c || e.body_weldid[a] === e.body_weldid[c] || this.hasNativeContact(r, n, a, c, s, o)) continue;
123
+ const l = this.pairTolerance(r, n), m = this.distance(i, r, n, l), h = m < -l || Math.abs(m) < l && this.hasDegenerateOverlap(i, r, n, l);
124
+ this.pairs.push({
125
+ first: r,
126
+ second: n,
127
+ firstBody: a,
128
+ secondBody: c,
129
+ tolerance: l,
130
+ initiallyOverlapping: h,
131
+ separated: !h
132
+ });
133
+ }
134
+ }
135
+ /** Select only pairs whose relative transform can change in this edit. */
136
+ prepare(t) {
137
+ const e = new Array(this.model.nbody).fill("");
138
+ for (let i = 1; i < this.model.nbody; i++) {
139
+ let s = e[this.model.body_parentid[i]];
140
+ const o = this.model.body_jntadr[i];
141
+ for (let r = o; r < o + this.model.body_jntnum[i]; r++)
142
+ t.has(r) && (s += `${r},`);
143
+ e[i] = s;
144
+ }
145
+ this.activePairs = this.pairs.filter((i) => e[i.firstBody] !== e[i.secondBody]);
146
+ }
147
+ /** Call after updating the candidate pose's kinematics, before accepting it. */
148
+ accept(t) {
149
+ const e = [];
150
+ for (const i of this.activePairs) {
151
+ const s = this.distance(t, i.first, i.second, i.tolerance);
152
+ if (!Number.isFinite(s)) return !1;
153
+ if (!i.separated) {
154
+ s >= i.tolerance && e.push(i);
155
+ continue;
156
+ }
157
+ if (s < -i.tolerance || Math.abs(s) < i.tolerance && this.hasDegenerateOverlap(t, i.first, i.second, i.tolerance)) return !1;
158
+ }
159
+ for (const i of e) i.separated = !0;
160
+ return !0;
161
+ }
162
+ /** Restore the original exemptions, without recapturing the current pose. */
163
+ reset() {
164
+ for (const t of this.pairs) t.separated = !t.initiallyOverlapping;
165
+ this.activePairs = [];
166
+ }
167
+ /** Default assembly intersections also need an exemption during playback. */
168
+ hasInitialBodyOverlap(t, e) {
169
+ return this.pairs.some((i) => i.initiallyOverlapping && (i.firstBody === t && i.secondBody === e || i.firstBody === e && i.secondBody === t));
170
+ }
171
+ isCollider(t) {
172
+ return this.model.geom_contype[t] !== 0 || this.model.geom_conaffinity[t] !== 0;
173
+ }
174
+ distance(t, e, i, s) {
175
+ const o = this.model.geom_rbound[e], r = this.model.geom_rbound[i], n = this.mujoco.mjtGeom.mjGEOM_PLANE.value;
176
+ if (o > 0 && r > 0 && this.model.geom_type[e] !== n && this.model.geom_type[i] !== n) {
177
+ const a = e * 3, c = i * 3, l = t.geom_xpos[a] - t.geom_xpos[c], m = t.geom_xpos[a + 1] - t.geom_xpos[c + 1], h = t.geom_xpos[a + 2] - t.geom_xpos[c + 2], d = o + r + s;
178
+ if (l * l + m * m + h * h > d * d) return s;
179
+ }
180
+ return this.mujoco.mj_geomDistance(this.model, t, e, i, s, null);
181
+ }
182
+ hasDegenerateOverlap(t, e, i, s) {
183
+ const o = Math.max(s * 4, 1e-8), r = i * 3;
184
+ for (let n = 0; n < 3; n++) {
185
+ const a = r + n, c = t.geom_xpos[a];
186
+ try {
187
+ for (const l of [-1, 1])
188
+ if (t.geom_xpos[a] = c + l * o, this.mujoco.mj_geomDistance(this.model, t, e, i, s, null) < -o - s) return !0;
189
+ } finally {
190
+ t.geom_xpos[a] = c;
191
+ }
192
+ }
193
+ return !1;
194
+ }
195
+ geomPairKey(t, e) {
196
+ return t < e ? `${t}:${e}` : `${e}:${t}`;
197
+ }
198
+ pairTolerance(t, e) {
199
+ const i = this.model.geom_rbound[t], s = this.model.geom_rbound[e], o = Math.min(i || s || 1, s || i || 1);
200
+ return Math.max(1e-8, Math.min(1e-5, o * 1e-5));
201
+ }
202
+ hasNativeContact(t, e, i, s, o, r) {
203
+ const n = this.model.opt.disableflags;
204
+ if (n & (this.mujoco.mjtDisableBit.mjDSBL_CONTACT.value | this.mujoco.mjtDisableBit.mjDSBL_CONSTRAINT.value)) return !1;
205
+ if (r.has(this.geomPairKey(t, e))) return !0;
206
+ const a = Math.min(i, s) * 65536 + Math.max(i, s);
207
+ if (o.has(a) || !(this.model.geom_contype[t] & this.model.geom_conaffinity[e]) && !(this.model.geom_contype[e] & this.model.geom_conaffinity[t])) return !1;
208
+ if (!(n & this.mujoco.mjtDisableBit.mjDSBL_FILTERPARENT.value)) {
209
+ const c = this.model.body_weldid[i], l = this.model.body_weldid[s], m = this.model.body_weldid[this.model.body_parentid[c]], h = this.model.body_weldid[this.model.body_parentid[l]];
210
+ if (c !== 0 && m === l && l !== 0 || l !== 0 && h === c && c !== 0) return !1;
211
+ }
212
+ return !0;
213
+ }
214
+ }
215
+ function lt(v) {
216
+ return Object.assign(new Error(v.message), {
217
+ name: v.name,
218
+ ...v.stack ? { stack: v.stack } : {}
219
+ });
220
+ }
221
+ function C(v) {
222
+ return [
223
+ v.qpos.buffer,
224
+ v.qvel.buffer,
225
+ v.ctrl.buffer,
226
+ v.qfrc_applied.buffer,
227
+ v.qacc_warmstart.buffer,
228
+ v.act.buffer
229
+ ];
230
+ }
231
+ class mt {
232
+ constructor(t) {
233
+ x(this, "worker");
234
+ x(this, "ready", null);
235
+ x(this, "disposed", !1);
236
+ this.options = t, this.worker = new Worker(new URL(
237
+ /* @vite-ignore */
238
+ "" + new URL("assets/mujoco-physics-worker-MMv4Gmu_.js", import.meta.url).href,
239
+ import.meta.url
240
+ ), {
241
+ type: "module",
242
+ name: "mujoco-physics"
243
+ }), this.worker.onmessage = (e) => this.onMessage(e.data), this.worker.onerror = (e) => {
244
+ this.fail(new Error(e.message || "MuJoCo physics worker failed."));
245
+ };
246
+ }
247
+ initialize(t, e, i, s) {
248
+ return new Promise((o, r) => {
249
+ this.ready = { resolve: o, reject: r };
250
+ const n = t.slice();
251
+ this.worker.postMessage({
252
+ type: "init",
253
+ model: n.buffer,
254
+ state: e,
255
+ timestep: i,
256
+ groundHeight: s,
257
+ ...this.options.wasmUrl ? { wasmUrl: this.options.wasmUrl } : {},
258
+ ...this.options.wasmModule ? { wasmModule: this.options.wasmModule } : {}
259
+ }, [
260
+ n.buffer,
261
+ ...C(e)
262
+ ]);
263
+ });
264
+ }
265
+ step(t, e, i, s, o, r) {
266
+ this.disposed || this.worker.postMessage({
267
+ type: "step",
268
+ generation: t,
269
+ deltaSeconds: e,
270
+ timestep: i,
271
+ groundHeight: s,
272
+ state: o,
273
+ grab: r
274
+ }, C(o));
275
+ }
276
+ sync(t, e, i, s, o) {
277
+ this.disposed || this.worker.postMessage({
278
+ type: t,
279
+ generation: e,
280
+ timestep: i,
281
+ groundHeight: s,
282
+ state: o
283
+ }, C(o));
284
+ }
285
+ dispose() {
286
+ var t;
287
+ if (!this.disposed) {
288
+ this.disposed = !0;
289
+ try {
290
+ this.worker.postMessage({ type: "dispose" });
291
+ } catch {
292
+ }
293
+ this.worker.terminate(), (t = this.ready) == null || t.reject(new Error("MuJoCo physics worker was disposed.")), this.ready = null;
294
+ }
295
+ }
296
+ onMessage(t) {
297
+ var e;
298
+ if (t.type === "ready") {
299
+ (e = this.ready) == null || e.resolve(), this.ready = null;
300
+ return;
301
+ }
302
+ if (t.type === "snapshot") {
303
+ this.disposed || this.options.onSnapshot(t.snapshot);
304
+ return;
305
+ }
306
+ this.fail(lt(t.error));
307
+ }
308
+ fail(t) {
309
+ var e, i, s;
310
+ this.disposed || ((e = this.ready) == null || e.reject(t), this.ready = null, (s = (i = this.options).onError) == null || s.call(i, t));
311
+ }
312
+ }
313
+ const J = 1 / 240, ht = 1 / 960, ut = 0.25, L = 0.05, H = 8, Z = 12, dt = 1e3, k = 500, F = 30, P = 60, R = 1.2, W = 14, ft = 1 / 960, pt = 2, X = 20, _t = 0.15, gt = 10, bt = 0.25;
314
+ class wt {
315
+ constructor() {
316
+ x(this, "mujoco", null);
317
+ x(this, "model", null);
318
+ x(this, "data", null);
319
+ x(this, "grab", null);
320
+ x(this, "lastGrabForce", [0, 0, 0]);
321
+ x(this, "physicsWorker", null);
322
+ x(this, "workerGeneration", 0);
323
+ x(this, "workerRevision", 0);
324
+ x(this, "workerAppliedRevision", 0);
325
+ x(this, "workerStepInFlight", !1);
326
+ x(this, "initialControls", []);
327
+ x(this, "initialJoints", {});
328
+ x(this, "accumulator", 0);
329
+ x(this, "timestep", J);
330
+ x(this, "playbackTimestep", J);
331
+ /** Authored ground pose, captured before any seating. Re-seats start here. */
332
+ x(this, "initialGround", null);
333
+ /** Ground pose currently in the model; restored verbatim by reset(). */
334
+ x(this, "seatedGround", null);
335
+ x(this, "worldRotation", new B());
336
+ x(this, "flexTopologies", /* @__PURE__ */ new Map());
337
+ x(this, "topLevelBodies", []);
338
+ x(this, "stepTotal", 0);
339
+ x(this, "initialVelocities", []);
340
+ x(this, "jointTargets", /* @__PURE__ */ new Map());
341
+ x(this, "jointDriveActive", !1);
342
+ x(this, "jointDriveAccumulator", 0);
343
+ x(this, "jointDriveSettledSeconds", 0);
344
+ x(this, "jointDriveElapsed", 0);
345
+ x(this, "jointDriveDuration", 0);
346
+ x(this, "jointDriveBestError", 0);
347
+ x(this, "jointDriveStalledSeconds", 0);
348
+ x(this, "heldJointPoses", []);
349
+ x(this, "jointPreviewCollision", null);
350
+ x(this, "jointPreviewExclusions", null);
351
+ }
352
+ async initialize(t, e = {}) {
353
+ var f, g, j;
354
+ const i = e.wasmModule ? await e.wasmModule : void 0;
355
+ this.mujoco ?? (this.mujoco = await it({
356
+ locateFile: (b) => b.endsWith(".wasm") ? U(e.baseUrl) : b,
357
+ ...i ? {
358
+ instantiateWasm(b, _) {
359
+ return st(i, b, _);
360
+ }
361
+ } : {}
362
+ }));
363
+ const s = nt(this.mujoco.FS, t.files);
364
+ let o = null, r = null, n = null, a = null, c = J, l = null, m = null, h = J, d = t.initialControls ?? [];
365
+ try {
366
+ if (o = this.mujoco.MjModel.from_xml_path(s.writeEntry(t.xml)), c = o.opt.timestep, !Number.isFinite(c) || c <= 0)
367
+ throw new Error(`Invalid MuJoCo timestep: ${c}`);
368
+ for (const _ of t.massOverrides ?? []) {
369
+ const u = this.mujoco.mj_name2id(o, this.mujoco.mjtObj.mjOBJ_BODY.value, _.body);
370
+ if (u <= 0 || !Number.isFinite(_.mass) || _.mass <= 0 || !(o.body_mass[u] > 0)) throw new Error(`Invalid mass override: ${_.body}`);
371
+ const y = _.mass / o.body_mass[u];
372
+ o.body_mass[u] = _.mass;
373
+ for (let p = 0; p < 3; p++) o.body_inertia[u * 3 + p] *= y;
374
+ }
375
+ r = new this.mujoco.MjData(o), (f = t.massOverrides) != null && f.length && this.mujoco.mj_setConst(o, r), this.applyCenterOfMassOverrides(o, t.centerOfMassOverrides), (g = t.centerOfMassOverrides) != null && g.length && this.mujoco.mj_setConst(o, r), this.worldRotation.identity(), this.mujoco.mj_forward(o, r), d = this.applyAccelerationDrives(
376
+ o,
377
+ r,
378
+ t.accelerationDrives,
379
+ d
380
+ ), this.applyInitialControls(r, d), this.applyInitialJoints(o, r, t.initialJoints), this.applyInitialVelocities(o, r, t.initialVelocities), this.mujoco.mj_forward(o, r);
381
+ const b = this.mujoco.mj_name2id(o, this.mujoco.mjtObj.mjOBJ_GEOM.value, "__viewer_default_ground__");
382
+ if (n = b < 0 ? null : { id: b, height: o.geom_pos[b * 3 + 2], sameFrame: o.geom_sameframe[b] }, a = this.seatDefaultGround(o, r), Array.from(o.jnt_type).some((_) => _ === this.mujoco.mjtJoint.mjJNT_HINGE.value || _ === this.mujoco.mjtJoint.mjJNT_SLIDE.value) && (l = new ct(this.mujoco, o, r)), l && ((j = t.jointPreviewCollisionExcludes) != null && j.length)) {
383
+ m = Int32Array.from(o.exclude_signature);
384
+ const _ = /* @__PURE__ */ new Set();
385
+ for (const p of t.jointPreviewCollisionExcludes) {
386
+ const w = this.mujoco.mj_name2id(o, this.mujoco.mjtObj.mjOBJ_BODY.value, p.body1), N = this.mujoco.mj_name2id(o, this.mujoco.mjtObj.mjOBJ_BODY.value, p.body2);
387
+ if (w <= 0 || N <= 0) throw new Error(`Invalid joint preview collision pair: ${p.body1}, ${p.body2}`);
388
+ l.hasInitialBodyOverlap(w, N) || _.add(Math.min(w, N) * 65536 + Math.max(w, N));
389
+ }
390
+ const u = m.filter((p) => !_.has(p)), y = new Int32Array(m.length);
391
+ y.set(u, y.length - u.length), o.exclude_signature.set(y), this.mujoco.mj_forward(o, r);
392
+ }
393
+ h = this.actuatorTimestep(o, c), o.opt.timestep = h;
394
+ } catch (b) {
395
+ throw r == null || r.delete(), o == null || o.delete(), I(b, "E_MUJOCO_INITIALIZE");
396
+ } finally {
397
+ s.dispose();
398
+ }
399
+ this.disposeModel(), this.model = o, this.data = r, this.initialControls = d, this.initialJoints = t.initialJoints ?? {}, this.initialVelocities = t.initialVelocities ?? [], this.accumulator = 0, this.stepTotal = 0, this.timestep = h, this.playbackTimestep = h, this.initialGround = n, this.seatedGround = a, this.topLevelBodies = this.captureTopLevelBodies(o), this.jointPreviewCollision = l, this.jointPreviewExclusions = m, await this.initializePhysicsWorker(e, i);
400
+ }
401
+ get defaultGroundHeight() {
402
+ if (!this.mujoco || !this.model) return;
403
+ const t = this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj.mjOBJ_GEOM.value, "__viewer_default_ground__");
404
+ return t < 0 ? void 0 : this.model.geom_pos[t * 3 + 2];
405
+ }
406
+ /**
407
+ * Live flex vertex positions in world space. This is a Float64Array view into
408
+ * WASM memory; callers that write to Three.js attributes must convert to
409
+ * Float32 instead of assuming a zero-copy handoff.
410
+ */
411
+ readFlexVertices(t) {
412
+ if (!this.mujoco || !this.model || !this.data) return null;
413
+ const e = this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj.mjOBJ_FLEX.value, t);
414
+ if (e < 0) return null;
415
+ const i = this.model.flex_vertadr[e], s = this.model.flex_vertnum[e];
416
+ return this.data.flexvert_xpos.subarray(i * 3, (i + s) * 3);
417
+ }
418
+ listFlexes() {
419
+ if (!this.mujoco || !this.model) return [];
420
+ const t = this.model, e = [];
421
+ for (let i = 0; i < t.nflex; i++) {
422
+ const s = this.mujoco.mj_id2name(t, this.mujoco.mjtObj.mjOBJ_FLEX.value, i) ?? `flex_${i}`, o = i * 4;
423
+ e.push({
424
+ id: i,
425
+ name: s,
426
+ dim: Number(t.flex_dim[i]),
427
+ vertexAddress: Number(t.flex_vertadr[i]),
428
+ vertexCount: Number(t.flex_vertnum[i]),
429
+ elementAddress: Number(t.flex_elemadr[i]),
430
+ elementCount: Number(t.flex_elemnum[i]),
431
+ rgba: [
432
+ Number(t.flex_rgba[o] ?? 0.33),
433
+ Number(t.flex_rgba[o + 1] ?? 0.7),
434
+ Number(t.flex_rgba[o + 2] ?? 0.7),
435
+ Number(t.flex_rgba[o + 3] ?? 1)
436
+ ]
437
+ });
438
+ }
439
+ return e;
440
+ }
441
+ /**
442
+ * Finds an authored MuJoCo plane geom that is not the viewer's injected
443
+ * fallback ground. MuJoCo models normally carry their own floor; the viewer
444
+ * can then align its reflection overlay to that floor instead of drawing a
445
+ * second grid plane on top of it.
446
+ */
447
+ authoredGroundPlane() {
448
+ if (!this.mujoco || !this.model || !this.data) return null;
449
+ const t = this.model, e = this.data, i = this.mujoco.mjtGeom.mjGEOM_PLANE.value;
450
+ for (let s = 0; s < t.ngeom; s++) {
451
+ if (t.geom_type[s] !== i || t.geom_bodyid[s] !== 0) continue;
452
+ const o = this.mujoco.mj_id2name(t, this.mujoco.mjtObj.mjOBJ_GEOM.value, s);
453
+ if (ot(o)) continue;
454
+ const r = s * 3, n = s * 9;
455
+ return {
456
+ geomId: s,
457
+ center: [
458
+ Number(e.geom_xpos[r] ?? 0),
459
+ Number(e.geom_xpos[r + 1] ?? 0),
460
+ Number(e.geom_xpos[r + 2] ?? 0)
461
+ ],
462
+ rotation: [
463
+ Number(e.geom_xmat[n] ?? 1),
464
+ Number(e.geom_xmat[n + 1] ?? 0),
465
+ Number(e.geom_xmat[n + 2] ?? 0),
466
+ Number(e.geom_xmat[n + 3] ?? 0),
467
+ Number(e.geom_xmat[n + 4] ?? 1),
468
+ Number(e.geom_xmat[n + 5] ?? 0),
469
+ Number(e.geom_xmat[n + 6] ?? 0),
470
+ Number(e.geom_xmat[n + 7] ?? 0),
471
+ Number(e.geom_xmat[n + 8] ?? 1)
472
+ ],
473
+ halfSize: [
474
+ Math.max(0, Number(t.geom_size[r] ?? 0)),
475
+ Math.max(0, Number(t.geom_size[r + 1] ?? 0))
476
+ ]
477
+ };
478
+ }
479
+ return null;
480
+ }
481
+ /**
482
+ * Picks a local surface patch around the rendered triangle under the cursor.
483
+ * `hint` is the mesh-local triangle and its barycentric hit point. Restricting the
484
+ * nearest search to them avoids grabbing the opposite side of a thin garment.
485
+ * Full-DOF flexes expand along mesh edges; interpolated flexes map the hit
486
+ * vertex to the background grid nodes of its interpolation cell.
487
+ */
488
+ pickFlexVertex(t, e, i = []) {
489
+ if (!this.model || !this.data || !Number.isInteger(t)) return null;
490
+ const s = this.model;
491
+ if (t < 0 || t >= s.nflex) return null;
492
+ const o = Number(s.flex_vertadr[t]), r = Number(s.flex_vertnum[t]);
493
+ if (!Number.isInteger(o) || !Number.isInteger(r) || o < 0 || r <= 0) return null;
494
+ const n = Array.isArray(i) ? { vertices: i } : i;
495
+ if (n.skin)
496
+ return this.flexAnchorsFromWeights(t, this.skinSurfaceWeights(n), e);
497
+ const a = n.vertices.filter((g) => Number.isInteger(g) && g >= 0 && g < r);
498
+ let c = -1, l = Number.POSITIVE_INFINITY;
499
+ const m = (g) => {
500
+ const j = this.flexVertexPoint(o + g), b = j[0] - e[0], _ = j[1] - e[1], u = j[2] - e[2], y = b * b + _ * _ + u * u;
501
+ y < l && (l = y, c = g);
502
+ };
503
+ if (a.length)
504
+ for (const g of a) m(g);
505
+ else
506
+ for (let g = 0; g < r; g++) m(g);
507
+ if (c < 0) return null;
508
+ if (Number(s.flex_vertbodyid[o + c] ?? 0) <= 0) return this.pickFlexNode(t, e, n);
509
+ const d = this.surfaceVertexWeights(t, n);
510
+ if (d.size) {
511
+ const g = this.flexAnchorsFromWeights(t, d, e);
512
+ if (g) return g;
513
+ }
514
+ const f = this.flexVertexPatch(t, c, e, 12);
515
+ return this.flexAnchorsFromWeights(
516
+ t,
517
+ new Map(f.map((g) => [g, 1 / f.length])),
518
+ e
519
+ );
520
+ }
521
+ surfaceVertexWeights(t, e) {
522
+ var n, a;
523
+ const i = Number(((n = this.model) == null ? void 0 : n.flex_vertnum[t]) ?? 0), s = /* @__PURE__ */ new Map(), o = e.barycentric, r = e.vertices;
524
+ if (o && o.length >= 3 && r.length >= 3) {
525
+ const c = o.slice(0, 3).reduce((l, m) => l + Math.max(0, m), 0);
526
+ if (c > 0)
527
+ for (let l = 0; l < 3; l++) {
528
+ const m = r[l];
529
+ m < 0 || m >= i || s.set(m, (s.get(m) ?? 0) + Math.max(0, o[l]) / c);
530
+ }
531
+ }
532
+ if (Number(((a = this.model) == null ? void 0 : a.flex_dim[t]) ?? 0) === 2 && s.size > 0) {
533
+ const c = this.flexTopology(t);
534
+ if (c)
535
+ for (const [l, m] of [...s])
536
+ for (let h = c.offsets[l]; h < c.offsets[l + 1]; h++) {
537
+ const d = c.neighbors[h];
538
+ d >= i || s.set(d, (s.get(d) ?? 0) + m * 0.25);
539
+ }
540
+ }
541
+ return s;
542
+ }
543
+ skinSurfaceWeights(t) {
544
+ const e = /* @__PURE__ */ new Map(), i = t.skin;
545
+ if (!i) return e;
546
+ const s = t.barycentric ?? [1, 0, 0], o = s.slice(0, 3).reduce((r, n) => r + Math.max(0, n), 0);
547
+ if (!(o > 0)) return e;
548
+ for (let r = 0; r < 3; r++) {
549
+ const n = t.vertices[r];
550
+ if (!Number.isInteger(n) || n < 0) continue;
551
+ const a = Math.max(0, s[r] ?? 0) / o;
552
+ if (a !== 0)
553
+ for (let c = 0; c < 4; c++) {
554
+ const l = Number(i.tetIndices[n * 4 + c] ?? -1), m = Number(i.weights[n * 4 + c] ?? 0);
555
+ l < 0 || !(m > 0) || e.set(l, (e.get(l) ?? 0) + m * a);
556
+ }
557
+ }
558
+ return e;
559
+ }
560
+ flexAnchorsFromWeights(t, e, i) {
561
+ if (!this.model || !this.data) return null;
562
+ const s = this.model, o = Number(s.flex_vertadr[t] ?? 0), r = Number(s.flex_vertnum[t] ?? 0), n = [...e].filter(([l, m]) => l >= 0 && l < r && m > 0).map(([l, m]) => {
563
+ const h = o + l, d = Number(s.flex_vertbodyid[h] ?? 0);
564
+ return d <= 0 ? null : { local: l, vertex: h, bodyId: d, weight: m, world: this.flexVertexPoint(h) };
565
+ }).filter((l) => l != null).sort((l, m) => m.weight - l.weight).slice(0, 16);
566
+ if (n.length === 0) return null;
567
+ const a = n.reduce((l, m) => l + m.weight, 0);
568
+ if (!(a > 0)) return null;
569
+ const c = n[0];
570
+ return {
571
+ bodyId: c.bodyId,
572
+ vertexIndex: c.vertex,
573
+ localPoint: this.flexVertexLocalPoint(c.vertex, c.bodyId),
574
+ anchors: n.map((l) => ({
575
+ bodyId: l.bodyId,
576
+ localPoint: this.flexVertexLocalPoint(l.vertex, l.bodyId),
577
+ targetOffset: [
578
+ l.world[0] - i[0],
579
+ l.world[1] - i[1],
580
+ l.world[2] - i[2]
581
+ ],
582
+ weight: l.weight / a
583
+ }))
584
+ };
585
+ }
586
+ flexVertexPoint(t) {
587
+ const e = this.data.flexvert_xpos, i = t * 3;
588
+ return [
589
+ Number(e[i] ?? 0),
590
+ Number(e[i + 1] ?? 0),
591
+ Number(e[i + 2] ?? 0)
592
+ ];
593
+ }
594
+ flexVertexLocalPoint(t, e) {
595
+ const i = this.data, s = i.flexvert_xpos, o = t * 3, r = e * 3, n = e * 9, a = Number(s[o] ?? 0) - Number(i.xpos[r] ?? 0), c = Number(s[o + 1] ?? 0) - Number(i.xpos[r + 1] ?? 0), l = Number(s[o + 2] ?? 0) - Number(i.xpos[r + 2] ?? 0), m = i.xmat;
596
+ return [
597
+ Number(m[n] ?? 1) * a + Number(m[n + 3] ?? 0) * c + Number(m[n + 6] ?? 0) * l,
598
+ Number(m[n + 1] ?? 0) * a + Number(m[n + 4] ?? 1) * c + Number(m[n + 7] ?? 0) * l,
599
+ Number(m[n + 2] ?? 0) * a + Number(m[n + 5] ?? 0) * c + Number(m[n + 8] ?? 1) * l
600
+ ];
601
+ }
602
+ /**
603
+ * Breadth-first expansion over the flex element graph. Unlike a world-space
604
+ * radius this cannot jump across a folded sleeve or two nearby cloth layers.
605
+ */
606
+ flexVertexPatch(t, e, i, s) {
607
+ var l;
608
+ const o = this.flexTopology(t);
609
+ if (!o) return this.flexVertexPatchByDistance(t, e, i, s);
610
+ const r = Number(((l = this.model) == null ? void 0 : l.flex_vertnum[t]) ?? 0), n = new Uint8Array(r), a = [e];
611
+ n[e] = 1;
612
+ let c = 0;
613
+ for (; c < a.length && a.length < s; ) {
614
+ const m = a[c++];
615
+ for (let h = o.offsets[m]; h < o.offsets[m + 1]; h++) {
616
+ const d = o.neighbors[h];
617
+ if (!(d >= r || n[d]) && (n[d] = 1, a.push(d), a.length >= s))
618
+ break;
619
+ }
620
+ }
621
+ return a;
622
+ }
623
+ flexVertexPatchByDistance(t, e, i, s) {
624
+ if (!this.model || !this.data) return [e];
625
+ const o = this.model, r = Number(o.flex_vertadr[t]), n = Number(o.flex_vertnum[t]), a = this.data.flexvert_xpos, c = (r + e) * 3;
626
+ let l = Number.POSITIVE_INFINITY;
627
+ for (let f = 0; f < n; f++) {
628
+ if (f === e) continue;
629
+ const g = (r + f) * 3, j = Math.hypot(
630
+ Number(a[g] ?? 0) - Number(a[c] ?? 0),
631
+ Number(a[g + 1] ?? 0) - Number(a[c + 1] ?? 0),
632
+ Number(a[g + 2] ?? 0) - Number(a[c + 2] ?? 0)
633
+ );
634
+ j > 1e-9 && j < l && (l = j);
635
+ }
636
+ const m = Math.max(0, Number(o.flex_radius[t] ?? 0)), h = Math.max(m * 5, Number.isFinite(l) ? l * 1.6 : 0, 0.02), d = [];
637
+ for (let f = 0; f < n; f++) {
638
+ const g = (r + f) * 3, j = (Number(a[g] ?? 0) - i[0]) ** 2 + (Number(a[g + 1] ?? 0) - i[1]) ** 2 + (Number(a[g + 2] ?? 0) - i[2]) ** 2;
639
+ j <= h * h && d.push({ local: f, distance: j });
640
+ }
641
+ return d.sort((f, g) => f.distance - g.distance), d.slice(0, s).map((f) => f.local);
642
+ }
643
+ flexTopology(t) {
644
+ var d;
645
+ if (this.flexTopologies.has(t)) return this.flexTopologies.get(t) ?? null;
646
+ if (!this.model) return null;
647
+ const e = this.model, i = Number(e.flex_dim[t] ?? 0), s = Number(e.flex_vertnum[t] ?? 0), o = Number(e.flex_elemnum[t] ?? 0);
648
+ if (i < 2 || i > 3 || s <= 0 || o <= 0)
649
+ return this.flexTopologies.set(t, null), null;
650
+ const r = i + 1, n = Number(((d = e.flex_elemdataadr) == null ? void 0 : d[t]) ?? Number(e.flex_elemadr[t]) * r), a = e.flex_elem, c = new Uint32Array(s + 1);
651
+ for (let f = 0; f < o; f++) {
652
+ const g = n + f * r;
653
+ for (let j = 0; j < r; j++) {
654
+ const b = Number(a[g + j] ?? -1);
655
+ if (!(b < 0 || b >= s))
656
+ for (let _ = j + 1; _ < r; _++) {
657
+ const u = Number(a[g + _] ?? -1);
658
+ u < 0 || u >= s || b === u || (c[b + 1]++, c[u + 1]++);
659
+ }
660
+ }
661
+ }
662
+ for (let f = 0; f < s; f++) c[f + 1] += c[f];
663
+ const l = new Uint32Array(c[s]), m = Uint32Array.from(c.subarray(0, s));
664
+ for (let f = 0; f < o; f++) {
665
+ const g = n + f * r;
666
+ for (let j = 0; j < r; j++) {
667
+ const b = Number(a[g + j] ?? -1);
668
+ if (!(b < 0 || b >= s))
669
+ for (let _ = j + 1; _ < r; _++) {
670
+ const u = Number(a[g + _] ?? -1);
671
+ u < 0 || u >= s || b === u || (l[m[b]++] = u, l[m[u]++] = b);
672
+ }
673
+ }
674
+ }
675
+ const h = { offsets: c, neighbors: l };
676
+ return this.flexTopologies.set(t, h), h;
677
+ }
678
+ /**
679
+ * Interpolated flexes (dof=trilinear/quadratic) expose draggable background
680
+ * nodes instead of per-source-vertex bodies. Pick the nearest node body so
681
+ * the same grab path can move a local part of a high-poly garment.
682
+ */
683
+ pickFlexNode(t, e, i) {
684
+ var g, j;
685
+ if (!this.model || !this.data) return null;
686
+ const s = this.model, o = this.data, r = Number(((g = s.flex_nodeadr) == null ? void 0 : g[t]) ?? 0), n = Number(((j = s.flex_nodenum) == null ? void 0 : j[t]) ?? 0);
687
+ if (!Number.isInteger(r) || !Number.isInteger(n) || r < 0 || n <= 0) return null;
688
+ if (i) {
689
+ const b = this.nodeAnchorsFromWeights(
690
+ t,
691
+ this.surfaceNodeWeights(t, i),
692
+ e
693
+ );
694
+ if (b) return b;
695
+ }
696
+ const a = [], c = (b) => {
697
+ var N;
698
+ const _ = Number(((N = s.flex_nodebodyid) == null ? void 0 : N[r + b]) ?? 0);
699
+ if (_ <= 0) return;
700
+ const u = _ * 3, y = Number(o.xpos[u] ?? 0) - e[0], p = Number(o.xpos[u + 1] ?? 0) - e[1], w = Number(o.xpos[u + 2] ?? 0) - e[2];
701
+ a.push({ index: b, bodyId: _, distance: y * y + p * p + w * w });
702
+ };
703
+ for (let b = 0; b < n; b++) c(b);
704
+ if (a.length === 0) return null;
705
+ a.sort((b, _) => b.distance - _.distance);
706
+ const l = a[0];
707
+ let m = Number.POSITIVE_INFINITY;
708
+ for (let b = 0; b < a.length; b++) {
709
+ const _ = a[b].bodyId * 3;
710
+ for (let u = b + 1; u < a.length; u++) {
711
+ const y = a[u].bodyId * 3, p = Math.hypot(
712
+ Number(o.xpos[_] ?? 0) - Number(o.xpos[y] ?? 0),
713
+ Number(o.xpos[_ + 1] ?? 0) - Number(o.xpos[y + 1] ?? 0),
714
+ Number(o.xpos[_ + 2] ?? 0) - Number(o.xpos[y + 2] ?? 0)
715
+ );
716
+ p > 1e-9 && p < m && (m = p);
717
+ }
718
+ }
719
+ const h = Math.max(Number.isFinite(m) ? m * 2.5 : 0, 0.02), d = h * h, f = a.filter((b) => b.distance <= d).slice(0, 9);
720
+ return f.includes(l) || f.push(l), this.nodeAnchorsFromWeights(
721
+ t,
722
+ new Map(f.map((b) => [b.index, 1 / f.length])),
723
+ e
724
+ );
725
+ }
726
+ /**
727
+ * Map a source mesh vertex to the background-grid nodes surrounding it.
728
+ * `flex_vert0` stores the source vertex in the interpolated [0,1]^3
729
+ * parametric frame, while `flex_cellnum` gives the number of cells per axis.
730
+ */
731
+ interpolatedCellNodeWeights(t, e) {
732
+ var b;
733
+ if (!this.model) return [];
734
+ const i = this.model, s = Math.max(1, Math.abs(Number(((b = i.flex_interp) == null ? void 0 : b[t]) ?? 0))), o = Number(i.flex_cellnum[t * 3] ?? 0), r = Number(i.flex_cellnum[t * 3 + 1] ?? 0), n = Number(i.flex_cellnum[t * 3 + 2] ?? 0), a = Number(i.flex_vertnum[t] ?? 0);
735
+ if (s <= 0 || o <= 0 || r <= 0 || n <= 0 || e < 0 || e >= a) return [];
736
+ const c = o * s + 1, l = r * s + 1, m = n * s + 1;
737
+ if (c <= 0 || l <= 0 || m <= 0) return [];
738
+ const h = [c, l, m], d = (Number(i.flex_vertadr[t] ?? 0) + e) * 3, f = [];
739
+ for (let _ = 0; _ < 3; _++) {
740
+ const u = h[_] - 1, y = Math.max(0, Math.min(u, Number(i.flex_vert0[d + _] ?? 0) * u));
741
+ if (s === 1) {
742
+ const p = Math.min(Math.floor(y), u), w = Math.min(p + 1, u), N = p === w ? 0 : y - p;
743
+ f.push(p === w ? [{ index: p, weight: 1 }] : [{ index: p, weight: 1 - N }, { index: w, weight: N }]);
744
+ } else {
745
+ const p = Math.min(Math.floor(y), u), w = [.../* @__PURE__ */ new Set([
746
+ Math.max(p - 1, 0),
747
+ p,
748
+ Math.min(p + 1, u)
749
+ ])];
750
+ f.push(w.map((N) => ({ index: N, weight: 1 / w.length })));
751
+ }
752
+ }
753
+ const g = /* @__PURE__ */ new Map();
754
+ for (const _ of f[0])
755
+ for (const u of f[1])
756
+ for (const y of f[2]) {
757
+ const p = _.index * l * m + u.index * m + y.index, w = _.weight * u.weight * y.weight;
758
+ g.set(p, (g.get(p) ?? 0) + w);
759
+ }
760
+ const j = [...g.values()].reduce((_, u) => _ + u, 0);
761
+ return j > 0 ? [...g].map(([_, u]) => ({ index: _, weight: u / j })) : [];
762
+ }
763
+ surfaceNodeWeights(t, e) {
764
+ const i = /* @__PURE__ */ new Map(), s = e.barycentric;
765
+ if (!s || s.length < 3) return i;
766
+ const o = s.slice(0, 3).reduce((r, n) => r + Math.max(0, n), 0);
767
+ if (!(o > 0)) return i;
768
+ for (let r = 0; r < 3; r++) {
769
+ const n = e.vertices[r];
770
+ if (!Number.isInteger(n) || n < 0) continue;
771
+ const a = Math.max(0, s[r]) / o;
772
+ if (a !== 0)
773
+ for (const c of this.interpolatedCellNodeWeights(t, n))
774
+ i.set(c.index, (i.get(c.index) ?? 0) + c.weight * a);
775
+ }
776
+ return i;
777
+ }
778
+ nodeAnchorsFromWeights(t, e, i) {
779
+ var l, m;
780
+ if (!this.model || !this.data) return null;
781
+ const s = this.model, o = Number(((l = s.flex_nodeadr) == null ? void 0 : l[t]) ?? 0), r = Number(((m = s.flex_nodenum) == null ? void 0 : m[t]) ?? 0), n = [...e].filter(([h, d]) => h >= 0 && h < r && d > 0).map(([h, d]) => {
782
+ var j;
783
+ const f = Number(((j = s.flex_nodebodyid) == null ? void 0 : j[o + h]) ?? 0);
784
+ if (f <= 0) return null;
785
+ const g = f * 3;
786
+ return {
787
+ index: h,
788
+ bodyId: f,
789
+ weight: d,
790
+ world: [
791
+ Number(this.data.xpos[g] ?? 0),
792
+ Number(this.data.xpos[g + 1] ?? 0),
793
+ Number(this.data.xpos[g + 2] ?? 0)
794
+ ]
795
+ };
796
+ }).filter((h) => h != null).sort((h, d) => d.weight - h.weight).slice(0, 16);
797
+ if (n.length === 0) return null;
798
+ const a = n.reduce((h, d) => h + d.weight, 0);
799
+ if (!(a > 0)) return null;
800
+ const c = n[0];
801
+ return {
802
+ bodyId: c.bodyId,
803
+ vertexIndex: c.index,
804
+ localPoint: [0, 0, 0],
805
+ anchors: n.map((h) => ({
806
+ bodyId: h.bodyId,
807
+ localPoint: [0, 0, 0],
808
+ targetOffset: [
809
+ h.world[0] - i[0],
810
+ h.world[1] - i[1],
811
+ h.world[2] - i[2]
812
+ ],
813
+ weight: h.weight / a
814
+ }))
815
+ };
816
+ }
817
+ /** Total authored mass of a flex, used to scale interactive grab force. */
818
+ flexMass(t) {
819
+ var o, r, n;
820
+ if (!this.model || !Number.isInteger(t) || t < 0 || t >= this.model.nflex) return 0;
821
+ const e = Number(this.model.flex_vertadr[t] ?? 0), i = Number(this.model.flex_vertnum[t] ?? 0);
822
+ let s = 0;
823
+ for (let a = e; a < e + i; a++) {
824
+ const c = Number(this.model.flex_vertbodyid[a] ?? 0);
825
+ c > 0 && (s += Number(this.model.body_mass[c] ?? 0));
826
+ }
827
+ if (s <= 0) {
828
+ const a = Number(((o = this.model.flex_nodeadr) == null ? void 0 : o[t]) ?? 0), c = Number(((r = this.model.flex_nodenum) == null ? void 0 : r[t]) ?? 0);
829
+ for (let l = 0; l < c; l++) {
830
+ const m = Number(((n = this.model.flex_nodebodyid) == null ? void 0 : n[a + l]) ?? 0);
831
+ m > 0 && (s += Number(this.model.body_mass[m] ?? 0));
832
+ }
833
+ }
834
+ return s;
835
+ }
836
+ flexElements(t) {
837
+ if (!this.model) return new Int32Array();
838
+ const e = t.dim + 1, i = t.elementAddress * e, s = this.model.flex_elem, o = new Int32Array(t.elementCount * e);
839
+ for (let r = 0; r < o.length; r++) o[r] = Number(s[i + r]) | 0;
840
+ return o;
841
+ }
842
+ /**
843
+ * Re-orients the compiled physics to the given authored up axis by rotating
844
+ * every top-level body about the world origin. Gravity stays -Z and the
845
+ * viewer ground stays the authored horizontal plane, so a cup that was
846
+ * standing now genuinely topples and settles on its side — the alternative,
847
+ * rotating only the rendered scene graph, would leave the visuals and the
848
+ * simulation in different frames.
849
+ *
850
+ * The full current state (free-joint positions, orientations and velocities)
851
+ * is rotated by the same delta, so a paused or running simulation is carried
852
+ * over instead of being re-seeded.
853
+ */
854
+ setWorldRotation(t) {
855
+ var o;
856
+ if (!this.mujoco || !this.model || !this.data) return;
857
+ const e = this.model, i = this.data;
858
+ if (t.equals(this.worldRotation)) return;
859
+ const s = t.clone().multiply(this.worldRotation.clone().invert());
860
+ this.rotateReferenceFrames(this.topLevelBodies, t), this.rotateState(this.topLevelBodies, e, i, s), this.worldRotation.copy(t), this.mujoco.mj_forward(e, i), this.seatedGround = this.seatDefaultGround(e, i, (o = this.initialGround) == null ? void 0 : o.height), this.accumulator = 0;
861
+ }
862
+ captureTopLevelBodies(t) {
863
+ const e = this.mujoco, i = [];
864
+ for (let s = 1; s < t.nbody; s++) {
865
+ if (t.body_parentid[s] !== 0) continue;
866
+ const o = t.body_jntadr[s], r = t.body_jntnum[s] === 1 && o >= 0 && t.jnt_type[o] === e.mjtJoint.mjJNT_FREE.value ? o : -1, n = s * 3, a = s * 4;
867
+ i.push({
868
+ id: s,
869
+ position: new D(t.body_pos[n], t.body_pos[n + 1], t.body_pos[n + 2]),
870
+ quaternion: new B(t.body_quat[a + 1], t.body_quat[a + 2], t.body_quat[a + 3], t.body_quat[a]),
871
+ freeJoint: r
872
+ });
873
+ }
874
+ return i;
875
+ }
876
+ /** Writes the rotated reference pose, which reset() and fixed bases follow. */
877
+ rotateReferenceFrames(t, e) {
878
+ const i = this.model;
879
+ for (const s of t) {
880
+ const o = s.position.clone().applyQuaternion(e), r = e.clone().multiply(s.quaternion), n = s.id * 3, a = s.id * 4;
881
+ if (i.body_pos[n] = o.x, i.body_pos[n + 1] = o.y, i.body_pos[n + 2] = o.z, i.body_quat[a] = r.w, i.body_quat[a + 1] = r.x, i.body_quat[a + 2] = r.y, i.body_quat[a + 3] = r.z, i.body_sameframe[s.id] && (i.body_sameframe[s.id] = 0), s.freeJoint < 0) continue;
882
+ const c = i.jnt_qposadr[s.freeJoint];
883
+ i.qpos0[c] = o.x, i.qpos0[c + 1] = o.y, i.qpos0[c + 2] = o.z, i.qpos0[c + 3] = r.w, i.qpos0[c + 4] = r.x, i.qpos0[c + 5] = r.y, i.qpos0[c + 6] = r.z;
884
+ }
885
+ }
886
+ /** Rotates the live free-joint state so the simulation keeps its progress. */
887
+ rotateState(t, e, i, s) {
888
+ for (const o of t) {
889
+ if (o.freeJoint < 0) continue;
890
+ const r = e.jnt_qposadr[o.freeJoint], n = e.jnt_dofadr[o.freeJoint], a = new D(i.qpos[r], i.qpos[r + 1], i.qpos[r + 2]).applyQuaternion(s);
891
+ i.qpos[r] = a.x, i.qpos[r + 1] = a.y, i.qpos[r + 2] = a.z;
892
+ const c = new B(i.qpos[r + 4], i.qpos[r + 5], i.qpos[r + 6], i.qpos[r + 3]).premultiply(s);
893
+ i.qpos[r + 3] = c.w, i.qpos[r + 4] = c.x, i.qpos[r + 5] = c.y, i.qpos[r + 6] = c.z;
894
+ const l = new D(i.qvel[n], i.qvel[n + 1], i.qvel[n + 2]).applyQuaternion(s);
895
+ i.qvel[n] = l.x, i.qvel[n + 1] = l.y, i.qvel[n + 2] = l.z;
896
+ const m = new D(i.qvel[n + 3], i.qvel[n + 4], i.qvel[n + 5]).applyQuaternion(s);
897
+ i.qvel[n + 3] = m.x, i.qvel[n + 4] = m.y, i.qvel[n + 5] = m.z;
898
+ }
899
+ }
900
+ /** Lower only the viewer-owned plane, never authored bodies or authored floors.
901
+ * Run after forward kinematics, not during stepping (the floor must not follow falling bodies).
902
+ * `baseHeight` re-seats from a stable reference; omitting it lowers from the current pose.
903
+ */
904
+ seatDefaultGround(t, e, i) {
905
+ const s = this.mujoco, o = s.mj_name2id(t, s.mjtObj.mjOBJ_GEOM.value, "__viewer_default_ground__");
906
+ if (o < 0 || t.geom_bodyid[o] !== 0 || t.geom_type[o] !== s.mjtGeom.mjGEOM_PLANE.value) return null;
907
+ let r = i ?? t.geom_pos[o * 3 + 2];
908
+ for (let n = 0; n < t.ngeom; n++) {
909
+ if (n === o || t.geom_type[n] === s.mjtGeom.mjGEOM_PLANE.value || !(t.geom_contype[n] & t.geom_conaffinity[o]) && !(t.geom_conaffinity[n] & t.geom_contype[o])) continue;
910
+ const a = this.geomBottom(t, e, n), c = Math.max(1e-3, t.geom_margin[n] + t.geom_margin[o]);
911
+ Number.isFinite(a) && a < r && (r = Math.min(r, a - c));
912
+ }
913
+ return r !== t.geom_pos[o * 3 + 2] && (t.geom_pos[o * 3 + 2] = r, t.geom_sameframe[o] = 0, s.mj_forward(t, e)), { id: o, height: r, sameFrame: t.geom_sameframe[o] };
914
+ }
915
+ /**
916
+ * Resolve the lowest world-space point directly from MuJoCo's primitive
917
+ * parameters. Rotating a mesh's local AABB into world space is conservative:
918
+ * for a long, rotated shape it can sit far below the actual geometry. Use the
919
+ * compiled vertices for mesh-backed geoms so the ground reflects the real
920
+ * lowest point rather than the corners of its local bounding box.
921
+ */
922
+ geomBottom(t, e, i) {
923
+ const s = this.mujoco, o = e.geom_xpos[i * 3 + 2], r = i * 3, n = i * 9, a = t.geom_type[i], c = Math.abs(t.geom_size[r]), l = Math.abs(t.geom_size[r + 1]), m = Math.abs(t.geom_size[r + 2]);
924
+ if (a === s.mjtGeom.mjGEOM_SPHERE.value)
925
+ return o - c;
926
+ if (a === s.mjtGeom.mjGEOM_CAPSULE.value)
927
+ return o - c - Math.abs(e.geom_xmat[n + 8]) * l;
928
+ if (a === s.mjtGeom.mjGEOM_CYLINDER.value) {
929
+ const _ = e.geom_xmat[n + 8];
930
+ return o - Math.abs(_) * l - Math.sqrt(Math.max(0, 1 - _ * _)) * c;
931
+ }
932
+ if (a === s.mjtGeom.mjGEOM_ELLIPSOID.value)
933
+ return o - Math.hypot(
934
+ e.geom_xmat[n + 2] * c,
935
+ e.geom_xmat[n + 5] * l,
936
+ e.geom_xmat[n + 8] * m
937
+ );
938
+ if (a === s.mjtGeom.mjGEOM_BOX.value)
939
+ return o - Math.abs(e.geom_xmat[n + 2]) * c - Math.abs(e.geom_xmat[n + 5]) * l - Math.abs(e.geom_xmat[n + 8]) * m;
940
+ if (a === s.mjtGeom.mjGEOM_MESH.value || a === s.mjtGeom.mjGEOM_SDF.value) {
941
+ const _ = t.geom_dataid[i];
942
+ if (_ < 0 || _ >= t.nmesh) return Number.POSITIVE_INFINITY;
943
+ const u = t.mesh_vertadr[_], y = t.mesh_vertnum[_];
944
+ if (!Number.isInteger(u) || !Number.isInteger(y) || u < 0 || y <= 0 || u + y > t.nmeshvert)
945
+ return Number.POSITIVE_INFINITY;
946
+ let p = Number.POSITIVE_INFINITY;
947
+ for (let w = u; w < u + y; w++) {
948
+ const N = w * 3, M = o + e.geom_xmat[n + 6] * t.mesh_vert[N] + e.geom_xmat[n + 7] * t.mesh_vert[N + 1] + e.geom_xmat[n + 8] * t.mesh_vert[N + 2];
949
+ Number.isFinite(M) && M < p && (p = M);
950
+ }
951
+ return p;
952
+ }
953
+ const h = i * 6, d = t.geom_aabb[h + 3], f = t.geom_aabb[h + 4], g = t.geom_aabb[h + 5];
954
+ if (![d, f, g].every((_) => Number.isFinite(_) && _ >= 0))
955
+ return Number.POSITIVE_INFINITY;
956
+ const j = o + e.geom_xmat[n + 6] * t.geom_aabb[h] + e.geom_xmat[n + 7] * t.geom_aabb[h + 1] + e.geom_xmat[n + 8] * t.geom_aabb[h + 2], b = Math.abs(e.geom_xmat[n + 6]) * d + Math.abs(e.geom_xmat[n + 7]) * f + Math.abs(e.geom_xmat[n + 8]) * g;
957
+ return j - b;
958
+ }
959
+ beginGrab({
960
+ bodyId: t,
961
+ localPoint: e,
962
+ target: i,
963
+ anchors: s,
964
+ stiffness: o,
965
+ damping: r,
966
+ maxForce: n,
967
+ maxTargetSpeed: a = R,
968
+ targetResponse: c = W
969
+ }) {
970
+ var u, y;
971
+ const l = Math.max(((u = this.model) == null ? void 0 : u.body_mass[t]) ?? 0, 0), m = o ?? dt, h = this.bodyInertia(t);
972
+ let d = l, f = (h[0] + h[1] + h[2]) / 3;
973
+ if (this.model && this.data && l > 0) {
974
+ const p = this.data.xmat.subarray(t * 9, t * 9 + 9), w = this.data.xpos.subarray(t * 3, t * 3 + 3), N = this.data.xipos.subarray(t * 3, t * 3 + 3), M = [
975
+ w[0] + p[0] * e[0] + p[1] * e[1] + p[2] * e[2],
976
+ w[1] + p[3] * e[0] + p[4] * e[1] + p[5] * e[2],
977
+ w[2] + p[6] * e[0] + p[7] * e[1] + p[8] * e[2]
978
+ ], O = [M[0] - N[0], M[1] - N[1], M[2] - N[2]];
979
+ d = V(l, h, p, O);
980
+ const E = ((y = this.model.body_invweight0) == null ? void 0 : y[t * 2 + 1]) ?? 0;
981
+ E > 0 && (f = 1 / E);
982
+ }
983
+ const g = r ?? 2 * Math.sqrt(m) * d, j = n ?? l * F, b = d > 0 ? j / d : F;
984
+ this.setTimestep(this.grabTimestep(
985
+ s != null && s.length ? m / s.length : m
986
+ ));
987
+ const _ = [i[0], i[1], i[2]];
988
+ this.grab = {
989
+ bodyId: t,
990
+ localPoint: [e[0], e[1], e[2]],
991
+ target: [..._],
992
+ requestedTarget: _,
993
+ stiffness: m,
994
+ damping: g,
995
+ dampingOverridden: r != null,
996
+ maxForce: j,
997
+ rotationalStiffness: k,
998
+ maxAngularAcceleration: P,
999
+ maxAcceleration: b,
1000
+ effectiveMass: d,
1001
+ representativeInertia: Math.max(f, 0),
1002
+ strength: 1,
1003
+ maxTargetSpeed: a,
1004
+ targetResponse: c,
1005
+ anchors: s != null && s.length ? s.map((p) => ({
1006
+ bodyId: p.bodyId,
1007
+ localPoint: [p.localPoint[0], p.localPoint[1], p.localPoint[2]],
1008
+ ...p.targetOffset ? {
1009
+ targetOffset: [
1010
+ p.targetOffset[0],
1011
+ p.targetOffset[1],
1012
+ p.targetOffset[2]
1013
+ ]
1014
+ } : {},
1015
+ ...p.weight != null ? { weight: p.weight } : {}
1016
+ })) : void 0
1017
+ };
1018
+ }
1019
+ updateGrabTarget(t) {
1020
+ this.grab && (this.grab.requestedTarget = [t[0], t[1], t[2]]);
1021
+ }
1022
+ updateGrabStrength(t) {
1023
+ this.grab && (this.grab.strength = t);
1024
+ }
1025
+ applyGrabForce() {
1026
+ var w, N, M;
1027
+ if (!this.grab || !this.model || !this.data || !this.mujoco) return;
1028
+ const t = this.grab.anchors;
1029
+ if (t != null && t.length) {
1030
+ const O = t.reduce((T, A) => T + (A.weight ?? 1), 0);
1031
+ this.data.qfrc_applied.fill(0);
1032
+ const E = [0, 0, 0];
1033
+ for (const T of t) {
1034
+ const A = O > 0 ? (T.weight ?? 1) / O : 1 / t.length, G = this.grab.stiffness * A, q = this.grab.maxForce * A, Q = (this.grab.rotationalStiffness ?? k) * A, K = [
1035
+ this.grab.target[0] + (((w = T.targetOffset) == null ? void 0 : w[0]) ?? 0),
1036
+ this.grab.target[1] + (((N = T.targetOffset) == null ? void 0 : N[1]) ?? 0),
1037
+ this.grab.target[2] + (((M = T.targetOffset) == null ? void 0 : M[2]) ?? 0)
1038
+ ], S = this.grabAnchorWrench(
1039
+ T.bodyId,
1040
+ T.localPoint,
1041
+ K,
1042
+ G,
1043
+ q,
1044
+ Q,
1045
+ this.grab.strength
1046
+ );
1047
+ S && (E[0] += S.force[0], E[1] += S.force[1], E[2] += S.force[2], this.mujoco.mj_applyFT(
1048
+ this.model,
1049
+ this.data,
1050
+ S.force,
1051
+ S.torque,
1052
+ S.center,
1053
+ T.bodyId,
1054
+ this.data.qfrc_applied
1055
+ ));
1056
+ }
1057
+ this.lastGrabForce = E;
1058
+ return;
1059
+ }
1060
+ const {
1061
+ bodyId: e,
1062
+ localPoint: i,
1063
+ target: s,
1064
+ stiffness: o,
1065
+ strength: r,
1066
+ rotationalStiffness: n,
1067
+ maxAcceleration: a,
1068
+ maxAngularAcceleration: c,
1069
+ representativeInertia: l
1070
+ } = this.grab, m = this.bodyInertia(e), h = n ?? k, d = a ?? F, f = c ?? P, g = l ?? (m[0] + m[1] + m[2]) / 3, j = this.data.xmat.subarray(e * 9, e * 9 + 9), b = this.data.xpos.subarray(e * 3, e * 3 + 3), _ = [
1071
+ b[0] + j[0] * i[0] + j[1] * i[1] + j[2] * i[2],
1072
+ b[1] + j[3] * i[0] + j[4] * i[1] + j[5] * i[2],
1073
+ b[2] + j[6] * i[0] + j[7] * i[1] + j[8] * i[2]
1074
+ ], u = this.data.xipos.subarray(e * 3, e * 3 + 3), y = this.data.cvel.subarray(e * 6, e * 6 + 6), p = Y({
1075
+ target: s,
1076
+ point: _,
1077
+ center: u,
1078
+ spatialVelocity: y,
1079
+ rotation: j,
1080
+ mass: this.model.body_mass[e],
1081
+ inertia: m,
1082
+ representativeInertia: g,
1083
+ stiffness: o,
1084
+ rotationalStiffness: h,
1085
+ ...this.grab.dampingOverridden ? { damping: this.grab.damping } : {},
1086
+ maxAcceleration: d,
1087
+ maxAngularAcceleration: f,
1088
+ strength: r
1089
+ });
1090
+ this.lastGrabForce = [...p.force], this.data.qfrc_applied.fill(0), this.mujoco.mj_applyFT(
1091
+ this.model,
1092
+ this.data,
1093
+ p.force,
1094
+ p.torque,
1095
+ u,
1096
+ e,
1097
+ this.data.qfrc_applied
1098
+ );
1099
+ }
1100
+ /** One patch anchor's critically damped Cartesian spring. */
1101
+ grabAnchorWrench(t, e, i, s, o, r, n) {
1102
+ var u;
1103
+ if (!this.model || !this.data) return null;
1104
+ const a = this.bodyInertia(t), c = this.data.xmat.subarray(t * 9, t * 9 + 9), l = this.data.xpos.subarray(t * 3, t * 3 + 3), m = this.data.xipos.subarray(t * 3, t * 3 + 3), h = [
1105
+ l[0] + c[0] * e[0] + c[1] * e[1] + c[2] * e[2],
1106
+ l[1] + c[3] * e[0] + c[4] * e[1] + c[5] * e[2],
1107
+ l[2] + c[6] * e[0] + c[7] * e[1] + c[8] * e[2]
1108
+ ], d = Math.max(this.model.body_mass[t] ?? 0, 0), f = [h[0] - m[0], h[1] - m[1], h[2] - m[2]], g = d > 0 ? V(d, a, c, f) : 0, j = ((u = this.model.body_invweight0) == null ? void 0 : u[t * 2 + 1]) ?? 0, b = j > 0 ? 1 / j : Math.max((a[0] + a[1] + a[2]) / 3, 0), _ = Y({
1109
+ target: i,
1110
+ point: h,
1111
+ center: m,
1112
+ spatialVelocity: this.data.cvel.subarray(t * 6, t * 6 + 6),
1113
+ rotation: c,
1114
+ mass: d,
1115
+ inertia: a,
1116
+ representativeInertia: b,
1117
+ stiffness: s,
1118
+ rotationalStiffness: r,
1119
+ damping: 2 * Math.sqrt(s) * g,
1120
+ maxAcceleration: g > 0 ? o / g : F,
1121
+ maxAngularAcceleration: P,
1122
+ strength: n
1123
+ });
1124
+ return {
1125
+ force: [..._.force],
1126
+ torque: [..._.torque],
1127
+ center: [m[0], m[1], m[2]]
1128
+ };
1129
+ }
1130
+ endGrab() {
1131
+ this.data && this.data.qfrc_applied.fill(0), this.lastGrabForce = [0, 0, 0], this.grab = null, this.setTimestep(this.playbackTimestep);
1132
+ }
1133
+ step(t) {
1134
+ if (!this.mujoco || !this.model || !this.data || t <= 0) return !1;
1135
+ if (this.physicsWorker) {
1136
+ let o = !1;
1137
+ return this.workerRevision !== this.workerAppliedRevision && (this.workerAppliedRevision = this.workerRevision, o = !0), this.workerStepInFlight || (this.updateGrabTargetForStep(Math.min(t, L)), this.applyGrabForce(), this.workerStepInFlight = !0, this.physicsWorker.step(
1138
+ this.workerGeneration,
1139
+ t,
1140
+ this.timestep,
1141
+ this.defaultGroundHeight ?? null,
1142
+ this.captureWorkerState(),
1143
+ this.serializeGrab()
1144
+ )), o;
1145
+ }
1146
+ this.accumulator += Math.min(t, L);
1147
+ let e = !1, i = 0;
1148
+ const s = z();
1149
+ for (; this.accumulator >= this.timestep && i < H && (this.updateGrabTargetForStep(), this.applyGrabForce(), this.mujoco.mj_step(this.model, this.data), this.accumulator -= this.timestep, this.stepTotal += 1, i += 1, e = !0, !(z() - s >= Z)); )
1150
+ ;
1151
+ return this.accumulator >= this.timestep && (i >= H || z() - s >= Z) && (this.accumulator = Math.min(this.accumulator, this.timestep)), e;
1152
+ }
1153
+ /** Number of integration steps since the last reset; diagnostics only. */
1154
+ get stepCount() {
1155
+ return this.stepTotal;
1156
+ }
1157
+ /** Pin the viewer-owned floor to a world-frame height, overriding auto-seating. */
1158
+ setDefaultGroundHeight(t) {
1159
+ if (!Number.isFinite(t) || !this.mujoco || !this.model || !this.data) return !1;
1160
+ const e = this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj.mjOBJ_GEOM.value, "__viewer_default_ground__");
1161
+ return e < 0 || this.model.geom_bodyid[e] !== 0 || this.model.geom_type[e] !== this.mujoco.mjtGeom.mjGEOM_PLANE.value ? !1 : (this.model.geom_pos[e * 3 + 2] = t, this.model.geom_sameframe[e] = 0, this.seatedGround = { id: e, height: t, sameFrame: 0 }, this.mujoco.mj_forward(this.model, this.data), this.workerSyncState("sync"), !0);
1162
+ }
1163
+ /**
1164
+ * Runs an exact number of fixed-size steps for a deterministic probe. The
1165
+ * compiled timestep is restored afterwards so the interactive runtime keeps
1166
+ * its authored cadence.
1167
+ */
1168
+ advanceFixed(t, e) {
1169
+ if (!this.mujoco || !this.model || !this.data || !Number.isFinite(t) || t <= 0 || !Number.isInteger(e) || e <= 0) return !1;
1170
+ const i = this.timestep;
1171
+ try {
1172
+ this.setTimestep(t);
1173
+ for (let s = 0; s < e; s += 1)
1174
+ this.mujoco.mj_step(this.model, this.data), this.stepTotal += 1;
1175
+ } finally {
1176
+ this.setTimestep(i);
1177
+ }
1178
+ return this.workerSyncState("sync"), !0;
1179
+ }
1180
+ updateGrabTargetForStep(t = this.timestep) {
1181
+ const e = this.grab;
1182
+ if (!e) return;
1183
+ const i = e.requestedTarget ?? e.target, s = (e.maxTargetSpeed ?? R) * Math.max(1, Math.sqrt(e.strength)), o = e.targetResponse ?? W, r = 1 - Math.exp(-o * t), n = s * t;
1184
+ for (let a = 0; a < 3; a++) {
1185
+ const c = i[a] - e.target[a], l = Math.sign(c) * Math.min(Math.abs(c) * r, n);
1186
+ e.target[a] += l;
1187
+ }
1188
+ }
1189
+ get isJointDriveActive() {
1190
+ return this.jointDriveActive;
1191
+ }
1192
+ /** Set servo goals only. Actual coordinates are written exclusively by mj_step. */
1193
+ setJointTargets(t) {
1194
+ if (!this.mujoco || !this.model || !this.data) return;
1195
+ const e = this.mujoco, i = this.model, s = /* @__PURE__ */ new Map();
1196
+ for (const [r, n] of Object.entries(t)) {
1197
+ if (!Number.isFinite(n)) continue;
1198
+ const a = e.mj_name2id(i, e.mjtObj.mjOBJ_JOINT.value, r);
1199
+ if (a < 0) continue;
1200
+ const c = i.jnt_type[a];
1201
+ if (c !== e.mjtJoint.mjJNT_HINGE.value && c !== e.mjtJoint.mjJNT_SLIDE.value) continue;
1202
+ const l = i.jnt(a);
1203
+ let m = n, h;
1204
+ try {
1205
+ l.limited && (h = { lower: i.jnt_range[a * 2], upper: i.jnt_range[a * 2 + 1] }, m = Math.max(h.lower, Math.min(h.upper, m)));
1206
+ } finally {
1207
+ l.delete();
1208
+ }
1209
+ s.set(a, {
1210
+ qpos: i.jnt_qposadr[a],
1211
+ dof: i.jnt_dofadr[a],
1212
+ sliding: c === e.mjtJoint.mjJNT_SLIDE.value,
1213
+ value: m,
1214
+ limits: h
1215
+ });
1216
+ }
1217
+ if (s.size !== this.jointTargets.size || [...s].some(([r, n]) => !this.jointTargets.has(r) || Math.abs(n.value - this.jointTargets.get(r).value) > 1e-9)) {
1218
+ if (this.jointTargets = s, this.captureHeldJointPoses(), !s.size || [...s.values()].every((r) => Math.abs(r.value - this.data.qpos[r.qpos]) < 1e-9)) {
1219
+ this.jointDriveActive = !1, this.jointDriveAccumulator = 0, this.freezeJointDrivePose();
1220
+ return;
1221
+ }
1222
+ this.jointDriveActive = !0, this.jointDriveSettledSeconds = 0, this.jointDriveElapsed = 0, this.jointDriveStalledSeconds = 0, this.jointDriveBestError = this.jointDriveError(), this.jointDriveDuration = Math.min(gt, this.jointDriveBestError * 2 + 3);
1223
+ }
1224
+ }
1225
+ clearJointTargets(t = {}) {
1226
+ this.jointTargets.clear(), this.heldJointPoses = [], this.jointDriveActive = !1, this.jointDriveAccumulator = 0, this.jointDriveSettledSeconds = 0, this.jointDriveElapsed = 0, this.jointDriveStalledSeconds = 0, t.freeze && this.freezeJointDrivePose();
1227
+ }
1228
+ jointDriveError() {
1229
+ let t = 0;
1230
+ for (const e of this.jointTargets.values())
1231
+ t = Math.max(t, Math.abs(e.value - this.data.qpos[e.qpos]) / (e.sliding ? 0.15 : 1));
1232
+ return t;
1233
+ }
1234
+ captureHeldJointPoses() {
1235
+ var n;
1236
+ const t = this.mujoco, e = this.model, i = this.data, s = new Set(this.jointTargets.keys());
1237
+ t.mj_forward(e, i);
1238
+ const o = /* @__PURE__ */ new Set();
1239
+ for (let a = 0; a < i.ne; a++) o.add(i.efc_id[a]);
1240
+ let r = !0;
1241
+ for (; r; ) {
1242
+ r = !1;
1243
+ for (let a = 0; a < e.neq; a++) {
1244
+ if (e.eq_type[a] !== t.mjtEq.mjEQ_JOINT.value || !o.has(a)) continue;
1245
+ const c = e.eq_obj1id[a], l = e.eq_obj2id[a];
1246
+ if (!(l < 0 || !s.has(c) && !s.has(l)))
1247
+ for (const m of [c, l]) s.has(m) || (s.add(m), r = !0);
1248
+ }
1249
+ }
1250
+ this.heldJointPoses = [];
1251
+ for (let a = 0; a < e.njnt; a++) {
1252
+ if (s.has(a)) continue;
1253
+ const c = e.jnt_type[a], l = c === t.mjtJoint.mjJNT_FREE.value, m = c === t.mjtJoint.mjJNT_BALL.value, h = e.jnt_qposadr[a], d = e.jnt_dofadr[a];
1254
+ this.heldJointPoses.push({ qpos: h, dof: d, values: Array.from(i.qpos.slice(h, h + (l ? 7 : m ? 4 : 1))), dofs: l ? 6 : m ? 3 : 1 });
1255
+ }
1256
+ this.holdJointPoses(), (n = this.jointPreviewCollision) == null || n.prepare(s);
1257
+ }
1258
+ holdJointPoses() {
1259
+ const t = this.data;
1260
+ for (const e of this.heldJointPoses)
1261
+ t.qpos.set(e.values, e.qpos), t.qvel.fill(0, e.dof, e.dof + e.dofs), t.qacc_warmstart.fill(0, e.dof, e.dof + e.dofs);
1262
+ }
1263
+ freezeJointDrivePose() {
1264
+ !this.model || !this.data || !this.mujoco || (this.data.qvel.fill(0), this.data.qacc_warmstart.fill(0), this.mujoco.mj_forward(this.model, this.data), this.data.qacc.fill(0), this.data.qacc_warmstart.fill(0));
1265
+ }
1266
+ /** A paused edit still needs integration and contact/equality constraint solving. */
1267
+ stepJointDrive(t) {
1268
+ if (!this.jointDriveActive || !this.mujoco || !this.model || !this.data || !(t > 0)) return !1;
1269
+ const e = this.mujoco, i = this.model, s = this.data, o = Math.min(this.timestep, ft), r = i.opt.timestep, n = i.opt.disableflags, a = this.jointPreviewExclusions ? Int32Array.from(i.exclude_signature) : null, c = Float64Array.from(s.qfrc_applied), l = new Float64Array(i.nq), m = [];
1270
+ this.jointDriveAccumulator += Math.min(t, L) * pt;
1271
+ let h = !1;
1272
+ try {
1273
+ this.jointPreviewExclusions && i.exclude_signature.set(this.jointPreviewExclusions), i.opt.timestep = o, i.opt.disableflags = n | e.mjtDisableBit.mjDSBL_ACTUATION.value;
1274
+ for (const d of this.heldJointPoses)
1275
+ for (let f = d.dof; f < d.dof + d.dofs; f++) {
1276
+ const g = i.dof_M0[f], j = i.dof_armature[f];
1277
+ m.push({ id: f, armature: j, inertia: g, invweight: i.dof_invweight0[f] });
1278
+ const b = Math.max(1e-9, g) * 1e6;
1279
+ i.dof_armature[f] = j + b, i.dof_M0[f] = g + b, i.dof_invweight0[f] = 0;
1280
+ }
1281
+ for (m.length && this.holdJointPoses(), (m.length || a) && e.mj_forward(i, s); this.jointDriveActive && this.jointDriveAccumulator >= o; ) {
1282
+ l.set(s.qpos);
1283
+ const d = s.time;
1284
+ s.qfrc_applied.set(c);
1285
+ for (const u of this.jointTargets.values()) {
1286
+ const y = u.value - s.qpos[u.qpos], p = u.sliding ? 0.15 : 1, w = Math.max(-p, Math.min(p, y * X / 2)), N = u.sliding ? 6 : 40, M = Math.max(-N, Math.min(
1287
+ N,
1288
+ 2 * X * (w - s.qvel[u.dof])
1289
+ )), O = Math.max(i.dof_M0[u.dof], 1e-9);
1290
+ s.qfrc_applied[u.dof] += O * M + s.qfrc_bias[u.dof];
1291
+ }
1292
+ e.mj_step(i, s), this.holdJointPoses();
1293
+ let f = Array.from(s.qpos).every(Number.isFinite) && [...this.jointTargets.values()].every((u) => {
1294
+ const y = l[u.qpos], p = s.qpos[u.qpos], w = (u.sliding ? 0.15 : 1) * o * 2, N = u.sliding ? 1e-5 : 1e-3;
1295
+ return Math.abs(p - y) <= w + 1e-8 && (!u.limits || p >= Math.min(y, u.limits.lower - N) - 1e-9 && p <= Math.max(y, u.limits.upper + N) + 1e-9);
1296
+ });
1297
+ if (f && this.jointPreviewCollision && (e.mj_kinematics(i, s), f = this.jointPreviewCollision.accept(s)), !f) {
1298
+ s.qpos.set(l), s.time = d, this.jointDriveActive = !1, this.jointDriveAccumulator = 0, h = !0;
1299
+ break;
1300
+ }
1301
+ this.jointDriveAccumulator -= o, h = !0, this.jointDriveElapsed += o;
1302
+ const g = this.jointDriveError(), j = g < this.jointDriveBestError - 1e-4;
1303
+ j && (this.jointDriveBestError = g);
1304
+ const b = [...this.jointTargets.values()].some((u) => Math.abs(s.qvel[u.dof]) > (u.sliding ? 0.15 : 1) * 1e-3);
1305
+ this.jointDriveStalledSeconds = j || b ? 0 : this.jointDriveStalledSeconds + o;
1306
+ let _ = !0;
1307
+ for (const u of this.jointTargets.values())
1308
+ if (Math.abs(u.value - s.qpos[u.qpos]) > (u.sliding ? 1e-5 : 1e-4) || Math.abs(s.qvel[u.dof]) > (u.sliding ? 1e-4 : 1e-3)) {
1309
+ _ = !1;
1310
+ break;
1311
+ }
1312
+ this.jointDriveSettledSeconds = _ ? this.jointDriveSettledSeconds + o : 0, (this.jointDriveSettledSeconds >= 0.1 || this.jointDriveStalledSeconds >= _t || this.jointDriveElapsed >= this.jointDriveDuration) && (this.jointDriveActive = !1, this.jointDriveAccumulator = 0);
1313
+ }
1314
+ h && !m.length && !a && (this.jointDriveActive ? e.mj_forward(i, s) : this.freezeJointDrivePose());
1315
+ } finally {
1316
+ i.opt.timestep = r, i.opt.disableflags = n, a && i.exclude_signature.set(a), s.qfrc_applied.set(c);
1317
+ for (const d of m)
1318
+ i.dof_armature[d.id] = d.armature, i.dof_M0[d.id] = d.inertia, i.dof_invweight0[d.id] = d.invweight;
1319
+ (m.length || a) && (this.jointDriveActive ? e.mj_forward(i, s) : this.freezeJointDrivePose());
1320
+ }
1321
+ return h && this.workerSyncState("sync"), h;
1322
+ }
1323
+ setJointValues(t) {
1324
+ if (!(!this.mujoco || !this.model || !this.data)) {
1325
+ for (const [e, i] of Object.entries(t)) {
1326
+ const s = this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj.mjOBJ_JOINT.value, e);
1327
+ if (s < 0 || !Number.isFinite(i)) continue;
1328
+ const o = this.model.jnt_type[s], r = this.mujoco.mjtJoint.mjJNT_HINGE.value, n = this.mujoco.mjtJoint.mjJNT_SLIDE.value;
1329
+ o !== r && o !== n || (this.data.qpos[this.model.jnt_qposadr[s]] = i);
1330
+ }
1331
+ this.mujoco.mj_forward(this.model, this.data), this.seatDefaultGround(this.model, this.data), this.accumulator = 0;
1332
+ }
1333
+ }
1334
+ /** Move scalar joints for a paused visual preview without running contacts or constraints. */
1335
+ setJointValuesKinematic(t) {
1336
+ if (!this.mujoco || !this.model || !this.data) return;
1337
+ const e = this.mujoco, i = this.model, s = this.data;
1338
+ this.jointTargets.clear(), this.heldJointPoses = [], this.jointDriveActive = !1, this.jointDriveAccumulator = 0, this.jointDriveSettledSeconds = 0, this.jointDriveElapsed = 0, this.jointDriveStalledSeconds = 0;
1339
+ for (const [o, r] of Object.entries(t)) {
1340
+ if (!Number.isFinite(r)) continue;
1341
+ const n = e.mj_name2id(i, e.mjtObj.mjOBJ_JOINT.value, o);
1342
+ if (n < 0) continue;
1343
+ const a = i.jnt_type[n];
1344
+ a !== e.mjtJoint.mjJNT_HINGE.value && a !== e.mjtJoint.mjJNT_SLIDE.value || (s.qpos[i.jnt_qposadr[n]] = r);
1345
+ }
1346
+ s.qvel.fill(0), s.qacc.fill(0), s.qacc_warmstart.fill(0), s.qfrc_applied.fill(0), e.mj_kinematics(i, s), this.accumulator = 0;
1347
+ }
1348
+ getJointValues(t) {
1349
+ const e = {};
1350
+ if (!this.mujoco || !this.model || !this.data) return e;
1351
+ for (const i of t) {
1352
+ const s = this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj.mjOBJ_JOINT.value, i);
1353
+ if (s < 0) continue;
1354
+ const o = this.model.jnt_type[s], r = this.mujoco.mjtJoint.mjJNT_HINGE.value, n = this.mujoco.mjtJoint.mjJNT_SLIDE.value;
1355
+ (o === r || o === n) && (e[i] = this.data.qpos[this.model.jnt_qposadr[s]]);
1356
+ }
1357
+ return e;
1358
+ }
1359
+ reset() {
1360
+ var t;
1361
+ if (!(!this.mujoco || !this.model || !this.data)) {
1362
+ if (this.clearJointTargets(), this.endGrab(), this.seatedGround) {
1363
+ const { id: e, height: i, sameFrame: s } = this.seatedGround;
1364
+ this.model.geom_pos[e * 3 + 2] = i, this.model.geom_sameframe[e] = s;
1365
+ }
1366
+ this.mujoco.mj_resetData(this.model, this.data), this.applyInitialControls(this.data, this.initialControls), this.applyInitialJoints(this.model, this.data, this.initialJoints), this.applyInitialVelocities(this.model, this.data, this.initialVelocities), this.mujoco.mj_forward(this.model, this.data), (t = this.jointPreviewCollision) == null || t.reset(), this.accumulator = 0, this.stepTotal = 0, this.workerSyncState("reset");
1367
+ }
1368
+ }
1369
+ dispose() {
1370
+ this.disposeModel(), this.mujoco = null;
1371
+ }
1372
+ actuatorTimestep(t, e) {
1373
+ const i = this.mujoco, s = /* @__PURE__ */ new Map();
1374
+ for (let r = 0; r < t.nu; r++) {
1375
+ if (t.actuator_trntype[r] !== i.mjtTrn.mjTRN_JOINT.value || t.actuator_biastype[r] !== i.mjtBias.mjBIAS_AFFINE.value) continue;
1376
+ const n = t.actuator_trnid[r * 2];
1377
+ if (n < 0 || t.jnt_type[n] !== i.mjtJoint.mjJNT_HINGE.value && t.jnt_type[n] !== i.mjtJoint.mjJNT_SLIDE.value) continue;
1378
+ const a = -t.actuator_biasprm[r * 10 + 1] * t.actuator_gear[r * 6] ** 2;
1379
+ if (!(a > 0) || !Number.isFinite(a)) continue;
1380
+ const c = t.jnt_dofadr[n];
1381
+ s.set(c, (s.get(c) ?? 0) + a);
1382
+ }
1383
+ let o = e;
1384
+ for (const [r, n] of s) {
1385
+ const a = t.dof_M0[r];
1386
+ !(a > 0) || !Number.isFinite(a) || (o = Math.min(o, bt * Math.sqrt(a / n)));
1387
+ }
1388
+ return o;
1389
+ }
1390
+ applyInitialControls(t, e) {
1391
+ if (e != null && e.length) {
1392
+ if (e.length !== t.ctrl.length) throw I(new Error(`Initial control count ${e.length} does not match MuJoCo actuator count ${t.ctrl.length}.`), "E_MUJOCO_INITIALIZE");
1393
+ t.ctrl.set(e);
1394
+ }
1395
+ }
1396
+ applyCenterOfMassOverrides(t, e) {
1397
+ for (const i of e ?? []) {
1398
+ const s = this.mujoco.mj_name2id(t, this.mujoco.mjtObj.mjOBJ_BODY.value, i.body);
1399
+ if (s <= 0 || i.position.length !== 3 || !i.position.every(Number.isFinite))
1400
+ throw I(new Error(`Invalid center-of-mass override: ${i.body}`), "E_MUJOCO_INITIALIZE");
1401
+ t.body_ipos.set(i.position, s * 3);
1402
+ }
1403
+ }
1404
+ /**
1405
+ * Re-applies the authored scalar-joint pose over `mj_resetData`. Unknown or
1406
+ * non-scalar names fail loudly: a saved pose that silently applied to nothing
1407
+ * would look like the studio lost the user's edit.
1408
+ */
1409
+ applyInitialJoints(t, e, i = {}) {
1410
+ if (Object.keys(i).length === 0) return;
1411
+ const s = this.mujoco, o = [s.mjtJoint.mjJNT_HINGE.value, s.mjtJoint.mjJNT_SLIDE.value];
1412
+ for (const [r, n] of Object.entries(i)) {
1413
+ const a = s.mj_name2id(t, s.mjtObj.mjOBJ_JOINT.value, r);
1414
+ if (a < 0 || !Number.isFinite(n) || !o.includes(t.jnt_type[a]))
1415
+ throw I(new Error("Initial pose requires a known scalar joint: " + r), "E_INITIAL_POSE_JOINT_INVALID");
1416
+ e.qpos[t.jnt_qposadr[a]] = n;
1417
+ }
1418
+ }
1419
+ applyAccelerationDrives(t, e, i, s) {
1420
+ if (!(i != null && i.length)) return s;
1421
+ if (s.length !== t.nu)
1422
+ throw I(new Error(`Acceleration drive control count ${s.length} does not match MuJoCo actuator count ${t.nu}.`), "E_MUJOCO_INITIALIZE");
1423
+ const o = new this.mujoco.DoubleBuffer(t.nv * t.nv);
1424
+ let r;
1425
+ try {
1426
+ this.mujoco.mj_fullM(t, e, o), r = o.GetView();
1427
+ } catch (a) {
1428
+ throw o.delete(), a;
1429
+ }
1430
+ const n = [...s];
1431
+ try {
1432
+ for (const a of i) {
1433
+ if (!Number.isInteger(a.actuator) || a.actuator < 0 || a.actuator >= t.nu)
1434
+ throw I(new Error(`Invalid acceleration actuator index: ${a.actuator}`), "E_MUJOCO_INITIALIZE");
1435
+ const c = this.mujoco.mj_name2id(
1436
+ t,
1437
+ this.mujoco.mjtObj.mjOBJ_JOINT.value,
1438
+ a.joint
1439
+ );
1440
+ if (c < 0)
1441
+ throw I(new Error(`Acceleration drive joint is missing: ${a.joint}`), "E_MUJOCO_INITIALIZE");
1442
+ const l = t.jnt_dofadr[c], m = r[l * t.nv + l];
1443
+ if (!(m > 0) || !Number.isFinite(m))
1444
+ throw I(new Error(`Acceleration drive has invalid effective inertia: ${a.joint}`), "E_MUJOCO_INITIALIZE");
1445
+ const h = a.stiffness * m, d = a.damping * m;
1446
+ if (![h, d, a.targetPosition, a.targetVelocity].every(Number.isFinite))
1447
+ throw I(new Error(`Acceleration drive has invalid values: ${a.joint}`), "E_MUJOCO_INITIALIZE");
1448
+ t.actuator_biasprm[a.actuator * 10] = 0, t.actuator_biasprm[a.actuator * 10 + 1] = -h, t.actuator_biasprm[a.actuator * 10 + 2] = -d, n[a.actuator] = h * a.targetPosition + d * a.targetVelocity;
1449
+ }
1450
+ } finally {
1451
+ o.delete();
1452
+ }
1453
+ return n;
1454
+ }
1455
+ bodyInertia(t) {
1456
+ var e;
1457
+ return (e = this.model) != null && e.body_inertia ? [
1458
+ Math.max(this.model.body_inertia[t * 3] ?? 0, 0),
1459
+ Math.max(this.model.body_inertia[t * 3 + 1] ?? 0, 0),
1460
+ Math.max(this.model.body_inertia[t * 3 + 2] ?? 0, 0)
1461
+ ] : [0, 0, 0];
1462
+ }
1463
+ /**
1464
+ * The grab spring is mass-normalized, so its natural frequency is
1465
+ * sqrt(stiffness). Only an explicitly very stiff request needs a finer step;
1466
+ * the default 100 s^-2 stays well inside the authored timestep.
1467
+ */
1468
+ grabTimestep(t) {
1469
+ if (!Number.isFinite(t) || t <= 0) return this.playbackTimestep;
1470
+ const e = ut / Math.sqrt(t);
1471
+ return Math.min(this.playbackTimestep, Math.max(ht, e));
1472
+ }
1473
+ setTimestep(t) {
1474
+ var e;
1475
+ this.timestep = t, (e = this.model) != null && e.opt && (this.model.opt.timestep = t);
1476
+ }
1477
+ applyInitialVelocities(t, e, i) {
1478
+ for (const s of i ?? []) {
1479
+ const o = this.mujoco.mj_name2id(t, this.mujoco.mjtObj.mjOBJ_BODY.value, s.body), r = o >= 0 ? t.body_jntadr[o] : -1;
1480
+ if (r < 0 || t.jnt_type[r] !== this.mujoco.mjtJoint.mjJNT_FREE.value || s.velocity.length !== 6 || !s.velocity.every(Number.isFinite))
1481
+ throw I(new Error(`Invalid free-body initial velocity: ${s.body}`), "E_MUJOCO_INITIALIZE");
1482
+ const { worldRotation: n } = this, a = new D(s.velocity[0], s.velocity[1], s.velocity[2]).applyQuaternion(n), c = new D(s.velocity[3], s.velocity[4], s.velocity[5]).applyQuaternion(n);
1483
+ e.qvel.set([a.x, a.y, a.z, c.x, c.y, c.z], t.jnt_dofadr[r]);
1484
+ }
1485
+ }
1486
+ async initializePhysicsWorker(t, e) {
1487
+ if (!(t.useWorker ?? (typeof Worker < "u" && typeof window < "u")) || !this.mujoco || !this.model || !this.data) return;
1488
+ let s = null;
1489
+ try {
1490
+ const o = this.serializeModelBytes();
1491
+ s = new mt({
1492
+ ...e ? {} : { wasmUrl: U(t.baseUrl) },
1493
+ ...e ? { wasmModule: e } : {},
1494
+ onSnapshot: (r) => this.receiveWorkerSnapshot(r),
1495
+ onError: (r) => this.disablePhysicsWorker(r)
1496
+ }), await s.initialize(
1497
+ o,
1498
+ this.captureWorkerState(),
1499
+ this.timestep,
1500
+ this.defaultGroundHeight ?? null
1501
+ ), this.physicsWorker = s;
1502
+ } catch (o) {
1503
+ s == null || s.dispose(), this.physicsWorker = null, console.warn("[mujoco] physics worker unavailable; using main thread.", o);
1504
+ }
1505
+ }
1506
+ serializeModelBytes() {
1507
+ if (!this.mujoco || !this.model) throw new Error("MuJoCo model is not initialized.");
1508
+ const t = `/viewer-physics-${Date.now()}-${Math.random().toString(36).slice(2)}.mjb`;
1509
+ try {
1510
+ return this.mujoco.mj_saveModel(this.model, t, null), new Uint8Array(this.mujoco.FS.readFile(t));
1511
+ } finally {
1512
+ try {
1513
+ this.mujoco.FS.unlink(t);
1514
+ } catch {
1515
+ }
1516
+ }
1517
+ }
1518
+ captureWorkerState() {
1519
+ const t = this.data;
1520
+ return {
1521
+ qpos: new Float64Array(t.qpos),
1522
+ qvel: new Float64Array(t.qvel),
1523
+ ctrl: new Float64Array(t.ctrl),
1524
+ qfrc_applied: new Float64Array(t.qfrc_applied),
1525
+ qacc_warmstart: new Float64Array(t.qacc_warmstart),
1526
+ act: new Float64Array(t.act ?? []),
1527
+ time: Number(t.time ?? 0),
1528
+ stepCount: this.stepTotal
1529
+ };
1530
+ }
1531
+ serializeGrab() {
1532
+ var e;
1533
+ const t = this.grab;
1534
+ return t ? {
1535
+ bodyId: t.bodyId,
1536
+ localPoint: [t.localPoint[0], t.localPoint[1], t.localPoint[2]],
1537
+ target: [t.target[0], t.target[1], t.target[2]],
1538
+ requestedTarget: [
1539
+ (t.requestedTarget ?? t.target)[0],
1540
+ (t.requestedTarget ?? t.target)[1],
1541
+ (t.requestedTarget ?? t.target)[2]
1542
+ ],
1543
+ stiffness: t.stiffness,
1544
+ rotationalStiffness: t.rotationalStiffness ?? k,
1545
+ ...t.dampingOverridden ? { damping: t.damping } : {},
1546
+ maxAcceleration: t.maxAcceleration ?? F,
1547
+ maxAngularAcceleration: t.maxAngularAcceleration ?? P,
1548
+ maxForce: t.maxForce,
1549
+ ...(e = t.anchors) != null && e.length ? {
1550
+ anchors: t.anchors.map((i) => ({
1551
+ bodyId: i.bodyId,
1552
+ localPoint: [i.localPoint[0], i.localPoint[1], i.localPoint[2]],
1553
+ ...i.targetOffset ? {
1554
+ targetOffset: [
1555
+ i.targetOffset[0],
1556
+ i.targetOffset[1],
1557
+ i.targetOffset[2]
1558
+ ]
1559
+ } : {},
1560
+ ...i.weight != null ? { weight: i.weight } : {}
1561
+ }))
1562
+ } : {},
1563
+ strength: t.strength,
1564
+ maxTargetSpeed: t.maxTargetSpeed ?? R,
1565
+ targetResponse: t.targetResponse ?? W
1566
+ } : null;
1567
+ }
1568
+ receiveWorkerSnapshot(t) {
1569
+ t.generation !== this.workerGeneration || !this.data || (this.applyWorkerSnapshot(t), this.workerStepInFlight = !1, this.workerRevision += 1);
1570
+ }
1571
+ applyWorkerSnapshot(t) {
1572
+ const e = this.data;
1573
+ e.qpos.set(t.qpos), e.qvel.set(t.qvel), e.ctrl.set(t.ctrl), e.qacc_warmstart.set(t.qacc_warmstart), e.act && t.act.length === e.act.length && e.act.set(t.act), e.time = t.time, e.ncon = t.ncon, this.stepTotal = t.stepCount, e.xpos.set(t.xpos), e.xquat.set(t.xquat), e.xipos.set(t.xipos), e.xmat.set(t.xmat), e.ximat.set(t.ximat), e.xanchor.set(t.xanchor), e.xaxis.set(t.xaxis), e.geom_xpos.set(t.geom_xpos), e.geom_xmat.set(t.geom_xmat), e.cvel.set(t.cvel), e.flexvert_xpos && t.flexvert_xpos.length === e.flexvert_xpos.length && e.flexvert_xpos.set(t.flexvert_xpos), e.body_awake && t.body_awake.length === e.body_awake.length && e.body_awake.set(t.body_awake);
1574
+ }
1575
+ workerSyncState(t) {
1576
+ this.physicsWorker && (this.workerGeneration += 1, this.workerStepInFlight = !1, this.physicsWorker.sync(
1577
+ t,
1578
+ this.workerGeneration,
1579
+ this.timestep,
1580
+ this.defaultGroundHeight ?? null,
1581
+ this.captureWorkerState()
1582
+ ));
1583
+ }
1584
+ disablePhysicsWorker(t) {
1585
+ this.physicsWorker && (console.warn("[mujoco] physics worker failed; falling back to main thread.", t), this.physicsWorker.dispose(), this.physicsWorker = null, this.workerStepInFlight = !1);
1586
+ }
1587
+ disposeModel() {
1588
+ var t, e, i;
1589
+ (t = this.physicsWorker) == null || t.dispose(), this.physicsWorker = null, this.workerStepInFlight = !1, this.clearJointTargets(), this.jointPreviewCollision = null, this.jointPreviewExclusions = null, this.endGrab(), (e = this.data) == null || e.delete(), (i = this.model) == null || i.delete(), this.data = null, this.model = null, this.initialGround = null, this.seatedGround = null, this.topLevelBodies = [], this.initialControls = [], this.initialVelocities = [], this.flexTopologies.clear(), this.accumulator = 0, this.playbackTimestep = J, this.timestep = J;
1590
+ }
1591
+ }
1592
+ function z() {
1593
+ return typeof performance < "u" ? performance.now() : Date.now();
1594
+ }
1595
+ function I(v, t) {
1596
+ const e = v instanceof Error ? v : new Error(String(v));
1597
+ return Object.assign(e, { code: t });
1598
+ }
1599
+ export {
1600
+ wt as MujocoRuntime
1601
+ };