TankTest.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <TestFramework.h>
  4. #include <Tests/Vehicle/TankTest.h>
  5. #include <Physics/Collision/CollisionCollectorImpl.h>
  6. #include <Physics/Collision/RayCast.h>
  7. #include <Physics/Collision/CastResult.h>
  8. #include <Physics/Collision/Shape/BoxShape.h>
  9. #include <Physics/Collision/Shape/CylinderShape.h>
  10. #include <Physics/Collision/Shape/SphereShape.h>
  11. #include <Physics/Collision/Shape/OffsetCenterOfMassShape.h>
  12. #include <Physics/Vehicle/TrackedVehicleController.h>
  13. #include <Physics/Collision/GroupFilterTable.h>
  14. #include <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. mPhysicsSystem->AddConstraint(mVehicleConstraint);
  96. mPhysicsSystem->AddStepListener(mVehicleConstraint);
  97. // Create turret
  98. Vec3 turret_position = body_position + Vec3(0, half_vehicle_height + half_turret_height, 0);
  99. BodyCreationSettings turret_body_setings(new BoxShape(Vec3(half_turret_width, half_turret_height, half_turret_length)), turret_position, Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  100. turret_body_setings.mCollisionGroup.SetGroupFilter(filter);
  101. turret_body_setings.mCollisionGroup.SetGroupID(0);
  102. turret_body_setings.mCollisionGroup.SetSubGroupID(0);
  103. turret_body_setings.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  104. turret_body_setings.mMassPropertiesOverride.mMass = 2000.0f;
  105. mTurretBody = mBodyInterface->CreateBody(turret_body_setings);
  106. mBodyInterface->AddBody(mTurretBody->GetID(), EActivation::Activate);
  107. // Attach turret to body
  108. HingeConstraintSettings turret_hinge;
  109. turret_hinge.mPoint1 = turret_hinge.mPoint2 = body_position + Vec3(0, half_vehicle_height, 0);
  110. turret_hinge.mHingeAxis1 = turret_hinge.mHingeAxis2 = Vec3::sAxisY();
  111. turret_hinge.mNormalAxis1 = turret_hinge.mNormalAxis2 = Vec3::sAxisZ();
  112. turret_hinge.mMotorSettings = MotorSettings(0.5f, 1.0f);
  113. mTurretHinge = static_cast<HingeConstraint *>(turret_hinge.Create(*mTankBody, *mTurretBody));
  114. mTurretHinge->SetMotorState(EMotorState::Position);
  115. mPhysicsSystem->AddConstraint(mTurretHinge);
  116. // Create barrel
  117. Vec3 barrel_position = turret_position + Vec3(0, 0, half_turret_length + half_barrel_length - barrel_rotation_offset);
  118. 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);
  119. barrel_body_setings.mCollisionGroup.SetGroupFilter(filter);
  120. barrel_body_setings.mCollisionGroup.SetGroupID(0);
  121. barrel_body_setings.mCollisionGroup.SetSubGroupID(0);
  122. barrel_body_setings.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  123. barrel_body_setings.mMassPropertiesOverride.mMass = 200.0f;
  124. mBarrelBody = mBodyInterface->CreateBody(barrel_body_setings);
  125. mBodyInterface->AddBody(mBarrelBody->GetID(), EActivation::Activate);
  126. // Attach barrel to turret
  127. HingeConstraintSettings barrel_hinge;
  128. barrel_hinge.mPoint1 = barrel_hinge.mPoint2 = barrel_position - Vec3(0, 0, half_barrel_length);
  129. barrel_hinge.mHingeAxis1 = barrel_hinge.mHingeAxis2 = -Vec3::sAxisX();
  130. barrel_hinge.mNormalAxis1 = barrel_hinge.mNormalAxis2 = Vec3::sAxisZ();
  131. barrel_hinge.mLimitsMin = DegreesToRadians(-10.0f);
  132. barrel_hinge.mLimitsMax = DegreesToRadians(40.0f);
  133. barrel_hinge.mMotorSettings = MotorSettings(10.0f, 1.0f);
  134. mBarrelHinge = static_cast<HingeConstraint *>(barrel_hinge.Create(*mTurretBody, *mBarrelBody));
  135. mBarrelHinge->SetMotorState(EMotorState::Position);
  136. mPhysicsSystem->AddConstraint(mBarrelHinge);
  137. }
  138. void TankTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  139. {
  140. const float min_velocity_pivot_turn = 1.0f;
  141. const float bullet_radius = 0.061f; // 120 mm
  142. const Vec3 bullet_pos = Vec3(0, 1.6f, 0);
  143. 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/)
  144. 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)
  145. const float bullet_reload_time = 2.0f;
  146. // Determine acceleration and brake
  147. float forward = 0.0f, left_ratio = 1.0f, right_ratio = 1.0f, brake = 0.0f;
  148. if (inParams.mKeyboard->IsKeyPressed(DIK_RSHIFT))
  149. brake = 1.0f;
  150. else if (inParams.mKeyboard->IsKeyPressed(DIK_UP))
  151. forward = 1.0f;
  152. else if (inParams.mKeyboard->IsKeyPressed(DIK_DOWN))
  153. forward = -1.0f;
  154. // Steering
  155. float velocity = (mTankBody->GetRotation().Conjugated() * mTankBody->GetLinearVelocity()).GetZ();
  156. if (inParams.mKeyboard->IsKeyPressed(DIK_LEFT))
  157. {
  158. if (brake == 0.0f && forward == 0.0f && abs(velocity) < min_velocity_pivot_turn)
  159. {
  160. // Pivot turn
  161. left_ratio = -1.0f;
  162. forward = 1.0f;
  163. }
  164. else
  165. left_ratio = 0.6f;
  166. }
  167. else if (inParams.mKeyboard->IsKeyPressed(DIK_RIGHT))
  168. {
  169. if (brake == 0.0f && forward == 0.0f && abs(velocity) < min_velocity_pivot_turn)
  170. {
  171. // Pivot turn
  172. right_ratio = -1.0f;
  173. forward = 1.0f;
  174. }
  175. else
  176. right_ratio = 0.6f;
  177. }
  178. // Check if we're reversing direction
  179. if (mPreviousForward * forward < 0.0f)
  180. {
  181. // Get vehicle velocity in local space to the body of the vehicle
  182. if ((forward > 0.0f && velocity < -0.1f) || (forward < 0.0f && velocity > 0.1f))
  183. {
  184. // Brake while we've not stopped yet
  185. forward = 0.0f;
  186. brake = 1.0f;
  187. }
  188. else
  189. {
  190. // When we've come to a stop, accept the new direction
  191. mPreviousForward = forward;
  192. }
  193. }
  194. // Assure the tank stays active as we're controlling the turret with the mouse
  195. mBodyInterface->ActivateBody(mTankBody->GetID());
  196. // Pass the input on to the constraint
  197. static_cast<TrackedVehicleController *>(mVehicleConstraint->GetController())->SetDriverInput(forward, left_ratio, right_ratio, brake);
  198. // Cast ray to find target
  199. RayCast ray { inParams.mCameraState.mPos, 1000.0f * inParams.mCameraState.mForward };
  200. RayCastSettings ray_settings;
  201. ClosestHitCollisionCollector<CastRayCollector> collector;
  202. IgnoreMultipleBodiesFilter body_filter;
  203. body_filter.Reserve(3);
  204. body_filter.IgnoreBody(mTankBody->GetID());
  205. body_filter.IgnoreBody(mTurretBody->GetID());
  206. body_filter.IgnoreBody(mBarrelBody->GetID());
  207. mPhysicsSystem->GetNarrowPhaseQuery().CastRay(ray, ray_settings, collector, {}, {}, body_filter);
  208. Vec3 hit_pos = collector.HadHit()? inParams.mCameraState.mPos + collector.mHit.mFraction * ray.mDirection : inParams.mCameraState.mPos + ray.mDirection;
  209. mDebugRenderer->DrawMarker(hit_pos, Color::sGreen, 1.0f);
  210. // Orient the turret towards the hit position
  211. Mat44 turret_to_world = mTankBody->GetCenterOfMassTransform() * mTurretHinge->GetConstraintToBody1Matrix();
  212. Vec3 hit_pos_in_turret = turret_to_world.InversedRotationTranslation() * hit_pos;
  213. float heading = atan2(hit_pos_in_turret.GetZ(), hit_pos_in_turret.GetY());
  214. mTurretHinge->SetTargetAngle(heading);
  215. // Orient barrel towards the hit position
  216. Mat44 barrel_to_world = mTurretBody->GetCenterOfMassTransform() * mBarrelHinge->GetConstraintToBody1Matrix();
  217. Vec3 hit_pos_in_barrel = barrel_to_world.InversedRotationTranslation() * hit_pos;
  218. float pitch = atan2(hit_pos_in_barrel.GetZ(), hit_pos_in_barrel.GetY());
  219. mBarrelHinge->SetTargetAngle(pitch);
  220. // Update reload time
  221. mReloadTime = max(0.0f, mReloadTime - inParams.mDeltaTime);
  222. // Shoot bullet
  223. if (mReloadTime == 0.0f && inParams.mKeyboard->IsKeyPressed(DIK_RETURN))
  224. {
  225. // Create bullet
  226. BodyCreationSettings bullet_creation_settings(new SphereShape(bullet_radius), mBarrelBody->GetCenterOfMassTransform() * bullet_pos, Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  227. bullet_creation_settings.mMotionQuality = EMotionQuality::LinearCast;
  228. bullet_creation_settings.mFriction = 1.0f;
  229. bullet_creation_settings.mRestitution = 0.0f;
  230. bullet_creation_settings.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  231. bullet_creation_settings.mMassPropertiesOverride.mMass = bullet_mass;
  232. Body *bullet = mBodyInterface->CreateBody(bullet_creation_settings);
  233. bullet->SetLinearVelocity(mBarrelBody->GetRotation() * bullet_velocity);
  234. mBodyInterface->AddBody(bullet->GetID(), EActivation::Activate);
  235. // Start reloading
  236. mReloadTime = bullet_reload_time;
  237. // Apply opposite impulse to turret body
  238. mBodyInterface->AddImpulse(mTurretBody->GetID(), -bullet->GetLinearVelocity() * bullet_mass);
  239. }
  240. // Draw our wheels (this needs to be done in the pre update since we draw the bodies too in the state before the step)
  241. for (uint w = 0; w < mVehicleConstraint->GetWheels().size(); ++w)
  242. {
  243. const WheelSettings *settings = mVehicleConstraint->GetWheels()[w]->GetSettings();
  244. 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
  245. mDebugRenderer->DrawCylinder(wheel_transform, 0.5f * settings->mWidth, settings->mRadius, Color::sGreen);
  246. }
  247. }
  248. void TankTest::GetInitialCamera(CameraState &ioState) const
  249. {
  250. // Position camera behind tank
  251. ioState.mPos = Vec3(0, 4.0f, 0);
  252. ioState.mForward = Vec3(0, -2.0f, 10.0f).Normalized();
  253. }
  254. Mat44 TankTest::GetCameraPivot(float inCameraHeading, float inCameraPitch) const
  255. {
  256. // Pivot is center of tank + a distance away from the tank based on the heading and pitch of the camera
  257. Vec3 fwd = Vec3(cos(inCameraPitch) * cos(inCameraHeading), sin(inCameraPitch), cos(inCameraPitch) * sin(inCameraHeading));
  258. return Mat44::sTranslation(mTankBody->GetPosition() - 10.0f * fwd);
  259. }