#include "meshedit.hpp" #include #include #include #include #include #include #include #include #include namespace meshedit { using geom::Vec3; using Tri = std::array; namespace { constexpr double kTiny = 1e-20; std::uint64_t edgeKey(int a, int b) { std::uint32_t lo = (std::uint32_t)std::min(a, b); std::uint32_t hi = (std::uint32_t)std::max(a, b); return ((std::uint64_t)lo << 32) | hi; } int edgeLo(std::uint64_t k) { return (int)(std::uint32_t)(k >> 32); } int edgeHi(std::uint64_t k) { return (int)(std::uint32_t)k; } double triArea(const mesh::Mesh& m, const Tri& t) { return 0.5 * geom::norm(geom::cross(m.verts[t[1]] - m.verts[t[0]], m.verts[t[2]] - m.verts[t[0]])); } void finishMutation(mesh::Mesh& m) { m.computeNormals(); m.computeBounds(); m.adj.clear(); m.curv.clear(); } struct DisjointSet { std::vector p; std::vector rank; explicit DisjointSet(std::size_t n) : p(n), rank(n, 0) { std::iota(p.begin(), p.end(), 0); } int find(int x) { int r = x; while (p[r] != r) r = p[r]; while (p[x] != x) { int q = p[x]; p[x] = r; x = q; } return r; } void unite(int a, int b) { a = find(a); b = find(b); if (a == b) return; if (rank[a] < rank[b]) std::swap(a, b); p[b] = a; if (rank[a] == rank[b]) ++rank[a]; } }; struct EdgeRecord { std::uint64_t key; int tri; bool operator<(const EdgeRecord& o) const { return key < o.key || (key == o.key && tri < o.tri); } }; bool directedEdge(const Tri& t, int a, int b) { return (t[0] == a && t[1] == b) || (t[1] == a && t[2] == b) || (t[2] == a && t[0] == b); } Vec3 closestPointTriangle(const Vec3& p, const Vec3& a, const Vec3& b, const Vec3& c) { // Ericson's Voronoi-region test remains stable for the tiny triangles common // in scans and avoids solving a poorly conditioned barycentric system. Vec3 ab = b - a, ac = c - a, ap = p - a; double d1 = geom::dot(ab, ap), d2 = geom::dot(ac, ap); if (d1 <= 0 && d2 <= 0) return a; Vec3 bp = p - b; double d3 = geom::dot(ab, bp), d4 = geom::dot(ac, bp); if (d3 >= 0 && d4 <= d3) return b; double vc = d1 * d4 - d3 * d2; if (vc <= 0 && d1 >= 0 && d3 <= 0) { double v = d1 / (d1 - d3); return a + ab * v; } Vec3 cp = p - c; double d5 = geom::dot(ab, cp), d6 = geom::dot(ac, cp); if (d6 >= 0 && d5 <= d6) return c; double vb = d5 * d2 - d1 * d6; if (vb <= 0 && d2 >= 0 && d6 <= 0) { double w = d2 / (d2 - d6); return a + ac * w; } double va = d3 * d6 - d5 * d4; if (va <= 0 && d4 - d3 >= 0 && d5 - d6 >= 0) { Vec3 bc = c - b; double w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); return b + bc * w; } double denom = va + vb + vc; if (std::fabs(denom) < kTiny) { Vec3 q0 = a, q1 = b, q2 = c; double e0 = geom::dot(p - q0, p - q0); double e1 = geom::dot(p - q1, p - q1); double e2 = geom::dot(p - q2, p - q2); return e0 < e1 && e0 < e2 ? q0 : e1 < e2 ? q1 : q2; } double inv = 1.0 / denom; return a + ab * (vb * inv) + ac * (vc * inv); } } // namespace Analysis analyze(const mesh::Mesh& m) { Analysis out; if (m.tris.empty()) return out; std::vector edges; edges.reserve(m.tris.size() * 3); for (int ti = 0; ti < (int)m.tris.size(); ++ti) { const Tri& t = m.tris[ti]; edges.push_back({edgeKey(t[0], t[1]), ti}); edges.push_back({edgeKey(t[1], t[2]), ti}); edges.push_back({edgeKey(t[2], t[0]), ti}); } std::sort(edges.begin(), edges.end()); DisjointSet sets(m.tris.size()); struct BoundaryEdge { int from, to; }; std::vector boundary; boundary.reserve(edges.size() / 100 + 8); for (std::size_t i = 0; i < edges.size();) { std::size_t j = i + 1; while (j < edges.size() && edges[j].key == edges[i].key) ++j; int incidence = (int)(j - i); for (std::size_t k = i + 1; k < j; ++k) sets.unite(edges[i].tri, edges[k].tri); if (incidence == 1) { ++out.boundaryEdges; int a = edgeLo(edges[i].key), b = edgeHi(edges[i].key); const Tri& t = m.tris[edges[i].tri]; // Patch winding must run opposite to the extant face along the seam. boundary.push_back(directedEdge(t, a, b) ? BoundaryEdge{b, a} : BoundaryEdge{a, b}); } else if (incidence > 2) { ++out.nonManifoldEdges; } i = j; } struct RawComponent { int root; Component data; }; std::unordered_map rootToRaw; rootToRaw.reserve(m.tris.size() / 16 + 1); std::vector raw; std::vector triRaw(m.tris.size(), -1); for (int ti = 0; ti < (int)m.tris.size(); ++ti) { int root = sets.find(ti); auto it = rootToRaw.find(root); int id; if (it == rootToRaw.end()) { id = (int)raw.size(); rootToRaw.emplace(root, id); raw.push_back({root, {}}); } else { id = it->second; } triRaw[ti] = id; ++raw[id].data.ntris; raw[id].data.area += triArea(m, m.tris[ti]); } std::vector order(raw.size()); std::iota(order.begin(), order.end(), 0); std::sort(order.begin(), order.end(), [&](int a, int b) { if (raw[a].data.ntris != raw[b].data.ntris) return raw[a].data.ntris > raw[b].data.ntris; return raw[a].data.area > raw[b].data.area; }); std::vector remap(raw.size()); out.components.reserve(raw.size()); for (int id = 0; id < (int)order.size(); ++id) { remap[order[id]] = id; out.components.push_back(raw[order[id]].data); } out.triangleComponent.resize(m.tris.size()); for (std::size_t i = 0; i < triRaw.size(); ++i) out.triangleComponent[i] = remap[triRaw[i]]; // A manifold boundary has one outgoing edge at every loop vertex. At damaged // non-manifold junctions we consume each edge once and report only closed walks. std::unordered_map> outgoing; outgoing.reserve(boundary.size() * 2 + 1); for (int i = 0; i < (int)boundary.size(); ++i) outgoing[boundary[i].from].push_back(i); std::vector used(boundary.size(), 0); for (int seed = 0; seed < (int)boundary.size(); ++seed) { if (used[seed]) continue; std::vector loop; int edge = seed; int start = boundary[edge].from; bool closed = false; while (!used[edge]) { used[edge] = 1; loop.push_back(boundary[edge].from); int at = boundary[edge].to; if (at == start) { closed = true; break; } int next = -1; auto it = outgoing.find(at); if (it != outgoing.end()) for (int candidate : it->second) if (!used[candidate]) { next = candidate; break; } if (next < 0) break; edge = next; } if (!closed || loop.size() < 3) continue; Hole h; h.vertices = std::move(loop); h.nedges = (int)h.vertices.size(); for (int v : h.vertices) h.center = h.center + m.verts[v]; h.center = h.center / (double)h.vertices.size(); for (int v : h.vertices) h.radius = std::max(h.radius, geom::norm(m.verts[v] - h.center)); out.holes.push_back(std::move(h)); } std::sort(out.holes.begin(), out.holes.end(), [](const Hole& a, const Hole& b) { if (a.nedges != b.nedges) return a.nedges > b.nedges; return a.radius > b.radius; }); out.watertight = out.boundaryEdges == 0 && out.nonManifoldEdges == 0 && out.components.size() == 1; return out; } void TriangleGrid::build(const mesh::Mesh& m) { source = &m; offsets.clear(); triangleIds.clear(); if (m.tris.empty() || m.verts.empty()) { nx = ny = nz = 1; offsets.assign(2, 0); return; } origin = m.bbMin; Vec3 span = m.bbMax - m.bbMin; double diag = std::max(m.bboxDiag(), 1e-9); std::size_t target = std::max( 1, std::min(2000000, m.tris.size() / 4 + 1)); cellSize = diag / std::cbrt((double)target); cellSize = std::max(cellSize, diag * 1e-9); nx = std::max(1, (int)std::ceil(span.x / cellSize)); ny = std::max(1, (int)std::ceil(span.y / cellSize)); nz = std::max(1, (int)std::ceil(span.z / cellSize)); auto product = [&]() { return (std::uint64_t)nx * (std::uint64_t)ny * (std::uint64_t)nz; }; while (product() > 3000000) { cellSize *= 1.15; nx = std::max(1, (int)std::ceil(span.x / cellSize)); ny = std::max(1, (int)std::ceil(span.y / cellSize)); nz = std::max(1, (int)std::ceil(span.z / cellSize)); } std::size_t ncells = (std::size_t)product(); std::vector counts(ncells, 0); auto coord = [&](double x, double o, int n) { return std::max(0, std::min(n - 1, (int)std::floor((x - o) / cellSize))); }; auto bounds = [&](const Tri& t, int& x0, int& x1, int& y0, int& y1, int& z0, int& z1) { const Vec3& a = m.verts[t[0]]; const Vec3& b = m.verts[t[1]]; const Vec3& c = m.verts[t[2]]; x0 = coord(std::min({a.x, b.x, c.x}), origin.x, nx); x1 = coord(std::max({a.x, b.x, c.x}), origin.x, nx); y0 = coord(std::min({a.y, b.y, c.y}), origin.y, ny); y1 = coord(std::max({a.y, b.y, c.y}), origin.y, ny); z0 = coord(std::min({a.z, b.z, c.z}), origin.z, nz); z1 = coord(std::max({a.z, b.z, c.z}), origin.z, nz); }; auto index = [&](int x, int y, int z) { return ((std::size_t)z * (std::size_t)ny + (std::size_t)y) * (std::size_t)nx + (std::size_t)x; }; for (const Tri& t : m.tris) { int x0, x1, y0, y1, z0, z1; bounds(t, x0, x1, y0, y1, z0, z1); for (int z = z0; z <= z1; ++z) for (int y = y0; y <= y1; ++y) for (int x = x0; x <= x1; ++x) ++counts[index(x, y, z)]; } offsets.resize(ncells + 1, 0); for (std::size_t i = 0; i < ncells; ++i) offsets[i + 1] = offsets[i] + counts[i]; triangleIds.resize((std::size_t)offsets.back()); std::vector cursor = offsets; for (int ti = 0; ti < (int)m.tris.size(); ++ti) { int x0, x1, y0, y1, z0, z1; bounds(m.tris[ti], x0, x1, y0, y1, z0, z1); for (int z = z0; z <= z1; ++z) for (int y = y0; y <= y1; ++y) for (int x = x0; x <= x1; ++x) { std::size_t ci = index(x, y, z); triangleIds[(std::size_t)cursor[ci]++] = ti; } } } bool TriangleGrid::closestPoint(const Vec3& p, Vec3& point, Vec3& normal, double& distance) const { if (!source || source->tris.empty() || offsets.size() < 2) return false; auto coord = [&](double x, double o, int n) { return std::max(0, std::min(n - 1, (int)std::floor((x - o) / cellSize))); }; int cx = coord(p.x, origin.x, nx); int cy = coord(p.y, origin.y, ny); int cz = coord(p.z, origin.z, nz); auto index = [&](int x, int y, int z) { return ((std::size_t)z * (std::size_t)ny + (std::size_t)y) * (std::size_t)nx + (std::size_t)x; }; double best2 = std::numeric_limits::infinity(); Vec3 bestPoint, bestNormal; int maxRing = std::max({nx, ny, nz}); for (int r = 0; r < maxRing; ++r) { int x0 = std::max(0, cx - r), x1 = std::min(nx - 1, cx + r); int y0 = std::max(0, cy - r), y1 = std::min(ny - 1, cy + r); int z0 = std::max(0, cz - r), z1 = std::min(nz - 1, cz + r); for (int z = z0; z <= z1; ++z) for (int y = y0; y <= y1; ++y) for (int x = x0; x <= x1; ++x) { if (r > 0 && x != x0 && x != x1 && y != y0 && y != y1 && z != z0 && z != z1) continue; std::size_t ci = index(x, y, z); for (std::uint64_t q = offsets[ci]; q < offsets[ci + 1]; ++q) { const Tri& t = source->tris[triangleIds[(std::size_t)q]]; Vec3 cp = closestPointTriangle( p, source->verts[t[0]], source->verts[t[1]], source->verts[t[2]]); double d2 = geom::dot(p - cp, p - cp); if (d2 < best2) { best2 = d2; bestPoint = cp; bestNormal = geom::normalize(geom::cross( source->verts[t[1]] - source->verts[t[0]], source->verts[t[2]] - source->verts[t[0]])); } } } if (std::isfinite(best2)) { double lower = std::numeric_limits::infinity(); if (x0 > 0) lower = std::min(lower, p.x - (origin.x + x0 * cellSize)); if (x1 + 1 < nx) lower = std::min(lower, origin.x + (x1 + 1) * cellSize - p.x); if (y0 > 0) lower = std::min(lower, p.y - (origin.y + y0 * cellSize)); if (y1 + 1 < ny) lower = std::min(lower, origin.y + (y1 + 1) * cellSize - p.y); if (z0 > 0) lower = std::min(lower, p.z - (origin.z + z0 * cellSize)); if (z1 + 1 < nz) lower = std::min(lower, origin.z + (z1 + 1) * cellSize - p.z); if (!std::isfinite(lower) || best2 <= lower * lower) break; } } if (!std::isfinite(best2)) return false; point = bestPoint; normal = bestNormal; distance = std::sqrt(best2); return true; } double TriangleGrid::closestDistance(const Vec3& p) const { Vec3 point, normal; double distance = std::numeric_limits::infinity(); closestPoint(p, point, normal, distance); return distance; } DeviationStats deviationStats(const mesh::Mesh& edited, const TriangleGrid& original, double tolerance) { DeviationStats out; out.distances.reserve(edited.verts.size()); long double sum2 = 0; std::size_t within = 0; for (const Vec3& p : edited.verts) { double d = original.closestDistance(p); out.distances.push_back(d); out.max = std::max(out.max, d); sum2 += (long double)d * d; if (d <= tolerance) ++within; } if (!out.distances.empty()) { out.rms = std::sqrt((double)(sum2 / out.distances.size())); out.pctWithin = 100.0 * (double)within / out.distances.size(); } return out; } DeviationStats deviationStats(const mesh::Mesh& edited, const mesh::Mesh& original, double tolerance) { TriangleGrid grid(original); return deviationStats(edited, grid, tolerance); } namespace { struct Quadric { // xx xy xz xw yy yz yw zz zw ww std::array a{}; Quadric& operator+=(const Quadric& q) { for (int i = 0; i < 10; ++i) a[i] += q.a[i]; return *this; } }; Quadric operator+(Quadric a, const Quadric& b) { a += b; return a; } void addPlane(Quadric& q, const Vec3& n, double d, double w) { double p[4] = {n.x, n.y, n.z, d}; int k = 0; for (int i = 0; i < 4; ++i) for (int j = i; j < 4; ++j) q.a[k++] += w * p[i] * p[j]; } double quadricCost(const Quadric& q, const Vec3& p) { double x = p.x, y = p.y, z = p.z; return q.a[0] * x * x + 2 * q.a[1] * x * y + 2 * q.a[2] * x * z + 2 * q.a[3] * x + q.a[4] * y * y + 2 * q.a[5] * y * z + 2 * q.a[6] * y + q.a[7] * z * z + 2 * q.a[8] * z + q.a[9]; } bool solveOptimal(const Quadric& q, Vec3& p) { double a00 = q.a[0], a01 = q.a[1], a02 = q.a[2]; double a11 = q.a[4], a12 = q.a[5], a22 = q.a[7]; double b0 = -q.a[3], b1 = -q.a[6], b2 = -q.a[8]; double det = a00 * (a11 * a22 - a12 * a12) - a01 * (a01 * a22 - a12 * a02) + a02 * (a01 * a12 - a11 * a02); double scale = std::max({std::fabs(a00), std::fabs(a11), std::fabs(a22), 1.0}); if (std::fabs(det) < 1e-12 * scale * scale * scale) return false; double i00 = (a11 * a22 - a12 * a12) / det; double i01 = (a02 * a12 - a01 * a22) / det; double i02 = (a01 * a12 - a02 * a11) / det; double i11 = (a00 * a22 - a02 * a02) / det; double i12 = (a01 * a02 - a00 * a12) / det; double i22 = (a00 * a11 - a01 * a01) / det; p = {i00 * b0 + i01 * b1 + i02 * b2, i01 * b0 + i11 * b1 + i12 * b2, i02 * b0 + i12 * b1 + i22 * b2}; return std::isfinite(p.x) && std::isfinite(p.y) && std::isfinite(p.z); } std::pair collapsePoint(const Quadric& q, const Vec3& a, const Vec3& b) { Vec3 p; if (solveOptimal(q, p)) return {p, quadricCost(q, p)}; Vec3 mid = (a + b) * 0.5; double ca = quadricCost(q, a), cb = quadricCost(q, b); double cm = quadricCost(q, mid); if (ca <= cb && ca <= cm) return {a, ca}; if (cb <= cm) return {b, cb}; return {mid, cm}; } struct Candidate { double cost; std::uint64_t edge; std::uint32_t vu, vv; bool operator<(const Candidate& o) const { return cost > o.cost; } }; } // namespace std::size_t decimate(mesh::Mesh& m, std::size_t targetTriangles) { if (m.tris.size() <= 4 || targetTriangles >= m.tris.size()) return m.tris.size(); targetTriangles = std::max(4, targetTriangles); const int nv = (int)m.verts.size(); const int nt = (int)m.tris.size(); std::vector quadrics(nv); std::vector head(nv, -1); std::vector next((std::size_t)nt * 3, -1); std::vector edges; edges.reserve((std::size_t)nt * 3); double totalArea = 0; for (int ti = 0; ti < nt; ++ti) { Tri& t = m.tris[ti]; Vec3 cr = geom::cross(m.verts[t[1]] - m.verts[t[0]], m.verts[t[2]] - m.verts[t[0]]); double area = 0.5 * geom::norm(cr); totalArea += area; if (area > kTiny) { Vec3 n = cr / (2.0 * area); double d = -geom::dot(n, m.verts[t[0]]); for (int k = 0; k < 3; ++k) addPlane(quadrics[t[k]], n, d, area); } for (int k = 0; k < 3; ++k) { int node = ti * 3 + k; next[node] = head[t[k]]; head[t[k]] = node; } edges.push_back(edgeKey(t[0], t[1])); edges.push_back(edgeKey(t[1], t[2])); edges.push_back(edgeKey(t[2], t[0])); } std::sort(edges.begin(), edges.end()); std::vector boundary; boundary.reserve(edges.size() / 100 + 8); std::size_t uniqueCount = 0; for (std::size_t i = 0; i < edges.size();) { std::size_t j = i + 1; while (j < edges.size() && edges[j] == edges[i]) ++j; if (j - i == 1) boundary.push_back(edges[i]); edges[uniqueCount++] = edges[i]; i = j; } edges.resize(uniqueCount); edges.shrink_to_fit(); double areaScale = totalArea / std::max(1, nt); for (std::uint64_t key : boundary) { int a = edgeLo(key), b = edgeHi(key); int face = -1; for (int node = head[a]; node >= 0; node = next[node]) { int ti = node / 3; const Tri& t = m.tris[ti]; if (t[0] == b || t[1] == b || t[2] == b) { face = ti; break; } } if (face < 0) continue; const Tri& t = m.tris[face]; Vec3 fn = geom::normalize(geom::cross(m.verts[t[1]] - m.verts[t[0]], m.verts[t[2]] - m.verts[t[0]])); Vec3 en = geom::normalize(m.verts[b] - m.verts[a]); Vec3 pn = geom::normalize(geom::cross(fn, en)); double d = -geom::dot(pn, m.verts[a]); double weight = 1000.0 * std::max(areaScale, kTiny); addPlane(quadrics[a], pn, d, weight); addPlane(quadrics[b], pn, d, weight); } std::vector version(nv, 0); std::vector vertexAlive(nv, 1), triAlive(nt, 1); std::priority_queue heap; for (std::uint64_t key : edges) { int a = edgeLo(key), b = edgeHi(key); auto cp = collapsePoint(quadrics[a] + quadrics[b], m.verts[a], m.verts[b]); heap.push({cp.second, key, 0, 0}); } std::vector().swap(edges); std::vector().swap(boundary); auto incident = [&](int v, std::vector& out) { out.clear(); // Unlink dead/retargeted nodes as we walk: without pruning, hub vertices // keep every node from every historical collapse and this walk (plus its // sort) turns the whole decimation quadratic on scan-sized meshes. int node = head[v], prevNode = -1; while (node >= 0) { int nx = next[node]; int ti = node / 3; const Tri& t = m.tris[ti]; bool live = triAlive[ti] && (t[0] == v || t[1] == v || t[2] == v); if (!live) { if (prevNode < 0) head[v] = nx; else next[prevNode] = nx; } else { out.push_back(ti); prevNode = node; } node = nx; } std::sort(out.begin(), out.end()); out.erase(std::unique(out.begin(), out.end()), out.end()); }; auto neighbors = [&](int v, const std::vector& inc, std::vector& out) { out.clear(); for (int ti : inc) for (int x : m.tris[ti]) if (x != v && vertexAlive[x]) out.push_back(x); std::sort(out.begin(), out.end()); out.erase(std::unique(out.begin(), out.end()), out.end()); }; std::size_t aliveTriangles = m.tris.size(); std::vector iu, iv, nu, nvlist, affected; while (aliveTriangles > targetTriangles && !heap.empty()) { Candidate c = heap.top(); heap.pop(); int u = edgeLo(c.edge), v = edgeHi(c.edge); if (!vertexAlive[u] || !vertexAlive[v] || c.vu != version[u] || c.vv != version[v]) continue; incident(u, iu); incident(v, iv); // Valence cap: on flat regions every collapse costs ~0, so the heap // happily funnels hundreds of collapses into one hub vertex whose ring // then grows unboundedly and per-collapse work goes quadratic. Skip // fan-building collapses — the neighboring edges collapse instead at // the same cost, reaching the same target count. if (iu.size() + iv.size() > 48) continue; neighbors(u, iu, nu); neighbors(v, iv, nvlist); int edgeIncidence = 0; for (int ti : iu) { const Tri& t = m.tris[ti]; if (t[0] == v || t[1] == v || t[2] == v) ++edgeIncidence; } if (edgeIncidence != 1 && edgeIncidence != 2) continue; int common = 0; std::size_t a = 0, b = 0; while (a < nu.size() && b < nvlist.size()) { if (nu[a] == nvlist[b]) { ++common; ++a; ++b; } else if (nu[a] < nvlist[b]) { ++a; } else { ++b; } } if (common != edgeIncidence) continue; Quadric merged = quadrics[u] + quadrics[v]; auto cp = collapsePoint(merged, m.verts[u], m.verts[v]); Vec3 pos = cp.first; affected = iu; affected.insert(affected.end(), iv.begin(), iv.end()); std::sort(affected.begin(), affected.end()); affected.erase(std::unique(affected.begin(), affected.end()), affected.end()); bool valid = true; for (int ti : affected) { const Tri& t = m.tris[ti]; bool hasU = t[0] == u || t[1] == u || t[2] == u; bool hasV = t[0] == v || t[1] == v || t[2] == v; if (hasU && hasV) continue; Vec3 oldn = geom::cross(m.verts[t[1]] - m.verts[t[0]], m.verts[t[2]] - m.verts[t[0]]); Vec3 p[3] = {m.verts[t[0]], m.verts[t[1]], m.verts[t[2]]}; for (int k = 0; k < 3; ++k) if (t[k] == u || t[k] == v) p[k] = pos; Vec3 newn = geom::cross(p[1] - p[0], p[2] - p[0]); double on = geom::norm(oldn), nn = geom::norm(newn); if (nn < on * 1e-8 || (on > kTiny && geom::dot(oldn, newn) < 0.2 * on * nn)) { valid = false; break; } } if (!valid) continue; m.verts[u] = pos; quadrics[u] = merged; vertexAlive[v] = 0; ++version[u]; ++version[v]; for (int ti : iv) { if (!triAlive[ti]) continue; Tri& t = m.tris[ti]; bool hasU = t[0] == u || t[1] == u || t[2] == u; if (hasU) { triAlive[ti] = 0; --aliveTriangles; continue; } for (int k = 0; k < 3; ++k) { if (t[k] != v) continue; t[k] = u; int node = ti * 3 + k; next[node] = head[u]; head[u] = node; break; } } head[v] = -1; incident(u, iu); neighbors(u, iu, nu); for (int w : nu) { int a0 = std::min(u, w), b0 = std::max(u, w); auto np = collapsePoint(quadrics[a0] + quadrics[b0], m.verts[a0], m.verts[b0]); heap.push({np.second, edgeKey(a0, b0), version[a0], version[b0]}); } } std::vector compactTris; compactTris.reserve(aliveTriangles); std::vector usedVertex(m.verts.size(), 0); for (int ti = 0; ti < nt; ++ti) { if (!triAlive[ti]) continue; compactTris.push_back(m.tris[ti]); for (int v : m.tris[ti]) usedVertex[v] = 1; } std::vector remap(m.verts.size(), -1); std::vector compactVerts; compactVerts.reserve(m.verts.size()); for (int i = 0; i < (int)m.verts.size(); ++i) if (usedVertex[i]) { remap[i] = (int)compactVerts.size(); compactVerts.push_back(m.verts[i]); } for (Tri& t : compactTris) for (int& v : t) v = remap[v]; m.verts.swap(compactVerts); m.tris.swap(compactTris); finishMutation(m); return m.tris.size(); } namespace { struct Point2 { double x, y; }; double orient2(const Point2& a, const Point2& b, const Point2& c) { return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); } bool pointInTriangle(const Point2& p, const Point2& a, const Point2& b, const Point2& c, double sign) { return orient2(a, b, p) * sign >= -1e-12 && orient2(b, c, p) * sign >= -1e-12 && orient2(c, a, p) * sign >= -1e-12; } struct Weight { double angle = std::numeric_limits::infinity(); double area = std::numeric_limits::infinity(); bool valid = false; }; bool lessWeight(const Weight& a, const Weight& b) { if (!a.valid) return false; if (!b.valid) return true; if (std::fabs(a.angle - b.angle) > 1e-12) return a.angle < b.angle; return a.area < b.area; } Weight combineWeight(const Weight& a, const Weight& b, const Weight& c) { if (!a.valid || !b.valid || !c.valid) return {}; return {std::max({a.angle, b.angle, c.angle}), a.area + b.area + c.area, true}; } Weight triangleWeight(const mesh::Mesh& m, int a, int b, int c) { Vec3 cr = geom::cross(m.verts[b] - m.verts[a], m.verts[c] - m.verts[a]); double twiceArea = geom::norm(cr); if (twiceArea < kTiny) return {}; Vec3 n = cr / twiceArea; Vec3 rim = m.vnormals.empty() ? n : geom::normalize(m.vnormals[a] + m.vnormals[b] + m.vnormals[c]); double cosine = std::max(-1.0, std::min(1.0, geom::dot(n, rim))); return {std::acos(cosine), 0.5 * twiceArea, true}; } bool triangulateDP(const mesh::Mesh& m, const std::vector& poly, const std::vector& p2, double sign, std::vector& patch) { int n = (int)poly.size(); std::vector dp((std::size_t)n * n); std::vector split((std::size_t)n * n, -1); auto at = [n](int i, int j) { return (std::size_t)i * n + j; }; for (int i = 0; i + 1 < n; ++i) dp[at(i, i + 1)] = {0, 0, true}; for (int gap = 2; gap < n; ++gap) { for (int i = 0; i + gap < n; ++i) { int j = i + gap; for (int k = i + 1; k < j; ++k) { if (orient2(p2[i], p2[k], p2[j]) * sign <= 1e-14) continue; Weight tw = triangleWeight(m, poly[i], poly[k], poly[j]); Weight candidate = combineWeight(dp[at(i, k)], dp[at(k, j)], tw); if (lessWeight(candidate, dp[at(i, j)])) { dp[at(i, j)] = candidate; split[at(i, j)] = k; } } } } if (!dp[at(0, n - 1)].valid) return false; std::vector> stack{{0, n - 1}}; while (!stack.empty()) { auto ij = stack.back(); stack.pop_back(); int i = ij.first, j = ij.second; if (j <= i + 1) continue; int k = split[at(i, j)]; if (k < 0) return false; patch.push_back({poly[i], poly[k], poly[j]}); stack.push_back({i, k}); stack.push_back({k, j}); } return true; } bool triangulateGreedy(const mesh::Mesh& m, const std::vector& poly, const std::vector& p2, double sign, std::vector& patch) { const int n = (int)poly.size(); std::vector prev(n), next(n), version(n, 0); std::vector active(n, 1); for (int i = 0; i < n; ++i) { prev[i] = (i + n - 1) % n; next[i] = (i + 1) % n; } // Static point bins make the empty-ear test local even as the active ring // shrinks. Removed vertices stay in the bins and are ignored by the mask. double xmin = p2[0].x, xmax = p2[0].x, ymin = p2[0].y, ymax = p2[0].y; for (const Point2& p : p2) { xmin = std::min(xmin, p.x); xmax = std::max(xmax, p.x); ymin = std::min(ymin, p.y); ymax = std::max(ymax, p.y); } int dim = std::max(1, (int)std::sqrt((double)n)); double sx = std::max((xmax - xmin) / dim, 1e-12); double sy = std::max((ymax - ymin) / dim, 1e-12); auto gx = [&](double x) { return std::max(0, std::min(dim - 1, (int)((x - xmin) / sx))); }; auto gy = [&](double y) { return std::max(0, std::min(dim - 1, (int)((y - ymin) / sy))); }; std::vector> bins((std::size_t)dim * dim); for (int i = 0; i < n; ++i) bins[(std::size_t)gy(p2[i].y) * dim + gx(p2[i].x)].push_back(i); auto isEar = [&](int j) { if (!active[j]) return false; int i = prev[j], k = next[j]; if (orient2(p2[i], p2[j], p2[k]) * sign <= 1e-14) return false; int x0 = gx(std::min({p2[i].x, p2[j].x, p2[k].x})); int x1 = gx(std::max({p2[i].x, p2[j].x, p2[k].x})); int y0 = gy(std::min({p2[i].y, p2[j].y, p2[k].y})); int y1 = gy(std::max({p2[i].y, p2[j].y, p2[k].y})); for (int y = y0; y <= y1; ++y) for (int x = x0; x <= x1; ++x) for (int r : bins[(std::size_t)y * dim + x]) { if (!active[r] || r == i || r == j || r == k) continue; if (pointInTriangle(p2[r], p2[i], p2[j], p2[k], sign)) return false; } return true; }; struct Ear { double angle, area; int vertex, version; bool operator<(const Ear& o) const { if (angle != o.angle) return angle > o.angle; return area > o.area; } }; std::priority_queue ears; auto pushEar = [&](int j) { if (!isEar(j)) return; Weight w = triangleWeight(m, poly[prev[j]], poly[j], poly[next[j]]); if (w.valid) ears.push({w.angle, w.area, j, version[j]}); }; for (int i = 0; i < n; ++i) pushEar(i); int remaining = n; while (remaining > 3) { Ear e; bool found = false; while (!ears.empty()) { e = ears.top(); ears.pop(); if (!active[e.vertex] || e.version != version[e.vertex] || !isEar(e.vertex)) continue; found = true; break; } if (!found) return false; int j = e.vertex, i = prev[j], k = next[j]; patch.push_back({poly[i], poly[j], poly[k]}); active[j] = 0; next[i] = k; prev[k] = i; ++version[i]; ++version[k]; --remaining; pushEar(i); pushEar(k); } int a = -1; for (int i = 0; i < n; ++i) if (active[i]) { a = i; break; } if (a < 0) return false; patch.push_back({poly[a], poly[next[a]], poly[next[next[a]]]}); return true; } int oppositeVertex(const Tri& t, int a, int b) { for (int v : t) if (v != a && v != b) return v; return -1; } bool splitTriangleEdge(Tri t, int a, int b, int w, Tri& first, Tri& second) { for (int k = 0; k < 3; ++k) { int x = t[k], y = t[(k + 1) % 3], z = t[(k + 2) % 3]; if ((x == a && y == b) || (x == b && y == a)) { first = {x, w, z}; second = {w, y, z}; return true; } } return false; } void refinePatch(mesh::Mesh& m, const Hole& hole, std::vector& patch) { double density = 0; for (int i = 0; i < hole.nedges; ++i) density += geom::norm(m.verts[hole.vertices[i]] - m.verts[hole.vertices[(i + 1) % hole.nedges]]); density /= std::max(1, hole.nedges); if (density <= kTiny) return; double limit = std::sqrt(2.0) * density; int maxSplits = std::min(20000, std::max(16, hole.nedges * 16)); int splitCount = 0; for (int pass = 0; pass < 32 && splitCount < maxSplits; ++pass) { struct Pair { int first = -1, second = -1; }; std::unordered_map map; map.reserve(patch.size() * 2); for (int ti = 0; ti < (int)patch.size(); ++ti) { const Tri& t = patch[ti]; for (int k = 0; k < 3; ++k) { Pair& e = map[edgeKey(t[k], t[(k + 1) % 3])]; if (e.first < 0) e.first = ti; else e.second = ti; } } struct LongEdge { double length; std::uint64_t key; Pair pair; }; std::vector longEdges; for (const auto& kv : map) { if (kv.second.second < 0) continue; // the fixed rim is never split int a = edgeLo(kv.first), b = edgeHi(kv.first); double len = geom::norm(m.verts[a] - m.verts[b]); if (len > limit) longEdges.push_back({len, kv.first, kv.second}); } if (longEdges.empty()) break; std::sort(longEdges.begin(), longEdges.end(), [](const LongEdge& a, const LongEdge& b) { return a.length > b.length; }); std::vector claimed(patch.size(), 0); std::unordered_map midpoint; midpoint.reserve(longEdges.size()); for (const LongEdge& e : longEdges) { if (splitCount >= maxSplits) break; if (claimed[e.pair.first] || claimed[e.pair.second]) continue; claimed[e.pair.first] = claimed[e.pair.second] = 1; int a = edgeLo(e.key), b = edgeHi(e.key); int w = (int)m.verts.size(); m.verts.push_back((m.verts[a] + m.verts[b]) * 0.5); midpoint.emplace(e.key, w); ++splitCount; } if (midpoint.empty()) break; std::vector refined; refined.reserve(patch.size() + midpoint.size() * 2); for (const Tri& t : patch) { bool didSplit = false; for (int k = 0; k < 3; ++k) { int a = t[k], b = t[(k + 1) % 3]; auto it = midpoint.find(edgeKey(a, b)); if (it == midpoint.end()) continue; Tri first, second; if (splitTriangleEdge(t, a, b, it->second, first, second)) { refined.push_back(first); refined.push_back(second); didSplit = true; } break; } if (!didSplit) refined.push_back(t); } patch.swap(refined); } // One conservative intrinsic-Delaunay pass improves the long, thin triangles // created by midpoint refinement without moving or subdividing the fixed rim. struct Pair { int first = -1, second = -1; }; std::unordered_map map; map.reserve(patch.size() * 2); for (int ti = 0; ti < (int)patch.size(); ++ti) for (int k = 0; k < 3; ++k) { Pair& e = map[edgeKey(patch[ti][k], patch[ti][(k + 1) % 3])]; if (e.first < 0) e.first = ti; else e.second = ti; } for (const auto& kv : map) { Pair e = kv.second; if (e.second < 0) continue; int a = edgeLo(kv.first), b = edgeHi(kv.first); int c = oppositeVertex(patch[e.first], a, b); int d = oppositeVertex(patch[e.second], a, b); if (c < 0 || d < 0 || c == d) continue; auto angle = [&](int x, int o, int y) { Vec3 u = geom::normalize(m.verts[x] - m.verts[o]); Vec3 v = geom::normalize(m.verts[y] - m.verts[o]); return std::acos(std::max(-1.0, std::min(1.0, geom::dot(u, v)))); }; if (angle(a, c, b) + angle(a, d, b) <= M_PI + 1e-6) continue; Tri t0 = patch[e.first], t1 = patch[e.second]; if (!directedEdge(t0, a, b)) { std::swap(t0, t1); std::swap(c, d); if (!directedEdge(t0, a, b)) std::swap(a, b); } if (!directedEdge(t1, b, a)) continue; Tri n0{c, d, b}, n1{d, c, a}; Vec3 oldn = geom::cross(m.verts[t0[1]] - m.verts[t0[0]], m.verts[t0[2]] - m.verts[t0[0]]) + geom::cross(m.verts[t1[1]] - m.verts[t1[0]], m.verts[t1[2]] - m.verts[t1[0]]); Vec3 newn = geom::cross(m.verts[n0[1]] - m.verts[n0[0]], m.verts[n0[2]] - m.verts[n0[0]]) + geom::cross(m.verts[n1[1]] - m.verts[n1[0]], m.verts[n1[2]] - m.verts[n1[0]]); if (geom::dot(oldn, newn) <= 0) continue; patch[e.first] = n0; patch[e.second] = n1; } } void fairPatch(mesh::Mesh& m, const Hole& hole, const std::vector& patch, const std::string& requested, int firstNewVertex) { int nnew = (int)m.verts.size() - firstNewVertex; if (nnew <= 0) return; std::string method = requested; if (method == "auto") method = hole.nedges < 40 ? "tangent" : "curvature"; std::unordered_map> adj; adj.reserve(patch.size()); auto link = [&](int a, int b) { adj[a].push_back(b); }; for (const Tri& t : patch) { link(t[0], t[1]); link(t[1], t[0]); link(t[1], t[2]); link(t[2], t[1]); link(t[2], t[0]); link(t[0], t[2]); } for (auto& kv : adj) { auto& a = kv.second; std::sort(a.begin(), a.end()); a.erase(std::unique(a.begin(), a.end()), a.end()); } std::vector interior; interior.reserve(nnew); for (int v = firstNewVertex; v < (int)m.verts.size(); ++v) interior.push_back(v); if (method == "tangent") { for (int it = 0; it < 200; ++it) { double maxMove = 0; for (int v : interior) { const auto& nb = adj[v]; if (nb.empty()) continue; Vec3 avg; for (int w : nb) avg = avg + m.verts[w]; avg = avg / (double)nb.size(); maxMove = std::max(maxMove, geom::norm(avg - m.verts[v])); m.verts[v] = avg; } if (maxMove < 1e-7) break; } return; } // Discrete thin-plate fairing: harmonically extend the rim's umbrella // curvature, then solve Δp=h with the boundary positions fixed. std::unordered_map h; h.reserve(adj.size()); for (int i = 0; i < hole.nedges; ++i) { int v = hole.vertices[i]; int prev = hole.vertices[(i + hole.nedges - 1) % hole.nedges]; int next = hole.vertices[(i + 1) % hole.nedges]; h[v] = (m.verts[v] - (m.verts[prev] + m.verts[next]) * 0.5) * 0.25; } for (int v : interior) h[v] = {}; for (int it = 0; it < 120; ++it) for (int v : interior) { Vec3 avg; for (int w : adj[v]) avg = avg + h[w]; if (!adj[v].empty()) h[v] = avg / (double)adj[v].size(); } for (int it = 0; it < 240; ++it) { double maxMove = 0; for (int v : interior) { Vec3 avg; for (int w : adj[v]) avg = avg + m.verts[w]; if (adj[v].empty()) continue; avg = avg / (double)adj[v].size() + h[v]; maxMove = std::max(maxMove, geom::norm(avg - m.verts[v])); m.verts[v] = avg; } if (maxMove < 1e-7) break; } } bool buildPatch(mesh::Mesh& m, const Hole& hole, const std::string& method, std::vector& patch) { if (hole.vertices.size() < 3) return false; Vec3 center; for (int v : hole.vertices) { if (v < 0 || v >= (int)m.verts.size()) return false; center = center + m.verts[v]; } center = center / (double)hole.vertices.size(); Vec3 normal; for (int i = 0; i < hole.nedges; ++i) { Vec3 a = m.verts[hole.vertices[i]] - center; Vec3 b = m.verts[hole.vertices[(i + 1) % hole.nedges]] - center; normal = normal + geom::cross(a, b); } if (geom::norm(normal) < kTiny) return false; Vec3 u, v; geom::basisFromNormal(normal, u, v); std::vector p2; p2.reserve(hole.vertices.size()); double signedArea = 0; for (int id : hole.vertices) { Vec3 d = m.verts[id] - center; p2.push_back({geom::dot(d, u), geom::dot(d, v)}); } for (int i = 0; i < hole.nedges; ++i) { const Point2& a = p2[i]; const Point2& b = p2[(i + 1) % hole.nedges]; signedArea += a.x * b.y - a.y * b.x; } double sign = signedArea >= 0 ? 1.0 : -1.0; bool ok = hole.nedges <= 200 ? triangulateDP(m, hole.vertices, p2, sign, patch) : triangulateGreedy(m, hole.vertices, p2, sign, patch); if (!ok) return false; int firstNewVertex = (int)m.verts.size(); refinePatch(m, hole, patch); fairPatch(m, hole, patch, method, firstNewVertex); return true; } } // namespace int fillHoles(mesh::Mesh& m, const std::vector& holes, const std::string& method) { int filled = 0; for (const Hole& h : holes) { std::vector patch; if (!buildPatch(m, h, method, patch)) continue; m.tris.insert(m.tris.end(), patch.begin(), patch.end()); ++filled; } if (filled) finishMutation(m); return filled; } int fillHole(mesh::Mesh& m, const Hole& hole, const std::string& method) { return fillHoles(m, std::vector{hole}, method); } int fillAllHoles(mesh::Mesh& m, const std::string& method, int maxEdges) { Analysis a = analyze(m); std::vector selected; for (const Hole& h : a.holes) if (maxEdges <= 0 || h.nedges <= maxEdges) selected.push_back(h); return fillHoles(m, selected, method); } int removeComponents(mesh::Mesh& m, const Analysis& analysis, const RemoveOptions& options) { if (analysis.components.empty() || analysis.triangleComponent.size() != m.tris.size()) return 0; std::vector remove(analysis.components.size(), 0); if (options.keepLargest) for (std::size_t i = 1; i < remove.size(); ++i) remove[i] = 1; for (int id : options.ids) if (id >= 0 && id < (int)remove.size()) remove[id] = 1; if (options.minTris >= 0) for (std::size_t i = 0; i < remove.size(); ++i) if (analysis.components[i].ntris < options.minTris) remove[i] = 1; if (options.minArea >= 0) for (std::size_t i = 0; i < remove.size(); ++i) if (analysis.components[i].area < options.minArea) remove[i] = 1; int removed = (int)std::count(remove.begin(), remove.end(), (char)1); if (!removed || removed == (int)remove.size()) return 0; std::vector tris; tris.reserve(m.tris.size()); std::vector used(m.verts.size(), 0); for (std::size_t ti = 0; ti < m.tris.size(); ++ti) { int id = analysis.triangleComponent[ti]; if (id < 0 || id >= (int)remove.size() || remove[id]) continue; tris.push_back(m.tris[ti]); for (int v : m.tris[ti]) used[v] = 1; } std::vector remap(m.verts.size(), -1); std::vector verts; verts.reserve(m.verts.size()); for (int i = 0; i < (int)m.verts.size(); ++i) if (used[i]) { remap[i] = (int)verts.size(); verts.push_back(m.verts[i]); } for (Tri& t : tris) for (int& v : t) v = remap[v]; m.verts.swap(verts); m.tris.swap(tris); finishMutation(m); return removed; } int removeComponents(mesh::Mesh& m, const RemoveOptions& options) { Analysis a = analyze(m); return removeComponents(m, a, options); } } // namespace meshedit