@pinkaphant/ecctrl 0.0.0-stage → 2.0.3

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 (117) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/LICENSE +21 -0
  3. package/NOTICE +10 -0
  4. package/dist/Color-V9u0UyNg.cjs +81 -0
  5. package/dist/Color-V9u0UyNg.cjs.map +1 -0
  6. package/dist/Color-rCfz0rNn.js +28 -0
  7. package/dist/Color-rCfz0rNn.js.map +1 -0
  8. package/dist/CurveLUT-BfMhx3LX.js +88 -0
  9. package/dist/CurveLUT-BfMhx3LX.js.map +1 -0
  10. package/dist/CurveLUT-Ck18ZlkK.cjs +99 -0
  11. package/dist/CurveLUT-Ck18ZlkK.cjs.map +1 -0
  12. package/dist/EcctrlAnimationStateController-41Cm1Tt1.cjs +111 -0
  13. package/dist/EcctrlAnimationStateController-41Cm1Tt1.cjs.map +1 -0
  14. package/dist/EcctrlAnimationStateController-Bb2fARWF.js +94 -0
  15. package/dist/EcctrlAnimationStateController-Bb2fARWF.js.map +1 -0
  16. package/dist/Math-BkrN2TZK.js +49 -0
  17. package/dist/Math-BkrN2TZK.js.map +1 -0
  18. package/dist/Math-ByyUpUHB.cjs +68 -0
  19. package/dist/Math-ByyUpUHB.cjs.map +1 -0
  20. package/dist/all.cjs +52 -0
  21. package/dist/all.cjs.map +1 -0
  22. package/dist/all.d.ts +16 -0
  23. package/dist/all.js +32 -0
  24. package/dist/all.js.map +1 -0
  25. package/dist/animation.cjs +23 -0
  26. package/dist/animation.cjs.map +1 -0
  27. package/dist/animation.d.ts +8 -0
  28. package/dist/animation.js +20 -0
  29. package/dist/animation.js.map +1 -0
  30. package/dist/camera-B_UgIm14.js +71 -0
  31. package/dist/camera-B_UgIm14.js.map +1 -0
  32. package/dist/camera-CzMKt9dI.cjs +79 -0
  33. package/dist/camera-CzMKt9dI.cjs.map +1 -0
  34. package/dist/camera.cjs +10 -0
  35. package/dist/camera.d.ts +9 -0
  36. package/dist/camera.js +9 -0
  37. package/dist/character/Ecctrl.d.ts +105 -0
  38. package/dist/character/animation/EcctrlAnimationStateController.d.ts +17 -0
  39. package/dist/character/animation/index.d.ts +13 -0
  40. package/dist/character/animation/resolveAnimationState.d.ts +9 -0
  41. package/dist/character/animation/types.d.ts +19 -0
  42. package/dist/character/animation/useEcctrlAnimationStore.d.ts +21 -0
  43. package/dist/character/types.d.ts +27 -0
  44. package/dist/chunk-D6vf50IK.cjs +35 -0
  45. package/dist/curves/CurveLUT.d.ts +27 -0
  46. package/dist/curves.cjs +22 -0
  47. package/dist/curves.cjs.map +1 -0
  48. package/dist/curves.d.ts +9 -0
  49. package/dist/curves.js +20 -0
  50. package/dist/curves.js.map +1 -0
  51. package/dist/gravity/EcctrlCameraControls.d.ts +28 -0
  52. package/dist/gravity/useCustomGravity.d.ts +23 -0
  53. package/dist/gravity.cjs +21 -0
  54. package/dist/gravity.cjs.map +1 -0
  55. package/dist/gravity.d.ts +9 -0
  56. package/dist/gravity.js +20 -0
  57. package/dist/gravity.js.map +1 -0
  58. package/dist/index.cjs +14 -0
  59. package/dist/index.d.ts +12 -0
  60. package/dist/index.js +10 -0
  61. package/dist/input/Joystick.d.ts +18 -0
  62. package/dist/input/VirtualButton.d.ts +17 -0
  63. package/dist/input/stores/useButtonStore.d.ts +21 -0
  64. package/dist/input/stores/useJoystickStore.d.ts +26 -0
  65. package/dist/input-CrNBMRxm.js +315 -0
  66. package/dist/input-CrNBMRxm.js.map +1 -0
  67. package/dist/input-DBhf3WZe.cjs +340 -0
  68. package/dist/input-DBhf3WZe.cjs.map +1 -0
  69. package/dist/input.cjs +13 -0
  70. package/dist/input.d.ts +15 -0
  71. package/dist/input.js +9 -0
  72. package/dist/leva--ZV58vPr.cjs +771 -0
  73. package/dist/leva--ZV58vPr.cjs.map +1 -0
  74. package/dist/leva-BjLuypTs.js +764 -0
  75. package/dist/leva-BjLuypTs.js.map +1 -0
  76. package/dist/leva.cjs +10 -0
  77. package/dist/leva.d.ts +9 -0
  78. package/dist/leva.js +9 -0
  79. package/dist/plugins/leva/CurveEditorPlugin.d.ts +72 -0
  80. package/dist/shared/Math.d.ts +11 -0
  81. package/dist/shared/constants/Color.d.ts +16 -0
  82. package/dist/shared/types.d.ts +16 -0
  83. package/dist/src-BTTVvwrl.cjs +1172 -0
  84. package/dist/src-BTTVvwrl.cjs.map +1 -0
  85. package/dist/src-XJOuoUi3.js +1164 -0
  86. package/dist/src-XJOuoUi3.js.map +1 -0
  87. package/dist/time/TimeControl.d.ts +16 -0
  88. package/dist/time-B4iUfe91.cjs +65 -0
  89. package/dist/time-B4iUfe91.cjs.map +1 -0
  90. package/dist/time-DTVzhzJ8.js +60 -0
  91. package/dist/time-DTVzhzJ8.js.map +1 -0
  92. package/dist/time.cjs +10 -0
  93. package/dist/time.d.ts +9 -0
  94. package/dist/time.js +9 -0
  95. package/dist/useCustomGravity-B35U0d4V.cjs +45 -0
  96. package/dist/useCustomGravity-B35U0d4V.cjs.map +1 -0
  97. package/dist/useCustomGravity-elzlTR6Y.js +38 -0
  98. package/dist/useCustomGravity-elzlTR6Y.js.map +1 -0
  99. package/dist/utils.cjs +23 -0
  100. package/dist/utils.cjs.map +1 -0
  101. package/dist/utils.d.ts +8 -0
  102. package/dist/utils.js +20 -0
  103. package/dist/utils.js.map +1 -0
  104. package/dist/vehicle-AEqO39Wm.js +2525 -0
  105. package/dist/vehicle-AEqO39Wm.js.map +1 -0
  106. package/dist/vehicle-DbaRBeDD.cjs +2545 -0
  107. package/dist/vehicle-DbaRBeDD.cjs.map +1 -0
  108. package/dist/vehicle.cjs +12 -0
  109. package/dist/vehicle.d.ts +14 -0
  110. package/dist/vehicle.js +9 -0
  111. package/dist/vehicles/EcctrlVehicle.d.ts +111 -0
  112. package/dist/vehicles/components/ShapeCastWheel.d.ts +114 -0
  113. package/dist/vehicles/components/ThrustPropeller.d.ts +51 -0
  114. package/dist/vehicles/types.d.ts +39 -0
  115. package/package.json +149 -4
  116. package/readme.md +739 -0
  117. package/README.md +0 -3
