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