WheeledVehicleController.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  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. VehicleConstraint::CombineFunction combine_friction = inConstraint.GetCombineFriction();
  102. mCombinedLongitudinalFriction = combine_friction(longitudinal_slip_friction, *mContactBody, mContactSubShapeID);
  103. mCombinedLateralFriction = combine_friction(lateral_slip_friction, *mContactBody, mContactSubShapeID);
  104. }
  105. else
  106. {
  107. // No collision
  108. mLongitudinalSlip = 0.0f;
  109. mCombinedLongitudinalFriction = mCombinedLateralFriction = 0.0f;
  110. }
  111. }
  112. VehicleController *WheeledVehicleControllerSettings::ConstructController(VehicleConstraint &inConstraint) const
  113. {
  114. return new WheeledVehicleController(*this, inConstraint);
  115. }
  116. void WheeledVehicleControllerSettings::SaveBinaryState(StreamOut &inStream) const
  117. {
  118. mEngine.SaveBinaryState(inStream);
  119. mTransmission.SaveBinaryState(inStream);
  120. uint32 num_differentials = (uint32)mDifferentials.size();
  121. inStream.Write(num_differentials);
  122. for (const VehicleDifferentialSettings &d : mDifferentials)
  123. d.SaveBinaryState(inStream);
  124. inStream.Write(mDifferentialLimitedSlipRatio);
  125. }
  126. void WheeledVehicleControllerSettings::RestoreBinaryState(StreamIn &inStream)
  127. {
  128. mEngine.RestoreBinaryState(inStream);
  129. mTransmission.RestoreBinaryState(inStream);
  130. uint32 num_differentials = 0;
  131. inStream.Read(num_differentials);
  132. mDifferentials.resize(num_differentials);
  133. for (VehicleDifferentialSettings &d : mDifferentials)
  134. d.RestoreBinaryState(inStream);
  135. inStream.Read(mDifferentialLimitedSlipRatio);
  136. }
  137. WheeledVehicleController::WheeledVehicleController(const WheeledVehicleControllerSettings &inSettings, VehicleConstraint &inConstraint) :
  138. VehicleController(inConstraint)
  139. {
  140. // Copy engine settings
  141. static_cast<VehicleEngineSettings &>(mEngine) = inSettings.mEngine;
  142. JPH_ASSERT(inSettings.mEngine.mMinRPM >= 0.0f);
  143. JPH_ASSERT(inSettings.mEngine.mMinRPM <= inSettings.mEngine.mMaxRPM);
  144. // Copy transmission settings
  145. static_cast<VehicleTransmissionSettings &>(mTransmission) = inSettings.mTransmission;
  146. #ifdef JPH_ENABLE_ASSERTS
  147. for (float r : inSettings.mTransmission.mGearRatios)
  148. JPH_ASSERT(r > 0.0f);
  149. for (float r : inSettings.mTransmission.mReverseGearRatios)
  150. JPH_ASSERT(r < 0.0f);
  151. #endif // JPH_ENABLE_ASSERTS
  152. JPH_ASSERT(inSettings.mTransmission.mSwitchTime >= 0.0f);
  153. JPH_ASSERT(inSettings.mTransmission.mShiftDownRPM > 0.0f);
  154. JPH_ASSERT(inSettings.mTransmission.mMode != ETransmissionMode::Auto || inSettings.mTransmission.mShiftUpRPM < inSettings.mEngine.mMaxRPM);
  155. JPH_ASSERT(inSettings.mTransmission.mShiftUpRPM > inSettings.mTransmission.mShiftDownRPM);
  156. JPH_ASSERT(inSettings.mTransmission.mClutchStrength > 0.0f);
  157. // Copy differential settings
  158. mDifferentials.resize(inSettings.mDifferentials.size());
  159. for (uint i = 0; i < mDifferentials.size(); ++i)
  160. {
  161. const VehicleDifferentialSettings &d = inSettings.mDifferentials[i];
  162. mDifferentials[i] = d;
  163. JPH_ASSERT(d.mDifferentialRatio > 0.0f);
  164. JPH_ASSERT(d.mLeftRightSplit >= 0.0f && d.mLeftRightSplit <= 1.0f);
  165. JPH_ASSERT(d.mEngineTorqueRatio >= 0.0f);
  166. JPH_ASSERT(d.mLimitedSlipRatio > 1.0f);
  167. }
  168. mDifferentialLimitedSlipRatio = inSettings.mDifferentialLimitedSlipRatio;
  169. JPH_ASSERT(mDifferentialLimitedSlipRatio > 1.0f);
  170. }
  171. bool WheeledVehicleController::AllowSleep() const
  172. {
  173. return mForwardInput == 0.0f // No user input
  174. && mEngine.GetCurrentRPM() <= 1.01f * mEngine.mMinRPM; // Engine is idling
  175. }
  176. void WheeledVehicleController::PreCollide(float inDeltaTime, PhysicsSystem &inPhysicsSystem)
  177. {
  178. JPH_PROFILE_FUNCTION();
  179. for (Wheel *w_base : mConstraint.GetWheels())
  180. {
  181. WheelWV *w = static_cast<WheelWV *>(w_base);
  182. // Set steering angle
  183. w->SetSteerAngle(-mRightInput * w->GetSettings()->mMaxSteerAngle);
  184. }
  185. }
  186. void WheeledVehicleController::PostCollide(float inDeltaTime, PhysicsSystem &inPhysicsSystem)
  187. {
  188. JPH_PROFILE_FUNCTION();
  189. // Remember old RPM so we're increasing or decreasing
  190. float old_engine_rpm = mEngine.GetCurrentRPM();
  191. Wheels &wheels = mConstraint.GetWheels();
  192. // Update wheel angle, do this before applying torque to the wheels (as friction will slow them down again)
  193. for (Wheel *w_base : wheels)
  194. {
  195. WheelWV *w = static_cast<WheelWV *>(w_base);
  196. w->Update(inDeltaTime, mConstraint);
  197. }
  198. // In auto transmission mode, don't accelerate the engine when switching gears
  199. float forward_input = abs(mForwardInput);
  200. if (mTransmission.mMode == ETransmissionMode::Auto)
  201. forward_input *= mTransmission.GetClutchFriction();
  202. // Apply damping if there is no acceleration
  203. if (forward_input < 1.0e-3f)
  204. mEngine.ApplyDamping(inDeltaTime);
  205. // Calculate engine torque
  206. float engine_torque = mEngine.GetTorque(forward_input);
  207. // Define a struct that contains information about driven differentials (i.e. that have wheels connected)
  208. struct DrivenDifferential
  209. {
  210. const VehicleDifferentialSettings * mDifferential;
  211. float mAngularVelocity;
  212. float mClutchToDifferentialTorqueRatio;
  213. float mTempTorqueFactor;
  214. };
  215. // Collect driven differentials and their speeds
  216. Array<DrivenDifferential> driven_differentials;
  217. driven_differentials.reserve(mDifferentials.size());
  218. float differential_omega_min = FLT_MAX, differential_omega_max = 0.0f;
  219. for (const VehicleDifferentialSettings &d : mDifferentials)
  220. {
  221. float avg_omega = 0.0f;
  222. int avg_omega_denom = 0;
  223. int indices[] = { d.mLeftWheel, d.mRightWheel };
  224. for (int idx : indices)
  225. if (idx != -1)
  226. {
  227. avg_omega += wheels[idx]->GetAngularVelocity();
  228. avg_omega_denom++;
  229. }
  230. if (avg_omega_denom > 0)
  231. {
  232. avg_omega = abs(avg_omega * d.mDifferentialRatio / float(avg_omega_denom)); // ignoring that the differentials may be rotating in different directions
  233. driven_differentials.push_back({ &d, avg_omega, d.mEngineTorqueRatio, 0 });
  234. // Remember min and max velocity
  235. differential_omega_min = min(differential_omega_min, avg_omega);
  236. differential_omega_max = max(differential_omega_max, avg_omega);
  237. }
  238. }
  239. if (mDifferentialLimitedSlipRatio < FLT_MAX // Limited slip differential needs to be turned on
  240. && differential_omega_max > differential_omega_min) // There needs to be a velocity difference
  241. {
  242. // Calculate factor based on relative speed of a differential
  243. float sum_factor = 0.0f;
  244. for (DrivenDifferential &d : driven_differentials)
  245. {
  246. // Differential with max velocity gets factor 0, differential with min velocity 1
  247. d.mTempTorqueFactor = (differential_omega_max - d.mAngularVelocity) / (differential_omega_max - differential_omega_min);
  248. sum_factor += d.mTempTorqueFactor;
  249. }
  250. // Normalize the result
  251. for (DrivenDifferential &d : driven_differentials)
  252. d.mTempTorqueFactor /= sum_factor;
  253. // Prevent div by zero
  254. differential_omega_min = max(1.0e-3f, differential_omega_min);
  255. differential_omega_max = max(1.0e-3f, differential_omega_max);
  256. // 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
  257. float alpha = min((differential_omega_max / differential_omega_min - 1.0f) / (mDifferentialLimitedSlipRatio - 1.0f), 1.0f);
  258. JPH_ASSERT(alpha >= 0.0f);
  259. float one_min_alpha = 1.0f - alpha;
  260. // Update torque ratio for all differentials
  261. for (DrivenDifferential &d : driven_differentials)
  262. d.mClutchToDifferentialTorqueRatio = one_min_alpha * d.mClutchToDifferentialTorqueRatio + alpha * d.mTempTorqueFactor;
  263. }
  264. #ifdef JPH_ENABLE_ASSERTS
  265. // Assert the values add up to 1
  266. float sum_torque_factors = 0.0f;
  267. for (DrivenDifferential &d : driven_differentials)
  268. sum_torque_factors += d.mClutchToDifferentialTorqueRatio;
  269. JPH_ASSERT(abs(sum_torque_factors - 1.0f) < 1.0e-6f);
  270. #endif // JPH_ENABLE_ASSERTS
  271. // Define a struct that collects information about the wheels that connect to the engine
  272. struct DrivenWheel
  273. {
  274. WheelWV * mWheel;
  275. float mClutchToWheelRatio;
  276. float mClutchToWheelTorqueRatio;
  277. };
  278. Array<DrivenWheel> driven_wheels;
  279. driven_wheels.reserve(wheels.size());
  280. // Collect driven wheels
  281. float transmission_ratio = mTransmission.GetCurrentRatio();
  282. for (const DrivenDifferential &dd : driven_differentials)
  283. {
  284. VehicleDifferentialSettings d = *dd.mDifferential;
  285. WheelWV *wl = d.mLeftWheel != -1? static_cast<WheelWV *>(wheels[d.mLeftWheel]) : nullptr;
  286. WheelWV *wr = d.mRightWheel != -1? static_cast<WheelWV *>(wheels[d.mRightWheel]) : nullptr;
  287. float clutch_to_wheel_ratio = transmission_ratio * d.mDifferentialRatio;
  288. if (wl != nullptr && wr != nullptr)
  289. {
  290. // Calculate torque ratio
  291. float ratio_l, ratio_r;
  292. d.CalculateTorqueRatio(wl->GetAngularVelocity(), wr->GetAngularVelocity(), ratio_l, ratio_r);
  293. // Add both wheels
  294. driven_wheels.push_back({ wl, clutch_to_wheel_ratio, dd.mClutchToDifferentialTorqueRatio * ratio_l });
  295. driven_wheels.push_back({ wr, clutch_to_wheel_ratio, dd.mClutchToDifferentialTorqueRatio * ratio_r });
  296. }
  297. else if (wl != nullptr)
  298. {
  299. // Only left wheel, all power to left
  300. driven_wheels.push_back({ wl, clutch_to_wheel_ratio, dd.mClutchToDifferentialTorqueRatio });
  301. }
  302. else if (wr != nullptr)
  303. {
  304. // Only right wheel, all power to right
  305. driven_wheels.push_back({ wr, clutch_to_wheel_ratio, dd.mClutchToDifferentialTorqueRatio });
  306. }
  307. }
  308. bool solved = false;
  309. if (!driven_wheels.empty())
  310. {
  311. // Define the torque at the clutch at time t as:
  312. //
  313. // tc(t):=S*(we(t)-sum(R(j)*ww(j,t),j,1,N)/N)
  314. //
  315. // Where:
  316. // S is the total strength of clutch (= friction * strength)
  317. // we(t) is the engine angular velocity at time t
  318. // R(j) is the total gear ratio of clutch to wheel for wheel j
  319. // ww(j,t) is the angular velocity of wheel j at time t
  320. // N is the amount of wheels
  321. //
  322. // The torque that increases the engine angular velocity at time t is:
  323. //
  324. // te(t):=TE-tc(t)
  325. //
  326. // Where:
  327. // TE is the torque delivered by the engine
  328. //
  329. // The torque that increases the wheel angular velocity for wheel i at time t is:
  330. //
  331. // tw(i,t):=TW(i)+R(i)*F(i)*tc(t)
  332. //
  333. // Where:
  334. // TW(i) is the torque applied to the wheel outside of the engine (brake + torque due to friction with the ground)
  335. // F(i) is the fraction of the engine torque applied from engine to wheel i
  336. //
  337. // Because the angular accelaration and torque are connected through: Torque = I * dw/dt
  338. //
  339. // We have the angular acceleration of the engine at time t:
  340. //
  341. // ddt_we(t):=te(t)/Ie
  342. //
  343. // Where:
  344. // Ie is the inertia of the engine
  345. //
  346. // We have the angular acceleration of wheel i at time t:
  347. //
  348. // ddt_ww(i,t):=tw(i,t)/Iw(i)
  349. //
  350. // Where:
  351. // Iw(i) is the inertia of wheel i
  352. //
  353. // 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:
  354. //
  355. // we(t+dt)=we(t)+dt*ddt_we(t+dt)
  356. //
  357. // and:
  358. //
  359. // ww(i,t+dt)=ww(i,t)+dt*ddt_ww(i,t+dt)
  360. //
  361. // Expanding both equations (the equations above are in wxMaxima format and this can easily be done by expand(%)):
  362. //
  363. // For wheel:
  364. //
  365. // 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)
  366. //
  367. // For engine:
  368. //
  369. // 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
  370. //
  371. // 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:
  372. //
  373. // a * w(t + dt) = b
  374. //
  375. // We then invert the matrix to get the new angular velocities.
  376. //
  377. // 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.
  378. // Dimension of matrix is N + 1
  379. int n = (int)driven_wheels.size() + 1;
  380. // Last column of w is for the engine angular velocity
  381. int engine = n - 1;
  382. // Define a and b
  383. DynMatrix a(n, n);
  384. DynMatrix b(n, 1);
  385. // Get number of driven wheels as a float
  386. float num_driven_wheels_float = float(driven_wheels.size());
  387. // Angular velocity of engine
  388. float w_engine = mEngine.GetAngularVelocity();
  389. // Calculate the total strength of the clutch
  390. float clutch_strength = transmission_ratio != 0.0f? mTransmission.GetClutchFriction() * mTransmission.mClutchStrength : 0.0f;
  391. // dt / Ie
  392. float dt_div_ie = inDeltaTime / mEngine.mInertia;
  393. // Iterate the rows for the wheels
  394. for (int i = 0; i < (int)driven_wheels.size(); ++i)
  395. {
  396. const DrivenWheel &w_i = driven_wheels[i];
  397. // dt / Iw
  398. float dt_div_iw = inDeltaTime / w_i.mWheel->GetSettings()->mInertia;
  399. // S * R(i)
  400. float s_r = clutch_strength * w_i.mClutchToWheelRatio;
  401. // dt * S * R(i) * F(i) / Iw
  402. float dt_s_r_f_div_iw = dt_div_iw * s_r * w_i.mClutchToWheelTorqueRatio;
  403. // Fill in the columns of a for wheel j
  404. for (int j = 0; j < (int)driven_wheels.size(); ++j)
  405. {
  406. const DrivenWheel &w_j = driven_wheels[j];
  407. a(i, j) = dt_s_r_f_div_iw * w_j.mClutchToWheelRatio / num_driven_wheels_float;
  408. }
  409. // Add ww(i, t+dt)
  410. a(i, i) += 1.0f;
  411. // Add the column for the engine
  412. a(i, engine) = -dt_s_r_f_div_iw;
  413. // Fill in the constant b
  414. b(i, 0) = w_i.mWheel->GetAngularVelocity(); // + dt_div_iw * (brake and tire torques)
  415. // To avoid looping over the wheels again, we also fill in the wheel columns of the engine row here
  416. a(engine, i) = -dt_div_ie * s_r / num_driven_wheels_float;
  417. }
  418. // Finalize the engine row
  419. a(engine, engine) = (1.0f + dt_div_ie * clutch_strength);
  420. b(engine, 0) = w_engine + dt_div_ie * engine_torque;
  421. // Solve the linear equation
  422. if (GaussianElimination(a, b))
  423. {
  424. // Update the angular velocities for the wheels
  425. for (int i = 0; i < (int)driven_wheels.size(); ++i)
  426. {
  427. DrivenWheel &dw1 = driven_wheels[i];
  428. dw1.mWheel->SetAngularVelocity(b(i, 0));
  429. }
  430. // Update the engine RPM
  431. mEngine.SetCurrentRPM(b(engine, 0) * VehicleEngine::cAngularVelocityToRPM);
  432. // The speeds have been solved
  433. solved = true;
  434. }
  435. else
  436. {
  437. JPH_ASSERT(false, "New engine/wheel speeds could not be calculated!");
  438. }
  439. }
  440. if (!solved)
  441. {
  442. // Engine not connected to wheels, apply all torque to engine rotation
  443. mEngine.ApplyTorque(engine_torque, inDeltaTime);
  444. }
  445. // Calculate if any of the wheels are slipping, this is used to prevent gear switching
  446. bool wheels_slipping = false;
  447. for (const DrivenWheel &w : driven_wheels)
  448. wheels_slipping |= w.mClutchToWheelTorqueRatio > 0.0f && (!w.mWheel->HasContact() || w.mWheel->mLongitudinalSlip > 0.1f);
  449. // Only allow shifting up when we're not slipping and we're increasing our RPM.
  450. // 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
  451. // during that time.
  452. bool can_shift_up = !wheels_slipping && mEngine.GetCurrentRPM() >= old_engine_rpm;
  453. // Update transmission
  454. mTransmission.Update(inDeltaTime, mEngine.GetCurrentRPM(), mForwardInput, can_shift_up);
  455. // Braking
  456. for (Wheel *w_base : wheels)
  457. {
  458. WheelWV *w = static_cast<WheelWV *>(w_base);
  459. const WheelSettingsWV *settings = w->GetSettings();
  460. // Combine brake with hand brake torque
  461. float brake_torque = mBrakeInput * settings->mMaxBrakeTorque + mHandBrakeInput * settings->mMaxHandBrakeTorque;
  462. if (brake_torque > 0.0f)
  463. {
  464. // Calculate how much torque is needed to stop the wheels from rotating in this time step
  465. float brake_torque_to_lock_wheels = abs(w->GetAngularVelocity()) * settings->mInertia / inDeltaTime;
  466. if (brake_torque > brake_torque_to_lock_wheels)
  467. {
  468. // Wheels are locked
  469. w->SetAngularVelocity(0.0f);
  470. w->mBrakeImpulse = (brake_torque - brake_torque_to_lock_wheels) * inDeltaTime / settings->mRadius;
  471. }
  472. else
  473. {
  474. // Slow down the wheels
  475. w->ApplyTorque(-Sign(w->GetAngularVelocity()) * brake_torque, inDeltaTime);
  476. w->mBrakeImpulse = 0.0f;
  477. }
  478. }
  479. else
  480. {
  481. // Not braking
  482. w->mBrakeImpulse = 0.0f;
  483. }
  484. }
  485. }
  486. bool WheeledVehicleController::SolveLongitudinalAndLateralConstraints(float inDeltaTime)
  487. {
  488. bool impulse = false;
  489. for (Wheel *w_base : mConstraint.GetWheels())
  490. if (w_base->HasContact())
  491. {
  492. WheelWV *w = static_cast<WheelWV *>(w_base);
  493. const WheelSettingsWV *settings = w->GetSettings();
  494. // Calculate max impulse that we can apply on the ground
  495. float max_longitudinal_friction_impulse = w->mCombinedLongitudinalFriction * w->GetSuspensionLambda();
  496. // Calculate relative velocity between wheel contact point and floor in longitudinal direction
  497. Vec3 relative_velocity = mConstraint.GetVehicleBody()->GetPointVelocity(w->GetContactPosition()) - w->GetContactPointVelocity();
  498. float relative_longitudinal_velocity = relative_velocity.Dot(w->GetContactLongitudinal());
  499. // Calculate brake force to apply
  500. float min_longitudinal_impulse, max_longitudinal_impulse;
  501. if (w->mBrakeImpulse != 0.0f)
  502. {
  503. // Limit brake force by max tire friction
  504. float brake_impulse = min(w->mBrakeImpulse, max_longitudinal_friction_impulse);
  505. // Check which direction the brakes should be applied (we don't want to apply an impulse that would accelerate the vehicle)
  506. if (relative_longitudinal_velocity >= 0.0f)
  507. {
  508. min_longitudinal_impulse = -brake_impulse;
  509. max_longitudinal_impulse = 0.0f;
  510. }
  511. else
  512. {
  513. min_longitudinal_impulse = 0.0f;
  514. max_longitudinal_impulse = brake_impulse;
  515. }
  516. // 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
  517. impulse |= w->SolveLongitudinalConstraintPart(mConstraint, min_longitudinal_impulse, max_longitudinal_impulse);
  518. }
  519. else
  520. {
  521. // 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
  522. float desired_angular_velocity = relative_longitudinal_velocity / settings->mRadius;
  523. float linear_impulse = (w->GetAngularVelocity() - desired_angular_velocity) * settings->mInertia / settings->mRadius;
  524. // Limit the impulse by max tire friction
  525. min_longitudinal_impulse = max_longitudinal_impulse = w->GetLongitudinalLambda() + Sign(linear_impulse) * min(abs(linear_impulse), max_longitudinal_friction_impulse);
  526. // Longitudinal impulse
  527. float prev_lambda = w->GetLongitudinalLambda();
  528. impulse |= w->SolveLongitudinalConstraintPart(mConstraint, min_longitudinal_impulse, max_longitudinal_impulse);
  529. // Update the angular velocity of the wheels according to the lambda that was applied
  530. w->SetAngularVelocity(w->GetAngularVelocity() - (w->GetLongitudinalLambda() - prev_lambda) * settings->mRadius / settings->mInertia);
  531. }
  532. }
  533. for (Wheel *w_base : mConstraint.GetWheels())
  534. if (w_base->HasContact())
  535. {
  536. WheelWV *w = static_cast<WheelWV *>(w_base);
  537. // Lateral friction
  538. float max_lateral_friction_impulse = w->mCombinedLateralFriction * w->GetSuspensionLambda();
  539. impulse |= w->SolveLateralConstraintPart(mConstraint, -max_lateral_friction_impulse, max_lateral_friction_impulse);
  540. }
  541. return impulse;
  542. }
  543. #ifdef JPH_DEBUG_RENDERER
  544. void WheeledVehicleController::Draw(DebugRenderer *inRenderer) const
  545. {
  546. float constraint_size = mConstraint.GetDrawConstraintSize();
  547. // Draw RPM
  548. Body *body = mConstraint.GetVehicleBody();
  549. Vec3 rpm_meter_up = body->GetRotation() * mConstraint.GetLocalUp();
  550. RVec3 rpm_meter_pos = body->GetPosition() + body->GetRotation() * mRPMMeterPosition;
  551. Vec3 rpm_meter_fwd = body->GetRotation() * mConstraint.GetLocalForward();
  552. mEngine.DrawRPM(inRenderer, rpm_meter_pos, rpm_meter_fwd, rpm_meter_up, mRPMMeterSize, mTransmission.mShiftDownRPM, mTransmission.mShiftUpRPM);
  553. // Calculate average wheel speed at clutch
  554. float wheel_speed_at_clutch = 0.0f;
  555. int num_driven_wheels = 0;
  556. for (const VehicleDifferentialSettings &d : mDifferentials)
  557. {
  558. int wheels[] = { d.mLeftWheel, d.mRightWheel };
  559. for (int w : wheels)
  560. if (w >= 0)
  561. {
  562. wheel_speed_at_clutch += mConstraint.GetWheel(w)->GetAngularVelocity() * d.mDifferentialRatio;
  563. num_driven_wheels++;
  564. }
  565. }
  566. wheel_speed_at_clutch = abs(wheel_speed_at_clutch / float(num_driven_wheels) * VehicleEngine::cAngularVelocityToRPM * mTransmission.GetCurrentRatio());
  567. // Draw the average wheel speed measured at clutch to compare engine RPM with wheel RPM
  568. inRenderer->DrawLine(rpm_meter_pos, rpm_meter_pos + Quat::sRotation(rpm_meter_fwd, mEngine.ConvertRPMToAngle(wheel_speed_at_clutch)) * (rpm_meter_up * 1.1f * mRPMMeterSize), Color::sYellow);
  569. // Draw current vehicle state
  570. String status = StringFormat("Forward: %.1f, Right: %.1f\nBrake: %.1f, HandBrake: %.1f\n"
  571. "Gear: %d, Clutch: %.1f\nEngineRPM: %.0f, V: %.1f km/h",
  572. (double)mForwardInput, (double)mRightInput, (double)mBrakeInput, (double)mHandBrakeInput,
  573. mTransmission.GetCurrentGear(), (double)mTransmission.GetClutchFriction(), (double)mEngine.GetCurrentRPM(), (double)body->GetLinearVelocity().Length() * 3.6);
  574. inRenderer->DrawText3D(body->GetPosition(), status, Color::sWhite, constraint_size);
  575. RMat44 body_transform = body->GetWorldTransform();
  576. for (const Wheel *w_base : mConstraint.GetWheels())
  577. {
  578. const WheelWV *w = static_cast<const WheelWV *>(w_base);
  579. const WheelSettings *settings = w->GetSettings();
  580. // Calculate where the suspension attaches to the body in world space
  581. RVec3 ws_position = body_transform * settings->mPosition;
  582. Vec3 ws_direction = body_transform.Multiply3x3(settings->mSuspensionDirection);
  583. // Draw suspension
  584. RVec3 min_suspension_pos = ws_position + ws_direction * settings->mSuspensionMinLength;
  585. RVec3 max_suspension_pos = ws_position + ws_direction * settings->mSuspensionMaxLength;
  586. inRenderer->DrawLine(ws_position, min_suspension_pos, Color::sRed);
  587. inRenderer->DrawLine(min_suspension_pos, max_suspension_pos, Color::sGreen);
  588. // Draw current length
  589. RVec3 wheel_pos = ws_position + ws_direction * w->GetSuspensionLength();
  590. inRenderer->DrawMarker(wheel_pos, w->GetSuspensionLength() < settings->mSuspensionMinLength? Color::sRed : Color::sGreen, constraint_size);
  591. // Draw wheel basis
  592. Vec3 wheel_forward, wheel_up, wheel_right;
  593. mConstraint.GetWheelLocalBasis(w, wheel_forward, wheel_up, wheel_right);
  594. wheel_forward = body_transform.Multiply3x3(wheel_forward);
  595. wheel_up = body_transform.Multiply3x3(wheel_up);
  596. wheel_right = body_transform.Multiply3x3(wheel_right);
  597. Vec3 steering_axis = body_transform.Multiply3x3(settings->mSteeringAxis);
  598. inRenderer->DrawLine(wheel_pos, wheel_pos + wheel_forward, Color::sRed);
  599. inRenderer->DrawLine(wheel_pos, wheel_pos + wheel_up, Color::sGreen);
  600. inRenderer->DrawLine(wheel_pos, wheel_pos + wheel_right, Color::sBlue);
  601. inRenderer->DrawLine(wheel_pos, wheel_pos + steering_axis, Color::sYellow);
  602. if (w->HasContact())
  603. {
  604. // Draw contact
  605. inRenderer->DrawLine(w->GetContactPosition(), w->GetContactPosition() + w->GetContactNormal(), Color::sYellow);
  606. inRenderer->DrawLine(w->GetContactPosition(), w->GetContactPosition() + w->GetContactLongitudinal(), Color::sRed);
  607. inRenderer->DrawLine(w->GetContactPosition(), w->GetContactPosition() + w->GetContactLateral(), Color::sBlue);
  608. DebugRenderer::sInstance->DrawText3D(wheel_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);
  609. }
  610. else
  611. {
  612. // Draw 'no hit'
  613. DebugRenderer::sInstance->DrawText3D(wheel_pos, StringFormat("W: %.1f", (double)w->GetAngularVelocity()), Color::sRed, constraint_size);
  614. }
  615. }
  616. }
  617. #endif // JPH_DEBUG_RENDERER
  618. void WheeledVehicleController::SaveState(StateRecorder &inStream) const
  619. {
  620. inStream.Write(mForwardInput);
  621. inStream.Write(mRightInput);
  622. inStream.Write(mBrakeInput);
  623. inStream.Write(mHandBrakeInput);
  624. mEngine.SaveState(inStream);
  625. mTransmission.SaveState(inStream);
  626. }
  627. void WheeledVehicleController::RestoreState(StateRecorder &inStream)
  628. {
  629. inStream.Read(mForwardInput);
  630. inStream.Read(mRightInput);
  631. inStream.Read(mBrakeInput);
  632. inStream.Read(mHandBrakeInput);
  633. mEngine.RestoreState(inStream);
  634. mTransmission.RestoreState(inStream);
  635. }
  636. JPH_NAMESPACE_END