RotationEulerConstraintPart.h 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/Physics/PhysicsSettings.h>
  5. #include <Jolt/Physics/Body/Body.h>
  6. #include <Jolt/Physics/StateRecorder.h>
  7. JPH_NAMESPACE_BEGIN
  8. /// Constrains rotation around all axis so that only translation is allowed
  9. ///
  10. /// Based on: "Constraints Derivation for Rigid Body Simulation in 3D" - Daniel Chappuis, section 2.5.1
  11. ///
  12. /// Constraint equation (eq 129):
  13. ///
  14. /// \f[C = \begin{bmatrix}\Delta\theta_x, \Delta\theta_y, \Delta\theta_z\end{bmatrix}\f]
  15. ///
  16. /// Jacobian (eq 131):
  17. ///
  18. /// \f[J = \begin{bmatrix}0 & -E & 0 & E\end{bmatrix}\f]
  19. ///
  20. /// Used terms (here and below, everything in world space):\n
  21. /// delta_theta_* = difference in rotation between initial rotation of bodyies 1 and 2.\n
  22. /// x1, x2 = center of mass for the bodies.\n
  23. /// v = [v1, w1, v2, w2].\n
  24. /// v1, v2 = linear velocity of body 1 and 2.\n
  25. /// w1, w2 = angular velocity of body 1 and 2.\n
  26. /// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n
  27. /// \f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n
  28. /// b = velocity bias.\n
  29. /// \f$\beta\f$ = baumgarte constant.\n
  30. /// E = identity matrix.\n
  31. class RotationEulerConstraintPart
  32. {
  33. private:
  34. /// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated
  35. JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, Vec3Arg inLambda) const
  36. {
  37. // Apply impulse if delta is not zero
  38. if (inLambda != Vec3::sZero())
  39. {
  40. // Calculate velocity change due to constraint
  41. //
  42. // Impulse:
  43. // P = J^T lambda
  44. //
  45. // Euler velocity integration:
  46. // v' = v + M^-1 P
  47. if (ioBody1.IsDynamic())
  48. ioBody1.GetMotionProperties()->SubAngularVelocityStep(mInvI1.Multiply3x3(inLambda));
  49. if (ioBody2.IsDynamic())
  50. ioBody2.GetMotionProperties()->AddAngularVelocityStep(mInvI2.Multiply3x3(inLambda));
  51. return true;
  52. }
  53. return false;
  54. }
  55. public:
  56. /// Return inverse of initial rotation from body 1 to body 2 in body 1 space
  57. static Quat sGetInvInitialOrientation(const Body &inBody1, const Body &inBody2)
  58. {
  59. // q20 = q10 r0
  60. // <=> r0 = q10^-1 q20
  61. // <=> r0^-1 = q20^-1 q10
  62. //
  63. // where:
  64. //
  65. // q20 = initial orientation of body 2
  66. // q10 = initial orientation of body 1
  67. // r0 = initial rotation rotation from body 1 to body 2
  68. return inBody2.GetRotation().Conjugated() * inBody1.GetRotation();
  69. }
  70. /// Calculate properties used during the functions below
  71. inline void CalculateConstraintProperties(const Body &inBody1, Mat44Arg inRotation1, const Body &inBody2, Mat44Arg inRotation2)
  72. {
  73. // Calculate properties used during constraint solving
  74. mInvI1 = inBody1.IsDynamic()? inBody1.GetMotionProperties()->GetInverseInertiaForRotation(inRotation1) : Mat44::sZero();
  75. mInvI2 = inBody2.IsDynamic()? inBody2.GetMotionProperties()->GetInverseInertiaForRotation(inRotation2) : Mat44::sZero();
  76. // Calculate effective mass: K^-1 = (J M^-1 J^T)^-1
  77. mEffectiveMass = (mInvI1 + mInvI2).Inversed3x3();
  78. }
  79. /// Deactivate this constraint
  80. inline void Deactivate()
  81. {
  82. mEffectiveMass(3, 3) = 0.0f;
  83. mTotalLambda = Vec3::sZero();
  84. }
  85. /// Check if constraint is active
  86. inline bool IsActive() const
  87. {
  88. return mEffectiveMass(3, 3) != 0.0f;
  89. }
  90. /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
  91. inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
  92. {
  93. mTotalLambda *= inWarmStartImpulseRatio;
  94. ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);
  95. }
  96. /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
  97. inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2)
  98. {
  99. // Calculate lagrange multiplier:
  100. //
  101. // lambda = -K^-1 (J v + b)
  102. Vec3 lambda = mEffectiveMass.Multiply3x3(ioBody1.GetAngularVelocity() - ioBody2.GetAngularVelocity());
  103. mTotalLambda += lambda;
  104. return ApplyVelocityStep(ioBody1, ioBody2, lambda);
  105. }
  106. /// Iteratively update the position constraint. Makes sure C(...) = 0.
  107. inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, QuatArg inInvInitialOrientation, float inBaumgarte) const
  108. {
  109. // Calculate difference in rotation
  110. //
  111. // The rotation should be:
  112. //
  113. // q2 = q1 r0
  114. //
  115. // But because of drift the actual rotation is
  116. //
  117. // q2 = diff q1 r0
  118. // <=> diff = q2 r0^-1 q1^-1
  119. //
  120. // Where:
  121. // q1 = current rotation of body 1
  122. // q2 = current rotation of body 2
  123. // diff = error that needs to be reduced to zero
  124. Quat diff = ioBody2.GetRotation() * inInvInitialOrientation * ioBody1.GetRotation().Conjugated();
  125. // A quaternion can be seen as:
  126. //
  127. // q = [sin(theta / 2) * v, cos(theta/2)]
  128. //
  129. // Where:
  130. // v = rotation vector
  131. // theta = rotation angle
  132. //
  133. // If we assume theta is small (error is small) then sin(x) = x so an approximation of the error angles is:
  134. Vec3 error = 2.0f * diff.EnsureWPositive().GetXYZ();
  135. if (error != Vec3::sZero())
  136. {
  137. // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
  138. //
  139. // lambda = -K^-1 * beta / dt * C
  140. //
  141. // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
  142. Vec3 lambda = -inBaumgarte * mEffectiveMass * error;
  143. // Directly integrate velocity change for one time step
  144. //
  145. // Euler velocity integration:
  146. // dv = M^-1 P
  147. //
  148. // Impulse:
  149. // P = J^T lambda
  150. //
  151. // Euler position integration:
  152. // x' = x + dv * dt
  153. //
  154. // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
  155. // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
  156. // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
  157. // integrate + a position integrate and then discard the velocity change.
  158. if (ioBody1.IsDynamic())
  159. ioBody1.SubRotationStep(mInvI1.Multiply3x3(lambda));
  160. if (ioBody2.IsDynamic())
  161. ioBody2.AddRotationStep(mInvI2.Multiply3x3(lambda));
  162. return true;
  163. }
  164. return false;
  165. }
  166. /// Return lagrange multiplier
  167. Vec3 GetTotalLambda() const
  168. {
  169. return mTotalLambda;
  170. }
  171. /// Save state of this constraint part
  172. void SaveState(StateRecorder &inStream) const
  173. {
  174. inStream.Write(mTotalLambda);
  175. }
  176. /// Restore state of this constraint part
  177. void RestoreState(StateRecorder &inStream)
  178. {
  179. inStream.Read(mTotalLambda);
  180. }
  181. private:
  182. Mat44 mInvI1;
  183. Mat44 mInvI2;
  184. Mat44 mEffectiveMass;
  185. Vec3 mTotalLambda { Vec3::sZero() };
  186. };
  187. JPH_NAMESPACE_END