@khr3/core 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/vehicle.js CHANGED
@@ -1,9 +1,9 @@
1
- import { C as effectiveJointInertia, D as bodyPoseMatrix, E as KhrValidationError, O as computeLumpedMassProps, S as WorldGravityContext, i as restoreSubtreeOrigin, m as assertUnitScale, o as toColliderMass, p as assertSceneIdentityWorldScale, r as captureSubtreeOrigins, s as KhrCollider, t as BundleSceneHost, x as JointRegistryContext } from "./BundleSceneHost-DUqqPtJF.js";
2
- import React, { useCallback, useContext, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
3
- import { useFrame } from "@react-three/fiber";
4
- import { useRapier } from "@react-three/rapier";
5
- import * as THREE from "three";
1
+ import { E as KhrValidationError, a as MountSubtreeSlot, d as computeLumpedMassProps, f as KhrCollider, i as BundleSceneHost, l as toColliderMass, n as buildJointRuntime, o as captureSubtreeOrigins, r as createRapierImpulseJoint, s as restoreSubtreeOrigin, t as JointRegistryContext, u as bodyPoseMatrix, v as assertSceneIdentityWorldScale, y as assertUnitScale } from "./physicsEcs-9H-Do7eX.js";
2
+ import { useCallback, useContext, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from "react";
3
+ import { RigidBody, useRapier } from "@react-three/rapier";
6
4
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
+ import * as THREE from "three";
6
+ import { useFrame } from "@react-three/fiber";
7
7
  import { EcctrlVehicle, ShapeCastWheel, ThrustPropeller } from "@pinkaphant/ecctrl/vehicle";
8
8
  import { useCustomGravity } from "@pinkaphant/ecctrl/gravity";
9
9
  // src/khrVehicleChassis.ts
@@ -82,7 +82,7 @@ function readSpawnQuat(rotation, quaternion) {
82
82
  ];
83
83
  }
84
84
  function computeChassisMassProps(bodies) {
85
- const dyn = bodies.filter((b) => !b.isKinematic);
85
+ const dyn = bodies.filter((b) => !b.isKinematic).filter((b) => b.joint === null);
86
86
  if (dyn.length === 0) throw new KhrValidationError("KhrVehicle: bundle has no dynamic rigid body for the chassis");
87
87
  const lumped = computeLumpedMassProps(dyn);
88
88
  if (!lumped || !(lumped.mass > 0)) throw new KhrValidationError("KhrVehicle: chassis dynamic mass must be positive");
@@ -182,10 +182,6 @@ function computeRotorLocalMatrix(node, scene, center, quaternion) {
182
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);
183
183
  }
184
184
  // src/khrVehicleJointHelpers.ts
185
- function isJointDescendant(body, ancestorName, byName) {
186
- for (let cur = body.joint ? byName.get(body.joint.connectedNodeName) : void 0; cur; cur = cur.joint ? byName.get(cur.joint.connectedNodeName) : void 0) if (cur.nodeName === ancestorName) return true;
187
- return false;
188
- }
189
185
  function planVehicleJointParts(bodies) {
190
186
  const dyn = bodies.filter((b) => !b.isKinematic);
191
187
  const byName = new Map(dyn.map((b) => [b.nodeName, b]));
@@ -201,43 +197,81 @@ function planVehicleJointParts(bodies) {
201
197
  };
202
198
  jointed.sort((a, b) => depthOf(a) - depthOf(b));
203
199
  const one = new THREE.Vector3(1, 1, 1);
204
- const pos = new THREE.Vector3();
205
- const quat = new THREE.Quaternion();
200
+ const rpPos = new THREE.Vector3();
201
+ const rpQuat = new THREE.Quaternion();
202
+ const rcPos = new THREE.Vector3();
203
+ const rcQuat = new THREE.Quaternion();
206
204
  const scl = new THREE.Vector3();
207
205
  const partByName = /* @__PURE__ */ new Map();
208
206
  return jointed.map((b) => {
209
207
  const joint = b.joint;
210
208
  const parent = partByName.get(joint.connectedNodeName) ?? null;
211
209
  const bodyMat = bodyPoseMatrix(b);
212
- const restRelParent = parent ? bodyPoseMatrix(parent.spec).clone().invert().multiply(bodyMat) : bodyMat;
213
- const descendants = jointed.filter((d) => d !== b && isJointDescendant(d, b.nodeName, byName));
214
- const colliders = b.colliders.map((spec) => {
210
+ (parent ? bodyPoseMatrix(parent.spec) : new THREE.Matrix4()).clone().invert().multiply(bodyMat).decompose(rpPos, rpQuat, scl);
211
+ rpQuat.normalize();
212
+ bodyMat.decompose(rcPos, rcQuat, scl);
213
+ rcQuat.normalize();
214
+ const axChildVec = new THREE.Vector3().fromArray(joint.axis).normalize();
215
+ const axParentVec = axChildVec.clone().applyQuaternion(rpQuat).normalize();
216
+ const ownLumped = computeLumpedMassProps([b], bodyMat.clone().invert());
217
+ const colliders = b.colliders.map((spec, idx) => {
215
218
  const colQuat = new THREE.Quaternion().fromArray(spec.localQuaternion);
216
219
  const local = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(spec.localPosition), colQuat, one);
217
- bodyMat.clone().multiply(local).decompose(pos, quat, scl);
218
- quat.normalize();
219
- return {
220
+ const planned = {
220
221
  spec,
221
222
  local,
222
223
  position: [
223
- pos.x,
224
- pos.y,
225
- pos.z
224
+ spec.localPosition[0],
225
+ spec.localPosition[1],
226
+ spec.localPosition[2]
226
227
  ],
227
228
  quaternion: [
228
- quat.x,
229
- quat.y,
230
- quat.z,
231
- quat.w
229
+ colQuat.x,
230
+ colQuat.y,
231
+ colQuat.z,
232
+ colQuat.w
232
233
  ]
233
234
  };
235
+ if (idx === 0 && ownLumped) planned.massProperties = toColliderMass(ownLumped, local, colQuat);
236
+ return planned;
234
237
  });
235
238
  const plan = {
236
239
  spec: b,
237
240
  joint,
238
241
  parent,
239
- restRelParent,
240
- inertia: effectiveJointInertia(b, joint, descendants),
242
+ restRelParentPos: [
243
+ rpPos.x,
244
+ rpPos.y,
245
+ rpPos.z
246
+ ],
247
+ restRelParentQuat: [
248
+ rpQuat.x,
249
+ rpQuat.y,
250
+ rpQuat.z,
251
+ rpQuat.w
252
+ ],
253
+ restRelChassisPos: [
254
+ rcPos.x,
255
+ rcPos.y,
256
+ rcPos.z
257
+ ],
258
+ restRelChassisQuat: [
259
+ rcQuat.x,
260
+ rcQuat.y,
261
+ rcQuat.z,
262
+ rcQuat.w
263
+ ],
264
+ axisParent: [
265
+ axParentVec.x,
266
+ axParentVec.y,
267
+ axParentVec.z
268
+ ],
269
+ axisChild: [
270
+ axChildVec.x,
271
+ axChildVec.y,
272
+ axChildVec.z
273
+ ],
274
+ ...ownLumped && colliders.length === 0 ? { partMass: toColliderMass(ownLumped) } : {},
241
275
  colliders
242
276
  };
243
277
  partByName.set(b.nodeName, plan);
@@ -250,130 +284,181 @@ function openTargetForLimits(limits) {
250
284
  function isVehicleJointOpen(rt) {
251
285
  if (!rt.limits) return false;
252
286
  const openTgt = openTargetForLimits(rt.limits);
253
- return Math.abs(openTgt) > 1e-6 && Math.abs((rt.positionTarget ?? rt.q) - openTgt) < Math.abs(openTgt) * .5;
254
- }
255
- function createVehicleJointRuntime(part, assemblyId, parent, colliderRefs) {
256
- const drive = part.joint.drive;
257
- return {
258
- assemblyId,
259
- nodeName: part.spec.nodeName,
260
- role: part.joint.role,
261
- kind: part.joint.kind,
262
- object: part.spec.object,
263
- axis: new THREE.Vector3().fromArray(part.joint.axis).normalize(),
264
- restPosition: part.spec.object.position.clone(),
265
- restQuaternion: part.spec.object.quaternion.clone(),
266
- q: 0,
267
- v: 0,
268
- positionTarget: drive?.positionTarget ?? null,
269
- velocityTarget: drive?.velocityTarget ?? 0,
270
- drive,
271
- limits: part.joint.limits,
272
- limitStiffness: part.joint.limitStiffness ?? null,
273
- limitDamping: part.joint.limitDamping ?? 0,
274
- inertia: part.inertia,
275
- parent,
276
- restRelParent: part.restRelParent,
277
- current: part.restRelParent.clone(),
278
- stamp: -1,
279
- colliders: part.colliders.map((c, idx) => ({
280
- ref: colliderRefs[idx],
281
- local: c.local
282
- }))
283
- };
287
+ return Math.abs(openTgt) > 1e-6 && Math.abs((rt.positionTarget ?? rt.getCoordinate()) - openTgt) < Math.abs(openTgt) * .5;
284
288
  }
285
289
  // src/khrVehicleJoints.tsx
286
- var nextVehicleJointAssemblyId = 1e5;
287
- function KhrVehicleJoints({ bodies, vehicleRef, jointsRef }) {
290
+ function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, parentBodyGetter, origin, onBody, onJointReady }) {
291
+ const { rapier, world } = useRapier();
288
292
  const registry = useContext(JointRegistryContext);
289
- const assemblyId = useMemo(() => nextVehicleJointAssemblyId++, []);
290
- const parts = useMemo(() => planVehicleJointParts(bodies), [bodies]);
291
- const colliderRefs = useMemo(() => parts.map((p) => p.colliders.map(() => ({ current: null }))), [parts]);
292
- const runtimeMapRef = React.useRef(/* @__PURE__ */ new Map());
293
- const byObjectRef = React.useRef(/* @__PURE__ */ new Map());
294
- useLayoutEffect(() => {
295
- const map = /* @__PURE__ */ new Map();
296
- const byObj = /* @__PURE__ */ new Map();
297
- for (let i = 0; i < parts.length; i++) {
298
- const part = parts[i];
299
- const parent = part.parent ? map.get(part.parent.spec.nodeName) ?? null : null;
300
- const rt = createVehicleJointRuntime(part, assemblyId, parent, colliderRefs[i]);
301
- map.set(rt.nodeName, rt);
302
- byObj.set(rt.object, rt);
303
- registry?.add(rt);
293
+ const childRef = useRef(null);
294
+ const worldPose = useMemo(() => {
295
+ const sq = new THREE.Quaternion(spawnQuat[0], spawnQuat[1], spawnQuat[2], spawnQuat[3]);
296
+ const pos = new THREE.Vector3().fromArray(part.restRelChassisPos).applyQuaternion(sq).add(new THREE.Vector3(spawnPos[0], spawnPos[1], spawnPos[2]));
297
+ const quat = sq.clone().multiply(new THREE.Quaternion().fromArray(part.restRelChassisQuat)).normalize();
298
+ return {
299
+ pos: [
300
+ pos.x,
301
+ pos.y,
302
+ pos.z
303
+ ],
304
+ quat: [
305
+ quat.x,
306
+ quat.y,
307
+ quat.z,
308
+ quat.w
309
+ ]
310
+ };
311
+ }, [
312
+ part.restRelChassisPos,
313
+ part.restRelChassisQuat,
314
+ spawnPos,
315
+ spawnQuat
316
+ ]);
317
+ useEffect(() => {
318
+ onBody(part.spec.nodeName, childRef.current);
319
+ return () => onBody(part.spec.nodeName, null);
320
+ }, [part.spec.nodeName, onBody]);
321
+ useEffect(() => {
322
+ const rb = childRef.current;
323
+ const pm = part.partMass;
324
+ if (rb && pm) {
325
+ rb.setAdditionalMassProperties(pm.mass, pm.centerOfMass, pm.principalAngularInertia, pm.angularInertiaLocalFrame, true);
326
+ rb.recomputeMassPropertiesFromColliders();
304
327
  }
305
- runtimeMapRef.current = map;
306
- byObjectRef.current = byObj;
328
+ }, [part.partMass]);
329
+ useEffect(() => {
330
+ const parentBody = parentBodyGetter();
331
+ const childBody = childRef.current;
332
+ if (!parentBody || !childBody) return;
333
+ const imp = createRapierImpulseJoint(rapier, world, parentBody, childBody, part.joint, part.restRelParentPos, [
334
+ 0,
335
+ 0,
336
+ 0
337
+ ], part.axisParent, part.axisChild, part.restRelParentQuat);
338
+ const rt = buildJointRuntime({
339
+ rapier,
340
+ nodeName: part.spec.nodeName,
341
+ role: part.joint.role,
342
+ kind: part.joint.kind,
343
+ object: part.spec.object,
344
+ axisParent: part.axisParent,
345
+ anchorParent: part.restRelParentPos,
346
+ restRelQuat: part.restRelParentQuat,
347
+ limits: part.joint.limits,
348
+ drive: part.joint.drive,
349
+ rapierJoint: imp,
350
+ parentBody,
351
+ childBody
352
+ });
353
+ registry?.add(rt);
354
+ onJointReady(rt.nodeName, part.spec.object, rt);
307
355
  return () => {
308
- runtimeMapRef.current = /* @__PURE__ */ new Map();
309
- byObjectRef.current = /* @__PURE__ */ new Map();
310
- for (const rt of map.values()) {
311
- registry?.delete(rt);
312
- rt.object.position.copy(rt.restPosition);
313
- rt.object.quaternion.copy(rt.restQuaternion);
314
- }
356
+ registry?.delete(rt);
357
+ onJointReady(rt.nodeName, part.spec.object, null);
358
+ if (world.getImpulseJoint(imp.handle)) world.removeImpulseJoint(imp, true);
315
359
  };
316
360
  }, [
317
- parts,
318
- colliderRefs,
319
- assemblyId,
320
- registry
361
+ rapier,
362
+ world,
363
+ part,
364
+ parentBodyGetter,
365
+ registry,
366
+ onJointReady
321
367
  ]);
322
- useImperativeHandle(jointsRef, () => {
323
- const applyTarget = (rt, target) => {
324
- if (!rt.drive || rt.drive.stiffness === void 0) throw new KhrValidationError(`Joint "${rt.nodeName}" has no authored drive stiffness; cannot set a position target`);
325
- rt.positionTarget = target;
326
- vehicleRef.current?.body?.wakeUp();
327
- };
328
- return {
329
- get hasJoints() {
330
- return parts.length > 0;
331
- },
332
- get jointNames() {
333
- return parts.map((p) => p.spec.nodeName);
334
- },
335
- getJointAngle: (nodeName) => runtimeMapRef.current.get(nodeName)?.q ?? null,
336
- setJointTarget: (nodeName, target) => {
337
- const rt = runtimeMapRef.current.get(nodeName);
338
- if (rt) applyTarget(rt, target);
339
- },
340
- setRoleTarget: (role, target) => {
341
- for (const rt of runtimeMapRef.current.values()) if (rt.role === role) applyTarget(rt, target);
342
- },
343
- toggleHitObject: (hit) => {
344
- for (let cur = hit; cur; cur = cur.parent) {
345
- const rt = byObjectRef.current.get(cur);
346
- if (rt && rt.limits && rt.drive?.stiffness !== void 0) {
347
- const openTgt = openTargetForLimits(rt.limits);
348
- applyTarget(rt, isVehicleJointOpen(rt) ? 0 : openTgt);
349
- return true;
350
- }
368
+ return /* @__PURE__ */ jsxs(RigidBody, {
369
+ ref: childRef,
370
+ type: "dynamic",
371
+ position: worldPose.pos,
372
+ quaternion: worldPose.quat,
373
+ colliders: false,
374
+ children: [/* @__PURE__ */ jsx(MountSubtreeSlot, {
375
+ object: part.spec.object,
376
+ position: [
377
+ 0,
378
+ 0,
379
+ 0
380
+ ],
381
+ quaternion: [
382
+ 0,
383
+ 0,
384
+ 0,
385
+ 1
386
+ ],
387
+ origin
388
+ }), part.colliders.map((col, cIdx) => /* @__PURE__ */ jsx(KhrCollider, {
389
+ c: col.spec,
390
+ position: col.position,
391
+ quaternion: col.quaternion,
392
+ massProperties: col.massProperties
393
+ }, `vj_${part.spec.nodeName}:${cIdx}`))]
394
+ });
395
+ }
396
+ function KhrVehicleJoints({ bodies, vehicleRef, spawnPos, spawnQuat, jointsRef }) {
397
+ const parts = useMemo(() => planVehicleJointParts(bodies), [bodies]);
398
+ const origins = useMemo(() => parts.length > 0 ? captureSubtreeOrigins(parts.map((p) => p.spec.object)) : null, [parts]);
399
+ const bodyMapRef = useRef(/* @__PURE__ */ new Map());
400
+ const runtimeMapRef = useRef(/* @__PURE__ */ new Map());
401
+ const byObjectRef = useRef(/* @__PURE__ */ new Map());
402
+ const handleBody = useCallback((nodeName, rb) => {
403
+ if (rb) bodyMapRef.current.set(nodeName, rb);
404
+ else bodyMapRef.current.delete(nodeName);
405
+ }, []);
406
+ const handleJointReady = useCallback((nodeName, obj, rt) => {
407
+ if (rt) {
408
+ runtimeMapRef.current.set(nodeName, rt);
409
+ byObjectRef.current.set(obj, rt);
410
+ } else {
411
+ runtimeMapRef.current.delete(nodeName);
412
+ byObjectRef.current.delete(obj);
413
+ }
414
+ }, []);
415
+ useImperativeHandle(jointsRef, () => ({
416
+ get hasJoints() {
417
+ return parts.length > 0;
418
+ },
419
+ get jointNames() {
420
+ return parts.map((p) => p.spec.nodeName);
421
+ },
422
+ getBody: (nodeName) => bodyMapRef.current.get(nodeName) ?? null,
423
+ getJointAngle: (nodeName) => runtimeMapRef.current.get(nodeName)?.getCoordinate() ?? null,
424
+ setJointTarget: (nodeName, target) => {
425
+ runtimeMapRef.current.get(nodeName)?.applyTarget(target);
426
+ },
427
+ setRoleTarget: (role, target) => {
428
+ for (const rt of runtimeMapRef.current.values()) if (rt.role === role) rt.applyTarget(target);
429
+ },
430
+ toggleHitObject: (hit) => {
431
+ for (let cur = hit; cur; cur = cur.parent) {
432
+ const rt = byObjectRef.current.get(cur);
433
+ if (rt && rt.limits && rt.drive?.stiffness !== void 0) {
434
+ rt.applyTarget(isVehicleJointOpen(rt) ? 0 : openTargetForLimits(rt.limits));
435
+ return true;
351
436
  }
352
- return false;
353
- },
354
- toggleRolePrefix: (prefix) => {
355
- const low = prefix.toLowerCase();
356
- 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)));
357
- if (matches.length === 0) return;
358
- const anyOpen = matches.some((rt) => isVehicleJointOpen(rt));
359
- for (const rt of matches) applyTarget(rt, anyOpen ? 0 : openTargetForLimits(rt.limits));
360
437
  }
361
- };
362
- }, [parts, vehicleRef]);
438
+ return false;
439
+ },
440
+ toggleRolePrefix: (prefix) => {
441
+ const low = prefix.toLowerCase();
442
+ 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)));
443
+ if (matches.length === 0) return;
444
+ const anyOpen = matches.some((rt) => isVehicleJointOpen(rt));
445
+ for (const rt of matches) rt.applyTarget(anyOpen ? 0 : openTargetForLimits(rt.limits));
446
+ }
447
+ }), [parts]);
363
448
  if (parts.length === 0) return null;
364
- return /* @__PURE__ */ jsx(Fragment, { children: parts.map((part, pIdx) => part.colliders.map((col, cIdx) => /* @__PURE__ */ jsx(KhrCollider, {
365
- ref: colliderRefs[pIdx][cIdx],
366
- c: col.spec,
367
- position: col.position,
368
- quaternion: col.quaternion
369
- }, `vj_${part.spec.nodeName}:${cIdx}`))) });
449
+ return /* @__PURE__ */ jsx(Fragment, { children: parts.map((part) => /* @__PURE__ */ jsx(VehicleArticulatedPanel, {
450
+ part,
451
+ spawnPos,
452
+ spawnQuat,
453
+ parentBodyGetter: () => part.parent ? bodyMapRef.current.get(part.parent.spec.nodeName) ?? null : vehicleRef.current?.body ?? null,
454
+ origin: origins?.get(part.spec.object),
455
+ onBody: handleBody,
456
+ onJointReady: handleJointReady
457
+ }, part.spec.nodeName)) });
370
458
  }
371
459
  // src/khrVehicleSlots.tsx
372
460
  var captureRotorOrigins = captureSubtreeOrigins;
373
461
  var _samplePos = new THREE.Vector3();
374
- function isZeroGravityVec(x, y, z) {
375
- return x * x + y * y + z * z <= 1e-12;
376
- }
377
462
  function resetAllWheelHits(handle) {
378
463
  if (!handle) return;
379
464
  for (const wheelRef of handle.wheelsInfo.values()) {
@@ -391,46 +476,38 @@ function resetAllWheelHits(handle) {
391
476
  w.effInertia = 0;
392
477
  }
393
478
  }
394
- function ZeroGWheelPreGuard({ vehicleRef, enable, enableCustomGravity, spawnPos, wheelActiveRef, zeroGRef, customPrimedRef, needsEpochBumpRef, onZeroGChange, onCustomPrimed, onBumpWheelEpoch }) {
479
+ /**
480
+ * Gates `<ShapeCastWheel>` only when gravity is non-zero (`gravityMag > 1e-6`), preventing
481
+ * `ShapeCastWheel`'s internal `smoothedLngImpulse += Infinity` closure poisoning in 0G.
482
+ */
483
+ function ZeroGWheelGate({ vehicleRef, enable, enableCustomGravity, spawnPos, zeroGRef, onZeroGChange }) {
395
484
  const { world } = useRapier();
396
485
  useFrame(() => {
397
486
  if (!enable) return;
398
487
  const handle = vehicleRef.current;
399
- let isZeroG;
488
+ let gSq;
400
489
  if (enableCustomGravity) {
401
- if (handle?.body && !handle.body.isSleeping()) isZeroG = handle.gravityMag <= 1e-6;
490
+ if (handle?.body && !handle.body.isSleeping()) gSq = handle.gravityMag * handle.gravityMag;
402
491
  else {
403
- const body = handle?.body;
404
- if (body) {
405
- const t = body.translation();
406
- _samplePos.set(t.x, t.y, t.z);
407
- } else _samplePos.set(spawnPos[0], spawnPos[1], spawnPos[2]);
408
- const g = useCustomGravity.getState().gravityField(_samplePos);
409
- isZeroG = isZeroGravityVec(g.x, g.y, g.z);
410
- }
411
- if (!customPrimedRef.current) {
412
- customPrimedRef.current = true;
413
- onCustomPrimed();
492
+ const t = handle?.body?.translation();
493
+ if (t) _samplePos.set(t.x, t.y, t.z);
494
+ else _samplePos.set(spawnPos[0], spawnPos[1], spawnPos[2]);
495
+ gSq = useCustomGravity.getState().gravityField(_samplePos).lengthSq();
414
496
  }
415
497
  } else {
416
498
  const g = world.gravity;
417
- isZeroG = isZeroGravityVec(g.x, g.y, g.z);
499
+ gSq = g.x * g.x + g.y * g.y + g.z * g.z;
418
500
  }
501
+ const isZeroG = gSq <= 1e-12;
419
502
  if (isZeroG !== zeroGRef.current) {
420
- const wasActive = wheelActiveRef.current;
421
503
  zeroGRef.current = isZeroG;
422
- if (isZeroG && wasActive) needsEpochBumpRef.current = true;
423
- else if (!isZeroG && needsEpochBumpRef.current) {
424
- needsEpochBumpRef.current = false;
425
- onBumpWheelEpoch();
426
- }
427
504
  onZeroGChange(isZeroG);
428
505
  }
429
506
  if (isZeroG) resetAllWheelHits(handle);
430
507
  });
431
508
  return null;
432
509
  }
433
- function ZeroGWheelPostGuard({ vehicleRef, zeroGRef }) {
510
+ function ZeroGWheelPostClear({ vehicleRef, zeroGRef }) {
434
511
  useFrame(() => {
435
512
  if (zeroGRef.current) resetAllWheelHits(vehicleRef.current);
436
513
  });
@@ -652,46 +729,34 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
652
729
  assertSceneIdentityWorldScale(bundle.scene);
653
730
  const { ref, vehicleRef, jointsRef, position, rotation, quaternion, enable = true, enableCustomGravity = false, carConfig, droneConfig, wheelConfig, frontWheelConfig, rearWheelConfig, propellerConfig, linearVelocity, angularVelocity, gravityScale, children, ...ecctrlRest } = rest;
654
731
  const { world } = useRapier();
655
- const worldGravity = useContext(WorldGravityContext);
656
- const propZeroG = worldGravity ? isZeroGravityVec(worldGravity[0], worldGravity[1], worldGravity[2]) : false;
657
- const [rotorsPrimed, setRotorsPrimed] = useState(false);
658
- const [customPrimed, setCustomPrimed] = useState(() => !enableCustomGravity);
659
- const [runtimeZeroG, setRuntimeZeroG] = useState(() => !enableCustomGravity && (propZeroG || isZeroGravityVec(world.gravity.x, world.gravity.y, world.gravity.z)));
732
+ const [rotorsMounted, setRotorsMounted] = useState(false);
733
+ const [isZeroG, setIsZeroG] = useState(() => {
734
+ if (enableCustomGravity) return true;
735
+ const g = world.gravity;
736
+ return g.x * g.x + g.y * g.y + g.z * g.z <= 1e-12;
737
+ });
660
738
  const [wheelEpoch, setWheelEpoch] = useState(0);
661
- const customPrimedRef = useRef(!enableCustomGravity);
662
- const zeroGRef = useRef(runtimeZeroG);
663
- const needsEpochBumpRef = useRef(false);
664
- const wheelEnable = enable && customPrimed && !(!enableCustomGravity && propZeroG) && !runtimeZeroG;
665
- const wheelActiveRef = useRef(wheelEnable);
666
- wheelActiveRef.current = wheelEnable;
667
- const bumpWheelEpoch = useCallback(() => setWheelEpoch((e) => e + 1), []);
668
- const markCustomPrimed = useCallback(() => setCustomPrimed(true), []);
739
+ const zeroGRef = useRef(isZeroG);
740
+ const poisonedRef = useRef(false);
669
741
  useLayoutEffect(() => {
670
- setRotorsPrimed(true);
742
+ setRotorsMounted(true);
671
743
  }, []);
672
- useLayoutEffect(() => {
673
- if (enableCustomGravity) {
674
- customPrimedRef.current = false;
675
- setCustomPrimed(false);
676
- } else {
677
- customPrimedRef.current = true;
678
- setCustomPrimed(true);
679
- const isZeroG = propZeroG || isZeroGravityVec(world.gravity.x, world.gravity.y, world.gravity.z);
680
- zeroGRef.current = isZeroG;
681
- setRuntimeZeroG(isZeroG);
682
- if (isZeroG) resetAllWheelHits(innerRef.current);
744
+ const handleZeroGChange = useCallback((nextZeroG) => {
745
+ if (nextZeroG) {
746
+ poisonedRef.current = true;
747
+ resetAllWheelHits(innerRef.current);
748
+ } else if (poisonedRef.current) {
749
+ poisonedRef.current = false;
750
+ setWheelEpoch((e) => e + 1);
683
751
  }
684
- }, [
685
- enableCustomGravity,
686
- propZeroG,
687
- world
688
- ]);
752
+ setIsZeroG(nextZeroG);
753
+ }, []);
689
754
  const chassis = useMemo(() => computeChassisMassProps(bundle.bodies), [bundle]);
690
755
  const collidersList = useMemo(() => buildChassisColliders(bundle.bodies, chassis), [bundle.bodies, chassis]);
691
- const solvedWheels = useMemo(() => solveWheelLoads(bundle.wheels, chassis.mass, chassis.com), [
756
+ const solvedWheels = useMemo(() => solveWheelLoads(bundle.wheels, bundle.totalDynamicMass, bundle.centerOfMass), [
692
757
  bundle.wheels,
693
- chassis.mass,
694
- chassis.com
758
+ bundle.totalDynamicMass,
759
+ bundle.centerOfMass
695
760
  ]);
696
761
  const rotorOrigins = useMemo(() => captureRotorOrigins([...bundle.wheels.map((w) => w.object), ...bundle.propellers.map((p) => p.object)]), [bundle.wheels, bundle.propellers]);
697
762
  const [px, py, pz] = readPosTuple(position);
@@ -748,7 +813,7 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
748
813
  const effLinVel = linearVelocity ?? chassis.linearVelocity;
749
814
  const effAngVel = angularVelocity ?? chassis.angularVelocity;
750
815
  const effGravScale = gravityScale ?? chassis.gravityFactor;
751
- return /* @__PURE__ */ jsxs(EcctrlVehicle, {
816
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs(EcctrlVehicle, {
752
817
  ref: assignRef,
753
818
  enable,
754
819
  enableCustomGravity,
@@ -770,24 +835,14 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
770
835
  c: spec,
771
836
  massProperties
772
837
  }, key)),
773
- /* @__PURE__ */ jsx(KhrVehicleJoints, {
774
- bodies: bundle.bodies,
775
- vehicleRef: innerRef,
776
- jointsRef
777
- }),
778
- rotorsPrimed && /* @__PURE__ */ jsxs(Fragment, { children: [
779
- /* @__PURE__ */ jsx(ZeroGWheelPreGuard, {
838
+ rotorsMounted && /* @__PURE__ */ jsxs(Fragment, { children: [
839
+ /* @__PURE__ */ jsx(ZeroGWheelGate, {
780
840
  vehicleRef: innerRef,
781
841
  enable,
782
842
  enableCustomGravity,
783
843
  spawnPos: bodyPos,
784
- wheelActiveRef,
785
844
  zeroGRef,
786
- customPrimedRef,
787
- needsEpochBumpRef,
788
- onZeroGChange: setRuntimeZeroG,
789
- onCustomPrimed: markCustomPrimed,
790
- onBumpWheelEpoch: bumpWheelEpoch
845
+ onZeroGChange: handleZeroGChange
791
846
  }),
792
847
  /* @__PURE__ */ jsx(KhrVehicleRotors, {
793
848
  solvedWheels,
@@ -796,20 +851,26 @@ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
796
851
  comZ: chassis.com[2],
797
852
  rotorOrigins,
798
853
  enable,
799
- wheelEnable,
854
+ wheelEnable: enable && !isZeroG,
800
855
  wheelEpoch,
801
856
  wheelConfig,
802
857
  frontWheelConfig,
803
858
  rearWheelConfig,
804
859
  propellerConfig
805
860
  }),
806
- /* @__PURE__ */ jsx(ZeroGWheelPostGuard, {
861
+ /* @__PURE__ */ jsx(ZeroGWheelPostClear, {
807
862
  vehicleRef: innerRef,
808
863
  zeroGRef
809
- })
864
+ }, `post:${wheelEpoch}`)
810
865
  ] })
811
866
  ]
812
- });
867
+ }), rotorsMounted && /* @__PURE__ */ jsx(KhrVehicleJoints, {
868
+ bodies: bundle.bodies,
869
+ vehicleRef: innerRef,
870
+ spawnPos: bodyPos,
871
+ spawnQuat: bodyQuat,
872
+ jointsRef
873
+ })] });
813
874
  }
814
875
  export { KhrVehicle, solveWheelLoads };
815
876