PointConstraintPart.h 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. // SPDX-FileCopyrightText: 2021 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. /// Constrains movement along 3 axis
  8. ///
  9. /// @see "Constraints Derivation for Rigid Body Simulation in 3D" - Daniel Chappuis, section 2.2.1
  10. ///
  11. /// Constraint equation (eq 45):
  12. ///
  13. /// \f[C = p_2 - p_1\f]
  14. ///
  15. /// Jacobian (transposed) (eq 47):
  16. ///
  17. /// \f[J^T = \begin{bmatrix}-E & r1x & E & -r2x^T\end{bmatrix}
  18. /// = \begin{bmatrix}-E^T \\ r1x^T \\ E^T \\ -r2x^T\end{bmatrix}
  19. /// = \begin{bmatrix}-E \\ -r1x \\ E \\ r2x\end{bmatrix}\f]
  20. ///
  21. /// Used terms (here and below, everything in world space):\n
  22. /// p1, p2 = constraint points.\n
  23. /// r1 = p1 - x1.\n
  24. /// r2 = p2 - x2.\n
  25. /// r1x = 3x3 matrix for which r1x v = r1 x v (cross product).\n
  26. /// x1, x2 = center of mass for the bodies.\n
  27. /// v = [v1, w1, v2, w2].\n
  28. /// v1, v2 = linear velocity of body 1 and 2.\n
  29. /// w1, w2 = angular velocity of body 1 and 2.\n
  30. /// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n
  31. /// \f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n
  32. /// b = velocity bias.\n
  33. /// \f$\beta\f$ = baumgarte constant.\n
  34. /// E = identity matrix.
  35. class PointConstraintPart
  36. {
  37. JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, Vec3Arg inLambda) const
  38. {
  39. // Apply impulse if delta is not zero
  40. if (inLambda != Vec3::sZero())
  41. {
  42. // Calculate velocity change due to constraint
  43. //
  44. // Impulse:
  45. // P = J^T lambda
  46. //
  47. // Euler velocity integration:
  48. // v' = v + M^-1 P
  49. if (ioBody1.IsDynamic())
  50. {
  51. MotionProperties *mp1 = ioBody1.GetMotionProperties();
  52. mp1->SubLinearVelocityStep(mp1->GetInverseMass() * inLambda);
  53. mp1->SubAngularVelocityStep(mInvI1_R1X * inLambda);
  54. }
  55. if (ioBody2.IsDynamic())
  56. {
  57. MotionProperties *mp2 = ioBody2.GetMotionProperties();
  58. mp2->AddLinearVelocityStep(mp2->GetInverseMass() * inLambda);
  59. mp2->AddAngularVelocityStep(mInvI2_R2X * inLambda);
  60. }
  61. return true;
  62. }
  63. return false;
  64. }
  65. public:
  66. /// Calculate properties used during the functions below
  67. /// @param inBody1 The first body that this constraint is attached to
  68. /// @param inBody2 The second body that this constraint is attached to
  69. /// @param inRotation1 The 3x3 rotation matrix for body 1 (translation part is ignored)
  70. /// @param inRotation2 The 3x3 rotation matrix for body 2 (translation part is ignored)
  71. /// @param inR1 Local space vector from center of mass to constraint point for body 1
  72. /// @param inR2 Local space vector from center of mass to constraint point for body 2
  73. inline void CalculateConstraintProperties(const Body &inBody1, Mat44Arg inRotation1, Vec3Arg inR1, const Body &inBody2, Mat44Arg inRotation2, Vec3Arg inR2)
  74. {
  75. // Positions where the point constraint acts on (middle point between center of masses) in world space
  76. mR1 = inRotation1.Multiply3x3(inR1);
  77. mR2 = inRotation2.Multiply3x3(inR2);
  78. // Calculate effective mass: K^-1 = (J M^-1 J^T)^-1
  79. // Using: I^-1 = R * Ibody^-1 * R^T
  80. float summed_inv_mass;
  81. Mat44 inv_effective_mass;
  82. if (inBody1.IsDynamic())
  83. {
  84. const MotionProperties *mp1 = inBody1.GetMotionProperties();
  85. Mat44 invi1 = mp1->GetInverseInertiaForRotation(inRotation1);
  86. summed_inv_mass = mp1->GetInverseMass();
  87. Mat44 r1x = Mat44::sCrossProduct(mR1);
  88. mInvI1_R1X = invi1.Multiply3x3(r1x);
  89. inv_effective_mass = r1x.Multiply3x3(invi1).Multiply3x3RightTransposed(r1x);
  90. }
  91. else
  92. {
  93. JPH_IF_DEBUG(mInvI1_R1X = Mat44::sNaN();)
  94. summed_inv_mass = 0.0f;
  95. inv_effective_mass = Mat44::sZero();
  96. }
  97. if (inBody2.IsDynamic())
  98. {
  99. const MotionProperties *mp2 = inBody2.GetMotionProperties();
  100. Mat44 invi2 = mp2->GetInverseInertiaForRotation(inRotation2);
  101. summed_inv_mass += mp2->GetInverseMass();
  102. Mat44 r2x = Mat44::sCrossProduct(mR2);
  103. mInvI2_R2X = invi2.Multiply3x3(r2x);
  104. inv_effective_mass += r2x.Multiply3x3(invi2).Multiply3x3RightTransposed(r2x);
  105. }
  106. else
  107. {
  108. JPH_IF_DEBUG(mInvI2_R2X = Mat44::sNaN();)
  109. }
  110. inv_effective_mass += Mat44::sScale(summed_inv_mass);
  111. mEffectiveMass = inv_effective_mass.Inversed3x3();
  112. }
  113. /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
  114. /// @param ioBody1 The first body that this constraint is attached to
  115. /// @param ioBody2 The second body that this constraint is attached to
  116. /// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame
  117. inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
  118. {
  119. mTotalLambda *= inWarmStartImpulseRatio;
  120. ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);
  121. }
  122. /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
  123. /// @param ioBody1 The first body that this constraint is attached to
  124. /// @param ioBody2 The second body that this constraint is attached to
  125. inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2)
  126. {
  127. // Calculate lagrange multiplier:
  128. //
  129. // lambda = -K^-1 (J v + b)
  130. Vec3 lambda = mEffectiveMass * (ioBody1.GetLinearVelocity() - mR1.Cross(ioBody1.GetAngularVelocity()) - ioBody2.GetLinearVelocity() + mR2.Cross(ioBody2.GetAngularVelocity()));
  131. mTotalLambda += lambda; // Store accumulated lambda
  132. return ApplyVelocityStep(ioBody1, ioBody2, lambda);
  133. }
  134. /// Iteratively update the position constraint. Makes sure C(...) = 0.
  135. /// @param ioBody1 The first body that this constraint is attached to
  136. /// @param ioBody2 The second body that this constraint is attached to
  137. /// @param inBaumgarte Baumgarte constant (fraction of the error to correct)
  138. inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inBaumgarte) const
  139. {
  140. Vec3 separation = (ioBody2.GetCenterOfMassPosition() + mR2 - ioBody1.GetCenterOfMassPosition() - mR1);
  141. if (separation != Vec3::sZero())
  142. {
  143. // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
  144. //
  145. // lambda = -K^-1 * beta / dt * C
  146. //
  147. // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
  148. Vec3 lambda = mEffectiveMass * -inBaumgarte * separation;
  149. // Directly integrate velocity change for one time step
  150. //
  151. // Euler velocity integration:
  152. // dv = M^-1 P
  153. //
  154. // Impulse:
  155. // P = J^T lambda
  156. //
  157. // Euler position integration:
  158. // x' = x + dv * dt
  159. //
  160. // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
  161. // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
  162. // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
  163. // integrate + a position integrate and then discard the velocity change.
  164. if (ioBody1.IsDynamic())
  165. {
  166. ioBody1.SubPositionStep(ioBody1.GetMotionProperties()->GetInverseMass() * lambda);
  167. ioBody1.SubRotationStep(mInvI1_R1X * lambda);
  168. }
  169. if (ioBody2.IsDynamic())
  170. {
  171. ioBody2.AddPositionStep(ioBody2.GetMotionProperties()->GetInverseMass() * lambda);
  172. ioBody2.AddRotationStep(mInvI2_R2X * lambda);
  173. }
  174. return true;
  175. }
  176. return false;
  177. }
  178. /// Return lagrange multiplier
  179. Vec3 GetTotalLambda() const
  180. {
  181. return mTotalLambda;
  182. }
  183. /// Save state of this constraint part
  184. void SaveState(StateRecorder &inStream) const
  185. {
  186. inStream.Write(mTotalLambda);
  187. }
  188. /// Restore state of this constraint part
  189. void RestoreState(StateRecorder &inStream)
  190. {
  191. inStream.Read(mTotalLambda);
  192. }
  193. private:
  194. Vec3 mR1;
  195. Vec3 mR2;
  196. Mat44 mInvI1_R1X;
  197. Mat44 mInvI2_R2X;
  198. Mat44 mEffectiveMass;
  199. Vec3 mTotalLambda { Vec3::sZero() };
  200. };
  201. JPH_NAMESPACE_END