SelfIntersectMesh.h 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  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_COPYLEFT_CGAL_SELFINTERSECTMESH_H
  9. #define IGL_COPYLEFT_CGAL_SELFINTERSECTMESH_H
  10. #include "CGAL_includes.hpp"
  11. #include "RemeshSelfIntersectionsParam.h"
  12. #include "../../unique.h"
  13. #include <Eigen/Dense>
  14. #include <list>
  15. #include <map>
  16. #include <vector>
  17. #include <thread>
  18. #include <mutex>
  19. //#define IGL_SELFINTERSECTMESH_DEBUG
  20. #ifndef IGL_FIRST_HIT_EXCEPTION
  21. #define IGL_FIRST_HIT_EXCEPTION 10
  22. #endif
  23. // The easiest way to keep track of everything is to use a class
  24. namespace igl
  25. {
  26. namespace copyleft
  27. {
  28. namespace cgal
  29. {
  30. // Kernel is a CGAL kernel like:
  31. // CGAL::Exact_predicates_inexact_constructions_kernel
  32. // or
  33. // CGAL::Exact_predicates_exact_constructions_kernel
  34. template <
  35. typename Kernel,
  36. typename DerivedV,
  37. typename DerivedF,
  38. typename DerivedVV,
  39. typename DerivedFF,
  40. typename DerivedIF,
  41. typename DerivedJ,
  42. typename DerivedIM>
  43. class SelfIntersectMesh
  44. {
  45. typedef
  46. SelfIntersectMesh<
  47. Kernel,
  48. DerivedV,
  49. DerivedF,
  50. DerivedVV,
  51. DerivedFF,
  52. DerivedIF,
  53. DerivedJ,
  54. DerivedIM> Self;
  55. public:
  56. // 3D Primitives
  57. typedef CGAL::Point_3<Kernel> Point_3;
  58. typedef CGAL::Segment_3<Kernel> Segment_3;
  59. typedef CGAL::Triangle_3<Kernel> Triangle_3;
  60. typedef CGAL::Plane_3<Kernel> Plane_3;
  61. typedef CGAL::Tetrahedron_3<Kernel> Tetrahedron_3;
  62. //typedef CGAL::Polyhedron_3<Kernel> Polyhedron_3;
  63. //typedef CGAL::Nef_polyhedron_3<Kernel> Nef_polyhedron_3;
  64. // 2D Primitives
  65. typedef CGAL::Point_2<Kernel> Point_2;
  66. typedef CGAL::Segment_2<Kernel> Segment_2;
  67. typedef CGAL::Triangle_2<Kernel> Triangle_2;
  68. // 2D Constrained Delaunay Triangulation types
  69. //typedef CGAL::Triangulation_vertex_base_2<Kernel> TVB_2;
  70. //typedef CGAL::Constrained_triangulation_face_base_2<Kernel> CTFB_2;
  71. //typedef CGAL::Triangulation_data_structure_2<TVB_2,CTFB_2> TDS_2;
  72. typedef CGAL::Exact_intersections_tag Itag;
  73. // Axis-align boxes for all-pairs self-intersection detection
  74. typedef std::vector<Triangle_3> Triangles;
  75. typedef typename Triangles::iterator TrianglesIterator;
  76. typedef typename Triangles::const_iterator TrianglesConstIterator;
  77. typedef
  78. CGAL::Box_intersection_d::Box_with_handle_d<double,3,TrianglesIterator>
  79. Box;
  80. // Input mesh
  81. const Eigen::PlainObjectBase<DerivedV> & V;
  82. const Eigen::PlainObjectBase<DerivedF> & F;
  83. // Number of self-intersecting triangle pairs
  84. typedef typename DerivedF::Index Index;
  85. Index count;
  86. typedef std::vector<std::pair<Index, CGAL::Object>> ObjectList;
  87. // Using a vector here makes this **not** output sensitive
  88. Triangles T;
  89. typedef std::vector<Index> IndexList;
  90. IndexList lIF;
  91. // #F-long list of faces with intersections mapping to the order in
  92. // which they were first found
  93. std::map<Index,ObjectList> offending;
  94. // Make a short name for the edge map's key
  95. typedef std::pair<Index,Index> EMK;
  96. // Make a short name for the type stored at each edge, the edge map's
  97. // value
  98. typedef std::vector<Index> EMV;
  99. // Make a short name for the edge map
  100. typedef std::map<EMK,EMV> EdgeMap;
  101. // Maps edges of offending faces to all incident offending faces
  102. //EdgeMap edge2faces;
  103. std::vector<std::pair<const Box, const Box> > candidate_box_pairs;
  104. public:
  105. RemeshSelfIntersectionsParam params;
  106. public:
  107. // Constructs (VV,FF) a new mesh with self-intersections of (V,F)
  108. // subdivided
  109. //
  110. // See also: remesh_self_intersections.h
  111. inline SelfIntersectMesh(
  112. const Eigen::PlainObjectBase<DerivedV> & V,
  113. const Eigen::PlainObjectBase<DerivedF> & F,
  114. const RemeshSelfIntersectionsParam & params,
  115. Eigen::PlainObjectBase<DerivedVV> & VV,
  116. Eigen::PlainObjectBase<DerivedFF> & FF,
  117. Eigen::PlainObjectBase<DerivedIF> & IF,
  118. Eigen::PlainObjectBase<DerivedJ> & J,
  119. Eigen::PlainObjectBase<DerivedIM> & IM);
  120. private:
  121. // Helper function to mark a face as offensive
  122. //
  123. // Inputs:
  124. // f index of face in F
  125. inline void mark_offensive(const Index f);
  126. // Helper function to count intersections between faces
  127. //
  128. // Input:
  129. // fa index of face A in F
  130. // fb index of face B in F
  131. inline void count_intersection( const Index fa, const Index fb);
  132. // Helper function for box_intersect. Intersect two triangles A and B,
  133. // append the intersection object (point,segment,triangle) to a running
  134. // list for A and B
  135. //
  136. // Inputs:
  137. // A triangle in 3D
  138. // B triangle in 3D
  139. // fa index of A in F (and key into offending)
  140. // fb index of B in F (and key into offending)
  141. // Returns true only if A intersects B
  142. //
  143. inline bool intersect(
  144. const Triangle_3 & A,
  145. const Triangle_3 & B,
  146. const Index fa,
  147. const Index fb);
  148. // Helper function for box_intersect. In the case where A and B have
  149. // already been identified to share a vertex, then we only want to add
  150. // possible segment intersections. Assumes truly duplicate triangles are
  151. // not given as input
  152. //
  153. // Inputs:
  154. // A triangle in 3D
  155. // B triangle in 3D
  156. // fa index of A in F (and key into offending)
  157. // fb index of B in F (and key into offending)
  158. // va index of shared vertex in A (and key into offending)
  159. // vb index of shared vertex in B (and key into offending)
  160. //// Returns object of intersection (should be Segment or point)
  161. // Returns true if intersection (besides shared point)
  162. //
  163. inline bool single_shared_vertex(
  164. const Triangle_3 & A,
  165. const Triangle_3 & B,
  166. const Index fa,
  167. const Index fb,
  168. const Index va,
  169. const Index vb);
  170. // Helper handling one direction
  171. inline bool single_shared_vertex(
  172. const Triangle_3 & A,
  173. const Triangle_3 & B,
  174. const Index fa,
  175. const Index fb,
  176. const Index va);
  177. // Helper function for box_intersect. In the case where A and B have
  178. // already been identified to share two vertices, then we only want to add
  179. // a possible coplanar (Triangle) intersection. Assumes truly degenerate
  180. // facets are not givin as input.
  181. inline bool double_shared_vertex(
  182. const Triangle_3 & A,
  183. const Triangle_3 & B,
  184. const Index fa,
  185. const Index fb,
  186. const std::vector<std::pair<Index,Index> > shared);
  187. public:
  188. // Callback function called during box self intersections test. Means
  189. // boxes a and b intersect. This method then checks if the triangles in
  190. // each box intersect and if so, then processes the intersections
  191. //
  192. // Inputs:
  193. // a box containing a triangle
  194. // b box containing a triangle
  195. inline void box_intersect(const Box& a, const Box& b);
  196. inline void process_intersecting_boxes();
  197. public:
  198. // Getters:
  199. //const IndexList& get_lIF() const{ return lIF;}
  200. static inline void box_intersect_static(
  201. SelfIntersectMesh * SIM,
  202. const Box &a,
  203. const Box &b);
  204. private:
  205. std::mutex m_offending_lock;
  206. };
  207. }
  208. }
  209. }
  210. // Implementation
  211. #include "mesh_to_cgal_triangle_list.h"
  212. #include "remesh_intersections.h"
  213. #include "../../REDRUM.h"
  214. #include "../../get_seconds.h"
  215. #include "../../C_STR.h"
  216. #include <functional>
  217. #include <algorithm>
  218. #include <exception>
  219. #include <cassert>
  220. #include <iostream>
  221. // References:
  222. // http://minregret.googlecode.com/svn/trunk/skyline/src/extern/CGAL-3.3.1/examples/Polyhedron/polyhedron_self_intersection.cpp
  223. // http://www.cgal.org/Manual/3.9/examples/Boolean_set_operations_2/do_intersect.cpp
  224. // Q: Should we be using CGAL::Polyhedron_3?
  225. // A: No! Input is just a list of unoriented triangles. Polyhedron_3 requires
  226. // a 2-manifold.
  227. // A: But! It seems we could use CGAL::Triangulation_3. Though it won't be easy
  228. // to take advantage of functions like insert_in_facet because we want to
  229. // constrain segments. Hmmm. Actualy Triangulation_3 doesn't look right...
  230. //static void box_intersect(SelfIntersectMesh * SIM,const Box & A, const Box & B)
  231. //{
  232. // return SIM->box_intersect(A,B);
  233. //}
  234. // CGAL's box_self_intersection_d uses C-style function callbacks without
  235. // userdata. This is a leapfrog method for calling a member function. It should
  236. // be bound as if the prototype was:
  237. // static void box_intersect(const Box &a, const Box &b)
  238. // using boost:
  239. // boost::function<void(const Box &a,const Box &b)> cb
  240. // = boost::bind(&::box_intersect, this, _1,_2);
  241. //
  242. template <
  243. typename Kernel,
  244. typename DerivedV,
  245. typename DerivedF,
  246. typename DerivedVV,
  247. typename DerivedFF,
  248. typename DerivedIF,
  249. typename DerivedJ,
  250. typename DerivedIM>
  251. inline void igl::copyleft::cgal::SelfIntersectMesh<
  252. Kernel,
  253. DerivedV,
  254. DerivedF,
  255. DerivedVV,
  256. DerivedFF,
  257. DerivedIF,
  258. DerivedJ,
  259. DerivedIM>::box_intersect_static(
  260. Self * SIM,
  261. const typename Self::Box &a,
  262. const typename Self::Box &b)
  263. {
  264. SIM->box_intersect(a,b);
  265. }
  266. template <
  267. typename Kernel,
  268. typename DerivedV,
  269. typename DerivedF,
  270. typename DerivedVV,
  271. typename DerivedFF,
  272. typename DerivedIF,
  273. typename DerivedJ,
  274. typename DerivedIM>
  275. inline igl::copyleft::cgal::SelfIntersectMesh<
  276. Kernel,
  277. DerivedV,
  278. DerivedF,
  279. DerivedVV,
  280. DerivedFF,
  281. DerivedIF,
  282. DerivedJ,
  283. DerivedIM>::SelfIntersectMesh(
  284. const Eigen::PlainObjectBase<DerivedV> & V,
  285. const Eigen::PlainObjectBase<DerivedF> & F,
  286. const RemeshSelfIntersectionsParam & params,
  287. Eigen::PlainObjectBase<DerivedVV> & VV,
  288. Eigen::PlainObjectBase<DerivedFF> & FF,
  289. Eigen::PlainObjectBase<DerivedIF> & IF,
  290. Eigen::PlainObjectBase<DerivedJ> & J,
  291. Eigen::PlainObjectBase<DerivedIM> & IM):
  292. V(V),
  293. F(F),
  294. count(0),
  295. T(),
  296. lIF(),
  297. offending(),
  298. //edge2faces(),
  299. params(params)
  300. {
  301. using namespace std;
  302. using namespace Eigen;
  303. #ifdef IGL_SELFINTERSECTMESH_DEBUG
  304. const auto & tictoc = []() -> double
  305. {
  306. static double t_start = igl::get_seconds();
  307. double diff = igl::get_seconds()-t_start;
  308. t_start += diff;
  309. return diff;
  310. };
  311. const auto log_time = [&](const std::string& label) -> void{
  312. std::cout << "SelfIntersectMesh." << label << ": "
  313. << tictoc() << std::endl;
  314. };
  315. tictoc();
  316. #endif
  317. // Compute and process self intersections
  318. mesh_to_cgal_triangle_list(V,F,T);
  319. #ifdef IGL_SELFINTERSECTMESH_DEBUG
  320. log_time("convert_to_triangle_list");
  321. #endif
  322. // http://www.cgal.org/Manual/latest/doc_html/cgal_manual/Box_intersection_d/Chapter_main.html#Section_63.5
  323. // Create the corresponding vector of bounding boxes
  324. std::vector<Box> boxes;
  325. boxes.reserve(T.size());
  326. for (
  327. TrianglesIterator tit = T.begin();
  328. tit != T.end();
  329. ++tit)
  330. {
  331. if (!tit->is_degenerate())
  332. {
  333. boxes.push_back(Box(tit->bbox(), tit));
  334. }
  335. }
  336. // Leapfrog callback
  337. std::function<void(const Box &a,const Box &b)> cb =
  338. std::bind(&box_intersect_static, this,
  339. // Explicitly use std namespace to avoid confusion with boost (who puts
  340. // _1 etc. in global namespace)
  341. std::placeholders::_1,
  342. std::placeholders::_2);
  343. #ifdef IGL_SELFINTERSECTMESH_DEBUG
  344. log_time("box_and_bind");
  345. #endif
  346. // Run the self intersection algorithm with all defaults
  347. CGAL::box_self_intersection_d(boxes.begin(), boxes.end(),cb);
  348. #ifdef IGL_SELFINTERSECTMESH_DEBUG
  349. log_time("box_intersection_d");
  350. #endif
  351. try{
  352. process_intersecting_boxes();
  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. log_time("resolve_intersection");
  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. log_time("store_intersecting_face_pairs");
  384. #endif
  385. if(params.detect_only)
  386. {
  387. return;
  388. }
  389. remesh_intersections(
  390. V,F,T,offending,params.stitch_all,VV,FF,J,IM);
  391. #ifdef IGL_SELFINTERSECTMESH_DEBUG
  392. log_time("remesh_intersection");
  393. #endif
  394. }
  395. template <
  396. typename Kernel,
  397. typename DerivedV,
  398. typename DerivedF,
  399. typename DerivedVV,
  400. typename DerivedFF,
  401. typename DerivedIF,
  402. typename DerivedJ,
  403. typename DerivedIM>
  404. inline void igl::copyleft::cgal::SelfIntersectMesh<
  405. Kernel,
  406. DerivedV,
  407. DerivedF,
  408. DerivedVV,
  409. DerivedFF,
  410. DerivedIF,
  411. DerivedJ,
  412. DerivedIM>::mark_offensive(const Index f)
  413. {
  414. using namespace std;
  415. lIF.push_back(f);
  416. if(offending.count(f) == 0)
  417. {
  418. // first time marking, initialize with new id and empty list
  419. offending[f] = {};
  420. for(Index e = 0; e<3;e++)
  421. {
  422. // append face to edge's list
  423. Index i = F(f,(e+1)%3) < F(f,(e+2)%3) ? F(f,(e+1)%3) : F(f,(e+2)%3);
  424. Index j = F(f,(e+1)%3) < F(f,(e+2)%3) ? F(f,(e+2)%3) : F(f,(e+1)%3);
  425. //edge2faces[EMK(i,j)].push_back(f);
  426. }
  427. }
  428. }
  429. template <
  430. typename Kernel,
  431. typename DerivedV,
  432. typename DerivedF,
  433. typename DerivedVV,
  434. typename DerivedFF,
  435. typename DerivedIF,
  436. typename DerivedJ,
  437. typename DerivedIM>
  438. inline void igl::copyleft::cgal::SelfIntersectMesh<
  439. Kernel,
  440. DerivedV,
  441. DerivedF,
  442. DerivedVV,
  443. DerivedFF,
  444. DerivedIF,
  445. DerivedJ,
  446. DerivedIM>::count_intersection(
  447. const Index fa,
  448. const Index fb)
  449. {
  450. std::lock_guard<std::mutex> guard(m_offending_lock);
  451. mark_offensive(fa);
  452. mark_offensive(fb);
  453. this->count++;
  454. // We found the first intersection
  455. if(params.first_only && this->count >= 1)
  456. {
  457. throw IGL_FIRST_HIT_EXCEPTION;
  458. }
  459. }
  460. template <
  461. typename Kernel,
  462. typename DerivedV,
  463. typename DerivedF,
  464. typename DerivedVV,
  465. typename DerivedFF,
  466. typename DerivedIF,
  467. typename DerivedJ,
  468. typename DerivedIM>
  469. inline bool igl::copyleft::cgal::SelfIntersectMesh<
  470. Kernel,
  471. DerivedV,
  472. DerivedF,
  473. DerivedVV,
  474. DerivedFF,
  475. DerivedIF,
  476. DerivedJ,
  477. DerivedIM>::intersect(
  478. const Triangle_3 & A,
  479. const Triangle_3 & B,
  480. const Index fa,
  481. const Index fb)
  482. {
  483. // Determine whether there is an intersection
  484. if(!CGAL::do_intersect(A,B))
  485. {
  486. return false;
  487. }
  488. count_intersection(fa,fb);
  489. if(!params.detect_only)
  490. {
  491. // Construct intersection
  492. CGAL::Object result = CGAL::intersection(A,B);
  493. std::lock_guard<std::mutex> guard(m_offending_lock);
  494. offending[fa].push_back({fb, result});
  495. offending[fb].push_back({fa, result});
  496. }
  497. return true;
  498. }
  499. template <
  500. typename Kernel,
  501. typename DerivedV,
  502. typename DerivedF,
  503. typename DerivedVV,
  504. typename DerivedFF,
  505. typename DerivedIF,
  506. typename DerivedJ,
  507. typename DerivedIM>
  508. inline bool igl::copyleft::cgal::SelfIntersectMesh<
  509. Kernel,
  510. DerivedV,
  511. DerivedF,
  512. DerivedVV,
  513. DerivedFF,
  514. DerivedIF,
  515. DerivedJ,
  516. DerivedIM>::single_shared_vertex(
  517. const Triangle_3 & A,
  518. const Triangle_3 & B,
  519. const Index fa,
  520. const Index fb,
  521. const Index va,
  522. const Index vb)
  523. {
  524. ////using namespace std;
  525. //CGAL::Object result = CGAL::intersection(A,B);
  526. //if(CGAL::object_cast<Segment_3 >(&result))
  527. //{
  528. // // Append to each triangle's running list
  529. // F_objects[fa].push_back(result);
  530. // F_objects[fb].push_back(result);
  531. // count_intersection(fa,fb);
  532. //}else
  533. //{
  534. // // Then intersection must be at point
  535. // // And point must be at shared vertex
  536. // assert(CGAL::object_cast<Point_3>(&result));
  537. //}
  538. if(single_shared_vertex(A,B,fa,fb,va))
  539. {
  540. return true;
  541. }
  542. return single_shared_vertex(B,A,fb,fa,vb);
  543. }
  544. template <
  545. typename Kernel,
  546. typename DerivedV,
  547. typename DerivedF,
  548. typename DerivedVV,
  549. typename DerivedFF,
  550. typename DerivedIF,
  551. typename DerivedJ,
  552. typename DerivedIM>
  553. inline bool igl::copyleft::cgal::SelfIntersectMesh<
  554. Kernel,
  555. DerivedV,
  556. DerivedF,
  557. DerivedVV,
  558. DerivedFF,
  559. DerivedIF,
  560. DerivedJ,
  561. DerivedIM>::single_shared_vertex(
  562. const Triangle_3 & A,
  563. const Triangle_3 & B,
  564. const Index fa,
  565. const Index fb,
  566. const Index va)
  567. {
  568. // This was not a good idea. It will not handle coplanar triangles well.
  569. using namespace std;
  570. Segment_3 sa(
  571. A.vertex((va+1)%3),
  572. A.vertex((va+2)%3));
  573. if(CGAL::do_intersect(sa,B))
  574. {
  575. // can't put count_intersection(fa,fb) here since we use intersect below
  576. // and then it will be counted twice.
  577. if(params.detect_only)
  578. {
  579. count_intersection(fa,fb);
  580. return true;
  581. }
  582. CGAL::Object result = CGAL::intersection(sa,B);
  583. if(const Point_3 * p = CGAL::object_cast<Point_3 >(&result))
  584. {
  585. // Single intersection --> segment from shared point to intersection
  586. CGAL::Object seg = CGAL::make_object(Segment_3(
  587. A.vertex(va),
  588. *p));
  589. count_intersection(fa,fb);
  590. std::lock_guard<std::mutex> guard(m_offending_lock);
  591. offending[fa].push_back({fb, seg});
  592. offending[fb].push_back({fa, seg});
  593. return true;
  594. }else if(CGAL::object_cast<Segment_3 >(&result))
  595. {
  596. //cerr<<REDRUM("Coplanar at: "<<fa<<" & "<<fb<<" (single shared).")<<endl;
  597. // Must be coplanar
  598. // WRONG:
  599. //// Segment intersection --> triangle from shared point to intersection
  600. //CGAL::Object tri = CGAL::make_object(Triangle_3(
  601. // A.vertex(va),
  602. // s->vertex(0),
  603. // s->vertex(1)));
  604. //F_objects[fa].push_back(tri);
  605. //F_objects[fb].push_back(tri);
  606. //count_intersection(fa,fb);
  607. // Need to do full test. Intersection could be a general poly.
  608. bool test = intersect(A,B,fa,fb);
  609. ((void)test);
  610. assert(test && "intersect should agree with do_intersect");
  611. return true;
  612. }else
  613. {
  614. cerr<<REDRUM("Segment ∩ triangle neither point nor segment?")<<endl;
  615. assert(false);
  616. }
  617. }
  618. return false;
  619. }
  620. template <
  621. typename Kernel,
  622. typename DerivedV,
  623. typename DerivedF,
  624. typename DerivedVV,
  625. typename DerivedFF,
  626. typename DerivedIF,
  627. typename DerivedJ,
  628. typename DerivedIM>
  629. inline bool igl::copyleft::cgal::SelfIntersectMesh<
  630. Kernel,
  631. DerivedV,
  632. DerivedF,
  633. DerivedVV,
  634. DerivedFF,
  635. DerivedIF,
  636. DerivedJ,
  637. DerivedIM>::double_shared_vertex(
  638. const Triangle_3 & A,
  639. const Triangle_3 & B,
  640. const Index fa,
  641. const Index fb,
  642. const std::vector<std::pair<Index,Index> > shared)
  643. {
  644. using namespace std;
  645. // must be co-planar
  646. if(
  647. A.supporting_plane() != B.supporting_plane() &&
  648. A.supporting_plane() != B.supporting_plane().opposite())
  649. {
  650. return false;
  651. }
  652. // Since A and B are non-degenerate the intersection must be a polygon
  653. // (triangle). Either
  654. // - the vertex of A (B) opposite the shared edge of lies on B (A), or
  655. // - an edge of A intersects and edge of B without sharing a vertex
  656. // Determine if the vertex opposite edge (a0,a1) in triangle A lies in
  657. // (intersects) triangle B
  658. const auto & opposite_point_inside = [](
  659. const Triangle_3 & A, const Index a0, const Index a1, const Triangle_3 & B)
  660. -> bool
  661. {
  662. // get opposite index
  663. Index a2 = -1;
  664. for(int c = 0;c<3;c++)
  665. {
  666. if(c != a0 && c != a1)
  667. {
  668. a2 = c;
  669. break;
  670. }
  671. }
  672. assert(a2 != -1);
  673. bool ret = CGAL::do_intersect(A.vertex(a2),B);
  674. //cout<<"opposite_point_inside: "<<ret<<endl;
  675. return ret;
  676. };
  677. // Determine if edge opposite vertex va in triangle A intersects edge
  678. // opposite vertex vb in triangle B.
  679. const auto & opposite_edges_intersect = [](
  680. const Triangle_3 & A, const Index va,
  681. const Triangle_3 & B, const Index vb) -> bool
  682. {
  683. Segment_3 sa( A.vertex((va+1)%3), A.vertex((va+2)%3));
  684. Segment_3 sb( B.vertex((vb+1)%3), B.vertex((vb+2)%3));
  685. //cout<<sa<<endl;
  686. //cout<<sb<<endl;
  687. bool ret = CGAL::do_intersect(sa,sb);
  688. //cout<<"opposite_edges_intersect: "<<ret<<endl;
  689. return ret;
  690. };
  691. if(
  692. !opposite_point_inside(A,shared[0].first,shared[1].first,B) &&
  693. !opposite_point_inside(B,shared[0].second,shared[1].second,A) &&
  694. !opposite_edges_intersect(A,shared[0].first,B,shared[1].second) &&
  695. !opposite_edges_intersect(A,shared[1].first,B,shared[0].second))
  696. {
  697. return false;
  698. }
  699. // there is an intersection indeed
  700. count_intersection(fa,fb);
  701. if(params.detect_only)
  702. {
  703. return true;
  704. }
  705. // Construct intersection
  706. try
  707. {
  708. // This can fail for Epick but not Epeck
  709. CGAL::Object result = CGAL::intersection(A,B);
  710. if(!result.empty())
  711. {
  712. if(CGAL::object_cast<Segment_3 >(&result))
  713. {
  714. // not coplanar
  715. assert(false &&
  716. "Co-planar non-degenerate triangles should intersect over triangle");
  717. return false;
  718. } else if(CGAL::object_cast<Point_3 >(&result))
  719. {
  720. // this "shouldn't" happen but does for inexact
  721. assert(false &&
  722. "Co-planar non-degenerate triangles should intersect over triangle");
  723. return false;
  724. } else
  725. {
  726. // Triangle object
  727. std::lock_guard<std::mutex> guard(m_offending_lock);
  728. offending[fa].push_back({fb, result});
  729. offending[fb].push_back({fa, result});
  730. //cerr<<REDRUM("Coplanar at: "<<fa<<" & "<<fb<<" (double shared).")<<endl;
  731. return true;
  732. }
  733. }else
  734. {
  735. // CGAL::intersection is disagreeing with do_intersect
  736. assert(false && "CGAL::intersection should agree with predicate tests");
  737. return false;
  738. }
  739. }catch(...)
  740. {
  741. // This catches some cgal assertion:
  742. // CGAL error: assertion violation!
  743. // Expression : is_finite(d)
  744. // File : /opt/local/include/CGAL/GMP/Gmpq_type.h
  745. // Line : 132
  746. // Explanation:
  747. // But only if NDEBUG is not defined, otherwise there's an uncaught
  748. // "Floating point exception: 8" SIGFPE
  749. return false;
  750. }
  751. // No intersection.
  752. return false;
  753. }
  754. template <
  755. typename Kernel,
  756. typename DerivedV,
  757. typename DerivedF,
  758. typename DerivedVV,
  759. typename DerivedFF,
  760. typename DerivedIF,
  761. typename DerivedJ,
  762. typename DerivedIM>
  763. inline void igl::copyleft::cgal::SelfIntersectMesh<
  764. Kernel,
  765. DerivedV,
  766. DerivedF,
  767. DerivedVV,
  768. DerivedFF,
  769. DerivedIF,
  770. DerivedJ,
  771. DerivedIM>::box_intersect(
  772. const Box& a,
  773. const Box& b)
  774. {
  775. candidate_box_pairs.push_back({a, b});
  776. }
  777. template <
  778. typename Kernel,
  779. typename DerivedV,
  780. typename DerivedF,
  781. typename DerivedVV,
  782. typename DerivedFF,
  783. typename DerivedIF,
  784. typename DerivedJ,
  785. typename DerivedIM>
  786. inline void igl::copyleft::cgal::SelfIntersectMesh<
  787. Kernel,
  788. DerivedV,
  789. DerivedF,
  790. DerivedVV,
  791. DerivedFF,
  792. DerivedIF,
  793. DerivedJ,
  794. DerivedIM>::process_intersecting_boxes()
  795. {
  796. std::vector<std::mutex> triangle_locks(T.size());
  797. std::vector<std::mutex> vertex_locks(V.rows());
  798. std::mutex index_lock;
  799. std::mutex exception_mutex;
  800. bool exception_fired = false;
  801. int exception = -1;
  802. auto process_chunk =
  803. [&](
  804. const size_t first,
  805. const size_t last) -> void
  806. {
  807. try
  808. {
  809. assert(last >= first);
  810. for (size_t i=first; i<last; i++)
  811. {
  812. if(exception_fired) return;
  813. Index fa=T.size(), fb=T.size();
  814. {
  815. // Before knowing which triangles are involved, we need to lock
  816. // everything to prevent race condition in updating reference counters.
  817. std::lock_guard<std::mutex> guard(index_lock);
  818. const auto& box_pair = candidate_box_pairs[i];
  819. const auto& a = box_pair.first;
  820. const auto& b = box_pair.second;
  821. fa = a.handle()-T.begin();
  822. fb = b.handle()-T.begin();
  823. }
  824. assert(fa < T.size());
  825. assert(fb < T.size());
  826. // Lock triangles
  827. std::lock_guard<std::mutex> guard_A(triangle_locks[fa]);
  828. std::lock_guard<std::mutex> guard_B(triangle_locks[fb]);
  829. // Lock vertices
  830. std::list<std::lock_guard<std::mutex> > guard_vertices;
  831. {
  832. std::vector<typename DerivedF::Scalar> unique_vertices;
  833. std::vector<size_t> tmp1, tmp2;
  834. igl::unique({F(fa,0), F(fa,1), F(fa,2), F(fb,0), F(fb,1), F(fb,2)},
  835. unique_vertices, tmp1, tmp2);
  836. std::for_each(unique_vertices.begin(), unique_vertices.end(),
  837. [&](const typename DerivedF::Scalar& vi) {
  838. guard_vertices.emplace_back(vertex_locks[vi]);
  839. });
  840. }
  841. if(exception_fired) return;
  842. const Triangle_3& A = T[fa];
  843. const Triangle_3& B = T[fb];
  844. // Number of combinatorially shared vertices
  845. Index comb_shared_vertices = 0;
  846. // Number of geometrically shared vertices (*not* including combinatorially
  847. // shared)
  848. Index geo_shared_vertices = 0;
  849. // Keep track of shared vertex indices
  850. std::vector<std::pair<Index,Index> > shared;
  851. Index ea,eb;
  852. for(ea=0;ea<3;ea++)
  853. {
  854. for(eb=0;eb<3;eb++)
  855. {
  856. if(F(fa,ea) == F(fb,eb))
  857. {
  858. comb_shared_vertices++;
  859. shared.emplace_back(ea,eb);
  860. }else if(A.vertex(ea) == B.vertex(eb))
  861. {
  862. geo_shared_vertices++;
  863. shared.emplace_back(ea,eb);
  864. }
  865. }
  866. }
  867. const Index total_shared_vertices = comb_shared_vertices + geo_shared_vertices;
  868. if(exception_fired) return;
  869. if(comb_shared_vertices== 3)
  870. {
  871. assert(shared.size() == 3);
  872. //// Combinatorially duplicate face, these should be removed by preprocessing
  873. //cerr<<REDRUM("Facets "<<fa<<" and "<<fb<<" are combinatorial duplicates")<<endl;
  874. continue;
  875. }
  876. if(total_shared_vertices== 3)
  877. {
  878. assert(shared.size() == 3);
  879. //// Geometrically duplicate face, these should be removed by preprocessing
  880. //cerr<<REDRUM("Facets "<<fa<<" and "<<fb<<" are geometrical duplicates")<<endl;
  881. continue;
  882. }
  883. if(total_shared_vertices == 2)
  884. {
  885. assert(shared.size() == 2);
  886. // Q: What about coplanar?
  887. //
  888. // o o
  889. // |\ /|
  890. // | \/ |
  891. // | /\ |
  892. // |/ \|
  893. // o----o
  894. double_shared_vertex(A,B,fa,fb,shared);
  895. continue;
  896. }
  897. assert(total_shared_vertices<=1);
  898. if(total_shared_vertices==1)
  899. {
  900. single_shared_vertex(A,B,fa,fb,shared[0].first,shared[0].second);
  901. }else
  902. {
  903. intersect(A,B,fa,fb);
  904. }
  905. }
  906. }catch(int e)
  907. {
  908. std::lock_guard<std::mutex> exception_lock(exception_mutex);
  909. exception_fired = true;
  910. exception = e;
  911. }
  912. };
  913. size_t num_threads=0;
  914. const size_t hardware_limit = std::thread::hardware_concurrency();
  915. if (const char* igl_num_threads = std::getenv("LIBIGL_NUM_THREADS")) {
  916. num_threads = atoi(igl_num_threads);
  917. }
  918. if (num_threads == 0 || num_threads > hardware_limit) {
  919. num_threads = hardware_limit;
  920. }
  921. assert(num_threads > 0);
  922. const size_t num_pairs = candidate_box_pairs.size();
  923. const size_t chunk_size = num_pairs / num_threads;
  924. std::vector<std::thread> threads;
  925. for (size_t i=0; i<num_threads-1; i++)
  926. {
  927. threads.emplace_back(process_chunk, i*chunk_size, (i+1)*chunk_size);
  928. }
  929. // Do some work in the master thread.
  930. process_chunk((num_threads-1)*chunk_size, num_pairs);
  931. for (auto& t : threads)
  932. {
  933. if (t.joinable()) t.join();
  934. }
  935. if(exception_fired) throw exception;
  936. //process_chunk(0, candidate_box_pairs.size());
  937. }
  938. #endif