Body.cpp 14 KB

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