@nebula-spatial/viewer 0.4.2 → 0.4.3

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,761 +0,0 @@
1
- var Se = Object.defineProperty;
2
- var Ae = (o, e, t) => e in o ? Se(o, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : o[e] = t;
3
- var q = (o, e, t) => Ae(o, typeof e != "symbol" ? e + "" : e, t);
4
- import { d as ve, S as ue } from "./stage-D-Q_zul6.js";
5
- import { ConvexGeometry as Me } from "three/examples/jsm/geometries/ConvexGeometry.js";
6
- import { LineBasicMaterial as Oe, EdgesGeometry as W, LineSegments as $e, Group as z, MeshStandardMaterial as ye, Mesh as N, PlaneGeometry as Re, BoxGeometry as X, SphereGeometry as te, CylinderGeometry as re, CapsuleGeometry as be, Vector3 as T, BufferGeometry as Pe, BufferAttribute as ce, Euler as J, MathUtils as Ue, Matrix3 as fe, Matrix4 as k, Quaternion as ge, LoadingManager as Fe } from "three";
7
- import { GLTFLoader as De } from "three/examples/jsm/loaders/GLTFLoader.js";
8
- import { OBJLoader as qe } from "three/examples/jsm/loaders/OBJLoader.js";
9
- import { STLLoader as Ge } from "three/examples/jsm/loaders/STLLoader.js";
10
- class Y {
11
- constructor(e, t) {
12
- q(this, "root");
13
- q(this, "bodies", /* @__PURE__ */ new Map());
14
- q(this, "disposed", !1);
15
- this.runtime = e, this.root = t.root;
16
- const r = e.mujoco, n = e.model;
17
- for (const [l, u] of t.bindings) {
18
- const c = r.mj_name2id(n, r.mjtObj.mjOBJ_BODY.value, l);
19
- if (c < 0) throw me(`Physics body missing for visual link: ${l}`, "E_SIMULATION_BIND");
20
- u.userData.bodyId = c, this.bodies.set(c, u);
21
- }
22
- if (this.bodies.size !== t.expectedLinkCount) throw me("Visual body binding count mismatch.", "E_SIMULATION_BIND");
23
- this.sync();
24
- }
25
- sync() {
26
- if (this.disposed || !this.runtime.data) return;
27
- const { xpos: e, xquat: t } = this.runtime.data;
28
- for (const [r, n] of this.bodies) {
29
- const l = r * 3, u = r * 4;
30
- n.position.set(e[l], e[l + 1], e[l + 2]), n.quaternion.set(t[u + 1], t[u + 2], t[u + 3], t[u]);
31
- }
32
- this.root.updateMatrixWorld(!0);
33
- }
34
- dispose() {
35
- this.disposed || (this.disposed = !0, this.bodies.clear(), ve(this.root));
36
- }
37
- }
38
- function me(o, e) {
39
- return Object.assign(new Error(o), { code: e });
40
- }
41
- class Ce {
42
- constructor(e) {
43
- q(this, "entries", /* @__PURE__ */ new Map());
44
- q(this, "objectUrls", /* @__PURE__ */ new Map());
45
- this.source = e;
46
- const t = e.original;
47
- if (Ie(t))
48
- for (const r of t.files) this.entries.set(A(r.path), r.file);
49
- else typeof Blob < "u" && t instanceof Blob ? this.entries.set(e.entryPath ?? e.filename ?? "asset", t) : t instanceof ArrayBuffer ? this.entries.set(e.entryPath ?? e.filename ?? "asset", new Blob([t])) : typeof t == "object" && t !== null && "kind" in t && t.kind === "buffer" && this.entries.set(e.entryPath ?? e.filename ?? "asset", new Blob([t.buffer]));
50
- }
51
- paths() {
52
- return [...this.entries.keys()];
53
- }
54
- hasLocalFiles() {
55
- return this.entries.size > 0;
56
- }
57
- put(e, t) {
58
- this.entries.set(A(e), t);
59
- }
60
- asSourceRecord(e = "") {
61
- const t = A(e), r = t ? `${t}/` : "", n = {};
62
- for (const [l, u] of this.entries)
63
- (!r || l.startsWith(r)) && (n[r ? l.slice(r.length) : l] = u);
64
- return n;
65
- }
66
- resolve(e, t = "") {
67
- const r = this.find(e, t);
68
- if (r) return r;
69
- const n = A(t).split("/").slice(0, -1).join("/");
70
- if (this.source.url) return A(`${n}/${e.replace(/^package:\/\//, "")}`);
71
- throw U(`Simulation resource not found: ${e}`, "E_ASSET_RESOURCE_NOT_FOUND");
72
- }
73
- find(e, t = "") {
74
- const r = A(e.replace(/^package:\/\//, "")), n = A(t).split("/").slice(0, -1).join("/");
75
- for (const u of [A(`${n}/${e.replace(/^package:\/\//, "")}`), r])
76
- if (this.entries.has(u)) return u;
77
- const l = this.paths().filter(
78
- (u) => u === r || u.endsWith(`/${r}`) || r.endsWith(`/${u}`)
79
- );
80
- return l.length === 1 ? l[0] : null;
81
- }
82
- async text(e) {
83
- await this.ensure(e);
84
- const t = this.entries.get(this.resolve(e));
85
- if (!t) throw U(`Simulation resource not found: ${e}`, "E_ASSET_RESOURCE_NOT_FOUND");
86
- return t.text();
87
- }
88
- async bytes(e) {
89
- await this.ensure(e);
90
- const t = this.entries.get(this.resolve(e));
91
- if (!t) throw U(`Simulation resource not found: ${e}`, "E_ASSET_RESOURCE_NOT_FOUND");
92
- return new Uint8Array(await t.arrayBuffer());
93
- }
94
- getBlob(e) {
95
- const t = this.resolve(e), r = this.entries.get(t);
96
- if (!r) throw U(`Simulation resource not found: ${e}`, "E_ASSET_RESOURCE_NOT_FOUND");
97
- return r;
98
- }
99
- async ensure(e) {
100
- const t = A(e);
101
- if (this.entries.has(t)) return;
102
- const r = await this.source.resolve(t);
103
- if (!/^https?:\/\//i.test(r) && !/^blob:/i.test(r))
104
- throw U(`Simulation resource not found: ${e}. Upload the complete asset folder or provide a resourceResolver/baseUrl.`, "E_ASSET_RESOURCE_NOT_FOUND");
105
- const n = await fetch(r, { signal: this.source.signal });
106
- if (!n.ok) throw U(`Simulation resource request failed (${n.status}): ${r}`, "E_ASSET_FETCH");
107
- const l = await n.blob();
108
- this.source.signal.throwIfAborted(), this.entries.set(t, l);
109
- }
110
- objectUrl(e) {
111
- const t = this.resolve(e);
112
- let r = this.objectUrls.get(t);
113
- return r || (r = URL.createObjectURL(this.getBlob(t)), this.objectUrls.set(t, r)), r;
114
- }
115
- objectUrlIfPresent(e, t = "") {
116
- const r = A(t), n = r ? `${r}/` : "", l = A(e), u = n ? this.paths().filter((i) => {
117
- if (!i.startsWith(n)) return !1;
118
- const s = i.slice(n.length);
119
- return s === l || l.endsWith(`/${s}`);
120
- }) : [], c = u.length === 1 ? u[0] : this.find(e);
121
- return c ? this.objectUrl(c) : null;
122
- }
123
- dispose() {
124
- for (const e of this.objectUrls.values()) URL.revokeObjectURL(e);
125
- this.objectUrls.clear(), this.entries.clear();
126
- }
127
- }
128
- async function Le(o, e) {
129
- if (e.hasLocalFiles()) return e.text(o.entryPath ?? o.filename ?? e.paths()[0]);
130
- const t = await fetch(o.url ?? await o.resolve(o.entryPath ?? ""), { signal: o.signal });
131
- if (!t.ok) throw U(`Simulation asset request failed: ${t.status}`, "E_ASSET_FETCH");
132
- return t.text();
133
- }
134
- function A(o) {
135
- const e = [];
136
- for (const t of o.replaceAll("\\", "/").split("/"))
137
- !t || t === "." || (t === ".." && e.length && e.at(-1) !== ".." ? e.pop() : e.push(t));
138
- return e.join("/");
139
- }
140
- function Ie(o) {
141
- return typeof o == "object" && o !== null && "kind" in o && o.kind === "files";
142
- }
143
- function U(o, e) {
144
- return Object.assign(new Error(o), { code: e });
145
- }
146
- function we() {
147
- return { errors: [], warnings: [], approximations: [], droppedFeatures: [] };
148
- }
149
- function _e(o) {
150
- const e = Object.freeze({ schemaVersion: 1, ...o });
151
- return Ne(e), e;
152
- }
153
- function Ne(o) {
154
- if (!o.id.trim() || !o.name.trim()) throw x("Asset IR id and name are required.", "E_ASSET_IR_INVALID");
155
- if (o.source.format !== "usd" && o.links.length === 0) throw x("Asset IR requires at least one link.", "E_ASSET_IR_INVALID");
156
- const e = /* @__PURE__ */ new Set();
157
- for (const r of o.links) {
158
- if (!r.id || e.has(r.id)) throw x(`Invalid or duplicate link: ${r.id}`, "E_ASSET_IR_INVALID");
159
- e.add(r.id);
160
- }
161
- const t = /* @__PURE__ */ new Set();
162
- for (const r of o.joints) {
163
- if (!r.id || t.has(r.id) || !e.has(r.parent) || !e.has(r.child))
164
- throw x(`Invalid joint: ${r.id}`, "E_ASSET_IR_INVALID");
165
- t.add(r.id);
166
- }
167
- }
168
- function x(o, e) {
169
- return Object.assign(new Error(o), { code: e });
170
- }
171
- async function ze(o, e, t) {
172
- var i;
173
- const r = /* @__PURE__ */ new Map(), n = /* @__PURE__ */ new Set(), l = /* @__PURE__ */ new Set(), u = async (s, m) => {
174
- if (l.has(s)) throw K(`MJCF include cycle: ${s}`, "E_MJCF_INCLUDE_CYCLE");
175
- l.add(s);
176
- const b = Ve(m, s);
177
- r.set(s, b);
178
- for (const h of b.querySelectorAll("worldbody body[name]")) n.add(h.getAttribute("name"));
179
- for (const h of b.querySelectorAll("include[file]")) {
180
- const p = t.resolve(h.getAttribute("file"), s);
181
- await u(p, await t.text(p));
182
- }
183
- l.delete(s);
184
- };
185
- await u(e, o);
186
- const c = (i = r.get(e)) == null ? void 0 : i.querySelector("mujoco");
187
- if (!c || n.size === 0) throw K("MJCF requires a mujoco root and at least one named body.", "E_MJCF_PARSE");
188
- return _e({
189
- id: c.getAttribute("model") || e,
190
- name: c.getAttribute("model") || e,
191
- source: { format: "mjcf", uri: e },
192
- links: [...n].map((s) => ({ id: s, name: s, visuals: [], collisions: [] })),
193
- joints: [],
194
- diagnostics: we(),
195
- extension: { files: t, xml: o, documents: r }
196
- });
197
- }
198
- async function ke(o) {
199
- const e = o.extension.files, t = o.source.uri, r = t.split("/").slice(0, -1).join("/"), n = /* @__PURE__ */ new Map(), l = o.extension.documents;
200
- for (const [i, s] of l) {
201
- const m = s.querySelector("compiler");
202
- for (const b of s.querySelectorAll("asset [file]")) {
203
- const h = (m == null ? void 0 : m.getAttribute(b.tagName === "texture" ? "texturedir" : "meshdir")) ?? (m == null ? void 0 : m.getAttribute("assetdir")) ?? "", p = e.resolve(`${h}/${b.getAttribute("file")}`, i);
204
- await e.bytes(p);
205
- }
206
- }
207
- for (const i of xe(e.paths(), l)) {
208
- if (i === t) continue;
209
- const s = r && i.startsWith(`${r}/`) ? i.slice(r.length + 1) : i;
210
- n.set(s, await e.bytes(i));
211
- }
212
- const u = o.extension.xml;
213
- return { format: "mjcf", xml: Te(l) ? Be(u) : u, files: n };
214
- }
215
- function Te(o) {
216
- return o.size === 0 || ![...o.values()].some((t) => t.querySelector("freejoint, actuator") ? !0 : [...t.querySelectorAll("joint")].some(
217
- (r) => (r.getAttribute("type") ?? "hinge").toLowerCase() !== "fixed"
218
- )) ? !1 : ![...o.values()].some(
219
- (t) => [...t.querySelectorAll("worldbody geom")].some((r) => {
220
- var n;
221
- return ((n = r.getAttribute("type")) == null ? void 0 : n.toLowerCase()) === "plane";
222
- })
223
- );
224
- }
225
- function Be(o) {
226
- const e = '<geom name="__viewer_default_ground__" type="plane" size="5 5 0.1" contype="1" conaffinity="1" friction="0.8 0.01 0.0002"/>';
227
- return /<worldbody\b[^>]*>/i.test(o) ? o.replace(/(<worldbody\b[^>]*>)/i, `$1${e}`) : o.replace(/<\/mujoco\s*>/i, `<worldbody>${e}</worldbody></mujoco>`);
228
- }
229
- function xe(o, e) {
230
- const t = (c) => c.replaceAll("\\", "/").split("/").pop() ?? "", r = /* @__PURE__ */ new Map();
231
- for (const c of o) {
232
- const i = t(c), s = r.get(i) ?? [];
233
- s.push(c), r.set(i, s);
234
- }
235
- const n = new Set(e.keys()), l = /* @__PURE__ */ new Set(["include", "mesh", "texture", "hfield", "skin"]), u = /* @__PURE__ */ new Set(["fileleft", "fileright", "fileup", "filedown", "filefront", "fileback"]);
236
- for (const c of e.values()) {
237
- if (c.querySelector("plugin, extension, model, attach")) return o;
238
- for (const i of c.querySelectorAll("*"))
239
- for (const s of i.attributes) {
240
- if (!s.name.startsWith("file")) continue;
241
- if (s.name === "file") {
242
- if (!l.has(i.tagName)) return o;
243
- } else if (!(i.tagName === "texture" && u.has(s.name)))
244
- return o;
245
- if (!s.value) continue;
246
- const m = r.get(t(s.value));
247
- if (!m) return o;
248
- for (const b of m) n.add(b);
249
- }
250
- }
251
- return o.filter((c) => n.has(c));
252
- }
253
- function Ve(o, e) {
254
- const t = new DOMParser().parseFromString(o, "application/xml"), r = t.querySelector("parsererror");
255
- if (r) throw K(`MJCF XML parse failed (${e}): ${r.textContent ?? ""}`, "E_MJCF_PARSE");
256
- return t;
257
- }
258
- function K(o, e) {
259
- return Object.assign(new Error(o), { code: e });
260
- }
261
- const Xe = 1476466, Je = 0.72, He = 20, We = 1;
262
- function Ye() {
263
- return new Oe({
264
- color: Xe,
265
- transparent: !0,
266
- opacity: Je,
267
- depthTest: !1
268
- });
269
- }
270
- function Ze(o, e) {
271
- let t = new W(o, He);
272
- t.getAttribute("position").count === 0 && (t.dispose(), t = new W(o, We)), t.getAttribute("position").count === 0 && (t.dispose(), t = new W(o, 0));
273
- const r = new $e(t, e);
274
- return r.renderOrder = 9, r;
275
- }
276
- const de = 0.68;
277
- function Qe(o, e) {
278
- if (e < 0) return de;
279
- const t = o.mat_roughness[e];
280
- if (t >= 0) return t;
281
- const r = o.mat_shininess[e];
282
- return !Number.isFinite(r) || r <= 0 ? de : Math.sqrt(2 / (r + 2));
283
- }
284
- function Ke(o, e) {
285
- if (e < 0) return 0;
286
- const t = o.mat_metallic[e];
287
- return Number.isFinite(t) && t >= 0 ? t : 0;
288
- }
289
- function Z(o, e = !1) {
290
- const t = o.model, r = o.mujoco, n = new z();
291
- n.name = "MuJoCo scene";
292
- const l = /* @__PURE__ */ new Map(), u = /* @__PURE__ */ new Map();
293
- for (let c = 1; c < t.nbody; c += 1) {
294
- const i = r.mj_id2name(t, r.mjtObj.mjOBJ_BODY.value, c);
295
- if (!i) continue;
296
- const s = new z();
297
- s.name = i, s.userData.bodyId = c, l.set(c, s), u.set(i, s), n.add(s);
298
- }
299
- if (e && l.set(0, n), e) {
300
- const c = Ye();
301
- let i = 0;
302
- for (let s = 0; s < t.ngeom; s += 1) {
303
- if (r.mj_id2name(t, r.mjtObj.mjOBJ_GEOM.value, s) === "__viewer_default_ground__" || t.geom_contype[s] === 0 && t.geom_conaffinity[s] === 0) continue;
304
- const b = l.get(t.geom_bodyid[s]), h = et(o, s);
305
- if (!b || !h) continue;
306
- const p = Ze(h, c);
307
- h.dispose(), p.userData.geomId = s, i += 1;
308
- const f = s * 3, a = s * 4;
309
- p.position.fromArray(t.geom_pos, f), p.quaternion.set(t.geom_quat[a + 1], t.geom_quat[a + 2], t.geom_quat[a + 3], t.geom_quat[a]), b.add(p);
310
- }
311
- i === 0 && c.dispose();
312
- } else
313
- for (let c = 0; c < t.ngeom; c += 1) {
314
- if (t.geom_group[c] > 2) continue;
315
- const i = l.get(t.geom_bodyid[c]), s = tt(o, c);
316
- if (!i || !s) continue;
317
- const m = c * 4, b = t.geom_matid[c], h = new ye({
318
- opacity: t.geom_rgba[m + 3],
319
- transparent: t.geom_rgba[m + 3] < 1,
320
- roughness: Qe(t, b),
321
- metalness: Ke(t, b)
322
- });
323
- if (h.color.setRGB(t.geom_rgba[m], t.geom_rgba[m + 1], t.geom_rgba[m + 2]), b >= 0 && [0.5, 0.5, 0.5, 1].every((d, _) => t.geom_rgba[m + _] === d)) {
324
- const d = b * 4;
325
- h.color.setRGB(t.mat_rgba[d], t.mat_rgba[d + 1], t.mat_rgba[d + 2]), h.opacity = t.mat_rgba[d + 3], h.transparent = h.opacity < 1;
326
- }
327
- const p = new N(s, h), f = c * 3, a = c * 4;
328
- p.position.fromArray(t.geom_pos, f), p.quaternion.set(t.geom_quat[a + 1], t.geom_quat[a + 2], t.geom_quat[a + 3], t.geom_quat[a]), i.add(p);
329
- }
330
- return { root: n, bindings: u, expectedLinkCount: u.size };
331
- }
332
- function et(o, e) {
333
- const t = o.model, r = o.mujoco, n = e * 3, l = t.geom_size[n], u = t.geom_size[n + 1], c = t.geom_size[n + 2], i = t.geom_type[e];
334
- if (i === r.mjtGeom.mjGEOM_PLANE.value)
335
- return new Re(Math.max(l * 2, 2), Math.max(u * 2, 2), 10, 10);
336
- if (i === r.mjtGeom.mjGEOM_BOX.value) return new X(l * 2, u * 2, c * 2);
337
- if (i === r.mjtGeom.mjGEOM_SPHERE.value) return new te(l, 20, 12);
338
- if (i === r.mjtGeom.mjGEOM_CYLINDER.value) {
339
- const s = new re(l, l, u * 2, 24);
340
- return s.rotateX(Math.PI / 2), s;
341
- }
342
- if (i === r.mjtGeom.mjGEOM_CAPSULE.value) {
343
- const s = new be(l, u * 2, 6, 16);
344
- return s.rotateX(Math.PI / 2), s;
345
- }
346
- if (i === r.mjtGeom.mjGEOM_MESH.value) {
347
- const s = t.geom_dataid[e], m = t.mesh_vertadr[s], b = t.mesh_vertnum[s];
348
- t.mesh_faceadr[s], t.mesh_facenum[s];
349
- const h = [];
350
- for (let p = m; p < m + b; p++) h.push(new T(t.mesh_vert[p * 3], t.mesh_vert[p * 3 + 1], t.mesh_vert[p * 3 + 2]));
351
- return new Me(h);
352
- }
353
- return new X(Math.max(l * 2, 0.02), Math.max(u * 2, 0.02), Math.max(c * 2, 0.02));
354
- }
355
- function tt(o, e) {
356
- const t = o.model, r = o.mujoco, n = e * 3, l = t.geom_size[n], u = t.geom_size[n + 1], c = t.geom_size[n + 2], i = t.geom_type[e];
357
- if (i === r.mjtGeom.mjGEOM_BOX.value) return new X(l * 2, u * 2, c * 2);
358
- if (i === r.mjtGeom.mjGEOM_SPHERE.value) return new te(l, 24, 16);
359
- if (i === r.mjtGeom.mjGEOM_CYLINDER.value) {
360
- const a = new re(l, l, u * 2, 24);
361
- return a.rotateX(Math.PI / 2), a;
362
- }
363
- if (i === r.mjtGeom.mjGEOM_CAPSULE.value) {
364
- const a = new be(l, u * 2, 6, 16);
365
- return a.rotateX(Math.PI / 2), a;
366
- }
367
- if (i !== r.mjtGeom.mjGEOM_MESH.value) return null;
368
- const s = t.geom_dataid[e], m = t.mesh_vertadr[s], b = t.mesh_vertnum[s], h = t.mesh_faceadr[s], p = t.mesh_facenum[s], f = new Pe();
369
- return f.setAttribute("position", new ce(Float32Array.from(t.mesh_vert.subarray(m * 3, (m + b) * 3)), 3)), f.setIndex(new ce(Uint32Array.from(t.mesh_face.subarray(h * 3, (h + p) * 3)), 1)), f.computeVertexNormals(), f;
370
- }
371
- function C(o, e) {
372
- if (!o) return [...e];
373
- const t = o.trim().split(/\s+/).map(Number);
374
- if (t.some((r) => !Number.isFinite(r))) throw D(`Invalid numeric value: ${o}`, "E_URDF_PARSE");
375
- return t;
376
- }
377
- function V(o) {
378
- const e = (o == null ? void 0 : o.querySelector("origin")) ?? null;
379
- return { position: C((e == null ? void 0 : e.getAttribute("xyz")) ?? null, [0, 0, 0]), rotationRpy: C((e == null ? void 0 : e.getAttribute("rpy")) ?? null, [0, 0, 0]) };
380
- }
381
- function pe(o, e, t) {
382
- const r = o.querySelector("geometry"), n = r == null ? void 0 : r.querySelector("box");
383
- if (n) return { type: "box", size: C(n.getAttribute("size"), [1, 1, 1]) };
384
- const l = r == null ? void 0 : r.querySelector("sphere");
385
- if (l) return { type: "sphere", radius: F(l.getAttribute("radius"), 1) };
386
- const u = r == null ? void 0 : r.querySelector("cylinder");
387
- if (u) return { type: "cylinder", radius: F(u.getAttribute("radius"), 1), length: F(u.getAttribute("length"), 1) };
388
- const c = r == null ? void 0 : r.querySelector("mesh"), i = c == null ? void 0 : c.getAttribute("filename");
389
- return i ? { type: "mesh", resourcePath: t.resolve(i, e), scale: C(c.getAttribute("scale"), [1, 1, 1]) } : null;
390
- }
391
- function rt(o, e, t) {
392
- const n = lt(o, "URDF").querySelector("robot");
393
- if (!n) throw D("URDF requires a robot root element.", "E_URDF_PARSE");
394
- const l = we(), u = [...n.querySelectorAll("link")].map((i) => ({
395
- id: I(i, "name"),
396
- name: I(i, "name"),
397
- inertial: ut(i),
398
- visuals: [...i.querySelectorAll("visual")].map((s) => {
399
- var h;
400
- const m = pe(s, e, t), b = C(((h = s.querySelector("color")) == null ? void 0 : h.getAttribute("rgba")) ?? null, [0.68, 0.72, 0.7, 1]);
401
- return m ? { origin: V(s), geometry: m, color: b } : null;
402
- }).filter((s) => !!s),
403
- collisions: [...i.querySelectorAll("collision")].map((s) => {
404
- const m = pe(s, e, t);
405
- return m ? { origin: V(s), geometry: m } : null;
406
- }).filter((s) => !!s)
407
- })), c = [...n.querySelectorAll("joint")].map((i) => {
408
- var f;
409
- const s = i.querySelector("limit"), m = i.querySelector("dynamics"), b = m ? F(m.getAttribute("damping"), 0) : 0, h = m ? F(m.getAttribute("friction"), 0) : 0, p = m && (b > 0 || h > 0) ? { damping: b, friction: h } : void 0;
410
- return {
411
- id: I(i, "name"),
412
- type: i.getAttribute("type") ?? "fixed",
413
- parent: I(i.querySelector("parent"), "link"),
414
- child: I(i.querySelector("child"), "link"),
415
- origin: V(i),
416
- axis: C(((f = i.querySelector("axis")) == null ? void 0 : f.getAttribute("xyz")) ?? null, [1, 0, 0]),
417
- ...s ? { limits: { lower: F(s.getAttribute("lower"), 0), upper: F(s.getAttribute("upper"), 0) } } : {},
418
- ...p ? { dynamics: p } : {}
419
- };
420
- });
421
- return n.querySelector("transmission, gazebo") && l.droppedFeatures.push({ code: "UNSUPPORTED_URDF_EXTENSION", message: "URDF transmission/gazebo extensions are not compiled." }), _e({ id: n.getAttribute("name") || e, name: n.getAttribute("name") || e, source: { format: "urdf", uri: e }, links: u, joints: c, diagnostics: l, extension: { files: t } });
422
- }
423
- function he(o) {
424
- const e = new k(), t = new ge().setFromEuler(new J(...o.rotationRpy, "XYZ"));
425
- return e.compose(new T().fromArray(o.position), t, new T(1, 1, 1));
426
- }
427
- function ee(o) {
428
- if (o.type === "continuous" || !o.limits) return 0;
429
- const { lower: e, upper: t } = o.limits;
430
- return !Number.isFinite(e) || !Number.isFinite(t) ? 0 : Ue.clamp(0, e, t);
431
- }
432
- function ot(o) {
433
- let e;
434
- if (o.type === "box")
435
- e = [o.size[0] / 2, o.size[1] / 2, o.size[2] / 2];
436
- else if (o.type === "sphere")
437
- e = [o.radius, o.radius, o.radius];
438
- else if (o.type === "cylinder")
439
- e = [o.radius, o.radius, o.length / 2];
440
- else
441
- return null;
442
- const t = [];
443
- for (const r of [-e[0], e[0]])
444
- for (const n of [-e[1], e[1]])
445
- for (const l of [-e[2], e[2]])
446
- t.push(new T(r, n, l));
447
- return t;
448
- }
449
- function st(o, e, t) {
450
- let r = 0;
451
- const n = new Map(o.links.map((s) => [s.id, s])), l = (s) => {
452
- let m = 1 / 0;
453
- const b = (h, p) => {
454
- const f = n.get(h);
455
- if (f) {
456
- for (const a of f.collisions) {
457
- const d = ot(a.geometry);
458
- if (!d) {
459
- s && (r += 1);
460
- continue;
461
- }
462
- const _ = p.clone().multiply(he(a.origin));
463
- for (const y of d)
464
- m = Math.min(m, y.applyMatrix4(_).z);
465
- }
466
- for (const a of t.get(h) ?? []) {
467
- const d = p.clone().multiply(he(a.origin)), _ = s ? ee(a) : 0;
468
- _ && a.type === "revolute" ? d.multiply(new k().makeRotationAxis(new T().fromArray(a.axis).normalize(), _)) : _ && a.type === "prismatic" && d.multiply(new k().makeTranslation(a.axis[0] * _, a.axis[1] * _, a.axis[2] * _)), b(a.child, d);
469
- }
470
- }
471
- };
472
- return b(e, new k()), m;
473
- }, u = l(!0), c = l(!1), i = Math.min(u, c);
474
- return r && o.diagnostics.warnings.push({
475
- code: "GROUNDING_IGNORED_MESH_COLLIDERS",
476
- message: `自动落地忽略了 ${r} 个网格碰撞体`
477
- }), Number.isFinite(i) ? Math.max(0, 0.015 - i) : 0;
478
- }
479
- async function nt(o) {
480
- const e = o.extension.files, t = /* @__PURE__ */ new Map(), r = new Set(o.joints.map((a) => a.child));
481
- for (const a of o.joints) t.set(a.parent, [...t.get(a.parent) ?? [], a]);
482
- const n = o.links.filter((a) => !r.has(a.id));
483
- if (n.length !== 1) throw D(`URDF requires exactly one root link; found ${n.length}.`, "E_URDF_COMPILE");
484
- const l = st(o, n[0].id, t);
485
- l > 0 && o.diagnostics.approximations.push({
486
- code: "AUTO_GROUNDED_FREE_ROOT",
487
- message: `自由根初始高度自动抬升 ${l.toFixed(4)} m`
488
- });
489
- const u = o.joints.filter((a) => ee(a) !== 0);
490
- u.length && o.diagnostics.approximations.push({
491
- code: "JOINT_REFERENCE_CLAMPED",
492
- message: `${u.length} 个关节的默认参考值已夹到合法限位`
493
- });
494
- const c = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Map(), s = [], m = async (a) => {
495
- var g;
496
- if (a.type === "box") return `type="box" size="${a.size.map((E) => E / 2).join(" ")}"`;
497
- if (a.type === "sphere") return `type="sphere" size="${a.radius}"`;
498
- if (a.type === "cylinder") return `type="cylinder" size="${a.radius} ${a.length / 2}"`;
499
- const d = (g = a.resourcePath.split(".").pop()) == null ? void 0 : g.toLowerCase();
500
- if (d !== "stl" && d !== "obj") return null;
501
- const _ = `${a.resourcePath}|${a.scale.join(" ")}`;
502
- let y = i.get(_);
503
- if (!y) {
504
- const E = { name: `mesh_${i.size}`, path: a.resourcePath, scale: a.scale };
505
- i.set(_, E), c.set(`${E.name}.${d}`, await e.bytes(a.resourcePath)), y = E;
506
- }
507
- return `type="mesh" mesh="${y.name}"`;
508
- }, b = async (a, d) => {
509
- var E, $;
510
- const _ = o.links.find((w) => w.id === a), y = [...(d == null ? void 0 : d.origin.position) ?? [0, 0, 0]];
511
- d || (y[2] += l);
512
- const g = [`<body name="${Q(a)}" pos="${y.join(" ")}" euler="${((d == null ? void 0 : d.origin.rotationRpy) ?? [0, 0, 0]).join(" ")}">`];
513
- if (_.inertial) {
514
- const { origin: w, mass: v, tensor: S } = _.inertial, R = new fe().setFromMatrix4(new k().makeRotationFromEuler(new J(...w.rotationRpy, "XYZ"))), P = new fe().set(S[0], S[3], S[4], S[3], S[1], S[5], S[4], S[5], S[2]);
515
- P.premultiply(R).multiply(R.clone().transpose());
516
- const M = P.elements;
517
- g.push(`<inertial pos="${w.position.join(" ")}" mass="${v}" fullinertia="${[M[0], M[4], M[8], M[3], M[6], M[7]].join(" ")}"/>`);
518
- }
519
- if (!d) g.push("<freejoint/>");
520
- else if (["fixed", "planar", "floating"].includes(d.type))
521
- (d == null ? void 0 : d.type) === "floating" && (g.push("<freejoint/>"), s.push(0, 0, 0, 1, 0, 0, 0));
522
- else {
523
- const w = d.type === "prismatic" ? "slide" : "hinge", v = d.type !== "continuous" && !!d.limits && Number.isFinite(d.limits.lower) && Number.isFinite(d.limits.upper), S = ee(d);
524
- s.push(S);
525
- const R = ((E = d.dynamics) == null ? void 0 : E.damping) ?? 0, P = (($ = d.dynamics) == null ? void 0 : $.friction) ?? 0;
526
- g.push(`<joint name="${Q(d.id)}" type="${w}" axis="${d.axis.join(" ")}"${v ? ` limited="true" range="${d.limits.lower} ${d.limits.upper}" ref="${S}"` : ""} damping="${R}" frictionloss="${P}"/>`);
527
- }
528
- for (const w of _.collisions) {
529
- const v = await m(w.geometry);
530
- v && g.push(`<geom ${v} pos="${w.origin.position.join(" ")}" euler="${w.origin.rotationRpy.join(" ")}" rgba="0.55 0.62 0.59 1"/>`);
531
- }
532
- for (const w of t.get(a) ?? []) g.push(await b(w.child, w));
533
- return g.push("</body>"), g.join("");
534
- }, h = await b(n[0].id), p = [...i.values()].map((a) => {
535
- var d;
536
- return `<mesh name="${a.name}" file="${a.name}.${(d = a.path.split(".").pop()) == null ? void 0 : d.toLowerCase()}" scale="${a.scale.join(" ")}"/>`;
537
- }).join(""), f = `<keyframe><key name="home" qpos="0 0 ${l} 1 0 0 0 ${s.join(" ")}"/></keyframe>`;
538
- return {
539
- format: "mjcf",
540
- files: c,
541
- xml: `<mujoco model="${Q(o.name)}"><compiler angle="radian" autolimits="true"/><option gravity="0 0 -9.81"/><asset>${p}</asset><worldbody><geom name="__viewer_default_ground__" type="plane" size="5 5 0.1" contype="1" conaffinity="1" friction="0.8 0.01 0.0002"/>${h}</worldbody>${f}</mujoco>`
542
- };
543
- }
544
- async function it(o) {
545
- const e = o.extension.files, t = new z();
546
- t.name = o.name;
547
- const r = /* @__PURE__ */ new Map();
548
- for (const n of o.links) {
549
- const l = new z();
550
- l.name = n.id, r.set(n.id, l), t.add(l);
551
- for (const u of n.visuals) {
552
- const c = await at(u, e), i = new z();
553
- i.position.fromArray(u.origin.position), i.quaternion.setFromEuler(new J(...u.origin.rotationRpy, "XYZ")), i.add(c), l.add(i);
554
- }
555
- }
556
- return { root: t, bindings: r, expectedLinkCount: o.links.length };
557
- }
558
- async function at(o, e) {
559
- var u, c, i;
560
- const t = new ye({ color: o.color ? void 0 : 11385011, opacity: ((u = o.color) == null ? void 0 : u[3]) ?? 1, transparent: (((c = o.color) == null ? void 0 : c[3]) ?? 1) < 1 });
561
- o.color && t.color.setRGB(o.color[0], o.color[1], o.color[2]);
562
- const r = o.geometry;
563
- if (r.type === "box") return new N(new X(...r.size), t);
564
- if (r.type === "sphere") return new N(new te(r.radius, 24, 16), t);
565
- if (r.type === "cylinder") {
566
- const s = new N(new re(r.radius, r.radius, r.length, 24), t);
567
- return s.quaternion.copy(new ge().setFromEuler(new J(Math.PI / 2, 0, 0))), s;
568
- }
569
- const n = (i = r.resourcePath.split(".").pop()) == null ? void 0 : i.toLowerCase();
570
- await e.ensure(r.resourcePath);
571
- let l;
572
- if (n === "stl") l = new N(new Ge().parse(await e.getBlob(r.resourcePath).arrayBuffer()), t);
573
- else if (n === "obj")
574
- l = new qe().parse(await e.getBlob(r.resourcePath).text()), l.traverse((s) => {
575
- "material" in s && (s.material = t);
576
- });
577
- else if (n === "gltf" || n === "glb") {
578
- const s = new Fe();
579
- s.setURLModifier((m) => {
580
- try {
581
- return e.objectUrl(e.resolve(m, r.resourcePath));
582
- } catch {
583
- return m;
584
- }
585
- }), l = (await new De(s).parseAsync(await e.getBlob(r.resourcePath).arrayBuffer(), "")).scene;
586
- } else throw D(`Unsupported URDF visual mesh: .${n ?? ""}`, "E_URDF_VISUAL");
587
- return l.scale.fromArray(r.scale), l;
588
- }
589
- function lt(o, e) {
590
- const t = new DOMParser().parseFromString(o, "application/xml"), r = t.querySelector("parsererror");
591
- if (r) throw D(`${e} XML parse failed: ${r.textContent ?? ""}`, `E_${e}_PARSE`);
592
- return t;
593
- }
594
- function I(o, e) {
595
- const t = o == null ? void 0 : o.getAttribute(e);
596
- if (!t) throw D(`Missing ${e}.`, "E_URDF_PARSE");
597
- return t;
598
- }
599
- function F(o, e) {
600
- const t = Number(o);
601
- return Number.isFinite(t) ? t : e;
602
- }
603
- function Q(o) {
604
- return o.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
605
- }
606
- function D(o, e) {
607
- return Object.assign(new Error(o), { code: e });
608
- }
609
- function ut(o) {
610
- var l;
611
- const e = o.querySelector("inertial");
612
- if (!e) return;
613
- const t = e.querySelector("inertia"), r = Number((l = e.querySelector("mass")) == null ? void 0 : l.getAttribute("value")), n = ["ixx", "iyy", "izz", "ixy", "ixz", "iyz"].map((u) => Number(t == null ? void 0 : t.getAttribute(u)));
614
- if (!(r > 0) || n.some((u) => !Number.isFinite(u))) throw D("Invalid URDF inertia.", "E_URDF_PARSE");
615
- return { origin: V(e), mass: r, tensor: n };
616
- }
617
- function ct(o, e) {
618
- const t = new Ce(o);
619
- let r = null, n = null, l = null, u = null, c = null, i = !1, s = !0, m = !1, b = null, h, p = null, f = null, a = null;
620
- const d = () => {
621
- i = !0, s = !1;
622
- }, _ = (async () => {
623
- var y, g, E, $, w, v, S, R, P, M, oe, se;
624
- try {
625
- const O = e.format;
626
- if (O === "usd" || O === "usda" || O === "usdc" || O === "usdz") {
627
- (y = e.reportProgress) == null || y.call(e, "usd", "正在解析 USD 场景与物理刚体...");
628
- const j = await (await import("./usd-session-DCuV_H-Y.js")).loadUsdSimulation(o, e, t);
629
- if (i || e.signal.aborted)
630
- throw j.dispose(), Ee();
631
- p = j.asset, n = j.binding, l = j.dispose, u = j.hasPhysics ? j.step : null, c = j.reset, s = j.hasPhysics, m = j.hasPhysics, b = j.fallback ? { ...j.fallback, stage: "physics-fallback" } : null, (g = e.reportProgress) == null || g.call(e, "stage", "正在构建三维场景与环境光影..."), f = new ue(n.root, e.options.simulationTheme, j.runtime), j.runtime ? (r = j.runtime, a = new Y(r, Z(r, !0))) : a = j.collision ?? null, a && (a.root.visible = !1, f.attachAuxiliary(a.root));
632
- return;
633
- }
634
- let L = o.entryPath ?? o.filename;
635
- if (!L && O === "mjcf") {
636
- const ie = t.paths().filter((j) => j.toLowerCase().endsWith(".xml"));
637
- for (const j of ["scene.xml", "model.xml", "main.xml"]) {
638
- const ae = ie.find((le) => le.toLowerCase().endsWith(`/${j}`) || le.toLowerCase() === j);
639
- if (ae) {
640
- L = ae;
641
- break;
642
- }
643
- }
644
- }
645
- L ?? (L = O === "urdf" ? "asset.urdf" : "asset.xml"), (E = e.reportProgress) == null || E.call(e, "fetch", "正在读取模型描述与依赖资源...");
646
- const { MujocoRuntime: je } = await import("./mujoco-runtime-s85kwjo7.js");
647
- r = new je();
648
- const ne = await Le(o, t);
649
- G(i, e.signal);
650
- let B, H;
651
- O === "urdf" ? (($ = e.reportProgress) == null || $.call(e, "parse", "正在解析 URDF 结构与连杆..."), p = rt(ne, L, t), (w = e.reportProgress) == null || w.call(e, "compile", "正在编译物理碰撞体与惯性矩阵..."), B = await nt(p), G(i, e.signal), (v = e.reportProgress) == null || v.call(e, "runtime", "正在初始化物理内核..."), await r.initialize(B, e.options.mujocoBaseUrl), m = !0, G(i, e.signal), (S = e.reportProgress) == null || S.call(e, "visual", "正在构建视觉渲染网格..."), H = await it(p)) : ((R = e.reportProgress) == null || R.call(e, "parse", "正在解析 MJCF 场景与连杆..."), p = await ze(ne, L, t), (P = e.reportProgress) == null || P.call(e, "compile", "正在编译物理模型与参数..."), B = await ke(p), G(i, e.signal), (M = e.reportProgress) == null || M.call(e, "runtime", "正在初始化物理内核..."), await r.initialize(B, e.options.mujocoBaseUrl), m = !0, G(i, e.signal), (oe = e.reportProgress) == null || oe.call(e, "visual", "正在构建视觉渲染网格..."), H = Z(r)), G(i, e.signal), (se = e.reportProgress) == null || se.call(e, "stage", "正在构建三维场景与环境光影..."), n = new Y(r, H), f = new ue(n.root, e.options.simulationTheme, r), a = new Y(r, Z(r, !0)), a.root.visible = !1, f.attachAuxiliary(a.root);
652
- } catch (O) {
653
- throw f == null || f.dispose(), f = null, n == null || n.dispose(), n = null, r == null || r.dispose(), t.dispose(), O;
654
- }
655
- })();
656
- return _.catch(() => {
657
- }), {
658
- id: `simulation-${Math.random().toString(36).slice(2)}`,
659
- opened: _,
660
- get root() {
661
- return (f == null ? void 0 : f.root) ?? null;
662
- },
663
- getFitBounds() {
664
- return (f == null ? void 0 : f.getModelBounds()) ?? null;
665
- },
666
- beforeRender(y, g, E) {
667
- return f == null ? void 0 : f.beforeRender(y, g, E);
668
- },
669
- get capabilities() {
670
- return { canPlay: m, canPause: m, canReset: m, hasPhysics: m, canToggleGround: !0, canToggleCollision: a !== null };
671
- },
672
- get warning() {
673
- return b;
674
- },
675
- setTheme(y) {
676
- f == null || f.setTheme(y);
677
- },
678
- setGroundVisible(y) {
679
- f == null || f.setGroundVisible(y);
680
- },
681
- getGroundVisible() {
682
- return (f == null ? void 0 : f.getGroundVisible()) ?? !0;
683
- },
684
- presentation: { preferredViewMode: "3d", interactionMode: "simulation", uiProfile: "simulation", fitPolicy: "fit-on-ready" },
685
- beginDispose: d,
686
- setCollisionVisible(y) {
687
- if (i || !a) throw new Error("This asset has no collision display.");
688
- a.root.visible = y;
689
- },
690
- getPhysicsProperties() {
691
- if (i || !(r != null && r.model) || !r.mujoco) return null;
692
- const y = r.model, g = r.mujoco;
693
- return structuredClone({
694
- units: { length: "m", mass: "kg", time: "s" },
695
- timestep: y.opt.timestep,
696
- gravity: Array.from(y.opt.gravity),
697
- bodyCount: y.nbody - 1,
698
- jointCount: y.njnt,
699
- geomCount: y.ngeom,
700
- bodies: Array.from({ length: y.nbody - 1 }, (E, $) => {
701
- const w = $ + 1;
702
- return { id: w, name: g.mj_id2name(y, g.mjtObj.mjOBJ_BODY.value, w), mass: y.body_mass[w], inertia: Array.from(y.body_inertia.slice(w * 3, w * 3 + 3)) };
703
- }),
704
- diagnostics: p == null ? void 0 : p.diagnostics
705
- });
706
- },
707
- get update() {
708
- return r != null && r.model || u ? (y) => {
709
- if (i || !s || !n) return !1;
710
- if (u) {
711
- const E = u(y);
712
- return E && (a == null || a.sync()), E;
713
- }
714
- const g = r.step(y);
715
- return g && (n.sync(), a == null || a.sync(), f == null || f.updateForceLine()), g;
716
- } : void 0;
717
- },
718
- play() {
719
- !i && m && (s = !0);
720
- },
721
- pause() {
722
- s = !1;
723
- },
724
- reset() {
725
- i || !n || (c ? c() : (r == null || r.reset(), n.sync()), a == null || a.sync(), f == null || f.updateForceLine());
726
- },
727
- beginGrab(y, g, E) {
728
- return (f == null ? void 0 : f.beginGrab(y, g, E)) ?? !1;
729
- },
730
- moveGrab(y, g, E) {
731
- f == null || f.moveGrab(y, g, E);
732
- },
733
- endGrab() {
734
- f == null || f.endGrab();
735
- },
736
- dispose() {
737
- return d(), h ?? (h = _.catch(() => {
738
- }).then(() => {
739
- f == null || f.dispose(), f = null, a == null || a.root.removeFromParent(), a == null || a.dispose(), a = null, l ? (l(), l = null, n = null) : (n == null || n.dispose(), n = null, r == null || r.dispose()), t.dispose(), p = null, u = null, c = null, m = !1, b = null;
740
- })), h;
741
- }
742
- };
743
- }
744
- function G(o, e) {
745
- if (o || e.aborted) throw Ee();
746
- }
747
- function Ee() {
748
- return Object.assign(new Error("Simulation load aborted."), { name: "AbortError", code: "E_ABORTED" });
749
- }
750
- const gt = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
751
- __proto__: null,
752
- createSimulationSession: ct
753
- }, Symbol.toStringTag, { value: "Module" }));
754
- export {
755
- Y as S,
756
- Ze as a,
757
- we as b,
758
- Ye as c,
759
- _e as d,
760
- gt as s
761
- };