RotationEulerConstraintPart.h 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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. 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. /// @brief Return inverse of initial rotation from body 1 to body 2 in body 1 space
  71. /// @param inAxisX1 Reference axis X for body 1
  72. /// @param inAxisY1 Reference axis Y for body 1
  73. /// @param inAxisX2 Reference axis X for body 2
  74. /// @param inAxisY2 Reference axis Y for body 2
  75. static Quat sGetInvInitialOrientationXY(Vec3Arg inAxisX1, Vec3Arg inAxisY1, Vec3Arg inAxisX2, Vec3Arg inAxisY2)
  76. {
  77. // Store inverse of initial rotation from body 1 to body 2 in body 1 space:
  78. //
  79. // q20 = q10 r0
  80. // <=> r0 = q10^-1 q20
  81. // <=> r0^-1 = q20^-1 q10
  82. //
  83. // where:
  84. //
  85. // q10, q20 = world space initial orientation of body 1 and 2
  86. // r0 = initial rotation rotation from body 1 to body 2 in local space of body 1
  87. //
  88. // We can also write this in terms of the constraint matrices:
  89. //
  90. // q20 c2 = q10 c1
  91. // <=> q20 = q10 c1 c2^-1
  92. // => r0 = c1 c2^-1
  93. // <=> r0^-1 = c2 c1^-1
  94. //
  95. // where:
  96. //
  97. // c1, c2 = matrix that takes us from body 1 and 2 COM to constraint space 1 and 2
  98. if (inAxisX1 == inAxisX2 && inAxisY1 == inAxisY2)
  99. {
  100. // Axis are the same -> identity transform
  101. return Quat::sIdentity();
  102. }
  103. else
  104. {
  105. Mat44 constraint1(Vec4(inAxisX1, 0), Vec4(inAxisY1, 0), Vec4(inAxisX1.Cross(inAxisY1), 0), Vec4(0, 0, 0, 1));
  106. Mat44 constraint2(Vec4(inAxisX2, 0), Vec4(inAxisY2, 0), Vec4(inAxisX2.Cross(inAxisY2), 0), Vec4(0, 0, 0, 1));
  107. return constraint2.GetQuaternion() * constraint1.GetQuaternion().Conjugated();
  108. }
  109. }
  110. /// @brief Return inverse of initial rotation from body 1 to body 2 in body 1 space
  111. /// @param inAxisX1 Reference axis X for body 1
  112. /// @param inAxisZ1 Reference axis Z for body 1
  113. /// @param inAxisX2 Reference axis X for body 2
  114. /// @param inAxisZ2 Reference axis Z for body 2
  115. static Quat sGetInvInitialOrientationXZ(Vec3Arg inAxisX1, Vec3Arg inAxisZ1, Vec3Arg inAxisX2, Vec3Arg inAxisZ2)
  116. {
  117. // See comment at sGetInvInitialOrientationXY
  118. if (inAxisX1 == inAxisX2 && inAxisZ1 == inAxisZ2)
  119. {
  120. return Quat::sIdentity();
  121. }
  122. else
  123. {
  124. Mat44 constraint1(Vec4(inAxisX1, 0), Vec4(inAxisZ1.Cross(inAxisX1), 0), Vec4(inAxisZ1, 0), Vec4(0, 0, 0, 1));
  125. Mat44 constraint2(Vec4(inAxisX2, 0), Vec4(inAxisZ2.Cross(inAxisX2), 0), Vec4(inAxisZ2, 0), Vec4(0, 0, 0, 1));
  126. return constraint2.GetQuaternion() * constraint1.GetQuaternion().Conjugated();
  127. }
  128. }
  129. /// Calculate properties used during the functions below
  130. inline void CalculateConstraintProperties(const Body &inBody1, Mat44Arg inRotation1, const Body &inBody2, Mat44Arg inRotation2)
  131. {
  132. // Calculate properties used during constraint solving
  133. mInvI1 = inBody1.IsDynamic()? inBody1.GetMotionProperties()->GetInverseInertiaForRotation(inRotation1) : Mat44::sZero();
  134. mInvI2 = inBody2.IsDynamic()? inBody2.GetMotionProperties()->GetInverseInertiaForRotation(inRotation2) : Mat44::sZero();
  135. // Calculate effective mass: K^-1 = (J M^-1 J^T)^-1
  136. mEffectiveMass = (mInvI1 + mInvI2).Inversed3x3();
  137. }
  138. /// Deactivate this constraint
  139. inline void Deactivate()
  140. {
  141. mEffectiveMass(3, 3) = 0.0f;
  142. mTotalLambda = Vec3::sZero();
  143. }
  144. /// Check if constraint is active
  145. inline bool IsActive() const
  146. {
  147. return mEffectiveMass(3, 3) != 0.0f;
  148. }
  149. /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
  150. inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
  151. {
  152. mTotalLambda *= inWarmStartImpulseRatio;
  153. ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);
  154. }
  155. /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
  156. inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2)
  157. {
  158. // Calculate lagrange multiplier:
  159. //
  160. // lambda = -K^-1 (J v + b)
  161. Vec3 lambda = mEffectiveMass.Multiply3x3(ioBody1.GetAngularVelocity() - ioBody2.GetAngularVelocity());
  162. mTotalLambda += lambda;
  163. return ApplyVelocityStep(ioBody1, ioBody2, lambda);
  164. }
  165. /// Iteratively update the position constraint. Makes sure C(...) = 0.
  166. inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, QuatArg inInvInitialOrientation, float inBaumgarte) const
  167. {
  168. // Calculate difference in rotation
  169. //
  170. // The rotation should be:
  171. //
  172. // q2 = q1 r0
  173. //
  174. // But because of drift the actual rotation is
  175. //
  176. // q2 = diff q1 r0
  177. // <=> diff = q2 r0^-1 q1^-1
  178. //
  179. // Where:
  180. // q1 = current rotation of body 1
  181. // q2 = current rotation of body 2
  182. // diff = error that needs to be reduced to zero
  183. Quat diff = ioBody2.GetRotation() * inInvInitialOrientation * ioBody1.GetRotation().Conjugated();
  184. // A quaternion can be seen as:
  185. //
  186. // q = [sin(theta / 2) * v, cos(theta/2)]
  187. //
  188. // Where:
  189. // v = rotation vector
  190. // theta = rotation angle
  191. //
  192. // If we assume theta is small (error is small) then sin(x) = x so an approximation of the error angles is:
  193. Vec3 error = 2.0f * diff.EnsureWPositive().GetXYZ();
  194. if (error != Vec3::sZero())
  195. {
  196. // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
  197. //
  198. // lambda = -K^-1 * beta / dt * C
  199. //
  200. // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
  201. Vec3 lambda = -inBaumgarte * mEffectiveMass * error;
  202. // Directly integrate velocity change for one time step
  203. //
  204. // Euler velocity integration:
  205. // dv = M^-1 P
  206. //
  207. // Impulse:
  208. // P = J^T lambda
  209. //
  210. // Euler position integration:
  211. // x' = x + dv * dt
  212. //
  213. // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
  214. // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
  215. // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
  216. // integrate + a position integrate and then discard the velocity change.
  217. if (ioBody1.IsDynamic())
  218. ioBody1.SubRotationStep(mInvI1.Multiply3x3(lambda));
  219. if (ioBody2.IsDynamic())
  220. ioBody2.AddRotationStep(mInvI2.Multiply3x3(lambda));
  221. return true;
  222. }
  223. return false;
  224. }
  225. /// Return lagrange multiplier
  226. Vec3 GetTotalLambda() const
  227. {
  228. return mTotalLambda;
  229. }
  230. /// Save state of this constraint part
  231. void SaveState(StateRecorder &inStream) const
  232. {
  233. inStream.Write(mTotalLambda);
  234. }
  235. /// Restore state of this constraint part
  236. void RestoreState(StateRecorder &inStream)
  237. {
  238. inStream.Read(mTotalLambda);
  239. }
  240. private:
  241. Mat44 mInvI1;
  242. Mat44 mInvI2;
  243. Mat44 mEffectiveMass;
  244. Vec3 mTotalLambda { Vec3::sZero() };
  245. };
  246. JPH_NAMESPACE_END