PointConstraintPart.h 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 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. /// 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) const
  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. if (!mEffectiveMass.SetInversed3x3(inv_effective_mass))
  113. Deactivate();
  114. }
  115. /// Deactivate this constraint
  116. inline void Deactivate()
  117. {
  118. mEffectiveMass = Mat44::sZero();
  119. mTotalLambda = Vec3::sZero();
  120. }
  121. /// Check if constraint is active
  122. inline bool IsActive() const
  123. {
  124. return mEffectiveMass(3, 3) != 0.0f;
  125. }
  126. /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
  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 inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame
  130. inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
  131. {
  132. mTotalLambda *= inWarmStartImpulseRatio;
  133. ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);
  134. }
  135. /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
  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. inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2)
  139. {
  140. // Calculate lagrange multiplier:
  141. //
  142. // lambda = -K^-1 (J v + b)
  143. Vec3 lambda = mEffectiveMass * (ioBody1.GetLinearVelocity() - mR1.Cross(ioBody1.GetAngularVelocity()) - ioBody2.GetLinearVelocity() + mR2.Cross(ioBody2.GetAngularVelocity()));
  144. mTotalLambda += lambda; // Store accumulated lambda
  145. return ApplyVelocityStep(ioBody1, ioBody2, lambda);
  146. }
  147. /// Iteratively update the position constraint. Makes sure C(...) = 0.
  148. /// @param ioBody1 The first body that this constraint is attached to
  149. /// @param ioBody2 The second body that this constraint is attached to
  150. /// @param inBaumgarte Baumgarte constant (fraction of the error to correct)
  151. inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inBaumgarte) const
  152. {
  153. Vec3 separation = (Vec3(ioBody2.GetCenterOfMassPosition() - ioBody1.GetCenterOfMassPosition()) + mR2 - mR1);
  154. if (separation != Vec3::sZero())
  155. {
  156. // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
  157. //
  158. // lambda = -K^-1 * beta / dt * C
  159. //
  160. // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
  161. Vec3 lambda = mEffectiveMass * -inBaumgarte * separation;
  162. // Directly integrate velocity change for one time step
  163. //
  164. // Euler velocity integration:
  165. // dv = M^-1 P
  166. //
  167. // Impulse:
  168. // P = J^T lambda
  169. //
  170. // Euler position integration:
  171. // x' = x + dv * dt
  172. //
  173. // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
  174. // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
  175. // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
  176. // integrate + a position integrate and then discard the velocity change.
  177. if (ioBody1.IsDynamic())
  178. {
  179. ioBody1.SubPositionStep(ioBody1.GetMotionProperties()->GetInverseMass() * lambda);
  180. ioBody1.SubRotationStep(mInvI1_R1X * lambda);
  181. }
  182. if (ioBody2.IsDynamic())
  183. {
  184. ioBody2.AddPositionStep(ioBody2.GetMotionProperties()->GetInverseMass() * lambda);
  185. ioBody2.AddRotationStep(mInvI2_R2X * lambda);
  186. }
  187. return true;
  188. }
  189. return false;
  190. }
  191. /// Return lagrange multiplier
  192. Vec3 GetTotalLambda() const
  193. {
  194. return mTotalLambda;
  195. }
  196. /// Save state of this constraint part
  197. void SaveState(StateRecorder &inStream) const
  198. {
  199. inStream.Write(mTotalLambda);
  200. }
  201. /// Restore state of this constraint part
  202. void RestoreState(StateRecorder &inStream)
  203. {
  204. inStream.Read(mTotalLambda);
  205. }
  206. private:
  207. Vec3 mR1;
  208. Vec3 mR2;
  209. Mat44 mInvI1_R1X;
  210. Mat44 mInvI2_R2X;
  211. Mat44 mEffectiveMass;
  212. Vec3 mTotalLambda { Vec3::sZero() };
  213. };
  214. JPH_NAMESPACE_END