Body.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <Jolt/Jolt.h>
  4. #include <Jolt/Physics/Body/Body.h>
  5. #include <Jolt/Physics/Body/BodyCreationSettings.h>
  6. #include <Jolt/Physics/PhysicsSettings.h>
  7. #include <Jolt/Physics/StateRecorder.h>
  8. #include <Jolt/Physics/Collision/Shape/SphereShape.h>
  9. #include <Jolt/Core/StringTools.h>
  10. #include <Jolt/Core/Profiler.h>
  11. #ifdef JPH_DEBUG_RENDERER
  12. #include <Jolt/Renderer/DebugRenderer.h>
  13. #endif // JPH_DEBUG_RENDERER
  14. JPH_NAMESPACE_BEGIN
  15. Body Body::sFixedToWorld(false);
  16. Body::Body(bool) :
  17. mPosition(Vec3::sZero()),
  18. mRotation(Quat::sIdentity()),
  19. mShape(new SphereShape(FLT_EPSILON)), // Dummy shape
  20. mFriction(0.0f),
  21. mRestitution(0.0f),
  22. mObjectLayer(cObjectLayerInvalid),
  23. mMotionType(EMotionType::Static)
  24. {
  25. }
  26. void Body::SetMotionType(EMotionType inMotionType)
  27. {
  28. if (mMotionType == inMotionType)
  29. return;
  30. JPH_ASSERT(inMotionType == EMotionType::Static || mMotionProperties != nullptr, "Body needs to be created with mAllowDynamicOrKinematic set tot true");
  31. JPH_ASSERT(inMotionType != EMotionType::Static || !IsActive(), "Deactivate body first");
  32. // Store new motion type
  33. mMotionType = inMotionType;
  34. if (mMotionProperties != nullptr)
  35. {
  36. // Update cache
  37. JPH_IF_ENABLE_ASSERTS(mMotionProperties->mCachedMotionType = inMotionType;)
  38. switch (inMotionType)
  39. {
  40. case EMotionType::Static:
  41. // Stop the object
  42. mMotionProperties->mLinearVelocity = Vec3::sZero();
  43. mMotionProperties->mAngularVelocity = Vec3::sZero();
  44. [[fallthrough]];
  45. case EMotionType::Kinematic:
  46. // Cancel forces
  47. mMotionProperties->mForce = Float3(0, 0, 0);
  48. mMotionProperties->mTorque = Float3(0, 0, 0);
  49. break;
  50. case EMotionType::Dynamic:
  51. break;
  52. }
  53. }
  54. }
  55. void Body::SetAllowSleeping(bool inAllow)
  56. {
  57. mMotionProperties->mAllowSleeping = inAllow;
  58. if (inAllow)
  59. ResetSleepTestSpheres();
  60. }
  61. void Body::MoveKinematic(Vec3Arg inTargetPosition, QuatArg inTargetRotation, float inDeltaTime)
  62. {
  63. JPH_ASSERT(!IsStatic());
  64. JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess, BodyAccess::EAccess::Read));
  65. // Calculate center of mass at end situation
  66. Vec3 new_com = inTargetPosition + inTargetRotation * mShape->GetCenterOfMass();
  67. // Calculate delta position and rotation
  68. Vec3 delta_pos = new_com - mPosition;
  69. Quat delta_rotation = inTargetRotation * mRotation.Conjugated();
  70. mMotionProperties->MoveKinematic(delta_pos, delta_rotation, inDeltaTime);
  71. }
  72. void Body::CalculateWorldSpaceBoundsInternal()
  73. {
  74. mBounds = mShape->GetWorldSpaceBounds(GetCenterOfMassTransform(), Vec3::sReplicate(1.0f));
  75. }
  76. void Body::SetPositionAndRotationInternal(Vec3Arg inPosition, QuatArg inRotation)
  77. {
  78. JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess, BodyAccess::EAccess::ReadWrite));
  79. mPosition = inPosition + inRotation * mShape->GetCenterOfMass();
  80. mRotation = inRotation;
  81. // Initialize bounding box
  82. CalculateWorldSpaceBoundsInternal();
  83. // Reset sleeping test
  84. if (mMotionProperties != nullptr)
  85. ResetSleepTestSpheres();
  86. }
  87. void Body::UpdateCenterOfMassInternal(Vec3Arg inPreviousCenterOfMass, bool inUpdateMassProperties)
  88. {
  89. // Update center of mass position so the world position for this body stays the same
  90. mPosition += mRotation * (mShape->GetCenterOfMass() - inPreviousCenterOfMass);
  91. // Recalculate mass and inertia if requested
  92. if (inUpdateMassProperties && mMotionProperties != nullptr)
  93. mMotionProperties->SetMassProperties(mShape->GetMassProperties());
  94. }
  95. void Body::SetShapeInternal(const Shape *inShape, bool inUpdateMassProperties)
  96. {
  97. JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess, BodyAccess::EAccess::ReadWrite));
  98. // Get the old center of mass
  99. Vec3 old_com = mShape->GetCenterOfMass();
  100. // Update the shape
  101. mShape = inShape;
  102. // Update center of mass
  103. UpdateCenterOfMassInternal(old_com, inUpdateMassProperties);
  104. // Recalculate bounding box
  105. CalculateWorldSpaceBoundsInternal();
  106. }
  107. Body::ECanSleep Body::UpdateSleepStateInternal(float inDeltaTime, float inMaxMovement, float inTimeBeforeSleep)
  108. {
  109. // Check override & sensors will never go to sleep (they would stop detecting collisions with sleeping bodies)
  110. if (!mMotionProperties->mAllowSleeping || IsSensor())
  111. return ECanSleep::CannotSleep;
  112. // Get the points to test
  113. Vec3 points[3];
  114. GetSleepTestPoints(points);
  115. for (int i = 0; i < 3; ++i)
  116. {
  117. Sphere &sphere = mMotionProperties->mSleepTestSpheres[i];
  118. // Encapsulate the point in a sphere
  119. sphere.EncapsulatePoint(points[i]);
  120. // Test if it exceeded the max movement
  121. if (sphere.GetRadius() > inMaxMovement)
  122. {
  123. // Body is not sleeping, reset test
  124. mMotionProperties->ResetSleepTestSpheres(points);
  125. return ECanSleep::CannotSleep;
  126. }
  127. }
  128. mMotionProperties->mSleepTestTimer += inDeltaTime;
  129. return mMotionProperties->mSleepTestTimer >= inTimeBeforeSleep? ECanSleep::CanSleep : ECanSleep::CannotSleep;
  130. }
  131. bool Body::ApplyBuoyancyImpulse(const Plane &inSurface, float inBuoyancy, float inLinearDrag, float inAngularDrag, Vec3Arg inFluidVelocity, Vec3Arg inGravity, float inDeltaTime)
  132. {
  133. JPH_PROFILE_FUNCTION();
  134. // We follow the approach from 'Game Programming Gems 6' 2.5 Exact Buoyancy for Polyhedra
  135. // All quantities below are in world space
  136. // Calculate amount of volume that is submerged and what the center of buoyancy is
  137. float total_volume, submerged_volume;
  138. Vec3 center_of_buoyancy;
  139. mShape->GetSubmergedVolume(GetCenterOfMassTransform(), Vec3::sReplicate(1.0f), inSurface, total_volume, submerged_volume, center_of_buoyancy);
  140. // If we're not submerged, there's no point in doing the rest of the calculations
  141. if (submerged_volume > 0.0f)
  142. {
  143. #ifdef JPH_DEBUG_RENDERER
  144. // Draw submerged volume properties
  145. if (Shape::sDrawSubmergedVolumes)
  146. {
  147. DebugRenderer::sInstance->DrawMarker(center_of_buoyancy, Color::sWhite, 2.0f);
  148. DebugRenderer::sInstance->DrawText3D(center_of_buoyancy, StringFormat("%.3f / %.3f", (double)submerged_volume, (double)total_volume));
  149. }
  150. #endif // JPH_DEBUG_RENDERER
  151. // When buoyancy is 1 we want neutral buoyancy, this means that the density of the liquid is the same as the density of the body at that point.
  152. // Buoyancy > 1 should make the object float, < 1 should make it sink.
  153. float inverse_mass = mMotionProperties->GetInverseMass();
  154. float fluid_density = inBuoyancy / (total_volume * inverse_mass);
  155. // Buoyancy force = Density of Fluid * Submerged volume * Magnitude of gravity * Up direction (eq 2.5.1)
  156. // Impulse = Force * Delta time
  157. // We should apply this at the center of buoyancy (= center of mass of submerged volume)
  158. Vec3 buoyancy_impulse = -fluid_density * submerged_volume * mMotionProperties->GetGravityFactor() * inGravity * inDeltaTime;
  159. // Calculate the velocity of the center of buoyancy relative to the fluid
  160. Vec3 relative_center_of_buoyancy = center_of_buoyancy - mPosition;
  161. Vec3 linear_velocity = mMotionProperties->GetLinearVelocity();
  162. Vec3 angular_velocity = mMotionProperties->GetAngularVelocity();
  163. Vec3 center_of_buoyancy_velocity = linear_velocity + angular_velocity.Cross(relative_center_of_buoyancy);
  164. Vec3 relative_center_of_buoyancy_velocity = inFluidVelocity - center_of_buoyancy_velocity;
  165. // Here we deviate from the article, instead of eq 2.5.14 we use a quadratic drag formula: https://en.wikipedia.org/wiki/Drag_%28physics%29
  166. // Drag force = 0.5 * Fluid Density * (Velocity of fluid - Velocity of center of buoyancy)^2 * Linear Drag * Area Facing the Relative Fluid Velocity
  167. // Again Impulse = Force * Delta Time
  168. // We should apply this at the center of buoyancy (= center of mass for submerged volume with no center of mass offset)
  169. // Get size of local bounding box
  170. Vec3 size = mShape->GetLocalBounds().GetSize();
  171. // Determine area of the local space bounding box in the direction of the relative velocity between the fluid and the center of buoyancy
  172. float area = 0.0f;
  173. float relative_center_of_buoyancy_velocity_len_sq = relative_center_of_buoyancy_velocity.LengthSq();
  174. if (relative_center_of_buoyancy_velocity_len_sq > 1.0e-12f)
  175. {
  176. Vec3 local_relative_center_of_buoyancy_velocity = GetRotation().Conjugated() * relative_center_of_buoyancy_velocity;
  177. area = local_relative_center_of_buoyancy_velocity.Abs().Dot(size.Swizzle<SWIZZLE_Y, SWIZZLE_Z, SWIZZLE_X>() * size.Swizzle<SWIZZLE_Z, SWIZZLE_X, SWIZZLE_Y>()) / sqrt(relative_center_of_buoyancy_velocity_len_sq);
  178. }
  179. // Calculate the impulse
  180. Vec3 drag_impulse = (0.5f * fluid_density * inLinearDrag * area * inDeltaTime) * relative_center_of_buoyancy_velocity * relative_center_of_buoyancy_velocity.Length();
  181. // Clamp magnitude against current linear velocity to prevent overshoot
  182. float linear_velocity_len_sq = linear_velocity.LengthSq();
  183. float drag_delta_linear_velocity_len_sq = (drag_impulse * inverse_mass).LengthSq();
  184. if (drag_delta_linear_velocity_len_sq > linear_velocity_len_sq)
  185. drag_impulse *= sqrt(linear_velocity_len_sq / drag_delta_linear_velocity_len_sq);
  186. // Calculate the resulting delta linear velocity due to buoyancy and drag
  187. Vec3 delta_linear_velocity = (drag_impulse + buoyancy_impulse) * inverse_mass;
  188. mMotionProperties->AddLinearVelocityStep(delta_linear_velocity);
  189. // Determine average width of the body (across the three axis)
  190. float l = (size.GetX() + size.GetY() + size.GetZ()) / 3.0f;
  191. // Drag torque = -Angular Drag * Mass * Submerged volume / Total volume * (Average width of body)^2 * Angular velocity (eq 2.5.15)
  192. Vec3 drag_angular_impulse = (-inAngularDrag * submerged_volume / total_volume * inDeltaTime * Square(l) / inverse_mass) * angular_velocity;
  193. Mat44 inv_inertia = GetInverseInertia();
  194. Vec3 drag_delta_angular_velocity = inv_inertia * drag_angular_impulse;
  195. // Clamp magnitude against the current angular velocity to prevent overshoot
  196. float angular_velocity_len_sq = angular_velocity.LengthSq();
  197. float drag_delta_angular_velocity_len_sq = drag_delta_angular_velocity.LengthSq();
  198. if (drag_delta_angular_velocity_len_sq > angular_velocity_len_sq)
  199. drag_delta_angular_velocity *= sqrt(angular_velocity_len_sq / drag_delta_angular_velocity_len_sq);
  200. // Calculate total delta angular velocity due to drag and buoyancy
  201. Vec3 delta_angular_velocity = drag_delta_angular_velocity + inv_inertia * relative_center_of_buoyancy.Cross(buoyancy_impulse + drag_impulse);
  202. mMotionProperties->AddAngularVelocityStep(delta_angular_velocity);
  203. return true;
  204. }
  205. return false;
  206. }
  207. void Body::SaveState(StateRecorder &inStream) const
  208. {
  209. // Only write properties that can change at runtime
  210. inStream.Write(mPosition);
  211. inStream.Write(mRotation);
  212. inStream.Write(mFriction);
  213. inStream.Write(mRestitution);
  214. mCollisionGroup.SaveBinaryState(inStream);
  215. inStream.Write(mMotionType);
  216. if (mMotionProperties != nullptr)
  217. mMotionProperties->SaveState(inStream);
  218. }
  219. void Body::RestoreState(StateRecorder &inStream)
  220. {
  221. inStream.Read(mPosition);
  222. inStream.Read(mRotation);
  223. inStream.Read(mFriction);
  224. inStream.Read(mRestitution);
  225. mCollisionGroup.RestoreBinaryState(inStream);
  226. inStream.Read(mMotionType);
  227. if (mMotionProperties != nullptr)
  228. {
  229. mMotionProperties->RestoreState(inStream);
  230. JPH_IF_ENABLE_ASSERTS(mMotionProperties->mCachedMotionType = mMotionType);
  231. }
  232. // Initialize bounding box
  233. CalculateWorldSpaceBoundsInternal();
  234. }
  235. BodyCreationSettings Body::GetBodyCreationSettings() const
  236. {
  237. BodyCreationSettings result;
  238. result.mPosition = GetPosition();
  239. result.mRotation = GetRotation();
  240. result.mLinearVelocity = mMotionProperties != nullptr? mMotionProperties->GetLinearVelocity() : Vec3::sZero();
  241. result.mAngularVelocity = mMotionProperties != nullptr? mMotionProperties->GetAngularVelocity() : Vec3::sZero();
  242. result.mObjectLayer = GetObjectLayer();
  243. result.mCollisionGroup = GetCollisionGroup();
  244. result.mMotionType = GetMotionType();
  245. result.mAllowDynamicOrKinematic = mMotionProperties != nullptr;
  246. result.mIsSensor = IsSensor();
  247. result.mMotionQuality = mMotionProperties != nullptr? mMotionProperties->GetMotionQuality() : EMotionQuality::Discrete;
  248. result.mAllowSleeping = mMotionProperties != nullptr? GetAllowSleeping() : true;
  249. result.mFriction = GetFriction();
  250. result.mRestitution = GetRestitution();
  251. result.mLinearDamping = mMotionProperties != nullptr? mMotionProperties->GetLinearDamping() : 0.0f;
  252. result.mAngularDamping = mMotionProperties != nullptr? mMotionProperties->GetAngularDamping() : 0.0f;
  253. result.mMaxLinearVelocity = mMotionProperties != nullptr? mMotionProperties->GetMaxLinearVelocity() : 0.0f;
  254. result.mMaxAngularVelocity = mMotionProperties != nullptr? mMotionProperties->GetMaxAngularVelocity() : 0.0f;
  255. result.mGravityFactor = mMotionProperties != nullptr? mMotionProperties->GetGravityFactor() : 1.0f;
  256. result.mOverrideMassProperties = EOverrideMassProperties::MassAndInertiaProvided;
  257. result.mMassPropertiesOverride.mMass = mMotionProperties != nullptr? 1.0f / mMotionProperties->GetInverseMassUnchecked() : FLT_MAX;
  258. result.mMassPropertiesOverride.mInertia = mMotionProperties != nullptr? mMotionProperties->GetLocalSpaceInverseInertiaUnchecked().Inversed3x3() : Mat44::sIdentity();
  259. result.SetShape(GetShape());
  260. return result;
  261. }
  262. JPH_NAMESPACE_END