gjk_epa.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  1. /*************************************************************************/
  2. /* gjk_epa.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* http://www.godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  9. /* */
  10. /* Permission is hereby granted, free of charge, to any person obtaining */
  11. /* a copy of this software and associated documentation files (the */
  12. /* "Software"), to deal in the Software without restriction, including */
  13. /* without limitation the rights to use, copy, modify, merge, publish, */
  14. /* distribute, sublicense, and/or sell copies of the Software, and to */
  15. /* permit persons to whom the Software is furnished to do so, subject to */
  16. /* the following conditions: */
  17. /* */
  18. /* The above copyright notice and this permission notice shall be */
  19. /* included in all copies or substantial portions of the Software. */
  20. /* */
  21. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  22. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  23. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  24. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  25. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  26. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  27. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  28. /*************************************************************************/
  29. #include "gjk_epa.h"
  30. /*************** Bullet's GJK-EPA2 IMPLEMENTATION *******************/
  31. // Config
  32. /* GJK */
  33. #define GJK_MAX_ITERATIONS 128
  34. #define GJK_ACCURARY ((real_t)0.0001)
  35. #define GJK_MIN_DISTANCE ((real_t)0.0001)
  36. #define GJK_DUPLICATED_EPS ((real_t)0.0001)
  37. #define GJK_SIMPLEX2_EPS ((real_t)0.0)
  38. #define GJK_SIMPLEX3_EPS ((real_t)0.0)
  39. #define GJK_SIMPLEX4_EPS ((real_t)0.0)
  40. /* EPA */
  41. #define EPA_MAX_VERTICES 64
  42. #define EPA_MAX_FACES (EPA_MAX_VERTICES*2)
  43. #define EPA_MAX_ITERATIONS 255
  44. #define EPA_ACCURACY ((real_t)0.0001)
  45. #define EPA_FALLBACK (10*EPA_ACCURACY)
  46. #define EPA_PLANE_EPS ((real_t)0.00001)
  47. #define EPA_INSIDE_EPS ((real_t)0.01)
  48. namespace GjkEpa2 {
  49. struct sResults {
  50. enum eStatus {
  51. Separated, /* Shapes doesnt penetrate */
  52. Penetrating, /* Shapes are penetrating */
  53. GJK_Failed, /* GJK phase fail, no big issue, shapes are probably just 'touching' */
  54. EPA_Failed /* EPA phase fail, bigger problem, need to save parameters, and debug */
  55. } status;
  56. Vector3 witnesses[2];
  57. Vector3 normal;
  58. real_t distance;
  59. };
  60. // Shorthands
  61. typedef unsigned int U;
  62. typedef unsigned char U1;
  63. // MinkowskiDiff
  64. struct MinkowskiDiff {
  65. const ShapeSW* m_shapes[2];
  66. Transform transform_A;
  67. Transform transform_B;
  68. // i wonder how this could be sped up... if it can
  69. _FORCE_INLINE_ Vector3 Support0 ( const Vector3& d ) const {
  70. return transform_A.xform( m_shapes[0]->get_support( transform_A.basis.xform_inv(d).normalized() ) );
  71. }
  72. _FORCE_INLINE_ Vector3 Support1 ( const Vector3& d ) const {
  73. return transform_B.xform( m_shapes[1]->get_support( transform_B.basis.xform_inv(d).normalized() ) );
  74. }
  75. _FORCE_INLINE_ Vector3 Support ( const Vector3& d ) const {
  76. return ( Support0 ( d )-Support1 ( -d ) );
  77. }
  78. _FORCE_INLINE_ Vector3 Support ( const Vector3& d,U index ) const
  79. {
  80. if ( index )
  81. return ( Support1 ( d ) );
  82. else
  83. return ( Support0 ( d ) );
  84. }
  85. };
  86. typedef MinkowskiDiff tShape;
  87. // GJK
  88. struct GJK
  89. {
  90. /* Types */
  91. struct sSV
  92. {
  93. Vector3 d,w;
  94. };
  95. struct sSimplex
  96. {
  97. sSV* c[4];
  98. real_t p[4];
  99. U rank;
  100. };
  101. struct eStatus { enum _ {
  102. Valid,
  103. Inside,
  104. Failed };};
  105. /* Fields */
  106. tShape m_shape;
  107. Vector3 m_ray;
  108. real_t m_distance;
  109. sSimplex m_simplices[2];
  110. sSV m_store[4];
  111. sSV* m_free[4];
  112. U m_nfree;
  113. U m_current;
  114. sSimplex* m_simplex;
  115. eStatus::_ m_status;
  116. /* Methods */
  117. GJK()
  118. {
  119. Initialize();
  120. }
  121. void Initialize()
  122. {
  123. m_ray = Vector3(0,0,0);
  124. m_nfree = 0;
  125. m_status = eStatus::Failed;
  126. m_current = 0;
  127. m_distance = 0;
  128. }
  129. eStatus::_ Evaluate(const tShape& shapearg,const Vector3& guess)
  130. {
  131. U iterations=0;
  132. real_t sqdist=0;
  133. real_t alpha=0;
  134. Vector3 lastw[4];
  135. U clastw=0;
  136. /* Initialize solver */
  137. m_free[0] = &m_store[0];
  138. m_free[1] = &m_store[1];
  139. m_free[2] = &m_store[2];
  140. m_free[3] = &m_store[3];
  141. m_nfree = 4;
  142. m_current = 0;
  143. m_status = eStatus::Valid;
  144. m_shape = shapearg;
  145. m_distance = 0;
  146. /* Initialize simplex */
  147. m_simplices[0].rank = 0;
  148. m_ray = guess;
  149. const real_t sqrl= m_ray.length_squared();
  150. appendvertice(m_simplices[0],sqrl>0?-m_ray:Vector3(1,0,0));
  151. m_simplices[0].p[0] = 1;
  152. m_ray = m_simplices[0].c[0]->w;
  153. sqdist = sqrl;
  154. lastw[0] =
  155. lastw[1] =
  156. lastw[2] =
  157. lastw[3] = m_ray;
  158. /* Loop */
  159. do {
  160. const U next=1-m_current;
  161. sSimplex& cs=m_simplices[m_current];
  162. sSimplex& ns=m_simplices[next];
  163. /* Check zero */
  164. const real_t rl=m_ray.length();
  165. if(rl<GJK_MIN_DISTANCE)
  166. {/* Touching or inside */
  167. m_status=eStatus::Inside;
  168. break;
  169. }
  170. /* Append new vertice in -'v' direction */
  171. appendvertice(cs,-m_ray);
  172. const Vector3& w=cs.c[cs.rank-1]->w;
  173. bool found=false;
  174. for(U i=0;i<4;++i)
  175. {
  176. if((w-lastw[i]).length_squared()<GJK_DUPLICATED_EPS)
  177. { found=true;break; }
  178. }
  179. if(found)
  180. {/* Return old simplex */
  181. removevertice(m_simplices[m_current]);
  182. break;
  183. }
  184. else
  185. {/* Update lastw */
  186. lastw[clastw=(clastw+1)&3]=w;
  187. }
  188. /* Check for termination */
  189. const real_t omega=vec3_dot(m_ray,w)/rl;
  190. alpha=MAX(omega,alpha);
  191. if(((rl-alpha)-(GJK_ACCURARY*rl))<=0)
  192. {/* Return old simplex */
  193. removevertice(m_simplices[m_current]);
  194. break;
  195. }
  196. /* Reduce simplex */
  197. real_t weights[4];
  198. U mask=0;
  199. switch(cs.rank)
  200. {
  201. case 2: sqdist=projectorigin( cs.c[0]->w,
  202. cs.c[1]->w,
  203. weights,mask);break;
  204. case 3: sqdist=projectorigin( cs.c[0]->w,
  205. cs.c[1]->w,
  206. cs.c[2]->w,
  207. weights,mask);break;
  208. case 4: sqdist=projectorigin( cs.c[0]->w,
  209. cs.c[1]->w,
  210. cs.c[2]->w,
  211. cs.c[3]->w,
  212. weights,mask);break;
  213. }
  214. if(sqdist>=0)
  215. {/* Valid */
  216. ns.rank = 0;
  217. m_ray = Vector3(0,0,0);
  218. m_current = next;
  219. for(U i=0,ni=cs.rank;i<ni;++i)
  220. {
  221. if(mask&(1<<i))
  222. {
  223. ns.c[ns.rank] = cs.c[i];
  224. ns.p[ns.rank++] = weights[i];
  225. m_ray += cs.c[i]->w*weights[i];
  226. }
  227. else
  228. {
  229. m_free[m_nfree++] = cs.c[i];
  230. }
  231. }
  232. if(mask==15) m_status=eStatus::Inside;
  233. }
  234. else
  235. {/* Return old simplex */
  236. removevertice(m_simplices[m_current]);
  237. break;
  238. }
  239. m_status=((++iterations)<GJK_MAX_ITERATIONS)?m_status:eStatus::Failed;
  240. } while(m_status==eStatus::Valid);
  241. m_simplex=&m_simplices[m_current];
  242. switch(m_status)
  243. {
  244. case eStatus::Valid: m_distance=m_ray.length();break;
  245. case eStatus::Inside: m_distance=0;break;
  246. default: {}
  247. }
  248. return(m_status);
  249. }
  250. bool EncloseOrigin()
  251. {
  252. switch(m_simplex->rank)
  253. {
  254. case 1:
  255. {
  256. for(U i=0;i<3;++i)
  257. {
  258. Vector3 axis=Vector3(0,0,0);
  259. axis[i]=1;
  260. appendvertice(*m_simplex, axis);
  261. if(EncloseOrigin()) return(true);
  262. removevertice(*m_simplex);
  263. appendvertice(*m_simplex,-axis);
  264. if(EncloseOrigin()) return(true);
  265. removevertice(*m_simplex);
  266. }
  267. }
  268. break;
  269. case 2:
  270. {
  271. const Vector3 d=m_simplex->c[1]->w-m_simplex->c[0]->w;
  272. for(U i=0;i<3;++i)
  273. {
  274. Vector3 axis=Vector3(0,0,0);
  275. axis[i]=1;
  276. const Vector3 p=vec3_cross(d,axis);
  277. if(p.length_squared()>0)
  278. {
  279. appendvertice(*m_simplex, p);
  280. if(EncloseOrigin()) return(true);
  281. removevertice(*m_simplex);
  282. appendvertice(*m_simplex,-p);
  283. if(EncloseOrigin()) return(true);
  284. removevertice(*m_simplex);
  285. }
  286. }
  287. }
  288. break;
  289. case 3:
  290. {
  291. const Vector3 n=vec3_cross(m_simplex->c[1]->w-m_simplex->c[0]->w,
  292. m_simplex->c[2]->w-m_simplex->c[0]->w);
  293. if(n.length_squared()>0)
  294. {
  295. appendvertice(*m_simplex,n);
  296. if(EncloseOrigin()) return(true);
  297. removevertice(*m_simplex);
  298. appendvertice(*m_simplex,-n);
  299. if(EncloseOrigin()) return(true);
  300. removevertice(*m_simplex);
  301. }
  302. }
  303. break;
  304. case 4:
  305. {
  306. if(Math::abs(det( m_simplex->c[0]->w-m_simplex->c[3]->w,
  307. m_simplex->c[1]->w-m_simplex->c[3]->w,
  308. m_simplex->c[2]->w-m_simplex->c[3]->w))>0)
  309. return(true);
  310. }
  311. break;
  312. }
  313. return(false);
  314. }
  315. /* Internals */
  316. void getsupport(const Vector3& d,sSV& sv) const
  317. {
  318. sv.d = d/d.length();
  319. sv.w = m_shape.Support(sv.d);
  320. }
  321. void removevertice(sSimplex& simplex)
  322. {
  323. m_free[m_nfree++]=simplex.c[--simplex.rank];
  324. }
  325. void appendvertice(sSimplex& simplex,const Vector3& v)
  326. {
  327. simplex.p[simplex.rank]=0;
  328. simplex.c[simplex.rank]=m_free[--m_nfree];
  329. getsupport(v,*simplex.c[simplex.rank++]);
  330. }
  331. static real_t det(const Vector3& a,const Vector3& b,const Vector3& c)
  332. {
  333. return( a.y*b.z*c.x+a.z*b.x*c.y-
  334. a.x*b.z*c.y-a.y*b.x*c.z+
  335. a.x*b.y*c.z-a.z*b.y*c.x);
  336. }
  337. static real_t projectorigin( const Vector3& a,
  338. const Vector3& b,
  339. real_t* w,U& m)
  340. {
  341. const Vector3 d=b-a;
  342. const real_t l=d.length_squared();
  343. if(l>GJK_SIMPLEX2_EPS)
  344. {
  345. const real_t t(l>0?-vec3_dot(a,d)/l:0);
  346. if(t>=1) { w[0]=0;w[1]=1;m=2;return(b.length_squared()); }
  347. else if(t<=0) { w[0]=1;w[1]=0;m=1;return(a.length_squared()); }
  348. else { w[0]=1-(w[1]=t);m=3;return((a+d*t).length_squared()); }
  349. }
  350. return(-1);
  351. }
  352. static real_t projectorigin( const Vector3& a,
  353. const Vector3& b,
  354. const Vector3& c,
  355. real_t* w,U& m)
  356. {
  357. static const U imd3[]={1,2,0};
  358. const Vector3* vt[]={&a,&b,&c};
  359. const Vector3 dl[]={a-b,b-c,c-a};
  360. const Vector3 n=vec3_cross(dl[0],dl[1]);
  361. const real_t l=n.length_squared();
  362. if(l>GJK_SIMPLEX3_EPS)
  363. {
  364. real_t mindist=-1;
  365. real_t subw[2];
  366. U subm;
  367. for(U i=0;i<3;++i)
  368. {
  369. if(vec3_dot(*vt[i],vec3_cross(dl[i],n))>0)
  370. {
  371. const U j=imd3[i];
  372. const real_t subd(projectorigin(*vt[i],*vt[j],subw,subm));
  373. if((mindist<0)||(subd<mindist))
  374. {
  375. mindist = subd;
  376. m = static_cast<U>(((subm&1)?1<<i:0)+((subm&2)?1<<j:0));
  377. w[i] = subw[0];
  378. w[j] = subw[1];
  379. w[imd3[j]] = 0;
  380. }
  381. }
  382. }
  383. if(mindist<0)
  384. {
  385. const real_t d=vec3_dot(a,n);
  386. const real_t s=Math::sqrt(l);
  387. const Vector3 p=n*(d/l);
  388. mindist = p.length_squared();
  389. m = 7;
  390. w[0] = (vec3_cross(dl[1],b-p)).length()/s;
  391. w[1] = (vec3_cross(dl[2],c-p)).length()/s;
  392. w[2] = 1-(w[0]+w[1]);
  393. }
  394. return(mindist);
  395. }
  396. return(-1);
  397. }
  398. static real_t projectorigin( const Vector3& a,
  399. const Vector3& b,
  400. const Vector3& c,
  401. const Vector3& d,
  402. real_t* w,U& m)
  403. {
  404. static const U imd3[]={1,2,0};
  405. const Vector3* vt[]={&a,&b,&c,&d};
  406. const Vector3 dl[]={a-d,b-d,c-d};
  407. const real_t vl=det(dl[0],dl[1],dl[2]);
  408. const bool ng=(vl*vec3_dot(a,vec3_cross(b-c,a-b)))<=0;
  409. if(ng&&(Math::abs(vl)>GJK_SIMPLEX4_EPS))
  410. {
  411. real_t mindist=-1;
  412. real_t subw[3];
  413. U subm;
  414. for(U i=0;i<3;++i)
  415. {
  416. const U j=imd3[i];
  417. const real_t s=vl*vec3_dot(d,vec3_cross(dl[i],dl[j]));
  418. if(s>0)
  419. {
  420. const real_t subd=projectorigin(*vt[i],*vt[j],d,subw,subm);
  421. if((mindist<0)||(subd<mindist))
  422. {
  423. mindist = subd;
  424. m = static_cast<U>((subm&1?1<<i:0)+
  425. (subm&2?1<<j:0)+
  426. (subm&4?8:0));
  427. w[i] = subw[0];
  428. w[j] = subw[1];
  429. w[imd3[j]] = 0;
  430. w[3] = subw[2];
  431. }
  432. }
  433. }
  434. if(mindist<0)
  435. {
  436. mindist = 0;
  437. m = 15;
  438. w[0] = det(c,b,d)/vl;
  439. w[1] = det(a,c,d)/vl;
  440. w[2] = det(b,a,d)/vl;
  441. w[3] = 1-(w[0]+w[1]+w[2]);
  442. }
  443. return(mindist);
  444. }
  445. return(-1);
  446. }
  447. };
  448. // EPA
  449. struct EPA
  450. {
  451. /* Types */
  452. typedef GJK::sSV sSV;
  453. struct sFace
  454. {
  455. Vector3 n;
  456. real_t d;
  457. real_t p;
  458. sSV* c[3];
  459. sFace* f[3];
  460. sFace* l[2];
  461. U1 e[3];
  462. U1 pass;
  463. };
  464. struct sList
  465. {
  466. sFace* root;
  467. U count;
  468. sList() : root(0),count(0) {}
  469. };
  470. struct sHorizon
  471. {
  472. sFace* cf;
  473. sFace* ff;
  474. U nf;
  475. sHorizon() : cf(0),ff(0),nf(0) {}
  476. };
  477. struct eStatus { enum _ {
  478. Valid,
  479. Touching,
  480. Degenerated,
  481. NonConvex,
  482. InvalidHull,
  483. OutOfFaces,
  484. OutOfVertices,
  485. AccuraryReached,
  486. FallBack,
  487. Failed };};
  488. /* Fields */
  489. eStatus::_ m_status;
  490. GJK::sSimplex m_result;
  491. Vector3 m_normal;
  492. real_t m_depth;
  493. sSV m_sv_store[EPA_MAX_VERTICES];
  494. sFace m_fc_store[EPA_MAX_FACES];
  495. U m_nextsv;
  496. sList m_hull;
  497. sList m_stock;
  498. /* Methods */
  499. EPA()
  500. {
  501. Initialize();
  502. }
  503. static inline void bind(sFace* fa,U ea,sFace* fb,U eb)
  504. {
  505. fa->e[ea]=(U1)eb;fa->f[ea]=fb;
  506. fb->e[eb]=(U1)ea;fb->f[eb]=fa;
  507. }
  508. static inline void append(sList& list,sFace* face)
  509. {
  510. face->l[0] = 0;
  511. face->l[1] = list.root;
  512. if(list.root) list.root->l[0]=face;
  513. list.root = face;
  514. ++list.count;
  515. }
  516. static inline void remove(sList& list,sFace* face)
  517. {
  518. if(face->l[1]) face->l[1]->l[0]=face->l[0];
  519. if(face->l[0]) face->l[0]->l[1]=face->l[1];
  520. if(face==list.root) list.root=face->l[1];
  521. --list.count;
  522. }
  523. void Initialize()
  524. {
  525. m_status = eStatus::Failed;
  526. m_normal = Vector3(0,0,0);
  527. m_depth = 0;
  528. m_nextsv = 0;
  529. for(U i=0;i<EPA_MAX_FACES;++i)
  530. {
  531. append(m_stock,&m_fc_store[EPA_MAX_FACES-i-1]);
  532. }
  533. }
  534. eStatus::_ Evaluate(GJK& gjk,const Vector3& guess)
  535. {
  536. GJK::sSimplex& simplex=*gjk.m_simplex;
  537. if((simplex.rank>1)&&gjk.EncloseOrigin())
  538. {
  539. /* Clean up */
  540. while(m_hull.root)
  541. {
  542. sFace* f = m_hull.root;
  543. remove(m_hull,f);
  544. append(m_stock,f);
  545. }
  546. m_status = eStatus::Valid;
  547. m_nextsv = 0;
  548. /* Orient simplex */
  549. if(gjk.det( simplex.c[0]->w-simplex.c[3]->w,
  550. simplex.c[1]->w-simplex.c[3]->w,
  551. simplex.c[2]->w-simplex.c[3]->w)<0)
  552. {
  553. SWAP(simplex.c[0],simplex.c[1]);
  554. SWAP(simplex.p[0],simplex.p[1]);
  555. }
  556. /* Build initial hull */
  557. sFace* tetra[]={newface(simplex.c[0],simplex.c[1],simplex.c[2],true),
  558. newface(simplex.c[1],simplex.c[0],simplex.c[3],true),
  559. newface(simplex.c[2],simplex.c[1],simplex.c[3],true),
  560. newface(simplex.c[0],simplex.c[2],simplex.c[3],true)};
  561. if(m_hull.count==4)
  562. {
  563. sFace* best=findbest();
  564. sFace outer=*best;
  565. U pass=0;
  566. U iterations=0;
  567. bind(tetra[0],0,tetra[1],0);
  568. bind(tetra[0],1,tetra[2],0);
  569. bind(tetra[0],2,tetra[3],0);
  570. bind(tetra[1],1,tetra[3],2);
  571. bind(tetra[1],2,tetra[2],1);
  572. bind(tetra[2],2,tetra[3],1);
  573. m_status=eStatus::Valid;
  574. for(;iterations<EPA_MAX_ITERATIONS;++iterations)
  575. {
  576. if(m_nextsv<EPA_MAX_VERTICES)
  577. {
  578. sHorizon horizon;
  579. sSV* w=&m_sv_store[m_nextsv++];
  580. bool valid=true;
  581. best->pass = (U1)(++pass);
  582. gjk.getsupport(best->n,*w);
  583. const real_t wdist=vec3_dot(best->n,w->w)-best->d;
  584. if(wdist>EPA_ACCURACY)
  585. {
  586. for(U j=0;(j<3)&&valid;++j)
  587. {
  588. valid&=expand( pass,w,
  589. best->f[j],best->e[j],
  590. horizon);
  591. }
  592. if(valid&&(horizon.nf>=3))
  593. {
  594. bind(horizon.cf,1,horizon.ff,2);
  595. remove(m_hull,best);
  596. append(m_stock,best);
  597. best=findbest();
  598. if(best->p>=outer.p) outer=*best;
  599. } else { m_status=eStatus::InvalidHull;break; }
  600. } else { m_status=eStatus::AccuraryReached;break; }
  601. } else { m_status=eStatus::OutOfVertices;break; }
  602. }
  603. const Vector3 projection=outer.n*outer.d;
  604. m_normal = outer.n;
  605. m_depth = outer.d;
  606. m_result.rank = 3;
  607. m_result.c[0] = outer.c[0];
  608. m_result.c[1] = outer.c[1];
  609. m_result.c[2] = outer.c[2];
  610. m_result.p[0] = vec3_cross( outer.c[1]->w-projection,
  611. outer.c[2]->w-projection).length();
  612. m_result.p[1] = vec3_cross( outer.c[2]->w-projection,
  613. outer.c[0]->w-projection).length();
  614. m_result.p[2] = vec3_cross( outer.c[0]->w-projection,
  615. outer.c[1]->w-projection).length();
  616. const real_t sum=m_result.p[0]+m_result.p[1]+m_result.p[2];
  617. m_result.p[0] /= sum;
  618. m_result.p[1] /= sum;
  619. m_result.p[2] /= sum;
  620. return(m_status);
  621. }
  622. }
  623. /* Fallback */
  624. m_status = eStatus::FallBack;
  625. m_normal = -guess;
  626. const real_t nl=m_normal.length();
  627. if(nl>0)
  628. m_normal = m_normal/nl;
  629. else
  630. m_normal = Vector3(1,0,0);
  631. m_depth = 0;
  632. m_result.rank=1;
  633. m_result.c[0]=simplex.c[0];
  634. m_result.p[0]=1;
  635. return(m_status);
  636. }
  637. sFace* newface(sSV* a,sSV* b,sSV* c,bool forced)
  638. {
  639. if(m_stock.root)
  640. {
  641. sFace* face=m_stock.root;
  642. remove(m_stock,face);
  643. append(m_hull,face);
  644. face->pass = 0;
  645. face->c[0] = a;
  646. face->c[1] = b;
  647. face->c[2] = c;
  648. face->n = vec3_cross(b->w-a->w,c->w-a->w);
  649. const real_t l=face->n.length();
  650. const bool v=l>EPA_ACCURACY;
  651. face->p = MIN(MIN(
  652. vec3_dot(a->w,vec3_cross(face->n,a->w-b->w)),
  653. vec3_dot(b->w,vec3_cross(face->n,b->w-c->w))),
  654. vec3_dot(c->w,vec3_cross(face->n,c->w-a->w))) /
  655. (v?l:1);
  656. face->p = face->p>=-EPA_INSIDE_EPS?0:face->p;
  657. if(v)
  658. {
  659. face->d = vec3_dot(a->w,face->n)/l;
  660. face->n /= l;
  661. if(forced||(face->d>=-EPA_PLANE_EPS))
  662. {
  663. return(face);
  664. } else m_status=eStatus::NonConvex;
  665. } else m_status=eStatus::Degenerated;
  666. remove(m_hull,face);
  667. append(m_stock,face);
  668. return(0);
  669. }
  670. m_status=m_stock.root?eStatus::OutOfVertices:eStatus::OutOfFaces;
  671. return(0);
  672. }
  673. sFace* findbest()
  674. {
  675. sFace* minf=m_hull.root;
  676. real_t mind=minf->d*minf->d;
  677. real_t maxp=minf->p;
  678. for(sFace* f=minf->l[1];f;f=f->l[1])
  679. {
  680. const real_t sqd=f->d*f->d;
  681. if((f->p>=maxp)&&(sqd<mind))
  682. {
  683. minf=f;
  684. mind=sqd;
  685. maxp=f->p;
  686. }
  687. }
  688. return(minf);
  689. }
  690. bool expand(U pass,sSV* w,sFace* f,U e,sHorizon& horizon)
  691. {
  692. static const U i1m3[]={1,2,0};
  693. static const U i2m3[]={2,0,1};
  694. if(f->pass!=pass)
  695. {
  696. const U e1=i1m3[e];
  697. if((vec3_dot(f->n,w->w)-f->d)<-EPA_PLANE_EPS)
  698. {
  699. sFace* nf=newface(f->c[e1],f->c[e],w,false);
  700. if(nf)
  701. {
  702. bind(nf,0,f,e);
  703. if(horizon.cf) bind(horizon.cf,1,nf,2); else horizon.ff=nf;
  704. horizon.cf=nf;
  705. ++horizon.nf;
  706. return(true);
  707. }
  708. }
  709. else
  710. {
  711. const U e2=i2m3[e];
  712. f->pass = (U1)pass;
  713. if( expand(pass,w,f->f[e1],f->e[e1],horizon)&&
  714. expand(pass,w,f->f[e2],f->e[e2],horizon))
  715. {
  716. remove(m_hull,f);
  717. append(m_stock,f);
  718. return(true);
  719. }
  720. }
  721. }
  722. return(false);
  723. }
  724. };
  725. //
  726. static void Initialize( const ShapeSW* shape0,const Transform& wtrs0,
  727. const ShapeSW* shape1,const Transform& wtrs1,
  728. sResults& results,
  729. tShape& shape,
  730. bool withmargins)
  731. {
  732. /* Results */
  733. results.witnesses[0] =
  734. results.witnesses[1] = Vector3(0,0,0);
  735. results.status = sResults::Separated;
  736. /* Shape */
  737. shape.m_shapes[0] = shape0;
  738. shape.m_shapes[1] = shape1;
  739. shape.transform_A = wtrs0;
  740. shape.transform_B = wtrs1;
  741. }
  742. //
  743. // Api
  744. //
  745. //
  746. //
  747. bool Distance( const ShapeSW* shape0,
  748. const Transform& wtrs0,
  749. const ShapeSW* shape1,
  750. const Transform& wtrs1,
  751. const Vector3& guess,
  752. sResults& results)
  753. {
  754. tShape shape;
  755. Initialize(shape0,wtrs0,shape1,wtrs1,results,shape,false);
  756. GJK gjk;
  757. GJK::eStatus::_ gjk_status=gjk.Evaluate(shape,guess);
  758. if(gjk_status==GJK::eStatus::Valid)
  759. {
  760. Vector3 w0=Vector3(0,0,0);
  761. Vector3 w1=Vector3(0,0,0);
  762. for(U i=0;i<gjk.m_simplex->rank;++i)
  763. {
  764. const real_t p=gjk.m_simplex->p[i];
  765. w0+=shape.Support( gjk.m_simplex->c[i]->d,0)*p;
  766. w1+=shape.Support(-gjk.m_simplex->c[i]->d,1)*p;
  767. }
  768. results.witnesses[0] = wtrs0.xform(w0);
  769. results.witnesses[1] = wtrs0.xform(w1);
  770. results.normal = w0-w1;
  771. results.distance = results.normal.length();
  772. results.normal /= results.distance>GJK_MIN_DISTANCE?results.distance:1;
  773. return(true);
  774. }
  775. else
  776. {
  777. results.status = gjk_status==GJK::eStatus::Inside?
  778. sResults::Penetrating :
  779. sResults::GJK_Failed ;
  780. return(false);
  781. }
  782. }
  783. //
  784. bool Penetration( const ShapeSW* shape0,
  785. const Transform& wtrs0,
  786. const ShapeSW* shape1,
  787. const Transform& wtrs1,
  788. const Vector3& guess,
  789. sResults& results
  790. )
  791. {
  792. tShape shape;
  793. Initialize(shape0,wtrs0,shape1,wtrs1,results,shape,false);
  794. GJK gjk;
  795. GJK::eStatus::_ gjk_status=gjk.Evaluate(shape,-guess);
  796. switch(gjk_status)
  797. {
  798. case GJK::eStatus::Inside:
  799. {
  800. EPA epa;
  801. EPA::eStatus::_ epa_status=epa.Evaluate(gjk,-guess);
  802. if(epa_status!=EPA::eStatus::Failed)
  803. {
  804. Vector3 w0=Vector3(0,0,0);
  805. for(U i=0;i<epa.m_result.rank;++i)
  806. {
  807. w0+=shape.Support(epa.m_result.c[i]->d,0)*epa.m_result.p[i];
  808. }
  809. results.status = sResults::Penetrating;
  810. results.witnesses[0] = w0;
  811. results.witnesses[1] = w0-epa.m_normal*epa.m_depth;
  812. results.normal = -epa.m_normal;
  813. results.distance = -epa.m_depth;
  814. return(true);
  815. } else results.status=sResults::EPA_Failed;
  816. }
  817. break;
  818. case GJK::eStatus::Failed:
  819. results.status=sResults::GJK_Failed;
  820. break;
  821. default: {}
  822. }
  823. return(false);
  824. }
  825. /* Symbols cleanup */
  826. #undef GJK_MAX_ITERATIONS
  827. #undef GJK_ACCURARY
  828. #undef GJK_MIN_DISTANCE
  829. #undef GJK_DUPLICATED_EPS
  830. #undef GJK_SIMPLEX2_EPS
  831. #undef GJK_SIMPLEX3_EPS
  832. #undef GJK_SIMPLEX4_EPS
  833. #undef EPA_MAX_VERTICES
  834. #undef EPA_MAX_FACES
  835. #undef EPA_MAX_ITERATIONS
  836. #undef EPA_ACCURACY
  837. #undef EPA_FALLBACK
  838. #undef EPA_PLANE_EPS
  839. #undef EPA_INSIDE_EPS
  840. } // end of namespace
  841. bool gjk_epa_calculate_penetration(const ShapeSW *p_shape_A, const Transform& p_transform_A, const ShapeSW *p_shape_B, const Transform& p_transform_B, CollisionSolverSW::CallbackResult p_result_callback,void *p_userdata, bool p_swap ) {
  842. GjkEpa2::sResults res;
  843. if (GjkEpa2::Penetration(p_shape_A,p_transform_A,p_shape_B,p_transform_B,p_transform_B.origin-p_transform_A.origin,res)) {
  844. if (p_result_callback) {
  845. if (p_swap)
  846. p_result_callback(res.witnesses[1],res.witnesses[0],p_userdata);
  847. else
  848. p_result_callback(res.witnesses[0],res.witnesses[1],p_userdata);
  849. }
  850. return true;
  851. }
  852. return false;
  853. }