IndependentAxisConstraintPart.h 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2022 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Jolt/Physics/Body/Body.h>
  6. #include <Jolt/Physics/StateRecorder.h>
  7. JPH_NAMESPACE_BEGIN
  8. /// Constraint part to an AxisConstraintPart but both bodies have an independent axis on which the force is applied.
  9. ///
  10. /// Constraint equation:
  11. ///
  12. /// \f[C = (x_1 + r_1 - f_1) . n_1 + r (x_2 + r_2 - f_2) \cdot n_2\f]
  13. ///
  14. /// Calculating the Jacobian:
  15. ///
  16. /// \f[dC/dt = (v_1 + w_1 \times r_1) \cdot n_1 + (x_1 + r_1 - f_1) \cdot d n_1/dt + r (v_2 + w_2 \times r_2) \cdot n_2 + r (x_2 + r_2 - f_2) \cdot d n_2/dt\f]
  17. ///
  18. /// Assuming that d n1/dt and d n2/dt are small this becomes:
  19. ///
  20. /// \f[(v_1 + w_1 \times r_1) \cdot n_1 + r (v_2 + w_2 \times r_2) \cdot n_2\f]
  21. /// \f[= v_1 \cdot n_1 + r_1 \times n_1 \cdot w_1 + r v_2 \cdot n_2 + r r_2 \times n_2 \cdot w_2\f]
  22. ///
  23. /// Jacobian:
  24. ///
  25. /// \f[J = \begin{bmatrix}n_1 & r_1 \times n_1 & r n_2 & r r_2 \times n_2\end{bmatrix}\f]
  26. ///
  27. /// Effective mass:
  28. ///
  29. /// \f[K = m_1^{-1} + r_1 \times n_1 I_1^{-1} r_1 \times n_1 + r^2 m_2^{-1} + r^2 r_2 \times n_2 I_2^{-1} r_2 \times n_2\f]
  30. ///
  31. /// Used terms (here and below, everything in world space):\n
  32. /// n1 = (x1 + r1 - f1) / |x1 + r1 - f1|, axis along which the force is applied for body 1\n
  33. /// n2 = (x2 + r2 - f2) / |x2 + r2 - f2|, axis along which the force is applied for body 2\n
  34. /// r = ratio how forces are applied between bodies.\n
  35. /// x1, x2 = center of mass for the bodies.\n
  36. /// v = [v1, w1, v2, w2].\n
  37. /// v1, v2 = linear velocity of body 1 and 2.\n
  38. /// w1, w2 = angular velocity of body 1 and 2.\n
  39. /// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n
  40. /// \f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n
  41. /// b = velocity bias.\n
  42. /// \f$\beta\f$ = baumgarte constant.
  43. class IndependentAxisConstraintPart
  44. {
  45. /// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated
  46. JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, Vec3Arg inN1, Vec3Arg inN2, float inRatio, float inLambda) const
  47. {
  48. // Apply impulse if delta is not zero
  49. if (inLambda != 0.0f)
  50. {
  51. // Calculate velocity change due to constraint
  52. //
  53. // Impulse:
  54. // P = J^T lambda
  55. //
  56. // Euler velocity integration:
  57. // v' = v + M^-1 P
  58. if (ioBody1.IsDynamic())
  59. {
  60. MotionProperties *mp1 = ioBody1.GetMotionProperties();
  61. mp1->AddLinearVelocityStep((mp1->GetInverseMass() * inLambda) * inN1);
  62. mp1->AddAngularVelocityStep(mInvI1_R1xN1 * inLambda);
  63. }
  64. if (ioBody2.IsDynamic())
  65. {
  66. MotionProperties *mp2 = ioBody2.GetMotionProperties();
  67. mp2->AddLinearVelocityStep((inRatio * mp2->GetInverseMass() * inLambda) * inN2);
  68. mp2->AddAngularVelocityStep(mInvI2_RatioR2xN2 * inLambda);
  69. }
  70. return true;
  71. }
  72. return false;
  73. }
  74. public:
  75. /// Calculate properties used during the functions below
  76. /// @param inBody1 The first body that this constraint is attached to
  77. /// @param inBody2 The second body that this constraint is attached to
  78. /// @param inR1 The position on which the constraint operates on body 1 relative to COM
  79. /// @param inN1 The world space normal in which the constraint operates for body 1
  80. /// @param inR2 The position on which the constraint operates on body 1 relative to COM
  81. /// @param inN2 The world space normal in which the constraint operates for body 2
  82. /// @param inRatio The ratio how forces are applied between bodies
  83. inline void CalculateConstraintProperties(const Body &inBody1, const Body &inBody2, Vec3Arg inR1, Vec3Arg inN1, Vec3Arg inR2, Vec3Arg inN2, float inRatio)
  84. {
  85. JPH_ASSERT(inN1.IsNormalized(1.0e-4f) && inN2.IsNormalized(1.0e-4f));
  86. float inv_effective_mass = 0.0f;
  87. if (!inBody1.IsStatic())
  88. {
  89. const MotionProperties *mp1 = inBody1.GetMotionProperties();
  90. mR1xN1 = inR1.Cross(inN1);
  91. mInvI1_R1xN1 = mp1->MultiplyWorldSpaceInverseInertiaByVector(inBody1.GetRotation(), mR1xN1);
  92. inv_effective_mass += mp1->GetInverseMass() + mInvI1_R1xN1.Dot(mR1xN1);
  93. }
  94. if (!inBody2.IsStatic())
  95. {
  96. const MotionProperties *mp2 = inBody2.GetMotionProperties();
  97. mRatioR2xN2 = inRatio * inR2.Cross(inN2);
  98. mInvI2_RatioR2xN2 = mp2->MultiplyWorldSpaceInverseInertiaByVector(inBody2.GetRotation(), mRatioR2xN2);
  99. inv_effective_mass += Square(inRatio) * mp2->GetInverseMass() + mInvI2_RatioR2xN2.Dot(mRatioR2xN2);
  100. }
  101. // Calculate inverse effective mass: K = J M^-1 J^T
  102. if (inv_effective_mass == 0.0f)
  103. Deactivate();
  104. else
  105. mEffectiveMass = 1.0f / inv_effective_mass;
  106. }
  107. /// Deactivate this constraint
  108. inline void Deactivate()
  109. {
  110. mEffectiveMass = 0.0f;
  111. mTotalLambda = 0.0f;
  112. }
  113. /// Check if constraint is active
  114. inline bool IsActive() const
  115. {
  116. return mEffectiveMass != 0.0f;
  117. }
  118. /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
  119. /// @param ioBody1 The first body that this constraint is attached to
  120. /// @param ioBody2 The second body that this constraint is attached to
  121. /// @param inN1 The world space normal in which the constraint operates for body 1
  122. /// @param inN2 The world space normal in which the constraint operates for body 2
  123. /// @param inRatio The ratio how forces are applied between bodies
  124. /// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame
  125. inline void WarmStart(Body &ioBody1, Body &ioBody2, Vec3Arg inN1, Vec3Arg inN2, float inRatio, float inWarmStartImpulseRatio)
  126. {
  127. mTotalLambda *= inWarmStartImpulseRatio;
  128. ApplyVelocityStep(ioBody1, ioBody2, inN1, inN2, inRatio, mTotalLambda);
  129. }
  130. /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
  131. /// @param ioBody1 The first body that this constraint is attached to
  132. /// @param ioBody2 The second body that this constraint is attached to
  133. /// @param inN1 The world space normal in which the constraint operates for body 1
  134. /// @param inN2 The world space normal in which the constraint operates for body 2
  135. /// @param inRatio The ratio how forces are applied between bodies
  136. /// @param inMinLambda Minimum angular impulse to apply (N m s)
  137. /// @param inMaxLambda Maximum angular impulse to apply (N m s)
  138. inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inN1, Vec3Arg inN2, float inRatio, float inMinLambda, float inMaxLambda)
  139. {
  140. // Lagrange multiplier is:
  141. //
  142. // lambda = -K^-1 (J v + b)
  143. float lambda = -mEffectiveMass * (inN1.Dot(ioBody1.GetLinearVelocity()) + mR1xN1.Dot(ioBody1.GetAngularVelocity()) + inRatio * inN2.Dot(ioBody2.GetLinearVelocity()) + mRatioR2xN2.Dot(ioBody2.GetAngularVelocity()));
  144. float new_lambda = Clamp(mTotalLambda + lambda, inMinLambda, inMaxLambda); // Clamp impulse
  145. lambda = new_lambda - mTotalLambda; // Lambda potentially got clamped, calculate the new impulse to apply
  146. mTotalLambda = new_lambda; // Store accumulated impulse
  147. return ApplyVelocityStep(ioBody1, ioBody2, inN1, inN2, inRatio, lambda);
  148. }
  149. /// Return lagrange multiplier
  150. float GetTotalLambda() const
  151. {
  152. return mTotalLambda;
  153. }
  154. /// Iteratively update the position constraint. Makes sure C(...) == 0.
  155. /// @param ioBody1 The first body that this constraint is attached to
  156. /// @param ioBody2 The second body that this constraint is attached to
  157. /// @param inN1 The world space normal in which the constraint operates for body 1
  158. /// @param inN2 The world space normal in which the constraint operates for body 2
  159. /// @param inRatio The ratio how forces are applied between bodies
  160. /// @param inC Value of the constraint equation (C)
  161. /// @param inBaumgarte Baumgarte constant (fraction of the error to correct)
  162. inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inN1, Vec3Arg inN2, float inRatio, float inC, float inBaumgarte) const
  163. {
  164. if (inC != 0.0f)
  165. {
  166. // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
  167. //
  168. // lambda = -K^-1 * beta / dt * C
  169. //
  170. // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
  171. float lambda = -mEffectiveMass * inBaumgarte * inC;
  172. // Directly integrate velocity change for one time step
  173. //
  174. // Euler velocity integration:
  175. // dv = M^-1 P
  176. //
  177. // Impulse:
  178. // P = J^T lambda
  179. //
  180. // Euler position integration:
  181. // x' = x + dv * dt
  182. //
  183. // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
  184. // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
  185. // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
  186. // integrate + a position integrate and then discard the velocity change.
  187. if (ioBody1.IsDynamic())
  188. {
  189. ioBody1.AddPositionStep((lambda * ioBody1.GetMotionPropertiesUnchecked()->GetInverseMass()) * inN1);
  190. ioBody1.AddRotationStep(lambda * mInvI1_R1xN1);
  191. }
  192. if (ioBody2.IsDynamic())
  193. {
  194. ioBody2.AddPositionStep((lambda * inRatio * ioBody2.GetMotionPropertiesUnchecked()->GetInverseMass()) * inN2);
  195. ioBody2.AddRotationStep(lambda * mInvI2_RatioR2xN2);
  196. }
  197. return true;
  198. }
  199. return false;
  200. }
  201. /// Save state of this constraint part
  202. void SaveState(StateRecorder &inStream) const
  203. {
  204. inStream.Write(mTotalLambda);
  205. }
  206. /// Restore state of this constraint part
  207. void RestoreState(StateRecorder &inStream)
  208. {
  209. inStream.Read(mTotalLambda);
  210. }
  211. private:
  212. Vec3 mR1xN1;
  213. Vec3 mInvI1_R1xN1;
  214. Vec3 mRatioR2xN2;
  215. Vec3 mInvI2_RatioR2xN2;
  216. float mEffectiveMass = 0.0f;
  217. float mTotalLambda = 0.0f;
  218. };
  219. JPH_NAMESPACE_END