@khr3/core 0.1.5 → 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.
Files changed (46) hide show
  1. package/README.md +3 -114
  2. package/dist/AssemblyRootBody.d.ts +2 -3
  3. package/dist/KhrAssembly.d.ts +3 -5
  4. package/dist/KhrCollider.d.ts +1 -1
  5. package/dist/KhrVehicle.d.ts +5 -7
  6. package/dist/PhysicsWorld.d.ts +2 -2
  7. package/dist/assemblyPlan.d.ts +10 -9
  8. package/dist/curves.d.ts +11 -32
  9. package/dist/curves.js +141 -139
  10. package/dist/curves.js.map +1 -0
  11. package/dist/index.d.ts +3 -2
  12. package/dist/index.js +1708 -1284
  13. package/dist/index.js.map +1 -0
  14. package/dist/jointDynamics.d.ts +21 -17
  15. package/dist/khrBundleFinalize.d.ts +14 -0
  16. package/dist/khrConfigTypes.d.ts +62 -0
  17. package/dist/khrExportEncoders.d.ts +8 -0
  18. package/dist/khrExporter.d.ts +2 -1
  19. package/dist/khrExtras.d.ts +3 -3
  20. package/dist/khrGlb.d.ts +18 -0
  21. package/dist/khrJointParser.d.ts +3 -0
  22. package/dist/khrLoader.d.ts +2 -1
  23. package/dist/khrParsers.d.ts +5 -9
  24. package/dist/khrPlugin.d.ts +2 -3
  25. package/dist/khrPluginHelpers.d.ts +4 -0
  26. package/dist/khrRotorDecoders.d.ts +4 -0
  27. package/dist/khrShapeParser.d.ts +8 -0
  28. package/dist/khrTypes.d.ts +11 -103
  29. package/dist/khrVehicleChassis.d.ts +9 -17
  30. package/dist/khrVehicleJointHelpers.d.ts +22 -0
  31. package/dist/khrVehicleJoints.d.ts +22 -0
  32. package/dist/khrVehicleRotors.d.ts +22 -0
  33. package/dist/khrVehicleSlots.d.ts +17 -15
  34. package/dist/khrVehicleTypes.d.ts +52 -0
  35. package/dist/pacejka.d.ts +1 -1
  36. package/dist/physicsEcs-9H-Do7eX.js +1060 -0
  37. package/dist/physicsEcs-9H-Do7eX.js.map +1 -0
  38. package/dist/physicsEcs.d.ts +9 -45
  39. package/dist/useKhrGlb.d.ts +2 -2
  40. package/dist/vehicle.d.ts +2 -2
  41. package/dist/vehicle.js +821 -454
  42. package/dist/vehicle.js.map +1 -0
  43. package/dist/wheelLoads.d.ts +4 -7
  44. package/docs/api-reference.md +208 -0
  45. package/package.json +8 -7
  46. package/dist/BundleSceneHost-CE3HPB8a.js +0 -556
package/dist/vehicle.js CHANGED
@@ -1,34 +1,33 @@
1
- import { C as e, S as t, T as n, a as r, b as i, d as a, f as o, i as s, r as c, t as l, x as u } from "./BundleSceneHost-CE3HPB8a.js";
2
- import { useCallback as d, useContext as f, useEffect as p, useLayoutEffect as m, useMemo as h, useRef as g, useState as _ } from "react";
3
- import { useFrame as v } from "@react-three/fiber";
4
- import { useAfterPhysicsStep as y, useRapier as b } from "@react-three/rapier";
5
- import * as x from "three";
6
- import { jsx as S, jsxs as C } from "react/jsx-runtime";
7
- import { useCustomGravity as w } from "@pinkaphant/ecctrl/gravity";
8
- import { EcctrlVehicle as T, ShapeCastWheel as ee, ThrustPropeller as te } from "@pinkaphant/ecctrl/vehicle";
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";
4
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
+ import * as THREE from "three";
6
+ import { useFrame } from "@react-three/fiber";
7
+ import { EcctrlVehicle, ShapeCastWheel, ThrustPropeller } from "@pinkaphant/ecctrl/vehicle";
8
+ import { useCustomGravity } from "@pinkaphant/ecctrl/gravity";
9
9
  // src/khrVehicleChassis.ts
10
- var E = new x.Euler(), D = new x.Quaternion(), O = new x.Matrix4(), k = new x.Vector3(), A = new x.Vector3(1, 1, 1);
11
- function j(t, n) {
12
- if (n !== void 0) throw new e(`KhrVehicle: colliders prop cannot be overridden (got ${JSON.stringify(n)}); colliders are authored in the .glb`);
13
- o(t, "KhrVehicle");
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");
14
13
  }
