MotionProperties.inl 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. JPH_NAMESPACE_BEGIN
  6. void MotionProperties::MoveKinematic(Vec3Arg inDeltaPosition, QuatArg inDeltaRotation, float inDeltaTime)
  7. {
  8. JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::ReadWrite));
  9. JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sPositionAccess(), BodyAccess::EAccess::Read));
  10. JPH_ASSERT(mCachedBodyType == EBodyType::RigidBody);
  11. JPH_ASSERT(mCachedMotionType != EMotionType::Static);
  12. // Calculate required linear velocity
  13. mLinearVelocity = LockTranslation(inDeltaPosition / inDeltaTime);
  14. // Calculate required angular velocity
  15. mAngularVelocity = LockAngular(inDeltaRotation.GetAngularVelocity(inDeltaTime));
  16. }
  17. void MotionProperties::ClampLinearVelocity()
  18. {
  19. JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::ReadWrite));
  20. float len_sq = mLinearVelocity.LengthSq();
  21. JPH_ASSERT(isfinite(len_sq));
  22. if (len_sq > Square(mMaxLinearVelocity))
  23. mLinearVelocity *= mMaxLinearVelocity / sqrt(len_sq);
  24. }
  25. void MotionProperties::ClampAngularVelocity()
  26. {
  27. JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::ReadWrite));
  28. float len_sq = mAngularVelocity.LengthSq();
  29. JPH_ASSERT(isfinite(len_sq));
  30. if (len_sq > Square(mMaxAngularVelocity))
  31. mAngularVelocity *= mMaxAngularVelocity / sqrt(len_sq);
  32. }
  33. inline Mat44 MotionProperties::GetLocalSpaceInverseInertiaUnchecked() const
  34. {
  35. Mat44 rotation = Mat44::sRotation(mInertiaRotation);
  36. Mat44 rotation_mul_scale_transposed(mInvInertiaDiagonal.SplatX() * rotation.GetColumn4(0), mInvInertiaDiagonal.SplatY() * rotation.GetColumn4(1), mInvInertiaDiagonal.SplatZ() * rotation.GetColumn4(2), Vec4(0, 0, 0, 1));
  37. return rotation.Multiply3x3RightTransposed(rotation_mul_scale_transposed);
  38. }
  39. inline void MotionProperties::ScaleToMass(float inMass)
  40. {
  41. JPH_ASSERT(mInvMass > 0.0f, "Body must have finite mass");
  42. JPH_ASSERT(inMass > 0.0f, "New mass cannot be zero");
  43. float new_inv_mass = 1.0f / inMass;
  44. mInvInertiaDiagonal *= new_inv_mass / mInvMass;
  45. mInvMass = new_inv_mass;
  46. }
  47. inline Mat44 MotionProperties::GetLocalSpaceInverseInertia() const
  48. {
  49. JPH_ASSERT(mCachedMotionType == EMotionType::Dynamic);
  50. return GetLocalSpaceInverseInertiaUnchecked();
  51. }
  52. Mat44 MotionProperties::GetInverseInertiaForRotation(Mat44Arg inRotation) const
  53. {
  54. JPH_ASSERT(mCachedMotionType == EMotionType::Dynamic);
  55. Mat44 rotation = inRotation.Multiply3x3(Mat44::sRotation(mInertiaRotation));
  56. Mat44 rotation_mul_scale_transposed(mInvInertiaDiagonal.SplatX() * rotation.GetColumn4(0), mInvInertiaDiagonal.SplatY() * rotation.GetColumn4(1), mInvInertiaDiagonal.SplatZ() * rotation.GetColumn4(2), Vec4(0, 0, 0, 1));
  57. Mat44 inverse_inertia = rotation.Multiply3x3RightTransposed(rotation_mul_scale_transposed);
  58. // We need to mask out both the rows and columns of DOFs that are not allowed
  59. Vec4 angular_dofs_mask = GetAngularDOFsMask().ReinterpretAsFloat();
  60. inverse_inertia.SetColumn4(0, Vec4::sAnd(inverse_inertia.GetColumn4(0), Vec4::sAnd(angular_dofs_mask, angular_dofs_mask.SplatX())));
  61. inverse_inertia.SetColumn4(1, Vec4::sAnd(inverse_inertia.GetColumn4(1), Vec4::sAnd(angular_dofs_mask, angular_dofs_mask.SplatY())));
  62. inverse_inertia.SetColumn4(2, Vec4::sAnd(inverse_inertia.GetColumn4(2), Vec4::sAnd(angular_dofs_mask, angular_dofs_mask.SplatZ())));
  63. return inverse_inertia;
  64. }
  65. Vec3 MotionProperties::MultiplyWorldSpaceInverseInertiaByVector(QuatArg inBodyRotation, Vec3Arg inV) const
  66. {
  67. JPH_ASSERT(mCachedMotionType == EMotionType::Dynamic);
  68. // Mask out columns of DOFs that are not allowed
  69. Vec3 angular_dofs_mask = Vec3(GetAngularDOFsMask().ReinterpretAsFloat());
  70. Vec3 v = Vec3::sAnd(inV, angular_dofs_mask);
  71. // Multiply vector by inverse inertia
  72. Mat44 rotation = Mat44::sRotation(inBodyRotation * mInertiaRotation);
  73. Vec3 result = rotation.Multiply3x3(mInvInertiaDiagonal * rotation.Multiply3x3Transposed(v));
  74. // Mask out rows of DOFs that are not allowed
  75. return Vec3::sAnd(result, angular_dofs_mask);
  76. }
  77. void MotionProperties::ApplyGyroscopicForceInternal(QuatArg inBodyRotation, float inDeltaTime)
  78. {
  79. JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::ReadWrite));
  80. JPH_ASSERT(mCachedBodyType == EBodyType::RigidBody);
  81. JPH_ASSERT(mCachedMotionType == EMotionType::Dynamic);
  82. // Calculate local space inertia tensor (a diagonal in local space)
  83. UVec4 is_zero = Vec3::sEquals(mInvInertiaDiagonal, Vec3::sZero());
  84. Vec3 denominator = Vec3::sSelect(mInvInertiaDiagonal, Vec3::sOne(), is_zero);
  85. Vec3 nominator = Vec3::sSelect(Vec3::sOne(), Vec3::sZero(), is_zero);
  86. Vec3 local_inertia = nominator / denominator; // Avoid dividing by zero, inertia in this axis will be zero
  87. // Calculate local space angular momentum
  88. Quat inertia_space_to_world_space = inBodyRotation * mInertiaRotation;
  89. Vec3 local_angular_velocity = inertia_space_to_world_space.InverseRotate(mAngularVelocity);
  90. Vec3 local_momentum = local_inertia * local_angular_velocity;
  91. // The gyroscopic force applies a torque: T = -w x I w where w is angular velocity and I the inertia tensor
  92. // Calculate the new angular momentum by applying the gyroscopic force and make sure the new magnitude is the same as the old one
  93. // to avoid introducing energy into the system due to the Euler step
  94. Vec3 new_local_momentum = local_momentum - inDeltaTime * local_angular_velocity.Cross(local_momentum);
  95. float new_local_momentum_len_sq = new_local_momentum.LengthSq();
  96. new_local_momentum = new_local_momentum_len_sq > 0.0f? new_local_momentum * sqrt(local_momentum.LengthSq() / new_local_momentum_len_sq) : Vec3::sZero();
  97. // Convert back to world space angular velocity
  98. mAngularVelocity = inertia_space_to_world_space * (mInvInertiaDiagonal * new_local_momentum);
  99. }
  100. void MotionProperties::ApplyForceTorqueAndDragInternal(QuatArg inBodyRotation, Vec3Arg inGravity, float inDeltaTime)
  101. {
  102. JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::ReadWrite));
  103. JPH_ASSERT(mCachedBodyType == EBodyType::RigidBody);
  104. JPH_ASSERT(mCachedMotionType == EMotionType::Dynamic);
  105. // Update linear velocity
  106. mLinearVelocity = LockTranslation(mLinearVelocity + inDeltaTime * (mGravityFactor * inGravity + mInvMass * GetAccumulatedForce()));
  107. // Update angular velocity
  108. mAngularVelocity += inDeltaTime * MultiplyWorldSpaceInverseInertiaByVector(inBodyRotation, GetAccumulatedTorque());
  109. // Linear damping: dv/dt = -c * v
  110. // Solution: v(t) = v(0) * e^(-c * t) or v2 = v1 * e^(-c * dt)
  111. // Taylor expansion of e^(-c * dt) = 1 - c * dt + ...
  112. // Since dt is usually in the order of 1/60 and c is a low number too this approximation is good enough
  113. mLinearVelocity *= max(0.0f, 1.0f - mLinearDamping * inDeltaTime);
  114. mAngularVelocity *= max(0.0f, 1.0f - mAngularDamping * inDeltaTime);
  115. // Clamp velocities
  116. ClampLinearVelocity();
  117. ClampAngularVelocity();
  118. }
  119. void MotionProperties::ResetSleepTestSpheres(const RVec3 *inPoints)
  120. {
  121. #ifdef JPH_DOUBLE_PRECISION
  122. // Make spheres relative to the first point and initialize them to zero radius
  123. DVec3 offset = inPoints[0];
  124. offset.StoreDouble3(&mSleepTestOffset);
  125. mSleepTestSpheres[0] = Sphere(Vec3::sZero(), 0.0f);
  126. for (int i = 1; i < 3; ++i)
  127. mSleepTestSpheres[i] = Sphere(Vec3(inPoints[i] - offset), 0.0f);
  128. #else
  129. // Initialize the spheres to zero radius around the supplied points
  130. for (int i = 0; i < 3; ++i)
  131. mSleepTestSpheres[i] = Sphere(inPoints[i], 0.0f);
  132. #endif
  133. mSleepTestTimer = 0.0f;
  134. }
  135. ECanSleep MotionProperties::AccumulateSleepTime(float inDeltaTime, float inTimeBeforeSleep)
  136. {
  137. mSleepTestTimer += inDeltaTime;
  138. return mSleepTestTimer >= inTimeBeforeSleep? ECanSleep::CanSleep : ECanSleep::CannotSleep;
  139. }
  140. JPH_NAMESPACE_END