@khr3/core 0.1.4 → 0.2.0

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 (42) hide show
  1. package/README.md +3 -114
  2. package/dist/BundleSceneHost-DUqqPtJF.js +1036 -0
  3. package/dist/BundleSceneHost-DUqqPtJF.js.map +1 -0
  4. package/dist/KhrCollider.d.ts +1 -1
  5. package/dist/KhrVehicle.d.ts +6 -6
  6. package/dist/PhysicsWorld.d.ts +2 -2
  7. package/dist/assemblyPlan.d.ts +2 -0
  8. package/dist/curves.js +130 -102
  9. package/dist/curves.js.map +1 -0
  10. package/dist/index.d.ts +2 -1
  11. package/dist/index.js +1639 -1230
  12. package/dist/index.js.map +1 -0
  13. package/dist/jointDynamics.d.ts +1 -1
  14. package/dist/khrBundleFinalize.d.ts +14 -0
  15. package/dist/khrConfigTypes.d.ts +62 -0
  16. package/dist/khrExportEncoders.d.ts +8 -0
  17. package/dist/khrExporter.d.ts +2 -1
  18. package/dist/khrExtras.d.ts +3 -3
  19. package/dist/khrGlb.d.ts +23 -0
  20. package/dist/khrJointParser.d.ts +3 -0
  21. package/dist/khrLoader.d.ts +2 -1
  22. package/dist/khrParsers.d.ts +5 -9
  23. package/dist/khrPlugin.d.ts +2 -3
  24. package/dist/khrPluginHelpers.d.ts +4 -0
  25. package/dist/khrRotorDecoders.d.ts +4 -0
  26. package/dist/khrShapeParser.d.ts +8 -0
  27. package/dist/khrTypes.d.ts +11 -99
  28. package/dist/khrVehicleChassis.d.ts +7 -8
  29. package/dist/khrVehicleJointHelpers.d.ts +24 -0
  30. package/dist/khrVehicleJoints.d.ts +18 -0
  31. package/dist/khrVehicleRotors.d.ts +22 -0
  32. package/dist/khrVehicleSlots.d.ts +19 -15
  33. package/dist/khrVehicleTypes.d.ts +52 -0
  34. package/dist/physicsEcs.d.ts +2 -7
  35. package/dist/useKhrGlb.d.ts +2 -2
  36. package/dist/vehicle.d.ts +2 -2
  37. package/dist/vehicle.js +760 -423
  38. package/dist/vehicle.js.map +1 -0
  39. package/dist/wheelLoads.d.ts +4 -7
  40. package/docs/api-reference.md +209 -0
  41. package/package.json +8 -7
  42. 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 { 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";
6
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
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,443 +36,781 @@ 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);
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
- }))));
168
+ }
169
+ if (out.length === 0) throw new KhrValidationError("KhrVehicle: chassis has no colliders");
170
+ return out;
111
171
  }
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);
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;
117
180
  }
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);
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);
119
183
  }
120
- // src/khrVehicleSlots.tsx
121
- var P = new x.Vector3();
122
- function F(e) {
123
- e.rayHit !== null && (e.rayHit = null, e.floatImp.set(0, 0, 0), e.lngFricImp.set(0, 0, 0), e.latFricImp.set(0, 0, 0));
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;
124
188
  }
125
- var ae = c;
126
- function oe({ object: e, center: t, quaternion: n, scene: r, origin: i }) {
127
- let a = g(null);
128
- return m(() => {
129
- let o = a.current?.parent;
130
- if (!o) return;
131
- let l = i ?? c([e]).get(e), u = ie(e, r, t, n);
132
- return l.origParent && l.origParent.remove(e), u.decompose(e.position, e.quaternion, e.scale), o.add(e), () => {
133
- e.parent === o && o.remove(e), s(e, l);
189
+ function planVehicleJointParts(bodies) {
190
+ const dyn = bodies.filter((b) => !b.isKinematic);
191
+ const byName = new Map(dyn.map((b) => [b.nodeName, b]));
192
+ const jointed = dyn.filter((b) => b.joint !== null);
193
+ if (jointed.length === 0) return [];
194
+ const depthOf = (b, seen = /* @__PURE__ */ new Set()) => {
195
+ if (!b.joint) return 0;
196
+ if (seen.has(b.nodeName)) throw new KhrValidationError(`Joint cycle through "${b.nodeName}"`);
197
+ seen.add(b.nodeName);
198
+ const parent = byName.get(b.joint.connectedNodeName);
199
+ if (!parent) throw new KhrValidationError(`Vehicle joint on "${b.nodeName}" targets "${b.joint.connectedNodeName}", which is not a dynamic KHR body`);
200
+ return 1 + depthOf(parent, seen);
201
+ };
202
+ jointed.sort((a, b) => depthOf(a) - depthOf(b));
203
+ const one = new THREE.Vector3(1, 1, 1);
204
+ const pos = new THREE.Vector3();
205
+ const quat = new THREE.Quaternion();
206
+ const scl = new THREE.Vector3();
207
+ const partByName = /* @__PURE__ */ new Map();
208
+ return jointed.map((b) => {
209
+ const joint = b.joint;
210
+ const parent = partByName.get(joint.connectedNodeName) ?? null;
211
+ 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) => {
215
+ const colQuat = new THREE.Quaternion().fromArray(spec.localQuaternion);
216
+ 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
+ spec,
221
+ local,
222
+ position: [
223
+ pos.x,
224
+ pos.y,
225
+ pos.z
226
+ ],
227
+ quaternion: [
228
+ quat.x,
229
+ quat.y,
230
+ quat.z,
231
+ quat.w
232
+ ]
233
+ };
234
+ });
235
+ const plan = {
236
+ spec: b,
237
+ joint,
238
+ parent,
239
+ restRelParent,
240
+ inertia: effectiveJointInertia(b, joint, descendants),
241
+ colliders
242
+ };
243
+ partByName.set(b.nodeName, plan);
244
+ return plan;
245
+ });
246
+ }
247
+ function openTargetForLimits(limits) {
248
+ return Math.abs(limits[0]) > Math.abs(limits[1]) ? limits[0] : limits[1];
249
+ }
250
+ function isVehicleJointOpen(rt) {
251
+ if (!rt.limits) return false;
252
+ 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
+ };
284
+ }
285
+ // src/khrVehicleJoints.tsx
286
+ var nextVehicleJointAssemblyId = 1e5;
287
+ function KhrVehicleJoints({ bodies, vehicleRef, jointsRef }) {
288
+ 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);
304
+ }
305
+ runtimeMapRef.current = map;
306
+ byObjectRef.current = byObj;
307
+ 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
+ }
134
315
  };