@@ -0,0 +1,2525 @@
1
+ /*!
2
+ * Ecctrl
3
+ * https://github.com/pmndrs/ecctrl
4
+ *
5
+ * SPDX-FileCopyrightText: 2023-2026 Erdong Chen
6
+ * SPDX-License-Identifier: MIT
7
+ */
8
+ import { t as useCustomGravity } from "./useCustomGravity-elzlTR6Y.js";
9
+ import { n as evaluateCurveLUT, t as bakeCurveLUT } from "./CurveLUT-BfMhx3LX.js";
10
+ import { r as remap, t as createSlerpVec3 } from "./Math-BkrN2TZK.js";
11
+ import { a as EC_GREEN, c as EC_PURPLE, l as EC_RED, n as EC_BLUE, s as EC_MED_PURPLE, t as EC_AZURE } from "./Color-rCfz0rNn.js";
12
+ import * as THREE from "three";
13
+ import { useFrame } from "@react-three/fiber";
14
+ import { RigidBody, useBeforePhysicsStep, useRapier } from "@react-three/rapier";
15
+ import React, { createContext, forwardRef, useCallback, useContext, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef } from "react";
16
+ import { QueryFilterFlags } from "@dimforge/rapier3d-compat";
17
+ import { clamp, generateUUID, lerp } from "three/src/math/MathUtils.js";
18
+ //#region src/vehicles/EcctrlVehicle.tsx
19
+ /*!
20
+ * Ecctrl
21
+ * https://github.com/pmndrs/ecctrl
22
+ *
23
+ * SPDX-FileCopyrightText: 2023-2026 Erdong Chen
24
+ * SPDX-License-Identifier: MIT
25
+ */
26
+ var DEFAULT_CAR_CONFIG = {
27
+ controlMode: "VELOCITY",
28
+ engineHorsepower: 6,
29
+ engineMaxRPM: 6e3,
30
+ gearRatios: [10],
31
+ finalDriveRatio: 1,
32
+ transmissionMode: "auto",
33
+ shiftUpRPM: 5200,
34
+ shiftDownRPM: 2200,
35
+ shiftCooldown: .35,
36
+ steerRate: Math.PI * 2,
37
+ maxSteerAngle: Math.PI / 6,
38
+ reverseTorqueScale: 1,
39
+ reverseRPMScale: .3,
40
+ engineTorqueCurveData: {
41
+ points: [{
42
+ x: 0,
43
+ y: 1,
44
+ r_out: 0
45
+ }, {
46
+ x: 1,
47
+ y: 0,
48
+ r_in: 0
49
+ }],
50
+ samples: 50
51
+ },
52
+ steerAngleCurveData: {
53
+ points: [
54
+ {
55
+ x: 0,
56
+ y: 1,
57
+ r_out: 0
58
+ },
59
+ {
60
+ x: .2,
61
+ y: 1,
62
+ r_in: 0,
63
+ r_out: 0
64
+ },
65
+ {
66
+ x: 1,
67
+ y: .4,
68
+ r_in: 0
69
+ }
70
+ ],
71
+ samples: 50
72
+ }
73
+ };
74
+ var DEFAULT_DRONE_CONFIG = {
75
+ controlMode: "VELOCITY",
76
+ maxYawRate: 2,
77
+ maxHorizSpeed: 30,
78
+ maxVertSpeed: 8,
79
+ maxTiltAngle: Math.PI / 4,
80
+ airDragFactor: .2,
81
+ TILT_P: 15,
82
+ TILT_D: 3,
83
+ YAW_POS_P: 6,
84
+ YAW_VEL_P: 4,
85
+ VERT_POS_P: 9,
86
+ VERT_POS_D: 7,
87
+ HORIZ_POS_P: 5,
88
+ HORIZ_POS_D: 5.5,
89
+ HORIZ_VEL_P: 1,
90
+ VERT_VEL_P: 2
91
+ };
92
+ var getDriveRatio = (gearRatios, gearIndex, finalDriveRatio) => {
93
+ var _ref, _gearRatios$gearIndex;
94
+ return ((_ref = (_gearRatios$gearIndex = gearRatios[gearIndex]) !== null && _gearRatios$gearIndex !== void 0 ? _gearRatios$gearIndex : gearRatios[0]) !== null && _ref !== void 0 ? _ref : 0) * finalDriveRatio;
95
+ };
96
+ var getMaxWheelAngVel = (engineMaxRPM, driveRatio) => driveRatio !== 0 ? engineMaxRPM / driveRatio * (2 * Math.PI / 60) : 0;
97
+ function solve4x4(G, b, aug, out) {
98
+ for (let r = 0; r < 4; r++) {
99
+ const r4 = r * 4;
100
+ const r5 = r * 5;
101
+ aug[r5] = G[r4];
102
+ aug[r5 + 1] = G[r4 + 1];
103
+ aug[r5 + 2] = G[r4 + 2];
104
+ aug[r5 + 3] = G[r4 + 3];
105
+ aug[r5 + 4] = b[r];
106
+ }
107
+ for (let col = 0; col < 4; col++) {
108
+ let pivotRow = col;
109
+ let maxAbs = Math.abs(aug[col * 5 + col]);
110
+ for (let r = col + 1; r < 4; r++) {
111
+ const v = Math.abs(aug[r * 5 + col]);
112
+ if (v > maxAbs) {
113
+ maxAbs = v;
114
+ pivotRow = r;
115
+ }
116
+ }
117
+ if (maxAbs < 1e-15) {
118
+ out[col] = 0;
119
+ continue;
120
+ }
121
+ if (pivotRow !== col) {
122
+ const c5 = col * 5;
123
+ const p5 = pivotRow * 5;
124
+ for (let k = col; k < 5; k++) {
125
+ const tmp = aug[c5 + k];
126
+ aug[c5 + k] = aug[p5 + k];
127
+ aug[p5 + k] = tmp;
128
+ }
129
+ }
130
+ const c5 = col * 5;
131
+ const diag = aug[c5 + col];
132
+ for (let r = col + 1; r < 4; r++) {
133
+ const r5 = r * 5;
134
+ const factor = aug[r5 + col] / diag;
135
+ if (factor === 0) continue;
136
+ for (let k = col + 1; k < 5; k++) aug[r5 + k] -= factor * aug[c5 + k];
137
+ }
138
+ }
139
+ for (let r = 3; r >= 0; r--) {
140
+ const r5 = r * 5;
141
+ const diag = aug[r5 + r];
142
+ if (Math.abs(diag) < 1e-15) {
143
+ out[r] = 0;
144
+ continue;
145
+ }
146
+ let sum = aug[r5 + 4];
147
+ for (let c = r + 1; c < 4; c++) sum -= aug[r5 + c] * out[c];
148
+ out[r] = sum / diag;
149
+ }
150
+ }
151
+ var VehicleContext = createContext(null);
152
+ var EcctrlVehicle = /* @__PURE__ */ forwardRef(({ children, enable = true, carConfig = {}, droneConfig = {}, enableCustomGravity = false, gravityDirLerpSpeed = 6, ...props }, ref) => {
153
+ /**
154
+ * Rapier preset
155
+ */
156
+ const { rapier, world } = useRapier();
157
+ /**
158
+ * Vehicle controls preset
159
+ */
160
+ const carControlConfig = useMemo(() => ({
161
+ ...DEFAULT_CAR_CONFIG,
162
+ ...carConfig
163
+ }), [carConfig]);
164
+ const droneControlConfig = useMemo(() => ({
165
+ ...DEFAULT_DRONE_CONFIG,
166
+ ...droneConfig
167
+ }), [droneConfig]);
168
+ /**
169
+ * Car controller preset
170
+ */
171
+ const engineMaxTorque = useRef(0);
172
+ engineMaxTorque.current = carControlConfig.engineMaxRPM !== 0 ? carControlConfig.engineHorsepower * 7022 / carControlConfig.engineMaxRPM : 0;
173
+ const gearRatios = Array.isArray(carControlConfig.gearRatios) && carControlConfig.gearRatios.length > 0 ? carControlConfig.gearRatios : DEFAULT_CAR_CONFIG.gearRatios;
174
+ const gearIndex = useRef(0);
175
+ gearIndex.current = clamp(Math.floor(gearIndex.current), 0, gearRatios.length - 1);
176
+ const driveRatio = useRef(getDriveRatio(gearRatios, gearIndex.current, carControlConfig.finalDriveRatio));
177
+ driveRatio.current = getDriveRatio(gearRatios, gearIndex.current, carControlConfig.finalDriveRatio);
178
+ const engineRPM = useRef(0);
179
+ const shiftCooldownTimer = useRef(0);
180
+ const engineTorqueCurve = useMemo(() => {
181
+ var _carControlConfig$eng;
182
+ return bakeCurveLUT(carControlConfig.engineTorqueCurveData.points, (_carControlConfig$eng = carControlConfig.engineTorqueCurveData.samples) !== null && _carControlConfig$eng !== void 0 ? _carControlConfig$eng : 50);
183
+ }, [carControlConfig.engineTorqueCurveData]);
184
+ const steerAngleCurve = useMemo(() => {
185
+ var _carControlConfig$ste;
186
+ return bakeCurveLUT(carControlConfig.steerAngleCurveData.points || [], (_carControlConfig$ste = carControlConfig.steerAngleCurveData.samples) !== null && _carControlConfig$ste !== void 0 ? _carControlConfig$ste : 50);
187
+ }, [carControlConfig.steerAngleCurveData]);
188
+ const maxWheelAngVel = useRef(getMaxWheelAngVel(carControlConfig.engineMaxRPM, driveRatio.current));
189
+ maxWheelAngVel.current = getMaxWheelAngVel(carControlConfig.engineMaxRPM, driveRatio.current);
190
+ const driveWheelConfig = useRef({
191
+ maxDriveTorque: 0,
192
+ maxWheelAngVel: maxWheelAngVel.current,
193
+ engineTorqueCurve,
194
+ reverseTorqueScale: carControlConfig.reverseTorqueScale,
195
+ reverseRPMScale: carControlConfig.reverseRPMScale,
196
+ driveRatio: driveRatio.current
197
+ });
198
+ driveWheelConfig.current.maxWheelAngVel = maxWheelAngVel.current;
199
+ driveWheelConfig.current.engineTorqueCurve = engineTorqueCurve;
200
+ driveWheelConfig.current.reverseTorqueScale = carControlConfig.reverseTorqueScale;
201
+ driveWheelConfig.current.reverseRPMScale = carControlConfig.reverseRPMScale;
202
+ driveWheelConfig.current.driveRatio = driveRatio.current;
203
+ const steerWheelConfig = useRef({
204
+ steerAngleCurve,
205
+ steerRate: carControlConfig.steerRate,
206
+ maxSteerAngle: carControlConfig.maxSteerAngle,
207
+ maxWheelAngVel: maxWheelAngVel.current
208
+ });
209
+ steerWheelConfig.current.steerAngleCurve = steerAngleCurve;
210
+ steerWheelConfig.current.steerRate = carControlConfig.steerRate;
211
+ steerWheelConfig.current.maxSteerAngle = carControlConfig.maxSteerAngle;
212
+ steerWheelConfig.current.maxWheelAngVel = maxWheelAngVel.current;
213
+ const syncTransmissionConfig = useCallback(() => {
214
+ driveRatio.current = getDriveRatio(gearRatios, gearIndex.current, carControlConfig.finalDriveRatio);
215
+ maxWheelAngVel.current = getMaxWheelAngVel(carControlConfig.engineMaxRPM, driveRatio.current);
216
+ driveWheelConfig.current.driveRatio = driveRatio.current;
217
+ driveWheelConfig.current.maxWheelAngVel = maxWheelAngVel.current;
218
+ steerWheelConfig.current.maxWheelAngVel = maxWheelAngVel.current;
219
+ }, [
220
+ carControlConfig.engineMaxRPM,
221
+ carControlConfig.finalDriveRatio,
222
+ gearRatios
223
+ ]);
224
+ /**
225
+ * Drone controller preset
226
+ */
227
+ const maxTiltTan = useMemo(() => Math.tan(droneControlConfig.maxTiltAngle), [droneControlConfig.maxTiltAngle]);
228
+ const hoverThrottle = useRef(0);
229
+ const desiredVertForce = useRef(0);
230
+ const gramMatrix = useRef(new Float64Array(16));
231
+ const wrenchRhs = useRef(new Float64Array(4));
232
+ const wrenchAug = useRef(new Float64Array(20));
233
+ const wrenchLambda = useRef(new Float64Array(4));
234
+ const targetUp = useRef(new THREE.Vector3());
235
+ const tiltError = useRef(new THREE.Vector3());
236
+ const tiltAngVel = useRef(new THREE.Vector3());
237
+ const torqueWorld = useRef(new THREE.Vector3());
238
+ const torqueBody = useRef(new THREE.Vector3());
239
+ const airDragImpulse = useRef(new THREE.Vector3());
240
+ const worldThrustDir = useRef(new THREE.Vector3());
241
+ const worldThrustPos = useRef(new THREE.Vector3());
242
+ const worldTorqueDir = useRef(new THREE.Vector3());
243
+ const targetPosition = useRef(new THREE.Vector3());
244
+ const targetHeading = useRef(new THREE.Vector3());
245
+ const targetFwd = useRef(new THREE.Vector3());
246
+ const currentFwd = useRef(new THREE.Vector3());
247
+ const posError = useRef(new THREE.Vector3());
248
+ const horizPosError = useRef(new THREE.Vector3());
249
+ const horizLinVel = useRef(new THREE.Vector3());
250
+ const horizForce = useRef(new THREE.Vector3());
251
+ const worldXAxis = useRef(new THREE.Vector3());
252
+ const worldZAxis = useRef(new THREE.Vector3());
253
+ const vertAccCmd = useRef(0);
254
+ const horizAccCmd = useRef(new THREE.Vector3());
255
+ const targetLinVel = useRef(new THREE.Vector3());
256
+ const linVelError = useRef(new THREE.Vector3());
257
+ /**
258
+ * Gravity controls preset
259
+ */
260
+ const gravityField = useCustomGravity((state) => state.gravityField);
261
+ const applyGravityField = useCustomGravity((state) => state.applyGravityField);
262
+ const upAxis = useRef(new THREE.Vector3(0, 1, 0));
263
+ const referenceGravity = useRef(new THREE.Vector3());
264
+ const referenceGravityMag = useRef(0);
265
+ const referenceGravityDir = useRef(new THREE.Vector3(0, -1, 0));
266
+ const gravityDir = useRef(new THREE.Vector3(0, -1, 0));
267
+ const gravityInitRef = useRef(false);
268
+ const slerpRef = useRef(createSlerpVec3());
269
+ /**
270
+ * User controls setup
271
+ */
272
+ const movementState = useRef({
273
+ forward: false,
274
+ backward: false,
275
+ steerLeft: false,
276
+ steerRight: false,
277
+ brake: false,
278
+ throttleUp: false,
279
+ throttleDown: false,
280
+ yawLeft: false,
281
+ yawRight: false,
282
+ pitchForward: false,
283
+ pitchBackward: false,
284
+ rollLeft: false,
285
+ rollRight: false,
286
+ joystickL: {
287
+ x: 0,
288
+ y: 0
289
+ },
290
+ joystickR: {
291
+ x: 0,
292
+ y: 0
293
+ }
294
+ });
295
+ /**
296
+ * Vehicle collider/model preset
297
+ */
298
+ const vehicleRef = useRef(null);
299
+ const vehiclePos = useRef(new THREE.Vector3());
300
+ const vehicleQuat = useRef(new THREE.Quaternion());
301
+ const vehicleInvertQuat = useRef(new THREE.Quaternion());
302
+ const vehicleLinVel = useRef(new THREE.Vector3());
303
+ const vehicleAngVel = useRef(new THREE.Vector3());
304
+ const vehicleXAxis = useRef(new THREE.Vector3());
305
+ const vehicleYAxis = useRef(new THREE.Vector3());
306
+ const vehicleZAxis = useRef(new THREE.Vector3());
307
+ if (!gravityInitRef.current) {
308
+ gravityInitRef.current = true;
309
+ referenceGravity.current.copy(enableCustomGravity ? gravityField(vehiclePos.current) : world.gravity);
310
+ const initMag = referenceGravity.current.length();
311
+ referenceGravityMag.current = initMag;
312
+ if (initMag > 1e-6) {
313
+ referenceGravityDir.current.copy(referenceGravity.current).divideScalar(initMag);
314
+ gravityDir.current.copy(referenceGravityDir.current);
315
+ upAxis.current.copy(gravityDir.current).negate();
316
+ }
317
+ }
318
+ const setMovement = useCallback((movement) => {
319
+ if (movement.forward !== void 0) movementState.current.forward = movement.forward;
320
+ if (movement.backward !== void 0) movementState.current.backward = movement.backward;
321
+ if (movement.steerLeft !== void 0) movementState.current.steerLeft = movement.steerLeft;
322
+ if (movement.steerRight !== void 0) movementState.current.steerRight = movement.steerRight;
323
+ if (movement.brake !== void 0) movementState.current.brake = movement.brake;
324
+ if (movement.throttleUp !== void 0) movementState.current.throttleUp = movement.throttleUp;
325
+ if (movement.throttleDown !== void 0) movementState.current.throttleDown = movement.throttleDown;
326
+ if (movement.yawLeft !== void 0) movementState.current.yawLeft = movement.yawLeft;
327
+ if (movement.yawRight !== void 0) movementState.current.yawRight = movement.yawRight;
328
+ if (movement.pitchForward !== void 0) movementState.current.pitchForward = movement.pitchForward;
329
+ if (movement.pitchBackward !== void 0) movementState.current.pitchBackward = movement.pitchBackward;
330
+ if (movement.rollLeft !== void 0) movementState.current.rollLeft = movement.rollLeft;
331
+ if (movement.rollRight !== void 0) movementState.current.rollRight = movement.rollRight;
332
+ if (movement.joystickL) {
333
+ movementState.current.joystickL.x = movement.joystickL.x;
334
+ movementState.current.joystickL.y = movement.joystickL.y;
335
+ }
336
+ if (movement.joystickR) {
337
+ movementState.current.joystickR.x = movement.joystickR.x;
338
+ movementState.current.joystickR.y = movement.joystickR.y;
339
+ }
340
+ }, []);
341
+ const setTarget = useCallback((pos, dir) => {
342
+ if (pos) targetPosition.current.copy(pos);
343
+ if (dir) targetHeading.current.copy(dir);
344
+ }, []);
345
+ /**
346
+ * Register/unregister wheels information
347
+ */
348
+ const wheelsInfo = useRef(/* @__PURE__ */ new Map());
349
+ const syncWheelConfig = useCallback(() => {
350
+ let totalDriveTorqueWeight = 0;
351
+ wheelsInfo.current.forEach((wheelInfo) => {
352
+ var _wheelInfo$current$dr;
353
+ if (!wheelInfo.current.driveWheel) return;
354
+ totalDriveTorqueWeight += Math.max(0, (_wheelInfo$current$dr = wheelInfo.current.driveTorqueWeight) !== null && _wheelInfo$current$dr !== void 0 ? _wheelInfo$current$dr : 1);
355
+ });
356
+ wheelsInfo.current.forEach((wheelInfo) => {
357
+ var _wheelInfo$current$se2, _wheelInfo$current2;
358
+ if (wheelInfo.current.driveWheel) {
359
+ var _wheelInfo$current$dr2, _wheelInfo$current$se, _wheelInfo$current;
360
+ const driveTorqueWeight = Math.max(0, (_wheelInfo$current$dr2 = wheelInfo.current.driveTorqueWeight) !== null && _wheelInfo$current$dr2 !== void 0 ? _wheelInfo$current$dr2 : 1);
361
+ (_wheelInfo$current$se = (_wheelInfo$current = wheelInfo.current).setDriveWheelConfig) === null || _wheelInfo$current$se === void 0 || _wheelInfo$current$se.call(_wheelInfo$current, {
362
+ ...driveWheelConfig.current,
363
+ maxDriveTorque: totalDriveTorqueWeight > 0 ? engineMaxTorque.current * driveTorqueWeight / totalDriveTorqueWeight : 0
364
+ });
365
+ }
366
+ if (wheelInfo.current.steerWheel) (_wheelInfo$current$se2 = (_wheelInfo$current2 = wheelInfo.current).setSteerWheelConfig) === null || _wheelInfo$current$se2 === void 0 || _wheelInfo$current$se2.call(_wheelInfo$current2, steerWheelConfig.current);
367
+ });
368
+ }, []);
369
+ const regWheel = useCallback((wheelInfo) => {
370
+ const id = wheelInfo.current.id;
371
+ if (!wheelsInfo.current.has(id)) {
372
+ wheelsInfo.current.set(id, wheelInfo);
373
+ syncWheelConfig();
374
+ }
375
+ }, [syncWheelConfig]);
376
+ const unregWheel = useCallback((id) => {
377
+ if (wheelsInfo.current.delete(id)) syncWheelConfig();
378
+ }, [syncWheelConfig]);
379
+ const setGear = useCallback((index) => {
380
+ const nextGearIndex = clamp(Math.floor(index), 0, gearRatios.length - 1);
381
+ if (gearIndex.current === nextGearIndex) return;
382
+ gearIndex.current = nextGearIndex;
383
+ shiftCooldownTimer.current = carControlConfig.shiftCooldown;
384
+ syncTransmissionConfig();
385
+ syncWheelConfig();
386
+ }, [
387
+ carControlConfig.shiftCooldown,
388
+ gearRatios.length,
389
+ syncTransmissionConfig,
390
+ syncWheelConfig
391
+ ]);
392
+ useEffect(() => {
393
+ syncTransmissionConfig();
394
+ syncWheelConfig();
395
+ }, [
396
+ carControlConfig.engineHorsepower,
397
+ carControlConfig.engineMaxRPM,
398
+ carControlConfig.finalDriveRatio,
399
+ carControlConfig.maxSteerAngle,
400
+ carControlConfig.reverseRPMScale,
401
+ carControlConfig.reverseTorqueScale,
402
+ carControlConfig.steerRate,
403
+ engineTorqueCurve,
404
+ gearRatios,
405
+ steerAngleCurve,
406
+ syncTransmissionConfig,
407
+ syncWheelConfig
408
+ ]);
409
+ /**
410
+ * Register/unregister propellers information
411
+ */
412
+ const propellersInfo = useRef(/* @__PURE__ */ new Map());
413
+ const regPropeller = useCallback((propellerInfo) => {
414
+ const id = propellerInfo.current.id;
415
+ if (!propellersInfo.current.has(id)) propellersInfo.current.set(id, propellerInfo);
416
+ }, []);
417
+ const unregPropeller = useCallback((id) => propellersInfo.current.delete(id), []);
418
+ /**
419
+ * Expose vehicle info and control functions to children via ref and context
420
+ */
421
+ useImperativeHandle(ref, () => ({
422
+ get body() {
423
+ return vehicleRef.current;
424
+ },
425
+ get upAxis() {
426
+ return upAxis.current;
427
+ },
428
+ get gravityDir() {
429
+ return gravityDir.current;
430
+ },
431
+ get gravityMag() {
432
+ return referenceGravityMag.current;
433
+ },
434
+ get currPos() {
435
+ return vehiclePos.current;
436
+ },
437
+ get currQuat() {
438
+ return vehicleQuat.current;
439
+ },
440
+ get currLinVel() {
441
+ return vehicleLinVel.current;
442
+ },
443
+ get currAngVel() {
444
+ return vehicleAngVel.current;
445
+ },
446
+ get bodyXAxis() {
447
+ return vehicleXAxis.current;
448
+ },
449
+ get bodyYAxis() {
450
+ return vehicleYAxis.current;
451
+ },
452
+ get bodyZAxis() {
453
+ return vehicleZAxis.current;
454
+ },
455
+ get targetPos() {
456
+ return targetPosition.current;
457
+ },
458
+ get targetFwd() {
459
+ return targetHeading.current;
460
+ },
461
+ get input() {
462
+ return movementState.current;
463
+ },
464
+ get wheelsInfo() {
465
+ return wheelsInfo.current;
466
+ },
467
+ get propellersInfo() {
468
+ return propellersInfo.current;
469
+ },
470
+ get gearIndex() {
471
+ return gearIndex.current;
472
+ },
473
+ get driveRatio() {
474
+ return driveRatio.current;
475
+ },
476
+ get engineRPM() {
477
+ return engineRPM.current;
478
+ },
479
+ setMovement,
480
+ setTarget,
481
+ setGear
482
+ }), [
483
+ setGear,
484
+ setMovement,
485
+ setTarget
486
+ ]);
487
+ /**
488
+ *
489
+ *
490
+ *
491
+ *
492
+ *
493
+ *
494
+ *
495
+ *
496
+ *
497
+ *
498
+ *
499
+ *
500
+ *
501
+ *
502
+ *
503
+ *
504
+ *
505
+ *
506
+ *
507
+ *
508
+ *
509
+ *
510
+ *
511
+ *
512
+ *
513
+ */
514
+ /**
515
+ * Update vehicle info function
516
+ */
517
+ const updateVehicleInfo = useCallback((body) => {
518
+ vehiclePos.current.copy(body.translation());
519
+ vehicleQuat.current.copy(body.rotation());
520
+ vehicleInvertQuat.current.copy(vehicleQuat.current).invert();
521
+ vehicleLinVel.current.copy(body.linvel());
522
+ vehicleAngVel.current.copy(body.angvel());
523
+ vehicleYAxis.current.set(0, 1, 0).applyQuaternion(vehicleQuat.current);
524
+ vehicleXAxis.current.set(1, 0, 0).applyQuaternion(vehicleQuat.current);
525
+ vehicleZAxis.current.set(0, 0, 1).applyQuaternion(vehicleQuat.current);
526
+ }, []);
527
+ /**
528
+ * Update gravity/upAxis direction and value (sensing only; custom gravity impulse is applied after wheel/propeller sampling)
529
+ */
530
+ const updateGravityInfo = useCallback(() => {
531
+ if (enableCustomGravity) referenceGravity.current.copy(gravityField(vehiclePos.current));
532
+ else referenceGravity.current.copy(world.gravity);
533
+ referenceGravityMag.current = referenceGravity.current.length();
534
+ referenceGravityDir.current.copy(referenceGravity.current).normalize();
535
+ if (referenceGravityDir.current.lengthSq() === 0) referenceGravityDir.current.copy(vehicleYAxis.current).negate();
536
+ gravityDir.current.copy(slerpRef.current(gravityDir.current, referenceGravityDir.current, 1 - Math.exp(-gravityDirLerpSpeed * world.timestep), vehicleZAxis.current));
537
+ upAxis.current.copy(gravityDir.current).negate();
538
+ }, [
539
+ enableCustomGravity,
540
+ gravityDirLerpSpeed,
541
+ gravityField
542
+ ]);
543
+ /**
544
+ *
545
+ *
546
+ *
547
+ *
548
+ *
549
+ *
550
+ *
551
+ *
552
+ *
553
+ *
554
+ *
555
+ *
556
+ *
557
+ *
558
+ *
559
+ *
560
+ *
561
+ *
562
+ *
563
+ *
564
+ *
565
+ *
566
+ *
567
+ *
568
+ *
569
+ */
570
+ /**
571
+ * Car overall control logics
572
+ */
573
+ const updateTransmission = useCallback((wheels) => {
574
+ let totalWheelRPM = 0;
575
+ let totalDriveTorqueWeight = 0;
576
+ wheels.forEach((wheel) => {
577
+ var _wheel$current$driveT;
578
+ if (!wheel.current.driveWheel) return;
579
+ const driveTorqueWeight = Math.max(0, (_wheel$current$driveT = wheel.current.driveTorqueWeight) !== null && _wheel$current$driveT !== void 0 ? _wheel$current$driveT : 1);
580
+ totalWheelRPM += Math.abs(wheel.current.wheelAngVel) * 60 / (Math.PI * 2) * driveTorqueWeight;
581
+ totalDriveTorqueWeight += driveTorqueWeight;
582
+ });
583
+ engineRPM.current = (totalDriveTorqueWeight > 0 ? totalWheelRPM / totalDriveTorqueWeight : 0) * Math.abs(driveRatio.current);
584
+ if (carControlConfig.transmissionMode !== "auto" || gearRatios.length <= 1) return;
585
+ if (shiftCooldownTimer.current > 0) {
586
+ shiftCooldownTimer.current = Math.max(0, shiftCooldownTimer.current - world.timestep);
587
+ return;
588
+ }
589
+ if (engineRPM.current > carControlConfig.shiftUpRPM && gearIndex.current < gearRatios.length - 1) setGear(gearIndex.current + 1);
590
+ else if (engineRPM.current < carControlConfig.shiftDownRPM && gearIndex.current > 0) setGear(gearIndex.current - 1);
591
+ }, [
592
+ carControlConfig.shiftDownRPM,
593
+ carControlConfig.shiftUpRPM,
594
+ carControlConfig.transmissionMode,
595
+ gearRatios.length,
596
+ setGear,
597
+ world.timestep
598
+ ]);
599
+ const velocityBasedCarControl = useCallback((input, wheels) => {
600
+ var _input$joystickL$x, _input$joystickL;
601
+ const driveIn = clamp((input.forward ? 1 : 0) - (input.backward ? 1 : 0), -1, 1);
602
+ const steerIn = clamp((input.steerLeft ? 1 : 0) - (input.steerRight ? 1 : 0) - ((_input$joystickL$x = (_input$joystickL = input.joystickL) === null || _input$joystickL === void 0 ? void 0 : _input$joystickL.x) !== null && _input$joystickL$x !== void 0 ? _input$joystickL$x : 0), -1, 1);
603
+ const brakeIn = input.brake ? 1 : 0;
604
+ wheels.forEach((wheel) => {
605
+ if (wheel.current.driveWheel && wheel.current.setDriveDemand) wheel.current.setDriveDemand(driveIn);
606
+ if (wheel.current.brakeWheel && wheel.current.setBrakeDemand) wheel.current.setBrakeDemand(brakeIn);
607
+ if (wheel.current.steerWheel && wheel.current.setSteerDemand) wheel.current.setSteerDemand(steerIn);
608
+ });
609
+ }, []);
610
+ const applyWheelImpulse = useCallback((wheels, body) => {
611
+ if (!body) return;
612
+ if (body.isSleeping()) {
613
+ let shouldWake = false;
614
+ let enabledCount = 0;
615
+ let hitCount = 0;
616
+ for (const wheel of wheels.values()) {
617
+ const w = wheel.current;
618
+ if (!w.enable) continue;
619
+ enabledCount++;
620
+ if (!w.rayHit) continue;
621
+ hitCount++;
622
+ if (w.isOnPlatform || Math.abs(w.wheelLinVel) > 1e-4) {
623
+ shouldWake = true;
624
+ break;
625
+ }
626
+ }
627
+ if (!shouldWake && enabledCount > 0 && hitCount === 0 && referenceGravityMag.current > 1e-6) shouldWake = true;
628
+ if (!shouldWake) return;
629
+ body.wakeUp();
630
+ }
631
+ wheels.forEach((wheel) => {
632
+ if (!wheel.current.rayHit) return;
633
+ body.applyImpulseAtPoint(wheel.current.floatImp, wheel.current.supPos, false);
634
+ body.applyImpulseAtPoint(wheel.current.lngFricImp, wheel.current.rayHitPos, false);
635
+ body.applyImpulseAtPoint(wheel.current.latFricImp, wheel.current.rayHitPos, false);
636
+ });
637
+ }, []);
638
+ const applyCarControl = useCallback((wheels, body, input) => {
639
+ if (!body) return;
640
+ updateTransmission(wheels);
641
+ velocityBasedCarControl(input, wheels);
642
+ let hasSplitStep = false;
643
+ wheels.forEach((wheel) => {
644
+ if (wheel.current.stepWheelSuspension) {
645
+ hasSplitStep = true;
646
+ wheel.current.stepWheelSuspension();
647
+ } else {
648
+ var _wheel$current$stepWh, _wheel$current;
649
+ (_wheel$current$stepWh = (_wheel$current = wheel.current).stepWheelPhysics) === null || _wheel$current$stepWh === void 0 || _wheel$current$stepWh.call(_wheel$current);
650
+ }
651
+ });
652
+ if (hasSplitStep) {
653
+ const driveIn = clamp((input.forward ? 1 : 0) - (input.backward ? 1 : 0), -1, 1);
654
+ let brakedSupportSum = 0;
655
+ let brkDirX = 0, brkDirY = 0, brkDirZ = 0;
656
+ if (driveIn === 0) wheels.forEach((wheel) => {
657
+ var _w$supportForceMag;
658
+ const w = wheel.current;
659
+ if (!w.enable || !w.rayHit) return;
660
+ const fn = (_w$supportForceMag = w.supportForceMag) !== null && _w$supportForceMag !== void 0 ? _w$supportForceMag : 0;
661
+ if (fn <= 1e-6 || !w.isActivelyBraking) return;
662
+ brakedSupportSum += fn;
663
+ brkDirX += fn * w.lngAxis.x;
664
+ brkDirY += fn * w.lngAxis.y;
665
+ brkDirZ += fn * w.lngAxis.z;
666
+ });
667
+ const brkDirLen = Math.hypot(brkDirX, brkDirY, brkDirZ);
668
+ if (driveIn === 0 && brakedSupportSum > 1e-6 && brkDirLen > 1e-6) {
669
+ const eBrkX = brkDirX / brkDirLen;
670
+ const eBrkY = brkDirY / brkDirLen;
671
+ const eBrkZ = brkDirZ / brkDirLen;
672
+ let remX = 0, remY = 0, remZ = 0;
673
+ wheels.forEach((wheel) => {
674
+ var _w$supportForceMag2, _w$stepWheelTireAndSp2;
675
+ const w = wheel.current;
676
+ if (!w.enable) return;
677
+ if (!w.rayHit || ((_w$supportForceMag2 = w.supportForceMag) !== null && _w$supportForceMag2 !== void 0 ? _w$supportForceMag2 : 0) <= 1e-6) {
678
+ var _w$stepWheelTireAndSp;
679
+ (_w$stepWheelTireAndSp = w.stepWheelTireAndSpin) === null || _w$stepWheelTireAndSp === void 0 || _w$stepWheelTireAndSp.call(w);
680
+ return;
681
+ }
682
+ if (w.isActivelyBraking) return;
683
+ const sg = w.slopeGravImp;
684
+ const alongBrk = sg.x * eBrkX + sg.y * eBrkY + sg.z * eBrkZ;
685
+ const crossX = sg.x - alongBrk * eBrkX;
686
+ const crossY = sg.y - alongBrk * eBrkY;
687
+ const crossZ = sg.z - alongBrk * eBrkZ;
688
+ const crossLen = Math.hypot(crossX, crossY, crossZ);
689
+ let latHoldImp = 0;
690
+ if (crossLen > 1e-9) {
691
+ const eCrossX = crossX / crossLen;
692
+ const eCrossY = crossY / crossLen;
693
+ const eCrossZ = crossZ / crossLen;
694
+ const cosDelta = w.latAxis.x * eCrossX + w.latAxis.y * eCrossY + w.latAxis.z * eCrossZ;
695
+ latHoldImp = (crossX * w.latAxis.x + crossY * w.latAxis.y + crossZ * w.latAxis.z) / Math.max(cosDelta * cosDelta, .25);
696
+ }
697
+ remX += sg.x - latHoldImp * w.latAxis.x;
698
+ remY += sg.y - latHoldImp * w.latAxis.y;
699
+ remZ += sg.z - latHoldImp * w.latAxis.z;
700
+ (_w$stepWheelTireAndSp2 = w.stepWheelTireAndSpin) === null || _w$stepWheelTireAndSp2 === void 0 || _w$stepWheelTireAndSp2.call(w, 0, latHoldImp);
701
+ });
702
+ let excessAlongBrk = 0;
703
+ let spareCapSum = 0;
704
+ wheels.forEach((wheel) => {
705
+ var _w$supportForceMag3, _w$supportForceMag4, _w$maxCaliperImp;
706
+ const w = wheel.current;
707
+ if (!w.enable || !w.rayHit || ((_w$supportForceMag3 = w.supportForceMag) !== null && _w$supportForceMag3 !== void 0 ? _w$supportForceMag3 : 0) <= 1e-6 || !w.isActivelyBraking) return;
708
+ const share = ((_w$supportForceMag4 = w.supportForceMag) !== null && _w$supportForceMag4 !== void 0 ? _w$supportForceMag4 : 0) / brakedSupportSum;
709
+ const sg = w.slopeGravImp;
710
+ const effX = sg.x + share * remX;
711
+ const effY = sg.y + share * remY;
712
+ const effZ = sg.z + share * remZ;
713
+ const effLng = effX * w.lngAxis.x + effY * w.lngAxis.y + effZ * w.lngAxis.z;
714
+ const cap = (_w$maxCaliperImp = w.maxCaliperImp) !== null && _w$maxCaliperImp !== void 0 ? _w$maxCaliperImp : Infinity;
715
+ if (Math.abs(effLng) > cap) {
716
+ const clamped = Math.sign(effLng) * cap;
717
+ excessAlongBrk += (effLng - clamped) * (w.lngAxis.x * eBrkX + w.lngAxis.y * eBrkY + w.lngAxis.z * eBrkZ);
718
+ } else spareCapSum += cap - Math.abs(effLng);
719
+ });
720
+ wheels.forEach((wheel) => {
721
+ var _w$supportForceMag5, _w$supportForceMag6, _w$maxCaliperImp2, _w$stepWheelTireAndSp3;
722
+ const w = wheel.current;
723
+ if (!w.enable || !w.rayHit || ((_w$supportForceMag5 = w.supportForceMag) !== null && _w$supportForceMag5 !== void 0 ? _w$supportForceMag5 : 0) <= 1e-6 || !w.isActivelyBraking) return;
724
+ const share = ((_w$supportForceMag6 = w.supportForceMag) !== null && _w$supportForceMag6 !== void 0 ? _w$supportForceMag6 : 0) / brakedSupportSum;
725
+ const sg = w.slopeGravImp;
726
+ const effX = sg.x + share * remX;
727
+ const effY = sg.y + share * remY;
728
+ const effZ = sg.z + share * remZ;
729
+ let effLng = effX * w.lngAxis.x + effY * w.lngAxis.y + effZ * w.lngAxis.z;
730
+ const effLat = effX * w.latAxis.x + effY * w.latAxis.y + effZ * w.latAxis.z;
731
+ const cap = (_w$maxCaliperImp2 = w.maxCaliperImp) !== null && _w$maxCaliperImp2 !== void 0 ? _w$maxCaliperImp2 : Infinity;
732
+ if (Math.abs(effLng) > cap) effLng = Math.sign(effLng) * cap;
733
+ else if (Math.abs(excessAlongBrk) > 1e-9 && spareCapSum > 1e-9) {
734
+ const spare = cap - Math.abs(effLng);
735
+ const align = w.lngAxis.x * eBrkX + w.lngAxis.y * eBrkY + w.lngAxis.z * eBrkZ;
736
+ if (Math.abs(align) > .001) effLng = clamp(effLng + excessAlongBrk * (spare / spareCapSum) / align, -cap, cap);
737
+ }
738
+ (_w$stepWheelTireAndSp3 = w.stepWheelTireAndSpin) === null || _w$stepWheelTireAndSp3 === void 0 || _w$stepWheelTireAndSp3.call(w, effLng, effLat);
739
+ });
740
+ } else wheels.forEach((wheel) => {
741
+ var _wheel$current$stepWh2, _wheel$current2;
742
+ (_wheel$current$stepWh2 = (_wheel$current2 = wheel.current).stepWheelTireAndSpin) === null || _wheel$current$stepWh2 === void 0 || _wheel$current$stepWh2.call(_wheel$current2);
743
+ });
744
+ }
745
+ applyWheelImpulse(wheels, body);
746
+ }, [
747
+ applyWheelImpulse,
748
+ updateTransmission,
749
+ velocityBasedCarControl
750
+ ]);
751
+ /**
752
+ *
753
+ *
754
+ *
755
+ *
756
+ *
757
+ *
758
+ *
759
+ *
760
+ *
761
+ *
762
+ *
763
+ *
764
+ *
765
+ *
766
+ *
767
+ *
768
+ *
769
+ *
770
+ *
771
+ *
772
+ *
773
+ *
774
+ *
775
+ *
776
+ *
777
+ *
778
+ */
779
+ /**
780
+ * Drone overall control logics
781
+ */
782
+ const propellerPotential = useRef({
783
+ sumLX: 0,
784
+ sumLY: 0,
785
+ sumLZ: 0,
786
+ sumAX: 0,
787
+ sumAY: 0,
788
+ sumAZ: 0
789
+ });
790
+ const computePropellerPotential = useCallback((propellers) => {
791
+ let sumLX = 0, sumLY = 0, sumLZ = 0;
792
+ let sumAX = 0, sumAY = 0, sumAZ = 0;
793
+ propellers.forEach((p) => {
794
+ if (!p.current.enable) return;
795
+ sumLX += p.current.lx;
796
+ sumLY += p.current.ly;
797
+ sumLZ += p.current.lz;
798
+ sumAX += Math.abs(p.current.ax);
799
+ sumAY += Math.abs(p.current.ay);
800
+ sumAZ += Math.abs(p.current.az);
801
+ });
802
+ propellerPotential.current.sumLX = sumLX;
803
+ propellerPotential.current.sumLY = sumLY;
804
+ propellerPotential.current.sumLZ = sumLZ;
805
+ propellerPotential.current.sumAX = sumAX;
806
+ propellerPotential.current.sumAY = sumAY;
807
+ propellerPotential.current.sumAZ = sumAZ;
808
+ }, []);
809
+ const positionBasedDroneControl = useCallback((weight, sumWorldLY) => {
810
+ posError.current.subVectors(targetPosition.current, vehiclePos.current);
811
+ const vertPosErrorMag = posError.current.dot(upAxis.current);
812
+ horizPosError.current.copy(posError.current).projectOnPlane(upAxis.current);
813
+ const vertLinVelMag = vehicleLinVel.current.dot(upAxis.current);
814
+ horizLinVel.current.copy(vehicleLinVel.current).projectOnPlane(upAxis.current);
815
+ const vertForceMag = weight + clamp(vertPosErrorMag * droneControlConfig.VERT_POS_P, -droneControlConfig.VERT_POS_D * droneControlConfig.maxVertSpeed, droneControlConfig.VERT_POS_D * droneControlConfig.maxVertSpeed) - vertLinVelMag * droneControlConfig.VERT_POS_D;
816
+ desiredVertForce.current = Math.max(0, vertForceMag);
817
+ hoverThrottle.current = desiredVertForce.current / (sumWorldLY || 1);
818
+ horizForce.current.set(0, 0, 0).addScaledVector(horizPosError.current, droneControlConfig.HORIZ_POS_P).addScaledVector(horizLinVel.current, -droneControlConfig.HORIZ_POS_D).clampLength(0, droneControlConfig.HORIZ_POS_D * droneControlConfig.maxHorizSpeed);
819
+ targetUp.current.copy(upAxis.current).multiplyScalar(weight).add(horizForce.current.clampLength(0, weight * maxTiltTan)).normalize();
820
+ tiltError.current.crossVectors(vehicleYAxis.current, targetUp.current);
821
+ tiltAngVel.current.copy(vehicleAngVel.current).projectOnPlane(upAxis.current);
822
+ targetFwd.current.copy(targetHeading.current).projectOnPlane(upAxis.current).normalize();
823
+ currentFwd.current.copy(vehicleZAxis.current).projectOnPlane(upAxis.current).normalize();
824
+ const yawError = targetFwd.current.angleTo(currentFwd.current) * Math.sign(currentFwd.current.cross(targetFwd.current).dot(upAxis.current));
825
+ const currentYawRate = vehicleAngVel.current.dot(upAxis.current);
826
+ const yawRateError = clamp(yawError * droneControlConfig.YAW_POS_P, -droneControlConfig.maxYawRate, droneControlConfig.maxYawRate) - currentYawRate;
827
+ torqueWorld.current.set(0, 0, 0).addScaledVector(tiltError.current, droneControlConfig.TILT_P).addScaledVector(tiltAngVel.current, -droneControlConfig.TILT_D).addScaledVector(upAxis.current, yawRateError * droneControlConfig.YAW_VEL_P);
828
+ torqueBody.current.copy(torqueWorld.current).applyQuaternion(vehicleInvertQuat.current);
829
+ }, [droneControlConfig, maxTiltTan]);
830
+ const velocityBasedDroneControl = useCallback((input, body, weight, sumWorldLY) => {
831
+ var _input$joystickL$y, _input$joystickL2, _input$joystickL$x2, _input$joystickL3, _input$joystickR$y, _input$joystickR, _input$joystickR$x, _input$joystickR2;
832
+ const throttleIn = clamp((input.throttleUp ? 1 : 0) - (input.throttleDown ? 1 : 0) + ((_input$joystickL$y = (_input$joystickL2 = input.joystickL) === null || _input$joystickL2 === void 0 ? void 0 : _input$joystickL2.y) !== null && _input$joystickL$y !== void 0 ? _input$joystickL$y : 0), -1, 1);
833
+ const yawIn = clamp((input.yawLeft ? 1 : 0) - (input.yawRight ? 1 : 0) - ((_input$joystickL$x2 = (_input$joystickL3 = input.joystickL) === null || _input$joystickL3 === void 0 ? void 0 : _input$joystickL3.x) !== null && _input$joystickL$x2 !== void 0 ? _input$joystickL$x2 : 0), -1, 1);
834
+ const pitchIn = clamp((input.pitchForward ? 1 : 0) - (input.pitchBackward ? 1 : 0) + ((_input$joystickR$y = (_input$joystickR = input.joystickR) === null || _input$joystickR === void 0 ? void 0 : _input$joystickR.y) !== null && _input$joystickR$y !== void 0 ? _input$joystickR$y : 0), -1, 1);
835
+ const rollIn = clamp((input.rollRight ? 1 : 0) - (input.rollLeft ? 1 : 0) + ((_input$joystickR$x = (_input$joystickR2 = input.joystickR) === null || _input$joystickR2 === void 0 ? void 0 : _input$joystickR2.x) !== null && _input$joystickR$x !== void 0 ? _input$joystickR$x : 0), -1, 1);
836
+ worldXAxis.current.copy(vehicleXAxis.current).projectOnPlane(upAxis.current).normalize();
837
+ worldZAxis.current.copy(vehicleZAxis.current).projectOnPlane(upAxis.current).normalize();
838
+ targetLinVel.current.set(0, 0, 0).addScaledVector(worldXAxis.current, -rollIn * droneControlConfig.maxHorizSpeed).addScaledVector(worldZAxis.current, pitchIn * droneControlConfig.maxHorizSpeed).addScaledVector(upAxis.current, throttleIn * droneControlConfig.maxVertSpeed);
839
+ linVelError.current.subVectors(targetLinVel.current, vehicleLinVel.current);
840
+ vertAccCmd.current = clamp(linVelError.current.dot(upAxis.current) * droneControlConfig.VERT_VEL_P, -referenceGravityMag.current, referenceGravityMag.current);
841
+ horizAccCmd.current.copy(linVelError.current).projectOnPlane(upAxis.current).multiplyScalar(droneControlConfig.HORIZ_VEL_P).clampLength(0, referenceGravityMag.current * maxTiltTan);
842
+ const verticalForceMag = weight + vertAccCmd.current * body.mass();
843
+ desiredVertForce.current = Math.max(0, verticalForceMag);
844
+ hoverThrottle.current = desiredVertForce.current / (sumWorldLY || 1);
845
+ targetUp.current.copy(upAxis.current).multiplyScalar(referenceGravityMag.current).add(horizAccCmd.current).normalize();
846
+ tiltError.current.crossVectors(vehicleYAxis.current, targetUp.current);
847
+ tiltAngVel.current.copy(vehicleAngVel.current).projectOnPlane(upAxis.current);
848
+ const currentYawRate = vehicleAngVel.current.dot(upAxis.current);
849
+ const yawRateError = yawIn * droneControlConfig.maxYawRate - currentYawRate;
850
+ torqueWorld.current.set(0, 0, 0).addScaledVector(tiltError.current, droneControlConfig.TILT_P).addScaledVector(tiltAngVel.current, -droneControlConfig.TILT_D).addScaledVector(upAxis.current, yawRateError * droneControlConfig.YAW_VEL_P);
851
+ torqueBody.current.copy(torqueWorld.current).applyQuaternion(vehicleInvertQuat.current);
852
+ }, [droneControlConfig, maxTiltTan]);
853
+ const solveDroneWrenchLambda = useCallback((propellers, body, ux, uy, uz) => {
854
+ const G = gramMatrix.current;
855
+ G.fill(0);
856
+ let sumAX = 0, sumAY = 0, sumAZ = 0;
857
+ let sumAX2 = 0, sumAY2 = 0, sumAZ2 = 0;
858
+ for (const propeller of propellers.values()) {
859
+ const info = propeller.current;
860
+ if (!info.enable) continue;
861
+ const fUp = info.lx * ux + info.ly * uy + info.lz * uz;
862
+ const ax = info.ax;
863
+ const ay = info.ay;
864
+ const az = info.az;
865
+ sumAX += Math.abs(ax);
866
+ sumAY += Math.abs(ay);
867
+ sumAZ += Math.abs(az);
868
+ sumAX2 += ax * ax;
869
+ sumAY2 += ay * ay;
870
+ sumAZ2 += az * az;
871
+ G[0] += fUp * fUp;
872
+ G[1] += fUp * ax;
873
+ G[2] += fUp * ay;
874
+ G[3] += fUp * az;
875
+ G[4] += ax * fUp;
876
+ G[5] += ax * ax;
877
+ G[6] += ax * ay;
878
+ G[7] += ax * az;
879
+ G[8] += ay * fUp;
880
+ G[9] += ay * ax;
881
+ G[10] += ay * ay;
882
+ G[11] += ay * az;
883
+ G[12] += az * fUp;
884
+ G[13] += az * ax;
885
+ G[14] += az * ay;
886
+ G[15] += az * az;
887
+ }
888
+ const trace = G[0] + G[5] + G[10] + G[15];
889
+ if (trace <= 1e-12) {
890
+ wrenchLambda.current.fill(0);
891
+ return;
892
+ }
893
+ const eps = Math.max(1e-9, trace * 1e-9);
894
+ G[0] += eps;
895
+ G[5] += eps;
896
+ G[10] += eps;
897
+ G[15] += eps;
898
+ let sx = sumAX > 1e-9 ? sumAX2 / sumAX : 0;
899
+ let sy = sumAY > 1e-9 ? sumAY2 / sumAY : 0;
900
+ let sz = sumAZ > 1e-9 ? sumAZ2 / sumAZ : 0;
901
+ const dt = world.timestep;
902
+ if (dt > 0) {
903
+ const invI = body.effectiveWorldInvInertia();
904
+ const invITrace = invI.m11 + invI.m22 + invI.m33;
905
+ if (invITrace > 1e-9) {
906
+ const tiltDamp = Math.max(droneControlConfig.TILT_D, .001);
907
+ const yawDamp = Math.max(droneControlConfig.YAW_VEL_P, .001);
908
+ const maxTiltScale = .8 / (invITrace * tiltDamp * dt);
909
+ const maxYawScale = .8 / (invITrace * yawDamp * dt);
910
+ sx = Math.min(sx, maxTiltScale);
911
+ sy = Math.min(sy, maxYawScale);
912
+ sz = Math.min(sz, maxTiltScale);
913
+ }
914
+ }
915
+ const b = wrenchRhs.current;
916
+ b[0] = desiredVertForce.current;
917
+ b[1] = torqueBody.current.x * sx;
918
+ b[2] = torqueBody.current.y * sy;
919
+ b[3] = torqueBody.current.z * sz;
920
+ solve4x4(G, b, wrenchAug.current, wrenchLambda.current);
921
+ }, [
922
+ droneControlConfig.TILT_D,
923
+ droneControlConfig.YAW_VEL_P,
924
+ world
925
+ ]);
926
+ const computePropellerFinalThrottle = useCallback((propeller, ux, uy, uz) => {
927
+ if (!propeller.enable) return 0;
928
+ const fUp = propeller.lx * ux + propeller.ly * uy + propeller.lz * uz;
929
+ const lam = wrenchLambda.current;
930
+ return clamp(fUp * lam[0] + propeller.ax * lam[1] + propeller.ay * lam[2] + propeller.az * lam[3], 0, 1);
931
+ }, []);
932
+ const applyMixerImpulse = useCallback((propellers, body) => {
933
+ const ux = vehicleXAxis.current.dot(upAxis.current);
934
+ const uy = vehicleYAxis.current.dot(upAxis.current);
935
+ const uz = vehicleZAxis.current.dot(upAxis.current);
936
+ solveDroneWrenchLambda(propellers, body, ux, uy, uz);
937
+ if (body.isSleeping()) {
938
+ let shouldWake = false;
939
+ for (const propeller of propellers.values()) {
940
+ const info = propeller.current;
941
+ const finalThrottle = computePropellerFinalThrottle(info, ux, uy, uz);
942
+ if (Math.abs(finalThrottle - info.throttle) > 1e-4) {
943
+ shouldWake = true;
944
+ break;
945
+ }
946
+ }
947
+ if (!shouldWake) return;
948
+ body.wakeUp();
949
+ }
950
+ propellers.forEach((propeller) => {
951
+ const info = propeller.current;
952
+ if (!info.enable) {
953
+ info.finalThrottle = 0;
954
+ if (info.setThrottle) info.setThrottle(0);
955
+ info.thrustImpulse.set(0, 0, 0);
956
+ info.torqueImpulse.set(0, 0, 0);
957
+ return;
958
+ }
959
+ const finalThrottle = computePropellerFinalThrottle(info, ux, uy, uz);
960
+ info.finalThrottle = finalThrottle;
961
+ if (info.setThrottle) info.setThrottle(finalThrottle);
962
+ worldThrustDir.current.copy(info.thrustDir).applyQuaternion(vehicleQuat.current).normalize();
963
+ worldThrustPos.current.copy(info.thrustPos).applyQuaternion(vehicleQuat.current).add(vehiclePos.current);
964
+ worldTorqueDir.current.copy(info.torqueDir).applyQuaternion(vehicleQuat.current).normalize();
965
+ info.worldThrustDir.copy(worldThrustDir.current);
966
+ info.worldThrustPos.copy(worldThrustPos.current);
967
+ info.worldTorqueDir.copy(worldTorqueDir.current);
968
+ info.thrustImpulse.copy(worldThrustDir.current).multiplyScalar(info.maxThrust * finalThrottle * world.timestep);
969
+ info.torqueImpulse.copy(worldTorqueDir.current).multiplyScalar(info.maxThrust * finalThrottle * world.timestep * info.torqueRatio);
970
+ body.applyImpulseAtPoint(info.thrustImpulse, info.worldThrustPos, false);
971
+ body.applyTorqueImpulse(info.torqueImpulse, false);
972
+ });
973
+ }, [computePropellerFinalThrottle, solveDroneWrenchLambda]);
974
+ const applyAirDrag = useCallback((body) => {
975
+ airDragImpulse.current.copy(vehicleLinVel.current).multiplyScalar(-droneControlConfig.airDragFactor * world.timestep);
976
+ body.applyImpulse(airDragImpulse.current, false);
977
+ }, [droneControlConfig.airDragFactor, world.timestep]);
978
+ const applyDroneControl = useCallback((propellers, body, input) => {
979
+ if (!body) return;
980
+ propellers.forEach((propeller) => {
981
+ var _propeller$current$st, _propeller$current;
982
+ (_propeller$current$st = (_propeller$current = propeller.current).stepPropellerPhysics) === null || _propeller$current$st === void 0 || _propeller$current$st.call(_propeller$current);
983
+ });
984
+ computePropellerPotential(propellers);
985
+ const sumWorldLY = propellerPotential.current.sumLX * vehicleXAxis.current.dot(upAxis.current) + propellerPotential.current.sumLY * vehicleYAxis.current.dot(upAxis.current) + propellerPotential.current.sumLZ * vehicleZAxis.current.dot(upAxis.current);
986
+ const weight = body.mass() * referenceGravityMag.current;
987
+ switch (droneControlConfig.controlMode) {
988
+ case "POSITION":
989
+ positionBasedDroneControl(weight, sumWorldLY);
990
+ break;
991
+ case "VELOCITY":
992
+ velocityBasedDroneControl(input, body, weight, sumWorldLY);
993
+ break;
994
+ }
995
+ applyMixerImpulse(propellers, body);
996
+ applyAirDrag(body);
997
+ }, [
998
+ computePropellerPotential,
999
+ positionBasedDroneControl,
1000
+ velocityBasedDroneControl,
1001
+ droneControlConfig.controlMode,
1002
+ applyMixerImpulse,
1003
+ applyAirDrag
1004
+ ]);
1005
+ /**
1006
+ *
1007
+ *
1008
+ *
1009
+ *
1010
+ *
1011
+ *
1012
+ *
1013
+ *
1014
+ *
1015
+ *
1016
+ *
1017
+ *
1018
+ *
1019
+ *
1020
+ *
1021
+ *
1022
+ *
1023
+ *
1024
+ *
1025
+ */
1026
+ useBeforePhysicsStep(() => {
1027
+ if (!enable || !vehicleRef.current) return;
1028
+ updateVehicleInfo(vehicleRef.current);
1029
+ updateGravityInfo();
1030
+ /**
1031
+ * Apply drive/brake/friction impulse from shape cast wheels
1032
+ * whenever there is a wheel component
1033
+ */
1034
+ if (wheelsInfo.current.size > 0) applyCarControl(wheelsInfo.current, vehicleRef.current, movementState.current);
1035
+ /**
1036
+ * Apply drone control logics
1037
+ * whenever there is a propeller component
1038
+ */
1039
+ if (propellersInfo.current.size > 0) applyDroneControl(propellersInfo.current, vehicleRef.current, movementState.current);
1040
+ /**
1041
+ * Apply custom gravity impulse after wheels and propellers sample pre-step velocity so custom gravity
1042
+ * neither biases suspension damping nor gets skipped on the step a sleeping body wakes up
1043
+ */
1044
+ if (enableCustomGravity && !vehicleRef.current.isSleeping()) applyGravityField(vehicleRef.current, world.timestep);
1045
+ });
1046
+ /**
1047
+ *
1048
+ *
1049
+ *
1050
+ *
1051
+ *
1052
+ *
1053
+ *
1054
+ *
1055
+ *
1056
+ *
1057
+ *
1058
+ *
1059
+ */
1060
+ const vehicleContextValue = useMemo(() => ({
1061
+ body: vehicleRef,
1062
+ enableCustomGravity,
1063
+ referenceGravity,
1064
+ upAxis,
1065
+ gravityDir,
1066
+ gravityMag: referenceGravityMag,
1067
+ currPos: vehiclePos,
1068
+ currQuat: vehicleQuat,
1069
+ currLinvel: vehicleLinVel,
1070
+ currAngvel: vehicleAngVel,
1071
+ bodyXAxis: vehicleXAxis,
1072
+ bodyYAxis: vehicleYAxis,
1073
+ bodyZAxis: vehicleZAxis,
1074
+ movementState,
1075
+ wheelsInfo,
1076
+ propellersInfo,
1077
+ regWheel,
1078
+ unregWheel,
1079
+ regPropeller,
1080
+ unregPropeller
1081
+ }), [
1082
+ enableCustomGravity,
1083
+ regWheel,
1084
+ unregWheel,
1085
+ regPropeller,
1086
+ unregPropeller
1087
+ ]);
1088
+ return /* @__PURE__ */ React.createElement(VehicleContext.Provider, { value: vehicleContextValue }, /* @__PURE__ */ React.createElement(RigidBody, {
1089
+ colliders: false,
1090
+ ref: vehicleRef,
1091
+ ...props
1092
+ }, children));
1093
+ });
1094
+ var EcctrlVehicle_default = React.memo(EcctrlVehicle);
1095
+ //#endregion
1096
+ //#region src/vehicles/components/ShapeCastWheel.tsx
1097
+ /*!
1098
+ * Ecctrl
1099
+ * https://github.com/pmndrs/ecctrl
1100
+ *
1101
+ * SPDX-FileCopyrightText: 2023-2026 Erdong Chen
1102
+ * SPDX-License-Identifier: MIT
1103
+ */
1104
+ var ShapeCastWheel = /* @__PURE__ */ forwardRef(({ children, debug = false, enable = true, name = "", groundDetection = "shapeCast", rayShapeR = .5, rayShapeH = .15, rayLength = .5, springK = 180, dampingC = 16, driveInvert = false, driveWheel = false, driveTorqueWeight = 1, steerInvert = false, steerWheel = false, brakeWheel = false, maxBrakeTorque = 40, rollingResistanceCoef = .007, lowVelThreshold = .4, tireGripFactor = 1.5, lngFrictionEllipseScale = 1, latFrictionEllipseScale = 1, relaxLngRate = .05, relaxLatRate = .1, minLngRelaxCoeff = .3, minLatRelaxCoeff = .3, lngSlipRatioCurveData = { points: [
1105
+ {
1106
+ x: 0,
1107
+ y: 0,
1108
+ r_out: 1.45
1109
+ },
1110
+ {
1111
+ x: .25,
1112
+ y: 1,
1113
+ r_in: 0,
1114
+ r_out: 0
1115
+ },
1116
+ {
1117
+ x: 1,
1118
+ y: .7,
1119
+ r_in: 0
1120
+ }
1121
+ ] }, latSlipRatioCurveData = { points: [
1122
+ {
1123
+ x: 0,
1124
+ y: 0,
1125
+ r_out: 1.45
1126
+ },
1127
+ {
1128
+ x: .15,
1129
+ y: 1,
1130
+ r_in: 0,
1131
+ r_out: 0
1132
+ },
1133
+ {
1134
+ x: 1,
1135
+ y: .9,
1136
+ r_in: 0
1137
+ }
1138
+ ] }, followPlatform = true, massRatioFallOffCurveData = { points: [
1139
+ {
1140
+ x: 0,
1141
+ y: .5,
1142
+ r_out: 0
1143
+ },
1144
+ {
1145
+ x: .5,
1146
+ y: 1,
1147
+ r_out: 0
1148
+ },
1149
+ {
1150
+ x: 1,
1151
+ y: 1,
1152
+ r_in: 0
1153
+ }
1154
+ ] }, applyCounterMass = true, applyCounterFriction = true, showWheelModel = true, wheelModelDensity = 1.5, wheelModelUpdate = true, wheelModelRadius = .5, wheelModelLerpPosRate = 10, wheelModelReversRotation = false, debuggerArrowScale = 10, ...props }, ref) => {
1155
+ /**
1156
+ * Rapier preset
1157
+ */
1158
+ const { rapier, world, rigidBodyStates } = useRapier();
1159
+ /**
1160
+ * Retrieve context object from ecctrl vehicle
1161
+ */
1162
+ const vehicleValue = useContext(VehicleContext);
1163
+ const fixedScale = useMemo(() => new THREE.Vector3(1, 1, 1), []);
1164
+ useMemo(() => new THREE.Vector3(0, 0, 0), []);
1165
+ useMemo(() => new THREE.Vector3(1, 0, 0), []);
1166
+ const fixedYAxis = useMemo(() => new THREE.Vector3(0, 1, 0), []);
1167
+ const fixedZAxis = useMemo(() => new THREE.Vector3(0, 0, 1), []);
1168
+ const vehiclePos = useRef(new THREE.Vector3());
1169
+ const vehicleCom = useRef(new THREE.Vector3());
1170
+ const vehicleQuat = useRef(new THREE.Quaternion());
1171
+ const vehicleInvertQuat = useRef(new THREE.Quaternion());
1172
+ const vehicleMatrix = useRef(new THREE.Matrix4());
1173
+ const vehicleInvertMatrix = useRef(new THREE.Matrix4());
1174
+ const vehicleLinVel = useRef(new THREE.Vector3());
1175
+ const vehicleAngVel = useRef(new THREE.Vector3());
1176
+ const vehicleXAxis = useRef(new THREE.Vector3());
1177
+ const vehicleYAxis = useRef(new THREE.Vector3());
1178
+ const vehicleZAxis = useRef(new THREE.Vector3());
1179
+ /**
1180
+ * Wheel physical properties and states
1181
+ */
1182
+ const effectiveInertia = useRef(0);
1183
+ const wheelAngVel = useRef(0);
1184
+ const supportPoint = useRef(new THREE.Vector3());
1185
+ const wheelVolume = useMemo(() => Math.PI * rayShapeR * rayShapeR * (rayShapeH * 2), [rayShapeR, rayShapeH]);
1186
+ const wheelMass = useMemo(() => wheelModelDensity * wheelVolume, [wheelModelDensity, wheelVolume]);
1187
+ const wheelInertia = useMemo(() => .5 * wheelMass * rayShapeR * rayShapeR, [wheelMass, rayShapeR]);
1188
+ /**
1189
+ * Control preset
1190
+ */
1191
+ const frictionCoef = useRef(0);
1192
+ const lngAxis = useRef(new THREE.Vector3());
1193
+ const latAxis = useRef(new THREE.Vector3());
1194
+ const lngFrictionImp = useRef(new THREE.Vector3());
1195
+ const latFrictionImp = useRef(new THREE.Vector3());
1196
+ const lngSlipRatioCurve = useMemo(() => {
1197
+ var _lngSlipRatioCurveDat;
1198
+ return bakeCurveLUT(lngSlipRatioCurveData.points, (_lngSlipRatioCurveDat = lngSlipRatioCurveData.samples) !== null && _lngSlipRatioCurveDat !== void 0 ? _lngSlipRatioCurveDat : 50);
1199
+ }, [lngSlipRatioCurveData]);
1200
+ const latSlipRatioCurve = useMemo(() => {
1201
+ var _latSlipRatioCurveDat;
1202
+ return bakeCurveLUT(latSlipRatioCurveData.points, (_latSlipRatioCurveDat = latSlipRatioCurveData.samples) !== null && _latSlipRatioCurveDat !== void 0 ? _latSlipRatioCurveDat : 50);
1203
+ }, [latSlipRatioCurveData]);
1204
+ const lngSlipRatio = useRef(0);
1205
+ const latSlipRatio = useRef(0);
1206
+ const slipStrength = useRef(0);
1207
+ const smoothedLngImpulse = useRef(0);
1208
+ const smoothedLatImpulse = useRef(0);
1209
+ const desiredLngImpulse = useRef(0);
1210
+ const desiredLatImpulse = useRef(0);
1211
+ const defaultLngSlopeGravImp = useRef(0);
1212
+ const defaultLatSlopeGravImp = useRef(0);
1213
+ const slopeGravImpVec = useRef(new THREE.Vector3());
1214
+ const baseLocalQuat = useRef(new THREE.Quaternion());
1215
+ const baseLocalQuatCaptured = useRef(false);
1216
+ const steerQuat = useRef(new THREE.Quaternion());
1217
+ const steerAngle = useRef(0);
1218
+ const steerTarget = useRef(0);
1219
+ const steerIncrement = useRef(0);
1220
+ const steerDemand = useRef(0);
1221
+ const steerWheelConfig = useRef(null);
1222
+ const setSteerDemand = useCallback((value) => steerDemand.current = value, []);
1223
+ const setSteerWheelConfig = useCallback((value) => steerWheelConfig.current = value, []);
1224
+ const driveTorque = useRef(0);
1225
+ const driveDemand = useRef(0);
1226
+ const driveWheelConfig = useRef(null);
1227
+ const setDriveDemand = useCallback((value) => driveDemand.current = value, []);
1228
+ const setDriveWheelConfig = useCallback((value) => driveWheelConfig.current = value, []);
1229
+ const brakeTorque = useRef(0);
1230
+ const brakeDemand = useRef(0);
1231
+ const setBrakeDemand = useCallback((value) => brakeDemand.current = value, []);
1232
+ /**
1233
+ * Shape cast preset
1234
+ */
1235
+ const distFromRayOriginToVehicle = useRef(new THREE.Vector3());
1236
+ const angvelToLinvel = useRef(new THREE.Vector3());
1237
+ const floatingImpulse = useRef(new THREE.Vector3());
1238
+ const rayOrigin = useRef(new THREE.Vector3());
1239
+ const rayRotation = useRef(new THREE.Quaternion());
1240
+ const rayDirection = useRef(new THREE.Vector3());
1241
+ const rayOriginVel = useRef(new THREE.Vector3());
1242
+ const rayUpAxis = useRef(new THREE.Vector3());
1243
+ const rayFWDAxis = useRef(new THREE.Vector3());
1244
+ const rayBWDAxis = useRef(new THREE.Vector3());
1245
+ const rayLeftAxis = useRef(new THREE.Vector3());
1246
+ const rayShape = useMemo(() => new rapier.Cylinder(rayShapeH, rayShapeR), [rayShapeH, rayShapeR]);
1247
+ const rotZ90 = useMemo(() => new THREE.Quaternion().setFromAxisAngle(fixedZAxis, Math.PI / 2), []);
1248
+ const shapeRayHit = useRef(null);
1249
+ const rayHit = useRef(null);
1250
+ const rayCast = useMemo(() => new rapier.Ray(rayOrigin.current, rayDirection.current), [rapier]);
1251
+ const suspensionToi = useRef(0);
1252
+ const rayHitBody = useRef(null);
1253
+ const rayShapeCenter = useRef(new THREE.Vector3());
1254
+ const stableRayHitPoint = useRef(new THREE.Vector3());
1255
+ const targetRayHitPoint = useRef(new THREE.Vector3());
1256
+ const rayHitPointOffset = useRef(new THREE.Vector3());
1257
+ const rayHitPointPosition = useRef(new THREE.Vector3());
1258
+ const rayHitPointVelocity = useRef(new THREE.Vector3());
1259
+ const supportPointVelocity = useRef(new THREE.Vector3());
1260
+ const rayHitPointVelOnPlane = useRef(new THREE.Vector3());
1261
+ const rayHitPointNormal = useRef(new THREE.Vector3());
1262
+ const rayHitPointFriction = useRef(0);
1263
+ useEffect(() => {
1264
+ if (groundDetection === "rayCast") shapeRayHit.current = null;
1265
+ else rayHit.current = null;
1266
+ }, [groundDetection]);
1267
+ /**
1268
+ * Moving platform preset
1269
+ */
1270
+ const massRatio = useRef(1);
1271
+ const isOnMovingObject = useRef(false);
1272
+ const wheelSupportForceMag = useRef(0);
1273
+ const wheelSupportImpulse = useRef(new THREE.Vector3());
1274
+ const wheelFrictionImpulse = useRef(new THREE.Vector3());
1275
+ const movingObjectPosition = useRef(new THREE.Vector3());
1276
+ const movingObjectVelocity = useRef(new THREE.Vector3());
1277
+ const movingObjectVelocityOnPlane = useRef(new THREE.Vector3());
1278
+ const movingObjectLinearVelocity = useRef(new THREE.Vector3());
1279
+ const movingObjectAngularVelocity = useRef(new THREE.Vector3());
1280
+ const distanceFromOriginToObjectPoint = useRef(new THREE.Vector3());
1281
+ const movingObjectAngvelToLinvel = useRef(new THREE.Vector3());
1282
+ const massRatioFallOffCurve = useMemo(() => {
1283
+ var _massRatioFallOffCurv;
1284
+ return bakeCurveLUT(massRatioFallOffCurveData.points, (_massRatioFallOffCurv = massRatioFallOffCurveData.samples) !== null && _massRatioFallOffCurv !== void 0 ? _massRatioFallOffCurv : 50);
1285
+ }, [massRatioFallOffCurveData]);
1286
+ /**
1287
+ * Wheel ref preset and handles
1288
+ */
1289
+ const shapeCastWheelRef = useRef(null);
1290
+ const modelRef = useRef(null);
1291
+ const wheelRef = useRef(null);
1292
+ const localPos = useRef(new THREE.Vector3());
1293
+ const localQuat = useRef(new THREE.Quaternion());
1294
+ const worldPos = useRef(new THREE.Vector3());
1295
+ const worldQuat = useRef(new THREE.Quaternion());
1296
+ useImperativeHandle(ref, () => shapeCastWheelRef.current, []);
1297
+ useLayoutEffect(() => {
1298
+ if (!shapeCastWheelRef.current) return;
1299
+ baseLocalQuat.current.copy(shapeCastWheelRef.current.quaternion);
1300
+ baseLocalQuatCaptured.current = true;
1301
+ }, [props.rotation, props.quaternion]);
1302
+ /**
1303
+ * Register wheel information
1304
+ */
1305
+ const wheelId = useMemo(() => {
1306
+ var _props$id;
1307
+ return String((_props$id = props.id) !== null && _props$id !== void 0 ? _props$id : generateUUID());
1308
+ }, [props.id]);
1309
+ const wheelInfo = useRef({
1310
+ id: wheelId,
1311
+ name,
1312
+ enable,
1313
+ debug,
1314
+ rayShapeR,
1315
+ rayShapeH,
1316
+ rayLength,
1317
+ springK,
1318
+ dampingC,
1319
+ steerInvert,
1320
+ steerWheel,
1321
+ driveInvert,
1322
+ driveWheel,
1323
+ driveTorqueWeight,
1324
+ brakeWheel,
1325
+ maxBrakeTorque,
1326
+ rollingResistanceCoef,
1327
+ lowVelThreshold,
1328
+ tireGripFactor,
1329
+ lngFrictionEllipseScale,
1330
+ latFrictionEllipseScale,
1331
+ relaxLngRate,
1332
+ relaxLatRate,
1333
+ minLngRelaxCoeff,
1334
+ minLatRelaxCoeff,
1335
+ followPlatform,
1336
+ applyCounterMass,
1337
+ applyCounterFriction,
1338
+ showWheelModel,
1339
+ wheelModelDensity,
1340
+ wheelModelUpdate,
1341
+ wheelModelRadius,
1342
+ wheelModelLerpPosRate,
1343
+ wheelModelReversRotation,
1344
+ debuggerArrowScale,
1345
+ rayPos: new THREE.Vector3(),
1346
+ rayDir: new THREE.Vector3(),
1347
+ rayRot: new THREE.Quaternion(),
1348
+ rayUpDir: new THREE.Vector3(),
1349
+ rayFwdDir: new THREE.Vector3(),
1350
+ rayLeftDir: new THREE.Vector3(),
1351
+ floatImp: new THREE.Vector3(),
1352
+ rayHit: null,
1353
+ rayHitBody: null,
1354
+ rayHitPos: new THREE.Vector3(),
1355
+ rayHitNormal: new THREE.Vector3(),
1356
+ rayHitFriciton: 0,
1357
+ rayOriginVel: new THREE.Vector3(),
1358
+ rayHitPointVel: new THREE.Vector3(),
1359
+ isOnPlatform: false,
1360
+ lngSlipRatio: 0,
1361
+ latSlipRatio: 0,
1362
+ slipStrength: 0,
1363
+ lngAxis: new THREE.Vector3(),
1364
+ latAxis: new THREE.Vector3(),
1365
+ lngFricImp: new THREE.Vector3(),
1366
+ latFricImp: new THREE.Vector3(),
1367
+ supportForceMag: 0,
1368
+ maxCaliperImp: 0,
1369
+ slopeGravImp: new THREE.Vector3(),
1370
+ isActivelyBraking: false,
1371
+ effInertia: 0,
1372
+ supPos: new THREE.Vector3(),
1373
+ steerAngle: 0,
1374
+ driveTorque: 0,
1375
+ brakeTorque: 0,
1376
+ wheelLinVel: 0,
1377
+ wheelAngVel: 0,
1378
+ setDriveDemand,
1379
+ setBrakeDemand,
1380
+ setSteerDemand,
1381
+ setDriveWheelConfig,
1382
+ setSteerWheelConfig
1383
+ });
1384
+ wheelInfo.current.enable = enable;
1385
+ wheelInfo.current.driveWheel = driveWheel;
1386
+ wheelInfo.current.driveTorqueWeight = driveTorqueWeight;
1387
+ wheelInfo.current.steerWheel = steerWheel;
1388
+ wheelInfo.current.brakeWheel = brakeWheel;
1389
+ wheelInfo.current.maxBrakeTorque = maxBrakeTorque;
1390
+ /**
1391
+ * Register the wheel to vehicle on mount, and unregister on unmount
1392
+ */
1393
+ useEffect(() => {
1394
+ vehicleValue === null || vehicleValue === void 0 || vehicleValue.regWheel(wheelInfo);
1395
+ return () => vehicleValue === null || vehicleValue === void 0 ? void 0 : vehicleValue.unregWheel(wheelId);
1396
+ }, [
1397
+ vehicleValue,
1398
+ wheelId,
1399
+ driveWheel,
1400
+ driveTorqueWeight,
1401
+ steerWheel
1402
+ ]);
1403
+ /**
1404
+ * Debug indicators preset
1405
+ */
1406
+ const forwardIndicatorRef = useRef(null);
1407
+ const rayHitPointRef = useRef(null);
1408
+ const xAxisPointRef = useRef(null);
1409
+ const yAxisPointRef = useRef(null);
1410
+ const zAxisPointRef = useRef(null);
1411
+ const currFloatArrowRef = useRef(null);
1412
+ const currFloatArrowDir = useRef(new THREE.Vector3());
1413
+ const currDriftArrowRef = useRef(null);
1414
+ const currDriftArrowDir = useRef(new THREE.Vector3());
1415
+ const currEngineArrowRef = useRef(null);
1416
+ const currEngineArrowDir = useRef(new THREE.Vector3());
1417
+ const debugAssets = useMemo(() => {
1418
+ if (!debug) return null;
1419
+ return {
1420
+ forwardRingGeo: new THREE.RingGeometry(rayShapeH * 1.6, rayShapeH * 2, 12),
1421
+ forwardPointerGeo: new THREE.PlaneGeometry(rayShapeH, rayShapeH),
1422
+ forwardIndicatorMat: new THREE.MeshBasicMaterial({
1423
+ color: EC_AZURE,
1424
+ side: THREE.DoubleSide
1425
+ }),
1426
+ rayCastGeo: new THREE.CircleGeometry(rayShapeH * .5, 12),
1427
+ rayCastHalfGeo: new THREE.CylinderGeometry(rayShapeR, rayShapeR, rayShapeH * 2, 12, 1, true, 0, -Math.PI),
1428
+ rayCastMat: new THREE.MeshBasicMaterial({
1429
+ color: EC_MED_PURPLE,
1430
+ side: THREE.DoubleSide,
1431
+ transparent: true,
1432
+ opacity: .5
1433
+ }),
1434
+ standingGeo: new THREE.OctahedronGeometry(rayShapeH * .5, 3),
1435
+ standingMat: new THREE.MeshBasicMaterial({
1436
+ color: EC_PURPLE,
1437
+ transparent: true,
1438
+ opacity: .5
1439
+ }),
1440
+ xAxisPointMat: new THREE.MeshBasicMaterial({
1441
+ color: EC_GREEN,
1442
+ transparent: true,
1443
+ opacity: 1
1444
+ }),
1445
+ yAxisPointMat: new THREE.MeshBasicMaterial({
1446
+ color: EC_BLUE,
1447
+ transparent: true,
1448
+ opacity: 1
1449
+ }),
1450
+ zAxisPointMat: new THREE.MeshBasicMaterial({
1451
+ color: EC_RED,
1452
+ transparent: true,
1453
+ opacity: 1
1454
+ })
1455
+ };
1456
+ }, [
1457
+ debug,
1458
+ rayShapeR,
1459
+ rayShapeH
1460
+ ]);
1461
+ useEffect(() => {
1462
+ return () => {
1463
+ if (!debugAssets) return;
1464
+ for (const key in debugAssets) {
1465
+ const item = debugAssets[key];
1466
+ if ("dispose" in item && typeof item.dispose === "function") item.dispose();
1467
+ }
1468
+ };
1469
+ }, [debugAssets]);
1470
+ /**
1471
+ *
1472
+ *
1473
+ *
1474
+ *
1475
+ *
1476
+ *
1477
+ *
1478
+ *
1479
+ *
1480
+ *
1481
+ *
1482
+ *
1483
+ *
1484
+ *
1485
+ *
1486
+ *
1487
+ *
1488
+ *
1489
+ *
1490
+ *
1491
+ *
1492
+ *
1493
+ *
1494
+ *
1495
+ *
1496
+ *
1497
+ *
1498
+ *
1499
+ *
1500
+ */
1501
+ /**
1502
+ * Update vehicle/wheel info function
1503
+ * (needs to recompute vehicle's info for each wheel, to gain the most updated info)
1504
+ */
1505
+ const syncWheelInfo = useCallback(() => {
1506
+ wheelInfo.current.rayPos = rayOrigin.current;
1507
+ wheelInfo.current.rayDir = rayDirection.current;
1508
+ wheelInfo.current.rayRot = rayRotation.current;
1509
+ wheelInfo.current.rayUpDir = rayUpAxis.current;
1510
+ wheelInfo.current.rayFwdDir = rayFWDAxis.current;
1511
+ wheelInfo.current.rayLeftDir = rayLeftAxis.current;
1512
+ wheelInfo.current.rayHit = groundDetection === "rayCast" ? rayHit.current : shapeRayHit.current;
1513
+ wheelInfo.current.rayHitBody = rayHitBody.current;
1514
+ wheelInfo.current.rayHitPos = rayHitPointPosition.current;
1515
+ wheelInfo.current.rayHitNormal = rayHitPointNormal.current;
1516
+ wheelInfo.current.rayHitFriciton = rayHitPointFriction.current;
1517
+ wheelInfo.current.rayOriginVel = rayOriginVel.current;
1518
+ wheelInfo.current.rayHitPointVel = rayHitPointVelocity.current;
1519
+ wheelInfo.current.isOnPlatform = isOnMovingObject.current;
1520
+ wheelInfo.current.floatImp = floatingImpulse.current;
1521
+ wheelInfo.current.lngSlipRatio = lngSlipRatio.current;
1522
+ wheelInfo.current.latSlipRatio = latSlipRatio.current;
1523
+ wheelInfo.current.slipStrength = slipStrength.current;
1524
+ wheelInfo.current.lngAxis = lngAxis.current;
1525
+ wheelInfo.current.latAxis = latAxis.current;
1526
+ wheelInfo.current.lngFricImp = lngFrictionImp.current;
1527
+ wheelInfo.current.latFricImp = latFrictionImp.current;
1528
+ wheelInfo.current.effInertia = effectiveInertia.current;
1529
+ wheelInfo.current.supPos = supportPoint.current;
1530
+ wheelInfo.current.steerAngle = steerAngle.current;
1531
+ wheelInfo.current.driveTorque = driveTorque.current;
1532
+ wheelInfo.current.brakeTorque = brakeTorque.current;
1533
+ wheelInfo.current.wheelAngVel = wheelAngVel.current;
1534
+ wheelInfo.current.wheelLinVel = wheelAngVel.current * rayShapeR;
1535
+ }, [groundDetection, rayShapeR]);
1536
+ const updateVehicleInfo = useCallback((body) => {
1537
+ vehiclePos.current.copy(body.translation());
1538
+ vehicleCom.current.copy(body.worldCom());
1539
+ vehicleQuat.current.copy(body.rotation());
1540
+ vehicleMatrix.current.compose(vehiclePos.current, vehicleQuat.current, fixedScale);
1541
+ vehicleYAxis.current.set(0, 1, 0).applyQuaternion(vehicleQuat.current);
1542
+ vehicleXAxis.current.set(1, 0, 0).applyQuaternion(vehicleQuat.current);
1543
+ vehicleZAxis.current.set(0, 0, 1).applyQuaternion(vehicleQuat.current);
1544
+ vehicleLinVel.current.copy(body.linvel());
1545
+ vehicleAngVel.current.copy(body.angvel());
1546
+ }, [fixedScale]);
1547
+ /**
1548
+ * Compute ray hit point and support point relative velocities
1549
+ */
1550
+ const computeRelativeVelocity = useCallback(() => {
1551
+ if (rayHitBody.current) {
1552
+ distFromRayOriginToVehicle.current.copy(rayHitPointPosition.current).sub(vehicleCom.current);
1553
+ angvelToLinvel.current.crossVectors(vehicleAngVel.current, distFromRayOriginToVehicle.current);
1554
+ rayHitPointVelocity.current.copy(vehicleLinVel.current).add(angvelToLinvel.current);
1555
+ distFromRayOriginToVehicle.current.copy(supportPoint.current).sub(vehicleCom.current);
1556
+ angvelToLinvel.current.crossVectors(vehicleAngVel.current, distFromRayOriginToVehicle.current);
1557
+ supportPointVelocity.current.copy(vehicleLinVel.current).add(angvelToLinvel.current);
1558
+ } else {
1559
+ rayHitPointVelocity.current.copy(rayOriginVel.current);
1560
+ supportPointVelocity.current.copy(rayOriginVel.current);
1561
+ }
1562
+ rayHitPointVelOnPlane.current.copy(rayHitPointVelocity.current).projectOnPlane(rayHitPointNormal.current);
1563
+ if (isOnMovingObject.current && followPlatform) {
1564
+ rayHitPointVelocity.current.sub(movingObjectVelocity.current);
1565
+ supportPointVelocity.current.sub(movingObjectVelocity.current);
1566
+ rayHitPointVelOnPlane.current.sub(movingObjectVelocityOnPlane.current);
1567
+ }
1568
+ }, [followPlatform]);
1569
+ /**
1570
+ * Update shape cast info directly from Rapier's rigid-body pose (immune to Three.js render interpolation)
1571
+ */
1572
+ const updateShapeCastDir = useCallback((body) => {
1573
+ var _rigidBodyStates$get;
1574
+ if (!shapeCastWheelRef.current) return;
1575
+ if (!baseLocalQuatCaptured.current) {
1576
+ baseLocalQuat.current.copy(shapeCastWheelRef.current.quaternion);
1577
+ baseLocalQuatCaptured.current = true;
1578
+ }
1579
+ if (steerWheel) {
1580
+ steerQuat.current.setFromAxisAngle(fixedYAxis, steerAngle.current);
1581
+ shapeCastWheelRef.current.quaternion.multiplyQuaternions(baseLocalQuat.current, steerQuat.current);
1582
+ }
1583
+ localPos.current.copy(shapeCastWheelRef.current.position);
1584
+ localQuat.current.copy(shapeCastWheelRef.current.quaternion);
1585
+ const rigidBodyObject = (_rigidBodyStates$get = rigidBodyStates.get(body.handle)) === null || _rigidBodyStates$get === void 0 ? void 0 : _rigidBodyStates$get.object;
1586
+ let parent = shapeCastWheelRef.current.parent;
1587
+ if (rigidBodyObject && parent && parent !== rigidBodyObject) while (parent && parent !== rigidBodyObject) {
1588
+ localPos.current.multiply(parent.scale).applyQuaternion(parent.quaternion).add(parent.position);
1589
+ localQuat.current.premultiply(parent.quaternion);
1590
+ parent = parent.parent;
1591
+ }
1592
+ worldPos.current.copy(localPos.current).applyMatrix4(vehicleMatrix.current);
1593
+ worldQuat.current.multiplyQuaternions(vehicleQuat.current, localQuat.current);
1594
+ rayOrigin.current.copy(worldPos.current);
1595
+ rayDirection.current.set(0, -1, 0).applyQuaternion(worldQuat.current);
1596
+ rayUpAxis.current.copy(rayDirection.current).negate();
1597
+ rayFWDAxis.current.set(0, 0, 1).applyQuaternion(worldQuat.current);
1598
+ rayBWDAxis.current.copy(rayFWDAxis.current).negate();
1599
+ rayLeftAxis.current.crossVectors(rayUpAxis.current, rayFWDAxis.current).normalize();
1600
+ distFromRayOriginToVehicle.current.copy(rayOrigin.current).sub(vehicleCom.current);
1601
+ angvelToLinvel.current.crossVectors(vehicleAngVel.current, distFromRayOriginToVehicle.current);
1602
+ rayOriginVel.current.copy(vehicleLinVel.current).add(angvelToLinvel.current);
1603
+ }, [
1604
+ steerWheel,
1605
+ fixedYAxis,
1606
+ rigidBodyStates
1607
+ ]);
1608
+ /**
1609
+ * Detect is on a moving object
1610
+ */
1611
+ const isOnMovingObjectDetect = useCallback((body) => {
1612
+ if (followPlatform && rayHitBody.current && (rayHitBody.current.isDynamic() || rayHitBody.current.isKinematic())) {
1613
+ isOnMovingObject.current = true;
1614
+ if (rayHitBody.current.isDynamic()) massRatio.current = evaluateCurveLUT(clamp(rayHitBody.current.mass() / Math.max(body.mass(), 1e-6), 0, 1), massRatioFallOffCurve);
1615
+ else massRatio.current = 1;
1616
+ movingObjectPosition.current.copy(rayHitBody.current.worldCom());
1617
+ distanceFromOriginToObjectPoint.current.copy(rayHitPointPosition.current).sub(movingObjectPosition.current);
1618
+ movingObjectLinearVelocity.current.copy(rayHitBody.current.linvel());
1619
+ movingObjectAngularVelocity.current.copy(rayHitBody.current.angvel());
1620
+ movingObjectAngvelToLinvel.current.crossVectors(movingObjectAngularVelocity.current, distanceFromOriginToObjectPoint.current);
1621
+ movingObjectVelocity.current.copy(movingObjectLinearVelocity.current).add(movingObjectAngvelToLinvel.current).multiplyScalar(massRatio.current);
1622
+ movingObjectVelocityOnPlane.current.copy(movingObjectVelocity.current).projectOnPlane(rayHitPointNormal.current);
1623
+ } else {
1624
+ isOnMovingObject.current = false;
1625
+ movingObjectVelocity.current.set(0, 0, 0);
1626
+ movingObjectVelocityOnPlane.current.set(0, 0, 0);
1627
+ massRatio.current = 1;
1628
+ }
1629
+ }, [followPlatform, massRatioFallOffCurve]);
1630
+ /**
1631
+ * Floating function
1632
+ */
1633
+ const ecctrlVehicleRayFilter = useCallback((collider) => {
1634
+ var _collider$parent, _userData$ecctrl, _userData$ecctrl2;
1635
+ const userData = (_collider$parent = collider.parent) === null || _collider$parent === void 0 || (_collider$parent = _collider$parent.call(collider)) === null || _collider$parent === void 0 ? void 0 : _collider$parent.userData;
1636
+ return !((userData === null || userData === void 0 || (_userData$ecctrl = userData.ecctrl) === null || _userData$ecctrl === void 0 ? void 0 : _userData$ecctrl.excludeRay) || (userData === null || userData === void 0 || (_userData$ecctrl2 = userData.ecctrl) === null || _userData$ecctrl2 === void 0 ? void 0 : _userData$ecctrl2.excludeVehicleRay));
1637
+ }, []);
1638
+ const floatVehicle = useCallback((body) => {
1639
+ var _rayHit$current, _shapeRayHit$current, _rayHit$current2, _shapeRayHit$current2;
1640
+ if (groundDetection === "rayCast") rayHit.current = world.castRayAndGetNormal(rayCast, rayLength + rayShapeR, false, QueryFilterFlags.EXCLUDE_SENSORS, void 0, void 0, body, ecctrlVehicleRayFilter);
1641
+ else shapeRayHit.current = world.castShape(rayOrigin.current, rayRotation.current.copy(worldQuat.current).multiply(rotZ90), rayDirection.current, rayShape, 0, rayLength, false, QueryFilterFlags.EXCLUDE_SENSORS, void 0, void 0, body, ecctrlVehicleRayFilter);
1642
+ const hitCollider = groundDetection === "rayCast" ? (_rayHit$current = rayHit.current) === null || _rayHit$current === void 0 ? void 0 : _rayHit$current.collider : (_shapeRayHit$current = shapeRayHit.current) === null || _shapeRayHit$current === void 0 ? void 0 : _shapeRayHit$current.collider;
1643
+ const hitDistance = groundDetection === "rayCast" ? (_rayHit$current2 = rayHit.current) === null || _rayHit$current2 === void 0 ? void 0 : _rayHit$current2.timeOfImpact : (_shapeRayHit$current2 = shapeRayHit.current) === null || _shapeRayHit$current2 === void 0 ? void 0 : _shapeRayHit$current2.time_of_impact;
1644
+ if (hitCollider && hitDistance != null) {
1645
+ var _hitCollider$friction;
1646
+ suspensionToi.current = groundDetection === "rayCast" ? Math.max(0, hitDistance - rayShapeR) : hitDistance;
1647
+ rayHitBody.current = hitCollider.parent();
1648
+ if (groundDetection === "rayCast") targetRayHitPoint.current.copy(rayOrigin.current).addScaledVector(rayDirection.current, hitDistance);
1649
+ else targetRayHitPoint.current.copy(shapeRayHit.current.witness1);
1650
+ rayHitPointNormal.current.copy(groundDetection === "rayCast" ? rayHit.current.normal : shapeRayHit.current.normal1).normalize();
1651
+ rayShapeCenter.current.copy(rayOrigin.current).addScaledVector(rayDirection.current, suspensionToi.current);
1652
+ let supportOffset = 0;
1653
+ if (groundDetection === "rayCast") stableRayHitPoint.current.copy(targetRayHitPoint.current);
1654
+ else {
1655
+ const rawOffset = clamp(rayHitPointOffset.current.copy(targetRayHitPoint.current).sub(rayShapeCenter.current).dot(rayLeftAxis.current), -rayShapeH, rayShapeH);
1656
+ stableRayHitPoint.current.copy(targetRayHitPoint.current).addScaledVector(rayLeftAxis.current, -rawOffset);
1657
+ const normalSide = rayHitPointNormal.current.dot(rayLeftAxis.current);
1658
+ const normalFwd = rayHitPointNormal.current.dot(rayFWDAxis.current);
1659
+ const sideWeight = clamp(Math.abs(normalSide) / Math.sqrt(Math.max(1 - normalFwd * normalFwd, 1e-6)), 0, 1);
1660
+ supportOffset = -Math.abs(rawOffset) * Math.sign(normalSide) * sideWeight;
1661
+ }
1662
+ rayHitPointPosition.current.copy(stableRayHitPoint.current).addScaledVector(rayLeftAxis.current, supportOffset);
1663
+ supportPoint.current.copy(rayShapeCenter.current).addScaledVector(rayLeftAxis.current, supportOffset);
1664
+ if (rayHitPointFriction.current !== hitCollider.friction()) rayHitPointFriction.current = (_hitCollider$friction = hitCollider.friction()) !== null && _hitCollider$friction !== void 0 ? _hitCollider$friction : 0;
1665
+ isOnMovingObjectDetect(body);
1666
+ computeRelativeVelocity();
1667
+ const springForce = springK * Math.max(0, rayLength - suspensionToi.current);
1668
+ const solverSteps = world.integrationParameters.numSolverIterations;
1669
+ const gravityAlongUp = (world.gravity.x * rayUpAxis.current.x + world.gravity.y * rayUpAxis.current.y + world.gravity.z * rayUpAxis.current.z) * body.gravityScale();
1670
+ const dampingForce = dampingC * (supportPointVelocity.current.dot(rayUpAxis.current) - (solverSteps - 1) / (2 * solverSteps) * world.timestep * gravityAlongUp);
1671
+ floatingImpulse.current.copy(rayHitPointNormal.current).multiplyScalar(springForce - dampingForce).multiplyScalar(world.timestep);
1672
+ } else {
1673
+ rayHitBody.current = null;
1674
+ suspensionToi.current = 0;
1675
+ rayHitPointFriction.current = 0;
1676
+ floatingImpulse.current.set(0, 0, 0);
1677
+ isOnMovingObjectDetect(body);
1678
+ computeRelativeVelocity();
1679
+ }
1680
+ }, [
1681
+ groundDetection,
1682
+ rayCast,
1683
+ rayShape,
1684
+ rayLength,
1685
+ rayShapeR,
1686
+ rayShapeH,
1687
+ springK,
1688
+ dampingC,
1689
+ ecctrlVehicleRayFilter,
1690
+ isOnMovingObjectDetect,
1691
+ computeRelativeVelocity
1692
+ ]);
1693
+ /**
1694
+ * Apply wheel mass on standing collider
1695
+ */
1696
+ const applyMassOnStandCollider = useCallback(() => {
1697
+ if (!rayHitBody.current || rayHitBody.current.bodyType() !== 0 || !applyCounterMass) return;
1698
+ wheelSupportImpulse.current.copy(rayHitPointNormal.current).multiplyScalar(-1 * wheelSupportForceMag.current * world.timestep * massRatio.current);
1699
+ if (wheelSupportForceMag.current > 0) rayHitBody.current.applyImpulseAtPoint(wheelSupportImpulse.current, rayHitPointPosition.current, true);
1700
+ }, [applyCounterMass]);
1701
+ /**
1702
+ * Apply tire friction on standing collider
1703
+ */
1704
+ const applyFricitonOnStandCollider = useCallback(() => {
1705
+ if (!rayHitBody.current || rayHitBody.current.bodyType() !== 0 || !applyCounterFriction) return;
1706
+ wheelFrictionImpulse.current.addVectors(lngFrictionImp.current, latFrictionImp.current).multiplyScalar(-1 * massRatio.current);
1707
+ if (wheelFrictionImpulse.current.lengthSq() > 1e-4) rayHitBody.current.applyImpulseAtPoint(wheelFrictionImpulse.current, rayHitPointPosition.current, true);
1708
+ }, [applyCounterFriction]);
1709
+ /**
1710
+ * Handle user input function
1711
+ */
1712
+ const handleUserInput = useCallback(() => {
1713
+ const currDriveConfig = driveWheelConfig.current;
1714
+ const currSteerConfig = steerWheelConfig.current;
1715
+ if (driveWheel && currDriveConfig && currDriveConfig.maxDriveTorque !== 0) {
1716
+ const maxAngVel = currDriveConfig.maxWheelAngVel * (driveDemand.current < 0 ? currDriveConfig.reverseRPMScale : 1);
1717
+ const angvelRatio = maxAngVel > 0 ? Math.abs(wheelAngVel.current) / maxAngVel : 1;
1718
+ driveTorque.current = driveDemand.current * currDriveConfig.maxDriveTorque * currDriveConfig.driveRatio * (driveDemand.current < 0 ? currDriveConfig.reverseTorqueScale : 1) * evaluateCurveLUT(angvelRatio, currDriveConfig.engineTorqueCurve) * (driveInvert ? -1 : 1);
1719
+ }
1720
+ if (steerWheel && currSteerConfig) {
1721
+ var _currSteerConfig$maxW;
1722
+ const steerMaxWheelAngVel = (_currSteerConfig$maxW = currSteerConfig === null || currSteerConfig === void 0 ? void 0 : currSteerConfig.maxWheelAngVel) !== null && _currSteerConfig$maxW !== void 0 ? _currSteerConfig$maxW : 0;
1723
+ const speedRatio = steerMaxWheelAngVel > 0 ? clamp(vehicleLinVel.current.dot(vehicleZAxis.current) / (steerMaxWheelAngVel * rayShapeR), 0, 1) : 0;
1724
+ steerTarget.current = steerDemand.current * currSteerConfig.maxSteerAngle * evaluateCurveLUT(speedRatio, currSteerConfig.steerAngleCurve) * (steerInvert ? -1 : 1);
1725
+ }
1726
+ if (brakeWheel) brakeTorque.current = brakeDemand.current * maxBrakeTorque;
1727
+ }, [
1728
+ driveWheel,
1729
+ driveInvert,
1730
+ maxBrakeTorque,
1731
+ steerWheel,
1732
+ steerInvert
1733
+ ]);
1734
+ /**
1735
+ * Steering wheel function
1736
+ */
1737
+ const steeringWheel = useCallback(() => {
1738
+ var _steerWheelConfig$cur, _steerWheelConfig$cur2;
1739
+ const angleDiff = steerTarget.current - steerAngle.current;
1740
+ const maxIncrement = ((_steerWheelConfig$cur = (_steerWheelConfig$cur2 = steerWheelConfig.current) === null || _steerWheelConfig$cur2 === void 0 ? void 0 : _steerWheelConfig$cur2.steerRate) !== null && _steerWheelConfig$cur !== void 0 ? _steerWheelConfig$cur : 0) * world.timestep;
1741
+ steerIncrement.current = Math.sign(angleDiff) * Math.min(Math.abs(angleDiff), maxIncrement);
1742
+ steerAngle.current += steerIncrement.current;
1743
+ }, [steerWheelConfig]);
1744
+ /**
1745
+ * Compute friction coefficient based on contact surface friction and tire grip factor
1746
+ */
1747
+ const computeContactFriction = useCallback(() => {
1748
+ if (rayHitBody.current) frictionCoef.current = Math.max((rayHitPointFriction.current + tireGripFactor) * .5, 0);
1749
+ else frictionCoef.current = 0;
1750
+ }, [tireGripFactor]);
1751
+ /**
1752
+ * Prepare contact axes, support load, and local slope-gravity impulse for vehicle-wide load sharing (Pass 1)
1753
+ */
1754
+ const prepareContactSlopeGravity = useCallback((gravityMag, body) => {
1755
+ if (!rayHitBody.current) {
1756
+ wheelSupportForceMag.current = wheelMass * gravityMag;
1757
+ effectiveInertia.current = wheelInertia + (gravityMag > 1e-6 ? wheelSupportForceMag.current / gravityMag * rayShapeR * rayShapeR : 0);
1758
+ defaultLngSlopeGravImp.current = 0;
1759
+ defaultLatSlopeGravImp.current = 0;
1760
+ slopeGravImpVec.current.set(0, 0, 0);
1761
+ wheelInfo.current.rayHit = null;
1762
+ wheelInfo.current.supportForceMag = 0;
1763
+ wheelInfo.current.maxCaliperImp = 0;
1764
+ wheelInfo.current.slopeGravImp = slopeGravImpVec.current;
1765
+ wheelInfo.current.isActivelyBraking = false;
1766
+ return;
1767
+ }
1768
+ wheelSupportForceMag.current = Math.max(floatingImpulse.current.dot(rayHitPointNormal.current), 0) / world.timestep;
1769
+ const supportedMass = gravityMag > 1e-6 ? wheelSupportForceMag.current / gravityMag : wheelMass;
1770
+ effectiveInertia.current = wheelInertia + supportedMass * rayShapeR * rayShapeR;
1771
+ lngAxis.current.copy(rayFWDAxis.current).projectOnPlane(rayHitPointNormal.current).normalize();
1772
+ latAxis.current.copy(rayLeftAxis.current).projectOnPlane(rayHitPointNormal.current).normalize();
1773
+ const gravScale = body.gravityScale();
1774
+ let totalGravX = world.gravity.x * gravScale;
1775
+ let totalGravY = world.gravity.y * gravScale;
1776
+ let totalGravZ = world.gravity.z * gravScale;
1777
+ if (vehicleValue === null || vehicleValue === void 0 ? void 0 : vehicleValue.enableCustomGravity) {
1778
+ const customGrav = vehicleValue.referenceGravity.current;
1779
+ totalGravX += customGrav.x * gravScale;
1780
+ totalGravY += customGrav.y * gravScale;
1781
+ totalGravZ += customGrav.z * gravScale;
1782
+ }
1783
+ const totalGravMag = Math.hypot(totalGravX, totalGravY, totalGravZ);
1784
+ const normalGrav = -(totalGravX * rayHitPointNormal.current.x + totalGravY * rayHitPointNormal.current.y + totalGravZ * rayHitPointNormal.current.z);
1785
+ const slopeMass = totalGravMag > 1e-6 && normalGrav > 1e-6 ? wheelSupportForceMag.current / Math.max(normalGrav, .25 * totalGravMag) : supportedMass;
1786
+ const totalGravLng = totalGravX * lngAxis.current.x + totalGravY * lngAxis.current.y + totalGravZ * lngAxis.current.z;
1787
+ const totalGravLat = totalGravX * latAxis.current.x + totalGravY * latAxis.current.y + totalGravZ * latAxis.current.z;
1788
+ defaultLngSlopeGravImp.current = slopeMass * totalGravLng * world.timestep;
1789
+ defaultLatSlopeGravImp.current = slopeMass * totalGravLat * world.timestep;
1790
+ slopeGravImpVec.current.copy(lngAxis.current).multiplyScalar(defaultLngSlopeGravImp.current).addScaledVector(latAxis.current, defaultLatSlopeGravImp.current);
1791
+ const activelyBraking = Boolean(brakeWheel && brakeTorque.current > 0 && rayShapeR > 1e-6);
1792
+ const maxStaticGripImp = wheelSupportForceMag.current * frictionCoef.current * world.timestep * lngFrictionEllipseScale;
1793
+ wheelInfo.current.rayHit = groundDetection === "rayCast" ? rayHit.current : shapeRayHit.current;
1794
+ wheelInfo.current.supportForceMag = wheelSupportForceMag.current;
1795
+ wheelInfo.current.maxCaliperImp = activelyBraking ? Math.min(Math.abs(brakeTorque.current) * world.timestep / rayShapeR, maxStaticGripImp) : 0;
1796
+ wheelInfo.current.lngAxis = lngAxis.current;
1797
+ wheelInfo.current.latAxis = latAxis.current;
1798
+ wheelInfo.current.slopeGravImp = slopeGravImpVec.current;
1799
+ wheelInfo.current.isActivelyBraking = activelyBraking;
1800
+ }, [
1801
+ vehicleValue,
1802
+ groundDetection,
1803
+ brakeWheel,
1804
+ wheelMass,
1805
+ wheelInertia,
1806
+ rayShapeR,
1807
+ lngFrictionEllipseScale
1808
+ ]);
1809
+ /**
1810
+ * Compute longitudinal and lateral friction impulses based on wheel slip and contact conditions
1811
+ */
1812
+ const computeWheelFrictionImpulse = useCallback((gravityMag, body, overrideLngGravImp, overrideLatGravImp) => {
1813
+ if (!rayHitBody.current) {
1814
+ lngSlipRatio.current = 0;
1815
+ latSlipRatio.current = 0;
1816
+ slipStrength.current = 0;
1817
+ desiredLngImpulse.current = 0;
1818
+ desiredLatImpulse.current = 0;
1819
+ smoothedLngImpulse.current = 0;
1820
+ smoothedLatImpulse.current = 0;
1821
+ lngFrictionImp.current.set(0, 0, 0);
1822
+ latFrictionImp.current.set(0, 0, 0);
1823
+ return;
1824
+ }
1825
+ const supportedMass = gravityMag > 1e-6 ? wheelSupportForceMag.current / gravityMag : wheelMass;
1826
+ const solverSteps = world.integrationParameters.numSolverIterations;
1827
+ const gravScale = body.gravityScale();
1828
+ const substepWeight = (solverSteps - 1) / (2 * solverSteps) * world.timestep * gravScale;
1829
+ const worldGravLng = world.gravity.x * lngAxis.current.x + world.gravity.y * lngAxis.current.y + world.gravity.z * lngAxis.current.z;
1830
+ const worldGravLat = world.gravity.x * latAxis.current.x + world.gravity.y * latAxis.current.y + world.gravity.z * latAxis.current.z;
1831
+ const lngContactVel = rayHitPointVelocity.current.dot(lngAxis.current) - substepWeight * worldGravLng;
1832
+ const latContactVel = rayHitPointVelocity.current.dot(latAxis.current) - substepWeight * worldGravLat;
1833
+ const lngContactVelAbs = Math.abs(lngContactVel);
1834
+ const latContactVelAbs = Math.abs(latContactVel);
1835
+ const slipDiff = wheelAngVel.current * rayShapeR - lngContactVel;
1836
+ const slipDiffAbs = Math.abs(slipDiff);
1837
+ lngSlipRatio.current = slipDiffAbs / Math.max(lngContactVelAbs, 1e-4);
1838
+ latSlipRatio.current = latContactVelAbs === 0 && lngContactVelAbs === 0 ? 0 : clamp(Math.atan2(latContactVelAbs, lngContactVelAbs) / (Math.PI / 2), 0, 1);
1839
+ slipStrength.current = Math.max(lngSlipRatio.current, latSlipRatio.current);
1840
+ const lngSlipValue = evaluateCurveLUT(lngSlipRatio.current, lngSlipRatioCurve);
1841
+ const latSlipValue = evaluateCurveLUT(latSlipRatio.current, latSlipRatioCurve);
1842
+ const finalLngSlipValue = remap(clamp(1 - Math.max(slipDiffAbs, lngContactVelAbs) / lowVelThreshold, 0, 1), 0, 1, lngSlipValue, 1);
1843
+ const finalLatSlipValue = remap(clamp(1 - Math.max(latContactVelAbs, lngContactVelAbs) / lowVelThreshold, 0, 1), 0, 1, latSlipValue, 1);
1844
+ const maxLngImp = wheelSupportForceMag.current * finalLngSlipValue * frictionCoef.current * world.timestep * lngFrictionEllipseScale;
1845
+ const maxLatImp = wheelSupportForceMag.current * finalLatSlipValue * frictionCoef.current * world.timestep * latFrictionEllipseScale;
1846
+ if (maxLngImp <= 1e-9 || maxLatImp <= 1e-9) {
1847
+ desiredLngImpulse.current = 0;
1848
+ desiredLatImpulse.current = 0;
1849
+ smoothedLngImpulse.current = 0;
1850
+ smoothedLatImpulse.current = 0;
1851
+ lngFrictionImp.current.set(0, 0, 0);
1852
+ latFrictionImp.current.set(0, 0, 0);
1853
+ return;
1854
+ }
1855
+ let latEffectiveMass = supportedMass;
1856
+ const bodyMass = body.mass();
1857
+ if (bodyMass > 0) {
1858
+ const rx = rayHitPointPosition.current.x - vehicleCom.current.x;
1859
+ const ry = rayHitPointPosition.current.y - vehicleCom.current.y;
1860
+ const rz = rayHitPointPosition.current.z - vehicleCom.current.z;
1861
+ const invI = body.effectiveWorldInvInertia();
1862
+ const lx = latAxis.current.x;
1863
+ const ly = latAxis.current.y;
1864
+ const lz = latAxis.current.z;
1865
+ const cx = ry * lz - rz * ly;
1866
+ const cy = rz * lx - rx * lz;
1867
+ const cz = rx * ly - ry * lx;
1868
+ const rotTerm = cx * (invI.m11 * cx + invI.m12 * cy + invI.m13 * cz) + cy * (invI.m21 * cx + invI.m22 * cy + invI.m23 * cz) + cz * (invI.m31 * cx + invI.m32 * cy + invI.m33 * cz);
1869
+ if (rotTerm > 0) latEffectiveMass = supportedMass / (1 + bodyMass * rotTerm);
1870
+ }
1871
+ const lngSlopeGravImp = overrideLngGravImp !== null && overrideLngGravImp !== void 0 ? overrideLngGravImp : defaultLngSlopeGravImp.current;
1872
+ const latSlopeGravImp = overrideLatGravImp !== null && overrideLatGravImp !== void 0 ? overrideLatGravImp : defaultLatSlopeGravImp.current;
1873
+ const freeSpinImp = slipDiff * effectiveInertia.current / (rayShapeR * rayShapeR);
1874
+ if (brakeWheel && brakeTorque.current > 0 && rayShapeR > 1e-6) {
1875
+ const maxCaliperImp = Math.abs(brakeTorque.current) * world.timestep / rayShapeR;
1876
+ desiredLngImpulse.current = clamp(-(lngContactVel * effectiveInertia.current) / (rayShapeR * rayShapeR) - lngSlopeGravImp, freeSpinImp - maxCaliperImp, freeSpinImp + maxCaliperImp);
1877
+ } else desiredLngImpulse.current = freeSpinImp;
1878
+ desiredLatImpulse.current = latContactVel * latEffectiveMass + latSlopeGravImp;
1879
+ const lngUsage = desiredLngImpulse.current / maxLngImp;
1880
+ const latUsage = desiredLatImpulse.current / maxLatImp;
1881
+ const ellipseUsage = Math.sqrt(lngUsage * lngUsage + latUsage * latUsage);
1882
+ if (ellipseUsage > 1) {
1883
+ desiredLngImpulse.current /= ellipseUsage;
1884
+ desiredLatImpulse.current /= ellipseUsage;
1885
+ }
1886
+ const lngCoeff = clamp(Math.max(minLngRelaxCoeff, lngContactVelAbs / Math.max(relaxLngRate, 1e-6) * world.timestep), 0, 1);
1887
+ const latCoeff = clamp(Math.max(minLatRelaxCoeff, latContactVelAbs / Math.max(relaxLatRate, 1e-6) * world.timestep), 0, 1);
1888
+ smoothedLngImpulse.current += (desiredLngImpulse.current - smoothedLngImpulse.current) * lngCoeff;
1889
+ smoothedLatImpulse.current += (desiredLatImpulse.current - smoothedLatImpulse.current) * latCoeff;
1890
+ const capToward = (smoothed, desired) => smoothed * desired <= 0 ? 0 : Math.abs(smoothed) > Math.abs(desired) ? desired : smoothed;
1891
+ smoothedLngImpulse.current = capToward(smoothedLngImpulse.current, desiredLngImpulse.current);
1892
+ smoothedLatImpulse.current = capToward(smoothedLatImpulse.current, desiredLatImpulse.current);
1893
+ lngFrictionImp.current.copy(lngAxis.current).multiplyScalar(smoothedLngImpulse.current);
1894
+ latFrictionImp.current.copy(latAxis.current).multiplyScalar(-smoothedLatImpulse.current);
1895
+ }, [
1896
+ brakeWheel,
1897
+ wheelMass,
1898
+ rayShapeR,
1899
+ lowVelThreshold,
1900
+ lngSlipRatioCurve,
1901
+ latSlipRatioCurve,
1902
+ lngFrictionEllipseScale,
1903
+ latFrictionEllipseScale,
1904
+ relaxLngRate,
1905
+ relaxLatRate,
1906
+ minLngRelaxCoeff,
1907
+ minLatRelaxCoeff
1908
+ ]);
1909
+ /**
1910
+ * Solve wheel rotation based on drive/brake torque and friction torque
1911
+ */
1912
+ const solveWheelRotation = useCallback(() => {
1913
+ const isDriving = driveWheel && Math.abs(driveTorque.current) > 0 && rayHitBody.current;
1914
+ const isBraking = brakeWheel && Math.abs(brakeTorque.current) > 0 && rayHitBody.current;
1915
+ const isFreeRolling = !isDriving && !isBraking;
1916
+ if (rayHitBody.current) wheelAngVel.current -= lngFrictionImp.current.dot(lngAxis.current) * rayShapeR / effectiveInertia.current;
1917
+ if (rayHitBody.current && isFreeRolling || !rayHitBody.current && wheelAngVel.current !== 0) {
1918
+ const rollingResistTorque = -rollingResistanceCoef * wheelSupportForceMag.current * wheelAngVel.current;
1919
+ wheelAngVel.current += rollingResistTorque / effectiveInertia.current * world.timestep;
1920
+ }
1921
+ if (isDriving && !isBraking) wheelAngVel.current += driveTorque.current / effectiveInertia.current * world.timestep;
1922
+ if (isBraking) {
1923
+ const appliedBrakeTorque = brakeTorque.current * -Math.sign(wheelAngVel.current);
1924
+ wheelAngVel.current += Math.min(Math.abs(wheelAngVel.current), Math.abs(appliedBrakeTorque / effectiveInertia.current) * world.timestep) * -Math.sign(wheelAngVel.current);
1925
+ }
1926
+ }, [
1927
+ rollingResistanceCoef,
1928
+ effectiveInertia,
1929
+ driveTorque,
1930
+ brakeTorque,
1931
+ rayShapeR,
1932
+ driveWheel,
1933
+ brakeWheel
1934
+ ]);
1935
+ /**
1936
+ * Update wheel models
1937
+ */
1938
+ const updateWheelModel = useCallback((delta) => {
1939
+ if (!wheelRef.current || !modelRef.current || !wheelModelUpdate) return;
1940
+ const dt = delta > 0 ? delta : world.timestep;
1941
+ const offsetY = (groundDetection === "rayCast" ? rayHit.current : shapeRayHit.current) ? -(rayLength + rayShapeR) + wheelModelRadius + (rayLength - suspensionToi.current) : -(rayLength + rayShapeR) + wheelModelRadius;
1942
+ wheelRef.current.position.y = THREE.MathUtils.lerp(wheelRef.current.position.y, offsetY, 1 - Math.exp(-wheelModelLerpPosRate * dt));
1943
+ modelRef.current.rotation.x += wheelAngVel.current * dt * (wheelModelReversRotation ? -1 : 1);
1944
+ }, [
1945
+ groundDetection,
1946
+ wheelModelRadius,
1947
+ rayLength,
1948
+ rayShapeR,
1949
+ wheelModelLerpPosRate,
1950
+ wheelModelUpdate,
1951
+ wheelModelReversRotation
1952
+ ]);
1953
+ /**
1954
+ * Update debug indicators
1955
+ */
1956
+ const updateDebugger = useCallback(() => {
1957
+ const hasContact = groundDetection === "rayCast" ? rayHit.current : shapeRayHit.current;
1958
+ vehicleInvertQuat.current.copy(vehicleQuat.current).invert();
1959
+ vehicleInvertMatrix.current.copy(vehicleMatrix.current).invert();
1960
+ if (rayHitPointRef.current) rayHitPointRef.current.position.copy(rayHitPointPosition.current).applyMatrix4(vehicleInvertMatrix.current);
1961
+ if (!shapeCastWheelRef.current) return;
1962
+ if (currFloatArrowRef.current) {
1963
+ currFloatArrowRef.current.position.copy(shapeCastWheelRef.current.position);
1964
+ currFloatArrowDir.current.copy(rayHitPointNormal.current).applyQuaternion(vehicleInvertQuat.current);
1965
+ currFloatArrowRef.current.setDirection(currFloatArrowDir.current);
1966
+ const length = hasContact ? wheelSupportForceMag.current * world.timestep * debuggerArrowScale : 0;
1967
+ currFloatArrowRef.current.setLength(length);
1968
+ }
1969
+ if (currDriftArrowRef.current) {
1970
+ currDriftArrowRef.current.position.copy(shapeCastWheelRef.current.position);
1971
+ currDriftArrowDir.current.copy(latAxis.current).negate().applyQuaternion(vehicleInvertQuat.current);
1972
+ currDriftArrowRef.current.setDirection(currDriftArrowDir.current);
1973
+ const length = hasContact ? desiredLatImpulse.current * debuggerArrowScale : 0;
1974
+ currDriftArrowRef.current.setLength(length);
1975
+ }
1976
+ if (currEngineArrowRef.current) {
1977
+ currEngineArrowRef.current.position.copy(shapeCastWheelRef.current.position);
1978
+ currEngineArrowDir.current.copy(lngAxis.current).applyQuaternion(vehicleInvertQuat.current);
1979
+ currEngineArrowRef.current.setDirection(currEngineArrowDir.current);
1980
+ const length = hasContact ? desiredLngImpulse.current * debuggerArrowScale : 0;
1981
+ currEngineArrowRef.current.setLength(length);
1982
+ }
1983
+ }, [groundDetection, debuggerArrowScale]);
1984
+ const stepWheelSuspension = useCallback(() => {
1985
+ if (!vehicleValue || !enable) {
1986
+ wheelInfo.current.rayHit = null;
1987
+ wheelInfo.current.supportForceMag = 0;
1988
+ wheelInfo.current.maxCaliperImp = 0;
1989
+ wheelInfo.current.isActivelyBraking = false;
1990
+ return;
1991
+ }
1992
+ const vehicleBody = vehicleValue.body.current;
1993
+ if (!vehicleBody) return;
1994
+ updateVehicleInfo(vehicleBody);
1995
+ handleUserInput();
1996
+ steeringWheel();
1997
+ updateShapeCastDir(vehicleBody);
1998
+ floatVehicle(vehicleBody);
1999
+ computeContactFriction();
2000
+ prepareContactSlopeGravity(vehicleValue.gravityMag.current, vehicleBody);
2001
+ }, [
2002
+ vehicleValue,
2003
+ enable,
2004
+ updateVehicleInfo,
2005
+ handleUserInput,
2006
+ steeringWheel,
2007
+ updateShapeCastDir,
2008
+ floatVehicle,
2009
+ computeContactFriction,
2010
+ prepareContactSlopeGravity
2011
+ ]);
2012
+ const stepWheelTireAndSpin = useCallback((overrideLngGravImp, overrideLatGravImp) => {
2013
+ if (!vehicleValue || !enable) return;
2014
+ const vehicleBody = vehicleValue.body.current;
2015
+ if (!vehicleBody) return;
2016
+ computeWheelFrictionImpulse(vehicleValue.gravityMag.current, vehicleBody, overrideLngGravImp, overrideLatGravImp);
2017
+ applyMassOnStandCollider();
2018
+ applyFricitonOnStandCollider();
2019
+ solveWheelRotation();
2020
+ syncWheelInfo();
2021
+ }, [
2022
+ vehicleValue,
2023
+ enable,
2024
+ computeWheelFrictionImpulse,
2025
+ applyMassOnStandCollider,
2026
+ applyFricitonOnStandCollider,
2027
+ solveWheelRotation,
2028
+ syncWheelInfo
2029
+ ]);
2030
+ const stepWheelPhysics = useCallback(() => {
2031
+ stepWheelSuspension();
2032
+ stepWheelTireAndSpin();
2033
+ }, [stepWheelSuspension, stepWheelTireAndSpin]);
2034
+ wheelInfo.current.stepWheelSuspension = stepWheelSuspension;
2035
+ wheelInfo.current.stepWheelTireAndSpin = stepWheelTireAndSpin;
2036
+ wheelInfo.current.stepWheelPhysics = stepWheelPhysics;
2037
+ useFrame((_, delta) => {
2038
+ if (!vehicleValue || !enable || !vehicleValue.body.current) return;
2039
+ updateWheelModel(delta);
2040
+ if (debug) updateDebugger();
2041
+ });
2042
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("group", {
2043
+ ref: shapeCastWheelRef,
2044
+ ...props
2045
+ }, showWheelModel && /* @__PURE__ */ React.createElement("group", { ref: wheelRef }, /* @__PURE__ */ React.createElement("group", { ref: modelRef }, children)), debug && debugAssets && /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("group", { ref: forwardIndicatorRef }, /* @__PURE__ */ React.createElement("mesh", {
2046
+ rotation: [
2047
+ Math.PI / 2,
2048
+ 0,
2049
+ 0
2050
+ ],
2051
+ geometry: debugAssets.forwardRingGeo,
2052
+ material: debugAssets.forwardIndicatorMat
2053
+ }), /* @__PURE__ */ React.createElement("mesh", {
2054
+ rotation: [
2055
+ Math.PI / 2,
2056
+ 0,
2057
+ Math.PI / 4
2058
+ ],
2059
+ position: [
2060
+ 0,
2061
+ 0,
2062
+ rayShapeH * 1.6
2063
+ ],
2064
+ geometry: debugAssets.forwardPointerGeo,
2065
+ material: debugAssets.forwardIndicatorMat
2066
+ })), groundDetection === "shapeCast" && /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("mesh", {
2067
+ rotation: [
2068
+ Math.PI,
2069
+ 0,
2070
+ Math.PI / 2
2071
+ ],
2072
+ geometry: debugAssets.rayCastHalfGeo,
2073
+ material: debugAssets.rayCastMat
2074
+ }), /* @__PURE__ */ React.createElement("mesh", {
2075
+ position: [
2076
+ 0,
2077
+ -rayLength,
2078
+ 0
2079
+ ],
2080
+ rotation: [
2081
+ 0,
2082
+ 0,
2083
+ Math.PI / 2
2084
+ ],
2085
+ geometry: debugAssets.rayCastHalfGeo,
2086
+ material: debugAssets.rayCastMat
2087
+ })), groundDetection === "rayCast" && /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("mesh", {
2088
+ rotation: [
2089
+ -Math.PI / 2,
2090
+ 0,
2091
+ 0
2092
+ ],
2093
+ geometry: debugAssets.rayCastGeo,
2094
+ material: debugAssets.rayCastMat
2095
+ }), /* @__PURE__ */ React.createElement("mesh", {
2096
+ position: [
2097
+ 0,
2098
+ -(rayLength + rayShapeR),
2099
+ 0
2100
+ ],
2101
+ rotation: [
2102
+ -Math.PI / 2,
2103
+ 0,
2104
+ 0
2105
+ ],
2106
+ geometry: debugAssets.rayCastGeo,
2107
+ material: debugAssets.rayCastMat
2108
+ })), /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("mesh", {
2109
+ ref: xAxisPointRef,
2110
+ position: [
2111
+ 1,
2112
+ 0,
2113
+ 0
2114
+ ],
2115
+ geometry: debugAssets.standingGeo,
2116
+ material: debugAssets.xAxisPointMat
2117
+ }), /* @__PURE__ */ React.createElement("mesh", {
2118
+ ref: yAxisPointRef,
2119
+ position: [
2120
+ 0,
2121
+ 1,
2122
+ 0
2123
+ ],
2124
+ geometry: debugAssets.standingGeo,
2125
+ material: debugAssets.yAxisPointMat
2126
+ }), /* @__PURE__ */ React.createElement("mesh", {
2127
+ ref: zAxisPointRef,
2128
+ position: [
2129
+ 0,
2130
+ 0,
2131
+ 1
2132
+ ],
2133
+ geometry: debugAssets.standingGeo,
2134
+ material: debugAssets.zAxisPointMat
2135
+ })))), debug && debugAssets && /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("mesh", {
2136
+ ref: rayHitPointRef,
2137
+ geometry: debugAssets.standingGeo,
2138
+ material: debugAssets.standingMat
2139
+ }), /* @__PURE__ */ React.createElement("arrowHelper", {
2140
+ ref: currFloatArrowRef,
2141
+ args: [
2142
+ void 0,
2143
+ void 0,
2144
+ void 0,
2145
+ "#87CEFA"
2146
+ ]
2147
+ }), /* @__PURE__ */ React.createElement("arrowHelper", {
2148
+ ref: currDriftArrowRef,
2149
+ args: [
2150
+ void 0,
2151
+ void 0,
2152
+ void 0,
2153
+ "#96FA87"
2154
+ ]
2155
+ }), /* @__PURE__ */ React.createElement("arrowHelper", {
2156
+ ref: currEngineArrowRef,
2157
+ args: [
2158
+ void 0,
2159
+ void 0,
2160
+ void 0,
2161
+ "#FA8787"
2162
+ ]
2163
+ })));
2164
+ });
2165
+ var ShapeCastWheel_default = React.memo(ShapeCastWheel);
2166
+ //#endregion
2167
+ //#region src/vehicles/components/ThrustPropeller.tsx
2168
+ /*!
2169
+ * Ecctrl
2170
+ * https://github.com/pmndrs/ecctrl
2171
+ *
2172
+ * SPDX-FileCopyrightText: 2023-2026 Erdong Chen
2173
+ * SPDX-License-Identifier: MIT
2174
+ */
2175
+ var ThrustPropeller = /* @__PURE__ */ forwardRef(({ children, debug = true, enable = true, name = "", maxThrust = 500, torqueRatio = .6, invertThrust = false, invertTorque = false, showPropellerModel = true, propellerModelUpdate = true, propellerModelMaxSpin = 50, propellerModelLerpSpinRate = 10, debuggerScale = 1, debuggerArrowScale = 35, ...props }, ref) => {
2176
+ /**
2177
+ * Rapier preset
2178
+ */
2179
+ const { world, rigidBodyStates } = useRapier();
2180
+ /**
2181
+ * Retrieve context object from ecctrl vehicle
2182
+ */
2183
+ const vehicleValue = useContext(VehicleContext);
2184
+ const vehiclePos = useRef(new THREE.Vector3());
2185
+ const vehicleLocalCom = useRef(new THREE.Vector3());
2186
+ const vehicleQuat = useRef(new THREE.Quaternion());
2187
+ const vehicleLinVel = useRef(new THREE.Vector3());
2188
+ const vehicleAngVel = useRef(new THREE.Vector3());
2189
+ /**
2190
+ * Control preset
2191
+ */
2192
+ const localPos = useRef(new THREE.Vector3());
2193
+ const localArm = useRef(new THREE.Vector3());
2194
+ const localQuat = useRef(new THREE.Quaternion());
2195
+ const worldPos = useRef(new THREE.Vector3());
2196
+ const worldQuat = useRef(new THREE.Quaternion());
2197
+ const thrustDir = useRef(new THREE.Vector3());
2198
+ const thrustForce = useRef(new THREE.Vector3());
2199
+ const leverageTorque = useRef(new THREE.Vector3());
2200
+ const reactionTorque = useRef(new THREE.Vector3());
2201
+ const reactionTorqueDir = useRef(new THREE.Vector3());
2202
+ const torqueInfluence = useRef(new THREE.Vector3());
2203
+ const throttle = useRef(0);
2204
+ const setThrottle = useCallback((value) => throttle.current = clamp(value, 0, 1), []);
2205
+ /**
2206
+ * Refs and handles
2207
+ */
2208
+ const thrustPropellerRef = useRef(null);
2209
+ useImperativeHandle(ref, () => thrustPropellerRef.current, []);
2210
+ /**
2211
+ * Propeller model preset
2212
+ */
2213
+ const modelRef = useRef(null);
2214
+ const modelSpinVel = useRef(0);
2215
+ /**
2216
+ * Register propeller information
2217
+ */
2218
+ const propellerId = useMemo(() => {
2219
+ var _props$id;
2220
+ return String((_props$id = props.id) !== null && _props$id !== void 0 ? _props$id : generateUUID());
2221
+ }, [props.id]);
2222
+ const propellerInfo = useRef({
2223
+ id: propellerId,
2224
+ name,
2225
+ enable,
2226
+ debug,
2227
+ maxThrust,
2228
+ torqueRatio,
2229
+ debuggerScale,
2230
+ invertThrust,
2231
+ invertTorque,
2232
+ thrustPos: new THREE.Vector3(),
2233
+ thrustDir: new THREE.Vector3(),
2234
+ thrustPot: new THREE.Vector3(),
2235
+ torqueDir: new THREE.Vector3(),
2236
+ torquePot: new THREE.Vector3(),
2237
+ worldThrustPos: new THREE.Vector3(),
2238
+ worldThrustDir: new THREE.Vector3(),
2239
+ worldTorqueDir: new THREE.Vector3(),
2240
+ thrustImpulse: new THREE.Vector3(),
2241
+ torqueImpulse: new THREE.Vector3(),
2242
+ finalThrottle: 0,
2243
+ throttle: throttle.current,
2244
+ setThrottle,
2245
+ lx: 0,
2246
+ ly: 0,
2247
+ lz: 0,
2248
+ ax: 0,
2249
+ ay: 0,
2250
+ az: 0
2251
+ });
2252
+ propellerInfo.current.name = name;
2253
+ propellerInfo.current.enable = enable;
2254
+ propellerInfo.current.debug = debug;
2255
+ propellerInfo.current.maxThrust = maxThrust;
2256
+ propellerInfo.current.torqueRatio = torqueRatio;
2257
+ propellerInfo.current.debuggerScale = debuggerScale;
2258
+ propellerInfo.current.invertThrust = invertThrust;
2259
+ propellerInfo.current.invertTorque = invertTorque;
2260
+ useEffect(() => {
2261
+ vehicleValue === null || vehicleValue === void 0 || vehicleValue.regPropeller(propellerInfo);
2262
+ return () => vehicleValue === null || vehicleValue === void 0 ? void 0 : vehicleValue.unregPropeller(propellerId);
2263
+ }, [vehicleValue]);
2264
+ /**
2265
+ * Debug indicators preset
2266
+ */
2267
+ const xAxisPointRef = useRef(null);
2268
+ const yAxisPointRef = useRef(null);
2269
+ const zAxisPointRef = useRef(null);
2270
+ const currThrustArrowRef = useRef(null);
2271
+ const currTorqueArrowRef = useRef(null);
2272
+ const debugAssets = useMemo(() => {
2273
+ if (!debug) return null;
2274
+ return {
2275
+ thrustRingGeo: new THREE.RingGeometry(debuggerScale * .5, debuggerScale * .55, 12, 1, 0, -Math.PI * 1),
2276
+ thrustRingMat: new THREE.MeshBasicMaterial({
2277
+ color: EC_AZURE,
2278
+ side: THREE.DoubleSide
2279
+ }),
2280
+ thrustPointerGeo: new THREE.ConeGeometry(debuggerScale * .06, debuggerScale * .5, 8, 1, true),
2281
+ thrustIndicatorMat: new THREE.MeshBasicMaterial({
2282
+ color: EC_MED_PURPLE,
2283
+ side: THREE.DoubleSide,
2284
+ transparent: true,
2285
+ opacity: .3
2286
+ }),
2287
+ axisPointGeo: new THREE.OctahedronGeometry(debuggerScale * .05, 3),
2288
+ xAxisPointMat: new THREE.MeshBasicMaterial({
2289
+ color: EC_GREEN,
2290
+ transparent: true,
2291
+ opacity: 1
2292
+ }),
2293
+ yAxisPointMat: new THREE.MeshBasicMaterial({
2294
+ color: EC_BLUE,
2295
+ transparent: true,
2296
+ opacity: 1
2297
+ }),
2298
+ zAxisPointMat: new THREE.MeshBasicMaterial({
2299
+ color: EC_RED,
2300
+ transparent: true,
2301
+ opacity: 1
2302
+ })
2303
+ };
2304
+ }, [debug, debuggerScale]);
2305
+ useEffect(() => {
2306
+ return () => {
2307
+ if (!debugAssets) return;
2308
+ for (const key in debugAssets) {
2309
+ const item = debugAssets[key];
2310
+ if ("dispose" in item && typeof item.dispose === "function") item.dispose();
2311
+ }
2312
+ };
2313
+ }, [debugAssets]);
2314
+ /**
2315
+ *
2316
+ *
2317
+ *
2318
+ *
2319
+ *
2320
+ *
2321
+ *
2322
+ *
2323
+ *
2324
+ *
2325
+ *
2326
+ *
2327
+ *
2328
+ *
2329
+ *
2330
+ *
2331
+ *
2332
+ *
2333
+ *
2334
+ *
2335
+ *
2336
+ *
2337
+ *
2338
+ *
2339
+ *
2340
+ *
2341
+ *
2342
+ *
2343
+ *
2344
+ *
2345
+ *
2346
+ *
2347
+ *
2348
+ *
2349
+ */
2350
+ /**
2351
+ * Update vehicle info function
2352
+ */
2353
+ const updateVehicleInfo = useCallback((body) => {
2354
+ vehiclePos.current.copy(body.translation());
2355
+ vehicleLocalCom.current.copy(body.localCom());
2356
+ vehicleQuat.current.copy(body.rotation());
2357
+ vehicleLinVel.current.copy(body.linvel());
2358
+ vehicleAngVel.current.copy(body.angvel());
2359
+ }, []);
2360
+ /**
2361
+ * Update propeller info function directly from local propeller transform (immune to Three.js render interpolation)
2362
+ */
2363
+ const updatePropellerInfo = useCallback((body) => {
2364
+ var _rigidBodyStates$get;
2365
+ if (!thrustPropellerRef.current) return;
2366
+ localPos.current.copy(thrustPropellerRef.current.position);
2367
+ localQuat.current.copy(thrustPropellerRef.current.quaternion);
2368
+ const rigidBodyObject = (_rigidBodyStates$get = rigidBodyStates.get(body.handle)) === null || _rigidBodyStates$get === void 0 ? void 0 : _rigidBodyStates$get.object;
2369
+ let parent = thrustPropellerRef.current.parent;
2370
+ if (rigidBodyObject && parent && parent !== rigidBodyObject) while (parent && parent !== rigidBodyObject) {
2371
+ localPos.current.multiply(parent.scale).applyQuaternion(parent.quaternion).add(parent.position);
2372
+ localQuat.current.premultiply(parent.quaternion);
2373
+ parent = parent.parent;
2374
+ }
2375
+ worldQuat.current.multiplyQuaternions(vehicleQuat.current, localQuat.current);
2376
+ worldPos.current.copy(localPos.current).applyQuaternion(vehicleQuat.current).add(vehiclePos.current);
2377
+ thrustDir.current.set(0, invertThrust ? -1 : 1, 0).applyQuaternion(localQuat.current);
2378
+ thrustForce.current.copy(thrustDir.current).multiplyScalar(maxThrust);
2379
+ localArm.current.subVectors(localPos.current, vehicleLocalCom.current);
2380
+ leverageTorque.current.crossVectors(localArm.current, thrustForce.current);
2381
+ reactionTorqueDir.current.set(0, invertTorque ? -1 : 1, 0).applyQuaternion(localQuat.current);
2382
+ reactionTorque.current.copy(reactionTorqueDir.current).multiplyScalar(maxThrust * torqueRatio);
2383
+ torqueInfluence.current.copy(leverageTorque.current).add(reactionTorque.current);
2384
+ propellerInfo.current.lx = thrustForce.current.x;
2385
+ propellerInfo.current.ly = thrustForce.current.y;
2386
+ propellerInfo.current.lz = thrustForce.current.z;
2387
+ propellerInfo.current.ax = torqueInfluence.current.x;
2388
+ propellerInfo.current.ay = torqueInfluence.current.y;
2389
+ propellerInfo.current.az = torqueInfluence.current.z;
2390
+ propellerInfo.current.thrustPos = localPos.current;
2391
+ propellerInfo.current.thrustDir = thrustDir.current;
2392
+ propellerInfo.current.thrustPot = thrustForce.current;
2393
+ propellerInfo.current.torqueDir = reactionTorqueDir.current;
2394
+ propellerInfo.current.torquePot = torqueInfluence.current;
2395
+ propellerInfo.current.throttle = throttle.current;
2396
+ }, [
2397
+ invertThrust,
2398
+ invertTorque,
2399
+ maxThrust,
2400
+ rigidBodyStates,
2401
+ torqueRatio
2402
+ ]);
2403
+ /**
2404
+ * Update propeller model function
2405
+ */
2406
+ const updatePropellerModel = useCallback((delta) => {
2407
+ if (!modelRef.current) return;
2408
+ const dt = delta > 0 ? delta : world.timestep;
2409
+ const frameRateCorrection = 60 * dt;
2410
+ const targetVel = throttle.current * propellerModelMaxSpin * (invertTorque ? -1 : 1);
2411
+ modelSpinVel.current = lerp(modelSpinVel.current, targetVel, 1 - Math.exp(-propellerModelLerpSpinRate * dt));
2412
+ modelRef.current.rotateY(modelSpinVel.current * frameRateCorrection);
2413
+ }, [
2414
+ propellerModelMaxSpin,
2415
+ propellerModelLerpSpinRate,
2416
+ invertTorque
2417
+ ]);
2418
+ /**
2419
+ * Update debug indicators
2420
+ */
2421
+ const updateDebugger = useCallback(() => {
2422
+ if (currThrustArrowRef.current) currThrustArrowRef.current.setLength(throttle.current * debuggerArrowScale);
2423
+ if (currTorqueArrowRef.current) currTorqueArrowRef.current.setLength(throttle.current * debuggerArrowScale * torqueRatio);
2424
+ }, [debuggerArrowScale, torqueRatio]);
2425
+ const stepPropellerPhysics = useCallback(() => {
2426
+ const body = vehicleValue === null || vehicleValue === void 0 ? void 0 : vehicleValue.body.current;
2427
+ if (!body || !enable) return;
2428
+ updateVehicleInfo(body);
2429
+ updatePropellerInfo(body);
2430
+ }, [
2431
+ vehicleValue,
2432
+ enable,
2433
+ updateVehicleInfo,
2434
+ updatePropellerInfo
2435
+ ]);
2436
+ propellerInfo.current.stepPropellerPhysics = stepPropellerPhysics;
2437
+ useFrame((_, delta) => {
2438
+ if (!(vehicleValue === null || vehicleValue === void 0 ? void 0 : vehicleValue.body.current) || !enable) return;
2439
+ if (propellerModelUpdate) updatePropellerModel(delta);
2440
+ if (debug) updateDebugger();
2441
+ });
2442
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("group", {
2443
+ ref: thrustPropellerRef,
2444
+ ...props
2445
+ }, showPropellerModel && /* @__PURE__ */ React.createElement("group", { ref: modelRef }, children), debug && debugAssets && /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("mesh", {
2446
+ "rotation-x": invertThrust ? Math.PI : 0,
2447
+ position: [
2448
+ 0,
2449
+ debuggerScale * .25 * (invertThrust ? -1 : 1),
2450
+ 0
2451
+ ],
2452
+ geometry: debugAssets.thrustPointerGeo,
2453
+ material: debugAssets.thrustIndicatorMat
2454
+ })), /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("mesh", {
2455
+ "rotation-x": Math.PI / 2,
2456
+ position: [
2457
+ debuggerScale * .53 * (invertTorque ? 1 : -1),
2458
+ 0,
2459
+ debuggerScale * .25
2460
+ ],
2461
+ geometry: debugAssets.thrustPointerGeo,
2462
+ material: debugAssets.thrustRingMat
2463
+ }), /* @__PURE__ */ React.createElement("mesh", {
2464
+ "rotation-x": Math.PI / 2,
2465
+ geometry: debugAssets.thrustRingGeo,
2466
+ material: debugAssets.thrustRingMat
2467
+ })), /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("mesh", {
2468
+ ref: xAxisPointRef,
2469
+ position: [
2470
+ debuggerScale,
2471
+ 0,
2472
+ 0
2473
+ ],
2474
+ geometry: debugAssets.axisPointGeo,
2475
+ material: debugAssets.xAxisPointMat
2476
+ }), /* @__PURE__ */ React.createElement("mesh", {
2477
+ ref: yAxisPointRef,
2478
+ position: [
2479
+ 0,
2480
+ debuggerScale,
2481
+ 0
2482
+ ],
2483
+ geometry: debugAssets.axisPointGeo,
2484
+ material: debugAssets.yAxisPointMat
2485
+ }), /* @__PURE__ */ React.createElement("mesh", {
2486
+ ref: zAxisPointRef,
2487
+ position: [
2488
+ 0,
2489
+ 0,
2490
+ debuggerScale
2491
+ ],
2492
+ geometry: debugAssets.axisPointGeo,
2493
+ material: debugAssets.zAxisPointMat
2494
+ })), /* @__PURE__ */ React.createElement("group", null, /* @__PURE__ */ React.createElement("arrowHelper", {
2495
+ ref: currThrustArrowRef,
2496
+ args: [
2497
+ new THREE.Vector3(0, invertThrust ? -1 : 1, 0),
2498
+ void 0,
2499
+ 0,
2500
+ "#87CEFA"
2501
+ ]
2502
+ }), /* @__PURE__ */ React.createElement("arrowHelper", {
2503
+ ref: currTorqueArrowRef,
2504
+ args: [
2505
+ new THREE.Vector3(0, invertTorque ? -1 : 1, 0),
2506
+ void 0,
2507
+ 0,
2508
+ "#FA8787"
2509
+ ]
2510
+ })))));
2511
+ });
2512
+ var ThrustPropeller_default = React.memo(ThrustPropeller);
2513
+ //#endregion
2514
+ //#region src/vehicle.ts
2515
+ /*!
2516
+ * Ecctrl
2517
+ * https://github.com/pmndrs/ecctrl
2518
+ *
2519
+ * SPDX-FileCopyrightText: 2023-2026 Erdong Chen
2520
+ * SPDX-License-Identifier: MIT
2521
+ */
2522
+ //#endregion
2523
+ export { ShapeCastWheel_default as n, EcctrlVehicle_default as r, ThrustPropeller_default as t };
2524
+
2525
+ //# sourceMappingURL=vehicle-AEqO39Wm.js.map