btSequentialImpulseConstraintSolver.cpp 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875
  1. /*
  2. Bullet Continuous Collision Detection and Physics Library
  3. Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
  4. This software is provided 'as-is', without any express or implied warranty.
  5. In no event will the authors be held liable for any damages arising from the use of this software.
  6. Permission is granted to anyone to use this software for any purpose,
  7. including commercial applications, and to alter it and redistribute it freely,
  8. subject to the following restrictions:
  9. 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
  10. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  11. 3. This notice may not be removed or altered from any source distribution.
  12. */
  13. //#define COMPUTE_IMPULSE_DENOM 1
  14. #ifdef BT_DEBUG
  15. # define BT_ADDITIONAL_DEBUG
  16. #endif
  17. //It is not necessary (redundant) to refresh contact manifolds, this refresh has been moved to the collision algorithms.
  18. #include "btSequentialImpulseConstraintSolver.h"
  19. #include "BulletCollision/NarrowPhaseCollision/btPersistentManifold.h"
  20. #include "LinearMath/btIDebugDraw.h"
  21. #include "LinearMath/btCpuFeatureUtility.h"
  22. //#include "btJacobianEntry.h"
  23. #include "LinearMath/btMinMax.h"
  24. #include "BulletDynamics/ConstraintSolver/btTypedConstraint.h"
  25. #include <new>
  26. #include "LinearMath/btStackAlloc.h"
  27. #include "LinearMath/btQuickprof.h"
  28. //#include "btSolverBody.h"
  29. //#include "btSolverConstraint.h"
  30. #include "LinearMath/btAlignedObjectArray.h"
  31. #include <string.h> //for memset
  32. int gNumSplitImpulseRecoveries = 0;
  33. #include "BulletDynamics/Dynamics/btRigidBody.h"
  34. //#define VERBOSE_RESIDUAL_PRINTF 1
  35. ///This is the scalar reference implementation of solving a single constraint row, the innerloop of the Projected Gauss Seidel/Sequential Impulse constraint solver
  36. ///Below are optional SSE2 and SSE4/FMA3 versions. We assume most hardware has SSE2. For SSE4/FMA3 we perform a CPU feature check.
  37. static btScalar gResolveSingleConstraintRowGeneric_scalar_reference(btSolverBody& bodyA, btSolverBody& bodyB, const btSolverConstraint& c)
  38. {
  39. btScalar deltaImpulse = c.m_rhs - btScalar(c.m_appliedImpulse) * c.m_cfm;
  40. const btScalar deltaVel1Dotn = c.m_contactNormal1.dot(bodyA.internalGetDeltaLinearVelocity()) + c.m_relpos1CrossNormal.dot(bodyA.internalGetDeltaAngularVelocity());
  41. const btScalar deltaVel2Dotn = c.m_contactNormal2.dot(bodyB.internalGetDeltaLinearVelocity()) + c.m_relpos2CrossNormal.dot(bodyB.internalGetDeltaAngularVelocity());
  42. // const btScalar delta_rel_vel = deltaVel1Dotn-deltaVel2Dotn;
  43. deltaImpulse -= deltaVel1Dotn * c.m_jacDiagABInv;
  44. deltaImpulse -= deltaVel2Dotn * c.m_jacDiagABInv;
  45. const btScalar sum = btScalar(c.m_appliedImpulse) + deltaImpulse;
  46. if (sum < c.m_lowerLimit)
  47. {
  48. deltaImpulse = c.m_lowerLimit - c.m_appliedImpulse;
  49. c.m_appliedImpulse = c.m_lowerLimit;
  50. }
  51. else if (sum > c.m_upperLimit)
  52. {
  53. deltaImpulse = c.m_upperLimit - c.m_appliedImpulse;
  54. c.m_appliedImpulse = c.m_upperLimit;
  55. }
  56. else
  57. {
  58. c.m_appliedImpulse = sum;
  59. }
  60. bodyA.internalApplyImpulse(c.m_contactNormal1 * bodyA.internalGetInvMass(), c.m_angularComponentA, deltaImpulse);
  61. bodyB.internalApplyImpulse(c.m_contactNormal2 * bodyB.internalGetInvMass(), c.m_angularComponentB, deltaImpulse);
  62. return deltaImpulse * (1. / c.m_jacDiagABInv);
  63. }
  64. static btScalar gResolveSingleConstraintRowLowerLimit_scalar_reference(btSolverBody& bodyA, btSolverBody& bodyB, const btSolverConstraint& c)
  65. {
  66. btScalar deltaImpulse = c.m_rhs - btScalar(c.m_appliedImpulse) * c.m_cfm;
  67. const btScalar deltaVel1Dotn = c.m_contactNormal1.dot(bodyA.internalGetDeltaLinearVelocity()) + c.m_relpos1CrossNormal.dot(bodyA.internalGetDeltaAngularVelocity());
  68. const btScalar deltaVel2Dotn = c.m_contactNormal2.dot(bodyB.internalGetDeltaLinearVelocity()) + c.m_relpos2CrossNormal.dot(bodyB.internalGetDeltaAngularVelocity());
  69. deltaImpulse -= deltaVel1Dotn * c.m_jacDiagABInv;
  70. deltaImpulse -= deltaVel2Dotn * c.m_jacDiagABInv;
  71. const btScalar sum = btScalar(c.m_appliedImpulse) + deltaImpulse;
  72. if (sum < c.m_lowerLimit)
  73. {
  74. deltaImpulse = c.m_lowerLimit - c.m_appliedImpulse;
  75. c.m_appliedImpulse = c.m_lowerLimit;
  76. }
  77. else
  78. {
  79. c.m_appliedImpulse = sum;
  80. }
  81. bodyA.internalApplyImpulse(c.m_contactNormal1 * bodyA.internalGetInvMass(), c.m_angularComponentA, deltaImpulse);
  82. bodyB.internalApplyImpulse(c.m_contactNormal2 * bodyB.internalGetInvMass(), c.m_angularComponentB, deltaImpulse);
  83. return deltaImpulse * (1. / c.m_jacDiagABInv);
  84. }
  85. #ifdef USE_SIMD
  86. #include <emmintrin.h>
  87. #define btVecSplat(x, e) _mm_shuffle_ps(x, x, _MM_SHUFFLE(e, e, e, e))
  88. static inline __m128 btSimdDot3(__m128 vec0, __m128 vec1)
  89. {
  90. __m128 result = _mm_mul_ps(vec0, vec1);
  91. return _mm_add_ps(btVecSplat(result, 0), _mm_add_ps(btVecSplat(result, 1), btVecSplat(result, 2)));
  92. }
  93. #if defined(BT_ALLOW_SSE4)
  94. #include <intrin.h>
  95. #define USE_FMA 1
  96. #define USE_FMA3_INSTEAD_FMA4 1
  97. #define USE_SSE4_DOT 1
  98. #define SSE4_DP(a, b) _mm_dp_ps(a, b, 0x7f)
  99. #define SSE4_DP_FP(a, b) _mm_cvtss_f32(_mm_dp_ps(a, b, 0x7f))
  100. #if USE_SSE4_DOT
  101. #define DOT_PRODUCT(a, b) SSE4_DP(a, b)
  102. #else
  103. #define DOT_PRODUCT(a, b) btSimdDot3(a, b)
  104. #endif
  105. #if USE_FMA
  106. #if USE_FMA3_INSTEAD_FMA4
  107. // a*b + c
  108. #define FMADD(a, b, c) _mm_fmadd_ps(a, b, c)
  109. // -(a*b) + c
  110. #define FMNADD(a, b, c) _mm_fnmadd_ps(a, b, c)
  111. #else // USE_FMA3
  112. // a*b + c
  113. #define FMADD(a, b, c) _mm_macc_ps(a, b, c)
  114. // -(a*b) + c
  115. #define FMNADD(a, b, c) _mm_nmacc_ps(a, b, c)
  116. #endif
  117. #else // USE_FMA
  118. // c + a*b
  119. #define FMADD(a, b, c) _mm_add_ps(c, _mm_mul_ps(a, b))
  120. // c - a*b
  121. #define FMNADD(a, b, c) _mm_sub_ps(c, _mm_mul_ps(a, b))
  122. #endif
  123. #endif
  124. // Project Gauss Seidel or the equivalent Sequential Impulse
  125. static btScalar gResolveSingleConstraintRowGeneric_sse2(btSolverBody& bodyA, btSolverBody& bodyB, const btSolverConstraint& c)
  126. {
  127. __m128 cpAppliedImp = _mm_set1_ps(c.m_appliedImpulse);
  128. __m128 lowerLimit1 = _mm_set1_ps(c.m_lowerLimit);
  129. __m128 upperLimit1 = _mm_set1_ps(c.m_upperLimit);
  130. btSimdScalar deltaImpulse = _mm_sub_ps(_mm_set1_ps(c.m_rhs), _mm_mul_ps(_mm_set1_ps(c.m_appliedImpulse), _mm_set1_ps(c.m_cfm)));
  131. __m128 deltaVel1Dotn = _mm_add_ps(btSimdDot3(c.m_contactNormal1.mVec128, bodyA.internalGetDeltaLinearVelocity().mVec128), btSimdDot3(c.m_relpos1CrossNormal.mVec128, bodyA.internalGetDeltaAngularVelocity().mVec128));
  132. __m128 deltaVel2Dotn = _mm_add_ps(btSimdDot3(c.m_contactNormal2.mVec128, bodyB.internalGetDeltaLinearVelocity().mVec128), btSimdDot3(c.m_relpos2CrossNormal.mVec128, bodyB.internalGetDeltaAngularVelocity().mVec128));
  133. deltaImpulse = _mm_sub_ps(deltaImpulse, _mm_mul_ps(deltaVel1Dotn, _mm_set1_ps(c.m_jacDiagABInv)));
  134. deltaImpulse = _mm_sub_ps(deltaImpulse, _mm_mul_ps(deltaVel2Dotn, _mm_set1_ps(c.m_jacDiagABInv)));
  135. btSimdScalar sum = _mm_add_ps(cpAppliedImp, deltaImpulse);
  136. btSimdScalar resultLowerLess, resultUpperLess;
  137. resultLowerLess = _mm_cmplt_ps(sum, lowerLimit1);
  138. resultUpperLess = _mm_cmplt_ps(sum, upperLimit1);
  139. __m128 lowMinApplied = _mm_sub_ps(lowerLimit1, cpAppliedImp);
  140. deltaImpulse = _mm_or_ps(_mm_and_ps(resultLowerLess, lowMinApplied), _mm_andnot_ps(resultLowerLess, deltaImpulse));
  141. c.m_appliedImpulse = _mm_or_ps(_mm_and_ps(resultLowerLess, lowerLimit1), _mm_andnot_ps(resultLowerLess, sum));
  142. __m128 upperMinApplied = _mm_sub_ps(upperLimit1, cpAppliedImp);
  143. deltaImpulse = _mm_or_ps(_mm_and_ps(resultUpperLess, deltaImpulse), _mm_andnot_ps(resultUpperLess, upperMinApplied));
  144. c.m_appliedImpulse = _mm_or_ps(_mm_and_ps(resultUpperLess, c.m_appliedImpulse), _mm_andnot_ps(resultUpperLess, upperLimit1));
  145. __m128 linearComponentA = _mm_mul_ps(c.m_contactNormal1.mVec128, bodyA.internalGetInvMass().mVec128);
  146. __m128 linearComponentB = _mm_mul_ps((c.m_contactNormal2).mVec128, bodyB.internalGetInvMass().mVec128);
  147. __m128 impulseMagnitude = deltaImpulse;
  148. bodyA.internalGetDeltaLinearVelocity().mVec128 = _mm_add_ps(bodyA.internalGetDeltaLinearVelocity().mVec128, _mm_mul_ps(linearComponentA, impulseMagnitude));
  149. bodyA.internalGetDeltaAngularVelocity().mVec128 = _mm_add_ps(bodyA.internalGetDeltaAngularVelocity().mVec128, _mm_mul_ps(c.m_angularComponentA.mVec128, impulseMagnitude));
  150. bodyB.internalGetDeltaLinearVelocity().mVec128 = _mm_add_ps(bodyB.internalGetDeltaLinearVelocity().mVec128, _mm_mul_ps(linearComponentB, impulseMagnitude));
  151. bodyB.internalGetDeltaAngularVelocity().mVec128 = _mm_add_ps(bodyB.internalGetDeltaAngularVelocity().mVec128, _mm_mul_ps(c.m_angularComponentB.mVec128, impulseMagnitude));
  152. return deltaImpulse.m_floats[0] / c.m_jacDiagABInv;
  153. }
  154. // Enhanced version of gResolveSingleConstraintRowGeneric_sse2 with SSE4.1 and FMA3
  155. static btScalar gResolveSingleConstraintRowGeneric_sse4_1_fma3(btSolverBody& bodyA, btSolverBody& bodyB, const btSolverConstraint& c)
  156. {
  157. #if defined(BT_ALLOW_SSE4)
  158. __m128 tmp = _mm_set_ps1(c.m_jacDiagABInv);
  159. __m128 deltaImpulse = _mm_set_ps1(c.m_rhs - btScalar(c.m_appliedImpulse) * c.m_cfm);
  160. const __m128 lowerLimit = _mm_set_ps1(c.m_lowerLimit);
  161. const __m128 upperLimit = _mm_set_ps1(c.m_upperLimit);
  162. const __m128 deltaVel1Dotn = _mm_add_ps(DOT_PRODUCT(c.m_contactNormal1.mVec128, bodyA.internalGetDeltaLinearVelocity().mVec128), DOT_PRODUCT(c.m_relpos1CrossNormal.mVec128, bodyA.internalGetDeltaAngularVelocity().mVec128));
  163. const __m128 deltaVel2Dotn = _mm_add_ps(DOT_PRODUCT(c.m_contactNormal2.mVec128, bodyB.internalGetDeltaLinearVelocity().mVec128), DOT_PRODUCT(c.m_relpos2CrossNormal.mVec128, bodyB.internalGetDeltaAngularVelocity().mVec128));
  164. deltaImpulse = FMNADD(deltaVel1Dotn, tmp, deltaImpulse);
  165. deltaImpulse = FMNADD(deltaVel2Dotn, tmp, deltaImpulse);
  166. tmp = _mm_add_ps(c.m_appliedImpulse, deltaImpulse); // sum
  167. const __m128 maskLower = _mm_cmpgt_ps(tmp, lowerLimit);
  168. const __m128 maskUpper = _mm_cmpgt_ps(upperLimit, tmp);
  169. deltaImpulse = _mm_blendv_ps(_mm_sub_ps(lowerLimit, c.m_appliedImpulse), _mm_blendv_ps(_mm_sub_ps(upperLimit, c.m_appliedImpulse), deltaImpulse, maskUpper), maskLower);
  170. c.m_appliedImpulse = _mm_blendv_ps(lowerLimit, _mm_blendv_ps(upperLimit, tmp, maskUpper), maskLower);
  171. bodyA.internalGetDeltaLinearVelocity().mVec128 = FMADD(_mm_mul_ps(c.m_contactNormal1.mVec128, bodyA.internalGetInvMass().mVec128), deltaImpulse, bodyA.internalGetDeltaLinearVelocity().mVec128);
  172. bodyA.internalGetDeltaAngularVelocity().mVec128 = FMADD(c.m_angularComponentA.mVec128, deltaImpulse, bodyA.internalGetDeltaAngularVelocity().mVec128);
  173. bodyB.internalGetDeltaLinearVelocity().mVec128 = FMADD(_mm_mul_ps(c.m_contactNormal2.mVec128, bodyB.internalGetInvMass().mVec128), deltaImpulse, bodyB.internalGetDeltaLinearVelocity().mVec128);
  174. bodyB.internalGetDeltaAngularVelocity().mVec128 = FMADD(c.m_angularComponentB.mVec128, deltaImpulse, bodyB.internalGetDeltaAngularVelocity().mVec128);
  175. btSimdScalar deltaImp = deltaImpulse;
  176. return deltaImp.m_floats[0] * (1. / c.m_jacDiagABInv);
  177. #else
  178. return gResolveSingleConstraintRowGeneric_sse2(bodyA, bodyB, c);
  179. #endif
  180. }
  181. static btScalar gResolveSingleConstraintRowLowerLimit_sse2(btSolverBody& bodyA, btSolverBody& bodyB, const btSolverConstraint& c)
  182. {
  183. __m128 cpAppliedImp = _mm_set1_ps(c.m_appliedImpulse);
  184. __m128 lowerLimit1 = _mm_set1_ps(c.m_lowerLimit);
  185. __m128 upperLimit1 = _mm_set1_ps(c.m_upperLimit);
  186. btSimdScalar deltaImpulse = _mm_sub_ps(_mm_set1_ps(c.m_rhs), _mm_mul_ps(_mm_set1_ps(c.m_appliedImpulse), _mm_set1_ps(c.m_cfm)));
  187. __m128 deltaVel1Dotn = _mm_add_ps(btSimdDot3(c.m_contactNormal1.mVec128, bodyA.internalGetDeltaLinearVelocity().mVec128), btSimdDot3(c.m_relpos1CrossNormal.mVec128, bodyA.internalGetDeltaAngularVelocity().mVec128));
  188. __m128 deltaVel2Dotn = _mm_add_ps(btSimdDot3(c.m_contactNormal2.mVec128, bodyB.internalGetDeltaLinearVelocity().mVec128), btSimdDot3(c.m_relpos2CrossNormal.mVec128, bodyB.internalGetDeltaAngularVelocity().mVec128));
  189. deltaImpulse = _mm_sub_ps(deltaImpulse, _mm_mul_ps(deltaVel1Dotn, _mm_set1_ps(c.m_jacDiagABInv)));
  190. deltaImpulse = _mm_sub_ps(deltaImpulse, _mm_mul_ps(deltaVel2Dotn, _mm_set1_ps(c.m_jacDiagABInv)));
  191. btSimdScalar sum = _mm_add_ps(cpAppliedImp, deltaImpulse);
  192. btSimdScalar resultLowerLess, resultUpperLess;
  193. resultLowerLess = _mm_cmplt_ps(sum, lowerLimit1);
  194. resultUpperLess = _mm_cmplt_ps(sum, upperLimit1);
  195. __m128 lowMinApplied = _mm_sub_ps(lowerLimit1, cpAppliedImp);
  196. deltaImpulse = _mm_or_ps(_mm_and_ps(resultLowerLess, lowMinApplied), _mm_andnot_ps(resultLowerLess, deltaImpulse));
  197. c.m_appliedImpulse = _mm_or_ps(_mm_and_ps(resultLowerLess, lowerLimit1), _mm_andnot_ps(resultLowerLess, sum));
  198. __m128 linearComponentA = _mm_mul_ps(c.m_contactNormal1.mVec128, bodyA.internalGetInvMass().mVec128);
  199. __m128 linearComponentB = _mm_mul_ps(c.m_contactNormal2.mVec128, bodyB.internalGetInvMass().mVec128);
  200. __m128 impulseMagnitude = deltaImpulse;
  201. bodyA.internalGetDeltaLinearVelocity().mVec128 = _mm_add_ps(bodyA.internalGetDeltaLinearVelocity().mVec128, _mm_mul_ps(linearComponentA, impulseMagnitude));
  202. bodyA.internalGetDeltaAngularVelocity().mVec128 = _mm_add_ps(bodyA.internalGetDeltaAngularVelocity().mVec128, _mm_mul_ps(c.m_angularComponentA.mVec128, impulseMagnitude));
  203. bodyB.internalGetDeltaLinearVelocity().mVec128 = _mm_add_ps(bodyB.internalGetDeltaLinearVelocity().mVec128, _mm_mul_ps(linearComponentB, impulseMagnitude));
  204. bodyB.internalGetDeltaAngularVelocity().mVec128 = _mm_add_ps(bodyB.internalGetDeltaAngularVelocity().mVec128, _mm_mul_ps(c.m_angularComponentB.mVec128, impulseMagnitude));
  205. return deltaImpulse.m_floats[0] / c.m_jacDiagABInv;
  206. }
  207. // Enhanced version of gResolveSingleConstraintRowGeneric_sse2 with SSE4.1 and FMA3
  208. static btScalar gResolveSingleConstraintRowLowerLimit_sse4_1_fma3(btSolverBody& bodyA, btSolverBody& bodyB, const btSolverConstraint& c)
  209. {
  210. #ifdef BT_ALLOW_SSE4
  211. __m128 tmp = _mm_set_ps1(c.m_jacDiagABInv);
  212. __m128 deltaImpulse = _mm_set_ps1(c.m_rhs - btScalar(c.m_appliedImpulse) * c.m_cfm);
  213. const __m128 lowerLimit = _mm_set_ps1(c.m_lowerLimit);
  214. const __m128 deltaVel1Dotn = _mm_add_ps(DOT_PRODUCT(c.m_contactNormal1.mVec128, bodyA.internalGetDeltaLinearVelocity().mVec128), DOT_PRODUCT(c.m_relpos1CrossNormal.mVec128, bodyA.internalGetDeltaAngularVelocity().mVec128));
  215. const __m128 deltaVel2Dotn = _mm_add_ps(DOT_PRODUCT(c.m_contactNormal2.mVec128, bodyB.internalGetDeltaLinearVelocity().mVec128), DOT_PRODUCT(c.m_relpos2CrossNormal.mVec128, bodyB.internalGetDeltaAngularVelocity().mVec128));
  216. deltaImpulse = FMNADD(deltaVel1Dotn, tmp, deltaImpulse);
  217. deltaImpulse = FMNADD(deltaVel2Dotn, tmp, deltaImpulse);
  218. tmp = _mm_add_ps(c.m_appliedImpulse, deltaImpulse);
  219. const __m128 mask = _mm_cmpgt_ps(tmp, lowerLimit);
  220. deltaImpulse = _mm_blendv_ps(_mm_sub_ps(lowerLimit, c.m_appliedImpulse), deltaImpulse, mask);
  221. c.m_appliedImpulse = _mm_blendv_ps(lowerLimit, tmp, mask);
  222. bodyA.internalGetDeltaLinearVelocity().mVec128 = FMADD(_mm_mul_ps(c.m_contactNormal1.mVec128, bodyA.internalGetInvMass().mVec128), deltaImpulse, bodyA.internalGetDeltaLinearVelocity().mVec128);
  223. bodyA.internalGetDeltaAngularVelocity().mVec128 = FMADD(c.m_angularComponentA.mVec128, deltaImpulse, bodyA.internalGetDeltaAngularVelocity().mVec128);
  224. bodyB.internalGetDeltaLinearVelocity().mVec128 = FMADD(_mm_mul_ps(c.m_contactNormal2.mVec128, bodyB.internalGetInvMass().mVec128), deltaImpulse, bodyB.internalGetDeltaLinearVelocity().mVec128);
  225. bodyB.internalGetDeltaAngularVelocity().mVec128 = FMADD(c.m_angularComponentB.mVec128, deltaImpulse, bodyB.internalGetDeltaAngularVelocity().mVec128);
  226. btSimdScalar deltaImp = deltaImpulse;
  227. return deltaImp.m_floats[0] * (1. / c.m_jacDiagABInv);
  228. #else
  229. return gResolveSingleConstraintRowLowerLimit_sse2(bodyA, bodyB, c);
  230. #endif //BT_ALLOW_SSE4
  231. }
  232. #endif //USE_SIMD
  233. btScalar btSequentialImpulseConstraintSolver::resolveSingleConstraintRowGenericSIMD(btSolverBody& bodyA, btSolverBody& bodyB, const btSolverConstraint& c)
  234. {
  235. return m_resolveSingleConstraintRowGeneric(bodyA, bodyB, c);
  236. }
  237. // Project Gauss Seidel or the equivalent Sequential Impulse
  238. btScalar btSequentialImpulseConstraintSolver::resolveSingleConstraintRowGeneric(btSolverBody& bodyA, btSolverBody& bodyB, const btSolverConstraint& c)
  239. {
  240. return m_resolveSingleConstraintRowGeneric(bodyA, bodyB, c);
  241. }
  242. btScalar btSequentialImpulseConstraintSolver::resolveSingleConstraintRowLowerLimitSIMD(btSolverBody& bodyA, btSolverBody& bodyB, const btSolverConstraint& c)
  243. {
  244. return m_resolveSingleConstraintRowLowerLimit(bodyA, bodyB, c);
  245. }
  246. btScalar btSequentialImpulseConstraintSolver::resolveSingleConstraintRowLowerLimit(btSolverBody& bodyA, btSolverBody& bodyB, const btSolverConstraint& c)
  247. {
  248. return m_resolveSingleConstraintRowLowerLimit(bodyA, bodyB, c);
  249. }
  250. static btScalar gResolveSplitPenetrationImpulse_scalar_reference(
  251. btSolverBody& bodyA,
  252. btSolverBody& bodyB,
  253. const btSolverConstraint& c)
  254. {
  255. btScalar deltaImpulse = 0.f;
  256. if (c.m_rhsPenetration)
  257. {
  258. gNumSplitImpulseRecoveries++;
  259. deltaImpulse = c.m_rhsPenetration - btScalar(c.m_appliedPushImpulse) * c.m_cfm;
  260. const btScalar deltaVel1Dotn = c.m_contactNormal1.dot(bodyA.internalGetPushVelocity()) + c.m_relpos1CrossNormal.dot(bodyA.internalGetTurnVelocity());
  261. const btScalar deltaVel2Dotn = c.m_contactNormal2.dot(bodyB.internalGetPushVelocity()) + c.m_relpos2CrossNormal.dot(bodyB.internalGetTurnVelocity());
  262. deltaImpulse -= deltaVel1Dotn * c.m_jacDiagABInv;
  263. deltaImpulse -= deltaVel2Dotn * c.m_jacDiagABInv;
  264. const btScalar sum = btScalar(c.m_appliedPushImpulse) + deltaImpulse;
  265. if (sum < c.m_lowerLimit)
  266. {
  267. deltaImpulse = c.m_lowerLimit - c.m_appliedPushImpulse;
  268. c.m_appliedPushImpulse = c.m_lowerLimit;
  269. }
  270. else
  271. {
  272. c.m_appliedPushImpulse = sum;
  273. }
  274. bodyA.internalApplyPushImpulse(c.m_contactNormal1 * bodyA.internalGetInvMass(), c.m_angularComponentA, deltaImpulse);
  275. bodyB.internalApplyPushImpulse(c.m_contactNormal2 * bodyB.internalGetInvMass(), c.m_angularComponentB, deltaImpulse);
  276. }
  277. return deltaImpulse * (1. / c.m_jacDiagABInv);
  278. }
  279. static btScalar gResolveSplitPenetrationImpulse_sse2(btSolverBody& bodyA, btSolverBody& bodyB, const btSolverConstraint& c)
  280. {
  281. #ifdef USE_SIMD
  282. if (!c.m_rhsPenetration)
  283. return 0.f;
  284. gNumSplitImpulseRecoveries++;
  285. __m128 cpAppliedImp = _mm_set1_ps(c.m_appliedPushImpulse);
  286. __m128 lowerLimit1 = _mm_set1_ps(c.m_lowerLimit);
  287. __m128 upperLimit1 = _mm_set1_ps(c.m_upperLimit);
  288. __m128 deltaImpulse = _mm_sub_ps(_mm_set1_ps(c.m_rhsPenetration), _mm_mul_ps(_mm_set1_ps(c.m_appliedPushImpulse), _mm_set1_ps(c.m_cfm)));
  289. __m128 deltaVel1Dotn = _mm_add_ps(btSimdDot3(c.m_contactNormal1.mVec128, bodyA.internalGetPushVelocity().mVec128), btSimdDot3(c.m_relpos1CrossNormal.mVec128, bodyA.internalGetTurnVelocity().mVec128));
  290. __m128 deltaVel2Dotn = _mm_add_ps(btSimdDot3(c.m_contactNormal2.mVec128, bodyB.internalGetPushVelocity().mVec128), btSimdDot3(c.m_relpos2CrossNormal.mVec128, bodyB.internalGetTurnVelocity().mVec128));
  291. deltaImpulse = _mm_sub_ps(deltaImpulse, _mm_mul_ps(deltaVel1Dotn, _mm_set1_ps(c.m_jacDiagABInv)));
  292. deltaImpulse = _mm_sub_ps(deltaImpulse, _mm_mul_ps(deltaVel2Dotn, _mm_set1_ps(c.m_jacDiagABInv)));
  293. btSimdScalar sum = _mm_add_ps(cpAppliedImp, deltaImpulse);
  294. btSimdScalar resultLowerLess, resultUpperLess;
  295. resultLowerLess = _mm_cmplt_ps(sum, lowerLimit1);
  296. resultUpperLess = _mm_cmplt_ps(sum, upperLimit1);
  297. __m128 lowMinApplied = _mm_sub_ps(lowerLimit1, cpAppliedImp);
  298. deltaImpulse = _mm_or_ps(_mm_and_ps(resultLowerLess, lowMinApplied), _mm_andnot_ps(resultLowerLess, deltaImpulse));
  299. c.m_appliedPushImpulse = _mm_or_ps(_mm_and_ps(resultLowerLess, lowerLimit1), _mm_andnot_ps(resultLowerLess, sum));
  300. __m128 linearComponentA = _mm_mul_ps(c.m_contactNormal1.mVec128, bodyA.internalGetInvMass().mVec128);
  301. __m128 linearComponentB = _mm_mul_ps(c.m_contactNormal2.mVec128, bodyB.internalGetInvMass().mVec128);
  302. __m128 impulseMagnitude = deltaImpulse;
  303. bodyA.internalGetPushVelocity().mVec128 = _mm_add_ps(bodyA.internalGetPushVelocity().mVec128, _mm_mul_ps(linearComponentA, impulseMagnitude));
  304. bodyA.internalGetTurnVelocity().mVec128 = _mm_add_ps(bodyA.internalGetTurnVelocity().mVec128, _mm_mul_ps(c.m_angularComponentA.mVec128, impulseMagnitude));
  305. bodyB.internalGetPushVelocity().mVec128 = _mm_add_ps(bodyB.internalGetPushVelocity().mVec128, _mm_mul_ps(linearComponentB, impulseMagnitude));
  306. bodyB.internalGetTurnVelocity().mVec128 = _mm_add_ps(bodyB.internalGetTurnVelocity().mVec128, _mm_mul_ps(c.m_angularComponentB.mVec128, impulseMagnitude));
  307. btSimdScalar deltaImp = deltaImpulse;
  308. return deltaImp.m_floats[0] * (1. / c.m_jacDiagABInv);
  309. #else
  310. return gResolveSplitPenetrationImpulse_scalar_reference(bodyA, bodyB, c);
  311. #endif
  312. }
  313. btSequentialImpulseConstraintSolver::btSequentialImpulseConstraintSolver()
  314. {
  315. m_btSeed2 = 0;
  316. m_cachedSolverMode = 0;
  317. setupSolverFunctions(false);
  318. }
  319. void btSequentialImpulseConstraintSolver::setupSolverFunctions(bool useSimd)
  320. {
  321. m_resolveSingleConstraintRowGeneric = gResolveSingleConstraintRowGeneric_scalar_reference;
  322. m_resolveSingleConstraintRowLowerLimit = gResolveSingleConstraintRowLowerLimit_scalar_reference;
  323. m_resolveSplitPenetrationImpulse = gResolveSplitPenetrationImpulse_scalar_reference;
  324. if (useSimd)
  325. {
  326. #ifdef USE_SIMD
  327. m_resolveSingleConstraintRowGeneric = gResolveSingleConstraintRowGeneric_sse2;
  328. m_resolveSingleConstraintRowLowerLimit = gResolveSingleConstraintRowLowerLimit_sse2;
  329. m_resolveSplitPenetrationImpulse = gResolveSplitPenetrationImpulse_sse2;
  330. #ifdef BT_ALLOW_SSE4
  331. int cpuFeatures = btCpuFeatureUtility::getCpuFeatures();
  332. if ((cpuFeatures & btCpuFeatureUtility::CPU_FEATURE_FMA3) && (cpuFeatures & btCpuFeatureUtility::CPU_FEATURE_SSE4_1))
  333. {
  334. m_resolveSingleConstraintRowGeneric = gResolveSingleConstraintRowGeneric_sse4_1_fma3;
  335. m_resolveSingleConstraintRowLowerLimit = gResolveSingleConstraintRowLowerLimit_sse4_1_fma3;
  336. }
  337. #endif //BT_ALLOW_SSE4
  338. #endif //USE_SIMD
  339. }
  340. }
  341. btSequentialImpulseConstraintSolver::~btSequentialImpulseConstraintSolver()
  342. {
  343. }
  344. btSingleConstraintRowSolver btSequentialImpulseConstraintSolver::getScalarConstraintRowSolverGeneric()
  345. {
  346. return gResolveSingleConstraintRowGeneric_scalar_reference;
  347. }
  348. btSingleConstraintRowSolver btSequentialImpulseConstraintSolver::getScalarConstraintRowSolverLowerLimit()
  349. {
  350. return gResolveSingleConstraintRowLowerLimit_scalar_reference;
  351. }
  352. #ifdef USE_SIMD
  353. btSingleConstraintRowSolver btSequentialImpulseConstraintSolver::getSSE2ConstraintRowSolverGeneric()
  354. {
  355. return gResolveSingleConstraintRowGeneric_sse2;
  356. }
  357. btSingleConstraintRowSolver btSequentialImpulseConstraintSolver::getSSE2ConstraintRowSolverLowerLimit()
  358. {
  359. return gResolveSingleConstraintRowLowerLimit_sse2;
  360. }
  361. #ifdef BT_ALLOW_SSE4
  362. btSingleConstraintRowSolver btSequentialImpulseConstraintSolver::getSSE4_1ConstraintRowSolverGeneric()
  363. {
  364. return gResolveSingleConstraintRowGeneric_sse4_1_fma3;
  365. }
  366. btSingleConstraintRowSolver btSequentialImpulseConstraintSolver::getSSE4_1ConstraintRowSolverLowerLimit()
  367. {
  368. return gResolveSingleConstraintRowLowerLimit_sse4_1_fma3;
  369. }
  370. #endif //BT_ALLOW_SSE4
  371. #endif //USE_SIMD
  372. unsigned long btSequentialImpulseConstraintSolver::btRand2()
  373. {
  374. m_btSeed2 = (1664525L * m_btSeed2 + 1013904223L) & 0xffffffff;
  375. return m_btSeed2;
  376. }
  377. //See ODE: adam's all-int straightforward(?) dRandInt (0..n-1)
  378. int btSequentialImpulseConstraintSolver::btRandInt2(int n)
  379. {
  380. // seems good; xor-fold and modulus
  381. const unsigned long un = static_cast<unsigned long>(n);
  382. unsigned long r = btRand2();
  383. // note: probably more aggressive than it needs to be -- might be
  384. // able to get away without one or two of the innermost branches.
  385. if (un <= 0x00010000UL)
  386. {
  387. r ^= (r >> 16);
  388. if (un <= 0x00000100UL)
  389. {
  390. r ^= (r >> 8);
  391. if (un <= 0x00000010UL)
  392. {
  393. r ^= (r >> 4);
  394. if (un <= 0x00000004UL)
  395. {
  396. r ^= (r >> 2);
  397. if (un <= 0x00000002UL)
  398. {
  399. r ^= (r >> 1);
  400. }
  401. }
  402. }
  403. }
  404. }
  405. return (int)(r % un);
  406. }
  407. void btSequentialImpulseConstraintSolver::initSolverBody(btSolverBody* solverBody, btCollisionObject* collisionObject, btScalar timeStep)
  408. {
  409. btRigidBody* rb = collisionObject ? btRigidBody::upcast(collisionObject) : 0;
  410. solverBody->internalGetDeltaLinearVelocity().setValue(0.f, 0.f, 0.f);
  411. solverBody->internalGetDeltaAngularVelocity().setValue(0.f, 0.f, 0.f);
  412. solverBody->internalGetPushVelocity().setValue(0.f, 0.f, 0.f);
  413. solverBody->internalGetTurnVelocity().setValue(0.f, 0.f, 0.f);
  414. if (rb)
  415. {
  416. solverBody->m_worldTransform = rb->getWorldTransform();
  417. solverBody->internalSetInvMass(btVector3(rb->getInvMass(), rb->getInvMass(), rb->getInvMass()) * rb->getLinearFactor());
  418. solverBody->m_originalBody = rb;
  419. solverBody->m_angularFactor = rb->getAngularFactor();
  420. solverBody->m_linearFactor = rb->getLinearFactor();
  421. solverBody->m_linearVelocity = rb->getLinearVelocity();
  422. solverBody->m_angularVelocity = rb->getAngularVelocity();
  423. solverBody->m_externalForceImpulse = rb->getTotalForce() * rb->getInvMass() * timeStep;
  424. solverBody->m_externalTorqueImpulse = rb->getTotalTorque() * rb->getInvInertiaTensorWorld() * timeStep;
  425. }
  426. else
  427. {
  428. solverBody->m_worldTransform.setIdentity();
  429. solverBody->internalSetInvMass(btVector3(0, 0, 0));
  430. solverBody->m_originalBody = 0;
  431. solverBody->m_angularFactor.setValue(1, 1, 1);
  432. solverBody->m_linearFactor.setValue(1, 1, 1);
  433. solverBody->m_linearVelocity.setValue(0, 0, 0);
  434. solverBody->m_angularVelocity.setValue(0, 0, 0);
  435. solverBody->m_externalForceImpulse.setValue(0, 0, 0);
  436. solverBody->m_externalTorqueImpulse.setValue(0, 0, 0);
  437. }
  438. }
  439. btScalar btSequentialImpulseConstraintSolver::restitutionCurve(btScalar rel_vel, btScalar restitution, btScalar velocityThreshold)
  440. {
  441. //printf("rel_vel =%f\n", rel_vel);
  442. if (btFabs(rel_vel) < velocityThreshold)
  443. return 0.;
  444. btScalar rest = restitution * -rel_vel;
  445. return rest;
  446. }
  447. void btSequentialImpulseConstraintSolver::applyAnisotropicFriction(btCollisionObject* colObj, btVector3& frictionDirection, int frictionMode)
  448. {
  449. if (colObj && colObj->hasAnisotropicFriction(frictionMode))
  450. {
  451. // transform to local coordinates
  452. btVector3 loc_lateral = frictionDirection * colObj->getWorldTransform().getBasis();
  453. const btVector3& friction_scaling = colObj->getAnisotropicFriction();
  454. //apply anisotropic friction
  455. loc_lateral *= friction_scaling;
  456. // ... and transform it back to global coordinates
  457. frictionDirection = colObj->getWorldTransform().getBasis() * loc_lateral;
  458. }
  459. }
  460. void btSequentialImpulseConstraintSolver::setupFrictionConstraint(btSolverConstraint& solverConstraint, const btVector3& normalAxis, int solverBodyIdA, int solverBodyIdB, btManifoldPoint& cp, const btVector3& rel_pos1, const btVector3& rel_pos2, btCollisionObject* colObj0, btCollisionObject* colObj1, btScalar relaxation, const btContactSolverInfo& infoGlobal, btScalar desiredVelocity, btScalar cfmSlip)
  461. {
  462. btSolverBody& solverBodyA = m_tmpSolverBodyPool[solverBodyIdA];
  463. btSolverBody& solverBodyB = m_tmpSolverBodyPool[solverBodyIdB];
  464. btRigidBody* body0 = m_tmpSolverBodyPool[solverBodyIdA].m_originalBody;
  465. btRigidBody* bodyA = m_tmpSolverBodyPool[solverBodyIdB].m_originalBody;
  466. solverConstraint.m_solverBodyIdA = solverBodyIdA;
  467. solverConstraint.m_solverBodyIdB = solverBodyIdB;
  468. solverConstraint.m_friction = cp.m_combinedFriction;
  469. solverConstraint.m_originalContactPoint = 0;
  470. solverConstraint.m_appliedImpulse = 0.f;
  471. solverConstraint.m_appliedPushImpulse = 0.f;
  472. if (body0)
  473. {
  474. solverConstraint.m_contactNormal1 = normalAxis;
  475. btVector3 ftorqueAxis1 = rel_pos1.cross(solverConstraint.m_contactNormal1);
  476. solverConstraint.m_relpos1CrossNormal = ftorqueAxis1;
  477. solverConstraint.m_angularComponentA = body0->getInvInertiaTensorWorld() * ftorqueAxis1 * body0->getAngularFactor();
  478. }
  479. else
  480. {
  481. solverConstraint.m_contactNormal1.setZero();
  482. solverConstraint.m_relpos1CrossNormal.setZero();
  483. solverConstraint.m_angularComponentA.setZero();
  484. }
  485. if (bodyA)
  486. {
  487. solverConstraint.m_contactNormal2 = -normalAxis;
  488. btVector3 ftorqueAxis1 = rel_pos2.cross(solverConstraint.m_contactNormal2);
  489. solverConstraint.m_relpos2CrossNormal = ftorqueAxis1;
  490. solverConstraint.m_angularComponentB = bodyA->getInvInertiaTensorWorld() * ftorqueAxis1 * bodyA->getAngularFactor();
  491. }
  492. else
  493. {
  494. solverConstraint.m_contactNormal2.setZero();
  495. solverConstraint.m_relpos2CrossNormal.setZero();
  496. solverConstraint.m_angularComponentB.setZero();
  497. }
  498. {
  499. btVector3 vec;
  500. btScalar denom0 = 0.f;
  501. btScalar denom1 = 0.f;
  502. if (body0)
  503. {
  504. vec = (solverConstraint.m_angularComponentA).cross(rel_pos1);
  505. denom0 = body0->getInvMass() + normalAxis.dot(vec);
  506. }
  507. if (bodyA)
  508. {
  509. vec = (-solverConstraint.m_angularComponentB).cross(rel_pos2);
  510. denom1 = bodyA->getInvMass() + normalAxis.dot(vec);
  511. }
  512. btScalar denom = relaxation / (denom0 + denom1);
  513. solverConstraint.m_jacDiagABInv = denom;
  514. }
  515. {
  516. btScalar rel_vel;
  517. btScalar vel1Dotn = solverConstraint.m_contactNormal1.dot(body0 ? solverBodyA.m_linearVelocity + solverBodyA.m_externalForceImpulse : btVector3(0, 0, 0)) + solverConstraint.m_relpos1CrossNormal.dot(body0 ? solverBodyA.m_angularVelocity : btVector3(0, 0, 0));
  518. btScalar vel2Dotn = solverConstraint.m_contactNormal2.dot(bodyA ? solverBodyB.m_linearVelocity + solverBodyB.m_externalForceImpulse : btVector3(0, 0, 0)) + solverConstraint.m_relpos2CrossNormal.dot(bodyA ? solverBodyB.m_angularVelocity : btVector3(0, 0, 0));
  519. rel_vel = vel1Dotn + vel2Dotn;
  520. // btScalar positionalError = 0.f;
  521. btScalar velocityError = desiredVelocity - rel_vel;
  522. btScalar velocityImpulse = velocityError * solverConstraint.m_jacDiagABInv;
  523. btScalar penetrationImpulse = btScalar(0);
  524. if (cp.m_contactPointFlags & BT_CONTACT_FLAG_FRICTION_ANCHOR)
  525. {
  526. btScalar distance = (cp.getPositionWorldOnA() - cp.getPositionWorldOnB()).dot(normalAxis);
  527. btScalar positionalError = -distance * infoGlobal.m_frictionERP / infoGlobal.m_timeStep;
  528. penetrationImpulse = positionalError * solverConstraint.m_jacDiagABInv;
  529. }
  530. solverConstraint.m_rhs = penetrationImpulse + velocityImpulse;
  531. solverConstraint.m_rhsPenetration = 0.f;
  532. solverConstraint.m_cfm = cfmSlip;
  533. solverConstraint.m_lowerLimit = -solverConstraint.m_friction;
  534. solverConstraint.m_upperLimit = solverConstraint.m_friction;
  535. }
  536. }
  537. btSolverConstraint& btSequentialImpulseConstraintSolver::addFrictionConstraint(const btVector3& normalAxis, int solverBodyIdA, int solverBodyIdB, int frictionIndex, btManifoldPoint& cp, const btVector3& rel_pos1, const btVector3& rel_pos2, btCollisionObject* colObj0, btCollisionObject* colObj1, btScalar relaxation, const btContactSolverInfo& infoGlobal, btScalar desiredVelocity, btScalar cfmSlip)
  538. {
  539. btSolverConstraint& solverConstraint = m_tmpSolverContactFrictionConstraintPool.expandNonInitializing();
  540. solverConstraint.m_frictionIndex = frictionIndex;
  541. setupFrictionConstraint(solverConstraint, normalAxis, solverBodyIdA, solverBodyIdB, cp, rel_pos1, rel_pos2,
  542. colObj0, colObj1, relaxation, infoGlobal, desiredVelocity, cfmSlip);
  543. return solverConstraint;
  544. }
  545. void btSequentialImpulseConstraintSolver::setupTorsionalFrictionConstraint(btSolverConstraint& solverConstraint, const btVector3& normalAxis1, int solverBodyIdA, int solverBodyIdB,
  546. btManifoldPoint& cp, btScalar combinedTorsionalFriction, const btVector3& rel_pos1, const btVector3& rel_pos2,
  547. btCollisionObject* colObj0, btCollisionObject* colObj1, btScalar relaxation,
  548. btScalar desiredVelocity, btScalar cfmSlip)
  549. {
  550. btVector3 normalAxis(0, 0, 0);
  551. solverConstraint.m_contactNormal1 = normalAxis;
  552. solverConstraint.m_contactNormal2 = -normalAxis;
  553. btSolverBody& solverBodyA = m_tmpSolverBodyPool[solverBodyIdA];
  554. btSolverBody& solverBodyB = m_tmpSolverBodyPool[solverBodyIdB];
  555. btRigidBody* body0 = m_tmpSolverBodyPool[solverBodyIdA].m_originalBody;
  556. btRigidBody* bodyA = m_tmpSolverBodyPool[solverBodyIdB].m_originalBody;
  557. solverConstraint.m_solverBodyIdA = solverBodyIdA;
  558. solverConstraint.m_solverBodyIdB = solverBodyIdB;
  559. solverConstraint.m_friction = combinedTorsionalFriction;
  560. solverConstraint.m_originalContactPoint = 0;
  561. solverConstraint.m_appliedImpulse = 0.f;
  562. solverConstraint.m_appliedPushImpulse = 0.f;
  563. {
  564. btVector3 ftorqueAxis1 = -normalAxis1;
  565. solverConstraint.m_relpos1CrossNormal = ftorqueAxis1;
  566. solverConstraint.m_angularComponentA = body0 ? body0->getInvInertiaTensorWorld() * ftorqueAxis1 * body0->getAngularFactor() : btVector3(0, 0, 0);
  567. }
  568. {
  569. btVector3 ftorqueAxis1 = normalAxis1;
  570. solverConstraint.m_relpos2CrossNormal = ftorqueAxis1;
  571. solverConstraint.m_angularComponentB = bodyA ? bodyA->getInvInertiaTensorWorld() * ftorqueAxis1 * bodyA->getAngularFactor() : btVector3(0, 0, 0);
  572. }
  573. {
  574. btVector3 iMJaA = body0 ? body0->getInvInertiaTensorWorld() * solverConstraint.m_relpos1CrossNormal : btVector3(0, 0, 0);
  575. btVector3 iMJaB = bodyA ? bodyA->getInvInertiaTensorWorld() * solverConstraint.m_relpos2CrossNormal : btVector3(0, 0, 0);
  576. btScalar sum = 0;
  577. sum += iMJaA.dot(solverConstraint.m_relpos1CrossNormal);
  578. sum += iMJaB.dot(solverConstraint.m_relpos2CrossNormal);
  579. solverConstraint.m_jacDiagABInv = btScalar(1.) / sum;
  580. }
  581. {
  582. btScalar rel_vel;
  583. btScalar vel1Dotn = solverConstraint.m_contactNormal1.dot(body0 ? solverBodyA.m_linearVelocity + solverBodyA.m_externalForceImpulse : btVector3(0, 0, 0)) + solverConstraint.m_relpos1CrossNormal.dot(body0 ? solverBodyA.m_angularVelocity : btVector3(0, 0, 0));
  584. btScalar vel2Dotn = solverConstraint.m_contactNormal2.dot(bodyA ? solverBodyB.m_linearVelocity + solverBodyB.m_externalForceImpulse : btVector3(0, 0, 0)) + solverConstraint.m_relpos2CrossNormal.dot(bodyA ? solverBodyB.m_angularVelocity : btVector3(0, 0, 0));
  585. rel_vel = vel1Dotn + vel2Dotn;
  586. // btScalar positionalError = 0.f;
  587. btSimdScalar velocityError = desiredVelocity - rel_vel;
  588. btSimdScalar velocityImpulse = velocityError * btSimdScalar(solverConstraint.m_jacDiagABInv);
  589. solverConstraint.m_rhs = velocityImpulse;
  590. solverConstraint.m_cfm = cfmSlip;
  591. solverConstraint.m_lowerLimit = -solverConstraint.m_friction;
  592. solverConstraint.m_upperLimit = solverConstraint.m_friction;
  593. }
  594. }
  595. btSolverConstraint& btSequentialImpulseConstraintSolver::addTorsionalFrictionConstraint(const btVector3& normalAxis, int solverBodyIdA, int solverBodyIdB, int frictionIndex, btManifoldPoint& cp, btScalar combinedTorsionalFriction, const btVector3& rel_pos1, const btVector3& rel_pos2, btCollisionObject* colObj0, btCollisionObject* colObj1, btScalar relaxation, btScalar desiredVelocity, btScalar cfmSlip)
  596. {
  597. btSolverConstraint& solverConstraint = m_tmpSolverContactRollingFrictionConstraintPool.expandNonInitializing();
  598. solverConstraint.m_frictionIndex = frictionIndex;
  599. setupTorsionalFrictionConstraint(solverConstraint, normalAxis, solverBodyIdA, solverBodyIdB, cp, combinedTorsionalFriction, rel_pos1, rel_pos2,
  600. colObj0, colObj1, relaxation, desiredVelocity, cfmSlip);
  601. return solverConstraint;
  602. }
  603. int btSequentialImpulseConstraintSolver::getOrInitSolverBody(btCollisionObject& body, btScalar timeStep)
  604. {
  605. #if BT_THREADSAFE
  606. int solverBodyId = -1;
  607. const bool isRigidBodyType = btRigidBody::upcast(&body) != NULL;
  608. const bool isStaticOrKinematic = body.isStaticOrKinematicObject();
  609. const bool isKinematic = body.isKinematicObject();
  610. if (isRigidBodyType && !isStaticOrKinematic)
  611. {
  612. // dynamic body
  613. // Dynamic bodies can only be in one island, so it's safe to write to the companionId
  614. solverBodyId = body.getCompanionId();
  615. if (solverBodyId < 0)
  616. {
  617. solverBodyId = m_tmpSolverBodyPool.size();
  618. btSolverBody& solverBody = m_tmpSolverBodyPool.expand();
  619. initSolverBody(&solverBody, &body, timeStep);
  620. body.setCompanionId(solverBodyId);
  621. }
  622. }
  623. else if (isRigidBodyType && isKinematic)
  624. {
  625. //
  626. // NOTE: must test for kinematic before static because some kinematic objects also
  627. // identify as "static"
  628. //
  629. // Kinematic bodies can be in multiple islands at once, so it is a
  630. // race condition to write to them, so we use an alternate method
  631. // to record the solverBodyId
  632. int uniqueId = body.getWorldArrayIndex();
  633. const int INVALID_SOLVER_BODY_ID = -1;
  634. if (uniqueId >= m_kinematicBodyUniqueIdToSolverBodyTable.size())
  635. {
  636. m_kinematicBodyUniqueIdToSolverBodyTable.resize(uniqueId + 1, INVALID_SOLVER_BODY_ID);
  637. }
  638. solverBodyId = m_kinematicBodyUniqueIdToSolverBodyTable[uniqueId];
  639. // if no table entry yet,
  640. if (solverBodyId == INVALID_SOLVER_BODY_ID)
  641. {
  642. // create a table entry for this body
  643. solverBodyId = m_tmpSolverBodyPool.size();
  644. btSolverBody& solverBody = m_tmpSolverBodyPool.expand();
  645. initSolverBody(&solverBody, &body, timeStep);
  646. m_kinematicBodyUniqueIdToSolverBodyTable[uniqueId] = solverBodyId;
  647. }
  648. }
  649. else
  650. {
  651. bool isMultiBodyType = (body.getInternalType() & btCollisionObject::CO_FEATHERSTONE_LINK);
  652. // Incorrectly set collision object flags can degrade performance in various ways.
  653. if (!isMultiBodyType)
  654. {
  655. btAssert(body.isStaticOrKinematicObject());
  656. }
  657. //it could be a multibody link collider
  658. // all fixed bodies (inf mass) get mapped to a single solver id
  659. if (m_fixedBodyId < 0)
  660. {
  661. m_fixedBodyId = m_tmpSolverBodyPool.size();
  662. btSolverBody& fixedBody = m_tmpSolverBodyPool.expand();
  663. initSolverBody(&fixedBody, 0, timeStep);
  664. }
  665. solverBodyId = m_fixedBodyId;
  666. }
  667. btAssert(solverBodyId >= 0 && solverBodyId < m_tmpSolverBodyPool.size());
  668. return solverBodyId;
  669. #else // BT_THREADSAFE
  670. int solverBodyIdA = -1;
  671. if (body.getCompanionId() >= 0)
  672. {
  673. //body has already been converted
  674. solverBodyIdA = body.getCompanionId();
  675. btAssert(solverBodyIdA < m_tmpSolverBodyPool.size());
  676. }
  677. else
  678. {
  679. btRigidBody* rb = btRigidBody::upcast(&body);
  680. //convert both active and kinematic objects (for their velocity)
  681. if (rb && (rb->getInvMass() || rb->isKinematicObject()))
  682. {
  683. solverBodyIdA = m_tmpSolverBodyPool.size();
  684. btSolverBody& solverBody = m_tmpSolverBodyPool.expand();
  685. initSolverBody(&solverBody, &body, timeStep);
  686. body.setCompanionId(solverBodyIdA);
  687. }
  688. else
  689. {
  690. if (m_fixedBodyId < 0)
  691. {
  692. m_fixedBodyId = m_tmpSolverBodyPool.size();
  693. btSolverBody& fixedBody = m_tmpSolverBodyPool.expand();
  694. initSolverBody(&fixedBody, 0, timeStep);
  695. }
  696. return m_fixedBodyId;
  697. // return 0;//assume first one is a fixed solver body
  698. }
  699. }
  700. return solverBodyIdA;
  701. #endif // BT_THREADSAFE
  702. }
  703. #include <stdio.h>
  704. void btSequentialImpulseConstraintSolver::setupContactConstraint(btSolverConstraint& solverConstraint,
  705. int solverBodyIdA, int solverBodyIdB,
  706. btManifoldPoint& cp, const btContactSolverInfo& infoGlobal,
  707. btScalar& relaxation,
  708. const btVector3& rel_pos1, const btVector3& rel_pos2)
  709. {
  710. // const btVector3& pos1 = cp.getPositionWorldOnA();
  711. // const btVector3& pos2 = cp.getPositionWorldOnB();
  712. btSolverBody* bodyA = &m_tmpSolverBodyPool[solverBodyIdA];
  713. btSolverBody* bodyB = &m_tmpSolverBodyPool[solverBodyIdB];
  714. btRigidBody* rb0 = bodyA->m_originalBody;
  715. btRigidBody* rb1 = bodyB->m_originalBody;
  716. // btVector3 rel_pos1 = pos1 - colObj0->getWorldTransform().getOrigin();
  717. // btVector3 rel_pos2 = pos2 - colObj1->getWorldTransform().getOrigin();
  718. //rel_pos1 = pos1 - bodyA->getWorldTransform().getOrigin();
  719. //rel_pos2 = pos2 - bodyB->getWorldTransform().getOrigin();
  720. relaxation = infoGlobal.m_sor;
  721. btScalar invTimeStep = btScalar(1) / infoGlobal.m_timeStep;
  722. //cfm = 1 / ( dt * kp + kd )
  723. //erp = dt * kp / ( dt * kp + kd )
  724. btScalar cfm = infoGlobal.m_globalCfm;
  725. btScalar erp = infoGlobal.m_erp2;
  726. if ((cp.m_contactPointFlags & BT_CONTACT_FLAG_HAS_CONTACT_CFM) || (cp.m_contactPointFlags & BT_CONTACT_FLAG_HAS_CONTACT_ERP))
  727. {
  728. if (cp.m_contactPointFlags & BT_CONTACT_FLAG_HAS_CONTACT_CFM)
  729. cfm = cp.m_contactCFM;
  730. if (cp.m_contactPointFlags & BT_CONTACT_FLAG_HAS_CONTACT_ERP)
  731. erp = cp.m_contactERP;
  732. }
  733. else
  734. {
  735. if (cp.m_contactPointFlags & BT_CONTACT_FLAG_CONTACT_STIFFNESS_DAMPING)
  736. {
  737. btScalar denom = (infoGlobal.m_timeStep * cp.m_combinedContactStiffness1 + cp.m_combinedContactDamping1);
  738. if (denom < SIMD_EPSILON)
  739. {
  740. denom = SIMD_EPSILON;
  741. }
  742. cfm = btScalar(1) / denom;
  743. erp = (infoGlobal.m_timeStep * cp.m_combinedContactStiffness1) / denom;
  744. }
  745. }
  746. cfm *= invTimeStep;
  747. btVector3 torqueAxis0 = rel_pos1.cross(cp.m_normalWorldOnB);
  748. solverConstraint.m_angularComponentA = rb0 ? rb0->getInvInertiaTensorWorld() * torqueAxis0 * rb0->getAngularFactor() : btVector3(0, 0, 0);
  749. btVector3 torqueAxis1 = rel_pos2.cross(cp.m_normalWorldOnB);
  750. solverConstraint.m_angularComponentB = rb1 ? rb1->getInvInertiaTensorWorld() * -torqueAxis1 * rb1->getAngularFactor() : btVector3(0, 0, 0);
  751. {
  752. #ifdef COMPUTE_IMPULSE_DENOM
  753. btScalar denom0 = rb0->computeImpulseDenominator(pos1, cp.m_normalWorldOnB);
  754. btScalar denom1 = rb1->computeImpulseDenominator(pos2, cp.m_normalWorldOnB);
  755. #else
  756. btVector3 vec;
  757. btScalar denom0 = 0.f;
  758. btScalar denom1 = 0.f;
  759. if (rb0)
  760. {
  761. vec = (solverConstraint.m_angularComponentA).cross(rel_pos1);
  762. denom0 = rb0->getInvMass() + cp.m_normalWorldOnB.dot(vec);
  763. }
  764. if (rb1)
  765. {
  766. vec = (-solverConstraint.m_angularComponentB).cross(rel_pos2);
  767. denom1 = rb1->getInvMass() + cp.m_normalWorldOnB.dot(vec);
  768. }
  769. #endif //COMPUTE_IMPULSE_DENOM
  770. btScalar denom = relaxation / (denom0 + denom1 + cfm);
  771. solverConstraint.m_jacDiagABInv = denom;
  772. }
  773. if (rb0)
  774. {
  775. solverConstraint.m_contactNormal1 = cp.m_normalWorldOnB;
  776. solverConstraint.m_relpos1CrossNormal = torqueAxis0;
  777. }
  778. else
  779. {
  780. solverConstraint.m_contactNormal1.setZero();
  781. solverConstraint.m_relpos1CrossNormal.setZero();
  782. }
  783. if (rb1)
  784. {
  785. solverConstraint.m_contactNormal2 = -cp.m_normalWorldOnB;
  786. solverConstraint.m_relpos2CrossNormal = -torqueAxis1;
  787. }
  788. else
  789. {
  790. solverConstraint.m_contactNormal2.setZero();
  791. solverConstraint.m_relpos2CrossNormal.setZero();
  792. }
  793. btScalar restitution = 0.f;
  794. btScalar penetration = cp.getDistance() + infoGlobal.m_linearSlop;
  795. {
  796. btVector3 vel1, vel2;
  797. vel1 = rb0 ? rb0->getVelocityInLocalPoint(rel_pos1) : btVector3(0, 0, 0);
  798. vel2 = rb1 ? rb1->getVelocityInLocalPoint(rel_pos2) : btVector3(0, 0, 0);
  799. // btVector3 vel2 = rb1 ? rb1->getVelocityInLocalPoint(rel_pos2) : btVector3(0,0,0);
  800. btVector3 vel = vel1 - vel2;
  801. btScalar rel_vel = cp.m_normalWorldOnB.dot(vel);
  802. solverConstraint.m_friction = cp.m_combinedFriction;
  803. restitution = restitutionCurve(rel_vel, cp.m_combinedRestitution, infoGlobal.m_restitutionVelocityThreshold);
  804. if (restitution <= btScalar(0.))
  805. {
  806. restitution = 0.f;
  807. };
  808. }
  809. ///warm starting (or zero if disabled)
  810. if (infoGlobal.m_solverMode & SOLVER_USE_WARMSTARTING)
  811. {
  812. solverConstraint.m_appliedImpulse = cp.m_appliedImpulse * infoGlobal.m_warmstartingFactor;
  813. if (rb0)
  814. bodyA->internalApplyImpulse(solverConstraint.m_contactNormal1 * bodyA->internalGetInvMass(), solverConstraint.m_angularComponentA, solverConstraint.m_appliedImpulse);
  815. if (rb1)
  816. bodyB->internalApplyImpulse(-solverConstraint.m_contactNormal2 * bodyB->internalGetInvMass(), -solverConstraint.m_angularComponentB, -(btScalar)solverConstraint.m_appliedImpulse);
  817. }
  818. else
  819. {
  820. solverConstraint.m_appliedImpulse = 0.f;
  821. }
  822. solverConstraint.m_appliedPushImpulse = 0.f;
  823. {
  824. btVector3 externalForceImpulseA = bodyA->m_originalBody ? bodyA->m_externalForceImpulse : btVector3(0, 0, 0);
  825. btVector3 externalTorqueImpulseA = bodyA->m_originalBody ? bodyA->m_externalTorqueImpulse : btVector3(0, 0, 0);
  826. btVector3 externalForceImpulseB = bodyB->m_originalBody ? bodyB->m_externalForceImpulse : btVector3(0, 0, 0);
  827. btVector3 externalTorqueImpulseB = bodyB->m_originalBody ? bodyB->m_externalTorqueImpulse : btVector3(0, 0, 0);
  828. btScalar vel1Dotn = solverConstraint.m_contactNormal1.dot(bodyA->m_linearVelocity + externalForceImpulseA) + solverConstraint.m_relpos1CrossNormal.dot(bodyA->m_angularVelocity + externalTorqueImpulseA);
  829. btScalar vel2Dotn = solverConstraint.m_contactNormal2.dot(bodyB->m_linearVelocity + externalForceImpulseB) + solverConstraint.m_relpos2CrossNormal.dot(bodyB->m_angularVelocity + externalTorqueImpulseB);
  830. btScalar rel_vel = vel1Dotn + vel2Dotn;
  831. btScalar positionalError = 0.f;
  832. btScalar velocityError = restitution - rel_vel; // * damping;
  833. if (penetration > 0)
  834. {
  835. positionalError = 0;
  836. velocityError -= penetration * invTimeStep;
  837. }
  838. else
  839. {
  840. positionalError = -penetration * erp * invTimeStep;
  841. }
  842. btScalar penetrationImpulse = positionalError * solverConstraint.m_jacDiagABInv;
  843. btScalar velocityImpulse = velocityError * solverConstraint.m_jacDiagABInv;
  844. if (!infoGlobal.m_splitImpulse || (penetration > infoGlobal.m_splitImpulsePenetrationThreshold))
  845. {
  846. //combine position and velocity into rhs
  847. solverConstraint.m_rhs = penetrationImpulse + velocityImpulse; //-solverConstraint.m_contactNormal1.dot(bodyA->m_externalForce*bodyA->m_invMass-bodyB->m_externalForce/bodyB->m_invMass)*solverConstraint.m_jacDiagABInv;
  848. solverConstraint.m_rhsPenetration = 0.f;
  849. }
  850. else
  851. {
  852. //split position and velocity into rhs and m_rhsPenetration
  853. solverConstraint.m_rhs = velocityImpulse;
  854. solverConstraint.m_rhsPenetration = penetrationImpulse;
  855. }
  856. solverConstraint.m_cfm = cfm * solverConstraint.m_jacDiagABInv;
  857. solverConstraint.m_lowerLimit = 0;
  858. solverConstraint.m_upperLimit = 1e10f;
  859. }
  860. }
  861. void btSequentialImpulseConstraintSolver::setFrictionConstraintImpulse(btSolverConstraint& solverConstraint,
  862. int solverBodyIdA, int solverBodyIdB,
  863. btManifoldPoint& cp, const btContactSolverInfo& infoGlobal)
  864. {
  865. {
  866. btSolverConstraint& frictionConstraint1 = m_tmpSolverContactFrictionConstraintPool[solverConstraint.m_frictionIndex];
  867. frictionConstraint1.m_appliedImpulse = 0.f;
  868. }
  869. if ((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS))
  870. {
  871. btSolverConstraint& frictionConstraint2 = m_tmpSolverContactFrictionConstraintPool[solverConstraint.m_frictionIndex + 1];
  872. frictionConstraint2.m_appliedImpulse = 0.f;
  873. }
  874. }
  875. void btSequentialImpulseConstraintSolver::convertContact(btPersistentManifold* manifold, const btContactSolverInfo& infoGlobal)
  876. {
  877. btCollisionObject *colObj0 = 0, *colObj1 = 0;
  878. colObj0 = (btCollisionObject*)manifold->getBody0();
  879. colObj1 = (btCollisionObject*)manifold->getBody1();
  880. int solverBodyIdA = getOrInitSolverBody(*colObj0, infoGlobal.m_timeStep);
  881. int solverBodyIdB = getOrInitSolverBody(*colObj1, infoGlobal.m_timeStep);
  882. // btRigidBody* bodyA = btRigidBody::upcast(colObj0);
  883. // btRigidBody* bodyB = btRigidBody::upcast(colObj1);
  884. btSolverBody* solverBodyA = &m_tmpSolverBodyPool[solverBodyIdA];
  885. btSolverBody* solverBodyB = &m_tmpSolverBodyPool[solverBodyIdB];
  886. ///avoid collision response between two static objects
  887. if (!solverBodyA || (solverBodyA->m_invMass.fuzzyZero() && (!solverBodyB || solverBodyB->m_invMass.fuzzyZero())))
  888. return;
  889. int rollingFriction = 1;
  890. for (int j = 0; j < manifold->getNumContacts(); j++)
  891. {
  892. btManifoldPoint& cp = manifold->getContactPoint(j);
  893. if (cp.getDistance() <= manifold->getContactProcessingThreshold())
  894. {
  895. btVector3 rel_pos1;
  896. btVector3 rel_pos2;
  897. btScalar relaxation;
  898. int frictionIndex = m_tmpSolverContactConstraintPool.size();
  899. btSolverConstraint& solverConstraint = m_tmpSolverContactConstraintPool.expandNonInitializing();
  900. solverConstraint.m_solverBodyIdA = solverBodyIdA;
  901. solverConstraint.m_solverBodyIdB = solverBodyIdB;
  902. solverConstraint.m_originalContactPoint = &cp;
  903. const btVector3& pos1 = cp.getPositionWorldOnA();
  904. const btVector3& pos2 = cp.getPositionWorldOnB();
  905. rel_pos1 = pos1 - colObj0->getWorldTransform().getOrigin();
  906. rel_pos2 = pos2 - colObj1->getWorldTransform().getOrigin();
  907. btVector3 vel1;
  908. btVector3 vel2;
  909. solverBodyA->getVelocityInLocalPointNoDelta(rel_pos1, vel1);
  910. solverBodyB->getVelocityInLocalPointNoDelta(rel_pos2, vel2);
  911. btVector3 vel = vel1 - vel2;
  912. btScalar rel_vel = cp.m_normalWorldOnB.dot(vel);
  913. setupContactConstraint(solverConstraint, solverBodyIdA, solverBodyIdB, cp, infoGlobal, relaxation, rel_pos1, rel_pos2);
  914. /////setup the friction constraints
  915. solverConstraint.m_frictionIndex = m_tmpSolverContactFrictionConstraintPool.size();
  916. if ((cp.m_combinedRollingFriction > 0.f) && (rollingFriction > 0))
  917. {
  918. {
  919. addTorsionalFrictionConstraint(cp.m_normalWorldOnB, solverBodyIdA, solverBodyIdB, frictionIndex, cp, cp.m_combinedSpinningFriction, rel_pos1, rel_pos2, colObj0, colObj1, relaxation);
  920. btVector3 axis0, axis1;
  921. btPlaneSpace1(cp.m_normalWorldOnB, axis0, axis1);
  922. axis0.normalize();
  923. axis1.normalize();
  924. applyAnisotropicFriction(colObj0, axis0, btCollisionObject::CF_ANISOTROPIC_ROLLING_FRICTION);
  925. applyAnisotropicFriction(colObj1, axis0, btCollisionObject::CF_ANISOTROPIC_ROLLING_FRICTION);
  926. applyAnisotropicFriction(colObj0, axis1, btCollisionObject::CF_ANISOTROPIC_ROLLING_FRICTION);
  927. applyAnisotropicFriction(colObj1, axis1, btCollisionObject::CF_ANISOTROPIC_ROLLING_FRICTION);
  928. if (axis0.length() > 0.001)
  929. addTorsionalFrictionConstraint(axis0, solverBodyIdA, solverBodyIdB, frictionIndex, cp,
  930. cp.m_combinedRollingFriction, rel_pos1, rel_pos2, colObj0, colObj1, relaxation);
  931. if (axis1.length() > 0.001)
  932. addTorsionalFrictionConstraint(axis1, solverBodyIdA, solverBodyIdB, frictionIndex, cp,
  933. cp.m_combinedRollingFriction, rel_pos1, rel_pos2, colObj0, colObj1, relaxation);
  934. }
  935. }
  936. ///Bullet has several options to set the friction directions
  937. ///By default, each contact has only a single friction direction that is recomputed automatically very frame
  938. ///based on the relative linear velocity.
  939. ///If the relative velocity it zero, it will automatically compute a friction direction.
  940. ///You can also enable two friction directions, using the SOLVER_USE_2_FRICTION_DIRECTIONS.
  941. ///In that case, the second friction direction will be orthogonal to both contact normal and first friction direction.
  942. ///
  943. ///If you choose SOLVER_DISABLE_VELOCITY_DEPENDENT_FRICTION_DIRECTION, then the friction will be independent from the relative projected velocity.
  944. ///
  945. ///The user can manually override the friction directions for certain contacts using a contact callback,
  946. ///and use contactPoint.m_contactPointFlags |= BT_CONTACT_FLAG_LATERAL_FRICTION_INITIALIZED
  947. ///In that case, you can set the target relative motion in each friction direction (cp.m_contactMotion1 and cp.m_contactMotion2)
  948. ///this will give a conveyor belt effect
  949. ///
  950. if (!(infoGlobal.m_solverMode & SOLVER_ENABLE_FRICTION_DIRECTION_CACHING) || !(cp.m_contactPointFlags & BT_CONTACT_FLAG_LATERAL_FRICTION_INITIALIZED))
  951. {
  952. cp.m_lateralFrictionDir1 = vel - cp.m_normalWorldOnB * rel_vel;
  953. btScalar lat_rel_vel = cp.m_lateralFrictionDir1.length2();
  954. if (!(infoGlobal.m_solverMode & SOLVER_DISABLE_VELOCITY_DEPENDENT_FRICTION_DIRECTION) && lat_rel_vel > SIMD_EPSILON)
  955. {
  956. cp.m_lateralFrictionDir1 *= 1.f / btSqrt(lat_rel_vel);
  957. applyAnisotropicFriction(colObj0, cp.m_lateralFrictionDir1, btCollisionObject::CF_ANISOTROPIC_FRICTION);
  958. applyAnisotropicFriction(colObj1, cp.m_lateralFrictionDir1, btCollisionObject::CF_ANISOTROPIC_FRICTION);
  959. addFrictionConstraint(cp.m_lateralFrictionDir1, solverBodyIdA, solverBodyIdB, frictionIndex, cp, rel_pos1, rel_pos2, colObj0, colObj1, relaxation, infoGlobal);
  960. if ((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS))
  961. {
  962. cp.m_lateralFrictionDir2 = cp.m_lateralFrictionDir1.cross(cp.m_normalWorldOnB);
  963. cp.m_lateralFrictionDir2.normalize(); //??
  964. applyAnisotropicFriction(colObj0, cp.m_lateralFrictionDir2, btCollisionObject::CF_ANISOTROPIC_FRICTION);
  965. applyAnisotropicFriction(colObj1, cp.m_lateralFrictionDir2, btCollisionObject::CF_ANISOTROPIC_FRICTION);
  966. addFrictionConstraint(cp.m_lateralFrictionDir2, solverBodyIdA, solverBodyIdB, frictionIndex, cp, rel_pos1, rel_pos2, colObj0, colObj1, relaxation, infoGlobal);
  967. }
  968. }
  969. else
  970. {
  971. btPlaneSpace1(cp.m_normalWorldOnB, cp.m_lateralFrictionDir1, cp.m_lateralFrictionDir2);
  972. applyAnisotropicFriction(colObj0, cp.m_lateralFrictionDir1, btCollisionObject::CF_ANISOTROPIC_FRICTION);
  973. applyAnisotropicFriction(colObj1, cp.m_lateralFrictionDir1, btCollisionObject::CF_ANISOTROPIC_FRICTION);
  974. addFrictionConstraint(cp.m_lateralFrictionDir1, solverBodyIdA, solverBodyIdB, frictionIndex, cp, rel_pos1, rel_pos2, colObj0, colObj1, relaxation, infoGlobal);
  975. if ((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS))
  976. {
  977. applyAnisotropicFriction(colObj0, cp.m_lateralFrictionDir2, btCollisionObject::CF_ANISOTROPIC_FRICTION);
  978. applyAnisotropicFriction(colObj1, cp.m_lateralFrictionDir2, btCollisionObject::CF_ANISOTROPIC_FRICTION);
  979. addFrictionConstraint(cp.m_lateralFrictionDir2, solverBodyIdA, solverBodyIdB, frictionIndex, cp, rel_pos1, rel_pos2, colObj0, colObj1, relaxation, infoGlobal);
  980. }
  981. if ((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS) && (infoGlobal.m_solverMode & SOLVER_DISABLE_VELOCITY_DEPENDENT_FRICTION_DIRECTION))
  982. {
  983. cp.m_contactPointFlags |= BT_CONTACT_FLAG_LATERAL_FRICTION_INITIALIZED;
  984. }
  985. }
  986. }
  987. else
  988. {
  989. addFrictionConstraint(cp.m_lateralFrictionDir1, solverBodyIdA, solverBodyIdB, frictionIndex, cp, rel_pos1, rel_pos2, colObj0, colObj1, relaxation, infoGlobal, cp.m_contactMotion1, cp.m_frictionCFM);
  990. if ((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS))
  991. addFrictionConstraint(cp.m_lateralFrictionDir2, solverBodyIdA, solverBodyIdB, frictionIndex, cp, rel_pos1, rel_pos2, colObj0, colObj1, relaxation, infoGlobal, cp.m_contactMotion2, cp.m_frictionCFM);
  992. }
  993. setFrictionConstraintImpulse(solverConstraint, solverBodyIdA, solverBodyIdB, cp, infoGlobal);
  994. }
  995. }
  996. }
  997. void btSequentialImpulseConstraintSolver::convertContacts(btPersistentManifold** manifoldPtr, int numManifolds, const btContactSolverInfo& infoGlobal)
  998. {
  999. int i;
  1000. btPersistentManifold* manifold = 0;
  1001. // btCollisionObject* colObj0=0,*colObj1=0;
  1002. for (i = 0; i < numManifolds; i++)
  1003. {
  1004. manifold = manifoldPtr[i];
  1005. convertContact(manifold, infoGlobal);
  1006. }
  1007. }
  1008. void btSequentialImpulseConstraintSolver::convertJoint(btSolverConstraint* currentConstraintRow,
  1009. btTypedConstraint* constraint,
  1010. const btTypedConstraint::btConstraintInfo1& info1,
  1011. int solverBodyIdA,
  1012. int solverBodyIdB,
  1013. const btContactSolverInfo& infoGlobal)
  1014. {
  1015. const btRigidBody& rbA = constraint->getRigidBodyA();
  1016. const btRigidBody& rbB = constraint->getRigidBodyB();
  1017. const btSolverBody* bodyAPtr = &m_tmpSolverBodyPool[solverBodyIdA];
  1018. const btSolverBody* bodyBPtr = &m_tmpSolverBodyPool[solverBodyIdB];
  1019. int overrideNumSolverIterations = constraint->getOverrideNumSolverIterations() > 0 ? constraint->getOverrideNumSolverIterations() : infoGlobal.m_numIterations;
  1020. if (overrideNumSolverIterations > m_maxOverrideNumSolverIterations)
  1021. m_maxOverrideNumSolverIterations = overrideNumSolverIterations;
  1022. for (int j = 0; j < info1.m_numConstraintRows; j++)
  1023. {
  1024. memset(&currentConstraintRow[j], 0, sizeof(btSolverConstraint));
  1025. currentConstraintRow[j].m_lowerLimit = -SIMD_INFINITY;
  1026. currentConstraintRow[j].m_upperLimit = SIMD_INFINITY;
  1027. currentConstraintRow[j].m_appliedImpulse = 0.f;
  1028. currentConstraintRow[j].m_appliedPushImpulse = 0.f;
  1029. currentConstraintRow[j].m_solverBodyIdA = solverBodyIdA;
  1030. currentConstraintRow[j].m_solverBodyIdB = solverBodyIdB;
  1031. currentConstraintRow[j].m_overrideNumSolverIterations = overrideNumSolverIterations;
  1032. }
  1033. // these vectors are already cleared in initSolverBody, no need to redundantly clear again
  1034. btAssert(bodyAPtr->getDeltaLinearVelocity().isZero());
  1035. btAssert(bodyAPtr->getDeltaAngularVelocity().isZero());
  1036. btAssert(bodyAPtr->getPushVelocity().isZero());
  1037. btAssert(bodyAPtr->getTurnVelocity().isZero());
  1038. btAssert(bodyBPtr->getDeltaLinearVelocity().isZero());
  1039. btAssert(bodyBPtr->getDeltaAngularVelocity().isZero());
  1040. btAssert(bodyBPtr->getPushVelocity().isZero());
  1041. btAssert(bodyBPtr->getTurnVelocity().isZero());
  1042. //bodyAPtr->internalGetDeltaLinearVelocity().setValue(0.f,0.f,0.f);
  1043. //bodyAPtr->internalGetDeltaAngularVelocity().setValue(0.f,0.f,0.f);
  1044. //bodyAPtr->internalGetPushVelocity().setValue(0.f,0.f,0.f);
  1045. //bodyAPtr->internalGetTurnVelocity().setValue(0.f,0.f,0.f);
  1046. //bodyBPtr->internalGetDeltaLinearVelocity().setValue(0.f,0.f,0.f);
  1047. //bodyBPtr->internalGetDeltaAngularVelocity().setValue(0.f,0.f,0.f);
  1048. //bodyBPtr->internalGetPushVelocity().setValue(0.f,0.f,0.f);
  1049. //bodyBPtr->internalGetTurnVelocity().setValue(0.f,0.f,0.f);
  1050. btTypedConstraint::btConstraintInfo2 info2;
  1051. info2.fps = 1.f / infoGlobal.m_timeStep;
  1052. info2.erp = infoGlobal.m_erp;
  1053. info2.m_J1linearAxis = currentConstraintRow->m_contactNormal1;
  1054. info2.m_J1angularAxis = currentConstraintRow->m_relpos1CrossNormal;
  1055. info2.m_J2linearAxis = currentConstraintRow->m_contactNormal2;
  1056. info2.m_J2angularAxis = currentConstraintRow->m_relpos2CrossNormal;
  1057. info2.rowskip = sizeof(btSolverConstraint) / sizeof(btScalar); //check this
  1058. ///the size of btSolverConstraint needs be a multiple of btScalar
  1059. btAssert(info2.rowskip * sizeof(btScalar) == sizeof(btSolverConstraint));
  1060. info2.m_constraintError = &currentConstraintRow->m_rhs;
  1061. currentConstraintRow->m_cfm = infoGlobal.m_globalCfm;
  1062. info2.m_damping = infoGlobal.m_damping;
  1063. info2.cfm = &currentConstraintRow->m_cfm;
  1064. info2.m_lowerLimit = &currentConstraintRow->m_lowerLimit;
  1065. info2.m_upperLimit = &currentConstraintRow->m_upperLimit;
  1066. info2.m_numIterations = infoGlobal.m_numIterations;
  1067. constraint->getInfo2(&info2);
  1068. ///finalize the constraint setup
  1069. for (int j = 0; j < info1.m_numConstraintRows; j++)
  1070. {
  1071. btSolverConstraint& solverConstraint = currentConstraintRow[j];
  1072. if (solverConstraint.m_upperLimit >= constraint->getBreakingImpulseThreshold())
  1073. {
  1074. solverConstraint.m_upperLimit = constraint->getBreakingImpulseThreshold();
  1075. }
  1076. if (solverConstraint.m_lowerLimit <= -constraint->getBreakingImpulseThreshold())
  1077. {
  1078. solverConstraint.m_lowerLimit = -constraint->getBreakingImpulseThreshold();
  1079. }
  1080. solverConstraint.m_originalContactPoint = constraint;
  1081. {
  1082. const btVector3& ftorqueAxis1 = solverConstraint.m_relpos1CrossNormal;
  1083. solverConstraint.m_angularComponentA = constraint->getRigidBodyA().getInvInertiaTensorWorld() * ftorqueAxis1 * constraint->getRigidBodyA().getAngularFactor();
  1084. }
  1085. {
  1086. const btVector3& ftorqueAxis2 = solverConstraint.m_relpos2CrossNormal;
  1087. solverConstraint.m_angularComponentB = constraint->getRigidBodyB().getInvInertiaTensorWorld() * ftorqueAxis2 * constraint->getRigidBodyB().getAngularFactor();
  1088. }
  1089. {
  1090. btVector3 iMJlA = solverConstraint.m_contactNormal1 * rbA.getInvMass();
  1091. btVector3 iMJaA = rbA.getInvInertiaTensorWorld() * solverConstraint.m_relpos1CrossNormal;
  1092. btVector3 iMJlB = solverConstraint.m_contactNormal2 * rbB.getInvMass(); //sign of normal?
  1093. btVector3 iMJaB = rbB.getInvInertiaTensorWorld() * solverConstraint.m_relpos2CrossNormal;
  1094. btScalar sum = iMJlA.dot(solverConstraint.m_contactNormal1);
  1095. sum += iMJaA.dot(solverConstraint.m_relpos1CrossNormal);
  1096. sum += iMJlB.dot(solverConstraint.m_contactNormal2);
  1097. sum += iMJaB.dot(solverConstraint.m_relpos2CrossNormal);
  1098. btScalar fsum = btFabs(sum);
  1099. btAssert(fsum > SIMD_EPSILON);
  1100. btScalar sorRelaxation = 1.f; //todo: get from globalInfo?
  1101. solverConstraint.m_jacDiagABInv = fsum > SIMD_EPSILON ? sorRelaxation / sum : 0.f;
  1102. }
  1103. {
  1104. btScalar rel_vel;
  1105. btVector3 externalForceImpulseA = bodyAPtr->m_originalBody ? bodyAPtr->m_externalForceImpulse : btVector3(0, 0, 0);
  1106. btVector3 externalTorqueImpulseA = bodyAPtr->m_originalBody ? bodyAPtr->m_externalTorqueImpulse : btVector3(0, 0, 0);
  1107. btVector3 externalForceImpulseB = bodyBPtr->m_originalBody ? bodyBPtr->m_externalForceImpulse : btVector3(0, 0, 0);
  1108. btVector3 externalTorqueImpulseB = bodyBPtr->m_originalBody ? bodyBPtr->m_externalTorqueImpulse : btVector3(0, 0, 0);
  1109. btScalar vel1Dotn = solverConstraint.m_contactNormal1.dot(rbA.getLinearVelocity() + externalForceImpulseA) + solverConstraint.m_relpos1CrossNormal.dot(rbA.getAngularVelocity() + externalTorqueImpulseA);
  1110. btScalar vel2Dotn = solverConstraint.m_contactNormal2.dot(rbB.getLinearVelocity() + externalForceImpulseB) + solverConstraint.m_relpos2CrossNormal.dot(rbB.getAngularVelocity() + externalTorqueImpulseB);
  1111. rel_vel = vel1Dotn + vel2Dotn;
  1112. btScalar restitution = 0.f;
  1113. btScalar positionalError = solverConstraint.m_rhs; //already filled in by getConstraintInfo2
  1114. btScalar velocityError = restitution - rel_vel * info2.m_damping;
  1115. btScalar penetrationImpulse = positionalError * solverConstraint.m_jacDiagABInv;
  1116. btScalar velocityImpulse = velocityError * solverConstraint.m_jacDiagABInv;
  1117. solverConstraint.m_rhs = penetrationImpulse + velocityImpulse;
  1118. solverConstraint.m_appliedImpulse = 0.f;
  1119. }
  1120. }
  1121. }
  1122. void btSequentialImpulseConstraintSolver::convertJoints(btTypedConstraint** constraints, int numConstraints, const btContactSolverInfo& infoGlobal)
  1123. {
  1124. BT_PROFILE("convertJoints");
  1125. for (int j = 0; j < numConstraints; j++)
  1126. {
  1127. btTypedConstraint* constraint = constraints[j];
  1128. constraint->buildJacobian();
  1129. constraint->internalSetAppliedImpulse(0.0f);
  1130. }
  1131. int totalNumRows = 0;
  1132. m_tmpConstraintSizesPool.resizeNoInitialize(numConstraints);
  1133. //calculate the total number of contraint rows
  1134. for (int i = 0; i < numConstraints; i++)
  1135. {
  1136. btTypedConstraint::btConstraintInfo1& info1 = m_tmpConstraintSizesPool[i];
  1137. btJointFeedback* fb = constraints[i]->getJointFeedback();
  1138. if (fb)
  1139. {
  1140. fb->m_appliedForceBodyA.setZero();
  1141. fb->m_appliedTorqueBodyA.setZero();
  1142. fb->m_appliedForceBodyB.setZero();
  1143. fb->m_appliedTorqueBodyB.setZero();
  1144. }
  1145. if (constraints[i]->isEnabled())
  1146. {
  1147. constraints[i]->getInfo1(&info1);
  1148. }
  1149. else
  1150. {
  1151. info1.m_numConstraintRows = 0;
  1152. info1.nub = 0;
  1153. }
  1154. totalNumRows += info1.m_numConstraintRows;
  1155. }
  1156. m_tmpSolverNonContactConstraintPool.resizeNoInitialize(totalNumRows);
  1157. ///setup the btSolverConstraints
  1158. int currentRow = 0;
  1159. for (int i = 0; i < numConstraints; i++)
  1160. {
  1161. const btTypedConstraint::btConstraintInfo1& info1 = m_tmpConstraintSizesPool[i];
  1162. if (info1.m_numConstraintRows)
  1163. {
  1164. btAssert(currentRow < totalNumRows);
  1165. btSolverConstraint* currentConstraintRow = &m_tmpSolverNonContactConstraintPool[currentRow];
  1166. btTypedConstraint* constraint = constraints[i];
  1167. btRigidBody& rbA = constraint->getRigidBodyA();
  1168. btRigidBody& rbB = constraint->getRigidBodyB();
  1169. int solverBodyIdA = getOrInitSolverBody(rbA, infoGlobal.m_timeStep);
  1170. int solverBodyIdB = getOrInitSolverBody(rbB, infoGlobal.m_timeStep);
  1171. convertJoint(currentConstraintRow, constraint, info1, solverBodyIdA, solverBodyIdB, infoGlobal);
  1172. }
  1173. currentRow += info1.m_numConstraintRows;
  1174. }
  1175. }
  1176. void btSequentialImpulseConstraintSolver::convertBodies(btCollisionObject** bodies, int numBodies, const btContactSolverInfo& infoGlobal)
  1177. {
  1178. BT_PROFILE("convertBodies");
  1179. for (int i = 0; i < numBodies; i++)
  1180. {
  1181. bodies[i]->setCompanionId(-1);
  1182. }
  1183. #if BT_THREADSAFE
  1184. m_kinematicBodyUniqueIdToSolverBodyTable.resize(0);
  1185. #endif // BT_THREADSAFE
  1186. m_tmpSolverBodyPool.reserve(numBodies + 1);
  1187. m_tmpSolverBodyPool.resize(0);
  1188. //btSolverBody& fixedBody = m_tmpSolverBodyPool.expand();
  1189. //initSolverBody(&fixedBody,0);
  1190. for (int i = 0; i < numBodies; i++)
  1191. {
  1192. int bodyId = getOrInitSolverBody(*bodies[i], infoGlobal.m_timeStep);
  1193. btRigidBody* body = btRigidBody::upcast(bodies[i]);
  1194. if (body && body->getInvMass())
  1195. {
  1196. btSolverBody& solverBody = m_tmpSolverBodyPool[bodyId];
  1197. btVector3 gyroForce(0, 0, 0);
  1198. if (body->getFlags() & BT_ENABLE_GYROSCOPIC_FORCE_EXPLICIT)
  1199. {
  1200. gyroForce = body->computeGyroscopicForceExplicit(infoGlobal.m_maxGyroscopicForce);
  1201. solverBody.m_externalTorqueImpulse -= gyroForce * body->getInvInertiaTensorWorld() * infoGlobal.m_timeStep;
  1202. }
  1203. if (body->getFlags() & BT_ENABLE_GYROSCOPIC_FORCE_IMPLICIT_WORLD)
  1204. {
  1205. gyroForce = body->computeGyroscopicImpulseImplicit_World(infoGlobal.m_timeStep);
  1206. solverBody.m_externalTorqueImpulse += gyroForce;
  1207. }
  1208. if (body->getFlags() & BT_ENABLE_GYROSCOPIC_FORCE_IMPLICIT_BODY)
  1209. {
  1210. gyroForce = body->computeGyroscopicImpulseImplicit_Body(infoGlobal.m_timeStep);
  1211. solverBody.m_externalTorqueImpulse += gyroForce;
  1212. }
  1213. }
  1214. }
  1215. }
  1216. btScalar btSequentialImpulseConstraintSolver::solveGroupCacheFriendlySetup(btCollisionObject** bodies, int numBodies, btPersistentManifold** manifoldPtr, int numManifolds, btTypedConstraint** constraints, int numConstraints, const btContactSolverInfo& infoGlobal, btIDebugDraw* debugDrawer)
  1217. {
  1218. m_fixedBodyId = -1;
  1219. BT_PROFILE("solveGroupCacheFriendlySetup");
  1220. (void)debugDrawer;
  1221. // if solver mode has changed,
  1222. if (infoGlobal.m_solverMode != m_cachedSolverMode)
  1223. {
  1224. // update solver functions to use SIMD or non-SIMD
  1225. bool useSimd = !!(infoGlobal.m_solverMode & SOLVER_SIMD);
  1226. setupSolverFunctions(useSimd);
  1227. m_cachedSolverMode = infoGlobal.m_solverMode;
  1228. }
  1229. m_maxOverrideNumSolverIterations = 0;
  1230. #ifdef BT_ADDITIONAL_DEBUG
  1231. //make sure that dynamic bodies exist for all (enabled) constraints
  1232. for (int i = 0; i < numConstraints; i++)
  1233. {
  1234. btTypedConstraint* constraint = constraints[i];
  1235. if (constraint->isEnabled())
  1236. {
  1237. if (!constraint->getRigidBodyA().isStaticOrKinematicObject())
  1238. {
  1239. bool found = false;
  1240. for (int b = 0; b < numBodies; b++)
  1241. {
  1242. if (&constraint->getRigidBodyA() == bodies[b])
  1243. {
  1244. found = true;
  1245. break;
  1246. }
  1247. }
  1248. btAssert(found);
  1249. }
  1250. if (!constraint->getRigidBodyB().isStaticOrKinematicObject())
  1251. {
  1252. bool found = false;
  1253. for (int b = 0; b < numBodies; b++)
  1254. {
  1255. if (&constraint->getRigidBodyB() == bodies[b])
  1256. {
  1257. found = true;
  1258. break;
  1259. }
  1260. }
  1261. btAssert(found);
  1262. }
  1263. }
  1264. }
  1265. //make sure that dynamic bodies exist for all contact manifolds
  1266. for (int i = 0; i < numManifolds; i++)
  1267. {
  1268. if (!manifoldPtr[i]->getBody0()->isStaticOrKinematicObject())
  1269. {
  1270. bool found = false;
  1271. for (int b = 0; b < numBodies; b++)
  1272. {
  1273. if (manifoldPtr[i]->getBody0() == bodies[b])
  1274. {
  1275. found = true;
  1276. break;
  1277. }
  1278. }
  1279. btAssert(found);
  1280. }
  1281. if (!manifoldPtr[i]->getBody1()->isStaticOrKinematicObject())
  1282. {
  1283. bool found = false;
  1284. for (int b = 0; b < numBodies; b++)
  1285. {
  1286. if (manifoldPtr[i]->getBody1() == bodies[b])
  1287. {
  1288. found = true;
  1289. break;
  1290. }
  1291. }
  1292. btAssert(found);
  1293. }
  1294. }
  1295. #endif //BT_ADDITIONAL_DEBUG
  1296. //convert all bodies
  1297. convertBodies(bodies, numBodies, infoGlobal);
  1298. convertJoints(constraints, numConstraints, infoGlobal);
  1299. convertContacts(manifoldPtr, numManifolds, infoGlobal);
  1300. // btContactSolverInfo info = infoGlobal;
  1301. int numNonContactPool = m_tmpSolverNonContactConstraintPool.size();
  1302. int numConstraintPool = m_tmpSolverContactConstraintPool.size();
  1303. int numFrictionPool = m_tmpSolverContactFrictionConstraintPool.size();
  1304. ///@todo: use stack allocator for such temporarily memory, same for solver bodies/constraints
  1305. m_orderNonContactConstraintPool.resizeNoInitialize(numNonContactPool);
  1306. if ((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS))
  1307. m_orderTmpConstraintPool.resizeNoInitialize(numConstraintPool * 2);
  1308. else
  1309. m_orderTmpConstraintPool.resizeNoInitialize(numConstraintPool);
  1310. m_orderFrictionConstraintPool.resizeNoInitialize(numFrictionPool);
  1311. {
  1312. int i;
  1313. for (i = 0; i < numNonContactPool; i++)
  1314. {
  1315. m_orderNonContactConstraintPool[i] = i;
  1316. }
  1317. for (i = 0; i < numConstraintPool; i++)
  1318. {
  1319. m_orderTmpConstraintPool[i] = i;
  1320. }
  1321. for (i = 0; i < numFrictionPool; i++)
  1322. {
  1323. m_orderFrictionConstraintPool[i] = i;
  1324. }
  1325. }
  1326. return 0.f;
  1327. }
  1328. btScalar btSequentialImpulseConstraintSolver::solveSingleIteration(int iteration, btCollisionObject** /*bodies */, int /*numBodies*/, btPersistentManifold** /*manifoldPtr*/, int /*numManifolds*/, btTypedConstraint** constraints, int numConstraints, const btContactSolverInfo& infoGlobal, btIDebugDraw* /*debugDrawer*/)
  1329. {
  1330. BT_PROFILE("solveSingleIteration");
  1331. btScalar leastSquaresResidual = 0.f;
  1332. int numNonContactPool = m_tmpSolverNonContactConstraintPool.size();
  1333. int numConstraintPool = m_tmpSolverContactConstraintPool.size();
  1334. int numFrictionPool = m_tmpSolverContactFrictionConstraintPool.size();
  1335. if (infoGlobal.m_solverMode & SOLVER_RANDMIZE_ORDER)
  1336. {
  1337. if (1) // uncomment this for a bit less random ((iteration & 7) == 0)
  1338. {
  1339. for (int j = 0; j < numNonContactPool; ++j)
  1340. {
  1341. int tmp = m_orderNonContactConstraintPool[j];
  1342. int swapi = btRandInt2(j + 1);
  1343. m_orderNonContactConstraintPool[j] = m_orderNonContactConstraintPool[swapi];
  1344. m_orderNonContactConstraintPool[swapi] = tmp;
  1345. }
  1346. //contact/friction constraints are not solved more than
  1347. if (iteration < infoGlobal.m_numIterations)
  1348. {
  1349. for (int j = 0; j < numConstraintPool; ++j)
  1350. {
  1351. int tmp = m_orderTmpConstraintPool[j];
  1352. int swapi = btRandInt2(j + 1);
  1353. m_orderTmpConstraintPool[j] = m_orderTmpConstraintPool[swapi];
  1354. m_orderTmpConstraintPool[swapi] = tmp;
  1355. }
  1356. for (int j = 0; j < numFrictionPool; ++j)
  1357. {
  1358. int tmp = m_orderFrictionConstraintPool[j];
  1359. int swapi = btRandInt2(j + 1);
  1360. m_orderFrictionConstraintPool[j] = m_orderFrictionConstraintPool[swapi];
  1361. m_orderFrictionConstraintPool[swapi] = tmp;
  1362. }
  1363. }
  1364. }
  1365. }
  1366. ///solve all joint constraints
  1367. for (int j = 0; j < m_tmpSolverNonContactConstraintPool.size(); j++)
  1368. {
  1369. btSolverConstraint& constraint = m_tmpSolverNonContactConstraintPool[m_orderNonContactConstraintPool[j]];
  1370. if (iteration < constraint.m_overrideNumSolverIterations)
  1371. {
  1372. btScalar residual = resolveSingleConstraintRowGeneric(m_tmpSolverBodyPool[constraint.m_solverBodyIdA], m_tmpSolverBodyPool[constraint.m_solverBodyIdB], constraint);
  1373. leastSquaresResidual = btMax(leastSquaresResidual, residual * residual);
  1374. }
  1375. }
  1376. if (iteration < infoGlobal.m_numIterations)
  1377. {
  1378. for (int j = 0; j < numConstraints; j++)
  1379. {
  1380. if (constraints[j]->isEnabled())
  1381. {
  1382. int bodyAid = getOrInitSolverBody(constraints[j]->getRigidBodyA(), infoGlobal.m_timeStep);
  1383. int bodyBid = getOrInitSolverBody(constraints[j]->getRigidBodyB(), infoGlobal.m_timeStep);
  1384. btSolverBody& bodyA = m_tmpSolverBodyPool[bodyAid];
  1385. btSolverBody& bodyB = m_tmpSolverBodyPool[bodyBid];
  1386. constraints[j]->solveConstraintObsolete(bodyA, bodyB, infoGlobal.m_timeStep);
  1387. }
  1388. }
  1389. ///solve all contact constraints
  1390. if (infoGlobal.m_solverMode & SOLVER_INTERLEAVE_CONTACT_AND_FRICTION_CONSTRAINTS)
  1391. {
  1392. int numPoolConstraints = m_tmpSolverContactConstraintPool.size();
  1393. int multiplier = (infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS) ? 2 : 1;
  1394. for (int c = 0; c < numPoolConstraints; c++)
  1395. {
  1396. btScalar totalImpulse = 0;
  1397. {
  1398. const btSolverConstraint& solveManifold = m_tmpSolverContactConstraintPool[m_orderTmpConstraintPool[c]];
  1399. btScalar residual = resolveSingleConstraintRowLowerLimit(m_tmpSolverBodyPool[solveManifold.m_solverBodyIdA], m_tmpSolverBodyPool[solveManifold.m_solverBodyIdB], solveManifold);
  1400. leastSquaresResidual = btMax(leastSquaresResidual, residual * residual);
  1401. totalImpulse = solveManifold.m_appliedImpulse;
  1402. }
  1403. bool applyFriction = true;
  1404. if (applyFriction)
  1405. {
  1406. {
  1407. btSolverConstraint& solveManifold = m_tmpSolverContactFrictionConstraintPool[m_orderFrictionConstraintPool[c * multiplier]];
  1408. if (totalImpulse > btScalar(0))
  1409. {
  1410. solveManifold.m_lowerLimit = -(solveManifold.m_friction * totalImpulse);
  1411. solveManifold.m_upperLimit = solveManifold.m_friction * totalImpulse;
  1412. btScalar residual = resolveSingleConstraintRowGeneric(m_tmpSolverBodyPool[solveManifold.m_solverBodyIdA], m_tmpSolverBodyPool[solveManifold.m_solverBodyIdB], solveManifold);
  1413. leastSquaresResidual = btMax(leastSquaresResidual, residual * residual);
  1414. }
  1415. }
  1416. if (infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS)
  1417. {
  1418. btSolverConstraint& solveManifold = m_tmpSolverContactFrictionConstraintPool[m_orderFrictionConstraintPool[c * multiplier + 1]];
  1419. if (totalImpulse > btScalar(0))
  1420. {
  1421. solveManifold.m_lowerLimit = -(solveManifold.m_friction * totalImpulse);
  1422. solveManifold.m_upperLimit = solveManifold.m_friction * totalImpulse;
  1423. btScalar residual = resolveSingleConstraintRowGeneric(m_tmpSolverBodyPool[solveManifold.m_solverBodyIdA], m_tmpSolverBodyPool[solveManifold.m_solverBodyIdB], solveManifold);
  1424. leastSquaresResidual = btMax(leastSquaresResidual, residual * residual);
  1425. }
  1426. }
  1427. }
  1428. }
  1429. }
  1430. else //SOLVER_INTERLEAVE_CONTACT_AND_FRICTION_CONSTRAINTS
  1431. {
  1432. //solve the friction constraints after all contact constraints, don't interleave them
  1433. int numPoolConstraints = m_tmpSolverContactConstraintPool.size();
  1434. int j;
  1435. for (j = 0; j < numPoolConstraints; j++)
  1436. {
  1437. const btSolverConstraint& solveManifold = m_tmpSolverContactConstraintPool[m_orderTmpConstraintPool[j]];
  1438. btScalar residual = resolveSingleConstraintRowLowerLimit(m_tmpSolverBodyPool[solveManifold.m_solverBodyIdA], m_tmpSolverBodyPool[solveManifold.m_solverBodyIdB], solveManifold);
  1439. leastSquaresResidual = btMax(leastSquaresResidual, residual * residual);
  1440. }
  1441. ///solve all friction constraints
  1442. int numFrictionPoolConstraints = m_tmpSolverContactFrictionConstraintPool.size();
  1443. for (j = 0; j < numFrictionPoolConstraints; j++)
  1444. {
  1445. btSolverConstraint& solveManifold = m_tmpSolverContactFrictionConstraintPool[m_orderFrictionConstraintPool[j]];
  1446. btScalar totalImpulse = m_tmpSolverContactConstraintPool[solveManifold.m_frictionIndex].m_appliedImpulse;
  1447. if (totalImpulse > btScalar(0))
  1448. {
  1449. solveManifold.m_lowerLimit = -(solveManifold.m_friction * totalImpulse);
  1450. solveManifold.m_upperLimit = solveManifold.m_friction * totalImpulse;
  1451. btScalar residual = resolveSingleConstraintRowGeneric(m_tmpSolverBodyPool[solveManifold.m_solverBodyIdA], m_tmpSolverBodyPool[solveManifold.m_solverBodyIdB], solveManifold);
  1452. leastSquaresResidual = btMax(leastSquaresResidual, residual * residual);
  1453. }
  1454. }
  1455. }
  1456. int numRollingFrictionPoolConstraints = m_tmpSolverContactRollingFrictionConstraintPool.size();
  1457. for (int j = 0; j < numRollingFrictionPoolConstraints; j++)
  1458. {
  1459. btSolverConstraint& rollingFrictionConstraint = m_tmpSolverContactRollingFrictionConstraintPool[j];
  1460. btScalar totalImpulse = m_tmpSolverContactConstraintPool[rollingFrictionConstraint.m_frictionIndex].m_appliedImpulse;
  1461. if (totalImpulse > btScalar(0))
  1462. {
  1463. btScalar rollingFrictionMagnitude = rollingFrictionConstraint.m_friction * totalImpulse;
  1464. if (rollingFrictionMagnitude > rollingFrictionConstraint.m_friction)
  1465. rollingFrictionMagnitude = rollingFrictionConstraint.m_friction;
  1466. rollingFrictionConstraint.m_lowerLimit = -rollingFrictionMagnitude;
  1467. rollingFrictionConstraint.m_upperLimit = rollingFrictionMagnitude;
  1468. btScalar residual = resolveSingleConstraintRowGeneric(m_tmpSolverBodyPool[rollingFrictionConstraint.m_solverBodyIdA], m_tmpSolverBodyPool[rollingFrictionConstraint.m_solverBodyIdB], rollingFrictionConstraint);
  1469. leastSquaresResidual = btMax(leastSquaresResidual, residual * residual);
  1470. }
  1471. }
  1472. }
  1473. return leastSquaresResidual;
  1474. }
  1475. void btSequentialImpulseConstraintSolver::solveGroupCacheFriendlySplitImpulseIterations(btCollisionObject** bodies, int numBodies, btPersistentManifold** manifoldPtr, int numManifolds, btTypedConstraint** constraints, int numConstraints, const btContactSolverInfo& infoGlobal, btIDebugDraw* debugDrawer)
  1476. {
  1477. BT_PROFILE("solveGroupCacheFriendlySplitImpulseIterations");
  1478. int iteration;
  1479. if (infoGlobal.m_splitImpulse)
  1480. {
  1481. {
  1482. for (iteration = 0; iteration < infoGlobal.m_numIterations; iteration++)
  1483. {
  1484. btScalar leastSquaresResidual = 0.f;
  1485. {
  1486. int numPoolConstraints = m_tmpSolverContactConstraintPool.size();
  1487. int j;
  1488. for (j = 0; j < numPoolConstraints; j++)
  1489. {
  1490. const btSolverConstraint& solveManifold = m_tmpSolverContactConstraintPool[m_orderTmpConstraintPool[j]];
  1491. btScalar residual = resolveSplitPenetrationImpulse(m_tmpSolverBodyPool[solveManifold.m_solverBodyIdA], m_tmpSolverBodyPool[solveManifold.m_solverBodyIdB], solveManifold);
  1492. leastSquaresResidual = btMax(leastSquaresResidual, residual * residual);
  1493. }
  1494. }
  1495. if (leastSquaresResidual <= infoGlobal.m_leastSquaresResidualThreshold || iteration >= (infoGlobal.m_numIterations - 1))
  1496. {
  1497. #ifdef VERBOSE_RESIDUAL_PRINTF
  1498. printf("residual = %f at iteration #%d\n", leastSquaresResidual, iteration);
  1499. #endif
  1500. break;
  1501. }
  1502. }
  1503. }
  1504. }
  1505. }
  1506. btScalar btSequentialImpulseConstraintSolver::solveGroupCacheFriendlyIterations(btCollisionObject** bodies, int numBodies, btPersistentManifold** manifoldPtr, int numManifolds, btTypedConstraint** constraints, int numConstraints, const btContactSolverInfo& infoGlobal, btIDebugDraw* debugDrawer)
  1507. {
  1508. BT_PROFILE("solveGroupCacheFriendlyIterations");
  1509. {
  1510. ///this is a special step to resolve penetrations (just for contacts)
  1511. solveGroupCacheFriendlySplitImpulseIterations(bodies, numBodies, manifoldPtr, numManifolds, constraints, numConstraints, infoGlobal, debugDrawer);
  1512. int maxIterations = m_maxOverrideNumSolverIterations > infoGlobal.m_numIterations ? m_maxOverrideNumSolverIterations : infoGlobal.m_numIterations;
  1513. for (int iteration = 0; iteration < maxIterations; iteration++)
  1514. //for ( int iteration = maxIterations-1 ; iteration >= 0;iteration--)
  1515. {
  1516. m_leastSquaresResidual = solveSingleIteration(iteration, bodies, numBodies, manifoldPtr, numManifolds, constraints, numConstraints, infoGlobal, debugDrawer);
  1517. if (m_leastSquaresResidual <= infoGlobal.m_leastSquaresResidualThreshold || (iteration >= (maxIterations - 1)))
  1518. {
  1519. #ifdef VERBOSE_RESIDUAL_PRINTF
  1520. printf("residual = %f at iteration #%d\n", m_leastSquaresResidual, iteration);
  1521. #endif
  1522. m_analyticsData.m_numSolverCalls++;
  1523. m_analyticsData.m_numIterationsUsed = iteration+1;
  1524. m_analyticsData.m_islandId = -2;
  1525. if (numBodies>0)
  1526. m_analyticsData.m_islandId = bodies[0]->getCompanionId();
  1527. m_analyticsData.m_numBodies = numBodies;
  1528. m_analyticsData.m_numContactManifolds = numManifolds;
  1529. m_analyticsData.m_remainingLeastSquaresResidual = m_leastSquaresResidual;
  1530. break;
  1531. }
  1532. }
  1533. }
  1534. return 0.f;
  1535. }
  1536. void btSequentialImpulseConstraintSolver::writeBackContacts(int iBegin, int iEnd, const btContactSolverInfo& infoGlobal)
  1537. {
  1538. for (int j = iBegin; j < iEnd; j++)
  1539. {
  1540. const btSolverConstraint& solveManifold = m_tmpSolverContactConstraintPool[j];
  1541. btManifoldPoint* pt = (btManifoldPoint*)solveManifold.m_originalContactPoint;
  1542. btAssert(pt);
  1543. pt->m_appliedImpulse = solveManifold.m_appliedImpulse;
  1544. // float f = m_tmpSolverContactFrictionConstraintPool[solveManifold.m_frictionIndex].m_appliedImpulse;
  1545. // printf("pt->m_appliedImpulseLateral1 = %f\n", f);
  1546. pt->m_appliedImpulseLateral1 = m_tmpSolverContactFrictionConstraintPool[solveManifold.m_frictionIndex].m_appliedImpulse;
  1547. //printf("pt->m_appliedImpulseLateral1 = %f\n", pt->m_appliedImpulseLateral1);
  1548. if ((infoGlobal.m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS))
  1549. {
  1550. pt->m_appliedImpulseLateral2 = m_tmpSolverContactFrictionConstraintPool[solveManifold.m_frictionIndex + 1].m_appliedImpulse;
  1551. }
  1552. //do a callback here?
  1553. }
  1554. }
  1555. void btSequentialImpulseConstraintSolver::writeBackJoints(int iBegin, int iEnd, const btContactSolverInfo& infoGlobal)
  1556. {
  1557. for (int j = iBegin; j < iEnd; j++)
  1558. {
  1559. const btSolverConstraint& solverConstr = m_tmpSolverNonContactConstraintPool[j];
  1560. btTypedConstraint* constr = (btTypedConstraint*)solverConstr.m_originalContactPoint;
  1561. btJointFeedback* fb = constr->getJointFeedback();
  1562. if (fb)
  1563. {
  1564. fb->m_appliedForceBodyA += solverConstr.m_contactNormal1 * solverConstr.m_appliedImpulse * constr->getRigidBodyA().getLinearFactor() / infoGlobal.m_timeStep;
  1565. fb->m_appliedForceBodyB += solverConstr.m_contactNormal2 * solverConstr.m_appliedImpulse * constr->getRigidBodyB().getLinearFactor() / infoGlobal.m_timeStep;
  1566. fb->m_appliedTorqueBodyA += solverConstr.m_relpos1CrossNormal * constr->getRigidBodyA().getAngularFactor() * solverConstr.m_appliedImpulse / infoGlobal.m_timeStep;
  1567. fb->m_appliedTorqueBodyB += solverConstr.m_relpos2CrossNormal * constr->getRigidBodyB().getAngularFactor() * solverConstr.m_appliedImpulse / infoGlobal.m_timeStep; /*RGM ???? */
  1568. }
  1569. constr->internalSetAppliedImpulse(solverConstr.m_appliedImpulse);
  1570. if (btFabs(solverConstr.m_appliedImpulse) >= constr->getBreakingImpulseThreshold())
  1571. {
  1572. constr->setEnabled(false);
  1573. }
  1574. }
  1575. }
  1576. void btSequentialImpulseConstraintSolver::writeBackBodies(int iBegin, int iEnd, const btContactSolverInfo& infoGlobal)
  1577. {
  1578. for (int i = iBegin; i < iEnd; i++)
  1579. {
  1580. btRigidBody* body = m_tmpSolverBodyPool[i].m_originalBody;
  1581. if (body)
  1582. {
  1583. if (infoGlobal.m_splitImpulse)
  1584. m_tmpSolverBodyPool[i].writebackVelocityAndTransform(infoGlobal.m_timeStep, infoGlobal.m_splitImpulseTurnErp);
  1585. else
  1586. m_tmpSolverBodyPool[i].writebackVelocity();
  1587. m_tmpSolverBodyPool[i].m_originalBody->setLinearVelocity(
  1588. m_tmpSolverBodyPool[i].m_linearVelocity +
  1589. m_tmpSolverBodyPool[i].m_externalForceImpulse);
  1590. m_tmpSolverBodyPool[i].m_originalBody->setAngularVelocity(
  1591. m_tmpSolverBodyPool[i].m_angularVelocity +
  1592. m_tmpSolverBodyPool[i].m_externalTorqueImpulse);
  1593. if (infoGlobal.m_splitImpulse)
  1594. m_tmpSolverBodyPool[i].m_originalBody->setWorldTransform(m_tmpSolverBodyPool[i].m_worldTransform);
  1595. m_tmpSolverBodyPool[i].m_originalBody->setCompanionId(-1);
  1596. }
  1597. }
  1598. }
  1599. btScalar btSequentialImpulseConstraintSolver::solveGroupCacheFriendlyFinish(btCollisionObject** bodies, int numBodies, const btContactSolverInfo& infoGlobal)
  1600. {
  1601. BT_PROFILE("solveGroupCacheFriendlyFinish");
  1602. if (infoGlobal.m_solverMode & SOLVER_USE_WARMSTARTING)
  1603. {
  1604. writeBackContacts(0, m_tmpSolverContactConstraintPool.size(), infoGlobal);
  1605. }
  1606. writeBackJoints(0, m_tmpSolverNonContactConstraintPool.size(), infoGlobal);
  1607. writeBackBodies(0, m_tmpSolverBodyPool.size(), infoGlobal);
  1608. m_tmpSolverContactConstraintPool.resizeNoInitialize(0);
  1609. m_tmpSolverNonContactConstraintPool.resizeNoInitialize(0);
  1610. m_tmpSolverContactFrictionConstraintPool.resizeNoInitialize(0);
  1611. m_tmpSolverContactRollingFrictionConstraintPool.resizeNoInitialize(0);
  1612. m_tmpSolverBodyPool.resizeNoInitialize(0);
  1613. return 0.f;
  1614. }
  1615. /// btSequentialImpulseConstraintSolver Sequentially applies impulses
  1616. btScalar btSequentialImpulseConstraintSolver::solveGroup(btCollisionObject** bodies, int numBodies, btPersistentManifold** manifoldPtr, int numManifolds, btTypedConstraint** constraints, int numConstraints, const btContactSolverInfo& infoGlobal, btIDebugDraw* debugDrawer, btDispatcher* /*dispatcher*/)
  1617. {
  1618. BT_PROFILE("solveGroup");
  1619. //you need to provide at least some bodies
  1620. solveGroupCacheFriendlySetup(bodies, numBodies, manifoldPtr, numManifolds, constraints, numConstraints, infoGlobal, debugDrawer);
  1621. solveGroupCacheFriendlyIterations(bodies, numBodies, manifoldPtr, numManifolds, constraints, numConstraints, infoGlobal, debugDrawer);
  1622. solveGroupCacheFriendlyFinish(bodies, numBodies, infoGlobal);
  1623. return 0.f;
  1624. }
  1625. void btSequentialImpulseConstraintSolver::reset()
  1626. {
  1627. m_btSeed2 = 0;
  1628. }