DualAxisConstraintPart.h 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. #include <Jolt/Math/Vector.h>
  8. #include <Jolt/Math/Matrix.h>
  9. JPH_NAMESPACE_BEGIN
  10. /// Constrains movement on 2 axis
  11. ///
  12. /// @see "Constraints Derivation for Rigid Body Simulation in 3D" - Daniel Chappuis, section 2.3.1
  13. ///
  14. /// Constraint equation (eq 51):
  15. ///
  16. /// \f[C = \begin{bmatrix} (p_2 - p_1) \cdot n_1 \\ (p_2 - p_1) \cdot n_2\end{bmatrix}\f]
  17. ///
  18. /// Jacobian (transposed) (eq 55):
  19. ///
  20. /// \f[J^T = \begin{bmatrix}
  21. /// -n_1 & -n_2 \\
  22. /// -(r_1 + u) \times n_1 & -(r_1 + u) \times n_2 \\
  23. /// n_1 & n_2 \\
  24. /// r_2 \times n_1 & r_2 \times n_2
  25. /// \end{bmatrix}\f]
  26. ///
  27. /// Used terms (here and below, everything in world space):\n
  28. /// n1, n2 = constraint axis (normalized).\n
  29. /// p1, p2 = constraint points.\n
  30. /// r1 = p1 - x1.\n
  31. /// r2 = p2 - x2.\n
  32. /// u = x2 + r2 - x1 - r1 = p2 - p1.\n
  33. /// x1, x2 = center of mass for the bodies.\n
  34. /// v = [v1, w1, v2, w2].\n
  35. /// v1, v2 = linear velocity of body 1 and 2.\n
  36. /// w1, w2 = angular velocity of body 1 and 2.\n
  37. /// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n
  38. /// \f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n
  39. /// b = velocity bias.\n
  40. /// \f$\beta\f$ = baumgarte constant.
  41. class DualAxisConstraintPart
  42. {
  43. public:
  44. using Vec2 = Vector<2>;
  45. using Mat22 = Matrix<2, 2>;
  46. private:
  47. /// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated
  48. JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, Vec3Arg inN1, Vec3Arg inN2, const Vec2 &inLambda) const
  49. {
  50. // Apply impulse if delta is not zero
  51. if (!inLambda.IsZero())
  52. {
  53. // Calculate velocity change due to constraint
  54. //
  55. // Impulse:
  56. // P = J^T lambda
  57. //
  58. // Euler velocity integration:
  59. // v' = v + M^-1 P
  60. Vec3 impulse = inN1 * inLambda[0] + inN2 * inLambda[1];
  61. if (ioBody1.IsDynamic())
  62. {
  63. MotionProperties *mp1 = ioBody1.GetMotionProperties();
  64. mp1->SubLinearVelocityStep(mp1->GetInverseMass() * impulse);
  65. mp1->SubAngularVelocityStep(mInvI1_R1PlusUxN1 * inLambda[0] + mInvI1_R1PlusUxN2 * inLambda[1]);
  66. }
  67. if (ioBody2.IsDynamic())
  68. {
  69. MotionProperties *mp2 = ioBody2.GetMotionProperties();
  70. mp2->AddLinearVelocityStep(mp2->GetInverseMass() * impulse);
  71. mp2->AddAngularVelocityStep(mInvI2_R2xN1 * inLambda[0] + mInvI2_R2xN2 * inLambda[1]);
  72. }
  73. return true;
  74. }
  75. return false;
  76. }
  77. /// Internal helper function to calculate the lagrange multiplier
  78. inline void CalculateLagrangeMultiplier(const Body &inBody1, const Body &inBody2, Vec3Arg inN1, Vec3Arg inN2, Vec2 &outLambda) const
  79. {
  80. // Calculate lagrange multiplier:
  81. //
  82. // lambda = -K^-1 (J v + b)
  83. Vec3 delta_lin = inBody1.GetLinearVelocity() - inBody2.GetLinearVelocity();
  84. Vec2 jv;
  85. jv[0] = inN1.Dot(delta_lin) + mR1PlusUxN1.Dot(inBody1.GetAngularVelocity()) - mR2xN1.Dot(inBody2.GetAngularVelocity());
  86. jv[1] = inN2.Dot(delta_lin) + mR1PlusUxN2.Dot(inBody1.GetAngularVelocity()) - mR2xN2.Dot(inBody2.GetAngularVelocity());
  87. outLambda = mEffectiveMass * jv;
  88. }
  89. public:
  90. /// Calculate properties used during the functions below
  91. /// All input vectors are in world space
  92. inline void CalculateConstraintProperties(const Body &inBody1, Mat44Arg inRotation1, Vec3Arg inR1PlusU, const Body &inBody2, Mat44Arg inRotation2, Vec3Arg inR2, Vec3Arg inN1, Vec3Arg inN2)
  93. {
  94. JPH_ASSERT(inN1.IsNormalized(1.0e-5f));
  95. JPH_ASSERT(inN2.IsNormalized(1.0e-5f));
  96. // Calculate properties used during constraint solving
  97. mR1PlusUxN1 = inR1PlusU.Cross(inN1);
  98. mR1PlusUxN2 = inR1PlusU.Cross(inN2);
  99. mR2xN1 = inR2.Cross(inN1);
  100. mR2xN2 = inR2.Cross(inN2);
  101. // Calculate effective mass: K^-1 = (J M^-1 J^T)^-1, eq 59
  102. Mat22 inv_effective_mass;
  103. if (inBody1.IsDynamic())
  104. {
  105. const MotionProperties *mp1 = inBody1.GetMotionProperties();
  106. Mat44 inv_i1 = mp1->GetInverseInertiaForRotation(inRotation1);
  107. mInvI1_R1PlusUxN1 = inv_i1.Multiply3x3(mR1PlusUxN1);
  108. mInvI1_R1PlusUxN2 = inv_i1.Multiply3x3(mR1PlusUxN2);
  109. inv_effective_mass(0, 0) = mp1->GetInverseMass() + mR1PlusUxN1.Dot(mInvI1_R1PlusUxN1);
  110. inv_effective_mass(0, 1) = mR1PlusUxN1.Dot(mInvI1_R1PlusUxN2);
  111. inv_effective_mass(1, 0) = mR1PlusUxN2.Dot(mInvI1_R1PlusUxN1);
  112. inv_effective_mass(1, 1) = mp1->GetInverseMass() + mR1PlusUxN2.Dot(mInvI1_R1PlusUxN2);
  113. }
  114. else
  115. {
  116. JPH_IF_DEBUG(mInvI1_R1PlusUxN1 = Vec3::sNaN();)
  117. JPH_IF_DEBUG(mInvI1_R1PlusUxN2 = Vec3::sNaN();)
  118. inv_effective_mass = Mat22::sZero();
  119. }
  120. if (inBody2.IsDynamic())
  121. {
  122. const MotionProperties *mp2 = inBody2.GetMotionProperties();
  123. Mat44 inv_i2 = mp2->GetInverseInertiaForRotation(inRotation2);
  124. mInvI2_R2xN1 = inv_i2.Multiply3x3(mR2xN1);
  125. mInvI2_R2xN2 = inv_i2.Multiply3x3(mR2xN2);
  126. inv_effective_mass(0, 0) += mp2->GetInverseMass() + mR2xN1.Dot(mInvI2_R2xN1);
  127. inv_effective_mass(0, 1) += mR2xN1.Dot(mInvI2_R2xN2);
  128. inv_effective_mass(1, 0) += mR2xN2.Dot(mInvI2_R2xN1);
  129. inv_effective_mass(1, 1) += mp2->GetInverseMass() + mR2xN2.Dot(mInvI2_R2xN2);
  130. }
  131. else
  132. {
  133. JPH_IF_DEBUG(mInvI2_R2xN1 = Vec3::sNaN();)
  134. JPH_IF_DEBUG(mInvI2_R2xN2 = Vec3::sNaN();)
  135. }
  136. if (!mEffectiveMass.SetInversed(inv_effective_mass))
  137. Deactivate();
  138. }
  139. /// Deactivate this constraint
  140. inline void Deactivate()
  141. {
  142. mEffectiveMass.SetZero();
  143. mTotalLambda.SetZero();
  144. }
  145. /// Check if constraint is active
  146. inline bool IsActive() const
  147. {
  148. return !mEffectiveMass.IsZero();
  149. }
  150. /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
  151. /// All input vectors are in world space
  152. inline void WarmStart(Body &ioBody1, Body &ioBody2, Vec3Arg inN1, Vec3Arg inN2, float inWarmStartImpulseRatio)
  153. {
  154. mTotalLambda *= inWarmStartImpulseRatio;
  155. ApplyVelocityStep(ioBody1, ioBody2, inN1, inN2, mTotalLambda);
  156. }
  157. /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
  158. /// All input vectors are in world space
  159. inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inN1, Vec3Arg inN2)
  160. {
  161. Vec2 lambda;
  162. CalculateLagrangeMultiplier(ioBody1, ioBody2, inN1, inN2, lambda);
  163. // Store accumulated lambda
  164. mTotalLambda += lambda;
  165. return ApplyVelocityStep(ioBody1, ioBody2, inN1, inN2, lambda);
  166. }
  167. /// Iteratively update the position constraint. Makes sure C(...) = 0.
  168. /// All input vectors are in world space
  169. inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inU, Vec3Arg inN1, Vec3Arg inN2, float inBaumgarte) const
  170. {
  171. Vec2 c;
  172. c[0] = inU.Dot(inN1);
  173. c[1] = inU.Dot(inN2);
  174. if (!c.IsZero())
  175. {
  176. // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
  177. //
  178. // lambda = -K^-1 * beta / dt * C
  179. //
  180. // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
  181. Vec2 lambda = -inBaumgarte * (mEffectiveMass * c);
  182. // Directly integrate velocity change for one time step
  183. //
  184. // Euler velocity integration:
  185. // dv = M^-1 P
  186. //
  187. // Impulse:
  188. // P = J^T lambda
  189. //
  190. // Euler position integration:
  191. // x' = x + dv * dt
  192. //
  193. // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
  194. // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
  195. // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
  196. // integrate + a position integrate and then discard the velocity change.
  197. Vec3 impulse = inN1 * lambda[0] + inN2 * lambda[1];
  198. if (ioBody1.IsDynamic())
  199. {
  200. ioBody1.SubPositionStep(ioBody1.GetMotionProperties()->GetInverseMass() * impulse);
  201. ioBody1.SubRotationStep(mInvI1_R1PlusUxN1 * lambda[0] + mInvI1_R1PlusUxN2 * lambda[1]);
  202. }
  203. if (ioBody2.IsDynamic())
  204. {
  205. ioBody2.AddPositionStep(ioBody2.GetMotionProperties()->GetInverseMass() * impulse);
  206. ioBody2.AddRotationStep(mInvI2_R2xN1 * lambda[0] + mInvI2_R2xN2 * lambda[1]);
  207. }
  208. return true;
  209. }
  210. return false;
  211. }
  212. /// Override total lagrange multiplier, can be used to set the initial value for warm starting
  213. inline void SetTotalLambda(const Vec2 &inLambda)
  214. {
  215. mTotalLambda = inLambda;
  216. }
  217. /// Return lagrange multiplier
  218. inline const Vec2 & GetTotalLambda() const
  219. {
  220. return mTotalLambda;
  221. }
  222. /// Save state of this constraint part
  223. void SaveState(StateRecorder &inStream) const
  224. {
  225. inStream.Write(mTotalLambda);
  226. }
  227. /// Restore state of this constraint part
  228. void RestoreState(StateRecorder &inStream)
  229. {
  230. inStream.Read(mTotalLambda);
  231. }
  232. private:
  233. Vec3 mR1PlusUxN1;
  234. Vec3 mR1PlusUxN2;
  235. Vec3 mR2xN1;
  236. Vec3 mR2xN2;
  237. Vec3 mInvI1_R1PlusUxN1;
  238. Vec3 mInvI1_R1PlusUxN2;
  239. Vec3 mInvI2_R2xN1;
  240. Vec3 mInvI2_R2xN2;
  241. Mat22 mEffectiveMass;
  242. Vec2 mTotalLambda { Vec2::sZero() };
  243. };
  244. JPH_NAMESPACE_END