WheeledVehicleController.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/Physics/Vehicle/WheeledVehicleController.h>
  6. #include <Jolt/Physics/PhysicsSystem.h>
  7. #include <Jolt/ObjectStream/TypeDeclarations.h>
  8. #include <Jolt/Core/StreamIn.h>
  9. #include <Jolt/Core/StreamOut.h>
  10. #include <Jolt/Math/DynMatrix.h>
  11. #include <Jolt/Math/GaussianElimination.h>
  12. #ifdef JPH_DEBUG_RENDERER
  13. #include <Jolt/Renderer/DebugRenderer.h>
  14. #endif // JPH_DEBUG_RENDERER
  15. JPH_NAMESPACE_BEGIN
  16. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(WheeledVehicleControllerSettings)
  17. {
  18. JPH_ADD_BASE_CLASS(WheeledVehicleControllerSettings, VehicleControllerSettings)
  19. JPH_ADD_ATTRIBUTE(WheeledVehicleControllerSettings, mEngine)
  20. JPH_ADD_ATTRIBUTE(WheeledVehicleControllerSettings, mTransmission)
  21. JPH_ADD_ATTRIBUTE(WheeledVehicleControllerSettings, mDifferentials)
  22. JPH_ADD_ATTRIBUTE(WheeledVehicleControllerSettings, mDifferentialLimitedSlipRatio)
  23. }
  24. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(WheelSettingsWV)
  25. {
  26. JPH_ADD_ATTRIBUTE(WheelSettingsWV, mInertia)
  27. JPH_ADD_ATTRIBUTE(WheelSettingsWV, mAngularDamping)
  28. JPH_ADD_ATTRIBUTE(WheelSettingsWV, mMaxSteerAngle)
  29. JPH_ADD_ATTRIBUTE(WheelSettingsWV, mLongitudinalFriction)
  30. JPH_ADD_ATTRIBUTE(WheelSettingsWV, mLateralFriction)
  31. JPH_ADD_ATTRIBUTE(WheelSettingsWV, mMaxBrakeTorque)
  32. JPH_ADD_ATTRIBUTE(WheelSettingsWV, mMaxHandBrakeTorque)
  33. }
  34. WheelSettingsWV::WheelSettingsWV()
  35. {
  36. mLongitudinalFriction.Reserve(3);
  37. mLongitudinalFriction.AddPoint(0.0f, 0.0f);
  38. mLongitudinalFriction.AddPoint(0.06f, 1.2f);
  39. mLongitudinalFriction.AddPoint(0.2f, 1.0f);
  40. mLateralFriction.Reserve(3);
  41. mLateralFriction.AddPoint(0.0f, 0.0f);
  42. mLateralFriction.AddPoint(3.0f, 1.2f);
  43. mLateralFriction.AddPoint(20.0f, 1.0f);
  44. }
  45. void WheelSettingsWV::SaveBinaryState(StreamOut &inStream) const
  46. {
  47. inStream.Write(mInertia);
  48. inStream.Write(mAngularDamping);
  49. inStream.Write(mMaxSteerAngle);
  50. mLongitudinalFriction.SaveBinaryState(inStream);
  51. mLateralFriction.SaveBinaryState(inStream);
  52. inStream.Write(mMaxBrakeTorque);
  53. inStream.Write(mMaxHandBrakeTorque);
  54. }
  55. void WheelSettingsWV::RestoreBinaryState(StreamIn &inStream)
  56. {
  57. inStream.Read(mInertia);
  58. inStream.Read(mAngularDamping);
  59. inStream.Read(mMaxSteerAngle);
  60. mLongitudinalFriction.RestoreBinaryState(inStream);
  61. mLateralFriction.RestoreBinaryState(inStream);
  62. inStream.Read(mMaxBrakeTorque);
  63. inStream.Read(mMaxHandBrakeTorque);
  64. }
  65. WheelWV::WheelWV(const WheelSettingsWV &inSettings) :
  66. Wheel(inSettings)
  67. {
  68. JPH_ASSERT(inSettings.mInertia >= 0.0f);
  69. JPH_ASSERT(inSettings.mAngularDamping >= 0.0f);
  70. JPH_ASSERT(abs(inSettings.mMaxSteerAngle) <= 0.5f * JPH_PI);
  71. JPH_ASSERT(inSettings.mMaxBrakeTorque >= 0.0f);
  72. JPH_ASSERT(inSettings.mMaxHandBrakeTorque >= 0.0f);
  73. }
  74. void WheelWV::Update(float inDeltaTime, const VehicleConstraint &inConstraint)
  75. {
  76. const WheelSettingsWV *settings = GetSettings();
  77. // Angular damping: dw/dt = -c * w
  78. // Solution: w(t) = w(0) * e^(-c * t) or w2 = w1 * e^(-c * dt)
  79. // Taylor expansion of e^(-c * dt) = 1 - c * dt + ...
  80. // Since dt is usually in the order of 1/60 and c is a low number too this approximation is good enough
  81. mAngularVelocity *= max(0.0f, 1.0f - settings->mAngularDamping * inDeltaTime);
  82. // Update rotation of wheel
  83. mAngle = fmod(mAngle + mAngularVelocity * inDeltaTime, 2.0f * JPH_PI);
  84. if (mContactBody != nullptr)
  85. {
  86. const Body *body = inConstraint.GetVehicleBody();
  87. // Calculate relative velocity between wheel contact point and floor
  88. Vec3 relative_velocity = body->GetPointVelocity(mContactPosition) - mContactPointVelocity;
  89. // Cancel relative velocity in the normal plane
  90. relative_velocity -= mContactNormal.Dot(relative_velocity) * mContactNormal;
  91. float relative_longitudinal_velocity = relative_velocity.Dot(mContactLongitudinal);
  92. // Calculate longitudinal friction based on difference between velocity of rolling wheel and drive surface
  93. float relative_longitudinal_velocity_denom = Sign(relative_longitudinal_velocity) * max(1.0e-3f, abs(relative_longitudinal_velocity)); // Ensure we don't divide by zero
  94. mLongitudinalSlip = abs((mAngularVelocity * settings->mRadius - relative_longitudinal_velocity) / relative_longitudinal_velocity_denom);
  95. float longitudinal_slip_friction = settings->mLongitudinalFriction.GetValue(mLongitudinalSlip);
  96. // Calculate lateral friction based on slip angle
  97. float relative_velocity_len = relative_velocity.Length();
  98. float lateral_slip_angle = relative_velocity_len < 1.0e-3f? 0.0f : RadiansToDegrees(ACos(abs(relative_longitudinal_velocity) / relative_velocity_len));
  99. float lateral_slip_friction = settings->mLateralFriction.GetValue(lateral_slip_angle);
  100. // Tire friction
  101. mCombinedLongitudinalFriction = sqrt(longitudinal_slip_friction * mContactBody->GetFriction());
  102. mCombinedLateralFriction = sqrt(lateral_slip_friction * mContactBody->GetFriction());
  103. }
  104. else
  105. {
  106. // No collision
  107. mLongitudinalSlip = 0.0f;
  108. mCombinedLongitudinalFriction = mCombinedLateralFriction = 0.0f;
  109. }
  110. }
  111. VehicleController *WheeledVehicleControllerSettings::ConstructController(VehicleConstraint &inConstraint) const
  112. {
  113. return new WheeledVehicleController(*this, inConstraint);
  114. }
  115. void WheeledVehicleControllerSettings::SaveBinaryState(StreamOut &inStream) const
  116. {
  117. mEngine.SaveBinaryState(inStream);
  118. mTransmission.SaveBinaryState(inStream);
  119. uint32 num_differentials = (uint32)mDifferentials.size();
  120. inStream.Write(num_differentials);
  121. for (const VehicleDifferentialSettings &d : mDifferentials)
  122. d.SaveBinaryState(inStream);
  123. inStream.Write(mDifferentialLimitedSlipRatio);
  124. }
  125. void WheeledVehicleControllerSettings::RestoreBinaryState(StreamIn &inStream)
  126. {
  127. mEngine.RestoreBinaryState(inStream);
  128. mTransmission.RestoreBinaryState(inStream);
  129. uint32 num_differentials = 0;
  130. inStream.Read(num_differentials);
  131. mDifferentials.resize(num_differentials);
  132. for (VehicleDifferentialSettings &d : mDifferentials)
  133. d.RestoreBinaryState(inStream);
  134. inStream.Read(mDifferentialLimitedSlipRatio);
  135. }
  136. WheeledVehicleController::WheeledVehicleController(const WheeledVehicleControllerSettings &inSettings, VehicleConstraint &inConstraint) :
  137. VehicleController(inConstraint)
  138. {
  139. // Copy engine settings
  140. static_cast<VehicleEngineSettings &>(mEngine) = inSettings.mEngine;
  141. JPH_ASSERT(inSettings.mEngine.mMinRPM >= 0.0f);
  142. JPH_ASSERT(inSettings.mEngine.mMinRPM <= inSettings.mEngine.mMaxRPM);
  143. // Copy transmission settings
  144. static_cast<VehicleTransmissionSettings &>(mTransmission) = inSettings.mTransmission;
  145. #ifdef JPH_ENABLE_ASSERTS
  146. for (float r : inSettings.mTransmission.mGearRatios)
  147. JPH_ASSERT(r > 0.0f);
  148. for (float r : inSettings.mTransmission.mReverseGearRatios)
  149. JPH_ASSERT(r < 0.0f);
  150. #endif // JPH_ENABLE_ASSERTS
  151. JPH_ASSERT(inSettings.mTransmission.mSwitchTime >= 0.0f);
  152. JPH_ASSERT(inSettings.mTransmission.mShiftDownRPM > 0.0f);
  153. JPH_ASSERT(inSettings.mTransmission.mMode != ETransmissionMode::Auto || inSettings.mTransmission.mShiftUpRPM < inSettings.mEngine.mMaxRPM);
  154. JPH_ASSERT(inSettings.mTransmission.mShiftUpRPM > inSettings.mTransmission.mShiftDownRPM);
  155. JPH_ASSERT(inSettings.mTransmission.mClutchStrength > 0.0f);
  156. // Copy differential settings
  157. mDifferentials.resize(inSettings.mDifferentials.size());
  158. for (uint i = 0; i < mDifferentials.size(); ++i)
  159. {
  160. const VehicleDifferentialSettings &d = inSettings.mDifferentials[i];
  161. mDifferentials[i] = d;
  162. JPH_ASSERT(d.mDifferentialRatio > 0.0f);
  163. JPH_ASSERT(d.mLeftRightSplit >= 0.0f && d.mLeftRightSplit <= 1.0f);
  164. JPH_ASSERT(d.mEngineTorqueRatio >= 0.0f);
  165. JPH_ASSERT(d.mLimitedSlipRatio > 1.0f);
  166. }
  167. mDifferentialLimitedSlipRatio = inSettings.mDifferentialLimitedSlipRatio;
  168. JPH_ASSERT(mDifferentialLimitedSlipRatio > 1.0f);
  169. }
  170. void WheeledVehicleController::PreCollide(float inDeltaTime, PhysicsSystem &inPhysicsSystem)
  171. {
  172. JPH_PROFILE_FUNCTION();
  173. for (Wheel *w_base : mConstraint.GetWheels())
  174. {
  175. WheelWV *w = static_cast<WheelWV *>(w_base);
  176. // Set steering angle
  177. w->SetSteerAngle(-mRightInput * w->GetSettings()->mMaxSteerAngle);
  178. }
  179. }
  180. void WheeledVehicleController::PostCollide(float inDeltaTime, PhysicsSystem &inPhysicsSystem)
  181. {
  182. JPH_PROFILE_FUNCTION();
  183. // Remember old RPM so we're increasing or decreasing
  184. float old_engine_rpm = mEngine.GetCurrentRPM();
  185. Wheels &wheels = mConstraint.GetWheels();
  186. // Update wheel angle, do this before applying torque to the wheels (as friction will slow them down again)
  187. for (Wheel *w_base : wheels)
  188. {
  189. WheelWV *w = static_cast<WheelWV *>(w_base);
  190. w->Update(inDeltaTime, mConstraint);
  191. }
  192. // In auto transmission mode, don't accelerate the engine when switching gears
  193. float forward_input = abs(mForwardInput);
  194. if (mTransmission.mMode == ETransmissionMode::Auto)
  195. forward_input *= mTransmission.GetClutchFriction();
  196. // Apply damping if there is no acceleration
  197. if (forward_input < 1.0e-3f)
  198. mEngine.ApplyDamping(inDeltaTime);
  199. // Calculate engine torque
  200. float engine_torque = mEngine.GetTorque(forward_input);
  201. // Define a struct that contains information about driven differentials (i.e. that have wheels connected)
  202. struct DrivenDifferential
  203. {
  204. const VehicleDifferentialSettings * mDifferential;
  205. float mAngularVelocity;
  206. float mClutchToDifferentialTorqueRatio;
  207. float mTempTorqueFactor;
  208. };
  209. // Collect driven differentials and their speeds
  210. Array<DrivenDifferential> driven_differentials;
  211. driven_differentials.reserve(mDifferentials.size());
  212. float differential_omega_min = FLT_MAX, differential_omega_max = 0.0f;
  213. for (const VehicleDifferentialSettings &d : mDifferentials)
  214. {
  215. float avg_omega = 0.0f;
  216. int avg_omega_denom = 0;
  217. int indices[] = { d.mLeftWheel, d.mRightWheel };
  218. for (int idx : indices)
  219. if (idx != -1)
  220. {
  221. avg_omega += wheels[idx]->GetAngularVelocity();
  222. avg_omega_denom++;
  223. }
  224. if (avg_omega_denom > 0)
  225. {
  226. avg_omega = abs(avg_omega * d.mDifferentialRatio / float(avg_omega_denom)); // ignoring that the differentials may be rotating in different directions
  227. driven_differentials.push_back({ &d, avg_omega, d.mEngineTorqueRatio, 0 });
  228. // Remember min and max velocity
  229. differential_omega_min = min(differential_omega_min, avg_omega);
  230. differential_omega_max = max(differential_omega_max, avg_omega);
  231. }
  232. }
  233. if (mDifferentialLimitedSlipRatio < FLT_MAX // Limited slip differential needs to be turned on
  234. && differential_omega_max > differential_omega_min) // There needs to be a velocity difference
  235. {
  236. // Calculate factor based on relative speed of a differential
  237. float sum_factor = 0.0f;
  238. for (DrivenDifferential &d : driven_differentials)
  239. {
  240. // Differential with max velocity gets factor 0, differential with min velocity 1
  241. d.mTempTorqueFactor = (differential_omega_max - d.mAngularVelocity) / (differential_omega_max - differential_omega_min);
  242. sum_factor += d.mTempTorqueFactor;
  243. }
  244. // Normalize the result
  245. for (DrivenDifferential &d : driven_differentials)
  246. d.mTempTorqueFactor /= sum_factor;
  247. // Prevent div by zero
  248. differential_omega_min = max(1.0e-3f, differential_omega_min);
  249. differential_omega_max = max(1.0e-3f, differential_omega_max);
  250. // Map into a value that is 0 when the wheels are turning at an equal rate and 1 when the wheels are turning at mDifferentialLimitedSlipRatio
  251. float alpha = min((differential_omega_max / differential_omega_min - 1.0f) / (mDifferentialLimitedSlipRatio - 1.0f), 1.0f);
  252. JPH_ASSERT(alpha >= 0.0f);
  253. float one_min_alpha = 1.0f - alpha;
  254. // Update torque ratio for all differentials
  255. for (DrivenDifferential &d : driven_differentials)
  256. d.mClutchToDifferentialTorqueRatio = one_min_alpha * d.mClutchToDifferentialTorqueRatio + alpha * d.mTempTorqueFactor;
  257. }
  258. #ifdef JPH_ENABLE_ASSERTS
  259. // Assert the values add up to 1
  260. float sum_torque_factors = 0.0f;
  261. for (DrivenDifferential &d : driven_differentials)
  262. sum_torque_factors += d.mClutchToDifferentialTorqueRatio;
  263. JPH_ASSERT(abs(sum_torque_factors - 1.0f) < 1.0e-6f);
  264. #endif // JPH_ENABLE_ASSERTS
  265. // Define a struct that collects information about the wheels that connect to the engine
  266. struct DrivenWheel
  267. {
  268. WheelWV * mWheel;
  269. float mClutchToWheelRatio;
  270. float mClutchToWheelTorqueRatio;
  271. };
  272. Array<DrivenWheel> driven_wheels;
  273. driven_wheels.reserve(wheels.size());
  274. // Collect driven wheels
  275. float transmission_ratio = mTransmission.GetCurrentRatio();
  276. for (const DrivenDifferential &dd : driven_differentials)
  277. {
  278. VehicleDifferentialSettings d = *dd.mDifferential;
  279. WheelWV *wl = d.mLeftWheel != -1? static_cast<WheelWV *>(wheels[d.mLeftWheel]) : nullptr;
  280. WheelWV *wr = d.mRightWheel != -1? static_cast<WheelWV *>(wheels[d.mRightWheel]) : nullptr;
  281. float clutch_to_wheel_ratio = transmission_ratio * d.mDifferentialRatio;
  282. if (wl != nullptr && wr != nullptr)
  283. {
  284. // Calculate torque ratio
  285. float ratio_l, ratio_r;
  286. d.CalculateTorqueRatio(wl->GetAngularVelocity(), wr->GetAngularVelocity(), ratio_l, ratio_r);
  287. // Add both wheels
  288. driven_wheels.push_back({ wl, clutch_to_wheel_ratio, dd.mClutchToDifferentialTorqueRatio * ratio_l });
  289. driven_wheels.push_back({ wr, clutch_to_wheel_ratio, dd.mClutchToDifferentialTorqueRatio * ratio_r });
  290. }
  291. else if (wl != nullptr)
  292. {
  293. // Only left wheel, all power to left
  294. driven_wheels.push_back({ wl, clutch_to_wheel_ratio, dd.mClutchToDifferentialTorqueRatio });
  295. }
  296. else if (wr != nullptr)
  297. {
  298. // Only right wheel, all power to right
  299. driven_wheels.push_back({ wr, clutch_to_wheel_ratio, dd.mClutchToDifferentialTorqueRatio });
  300. }
  301. }
  302. bool solved = false;
  303. if (!driven_wheels.empty())
  304. {
  305. // Define the torque at the clutch at time t as:
  306. //
  307. // tc(t):=S*(we(t)-sum(R(j)*ww(j,t),j,1,N)/N)
  308. //
  309. // Where:
  310. // S is the total strength of clutch (= friction * strength)
  311. // we(t) is the engine angular velocity at time t
  312. // R(j) is the total gear ratio of clutch to wheel for wheel j
  313. // ww(j,t) is the angular velocity of wheel j at time t
  314. // N is the amount of wheels
  315. //
  316. // The torque that increases the engine angular velocity at time t is:
  317. //
  318. // te(t):=TE-tc(t)
  319. //
  320. // Where:
  321. // TE is the torque delivered by the engine
  322. //
  323. // The torque that increases the wheel angular velocity for wheel i at time t is:
  324. //
  325. // tw(i,t):=TW(i)+R(i)*F(i)*tc(t)
  326. //
  327. // Where:
  328. // TW(i) is the torque applied to the wheel outside of the engine (brake + torque due to friction with the ground)
  329. // F(i) is the fraction of the engine torque applied from engine to wheel i
  330. //
  331. // Because the angular accelaration and torque are connected through: Torque = I * dw/dt
  332. //
  333. // We have the angular acceleration of the engine at time t:
  334. //
  335. // ddt_we(t):=te(t)/Ie
  336. //
  337. // Where:
  338. // Ie is the inertia of the engine
  339. //
  340. // We have the angular acceleration of wheel i at time t:
  341. //
  342. // ddt_ww(i,t):=tw(i,t)/Iw(i)
  343. //
  344. // Where:
  345. // Iw(i) is the inertia of wheel i
  346. //
  347. // We could take a simple Euler step to calculate the resulting accelerations but because the system is very stiff this turns out to be unstable, so we need to use implicit Euler instead:
  348. //
  349. // we(t+dt)=we(t)+dt*ddt_we(t+dt)
  350. //
  351. // and:
  352. //
  353. // ww(i,t+dt)=ww(i,t)+dt*ddt_ww(i,t+dt)
  354. //
  355. // Expanding both equations (the equations above are in wxMaxima format and this can easily be done by expand(%)):
  356. //
  357. // For wheel:
  358. //
  359. // ww(i,t+dt) + (S*dt*F(i)*R(i)*sum(R(j)*ww(j,t+dt),j,1,N))/(N*Iw(i)) - (S*dt*F(i)*R(i)*we(t+dt))/Iw(i) = ww(i,t)+(dt*TW(i))/Iw(i)
  360. //
  361. // For engine:
  362. //
  363. // we(t+dt) + (S*dt*we(t+dt))/Ie - (S*dt*sum(R(j)*ww(j,t+dt),j,1,N))/(Ie*N) = we(t)+(TE*dt)/Ie
  364. //
  365. // Defining a vector w(t) = (ww(1, t), ww(2, t), ..., ww(N, t), we(t)) we can write both equations as a matrix multiplication:
  366. //
  367. // a * w(t + dt) = b
  368. //
  369. // We then invert the matrix to get the new angular velocities.
  370. //
  371. // Note that currently we set TW(i) = 0 so that the wheels will accelerate as if no external force was applied to them. These external forces are applied later and will slow down the wheel before the end of the time step.
  372. // Dimension of matrix is N + 1
  373. int n = (int)driven_wheels.size() + 1;
  374. // Last column of w is for the engine angular velocity
  375. int engine = n - 1;
  376. // Define a and b
  377. DynMatrix a(n, n);
  378. DynMatrix b(n, 1);
  379. // Get number of driven wheels as a float
  380. float num_driven_wheels_float = float(driven_wheels.size());
  381. // Angular velocity of engine
  382. float w_engine = mEngine.GetAngularVelocity();
  383. // Calculate the total strength of the clutch
  384. float clutch_strength = transmission_ratio != 0.0f? mTransmission.GetClutchFriction() * mTransmission.mClutchStrength : 0.0f;
  385. // dt / Ie
  386. float dt_div_ie = inDeltaTime / mEngine.mInertia;
  387. // Iterate the rows for the wheels
  388. for (int i = 0; i < (int)driven_wheels.size(); ++i)
  389. {
  390. const DrivenWheel &w_i = driven_wheels[i];
  391. // dt / Iw
  392. float dt_div_iw = inDeltaTime / w_i.mWheel->GetSettings()->mInertia;
  393. // S * R(i)
  394. float s_r = clutch_strength * w_i.mClutchToWheelRatio;
  395. // dt * S * R(i) * F(i) / Iw
  396. float dt_s_r_f_div_iw = dt_div_iw * s_r * w_i.mClutchToWheelTorqueRatio;
  397. // Fill in the columns of a for wheel j
  398. for (int j = 0; j < (int)driven_wheels.size(); ++j)
  399. {
  400. const DrivenWheel &w_j = driven_wheels[j];
  401. a(i, j) = dt_s_r_f_div_iw * w_j.mClutchToWheelRatio / num_driven_wheels_float;
  402. }
  403. // Add ww(i, t+dt)
  404. a(i, i) += 1.0f;
  405. // Add the column for the engine
  406. a(i, engine) = -dt_s_r_f_div_iw;
  407. // Fill in the constant b
  408. b(i, 0) = w_i.mWheel->GetAngularVelocity(); // + dt_div_iw * (brake and tire torques)
  409. // To avoid looping over the wheels again, we also fill in the wheel columns of the engine row here
  410. a(engine, i) = -dt_div_ie * s_r / num_driven_wheels_float;
  411. }
  412. // Finalize the engine row
  413. a(engine, engine) = (1.0f + dt_div_ie * clutch_strength);
  414. b(engine, 0) = w_engine + dt_div_ie * engine_torque;
  415. // Solve the linear equation
  416. if (GaussianElimination(a, b))
  417. {
  418. // Update the angular velocities for the wheels
  419. for (int i = 0; i < (int)driven_wheels.size(); ++i)
  420. {
  421. DrivenWheel &dw1 = driven_wheels[i];
  422. dw1.mWheel->SetAngularVelocity(b(i, 0));
  423. }
  424. // Update the engine RPM
  425. mEngine.SetCurrentRPM(b(engine, 0) * VehicleEngine::cAngularVelocityToRPM);
  426. // The speeds have been solved
  427. solved = true;
  428. }
  429. else
  430. {
  431. JPH_ASSERT(false, "New engine/wheel speeds could not be calculated!");
  432. }
  433. }
  434. if (!solved)
  435. {
  436. // Engine not connected to wheels, apply all torque to engine rotation
  437. mEngine.ApplyTorque(engine_torque, inDeltaTime);
  438. }
  439. // Calculate if any of the wheels are slipping, this is used to prevent gear switching
  440. bool wheels_slipping = false;
  441. for (const DrivenWheel &w : driven_wheels)
  442. wheels_slipping |= w.mClutchToWheelTorqueRatio > 0.0f && (!w.mWheel->HasContact() || w.mWheel->mLongitudinalSlip > 0.1f);
  443. // Only allow shifting up when we're not slipping and we're increasing our RPM.
  444. // After a jump, we have a very high engine RPM but once we hit the ground the RPM should be decreasing and we don't want to shift up
  445. // during that time.
  446. bool can_shift_up = !wheels_slipping && mEngine.GetCurrentRPM() >= old_engine_rpm;
  447. // Update transmission
  448. mTransmission.Update(inDeltaTime, mEngine.GetCurrentRPM(), mForwardInput, can_shift_up);
  449. // Braking
  450. for (Wheel *w_base : wheels)
  451. {
  452. WheelWV *w = static_cast<WheelWV *>(w_base);
  453. const WheelSettingsWV *settings = w->GetSettings();
  454. // Combine brake with hand brake torque
  455. float brake_torque = mBrakeInput * settings->mMaxBrakeTorque + mHandBrakeInput * settings->mMaxHandBrakeTorque;
  456. if (brake_torque > 0.0f)
  457. {
  458. // Calculate how much torque is needed to stop the wheels from rotating in this time step
  459. float brake_torque_to_lock_wheels = abs(w->GetAngularVelocity()) * settings->mInertia / inDeltaTime;
  460. if (brake_torque > brake_torque_to_lock_wheels)
  461. {
  462. // Wheels are locked
  463. w->SetAngularVelocity(0.0f);
  464. w->mBrakeImpulse = (brake_torque - brake_torque_to_lock_wheels) * inDeltaTime / settings->mRadius;
  465. }
  466. else
  467. {
  468. // Slow down the wheels
  469. w->ApplyTorque(-Sign(w->GetAngularVelocity()) * brake_torque, inDeltaTime);
  470. w->mBrakeImpulse = 0.0f;
  471. }
  472. }
  473. else
  474. {
  475. // Not braking
  476. w->mBrakeImpulse = 0.0f;
  477. }
  478. }
  479. }
  480. bool WheeledVehicleController::SolveLongitudinalAndLateralConstraints(float inDeltaTime)
  481. {
  482. bool impulse = false;
  483. for (Wheel *w_base : mConstraint.GetWheels())
  484. if (w_base->HasContact())
  485. {
  486. WheelWV *w = static_cast<WheelWV *>(w_base);
  487. const WheelSettingsWV *settings = w->GetSettings();
  488. // Calculate max impulse that we can apply on the ground
  489. float max_longitudinal_friction_impulse = w->mCombinedLongitudinalFriction * w->GetSuspensionLambda();
  490. // Calculate relative velocity between wheel contact point and floor in longitudinal direction
  491. Vec3 relative_velocity = mConstraint.GetVehicleBody()->GetPointVelocity(w->GetContactPosition()) - w->GetContactPointVelocity();
  492. float relative_longitudinal_velocity = relative_velocity.Dot(w->GetContactLongitudinal());
  493. // Calculate brake force to apply
  494. float min_longitudinal_impulse, max_longitudinal_impulse;
  495. if (w->mBrakeImpulse != 0.0f)
  496. {
  497. // Limit brake force by max tire friction
  498. float brake_impulse = min(w->mBrakeImpulse, max_longitudinal_friction_impulse);
  499. // Check which direction the brakes should be applied (we don't want to apply an impulse that would accelerate the vehicle)
  500. if (relative_longitudinal_velocity >= 0.0f)
  501. {
  502. min_longitudinal_impulse = -brake_impulse;
  503. max_longitudinal_impulse = 0.0f;
  504. }
  505. else
  506. {
  507. min_longitudinal_impulse = 0.0f;
  508. max_longitudinal_impulse = brake_impulse;
  509. }
  510. // Longitudinal impulse, note that we assume that once the wheels are locked that the brakes have more than enough torque to keep the wheels locked so we exclude any rotation deltas
  511. impulse |= w->SolveLongitudinalConstraintPart(mConstraint, min_longitudinal_impulse, max_longitudinal_impulse);
  512. }
  513. else
  514. {
  515. // Assume we want to apply an angular impulse that makes the delta velocity between wheel and ground zero in one time step, calculate the amount of linear impulse needed to do that
  516. float desired_angular_velocity = relative_longitudinal_velocity / settings->mRadius;
  517. float linear_impulse = (w->GetAngularVelocity() - desired_angular_velocity) * settings->mInertia / settings->mRadius;
  518. // Limit the impulse by max tire friction
  519. min_longitudinal_impulse = max_longitudinal_impulse = w->GetLongitudinalLambda() + Sign(linear_impulse) * min(abs(linear_impulse), max_longitudinal_friction_impulse);
  520. // Longitudinal impulse
  521. float prev_lambda = w->GetLongitudinalLambda();
  522. impulse |= w->SolveLongitudinalConstraintPart(mConstraint, min_longitudinal_impulse, max_longitudinal_impulse);
  523. // Update the angular velocity of the wheels according to the lambda that was applied
  524. w->SetAngularVelocity(w->GetAngularVelocity() - (w->GetLongitudinalLambda() - prev_lambda) * settings->mRadius / settings->mInertia);
  525. }
  526. }
  527. for (Wheel *w_base : mConstraint.GetWheels())
  528. if (w_base->HasContact())
  529. {
  530. WheelWV *w = static_cast<WheelWV *>(w_base);
  531. // Lateral friction
  532. float max_lateral_friction_impulse = w->mCombinedLateralFriction * w->GetSuspensionLambda();
  533. impulse |= w->SolveLateralConstraintPart(mConstraint, -max_lateral_friction_impulse, max_lateral_friction_impulse);
  534. }
  535. return impulse;
  536. }
  537. #ifdef JPH_DEBUG_RENDERER
  538. void WheeledVehicleController::Draw(DebugRenderer *inRenderer) const
  539. {
  540. float constraint_size = mConstraint.GetDrawConstraintSize();
  541. // Draw RPM
  542. Body *body = mConstraint.GetVehicleBody();
  543. Vec3 rpm_meter_up = body->GetRotation() * mConstraint.GetLocalUp();
  544. RVec3 rpm_meter_pos = body->GetPosition() + body->GetRotation() * mRPMMeterPosition;
  545. Vec3 rpm_meter_fwd = body->GetRotation() * mConstraint.GetLocalForward();
  546. mEngine.DrawRPM(inRenderer, rpm_meter_pos, rpm_meter_fwd, rpm_meter_up, mRPMMeterSize, mTransmission.mShiftDownRPM, mTransmission.mShiftUpRPM);
  547. // Draw current vehicle state
  548. String status = StringFormat("Forward: %.1f, Right: %.1f\nBrake: %.1f, HandBrake: %.1f\n"
  549. "Gear: %d, Clutch: %.1f\nEngineRPM: %.0f, V: %.1f km/h",
  550. (double)mForwardInput, (double)mRightInput, (double)mBrakeInput, (double)mHandBrakeInput,
  551. mTransmission.GetCurrentGear(), (double)mTransmission.GetClutchFriction(), (double)mEngine.GetCurrentRPM(), (double)body->GetLinearVelocity().Length() * 3.6);
  552. inRenderer->DrawText3D(body->GetPosition(), status, Color::sWhite, constraint_size);
  553. for (const Wheel *w_base : mConstraint.GetWheels())
  554. {
  555. const WheelWV *w = static_cast<const WheelWV *>(w_base);
  556. const WheelSettings *settings = w->GetSettings();
  557. // Calculate where the suspension attaches to the body in world space
  558. RVec3 ws_position = body->GetCenterOfMassPosition() + body->GetRotation() * (settings->mPosition - body->GetShape()->GetCenterOfMass());
  559. Vec3 ws_direction = body->GetRotation() * settings->mDirection;
  560. // Draw suspension
  561. RVec3 min_suspension_pos = ws_position + ws_direction * settings->mSuspensionMinLength;
  562. RVec3 max_suspension_pos = ws_position + ws_direction * settings->mSuspensionMaxLength;
  563. inRenderer->DrawLine(ws_position, min_suspension_pos, Color::sRed);
  564. inRenderer->DrawLine(min_suspension_pos, max_suspension_pos, Color::sGreen);
  565. // Draw current length
  566. RVec3 cur_suspension_pos = ws_position + ws_direction * w->GetSuspensionLength();
  567. inRenderer->DrawMarker(cur_suspension_pos, w->GetSuspensionLength() < settings->mSuspensionMinLength? Color::sRed : Color::sGreen, constraint_size);
  568. if (w->HasContact())
  569. {
  570. // Draw contact
  571. inRenderer->DrawLine(w->GetContactPosition(), w->GetContactPosition() + w->GetContactNormal(), Color::sYellow);
  572. inRenderer->DrawLine(w->GetContactPosition(), w->GetContactPosition() + w->GetContactLongitudinal(), Color::sRed);
  573. inRenderer->DrawLine(w->GetContactPosition(), w->GetContactPosition() + w->GetContactLateral(), Color::sBlue);
  574. DebugRenderer::sInstance->DrawText3D(cur_suspension_pos, StringFormat("W: %.1f, S: %.2f\nSlip: %.2f, FrLateral: %.1f, FrLong: %.1f", (double)w->GetAngularVelocity(), (double)w->GetSuspensionLength(), (double)w->mLongitudinalSlip, (double)w->mCombinedLateralFriction, (double)w->mCombinedLongitudinalFriction), Color::sWhite, constraint_size);
  575. }
  576. else
  577. {
  578. // Draw 'no hit'
  579. DebugRenderer::sInstance->DrawText3D(cur_suspension_pos, StringFormat("W: %.1f", (double)w->GetAngularVelocity()), Color::sRed, constraint_size);
  580. }
  581. }
  582. }
  583. #endif // JPH_DEBUG_RENDERER
  584. void WheeledVehicleController::SaveState(StateRecorder &inStream) const
  585. {
  586. inStream.Write(mForwardInput);
  587. inStream.Write(mRightInput);
  588. inStream.Write(mBrakeInput);
  589. inStream.Write(mHandBrakeInput);
  590. mEngine.SaveState(inStream);
  591. mTransmission.SaveState(inStream);
  592. }
  593. void WheeledVehicleController::RestoreState(StateRecorder &inStream)
  594. {
  595. inStream.Read(mForwardInput);
  596. inStream.Read(mRightInput);
  597. inStream.Read(mBrakeInput);
  598. inStream.Read(mHandBrakeInput);
  599. mEngine.RestoreState(inStream);
  600. mTransmission.RestoreState(inStream);
  601. }
  602. JPH_NAMESPACE_END