btSequentialImpulseConstraintSolver.cpp 82 KB

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