HingeRotationConstraintPart.h 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. #include <Jolt/Math/Vector.h>
  7. #include <Jolt/Math/Matrix.h>
  8. JPH_NAMESPACE_BEGIN
  9. /// Constrains rotation around 2 axis so that it only allows rotation around 1 axis
  10. ///
  11. /// Based on: "Constraints Derivation for Rigid Body Simulation in 3D" - Daniel Chappuis, section 2.4.1
  12. ///
  13. /// Constraint equation (eq 87):
  14. ///
  15. /// \f[C = \begin{bmatrix}a_1 \cdot b_2 \\ a_1 \cdot c_2\end{bmatrix}\f]
  16. ///
  17. /// Jacobian (eq 90):
  18. ///
  19. /// \f[J = \begin{bmatrix}
  20. /// 0 & -b_2 \times a_1 & 0 & b_2 \times a_1 \\
  21. /// 0 & -c_2 \times a_1 & 0 & c2 \times a_1
  22. /// \end{bmatrix}\f]
  23. ///
  24. /// Used terms (here and below, everything in world space):\n
  25. /// a1 = hinge axis on body 1.\n
  26. /// b2, c2 = axis perpendicular to hinge axis on body 2.\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 HingeRotationConstraintPart
  37. {
  38. public:
  39. using Vec2 = Vector<2>;
  40. using Mat22 = Matrix<2, 2>;
  41. private:
  42. /// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated
  43. JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, const Vec2 &inLambda) const
  44. {
  45. // Apply impulse if delta is not zero
  46. if (!inLambda.IsZero())
  47. {
  48. // Calculate velocity change due to constraint
  49. //
  50. // Impulse:
  51. // P = J^T lambda
  52. //
  53. // Euler velocity integration:
  54. // v' = v + M^-1 P
  55. Vec3 impulse = mB2xA1 * inLambda[0] + mC2xA1 * inLambda[1];
  56. if (ioBody1.IsDynamic())
  57. ioBody1.GetMotionProperties()->SubAngularVelocityStep(mInvI1.Multiply3x3(impulse));
  58. if (ioBody2.IsDynamic())
  59. ioBody2.GetMotionProperties()->AddAngularVelocityStep(mInvI2.Multiply3x3(impulse));
  60. return true;
  61. }
  62. return false;
  63. }
  64. public:
  65. /// Calculate properties used during the functions below
  66. inline void CalculateConstraintProperties(const Body &inBody1, Mat44Arg inRotation1, Vec3Arg inWorldSpaceHingeAxis1, const Body &inBody2, Mat44Arg inRotation2, Vec3Arg inWorldSpaceHingeAxis2)
  67. {
  68. JPH_ASSERT(inWorldSpaceHingeAxis1.IsNormalized(1.0e-5f));
  69. JPH_ASSERT(inWorldSpaceHingeAxis2.IsNormalized(1.0e-5f));
  70. // Calculate hinge axis in world space
  71. mA1 = inWorldSpaceHingeAxis1;
  72. Vec3 a2 = inWorldSpaceHingeAxis2;
  73. float dot = mA1.Dot(a2);
  74. if (dot <= 1.0e-3f)
  75. {
  76. // World space axes are more than 90 degrees apart, get a perpendicular vector in the plane formed by mA1 and a2 as hinge axis until the rotation is less than 90 degrees
  77. Vec3 perp = a2 - dot * mA1;
  78. if (perp.LengthSq() < 1.0e-6f)
  79. {
  80. // mA1 ~ -a2, take random perpendicular
  81. perp = mA1.GetNormalizedPerpendicular();
  82. }
  83. // Blend in a little bit from mA1 so we're less than 90 degrees apart
  84. a2 = (0.99f * perp.Normalized() + 0.01f * mA1).Normalized();
  85. }
  86. mB2 = a2.GetNormalizedPerpendicular();
  87. mC2 = a2.Cross(mB2);
  88. // Calculate properties used during constraint solving
  89. mInvI1 = inBody1.IsDynamic()? inBody1.GetMotionProperties()->GetInverseInertiaForRotation(inRotation1) : Mat44::sZero();
  90. mInvI2 = inBody2.IsDynamic()? inBody2.GetMotionProperties()->GetInverseInertiaForRotation(inRotation2) : Mat44::sZero();
  91. mB2xA1 = mB2.Cross(mA1);
  92. mC2xA1 = mC2.Cross(mA1);
  93. // Calculate effective mass: K^-1 = (J M^-1 J^T)^-1
  94. Mat44 summed_inv_inertia = mInvI1 + mInvI2;
  95. Mat22 inv_effective_mass;
  96. inv_effective_mass(0, 0) = mB2xA1.Dot(summed_inv_inertia.Multiply3x3(mB2xA1));
  97. inv_effective_mass(0, 1) = mB2xA1.Dot(summed_inv_inertia.Multiply3x3(mC2xA1));
  98. inv_effective_mass(1, 0) = mC2xA1.Dot(summed_inv_inertia.Multiply3x3(mB2xA1));
  99. inv_effective_mass(1, 1) = mC2xA1.Dot(summed_inv_inertia.Multiply3x3(mC2xA1));
  100. if (!mEffectiveMass.SetInversed(inv_effective_mass))
  101. {
  102. JPH_ASSERT(false, "Determinant is zero!");
  103. Deactivate();
  104. }
  105. }
  106. /// Deactivate this constraint
  107. inline void Deactivate()
  108. {
  109. mEffectiveMass.SetZero();
  110. mTotalLambda.SetZero();
  111. }
  112. /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
  113. inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
  114. {
  115. mTotalLambda *= inWarmStartImpulseRatio;
  116. ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);
  117. }
  118. /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
  119. inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2)
  120. {
  121. // Calculate lagrange multiplier:
  122. //
  123. // lambda = -K^-1 (J v + b)
  124. Vec3 delta_ang = ioBody1.GetAngularVelocity() - ioBody2.GetAngularVelocity();
  125. Vec2 jv;
  126. jv[0] = mB2xA1.Dot(delta_ang);
  127. jv[1] = mC2xA1.Dot(delta_ang);
  128. Vec2 lambda = mEffectiveMass * jv;
  129. // Store accumulated lambda
  130. mTotalLambda += lambda;
  131. return ApplyVelocityStep(ioBody1, ioBody2, lambda);
  132. }
  133. /// Iteratively update the position constraint. Makes sure C(...) = 0.
  134. inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inBaumgarte) const
  135. {
  136. // Constraint needs Axis of body 1 perpendicular to both B and C from body 2 (which are both perpendicular to the Axis of body 2)
  137. Vec2 c;
  138. c[0] = mA1.Dot(mB2);
  139. c[1] = mA1.Dot(mC2);
  140. if (!c.IsZero())
  141. {
  142. // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
  143. //
  144. // lambda = -K^-1 * beta / dt * C
  145. //
  146. // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
  147. Vec2 lambda = -inBaumgarte * (mEffectiveMass * c);
  148. // Directly integrate velocity change for one time step
  149. //
  150. // Euler velocity integration:
  151. // dv = M^-1 P
  152. //
  153. // Impulse:
  154. // P = J^T lambda
  155. //
  156. // Euler position integration:
  157. // x' = x + dv * dt
  158. //
  159. // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
  160. // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
  161. // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
  162. // integrate + a position integrate and then discard the velocity change.
  163. Vec3 impulse = mB2xA1 * lambda[0] + mC2xA1 * lambda[1];
  164. if (ioBody1.IsDynamic())
  165. ioBody1.SubRotationStep(mInvI1.Multiply3x3(impulse));
  166. if (ioBody2.IsDynamic())
  167. ioBody2.AddRotationStep(mInvI2.Multiply3x3(impulse));
  168. return true;
  169. }
  170. return false;
  171. }
  172. /// Return lagrange multiplier
  173. const Vec2 & GetTotalLambda() const
  174. {
  175. return mTotalLambda;
  176. }
  177. /// Save state of this constraint part
  178. void SaveState(StateRecorder &inStream) const
  179. {
  180. inStream.Write(mTotalLambda);
  181. }
  182. /// Restore state of this constraint part
  183. void RestoreState(StateRecorder &inStream)
  184. {
  185. inStream.Read(mTotalLambda);
  186. }
  187. private:
  188. Vec3 mA1; ///< World space hinge axis for body 1
  189. Vec3 mB2; ///< World space perpendiculars of hinge axis for body 2
  190. Vec3 mC2;
  191. Mat44 mInvI1;
  192. Mat44 mInvI2;
  193. Vec3 mB2xA1;
  194. Vec3 mC2xA1;
  195. Mat22 mEffectiveMass;
  196. Vec2 mTotalLambda { Vec2::sZero() };
  197. };
  198. JPH_NAMESPACE_END