15
- function M(e) {
16
- if (typeof e == "number") return [
17
- e,
18
- e,
19
- e
14
+ function readPosTuple(pos) {
15
+ if (typeof pos === "number") return [
16
+ pos,
17
+ pos,
18
+ pos
20
19
  ];
21
- if (Array.isArray(e)) return [
22
- e[0] ?? 0,
23
- e[1] ?? 0,
24
- e[2] ?? 0
20
+ if (Array.isArray(pos)) return [
21
+ Number(pos[0] ?? 0),
22
+ Number(pos[1] ?? 0),
23
+ Number(pos[2] ?? 0)
25
24
  ];
26
- if (e && typeof e == "object" && "x" in e) {
27
- let t = e;
25
+ if (pos && typeof pos === "object" && "x" in pos) {
26
+ const v = pos;
28
27
  return [
29
- t.x,
30
- t.y,
31
- t.z
28
+ Number(v.x ?? 0),
29
+ Number(v.y ?? 0),
30
+ Number(v.z ?? 0)
32
31
  ];
33
32
  }
34
33
  return [
@@ -37,474 +36,842 @@ function M(e) {
37
36
  0
38
37
  ];
39
38
  }
40
- function N(e, t) {
41
- return t === void 0 ? e === void 0 ? [
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 [
42
78
  0,
43
79
  0,
44
80
  0,
45
81
  1
46
- ] : (typeof e == "number" ? E.set(e, e, e, "XYZ") : Array.isArray(e) ? E.set(e[0], e[1], e[2], e[3] ?? "XYZ") : typeof e == "object" && "x" in e ? E.copy(e) : E.set(0, 0, 0, "XYZ"), D.setFromEuler(E), [
47
- D.x,
48
- D.y,
49
- D.z,
50
- D.w
51
- ]) : (Array.isArray(t) ? D.set(t[0], t[1], t[2], t[3]) : typeof t == "object" && "x" in t ? D.copy(t) : D.identity(), D.lengthSq() > 0 && D.normalize(), [
52
- D.x,
53
- D.y,
54
- D.z,
55
- D.w
56
- ]);
82
+ ];
57
83
  }
58
- function ne(t) {
59
- let r = t.filter((e) => !e.isKinematic), i = n(r);
60
- if (!i) throw new e("KhrVehicle: bundle has no dynamic KHR motion.mass; author a dynamic chassis node with mass");
61
- let { mass: a, com: o, inertia: s, inertiaFrame: c } = i;
62
- if (!(s[0] > 0 && s[1] > 0 && s[2] > 0)) throw new e(`KhrVehicle: authored inertia is non-positive [${s.join(", ")}]`);
63
- let l = r.find((e) => e.joint === null) ?? r[0], u = r.filter((e) => e.gravityFactor !== void 0).map((e) => e.gravityFactor), d;
64
- if (u.length > 0) {
65
- if (u.some((e) => Math.abs(e - u[0]) > 1e-6)) throw new e("KhrVehicle: dynamic chassis bodies have conflicting motion.gravityFactor values");
66
- d = u[0];
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;
67
95
  }
68
- let f = r.filter((e) => e.linearVelocity !== void 0), p;
69
- if (f.length === 1) p = f[0].linearVelocity;
70
- else if (f.length > 1) {
71
- let e = f.reduce((e, t) => e + t.mass, 0);
72
- p = [
73
- f.reduce((e, t) => e + t.linearVelocity[0] * t.mass, 0) / e,
74
- f.reduce((e, t) => e + t.linearVelocity[1] * t.mass, 0) / e,
75
- f.reduce((e, t) => e + t.linearVelocity[2] * t.mass, 0) / e
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
76
115
  ];
77
116
  }
78
- let m = r.filter((e) => e.angularVelocity !== void 0), h = m.length === 1 ? m[0].angularVelocity : l.angularVelocity ?? m[0]?.angularVelocity;
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;
79
123
  return {
80
- mass: a,
81
- com: o,
82
- inertia: s,
83
- inertiaFrame: c,
84
- ...p ? { linearVelocity: p } : {},
85
- ...h ? { angularVelocity: h } : {},
86
- ...d === void 0 ? {} : { gravityFactor: d }
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 } : {}
87
131
  };
88
132
  }
89
- function re(e, t) {
90
- let n = new x.Vector3(), r = new x.Quaternion(), i = new x.Vector3(), a = new x.Quaternion(), o = new x.Quaternion();
91
- return e.flatMap((e) => (n.fromArray(e.localPosition), r.fromArray(e.localQuaternion), e.colliders.map((s, c) => (i.fromArray(s.localPosition).applyQuaternion(r).add(n), a.copy(r).multiply(o.fromArray(s.localQuaternion)), {
92
- key: `${e.nodeName}-${c}`,
93
- spec: {
94
- shape: s.shape,
95
- localPosition: [
96
- i.x - t[0],
97
- i.y - t[1],
98
- i.z - t[2]
99
- ],
100
- localQuaternion: [
101
- a.x,
102
- a.y,
103
- a.z,
104
- a.w
105
- ],
106
- ...s.friction === void 0 ? {} : { friction: s.friction },
107
- ...s.restitution === void 0 ? {} : { restitution: s.restitution },
108
- ...s.collisionGroups === void 0 ? {} : { collisionGroups: s.collisionGroups }
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
+ });
109
167
  }
110
- }))));
111
- }
112
- function ie(t, n, r, i) {
113
- let a = new x.Matrix4();
114
- for (let r = t; r && r !== n; r = r.parent) {
115
- if (!r.parent) throw new e(`KhrVehicle: rotor node "${t.name}" is detached from bundle.scene`);
116
- r.updateMatrix(), a.premultiply(r.matrix);
117
168
  }
118
- return k.set(r[0], r[1], r[2]), i ? D.set(i[0], i[1], i[2], i[3]).normalize() : D.identity(), O.compose(k, D, A).invert().clone().multiply(a);
169
+ if (out.length === 0) throw new KhrValidationError("KhrVehicle: chassis has no colliders");
170
+ return out;
119
171
  }
120
- function ae(e, t, n, r, i, a) {
121
- let o = e[t], s;
122
- if (r || i) {
123
- let t = !1, n = !1, a = 0;
124
- for (let r of e) r.steer ? t = !0 : n = !0, a += r.position[2];
125
- if (t && n) s = o.steer ? r : i;
126
- else {
127
- let t = o.position[2] - a / e.length;
128
- t > 1e-4 ? s = r : t < -1e-4 && (s = i);
129
- }
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;
130
180
  }
131
- let c = typeof a == "function" ? a(o, t) : a?.[o.nodeName];
132
- if (n || s || c) return {
133
- ...n,
134
- ...s,
135
- ...c
136
- };
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);
137
183
  }
138
- function oe(e, t, n, r) {
139
- let i = typeof r == "function" ? r(e, t) : r?.[e.nodeName];
140
- if (n || i) return {
141
- ...n,
142
- ...i
184
+ // src/khrVehicleJointHelpers.ts
185
+ function planVehicleJointParts(bodies) {
186
+ const dyn = bodies.filter((b) => !b.isKinematic);
187
+ const byName = new Map(dyn.map((b) => [b.nodeName, b]));
188
+ const jointed = dyn.filter((b) => b.joint !== null);
189
+ if (jointed.length === 0) return [];
190
+ const depthOf = (b, seen = /* @__PURE__ */ new Set()) => {
191
+ if (!b.joint) return 0;
192
+ if (seen.has(b.nodeName)) throw new KhrValidationError(`Joint cycle through "${b.nodeName}"`);
193
+ seen.add(b.nodeName);
194
+ const parent = byName.get(b.joint.connectedNodeName);
195
+ if (!parent) throw new KhrValidationError(`Vehicle joint on "${b.nodeName}" targets "${b.joint.connectedNodeName}", which is not a dynamic KHR body`);
196
+ return 1 + depthOf(parent, seen);
143
197
  };
198
+ jointed.sort((a, b) => depthOf(a) - depthOf(b));
199
+ const one = new THREE.Vector3(1, 1, 1);
200
+ const rpPos = new THREE.Vector3();
201
+ const rpQuat = new THREE.Quaternion();
202
+ const rcPos = new THREE.Vector3();
203
+ const rcQuat = new THREE.Quaternion();
204
+ const scl = new THREE.Vector3();
205
+ const partByName = /* @__PURE__ */ new Map();
206
+ return jointed.map((b) => {
207
+ const joint = b.joint;
208
+ const parent = partByName.get(joint.connectedNodeName) ?? null;
209
+ const bodyMat = bodyPoseMatrix(b);
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) => {
218
+ const colQuat = new THREE.Quaternion().fromArray(spec.localQuaternion);
219
+ const local = new THREE.Matrix4().compose(new THREE.Vector3().fromArray(spec.localPosition), colQuat, one);
220
+ const planned = {
221
+ spec,
222
+ local,
223
+ position: [
224
+ spec.localPosition[0],
225
+ spec.localPosition[1],
226
+ spec.localPosition[2]
227
+ ],
228
+ quaternion: [
229
+ colQuat.x,
230
+ colQuat.y,
231
+ colQuat.z,
232
+ colQuat.w
233
+ ]
234
+ };
235
+ if (idx === 0 && ownLumped) planned.massProperties = toColliderMass(ownLumped, local, colQuat);
236
+ return planned;
237
+ });
238
+ const plan = {
239
+ spec: b,
240
+ joint,
241
+ parent,
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) } : {},
275
+ colliders
276
+ };
277
+ partByName.set(b.nodeName, plan);
278
+ return plan;
279
+ });
144
280
  }
