DualAxisConstraintPart.h 8.9 KB

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