AABB.h 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2015 Alec Jacobson <alecjacobson@gmail.com>
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public License
  6. // v. 2.0. If a copy of the MPL was not distributed with this file, You can
  7. // obtain one at http://mozilla.org/MPL/2.0/.
  8. #ifndef IGL_AABB_H
  9. #define IGL_AABB_H
  10. #include "Hit.h"
  11. #include <Eigen/Core>
  12. #include <Eigen/Geometry>
  13. #include <vector>
  14. namespace igl
  15. {
  16. // Implementation of semi-general purpose axis-aligned bounding box hierarchy.
  17. // The mesh (V,Ele) is stored and managed by the caller and each routine here
  18. // simply takes it as references (it better not change between calls).
  19. //
  20. // It's a little annoying that the Dimension is a template parameter and not
  21. // picked up at run time from V. This leads to duplicated code for 2d/3d (up to
  22. // dim).
  23. template <typename DerivedV, int DIM>
  24. class AABB
  25. {
  26. public:
  27. typedef typename DerivedV::Scalar Scalar;
  28. typedef Eigen::Matrix<Scalar,1,DIM> RowVectorDIMS;
  29. typedef Eigen::Matrix<Scalar,DIM,1> VectorDIMS;
  30. typedef Eigen::Matrix<Scalar,Eigen::Dynamic,DIM> MatrixXDIMS;
  31. // Shared pointers are slower...
  32. AABB * m_left;
  33. AABB * m_right;
  34. Eigen::AlignedBox<Scalar,DIM> m_box;
  35. // -1 non-leaf
  36. int m_primitive;
  37. //Scalar m_max_sqr_d;
  38. //int m_depth;
  39. AABB():
  40. m_left(NULL), m_right(NULL),
  41. m_box(), m_primitive(-1)
  42. //m_max_sqr_d(std::numeric_limits<double>::infinity()),
  43. //m_depth(0)
  44. {}
  45. // http://stackoverflow.com/a/3279550/148668
  46. AABB(const AABB& other):
  47. m_left(other.m_left ? new AABB(*other.m_left) : NULL),
  48. m_right(other.m_right ? new AABB(*other.m_right) : NULL),
  49. m_box(other.m_box),
  50. m_primitive(other.m_primitive)
  51. //m_max_sqr_d(other.m_max_sqr_d),
  52. //m_depth(std::max(
  53. // m_left ? m_left->m_depth + 1 : 0,
  54. // m_right ? m_right->m_depth + 1 : 0))
  55. {
  56. }
  57. // copy-swap idiom
  58. friend void swap(AABB& first, AABB& second)
  59. {
  60. // Enable ADL
  61. using std::swap;
  62. swap(first.m_left,second.m_left);
  63. swap(first.m_right,second.m_right);
  64. swap(first.m_box,second.m_box);
  65. swap(first.m_primitive,second.m_primitive);
  66. //swap(first.m_max_sqr_d,second.m_max_sqr_d);
  67. //swap(first.m_depth,second.m_depth);
  68. }
  69. // Pass-by-value (aka copy)
  70. AABB& operator=(AABB other)
  71. {
  72. swap(*this,other);
  73. return *this;
  74. }
  75. AABB(AABB&& other):
  76. // initialize via default constructor
  77. AABB()
  78. {
  79. swap(*this,other);
  80. }
  81. // Seems like there should have been an elegant solution to this using
  82. // the copy-swap idiom above:
  83. inline void deinit()
  84. {
  85. m_primitive = -1;
  86. m_box = Eigen::AlignedBox<Scalar,DIM>();
  87. delete m_left;
  88. m_left = NULL;
  89. delete m_right;
  90. m_right = NULL;
  91. }
  92. ~AABB()
  93. {
  94. deinit();
  95. }
  96. // Build an Axis-Aligned Bounding Box tree for a given mesh and given
  97. // serialization of a previous AABB tree.
  98. //
  99. // Inputs:
  100. // V #V by dim list of mesh vertex positions.
  101. // Ele #Ele by dim+1 list of mesh indices into #V.
  102. // bb_mins max_tree by dim list of bounding box min corner positions
  103. // bb_maxs max_tree by dim list of bounding box max corner positions
  104. // elements max_tree list of element or (not leaf id) indices into Ele
  105. // i recursive call index {0}
  106. template <typename Derivedbb_mins, typename Derivedbb_maxs>
  107. inline void init(
  108. const Eigen::PlainObjectBase<DerivedV> & V,
  109. const Eigen::MatrixXi & Ele,
  110. const Eigen::PlainObjectBase<Derivedbb_mins> & bb_mins,
  111. const Eigen::PlainObjectBase<Derivedbb_maxs> & bb_maxs,
  112. const Eigen::VectorXi & elements,
  113. const int i = 0);
  114. // Wrapper for root with empty serialization
  115. inline void init(
  116. const Eigen::PlainObjectBase<DerivedV> & V,
  117. const Eigen::MatrixXi & Ele);
  118. // Build an Axis-Aligned Bounding Box tree for a given mesh.
  119. //
  120. // Inputs:
  121. // V #V by dim list of mesh vertex positions.
  122. // Ele #Ele by dim+1 list of mesh indices into #V.
  123. // SI #Ele by dim list revealing for each coordinate where Ele's
  124. // barycenters would be sorted: SI(e,d) = i --> the dth coordinate of
  125. // the barycenter of the eth element would be placed at position i in a
  126. // sorted list.
  127. // I #I list of indices into Ele of elements to include (for recursive
  128. // calls)
  129. //
  130. inline void init(
  131. const Eigen::PlainObjectBase<DerivedV> & V,
  132. const Eigen::MatrixXi & Ele,
  133. const Eigen::MatrixXi & SI,
  134. const Eigen::VectorXi & I);
  135. // Return whether at leaf node
  136. inline bool is_leaf() const;
  137. // Find the indices of elements containing given point: this makes sense
  138. // when Ele is a co-dimension 0 simplex (tets in 3D, triangles in 2D).
  139. //
  140. // Inputs:
  141. // V #V by dim list of mesh vertex positions. **Should be same as used to
  142. // construct mesh.**
  143. // Ele #Ele by dim+1 list of mesh indices into #V. **Should be same as used to
  144. // construct mesh.**
  145. // q dim row-vector query position
  146. // first whether to only return first element containing q
  147. // Returns:
  148. // list of indices of elements containing q
  149. template <typename Derivedq>
  150. inline std::vector<int> find(
  151. const Eigen::PlainObjectBase<DerivedV> & V,
  152. const Eigen::MatrixXi & Ele,
  153. const Eigen::PlainObjectBase<Derivedq> & q,
  154. const bool first=false) const;
  155. // If number of elements m then total tree size should be 2*h where h is
  156. // the deepest depth 2^ceil(log(#Ele*2-1))
  157. inline int subtree_size() const;
  158. // Serialize this class into 3 arrays (so we can pass it pack to matlab)
  159. //
  160. // Outputs:
  161. // bb_mins max_tree by dim list of bounding box min corner positions
  162. // bb_maxs max_tree by dim list of bounding box max corner positions
  163. // elements max_tree list of element or (not leaf id) indices into Ele
  164. // i recursive call index into these arrays {0}
  165. template <typename Derivedbb_mins, typename Derivedbb_maxs>
  166. inline void serialize(
  167. Eigen::PlainObjectBase<Derivedbb_mins> & bb_mins,
  168. Eigen::PlainObjectBase<Derivedbb_maxs> & bb_maxs,
  169. Eigen::VectorXi & elements,
  170. const int i = 0) const;
  171. // Compute squared distance to a query point
  172. //
  173. // Inputs:
  174. // V #V by dim list of vertex positions
  175. // Ele #Ele by dim list of simplex indices
  176. // P 3 list of query point coordinates
  177. // min_sqr_d current minimum squared distance (only find distances
  178. // less than this)
  179. // Outputs:
  180. // I #P list of facet indices corresponding to smallest distances
  181. // C #P by 3 list of closest points
  182. // Returns squared distance
  183. //
  184. // Known bugs: currently assumes Elements are triangles regardless of
  185. // dimension.
  186. inline Scalar squared_distance(
  187. const Eigen::PlainObjectBase<DerivedV> & V,
  188. const Eigen::MatrixXi & Ele,
  189. const RowVectorDIMS & p,
  190. int & i,
  191. RowVectorDIMS & c) const;
  192. //private:
  193. inline Scalar squared_distance(
  194. const Eigen::PlainObjectBase<DerivedV> & V,
  195. const Eigen::MatrixXi & Ele,
  196. const RowVectorDIMS & p,
  197. const Scalar min_sqr_d,
  198. int & i,
  199. RowVectorDIMS & c) const;
  200. // All hits
  201. inline bool intersect_ray(
  202. const Eigen::PlainObjectBase<DerivedV> & V,
  203. const Eigen::MatrixXi & Ele,
  204. const RowVectorDIMS & origin,
  205. const RowVectorDIMS & dir,
  206. std::vector<igl::Hit> & hits) const;
  207. // First hit
  208. inline bool intersect_ray(
  209. const Eigen::PlainObjectBase<DerivedV> & V,
  210. const Eigen::MatrixXi & Ele,
  211. const RowVectorDIMS & origin,
  212. const RowVectorDIMS & dir,
  213. igl::Hit & hit) const;
  214. //private:
  215. inline bool intersect_ray(
  216. const Eigen::PlainObjectBase<DerivedV> & V,
  217. const Eigen::MatrixXi & Ele,
  218. const RowVectorDIMS & origin,
  219. const RowVectorDIMS & dir,
  220. const Scalar min_t,
  221. igl::Hit & hit) const;
  222. public:
  223. template <
  224. typename DerivedP,
  225. typename DerivedsqrD,
  226. typename DerivedI,
  227. typename DerivedC>
  228. inline void squared_distance(
  229. const Eigen::PlainObjectBase<DerivedV> & V,
  230. const Eigen::MatrixXi & Ele,
  231. const Eigen::PlainObjectBase<DerivedP> & P,
  232. Eigen::PlainObjectBase<DerivedsqrD> & sqrD,
  233. Eigen::PlainObjectBase<DerivedI> & I,
  234. Eigen::PlainObjectBase<DerivedC> & C) const;
  235. template <
  236. typename Derivedother_V,
  237. typename DerivedsqrD,
  238. typename DerivedI,
  239. typename DerivedC>
  240. inline void squared_distance(
  241. const Eigen::PlainObjectBase<DerivedV> & V,
  242. const Eigen::MatrixXi & Ele,
  243. const AABB<Derivedother_V,DIM> & other,
  244. const Eigen::PlainObjectBase<Derivedother_V> & other_V,
  245. const Eigen::MatrixXi & other_Ele,
  246. Eigen::PlainObjectBase<DerivedsqrD> & sqrD,
  247. Eigen::PlainObjectBase<DerivedI> & I,
  248. Eigen::PlainObjectBase<DerivedC> & C) const;
  249. private:
  250. template <
  251. typename Derivedother_V,
  252. typename DerivedsqrD,
  253. typename DerivedI,
  254. typename DerivedC>
  255. inline Scalar squared_distance_helper(
  256. const Eigen::PlainObjectBase<DerivedV> & V,
  257. const Eigen::MatrixXi & Ele,
  258. const AABB<Derivedother_V,DIM> * other,
  259. const Eigen::PlainObjectBase<Derivedother_V> & other_V,
  260. const Eigen::MatrixXi & other_Ele,
  261. const Scalar min_sqr_d,
  262. Eigen::PlainObjectBase<DerivedsqrD> & sqrD,
  263. Eigen::PlainObjectBase<DerivedI> & I,
  264. Eigen::PlainObjectBase<DerivedC> & C) const;
  265. // Helper function for leaves: works in-place on sqr_d
  266. inline void leaf_squared_distance(
  267. const Eigen::PlainObjectBase<DerivedV> & V,
  268. const Eigen::MatrixXi & Ele,
  269. const RowVectorDIMS & p,
  270. Scalar & sqr_d,
  271. int & i,
  272. RowVectorDIMS & c) const;
  273. inline void set_min(
  274. const RowVectorDIMS & p,
  275. const Scalar sqr_d_candidate,
  276. const int i_candidate,
  277. const RowVectorDIMS & c_candidate,
  278. Scalar & sqr_d,
  279. int & i,
  280. RowVectorDIMS & c) const;
  281. public:
  282. static
  283. inline void barycentric_coordinates(
  284. const RowVectorDIMS & p,
  285. const RowVectorDIMS & a,
  286. const RowVectorDIMS & b,
  287. const RowVectorDIMS & c,
  288. Eigen::Matrix<Scalar,1,3> & bary);
  289. public:
  290. EIGEN_MAKE_ALIGNED_OPERATOR_NEW
  291. };
  292. }
  293. // Implementation
  294. #include "EPS.h"
  295. #include "barycenter.h"
  296. #include "colon.h"
  297. #include "colon.h"
  298. #include "doublearea.h"
  299. #include "matlab_format.h"
  300. #include "project_to_line_segment.h"
  301. #include "sort.h"
  302. #include "volume.h"
  303. #include "ray_box_intersect.h"
  304. #include "ray_mesh_intersect.h"
  305. #include <iostream>
  306. #include <iomanip>
  307. #include <limits>
  308. #include <list>
  309. #include <queue>
  310. #include <stack>
  311. template <typename DerivedV, int DIM>
  312. template <typename Derivedbb_mins, typename Derivedbb_maxs>
  313. inline void igl::AABB<DerivedV,DIM>::init(
  314. const Eigen::PlainObjectBase<DerivedV> & V,
  315. const Eigen::MatrixXi & Ele,
  316. const Eigen::PlainObjectBase<Derivedbb_mins> & bb_mins,
  317. const Eigen::PlainObjectBase<Derivedbb_maxs> & bb_maxs,
  318. const Eigen::VectorXi & elements,
  319. const int i)
  320. {
  321. using namespace std;
  322. using namespace Eigen;
  323. if(bb_mins.size() > 0)
  324. {
  325. assert(bb_mins.rows() == bb_maxs.rows() && "Serial tree arrays must match");
  326. assert(bb_mins.cols() == V.cols() && "Serial tree array dim must match V");
  327. assert(bb_mins.cols() == bb_maxs.cols() && "Serial tree arrays must match");
  328. assert(bb_mins.rows() == elements.rows() &&
  329. "Serial tree arrays must match");
  330. // construct from serialization
  331. m_box.extend(bb_mins.row(i).transpose());
  332. m_box.extend(bb_maxs.row(i).transpose());
  333. m_primitive = elements(i);
  334. // Not leaf then recurse
  335. if(m_primitive == -1)
  336. {
  337. m_left = new AABB();
  338. m_left->init( V,Ele,bb_mins,bb_maxs,elements,2*i+1);
  339. m_right = new AABB();
  340. m_right->init( V,Ele,bb_mins,bb_maxs,elements,2*i+2);
  341. //m_depth = std::max( m_left->m_depth, m_right->m_depth)+1;
  342. }
  343. }else
  344. {
  345. VectorXi allI = colon<int>(0,Ele.rows()-1);
  346. MatrixXDIMS BC;
  347. if(Ele.cols() == 1)
  348. {
  349. // points
  350. BC = V;
  351. }else
  352. {
  353. // Simplices
  354. barycenter(V,Ele,BC);
  355. }
  356. MatrixXi SI(BC.rows(),BC.cols());
  357. {
  358. MatrixXDIMS _;
  359. MatrixXi IS;
  360. igl::sort(BC,1,true,_,IS);
  361. // Need SI(i) to tell which place i would be sorted into
  362. const int dim = IS.cols();
  363. for(int i = 0;i<IS.rows();i++)
  364. {
  365. for(int d = 0;d<dim;d++)
  366. {
  367. SI(IS(i,d),d) = i;
  368. }
  369. }
  370. }
  371. init(V,Ele,SI,allI);
  372. }
  373. }
  374. template <typename DerivedV, int DIM>
  375. inline void igl::AABB<DerivedV,DIM>::init(
  376. const Eigen::PlainObjectBase<DerivedV> & V,
  377. const Eigen::MatrixXi & Ele)
  378. {
  379. using namespace Eigen;
  380. return init(V,Ele,MatrixXDIMS(),MatrixXDIMS(),VectorXi(),0);
  381. }
  382. template <typename DerivedV, int DIM>
  383. inline void igl::AABB<DerivedV,DIM>::init(
  384. const Eigen::PlainObjectBase<DerivedV> & V,
  385. const Eigen::MatrixXi & Ele,
  386. const Eigen::MatrixXi & SI,
  387. const Eigen::VectorXi & I)
  388. {
  389. using namespace Eigen;
  390. using namespace std;
  391. assert(DIM == V.cols() && "V.cols() should matched declared dimension");
  392. //const Scalar inf = numeric_limits<Scalar>::infinity();
  393. m_box = AlignedBox<Scalar,DIM>();
  394. // Compute bounding box
  395. for(int i = 0;i<I.rows();i++)
  396. {
  397. for(int c = 0;c<Ele.cols();c++)
  398. {
  399. m_box.extend(V.row(Ele(I(i),c)).transpose());
  400. m_box.extend(V.row(Ele(I(i),c)).transpose());
  401. }
  402. }
  403. switch(I.size())
  404. {
  405. case 0:
  406. {
  407. assert(false);
  408. }
  409. case 1:
  410. {
  411. m_primitive = I(0);
  412. break;
  413. }
  414. default:
  415. {
  416. // Compute longest direction
  417. int max_d = -1;
  418. m_box.diagonal().maxCoeff(&max_d);
  419. // Can't use median on BC directly because many may have same value,
  420. // but can use median on sorted BC indices
  421. VectorXi SIdI(I.rows());
  422. for(int i = 0;i<I.rows();i++)
  423. {
  424. SIdI(i) = SI(I(i),max_d);
  425. }
  426. // Since later I use <= I think I don't need to worry about odd/even
  427. // Pass by copy to avoid changing input
  428. const auto median = [](VectorXi A)->Scalar
  429. {
  430. size_t n = A.size()/2;
  431. nth_element(A.data(),A.data()+n,A.data()+A.size());
  432. if(A.rows() % 2 == 1)
  433. {
  434. return A(n);
  435. }else
  436. {
  437. nth_element(A.data(),A.data()+n-1,A.data()+A.size());
  438. return 0.5*(A(n)+A(n-1));
  439. }
  440. };
  441. const Scalar med = median(SIdI);
  442. VectorXi LI((I.rows()+1)/2),RI(I.rows()/2);
  443. assert(LI.rows()+RI.rows() == I.rows());
  444. // Distribute left and right
  445. {
  446. int li = 0;
  447. int ri = 0;
  448. for(int i = 0;i<I.rows();i++)
  449. {
  450. if(SIdI(i)<=med)
  451. {
  452. LI(li++) = I(i);
  453. }else
  454. {
  455. RI(ri++) = I(i);
  456. }
  457. }
  458. }
  459. //m_depth = 0;
  460. if(LI.rows()>0)
  461. {
  462. m_left = new AABB();
  463. m_left->init(V,Ele,SI,LI);
  464. //m_depth = std::max(m_depth, m_left->m_depth+1);
  465. }
  466. if(RI.rows()>0)
  467. {
  468. m_right = new AABB();
  469. m_right->init(V,Ele,SI,RI);
  470. //m_depth = std::max(m_depth, m_right->m_depth+1);
  471. }
  472. }
  473. }
  474. }
  475. template <typename DerivedV, int DIM>
  476. inline bool igl::AABB<DerivedV,DIM>::is_leaf() const
  477. {
  478. return m_primitive != -1;
  479. }
  480. template <typename DerivedV, int DIM>
  481. template <typename Derivedq>
  482. inline std::vector<int> igl::AABB<DerivedV,DIM>::find(
  483. const Eigen::PlainObjectBase<DerivedV> & V,
  484. const Eigen::MatrixXi & Ele,
  485. const Eigen::PlainObjectBase<Derivedq> & q,
  486. const bool first) const
  487. {
  488. using namespace std;
  489. using namespace Eigen;
  490. assert(q.size() == DIM &&
  491. "Query dimension should match aabb dimension");
  492. assert(Ele.cols() == V.cols()+1 &&
  493. "AABB::find only makes sense for (d+1)-simplices");
  494. const Scalar epsilon = igl::EPS<Scalar>();
  495. // Check if outside bounding box
  496. bool inside = m_box.contains(q.transpose());
  497. if(!inside)
  498. {
  499. return std::vector<int>();
  500. }
  501. assert(m_primitive==-1 || (m_left == NULL && m_right == NULL));
  502. if(is_leaf())
  503. {
  504. // Initialize to some value > -epsilon
  505. Scalar a1=0,a2=0,a3=0,a4=0;
  506. switch(DIM)
  507. {
  508. case 3:
  509. {
  510. // Barycentric coordinates
  511. typedef Eigen::Matrix<Scalar,1,3> RowVector3S;
  512. const RowVector3S V1 = V.row(Ele(m_primitive,0));
  513. const RowVector3S V2 = V.row(Ele(m_primitive,1));
  514. const RowVector3S V3 = V.row(Ele(m_primitive,2));
  515. const RowVector3S V4 = V.row(Ele(m_primitive,3));
  516. a1 = volume_single(V2,V4,V3,(RowVector3S)q);
  517. a2 = volume_single(V1,V3,V4,(RowVector3S)q);
  518. a3 = volume_single(V1,V4,V2,(RowVector3S)q);
  519. a4 = volume_single(V1,V2,V3,(RowVector3S)q);
  520. break;
  521. }
  522. case 2:
  523. {
  524. // Barycentric coordinates
  525. typedef Eigen::Matrix<Scalar,2,1> Vector2S;
  526. const Vector2S V1 = V.row(Ele(m_primitive,0));
  527. const Vector2S V2 = V.row(Ele(m_primitive,1));
  528. const Vector2S V3 = V.row(Ele(m_primitive,2));
  529. // Hack for now to keep templates simple. If becomes bottleneck
  530. // consider using std::enable_if_t
  531. const Vector2S q2 = q.head(2);
  532. a1 = doublearea_single(V1,V2,q2);
  533. a2 = doublearea_single(V2,V3,q2);
  534. a3 = doublearea_single(V3,V1,q2);
  535. break;
  536. }
  537. default:assert(false);
  538. }
  539. // Normalization is important for correcting sign
  540. Scalar sum = a1+a2+a3+a4;
  541. a1 /= sum;
  542. a2 /= sum;
  543. a3 /= sum;
  544. a4 /= sum;
  545. if(
  546. a1>=-epsilon &&
  547. a2>=-epsilon &&
  548. a3>=-epsilon &&
  549. a4>=-epsilon)
  550. {
  551. return std::vector<int>(1,m_primitive);
  552. }else
  553. {
  554. return std::vector<int>();
  555. }
  556. }
  557. std::vector<int> left = m_left->find(V,Ele,q,first);
  558. if(first && !left.empty())
  559. {
  560. return left;
  561. }
  562. std::vector<int> right = m_right->find(V,Ele,q,first);
  563. if(first)
  564. {
  565. return right;
  566. }
  567. left.insert(left.end(),right.begin(),right.end());
  568. return left;
  569. }
  570. template <typename DerivedV, int DIM>
  571. inline int igl::AABB<DerivedV,DIM>::subtree_size() const
  572. {
  573. // 1 for self
  574. int n = 1;
  575. int n_left = 0,n_right = 0;
  576. if(m_left != NULL)
  577. {
  578. n_left = m_left->subtree_size();
  579. }
  580. if(m_right != NULL)
  581. {
  582. n_right = m_right->subtree_size();
  583. }
  584. n += 2*std::max(n_left,n_right);
  585. return n;
  586. }
  587. template <typename DerivedV, int DIM>
  588. template <typename Derivedbb_mins, typename Derivedbb_maxs>
  589. inline void igl::AABB<DerivedV,DIM>::serialize(
  590. Eigen::PlainObjectBase<Derivedbb_mins> & bb_mins,
  591. Eigen::PlainObjectBase<Derivedbb_maxs> & bb_maxs,
  592. Eigen::VectorXi & elements,
  593. const int i) const
  594. {
  595. using namespace std;
  596. using namespace Eigen;
  597. // Calling for root then resize output
  598. if(i==0)
  599. {
  600. const int m = subtree_size();
  601. //cout<<"m: "<<m<<endl;
  602. bb_mins.resize(m,DIM);
  603. bb_maxs.resize(m,DIM);
  604. elements.resize(m,1);
  605. }
  606. //cout<<i<<" ";
  607. bb_mins.row(i) = m_box.min();
  608. bb_maxs.row(i) = m_box.max();
  609. elements(i) = m_primitive;
  610. if(m_left != NULL)
  611. {
  612. m_left->serialize(bb_mins,bb_maxs,elements,2*i+1);
  613. }
  614. if(m_right != NULL)
  615. {
  616. m_right->serialize(bb_mins,bb_maxs,elements,2*i+2);
  617. }
  618. }
  619. template <typename DerivedV, int DIM>
  620. inline typename igl::AABB<DerivedV,DIM>::Scalar
  621. igl::AABB<DerivedV,DIM>::squared_distance(
  622. const Eigen::PlainObjectBase<DerivedV> & V,
  623. const Eigen::MatrixXi & Ele,
  624. const RowVectorDIMS & p,
  625. int & i,
  626. RowVectorDIMS & c) const
  627. {
  628. return squared_distance(V,Ele,p,std::numeric_limits<Scalar>::infinity(),i,c);
  629. }
  630. template <typename DerivedV, int DIM>
  631. inline typename igl::AABB<DerivedV,DIM>::Scalar
  632. igl::AABB<DerivedV,DIM>::squared_distance(
  633. const Eigen::PlainObjectBase<DerivedV> & V,
  634. const Eigen::MatrixXi & Ele,
  635. const RowVectorDIMS & p,
  636. Scalar min_sqr_d,
  637. int & i,
  638. RowVectorDIMS & c) const
  639. {
  640. using namespace Eigen;
  641. using namespace std;
  642. Scalar sqr_d = min_sqr_d;
  643. //assert(DIM == 3 && "Code has only been tested for DIM == 3");
  644. assert((Ele.cols() == 3 || Ele.cols() == 2 || Ele.cols() == 1)
  645. && "Code has only been tested for simplex sizes 3,2,1");
  646. assert(m_primitive==-1 || (m_left == NULL && m_right == NULL));
  647. if(is_leaf())
  648. {
  649. leaf_squared_distance(V,Ele,p,sqr_d,i,c);
  650. }else
  651. {
  652. bool looked_left = false;
  653. bool looked_right = false;
  654. const auto & look_left = [&]()
  655. {
  656. int i_left;
  657. RowVectorDIMS c_left = c;
  658. Scalar sqr_d_left = m_left->squared_distance(V,Ele,p,sqr_d,i_left,c_left);
  659. set_min(p,sqr_d_left,i_left,c_left,sqr_d,i,c);
  660. looked_left = true;
  661. };
  662. const auto & look_right = [&]()
  663. {
  664. int i_right;
  665. RowVectorDIMS c_right = c;
  666. Scalar sqr_d_right = m_right->squared_distance(V,Ele,p,sqr_d,i_right,c_right);
  667. set_min(p,sqr_d_right,i_right,c_right,sqr_d,i,c);
  668. looked_right = true;
  669. };
  670. // must look left or right if in box
  671. if(m_left->m_box.contains(p.transpose()))
  672. {
  673. look_left();
  674. }
  675. if(m_right->m_box.contains(p.transpose()))
  676. {
  677. look_right();
  678. }
  679. // if haven't looked left and could be less than current min, then look
  680. Scalar left_min_sqr_d = m_left->m_box.squaredExteriorDistance(p.transpose());
  681. Scalar right_min_sqr_d = m_right->m_box.squaredExteriorDistance(p.transpose());
  682. if(left_min_sqr_d < right_min_sqr_d)
  683. {
  684. if(!looked_left && left_min_sqr_d<sqr_d)
  685. {
  686. look_left();
  687. }
  688. if( !looked_right && right_min_sqr_d<sqr_d)
  689. {
  690. look_right();
  691. }
  692. }else
  693. {
  694. if( !looked_right && right_min_sqr_d<sqr_d)
  695. {
  696. look_right();
  697. }
  698. if(!looked_left && left_min_sqr_d<sqr_d)
  699. {
  700. look_left();
  701. }
  702. }
  703. }
  704. return sqr_d;
  705. }
  706. template <typename DerivedV, int DIM>
  707. template <
  708. typename DerivedP,
  709. typename DerivedsqrD,
  710. typename DerivedI,
  711. typename DerivedC>
  712. inline void igl::AABB<DerivedV,DIM>::squared_distance(
  713. const Eigen::PlainObjectBase<DerivedV> & V,
  714. const Eigen::MatrixXi & Ele,
  715. const Eigen::PlainObjectBase<DerivedP> & P,
  716. Eigen::PlainObjectBase<DerivedsqrD> & sqrD,
  717. Eigen::PlainObjectBase<DerivedI> & I,
  718. Eigen::PlainObjectBase<DerivedC> & C) const
  719. {
  720. assert(P.cols() == V.cols() && "cols in P should match dim of cols in V");
  721. sqrD.resize(P.rows(),1);
  722. I.resize(P.rows(),1);
  723. C.resize(P.rows(),P.cols());
  724. for(int p = 0;p<P.rows();p++)
  725. {
  726. RowVectorDIMS Pp = P.row(p), c;
  727. int Ip;
  728. sqrD(p) = squared_distance(V,Ele,Pp,Ip,c);
  729. I(p) = Ip;
  730. C.row(p).head(DIM) = c;
  731. }
  732. }
  733. template <typename DerivedV, int DIM>
  734. template <
  735. typename Derivedother_V,
  736. typename DerivedsqrD,
  737. typename DerivedI,
  738. typename DerivedC>
  739. inline void igl::AABB<DerivedV,DIM>::squared_distance(
  740. const Eigen::PlainObjectBase<DerivedV> & V,
  741. const Eigen::MatrixXi & Ele,
  742. const AABB<Derivedother_V,DIM> & other,
  743. const Eigen::PlainObjectBase<Derivedother_V> & other_V,
  744. const Eigen::MatrixXi & other_Ele,
  745. Eigen::PlainObjectBase<DerivedsqrD> & sqrD,
  746. Eigen::PlainObjectBase<DerivedI> & I,
  747. Eigen::PlainObjectBase<DerivedC> & C) const
  748. {
  749. assert(other_Ele.cols() == 1 &&
  750. "Only implemented for other as list of points");
  751. assert(other_V.cols() == V.cols() && "other must match this dimension");
  752. sqrD.setConstant(other_Ele.rows(),1,std::numeric_limits<double>::infinity());
  753. I.resize(other_Ele.rows(),1);
  754. C.resize(other_Ele.rows(),other_V.cols());
  755. // All points in other_V currently think they need to check against root of
  756. // this. The point of using another AABB is to quickly prune chunks of
  757. // other_V so that most points just check some subtree of this.
  758. // This holds a conservative estimate of max(sqr_D) where sqr_D is the
  759. // current best minimum squared distance for all points in this subtree
  760. double min_sqr_d = std::numeric_limits<double>::infinity();
  761. squared_distance_helper(
  762. V,Ele,&other,other_V,other_Ele,min_sqr_d,sqrD,I,C);
  763. }
  764. template <typename DerivedV, int DIM>
  765. template <
  766. typename Derivedother_V,
  767. typename DerivedsqrD,
  768. typename DerivedI,
  769. typename DerivedC>
  770. inline typename igl::AABB<DerivedV,DIM>::Scalar igl::AABB<DerivedV,DIM>::squared_distance_helper(
  771. const Eigen::PlainObjectBase<DerivedV> & V,
  772. const Eigen::MatrixXi & Ele,
  773. const AABB<Derivedother_V,DIM> * other,
  774. const Eigen::PlainObjectBase<Derivedother_V> & other_V,
  775. const Eigen::MatrixXi & other_Ele,
  776. const Scalar /*min_sqr_d*/,
  777. Eigen::PlainObjectBase<DerivedsqrD> & sqrD,
  778. Eigen::PlainObjectBase<DerivedI> & I,
  779. Eigen::PlainObjectBase<DerivedC> & C) const
  780. {
  781. using namespace std;
  782. using namespace Eigen;
  783. // This implementation is a bit disappointing. There's no major speed up. Any
  784. // performance gains seem to come from accidental cache coherency and
  785. // diminish for larger "other" (the opposite of what was intended).
  786. // Base case
  787. if(other->is_leaf() && this->is_leaf())
  788. {
  789. Scalar sqr_d = sqrD(other->m_primitive);
  790. int i = I(other->m_primitive);
  791. RowVectorDIMS c = C.row( other->m_primitive);
  792. RowVectorDIMS p = other_V.row(other->m_primitive);
  793. leaf_squared_distance(V,Ele,p,sqr_d,i,c);
  794. sqrD( other->m_primitive) = sqr_d;
  795. I( other->m_primitive) = i;
  796. C.row(other->m_primitive) = c;
  797. //cout<<"leaf: "<<sqr_d<<endl;
  798. //other->m_max_sqr_d = sqr_d;
  799. return sqr_d;
  800. }
  801. if(other->is_leaf())
  802. {
  803. Scalar sqr_d = sqrD(other->m_primitive);
  804. int i = I(other->m_primitive);
  805. RowVectorDIMS c = C.row( other->m_primitive);
  806. RowVectorDIMS p = other_V.row(other->m_primitive);
  807. sqr_d = squared_distance(V,Ele,p,sqr_d,i,c);
  808. sqrD( other->m_primitive) = sqr_d;
  809. I( other->m_primitive) = i;
  810. C.row(other->m_primitive) = c;
  811. //other->m_max_sqr_d = sqr_d;
  812. return sqr_d;
  813. }
  814. //// Exact minimum squared distance between arbitary primitives inside this and
  815. //// othre's bounding boxes
  816. //const auto & min_squared_distance = [&](
  817. // const AABB<DerivedV,DIM> * A,
  818. // const AABB<Derivedother_V,DIM> * B)->Scalar
  819. //{
  820. // return A->m_box.squaredExteriorDistance(B->m_box);
  821. //};
  822. if(this->is_leaf())
  823. {
  824. //if(min_squared_distance(this,other) < other->m_max_sqr_d)
  825. if(true)
  826. {
  827. this->squared_distance_helper(
  828. V,Ele,other->m_left,other_V,other_Ele,0,sqrD,I,C);
  829. this->squared_distance_helper(
  830. V,Ele,other->m_right,other_V,other_Ele,0,sqrD,I,C);
  831. }else
  832. {
  833. // This is never reached...
  834. }
  835. //// we know other is not a leaf
  836. //other->m_max_sqr_d = std::max(other->m_left->m_max_sqr_d,other->m_right->m_max_sqr_d);
  837. return 0;
  838. }
  839. // FORCE DOWN TO OTHER LEAF EVAL
  840. //if(min_squared_distance(this,other) < other->m_max_sqr_d)
  841. if(true)
  842. {
  843. if(true)
  844. {
  845. this->squared_distance_helper(
  846. V,Ele,other->m_left,other_V,other_Ele,0,sqrD,I,C);
  847. this->squared_distance_helper(
  848. V,Ele,other->m_right,other_V,other_Ele,0,sqrD,I,C);
  849. }else // this direction never seems to be faster
  850. {
  851. this->m_left->squared_distance_helper(
  852. V,Ele,other,other_V,other_Ele,0,sqrD,I,C);
  853. this->m_right->squared_distance_helper(
  854. V,Ele,other,other_V,other_Ele,0,sqrD,I,C);
  855. }
  856. }else
  857. {
  858. // this is never reached ... :-(
  859. }
  860. //// we know other is not a leaf
  861. //other->m_max_sqr_d = std::max(other->m_left->m_max_sqr_d,other->m_right->m_max_sqr_d);
  862. return 0;
  863. #if 0 // False
  864. // _Very_ conservative approximation of maximum squared distance between
  865. // primitives inside this and other's bounding boxes
  866. const auto & max_squared_distance = [](
  867. const AABB<DerivedV,DIM> * A,
  868. const AABB<Derivedother_V,DIM> * B)->Scalar
  869. {
  870. AlignedBox<Scalar,DIM> combo = A->m_box;
  871. combo.extend(B->m_box);
  872. return combo.diagonal().squaredNorm();
  873. };
  874. //// other base-case
  875. //if(other->is_leaf())
  876. //{
  877. // double sqr_d = sqrD(other->m_primitive);
  878. // int i = I(other->m_primitive);
  879. // RowVectorDIMS c = C.row(m_primitive);
  880. // RowVectorDIMS p = other_V.row(m_primitive);
  881. // leaf_squared_distance(V,Ele,p,sqr_d,i,c);
  882. // sqrD(other->m_primitive) = sqr_d;
  883. // I(other->m_primitive) = i;
  884. // C.row(m_primitive) = c;
  885. // return;
  886. //}
  887. std::vector<const AABB<DerivedV,DIM> * > this_list;
  888. if(this->is_leaf())
  889. {
  890. this_list.push_back(this);
  891. }else
  892. {
  893. assert(this->m_left);
  894. this_list.push_back(this->m_left);
  895. assert(this->m_right);
  896. this_list.push_back(this->m_right);
  897. }
  898. std::vector<AABB<Derivedother_V,DIM> *> other_list;
  899. if(other->is_leaf())
  900. {
  901. other_list.push_back(other);
  902. }else
  903. {
  904. assert(other->m_left);
  905. other_list.push_back(other->m_left);
  906. assert(other->m_right);
  907. other_list.push_back(other->m_right);
  908. }
  909. //const std::function<Scalar(
  910. // const AABB<Derivedother_V,DIM> * other)
  911. // > max_sqr_d = [&sqrD,&max_sqr_d](const AABB<Derivedother_V,DIM> * other)->Scalar
  912. // {
  913. // if(other->is_leaf())
  914. // {
  915. // return sqrD(other->m_primitive);
  916. // }else
  917. // {
  918. // return std::max(max_sqr_d(other->m_left),max_sqr_d(other->m_right));
  919. // }
  920. // };
  921. //// Potentially recurse on all pairs, if minimum distance is less than running
  922. //// bound
  923. //Eigen::Matrix<Scalar,Eigen::Dynamic,1> other_max_sqr_d =
  924. // Eigen::Matrix<Scalar,Eigen::Dynamic,1>::Constant(other_list.size(),1,min_sqr_d);
  925. for(size_t child = 0;child<other_list.size();child++)
  926. {
  927. auto other_tree = other_list[child];
  928. Eigen::Matrix<Scalar,Eigen::Dynamic,1> this_max_sqr_d(this_list.size(),1);
  929. for(size_t t = 0;t<this_list.size();t++)
  930. {
  931. const auto this_tree = this_list[t];
  932. this_max_sqr_d(t) = max_squared_distance(this_tree,other_tree);
  933. }
  934. if(this_list.size() ==2 &&
  935. ( this_max_sqr_d(0) > this_max_sqr_d(1))
  936. )
  937. {
  938. std::swap(this_list[0],this_list[1]);
  939. //std::swap(this_max_sqr_d(0),this_max_sqr_d(1));
  940. }
  941. const Scalar sqr_d = this_max_sqr_d.minCoeff();
  942. for(size_t t = 0;t<this_list.size();t++)
  943. {
  944. const auto this_tree = this_list[t];
  945. //const auto mm = max_sqr_d(other_tree);
  946. //const Scalar mc = other_max_sqr_d(child);
  947. //assert(mc == mm);
  948. // Only look left/right in this_list if can possible decrease somebody's
  949. // distance in this_tree.
  950. const Scalar min_this_other = min_squared_distance(this_tree,other_tree);
  951. if(
  952. min_this_other < sqr_d &&
  953. min_this_other < other_tree->m_max_sqr_d)
  954. {
  955. //cout<<"before: "<<other_max_sqr_d(child)<<endl;
  956. //other_max_sqr_d(child) = std::min(
  957. // other_max_sqr_d(child),
  958. // this_tree->squared_distance_helper(
  959. // V,Ele,other_tree,other_V,other_Ele,other_max_sqr_d(child),sqrD,I,C));
  960. //cout<<"after: "<<other_max_sqr_d(child)<<endl;
  961. this_tree->squared_distance_helper(
  962. V,Ele,other_tree,other_V,other_Ele,0,sqrD,I,C);
  963. }
  964. }
  965. }
  966. //const Scalar ret = other_max_sqr_d.maxCoeff();
  967. //const auto mm = max_sqr_d(other);
  968. //assert(mm == ret);
  969. //cout<<"non-leaf: "<<ret<<endl;
  970. //return ret;
  971. if(!other->is_leaf())
  972. {
  973. other->m_max_sqr_d = std::max(other->m_left->m_max_sqr_d,other->m_right->m_max_sqr_d);
  974. }
  975. return 0;
  976. #endif
  977. }
  978. template <typename DerivedV, int DIM>
  979. inline void igl::AABB<DerivedV,DIM>::leaf_squared_distance(
  980. const Eigen::PlainObjectBase<DerivedV> & V,
  981. const Eigen::MatrixXi & Ele,
  982. const RowVectorDIMS & p,
  983. Scalar & sqr_d,
  984. int & i,
  985. RowVectorDIMS & c) const
  986. {
  987. using namespace Eigen;
  988. using namespace std;
  989. // Simplex size
  990. const size_t ss = Ele.cols();
  991. // Only one element per node
  992. // plane unit normal
  993. bool inside_triangle = false;
  994. Scalar d_j = std::numeric_limits<Scalar>::infinity();
  995. RowVectorDIMS pp;
  996. // Only consider triangles, and non-degenerate triangles at that
  997. if(ss == 3 &&
  998. Ele(m_primitive,0) != Ele(m_primitive,1) &&
  999. Ele(m_primitive,1) != Ele(m_primitive,2) &&
  1000. Ele(m_primitive,2) != Ele(m_primitive,0))
  1001. {
  1002. assert(DIM == 3 && "Only implemented for 3D triangles");
  1003. typedef Eigen::Matrix<Scalar,1,3> RowVector3S;
  1004. // can't be const because of annoying DIM template
  1005. RowVector3S v10(0,0,0);
  1006. v10.head(DIM) = (V.row(Ele(m_primitive,1))- V.row(Ele(m_primitive,0)));
  1007. RowVector3S v20(0,0,0);
  1008. v20.head(DIM) = (V.row(Ele(m_primitive,2))- V.row(Ele(m_primitive,0)));
  1009. const RowVectorDIMS n = (v10.cross(v20)).head(DIM);
  1010. Scalar n_norm = n.norm();
  1011. if(n_norm > 0)
  1012. {
  1013. const RowVectorDIMS un = n/n.norm();
  1014. // vector to plane
  1015. const RowVectorDIMS bc =
  1016. 1./3.*
  1017. ( V.row(Ele(m_primitive,0))+
  1018. V.row(Ele(m_primitive,1))+
  1019. V.row(Ele(m_primitive,2)));
  1020. const auto & v = p-bc;
  1021. // projected point on plane
  1022. d_j = v.dot(un);
  1023. pp = p - d_j*un;
  1024. // determine if pp is inside triangle
  1025. Eigen::Matrix<Scalar,1,3> b;
  1026. barycentric_coordinates(
  1027. pp,
  1028. V.row(Ele(m_primitive,0)),
  1029. V.row(Ele(m_primitive,1)),
  1030. V.row(Ele(m_primitive,2)),
  1031. b);
  1032. inside_triangle = fabs(fabs(b(0)) + fabs(b(1)) + fabs(b(2)) - 1.) <= 1e-10;
  1033. }
  1034. }
  1035. const auto & point_point_squared_distance = [&](const RowVectorDIMS & s)
  1036. {
  1037. const Scalar sqr_d_s = (p-s).squaredNorm();
  1038. set_min(p,sqr_d_s,m_primitive,s,sqr_d,i,c);
  1039. };
  1040. if(inside_triangle)
  1041. {
  1042. // point-triangle squared distance
  1043. const Scalar sqr_d_j = d_j*d_j;
  1044. //cout<<"point-triangle..."<<endl;
  1045. set_min(p,sqr_d_j,m_primitive,pp,sqr_d,i,c);
  1046. }else
  1047. {
  1048. if(ss >= 2)
  1049. {
  1050. // point-segment distance
  1051. // number of edges
  1052. size_t ne = ss==3?3:1;
  1053. for(size_t x = 0;x<ne;x++)
  1054. {
  1055. const size_t e1 = Ele(m_primitive,(x+1)%ss);
  1056. const size_t e2 = Ele(m_primitive,(x+2)%ss);
  1057. const RowVectorDIMS & s = V.row(e1);
  1058. const RowVectorDIMS & d = V.row(e2);
  1059. // Degenerate edge
  1060. if(e1 == e2 || (s-d).squaredNorm()==0)
  1061. {
  1062. // only consider once
  1063. if(e1 < e2)
  1064. {
  1065. point_point_squared_distance(s);
  1066. }
  1067. continue;
  1068. }
  1069. Matrix<Scalar,1,1> sqr_d_j_x(1,1);
  1070. Matrix<Scalar,1,1> t(1,1);
  1071. project_to_line_segment(p,s,d,t,sqr_d_j_x);
  1072. const RowVectorDIMS q = s+t(0)*(d-s);
  1073. set_min(p,sqr_d_j_x(0),m_primitive,q,sqr_d,i,c);
  1074. }
  1075. }else
  1076. {
  1077. // So then Ele is just a list of points...
  1078. assert(ss == 1);
  1079. const RowVectorDIMS & s = V.row(Ele(m_primitive,0));
  1080. point_point_squared_distance(s);
  1081. }
  1082. }
  1083. }
  1084. template <typename DerivedV, int DIM>
  1085. inline void igl::AABB<DerivedV,DIM>::set_min(
  1086. const RowVectorDIMS &
  1087. #ifndef NDEBUG
  1088. p
  1089. #endif
  1090. ,
  1091. const Scalar sqr_d_candidate,
  1092. const int i_candidate,
  1093. const RowVectorDIMS & c_candidate,
  1094. Scalar & sqr_d,
  1095. int & i,
  1096. RowVectorDIMS & c) const
  1097. {
  1098. #ifndef NDEBUG
  1099. //std::cout<<matlab_format(c_candidate,"c_candidate")<<std::endl;
  1100. const Scalar pc_norm = (p-c_candidate).squaredNorm();
  1101. const Scalar diff = fabs(sqr_d_candidate - pc_norm);
  1102. assert(diff<=1e-10 && "distance should match norm of difference");
  1103. #endif
  1104. if(sqr_d_candidate < sqr_d)
  1105. {
  1106. i = i_candidate;
  1107. c = c_candidate;
  1108. sqr_d = sqr_d_candidate;
  1109. }
  1110. }
  1111. template <typename DerivedV, int DIM>
  1112. inline void
  1113. igl::AABB<DerivedV,DIM>::barycentric_coordinates(
  1114. const RowVectorDIMS & p,
  1115. const RowVectorDIMS & a,
  1116. const RowVectorDIMS & b,
  1117. const RowVectorDIMS & c,
  1118. Eigen::Matrix<Scalar,1,3> & bary)
  1119. {
  1120. // http://gamedev.stackexchange.com/a/23745
  1121. const RowVectorDIMS v0 = b - a;
  1122. const RowVectorDIMS v1 = c - a;
  1123. const RowVectorDIMS v2 = p - a;
  1124. Scalar d00 = v0.dot(v0);
  1125. Scalar d01 = v0.dot(v1);
  1126. Scalar d11 = v1.dot(v1);
  1127. Scalar d20 = v2.dot(v0);
  1128. Scalar d21 = v2.dot(v1);
  1129. Scalar denom = d00 * d11 - d01 * d01;
  1130. bary(1) = (d11 * d20 - d01 * d21) / denom;
  1131. bary(2) = (d00 * d21 - d01 * d20) / denom;
  1132. bary(0) = 1.0f - bary(1) - bary(2);
  1133. }
  1134. template <typename DerivedV, int DIM>
  1135. inline bool
  1136. igl::AABB<DerivedV,DIM>::intersect_ray(
  1137. const Eigen::PlainObjectBase<DerivedV> & V,
  1138. const Eigen::MatrixXi & Ele,
  1139. const RowVectorDIMS & origin,
  1140. const RowVectorDIMS & dir,
  1141. std::vector<igl::Hit> & hits) const
  1142. {
  1143. hits.clear();
  1144. const Scalar t0 = 0;
  1145. const Scalar t1 = std::numeric_limits<Scalar>::infinity();
  1146. {
  1147. Scalar _1,_2;
  1148. if(!ray_box_intersect(origin,dir,m_box,t0,t1,_1,_2))
  1149. {
  1150. return false;
  1151. }
  1152. }
  1153. if(this->is_leaf())
  1154. {
  1155. // Actually process elements
  1156. assert((Ele.size() == 0 || Ele.cols() == 3) && "Elements should be triangles");
  1157. // Cheesecake way of hitting element
  1158. return ray_mesh_intersect(origin,dir,V,Ele.row(m_primitive).eval(),hits);
  1159. }
  1160. std::vector<igl::Hit> left_hits;
  1161. std::vector<igl::Hit> right_hits;
  1162. const bool left_ret = m_left->intersect_ray(V,Ele,origin,dir,left_hits);
  1163. const bool right_ret = m_right->intersect_ray(V,Ele,origin,dir,right_hits);
  1164. hits.insert(hits.end(),left_hits.begin(),left_hits.end());
  1165. hits.insert(hits.end(),right_hits.begin(),right_hits.end());
  1166. return left_ret || right_ret;
  1167. }
  1168. template <typename DerivedV, int DIM>
  1169. inline bool
  1170. igl::AABB<DerivedV,DIM>::intersect_ray(
  1171. const Eigen::PlainObjectBase<DerivedV> & V,
  1172. const Eigen::MatrixXi & Ele,
  1173. const RowVectorDIMS & origin,
  1174. const RowVectorDIMS & dir,
  1175. igl::Hit & hit) const
  1176. {
  1177. #if false
  1178. // BFS
  1179. std::queue<const AABB *> Q;
  1180. // Or DFS
  1181. //std::stack<const AABB *> Q;
  1182. Q.push(this);
  1183. bool any_hit = false;
  1184. hit.t = std::numeric_limits<Scalar>::infinity();
  1185. while(!Q.empty())
  1186. {
  1187. const AABB * tree = Q.front();
  1188. //const AABB * tree = Q.top();
  1189. Q.pop();
  1190. {
  1191. Scalar _1,_2;
  1192. if(!ray_box_intersect(
  1193. origin,dir,tree->m_box,Scalar(0),Scalar(hit.t),_1,_2))
  1194. {
  1195. continue;
  1196. }
  1197. }
  1198. if(tree->is_leaf())
  1199. {
  1200. // Actually process elements
  1201. assert((Ele.size() == 0 || Ele.cols() == 3) && "Elements should be triangles");
  1202. igl::Hit leaf_hit;
  1203. if(
  1204. ray_mesh_intersect(origin,dir,V,Ele.row(tree->m_primitive).eval(),leaf_hit)&&
  1205. leaf_hit.t < hit.t)
  1206. {
  1207. hit = leaf_hit;
  1208. }
  1209. continue;
  1210. }
  1211. // Add children to queue
  1212. Q.push(tree->m_left);
  1213. Q.push(tree->m_right);
  1214. }
  1215. return any_hit;
  1216. #else
  1217. // DFS
  1218. return intersect_ray(
  1219. V,Ele,origin,dir,std::numeric_limits<Scalar>::infinity(),hit);
  1220. #endif
  1221. }
  1222. template <typename DerivedV, int DIM>
  1223. inline bool
  1224. igl::AABB<DerivedV,DIM>::intersect_ray(
  1225. const Eigen::PlainObjectBase<DerivedV> & V,
  1226. const Eigen::MatrixXi & Ele,
  1227. const RowVectorDIMS & origin,
  1228. const RowVectorDIMS & dir,
  1229. const Scalar _min_t,
  1230. igl::Hit & hit) const
  1231. {
  1232. //// Naive, slow
  1233. //std::vector<igl::Hit> hits;
  1234. //intersect_ray(V,Ele,origin,dir,hits);
  1235. //if(hits.size() > 0)
  1236. //{
  1237. // hit = hits.front();
  1238. // return true;
  1239. //}else
  1240. //{
  1241. // return false;
  1242. //}
  1243. Scalar min_t = _min_t;
  1244. const Scalar t0 = 0;
  1245. {
  1246. Scalar _1,_2;
  1247. if(!ray_box_intersect(origin,dir,m_box,t0,min_t,_1,_2))
  1248. {
  1249. return false;
  1250. }
  1251. }
  1252. if(this->is_leaf())
  1253. {
  1254. // Actually process elements
  1255. assert((Ele.size() == 0 || Ele.cols() == 3) && "Elements should be triangles");
  1256. // Cheesecake way of hitting element
  1257. return ray_mesh_intersect(origin,dir,V,Ele.row(m_primitive).eval(),hit);
  1258. }
  1259. // Doesn't seem like smartly choosing left before/after right makes a
  1260. // differnce
  1261. igl::Hit left_hit;
  1262. igl::Hit right_hit;
  1263. bool left_ret = m_left->intersect_ray(V,Ele,origin,dir,min_t,left_hit);
  1264. if(left_ret && left_hit.t<min_t)
  1265. {
  1266. // It's scary that this line doesn't seem to matter....
  1267. min_t = left_hit.t;
  1268. hit = left_hit;
  1269. left_ret = true;
  1270. }else
  1271. {
  1272. left_ret = false;
  1273. }
  1274. bool right_ret = m_right->intersect_ray(V,Ele,origin,dir,min_t,right_hit);
  1275. if(right_ret && right_hit.t<min_t)
  1276. {
  1277. min_t = right_hit.t;
  1278. hit = right_hit;
  1279. right_ret = true;
  1280. }else
  1281. {
  1282. right_ret = false;
  1283. }
  1284. return left_ret || right_ret;
  1285. }
  1286. #endif