BoatTest.cpp 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2024 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <TestFramework.h>
  5. #include <Tests/Water/BoatTest.h>
  6. #include <Jolt/Physics/Collision/Shape/BoxShape.h>
  7. #include <Jolt/Physics/Collision/Shape/CylinderShape.h>
  8. #include <Jolt/Physics/Collision/Shape/ConvexHullShape.h>
  9. #include <Jolt/Physics/Collision/Shape/OffsetCenterOfMassShape.h>
  10. #include <Jolt/Physics/Body/BodyCreationSettings.h>
  11. #include <Layers.h>
  12. #include <Renderer/DebugRendererImp.h>
  13. JPH_IMPLEMENT_RTTI_VIRTUAL(BoatTest)
  14. {
  15. JPH_ADD_BASE_CLASS(BoatTest, Test)
  16. }
  17. void BoatTest::Initialize()
  18. {
  19. // Create boat
  20. ConvexHullShapeSettings boat_hull;
  21. boat_hull.mPoints = {
  22. Vec3(-cHalfBoatTopWidth, cHalfBoatHeight, -cHalfBoatLength),
  23. Vec3(cHalfBoatTopWidth, cHalfBoatHeight, -cHalfBoatLength),
  24. Vec3(-cHalfBoatTopWidth, cHalfBoatHeight, cHalfBoatLength),
  25. Vec3(cHalfBoatTopWidth, cHalfBoatHeight, cHalfBoatLength),
  26. Vec3(-cHalfBoatBottomWidth, -cHalfBoatHeight, -cHalfBoatLength),
  27. Vec3(cHalfBoatBottomWidth, -cHalfBoatHeight, -cHalfBoatLength),
  28. Vec3(-cHalfBoatBottomWidth, -cHalfBoatHeight, cHalfBoatLength),
  29. Vec3(cHalfBoatBottomWidth, -cHalfBoatHeight, cHalfBoatLength),
  30. Vec3(0, cHalfBoatHeight, cHalfBoatLength + cBoatBowLength)
  31. };
  32. boat_hull.SetEmbedded();
  33. OffsetCenterOfMassShapeSettings com_offset(Vec3(0, -cHalfBoatHeight, 0), &boat_hull);
  34. com_offset.SetEmbedded();
  35. RVec3 position(0, cMaxWaterHeight + 2, 0);
  36. BodyCreationSettings boat(&com_offset, position, Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  37. boat.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  38. boat.mMassPropertiesOverride.mMass = cBoatMass;
  39. mBoatBody = mBodyInterface->CreateBody(boat);
  40. mBodyInterface->AddBody(mBoatBody->GetID(), EActivation::Activate);
  41. // Create water sensor. We use this to detect which bodies entered the water (in this sample we could have assumed everything is in the water)
  42. BodyCreationSettings water_sensor(new BoxShape(Vec3(cWaterWidth, cMaxWaterHeight, cWaterWidth)), RVec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::SENSOR);
  43. water_sensor.mIsSensor = true;
  44. mWaterSensor = mBodyInterface->CreateAndAddBody(water_sensor, EActivation::Activate);
  45. // Create some barrels to float in the water
  46. default_random_engine random;
  47. BodyCreationSettings barrel(new CylinderShape(1.0f, 0.7f), RVec3::sZero(), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
  48. barrel.mOverrideMassProperties = EOverrideMassProperties::CalculateInertia;
  49. barrel.mMassPropertiesOverride.mMass = cBarrelMass;
  50. for (int i = 0; i < 10; ++i)
  51. {
  52. barrel.mPosition = RVec3(-10.0f + i * 2.0f, cMaxWaterHeight + 2, 10);
  53. barrel.mRotation = Quat::sRandom(random);
  54. mBodyInterface->CreateAndAddBody(barrel, EActivation::Activate);
  55. }
  56. UpdateCameraPivot();
  57. }
  58. void BoatTest::ProcessInput(const ProcessInputParams &inParams)
  59. {
  60. // Determine acceleration and brake
  61. mForward = 0.0f;
  62. if (inParams.mKeyboard->IsKeyPressed(DIK_UP))
  63. mForward = 1.0f;
  64. else if (inParams.mKeyboard->IsKeyPressed(DIK_DOWN))
  65. mForward = -1.0f;
  66. // Steering
  67. mRight = 0.0f;
  68. if (inParams.mKeyboard->IsKeyPressed(DIK_LEFT))
  69. mRight = -1.0f;
  70. else if (inParams.mKeyboard->IsKeyPressed(DIK_RIGHT))
  71. mRight = 1.0f;
  72. }
  73. RVec3 BoatTest::GetWaterSurfacePosition(RVec3Arg inXZPosition) const
  74. {
  75. return RVec3(inXZPosition.GetX(), cMinWaterHeight + Sin(0.1f * float(inXZPosition.GetZ()) + mTime) * (cMaxWaterHeight - cMinWaterHeight), inXZPosition.GetZ());
  76. }
  77. void BoatTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  78. {
  79. // Update time
  80. mTime += inParams.mDeltaTime;
  81. // Draw the water surface
  82. const float step = 1.0f;
  83. for (float z = -cWaterWidth; z < cWaterWidth; z += step)
  84. {
  85. RVec3 p1 = GetWaterSurfacePosition(RVec3(-cWaterWidth, 0, z));
  86. RVec3 p2 = GetWaterSurfacePosition(RVec3(-cWaterWidth, 0, z + step));
  87. RVec3 p3 = GetWaterSurfacePosition(RVec3(cWaterWidth, 0, z));
  88. RVec3 p4 = GetWaterSurfacePosition(RVec3(cWaterWidth, 0, z + step));
  89. mDebugRenderer->DrawTriangle(p1, p2, p3, Color::sBlue);
  90. mDebugRenderer->DrawTriangle(p2, p4, p3, Color::sBlue);
  91. }
  92. // Apply buoyancy to all bodies in the water
  93. {
  94. lock_guard<Mutex> lock(mBodiesInWaterMutex);
  95. for (const BodyID &id : mBodiesInWater)
  96. {
  97. BodyLockWrite body_lock(mPhysicsSystem->GetBodyLockInterface(), id);
  98. Body &body = body_lock.GetBody();
  99. if (body.IsActive())
  100. {
  101. // Use center of mass position to determine water surface position (you could test multiple points on the actual shape of the boat to get a more accurate result)
  102. RVec3 surface_position = GetWaterSurfacePosition(body.GetCenterOfMassPosition());
  103. // Crude way of approximating the surface normal
  104. RVec3 p2 = GetWaterSurfacePosition(body.GetCenterOfMassPosition() + Vec3(0, 0, 1));
  105. RVec3 p3 = GetWaterSurfacePosition(body.GetCenterOfMassPosition() + Vec3(1, 0, 0));
  106. Vec3 surface_normal = Vec3(p2 - surface_position).Cross(Vec3(p3 - surface_position)).Normalized();
  107. // Determine buoyancy and drag
  108. float buoyancy, linear_drag, angular_drag;
  109. if (id == mBoatBody->GetID())
  110. {
  111. buoyancy = cBoatBuoyancy;
  112. linear_drag = cBoatLinearDrag;
  113. angular_drag = cBoatAngularDrag;
  114. }
  115. else
  116. {
  117. buoyancy = cBarrelBuoyancy;
  118. linear_drag = cBarrelLinearDrag;
  119. angular_drag = cBarrelAngularDrag;
  120. }
  121. // Apply buoyancy to the body
  122. body.ApplyBuoyancyImpulse(surface_position, surface_normal, buoyancy, linear_drag, angular_drag, Vec3::sZero(), mPhysicsSystem->GetGravity(), inParams.mDeltaTime);
  123. }
  124. }
  125. }
  126. // On user input, assure that the boat is active
  127. if (mRight != 0.0f || mForward != 0.0f)
  128. mBodyInterface->ActivateBody(mBoatBody->GetID());
  129. // Apply forces to rear of boat where the propeller would be but only when the propeller is under water
  130. RVec3 propeller_position = mBoatBody->GetWorldTransform() * Vec3(0, -cHalfBoatHeight, -cHalfBoatLength);
  131. RVec3 propeller_surface_position = GetWaterSurfacePosition(propeller_position);
  132. if (propeller_surface_position.GetY() > propeller_position.GetY())
  133. {
  134. Vec3 forward = mBoatBody->GetRotation().RotateAxisZ();
  135. Vec3 right = mBoatBody->GetRotation().RotateAxisX();
  136. mBoatBody->AddImpulse((forward * mForward * cForwardAcceleration + right * Sign(mForward) * mRight * cSteerAcceleration) * cBoatMass * inParams.mDeltaTime, propeller_position);
  137. }
  138. UpdateCameraPivot();
  139. }
  140. void BoatTest::SaveInputState(StateRecorder &inStream) const
  141. {
  142. inStream.Write(mForward);
  143. inStream.Write(mRight);
  144. }
  145. void BoatTest::RestoreInputState(StateRecorder &inStream)
  146. {
  147. inStream.Read(mForward);
  148. inStream.Read(mRight);
  149. }
  150. void BoatTest::SaveState(StateRecorder &inStream) const
  151. {
  152. inStream.Write(mTime);
  153. inStream.Write(mBodiesInWater);
  154. }
  155. void BoatTest::RestoreState(StateRecorder &inStream)
  156. {
  157. inStream.Read(mTime);
  158. inStream.Read(mBodiesInWater);
  159. }
  160. void BoatTest::GetInitialCamera(CameraState &ioState) const
  161. {
  162. // Position camera behind boat
  163. RVec3 cam_tgt = RVec3(0, 0, 5);
  164. ioState.mPos = RVec3(0, 5, -10);
  165. ioState.mForward = Vec3(cam_tgt - ioState.mPos).Normalized();
  166. }
  167. void BoatTest::UpdateCameraPivot()
  168. {
  169. // Pivot is center of boat and rotates with boat around Y axis only
  170. Vec3 fwd = mBoatBody->GetRotation().RotateAxisZ();
  171. fwd.SetY(0.0f);
  172. float len = fwd.Length();
  173. if (len != 0.0f)
  174. fwd /= len;
  175. else
  176. fwd = Vec3::sAxisZ();
  177. Vec3 up = Vec3::sAxisY();
  178. Vec3 right = up.Cross(fwd);
  179. mCameraPivot = RMat44(Vec4(right, 0), Vec4(up, 0), Vec4(fwd, 0), mBoatBody->GetPosition());
  180. }
  181. void BoatTest::OnContactAdded(const Body &inBody1, const Body &inBody2, const ContactManifold &inManifold, ContactSettings &ioSettings)
  182. {
  183. // When a body enters the water add it to the list of bodies in the water
  184. lock_guard<Mutex> lock(mBodiesInWaterMutex);
  185. if (inBody1.GetID() == mWaterSensor)
  186. mBodiesInWater.push_back(inBody2.GetID());
  187. else if (inBody2.GetID() == mWaterSensor)
  188. mBodiesInWater.push_back(inBody1.GetID());
  189. }
  190. void BoatTest::OnContactRemoved(const SubShapeIDPair &inSubShapePair)
  191. {
  192. // When a body leaves the water remove it from the list of bodies in the water
  193. lock_guard<Mutex> lock(mBodiesInWaterMutex);
  194. if (inSubShapePair.GetBody1ID() == mWaterSensor)
  195. mBodiesInWater.erase(std::find(mBodiesInWater.begin(), mBodiesInWater.end(), inSubShapePair.GetBody2ID()));
  196. else if (inSubShapePair.GetBody2ID() == mWaterSensor)
  197. mBodiesInWater.erase(std::find(mBodiesInWater.begin(), mBodiesInWater.end(), inSubShapePair.GetBody1ID()));
  198. }