@khr3/core 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,196 +1,7 @@
1
1
  import { createContext, useCallback, useEffect, useLayoutEffect, useRef } from "react";
2
2
  import { BallCollider, CapsuleCollider, CoefficientCombineRule, ConvexHullCollider, CuboidCollider, CylinderCollider, TrimeshCollider } from "@react-three/rapier";
3
- import * as THREE from "three";
4
3
  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
- }
4
+ import * as THREE from "three";
194
5
  // src/khrConfigTypes.ts
195
6
  var KhrValidationError = class extends Error {
196
7
  constructor(message) {
@@ -198,141 +9,6 @@ var KhrValidationError = class extends Error {
198
9
  this.name = "KhrValidationError";
199
10
  }
200
11
  };
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
12
  // src/khrInertia.ts
337
13
  var SCALE_EPS = 1e-4;
338
14
  function isUnitScalar(v) {
@@ -652,6 +328,7 @@ function cloneKhrBundle(bundle) {
652
328
  anchor1: [...b.joint.anchor1],
653
329
  anchor2: [...b.joint.anchor2]
654
330
  } : null,
331
+ ...b.breakaway ? { breakaway: { ...b.breakaway } } : {},
655
332
  object: remapNode(bundle.scene, b.object, scene)
656
333
  };
657
334
  }),
@@ -776,6 +453,195 @@ function KhrCollider({ c, position, quaternion, massProperties, ref }) {
776
453
  ...common
777
454
  });
778
455
  }
