2
0

TankTest.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <TestFramework.h>
  4. #include <Tests/Vehicle/TankTest.h>
  5. #include <Jolt/Physics/Collision/CollisionCollectorImpl.h>
  6. #include <Jolt/Physics/Collision/RayCast.h>
  7. #include <Jolt/Physics/Collision/CastResult.h>
  8. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  9. #include <Jolt/Physics/Collision/Shape/CylinderShape.h>
  10. #include <Jolt/Physics/Collision/Shape/SphereShape.h>
  11. #include <Jolt/Physics/Collision/Shape/OffsetCenterOfMassShape.h>
  12. #include <Jolt/Physics/Vehicle/TrackedVehicleController.h>
  13. #include <Jolt/Physics/Collision/GroupFilterTable.h>
  14. #include <Jolt/Physics/Body/BodyCreationSettings.h>
  15. #include <Application/DebugUI.h>
  16. #include <Layers.h>
  17. #include <Renderer/DebugRendererImp.h>
  18. JPH_IMPLEMENT_RTTI_VIRTUAL(TankTest)
  19. {
  20. JPH_ADD_BASE_CLASS(TankTest, VehicleTest)
  21. }
  22. TankTest::~TankTest()
  23. {
  24. mPhysicsSystem->RemoveStepListener(mVehicleConstraint);
  25. }
  26. void TankTest::Initialize()
  27. {
  28. VehicleTest::Initialize();
  29. const float wheel_radius = 0.3f;
  30. const float wheel_width = 0.1f;
  31. const float half_vehicle_length = 3.2f;
  32. const float half_vehicle_width = 1.7f;
  33. const float half_vehicle_height = 0.5f;
  34. const float suspension_min_length = 0.3f;
  35. const float suspension_max_length = 0.5f;
  36. const float suspension_frequency = 1.0f;
  37. const float half_turret_width = 1.4f;
  38. const float half_turret_length = 2.0f;
  39. const float half_turret_height = 0.4f;
  40. const float half_barrel_length = 1.5f;
  41. const float barrel_radius = 0.1f;
  42. const float barrel_rotation_offset = 0.2f;
  43. static Vec3 wheel_pos[] = {
  44. Vec3(0.0f, -0.0f, 2.95f),
  45. Vec3(0.0f, -0.3f, 2.1f),
  46. Vec3(0.0f, -0.3f, 1.4f),
  47. Vec3(0.0f, -0.3f, 0.7f),
  48. Vec3(0.0f, -0.3f, 0.0f),
  49. Vec3(0.0f, -0.3f, -0.7f),
  50. Vec3(0.0f, -0.3f, -1.4f),
  51. Vec3(0.0f, -0.3f, -2.1f),
  52. Vec3(0.0f, -0.0f, -2.75f),
  53. };
  54. // Create filter to prevent body, turret and barrel from colliding
  55. GroupFilter *filter = new GroupFilterTable;
  56. // Create tank body
  57. Vec3 body_position(0, 2, 0);
  58. RefConst<Shape> tank_body_shape = OffsetCenterOfMassShapeSettings(Vec3(0, -half_vehicle_height, 0), new BoxShape(Vec3(half_vehicle_width, half_vehicle_height, half_vehicle_length))).Create().Get();
  59. BodyCreationSettings tank_body_settings(tank_body_shape, body_position, Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  60. tank_body_settings.mCollisionGroup.SetGroupFilter(filter);
  61. tank_body_settings.mCollisionGroup.SetGroupID(0);
  62. tank_body_settings.mCollisionGroup.SetSubGroupID(0);
  63. tank_body_settings.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  64. tank_body_settings.mMassPropertiesOverride.mMass = 4000.0f;
  65. mTankBody = mBodyInterface->CreateBody(tank_body_settings);
  66. mBodyInterface->AddBody(mTankBody->GetID(), EActivation::Activate);
  67. // Create vehicle constraint
  68. VehicleConstraintSettings vehicle;
  69. vehicle.mDrawConstraintSize = 0.1f;
  70. vehicle.mMaxPitchRollAngle = DegreesToRadians(60.0f);
  71. TrackedVehicleControllerSettings *controller = new TrackedVehicleControllerSettings;
  72. vehicle.mController = controller;
  73. for (int t = 0; t < 2; ++t)
  74. {
  75. VehicleTrackSettings &track = controller->mTracks[t];
  76. // Last wheel is driven wheel
  77. track.mDrivenWheel = (uint)(vehicle.mWheels.size() + size(wheel_pos) - 1);
  78. for (uint wheel = 0; wheel < size(wheel_pos); ++wheel)
  79. {
  80. WheelSettingsTV *w = new WheelSettingsTV;
  81. w->mPosition = wheel_pos[wheel];
  82. w->mPosition.SetX(t == 0? half_vehicle_width : -half_vehicle_width);
  83. w->mRadius = wheel_radius;
  84. w->mWidth = wheel_width;
  85. w->mSuspensionMinLength = suspension_min_length;
  86. w->mSuspensionMaxLength = wheel == 0 || wheel == size(wheel_pos) - 1? suspension_min_length : suspension_max_length;
  87. w->mSuspensionFrequency = suspension_frequency;
  88. // Add the wheel to the vehicle
  89. track.mWheels.push_back((uint)vehicle.mWheels.size());
  90. vehicle.mWheels.push_back(w);
  91. }
  92. }
  93. mVehicleConstraint = new VehicleConstraint(*mTankBody, vehicle);
  94. mVehicleConstraint->SetVehicleCollisionTester(new VehicleCollisionTesterRay(Layers::MOVING));
  95. #ifdef JPH_DEBUG_RENDERER
  96. static_cast<TrackedVehicleController *>(mVehicleConstraint->GetController())->SetRPMMeter(Vec3(0, 2, 0), 0.5f);
  97. #endif // JPH_DEBUG_RENDERER
  98. mPhysicsSystem->AddConstraint(mVehicleConstraint);
  99. mPhysicsSystem->AddStepListener(mVehicleConstraint);
  100. // Create turret
  101. Vec3 turret_position = body_position + Vec3(0, half_vehicle_height + half_turret_height, 0);
  102. BodyCreationSettings turret_body_setings(new BoxShape(Vec3(half_turret_width, half_turret_height, half_turret_length)), turret_position, Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  103. turret_body_setings.mCollisionGroup.SetGroupFilter(filter);
  104. turret_body_setings.mCollisionGroup.SetGroupID(0);
  105. turret_body_setings.mCollisionGroup.SetSubGroupID(0);
  106. turret_body_setings.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  107. turret_body_setings.mMassPropertiesOverride.mMass = 2000.0f;
  108. mTurretBody = mBodyInterface->CreateBody(turret_body_setings);
  109. mBodyInterface->AddBody(mTurretBody->GetID(), EActivation::Activate);
  110. // Attach turret to body
  111. HingeConstraintSettings turret_hinge;
  112. turret_hinge.mPoint1 = turret_hinge.mPoint2 = body_position + Vec3(0, half_vehicle_height, 0);
  113. turret_hinge.mHingeAxis1 = turret_hinge.mHingeAxis2 = Vec3::sAxisY();
  114. turret_hinge.mNormalAxis1 = turret_hinge.mNormalAxis2 = Vec3::sAxisZ();
  115. turret_hinge.mMotorSettings = MotorSettings(0.5f, 1.0f);
  116. mTurretHinge = static_cast<HingeConstraint *>(turret_hinge.Create(*mTankBody, *mTurretBody));
  117. mTurretHinge->SetMotorState(EMotorState::Position);
  118. mPhysicsSystem->AddConstraint(mTurretHinge);
  119. // Create barrel
  120. Vec3 barrel_position = turret_position + Vec3(0, 0, half_turret_length + half_barrel_length - barrel_rotation_offset);
  121. BodyCreationSettings barrel_body_setings(new CylinderShape(half_barrel_length, barrel_radius), barrel_position, Quat::sRotation(Vec3::sAxisX(), 0.5f * JPH_PI), EMotionType::Dynamic, Layers::MOVING);
  122. barrel_body_setings.mCollisionGroup.SetGroupFilter(filter);
  123. barrel_body_setings.mCollisionGroup.SetGroupID(0);
  124. barrel_body_setings.mCollisionGroup.SetSubGroupID(0);
  125. barrel_body_setings.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  126. barrel_body_setings.mMassPropertiesOverride.mMass = 200.0f;
  127. mBarrelBody = mBodyInterface->CreateBody(barrel_body_setings);
  128. mBodyInterface->AddBody(mBarrelBody->GetID(), EActivation::Activate);
  129. // Attach barrel to turret
  130. HingeConstraintSettings barrel_hinge;
  131. barrel_hinge.mPoint1 = barrel_hinge.mPoint2 = barrel_position - Vec3(0, 0, half_barrel_length);
  132. barrel_hinge.mHingeAxis1 = barrel_hinge.mHingeAxis2 = -Vec3::sAxisX();
  133. barrel_hinge.mNormalAxis1 = barrel_hinge.mNormalAxis2 = Vec3::sAxisZ();
  134. barrel_hinge.mLimitsMin = DegreesToRadians(-10.0f);
  135. barrel_hinge.mLimitsMax = DegreesToRadians(40.0f);
  136. barrel_hinge.mMotorSettings = MotorSettings(10.0f, 1.0f);
  137. mBarrelHinge = static_cast<HingeConstraint *>(barrel_hinge.Create(*mTurretBody, *mBarrelBody));
  138. mBarrelHinge->SetMotorState(EMotorState::Position);
  139. mPhysicsSystem->AddConstraint(mBarrelHinge);
  140. }
  141. void TankTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  142. {
  143. const float min_velocity_pivot_turn = 1.0f;
  144. const float bullet_radius = 0.061f; // 120 mm
  145. const Vec3 bullet_pos = Vec3(0, 1.6f, 0);
  146. const Vec3 bullet_velocity = Vec3(0, 400.0f, 0); // Normal exit velocities are around 1100-1700 m/s, use a lower variable as we have a limit to max velocity (See: https://tanks-encyclopedia.com/coldwar-usa-120mm-gun-tank-m1e1-abrams/)
  147. const float bullet_mass = 40.0f; // Normal projectile weight is around 7 kg, use an increased value so the momentum is more realistic (with the lower exit velocity)
  148. const float bullet_reload_time = 2.0f;
  149. // Determine acceleration and brake
  150. float forward = 0.0f, left_ratio = 1.0f, right_ratio = 1.0f, brake = 0.0f;
  151. if (inParams.mKeyboard->IsKeyPressed(DIK_RSHIFT))
  152. brake = 1.0f;
  153. else if (inParams.mKeyboard->IsKeyPressed(DIK_UP))
  154. forward = 1.0f;
  155. else if (inParams.mKeyboard->IsKeyPressed(DIK_DOWN))
  156. forward = -1.0f;
  157. // Steering
  158. float velocity = (mTankBody->GetRotation().Conjugated() * mTankBody->GetLinearVelocity()).GetZ();
  159. if (inParams.mKeyboard->IsKeyPressed(DIK_LEFT))
  160. {
  161. if (brake == 0.0f && forward == 0.0f && abs(velocity) < min_velocity_pivot_turn)
  162. {
  163. // Pivot turn
  164. left_ratio = -1.0f;
  165. forward = 1.0f;
  166. }
  167. else
  168. left_ratio = 0.6f;
  169. }
  170. else if (inParams.mKeyboard->IsKeyPressed(DIK_RIGHT))
  171. {
  172. if (brake == 0.0f && forward == 0.0f && abs(velocity) < min_velocity_pivot_turn)
  173. {
  174. // Pivot turn
  175. right_ratio = -1.0f;
  176. forward = 1.0f;
  177. }
  178. else
  179. right_ratio = 0.6f;
  180. }
  181. // Check if we're reversing direction
  182. if (mPreviousForward * forward < 0.0f)
  183. {
  184. // Get vehicle velocity in local space to the body of the vehicle
  185. if ((forward > 0.0f && velocity < -0.1f) || (forward < 0.0f && velocity > 0.1f))
  186. {
  187. // Brake while we've not stopped yet
  188. forward = 0.0f;
  189. brake = 1.0f;
  190. }
  191. else
  192. {
  193. // When we've come to a stop, accept the new direction
  194. mPreviousForward = forward;
  195. }
  196. }
  197. // Assure the tank stays active as we're controlling the turret with the mouse
  198. mBodyInterface->ActivateBody(mTankBody->GetID());
  199. // Pass the input on to the constraint
  200. static_cast<TrackedVehicleController *>(mVehicleConstraint->GetController())->SetDriverInput(forward, left_ratio, right_ratio, brake);
  201. // Cast ray to find target
  202. RayCast ray { inParams.mCameraState.mPos, 1000.0f * inParams.mCameraState.mForward };
  203. RayCastSettings ray_settings;
  204. ClosestHitCollisionCollector<CastRayCollector> collector;
  205. IgnoreMultipleBodiesFilter body_filter;
  206. body_filter.Reserve(3);
  207. body_filter.IgnoreBody(mTankBody->GetID());
  208. body_filter.IgnoreBody(mTurretBody->GetID());
  209. body_filter.IgnoreBody(mBarrelBody->GetID());
  210. mPhysicsSystem->GetNarrowPhaseQuery().CastRay(ray, ray_settings, collector, {}, {}, body_filter);
  211. Vec3 hit_pos = collector.HadHit()? inParams.mCameraState.mPos + collector.mHit.mFraction * ray.mDirection : inParams.mCameraState.mPos + ray.mDirection;
  212. mDebugRenderer->DrawMarker(hit_pos, Color::sGreen, 1.0f);
  213. // Orient the turret towards the hit position
  214. Mat44 turret_to_world = mTankBody->GetCenterOfMassTransform() * mTurretHinge->GetConstraintToBody1Matrix();
  215. Vec3 hit_pos_in_turret = turret_to_world.InversedRotationTranslation() * hit_pos;
  216. float heading = ATan2(hit_pos_in_turret.GetZ(), hit_pos_in_turret.GetY());
  217. mTurretHinge->SetTargetAngle(heading);
  218. // Orient barrel towards the hit position
  219. Mat44 barrel_to_world = mTurretBody->GetCenterOfMassTransform() * mBarrelHinge->GetConstraintToBody1Matrix();
  220. Vec3 hit_pos_in_barrel = barrel_to_world.InversedRotationTranslation() * hit_pos;
  221. float pitch = ATan2(hit_pos_in_barrel.GetZ(), hit_pos_in_barrel.GetY());
  222. mBarrelHinge->SetTargetAngle(pitch);
  223. // Update reload time
  224. mReloadTime = max(0.0f, mReloadTime - inParams.mDeltaTime);
  225. // Shoot bullet
  226. if (mReloadTime == 0.0f && inParams.mKeyboard->IsKeyPressed(DIK_RETURN))
  227. {
  228. // Create bullet
  229. BodyCreationSettings bullet_creation_settings(new SphereShape(bullet_radius), mBarrelBody->GetCenterOfMassTransform() * bullet_pos, Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  230. bullet_creation_settings.mMotionQuality = EMotionQuality::LinearCast;
  231. bullet_creation_settings.mFriction = 1.0f;
  232. bullet_creation_settings.mRestitution = 0.0f;
  233. bullet_creation_settings.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  234. bullet_creation_settings.mMassPropertiesOverride.mMass = bullet_mass;
  235. Body *bullet = mBodyInterface->CreateBody(bullet_creation_settings);
  236. bullet->SetLinearVelocity(mBarrelBody->GetRotation() * bullet_velocity);
  237. mBodyInterface->AddBody(bullet->GetID(), EActivation::Activate);
  238. // Start reloading
  239. mReloadTime = bullet_reload_time;
  240. // Apply opposite impulse to turret body
  241. mBodyInterface->AddImpulse(mTurretBody->GetID(), -bullet->GetLinearVelocity() * bullet_mass);
  242. }
  243. // Draw our wheels (this needs to be done in the pre update since we draw the bodies too in the state before the step)
  244. for (uint w = 0; w < mVehicleConstraint->GetWheels().size(); ++w)
  245. {
  246. const WheelSettings *settings = mVehicleConstraint->GetWheels()[w]->GetSettings();
  247. Mat44 wheel_transform = mVehicleConstraint->GetWheelWorldTransform(w, Vec3::sAxisY(), Vec3::sAxisX()); // The cylinder we draw is aligned with Y so we specify that as rotational axis
  248. mDebugRenderer->DrawCylinder(wheel_transform, 0.5f * settings->mWidth, settings->mRadius, Color::sGreen);
  249. }
  250. }
  251. void TankTest::GetInitialCamera(CameraState &ioState) const
  252. {
  253. // Position camera behind tank
  254. ioState.mPos = Vec3(0, 4.0f, 0);
  255. ioState.mForward = Vec3(0, -2.0f, 10.0f).Normalized();
  256. }
  257. Mat44 TankTest::GetCameraPivot(float inCameraHeading, float inCameraPitch) const
  258. {
  259. // Pivot is center of tank + a distance away from the tank based on the heading and pitch of the camera
  260. Vec3 fwd = Vec3(Cos(inCameraPitch) * Cos(inCameraHeading), Sin(inCameraPitch), Cos(inCameraPitch) * Sin(inCameraHeading));
  261. return Mat44::sTranslation(mTankBody->GetPosition() - 10.0f * fwd);
  262. }