MotorcycleTest.cpp 8.6 KB

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