@khr3/core 0.2.9 → 0.2.11

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 (76) hide show
  1. package/README.md +5 -175
  2. package/dist/KhrAssembly-CKW8I_2z.js +1667 -0
  3. package/dist/KhrAssembly-CKW8I_2z.js.map +1 -0
  4. package/dist/KhrAssembly.d.ts +46 -8
  5. package/dist/KhrCollider.d.ts +21 -7
  6. package/dist/clone.d.ts +40 -0
  7. package/dist/{khrExporter.d.ts → exporter.d.ts} +2 -2
  8. package/dist/{khrGlb.d.ts → glb.d.ts} +4 -3
  9. package/dist/index.d.ts +10 -10
  10. package/dist/index.js +1548 -343
  11. package/dist/index.js.map +1 -1
  12. package/dist/{khrInertia.d.ts → inertia.d.ts} +22 -8
  13. package/dist/{jointDynamics.d.ts → joints.d.ts} +8 -7
  14. package/dist/loader.d.ts +9 -0
  15. package/dist/types.d.ts +282 -0
  16. package/dist/useKhrGlb.d.ts +6 -1
  17. package/dist/vehicle.d.ts +35 -2
  18. package/dist/vehicle.js +435 -539
  19. package/dist/vehicle.js.map +1 -1
  20. package/dist/wheelLoads.d.ts +5 -4
  21. package/package.json +6 -25
  22. package/AGENTS.md +0 -12
  23. package/CLAUDE.md +0 -8
  24. package/dist/AssemblyRootBody.d.ts +0 -16
  25. package/dist/BundleSceneHost.d.ts +0 -23
  26. package/dist/KhrVehicle.d.ts +0 -20
  27. package/dist/assemblyPlan.d.ts +0 -61
  28. package/dist/curves-Cf8okB-M.js +0 -542
  29. package/dist/curves-Cf8okB-M.js.map +0 -1
  30. package/dist/curves.d.ts +0 -378
  31. package/dist/curves.js +0 -1
  32. package/dist/khrBundleFinalize.d.ts +0 -15
  33. package/dist/khrClone.d.ts +0 -14
  34. package/dist/khrConfigTypes.d.ts +0 -62
  35. package/dist/khrExportEncoders.d.ts +0 -8
  36. package/dist/khrExtras.d.ts +0 -22
  37. package/dist/khrInertia-DgCUCDTx.js +0 -247
  38. package/dist/khrInertia-DgCUCDTx.js.map +0 -1
  39. package/dist/khrJointParser.d.ts +0 -3
  40. package/dist/khrLoader.d.ts +0 -7
  41. package/dist/khrMassProps.d.ts +0 -16
  42. package/dist/khrParsers.d.ts +0 -10
  43. package/dist/khrPlugin.d.ts +0 -8
  44. package/dist/khrPluginHelpers.d.ts +0 -26
  45. package/dist/khrRotorDecoders.d.ts +0 -4
  46. package/dist/khrShapeParser.d.ts +0 -8
  47. package/dist/khrTypes.d.ts +0 -141
  48. package/dist/khrVehicleChassis.d.ts +0 -20
  49. package/dist/khrVehicleJointHelpers.d.ts +0 -37
  50. package/dist/khrVehicleJoints.d.ts +0 -30
  51. package/dist/khrVehicleRotors.d.ts +0 -22
  52. package/dist/khrVehicleSlots.d.ts +0 -41
  53. package/dist/khrVehicleTypes.d.ts +0 -52
  54. package/dist/pacejka.d.ts +0 -22
  55. package/dist/physicsEcs-C00N5zCh.js +0 -914
  56. package/dist/physicsEcs-C00N5zCh.js.map +0 -1
  57. package/dist/physicsEcs.d.ts +0 -25
  58. package/dist/sand3d/sand3dAssemblyHelpers.d.ts +0 -30
  59. package/dist/sand3d/sand3dCavityOps.d.ts +0 -15
  60. package/dist/sand3d/sand3dCompiler.d.ts +0 -121
  61. package/dist/sand3d/sand3dEvaluator.d.ts +0 -80
  62. package/dist/sand3d/sand3dFramesAndEdits.d.ts +0 -30
  63. package/dist/sand3d/sand3dHullAndSweep.d.ts +0 -27
  64. package/dist/sand3d/sand3dParser.d.ts +0 -6
  65. package/dist/sand3d/sand3dPrimitives.d.ts +0 -50
  66. package/dist/sand3d/sand3dProfiles.d.ts +0 -32
  67. package/dist/sand3d/sand3dRecipes.d.ts +0 -5
  68. package/dist/sand3d/sand3dShellOp.d.ts +0 -8
  69. package/dist/sand3d/sand3dSolids.d.ts +0 -32
  70. package/dist/sand3d/sand3dTokenizer.d.ts +0 -8
  71. package/dist/sand3d/sand3dTypes.d.ts +0 -157
  72. package/dist/sand3d-DQ8-OMlo.js +0 -5045
  73. package/dist/sand3d-DQ8-OMlo.js.map +0 -1
  74. package/dist/sand3d.d.ts +0 -23
  75. package/dist/sand3d.js +0 -1
  76. package/docs/api-reference.md +0 -383
