RotationEulerConstraintPart.h 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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 bodies 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 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 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. Mat44 inertia_sum = mInvI1 + mInvI2;
  137. if (!mEffectiveMass.SetInversed3x3(inertia_sum))
  138. {
  139. // If a column is zero, the axis is locked and we set the column to identity.
  140. // This does not matter because any impulse will always be multiplied with mInvI1 or mInvI2 which will result in zero for the locked coordinate.
  141. Vec4 zero = Vec4::sZero();
  142. if (inertia_sum.GetColumn4(0) == zero)
  143. inertia_sum.SetColumn4(0, Vec4(1, 0, 0, 0));
  144. if (inertia_sum.GetColumn4(1) == zero)
  145. inertia_sum.SetColumn4(1, Vec4(0, 1, 0, 0));
  146. if (inertia_sum.GetColumn4(2) == zero)
  147. inertia_sum.SetColumn4(2, Vec4(0, 0, 1, 0));
  148. if (!mEffectiveMass.SetInversed3x3(inertia_sum))
  149. Deactivate();
  150. }
  151. }
  152. /// Deactivate this constraint
  153. inline void Deactivate()
  154. {
  155. mEffectiveMass = Mat44::sZero();
  156. mTotalLambda = Vec3::sZero();
  157. }
  158. /// Check if constraint is active
  159. inline bool IsActive() const
  160. {
  161. return mEffectiveMass(3, 3) != 0.0f;
  162. }
  163. /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
  164. inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
  165. {
  166. mTotalLambda *= inWarmStartImpulseRatio;
  167. ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);
  168. }
  169. /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
  170. inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2)
  171. {
  172. // Calculate lagrange multiplier:
  173. //
  174. // lambda = -K^-1 (J v + b)
  175. Vec3 lambda = mEffectiveMass.Multiply3x3(ioBody1.GetAngularVelocity() - ioBody2.GetAngularVelocity());
  176. mTotalLambda += lambda;
  177. return ApplyVelocityStep(ioBody1, ioBody2, lambda);
  178. }
  179. /// Iteratively update the position constraint. Makes sure C(...) = 0.
  180. inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, QuatArg inInvInitialOrientation, float inBaumgarte) const
  181. {
  182. // Calculate difference in rotation
  183. //
  184. // The rotation should be:
  185. //
  186. // q2 = q1 r0
  187. //
  188. // But because of drift the actual rotation is
  189. //
  190. // q2 = diff q1 r0
  191. // <=> diff = q2 r0^-1 q1^-1
  192. //
  193. // Where:
  194. // q1 = current rotation of body 1
  195. // q2 = current rotation of body 2
  196. // diff = error that needs to be reduced to zero
  197. Quat diff = ioBody2.GetRotation() * inInvInitialOrientation * ioBody1.GetRotation().Conjugated();
  198. // A quaternion can be seen as:
  199. //
  200. // q = [sin(theta / 2) * v, cos(theta/2)]
  201. //
  202. // Where:
  203. // v = rotation vector
  204. // theta = rotation angle
  205. //
  206. // If we assume theta is small (error is small) then sin(x) = x so an approximation of the error angles is:
  207. Vec3 error = 2.0f * diff.EnsureWPositive().GetXYZ();
  208. if (error != Vec3::sZero())
  209. {
  210. // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
  211. //
  212. // lambda = -K^-1 * beta / dt * C
  213. //
  214. // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
  215. Vec3 lambda = -inBaumgarte * mEffectiveMass * error;
  216. // Directly integrate velocity change for one time step
  217. //
  218. // Euler velocity integration:
  219. // dv = M^-1 P
  220. //
  221. // Impulse:
  222. // P = J^T lambda
  223. //
  224. // Euler position integration:
  225. // x' = x + dv * dt
  226. //
  227. // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
  228. // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
  229. // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
  230. // integrate + a position integrate and then discard the velocity change.
  231. if (ioBody1.IsDynamic())
  232. ioBody1.SubRotationStep(mInvI1.Multiply3x3(lambda));
  233. if (ioBody2.IsDynamic())
  234. ioBody2.AddRotationStep(mInvI2.Multiply3x3(lambda));
  235. return true;
  236. }
  237. return false;
  238. }
  239. /// Return lagrange multiplier
  240. Vec3 GetTotalLambda() const
  241. {
  242. return mTotalLambda;
  243. }
  244. /// Save state of this constraint part
  245. void SaveState(StateRecorder &inStream) const
  246. {
  247. inStream.Write(mTotalLambda);
  248. }
  249. /// Restore state of this constraint part
  250. void RestoreState(StateRecorder &inStream)
  251. {
  252. inStream.Read(mTotalLambda);
  253. }
  254. private:
  255. Mat44 mInvI1;
  256. Mat44 mInvI2;
  257. Mat44 mEffectiveMass;
  258. Vec3 mTotalLambda { Vec3::sZero() };
  259. };
  260. JPH_NAMESPACE_END