145
- // src/khrVehicleSlots.tsx
146
- var P = new x.Vector3();
147
- function F(e) {
148
- e.rayHit !== null && (e.rayHit = null, e.floatImp.set(0, 0, 0), e.lngFricImp.set(0, 0, 0), e.latFricImp.set(0, 0, 0));
281
+ function openTargetForLimits(limits) {
282
+ return Math.abs(limits[0]) > Math.abs(limits[1]) ? limits[0] : limits[1];
149
283
  }
150
- var se = c;
151
- function ce({ object: e, center: t, quaternion: n, scene: r, origin: i }) {
152
- let a = g(null);
153
- return m(() => {
154
- let o = a.current?.parent;
155
- if (!o) return;
156
- let l = i ?? c([e]).get(e), u = ie(e, r, t, n);
157
- return l.origParent && l.origParent.remove(e), u.decompose(e.position, e.quaternion, e.scale), o.add(e), () => {
158
- e.parent === o && o.remove(e), s(e, l);
284
+ function isVehicleJointOpen(rt) {
285
+ if (!rt.limits) return false;
286
+ const openTgt = openTargetForLimits(rt.limits);
287
+ return Math.abs(openTgt) > 1e-6 && Math.abs((rt.positionTarget ?? rt.getCoordinate()) - openTgt) < Math.abs(openTgt) * .5;
288
+ }
289
+ // src/khrVehicleJoints.tsx
290
+ function VehicleArticulatedPanel({ part, spawnPos, spawnQuat, parentBodyGetter, origin, onBody, onJointReady }) {
291
+ const { rapier, world } = useRapier();
292
+ const registry = useContext(JointRegistryContext);
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
+ ]
159
310
  };
160
311
  }, [
161
- e,
162
- t,
163
- n,
164
- r,
165
- i
166
- ]), /* @__PURE__ */ S("group", { ref: a });
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();
327
+ }
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);
355
+ return () => {
356
+ registry?.delete(rt);
357
+ onJointReady(rt.nodeName, part.spec.object, null);
358
+ if (world.getImpulseJoint(imp.handle)) world.removeImpulseJoint(imp, true);
359
+ };
360
+ }, [
361
+ rapier,
362
+ world,
363
+ part,
364
+ parentBodyGetter,
365
+ registry,
366
+ onJointReady
367
+ ]);
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;
436
+ }
437
+ }
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]);
448
+ if (parts.length === 0) return null;
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)) });
167
458
  }
