@khr3/core 0.1.5 → 0.2.0

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 (44) hide show
  1. package/README.md +3 -114
  2. package/dist/BundleSceneHost-DUqqPtJF.js +1036 -0
  3. package/dist/BundleSceneHost-DUqqPtJF.js.map +1 -0
  4. package/dist/KhrCollider.d.ts +1 -1
  5. package/dist/KhrVehicle.d.ts +5 -7
  6. package/dist/PhysicsWorld.d.ts +2 -2
  7. package/dist/assemblyPlan.d.ts +2 -0
  8. package/dist/curves.d.ts +11 -32
  9. package/dist/curves.js +141 -139
  10. package/dist/curves.js.map +1 -0
  11. package/dist/index.d.ts +2 -1
  12. package/dist/index.js +1639 -1240
  13. package/dist/index.js.map +1 -0
  14. package/dist/jointDynamics.d.ts +1 -1
  15. package/dist/khrBundleFinalize.d.ts +14 -0
  16. package/dist/khrConfigTypes.d.ts +62 -0
  17. package/dist/khrExportEncoders.d.ts +8 -0
  18. package/dist/khrExporter.d.ts +2 -1
  19. package/dist/khrExtras.d.ts +3 -3
  20. package/dist/khrGlb.d.ts +23 -0
  21. package/dist/khrJointParser.d.ts +3 -0
  22. package/dist/khrLoader.d.ts +2 -1
  23. package/dist/khrParsers.d.ts +5 -9
  24. package/dist/khrPlugin.d.ts +2 -3
  25. package/dist/khrPluginHelpers.d.ts +4 -0
  26. package/dist/khrRotorDecoders.d.ts +4 -0
  27. package/dist/khrShapeParser.d.ts +8 -0
  28. package/dist/khrTypes.d.ts +11 -103
  29. package/dist/khrVehicleChassis.d.ts +9 -17
  30. package/dist/khrVehicleJointHelpers.d.ts +24 -0
  31. package/dist/khrVehicleJoints.d.ts +18 -0
  32. package/dist/khrVehicleRotors.d.ts +22 -0
  33. package/dist/khrVehicleSlots.d.ts +19 -15
  34. package/dist/khrVehicleTypes.d.ts +52 -0
  35. package/dist/pacejka.d.ts +1 -1
  36. package/dist/physicsEcs.d.ts +2 -7
  37. package/dist/useKhrGlb.d.ts +2 -2
  38. package/dist/vehicle.d.ts +2 -2
  39. package/dist/vehicle.js +757 -451
  40. package/dist/vehicle.js.map +1 -0
  41. package/dist/wheelLoads.d.ts +4 -7
  42. package/docs/api-reference.md +209 -0
  43. package/package.json +8 -7
  44. package/dist/BundleSceneHost-CE3HPB8a.js +0 -556
