@khr3/core 0.2.5 → 0.2.7

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 (43) hide show
  1. package/README.md +169 -9
  2. package/dist/KhrAssembly.d.ts +1 -1
  3. package/dist/KhrCollider.d.ts +5 -1
  4. package/dist/curves-Cf8okB-M.js +542 -0
  5. package/dist/curves-Cf8okB-M.js.map +1 -0
  6. package/dist/curves.js +1 -542
  7. package/dist/index.d.ts +3 -2
  8. package/dist/index.js +4 -1544
  9. package/dist/index.js.map +1 -1
  10. package/dist/jointDynamics.d.ts +7 -0
  11. package/dist/khrClone.d.ts +3 -3
  12. package/dist/khrInertia-DgCUCDTx.js +247 -0
  13. package/dist/khrInertia-DgCUCDTx.js.map +1 -0
  14. package/dist/khrVehicleJointHelpers.d.ts +16 -0
  15. package/dist/khrVehicleJoints.d.ts +2 -1
  16. package/dist/khrVehicleSlots.d.ts +11 -3
  17. package/dist/{physicsEcs-dBq4psbC.js → physicsEcs-C00N5zCh.js} +27 -251
  18. package/dist/physicsEcs-C00N5zCh.js.map +1 -0
  19. package/dist/sand3d/sand3dAssemblyHelpers.d.ts +30 -0
  20. package/dist/sand3d/sand3dCavityOps.d.ts +15 -0
  21. package/dist/sand3d/sand3dCompiler.d.ts +121 -0
  22. package/dist/sand3d/sand3dEvaluator.d.ts +80 -0
  23. package/dist/sand3d/sand3dFramesAndEdits.d.ts +30 -0
  24. package/dist/sand3d/sand3dHullAndSweep.d.ts +27 -0
  25. package/dist/sand3d/sand3dParser.d.ts +6 -0
  26. package/dist/sand3d/sand3dPrimitives.d.ts +50 -0
  27. package/dist/sand3d/sand3dProfiles.d.ts +32 -0
  28. package/dist/sand3d/sand3dRecipes.d.ts +5 -0
  29. package/dist/sand3d/sand3dShellOp.d.ts +8 -0
  30. package/dist/sand3d/sand3dSolids.d.ts +32 -0
  31. package/dist/sand3d/sand3dTokenizer.d.ts +8 -0
  32. package/dist/sand3d/sand3dTypes.d.ts +157 -0
  33. package/dist/sand3d-DQ8-OMlo.js +5045 -0
  34. package/dist/sand3d-DQ8-OMlo.js.map +1 -0
  35. package/dist/sand3d.d.ts +23 -0
  36. package/dist/sand3d.js +1 -0
  37. package/dist/vehicle.js +198 -21
  38. package/dist/vehicle.js.map +1 -1
  39. package/dist/wheelLoads.d.ts +3 -1
  40. package/docs/api-reference.md +332 -163
  41. package/package.json +5 -1
  42. package/dist/curves.js.map +0 -1
  43. package/dist/physicsEcs-dBq4psbC.js.map +0 -1
