@nebula-spatial/studio 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +2 -0
  2. package/dist/assets/openusd_three_loader-DLiqJWUM.js +13769 -0
  3. package/dist/assets/usd-export-worker-BRxTLqer.js +182 -0
  4. package/dist/assets/usd-worker-DekqMsQv.js +1392 -0
  5. package/dist/{builders-BAXRR5o5.js → builders-lydx4-Rh.js} +1 -1
  6. package/dist/core/session-persistence-controller.d.ts +55 -0
  7. package/dist/doc/placement-policy.d.ts +4 -0
  8. package/dist/editor/editor.d.ts +3 -1
  9. package/dist/editor/index.d.ts +2 -0
  10. package/dist/editor/session-persistence.d.ts +54 -0
  11. package/dist/editor.js +727 -490
  12. package/dist/export-evidence-z2Ne7Trf.js +2387 -0
  13. package/dist/generalization.js +2 -2
  14. package/dist/index.d.ts +4 -2
  15. package/dist/index.js +314 -306
  16. package/dist/mjcf-visual-IOy-ucto.js +72 -0
  17. package/dist/mujoco-runtime-BYZnrvbR.js +467 -0
  18. package/dist/persist/indexeddb-store.d.ts +22 -2
  19. package/dist/persist/session.d.ts +22 -0
  20. package/dist/persist/snapshot.d.ts +24 -0
  21. package/dist/{physics-facts-tfQYyNTD.js → physics-facts-D-URIBrt.js} +8 -7
  22. package/dist/{placement-policy-DY_FNRDu.js → placement-policy-C6dV6Tf-.js} +161 -141
  23. package/dist/ports/persistence.d.ts +45 -1
  24. package/dist/project/contracts.d.ts +3 -0
  25. package/dist/remote-asset-resolver-D-UeyDMD.js +311 -0
  26. package/dist/{scene-graph-DBLKAhxa.js → scene-graph-DVOXjMmp.js} +2 -2
  27. package/dist/scene-session-PhoFXFCY.js +22006 -0
  28. package/dist/scene.js +2 -2
  29. package/dist/session-2bp8YOA4.js +963 -0
  30. package/dist/session-B3WbC7Y2.js +296 -0
  31. package/dist/session-B9kEf4xN.js +915 -0
  32. package/dist/session-DYThdzLZ.js +825 -0
  33. package/dist/studio/index.d.ts +5 -0
  34. package/dist/studio/indexeddb-persistence.d.ts +2 -0
  35. package/dist/studio/indexeddb-session-persistence.d.ts +11 -0
  36. package/dist/studio/scene-package-asset-sources.d.ts +14 -0
  37. package/dist/studio.js +1423 -1220
  38. package/dist/urdf-session-CRXL4bHf.js +1230 -0
  39. package/dist/usd-session-CTzInpNy.js +7385 -0
  40. package/dist/version.d.ts +1 -1
  41. package/dist/view/scene-session.d.ts +5 -1
  42. package/dist/wasm-module-DZn2AM1W.js +13 -0
  43. package/dist/xacro-IpPHTMYs.js +76 -0
  44. package/package.json +1 -1
  45. package/dist/asset-source-BExlEcRt.js +0 -444
  46. package/dist/assets/usd-export-worker-BsGubtAE.js +0 -1
  47. package/dist/editorial-BkAFWfbg.js +0 -83
  48. package/dist/export-evidence-B_0zRmb8.js +0 -5027
  49. package/dist/remote-asset-resolver-Cb8cfNmw.js +0 -136
  50. package/dist/scene-session-BV1HnxNh.js +0 -3506