168
- function I(e, t) {
169
- let n = 0;
170
- for (let r of e.wheelsInfo.values()) {
171
- let i = r.current;
172
- if (!t.has(i.name ?? "") || !i.rayHit) continue;
173
- let a = Math.min(1, Math.max(-1, i.rayHitNormal.dot(e.upAxis))), o = Math.sqrt(Math.max(0, 1 - a * a));
174
- o > n && (n = o);
459
+ // src/khrVehicleSlots.tsx
460
+ var captureRotorOrigins = captureSubtreeOrigins;
461
+ var _samplePos = new THREE.Vector3();
462
+ function resetAllWheelHits(handle) {
463
+ if (!handle) return;
464
+ for (const wheelRef of handle.wheelsInfo.values()) {
465
+ const w = wheelRef.current;
466
+ if (!w) continue;
467
+ w.rayHit = null;
468
+ w.rayHitBody = null;
469
+ w.floatImp.set(0, 0, 0);
470
+ w.lngFricImp.set(0, 0, 0);
471
+ w.latFricImp.set(0, 0, 0);
472
+ w.lngSlipRatio = 0;
473
+ w.latSlipRatio = 0;
474
+ w.slipStrength = 0;
475
+ w.isOnPlatform = false;
476
+ w.effInertia = 0;
175
477
  }
176
- return n;
177
478
  }
178
- function le({ vehicleRef: e, active: n, hasRenderGravity: r, enableCustomGravity: i, activeWheelNames: a, gravityPrimedRef: o, setGravityPrimed: s, spatialZeroGRef: c, setSpatialZeroG: l }) {
179
- let u = f(t), d = g(0);
180
- return y(() => {
181
- let t = e.current, n = t?.body;
182
- if (!t || !n) return;
183
- let r = !1;
184
- if (i) {
185
- let e = n.translation();
186
- if (P.set(e.x, e.y, e.z), r = w.getState().gravityField(P).lengthSq() <= 1e-12, r) for (let e of t.wheelsInfo.values()) F(e.current);
187
- r !== c.current && (c.current = r, l(r));
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 }) {
484
+ const { world } = useRapier();
485
+ useFrame(() => {
486
+ if (!enable) return;
487
+ const handle = vehicleRef.current;
488
+ let gSq;
489
+ if (enableCustomGravity) {
490
+ if (handle?.body && !handle.body.isSleeping()) gSq = handle.gravityMag * handle.gravityMag;
491
+ else {
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();
496
+ }
497
+ } else {
498
+ const g = world.gravity;
499
+ gSq = g.x * g.x + g.y * g.y + g.z * g.z;
188
500
  }
189
- let a = !r && t.gravityMag > 1e-6;
190
- a !== o.current && (o.current = a, s(a));
191
- }), v(() => {
192
- let t = e.current, i = t?.body;
193
- if (!t || !i) return;
194
- for (let e of t.wheelsInfo.values()) {
195
- let t = e.current;
196
- a.has(t.name ?? "") || F(t);
501
+ const isZeroG = gSq <= 1e-12;
502
+ if (isZeroG !== zeroGRef.current) {
503
+ zeroGRef.current = isZeroG;
504
+ onZeroGChange(isZeroG);
197
505
  }
198
- if (!n || u !== null && !(u.current > 0)) return;
199
- (r && !c.current && !o.current || (!r || c.current) && t.gravityMag > 1e-6) && i.isSleeping() && i.wakeUp();
200
- let s = t.input, l = Math.abs(s.joystickL?.x ?? 0) > .001, f = Math.abs(s.joystickL?.y ?? 0) > .001, p = Math.abs(s.joystickR?.x ?? 0) > .001 || Math.abs(s.joystickR?.y ?? 0) > .001, m = !!(s.forward || s.backward), h = !!(s.steerLeft || s.steerRight || l), g = !!s.brake, _ = !!(f || p || s.throttleUp || s.throttleDown || s.yawLeft || s.yawRight || s.pitchForward || s.pitchBackward || s.rollLeft || s.rollRight), v = !!m | (h ? 2 : 0) | (g ? 4 : 0) | (_ ? 8 : 0), y = d.current;
201
- d.current = v, i.isSleeping() ? (v & 11 & ~(y & 11) || y & 4 && !g) && i.wakeUp() : (!g && h || g && I(t, a) >= .025) && i.wakeUp();
202
- }), null;
506
+ if (isZeroG) resetAllWheelHits(handle);
507
+ });
508
+ return null;
203
509
  }
204
- // src/wheelLoads.ts
205
- var L = 9.80665;
206
- function R(e) {
207
- let t = e.travel - e.sag, n = e.quaternion;
208
- if (!n) return [
209
- e.position[0],
210
- e.position[1] + t,
211
- e.position[2]
212
- ];
213
- let [r, i, a, o] = n, s = 2 * (r * i - o * a), c = 1 - 2 * (r * r + a * a), l = 2 * (i * a + o * r);
214
- return [
215
- e.position[0] + s * t,
216
- e.position[1] + c * t,
217
- e.position[2] + l * t
218
- ];
510
+ function ZeroGWheelPostClear({ vehicleRef, zeroGRef }) {
511
+ useFrame(() => {
512
+ if (zeroGRef.current) resetAllWheelHits(vehicleRef.current);
513
+ });
514
+ return null;
515
+ }
516
+ function RotorVisualSlot({ object, center, quaternion, scene, origin }) {
517
+ const slotRef = useRef(null);
518
+ useLayoutEffect(() => {
519
+ const slot = slotRef.current;
520
+ const parent = slot?.parent ?? null;
521
+ if (!slot || !parent) return;
522
+ const snap = origin ?? captureSubtreeOrigins([object]).get(object);
523
+ scene.updateMatrixWorld(true);
524
+ const localMat = computeRotorLocalMatrix(object, scene, center, quaternion);
525
+ if (snap.origParent) snap.origParent.remove(object);
526
+ const pos = new THREE.Vector3();
527
+ const quat = new THREE.Quaternion();
528
+ const scl = new THREE.Vector3();
529
+ localMat.decompose(pos, quat, scl);
530
+ object.position.copy(pos);
531
+ object.quaternion.copy(quat.normalize());
532
+ object.scale.copy(scl);
533
+ slot.add(object);
534
+ return () => {
535
+ if (object.parent === slot) slot.remove(object);
536
+ restoreSubtreeOrigin(object, snap);
537
+ };
538
+ }, [
539
+ object,
540
+ center,
541
+ quaternion,
542
+ scene,
543
+ origin
544
+ ]);
545
+ return /* @__PURE__ */ jsx("group", { ref: slotRef });
546
+ }
547
+ // src/khrVehicleRotors.tsx
548
+ var G_SI$1 = 9.81;
549
+ var UNSPRUNG_CORNER_RATIO = .035;
550
+ function KhrVehicleRotors({ solvedWheels, propellers, scene, comZ, rotorOrigins, enable, wheelEnable, wheelEpoch = 0, wheelConfig, frontWheelConfig, rearWheelConfig, propellerConfig }) {
551
+ return /* @__PURE__ */ jsxs(Fragment, { children: [solvedWheels.map(({ tag, cornerMassKg, springK, dampingC, mountPos }) => {
552
+ const axleCfg = mountPos[2] >= comZ ? frontWheelConfig : rearWheelConfig;
553
+ const wheelVol = Math.max(Math.PI * tag.radius * tag.radius * tag.width, 1e-6);
554
+ const wheelModelDensity = tag.wheelDensity ?? UNSPRUNG_CORNER_RATIO * cornerMassKg / wheelVol;
555
+ const tagWheelProps = {
556
+ rayLength: tag.travel,
557
+ rayShapeR: tag.radius,
558
+ rayShapeH: tag.width * .5,
559
+ wheelModelRadius: tag.radius,
560
+ wheelModelDensity,
561
+ springK,
562
+ dampingC,
563
+ steerWheel: tag.steer,
564
+ driveWheel: tag.drive,
565
+ brakeWheel: tag.brake,
566
+ maxBrakeTorque: tag.maxBrakeTorque ?? cornerMassKg * G_SI$1 * tag.radius,
567
+ ...tag.steerInvert !== void 0 ? { steerInvert: tag.steerInvert } : {},
568
+ ...tag.driveInvert !== void 0 ? { driveInvert: tag.driveInvert } : {},
569
+ ...tag.driveTorqueWeight !== void 0 ? { driveTorqueWeight: tag.driveTorqueWeight } : {},
570
+ ...tag.rollingResistanceCoef !== void 0 ? { rollingResistanceCoef: tag.rollingResistanceCoef } : {},
571
+ ...tag.tireGripFactor !== void 0 ? { tireGripFactor: tag.tireGripFactor } : {},
572
+ ...tag.latFrictionEllipseScale !== void 0 ? { latFrictionEllipseScale: tag.latFrictionEllipseScale } : {},
573
+ ...tag.relaxLngRate !== void 0 ? { relaxLngRate: tag.relaxLngRate } : {},
574
+ ...tag.relaxLatRate !== void 0 ? { relaxLatRate: tag.relaxLatRate } : {},
575
+ ...tag.lngSlipRatioCurveData !== void 0 ? { lngSlipRatioCurveData: tag.lngSlipRatioCurveData } : {},
576
+ ...tag.latSlipRatioCurveData !== void 0 ? { latSlipRatioCurveData: tag.latSlipRatioCurveData } : {}
577
+ };
578
+ return /* @__PURE__ */ jsx(ShapeCastWheel, {
579
+ name: tag.nodeName,
580
+ position: mountPos,
581
+ quaternion: tag.quaternion ?? [
582
+ 0,
583
+ 0,
584
+ 0,
585
+ 1
586
+ ],
587
+ enable: wheelEnable,
588
+ ...tagWheelProps,
589
+ ...wheelConfig,
590
+ ...axleCfg,
591
+ children: /* @__PURE__ */ jsx(RotorVisualSlot, {
592
+ object: tag.object,
593
+ center: tag.position,
594
+ quaternion: tag.quaternion,
595
+ scene,
596
+ origin: rotorOrigins.get(tag.object)
597
+ })
598
+ }, `${tag.nodeName}:${wheelEpoch}`);
599
+ }), propellers.map((tag) => /* @__PURE__ */ jsx(ThrustPropeller, {
600
+ name: tag.nodeName,
601
+ position: [
602
+ tag.position[0],
603
+ tag.position[1],
604
+ tag.position[2]
605
+ ],
606
+ quaternion: tag.quaternion ?? [
607
+ 0,
608
+ 0,
609
+ 0,
610
+ 1
611
+ ],
612
+ debug: false,
613
+ enable,
614
+ maxThrust: tag.maxThrust,
615
+ ...tag.torqueRatio !== void 0 ? { torqueRatio: tag.torqueRatio } : {},
616
+ ...tag.invertThrust !== void 0 ? { invertThrust: tag.invertThrust } : {},
617
+ ...tag.invertTorque !== void 0 ? { invertTorque: tag.invertTorque } : {},
618
+ ...propellerConfig,
619
+ children: /* @__PURE__ */ jsx(RotorVisualSlot, {
620
+ object: tag.object,
621
+ center: tag.position,
622
+ quaternion: tag.quaternion,
623
+ scene,
624
+ origin: rotorOrigins.get(tag.object)
625
+ })
626
+ }, tag.nodeName))] });
219
627
  }
220
- var z = new x.Quaternion(), B = new x.Matrix4();
221
- function ue(t, n, r, i = .7, a, o) {
222
- let s = t.length;
223
- if (s === 0) return [];
224
- if (!Number.isFinite(n) || n <= 0) throw new e(`solveWheelLoads: totalMassKg must be positive finite (got ${n})`);
225
- for (let n of t) if (!Number.isFinite(n.sag) || n.sag < 0 || n.springK === void 0 && n.sag <= 0) throw new e(`solveWheelLoads: wheel "${n.nodeName}" requires positive sag (got ${n.sag})`);
226
- let c = n * L;
227
- if (s === 1) {
228
- let e = t[0], r = e.springK ?? c / e.sag;
229
- return [{
230
- tag: e,
231
- cornerMassKg: n,
232
- springK: r,
233
- dampingC: e.dampingC ?? 2 * i * Math.sqrt(r * n),
234
- mountPos: R(e)
235
- }];
628
+ // src/wheelLoads.ts
629
+ var G_SI = 9.81;
630
+ function projectToLowerBoundedSimplex(values, lowerBound, totalSum) {
631
+ const n = values.length;
632
+ const shifted = values.map((v) => v - lowerBound);
633
+ const rem = Math.max(0, totalSum - n * lowerBound);
634
+ const sorted = [...shifted].sort((a, b) => b - a);
635
+ let prefix = 0;
636
+ let k = 0;
637
+ let theta = 0;
638
+ for (let i = 0; i < n; i++) {
639
+ prefix += sorted[i];
640
+ const candidate = (prefix - rem) / (i + 1);
641
+ if (sorted[i] - candidate > 0) {
642
+ k = i + 1;
643
+ theta = candidate;
644
+ }
236
645
  }
237
- let l = 0, u = 0;
238
- for (let e of t) l += e.position[0], u += e.position[2];
239
- l /= s, u /= s;
240
- let d = 0, f = 0, p = 0, m = t.map((e) => {
241
- let t = e.position[0] - l, n = e.position[2] - u;
242
- return d += t * t, f += t * n, p += n * n, [t, n];
243
- }), h = (r[0] - l) * c, g = (r[2] - u) * c, _ = d + p, v = d * p - f * f, y = 0, b = 0;
244
- if (v > 1e-6 * _ * _) y = (p * h - f * g) / v, b = (-f * h + d * g) / v;
245
- else if (_ > 1e-12) {
246
- let e = 1 / (_ * _);
247
- y = (d * h + f * g) * e, b = (f * h + p * g) * e;
646
+ if (k === 0) theta = (prefix - rem) / n;
647
+ return shifted.map((v) => lowerBound + Math.max(v - theta, 0));
648
+ }
649
+ function solveCornerMasses(wheels, totalMassKg, com) {
650
+ const n = wheels.length;
651
+ if (n === 0) return [];
652
+ if (n === 1) return [totalMassKg];
653
+ const mBase = totalMassKg / n;
654
+ const xs = wheels.map((w) => w.position[0] - com[0]);
655
+ const zs = wheels.map((w) => w.position[2] - com[2]);
656
+ const meanX = xs.reduce((s, v) => s + v, 0) / n;
657
+ const meanZ = zs.reduce((s, v) => s + v, 0) / n;
658
+ const cx = xs.map((v) => v - meanX);
659
+ const cz = zs.map((v) => v - meanZ);
660
+ let sxx = 0;
661
+ let szz = 0;
662
+ let sxz = 0;
663
+ for (let i = 0; i < n; i++) {
664
+ sxx += cx[i] * cx[i];
665
+ szz += cz[i] * cz[i];
666
+ sxz += cx[i] * cz[i];
248
667
  }
249
- let x = c / s, S = Math.min(c * .05, x), C = m.map(([e, t]) => x + e * y + t * b);
250
- if (C.some((e) => e < S)) {
251
- let e = new Uint8Array(s);
252
- for (let t = 0; t < s; t++) {
253
- let t = 0, n = 0, r = 0;
254
- for (let i = 0; i < s; i++) e[i] || C[i] <= S ? (e[i] = 1, C[i] = S, t += S) : (n += C[i], r++);
255
- if (r === 0) break;
256
- let i = c - t, a = n > 1e-12 ? i / n : 0, o = !1;
257
- for (let t = 0; t < s; t++) e[t] || (C[t] = n > 1e-12 ? C[t] * a : i / r, C[t] < S - 1e-9 && (o = !0));
258
- if (!o) break;
668
+ const bx = -totalMassKg * meanX;
669
+ const bz = -totalMassKg * meanZ;
670
+ const det = sxx * szz - sxz * sxz;
671
+ const trace = sxx + szz;
672
+ let lx = 0;
673
+ let lz = 0;
674
+ if (det > 1e-10 * trace * trace && det > 1e-12) {
675
+ lx = (szz * bx - sxz * bz) / det;
676
+ lz = (sxx * bz - sxz * bx) / det;
677
+ } else if (trace > 1e-10) {
678
+ const angle = .5 * Math.atan2(2 * sxz, sxx - szz);
679
+ const ux = Math.cos(angle);
680
+ const uz = Math.sin(angle);
681
+ const normSq = ux * ux * sxx + 2 * ux * uz * sxz + uz * uz * szz;
682
+ if (normSq > 1e-10) {
683
+ const proj = (ux * bx + uz * bz) / normSq;
684
+ lx = proj * ux;
685
+ lz = proj * uz;
259
686
  }
260
687
  }
261
- let w = t.map((e, t) => {
262
- let n = C[t], r = n / L, a = e.springK ?? n / e.sag;
688
+ const raw = wheels.map((_, i) => mBase + lx * cx[i] + lz * cz[i]);
689
+ const mMin = Math.min(.05 * totalMassKg, totalMassKg / n);
690
+ if (raw.every((m) => m >= mMin - 1e-9)) return raw;
691
+ return projectToLowerBoundedSimplex(raw, mMin, totalMassKg);
692
+ }
693
+ /**
694
+ * Distributes `totalMassKg` across N >= 1 wheels around `com`, resolves fallback
695
+ * `springK` / `dampingC` when omitted on the `.glb` wheel descriptor, and returns
696
+ * natural scene-space `mountPos` (`tag.position + lift`).
697
+ */
698
+ function solveWheelLoads(wheels, totalMassKg, com, dampingRatio = .7) {
699
+ if (wheels.length === 0) return [];
700
+ const cornerMasses = solveCornerMasses(wheels, totalMassKg, com);
701
+ return wheels.map((tag, i) => {
702
+ const cornerMassKg = cornerMasses[i];
703
+ const springK = tag.springK ?? cornerMassKg * G_SI / Math.max(tag.sag, 1e-4);
704
+ const dampingC = tag.dampingC ?? 2 * dampingRatio * Math.sqrt(springK * cornerMassKg);
705
+ const lift = Math.max(0, tag.travel - tag.sag);
706
+ const mountOffset = new THREE.Vector3(0, lift, 0);
707
+ if (tag.quaternion) mountOffset.applyQuaternion(new THREE.Quaternion(tag.quaternion[0], tag.quaternion[1], tag.quaternion[2], tag.quaternion[3]).normalize());
263
708
  return {
264
- tag: e,
265
- cornerMassKg: r,
266
- springK: a,
267
- dampingC: e.dampingC ?? 2 * i * Math.sqrt(a * r),
268
- mountPos: R(e)
709
+ tag,
710
+ cornerMassKg,
711
+ springK,
712
+ dampingC,
713
+ mountPos: [
714
+ tag.position[0] + mountOffset.x,
715
+ tag.position[1] + mountOffset.y,
716
+ tag.position[2] + mountOffset.z
717
+ ]
269
718
  };
270
719
  });
271
- if (!a || !o) return w;
272
- z.set(o[0], o[1], o[2], o[3]).normalize(), B.makeRotationFromQuaternion(z);
273
- let T = B.elements, ee = T[0] * T[0] * a[0] + T[4] * T[4] * a[1] + T[8] * T[8] * a[2], te = T[2] * T[2] * a[0] + T[6] * T[6] * a[1] + T[10] * T[10] * a[2], E = 0, D = 0, O = 0, k = 0, A = 0, j = 0;
274
- for (let e of w) {
275
- let t = e.mountPos[0] - r[0], n = e.mountPos[2] - r[2];
276
- E += e.dampingC, D += e.dampingC * t * t, O += e.dampingC * n * n, k += e.springK, A += e.springK * t * t, j += e.springK * n * n;
277
- }
278
- let M = (e, t, n) => {
279
- if (!(n > 1e-6) || !(e > 0)) return 1;
280
- let r = t > 0 ? Math.min(1, 2 * i * Math.sqrt(t * n) / e) : 1, a = e * r * .03333333333333333 / n, o = Math.max(.35, 1 - t * .0011111111111111111 / n);
281
- return r * (a > o ? o / a : 1);
282
- }, N = Math.min(M(E, k, n), M(O, j, ee), M(D, A, te));
283
- return N < 1 ? w.map((e) => e.tag.dampingC === void 0 ? {
284
- ...e,
285
- dampingC: e.dampingC * N
286
- } : e) : w;
287
720
  }
288
721
  // src/KhrVehicle.tsx
289
- var de = 220, fe = new x.Quaternion(), V = new x.Vector3();
290
- function pe({ ref: t, bundle: n, position: a = [
291
- 0,
292
- .5,
293
- 0
294
- ], enable: o = !0, carConfig: s, droneConfig: c, wheelConfig: m, frontWheelConfig: v, rearWheelConfig: y, wheelConfigs: x, propellerConfig: E, propellerConfigs: D, vehicleRef: O, children: k, ...A }) {
295
- let { world: j } = b(), ie = f(u), P = f(i), F = w((e) => e.gravityField), I = g(null), [L, R] = _(!1), [z, B] = _(!1), de = g(!1), [pe, H] = _(!1), U = g(!1), me = d((e) => {
296
- I.current = e, O && (O.current = e), typeof t == "function" ? t(e) : t && (t.current = e);
297
- }, [t, O]), { mass: W, com: G, inertia: K, inertiaFrame: q, linearVelocity: he, angularVelocity: ge, gravityFactor: _e } = h(() => ne(n.bodies), [n.bodies]), ve = h(() => se([...n.wheels.map((e) => e.object), ...n.propellers.map((e) => e.object)]), [n]), [ye, be, xe] = M(a), [Se, Ce, we, Te] = N(A.rotation, A.quaternion), J = h(() => (fe.set(Se, Ce, we, Te), V.set(G[0], G[1], G[2]).applyQuaternion(fe), [
298
- ye + V.x,
299
- be + V.y,
300
- xe + V.z
301
- ]), [
302
- ye,
303
- be,
304
- xe,
305
- Se,
306
- Ce,
307
- we,
308
- Te,
309
- G
310
- ]), Ee = h(() => [
311
- -G[0],
312
- -G[1],
313
- -G[2]
314
- ], [G]), De = h(() => re(n.bodies, G), [n.bodies, G]), Oe = h(() => {
315
- let t = {
316
- ...n.tune,
317
- ...s
318
- };
319
- if (n.wheels.some((e) => e.drive) && !(typeof t.engineHorsepower == "number" && t.engineHorsepower > 0)) throw new e("KhrVehicle: drive wheels need carConfig.engineHorsepower (author scene.extras.tune or pass the carConfig prop)");
320
- return t;
321
- }, [
322
- n.tune,
323
- n.wheels,
324
- s
325
- ]), Y = h(() => ue(n.wheels, W, G, .7, K, q).map((e) => ({
326
- sw: e,
327
- localPos: [
328
- e.mountPos[0] - G[0],
329
- e.mountPos[1] - G[1],
330
- e.mountPos[2] - G[2]
331
- ]
332
- })), [
333
- n.wheels,
334
- W,
335
- G,
336
- K,
337
- q
338
- ]), X = h(() => n.propellers.map((e) => ({
339
- p: e,
340
- localPos: [
341
- e.position[0] - G[0],
342
- e.position[1] - G[1],
343
- e.position[2] - G[2]
344
- ]
345
- })), [n.propellers, G]), ke = h(() => n.droneTune || c ? {
346
- ...n.droneTune,
347
- ...c
348
- } : void 0, [n.droneTune, c]);
349
- p(() => {
350
- let e = I.current?.body;
351
- e && (e.setAdditionalMassProperties(W, {
352
- x: 0,
353
- y: 0,
354
- z: 0
355
- }, {
356
- x: K[0],
357
- y: K[1],
358
- z: K[2]
359
- }, {
360
- x: q[0],
361
- y: q[1],
362
- z: q[2],
363
- w: q[3]
364
- }, !0), e.recomputeMassPropertiesFromColliders(), X.length > 0 && R(!0));
365
- }, [
366
- W,
367
- K,
368
- q,
369
- X.length
722
+ var patchedHandles = /* @__PURE__ */ new WeakSet();
723
+ function hasActiveMovement(m) {
724
+ 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));
725
+ }
726
+ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
727
+ assertVehicleProps(scale, colliders);
728
+ bundle.scene.updateMatrixWorld(true);
729
+ assertSceneIdentityWorldScale(bundle.scene);
730
+ const { ref, vehicleRef, jointsRef, position, rotation, quaternion, enable = true, enableCustomGravity = false, carConfig, droneConfig, wheelConfig, frontWheelConfig, rearWheelConfig, propellerConfig, linearVelocity, angularVelocity, gravityScale, children, ...ecctrlRest } = rest;
731
+ const { world } = useRapier();
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
+ });
738
+ const [wheelEpoch, setWheelEpoch] = useState(0);
739
+ const zeroGRef = useRef(isZeroG);
740
+ const poisonedRef = useRef(false);
741
+ useLayoutEffect(() => {
742
+ setRotorsMounted(true);
743
+ }, []);
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);
751
+ }
752
+ setIsZeroG(nextZeroG);
753
+ }, []);
754
+ const chassis = useMemo(() => computeChassisMassProps(bundle.bodies), [bundle]);
755
+ const collidersList = useMemo(() => buildChassisColliders(bundle.bodies, chassis), [bundle.bodies, chassis]);
756
+ const solvedWheels = useMemo(() => solveWheelLoads(bundle.wheels, bundle.totalDynamicMass, bundle.centerOfMass), [
757
+ bundle.wheels,
758
+ bundle.totalDynamicMass,
759
+ bundle.centerOfMass
370
760
  ]);
371
- let Ae = !!A.enableCustomGravity, Z;
372
- if (Ae) I.current?.body ? V.copy(I.current.body.translation()) : V.set(J[0], J[1], J[2]), Z = F(V).lengthSq() > 1e-12;
373
- else {
374
- let [e, t, n] = ie ?? [
375
- j.gravity.x,
376
- j.gravity.y,
377
- j.gravity.z
378
- ];
379
- Z = e * e + t * t + n * n > 1e-12;
380
- }
381
- let Q = o && P, je = Q && Z && !pe && z;
382
- p(() => {
383
- Z && U.current && (U.current = !1, H(!1));
384
- }, [Z]);
385
- let $ = h(() => Y.map((e, t) => ae(n.wheels, t, m, v, y, x)), [
386
- Y,
387
- n.wheels,
388
- m,
389
- v,
390
- y,
391
- x
392
- ]), Me = h(() => {
393
- let e = /* @__PURE__ */ new Set();
394
- if (!je) return e;
395
- for (let t = 0; t < Y.length; t++) ($[t]?.enable ?? o) && e.add(Y[t].sw.tag.nodeName);
396
- return e;
397
- }, [
398
- Y,
399
- $,
400
- je,
401
- o
761
+ const rotorOrigins = useMemo(() => captureRotorOrigins([...bundle.wheels.map((w) => w.object), ...bundle.propellers.map((p) => p.object)]), [bundle.wheels, bundle.propellers]);
762
+ const [px, py, pz] = readPosTuple(position);
763
+ const [qx, qy, qz, qw] = readSpawnQuat(rotation, quaternion);
764
+ const bodyPos = useMemo(() => [
765
+ px,
766
+ py,
767
+ pz
768
+ ], [
769
+ px,
770
+ py,
771
+ pz
772
+ ]);
773
+ const bodyQuat = useMemo(() => [
774
+ qx,
775
+ qy,
776
+ qz,
777
+ qw
778
+ ], [
779
+ qx,
780
+ qy,
781
+ qz,
782
+ qw
402
783
  ]);
403
- return /* @__PURE__ */ C(T, {
404
- ref: me,
405
- position: J,
406
- enable: Q,
407
- carConfig: Oe,
408
- droneConfig: ke,
409
- ...he ? { linearVelocity: he } : {},
410
- ...ge ? { angularVelocity: ge } : {},
411
- ..._e === void 0 ? {} : { gravityScale: _e },
412
- ...A,
784
+ const innerRef = useRef(null);
785
+ const assignRef = useCallback((handle) => {
786
+ if (handle && !patchedHandles.has(handle)) {
787
+ patchedHandles.add(handle);
788
+ const origSetMovement = handle.setMovement;
789
+ handle.setMovement = (state) => {
790
+ origSetMovement(state);
791
+ if (hasActiveMovement(state) && handle.body?.isSleeping()) handle.body.wakeUp();
792
+ };
793
+ }
794
+ innerRef.current = handle;
795
+ if (vehicleRef) vehicleRef.current = handle;
796
+ if (typeof ref === "function") ref(handle);
797
+ else if (ref && typeof ref === "object") ref.current = handle;
798
+ }, [ref, vehicleRef]);
799
+ const omiSteerAngle = useMemo(() => bundle.wheels.find((w) => w.steer && w.maxSteeringAngle !== void 0 && w.maxSteeringAngle > 0)?.maxSteeringAngle, [bundle.wheels]);
800
+ const mergedCarConfig = useMemo(() => bundle.tune || carConfig || omiSteerAngle !== void 0 ? {
801
+ ...omiSteerAngle !== void 0 ? { maxSteerAngle: omiSteerAngle } : {},
802
+ ...bundle.tune,
803
+ ...carConfig
804
+ } : void 0, [
805
+ omiSteerAngle,
806
+ bundle.tune,
807
+ carConfig
808
+ ]);
809
+ const mergedDroneConfig = useMemo(() => bundle.droneTune || droneConfig ? {
810
+ ...bundle.droneTune,
811
+ ...droneConfig
812
+ } : void 0, [bundle.droneTune, droneConfig]);
813
+ const effLinVel = linearVelocity ?? chassis.linearVelocity;
814
+ const effAngVel = angularVelocity ?? chassis.angularVelocity;
815
+ const effGravScale = gravityScale ?? chassis.gravityFactor;
816
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs(EcctrlVehicle, {
817
+ ref: assignRef,
818
+ enable,
819
+ enableCustomGravity,
820
+ position: bodyPos,
821
+ quaternion: bodyQuat,
822
+ ...effLinVel !== void 0 ? { linearVelocity: effLinVel } : {},
823
+ ...effAngVel !== void 0 ? { angularVelocity: effAngVel } : {},
824
+ ...effGravScale !== void 0 ? { gravityScale: effGravScale } : {},
825
+ carConfig: mergedCarConfig,
826
+ droneConfig: mergedDroneConfig,
827
+ ...ecctrlRest,
413
828
  children: [
414
- /* @__PURE__ */ C("group", {
415
- position: Ee,
416
- children: [/* @__PURE__ */ S(l, {
417
- bundle: n,
418
- owner: "KhrVehicle"
419
- }), k]
420
- }),
421
- De.map(({ key: e, spec: t }) => /* @__PURE__ */ S(r, { c: t }, e)),
422
- /* @__PURE__ */ S(le, {
423
- vehicleRef: I,
424
- active: Q,
425
- hasRenderGravity: Z,
426
- enableCustomGravity: Ae,
427
- activeWheelNames: Me,
428
- gravityPrimedRef: de,
429
- setGravityPrimed: B,
430
- spatialZeroGRef: U,
431
- setSpatialZeroG: H
829
+ /* @__PURE__ */ jsx(BundleSceneHost, {
830
+ bundle,
831
+ owner: "KhrVehicle"
432
832
  }),
433
- Y.map(({ sw: e, localPos: t }, r) => {
434
- let i = e.tag.nodeName;
435
- return /* @__PURE__ */ S(ee, {
436
- quaternion: e.tag.quaternion,
437
- wheelModelDensity: e.tag.wheelDensity ?? 220,
438
- wheelModelRadius: e.tag.radius,
439
- rayShapeR: e.tag.radius,
440
- rayShapeH: e.tag.width * .5,
441
- rayLength: e.tag.travel,
442
- springK: e.tag.springK ?? e.springK,
443
- dampingC: e.tag.dampingC ?? e.dampingC,
444
- steerWheel: e.tag.steer,
445
- driveWheel: e.tag.drive,
446
- brakeWheel: e.tag.brake,
447
- steerInvert: e.tag.steerInvert,
448
- driveInvert: e.tag.driveInvert,
449
- driveTorqueWeight: e.tag.driveTorqueWeight,
450
- tireGripFactor: e.tag.tireGripFactor,
451
- lngFrictionEllipseScale: e.tag.lngFrictionEllipseScale,
452
- latFrictionEllipseScale: e.tag.latFrictionEllipseScale,
453
- relaxLngRate: e.tag.relaxLngRate,
454
- relaxLatRate: e.tag.relaxLatRate,
455
- minLngRelaxCoeff: e.tag.minLngRelaxCoeff,
456
- minLatRelaxCoeff: e.tag.minLatRelaxCoeff,
457
- rollingResistanceCoef: e.tag.rollingResistanceCoef,
458
- lngSlipRatioCurveData: e.tag.lngSlipRatioCurveData,
459
- latSlipRatioCurveData: e.tag.latSlipRatioCurveData,
460
- maxBrakeTorque: e.tag.maxBrakeTorque ?? e.cornerMassKg * 9.80665 * e.tag.radius,
461
- groundDetection: e.tag.groundDetection ?? "shapeCast",
462
- ...$[r],
463
- name: i,
464
- position: t,
465
- enable: Me.has(i),
466
- children: /* @__PURE__ */ S(ce, {
467
- object: e.tag.object,
468
- center: e.tag.position,
469
- quaternion: e.tag.quaternion,
470
- scene: n.scene,
471
- origin: ve.get(e.tag.object)
472
- })
473
- }, i);
474
- }),
475
- X.map(({ p: e, localPos: t }, r) => {
476
- let i = oe(e, r, E, D), a = !!((i?.enable ?? o) && Q), s = /* @__PURE__ */ S(ce, {
477
- object: e.object,
478
- center: e.position,
479
- quaternion: e.quaternion,
480
- scene: n.scene,
481
- origin: ve.get(e.object)
482
- });
483
- return a ? /* @__PURE__ */ S(te, {
484
- debug: !1,
485
- maxThrust: e.maxThrust,
486
- torqueRatio: e.torqueRatio,
487
- invertThrust: e.invertThrust,
488
- invertTorque: e.invertTorque,
489
- ...i,
490
- name: e.nodeName,
491
- position: t,
492
- quaternion: e.quaternion,
493
- enable: L,
494
- children: s
495
- }, e.nodeName) : /* @__PURE__ */ S("group", {
496
- position: t,
497
- quaternion: e.quaternion,
498
- children: s
499
- }, `${e.nodeName}-idle`);
500
- })
833
+ children,
834
+ collidersList.map(({ key, spec, massProperties }) => /* @__PURE__ */ jsx(KhrCollider, {
835
+ c: spec,
836
+ massProperties
837
+ }, key)),
838
+ rotorsMounted && /* @__PURE__ */ jsxs(Fragment, { children: [
839
+ /* @__PURE__ */ jsx(ZeroGWheelGate, {
840
+ vehicleRef: innerRef,
841
+ enable,
842
+ enableCustomGravity,
843
+ spawnPos: bodyPos,
844
+ zeroGRef,
845
+ onZeroGChange: handleZeroGChange
846
+ }),
847
+ /* @__PURE__ */ jsx(KhrVehicleRotors, {
848
+ solvedWheels,
849
+ propellers: bundle.propellers,
850
+ scene: bundle.scene,
851
+ comZ: chassis.com[2],
852
+ rotorOrigins,
853
+ enable,
854
+ wheelEnable: enable && !isZeroG,
855
+ wheelEpoch,
856
+ wheelConfig,
857
+ frontWheelConfig,
858
+ rearWheelConfig,
859
+ propellerConfig
860
+ }),
861
+ /* @__PURE__ */ jsx(ZeroGWheelPostClear, {
862
+ vehicleRef: innerRef,
863
+ zeroGRef
864
+ }, `post:${wheelEpoch}`)
865
+ ] })
501
866
  ]
502
- });
503
- }
504
- function H({ scale: e, colliders: t, bundle: n, ...r }) {
505
- return j(e, t), n.scene.updateMatrixWorld(!0), a(n.scene), /* @__PURE__ */ S(pe, {
506
- bundle: n,
507
- ...r
508
- }, n.scene.uuid);
867
+ }), rotorsMounted && /* @__PURE__ */ jsx(KhrVehicleJoints, {
868
+ bodies: bundle.bodies,
869
+ vehicleRef: innerRef,
870
+ spawnPos: bodyPos,
871
+ spawnQuat: bodyQuat,
872
+ jointsRef
873
+ })] });
509
874
  }
510
- export { L as BENCH_GRAVITY, H as KhrVehicle, de as WHEEL_ASSEMBLY_DENSITY_KG_M3, ue as solveWheelLoads };
875
+ export { KhrVehicle, solveWheelLoads };
876
+
877
+ //# sourceMappingURL=vehicle.js.map