@@ -0,0 +1,23 @@
1
+ import type { KhrAssetBundle } from "./khrTypes.js";
2
+ import { assembly, exportTarget, joint, part, s3d, socket, thruster, wheel } from "./sand3d/sand3dCompiler.js";
3
+ import { isSand3dFileName, parseSand3dSource } from "./sand3d/sand3dParser.js";
4
+ import { buildSand3dRecipe, findSand3dRecipe, SAND3D_RECIPE_MAP, SAND3D_RECIPES } from "./sand3d/sand3dRecipes.js";
5
+ import type { CompiledSand3dAssembly, Sand3dAssembly, Sand3dPartSpec, Sand3dRecipeId, Sand3dSolid, Sand3dUnits } from "./sand3d/sand3dTypes.js";
6
+ export * from "./sand3d/sand3dTypes.js";
7
+ export * from "./sand3d/sand3dProfiles.js";
8
+ export * from "./sand3d/sand3dSolids.js";
9
+ export * from "./sand3d/sand3dFramesAndEdits.js";
10
+ export { assembly, buildSand3dRecipe, exportTarget, findSand3dRecipe, isSand3dFileName, joint, parseSand3dSource, part, s3d, SAND3D_RECIPE_MAP, SAND3D_RECIPES, socket, thruster, wheel, };
11
+ export type Sand3dCompileInput = Sand3dAssembly | Sand3dPartSpec | Sand3dSolid | Sand3dRecipeId | string;
12
+ /** Compiles a Sand3D assembly, solid, recipe ID, or script string into a Three.js scene and KHR specs. */
13
+ export declare function compileSand3dAssembly(input: Sand3dCompileInput, opts?: {
14
+ units?: Sand3dUnits;
15
+ }): CompiledSand3dAssembly;
16
+ /** Compiles and exports any Sand3D assembly, solid, recipe ID, or script string into binary .glb bytes. */
17
+ export declare function exportSand3dGlb(input: Sand3dCompileInput, opts?: {
18
+ units?: Sand3dUnits;
19
+ }): Promise<Uint8Array>;
20
+ /** Compiles, exports, and loads any Sand3D assembly, recipe ID, or script into a validated KhrAssetBundle. */
21
+ export declare function loadSand3dBundle(input: Sand3dCompileInput, opts?: {
22
+ units?: Sand3dUnits;
23
+ }): Promise<KhrAssetBundle>;
package/dist/sand3d.js ADDED
@@ -0,0 +1 @@
1
+ export { i as SAND3D_RECIPES, a as SAND3D_RECIPE_MAP, f as assembly, N as at, P as bend, S as box, o as buildSand3dRecipe, F as chamfer, X as circle, Z as cleanLoop2D, I as color, t as compileSand3dAssembly, C as cone, w as cylinder, T as dome, n as exportSand3dGlb, p as exportTarget, y as extrude, L as fillet, k as finalizeManifoldGeometry, s as findSand3dRecipe, R as grid, A as helix, K as hole, j as hull, c as isSand3dFileName, m as joint, r as loadSand3dBundle, b as loft, Q as ngon, z as on, l as parseSand3dSource, h as part, q as pocket, B as polar, $ as polygon, et as rect, J as resolveFaceFrame, x as revolve, V as rotate, u as s3d, d as sand3dUnitScale, Y as shell, tt as signedArea2D, nt as slot, g as socket, E as sphere, rt as star, it as subtractProfileHole, M as sweep, H as taper, _ as thruster, D as torus, U as translate, at as triangulateProfile2D, O as tube, W as twist, G as unionSolids, v as wheel } from "./sand3d-DQ8-OMlo.js";
package/dist/vehicle.js CHANGED
@@ -1,4 +1,5 @@
1
- import { D as KhrValidationError, a as MountSubtreeSlot, b as assertUnitScale, 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, y as assertSceneIdentityWorldScale } from "./physicsEcs-dBq4psbC.js";
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";
2
3
  import { useCallback, useContext, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
3
4
  import { useFrame } from "@react-three/fiber";
4
5
  import { RigidBody, useRapier } from "@react-three/rapier";
@@ -182,6 +183,9 @@ function computeRotorLocalMatrix(node, scene, center, quaternion) {
182
183
  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);
183
184
  }
