@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.
@@ -1,1290 +0,0 @@
1
- var X = Object.defineProperty;
2
- var Z = (_, t, e) => t in _ ? X(_, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : _[t] = e;
3
- var y = (_, t, e) => Z(_, typeof t != "symbol" ? t + "" : t, e);
4
- import Q from "@mujoco/mujoco";
5
- import { Quaternion as G, Vector3 as A } from "three";
6
- import { e as K, y as tt, z as et } from "./index-B_0o0gFp.js";
7
- let it = 0;
8
- function st(_, t) {
9
- const e = `/viewer-simulation-${++it}`;
10
- _.mkdir(e);
11
- const i = /* @__PURE__ */ new Set([e]), s = /* @__PURE__ */ new Set(), o = (n, a) => {
12
- const l = n.replaceAll("\\", "/").split("/");
13
- if (l[0] === "" || l.some((f) => f === ".." || f.includes(":"))) throw W(`Invalid package path: ${n}`, "E_SIMULATION_PATH");
14
- const m = l.filter((f) => f && f !== ".");
15
- if (!m.length) throw W("Package path is empty.", "E_SIMULATION_PATH");
16
- let h = e;
17
- for (const f of m.slice(0, -1))
18
- h += `/${f}`, i.has(h) || (_.mkdir(h), i.add(h));
19
- const d = `${e}/${m.join("/")}`;
20
- return _.writeFile(d, a), s.add(d), d;
21
- }, r = () => {
22
- for (const n of s) _.unlink(n);
23
- s.clear();
24
- for (const n of [...i].reverse()) _.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 W(_, t) {
35
- return Object.assign(new Error(_), { code: t });
36
- }
37
- function ot(_, t, e, i) {
38
- if (!(_ > 0) || !Number.isFinite(_)) return Number.POSITIVE_INFINITY;
39
- const s = 1 / _, 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((l) => {
44
- const m = Math.max(l, 1e-12);
45
- return Number.isFinite(m) ? 1 / m : 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 z(_, t, e, i) {
50
- const s = ot(_, t, e, i);
51
- return Number.isFinite(s) && s > 0 ? Math.min(_, 3 / s) : 0;
52
- }
53
- function U({
54
- target: _,
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: l,
64
- damping: m,
65
- maxAcceleration: h,
66
- maxAngularAcceleration: d,
67
- strength: f
68
- }) {
69
- const j = [
70
- t[0] - e[0],
71
- t[1] - e[1],
72
- t[2] - e[2]
73
- ], N = [
74
- i[3] + i[1] * j[2] - i[2] * j[1],
75
- i[4] + i[2] * j[0] - i[0] * j[2],
76
- i[5] + i[0] * j[1] - i[1] * j[0]
77
- ], g = z(o, r, s, j);
78
- if (!(g > 0))
79
- return { force: [0, 0, 0], torque: [0, 0, 0], effectiveMass: 0, pointVelocity: N };
80
- const x = Math.max(1, f), p = Math.max(a, 1e-6) * x, c = m && m > 0 ? m : 2 * Math.sqrt(p) * g, v = [
81
- _[0] - t[0],
82
- _[1] - t[1],
83
- _[2] - t[2]
84
- ], u = [
85
- p * g * v[0] - c * N[0],
86
- p * g * v[1] - c * N[1],
87
- p * g * v[2] - c * N[2]
88
- ], w = g * h * x, b = Math.hypot(u[0], u[1], u[2]);
89
- if (b > w && b > 0) {
90
- const O = w / b;
91
- u[0] *= O, u[1] *= O, u[2] *= O;
92
- }
93
- const M = [
94
- j[1] * u[2] - j[2] * u[1],
95
- j[2] * u[0] - j[0] * u[2],
96
- j[0] * u[1] - j[1] * u[0]
97
- ], E = Math.min(x, 2), T = Math.max(n, 1e-12) * d * E, I = Math.hypot(M[0], M[1], M[2]);
98
- if (I > T && I > 0) {
99
- const O = T / I;
100
- M[0] *= O, M[1] *= O, M[2] *= O;
101
- }
102
- const k = Math.sqrt(Math.max(l, 1e-6) * E) * Math.max(n, 1e-12), Y = [
103
- M[0] - k * i[0],
104
- M[1] - k * i[1],
105
- M[2] - k * i[2]
106
- ];
107
- return { force: u, torque: Y, effectiveMass: g, pointVelocity: N };
108
- }
109
- class rt {
110
- constructor(t, e, i) {
111
- y(this, "pairs", []);
112
- y(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], l = e.geom_bodyid[n];
122
- if (a === l || e.body_weldid[a] === e.body_weldid[l] || this.hasNativeContact(r, n, a, l, s, o)) continue;
123
- const m = this.pairTolerance(r, n), h = this.distance(i, r, n, m), d = h < -m || Math.abs(h) < m && this.hasDegenerateOverlap(i, r, n, m);
124
- this.pairs.push({
125
- first: r,
126
- second: n,
127
- firstBody: a,
128
- secondBody: l,
129
- tolerance: m,
130
- initiallyOverlapping: d,
131
- separated: !d
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, l = i * 3, m = t.geom_xpos[a] - t.geom_xpos[l], h = t.geom_xpos[a + 1] - t.geom_xpos[l + 1], d = t.geom_xpos[a + 2] - t.geom_xpos[l + 2], f = o + r + s;
178
- if (m * m + h * h + d * d > f * f) 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, l = t.geom_xpos[a];
186
- try {
187
- for (const m of [-1, 1])
188
- if (t.geom_xpos[a] = l + m * o, this.mujoco.mj_geomDistance(this.model, t, e, i, s, null) < -o - s) return !0;
189
- } finally {
190
- t.geom_xpos[a] = l;
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 l = this.model.body_weldid[i], m = this.model.body_weldid[s], h = this.model.body_weldid[this.model.body_parentid[l]], d = this.model.body_weldid[this.model.body_parentid[m]];
210
- if (l !== 0 && h === m && m !== 0 || m !== 0 && d === l && l !== 0) return !1;
211
- }
212
- return !0;
213
- }
214
- }
215
- function nt(_) {
216
- return Object.assign(new Error(_.message), {
217
- name: _.name,
218
- ..._.stack ? { stack: _.stack } : {}
219
- });
220
- }
221
- function P(_) {
222
- return [
223
- _.qpos.buffer,
224
- _.qvel.buffer,
225
- _.ctrl.buffer,
226
- _.qfrc_applied.buffer,
227
- _.qacc_warmstart.buffer,
228
- _.act.buffer
229
- ];
230
- }
231
- class at {
232
- constructor(t) {
233
- y(this, "worker");
234
- y(this, "ready", null);
235
- y(this, "disposed", !1);
236
- this.options = t, this.worker = new Worker(new URL(
237
- /* @vite-ignore */
238
- "" + new URL("assets/mujoco-physics-worker-8NOXf5Pk.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.baseUrl ? { baseUrl: this.options.baseUrl } : {},
258
- ...this.options.wasmModule ? { wasmModule: this.options.wasmModule } : {}
259
- }, [
260
- n.buffer,
261
- ...P(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
- }, P(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
- }, P(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(nt(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 S = 1 / 240, lt = 1 / 960, ct = 0.25, B = 0.05, $ = 8, V = 12, mt = 1e3, D = 500, J = 30, F = 60, C = 1.2, L = 14, ht = 1 / 960, ut = 2, H = 20, dt = 0.15, ft = 10, pt = 0.25;
314
- class vt {
315
- constructor() {
316
- y(this, "mujoco", null);
317
- y(this, "model", null);
318
- y(this, "data", null);
319
- y(this, "grab", null);
320
- y(this, "lastGrabForce", [0, 0, 0]);
321
- y(this, "physicsWorker", null);
322
- y(this, "workerGeneration", 0);
323
- y(this, "workerRevision", 0);
324
- y(this, "workerAppliedRevision", 0);
325
- y(this, "workerStepInFlight", !1);
326
- y(this, "initialControls", []);
327
- y(this, "initialJoints", {});
328
- y(this, "accumulator", 0);
329
- y(this, "timestep", S);
330
- y(this, "playbackTimestep", S);
331
- /** Authored ground pose, captured before any seating. Re-seats start here. */
332
- y(this, "initialGround", null);
333
- /** Ground pose currently in the model; restored verbatim by reset(). */
334
- y(this, "seatedGround", null);
335
- y(this, "worldRotation", new G());
336
- y(this, "topLevelBodies", []);
337
- y(this, "stepTotal", 0);
338
- y(this, "initialVelocities", []);
339
- y(this, "jointTargets", /* @__PURE__ */ new Map());
340
- y(this, "jointDriveActive", !1);
341
- y(this, "jointDriveAccumulator", 0);
342
- y(this, "jointDriveSettledSeconds", 0);
343
- y(this, "jointDriveElapsed", 0);
344
- y(this, "jointDriveDuration", 0);
345
- y(this, "jointDriveBestError", 0);
346
- y(this, "jointDriveStalledSeconds", 0);
347
- y(this, "heldJointPoses", []);
348
- y(this, "jointPreviewCollision", null);
349
- y(this, "jointPreviewExclusions", null);
350
- }
351
- async initialize(t, e = {}) {
352
- var j, N, g;
353
- const i = e.wasmModule ? await e.wasmModule : void 0;
354
- this.mujoco ?? (this.mujoco = await Q({
355
- locateFile: (x) => x.endsWith(".wasm") ? tt(e.baseUrl) : x,
356
- ...i ? {
357
- instantiateWasm(x, p) {
358
- return K(i, x, p);
359
- }
360
- } : {}
361
- }));
362
- const s = st(this.mujoco.FS, t.files);
363
- let o = null, r = null, n = null, a = null, l = S, m = null, h = null, d = S, f = t.initialControls ?? [];
364
- try {
365
- if (o = this.mujoco.MjModel.from_xml_path(s.writeEntry(t.xml)), l = o.opt.timestep, !Number.isFinite(l) || l <= 0)
366
- throw new Error(`Invalid MuJoCo timestep: ${l}`);
367
- for (const p of t.massOverrides ?? []) {
368
- const c = this.mujoco.mj_name2id(o, this.mujoco.mjtObj.mjOBJ_BODY.value, p.body);
369
- if (c <= 0 || !Number.isFinite(p.mass) || p.mass <= 0 || !(o.body_mass[c] > 0)) throw new Error(`Invalid mass override: ${p.body}`);
370
- const v = p.mass / o.body_mass[c];
371
- o.body_mass[c] = p.mass;
372
- for (let u = 0; u < 3; u++) o.body_inertia[c * 3 + u] *= v;
373
- }
374
- r = new this.mujoco.MjData(o), (j = t.massOverrides) != null && j.length && this.mujoco.mj_setConst(o, r), this.applyCenterOfMassOverrides(o, t.centerOfMassOverrides), (N = t.centerOfMassOverrides) != null && N.length && this.mujoco.mj_setConst(o, r), this.worldRotation.identity(), this.mujoco.mj_forward(o, r), f = this.applyAccelerationDrives(
375
- o,
376
- r,
377
- t.accelerationDrives,
378
- f
379
- ), this.applyInitialControls(r, f), this.applyInitialJoints(o, r, t.initialJoints), this.applyInitialVelocities(o, r, t.initialVelocities), this.mujoco.mj_forward(o, r);
380
- const x = this.mujoco.mj_name2id(o, this.mujoco.mjtObj.mjOBJ_GEOM.value, "__viewer_default_ground__");
381
- if (n = x < 0 ? null : { id: x, height: o.geom_pos[x * 3 + 2], sameFrame: o.geom_sameframe[x] }, a = this.seatDefaultGround(o, r), Array.from(o.jnt_type).some((p) => p === this.mujoco.mjtJoint.mjJNT_HINGE.value || p === this.mujoco.mjtJoint.mjJNT_SLIDE.value) && (m = new rt(this.mujoco, o, r)), m && ((g = t.jointPreviewCollisionExcludes) != null && g.length)) {
382
- h = Int32Array.from(o.exclude_signature);
383
- const p = /* @__PURE__ */ new Set();
384
- for (const u of t.jointPreviewCollisionExcludes) {
385
- const w = this.mujoco.mj_name2id(o, this.mujoco.mjtObj.mjOBJ_BODY.value, u.body1), b = this.mujoco.mj_name2id(o, this.mujoco.mjtObj.mjOBJ_BODY.value, u.body2);
386
- if (w <= 0 || b <= 0) throw new Error(`Invalid joint preview collision pair: ${u.body1}, ${u.body2}`);
387
- m.hasInitialBodyOverlap(w, b) || p.add(Math.min(w, b) * 65536 + Math.max(w, b));
388
- }
389
- const c = h.filter((u) => !p.has(u)), v = new Int32Array(h.length);
390
- v.set(c, v.length - c.length), o.exclude_signature.set(v), this.mujoco.mj_forward(o, r);
391
- }
392
- d = this.actuatorTimestep(o, l), o.opt.timestep = d;
393
- } catch (x) {
394
- throw r == null || r.delete(), o == null || o.delete(), q(x, "E_MUJOCO_INITIALIZE");
395
- } finally {
396
- s.dispose();
397
- }
398
- this.disposeModel(), this.model = o, this.data = r, this.initialControls = f, this.initialJoints = t.initialJoints ?? {}, this.initialVelocities = t.initialVelocities ?? [], this.accumulator = 0, this.stepTotal = 0, this.timestep = d, this.playbackTimestep = d, this.initialGround = n, this.seatedGround = a, this.topLevelBodies = this.captureTopLevelBodies(o), this.jointPreviewCollision = m, this.jointPreviewExclusions = h, await this.initializePhysicsWorker(e, i);
399
- }
400
- get defaultGroundHeight() {
401
- if (!this.mujoco || !this.model) return;
402
- const t = this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj.mjOBJ_GEOM.value, "__viewer_default_ground__");
403
- return t < 0 ? void 0 : this.model.geom_pos[t * 3 + 2];
404
- }
405
- /**
406
- * Live flex vertex positions in world space. This is a Float64Array view into
407
- * WASM memory; callers that write to Three.js attributes must convert to
408
- * Float32 instead of assuming a zero-copy handoff.
409
- */
410
- readFlexVertices(t) {
411
- if (!this.mujoco || !this.model || !this.data) return null;
412
- const e = this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj.mjOBJ_FLEX.value, t);
413
- if (e < 0) return null;
414
- const i = this.model.flex_vertadr[e], s = this.model.flex_vertnum[e];
415
- return this.data.flexvert_xpos.subarray(i * 3, (i + s) * 3);
416
- }
417
- listFlexes() {
418
- if (!this.mujoco || !this.model) return [];
419
- const t = this.model, e = [];
420
- for (let i = 0; i < t.nflex; i++) {
421
- const s = this.mujoco.mj_id2name(t, this.mujoco.mjtObj.mjOBJ_FLEX.value, i) ?? `flex_${i}`, o = i * 4;
422
- e.push({
423
- id: i,
424
- name: s,
425
- dim: Number(t.flex_dim[i]),
426
- vertexAddress: Number(t.flex_vertadr[i]),
427
- vertexCount: Number(t.flex_vertnum[i]),
428
- elementAddress: Number(t.flex_elemadr[i]),
429
- elementCount: Number(t.flex_elemnum[i]),
430
- rgba: [
431
- Number(t.flex_rgba[o] ?? 0.33),
432
- Number(t.flex_rgba[o + 1] ?? 0.7),
433
- Number(t.flex_rgba[o + 2] ?? 0.7),
434
- Number(t.flex_rgba[o + 3] ?? 1)
435
- ]
436
- });
437
- }
438
- return e;
439
- }
440
- /**
441
- * Finds an authored MuJoCo plane geom that is not the viewer's injected
442
- * fallback ground. MuJoCo models normally carry their own floor; the viewer
443
- * can then align its reflection overlay to that floor instead of drawing a
444
- * second grid plane on top of it.
445
- */
446
- authoredGroundPlane() {
447
- if (!this.mujoco || !this.model || !this.data) return null;
448
- const t = this.model, e = this.data, i = this.mujoco.mjtGeom.mjGEOM_PLANE.value;
449
- for (let s = 0; s < t.ngeom; s++) {
450
- if (t.geom_type[s] !== i || t.geom_bodyid[s] !== 0) continue;
451
- const o = this.mujoco.mj_id2name(t, this.mujoco.mjtObj.mjOBJ_GEOM.value, s);
452
- if (et(o)) continue;
453
- const r = s * 3, n = s * 9;
454
- return {
455
- geomId: s,
456
- center: [
457
- Number(e.geom_xpos[r] ?? 0),
458
- Number(e.geom_xpos[r + 1] ?? 0),
459
- Number(e.geom_xpos[r + 2] ?? 0)
460
- ],
461
- rotation: [
462
- Number(e.geom_xmat[n] ?? 1),
463
- Number(e.geom_xmat[n + 1] ?? 0),
464
- Number(e.geom_xmat[n + 2] ?? 0),
465
- Number(e.geom_xmat[n + 3] ?? 0),
466
- Number(e.geom_xmat[n + 4] ?? 1),
467
- Number(e.geom_xmat[n + 5] ?? 0),
468
- Number(e.geom_xmat[n + 6] ?? 0),
469
- Number(e.geom_xmat[n + 7] ?? 0),
470
- Number(e.geom_xmat[n + 8] ?? 1)
471
- ],
472
- halfSize: [
473
- Math.max(0, Number(t.geom_size[r] ?? 0)),
474
- Math.max(0, Number(t.geom_size[r + 1] ?? 0))
475
- ]
476
- };
477
- }
478
- return null;
479
- }
480
- /**
481
- * Picks the nearest non-world flex vertex to a point in MuJoCo world space.
482
- * Flex vertices are backed by tiny MuJoCo bodies, so the existing 6-DOF grab
483
- * spring can pull a local cloth patch without inventing a separate solver.
484
- */
485
- pickFlexVertex(t, e) {
486
- if (!this.model || !this.data || !Number.isInteger(t)) return null;
487
- const i = this.model, s = this.data;
488
- if (t < 0 || t >= i.nflex) return null;
489
- const o = Number(i.flex_vertadr[t]), r = Number(i.flex_vertnum[t]);
490
- if (!Number.isInteger(o) || !Number.isInteger(r) || o < 0 || r <= 0) return null;
491
- const n = s.flexvert_xpos;
492
- let a = -1, l = Number.POSITIVE_INFINITY;
493
- for (let c = o; c < o + r; c++) {
494
- if (Number(i.flex_vertbodyid[c] ?? 0) <= 0) continue;
495
- const u = c * 3, w = Number(n[u] ?? 0) - e[0], b = Number(n[u + 1] ?? 0) - e[1], M = Number(n[u + 2] ?? 0) - e[2], E = w * w + b * b + M * M;
496
- E < l && (l = E, a = c);
497
- }
498
- if (a < 0) return null;
499
- let m = Number.POSITIVE_INFINITY;
500
- const h = a * 3;
501
- for (let c = o; c < o + r; c++) {
502
- if (c === a) continue;
503
- const v = c * 3, u = Math.hypot(
504
- Number(n[v] ?? 0) - Number(n[h] ?? 0),
505
- Number(n[v + 1] ?? 0) - Number(n[h + 1] ?? 0),
506
- Number(n[v + 2] ?? 0) - Number(n[h + 2] ?? 0)
507
- );
508
- u > 1e-9 && u < m && (m = u);
509
- }
510
- const d = Math.max(0, Number(i.flex_radius[t] ?? 0)), f = Math.max(d * 5, Number.isFinite(m) ? m * 1.6 : 0, 0.02), j = f * f, N = [];
511
- for (let c = o; c < o + r; c++) {
512
- const v = Number(i.flex_vertbodyid[c] ?? 0);
513
- if (v <= 0) continue;
514
- const u = c * 3, w = Number(n[u] ?? 0) - e[0], b = Number(n[u + 1] ?? 0) - e[1], M = Number(n[u + 2] ?? 0) - e[2], E = w * w + b * b + M * M;
515
- E <= j && N.push({ vertex: c, bodyId: v, distance: E });
516
- }
517
- const g = (c, v) => {
518
- const u = c * 3, w = v * 3, b = v * 9, M = Number(n[u] ?? 0) - Number(s.xpos[w] ?? 0), E = Number(n[u + 1] ?? 0) - Number(s.xpos[w + 1] ?? 0), T = Number(n[u + 2] ?? 0) - Number(s.xpos[w + 2] ?? 0), I = s.xmat;
519
- return [
520
- Number(I[b] ?? 1) * M + Number(I[b + 3] ?? 0) * E + Number(I[b + 6] ?? 0) * T,
521
- Number(I[b + 1] ?? 0) * M + Number(I[b + 4] ?? 1) * E + Number(I[b + 7] ?? 0) * T,
522
- Number(I[b + 2] ?? 0) * M + Number(I[b + 5] ?? 0) * E + Number(I[b + 8] ?? 1) * T
523
- ];
524
- }, x = N.sort((c, v) => c.distance - v.distance).slice(0, 9).map((c) => ({
525
- bodyId: c.bodyId,
526
- localPoint: g(c.vertex, c.bodyId)
527
- })), p = Number(i.flex_vertbodyid[a] ?? 0);
528
- return {
529
- bodyId: p,
530
- vertexIndex: a,
531
- localPoint: g(a, p),
532
- anchors: x.length ? x : [{ bodyId: p, localPoint: g(a, p) }]
533
- };
534
- }
535
- /** Total authored mass of a flex, used to scale interactive grab force. */
536
- flexMass(t) {
537
- if (!this.model || !Number.isInteger(t) || t < 0 || t >= this.model.nflex) return 0;
538
- const e = Number(this.model.flex_vertadr[t] ?? 0), i = Number(this.model.flex_vertnum[t] ?? 0);
539
- let s = 0;
540
- for (let o = e; o < e + i; o++) {
541
- const r = Number(this.model.flex_vertbodyid[o] ?? 0);
542
- r > 0 && (s += Number(this.model.body_mass[r] ?? 0));
543
- }
544
- return s;
545
- }
546
- flexElements(t) {
547
- if (!this.model) return new Int32Array();
548
- const e = t.dim + 1, i = t.elementAddress * e, s = this.model.flex_elem, o = new Int32Array(t.elementCount * e);
549
- for (let r = 0; r < o.length; r++) o[r] = Number(s[i + r]) | 0;
550
- return o;
551
- }
552
- /**
553
- * Re-orients the compiled physics to the given authored up axis by rotating
554
- * every top-level body about the world origin. Gravity stays -Z and the
555
- * viewer ground stays the authored horizontal plane, so a cup that was
556
- * standing now genuinely topples and settles on its side — the alternative,
557
- * rotating only the rendered scene graph, would leave the visuals and the
558
- * simulation in different frames.
559
- *
560
- * The full current state (free-joint positions, orientations and velocities)
561
- * is rotated by the same delta, so a paused or running simulation is carried
562
- * over instead of being re-seeded.
563
- */
564
- setWorldRotation(t) {
565
- var o;
566
- if (!this.mujoco || !this.model || !this.data) return;
567
- const e = this.model, i = this.data;
568
- if (t.equals(this.worldRotation)) return;
569
- const s = t.clone().multiply(this.worldRotation.clone().invert());
570
- 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;
571
- }
572
- captureTopLevelBodies(t) {
573
- const e = this.mujoco, i = [];
574
- for (let s = 1; s < t.nbody; s++) {
575
- if (t.body_parentid[s] !== 0) continue;
576
- 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;
577
- i.push({
578
- id: s,
579
- position: new A(t.body_pos[n], t.body_pos[n + 1], t.body_pos[n + 2]),
580
- quaternion: new G(t.body_quat[a + 1], t.body_quat[a + 2], t.body_quat[a + 3], t.body_quat[a]),
581
- freeJoint: r
582
- });
583
- }
584
- return i;
585
- }
586
- /** Writes the rotated reference pose, which reset() and fixed bases follow. */
587
- rotateReferenceFrames(t, e) {
588
- const i = this.model;
589
- for (const s of t) {
590
- const o = s.position.clone().applyQuaternion(e), r = e.clone().multiply(s.quaternion), n = s.id * 3, a = s.id * 4;
591
- 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;
592
- const l = i.jnt_qposadr[s.freeJoint];
593
- i.qpos0[l] = o.x, i.qpos0[l + 1] = o.y, i.qpos0[l + 2] = o.z, i.qpos0[l + 3] = r.w, i.qpos0[l + 4] = r.x, i.qpos0[l + 5] = r.y, i.qpos0[l + 6] = r.z;
594
- }
595
- }
596
- /** Rotates the live free-joint state so the simulation keeps its progress. */
597
- rotateState(t, e, i, s) {
598
- for (const o of t) {
599
- if (o.freeJoint < 0) continue;
600
- const r = e.jnt_qposadr[o.freeJoint], n = e.jnt_dofadr[o.freeJoint], a = new A(i.qpos[r], i.qpos[r + 1], i.qpos[r + 2]).applyQuaternion(s);
601
- i.qpos[r] = a.x, i.qpos[r + 1] = a.y, i.qpos[r + 2] = a.z;
602
- const l = new G(i.qpos[r + 4], i.qpos[r + 5], i.qpos[r + 6], i.qpos[r + 3]).premultiply(s);
603
- i.qpos[r + 3] = l.w, i.qpos[r + 4] = l.x, i.qpos[r + 5] = l.y, i.qpos[r + 6] = l.z;
604
- const m = new A(i.qvel[n], i.qvel[n + 1], i.qvel[n + 2]).applyQuaternion(s);
605
- i.qvel[n] = m.x, i.qvel[n + 1] = m.y, i.qvel[n + 2] = m.z;
606
- const h = new A(i.qvel[n + 3], i.qvel[n + 4], i.qvel[n + 5]).applyQuaternion(s);
607
- i.qvel[n + 3] = h.x, i.qvel[n + 4] = h.y, i.qvel[n + 5] = h.z;
608
- }
609
- }
610
- /** Lower only the viewer-owned plane, never authored bodies or authored floors.
611
- * Run after forward kinematics, not during stepping (the floor must not follow falling bodies).
612
- * `baseHeight` re-seats from a stable reference; omitting it lowers from the current pose.
613
- */
614
- seatDefaultGround(t, e, i) {
615
- const s = this.mujoco, o = s.mj_name2id(t, s.mjtObj.mjOBJ_GEOM.value, "__viewer_default_ground__");
616
- if (o < 0 || t.geom_bodyid[o] !== 0 || t.geom_type[o] !== s.mjtGeom.mjGEOM_PLANE.value) return null;
617
- let r = i ?? t.geom_pos[o * 3 + 2];
618
- for (let n = 0; n < t.ngeom; n++) {
619
- 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;
620
- const a = this.geomBottom(t, e, n), l = Math.max(1e-3, t.geom_margin[n] + t.geom_margin[o]);
621
- Number.isFinite(a) && a < r && (r = Math.min(r, a - l));
622
- }
623
- 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] };
624
- }
625
- /**
626
- * Resolve the lowest world-space point directly from MuJoCo's primitive
627
- * parameters. Rotating a mesh's local AABB into world space is conservative:
628
- * for a long, rotated shape it can sit far below the actual geometry. Use the
629
- * compiled vertices for mesh-backed geoms so the ground reflects the real
630
- * lowest point rather than the corners of its local bounding box.
631
- */
632
- geomBottom(t, e, i) {
633
- const s = this.mujoco, o = e.geom_xpos[i * 3 + 2], r = i * 3, n = i * 9, a = t.geom_type[i], l = Math.abs(t.geom_size[r]), m = Math.abs(t.geom_size[r + 1]), h = Math.abs(t.geom_size[r + 2]);
634
- if (a === s.mjtGeom.mjGEOM_SPHERE.value)
635
- return o - l;
636
- if (a === s.mjtGeom.mjGEOM_CAPSULE.value)
637
- return o - l - Math.abs(e.geom_xmat[n + 8]) * m;
638
- if (a === s.mjtGeom.mjGEOM_CYLINDER.value) {
639
- const p = e.geom_xmat[n + 8];
640
- return o - Math.abs(p) * m - Math.sqrt(Math.max(0, 1 - p * p)) * l;
641
- }
642
- if (a === s.mjtGeom.mjGEOM_ELLIPSOID.value)
643
- return o - Math.hypot(
644
- e.geom_xmat[n + 2] * l,
645
- e.geom_xmat[n + 5] * m,
646
- e.geom_xmat[n + 8] * h
647
- );
648
- if (a === s.mjtGeom.mjGEOM_BOX.value)
649
- return o - Math.abs(e.geom_xmat[n + 2]) * l - Math.abs(e.geom_xmat[n + 5]) * m - Math.abs(e.geom_xmat[n + 8]) * h;
650
- if (a === s.mjtGeom.mjGEOM_MESH.value || a === s.mjtGeom.mjGEOM_SDF.value) {
651
- const p = t.geom_dataid[i];
652
- if (p < 0 || p >= t.nmesh) return Number.POSITIVE_INFINITY;
653
- const c = t.mesh_vertadr[p], v = t.mesh_vertnum[p];
654
- if (!Number.isInteger(c) || !Number.isInteger(v) || c < 0 || v <= 0 || c + v > t.nmeshvert)
655
- return Number.POSITIVE_INFINITY;
656
- let u = Number.POSITIVE_INFINITY;
657
- for (let w = c; w < c + v; w++) {
658
- const b = w * 3, M = o + e.geom_xmat[n + 6] * t.mesh_vert[b] + e.geom_xmat[n + 7] * t.mesh_vert[b + 1] + e.geom_xmat[n + 8] * t.mesh_vert[b + 2];
659
- Number.isFinite(M) && M < u && (u = M);
660
- }
661
- return u;
662
- }
663
- const d = i * 6, f = t.geom_aabb[d + 3], j = t.geom_aabb[d + 4], N = t.geom_aabb[d + 5];
664
- if (![f, j, N].every((p) => Number.isFinite(p) && p >= 0))
665
- return Number.POSITIVE_INFINITY;
666
- const g = o + e.geom_xmat[n + 6] * t.geom_aabb[d] + e.geom_xmat[n + 7] * t.geom_aabb[d + 1] + e.geom_xmat[n + 8] * t.geom_aabb[d + 2], x = Math.abs(e.geom_xmat[n + 6]) * f + Math.abs(e.geom_xmat[n + 7]) * j + Math.abs(e.geom_xmat[n + 8]) * N;
667
- return g - x;
668
- }
669
- beginGrab({
670
- bodyId: t,
671
- localPoint: e,
672
- target: i,
673
- anchors: s,
674
- stiffness: o,
675
- damping: r,
676
- maxForce: n,
677
- maxTargetSpeed: a = C,
678
- targetResponse: l = L
679
- }) {
680
- var c, v;
681
- const m = Math.max(((c = this.model) == null ? void 0 : c.body_mass[t]) ?? 0, 0), h = o ?? mt, d = this.bodyInertia(t);
682
- let f = m, j = (d[0] + d[1] + d[2]) / 3;
683
- if (this.model && this.data && m > 0) {
684
- const u = this.data.xmat.subarray(t * 9, t * 9 + 9), w = this.data.xpos.subarray(t * 3, t * 3 + 3), b = this.data.xipos.subarray(t * 3, t * 3 + 3), M = [
685
- w[0] + u[0] * e[0] + u[1] * e[1] + u[2] * e[2],
686
- w[1] + u[3] * e[0] + u[4] * e[1] + u[5] * e[2],
687
- w[2] + u[6] * e[0] + u[7] * e[1] + u[8] * e[2]
688
- ], E = [M[0] - b[0], M[1] - b[1], M[2] - b[2]];
689
- f = z(m, d, u, E);
690
- const T = ((v = this.model.body_invweight0) == null ? void 0 : v[t * 2 + 1]) ?? 0;
691
- T > 0 && (j = 1 / T);
692
- }
693
- const N = r ?? 2 * Math.sqrt(h) * f, g = n ?? f * J, x = f > 0 ? g / f : J;
694
- this.setTimestep(this.grabTimestep(
695
- s != null && s.length ? h / s.length : h
696
- ));
697
- const p = [i[0], i[1], i[2]];
698
- this.grab = {
699
- bodyId: t,
700
- localPoint: [e[0], e[1], e[2]],
701
- target: [...p],
702
- requestedTarget: p,
703
- stiffness: h,
704
- damping: N,
705
- dampingOverridden: r != null,
706
- maxForce: g,
707
- rotationalStiffness: D,
708
- maxAngularAcceleration: F,
709
- maxAcceleration: x,
710
- effectiveMass: f,
711
- representativeInertia: Math.max(j, 0),
712
- strength: 1,
713
- maxTargetSpeed: a,
714
- targetResponse: l,
715
- anchors: s != null && s.length ? s.map((u) => ({
716
- bodyId: u.bodyId,
717
- localPoint: [u.localPoint[0], u.localPoint[1], u.localPoint[2]]
718
- })) : void 0
719
- };
720
- }
721
- updateGrabTarget(t) {
722
- this.grab && (this.grab.requestedTarget = [t[0], t[1], t[2]]);
723
- }
724
- updateGrabStrength(t) {
725
- this.grab && (this.grab.strength = t);
726
- }
727
- applyGrabForce() {
728
- if (!this.grab || !this.model || !this.data || !this.mujoco) return;
729
- const t = this.grab.anchors;
730
- if (t != null && t.length) {
731
- const w = this.grab.stiffness / t.length, b = this.grab.maxForce / t.length, M = (this.grab.rotationalStiffness ?? D) / t.length;
732
- this.data.qfrc_applied.fill(0);
733
- const E = [0, 0, 0];
734
- for (const T of t) {
735
- const I = this.grabAnchorWrench(
736
- T.bodyId,
737
- T.localPoint,
738
- this.grab.target,
739
- w,
740
- b,
741
- M,
742
- this.grab.strength
743
- );
744
- I && (E[0] += I.force[0], E[1] += I.force[1], E[2] += I.force[2], this.mujoco.mj_applyFT(
745
- this.model,
746
- this.data,
747
- I.force,
748
- I.torque,
749
- I.center,
750
- T.bodyId,
751
- this.data.qfrc_applied
752
- ));
753
- }
754
- this.lastGrabForce = E;
755
- return;
756
- }
757
- const {
758
- bodyId: e,
759
- localPoint: i,
760
- target: s,
761
- stiffness: o,
762
- strength: r,
763
- rotationalStiffness: n,
764
- maxAcceleration: a,
765
- maxAngularAcceleration: l,
766
- representativeInertia: m
767
- } = this.grab, h = this.bodyInertia(e), d = n ?? D, f = a ?? J, j = l ?? F, N = m ?? (h[0] + h[1] + h[2]) / 3, g = this.data.xmat.subarray(e * 9, e * 9 + 9), x = this.data.xpos.subarray(e * 3, e * 3 + 3), p = [
768
- x[0] + g[0] * i[0] + g[1] * i[1] + g[2] * i[2],
769
- x[1] + g[3] * i[0] + g[4] * i[1] + g[5] * i[2],
770
- x[2] + g[6] * i[0] + g[7] * i[1] + g[8] * i[2]
771
- ], c = this.data.xipos.subarray(e * 3, e * 3 + 3), v = this.data.cvel.subarray(e * 6, e * 6 + 6), u = U({
772
- target: s,
773
- point: p,
774
- center: c,
775
- spatialVelocity: v,
776
- rotation: g,
777
- mass: this.model.body_mass[e],
778
- inertia: h,
779
- representativeInertia: N,
780
- stiffness: o,
781
- rotationalStiffness: d,
782
- ...this.grab.dampingOverridden ? { damping: this.grab.damping } : {},
783
- maxAcceleration: f,
784
- maxAngularAcceleration: j,
785
- strength: r
786
- });
787
- this.lastGrabForce = [...u.force], this.data.qfrc_applied.fill(0), this.mujoco.mj_applyFT(
788
- this.model,
789
- this.data,
790
- u.force,
791
- u.torque,
792
- c,
793
- e,
794
- this.data.qfrc_applied
795
- );
796
- }
797
- /** One patch anchor's critically damped Cartesian spring. */
798
- grabAnchorWrench(t, e, i, s, o, r, n) {
799
- var c;
800
- if (!this.model || !this.data) return null;
801
- const a = this.bodyInertia(t), l = this.data.xmat.subarray(t * 9, t * 9 + 9), m = this.data.xpos.subarray(t * 3, t * 3 + 3), h = this.data.xipos.subarray(t * 3, t * 3 + 3), d = [
802
- m[0] + l[0] * e[0] + l[1] * e[1] + l[2] * e[2],
803
- m[1] + l[3] * e[0] + l[4] * e[1] + l[5] * e[2],
804
- m[2] + l[6] * e[0] + l[7] * e[1] + l[8] * e[2]
805
- ], f = Math.max(this.model.body_mass[t] ?? 0, 0), j = [d[0] - h[0], d[1] - h[1], d[2] - h[2]], N = f > 0 ? z(f, a, l, j) : 0, g = ((c = this.model.body_invweight0) == null ? void 0 : c[t * 2 + 1]) ?? 0, x = g > 0 ? 1 / g : Math.max((a[0] + a[1] + a[2]) / 3, 0), p = U({
806
- target: i,
807
- point: d,
808
- center: h,
809
- spatialVelocity: this.data.cvel.subarray(t * 6, t * 6 + 6),
810
- rotation: l,
811
- mass: f,
812
- inertia: a,
813
- representativeInertia: x,
814
- stiffness: s,
815
- rotationalStiffness: r,
816
- damping: 2 * Math.sqrt(s) * N,
817
- maxAcceleration: N > 0 ? o / N : J,
818
- maxAngularAcceleration: F,
819
- strength: n
820
- });
821
- return {
822
- force: [...p.force],
823
- torque: [...p.torque],
824
- center: [h[0], h[1], h[2]]
825
- };
826
- }
827
- endGrab() {
828
- this.data && this.data.qfrc_applied.fill(0), this.lastGrabForce = [0, 0, 0], this.grab = null, this.setTimestep(this.playbackTimestep);
829
- }
830
- step(t) {
831
- if (!this.mujoco || !this.model || !this.data || t <= 0) return !1;
832
- if (this.physicsWorker) {
833
- let o = !1;
834
- return this.workerRevision !== this.workerAppliedRevision && (this.workerAppliedRevision = this.workerRevision, o = !0), this.workerStepInFlight || (this.updateGrabTargetForStep(Math.min(t, B)), this.applyGrabForce(), this.workerStepInFlight = !0, this.physicsWorker.step(
835
- this.workerGeneration,
836
- t,
837
- this.timestep,
838
- this.defaultGroundHeight ?? null,
839
- this.captureWorkerState(),
840
- this.serializeGrab()
841
- )), o;
842
- }
843
- this.accumulator += Math.min(t, B);
844
- let e = !1, i = 0;
845
- const s = R();
846
- for (; this.accumulator >= this.timestep && i < $ && (this.updateGrabTargetForStep(), this.applyGrabForce(), this.mujoco.mj_step(this.model, this.data), this.accumulator -= this.timestep, this.stepTotal += 1, i += 1, e = !0, !(R() - s >= V)); )
847
- ;
848
- return this.accumulator >= this.timestep && (i >= $ || R() - s >= V) && (this.accumulator = Math.min(this.accumulator, this.timestep)), e;
849
- }
850
- /** Number of integration steps since the last reset; diagnostics only. */
851
- get stepCount() {
852
- return this.stepTotal;
853
- }
854
- /** Pin the viewer-owned floor to a world-frame height, overriding auto-seating. */
855
- setDefaultGroundHeight(t) {
856
- if (!Number.isFinite(t) || !this.mujoco || !this.model || !this.data) return !1;
857
- const e = this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj.mjOBJ_GEOM.value, "__viewer_default_ground__");
858
- 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);
859
- }
860
- /**
861
- * Runs an exact number of fixed-size steps for a deterministic probe. The
862
- * compiled timestep is restored afterwards so the interactive runtime keeps
863
- * its authored cadence.
864
- */
865
- advanceFixed(t, e) {
866
- if (!this.mujoco || !this.model || !this.data || !Number.isFinite(t) || t <= 0 || !Number.isInteger(e) || e <= 0) return !1;
867
- const i = this.timestep;
868
- try {
869
- this.setTimestep(t);
870
- for (let s = 0; s < e; s += 1)
871
- this.mujoco.mj_step(this.model, this.data), this.stepTotal += 1;
872
- } finally {
873
- this.setTimestep(i);
874
- }
875
- return this.workerSyncState("sync"), !0;
876
- }
877
- updateGrabTargetForStep(t = this.timestep) {
878
- const e = this.grab;
879
- if (!e) return;
880
- const i = e.requestedTarget ?? e.target, s = (e.maxTargetSpeed ?? C) * Math.max(1, Math.sqrt(e.strength)), o = e.targetResponse ?? L, r = 1 - Math.exp(-o * t), n = s * t;
881
- for (let a = 0; a < 3; a++) {
882
- const l = i[a] - e.target[a], m = Math.sign(l) * Math.min(Math.abs(l) * r, n);
883
- e.target[a] += m;
884
- }
885
- }
886
- get isJointDriveActive() {
887
- return this.jointDriveActive;
888
- }
889
- /** Set servo goals only. Actual coordinates are written exclusively by mj_step. */
890
- setJointTargets(t) {
891
- if (!this.mujoco || !this.model || !this.data) return;
892
- const e = this.mujoco, i = this.model, s = /* @__PURE__ */ new Map();
893
- for (const [r, n] of Object.entries(t)) {
894
- if (!Number.isFinite(n)) continue;
895
- const a = e.mj_name2id(i, e.mjtObj.mjOBJ_JOINT.value, r);
896
- if (a < 0) continue;
897
- const l = i.jnt_type[a];
898
- if (l !== e.mjtJoint.mjJNT_HINGE.value && l !== e.mjtJoint.mjJNT_SLIDE.value) continue;
899
- const m = i.jnt(a);
900
- let h = n, d;
901
- try {
902
- m.limited && (d = { lower: i.jnt_range[a * 2], upper: i.jnt_range[a * 2 + 1] }, h = Math.max(d.lower, Math.min(d.upper, h)));
903
- } finally {
904
- m.delete();
905
- }
906
- s.set(a, {
907
- qpos: i.jnt_qposadr[a],
908
- dof: i.jnt_dofadr[a],
909
- sliding: l === e.mjtJoint.mjJNT_SLIDE.value,
910
- value: h,
911
- limits: d
912
- });
913
- }
914
- 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)) {
915
- if (this.jointTargets = s, this.captureHeldJointPoses(), !s.size || [...s.values()].every((r) => Math.abs(r.value - this.data.qpos[r.qpos]) < 1e-9)) {
916
- this.jointDriveActive = !1, this.jointDriveAccumulator = 0, this.freezeJointDrivePose();
917
- return;
918
- }
919
- this.jointDriveActive = !0, this.jointDriveSettledSeconds = 0, this.jointDriveElapsed = 0, this.jointDriveStalledSeconds = 0, this.jointDriveBestError = this.jointDriveError(), this.jointDriveDuration = Math.min(ft, this.jointDriveBestError * 2 + 3);
920
- }
921
- }
922
- clearJointTargets(t = {}) {
923
- this.jointTargets.clear(), this.heldJointPoses = [], this.jointDriveActive = !1, this.jointDriveAccumulator = 0, this.jointDriveSettledSeconds = 0, this.jointDriveElapsed = 0, this.jointDriveStalledSeconds = 0, t.freeze && this.freezeJointDrivePose();
924
- }
925
- jointDriveError() {
926
- let t = 0;
927
- for (const e of this.jointTargets.values())
928
- t = Math.max(t, Math.abs(e.value - this.data.qpos[e.qpos]) / (e.sliding ? 0.15 : 1));
929
- return t;
930
- }
931
- captureHeldJointPoses() {
932
- var n;
933
- const t = this.mujoco, e = this.model, i = this.data, s = new Set(this.jointTargets.keys());
934
- t.mj_forward(e, i);
935
- const o = /* @__PURE__ */ new Set();
936
- for (let a = 0; a < i.ne; a++) o.add(i.efc_id[a]);
937
- let r = !0;
938
- for (; r; ) {
939
- r = !1;
940
- for (let a = 0; a < e.neq; a++) {
941
- if (e.eq_type[a] !== t.mjtEq.mjEQ_JOINT.value || !o.has(a)) continue;
942
- const l = e.eq_obj1id[a], m = e.eq_obj2id[a];
943
- if (!(m < 0 || !s.has(l) && !s.has(m)))
944
- for (const h of [l, m]) s.has(h) || (s.add(h), r = !0);
945
- }
946
- }
947
- this.heldJointPoses = [];
948
- for (let a = 0; a < e.njnt; a++) {
949
- if (s.has(a)) continue;
950
- const l = e.jnt_type[a], m = l === t.mjtJoint.mjJNT_FREE.value, h = l === t.mjtJoint.mjJNT_BALL.value, d = e.jnt_qposadr[a], f = e.jnt_dofadr[a];
951
- this.heldJointPoses.push({ qpos: d, dof: f, values: Array.from(i.qpos.slice(d, d + (m ? 7 : h ? 4 : 1))), dofs: m ? 6 : h ? 3 : 1 });
952
- }
953
- this.holdJointPoses(), (n = this.jointPreviewCollision) == null || n.prepare(s);
954
- }
955
- holdJointPoses() {
956
- const t = this.data;
957
- for (const e of this.heldJointPoses)
958
- 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);
959
- }
960
- freezeJointDrivePose() {
961
- !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));
962
- }
963
- /** A paused edit still needs integration and contact/equality constraint solving. */
964
- stepJointDrive(t) {
965
- if (!this.jointDriveActive || !this.mujoco || !this.model || !this.data || !(t > 0)) return !1;
966
- const e = this.mujoco, i = this.model, s = this.data, o = Math.min(this.timestep, ht), r = i.opt.timestep, n = i.opt.disableflags, a = this.jointPreviewExclusions ? Int32Array.from(i.exclude_signature) : null, l = Float64Array.from(s.qfrc_applied), m = new Float64Array(i.nq), h = [];
967
- this.jointDriveAccumulator += Math.min(t, B) * ut;
968
- let d = !1;
969
- try {
970
- this.jointPreviewExclusions && i.exclude_signature.set(this.jointPreviewExclusions), i.opt.timestep = o, i.opt.disableflags = n | e.mjtDisableBit.mjDSBL_ACTUATION.value;
971
- for (const f of this.heldJointPoses)
972
- for (let j = f.dof; j < f.dof + f.dofs; j++) {
973
- const N = i.dof_M0[j], g = i.dof_armature[j];
974
- h.push({ id: j, armature: g, inertia: N, invweight: i.dof_invweight0[j] });
975
- const x = Math.max(1e-9, N) * 1e6;
976
- i.dof_armature[j] = g + x, i.dof_M0[j] = N + x, i.dof_invweight0[j] = 0;
977
- }
978
- for (h.length && this.holdJointPoses(), (h.length || a) && e.mj_forward(i, s); this.jointDriveActive && this.jointDriveAccumulator >= o; ) {
979
- m.set(s.qpos);
980
- const f = s.time;
981
- s.qfrc_applied.set(l);
982
- for (const c of this.jointTargets.values()) {
983
- const v = c.value - s.qpos[c.qpos], u = c.sliding ? 0.15 : 1, w = Math.max(-u, Math.min(u, v * H / 2)), b = c.sliding ? 6 : 40, M = Math.max(-b, Math.min(
984
- b,
985
- 2 * H * (w - s.qvel[c.dof])
986
- )), E = Math.max(i.dof_M0[c.dof], 1e-9);
987
- s.qfrc_applied[c.dof] += E * M + s.qfrc_bias[c.dof];
988
- }
989
- e.mj_step(i, s), this.holdJointPoses();
990
- let j = Array.from(s.qpos).every(Number.isFinite) && [...this.jointTargets.values()].every((c) => {
991
- const v = m[c.qpos], u = s.qpos[c.qpos], w = (c.sliding ? 0.15 : 1) * o * 2, b = c.sliding ? 1e-5 : 1e-3;
992
- return Math.abs(u - v) <= w + 1e-8 && (!c.limits || u >= Math.min(v, c.limits.lower - b) - 1e-9 && u <= Math.max(v, c.limits.upper + b) + 1e-9);
993
- });
994
- if (j && this.jointPreviewCollision && (e.mj_kinematics(i, s), j = this.jointPreviewCollision.accept(s)), !j) {
995
- s.qpos.set(m), s.time = f, this.jointDriveActive = !1, this.jointDriveAccumulator = 0, d = !0;
996
- break;
997
- }
998
- this.jointDriveAccumulator -= o, d = !0, this.jointDriveElapsed += o;
999
- const N = this.jointDriveError(), g = N < this.jointDriveBestError - 1e-4;
1000
- g && (this.jointDriveBestError = N);
1001
- const x = [...this.jointTargets.values()].some((c) => Math.abs(s.qvel[c.dof]) > (c.sliding ? 0.15 : 1) * 1e-3);
1002
- this.jointDriveStalledSeconds = g || x ? 0 : this.jointDriveStalledSeconds + o;
1003
- let p = !0;
1004
- for (const c of this.jointTargets.values())
1005
- if (Math.abs(c.value - s.qpos[c.qpos]) > (c.sliding ? 1e-5 : 1e-4) || Math.abs(s.qvel[c.dof]) > (c.sliding ? 1e-4 : 1e-3)) {
1006
- p = !1;
1007
- break;
1008
- }
1009
- this.jointDriveSettledSeconds = p ? this.jointDriveSettledSeconds + o : 0, (this.jointDriveSettledSeconds >= 0.1 || this.jointDriveStalledSeconds >= dt || this.jointDriveElapsed >= this.jointDriveDuration) && (this.jointDriveActive = !1, this.jointDriveAccumulator = 0);
1010
- }
1011
- d && !h.length && !a && (this.jointDriveActive ? e.mj_forward(i, s) : this.freezeJointDrivePose());
1012
- } finally {
1013
- i.opt.timestep = r, i.opt.disableflags = n, a && i.exclude_signature.set(a), s.qfrc_applied.set(l);
1014
- for (const f of h)
1015
- i.dof_armature[f.id] = f.armature, i.dof_M0[f.id] = f.inertia, i.dof_invweight0[f.id] = f.invweight;
1016
- (h.length || a) && (this.jointDriveActive ? e.mj_forward(i, s) : this.freezeJointDrivePose());
1017
- }
1018
- return d && this.workerSyncState("sync"), d;
1019
- }
1020
- setJointValues(t) {
1021
- if (!(!this.mujoco || !this.model || !this.data)) {
1022
- for (const [e, i] of Object.entries(t)) {
1023
- const s = this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj.mjOBJ_JOINT.value, e);
1024
- if (s < 0 || !Number.isFinite(i)) continue;
1025
- const o = this.model.jnt_type[s], r = this.mujoco.mjtJoint.mjJNT_HINGE.value, n = this.mujoco.mjtJoint.mjJNT_SLIDE.value;
1026
- o !== r && o !== n || (this.data.qpos[this.model.jnt_qposadr[s]] = i);
1027
- }
1028
- this.mujoco.mj_forward(this.model, this.data), this.seatDefaultGround(this.model, this.data), this.accumulator = 0;
1029
- }
1030
- }
1031
- /** Move scalar joints for a paused visual preview without running contacts or constraints. */
1032
- setJointValuesKinematic(t) {
1033
- if (!this.mujoco || !this.model || !this.data) return;
1034
- const e = this.mujoco, i = this.model, s = this.data;
1035
- this.jointTargets.clear(), this.heldJointPoses = [], this.jointDriveActive = !1, this.jointDriveAccumulator = 0, this.jointDriveSettledSeconds = 0, this.jointDriveElapsed = 0, this.jointDriveStalledSeconds = 0;
1036
- for (const [o, r] of Object.entries(t)) {
1037
- if (!Number.isFinite(r)) continue;
1038
- const n = e.mj_name2id(i, e.mjtObj.mjOBJ_JOINT.value, o);
1039
- if (n < 0) continue;
1040
- const a = i.jnt_type[n];
1041
- a !== e.mjtJoint.mjJNT_HINGE.value && a !== e.mjtJoint.mjJNT_SLIDE.value || (s.qpos[i.jnt_qposadr[n]] = r);
1042
- }
1043
- 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;
1044
- }
1045
- getJointValues(t) {
1046
- const e = {};
1047
- if (!this.mujoco || !this.model || !this.data) return e;
1048
- for (const i of t) {
1049
- const s = this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj.mjOBJ_JOINT.value, i);
1050
- if (s < 0) continue;
1051
- const o = this.model.jnt_type[s], r = this.mujoco.mjtJoint.mjJNT_HINGE.value, n = this.mujoco.mjtJoint.mjJNT_SLIDE.value;
1052
- (o === r || o === n) && (e[i] = this.data.qpos[this.model.jnt_qposadr[s]]);
1053
- }
1054
- return e;
1055
- }
1056
- reset() {
1057
- var t;
1058
- if (!(!this.mujoco || !this.model || !this.data)) {
1059
- if (this.clearJointTargets(), this.endGrab(), this.seatedGround) {
1060
- const { id: e, height: i, sameFrame: s } = this.seatedGround;
1061
- this.model.geom_pos[e * 3 + 2] = i, this.model.geom_sameframe[e] = s;
1062
- }
1063
- 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");
1064
- }
1065
- }
1066
- dispose() {
1067
- this.disposeModel(), this.mujoco = null;
1068
- }
1069
- actuatorTimestep(t, e) {
1070
- const i = this.mujoco, s = /* @__PURE__ */ new Map();
1071
- for (let r = 0; r < t.nu; r++) {
1072
- if (t.actuator_trntype[r] !== i.mjtTrn.mjTRN_JOINT.value || t.actuator_biastype[r] !== i.mjtBias.mjBIAS_AFFINE.value) continue;
1073
- const n = t.actuator_trnid[r * 2];
1074
- if (n < 0 || t.jnt_type[n] !== i.mjtJoint.mjJNT_HINGE.value && t.jnt_type[n] !== i.mjtJoint.mjJNT_SLIDE.value) continue;
1075
- const a = -t.actuator_biasprm[r * 10 + 1] * t.actuator_gear[r * 6] ** 2;
1076
- if (!(a > 0) || !Number.isFinite(a)) continue;
1077
- const l = t.jnt_dofadr[n];
1078
- s.set(l, (s.get(l) ?? 0) + a);
1079
- }
1080
- let o = e;
1081
- for (const [r, n] of s) {
1082
- const a = t.dof_M0[r];
1083
- !(a > 0) || !Number.isFinite(a) || (o = Math.min(o, pt * Math.sqrt(a / n)));
1084
- }
1085
- return o;
1086
- }
1087
- applyInitialControls(t, e) {
1088
- if (e != null && e.length) {
1089
- if (e.length !== t.ctrl.length) throw q(new Error(`Initial control count ${e.length} does not match MuJoCo actuator count ${t.ctrl.length}.`), "E_MUJOCO_INITIALIZE");
1090
- t.ctrl.set(e);
1091
- }
1092
- }
1093
- applyCenterOfMassOverrides(t, e) {
1094
- for (const i of e ?? []) {
1095
- const s = this.mujoco.mj_name2id(t, this.mujoco.mjtObj.mjOBJ_BODY.value, i.body);
1096
- if (s <= 0 || i.position.length !== 3 || !i.position.every(Number.isFinite))
1097
- throw q(new Error(`Invalid center-of-mass override: ${i.body}`), "E_MUJOCO_INITIALIZE");
1098
- t.body_ipos.set(i.position, s * 3);
1099
- }
1100
- }
1101
- /**
1102
- * Re-applies the authored scalar-joint pose over `mj_resetData`. Unknown or
1103
- * non-scalar names fail loudly: a saved pose that silently applied to nothing
1104
- * would look like the studio lost the user's edit.
1105
- */
1106
- applyInitialJoints(t, e, i = {}) {
1107
- if (Object.keys(i).length === 0) return;
1108
- const s = this.mujoco, o = [s.mjtJoint.mjJNT_HINGE.value, s.mjtJoint.mjJNT_SLIDE.value];
1109
- for (const [r, n] of Object.entries(i)) {
1110
- const a = s.mj_name2id(t, s.mjtObj.mjOBJ_JOINT.value, r);
1111
- if (a < 0 || !Number.isFinite(n) || !o.includes(t.jnt_type[a]))
1112
- throw q(new Error("Initial pose requires a known scalar joint: " + r), "E_INITIAL_POSE_JOINT_INVALID");
1113
- e.qpos[t.jnt_qposadr[a]] = n;
1114
- }
1115
- }
1116
- applyAccelerationDrives(t, e, i, s) {
1117
- if (!(i != null && i.length)) return s;
1118
- if (s.length !== t.nu)
1119
- throw q(new Error(`Acceleration drive control count ${s.length} does not match MuJoCo actuator count ${t.nu}.`), "E_MUJOCO_INITIALIZE");
1120
- const o = new this.mujoco.DoubleBuffer(t.nv * t.nv);
1121
- let r;
1122
- try {
1123
- this.mujoco.mj_fullM(t, e, o), r = o.GetView();
1124
- } catch (a) {
1125
- throw o.delete(), a;
1126
- }
1127
- const n = [...s];
1128
- try {
1129
- for (const a of i) {
1130
- if (!Number.isInteger(a.actuator) || a.actuator < 0 || a.actuator >= t.nu)
1131
- throw q(new Error(`Invalid acceleration actuator index: ${a.actuator}`), "E_MUJOCO_INITIALIZE");
1132
- const l = this.mujoco.mj_name2id(
1133
- t,
1134
- this.mujoco.mjtObj.mjOBJ_JOINT.value,
1135
- a.joint
1136
- );
1137
- if (l < 0)
1138
- throw q(new Error(`Acceleration drive joint is missing: ${a.joint}`), "E_MUJOCO_INITIALIZE");
1139
- const m = t.jnt_dofadr[l], h = r[m * t.nv + m];
1140
- if (!(h > 0) || !Number.isFinite(h))
1141
- throw q(new Error(`Acceleration drive has invalid effective inertia: ${a.joint}`), "E_MUJOCO_INITIALIZE");
1142
- const d = a.stiffness * h, f = a.damping * h;
1143
- if (![d, f, a.targetPosition, a.targetVelocity].every(Number.isFinite))
1144
- throw q(new Error(`Acceleration drive has invalid values: ${a.joint}`), "E_MUJOCO_INITIALIZE");
1145
- t.actuator_biasprm[a.actuator * 10] = 0, t.actuator_biasprm[a.actuator * 10 + 1] = -d, t.actuator_biasprm[a.actuator * 10 + 2] = -f, n[a.actuator] = d * a.targetPosition + f * a.targetVelocity;
1146
- }
1147
- } finally {
1148
- o.delete();
1149
- }
1150
- return n;
1151
- }
1152
- bodyInertia(t) {
1153
- var e;
1154
- return (e = this.model) != null && e.body_inertia ? [
1155
- Math.max(this.model.body_inertia[t * 3] ?? 0, 0),
1156
- Math.max(this.model.body_inertia[t * 3 + 1] ?? 0, 0),
1157
- Math.max(this.model.body_inertia[t * 3 + 2] ?? 0, 0)
1158
- ] : [0, 0, 0];
1159
- }
1160
- /**
1161
- * The grab spring is mass-normalized, so its natural frequency is
1162
- * sqrt(stiffness). Only an explicitly very stiff request needs a finer step;
1163
- * the default 100 s^-2 stays well inside the authored timestep.
1164
- */
1165
- grabTimestep(t) {
1166
- if (!Number.isFinite(t) || t <= 0) return this.playbackTimestep;
1167
- const e = ct / Math.sqrt(t);
1168
- return Math.min(this.playbackTimestep, Math.max(lt, e));
1169
- }
1170
- setTimestep(t) {
1171
- var e;
1172
- this.timestep = t, (e = this.model) != null && e.opt && (this.model.opt.timestep = t);
1173
- }
1174
- applyInitialVelocities(t, e, i) {
1175
- for (const s of i ?? []) {
1176
- const o = this.mujoco.mj_name2id(t, this.mujoco.mjtObj.mjOBJ_BODY.value, s.body), r = o >= 0 ? t.body_jntadr[o] : -1;
1177
- if (r < 0 || t.jnt_type[r] !== this.mujoco.mjtJoint.mjJNT_FREE.value || s.velocity.length !== 6 || !s.velocity.every(Number.isFinite))
1178
- throw q(new Error(`Invalid free-body initial velocity: ${s.body}`), "E_MUJOCO_INITIALIZE");
1179
- const { worldRotation: n } = this, a = new A(s.velocity[0], s.velocity[1], s.velocity[2]).applyQuaternion(n), l = new A(s.velocity[3], s.velocity[4], s.velocity[5]).applyQuaternion(n);
1180
- e.qvel.set([a.x, a.y, a.z, l.x, l.y, l.z], t.jnt_dofadr[r]);
1181
- }
1182
- }
1183
- async initializePhysicsWorker(t, e) {
1184
- if (!(t.useWorker ?? (typeof Worker < "u" && typeof window < "u")) || !this.mujoco || !this.model || !this.data) return;
1185
- let s = null;
1186
- try {
1187
- const o = this.serializeModelBytes();
1188
- s = new at({
1189
- ...t.baseUrl ? { baseUrl: t.baseUrl } : {},
1190
- ...e ? { wasmModule: e } : {},
1191
- onSnapshot: (r) => this.receiveWorkerSnapshot(r),
1192
- onError: (r) => this.disablePhysicsWorker(r)
1193
- }), await s.initialize(
1194
- o,
1195
- this.captureWorkerState(),
1196
- this.timestep,
1197
- this.defaultGroundHeight ?? null
1198
- ), this.physicsWorker = s;
1199
- } catch (o) {
1200
- s == null || s.dispose(), this.physicsWorker = null, console.warn("[mujoco] physics worker unavailable; using main thread.", o);
1201
- }
1202
- }
1203
- serializeModelBytes() {
1204
- if (!this.mujoco || !this.model) throw new Error("MuJoCo model is not initialized.");
1205
- const t = `/viewer-physics-${Date.now()}-${Math.random().toString(36).slice(2)}.mjb`;
1206
- try {
1207
- return this.mujoco.mj_saveModel(this.model, t, null), new Uint8Array(this.mujoco.FS.readFile(t));
1208
- } finally {
1209
- try {
1210
- this.mujoco.FS.unlink(t);
1211
- } catch {
1212
- }
1213
- }
1214
- }
1215
- captureWorkerState() {
1216
- const t = this.data;
1217
- return {
1218
- qpos: new Float64Array(t.qpos),
1219
- qvel: new Float64Array(t.qvel),
1220
- ctrl: new Float64Array(t.ctrl),
1221
- qfrc_applied: new Float64Array(t.qfrc_applied),
1222
- qacc_warmstart: new Float64Array(t.qacc_warmstart),
1223
- act: new Float64Array(t.act ?? []),
1224
- time: Number(t.time ?? 0),
1225
- stepCount: this.stepTotal
1226
- };
1227
- }
1228
- serializeGrab() {
1229
- var e;
1230
- const t = this.grab;
1231
- return t ? {
1232
- bodyId: t.bodyId,
1233
- localPoint: [t.localPoint[0], t.localPoint[1], t.localPoint[2]],
1234
- target: [t.target[0], t.target[1], t.target[2]],
1235
- requestedTarget: [
1236
- (t.requestedTarget ?? t.target)[0],
1237
- (t.requestedTarget ?? t.target)[1],
1238
- (t.requestedTarget ?? t.target)[2]
1239
- ],
1240
- stiffness: t.stiffness,
1241
- rotationalStiffness: t.rotationalStiffness ?? D,
1242
- ...t.dampingOverridden ? { damping: t.damping } : {},
1243
- maxAcceleration: t.maxAcceleration ?? J,
1244
- maxAngularAcceleration: t.maxAngularAcceleration ?? F,
1245
- maxForce: t.maxForce,
1246
- ...(e = t.anchors) != null && e.length ? {
1247
- anchors: t.anchors.map((i) => ({
1248
- bodyId: i.bodyId,
1249
- localPoint: [i.localPoint[0], i.localPoint[1], i.localPoint[2]]
1250
- }))
1251
- } : {},
1252
- strength: t.strength,
1253
- maxTargetSpeed: t.maxTargetSpeed ?? C,
1254
- targetResponse: t.targetResponse ?? L
1255
- } : null;
1256
- }
1257
- receiveWorkerSnapshot(t) {
1258
- t.generation !== this.workerGeneration || !this.data || (this.applyWorkerSnapshot(t), this.workerStepInFlight = !1, this.workerRevision += 1);
1259
- }
1260
- applyWorkerSnapshot(t) {
1261
- const e = this.data;
1262
- 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);
1263
- }
1264
- workerSyncState(t) {
1265
- this.physicsWorker && (this.workerGeneration += 1, this.workerStepInFlight = !1, this.physicsWorker.sync(
1266
- t,
1267
- this.workerGeneration,
1268
- this.timestep,
1269
- this.defaultGroundHeight ?? null,
1270
- this.captureWorkerState()
1271
- ));
1272
- }
1273
- disablePhysicsWorker(t) {
1274
- this.physicsWorker && (console.warn("[mujoco] physics worker failed; falling back to main thread.", t), this.physicsWorker.dispose(), this.physicsWorker = null, this.workerStepInFlight = !1);
1275
- }
1276
- disposeModel() {
1277
- var t, e, i;
1278
- (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.accumulator = 0, this.playbackTimestep = S, this.timestep = S;
1279
- }
1280
- }
1281
- function R() {
1282
- return typeof performance < "u" ? performance.now() : Date.now();
1283
- }
1284
- function q(_, t) {
1285
- const e = _ instanceof Error ? _ : new Error(String(_));
1286
- return Object.assign(e, { code: t });
1287
- }
1288
- export {
1289
- vt as MujocoRuntime
1290
- };