VehicleConstraintTest.cpp 8.5 KB

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