SixDOFConstraint.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/Physics/Constraints/SixDOFConstraint.h>
  6. #include <Jolt/Physics/Body/Body.h>
  7. #include <Jolt/Geometry/Ellipse.h>
  8. #include <Jolt/ObjectStream/TypeDeclarations.h>
  9. #include <Jolt/Core/StreamIn.h>
  10. #include <Jolt/Core/StreamOut.h>
  11. #ifdef JPH_DEBUG_RENDERER
  12. #include <Jolt/Renderer/DebugRenderer.h>
  13. #endif // JPH_DEBUG_RENDERER
  14. JPH_NAMESPACE_BEGIN
  15. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(SixDOFConstraintSettings)
  16. {
  17. JPH_ADD_BASE_CLASS(SixDOFConstraintSettings, TwoBodyConstraintSettings)
  18. JPH_ADD_ENUM_ATTRIBUTE(SixDOFConstraintSettings, mSpace)
  19. JPH_ADD_ATTRIBUTE(SixDOFConstraintSettings, mPosition1)
  20. JPH_ADD_ATTRIBUTE(SixDOFConstraintSettings, mAxisX1)
  21. JPH_ADD_ATTRIBUTE(SixDOFConstraintSettings, mAxisY1)
  22. JPH_ADD_ATTRIBUTE(SixDOFConstraintSettings, mPosition2)
  23. JPH_ADD_ATTRIBUTE(SixDOFConstraintSettings, mAxisX2)
  24. JPH_ADD_ATTRIBUTE(SixDOFConstraintSettings, mAxisY2)
  25. JPH_ADD_ATTRIBUTE(SixDOFConstraintSettings, mMaxFriction)
  26. JPH_ADD_ENUM_ATTRIBUTE(SixDOFConstraintSettings, mSwingType)
  27. JPH_ADD_ATTRIBUTE(SixDOFConstraintSettings, mLimitMin)
  28. JPH_ADD_ATTRIBUTE(SixDOFConstraintSettings, mLimitMax)
  29. JPH_ADD_ATTRIBUTE(SixDOFConstraintSettings, mLimitsSpringSettings)
  30. JPH_ADD_ATTRIBUTE(SixDOFConstraintSettings, mMotorSettings)
  31. }
  32. void SixDOFConstraintSettings::SaveBinaryState(StreamOut &inStream) const
  33. {
  34. ConstraintSettings::SaveBinaryState(inStream);
  35. inStream.Write(mSpace);
  36. inStream.Write(mPosition1);
  37. inStream.Write(mAxisX1);
  38. inStream.Write(mAxisY1);
  39. inStream.Write(mPosition2);
  40. inStream.Write(mAxisX2);
  41. inStream.Write(mAxisY2);
  42. inStream.Write(mMaxFriction);
  43. inStream.Write(mSwingType);
  44. inStream.Write(mLimitMin);
  45. inStream.Write(mLimitMax);
  46. for (const SpringSettings &s : mLimitsSpringSettings)
  47. s.SaveBinaryState(inStream);
  48. for (const MotorSettings &m : mMotorSettings)
  49. m.SaveBinaryState(inStream);
  50. }
  51. void SixDOFConstraintSettings::RestoreBinaryState(StreamIn &inStream)
  52. {
  53. ConstraintSettings::RestoreBinaryState(inStream);
  54. inStream.Read(mSpace);
  55. inStream.Read(mPosition1);
  56. inStream.Read(mAxisX1);
  57. inStream.Read(mAxisY1);
  58. inStream.Read(mPosition2);
  59. inStream.Read(mAxisX2);
  60. inStream.Read(mAxisY2);
  61. inStream.Read(mMaxFriction);
  62. inStream.Read(mSwingType);
  63. inStream.Read(mLimitMin);
  64. inStream.Read(mLimitMax);
  65. for (SpringSettings &s : mLimitsSpringSettings)
  66. s.RestoreBinaryState(inStream);
  67. for (MotorSettings &m : mMotorSettings)
  68. m.RestoreBinaryState(inStream);
  69. }
  70. TwoBodyConstraint *SixDOFConstraintSettings::Create(Body &inBody1, Body &inBody2) const
  71. {
  72. return new SixDOFConstraint(inBody1, inBody2, *this);
  73. }
  74. void SixDOFConstraint::UpdateRotationLimits()
  75. {
  76. // Make values sensible
  77. for (int i = 3; i < 6; ++i)
  78. if (IsFixedAxis((EAxis)i))
  79. mLimitMin[i] = mLimitMax[i] = 0.0f;
  80. else
  81. {
  82. mLimitMin[i] = max(-JPH_PI, mLimitMin[i]);
  83. mLimitMax[i] = min(JPH_PI, mLimitMax[i]);
  84. }
  85. // Pass limits on to constraint part
  86. mSwingTwistConstraintPart.SetLimits(mLimitMin[EAxis::RotationX], mLimitMax[EAxis::RotationX], mLimitMin[EAxis::RotationY], mLimitMax[EAxis::RotationY], mLimitMin[EAxis::RotationZ], mLimitMax[EAxis::RotationZ]);
  87. }
  88. SixDOFConstraint::SixDOFConstraint(Body &inBody1, Body &inBody2, const SixDOFConstraintSettings &inSettings) :
  89. TwoBodyConstraint(inBody1, inBody2, inSettings)
  90. {
  91. // Override swing type
  92. mSwingTwistConstraintPart.SetSwingType(inSettings.mSwingType);
  93. // Calculate rotation needed to go from constraint space to body1 local space
  94. Vec3 axis_z1 = inSettings.mAxisX1.Cross(inSettings.mAxisY1);
  95. Mat44 c_to_b1(Vec4(inSettings.mAxisX1, 0), Vec4(inSettings.mAxisY1, 0), Vec4(axis_z1, 0), Vec4(0, 0, 0, 1));
  96. mConstraintToBody1 = c_to_b1.GetQuaternion();
  97. // Calculate rotation needed to go from constraint space to body2 local space
  98. Vec3 axis_z2 = inSettings.mAxisX2.Cross(inSettings.mAxisY2);
  99. Mat44 c_to_b2(Vec4(inSettings.mAxisX2, 0), Vec4(inSettings.mAxisY2, 0), Vec4(axis_z2, 0), Vec4(0, 0, 0, 1));
  100. mConstraintToBody2 = c_to_b2.GetQuaternion();
  101. if (inSettings.mSpace == EConstraintSpace::WorldSpace)
  102. {
  103. // If all properties were specified in world space, take them to local space now
  104. mLocalSpacePosition1 = Vec3(inBody1.GetInverseCenterOfMassTransform() * inSettings.mPosition1);
  105. mConstraintToBody1 = inBody1.GetRotation().Conjugated() * mConstraintToBody1;
  106. mLocalSpacePosition2 = Vec3(inBody2.GetInverseCenterOfMassTransform() * inSettings.mPosition2);
  107. mConstraintToBody2 = inBody2.GetRotation().Conjugated() * mConstraintToBody2;
  108. }
  109. else
  110. {
  111. mLocalSpacePosition1 = Vec3(inSettings.mPosition1);
  112. mLocalSpacePosition2 = Vec3(inSettings.mPosition2);
  113. }
  114. // Cache which axis are fixed and which ones are free
  115. mFreeAxis = 0;
  116. mFixedAxis = 0;
  117. for (int a = 0; a < EAxis::Num; ++a)
  118. {
  119. if (inSettings.IsFixedAxis((EAxis)a))
  120. mFixedAxis |= 1 << a;
  121. if (inSettings.IsFreeAxis((EAxis)a))
  122. mFreeAxis |= 1 << a;
  123. }
  124. // Copy translation and rotation limits
  125. memcpy(mLimitMin, inSettings.mLimitMin, sizeof(mLimitMin));
  126. memcpy(mLimitMax, inSettings.mLimitMax, sizeof(mLimitMax));
  127. memcpy(mLimitsSpringSettings, inSettings.mLimitsSpringSettings, sizeof(mLimitsSpringSettings));
  128. UpdateRotationLimits();
  129. CacheHasSpringLimits();
  130. // Store friction settings
  131. memcpy(mMaxFriction, inSettings.mMaxFriction, sizeof(mMaxFriction));
  132. // Store motor settings
  133. for (int i = 0; i < EAxis::Num; ++i)
  134. mMotorSettings[i] = inSettings.mMotorSettings[i];
  135. // Cache if motors are active (motors are off initially, but we may have friction)
  136. CacheTranslationMotorActive();
  137. CacheRotationMotorActive();
  138. }
  139. void SixDOFConstraint::NotifyShapeChanged(const BodyID &inBodyID, Vec3Arg inDeltaCOM)
  140. {
  141. if (mBody1->GetID() == inBodyID)
  142. mLocalSpacePosition1 -= inDeltaCOM;
  143. else if (mBody2->GetID() == inBodyID)
  144. mLocalSpacePosition2 -= inDeltaCOM;
  145. }
  146. void SixDOFConstraint::SetTranslationLimits(Vec3Arg inLimitMin, Vec3Arg inLimitMax)
  147. {
  148. mLimitMin[EAxis::TranslationX] = inLimitMin.GetX();
  149. mLimitMin[EAxis::TranslationY] = inLimitMin.GetY();
  150. mLimitMin[EAxis::TranslationZ] = inLimitMin.GetZ();
  151. mLimitMax[EAxis::TranslationX] = inLimitMax.GetX();
  152. mLimitMax[EAxis::TranslationY] = inLimitMax.GetY();
  153. mLimitMax[EAxis::TranslationZ] = inLimitMax.GetZ();
  154. }
  155. void SixDOFConstraint::SetRotationLimits(Vec3Arg inLimitMin, Vec3Arg inLimitMax)
  156. {
  157. mLimitMin[EAxis::RotationX] = inLimitMin.GetX();
  158. mLimitMin[EAxis::RotationY] = inLimitMin.GetY();
  159. mLimitMin[EAxis::RotationZ] = inLimitMin.GetZ();
  160. mLimitMax[EAxis::RotationX] = inLimitMax.GetX();
  161. mLimitMax[EAxis::RotationY] = inLimitMax.GetY();
  162. mLimitMax[EAxis::RotationZ] = inLimitMax.GetZ();
  163. UpdateRotationLimits();
  164. }
  165. void SixDOFConstraint::SetMaxFriction(EAxis inAxis, float inFriction)
  166. {
  167. mMaxFriction[inAxis] = inFriction;
  168. if (inAxis >= EAxis::TranslationX && inAxis <= EAxis::TranslationZ)
  169. CacheTranslationMotorActive();
  170. else
  171. CacheRotationMotorActive();
  172. }
  173. void SixDOFConstraint::GetPositionConstraintProperties(Vec3 &outR1PlusU, Vec3 &outR2, Vec3 &outU) const
  174. {
  175. RVec3 p1 = mBody1->GetCenterOfMassTransform() * mLocalSpacePosition1;
  176. RVec3 p2 = mBody2->GetCenterOfMassTransform() * mLocalSpacePosition2;
  177. outR1PlusU = Vec3(p2 - mBody1->GetCenterOfMassPosition()); // r1 + u = (p1 - x1) + (p2 - p1) = p2 - x1
  178. outR2 = Vec3(p2 - mBody2->GetCenterOfMassPosition());
  179. outU = Vec3(p2 - p1);
  180. }
  181. Quat SixDOFConstraint::GetRotationInConstraintSpace() const
  182. {
  183. // Let b1, b2 be the center of mass transform of body1 and body2 (For body1 this is mBody1->GetCenterOfMassTransform())
  184. // Let c1, c2 be the transform that takes a vector from constraint space to local space of body1 and body2 (For body1 this is Mat44::sRotationTranslation(mConstraintToBody1, mLocalSpacePosition1))
  185. // Let q be the rotation of the constraint in constraint space
  186. // b2 takes a vector from the local space of body2 to world space
  187. // To express this in terms of b1: b2 = b1 * c1 * q * c2^-1
  188. // c2^-1 goes from local body 2 space to constraint space
  189. // q rotates the constraint
  190. // c1 goes from constraint space to body 1 local space
  191. // b1 goes from body 1 local space to world space
  192. // So when the body rotations are given, q = (b1 * c1)^-1 * b2 c2
  193. // Or: q = (q1 * c1)^-1 * (q2 * c2) if we're only interested in rotations
  194. return (mBody1->GetRotation() * mConstraintToBody1).Conjugated() * mBody2->GetRotation() * mConstraintToBody2;
  195. }
  196. void SixDOFConstraint::CacheTranslationMotorActive()
  197. {
  198. mTranslationMotorActive = mMotorState[EAxis::TranslationX] != EMotorState::Off
  199. || mMotorState[EAxis::TranslationY] != EMotorState::Off
  200. || mMotorState[EAxis::TranslationZ] != EMotorState::Off
  201. || HasFriction(EAxis::TranslationX)
  202. || HasFriction(EAxis::TranslationY)
  203. || HasFriction(EAxis::TranslationZ);
  204. }
  205. void SixDOFConstraint::CacheRotationMotorActive()
  206. {
  207. mRotationMotorActive = mMotorState[EAxis::RotationX] != EMotorState::Off
  208. || mMotorState[EAxis::RotationY] != EMotorState::Off
  209. || mMotorState[EAxis::RotationZ] != EMotorState::Off
  210. || HasFriction(EAxis::RotationX)
  211. || HasFriction(EAxis::RotationY)
  212. || HasFriction(EAxis::RotationZ);
  213. }
  214. void SixDOFConstraint::CacheRotationPositionMotorActive()
  215. {
  216. mRotationPositionMotorActive = 0;
  217. for (int i = 0; i < 3; ++i)
  218. if (mMotorState[EAxis::RotationX + i] == EMotorState::Position)
  219. mRotationPositionMotorActive |= 1 << i;
  220. }
  221. void SixDOFConstraint::CacheHasSpringLimits()
  222. {
  223. mHasSpringLimits = mLimitsSpringSettings[EAxis::TranslationX].mFrequency > 0.0f
  224. || mLimitsSpringSettings[EAxis::TranslationY].mFrequency > 0.0f
  225. || mLimitsSpringSettings[EAxis::TranslationZ].mFrequency > 0.0f;
  226. }
  227. void SixDOFConstraint::SetMotorState(EAxis inAxis, EMotorState inState)
  228. {
  229. JPH_ASSERT(inState == EMotorState::Off || mMotorSettings[inAxis].IsValid());
  230. if (mMotorState[inAxis] != inState)
  231. {
  232. mMotorState[inAxis] = inState;
  233. // Ensure that warm starting next frame doesn't apply any impulses (motor parts are repurposed for different modes)
  234. if (inAxis >= EAxis::TranslationX && inAxis <= EAxis::TranslationZ)
  235. {
  236. mMotorTranslationConstraintPart[inAxis - EAxis::TranslationX].Deactivate();
  237. CacheTranslationMotorActive();
  238. }
  239. else
  240. {
  241. JPH_ASSERT(inAxis >= EAxis::RotationX && inAxis <= EAxis::RotationZ);
  242. mMotorRotationConstraintPart[inAxis - EAxis::RotationX].Deactivate();
  243. CacheRotationMotorActive();
  244. CacheRotationPositionMotorActive();
  245. }
  246. }
  247. }
  248. void SixDOFConstraint::SetTargetOrientationCS(QuatArg inOrientation)
  249. {
  250. Quat q_swing, q_twist;
  251. inOrientation.GetSwingTwist(q_swing, q_twist);
  252. uint clamped_axis;
  253. mSwingTwistConstraintPart.ClampSwingTwist(q_swing, q_twist, clamped_axis);
  254. if (clamped_axis != 0)
  255. mTargetOrientation = q_swing * q_twist;
  256. else
  257. mTargetOrientation = inOrientation;
  258. }
  259. void SixDOFConstraint::SetupVelocityConstraint(float inDeltaTime)
  260. {
  261. // Get body rotations
  262. Quat rotation1 = mBody1->GetRotation();
  263. Quat rotation2 = mBody2->GetRotation();
  264. // Quaternion that rotates from body1's constraint space to world space
  265. Quat constraint_body1_to_world = rotation1 * mConstraintToBody1;
  266. // Store world space axis of constraint space
  267. Mat44 translation_axis_mat = Mat44::sRotation(constraint_body1_to_world);
  268. for (int i = 0; i < 3; ++i)
  269. mTranslationAxis[i] = translation_axis_mat.GetColumn3(i);
  270. if (IsTranslationFullyConstrained())
  271. {
  272. // All translation locked: Setup point constraint
  273. mPointConstraintPart.CalculateConstraintProperties(*mBody1, Mat44::sRotation(rotation1), mLocalSpacePosition1, *mBody2, Mat44::sRotation(rotation2), mLocalSpacePosition2);
  274. }
  275. else if (IsTranslationConstrained() || mTranslationMotorActive)
  276. {
  277. // Update world space positions (the bodies may have moved)
  278. Vec3 r1_plus_u, r2, u;
  279. GetPositionConstraintProperties(r1_plus_u, r2, u);
  280. // Setup axis constraint parts
  281. for (int i = 0; i < 3; ++i)
  282. {
  283. EAxis axis = EAxis(EAxis::TranslationX + i);
  284. Vec3 translation_axis = mTranslationAxis[i];
  285. // Calculate displacement along this axis
  286. float d = translation_axis.Dot(u);
  287. mDisplacement[i] = d; // Store for SolveVelocityConstraint
  288. // Setup limit constraint
  289. bool constraint_active = false;
  290. float constraint_value = 0.0f;
  291. if (IsFixedAxis(axis))
  292. {
  293. // When constraint is fixed it is always active
  294. constraint_value = d;
  295. constraint_active = true;
  296. }
  297. else if (!IsFreeAxis(axis))
  298. {
  299. // When constraint is limited, it is only active when outside of the allowed range
  300. if (d <= mLimitMin[i])
  301. {
  302. constraint_value = d - mLimitMin[i];
  303. constraint_active = true;
  304. }
  305. else if (d >= mLimitMax[i])
  306. {
  307. constraint_value = d - mLimitMax[i];
  308. constraint_active = true;
  309. }
  310. }
  311. if (constraint_active)
  312. mTranslationConstraintPart[i].CalculateConstraintPropertiesWithSettings(inDeltaTime, *mBody1, r1_plus_u, *mBody2, r2, translation_axis, 0.0f, constraint_value, mLimitsSpringSettings[i]);
  313. else
  314. mTranslationConstraintPart[i].Deactivate();
  315. // Setup motor constraint
  316. switch (mMotorState[i])
  317. {
  318. case EMotorState::Off:
  319. if (HasFriction(axis))
  320. mMotorTranslationConstraintPart[i].CalculateConstraintProperties(*mBody1, r1_plus_u, *mBody2, r2, translation_axis);
  321. else
  322. mMotorTranslationConstraintPart[i].Deactivate();
  323. break;
  324. case EMotorState::Velocity:
  325. mMotorTranslationConstraintPart[i].CalculateConstraintProperties(*mBody1, r1_plus_u, *mBody2, r2, translation_axis, -mTargetVelocity[i]);
  326. break;
  327. case EMotorState::Position:
  328. {
  329. const SpringSettings &spring_settings = mMotorSettings[i].mSpringSettings;
  330. if (spring_settings.HasStiffness())
  331. mMotorTranslationConstraintPart[i].CalculateConstraintPropertiesWithSettings(inDeltaTime, *mBody1, r1_plus_u, *mBody2, r2, translation_axis, 0.0f, translation_axis.Dot(u) - mTargetPosition[i], spring_settings);
  332. else
  333. mMotorTranslationConstraintPart[i].Deactivate();
  334. break;
  335. }
  336. }
  337. }
  338. }
  339. // Setup rotation constraints
  340. if (IsRotationFullyConstrained())
  341. {
  342. // All rotation locked: Setup rotation contraint
  343. mRotationConstraintPart.CalculateConstraintProperties(*mBody1, Mat44::sRotation(mBody1->GetRotation()), *mBody2, Mat44::sRotation(mBody2->GetRotation()));
  344. }
  345. else if (IsRotationConstrained() || mRotationMotorActive)
  346. {
  347. // GetRotationInConstraintSpace without redoing the calculation of constraint_body1_to_world
  348. Quat constraint_body2_to_world = mBody2->GetRotation() * mConstraintToBody2;
  349. Quat q = constraint_body1_to_world.Conjugated() * constraint_body2_to_world;
  350. // Use swing twist constraint part
  351. if (IsRotationConstrained())
  352. mSwingTwistConstraintPart.CalculateConstraintProperties(*mBody1, *mBody2, q, constraint_body1_to_world);
  353. else
  354. mSwingTwistConstraintPart.Deactivate();
  355. if (mRotationMotorActive)
  356. {
  357. // Calculate rotation motor axis
  358. Mat44 ws_axis = Mat44::sRotation(constraint_body2_to_world);
  359. for (int i = 0; i < 3; ++i)
  360. mRotationAxis[i] = ws_axis.GetColumn3(i);
  361. // Get target orientation along the shortest path from q
  362. Quat target_orientation = q.Dot(mTargetOrientation) > 0.0f? mTargetOrientation : -mTargetOrientation;
  363. // The definition of the constraint rotation q:
  364. // R2 * ConstraintToBody2 = R1 * ConstraintToBody1 * q (1)
  365. //
  366. // R2' is the rotation of body 2 when reaching the target_orientation:
  367. // R2' * ConstraintToBody2 = R1 * ConstraintToBody1 * target_orientation (2)
  368. //
  369. // The difference in body 2 space:
  370. // R2' = R2 * diff_body2 (3)
  371. //
  372. // We want to specify the difference in the constraint space of body 2:
  373. // diff_body2 = ConstraintToBody2 * diff * ConstraintToBody2^* (4)
  374. //
  375. // Extracting R2' from 2: R2' = R1 * ConstraintToBody1 * target_orientation * ConstraintToBody2^* (5)
  376. // Combining 3 & 4: R2' = R2 * ConstraintToBody2 * diff * ConstraintToBody2^* (6)
  377. // Combining 1 & 6: R2' = R1 * ConstraintToBody1 * q * diff * ConstraintToBody2^* (7)
  378. // Combining 5 & 7: R1 * ConstraintToBody1 * target_orientation * ConstraintToBody2^* = R1 * ConstraintToBody1 * q * diff * ConstraintToBody2^*
  379. // <=> target_orientation = q * diff
  380. // <=> diff = q^* * target_orientation
  381. Quat diff = q.Conjugated() * target_orientation;
  382. // Project diff so that only rotation around axis that have a position motor are remaining
  383. Quat projected_diff;
  384. switch (mRotationPositionMotorActive)
  385. {
  386. case 0b001:
  387. // Keep only rotation around X
  388. projected_diff = diff.GetTwist(Vec3::sAxisX());
  389. break;
  390. case 0b010:
  391. // Keep only rotation around Y
  392. projected_diff = diff.GetTwist(Vec3::sAxisY());
  393. break;
  394. case 0b100:
  395. // Keep only rotation around Z
  396. projected_diff = diff.GetTwist(Vec3::sAxisZ());
  397. break;
  398. case 0b011:
  399. // Remove rotation around Z
  400. // q = swing_xy * twist_z <=> swing_xy = q * twist_z^*
  401. projected_diff = diff * diff.GetTwist(Vec3::sAxisZ()).Conjugated();
  402. break;
  403. case 0b101:
  404. // Remove rotation around Y
  405. // q = swing_xz * twist_y <=> swing_xz = q * twist_y^*
  406. projected_diff = diff * diff.GetTwist(Vec3::sAxisY()).Conjugated();
  407. break;
  408. case 0b110:
  409. // Remove rotation around X
  410. // q = swing_yz * twist_x <=> swing_yz = q * twist_x^*
  411. projected_diff = diff * diff.GetTwist(Vec3::sAxisX()).Conjugated();
  412. break;
  413. case 0b111:
  414. default: // All motors off is handled here but the results are unused
  415. // Keep entire rotation
  416. projected_diff = diff;
  417. break;
  418. }
  419. // Approximate error angles
  420. // The imaginary part of a quaternion is rotation_axis * sin(angle / 2)
  421. // If angle is small, sin(x) = x so angle[i] ~ 2.0f * rotation_axis[i]
  422. // We'll be making small time steps, so if the angle is not small at least the sign will be correct and we'll move in the right direction
  423. Vec3 rotation_error = -2.0f * projected_diff.GetXYZ();
  424. // Setup motors
  425. for (int i = 0; i < 3; ++i)
  426. {
  427. EAxis axis = EAxis(EAxis::RotationX + i);
  428. Vec3 rotation_axis = mRotationAxis[i];
  429. switch (mMotorState[axis])
  430. {
  431. case EMotorState::Off:
  432. if (HasFriction(axis))
  433. mMotorRotationConstraintPart[i].CalculateConstraintProperties(*mBody1, *mBody2, rotation_axis);
  434. else
  435. mMotorRotationConstraintPart[i].Deactivate();
  436. break;
  437. case EMotorState::Velocity:
  438. mMotorRotationConstraintPart[i].CalculateConstraintProperties(*mBody1, *mBody2, rotation_axis, -mTargetAngularVelocity[i]);
  439. break;
  440. case EMotorState::Position:
  441. {
  442. const SpringSettings &spring_settings = mMotorSettings[axis].mSpringSettings;
  443. if (spring_settings.HasStiffness())
  444. mMotorRotationConstraintPart[i].CalculateConstraintPropertiesWithSettings(inDeltaTime, *mBody1, *mBody2, rotation_axis, 0.0f, rotation_error[i], spring_settings);
  445. else
  446. mMotorRotationConstraintPart[i].Deactivate();
  447. break;
  448. }
  449. }
  450. }
  451. }
  452. }
  453. }
  454. void SixDOFConstraint::WarmStartVelocityConstraint(float inWarmStartImpulseRatio)
  455. {
  456. // Warm start translation motors
  457. if (mTranslationMotorActive)
  458. for (int i = 0; i < 3; ++i)
  459. if (mMotorTranslationConstraintPart[i].IsActive())
  460. mMotorTranslationConstraintPart[i].WarmStart(*mBody1, *mBody2, mTranslationAxis[i], inWarmStartImpulseRatio);
  461. // Warm start rotation motors
  462. if (mRotationMotorActive)
  463. for (AngleConstraintPart &c : mMotorRotationConstraintPart)
  464. if (c.IsActive())
  465. c.WarmStart(*mBody1, *mBody2, inWarmStartImpulseRatio);
  466. // Warm start rotation constraints
  467. if (IsRotationFullyConstrained())
  468. mRotationConstraintPart.WarmStart(*mBody1, *mBody2, inWarmStartImpulseRatio);
  469. else if (IsRotationConstrained())
  470. mSwingTwistConstraintPart.WarmStart(*mBody1, *mBody2, inWarmStartImpulseRatio);
  471. // Warm start translation constraints
  472. if (IsTranslationFullyConstrained())
  473. mPointConstraintPart.WarmStart(*mBody1, *mBody2, inWarmStartImpulseRatio);
  474. else if (IsTranslationConstrained())
  475. for (int i = 0; i < 3; ++i)
  476. if (mTranslationConstraintPart[i].IsActive())
  477. mTranslationConstraintPart[i].WarmStart(*mBody1, *mBody2, mTranslationAxis[i], inWarmStartImpulseRatio);
  478. }
  479. bool SixDOFConstraint::SolveVelocityConstraint(float inDeltaTime)
  480. {
  481. bool impulse = false;
  482. // Solve translation motor
  483. if (mTranslationMotorActive)
  484. for (int i = 0; i < 3; ++i)
  485. if (mMotorTranslationConstraintPart[i].IsActive())
  486. switch (mMotorState[i])
  487. {
  488. case EMotorState::Off:
  489. {
  490. // Apply friction only
  491. float max_lambda = mMaxFriction[i] * inDeltaTime;
  492. impulse |= mMotorTranslationConstraintPart[i].SolveVelocityConstraint(*mBody1, *mBody2, mTranslationAxis[i], -max_lambda, max_lambda);
  493. break;
  494. }
  495. case EMotorState::Velocity:
  496. case EMotorState::Position:
  497. // Drive motor
  498. impulse |= mMotorTranslationConstraintPart[i].SolveVelocityConstraint(*mBody1, *mBody2, mTranslationAxis[i], inDeltaTime * mMotorSettings[i].mMinForceLimit, inDeltaTime * mMotorSettings[i].mMaxForceLimit);
  499. break;
  500. }
  501. // Solve rotation motor
  502. if (mRotationMotorActive)
  503. for (int i = 0; i < 3; ++i)
  504. {
  505. EAxis axis = EAxis(EAxis::RotationX + i);
  506. if (mMotorRotationConstraintPart[i].IsActive())
  507. switch (mMotorState[axis])
  508. {
  509. case EMotorState::Off:
  510. {
  511. // Apply friction only
  512. float max_lambda = mMaxFriction[axis] * inDeltaTime;
  513. impulse |= mMotorRotationConstraintPart[i].SolveVelocityConstraint(*mBody1, *mBody2, mRotationAxis[i], -max_lambda, max_lambda);
  514. break;
  515. }
  516. case EMotorState::Velocity:
  517. case EMotorState::Position:
  518. // Drive motor
  519. impulse |= mMotorRotationConstraintPart[i].SolveVelocityConstraint(*mBody1, *mBody2, mRotationAxis[i], inDeltaTime * mMotorSettings[axis].mMinTorqueLimit, inDeltaTime * mMotorSettings[axis].mMaxTorqueLimit);
  520. break;
  521. }
  522. }
  523. // Solve rotation constraint
  524. if (IsRotationFullyConstrained())
  525. impulse |= mRotationConstraintPart.SolveVelocityConstraint(*mBody1, *mBody2);
  526. else if (IsRotationConstrained())
  527. impulse |= mSwingTwistConstraintPart.SolveVelocityConstraint(*mBody1, *mBody2);
  528. // Solve position constraint
  529. if (IsTranslationFullyConstrained())
  530. impulse |= mPointConstraintPart.SolveVelocityConstraint(*mBody1, *mBody2);
  531. else if (IsTranslationConstrained())
  532. for (int i = 0; i < 3; ++i)
  533. if (mTranslationConstraintPart[i].IsActive())
  534. {
  535. // If the axis is not fixed it must be limited (or else the constraint would not be active)
  536. // Calculate the min and max constraint force based on on which side we're limited
  537. float limit_min = -FLT_MAX, limit_max = FLT_MAX;
  538. if (!IsFixedAxis(EAxis(EAxis::TranslationX + i)))
  539. {
  540. JPH_ASSERT(!IsFreeAxis(EAxis(EAxis::TranslationX + i)));
  541. if (mDisplacement[i] <= mLimitMin[i])
  542. limit_min = 0;
  543. else if (mDisplacement[i] >= mLimitMax[i])
  544. limit_max = 0;
  545. }
  546. impulse |= mTranslationConstraintPart[i].SolveVelocityConstraint(*mBody1, *mBody2, mTranslationAxis[i], limit_min, limit_max);
  547. }
  548. return impulse;
  549. }
  550. bool SixDOFConstraint::SolvePositionConstraint(float inDeltaTime, float inBaumgarte)
  551. {
  552. bool impulse = false;
  553. if (IsRotationFullyConstrained())
  554. {
  555. // Rotation locked: Solve rotation constraint
  556. // Inverse of initial rotation from body 1 to body 2 in body 1 space
  557. // Definition of initial orientation r0: q2 = q1 r0
  558. // Initial rotation (see: GetRotationInConstraintSpace): q2 = q1 c1 c2^-1
  559. // So: r0^-1 = (c1 c2^-1)^-1 = c2 * c1^-1
  560. Quat inv_initial_orientation = mConstraintToBody2 * mConstraintToBody1.Conjugated();
  561. // Solve rotation violations
  562. mRotationConstraintPart.CalculateConstraintProperties(*mBody1, Mat44::sRotation(mBody1->GetRotation()), *mBody2, Mat44::sRotation(mBody2->GetRotation()));
  563. impulse |= mRotationConstraintPart.SolvePositionConstraint(*mBody1, *mBody2, inv_initial_orientation, inBaumgarte);
  564. }
  565. else if (IsRotationConstrained())
  566. {
  567. // Rotation partially constraint
  568. // Solve rotation violations
  569. Quat q = GetRotationInConstraintSpace();
  570. impulse |= mSwingTwistConstraintPart.SolvePositionConstraint(*mBody1, *mBody2, q, mConstraintToBody1, mConstraintToBody2, inBaumgarte);
  571. }
  572. // Solve position violations
  573. if (IsTranslationFullyConstrained())
  574. {
  575. // Translation locked: Solve point constraint
  576. mPointConstraintPart.CalculateConstraintProperties(*mBody1, Mat44::sRotation(mBody1->GetRotation()), mLocalSpacePosition1, *mBody2, Mat44::sRotation(mBody2->GetRotation()), mLocalSpacePosition2);
  577. impulse |= mPointConstraintPart.SolvePositionConstraint(*mBody1, *mBody2, inBaumgarte);
  578. }
  579. else if (IsTranslationConstrained())
  580. {
  581. // Translation partially locked: Solve per axis
  582. for (int i = 0; i < 3; ++i)
  583. if (mLimitsSpringSettings[i].mFrequency <= 0.0f) // If not soft limit
  584. {
  585. // Update world space positions (the bodies may have moved)
  586. Vec3 r1_plus_u, r2, u;
  587. GetPositionConstraintProperties(r1_plus_u, r2, u);
  588. // Quaternion that rotates from body1's constraint space to world space
  589. Quat constraint_body1_to_world = mBody1->GetRotation() * mConstraintToBody1;
  590. // Calculate axis
  591. Vec3 translation_axis;
  592. switch (i)
  593. {
  594. case 0: translation_axis = constraint_body1_to_world.RotateAxisX(); break;
  595. case 1: translation_axis = constraint_body1_to_world.RotateAxisY(); break;
  596. default: JPH_ASSERT(i == 2); translation_axis = constraint_body1_to_world.RotateAxisZ(); break;
  597. }
  598. // Determine position error
  599. float error = 0.0f;
  600. EAxis axis(EAxis(EAxis::TranslationX + i));
  601. if (IsFixedAxis(axis))
  602. error = u.Dot(translation_axis);
  603. else if (!IsFreeAxis(axis))
  604. {
  605. float displacement = u.Dot(translation_axis);
  606. if (displacement <= mLimitMin[axis])
  607. error = displacement - mLimitMin[axis];
  608. else if (displacement >= mLimitMax[axis])
  609. error = displacement - mLimitMax[axis];
  610. }
  611. if (error != 0.0f)
  612. {
  613. // Setup axis constraint part and solve it
  614. mTranslationConstraintPart[i].CalculateConstraintProperties(*mBody1, r1_plus_u, *mBody2, r2, translation_axis);
  615. impulse |= mTranslationConstraintPart[i].SolvePositionConstraint(*mBody1, *mBody2, translation_axis, error, inBaumgarte);
  616. }
  617. }
  618. }
  619. return impulse;
  620. }
  621. #ifdef JPH_DEBUG_RENDERER
  622. void SixDOFConstraint::DrawConstraint(DebugRenderer *inRenderer) const
  623. {
  624. // Get constraint properties in world space
  625. RVec3 position1 = mBody1->GetCenterOfMassTransform() * mLocalSpacePosition1;
  626. Quat rotation1 = mBody1->GetRotation() * mConstraintToBody1;
  627. Quat rotation2 = mBody2->GetRotation() * mConstraintToBody2;
  628. // Draw constraint orientation
  629. inRenderer->DrawCoordinateSystem(RMat44::sRotationTranslation(rotation1, position1), mDrawConstraintSize);
  630. if ((IsRotationConstrained() || mRotationPositionMotorActive != 0) && !IsRotationFullyConstrained())
  631. {
  632. // Draw current swing and twist
  633. Quat q = GetRotationInConstraintSpace();
  634. Quat q_swing, q_twist;
  635. q.GetSwingTwist(q_swing, q_twist);
  636. inRenderer->DrawLine(position1, position1 + mDrawConstraintSize * (rotation1 * q_twist).RotateAxisY(), Color::sWhite);
  637. inRenderer->DrawLine(position1, position1 + mDrawConstraintSize * (rotation1 * q_swing).RotateAxisX(), Color::sWhite);
  638. }
  639. // Draw target rotation
  640. Quat m_swing, m_twist;
  641. mTargetOrientation.GetSwingTwist(m_swing, m_twist);
  642. if (mMotorState[EAxis::RotationX] == EMotorState::Position)
  643. inRenderer->DrawLine(position1, position1 + mDrawConstraintSize * (rotation1 * m_twist).RotateAxisY(), Color::sYellow);
  644. if (mMotorState[EAxis::RotationY] == EMotorState::Position || mMotorState[EAxis::RotationZ] == EMotorState::Position)
  645. inRenderer->DrawLine(position1, position1 + mDrawConstraintSize * (rotation1 * m_swing).RotateAxisX(), Color::sYellow);
  646. // Draw target angular velocity
  647. Vec3 target_angular_velocity = Vec3::sZero();
  648. for (int i = 0; i < 3; ++i)
  649. if (mMotorState[EAxis::RotationX + i] == EMotorState::Velocity)
  650. target_angular_velocity.SetComponent(i, mTargetAngularVelocity[i]);
  651. if (target_angular_velocity != Vec3::sZero())
  652. inRenderer->DrawArrow(position1, position1 + rotation2 * target_angular_velocity, Color::sRed, 0.1f);
  653. }
  654. void SixDOFConstraint::DrawConstraintLimits(DebugRenderer *inRenderer) const
  655. {
  656. // Get matrix that transforms from constraint space to world space
  657. RMat44 constraint_body1_to_world = RMat44::sRotationTranslation(mBody1->GetRotation() * mConstraintToBody1, mBody1->GetCenterOfMassTransform() * mLocalSpacePosition1);
  658. // Draw limits
  659. if (mSwingTwistConstraintPart.GetSwingType() == ESwingType::Pyramid
  660. || mLimitMin[EAxis::RotationY] >= mLimitMax[EAxis::RotationY]
  661. || mLimitMin[EAxis::RotationZ] >= mLimitMax[EAxis::RotationZ])
  662. inRenderer->DrawSwingPyramidLimits(constraint_body1_to_world, mLimitMin[EAxis::RotationY], mLimitMax[EAxis::RotationY], mLimitMin[EAxis::RotationZ], mLimitMax[EAxis::RotationZ], mDrawConstraintSize, Color::sGreen, DebugRenderer::ECastShadow::Off);
  663. else
  664. inRenderer->DrawSwingConeLimits(constraint_body1_to_world, mLimitMax[EAxis::RotationY], mLimitMax[EAxis::RotationZ], mDrawConstraintSize, Color::sGreen, DebugRenderer::ECastShadow::Off);
  665. inRenderer->DrawPie(constraint_body1_to_world.GetTranslation(), mDrawConstraintSize, constraint_body1_to_world.GetAxisX(), constraint_body1_to_world.GetAxisY(), mLimitMin[EAxis::RotationX], mLimitMax[EAxis::RotationX], Color::sPurple, DebugRenderer::ECastShadow::Off);
  666. }
  667. #endif // JPH_DEBUG_RENDERER
  668. void SixDOFConstraint::SaveState(StateRecorder &inStream) const
  669. {
  670. TwoBodyConstraint::SaveState(inStream);
  671. for (const AxisConstraintPart &c : mTranslationConstraintPart)
  672. c.SaveState(inStream);
  673. mPointConstraintPart.SaveState(inStream);
  674. mSwingTwistConstraintPart.SaveState(inStream);
  675. mRotationConstraintPart.SaveState(inStream);
  676. for (const AxisConstraintPart &c : mMotorTranslationConstraintPart)
  677. c.SaveState(inStream);
  678. for (const AngleConstraintPart &c : mMotorRotationConstraintPart)
  679. c.SaveState(inStream);
  680. inStream.Write(mMotorState);
  681. inStream.Write(mTargetVelocity);
  682. inStream.Write(mTargetAngularVelocity);
  683. inStream.Write(mTargetPosition);
  684. inStream.Write(mTargetOrientation);
  685. }
  686. void SixDOFConstraint::RestoreState(StateRecorder &inStream)
  687. {
  688. TwoBodyConstraint::RestoreState(inStream);
  689. for (AxisConstraintPart &c : mTranslationConstraintPart)
  690. c.RestoreState(inStream);
  691. mPointConstraintPart.RestoreState(inStream);
  692. mSwingTwistConstraintPart.RestoreState(inStream);
  693. mRotationConstraintPart.RestoreState(inStream);
  694. for (AxisConstraintPart &c : mMotorTranslationConstraintPart)
  695. c.RestoreState(inStream);
  696. for (AngleConstraintPart &c : mMotorRotationConstraintPart)
  697. c.RestoreState(inStream);
  698. inStream.Read(mMotorState);
  699. inStream.Read(mTargetVelocity);
  700. inStream.Read(mTargetAngularVelocity);
  701. inStream.Read(mTargetPosition);
  702. inStream.Read(mTargetOrientation);
  703. CacheTranslationMotorActive();
  704. CacheRotationMotorActive();
  705. CacheRotationPositionMotorActive();
  706. }
  707. Ref<ConstraintSettings> SixDOFConstraint::GetConstraintSettings() const
  708. {
  709. SixDOFConstraintSettings *settings = new SixDOFConstraintSettings;
  710. ToConstraintSettings(*settings);
  711. settings->mSpace = EConstraintSpace::LocalToBodyCOM;
  712. settings->mPosition1 = RVec3(mLocalSpacePosition1);
  713. settings->mAxisX1 = mConstraintToBody1.RotateAxisX();
  714. settings->mAxisY1 = mConstraintToBody1.RotateAxisY();
  715. settings->mPosition2 = RVec3(mLocalSpacePosition2);
  716. settings->mAxisX2 = mConstraintToBody2.RotateAxisX();
  717. settings->mAxisY2 = mConstraintToBody2.RotateAxisY();
  718. memcpy(settings->mLimitMin, mLimitMin, sizeof(mLimitMin));
  719. memcpy(settings->mLimitMax, mLimitMax, sizeof(mLimitMax));
  720. memcpy(settings->mMaxFriction, mMaxFriction, sizeof(mMaxFriction));
  721. for (int i = 0; i < EAxis::Num; ++i)
  722. settings->mMotorSettings[i] = mMotorSettings[i];
  723. return settings;
  724. }
  725. JPH_NAMESPACE_END