AABB.h 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338
  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. using namespace igl;
  643. Scalar sqr_d = min_sqr_d;
  644. //assert(DIM == 3 && "Code has only been tested for DIM == 3");
  645. assert((Ele.cols() == 3 || Ele.cols() == 2 || Ele.cols() == 1)
  646. && "Code has only been tested for simplex sizes 3,2,1");
  647. assert(m_primitive==-1 || (m_left == NULL && m_right == NULL));
  648. if(is_leaf())
  649. {
  650. leaf_squared_distance(V,Ele,p,sqr_d,i,c);
  651. }else
  652. {
  653. bool looked_left = false;
  654. bool looked_right = false;
  655. const auto & look_left = [&]()
  656. {
  657. int i_left;
  658. RowVectorDIMS c_left = c;
  659. Scalar sqr_d_left = m_left->squared_distance(V,Ele,p,sqr_d,i_left,c_left);
  660. set_min(p,sqr_d_left,i_left,c_left,sqr_d,i,c);
  661. looked_left = true;
  662. };
  663. const auto & look_right = [&]()
  664. {
  665. int i_right;
  666. RowVectorDIMS c_right = c;
  667. Scalar sqr_d_right = m_right->squared_distance(V,Ele,p,sqr_d,i_right,c_right);
  668. set_min(p,sqr_d_right,i_right,c_right,sqr_d,i,c);
  669. looked_right = true;
  670. };
  671. // must look left or right if in box
  672. if(m_left->m_box.contains(p.transpose()))
  673. {
  674. look_left();
  675. }
  676. if(m_right->m_box.contains(p.transpose()))
  677. {
  678. look_right();
  679. }
  680. // if haven't looked left and could be less than current min, then look
  681. Scalar left_min_sqr_d = m_left->m_box.squaredExteriorDistance(p.transpose());
  682. Scalar right_min_sqr_d = m_right->m_box.squaredExteriorDistance(p.transpose());
  683. if(left_min_sqr_d < right_min_sqr_d)
  684. {
  685. if(!looked_left && left_min_sqr_d<sqr_d)
  686. {
  687. look_left();
  688. }
  689. if( !looked_right && right_min_sqr_d<sqr_d)
  690. {
  691. look_right();
  692. }
  693. }else
  694. {
  695. if( !looked_right && right_min_sqr_d<sqr_d)
  696. {
  697. look_right();
  698. }
  699. if(!looked_left && left_min_sqr_d<sqr_d)
  700. {
  701. look_left();
  702. }
  703. }
  704. }
  705. return sqr_d;
  706. }
  707. template <typename DerivedV, int DIM>
  708. template <
  709. typename DerivedP,
  710. typename DerivedsqrD,
  711. typename DerivedI,
  712. typename DerivedC>
  713. inline void igl::AABB<DerivedV,DIM>::squared_distance(
  714. const Eigen::PlainObjectBase<DerivedV> & V,
  715. const Eigen::MatrixXi & Ele,
  716. const Eigen::PlainObjectBase<DerivedP> & P,
  717. Eigen::PlainObjectBase<DerivedsqrD> & sqrD,
  718. Eigen::PlainObjectBase<DerivedI> & I,
  719. Eigen::PlainObjectBase<DerivedC> & C) const
  720. {
  721. assert(P.cols() == V.cols() && "cols in P should match dim of cols in V");
  722. sqrD.resize(P.rows(),1);
  723. I.resize(P.rows(),1);
  724. C.resize(P.rows(),P.cols());
  725. for(int p = 0;p<P.rows();p++)
  726. {
  727. RowVectorDIMS Pp = P.row(p), c;
  728. int Ip;
  729. sqrD(p) = squared_distance(V,Ele,Pp,Ip,c);
  730. I(p) = Ip;
  731. C.row(p).head(DIM) = c;
  732. }
  733. }
  734. template <typename DerivedV, int DIM>
  735. template <
  736. typename Derivedother_V,
  737. typename DerivedsqrD,
  738. typename DerivedI,
  739. typename DerivedC>
  740. inline void igl::AABB<DerivedV,DIM>::squared_distance(
  741. const Eigen::PlainObjectBase<DerivedV> & V,
  742. const Eigen::MatrixXi & Ele,
  743. const AABB<Derivedother_V,DIM> & other,
  744. const Eigen::PlainObjectBase<Derivedother_V> & other_V,
  745. const Eigen::MatrixXi & other_Ele,
  746. Eigen::PlainObjectBase<DerivedsqrD> & sqrD,
  747. Eigen::PlainObjectBase<DerivedI> & I,
  748. Eigen::PlainObjectBase<DerivedC> & C) const
  749. {
  750. assert(other_Ele.cols() == 1 &&
  751. "Only implemented for other as list of points");
  752. assert(other_V.cols() == V.cols() && "other must match this dimension");
  753. sqrD.setConstant(other_Ele.rows(),1,std::numeric_limits<double>::infinity());
  754. I.resize(other_Ele.rows(),1);
  755. C.resize(other_Ele.rows(),other_V.cols());
  756. // All points in other_V currently think they need to check against root of
  757. // this. The point of using another AABB is to quickly prune chunks of
  758. // other_V so that most points just check some subtree of this.
  759. // This holds a conservative estimate of max(sqr_D) where sqr_D is the
  760. // current best minimum squared distance for all points in this subtree
  761. double min_sqr_d = std::numeric_limits<double>::infinity();
  762. squared_distance_helper(
  763. V,Ele,&other,other_V,other_Ele,min_sqr_d,sqrD,I,C);
  764. }
  765. template <typename DerivedV, int DIM>
  766. template <
  767. typename Derivedother_V,
  768. typename DerivedsqrD,
  769. typename DerivedI,
  770. typename DerivedC>
  771. inline typename igl::AABB<DerivedV,DIM>::Scalar igl::AABB<DerivedV,DIM>::squared_distance_helper(
  772. const Eigen::PlainObjectBase<DerivedV> & V,
  773. const Eigen::MatrixXi & Ele,
  774. const AABB<Derivedother_V,DIM> * other,
  775. const Eigen::PlainObjectBase<Derivedother_V> & other_V,
  776. const Eigen::MatrixXi & other_Ele,
  777. const Scalar /*min_sqr_d*/,
  778. Eigen::PlainObjectBase<DerivedsqrD> & sqrD,
  779. Eigen::PlainObjectBase<DerivedI> & I,
  780. Eigen::PlainObjectBase<DerivedC> & C) const
  781. {
  782. using namespace std;
  783. using namespace Eigen;
  784. // This implementation is a bit disappointing. There's no major speed up. Any
  785. // performance gains seem to come from accidental cache coherency and
  786. // diminish for larger "other" (the opposite of what was intended).
  787. // Base case
  788. if(other->is_leaf() && this->is_leaf())
  789. {
  790. Scalar sqr_d = sqrD(other->m_primitive);
  791. int i = I(other->m_primitive);
  792. RowVectorDIMS c = C.row( other->m_primitive);
  793. RowVectorDIMS p = other_V.row(other->m_primitive);
  794. leaf_squared_distance(V,Ele,p,sqr_d,i,c);
  795. sqrD( other->m_primitive) = sqr_d;
  796. I( other->m_primitive) = i;
  797. C.row(other->m_primitive) = c;
  798. //cout<<"leaf: "<<sqr_d<<endl;
  799. //other->m_max_sqr_d = sqr_d;
  800. return sqr_d;
  801. }
  802. if(other->is_leaf())
  803. {
  804. Scalar sqr_d = sqrD(other->m_primitive);
  805. int i = I(other->m_primitive);
  806. RowVectorDIMS c = C.row( other->m_primitive);
  807. RowVectorDIMS p = other_V.row(other->m_primitive);
  808. sqr_d = squared_distance(V,Ele,p,sqr_d,i,c);
  809. sqrD( other->m_primitive) = sqr_d;
  810. I( other->m_primitive) = i;
  811. C.row(other->m_primitive) = c;
  812. //other->m_max_sqr_d = sqr_d;
  813. return sqr_d;
  814. }
  815. //// Exact minimum squared distance between arbitary primitives inside this and
  816. //// othre's bounding boxes
  817. //const auto & min_squared_distance = [&](
  818. // const AABB<DerivedV,DIM> * A,
  819. // const AABB<Derivedother_V,DIM> * B)->Scalar
  820. //{
  821. // return A->m_box.squaredExteriorDistance(B->m_box);
  822. //};
  823. if(this->is_leaf())
  824. {
  825. //if(min_squared_distance(this,other) < other->m_max_sqr_d)
  826. if(true)
  827. {
  828. this->squared_distance_helper(
  829. V,Ele,other->m_left,other_V,other_Ele,0,sqrD,I,C);
  830. this->squared_distance_helper(
  831. V,Ele,other->m_right,other_V,other_Ele,0,sqrD,I,C);
  832. }else
  833. {
  834. // This is never reached...
  835. }
  836. //// we know other is not a leaf
  837. //other->m_max_sqr_d = std::max(other->m_left->m_max_sqr_d,other->m_right->m_max_sqr_d);
  838. return 0;
  839. }
  840. // FORCE DOWN TO OTHER LEAF EVAL
  841. //if(min_squared_distance(this,other) < other->m_max_sqr_d)
  842. if(true)
  843. {
  844. if(true)
  845. {
  846. this->squared_distance_helper(
  847. V,Ele,other->m_left,other_V,other_Ele,0,sqrD,I,C);
  848. this->squared_distance_helper(
  849. V,Ele,other->m_right,other_V,other_Ele,0,sqrD,I,C);
  850. }else // this direction never seems to be faster
  851. {
  852. this->m_left->squared_distance_helper(
  853. V,Ele,other,other_V,other_Ele,0,sqrD,I,C);
  854. this->m_right->squared_distance_helper(
  855. V,Ele,other,other_V,other_Ele,0,sqrD,I,C);
  856. }
  857. }else
  858. {
  859. // this is never reached ... :-(
  860. }
  861. //// we know other is not a leaf
  862. //other->m_max_sqr_d = std::max(other->m_left->m_max_sqr_d,other->m_right->m_max_sqr_d);
  863. return 0;
  864. #if 0 // False
  865. // _Very_ conservative approximation of maximum squared distance between
  866. // primitives inside this and other's bounding boxes
  867. const auto & max_squared_distance = [](
  868. const AABB<DerivedV,DIM> * A,
  869. const AABB<Derivedother_V,DIM> * B)->Scalar
  870. {
  871. AlignedBox<Scalar,DIM> combo = A->m_box;
  872. combo.extend(B->m_box);
  873. return combo.diagonal().squaredNorm();
  874. };
  875. //// other base-case
  876. //if(other->is_leaf())
  877. //{
  878. // double sqr_d = sqrD(other->m_primitive);
  879. // int i = I(other->m_primitive);
  880. // RowVectorDIMS c = C.row(m_primitive);
  881. // RowVectorDIMS p = other_V.row(m_primitive);
  882. // leaf_squared_distance(V,Ele,p,sqr_d,i,c);
  883. // sqrD(other->m_primitive) = sqr_d;
  884. // I(other->m_primitive) = i;
  885. // C.row(m_primitive) = c;
  886. // return;
  887. //}
  888. std::vector<const AABB<DerivedV,DIM> * > this_list;
  889. if(this->is_leaf())
  890. {
  891. this_list.push_back(this);
  892. }else
  893. {
  894. assert(this->m_left);
  895. this_list.push_back(this->m_left);
  896. assert(this->m_right);
  897. this_list.push_back(this->m_right);
  898. }
  899. std::vector<AABB<Derivedother_V,DIM> *> other_list;
  900. if(other->is_leaf())
  901. {
  902. other_list.push_back(other);
  903. }else
  904. {
  905. assert(other->m_left);
  906. other_list.push_back(other->m_left);
  907. assert(other->m_right);
  908. other_list.push_back(other->m_right);
  909. }
  910. //const std::function<Scalar(
  911. // const AABB<Derivedother_V,DIM> * other)
  912. // > max_sqr_d = [&sqrD,&max_sqr_d](const AABB<Derivedother_V,DIM> * other)->Scalar
  913. // {
  914. // if(other->is_leaf())
  915. // {
  916. // return sqrD(other->m_primitive);
  917. // }else
  918. // {
  919. // return std::max(max_sqr_d(other->m_left),max_sqr_d(other->m_right));
  920. // }
  921. // };
  922. //// Potentially recurse on all pairs, if minimum distance is less than running
  923. //// bound
  924. //Eigen::Matrix<Scalar,Eigen::Dynamic,1> other_max_sqr_d =
  925. // Eigen::Matrix<Scalar,Eigen::Dynamic,1>::Constant(other_list.size(),1,min_sqr_d);
  926. for(size_t child = 0;child<other_list.size();child++)
  927. {
  928. auto other_tree = other_list[child];
  929. Eigen::Matrix<Scalar,Eigen::Dynamic,1> this_max_sqr_d(this_list.size(),1);
  930. for(size_t t = 0;t<this_list.size();t++)
  931. {
  932. const auto this_tree = this_list[t];
  933. this_max_sqr_d(t) = max_squared_distance(this_tree,other_tree);
  934. }
  935. if(this_list.size() ==2 &&
  936. ( this_max_sqr_d(0) > this_max_sqr_d(1))
  937. )
  938. {
  939. std::swap(this_list[0],this_list[1]);
  940. //std::swap(this_max_sqr_d(0),this_max_sqr_d(1));
  941. }
  942. const Scalar sqr_d = this_max_sqr_d.minCoeff();
  943. for(size_t t = 0;t<this_list.size();t++)
  944. {
  945. const auto this_tree = this_list[t];
  946. //const auto mm = max_sqr_d(other_tree);
  947. //const Scalar mc = other_max_sqr_d(child);
  948. //assert(mc == mm);
  949. // Only look left/right in this_list if can possible decrease somebody's
  950. // distance in this_tree.
  951. const Scalar min_this_other = min_squared_distance(this_tree,other_tree);
  952. if(
  953. min_this_other < sqr_d &&
  954. min_this_other < other_tree->m_max_sqr_d)
  955. {
  956. //cout<<"before: "<<other_max_sqr_d(child)<<endl;
  957. //other_max_sqr_d(child) = std::min(
  958. // other_max_sqr_d(child),
  959. // this_tree->squared_distance_helper(
  960. // V,Ele,other_tree,other_V,other_Ele,other_max_sqr_d(child),sqrD,I,C));
  961. //cout<<"after: "<<other_max_sqr_d(child)<<endl;
  962. this_tree->squared_distance_helper(
  963. V,Ele,other_tree,other_V,other_Ele,0,sqrD,I,C);
  964. }
  965. }
  966. }
  967. //const Scalar ret = other_max_sqr_d.maxCoeff();
  968. //const auto mm = max_sqr_d(other);
  969. //assert(mm == ret);
  970. //cout<<"non-leaf: "<<ret<<endl;
  971. //return ret;
  972. if(!other->is_leaf())
  973. {
  974. other->m_max_sqr_d = std::max(other->m_left->m_max_sqr_d,other->m_right->m_max_sqr_d);
  975. }
  976. return 0;
  977. #endif
  978. }
  979. template <typename DerivedV, int DIM>
  980. inline void igl::AABB<DerivedV,DIM>::leaf_squared_distance(
  981. const Eigen::PlainObjectBase<DerivedV> & V,
  982. const Eigen::MatrixXi & Ele,
  983. const RowVectorDIMS & p,
  984. Scalar & sqr_d,
  985. int & i,
  986. RowVectorDIMS & c) const
  987. {
  988. using namespace Eigen;
  989. using namespace igl;
  990. using namespace std;
  991. // Simplex size
  992. const size_t ss = Ele.cols();
  993. // Only one element per node
  994. // plane unit normal
  995. bool inside_triangle = false;
  996. Scalar d_j = std::numeric_limits<Scalar>::infinity();
  997. RowVectorDIMS pp;
  998. // Only consider triangles, and non-degenerate triangles at that
  999. if(ss == 3 &&
  1000. Ele(m_primitive,0) != Ele(m_primitive,1) &&
  1001. Ele(m_primitive,1) != Ele(m_primitive,2) &&
  1002. Ele(m_primitive,2) != Ele(m_primitive,0))
  1003. {
  1004. assert(DIM == 3 && "Only implemented for 3D triangles");
  1005. typedef Eigen::Matrix<Scalar,1,3> RowVector3S;
  1006. // can't be const because of annoying DIM template
  1007. RowVector3S v10(0,0,0);
  1008. v10.head(DIM) = (V.row(Ele(m_primitive,1))- V.row(Ele(m_primitive,0)));
  1009. RowVector3S v20(0,0,0);
  1010. v20.head(DIM) = (V.row(Ele(m_primitive,2))- V.row(Ele(m_primitive,0)));
  1011. const RowVectorDIMS n = (v10.cross(v20)).head(DIM);
  1012. Scalar n_norm = n.norm();
  1013. if(n_norm > 0)
  1014. {
  1015. const RowVectorDIMS un = n/n.norm();
  1016. // vector to plane
  1017. const RowVectorDIMS bc =
  1018. 1./3.*
  1019. ( V.row(Ele(m_primitive,0))+
  1020. V.row(Ele(m_primitive,1))+
  1021. V.row(Ele(m_primitive,2)));
  1022. const auto & v = p-bc;
  1023. // projected point on plane
  1024. d_j = v.dot(un);
  1025. pp = p - d_j*un;
  1026. // determine if pp is inside triangle
  1027. Eigen::Matrix<Scalar,1,3> b;
  1028. barycentric_coordinates(
  1029. pp,
  1030. V.row(Ele(m_primitive,0)),
  1031. V.row(Ele(m_primitive,1)),
  1032. V.row(Ele(m_primitive,2)),
  1033. b);
  1034. inside_triangle = fabs(fabs(b(0)) + fabs(b(1)) + fabs(b(2)) - 1.) <= 1e-10;
  1035. }
  1036. }
  1037. const auto & point_point_squared_distance = [&](const RowVectorDIMS & s)
  1038. {
  1039. const Scalar sqr_d_s = (p-s).squaredNorm();
  1040. set_min(p,sqr_d_s,m_primitive,s,sqr_d,i,c);
  1041. };
  1042. if(inside_triangle)
  1043. {
  1044. // point-triangle squared distance
  1045. const Scalar sqr_d_j = d_j*d_j;
  1046. //cout<<"point-triangle..."<<endl;
  1047. set_min(p,sqr_d_j,m_primitive,pp,sqr_d,i,c);
  1048. }else
  1049. {
  1050. if(ss >= 2)
  1051. {
  1052. // point-segment distance
  1053. // number of edges
  1054. size_t ne = ss==3?3:1;
  1055. for(size_t x = 0;x<ne;x++)
  1056. {
  1057. const size_t e1 = Ele(m_primitive,(x+1)%ss);
  1058. const size_t e2 = Ele(m_primitive,(x+2)%ss);
  1059. const RowVectorDIMS & s = V.row(e1);
  1060. const RowVectorDIMS & d = V.row(e2);
  1061. // Degenerate edge
  1062. if(e1 == e2 || (s-d).squaredNorm()==0)
  1063. {
  1064. // only consider once
  1065. if(e1 < e2)
  1066. {
  1067. point_point_squared_distance(s);
  1068. }
  1069. continue;
  1070. }
  1071. Matrix<Scalar,1,1> sqr_d_j_x(1,1);
  1072. Matrix<Scalar,1,1> t(1,1);
  1073. project_to_line_segment(p,s,d,t,sqr_d_j_x);
  1074. const RowVectorDIMS q = s+t(0)*(d-s);
  1075. set_min(p,sqr_d_j_x(0),m_primitive,q,sqr_d,i,c);
  1076. }
  1077. }else
  1078. {
  1079. // So then Ele is just a list of points...
  1080. assert(ss == 1);
  1081. const RowVectorDIMS & s = V.row(Ele(m_primitive,0));
  1082. point_point_squared_distance(s);
  1083. }
  1084. }
  1085. }
  1086. template <typename DerivedV, int DIM>
  1087. inline void igl::AABB<DerivedV,DIM>::set_min(
  1088. const RowVectorDIMS &
  1089. #ifndef NDEBUG
  1090. p
  1091. #endif
  1092. ,
  1093. const Scalar sqr_d_candidate,
  1094. const int i_candidate,
  1095. const RowVectorDIMS & c_candidate,
  1096. Scalar & sqr_d,
  1097. int & i,
  1098. RowVectorDIMS & c) const
  1099. {
  1100. #ifndef NDEBUG
  1101. //std::cout<<matlab_format(c_candidate,"c_candidate")<<std::endl;
  1102. const Scalar pc_norm = (p-c_candidate).squaredNorm();
  1103. const Scalar diff = fabs(sqr_d_candidate - pc_norm);
  1104. assert(diff<=1e-10 && "distance should match norm of difference");
  1105. #endif
  1106. if(sqr_d_candidate < sqr_d)
  1107. {
  1108. i = i_candidate;
  1109. c = c_candidate;
  1110. sqr_d = sqr_d_candidate;
  1111. }
  1112. }
  1113. template <typename DerivedV, int DIM>
  1114. inline void
  1115. igl::AABB<DerivedV,DIM>::barycentric_coordinates(
  1116. const RowVectorDIMS & p,
  1117. const RowVectorDIMS & a,
  1118. const RowVectorDIMS & b,
  1119. const RowVectorDIMS & c,
  1120. Eigen::Matrix<Scalar,1,3> & bary)
  1121. {
  1122. // http://gamedev.stackexchange.com/a/23745
  1123. const RowVectorDIMS v0 = b - a;
  1124. const RowVectorDIMS v1 = c - a;
  1125. const RowVectorDIMS v2 = p - a;
  1126. Scalar d00 = v0.dot(v0);
  1127. Scalar d01 = v0.dot(v1);
  1128. Scalar d11 = v1.dot(v1);
  1129. Scalar d20 = v2.dot(v0);
  1130. Scalar d21 = v2.dot(v1);
  1131. Scalar denom = d00 * d11 - d01 * d01;
  1132. bary(1) = (d11 * d20 - d01 * d21) / denom;
  1133. bary(2) = (d00 * d21 - d01 * d20) / denom;
  1134. bary(0) = 1.0f - bary(1) - bary(2);
  1135. }
  1136. template <typename DerivedV, int DIM>
  1137. inline bool
  1138. igl::AABB<DerivedV,DIM>::intersect_ray(
  1139. const Eigen::PlainObjectBase<DerivedV> & V,
  1140. const Eigen::MatrixXi & Ele,
  1141. const RowVectorDIMS & origin,
  1142. const RowVectorDIMS & dir,
  1143. std::vector<igl::Hit> & hits) const
  1144. {
  1145. hits.clear();
  1146. const Scalar t0 = 0;
  1147. const Scalar t1 = std::numeric_limits<Scalar>::infinity();
  1148. {
  1149. Scalar _1,_2;
  1150. if(!ray_box_intersect(origin,dir,m_box,t0,t1,_1,_2))
  1151. {
  1152. return false;
  1153. }
  1154. }
  1155. if(this->is_leaf())
  1156. {
  1157. // Actually process elements
  1158. assert((Ele.size() == 0 || Ele.cols() == 3) && "Elements should be triangles");
  1159. // Cheesecake way of hitting element
  1160. return ray_mesh_intersect(origin,dir,V,Ele.row(m_primitive).eval(),hits);
  1161. }
  1162. std::vector<igl::Hit> left_hits;
  1163. std::vector<igl::Hit> right_hits;
  1164. const bool left_ret = m_left->intersect_ray(V,Ele,origin,dir,left_hits);
  1165. const bool right_ret = m_right->intersect_ray(V,Ele,origin,dir,right_hits);
  1166. hits.insert(hits.end(),left_hits.begin(),left_hits.end());
  1167. hits.insert(hits.end(),right_hits.begin(),right_hits.end());
  1168. return left_ret || right_ret;
  1169. }
  1170. template <typename DerivedV, int DIM>
  1171. inline bool
  1172. igl::AABB<DerivedV,DIM>::intersect_ray(
  1173. const Eigen::PlainObjectBase<DerivedV> & V,
  1174. const Eigen::MatrixXi & Ele,
  1175. const RowVectorDIMS & origin,
  1176. const RowVectorDIMS & dir,
  1177. igl::Hit & hit) const
  1178. {
  1179. #if false
  1180. // BFS
  1181. std::queue<const AABB *> Q;
  1182. // Or DFS
  1183. //std::stack<const AABB *> Q;
  1184. Q.push(this);
  1185. bool any_hit = false;
  1186. hit.t = std::numeric_limits<Scalar>::infinity();
  1187. while(!Q.empty())
  1188. {
  1189. const AABB * tree = Q.front();
  1190. //const AABB * tree = Q.top();
  1191. Q.pop();
  1192. {
  1193. Scalar _1,_2;
  1194. if(!ray_box_intersect(
  1195. origin,dir,tree->m_box,Scalar(0),Scalar(hit.t),_1,_2))
  1196. {
  1197. continue;
  1198. }
  1199. }
  1200. if(tree->is_leaf())
  1201. {
  1202. // Actually process elements
  1203. assert((Ele.size() == 0 || Ele.cols() == 3) && "Elements should be triangles");
  1204. igl::Hit leaf_hit;
  1205. if(
  1206. ray_mesh_intersect(origin,dir,V,Ele.row(tree->m_primitive).eval(),leaf_hit)&&
  1207. leaf_hit.t < hit.t)
  1208. {
  1209. hit = leaf_hit;
  1210. }
  1211. continue;
  1212. }
  1213. // Add children to queue
  1214. Q.push(tree->m_left);
  1215. Q.push(tree->m_right);
  1216. }
  1217. return any_hit;
  1218. #else
  1219. // DFS
  1220. return intersect_ray(
  1221. V,Ele,origin,dir,std::numeric_limits<Scalar>::infinity(),hit);
  1222. #endif
  1223. }
  1224. template <typename DerivedV, int DIM>
  1225. inline bool
  1226. igl::AABB<DerivedV,DIM>::intersect_ray(
  1227. const Eigen::PlainObjectBase<DerivedV> & V,
  1228. const Eigen::MatrixXi & Ele,
  1229. const RowVectorDIMS & origin,
  1230. const RowVectorDIMS & dir,
  1231. const Scalar _min_t,
  1232. igl::Hit & hit) const
  1233. {
  1234. //// Naive, slow
  1235. //std::vector<igl::Hit> hits;
  1236. //intersect_ray(V,Ele,origin,dir,hits);
  1237. //if(hits.size() > 0)
  1238. //{
  1239. // hit = hits.front();
  1240. // return true;
  1241. //}else
  1242. //{
  1243. // return false;
  1244. //}
  1245. Scalar min_t = _min_t;
  1246. const Scalar t0 = 0;
  1247. {
  1248. Scalar _1,_2;
  1249. if(!ray_box_intersect(origin,dir,m_box,t0,min_t,_1,_2))
  1250. {
  1251. return false;
  1252. }
  1253. }
  1254. if(this->is_leaf())
  1255. {
  1256. // Actually process elements
  1257. assert((Ele.size() == 0 || Ele.cols() == 3) && "Elements should be triangles");
  1258. // Cheesecake way of hitting element
  1259. return ray_mesh_intersect(origin,dir,V,Ele.row(m_primitive).eval(),hit);
  1260. }
  1261. // Doesn't seem like smartly choosing left before/after right makes a
  1262. // differnce
  1263. igl::Hit left_hit;
  1264. igl::Hit right_hit;
  1265. bool left_ret = m_left->intersect_ray(V,Ele,origin,dir,min_t,left_hit);
  1266. if(left_ret && left_hit.t<min_t)
  1267. {
  1268. // It's scary that this line doesn't seem to matter....
  1269. min_t = left_hit.t;
  1270. hit = left_hit;
  1271. left_ret = true;
  1272. }else
  1273. {
  1274. left_ret = false;
  1275. }
  1276. bool right_ret = m_right->intersect_ray(V,Ele,origin,dir,min_t,right_hit);
  1277. if(right_ret && right_hit.t<min_t)
  1278. {
  1279. min_t = right_hit.t;
  1280. hit = right_hit;
  1281. right_ret = true;
  1282. }else
  1283. {
  1284. right_ret = false;
  1285. }
  1286. return left_ret || right_ret;
  1287. }
  1288. #endif