AABB.h 22 KB

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