closest_facet.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. // This file is part of libigl, a simple c++ geometry processing library.
  2. //
  3. // Copyright (C) 2015 Qingnan Zhou <qnzhou@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. //
  9. #include "closest_facet.h"
  10. #include <vector>
  11. #include <stdexcept>
  12. #include <unordered_map>
  13. #include <CGAL/AABB_tree.h>
  14. #include <CGAL/AABB_traits.h>
  15. #include <CGAL/AABB_triangle_primitive.h>
  16. #include <CGAL/intersections.h>
  17. #include <CGAL/Exact_predicates_exact_constructions_kernel.h>
  18. #include "order_facets_around_edge.h"
  19. #include "../../vertex_triangle_adjacency.h"
  20. #include "../../writePLY.h"
  21. template<
  22. typename DerivedV,
  23. typename DerivedF,
  24. typename DerivedI,
  25. typename DerivedP,
  26. typename uE2EType,
  27. typename DerivedEMAP,
  28. typename DerivedR,
  29. typename DerivedS >
  30. IGL_INLINE void igl::copyleft::cgal::closest_facet(
  31. const Eigen::PlainObjectBase<DerivedV>& V,
  32. const Eigen::PlainObjectBase<DerivedF>& F,
  33. const Eigen::PlainObjectBase<DerivedI>& I,
  34. const Eigen::PlainObjectBase<DerivedP>& P,
  35. const std::vector<std::vector<uE2EType> >& uE2E,
  36. const Eigen::PlainObjectBase<DerivedEMAP>& EMAP,
  37. Eigen::PlainObjectBase<DerivedR>& R,
  38. Eigen::PlainObjectBase<DerivedS>& S) {
  39. typedef CGAL::Exact_predicates_exact_constructions_kernel Kernel;
  40. typedef Kernel::Point_3 Point_3;
  41. typedef Kernel::Plane_3 Plane_3;
  42. typedef Kernel::Segment_3 Segment_3;
  43. typedef Kernel::Triangle_3 Triangle;
  44. typedef std::vector<Triangle>::iterator Iterator;
  45. typedef CGAL::AABB_triangle_primitive<Kernel, Iterator> Primitive;
  46. typedef CGAL::AABB_traits<Kernel, Primitive> AABB_triangle_traits;
  47. typedef CGAL::AABB_tree<AABB_triangle_traits> Tree;
  48. if (F.rows() <= 0 || I.rows() <= 0) {
  49. throw std::runtime_error(
  50. "Closest facet cannot be computed on empty mesh.");
  51. }
  52. std::vector<std::vector<size_t> > VF;
  53. std::vector<std::vector<size_t> > VFi;
  54. igl::vertex_triangle_adjacency(V, F, VF, VFi);
  55. std::vector<bool> in_I(F.rows(), false);
  56. const size_t num_faces = I.rows();
  57. std::vector<Triangle> triangles;
  58. for (size_t i=0; i<num_faces; i++) {
  59. const Eigen::Vector3i f = F.row(I(i, 0));
  60. in_I[I(i,0)] = true;
  61. triangles.emplace_back(
  62. Point_3(V(f[0], 0), V(f[0], 1), V(f[0], 2)),
  63. Point_3(V(f[1], 0), V(f[1], 1), V(f[1], 2)),
  64. Point_3(V(f[2], 0), V(f[2], 1), V(f[2], 2)));
  65. if (triangles.back().is_degenerate()) {
  66. throw std::runtime_error(
  67. "Input facet components contains degenerated triangles");
  68. }
  69. }
  70. Tree tree(triangles.begin(), triangles.end());
  71. tree.accelerate_distance_queries();
  72. auto on_the_positive_side = [&](size_t fid, const Point_3& p) {
  73. const auto& f = F.row(fid).eval();
  74. Point_3 v0(V(f[0], 0), V(f[0], 1), V(f[0], 2));
  75. Point_3 v1(V(f[1], 0), V(f[1], 1), V(f[1], 2));
  76. Point_3 v2(V(f[2], 0), V(f[2], 1), V(f[2], 2));
  77. auto ori = CGAL::orientation(v0, v1, v2, p);
  78. switch (ori) {
  79. case CGAL::POSITIVE:
  80. return true;
  81. case CGAL::NEGATIVE:
  82. return false;
  83. case CGAL::COPLANAR:
  84. throw std::runtime_error(
  85. "It seems input mesh contains self intersection");
  86. default:
  87. throw std::runtime_error("Unknown CGAL state.");
  88. }
  89. return false;
  90. };
  91. auto get_orientation = [&](size_t fid, size_t s, size_t d) -> bool {
  92. const auto& f = F.row(fid);
  93. if ((size_t)f[0] == s && (size_t)f[1] == d) return false;
  94. else if ((size_t)f[1] == s && (size_t)f[2] == d) return false;
  95. else if ((size_t)f[2] == s && (size_t)f[0] == d) return false;
  96. else if ((size_t)f[0] == d && (size_t)f[1] == s) return true;
  97. else if ((size_t)f[1] == d && (size_t)f[2] == s) return true;
  98. else if ((size_t)f[2] == d && (size_t)f[0] == s) return true;
  99. else {
  100. throw std::runtime_error(
  101. "Cannot compute orientation due to incorrect connectivity");
  102. return false;
  103. }
  104. };
  105. auto index_to_signed_index = [&](size_t index, bool ori) -> int{
  106. return (index+1) * (ori? 1:-1);
  107. };
  108. //auto signed_index_to_index = [&](int signed_index) -> size_t {
  109. // return abs(signed_index) - 1;
  110. //};
  111. enum ElementType { VERTEX, EDGE, FACE };
  112. auto determine_element_type = [&](const Point_3& p, const size_t fid,
  113. size_t& element_index) {
  114. const auto& tri = triangles[fid];
  115. const Point_3 p0 = tri[0];
  116. const Point_3 p1 = tri[1];
  117. const Point_3 p2 = tri[2];
  118. if (p == p0) { element_index = 0; return VERTEX; }
  119. if (p == p1) { element_index = 1; return VERTEX; }
  120. if (p == p2) { element_index = 2; return VERTEX; }
  121. if (CGAL::collinear(p0, p1, p)) { element_index = 2; return EDGE; }
  122. if (CGAL::collinear(p1, p2, p)) { element_index = 0; return EDGE; }
  123. if (CGAL::collinear(p2, p0, p)) { element_index = 1; return EDGE; }
  124. element_index = 0;
  125. return FACE;
  126. };
  127. auto process_edge_case = [&](
  128. size_t query_idx,
  129. const size_t s, const size_t d,
  130. size_t preferred_facet,
  131. bool& orientation) {
  132. Point_3 query_point(
  133. P(query_idx, 0),
  134. P(query_idx, 1),
  135. P(query_idx, 2));
  136. size_t corner_idx = std::numeric_limits<size_t>::max();
  137. if ((s == F(preferred_facet, 0) && d == F(preferred_facet, 1)) ||
  138. (s == F(preferred_facet, 1) && d == F(preferred_facet, 0))) {
  139. corner_idx = 2;
  140. } else if ((s == F(preferred_facet, 0) && d == F(preferred_facet, 2)) ||
  141. (s == F(preferred_facet, 2) && d == F(preferred_facet, 0))) {
  142. corner_idx = 1;
  143. } else if ((s == F(preferred_facet, 1) && d == F(preferred_facet, 2)) ||
  144. (s == F(preferred_facet, 2) && d == F(preferred_facet, 1))) {
  145. corner_idx = 0;
  146. } else {
  147. std::cerr << "s: " << s << "\t d:" << d << std::endl;
  148. std::cerr << F.row(preferred_facet) << std::endl;
  149. throw std::runtime_error(
  150. "Invalid connectivity, edge does not belong to facet");
  151. }
  152. auto ueid = EMAP(preferred_facet + corner_idx * F.rows());
  153. auto eids = uE2E[ueid];
  154. std::vector<size_t> intersected_face_indices;
  155. for (auto eid : eids) {
  156. const size_t fid = eid % F.rows();
  157. if (in_I[fid]) {
  158. intersected_face_indices.push_back(fid);
  159. }
  160. }
  161. const size_t num_intersected_faces = intersected_face_indices.size();
  162. std::vector<int> intersected_face_signed_indices(num_intersected_faces);
  163. std::transform(
  164. intersected_face_indices.begin(),
  165. intersected_face_indices.end(),
  166. intersected_face_signed_indices.begin(),
  167. [&](size_t index) {
  168. return index_to_signed_index(
  169. index, get_orientation(index, s,d));
  170. });
  171. assert(num_intersected_faces >= 1);
  172. if (num_intersected_faces == 1) {
  173. // The edge must be a boundary edge. Thus, the orientation can be
  174. // simply determined by checking if the query point is on the
  175. // positive side of the facet.
  176. const size_t fid = intersected_face_indices[0];
  177. orientation = on_the_positive_side(fid, query_point);
  178. return fid;
  179. }
  180. Eigen::VectorXi order;
  181. DerivedP pivot = P.row(query_idx).eval();
  182. igl::copyleft::cgal::order_facets_around_edge(V, F, s, d,
  183. intersected_face_signed_indices,
  184. pivot, order);
  185. // Although first and last are equivalent, make the choice based on
  186. // preferred_facet.
  187. const size_t first = order[0];
  188. const size_t last = order[num_intersected_faces-1];
  189. if (intersected_face_indices[first] == preferred_facet) {
  190. orientation = intersected_face_signed_indices[first] < 0;
  191. return intersected_face_indices[first];
  192. } else if (intersected_face_indices[last] == preferred_facet) {
  193. orientation = intersected_face_signed_indices[last] > 0;
  194. return intersected_face_indices[last];
  195. } else {
  196. orientation = intersected_face_signed_indices[order[0]] < 0;
  197. return intersected_face_indices[order[0]];
  198. }
  199. };
  200. auto process_face_case = [&](
  201. const size_t query_idx, const Point_3& closest_point,
  202. const size_t fid, bool& orientation) {
  203. const auto& f = F.row(I(fid, 0));
  204. return process_edge_case(query_idx, f[0], f[1], I(fid, 0), orientation);
  205. };
  206. auto process_vertex_case = [&](const size_t query_idx, size_t s,
  207. size_t preferred_facet, bool& orientation) {
  208. const Point_3 query_point(
  209. P(query_idx, 0), P(query_idx, 1), P(query_idx, 2));
  210. const Point_3 closest_point(V(s, 0), V(s, 1), V(s, 2));
  211. std::vector<size_t> adj_faces;
  212. std::vector<size_t> adj_face_corners;
  213. {
  214. // Gether adj faces to s within I.
  215. const auto& all_adj_faces = VF[s];
  216. const auto& all_adj_face_corners = VFi[s];
  217. const size_t num_all_adj_faces = all_adj_faces.size();
  218. for (size_t i=0; i<num_all_adj_faces; i++) {
  219. const size_t fid = all_adj_faces[i];
  220. if (in_I[fid]) {
  221. adj_faces.push_back(fid);
  222. adj_face_corners.push_back(all_adj_face_corners[i]);
  223. }
  224. }
  225. }
  226. const size_t num_adj_faces = adj_faces.size();
  227. assert(num_adj_faces > 0);
  228. std::set<size_t> adj_vertices_set;
  229. std::unordered_multimap<size_t, size_t> v2f;
  230. for (size_t i=0; i<num_adj_faces; i++) {
  231. const size_t fid = adj_faces[i];
  232. const size_t cid = adj_face_corners[i];
  233. const auto& f = F.row(adj_faces[i]);
  234. const size_t next = f[(cid+1)%3];
  235. const size_t prev = f[(cid+2)%3];
  236. adj_vertices_set.insert(next);
  237. adj_vertices_set.insert(prev);
  238. v2f.insert({{next, fid}, {prev, fid}});
  239. }
  240. const size_t num_adj_vertices = adj_vertices_set.size();
  241. std::vector<size_t> adj_vertices(num_adj_vertices);
  242. std::copy(adj_vertices_set.begin(), adj_vertices_set.end(),
  243. adj_vertices.begin());
  244. std::vector<Point_3> adj_points;
  245. for (size_t vid : adj_vertices) {
  246. adj_points.emplace_back(V(vid,0), V(vid,1), V(vid,2));
  247. }
  248. // A plane is on the exterior if all adj_points lies on or to
  249. // one side of the plane.
  250. auto is_on_exterior = [&](const Plane_3& separator) {
  251. size_t positive=0;
  252. size_t negative=0;
  253. size_t coplanar=0;
  254. for (const auto& point : adj_points) {
  255. switch(separator.oriented_side(point)) {
  256. case CGAL::ON_POSITIVE_SIDE:
  257. positive++;
  258. break;
  259. case CGAL::ON_NEGATIVE_SIDE:
  260. negative++;
  261. break;
  262. case CGAL::ON_ORIENTED_BOUNDARY:
  263. coplanar++;
  264. break;
  265. default:
  266. throw "Unknown plane-point orientation";
  267. }
  268. }
  269. auto query_orientation = separator.oriented_side(query_point);
  270. if (query_orientation == CGAL::ON_ORIENTED_BOUNDARY &&
  271. (positive == 0 && negative == 0)) {
  272. // All adj vertices and query point are coplanar.
  273. // In this case, all separators are equally valid.
  274. return true;
  275. } else {
  276. bool r = (positive == 0 && query_orientation == CGAL::POSITIVE)
  277. || (negative == 0 && query_orientation == CGAL::NEGATIVE);
  278. return r;
  279. }
  280. };
  281. size_t d = std::numeric_limits<size_t>::max();
  282. for (size_t i=0; i<num_adj_vertices; i++) {
  283. const size_t vi = adj_vertices[i];
  284. for (size_t j=i+1; j<num_adj_vertices; j++) {
  285. Plane_3 separator(closest_point, adj_points[i], adj_points[j]);
  286. if (separator.is_degenerate()) {
  287. continue;
  288. }
  289. if (is_on_exterior(separator)) {
  290. if (!CGAL::collinear(
  291. query_point, adj_points[i], closest_point)) {
  292. d = vi;
  293. break;
  294. } else {
  295. d = adj_vertices[j];
  296. assert(!CGAL::collinear(
  297. query_point, adj_points[j], closest_point));
  298. break;
  299. }
  300. }
  301. }
  302. }
  303. if (d == std::numeric_limits<size_t>::max()) {
  304. Eigen::MatrixXd tmp_vertices(V.rows(), V.cols());
  305. for (size_t i=0; i<V.rows(); i++) {
  306. for (size_t j=0; j<V.cols(); j++) {
  307. tmp_vertices(i,j) = CGAL::to_double(V(i,j));
  308. }
  309. }
  310. Eigen::MatrixXi tmp_faces(adj_faces.size(), 3);
  311. for (size_t i=0; i<adj_faces.size(); i++) {
  312. tmp_faces.row(i) = F.row(adj_faces[i]);
  313. }
  314. igl::writePLY("debug.ply", tmp_vertices, tmp_faces, false);
  315. throw std::runtime_error("Invalid vertex neighborhood");
  316. }
  317. const auto itr = v2f.equal_range(d);
  318. assert(itr.first != itr.second);
  319. return process_edge_case(query_idx, s, d, itr.first->second, orientation);
  320. };
  321. const size_t num_queries = P.rows();
  322. R.resize(num_queries, 1);
  323. S.resize(num_queries, 1);
  324. for (size_t i=0; i<num_queries; i++) {
  325. const Point_3 query(P(i,0), P(i,1), P(i,2));
  326. auto projection = tree.closest_point_and_primitive(query);
  327. const Point_3 closest_point = projection.first;
  328. size_t fid = projection.second - triangles.begin();
  329. bool fid_ori = false;
  330. // Gether all facets sharing the closest point.
  331. std::vector<Tree::Primitive_id> intersected_faces;
  332. tree.all_intersected_primitives(Segment_3(closest_point, query),
  333. std::back_inserter(intersected_faces));
  334. const size_t num_intersected_faces = intersected_faces.size();
  335. std::vector<size_t> intersected_face_indices(num_intersected_faces);
  336. std::transform(intersected_faces.begin(),
  337. intersected_faces.end(),
  338. intersected_face_indices.begin(),
  339. [&](const Tree::Primitive_id& itr) -> size_t
  340. { return I(itr-triangles.begin(), 0); });
  341. size_t element_index;
  342. auto element_type = determine_element_type(closest_point, fid,
  343. element_index);
  344. switch(element_type) {
  345. case VERTEX:
  346. {
  347. const auto& f = F.row(I(fid, 0));
  348. const size_t s = f[element_index];
  349. fid = process_vertex_case(i, s, I(fid, 0), fid_ori);
  350. }
  351. break;
  352. case EDGE:
  353. {
  354. const auto& f = F.row(I(fid, 0));
  355. const size_t s = f[(element_index+1)%3];
  356. const size_t d = f[(element_index+2)%3];
  357. fid = process_edge_case(i, s, d, I(fid, 0), fid_ori);
  358. }
  359. break;
  360. case FACE:
  361. {
  362. fid = process_face_case(i, closest_point, fid, fid_ori);
  363. }
  364. break;
  365. default:
  366. throw std::runtime_error("Unknown element type.");
  367. }
  368. R(i,0) = fid;
  369. S(i,0) = fid_ori;
  370. }
  371. }
  372. template<
  373. typename DerivedV,
  374. typename DerivedF,
  375. typename DerivedP,
  376. typename uE2EType,
  377. typename DerivedEMAP,
  378. typename DerivedR,
  379. typename DerivedS >
  380. IGL_INLINE void igl::copyleft::cgal::closest_facet(
  381. const Eigen::PlainObjectBase<DerivedV>& V,
  382. const Eigen::PlainObjectBase<DerivedF>& F,
  383. const Eigen::PlainObjectBase<DerivedP>& P,
  384. const std::vector<std::vector<uE2EType> >& uE2E,
  385. const Eigen::PlainObjectBase<DerivedEMAP>& EMAP,
  386. Eigen::PlainObjectBase<DerivedR>& R,
  387. Eigen::PlainObjectBase<DerivedS>& S) {
  388. const size_t num_faces = F.rows();
  389. Eigen::VectorXi I(num_faces);
  390. I.setLinSpaced(num_faces, 0, num_faces-1);
  391. igl::copyleft::cgal::closest_facet(V, F, I, P, uE2E, EMAP, R, S);
  392. }
  393. #ifdef IGL_STATIC_LIBRARY
  394. template void igl::copyleft::cgal::closest_facet<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<CGAL::Lazy_exact_nt<CGAL::Gmpq>, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
  395. #endif