PointConstraintPart.h 7.7 KB

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