184
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;
185
189
  function planVehicleJointParts(bodies) {
186
190
  const dyn = bodies.filter((b) => !b.isKinematic);
187
191
  const byName = new Map(dyn.map((b) => [b.nodeName, b]));
@@ -232,7 +236,10 @@ function planVehicleJointParts(bodies) {
232
236
  local.decompose(cPos, cQuat, scl);
233
237
  cQuat.normalize();
234
238
  const planned = {
235
- spec,
239
+ spec: spec.collisionGroups === void 0 ? {
240
+ ...spec,
241
+ collisionGroups: ATTACHED_PANEL_COLLISION_GROUPS
242
+ } : spec,
236
243
  local,
237
244
  position: [
238
245
  cPos.x,
@@ -296,8 +303,71 @@ function isVehicleJointOpen(rt) {
296
303
  const openTgt = openTargetForLimits(rt.limits);
297
304
  return Math.abs(openTgt) > 1e-6 && Math.abs((rt.positionTarget ?? rt.getCoordinate()) - openTgt) < Math.abs(openTgt) * .5;
298
305
  }
306
+ var _pPos = new THREE.Vector3();
307
+ var _pQuat = new THREE.Quaternion();
308
+ var _rQuat = new THREE.Quaternion();
309
+ var _cQuat = new THREE.Quaternion();
310
+ var _anchor = new THREE.Vector3();
311
+ var _gravSample = new THREE.Vector3();
312
+ function stepVehicleArticulatedPanels(params) {
313
+ const { parts, bodyMap, runtimeMap, detachedCleared, parentBody, enableCustomGravity, gravityScale, timestep, gravityField } = params;
314
+ for (const part of parts) {
315
+ const rb = bodyMap.get(part.spec.nodeName);
316
+ if (!rb) continue;
317
+ if (runtimeMap.get(part.spec.nodeName)?.detached) {
318
+ if (!detachedCleared.has(rb)) {
319
+ detachedCleared.add(rb);
320
+ rb.userData = {};
321
+ const n = rb.numColliders();
322
+ for (let i = 0; i < n; i++) if (part.spec.colliders[i]?.collisionGroups === void 0) rb.collider(i).setCollisionGroups(DETACHED_PANEL_COLLISION_GROUPS);
323
+ }
324
+ } else if (!part.spec.isKinematic) {
325
+ const pRb = part.parent ? bodyMap.get(part.parent.spec.nodeName) ?? null : parentBody;
326
+ if (pRb) {
327
+ const pt = pRb.translation();
328
+ const pr = pRb.rotation();
329
+ const ct = rb.translation();
330
+ _pQuat.set(pr.x, pr.y, pr.z, pr.w);
331
+ _anchor.set(part.restRelParentPos[0], part.restRelParentPos[1], part.restRelParentPos[2]).applyQuaternion(_pQuat).add(_pPos.set(pt.x, pt.y, pt.z));
332
+ const dx = ct.x - _anchor.x, dy = ct.y - _anchor.y, dz = ct.z - _anchor.z;
333
+ const maxDrift = 1.5 + (part.joint.kind === "prismatic" && part.joint.limits ? Math.abs(part.joint.limits[0]) + Math.abs(part.joint.limits[1]) : 0);
334
+ if (dx * dx + dy * dy + dz * dz > maxDrift * maxDrift) {
335
+ const rrq = part.restRelParentQuat;
336
+ _cQuat.copy(_pQuat).multiply(_rQuat.set(rrq[0], rrq[1], rrq[2], rrq[3])).normalize();
337
+ rb.setTranslation({
338
+ x: _anchor.x,
339
+ y: _anchor.y,
340
+ z: _anchor.z
341
+ }, true);
342
+ rb.setRotation({
343
+ x: _cQuat.x,
344
+ y: _cQuat.y,
345
+ z: _cQuat.z,
346
+ w: _cQuat.w
347
+ }, true);
348
+ rb.setLinvel(pRb.linvel(), true);
349
+ rb.setAngvel(pRb.angvel(), true);
350
+ }
351
+ }
352
+ }
353
+ if (enableCustomGravity && timestep > 0 && gravityField && rb.isDynamic() && !rb.isSleeping()) {
354
+ const effScale = part.spec.gravityFactor ?? gravityScale ?? 1;
355
+ if (effScale !== 0) {
356
+ const ct = rb.translation();
357
+ const g = gravityField(_gravSample.set(ct.x, ct.y, ct.z));
358
+ const s = rb.mass() * effScale * timestep;
359
+ rb.applyImpulse({
360
+ x: g.x * s,
361
+ y: g.y * s,
362
+ z: g.z * s
363
+ }, false);
364
+ }
365
+ }
366
+ }
367
+ }
299
368
  // src/khrVehicleJoints.tsx
300
- function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, linearVelocity, angularVelocity, gravityScale, parentBodyGetter, origin, onBody, onJointReady }) {
369
+ var ATTACHED_PANEL_USER_DATA = { ecctrl: { excludeVehicleRay: true } };
370
+ function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, enableCustomGravity, linearVelocity, angularVelocity, gravityScale, parentBodyGetter, origin, onBody, onJointReady }) {
301
371
  const { rapier, world } = useRapier();
302
372
  const registry = useContext(JointRegistryContext);
303
373
  const childRef = useRef(null);
@@ -389,13 +459,14 @@ function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, linearVelocity, an
389
459
  } : void 0;
390
460
  const linVel = part.spec.linearVelocity ?? linearVelocity;
391
461
  const angVel = part.spec.angularVelocity ?? angularVelocity;
392
- const gravScale = part.spec.gravityFactor ?? gravityScale;
462
+ const gravScale = enableCustomGravity ? 0 : part.spec.gravityFactor ?? gravityScale;
393
463
  return /* @__PURE__ */ jsxs(RigidBody, {
394
464
  ref: childRef,
395
465
  type: part.spec.isKinematic ? "kinematicPosition" : "dynamic",
396
466
  position: worldPose.pos,
397
467
  quaternion: worldPose.quat,
398
468
  colliders: false,
469
+ userData: ATTACHED_PANEL_USER_DATA,
399
470
  onContactForce: onForce,
400
471
  ...linVel ? { linearVelocity: linVel } : {},
401
472
  ...angVel ? { angularVelocity: angVel } : {},
@@ -417,12 +488,28 @@ function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, linearVelocity, an
417
488
  }, `vj_${part.spec.nodeName}:${cIdx}`))]