135
316
  }, [
136
- e,
137
- t,
138
- n,
139
- r,
140
- i
141
- ]), /* @__PURE__ */ S("group", { ref: a });
317
+ parts,
318
+ colliderRefs,
319
+ assemblyId,
320
+ registry
321
+ ]);
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
+ }
351
+ }
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
+ }
361
+ };
362
+ }, [parts, vehicleRef]);
363
+ 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}`))) });
142
370
  }
143
- function se(e, t) {
144
- let n = 0;
145
- for (let r of e.wheelsInfo.values()) {
146
- let i = r.current;
147
- if (!t.has(i.name ?? "") || !i.rayHit) continue;
148
- let a = Math.min(1, Math.max(-1, i.rayHitNormal.dot(e.upAxis))), o = Math.sqrt(Math.max(0, 1 - a * a));
149
- o > n && (n = o);
371
+ // src/khrVehicleSlots.tsx
372
+ var captureRotorOrigins = captureSubtreeOrigins;
373
+ var _samplePos = new THREE.Vector3();
374
+ function isZeroGravityVec(x, y, z) {
375
+ return x * x + y * y + z * z <= 1e-12;
376
+ }
377
+ function resetAllWheelHits(handle) {
378
+ if (!handle) return;
379
+ for (const wheelRef of handle.wheelsInfo.values()) {
380
+ const w = wheelRef.current;
381
+ if (!w) continue;
382
+ w.rayHit = null;
383
+ w.rayHitBody = null;
384
+ w.floatImp.set(0, 0, 0);
385
+ w.lngFricImp.set(0, 0, 0);
386
+ w.latFricImp.set(0, 0, 0);
387
+ w.lngSlipRatio = 0;
388
+ w.latSlipRatio = 0;
389
+ w.slipStrength = 0;
390
+ w.isOnPlatform = false;
391
+ w.effInertia = 0;
150
392
  }
151
- return n;
152
393
  }
153
- function ce({ vehicleRef: e, active: n, hasRenderGravity: r, enableCustomGravity: i, activeWheelNames: a, gravityPrimedRef: o, setGravityPrimed: s, spatialZeroGRef: c, setSpatialZeroG: l }) {
154
- let u = f(t), d = g(0);
155
- return y(() => {
156
- let t = e.current, n = t?.body;
157
- if (!t || !n) return;
158
- let r = !1;
159
- if (i) {
160
- let e = n.translation();
161
- 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);
162
- r !== c.current && (c.current = r, l(r));
394
+ function ZeroGWheelPreGuard({ vehicleRef, enable, enableCustomGravity, spawnPos, wheelActiveRef, zeroGRef, customPrimedRef, needsEpochBumpRef, onZeroGChange, onCustomPrimed, onBumpWheelEpoch }) {
395
+ const { world } = useRapier();
396
+ useFrame(() => {
397
+ if (!enable) return;
398
+ const handle = vehicleRef.current;
399
+ let isZeroG;
400
+ if (enableCustomGravity) {
401
+ if (handle?.body && !handle.body.isSleeping()) isZeroG = handle.gravityMag <= 1e-6;
402
+ 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();
414
+ }
415
+ } else {
416
+ const g = world.gravity;
417
+ isZeroG = isZeroGravityVec(g.x, g.y, g.z);
163
418
  }
164
- let a = !r && t.gravityMag > 1e-6;
165
- a !== o.current && (o.current = a, s(a));
166
- }), v(() => {
167
- let t = e.current, i = t?.body;
168
- if (!t || !i) return;
169
- for (let e of t.wheelsInfo.values()) {
170
- let t = e.current;
171
- a.has(t.name ?? "") || F(t);
419
+ if (isZeroG !== zeroGRef.current) {
420
+ const wasActive = wheelActiveRef.current;
421
+ zeroGRef.current = isZeroG;
422
+ if (isZeroG && wasActive) needsEpochBumpRef.current = true;
423
+ else if (!isZeroG && needsEpochBumpRef.current) {
424
+ needsEpochBumpRef.current = false;
425
+ onBumpWheelEpoch();
426
+ }
427
+ onZeroGChange(isZeroG);
172
428
  }
173
- if (!n || u !== null && !(u.current > 0)) return;
174
- (r && !c.current && !o.current || (!r || c.current) && t.gravityMag > 1e-6) && i.isSleeping() && i.wakeUp();
175
- 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;
176
- d.current = v, i.isSleeping() ? (v & 11 & ~(y & 11) || y & 4 && !g) && i.wakeUp() : (!g && h || g && se(t, a) >= .025) && i.wakeUp();
177
- }), null;
429
+ if (isZeroG) resetAllWheelHits(handle);
430
+ });
431
+ return null;
178
432
  }
179
- // src/wheelLoads.ts
180
- var I = 9.80665;
181
- function L(e) {
182
- let t = e.travel - e.sag, n = e.quaternion;
183
- if (!n) return [
184
- e.position[0],
185
- e.position[1] + t,
186
- e.position[2]
187
- ];
188
- 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);
189
- return [
190
- e.position[0] + s * t,
191
- e.position[1] + c * t,
192
- e.position[2] + l * t
193
- ];
433
+ function ZeroGWheelPostGuard({ vehicleRef, zeroGRef }) {
434
+ useFrame(() => {
435
+ if (zeroGRef.current) resetAllWheelHits(vehicleRef.current);
436
+ });
437
+ return null;
194
438
  }
195
- var R = new x.Quaternion(), z = new x.Matrix4();
196
- function le(t, n, r, i = .7, a, o) {
197
- let s = t.length;
198
- if (s === 0) return [];
199
- if (!Number.isFinite(n) || n <= 0) throw new e(`solveWheelLoads: totalMassKg must be positive finite (got ${n})`);
200
- 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})`);
201
- let c = n * I;
202
- if (s === 1) {
203
- let e = t[0], r = e.springK ?? c / e.sag;
204
- return [{
205
- tag: e,
206
- cornerMassKg: n,
207
- springK: r,
208
- dampingC: e.dampingC ?? 2 * i * Math.sqrt(r * n),
209
- mountPos: L(e)
210
- }];
439
+ function RotorVisualSlot({ object, center, quaternion, scene, origin }) {
440
+ const slotRef = useRef(null);
441
+ useLayoutEffect(() => {
442
+ const slot = slotRef.current;
443
+ const parent = slot?.parent ?? null;
444
+ if (!slot || !parent) return;
445
+ const snap = origin ?? captureSubtreeOrigins([object]).get(object);
446
+ scene.updateMatrixWorld(true);
447
+ const localMat = computeRotorLocalMatrix(object, scene, center, quaternion);
448
+ if (snap.origParent) snap.origParent.remove(object);
449
+ const pos = new THREE.Vector3();
450
+ const quat = new THREE.Quaternion();
451
+ const scl = new THREE.Vector3();
452
+ localMat.decompose(pos, quat, scl);
453
+ object.position.copy(pos);
454
+ object.quaternion.copy(quat.normalize());
455
+ object.scale.copy(scl);
456
+ slot.add(object);
457
+ return () => {
458
+ if (object.parent === slot) slot.remove(object);
459
+ restoreSubtreeOrigin(object, snap);
460
+ };
461
+ }, [
462
+ object,
463
+ center,
464
+ quaternion,
465
+ scene,
466
+ origin
467
+ ]);
468
+ return /* @__PURE__ */ jsx("group", { ref: slotRef });
469
+ }
470
+ // src/khrVehicleRotors.tsx
471
+ var G_SI$1 = 9.81;
472
+ var UNSPRUNG_CORNER_RATIO = .035;
473
+ function KhrVehicleRotors({ solvedWheels, propellers, scene, comZ, rotorOrigins, enable, wheelEnable, wheelEpoch = 0, wheelConfig, frontWheelConfig, rearWheelConfig, propellerConfig }) {
474
+ return /* @__PURE__ */ jsxs(Fragment, { children: [solvedWheels.map(({ tag, cornerMassKg, springK, dampingC, mountPos }) => {
475
+ const axleCfg = mountPos[2] >= comZ ? frontWheelConfig : rearWheelConfig;
476
+ const wheelVol = Math.max(Math.PI * tag.radius * tag.radius * tag.width, 1e-6);
477
+ const wheelModelDensity = tag.wheelDensity ?? UNSPRUNG_CORNER_RATIO * cornerMassKg / wheelVol;
478
+ const tagWheelProps = {
479
+ rayLength: tag.travel,
480
+ rayShapeR: tag.radius,
481
+ rayShapeH: tag.width * .5,
482
+ wheelModelRadius: tag.radius,
483
+ wheelModelDensity,
484
+ springK,
485
+ dampingC,
486
+ steerWheel: tag.steer,
487
+ driveWheel: tag.drive,
488
+ brakeWheel: tag.brake,
489
+ maxBrakeTorque: tag.maxBrakeTorque ?? cornerMassKg * G_SI$1 * tag.radius,
490
+ ...tag.steerInvert !== void 0 ? { steerInvert: tag.steerInvert } : {},
491
+ ...tag.driveInvert !== void 0 ? { driveInvert: tag.driveInvert } : {},
492
+ ...tag.driveTorqueWeight !== void 0 ? { driveTorqueWeight: tag.driveTorqueWeight } : {},
493
+ ...tag.rollingResistanceCoef !== void 0 ? { rollingResistanceCoef: tag.rollingResistanceCoef } : {},
494
+ ...tag.tireGripFactor !== void 0 ? { tireGripFactor: tag.tireGripFactor } : {},
495
+ ...tag.latFrictionEllipseScale !== void 0 ? { latFrictionEllipseScale: tag.latFrictionEllipseScale } : {},
496
+ ...tag.relaxLngRate !== void 0 ? { relaxLngRate: tag.relaxLngRate } : {},
497
+ ...tag.relaxLatRate !== void 0 ? { relaxLatRate: tag.relaxLatRate } : {},
498
+ ...tag.lngSlipRatioCurveData !== void 0 ? { lngSlipRatioCurveData: tag.lngSlipRatioCurveData } : {},
499
+ ...tag.latSlipRatioCurveData !== void 0 ? { latSlipRatioCurveData: tag.latSlipRatioCurveData } : {}
500
+ };
501
+ return /* @__PURE__ */ jsx(ShapeCastWheel, {
502
+ name: tag.nodeName,
503
+ position: mountPos,
504
+ quaternion: tag.quaternion ?? [
505
+ 0,
506
+ 0,
507
+ 0,
508
+ 1
509
+ ],
510
+ enable: wheelEnable,
511
+ ...tagWheelProps,
512
+ ...wheelConfig,
513
+ ...axleCfg,
514
+ children: /* @__PURE__ */ jsx(RotorVisualSlot, {
515
+ object: tag.object,
516
+ center: tag.position,
517
+ quaternion: tag.quaternion,
518
+ scene,
519
+ origin: rotorOrigins.get(tag.object)
520
+ })
521
+ }, `${tag.nodeName}:${wheelEpoch}`);
522
+ }), propellers.map((tag) => /* @__PURE__ */ jsx(ThrustPropeller, {
523
+ name: tag.nodeName,
524
+ position: [
525
+ tag.position[0],
526
+ tag.position[1],
527
+ tag.position[2]
528
+ ],
529
+ quaternion: tag.quaternion ?? [
530
+ 0,
531
+ 0,
532
+ 0,
533
+ 1
534
+ ],
535
+ debug: false,
536
+ enable,
537
+ maxThrust: tag.maxThrust,
538
+ ...tag.torqueRatio !== void 0 ? { torqueRatio: tag.torqueRatio } : {},
539
+ ...tag.invertThrust !== void 0 ? { invertThrust: tag.invertThrust } : {},
540
+ ...tag.invertTorque !== void 0 ? { invertTorque: tag.invertTorque } : {},
541
+ ...propellerConfig,
542
+ children: /* @__PURE__ */ jsx(RotorVisualSlot, {
543
+ object: tag.object,
544
+ center: tag.position,
545
+ quaternion: tag.quaternion,
546
+ scene,
547
+ origin: rotorOrigins.get(tag.object)
548
+ })
549
+ }, tag.nodeName))] });
550
+ }
551
+ // src/wheelLoads.ts
552
+ var G_SI = 9.81;
553
+ function projectToLowerBoundedSimplex(values, lowerBound, totalSum) {
554
+ const n = values.length;
555
+ const shifted = values.map((v) => v - lowerBound);
556
+ const rem = Math.max(0, totalSum - n * lowerBound);
557
+ const sorted = [...shifted].sort((a, b) => b - a);
558
+ let prefix = 0;
559
+ let k = 0;
560
+ let theta = 0;
561
+ for (let i = 0; i < n; i++) {
562
+ prefix += sorted[i];
563
+ const candidate = (prefix - rem) / (i + 1);
564
+ if (sorted[i] - candidate > 0) {
565
+ k = i + 1;
566
+ theta = candidate;
567
+ }
211
568
  }
212
- let l = 0, u = 0;
213
- for (let e of t) l += e.position[0], u += e.position[2];
214
- l /= s, u /= s;
215
- let d = 0, f = 0, p = 0, m = t.map((e) => {
216
- let t = e.position[0] - l, n = e.position[2] - u;
217
- return d += t * t, f += t * n, p += n * n, [t, n];
218
- }), h = (r[0] - l) * c, g = (r[2] - u) * c, _ = d + p, v = d * p - f * f, y = 0, b = 0;
219
- if (v > 1e-6 * _ * _) y = (p * h - f * g) / v, b = (-f * h + d * g) / v;
220
- else if (_ > 1e-12) {
221
- let e = 1 / (_ * _);
222
- y = (d * h + f * g) * e, b = (f * h + p * g) * e;
569
+ if (k === 0) theta = (prefix - rem) / n;
570
+ return shifted.map((v) => lowerBound + Math.max(v - theta, 0));
571
+ }
572
+ function solveCornerMasses(wheels, totalMassKg, com) {
573
+ const n = wheels.length;
574
+ if (n === 0) return [];
575
+ if (n === 1) return [totalMassKg];
576
+ const mBase = totalMassKg / n;
577
+ const xs = wheels.map((w) => w.position[0] - com[0]);
578
+ const zs = wheels.map((w) => w.position[2] - com[2]);
579
+ const meanX = xs.reduce((s, v) => s + v, 0) / n;
580
+ const meanZ = zs.reduce((s, v) => s + v, 0) / n;
581
+ const cx = xs.map((v) => v - meanX);
582
+ const cz = zs.map((v) => v - meanZ);
583
+ let sxx = 0;
584
+ let szz = 0;
585
+ let sxz = 0;
586
+ for (let i = 0; i < n; i++) {
587
+ sxx += cx[i] * cx[i];
588
+ szz += cz[i] * cz[i];
589
+ sxz += cx[i] * cz[i];
223
590
  }
224
- let x = c / s, S = Math.min(c * .05, x), C = m.map(([e, t]) => x + e * y + t * b);
225
- if (C.some((e) => e < S)) {
226
- let e = new Uint8Array(s);
227
- for (let t = 0; t < s; t++) {
228
- let t = 0, n = 0, r = 0;
229
- for (let i = 0; i < s; i++) e[i] || C[i] <= S ? (e[i] = 1, C[i] = S, t += S) : (n += C[i], r++);
230
- if (r === 0) break;
231
- let i = c - t, a = n > 1e-12 ? i / n : 0, o = !1;
232
- 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));
233
- if (!o) break;
591
+ const bx = -totalMassKg * meanX;
592
+ const bz = -totalMassKg * meanZ;
593
+ const det = sxx * szz - sxz * sxz;
594
+ const trace = sxx + szz;
595
+ let lx = 0;
596
+ let lz = 0;
597
+ if (det > 1e-10 * trace * trace && det > 1e-12) {
598
+ lx = (szz * bx - sxz * bz) / det;
599
+ lz = (sxx * bz - sxz * bx) / det;
600
+ } else if (trace > 1e-10) {
601
+ const angle = .5 * Math.atan2(2 * sxz, sxx - szz);
602
+ const ux = Math.cos(angle);
603
+ const uz = Math.sin(angle);
604
+ const normSq = ux * ux * sxx + 2 * ux * uz * sxz + uz * uz * szz;
605
+ if (normSq > 1e-10) {
606
+ const proj = (ux * bx + uz * bz) / normSq;
607
+ lx = proj * ux;
608
+ lz = proj * uz;
234
609
  }
235
610
  }
236
- let w = t.map((e, t) => {
237
- let n = C[t], r = n / I, a = e.springK ?? n / e.sag;
611
+ const raw = wheels.map((_, i) => mBase + lx * cx[i] + lz * cz[i]);
612
+ const mMin = Math.min(.05 * totalMassKg, totalMassKg / n);
613
+ if (raw.every((m) => m >= mMin - 1e-9)) return raw;
614
+ return projectToLowerBoundedSimplex(raw, mMin, totalMassKg);
615
+ }
616
+ /**
617
+ * Distributes `totalMassKg` across N >= 1 wheels around `com`, resolves fallback
618
+ * `springK` / `dampingC` when omitted on the `.glb` wheel descriptor, and returns
619
+ * natural scene-space `mountPos` (`tag.position + lift`).
620
+ */
621
+ function solveWheelLoads(wheels, totalMassKg, com, dampingRatio = .7) {
622
+ if (wheels.length === 0) return [];
623
+ const cornerMasses = solveCornerMasses(wheels, totalMassKg, com);
624
+ return wheels.map((tag, i) => {
625
+ const cornerMassKg = cornerMasses[i];
626
+ const springK = tag.springK ?? cornerMassKg * G_SI / Math.max(tag.sag, 1e-4);
627
+ const dampingC = tag.dampingC ?? 2 * dampingRatio * Math.sqrt(springK * cornerMassKg);
628
+ const lift = Math.max(0, tag.travel - tag.sag);
629
+ const mountOffset = new THREE.Vector3(0, lift, 0);
630
+ if (tag.quaternion) mountOffset.applyQuaternion(new THREE.Quaternion(tag.quaternion[0], tag.quaternion[1], tag.quaternion[2], tag.quaternion[3]).normalize());
238
631
  return {
239
- tag: e,
240
- cornerMassKg: r,
241
- springK: a,
242
- dampingC: e.dampingC ?? 2 * i * Math.sqrt(a * r),
243
- mountPos: L(e)
632
+ tag,
633
+ cornerMassKg,
634
+ springK,
635
+ dampingC,
636
+ mountPos: [
637
+ tag.position[0] + mountOffset.x,
638
+ tag.position[1] + mountOffset.y,
639
+ tag.position[2] + mountOffset.z
640
+ ]
244
641
  };
245
642
  });
246
- if (!a || !o) return w;
247
- R.set(o[0], o[1], o[2], o[3]).normalize(), z.makeRotationFromQuaternion(R);
248
- let T = z.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;
249
- for (let e of w) {
250
- let t = e.mountPos[0] - r[0], n = e.mountPos[2] - r[2];
251
- 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;
252
- }
253
- let M = (e, t, n) => {
254
- if (!(n > 1e-6) || !(e > 0)) return 1;
255
- let r = e * .03333333333333333 / n, i = Math.max(.5, 1 - .5 * (t * .0011111111111111111 / n));
256
- return r > i ? i / r : 1;
257
- }, N = Math.min(M(E, k, n), M(O, j, ee), M(D, A, te));
258
- return N < 1 ? w.map((e) => e.tag.dampingC === void 0 ? {
259
- ...e,
260
- dampingC: e.dampingC * N
261
- } : e) : w;
262
643
  }
263
644
  // src/KhrVehicle.tsx
264
- var B = 220, ue = new x.Quaternion(), V = new x.Vector3();
265
- function H({ ref: t, bundle: n, position: a = [
266
- 0,
267
- .5,
268
- 0
269
- ], enable: o = !0, carConfig: s, droneConfig: c, wheelConfig: m, frontWheelConfig: v, rearWheelConfig: y, propellerConfig: x, vehicleRef: E, children: D, ...O }) {
270
- let { world: k } = b(), A = f(u), j = f(i), ie = w((e) => e.gravityField), P = g(null), [F, se] = _(!1), [I, L] = _(!1), R = g(!1), [z, B] = _(!1), H = g(!1), U = d((e) => {
271
- P.current = e, E && (E.current = e), typeof t == "function" ? t(e) : t && (t.current = e);
272
- }, [t, E]), { mass: W, com: G, inertia: K, inertiaFrame: q, linearVelocity: de, angularVelocity: fe, gravityFactor: pe } = h(() => ne(n.bodies), [n.bodies]), me = h(() => ae([...n.wheels.map((e) => e.object), ...n.propellers.map((e) => e.object)]), [n]), [he, ge, J] = M(a), [_e, ve, ye, be] = N(O.rotation, O.quaternion), Y = h(() => (ue.set(_e, ve, ye, be), V.set(G[0], G[1], G[2]).applyQuaternion(ue), [
273
- he + V.x,
274
- ge + V.y,
275
- J + V.z
276
- ]), [
277
- he,
278
- ge,
279
- J,
280
- _e,
281
- ve,
282
- ye,
283
- be,
284
- G
285
- ]), xe = h(() => [
286
- -G[0],
287
- -G[1],
288
- -G[2]
289
- ], [G]), Se = h(() => re(n.bodies, G), [n.bodies, G]), Ce = h(() => {
290
- let t = {
291
- ...n.tune,
292
- ...s
293
- };
294
- 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)");
295
- return t;
296
- }, [
297
- n.tune,
298
- n.wheels,
299
- s
300
- ]), X = h(() => le(n.wheels, W, G, .7, K, q).map((e) => ({
301
- sw: e,
302
- localPos: [
303
- e.mountPos[0] - G[0],
304
- e.mountPos[1] - G[1],
305
- e.mountPos[2] - G[2]
306
- ]
307
- })), [
308
- n.wheels,
309
- W,
310
- G,
311
- K,
312
- q
313
- ]), Z = h(() => n.propellers.map((e) => ({
314
- p: e,
315
- localPos: [
316
- e.position[0] - G[0],
317
- e.position[1] - G[1],
318
- e.position[2] - G[2]
319
- ]
320
- })), [n.propellers, G]), we = h(() => n.droneTune || c ? {
321
- ...n.droneTune,
322
- ...c
323
- } : void 0, [n.droneTune, c]);
324
- p(() => {
325
- let e = P.current?.body;
326
- e && (e.setAdditionalMassProperties(W, {
327
- x: 0,
328
- y: 0,
329
- z: 0
330
- }, {
331
- x: K[0],
332
- y: K[1],
333
- z: K[2]
334
- }, {
335
- x: q[0],
336
- y: q[1],
337
- z: q[2],
338
- w: q[3]
339
- }, !0), e.recomputeMassPropertiesFromColliders(), Z.length > 0 && se(!0));
645
+ var patchedHandles = /* @__PURE__ */ new WeakSet();
646
+ function hasActiveMovement(m) {
647
+ 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));
648
+ }
649
+ function KhrVehicle({ scale, colliders, bundle, ...rest }) {
650
+ assertVehicleProps(scale, colliders);
651
+ bundle.scene.updateMatrixWorld(true);
652
+ assertSceneIdentityWorldScale(bundle.scene);
653
+ const { ref, vehicleRef, jointsRef, position, rotation, quaternion, enable = true, enableCustomGravity = false, carConfig, droneConfig, wheelConfig, frontWheelConfig, rearWheelConfig, propellerConfig, linearVelocity, angularVelocity, gravityScale, children, ...ecctrlRest } = rest;
654
+ 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)));
660
+ 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), []);
669
+ useLayoutEffect(() => {
670
+ setRotorsPrimed(true);
671
+ }, []);
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);
683
+ }
340
684
  }, [
341
- W,
342
- K,
343
- q,
344
- Z.length
685
+ enableCustomGravity,
686
+ propZeroG,
687
+ world
345
688
  ]);
