MotorcycleTest.cpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2023 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <TestFramework.h>
  5. #include <Tests/Vehicle/MotorcycleTest.h>
  6. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  7. #include <Jolt/Physics/Collision/Shape/OffsetCenterOfMassShape.h>
  8. #include <Jolt/Physics/Vehicle/MotorcycleController.h>
  9. #include <Jolt/Physics/Body/BodyCreationSettings.h>
  10. #include <Application/DebugUI.h>
  11. #include <Layers.h>
  12. #include <Renderer/DebugRendererImp.h>
  13. JPH_IMPLEMENT_RTTI_VIRTUAL(MotorcycleTest)
  14. {
  15. JPH_ADD_BASE_CLASS(MotorcycleTest, VehicleTest)
  16. }
  17. MotorcycleTest::~MotorcycleTest()
  18. {
  19. mPhysicsSystem->RemoveStepListener(mVehicleConstraint);
  20. }
  21. void MotorcycleTest::Initialize()
  22. {
  23. VehicleTest::Initialize();
  24. // Loosly based on: https://www.whitedogbikes.com/whitedogblog/yamaha-xj-900-specs/
  25. const float back_wheel_radius = 0.31f;
  26. const float back_wheel_width = 0.05f;
  27. const float back_wheel_pos_z = -0.75f;
  28. const float back_suspension_min_length = 0.3f;
  29. const float back_suspension_max_length = 0.5f;
  30. const float back_suspension_freq = 2.0f;
  31. const float back_brake_torque = 250.0f;
  32. const float front_wheel_radius = 0.31f;
  33. const float front_wheel_width = 0.05f;
  34. const float front_wheel_pos_z = 0.75f;
  35. const float front_suspension_min_length = 0.3f;
  36. const float front_suspension_max_length = 0.5f;
  37. const float front_suspension_freq = 1.5f;
  38. const float front_brake_torque = 500.0f;
  39. const float half_vehicle_length = 0.4f;
  40. const float half_vehicle_width = 0.2f;
  41. const float half_vehicle_height = 0.3f;
  42. const float max_steering_angle = DegreesToRadians(30);
  43. // Angle of the front suspension
  44. const float caster_angle = DegreesToRadians(30);
  45. // Create vehicle body
  46. RVec3 position(0, 2, 0);
  47. RefConst<Shape> motorcycle_shape = OffsetCenterOfMassShapeSettings(Vec3(0, -half_vehicle_height, 0), new BoxShape(Vec3(half_vehicle_width, half_vehicle_height, half_vehicle_length))).Create().Get();
  48. BodyCreationSettings motorcycle_body_settings(motorcycle_shape, position, Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  49. motorcycle_body_settings.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  50. motorcycle_body_settings.mMassPropertiesOverride.mMass = 240.0f;
  51. mMotorcycleBody = mBodyInterface->CreateBody(motorcycle_body_settings);
  52. mBodyInterface->AddBody(mMotorcycleBody->GetID(), EActivation::Activate);
  53. // Create vehicle constraint
  54. VehicleConstraintSettings vehicle;
  55. vehicle.mDrawConstraintSize = 0.1f;
  56. vehicle.mMaxPitchRollAngle = DegreesToRadians(60.0f);
  57. // Wheels
  58. WheelSettingsWV *front = new WheelSettingsWV;
  59. front->mPosition = Vec3(0.0f, -0.9f * half_vehicle_height, front_wheel_pos_z);
  60. front->mMaxSteerAngle = max_steering_angle;
  61. front->mSuspensionDirection = Vec3(0, -1, Tan(caster_angle)).Normalized();
  62. front->mSteeringAxis = -front->mSuspensionDirection;
  63. front->mRadius = front_wheel_radius;
  64. front->mWidth = front_wheel_width;
  65. front->mSuspensionMinLength = front_suspension_min_length;
  66. front->mSuspensionMaxLength = front_suspension_max_length;
  67. front->mSuspensionSpring.mFrequency = front_suspension_freq;
  68. front->mMaxBrakeTorque = front_brake_torque;
  69. WheelSettingsWV *back = new WheelSettingsWV;
  70. back->mPosition = Vec3(0.0f, -0.9f * half_vehicle_height, back_wheel_pos_z);
  71. back->mMaxSteerAngle = 0.0f;
  72. back->mRadius = back_wheel_radius;
  73. back->mWidth = back_wheel_width;
  74. back->mSuspensionMinLength = back_suspension_min_length;
  75. back->mSuspensionMaxLength = back_suspension_max_length;
  76. back->mSuspensionSpring.mFrequency = back_suspension_freq;
  77. back->mMaxBrakeTorque = back_brake_torque;
  78. if (sOverrideFrontSuspensionForcePoint)
  79. {
  80. front->mEnableSuspensionForcePoint = true;
  81. front->mSuspensionForcePoint = front->mPosition + front->mSuspensionDirection * front->mSuspensionMinLength;
  82. }
  83. if (sOverrideRearSuspensionForcePoint)
  84. {
  85. back->mEnableSuspensionForcePoint = true;
  86. back->mSuspensionForcePoint = back->mPosition + back->mSuspensionDirection * back->mSuspensionMinLength;
  87. }
  88. vehicle.mWheels = { front, back };
  89. MotorcycleControllerSettings *controller = new MotorcycleControllerSettings;
  90. controller->mEngine.mMaxTorque = 150.0f;
  91. controller->mEngine.mMinRPM = 1000.0f;
  92. controller->mEngine.mMaxRPM = 10000.0f;
  93. controller->mTransmission.mShiftDownRPM = 2000.0f;
  94. controller->mTransmission.mShiftUpRPM = 8000.0f;
  95. controller->mTransmission.mGearRatios = { 2.27f, 1.63f, 1.3f, 1.09f, 0.96f, 0.88f }; // From: https://www.blocklayer.com/rpm-gear-bikes
  96. controller->mTransmission.mReverseGearRatios = { -4.0f };
  97. controller->mTransmission.mClutchStrength = 2.0f;
  98. vehicle.mController = controller;
  99. // Differential (not really applicable to a motorcycle but we need one anyway to drive it)
  100. controller->mDifferentials.resize(1);
  101. controller->mDifferentials[0].mLeftWheel = -1;
  102. controller->mDifferentials[0].mRightWheel = 1;
  103. controller->mDifferentials[0].mDifferentialRatio = 1.93f * 40.0f / 16.0f; // Combining primary and final drive (back divided by front sprockets) from: https://www.blocklayer.com/rpm-gear-bikes
  104. mVehicleConstraint = new VehicleConstraint(*mMotorcycleBody, vehicle);
  105. mVehicleConstraint->SetVehicleCollisionTester(new VehicleCollisionTesterCastCylinder(Layers::MOVING, 1.0f)); // Use half wheel width as convex radius so we get a rounded cyclinder
  106. mPhysicsSystem->AddConstraint(mVehicleConstraint);
  107. mPhysicsSystem->AddStepListener(mVehicleConstraint);
  108. }
  109. void MotorcycleTest::ProcessInput(const ProcessInputParams &inParams)
  110. {
  111. // Determine acceleration and brake
  112. mForward = 0.0f;
  113. mBrake = 0.0f;
  114. if (inParams.mKeyboard->IsKeyPressed(DIK_Z))
  115. mBrake = 1.0f;
  116. else if (inParams.mKeyboard->IsKeyPressed(DIK_UP))
  117. mForward = 1.0f;
  118. else if (inParams.mKeyboard->IsKeyPressed(DIK_DOWN))
  119. mForward = -1.0f;
  120. // Check if we're reversing direction
  121. if (mPreviousForward * mForward < 0.0f)
  122. {
  123. // Get vehicle velocity in local space to the body of the vehicle
  124. float velocity = (mMotorcycleBody->GetRotation().Conjugated() * mMotorcycleBody->GetLinearVelocity()).GetZ();
  125. if ((mForward > 0.0f && velocity < -0.1f) || (mForward < 0.0f && velocity > 0.1f))
  126. {
  127. // Brake while we've not stopped yet
  128. mForward = 0.0f;
  129. mBrake = 1.0f;
  130. }
  131. else
  132. {
  133. // When we've come to a stop, accept the new direction
  134. mPreviousForward = mForward;
  135. }
  136. }
  137. // Steering
  138. float right = 0.0f;
  139. if (inParams.mKeyboard->IsKeyPressed(DIK_LEFT))
  140. right = -1.0f;
  141. else if (inParams.mKeyboard->IsKeyPressed(DIK_RIGHT))
  142. right = 1.0f;
  143. const float steer_speed = 4.0f;
  144. if (right > mRight)
  145. mRight = min(mRight + steer_speed * inParams.mDeltaTime, right);
  146. else if (right < mRight)
  147. mRight = max(mRight - steer_speed * inParams.mDeltaTime, right);
  148. // When leaned, we don't want to use the brakes fully as we'll spin out
  149. if (mBrake > 0.0f)
  150. {
  151. Vec3 world_up = -mPhysicsSystem->GetGravity().Normalized();
  152. Vec3 up = mMotorcycleBody->GetRotation() * mVehicleConstraint->GetLocalUp();
  153. Vec3 fwd = mMotorcycleBody->GetRotation() * mVehicleConstraint->GetLocalForward();
  154. float sin_lean_angle = abs(world_up.Cross(up).Dot(fwd));
  155. float brake_multiplier = Square(1.0f - sin_lean_angle);
  156. mBrake *= brake_multiplier;
  157. }
  158. }
  159. void MotorcycleTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  160. {
  161. VehicleTest::PrePhysicsUpdate(inParams);
  162. // On user input, assure that the motorcycle is active
  163. if (mRight != 0.0f || mForward != 0.0f || mBrake != 0.0f)
  164. mBodyInterface->ActivateBody(mMotorcycleBody->GetID());
  165. // Pass the input on to the constraint
  166. MotorcycleController *controller = static_cast<MotorcycleController *>(mVehicleConstraint->GetController());
  167. controller->SetDriverInput(mForward, mRight, mBrake, false);
  168. controller->EnableLeanController(sEnableLeanController);
  169. // Draw our wheels (this needs to be done in the pre update since we draw the bodies too in the state before the step)
  170. for (uint w = 0; w < 2; ++w)
  171. {
  172. const WheelSettings *settings = mVehicleConstraint->GetWheels()[w]->GetSettings();
  173. RMat44 wheel_transform = mVehicleConstraint->GetWheelWorldTransform(w, Vec3::sAxisY(), Vec3::sAxisX()); // The cyclinder we draw is aligned with Y so we specify that as rotational axis
  174. mDebugRenderer->DrawCylinder(wheel_transform, 0.5f * settings->mWidth, settings->mRadius, Color::sGreen);
  175. }
  176. }
  177. void MotorcycleTest::SaveInputState(StateRecorder &inStream) const
  178. {
  179. inStream.Write(mForward);
  180. inStream.Write(mPreviousForward);
  181. inStream.Write(mRight);
  182. inStream.Write(mBrake);
  183. }
  184. void MotorcycleTest::RestoreInputState(StateRecorder &inStream)
  185. {
  186. inStream.Read(mForward);
  187. inStream.Read(mPreviousForward);
  188. inStream.Read(mRight);
  189. inStream.Read(mBrake);
  190. }
  191. void MotorcycleTest::GetInitialCamera(CameraState &ioState) const
  192. {
  193. // Position camera behind motorcycle
  194. RVec3 cam_tgt = RVec3(0, 0, 5);
  195. ioState.mPos = RVec3(0, 2.5f, -5);
  196. ioState.mForward = Vec3(cam_tgt - ioState.mPos).Normalized();
  197. }
  198. RMat44 MotorcycleTest::GetCameraPivot(float inCameraHeading, float inCameraPitch) const
  199. {
  200. // Pivot is center of motorcycle and rotates with motorcycle around Y axis only
  201. Vec3 fwd = mMotorcycleBody->GetRotation().RotateAxisZ();
  202. fwd.SetY(0.0f);
  203. float len = fwd.Length();
  204. if (len != 0.0f)
  205. fwd /= len;
  206. else
  207. fwd = Vec3::sAxisZ();
  208. Vec3 up = Vec3::sAxisY();
  209. Vec3 right = up.Cross(fwd);
  210. return RMat44(Vec4(right, 0), Vec4(up, 0), Vec4(fwd, 0), mMotorcycleBody->GetPosition());
  211. }
  212. void MotorcycleTest::CreateSettingsMenu(DebugUI *inUI, UIElement *inSubMenu)
  213. {
  214. VehicleTest::CreateSettingsMenu(inUI, inSubMenu);
  215. inUI->CreateCheckBox(inSubMenu, "Override Front Suspension Force Point", sOverrideFrontSuspensionForcePoint, [](UICheckBox::EState inState) { sOverrideFrontSuspensionForcePoint = inState == UICheckBox::STATE_CHECKED; });
  216. inUI->CreateCheckBox(inSubMenu, "Override Rear Suspension Force Point", sOverrideRearSuspensionForcePoint, [](UICheckBox::EState inState) { sOverrideRearSuspensionForcePoint = inState == UICheckBox::STATE_CHECKED; });
  217. inUI->CreateCheckBox(inSubMenu, "Enable Lean Controller", sEnableLeanController, [](UICheckBox::EState inState) { sEnableLeanController = inState == UICheckBox::STATE_CHECKED; });
  218. inUI->CreateTextButton(inSubMenu, "Accept", [this]() { RestartTest(); });
  219. }