Body.cpp 13 KB

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