346
- let Te = !!O.enableCustomGravity, Q;
347
- if (Te) P.current?.body ? V.copy(P.current.body.translation()) : V.set(Y[0], Y[1], Y[2]), Q = ie(V).lengthSq() > 1e-12;
348
- else {
349
- let [e, t, n] = A ?? [
350
- k.gravity.x,
351
- k.gravity.y,
352
- k.gravity.z
353
- ];
354
- Q = e * e + t * t + n * n > 1e-12;
355
- }
356
- let $ = o && j, Ee = $ && Q && !z && I;
357
- p(() => {
358
- Q && H.current && (H.current = !1, B(!1));
359
- }, [Q]);
360
- let De = m?.enable, Oe = v?.enable, ke = y?.enable, Ae = h(() => {
361
- let e = /* @__PURE__ */ new Set();
362
- if (!Ee) return e;
363
- for (let { sw: t } of X) ((t.tag.steer ? Oe : ke) ?? De ?? o) && e.add(t.tag.nodeName);
364
- return e;
365
- }, [
366
- X,
367
- Ee,
368
- o,
369
- De,
370
- Oe,
371
- ke
689
+ const chassis = useMemo(() => computeChassisMassProps(bundle.bodies), [bundle]);
690
+ const collidersList = useMemo(() => buildChassisColliders(bundle.bodies, chassis), [bundle.bodies, chassis]);
691
+ const solvedWheels = useMemo(() => solveWheelLoads(bundle.wheels, chassis.mass, chassis.com), [
692
+ bundle.wheels,
693
+ chassis.mass,
694
+ chassis.com
695
+ ]);
696
+ const rotorOrigins = useMemo(() => captureRotorOrigins([...bundle.wheels.map((w) => w.object), ...bundle.propellers.map((p) => p.object)]), [bundle.wheels, bundle.propellers]);
697
+ const [px, py, pz] = readPosTuple(position);
698
+ const [qx, qy, qz, qw] = readSpawnQuat(rotation, quaternion);
699
+ const bodyPos = useMemo(() => [
700
+ px,
701
+ py,
702
+ pz
703
+ ], [
704
+ px,
705
+ py,
706
+ pz
707
+ ]);
708
+ const bodyQuat = useMemo(() => [
709
+ qx,
710
+ qy,
711
+ qz,
712
+ qw
713
+ ], [
714
+ qx,
715
+ qy,
716
+ qz,
717
+ qw
718
+ ]);
719
+ const innerRef = useRef(null);
720
+ const assignRef = useCallback((handle) => {
721
+ if (handle && !patchedHandles.has(handle)) {
722
+ patchedHandles.add(handle);
723
+ const origSetMovement = handle.setMovement;
724
+ handle.setMovement = (state) => {
725
+ origSetMovement(state);
726
+ if (hasActiveMovement(state) && handle.body?.isSleeping()) handle.body.wakeUp();
727
+ };
728
+ }
729
+ innerRef.current = handle;
730
+ if (vehicleRef) vehicleRef.current = handle;
731
+ if (typeof ref === "function") ref(handle);
732
+ else if (ref && typeof ref === "object") ref.current = handle;
733
+ }, [ref, vehicleRef]);
734
+ const omiSteerAngle = useMemo(() => bundle.wheels.find((w) => w.steer && w.maxSteeringAngle !== void 0 && w.maxSteeringAngle > 0)?.maxSteeringAngle, [bundle.wheels]);
735
+ const mergedCarConfig = useMemo(() => bundle.tune || carConfig || omiSteerAngle !== void 0 ? {
736
+ ...omiSteerAngle !== void 0 ? { maxSteerAngle: omiSteerAngle } : {},
737
+ ...bundle.tune,
738
+ ...carConfig
739
+ } : void 0, [
740
+ omiSteerAngle,
741
+ bundle.tune,
742
+ carConfig
372
743
  ]);
373
- return /* @__PURE__ */ C(T, {
374
- ref: U,
375
- position: Y,
376
- enable: $,
377
- carConfig: Ce,
378
- droneConfig: we,
379
- ...de ? { linearVelocity: de } : {},
380
- ...fe ? { angularVelocity: fe } : {},
381
- ...pe === void 0 ? {} : { gravityScale: pe },
382
- ...O,
744
+ const mergedDroneConfig = useMemo(() => bundle.droneTune || droneConfig ? {
745
+ ...bundle.droneTune,
746
+ ...droneConfig
747
+ } : void 0, [bundle.droneTune, droneConfig]);
748
+ const effLinVel = linearVelocity ?? chassis.linearVelocity;
749
+ const effAngVel = angularVelocity ?? chassis.angularVelocity;
750
+ const effGravScale = gravityScale ?? chassis.gravityFactor;
751
+ return /* @__PURE__ */ jsxs(EcctrlVehicle, {
752
+ ref: assignRef,
753
+ enable,
754
+ enableCustomGravity,
755
+ position: bodyPos,
756
+ quaternion: bodyQuat,
757
+ ...effLinVel !== void 0 ? { linearVelocity: effLinVel } : {},
758
+ ...effAngVel !== void 0 ? { angularVelocity: effAngVel } : {},
759
+ ...effGravScale !== void 0 ? { gravityScale: effGravScale } : {},
760
+ carConfig: mergedCarConfig,
761
+ droneConfig: mergedDroneConfig,
762
+ ...ecctrlRest,
383
763
  children: [
384
- /* @__PURE__ */ C("group", {
385
- position: xe,
386
- children: [/* @__PURE__ */ S(l, {
387
- bundle: n,
388
- owner: "KhrVehicle"
389
- }), D]
390
- }),
391
- Se.map(({ key: e, spec: t }) => /* @__PURE__ */ S(r, { c: t }, e)),
392
- /* @__PURE__ */ S(ce, {
393
- vehicleRef: P,
394
- active: $,
395
- hasRenderGravity: Q,
396
- enableCustomGravity: Te,
397
- activeWheelNames: Ae,
398
- gravityPrimedRef: R,
399
- setGravityPrimed: L,
400
- spatialZeroGRef: H,
401
- setSpatialZeroG: B
764
+ /* @__PURE__ */ jsx(BundleSceneHost, {
765
+ bundle,
766
+ owner: "KhrVehicle"
402
767
  }),
403
- X.map(({ sw: e, localPos: t }) => {
404
- let r = e.tag.steer ? v : y, i = e.tag.nodeName;
405
- return /* @__PURE__ */ S(ee, {
406
- quaternion: e.tag.quaternion,
407
- wheelModelDensity: e.tag.wheelDensity ?? 220,
408
- wheelModelRadius: e.tag.radius,
409
- rayShapeR: e.tag.radius,
410
- rayShapeH: e.tag.width * .5,
411
- rayLength: e.tag.travel,
412
- springK: e.tag.springK ?? e.springK,
413
- dampingC: e.tag.dampingC ?? e.dampingC,
414
- steerWheel: e.tag.steer,
415
- driveWheel: e.tag.drive,
416
- brakeWheel: e.tag.brake,
417
- steerInvert: e.tag.steerInvert,
418
- driveInvert: e.tag.driveInvert,
419
- driveTorqueWeight: e.tag.driveTorqueWeight,
420
- tireGripFactor: e.tag.tireGripFactor,
421
- latFrictionEllipseScale: e.tag.latFrictionEllipseScale,
422
- relaxLngRate: e.tag.relaxLngRate,
423
- relaxLatRate: e.tag.relaxLatRate,
424
- rollingResistanceCoef: e.tag.rollingResistanceCoef,
425
- lngSlipRatioCurveData: e.tag.lngSlipRatioCurveData,
426
- latSlipRatioCurveData: e.tag.latSlipRatioCurveData,
427
- maxBrakeTorque: e.tag.maxBrakeTorque ?? e.cornerMassKg * 9.80665 * e.tag.radius,
428
- minLatRelaxCoeff: 1,
429
- groundDetection: "rayCast",
430
- ...m,
431
- ...r,
432
- name: i,
433
- position: t,
434
- enable: Ae.has(i),
435
- children: /* @__PURE__ */ S(oe, {
436
- object: e.tag.object,
437
- center: e.tag.position,
438
- quaternion: e.tag.quaternion,
439
- scene: n.scene,
440
- origin: me.get(e.tag.object)
441
- })
442
- }, i);
768
+ children,
769
+ collidersList.map(({ key, spec, massProperties }) => /* @__PURE__ */ jsx(KhrCollider, {
770
+ c: spec,
771
+ massProperties
772
+ }, key)),
773
+ /* @__PURE__ */ jsx(KhrVehicleJoints, {
774
+ bodies: bundle.bodies,
775
+ vehicleRef: innerRef,
776
+ jointsRef
443
777
  }),
444
- Z.map(({ p: e, localPos: t }) => {
445
- let r = !!((x?.enable ?? o) && $), i = /* @__PURE__ */ S(oe, {
446
- object: e.object,
447
- center: e.position,
448
- quaternion: e.quaternion,
449
- scene: n.scene,
450
- origin: me.get(e.object)
451
- });
452
- return r ? /* @__PURE__ */ S(te, {
453
- debug: !1,
454
- maxThrust: e.maxThrust,
455
- torqueRatio: e.torqueRatio,
456
- invertThrust: e.invertThrust,
457
- invertTorque: e.invertTorque,
458
- ...x,
459
- name: e.nodeName,
460
- position: t,
461
- quaternion: e.quaternion,
462
- enable: F,
463
- children: i
464
- }, e.nodeName) : /* @__PURE__ */ S("group", {
465
- position: t,
466
- quaternion: e.quaternion,
467
- children: i
468
- }, `${e.nodeName}-idle`);
469
- })
778
+ rotorsPrimed && /* @__PURE__ */ jsxs(Fragment, { children: [
779
+ /* @__PURE__ */ jsx(ZeroGWheelPreGuard, {
780
+ vehicleRef: innerRef,
781
+ enable,
782
+ enableCustomGravity,
783
+ spawnPos: bodyPos,
784
+ wheelActiveRef,
785
+ zeroGRef,
786
+ customPrimedRef,
787
+ needsEpochBumpRef,
788
+ onZeroGChange: setRuntimeZeroG,
789
+ onCustomPrimed: markCustomPrimed,
790
+ onBumpWheelEpoch: bumpWheelEpoch
791
+ }),
792
+ /* @__PURE__ */ jsx(KhrVehicleRotors, {
793
+ solvedWheels,
794
+ propellers: bundle.propellers,
795
+ scene: bundle.scene,
796
+ comZ: chassis.com[2],
797
+ rotorOrigins,
798
+ enable,
799
+ wheelEnable,
800
+ wheelEpoch,
801
+ wheelConfig,
802
+ frontWheelConfig,
803
+ rearWheelConfig,
804
+ propellerConfig
805
+ }),
806
+ /* @__PURE__ */ jsx(ZeroGWheelPostGuard, {
807
+ vehicleRef: innerRef,
808
+ zeroGRef
809
+ })
810
+ ] })
470
811
  ]
471
812
  });
472
813
  }
473
- function U({ scale: e, colliders: t, bundle: n, ...r }) {
474
- return j(e, t), n.scene.updateMatrixWorld(!0), a(n.scene), /* @__PURE__ */ S(H, {
475
- bundle: n,
476
- ...r
477
- }, n.scene.uuid);
478
- }
479
- export { I as BENCH_GRAVITY, U as KhrVehicle, B as WHEEL_ASSEMBLY_DENSITY_KG_M3, le as solveWheelLoads };
814
+ export { KhrVehicle, solveWheelLoads };
815
+
816
+ //# sourceMappingURL=vehicle.js.map