456
+ // src/khrMassProps.ts
457
+ var _pos = new THREE.Vector3();
458
+ var _quat = new THREE.Quaternion();
459
+ var _qExtra = new THREE.Quaternion();
460
+ var _comVec = new THREE.Vector3();
461
+ var _one = new THREE.Vector3(1, 1, 1);
462
+ var _mat = new THREE.Matrix4();
463
+ var _tmpMat = new THREE.Matrix4();
464
+ var _rCom = new THREE.Vector3();
465
+ function bodyPoseMatrix(body, target = new THREE.Matrix4()) {
466
+ _pos.fromArray(body.localPosition);
467
+ _quat.fromArray(body.localQuaternion);
468
+ return target.compose(_pos, _quat, _one);
469
+ }
470
+ function jacobiPrincipalInertia(ixx, iyy, izz, ixy, ixz, iyz) {
471
+ const a = [
472
+ [
473
+ ixx,
474
+ ixy,
475
+ ixz
476
+ ],
477
+ [
478
+ ixy,
479
+ iyy,
480
+ iyz
481
+ ],
482
+ [
483
+ ixz,
484
+ iyz,
485
+ izz
486
+ ]
487
+ ];
488
+ const v = [
489
+ [
490
+ 1,
491
+ 0,
492
+ 0
493
+ ],
494
+ [
495
+ 0,
496
+ 1,
497
+ 0
498
+ ],
499
+ [
500
+ 0,
501
+ 0,
502
+ 1
503
+ ]
504
+ ];
505
+ for (let iter = 0; iter < 32; iter++) {
506
+ const tr = Math.max(a[0][0] + a[1][1] + a[2][2], 0);
507
+ let p = 0, q = 1, maxOff = Math.abs(a[0][1]);
508
+ if (Math.abs(a[0][2]) > maxOff) {
509
+ p = 0;
510
+ q = 2;
511
+ maxOff = Math.abs(a[0][2]);
512
+ }
513
+ if (Math.abs(a[1][2]) > maxOff) {
514
+ p = 1;
515
+ q = 2;
516
+ maxOff = Math.abs(a[1][2]);
517
+ }
518
+ if (maxOff <= 1e-12 * tr) break;
519
+ const apq = a[p][q], app = a[p][p], aqq = a[q][q];
520
+ const tau = (aqq - app) / (2 * apq);
521
+ const t = tau >= 0 ? 1 / (tau + Math.sqrt(1 + tau * tau)) : -1 / (-tau + Math.sqrt(1 + tau * tau));
522
+ const c = 1 / Math.sqrt(1 + t * t), s = t * c;
523
+ const r = 3 - p - q;
524
+ a[p][p] = c * c * app - 2 * s * c * apq + s * s * aqq;
525
+ a[q][q] = s * s * app + 2 * s * c * apq + c * c * aqq;
526
+ a[p][q] = a[q][p] = 0;
527
+ const arp = a[r][p], arq = a[r][q];
528
+ a[r][p] = a[p][r] = c * arp - s * arq;
529
+ a[r][q] = a[q][r] = s * arp + c * arq;
530
+ for (let i = 0; i < 3; i++) {
531
+ const vip = v[i][p], viq = v[i][q];
532
+ v[i][p] = c * vip - s * viq;
533
+ v[i][q] = s * vip + c * viq;
534
+ }
535
+ }
536
+ 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) {
537
+ v[0][2] = -v[0][2];
538
+ v[1][2] = -v[1][2];
539
+ v[2][2] = -v[2][2];
540
+ }
541
+ _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);
542
+ _quat.setFromRotationMatrix(_mat).normalize();
543
+ return {
544
+ inertia: [
545
+ a[0][0],
546
+ a[1][1],
547
+ a[2][2]
548
+ ],
549
+ inertiaFrame: [
550
+ _quat.x,
551
+ _quat.y,
552
+ _quat.z,
553
+ _quat.w
554
+ ]
555
+ };
556
+ }
557
+ function resolvePose(body, invFrame) {
558
+ if (invFrame) {
559
+ _mat.multiplyMatrices(invFrame, bodyPoseMatrix(body, _tmpMat)).decompose(_pos, _quat, _comVec);
560
+ _quat.normalize();
561
+ } else {
562
+ _pos.fromArray(body.localPosition);
563
+ _quat.fromArray(body.localQuaternion).normalize();
564
+ }
565
+ }
566
+ function computeLumpedMassProps(bodies, invFrame) {
567
+ const dyn = bodies.filter((b) => !b.isKinematic && b.mass > 0);
568
+ if (dyn.length === 0) return null;
569
+ let totalMass = 0, mx = 0, my = 0, mz = 0;
570
+ for (const b of dyn) {
571
+ resolvePose(b, invFrame);
572
+ _rCom.fromArray(b.centerOfMass).applyQuaternion(_quat);
573
+ totalMass += b.mass;
574
+ mx += (_pos.x + _rCom.x) * b.mass;
575
+ my += (_pos.y + _rCom.y) * b.mass;
576
+ mz += (_pos.z + _rCom.z) * b.mass;
577
+ }
578
+ if (!(totalMass > 0)) return null;
579
+ const com = [
580
+ mx / totalMass,
581
+ my / totalMass,
582
+ mz / totalMass
583
+ ];
584
+ let ixx = 0, iyy = 0, izz = 0, ixy = 0, ixz = 0, iyz = 0;
585
+ const m = _mat.elements;
586
+ for (const b of dyn) {
587
+ resolvePose(b, invFrame);
588
+ _rCom.fromArray(b.centerOfMass).applyQuaternion(_quat);
589
+ const dx = _pos.x + _rCom.x - com[0];
590
+ const dy = _pos.y + _rCom.y - com[1];
591
+ const dz = _pos.z + _rCom.z - com[2];
592
+ _mat.makeRotationFromQuaternion(_quat.multiply(_qExtra.fromArray(b.inertiaOrientation)));
593
+ const [d0, d1, d2] = b.inertiaDiagonal;
594
+ ixx += m[0] * m[0] * d0 + m[4] * m[4] * d1 + m[8] * m[8] * d2 + b.mass * (dy * dy + dz * dz);
595
+ iyy += m[1] * m[1] * d0 + m[5] * m[5] * d1 + m[9] * m[9] * d2 + b.mass * (dx * dx + dz * dz);
596
+ izz += m[2] * m[2] * d0 + m[6] * m[6] * d1 + m[10] * m[10] * d2 + b.mass * (dx * dx + dy * dy);
597
+ ixy += m[0] * m[1] * d0 + m[4] * m[5] * d1 + m[8] * m[9] * d2 - b.mass * dx * dy;
598
+ ixz += m[0] * m[2] * d0 + m[4] * m[6] * d1 + m[8] * m[10] * d2 - b.mass * dx * dz;
599
+ iyz += m[1] * m[2] * d0 + m[5] * m[6] * d1 + m[9] * m[10] * d2 - b.mass * dy * dz;
600
+ }
601
+ if (dyn.length === 1) {
602
+ const b = dyn[0];
603
+ resolvePose(b, invFrame);
604
+ _quat.multiply(_qExtra.fromArray(b.inertiaOrientation)).normalize();
605
+ return {
606
+ mass: totalMass,
607
+ com,
608
+ inertia: [
609
+ b.inertiaDiagonal[0],
610
+ b.inertiaDiagonal[1],
611
+ b.inertiaDiagonal[2]
612
+ ],
613
+ inertiaFrame: [
614
+ _quat.x,
615
+ _quat.y,
616
+ _quat.z,
617
+ _quat.w
618
+ ]
619
+ };
620
+ }
621
+ const diagSum = Math.max(ixx + iyy + izz, 0);
622
+ if (Math.max(Math.abs(ixy), Math.abs(ixz), Math.abs(iyz)) <= 1e-12 * diagSum) return {
623
+ mass: totalMass,
624
+ com,
625
+ inertia: [
626
+ ixx,
627
+ iyy,
628
+ izz
629
+ ],
630
+ inertiaFrame: [
631
+ 0,
632
+ 0,
633
+ 0,
634
+ 1
635
+ ]
636
+ };
637
+ const { inertia, inertiaFrame } = jacobiPrincipalInertia(ixx, iyy, izz, ixy, ixz, iyz);
638
+ return {
639
+ mass: totalMass,
640
+ com,
641
+ inertia,
642
+ inertiaFrame
643
+ };
644
+ }
779
645
  // src/assemblyPlan.ts
