@nebula-spatial/viewer 0.5.15 → 0.5.17

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,698 +0,0 @@
1
- var F = Object.defineProperty;
2
- var B = (v, t, e) => t in v ? F(v, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : v[t] = e;
3
- var f = (v, t, e) => B(v, typeof t != "symbol" ? t + "" : t, e);
4
- import L from "@mujoco/mujoco";
5
- import { Quaternion as D, Vector3 as q } from "three";
6
- import { b as R, z as C } from "./index-YdnQRm_T.js";
7
- let z = 0;
8
- function V(v, t) {
9
- const e = `/viewer-simulation-${++z}`;
10
- v.mkdir(e);
11
- const i = /* @__PURE__ */ new Set([e]), o = /* @__PURE__ */ new Set(), a = (s, r) => {
12
- const l = s.replaceAll("\\", "/").split("/");
13
- if (l[0] === "" || l.some((d) => d === ".." || d.includes(":"))) throw S(`Invalid package path: ${s}`, "E_SIMULATION_PATH");
14
- const c = l.filter((d) => d && d !== ".");
15
- if (!c.length) throw S("Package path is empty.", "E_SIMULATION_PATH");
16
- let m = e;
17
- for (const d of c.slice(0, -1))
18
- m += `/${d}`, i.has(m) || (v.mkdir(m), i.add(m));
19
- const h = `${e}/${c.join("/")}`;
20
- return v.writeFile(h, r), o.add(h), h;
21
- }, n = () => {
22
- for (const s of o) v.unlink(s);
23
- o.clear();
24
- for (const s of [...i].reverse()) v.rmdir(s);
25
- i.clear();
26
- };
27
- try {
28
- for (const [s, r] of t) a(s, r);
29
- return { writeEntry: (s) => a("__viewer_entry.xml", s), dispose: n };
30
- } catch (s) {
31
- throw n(), s;
32
- }
33
- }
34
- function S(v, t) {
35
- return Object.assign(new Error(v), { code: t });
36
- }
37
- function k({
38
- target: v,
39
- point: t,
40
- velocity: e,
41
- stiffness: i,
42
- damping: o,
43
- maxForce: a,
44
- strength: n
45
- }) {
46
- const s = [
47
- i * (v[0] - t[0]) - o * e[0],
48
- i * (v[1] - t[1]) - o * e[1],
49
- i * (v[2] - t[2]) - o * e[2]
50
- ], r = Math.hypot(s[0], s[1], s[2]), l = a * n;
51
- if (r > l && r > 0) {
52
- const c = l / r;
53
- s[0] *= c, s[1] *= c, s[2] *= c;
54
- }
55
- return s;
56
- }
57
- class U {
58
- constructor(t, e, i) {
59
- f(this, "pairs", []);
60
- f(this, "activePairs", []);
61
- this.mujoco = t, this.model = e;
62
- const o = new Set(Array.from(e.exclude_signature)), a = /* @__PURE__ */ new Set();
63
- for (let n = 0; n < e.npair; n++)
64
- a.add(this.geomPairKey(e.pair_geom1[n], e.pair_geom2[n]));
65
- for (let n = 0; n < e.ngeom; n++)
66
- if (this.isCollider(n))
67
- for (let s = n + 1; s < e.ngeom; s++) {
68
- if (!this.isCollider(s)) continue;
69
- const r = e.geom_bodyid[n], l = e.geom_bodyid[s];
70
- if (r === l || e.body_weldid[r] === e.body_weldid[l] || this.hasNativeContact(n, s, r, l, o, a)) continue;
71
- const c = this.pairTolerance(n, s), m = this.distance(i, n, s, c), h = m < -c || Math.abs(m) < c && this.hasDegenerateOverlap(i, n, s, c);
72
- this.pairs.push({
73
- first: n,
74
- second: s,
75
- firstBody: r,
76
- secondBody: l,
77
- tolerance: c,
78
- initiallyOverlapping: h,
79
- separated: !h
80
- });
81
- }
82
- }
83
- /** Select only pairs whose relative transform can change in this edit. */
84
- prepare(t) {
85
- const e = new Array(this.model.nbody).fill("");
86
- for (let i = 1; i < this.model.nbody; i++) {
87
- let o = e[this.model.body_parentid[i]];
88
- const a = this.model.body_jntadr[i];
89
- for (let n = a; n < a + this.model.body_jntnum[i]; n++)
90
- t.has(n) && (o += `${n},`);
91
- e[i] = o;
92
- }
93
- this.activePairs = this.pairs.filter((i) => e[i.firstBody] !== e[i.secondBody]);
94
- }
95
- /** Call after updating the candidate pose's kinematics, before accepting it. */
96
- accept(t) {
97
- const e = [];
98
- for (const i of this.activePairs) {
99
- const o = this.distance(t, i.first, i.second, i.tolerance);
100
- if (!Number.isFinite(o)) return !1;
101
- if (!i.separated) {
102
- o >= i.tolerance && e.push(i);
103
- continue;
104
- }
105
- if (o < -i.tolerance || Math.abs(o) < i.tolerance && this.hasDegenerateOverlap(t, i.first, i.second, i.tolerance)) return !1;
106
- }
107
- for (const i of e) i.separated = !0;
108
- return !0;
109
- }
110
- /** Restore the original exemptions, without recapturing the current pose. */
111
- reset() {
112
- for (const t of this.pairs) t.separated = !t.initiallyOverlapping;
113
- this.activePairs = [];
114
- }
115
- /** Default assembly intersections also need an exemption during playback. */
116
- hasInitialBodyOverlap(t, e) {
117
- return this.pairs.some((i) => i.initiallyOverlapping && (i.firstBody === t && i.secondBody === e || i.firstBody === e && i.secondBody === t));
118
- }
119
- isCollider(t) {
120
- return this.model.geom_contype[t] !== 0 || this.model.geom_conaffinity[t] !== 0;
121
- }
122
- distance(t, e, i, o) {
123
- const a = this.model.geom_rbound[e], n = this.model.geom_rbound[i], s = this.mujoco.mjtGeom.mjGEOM_PLANE.value;
124
- if (a > 0 && n > 0 && this.model.geom_type[e] !== s && this.model.geom_type[i] !== s) {
125
- const r = e * 3, l = i * 3, c = t.geom_xpos[r] - t.geom_xpos[l], m = t.geom_xpos[r + 1] - t.geom_xpos[l + 1], h = t.geom_xpos[r + 2] - t.geom_xpos[l + 2], d = a + n + o;
126
- if (c * c + m * m + h * h > d * d) return o;
127
- }
128
- return this.mujoco.mj_geomDistance(this.model, t, e, i, o, null);
129
- }
130
- hasDegenerateOverlap(t, e, i, o) {
131
- const a = Math.max(o * 4, 1e-8), n = i * 3;
132
- for (let s = 0; s < 3; s++) {
133
- const r = n + s, l = t.geom_xpos[r];
134
- try {
135
- for (const c of [-1, 1])
136
- if (t.geom_xpos[r] = l + c * a, this.mujoco.mj_geomDistance(this.model, t, e, i, o, null) < -a - o) return !0;
137
- } finally {
138
- t.geom_xpos[r] = l;
139
- }
140
- }
141
- return !1;
142
- }
143
- geomPairKey(t, e) {
144
- return t < e ? `${t}:${e}` : `${e}:${t}`;
145
- }
146
- pairTolerance(t, e) {
147
- const i = this.model.geom_rbound[t], o = this.model.geom_rbound[e], a = Math.min(i || o || 1, o || i || 1);
148
- return Math.max(1e-8, Math.min(1e-5, a * 1e-5));
149
- }
150
- hasNativeContact(t, e, i, o, a, n) {
151
- const s = this.model.opt.disableflags;
152
- if (s & (this.mujoco.mjtDisableBit.mjDSBL_CONTACT.value | this.mujoco.mjtDisableBit.mjDSBL_CONSTRAINT.value)) return !1;
153
- if (n.has(this.geomPairKey(t, e))) return !0;
154
- const r = Math.min(i, o) * 65536 + Math.max(i, o);
155
- if (a.has(r) || !(this.model.geom_contype[t] & this.model.geom_conaffinity[e]) && !(this.model.geom_contype[e] & this.model.geom_conaffinity[t])) return !1;
156
- if (!(s & this.mujoco.mjtDisableBit.mjDSBL_FILTERPARENT.value)) {
157
- const l = this.model.body_weldid[i], c = this.model.body_weldid[o], m = this.model.body_weldid[this.model.body_parentid[l]], h = this.model.body_weldid[this.model.body_parentid[c]];
158
- if (l !== 0 && m === c && c !== 0 || c !== 0 && h === l && l !== 0) return !1;
159
- }
160
- return !0;
161
- }
162
- }
163
- const w = 1 / 240, $ = 1 / 960, H = 0.25, O = 0.05, Y = 80, W = 0.7, Q = 60, X = 1e-4, I = 10, N = 3.5, A = 14, Z = 1 / 960, K = 2, G = 20, tt = 0.15, et = 10, it = 0.25;
164
- class rt {
165
- constructor() {
166
- f(this, "mujoco", null);
167
- f(this, "model", null);
168
- f(this, "data", null);
169
- f(this, "grab", null);
170
- f(this, "lastGrabForce", [0, 0, 0]);
171
- f(this, "initialControls", []);
172
- f(this, "accumulator", 0);
173
- f(this, "timestep", w);
174
- f(this, "playbackTimestep", w);
175
- /** Authored ground pose, captured before any seating. Re-seats start here. */
176
- f(this, "initialGround", null);
177
- /** Ground pose currently in the model; restored verbatim by reset(). */
178
- f(this, "seatedGround", null);
179
- f(this, "worldRotation", new D());
180
- f(this, "topLevelBodies", []);
181
- f(this, "initialVelocities", []);
182
- f(this, "jointTargets", /* @__PURE__ */ new Map());
183
- f(this, "jointDriveActive", !1);
184
- f(this, "jointDriveAccumulator", 0);
185
- f(this, "jointDriveSettledSeconds", 0);
186
- f(this, "jointDriveElapsed", 0);
187
- f(this, "jointDriveDuration", 0);
188
- f(this, "jointDriveBestError", 0);
189
- f(this, "jointDriveStalledSeconds", 0);
190
- f(this, "heldJointPoses", []);
191
- f(this, "jointPreviewCollision", null);
192
- f(this, "jointPreviewExclusions", null);
193
- }
194
- async initialize(t, e = {}) {
195
- var d, _;
196
- const i = e.wasmModule ? await e.wasmModule : void 0;
197
- this.mujoco ?? (this.mujoco = await L({
198
- locateFile: (p) => p.endsWith(".wasm") ? C(e.baseUrl) : p,
199
- ...i ? {
200
- instantiateWasm(p, j) {
201
- return R(i, p, j);
202
- }
203
- } : {}
204
- }));
205
- const o = V(this.mujoco.FS, t.files);
206
- let a = null, n = null, s = null, r = null, l = w, c = null, m = null, h = w;
207
- try {
208
- if (a = this.mujoco.MjModel.from_xml_path(o.writeEntry(t.xml)), l = a.opt.timestep, !Number.isFinite(l) || l <= 0)
209
- throw new Error(`Invalid MuJoCo timestep: ${l}`);
210
- for (const j of t.massOverrides ?? []) {
211
- const b = this.mujoco.mj_name2id(a, this.mujoco.mjtObj.mjOBJ_BODY.value, j.body);
212
- if (b <= 0 || !Number.isFinite(j.mass) || j.mass <= 0 || !(a.body_mass[b] > 0)) throw new Error(`Invalid mass override: ${j.body}`);
213
- const g = j.mass / a.body_mass[b];
214
- a.body_mass[b] = j.mass;
215
- for (let u = 0; u < 3; u++) a.body_inertia[b * 3 + u] *= g;
216
- }
217
- n = new this.mujoco.MjData(a), (d = t.massOverrides) != null && d.length && this.mujoco.mj_setConst(a, n), this.worldRotation.identity(), this.applyInitialControls(n, t.initialControls), this.applyInitialVelocities(a, n, t.initialVelocities), this.mujoco.mj_forward(a, n);
218
- const p = this.mujoco.mj_name2id(a, this.mujoco.mjtObj.mjOBJ_GEOM.value, "__viewer_default_ground__");
219
- if (s = p < 0 ? null : { id: p, height: a.geom_pos[p * 3 + 2], sameFrame: a.geom_sameframe[p] }, r = this.seatDefaultGround(a, n), Array.from(a.jnt_type).some((j) => j === this.mujoco.mjtJoint.mjJNT_HINGE.value || j === this.mujoco.mjtJoint.mjJNT_SLIDE.value) && (c = new U(this.mujoco, a, n)), c && ((_ = t.jointPreviewCollisionExcludes) != null && _.length)) {
220
- m = Int32Array.from(a.exclude_signature);
221
- const j = /* @__PURE__ */ new Set();
222
- for (const u of t.jointPreviewCollisionExcludes) {
223
- const y = this.mujoco.mj_name2id(a, this.mujoco.mjtObj.mjOBJ_BODY.value, u.body1), E = this.mujoco.mj_name2id(a, this.mujoco.mjtObj.mjOBJ_BODY.value, u.body2);
224
- if (y <= 0 || E <= 0) throw new Error(`Invalid joint preview collision pair: ${u.body1}, ${u.body2}`);
225
- c.hasInitialBodyOverlap(y, E) || j.add(Math.min(y, E) * 65536 + Math.max(y, E));
226
- }
227
- const b = m.filter((u) => !j.has(u)), g = new Int32Array(m.length);
228
- g.set(b, g.length - b.length), a.exclude_signature.set(g), this.mujoco.mj_forward(a, n);
229
- }
230
- h = this.actuatorTimestep(a, l), a.opt.timestep = h;
231
- } catch (p) {
232
- throw n == null || n.delete(), a == null || a.delete(), J(p, "E_MUJOCO_INITIALIZE");
233
- } finally {
234
- o.dispose();
235
- }
236
- this.disposeModel(), this.model = a, this.data = n, this.initialControls = t.initialControls ?? [], this.initialVelocities = t.initialVelocities ?? [], this.accumulator = 0, this.timestep = h, this.playbackTimestep = h, this.initialGround = s, this.seatedGround = r, this.topLevelBodies = this.captureTopLevelBodies(a), this.jointPreviewCollision = c, this.jointPreviewExclusions = m;
237
- }
238
- get defaultGroundHeight() {
239
- if (!this.mujoco || !this.model) return;
240
- const t = this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj.mjOBJ_GEOM.value, "__viewer_default_ground__");
241
- return t < 0 ? void 0 : this.model.geom_pos[t * 3 + 2];
242
- }
243
- /**
244
- * Re-orients the compiled physics to the given authored up axis by rotating
245
- * every top-level body about the world origin. Gravity stays -Z and the
246
- * viewer ground stays the authored horizontal plane, so a cup that was
247
- * standing now genuinely topples and settles on its side — the alternative,
248
- * rotating only the rendered scene graph, would leave the visuals and the
249
- * simulation in different frames.
250
- *
251
- * The full current state (free-joint positions, orientations and velocities)
252
- * is rotated by the same delta, so a paused or running simulation is carried
253
- * over instead of being re-seeded.
254
- */
255
- setWorldRotation(t) {
256
- var a;
257
- if (!this.mujoco || !this.model || !this.data) return;
258
- const e = this.model, i = this.data;
259
- if (t.equals(this.worldRotation)) return;
260
- const o = t.clone().multiply(this.worldRotation.clone().invert());
261
- this.rotateReferenceFrames(this.topLevelBodies, t), this.rotateState(this.topLevelBodies, e, i, o), this.worldRotation.copy(t), this.mujoco.mj_forward(e, i), this.seatedGround = this.seatDefaultGround(e, i, (a = this.initialGround) == null ? void 0 : a.height), this.accumulator = 0;
262
- }
263
- captureTopLevelBodies(t) {
264
- const e = this.mujoco, i = [];
265
- for (let o = 1; o < t.nbody; o++) {
266
- if (t.body_parentid[o] !== 0) continue;
267
- const a = t.body_jntadr[o], n = t.body_jntnum[o] === 1 && a >= 0 && t.jnt_type[a] === e.mjtJoint.mjJNT_FREE.value ? a : -1, s = o * 3, r = o * 4;
268
- i.push({
269
- id: o,
270
- position: new q(t.body_pos[s], t.body_pos[s + 1], t.body_pos[s + 2]),
271
- quaternion: new D(t.body_quat[r + 1], t.body_quat[r + 2], t.body_quat[r + 3], t.body_quat[r]),
272
- freeJoint: n
273
- });
274
- }
275
- return i;
276
- }
277
- /** Writes the rotated reference pose, which reset() and fixed bases follow. */
278
- rotateReferenceFrames(t, e) {
279
- const i = this.model;
280
- for (const o of t) {
281
- const a = o.position.clone().applyQuaternion(e), n = e.clone().multiply(o.quaternion), s = o.id * 3, r = o.id * 4;
282
- if (i.body_pos[s] = a.x, i.body_pos[s + 1] = a.y, i.body_pos[s + 2] = a.z, i.body_quat[r] = n.w, i.body_quat[r + 1] = n.x, i.body_quat[r + 2] = n.y, i.body_quat[r + 3] = n.z, i.body_sameframe[o.id] && (i.body_sameframe[o.id] = 0), o.freeJoint < 0) continue;
283
- const l = i.jnt_qposadr[o.freeJoint];
284
- i.qpos0[l] = a.x, i.qpos0[l + 1] = a.y, i.qpos0[l + 2] = a.z, i.qpos0[l + 3] = n.w, i.qpos0[l + 4] = n.x, i.qpos0[l + 5] = n.y, i.qpos0[l + 6] = n.z;
285
- }
286
- }
287
- /** Rotates the live free-joint state so the simulation keeps its progress. */
288
- rotateState(t, e, i, o) {
289
- for (const a of t) {
290
- if (a.freeJoint < 0) continue;
291
- const n = e.jnt_qposadr[a.freeJoint], s = e.jnt_dofadr[a.freeJoint], r = new q(i.qpos[n], i.qpos[n + 1], i.qpos[n + 2]).applyQuaternion(o);
292
- i.qpos[n] = r.x, i.qpos[n + 1] = r.y, i.qpos[n + 2] = r.z;
293
- const l = new D(i.qpos[n + 4], i.qpos[n + 5], i.qpos[n + 6], i.qpos[n + 3]).premultiply(o);
294
- i.qpos[n + 3] = l.w, i.qpos[n + 4] = l.x, i.qpos[n + 5] = l.y, i.qpos[n + 6] = l.z;
295
- const c = new q(i.qvel[s], i.qvel[s + 1], i.qvel[s + 2]).applyQuaternion(o);
296
- i.qvel[s] = c.x, i.qvel[s + 1] = c.y, i.qvel[s + 2] = c.z;
297
- const m = new q(i.qvel[s + 3], i.qvel[s + 4], i.qvel[s + 5]).applyQuaternion(o);
298
- i.qvel[s + 3] = m.x, i.qvel[s + 4] = m.y, i.qvel[s + 5] = m.z;
299
- }
300
- }
301
- /** Lower only the viewer-owned plane, never authored bodies or authored floors.
302
- * Run after forward kinematics, not during stepping (the floor must not follow falling bodies).
303
- * `baseHeight` re-seats from a stable reference; omitting it lowers from the current pose.
304
- */
305
- seatDefaultGround(t, e, i) {
306
- const o = this.mujoco, a = o.mj_name2id(t, o.mjtObj.mjOBJ_GEOM.value, "__viewer_default_ground__");
307
- if (a < 0 || t.geom_bodyid[a] !== 0 || t.geom_type[a] !== o.mjtGeom.mjGEOM_PLANE.value) return null;
308
- let n = i ?? t.geom_pos[a * 3 + 2];
309
- for (let s = 0; s < t.ngeom; s++) {
310
- if (s === a || t.geom_type[s] === o.mjtGeom.mjGEOM_PLANE.value || !(t.geom_contype[s] & t.geom_conaffinity[a]) && !(t.geom_conaffinity[s] & t.geom_contype[a])) continue;
311
- const r = this.geomBottom(t, e, s), l = Math.max(1e-3, t.geom_margin[s] + t.geom_margin[a]);
312
- Number.isFinite(r) && r < n && (n = Math.min(n, r - l));
313
- }
314
- return n !== t.geom_pos[a * 3 + 2] && (t.geom_pos[a * 3 + 2] = n, t.geom_sameframe[a] = 0, o.mj_forward(t, e)), { id: a, height: n, sameFrame: t.geom_sameframe[a] };
315
- }
316
- /**
317
- * Resolve the lowest world-space point directly from MuJoCo's primitive
318
- * parameters. Rotating a mesh's local AABB into world space is conservative:
319
- * for a long, rotated shape it can sit far below the actual geometry. Use the
320
- * compiled vertices for mesh-backed geoms so the ground reflects the real
321
- * lowest point rather than the corners of its local bounding box.
322
- */
323
- geomBottom(t, e, i) {
324
- const o = this.mujoco, a = e.geom_xpos[i * 3 + 2], n = i * 3, s = i * 9, r = t.geom_type[i], l = Math.abs(t.geom_size[n]), c = Math.abs(t.geom_size[n + 1]), m = Math.abs(t.geom_size[n + 2]);
325
- if (r === o.mjtGeom.mjGEOM_SPHERE.value)
326
- return a - l;
327
- if (r === o.mjtGeom.mjGEOM_CAPSULE.value)
328
- return a - l - Math.abs(e.geom_xmat[s + 8]) * c;
329
- if (r === o.mjtGeom.mjGEOM_CYLINDER.value) {
330
- const g = e.geom_xmat[s + 8];
331
- return a - Math.abs(g) * c - Math.sqrt(Math.max(0, 1 - g * g)) * l;
332
- }
333
- if (r === o.mjtGeom.mjGEOM_ELLIPSOID.value)
334
- return a - Math.hypot(
335
- e.geom_xmat[s + 2] * l,
336
- e.geom_xmat[s + 5] * c,
337
- e.geom_xmat[s + 8] * m
338
- );
339
- if (r === o.mjtGeom.mjGEOM_BOX.value)
340
- return a - Math.abs(e.geom_xmat[s + 2]) * l - Math.abs(e.geom_xmat[s + 5]) * c - Math.abs(e.geom_xmat[s + 8]) * m;
341
- if (r === o.mjtGeom.mjGEOM_MESH.value || r === o.mjtGeom.mjGEOM_SDF.value) {
342
- const g = t.geom_dataid[i];
343
- if (g < 0 || g >= t.nmesh) return Number.POSITIVE_INFINITY;
344
- const u = t.mesh_vertadr[g], y = t.mesh_vertnum[g];
345
- if (!Number.isInteger(u) || !Number.isInteger(y) || u < 0 || y <= 0 || u + y > t.nmeshvert)
346
- return Number.POSITIVE_INFINITY;
347
- let E = Number.POSITIVE_INFINITY;
348
- for (let M = u; M < u + y; M++) {
349
- const T = M * 3, x = a + e.geom_xmat[s + 6] * t.mesh_vert[T] + e.geom_xmat[s + 7] * t.mesh_vert[T + 1] + e.geom_xmat[s + 8] * t.mesh_vert[T + 2];
350
- Number.isFinite(x) && x < E && (E = x);
351
- }
352
- return E;
353
- }
354
- const h = i * 6, d = t.geom_aabb[h + 3], _ = t.geom_aabb[h + 4], p = t.geom_aabb[h + 5];
355
- if (![d, _, p].every((g) => Number.isFinite(g) && g >= 0))
356
- return Number.POSITIVE_INFINITY;
357
- const j = a + e.geom_xmat[s + 6] * t.geom_aabb[h] + e.geom_xmat[s + 7] * t.geom_aabb[h + 1] + e.geom_xmat[s + 8] * t.geom_aabb[h + 2], b = Math.abs(e.geom_xmat[s + 6]) * d + Math.abs(e.geom_xmat[s + 7]) * _ + Math.abs(e.geom_xmat[s + 8]) * p;
358
- return j - b;
359
- }
360
- beginGrab({
361
- bodyId: t,
362
- localPoint: e,
363
- target: i,
364
- stiffness: o,
365
- damping: a,
366
- maxForce: n,
367
- dampingRatio: s = W,
368
- maxTargetSpeed: r = N,
369
- targetResponse: l = A
370
- }) {
371
- var p;
372
- const c = Math.max(((p = this.model) == null ? void 0 : p.body_mass[t]) ?? 1, 1e-6), m = o ?? Y, h = a ?? 2 * Math.sqrt(m * c) * s, d = n ?? Math.max(X, c * Q);
373
- this.setTimestep(this.grabTimestep(t, e, c, m));
374
- const _ = [i[0], i[1], i[2]];
375
- this.grab = {
376
- bodyId: t,
377
- localPoint: [e[0], e[1], e[2]],
378
- target: [..._],
379
- requestedTarget: _,
380
- stiffness: m,
381
- damping: h,
382
- maxForce: d,
383
- strength: 1,
384
- maxTargetSpeed: r,
385
- targetResponse: l
386
- };
387
- }
388
- updateGrabTarget(t) {
389
- this.grab && (this.grab.requestedTarget = [t[0], t[1], t[2]]);
390
- }
391
- updateGrabStrength(t) {
392
- this.grab && (this.grab.strength = t);
393
- }
394
- applyGrabForce() {
395
- if (!this.grab || !this.model || !this.data || !this.mujoco) return;
396
- const { bodyId: t, localPoint: e, target: i, stiffness: o, damping: a, maxForce: n, strength: s } = this.grab, r = this.data.xmat.subarray(t * 9, t * 9 + 9), l = this.data.xpos.subarray(t * 3, t * 3 + 3), c = [
397
- l[0] + r[0] * e[0] + r[1] * e[1] + r[2] * e[2],
398
- l[1] + r[3] * e[0] + r[4] * e[1] + r[5] * e[2],
399
- l[2] + r[6] * e[0] + r[7] * e[1] + r[8] * e[2]
400
- ], m = this.data.cvel.subarray(t * 6, t * 6 + 6), h = this.data.xipos.subarray(t * 3, t * 3 + 3), d = [
401
- c[0] - h[0],
402
- c[1] - h[1],
403
- c[2] - h[2]
404
- ], _ = [
405
- m[3] + m[1] * d[2] - m[2] * d[1],
406
- m[4] + m[2] * d[0] - m[0] * d[2],
407
- m[5] + m[0] * d[1] - m[1] * d[0]
408
- ], p = k({ target: i, point: c, velocity: _, stiffness: o, damping: a, maxForce: n, strength: s });
409
- this.lastGrabForce = [...p], this.data.qfrc_applied.fill(0);
410
- const j = Math.min(
411
- Math.max(this.model.body_inertia[t * 3], 1e-9),
412
- Math.max(this.model.body_inertia[t * 3 + 1], 1e-9),
413
- Math.max(this.model.body_inertia[t * 3 + 2], 1e-9)
414
- ), b = [
415
- -j * I * m[0],
416
- -j * I * m[1],
417
- -j * I * m[2]
418
- ];
419
- this.mujoco.mj_applyFT(
420
- this.model,
421
- this.data,
422
- p,
423
- b,
424
- c,
425
- t,
426
- this.data.qfrc_applied
427
- );
428
- }
429
- endGrab() {
430
- this.data && this.data.qfrc_applied.fill(0), this.lastGrabForce = [0, 0, 0], this.grab = null, this.setTimestep(this.playbackTimestep);
431
- }
432
- step(t) {
433
- if (!this.mujoco || !this.model || !this.data || t <= 0) return !1;
434
- this.accumulator += Math.min(t, O);
435
- let e = !1;
436
- for (; this.accumulator >= this.timestep; )
437
- this.updateGrabTargetForStep(), this.applyGrabForce(), this.mujoco.mj_step(this.model, this.data), this.accumulator -= this.timestep, e = !0;
438
- return e;
439
- }
440
- updateGrabTargetForStep() {
441
- const t = this.grab;
442
- if (!t) return;
443
- const e = t.requestedTarget ?? t.target, i = (t.maxTargetSpeed ?? N) * Math.max(1, Math.sqrt(t.strength)), o = t.targetResponse ?? A, a = 1 - Math.exp(-o * this.timestep), n = i * this.timestep;
444
- for (let s = 0; s < 3; s++) {
445
- const r = e[s] - t.target[s], l = Math.sign(r) * Math.min(Math.abs(r) * a, n);
446
- t.target[s] += l;
447
- }
448
- }
449
- get isJointDriveActive() {
450
- return this.jointDriveActive;
451
- }
452
- /** Set servo goals only. Actual coordinates are written exclusively by mj_step. */
453
- setJointTargets(t) {
454
- if (!this.mujoco || !this.model || !this.data) return;
455
- const e = this.mujoco, i = this.model, o = /* @__PURE__ */ new Map();
456
- for (const [n, s] of Object.entries(t)) {
457
- if (!Number.isFinite(s)) continue;
458
- const r = e.mj_name2id(i, e.mjtObj.mjOBJ_JOINT.value, n);
459
- if (r < 0) continue;
460
- const l = i.jnt_type[r];
461
- if (l !== e.mjtJoint.mjJNT_HINGE.value && l !== e.mjtJoint.mjJNT_SLIDE.value) continue;
462
- const c = i.jnt(r);
463
- let m = s, h;
464
- try {
465
- c.limited && (h = { lower: i.jnt_range[r * 2], upper: i.jnt_range[r * 2 + 1] }, m = Math.max(h.lower, Math.min(h.upper, m)));
466
- } finally {
467
- c.delete();
468
- }
469
- o.set(r, {
470
- qpos: i.jnt_qposadr[r],
471
- dof: i.jnt_dofadr[r],
472
- sliding: l === e.mjtJoint.mjJNT_SLIDE.value,
473
- value: m,
474
- limits: h
475
- });
476
- }
477
- if (o.size !== this.jointTargets.size || [...o].some(([n, s]) => !this.jointTargets.has(n) || Math.abs(s.value - this.jointTargets.get(n).value) > 1e-9)) {
478
- if (this.jointTargets = o, this.captureHeldJointPoses(), !o.size || [...o.values()].every((n) => Math.abs(n.value - this.data.qpos[n.qpos]) < 1e-9)) {
479
- this.jointDriveActive = !1, this.jointDriveAccumulator = 0, this.freezeJointDrivePose();
480
- return;
481
- }
482
- this.jointDriveActive = !0, this.jointDriveSettledSeconds = 0, this.jointDriveElapsed = 0, this.jointDriveStalledSeconds = 0, this.jointDriveBestError = this.jointDriveError(), this.jointDriveDuration = Math.min(et, this.jointDriveBestError * 2 + 3);
483
- }
484
- }
485
- clearJointTargets(t = {}) {
486
- this.jointTargets.clear(), this.heldJointPoses = [], this.jointDriveActive = !1, this.jointDriveAccumulator = 0, this.jointDriveSettledSeconds = 0, this.jointDriveElapsed = 0, this.jointDriveStalledSeconds = 0, t.freeze && this.freezeJointDrivePose();
487
- }
488
- jointDriveError() {
489
- let t = 0;
490
- for (const e of this.jointTargets.values())
491
- t = Math.max(t, Math.abs(e.value - this.data.qpos[e.qpos]) / (e.sliding ? 0.15 : 1));
492
- return t;
493
- }
494
- captureHeldJointPoses() {
495
- var s;
496
- const t = this.mujoco, e = this.model, i = this.data, o = new Set(this.jointTargets.keys());
497
- t.mj_forward(e, i);
498
- const a = /* @__PURE__ */ new Set();
499
- for (let r = 0; r < i.ne; r++) a.add(i.efc_id[r]);
500
- let n = !0;
501
- for (; n; ) {
502
- n = !1;
503
- for (let r = 0; r < e.neq; r++) {
504
- if (e.eq_type[r] !== t.mjtEq.mjEQ_JOINT.value || !a.has(r)) continue;
505
- const l = e.eq_obj1id[r], c = e.eq_obj2id[r];
506
- if (!(c < 0 || !o.has(l) && !o.has(c)))
507
- for (const m of [l, c]) o.has(m) || (o.add(m), n = !0);
508
- }
509
- }
510
- this.heldJointPoses = [];
511
- for (let r = 0; r < e.njnt; r++) {
512
- if (o.has(r)) continue;
513
- const l = e.jnt_type[r], c = l === t.mjtJoint.mjJNT_FREE.value, m = l === t.mjtJoint.mjJNT_BALL.value, h = e.jnt_qposadr[r], d = e.jnt_dofadr[r];
514
- this.heldJointPoses.push({ qpos: h, dof: d, values: Array.from(i.qpos.slice(h, h + (c ? 7 : m ? 4 : 1))), dofs: c ? 6 : m ? 3 : 1 });
515
- }
516
- this.holdJointPoses(), (s = this.jointPreviewCollision) == null || s.prepare(o);
517
- }
518
- holdJointPoses() {
519
- const t = this.data;
520
- for (const e of this.heldJointPoses)
521
- 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);
522
- }
523
- freezeJointDrivePose() {
524
- !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));
525
- }
526
- /** A paused edit still needs integration and contact/equality constraint solving. */
527
- stepJointDrive(t) {
528
- if (!this.jointDriveActive || !this.mujoco || !this.model || !this.data || !(t > 0)) return !1;
529
- const e = this.mujoco, i = this.model, o = this.data, a = Math.min(this.timestep, Z), n = i.opt.timestep, s = i.opt.disableflags, r = this.jointPreviewExclusions ? Int32Array.from(i.exclude_signature) : null, l = Float64Array.from(o.qfrc_applied), c = new Float64Array(i.nq), m = [];
530
- this.jointDriveAccumulator += Math.min(t, O) * K;
531
- let h = !1;
532
- try {
533
- this.jointPreviewExclusions && i.exclude_signature.set(this.jointPreviewExclusions), i.opt.timestep = a, i.opt.disableflags = s | e.mjtDisableBit.mjDSBL_ACTUATION.value;
534
- for (const d of this.heldJointPoses)
535
- for (let _ = d.dof; _ < d.dof + d.dofs; _++) {
536
- const p = i.dof_M0[_], j = i.dof_armature[_];
537
- m.push({ id: _, armature: j, inertia: p, invweight: i.dof_invweight0[_] });
538
- const b = Math.max(1e-9, p) * 1e6;
539
- i.dof_armature[_] = j + b, i.dof_M0[_] = p + b, i.dof_invweight0[_] = 0;
540
- }
541
- for (m.length && this.holdJointPoses(), (m.length || r) && e.mj_forward(i, o); this.jointDriveActive && this.jointDriveAccumulator >= a; ) {
542
- c.set(o.qpos);
543
- const d = o.time;
544
- o.qfrc_applied.set(l);
545
- for (const u of this.jointTargets.values()) {
546
- const y = u.value - o.qpos[u.qpos], E = u.sliding ? 0.15 : 1, M = Math.max(-E, Math.min(E, y * G / 2)), T = u.sliding ? 6 : 40, x = Math.max(-T, Math.min(
547
- T,
548
- 2 * G * (M - o.qvel[u.dof])
549
- )), P = Math.max(i.dof_M0[u.dof], 1e-9);
550
- o.qfrc_applied[u.dof] += P * x + o.qfrc_bias[u.dof];
551
- }
552
- e.mj_step(i, o), this.holdJointPoses();
553
- let _ = Array.from(o.qpos).every(Number.isFinite) && [...this.jointTargets.values()].every((u) => {
554
- const y = c[u.qpos], E = o.qpos[u.qpos], M = (u.sliding ? 0.15 : 1) * a * 2, T = u.sliding ? 1e-5 : 1e-3;
555
- return Math.abs(E - y) <= M + 1e-8 && (!u.limits || E >= Math.min(y, u.limits.lower - T) - 1e-9 && E <= Math.max(y, u.limits.upper + T) + 1e-9);
556
- });
557
- if (_ && this.jointPreviewCollision && (e.mj_kinematics(i, o), _ = this.jointPreviewCollision.accept(o)), !_) {
558
- o.qpos.set(c), o.time = d, this.jointDriveActive = !1, this.jointDriveAccumulator = 0, h = !0;
559
- break;
560
- }
561
- this.jointDriveAccumulator -= a, h = !0, this.jointDriveElapsed += a;
562
- const p = this.jointDriveError(), j = p < this.jointDriveBestError - 1e-4;
563
- j && (this.jointDriveBestError = p);
564
- const b = [...this.jointTargets.values()].some((u) => Math.abs(o.qvel[u.dof]) > (u.sliding ? 0.15 : 1) * 1e-3);
565
- this.jointDriveStalledSeconds = j || b ? 0 : this.jointDriveStalledSeconds + a;
566
- let g = !0;
567
- for (const u of this.jointTargets.values())
568
- if (Math.abs(u.value - o.qpos[u.qpos]) > (u.sliding ? 1e-5 : 1e-4) || Math.abs(o.qvel[u.dof]) > (u.sliding ? 1e-4 : 1e-3)) {
569
- g = !1;
570
- break;
571
- }
572
- this.jointDriveSettledSeconds = g ? this.jointDriveSettledSeconds + a : 0, (this.jointDriveSettledSeconds >= 0.1 || this.jointDriveStalledSeconds >= tt || this.jointDriveElapsed >= this.jointDriveDuration) && (this.jointDriveActive = !1, this.jointDriveAccumulator = 0);
573
- }
574
- h && !m.length && !r && (this.jointDriveActive ? e.mj_forward(i, o) : this.freezeJointDrivePose());
575
- } finally {
576
- i.opt.timestep = n, i.opt.disableflags = s, r && i.exclude_signature.set(r), o.qfrc_applied.set(l);
577
- for (const d of m)
578
- i.dof_armature[d.id] = d.armature, i.dof_M0[d.id] = d.inertia, i.dof_invweight0[d.id] = d.invweight;
579
- (m.length || r) && (this.jointDriveActive ? e.mj_forward(i, o) : this.freezeJointDrivePose());
580
- }
581
- return h;
582
- }
583
- setJointValues(t) {
584
- if (!(!this.mujoco || !this.model || !this.data)) {
585
- for (const [e, i] of Object.entries(t)) {
586
- const o = this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj.mjOBJ_JOINT.value, e);
587
- if (o < 0 || !Number.isFinite(i)) continue;
588
- const a = this.model.jnt_type[o], n = this.mujoco.mjtJoint.mjJNT_HINGE.value, s = this.mujoco.mjtJoint.mjJNT_SLIDE.value;
589
- a !== n && a !== s || (this.data.qpos[this.model.jnt_qposadr[o]] = i);
590
- }
591
- this.mujoco.mj_forward(this.model, this.data), this.seatDefaultGround(this.model, this.data), this.accumulator = 0;
592
- }
593
- }
594
- /** Move scalar joints for a paused visual preview without running contacts or constraints. */
595
- setJointValuesKinematic(t) {
596
- if (!this.mujoco || !this.model || !this.data) return;
597
- const e = this.mujoco, i = this.model, o = this.data;
598
- this.jointTargets.clear(), this.heldJointPoses = [], this.jointDriveActive = !1, this.jointDriveAccumulator = 0, this.jointDriveSettledSeconds = 0, this.jointDriveElapsed = 0, this.jointDriveStalledSeconds = 0;
599
- for (const [a, n] of Object.entries(t)) {
600
- if (!Number.isFinite(n)) continue;
601
- const s = e.mj_name2id(i, e.mjtObj.mjOBJ_JOINT.value, a);
602
- if (s < 0) continue;
603
- const r = i.jnt_type[s];
604
- r !== e.mjtJoint.mjJNT_HINGE.value && r !== e.mjtJoint.mjJNT_SLIDE.value || (o.qpos[i.jnt_qposadr[s]] = n);
605
- }
606
- o.qvel.fill(0), o.qacc.fill(0), o.qacc_warmstart.fill(0), o.qfrc_applied.fill(0), e.mj_kinematics(i, o), this.accumulator = 0;
607
- }
608
- getJointValues(t) {
609
- const e = {};
610
- if (!this.mujoco || !this.model || !this.data) return e;
611
- for (const i of t) {
612
- const o = this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj.mjOBJ_JOINT.value, i);
613
- if (o < 0) continue;
614
- const a = this.model.jnt_type[o], n = this.mujoco.mjtJoint.mjJNT_HINGE.value, s = this.mujoco.mjtJoint.mjJNT_SLIDE.value;
615
- (a === n || a === s) && (e[i] = this.data.qpos[this.model.jnt_qposadr[o]]);
616
- }
617
- return e;
618
- }
619
- reset() {
620
- var t;
621
- if (!(!this.mujoco || !this.model || !this.data)) {
622
- if (this.clearJointTargets(), this.endGrab(), this.seatedGround) {
623
- const { id: e, height: i, sameFrame: o } = this.seatedGround;
624
- this.model.geom_pos[e * 3 + 2] = i, this.model.geom_sameframe[e] = o;
625
- }
626
- this.mujoco.mj_resetData(this.model, this.data), this.applyInitialControls(this.data, this.initialControls), 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;
627
- }
628
- }
629
- dispose() {
630
- this.disposeModel(), this.mujoco = null;
631
- }
632
- actuatorTimestep(t, e) {
633
- const i = this.mujoco, o = /* @__PURE__ */ new Map();
634
- for (let n = 0; n < t.nu; n++) {
635
- if (t.actuator_trntype[n] !== i.mjtTrn.mjTRN_JOINT.value || t.actuator_biastype[n] !== i.mjtBias.mjBIAS_AFFINE.value) continue;
636
- const s = t.actuator_trnid[n * 2];
637
- if (s < 0 || t.jnt_type[s] !== i.mjtJoint.mjJNT_HINGE.value && t.jnt_type[s] !== i.mjtJoint.mjJNT_SLIDE.value) continue;
638
- const r = -t.actuator_biasprm[n * 10 + 1] * t.actuator_gear[n * 6] ** 2;
639
- if (!(r > 0) || !Number.isFinite(r)) continue;
640
- const l = t.jnt_dofadr[s];
641
- o.set(l, (o.get(l) ?? 0) + r);
642
- }
643
- let a = e;
644
- for (const [n, s] of o) {
645
- const r = t.dof_M0[n];
646
- !(r > 0) || !Number.isFinite(r) || (a = Math.min(a, it * Math.sqrt(r / s)));
647
- }
648
- return a;
649
- }
650
- applyInitialControls(t, e) {
651
- if (e != null && e.length) {
652
- if (e.length !== t.ctrl.length) throw J(new Error(`Initial control count ${e.length} does not match MuJoCo actuator count ${t.ctrl.length}.`), "E_MUJOCO_INITIALIZE");
653
- t.ctrl.set(e);
654
- }
655
- }
656
- /**
657
- * A point force on a light body can excite a much higher rotational
658
- * frequency than its translational mass suggests. Refine physics only while
659
- * that body is grabbed instead of adding global damping to hide the error.
660
- */
661
- grabTimestep(t, e, i, o) {
662
- if (!this.model || !this.data) return this.playbackTimestep;
663
- const a = Math.min(
664
- Math.max(this.model.body_inertia[t * 3], 1e-9),
665
- Math.max(this.model.body_inertia[t * 3 + 1], 1e-9),
666
- Math.max(this.model.body_inertia[t * 3 + 2], 1e-9)
667
- ), n = this.data.xpos.subarray(t * 3, t * 3 + 3), s = this.data.xipos.subarray(t * 3, t * 3 + 3), r = this.data.xmat.subarray(t * 9, t * 9 + 9), l = [
668
- n[0] + r[0] * e[0] + r[1] * e[1] + r[2] * e[2],
669
- n[1] + r[3] * e[0] + r[4] * e[1] + r[5] * e[2],
670
- n[2] + r[6] * e[0] + r[7] * e[1] + r[8] * e[2]
671
- ], c = (l[0] - s[0]) ** 2 + (l[1] - s[1]) ** 2 + (l[2] - s[2]) ** 2, m = Math.sqrt(o * (1 / i + c / a)), h = H / Math.max(m, 1e-9);
672
- return Math.min(this.playbackTimestep, Math.max($, h));
673
- }
674
- setTimestep(t) {
675
- var e;
676
- this.timestep = t, (e = this.model) != null && e.opt && (this.model.opt.timestep = t);
677
- }
678
- applyInitialVelocities(t, e, i) {
679
- for (const o of i ?? []) {
680
- const a = this.mujoco.mj_name2id(t, this.mujoco.mjtObj.mjOBJ_BODY.value, o.body), n = a >= 0 ? t.body_jntadr[a] : -1;
681
- if (n < 0 || t.jnt_type[n] !== this.mujoco.mjtJoint.mjJNT_FREE.value || o.velocity.length !== 6 || !o.velocity.every(Number.isFinite))
682
- throw J(new Error(`Invalid free-body initial velocity: ${o.body}`), "E_MUJOCO_INITIALIZE");
683
- const { worldRotation: s } = this, r = new q(o.velocity[0], o.velocity[1], o.velocity[2]).applyQuaternion(s), l = new q(o.velocity[3], o.velocity[4], o.velocity[5]).applyQuaternion(s);
684
- e.qvel.set([r.x, r.y, r.z, l.x, l.y, l.z], t.jnt_dofadr[n]);
685
- }
686
- }
687
- disposeModel() {
688
- var t, e;
689
- this.clearJointTargets(), this.jointPreviewCollision = null, this.jointPreviewExclusions = null, this.endGrab(), (t = this.data) == null || t.delete(), (e = this.model) == null || e.delete(), this.data = null, this.model = null, this.initialGround = null, this.seatedGround = null, this.topLevelBodies = [], this.initialControls = [], this.initialVelocities = [], this.accumulator = 0, this.playbackTimestep = w, this.timestep = w;
690
- }
691
- }
692
- function J(v, t) {
693
- const e = v instanceof Error ? v : new Error(String(v));
694
- return Object.assign(e, { code: t });
695
- }
696
- export {
697
- rt as MujocoRuntime
698
- };