AABB.h 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  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. // Implementation of semi-general purpose axis-aligned bounding box hierarchy.
  11. // The mesh (V,Ele) is stored and managed by the caller and each routine here
  12. // simply takes it as references (it better not change between calls).
  13. //
  14. // It's a little annoying that the Dimension is a template parameter and not
  15. // picked up at run time from V. This leads to duplicated code for 2d/3d (up to
  16. // dim).
  17. #include <Eigen/Core>
  18. #include <Eigen/Geometry>
  19. #include <vector>
  20. namespace igl
  21. {
  22. template <typename DerivedV, int DIM>
  23. class AABB
  24. {
  25. public:
  26. typedef typename DerivedV::Scalar Scalar;
  27. typedef Eigen::Matrix<Scalar,1,DIM> RowVectorDIMS;
  28. typedef Eigen::Matrix<Scalar,DIM,1> VectorDIMS;
  29. typedef Eigen::Matrix<Scalar,Eigen::Dynamic,DIM> MatrixXDIMS;
  30. // Shared pointers are slower...
  31. AABB * m_left;
  32. AABB * m_right;
  33. Eigen::AlignedBox<Scalar,DIM> m_box;
  34. // -1 non-leaf
  35. int m_primitive;
  36. AABB():
  37. m_left(NULL), m_right(NULL),
  38. m_box(), m_primitive(-1)
  39. {}
  40. // http://stackoverflow.com/a/3279550/148668
  41. AABB(const AABB& other):
  42. m_left(other.m_left ? new AABB(*other.m_left) : NULL),
  43. m_right(other.m_right ? new AABB(*other.m_right) : NULL),
  44. m_box(other.m_box),
  45. m_primitive(other.m_primitive)
  46. {
  47. }
  48. // copy-swap idiom
  49. friend void swap(AABB& first, AABB& second)
  50. {
  51. // Enable ADL
  52. using std::swap;
  53. swap(first.m_left,second.m_left);
  54. swap(first.m_right,second.m_right);
  55. swap(first.m_box,second.m_box);
  56. swap(first.m_primitive,second.m_primitive);
  57. }
  58. // Pass-by-value (aka copy)
  59. AABB& operator=(AABB other)
  60. {
  61. swap(*this,other);
  62. return *this;
  63. }
  64. AABB(AABB&& other):
  65. // initialize via default constructor
  66. AABB()
  67. {
  68. swap(*this,other);
  69. }
  70. // Seems like there should have been an elegant solution to this using
  71. // the copy-swap idiom above:
  72. inline void deinit()
  73. {
  74. m_primitive = -1;
  75. m_box = Eigen::AlignedBox<Scalar,DIM>();
  76. delete m_left;
  77. m_left = NULL;
  78. delete m_right;
  79. m_right = NULL;
  80. }
  81. ~AABB()
  82. {
  83. deinit();
  84. }
  85. // Build an Axis-Aligned Bounding Box tree for a given mesh and given
  86. // serialization of a previous AABB tree.
  87. //
  88. // Inputs:
  89. // V #V by dim list of mesh vertex positions.
  90. // Ele #Ele by dim+1 list of mesh indices into #V.
  91. // bb_mins max_tree by dim list of bounding box min corner positions
  92. // bb_maxs max_tree by dim list of bounding box max corner positions
  93. // elements max_tree list of element or (not leaf id) indices into Ele
  94. // i recursive call index {0}
  95. template <typename Derivedbb_mins, typename Derivedbb_maxs>
  96. inline void init(
  97. const Eigen::PlainObjectBase<DerivedV> & V,
  98. const Eigen::MatrixXi & Ele,
  99. const Eigen::PlainObjectBase<Derivedbb_mins> & bb_mins,
  100. const Eigen::PlainObjectBase<Derivedbb_maxs> & bb_maxs,
  101. const Eigen::VectorXi & elements,
  102. const int i = 0);
  103. // Wrapper for root with empty serialization
  104. inline void init(
  105. const Eigen::PlainObjectBase<DerivedV> & V,
  106. const Eigen::MatrixXi & Ele);
  107. // Build an Axis-Aligned Bounding Box tree for a given mesh.
  108. //
  109. // Inputs:
  110. // V #V by dim list of mesh vertex positions.
  111. // Ele #Ele by dim+1 list of mesh indices into #V.
  112. // SI #Ele by dim list revealing for each coordinate where Ele's
  113. // barycenters would be sorted: SI(e,d) = i --> the dth coordinate of
  114. // the barycenter of the eth element would be placed at position i in a
  115. // sorted list.
  116. // I #I list of indices into Ele of elements to include (for recursive
  117. // calls)
  118. //
  119. inline void init(
  120. const Eigen::PlainObjectBase<DerivedV> & V,
  121. const Eigen::MatrixXi & Ele,
  122. const Eigen::MatrixXi & SI,
  123. const Eigen::VectorXi & I);
  124. // Return whether at leaf node
  125. inline bool is_leaf() const;
  126. // Find the indices of elements containing given point.
  127. //
  128. // Inputs:
  129. // V #V by dim list of mesh vertex positions. **Should be same as used to
  130. // construct mesh.**
  131. // Ele #Ele by dim+1 list of mesh indices into #V. **Should be same as used to
  132. // construct mesh.**
  133. // q dim row-vector query position
  134. // first whether to only return first element containing q
  135. // Returns:
  136. // list of indices of elements containing q
  137. template <typename Derivedq>
  138. inline std::vector<int> find(
  139. const Eigen::PlainObjectBase<DerivedV> & V,
  140. const Eigen::MatrixXi & Ele,
  141. const Eigen::PlainObjectBase<Derivedq> & q,
  142. const bool first=false) const;
  143. // If number of elements m then total tree size should be 2*h where h is
  144. // the deepest depth 2^ceil(log(#Ele*2-1))
  145. inline int subtree_size() const;
  146. // Serialize this class into 3 arrays (so we can pass it pack to matlab)
  147. //
  148. // Outputs:
  149. // bb_mins max_tree by dim list of bounding box min corner positions
  150. // bb_maxs max_tree by dim list of bounding box max corner positions
  151. // elements max_tree list of element or (not leaf id) indices into Ele
  152. // i recursive call index into these arrays {0}
  153. template <typename Derivedbb_mins, typename Derivedbb_maxs>
  154. inline void serialize(
  155. Eigen::PlainObjectBase<Derivedbb_mins> & bb_mins,
  156. Eigen::PlainObjectBase<Derivedbb_maxs> & bb_maxs,
  157. Eigen::VectorXi & elements,
  158. const int i = 0) const;
  159. // Compute squared distance to a query point
  160. //
  161. // Inputs:
  162. // V #V by dim list of vertex positions
  163. // Ele #Ele by dim list of simplex indices
  164. // P 3 list of query point coordinates
  165. // min_sqr_d current minimum squared distance (only find distances
  166. // less than this)
  167. // Outputs:
  168. // I #P list of facet indices corresponding to smallest distances
  169. // C #P by 3 list of closest points
  170. // Returns squared distance
  171. //
  172. // Known bugs: currently assumes Elements are triangles regardless of
  173. // dimension.
  174. inline Scalar squared_distance(
  175. const Eigen::PlainObjectBase<DerivedV> & V,
  176. const Eigen::MatrixXi & Ele,
  177. const RowVectorDIMS & p,
  178. int & i,
  179. RowVectorDIMS & c) const;
  180. private:
  181. inline Scalar squared_distance(
  182. const Eigen::PlainObjectBase<DerivedV> & V,
  183. const Eigen::MatrixXi & Ele,
  184. const RowVectorDIMS & p,
  185. const Scalar min_sqr_d,
  186. int & i,
  187. RowVectorDIMS & c) const;
  188. public:
  189. template <
  190. typename DerivedP,
  191. typename DerivedsqrD,
  192. typename DerivedI,
  193. typename DerivedC>
  194. inline void squared_distance(
  195. const Eigen::PlainObjectBase<DerivedV> & V,
  196. const Eigen::MatrixXi & Ele,
  197. const Eigen::PlainObjectBase<DerivedP> & P,
  198. Eigen::PlainObjectBase<DerivedsqrD> & sqrD,
  199. Eigen::PlainObjectBase<DerivedI> & I,
  200. Eigen::PlainObjectBase<DerivedC> & C) const;
  201. private:
  202. // Helper function for leaves: works in-place on sqr_d
  203. inline void leaf_squared_distance(
  204. const Eigen::PlainObjectBase<DerivedV> & V,
  205. const Eigen::MatrixXi & Ele,
  206. const RowVectorDIMS & p,
  207. Scalar & sqr_d,
  208. int & i,
  209. RowVectorDIMS & c) const;
  210. inline void set_min(
  211. const RowVectorDIMS & p,
  212. const Scalar sqr_d_candidate,
  213. const int i_candidate,
  214. const RowVectorDIMS & c_candidate,
  215. Scalar & sqr_d,
  216. int & i,
  217. RowVectorDIMS & c) const;
  218. public:
  219. template <int SS>
  220. static
  221. void barycentric_coordinates(
  222. const RowVectorDIMS & p,
  223. const RowVectorDIMS & a,
  224. const RowVectorDIMS & b,
  225. const RowVectorDIMS & c,
  226. Eigen::Matrix<Scalar,1,SS> & bary);
  227. };
  228. }
  229. // Implementation
  230. #include "EPS.h"
  231. #include "barycenter.h"
  232. #include "colon.h"
  233. #include "colon.h"
  234. #include "doublearea.h"
  235. #include "matlab_format.h"
  236. #include "project_to_line_segment.h"
  237. #include "sort.h"
  238. #include "volume.h"
  239. #include <iostream>
  240. #include <limits>
  241. template <typename DerivedV, int DIM>
  242. template <typename Derivedbb_mins, typename Derivedbb_maxs>
  243. inline void igl::AABB<DerivedV,DIM>::init(
  244. const Eigen::PlainObjectBase<DerivedV> & V,
  245. const Eigen::MatrixXi & Ele,
  246. const Eigen::PlainObjectBase<Derivedbb_mins> & bb_mins,
  247. const Eigen::PlainObjectBase<Derivedbb_maxs> & bb_maxs,
  248. const Eigen::VectorXi & elements,
  249. const int i)
  250. {
  251. using namespace std;
  252. using namespace Eigen;
  253. if(bb_mins.size() > 0)
  254. {
  255. assert(bb_mins.rows() == bb_maxs.rows() && "Serial tree arrays must match");
  256. assert(bb_mins.cols() == V.cols() && "Serial tree array dim must match V");
  257. assert(bb_mins.cols() == bb_maxs.cols() && "Serial tree arrays must match");
  258. assert(bb_mins.rows() == elements.rows() &&
  259. "Serial tree arrays must match");
  260. // construct from serialization
  261. m_box.extend(bb_mins.row(i).transpose());
  262. m_box.extend(bb_maxs.row(i).transpose());
  263. m_primitive = elements(i);
  264. // Not leaf then recurse
  265. if(m_primitive == -1)
  266. {
  267. m_left = new AABB();
  268. m_left->init( V,Ele,bb_mins,bb_maxs,elements,2*i+1);
  269. m_right = new AABB();
  270. m_right->init( V,Ele,bb_mins,bb_maxs,elements,2*i+2);
  271. }
  272. }else
  273. {
  274. VectorXi allI = colon<int>(0,Ele.rows()-1);
  275. MatrixXDIMS BC;
  276. barycenter(V,Ele,BC);
  277. MatrixXi SI(BC.rows(),BC.cols());
  278. {
  279. MatrixXDIMS _;
  280. MatrixXi IS;
  281. igl::sort(BC,1,true,_,IS);
  282. // Need SI(i) to tell which place i would be sorted into
  283. const int dim = IS.cols();
  284. for(int i = 0;i<IS.rows();i++)
  285. {
  286. for(int d = 0;d<dim;d++)
  287. {
  288. SI(IS(i,d),d) = i;
  289. }
  290. }
  291. }
  292. init(V,Ele,SI,allI);
  293. }
  294. }
  295. template <typename DerivedV, int DIM>
  296. inline void igl::AABB<DerivedV,DIM>::init(
  297. const Eigen::PlainObjectBase<DerivedV> & V,
  298. const Eigen::MatrixXi & Ele)
  299. {
  300. using namespace Eigen;
  301. return init(V,Ele,MatrixXDIMS(),MatrixXDIMS(),VectorXi(),0);
  302. }
  303. template <typename DerivedV, int DIM>
  304. inline void igl::AABB<DerivedV,DIM>::init(
  305. const Eigen::PlainObjectBase<DerivedV> & V,
  306. const Eigen::MatrixXi & Ele,
  307. const Eigen::MatrixXi & SI,
  308. const Eigen::VectorXi & I)
  309. {
  310. using namespace Eigen;
  311. using namespace std;
  312. assert(DIM == V.cols() && "V.cols() should matched declared dimension");
  313. const Scalar inf = numeric_limits<Scalar>::infinity();
  314. m_box = AlignedBox<Scalar,DIM>();
  315. // Compute bounding box
  316. for(int i = 0;i<I.rows();i++)
  317. {
  318. for(int c = 0;c<Ele.cols();c++)
  319. {
  320. m_box.extend(V.row(Ele(I(i),c)).transpose());
  321. m_box.extend(V.row(Ele(I(i),c)).transpose());
  322. }
  323. }
  324. switch(I.size())
  325. {
  326. case 0:
  327. {
  328. assert(false);
  329. }
  330. case 1:
  331. {
  332. m_primitive = I(0);
  333. break;
  334. }
  335. default:
  336. {
  337. // Compute longest direction
  338. int max_d = -1;
  339. m_box.diagonal().maxCoeff(&max_d);
  340. // Can't use median on BC directly because many may have same value,
  341. // but can use median on sorted BC indices
  342. VectorXi SIdI(I.rows());
  343. for(int i = 0;i<I.rows();i++)
  344. {
  345. SIdI(i) = SI(I(i),max_d);
  346. }
  347. // Since later I use <= I think I don't need to worry about odd/even
  348. // Pass by copy to avoid changing input
  349. const auto median = [](VectorXi A)->Scalar
  350. {
  351. size_t n = A.size()/2;
  352. nth_element(A.data(),A.data()+n,A.data()+A.size());
  353. if(A.rows() % 2 == 1)
  354. {
  355. return A(n);
  356. }else
  357. {
  358. nth_element(A.data(),A.data()+n-1,A.data()+A.size());
  359. return 0.5*(A(n)+A(n-1));
  360. }
  361. };
  362. const Scalar med = median(SIdI);
  363. VectorXi LI((I.rows()+1)/2),RI(I.rows()/2);
  364. assert(LI.rows()+RI.rows() == I.rows());
  365. // Distribute left and right
  366. {
  367. int li = 0;
  368. int ri = 0;
  369. for(int i = 0;i<I.rows();i++)
  370. {
  371. if(SIdI(i)<=med)
  372. {
  373. LI(li++) = I(i);
  374. }else
  375. {
  376. RI(ri++) = I(i);
  377. }
  378. }
  379. }
  380. if(LI.rows()>0)
  381. {
  382. m_left = new AABB();
  383. m_left->init(V,Ele,SI,LI);
  384. }
  385. if(RI.rows()>0)
  386. {
  387. m_right = new AABB();
  388. m_right->init(V,Ele,SI,RI);
  389. }
  390. }
  391. }
  392. }
  393. template <typename DerivedV, int DIM>
  394. inline bool igl::AABB<DerivedV,DIM>::is_leaf() const
  395. {
  396. return m_primitive != -1;
  397. }
  398. template <typename DerivedV, int DIM>
  399. template <typename Derivedq>
  400. inline std::vector<int> igl::AABB<DerivedV,DIM>::find(
  401. const Eigen::PlainObjectBase<DerivedV> & V,
  402. const Eigen::MatrixXi & Ele,
  403. const Eigen::PlainObjectBase<Derivedq> & q,
  404. const bool first) const
  405. {
  406. using namespace std;
  407. using namespace Eigen;
  408. assert(q.size() == DIM &&
  409. "Query dimension should match aabb dimension");
  410. assert(Ele.cols() == V.cols()+1 &&
  411. "AABB::find only makes sense for (d+1)-simplices");
  412. const Scalar epsilon = igl::EPS<Scalar>();
  413. // Check if outside bounding box
  414. bool inside = m_box.contains(q.transpose());
  415. if(!inside)
  416. {
  417. return std::vector<int>();
  418. }
  419. assert(m_primitive==-1 || (m_left == NULL && m_right == NULL));
  420. if(is_leaf())
  421. {
  422. // Initialize to some value > -epsilon
  423. Scalar a1=1,a2=1,a3=1,a4=1;
  424. switch(DIM)
  425. {
  426. case 3:
  427. {
  428. // Barycentric coordinates
  429. typedef Eigen::Matrix<Scalar,1,3> RowVector3S;
  430. const RowVector3S V1 = V.row(Ele(m_primitive,0));
  431. const RowVector3S V2 = V.row(Ele(m_primitive,1));
  432. const RowVector3S V3 = V.row(Ele(m_primitive,2));
  433. const RowVector3S V4 = V.row(Ele(m_primitive,3));
  434. a1 = volume_single(V2,V4,V3,(RowVector3S)q);
  435. a2 = volume_single(V1,V3,V4,(RowVector3S)q);
  436. a3 = volume_single(V1,V4,V2,(RowVector3S)q);
  437. a4 = volume_single(V1,V2,V3,(RowVector3S)q);
  438. break;
  439. }
  440. case 2:
  441. {
  442. // Barycentric coordinates
  443. typedef Eigen::Matrix<Scalar,2,1> Vector2S;
  444. const Vector2S V1 = V.row(Ele(m_primitive,0));
  445. const Vector2S V2 = V.row(Ele(m_primitive,1));
  446. const Vector2S V3 = V.row(Ele(m_primitive,2));
  447. // Hack for now to keep templates simple. If becomes bottleneck
  448. // consider using std::enable_if_t
  449. const Vector2S q2 = q.head(2);
  450. Scalar a0 = doublearea_single(V1,V2,V3);
  451. a1 = doublearea_single(V1,V2,q2);
  452. a2 = doublearea_single(V2,V3,q2);
  453. a3 = doublearea_single(V3,V1,q2);
  454. break;
  455. }
  456. default:assert(false);
  457. }
  458. if(
  459. a1>=-epsilon &&
  460. a2>=-epsilon &&
  461. a3>=-epsilon &&
  462. a4>=-epsilon)
  463. {
  464. return std::vector<int>(1,m_primitive);
  465. }else
  466. {
  467. return std::vector<int>();
  468. }
  469. }
  470. std::vector<int> left = m_left->find(V,Ele,q,first);
  471. if(first && !left.empty())
  472. {
  473. return left;
  474. }
  475. std::vector<int> right = m_right->find(V,Ele,q,first);
  476. if(first)
  477. {
  478. return right;
  479. }
  480. left.insert(left.end(),right.begin(),right.end());
  481. return left;
  482. }
  483. template <typename DerivedV, int DIM>
  484. inline int igl::AABB<DerivedV,DIM>::subtree_size() const
  485. {
  486. // 1 for self
  487. int n = 1;
  488. int n_left = 0,n_right = 0;
  489. if(m_left != NULL)
  490. {
  491. n_left = m_left->subtree_size();
  492. }
  493. if(m_right != NULL)
  494. {
  495. n_right = m_right->subtree_size();
  496. }
  497. n += 2*std::max(n_left,n_right);
  498. return n;
  499. }
  500. template <typename DerivedV, int DIM>
  501. template <typename Derivedbb_mins, typename Derivedbb_maxs>
  502. inline void igl::AABB<DerivedV,DIM>::serialize(
  503. Eigen::PlainObjectBase<Derivedbb_mins> & bb_mins,
  504. Eigen::PlainObjectBase<Derivedbb_maxs> & bb_maxs,
  505. Eigen::VectorXi & elements,
  506. const int i) const
  507. {
  508. using namespace std;
  509. using namespace Eigen;
  510. // Calling for root then resize output
  511. if(i==0)
  512. {
  513. const int m = subtree_size();
  514. //cout<<"m: "<<m<<endl;
  515. bb_mins.resize(m,DIM);
  516. bb_maxs.resize(m,DIM);
  517. elements.resize(m,1);
  518. }
  519. //cout<<i<<" ";
  520. bb_mins.row(i) = m_box.min();
  521. bb_maxs.row(i) = m_box.max();
  522. elements(i) = m_primitive;
  523. if(m_left != NULL)
  524. {
  525. m_left->serialize(bb_mins,bb_maxs,elements,2*i+1);
  526. }
  527. if(m_right != NULL)
  528. {
  529. m_right->serialize(bb_mins,bb_maxs,elements,2*i+2);
  530. }
  531. }
  532. template <typename DerivedV, int DIM>
  533. inline typename igl::AABB<DerivedV,DIM>::Scalar
  534. igl::AABB<DerivedV,DIM>::squared_distance(
  535. const Eigen::PlainObjectBase<DerivedV> & V,
  536. const Eigen::MatrixXi & Ele,
  537. const RowVectorDIMS & p,
  538. int & i,
  539. RowVectorDIMS & c) const
  540. {
  541. return squared_distance(V,Ele,p,std::numeric_limits<Scalar>::infinity(),i,c);
  542. }
  543. template <typename DerivedV, int DIM>
  544. inline typename igl::AABB<DerivedV,DIM>::Scalar
  545. igl::AABB<DerivedV,DIM>::squared_distance(
  546. const Eigen::PlainObjectBase<DerivedV> & V,
  547. const Eigen::MatrixXi & Ele,
  548. const RowVectorDIMS & p,
  549. Scalar min_sqr_d,
  550. int & i,
  551. RowVectorDIMS & c) const
  552. {
  553. using namespace Eigen;
  554. using namespace std;
  555. using namespace igl;
  556. Scalar sqr_d = min_sqr_d;
  557. assert(DIM == 3 && "Code has only been tested for DIM == 3");
  558. assert((Ele.cols() == 3 || Ele.cols() == 2 || Ele.cols() == 1)
  559. && "Code has only been tested for simplex sizes 3,2,1");
  560. assert(m_primitive==-1 || (m_left == NULL && m_right == NULL));
  561. if(is_leaf())
  562. {
  563. leaf_squared_distance(V,Ele,p,sqr_d,i,c);
  564. }else
  565. {
  566. bool looked_left = false;
  567. bool looked_right = false;
  568. const auto & look_left = [&]()
  569. {
  570. int i_left;
  571. RowVectorDIMS c_left;
  572. Scalar sqr_d_left = m_left->squared_distance(V,Ele,p,sqr_d,i_left,c_left);
  573. set_min(p,sqr_d_left,i_left,c_left,sqr_d,i,c);
  574. looked_left = true;
  575. };
  576. const auto & look_right = [&]()
  577. {
  578. int i_right;
  579. RowVectorDIMS c_right;
  580. Scalar sqr_d_right = m_right->squared_distance(V,Ele,p,sqr_d,i_right,c_right);
  581. set_min(p,sqr_d_right,i_right,c_right,sqr_d,i,c);
  582. looked_right = true;
  583. };
  584. // must look left or right if in box
  585. if(m_left->m_box.contains(p.transpose()))
  586. {
  587. look_left();
  588. }
  589. if(m_right->m_box.contains(p.transpose()))
  590. {
  591. look_right();
  592. }
  593. // if haven't looked left and could be less than current min, then look
  594. Scalar left_min_sqr_d = m_left->m_box.squaredExteriorDistance(p.transpose());
  595. Scalar right_min_sqr_d = m_right->m_box.squaredExteriorDistance(p.transpose());
  596. if(left_min_sqr_d < right_min_sqr_d)
  597. {
  598. if(!looked_left && left_min_sqr_d<sqr_d)
  599. {
  600. look_left();
  601. }
  602. if( !looked_right && right_min_sqr_d<sqr_d)
  603. {
  604. look_right();
  605. }
  606. }else
  607. {
  608. if( !looked_right && right_min_sqr_d<sqr_d)
  609. {
  610. look_right();
  611. }
  612. if(!looked_left && left_min_sqr_d<sqr_d)
  613. {
  614. look_left();
  615. }
  616. }
  617. }
  618. return sqr_d;
  619. }
  620. template <typename DerivedV, int DIM>
  621. template <
  622. typename DerivedP,
  623. typename DerivedsqrD,
  624. typename DerivedI,
  625. typename DerivedC>
  626. inline void igl::AABB<DerivedV,DIM>::squared_distance(
  627. const Eigen::PlainObjectBase<DerivedV> & V,
  628. const Eigen::MatrixXi & Ele,
  629. const Eigen::PlainObjectBase<DerivedP> & P,
  630. Eigen::PlainObjectBase<DerivedsqrD> & sqrD,
  631. Eigen::PlainObjectBase<DerivedI> & I,
  632. Eigen::PlainObjectBase<DerivedC> & C) const
  633. {
  634. assert(P.cols() == V.cols() && "cols in P should match dim of cols in V");
  635. sqrD.resize(P.rows(),1);
  636. I.resize(P.rows(),1);
  637. C.resize(P.rows(),P.cols());
  638. for(int p = 0;p<P.rows();p++)
  639. {
  640. RowVectorDIMS Pp = P.row(p), c;
  641. int Ip;
  642. sqrD(p) = squared_distance(V,Ele,Pp,Ip,c);
  643. I(p) = Ip;
  644. C.row(p) = c;
  645. }
  646. }
  647. template <typename DerivedV, int DIM>
  648. inline void igl::AABB<DerivedV,DIM>::leaf_squared_distance(
  649. const Eigen::PlainObjectBase<DerivedV> & V,
  650. const Eigen::MatrixXi & Ele,
  651. const RowVectorDIMS & p,
  652. Scalar & sqr_d,
  653. int & i,
  654. RowVectorDIMS & c) const
  655. {
  656. using namespace Eigen;
  657. using namespace igl;
  658. using namespace std;
  659. // Simplex size
  660. const size_t ss = Ele.cols();
  661. // Only one element per node
  662. // plane unit normal
  663. bool inside_triangle = false;
  664. Scalar d_j = std::numeric_limits<Scalar>::infinity();
  665. RowVectorDIMS pp;
  666. // Only consider triangles, and non-degenerate triangles at that
  667. if(ss == 3 &&
  668. Ele(m_primitive,0) != Ele(m_primitive,1) &&
  669. Ele(m_primitive,1) != Ele(m_primitive,2) &&
  670. Ele(m_primitive,2) != Ele(m_primitive,0))
  671. {
  672. const RowVectorDIMS v10 = (V.row(Ele(m_primitive,1))- V.row(Ele(m_primitive,0)));
  673. const RowVectorDIMS v20 = (V.row(Ele(m_primitive,2))- V.row(Ele(m_primitive,0)));
  674. const RowVectorDIMS n = v10.cross(v20);
  675. Scalar n_norm = n.norm();
  676. if(n_norm > 0)
  677. {
  678. const RowVectorDIMS un = n/n.norm();
  679. // vector to plane
  680. const RowVectorDIMS bc =
  681. 1./3.*
  682. ( V.row(Ele(m_primitive,0))+
  683. V.row(Ele(m_primitive,1))+
  684. V.row(Ele(m_primitive,2)));
  685. const auto & v = p-bc;
  686. // projected point on plane
  687. d_j = v.dot(un);
  688. pp = p - d_j*un;
  689. // determine if pp is inside triangle
  690. Eigen::Matrix<Scalar,1,3> b;
  691. barycentric_coordinates(
  692. pp,
  693. V.row(Ele(m_primitive,0)),
  694. V.row(Ele(m_primitive,1)),
  695. V.row(Ele(m_primitive,2)),
  696. b);
  697. inside_triangle = fabs(fabs(b(0)) + fabs(b(1)) + fabs(b(2)) - 1.) <= 1e-10;
  698. }
  699. }
  700. const auto & point_point_squared_distance = [&](const RowVectorDIMS & s)
  701. {
  702. const Scalar sqr_d_s = (p-s).squaredNorm();
  703. set_min(p,sqr_d_s,m_primitive,s,sqr_d,i,c);
  704. };
  705. if(inside_triangle)
  706. {
  707. // point-triangle squared distance
  708. const Scalar sqr_d_j = d_j*d_j;
  709. //cout<<"point-triangle..."<<endl;
  710. set_min(p,sqr_d_j,m_primitive,pp,sqr_d,i,c);
  711. }else
  712. {
  713. if(ss >= 2)
  714. {
  715. // point-segment distance
  716. // number of edges
  717. size_t ne = ss==3?3:1;
  718. for(size_t x = 0;x<ne;x++)
  719. {
  720. const size_t e1 = Ele(m_primitive,(x+1)%ss);
  721. const size_t e2 = Ele(m_primitive,(x+2)%ss);
  722. const RowVectorDIMS & s = V.row(e1);
  723. const RowVectorDIMS & d = V.row(e2);
  724. // Degenerate edge
  725. if(e1 == e2 || (s-d).squaredNorm()==0)
  726. {
  727. // only consider once
  728. if(e1 < e2)
  729. {
  730. point_point_squared_distance(s);
  731. }
  732. continue;
  733. }
  734. Matrix<Scalar,1,1> sqr_d_j_x(1,1);
  735. Matrix<Scalar,1,1> t(1,1);
  736. project_to_line_segment(p,s,d,t,sqr_d_j_x);
  737. const RowVectorDIMS q = s+t(0)*(d-s);
  738. set_min(p,sqr_d_j_x(0),m_primitive,q,sqr_d,i,c);
  739. }
  740. }else
  741. {
  742. // So then Ele is just a list of points...
  743. assert(ss == 1);
  744. const RowVectorDIMS & s = V.row(Ele(m_primitive,0));
  745. point_point_squared_distance(s);
  746. }
  747. }
  748. }
  749. template <typename DerivedV, int DIM>
  750. inline void igl::AABB<DerivedV,DIM>::set_min(
  751. const RowVectorDIMS & p,
  752. const Scalar sqr_d_candidate,
  753. const int i_candidate,
  754. const RowVectorDIMS & c_candidate,
  755. Scalar & sqr_d,
  756. int & i,
  757. RowVectorDIMS & c) const
  758. {
  759. #ifndef NDEBUG
  760. const Scalar diff = fabs(sqr_d_candidate - (p-c_candidate).squaredNorm());
  761. assert(diff<=1e-10 && "distance should match norm of difference");
  762. #endif
  763. if(sqr_d_candidate < sqr_d)
  764. {
  765. i = i_candidate;
  766. c = c_candidate;
  767. sqr_d = sqr_d_candidate;
  768. }
  769. }
  770. template <typename DerivedV, int DIM>
  771. template <int SS>
  772. inline void
  773. igl::AABB<DerivedV,DIM>::barycentric_coordinates(
  774. const RowVectorDIMS & p,
  775. const RowVectorDIMS & a,
  776. const RowVectorDIMS & b,
  777. const RowVectorDIMS & c,
  778. Eigen::Matrix<Scalar,1,SS> & bary)
  779. {
  780. assert(SS==3);
  781. // http://gamedev.stackexchange.com/a/23745
  782. const RowVectorDIMS v0 = b - a;
  783. const RowVectorDIMS v1 = c - a;
  784. const RowVectorDIMS v2 = p - a;
  785. Scalar d00 = v0.dot(v0);
  786. Scalar d01 = v0.dot(v1);
  787. Scalar d11 = v1.dot(v1);
  788. Scalar d20 = v2.dot(v0);
  789. Scalar d21 = v2.dot(v1);
  790. Scalar denom = d00 * d11 - d01 * d01;
  791. bary(1) = (d11 * d20 - d01 * d21) / denom;
  792. bary(2) = (d00 * d21 - d01 * d20) / denom;
  793. bary(0) = 1.0f - bary(1) - bary(2);
  794. };
  795. #endif