MotorcycleController.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2023 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/Physics/Vehicle/MotorcycleController.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. #ifdef JPH_DEBUG_RENDERER
  11. #include <Jolt/Renderer/DebugRenderer.h>
  12. #endif // JPH_DEBUG_RENDERER
  13. JPH_NAMESPACE_BEGIN
  14. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(MotorcycleControllerSettings)
  15. {
  16. JPH_ADD_BASE_CLASS(MotorcycleControllerSettings, VehicleControllerSettings)
  17. JPH_ADD_ATTRIBUTE(MotorcycleControllerSettings, mMaxLeanAngle)
  18. JPH_ADD_ATTRIBUTE(MotorcycleControllerSettings, mLeanSpringConstant)
  19. JPH_ADD_ATTRIBUTE(MotorcycleControllerSettings, mLeanSpringDamping)
  20. JPH_ADD_ATTRIBUTE(MotorcycleControllerSettings, mLeanSmoothingFactor)
  21. }
  22. VehicleController *MotorcycleControllerSettings::ConstructController(VehicleConstraint &inConstraint) const
  23. {
  24. return new MotorcycleController(*this, inConstraint);
  25. }
  26. void MotorcycleControllerSettings::SaveBinaryState(StreamOut &inStream) const
  27. {
  28. WheeledVehicleControllerSettings::SaveBinaryState(inStream);
  29. inStream.Write(mMaxLeanAngle);
  30. inStream.Write(mLeanSpringConstant);
  31. inStream.Write(mLeanSpringDamping);
  32. inStream.Write(mLeanSmoothingFactor);
  33. }
  34. void MotorcycleControllerSettings::RestoreBinaryState(StreamIn &inStream)
  35. {
  36. WheeledVehicleControllerSettings::RestoreBinaryState(inStream);
  37. inStream.Read(mMaxLeanAngle);
  38. inStream.Read(mLeanSpringConstant);
  39. inStream.Read(mLeanSpringDamping);
  40. inStream.Read(mLeanSmoothingFactor);
  41. }
  42. MotorcycleController::MotorcycleController(const MotorcycleControllerSettings &inSettings, VehicleConstraint &inConstraint) :
  43. WheeledVehicleController(inSettings, inConstraint),
  44. mMaxLeanAngle(inSettings.mMaxLeanAngle),
  45. mLeanSpringConstant(inSettings.mLeanSpringConstant),
  46. mLeanSpringDamping(inSettings.mLeanSpringDamping),
  47. mLeanSmoothingFactor(inSettings.mLeanSmoothingFactor)
  48. {
  49. }
  50. float MotorcycleController::GetWheelBase() const
  51. {
  52. float low = FLT_MAX, high = -FLT_MAX;
  53. for (const Wheel *w : mConstraint.GetWheels())
  54. {
  55. const WheelSettings *s = w->GetSettings();
  56. // Measure distance along the forward axis by looking at the fully extended suspension
  57. float value = (s->mPosition + s->mSuspensionDirection * s->mSuspensionMaxLength).Dot(mConstraint.GetLocalForward());
  58. // Update min and max
  59. low = min(low, value);
  60. high = max(high, value);
  61. }
  62. return high - low;
  63. }
  64. void MotorcycleController::PreCollide(float inDeltaTime, PhysicsSystem &inPhysicsSystem)
  65. {
  66. WheeledVehicleController::PreCollide(inDeltaTime, inPhysicsSystem);
  67. const Body *body = mConstraint.GetVehicleBody();
  68. Vec3 forward = body->GetRotation() * mConstraint.GetLocalForward();
  69. float wheel_base = GetWheelBase();
  70. float velocity = body->GetLinearVelocity().Dot(forward);
  71. float velocity_sq = Square(velocity);
  72. // Calculate the target lean vector, this is in the direction of the total applied impulse by the ground on the wheels
  73. Vec3 target_lean = Vec3::sZero();
  74. for (const Wheel *w : mConstraint.GetWheels())
  75. if (w->HasContact())
  76. target_lean += w->GetContactNormal() * w->GetSuspensionLambda() + w->GetContactLateral() * w->GetLateralLambda();
  77. // Normalize the impulse
  78. Vec3 world_up = mConstraint.GetWorldUp();
  79. target_lean = target_lean.NormalizedOr(world_up);
  80. // Smooth the impulse to avoid jittery behavior
  81. mTargetLean = mLeanSmoothingFactor * mTargetLean + (1.0f - mLeanSmoothingFactor) * target_lean;
  82. // Remove forward component, we can only lean sideways
  83. mTargetLean -= mTargetLean * mTargetLean.Dot(forward);
  84. mTargetLean = mTargetLean.NormalizedOr(world_up);
  85. JPH_DET_LOG("WheeledVehicleController::PreCollide: target_lean: " << target_lean << " mTargetLean: " << mTargetLean);
  86. // Calculate max steering angle based on the max lean angle we're willing to take
  87. // See: https://en.wikipedia.org/wiki/Bicycle_and_motorcycle_dynamics#Leaning
  88. // LeanAngle = Atan(Velocity^2 / (Gravity * TurnRadius))
  89. // And: https://en.wikipedia.org/wiki/Turning_radius (we're ignoring the tire width)
  90. // The CasterAngle is the added according to https://en.wikipedia.org/wiki/Bicycle_and_motorcycle_dynamics#Turning (this is the same formula but without small angle approximation)
  91. // TurnRadius = WheelBase / (Sin(SteerAngle) * Cos(CasterAngle))
  92. // => SteerAngle = ASin(WheelBase * Tan(LeanAngle) * Gravity / (Velocity^2 * Cos(CasterAngle))
  93. // The caster angle is different for each wheel so we can only calculate part of the equation here
  94. float max_steer_angle_factor = wheel_base * Tan(mMaxLeanAngle) * inPhysicsSystem.GetGravity().Length();
  95. // Decompose steering into sign and direction
  96. float steer_strength = abs(mRightInput);
  97. float steer_sign = -Sign(mRightInput);
  98. for (Wheel *w_base : mConstraint.GetWheels())
  99. {
  100. WheelWV *w = static_cast<WheelWV *>(w_base);
  101. const WheelSettingsWV *s = w->GetSettings();
  102. // Check if this wheel can steer
  103. if (s->mMaxSteerAngle != 0.0f)
  104. {
  105. // Calculate cos(caster angle), the angle between the steering axis and the up vector
  106. float cos_caster_angle = s->mSteeringAxis.Dot(mConstraint.GetLocalUp());
  107. // Calculate steer angle
  108. float steer_angle = steer_strength * w->GetSettings()->mMaxSteerAngle;
  109. // Clamp to max steering angle
  110. if (velocity_sq > 1.0e-6f && cos_caster_angle > 1.0e-6f)
  111. {
  112. float max_steer_angle = ASin(max_steer_angle_factor / (velocity_sq * cos_caster_angle));
  113. steer_angle = min(steer_angle, max_steer_angle);
  114. }
  115. // Set steering angle
  116. w->SetSteerAngle(steer_sign * steer_angle);
  117. }
  118. }
  119. // Reset applied impulse
  120. mAppliedImpulse = 0;
  121. }
  122. bool MotorcycleController::SolveLongitudinalAndLateralConstraints(float inDeltaTime)
  123. {
  124. bool impulse = WheeledVehicleController::SolveLongitudinalAndLateralConstraints(inDeltaTime);
  125. // Only apply a lean impulse if all wheels are in contact, otherwise we can easily spin out
  126. bool all_in_contact = true;
  127. for (const Wheel *w : mConstraint.GetWheels())
  128. if (!w->HasContact() || w->GetSuspensionLambda() <= 0.0f)
  129. {
  130. all_in_contact = false;
  131. break;
  132. }
  133. if (all_in_contact)
  134. {
  135. Body *body = mConstraint.GetVehicleBody();
  136. const MotionProperties *mp = body->GetMotionProperties();
  137. Vec3 forward = body->GetRotation() * mConstraint.GetLocalForward();
  138. Vec3 up = body->GetRotation() * mConstraint.GetLocalUp();
  139. // Calculate delta to target angle and derivative
  140. float d_angle = -Sign(mTargetLean.Cross(up).Dot(forward)) * ACos(mTargetLean.Dot(up));
  141. float ddt_angle = body->GetAngularVelocity().Dot(forward);
  142. // Calculate impulse to apply to get to target lean angle
  143. float total_impulse = (mLeanSpringConstant * d_angle - mLeanSpringDamping * ddt_angle) * inDeltaTime;
  144. // Remember angular velocity pre angular impulse
  145. Vec3 old_w = mp->GetAngularVelocity();
  146. // Apply impulse taking into account the impulse we've applied earlier
  147. float delta_impulse = total_impulse - mAppliedImpulse;
  148. body->AddAngularImpulse(delta_impulse * forward);
  149. mAppliedImpulse = total_impulse;
  150. // Calculate delta angular velocity due to angular impulse
  151. Vec3 dw = mp->GetAngularVelocity() - old_w;
  152. Vec3 linear_acceleration = Vec3::sZero();
  153. float total_lambda = 0.0f;
  154. for (Wheel *w_base : mConstraint.GetWheels())
  155. {
  156. const WheelWV *w = static_cast<WheelWV *>(w_base);
  157. // We weigh the importance of each contact point according to the contact force
  158. float lambda = w->GetSuspensionLambda();
  159. total_lambda += lambda;
  160. // Linear acceleration of contact point is dw x com_to_contact
  161. Vec3 r = Vec3(w->GetContactPosition() - body->GetCenterOfMassPosition());
  162. linear_acceleration += lambda * dw.Cross(r);
  163. }
  164. // Apply linear impulse to COM to cancel the average velocity change on the wheels due to the angular impulse
  165. Vec3 linear_impulse = -linear_acceleration / (total_lambda * mp->GetInverseMass());
  166. body->AddImpulse(linear_impulse);
  167. // Return true if we applied an impulse
  168. impulse |= delta_impulse != 0.0f;
  169. }
  170. return impulse;
  171. }
  172. void MotorcycleController::SaveState(StateRecorder& inStream) const
  173. {
  174. WheeledVehicleController::SaveState(inStream);
  175. inStream.Write(mTargetLean);
  176. }
  177. void MotorcycleController::RestoreState(StateRecorder& inStream)
  178. {
  179. WheeledVehicleController::RestoreState(inStream);
  180. inStream.Read(mTargetLean);
  181. }
  182. #ifdef JPH_DEBUG_RENDERER
  183. void MotorcycleController::Draw(DebugRenderer *inRenderer) const
  184. {
  185. WheeledVehicleController::Draw(inRenderer);
  186. // Draw current and desired lean angle
  187. Body *body = mConstraint.GetVehicleBody();
  188. RVec3 center_of_mass = body->GetCenterOfMassPosition();
  189. Vec3 up = body->GetRotation() * mConstraint.GetLocalUp();
  190. inRenderer->DrawArrow(center_of_mass, center_of_mass + up, Color::sYellow, 0.1f);
  191. inRenderer->DrawArrow(center_of_mass, center_of_mass + mTargetLean, Color::sRed, 0.1f);
  192. }
  193. #endif // JPH_DEBUG_RENDERER
  194. JPH_NAMESPACE_END