@khr3/core 0.2.10 → 0.2.12

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