WheeledVehicleController.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  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. //#define JPH_TRACE_VEHICLE_STATS
  16. JPH_NAMESPACE_BEGIN
  17. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(WheeledVehicleControllerSettings)
  18. {
  19. JPH_ADD_BASE_CLASS(WheeledVehicleControllerSettings, VehicleControllerSettings)
  20. JPH_ADD_ATTRIBUTE(WheeledVehicleControllerSettings, mEngine)
  21. JPH_ADD_ATTRIBUTE(WheeledVehicleControllerSettings, mTransmission)
  22. JPH_ADD_ATTRIBUTE(WheeledVehicleControllerSettings, mDifferentials)
  23. JPH_ADD_ATTRIBUTE(WheeledVehicleControllerSettings, mDifferentialLimitedSlipRatio)
  24. }
  25. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(WheelSettingsWV)
  26. {
  27. JPH_ADD_BASE_CLASS(WheelSettingsWV, WheelSettings)
  28. JPH_ADD_ATTRIBUTE(WheelSettingsWV, mInertia)
  29. JPH_ADD_ATTRIBUTE(WheelSettingsWV, mAngularDamping)
  30. JPH_ADD_ATTRIBUTE(WheelSettingsWV, mMaxSteerAngle)
  31. JPH_ADD_ATTRIBUTE(WheelSettingsWV, mLongitudinalFriction)
  32. JPH_ADD_ATTRIBUTE(WheelSettingsWV, mLateralFriction)
  33. JPH_ADD_ATTRIBUTE(WheelSettingsWV, mMaxBrakeTorque)
  34. JPH_ADD_ATTRIBUTE(WheelSettingsWV, mMaxHandBrakeTorque)
  35. }
  36. WheelSettingsWV::WheelSettingsWV()
  37. {
  38. mLongitudinalFriction.Reserve(3);
  39. mLongitudinalFriction.AddPoint(0.0f, 0.0f);
  40. mLongitudinalFriction.AddPoint(0.06f, 1.2f);
  41. mLongitudinalFriction.AddPoint(0.2f, 1.0f);
  42. mLateralFriction.Reserve(3);
  43. mLateralFriction.AddPoint(0.0f, 0.0f);
  44. mLateralFriction.AddPoint(3.0f, 1.2f);
  45. mLateralFriction.AddPoint(20.0f, 1.0f);
  46. }
  47. void WheelSettingsWV::SaveBinaryState(StreamOut &inStream) const
  48. {
  49. WheelSettings::SaveBinaryState(inStream);
  50. inStream.Write(mInertia);
  51. inStream.Write(mAngularDamping);
  52. inStream.Write(mMaxSteerAngle);
  53. mLongitudinalFriction.SaveBinaryState(inStream);
  54. mLateralFriction.SaveBinaryState(inStream);
  55. inStream.Write(mMaxBrakeTorque);
  56. inStream.Write(mMaxHandBrakeTorque);
  57. }
  58. void WheelSettingsWV::RestoreBinaryState(StreamIn &inStream)
  59. {
  60. WheelSettings::RestoreBinaryState(inStream);
  61. inStream.Read(mInertia);
  62. inStream.Read(mAngularDamping);
  63. inStream.Read(mMaxSteerAngle);
  64. mLongitudinalFriction.RestoreBinaryState(inStream);
  65. mLateralFriction.RestoreBinaryState(inStream);
  66. inStream.Read(mMaxBrakeTorque);
  67. inStream.Read(mMaxHandBrakeTorque);
  68. }
  69. WheelWV::WheelWV(const WheelSettingsWV &inSettings) :
  70. Wheel(inSettings)
  71. {
  72. JPH_ASSERT(inSettings.mInertia >= 0.0f);
  73. JPH_ASSERT(inSettings.mAngularDamping >= 0.0f);
  74. JPH_ASSERT(abs(inSettings.mMaxSteerAngle) <= 0.5f * JPH_PI);
  75. JPH_ASSERT(inSettings.mMaxBrakeTorque >= 0.0f);
  76. JPH_ASSERT(inSettings.mMaxHandBrakeTorque >= 0.0f);
  77. }
  78. void WheelWV::Update(uint inWheelIndex, float inDeltaTime, const VehicleConstraint &inConstraint)
  79. {
  80. const WheelSettingsWV *settings = GetSettings();
  81. // Angular damping: dw/dt = -c * w
  82. // Solution: w(t) = w(0) * e^(-c * t) or w2 = w1 * e^(-c * dt)
  83. // Taylor expansion of e^(-c * dt) = 1 - c * dt + ...
  84. // Since dt is usually in the order of 1/60 and c is a low number too this approximation is good enough
  85. mAngularVelocity *= max(0.0f, 1.0f - settings->mAngularDamping * inDeltaTime);
  86. // Update rotation of wheel
  87. mAngle = fmod(mAngle + mAngularVelocity * inDeltaTime, 2.0f * JPH_PI);
  88. if (mContactBody != nullptr)
  89. {
  90. const Body *body = inConstraint.GetVehicleBody();
  91. // Calculate relative velocity between wheel contact point and floor
  92. Vec3 relative_velocity = body->GetPointVelocity(mContactPosition) - mContactPointVelocity;
  93. // Cancel relative velocity in the normal plane
  94. relative_velocity -= mContactNormal.Dot(relative_velocity) * mContactNormal;
  95. float relative_longitudinal_velocity = relative_velocity.Dot(mContactLongitudinal);
  96. // Calculate longitudinal friction based on difference between velocity of rolling wheel and drive surface
  97. float relative_longitudinal_velocity_denom = Sign(relative_longitudinal_velocity) * max(1.0e-3f, abs(relative_longitudinal_velocity)); // Ensure we don't divide by zero
  98. mLongitudinalSlip = abs((mAngularVelocity * settings->mRadius - relative_longitudinal_velocity) / relative_longitudinal_velocity_denom);
  99. float longitudinal_slip_friction = settings->mLongitudinalFriction.GetValue(mLongitudinalSlip);
  100. // Calculate lateral friction based on slip angle
  101. float relative_velocity_len = relative_velocity.Length();
  102. mLateralSlip = relative_velocity_len < 1.0e-3f ? 0.0f : ACos(abs(relative_longitudinal_velocity) / relative_velocity_len);
  103. float lateral_slip_angle = RadiansToDegrees(mLateralSlip);
  104. float lateral_slip_friction = settings->mLateralFriction.GetValue(lateral_slip_angle);
  105. // Tire friction
  106. VehicleConstraint::CombineFunction combine_friction = inConstraint.GetCombineFriction();
  107. mCombinedLongitudinalFriction = longitudinal_slip_friction;
  108. mCombinedLateralFriction = lateral_slip_friction;
  109. combine_friction(inWheelIndex, mCombinedLongitudinalFriction, mCombinedLateralFriction, *mContactBody, mContactSubShapeID);
  110. }
  111. else
  112. {
  113. // No collision
  114. mLongitudinalSlip = 0.0f;
  115. mLateralSlip = 0.0f;
  116. mCombinedLongitudinalFriction = mCombinedLateralFriction = 0.0f;
  117. }
  118. }
  119. VehicleController *WheeledVehicleControllerSettings::ConstructController(VehicleConstraint &inConstraint) const
  120. {
  121. return new WheeledVehicleController(*this, inConstraint);
  122. }
  123. void WheeledVehicleControllerSettings::SaveBinaryState(StreamOut &inStream) const
  124. {
  125. mEngine.SaveBinaryState(inStream);
  126. mTransmission.SaveBinaryState(inStream);
  127. uint32 num_differentials = (uint32)mDifferentials.size();
  128. inStream.Write(num_differentials);
  129. for (const VehicleDifferentialSettings &d : mDifferentials)
  130. d.SaveBinaryState(inStream);
  131. inStream.Write(mDifferentialLimitedSlipRatio);
  132. }
  133. void WheeledVehicleControllerSettings::RestoreBinaryState(StreamIn &inStream)
  134. {
  135. mEngine.RestoreBinaryState(inStream);
  136. mTransmission.RestoreBinaryState(inStream);
  137. uint32 num_differentials = 0;
  138. inStream.Read(num_differentials);
  139. mDifferentials.resize(num_differentials);
  140. for (VehicleDifferentialSettings &d : mDifferentials)
  141. d.RestoreBinaryState(inStream);
  142. inStream.Read(mDifferentialLimitedSlipRatio);
  143. }
  144. WheeledVehicleController::WheeledVehicleController(const WheeledVehicleControllerSettings &inSettings, VehicleConstraint &inConstraint) :
  145. VehicleController(inConstraint)
  146. {
  147. // Copy engine settings
  148. static_cast<VehicleEngineSettings &>(mEngine) = inSettings.mEngine;
  149. JPH_ASSERT(inSettings.mEngine.mMinRPM >= 0.0f);
  150. JPH_ASSERT(inSettings.mEngine.mMinRPM <= inSettings.mEngine.mMaxRPM);
  151. mEngine.SetCurrentRPM(mEngine.mMinRPM);
  152. // Copy transmission settings
  153. static_cast<VehicleTransmissionSettings &>(mTransmission) = inSettings.mTransmission;
  154. #ifdef JPH_ENABLE_ASSERTS
  155. for (float r : inSettings.mTransmission.mGearRatios)
  156. JPH_ASSERT(r > 0.0f);
  157. for (float r : inSettings.mTransmission.mReverseGearRatios)
  158. JPH_ASSERT(r < 0.0f);
  159. #endif // JPH_ENABLE_ASSERTS
  160. JPH_ASSERT(inSettings.mTransmission.mSwitchTime >= 0.0f);
  161. JPH_ASSERT(inSettings.mTransmission.mShiftDownRPM > 0.0f);
  162. JPH_ASSERT(inSettings.mTransmission.mMode != ETransmissionMode::Auto || inSettings.mTransmission.mShiftUpRPM < inSettings.mEngine.mMaxRPM);
  163. JPH_ASSERT(inSettings.mTransmission.mShiftUpRPM > inSettings.mTransmission.mShiftDownRPM);
  164. JPH_ASSERT(inSettings.mTransmission.mClutchStrength > 0.0f);
  165. // Copy differential settings
  166. mDifferentials.resize(inSettings.mDifferentials.size());
  167. for (uint i = 0; i < mDifferentials.size(); ++i)
  168. {
  169. const VehicleDifferentialSettings &d = inSettings.mDifferentials[i];
  170. mDifferentials[i] = d;
  171. JPH_ASSERT(d.mDifferentialRatio > 0.0f);
  172. JPH_ASSERT(d.mLeftRightSplit >= 0.0f && d.mLeftRightSplit <= 1.0f);
  173. JPH_ASSERT(d.mEngineTorqueRatio >= 0.0f);
  174. JPH_ASSERT(d.mLimitedSlipRatio > 1.0f);
  175. }
  176. mDifferentialLimitedSlipRatio = inSettings.mDifferentialLimitedSlipRatio;
  177. JPH_ASSERT(mDifferentialLimitedSlipRatio > 1.0f);
  178. }
  179. float WheeledVehicleController::GetWheelSpeedAtClutch() const
  180. {
  181. float wheel_speed_at_clutch = 0.0f;
  182. int num_driven_wheels = 0;
  183. for (const VehicleDifferentialSettings &d : mDifferentials)
  184. {
  185. int wheels[] = { d.mLeftWheel, d.mRightWheel };
  186. for (int w : wheels)
  187. if (w >= 0)
  188. {
  189. wheel_speed_at_clutch += mConstraint.GetWheel(w)->GetAngularVelocity() * d.mDifferentialRatio;
  190. num_driven_wheels++;
  191. }
  192. }
  193. return wheel_speed_at_clutch / float(num_driven_wheels) * VehicleEngine::cAngularVelocityToRPM * mTransmission.GetCurrentRatio();
  194. }
  195. bool WheeledVehicleController::AllowSleep() const
  196. {
  197. return mForwardInput == 0.0f // No user input
  198. && mTransmission.AllowSleep() // Transmission is not shifting
  199. && mEngine.AllowSleep(); // Engine is idling
  200. }
  201. void WheeledVehicleController::PreCollide(float inDeltaTime, PhysicsSystem &inPhysicsSystem)
  202. {
  203. JPH_PROFILE_FUNCTION();
  204. #ifdef JPH_TRACE_VEHICLE_STATS
  205. static bool sTracedHeader = false;
  206. if (!sTracedHeader)
  207. {
  208. Trace("Time, ForwardInput, Gear, ClutchFriction, EngineRPM, WheelRPM, Velocity (km/h)");
  209. sTracedHeader = true;
  210. }
  211. static float sTime = 0.0f;
  212. sTime += inDeltaTime;
  213. Trace("%.3f, %.1f, %d, %.1f, %.1f, %.1f, %.1f", sTime, mForwardInput, mTransmission.GetCurrentGear(), mTransmission.GetClutchFriction(), mEngine.GetCurrentRPM(), GetWheelSpeedAtClutch(), mConstraint.GetVehicleBody()->GetLinearVelocity().Length() * 3.6f);
  214. #endif // JPH_TRACE_VEHICLE_STATS
  215. for (Wheel *w_base : mConstraint.GetWheels())
  216. {
  217. WheelWV *w = static_cast<WheelWV *>(w_base);
  218. // Set steering angle
  219. w->SetSteerAngle(-mRightInput * w->GetSettings()->mMaxSteerAngle);
  220. }
  221. }
  222. void WheeledVehicleController::PostCollide(float inDeltaTime, PhysicsSystem &inPhysicsSystem)
  223. {
  224. JPH_PROFILE_FUNCTION();
  225. // Remember old RPM so we can detect if we're increasing or decreasing
  226. float old_engine_rpm = mEngine.GetCurrentRPM();
  227. Wheels &wheels = mConstraint.GetWheels();
  228. // Update wheel angle, do this before applying torque to the wheels (as friction will slow them down again)
  229. for (uint wheel_index = 0, num_wheels = (uint)wheels.size(); wheel_index < num_wheels; ++wheel_index)
  230. {
  231. WheelWV *w = static_cast<WheelWV *>(wheels[wheel_index]);
  232. w->Update(wheel_index, inDeltaTime, mConstraint);
  233. }
  234. // In auto transmission mode, don't accelerate the engine when switching gears
  235. float forward_input = abs(mForwardInput);
  236. if (mTransmission.mMode == ETransmissionMode::Auto)
  237. forward_input *= mTransmission.GetClutchFriction();
  238. // Apply engine damping
  239. mEngine.ApplyDamping(inDeltaTime);
  240. // Calculate engine torque
  241. float engine_torque = mEngine.GetTorque(forward_input);
  242. // Define a struct that contains information about driven differentials (i.e. that have wheels connected)
  243. struct DrivenDifferential
  244. {
  245. const VehicleDifferentialSettings * mDifferential;
  246. float mAngularVelocity;
  247. float mClutchToDifferentialTorqueRatio;
  248. float mTempTorqueFactor;
  249. };
  250. // Collect driven differentials and their speeds
  251. Array<DrivenDifferential> driven_differentials;
  252. driven_differentials.reserve(mDifferentials.size());
  253. float differential_omega_min = FLT_MAX, differential_omega_max = 0.0f;
  254. for (const VehicleDifferentialSettings &d : mDifferentials)
  255. {
  256. float avg_omega = 0.0f;
  257. int avg_omega_denom = 0;
  258. int indices[] = { d.mLeftWheel, d.mRightWheel };
  259. for (int idx : indices)
  260. if (idx != -1)
  261. {
  262. avg_omega += wheels[idx]->GetAngularVelocity();
  263. avg_omega_denom++;
  264. }
  265. if (avg_omega_denom > 0)
  266. {
  267. avg_omega = abs(avg_omega * d.mDifferentialRatio / float(avg_omega_denom)); // ignoring that the differentials may be rotating in different directions
  268. driven_differentials.push_back({ &d, avg_omega, d.mEngineTorqueRatio, 0 });
  269. // Remember min and max velocity
  270. differential_omega_min = min(differential_omega_min, avg_omega);
  271. differential_omega_max = max(differential_omega_max, avg_omega);
  272. }
  273. }
  274. if (mDifferentialLimitedSlipRatio < FLT_MAX // Limited slip differential needs to be turned on
  275. && differential_omega_max > differential_omega_min) // There needs to be a velocity difference
  276. {
  277. // Calculate factor based on relative speed of a differential
  278. float sum_factor = 0.0f;
  279. for (DrivenDifferential &d : driven_differentials)
  280. {
  281. // Differential with max velocity gets factor 0, differential with min velocity 1
  282. d.mTempTorqueFactor = (differential_omega_max - d.mAngularVelocity) / (differential_omega_max - differential_omega_min);
  283. sum_factor += d.mTempTorqueFactor;
  284. }
  285. // Normalize the result
  286. for (DrivenDifferential &d : driven_differentials)
  287. d.mTempTorqueFactor /= sum_factor;
  288. // Prevent div by zero
  289. differential_omega_min = max(1.0e-3f, differential_omega_min);
  290. differential_omega_max = max(1.0e-3f, differential_omega_max);
  291. // 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
  292. float alpha = min((differential_omega_max / differential_omega_min - 1.0f) / (mDifferentialLimitedSlipRatio - 1.0f), 1.0f);
  293. JPH_ASSERT(alpha >= 0.0f);
  294. float one_min_alpha = 1.0f - alpha;
  295. // Update torque ratio for all differentials
  296. for (DrivenDifferential &d : driven_differentials)
  297. d.mClutchToDifferentialTorqueRatio = one_min_alpha * d.mClutchToDifferentialTorqueRatio + alpha * d.mTempTorqueFactor;
  298. }
  299. #ifdef JPH_ENABLE_ASSERTS
  300. // Assert the values add up to 1
  301. float sum_torque_factors = 0.0f;
  302. for (DrivenDifferential &d : driven_differentials)
  303. sum_torque_factors += d.mClutchToDifferentialTorqueRatio;
  304. JPH_ASSERT(abs(sum_torque_factors - 1.0f) < 1.0e-6f);
  305. #endif // JPH_ENABLE_ASSERTS
  306. // Define a struct that collects information about the wheels that connect to the engine
  307. struct DrivenWheel
  308. {
  309. WheelWV * mWheel;
  310. float mClutchToWheelRatio;
  311. float mClutchToWheelTorqueRatio;
  312. float mEstimatedAngularImpulse;
  313. };
  314. Array<DrivenWheel> driven_wheels;
  315. driven_wheels.reserve(wheels.size());
  316. // Collect driven wheels
  317. float transmission_ratio = mTransmission.GetCurrentRatio();
  318. for (const DrivenDifferential &dd : driven_differentials)
  319. {
  320. VehicleDifferentialSettings d = *dd.mDifferential;
  321. WheelWV *wl = d.mLeftWheel != -1? static_cast<WheelWV *>(wheels[d.mLeftWheel]) : nullptr;
  322. WheelWV *wr = d.mRightWheel != -1? static_cast<WheelWV *>(wheels[d.mRightWheel]) : nullptr;
  323. float clutch_to_wheel_ratio = transmission_ratio * d.mDifferentialRatio;
  324. if (wl != nullptr && wr != nullptr)
  325. {
  326. // Calculate torque ratio
  327. float ratio_l, ratio_r;
  328. d.CalculateTorqueRatio(wl->GetAngularVelocity(), wr->GetAngularVelocity(), ratio_l, ratio_r);
  329. // Add both wheels
  330. driven_wheels.push_back({ wl, clutch_to_wheel_ratio, dd.mClutchToDifferentialTorqueRatio * ratio_l, 0.0f });
  331. driven_wheels.push_back({ wr, clutch_to_wheel_ratio, dd.mClutchToDifferentialTorqueRatio * ratio_r, 0.0f });
  332. }
  333. else if (wl != nullptr)
  334. {
  335. // Only left wheel, all power to left
  336. driven_wheels.push_back({ wl, clutch_to_wheel_ratio, dd.mClutchToDifferentialTorqueRatio, 0.0f });
  337. }
  338. else if (wr != nullptr)
  339. {
  340. // Only right wheel, all power to right
  341. driven_wheels.push_back({ wr, clutch_to_wheel_ratio, dd.mClutchToDifferentialTorqueRatio, 0.0f });
  342. }
  343. }
  344. bool solved = false;
  345. if (!driven_wheels.empty())
  346. {
  347. // Define the torque at the clutch at time t as:
  348. //
  349. // tc(t):=S*(we(t)-sum(R(j)*ww(j,t),j,1,N)/N)
  350. //
  351. // Where:
  352. // S is the total strength of clutch (= friction * strength)
  353. // we(t) is the engine angular velocity at time t
  354. // R(j) is the total gear ratio of clutch to wheel for wheel j
  355. // ww(j,t) is the angular velocity of wheel j at time t
  356. // N is the amount of wheels
  357. //
  358. // The torque that increases the engine angular velocity at time t is:
  359. //
  360. // te(t):=TE-tc(t)
  361. //
  362. // Where:
  363. // TE is the torque delivered by the engine
  364. //
  365. // The torque that increases the wheel angular velocity for wheel i at time t is:
  366. //
  367. // tw(i,t):=TW(i)+R(i)*F(i)*tc(t)
  368. //
  369. // Where:
  370. // TW(i) is the torque applied to the wheel outside of the engine (brake + torque due to friction with the ground)
  371. // F(i) is the fraction of the engine torque applied from engine to wheel i
  372. //
  373. // Because the angular acceleration and torque are connected through: Torque = I * dw/dt
  374. //
  375. // We have the angular acceleration of the engine at time t:
  376. //
  377. // ddt_we(t):=te(t)/Ie
  378. //
  379. // Where:
  380. // Ie is the inertia of the engine
  381. //
  382. // We have the angular acceleration of wheel i at time t:
  383. //
  384. // ddt_ww(i,t):=tw(i,t)/Iw(i)
  385. //
  386. // Where:
  387. // Iw(i) is the inertia of wheel i
  388. //
  389. // 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:
  390. //
  391. // we(t+dt)=we(t)+dt*ddt_we(t+dt)
  392. //
  393. // and:
  394. //
  395. // ww(i,t+dt)=ww(i,t)+dt*ddt_ww(i,t+dt)
  396. //
  397. // Expanding both equations (the equations above are in wxMaxima format and this can easily be done by expand(%)):
  398. //
  399. // For wheel:
  400. //
  401. // 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)
  402. //
  403. // For engine:
  404. //
  405. // 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
  406. //
  407. // 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:
  408. //
  409. // a * w(t + dt) = b
  410. //
  411. // We then invert the matrix to get the new angular velocities.
  412. // Dimension of matrix is N + 1
  413. int n = (int)driven_wheels.size() + 1;
  414. // Last column of w is for the engine angular velocity
  415. int engine = n - 1;
  416. // Define a and b
  417. DynMatrix a(n, n);
  418. DynMatrix b(n, 1);
  419. // Get number of driven wheels as a float
  420. float num_driven_wheels_float = float(driven_wheels.size());
  421. // Angular velocity of engine
  422. float w_engine = mEngine.GetAngularVelocity();
  423. // Calculate the total strength of the clutch
  424. float clutch_strength = transmission_ratio != 0.0f? mTransmission.GetClutchFriction() * mTransmission.mClutchStrength : 0.0f;
  425. // dt / Ie
  426. float dt_div_ie = inDeltaTime / mEngine.mInertia;
  427. // Calculate scale factor for impulses based on previous delta time
  428. float impulse_scale = mPreviousDeltaTime > 0.0f? inDeltaTime / mPreviousDeltaTime : 0.0f;
  429. // Iterate the rows for the wheels
  430. for (int i = 0; i < (int)driven_wheels.size(); ++i)
  431. {
  432. DrivenWheel &w_i = driven_wheels[i];
  433. const WheelSettingsWV *settings = w_i.mWheel->GetSettings();
  434. // Get wheel inertia
  435. float inertia = settings->mInertia;
  436. // S * R(i)
  437. float s_r = clutch_strength * w_i.mClutchToWheelRatio;
  438. // dt * S * R(i) * F(i) / Iw
  439. float dt_s_r_f_div_iw = inDeltaTime * s_r * w_i.mClutchToWheelTorqueRatio / inertia;
  440. // Fill in the columns of a for wheel j
  441. for (int j = 0; j < (int)driven_wheels.size(); ++j)
  442. {
  443. const DrivenWheel &w_j = driven_wheels[j];
  444. a(i, j) = dt_s_r_f_div_iw * w_j.mClutchToWheelRatio / num_driven_wheels_float;
  445. }
  446. // Add ww(i, t+dt)
  447. a(i, i) += 1.0f;
  448. // Add the column for the engine
  449. a(i, engine) = -dt_s_r_f_div_iw;
  450. // Calculate external angular impulse operating on the wheel: TW(i) * dt
  451. float dt_tw = 0.0f;
  452. // Combine brake with hand brake torque
  453. float brake_torque = mBrakeInput * settings->mMaxBrakeTorque + mHandBrakeInput * settings->mMaxHandBrakeTorque;
  454. if (brake_torque > 0.0f)
  455. {
  456. // We're braking
  457. // Calculate brake angular impulse
  458. float sign;
  459. if (w_i.mWheel->GetAngularVelocity() != 0.0f)
  460. sign = Sign(w_i.mWheel->GetAngularVelocity());
  461. else
  462. sign = Sign(mTransmission.GetCurrentRatio()); // When wheels have locked up use the transmission ratio to determine the sign
  463. dt_tw = sign * inDeltaTime * brake_torque;
  464. }
  465. if (w_i.mWheel->HasContact())
  466. {
  467. // We have wheel contact with the floor
  468. // Note that we don't know the torque due to the ground contact yet, so we use the impulse applied from the last frame to estimate it
  469. // Wheel torque TW = force * radius = lambda / dt * radius
  470. dt_tw += impulse_scale * w_i.mWheel->GetLongitudinalLambda() * settings->mRadius;
  471. }
  472. w_i.mEstimatedAngularImpulse = dt_tw;
  473. // Fill in the constant b = ww(i,t)+(dt*TW(i))/Iw(i)
  474. b(i, 0) = w_i.mWheel->GetAngularVelocity() - dt_tw / inertia;
  475. // To avoid looping over the wheels again, we also fill in the wheel columns of the engine row here
  476. a(engine, i) = -dt_div_ie * s_r / num_driven_wheels_float;
  477. }
  478. // Finalize the engine row
  479. a(engine, engine) = (1.0f + dt_div_ie * clutch_strength);
  480. b(engine, 0) = w_engine + dt_div_ie * engine_torque;
  481. // Solve the linear equation
  482. if (GaussianElimination(a, b))
  483. {
  484. // Update the angular velocities for the wheels
  485. for (int i = 0; i < (int)driven_wheels.size(); ++i)
  486. {
  487. DrivenWheel &w_i = driven_wheels[i];
  488. const WheelSettingsWV *settings = w_i.mWheel->GetSettings();
  489. // Get solved wheel angular velocity
  490. float angular_velocity = b(i, 0);
  491. // We estimated TW and applied it in the equation above, but we haven't actually applied this torque yet so we undo it here.
  492. // It will be applied when we solve the actual braking / the constraints with the floor.
  493. angular_velocity += w_i.mEstimatedAngularImpulse / settings->mInertia;
  494. // Update angular velocity
  495. w_i.mWheel->SetAngularVelocity(angular_velocity);
  496. }
  497. // Update the engine RPM
  498. mEngine.SetCurrentRPM(b(engine, 0) * VehicleEngine::cAngularVelocityToRPM);
  499. // The speeds have been solved
  500. solved = true;
  501. }
  502. else
  503. {
  504. JPH_ASSERT(false, "New engine/wheel speeds could not be calculated!");
  505. }
  506. }
  507. if (!solved)
  508. {
  509. // Engine not connected to wheels, apply all torque to engine rotation
  510. mEngine.ApplyTorque(engine_torque, inDeltaTime);
  511. }
  512. // Calculate if any of the wheels are slipping, this is used to prevent gear switching
  513. bool wheels_slipping = false;
  514. for (const DrivenWheel &w : driven_wheels)
  515. wheels_slipping |= w.mClutchToWheelTorqueRatio > 0.0f && (!w.mWheel->HasContact() || w.mWheel->mLongitudinalSlip > 0.1f);
  516. // Only allow shifting up when we're not slipping and we're increasing our RPM.
  517. // 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
  518. // during that time.
  519. bool can_shift_up = !wheels_slipping && mEngine.GetCurrentRPM() >= old_engine_rpm;
  520. // Update transmission
  521. mTransmission.Update(inDeltaTime, mEngine.GetCurrentRPM(), mForwardInput, can_shift_up);
  522. // Braking
  523. for (Wheel *w_base : wheels)
  524. {
  525. WheelWV *w = static_cast<WheelWV *>(w_base);
  526. const WheelSettingsWV *settings = w->GetSettings();
  527. // Combine brake with hand brake torque
  528. float brake_torque = mBrakeInput * settings->mMaxBrakeTorque + mHandBrakeInput * settings->mMaxHandBrakeTorque;
  529. if (brake_torque > 0.0f)
  530. {
  531. // Calculate how much torque is needed to stop the wheels from rotating in this time step
  532. float brake_torque_to_lock_wheels = abs(w->GetAngularVelocity()) * settings->mInertia / inDeltaTime;
  533. if (brake_torque > brake_torque_to_lock_wheels)
  534. {
  535. // Wheels are locked
  536. w->SetAngularVelocity(0.0f);
  537. w->mBrakeImpulse = (brake_torque - brake_torque_to_lock_wheels) * inDeltaTime / settings->mRadius;
  538. }
  539. else
  540. {
  541. // Slow down the wheels
  542. w->ApplyTorque(-Sign(w->GetAngularVelocity()) * brake_torque, inDeltaTime);
  543. w->mBrakeImpulse = 0.0f;
  544. }
  545. }
  546. else
  547. {
  548. // Not braking
  549. w->mBrakeImpulse = 0.0f;
  550. }
  551. }
  552. // Remember previous delta time so we can scale the impulses correctly
  553. mPreviousDeltaTime = inDeltaTime;
  554. }
  555. bool WheeledVehicleController::SolveLongitudinalAndLateralConstraints(float inDeltaTime)
  556. {
  557. bool impulse = false;
  558. float *max_lateral_friction_impulse = (float *)JPH_STACK_ALLOC(mConstraint.GetWheels().size() * sizeof(float));
  559. uint wheel_index = 0;
  560. for (Wheel *w_base : mConstraint.GetWheels())
  561. {
  562. if (w_base->HasContact())
  563. {
  564. WheelWV *w = static_cast<WheelWV *>(w_base);
  565. const WheelSettingsWV *settings = w->GetSettings();
  566. // Calculate max impulse that we can apply on the ground
  567. float max_longitudinal_friction_impulse;
  568. mTireMaxImpulseCallback(wheel_index,
  569. max_longitudinal_friction_impulse, max_lateral_friction_impulse[wheel_index], w->GetSuspensionLambda(),
  570. w->mCombinedLongitudinalFriction, w->mCombinedLateralFriction, w->mLongitudinalSlip, w->mLateralSlip, inDeltaTime);
  571. // Calculate relative velocity between wheel contact point and floor in longitudinal direction
  572. Vec3 relative_velocity = mConstraint.GetVehicleBody()->GetPointVelocity(w->GetContactPosition()) - w->GetContactPointVelocity();
  573. float relative_longitudinal_velocity = relative_velocity.Dot(w->GetContactLongitudinal());
  574. // Calculate brake force to apply
  575. float min_longitudinal_impulse, max_longitudinal_impulse;
  576. if (w->mBrakeImpulse != 0.0f)
  577. {
  578. // Limit brake force by max tire friction
  579. float brake_impulse = min(w->mBrakeImpulse, max_longitudinal_friction_impulse);
  580. // Check which direction the brakes should be applied (we don't want to apply an impulse that would accelerate the vehicle)
  581. if (relative_longitudinal_velocity >= 0.0f)
  582. {
  583. min_longitudinal_impulse = -brake_impulse;
  584. max_longitudinal_impulse = 0.0f;
  585. }
  586. else
  587. {
  588. min_longitudinal_impulse = 0.0f;
  589. max_longitudinal_impulse = brake_impulse;
  590. }
  591. // 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
  592. impulse |= w->SolveLongitudinalConstraintPart(mConstraint, min_longitudinal_impulse, max_longitudinal_impulse);
  593. }
  594. else
  595. {
  596. // 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
  597. float desired_angular_velocity = relative_longitudinal_velocity / settings->mRadius;
  598. float linear_impulse = (w->GetAngularVelocity() - desired_angular_velocity) * settings->mInertia / settings->mRadius;
  599. // Limit the impulse by max tire friction
  600. float prev_lambda = w->GetLongitudinalLambda();
  601. min_longitudinal_impulse = max_longitudinal_impulse = Clamp(prev_lambda + linear_impulse, -max_longitudinal_friction_impulse, max_longitudinal_friction_impulse);
  602. // Longitudinal impulse
  603. impulse |= w->SolveLongitudinalConstraintPart(mConstraint, min_longitudinal_impulse, max_longitudinal_impulse);
  604. // Update the angular velocity of the wheels according to the lambda that was applied
  605. w->SetAngularVelocity(w->GetAngularVelocity() - (w->GetLongitudinalLambda() - prev_lambda) * settings->mRadius / settings->mInertia);
  606. }
  607. }
  608. ++wheel_index;
  609. }
  610. wheel_index = 0;
  611. for (Wheel *w_base : mConstraint.GetWheels())
  612. {
  613. if (w_base->HasContact())
  614. {
  615. WheelWV *w = static_cast<WheelWV *>(w_base);
  616. // Lateral friction
  617. float max_lateral_impulse = max_lateral_friction_impulse[wheel_index];
  618. impulse |= w->SolveLateralConstraintPart(mConstraint, -max_lateral_impulse, max_lateral_impulse);
  619. }
  620. ++wheel_index;
  621. }
  622. return impulse;
  623. }
  624. #ifdef JPH_DEBUG_RENDERER
  625. void WheeledVehicleController::Draw(DebugRenderer *inRenderer) const
  626. {
  627. float constraint_size = mConstraint.GetDrawConstraintSize();
  628. // Draw RPM
  629. Body *body = mConstraint.GetVehicleBody();
  630. Vec3 rpm_meter_up = body->GetRotation() * mConstraint.GetLocalUp();
  631. RVec3 rpm_meter_pos = body->GetPosition() + body->GetRotation() * mRPMMeterPosition;
  632. Vec3 rpm_meter_fwd = body->GetRotation() * mConstraint.GetLocalForward();
  633. mEngine.DrawRPM(inRenderer, rpm_meter_pos, rpm_meter_fwd, rpm_meter_up, mRPMMeterSize, mTransmission.mShiftDownRPM, mTransmission.mShiftUpRPM);
  634. if (mTransmission.GetCurrentRatio() != 0.0f)
  635. {
  636. // Calculate average wheel speed at clutch
  637. float wheel_speed_at_clutch = GetWheelSpeedAtClutch();
  638. // Draw the average wheel speed measured at clutch to compare engine RPM with wheel RPM
  639. 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);
  640. }
  641. // Draw current vehicle state
  642. String status = StringFormat("Forward: %.1f, Right: %.1f\nBrake: %.1f, HandBrake: %.1f\n"
  643. "Gear: %d, Clutch: %.1f\nEngineRPM: %.0f, V: %.1f km/h",
  644. (double)mForwardInput, (double)mRightInput, (double)mBrakeInput, (double)mHandBrakeInput,
  645. mTransmission.GetCurrentGear(), (double)mTransmission.GetClutchFriction(), (double)mEngine.GetCurrentRPM(), (double)body->GetLinearVelocity().Length() * 3.6);
  646. inRenderer->DrawText3D(body->GetPosition(), status, Color::sWhite, constraint_size);
  647. RMat44 body_transform = body->GetWorldTransform();
  648. for (const Wheel *w_base : mConstraint.GetWheels())
  649. {
  650. const WheelWV *w = static_cast<const WheelWV *>(w_base);
  651. const WheelSettings *settings = w->GetSettings();
  652. // Calculate where the suspension attaches to the body in world space
  653. RVec3 ws_position = body_transform * settings->mPosition;
  654. Vec3 ws_direction = body_transform.Multiply3x3(settings->mSuspensionDirection);
  655. // Draw suspension
  656. RVec3 min_suspension_pos = ws_position + ws_direction * settings->mSuspensionMinLength;
  657. RVec3 max_suspension_pos = ws_position + ws_direction * settings->mSuspensionMaxLength;
  658. inRenderer->DrawLine(ws_position, min_suspension_pos, Color::sRed);
  659. inRenderer->DrawLine(min_suspension_pos, max_suspension_pos, Color::sGreen);
  660. // Draw current length
  661. RVec3 wheel_pos = ws_position + ws_direction * w->GetSuspensionLength();
  662. inRenderer->DrawMarker(wheel_pos, w->GetSuspensionLength() < settings->mSuspensionMinLength? Color::sRed : Color::sGreen, constraint_size);
  663. // Draw wheel basis
  664. Vec3 wheel_forward, wheel_up, wheel_right;
  665. mConstraint.GetWheelLocalBasis(w, wheel_forward, wheel_up, wheel_right);
  666. wheel_forward = body_transform.Multiply3x3(wheel_forward);
  667. wheel_up = body_transform.Multiply3x3(wheel_up);
  668. wheel_right = body_transform.Multiply3x3(wheel_right);
  669. Vec3 steering_axis = body_transform.Multiply3x3(settings->mSteeringAxis);
  670. inRenderer->DrawLine(wheel_pos, wheel_pos + wheel_forward, Color::sRed);
  671. inRenderer->DrawLine(wheel_pos, wheel_pos + wheel_up, Color::sGreen);
  672. inRenderer->DrawLine(wheel_pos, wheel_pos + wheel_right, Color::sBlue);
  673. inRenderer->DrawLine(wheel_pos, wheel_pos + steering_axis, Color::sYellow);
  674. // Draw wheel
  675. RMat44 wheel_transform(Vec4(wheel_up, 0.0f), Vec4(wheel_right, 0.0f), Vec4(wheel_forward, 0.0f), wheel_pos);
  676. wheel_transform.SetRotation(wheel_transform.GetRotation() * Mat44::sRotationY(-w->GetRotationAngle()));
  677. inRenderer->DrawCylinder(wheel_transform, settings->mWidth * 0.5f, settings->mRadius, w->GetSuspensionLength() <= settings->mSuspensionMinLength? Color::sRed : Color::sGreen, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  678. if (w->HasContact())
  679. {
  680. // Draw contact
  681. inRenderer->DrawLine(w->GetContactPosition(), w->GetContactPosition() + w->GetContactNormal(), Color::sYellow);
  682. inRenderer->DrawLine(w->GetContactPosition(), w->GetContactPosition() + w->GetContactLongitudinal(), Color::sRed);
  683. inRenderer->DrawLine(w->GetContactPosition(), w->GetContactPosition() + w->GetContactLateral(), Color::sBlue);
  684. DebugRenderer::sInstance->DrawText3D(wheel_pos, StringFormat("W: %.1f, S: %.2f\nSlipLateral: %.1f, SlipLong: %.2f\nFrLateral: %.1f, FrLong: %.1f", (double)w->GetAngularVelocity(), (double)w->GetSuspensionLength(), (double)RadiansToDegrees(w->mLateralSlip), (double)w->mLongitudinalSlip, (double)w->mCombinedLateralFriction, (double)w->mCombinedLongitudinalFriction), Color::sWhite, constraint_size);
  685. }
  686. else
  687. {
  688. // Draw 'no hit'
  689. DebugRenderer::sInstance->DrawText3D(wheel_pos, StringFormat("W: %.1f", (double)w->GetAngularVelocity()), Color::sRed, constraint_size);
  690. }
  691. }
  692. }
  693. #endif // JPH_DEBUG_RENDERER
  694. void WheeledVehicleController::SaveState(StateRecorder &inStream) const
  695. {
  696. inStream.Write(mForwardInput);
  697. inStream.Write(mRightInput);
  698. inStream.Write(mBrakeInput);
  699. inStream.Write(mHandBrakeInput);
  700. inStream.Write(mPreviousDeltaTime);
  701. mEngine.SaveState(inStream);
  702. mTransmission.SaveState(inStream);
  703. }
  704. void WheeledVehicleController::RestoreState(StateRecorder &inStream)
  705. {
  706. inStream.Read(mForwardInput);
  707. inStream.Read(mRightInput);
  708. inStream.Read(mBrakeInput);
  709. inStream.Read(mHandBrakeInput);
  710. inStream.Read(mPreviousDeltaTime);
  711. mEngine.RestoreState(inStream);
  712. mTransmission.RestoreState(inStream);
  713. }
  714. void WheeledVehicleController::ToSettings(WheeledVehicleControllerSettings &outSettings) const
  715. {
  716. outSettings.mEngine = static_cast<const VehicleEngineSettings &>(mEngine);
  717. outSettings.mTransmission = static_cast<const VehicleTransmissionSettings &>(mTransmission);
  718. outSettings.mDifferentials = mDifferentials;
  719. outSettings.mDifferentialLimitedSlipRatio = mDifferentialLimitedSlipRatio;
  720. }
  721. Ref<VehicleControllerSettings> WheeledVehicleController::GetSettings() const
  722. {
  723. WheeledVehicleControllerSettings *settings = new WheeledVehicleControllerSettings;
  724. ToSettings(*settings);
  725. return settings;
  726. }
  727. JPH_NAMESPACE_END