VehicleConstraintTest.cpp 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <TestFramework.h>
  5. #include <Tests/Vehicle/VehicleConstraintTest.h>
  6. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  7. #include <Jolt/Physics/Collision/Shape/OffsetCenterOfMassShape.h>
  8. #include <Jolt/Physics/Vehicle/WheeledVehicleController.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(VehicleConstraintTest)
  14. {
  15. JPH_ADD_BASE_CLASS(VehicleConstraintTest, VehicleTest)
  16. }
  17. VehicleConstraintTest::~VehicleConstraintTest()
  18. {
  19. mPhysicsSystem->RemoveStepListener(mVehicleConstraint);
  20. }
  21. void VehicleConstraintTest::Initialize()
  22. {
  23. VehicleTest::Initialize();
  24. const float wheel_radius = 0.3f;
  25. const float wheel_width = 0.1f;
  26. const float half_vehicle_length = 2.0f;
  27. const float half_vehicle_width = 0.9f;
  28. const float half_vehicle_height = 0.2f;
  29. const float suspension_min_length = 0.3f;
  30. const float suspension_max_length = 0.5f;
  31. const float max_steering_angle = DegreesToRadians(30);
  32. // Create collision testers
  33. mTesters[0] = new VehicleCollisionTesterRay(Layers::MOVING);
  34. mTesters[1] = new VehicleCollisionTesterCastSphere(Layers::MOVING, 0.5f * wheel_width);
  35. mTesters[2] = new VehicleCollisionTesterCastCylinder(Layers::MOVING);
  36. // Create vehicle body
  37. RVec3 position(0, 2, 0);
  38. RefConst<Shape> car_shape = OffsetCenterOfMassShapeSettings(Vec3(0, -half_vehicle_height, 0), new BoxShape(Vec3(half_vehicle_width, half_vehicle_height, half_vehicle_length))).Create().Get();
  39. BodyCreationSettings car_body_settings(car_shape, position, Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  40. car_body_settings.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  41. car_body_settings.mMassPropertiesOverride.mMass = 1500.0f;
  42. mCarBody = mBodyInterface->CreateBody(car_body_settings);
  43. mBodyInterface->AddBody(mCarBody->GetID(), EActivation::Activate);
  44. // Create vehicle constraint
  45. VehicleConstraintSettings vehicle;
  46. vehicle.mDrawConstraintSize = 0.1f;
  47. vehicle.mMaxPitchRollAngle = DegreesToRadians(60.0f);
  48. // Wheels
  49. WheelSettingsWV *w1 = new WheelSettingsWV;
  50. w1->mPosition = Vec3(half_vehicle_width, -0.9f * half_vehicle_height, half_vehicle_length - 2.0f * wheel_radius);
  51. w1->mMaxSteerAngle = max_steering_angle;
  52. w1->mMaxHandBrakeTorque = 0.0f; // Front wheel doesn't have hand brake
  53. WheelSettingsWV *w2 = new WheelSettingsWV;
  54. w2->mPosition = Vec3(-half_vehicle_width, -0.9f * half_vehicle_height, half_vehicle_length - 2.0f * wheel_radius);
  55. w2->mMaxSteerAngle = max_steering_angle;
  56. w2->mMaxHandBrakeTorque = 0.0f; // Front wheel doesn't have hand brake
  57. WheelSettingsWV *w3 = new WheelSettingsWV;
  58. w3->mPosition = Vec3(half_vehicle_width, -0.9f * half_vehicle_height, -half_vehicle_length + 2.0f * wheel_radius);
  59. w3->mMaxSteerAngle = 0.0f;
  60. WheelSettingsWV *w4 = new WheelSettingsWV;
  61. w4->mPosition = Vec3(-half_vehicle_width, -0.9f * half_vehicle_height, -half_vehicle_length + 2.0f * wheel_radius);
  62. w4->mMaxSteerAngle = 0.0f;
  63. vehicle.mWheels = { w1, w2, w3, w4 };
  64. for (WheelSettings *w : vehicle.mWheels)
  65. {
  66. w->mRadius = wheel_radius;
  67. w->mWidth = wheel_width;
  68. w->mSuspensionMinLength = suspension_min_length;
  69. w->mSuspensionMaxLength = suspension_max_length;
  70. }
  71. WheeledVehicleControllerSettings *controller = new WheeledVehicleControllerSettings;
  72. vehicle.mController = controller;
  73. // Differential
  74. controller->mDifferentials.resize(sFourWheelDrive? 2 : 1);
  75. controller->mDifferentials[0].mLeftWheel = 0;
  76. controller->mDifferentials[0].mRightWheel = 1;
  77. if (sFourWheelDrive)
  78. {
  79. controller->mDifferentials[1].mLeftWheel = 2;
  80. controller->mDifferentials[1].mRightWheel = 3;
  81. // Split engine torque
  82. controller->mDifferentials[0].mEngineTorqueRatio = controller->mDifferentials[1].mEngineTorqueRatio = 0.5f;
  83. }
  84. // Anti rollbars
  85. if (sAntiRollbar)
  86. {
  87. vehicle.mAntiRollBars.resize(2);
  88. vehicle.mAntiRollBars[0].mLeftWheel = 0;
  89. vehicle.mAntiRollBars[0].mRightWheel = 1;
  90. vehicle.mAntiRollBars[1].mLeftWheel = 2;
  91. vehicle.mAntiRollBars[1].mRightWheel = 3;
  92. }
  93. mVehicleConstraint = new VehicleConstraint(*mCarBody, vehicle);
  94. mPhysicsSystem->AddConstraint(mVehicleConstraint);
  95. mPhysicsSystem->AddStepListener(mVehicleConstraint);
  96. }
  97. void VehicleConstraintTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  98. {
  99. // Determine acceleration and brake
  100. float forward = 0.0f, right = 0.0f, brake = 0.0f, hand_brake = 0.0f;
  101. if (inParams.mKeyboard->IsKeyPressed(DIK_UP))
  102. forward = 1.0f;
  103. else if (inParams.mKeyboard->IsKeyPressed(DIK_DOWN))
  104. forward = -1.0f;
  105. // Check if we're reversing direction
  106. if (mPreviousForward * forward < 0.0f)
  107. {
  108. // Get vehicle velocity in local space to the body of the vehicle
  109. float velocity = (mCarBody->GetRotation().Conjugated() * mCarBody->GetLinearVelocity()).GetZ();
  110. if ((forward > 0.0f && velocity < -0.1f) || (forward < 0.0f && velocity > 0.1f))
  111. {
  112. // Brake while we've not stopped yet
  113. forward = 0.0f;
  114. brake = 1.0f;
  115. }
  116. else
  117. {
  118. // When we've come to a stop, accept the new direction
  119. mPreviousForward = forward;
  120. }
  121. }
  122. // Hand brake will cancel gas pedal
  123. if (inParams.mKeyboard->IsKeyPressed(DIK_Z))
  124. {
  125. forward = 0.0f;
  126. hand_brake = 1.0f;
  127. }
  128. // Steering
  129. if (inParams.mKeyboard->IsKeyPressed(DIK_LEFT))
  130. right = -1.0f;
  131. else if (inParams.mKeyboard->IsKeyPressed(DIK_RIGHT))
  132. right = 1.0f;
  133. // On user input, assure that the car is active
  134. if (right != 0.0f || forward != 0.0f || brake != 0.0f || hand_brake != 0.0f)
  135. mBodyInterface->ActivateBody(mCarBody->GetID());
  136. WheeledVehicleController *controller = static_cast<WheeledVehicleController *>(mVehicleConstraint->GetController());
  137. // Update vehicle statistics
  138. controller->GetEngine().mMaxTorque = sMaxEngineTorque;
  139. controller->GetTransmission().mClutchStrength = sClutchStrength;
  140. // Set slip ratios to the same for everything
  141. float limited_slip_ratio = sLimitedSlipDifferentials? 1.4f : FLT_MAX;
  142. controller->SetDifferentialLimitedSlipRatio(limited_slip_ratio);
  143. for (VehicleDifferentialSettings &d : controller->GetDifferentials())
  144. d.mLimitedSlipRatio = limited_slip_ratio;
  145. // Pass the input on to the constraint
  146. controller->SetDriverInput(forward, right, brake, hand_brake);
  147. // Set the collision tester
  148. mVehicleConstraint->SetVehicleCollisionTester(mTesters[sCollisionMode]);
  149. // Draw our wheels (this needs to be done in the pre update since we draw the bodies too in the state before the step)
  150. for (uint w = 0; w < 4; ++w)
  151. {
  152. const WheelSettings *settings = mVehicleConstraint->GetWheels()[w]->GetSettings();
  153. 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
  154. mDebugRenderer->DrawCylinder(wheel_transform, 0.5f * settings->mWidth, settings->mRadius, Color::sGreen);
  155. }
  156. }
  157. void VehicleConstraintTest::GetInitialCamera(CameraState &ioState) const
  158. {
  159. // Position camera behind car
  160. RVec3 cam_tgt = RVec3(0, 0, 5);
  161. ioState.mPos = RVec3(0, 2.5f, -5);
  162. ioState.mForward = Vec3(cam_tgt - ioState.mPos).Normalized();
  163. }
  164. RMat44 VehicleConstraintTest::GetCameraPivot(float inCameraHeading, float inCameraPitch) const
  165. {
  166. // Pivot is center of car and rotates with car around Y axis only
  167. Vec3 fwd = mCarBody->GetRotation().RotateAxisZ();
  168. fwd.SetY(0.0f);
  169. float len = fwd.Length();
  170. if (len != 0.0f)
  171. fwd /= len;
  172. else
  173. fwd = Vec3::sAxisZ();
  174. Vec3 up = Vec3::sAxisY();
  175. Vec3 right = up.Cross(fwd);
  176. return RMat44(Vec4(right, 0), Vec4(up, 0), Vec4(fwd, 0), mCarBody->GetPosition());
  177. }
  178. void VehicleConstraintTest::CreateSettingsMenu(DebugUI *inUI, UIElement *inSubMenu)
  179. {
  180. VehicleTest::CreateSettingsMenu(inUI, inSubMenu);
  181. inUI->CreateComboBox(inSubMenu, "Collision Mode", { "Ray", "Cast Sphere", "Cast Cylinder" }, sCollisionMode, [](int inItem) { sCollisionMode = inItem; });
  182. inUI->CreateCheckBox(inSubMenu, "4 Wheel Drive", sFourWheelDrive, [this](UICheckBox::EState inState) { sFourWheelDrive = inState == UICheckBox::STATE_CHECKED; RestartTest(); });
  183. inUI->CreateCheckBox(inSubMenu, "Anti Rollbars", sAntiRollbar, [this](UICheckBox::EState inState) { sAntiRollbar = inState == UICheckBox::STATE_CHECKED; RestartTest(); });
  184. inUI->CreateCheckBox(inSubMenu, "Limited Slip Differentials", sLimitedSlipDifferentials, [](UICheckBox::EState inState) { sLimitedSlipDifferentials = inState == UICheckBox::STATE_CHECKED; });
  185. inUI->CreateSlider(inSubMenu, "Max Engine Torque", float(sMaxEngineTorque), 100.0f, 2000.0f, 10.0f, [](float inValue) { sMaxEngineTorque = inValue; });
  186. inUI->CreateSlider(inSubMenu, "Clutch Strength", float(sClutchStrength), 1.0f, 40.0f, 1.0f, [](float inValue) { sClutchStrength = inValue; });
  187. }