btConvexConvexAlgorithm.cpp 25 KB

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