IndependentAxisConstraintPart.h 9.5 KB

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