780
646
  function matrixToRoot(node, sceneRoot) {
781
647
  const out = new THREE.Matrix4();
@@ -830,42 +696,45 @@ function toColliderMass(lumped, colMat, colQuat) {
830
696
  }
831
697
  };
832
698
  }
833
- function planBodyColliders(body, relToRoot, lumped) {
699
+ function planOwnColliders(body, lumped) {
834
700
  return body.colliders.map((spec, idx) => {
835
701
  const colQuat = new THREE.Quaternion().fromArray(spec.localQuaternion);
836
702
  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
703
  const planned = {
842
704
  spec,
843
705
  local,
844
706
  position: [
845
- pos.x,
846
- pos.y,
847
- pos.z
707
+ spec.localPosition[0],
708
+ spec.localPosition[1],
709
+ spec.localPosition[2]
848
710
  ],
849
711
  quaternion: [
850
- quat.x,
851
- quat.y,
852
- quat.z,
853
- quat.w
712
+ colQuat.x,
713
+ colQuat.y,
714
+ colQuat.z,
715
+ colQuat.w
854
716
  ]
855
717
  };
856
718
  if (idx === 0 && lumped) planned.massProperties = toColliderMass(lumped, local, colQuat);
857
719
  return planned;
858
720
  });
859
721
  }
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
722
  function isSceneDescendant(node, ancestor) {
865
723
  for (let cur = node; cur; cur = cur.parent) if (cur === ancestor) return true;
866
724
  return false;
867
725
  }
868
- /** Splits a bundle into one rigid body per jointless root; jointed bodies become articulated compound parts of their root. */
726
+ function approxPartInertia(b, axisChild) {
727
+ if (b.joint?.kind === "fixed") return 0;
728
+ if (b.joint?.kind === "prismatic") return b.mass;
729
+ const ax = new THREE.Vector3().fromArray(axisChild).normalize();
730
+ const qInv = new THREE.Quaternion().fromArray(b.inertiaOrientation).invert();
731
+ const axLocal = ax.clone().applyQuaternion(qInv);
732
+ const [d0, d1, d2] = b.inertiaDiagonal;
733
+ const com = new THREE.Vector3().fromArray(b.centerOfMass);
734
+ const along = com.dot(ax);
735
+ return d0 * axLocal.x * axLocal.x + d1 * axLocal.y * axLocal.y + d2 * axLocal.z * axLocal.z + b.mass * (com.lengthSq() - along * along);
736
+ }
737
+ /** Plans independent Rapier bodies for roots and jointed dynamic children connected by Rapier ImpulseJoints. */
869
738
  function planAssembly(bundle) {
870
739
  const byName = new Map(bundle.bodies.map((b) => [b.nodeName, b]));
871
740
  const findRoot = (b, seen = /* @__PURE__ */ new Set()) => {
@@ -886,32 +755,74 @@ function planAssembly(bundle) {
886
755
  const joint = b.joint;
887
756
  const parent = partByName.get(joint.connectedNodeName) ?? null;
888
757
  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));
758
+ const relParentMat = bodyPoseMatrix(parent ? parent.spec : root).clone().invert().multiply(bodyPoseMatrix(b));
759
+ const relRootMat = invRoot.clone().multiply(bodyPoseMatrix(b));
760
+ const rpPos = new THREE.Vector3(), rpQuat = new THREE.Quaternion(), rpScl = new THREE.Vector3();
761
+ relParentMat.decompose(rpPos, rpQuat, rpScl);
762
+ rpQuat.normalize();
763
+ const rrPos = new THREE.Vector3(), rrQuat = new THREE.Quaternion();
764
+ relRootMat.decompose(rrPos, rrQuat, rpScl);
765
+ rrQuat.normalize();
766
+ const axChildVec = new THREE.Vector3().fromArray(joint.axis).normalize();
767
+ const axParentVec = axChildVec.clone().applyQuaternion(rpQuat).normalize();
768
+ const axisChild = [
769
+ axChildVec.x,
770
+ axChildVec.y,
771
+ axChildVec.z
772
+ ];
773
+ const axisParent = [
774
+ axParentVec.x,
775
+ axParentVec.y,
776
+ axParentVec.z
777
+ ];
778
+ const ownLumped = b.isKinematic ? null : computeLumpedMassProps([b], bodyPoseMatrix(b).clone().invert());
779
+ const colliders = planOwnColliders(b, ownLumped);
780
+ const partMass = ownLumped && colliders.length === 0 ? toColliderMass(ownLumped) : void 0;
890
781
  const plan = {
891
782
  spec: b,
892
783
  joint,
893
784
  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)
785
+ restRelParentPos: [
786
+ rpPos.x,
787
+ rpPos.y,
788
+ rpPos.z
789
+ ],
790
+ restRelParentQuat: [
791
+ rpQuat.x,
792
+ rpQuat.y,
793
+ rpQuat.z,
794
+ rpQuat.w
795
+ ],
796
+ restRelRootPos: [
797
+ rrPos.x,
798
+ rrPos.y,
799
+ rrPos.z
800
+ ],
801
+ restRelRootQuat: [
802
+ rrQuat.x,
803
+ rrQuat.y,
804
+ rrQuat.z,
805
+ rrQuat.w
806
+ ],
807
+ axisParent,
808
+ axisChild,
809
+ inertia: approxPartInertia(b, axisChild),
810
+ ...partMass ? { partMass } : {},
811
+ colliders
897
812
  };
898
813
  partByName.set(b.nodeName, plan);
899
814
  return plan;
900
815
  });
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;
816
+ const rootLumped = root.isKinematic ? null : computeLumpedMassProps([root], invRoot);
817
+ const colliders = planOwnColliders(root, rootLumped);
818
+ const rootMass = rootLumped && colliders.length === 0 ? toColliderMass(rootLumped) : void 0;
904
819
  const mountNode = lowestCommonAncestor([root.object, ...descendants.map((d) => d.object)], bundle.scene);
