VehicleConstraint.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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/VehicleConstraint.h>
  6. #include <Jolt/Physics/Vehicle/VehicleController.h>
  7. #include <Jolt/Physics/PhysicsSystem.h>
  8. #include <Jolt/ObjectStream/TypeDeclarations.h>
  9. #include <Jolt/Core/StreamIn.h>
  10. #include <Jolt/Core/StreamOut.h>
  11. #include <Jolt/Core/Factory.h>
  12. JPH_NAMESPACE_BEGIN
  13. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(VehicleConstraintSettings)
  14. {
  15. JPH_ADD_BASE_CLASS(VehicleConstraintSettings, ConstraintSettings)
  16. JPH_ADD_ATTRIBUTE(VehicleConstraintSettings, mUp)
  17. JPH_ADD_ATTRIBUTE(VehicleConstraintSettings, mForward)
  18. JPH_ADD_ATTRIBUTE(VehicleConstraintSettings, mMaxPitchRollAngle)
  19. JPH_ADD_ATTRIBUTE(VehicleConstraintSettings, mWheels)
  20. JPH_ADD_ATTRIBUTE(VehicleConstraintSettings, mAntiRollBars)
  21. JPH_ADD_ATTRIBUTE(VehicleConstraintSettings, mController)
  22. }
  23. void VehicleConstraintSettings::SaveBinaryState(StreamOut &inStream) const
  24. {
  25. ConstraintSettings::SaveBinaryState(inStream);
  26. inStream.Write(mUp);
  27. inStream.Write(mForward);
  28. inStream.Write(mMaxPitchRollAngle);
  29. uint32 num_anti_rollbars = (uint32)mAntiRollBars.size();
  30. inStream.Write(num_anti_rollbars);
  31. for (const VehicleAntiRollBar &r : mAntiRollBars)
  32. r.SaveBinaryState(inStream);
  33. uint32 num_wheels = (uint32)mWheels.size();
  34. inStream.Write(num_wheels);
  35. for (const WheelSettings *w : mWheels)
  36. w->SaveBinaryState(inStream);
  37. inStream.Write(mController->GetRTTI()->GetHash());
  38. mController->SaveBinaryState(inStream);
  39. }
  40. void VehicleConstraintSettings::RestoreBinaryState(StreamIn &inStream)
  41. {
  42. ConstraintSettings::RestoreBinaryState(inStream);
  43. inStream.Read(mUp);
  44. inStream.Read(mForward);
  45. inStream.Read(mMaxPitchRollAngle);
  46. uint32 num_anti_rollbars = 0;
  47. inStream.Read(num_anti_rollbars);
  48. mAntiRollBars.resize(num_anti_rollbars);
  49. for (VehicleAntiRollBar &r : mAntiRollBars)
  50. r.RestoreBinaryState(inStream);
  51. uint32 num_wheels = 0;
  52. inStream.Read(num_wheels);
  53. mWheels.resize(num_wheels);
  54. for (WheelSettings *w : mWheels)
  55. w->RestoreBinaryState(inStream);
  56. uint32 hash = 0;
  57. inStream.Read(hash);
  58. const RTTI *rtti = Factory::sInstance->Find(hash);
  59. mController = reinterpret_cast<VehicleControllerSettings *>(rtti->CreateObject());
  60. mController->RestoreBinaryState(inStream);
  61. }
  62. VehicleConstraint::VehicleConstraint(Body &inVehicleBody, const VehicleConstraintSettings &inSettings) :
  63. Constraint(inSettings),
  64. mBody(&inVehicleBody),
  65. mForward(inSettings.mForward),
  66. mUp(inSettings.mUp),
  67. mWorldUp(inSettings.mUp)
  68. {
  69. // Check sanity of incoming settings
  70. JPH_ASSERT(inSettings.mUp.IsNormalized());
  71. JPH_ASSERT(inSettings.mForward.IsNormalized());
  72. JPH_ASSERT(!inSettings.mWheels.empty());
  73. // Store max pitch/roll angle
  74. SetMaxPitchRollAngle(inSettings.mMaxPitchRollAngle);
  75. // Copy anti-rollbar settings
  76. mAntiRollBars.resize(inSettings.mAntiRollBars.size());
  77. for (uint i = 0; i < mAntiRollBars.size(); ++i)
  78. {
  79. const VehicleAntiRollBar &r = inSettings.mAntiRollBars[i];
  80. mAntiRollBars[i] = r;
  81. JPH_ASSERT(r.mStiffness >= 0.0f);
  82. }
  83. // Construct our controller class
  84. mController = inSettings.mController->ConstructController(*this);
  85. // Create wheels
  86. mWheels.resize(inSettings.mWheels.size());
  87. for (uint i = 0; i < mWheels.size(); ++i)
  88. mWheels[i] = mController->ConstructWheel(*inSettings.mWheels[i]);
  89. // Use the body ID as a seed for the step counter so that not all vehicles will update at the same time
  90. mCurrentStep = uint32(Hash64(inVehicleBody.GetID().GetIndex()));
  91. }
  92. VehicleConstraint::~VehicleConstraint()
  93. {
  94. // Destroy controller
  95. delete mController;
  96. // Destroy our wheels
  97. for (Wheel *w : mWheels)
  98. delete w;
  99. }
  100. void VehicleConstraint::GetWheelLocalBasis(const Wheel *inWheel, Vec3 &outForward, Vec3 &outUp, Vec3 &outRight) const
  101. {
  102. const WheelSettings *settings = inWheel->mSettings;
  103. Quat steer_rotation = Quat::sRotation(settings->mSteeringAxis, inWheel->mSteerAngle);
  104. outUp = steer_rotation * settings->mWheelUp;
  105. outForward = steer_rotation * settings->mWheelForward;
  106. outRight = outForward.Cross(outUp).Normalized();
  107. outForward = outUp.Cross(outRight).Normalized();
  108. }
  109. Mat44 VehicleConstraint::GetWheelLocalTransform(uint inWheelIndex, Vec3Arg inWheelRight, Vec3Arg inWheelUp) const
  110. {
  111. JPH_ASSERT(inWheelIndex < mWheels.size());
  112. const Wheel *wheel = mWheels[inWheelIndex];
  113. const WheelSettings *settings = wheel->mSettings;
  114. // Use the two vectors provided to calculate a matrix that takes us from wheel model space to X = right, Y = up, Z = forward (the space where we will rotate the wheel)
  115. Mat44 wheel_to_rotational = Mat44(Vec4(inWheelRight, 0), Vec4(inWheelUp, 0), Vec4(inWheelUp.Cross(inWheelRight), 0), Vec4(0, 0, 0, 1)).Transposed();
  116. // Calculate the matrix that takes us from the rotational space to vehicle local space
  117. Vec3 local_forward, local_up, local_right;
  118. GetWheelLocalBasis(wheel, local_forward, local_up, local_right);
  119. Vec3 local_wheel_pos = settings->mPosition + settings->mSuspensionDirection * wheel->mSuspensionLength;
  120. Mat44 rotational_to_local(Vec4(local_right, 0), Vec4(local_up, 0), Vec4(local_forward, 0), Vec4(local_wheel_pos, 1));
  121. // Calculate transform of rotated wheel
  122. return rotational_to_local * Mat44::sRotationX(wheel->mAngle) * wheel_to_rotational;
  123. }
  124. RMat44 VehicleConstraint::GetWheelWorldTransform(uint inWheelIndex, Vec3Arg inWheelRight, Vec3Arg inWheelUp) const
  125. {
  126. return mBody->GetWorldTransform() * GetWheelLocalTransform(inWheelIndex, inWheelRight, inWheelUp);
  127. }
  128. void VehicleConstraint::OnStep(float inDeltaTime, PhysicsSystem &inPhysicsSystem)
  129. {
  130. JPH_PROFILE_FUNCTION();
  131. // Callback to higher-level systems. We do it before PreCollide, in case steering changes.
  132. if (mPreStepCallback != nullptr)
  133. mPreStepCallback(*this, inDeltaTime, inPhysicsSystem);
  134. if (mIsGravityOverridden)
  135. {
  136. // If gravity is overridden, we replace the normal gravity calculations
  137. if (mBody->IsActive())
  138. {
  139. MotionProperties *mp = mBody->GetMotionProperties();
  140. mp->SetGravityFactor(0.0f);
  141. mBody->AddForce(mGravityOverride / mp->GetInverseMass());
  142. }
  143. // And we calculate the world up using the custom gravity
  144. mWorldUp = (-mGravityOverride).NormalizedOr(mWorldUp);
  145. }
  146. else
  147. {
  148. // Calculate new world up vector by inverting gravity
  149. mWorldUp = (-inPhysicsSystem.GetGravity()).NormalizedOr(mWorldUp);
  150. }
  151. // Callback on our controller
  152. mController->PreCollide(inDeltaTime, inPhysicsSystem);
  153. // Calculate if this constraint is active by checking if our main vehicle body is active or any of the bodies we touch are active
  154. mIsActive = mBody->IsActive();
  155. // Test how often we need to update the wheels
  156. uint num_steps_between_collisions = mIsActive? mNumStepsBetweenCollisionTestActive : mNumStepsBetweenCollisionTestInactive;
  157. RMat44 body_transform = mBody->GetWorldTransform();
  158. // Test collision for wheels
  159. for (uint wheel_index = 0; wheel_index < mWheels.size(); ++wheel_index)
  160. {
  161. Wheel *w = mWheels[wheel_index];
  162. const WheelSettings *settings = w->mSettings;
  163. // Calculate suspension origin and direction
  164. RVec3 ws_origin = body_transform * settings->mPosition;
  165. Vec3 ws_direction = body_transform.Multiply3x3(settings->mSuspensionDirection);
  166. // Test if we need to update this wheel
  167. if (num_steps_between_collisions == 0
  168. || (mCurrentStep + wheel_index) % num_steps_between_collisions != 0)
  169. {
  170. // Simplified wheel contact test
  171. if (!w->mContactBodyID.IsInvalid())
  172. {
  173. // Test if the body is still valid
  174. w->mContactBody = inPhysicsSystem.GetBodyLockInterfaceNoLock().TryGetBody(w->mContactBodyID);
  175. if (w->mContactBody == nullptr)
  176. {
  177. // It's not, forget the contact
  178. w->mContactBodyID = BodyID();
  179. w->mContactSubShapeID = SubShapeID();
  180. w->mSuspensionLength = settings->mSuspensionMaxLength;
  181. }
  182. else
  183. {
  184. // Extrapolate the wheel contact properties
  185. mVehicleCollisionTester->PredictContactProperties(inPhysicsSystem, *this, wheel_index, ws_origin, ws_direction, mBody->GetID(), w->mContactBody, w->mContactSubShapeID, w->mContactPosition, w->mContactNormal, w->mSuspensionLength);
  186. }
  187. }
  188. }
  189. else
  190. {
  191. // Full wheel contact test, start by resetting the contact data
  192. w->mContactBodyID = BodyID();
  193. w->mContactBody = nullptr;
  194. w->mContactSubShapeID = SubShapeID();
  195. w->mSuspensionLength = settings->mSuspensionMaxLength;
  196. // Test collision to find the floor
  197. if (mVehicleCollisionTester->Collide(inPhysicsSystem, *this, wheel_index, ws_origin, ws_direction, mBody->GetID(), w->mContactBody, w->mContactSubShapeID, w->mContactPosition, w->mContactNormal, w->mSuspensionLength))
  198. {
  199. // Store ID (pointer is not valid outside of the simulation step)
  200. w->mContactBodyID = w->mContactBody->GetID();
  201. }
  202. }
  203. if (w->mContactBody != nullptr)
  204. {
  205. // Store contact velocity, cache this as the contact body may be removed
  206. w->mContactPointVelocity = w->mContactBody->GetPointVelocity(w->mContactPosition);
  207. // Determine plane constant for axle contact plane
  208. w->mAxlePlaneConstant = RVec3(w->mContactNormal).Dot(ws_origin + w->mSuspensionLength * ws_direction);
  209. // Check if body is active, if so the entire vehicle should be active
  210. mIsActive |= w->mContactBody->IsActive();
  211. // Determine world space forward using steering angle and body rotation
  212. Vec3 forward, up, right;
  213. GetWheelLocalBasis(w, forward, up, right);
  214. forward = body_transform.Multiply3x3(forward);
  215. right = body_transform.Multiply3x3(right);
  216. // The longitudinal axis is in the up/forward plane
  217. w->mContactLongitudinal = w->mContactNormal.Cross(right);
  218. // Make sure that the longitudinal axis is aligned with the forward axis
  219. if (w->mContactLongitudinal.Dot(forward) < 0.0f)
  220. w->mContactLongitudinal = -w->mContactLongitudinal;
  221. // Normalize it
  222. w->mContactLongitudinal = w->mContactLongitudinal.NormalizedOr(w->mContactNormal.GetNormalizedPerpendicular());
  223. // The lateral axis is perpendicular to contact normal and longitudinal axis
  224. w->mContactLateral = w->mContactLongitudinal.Cross(w->mContactNormal).Normalized();
  225. }
  226. }
  227. // Callback to higher-level systems. We do it immediately after wheel collision.
  228. if (mPostCollideCallback != nullptr)
  229. mPostCollideCallback(*this, inDeltaTime, inPhysicsSystem);
  230. // Calculate anti-rollbar impulses
  231. for (const VehicleAntiRollBar &r : mAntiRollBars)
  232. {
  233. Wheel *lw = mWheels[r.mLeftWheel];
  234. Wheel *rw = mWheels[r.mRightWheel];
  235. if (lw->mContactBody != nullptr && rw->mContactBody != nullptr)
  236. {
  237. // Calculate the impulse to apply based on the difference in suspension length
  238. float difference = rw->mSuspensionLength - lw->mSuspensionLength;
  239. float impulse = difference * r.mStiffness * inDeltaTime;
  240. lw->mAntiRollBarImpulse = -impulse;
  241. rw->mAntiRollBarImpulse = impulse;
  242. }
  243. else
  244. {
  245. // When one of the wheels is not on the ground we don't apply any impulses
  246. lw->mAntiRollBarImpulse = rw->mAntiRollBarImpulse = 0.0f;
  247. }
  248. }
  249. // Callback on our controller
  250. mController->PostCollide(inDeltaTime, inPhysicsSystem);
  251. // Callback to higher-level systems. We do it before the sleep section, in case velocities change.
  252. if (mPostStepCallback != nullptr)
  253. mPostStepCallback(*this, inDeltaTime, inPhysicsSystem);
  254. // If the wheels are rotating, we don't want to go to sleep yet
  255. bool allow_sleep = mController->AllowSleep();
  256. if (allow_sleep)
  257. for (const Wheel *w : mWheels)
  258. if (abs(w->mAngularVelocity) > DegreesToRadians(10.0f))
  259. {
  260. allow_sleep = false;
  261. break;
  262. }
  263. if (mBody->GetAllowSleeping() != allow_sleep)
  264. mBody->SetAllowSleeping(allow_sleep);
  265. // Increment step counter
  266. ++mCurrentStep;
  267. }
  268. void VehicleConstraint::BuildIslands(uint32 inConstraintIndex, IslandBuilder &ioBuilder, BodyManager &inBodyManager)
  269. {
  270. // Find dynamic bodies that our wheels are touching
  271. BodyID *body_ids = (BodyID *)JPH_STACK_ALLOC((mWheels.size() + 1) * sizeof(BodyID));
  272. int num_bodies = 0;
  273. bool needs_to_activate = false;
  274. for (const Wheel *w : mWheels)
  275. if (w->mContactBody != nullptr)
  276. {
  277. // Avoid adding duplicates
  278. bool duplicate = false;
  279. BodyID id = w->mContactBody->GetID();
  280. for (int i = 0; i < num_bodies; ++i)
  281. if (body_ids[i] == id)
  282. {
  283. duplicate = true;
  284. break;
  285. }
  286. if (duplicate)
  287. continue;
  288. if (w->mContactBody->IsDynamic())
  289. {
  290. body_ids[num_bodies++] = id;
  291. needs_to_activate |= !w->mContactBody->IsActive();
  292. }
  293. }
  294. // Activate bodies, note that if we get here we have already told the system that we're active so that means our main body needs to be active too
  295. if (!mBody->IsActive())
  296. {
  297. // Our main body is not active, activate it too
  298. body_ids[num_bodies] = mBody->GetID();
  299. inBodyManager.ActivateBodies(body_ids, num_bodies + 1);
  300. }
  301. else if (needs_to_activate)
  302. {
  303. // Only activate bodies the wheels are touching
  304. inBodyManager.ActivateBodies(body_ids, num_bodies);
  305. }
  306. // Link the bodies into the same island
  307. uint32 min_active_index = Body::cInactiveIndex;
  308. for (int i = 0; i < num_bodies; ++i)
  309. {
  310. const Body &body = inBodyManager.GetBody(body_ids[i]);
  311. min_active_index = min(min_active_index, body.GetIndexInActiveBodiesInternal());
  312. ioBuilder.LinkBodies(mBody->GetIndexInActiveBodiesInternal(), body.GetIndexInActiveBodiesInternal());
  313. }
  314. // Link the constraint in the island
  315. ioBuilder.LinkConstraint(inConstraintIndex, mBody->GetIndexInActiveBodiesInternal(), min_active_index);
  316. }
  317. uint VehicleConstraint::BuildIslandSplits(LargeIslandSplitter &ioSplitter) const
  318. {
  319. return ioSplitter.AssignToNonParallelSplit(mBody);
  320. }
  321. void VehicleConstraint::CalculateSuspensionForcePoint(const Wheel &inWheel, Vec3 &outR1PlusU, Vec3 &outR2) const
  322. {
  323. // Determine point to apply force to
  324. RVec3 force_point;
  325. if (inWheel.mSettings->mEnableSuspensionForcePoint)
  326. force_point = mBody->GetWorldTransform() * inWheel.mSettings->mSuspensionForcePoint;
  327. else
  328. force_point = inWheel.mContactPosition;
  329. // Calculate r1 + u and r2
  330. outR1PlusU = Vec3(force_point - mBody->GetCenterOfMassPosition());
  331. outR2 = Vec3(force_point - inWheel.mContactBody->GetCenterOfMassPosition());
  332. }
  333. void VehicleConstraint::CalculatePitchRollConstraintProperties(RMat44Arg inBodyTransform)
  334. {
  335. // Check if a limit was specified
  336. if (mCosMaxPitchRollAngle > -1.0f)
  337. {
  338. // Calculate cos of angle between world up vector and vehicle up vector
  339. Vec3 vehicle_up = inBodyTransform.Multiply3x3(mUp);
  340. mCosPitchRollAngle = mWorldUp.Dot(vehicle_up);
  341. if (mCosPitchRollAngle < mCosMaxPitchRollAngle)
  342. {
  343. // Calculate rotation axis to rotate vehicle towards up
  344. Vec3 rotation_axis = mWorldUp.Cross(vehicle_up);
  345. float len = rotation_axis.Length();
  346. if (len > 0.0f)
  347. mPitchRollRotationAxis = rotation_axis / len;
  348. mPitchRollPart.CalculateConstraintProperties(*mBody, Body::sFixedToWorld, mPitchRollRotationAxis);
  349. }
  350. else
  351. mPitchRollPart.Deactivate();
  352. }
  353. else
  354. mPitchRollPart.Deactivate();
  355. }
  356. void VehicleConstraint::SetupVelocityConstraint(float inDeltaTime)
  357. {
  358. RMat44 body_transform = mBody->GetWorldTransform();
  359. for (Wheel *w : mWheels)
  360. if (w->mContactBody != nullptr)
  361. {
  362. const WheelSettings *settings = w->mSettings;
  363. Vec3 neg_contact_normal = -w->mContactNormal;
  364. Vec3 r1_plus_u, r2;
  365. CalculateSuspensionForcePoint(*w, r1_plus_u, r2);
  366. // Suspension spring
  367. if (settings->mSuspensionMaxLength > settings->mSuspensionMinLength)
  368. {
  369. float stiffness, damping;
  370. if (settings->mSuspensionSpring.mMode == ESpringMode::FrequencyAndDamping)
  371. {
  372. // Calculate effective mass based on vehicle configuration (the stiffness of the spring should not be affected by the dynamics of the vehicle): K = 1 / (J M^-1 J^T)
  373. // Note that if no suspension force point is supplied we don't know where the force is applied so we assume it is applied at average suspension length
  374. Vec3 force_point = settings->mEnableSuspensionForcePoint? settings->mSuspensionForcePoint : settings->mPosition + 0.5f * (settings->mSuspensionMinLength + settings->mSuspensionMaxLength) * settings->mSuspensionDirection;
  375. Vec3 force_point_x_neg_up = force_point.Cross(-mUp);
  376. const MotionProperties *mp = mBody->GetMotionProperties();
  377. float effective_mass = 1.0f / (mp->GetInverseMass() + force_point_x_neg_up.Dot(mp->GetLocalSpaceInverseInertia().Multiply3x3(force_point_x_neg_up)));
  378. // Convert frequency and damping to stiffness and damping
  379. float omega = 2.0f * JPH_PI * settings->mSuspensionSpring.mFrequency;
  380. stiffness = effective_mass * Square(omega);
  381. damping = 2.0f * effective_mass * settings->mSuspensionSpring.mDamping * omega;
  382. }
  383. else
  384. {
  385. // In this case we can simply copy the properties
  386. stiffness = settings->mSuspensionSpring.mStiffness;
  387. damping = settings->mSuspensionSpring.mDamping;
  388. }
  389. // Calculate the damping and frequency of the suspension spring given the angle between the suspension direction and the contact normal
  390. // If the angle between the suspension direction and the inverse of the contact normal is alpha then the force on the spring relates to the force along the contact normal as:
  391. //
  392. // Fspring = Fnormal * cos(alpha)
  393. //
  394. // The spring force is:
  395. //
  396. // Fspring = -k * x
  397. //
  398. // where k is the spring constant and x is the displacement of the spring. So we have:
  399. //
  400. // Fnormal * cos(alpha) = -k * x <=> Fnormal = -k / cos(alpha) * x
  401. //
  402. // So we can see this as a spring with spring constant:
  403. //
  404. // k' = k / cos(alpha)
  405. //
  406. // In the same way the velocity relates like:
  407. //
  408. // Vspring = Vnormal * cos(alpha)
  409. //
  410. // Which results in the modified damping constant c:
  411. //
  412. // c' = c / cos(alpha)
  413. //
  414. // Note that we clamp 1 / cos(alpha) to the range [0.1, 1] in order not to increase the stiffness / damping by too much.
  415. Vec3 ws_direction = body_transform.Multiply3x3(settings->mSuspensionDirection);
  416. float cos_angle = max(0.1f, ws_direction.Dot(neg_contact_normal));
  417. stiffness /= cos_angle;
  418. damping /= cos_angle;
  419. // Get the value of the constraint equation
  420. float c = w->mSuspensionLength - settings->mSuspensionMaxLength - settings->mSuspensionPreloadLength;
  421. w->mSuspensionPart.CalculateConstraintPropertiesWithStiffnessAndDamping(inDeltaTime, *mBody, r1_plus_u, *w->mContactBody, r2, neg_contact_normal, w->mAntiRollBarImpulse, c, stiffness, damping);
  422. }
  423. else
  424. w->mSuspensionPart.Deactivate();
  425. // Check if we reached the 'max up' position and if so add a hard velocity constraint that stops any further movement in the normal direction
  426. if (w->mSuspensionLength < settings->mSuspensionMinLength)
  427. w->mSuspensionMaxUpPart.CalculateConstraintProperties(*mBody, r1_plus_u, *w->mContactBody, r2, neg_contact_normal);
  428. else
  429. w->mSuspensionMaxUpPart.Deactivate();
  430. // Friction and propulsion
  431. w->mLongitudinalPart.CalculateConstraintProperties(*mBody, r1_plus_u, *w->mContactBody, r2, -w->mContactLongitudinal);
  432. w->mLateralPart.CalculateConstraintProperties(*mBody, r1_plus_u, *w->mContactBody, r2, -w->mContactLateral);
  433. }
  434. else
  435. {
  436. // No contact -> disable everything
  437. w->mSuspensionPart.Deactivate();
  438. w->mSuspensionMaxUpPart.Deactivate();
  439. w->mLongitudinalPart.Deactivate();
  440. w->mLateralPart.Deactivate();
  441. }
  442. CalculatePitchRollConstraintProperties(body_transform);
  443. }
  444. void VehicleConstraint::ResetWarmStart()
  445. {
  446. for (Wheel *w : mWheels)
  447. {
  448. w->mSuspensionPart.Deactivate();
  449. w->mSuspensionMaxUpPart.Deactivate();
  450. w->mLongitudinalPart.Deactivate();
  451. w->mLateralPart.Deactivate();
  452. }
  453. mPitchRollPart.Deactivate();
  454. }
  455. void VehicleConstraint::WarmStartVelocityConstraint(float inWarmStartImpulseRatio)
  456. {
  457. for (Wheel *w : mWheels)
  458. if (w->mContactBody != nullptr)
  459. {
  460. Vec3 neg_contact_normal = -w->mContactNormal;
  461. w->mSuspensionPart.WarmStart(*mBody, *w->mContactBody, neg_contact_normal, inWarmStartImpulseRatio);
  462. w->mSuspensionMaxUpPart.WarmStart(*mBody, *w->mContactBody, neg_contact_normal, inWarmStartImpulseRatio);
  463. w->mLongitudinalPart.WarmStart(*mBody, *w->mContactBody, -w->mContactLongitudinal, 0.0f); // Don't warm start the longitudinal part (the engine/brake force, we don't want to preserve anything from the last frame)
  464. w->mLateralPart.WarmStart(*mBody, *w->mContactBody, -w->mContactLateral, inWarmStartImpulseRatio);
  465. }
  466. mPitchRollPart.WarmStart(*mBody, Body::sFixedToWorld, inWarmStartImpulseRatio);
  467. }
  468. bool VehicleConstraint::SolveVelocityConstraint(float inDeltaTime)
  469. {
  470. bool impulse = false;
  471. // Solve suspension
  472. for (Wheel *w : mWheels)
  473. if (w->mContactBody != nullptr)
  474. {
  475. Vec3 neg_contact_normal = -w->mContactNormal;
  476. // Suspension spring, note that it can only push and not pull
  477. if (w->mSuspensionPart.IsActive())
  478. impulse |= w->mSuspensionPart.SolveVelocityConstraint(*mBody, *w->mContactBody, neg_contact_normal, 0.0f, FLT_MAX);
  479. // When reaching the minimal suspension length only allow forces pushing the bodies away
  480. if (w->mSuspensionMaxUpPart.IsActive())
  481. impulse |= w->mSuspensionMaxUpPart.SolveVelocityConstraint(*mBody, *w->mContactBody, neg_contact_normal, 0.0f, FLT_MAX);
  482. }
  483. // Solve the horizontal movement of the vehicle
  484. impulse |= mController->SolveLongitudinalAndLateralConstraints(inDeltaTime);
  485. // Apply the pitch / roll constraint to avoid the vehicle from toppling over
  486. if (mPitchRollPart.IsActive())
  487. impulse |= mPitchRollPart.SolveVelocityConstraint(*mBody, Body::sFixedToWorld, mPitchRollRotationAxis, 0, FLT_MAX);
  488. return impulse;
  489. }
  490. bool VehicleConstraint::SolvePositionConstraint(float inDeltaTime, float inBaumgarte)
  491. {
  492. bool impulse = false;
  493. RMat44 body_transform = mBody->GetWorldTransform();
  494. for (Wheel *w : mWheels)
  495. if (w->mContactBody != nullptr)
  496. {
  497. const WheelSettings *settings = w->mSettings;
  498. // Check if we reached the 'max up' position now that the body has possibly moved
  499. // We do this by calculating the axle position at minimum suspension length and making sure it does not go through the
  500. // plane defined by the contact normal and the axle position when the contact happened
  501. // TODO: This assumes that only the vehicle moved and not the ground as we kept the axle contact plane in world space
  502. Vec3 ws_direction = body_transform.Multiply3x3(settings->mSuspensionDirection);
  503. RVec3 ws_position = body_transform * settings->mPosition;
  504. RVec3 min_suspension_pos = ws_position + settings->mSuspensionMinLength * ws_direction;
  505. float max_up_error = float(RVec3(w->mContactNormal).Dot(min_suspension_pos) - w->mAxlePlaneConstant);
  506. if (max_up_error < 0.0f)
  507. {
  508. Vec3 neg_contact_normal = -w->mContactNormal;
  509. // Recalculate constraint properties since the body may have moved
  510. Vec3 r1_plus_u, r2;
  511. CalculateSuspensionForcePoint(*w, r1_plus_u, r2);
  512. w->mSuspensionMaxUpPart.CalculateConstraintProperties(*mBody, r1_plus_u, *w->mContactBody, r2, neg_contact_normal);
  513. impulse |= w->mSuspensionMaxUpPart.SolvePositionConstraint(*mBody, *w->mContactBody, neg_contact_normal, max_up_error, inBaumgarte);
  514. }
  515. }
  516. // Apply the pitch / roll constraint to avoid the vehicle from toppling over
  517. CalculatePitchRollConstraintProperties(body_transform);
  518. if (mPitchRollPart.IsActive())
  519. impulse |= mPitchRollPart.SolvePositionConstraint(*mBody, Body::sFixedToWorld, mCosPitchRollAngle - mCosMaxPitchRollAngle, inBaumgarte);
  520. return impulse;
  521. }
  522. #ifdef JPH_DEBUG_RENDERER
  523. void VehicleConstraint::DrawConstraint(DebugRenderer *inRenderer) const
  524. {
  525. mController->Draw(inRenderer);
  526. }
  527. void VehicleConstraint::DrawConstraintLimits(DebugRenderer *inRenderer) const
  528. {
  529. }
  530. #endif // JPH_DEBUG_RENDERER
  531. void VehicleConstraint::SaveState(StateRecorder &inStream) const
  532. {
  533. Constraint::SaveState(inStream);
  534. mController->SaveState(inStream);
  535. for (const Wheel *w : mWheels)
  536. {
  537. inStream.Write(w->mAngularVelocity);
  538. inStream.Write(w->mAngle);
  539. inStream.Write(w->mContactBodyID); // Used by MotorcycleController::PreCollide
  540. inStream.Write(w->mContactPosition); // Used by VehicleCollisionTester::PredictContactProperties
  541. inStream.Write(w->mContactNormal); // Used by MotorcycleController::PreCollide
  542. inStream.Write(w->mContactLateral); // Used by MotorcycleController::PreCollide
  543. inStream.Write(w->mSuspensionLength); // Used by VehicleCollisionTester::PredictContactProperties
  544. w->mSuspensionPart.SaveState(inStream);
  545. w->mSuspensionMaxUpPart.SaveState(inStream);
  546. w->mLongitudinalPart.SaveState(inStream);
  547. w->mLateralPart.SaveState(inStream);
  548. }
  549. inStream.Write(mPitchRollRotationAxis); // When rotation is too small we use last frame so we need to store it
  550. mPitchRollPart.SaveState(inStream);
  551. inStream.Write(mCurrentStep);
  552. }
  553. void VehicleConstraint::RestoreState(StateRecorder &inStream)
  554. {
  555. Constraint::RestoreState(inStream);
  556. mController->RestoreState(inStream);
  557. for (Wheel *w : mWheels)
  558. {
  559. inStream.Read(w->mAngularVelocity);
  560. inStream.Read(w->mAngle);
  561. inStream.Read(w->mContactBodyID);
  562. inStream.Read(w->mContactPosition);
  563. inStream.Read(w->mContactNormal);
  564. inStream.Read(w->mContactLateral);
  565. inStream.Read(w->mSuspensionLength);
  566. w->mContactBody = nullptr; // No longer valid
  567. w->mSuspensionPart.RestoreState(inStream);
  568. w->mSuspensionMaxUpPart.RestoreState(inStream);
  569. w->mLongitudinalPart.RestoreState(inStream);
  570. w->mLateralPart.RestoreState(inStream);
  571. }
  572. inStream.Read(mPitchRollRotationAxis);
  573. mPitchRollPart.RestoreState(inStream);
  574. inStream.Read(mCurrentStep);
  575. }
  576. Ref<ConstraintSettings> VehicleConstraint::GetConstraintSettings() const
  577. {
  578. JPH_ASSERT(false); // Not implemented yet
  579. return nullptr;
  580. }
  581. JPH_NAMESPACE_END