MotorcycleTest.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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->mSuspensionFrequency = 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->mSuspensionFrequency = back_suspension_freq;
  77. back->mMaxBrakeTorque = back_brake_torque;
  78. vehicle.mWheels = { front, back };
  79. MotorcycleControllerSettings *controller = new MotorcycleControllerSettings;
  80. controller->mEngine.mMaxTorque = 80.0f;
  81. controller->mEngine.mMinRPM = 1000.0f;
  82. controller->mEngine.mMaxRPM = 10000.0f;
  83. controller->mTransmission.mShiftDownRPM = 2000.0f;
  84. controller->mTransmission.mShiftUpRPM = 9000.0f;
  85. controller->mTransmission.mGearRatios = { 2.27f, 1.63f, 1.3f, 1.09f, 0.96f, 0.88f }; // From: https://www.blocklayer.com/rpm-gear-bikes
  86. controller->mTransmission.mReverseGearRatios = { -4.0f };
  87. vehicle.mController = controller;
  88. // Differential (not really applicable to a motorcycle but we need one anyway to drive it)
  89. controller->mDifferentials.resize(1);
  90. controller->mDifferentials[0].mLeftWheel = -1;
  91. controller->mDifferentials[0].mRightWheel = 1;
  92. 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
  93. mVehicleConstraint = new VehicleConstraint(*mMotorcycleBody, vehicle);
  94. mVehicleConstraint->SetVehicleCollisionTester(new VehicleCollisionTesterCastCylinder(Layers::MOVING, 1.0f)); // Use half wheel width as convex radius so we get a rounded cyclinder
  95. mPhysicsSystem->AddConstraint(mVehicleConstraint);
  96. mPhysicsSystem->AddStepListener(mVehicleConstraint);
  97. }
  98. void MotorcycleTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  99. {
  100. VehicleTest::PrePhysicsUpdate(inParams);
  101. // Determine acceleration and brake
  102. float forward = 0.0f, right = 0.0f, brake = 0.0f;
  103. if (inParams.mKeyboard->IsKeyPressed(DIK_Z))
  104. brake = 1.0f;
  105. else if (inParams.mKeyboard->IsKeyPressed(DIK_UP))
  106. forward = 1.0f;
  107. else if (inParams.mKeyboard->IsKeyPressed(DIK_DOWN))
  108. forward = -1.0f;
  109. // Check if we're reversing direction
  110. if (mPreviousForward * forward < 0.0f)
  111. {
  112. // Get vehicle velocity in local space to the body of the vehicle
  113. float velocity = (mMotorcycleBody->GetRotation().Conjugated() * mMotorcycleBody->GetLinearVelocity()).GetZ();
  114. if ((forward > 0.0f && velocity < -0.1f) || (forward < 0.0f && velocity > 0.1f))
  115. {
  116. // Brake while we've not stopped yet
  117. forward = 0.0f;
  118. brake = 1.0f;
  119. }
  120. else
  121. {
  122. // When we've come to a stop, accept the new direction
  123. mPreviousForward = forward;
  124. }
  125. }
  126. // Steering
  127. if (inParams.mKeyboard->IsKeyPressed(DIK_LEFT))
  128. right = -1.0f;
  129. else if (inParams.mKeyboard->IsKeyPressed(DIK_RIGHT))
  130. right = 1.0f;
  131. const float steer_speed = 4.0f;
  132. if (right > mCurrentRight)
  133. mCurrentRight = min(mCurrentRight + steer_speed * inParams.mDeltaTime, right);
  134. else if (right < mCurrentRight)
  135. mCurrentRight = max(mCurrentRight - steer_speed * inParams.mDeltaTime, right);
  136. // When leaned, we don't want to use the brakes fully as we'll spin out
  137. if (brake > 0.0f)
  138. {
  139. Vec3 world_up = -mPhysicsSystem->GetGravity().Normalized();
  140. Vec3 up = mMotorcycleBody->GetRotation() * mVehicleConstraint->GetLocalUp();
  141. Vec3 fwd = mMotorcycleBody->GetRotation() * mVehicleConstraint->GetLocalForward();
  142. float sin_lean_angle = abs(world_up.Cross(up).Dot(fwd));
  143. float brake_multiplier = Square(1.0f - sin_lean_angle);
  144. brake *= brake_multiplier;
  145. }
  146. // On user input, assure that the motorcycle is active
  147. if (mCurrentRight != 0.0f || forward != 0.0f || brake != 0.0f)
  148. mBodyInterface->ActivateBody(mMotorcycleBody->GetID());
  149. // Pass the input on to the constraint
  150. WheeledVehicleController *controller = static_cast<WheeledVehicleController *>(mVehicleConstraint->GetController());
  151. controller->SetDriverInput(forward, mCurrentRight, brake, false);
  152. // Draw our wheels (this needs to be done in the pre update since we draw the bodies too in the state before the step)
  153. for (uint w = 0; w < 2; ++w)
  154. {
  155. const WheelSettings *settings = mVehicleConstraint->GetWheels()[w]->GetSettings();
  156. 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
  157. mDebugRenderer->DrawCylinder(wheel_transform, 0.5f * settings->mWidth, settings->mRadius, Color::sGreen);
  158. }
  159. }
  160. void MotorcycleTest::SaveState(StateRecorder& inStream) const
  161. {
  162. VehicleTest::SaveState(inStream);
  163. inStream.Write(mPreviousForward);
  164. inStream.Write(mCurrentRight);
  165. }
  166. void MotorcycleTest::RestoreState(StateRecorder& inStream)
  167. {
  168. VehicleTest::RestoreState(inStream);
  169. inStream.Read(mPreviousForward);
  170. inStream.Read(mCurrentRight);
  171. }
  172. void MotorcycleTest::GetInitialCamera(CameraState &ioState) const
  173. {
  174. // Position camera behind motorcycle
  175. RVec3 cam_tgt = RVec3(0, 0, 5);
  176. ioState.mPos = RVec3(0, 2.5f, -5);
  177. ioState.mForward = Vec3(cam_tgt - ioState.mPos).Normalized();
  178. }
  179. RMat44 MotorcycleTest::GetCameraPivot(float inCameraHeading, float inCameraPitch) const
  180. {
  181. // Pivot is center of motorcycle and rotates with motorcycle around Y axis only
  182. Vec3 fwd = mMotorcycleBody->GetRotation().RotateAxisZ();
  183. fwd.SetY(0.0f);
  184. float len = fwd.Length();
  185. if (len != 0.0f)
  186. fwd /= len;
  187. else
  188. fwd = Vec3::sAxisZ();
  189. Vec3 up = Vec3::sAxisY();
  190. Vec3 right = up.Cross(fwd);
  191. return RMat44(Vec4(right, 0), Vec4(up, 0), Vec4(fwd, 0), mMotorcycleBody->GetPosition());
  192. }
  193. void MotorcycleTest::CreateSettingsMenu(DebugUI *inUI, UIElement *inSubMenu)
  194. {
  195. VehicleTest::CreateSettingsMenu(inUI, inSubMenu);
  196. MotorcycleController *controller = static_cast<MotorcycleController *>(mVehicleConstraint->GetController());
  197. inUI->CreateCheckBox(inSubMenu, "Enable Lean Controller", controller->IsLeanControllerEnabled(), [controller](UICheckBox::EState inState) { controller->EnableLeanController(inState == UICheckBox::STATE_CHECKED); });
  198. }