Vulpes  0.1.0
Versatile and parallel compUtational Library for high-order discontinuous Polytopal Element Simulations
Loading...
Searching...
No Matches
mesher.hpp
Go to the documentation of this file.
1// ----------------------------------------------------------------------
2//
3// Copyright (C) 2024 - 2026 by the Vulpes authors.
4// This file is part of Vulpes.
5//
6// Vulpes is free software; you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10//
11// Vulpes is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14// General Public License for more details.
15//
16// You should have received a copy of the GNU General Public License
17// along with Vulpes. If not, see <http://www.gnu.org/licenses/>.
18//
19// ----------------------------------------------------------------------
20
21// Author: Francesco Rosnati <francesco.rosnati@polimi.it>
22// Author: Matteo Caldana <matteo.caldana@polimi.it>
23// Author: Pedro Peixoto <ppeixoto@usp.br>
24
38
39#ifndef VULPES_GEOMETRY_MESHER_HPP_
40#define VULPES_GEOMETRY_MESHER_HPP_
41
42#include <cassert>
43#include <cstdint>
44#include <iostream>
45#include <limits>
46#include <random>
47#include <stdexcept>
48#include <unordered_map>
49#include <utility>
50#include <vector>
51
52#include <Eigen/Dense>
53
61
62namespace vulpes {
63namespace geometry {
64
66namespace vulpoly {
67
71template <typename FloatType>
74 const FloatType area_relax = 2.0; // c
76 const FloatType toll = 1e-4;
78 const FloatType finite_difference_h = 1e-8; // \epsilon
80 const FloatType reflection_relax = 0.85; // \eta
82 const size_t max_iter = 200;
84 const FloatType clipping_relax = 0.3;
86 const FloatType collapse_edge_toll = 0.1; // \epsilon_a
88 const bool clip_to_bnd = true;
89};
90} // namespace vulpoly
91
97namespace internal {
111template <int32_t Dim>
112std::pair<double, double> updateVoronoiCentroid(
113 const std::array<Point<double, Dim>, 2>& bbox,
114 std::vector<Point<double, Dim>>& points,
115 int32_t n_inside_seeds) {
116 double err = 0.0;
117 double total_area = 0.0;
118
119 voronoi<Dim>(bbox, points, [&](auto& cell, auto id) {
120 double area_and_centroid[Dim + 1];
121 cell.centroid(area_and_centroid);
122 Eigen::Map<Point<double, Dim>> centroid(area_and_centroid + 1);
123 points[id] += centroid;
124 // the point may be outside due to the adjustment
125 // however we are interested in an estimate of the error
126 double area = area_and_centroid[0];
127 if (id < n_inside_seeds) {
128 err += centroid.cwiseAbs2().sum() * area * area;
129 total_area += area;
130 }
131 });
132
133 const double total_err =
134 std::sqrt(err) * points.size() / std::pow(total_area, 1.5);
135 return {total_err, total_area};
136}
137
150template <typename FloatType, typename IndexType, IndexType Dim, typename D>
152 const Point<FloatType, Dim> x,
153 const DistanceExpression<double, Dim, D>& distanceFunction,
154 IndexType idx,
155 FloatType finite_difference_h) {
156 Point<FloatType, Dim> gradient;
157 for (size_t d = 0; d < Dim; ++d) {
158 Point<double, Dim> x_plus = x;
159 Point<double, Dim> x_minus = x;
160 x_plus[d] += finite_difference_h;
161 x_minus[d] -= finite_difference_h;
162 // TODO: trunc computations of distance at j-th index
163 const auto d_x_plus = computeDistance(x_plus, distanceFunction);
164 const auto d_x_minus = computeDistance(x_minus, distanceFunction);
165 if (idx == -1) {
166 gradient[d] = d_x_plus.back() - d_x_minus.back();
167
168 } else {
169 gradient[d] = d_x_plus[idx] - d_x_minus[idx];
170 }
171 gradient[d] /= 2.0 * finite_difference_h;
172 }
173 return gradient;
174}
175
185template <int32_t Dim, typename D>
187 const std::array<Point<double, 2>, 2>& bbox,
188 const std::vector<Point<double, 2>>& points,
189 const DistanceExpression<double, Dim, D>& distanceFunction) {
190 // the square of the euclidean distance
191 constexpr double same_vertex_distance_tol = 1e-18;
192
194 std::vector<Point<double, 2>> vertices;
195 std::vector<bool> visited(points.size(), false);
196 std::vector<int32_t> neighs_buffer(128);
197 std::vector<double> vertices_buffer(128);
198
199 voronoi2D(
200 bbox, points, [&](const voro::voronoicell_neighbor_2d& cell, auto id) {
201 cell.neighbors(neighs_buffer);
202 cell.ordered_vertices(points[id][0], points[id][1], vertices_buffer);
203 const size_t n_cell_vtxs = vertices_buffer.size() / 2;
204
205 // if the cell is internal to the domain
206 if (computeDistance(points[id], distanceFunction).back() <= 0.0) {
207 // for each vertex of this cell
208 for (size_t vid = 0; vid < n_cell_vtxs; ++vid) {
209 bool collision_found = false;
210 // for each cell in the neighbourhood
211 for (size_t cidn = 0;
212 cidn < neighs_buffer.size() && !collision_found; ++cidn) {
213 const int32_t neigh = neighs_buffer[cidn];
214 // if neigh < 0, means the cell is touching the boundary bbox
215 if (neigh >= 0 && visited[neigh]) {
216 const size_t n_neigh_vtxs = vertices_idxs.getRow(neigh).size();
217 for (size_t vidn = 0; vidn < n_neigh_vtxs; ++vidn) {
218 const Point<double, 2> vtx1 =
219 vertices[vertices_idxs.getRow(neigh)[vidn]];
220 const Eigen::Map<const Point<double, 2>> vtx2(
221 &vertices_buffer[2 * vid]);
222 const double dist_sqrd = (vtx1 - vtx2).cwiseAbs2().sum();
223 const double magn_sqrd =
224 vtx1.cwiseAbs2().sum() + vtx2.cwiseAbs2().sum();
225 if (dist_sqrd / magn_sqrd < same_vertex_distance_tol) {
226 collision_found = true;
227 const auto new_vtx_id = vertices_idxs.getRow(neigh)[vidn];
228 // workaround voro bug
229 auto& row = vertices_idxs.getRow(id);
230 if ((row.size() == 0) ||
231 ((new_vtx_id != row[row.size() - 1]) &&
232 (new_vtx_id != row[0]))) {
233 row.push_back(new_vtx_id);
234 }
235
236 break;
237 }
238 }
239 }
240 }
241
242 if (!collision_found) {
243 vertices.emplace_back(
244 vertices_buffer[2 * vid], vertices_buffer[2 * vid + 1]);
245 vertices_idxs.getRow(id).push_back(vertices.size() - 1);
246 }
247 }
248 visited[id] = true;
249 }
250 });
251 return Mesh2D<double, int32_t>(vertices, vertices_idxs);
252}
253
263template <int32_t Dim, typename D>
265 const std::array<Point<double, 3>, 2>& bbox,
266 const std::vector<Point<double, 3>>& points,
267 const DistanceExpression<double, Dim, D>& distanceFunction) {
268 // the square of the euclidean distance
269 constexpr double same_vertex_distance_tol = 1e-18;
270
272 std::vector<Point<double, 3>> vertices;
273 std::vector<int32_t> visited(points.size(), -1);
274 std::vector<int32_t> neighs_buffer(128);
275 std::vector<double> vertices_buffer(128);
276 std::vector<std::vector<int32_t>> faces_staggered;
277 std::vector<int32_t> face_sizes(128);
278 std::vector<int32_t> face_vertices(512);
279 int32_t curr_id = 0;
280
281 voronoi3D(bbox, points, [&](auto& cell, auto id) {
282 const auto dist = computeDistance(points[id], distanceFunction).back();
283
284 if (dist <= 0.0) {
285 auto& curr_cell_vtx = vertices_idxs.getRow(curr_id);
286 cell.vertices(
287 points[id][0], points[id][1], points[id][2], vertices_buffer);
288 assert(vertices_buffer.size() % 3 == 0);
289 cell.neighbors(neighs_buffer);
290 // for each vertex of this cell
291 const size_t n_cell_vtxs = vertices_buffer.size() / 3;
292 for (size_t vid = 0; vid < n_cell_vtxs; ++vid) {
293 bool collision_found = false;
294 // for each cell in the neighbourhood
295 const size_t n_neighs = neighs_buffer.size();
296 for (size_t cidn = 0; cidn < n_neighs && !collision_found; ++cidn) {
297 const int32_t neigh = neighs_buffer[cidn];
298 // if neigh < 0, means the cell is touching the boundary bbox
299 if (neigh >= 0 && (visited[neigh] != -1)) {
300 auto& neigh_cell_vtx = vertices_idxs.getRow(visited[neigh]);
301 const size_t n_neigh_vtxs = neigh_cell_vtx.size();
302 for (size_t vidn = 0; vidn < n_neigh_vtxs; ++vidn) {
303 const Point<double, 3> vtx1 = vertices[neigh_cell_vtx[vidn]];
304 const Eigen::Map<const Point<double, 3>> vtx2(
305 &vertices_buffer[3 * vid]);
306 const double dist_sqrd = (vtx1 - vtx2).cwiseAbs2().sum();
307 const double magn_sqrd =
308 vtx1.cwiseAbs2().sum() + vtx2.cwiseAbs2().sum();
309 if (dist_sqrd / magn_sqrd < same_vertex_distance_tol) {
310 collision_found = true;
311 curr_cell_vtx.push_back(neigh_cell_vtx[vidn]);
312 break;
313 }
314 }
315 }
316 }
317
318 if (!collision_found) {
319 vertices.emplace_back(
320 vertices_buffer[3 * vid], vertices_buffer[3 * vid + 1],
321 vertices_buffer[3 * vid + 2]);
322 curr_cell_vtx.push_back(vertices.size() - 1);
323 }
324 }
325 visited[id] = curr_id++;
326
327 // Get face-vertices connectivity
328 cell.face_vertices(face_vertices, face_sizes);
329 faces_staggered.emplace_back();
330 auto& curr_cell_face_vtx = faces_staggered.back();
331 size_t count = 0;
332 // for each face
333 for (size_t j = 0; j < face_sizes.size(); ++j) {
334 for (int32_t k = 0; k < face_sizes[j] + 1; ++k) {
335 assert(count < face_vertices.size());
336 if (k == 0) {
337 assert(face_vertices[count] == face_sizes[j]);
338 curr_cell_face_vtx.push_back(face_vertices[count]);
339 } else {
340 curr_cell_face_vtx.push_back(curr_cell_vtx[face_vertices[count]]);
341 }
342 count++;
343 }
344 std::reverse(
345 curr_cell_face_vtx.end() - face_sizes[j], curr_cell_face_vtx.end());
346 }
347 assert(count == face_vertices.size());
348 }
349 });
350 return Mesh3D<double, int32_t>{vertices, vertices_idxs, faces_staggered};
351}
352
363template <typename FloatType, typename IndexType, IndexType Dim>
365 const std::vector<Point<FloatType, Dim>>& fixed_pts,
366 const std::vector<IndexType>& near_boundary_idxs,
367 std::vector<Point<FloatType, Dim>>& seed_pts) {
368 if (fixed_pts.empty()) {
369 return;
370 }
371
372 for (const auto& fix_pt : fixed_pts) {
373 // find the 2 * dim (TODO: or 2 + Dim?) closest points to `fix_pt`
374 std::array<std::pair<IndexType, FloatType>, 2 * Dim> closest_seeds;
375 for (size_t d = 0; d < closest_seeds.size(); ++d) {
376 closest_seeds[d] = {-1, std::numeric_limits<FloatType>::max()};
377 }
378 // TODO: here we could be much faster with a data structure like a kdtree
379 // however this should have complexity sqrt(n_seeds) which is reasonable
380 for (const IndexType idx : near_boundary_idxs) {
381 const FloatType dist = (seed_pts[idx] - fix_pt).norm();
382 auto max_it = std::max_element(
383 closest_seeds.begin(), closest_seeds.end(),
384 [](const auto& lhs, const auto& rhs) {
385 return lhs.second < rhs.second;
386 });
387 if (dist < max_it->second) {
388 max_it->second = dist;
389 max_it->first = idx;
390 }
391 }
392
393 // TODO: is this needed? we could move the points on any circumference
394 std::sort(
395 closest_seeds.begin(), closest_seeds.end(),
396 [](const auto& lhs, const auto& rhs) {
397 return lhs.second < rhs.second;
398 });
399
400 if (closest_seeds.back().first == -1) {
401 std::cout << "WARNING: could not find enough points near the fixed point "
402 << std::endl;
403 } else {
404 // fix the tessellation points
405 for (size_t i = 1; i < closest_seeds.size(); ++i) {
406 Point<FloatType, Dim> normal =
407 seed_pts[closest_seeds[i].first] - fix_pt;
408 seed_pts[closest_seeds[i].first] -=
409 normal * (1.0 - closest_seeds[0].second / closest_seeds[i].second);
410 // we are moving the points on the circle centered in `fix_pt`, check
411 // the distance from center is always the same
412 assert(
413 std::abs(
414 (fix_pt - seed_pts[closest_seeds[i].first]).norm() -
415 (fix_pt - seed_pts[closest_seeds[0].first]).norm()) <
416 2 * std::numeric_limits<FloatType>::epsilon());
417 }
418 }
419 }
420}
421
435template <typename FloatType, typename IndexType, IndexType Dim, typename D>
436std::vector<IndexType> vulPolyReflect(
437 const DistanceExpression<FloatType, Dim, D>& distanceFunction,
438 FloatType alpha,
440 std::vector<Point<FloatType, Dim>>& seed_pts) {
441 std::vector<IndexType> near_boundary_idxs;
442
443 const size_t n_seed_pts = seed_pts.size();
444 size_t near_boundary = 0;
445 size_t reflected_with_success = 0;
446 for (size_t i = 0; i < n_seed_pts; ++i) {
447 const Point<FloatType, Dim> seed_pt_i = seed_pts[i];
448 const auto d_i = computeDistance(seed_pt_i, distanceFunction);
449 assert(d_i.back() < 0.0);
450 if (-d_i.back() < alpha) {
451 near_boundary++;
452 near_boundary_idxs.push_back(i);
453 bool reflection_inserted = false;
454 // loop subdomains
455 for (size_t j = 0; j < d_i.size() - 1; ++j) {
456 // distance of point i from boundary j (might not be positive!)
457 const FloatType d_seed_j = d_i[j];
458 const FloatType d_seed_j_abs = std::abs(d_seed_j);
459 if (d_seed_j_abs < alpha) {
460 // compute reflection with finite difference
461 // R(x) = x - 2d(x)\nabla d(x)
462 const Point<FloatType, Dim> gradient = computeGradient(
463 seed_pt_i, distanceFunction, (IndexType)j,
464 params.finite_difference_h);
465 const Point<FloatType, Dim> rflc_pt =
466 seed_pts[i] - 2.0 * d_seed_j * gradient;
467 const auto pt_d = computeDistance(rflc_pt, distanceFunction);
468 // distance is positive (is outside) and necessary for this subdomain
469 if (pt_d.back() > 0 &&
470 pt_d.back() > params.reflection_relax * d_seed_j_abs) {
471 near_boundary_idxs.push_back(seed_pts.size());
472 seed_pts.push_back(rflc_pt);
473 reflection_inserted = true;
474 }
475 }
476 }
477 reflected_with_success += reflection_inserted;
478 }
479 }
480
481 if (reflected_with_success < near_boundary) {
482 std::cout << "WARNING: could not insert some reflections, succeeded: "
483 << reflected_with_success << " / " << near_boundary << std::endl;
484 }
485
486 return near_boundary_idxs;
487}
488
500template <typename FloatType, typename MeshType, typename D>
502 MeshType& mesh,
503 FloatType alpha,
505 distanceFunction,
506 const vulpoly::VulPolyParams<FloatType>& params) {
507 constexpr auto Dim = MeshType::self_dim;
508 size_t possible_clipping = 0;
509 size_t successfull_clipping = 0;
510 for (auto& vtx : mesh.getVertexes()) {
511 const auto distance_from_bnd =
512 computeDistance(vtx, distanceFunction).back();
513 // if close enough to the boundary we try to clip the point to it
514 if (std::abs(distance_from_bnd) < params.clipping_relax * alpha) {
515 possible_clipping++;
516 const Point<FloatType, Dim> gradient = computeGradient(
517 vtx, distanceFunction, -1, params.finite_difference_h);
518 const Point<FloatType, Dim> new_vtx = vtx - distance_from_bnd * gradient;
519 // check the adjustment improved the position
520 // (gradient computaitons can be ill)
521 const auto new_distance_from_bnd =
522 computeDistance(new_vtx, distanceFunction).back();
523 if (std::abs(new_distance_from_bnd) < std::abs(distance_from_bnd)) {
524 vtx = new_vtx;
525 successfull_clipping++;
526 }
527 }
528 }
529 std::cout << "possible_clipping: " << possible_clipping
530 << " successfull_clipping: " << successfull_clipping << std::endl;
531}
532
541template <typename FloatType, typename IndexType>
544 IndexType cell_id,
545 const std::array<IndexType, 2>& edge) {
546 if (cell_id == -1) {
547 return std::numeric_limits<FloatType>::max();
548 }
549 const auto vtx_ids = mesh.getCellToVtxMap().getRow(cell_id);
550 const auto& pts = mesh.getVertexes();
551
552 FloatType meanvy = 0.0;
553 FloatType meanvx = 0.0;
554 for (const auto& vid : vtx_ids) {
555 meanvx += pts[vid][0];
556 meanvy += pts[vid][1];
557 }
558 meanvx /= vtx_ids.size();
559 meanvy /= vtx_ids.size();
560
561 constexpr FloatType pi2 = 2 * vmath::pi<FloatType>();
562 FloatType angle =
563 std::atan2(pts[edge[1]][1] - meanvy, pts[edge[1]][0] - meanvx) -
564 std::atan2(pts[edge[0]][1] - meanvy, pts[edge[0]][0] - meanvx);
565
566 // numerical stability
567 constexpr auto min_angle = 1e-8;
568 angle += min_angle;
569 angle = std::fmod(angle + pi2, pi2);
570 assert((angle >= 0) && (angle <= vmath::pi<FloatType>()));
571 return std::abs(angle) * vtx_ids.size() / pi2;
572}
573
585template <typename FloatType, typename IndexType, IndexType Dim, typename D>
588 const DistanceExpression<FloatType, Dim, D>& distanceFunction,
589 FloatType edge_collapse_tol) {
590 std::vector<IndexType> small_edges;
591 const IndexType n_edges = mesh.getFacetToCellMap().size();
592 for (IndexType i = 0; i < n_edges; ++i) {
593 const auto edge = mesh.getFacetToVtxMap().getRow(i);
594 const auto& cells = mesh.getFacetToCellMap()[i];
595 // if the edge does not belong to any triangle
596 const auto& map = mesh.getCellToVtxMap();
597 if ((cells[0] == -1 || map.getRow(cells[0]).size() > 3) &&
598 (cells[1] == -1 || map.getRow(cells[1]).size() > 3)) {
599 //
600 const FloatType angle_normalized_size_0 =
601 vulPolyComputeEdgeAngle(mesh, cells[0], {edge[0], edge[1]});
602 const FloatType angle_normalized_size_1 =
603 vulPolyComputeEdgeAngle(mesh, cells[1], {edge[1], edge[0]});
604 // if the edge is too small for one of the two cells
605 if ((angle_normalized_size_0 < edge_collapse_tol) ||
606 (angle_normalized_size_1 < edge_collapse_tol)) {
607 small_edges.push_back(i);
608 }
609 }
610 }
611
612 // we remove only the edges that do not form a path (are "alone")
613 // we build the vertex to edge map to check for this ^
614 // TODO: remove this constraint, or at least pick the smallest edge of
615 // the path and remove it
616 std::unordered_map<IndexType, uint64_t> vertex_to_edges;
617 for (size_t i = 0; i < small_edges.size(); ++i) {
618 const auto edge_id = small_edges[i];
619 const auto edge_vtx = mesh.getFacetToVtxMap().getRow(edge_id);
620 // assume that the edges are no more than 2^32
621 // we store both the count of edges and the edge id (which is overwritten if
622 // we have more than one edge, but it is fine since we skip them)
623 vertex_to_edges[edge_vtx[0]] += (1ULL << 32) + uint64_t(edge_id);
624 vertex_to_edges[edge_vtx[1]] += (1ULL << 32) + uint64_t(edge_id);
625 }
626
627 std::unordered_map<IndexType, IndexType> vtxs_to_remove_in_edge;
628 for (const auto& [vertex_id, edge_count_and_id] : vertex_to_edges) {
629 // if the vertex belongs to only one edge, then we increase the number of
630 // vertices that can be removed in that edge
631 if ((edge_count_and_id >> 32) == 1) {
632 vtxs_to_remove_in_edge[edge_count_and_id & 0xFFFFFFFFULL]++;
633 }
634 }
635
636 std::vector<std::array<IndexType, 2>> vtxs_to_remove;
637 auto new_cell_to_vtx = mesh.getCellToVtxMap();
638 for (const auto& [edge_id, vtx_count] : vtxs_to_remove_in_edge) {
639 // if we can remove either vertex
640 if (vtx_count == 2) {
641 // check which vertex is closest to the boundary and we keep it
642 // for point inside the domain which we keep does not matter
643 // but near the boundary this allows to better approximate the border
644 const IndexType v1_id = mesh.getFacetToVtxMap()(edge_id, 0);
645 const IndexType v2_id = mesh.getFacetToVtxMap()(edge_id, 1);
646 const auto& pt1 = mesh.getVertexes()[v1_id];
647 const auto& pt2 = mesh.getVertexes()[v2_id];
648 const auto d1 = computeDistance(pt1, distanceFunction).back();
649 const auto d2 = computeDistance(pt2, distanceFunction).back();
650 // the first element in the array is the one to remove, then we have the
651 // other: we need this information later
652 if (std::abs(d1) < std::abs(d2)) {
653 vtxs_to_remove.push_back({v2_id, v1_id});
654 } else {
655 vtxs_to_remove.push_back({v1_id, v2_id});
656 }
657 // remove the edge for the affected cells
658 for (const auto& cell : mesh.getFacetToCellMap()[edge_id]) {
659 if (cell != -1) {
660 for (IndexType& vtx_id : new_cell_to_vtx.getRow(cell)) {
661 if (vtx_id == vtxs_to_remove.back()[0]) {
662 vtx_id = -1;
663 }
664 }
665 }
666 }
667 }
668 }
669
670 // most important bit (sign bit for signed integer, largest 2 power for
671 // unsigned)
672 constexpr IndexType mask = IndexType(1)
673 << IndexType(sizeof(IndexType) * 8 - 1);
674 // remove points
675 std::sort(
676 vtxs_to_remove.begin(), vtxs_to_remove.end(),
677 [](const auto& lhs, const auto& rhs) { return lhs[0] < rhs[0]; });
678 // dummy to avoid `j` problem in the merge
679 vtxs_to_remove.push_back({-1, -1});
680 std::vector<Point<FloatType, 2>> new_vxts;
681 std::vector<IndexType> vtx_old_new_table;
682 IndexType j = 0; // vtx to remove idx
683 const IndexType n_vtxs = mesh.getVertexes().size();
684 for (IndexType i = 0; i < n_vtxs; ++i) {
685 if (vtxs_to_remove[j][0] == i) {
686 // We need to substitute this vertex with its corresponding in the edge.
687 // The mapping is incomplete, so we signal with a mask that it must be
688 // recomputed
689 vtx_old_new_table.push_back(vtxs_to_remove[j][1] | mask);
690 j++;
691 continue;
692 }
693 vtx_old_new_table.push_back(new_vxts.size());
694 new_vxts.push_back(mesh.getVertexes()[i]);
695 }
696 assert(
697 new_vxts.size() == mesh.getVertexes().size() - vtxs_to_remove.size() + 1);
698
699 // recompute cell to vtx map removing -1 from `new_cell_to_vtx`
700 std::vector<IndexType> crs_indexes = {0};
701 std::vector<IndexType> crs_data;
702 for (IndexType i = 0; i < new_cell_to_vtx.size(); ++i) {
703 const auto row = new_cell_to_vtx.getRow(i);
704 for (const auto elem : row) {
705 if (elem != -1) {
706 const auto new_elem = vtx_old_new_table[elem];
707 // requires recomputations since the vertex was removed
708 if (mask & new_elem) {
709 crs_data.push_back(vtx_old_new_table[new_elem & (~mask)]);
710 } else {
711 crs_data.push_back(new_elem);
712 }
713 }
714 }
715 crs_indexes.push_back(crs_data.size());
716 }
717
718 mesh = Mesh2D(
719 new_vxts,
720 datastructure::CrsMap<IndexType, IndexType>(crs_data, crs_indexes));
721}
722
723} // namespace internal
724
729namespace vulpoly {
730
732enum RandomEngine : std::uint8_t {
737};
738
740template <
741 typename FloatType,
742 typename IndexType,
743 IndexType Dim,
744 typename = std::enable_if_t<(Dim == 2) || (Dim == 3)>>
745using Mesh = std::conditional_t<
746 Dim == 2,
749
766template <typename FloatType, typename IndexType, IndexType Dim, typename D>
767std::pair<Mesh<FloatType, IndexType, Dim>, std::vector<Point<FloatType, Dim>>>
769 const DistanceExpression<FloatType, Dim, D>& distanceFunction,
770 size_t n_elems,
771 const std::vector<Point<FloatType, Dim>>& fixed_pts = {},
772 const VulPolyParams<FloatType>& params = {},
773 size_t seed = 0) {
774 const auto bbox = distanceFunction.bbox();
775
776 std::mt19937 gen(seed);
777 std::uniform_real_distribution<FloatType> dis(0.0, 1.0);
778
780 const auto gen_random_pt = [&](size_t iter) {
781 std::array<FloatType, Dim> pt;
782 switch (engine_type) {
784 for (size_t d = 0; d < Dim; ++d) {
785 pt[d] = dis(gen);
786 }
787 break;
788 }
790 pt = random::additiveRecurrence<Dim>(iter, iter + 1)[0];
791 break;
792 }
793 default: {
794 throw std::logic_error("Mesher: unknown random engine");
795 }
796 }
797 return pt;
798 };
799
800 std::vector<Point<FloatType, Dim>> seed_pts(n_elems);
801 size_t found = 0;
802 size_t count = 0;
803 while (found < n_elems) {
804 // random point in [0, 1]^Dim
805 const auto raw_random_pt = gen_random_pt(count++);
806 Eigen::Map<const Point<FloatType, Dim>> random_pt(raw_random_pt.data());
807 // rescale in the bounding box
808 const Point<FloatType, Dim> pt =
809 bbox[0].array() + random_pt.array() * (bbox[1] - bbox[0]).array();
810 // accept if internal
811 const auto distance = computeDistance(pt, distanceFunction);
812 if (distance.back() < 0) {
813 seed_pts[found++] = pt;
814 }
815 }
816
817 return {mesh(seed_pts, distanceFunction, fixed_pts, params), seed_pts};
818}
819
835template <typename FloatType, typename IndexType, IndexType Dim, typename D>
837 std::vector<Point<FloatType, Dim>>& center_pts,
838 const DistanceExpression<FloatType, Dim, D>& distanceFunction,
839 const std::vector<Point<FloatType, Dim>>& fixed_pts = {},
840 const VulPolyParams<FloatType>& params = {}) {
841 const auto bbox = distanceFunction.bbox();
842 // increase the bounding box of the half size of the box in each direction
843 // the final size is thus two times the original
844 const std::array<Point<FloatType, Dim>, 2> extended_bbox = {
845 bbox[0].array() - 0.5 * (bbox[1] - bbox[0]).array(),
846 bbox[1].array() + 0.5 * (bbox[1] - bbox[0]).array()};
847 FloatType area = (bbox[1] - bbox[0]).prod();
848
849 FloatType err = std::numeric_limits<FloatType>::infinity();
850 for (size_t it = 0; it < params.max_iter; ++it) {
851 const size_t n_elems = center_pts.size();
852 // average relaxed width of an element
853 const FloatType alpha =
854 params.area_relax * std::pow(area / n_elems, 1.0 / Dim);
855 const auto near_boundary_idxs =
856 internal::vulPolyReflect(distanceFunction, alpha, params, center_pts);
858 fixed_pts, near_boundary_idxs, center_pts);
859
860 // we break the loop before updating the centroid since we are
861 // re-computing the voronoi, and this task needs updated fixed points
862 // and reflected points
863 if (err < params.toll || it == (params.max_iter - 1)) {
864 break;
865 }
866
867 std::tie(err, area) = internal::updateVoronoiCentroid<Dim>(
868 extended_bbox, center_pts, n_elems);
869
870 // Select only the cells inside the domain
871 std::vector<Point<FloatType, Dim>> new_center_pts;
872 for (const auto& pt : center_pts) {
873 if (computeDistance(pt, distanceFunction).back() <= 0.) {
874 new_center_pts.push_back(pt);
875 }
876 }
877 center_pts = new_center_pts;
878
879 std::cout << "VulPoly: " << err << " " << it << std::endl;
880 }
881
882 // Increase mesh quality by collapsing and clipping
883 if constexpr (Dim == 2) {
884 auto tmp_mesh = internal::computeVoronoiMesh2D(
885 extended_bbox, center_pts, distanceFunction);
887 tmp_mesh, distanceFunction, params.collapse_edge_toll);
888 const auto alpha = std::pow(area / center_pts.size(), 1.0 / Dim);
889 // TODO: do this before collapse to remove possible degenerate edges
890 if (params.clip_to_bnd) {
892 tmp_mesh, alpha, distanceFunction, params);
893 }
894 return tmp_mesh;
895 } else if constexpr (Dim == 3) {
896 auto tmp_mesh = internal::computeVoronoiMesh3D(
897 extended_bbox, center_pts, distanceFunction);
898 const auto alpha = std::pow(area / tmp_mesh.numCells(), 1.0 / Dim);
899 if (params.clip_to_bnd) {
901 tmp_mesh, alpha, distanceFunction, params);
902 }
903 return tmp_mesh;
904 } else {
905 static_assert(Dim * 0, "Not Implemented");
906 }
907}
908
918template <typename FloatType, typename IndexType>
920 const Point<FloatType, 2>& corner_a,
921 const Point<FloatType, 2>& corner_b,
922 const Point<IndexType, 2>& n_divisions) {
923 const auto distanceRectangle =
924 dist2d::RectangleDistance<FloatType>(corner_a, corner_b);
925 const std::vector<Point<FloatType, 2>> fixed_pts = {};
926
927 constexpr FloatType sqrt3_2 = std::sqrt(3) / 2.0;
928 const FloatType dx = (corner_b[0] - corner_a[0]) / n_divisions[0];
929 const FloatType dy = (corner_b[1] - corner_a[1]) / n_divisions[1];
930 const IndexType ny = IndexType(std::ceil(n_divisions[1] / sqrt3_2)) + 2;
931 std::vector<Point<FloatType, 2>> seeds;
932 for (IndexType i = 0; i < n_divisions[0] + 1; ++i) {
933 for (IndexType j = 0; j < ny; ++j) {
934 const FloatType x = corner_a[0] + i * dx + ((j % 2) * dx) / 2.0;
935 const FloatType y = corner_a[1] + j * sqrt3_2 * dy;
936 const Point<FloatType, 2> pt{x + dx / 4, y + dy / 4};
937 if (computeDistance(pt, distanceRectangle).back() <= 0.0) {
938 seeds.push_back(pt);
939 }
940 }
941 }
942 const VulPolyParams<FloatType> options = {.max_iter = 1};
943 return vulpoly::mesh(seeds, distanceRectangle, fixed_pts, options);
944}
945
955template <typename FloatType, typename IndexType>
957 const Point<FloatType, 3>& corner_a,
958 const Point<FloatType, 3>& corner_b,
959 const Point<IndexType, 3>& n_divisions) {
960 const auto distanceFn =
961 dist3d::HexahedronDistance<FloatType>(corner_a, corner_b);
962 const std::vector<Point<FloatType, 3>> fixed_pts = {};
963
964 const FloatType dt = 0.01;
965
966 const FloatType dx =
967 (corner_b[0] - corner_a[0]) / (n_divisions[0] - 1. + 2 * dt);
968 const FloatType dy =
969 (corner_b[1] - corner_a[1]) / (n_divisions[1] - 1. + 2 * dt);
970 const FloatType dz =
971 (corner_b[2] - corner_a[2]) / (n_divisions[2] - 1. + 2 * dt);
972
973 std::vector<Point<FloatType, 3>> seeds;
974 for (IndexType i = 0; i < n_divisions[0] + 2; ++i) {
975 for (IndexType j = 0; j < n_divisions[1] + 2; ++j) {
976 for (IndexType k = 0; k < n_divisions[2] + 2; ++k) {
977 {
978 const FloatType x = corner_a[0] + i * dx;
979 const FloatType y = corner_a[1] + j * dy;
980 const FloatType z = corner_a[2] + k * dz;
981 const Point<FloatType, 3> pt{x + dx * dt, y + dy * dt, z + dz * dt};
982 if (computeDistance(pt, distanceFn).back() < 0.0) {
983 seeds.push_back(pt);
984 }
985 }
986 {
987 const FloatType x = corner_a[0] + (2 * i + 1) * dx / 2.0;
988 const FloatType y = corner_a[1] + (2 * j + 1) * dy / 2.0;
989 const FloatType z = corner_a[2] + (2 * k + 1) * dz / 2.0;
990 const Point<FloatType, 3> pt{x + dx * dt, y + dy * dt, z + dz * dt};
991 if (computeDistance(pt, distanceFn).back() < 0.0) {
992 seeds.push_back(pt);
993 }
994 }
995 }
996 }
997 }
998 const VulPolyParams<FloatType> options = {.max_iter = 1};
999 return vulpoly::mesh(seeds, distanceFn, fixed_pts, options);
1000}
1001
1002} // namespace vulpoly
1003} // namespace geometry
1004} // namespace vulpes
1005
1006#endif // VULPES_GEOMETRY_MESHER_HPP_
A class that behaves like a vector of vectors, providing automatic row range checking.
Definition crs_map.hpp:758
SmallVector< DataType, N > & getRow(std::size_t row_idx)
Access a row of the matrix as a mutable reference.
Definition crs_map.hpp:857
Definition crs_map.hpp:72
Template class representing a generic signed distance expression.
Definition distance.hpp:65
std::array< Point< FloatType, Dim >, 2 > bbox() const
Get the bounding box (bbox) of the shape.
Definition distance.hpp:108
A class for a 2D mesh, inheriting from MeshBase.
Definition mesh_2d.hpp:94
Represents a 3D mesh.
Definition mesh_3d.hpp:82
Signed distance function for a rectangle in 2D space.
Definition distance.hpp:125
Signed distance function for a hexahedron (cuboid) in 3D space.
Definition distance.hpp:468
Helpers implementing VulPoly's Voronoi construction and cleanup.
Definition abs_agg_model.cpp:42
std::vector< IndexType > vulPolyReflect(const DistanceExpression< FloatType, Dim, D > &distanceFunction, FloatType alpha, const vulpoly::VulPolyParams< FloatType > &params, std::vector< Point< FloatType, Dim > > &seed_pts)
Add reflected seeds near domain boundaries.
Definition mesher.hpp:436
Point< FloatType, Dim > computeGradient(const Point< FloatType, Dim > x, const DistanceExpression< double, Dim, D > &distanceFunction, IndexType idx, FloatType finite_difference_h)
Estimate a signed-distance gradient by centered finite differences.
Definition mesher.hpp:151
void vulPolyAdjustFixedPoints(const std::vector< Point< FloatType, Dim > > &fixed_pts, const std::vector< IndexType > &near_boundary_idxs, std::vector< Point< FloatType, Dim > > &seed_pts)
Adjust nearby seeds to keep fixed points represented in the mesh.
Definition mesher.hpp:364
void vulPolyClipToBoundary(MeshType &mesh, FloatType alpha, const DistanceExpression< FloatType, MeshType::self_dim, D > &distanceFunction, const vulpoly::VulPolyParams< FloatType > &params)
Improve positions of mesh vertices close to the domain boundary.
Definition mesher.hpp:501
std::pair< double, double > updateVoronoiCentroid(const std::array< Point< double, Dim >, 2 > &bbox, std::vector< Point< double, Dim > > &points, int32_t n_inside_seeds)
Move each Voronoi seed to its cell centroid and estimate relaxation error.
Definition mesher.hpp:112
Mesh3D< double, int32_t > computeVoronoiMesh3D(const std::array< Point< double, 3 >, 2 > &bbox, const std::vector< Point< double, 3 > > &points, const DistanceExpression< double, Dim, D > &distanceFunction)
Convert in-domain 3D Voronoi cells into a Vulpes mesh.
Definition mesher.hpp:264
FloatType vulPolyComputeEdgeAngle(const Mesh2D< FloatType, IndexType > &mesh, IndexType cell_id, const std::array< IndexType, 2 > &edge)
Estimate an edge's normalized angular size in an adjacent cell.
Definition mesher.hpp:542
Mesh2D< double, int32_t > computeVoronoiMesh2D(const std::array< Point< double, 2 >, 2 > &bbox, const std::vector< Point< double, 2 > > &points, const DistanceExpression< double, Dim, D > &distanceFunction)
Convert in-domain 2D Voronoi cells into a Vulpes mesh.
Definition mesher.hpp:186
void vulPolyCollapseEdges(Mesh2D< FloatType, IndexType > &mesh, const DistanceExpression< FloatType, Dim, D > &distanceFunction, FloatType edge_collapse_tol)
Collapse isolated undersized edges in a 2D mesh.
Definition mesher.hpp:586
VulPoly meshing options and algorithm parameters.
Definition mesher.hpp:66
RandomEngine
Available random or low-discrepancy seed generation strategies.
Definition mesher.hpp:732
@ AdditiveRecurrence
Generate points with the additive recurrence sequence.
Definition mesher.hpp:736
@ Pseudo
Draw independent uniform samples from the unit box.
Definition mesher.hpp:734
auto buildHexagonTessellation(const Point< FloatType, 2 > &corner_a, const Point< FloatType, 2 > &corner_b, const Point< IndexType, 2 > &n_divisions)
Build a 2D hexagonal seed tessellation and mesh its rectangle.
Definition mesher.hpp:919
std::conditional_t< Dim==2, Mesh2D< FloatType, IndexType >, Mesh3D< FloatType, IndexType > > Mesh
Select the concrete mesh type for a supported spatial dimension.
Definition mesher.hpp:745
std::pair< Mesh< FloatType, IndexType, Dim >, std::vector< Point< FloatType, Dim > > > mesh(const DistanceExpression< FloatType, Dim, D > &distanceFunction, size_t n_elems, const std::vector< Point< FloatType, Dim > > &fixed_pts={}, const VulPolyParams< FloatType > &params={}, size_t seed=0)
Generate a VulPoly mesh from a requested number of seeds.
Definition mesher.hpp:768
auto buildOctahedronTessellation(const Point< FloatType, 3 > &corner_a, const Point< FloatType, 3 > &corner_b, const Point< IndexType, 3 > &n_divisions)
Build a 3D hexahedral-domain mesh from an octahedral seed pattern.
Definition mesher.hpp:956
Definition abs_agg_model.cpp:40
Eigen::Matrix< DataType, Dim, 1, Eigen::ColMajor > Point
Definition traits.hpp:34
void voronoi(const std::array< Point< double, Dim >, 2 > &bbox, std::vector< Point< double, Dim > > &points, const std::function< void(VoronoiCell< Dim > &cell, int32_t id)> &cell_callback)
Computes a Voronoi tessellation in either 2D or 3D space.
Definition voronoi.hpp:123
void voronoi2D(const std::array< Point< double, 2 >, 2 > &bbox, const std::vector< Point< double, 2 > > &points, const std::function< void(voro::voronoicell_neighbor_2d &cell, int32_t id)> &cell_callback)
Computes a 2D Voronoi tessellation for a given set of points within a bounding box.
Definition voronoi.cpp:44
void voronoi3D(const std::array< Point< double, 3 >, 2 > &bbox, const std::vector< Point< double, 3 > > &points, const std::function< void(voro::voronoicell_neighbor &cell, int32_t id)> &cell_callback)
Computes a 3D Voronoi tessellation for a given set of points within a bounding box.
Definition voronoi.cpp:72
auto computeDistance(const Point< FloatType, Dim > &point, const DistanceExpression< FloatType, Dim, D > &distance_function)
Computes the signed distance between a point and a shape defined by a distance function.
Definition distance.hpp:936
std::vector< std::array< double, M > > additiveRecurrence(std::size_t n0, std::size_t n1)
Generates a sequence of points using an additive recurrence formula.
Definition additive_recurrence.hpp:102
constexpr T pi()
Returns the value of pi.
Definition vmath.hpp:222
Definition cell_manager.hpp:38
Parameters controlling VulPoly relaxation and mesh cleanup.
Definition mesher.hpp:72
const FloatType collapse_edge_toll
Relative threshold below which a 2D edge may be collapsed.
Definition mesher.hpp:86
const FloatType finite_difference_h
Step size used in finite-difference boundary-gradient estimates.
Definition mesher.hpp:78
const FloatType clipping_relax
Maximum fraction of the characteristic width for boundary clipping.
Definition mesher.hpp:84
const FloatType area_relax
Multiplier for the characteristic cell width used during relaxation.
Definition mesher.hpp:74
const size_t max_iter
Maximum number of centroidal relaxation iterations.
Definition mesher.hpp:82
const FloatType toll
Convergence tolerance for the normalized centroid displacement.
Definition mesher.hpp:76
const bool clip_to_bnd
Whether to project nearby output vertices toward the domain boundary.
Definition mesher.hpp:88
const FloatType reflection_relax
Minimum reflected-point clearance as a fraction of boundary distance.
Definition mesher.hpp:80