VehicleConstraint.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  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. // Calculate new world up vector by inverting gravity
  135. mWorldUp = (-inPhysicsSystem.GetGravity()).NormalizedOr(mWorldUp);
  136. // Callback on our controller
  137. mController->PreCollide(inDeltaTime, inPhysicsSystem);
  138. // Calculate if this constraint is active by checking if our main vehicle body is active or any of the bodies we touch are active
  139. mIsActive = mBody->IsActive();
  140. // Test how often we need to update the wheels
  141. uint num_steps_between_collisions = mIsActive? mNumStepsBetweenCollisionTestActive : mNumStepsBetweenCollisionTestInactive;
  142. RMat44 body_transform = mBody->GetWorldTransform();
  143. // Test collision for wheels
  144. for (uint wheel_index = 0; wheel_index < mWheels.size(); ++wheel_index)
  145. {
  146. Wheel *w = mWheels[wheel_index];
  147. const WheelSettings *settings = w->mSettings;
  148. // Calculate suspension origin and direction
  149. RVec3 ws_origin = body_transform * settings->mPosition;
  150. Vec3 ws_direction = body_transform.Multiply3x3(settings->mSuspensionDirection);
  151. // Test if we need to update this wheel
  152. if (num_steps_between_collisions == 0
  153. || (mCurrentStep + wheel_index) % num_steps_between_collisions != 0)
  154. {
  155. // Simplified wheel contact test
  156. if (!w->mContactBodyID.IsInvalid())
  157. {
  158. // Test if the body is still valid
  159. w->mContactBody = inPhysicsSystem.GetBodyLockInterfaceNoLock().TryGetBody(w->mContactBodyID);
  160. if (w->mContactBody == nullptr)
  161. {
  162. // It's not, forget the contact
  163. w->mContactBodyID = BodyID();
  164. w->mContactSubShapeID = SubShapeID();
  165. w->mSuspensionLength = settings->mSuspensionMaxLength;
  166. }
  167. else
  168. {
  169. // Extrapolate the wheel contact properties
  170. mVehicleCollisionTester->PredictContactProperties(inPhysicsSystem, *this, wheel_index, ws_origin, ws_direction, mBody->GetID(), w->mContactBody, w->mContactSubShapeID, w->mContactPosition, w->mContactNormal, w->mSuspensionLength);
  171. }
  172. }
  173. }
  174. else
  175. {
  176. // Full wheel contact test, start by resetting the contact data
  177. w->mContactBodyID = BodyID();
  178. w->mContactBody = nullptr;
  179. w->mContactSubShapeID = SubShapeID();
  180. w->mSuspensionLength = settings->mSuspensionMaxLength;
  181. // Test collision to find the floor
  182. if (mVehicleCollisionTester->Collide(inPhysicsSystem, *this, wheel_index, ws_origin, ws_direction, mBody->GetID(), w->mContactBody, w->mContactSubShapeID, w->mContactPosition, w->mContactNormal, w->mSuspensionLength))
  183. {
  184. // Store ID (pointer is not valid outside of the simulation step)
  185. w->mContactBodyID = w->mContactBody->GetID();
  186. }
  187. }
  188. if (w->mContactBody != nullptr)
  189. {
  190. // Store contact velocity, cache this as the contact body may be removed
  191. w->mContactPointVelocity = w->mContactBody->GetPointVelocity(w->mContactPosition);
  192. // Determine plane constant for axle contact plane
  193. w->mAxlePlaneConstant = RVec3(w->mContactNormal).Dot(ws_origin + w->mSuspensionLength * ws_direction);
  194. // Check if body is active, if so the entire vehicle should be active
  195. mIsActive |= w->mContactBody->IsActive();
  196. // Determine world space forward using steering angle and body rotation
  197. Vec3 forward, up, right;
  198. GetWheelLocalBasis(w, forward, up, right);
  199. forward = body_transform.Multiply3x3(forward);
  200. right = body_transform.Multiply3x3(right);
  201. // The longitudinal axis is in the up/forward plane
  202. w->mContactLongitudinal = w->mContactNormal.Cross(right);
  203. // Make sure that the longitudinal axis is aligned with the forward axis
  204. if (w->mContactLongitudinal.Dot(forward) < 0.0f)
  205. w->mContactLongitudinal = -w->mContactLongitudinal;
  206. // Normalize it
  207. w->mContactLongitudinal = w->mContactLongitudinal.NormalizedOr(w->mContactNormal.GetNormalizedPerpendicular());
  208. // The lateral axis is perpendicular to contact normal and longitudinal axis
  209. w->mContactLateral = w->mContactLongitudinal.Cross(w->mContactNormal).Normalized();
  210. }
  211. }
  212. // Callback to higher-level systems. We do it immediately after wheel collision.
  213. if (mPostCollideCallback != nullptr)
  214. mPostCollideCallback(*this, inDeltaTime, inPhysicsSystem);
  215. // Calculate anti-rollbar impulses
  216. for (const VehicleAntiRollBar &r : mAntiRollBars)
  217. {
  218. Wheel *lw = mWheels[r.mLeftWheel];
  219. Wheel *rw = mWheels[r.mRightWheel];
  220. if (lw->mContactBody != nullptr && rw->mContactBody != nullptr)
  221. {
  222. // Calculate the impulse to apply based on the difference in suspension length
  223. float difference = rw->mSuspensionLength - lw->mSuspensionLength;
  224. float impulse = difference * r.mStiffness * inDeltaTime;
  225. lw->mAntiRollBarImpulse = -impulse;
  226. rw->mAntiRollBarImpulse = impulse;
  227. }
  228. else
  229. {
  230. // When one of the wheels is not on the ground we don't apply any impulses
  231. lw->mAntiRollBarImpulse = rw->mAntiRollBarImpulse = 0.0f;
  232. }
  233. }
  234. // Callback on our controller
  235. mController->PostCollide(inDeltaTime, inPhysicsSystem);
  236. // Callback to higher-level systems. We do it before the sleep section, in case velocities change.
  237. if (mPostStepCallback != nullptr)
  238. mPostStepCallback(*this, inDeltaTime, inPhysicsSystem);
  239. // If the wheels are rotating, we don't want to go to sleep yet
  240. bool allow_sleep = mController->AllowSleep();
  241. if (allow_sleep)
  242. for (const Wheel *w : mWheels)
  243. if (abs(w->mAngularVelocity) > DegreesToRadians(10.0f))
  244. {
  245. allow_sleep = false;
  246. break;
  247. }
  248. if (mBody->GetAllowSleeping() != allow_sleep)
  249. mBody->SetAllowSleeping(allow_sleep);
  250. // Increment step counter
  251. ++mCurrentStep;
  252. }
  253. void VehicleConstraint::BuildIslands(uint32 inConstraintIndex, IslandBuilder &ioBuilder, BodyManager &inBodyManager)
  254. {
  255. // Find dynamic bodies that our wheels are touching
  256. BodyID *body_ids = (BodyID *)JPH_STACK_ALLOC((mWheels.size() + 1) * sizeof(BodyID));
  257. int num_bodies = 0;
  258. bool needs_to_activate = false;
  259. for (const Wheel *w : mWheels)
  260. if (w->mContactBody != nullptr)
  261. {
  262. // Avoid adding duplicates
  263. bool duplicate = false;
  264. BodyID id = w->mContactBody->GetID();
  265. for (int i = 0; i < num_bodies; ++i)
  266. if (body_ids[i] == id)
  267. {
  268. duplicate = true;
  269. break;
  270. }
  271. if (duplicate)
  272. continue;
  273. if (w->mContactBody->IsDynamic())
  274. {
  275. body_ids[num_bodies++] = id;
  276. needs_to_activate |= !w->mContactBody->IsActive();
  277. }
  278. }
  279. // 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
  280. if (!mBody->IsActive())
  281. {
  282. // Our main body is not active, activate it too
  283. body_ids[num_bodies] = mBody->GetID();
  284. inBodyManager.ActivateBodies(body_ids, num_bodies + 1);
  285. }
  286. else if (needs_to_activate)
  287. {
  288. // Only activate bodies the wheels are touching
  289. inBodyManager.ActivateBodies(body_ids, num_bodies);
  290. }
  291. // Link the bodies into the same island
  292. uint32 min_active_index = Body::cInactiveIndex;
  293. for (int i = 0; i < num_bodies; ++i)
  294. {
  295. const Body &body = inBodyManager.GetBody(body_ids[i]);
  296. min_active_index = min(min_active_index, body.GetIndexInActiveBodiesInternal());
  297. ioBuilder.LinkBodies(mBody->GetIndexInActiveBodiesInternal(), body.GetIndexInActiveBodiesInternal());
  298. }
  299. // Link the constraint in the island
  300. ioBuilder.LinkConstraint(inConstraintIndex, mBody->GetIndexInActiveBodiesInternal(), min_active_index);
  301. }
  302. uint VehicleConstraint::BuildIslandSplits(LargeIslandSplitter &ioSplitter) const
  303. {
  304. return ioSplitter.AssignToNonParallelSplit(mBody);
  305. }
  306. void VehicleConstraint::CalculateSuspensionForcePoint(const Wheel &inWheel, Vec3 &outR1PlusU, Vec3 &outR2) const
  307. {
  308. // Determine point to apply force to
  309. RVec3 force_point;
  310. if (inWheel.mSettings->mEnableSuspensionForcePoint)
  311. force_point = mBody->GetWorldTransform() * inWheel.mSettings->mSuspensionForcePoint;
  312. else
  313. force_point = inWheel.mContactPosition;
  314. // Calculate r1 + u and r2
  315. outR1PlusU = Vec3(force_point - mBody->GetCenterOfMassPosition());
  316. outR2 = Vec3(force_point - inWheel.mContactBody->GetCenterOfMassPosition());
  317. }
  318. void VehicleConstraint::CalculatePitchRollConstraintProperties(RMat44Arg inBodyTransform)
  319. {
  320. // Check if a limit was specified
  321. if (mCosMaxPitchRollAngle > -1.0f)
  322. {
  323. // Calculate cos of angle between world up vector and vehicle up vector
  324. Vec3 vehicle_up = inBodyTransform.Multiply3x3(mUp);
  325. mCosPitchRollAngle = mWorldUp.Dot(vehicle_up);
  326. if (mCosPitchRollAngle < mCosMaxPitchRollAngle)
  327. {
  328. // Calculate rotation axis to rotate vehicle towards up
  329. Vec3 rotation_axis = mWorldUp.Cross(vehicle_up);
  330. float len = rotation_axis.Length();
  331. if (len > 0.0f)
  332. mPitchRollRotationAxis = rotation_axis / len;
  333. mPitchRollPart.CalculateConstraintProperties(*mBody, Body::sFixedToWorld, mPitchRollRotationAxis);
  334. }
  335. else
  336. mPitchRollPart.Deactivate();
  337. }
  338. else
  339. mPitchRollPart.Deactivate();
  340. }
  341. void VehicleConstraint::SetupVelocityConstraint(float inDeltaTime)
  342. {
  343. RMat44 body_transform = mBody->GetWorldTransform();
  344. for (Wheel *w : mWheels)
  345. if (w->mContactBody != nullptr)
  346. {
  347. const WheelSettings *settings = w->mSettings;
  348. Vec3 neg_contact_normal = -w->mContactNormal;
  349. Vec3 r1_plus_u, r2;
  350. CalculateSuspensionForcePoint(*w, r1_plus_u, r2);
  351. // Suspension spring
  352. if (settings->mSuspensionMaxLength > settings->mSuspensionMinLength)
  353. {
  354. float stiffness, damping;
  355. if (settings->mSuspensionSpring.mMode == ESpringMode::FrequencyAndDamping)
  356. {
  357. // 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)
  358. // 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
  359. Vec3 force_point = settings->mEnableSuspensionForcePoint? settings->mSuspensionForcePoint : settings->mPosition + 0.5f * (settings->mSuspensionMinLength + settings->mSuspensionMaxLength) * settings->mSuspensionDirection;
  360. Vec3 force_point_x_neg_up = force_point.Cross(-mUp);
  361. const MotionProperties *mp = mBody->GetMotionProperties();
  362. float effective_mass = 1.0f / (mp->GetInverseMass() + force_point_x_neg_up.Dot(mp->GetLocalSpaceInverseInertia().Multiply3x3(force_point_x_neg_up)));
  363. // Convert frequency and damping to stiffness and damping
  364. float omega = 2.0f * JPH_PI * settings->mSuspensionSpring.mFrequency;
  365. stiffness = effective_mass * Square(omega);
  366. damping = 2.0f * effective_mass * settings->mSuspensionSpring.mDamping * omega;
  367. }
  368. else
  369. {
  370. // In this case we can simply copy the properties
  371. stiffness = settings->mSuspensionSpring.mStiffness;
  372. damping = settings->mSuspensionSpring.mDamping;
  373. }
  374. // Calculate the damping and frequency of the suspension spring given the angle between the suspension direction and the contact normal
  375. // 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:
  376. //
  377. // Fspring = Fnormal * cos(alpha)
  378. //
  379. // The spring force is:
  380. //
  381. // Fspring = -k * x
  382. //
  383. // where k is the spring constant and x is the displacement of the spring. So we have:
  384. //
  385. // Fnormal * cos(alpha) = -k * x <=> Fnormal = -k / cos(alpha) * x
  386. //
  387. // So we can see this as a spring with spring constant:
  388. //
  389. // k' = k / cos(alpha)
  390. //
  391. // In the same way the velocity relates like:
  392. //
  393. // Vspring = Vnormal * cos(alpha)
  394. //
  395. // Which results in the modified damping constant c:
  396. //
  397. // c' = c / cos(alpha)
  398. //
  399. // Note that we clamp 1 / cos(alpha) to the range [0.1, 1] in order not to increase the stiffness / damping by too much.
  400. Vec3 ws_direction = body_transform.Multiply3x3(settings->mSuspensionDirection);
  401. float cos_angle = max(0.1f, ws_direction.Dot(neg_contact_normal));
  402. stiffness /= cos_angle;
  403. damping /= cos_angle;
  404. // Get the value of the constraint equation
  405. float c = w->mSuspensionLength - settings->mSuspensionMaxLength - settings->mSuspensionPreloadLength;
  406. w->mSuspensionPart.CalculateConstraintPropertiesWithStiffnessAndDamping(inDeltaTime, *mBody, r1_plus_u, *w->mContactBody, r2, neg_contact_normal, w->mAntiRollBarImpulse, c, stiffness, damping);
  407. }
  408. else
  409. w->mSuspensionPart.Deactivate();
  410. // 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
  411. if (w->mSuspensionLength < settings->mSuspensionMinLength)
  412. w->mSuspensionMaxUpPart.CalculateConstraintProperties(*mBody, r1_plus_u, *w->mContactBody, r2, neg_contact_normal);
  413. else
  414. w->mSuspensionMaxUpPart.Deactivate();
  415. // Friction and propulsion
  416. w->mLongitudinalPart.CalculateConstraintProperties(*mBody, r1_plus_u, *w->mContactBody, r2, -w->mContactLongitudinal);
  417. w->mLateralPart.CalculateConstraintProperties(*mBody, r1_plus_u, *w->mContactBody, r2, -w->mContactLateral);
  418. }
  419. else
  420. {
  421. // No contact -> disable everything
  422. w->mSuspensionPart.Deactivate();
  423. w->mSuspensionMaxUpPart.Deactivate();
  424. w->mLongitudinalPart.Deactivate();
  425. w->mLateralPart.Deactivate();
  426. }
  427. CalculatePitchRollConstraintProperties(body_transform);
  428. }
  429. void VehicleConstraint::ResetWarmStart()
  430. {
  431. for (Wheel *w : mWheels)
  432. {
  433. w->mSuspensionPart.Deactivate();
  434. w->mSuspensionMaxUpPart.Deactivate();
  435. w->mLongitudinalPart.Deactivate();
  436. w->mLateralPart.Deactivate();
  437. }
  438. mPitchRollPart.Deactivate();
  439. }
  440. void VehicleConstraint::WarmStartVelocityConstraint(float inWarmStartImpulseRatio)
  441. {
  442. for (Wheel *w : mWheels)
  443. if (w->mContactBody != nullptr)
  444. {
  445. Vec3 neg_contact_normal = -w->mContactNormal;
  446. w->mSuspensionPart.WarmStart(*mBody, *w->mContactBody, neg_contact_normal, inWarmStartImpulseRatio);
  447. w->mSuspensionMaxUpPart.WarmStart(*mBody, *w->mContactBody, neg_contact_normal, inWarmStartImpulseRatio);
  448. 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)
  449. w->mLateralPart.WarmStart(*mBody, *w->mContactBody, -w->mContactLateral, inWarmStartImpulseRatio);
  450. }
  451. mPitchRollPart.WarmStart(*mBody, Body::sFixedToWorld, inWarmStartImpulseRatio);
  452. }
  453. bool VehicleConstraint::SolveVelocityConstraint(float inDeltaTime)
  454. {
  455. bool impulse = false;
  456. // Solve suspension
  457. for (Wheel *w : mWheels)
  458. if (w->mContactBody != nullptr)
  459. {
  460. Vec3 neg_contact_normal = -w->mContactNormal;
  461. // Suspension spring, note that it can only push and not pull
  462. if (w->mSuspensionPart.IsActive())
  463. impulse |= w->mSuspensionPart.SolveVelocityConstraint(*mBody, *w->mContactBody, neg_contact_normal, 0.0f, FLT_MAX);
  464. // When reaching the minimal suspension length only allow forces pushing the bodies away
  465. if (w->mSuspensionMaxUpPart.IsActive())
  466. impulse |= w->mSuspensionMaxUpPart.SolveVelocityConstraint(*mBody, *w->mContactBody, neg_contact_normal, 0.0f, FLT_MAX);
  467. }
  468. // Solve the horizontal movement of the vehicle
  469. impulse |= mController->SolveLongitudinalAndLateralConstraints(inDeltaTime);
  470. // Apply the pitch / roll constraint to avoid the vehicle from toppling over
  471. if (mPitchRollPart.IsActive())
  472. impulse |= mPitchRollPart.SolveVelocityConstraint(*mBody, Body::sFixedToWorld, mPitchRollRotationAxis, 0, FLT_MAX);
  473. return impulse;
  474. }
  475. bool VehicleConstraint::SolvePositionConstraint(float inDeltaTime, float inBaumgarte)
  476. {
  477. bool impulse = false;
  478. RMat44 body_transform = mBody->GetWorldTransform();
  479. for (Wheel *w : mWheels)
  480. if (w->mContactBody != nullptr)
  481. {
  482. const WheelSettings *settings = w->mSettings;
  483. // Check if we reached the 'max up' position now that the body has possibly moved
  484. // We do this by calculating the axle position at minimum suspension length and making sure it does not go through the
  485. // plane defined by the contact normal and the axle position when the contact happened
  486. // TODO: This assumes that only the vehicle moved and not the ground as we kept the axle contact plane in world space
  487. Vec3 ws_direction = body_transform.Multiply3x3(settings->mSuspensionDirection);
  488. RVec3 ws_position = body_transform * settings->mPosition;
  489. RVec3 min_suspension_pos = ws_position + settings->mSuspensionMinLength * ws_direction;
  490. float max_up_error = float(RVec3(w->mContactNormal).Dot(min_suspension_pos) - w->mAxlePlaneConstant);
  491. if (max_up_error < 0.0f)
  492. {
  493. Vec3 neg_contact_normal = -w->mContactNormal;
  494. // Recalculate constraint properties since the body may have moved
  495. Vec3 r1_plus_u, r2;
  496. CalculateSuspensionForcePoint(*w, r1_plus_u, r2);
  497. w->mSuspensionMaxUpPart.CalculateConstraintProperties(*mBody, r1_plus_u, *w->mContactBody, r2, neg_contact_normal);
  498. impulse |= w->mSuspensionMaxUpPart.SolvePositionConstraint(*mBody, *w->mContactBody, neg_contact_normal, max_up_error, inBaumgarte);
  499. }
  500. }
  501. // Apply the pitch / roll constraint to avoid the vehicle from toppling over
  502. CalculatePitchRollConstraintProperties(body_transform);
  503. if (mPitchRollPart.IsActive())
  504. impulse |= mPitchRollPart.SolvePositionConstraint(*mBody, Body::sFixedToWorld, mCosPitchRollAngle - mCosMaxPitchRollAngle, inBaumgarte);
  505. return impulse;
  506. }
  507. #ifdef JPH_DEBUG_RENDERER
  508. void VehicleConstraint::DrawConstraint(DebugRenderer *inRenderer) const
  509. {
  510. mController->Draw(inRenderer);
  511. }
  512. void VehicleConstraint::DrawConstraintLimits(DebugRenderer *inRenderer) const
  513. {
  514. }
  515. #endif // JPH_DEBUG_RENDERER
  516. void VehicleConstraint::SaveState(StateRecorder &inStream) const
  517. {
  518. Constraint::SaveState(inStream);
  519. mController->SaveState(inStream);
  520. for (const Wheel *w : mWheels)
  521. {
  522. inStream.Write(w->mAngularVelocity);
  523. inStream.Write(w->mAngle);
  524. inStream.Write(w->mContactBodyID); // Used by MotorcycleController::PreCollide
  525. inStream.Write(w->mContactPosition); // Used by VehicleCollisionTester::PredictContactProperties
  526. inStream.Write(w->mContactNormal); // Used by MotorcycleController::PreCollide
  527. inStream.Write(w->mContactLateral); // Used by MotorcycleController::PreCollide
  528. inStream.Write(w->mSuspensionLength); // Used by VehicleCollisionTester::PredictContactProperties
  529. w->mSuspensionPart.SaveState(inStream);
  530. w->mSuspensionMaxUpPart.SaveState(inStream);
  531. w->mLongitudinalPart.SaveState(inStream);
  532. w->mLateralPart.SaveState(inStream);
  533. }
  534. inStream.Write(mPitchRollRotationAxis); // When rotation is too small we use last frame so we need to store it
  535. mPitchRollPart.SaveState(inStream);
  536. inStream.Write(mCurrentStep);
  537. }
  538. void VehicleConstraint::RestoreState(StateRecorder &inStream)
  539. {
  540. Constraint::RestoreState(inStream);
  541. mController->RestoreState(inStream);
  542. for (Wheel *w : mWheels)
  543. {
  544. inStream.Read(w->mAngularVelocity);
  545. inStream.Read(w->mAngle);
  546. inStream.Read(w->mContactBodyID);
  547. inStream.Read(w->mContactPosition);
  548. inStream.Read(w->mContactNormal);
  549. inStream.Read(w->mContactLateral);
  550. inStream.Read(w->mSuspensionLength);
  551. w->mContactBody = nullptr; // No longer valid
  552. w->mSuspensionPart.RestoreState(inStream);
  553. w->mSuspensionMaxUpPart.RestoreState(inStream);
  554. w->mLongitudinalPart.RestoreState(inStream);
  555. w->mLateralPart.RestoreState(inStream);
  556. }
  557. inStream.Read(mPitchRollRotationAxis);
  558. mPitchRollPart.RestoreState(inStream);
  559. inStream.Read(mCurrentStep);
  560. }
  561. Ref<ConstraintSettings> VehicleConstraint::GetConstraintSettings() const
  562. {
  563. JPH_ASSERT(false); // Not implemented yet
  564. return nullptr;
  565. }
  566. JPH_NAMESPACE_END