RotationEulerConstraintPart.h 8.8 KB

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