SelfIntersectMesh.h 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268
  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 "RemeshSelfIntersectionsParam.h"
  12. #include <Eigen/Dense>
  13. #include <list>
  14. #include <map>
  15. #include <vector>
  16. //#define IGL_SELFINTERSECTMESH_DEBUG
  17. #ifndef IGL_FIRST_HIT_EXCEPTION
  18. #define IGL_FIRST_HIT_EXCEPTION 10
  19. #endif
  20. // The easiest way to keep track of everything is to use a class
  21. namespace igl
  22. {
  23. // Kernel is a CGAL kernel like:
  24. // CGAL::Exact_predicates_inexact_constructions_kernel
  25. // or
  26. // CGAL::Exact_predicates_exact_constructions_kernel
  27. template <
  28. typename Kernel,
  29. typename DerivedV,
  30. typename DerivedF,
  31. typename DerivedVV,
  32. typename DerivedFF,
  33. typename DerivedIF,
  34. typename DerivedJ,
  35. typename DerivedIM>
  36. class SelfIntersectMesh
  37. {
  38. typedef
  39. SelfIntersectMesh<
  40. Kernel,
  41. DerivedV,
  42. DerivedF,
  43. DerivedVV,
  44. DerivedFF,
  45. DerivedIF,
  46. DerivedJ,
  47. DerivedIM> Self;
  48. public:
  49. // 3D Primitives
  50. typedef CGAL::Point_3<Kernel> Point_3;
  51. typedef CGAL::Segment_3<Kernel> Segment_3;
  52. typedef CGAL::Triangle_3<Kernel> Triangle_3;
  53. typedef CGAL::Plane_3<Kernel> Plane_3;
  54. typedef CGAL::Tetrahedron_3<Kernel> Tetrahedron_3;
  55. //typedef CGAL::Polyhedron_3<Kernel> Polyhedron_3;
  56. //typedef CGAL::Nef_polyhedron_3<Kernel> Nef_polyhedron_3;
  57. // 2D Primitives
  58. typedef CGAL::Point_2<Kernel> Point_2;
  59. typedef CGAL::Segment_2<Kernel> Segment_2;
  60. typedef CGAL::Triangle_2<Kernel> Triangle_2;
  61. // 2D Constrained Delaunay Triangulation types
  62. typedef CGAL::Triangulation_vertex_base_2<Kernel> TVB_2;
  63. typedef CGAL::Constrained_triangulation_face_base_2<Kernel> CTFB_2;
  64. typedef CGAL::Triangulation_data_structure_2<TVB_2,CTFB_2> TDS_2;
  65. typedef CGAL::Exact_intersections_tag Itag;
  66. typedef CGAL::Constrained_Delaunay_triangulation_2<Kernel,TDS_2,Itag>
  67. CDT_2;
  68. typedef CGAL::Constrained_triangulation_plus_2<CDT_2> CDT_plus_2;
  69. // Axis-align boxes for all-pairs self-intersection detection
  70. typedef std::vector<Triangle_3> Triangles;
  71. typedef typename Triangles::iterator TrianglesIterator;
  72. typedef typename Triangles::const_iterator TrianglesConstIterator;
  73. typedef
  74. CGAL::Box_intersection_d::Box_with_handle_d<double,3,TrianglesIterator>
  75. Box;
  76. // Input mesh
  77. const Eigen::PlainObjectBase<DerivedV> & V;
  78. const Eigen::PlainObjectBase<DerivedF> & F;
  79. // Number of self-intersecting triangle pairs
  80. typedef typename DerivedF::Index Index;
  81. Index count;
  82. typedef std::vector<CGAL::Object> ObjectList;
  83. std::vector<ObjectList > F_objects;
  84. Triangles T;
  85. typedef std::vector<Index> IndexList;
  86. IndexList lIF;
  87. std::vector<bool> offensive;
  88. std::vector<Index> offending_index;
  89. std::vector<Index> offending;
  90. // Make a short name for the edge map's key
  91. typedef std::pair<Index,Index> EMK;
  92. // Make a short name for the type stored at each edge, the edge map's
  93. // value
  94. typedef std::vector<Index> EMV;
  95. // Make a short name for the edge map
  96. typedef std::map<EMK,EMV> EdgeMap;
  97. EdgeMap edge2faces;
  98. public:
  99. RemeshSelfIntersectionsParam params;
  100. public:
  101. // Constructs (VV,FF) a new mesh with self-intersections of (V,F)
  102. // subdivided
  103. //
  104. // See also: remesh_self_intersections.h
  105. inline SelfIntersectMesh(
  106. const Eigen::PlainObjectBase<DerivedV> & V,
  107. const Eigen::PlainObjectBase<DerivedF> & F,
  108. const RemeshSelfIntersectionsParam & params,
  109. Eigen::PlainObjectBase<DerivedVV> & VV,
  110. Eigen::PlainObjectBase<DerivedFF> & FF,
  111. Eigen::PlainObjectBase<DerivedIF> & IF,
  112. Eigen::PlainObjectBase<DerivedJ> & J,
  113. Eigen::PlainObjectBase<DerivedIM> & IM);
  114. private:
  115. // Helper function to mark a face as offensive
  116. //
  117. // Inputs:
  118. // f index of face in F
  119. inline void mark_offensive(const Index f);
  120. // Helper function to count intersections between faces
  121. //
  122. // Input:
  123. // fa index of face A in F
  124. // fb index of face B in F
  125. inline void count_intersection( const Index fa, const Index fb);
  126. // Helper function for box_intersect. Intersect two triangles A and B,
  127. // append the intersection object (point,segment,triangle) to a running
  128. // list for A and B
  129. //
  130. // Inputs:
  131. // A triangle in 3D
  132. // B triangle in 3D
  133. // fa index of A in F (and F_objects)
  134. // fb index of A in F (and F_objects)
  135. // Returns true only if A intersects B
  136. //
  137. inline bool intersect(
  138. const Triangle_3 & A,
  139. const Triangle_3 & B,
  140. const Index fa,
  141. const Index fb);
  142. // Helper function for box_intersect. In the case where A and B have
  143. // already been identified to share a vertex, then we only want to add
  144. // possible segment intersections. Assumes truly duplicate triangles are
  145. // not given as input
  146. //
  147. // Inputs:
  148. // A triangle in 3D
  149. // B triangle in 3D
  150. // fa index of A in F (and F_objects)
  151. // fb index of B in F (and F_objects)
  152. // va index of shared vertex in A (and F_objects)
  153. // vb index of shared vertex in B (and F_objects)
  154. //// Returns object of intersection (should be Segment or point)
  155. // Returns true if intersection (besides shared point)
  156. //
  157. inline bool single_shared_vertex(
  158. const Triangle_3 & A,
  159. const Triangle_3 & B,
  160. const Index fa,
  161. const Index fb,
  162. const Index va,
  163. const Index vb);
  164. // Helper handling one direction
  165. inline bool single_shared_vertex(
  166. const Triangle_3 & A,
  167. const Triangle_3 & B,
  168. const Index fa,
  169. const Index fb,
  170. const Index va);
  171. // Helper function for box_intersect. In the case where A and B have
  172. // already been identified to share two vertices, then we only want to add
  173. // a possible coplanar (Triangle) intersection. Assumes truly degenerate
  174. // facets are not givin as input.
  175. inline bool double_shared_vertex(
  176. const Triangle_3 & A,
  177. const Triangle_3 & B,
  178. const Index fa,
  179. const Index fb);
  180. public:
  181. // Callback function called during box self intersections test. Means
  182. // boxes a and b intersect. This method then checks if the triangles in
  183. // each box intersect and if so, then processes the intersections
  184. //
  185. // Inputs:
  186. // a box containing a triangle
  187. // b box containing a triangle
  188. inline void box_intersect(const Box& a, const Box& b);
  189. private:
  190. // Compute 2D delaunay triangulation of a given 3d triangle and a list of
  191. // intersection objects (points,segments,triangles). CGAL uses an affine
  192. // projection rather than an isometric projection, so we're not
  193. // guaranteed that the 2D delaunay triangulation here will be a delaunay
  194. // triangulation in 3D.
  195. //
  196. // Inputs:
  197. // A triangle in 3D
  198. // A_objects_3 updated list of intersection objects for A
  199. // Outputs:
  200. // cdt Contrained delaunay triangulation in projected 2D plane
  201. inline void projected_delaunay(
  202. const Triangle_3 & A,
  203. const ObjectList & A_objects_3,
  204. CDT_plus_2 & cdt);
  205. // Getters:
  206. public:
  207. //const IndexList& get_lIF() const{ return lIF;}
  208. static inline void box_intersect_static(
  209. SelfIntersectMesh * SIM,
  210. const Box &a,
  211. const Box &b);
  212. // Annoying wrappers to conver from cgal to double or cgal
  213. static inline void to_output_type(const typename Kernel::FT & cgal,double & d);
  214. static inline void to_output_type(
  215. const typename CGAL::Epeck::FT & cgal,
  216. CGAL::Epeck::FT & d);
  217. };
  218. }
  219. // Implementation
  220. #include "mesh_to_cgal_triangle_list.h"
  221. #include <igl/REDRUM.h>
  222. #include <igl/get_seconds.h>
  223. #include <igl/C_STR.h>
  224. #include <functional>
  225. #include <algorithm>
  226. #include <exception>
  227. #include <cassert>
  228. #include <iostream>
  229. // References:
  230. // http://minregret.googlecode.com/svn/trunk/skyline/src/extern/CGAL-3.3.1/examples/Polyhedron/polyhedron_self_intersection.cpp
  231. // http://www.cgal.org/Manual/3.9/examples/Boolean_set_operations_2/do_intersect.cpp
  232. // Q: Should we be using CGAL::Polyhedron_3?
  233. // A: No! Input is just a list of unoriented triangles. Polyhedron_3 requires
  234. // a 2-manifold.
  235. // A: But! It seems we could use CGAL::Triangulation_3. Though it won't be easy
  236. // to take advantage of functions like insert_in_facet because we want to
  237. // constrain segments. Hmmm. Actualy Triangulation_3 doesn't look right...
  238. //static void box_intersect(SelfIntersectMesh * SIM,const Box & A, const Box & B)
  239. //{
  240. // return SIM->box_intersect(A,B);
  241. //}
  242. // CGAL's box_self_intersection_d uses C-style function callbacks without
  243. // userdata. This is a leapfrog method for calling a member function. It should
  244. // be bound as if the prototype was:
  245. // static void box_intersect(const Box &a, const Box &b)
  246. // using boost:
  247. // boost::function<void(const Box &a,const Box &b)> cb
  248. // = boost::bind(&::box_intersect, this, _1,_2);
  249. //
  250. template <
  251. typename Kernel,
  252. typename DerivedV,
  253. typename DerivedF,
  254. typename DerivedVV,
  255. typename DerivedFF,
  256. typename DerivedIF,
  257. typename DerivedJ,
  258. typename DerivedIM>
  259. inline void igl::SelfIntersectMesh<
  260. Kernel,
  261. DerivedV,
  262. DerivedF,
  263. DerivedVV,
  264. DerivedFF,
  265. DerivedIF,
  266. DerivedJ,
  267. DerivedIM>::box_intersect_static(
  268. Self * SIM,
  269. const typename Self::Box &a,
  270. const typename Self::Box &b)
  271. {
  272. SIM->box_intersect(a,b);
  273. }
  274. template <
  275. typename Kernel,
  276. typename DerivedV,
  277. typename DerivedF,
  278. typename DerivedVV,
  279. typename DerivedFF,
  280. typename DerivedIF,
  281. typename DerivedJ,
  282. typename DerivedIM>
  283. inline igl::SelfIntersectMesh<
  284. Kernel,
  285. DerivedV,
  286. DerivedF,
  287. DerivedVV,
  288. DerivedFF,
  289. DerivedIF,
  290. DerivedJ,
  291. DerivedIM>::SelfIntersectMesh(
  292. const Eigen::PlainObjectBase<DerivedV> & V,
  293. const Eigen::PlainObjectBase<DerivedF> & F,
  294. const RemeshSelfIntersectionsParam & params,
  295. Eigen::PlainObjectBase<DerivedVV> & VV,
  296. Eigen::PlainObjectBase<DerivedFF> & FF,
  297. Eigen::PlainObjectBase<DerivedIF> & IF,
  298. Eigen::PlainObjectBase<DerivedJ> & J,
  299. Eigen::PlainObjectBase<DerivedIM> & IM):
  300. V(V),
  301. F(F),
  302. count(0),
  303. F_objects(F.rows()),
  304. T(),
  305. lIF(),
  306. offensive(F.rows(),false),
  307. offending_index(F.rows(),-1),
  308. offending(),
  309. edge2faces(),
  310. params(params)
  311. {
  312. using namespace std;
  313. using namespace Eigen;
  314. #ifdef IGL_SELFINTERSECTMESH_DEBUG
  315. const auto & tictoc = []()
  316. {
  317. static double t_start = igl::get_seconds();
  318. double diff = igl::get_seconds()-t_start;
  319. t_start += diff;
  320. return diff;
  321. };
  322. tictoc();
  323. #endif
  324. // Compute and process self intersections
  325. mesh_to_cgal_triangle_list(V,F,T);
  326. #ifdef IGL_SELFINTERSECTMESH_DEBUG
  327. cout<<"mesh_to_cgal_triangle_list: "<<tictoc()<<endl;
  328. #endif
  329. // http://www.cgal.org/Manual/latest/doc_html/cgal_manual/Box_intersection_d/Chapter_main.html#Section_63.5
  330. // Create the corresponding vector of bounding boxes
  331. std::vector<Box> boxes;
  332. boxes.reserve(T.size());
  333. for (
  334. TrianglesIterator tit = T.begin();
  335. tit != T.end();
  336. ++tit)
  337. {
  338. boxes.push_back(Box(tit->bbox(), tit));
  339. }
  340. // Leapfrog callback
  341. std::function<void(const Box &a,const Box &b)> cb =
  342. std::bind(&box_intersect_static, this,
  343. // Explicitly use std namespace to avoid confusion with boost (who puts
  344. // _1 etc. in global namespace)
  345. std::placeholders::_1,
  346. std::placeholders::_2);
  347. #ifdef IGL_SELFINTERSECTMESH_DEBUG
  348. cout<<"boxes and bind: "<<tictoc()<<endl;
  349. #endif
  350. // Run the self intersection algorithm with all defaults
  351. try{
  352. CGAL::box_self_intersection_d(boxes.begin(), boxes.end(),cb);
  353. }catch(int e)
  354. {
  355. // Rethrow if not IGL_FIRST_HIT_EXCEPTION
  356. if(e != IGL_FIRST_HIT_EXCEPTION)
  357. {
  358. throw e;
  359. }
  360. // Otherwise just fall through
  361. }
  362. #ifdef IGL_SELFINTERSECTMESH_DEBUG
  363. cout<<"box_self_intersection_d: "<<tictoc()<<endl;
  364. #endif
  365. // Convert lIF to Eigen matrix
  366. assert(lIF.size()%2 == 0);
  367. IF.resize(lIF.size()/2,2);
  368. {
  369. Index i=0;
  370. for(
  371. typename IndexList::const_iterator ifit = lIF.begin();
  372. ifit!=lIF.end();
  373. )
  374. {
  375. IF(i,0) = (*ifit);
  376. ifit++;
  377. IF(i,1) = (*ifit);
  378. ifit++;
  379. i++;
  380. }
  381. }
  382. #ifdef IGL_SELFINTERSECTMESH_DEBUG
  383. cout<<"IF: "<<tictoc()<<endl;
  384. #endif
  385. if(params.detect_only)
  386. {
  387. return;
  388. }
  389. int NF_count = 0;
  390. // list of new faces, we'll fix F later
  391. vector<
  392. typename Eigen::Matrix<typename DerivedFF::Scalar,Dynamic,Dynamic>
  393. > NF(offending.size());
  394. // list of new vertices
  395. typedef vector<Point_3> Point_3List;
  396. Point_3List NV;
  397. Index NV_count = 0;
  398. vector<CDT_plus_2> cdt(offending.size());
  399. vector<Plane_3> P(offending.size());
  400. // Use map for *all* faces
  401. map<typename CDT_plus_2::Vertex_handle,Index> v2i;
  402. // Loop over offending triangles
  403. const size_t noff = offending.size();
  404. #ifdef IGL_SELFINTERSECTMESH_DEBUG
  405. double t_proj_del = 0;
  406. #endif
  407. // Unfortunately it looks like CGAL has trouble allocating memory when
  408. // multiple openmp threads are running. Crashes durring CDT...
  409. //# pragma omp parallel for if (noff>1000)
  410. for(Index o = 0;o<(Index)noff;o++)
  411. {
  412. // index in F
  413. const Index f = offending[o];
  414. {
  415. #ifdef IGL_SELFINTERSECTMESH_DEBUG
  416. const double t_before = get_seconds();
  417. #endif
  418. projected_delaunay(T[f],F_objects[f],cdt[o]);
  419. #ifdef IGL_SELFINTERSECTMESH_DEBUG
  420. t_proj_del += (get_seconds()-t_before);
  421. #endif
  422. }
  423. // Q: Is this also delaunay in 3D?
  424. // A: No, because the projection is affine and delaunay is not affine
  425. // invariant.
  426. // Q: Then, can't we first get the 2D delaunay triangulation, then lift it
  427. // to 3D and flip any offending edges?
  428. // Plane of projection (also used by projected_delaunay)
  429. P[o] = Plane_3(T[f].vertex(0),T[f].vertex(1),T[f].vertex(2));
  430. // Build index map
  431. {
  432. Index i=0;
  433. for(
  434. typename CDT_plus_2::Finite_vertices_iterator vit = cdt[o].finite_vertices_begin();
  435. vit != cdt[o].finite_vertices_end();
  436. ++vit)
  437. {
  438. if(i<3)
  439. {
  440. //cout<<T[f].vertex(i)<<
  441. // (T[f].vertex(i) == P[o].to_3d(vit->point())?" == ":" != ")<<
  442. // P[o].to_3d(vit->point())<<endl;
  443. #ifndef NDEBUG
  444. // I want to be sure that the original corners really show up as the
  445. // original corners of the CDT. I.e. I don't trust CGAL to maintain
  446. // the order
  447. assert(T[f].vertex(i) == P[o].to_3d(vit->point()));
  448. #endif
  449. // For first three, use original index in F
  450. //# pragma omp critical
  451. v2i[vit] = F(f,i);
  452. }else
  453. {
  454. const Point_3 vit_point_3 = P[o].to_3d(vit->point());
  455. // First look up each edge's neighbors to see if exact point has
  456. // already been added (This makes everything a bit quadratic)
  457. bool found = false;
  458. for(int e = 0; e<3 && !found;e++)
  459. {
  460. // Index of F's eth edge in V
  461. Index i = F(f,(e+1)%3);
  462. Index j = F(f,(e+2)%3);
  463. // Be sure that i<j
  464. if(i>j)
  465. {
  466. swap(i,j);
  467. }
  468. assert(edge2faces.count(EMK(i,j))==1);
  469. // loop over neighbors
  470. for(
  471. typename IndexList::const_iterator nit = edge2faces[EMK(i,j)].begin();
  472. nit != edge2faces[EMK(i,j)].end() && !found;
  473. nit++)
  474. {
  475. // don't consider self
  476. if(*nit == f)
  477. {
  478. continue;
  479. }
  480. // index of neighbor in offending (to find its cdt)
  481. Index no = offending_index[*nit];
  482. // Loop over vertices of that neighbor's cdt (might not have been
  483. // processed yet, but then it's OK because it'll just be empty)
  484. for(
  485. typename CDT_plus_2::Finite_vertices_iterator uit = cdt[no].finite_vertices_begin();
  486. uit != cdt[no].finite_vertices_end() && !found;
  487. ++uit)
  488. {
  489. if(vit_point_3 == P[no].to_3d(uit->point()))
  490. {
  491. assert(v2i.count(uit) == 1);
  492. //# pragma omp critical
  493. v2i[vit] = v2i[uit];
  494. found = true;
  495. }
  496. }
  497. }
  498. }
  499. if(!found)
  500. {
  501. //# pragma omp critical
  502. {
  503. v2i[vit] = V.rows()+NV_count;
  504. NV.push_back(vit_point_3);
  505. NV_count++;
  506. }
  507. }
  508. }
  509. i++;
  510. }
  511. }
  512. {
  513. Index i = 0;
  514. // Resize to fit new number of triangles
  515. NF[o].resize(cdt[o].number_of_faces(),3);
  516. //# pragma omp atomic
  517. NF_count+=NF[o].rows();
  518. // Append new faces to NF
  519. for(
  520. typename CDT_plus_2::Finite_faces_iterator fit = cdt[o].finite_faces_begin();
  521. fit != cdt[o].finite_faces_end();
  522. ++fit)
  523. {
  524. NF[o](i,0) = v2i[fit->vertex(0)];
  525. NF[o](i,1) = v2i[fit->vertex(1)];
  526. NF[o](i,2) = v2i[fit->vertex(2)];
  527. i++;
  528. }
  529. }
  530. }
  531. #ifdef IGL_SELFINTERSECTMESH_DEBUG
  532. cout<<"CDT: "<<tictoc()<<" "<<t_proj_del<<endl;
  533. #endif
  534. assert(NV_count == (Index)NV.size());
  535. // Build output
  536. #ifndef NDEBUG
  537. {
  538. Index off_count = 0;
  539. for(Index f = 0;f<F.rows();f++)
  540. {
  541. off_count+= (offensive[f]?1:0);
  542. }
  543. assert(off_count==(Index)offending.size());
  544. }
  545. #endif
  546. // Append faces
  547. FF.resize(F.rows()-offending.size()+NF_count,3);
  548. J.resize(FF.rows());
  549. // First append non-offending original faces
  550. // There's an Eigen way to do this in one line but I forget
  551. Index off = 0;
  552. for(Index f = 0;f<F.rows();f++)
  553. {
  554. if(!offensive[f])
  555. {
  556. FF.row(off) = F.row(f);
  557. J(off) = f;
  558. off++;
  559. }
  560. }
  561. assert(off == (Index)(F.rows()-offending.size()));
  562. // Now append replacement faces for offending faces
  563. for(Index o = 0;o<(Index)offending.size();o++)
  564. {
  565. FF.block(off,0,NF[o].rows(),3) = NF[o];
  566. J.block(off,0,NF[o].rows(),1).setConstant(offending[o]);
  567. off += NF[o].rows();
  568. }
  569. // Append vertices
  570. VV.resize(V.rows()+NV_count,3);
  571. VV.block(0,0,V.rows(),3) = V.template cast<typename DerivedVV::Scalar>();
  572. {
  573. Index i = 0;
  574. for(
  575. typename Point_3List::const_iterator nvit = NV.begin();
  576. nvit != NV.end();
  577. nvit++)
  578. {
  579. for(Index d = 0;d<3;d++)
  580. {
  581. const Point_3 & p = *nvit;
  582. // Don't convert via double if output type is same as Kernel
  583. to_output_type(p[d], VV(V.rows()+i,d));
  584. }
  585. i++;
  586. }
  587. }
  588. IM.resize(VV.rows(),1);
  589. map<Point_3,Index> vv2i;
  590. // Safe to check for duplicates using double for original vertices: if
  591. // incoming reps are different then the points are unique.
  592. for(Index v = 0;v<V.rows();v++)
  593. {
  594. const Point_3 p(V(v,0),V(v,1),V(v,2));
  595. if(vv2i.count(p)==0)
  596. {
  597. vv2i[p] = v;
  598. }
  599. assert(vv2i.count(p) == 1);
  600. IM(v) = vv2i[p];
  601. }
  602. // Must check for duplicates of new vertices using exact.
  603. {
  604. Index v = V.rows();
  605. for(
  606. typename Point_3List::const_iterator nvit = NV.begin();
  607. nvit != NV.end();
  608. nvit++)
  609. {
  610. const Point_3 & p = *nvit;
  611. if(vv2i.count(p)==0)
  612. {
  613. vv2i[p] = v;
  614. }
  615. assert(vv2i.count(p) == 1);
  616. IM(v) = vv2i[p];
  617. v++;
  618. }
  619. }
  620. #ifdef IGL_SELFINTERSECTMESH_DEBUG
  621. cout<<"Output + dupes: "<<tictoc()<<endl;
  622. #endif
  623. // Q: Does this give the same result as TETGEN?
  624. // A: For the cow and beast, yes.
  625. // Q: Is tetgen faster than this CGAL implementation?
  626. // A: Well, yes. But Tetgen is only solving the detection (predicates)
  627. // problem. This is also appending the intersection objects (construction).
  628. // But maybe tetgen is still faster for the detection part. For example, this
  629. // CGAL implementation on the beast takes 98 seconds but tetgen detection
  630. // takes 14 seconds
  631. }
  632. template <
  633. typename Kernel,
  634. typename DerivedV,
  635. typename DerivedF,
  636. typename DerivedVV,
  637. typename DerivedFF,
  638. typename DerivedIF,
  639. typename DerivedJ,
  640. typename DerivedIM>
  641. inline void igl::SelfIntersectMesh<
  642. Kernel,
  643. DerivedV,
  644. DerivedF,
  645. DerivedVV,
  646. DerivedFF,
  647. DerivedIF,
  648. DerivedJ,
  649. DerivedIM>::mark_offensive(const Index f)
  650. {
  651. using namespace std;
  652. lIF.push_back(f);
  653. if(!offensive[f])
  654. {
  655. offensive[f]=true;
  656. offending_index[f]=offending.size();
  657. offending.push_back(f);
  658. // Add to edge map
  659. for(Index e = 0; e<3;e++)
  660. {
  661. // Index of F's eth edge in V
  662. Index i = F(f,(e+1)%3);
  663. Index j = F(f,(e+2)%3);
  664. // Be sure that i<j
  665. if(i>j)
  666. {
  667. swap(i,j);
  668. }
  669. // Create new list if there is no entry
  670. if(edge2faces.count(EMK(i,j))==0)
  671. {
  672. edge2faces[EMK(i,j)] = EMV();
  673. }
  674. // append to list
  675. edge2faces[EMK(i,j)].push_back(f);
  676. }
  677. }
  678. }
  679. template <
  680. typename Kernel,
  681. typename DerivedV,
  682. typename DerivedF,
  683. typename DerivedVV,
  684. typename DerivedFF,
  685. typename DerivedIF,
  686. typename DerivedJ,
  687. typename DerivedIM>
  688. inline void igl::SelfIntersectMesh<
  689. Kernel,
  690. DerivedV,
  691. DerivedF,
  692. DerivedVV,
  693. DerivedFF,
  694. DerivedIF,
  695. DerivedJ,
  696. DerivedIM>::count_intersection(
  697. const Index fa,
  698. const Index fb)
  699. {
  700. mark_offensive(fa);
  701. mark_offensive(fb);
  702. this->count++;
  703. // We found the first intersection
  704. if(params.first_only && this->count >= 1)
  705. {
  706. throw IGL_FIRST_HIT_EXCEPTION;
  707. }
  708. }
  709. template <
  710. typename Kernel,
  711. typename DerivedV,
  712. typename DerivedF,
  713. typename DerivedVV,
  714. typename DerivedFF,
  715. typename DerivedIF,
  716. typename DerivedJ,
  717. typename DerivedIM>
  718. inline bool igl::SelfIntersectMesh<
  719. Kernel,
  720. DerivedV,
  721. DerivedF,
  722. DerivedVV,
  723. DerivedFF,
  724. DerivedIF,
  725. DerivedJ,
  726. DerivedIM>::intersect(
  727. const Triangle_3 & A,
  728. const Triangle_3 & B,
  729. const Index fa,
  730. const Index fb)
  731. {
  732. // Determine whether there is an intersection
  733. if(!CGAL::do_intersect(A,B))
  734. {
  735. return false;
  736. }
  737. if(!params.detect_only)
  738. {
  739. // Construct intersection
  740. CGAL::Object result = CGAL::intersection(A,B);
  741. F_objects[fa].push_back(result);
  742. F_objects[fb].push_back(result);
  743. }
  744. count_intersection(fa,fb);
  745. return true;
  746. }
  747. template <
  748. typename Kernel,
  749. typename DerivedV,
  750. typename DerivedF,
  751. typename DerivedVV,
  752. typename DerivedFF,
  753. typename DerivedIF,
  754. typename DerivedJ,
  755. typename DerivedIM>
  756. inline bool igl::SelfIntersectMesh<
  757. Kernel,
  758. DerivedV,
  759. DerivedF,
  760. DerivedVV,
  761. DerivedFF,
  762. DerivedIF,
  763. DerivedJ,
  764. DerivedIM>::single_shared_vertex(
  765. const Triangle_3 & A,
  766. const Triangle_3 & B,
  767. const Index fa,
  768. const Index fb,
  769. const Index va,
  770. const Index vb)
  771. {
  772. ////using namespace std;
  773. //CGAL::Object result = CGAL::intersection(A,B);
  774. //if(CGAL::object_cast<Segment_3 >(&result))
  775. //{
  776. // // Append to each triangle's running list
  777. // F_objects[fa].push_back(result);
  778. // F_objects[fb].push_back(result);
  779. // count_intersection(fa,fb);
  780. //}else
  781. //{
  782. // // Then intersection must be at point
  783. // // And point must be at shared vertex
  784. // assert(CGAL::object_cast<Point_3>(&result));
  785. //}
  786. if(single_shared_vertex(A,B,fa,fb,va))
  787. {
  788. return true;
  789. }
  790. return single_shared_vertex(B,A,fb,fa,vb);
  791. }
  792. template <
  793. typename Kernel,
  794. typename DerivedV,
  795. typename DerivedF,
  796. typename DerivedVV,
  797. typename DerivedFF,
  798. typename DerivedIF,
  799. typename DerivedJ,
  800. typename DerivedIM>
  801. inline bool igl::SelfIntersectMesh<
  802. Kernel,
  803. DerivedV,
  804. DerivedF,
  805. DerivedVV,
  806. DerivedFF,
  807. DerivedIF,
  808. DerivedJ,
  809. DerivedIM>::single_shared_vertex(
  810. const Triangle_3 & A,
  811. const Triangle_3 & B,
  812. const Index fa,
  813. const Index fb,
  814. const Index va)
  815. {
  816. // This was not a good idea. It will not handle coplanar triangles well.
  817. using namespace std;
  818. Segment_3 sa(
  819. A.vertex((va+1)%3),
  820. A.vertex((va+2)%3));
  821. if(CGAL::do_intersect(sa,B))
  822. {
  823. CGAL::Object result = CGAL::intersection(sa,B);
  824. if(const Point_3 * p = CGAL::object_cast<Point_3 >(&result))
  825. {
  826. if(!params.detect_only)
  827. {
  828. // Single intersection --> segment from shared point to intersection
  829. CGAL::Object seg = CGAL::make_object(Segment_3(
  830. A.vertex(va),
  831. *p));
  832. F_objects[fa].push_back(seg);
  833. F_objects[fb].push_back(seg);
  834. }
  835. count_intersection(fa,fb);
  836. return true;
  837. }else if(CGAL::object_cast<Segment_3 >(&result))
  838. {
  839. //cerr<<REDRUM("Coplanar at: "<<fa<<" & "<<fb<<" (single shared).")<<endl;
  840. // Must be coplanar
  841. if(params.detect_only)
  842. {
  843. count_intersection(fa,fb);
  844. }else
  845. {
  846. // WRONG:
  847. //// Segment intersection --> triangle from shared point to intersection
  848. //CGAL::Object tri = CGAL::make_object(Triangle_3(
  849. // A.vertex(va),
  850. // s->vertex(0),
  851. // s->vertex(1)));
  852. //F_objects[fa].push_back(tri);
  853. //F_objects[fb].push_back(tri);
  854. //count_intersection(fa,fb);
  855. // Need to do full test. Intersection could be a general poly.
  856. bool test = intersect(A,B,fa,fb);
  857. ((void)test);
  858. assert(test);
  859. }
  860. return true;
  861. }else
  862. {
  863. cerr<<REDRUM("Segment ∩ triangle neither point nor segment?")<<endl;
  864. assert(false);
  865. }
  866. }
  867. return false;
  868. }
  869. template <
  870. typename Kernel,
  871. typename DerivedV,
  872. typename DerivedF,
  873. typename DerivedVV,
  874. typename DerivedFF,
  875. typename DerivedIF,
  876. typename DerivedJ,
  877. typename DerivedIM>
  878. inline bool igl::SelfIntersectMesh<
  879. Kernel,
  880. DerivedV,
  881. DerivedF,
  882. DerivedVV,
  883. DerivedFF,
  884. DerivedIF,
  885. DerivedJ,
  886. DerivedIM>::double_shared_vertex(
  887. const Triangle_3 & A,
  888. const Triangle_3 & B,
  889. const Index fa,
  890. const Index fb)
  891. {
  892. using namespace std;
  893. // Cheaper way to do this than calling do_intersect?
  894. if(
  895. // Can only have an intersection if co-planar
  896. (A.supporting_plane() == B.supporting_plane() ||
  897. A.supporting_plane() == B.supporting_plane().opposite()) &&
  898. CGAL::do_intersect(A,B))
  899. {
  900. // Construct intersection
  901. try
  902. {
  903. // This can fail for Epick but not Epeck
  904. CGAL::Object result = CGAL::intersection(A,B);
  905. if(!result.empty())
  906. {
  907. if(CGAL::object_cast<Segment_3 >(&result))
  908. {
  909. // not coplanar
  910. return false;
  911. } else if(CGAL::object_cast<Point_3 >(&result))
  912. {
  913. // this "shouldn't" happen but does for inexact
  914. return false;
  915. } else
  916. {
  917. if(!params.detect_only)
  918. {
  919. // Triangle object
  920. F_objects[fa].push_back(result);
  921. F_objects[fb].push_back(result);
  922. }
  923. count_intersection(fa,fb);
  924. //cerr<<REDRUM("Coplanar at: "<<fa<<" & "<<fb<<" (double shared).")<<endl;
  925. return true;
  926. }
  927. }else
  928. {
  929. // CGAL::intersection is disagreeing with do_intersect
  930. return false;
  931. }
  932. }catch(...)
  933. {
  934. // This catches some cgal assertion:
  935. // CGAL error: assertion violation!
  936. // Expression : is_finite(d)
  937. // File : /opt/local/include/CGAL/GMP/Gmpq_type.h
  938. // Line : 132
  939. // Explanation:
  940. // But only if NDEBUG is not defined, otherwise there's an uncaught
  941. // "Floating point exception: 8" SIGFPE
  942. return false;
  943. }
  944. }
  945. // No intersection.
  946. return false;
  947. }
  948. template <
  949. typename Kernel,
  950. typename DerivedV,
  951. typename DerivedF,
  952. typename DerivedVV,
  953. typename DerivedFF,
  954. typename DerivedIF,
  955. typename DerivedJ,
  956. typename DerivedIM>
  957. inline void igl::SelfIntersectMesh<
  958. Kernel,
  959. DerivedV,
  960. DerivedF,
  961. DerivedVV,
  962. DerivedFF,
  963. DerivedIF,
  964. DerivedJ,
  965. DerivedIM>::box_intersect(
  966. const Box& a,
  967. const Box& b)
  968. {
  969. using namespace std;
  970. // Could we write this as a static function of:
  971. //
  972. // F.row(fa)
  973. // F.row(fb)
  974. // A
  975. // B
  976. // index in F and T
  977. Index fa = a.handle()-T.begin();
  978. Index fb = b.handle()-T.begin();
  979. const Triangle_3 & A = *a.handle();
  980. const Triangle_3 & B = *b.handle();
  981. // I'm not going to deal with degenerate triangles, though at some point we
  982. // should
  983. assert(!a.handle()->is_degenerate());
  984. assert(!b.handle()->is_degenerate());
  985. // Number of combinatorially shared vertices
  986. Index comb_shared_vertices = 0;
  987. // Number of geometrically shared vertices (*not* including combinatorially
  988. // shared)
  989. Index geo_shared_vertices = 0;
  990. // Keep track of shared vertex indices (we only handles single shared
  991. // vertices as a special case, so just need last/first/only ones)
  992. Index va=-1,vb=-1;
  993. Index ea,eb;
  994. for(ea=0;ea<3;ea++)
  995. {
  996. for(eb=0;eb<3;eb++)
  997. {
  998. if(F(fa,ea) == F(fb,eb))
  999. {
  1000. comb_shared_vertices++;
  1001. va = ea;
  1002. vb = eb;
  1003. }else if(A.vertex(ea) == B.vertex(eb))
  1004. {
  1005. geo_shared_vertices++;
  1006. va = ea;
  1007. vb = eb;
  1008. }
  1009. }
  1010. }
  1011. const Index total_shared_vertices = comb_shared_vertices + geo_shared_vertices;
  1012. if(comb_shared_vertices== 3)
  1013. {
  1014. //// Combinatorially duplicate face, these should be removed by preprocessing
  1015. //cerr<<REDRUM("Facets "<<fa<<" and "<<fb<<" are combinatorial duplicates")<<endl;
  1016. goto done;
  1017. }
  1018. if(total_shared_vertices== 3)
  1019. {
  1020. //// Geometrically duplicate face, these should be removed by preprocessing
  1021. //cerr<<REDRUM("Facets "<<fa<<" and "<<fb<<" are geometrical duplicates")<<endl;
  1022. goto done;
  1023. }
  1024. //// SPECIAL CASES ARE BROKEN FOR COPLANAR TRIANGLES
  1025. //if(total_shared_vertices > 0)
  1026. //{
  1027. // bool coplanar =
  1028. // CGAL::coplanar(A.vertex(0),A.vertex(1),A.vertex(2),B.vertex(0)) &&
  1029. // CGAL::coplanar(A.vertex(0),A.vertex(1),A.vertex(2),B.vertex(1)) &&
  1030. // CGAL::coplanar(A.vertex(0),A.vertex(1),A.vertex(2),B.vertex(2));
  1031. // if(coplanar)
  1032. // {
  1033. // cerr<<MAGENTAGIN("Facets "<<fa<<" and "<<fb<<
  1034. // " are coplanar and share vertices")<<endl;
  1035. // goto full;
  1036. // }
  1037. //}
  1038. if(total_shared_vertices == 2)
  1039. {
  1040. // Q: What about coplanar?
  1041. //
  1042. // o o
  1043. // |\ /|
  1044. // | \/ |
  1045. // | /\ |
  1046. // |/ \|
  1047. // o----o
  1048. double_shared_vertex(A,B,fa,fb);
  1049. goto done;
  1050. }
  1051. assert(total_shared_vertices<=1);
  1052. if(total_shared_vertices==1)
  1053. {
  1054. assert(va>=0 && va<3);
  1055. assert(vb>=0 && vb<3);
  1056. //#ifndef NDEBUG
  1057. // CGAL::Object result =
  1058. //#endif
  1059. single_shared_vertex(A,B,fa,fb,va,vb);
  1060. //#ifndef NDEBUG
  1061. // if(!CGAL::object_cast<Segment_3 >(&result))
  1062. // {
  1063. // const Point_3 * p = CGAL::object_cast<Point_3 >(&result);
  1064. // assert(p);
  1065. // for(int ea=0;ea<3;ea++)
  1066. // {
  1067. // for(int eb=0;eb<3;eb++)
  1068. // {
  1069. // if(F(fa,ea) == F(fb,eb))
  1070. // {
  1071. // assert(*p==A.vertex(ea));
  1072. // assert(*p==B.vertex(eb));
  1073. // }
  1074. // }
  1075. // }
  1076. // }
  1077. //#endif
  1078. }else
  1079. {
  1080. //full:
  1081. // No geometrically shared vertices, do general intersect
  1082. intersect(*a.handle(),*b.handle(),fa,fb);
  1083. }
  1084. done:
  1085. return;
  1086. }
  1087. // Compute 2D delaunay triangulation of a given 3d triangle and a list of
  1088. // intersection objects (points,segments,triangles). CGAL uses an affine
  1089. // projection rather than an isometric projection, so we're not guaranteed
  1090. // that the 2D delaunay triangulation here will be a delaunay triangulation
  1091. // in 3D.
  1092. //
  1093. // Inputs:
  1094. // A triangle in 3D
  1095. // A_objects_3 updated list of intersection objects for A
  1096. // Outputs:
  1097. // cdt Contrained delaunay triangulation in projected 2D plane
  1098. template <
  1099. typename Kernel,
  1100. typename DerivedV,
  1101. typename DerivedF,
  1102. typename DerivedVV,
  1103. typename DerivedFF,
  1104. typename DerivedIF,
  1105. typename DerivedJ,
  1106. typename DerivedIM>
  1107. inline void igl::SelfIntersectMesh<
  1108. Kernel,
  1109. DerivedV,
  1110. DerivedF,
  1111. DerivedVV,
  1112. DerivedFF,
  1113. DerivedIF,
  1114. DerivedJ,
  1115. DerivedIM>::projected_delaunay(
  1116. const Triangle_3 & A,
  1117. const ObjectList & A_objects_3,
  1118. CDT_plus_2 & cdt)
  1119. {
  1120. using namespace std;
  1121. // http://www.cgal.org/Manual/3.2/doc_html/cgal_manual/Triangulation_2/Chapter_main.html#Section_2D_Triangulations_Constrained_Plus
  1122. // Plane of triangle A
  1123. Plane_3 P(A.vertex(0),A.vertex(1),A.vertex(2));
  1124. // Insert triangle into vertices
  1125. typename CDT_plus_2::Vertex_handle corners[3];
  1126. for(Index i = 0;i<3;i++)
  1127. {
  1128. corners[i] = cdt.insert(P.to_2d(A.vertex(i)));
  1129. }
  1130. // Insert triangle edges as constraints
  1131. for(Index i = 0;i<3;i++)
  1132. {
  1133. cdt.insert_constraint( corners[(i+1)%3], corners[(i+2)%3]);
  1134. }
  1135. // Insert constraints for intersection objects
  1136. for( const auto & obj : A_objects_3)
  1137. {
  1138. if(const Segment_3 *iseg = CGAL::object_cast<Segment_3 >(&obj))
  1139. {
  1140. // Add segment constraint
  1141. cdt.insert_constraint(P.to_2d(iseg->vertex(0)),P.to_2d(iseg->vertex(1)));
  1142. }else if(const Point_3 *ipoint = CGAL::object_cast<Point_3 >(&obj))
  1143. {
  1144. // Add point
  1145. cdt.insert(P.to_2d(*ipoint));
  1146. } else if(const Triangle_3 *itri = CGAL::object_cast<Triangle_3 >(&obj))
  1147. {
  1148. // Add 3 segment constraints
  1149. cdt.insert_constraint(P.to_2d(itri->vertex(0)),P.to_2d(itri->vertex(1)));
  1150. cdt.insert_constraint(P.to_2d(itri->vertex(1)),P.to_2d(itri->vertex(2)));
  1151. cdt.insert_constraint(P.to_2d(itri->vertex(2)),P.to_2d(itri->vertex(0)));
  1152. } else if(const std::vector<Point_3 > *polyp =
  1153. CGAL::object_cast< std::vector<Point_3 > >(&obj))
  1154. {
  1155. //cerr<<REDRUM("Poly...")<<endl;
  1156. const std::vector<Point_3 > & poly = *polyp;
  1157. const Index m = poly.size();
  1158. assert(m>=2);
  1159. for(Index p = 0;p<m;p++)
  1160. {
  1161. const Index np = (p+1)%m;
  1162. cdt.insert_constraint(P.to_2d(poly[p]),P.to_2d(poly[np]));
  1163. }
  1164. }else
  1165. {
  1166. cerr<<REDRUM("What is this object?!")<<endl;
  1167. assert(false);
  1168. }
  1169. }
  1170. }
  1171. template <
  1172. typename Kernel,
  1173. typename DerivedV,
  1174. typename DerivedF,
  1175. typename DerivedVV,
  1176. typename DerivedFF,
  1177. typename DerivedIF,
  1178. typename DerivedJ,
  1179. typename DerivedIM>
  1180. inline
  1181. void
  1182. igl::SelfIntersectMesh<
  1183. Kernel,
  1184. DerivedV,
  1185. DerivedF,
  1186. DerivedVV,
  1187. DerivedFF,
  1188. DerivedIF,
  1189. DerivedJ,
  1190. DerivedIM>::to_output_type(
  1191. const typename Kernel::FT & cgal,
  1192. double & d)
  1193. {
  1194. d = CGAL::to_double(cgal);
  1195. }
  1196. template <
  1197. typename Kernel,
  1198. typename DerivedV,
  1199. typename DerivedF,
  1200. typename DerivedVV,
  1201. typename DerivedFF,
  1202. typename DerivedIF,
  1203. typename DerivedJ,
  1204. typename DerivedIM>
  1205. inline
  1206. void
  1207. igl::SelfIntersectMesh<
  1208. Kernel,
  1209. DerivedV,
  1210. DerivedF,
  1211. DerivedVV,
  1212. DerivedFF,
  1213. DerivedIF,
  1214. DerivedJ,
  1215. DerivedIM>::to_output_type(
  1216. const typename CGAL::Epeck::FT & cgal,
  1217. CGAL::Epeck::FT & d)
  1218. {
  1219. d = cgal;
  1220. }
  1221. #endif