@khr3/core 0.2.9 → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +5 -175
  2. package/dist/KhrAssembly-CKW8I_2z.js +1667 -0
  3. package/dist/KhrAssembly-CKW8I_2z.js.map +1 -0
  4. package/dist/KhrAssembly.d.ts +46 -8
  5. package/dist/KhrCollider.d.ts +21 -7
  6. package/dist/clone.d.ts +40 -0
  7. package/dist/{khrExporter.d.ts → exporter.d.ts} +2 -2
  8. package/dist/{khrGlb.d.ts → glb.d.ts} +4 -3
  9. package/dist/index.d.ts +10 -10
  10. package/dist/index.js +1548 -343
  11. package/dist/index.js.map +1 -1
  12. package/dist/{khrInertia.d.ts → inertia.d.ts} +22 -8
  13. package/dist/{jointDynamics.d.ts → joints.d.ts} +8 -7
  14. package/dist/loader.d.ts +9 -0
  15. package/dist/types.d.ts +282 -0
  16. package/dist/useKhrGlb.d.ts +6 -1
  17. package/dist/vehicle.d.ts +35 -2
  18. package/dist/vehicle.js +435 -539
  19. package/dist/vehicle.js.map +1 -1
  20. package/dist/wheelLoads.d.ts +5 -4
  21. package/package.json +6 -25
  22. package/AGENTS.md +0 -12
  23. package/CLAUDE.md +0 -8
  24. package/dist/AssemblyRootBody.d.ts +0 -16
  25. package/dist/BundleSceneHost.d.ts +0 -23
  26. package/dist/KhrVehicle.d.ts +0 -20
  27. package/dist/assemblyPlan.d.ts +0 -61
  28. package/dist/curves-Cf8okB-M.js +0 -542
  29. package/dist/curves-Cf8okB-M.js.map +0 -1
  30. package/dist/curves.d.ts +0 -378
  31. package/dist/curves.js +0 -1
  32. package/dist/khrBundleFinalize.d.ts +0 -15
  33. package/dist/khrClone.d.ts +0 -14
  34. package/dist/khrConfigTypes.d.ts +0 -62
  35. package/dist/khrExportEncoders.d.ts +0 -8
  36. package/dist/khrExtras.d.ts +0 -22
  37. package/dist/khrInertia-DgCUCDTx.js +0 -247
  38. package/dist/khrInertia-DgCUCDTx.js.map +0 -1
  39. package/dist/khrJointParser.d.ts +0 -3
  40. package/dist/khrLoader.d.ts +0 -7
  41. package/dist/khrMassProps.d.ts +0 -16
  42. package/dist/khrParsers.d.ts +0 -10
  43. package/dist/khrPlugin.d.ts +0 -8
  44. package/dist/khrPluginHelpers.d.ts +0 -26
  45. package/dist/khrRotorDecoders.d.ts +0 -4
  46. package/dist/khrShapeParser.d.ts +0 -8
  47. package/dist/khrTypes.d.ts +0 -141
  48. package/dist/khrVehicleChassis.d.ts +0 -20
  49. package/dist/khrVehicleJointHelpers.d.ts +0 -37
  50. package/dist/khrVehicleJoints.d.ts +0 -30
  51. package/dist/khrVehicleRotors.d.ts +0 -22
  52. package/dist/khrVehicleSlots.d.ts +0 -41
  53. package/dist/khrVehicleTypes.d.ts +0 -52
  54. package/dist/pacejka.d.ts +0 -22
  55. package/dist/physicsEcs-C00N5zCh.js +0 -914
  56. package/dist/physicsEcs-C00N5zCh.js.map +0 -1
  57. package/dist/physicsEcs.d.ts +0 -25
  58. package/dist/sand3d/sand3dAssemblyHelpers.d.ts +0 -30
  59. package/dist/sand3d/sand3dCavityOps.d.ts +0 -15
  60. package/dist/sand3d/sand3dCompiler.d.ts +0 -121
  61. package/dist/sand3d/sand3dEvaluator.d.ts +0 -80
  62. package/dist/sand3d/sand3dFramesAndEdits.d.ts +0 -30
  63. package/dist/sand3d/sand3dHullAndSweep.d.ts +0 -27
  64. package/dist/sand3d/sand3dParser.d.ts +0 -6
  65. package/dist/sand3d/sand3dPrimitives.d.ts +0 -50
  66. package/dist/sand3d/sand3dProfiles.d.ts +0 -32
  67. package/dist/sand3d/sand3dRecipes.d.ts +0 -5
  68. package/dist/sand3d/sand3dShellOp.d.ts +0 -8
  69. package/dist/sand3d/sand3dSolids.d.ts +0 -32
  70. package/dist/sand3d/sand3dTokenizer.d.ts +0 -8
  71. package/dist/sand3d/sand3dTypes.d.ts +0 -157
  72. package/dist/sand3d-DQ8-OMlo.js +0 -5045
  73. package/dist/sand3d-DQ8-OMlo.js.map +0 -1
  74. package/dist/sand3d.d.ts +0 -23
  75. package/dist/sand3d.js +0 -1
  76. package/docs/api-reference.md +0 -383