@@ -0,0 +1,1036 @@
1
+ import { createContext, useCallback, useEffect, useLayoutEffect, useRef } from "react";
2
+ import { BallCollider, CapsuleCollider, CoefficientCombineRule, ConvexHullCollider, CuboidCollider, CylinderCollider, TrimeshCollider } from "@react-three/rapier";
3
+ import * as THREE from "three";
4
+ import { jsx } from "react/jsx-runtime";
5
+ // src/khrMassProps.ts
6
+ var _pos = new THREE.Vector3();
7
+ var _quat = new THREE.Quaternion();
8
+ var _qExtra$1 = new THREE.Quaternion();
9
+ var _comVec = new THREE.Vector3();
10
+ var _one = new THREE.Vector3(1, 1, 1);
11
+ var _mat = new THREE.Matrix4();
12
+ var _tmpMat = new THREE.Matrix4();
13
+ var _rCom = new THREE.Vector3();
14
+ function bodyPoseMatrix(body, target = new THREE.Matrix4()) {
15
+ _pos.fromArray(body.localPosition);
16
+ _quat.fromArray(body.localQuaternion);
17
+ return target.compose(_pos, _quat, _one);
18
+ }
19
+ function jacobiPrincipalInertia(ixx, iyy, izz, ixy, ixz, iyz) {
20
+ const a = [
21
+ [
22
+ ixx,
23
+ ixy,
24
+ ixz
25
+ ],
26
+ [
27
+ ixy,
28
+ iyy,
29
+ iyz
30
+ ],
31
+ [
32
+ ixz,
33
+ iyz,
34
+ izz
35
+ ]
36
+ ];
37
+ const v = [
38
+ [
39
+ 1,
40
+ 0,
41
+ 0
42
+ ],
43
+ [
44
+ 0,
45
+ 1,
46
+ 0
47
+ ],
48
+ [
49
+ 0,
50
+ 0,
51
+ 1
52
+ ]
53
+ ];
54
+ for (let iter = 0; iter < 32; iter++) {
55
+ const tr = Math.max(a[0][0] + a[1][1] + a[2][2], 0);
56
+ let p = 0, q = 1, maxOff = Math.abs(a[0][1]);
57
+ if (Math.abs(a[0][2]) > maxOff) {
58
+ p = 0;
59
+ q = 2;
60
+ maxOff = Math.abs(a[0][2]);
61
+ }
62
+ if (Math.abs(a[1][2]) > maxOff) {
63
+ p = 1;
64
+ q = 2;
65
+ maxOff = Math.abs(a[1][2]);
66
+ }
67
+ if (maxOff <= 1e-12 * tr) break;
68
+ const apq = a[p][q], app = a[p][p], aqq = a[q][q];
69
+ const tau = (aqq - app) / (2 * apq);
70
+ const t = tau >= 0 ? 1 / (tau + Math.sqrt(1 + tau * tau)) : -1 / (-tau + Math.sqrt(1 + tau * tau));
71
+ const c = 1 / Math.sqrt(1 + t * t), s = t * c;
72
+ const r = 3 - p - q;
73
+ a[p][p] = c * c * app - 2 * s * c * apq + s * s * aqq;
74
+ a[q][q] = s * s * app + 2 * s * c * apq + c * c * aqq;
75
+ a[p][q] = a[q][p] = 0;
76
+ const arp = a[r][p], arq = a[r][q];
77
+ a[r][p] = a[p][r] = c * arp - s * arq;
78
+ a[r][q] = a[q][r] = s * arp + c * arq;
79
+ for (let i = 0; i < 3; i++) {
80
+ const vip = v[i][p], viq = v[i][q];
81
+ v[i][p] = c * vip - s * viq;
82
+ v[i][q] = s * vip + c * viq;
83
+ }
84
+ }
85
+ 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) {
86
+ v[0][2] = -v[0][2];
87
+ v[1][2] = -v[1][2];
88
+ v[2][2] = -v[2][2];
89
+ }
90
+ _mat.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);
91
+ _quat.setFromRotationMatrix(_mat).normalize();
92
+ return {
93
+ inertia: [
94
+ a[0][0],
95
+ a[1][1],
96
+ a[2][2]
97
+ ],
98
+ inertiaFrame: [
99
+ _quat.x,
100
+ _quat.y,
101
+ _quat.z,
102
+ _quat.w
103
+ ]
104
+ };
105
+ }
106
+ function resolvePose(body, invFrame) {
107
+ if (invFrame) {
108
+ _mat.multiplyMatrices(invFrame, bodyPoseMatrix(body, _tmpMat)).decompose(_pos, _quat, _comVec);
109
+ _quat.normalize();
110
+ } else {
111
+ _pos.fromArray(body.localPosition);
112
+ _quat.fromArray(body.localQuaternion).normalize();
113
+ }
114
+ }
115
+ function computeLumpedMassProps(bodies, invFrame) {
116
+ const dyn = bodies.filter((b) => !b.isKinematic && b.mass > 0);
117
+ if (dyn.length === 0) return null;
118
+ let totalMass = 0, mx = 0, my = 0, mz = 0;
119
+ for (const b of dyn) {
120
+ resolvePose(b, invFrame);
121
+ _rCom.fromArray(b.centerOfMass).applyQuaternion(_quat);
122
+ totalMass += b.mass;
123
+ mx += (_pos.x + _rCom.x) * b.mass;
124
+ my += (_pos.y + _rCom.y) * b.mass;
125
+ mz += (_pos.z + _rCom.z) * b.mass;
126
+ }
127
+ if (!(totalMass > 0)) return null;
128
+ const com = [
129
+ mx / totalMass,
130
+ my / totalMass,
131
+ mz / totalMass
132
+ ];
133
+ let ixx = 0, iyy = 0, izz = 0, ixy = 0, ixz = 0, iyz = 0;
134
+ const m = _mat.elements;
135
+ for (const b of dyn) {
136
+ resolvePose(b, invFrame);
137
+ _rCom.fromArray(b.centerOfMass).applyQuaternion(_quat);
138
+ const dx = _pos.x + _rCom.x - com[0];
139
+ const dy = _pos.y + _rCom.y - com[1];
140
+ const dz = _pos.z + _rCom.z - com[2];
141
+ _mat.makeRotationFromQuaternion(_quat.multiply(_qExtra$1.fromArray(b.inertiaOrientation)));
142
+ const [d0, d1, d2] = b.inertiaDiagonal;
143
+ ixx += m[0] * m[0] * d0 + m[4] * m[4] * d1 + m[8] * m[8] * d2 + b.mass * (dy * dy + dz * dz);
144
+ iyy += m[1] * m[1] * d0 + m[5] * m[5] * d1 + m[9] * m[9] * d2 + b.mass * (dx * dx + dz * dz);
145
+ izz += m[2] * m[2] * d0 + m[6] * m[6] * d1 + m[10] * m[10] * d2 + b.mass * (dx * dx + dy * dy);
146
+ ixy += m[0] * m[1] * d0 + m[4] * m[5] * d1 + m[8] * m[9] * d2 - b.mass * dx * dy;
147
+ ixz += m[0] * m[2] * d0 + m[4] * m[6] * d1 + m[8] * m[10] * d2 - b.mass * dx * dz;
148
+ iyz += m[1] * m[2] * d0 + m[5] * m[6] * d1 + m[9] * m[10] * d2 - b.mass * dy * dz;
149
+ }
150
+ if (dyn.length === 1) {
151
+ const b = dyn[0];
152
+ resolvePose(b, invFrame);
153
+ _quat.multiply(_qExtra$1.fromArray(b.inertiaOrientation)).normalize();
154
+ return {
155
+ mass: totalMass,
156
+ com,
157
+ inertia: [
158
+ b.inertiaDiagonal[0],
159
+ b.inertiaDiagonal[1],
160
+ b.inertiaDiagonal[2]
161
+ ],
162
+ inertiaFrame: [
163
+ _quat.x,
164
+ _quat.y,
165
+ _quat.z,
166
+ _quat.w
167
+ ]
168
+ };
169
+ }
170
+ const diagSum = Math.max(ixx + iyy + izz, 0);
171
+ if (Math.max(Math.abs(ixy), Math.abs(ixz), Math.abs(iyz)) <= 1e-12 * diagSum) return {
172
+ mass: totalMass,
173
+ com,
174
+ inertia: [
175
+ ixx,
176
+ iyy,
177
+ izz
178
+ ],
179
+ inertiaFrame: [
180
+ 0,
181
+ 0,
182
+ 0,
183
+ 1
184
+ ]
185
+ };
186
+ const { inertia, inertiaFrame } = jacobiPrincipalInertia(ixx, iyy, izz, ixy, ixz, iyz);
187
+ return {
188
+ mass: totalMass,
189
+ com,
190
+ inertia,
191
+ inertiaFrame
192
+ };
193
+ }
194
+ // src/khrConfigTypes.ts
195
+ var KhrValidationError = class extends Error {
196
+ constructor(message) {
197
+ super(message);
198
+ this.name = "KhrValidationError";
199
+ }
200
+ };
201
+ // src/jointDynamics.ts
202
+ var _axis = new THREE.Vector3();
203
+ var _axisInPart = new THREE.Vector3();
204
+ var _com = new THREE.Vector3();
205
+ var _qExtra = new THREE.Quaternion();
206
+ var _qPart = new THREE.Quaternion();
207
+ var _invRoot = new THREE.Matrix4();
208
+ var _relMat = new THREE.Matrix4();
209
+ var _deltaMat = new THREE.Matrix4();
210
+ var _colMat = new THREE.Matrix4();
211
+ var _tmpPos = new THREE.Vector3();
212
+ var _tmpQuat = new THREE.Quaternion();
213
+ var _tmpScale = new THREE.Vector3();
214
+ var _childMat = new THREE.Matrix4();
215
+ /**
216
+ * Effective inertia of a jointed subtree `[body, ...descendants]` about `body`'s joint axis
217
+ * (axis through `body`'s node origin, in `body`'s rest frame).
218
+ * Revolute: Sum_k [ a^T * R_k * diag(I_k) * R_k^T * a + m_k * (|c_k|^2 - (a . c_k)^2) ]. Prismatic: Sum_k m_k.
219
+ */
220
+ function effectiveJointInertia(body, joint, descendants = []) {
221
+ if (joint.kind === "fixed") return 0;
222
+ const subtree = descendants.length > 0 ? [body, ...descendants] : [body];
223
+ if (joint.kind === "prismatic") {
224
+ let m = 0;
225
+ for (const b of subtree) if (!(b.isKinematic && b !== body)) m += b.mass;
226
+ return m;
227
+ }
228
+ _axis.fromArray(joint.axis).normalize();
229
+ if (descendants.length > 0) bodyPoseMatrix(body, _invRoot).invert();
230
+ let total = 0;
231
+ for (const part of subtree) {
232
+ if (part !== body && part.isKinematic) continue;
233
+ if (part === body) {
234
+ _tmpPos.set(0, 0, 0);
235
+ _tmpQuat.identity();
236
+ } else {
237
+ _relMat.multiplyMatrices(_invRoot, bodyPoseMatrix(part, _colMat)).decompose(_tmpPos, _tmpQuat, _tmpScale);
238
+ _tmpQuat.normalize();
239
+ }
240
+ _qPart.copy(_tmpQuat).multiply(_qExtra.fromArray(part.inertiaOrientation)).invert();
241
+ _axisInPart.copy(_axis).applyQuaternion(_qPart);
242
+ const [d0, d1, d2] = part.inertiaDiagonal;
243
+ const iSpin = d0 * _axisInPart.x * _axisInPart.x + d1 * _axisInPart.y * _axisInPart.y + d2 * _axisInPart.z * _axisInPart.z;
244
+ _com.fromArray(part.centerOfMass).applyQuaternion(_tmpQuat).add(_tmpPos);
245
+ const along = _com.dot(_axis);
246
+ total += iSpin + part.mass * (_com.lengthSq() - along * along);
247
+ }
248
+ return total;
249
+ }
250
+ /**
251
+ * Advances one joint by `dt` seconds with the authored KHR drive (implicit spring-damper, unconditionally stable):
252
+ * force mode: I * a = k * (q* - q) + c * (v* - v)
253
+ * acceleration mode: a = k * (q* - q) + c * (v* - v)
254
+ * Soft limits add physical restoring stiffness/damping scaled by `1 / I` outside [min, max];
255
+ * hard limits (`limitStiffness === null`) clamp position and inward-Zero velocity.
256
+ */
257
+ function stepJoint(j, dt) {
258
+ if (j.kind === "fixed" || !(dt > 0)) return;
259
+ const drive = j.drive;
260
+ const isForce = drive?.mode === "force";
261
+ const hasSoftLimit = j.limits !== null && j.limitStiffness !== null;
262
+ if ((isForce || hasSoftLimit) && !(j.inertia > 0)) throw new KhrValidationError(`Joint "${j.nodeName}" requires positive effective inertia (got ${j.inertia})`);
263
+ const invI = isForce ? 1 / j.inertia : 1;
264
+ const k = j.positionTarget !== null && drive?.stiffness !== void 0 ? drive.stiffness * invI : 0;
265
+ const c = drive?.damping === void 0 ? 0 : drive.damping * invI;
266
+ let kLim = 0, cLim = 0, qBound = 0;
267
+ if (j.limits && j.limitStiffness !== null && (j.q < j.limits[0] || j.q > j.limits[1])) {
268
+ qBound = j.q < j.limits[0] ? j.limits[0] : j.limits[1];
269
+ const invILim = 1 / j.inertia;
270
+ kLim = j.limitStiffness * invILim;
271
+ cLim = j.limitDamping * invILim;
272
+ }
273
+ const qStar = j.positionTarget ?? 0;
274
+ let vNext = (j.v + dt * (k * (qStar - j.q) + c * j.velocityTarget + kLim * (qBound - j.q))) / (1 + dt * (c + cLim) + dt * dt * (k + kLim));
275
+ if (drive?.maxForce !== void 0) {
276
+ if (!(drive.maxForce >= 0)) throw new KhrValidationError(`Joint "${j.nodeName}" has negative drive.maxForce ${drive.maxForce}`);
277
+ const maxAccel = isForce ? drive.maxForce / j.inertia : drive.maxForce;
278
+ const accel = k * (qStar - (j.q + dt * vNext)) + c * (j.velocityTarget - vNext);
279
+ if (Math.abs(accel) > maxAccel) {
280
+ const clamped = Math.sign(accel) * maxAccel;
281
+ vNext = (j.v + dt * (clamped + kLim * (qBound - j.q))) / (1 + dt * cLim + dt * dt * kLim);
282
+ }
283
+ }
284
+ j.v = vNext;
285
+ j.q += vNext * dt;
286
+ if (j.limits && j.limitStiffness === null) {
287
+ if (j.q < j.limits[0]) {
288
+ j.q = j.limits[0];
289
+ if (j.v < 0) j.v = 0;
290
+ } else if (j.q > j.limits[1]) {
291
+ j.q = j.limits[1];
292
+ if (j.v > 0) j.v = 0;
293
+ }
294
+ }
295
+ }
296
+ var JOINT_POSE_EPS = 1e-7;
297
+ /** Writes `q` onto the live glTF node and re-poses its compound colliders inside the root body when moved. */
298
+ function writeJointPose(j, frame) {
299
+ if (j.stamp === frame) return;
300
+ if (j.parent && j.parent.stamp !== frame) writeJointPose(j.parent, frame);
301
+ j.stamp = frame;
302
+ const parentDirty = j.parent !== null && j.parent.dirtyStamp === frame;
303
+ const allCollidersReady = j.colliders.every((c) => c.ref.current !== null);
304
+ if (j.lastWrittenQ === void 0 || Math.abs(j.q - j.lastWrittenQ) > JOINT_POSE_EPS || parentDirty) {
305
+ j.dirtyStamp = frame;
306
+ if (allCollidersReady) j.lastWrittenQ = j.q;
307
+ if (j.kind === "revolute") {
308
+ _qExtra.setFromAxisAngle(j.axis, j.q);
309
+ j.object.quaternion.copy(j.restQuaternion).multiply(_qExtra);
310
+ j.object.position.copy(j.restPosition);
311
+ _deltaMat.makeRotationFromQuaternion(_qExtra);
312
+ } else if (j.kind === "prismatic") {
313
+ _axis.copy(j.axis).multiplyScalar(j.q);
314
+ j.object.quaternion.copy(j.restQuaternion);
315
+ j.object.position.copy(_axis).applyQuaternion(j.restQuaternion).add(j.restPosition);
316
+ _deltaMat.makeTranslation(_axis.x, _axis.y, _axis.z);
317
+ } else _deltaMat.identity();
318
+ if (j.parent) j.current.multiplyMatrices(j.parent.current, j.restRelParent);
319
+ else j.current.copy(j.restRelParent);
320
+ j.current.multiply(_deltaMat);
321
+ for (const col of j.colliders) {
322
+ const rapierCol = col.ref.current;
323
+ if (rapierCol) {
324
+ _childMat.multiplyMatrices(j.current, col.local).decompose(_tmpPos, _tmpQuat, _tmpScale);
325
+ rapierCol.setTranslationWrtParent(_tmpPos);
326
+ rapierCol.setRotationWrtParent(_tmpQuat);
327
+ }
328
+ }
329
+ }
330
+ }
331
+ // src/physicsEcs.ts
332
+ /** Zero-dependency joint registry provided by `<PhysicsWorld>` and populated by `<KhrAssembly>` / `<KhrVehicle>`. */
333
+ var JointRegistryContext = createContext(null);
334
+ /** Internal gravity tuple provided by `<PhysicsWorld>` so `<KhrVehicle>` reacts immediately to prop updates. */
335
+ var WorldGravityContext = createContext(null);
336
+ // src/khrInertia.ts
337
+ var SCALE_EPS = 1e-4;
338
+ function isUnitScalar(v) {
339
+ return typeof v === "number" && Number.isFinite(v) && Math.abs(v - 1) <= 1e-9;
340
+ }
341
+ function assertUnitScale(scale, owner) {
342
+ if (scale === void 0) return;
343
+ let ok = false;
344
+ if (typeof scale === "number") ok = isUnitScalar(scale);
345
+ else if (Array.isArray(scale)) ok = scale.length === 3 && scale.every(isUnitScalar);
346
+ else if (typeof scale === "object" && scale && "x" in scale && "y" in scale && "z" in scale) {
347
+ const v = scale;
348
+ ok = isUnitScalar(v.x) && isUnitScalar(v.y) && isUnitScalar(v.z);
349
+ }
350
+ 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`);
351
+ }
352
+ function readFiniteVec3(val, fieldLabel) {
353
+ 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`);
354
+ return [
355
+ val[0],
356
+ val[1],
357
+ val[2]
358
+ ];
359
+ }
360
+ function readUnitQuat(val, fieldLabel) {
361
+ 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`);
362
+ const norm = Math.hypot(val[0], val[1], val[2], val[3]);
363
+ if (!(norm > 1e-6)) throw new KhrValidationError(`Invalid ${fieldLabel}: zero-norm quaternion`);
364
+ return [
365
+ val[0] / norm,
366
+ val[1] / norm,
367
+ val[2] / norm,
368
+ val[3] / norm
369
+ ];
370
+ }
371
+ function assertIdentityWorldScale(obj, nodeName) {
372
+ const ws = obj.getWorldScale(new THREE.Vector3());
373
+ if (!Number.isFinite(ws.x) || !Number.isFinite(ws.y) || !Number.isFinite(ws.z) || Math.abs(ws.x - 1) > SCALE_EPS || Math.abs(ws.y - 1) > SCALE_EPS || Math.abs(ws.z - 1) > SCALE_EPS) throw new KhrValidationError(`Non-identity world scale [${ws.x.toFixed(4)}, ${ws.y.toFixed(4)}, ${ws.z.toFixed(4)}] on "${nodeName}"; bake scale=[1,1,1]`);
374
+ const ls = obj.scale;
375
+ 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]`);
376
+ }
377
+ function assertSceneIdentityWorldScale(root) {
378
+ root.traverse((child) => {
379
+ assertIdentityWorldScale(child, child.name || (child === root ? "gltf.scene" : "unnamed_node"));
380
+ });
381
+ }
382
+ function computeRelativePose(ownerObj, childObj) {
383
+ const ownerPos = ownerObj.getWorldPosition(new THREE.Vector3());
384
+ const ownerInvQuat = ownerObj.getWorldQuaternion(new THREE.Quaternion()).invert();
385
+ const pos = childObj.getWorldPosition(new THREE.Vector3()).sub(ownerPos).applyQuaternion(ownerInvQuat);
386
+ const quat = ownerInvQuat.multiply(childObj.getWorldQuaternion(new THREE.Quaternion()));
387
+ return {
388
+ localPosition: [
389
+ pos.x,
390
+ pos.y,
391
+ pos.z
392
+ ],
393
+ localQuaternion: [
394
+ quat.x,
395
+ quat.y,
396
+ quat.z,
397
+ quat.w
398
+ ]
399
+ };
400
+ }
401
+ function extractMeshColliderShape(targetObj, meshNodeName, convexHull) {
402
+ assertIdentityWorldScale(targetObj, meshNodeName);
403
+ const invOwner = targetObj.matrixWorld.clone().invert();
404
+ const rel = new THREE.Matrix4();
405
+ const v = new THREE.Vector3();
406
+ const verts = [];
407
+ const indices = [];
408
+ targetObj.traverse((child) => {
409
+ const mesh = child;
410
+ if (!mesh.isMesh || !mesh.geometry) return;
411
+ assertIdentityWorldScale(mesh, mesh.name || meshNodeName);
412
+ const posAttr = mesh.geometry.getAttribute("position");
413
+ if (!posAttr || posAttr.count === 0) return;
414
+ rel.multiplyMatrices(invOwner, mesh.matrixWorld);
415
+ const base = verts.length / 3;
416
+ for (let i = 0; i < posAttr.count; i++) {
417
+ v.fromBufferAttribute(posAttr, i).applyMatrix4(rel);
418
+ if (!Number.isFinite(v.x) || !Number.isFinite(v.y) || !Number.isFinite(v.z)) throw new KhrValidationError(`Non-finite vertex in collider mesh "${meshNodeName}"`);
419
+ verts.push(v.x, v.y, v.z);
420
+ }
421
+ const idx = mesh.geometry.getIndex();
422
+ if (idx) for (let i = 0; i < idx.count; i++) indices.push(base + idx.getX(i));
423
+ else for (let i = 0; i < posAttr.count; i++) indices.push(base + i);
424
+ });
425
+ if (verts.length < 9) throw new KhrValidationError(`Collider node "${meshNodeName}" has fewer than 3 vertices`);
426
+ if (convexHull) return {
427
+ type: "convexHull",
428
+ vertices: new Float32Array(verts),
429
+ meshNodeName
430
+ };
431
+ if (indices.length < 3) throw new KhrValidationError(`Trimesh node "${meshNodeName}" has fewer than 3 indices`);
432
+ return {
433
+ type: "trimesh",
434
+ vertices: new Float32Array(verts),
435
+ indices: new Uint32Array(indices),
436
+ meshNodeName
437
+ };
438
+ }
439
+ function unitInertiaForShape(shape) {
440
+ if (shape.type === "box") {
441
+ const [x, y, z] = shape.size;
442
+ return {
443
+ volume: x * y * z,
444
+ centroid: new THREE.Vector3(),
445
+ unitInertia: [
446
+ (y * y + z * z) / 12,
447
+ (x * x + z * z) / 12,
448
+ (x * x + y * y) / 12
449
+ ]
450
+ };
451
+ }
452
+ if (shape.type === "sphere") {
453
+ const r = shape.radius;
454
+ const i = .4 * r * r;
455
+ return {
456
+ volume: 4 / 3 * Math.PI * r * r * r,
457
+ centroid: new THREE.Vector3(),
458
+ unitInertia: [
459
+ i,
460
+ i,
461
+ i
462
+ ]
463
+ };
464
+ }
465
+ if (shape.type === "convexHull" || shape.type === "trimesh") {
466
+ const box = new THREE.Box3();
467
+ const pt = new THREE.Vector3();
468
+ const verts = shape.vertices;
469
+ for (let i = 0; i < verts.length; i += 3) box.expandByPoint(pt.set(verts[i], verts[i + 1], verts[i + 2]));
470
+ const s = box.getSize(new THREE.Vector3());
471
+ return {
472
+ volume: s.x * s.y * s.z,
473
+ centroid: box.getCenter(new THREE.Vector3()),
474
+ unitInertia: [
475
+ (s.y * s.y + s.z * s.z) / 12,
476
+ (s.x * s.x + s.z * s.z) / 12,
477
+ (s.x * s.x + s.y * s.y) / 12
478
+ ]
479
+ };
480
+ }
481
+ const r = shape.radiusTop;
482
+ const h = shape.height;
483
+ if (shape.type === "capsule") {
484
+ const cylVol = Math.PI * r * r * h;
485
+ const totVol = cylVol + 4 / 3 * Math.PI * r * r * r;
486
+ const fc = cylVol / totVol;
487
+ const fh = 1 - fc;
488
+ const iy = .5 * fc * r * r + .4 * fh * r * r;
489
+ const ix = fc * (h * h / 12 + .25 * r * r) + fh * (.4 * r * r + .25 * h * h + .375 * h * r);
490
+ return {
491
+ volume: totVol,
492
+ centroid: new THREE.Vector3(),
493
+ unitInertia: [
494
+ ix,
495
+ iy,
496
+ ix
497
+ ]
498
+ };
499
+ }
500
+ const ix = (3 * r * r + h * h) / 12;
501
+ return {
502
+ volume: Math.PI * r * r * h,
503
+ centroid: new THREE.Vector3(),
504
+ unitInertia: [
505
+ ix,
506
+ .5 * r * r,
507
+ ix
508
+ ]
509
+ };
510
+ }
511
+ function computeBodyInertia(colliders, mass, centerOfMass, inertiaOrientation, nodeName) {
512
+ if (colliders.length === 0) throw new KhrValidationError(`Dynamic node "${nodeName}" is missing motion.inertiaDiagonal and has no colliders`);
513
+ const shapes = colliders.map((c) => unitInertiaForShape(c.shape));
514
+ let totalVol = 0;
515
+ for (const s of shapes) totalVol += s.volume;
516
+ const invFrame = new THREE.Quaternion().fromArray(inertiaOrientation).invert();
517
+ const com = new THREE.Vector3().fromArray(centerOfMass);
518
+ const colQuat = new THREE.Quaternion();
519
+ const relQuat = new THREE.Quaternion();
520
+ const offset = new THREE.Vector3();
521
+ const rotMat = new THREE.Matrix4();
522
+ const m = rotMat.elements;
523
+ let ix = 0, iy = 0, iz = 0;
524
+ for (let i = 0; i < colliders.length; i++) {
525
+ const col = colliders[i];
526
+ const shp = shapes[i];
527
+ const mShare = totalVol > 0 ? mass * (shp.volume / totalVol) : mass / colliders.length;
528
+ colQuat.fromArray(col.localQuaternion);
529
+ offset.copy(shp.centroid).applyQuaternion(colQuat).add(new THREE.Vector3().fromArray(col.localPosition)).sub(com).applyQuaternion(invFrame);
530
+ relQuat.copy(invFrame).multiply(colQuat);
531
+ rotMat.makeRotationFromQuaternion(relQuat);
532
+ const [u0, u1, u2] = shp.unitInertia;
533
+ const rx = m[0] * m[0] * u0 + m[4] * m[4] * u1 + m[8] * m[8] * u2;
534
+ const ry = m[1] * m[1] * u0 + m[5] * m[5] * u1 + m[9] * m[9] * u2;
535
+ const rz = m[2] * m[2] * u0 + m[6] * m[6] * u1 + m[10] * m[10] * u2;
536
+ ix += mShare * (rx + offset.y * offset.y + offset.z * offset.z);
537
+ iy += mShare * (ry + offset.x * offset.x + offset.z * offset.z);
538
+ iz += mShare * (rz + offset.x * offset.x + offset.y * offset.y);
539
+ }
540
+ 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`);
541
+ return [
542
+ ix,
543
+ iy,
544
+ iz
545
+ ];
546
+ }
547
+ function computeAssemblyMassAndCom(bodies) {
548
+ let totalDynamicMass = 0, mx = 0, my = 0, mz = 0;
549
+ const q = new THREE.Quaternion();
550
+ const c = new THREE.Vector3();
551
+ for (const b of bodies) {
552
+ if (b.isKinematic) continue;
553
+ totalDynamicMass += b.mass;
554
+ c.fromArray(b.centerOfMass).applyQuaternion(q.fromArray(b.localQuaternion));
555
+ mx += (b.localPosition[0] + c.x) * b.mass;
556
+ my += (b.localPosition[1] + c.y) * b.mass;
557
+ mz += (b.localPosition[2] + c.z) * b.mass;
558
+ }
559
+ return {
560
+ totalDynamicMass,
561
+ centerOfMass: totalDynamicMass > 0 ? [
562
+ mx / totalDynamicMass,
563
+ my / totalDynamicMass,
564
+ mz / totalDynamicMass
565
+ ] : [
566
+ 0,
567
+ 0,
568
+ 0
569
+ ]
570
+ };
571
+ }
572
+ // src/khrClone.ts
573
+ var mountedScenes = /* @__PURE__ */ new WeakSet();
574
+ var clonedScenes = /* @__PURE__ */ new WeakSet();
575
+ var disposedScenes = /* @__PURE__ */ new WeakSet();
576
+ function claimBundleMount(bundle, ownerComponent) {
577
+ if (disposedScenes.has(bundle.scene)) throw new KhrValidationError(`${ownerComponent}: KhrAssetBundle "${bundle.scene.name || bundle.scene.uuid}" has already been disposed`);
578
+ 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`);
579
+ mountedScenes.add(bundle.scene);
580
+ }
581
+ function releaseBundleMount(bundle) {
582
+ mountedScenes.delete(bundle.scene);
583
+ }
584
+ function remapNode(srcRoot, node, dstRoot) {
585
+ if (node === srcRoot) return dstRoot;
586
+ const path = [];
587
+ let cur = node;
588
+ while (cur && cur !== srcRoot) {
589
+ const parent = cur.parent;
590
+ if (!parent) throw new KhrValidationError(`cloneKhrBundle: body node "${node.name}" is detached from bundle.scene`);
591
+ const idx = parent.children.indexOf(cur);
592
+ if (idx < 0) throw new KhrValidationError(`cloneKhrBundle: child index missing for "${node.name}"`);
593
+ path.push(idx);
594
+ cur = parent;
595
+ }
596
+ let out = dstRoot;
597
+ for (let i = path.length - 1; i >= 0; i--) out = out.children[path[i]];
598
+ return out;
599
+ }
600
+ function cloneCurve(curve) {
601
+ if (!curve) return void 0;
602
+ return {
603
+ ...curve,
604
+ points: curve.points.map((pt) => ({ ...pt }))
605
+ };
606
+ }
607
+ function cloneCarTune(tune) {
608
+ if (!tune) return void 0;
609
+ return {
610
+ ...tune,
611
+ ...tune.gearRatios ? { gearRatios: [...tune.gearRatios] } : {},
612
+ ...tune.engineTorqueCurveData ? { engineTorqueCurveData: cloneCurve(tune.engineTorqueCurveData) } : {},
613
+ ...tune.steerAngleCurveData ? { steerAngleCurveData: cloneCurve(tune.steerAngleCurveData) } : {}
614
+ };
615
+ }
616
+ /**
617
+ * Clones a parsed `KhrAssetBundle` in O(nodes) without re-parsing `.glb` bytes or duplicating
618
+ * GPU `BufferGeometry` / `Material` buffers or Rapier `Float32Array` collider vertices.
619
+ */
620
+ function cloneKhrBundle(bundle) {
621
+ if (disposedScenes.has(bundle.scene)) throw new KhrValidationError(`cloneKhrBundle: cannot clone disposed KhrAssetBundle "${bundle.scene.name || bundle.scene.uuid}"`);
622
+ const scene = bundle.scene.clone(true);
623
+ clonedScenes.add(scene);
624
+ return {
625
+ scene,
626
+ bodies: bundle.bodies.map((b) => {
627
+ const drives = b.joint ? b.joint.drives.map((d) => ({ ...d })) : [];
628
+ return {
629
+ ...b,
630
+ centerOfMass: [...b.centerOfMass],
631
+ inertiaDiagonal: [...b.inertiaDiagonal],
632
+ inertiaOrientation: [...b.inertiaOrientation],
633
+ ...b.linearVelocity ? { linearVelocity: [...b.linearVelocity] } : {},
634
+ ...b.angularVelocity ? { angularVelocity: [...b.angularVelocity] } : {},
635
+ localPosition: [...b.localPosition],
636
+ localQuaternion: [...b.localQuaternion],
637
+ colliders: b.colliders.map((c) => ({
638
+ ...c,
639
+ shape: c.shape.type === "box" ? {
640
+ ...c.shape,
641
+ size: [...c.shape.size]
642
+ } : { ...c.shape },
643
+ localPosition: [...c.localPosition],
644
+ localQuaternion: [...c.localQuaternion]
645
+ })),
646
+ joint: b.joint ? {
647
+ ...b.joint,
648
+ axis: [...b.joint.axis],
649
+ limits: b.joint.limits ? [...b.joint.limits] : null,
650
+ drive: drives[0] ?? (b.joint.drive ? { ...b.joint.drive } : null),
651
+ drives,
652
+ anchor1: [...b.joint.anchor1],
653
+ anchor2: [...b.joint.anchor2]
654
+ } : null,
655
+ object: remapNode(bundle.scene, b.object, scene)
656
+ };
657
+ }),
658
+ wheels: bundle.wheels.map((w) => ({
659
+ ...w,
660
+ object: remapNode(bundle.scene, w.object, scene),
661
+ position: [...w.position],
662
+ ...w.quaternion ? { quaternion: [...w.quaternion] } : {},
663
+ ...w.lngSlipRatioCurveData ? { lngSlipRatioCurveData: cloneCurve(w.lngSlipRatioCurveData) } : {},
664
+ ...w.latSlipRatioCurveData ? { latSlipRatioCurveData: cloneCurve(w.latSlipRatioCurveData) } : {}
665
+ })),
666
+ propellers: bundle.propellers.map((p) => ({
667
+ ...p,
668
+ object: remapNode(bundle.scene, p.object, scene),
669
+ position: [...p.position],
670
+ ...p.quaternion ? { quaternion: [...p.quaternion] } : {}
671
+ })),
672
+ sockets: Object.fromEntries(Object.entries(bundle.sockets).map(([k, v]) => [k, [...v]])),
673
+ totalDynamicMass: bundle.totalDynamicMass,
674
+ centerOfMass: [...bundle.centerOfMass],
675
+ ...bundle.tune ? { tune: cloneCarTune(bundle.tune) } : {},
676
+ ...bundle.droneTune ? { droneTune: { ...bundle.droneTune } } : {}
677
+ };
678
+ }
679
+ /**
680
+ * Releases mount ownership on clones without destroying shared template GPU resources.
681
+ * When called on a root template bundle, disposes unique GPU geometries, materials, and textures once.
682
+ */
683
+ function disposeKhrBundle(bundle) {
684
+ mountedScenes.delete(bundle.scene);
685
+ if (clonedScenes.has(bundle.scene) || disposedScenes.has(bundle.scene)) {
686
+ disposedScenes.add(bundle.scene);
687
+ return;
688
+ }
689
+ disposedScenes.add(bundle.scene);
690
+ const geos = /* @__PURE__ */ new Set();
691
+ const mats = /* @__PURE__ */ new Set();
692
+ const texs = /* @__PURE__ */ new Set();
693
+ const disposeTree = (obj) => {
694
+ obj.traverse((child) => {
695
+ const mesh = child;
696
+ if (mesh.geometry && !geos.has(mesh.geometry)) {
697
+ geos.add(mesh.geometry);
698
+ mesh.geometry.dispose();
699
+ }
700
+ const matList = Array.isArray(mesh.material) ? mesh.material : mesh.material ? [mesh.material] : [];
701
+ for (const mat of matList) if (!mats.has(mat)) {
702
+ mats.add(mat);
703
+ for (const val of Object.values(mat)) if (val && typeof val === "object" && "isTexture" in val && val.isTexture) {
704
+ const tex = val;
705
+ if (!texs.has(tex)) {
706
+ texs.add(tex);
707
+ tex.dispose();
708
+ }
709
+ }
710
+ mat.dispose();
711
+ }
712
+ });
713
+ };
714
+ disposeTree(bundle.scene);
715
+ for (const w of bundle.wheels) disposeTree(w.object);
716
+ for (const p of bundle.propellers) disposeTree(p.object);
717
+ }
718
+ // src/KhrCollider.tsx
719
+ var COMBINE_RULES = {
720
+ average: CoefficientCombineRule.Average,
721
+ minimum: CoefficientCombineRule.Min,
722
+ maximum: CoefficientCombineRule.Max,
723
+ multiply: CoefficientCombineRule.Multiply
724
+ };
725
+ function KhrCollider({ c, position, quaternion, massProperties, ref }) {
726
+ const innerRef = useRef(null);
727
+ const setRef = useCallback((node) => {
728
+ innerRef.current = node;
729
+ if (typeof ref === "function") ref(node);
730
+ else if (ref) ref.current = node;
731
+ }, [ref]);
732
+ useEffect(() => {
733
+ innerRef.current?.parent()?.recomputeMassPropertiesFromColliders();
734
+ }, [c, massProperties]);
735
+ const common = {
736
+ ref: setRef,
737
+ position: position ?? c.localPosition,
738
+ quaternion: quaternion ?? c.localQuaternion,
739
+ ...massProperties ? { massProperties } : { density: 0 },
740
+ ...c.friction === void 0 ? {} : { friction: c.friction },
741
+ ...c.restitution === void 0 ? {} : { restitution: c.restitution },
742
+ ...c.frictionCombine === void 0 ? {} : { frictionCombineRule: COMBINE_RULES[c.frictionCombine] },
743
+ ...c.restitutionCombine === void 0 ? {} : { restitutionCombineRule: COMBINE_RULES[c.restitutionCombine] },
744
+ ...c.collisionGroups === void 0 ? {} : { collisionGroups: c.collisionGroups }
745
+ };
746
+ const { shape } = c;
747
+ if (shape.type === "box") {
748
+ const [sx, sy, sz] = shape.size;
749
+ return /* @__PURE__ */ jsx(CuboidCollider, {
750
+ args: [
751
+ sx * .5,
752
+ sy * .5,
753
+ sz * .5
754
+ ],
755
+ ...common
756
+ });
757
+ }
758
+ if (shape.type === "sphere") return /* @__PURE__ */ jsx(BallCollider, {
759
+ args: [shape.radius],
760
+ ...common
761
+ });
762
+ if (shape.type === "cylinder") return /* @__PURE__ */ jsx(CylinderCollider, {
763
+ args: [shape.height * .5, shape.radiusTop],
764
+ ...common
765
+ });
766
+ if (shape.type === "capsule") return /* @__PURE__ */ jsx(CapsuleCollider, {
767
+ args: [shape.height * .5, shape.radiusTop],
768
+ ...common
769
+ });
770
+ if (shape.type === "convexHull") return /* @__PURE__ */ jsx(ConvexHullCollider, {
771
+ args: [shape.vertices],
772
+ ...common
773
+ });
774
+ return /* @__PURE__ */ jsx(TrimeshCollider, {
775
+ args: [shape.vertices, shape.indices],
776
+ ...common
777
+ });
778
+ }
779
+ // src/assemblyPlan.ts
780
+ function matrixToRoot(node, sceneRoot) {
781
+ const out = new THREE.Matrix4();
782
+ for (let cur = node; cur && cur !== sceneRoot; cur = cur.parent) {
783
+ if (!cur.parent) throw new KhrValidationError(`Node "${node.name}" is detached from bundle.scene`);
784
+ cur.updateMatrix();
785
+ out.premultiply(cur.matrix);
786
+ }
787
+ return out;
788
+ }
789
+ function lowestCommonAncestor(nodes, sceneRoot) {
790
+ const chain = (n) => {
791
+ const list = [];
792
+ for (let cur = n; cur; cur = cur.parent) {
793
+ list.push(cur);
794
+ if (cur === sceneRoot) break;
795
+ }
796
+ return list;
797
+ };
798
+ let shared = new Set(chain(nodes[0]));
799
+ for (let i = 1; i < nodes.length; i++) {
800
+ const setI = new Set(chain(nodes[i]));
801
+ shared = new Set([...shared].filter((x) => setI.has(x)));
802
+ }
803
+ for (const candidate of chain(nodes[0])) if (shared.has(candidate)) return candidate;
804
+ return sceneRoot;
805
+ }
806
+ function toColliderMass(lumped, colMat, colQuat) {
807
+ const com = new THREE.Vector3().fromArray(lumped.com);
808
+ const frame = new THREE.Quaternion().fromArray(lumped.inertiaFrame);
809
+ if (colMat && colQuat) {
810
+ com.applyMatrix4(colMat.clone().invert());
811
+ frame.premultiply(colQuat.clone().invert()).normalize();
812
+ }
813
+ return {
814
+ mass: lumped.mass,
815
+ centerOfMass: {
816
+ x: com.x,
817
+ y: com.y,
818
+ z: com.z
819
+ },
820
+ principalAngularInertia: {
821
+ x: lumped.inertia[0],
822
+ y: lumped.inertia[1],
823
+ z: lumped.inertia[2]
824
+ },
825
+ angularInertiaLocalFrame: {
826
+ x: frame.x,
827
+ y: frame.y,
828
+ z: frame.z,
829
+ w: frame.w
830
+ }
831
+ };
832
+ }
833
+ function planBodyColliders(body, relToRoot, lumped) {
834
+ return body.colliders.map((spec, idx) => {
835
+ const colQuat = new THREE.Quaternion().fromArray(spec.localQuaternion);
836
+ const local = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(spec.localPosition), colQuat, new THREE.Vector3(1, 1, 1));
837
+ const pos = new THREE.Vector3();
838
+ const quat = new THREE.Quaternion();
839
+ const scl = new THREE.Vector3();
840
+ new THREE.Matrix4().multiplyMatrices(relToRoot, local).decompose(pos, quat, scl);
841
+ const planned = {
842
+ spec,
843
+ local,
844
+ position: [
845
+ pos.x,
846
+ pos.y,
847
+ pos.z
848
+ ],
849
+ quaternion: [
850
+ quat.x,
851
+ quat.y,
852
+ quat.z,
853
+ quat.w
854
+ ]
855
+ };
856
+ if (idx === 0 && lumped) planned.massProperties = toColliderMass(lumped, local, colQuat);
857
+ return planned;
858
+ });
859
+ }
860
+ function isJointDescendant(body, ancestorName, byName) {
861
+ for (let cur = body.joint ? byName.get(body.joint.connectedNodeName) : void 0; cur; cur = cur.joint ? byName.get(cur.joint.connectedNodeName) : void 0) if (cur.nodeName === ancestorName) return true;
862
+ return false;
863
+ }
864
+ function isSceneDescendant(node, ancestor) {
865
+ for (let cur = node; cur; cur = cur.parent) if (cur === ancestor) return true;
866
+ return false;
867
+ }
868
+ /** Splits a bundle into one rigid body per jointless root; jointed bodies become articulated compound parts of their root. */
869
+ function planAssembly(bundle) {
870
+ const byName = new Map(bundle.bodies.map((b) => [b.nodeName, b]));
871
+ const findRoot = (b, seen = /* @__PURE__ */ new Set()) => {
872
+ if (!b.joint) return b;
873
+ if (seen.has(b.nodeName)) throw new KhrValidationError(`Joint cycle through "${b.nodeName}"`);
874
+ seen.add(b.nodeName);
875
+ const parent = byName.get(b.joint.connectedNodeName);
876
+ if (!parent) throw new KhrValidationError(`Joint on "${b.nodeName}" targets "${b.joint.connectedNodeName}", which is not a KHR body`);
877
+ return findRoot(parent, seen);
878
+ };
879
+ const plans = bundle.bodies.filter((b) => !b.joint).map((root) => {
880
+ const invRoot = bodyPoseMatrix(root).clone().invert();
881
+ const descendants = bundle.bodies.filter((b) => b.joint && findRoot(b) === root);
882
+ const depthOf = (b) => b.joint ? 1 + depthOf(byName.get(b.joint.connectedNodeName)) : 0;
883
+ descendants.sort((a, b) => depthOf(a) - depthOf(b));
884
+ const partByName = /* @__PURE__ */ new Map();
885
+ const parts = descendants.map((b) => {
886
+ const joint = b.joint;
887
+ const parent = partByName.get(joint.connectedNodeName) ?? null;
888
+ 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}"`);
889
+ const relToRoot = invRoot.clone().multiply(bodyPoseMatrix(b));
890
+ const plan = {
891
+ spec: b,
892
+ joint,
893
+ parent,
894
+ restRelParent: parent ? bodyPoseMatrix(parent.spec).invert().multiply(bodyPoseMatrix(b)) : relToRoot,
895
+ inertia: effectiveJointInertia(b, joint, descendants.filter((d) => d !== b && isJointDescendant(d, b.nodeName, byName))),
896
+ colliders: planBodyColliders(b, relToRoot, null)
897
+ };
898
+ partByName.set(b.nodeName, plan);
899
+ return plan;
900
+ });
901
+ const lumped = root.isKinematic ? null : computeLumpedMassProps([root, ...descendants], invRoot);
902
+ const colliders = planBodyColliders(root, new THREE.Matrix4(), lumped);
903
+ const rootMass = lumped && colliders.length === 0 ? toColliderMass(lumped) : void 0;
904
+ const mountNode = lowestCommonAncestor([root.object, ...descendants.map((d) => d.object)], bundle.scene);
905
+ const mountInRoot = invRoot.clone().multiply(matrixToRoot(mountNode, bundle.scene));
906
+ const scenePos = new THREE.Vector3();
907
+ const sceneQuat = new THREE.Quaternion();
908
+ const sceneScl = new THREE.Vector3();
909
+ invRoot.decompose(scenePos, sceneQuat, sceneScl);
910
+ sceneQuat.normalize();
911
+ const mountPos = new THREE.Vector3();
912
+ const mountQuat = new THREE.Quaternion();
913
+ const mountScl = new THREE.Vector3();
914
+ mountInRoot.decompose(mountPos, mountQuat, mountScl);
915
+ mountQuat.normalize();
916
+ return {
917
+ spec: root,
918
+ sceneInRootPos: [
919
+ scenePos.x,
920
+ scenePos.y,
921
+ scenePos.z
922
+ ],
923
+ sceneInRootQuat: [
924
+ sceneQuat.x,
925
+ sceneQuat.y,
926
+ sceneQuat.z,
927
+ sceneQuat.w
928
+ ],
929
+ mountNode,
930
+ mountInRoot,
931
+ mountPosition: [
932
+ mountPos.x,
933
+ mountPos.y,
934
+ mountPos.z
935
+ ],
936
+ mountQuaternion: [
937
+ mountQuat.x,
938
+ mountQuat.y,
939
+ mountQuat.z,
940
+ mountQuat.w
941
+ ],
942
+ ...rootMass ? { rootMass } : {},
943
+ colliders,
944
+ parts
945
+ };
946
+ });
947
+ 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`);
948
+ return plans;
949
+ }
950
+ // src/BundleSceneHost.tsx
951
+ function captureSubtreeOrigins(objects) {
952
+ const parentOrders = /* @__PURE__ */ new Map();
953
+ const origins = /* @__PURE__ */ new Map();
954
+ for (const obj of objects) {
955
+ const origParent = obj.parent;
956
+ let origOrder = /* @__PURE__ */ new Map();
957
+ let origIndex = -1;
958
+ if (origParent) {
959
+ let order = parentOrders.get(origParent);
960
+ if (!order) {
961
+ order = /* @__PURE__ */ new Map();
962
+ origParent.children.forEach((child, idx) => order.set(child, idx));
963
+ parentOrders.set(origParent, order);
964
+ }
965
+ origOrder = order;
966
+ origIndex = order.get(obj) ?? origParent.children.indexOf(obj);
967
+ }
968
+ origins.set(obj, {
969
+ origParent,
970
+ origIndex,
971
+ origOrder,
972
+ origPos: obj.position.clone(),
973
+ origQuat: obj.quaternion.clone(),
974
+ origScale: obj.scale.clone()
975
+ });
976
+ }
977
+ return origins;
978
+ }
979
+ function restoreSubtreeOrigin(object, snap) {
980
+ object.position.copy(snap.origPos);
981
+ object.quaternion.copy(snap.origQuat);
982
+ object.scale.copy(snap.origScale);
983
+ const { origParent, origIndex, origOrder } = snap;
984
+ if (origParent) {
985
+ origParent.add(object);
986
+ const curIdx = origParent.children.indexOf(object);
987
+ if (curIdx >= 0) origParent.children.splice(curIdx, 1);
988
+ let insertAt = origParent.children.length;
989
+ if (origOrder.size > 0) {
990
+ for (let i = 0; i < origParent.children.length; i++) if ((origOrder.get(origParent.children[i]) ?? Infinity) > origIndex) {
991
+ insertAt = i;
992
+ break;
993
+ }
994
+ } else if (origIndex >= 0) insertAt = Math.min(origIndex, origParent.children.length);
995
+ origParent.children.splice(insertAt, 0, object);
996
+ }
997
+ }
998
+ function BundleSceneHost({ bundle, owner }) {
999
+ const hostRef = useRef(null);
1000
+ useLayoutEffect(() => {
1001
+ const host = hostRef.current;
1002
+ if (!host) return;
1003
+ claimBundleMount(bundle, owner);
1004
+ host.add(bundle.scene);
1005
+ return () => {
1006
+ if (bundle.scene.parent === host) host.remove(bundle.scene);
1007
+ releaseBundleMount(bundle);
1008
+ };
1009
+ }, [bundle, owner]);
1010
+ return /* @__PURE__ */ jsx("group", { ref: hostRef });
1011
+ }
1012
+ function MountSubtreeSlot({ object, position, quaternion, origin }) {
1013
+ const slotRef = useRef(null);
1014
+ useLayoutEffect(() => {
1015
+ const slot = slotRef.current;
1016
+ if (!slot) return;
1017
+ const snap = origin ?? captureSubtreeOrigins([object]).get(object);
1018
+ if (snap.origParent) snap.origParent.remove(object);
1019
+ object.position.set(0, 0, 0);
1020
+ object.quaternion.set(0, 0, 0, 1);
1021
+ object.scale.set(1, 1, 1);
1022
+ slot.add(object);
1023
+ return () => {
1024
+ if (object.parent === slot) slot.remove(object);
1025
+ restoreSubtreeOrigin(object, snap);
1026
+ };
1027
+ }, [object, origin]);
1028
+ return /* @__PURE__ */ jsx("group", {
1029
+ ref: slotRef,
1030
+ position,
1031
+ quaternion
1032
+ });
1033
+ }
1034
+ export { effectiveJointInertia as C, bodyPoseMatrix as D, KhrValidationError as E, computeLumpedMassProps as O, WorldGravityContext as S, writeJointPose as T, computeRelativePose as _, planAssembly as a, readUnitQuat as b, claimBundleMount as c, releaseBundleMount as d, assertIdentityWorldScale as f, computeBodyInertia as g, computeAssemblyMassAndCom as h, restoreSubtreeOrigin as i, cloneKhrBundle as l, assertUnitScale as m, MountSubtreeSlot as n, toColliderMass as o, assertSceneIdentityWorldScale as p, captureSubtreeOrigins as r, KhrCollider as s, BundleSceneHost as t, disposeKhrBundle as u, extractMeshColliderShape as v, stepJoint as w, JointRegistryContext as x, readFiniteVec3 as y };
1035
+
1036
+ //# sourceMappingURL=BundleSceneHost-DUqqPtJF.js.map