btConvexConvexAlgorithm.cpp 31 KB

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