package/dist/vehicle.js CHANGED
@@ -1,17 +1,106 @@
1
- import { a as MountSubtreeSlot, d as computeLumpedMassProps, f as KhrCollider, g as registerMountedSubtree, i as BundleSceneHost, l as toColliderMass, n as buildJointRuntime, o as captureSubtreeOrigins, r as createRapierImpulseJoint, s as restoreSubtreeOrigin, t as JointRegistryContext, u as bodyPoseMatrix } from "./physicsEcs-C00N5zCh.js";
2
- import { n as assertSceneIdentityWorldScale, r as assertUnitScale, u as KhrValidationError } from "./khrInertia-DgCUCDTx.js";
3
1
  import { useCallback, useContext, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
2
+ import * as THREE from "three";
4
3
  import { useFrame } from "@react-three/fiber";
5
4
  import { RigidBody, useRapier } from "@react-three/rapier";
6
- import { Fragment, jsx, jsxs } from "react/jsx-runtime";
7
- import * as THREE from "three";
8
- import { EcctrlVehicle, ShapeCastWheel, ThrustPropeller } from "@pinkaphant/ecctrl/vehicle";
9
5
  import { useCustomGravity } from "@pinkaphant/ecctrl/gravity";
10
- // src/khrVehicleChassis.ts
11
- function assertVehicleProps(scale, colliders) {
12
- if (colliders !== void 0) throw new KhrValidationError("KhrVehicle: colliders prop cannot be overridden; edit colliders in the .glb asset");
13
- assertUnitScale(scale, "KhrVehicle");
6
+ import { EcctrlVehicle, ShapeCastWheel, ThrustPropeller } from "@pinkaphant/ecctrl/vehicle";
7
+ import { C as assertSceneIdentityWorldScale, F as JointRegistryContext, I as KhrValidationError, L as assignRef, O as computeLumpedMassProps, T as bodyPoseMatrix, c as createRapierImpulseJoint, d as openTargetForLimits, f as KhrCollider, h as captureSubtreeOrigins, i as ATTACHED_PANEL_INTERACTION_GROUPS, l as isJointOpen, m as MountSubtreeSlot, o as buildJointRuntime, p as BundleSceneHost, r as toColliderMass, w as assertUnitScale, x as restoreSubtreeOrigin, y as registerMountedSubtree } from "./KhrAssembly-CKW8I_2z.js";
8
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
9
+ // src/wheelLoads.ts
10
+ var STANDARD_GRAVITY = 9.81;
11
+ function projectToLowerBoundedSimplex(values, lowerBound, totalSum) {
12
+ const n = values.length;
13
+ const shifted = values.map((v) => v - lowerBound);
14
+ const rem = Math.max(0, totalSum - n * lowerBound);
15
+ const sorted = [...shifted].sort((a, b) => b - a);
16
+ let prefix = 0;
17
+ let k = 0;
18
+ let theta = 0;
19
+ for (let i = 0; i < n; i++) {
20
+ prefix += sorted[i];
21
+ const candidate = (prefix - rem) / (i + 1);
22
+ if (sorted[i] - candidate > 0) {
23
+ k = i + 1;
24
+ theta = candidate;
25
+ }
26
+ }
27
+ if (k === 0) theta = (prefix - rem) / n;
28
+ return shifted.map((v) => lowerBound + Math.max(v - theta, 0));
14
29
  }
30
+ function solveCornerMasses(wheels, totalMassKg, com) {
31
+ const n = wheels.length;
32
+ if (n === 0) return [];
33
+ if (n === 1) return [totalMassKg];
34
+ const mBase = totalMassKg / n;
35
+ const xs = wheels.map((w) => w.position[0] - com[0]);
36
+ const zs = wheels.map((w) => w.position[2] - com[2]);
37
+ const meanX = xs.reduce((s, v) => s + v, 0) / n;
38
+ const meanZ = zs.reduce((s, v) => s + v, 0) / n;
39
+ const cx = xs.map((v) => v - meanX);
40
+ const cz = zs.map((v) => v - meanZ);
41
+ let sxx = 0, szz = 0, sxz = 0;
42
+ for (let i = 0; i < n; i++) {
43
+ sxx += cx[i] * cx[i];
44
+ szz += cz[i] * cz[i];
45
+ sxz += cx[i] * cz[i];
46
+ }
47
+ const bx = -totalMassKg * meanX;
48
+ const bz = -totalMassKg * meanZ;
49
+ const det = sxx * szz - sxz * sxz;
50
+ const trace = sxx + szz;
51
+ let lx = 0, lz = 0;
52
+ if (det > 1e-10 * trace * trace && det > 1e-12) {
53
+ lx = (szz * bx - sxz * bz) / det;
54
+ lz = (sxx * bz - sxz * bx) / det;
55
+ } else if (trace > 1e-10) {
56
+ const angle = .5 * Math.atan2(2 * sxz, sxx - szz);
57
+ const ux = Math.cos(angle);
58
+ const uz = Math.sin(angle);
59
+ const normSq = ux * ux * sxx + 2 * ux * uz * sxz + uz * uz * szz;
60
+ if (normSq > 1e-10) {
61
+ const proj = (ux * bx + uz * bz) / normSq;
62
+ lx = proj * ux;
63
+ lz = proj * uz;
64
+ }
65
+ }
66
+ const raw = wheels.map((_, i) => mBase + lx * cx[i] + lz * cz[i]);
67
+ const mMin = Math.min(.05 * totalMassKg, totalMassKg / n);
68
+ if (raw.every((m) => m >= mMin - 1e-9)) return raw;
69
+ return projectToLowerBoundedSimplex(raw, mMin, totalMassKg);
70
+ }
71
+ /**
72
+ * Distributes `totalMassKg` across N >= 1 wheels around `com`, resolves fallback
73
+ * `springK` / `dampingC` using reference surface gravity `refGravity` (defaulting to `9.81 m/s^2`),
74
+ * and computes natural scene-space `mountPos` (`tag.position + lift`).
75
+ */
76
+ function solveWheelLoads(wheels, totalMassKg, com, dampingRatio = .7, refGravity = STANDARD_GRAVITY) {
77
+ if (wheels.length === 0) return [];
78
+ const effG = refGravity > 1e-4 ? refGravity : STANDARD_GRAVITY;
79
+ const cornerMasses = solveCornerMasses(wheels, totalMassKg, com);
80
+ return wheels.map((tag, i) => {
81
+ const cornerMassKg = cornerMasses[i];
82
+ const springK = tag.springK ?? cornerMassKg * effG / Math.max(tag.sag, 1e-4);
83
+ const dampingC = tag.dampingC ?? 2 * dampingRatio * Math.sqrt(springK * cornerMassKg);
84
+ const lift = Math.max(0, tag.travel - tag.sag);
85
+ const mountOffset = new THREE.Vector3(0, lift, 0);
86
+ if (tag.quaternion) mountOffset.applyQuaternion(new THREE.Quaternion(tag.quaternion[0], tag.quaternion[1], tag.quaternion[2], tag.quaternion[3]).normalize());
87
+ return {
88
+ tag,
89
+ cornerMassKg,
90
+ springK,
91
+ dampingC,
92
+ mountPos: [
93
+ tag.position[0] + mountOffset.x,
94
+ tag.position[1] + mountOffset.y,
95
+ tag.position[2] + mountOffset.z
96
+ ]
97
+ };
98
+ });
99
+ }
100
+ // src/vehicle.tsx
101
+ var UNSPRUNG_CORNER_RATIO = .035;
102
+ var ATTACHED_PANEL_USER_DATA = { ecctrl: { excludeVehicleRay: true } };
103
+ var _samplePos = new THREE.Vector3();
15
104
  function readPosTuple(pos) {
16
105
  if (typeof pos === "number") return [
17
106
  pos,
@@ -33,7 +122,7 @@ function readPosTuple(pos) {
33
122
  }
34
123
  return [
35
124
  0,
36
- .5,
125
+ 0,
37
126
  0
38
127
  ];
39
128
  }
@@ -83,7 +172,7 @@ function readSpawnQuat(rotation, quaternion) {
83
172
  ];
84
173
  }
85
174
  function computeChassisMassProps(bodies) {
86
- const dyn = bodies.filter((b) => !b.isKinematic).filter((b) => b.joint === null);
175
+ const dyn = bodies.filter((b) => !b.isKinematic && b.joint === null);
87
176
  if (dyn.length === 0) throw new KhrValidationError("KhrVehicle: bundle has no dynamic rigid body for the chassis");
88
177
  const lumped = computeLumpedMassProps(dyn);
89
178
  if (!lumped || !(lumped.mass > 0)) throw new KhrValidationError("KhrVehicle: chassis dynamic mass must be positive");
@@ -96,9 +185,7 @@ function computeChassisMassProps(bodies) {
96
185
  }
97
186
  let linearVelocity;
98
187
  if (dyn.some((b) => b.linearVelocity !== void 0)) {
99
- let vx = 0;
100
- let vy = 0;
101
- let vz = 0;
188
+ let vx = 0, vy = 0, vz = 0;
102
189
  for (const b of dyn) {
103
190
  const lv = b.linearVelocity ?? [
104
191
  0,
@@ -115,7 +202,7 @@ function computeChassisMassProps(bodies) {
115
202
  vz / lumped.mass
116
203
  ];
117
204
  }
118
- const rootDyn = dyn.find((b) => !b.joint && b.angularVelocity !== void 0) ?? dyn.find((b) => b.angularVelocity !== void 0);
205
+ const rootDyn = dyn.find((b) => b.angularVelocity !== void 0);
119
206
  const angularVelocity = rootDyn?.angularVelocity ? [
120
207
  rootDyn.angularVelocity[0],
121
208
  rootDyn.angularVelocity[1],
@@ -138,7 +225,7 @@ function buildChassisColliders(bodies, chassis) {
138
225
  const quat = new THREE.Quaternion();
139
226
  const scl = new THREE.Vector3();
140
227
  for (const b of bodies) {
141
- if (b.isKinematic || b.joint !== null) continue;
228
+ if (b.joint !== null || b.isKinematic && b.hasExplicitMotion) continue;
142
229
  const bodyMat = bodyPoseMatrix(b);
143
230
  for (let idx = 0; idx < b.colliders.length; idx++) {
144
231
  const c = b.colliders[idx];
@@ -182,22 +269,111 @@ function computeRotorLocalMatrix(node, scene, center, quaternion) {
182
269
  if (cur !== scene && node !== scene) throw new KhrValidationError(`Rotor node "${node.name}" is not under bundle.scene`);
183
270
  return new THREE.Matrix4().compose(new THREE.Vector3(center[0], center[1], center[2]), quaternion ? new THREE.Quaternion(quaternion[0], quaternion[1], quaternion[2], quaternion[3]).normalize() : new THREE.Quaternion(), new THREE.Vector3(1, 1, 1)).invert().multiply(nodeToScene);
184
271
  }
185
- // src/khrVehicleJointHelpers.ts
186
- /** Membership group 1 (0x0002), filter ~0x0002 (0xfffd): collides with world/actors, never with sibling attached vehicle panels. */
187
- var ATTACHED_PANEL_COLLISION_GROUPS = 196605;
188
- var DETACHED_PANEL_COLLISION_GROUPS = 4294967295;
272
+ function clearSingleWheelInfo(w) {
273
+ w.rayHit = null;
274
+ w.rayHitBody = null;
275
+ w.floatImp.set(0, 0, 0);
276
+ w.lngFricImp.set(0, 0, 0);
277
+ w.latFricImp.set(0, 0, 0);
278
+ w.lngSlipRatio = 0;
279
+ w.latSlipRatio = 0;
280
+ w.slipStrength = 0;
281
+ w.isOnPlatform = false;
282
+ w.effInertia = 0;
283
+ }
284
+ function resetWheelHits(handle, filter) {
285
+ if (!handle) return;
286
+ for (const wheelRef of handle.wheelsInfo.values()) {
287
+ const w = wheelRef.current;
288
+ if (w && (!filter || filter(w.name))) clearSingleWheelInfo(w);
289
+ }
290
+ }
291
+ function resetPropellerOutputs(handle) {
292
+ if (!handle) return;
293
+ for (const propRef of handle.propellersInfo.values()) {
294
+ const p = propRef.current;
295
+ if (!p) continue;
296
+ p.lx = 0;
297
+ p.ly = 0;
298
+ p.lz = 0;
299
+ p.ax = 0;
300
+ p.ay = 0;
301
+ p.az = 0;
302
+ p.thrustDir.set(0, 0, 0);
303
+ p.torqueDir.set(0, 0, 0);
304
+ p.thrustImpulse.set(0, 0, 0);
305
+ p.torqueImpulse.set(0, 0, 0);
306
+ p.finalThrottle = 0;
307
+ p.throttle = 0;
308
+ p.setThrottle?.(0);
309
+ }
310
+ }
311
+ function resetDisabledRotors(handle, opts) {
312
+ if (opts.wheelsAllOff) resetWheelHits(handle);
313
+ else if (opts.frontOff || opts.rearOff) resetWheelHits(handle, (name) => name && opts.frontWheelNames.has(name) ? opts.frontOff : opts.rearOff);
314
+ if (opts.propsOff) resetPropellerOutputs(handle);
315
+ }
316
+ function RotorVisualSlot({ object, center, quaternion, scene, origin }) {
317
+ const slotRef = useRef(null);
318
+ useLayoutEffect(() => {
319
+ const slot = slotRef.current;
320
+ if (!slot?.parent) return;
321
+ const snap = origin ?? captureSubtreeOrigins([object], scene).get(object);
322
+ scene.updateMatrixWorld(true);
323
+ const localMat = computeRotorLocalMatrix(object, scene, center, quaternion);
324
+ if (snap.origParent) snap.origParent.remove(object);
325
+ const pos = new THREE.Vector3(), quat = new THREE.Quaternion(), scl = new THREE.Vector3();
326
+ localMat.decompose(pos, quat, scl);
327
+ object.position.copy(pos);
328
+ object.quaternion.copy(quat.normalize());
329
+ object.scale.copy(scl);
330
+ slot.add(object);
331
+ const untrack = registerMountedSubtree(snap.ownerScene, () => {
332
+ const p = object.position.clone(), q = object.quaternion.clone(), s = object.scale.clone();
333
+ if (object.parent === slot) slot.remove(object);
334
+ restoreSubtreeOrigin(object, snap);
335
+ return () => {
336
+ if (snap.origParent) snap.origParent.remove(object);
337
+ object.position.copy(p);
338
+ object.quaternion.copy(q);
339
+ object.scale.copy(s);
340
+ slot.add(object);
341
+ };
342
+ });
343
+ return () => {
344
+ untrack();
345
+ if (object.parent === slot) slot.remove(object);
346
+ restoreSubtreeOrigin(object, snap);
347
+ };
348
+ }, [
349
+ object,
350
+ center,
351
+ quaternion,
352
+ scene,
353
+ origin
354
+ ]);
355
+ return /* @__PURE__ */ jsx("group", { ref: slotRef });
356
+ }
189
357
  function planVehicleJointParts(bodies) {
190
358
  const dyn = bodies.filter((b) => !b.isKinematic);
191
359
  const byName = new Map(dyn.map((b) => [b.nodeName, b]));
192
360
  const jointed = dyn.filter((b) => b.joint !== null);
193
361
  if (jointed.length === 0) return [];
362
+ const depthMemo = /* @__PURE__ */ new Map();
194
363
  const depthOf = (b, seen = /* @__PURE__ */ new Set()) => {
195
- if (!b.joint) return 0;
364
+ const hit = depthMemo.get(b.nodeName);
365
+ if (hit !== void 0) return hit;
366
+ if (!b.joint) {
367
+ depthMemo.set(b.nodeName, 0);
368
+ return 0;
369
+ }
196
370
  if (seen.has(b.nodeName)) throw new KhrValidationError(`Joint cycle through "${b.nodeName}"`);
197
371
  seen.add(b.nodeName);
198
372
  const parent = byName.get(b.joint.connectedNodeName);
199
373
  if (!parent) throw new KhrValidationError(`Vehicle joint on "${b.nodeName}" targets "${b.joint.connectedNodeName}", which is not a dynamic KHR body`);
200
- return 1 + depthOf(parent, seen);
374
+ const d = 1 + depthOf(parent, seen);
375
+ depthMemo.set(b.nodeName, d);
376
+ return d;
201
377
  };
202
378
  jointed.sort((a, b) => depthOf(a) - depthOf(b));
203
379
  const one = new THREE.Vector3(1, 1, 1);
@@ -209,7 +385,6 @@ function planVehicleJointParts(bodies) {
209
385
  const parent = partByName.get(joint.connectedNodeName) ?? null;
210
386
  const bodyMat = bodyPoseMatrix(b);
211
387
  (parent ? bodyPoseMatrix(parent.spec) : new THREE.Matrix4()).clone().invert().multiply(bodyMat).decompose(rpPos, rpQuat, scl);
212
- rpQuat.normalize();
213
388
  bodyMat.decompose(rcPos, rcQuat, scl);
214
389
  rcQuat.normalize();
215
390
  const axChildVec = new THREE.Vector3().fromArray(joint.axis).normalize();
@@ -235,9 +410,8 @@ function planVehicleJointParts(bodies) {
235
410
  const planned = {
236
411
  spec: spec.collisionGroups === void 0 ? {
237
412
  ...spec,
238
- collisionGroups: ATTACHED_PANEL_COLLISION_GROUPS
413
+ collisionGroups: ATTACHED_PANEL_INTERACTION_GROUPS
239
414
  } : spec,
240
- local,
241
415
  position: [
242
416
  cPos.x,
243
417
  cPos.y,
@@ -292,80 +466,11 @@ function planVehicleJointParts(bodies) {
292
466
  return plan;
293
467
  });
294
468
  }
295
- function openTargetForLimits(limits) {
296
- return Math.abs(limits[0]) > Math.abs(limits[1]) ? limits[0] : limits[1];
297
- }
298
- function isVehicleJointOpen(rt) {
299
- if (!rt.limits) return false;
300
- const openTgt = openTargetForLimits(rt.limits);
301
- return Math.abs(openTgt) > 1e-6 && Math.abs((rt.positionTarget ?? rt.getCoordinate()) - openTgt) < Math.abs(openTgt) * .5;
302
- }
303
- var _pPos = new THREE.Vector3();
304
- var _pQuat = new THREE.Quaternion();
305
- var _rQuat = new THREE.Quaternion();
306
- var _cQuat = new THREE.Quaternion();
307
- var _anchor = new THREE.Vector3();
308
- function shiftAttachedPanels(parts, bodyMap, runtimeMap, dx, dy, dz) {
309
- for (const part of parts) {
310
- const rb = bodyMap.get(part.spec.nodeName);
311
- const rt = runtimeMap.get(part.spec.nodeName);
312
- if (!rb || rt?.detached) continue;
313
- const t = rb.translation();
314
- rb.setTranslation({
315
- x: t.x + dx,
316
- y: t.y + dy,
317
- z: t.z + dz
318
- }, true);
319
- }
320
- }
321
- function syncAttachedPanelsToParent(parts, bodyMap, runtimeMap, parentBody) {
322
- if (!parentBody) return;
323
- const pt = parentBody.translation(), pr = parentBody.rotation(), lv = parentBody.linvel(), av = parentBody.angvel();
324
- _pPos.set(pt.x, pt.y, pt.z);
325
- _pQuat.set(pr.x, pr.y, pr.z, pr.w);
326
- for (const part of parts) {
327
- const rb = bodyMap.get(part.spec.nodeName), rt = runtimeMap.get(part.spec.nodeName);
328
- if (!rb || rt?.detached) continue;
329
- _anchor.fromArray(part.restRelChassisPos).applyQuaternion(_pQuat).add(_pPos);
330
- _cQuat.copy(_pQuat).multiply(_rQuat.fromArray(part.restRelChassisQuat)).normalize();
331
- rb.setTranslation({
332
- x: _anchor.x,
333
- y: _anchor.y,
334
- z: _anchor.z
335
- }, true);
336
- rb.setRotation({
337
- x: _cQuat.x,
338
- y: _cQuat.y,
339
- z: _cQuat.z,
340
- w: _cQuat.w
341
- }, true);
342
- rb.setLinvel(lv, true);
343
- rb.setAngvel(av, true);
344
- }
345
- }
346
- function stepVehicleArticulatedPanels(params) {
347
- const { parts, bodyMap, runtimeMap, detachedCleared, enableCustomGravity, timestep, applyGravityField } = params;
348
- for (const part of parts) {
349
- const rb = bodyMap.get(part.spec.nodeName);
350
- if (!rb) continue;
351
- if (runtimeMap.get(part.spec.nodeName)?.detached && !detachedCleared.has(rb)) {
352
- detachedCleared.add(rb);
353
- rb.userData = {};
354
- const n = rb.numColliders();
355
- for (let i = 0; i < n; i++) if (part.spec.colliders[i]?.collisionGroups === void 0) rb.collider(i).setCollisionGroups(DETACHED_PANEL_COLLISION_GROUPS);
356
- }
357
- if (enableCustomGravity && timestep > 0 && applyGravityField && rb.isDynamic()) applyGravityField(rb, timestep);
358
- }
359
- }
360
- // src/khrVehicleJoints.tsx
361
- var ATTACHED_PANEL_USER_DATA = { ecctrl: { excludeVehicleRay: true } };
362
- function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, linearVelocity, angularVelocity, gravityScale, parentBodyGetter, origin, onBody, onJointReady }) {
469
+ function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, linearVelocity, angularVelocity, gravityScale, parentBody, origin, onBody, onJointReady }) {
363
470
  const { rapier, world } = useRapier();
364
471
  const registry = useContext(JointRegistryContext);
365
- const childRef = useRef(null);
366
472
  const rtRef = useRef(null);
367
- const parentBodyGetterRef = useRef(parentBodyGetter);
368
- parentBodyGetterRef.current = parentBodyGetter;
473
+ const [childBody, setChildBody] = useState(null);
369
474
  const worldPose = useMemo(() => {
370
475
  const sq = new THREE.Quaternion(spawnQuat[0], spawnQuat[1], spawnQuat[2], spawnQuat[3]).normalize();
371
476
  const pos = new THREE.Vector3().fromArray(part.restRelChassisPos).applyQuaternion(sq).add(new THREE.Vector3(spawnPos[0], spawnPos[1], spawnPos[2]));
@@ -387,19 +492,19 @@ function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, linearVelocity, an
387
492
  spawnPos,
388
493
  spawnQuat
389
494
  ]);
390
- useEffect(() => {
391
- onBody(part.spec.nodeName, childRef.current);
392
- return () => onBody(part.spec.nodeName, null);
495
+ const assignChildRef = useCallback((rb) => {
496
+ setChildBody(rb);
497
+ onBody(part.spec.nodeName, rb);
393
498
  }, [part.spec.nodeName, onBody]);
499
+ useEffect(() => () => onBody(part.spec.nodeName, null), [part.spec.nodeName, onBody]);
394
500
  useEffect(() => {
395
- const rb = childRef.current, pm = part.partMass;
396
- if (rb && pm) {
397
- rb.setAdditionalMassProperties(pm.mass, pm.centerOfMass, pm.principalAngularInertia, pm.angularInertiaLocalFrame, true);
398
- rb.recomputeMassPropertiesFromColliders();
501
+ const pm = part.partMass;
502
+ if (childBody && pm) {
503
+ childBody.setAdditionalMassProperties(pm.mass, pm.centerOfMass, pm.principalAngularInertia, pm.angularInertiaLocalFrame, true);
504
+ childBody.recomputeMassPropertiesFromColliders();
399
505
  }
400
- }, [part.partMass]);
506
+ }, [childBody, part.partMass]);
401
507
  useEffect(() => {
402
- const parentBody = parentBodyGetterRef.current(), childBody = childRef.current;
403
508
  if (!parentBody || !childBody) return;
404
509
  const imp = createRapierImpulseJoint(rapier, world, parentBody, childBody, part.joint, part.restRelParentPos, [
405
510
  0,
@@ -415,12 +520,6 @@ function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, linearVelocity, an
415
520
  object: part.spec.object,
416
521
  axisParent: part.axisParent,
417
522
  anchorParent: part.restRelParentPos,
418
- restRelQuat: [
419
- 0,
420
- 0,
421
- 0,
422
- 1
423
- ],
424
523
  limits: part.joint.limits,
425
524
  drive: part.joint.drive,
426
525
  breakaway: part.spec.breakaway,
@@ -441,17 +540,19 @@ function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, linearVelocity, an
441
540
  rapier,
442
541
  world,
443
542
  part,
543
+ parentBody,
544
+ childBody,
444
545
  registry,
445
546
  onJointReady
446
547
  ]);
447
- const onForce = part.spec.breakaway ? (p) => {
448
- rtRef.current?.applyImpactImpulse(p.totalForceMagnitude * Math.max(world.timestep, 1 / 240));
449
- } : void 0;
548
+ const onForce = useMemo(() => part.spec.breakaway ? (p) => {
549
+ if (world.timestep > 0) rtRef.current?.applyImpactImpulse(p.totalForceMagnitude * world.timestep);
550
+ } : void 0, [part.spec.breakaway, world]);
450
551
  const linVel = part.spec.linearVelocity ?? linearVelocity;
451
552
  const angVel = part.spec.angularVelocity ?? angularVelocity;
452
553
  const gravScale = part.spec.gravityFactor ?? gravityScale;
453
554
  return /* @__PURE__ */ jsxs(RigidBody, {
454
- ref: childRef,
555
+ ref: assignChildRef,
455
556
  type: part.spec.isKinematic ? "kinematicPosition" : "dynamic",
456
557
  position: worldPose.pos,
457
558
  quaternion: worldPose.quat,
@@ -478,30 +579,34 @@ function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, linearVelocity, an
478
579
  }, `vj_${part.spec.nodeName}:${cIdx}`))]
479
580
  });
480
581
  }
481
- function KhrVehicleJoints({ bodies, vehicleRef, spawnPos, spawnQuat, enableCustomGravity = false, linearVelocity, angularVelocity, gravityScale, jointsRef }) {
582
+ var _pPos = new THREE.Vector3();
583
+ var _pQuat = new THREE.Quaternion();
584
+ var _rQuat = new THREE.Quaternion();
585
+ var _cQuat = new THREE.Quaternion();
586
+ var _anchor = new THREE.Vector3();
587
+ function KhrVehicleJoints({ bundleScene, bodies, vehicleRef, chassisBody, spawnPos, spawnQuat, enableCustomGravity = false, linearVelocity, angularVelocity, gravityScale, jointsRef }) {
482
588
  const { world } = useRapier();
483
589
  const applyGravityField = useCustomGravity((state) => state.applyGravityField);
484
590
  const parts = useMemo(() => planVehicleJointParts(bodies), [bodies]);
485
- const origins = useMemo(() => parts.length > 0 ? captureSubtreeOrigins(parts.map((p) => p.spec.object)) : null, [parts]);
591
+ const origins = useMemo(() => parts.length > 0 ? captureSubtreeOrigins(parts.map((p) => p.spec.object), bundleScene) : null, [parts, bundleScene]);
486
592
  const bodyMapRef = useRef(/* @__PURE__ */ new Map());
593
+ const [partBodies, setPartBodies] = useState(() => /* @__PURE__ */ new Map());
487
594
  const runtimeMapRef = useRef(/* @__PURE__ */ new Map());
488
595
  const byObjectRef = useRef(/* @__PURE__ */ new Map());
489
- const detachedClearedRef = useRef(/* @__PURE__ */ new WeakSet());
490
596
  useFrame(() => {
491
- if (parts.length === 0) return;
492
- stepVehicleArticulatedPanels({
493
- parts,
494
- bodyMap: bodyMapRef.current,
495
- runtimeMap: runtimeMapRef.current,
496
- detachedCleared: detachedClearedRef.current,
497
- enableCustomGravity,
498
- timestep: world.timestep,
499
- applyGravityField: enableCustomGravity ? applyGravityField : void 0
500
- });
597
+ if (!enableCustomGravity || parts.length === 0 || world.timestep <= 0) return;
598
+ for (const rb of bodyMapRef.current.values()) if (rb.isDynamic()) applyGravityField(rb, world.timestep);
501
599
  });
502
600
  const handleBody = useCallback((nodeName, rb) => {
503
601
  if (rb) bodyMapRef.current.set(nodeName, rb);
504
602
  else bodyMapRef.current.delete(nodeName);
603
+ setPartBodies((prev) => {
604
+ if ((prev.get(nodeName) ?? null) === rb) return prev;
605
+ const next = new Map(prev);
606
+ if (rb) next.set(nodeName, rb);
607
+ else next.delete(nodeName);
608
+ return next;
609
+ });
505
610
  }, []);
506
611
  const handleJointReady = useCallback((nodeName, obj, rt) => {
507
612
  if (rt) {
@@ -532,7 +637,7 @@ function KhrVehicleJoints({ bodies, vehicleRef, spawnPos, spawnQuat, enableCusto
532
637
  for (let cur = hit; cur; cur = cur.parent) {
533
638
  const rt = byObjectRef.current.get(cur);
534
639
  if (rt && rt.limits && rt.drive?.stiffness !== void 0) {
535
- rt.applyTarget(isVehicleJointOpen(rt) ? 0 : openTargetForLimits(rt.limits));
640
+ rt.applyTarget(isJointOpen(rt) ? 0 : openTargetForLimits(rt.limits));
536
641
  return true;
537
642
  }
538
643
  }
@@ -542,11 +647,49 @@ function KhrVehicleJoints({ bodies, vehicleRef, spawnPos, spawnQuat, enableCusto
542
647
  const low = prefix.toLowerCase();
543
648
  const matches = [...runtimeMapRef.current.values()].filter((rt) => rt.limits !== null && rt.drive?.stiffness !== void 0 && ((rt.role ?? "").toLowerCase().startsWith(low) || rt.nodeName.toLowerCase().startsWith(low)));
544
649
  if (matches.length === 0) return;
545
- const anyOpen = matches.some((rt) => isVehicleJointOpen(rt));
650
+ const anyOpen = matches.some((rt) => isJointOpen(rt));
546
651
  for (const rt of matches) rt.applyTarget(anyOpen ? 0 : openTargetForLimits(rt.limits));
547
652
  },
548
- shiftBodies: (dx, dy, dz) => shiftAttachedPanels(parts, bodyMapRef.current, runtimeMapRef.current, dx, dy, dz),
549
- syncBodiesToParent: () => syncAttachedPanelsToParent(parts, bodyMapRef.current, runtimeMapRef.current, vehicleRef.current?.body ?? null)
653
+ shiftBodies: (dx, dy, dz) => {
654
+ for (const part of parts) {
655
+ const rb = bodyMapRef.current.get(part.spec.nodeName);
656
+ const rt = runtimeMapRef.current.get(part.spec.nodeName);
657
+ if (!rb || rt?.detached) continue;
658
+ const t = rb.translation();
659
+ rb.setTranslation({
660
+ x: t.x + dx,
661
+ y: t.y + dy,
662
+ z: t.z + dz
663
+ }, true);
664
+ }
665
+ },
666
+ syncBodiesToParent: () => {
667
+ const parent = vehicleRef.current?.body;
668
+ if (!parent) return;
669
+ const pt = parent.translation(), pr = parent.rotation(), lv = parent.linvel(), av = parent.angvel();
670
+ _pPos.set(pt.x, pt.y, pt.z);
671
+ _pQuat.set(pr.x, pr.y, pr.z, pr.w);
672
+ for (const part of parts) {
673
+ const rb = bodyMapRef.current.get(part.spec.nodeName);
674
+ const rt = runtimeMapRef.current.get(part.spec.nodeName);
675
+ if (!rb || rt?.detached) continue;
676
+ _anchor.fromArray(part.restRelChassisPos).applyQuaternion(_pQuat).add(_pPos);
677
+ _cQuat.copy(_pQuat).multiply(_rQuat.fromArray(part.restRelChassisQuat)).normalize();
678
+ rb.setTranslation({
679
+ x: _anchor.x,
680
+ y: _anchor.y,
681
+ z: _anchor.z
682
+ }, true);
683
+ rb.setRotation({
684
+ x: _cQuat.x,
685
+ y: _cQuat.y,
686
+ z: _cQuat.z,
687
+ w: _cQuat.w
688
+ }, true);
689
+ rb.setLinvel(lv, true);
690
+ rb.setAngvel(av, true);
691
+ }
692
+ }
550
693
  }), [parts, vehicleRef]);
551
694
  if (parts.length === 0) return null;
552
695
  return /* @__PURE__ */ jsx(Fragment, { children: parts.map((part) => /* @__PURE__ */ jsx(VehicleArticulatedPanel, {
@@ -556,395 +699,50 @@ function KhrVehicleJoints({ bodies, vehicleRef, spawnPos, spawnQuat, enableCusto
556
699
  linearVelocity,
557
700
  angularVelocity,
558
701
  gravityScale,
559
- parentBodyGetter: () => part.parent ? bodyMapRef.current.get(part.parent.spec.nodeName) ?? null : vehicleRef.current?.body ?? null,
702
+ parentBody: part.parent ? partBodies.get(part.parent.spec.nodeName) ?? null : chassisBody ?? vehicleRef.current?.body ?? null,
560
703
  origin: origins?.get(part.spec.object),
561
704
  onBody: handleBody,
562
705
  onJointReady: handleJointReady
563
706
  }, part.spec.nodeName)) });
564
707
  }
565
- // src/khrVehicleSlots.tsx
566
- var captureRotorOrigins = captureSubtreeOrigins;
567
- var _samplePos = new THREE.Vector3();
568
- function resetAllWheelHits(handle) {
569
- if (!handle) return;
570
- for (const wheelRef of handle.wheelsInfo.values()) {
571
- const w = wheelRef.current;
572
- if (!w) continue;
573
- w.rayHit = null;
574
- w.rayHitBody = null;
575
- w.floatImp.set(0, 0, 0);
576
- w.lngFricImp.set(0, 0, 0);
577
- w.latFricImp.set(0, 0, 0);
578
- w.lngSlipRatio = 0;
579
- w.latSlipRatio = 0;
580
- w.slipStrength = 0;
581
- w.isOnPlatform = false;
582
- w.effInertia = 0;
583
- }
584
- }
585
- function resetDisabledWheelHits(handle, isDisabled) {
586
- if (!handle) return;
587
- for (const wheelRef of handle.wheelsInfo.values()) {
588
- const w = wheelRef.current;
589
- if (!w || !isDisabled(w.name)) continue;
590
- w.rayHit = null;
591
- w.rayHitBody = null;
592
- w.floatImp.set(0, 0, 0);
593
- w.lngFricImp.set(0, 0, 0);
594
- w.latFricImp.set(0, 0, 0);
595
- w.lngSlipRatio = 0;
596
- w.latSlipRatio = 0;
597
- w.slipStrength = 0;
598
- w.isOnPlatform = false;
599
- w.effInertia = 0;
600
- }
601
- }
602
- function resetAllPropellerOutputs(handle) {
603
- if (!handle) return;
604
- for (const propRef of handle.propellersInfo.values()) {
605
- const p = propRef.current;
606
- if (!p) continue;
607
- p.lx = 0;
608
- p.ly = 0;
609
- p.lz = 0;
610
- p.ax = 0;
611
- p.ay = 0;
612
- p.az = 0;
613
- p.thrustDir.set(0, 0, 0);
614
- p.torqueDir.set(0, 0, 0);
615
- p.thrustImpulse.set(0, 0, 0);
616
- p.torqueImpulse.set(0, 0, 0);
617
- p.finalThrottle = 0;
618
- p.throttle = 0;
619
- p.setThrottle?.(0);
620
- }
621
- }
622
- function resetDisabledRotors(handle, opts) {
623
- if (opts.wheelsAllOff) resetAllWheelHits(handle);
624
- else if (opts.frontOff || opts.rearOff) resetDisabledWheelHits(handle, (name) => name && opts.frontWheelNames.has(name) ? opts.frontOff : opts.rearOff);
625
- if (opts.propsOff) resetAllPropellerOutputs(handle);
626
- }
627
- /**
628
- * Enables `<ShapeCastWheel>` exclusively under positive gravity (`gravityMag > 1e-6`), keeping
629
- * `ShapeCastWheel` internal `smoothedLngImpulse` state finite during 0G flight.
630
- */
631
- function ZeroGWheelGate({ vehicleRef, enable, enableCustomGravity, spawnPos, zeroGRef, onZeroGChange }) {
632
- const { world } = useRapier();
633
- useFrame(() => {
634
- if (!enable) return;
635
- const handle = vehicleRef.current;
636
- let gSq;
637
- if (enableCustomGravity) {
638
- if (handle?.body && !handle.body.isSleeping()) gSq = handle.gravityMag * handle.gravityMag;
639
- else {
640
- const t = handle?.body?.translation();
641
- if (t) _samplePos.set(t.x, t.y, t.z);
642
- else _samplePos.set(spawnPos[0], spawnPos[1], spawnPos[2]);
643
- gSq = useCustomGravity.getState().gravityField(_samplePos).lengthSq();
644
- }
645
- } else {
646
- const g = world.gravity;
647
- gSq = g.x * g.x + g.y * g.y + g.z * g.z;
648
- }
649
- const isZeroG = gSq <= 1e-12;
650
- if (isZeroG !== zeroGRef.current) {
651
- zeroGRef.current = isZeroG;
652
- onZeroGChange(isZeroG);
653
- }
654
- if (isZeroG) resetAllWheelHits(handle);
655
- });
656
- return null;
657
- }
658
- function ZeroGWheelPostClear({ vehicleRef, zeroGRef, disabledRotorsRef }) {
659
- useFrame(() => {
660
- if (zeroGRef.current) {
661
- resetAllWheelHits(vehicleRef.current);
662
- return;
663
- }
664
- const flags = disabledRotorsRef?.current;
665
- if (flags && (flags.wheelsAllOff || flags.frontOff || flags.rearOff || flags.propsOff)) resetDisabledRotors(vehicleRef.current, flags);
666
- });
667
- return null;
668
- }
669
- function RotorVisualSlot({ object, center, quaternion, scene, origin }) {
670
- const slotRef = useRef(null);
671
- useLayoutEffect(() => {
672
- const slot = slotRef.current;
673
- const parent = slot?.parent ?? null;
674
- if (!slot || !parent) return;
675
- const snap = origin ?? captureSubtreeOrigins([object]).get(object);
676
- scene.updateMatrixWorld(true);
677
- const localMat = computeRotorLocalMatrix(object, scene, center, quaternion);
678
- if (snap.origParent) snap.origParent.remove(object);
679
- const pos = new THREE.Vector3();
680
- const quat = new THREE.Quaternion();
681
- const scl = new THREE.Vector3();
682
- localMat.decompose(pos, quat, scl);
683
- object.position.copy(pos);
684
- object.quaternion.copy(quat.normalize());
685
- object.scale.copy(scl);
686
- slot.add(object);
687
- const untrack = registerMountedSubtree(() => {
688
- const p = object.position.clone(), q = object.quaternion.clone(), s = object.scale.clone();
689
- if (object.parent === slot) slot.remove(object);
690
- restoreSubtreeOrigin(object, snap);
691
- return () => {
692
- if (snap.origParent) snap.origParent.remove(object);
693
- object.position.copy(p);
694
- object.quaternion.copy(q);
695
- object.scale.copy(s);
696
- slot.add(object);
697
- };
698
- });
699
- return () => {
700
- untrack();
701
- if (object.parent === slot) slot.remove(object);
702
- restoreSubtreeOrigin(object, snap);
703
- };
704
- }, [
705
- object,
706
- center,
707
- quaternion,
708
- scene,
709
- origin
710
- ]);
711
- return /* @__PURE__ */ jsx("group", { ref: slotRef });
712
- }
713
- // src/khrVehicleRotors.tsx
714
- var G_SI$1 = 9.81;
715
- var UNSPRUNG_CORNER_RATIO = .035;
716
- function KhrVehicleRotors({ solvedWheels, propellers, scene, comZ, rotorOrigins, enable, wheelEnable, wheelEpoch = 0, wheelConfig, frontWheelConfig, rearWheelConfig, propellerConfig }) {
717
- return /* @__PURE__ */ jsxs(Fragment, { children: [solvedWheels.map(({ tag, cornerMassKg, springK, dampingC, mountPos }) => {
718
- const axleCfg = mountPos[2] >= comZ ? frontWheelConfig : rearWheelConfig;
719
- const wheelVol = Math.max(Math.PI * tag.radius * tag.radius * tag.width, 1e-6);
720
- const wheelModelDensity = tag.wheelDensity ?? UNSPRUNG_CORNER_RATIO * cornerMassKg / wheelVol;
721
- const tagWheelProps = {
722
- rayLength: tag.travel,
723
- rayShapeR: tag.radius,
724
- rayShapeH: tag.width * .5,
725
- wheelModelRadius: tag.radius,
726
- wheelModelDensity,
727
- springK,
728
- dampingC,
729
- steerWheel: tag.steer,
730
- driveWheel: tag.drive,
731
- brakeWheel: tag.brake,
732
- maxBrakeTorque: tag.maxBrakeTorque ?? cornerMassKg * G_SI$1 * tag.radius,
733
- ...tag.steerInvert !== void 0 ? { steerInvert: tag.steerInvert } : {},
734
- ...tag.driveInvert !== void 0 ? { driveInvert: tag.driveInvert } : {},
735
- ...tag.driveTorqueWeight !== void 0 ? { driveTorqueWeight: tag.driveTorqueWeight } : {},
736
- ...tag.rollingResistanceCoef !== void 0 ? { rollingResistanceCoef: tag.rollingResistanceCoef } : {},
737
- ...tag.tireGripFactor !== void 0 ? { tireGripFactor: tag.tireGripFactor } : {},
738
- ...tag.latFrictionEllipseScale !== void 0 ? { latFrictionEllipseScale: tag.latFrictionEllipseScale } : {},
739
- ...tag.relaxLngRate !== void 0 ? { relaxLngRate: tag.relaxLngRate } : {},
740
- ...tag.relaxLatRate !== void 0 ? { relaxLatRate: tag.relaxLatRate } : {},
741
- ...tag.lngSlipRatioCurveData !== void 0 ? { lngSlipRatioCurveData: tag.lngSlipRatioCurveData } : {},
742
- ...tag.latSlipRatioCurveData !== void 0 ? { latSlipRatioCurveData: tag.latSlipRatioCurveData } : {}
743
- };
744
- return /* @__PURE__ */ jsx(ShapeCastWheel, {
745
- name: tag.nodeName,
746
- position: mountPos,
747
- quaternion: tag.quaternion ?? [
748
- 0,
749
- 0,
750
- 0,
751
- 1
752
- ],
753
- ...tagWheelProps,
754
- ...wheelConfig,
755
- ...axleCfg,
756
- enable: wheelEnable && (axleCfg?.enable ?? wheelConfig?.enable ?? true),
757
- children: /* @__PURE__ */ jsx(RotorVisualSlot, {
758
- object: tag.object,
759
- center: tag.position,
760
- quaternion: tag.quaternion,
761
- scene,
762
- origin: rotorOrigins.get(tag.object)
763
- })
764
- }, `${tag.nodeName}:${wheelEpoch}`);
765
- }), propellers.map((tag) => {
766
- const propEnabled = enable && (propellerConfig?.enable ?? true);
767
- const visual = /* @__PURE__ */ jsx(RotorVisualSlot, {
768
- object: tag.object,
769
- center: tag.position,
770
- quaternion: tag.quaternion,
771
- scene,
772
- origin: rotorOrigins.get(tag.object)
773
- });
774
- if (!propEnabled) return /* @__PURE__ */ jsx("group", {
775
- name: tag.nodeName,
776
- position: [
777
- tag.position[0],
778
- tag.position[1],
779
- tag.position[2]
780
- ],
781
- quaternion: tag.quaternion ?? [
782
- 0,
783
- 0,
784
- 0,
785
- 1
786
- ],
787
- children: visual
788
- }, `${tag.nodeName}:off`);
789
- return /* @__PURE__ */ jsx(ThrustPropeller, {
790
- name: tag.nodeName,
791
- position: [
792
- tag.position[0],
793
- tag.position[1],
794
- tag.position[2]
795
- ],
796
- quaternion: tag.quaternion ?? [
797
- 0,
798
- 0,
799
- 0,
800
- 1
801
- ],
802
- debug: false,
803
- maxThrust: tag.maxThrust,
804
- ...tag.torqueRatio !== void 0 ? { torqueRatio: tag.torqueRatio } : {},
805
- ...tag.invertThrust !== void 0 ? { invertThrust: tag.invertThrust } : {},
806
- ...tag.invertTorque !== void 0 ? { invertTorque: tag.invertTorque } : {},
807
- ...propellerConfig,
808
- enable: true,
809
- children: visual
810
- }, tag.nodeName);
811
- })] });
812
- }
813
- // src/wheelLoads.ts
814
- var G_SI = 9.81;
815
- function projectToLowerBoundedSimplex(values, lowerBound, totalSum) {
816
- const n = values.length;
817
- const shifted = values.map((v) => v - lowerBound);
818
- const rem = Math.max(0, totalSum - n * lowerBound);
819
- const sorted = [...shifted].sort((a, b) => b - a);
820
- let prefix = 0;
821
- let k = 0;
822
- let theta = 0;
823
- for (let i = 0; i < n; i++) {
824
- prefix += sorted[i];
825
- const candidate = (prefix - rem) / (i + 1);
826
- if (sorted[i] - candidate > 0) {
827
- k = i + 1;
828
- theta = candidate;
829
- }
830
- }
831
- if (k === 0) theta = (prefix - rem) / n;
832
- return shifted.map((v) => lowerBound + Math.max(v - theta, 0));
833
- }
834
- function solveCornerMasses(wheels, totalMassKg, com) {
835
- const n = wheels.length;
836
- if (n === 0) return [];
837
- if (n === 1) return [totalMassKg];
838
- const mBase = totalMassKg / n;
839
- const xs = wheels.map((w) => w.position[0] - com[0]);
840
- const zs = wheels.map((w) => w.position[2] - com[2]);
841
- const meanX = xs.reduce((s, v) => s + v, 0) / n;
842
- const meanZ = zs.reduce((s, v) => s + v, 0) / n;
843
- const cx = xs.map((v) => v - meanX);
844
- const cz = zs.map((v) => v - meanZ);
845
- let sxx = 0;
846
- let szz = 0;
847
- let sxz = 0;
848
- for (let i = 0; i < n; i++) {
849
- sxx += cx[i] * cx[i];
850
- szz += cz[i] * cz[i];
851
- sxz += cx[i] * cz[i];
852
- }
853
- const bx = -totalMassKg * meanX;
854
- const bz = -totalMassKg * meanZ;
855
- const det = sxx * szz - sxz * sxz;
856
- const trace = sxx + szz;
857
- let lx = 0;
858
- let lz = 0;
859
- if (det > 1e-10 * trace * trace && det > 1e-12) {
860
- lx = (szz * bx - sxz * bz) / det;
861
- lz = (sxx * bz - sxz * bx) / det;
862
- } else if (trace > 1e-10) {
863
- const angle = .5 * Math.atan2(2 * sxz, sxx - szz);
864
- const ux = Math.cos(angle);
865
- const uz = Math.sin(angle);
866
- const normSq = ux * ux * sxx + 2 * ux * uz * sxz + uz * uz * szz;
867
- if (normSq > 1e-10) {
868
- const proj = (ux * bx + uz * bz) / normSq;
869
- lx = proj * ux;
870
- lz = proj * uz;
871
- }
872
- }
873
- const raw = wheels.map((_, i) => mBase + lx * cx[i] + lz * cz[i]);
874
- const mMin = Math.min(.05 * totalMassKg, totalMassKg / n);
875
- if (raw.every((m) => m >= mMin - 1e-9)) return raw;
876
- return projectToLowerBoundedSimplex(raw, mMin, totalMassKg);
877
- }
878
- /**
879
- * Distributes `totalMassKg` across N >= 1 wheels around `com`, resolves fallback
880
- * `springK` / `dampingC` when omitted on the `.glb` wheel descriptor, and returns
881
- * natural scene-space `mountPos` (`tag.position + lift`).
882
- */
883
- function solveWheelLoads(wheels, totalMassKg, com, dampingRatio = .7) {
884
- if (wheels.length === 0) return [];
885
- const cornerMasses = solveCornerMasses(wheels, totalMassKg, com);
886
- return wheels.map((tag, i) => {
887
- const cornerMassKg = cornerMasses[i];
888
- const springK = tag.springK ?? cornerMassKg * G_SI / Math.max(tag.sag, 1e-4);
889
- const dampingC = tag.dampingC ?? 2 * dampingRatio * Math.sqrt(springK * cornerMassKg);
890
- const lift = Math.max(0, tag.travel - tag.sag);
891
- const mountOffset = new THREE.Vector3(0, lift, 0);
892
- if (tag.quaternion) mountOffset.applyQuaternion(new THREE.Quaternion(tag.quaternion[0], tag.quaternion[1], tag.quaternion[2], tag.quaternion[3]).normalize());
893
- return {
894
- tag,
895
- cornerMassKg,
896
- springK,
897
- dampingC,
898
- mountPos: [
899
- tag.position[0] + mountOffset.x,
900
- tag.position[1] + mountOffset.y,
901
- tag.position[2] + mountOffset.z
902
- ]
903
- };
904
- });
905
- }
906
- // src/KhrVehicle.tsx
907
- var patchedHandles = /* @__PURE__ */ new WeakSet();
908
708
  function hasActiveMovement(m) {
909
709
  return Boolean(m.forward || m.backward || m.steerLeft || m.steerRight || m.brake || m.throttleUp || m.throttleDown || m.yawLeft || m.yawRight || m.pitchForward || m.pitchBackward || m.rollLeft || m.rollRight || m.joystickL && (Math.abs(m.joystickL.x) > 1e-4 || Math.abs(m.joystickL.y) > 1e-4) || m.joystickR && (Math.abs(m.joystickR.x) > 1e-4 || Math.abs(m.joystickR.y) > 1e-4));
910
710
  }
711
+ var patchedHandles = /* @__PURE__ */ new WeakSet();
911
712
  function KhrVehicle({ scale, colliders, bundle, ...rest }) {
912
- assertVehicleProps(scale, colliders);
913
- bundle.scene.updateMatrixWorld(true);
914
- assertSceneIdentityWorldScale(bundle.scene);
713
+ if (colliders !== void 0) throw new KhrValidationError("KhrVehicle: colliders prop cannot be overridden; edit colliders in the .glb asset");
714
+ assertUnitScale(scale, "KhrVehicle");
715
+ useMemo(() => assertSceneIdentityWorldScale(bundle.scene), [bundle]);
915
716
  const { ref, vehicleRef, jointsRef, position, rotation, quaternion, enable = true, enableCustomGravity = false, carConfig, droneConfig, wheelConfig, frontWheelConfig, rearWheelConfig, propellerConfig, linearVelocity, angularVelocity, gravityScale, children, ...ecctrlRest } = rest;
916
717
  const { world } = useRapier();
917
- const [rotorsMounted, setRotorsMounted] = useState(false);
918
- const [isZeroG, setIsZeroG] = useState(() => {
919
- if (enableCustomGravity) return true;
920
- const g = world.gravity;
921
- return g.x * g.x + g.y * g.y + g.z * g.z <= 1e-12;
922
- });
923
- const [wheelEpoch, setWheelEpoch] = useState(0);
718
+ const worldGravMag = Math.hypot(world.gravity.x, world.gravity.y, world.gravity.z);
719
+ const refGrav = worldGravMag > 1e-4 ? worldGravMag : STANDARD_GRAVITY;
720
+ const [isZeroG, setIsZeroG] = useState(() => enableCustomGravity ? true : worldGravMag <= 1e-6);
924
721
  const zeroGRef = useRef(isZeroG);
925
- const poisonedRef = useRef(false);
926
- useLayoutEffect(() => {
927
- setRotorsMounted(true);
928
- }, []);
929
- const handleZeroGChange = useCallback((nextZeroG) => {
930
- if (nextZeroG) {
931
- poisonedRef.current = true;
932
- resetAllWheelHits(innerRef.current);
933
- } else if (poisonedRef.current) {
934
- poisonedRef.current = false;
935
- setWheelEpoch((e) => e + 1);
936
- }
937
- setIsZeroG(nextZeroG);
938
- }, []);
722
+ const [chassisBody, setChassisBody] = useState(null);
939
723
  const chassis = useMemo(() => computeChassisMassProps(bundle.bodies), [bundle]);
940
724
  const collidersList = useMemo(() => buildChassisColliders(bundle.bodies, chassis), [bundle.bodies, chassis]);
941
- const solvedWheels = useMemo(() => solveWheelLoads(bundle.wheels, bundle.totalDynamicMass, bundle.centerOfMass, .7), [
725
+ const solvedWheels = useMemo(() => solveWheelLoads(bundle.wheels, bundle.totalDynamicMass, bundle.centerOfMass, .7, refGrav), [
942
726
  bundle.wheels,
943
727
  bundle.totalDynamicMass,
944
- bundle.centerOfMass
728
+ bundle.centerOfMass,
729
+ refGrav
730
+ ]);
731
+ const rotorOrigins = useMemo(() => captureSubtreeOrigins([...bundle.wheels.map((w) => w.object), ...bundle.propellers.map((p) => p.object)], bundle.scene), [
732
+ bundle.wheels,
733
+ bundle.propellers,
734
+ bundle.scene
735
+ ]);
736
+ const forwardSign = useMemo(() => {
737
+ const steered = solvedWheels.filter((w) => w.tag.steer && !w.tag.steerInvert);
738
+ if (steered.length === 0) return 1;
739
+ return steered.reduce((s, w) => s + w.mountPos[2], 0) / steered.length < chassis.com[2] - .001 ? -1 : 1;
740
+ }, [solvedWheels, chassis.com]);
741
+ const frontWheelNames = useMemo(() => new Set(solvedWheels.filter((w) => (w.mountPos[2] - chassis.com[2]) * forwardSign >= 0).map((w) => w.tag.nodeName)), [
742
+ solvedWheels,
743
+ chassis.com,
744
+ forwardSign
945
745
  ]);
946
- const rotorOrigins = useMemo(() => captureRotorOrigins([...bundle.wheels.map((w) => w.object), ...bundle.propellers.map((p) => p.object)]), [bundle.wheels, bundle.propellers]);
947
- const frontWheelNames = useMemo(() => new Set(solvedWheels.filter((w) => w.mountPos[2] >= chassis.com[2]).map((w) => w.tag.nodeName)), [solvedWheels, chassis.com]);
948
746
  const wheelsAllOff = !enable || isZeroG || wheelConfig?.enable === false && frontWheelConfig?.enable !== true && rearWheelConfig?.enable !== true;
949
747
  const frontOff = frontWheelConfig?.enable === false || frontWheelConfig?.enable === void 0 && wheelConfig?.enable === false;
950
748
  const rearOff = rearWheelConfig?.enable === false || rearWheelConfig?.enable === void 0 && wheelConfig?.enable === false;
@@ -963,6 +761,7 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
963
761
  propsOff,
964
762
  frontWheelNames
965
763
  };
764
+ const innerRef = useRef(null);
966
765
  useLayoutEffect(() => {
967
766
  resetDisabledRotors(innerRef.current, disabledRotorsRef.current);
968
767
  }, [
@@ -972,6 +771,34 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
972
771
  propsOff,
973
772
  frontWheelNames
974
773
  ]);
774
+ useFrame(() => {
775
+ const handle = innerRef.current;
776
+ if (handle?.body && handle.body !== chassisBody) setChassisBody(handle.body);
777
+ if (!enable) return;
778
+ let gSq;
779
+ if (enableCustomGravity) {
780
+ if (handle?.body && !handle.body.isSleeping()) gSq = handle.gravityMag * handle.gravityMag;
781
+ else {
782
+ const t = handle?.body?.translation();
783
+ if (t) _samplePos.set(t.x, t.y, t.z);
784
+ else _samplePos.set(bodyPos[0], bodyPos[1], bodyPos[2]);
785
+ gSq = useCustomGravity.getState().gravityField(_samplePos).lengthSq();
786
+ }
787
+ } else {
788
+ const g = world.gravity;
789
+ gSq = g.x * g.x + g.y * g.y + g.z * g.z;
790
+ }
791
+ const nextZeroG = gSq <= 1e-12;
792
+ if (nextZeroG !== zeroGRef.current) {
793
+ zeroGRef.current = nextZeroG;
794
+ setIsZeroG(nextZeroG);
795
+ }
796
+ if (nextZeroG) resetWheelHits(handle);
797
+ else {
798
+ const flags = disabledRotorsRef.current;
799
+ if (flags.wheelsAllOff || flags.frontOff || flags.rearOff || flags.propsOff) resetDisabledRotors(handle, flags);
800
+ }
801
+ });
975
802
  const [px, py, pz] = readPosTuple(position);
976
803
  const [qx, qy, qz, qw] = readSpawnQuat(rotation, quaternion);
977
804
  const bodyPos = useMemo(() => [
@@ -994,8 +821,7 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
994
821
  qz,
995
822
  qw
996
823
  ]);
997
- const innerRef = useRef(null);
998
- const assignRef = useCallback((handle) => {
824
+ const assignVehicleRef = useCallback((handle) => {
999
825
  if (handle && !patchedHandles.has(handle)) {
1000
826
  patchedHandles.add(handle);
1001
827
  const origSetMovement = handle.setMovement;
@@ -1005,9 +831,9 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
1005
831
  };
1006
832
  }
1007
833
  innerRef.current = handle;
1008
- if (vehicleRef) vehicleRef.current = handle;
1009
- if (typeof ref === "function") ref(handle);
1010
- else if (ref && typeof ref === "object") ref.current = handle;
834
+ setChassisBody(handle?.body ?? null);
835
+ assignRef(vehicleRef, handle);
836
+ assignRef(ref, handle);
1011
837
  }, [ref, vehicleRef]);
1012
838
  const omiSteerAngle = useMemo(() => bundle.wheels.find((w) => w.steer && w.maxSteeringAngle !== void 0 && w.maxSteeringAngle > 0)?.maxSteeringAngle, [bundle.wheels]);
1013
839
  const mergedCarConfig = useMemo(() => bundle.tune || carConfig || omiSteerAngle !== void 0 ? {
@@ -1026,8 +852,9 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
1026
852
  const effLinVel = linearVelocity ?? chassis.linearVelocity;
1027
853
  const effAngVel = angularVelocity ?? chassis.angularVelocity;
1028
854
  const effGravScale = gravityScale ?? chassis.gravityFactor;
855
+ const wheelEnable = enable && !isZeroG;
1029
856
  return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs(EcctrlVehicle, {
1030
- ref: assignRef,
857
+ ref: assignVehicleRef,
1031
858
  enable,
1032
859
  enableCustomGravity,
1033
860
  position: bodyPos,
@@ -1048,39 +875,108 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
1048
875
  c: spec,
1049
876
  massProperties
1050
877
  }, key)),
1051
- rotorsMounted && /* @__PURE__ */ jsxs(Fragment, { children: [
1052
- /* @__PURE__ */ jsx(ZeroGWheelGate, {
1053
- vehicleRef: innerRef,
1054
- enable,
1055
- enableCustomGravity,
1056
- spawnPos: bodyPos,
1057
- zeroGRef,
1058
- onZeroGChange: handleZeroGChange
1059
- }),
1060
- /* @__PURE__ */ jsx(KhrVehicleRotors, {
1061
- solvedWheels,
1062
- propellers: bundle.propellers,
878
+ solvedWheels.map(({ tag, cornerMassKg, springK, dampingC, mountPos }) => {
879
+ const axleCfg = frontWheelNames.has(tag.nodeName) ? frontWheelConfig : rearWheelConfig;
880
+ const wheelVol = Math.max(Math.PI * tag.radius * tag.radius * tag.width, 1e-6);
881
+ const wheelModelDensity = tag.wheelDensity ?? UNSPRUNG_CORNER_RATIO * cornerMassKg / wheelVol;
882
+ const tagWheelProps = {
883
+ rayLength: tag.travel,
884
+ rayShapeR: tag.radius,
885
+ rayShapeH: tag.width * .5,
886
+ wheelModelRadius: tag.radius,
887
+ wheelModelDensity,
888
+ springK,
889
+ dampingC,
890
+ steerWheel: tag.steer,
891
+ driveWheel: tag.drive,
892
+ brakeWheel: tag.brake,
893
+ maxBrakeTorque: tag.maxBrakeTorque ?? cornerMassKg * refGrav * tag.radius,
894
+ ...tag.steerInvert !== void 0 ? { steerInvert: tag.steerInvert } : {},
895
+ ...tag.driveInvert !== void 0 ? { driveInvert: tag.driveInvert } : {},
896
+ ...tag.driveTorqueWeight !== void 0 ? { driveTorqueWeight: tag.driveTorqueWeight } : {},
897
+ ...tag.rollingResistanceCoef !== void 0 ? { rollingResistanceCoef: tag.rollingResistanceCoef } : {},
898
+ ...tag.tireGripFactor !== void 0 ? { tireGripFactor: tag.tireGripFactor } : {},
899
+ ...tag.latFrictionEllipseScale !== void 0 ? { latFrictionEllipseScale: tag.latFrictionEllipseScale } : {},
900
+ ...tag.relaxLngRate !== void 0 ? { relaxLngRate: tag.relaxLngRate } : {},
901
+ ...tag.relaxLatRate !== void 0 ? { relaxLatRate: tag.relaxLatRate } : {},
902
+ ...tag.lngSlipRatioCurveData !== void 0 ? { lngSlipRatioCurveData: tag.lngSlipRatioCurveData } : {},
903
+ ...tag.latSlipRatioCurveData !== void 0 ? { latSlipRatioCurveData: tag.latSlipRatioCurveData } : {}
904
+ };
905
+ return /* @__PURE__ */ jsx(ShapeCastWheel, {
906
+ name: tag.nodeName,
907
+ position: mountPos,
908
+ quaternion: tag.quaternion ?? [
909
+ 0,
910
+ 0,
911
+ 0,
912
+ 1
913
+ ],
914
+ ...tagWheelProps,
915
+ ...wheelConfig,
916
+ ...axleCfg,
917
+ enable: wheelEnable && (axleCfg?.enable ?? wheelConfig?.enable ?? true),
918
+ children: /* @__PURE__ */ jsx(RotorVisualSlot, {
919
+ object: tag.object,
920
+ center: tag.position,
921
+ quaternion: tag.quaternion,
922
+ scene: bundle.scene,
923
+ origin: rotorOrigins.get(tag.object)
924
+ })
925
+ }, tag.nodeName);
926
+ }),
927
+ bundle.propellers.map((tag) => {
928
+ const propEnabled = enable && (propellerConfig?.enable ?? true);
929
+ const visual = /* @__PURE__ */ jsx(RotorVisualSlot, {
930
+ object: tag.object,
931
+ center: tag.position,
932
+ quaternion: tag.quaternion,
1063
933
  scene: bundle.scene,
1064
- comZ: chassis.com[2],
1065
- rotorOrigins,
1066
- enable,
1067
- wheelEnable: enable && !isZeroG,
1068
- wheelEpoch,
1069
- wheelConfig,
1070
- frontWheelConfig,
1071
- rearWheelConfig,
1072
- propellerConfig
1073
- }),
1074
- /* @__PURE__ */ jsx(ZeroGWheelPostClear, {
1075
- vehicleRef: innerRef,
1076
- zeroGRef,
1077
- disabledRotorsRef
1078
- }, `post:${wheelEpoch}`)
1079
- ] })
934
+ origin: rotorOrigins.get(tag.object)
935
+ });
936
+ if (!propEnabled) return /* @__PURE__ */ jsx("group", {
937
+ name: tag.nodeName,
938
+ position: [
939
+ tag.position[0],
940
+ tag.position[1],
941
+ tag.position[2]
942
+ ],
943
+ quaternion: tag.quaternion ?? [
944
+ 0,
945
+ 0,
946
+ 0,
947
+ 1
948
+ ],
949
+ children: visual
950
+ }, `${tag.nodeName}:off`);
951
+ return /* @__PURE__ */ jsx(ThrustPropeller, {
952
+ name: tag.nodeName,
953
+ position: [
954
+ tag.position[0],
955
+ tag.position[1],
956
+ tag.position[2]
957
+ ],
958
+ quaternion: tag.quaternion ?? [
959
+ 0,
960
+ 0,
961
+ 0,
962
+ 1
963
+ ],
964
+ debug: false,
965
+ maxThrust: tag.maxThrust,
966
+ ...tag.torqueRatio !== void 0 ? { torqueRatio: tag.torqueRatio } : {},
967
+ ...tag.invertThrust !== void 0 ? { invertThrust: tag.invertThrust } : {},
968
+ ...tag.invertTorque !== void 0 ? { invertTorque: tag.invertTorque } : {},
969
+ ...propellerConfig,
970
+ enable: true,
971
+ children: visual
972
+ }, tag.nodeName);
973
+ })
1080
974
  ]
1081
- }), rotorsMounted && /* @__PURE__ */ jsx(KhrVehicleJoints, {
975
+ }), /* @__PURE__ */ jsx(KhrVehicleJoints, {
976
+ bundleScene: bundle.scene,
1082
977
  bodies: bundle.bodies,
1083
978
  vehicleRef: innerRef,
979
+ chassisBody,
1084
980
  spawnPos: bodyPos,
1085
981
  spawnQuat: bodyQuat,
1086
982
  enableCustomGravity,