@@ -0,0 +1,1230 @@
1
+ var We = Object.defineProperty;
2
+ var Ce = (i, e, n) => e in i ? We(i, e, { enumerable: !0, configurable: !0, writable: !0, value: n }) : i[e] = n;
3
+ var A = (i, e, n) => Ce(i, typeof e != "symbol" ? e + "" : e, n);
4
+ import { d as Ge, f as Te, g as Ve, w as ye, h as ge, p as Je } from "./session-DYThdzLZ.js";
5
+ import { b as L, j as Pe, k as be, g as Be, h as Qe, i as we, l as Xe, S as Ke, m as ve, f as Me } from "./scene-session-PhoFXFCY.js";
6
+ import { Quaternion as O, Euler as X, LoadingManager as _e, Group as q, Mesh as U, MeshLambertMaterial as Ze, MeshPhongMaterial as Re, MeshStandardMaterial as oe, TextureLoader as Ye, SRGBColorSpace as He, RepeatWrapping as et, BoxGeometry as re, SphereGeometry as ae, CylinderGeometry as De, CapsuleGeometry as qe, Matrix4 as W, Vector3 as z, MathUtils as tt, Matrix3 as Ae, Box3 as $e, AxesHelper as it, ArrowHelper as Ee, Line as nt, BufferGeometry as st, LineBasicMaterial as je, Float32BufferAttribute as ot, MeshBasicMaterial as Se, LineSegments as rt, EdgesGeometry as at } from "three";
7
+ import { GLTFLoader as lt } from "three/examples/jsm/loaders/GLTFLoader.js";
8
+ import { ColladaLoader as ct } from "three/examples/jsm/loaders/ColladaLoader.js";
9
+ import { OBJLoader as ut } from "three/examples/jsm/loaders/OBJLoader.js";
10
+ import { STLLoader as dt } from "three/examples/jsm/loaders/STLLoader.js";
11
+ import { MeshBVH as pt, acceleratedRaycast as ft } from "three-mesh-bvh";
12
+ function Le(i) {
13
+ const e = new Map(i.map((o) => [o.id, o])), n = /* @__PURE__ */ new Map(), t = /* @__PURE__ */ new Set(), s = (o) => {
14
+ throw Object.assign(new Error(`Invalid URDF mimic relationship: ${o}`), { code: "E_URDF_MIMIC" });
15
+ }, r = (o) => {
16
+ var d;
17
+ const m = n.get(o);
18
+ if (m) return m;
19
+ const u = e.get(o);
20
+ if (!u || t.has(o)) return s(o);
21
+ t.add(o);
22
+ let c = { root: o, multiplier: 1, offset: 0 };
23
+ if (u.mimic) {
24
+ const b = u.mimic;
25
+ if (![b.multiplier, b.offset].every(Number.isFinite) || !["revolute", "continuous", "prismatic"].includes(u.type) || !["revolute", "continuous", "prismatic"].includes(((d = e.get(b.joint)) == null ? void 0 : d.type) ?? "")) return s(o);
26
+ const a = r(b.joint);
27
+ if (c = { root: a.root, multiplier: b.multiplier * a.multiplier, offset: b.multiplier * a.offset + b.offset }, ![c.multiplier, c.offset].every(Number.isFinite)) return s(o);
28
+ }
29
+ return t.delete(o), n.set(o, c), c;
30
+ };
31
+ for (const o of i) r(o.id);
32
+ return n;
33
+ }
34
+ function ee(i) {
35
+ const e = Le(i), n = /* @__PURE__ */ new Map();
36
+ for (const t of i) {
37
+ const s = e.get(t.id);
38
+ if (n.has(s.root) || n.set(s.root, { lower: -1 / 0, upper: 1 / 0 }), t.type === "continuous" || !t.limits || t.limits.lower > t.limits.upper) continue;
39
+ const r = n.get(s.root);
40
+ if (s.multiplier === 0) {
41
+ if (s.offset < t.limits.lower || s.offset > t.limits.upper) throw new Error(`URDF mimic constant violates limits: ${t.id}`);
42
+ continue;
43
+ }
44
+ const o = (t.limits.lower - s.offset) / s.multiplier, m = (t.limits.upper - s.offset) / s.multiplier;
45
+ if (r.lower = Math.max(r.lower, Math.min(o, m)), r.upper = Math.min(r.upper, Math.max(o, m)), r.lower > r.upper) throw new Error(`URDF mimic limits have no feasible range: ${s.root}`);
46
+ }
47
+ return n;
48
+ }
49
+ function le(i, e = {}) {
50
+ const n = Le(i), t = ee(i);
51
+ return Object.fromEntries(i.map((s) => {
52
+ const r = n.get(s.id), o = t.get(r.root), m = Math.max(o.lower, Math.min(o.upper, e[r.root] ?? 0));
53
+ return [s.id, m * r.multiplier + r.offset];
54
+ }));
55
+ }
56
+ function K(i) {
57
+ return i.rotationQuaternion ? new O().fromArray(i.rotationQuaternion).normalize() : new O().setFromEuler(new X(i.rotationRpy[0], i.rotationRpy[1], i.rotationRpy[2], "ZYX"));
58
+ }
59
+ function mt(i) {
60
+ const e = /* @__PURE__ */ new Map(), n = (t) => {
61
+ if (!(t instanceof Ze || t instanceof Re)) return t;
62
+ const s = e.get(t);
63
+ if (s) return s;
64
+ const r = new oe({
65
+ name: t.name,
66
+ color: t.color.clone(),
67
+ emissive: t.emissive.clone(),
68
+ emissiveIntensity: t.emissiveIntensity,
69
+ map: t.map,
70
+ emissiveMap: t.emissiveMap,
71
+ normalMap: t.normalMap,
72
+ bumpMap: t.bumpMap,
73
+ bumpScale: t.bumpScale,
74
+ alphaMap: t.alphaMap,
75
+ aoMap: t.aoMap,
76
+ aoMapIntensity: t.aoMapIntensity,
77
+ lightMap: t.lightMap,
78
+ lightMapIntensity: t.lightMapIntensity,
79
+ opacity: t.opacity,
80
+ transparent: t.transparent,
81
+ alphaTest: t.alphaTest,
82
+ side: t.side,
83
+ depthWrite: t.depthWrite,
84
+ vertexColors: t.vertexColors,
85
+ flatShading: t.flatShading,
86
+ roughness: t instanceof Re ? Math.sqrt(2 / (Math.max(0, t.shininess) + 2)) : 0.5,
87
+ metalness: 0
88
+ });
89
+ return r.normalScale.copy(t.normalScale), r.normalMapType = t.normalMapType, r.userData = { ...t.userData, colladaSourceMaterial: t.type }, e.set(t, r), r;
90
+ };
91
+ i.traverse((t) => {
92
+ t instanceof U && (t.material = Array.isArray(t.material) ? t.material.map(n) : n(t.material));
93
+ });
94
+ for (const t of e.keys()) t.dispose();
95
+ }
96
+ async function ht(i, e) {
97
+ var b, a, l;
98
+ const n = await e.text(i), t = new DOMParser().parseFromString(n, "application/xml");
99
+ if (t.querySelector("parsererror") || t.documentElement.localName !== "COLLADA")
100
+ throw new Error(`Invalid URDF COLLADA document: ${i}`);
101
+ const s = ((a = (b = t.querySelector("asset > up_axis")) == null ? void 0 : b.textContent) == null ? void 0 : a.trim()) ?? "Y_UP";
102
+ if (!["X_UP", "Y_UP", "Z_UP"].includes(s)) throw new Error(`Unsupported COLLADA up-axis: ${s}`);
103
+ const r = /* @__PURE__ */ new Map();
104
+ for (const f of t.querySelectorAll("library_images image init_from")) {
105
+ const p = (l = f.textContent) == null ? void 0 : l.trim();
106
+ if (!p || p.startsWith("data:")) continue;
107
+ const y = e.resolve(p, i);
108
+ await e.ensure(y), r.set(p, e.objectUrl(y));
109
+ }
110
+ const o = new _e();
111
+ o.setURLModifier((f) => {
112
+ if (f.startsWith("data:")) return f;
113
+ const p = r.get(f);
114
+ if (!p) throw new Error(`Unresolved COLLADA image: ${f}`);
115
+ return p;
116
+ });
117
+ let m;
118
+ const u = new Promise((f) => {
119
+ m = f;
120
+ });
121
+ let c;
122
+ o.onLoad = m, o.onError = (f) => {
123
+ c = f;
124
+ }, o.itemStart("urdf-collada-parse");
125
+ const d = new q();
126
+ try {
127
+ const f = new ct(o).parse(n, "");
128
+ if (!(f != null && f.scene)) throw new Error(`COLLADA has no scene: ${i}`);
129
+ if (d.add(f.scene), s === "X_UP" ? f.scene.rotateY(-Math.PI / 2) : f.scene.rotateX(Math.PI / 2), o.itemEnd("urdf-collada-parse"), await u, c) throw new Error(`COLLADA texture failed to load: ${c}`);
130
+ let p = 0;
131
+ if (d.traverse((y) => {
132
+ y instanceof U && p++;
133
+ }), !p) throw new Error(`COLLADA has no visual meshes: ${i}`);
134
+ return mt(d), d.updateMatrixWorld(!0), d;
135
+ } catch (f) {
136
+ throw L(d), f;
137
+ }
138
+ }
139
+ function V(i, e) {
140
+ if (!i) return [...e];
141
+ const n = i.trim().split(/\s+/).map(Number);
142
+ if (n.some((t) => !Number.isFinite(t))) throw k(`Invalid numeric value: ${i}`, "E_URDF_PARSE");
143
+ return n;
144
+ }
145
+ function H(i) {
146
+ const e = (i == null ? void 0 : i.querySelector("origin")) ?? null, n = V((e == null ? void 0 : e.getAttribute("quat_xyzw")) ?? null, []);
147
+ if (n.length !== 0 && n.length !== 4) throw k("URDF origin quat_xyzw requires four values.", "E_URDF_PARSE");
148
+ if (n.length && (e != null && e.hasAttribute("rpy"))) throw k("URDF origin cannot declare both rpy and quat_xyzw.", "E_URDF_PARSE");
149
+ return {
150
+ position: V((e == null ? void 0 : e.getAttribute("xyz")) ?? null, [0, 0, 0]),
151
+ rotationRpy: V((e == null ? void 0 : e.getAttribute("rpy")) ?? null, [0, 0, 0]),
152
+ ...n.length ? { rotationQuaternion: n } : {}
153
+ };
154
+ }
155
+ function ke(i, e, n) {
156
+ const t = i.querySelector("geometry"), s = t == null ? void 0 : t.querySelector("box");
157
+ if (s) return { type: "box", size: $t(s.getAttribute("size"), 3, "box size") };
158
+ const r = t == null ? void 0 : t.querySelector("sphere");
159
+ if (r) return { type: "sphere", radius: J(r.getAttribute("radius"), "sphere radius") };
160
+ const o = t == null ? void 0 : t.querySelector("cylinder");
161
+ if (o) return { type: "cylinder", radius: J(o.getAttribute("radius"), "cylinder radius"), length: J(o.getAttribute("length"), "cylinder length") };
162
+ const m = t == null ? void 0 : t.querySelector("capsule");
163
+ if (m) return { type: "capsule", radius: J(m.getAttribute("radius"), "capsule radius"), length: J(m.getAttribute("length"), "capsule length") };
164
+ const u = t == null ? void 0 : t.querySelector("mesh"), c = u == null ? void 0 : u.getAttribute("filename");
165
+ return c ? { type: "mesh", resourcePath: n.resolve(c, e), scale: V(u.getAttribute("scale"), [1, 1, 1]) } : null;
166
+ }
167
+ function yt(i, e, n) {
168
+ const s = At(i, "URDF").querySelector("robot");
169
+ if (!s) throw k("URDF requires a robot root element.", "E_URDF_PARSE");
170
+ const r = Te(), o = /* @__PURE__ */ new Map();
171
+ for (const c of s.children) if (c.tagName === "material" && c.getAttribute("name")) {
172
+ const d = c.getAttribute("name");
173
+ if (o.has(d)) throw k(`Duplicate URDF material: ${d}`, "E_URDF_MATERIAL");
174
+ o.set(d, c);
175
+ }
176
+ const m = [...s.querySelectorAll("link")].map((c) => ({
177
+ id: _(c, "name"),
178
+ name: _(c, "name"),
179
+ inertial: (() => {
180
+ const d = Et(c);
181
+ return d && (!(d.mass > 0) || !Number.isFinite(d.mass) || !Pe(d.tensor)) && r.errors.push({ code: "E_URDF_INERTIA", message: `连杆 ${c.getAttribute("name")} 的质量或惯性张量无效。`, source: c.getAttribute("name") ?? void 0 }), d;
182
+ })(),
183
+ visuals: [...c.querySelectorAll("visual")].map((d) => {
184
+ const b = ke(d, e, n), a = d.querySelector("material"), l = a == null ? void 0 : a.getAttribute("name"), f = l ? o.get(l) : void 0, p = (a == null ? void 0 : a.querySelector("color")) ?? (f == null ? void 0 : f.querySelector("color")), y = (a == null ? void 0 : a.querySelector("texture")) ?? (f == null ? void 0 : f.querySelector("texture"));
185
+ l && !f && !p && !y && r.warnings.push({ code: "URDF_MATERIAL_UNRESOLVED", message: `Undefined material: ${l}`, source: c.getAttribute("name") ?? void 0 });
186
+ const h = p ? (p.getAttribute("rgba") ?? "").trim().split(/\s+/).map(Number) : y ? [1, 1, 1, 1] : void 0;
187
+ if (h && (h.length !== 4 || h.some((M) => !Number.isFinite(M) || M < 0 || M > 1))) throw k(`Invalid URDF material RGBA: ${l ?? ""}`, "E_URDF_MATERIAL");
188
+ const w = y == null ? void 0 : y.getAttribute("filename");
189
+ if (y && !w) throw k("URDF texture requires a filename", "E_URDF_MATERIAL");
190
+ const g = w ? n.resolve(w, e) : void 0;
191
+ return b ? { origin: H(d), geometry: b, color: h, texturePath: g } : null;
192
+ }).filter((d) => !!d),
193
+ collisions: [...c.querySelectorAll("collision")].map((d) => {
194
+ const b = ke(d, e, n);
195
+ return b ? { origin: H(d), geometry: b } : null;
196
+ }).filter((d) => !!d)
197
+ })), u = [...s.querySelectorAll("joint")].map((c) => {
198
+ var h;
199
+ const d = c.querySelector("limit"), b = c.querySelector("mimic"), a = b ? { joint: _(b, "joint"), multiplier: Y(b.getAttribute("multiplier"), "mimic multiplier") ?? 1, offset: Y(b.getAttribute("offset"), "mimic offset") ?? 0 } : void 0, l = c.querySelector("dynamics"), f = l ? Ue(l.getAttribute("damping"), 0) : 0, p = l ? Ue(l.getAttribute("friction"), 0) : 0, y = l && (f > 0 || p > 0) ? { damping: f, friction: p } : void 0;
200
+ return {
201
+ id: _(c, "name"),
202
+ type: c.getAttribute("type") ?? "fixed",
203
+ parent: _(c.querySelector("parent"), "link"),
204
+ child: _(c.querySelector("child"), "link"),
205
+ origin: H(c),
206
+ axis: V(((h = c.querySelector("axis")) == null ? void 0 : h.getAttribute("xyz")) ?? null, [1, 0, 0]),
207
+ ...d ? {
208
+ limits: { lower: se(d.getAttribute("lower"), `Joint ${_(c, "name")} limit lower`), upper: se(d.getAttribute("upper"), `Joint ${_(c, "name")} limit upper`) },
209
+ effort: Y(d.getAttribute("effort"), `Joint ${_(c, "name")} limit effort`),
210
+ velocity: Y(d.getAttribute("velocity"), `Joint ${_(c, "name")} limit velocity`)
211
+ } : {},
212
+ ...y ? { dynamics: y } : {},
213
+ ...a ? { mimic: a } : {}
214
+ };
215
+ });
216
+ return ee(u), s.querySelector("transmission, gazebo") && r.droppedFeatures.push({ code: "UNSUPPORTED_URDF_EXTENSION", message: "URDF transmission/gazebo extensions are not compiled." }), Ge({ id: s.getAttribute("name") || e, name: s.getAttribute("name") || e, source: { format: "urdf", uri: e }, links: m, joints: u, diagnostics: r, extension: { files: n } }, { allowInvalidGraph: !0 });
217
+ }
218
+ function xe(i) {
219
+ const e = K(i);
220
+ return `quat="${e.w} ${e.x} ${e.y} ${e.z}"`;
221
+ }
222
+ function ie(i) {
223
+ const e = new W(), n = K(i);
224
+ return e.compose(new z().fromArray(i.position), n, new z(1, 1, 1));
225
+ }
226
+ function gt(i) {
227
+ if (i.type === "continuous" || !i.limits) return 0;
228
+ const { lower: e, upper: n } = i.limits;
229
+ return !Number.isFinite(e) || !Number.isFinite(n) ? 0 : tt.clamp(0, e, n);
230
+ }
231
+ function bt(i) {
232
+ let e;
233
+ if (i.type === "box")
234
+ e = [i.size[0] / 2, i.size[1] / 2, i.size[2] / 2];
235
+ else if (i.type === "sphere")
236
+ e = [i.radius, i.radius, i.radius];
237
+ else if (i.type === "cylinder")
238
+ e = [i.radius, i.radius, i.length / 2];
239
+ else
240
+ return null;
241
+ const n = [];
242
+ for (const t of [-e[0], e[0]])
243
+ for (const s of [-e[1], e[1]])
244
+ for (const r of [-e[2], e[2]])
245
+ n.push(new z(t, s, r));
246
+ return n;
247
+ }
248
+ function Ie(i, e, n) {
249
+ let t = 0;
250
+ const s = new Map(i.links.map((d) => [d.id, d])), r = le(i.joints), o = (d) => {
251
+ let b = 1 / 0;
252
+ const a = (l, f) => {
253
+ const p = s.get(l);
254
+ if (p) {
255
+ for (const y of p.collisions) {
256
+ const h = bt(y.geometry);
257
+ if (!h) {
258
+ d && (t += 1);
259
+ continue;
260
+ }
261
+ const w = f.clone().multiply(ie(y.origin));
262
+ for (const g of h)
263
+ b = Math.min(b, g.applyMatrix4(w).z);
264
+ }
265
+ for (const y of n.get(l) ?? []) {
266
+ const h = f.clone().multiply(ie(y.origin)), w = d ? r[y.id] : 0;
267
+ w && y.type === "revolute" ? h.multiply(new W().makeRotationAxis(new z().fromArray(y.axis).normalize(), w)) : w && y.type === "prismatic" && h.multiply(new W().makeTranslation(y.axis[0] * w, y.axis[1] * w, y.axis[2] * w)), a(y.child, h);
268
+ }
269
+ }
270
+ };
271
+ return a(e, new W()), b;
272
+ }, m = o(!0), u = o(!1), c = Math.min(m, u);
273
+ return t && i.diagnostics.warnings.push({
274
+ code: "GROUNDING_IGNORED_MESH_COLLIDERS",
275
+ message: `自动落地忽略了 ${t} 个网格碰撞体`
276
+ }), Number.isFinite(c) ? Math.max(0, 0.015 - c) : 0;
277
+ }
278
+ async function wt(i) {
279
+ const e = i.extension.files, n = /* @__PURE__ */ new Map(), t = new Set(i.joints.map((h) => h.child));
280
+ for (const h of i.joints) n.set(h.parent, [...n.get(h.parent) ?? [], h]);
281
+ const s = i.links.filter((h) => !t.has(h.id));
282
+ if (s.length !== 1) throw k(`URDF requires exactly one root link; found ${s.length}.`, "E_URDF_COMPILE");
283
+ const r = Ie(i, s[0].id, n);
284
+ r > 0 && i.diagnostics.approximations.push({
285
+ code: "AUTO_GROUNDED_FREE_ROOT",
286
+ message: `自由根初始高度自动抬升 ${r.toFixed(4)} m`
287
+ });
288
+ const o = i.joints.filter((h) => gt(h) !== 0);
289
+ o.length && i.diagnostics.approximations.push({
290
+ code: "JOINT_REFERENCE_CLAMPED",
291
+ message: `${o.length} 个关节的默认参考值已夹到合法限位`
292
+ });
293
+ const m = /* @__PURE__ */ new Map(), u = /* @__PURE__ */ new Map(), c = [], d = le(i.joints), b = async (h) => {
294
+ var j;
295
+ if (h.type === "box") return `type="box" size="${h.size.map((E) => E / 2).join(" ")}"`;
296
+ if (h.type === "sphere") return `type="sphere" size="${h.radius}"`;
297
+ if (h.type === "cylinder") return `type="cylinder" size="${h.radius} ${h.length / 2}"`;
298
+ if (h.type === "capsule") return `type="capsule" size="${h.radius} ${h.length / 2}"`;
299
+ const w = (j = h.resourcePath.split(".").pop()) == null ? void 0 : j.toLowerCase();
300
+ if (w !== "stl" && w !== "obj") return null;
301
+ const g = `${h.resourcePath}|${h.scale.join(" ")}`;
302
+ let M = u.get(g);
303
+ if (!M) {
304
+ const E = { name: `mesh_${u.size}`, path: h.resourcePath, scale: h.scale };
305
+ u.set(g, E);
306
+ const R = await e.bytes(h.resourcePath);
307
+ m.set(`${E.name}.${w}`, R), M = E;
308
+ }
309
+ return `type="mesh" mesh="${M.name}"`;
310
+ }, a = async (h, w) => {
311
+ var R, I;
312
+ const g = i.links.find((x) => x.id === h), M = [...(w == null ? void 0 : w.origin.position) ?? [0, 0, 0]];
313
+ w || (M[2] += r);
314
+ const j = (w == null ? void 0 : w.origin) ?? { rotationRpy: [0, 0, 0] }, E = [`<body name="${T(h)}" pos="${M.join(" ")}" ${xe(j)}>`];
315
+ if (g.inertial) {
316
+ const { origin: x, mass: $, tensor: F } = g.inertial, C = new Ae().setFromMatrix4(new W().makeRotationFromQuaternion(K(x))), N = new Ae().set(F[0], F[3], F[4], F[3], F[1], F[5], F[4], F[5], F[2]);
317
+ N.premultiply(C).multiply(C.clone().transpose());
318
+ const D = N.elements;
319
+ E.push(`<inertial pos="${x.position.join(" ")}" mass="${$}" fullinertia="${[D[0], D[4], D[8], D[3], D[6], D[7]].join(" ")}"/>`);
320
+ }
321
+ if (!w) E.push("<freejoint/>");
322
+ else if (["fixed", "planar", "floating"].includes(w.type))
323
+ (w == null ? void 0 : w.type) === "floating" && (E.push("<freejoint/>"), c.push(0, 0, 0, 1, 0, 0, 0));
324
+ else {
325
+ const x = w.type === "prismatic" ? "slide" : "hinge", $ = w.type !== "continuous" && !!w.limits && Number.isFinite(w.limits.lower) && Number.isFinite(w.limits.upper), F = d[w.id];
326
+ c.push(F);
327
+ const C = ((R = w.dynamics) == null ? void 0 : R.damping) ?? 0, N = ((I = w.dynamics) == null ? void 0 : I.friction) ?? 0;
328
+ E.push(`<joint name="${T(w.id)}" type="${x}" axis="${w.axis.join(" ")}"${$ ? ` limited="true" range="${w.limits.lower} ${w.limits.upper}" ref="0"` : ""} damping="${C}" frictionloss="${N}"/>`);
329
+ }
330
+ for (const x of g.collisions) {
331
+ const $ = await b(x.geometry);
332
+ if ($) {
333
+ const F = ` ${xe(x.origin)}`;
334
+ E.push(`<geom ${$} pos="${x.origin.position.join(" ")}"${F} rgba="0.55 0.62 0.59 1"/>`);
335
+ }
336
+ }
337
+ for (const x of n.get(h) ?? []) E.push(await a(x.child, x));
338
+ return E.push("</body>"), E.join("");
339
+ }, l = await a(s[0].id), f = [...u.values()].map((h) => {
340
+ var w;
341
+ return `<mesh name="${h.name}" file="${h.name}.${(w = h.path.split(".").pop()) == null ? void 0 : w.toLowerCase()}" scale="${h.scale.join(" ")}"/>`;
342
+ }).join(""), p = `<keyframe><key name="home" qpos="0 0 ${r} 1 0 0 0 ${c.join(" ")}"/></keyframe>`, y = i.joints.filter((h) => h.mimic).map((h) => {
343
+ const w = h.mimic;
344
+ return `<joint name="mimic_${T(h.id)}" joint1="${T(h.id)}" joint2="${T(w.joint)}" polycoef="${w.offset} ${w.multiplier} 0 0 0"/>`;
345
+ }).join("");
346
+ return {
347
+ format: "mjcf",
348
+ files: m,
349
+ xml: `<mujoco model="${T(i.name)}"><compiler angle="radian" autolimits="true"/><option gravity="0 0 -9.81"/><asset>${f}</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"/>${l}</worldbody>${y ? `<equality>${y}</equality>` : ""}${p}</mujoco>`
350
+ };
351
+ }
352
+ async function Ne(i) {
353
+ const e = i.extension.files, n = new q();
354
+ n.name = "URDF authored collisions";
355
+ const t = /* @__PURE__ */ new Map(), s = Be(), r = Qe();
356
+ let o = 0;
357
+ for (const m of i.links) {
358
+ const u = new q();
359
+ u.name = m.id, u.userData.urdfEntityId = `link:${m.id}`, t.set(m.id, u), n.add(u);
360
+ for (const c of m.collisions) {
361
+ const d = new q();
362
+ if (d.matrixAutoUpdate = !1, d.matrix.copy(ie(c.origin)), u.add(d), c.geometry.type === "mesh") {
363
+ const b = await ne(c.geometry, e, new oe());
364
+ b.updateMatrixWorld(!0), b.traverse((a) => {
365
+ if (!(a instanceof U)) return;
366
+ const l = we(a.geometry, s, "mesh", r);
367
+ l.matrixAutoUpdate = !1, l.matrix.copy(a.matrixWorld), l.name = `Collision:${m.id}`, l.userData.urdfLink = m.id, d.add(l), o += 1;
368
+ }), L(b);
369
+ } else {
370
+ const b = Mt(c.geometry);
371
+ if (!b) continue;
372
+ const a = we(b, s, "feature", r);
373
+ b.dispose(), a.name = `Collision:${m.id}`, a.userData.urdfLink = m.id, d.add(a), o += 1;
374
+ }
375
+ }
376
+ }
377
+ if (o === 0) {
378
+ s.dispose(), r.dispose(), L(n);
379
+ return;
380
+ }
381
+ return { root: n, bindings: t, expectedLinkCount: t.size };
382
+ }
383
+ async function vt(i, e) {
384
+ const n = await Ne(i);
385
+ if (!n) return;
386
+ const t = () => {
387
+ e.root.updateMatrixWorld(!0);
388
+ for (const [s, r] of n.bindings) {
389
+ const o = e.bindings.get(s);
390
+ o && (r.matrixAutoUpdate = !1, r.matrix.copy(o.matrixWorld));
391
+ }
392
+ n.root.updateMatrixWorld(!0);
393
+ };
394
+ return t(), n.root.visible = !1, { root: n.root, sync: t, dispose() {
395
+ L(n.root);
396
+ } };
397
+ }
398
+ function Mt(i) {
399
+ if (i.type === "box") return new re(...i.size);
400
+ if (i.type === "sphere") return new ae(i.radius, 24, 16);
401
+ if (i.type === "cylinder") {
402
+ const e = new De(i.radius, i.radius, i.length, 24);
403
+ return e.rotateX(Math.PI / 2), e;
404
+ }
405
+ if (i.type === "capsule") {
406
+ const e = new qe(i.radius, i.length, 8, 24);
407
+ return e.rotateX(Math.PI / 2), e;
408
+ }
409
+ return null;
410
+ }
411
+ async function Fe(i) {
412
+ const e = i.extension.files, n = new q();
413
+ n.name = i.name;
414
+ const t = /* @__PURE__ */ new Map();
415
+ try {
416
+ for (const s of i.links) {
417
+ const r = new q();
418
+ r.name = s.id, r.userData.urdfEntityId = `link:${s.id}`, t.set(s.id, r), n.add(r);
419
+ for (const o of s.visuals) {
420
+ const m = await Rt(o, e, i.diagnostics), u = new q();
421
+ u.position.fromArray(o.origin.position), u.quaternion.copy(K(o.origin)), u.add(m), r.add(u);
422
+ }
423
+ }
424
+ return { root: n, bindings: t, expectedLinkCount: i.links.length };
425
+ } catch (s) {
426
+ throw L(n), s;
427
+ }
428
+ }
429
+ async function Rt(i, e, n) {
430
+ var r;
431
+ if (i.geometry.type === "mesh" && /\.gl(?:tf|b)$/i.test(i.geometry.resourcePath)) {
432
+ (i.color || i.texturePath) && n.warnings.push({ code: "URDF_EMBEDDED_MATERIAL_PRESERVED", message: "Embedded glTF materials take precedence over the URDF visual material.", source: i.geometry.resourcePath });
433
+ const o = be();
434
+ try {
435
+ return await ne(i.geometry, e, o);
436
+ } finally {
437
+ o.dispose();
438
+ }
439
+ }
440
+ const t = be({ color: i.color });
441
+ let s;
442
+ try {
443
+ if (i.texturePath && (await e.ensure(i.texturePath), t.map = await new Ye().loadAsync(e.objectUrl(i.texturePath)), t.transparent = !0, t.map.colorSpace = He, t.map.wrapS = t.map.wrapT = et), s = await ne(i.geometry, e, t), i.geometry.type === "mesh" && /\.dae$/i.test(i.geometry.resourcePath))
444
+ if (i.color || i.texturePath) {
445
+ const o = /* @__PURE__ */ new Set(), m = /* @__PURE__ */ new Set();
446
+ s.traverse((u) => {
447
+ if (u instanceof U) {
448
+ for (const c of Array.isArray(u.material) ? u.material : [u.material]) o.add(c);
449
+ u.material = t;
450
+ }
451
+ });
452
+ for (const u of o) {
453
+ for (const c of Object.values(u)) c != null && c.isTexture && m.add(c);
454
+ u.dispose();
455
+ }
456
+ for (const u of m) u.dispose();
457
+ } else t.dispose();
458
+ return t.map && s.traverse((o) => {
459
+ if (o instanceof U && !o.geometry.getAttribute("uv")) throw k(`URDF texture requires authored UVs: ${i.texturePath}`, "E_URDF_TEXTURE_UV");
460
+ }), s;
461
+ } catch (o) {
462
+ throw s ? L(s) : ((r = t.map) == null || r.dispose(), t.dispose()), o;
463
+ }
464
+ }
465
+ async function ne(i, e, n) {
466
+ var r;
467
+ if (i.type === "box") return new U(new re(...i.size), n);
468
+ if (i.type === "sphere") return new U(new ae(i.radius, 24, 16), n);
469
+ if (i.type === "cylinder") {
470
+ const o = new U(new De(i.radius, i.radius, i.length, 24), n);
471
+ return o.quaternion.copy(new O().setFromEuler(new X(Math.PI / 2, 0, 0))), o;
472
+ }
473
+ if (i.type === "capsule") {
474
+ const o = new U(new qe(i.radius, i.length, 8, 24), n);
475
+ return o.quaternion.copy(new O().setFromEuler(new X(Math.PI / 2, 0, 0))), o;
476
+ }
477
+ const t = (r = i.resourcePath.split(".").pop()) == null ? void 0 : r.toLowerCase();
478
+ await e.ensure(i.resourcePath);
479
+ let s;
480
+ if (t === "stl") s = new U(new dt().parse(await e.getBlob(i.resourcePath).arrayBuffer()), n);
481
+ else if (t === "obj")
482
+ s = new ut().parse(await e.getBlob(i.resourcePath).text()), s.traverse((o) => {
483
+ if (o instanceof U) {
484
+ for (const m of Array.isArray(o.material) ? o.material : [o.material]) m.dispose();
485
+ o.material = n;
486
+ }
487
+ });
488
+ else if (t === "gltf" || t === "glb") {
489
+ const o = new _e();
490
+ o.setURLModifier((m) => {
491
+ try {
492
+ return e.objectUrl(e.resolve(m, i.resourcePath));
493
+ } catch {
494
+ return m;
495
+ }
496
+ }), s = (await new lt(o).parseAsync(await e.getBlob(i.resourcePath).arrayBuffer(), "")).scene;
497
+ } else if (t === "dae") s = await ht(i.resourcePath, e);
498
+ else throw k(`Unsupported URDF visual mesh: .${t ?? ""}`, "E_URDF_VISUAL");
499
+ return s.scale.fromArray(i.scale), s;
500
+ }
501
+ function At(i, e) {
502
+ const n = new DOMParser().parseFromString(i, "application/xml"), t = n.querySelector("parsererror");
503
+ if (t) throw k(`${e} XML parse failed: ${t.textContent ?? ""}`, `E_${e}_PARSE`);
504
+ return n;
505
+ }
506
+ function _(i, e) {
507
+ const n = i == null ? void 0 : i.getAttribute(e);
508
+ if (!n) throw k(`Missing ${e}.`, "E_URDF_PARSE");
509
+ return n;
510
+ }
511
+ function Ue(i, e) {
512
+ const n = Number(i);
513
+ return Number.isFinite(n) ? n : e;
514
+ }
515
+ function se(i, e) {
516
+ if (i === null || i.trim() === "") throw k(`${e} is required.`, "E_URDF_PARSE");
517
+ const n = Number(i);
518
+ if (!Number.isFinite(n)) throw k(`${e} must be finite.`, "E_URDF_PARSE");
519
+ return n;
520
+ }
521
+ function J(i, e) {
522
+ const n = se(i, e);
523
+ if (!(n > 0)) throw k(`${e} must be greater than zero.`, "E_URDF_PARSE");
524
+ return n;
525
+ }
526
+ function $t(i, e, n) {
527
+ if (i === null || i.trim() === "") throw k(`${n} is required.`, "E_URDF_PARSE");
528
+ const t = V(i, []);
529
+ if (t.length !== e || t.some((s) => !(s > 0))) throw k(`${n} requires ${e} values greater than zero.`, "E_URDF_PARSE");
530
+ return t;
531
+ }
532
+ function Y(i, e) {
533
+ if (i === null || i.trim() === "") return;
534
+ const n = Number(i);
535
+ if (!Number.isFinite(n)) throw k(`${e} must be finite.`, "E_URDF_PARSE");
536
+ return n;
537
+ }
538
+ function T(i) {
539
+ return i.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
540
+ }
541
+ function k(i, e) {
542
+ return Object.assign(new Error(i), { code: e });
543
+ }
544
+ function Et(i) {
545
+ var o;
546
+ const e = i.querySelector("inertial");
547
+ if (!e) return;
548
+ const n = e.querySelector("inertia"), t = (o = e.querySelector("mass")) == null ? void 0 : o.getAttribute("value"), s = t == null || t.trim() === "" ? Number.NaN : Number(t), r = ["ixx", "iyy", "izz", "ixy", "ixz", "iyz"].map((m) => {
549
+ const u = n == null ? void 0 : n.getAttribute(m);
550
+ return u == null || u.trim() === "" ? Number.NaN : Number(u);
551
+ });
552
+ return { origin: H(e), mass: s, tensor: r };
553
+ }
554
+ function te(i) {
555
+ return i.type === "continuous" || !i.limits ? 0 : Math.max(i.limits.lower, Math.min(i.limits.upper, 0));
556
+ }
557
+ class jt {
558
+ constructor(e, n) {
559
+ A(this, "root");
560
+ A(this, "visual");
561
+ A(this, "joints", /* @__PURE__ */ new Map());
562
+ A(this, "values", /* @__PURE__ */ new Map());
563
+ A(this, "specs", /* @__PURE__ */ new Map());
564
+ A(this, "pickMeshes", []);
565
+ A(this, "disposed", !1);
566
+ A(this, "initialRoots", /* @__PURE__ */ new Map());
567
+ this.visual = n, this.root = n.root;
568
+ const t = new Set(e.links.map((l) => l.id)), s = e.joints.filter((l) => t.has(l.parent) && t.has(l.child) && l.parent !== l.child), r = new Set(s.map((l) => l.child)), o = e.links.filter((l) => !r.has(l.id)), m = /* @__PURE__ */ new Map(), u = /* @__PURE__ */ new Set();
569
+ for (const l of s)
570
+ u.has(l.child) || (u.add(l.child), m.set(l.parent, [...m.get(l.parent) ?? [], l]));
571
+ const c = /* @__PURE__ */ new Set(), d = /* @__PURE__ */ new Set(), b = (l) => {
572
+ if (d.has(l)) return;
573
+ d.add(l), c.add(l);
574
+ const f = n.bindings.get(l);
575
+ if (!f) {
576
+ d.delete(l);
577
+ return;
578
+ }
579
+ for (const p of m.get(l) ?? []) {
580
+ if (d.has(p.child) || c.has(p.child)) continue;
581
+ const y = n.bindings.get(p.child);
582
+ if (!y) continue;
583
+ f.add(y);
584
+ const h = {
585
+ joint: p,
586
+ child: y,
587
+ originPosition: new z().fromArray(p.origin.position),
588
+ originQuaternion: K(p.origin),
589
+ axis: new z().fromArray(p.axis).normalize()
590
+ };
591
+ this.joints.set(p.id, h), this.specs.set(p.id, p), this.values.set(p.id, te(p)), this.apply(h, this.values.get(p.id)), b(p.child);
592
+ }
593
+ d.delete(l);
594
+ }, a = o.length ? o : e.links;
595
+ for (const l of a) {
596
+ if (c.has(l.id)) continue;
597
+ const f = n.bindings.get(l.id);
598
+ f && (this.root.add(f), b(l.id));
599
+ }
600
+ for (const l of e.links) {
601
+ if (c.has(l.id)) continue;
602
+ const f = n.bindings.get(l.id);
603
+ f && (this.root.add(f), b(l.id));
604
+ }
605
+ if (o.length === 1) {
606
+ const l = Ie(e, o[0].id, m), f = n.bindings.get(o[0].id);
607
+ f && l > 0 && (f.position.z += l);
608
+ }
609
+ for (const l of n.bindings.values()) l.parent === this.root && this.initialRoots.set(l, { position: l.position.clone(), quaternion: l.quaternion.clone() });
610
+ this.applyAll(), this.preparePicking(), this.root.updateMatrixWorld(!0);
611
+ }
612
+ pickRoots() {
613
+ return this.pickMeshes;
614
+ }
615
+ value(e) {
616
+ return this.values.get(e);
617
+ }
618
+ valuesSnapshot() {
619
+ return Object.freeze(Object.fromEntries(this.values));
620
+ }
621
+ setJointValue(e, n) {
622
+ if (this.disposed) throw B("URDF kinematic binding has been disposed.", "E_URDF_INACTIVE");
623
+ const t = this.joints.get(e);
624
+ if (!t) throw B(`Unknown URDF joint: ${e}`, "E_URDF_JOINT_UNKNOWN");
625
+ if (!Number.isFinite(n)) throw B(`Joint value must be finite: ${e}`, "E_URDF_JOINT_VALUE");
626
+ let s = n;
627
+ if (t.joint.type !== "continuous" && t.joint.limits && (s = Math.max(t.joint.limits.lower, Math.min(t.joint.limits.upper, n))), ["revolute", "continuous", "prismatic"].includes(t.joint.type) || (s = 0), t.joint.mimic) throw B(`Mimic joint is controlled by ${t.joint.mimic.joint}: ${e}`, "E_URDF_MIMIC_READONLY");
628
+ const r = ee([...this.specs.values()]).get(e);
629
+ return r && (s = Math.max(r.lower, Math.min(r.upper, s))), this.values.set(e, s), this.applyAll(), this.root.updateMatrixWorld(!0), s;
630
+ }
631
+ resetJoint(e) {
632
+ const n = this.joints.get(e);
633
+ if (!n) throw B(`Unknown URDF joint: ${e}`, "E_URDF_JOINT_UNKNOWN");
634
+ this.setJointValue(e, te(n.joint));
635
+ }
636
+ syncPhysicsPose(e, n) {
637
+ for (const [t, s] of Object.entries(e)) {
638
+ const r = this.joints.get(t);
639
+ r && Number.isFinite(s) && (this.values.set(t, s), this.apply(r, s));
640
+ }
641
+ for (const t of this.initialRoots.keys()) {
642
+ const s = n.get(t.name);
643
+ s && (t.position.copy(s.position), t.quaternion.copy(s.quaternion));
644
+ }
645
+ this.root.updateMatrixWorld(!0);
646
+ }
647
+ resetPose() {
648
+ for (const [e, n] of this.initialRoots)
649
+ e.position.copy(n.position), e.quaternion.copy(n.quaternion);
650
+ for (const e of this.joints.values()) {
651
+ const n = te(e.joint);
652
+ e.joint.mimic || this.values.set(e.joint.id, n);
653
+ }
654
+ this.applyAll(), this.root.updateMatrixWorld(!0);
655
+ }
656
+ objectForEntity(e) {
657
+ var n;
658
+ return e.startsWith("link:") ? this.visual.bindings.get(e.slice(5)) ?? null : e.startsWith("joint:") ? ((n = this.joints.get(e.slice(6))) == null ? void 0 : n.child) ?? null : e.startsWith("robot:") ? this.root : null;
659
+ }
660
+ jointWorldFrame(e) {
661
+ const n = this.joints.get(e);
662
+ if (!n) return null;
663
+ const t = n.child.parent;
664
+ if (!t) return null;
665
+ t.updateMatrixWorld(!0);
666
+ const s = n.originPosition.clone().applyMatrix4(t.matrixWorld), r = t.getWorldQuaternion(new O()).multiply(n.originQuaternion);
667
+ return { position: s, quaternion: r, axis: n.axis.clone().applyQuaternion(r).normalize() };
668
+ }
669
+ dispose() {
670
+ if (!this.disposed) {
671
+ this.disposed = !0, this.joints.clear(), this.values.clear(), this.specs.clear();
672
+ for (const e of this.pickMeshes) {
673
+ const n = e.geometry;
674
+ delete n.boundsTree;
675
+ }
676
+ this.pickMeshes.length = 0, L(this.root);
677
+ }
678
+ }
679
+ applyAll() {
680
+ const e = le([...this.specs.values()], Object.fromEntries(this.values));
681
+ for (const [n, t] of this.joints)
682
+ this.values.set(n, e[n]), this.apply(t, e[n]);
683
+ }
684
+ preparePicking() {
685
+ const e = /* @__PURE__ */ new Set();
686
+ this.root.traverse((n) => {
687
+ if (!(n instanceof U) || !n.geometry) return;
688
+ const t = n.geometry;
689
+ !t.boundsTree && !e.has(t) && (t.boundsTree = new pt(t, { maxLeafSize: 20, indirect: !0, verbose: !1 }), e.add(t)), n.raycast = ft, this.pickMeshes.push(n);
690
+ });
691
+ }
692
+ apply(e, n) {
693
+ e.child.position.copy(e.originPosition), e.child.quaternion.copy(e.originQuaternion), e.joint.type === "revolute" || e.joint.type === "continuous" ? e.child.quaternion.multiply(new O().setFromAxisAngle(e.axis, n)) : e.joint.type === "prismatic" && e.child.position.addScaledVector(e.axis, n);
694
+ }
695
+ }
696
+ function B(i, e) {
697
+ return Object.assign(new Error(i), { code: e });
698
+ }
699
+ function St(i, e, n = i.source.uri) {
700
+ var w;
701
+ const t = Ut(e, n), s = new Set(i.links.map((g) => g.id)), r = i.joints.filter((g) => s.has(g.parent) && s.has(g.child) && g.parent !== g.child), o = /* @__PURE__ */ new Map();
702
+ for (const g of r) o.has(g.child) || o.set(g.child, g);
703
+ const m = i.links.filter((g) => !o.has(g.id)), u = /* @__PURE__ */ new Map();
704
+ for (const g of o.values()) u.set(g.parent, [...u.get(g.parent) ?? [], g]);
705
+ const c = [], d = /* @__PURE__ */ new Set(), b = (g) => {
706
+ if (!d.has(g)) {
707
+ d.add(g);
708
+ for (const M of u.get(g) ?? []) b(M.child);
709
+ }
710
+ };
711
+ for (const g of m)
712
+ c.push(g), b(g.id);
713
+ for (const g of i.links) d.has(g.id) || (c.push(g), b(g.id));
714
+ const a = new Set(c.map((g) => g.id)), l = `robot:${i.name}`, f = /* @__PURE__ */ new Map();
715
+ for (const g of i.joints) f.set(g.parent, [...f.get(g.parent) ?? [], `joint:${g.id}`]);
716
+ const p = [], y = Object.freeze({
717
+ id: l,
718
+ kind: "robot",
719
+ name: i.name,
720
+ childIds: c.map((g) => `link:${g.id}`),
721
+ rootLinkIds: c.map((g) => g.id),
722
+ source: t.robot
723
+ });
724
+ p.push(y);
725
+ for (const g of i.links) p.push(kt(g, i, t.links.get(g.id), f, a, o));
726
+ const h = ee(i.joints);
727
+ for (const g of i.joints) p.push(xt({ ...g, controlLimits: h.get(g.id) }, t.joints.get(g.id), ((w = o.get(g.child)) == null ? void 0 : w.id) === g.id));
728
+ return Object.freeze({
729
+ robotName: i.name,
730
+ sourcePath: n,
731
+ sourceText: e,
732
+ nodes: Object.freeze(p),
733
+ rootEntityId: l,
734
+ issues: Object.freeze(Ft(i, t))
735
+ });
736
+ }
737
+ function kt(i, e, n, t, s, r) {
738
+ var m, u, c, d;
739
+ const o = r.get(i.id);
740
+ return Object.freeze({
741
+ id: `link:${i.id}`,
742
+ kind: "link",
743
+ name: i.name,
744
+ parentId: o ? `joint:${o.id}` : `robot:${e.name}`,
745
+ childIds: Object.freeze(t.get(i.id) ?? []),
746
+ source: n,
747
+ mass: (m = i.inertial) == null ? void 0 : m.mass,
748
+ centerOfMass: (u = i.inertial) == null ? void 0 : u.origin.position,
749
+ inertiaTensor: (c = i.inertial) == null ? void 0 : c.tensor,
750
+ inertiaMass: (d = i.inertial) == null ? void 0 : d.mass,
751
+ inertialRotationRpy: i.inertial ? Object.freeze([...i.inertial.origin.rotationRpy]) : void 0,
752
+ visualCount: i.visuals.length,
753
+ collisionCount: i.collisions.length
754
+ });
755
+ }
756
+ function xt(i, e, n) {
757
+ return Object.freeze({
758
+ id: `joint:${i.id}`,
759
+ kind: "joint",
760
+ name: i.id,
761
+ parentId: `link:${i.parent}`,
762
+ childIds: Object.freeze([`link:${i.child}`]),
763
+ source: e,
764
+ jointType: i.type,
765
+ parentLink: i.parent,
766
+ childLink: i.child,
767
+ axis: Object.freeze([...i.axis]),
768
+ originPosition: Object.freeze([...i.origin.position]),
769
+ originRotationRpy: Object.freeze([...i.origin.rotationRpy]),
770
+ limits: i.limits,
771
+ effort: i.effort,
772
+ velocity: i.velocity,
773
+ controlLimits: i.controlLimits,
774
+ movable: ["revolute", "continuous", "prismatic"].includes(i.type),
775
+ ...i.mimic ? { mimic: Object.freeze({ ...i.mimic }) } : {}
776
+ });
777
+ }
778
+ function Ft(i, e) {
779
+ const n = [], t = (a, l, f, p, y, h) => {
780
+ n.push(Object.freeze({ id: `${a}:${p}`, ruleId: a, severity: "error", title: l, message: f, entityId: p, source: y, values: h ? Object.freeze(h) : void 0 }));
781
+ }, s = new Set(i.links.map((a) => a.id));
782
+ for (const a of i.joints)
783
+ s.has(a.parent) || t("joint.parent.missing", "父连杆不存在", `${a.id} 引用了不存在的 parent link ${a.parent}。`, `joint:${a.id}`, e.joints.get(a.id), { parent: a.parent }), s.has(a.child) || t("joint.child.missing", "子连杆不存在", `${a.id} 引用了不存在的 child link ${a.child}。`, `joint:${a.id}`, e.joints.get(a.id), { child: a.child });
784
+ const r = i.links.filter((a) => !i.joints.some((l) => s.has(l.parent) && l.child === a.id));
785
+ r.length !== 1 && t("robot.root.count", "根连杆数量无效", `URDF 必须恰好有一个根连杆,当前为 ${r.length} 个。`, `robot:${i.name}`, e.robot, { roots: r.map((a) => a.id) });
786
+ const o = /* @__PURE__ */ new Map();
787
+ for (const a of i.joints) s.has(a.parent) && s.has(a.child) && o.set(a.parent, [...o.get(a.parent) ?? [], a.child]);
788
+ const m = /* @__PURE__ */ new Set(), u = /* @__PURE__ */ new Set();
789
+ let c = null;
790
+ const d = (a, l) => {
791
+ if (!c) {
792
+ if (u.has(a)) {
793
+ const f = l.indexOf(a);
794
+ c = [...l.slice(Math.max(0, f)), a];
795
+ return;
796
+ }
797
+ if (!m.has(a)) {
798
+ u.add(a);
799
+ for (const f of o.get(a) ?? []) d(f, [...l, a]);
800
+ u.delete(a), m.add(a);
801
+ }
802
+ }
803
+ };
804
+ for (const a of i.links) d(a.id, []);
805
+ c && t("robot.graph.cycle", "运动学结构存在环", `运动学链形成循环:${c.join(" → ")}。`, `robot:${i.name}`, e.robot, { cycle: c });
806
+ const b = /* @__PURE__ */ new Map();
807
+ for (const a of i.joints) {
808
+ if (b.set(a.child, [...b.get(a.child) ?? [], a.id]), a.parent === a.child && t("joint.self-reference", "关节父子连杆相同", `${a.id} 的 parent 和 child 都是 ${a.parent}。`, `joint:${a.id}`, e.joints.get(a.id)), ["revolute", "continuous", "prismatic"].includes(a.type)) {
809
+ const l = a.axis.reduce((f, p) => f + p * p, 0);
810
+ (!Number.isFinite(l) || l <= Number.EPSILON) && t("joint.axis.zero", "关节轴无效", `${a.id} 的 axis 是零向量。`, `joint:${a.id}`, e.joints.get(a.id), { axis: a.axis });
811
+ }
812
+ a.type !== "continuous" && a.limits && a.limits.lower > a.limits.upper && t("joint.limit.order", "关节限位上下界无效", `${a.id} 的 lower ${a.limits.lower} 大于 upper ${a.limits.upper}。`, `joint:${a.id}`, e.joints.get(a.id), { ...a.limits });
813
+ }
814
+ for (const [a, l] of b) l.length > 1 && t("link.multiple-parents", "连杆存在多个父关节", `${a} 同时被 ${l.join("、")} 作为 child。`, `link:${a}`, e.links.get(a), { joints: l });
815
+ for (const a of i.links) {
816
+ const l = a.inertial;
817
+ l && ((!(l.mass > 0) || !Number.isFinite(l.mass)) && t("inertial.mass.invalid", "质量无效", `${a.id} 的质量必须是大于零的有限数。`, `link:${a.id}`, e.links.get(a.id), { mass: l.mass }), Pe(l.tensor) || t("inertial.tensor.invalid", "惯性张量无效", `${a.id} 的惯性张量不是正定的物理惯性张量。`, `link:${a.id}`, e.links.get(a.id), { tensor: l.tensor }));
818
+ }
819
+ return n;
820
+ }
821
+ function Ut(i, e) {
822
+ const n = { robot: void 0, links: /* @__PURE__ */ new Map(), joints: /* @__PURE__ */ new Map() };
823
+ n.robot = ze(i, "robot", void 0, e);
824
+ for (const t of ["link", "joint"]) {
825
+ const s = new RegExp(`<${t}\\b[^>]*\\bname\\s*=\\s*(["'])(.*?)\\1[^>]*>`, "gi");
826
+ for (const r of i.matchAll(s)) {
827
+ const o = r[2], m = ze(i, t, o, e, r.index);
828
+ m && n[t === "link" ? "links" : "joints"].set(o, m);
829
+ }
830
+ }
831
+ return n;
832
+ }
833
+ function ze(i, e, n, t, s) {
834
+ const r = s ?? i.search(new RegExp(`<${e}\\b`, "i"));
835
+ if (r < 0) return;
836
+ const o = i.indexOf(">", r);
837
+ if (o < 0) return;
838
+ const u = i.slice(r, o + 1).trimEnd().endsWith("/>") ? o + 1 : i.indexOf(`</${e}>`, o + 1), c = u < 0 ? o + 1 : u + e.length + 3, d = Oe(i, r), b = Oe(i, c);
839
+ return Object.freeze({ file: t, startOffset: r, endOffset: c, startLine: d.line, startColumn: d.column, endLine: b.line, endColumn: b.column });
840
+ }
841
+ function Oe(i, e) {
842
+ const t = i.slice(0, e).split(/\r?\n/);
843
+ return { line: t.length, column: t.at(-1).length + 1 };
844
+ }
845
+ class zt {
846
+ constructor(e, n, t, s, r) {
847
+ A(this, "kind", "urdf");
848
+ A(this, "overlayRoot", new q());
849
+ A(this, "listeners", /* @__PURE__ */ new Set());
850
+ A(this, "revision", 0);
851
+ A(this, "selectedEntityId");
852
+ A(this, "overlays", Object.freeze({ collision: !1, jointAxis: !1, centerOfMass: !1, inertia: !1 }));
853
+ A(this, "mode");
854
+ A(this, "dynamicsAvailable");
855
+ A(this, "dynamicsMessage");
856
+ A(this, "highlightedMaterials", /* @__PURE__ */ new Map());
857
+ A(this, "selectionMaterials", /* @__PURE__ */ new Map());
858
+ A(this, "guideBindings", []);
859
+ A(this, "guideMatrix", new W());
860
+ A(this, "overlayInverse", new W());
861
+ A(this, "guideSizes", /* @__PURE__ */ new Map());
862
+ A(this, "labelAnchors", /* @__PURE__ */ new Map());
863
+ A(this, "modelSize", 1);
864
+ A(this, "disposed", !1);
865
+ var o, m;
866
+ this.asset = e, this.document = n, this.binding = t, this.options = s, this.selectedEntityId = ((o = n.nodes.find((u) => u.kind === "joint")) == null ? void 0 : o.id) ?? ((m = n.nodes.find((u) => u.kind === "link")) == null ? void 0 : m.id) ?? n.rootEntityId, this.mode = "kinematic", this.dynamicsAvailable = r, this.overlayRoot.name = "URDF review overlays", this.measureGuideSizes(), this.rebuildOverlay();
867
+ }
868
+ getSnapshot() {
869
+ return Object.freeze({
870
+ revision: this.revision,
871
+ kind: "urdf",
872
+ robotName: this.document.robotName,
873
+ sourcePath: this.document.sourcePath,
874
+ sourceText: this.document.sourceText,
875
+ nodes: this.document.nodes,
876
+ rootEntityId: this.document.rootEntityId,
877
+ selectedEntityId: this.selectedEntityId,
878
+ jointValues: this.binding.valuesSnapshot(),
879
+ overlays: this.overlays,
880
+ issues: this.document.issues,
881
+ mode: this.mode,
882
+ dynamicsAvailable: this.dynamicsAvailable,
883
+ ...this.dynamicsMessage ? { dynamicsMessage: this.dynamicsMessage } : {}
884
+ });
885
+ }
886
+ subscribe(e) {
887
+ return this.listeners.add(e), () => this.listeners.delete(e);
888
+ }
889
+ select(e) {
890
+ if (!(this.mode === "dynamics-running" || this.mode === "dynamics-initializing")) {
891
+ if (e !== null && !this.document.nodes.some((n) => n.id === e)) throw Ot(`Unknown URDF entity: ${e}`, "E_URDF_ENTITY_UNKNOWN");
892
+ this.selectedEntityId !== e && (this.selectedEntityId = e, this.rebuildOverlay(), this.publish());
893
+ }
894
+ }
895
+ setJointValue(e, n) {
896
+ this.mode === "dynamics-running" || this.mode === "dynamics-initializing" || (this.options.enterKinematicPreview(), this.binding.setJointValue(e, n), this.mode = "kinematic", this.rebuildGuides(), this.publish());
897
+ }
898
+ resetJoint(e) {
899
+ this.mode === "dynamics-running" || this.mode === "dynamics-initializing" || (this.options.enterKinematicPreview(), this.binding.resetJoint(e), this.mode = "kinematic", this.rebuildOverlay(), this.publish());
900
+ }
901
+ resetPose() {
902
+ this.options.enterKinematicPreview(), this.binding.resetPose(), this.mode = "kinematic", this.rebuildOverlay(), this.publish();
903
+ }
904
+ setOverlay(e, n) {
905
+ this.overlays[e] !== n && (this.overlays = Object.freeze({ ...this.overlays, [e]: n }), e === "collision" && this.options.setCollisionVisible(n), this.rebuildOverlay(), this.publish());
906
+ }
907
+ enterKinematicPreview() {
908
+ this.options.enterKinematicPreview(), this.mode = "kinematic", this.overlayRoot.visible = !0, this.publish();
909
+ }
910
+ setMode(e, n) {
911
+ e === "dynamics-unavailable" ? (this.mode = "kinematic", this.dynamicsAvailable = !1) : this.mode = e, this.overlayRoot.visible = this.mode !== "dynamics-initializing", (e === "dynamics-running" || e === "dynamics-initializing") && (this.selectedEntityId = null), this.dynamicsMessage = n, this.rebuildOverlay(), this.publish();
912
+ }
913
+ jointWorldFrame(e) {
914
+ return this.binding.jointWorldFrame(e);
915
+ }
916
+ pickRoots() {
917
+ var e, n;
918
+ return ((n = (e = this.options).pickRoots) == null ? void 0 : n.call(e)) ?? this.binding.pickRoots();
919
+ }
920
+ selectionObject() {
921
+ return this.selectedEntityId ? this.binding.objectForEntity(this.selectedEntityId) : null;
922
+ }
923
+ dispose() {
924
+ if (!this.disposed) {
925
+ this.disposed = !0, this.listeners.clear(), this.restoreSelectionMaterials();
926
+ for (const e of this.selectionMaterials.values()) e.dispose();
927
+ this.selectionMaterials.clear(), L(this.overlayRoot), this.overlayRoot.removeFromParent();
928
+ }
929
+ }
930
+ publish() {
931
+ if (this.disposed) return;
932
+ this.revision += 1;
933
+ const e = this.getSnapshot();
934
+ for (const n of this.listeners) n(e);
935
+ this.options.requestRender();
936
+ }
937
+ rebuildOverlay() {
938
+ if (this.overlayRoot.visible = this.mode !== "dynamics-initializing", this.restoreSelectionMaterials(), this.clearGuides(), this.buildMassGuides(), this.buildJointGuides(), this.syncGuides(), !this.selectedEntityId) return;
939
+ const e = this.document.nodes.find((t) => t.id === this.selectedEntityId);
940
+ if (!e) return;
941
+ const n = this.binding.objectForEntity(e.id);
942
+ n && e.kind !== "robot" && this.applySelectionMaterials(n);
943
+ }
944
+ rebuildGuides() {
945
+ this.overlayRoot.visible = this.mode !== "dynamics-initializing", this.clearGuides(), this.buildMassGuides(), this.buildJointGuides(), this.syncGuides(), this.selectedEntityId && this.document.nodes.find((e) => e.id === this.selectedEntityId);
946
+ }
947
+ /** Update transforms only: physics ticks must not rebuild geometry or publish UI state. */
948
+ syncGuides() {
949
+ if (!(this.disposed || !this.overlayRoot.visible || !this.guideBindings.length)) {
950
+ this.overlayRoot.updateWorldMatrix(!0, !1), this.overlayInverse.copy(this.overlayRoot.matrixWorld).invert();
951
+ for (const { guide: e, source: n, local: t } of this.guideBindings)
952
+ n.updateWorldMatrix(!0, !1), this.guideMatrix.multiplyMatrices(this.overlayInverse, n.matrixWorld).multiply(t), this.guideMatrix.decompose(e.position, e.quaternion, e.scale), e.updateMatrixWorld(!0);
953
+ }
954
+ }
955
+ linkObject(e) {
956
+ var n, t;
957
+ return ((t = (n = this.options).linkObject) == null ? void 0 : t.call(n, e)) ?? this.binding.objectForEntity(`link:${e}`);
958
+ }
959
+ trackGuide(e, n) {
960
+ n.updateWorldMatrix(!0, !1), this.overlayRoot.updateWorldMatrix(!0, !1), e.updateWorldMatrix(!0, !1);
961
+ const t = n.matrixWorld.clone().invert().multiply(e.matrixWorld);
962
+ this.guideBindings.push({ guide: e, source: n, local: t });
963
+ }
964
+ clearGuides() {
965
+ this.guideBindings.length = 0, L(this.overlayRoot), this.overlayRoot.clear();
966
+ }
967
+ /** Cache own-link bounds once; exclude child links and never traverse meshes per physics tick. */
968
+ measureGuideSizes() {
969
+ const e = new $e();
970
+ for (const t of this.document.nodes) {
971
+ if (t.kind !== "link") continue;
972
+ const s = this.binding.objectForEntity(t.id);
973
+ if (!s) continue;
974
+ s.updateWorldMatrix(!0, !0);
975
+ const r = new $e(), o = (u) => {
976
+ if (!(u !== s && typeof u.userData.urdfEntityId == "string")) {
977
+ u instanceof U && (u.geometry.boundingBox || u.geometry.computeBoundingBox(), u.geometry.boundingBox && r.union(u.geometry.boundingBox.clone().applyMatrix4(u.matrixWorld)));
978
+ for (const c of u.children) o(c);
979
+ }
980
+ };
981
+ if (o(s), r.isEmpty()) continue;
982
+ this.labelAnchors.set(t.name, r.getCenter(new z()).applyMatrix4(s.matrixWorld.clone().invert()));
983
+ const m = r.getSize(new z()).length();
984
+ Number.isFinite(m) && m > 0 && (this.guideSizes.set(t.name, m), e.union(r));
985
+ }
986
+ const n = e.getSize(new z()).length();
987
+ Number.isFinite(n) && n > 0 && (this.modelSize = n);
988
+ }
989
+ linkWorldPosition(e, n) {
990
+ const t = this.linkObject(e);
991
+ return !t || this.disposed || this.mode === "dynamics-initializing" ? !1 : (t.updateWorldMatrix(!0, !1), n.copy(this.labelAnchors.get(e) ?? new z()).applyMatrix4(t.matrixWorld), !0);
992
+ }
993
+ guideSize(e) {
994
+ const n = this.guideSizes.get(e) ?? this.modelSize * 0.1;
995
+ return Math.max(this.modelSize * 3e-3, Math.min(n, this.modelSize * 0.35));
996
+ }
997
+ buildJointGuides() {
998
+ const e = this.document.nodes.find((t) => t.id === this.selectedEntityId), n = (e == null ? void 0 : e.kind) === "joint" ? e : (e == null ? void 0 : e.kind) === "link" ? this.document.nodes.find((t) => t.kind === "joint" && t.childLink === e.name) : void 0;
999
+ for (const t of this.document.nodes) {
1000
+ if (t.kind !== "joint" || !this.overlays.jointAxis && t.id !== (n == null ? void 0 : n.id)) continue;
1001
+ const s = this.linkObject(t.parentLink), r = s ? (() => {
1002
+ s.updateWorldMatrix(!0, !1);
1003
+ const c = s.getWorldQuaternion(new O()).multiply(new O().setFromEuler(new X(...t.originRotationRpy, "ZYX")));
1004
+ return { position: new z().fromArray(t.originPosition).applyMatrix4(s.matrixWorld), quaternion: c, axis: new z().fromArray(t.axis).applyQuaternion(c).normalize() };
1005
+ })() : this.binding.jointWorldFrame(t.name);
1006
+ if (!r) continue;
1007
+ const o = new q();
1008
+ o.name = `Joint guide:${t.name}`;
1009
+ const m = this.guideSize(t.childLink), u = new it(0.18 * m);
1010
+ if (u.name = `Joint frame:${t.name}`, u.position.copy(r.position), u.quaternion.copy(r.quaternion), o.add(u), ["revolute", "continuous", "prismatic"].includes(t.jointType)) {
1011
+ const c = r.axis.clone().normalize(), d = new Ee(c, r.position, 0.28 * m, 5625523, 0.045 * m, 0.022 * m);
1012
+ if (d.name = `Joint axis:${t.name}`, o.add(d), t.jointType !== "prismatic") {
1013
+ const a = (Math.abs(c.z) < 0.9 ? new z(0, 0, 1) : new z(0, 1, 0)).cross(c).normalize(), l = c.clone().cross(a).normalize(), f = 0.09 * m, p = Math.PI * 1.65, y = r.position.clone().addScaledVector(c, 0.085 * m), h = Array.from({ length: 33 }, (j, E) => {
1014
+ const R = p * E / 32;
1015
+ return y.clone().addScaledVector(a, f * Math.cos(R)).addScaledVector(l, f * Math.sin(R));
1016
+ }), w = new nt(new st().setFromPoints(h), new je({ color: 16761963 }));
1017
+ w.name = `Positive rotation:${t.name}`;
1018
+ const g = a.clone().multiplyScalar(-Math.sin(p)).addScaledVector(l, Math.cos(p)), M = new Ee(g, h[32], 0.03 * m, 16761963, 0.03 * m, 0.022 * m);
1019
+ M.name = `Positive rotation arrow:${t.name}`, o.add(w, M);
1020
+ }
1021
+ }
1022
+ o.traverse((c) => {
1023
+ c.renderOrder = 1001;
1024
+ const d = c.material;
1025
+ for (const b of Array.isArray(d) ? d : d ? [d] : [])
1026
+ b.depthTest = !1, b.depthWrite = !1, b.transparent = !0;
1027
+ }), this.overlayRoot.add(o), s && this.trackGuide(o, s);
1028
+ }
1029
+ }
1030
+ buildMassGuides() {
1031
+ if (!this.overlays.centerOfMass && !this.overlays.inertia) return;
1032
+ const e = this.document.nodes.find((t) => t.id === this.selectedEntityId), n = (e == null ? void 0 : e.kind) === "link" ? e.name : (e == null ? void 0 : e.kind) === "joint" ? e.childLink : void 0;
1033
+ for (const t of this.asset.links) {
1034
+ const s = t.inertial, r = this.linkObject(t.id);
1035
+ if (!s || !r) continue;
1036
+ r.updateWorldMatrix(!0, !1);
1037
+ const o = new z().fromArray(s.origin.position).applyMatrix4(r.matrixWorld), m = t.id === n;
1038
+ if (this.overlays.centerOfMass) {
1039
+ const l = new ae(0.025 * this.guideSize(t.id), 32, 16), f = l.toNonIndexed();
1040
+ l.dispose();
1041
+ const p = f.getAttribute("position"), y = new Float32Array(p.count * 3);
1042
+ for (let w = 0; w < p.count; w += 3) {
1043
+ let g = 0, M = 0, j = 0;
1044
+ for (let R = 0; R < 3; R++)
1045
+ g += p.getX(w + R), M += p.getY(w + R), j += p.getZ(w + R);
1046
+ const E = g * M * j >= 0 ? 1 : 0.015;
1047
+ for (let R = 0; R < 9; R++) y[w * 3 + R] = E;
1048
+ }
1049
+ f.setAttribute("color", new ot(y, 3));
1050
+ const h = new U(f, new Se({ color: m ? 16739210 : 16777215, vertexColors: !0, depthTest: !1, depthWrite: !1 }));
1051
+ h.quaternion.copy(r.getWorldQuaternion(new O())), h.position.copy(o), h.renderOrder = 1002, h.name = `Center of mass:${t.id}`, this.overlayRoot.add(h), this.trackGuide(h, r);
1052
+ }
1053
+ const u = this.overlays.inertia ? Xe(s.tensor, s.mass) : null;
1054
+ if (!u) continue;
1055
+ const c = new re(1, 1, 1), d = new rt(new at(c), new je({ color: m ? 16736135 : 2211300, transparent: !0, opacity: m ? 0.98 : 0.82, depthTest: !0, depthWrite: !1 })), b = new U(c, new Se({ color: m ? 16739210 : 3262699, transparent: !0, opacity: m ? 0.28 : 0.16, depthTest: !0, depthWrite: !1 }));
1056
+ b.name = `Inertia fill:${t.id}`;
1057
+ const a = s.origin.rotationQuaternion ? new O().fromArray(s.origin.rotationQuaternion) : new O().setFromEuler(new X(...s.origin.rotationRpy, "ZYX"));
1058
+ d.position.copy(o), d.scale.fromArray(u.size), d.quaternion.copy(r.getWorldQuaternion(new O())).multiply(a).multiply(u.rotation), d.renderOrder = 1001, d.name = `Inertia:${t.id}`, b.position.copy(d.position), b.quaternion.copy(d.quaternion), b.scale.copy(d.scale), b.renderOrder = 1e3, this.overlayRoot.add(b, d), this.trackGuide(b, r), this.trackGuide(d, r);
1059
+ }
1060
+ }
1061
+ applySelectionMaterials(e) {
1062
+ const n = (t, s) => {
1063
+ if (!(!s && typeof t.userData.urdfEntityId == "string")) {
1064
+ t instanceof U && t.material && (this.highlightedMaterials.set(t, t.material), t.material = Array.isArray(t.material) ? t.material.map((r) => this.createSelectionMaterial(r)) : this.createSelectionMaterial(t.material));
1065
+ for (const r of t.children) n(r, !1);
1066
+ }
1067
+ };
1068
+ n(e, !0);
1069
+ }
1070
+ createSelectionMaterial(e) {
1071
+ var r;
1072
+ const n = this.selectionMaterials.get(e);
1073
+ if (n) return n;
1074
+ const t = e.clone(), s = t;
1075
+ return (r = s.color) == null || r.set(9425919), s.emissive ? (s.emissive.set(2793430), s.emissiveIntensity = Math.max(s.emissiveIntensity ?? 0, 0.34)) : t instanceof oe && (t.emissive.set(2793430), t.emissiveIntensity = 0.34), t.transparent = e.transparent, t.opacity = e.opacity, t.depthWrite = e.depthWrite, t.needsUpdate = !0, this.selectionMaterials.set(e, t), t;
1076
+ }
1077
+ restoreSelectionMaterials() {
1078
+ for (const [e, n] of this.highlightedMaterials) e.material = n;
1079
+ this.highlightedMaterials.clear();
1080
+ }
1081
+ }
1082
+ function Ot(i, e) {
1083
+ return Object.assign(new Error(i), { code: e });
1084
+ }
1085
+ async function Tt(i, e, n) {
1086
+ var N, D, ce, ue;
1087
+ const t = i.entryPath ?? i.filename ?? "asset.urdf";
1088
+ (N = e.reportProgress) == null || N.call(e, "fetch", "正在读取模型描述与依赖资源...");
1089
+ let s = await Ve(i, n);
1090
+ const r = e.format === "xacro";
1091
+ if (r) {
1092
+ (D = e.reportProgress) == null || D.call(e, "xacro", "正在展开 Xacro 宏与依赖文件...");
1093
+ const { expandXacro: v } = await import("./xacro-IpPHTMYs.js");
1094
+ s = await v(s, t, n, e.options.xacro, e.signal);
1095
+ }
1096
+ if (e.signal.aborted) throw Q();
1097
+ (ce = e.reportProgress) == null || ce.call(e, "parse", "正在解析 URDF 结构与连杆...");
1098
+ const o = yt(s, t, n);
1099
+ (ue = e.reportProgress) == null || ue.call(e, "visual", "正在构建运动学预览...");
1100
+ const m = await Fe(o), u = new jt(o, m), c = await vt(o, m), d = o.diagnostics.errors.find((v) => v.code === "E_URDF_INERTIA"), b = o.links.some((v) => v.inertial), a = b && !d, l = new Ke(
1101
+ u.root,
1102
+ e.options.simulationTheme,
1103
+ void 0,
1104
+ "simulation",
1105
+ a ? "physics" : "visual"
1106
+ );
1107
+ c && (c.root.visible = !1, l.attachAuxiliary(c.root));
1108
+ let f = null, p = null, y = null;
1109
+ const h = o.diagnostics.warnings[0], w = h ? ye(h, "visual-material") : null;
1110
+ let g = d ? {
1111
+ code: d.code,
1112
+ message: d.message,
1113
+ stage: "physics-validation",
1114
+ notice: ge(d.code, d.source)
1115
+ } : w, M = d ? { status: "unavailable", issue: g } : b ? { status: "available" } : { status: "not-authored" }, j = !1, E = null, R = !1, I = !1;
1116
+ const x = () => {
1117
+ var S;
1118
+ const v = j || !u.root.visible;
1119
+ j = !1, l.setRuntime(void 0), p && (p.root.visible = !1), l.replaceModel(u.root, !1), u.root.visible = !0, c && c.sync(), c != null && c.root && (c.root.visible = $.getSnapshot().overlays.collision), y && (y.root.visible = !1), v && ((S = e.reportSessionState) == null || S.call(e)), e.requestRender();
1120
+ }, $ = new zt(o, St(o, s, r ? `${t} (expanded URDF)` : t), u, {
1121
+ requestRender() {
1122
+ u.root.visible && (c == null || c.sync()), e.requestRender();
1123
+ },
1124
+ setCollisionVisible(v) {
1125
+ c && (c.root.visible = v && u.root.visible), y && (y.root.visible = v && (p == null ? void 0 : p.root.visible) === !0);
1126
+ },
1127
+ enterKinematicPreview: x,
1128
+ linkObject: (v) => p != null && p.root.visible ? p.objectForLink(v) : u.objectForEntity(`link:${v}`),
1129
+ pickRoots: () => j || M.status === "initializing" ? [] : u.pickRoots()
1130
+ }, a);
1131
+ d && $.setMode(
1132
+ "dynamics-unavailable",
1133
+ ge(d.code, d.source).summary
1134
+ ), l.attachAuxiliary($.overlayRoot);
1135
+ const F = () => !f || !p ? !1 : (f.setJointValues($.getSnapshot().jointValues), l.replaceModel(p.root, !1), l.setRuntime(f), p.sync(), y == null || y.sync(), u.root.visible = !1, p.root.visible = !0, c && (c.root.visible = !1), y && (y.root.visible = $.getSnapshot().overlays.collision), !0), C = async () => {
1136
+ var de, pe, fe, me;
1137
+ if (f || R || !a) return;
1138
+ $.setMode("dynamics-initializing"), M = { status: "initializing" }, (de = e.reportSessionState) == null || de.call(e);
1139
+ let v = null, S = null, P = null;
1140
+ try {
1141
+ const G = await wt(o);
1142
+ if (e.signal.aborted || R) throw Q();
1143
+ const Z = await import("./mujoco-runtime-BYZnrvbR.js");
1144
+ if (v = new Z.MujocoRuntime(), await v.initialize(G, {
1145
+ baseUrl: e.options.mujocoBaseUrl,
1146
+ wasmModule: e.options.mujocoWasmModule
1147
+ }), v.setWorldRotation(ve(l.getUpAxis())), e.signal.aborted || R || (S = new Me(v, await Fe(o)), e.signal.aborted || R)) throw Q();
1148
+ const he = await Ne(o);
1149
+ if (P = he ? new Me(v, he) : null, e.signal.aborted || R) throw Q();
1150
+ f = v, v = null, p = S, S = null, p.root.visible = !1, y = P, P = null, y && (y.root.visible = !1, l.attachAuxiliary(y.root)), M = { status: "ready" }, g = w, I && (F(), j = !0, $.setMode("dynamics-running")), (pe = e.reportSessionState) == null || pe.call(e), e.requestRender();
1151
+ } catch (G) {
1152
+ if (P == null || P.dispose(), S == null || S.dispose(), v == null || v.dispose(), R || e.signal.aborted || G instanceof Error && G.name === "AbortError") return;
1153
+ const Z = Je(G, e.signal, "urdf-physics");
1154
+ l.setRuntime(void 0), l.setGroundPlacement("visual"), f == null || f.dispose(), f = null, p == null || p.dispose(), p = null, y && (l.detachAuxiliary(y.root), y.dispose(), y = null), x(), g = ye(Z, "physics-fallback"), M = { status: "unavailable", issue: g }, $.setMode("dynamics-unavailable", ((fe = g.notice) == null ? void 0 : fe.summary) ?? g.message), (me = e.reportSessionState) == null || me.call(e), e.reportError(G, { fatal: !1, stage: "physics-start", code: Z.code });
1155
+ }
1156
+ };
1157
+ return {
1158
+ asset: o,
1159
+ stage: l,
1160
+ inspection: $,
1161
+ autoPlay: !1,
1162
+ root: l.root,
1163
+ get capabilities() {
1164
+ const v = M.status === "initializing", S = M.status === "unavailable" || M.status === "not-authored";
1165
+ return { canPlay: !v && !S, canPause: f !== null, canReset: !0, hasPhysics: f !== null, canToggleGround: !0, canToggleCollision: c !== void 0 || y !== null, canReorientUpAxis: !0 };
1166
+ },
1167
+ get physics() {
1168
+ return M;
1169
+ },
1170
+ get warning() {
1171
+ return g;
1172
+ },
1173
+ isPlaying: () => j,
1174
+ play() {
1175
+ var v;
1176
+ if (!(R || M.status === "unavailable" || M.status === "not-authored")) {
1177
+ if (I = !0, $.select(null), !f) {
1178
+ E ?? (E = C().finally(() => {
1179
+ E = null;
1180
+ }));
1181
+ return;
1182
+ }
1183
+ F() && (j = !0, $.setMode("dynamics-running"), (v = e.reportSessionState) == null || v.call(e));
1184
+ }
1185
+ },
1186
+ pause() {
1187
+ var v;
1188
+ I = !1, j = !1, l.endGrab(), f && (u.syncPhysicsPose(f.getJointValues(o.joints.map((S) => S.id)), Pt(p.bodyPoses(), ve(l.getUpAxis()))), x(), $.setMode("dynamics-paused")), (v = e.reportSessionState) == null || v.call(e), e.requestRender();
1189
+ },
1190
+ reset() {
1191
+ var v;
1192
+ I = !1, l.endGrab(), f && (f.reset(), p == null || p.sync(), y == null || y.sync()), $.resetPose(), l.resetGround(), (v = e.reportSessionState) == null || v.call(e), e.requestRender();
1193
+ },
1194
+ step(v) {
1195
+ if (!f || !j) return !1;
1196
+ const S = f.step(v);
1197
+ return S && (p == null || p.sync(), y == null || y.sync(), $.syncGuides(), l.updateForceLine()), S;
1198
+ },
1199
+ beginGrab(v, S, P) {
1200
+ return !!(j && f && l.beginGrab(v, S, P));
1201
+ },
1202
+ moveGrab(v, S, P) {
1203
+ j && f && l.moveGrab(v, S, P);
1204
+ },
1205
+ endGrab() {
1206
+ l.endGrab();
1207
+ },
1208
+ setCollisionVisible(v) {
1209
+ c && (c.root.visible = v && u.root.visible), y && (y.root.visible = v && (p == null ? void 0 : p.root.visible) === !0);
1210
+ },
1211
+ dispose() {
1212
+ R || (R = !0, j = !1, $.dispose(), c && (l.detachAuxiliary(c.root), c.dispose()), y && (l.detachAuxiliary(y.root), y.dispose()), l.setRuntime(void 0), p == null || p.dispose(), u.dispose(), f == null || f.dispose(), l.dispose());
1213
+ }
1214
+ };
1215
+ }
1216
+ function Q() {
1217
+ return Object.assign(new Error("Simulation load aborted."), { name: "AbortError", code: "E_ABORTED" });
1218
+ }
1219
+ function Pt(i, e) {
1220
+ const n = e.clone().invert(), t = /* @__PURE__ */ new Map();
1221
+ for (const [s, r] of i)
1222
+ t.set(s, {
1223
+ position: r.position.clone().applyQuaternion(n),
1224
+ quaternion: n.clone().multiply(r.quaternion)
1225
+ });
1226
+ return t;
1227
+ }
1228
+ export {
1229
+ Tt as loadUrdfSimulation
1230
+ };