MotorcycleTest.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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::PrePhysicsUpdate(const PreUpdateParams &inParams)
  110. {
  111. VehicleTest::PrePhysicsUpdate(inParams);
  112. // Determine acceleration and brake
  113. float forward = 0.0f, right = 0.0f, brake = 0.0f;
  114. if (inParams.mKeyboard->IsKeyPressed(DIK_Z))
  115. brake = 1.0f;
  116. else if (inParams.mKeyboard->IsKeyPressed(DIK_UP))
  117. forward = 1.0f;
  118. else if (inParams.mKeyboard->IsKeyPressed(DIK_DOWN))
  119. forward = -1.0f;
  120. // Check if we're reversing direction
  121. if (mPreviousForward * forward < 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 ((forward > 0.0f && velocity < -0.1f) || (forward < 0.0f && velocity > 0.1f))
  126. {
  127. // Brake while we've not stopped yet
  128. forward = 0.0f;
  129. brake = 1.0f;
  130. }
  131. else
  132. {
  133. // When we've come to a stop, accept the new direction
  134. mPreviousForward = forward;
  135. }
  136. }
  137. // Steering
  138. if (inParams.mKeyboard->IsKeyPressed(DIK_LEFT))
  139. right = -1.0f;
  140. else if (inParams.mKeyboard->IsKeyPressed(DIK_RIGHT))
  141. right = 1.0f;
  142. const float steer_speed = 4.0f;
  143. if (right > mCurrentRight)
  144. mCurrentRight = min(mCurrentRight + steer_speed * inParams.mDeltaTime, right);
  145. else if (right < mCurrentRight)
  146. mCurrentRight = max(mCurrentRight - steer_speed * inParams.mDeltaTime, right);
  147. // When leaned, we don't want to use the brakes fully as we'll spin out
  148. if (brake > 0.0f)
  149. {
  150. Vec3 world_up = -mPhysicsSystem->GetGravity().Normalized();
  151. Vec3 up = mMotorcycleBody->GetRotation() * mVehicleConstraint->GetLocalUp();
  152. Vec3 fwd = mMotorcycleBody->GetRotation() * mVehicleConstraint->GetLocalForward();
  153. float sin_lean_angle = abs(world_up.Cross(up).Dot(fwd));
  154. float brake_multiplier = Square(1.0f - sin_lean_angle);
  155. brake *= brake_multiplier;
  156. }
  157. // On user input, assure that the motorcycle is active
  158. if (mCurrentRight != 0.0f || forward != 0.0f || brake != 0.0f)
  159. mBodyInterface->ActivateBody(mMotorcycleBody->GetID());
  160. // Pass the input on to the constraint
  161. MotorcycleController *controller = static_cast<MotorcycleController *>(mVehicleConstraint->GetController());
  162. controller->SetDriverInput(forward, mCurrentRight, brake, false);
  163. controller->EnableLeanController(sEnableLeanController);
  164. // Draw our wheels (this needs to be done in the pre update since we draw the bodies too in the state before the step)
  165. for (uint w = 0; w < 2; ++w)
  166. {
  167. const WheelSettings *settings = mVehicleConstraint->GetWheels()[w]->GetSettings();
  168. 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
  169. mDebugRenderer->DrawCylinder(wheel_transform, 0.5f * settings->mWidth, settings->mRadius, Color::sGreen);
  170. }
  171. }
  172. void MotorcycleTest::SaveState(StateRecorder& inStream) const
  173. {
  174. VehicleTest::SaveState(inStream);
  175. inStream.Write(mPreviousForward);
  176. inStream.Write(mCurrentRight);
  177. }
  178. void MotorcycleTest::RestoreState(StateRecorder& inStream)
  179. {
  180. VehicleTest::RestoreState(inStream);
  181. inStream.Read(mPreviousForward);
  182. inStream.Read(mCurrentRight);
  183. }
  184. void MotorcycleTest::GetInitialCamera(CameraState &ioState) const
  185. {
  186. // Position camera behind motorcycle
  187. RVec3 cam_tgt = RVec3(0, 0, 5);
  188. ioState.mPos = RVec3(0, 2.5f, -5);
  189. ioState.mForward = Vec3(cam_tgt - ioState.mPos).Normalized();
  190. }
  191. RMat44 MotorcycleTest::GetCameraPivot(float inCameraHeading, float inCameraPitch) const
  192. {
  193. // Pivot is center of motorcycle and rotates with motorcycle around Y axis only
  194. Vec3 fwd = mMotorcycleBody->GetRotation().RotateAxisZ();
  195. fwd.SetY(0.0f);
  196. float len = fwd.Length();
  197. if (len != 0.0f)
  198. fwd /= len;
  199. else
  200. fwd = Vec3::sAxisZ();
  201. Vec3 up = Vec3::sAxisY();
  202. Vec3 right = up.Cross(fwd);
  203. return RMat44(Vec4(right, 0), Vec4(up, 0), Vec4(fwd, 0), mMotorcycleBody->GetPosition());
  204. }
  205. void MotorcycleTest::CreateSettingsMenu(DebugUI *inUI, UIElement *inSubMenu)
  206. {
  207. VehicleTest::CreateSettingsMenu(inUI, inSubMenu);
  208. inUI->CreateCheckBox(inSubMenu, "Override Front Suspension Force Point", sOverrideFrontSuspensionForcePoint, [](UICheckBox::EState inState) { sOverrideFrontSuspensionForcePoint = inState == UICheckBox::STATE_CHECKED; });
  209. inUI->CreateCheckBox(inSubMenu, "Override Rear Suspension Force Point", sOverrideRearSuspensionForcePoint, [](UICheckBox::EState inState) { sOverrideRearSuspensionForcePoint = inState == UICheckBox::STATE_CHECKED; });
  210. inUI->CreateCheckBox(inSubMenu, "Enable Lean Controller", sEnableLeanController, [](UICheckBox::EState inState) { sEnableLeanController = inState == UICheckBox::STATE_CHECKED; });
  211. inUI->CreateTextButton(inSubMenu, "Accept", [this]() { RestartTest(); });
  212. }