SelfIntersectMesh.h 33 KB

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