@khr3/core 0.2.0 → 0.2.1

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