@@ -0,0 +1,1667 @@
1
+ import React, { createContext, useCallback, useContext, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef } from "react";
2
+ import * as THREE from "three";
3
+ import { useFrame } from "@react-three/fiber";
4
+ import { BallCollider, CapsuleCollider, CoefficientCombineRule, ConvexHullCollider, CuboidCollider, CylinderCollider, RigidBody, TrimeshCollider, useRapier } from "@react-three/rapier";
5
+ import { useCustomGravity } from "@pinkaphant/ecctrl/gravity";
6
+ import { ConvexGeometry } from "three/examples/jsm/geometries/ConvexGeometry.js";
7
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
8
+ // src/types.ts
9
+ var KhrValidationError = class extends Error {
10
+ constructor(message) {
11
+ super(message);
12
+ this.name = "KhrValidationError";
13
+ }
14
+ };
15
+ var JointRegistryContext = createContext(null);
16
+ var COMBINE_MODES = /* @__PURE__ */ new Set([
17
+ "average",
18
+ "minimum",
19
+ "maximum",
20
+ "multiply"
21
+ ]);
22
+ var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
23
+ var isFiniteNum = (v) => typeof v === "number" && Number.isFinite(v);
24
+ var isPosNum = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
25
+ var isNonNegNum = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0;
26
+ function optFiniteNum(v, label, nonNeg = false) {
27
+ if (v === void 0) return void 0;
28
+ if (!isFiniteNum(v) || nonNeg && v < 0) throw new KhrValidationError(`Invalid ${label}: expected finite number${nonNeg ? " >= 0" : ""}`);
29
+ return v;
30
+ }
31
+ function assignRef(ref, value) {
32
+ if (typeof ref === "function") ref(value);
33
+ else if (ref && typeof ref === "object") ref.current = value;
34
+ }
35
+ // src/inertia.ts
36
+ var SCALE_EPS = 1e-4;
37
+ var _wsScratch = new THREE.Vector3();
38
+ function isUnitScalar(v) {
39
+ return typeof v === "number" && Number.isFinite(v) && Math.abs(v - 1) <= 1e-9;
40
+ }
41
+ function assertUnitScale(scale, owner) {
42
+ if (scale === void 0) return;
43
+ let ok = false;
44
+ if (typeof scale === "number") ok = isUnitScalar(scale);
45
+ else if (Array.isArray(scale)) ok = scale.length === 3 && scale.every(isUnitScalar);
46
+ else if (typeof scale === "object" && scale && "x" in scale && "y" in scale && "z" in scale) {
47
+ const v = scale;
48
+ ok = isUnitScalar(v.x) && isUnitScalar(v.y) && isUnitScalar(v.z);
49
+ }
50
+ if (!ok) throw new KhrValidationError(`${owner}: scale must be 1 (got ${typeof scale === "number" && !Number.isFinite(scale) ? String(scale) : JSON.stringify(scale)}); bake scale into the .glb at import`);
51
+ }
52
+ function readFiniteVec3(val, fieldLabel) {
53
+ if (!Array.isArray(val) || val.length !== 3 || !val.every((n) => typeof n === "number" && Number.isFinite(n))) throw new KhrValidationError(`Invalid ${fieldLabel}: expected finite 3-tuple`);
54
+ return [
55
+ val[0],
56
+ val[1],
57
+ val[2]
58
+ ];
59
+ }
60
+ function readUnitQuat(val, fieldLabel) {
61
+ if (!Array.isArray(val) || val.length !== 4 || !val.every((n) => typeof n === "number" && Number.isFinite(n))) throw new KhrValidationError(`Invalid ${fieldLabel}: expected finite 4-tuple`);
62
+ const norm = Math.hypot(val[0], val[1], val[2], val[3]);
63
+ if (!(norm > 1e-6)) throw new KhrValidationError(`Invalid ${fieldLabel}: zero-norm quaternion`);
64
+ return [
65
+ val[0] / norm,
66
+ val[1] / norm,
67
+ val[2] / norm,
68
+ val[3] / norm
69
+ ];
70
+ }
71
+ function assertIdentityWorldScale(obj, nodeName) {
72
+ obj.getWorldScale(_wsScratch);
73
+ if (!Number.isFinite(_wsScratch.x) || !Number.isFinite(_wsScratch.y) || !Number.isFinite(_wsScratch.z) || Math.abs(_wsScratch.x - 1) > SCALE_EPS || Math.abs(_wsScratch.y - 1) > SCALE_EPS || Math.abs(_wsScratch.z - 1) > SCALE_EPS) throw new KhrValidationError(`Non-identity world scale [${_wsScratch.x.toFixed(4)}, ${_wsScratch.y.toFixed(4)}, ${_wsScratch.z.toFixed(4)}] on "${nodeName}"; bake scale=[1,1,1]`);
74
+ const ls = obj.scale;
75
+ if (!Number.isFinite(ls.x) || !Number.isFinite(ls.y) || !Number.isFinite(ls.z) || Math.abs(ls.x - 1) > SCALE_EPS || Math.abs(ls.y - 1) > SCALE_EPS || Math.abs(ls.z - 1) > SCALE_EPS) throw new KhrValidationError(`Non-identity local scale [${ls.x.toFixed(4)}, ${ls.y.toFixed(4)}, ${ls.z.toFixed(4)}] on "${nodeName}"; bake scale=[1,1,1]`);
76
+ }
77
+ function assertSceneIdentityWorldScale(root) {
78
+ root.updateMatrixWorld(true);
79
+ root.traverse((child) => {
80
+ assertIdentityWorldScale(child, child.name || (child === root ? "gltf.scene" : "unnamed_node"));
81
+ });
82
+ }
83
+ function computeRelativePose(ownerObj, childObj) {
84
+ const ownerPos = ownerObj.getWorldPosition(new THREE.Vector3());
85
+ const ownerInvQuat = ownerObj.getWorldQuaternion(new THREE.Quaternion()).invert();
86
+ const pos = childObj.getWorldPosition(new THREE.Vector3()).sub(ownerPos).applyQuaternion(ownerInvQuat);
87
+ const quat = ownerInvQuat.multiply(childObj.getWorldQuaternion(new THREE.Quaternion()));
88
+ return {
89
+ localPosition: [
90
+ pos.x,
91
+ pos.y,
92
+ pos.z
93
+ ],
94
+ localQuaternion: [
95
+ quat.x,
96
+ quat.y,
97
+ quat.z,
98
+ quat.w
99
+ ]
100
+ };
101
+ }
102
+ function extractMeshColliderShape(targetObj, meshNodeName, convexHull) {
103
+ assertIdentityWorldScale(targetObj, meshNodeName);
104
+ const invOwner = targetObj.matrixWorld.clone().invert();
105
+ const rel = new THREE.Matrix4();
106
+ const v = new THREE.Vector3();
107
+ const verts = [];
108
+ const indices = [];
109
+ targetObj.traverse((child) => {
110
+ const mesh = child;
111
+ if (!mesh.isMesh || !mesh.geometry) return;
112
+ assertIdentityWorldScale(mesh, mesh.name || meshNodeName);
113
+ const posAttr = mesh.geometry.getAttribute("position");
114
+ if (!posAttr || posAttr.count === 0) return;
115
+ rel.multiplyMatrices(invOwner, mesh.matrixWorld);
116
+ const base = verts.length / 3;
117
+ for (let i = 0; i < posAttr.count; i++) {
118
+ v.fromBufferAttribute(posAttr, i).applyMatrix4(rel);
119
+ if (!Number.isFinite(v.x) || !Number.isFinite(v.y) || !Number.isFinite(v.z)) throw new KhrValidationError(`Non-finite vertex in collider mesh "${meshNodeName}"`);
120
+ verts.push(v.x, v.y, v.z);
121
+ }
122
+ const idx = mesh.geometry.getIndex();
123
+ if (idx) for (let i = 0; i < idx.count; i++) indices.push(base + idx.getX(i));
124
+ else for (let i = 0; i < posAttr.count; i++) indices.push(base + i);
125
+ });
126
+ if (verts.length < 9) throw new KhrValidationError(`Collider node "${meshNodeName}" has fewer than 3 vertices`);
127
+ if (convexHull) return {
128
+ type: "convexHull",
129
+ vertices: new Float32Array(verts),
130
+ meshNodeName
131
+ };
132
+ if (indices.length < 3) throw new KhrValidationError(`Trimesh node "${meshNodeName}" has fewer than 3 indices`);
133
+ return {
134
+ type: "trimesh",
135
+ vertices: new Float32Array(verts),
136
+ indices: new Uint32Array(indices),
137
+ meshNodeName
138
+ };
139
+ }
140
+ function jacobiPrincipalInertia(ixx, iyy, izz, ixy, ixz, iyz) {
141
+ const a = [
142
+ [
143
+ ixx,
144
+ ixy,
145
+ ixz
146
+ ],
147
+ [
148
+ ixy,
149
+ iyy,
150
+ iyz
151
+ ],
152
+ [
153
+ ixz,
154
+ iyz,
155
+ izz
156
+ ]
157
+ ];
158
+ const v = [
159
+ [
160
+ 1,
161
+ 0,
162
+ 0
163
+ ],
164
+ [
165
+ 0,
166
+ 1,
167
+ 0
168
+ ],
169
+ [
170
+ 0,
171
+ 0,
172
+ 1
173
+ ]
174
+ ];
175
+ for (let iter = 0; iter < 32; iter++) {
176
+ const tr = Math.max(a[0][0] + a[1][1] + a[2][2], 0);
177
+ let p = 0, q = 1, maxOff = Math.abs(a[0][1]);
178
+ if (Math.abs(a[0][2]) > maxOff) {
179
+ p = 0;
180
+ q = 2;
181
+ maxOff = Math.abs(a[0][2]);
182
+ }
183
+ if (Math.abs(a[1][2]) > maxOff) {
184
+ p = 1;
185
+ q = 2;
186
+ maxOff = Math.abs(a[1][2]);
187
+ }
188
+ if (maxOff <= 1e-12 * tr) break;
189
+ const apq = a[p][q], app = a[p][p], aqq = a[q][q];
190
+ const tau = (aqq - app) / (2 * apq);
191
+ const t = tau >= 0 ? 1 / (tau + Math.sqrt(1 + tau * tau)) : -1 / (-tau + Math.sqrt(1 + tau * tau));
192
+ const c = 1 / Math.sqrt(1 + t * t), s = t * c;
193
+ const r = 3 - p - q;
194
+ a[p][p] = c * c * app - 2 * s * c * apq + s * s * aqq;
195
+ a[q][q] = s * s * app + 2 * s * c * apq + c * c * aqq;
196
+ a[p][q] = a[q][p] = 0;
197
+ const arp = a[r][p], arq = a[r][q];
198
+ a[r][p] = a[p][r] = c * arp - s * arq;
199
+ a[r][q] = a[q][r] = s * arp + c * arq;
200
+ for (let i = 0; i < 3; i++) {
201
+ const vip = v[i][p], viq = v[i][q];
202
+ v[i][p] = c * vip - s * viq;
203
+ v[i][q] = s * vip + c * viq;
204
+ }
205
+ }
206
+ if (v[0][0] * (v[1][1] * v[2][2] - v[1][2] * v[2][1]) - v[0][1] * (v[1][0] * v[2][2] - v[1][2] * v[2][0]) + v[0][2] * (v[1][0] * v[2][1] - v[1][1] * v[2][0]) < 0) {
207
+ v[0][2] = -v[0][2];
208
+ v[1][2] = -v[1][2];
209
+ v[2][2] = -v[2][2];
210
+ }
211
+ const mat = new THREE.Matrix4().set(v[0][0], v[0][1], v[0][2], 0, v[1][0], v[1][1], v[1][2], 0, v[2][0], v[2][1], v[2][2], 0, 0, 0, 0, 1);
212
+ const q = new THREE.Quaternion().setFromRotationMatrix(mat).normalize();
213
+ return {
214
+ inertia: [
215
+ a[0][0],
216
+ a[1][1],
217
+ a[2][2]
218
+ ],
219
+ inertiaFrame: [
220
+ q.x,
221
+ q.y,
222
+ q.z,
223
+ q.w
224
+ ]
225
+ };
226
+ }
227
+ /**
228
+ * Exact signed-tetrahedron divergence integration for closed triangle meshes (`trimesh` / `convexHull`).
229
+ * Falls back cleanly to AABB slab inertia only when the mesh is flat/open with near-zero enclosed volume.
230
+ */
231
+ function integrateTriangleMeshProps(vertices, indices) {
232
+ const triCount = indices ? Math.floor(indices.length / 3) : Math.floor(vertices.length / 9);
233
+ if (triCount < 4) return null;
234
+ let rx = 0, ry = 0, rz = 0;
235
+ const vCount = Math.floor(vertices.length / 3);
236
+ for (let i = 0; i < vCount; i++) {
237
+ rx += vertices[i * 3];
238
+ ry += vertices[i * 3 + 1];
239
+ rz += vertices[i * 3 + 2];
240
+ }
241
+ rx /= vCount;
242
+ ry /= vCount;
243
+ rz /= vCount;
244
+ let vol6 = 0;
245
+ let cx24 = 0, cy24 = 0, cz24 = 0;
246
+ let cxx120 = 0, cyy120 = 0, czz120 = 0;
247
+ let cxy120 = 0, cxz120 = 0, cyz120 = 0;
248
+ for (let t = 0; t < triCount; t++) {
249
+ const i0 = (indices ? indices[t * 3] : t * 3) * 3;
250
+ const i1 = (indices ? indices[t * 3 + 1] : t * 3 + 1) * 3;
251
+ const i2 = (indices ? indices[t * 3 + 2] : t * 3 + 2) * 3;
252
+ const ax = vertices[i0] - rx, ay = vertices[i0 + 1] - ry, az = vertices[i0 + 2] - rz;
253
+ const bx = vertices[i1] - rx, by = vertices[i1 + 1] - ry, bz = vertices[i1 + 2] - rz;
254
+ const cx = vertices[i2] - rx, cy = vertices[i2 + 1] - ry, cz = vertices[i2 + 2] - rz;
255
+ const det = ax * (by * cz - bz * cy) - ay * (bx * cz - bz * cx) + az * (bx * cy - by * cx);
256
+ vol6 += det;
257
+ const sx = ax + bx + cx, sy = ay + by + cy, sz = az + bz + cz;
258
+ cx24 += det * sx;
259
+ cy24 += det * sy;
260
+ cz24 += det * sz;
261
+ cxx120 += det * (sx * sx + ax * ax + bx * bx + cx * cx);
262
+ cyy120 += det * (sy * sy + ay * ay + by * by + cy * cy);
263
+ czz120 += det * (sz * sz + az * az + bz * bz + cz * cz);
264
+ cxy120 += det * (sx * sy + ax * ay + bx * by + cx * cy);
265
+ cxz120 += det * (sx * sz + ax * az + bx * bz + cx * cz);
266
+ cyz120 += det * (sy * sz + ay * az + by * bz + cy * cz);
267
+ }
268
+ const sign = vol6 < 0 ? -1 : 1;
269
+ const volume = sign * vol6 / 6;
270
+ if (!(volume > 1e-9)) return null;
271
+ const invV = 1 / volume;
272
+ const comRelX = sign * cx24 / (24 * volume);
273
+ const comRelY = sign * cy24 / (24 * volume);
274
+ const comRelZ = sign * cz24 / (24 * volume);
275
+ const cxx = sign * cxx120 / 120 * invV - comRelX * comRelX;
276
+ const cyy = sign * cyy120 / 120 * invV - comRelY * comRelY;
277
+ const czz = sign * czz120 / 120 * invV - comRelZ * comRelZ;
278
+ const cxy = sign * cxy120 / 120 * invV - comRelX * comRelY;
279
+ const cxz = sign * cxz120 / 120 * invV - comRelX * comRelZ;
280
+ const cyz = sign * cyz120 / 120 * invV - comRelY * comRelZ;
281
+ const ixx = cyy + czz;
282
+ const iyy = cxx + czz;
283
+ const izz = cxx + cyy;
284
+ if (!(ixx > 0 && iyy > 0 && izz > 0)) return null;
285
+ return {
286
+ volume,
287
+ centroid: new THREE.Vector3(rx + comRelX, ry + comRelY, rz + comRelZ),
288
+ unitTensor: [
289
+ ixx,
290
+ iyy,
291
+ izz,
292
+ -cxy,
293
+ -cxz,
294
+ -cyz
295
+ ]
296
+ };
297
+ }
298
+ function fallbackAabbProps(vertices) {
299
+ const box = new THREE.Box3();
300
+ const pt = new THREE.Vector3();
301
+ for (let i = 0; i < vertices.length; i += 3) box.expandByPoint(pt.set(vertices[i], vertices[i + 1], vertices[i + 2]));
302
+ const s = box.getSize(new THREE.Vector3());
303
+ const sx = Math.max(s.x, .001), sy = Math.max(s.y, .001), sz = Math.max(s.z, .001);
304
+ return {
305
+ volume: sx * sy * sz,
306
+ centroid: box.getCenter(new THREE.Vector3()),
307
+ unitTensor: [
308
+ (sy * sy + sz * sz) / 12,
309
+ (sx * sx + sz * sz) / 12,
310
+ (sx * sx + sy * sy) / 12,
311
+ 0,
312
+ 0,
313
+ 0
314
+ ]
315
+ };
316
+ }
317
+ function unitInertiaForShape(shape) {
318
+ if (shape.type === "box") {
319
+ const [x, y, z] = shape.size;
320
+ return {
321
+ volume: x * y * z,
322
+ centroid: new THREE.Vector3(),
323
+ unitTensor: [
324
+ (y * y + z * z) / 12,
325
+ (x * x + z * z) / 12,
326
+ (x * x + y * y) / 12,
327
+ 0,
328
+ 0,
329
+ 0
330
+ ]
331
+ };
332
+ }
333
+ if (shape.type === "sphere") {
334
+ const r = shape.radius;
335
+ const i = .4 * r * r;
336
+ return {
337
+ volume: 4 / 3 * Math.PI * r * r * r,
338
+ centroid: new THREE.Vector3(),
339
+ unitTensor: [
340
+ i,
341
+ i,
342
+ i,
343
+ 0,
344
+ 0,
345
+ 0
346
+ ]
347
+ };
348
+ }
349
+ if (shape.type === "trimesh") return integrateTriangleMeshProps(shape.vertices, shape.indices) ?? fallbackAabbProps(shape.vertices);
350
+ if (shape.type === "convexHull") {
351
+ if (shape.vertices.length >= 12) {
352
+ const pts = [];
353
+ for (let i = 0; i < shape.vertices.length; i += 3) {
354
+ const vx = shape.vertices[i], vy = shape.vertices[i + 1], vz = shape.vertices[i + 2];
355
+ let dup = false;
356
+ for (let j = 0; j < pts.length; j++) {
357
+ const p = pts[j];
358
+ if (Math.abs(p.x - vx) < 1e-5 && Math.abs(p.y - vy) < 1e-5 && Math.abs(p.z - vz) < 1e-5) {
359
+ dup = true;
360
+ break;
361
+ }
362
+ }
363
+ if (!dup) pts.push(new THREE.Vector3(vx, vy, vz));
364
+ }
365
+ if (pts.length >= 4) try {
366
+ const hullGeo = new ConvexGeometry(pts);
367
+ const pos = hullGeo.getAttribute("position");
368
+ const exact = pos && pos.count >= 12 ? integrateTriangleMeshProps(pos.array, null) : null;
369
+ hullGeo.dispose();
370
+ if (exact) return exact;
371
+ } catch {}
372
+ }
373
+ return fallbackAabbProps(shape.vertices);
374
+ }
375
+ const r = shape.radiusTop;
376
+ const h = shape.height;
377
+ if (shape.type === "capsule") {
378
+ const cylVol = Math.PI * r * r * h;
379
+ const totVol = cylVol + 4 / 3 * Math.PI * r * r * r;
380
+ const fc = cylVol / totVol;
381
+ const fh = 1 - fc;
382
+ const iy = .5 * fc * r * r + .4 * fh * r * r;
383
+ const ix = fc * (h * h / 12 + .25 * r * r) + fh * (.4 * r * r + .25 * h * h + .375 * h * r);
384
+ return {
385
+ volume: totVol,
386
+ centroid: new THREE.Vector3(),
387
+ unitTensor: [
388
+ ix,
389
+ iy,
390
+ ix,
391
+ 0,
392
+ 0,
393
+ 0
394
+ ]
395
+ };
396
+ }
397
+ const ix = (3 * r * r + h * h) / 12;
398
+ return {
399
+ volume: Math.PI * r * r * h,
400
+ centroid: new THREE.Vector3(),
401
+ unitTensor: [
402
+ ix,
403
+ .5 * r * r,
404
+ ix,
405
+ 0,
406
+ 0,
407
+ 0
408
+ ]
409
+ };
410
+ }
411
+ function computeShapeInertia(shape, mass) {
412
+ const [ixx, iyy, izz, ixy, ixz, iyz] = unitInertiaForShape(shape).unitTensor;
413
+ if (Math.abs(ixy) + Math.abs(ixz) + Math.abs(iyz) > 1e-12 * (ixx + iyy + izz)) {
414
+ const { inertia } = jacobiPrincipalInertia(ixx, iyy, izz, ixy, ixz, iyz);
415
+ return [
416
+ mass * inertia[0],
417
+ mass * inertia[1],
418
+ mass * inertia[2]
419
+ ];
420
+ }
421
+ return [
422
+ mass * ixx,
423
+ mass * iyy,
424
+ mass * izz
425
+ ];
426
+ }
427
+ function computeBodyInertia(colliders, mass, centerOfMass, inertiaOrientation, nodeName) {
428
+ if (colliders.length === 0) throw new KhrValidationError(`Dynamic node "${nodeName}" is missing motion.inertiaDiagonal and has no colliders`);
429
+ const shapes = colliders.map((c) => unitInertiaForShape(c.shape));
430
+ let totalVol = 0;
431
+ for (const s of shapes) totalVol += s.volume;
432
+ const invFrame = new THREE.Quaternion().fromArray(inertiaOrientation).invert();
433
+ const com = new THREE.Vector3().fromArray(centerOfMass);
434
+ const colQuat = new THREE.Quaternion();
435
+ const relQuat = new THREE.Quaternion();
436
+ const offset = new THREE.Vector3();
437
+ const rotMat = new THREE.Matrix4();
438
+ const m = rotMat.elements;
439
+ let ix = 0, iy = 0, iz = 0;
440
+ for (let i = 0; i < colliders.length; i++) {
441
+ const col = colliders[i];
442
+ const shp = shapes[i];
443
+ const mShare = totalVol > 0 ? mass * (shp.volume / totalVol) : mass / colliders.length;
444
+ colQuat.fromArray(col.localQuaternion);
445
+ offset.copy(shp.centroid).applyQuaternion(colQuat).add(new THREE.Vector3().fromArray(col.localPosition)).sub(com).applyQuaternion(invFrame);
446
+ relQuat.copy(invFrame).multiply(colQuat);
447
+ rotMat.makeRotationFromQuaternion(relQuat);
448
+ const [txx, tyy, tzz, txy, txz, tyz] = shp.unitTensor;
449
+ const r00 = m[0], r01 = m[4], r02 = m[8];
450
+ const r10 = m[1], r11 = m[5], r12 = m[9];
451
+ const r20 = m[2], r21 = m[6], r22 = m[10];
452
+ const rx = r00 * (txx * r00 + txy * r01 + txz * r02) + r01 * (txy * r00 + tyy * r01 + tyz * r02) + r02 * (txz * r00 + tyz * r01 + tzz * r02);
453
+ const ry = r10 * (txx * r10 + txy * r11 + txz * r12) + r11 * (txy * r10 + tyy * r11 + tyz * r12) + r12 * (txz * r10 + tyz * r11 + tzz * r12);
454
+ const rz = r20 * (txx * r20 + txy * r21 + txz * r22) + r21 * (txy * r20 + tyy * r21 + tyz * r22) + r22 * (txz * r20 + tyz * r21 + tzz * r22);
455
+ ix += mShare * (rx + offset.y * offset.y + offset.z * offset.z);
456
+ iy += mShare * (ry + offset.x * offset.x + offset.z * offset.z);
457
+ iz += mShare * (rz + offset.x * offset.x + offset.y * offset.y);
458
+ }
459
+ if (!Number.isFinite(ix) || !Number.isFinite(iy) || !Number.isFinite(iz) || ix <= 0 || iy <= 0 || iz <= 0) throw new KhrValidationError(`Dynamic node "${nodeName}" has degenerate collider geometry; cannot compute positive motion.inertiaDiagonal`);
460
+ return [
461
+ ix,
462
+ iy,
463
+ iz
464
+ ];
465
+ }
466
+ function computeAssemblyMassAndCom(bodies) {
467
+ let totalDynamicMass = 0, mx = 0, my = 0, mz = 0;
468
+ const q = new THREE.Quaternion();
469
+ const c = new THREE.Vector3();
470
+ for (const b of bodies) {
471
+ if (b.isKinematic) continue;
472
+ totalDynamicMass += b.mass;
473
+ c.fromArray(b.centerOfMass).applyQuaternion(q.fromArray(b.localQuaternion));
474
+ mx += (b.localPosition[0] + c.x) * b.mass;
475
+ my += (b.localPosition[1] + c.y) * b.mass;
476
+ mz += (b.localPosition[2] + c.z) * b.mass;
477
+ }
478
+ return {
479
+ totalDynamicMass,
480
+ centerOfMass: totalDynamicMass > 0 ? [
481
+ mx / totalDynamicMass,
482
+ my / totalDynamicMass,
483
+ mz / totalDynamicMass
484
+ ] : [
485
+ 0,
486
+ 0,
487
+ 0
488
+ ]
489
+ };
490
+ }
491
+ var _one = new THREE.Vector3(1, 1, 1);
492
+ function bodyPoseMatrix(body, target = new THREE.Matrix4()) {
493
+ return target.compose(new THREE.Vector3().fromArray(body.localPosition), new THREE.Quaternion().fromArray(body.localQuaternion), _one);
494
+ }
495
+ function decomposeBodyInFrame(body, invFrame, posOut, quatOut, sclScratch, matScratch) {
496
+ if (invFrame) {
497
+ matScratch.multiplyMatrices(invFrame, bodyPoseMatrix(body, matScratch)).decompose(posOut, quatOut, sclScratch);
498
+ quatOut.normalize();
499
+ } else {
500
+ posOut.fromArray(body.localPosition);
501
+ quatOut.fromArray(body.localQuaternion).normalize();
502
+ }
503
+ }
504
+ function computeLumpedMassProps(bodies, invFrame) {
505
+ const dyn = bodies.filter((b) => !b.isKinematic && b.mass > 0);
506
+ if (dyn.length === 0) return null;
507
+ const pos = new THREE.Vector3();
508
+ const quat = new THREE.Quaternion();
509
+ const qExtra = new THREE.Quaternion();
510
+ const rCom = new THREE.Vector3();
511
+ const scl = new THREE.Vector3();
512
+ const mat = new THREE.Matrix4();
513
+ if (dyn.length === 1) {
514
+ const b = dyn[0];
515
+ decomposeBodyInFrame(b, invFrame, pos, quat, scl, mat);
516
+ rCom.fromArray(b.centerOfMass).applyQuaternion(quat);
517
+ const frameQuat = quat.clone().multiply(qExtra.fromArray(b.inertiaOrientation)).normalize();
518
+ return {
519
+ mass: b.mass,
520
+ com: [
521
+ pos.x + rCom.x,
522
+ pos.y + rCom.y,
523
+ pos.z + rCom.z
524
+ ],
525
+ inertia: [
526
+ b.inertiaDiagonal[0],
527
+ b.inertiaDiagonal[1],
528
+ b.inertiaDiagonal[2]
529
+ ],
530
+ inertiaFrame: [
531
+ frameQuat.x,
532
+ frameQuat.y,
533
+ frameQuat.z,
534
+ frameQuat.w
535
+ ]
536
+ };
537
+ }
538
+ let totalMass = 0, mx = 0, my = 0, mz = 0;
539
+ for (const b of dyn) {
540
+ decomposeBodyInFrame(b, invFrame, pos, quat, scl, mat);
541
+ rCom.fromArray(b.centerOfMass).applyQuaternion(quat);
542
+ totalMass += b.mass;
543
+ mx += (pos.x + rCom.x) * b.mass;
544
+ my += (pos.y + rCom.y) * b.mass;
545
+ mz += (pos.z + rCom.z) * b.mass;
546
+ }
547
+ if (!(totalMass > 0)) return null;
548
+ const com = [
549
+ mx / totalMass,
550
+ my / totalMass,
551
+ mz / totalMass
552
+ ];
553
+ let ixx = 0, iyy = 0, izz = 0, ixy = 0, ixz = 0, iyz = 0;
554
+ const m = mat.elements;
555
+ for (const b of dyn) {
556
+ decomposeBodyInFrame(b, invFrame, pos, quat, scl, mat);
557
+ rCom.fromArray(b.centerOfMass).applyQuaternion(quat);
558
+ const dx = pos.x + rCom.x - com[0];
559
+ const dy = pos.y + rCom.y - com[1];
560
+ const dz = pos.z + rCom.z - com[2];
561
+ mat.makeRotationFromQuaternion(quat.multiply(qExtra.fromArray(b.inertiaOrientation)));
562
+ const [d0, d1, d2] = b.inertiaDiagonal;
563
+ ixx += m[0] * m[0] * d0 + m[4] * m[4] * d1 + m[8] * m[8] * d2 + b.mass * (dy * dy + dz * dz);
564
+ iyy += m[1] * m[1] * d0 + m[5] * m[5] * d1 + m[9] * m[9] * d2 + b.mass * (dx * dx + dz * dz);
565
+ izz += m[2] * m[2] * d0 + m[6] * m[6] * d1 + m[10] * m[10] * d2 + b.mass * (dx * dx + dy * dy);
566
+ ixy += m[0] * m[1] * d0 + m[4] * m[5] * d1 + m[8] * m[9] * d2 - b.mass * dx * dy;
567
+ ixz += m[0] * m[2] * d0 + m[4] * m[6] * d1 + m[8] * m[10] * d2 - b.mass * dx * dz;
568
+ iyz += m[1] * m[2] * d0 + m[5] * m[6] * d1 + m[9] * m[10] * d2 - b.mass * dy * dz;
569
+ }
570
+ const diagSum = Math.max(ixx + iyy + izz, 0);
571
+ if (Math.max(Math.abs(ixy), Math.abs(ixz), Math.abs(iyz)) <= 1e-12 * diagSum) return {
572
+ mass: totalMass,
573
+ com,
574
+ inertia: [
575
+ ixx,
576
+ iyy,
577
+ izz
578
+ ],
579
+ inertiaFrame: [
580
+ 0,
581
+ 0,
582
+ 0,
583
+ 1
584
+ ]
585
+ };
586
+ const { inertia, inertiaFrame } = jacobiPrincipalInertia(ixx, iyy, izz, ixy, ixz, iyz);
587
+ return {
588
+ mass: totalMass,
589
+ com,
590
+ inertia,
591
+ inertiaFrame
592
+ };
593
+ }
594
+ // src/clone.ts
595
+ var mountedScenes = /* @__PURE__ */ new WeakSet();
596
+ var clonedScenes = /* @__PURE__ */ new WeakSet();
597
+ var disposedScenes = /* @__PURE__ */ new WeakSet();
598
+ var templateByClone = /* @__PURE__ */ new WeakMap();
599
+ var subtreeRestorersByScene = /* @__PURE__ */ new WeakMap();
600
+ function findSceneRoot(obj) {
601
+ let cur = obj;
602
+ while (cur.parent) cur = cur.parent;
603
+ return cur;
604
+ }
605
+ function registerMountedSubtree(ownerScene, restoreForClone) {
606
+ let set = subtreeRestorersByScene.get(ownerScene);
607
+ if (!set) {
608
+ set = /* @__PURE__ */ new Set();
609
+ subtreeRestorersByScene.set(ownerScene, set);
610
+ }
611
+ set.add(restoreForClone);
612
+ return () => {
613
+ set?.delete(restoreForClone);
614
+ };
615
+ }
616
+ function claimBundleMount(bundle, ownerComponent) {
617
+ if (disposedScenes.has(bundle.scene)) throw new KhrValidationError(`${ownerComponent}: KhrAssetBundle "${bundle.scene.name || bundle.scene.uuid}" has already been disposed`);
618
+ if (mountedScenes.has(bundle.scene)) throw new KhrValidationError(`${ownerComponent}: KhrAssetBundle "${bundle.scene.name || bundle.scene.uuid}" is already mounted; call cloneKhrBundle(template) per concurrent instance`);
619
+ mountedScenes.add(bundle.scene);
620
+ }
621
+ function releaseBundleMount(bundle) {
622
+ mountedScenes.delete(bundle.scene);
623
+ }
624
+ function remapNode(srcRoot, node, dstRoot) {
625
+ if (node === srcRoot) return dstRoot;
626
+ const path = [];
627
+ let cur = node;
628
+ while (cur && cur !== srcRoot) {
629
+ const parent = cur.parent;
630
+ if (!parent) throw new KhrValidationError(`cloneKhrBundle: body node "${node.name}" is detached from bundle.scene`);
631
+ const idx = parent.children.indexOf(cur);
632
+ if (idx < 0) throw new KhrValidationError(`cloneKhrBundle: child index missing for "${node.name}"`);
633
+ path.push(idx);
634
+ cur = parent;
635
+ }
636
+ let out = dstRoot;
637
+ for (let i = path.length - 1; i >= 0; i--) out = out.children[path[i]];
638
+ return out;
639
+ }
640
+ function cloneCurve(curve) {
641
+ if (!curve) return void 0;
642
+ return {
643
+ ...curve,
644
+ points: curve.points.map((pt) => ({ ...pt }))
645
+ };
646
+ }
647
+ function cloneCarTune(tune) {
648
+ if (!tune) return void 0;
649
+ return {
650
+ ...tune,
651
+ ...tune.gearRatios ? { gearRatios: [...tune.gearRatios] } : {},
652
+ ...tune.engineTorqueCurveData ? { engineTorqueCurveData: cloneCurve(tune.engineTorqueCurveData) } : {},
653
+ ...tune.steerAngleCurveData ? { steerAngleCurveData: cloneCurve(tune.steerAngleCurveData) } : {}
654
+ };
655
+ }
656
+ /**
657
+ * Clones a parsed `KhrAssetBundle` in O(nodes) while sharing GPU `BufferGeometry` / `Material` buffers
658
+ * and Rapier `Float32Array` collider vertices. Only restores subtrees belonging to `bundle.scene`.
659
+ */
660
+ function cloneKhrBundle(bundle) {
661
+ if (disposedScenes.has(bundle.scene)) throw new KhrValidationError(`cloneKhrBundle: cannot clone disposed KhrAssetBundle "${bundle.scene.name || bundle.scene.uuid}"`);
662
+ const scopedSet = subtreeRestorersByScene.get(bundle.scene);
663
+ const restorers = scopedSet ? [...scopedSet] : [];
664
+ const reattach = [];
665
+ for (let i = restorers.length - 1; i >= 0; i--) reattach.push(restorers[i]());
666
+ try {
667
+ const scene = bundle.scene.clone(true);
668
+ clonedScenes.add(scene);
669
+ templateByClone.set(scene, templateByClone.get(bundle.scene) ?? bundle.scene);
670
+ const sockets = Object.create(null);
671
+ for (const [k, v] of Object.entries(bundle.sockets)) sockets[k] = [
672
+ v[0],
673
+ v[1],
674
+ v[2]
675
+ ];
676
+ return {
677
+ scene,
678
+ bodies: bundle.bodies.map((b) => {
679
+ const drives = b.joint ? b.joint.drives.map((d) => ({ ...d })) : [];
680
+ return {
681
+ ...b,
682
+ centerOfMass: [...b.centerOfMass],
683
+ inertiaDiagonal: [...b.inertiaDiagonal],
684
+ inertiaOrientation: [...b.inertiaOrientation],
685
+ ...b.linearVelocity ? { linearVelocity: [...b.linearVelocity] } : {},
686
+ ...b.angularVelocity ? { angularVelocity: [...b.angularVelocity] } : {},
687
+ localPosition: [...b.localPosition],
688
+ localQuaternion: [...b.localQuaternion],
689
+ colliders: b.colliders.map((c) => ({
690
+ ...c,
691
+ shape: c.shape.type === "box" ? {
692
+ ...c.shape,
693
+ size: [...c.shape.size]
694
+ } : { ...c.shape },
695
+ localPosition: [...c.localPosition],
696
+ localQuaternion: [...c.localQuaternion]
697
+ })),
698
+ joint: b.joint ? {
699
+ ...b.joint,
700
+ axis: [...b.joint.axis],
701
+ limits: b.joint.limits ? [...b.joint.limits] : null,
702
+ drive: drives[0] ?? (b.joint.drive ? { ...b.joint.drive } : null),
703
+ drives,
704
+ anchor1: [...b.joint.anchor1],
705
+ anchor2: [...b.joint.anchor2]
706
+ } : null,
707
+ ...b.breakaway ? { breakaway: { ...b.breakaway } } : {},
708
+ object: remapNode(bundle.scene, b.object, scene)
709
+ };
710
+ }),
711
+ wheels: bundle.wheels.map((w) => ({
712
+ ...w,
713
+ object: remapNode(bundle.scene, w.object, scene),
714
+ position: [...w.position],
715
+ ...w.quaternion ? { quaternion: [...w.quaternion] } : {},
716
+ ...w.lngSlipRatioCurveData ? { lngSlipRatioCurveData: cloneCurve(w.lngSlipRatioCurveData) } : {},
717
+ ...w.latSlipRatioCurveData ? { latSlipRatioCurveData: cloneCurve(w.latSlipRatioCurveData) } : {}
718
+ })),
719
+ propellers: bundle.propellers.map((p) => ({
720
+ ...p,
721
+ object: remapNode(bundle.scene, p.object, scene),
722
+ position: [...p.position],
723
+ ...p.quaternion ? { quaternion: [...p.quaternion] } : {}
724
+ })),
725
+ sockets,
726
+ totalDynamicMass: bundle.totalDynamicMass,
727
+ centerOfMass: [...bundle.centerOfMass],
728
+ ...bundle.tune ? { tune: cloneCarTune(bundle.tune) } : {},
729
+ ...bundle.droneTune ? { droneTune: { ...bundle.droneTune } } : {}
730
+ };
731
+ } finally {
732
+ for (let i = reattach.length - 1; i >= 0; i--) reattach[i]();
733
+ }
734
+ }
735
+ function disposeSceneGpuResources(roots) {
736
+ const geos = /* @__PURE__ */ new Set();
737
+ const mats = /* @__PURE__ */ new Set();
738
+ const texs = /* @__PURE__ */ new Set();
739
+ for (const root of roots) root.traverse((child) => {
740
+ const mesh = child;
741
+ if (mesh.geometry && !geos.has(mesh.geometry)) {
742
+ geos.add(mesh.geometry);
743
+ mesh.geometry.dispose();
744
+ }
745
+ const matList = Array.isArray(mesh.material) ? mesh.material : mesh.material ? [mesh.material] : [];
746
+ for (const mat of matList) if (!mats.has(mat)) {
747
+ mats.add(mat);
748
+ for (const val of Object.values(mat)) if (val && typeof val === "object" && "isTexture" in val && val.isTexture) {
749
+ const tex = val;
750
+ if (!texs.has(tex)) {
751
+ texs.add(tex);
752
+ tex.dispose();
753
+ }
754
+ }
755
+ mat.dispose();
756
+ }
757
+ });
758
+ }
759
+ /**
760
+ * Releases mount ownership. On root templates (or when `{ disposeTemplate: true }` is passed on a clone),
761
+ * disposes unique GPU geometries, materials, and textures once.
762
+ */
763
+ function disposeKhrBundle(bundle, options) {
764
+ mountedScenes.delete(bundle.scene);
765
+ if (disposedScenes.has(bundle.scene)) return;
766
+ disposedScenes.add(bundle.scene);
767
+ const isClone = clonedScenes.has(bundle.scene);
768
+ if (isClone && !options?.disposeTemplate) return;
769
+ const targetRoot = isClone ? templateByClone.get(bundle.scene) ?? bundle.scene : bundle.scene;
770
+ disposedScenes.add(targetRoot);
771
+ disposeSceneGpuResources([
772
+ targetRoot,
773
+ ...bundle.wheels.map((w) => w.object),
774
+ ...bundle.propellers.map((p) => p.object)
775
+ ]);
776
+ }
777
+ function captureSubtreeOrigins(objects, explicitScene) {
778
+ const parentOrders = /* @__PURE__ */ new Map();
779
+ const origins = /* @__PURE__ */ new Map();
780
+ for (const obj of objects) {
781
+ const ownerScene = explicitScene ?? findSceneRoot(obj);
782
+ const origParent = obj.parent;
783
+ let origOrder = null;
784
+ let origIndex = -1;
785
+ if (origParent) {
786
+ let order = parentOrders.get(origParent);
787
+ if (!order) {
788
+ order = /* @__PURE__ */ new Map();
789
+ origParent.children.forEach((child, idx) => order.set(child, idx));
790
+ parentOrders.set(origParent, order);
791
+ }
792
+ origOrder = order;
793
+ origIndex = order.get(obj) ?? origParent.children.indexOf(obj);
794
+ }
795
+ origins.set(obj, {
796
+ ownerScene,
797
+ origParent,
798
+ origIndex,
799
+ origOrder,
800
+ origPos: obj.position.clone(),
801
+ origQuat: obj.quaternion.clone(),
802
+ origScale: obj.scale.clone()
803
+ });
804
+ }
805
+ return origins;
806
+ }
807
+ function restoreSubtreeOrigin(object, snap) {
808
+ object.position.copy(snap.origPos);
809
+ object.quaternion.copy(snap.origQuat);
810
+ object.scale.copy(snap.origScale);
811
+ const { origParent, origIndex, origOrder } = snap;
812
+ if (!origParent) return;
813
+ if (object.parent && object.parent !== origParent) object.parent.remove(object);
814
+ const existingIdx = origParent.children.indexOf(object);
815
+ if (existingIdx >= 0) origParent.children.splice(existingIdx, 1);
816
+ let insertAt = origParent.children.length;
817
+ if (origOrder && origOrder.size > 0) {
818
+ for (let i = 0; i < origParent.children.length; i++) if ((origOrder.get(origParent.children[i]) ?? 1e400) > origIndex) {
819
+ insertAt = i;
820
+ break;
821
+ }
822
+ } else if (origIndex >= 0) insertAt = Math.min(origIndex, origParent.children.length);
823
+ object.parent = origParent;
824
+ origParent.children.splice(insertAt, 0, object);
825
+ }
826
+ function BundleSceneHost({ bundle, owner }) {
827
+ const hostRef = useRef(null);
828
+ useLayoutEffect(() => {
829
+ const host = hostRef.current;
830
+ if (!host) return;
831
+ claimBundleMount(bundle, owner);
832
+ host.add(bundle.scene);
833
+ return () => {
834
+ if (bundle.scene.parent === host) host.remove(bundle.scene);
835
+ releaseBundleMount(bundle);
836
+ };
837
+ }, [bundle, owner]);
838
+ return React.createElement("group", { ref: hostRef });
839
+ }
840
+ function MountSubtreeSlot({ object, position, quaternion, origin }) {
841
+ const slotRef = useRef(null);
842
+ useLayoutEffect(() => {
843
+ const slot = slotRef.current;
844
+ if (!slot) return;
845
+ const snap = origin ?? captureSubtreeOrigins([object]).get(object);
846
+ if (snap.origParent) snap.origParent.remove(object);
847
+ object.position.set(0, 0, 0);
848
+ object.quaternion.set(0, 0, 0, 1);
849
+ object.scale.set(1, 1, 1);
850
+ slot.add(object);
851
+ const untrack = registerMountedSubtree(snap.ownerScene, () => {
852
+ const p = object.position.clone(), q = object.quaternion.clone(), s = object.scale.clone();
853
+ if (object.parent === slot) slot.remove(object);
854
+ restoreSubtreeOrigin(object, snap);
855
+ return () => {
856
+ if (snap.origParent) snap.origParent.remove(object);
857
+ object.position.copy(p);
858
+ object.quaternion.copy(q);
859
+ object.scale.copy(s);
860
+ slot.add(object);
861
+ };
862
+ });
863
+ return () => {
864
+ untrack();
865
+ if (object.parent === slot) slot.remove(object);
866
+ restoreSubtreeOrigin(object, snap);
867
+ };
868
+ }, [object, origin]);
869
+ return React.createElement("group", {
870
+ ref: slotRef,
871
+ position,
872
+ quaternion
873
+ });
874
+ }
875
+ // src/KhrCollider.tsx
876
+ var COMBINE_RULES = {
877
+ average: CoefficientCombineRule.Average,
878
+ minimum: CoefficientCombineRule.Min,
879
+ maximum: CoefficientCombineRule.Max,
880
+ multiply: CoefficientCombineRule.Multiply
881
+ };
882
+ function KhrCollider({ c, position, quaternion, massProperties, collisionGroups, solverGroups, ref }) {
883
+ const innerRef = useRef(null);
884
+ const setRef = useCallback((node) => {
885
+ innerRef.current = node;
886
+ assignRef(ref, node);
887
+ }, [ref]);
888
+ useEffect(() => {
889
+ innerRef.current?.parent()?.recomputeMassPropertiesFromColliders();
890
+ }, [c, massProperties]);
891
+ const effCollisionGroups = c.collisionGroups ?? collisionGroups;
892
+ const effSolverGroups = solverGroups ?? effCollisionGroups;
893
+ const common = {
894
+ ref: setRef,
895
+ position: position ?? c.localPosition,
896
+ quaternion: quaternion ?? c.localQuaternion,
897
+ ...massProperties ? { massProperties } : { density: 0 },
898
+ ...c.friction === void 0 ? {} : { friction: c.friction },
899
+ ...c.restitution === void 0 ? {} : { restitution: c.restitution },
900
+ ...c.frictionCombine === void 0 ? {} : { frictionCombineRule: COMBINE_RULES[c.frictionCombine] },
901
+ ...c.restitutionCombine === void 0 ? {} : { restitutionCombineRule: COMBINE_RULES[c.restitutionCombine] },
902
+ ...effCollisionGroups === void 0 ? {} : { collisionGroups: effCollisionGroups },
903
+ ...effSolverGroups === void 0 ? {} : { solverGroups: effSolverGroups }
904
+ };
905
+ const { shape } = c;
906
+ if (shape.type === "box") {
907
+ const [sx, sy, sz] = shape.size;
908
+ return /* @__PURE__ */ jsx(CuboidCollider, {
909
+ args: [
910
+ sx * .5,
911
+ sy * .5,
912
+ sz * .5
913
+ ],
914
+ ...common
915
+ });
916
+ }
917
+ if (shape.type === "sphere") return /* @__PURE__ */ jsx(BallCollider, {
918
+ args: [shape.radius],
919
+ ...common
920
+ });
921
+ if (shape.type === "cylinder") return /* @__PURE__ */ jsx(CylinderCollider, {
922
+ args: [shape.height * .5, shape.radiusTop],
923
+ ...common
924
+ });
925
+ if (shape.type === "capsule") return /* @__PURE__ */ jsx(CapsuleCollider, {
926
+ args: [shape.height * .5, shape.radiusTop],
927
+ ...common
928
+ });
929
+ if (shape.type === "convexHull") return /* @__PURE__ */ jsx(ConvexHullCollider, {
930
+ args: [shape.vertices],
931
+ ...common
932
+ });
933
+ return /* @__PURE__ */ jsx(TrimeshCollider, {
934
+ args: [shape.vertices, shape.indices],
935
+ ...common
936
+ });
937
+ }
938
+ // src/joints.ts
939
+ /**
940
+ * Rapier interaction group bitmask for attached vehicle articulated panels:
941
+ * member of group 1 (`0x0002`), collides with all groups except group 1 (`0xfffd`),
942
+ * preventing sibling hinged panels (e.g. `door_fl` <-> `door_rl` / `hood`) from
943
+ * fighting across joints while colliding normally with world geometry and projectiles.
944
+ */
945
+ var ATTACHED_PANEL_INTERACTION_GROUPS = 196605;
946
+ var DETACHED_PANEL_INTERACTION_GROUPS = 0xffffffff;
947
+ var _q1 = new THREE.Quaternion();
948
+ var _q2 = new THREE.Quaternion();
949
+ var _qRel = new THREE.Quaternion();
950
+ var _deltaPos = new THREE.Vector3();
951
+ var _axWorld = new THREE.Vector3();
952
+ function createRapierImpulseJoint(rapier, world, parentBody, childBody, joint, anchorParent, anchorChild, axisParent, axisChild, restFrameRelQuat) {
953
+ const a1 = {
954
+ x: anchorParent[0],
955
+ y: anchorParent[1],
956
+ z: anchorParent[2]
957
+ };
958
+ const a2 = {
959
+ x: anchorChild[0],
960
+ y: anchorChild[1],
961
+ z: anchorChild[2]
962
+ };
963
+ const qRel = _qRel.set(restFrameRelQuat[0], restFrameRelQuat[1], restFrameRelQuat[2], restFrameRelQuat[3]).normalize();
964
+ const axFromChild = _axWorld.set(axisChild[0], axisChild[1], axisChild[2]).applyQuaternion(qRel);
965
+ const ax = (axFromChild.lengthSq() > 1e-12 ? axFromChild : _axWorld.set(axisParent[0], axisParent[1], axisParent[2])).normalize();
966
+ let data;
967
+ if (joint.kind === "fixed") {
968
+ const pr = parentBody.rotation();
969
+ const cr = childBody.rotation();
970
+ const bodyRel = _q1.set(pr.x, pr.y, pr.z, pr.w).invert().multiply(_q2.set(cr.x, cr.y, cr.z, cr.w)).normalize();
971
+ data = rapier.JointData.fixed(a1, {
972
+ x: bodyRel.x,
973
+ y: bodyRel.y,
974
+ z: bodyRel.z,
975
+ w: bodyRel.w
976
+ }, a2, {
977
+ x: 0,
978
+ y: 0,
979
+ z: 0,
980
+ w: 1
981
+ });
982
+ } else if (joint.kind === "revolute") {
983
+ data = rapier.JointData.revolute(a1, a2, {
984
+ x: ax.x,
985
+ y: ax.y,
986
+ z: ax.z
987
+ });
988
+ if (joint.limits) {
989
+ data.limitsEnabled = true;
990
+ data.limits = [joint.limits[0], joint.limits[1]];
991
+ }
992
+ } else {
993
+ data = rapier.JointData.prismatic(a1, a2, {
994
+ x: ax.x,
995
+ y: ax.y,
996
+ z: ax.z
997
+ });
998
+ if (joint.limits) {
999
+ data.limitsEnabled = true;
1000
+ data.limits = [joint.limits[0], joint.limits[1]];
1001
+ }
1002
+ }
1003
+ const imp = world.createImpulseJoint(data, parentBody, childBody, true);
1004
+ imp.setContactsEnabled(Boolean(joint.enableCollision));
1005
+ const activeDrive = selectMatchingDrive(joint);
1006
+ configureJointDrive(rapier, imp, joint.kind, activeDrive, activeDrive?.positionTarget ?? null);
1007
+ return imp;
1008
+ }
1009
+ function selectMatchingDrive(joint) {
1010
+ if (joint.kind === "fixed") return null;
1011
+ const expectedType = joint.kind === "revolute" ? "angular" : "linear";
1012
+ for (const d of joint.drives) if (d.type === void 0 || d.type === expectedType) return d;
1013
+ return joint.drive;
1014
+ }
1015
+ function configureJointDrive(rapier, imp, kind, drive, targetPos) {
1016
+ if (kind === "fixed" || !drive) return;
1017
+ const unit = imp;
1018
+ unit.configureMotorModel(drive.mode === "force" ? rapier.MotorModel.ForceBased : rapier.MotorModel.AccelerationBased);
1019
+ const effTargetPos = targetPos ?? drive.positionTarget ?? (drive.stiffness !== void 0 && drive.stiffness > 0 ? 0 : null);
1020
+ if (effTargetPos !== null && drive.stiffness !== void 0) {
1021
+ if (drive.velocityTarget !== void 0) unit.configureMotor(effTargetPos, drive.velocityTarget, drive.stiffness, drive.damping ?? 0);
1022
+ else unit.configureMotorPosition(effTargetPos, drive.stiffness, drive.damping ?? 0);
1023
+ } else if (drive.velocityTarget !== void 0) unit.configureMotorVelocity(drive.velocityTarget, drive.damping ?? 0);
1024
+ if (drive.maxForce !== void 0) unit.setMotorMaxForce?.(drive.maxForce);
1025
+ }
1026
+ function measureJointCoordinate(parentBody, childBody, kind, axisParent, anchorParent) {
1027
+ if (!parentBody || !childBody || kind === "fixed") return 0;
1028
+ const pr = parentBody.rotation();
1029
+ const cr = childBody.rotation();
1030
+ _q1.set(pr.x, pr.y, pr.z, pr.w);
1031
+ _q2.set(cr.x, cr.y, cr.z, cr.w);
1032
+ if (kind === "prismatic") {
1033
+ const pt = parentBody.translation();
1034
+ const ct = childBody.translation();
1035
+ _deltaPos.set(anchorParent[0], anchorParent[1], anchorParent[2]).applyQuaternion(_q1);
1036
+ _deltaPos.set(ct.x - (pt.x + _deltaPos.x), ct.y - (pt.y + _deltaPos.y), ct.z - (pt.z + _deltaPos.z));
1037
+ _axWorld.set(axisParent[0], axisParent[1], axisParent[2]).applyQuaternion(_q1).normalize();
1038
+ return _deltaPos.dot(_axWorld);
1039
+ }
1040
+ _qRel.copy(_q1).invert().multiply(_q2).normalize();
1041
+ if (_qRel.w < 0) _qRel.set(-_qRel.x, -_qRel.y, -_qRel.z, -_qRel.w);
1042
+ const sinHalf = _qRel.x * axisParent[0] + _qRel.y * axisParent[1] + _qRel.z * axisParent[2];
1043
+ return 2 * Math.atan2(sinHalf, _qRel.w);
1044
+ }
1045
+ function buildJointRuntime(params) {
1046
+ const { rapier, world, nodeName, role, kind, object, axisParent, anchorParent, limits, drive, breakaway, rapierJoint, parentBody, childBody } = params;
1047
+ const rt = {
1048
+ nodeName,
1049
+ role,
1050
+ kind,
1051
+ object,
1052
+ axis: new THREE.Vector3(axisParent[0], axisParent[1], axisParent[2]).normalize(),
1053
+ limits,
1054
+ drive,
1055
+ positionTarget: drive?.positionTarget ?? null,
1056
+ velocityTarget: drive?.velocityTarget ?? 0,
1057
+ rapierJoint,
1058
+ parentBody,
1059
+ childBody,
1060
+ unlatched: false,
1061
+ detached: false,
1062
+ getCoordinate: () => measureJointCoordinate(rt.parentBody, rt.childBody, kind, axisParent, anchorParent),
1063
+ applyTarget: (target) => {
1064
+ if (rt.detached || !rt.rapierJoint) return;
1065
+ if (!drive || drive.stiffness === void 0) throw new KhrValidationError(`Joint "${nodeName}" has no authored drive stiffness; cannot set a position target`);
1066
+ rt.unlatched = false;
1067
+ rt.positionTarget = target;
1068
+ configureJointDrive(rapier, rt.rapierJoint, kind, drive, target);
1069
+ if (parentBody.isDynamic()) parentBody.wakeUp();
1070
+ if (childBody.isDynamic()) childBody.wakeUp();
1071
+ },
1072
+ applyImpactImpulse: (impulseNs) => {
1073
+ if (rt.detached || !breakaway || !(impulseNs > 0)) return rt.detached ? "detached" : rt.unlatched ? "unlatched" : "intact";
1074
+ if (impulseNs >= breakaway.breakImpulseNs) {
1075
+ if (world && rt.rapierJoint && world.getImpulseJoint(rt.rapierJoint.handle)) world.removeImpulseJoint(rt.rapierJoint, true);
1076
+ rt.rapierJoint = null;
1077
+ rt.detached = true;
1078
+ rt.unlatched = true;
1079
+ rt.positionTarget = null;
1080
+ const ud = childBody.userData;
1081
+ if (ud?.ecctrl) childBody.userData = {
1082
+ ...ud,
1083
+ ecctrl: {
1084
+ ...ud.ecctrl,
1085
+ excludeVehicleRay: false
1086
+ }
1087
+ };
1088
+ for (let i = 0; i < childBody.numColliders(); i++) {
1089
+ const col = childBody.collider(i);
1090
+ if (col.collisionGroups() === 196605) {
1091
+ col.setCollisionGroups(DETACHED_PANEL_INTERACTION_GROUPS);
1092
+ col.setSolverGroups(DETACHED_PANEL_INTERACTION_GROUPS);
1093
+ }
1094
+ }
1095
+ if (childBody.isDynamic()) childBody.wakeUp();
1096
+ return "detached";
1097
+ }
1098
+ if (breakaway.latchImpulseNs !== void 0 && impulseNs >= breakaway.latchImpulseNs && !rt.unlatched) {
1099
+ rt.unlatched = true;
1100
+ rt.positionTarget = null;
1101
+ if (kind !== "fixed" && rt.rapierJoint) rt.rapierJoint.configureMotorPosition(0, 0, Math.min(drive?.damping ?? 1, 1.5));
1102
+ if (childBody.isDynamic()) childBody.wakeUp();
1103
+ return "unlatched";
1104
+ }
1105
+ return rt.unlatched ? "unlatched" : "intact";
1106
+ }
1107
+ };
1108
+ return rt;
1109
+ }
1110
+ function openTargetForLimits(limits) {
1111
+ return Math.abs(limits[0]) > Math.abs(limits[1]) ? limits[0] : limits[1];
1112
+ }
1113
+ function isJointOpen(rt) {
1114
+ if (!rt.limits) return false;
1115
+ const openTgt = openTargetForLimits(rt.limits);
1116
+ return Math.abs(openTgt) > 1e-6 && Math.abs((rt.positionTarget ?? rt.getCoordinate()) - openTgt) < Math.abs(openTgt) * .5;
1117
+ }
1118
+ // src/KhrAssembly.tsx
1119
+ function toColliderMass(lumped, colMat, colQuat) {
1120
+ const com = new THREE.Vector3().fromArray(lumped.com);
1121
+ const frame = new THREE.Quaternion().fromArray(lumped.inertiaFrame);
1122
+ if (colMat && colQuat) {
1123
+ com.applyMatrix4(colMat.clone().invert());
1124
+ frame.premultiply(colQuat.clone().invert()).normalize();
1125
+ }
1126
+ return {
1127
+ mass: lumped.mass,
1128
+ centerOfMass: {
1129
+ x: com.x,
1130
+ y: com.y,
1131
+ z: com.z
1132
+ },
1133
+ principalAngularInertia: {
1134
+ x: lumped.inertia[0],
1135
+ y: lumped.inertia[1],
1136
+ z: lumped.inertia[2]
1137
+ },
1138
+ angularInertiaLocalFrame: {
1139
+ x: frame.x,
1140
+ y: frame.y,
1141
+ z: frame.z,
1142
+ w: frame.w
1143
+ }
1144
+ };
1145
+ }
1146
+ function matrixToRoot(node, sceneRoot) {
1147
+ const out = new THREE.Matrix4();
1148
+ for (let cur = node; cur && cur !== sceneRoot; cur = cur.parent) {
1149
+ if (!cur.parent) throw new KhrValidationError(`Node "${node.name}" is detached from bundle.scene`);
1150
+ cur.updateMatrix();
1151
+ out.premultiply(cur.matrix);
1152
+ }
1153
+ return out;
1154
+ }
1155
+ function isSceneDescendant(node, ancestor) {
1156
+ for (let cur = node; cur; cur = cur.parent) if (cur === ancestor) return true;
1157
+ return false;
1158
+ }
1159
+ function lowestCommonAncestor(nodes, sceneRoot) {
1160
+ let candidate = nodes[0];
1161
+ while (candidate && candidate !== sceneRoot) {
1162
+ if (nodes.every((n) => isSceneDescendant(n, candidate))) return candidate;
1163
+ candidate = candidate.parent ?? sceneRoot;
1164
+ }
1165
+ return sceneRoot;
1166
+ }
1167
+ function planOwnColliders(body, lumped, frameQuat) {
1168
+ const one = new THREE.Vector3(1, 1, 1);
1169
+ const frameMat = frameQuat ? new THREE.Matrix4().makeRotationFromQuaternion(frameQuat) : null;
1170
+ const pos = new THREE.Vector3(), quat = new THREE.Quaternion(), scl = new THREE.Vector3();
1171
+ return body.colliders.map((spec, idx) => {
1172
+ const colQuat = new THREE.Quaternion().fromArray(spec.localQuaternion);
1173
+ const local = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(spec.localPosition), colQuat, one);
1174
+ if (frameMat) local.premultiply(frameMat);
1175
+ local.decompose(pos, quat, scl);
1176
+ quat.normalize();
1177
+ const planned = {
1178
+ spec,
1179
+ position: [
1180
+ pos.x,
1181
+ pos.y,
1182
+ pos.z
1183
+ ],
1184
+ quaternion: [
1185
+ quat.x,
1186
+ quat.y,
1187
+ quat.z,
1188
+ quat.w
1189
+ ]
1190
+ };
1191
+ if (idx === 0 && lumped) planned.massProperties = toColliderMass(lumped, local, quat);
1192
+ return planned;
1193
+ });
1194
+ }
1195
+ function planAssembly(bundle) {
1196
+ const byName = new Map(bundle.bodies.map((b) => [b.nodeName, b]));
1197
+ const rootMemo = /* @__PURE__ */ new Map();
1198
+ const depthMemo = /* @__PURE__ */ new Map();
1199
+ const resolveRootAndDepth = (b, visiting = /* @__PURE__ */ new Set()) => {
1200
+ const cachedRoot = rootMemo.get(b.nodeName);
1201
+ const cachedDepth = depthMemo.get(b.nodeName);
1202
+ if (cachedRoot && cachedDepth !== void 0) return {
1203
+ root: cachedRoot,
1204
+ depth: cachedDepth
1205
+ };
1206
+ if (!b.joint) {
1207
+ rootMemo.set(b.nodeName, b);
1208
+ depthMemo.set(b.nodeName, 0);
1209
+ return {
1210
+ root: b,
1211
+ depth: 0
1212
+ };
1213
+ }
1214
+ if (visiting.has(b.nodeName)) throw new KhrValidationError(`Joint cycle through "${b.nodeName}"`);
1215
+ visiting.add(b.nodeName);
1216
+ const parent = byName.get(b.joint.connectedNodeName);
1217
+ if (!parent) throw new KhrValidationError(`Joint on "${b.nodeName}" targets "${b.joint.connectedNodeName}", which is not a KHR body`);
1218
+ const up = resolveRootAndDepth(parent, visiting);
1219
+ rootMemo.set(b.nodeName, up.root);
1220
+ depthMemo.set(b.nodeName, up.depth + 1);
1221
+ return {
1222
+ root: up.root,
1223
+ depth: up.depth + 1
1224
+ };
1225
+ };
1226
+ for (const b of bundle.bodies) resolveRootAndDepth(b);
1227
+ const plans = bundle.bodies.filter((b) => !b.joint).map((root) => {
1228
+ const invRoot = bodyPoseMatrix(root).clone().invert();
1229
+ const descendants = bundle.bodies.filter((b) => b.joint && rootMemo.get(b.nodeName) === root).sort((a, b) => (depthMemo.get(a.nodeName) ?? 0) - (depthMemo.get(b.nodeName) ?? 0));
1230
+ const partByName = /* @__PURE__ */ new Map();
1231
+ const parts = descendants.map((b) => {
1232
+ const joint = b.joint;
1233
+ const parent = partByName.get(joint.connectedNodeName) ?? null;
1234
+ if (parent && !isSceneDescendant(b.object, parent.spec.object)) throw new KhrValidationError(`Jointed node "${b.nodeName}" must be a scene-graph descendant of its jointed parent "${joint.connectedNodeName}"`);
1235
+ const relParentMat = bodyPoseMatrix(parent ? parent.spec : root).clone().invert().multiply(bodyPoseMatrix(b));
1236
+ const relRootMat = invRoot.clone().multiply(bodyPoseMatrix(b));
1237
+ const rpPos = new THREE.Vector3(), tmpQ = new THREE.Quaternion(), rpScl = new THREE.Vector3();
1238
+ relParentMat.decompose(rpPos, tmpQ, rpScl);
1239
+ const rrPos = new THREE.Vector3(), rrQuat = new THREE.Quaternion();
1240
+ relRootMat.decompose(rrPos, rrQuat, rpScl);
1241
+ rrQuat.normalize();
1242
+ const axChildVec = new THREE.Vector3().fromArray(joint.axis).normalize();
1243
+ const axParentVec = axChildVec.clone().applyQuaternion(rrQuat).normalize();
1244
+ const anchorParent = parent ? [
1245
+ rrPos.x - parent.restRelRootPos[0],
1246
+ rrPos.y - parent.restRelRootPos[1],
1247
+ rrPos.z - parent.restRelRootPos[2]
1248
+ ] : [
1249
+ rpPos.x,
1250
+ rpPos.y,
1251
+ rpPos.z
1252
+ ];
1253
+ const bodyAlignInv = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(b.localPosition), new THREE.Quaternion().fromArray(root.localQuaternion), new THREE.Vector3(1, 1, 1)).invert();
1254
+ const ownLumped = b.isKinematic ? null : computeLumpedMassProps([b], bodyAlignInv);
1255
+ const colliders = planOwnColliders(b, ownLumped, rrQuat);
1256
+ const partMass = ownLumped && colliders.length === 0 ? toColliderMass(ownLumped) : void 0;
1257
+ const plan = {
1258
+ spec: b,
1259
+ joint,
1260
+ parent,
1261
+ restRelParentPos: anchorParent,
1262
+ restRelParentQuat: [
1263
+ rrQuat.x,
1264
+ rrQuat.y,
1265
+ rrQuat.z,
1266
+ rrQuat.w
1267
+ ],
1268
+ restRelRootPos: [
1269
+ rrPos.x,
1270
+ rrPos.y,
1271
+ rrPos.z
1272
+ ],
1273
+ restRelRootQuat: [
1274
+ rrQuat.x,
1275
+ rrQuat.y,
1276
+ rrQuat.z,
1277
+ rrQuat.w
1278
+ ],
1279
+ axisParent: [
1280
+ axParentVec.x,
1281
+ axParentVec.y,
1282
+ axParentVec.z
1283
+ ],
1284
+ axisChild: [
1285
+ axChildVec.x,
1286
+ axChildVec.y,
1287
+ axChildVec.z
1288
+ ],
1289
+ ...partMass ? { partMass } : {},
1290
+ colliders
1291
+ };
1292
+ partByName.set(b.nodeName, plan);
1293
+ return plan;
1294
+ });
1295
+ const rootLumped = root.isKinematic ? null : computeLumpedMassProps([root], invRoot);
1296
+ const colliders = planOwnColliders(root, rootLumped);
1297
+ const rootMass = rootLumped && colliders.length === 0 ? toColliderMass(rootLumped) : void 0;
1298
+ const mountNode = lowestCommonAncestor([root.object, ...descendants.map((d) => d.object)], bundle.scene);
1299
+ const mountInRoot = invRoot.clone().multiply(matrixToRoot(mountNode, bundle.scene));
1300
+ const scenePos = new THREE.Vector3(), sceneQuat = new THREE.Quaternion(), sceneScl = new THREE.Vector3();
1301
+ invRoot.decompose(scenePos, sceneQuat, sceneScl);
1302
+ sceneQuat.normalize();
1303
+ const mountPos = new THREE.Vector3(), mountQuat = new THREE.Quaternion();
1304
+ mountInRoot.decompose(mountPos, mountQuat, sceneScl);
1305
+ mountQuat.normalize();
1306
+ return {
1307
+ spec: root,
1308
+ sceneInRootPos: [
1309
+ scenePos.x,
1310
+ scenePos.y,
1311
+ scenePos.z
1312
+ ],
1313
+ sceneInRootQuat: [
1314
+ sceneQuat.x,
1315
+ sceneQuat.y,
1316
+ sceneQuat.z,
1317
+ sceneQuat.w
1318
+ ],
1319
+ mountNode,
1320
+ mountPosition: [
1321
+ mountPos.x,
1322
+ mountPos.y,
1323
+ mountPos.z
1324
+ ],
1325
+ mountQuaternion: [
1326
+ mountQuat.x,
1327
+ mountQuat.y,
1328
+ mountQuat.z,
1329
+ mountQuat.w
1330
+ ],
1331
+ ...rootMass ? { rootMass } : {},
1332
+ colliders,
1333
+ parts
1334
+ };
1335
+ });
1336
+ for (const a of plans) for (const b of plans) if (a !== b && isSceneDescendant(b.mountNode, a.mountNode)) throw new KhrValidationError(`Root bodies "${a.spec.nodeName}" and "${b.spec.nodeName}" share scene subtree "${a.mountNode.name}"; split them into separate glTF branches`);
1337
+ return plans;
1338
+ }
1339
+ function ArticulatedPartBody({ part, rootSpec, rootPos, rootQuat, parentBody, origin, onBody, onJointReady }) {
1340
+ const { rapier, world } = useRapier();
1341
+ const registry = useContext(JointRegistryContext);
1342
+ const childRef = useRef(null);
1343
+ const rtRef = useRef(null);
1344
+ const [childBody, setChildBody] = React.useState(null);
1345
+ const worldPose = useMemo(() => {
1346
+ const rq = new THREE.Quaternion(rootQuat[0], rootQuat[1], rootQuat[2], rootQuat[3]).normalize();
1347
+ const pos = new THREE.Vector3().fromArray(part.restRelRootPos).applyQuaternion(rq).add(new THREE.Vector3(rootPos[0], rootPos[1], rootPos[2]));
1348
+ return {
1349
+ pos: [
1350
+ pos.x,
1351
+ pos.y,
1352
+ pos.z
1353
+ ],
1354
+ quat: [
1355
+ rq.x,
1356
+ rq.y,
1357
+ rq.z,
1358
+ rq.w
1359
+ ]
1360
+ };
1361
+ }, [
1362
+ part.restRelRootPos,
1363
+ rootPos,
1364
+ rootQuat
1365
+ ]);
1366
+ const assignChildRef = useCallback((rb) => {
1367
+ childRef.current = rb;
1368
+ setChildBody(rb);
1369
+ onBody(part.spec.nodeName, rb);
1370
+ }, [part.spec.nodeName, onBody]);
1371
+ useEffect(() => () => onBody(part.spec.nodeName, null), [part.spec.nodeName, onBody]);
1372
+ useEffect(() => {
1373
+ const pm = part.partMass;
1374
+ if (childBody && pm) {
1375
+ childBody.setAdditionalMassProperties(pm.mass, pm.centerOfMass, pm.principalAngularInertia, pm.angularInertiaLocalFrame, true);
1376
+ childBody.recomputeMassPropertiesFromColliders();
1377
+ }
1378
+ }, [childBody, part.partMass]);
1379
+ useEffect(() => {
1380
+ if (!parentBody || !childBody) return;
1381
+ const imp = createRapierImpulseJoint(rapier, world, parentBody, childBody, part.joint, part.restRelParentPos, [
1382
+ 0,
1383
+ 0,
1384
+ 0
1385
+ ], part.axisParent, part.axisChild, part.restRelParentQuat);
1386
+ const rt = buildJointRuntime({
1387
+ rapier,
1388
+ world,
1389
+ nodeName: part.spec.nodeName,
1390
+ role: part.joint.role,
1391
+ kind: part.joint.kind,
1392
+ object: part.spec.object,
1393
+ axisParent: part.axisParent,
1394
+ anchorParent: part.restRelParentPos,
1395
+ limits: part.joint.limits,
1396
+ drive: part.joint.drive,
1397
+ breakaway: part.spec.breakaway,
1398
+ rapierJoint: imp,
1399
+ parentBody,
1400
+ childBody
1401
+ });
1402
+ rtRef.current = rt;
1403
+ registry?.add(rt);
1404
+ onJointReady(rt.nodeName, part.spec.object, rt);
1405
+ return () => {
1406
+ rtRef.current = null;
1407
+ registry?.delete(rt);
1408
+ onJointReady(rt.nodeName, part.spec.object, null);
1409
+ if (rt.rapierJoint && world.getImpulseJoint(rt.rapierJoint.handle)) world.removeImpulseJoint(rt.rapierJoint, true);
1410
+ };
1411
+ }, [
1412
+ rapier,
1413
+ world,
1414
+ part,
1415
+ parentBody,
1416
+ childBody,
1417
+ registry,
1418
+ onJointReady
1419
+ ]);
1420
+ const onForce = useMemo(() => part.spec.breakaway ? (p) => {
1421
+ if (world.timestep > 0) rtRef.current?.applyImpactImpulse(p.totalForceMagnitude * world.timestep);
1422
+ } : void 0, [part.spec.breakaway, world]);
1423
+ const linVel = part.spec.linearVelocity ?? rootSpec.linearVelocity;
1424
+ const angVel = part.spec.angularVelocity ?? rootSpec.angularVelocity;
1425
+ const gravScale = part.spec.gravityFactor ?? rootSpec.gravityFactor;
1426
+ return /* @__PURE__ */ jsxs(RigidBody, {
1427
+ ref: assignChildRef,
1428
+ type: part.spec.isKinematic ? "kinematicPosition" : "dynamic",
1429
+ position: worldPose.pos,
1430
+ quaternion: worldPose.quat,
1431
+ colliders: false,
1432
+ onContactForce: onForce,
1433
+ ...linVel ? { linearVelocity: linVel } : {},
1434
+ ...angVel ? { angularVelocity: angVel } : {},
1435
+ ...gravScale === void 0 ? {} : { gravityScale: gravScale },
1436
+ children: [/* @__PURE__ */ jsx(MountSubtreeSlot, {
1437
+ object: part.spec.object,
1438
+ position: [
1439
+ 0,
1440
+ 0,
1441
+ 0
1442
+ ],
1443
+ quaternion: part.restRelRootQuat,
1444
+ origin
1445
+ }), part.colliders.map((col, cIdx) => /* @__PURE__ */ jsx(KhrCollider, {
1446
+ c: col.spec,
1447
+ position: col.position,
1448
+ quaternion: col.quaternion,
1449
+ massProperties: col.massProperties
1450
+ }, `${part.spec.nodeName}:${cIdx}`))]
1451
+ });
1452
+ }
1453
+ function AssemblyRootBody({ plan, bundleScene, position, quaternion, fixedRoot, rigidBodyProps, onBody, onJointReady, children }) {
1454
+ const [rootBody, setRootBody] = React.useState(null);
1455
+ const [partBodies, setPartBodies] = React.useState(() => /* @__PURE__ */ new Map());
1456
+ const partOrigins = useMemo(() => plan.parts.length > 0 ? captureSubtreeOrigins(plan.parts.map((p) => p.spec.object), bundleScene) : null, [plan.parts, bundleScene]);
1457
+ const rootSpec = plan.spec;
1458
+ const assignRootRef = useCallback((rb) => {
1459
+ setRootBody(rb);
1460
+ onBody(rootSpec.nodeName, rb);
1461
+ }, [rootSpec.nodeName, onBody]);
1462
+ useEffect(() => () => onBody(rootSpec.nodeName, null), [rootSpec.nodeName, onBody]);
1463
+ useEffect(() => {
1464
+ const rm = plan.rootMass;
1465
+ if (rootBody && rm) {
1466
+ rootBody.setAdditionalMassProperties(rm.mass, rm.centerOfMass, rm.principalAngularInertia, rm.angularInertiaLocalFrame, true);
1467
+ rootBody.recomputeMassPropertiesFromColliders();
1468
+ }
1469
+ }, [rootBody, plan.rootMass]);
1470
+ const handlePartBody = useCallback((nodeName, rb) => {
1471
+ setPartBodies((prev) => {
1472
+ if ((prev.get(nodeName) ?? null) === rb) return prev;
1473
+ const next = new Map(prev);
1474
+ if (rb) next.set(nodeName, rb);
1475
+ else next.delete(nodeName);
1476
+ return next;
1477
+ });
1478
+ onBody(nodeName, rb);
1479
+ }, [onBody]);
1480
+ const bodyType = rootSpec.isKinematic ? fixedRoot ? "fixed" : "kinematicPosition" : "dynamic";
1481
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs(RigidBody, {
1482
+ ...rigidBodyProps,
1483
+ ref: assignRootRef,
1484
+ type: bodyType,
1485
+ position,
1486
+ quaternion,
1487
+ colliders: false,
1488
+ ...rootSpec.linearVelocity ? { linearVelocity: rootSpec.linearVelocity } : {},
1489
+ ...rootSpec.angularVelocity ? { angularVelocity: rootSpec.angularVelocity } : {},
1490
+ ...rootSpec.gravityFactor === void 0 ? {} : { gravityScale: rootSpec.gravityFactor },
1491
+ children: [children, plan.colliders.map((col, idx) => /* @__PURE__ */ jsx(KhrCollider, {
1492
+ c: col.spec,
1493
+ position: col.position,
1494
+ quaternion: col.quaternion,
1495
+ massProperties: col.massProperties
1496
+ }, `r${idx}`))]
1497
+ }), plan.parts.map((part) => /* @__PURE__ */ jsx(ArticulatedPartBody, {
1498
+ part,
1499
+ rootSpec,
1500
+ rootPos: position,
1501
+ rootQuat: quaternion,
1502
+ parentBody: part.parent ? partBodies.get(part.parent.spec.nodeName) ?? null : rootBody,
1503
+ origin: partOrigins?.get(part.spec.object),
1504
+ onBody: handlePartBody,
1505
+ onJointReady
1506
+ }, part.spec.nodeName))] });
1507
+ }
1508
+ function KhrAssembly({ ref, bundle, position = [
1509
+ 0,
1510
+ 0,
1511
+ 0
1512
+ ], rotation, quaternion, scale, fixedRoot = false, enableCustomGravity = false, rigidBodyProps, children, ...groupProps }) {
1513
+ assertUnitScale(scale, "KhrAssembly");
1514
+ useMemo(() => assertSceneIdentityWorldScale(bundle.scene), [bundle]);
1515
+ const { world } = useRapier();
1516
+ const applyGravityField = useCustomGravity((s) => s.applyGravityField);
1517
+ const plans = useMemo(() => planAssembly(bundle), [bundle]);
1518
+ const origins = useMemo(() => plans.length > 1 ? captureSubtreeOrigins(plans.map((p) => p.mountNode), bundle.scene) : null, [plans, bundle.scene]);
1519
+ const [px, py, pz] = position;
1520
+ const [rx, ry, rz] = rotation ?? [
1521
+ 0,
1522
+ 0,
1523
+ 0
1524
+ ];
1525
+ const [qx, qy, qz, qw] = quaternion ?? [
1526
+ NaN,
1527
+ NaN,
1528
+ NaN,
1529
+ NaN
1530
+ ];
1531
+ const spawnQuat = useMemo(() => quaternion ? new THREE.Quaternion(qx, qy, qz, qw) : new THREE.Quaternion().setFromEuler(new THREE.Euler(rx, ry, rz)), [
1532
+ qx,
1533
+ qy,
1534
+ qz,
1535
+ qw,
1536
+ rx,
1537
+ ry,
1538
+ rz,
1539
+ Boolean(quaternion)
1540
+ ]);
1541
+ const rootPoses = useMemo(() => plans.map((p) => {
1542
+ const pos = new THREE.Vector3().fromArray(p.spec.localPosition).applyQuaternion(spawnQuat).add(new THREE.Vector3(px, py, pz));
1543
+ const quat = spawnQuat.clone().multiply(new THREE.Quaternion().fromArray(p.spec.localQuaternion));
1544
+ return {
1545
+ position: [
1546
+ pos.x,
1547
+ pos.y,
1548
+ pos.z
1549
+ ],
1550
+ quaternion: [
1551
+ quat.x,
1552
+ quat.y,
1553
+ quat.z,
1554
+ quat.w
1555
+ ]
1556
+ };
1557
+ }), [
1558
+ plans,
1559
+ spawnQuat,
1560
+ px,
1561
+ py,
1562
+ pz
1563
+ ]);
1564
+ const bodiesRef = useRef(/* @__PURE__ */ new Map());
1565
+ const jointsRef = useRef(/* @__PURE__ */ new Map());
1566
+ const byObjectRef = useRef(/* @__PURE__ */ new Map());
1567
+ const handleBody = useCallback((nodeName, rb) => {
1568
+ if (rb) bodiesRef.current.set(nodeName, rb);
1569
+ else bodiesRef.current.delete(nodeName);
1570
+ }, []);
1571
+ const handleJointReady = useCallback((nodeName, obj, rt) => {
1572
+ if (rt) {
1573
+ jointsRef.current.set(nodeName, rt);
1574
+ byObjectRef.current.set(obj, rt);
1575
+ } else {
1576
+ jointsRef.current.delete(nodeName);
1577
+ byObjectRef.current.delete(obj);
1578
+ }
1579
+ }, []);
1580
+ useFrame(() => {
1581
+ if (!enableCustomGravity || world.timestep <= 0) return;
1582
+ for (const rb of bodiesRef.current.values()) if (rb.isDynamic()) applyGravityField(rb, world.timestep);
1583
+ });
1584
+ useImperativeHandle(ref, () => ({
1585
+ get jointNames() {
1586
+ return [...jointsRef.current.keys()];
1587
+ },
1588
+ getBody: (nodeName) => bodiesRef.current.get(nodeName) ?? null,
1589
+ getJointRuntime: (nodeName) => jointsRef.current.get(nodeName) ?? null,
1590
+ setJointTarget: (nodeName, target) => {
1591
+ jointsRef.current.get(nodeName)?.applyTarget(target);
1592
+ },
1593
+ setRoleTarget: (role, target) => {
1594
+ for (const rt of jointsRef.current.values()) if (rt.role === role) rt.applyTarget(target);
1595
+ },
1596
+ toggleHitObject: (hit) => {
1597
+ for (let cur = hit; cur; cur = cur.parent) {
1598
+ const rt = byObjectRef.current.get(cur);
1599
+ if (rt && rt.drive?.stiffness !== void 0) {
1600
+ const limits = rt.limits ?? [0, Math.PI / 2];
1601
+ const nextTgt = isJointOpen(rt) ? Math.min(limits[1], Math.max(limits[0], 0)) : openTargetForLimits(limits);
1602
+ rt.applyTarget(nextTgt);
1603
+ return true;
1604
+ }
1605
+ }
1606
+ return false;
1607
+ }
1608
+ }), []);
1609
+ if (plans.length === 1) {
1610
+ const plan = plans[0];
1611
+ return /* @__PURE__ */ jsx("group", {
1612
+ ...groupProps,
1613
+ children: /* @__PURE__ */ jsx(AssemblyRootBody, {
1614
+ plan,
1615
+ bundleScene: bundle.scene,
1616
+ position: rootPoses[0].position,
1617
+ quaternion: rootPoses[0].quaternion,
1618
+ fixedRoot,
1619
+ rigidBodyProps,
1620
+ onBody: handleBody,
1621
+ onJointReady: handleJointReady,
1622
+ children: /* @__PURE__ */ jsxs("group", {
1623
+ position: plan.sceneInRootPos,
1624
+ quaternion: plan.sceneInRootQuat,
1625
+ children: [/* @__PURE__ */ jsx(BundleSceneHost, {
1626
+ bundle,
1627
+ owner: "KhrAssembly"
1628
+ }), children]
1629
+ })
1630
+ }, `${bundle.scene.uuid}:${plan.spec.nodeName}`)
1631
+ });
1632
+ }
1633
+ return /* @__PURE__ */ jsxs("group", {
1634
+ ...groupProps,
1635
+ children: [/* @__PURE__ */ jsxs("group", {
1636
+ position,
1637
+ quaternion: [
1638
+ spawnQuat.x,
1639
+ spawnQuat.y,
1640
+ spawnQuat.z,
1641
+ spawnQuat.w
1642
+ ],
1643
+ children: [/* @__PURE__ */ jsx(BundleSceneHost, {
1644
+ bundle,
1645
+ owner: "KhrAssembly"
1646
+ }), children]
1647
+ }), plans.map((plan, idx) => /* @__PURE__ */ jsx(AssemblyRootBody, {
1648
+ plan,
1649
+ bundleScene: bundle.scene,
1650
+ position: rootPoses[idx].position,
1651
+ quaternion: rootPoses[idx].quaternion,
1652
+ fixedRoot,
1653
+ rigidBodyProps,
1654
+ onBody: handleBody,
1655
+ onJointReady: handleJointReady,
1656
+ children: /* @__PURE__ */ jsx(MountSubtreeSlot, {
1657
+ object: plan.mountNode,
1658
+ position: plan.mountPosition,
1659
+ quaternion: plan.mountQuaternion,
1660
+ origin: origins?.get(plan.mountNode)
1661
+ })
1662
+ }, `${bundle.scene.uuid}:${plan.spec.nodeName}`))]
1663
+ });
1664
+ }
1665
+ export { computeShapeInertia as A, isObj as B, assertSceneIdentityWorldScale as C, computeBodyInertia as D, computeAssemblyMassAndCom as E, JointRegistryContext as F, optFiniteNum as H, KhrValidationError as I, assignRef as L, readFiniteVec3 as M, readUnitQuat as N, computeLumpedMassProps as O, COMBINE_MODES as P, isFiniteNum as R, assertIdentityWorldScale as S, bodyPoseMatrix as T, isPosNum as V, cloneKhrBundle as _, DETACHED_PANEL_INTERACTION_GROUPS as a, releaseBundleMount as b, createRapierImpulseJoint as c, openTargetForLimits as d, KhrCollider as f, claimBundleMount as g, captureSubtreeOrigins as h, ATTACHED_PANEL_INTERACTION_GROUPS as i, extractMeshColliderShape as j, computeRelativePose as k, isJointOpen as l, MountSubtreeSlot as m, planAssembly as n, buildJointRuntime as o, BundleSceneHost as p, toColliderMass as r, configureJointDrive as s, KhrAssembly as t, measureJointCoordinate as u, disposeKhrBundle as v, assertUnitScale as w, restoreSubtreeOrigin as x, registerMountedSubtree as y, isNonNegNum as z };
1666
+
1667
+ //# sourceMappingURL=KhrAssembly-CKW8I_2z.js.map