905
820
  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();
821
+ const scenePos = new THREE.Vector3(), sceneQuat = new THREE.Quaternion(), sceneScl = new THREE.Vector3();
909
822
  invRoot.decompose(scenePos, sceneQuat, sceneScl);
910
823
  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);
824
+ const mountPos = new THREE.Vector3(), mountQuat = new THREE.Quaternion();
825
+ mountInRoot.decompose(mountPos, mountQuat, sceneScl);
915
826
  mountQuat.normalize();
916
827
  return {
917
828
  spec: root,
@@ -1031,6 +942,144 @@ function MountSubtreeSlot({ object, position, quaternion, origin }) {
1031
942
  quaternion
1032
943
  });
1033
944
  }
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 };
945
+ // src/jointDynamics.ts
946
+ var _q1 = new THREE.Quaternion();
947
+ var _q2 = new THREE.Quaternion();
948
+ var _qRel = new THREE.Quaternion();
949
+ var _restInv = 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
+ let data;
964
+ if (joint.kind === "fixed") data = rapier.JointData.fixed(a1, {
965
+ x: restFrameRelQuat[0],
966
+ y: restFrameRelQuat[1],
967
+ z: restFrameRelQuat[2],
968
+ w: restFrameRelQuat[3]
969
+ }, a2, {
970
+ x: 0,
971
+ y: 0,
972
+ z: 0,
973
+ w: 1
974
+ });
975
+ else if (joint.kind === "revolute") {
976
+ const ax = new THREE.Vector3(axisParent[0], axisParent[1], axisParent[2]).normalize();
977
+ data = rapier.JointData.revolute(a1, a2, {
978
+ x: ax.x,
979
+ y: ax.y,
980
+ z: ax.z
981
+ });
982
+ if (joint.limits) {
983
+ data.limitsEnabled = true;
984
+ data.limits = [joint.limits[0], joint.limits[1]];
985
+ }
986
+ } else {
987
+ const ax = new THREE.Vector3(axisParent[0], axisParent[1], axisParent[2]).normalize();
988
+ data = rapier.JointData.prismatic(a1, a2, {
989
+ x: ax.x,
990
+ y: ax.y,
991
+ z: ax.z
992
+ });
993
+ if (joint.limits) {
994
+ data.limitsEnabled = true;
995
+ data.limits = [joint.limits[0], joint.limits[1]];
996
+ }
997
+ }
998
+ const imp = world.createImpulseJoint(data, parentBody, childBody, true);
999
+ imp.setContactsEnabled(Boolean(joint.enableCollision));
1000
+ configureJointDrive(rapier, imp, joint.kind, joint.drive, joint.drive?.positionTarget ?? null);
1001
+ return imp;
1002
+ }
1003
+ function configureJointDrive(rapier, imp, kind, drive, targetPos) {
1004
+ if (kind === "fixed" || !drive) return;
1005
+ const unit = imp;
1006
+ unit.configureMotorModel(drive.mode === "force" ? rapier.MotorModel.ForceBased : rapier.MotorModel.AccelerationBased);
1007
+ if (targetPos !== null && drive.stiffness !== void 0) unit.configureMotorPosition(targetPos, drive.stiffness, drive.damping ?? 0);
1008
+ else if (drive.velocityTarget !== void 0) unit.configureMotorVelocity(drive.velocityTarget, drive.damping ?? 0);
1009
+ }
1010
+ function measureJointCoordinate(parentBody, childBody, kind, axisParent, anchorParent, restRelQuat) {
1011
+ if (!parentBody || !childBody || kind === "fixed") return 0;
1012
+ const pr = parentBody.rotation();
1013
+ const cr = childBody.rotation();
1014
+ _q1.set(pr.x, pr.y, pr.z, pr.w);
1015
+ _q2.set(cr.x, cr.y, cr.z, cr.w);
1016
+ if (kind === "prismatic") {
1017
+ const pt = parentBody.translation();
1018
+ const ct = childBody.translation();
1019
+ _deltaPos.set(anchorParent[0], anchorParent[1], anchorParent[2]).applyQuaternion(_q1);
1020
+ _deltaPos.set(ct.x - (pt.x + _deltaPos.x), ct.y - (pt.y + _deltaPos.y), ct.z - (pt.z + _deltaPos.z));
1021
+ _axWorld.set(axisParent[0], axisParent[1], axisParent[2]).applyQuaternion(_q1).normalize();
1022
+ return _deltaPos.dot(_axWorld);
1023
+ }
1024
+ _restInv.set(restRelQuat[0], restRelQuat[1], restRelQuat[2], restRelQuat[3]).invert();
1025
+ _qRel.copy(_q1).invert().multiply(_q2).premultiply(_restInv).normalize();
1026
+ if (_qRel.w < 0) _qRel.set(-_qRel.x, -_qRel.y, -_qRel.z, -_qRel.w);
1027
+ const sinHalf = _qRel.x * axisParent[0] + _qRel.y * axisParent[1] + _qRel.z * axisParent[2];
1028
+ return 2 * Math.atan2(sinHalf, _qRel.w);
1029
+ }
1030
+ function buildJointRuntime(params) {
1031
+ const { rapier, world, nodeName, role, kind, object, axisParent, anchorParent, restRelQuat, limits, drive, breakaway, rapierJoint, parentBody, childBody } = params;
1032
+ const rt = {
1033
+ nodeName,
1034
+ role,
1035
+ kind,
1036
+ object,
1037
+ axis: new THREE.Vector3(axisParent[0], axisParent[1], axisParent[2]).normalize(),
1038
+ limits,
1039
+ drive,
1040
+ positionTarget: drive?.positionTarget ?? null,
1041
+ velocityTarget: drive?.velocityTarget ?? 0,
1042
+ rapierJoint,
1043
+ parentBody,
1044
+ childBody,
1045
+ unlatched: false,
1046
+ detached: false,
1047
+ getCoordinate: () => measureJointCoordinate(rt.parentBody, rt.childBody, kind, axisParent, anchorParent, restRelQuat),
1048
+ applyTarget: (target) => {
1049
+ if (rt.detached || !rt.rapierJoint) return;
1050
+ if (!drive || drive.stiffness === void 0) throw new KhrValidationError(`Joint "${nodeName}" has no authored drive stiffness; cannot set a position target`);
1051
+ rt.unlatched = false;
1052
+ rt.positionTarget = target;
1053
+ configureJointDrive(rapier, rt.rapierJoint, kind, drive, target);
1054
+ if (parentBody.isDynamic()) parentBody.wakeUp();
1055
+ if (childBody.isDynamic()) childBody.wakeUp();
1056
+ },
1057
+ applyImpactImpulse: (impulseNs) => {
1058
+ if (rt.detached || !breakaway || !(impulseNs > 0)) return rt.detached ? "detached" : rt.unlatched ? "unlatched" : "intact";
1059
+ if (impulseNs >= breakaway.breakImpulseNs) {
1060
+ if (world && rt.rapierJoint && world.getImpulseJoint(rt.rapierJoint.handle)) world.removeImpulseJoint(rt.rapierJoint, true);
1061
+ rt.rapierJoint = null;
1062
+ rt.detached = true;
1063
+ rt.unlatched = true;
1064
+ rt.positionTarget = null;
1065
+ if (childBody.isDynamic()) childBody.wakeUp();
1066
+ return "detached";
1067
+ }
1068
+ if (breakaway.latchImpulseNs !== void 0 && impulseNs >= breakaway.latchImpulseNs && !rt.unlatched) {
1069
+ rt.unlatched = true;
1070
+ rt.positionTarget = null;
1071
+ if (kind !== "fixed" && rt.rapierJoint) rt.rapierJoint.configureMotorPosition(0, 0, Math.min(drive?.damping ?? 1, 1.5));
1072
+ if (childBody.isDynamic()) childBody.wakeUp();
1073
+ return "unlatched";
1074
+ }
1075
+ return rt.unlatched ? "unlatched" : "intact";
1076
+ }
1077
+ };
1078
+ return rt;
1079
+ }
1080
+ // src/physicsEcs.ts
1081
+ /** Retained as an optional context export for compatibility; Rapier steps ImpulseJoints natively. */
1082
+ var JointRegistryContext = createContext(null);
1083
+ export { extractMeshColliderShape as C, KhrValidationError as E, computeRelativePose as S, readUnitQuat as T, assertIdentityWorldScale as _, MountSubtreeSlot as a, computeAssemblyMassAndCom as b, planAssembly as c, computeLumpedMassProps as d, KhrCollider as f, releaseBundleMount as g, disposeKhrBundle as h, BundleSceneHost as i, toColliderMass as l, cloneKhrBundle as m, buildJointRuntime as n, captureSubtreeOrigins as o, claimBundleMount as p, createRapierImpulseJoint as r, restoreSubtreeOrigin as s, JointRegistryContext as t, bodyPoseMatrix as u, assertSceneIdentityWorldScale as v, readFiniteVec3 as w, computeBodyInertia as x, assertUnitScale as y };
1035
1084
 
1036
- //# sourceMappingURL=BundleSceneHost-DUqqPtJF.js.map
1085
+ //# sourceMappingURL=physicsEcs-B9XGoZtl.js.map