@nebula-spatial/viewer 0.5.7 → 0.5.9

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