418
489
  });
419
490
  }
420
- function KhrVehicleJoints({ bodies, vehicleRef, spawnPos, spawnQuat, linearVelocity, angularVelocity, gravityScale, jointsRef }) {
491
+ function KhrVehicleJoints({ bodies, vehicleRef, spawnPos, spawnQuat, enableCustomGravity = false, linearVelocity, angularVelocity, gravityScale, jointsRef }) {
492
+ const { world } = useRapier();
421
493
  const parts = useMemo(() => planVehicleJointParts(bodies), [bodies]);
422
494
  const origins = useMemo(() => parts.length > 0 ? captureSubtreeOrigins(parts.map((p) => p.spec.object)) : null, [parts]);
423
495
  const bodyMapRef = useRef(/* @__PURE__ */ new Map());
424
496
  const runtimeMapRef = useRef(/* @__PURE__ */ new Map());
425
497
  const byObjectRef = useRef(/* @__PURE__ */ new Map());
498
+ const detachedClearedRef = useRef(/* @__PURE__ */ new WeakSet());
499
+ useFrame(() => {
500
+ if (parts.length === 0) return;
501
+ stepVehicleArticulatedPanels({
502
+ parts,
503
+ bodyMap: bodyMapRef.current,
504
+ runtimeMap: runtimeMapRef.current,
505
+ detachedCleared: detachedClearedRef.current,
506
+ parentBody: vehicleRef.current?.body ?? null,
507
+ enableCustomGravity,
508
+ gravityScale,
509
+ timestep: world.timestep,
510
+ gravityField: enableCustomGravity ? useCustomGravity.getState().gravityField : void 0
511
+ });
512
+ });
426
513
  const handleBody = useCallback((nodeName, rb) => {
427
514
  if (rb) bodyMapRef.current.set(nodeName, rb);
428
515
  else bodyMapRef.current.delete(nodeName);
@@ -475,6 +562,7 @@ function KhrVehicleJoints({ bodies, vehicleRef, spawnPos, spawnQuat, linearVeloc
475
562
  part,
476
563
  spawnPos,
477
564
  spawnQuat,
565
+ enableCustomGravity,
478
566
  linearVelocity,
479
567
  angularVelocity,
480
568
  gravityScale,
@@ -487,6 +575,9 @@ function KhrVehicleJoints({ bodies, vehicleRef, spawnPos, spawnQuat, linearVeloc
487
575
  // src/khrVehicleSlots.tsx
488
576
  var captureRotorOrigins = captureSubtreeOrigins;
489
577
  var _samplePos = new THREE.Vector3();
578
+ var _hitNormal = new THREE.Vector3();
579
+ var _supDelta = new THREE.Vector3();
580
+ var G_SI$2 = 9.81;
490
581
  function resetAllWheelHits(handle) {
491
582
  if (!handle) return;
492
583
  for (const wheelRef of handle.wheelsInfo.values()) {
@@ -547,8 +638,8 @@ function resetDisabledRotors(handle, opts) {
547
638
  if (opts.propsOff) resetAllPropellerOutputs(handle);
548
639
  }
549
640
  /**
550
- * Gates `<ShapeCastWheel>` only when gravity is non-zero (`gravityMag > 1e-6`), preventing
551
- * `ShapeCastWheel`'s internal `smoothedLngImpulse += Infinity` closure poisoning in 0G.
641
+ * Enables `<ShapeCastWheel>` exclusively under positive gravity (`gravityMag > 1e-6`), keeping
642
+ * `ShapeCastWheel` internal `smoothedLngImpulse` state finite during 0G flight.
552
643
  */
553
644
  function ZeroGWheelGate({ vehicleRef, enable, enableCustomGravity, spawnPos, zeroGRef, onZeroGChange }) {
554
645
  const { world } = useRapier();
@@ -577,7 +668,63 @@ function ZeroGWheelGate({ vehicleRef, enable, enableCustomGravity, spawnPos, zer
577
668
  });
578
669
  return null;
579
670
  }
580
- function ZeroGWheelPostClear({ vehicleRef, zeroGRef, disabledRotorsRef }) {
671
+ /**
672
+ * Eliminates `EcctrlVehicle` + `ShapeCastWheel`'s 2-frame suspension/tire impulse lag by computing
673
+ * implicit modal-bounded suspension and non-reversing lateral tire impulses from current-frame
674
+ * `supPos` / `rayHitPointVel` and applying them directly to the chassis before `world.step()`.
675
+ */
676
+ function stabilizeWheelSuspensionImpulses(handle, solvedByName, dt) {
677
+ const body = handle?.body;
678
+ if (!handle || !body || body.isSleeping() || !(dt > 0)) return;
679
+ const gMag = handle.gravityMag > 1e-4 ? handle.gravityMag : G_SI$2;
680
+ for (const wheelRef of handle.wheelsInfo.values()) {
681
+ const w = wheelRef.current;
682
+ if (!w || w.enable === false) continue;
683
+ if (!(w.floatImp.lengthSq() > 0 || w.lngFricImp.lengthSq() > 0 || w.latFricImp.lengthSq() > 0)) continue;
684
+ const solved = w.name ? solvedByName?.get(w.name) : void 0;
685
+ const springK = w.springK ?? solved?.springK ?? 0;
686
+ const dampingC = w.dampingC ?? solved?.dampingC ?? 0;
687
+ const rayLen = w.rayLength ?? 0;
688
+ _hitNormal.copy(w.rayHitNormal);
689
+ if (_hitNormal.lengthSq() < 1e-6) _hitNormal.copy(w.rayUpDir);
690
+ else _hitNormal.normalize();
691
+ const upCos = _hitNormal.dot(w.rayUpDir);
692
+ if (springK > 0 && rayLen > 0) {
693
+ const suspensionToi = Math.max(0, _supDelta.subVectors(w.supPos, w.rayPos).dot(w.rayDir));
694
+ const supportScale = THREE.MathUtils.smoothstep(upCos, .15, .5);
695
+ const mModal = Math.max(solved?.modalMassKg ?? 120, 1);
696
+ const comp = Math.max(0, rayLen - suspensionToi);
697
+ const vUp = w.rayHitPointVel.dot(w.rayUpDir);
698
+ const springImp = springK * comp * dt;
699
+ const rawDampRate = (dampingC + springK * dt) * dt;
700
+ const effDampRate = rawDampRate / (1 + rawDampRate / mModal);
701
+ const totalFloatImp = Math.max(0, springImp - effDampRate * vUp) * supportScale;
702
+ w.floatImp.copy(_hitNormal).multiplyScalar(totalFloatImp);
703
+ }
704
+ if (w.latAxis.lengthSq() > 1e-6) {
705
+ const vLat = w.rayHitPointVel.dot(w.latAxis);
706
+ const latProj = w.latFricImp.dot(w.latAxis);
707
+ if (latProj * vLat > 0) w.latFricImp.set(0, 0, 0);
708
+ else {
709
+ const mModal = Math.max(solved?.modalMassKg ?? 120, 1);
710
+ const mLatModal = Math.max(solved?.lateralModalMassKg ?? mModal, 1);
711
+ const cornerMass = solved?.cornerMassKg ?? mModal;
712
+ const sinSlope = Math.sqrt(Math.max(0, 1 - upCos * upCos));
713
+ const maxNoReverse = Math.abs(vLat) * mLatModal + cornerMass * gMag * sinSlope * dt;
714
+ const absProj = Math.abs(latProj);
715
+ if (absProj > maxNoReverse && absProj > 1e-8) w.latFricImp.multiplyScalar(maxNoReverse / absProj);
716
+ }
717
+ }
718
+ if (w.floatImp.lengthSq() > 0) body.applyImpulseAtPoint(w.floatImp, w.supPos, false);
719
+ if (w.lngFricImp.lengthSq() > 0) body.applyImpulseAtPoint(w.lngFricImp, w.rayHitPos, false);
720
+ if (w.latFricImp.lengthSq() > 0) body.applyImpulseAtPoint(w.latFricImp, w.rayHitPos, false);
721
+ w.floatImp.set(0, 0, 0);
722
+ w.lngFricImp.set(0, 0, 0);
723
+ w.latFricImp.set(0, 0, 0);
724
+ }
725
+ }
726
+ function ZeroGWheelPostClear({ vehicleRef, zeroGRef, disabledRotorsRef, solvedByNameRef }) {
727
+ const { world } = useRapier();
581
728
  useFrame(() => {
582
729
  if (zeroGRef.current) {
583
730
  resetAllWheelHits(vehicleRef.current);
@@ -585,6 +732,7 @@ function ZeroGWheelPostClear({ vehicleRef, zeroGRef, disabledRotorsRef }) {
585
732
  }
586
733
  const flags = disabledRotorsRef?.current;
587
734
  if (flags && (flags.wheelsAllOff || flags.frontOff || flags.rearOff || flags.propsOff)) resetDisabledRotors(vehicleRef.current, flags);
735
+ if (!flags?.wheelsAllOff) stabilizeWheelSuspensionImpulses(vehicleRef.current, solvedByNameRef?.current, world.timestep);
588
736
  });
589
737
  return null;
590
738
  }
@@ -802,26 +950,49 @@ function solveCornerMasses(wheels, totalMassKg, com) {
802
950
  * `springK` / `dampingC` when omitted on the `.glb` wheel descriptor, and returns
803
951
  * natural scene-space `mountPos` (`tag.position + lift`).
804
952
  */
805
- function solveWheelLoads(wheels, totalMassKg, com, dampingRatio = .7) {
953
+ function solveWheelLoads(wheels, totalMassKg, com, dampingRatio = .7, inertia) {
806
954
  if (wheels.length === 0) return [];
807
955
  const cornerMasses = solveCornerMasses(wheels, totalMassKg, com);
808
- return wheels.map((tag, i) => {
809
- const cornerMassKg = cornerMasses[i];
810
- const springK = tag.springK ?? cornerMassKg * G_SI / Math.max(tag.sag, 1e-4);
811
- const dampingC = tag.dampingC ?? 2 * dampingRatio * Math.sqrt(springK * cornerMassKg);
956
+ const mountPositions = wheels.map((tag) => {
812
957
  const lift = Math.max(0, tag.travel - tag.sag);
813
958
  const mountOffset = new THREE.Vector3(0, lift, 0);
814
959
  if (tag.quaternion) mountOffset.applyQuaternion(new THREE.Quaternion(tag.quaternion[0], tag.quaternion[1], tag.quaternion[2], tag.quaternion[3]).normalize());
960
+ return [
961
+ tag.position[0] + mountOffset.x,
962
+ tag.position[1] + mountOffset.y,
963
+ tag.position[2] + mountOffset.z
964
+ ];
965
+ });
966
+ const sumAbsRx = mountPositions.reduce((s, m) => s + Math.abs(m[0] - com[0]), 0);
967
+ const sumAbsRz = mountPositions.reduce((s, m) => s + Math.abs(m[2] - com[2]), 0);
968
+ return wheels.map((tag, i) => {
969
+ const cornerMassKg = cornerMasses[i];
970
+ const mountPos = mountPositions[i];
971
+ let modalMassKg = cornerMassKg;
972
+ let lateralModalMassKg = cornerMassKg;
973
+ if (inertia) {
974
+ const [ixx, iyy, izz] = inertia;
975
+ const rx = Math.abs(mountPos[0] - com[0]);
976
+ const rz = Math.abs(mountPos[2] - com[2]);
977
+ const mPitch = rz > .001 && sumAbsRz > .001 ? Math.max(ixx, 1) / (rz * sumAbsRz) : Infinity;
978
+ const mRoll = rx > .001 && sumAbsRx > .001 ? Math.max(izz, 1) / (rx * sumAbsRx) : Infinity;
979
+ const minFloor = Math.min(cornerMassKg, 5);
980
+ modalMassKg = Math.max(minFloor, Math.min(cornerMassKg, mPitch, mRoll));
981
+ const h = Math.max(0, com[1] - (tag.position[1] - tag.radius));
982
+ const kappaLat = 1 + totalMassKg * h * h / Math.max(izz, 1) + totalMassKg * rz * (sumAbsRz / Math.max(wheels.length, 1)) / Math.max(iyy, 1);
983
+ lateralModalMassKg = Math.max(minFloor, cornerMassKg / kappaLat);
984
+ }
985
+ const springK = tag.springK ?? cornerMassKg * G_SI / Math.max(tag.sag, 1e-4);
986
+ const effDampMass = inertia ? Math.sqrt(cornerMassKg * modalMassKg) : cornerMassKg;
987
+ const dampingC = tag.dampingC ?? 2 * dampingRatio * Math.sqrt(springK * effDampMass);
815
988
  return {
816
989
  tag,
817
990
  cornerMassKg,
991
+ modalMassKg,
992
+ lateralModalMassKg,
818
993
  springK,
819
994
  dampingC,
820
- mountPos: [
821
- tag.position[0] + mountOffset.x,
822
- tag.position[1] + mountOffset.y,
823
- tag.position[2] + mountOffset.z
824
- ]
995
+ mountPos
825
996
  };
826
997
  });
827
998
  }
@@ -860,11 +1031,15 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
860
1031
  }, []);
861
1032
  const chassis = useMemo(() => computeChassisMassProps(bundle.bodies), [bundle]);
862
1033
  const collidersList = useMemo(() => buildChassisColliders(bundle.bodies, chassis), [bundle.bodies, chassis]);
863
- const solvedWheels = useMemo(() => solveWheelLoads(bundle.wheels, bundle.totalDynamicMass, bundle.centerOfMass), [
1034
+ const solvedWheels = useMemo(() => solveWheelLoads(bundle.wheels, bundle.totalDynamicMass, bundle.centerOfMass, .7, chassis.inertia), [
864
1035
  bundle.wheels,
865
1036
  bundle.totalDynamicMass,
866
- bundle.centerOfMass
1037
+ bundle.centerOfMass,
1038
+ chassis.inertia
867
1039
  ]);
1040
+ const solvedByName = useMemo(() => new Map(solvedWheels.map((w) => [w.tag.nodeName, w])), [solvedWheels]);
1041
+ const solvedByNameRef = useRef(solvedByName);
1042
+ solvedByNameRef.current = solvedByName;
868
1043
  const rotorOrigins = useMemo(() => captureRotorOrigins([...bundle.wheels.map((w) => w.object), ...bundle.propellers.map((p) => p.object)]), [bundle.wheels, bundle.propellers]);
869
1044
  const frontWheelNames = useMemo(() => new Set(solvedWheels.filter((w) => w.mountPos[2] >= chassis.com[2]).map((w) => w.tag.nodeName)), [solvedWheels, chassis.com]);
870
1045
  const wheelsAllOff = !enable || isZeroG || wheelConfig?.enable === false && frontWheelConfig?.enable !== true && rearWheelConfig?.enable !== true;
@@ -996,7 +1171,8 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
996
1171
  /* @__PURE__ */ jsx(ZeroGWheelPostClear, {
997
1172
  vehicleRef: innerRef,
998
1173
  zeroGRef,
999
- disabledRotorsRef
1174
+ disabledRotorsRef,
1175
+ solvedByNameRef
1000
1176
  }, `post:${wheelEpoch}`)
1001
1177
  ] })
1002
1178
  ]
@@ -1005,6 +1181,7 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
1005
1181
  vehicleRef: innerRef,
1006
1182
  spawnPos: bodyPos,
1007
1183
  spawnQuat: bodyQuat,
1184
+ enableCustomGravity,
1008
1185
  linearVelocity: effLinVel,
1009
1186
  angularVelocity: effAngVel,
1010
1187
  gravityScale: effGravScale,