btConvexConvexAlgorithm.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  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. ///Specialized capsule-capsule collision algorithm has been added for Bullet 2.75 release to increase ragdoll performance
  14. ///If you experience problems with capsule-capsule collision, try to define BT_DISABLE_CAPSULE_CAPSULE_COLLIDER and report it in the Bullet forums
  15. ///with reproduction case
  16. //#define BT_DISABLE_CAPSULE_CAPSULE_COLLIDER 1
  17. //#define ZERO_MARGIN
  18. #include "btConvexConvexAlgorithm.h"
  19. //#include <stdio.h>
  20. #include "BulletCollision/NarrowPhaseCollision/btDiscreteCollisionDetectorInterface.h"
  21. #include "BulletCollision/BroadphaseCollision/btBroadphaseInterface.h"
  22. #include "BulletCollision/CollisionDispatch/btCollisionObject.h"
  23. #include "BulletCollision/CollisionShapes/btConvexShape.h"
  24. #include "BulletCollision/CollisionShapes/btCapsuleShape.h"
  25. #include "BulletCollision/CollisionShapes/btTriangleShape.h"
  26. #include "BulletCollision/CollisionShapes/btConvexPolyhedron.h"
  27. #include "BulletCollision/NarrowPhaseCollision/btGjkPairDetector.h"
  28. #include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
  29. #include "BulletCollision/CollisionDispatch/btCollisionDispatcher.h"
  30. #include "BulletCollision/CollisionShapes/btBoxShape.h"
  31. #include "BulletCollision/CollisionDispatch/btManifoldResult.h"
  32. #include "BulletCollision/NarrowPhaseCollision/btConvexPenetrationDepthSolver.h"
  33. #include "BulletCollision/NarrowPhaseCollision/btContinuousConvexCollision.h"
  34. #include "BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.h"
  35. #include "BulletCollision/NarrowPhaseCollision/btGjkConvexCast.h"
  36. #include "BulletCollision/NarrowPhaseCollision/btVoronoiSimplexSolver.h"
  37. #include "BulletCollision/CollisionShapes/btSphereShape.h"
  38. #include "BulletCollision/NarrowPhaseCollision/btMinkowskiPenetrationDepthSolver.h"
  39. #include "BulletCollision/NarrowPhaseCollision/btGjkEpa2.h"
  40. #include "BulletCollision/NarrowPhaseCollision/btGjkEpaPenetrationDepthSolver.h"
  41. #include "BulletCollision/NarrowPhaseCollision/btPolyhedralContactClipping.h"
  42. #include "BulletCollision/CollisionDispatch/btCollisionObjectWrapper.h"
  43. ///////////
  44. static SIMD_FORCE_INLINE void segmentsClosestPoints(
  45. btVector3& ptsVector,
  46. btVector3& offsetA,
  47. btVector3& offsetB,
  48. btScalar& tA, btScalar& tB,
  49. const btVector3& translation,
  50. const btVector3& dirA, btScalar hlenA,
  51. const btVector3& dirB, btScalar hlenB )
  52. {
  53. // compute the parameters of the closest points on each line segment
  54. btScalar dirA_dot_dirB = btDot(dirA,dirB);
  55. btScalar dirA_dot_trans = btDot(dirA,translation);
  56. btScalar dirB_dot_trans = btDot(dirB,translation);
  57. btScalar denom = 1.0f - dirA_dot_dirB * dirA_dot_dirB;
  58. if ( denom == 0.0f ) {
  59. tA = 0.0f;
  60. } else {
  61. tA = ( dirA_dot_trans - dirB_dot_trans * dirA_dot_dirB ) / denom;
  62. if ( tA < -hlenA )
  63. tA = -hlenA;
  64. else if ( tA > hlenA )
  65. tA = hlenA;
  66. }
  67. tB = tA * dirA_dot_dirB - dirB_dot_trans;
  68. if ( tB < -hlenB ) {
  69. tB = -hlenB;
  70. tA = tB * dirA_dot_dirB + dirA_dot_trans;
  71. if ( tA < -hlenA )
  72. tA = -hlenA;
  73. else if ( tA > hlenA )
  74. tA = hlenA;
  75. } else if ( tB > hlenB ) {
  76. tB = hlenB;
  77. tA = tB * dirA_dot_dirB + dirA_dot_trans;
  78. if ( tA < -hlenA )
  79. tA = -hlenA;
  80. else if ( tA > hlenA )
  81. tA = hlenA;
  82. }
  83. // compute the closest points relative to segment centers.
  84. offsetA = dirA * tA;
  85. offsetB = dirB * tB;
  86. ptsVector = translation - offsetA + offsetB;
  87. }
  88. static SIMD_FORCE_INLINE btScalar capsuleCapsuleDistance(
  89. btVector3& normalOnB,
  90. btVector3& pointOnB,
  91. btScalar capsuleLengthA,
  92. btScalar capsuleRadiusA,
  93. btScalar capsuleLengthB,
  94. btScalar capsuleRadiusB,
  95. int capsuleAxisA,
  96. int capsuleAxisB,
  97. const btTransform& transformA,
  98. const btTransform& transformB,
  99. btScalar distanceThreshold )
  100. {
  101. btVector3 directionA = transformA.getBasis().getColumn(capsuleAxisA);
  102. btVector3 translationA = transformA.getOrigin();
  103. btVector3 directionB = transformB.getBasis().getColumn(capsuleAxisB);
  104. btVector3 translationB = transformB.getOrigin();
  105. // translation between centers
  106. btVector3 translation = translationB - translationA;
  107. // compute the closest points of the capsule line segments
  108. btVector3 ptsVector; // the vector between the closest points
  109. btVector3 offsetA, offsetB; // offsets from segment centers to their closest points
  110. btScalar tA, tB; // parameters on line segment
  111. segmentsClosestPoints( ptsVector, offsetA, offsetB, tA, tB, translation,
  112. directionA, capsuleLengthA, directionB, capsuleLengthB );
  113. btScalar distance = ptsVector.length() - capsuleRadiusA - capsuleRadiusB;
  114. if ( distance > distanceThreshold )
  115. return distance;
  116. btScalar lenSqr = ptsVector.length2();
  117. if (lenSqr<= (SIMD_EPSILON*SIMD_EPSILON))
  118. {
  119. //degenerate case where 2 capsules are likely at the same location: take a vector tangential to 'directionA'
  120. btVector3 q;
  121. btPlaneSpace1(directionA,normalOnB,q);
  122. } else
  123. {
  124. // compute the contact normal
  125. normalOnB = ptsVector*-btRecipSqrt(lenSqr);
  126. }
  127. pointOnB = transformB.getOrigin()+offsetB + normalOnB * capsuleRadiusB;
  128. return distance;
  129. }
  130. //////////
  131. btConvexConvexAlgorithm::CreateFunc::CreateFunc(btConvexPenetrationDepthSolver* pdSolver)
  132. {
  133. m_numPerturbationIterations = 0;
  134. m_minimumPointsPerturbationThreshold = 3;
  135. m_pdSolver = pdSolver;
  136. }
  137. btConvexConvexAlgorithm::CreateFunc::~CreateFunc()
  138. {
  139. }
  140. btConvexConvexAlgorithm::btConvexConvexAlgorithm(btPersistentManifold* mf,const btCollisionAlgorithmConstructionInfo& ci,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,btConvexPenetrationDepthSolver* pdSolver,int numPerturbationIterations, int minimumPointsPerturbationThreshold)
  141. : btActivatingCollisionAlgorithm(ci,body0Wrap,body1Wrap),
  142. m_pdSolver(pdSolver),
  143. m_ownManifold (false),
  144. m_manifoldPtr(mf),
  145. m_lowLevelOfDetail(false),
  146. #ifdef USE_SEPDISTANCE_UTIL2
  147. m_sepDistance((static_cast<btConvexShape*>(body0->getCollisionShape()))->getAngularMotionDisc(),
  148. (static_cast<btConvexShape*>(body1->getCollisionShape()))->getAngularMotionDisc()),
  149. #endif
  150. m_numPerturbationIterations(numPerturbationIterations),
  151. m_minimumPointsPerturbationThreshold(minimumPointsPerturbationThreshold)
  152. {
  153. (void)body0Wrap;
  154. (void)body1Wrap;
  155. }
  156. btConvexConvexAlgorithm::~btConvexConvexAlgorithm()
  157. {
  158. if (m_ownManifold)
  159. {
  160. if (m_manifoldPtr)
  161. m_dispatcher->releaseManifold(m_manifoldPtr);
  162. }
  163. }
  164. void btConvexConvexAlgorithm ::setLowLevelOfDetail(bool useLowLevel)
  165. {
  166. m_lowLevelOfDetail = useLowLevel;
  167. }
  168. struct btPerturbedContactResult : public btManifoldResult
  169. {
  170. btManifoldResult* m_originalManifoldResult;
  171. btTransform m_transformA;
  172. btTransform m_transformB;
  173. btTransform m_unPerturbedTransform;
  174. bool m_perturbA;
  175. btIDebugDraw* m_debugDrawer;
  176. btPerturbedContactResult(btManifoldResult* originalResult,const btTransform& transformA,const btTransform& transformB,const btTransform& unPerturbedTransform,bool perturbA,btIDebugDraw* debugDrawer)
  177. :m_originalManifoldResult(originalResult),
  178. m_transformA(transformA),
  179. m_transformB(transformB),
  180. m_unPerturbedTransform(unPerturbedTransform),
  181. m_perturbA(perturbA),
  182. m_debugDrawer(debugDrawer)
  183. {
  184. }
  185. virtual ~ btPerturbedContactResult()
  186. {
  187. }
  188. virtual void addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorld,btScalar orgDepth)
  189. {
  190. btVector3 endPt,startPt;
  191. btScalar newDepth;
  192. btVector3 newNormal;
  193. if (m_perturbA)
  194. {
  195. btVector3 endPtOrg = pointInWorld + normalOnBInWorld*orgDepth;
  196. endPt = (m_unPerturbedTransform*m_transformA.inverse())(endPtOrg);
  197. newDepth = (endPt - pointInWorld).dot(normalOnBInWorld);
  198. startPt = endPt - normalOnBInWorld*newDepth;
  199. } else
  200. {
  201. endPt = pointInWorld + normalOnBInWorld*orgDepth;
  202. startPt = (m_unPerturbedTransform*m_transformB.inverse())(pointInWorld);
  203. newDepth = (endPt - startPt).dot(normalOnBInWorld);
  204. }
  205. //#define DEBUG_CONTACTS 1
  206. #ifdef DEBUG_CONTACTS
  207. m_debugDrawer->drawLine(startPt,endPt,btVector3(1,0,0));
  208. m_debugDrawer->drawSphere(startPt,0.05,btVector3(0,1,0));
  209. m_debugDrawer->drawSphere(endPt,0.05,btVector3(0,0,1));
  210. #endif //DEBUG_CONTACTS
  211. m_originalManifoldResult->addContactPoint(normalOnBInWorld,startPt,newDepth);
  212. }
  213. };
  214. extern btScalar gContactBreakingThreshold;
  215. //
  216. // Convex-Convex collision algorithm
  217. //
  218. void btConvexConvexAlgorithm ::processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
  219. {
  220. if (!m_manifoldPtr)
  221. {
  222. //swapped?
  223. m_manifoldPtr = m_dispatcher->getNewManifold(body0Wrap->getCollisionObject(),body1Wrap->getCollisionObject());
  224. m_ownManifold = true;
  225. }
  226. resultOut->setPersistentManifold(m_manifoldPtr);
  227. //comment-out next line to test multi-contact generation
  228. //resultOut->getPersistentManifold()->clearManifold();
  229. const btConvexShape* min0 = static_cast<const btConvexShape*>(body0Wrap->getCollisionShape());
  230. const btConvexShape* min1 = static_cast<const btConvexShape*>(body1Wrap->getCollisionShape());
  231. btVector3 normalOnB;
  232. btVector3 pointOnBWorld;
  233. #ifndef BT_DISABLE_CAPSULE_CAPSULE_COLLIDER
  234. if ((min0->getShapeType() == CAPSULE_SHAPE_PROXYTYPE) && (min1->getShapeType() == CAPSULE_SHAPE_PROXYTYPE))
  235. {
  236. //m_manifoldPtr->clearManifold();
  237. btCapsuleShape* capsuleA = (btCapsuleShape*) min0;
  238. btCapsuleShape* capsuleB = (btCapsuleShape*) min1;
  239. btScalar threshold = m_manifoldPtr->getContactBreakingThreshold();
  240. btScalar dist = capsuleCapsuleDistance(normalOnB, pointOnBWorld,capsuleA->getHalfHeight(),capsuleA->getRadius(),
  241. capsuleB->getHalfHeight(),capsuleB->getRadius(),capsuleA->getUpAxis(),capsuleB->getUpAxis(),
  242. body0Wrap->getWorldTransform(),body1Wrap->getWorldTransform(),threshold);
  243. if (dist<threshold)
  244. {
  245. btAssert(normalOnB.length2()>=(SIMD_EPSILON*SIMD_EPSILON));
  246. resultOut->addContactPoint(normalOnB,pointOnBWorld,dist);
  247. }
  248. resultOut->refreshContactPoints();
  249. return;
  250. }
  251. if ((min0->getShapeType() == CAPSULE_SHAPE_PROXYTYPE) && (min1->getShapeType() == SPHERE_SHAPE_PROXYTYPE))
  252. {
  253. //m_manifoldPtr->clearManifold();
  254. btCapsuleShape* capsuleA = (btCapsuleShape*) min0;
  255. btSphereShape* capsuleB = (btSphereShape*) min1;
  256. btScalar threshold = m_manifoldPtr->getContactBreakingThreshold();
  257. btScalar dist = capsuleCapsuleDistance(normalOnB, pointOnBWorld,capsuleA->getHalfHeight(),capsuleA->getRadius(),
  258. 0.,capsuleB->getRadius(),capsuleA->getUpAxis(),1,
  259. body0Wrap->getWorldTransform(),body1Wrap->getWorldTransform(),threshold);
  260. if (dist<threshold)
  261. {
  262. btAssert(normalOnB.length2()>=(SIMD_EPSILON*SIMD_EPSILON));
  263. resultOut->addContactPoint(normalOnB,pointOnBWorld,dist);
  264. }
  265. resultOut->refreshContactPoints();
  266. return;
  267. }
  268. if ((min0->getShapeType() == SPHERE_SHAPE_PROXYTYPE) && (min1->getShapeType() == CAPSULE_SHAPE_PROXYTYPE))
  269. {
  270. //m_manifoldPtr->clearManifold();
  271. btSphereShape* capsuleA = (btSphereShape*) min0;
  272. btCapsuleShape* capsuleB = (btCapsuleShape*) min1;
  273. btScalar threshold = m_manifoldPtr->getContactBreakingThreshold();
  274. btScalar dist = capsuleCapsuleDistance(normalOnB, pointOnBWorld,0.,capsuleA->getRadius(),
  275. capsuleB->getHalfHeight(),capsuleB->getRadius(),1,capsuleB->getUpAxis(),
  276. body0Wrap->getWorldTransform(),body1Wrap->getWorldTransform(),threshold);
  277. if (dist<threshold)
  278. {
  279. btAssert(normalOnB.length2()>=(SIMD_EPSILON*SIMD_EPSILON));
  280. resultOut->addContactPoint(normalOnB,pointOnBWorld,dist);
  281. }
  282. resultOut->refreshContactPoints();
  283. return;
  284. }
  285. #endif //BT_DISABLE_CAPSULE_CAPSULE_COLLIDER
  286. #ifdef USE_SEPDISTANCE_UTIL2
  287. if (dispatchInfo.m_useConvexConservativeDistanceUtil)
  288. {
  289. m_sepDistance.updateSeparatingDistance(body0->getWorldTransform(),body1->getWorldTransform());
  290. }
  291. if (!dispatchInfo.m_useConvexConservativeDistanceUtil || m_sepDistance.getConservativeSeparatingDistance()<=0.f)
  292. #endif //USE_SEPDISTANCE_UTIL2
  293. {
  294. btGjkPairDetector::ClosestPointInput input;
  295. btVoronoiSimplexSolver simplexSolver;
  296. btGjkPairDetector gjkPairDetector( min0, min1, &simplexSolver, m_pdSolver );
  297. //TODO: if (dispatchInfo.m_useContinuous)
  298. gjkPairDetector.setMinkowskiA(min0);
  299. gjkPairDetector.setMinkowskiB(min1);
  300. #ifdef USE_SEPDISTANCE_UTIL2
  301. if (dispatchInfo.m_useConvexConservativeDistanceUtil)
  302. {
  303. input.m_maximumDistanceSquared = BT_LARGE_FLOAT;
  304. } else
  305. #endif //USE_SEPDISTANCE_UTIL2
  306. {
  307. //if (dispatchInfo.m_convexMaxDistanceUseCPT)
  308. //{
  309. // input.m_maximumDistanceSquared = min0->getMargin() + min1->getMargin() + m_manifoldPtr->getContactProcessingThreshold();
  310. //} else
  311. //{
  312. input.m_maximumDistanceSquared = min0->getMargin() + min1->getMargin() + m_manifoldPtr->getContactBreakingThreshold()+resultOut->m_closestPointDistanceThreshold;
  313. // }
  314. input.m_maximumDistanceSquared*= input.m_maximumDistanceSquared;
  315. }
  316. input.m_transformA = body0Wrap->getWorldTransform();
  317. input.m_transformB = body1Wrap->getWorldTransform();
  318. #ifdef USE_SEPDISTANCE_UTIL2
  319. btScalar sepDist = 0.f;
  320. if (dispatchInfo.m_useConvexConservativeDistanceUtil)
  321. {
  322. sepDist = gjkPairDetector.getCachedSeparatingDistance();
  323. if (sepDist>SIMD_EPSILON)
  324. {
  325. sepDist += dispatchInfo.m_convexConservativeDistanceThreshold;
  326. //now perturbe directions to get multiple contact points
  327. }
  328. }
  329. #endif //USE_SEPDISTANCE_UTIL2
  330. if (min0->isPolyhedral() && min1->isPolyhedral())
  331. {
  332. struct btDummyResult : public btDiscreteCollisionDetectorInterface::Result
  333. {
  334. btVector3 m_normalOnBInWorld;
  335. btVector3 m_pointInWorld;
  336. btScalar m_depth;
  337. bool m_hasContact;
  338. btDummyResult()
  339. : m_hasContact(false)
  340. {
  341. }
  342. virtual void setShapeIdentifiersA(int partId0,int index0){}
  343. virtual void setShapeIdentifiersB(int partId1,int index1){}
  344. virtual void addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorld,btScalar depth)
  345. {
  346. m_hasContact = true;
  347. m_normalOnBInWorld = normalOnBInWorld;
  348. m_pointInWorld = pointInWorld;
  349. m_depth = depth;
  350. }
  351. };
  352. struct btWithoutMarginResult : public btDiscreteCollisionDetectorInterface::Result
  353. {
  354. btDiscreteCollisionDetectorInterface::Result* m_originalResult;
  355. btVector3 m_reportedNormalOnWorld;
  356. btScalar m_marginOnA;
  357. btScalar m_marginOnB;
  358. btScalar m_reportedDistance;
  359. bool m_foundResult;
  360. btWithoutMarginResult(btDiscreteCollisionDetectorInterface::Result* result, btScalar marginOnA, btScalar marginOnB)
  361. :m_originalResult(result),
  362. m_marginOnA(marginOnA),
  363. m_marginOnB(marginOnB),
  364. m_foundResult(false)
  365. {
  366. }
  367. virtual void setShapeIdentifiersA(int partId0,int index0){}
  368. virtual void setShapeIdentifiersB(int partId1,int index1){}
  369. virtual void addContactPoint(const btVector3& normalOnBInWorld,const btVector3& pointInWorldOrg,btScalar depthOrg)
  370. {
  371. m_reportedDistance = depthOrg;
  372. m_reportedNormalOnWorld = normalOnBInWorld;
  373. btVector3 adjustedPointB = pointInWorldOrg - normalOnBInWorld*m_marginOnB;
  374. m_reportedDistance = depthOrg+(m_marginOnA+m_marginOnB);
  375. if (m_reportedDistance<0.f)
  376. {
  377. m_foundResult = true;
  378. }
  379. m_originalResult->addContactPoint(normalOnBInWorld,adjustedPointB,m_reportedDistance);
  380. }
  381. };
  382. btDummyResult dummy;
  383. ///btBoxShape is an exception: its vertices are created WITH margin so don't subtract it
  384. btScalar min0Margin = min0->getShapeType()==BOX_SHAPE_PROXYTYPE? 0.f : min0->getMargin();
  385. btScalar min1Margin = min1->getShapeType()==BOX_SHAPE_PROXYTYPE? 0.f : min1->getMargin();
  386. btWithoutMarginResult withoutMargin(resultOut, min0Margin,min1Margin);
  387. btPolyhedralConvexShape* polyhedronA = (btPolyhedralConvexShape*) min0;
  388. btPolyhedralConvexShape* polyhedronB = (btPolyhedralConvexShape*) min1;
  389. if (polyhedronA->getConvexPolyhedron() && polyhedronB->getConvexPolyhedron())
  390. {
  391. btScalar threshold = m_manifoldPtr->getContactBreakingThreshold();
  392. btScalar minDist = -1e30f;
  393. btVector3 sepNormalWorldSpace;
  394. bool foundSepAxis = true;
  395. if (dispatchInfo.m_enableSatConvex)
  396. {
  397. foundSepAxis = btPolyhedralContactClipping::findSeparatingAxis(
  398. *polyhedronA->getConvexPolyhedron(), *polyhedronB->getConvexPolyhedron(),
  399. body0Wrap->getWorldTransform(),
  400. body1Wrap->getWorldTransform(),
  401. sepNormalWorldSpace,*resultOut);
  402. } else
  403. {
  404. #ifdef ZERO_MARGIN
  405. gjkPairDetector.setIgnoreMargin(true);
  406. gjkPairDetector.getClosestPoints(input,*resultOut,dispatchInfo.m_debugDraw);
  407. #else
  408. gjkPairDetector.getClosestPoints(input,withoutMargin,dispatchInfo.m_debugDraw);
  409. //gjkPairDetector.getClosestPoints(input,dummy,dispatchInfo.m_debugDraw);
  410. #endif //ZERO_MARGIN
  411. //btScalar l2 = gjkPairDetector.getCachedSeparatingAxis().length2();
  412. //if (l2>SIMD_EPSILON)
  413. {
  414. sepNormalWorldSpace = withoutMargin.m_reportedNormalOnWorld;//gjkPairDetector.getCachedSeparatingAxis()*(1.f/l2);
  415. //minDist = -1e30f;//gjkPairDetector.getCachedSeparatingDistance();
  416. minDist = withoutMargin.m_reportedDistance;//gjkPairDetector.getCachedSeparatingDistance()+min0->getMargin()+min1->getMargin();
  417. #ifdef ZERO_MARGIN
  418. foundSepAxis = true;//gjkPairDetector.getCachedSeparatingDistance()<0.f;
  419. #else
  420. foundSepAxis = withoutMargin.m_foundResult && minDist<0;//-(min0->getMargin()+min1->getMargin());
  421. #endif
  422. }
  423. }
  424. if (foundSepAxis)
  425. {
  426. // printf("sepNormalWorldSpace=%f,%f,%f\n",sepNormalWorldSpace.getX(),sepNormalWorldSpace.getY(),sepNormalWorldSpace.getZ());
  427. worldVertsB1.resize(0);
  428. btPolyhedralContactClipping::clipHullAgainstHull(sepNormalWorldSpace, *polyhedronA->getConvexPolyhedron(), *polyhedronB->getConvexPolyhedron(),
  429. body0Wrap->getWorldTransform(),
  430. body1Wrap->getWorldTransform(), minDist-threshold, threshold, worldVertsB1,worldVertsB2,
  431. *resultOut);
  432. }
  433. if (m_ownManifold)
  434. {
  435. resultOut->refreshContactPoints();
  436. }
  437. return;
  438. } else
  439. {
  440. //we can also deal with convex versus triangle (without connectivity data)
  441. if (dispatchInfo.m_enableSatConvex && polyhedronA->getConvexPolyhedron() && polyhedronB->getShapeType()==TRIANGLE_SHAPE_PROXYTYPE)
  442. {
  443. btVertexArray worldSpaceVertices;
  444. btTriangleShape* tri = (btTriangleShape*)polyhedronB;
  445. worldSpaceVertices.push_back( body1Wrap->getWorldTransform()*tri->m_vertices1[0]);
  446. worldSpaceVertices.push_back( body1Wrap->getWorldTransform()*tri->m_vertices1[1]);
  447. worldSpaceVertices.push_back( body1Wrap->getWorldTransform()*tri->m_vertices1[2]);
  448. //tri->initializePolyhedralFeatures();
  449. btScalar threshold = m_manifoldPtr->getContactBreakingThreshold();
  450. btVector3 sepNormalWorldSpace;
  451. btScalar minDist =-1e30f;
  452. btScalar maxDist = threshold;
  453. bool foundSepAxis = false;
  454. bool useSatSepNormal = true;
  455. if (useSatSepNormal)
  456. {
  457. #if 0
  458. if (0)
  459. {
  460. //initializePolyhedralFeatures performs a convex hull computation, not needed for a single triangle
  461. polyhedronB->initializePolyhedralFeatures();
  462. } else
  463. #endif
  464. {
  465. btVector3 uniqueEdges[3] = {tri->m_vertices1[1]-tri->m_vertices1[0],
  466. tri->m_vertices1[2]-tri->m_vertices1[1],
  467. tri->m_vertices1[0]-tri->m_vertices1[2]};
  468. uniqueEdges[0].normalize();
  469. uniqueEdges[1].normalize();
  470. uniqueEdges[2].normalize();
  471. btConvexPolyhedron polyhedron;
  472. polyhedron.m_vertices.push_back(tri->m_vertices1[2]);
  473. polyhedron.m_vertices.push_back(tri->m_vertices1[0]);
  474. polyhedron.m_vertices.push_back(tri->m_vertices1[1]);
  475. {
  476. btFace combinedFaceA;
  477. combinedFaceA.m_indices.push_back(0);
  478. combinedFaceA.m_indices.push_back(1);
  479. combinedFaceA.m_indices.push_back(2);
  480. btVector3 faceNormal = uniqueEdges[0].cross(uniqueEdges[1]);
  481. faceNormal.normalize();
  482. btScalar planeEq=1e30f;
  483. for (int v=0;v<combinedFaceA.m_indices.size();v++)
  484. {
  485. btScalar eq = tri->m_vertices1[combinedFaceA.m_indices[v]].dot(faceNormal);
  486. if (planeEq>eq)
  487. {
  488. planeEq=eq;
  489. }
  490. }
  491. combinedFaceA.m_plane[0] = faceNormal[0];
  492. combinedFaceA.m_plane[1] = faceNormal[1];
  493. combinedFaceA.m_plane[2] = faceNormal[2];
  494. combinedFaceA.m_plane[3] = -planeEq;
  495. polyhedron.m_faces.push_back(combinedFaceA);
  496. }
  497. {
  498. btFace combinedFaceB;
  499. combinedFaceB.m_indices.push_back(0);
  500. combinedFaceB.m_indices.push_back(2);
  501. combinedFaceB.m_indices.push_back(1);
  502. btVector3 faceNormal = -uniqueEdges[0].cross(uniqueEdges[1]);
  503. faceNormal.normalize();
  504. btScalar planeEq=1e30f;
  505. for (int v=0;v<combinedFaceB.m_indices.size();v++)
  506. {
  507. btScalar eq = tri->m_vertices1[combinedFaceB.m_indices[v]].dot(faceNormal);
  508. if (planeEq>eq)
  509. {
  510. planeEq=eq;
  511. }
  512. }
  513. combinedFaceB.m_plane[0] = faceNormal[0];
  514. combinedFaceB.m_plane[1] = faceNormal[1];
  515. combinedFaceB.m_plane[2] = faceNormal[2];
  516. combinedFaceB.m_plane[3] = -planeEq;
  517. polyhedron.m_faces.push_back(combinedFaceB);
  518. }
  519. polyhedron.m_uniqueEdges.push_back(uniqueEdges[0]);
  520. polyhedron.m_uniqueEdges.push_back(uniqueEdges[1]);
  521. polyhedron.m_uniqueEdges.push_back(uniqueEdges[2]);
  522. polyhedron.initialize2();
  523. polyhedronB->setPolyhedralFeatures(polyhedron);
  524. }
  525. foundSepAxis = btPolyhedralContactClipping::findSeparatingAxis(
  526. *polyhedronA->getConvexPolyhedron(), *polyhedronB->getConvexPolyhedron(),
  527. body0Wrap->getWorldTransform(),
  528. body1Wrap->getWorldTransform(),
  529. sepNormalWorldSpace,*resultOut);
  530. // printf("sepNormalWorldSpace=%f,%f,%f\n",sepNormalWorldSpace.getX(),sepNormalWorldSpace.getY(),sepNormalWorldSpace.getZ());
  531. }
  532. else
  533. {
  534. #ifdef ZERO_MARGIN
  535. gjkPairDetector.setIgnoreMargin(true);
  536. gjkPairDetector.getClosestPoints(input,*resultOut,dispatchInfo.m_debugDraw);
  537. #else
  538. gjkPairDetector.getClosestPoints(input,dummy,dispatchInfo.m_debugDraw);
  539. #endif//ZERO_MARGIN
  540. if (dummy.m_hasContact && dummy.m_depth<0)
  541. {
  542. if (foundSepAxis)
  543. {
  544. if (dummy.m_normalOnBInWorld.dot(sepNormalWorldSpace)<0.99)
  545. {
  546. printf("?\n");
  547. }
  548. } else
  549. {
  550. printf("!\n");
  551. }
  552. sepNormalWorldSpace.setValue(0,0,1);// = dummy.m_normalOnBInWorld;
  553. //minDist = dummy.m_depth;
  554. foundSepAxis = true;
  555. }
  556. #if 0
  557. btScalar l2 = gjkPairDetector.getCachedSeparatingAxis().length2();
  558. if (l2>SIMD_EPSILON)
  559. {
  560. sepNormalWorldSpace = gjkPairDetector.getCachedSeparatingAxis()*(1.f/l2);
  561. //minDist = gjkPairDetector.getCachedSeparatingDistance();
  562. //maxDist = threshold;
  563. minDist = gjkPairDetector.getCachedSeparatingDistance()-min0->getMargin()-min1->getMargin();
  564. foundSepAxis = true;
  565. }
  566. #endif
  567. }
  568. if (foundSepAxis)
  569. {
  570. worldVertsB2.resize(0);
  571. btPolyhedralContactClipping::clipFaceAgainstHull(sepNormalWorldSpace, *polyhedronA->getConvexPolyhedron(),
  572. body0Wrap->getWorldTransform(), worldSpaceVertices, worldVertsB2,minDist-threshold, maxDist, *resultOut);
  573. }
  574. if (m_ownManifold)
  575. {
  576. resultOut->refreshContactPoints();
  577. }
  578. return;
  579. }
  580. }
  581. }
  582. gjkPairDetector.getClosestPoints(input,*resultOut,dispatchInfo.m_debugDraw);
  583. //now perform 'm_numPerturbationIterations' collision queries with the perturbated collision objects
  584. //perform perturbation when more then 'm_minimumPointsPerturbationThreshold' points
  585. if (m_numPerturbationIterations && resultOut->getPersistentManifold()->getNumContacts() < m_minimumPointsPerturbationThreshold)
  586. {
  587. int i;
  588. btVector3 v0,v1;
  589. btVector3 sepNormalWorldSpace;
  590. btScalar l2 = gjkPairDetector.getCachedSeparatingAxis().length2();
  591. if (l2>SIMD_EPSILON)
  592. {
  593. sepNormalWorldSpace = gjkPairDetector.getCachedSeparatingAxis()*(1.f/l2);
  594. btPlaneSpace1(sepNormalWorldSpace,v0,v1);
  595. bool perturbeA = true;
  596. const btScalar angleLimit = 0.125f * SIMD_PI;
  597. btScalar perturbeAngle;
  598. btScalar radiusA = min0->getAngularMotionDisc();
  599. btScalar radiusB = min1->getAngularMotionDisc();
  600. if (radiusA < radiusB)
  601. {
  602. perturbeAngle = gContactBreakingThreshold /radiusA;
  603. perturbeA = true;
  604. } else
  605. {
  606. perturbeAngle = gContactBreakingThreshold / radiusB;
  607. perturbeA = false;
  608. }
  609. if ( perturbeAngle > angleLimit )
  610. perturbeAngle = angleLimit;
  611. btTransform unPerturbedTransform;
  612. if (perturbeA)
  613. {
  614. unPerturbedTransform = input.m_transformA;
  615. } else
  616. {
  617. unPerturbedTransform = input.m_transformB;
  618. }
  619. for ( i=0;i<m_numPerturbationIterations;i++)
  620. {
  621. if (v0.length2()>SIMD_EPSILON)
  622. {
  623. btQuaternion perturbeRot(v0,perturbeAngle);
  624. btScalar iterationAngle = i*(SIMD_2_PI/btScalar(m_numPerturbationIterations));
  625. btQuaternion rotq(sepNormalWorldSpace,iterationAngle);
  626. if (perturbeA)
  627. {
  628. input.m_transformA.setBasis( btMatrix3x3(rotq.inverse()*perturbeRot*rotq)*body0Wrap->getWorldTransform().getBasis());
  629. input.m_transformB = body1Wrap->getWorldTransform();
  630. #ifdef DEBUG_CONTACTS
  631. dispatchInfo.m_debugDraw->drawTransform(input.m_transformA,10.0);
  632. #endif //DEBUG_CONTACTS
  633. } else
  634. {
  635. input.m_transformA = body0Wrap->getWorldTransform();
  636. input.m_transformB.setBasis( btMatrix3x3(rotq.inverse()*perturbeRot*rotq)*body1Wrap->getWorldTransform().getBasis());
  637. #ifdef DEBUG_CONTACTS
  638. dispatchInfo.m_debugDraw->drawTransform(input.m_transformB,10.0);
  639. #endif
  640. }
  641. btPerturbedContactResult perturbedResultOut(resultOut,input.m_transformA,input.m_transformB,unPerturbedTransform,perturbeA,dispatchInfo.m_debugDraw);
  642. gjkPairDetector.getClosestPoints(input,perturbedResultOut,dispatchInfo.m_debugDraw);
  643. }
  644. }
  645. }
  646. }
  647. #ifdef USE_SEPDISTANCE_UTIL2
  648. if (dispatchInfo.m_useConvexConservativeDistanceUtil && (sepDist>SIMD_EPSILON))
  649. {
  650. m_sepDistance.initSeparatingDistance(gjkPairDetector.getCachedSeparatingAxis(),sepDist,body0->getWorldTransform(),body1->getWorldTransform());
  651. }
  652. #endif //USE_SEPDISTANCE_UTIL2
  653. }
  654. if (m_ownManifold)
  655. {
  656. resultOut->refreshContactPoints();
  657. }
  658. }
  659. bool disableCcd = false;
  660. btScalar btConvexConvexAlgorithm::calculateTimeOfImpact(btCollisionObject* col0,btCollisionObject* col1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
  661. {
  662. (void)resultOut;
  663. (void)dispatchInfo;
  664. ///Rather then checking ALL pairs, only calculate TOI when motion exceeds threshold
  665. ///Linear motion for one of objects needs to exceed m_ccdSquareMotionThreshold
  666. ///col0->m_worldTransform,
  667. btScalar resultFraction = btScalar(1.);
  668. btScalar squareMot0 = (col0->getInterpolationWorldTransform().getOrigin() - col0->getWorldTransform().getOrigin()).length2();
  669. btScalar squareMot1 = (col1->getInterpolationWorldTransform().getOrigin() - col1->getWorldTransform().getOrigin()).length2();
  670. if (squareMot0 < col0->getCcdSquareMotionThreshold() &&
  671. squareMot1 < col1->getCcdSquareMotionThreshold())
  672. return resultFraction;
  673. if (disableCcd)
  674. return btScalar(1.);
  675. //An adhoc way of testing the Continuous Collision Detection algorithms
  676. //One object is approximated as a sphere, to simplify things
  677. //Starting in penetration should report no time of impact
  678. //For proper CCD, better accuracy and handling of 'allowed' penetration should be added
  679. //also the mainloop of the physics should have a kind of toi queue (something like Brian Mirtich's application of Timewarp for Rigidbodies)
  680. /// Convex0 against sphere for Convex1
  681. {
  682. btConvexShape* convex0 = static_cast<btConvexShape*>(col0->getCollisionShape());
  683. btSphereShape sphere1(col1->getCcdSweptSphereRadius()); //todo: allow non-zero sphere sizes, for better approximation
  684. btConvexCast::CastResult result;
  685. btVoronoiSimplexSolver voronoiSimplex;
  686. //SubsimplexConvexCast ccd0(&sphere,min0,&voronoiSimplex);
  687. ///Simplification, one object is simplified as a sphere
  688. btGjkConvexCast ccd1( convex0 ,&sphere1,&voronoiSimplex);
  689. //ContinuousConvexCollision ccd(min0,min1,&voronoiSimplex,0);
  690. if (ccd1.calcTimeOfImpact(col0->getWorldTransform(),col0->getInterpolationWorldTransform(),
  691. col1->getWorldTransform(),col1->getInterpolationWorldTransform(),result))
  692. {
  693. //store result.m_fraction in both bodies
  694. if (col0->getHitFraction()> result.m_fraction)
  695. col0->setHitFraction( result.m_fraction );
  696. if (col1->getHitFraction() > result.m_fraction)
  697. col1->setHitFraction( result.m_fraction);
  698. if (resultFraction > result.m_fraction)
  699. resultFraction = result.m_fraction;
  700. }
  701. }
  702. /// Sphere (for convex0) against Convex1
  703. {
  704. btConvexShape* convex1 = static_cast<btConvexShape*>(col1->getCollisionShape());
  705. btSphereShape sphere0(col0->getCcdSweptSphereRadius()); //todo: allow non-zero sphere sizes, for better approximation
  706. btConvexCast::CastResult result;
  707. btVoronoiSimplexSolver voronoiSimplex;
  708. //SubsimplexConvexCast ccd0(&sphere,min0,&voronoiSimplex);
  709. ///Simplification, one object is simplified as a sphere
  710. btGjkConvexCast ccd1(&sphere0,convex1,&voronoiSimplex);
  711. //ContinuousConvexCollision ccd(min0,min1,&voronoiSimplex,0);
  712. if (ccd1.calcTimeOfImpact(col0->getWorldTransform(),col0->getInterpolationWorldTransform(),
  713. col1->getWorldTransform(),col1->getInterpolationWorldTransform(),result))
  714. {
  715. //store result.m_fraction in both bodies
  716. if (col0->getHitFraction() > result.m_fraction)
  717. col0->setHitFraction( result.m_fraction);
  718. if (col1->getHitFraction() > result.m_fraction)
  719. col1->setHitFraction( result.m_fraction);
  720. if (resultFraction > result.m_fraction)
  721. resultFraction = result.m_fraction;
  722. }
  723. }
  724. return resultFraction;
  725. }