SelfIntersectMesh.h 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2014 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_SELFINTERSECTMESH_H
  9. #define IGL_SELFINTERSECTMESH_H
  10. #include "CGAL_includes.hpp"
  11. #include "selfintersect.h"
  12. #include <Eigen/Dense>
  13. #include <list>
  14. #include <map>
  15. #include <vector>
  16. #ifndef IGL_FIRST_HIT_EXCEPTION
  17. #define IGL_FIRST_HIT_EXCEPTION 10
  18. #endif
  19. // The easiest way to keep track of everything is to use a class
  20. namespace igl
  21. {
  22. // Kernel is a CGAL kernel like:
  23. // CGAL::Exact_predicates_inexact_constructions_kernel
  24. // or
  25. // CGAL::Exact_predicates_exact_constructions_kernel
  26. template <typename Kernel>
  27. class SelfIntersectMesh
  28. {
  29. public:
  30. // 3D Primitives
  31. typedef CGAL::Point_3<Kernel> Point_3;
  32. typedef CGAL::Segment_3<Kernel> Segment_3;
  33. typedef CGAL::Triangle_3<Kernel> Triangle_3;
  34. typedef CGAL::Plane_3<Kernel> Plane_3;
  35. typedef CGAL::Tetrahedron_3<Kernel> Tetrahedron_3;
  36. typedef CGAL::Polyhedron_3<Kernel> Polyhedron_3;
  37. typedef CGAL::Nef_polyhedron_3<Kernel> Nef_polyhedron_3;
  38. // 2D Primitives
  39. typedef CGAL::Point_2<Kernel> Point_2;
  40. typedef CGAL::Segment_2<Kernel> Segment_2;
  41. typedef CGAL::Triangle_2<Kernel> Triangle_2;
  42. // 2D Constrained Delaunay Triangulation types
  43. typedef CGAL::Triangulation_vertex_base_2<Kernel> TVB_2;
  44. typedef CGAL::Constrained_triangulation_face_base_2<Kernel> CTFB_2;
  45. typedef CGAL::Triangulation_data_structure_2<TVB_2,CTFB_2> TDS_2;
  46. typedef CGAL::Exact_intersections_tag Itag;
  47. typedef CGAL::Constrained_Delaunay_triangulation_2<Kernel,TDS_2,Itag>
  48. CDT_2;
  49. typedef CGAL::Constrained_triangulation_plus_2<CDT_2> CDT_plus_2;
  50. // Axis-align boxes for all-pairs self-intersection detection
  51. typedef std::vector<Triangle_3> Triangles;
  52. typedef typename Triangles::iterator TrianglesIterator;
  53. typedef typename Triangles::const_iterator TrianglesConstIterator;
  54. typedef
  55. CGAL::Box_intersection_d::Box_with_handle_d<double,3,TrianglesIterator>
  56. Box;
  57. // Input mesh
  58. const Eigen::MatrixXd & V;
  59. const Eigen::MatrixXi & F;
  60. // Number of self-intersecting triangle pairs
  61. int count;
  62. std::vector<std::list<CGAL::Object> > F_objects;
  63. Triangles T;
  64. std::list<int> lIF;
  65. std::vector<bool> offensive;
  66. std::vector<int> offending_index;
  67. std::vector<int> offending;
  68. // Make a short name for the edge map's key
  69. typedef std::pair<int,int> EMK;
  70. // Make a short name for the type stored at each edge, the edge map's
  71. // value
  72. typedef std::list<int> EMV;
  73. // Make a short name for the edge map
  74. typedef std::map<EMK,EMV> EdgeMap;
  75. EdgeMap edge2faces;
  76. public:
  77. SelfintersectParam params;
  78. public:
  79. // Constructs (VV,FF) a new mesh with self-intersections of (V,F)
  80. // subdivided
  81. inline SelfIntersectMesh(
  82. const Eigen::MatrixXd & V,
  83. const Eigen::MatrixXi & F,
  84. const SelfintersectParam & params,
  85. Eigen::MatrixXd & VV,
  86. Eigen::MatrixXi & FF,
  87. Eigen::MatrixXi & IF,
  88. Eigen::VectorXi & J);
  89. private:
  90. // Helper function to mark a face as offensive
  91. //
  92. // Inputs:
  93. // f index of face in F
  94. inline void mark_offensive(const int f);
  95. // Helper function to count intersections between faces
  96. //
  97. // Input:
  98. // fa index of face A in F
  99. // fb index of face B in F
  100. inline void count_intersection(const int fa,const int fb);
  101. // Helper function for box_intersect. Intersect two triangles A and B,
  102. // append the intersection object (point,segment,triangle) to a running
  103. // list for A and B
  104. //
  105. // Inputs:
  106. // A triangle in 3D
  107. // B triangle in 3D
  108. // fa index of A in F (and F_objects)
  109. // fb index of A in F (and F_objects)
  110. // Returns true only if A intersects B
  111. //
  112. inline bool intersect(
  113. const Triangle_3 & A,
  114. const Triangle_3 & B,
  115. const int fa,
  116. const int fb);
  117. // Helper function for box_intersect. In the case where A and B have
  118. // already been identified to share a vertex, then we only want to add
  119. // possible segment intersections. Assumes truly duplicate triangles are
  120. // not given as input
  121. //
  122. // Inputs:
  123. // A triangle in 3D
  124. // B triangle in 3D
  125. // fa index of A in F (and F_objects)
  126. // fb index of B in F (and F_objects)
  127. // va index of shared vertex in A (and F_objects)
  128. // vb index of shared vertex in B (and F_objects)
  129. //// Returns object of intersection (should be Segment or point)
  130. // Returns true if intersection (besides shared point)
  131. //
  132. inline bool single_shared_vertex(
  133. const Triangle_3 & A,
  134. const Triangle_3 & B,
  135. const int fa,
  136. const int fb,
  137. const int va,
  138. const int vb);
  139. // Helper handling one direction
  140. inline bool single_shared_vertex(
  141. const Triangle_3 & A,
  142. const Triangle_3 & B,
  143. const int fa,
  144. const int fb,
  145. const int va);
  146. // Helper function for box_intersect. In the case where A and B have
  147. // already been identified to share two vertices, then we only want to add
  148. // a possible coplanar (Triangle) intersection. Assumes truly degenerate
  149. // facets are not givine as input.
  150. inline bool double_shared_vertex(
  151. const Triangle_3 & A,
  152. const Triangle_3 & B,
  153. const int fa,
  154. const int fb);
  155. public:
  156. // Callback function called during box self intersections test. Means
  157. // boxes a and b intersect. This method then checks if the triangles in
  158. // each box intersect and if so, then processes the intersections
  159. //
  160. // Inputs:
  161. // a box containing a triangle
  162. // b box containing a triangle
  163. inline void box_intersect(const Box& a, const Box& b);
  164. private:
  165. // Compute 2D delaunay triangulation of a given 3d triangle and a list of
  166. // intersection objects (points,segments,triangles). CGAL uses an affine
  167. // projection rather than an isometric projection, so we're not
  168. // guaranteed that the 2D delaunay triangulation here will be a delaunay
  169. // triangulation in 3D.
  170. //
  171. // Inputs:
  172. // A triangle in 3D
  173. // A_objects_3 updated list of intersection objects for A
  174. // Outputs:
  175. // cdt Contrained delaunay triangulation in projected 2D plane
  176. inline void projected_delaunay(
  177. const Triangle_3 & A,
  178. const std::list<CGAL::Object> & A_objects_3,
  179. CDT_plus_2 & cdt);
  180. // Getters:
  181. public:
  182. //const std::list<int>& get_lIF() const{ return lIF;}
  183. static inline void box_intersect(
  184. SelfIntersectMesh * SIM,
  185. const SelfIntersectMesh::Box &a,
  186. const SelfIntersectMesh::Box &b);
  187. };
  188. }
  189. // Implementation
  190. #include "mesh_to_cgal_triangle_list.h"
  191. #include <igl/REDRUM.h>
  192. #include <igl/C_STR.h>
  193. #include <boost/function.hpp>
  194. #include <boost/bind.hpp>
  195. #include <algorithm>
  196. #include <exception>
  197. #include <cassert>
  198. #include <iostream>
  199. // References:
  200. // http://minregret.googlecode.com/svn/trunk/skyline/src/extern/CGAL-3.3.1/examples/Polyhedron/polyhedron_self_intersection.cpp
  201. // http://www.cgal.org/Manual/3.9/examples/Boolean_set_operations_2/do_intersect.cpp
  202. // Q: Should we be using CGAL::Polyhedron_3?
  203. // A: No! Input is just a list of unoriented triangles. Polyhedron_3 requires
  204. // a 2-manifold.
  205. // A: But! It seems we could use CGAL::Triangulation_3. Though it won't be easy
  206. // to take advantage of functions like insert_in_facet because we want to
  207. // constrain segments. Hmmm. Actualy Triangulation_3 doesn't look right...
  208. //static void box_intersect(SelfIntersectMesh * SIM,const Box & A, const Box & B)
  209. //{
  210. // return SIM->box_intersect(A,B);
  211. //}
  212. // CGAL's box_self_intersection_d uses C-style function callbacks without
  213. // userdata. This is a leapfrog method for calling a member function. It should
  214. // be bound as if the prototype was:
  215. // static void box_intersect(const Box &a, const Box &b)
  216. // using boost:
  217. // boost::function<void(const Box &a,const Box &b)> cb
  218. // = boost::bind(&::box_intersect, this, _1,_2);
  219. //
  220. template <typename Kernel>
  221. inline void igl::SelfIntersectMesh<Kernel>::box_intersect(
  222. igl::SelfIntersectMesh<Kernel> * SIM,
  223. const typename igl::SelfIntersectMesh<Kernel>::Box &a,
  224. const typename igl::SelfIntersectMesh<Kernel>::Box &b)
  225. {
  226. SIM->box_intersect(a,b);
  227. }
  228. template <typename Kernel>
  229. inline igl::SelfIntersectMesh<Kernel>::SelfIntersectMesh(
  230. const Eigen::MatrixXd & V,
  231. const Eigen::MatrixXi & F,
  232. const SelfintersectParam & params,
  233. Eigen::MatrixXd & VV,
  234. Eigen::MatrixXi & FF,
  235. Eigen::MatrixXi & IF,
  236. Eigen::VectorXi & J):
  237. V(V),
  238. F(F),
  239. count(0),
  240. F_objects(F.rows()),
  241. T(),
  242. lIF(),
  243. offensive(F.rows(),false),
  244. offending_index(F.rows(),-1),
  245. offending(),
  246. edge2faces(),
  247. params(params)
  248. {
  249. using namespace std;
  250. using namespace Eigen;
  251. // Compute and process self intersections
  252. mesh_to_cgal_triangle_list(V,F,T);
  253. // http://www.cgal.org/Manual/latest/doc_html/cgal_manual/Box_intersection_d/Chapter_main.html#Section_63.5
  254. // Create the corresponding vector of bounding boxes
  255. std::vector<Box> boxes;
  256. boxes.reserve(T.size());
  257. for (
  258. TrianglesIterator tit = T.begin();
  259. tit != T.end();
  260. ++tit)
  261. {
  262. boxes.push_back(Box(tit->bbox(), tit));
  263. }
  264. // Leapfrog callback
  265. boost::function<void(const Box &a,const Box &b)> cb
  266. = boost::bind(&box_intersect, this, _1,_2);
  267. // Run the self intersection algorithm with all defaults
  268. try{
  269. CGAL::box_self_intersection_d(boxes.begin(), boxes.end(),cb);
  270. }catch(int e)
  271. {
  272. // Rethrow if not IGL_FIRST_HIT_EXCEPTION
  273. if(e != IGL_FIRST_HIT_EXCEPTION)
  274. {
  275. throw e;
  276. }
  277. // Otherwise just fall through
  278. }
  279. // Convert lIF to Eigen matrix
  280. assert(lIF.size()%2 == 0);
  281. IF.resize(lIF.size()/2,2);
  282. {
  283. int i=0;
  284. for(
  285. typename list<int>::const_iterator ifit = lIF.begin();
  286. ifit!=lIF.end();
  287. )
  288. {
  289. IF(i,0) = (*ifit);
  290. ifit++;
  291. IF(i,1) = (*ifit);
  292. ifit++;
  293. i++;
  294. }
  295. }
  296. if(params.detect_only)
  297. {
  298. return;
  299. }
  300. int NF_count = 0;
  301. // list of new faces, we'll fix F later
  302. vector<MatrixXi> NF(offending.size());
  303. // list of new vertices
  304. list<Point_3> NV;
  305. int NV_count = 0;
  306. vector<CDT_plus_2> cdt(offending.size());
  307. vector<Plane_3> P(offending.size());
  308. // Use map for *all* faces
  309. map<typename CDT_plus_2::Vertex_handle,int> v2i;
  310. // Loop over offending triangles
  311. for(int o = 0;o<(int)offending.size();o++)
  312. {
  313. // index in F
  314. const int f = offending[o];
  315. projected_delaunay(T[f],F_objects[f],cdt[o]);
  316. // Q: Is this also delaunay in 3D?
  317. // A: No, because the projection is affine and delaunay is not affine
  318. // invariant.
  319. // Q: Then, can't we first get the 2D delaunay triangulation, then lift it
  320. // to 3D and flip any offending edges?
  321. // Plane of projection (also used by projected_delaunay)
  322. P[o] = Plane_3(T[f].vertex(0),T[f].vertex(1),T[f].vertex(2));
  323. // Build index map
  324. {
  325. int i=0;
  326. for(
  327. typename CDT_plus_2::Finite_vertices_iterator vit = cdt[o].finite_vertices_begin();
  328. vit != cdt[o].finite_vertices_end();
  329. ++vit)
  330. {
  331. if(i<3)
  332. {
  333. //cout<<T[f].vertex(i)<<
  334. // (T[f].vertex(i) == P[o].to_3d(vit->point())?" == ":" != ")<<
  335. // P[o].to_3d(vit->point())<<endl;
  336. #ifndef NDEBUG
  337. // I want to be sure that the original corners really show up as the
  338. // original corners of the CDT. I.e. I don't trust CGAL to maintain the
  339. // order
  340. assert(T[f].vertex(i) == P[o].to_3d(vit->point()));
  341. #endif
  342. // For first three, use original index in F
  343. v2i[vit] = F(f,i);
  344. }else
  345. {
  346. const Point_3 vit_point_3 = P[o].to_3d(vit->point());
  347. // First look up each edge's neighbors to see if exact point has
  348. // already been added (This makes everything a bit quadratic)
  349. bool found = false;
  350. for(int e = 0; e<3 && !found;e++)
  351. {
  352. // Index of F's eth edge in V
  353. int i = F(f,(e+1)%3);
  354. int j = F(f,(e+2)%3);
  355. // Be sure that i<j
  356. if(i>j)
  357. {
  358. swap(i,j);
  359. }
  360. assert(edge2faces.count(EMK(i,j))==1);
  361. // loop over neighbors
  362. for(
  363. list<int>::const_iterator nit = edge2faces[EMK(i,j)].begin();
  364. nit != edge2faces[EMK(i,j)].end() && !found;
  365. nit++)
  366. {
  367. // don't consider self
  368. if(*nit == f)
  369. {
  370. continue;
  371. }
  372. // index of neighbor in offending (to find its cdt)
  373. int no = offending_index[*nit];
  374. // Loop over vertices of that neighbor's cdt (might not have been
  375. // processed yet, but then it's OK because it'll just be empty)
  376. for(
  377. typename CDT_plus_2::Finite_vertices_iterator uit = cdt[no].finite_vertices_begin();
  378. uit != cdt[no].finite_vertices_end() && !found;
  379. ++uit)
  380. {
  381. if(vit_point_3 == P[no].to_3d(uit->point()))
  382. {
  383. assert(v2i.count(uit) == 1);
  384. v2i[vit] = v2i[uit];
  385. found = true;
  386. }
  387. }
  388. }
  389. }
  390. if(!found)
  391. {
  392. v2i[vit] = V.rows()+NV_count;
  393. NV.push_back(vit_point_3);
  394. NV_count++;
  395. }
  396. }
  397. i++;
  398. }
  399. }
  400. {
  401. int i = 0;
  402. // Resize to fit new number of triangles
  403. NF[o].resize(cdt[o].number_of_faces(),3);
  404. NF_count+=NF[o].rows();
  405. // Append new faces to NF
  406. for(
  407. typename CDT_plus_2::Finite_faces_iterator fit = cdt[o].finite_faces_begin();
  408. fit != cdt[o].finite_faces_end();
  409. ++fit)
  410. {
  411. NF[o](i,0) = v2i[fit->vertex(0)];
  412. NF[o](i,1) = v2i[fit->vertex(1)];
  413. NF[o](i,2) = v2i[fit->vertex(2)];
  414. i++;
  415. }
  416. }
  417. }
  418. assert(NV_count == (int)NV.size());
  419. // Build output
  420. #ifndef NDEBUG
  421. {
  422. int off_count = 0;
  423. for(int f = 0;f<F.rows();f++)
  424. {
  425. off_count+= (offensive[f]?1:0);
  426. }
  427. assert(off_count==(int)offending.size());
  428. }
  429. #endif
  430. // Append faces
  431. FF.resize(F.rows()-offending.size()+NF_count,3);
  432. J.resize(FF.rows());
  433. // First append non-offending original faces
  434. // There's an Eigen way to do this in one line but I forget
  435. int off = 0;
  436. for(int f = 0;f<F.rows();f++)
  437. {
  438. if(!offensive[f])
  439. {
  440. FF.row(off) = F.row(f);
  441. J(off) = f;
  442. off++;
  443. }
  444. }
  445. assert(off == (int)(F.rows()-offending.size()));
  446. // Now append replacement faces for offending faces
  447. for(int o = 0;o<(int)offending.size();o++)
  448. {
  449. FF.block(off,0,NF[o].rows(),3) = NF[o];
  450. J.block(off,0,NF[o].rows(),1).setConstant(offending[o]);
  451. off += NF[o].rows();
  452. }
  453. // Append vertices
  454. VV.resize(V.rows()+NV_count,3);
  455. VV.block(0,0,V.rows(),3) = V;
  456. {
  457. int i = 0;
  458. for(
  459. typename list<Point_3>::const_iterator nvit = NV.begin();
  460. nvit != NV.end();
  461. nvit++)
  462. {
  463. for(int d = 0;d<3;d++)
  464. {
  465. const Point_3 & p = *nvit;
  466. VV(V.rows()+i,d) = CGAL::to_double(p[d]);
  467. // This distinction does not seem necessary:
  468. //#ifdef INEXACT_CONSTRUCTION
  469. // VV(V.rows()+i,d) = CGAL::to_double(p[d]);
  470. //#else
  471. // VV(V.rows()+i,d) = CGAL::to_double(p[d].exact());
  472. //#endif
  473. }
  474. i++;
  475. }
  476. }
  477. // Q: Does this give the same result as TETGEN?
  478. // A: For the cow and beast, yes.
  479. // Q: Is tetgen faster than this CGAL implementation?
  480. // A: Well, yes. But Tetgen is only solving the detection (predicates)
  481. // problem. This is also appending the intersection objects (construction).
  482. // But maybe tetgen is still faster for the detection part. For example, this
  483. // CGAL implementation on the beast takes 98 seconds but tetgen detection
  484. // takes 14 seconds
  485. }
  486. template <typename Kernel>
  487. inline void igl::SelfIntersectMesh<Kernel>::mark_offensive(const int f)
  488. {
  489. using namespace std;
  490. lIF.push_back(f);
  491. if(!offensive[f])
  492. {
  493. offensive[f]=true;
  494. offending_index[f]=offending.size();
  495. offending.push_back(f);
  496. // Add to edge map
  497. for(int e = 0; e<3;e++)
  498. {
  499. // Index of F's eth edge in V
  500. int i = F(f,(e+1)%3);
  501. int j = F(f,(e+2)%3);
  502. // Be sure that i<j
  503. if(i>j)
  504. {
  505. swap(i,j);
  506. }
  507. // Create new list if there is no entry
  508. if(edge2faces.count(EMK(i,j))==0)
  509. {
  510. edge2faces[EMK(i,j)] = list<int>();
  511. }
  512. // append to list
  513. edge2faces[EMK(i,j)].push_back(f);
  514. }
  515. }
  516. }
  517. template <typename Kernel>
  518. inline void igl::SelfIntersectMesh<Kernel>::count_intersection(
  519. const int fa,
  520. const int fb)
  521. {
  522. mark_offensive(fa);
  523. mark_offensive(fb);
  524. this->count++;
  525. // We found the first intersection
  526. if(params.first_only && this->count >= 1)
  527. {
  528. throw IGL_FIRST_HIT_EXCEPTION;
  529. }
  530. }
  531. template <typename Kernel>
  532. inline bool igl::SelfIntersectMesh<Kernel>::intersect(
  533. const Triangle_3 & A,
  534. const Triangle_3 & B,
  535. const int fa,
  536. const int fb)
  537. {
  538. // Determine whether there is an intersection
  539. if(!CGAL::do_intersect(A,B))
  540. {
  541. return false;
  542. }
  543. if(!params.detect_only)
  544. {
  545. // Construct intersection
  546. CGAL::Object result = CGAL::intersection(A,B);
  547. F_objects[fa].push_back(result);
  548. F_objects[fb].push_back(result);
  549. }
  550. count_intersection(fa,fb);
  551. return true;
  552. }
  553. template <typename Kernel>
  554. inline bool igl::SelfIntersectMesh<Kernel>::single_shared_vertex(
  555. const Triangle_3 & A,
  556. const Triangle_3 & B,
  557. const int fa,
  558. const int fb,
  559. const int va,
  560. const int vb)
  561. {
  562. ////using namespace std;
  563. //CGAL::Object result = CGAL::intersection(A,B);
  564. //if(CGAL::object_cast<Segment_3 >(&result))
  565. //{
  566. // // Append to each triangle's running list
  567. // F_objects[fa].push_back(result);
  568. // F_objects[fb].push_back(result);
  569. // count_intersection(fa,fb);
  570. //}else
  571. //{
  572. // // Then intersection must be at point
  573. // // And point must be at shared vertex
  574. // assert(CGAL::object_cast<Point_3>(&result));
  575. //}
  576. if(single_shared_vertex(A,B,fa,fb,va))
  577. {
  578. return true;
  579. }
  580. return single_shared_vertex(B,A,fb,fa,vb);
  581. }
  582. template <typename Kernel>
  583. inline bool igl::SelfIntersectMesh<Kernel>::single_shared_vertex(
  584. const Triangle_3 & A,
  585. const Triangle_3 & B,
  586. const int fa,
  587. const int fb,
  588. const int va)
  589. {
  590. // This was not a good idea. It will not handle coplanar triangles well.
  591. using namespace std;
  592. Segment_3 sa(
  593. A.vertex((va+1)%3),
  594. A.vertex((va+2)%3));
  595. if(CGAL::do_intersect(sa,B))
  596. {
  597. CGAL::Object result = CGAL::intersection(sa,B);
  598. if(const Point_3 * p = CGAL::object_cast<Point_3 >(&result))
  599. {
  600. if(!params.detect_only)
  601. {
  602. // Single intersection --> segment from shared point to intersection
  603. CGAL::Object seg = CGAL::make_object(Segment_3(
  604. A.vertex(va),
  605. *p));
  606. F_objects[fa].push_back(seg);
  607. F_objects[fb].push_back(seg);
  608. }
  609. count_intersection(fa,fb);
  610. return true;
  611. }else if(CGAL::object_cast<Segment_3 >(&result))
  612. {
  613. //cerr<<REDRUM("Coplanar at: "<<fa<<" & "<<fb<<" (single shared).")<<endl;
  614. // Must be coplanar
  615. if(params.detect_only)
  616. {
  617. count_intersection(fa,fb);
  618. }else
  619. {
  620. // WRONG:
  621. //// Segment intersection --> triangle from shared point to intersection
  622. //CGAL::Object tri = CGAL::make_object(Triangle_3(
  623. // A.vertex(va),
  624. // s->vertex(0),
  625. // s->vertex(1)));
  626. //F_objects[fa].push_back(tri);
  627. //F_objects[fb].push_back(tri);
  628. //count_intersection(fa,fb);
  629. // Need to do full test. Intersection could be a general poly.
  630. bool test = intersect(A,B,fa,fb);
  631. ((void)test);
  632. assert(test);
  633. }
  634. return true;
  635. }else
  636. {
  637. cerr<<REDRUM("Segment ∩ triangle neither point nor segment?")<<endl;
  638. assert(false);
  639. }
  640. }
  641. return false;
  642. }
  643. template <typename Kernel>
  644. inline bool igl::SelfIntersectMesh<Kernel>::double_shared_vertex(
  645. const Triangle_3 & A,
  646. const Triangle_3 & B,
  647. const int fa,
  648. const int fb)
  649. {
  650. using namespace std;
  651. // Cheaper way to do this than calling do_intersect?
  652. if(
  653. // Can only have an intersection if co-planar
  654. (A.supporting_plane() == B.supporting_plane() ||
  655. A.supporting_plane() == B.supporting_plane().opposite()) &&
  656. CGAL::do_intersect(A,B))
  657. {
  658. // Construct intersection
  659. try
  660. {
  661. CGAL::Object result = CGAL::intersection(A,B);
  662. if(result)
  663. {
  664. if(CGAL::object_cast<Segment_3 >(&result))
  665. {
  666. // not coplanar
  667. return false;
  668. } else if(CGAL::object_cast<Point_3 >(&result))
  669. {
  670. // this "shouldn't" happen but does for inexact
  671. return false;
  672. } else
  673. {
  674. if(!params.detect_only)
  675. {
  676. // Triangle object
  677. F_objects[fa].push_back(result);
  678. F_objects[fb].push_back(result);
  679. }
  680. count_intersection(fa,fb);
  681. //cerr<<REDRUM("Coplanar at: "<<fa<<" & "<<fb<<" (double shared).")<<endl;
  682. return true;
  683. }
  684. }else
  685. {
  686. // CGAL::intersection is disagreeing with do_intersect
  687. return false;
  688. }
  689. }catch(...)
  690. {
  691. // This catches some cgal assertion:
  692. // CGAL error: assertion violation!
  693. // Expression : is_finite(d)
  694. // File : /opt/local/include/CGAL/GMP/Gmpq_type.h
  695. // Line : 132
  696. // Explanation:
  697. // But only if NDEBUG is not defined, otherwise there's an uncaught
  698. // "Floating point exception: 8" SIGFPE
  699. return false;
  700. }
  701. }
  702. // Shouldn't get here either
  703. assert(false);
  704. return false;
  705. }
  706. template <typename Kernel>
  707. inline void igl::SelfIntersectMesh<Kernel>::box_intersect(
  708. const Box& a,
  709. const Box& b)
  710. {
  711. using namespace std;
  712. // index in F and T
  713. int fa = a.handle()-T.begin();
  714. int fb = b.handle()-T.begin();
  715. const Triangle_3 & A = *a.handle();
  716. const Triangle_3 & B = *b.handle();
  717. // I'm not going to deal with degenerate triangles, though at some point we
  718. // should
  719. assert(!a.handle()->is_degenerate());
  720. assert(!b.handle()->is_degenerate());
  721. // Number of combinatorially shared vertices
  722. int comb_shared_vertices = 0;
  723. // Number of geometrically shared vertices (*not* including combinatorially
  724. // shared)
  725. int geo_shared_vertices = 0;
  726. // Keep track of shared vertex indices (we only handles single shared
  727. // vertices as a special case, so just need last/first/only ones)
  728. int va=-1,vb=-1;
  729. int ea,eb;
  730. for(ea=0;ea<3;ea++)
  731. {
  732. for(eb=0;eb<3;eb++)
  733. {
  734. if(F(fa,ea) == F(fb,eb))
  735. {
  736. comb_shared_vertices++;
  737. va = ea;
  738. vb = eb;
  739. }else if(A.vertex(ea) == B.vertex(eb))
  740. {
  741. geo_shared_vertices++;
  742. va = ea;
  743. vb = eb;
  744. }
  745. }
  746. }
  747. const int total_shared_vertices = comb_shared_vertices + geo_shared_vertices;
  748. if(comb_shared_vertices== 3)
  749. {
  750. // Combinatorially duplicate face, these should be removed by preprocessing
  751. cerr<<REDRUM("Facets "<<fa<<" and "<<fb<<" are combinatorial duplicates")<<endl;
  752. goto done;
  753. }
  754. if(total_shared_vertices== 3)
  755. {
  756. // Geometrically duplicate face, these should be removed by preprocessing
  757. cerr<<REDRUM("Facets "<<fa<<" and "<<fb<<" are geometrical duplicates")<<endl;
  758. goto done;
  759. }
  760. //// SPECIAL CASES ARE BROKEN FOR COPLANAR TRIANGLES
  761. //if(total_shared_vertices > 0)
  762. //{
  763. // bool coplanar =
  764. // CGAL::coplanar(A.vertex(0),A.vertex(1),A.vertex(2),B.vertex(0)) &&
  765. // CGAL::coplanar(A.vertex(0),A.vertex(1),A.vertex(2),B.vertex(1)) &&
  766. // CGAL::coplanar(A.vertex(0),A.vertex(1),A.vertex(2),B.vertex(2));
  767. // if(coplanar)
  768. // {
  769. // cerr<<MAGENTAGIN("Facets "<<fa<<" and "<<fb<<
  770. // " are coplanar and share vertices")<<endl;
  771. // goto full;
  772. // }
  773. //}
  774. if(total_shared_vertices == 2)
  775. {
  776. // Q: What about coplanar?
  777. //
  778. // o o
  779. // |\ /|
  780. // | \/ |
  781. // | /\ |
  782. // |/ \|
  783. // o----o
  784. double_shared_vertex(A,B,fa,fb);
  785. goto done;
  786. }
  787. assert(total_shared_vertices<=1);
  788. if(total_shared_vertices==1)
  789. {
  790. assert(va>=0 && va<3);
  791. assert(vb>=0 && vb<3);
  792. //#ifndef NDEBUG
  793. // CGAL::Object result =
  794. //#endif
  795. single_shared_vertex(A,B,fa,fb,va,vb);
  796. //#ifndef NDEBUG
  797. // if(!CGAL::object_cast<Segment_3 >(&result))
  798. // {
  799. // const Point_3 * p = CGAL::object_cast<Point_3 >(&result);
  800. // assert(p);
  801. // for(int ea=0;ea<3;ea++)
  802. // {
  803. // for(int eb=0;eb<3;eb++)
  804. // {
  805. // if(F(fa,ea) == F(fb,eb))
  806. // {
  807. // assert(*p==A.vertex(ea));
  808. // assert(*p==B.vertex(eb));
  809. // }
  810. // }
  811. // }
  812. // }
  813. //#endif
  814. }else
  815. {
  816. //full:
  817. // No geometrically shared vertices, do general intersect
  818. intersect(*a.handle(),*b.handle(),fa,fb);
  819. }
  820. done:
  821. return;
  822. }
  823. // Compute 2D delaunay triangulation of a given 3d triangle and a list of
  824. // intersection objects (points,segments,triangles). CGAL uses an affine
  825. // projection rather than an isometric projection, so we're not guaranteed
  826. // that the 2D delaunay triangulation here will be a delaunay triangulation
  827. // in 3D.
  828. //
  829. // Inputs:
  830. // A triangle in 3D
  831. // A_objects_3 updated list of intersection objects for A
  832. // Outputs:
  833. // cdt Contrained delaunay triangulation in projected 2D plane
  834. template <typename Kernel>
  835. inline void igl::SelfIntersectMesh<Kernel>::projected_delaunay(
  836. const Triangle_3 & A,
  837. const std::list<CGAL::Object> & A_objects_3,
  838. CDT_plus_2 & cdt)
  839. {
  840. using namespace std;
  841. // http://www.cgal.org/Manual/3.2/doc_html/cgal_manual/Triangulation_2/Chapter_main.html#Section_2D_Triangulations_Constrained_Plus
  842. // Plane of triangle A
  843. Plane_3 P(A.vertex(0),A.vertex(1),A.vertex(2));
  844. // Insert triangle into vertices
  845. typename CDT_plus_2::Vertex_handle corners[3];
  846. for(int i = 0;i<3;i++)
  847. {
  848. corners[i] = cdt.insert(P.to_2d(A.vertex(i)));
  849. }
  850. // Insert triangle edges as constraints
  851. for(int i = 0;i<3;i++)
  852. {
  853. cdt.insert_constraint( corners[(i+1)%3], corners[(i+2)%3]);
  854. }
  855. // Insert constraints for intersection objects
  856. for(
  857. typename list<CGAL::Object>::const_iterator lit = A_objects_3.begin();
  858. lit != A_objects_3.end();
  859. lit++)
  860. {
  861. CGAL::Object obj = *lit;
  862. if(const Point_3 *ipoint = CGAL::object_cast<Point_3 >(&obj))
  863. {
  864. // Add point
  865. cdt.insert(P.to_2d(*ipoint));
  866. } else if(const Segment_3 *iseg = CGAL::object_cast<Segment_3 >(&obj))
  867. {
  868. // Add segment constraint
  869. cdt.insert_constraint(P.to_2d(iseg->vertex(0)),P.to_2d(iseg->vertex(1)));
  870. } else if(const Triangle_3 *itri = CGAL::object_cast<Triangle_3 >(&obj))
  871. {
  872. // Add 3 segment constraints
  873. cdt.insert_constraint(P.to_2d(itri->vertex(0)),P.to_2d(itri->vertex(1)));
  874. cdt.insert_constraint(P.to_2d(itri->vertex(1)),P.to_2d(itri->vertex(2)));
  875. cdt.insert_constraint(P.to_2d(itri->vertex(2)),P.to_2d(itri->vertex(0)));
  876. } else if(const std::vector<Point_3 > *polyp =
  877. CGAL::object_cast< std::vector<Point_3 > >(&obj))
  878. {
  879. //cerr<<REDRUM("Poly...")<<endl;
  880. const std::vector<Point_3 > & poly = *polyp;
  881. const int m = poly.size();
  882. assert(m>=2);
  883. for(int p = 0;p<m;p++)
  884. {
  885. const int np = (p+1)%m;
  886. cdt.insert_constraint(P.to_2d(poly[p]),P.to_2d(poly[np]));
  887. }
  888. }else
  889. {
  890. cerr<<REDRUM("What is this object?!")<<endl;
  891. assert(false);
  892. }
  893. }
  894. }
  895. #endif