#include "fit.hpp" #include #include #include namespace fit { using geom::cross; using geom::dot; using geom::norm; using geom::normalize; using geom::Vec3; static Vec3 centroid(const std::vector& pts) { Vec3 c{0, 0, 0}; for (const auto& p : pts) c = c + p; return pts.empty() ? c : c / (double)pts.size(); } // 3x3 covariance of a point set about its centroid. static void covariance(const std::vector& pts, const Vec3& c, double C[3][3]) { for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) C[i][j] = 0; for (const auto& p : pts) { Vec3 d = p - c; double dd[3] = {d.x, d.y, d.z}; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) C[i][j] += dd[i] * dd[j]; } } PlaneFit fitPlanePoints(const std::vector& pts, const std::vector& nrm, const Vec3& viewDir) { PlaneFit f; if (pts.size() < 3) return f; Vec3 c = centroid(pts); double C[3][3]; covariance(pts, c, C); double ev[3], V[3][3]; geom::jacobiEigen3(C, ev, V); // Smallest-eigenvalue eigenvector (column 0) is the plane normal. Vec3 n = normalize({V[0][0], V[1][0], V[2][0]}); // Orient normal toward the pick side using averaged vertex normals (fallback: viewDir). Vec3 avgN{0, 0, 0}; for (const auto& vn : nrm) avgN = avgN + vn; if (norm(avgN) > 1e-9) { if (dot(n, avgN) < 0) n = n * -1.0; } else if (norm(viewDir) > 1e-9 && dot(n, viewDir) < 0) { n = n * -1.0; } geom::basisFromNormal(n, f.u, f.v); f.origin = c; f.normal = n; f.ok = true; f.npts = (int)pts.size(); double s2 = 0; for (const auto& p : pts) { double d = dot(p - c, n); s2 += d * d; } f.rms = std::sqrt(s2 / pts.size()); return f; } PlaneFit fitPlane(const mesh::Mesh& m, const Vec3& seed, double radius, const Vec3& viewDir) { auto ids = mesh::verticesInRadius(m, seed, radius); std::vector pts, nrm; pts.reserve(ids.size()); nrm.reserve(ids.size()); for (int i : ids) { pts.push_back(m.verts[i]); nrm.push_back(m.vnormals[i]); } return fitPlanePoints(pts, nrm, viewDir); } PlaneFit fitPlaneSlab(const mesh::Mesh& m, const Vec3& seed, double radius, const Vec3& axis, double slabHalf, std::vector* supportPts, std::vector* supportNrm) { Vec3 ax = normalize(axis); // Normal-consistency filter: near a plate edge the slab also catches side- and // bore-wall vertices (normals ⊥ axis), which tilt the fit by fractions of a // degree. Keep face points only (normal within ~45° of the axis, either sign); // fall back to the unfiltered set if the scan's normals are too noisy to pass. std::vector pts, nrm, ptsAll, nrmAll; for (int i : mesh::verticesInRadius(m, seed, radius)) { if (std::abs(dot(m.verts[i] - seed, ax)) > slabHalf) continue; ptsAll.push_back(m.verts[i]); nrmAll.push_back(m.vnormals[i]); if (std::fabs(dot(m.vnormals[i], ax)) < 0.7) continue; pts.push_back(m.verts[i]); nrm.push_back(m.vnormals[i]); } if (pts.size() < 30) { pts = std::move(ptsAll); nrm = std::move(nrmAll); } PlaneFit f = fitPlanePoints(pts, nrm, ax); if (supportPts) *supportPts = std::move(pts); if (supportNrm) *supportNrm = std::move(nrm); return f; } int materialSide(const mesh::Mesh& m, const Vec3& seat, const Vec3& axis, double radius, double height) { if (m.empty() || height <= 0 || radius <= 0) return 0; Vec3 ax = normalize(axis); // Skip a band around the seat plane itself: its own vertices scatter to either // side by scan noise and would dilute the vote. const double band = std::min(1.0, height * 0.2); const double reach = std::sqrt(radius * radius + height * height); int pos = 0, neg = 0; for (int i : mesh::verticesInRadius(m, seat, reach)) { Vec3 d = m.verts[i] - seat; double t = dot(d, ax); if (std::abs(t) < band || std::abs(t) > height) continue; Vec3 r = d - ax * t; if (dot(r, r) > radius * radius) continue; (t > 0 ? pos : neg)++; } if (pos + neg < 30) return 0; // too little evidence either way if (pos > neg * 3) return +1; if (neg > pos * 3) return -1; return 0; } // Taubin circle fit in 2D. Far less biased than algebraic (Kasa) fitting on // short arcs, which is exactly the regime a clicked hole patch produces. // Ref: G. Taubin, PAMI 1991 / N. Chernov's implementation. static bool circleFit2D(const std::vector>& q, double& cx, double& cy, double& r) { int n = (int)q.size(); if (n < 3) return false; double xm = 0, ym = 0; for (auto& p : q) { xm += p[0]; ym += p[1]; } xm /= n; ym /= n; double Mxx = 0, Myy = 0, Mxy = 0, Mxz = 0, Myz = 0, Mzz = 0; for (auto& p : q) { double X = p[0] - xm, Y = p[1] - ym, Z = X * X + Y * Y; Mxx += X * X; Myy += Y * Y; Mxy += X * Y; Mxz += X * Z; Myz += Y * Z; Mzz += Z * Z; } Mxx /= n; Myy /= n; Mxy /= n; Mxz /= n; Myz /= n; Mzz /= n; double Mz = Mxx + Myy; double Cov_xy = Mxx * Myy - Mxy * Mxy; double Var_z = Mzz - Mz * Mz; double A3 = 4 * Mz; double A2 = -3 * Mz * Mz - Mzz; double A1 = Var_z * Mz + 4 * Cov_xy * Mz - Mxz * Mxz - Myz * Myz; double A0 = Mxz * (Mxz * Myy - Myz * Mxy) + Myz * (Myz * Mxx - Mxz * Mxy) - Var_z * Cov_xy; double A22 = A2 + A2, A33 = A3 + A3 + A3; double x = 0, y = A0; for (int it = 0; it < 50; ++it) { double Dy = A1 + x * (A22 + x * A33); if (std::fabs(Dy) < 1e-300) break; double xn = x - y / Dy; if (xn == x || !std::isfinite(xn)) break; double yn = A0 + xn * (A1 + xn * (A2 + xn * A3)); x = xn; y = yn; if (std::fabs(y) < 1e-14) break; } double det = x * x - x * Mz + Cov_xy; if (std::fabs(det) < 1e-300) return false; double xc = (Mxz * (Myy - x) - Myz * Mxy) / det / 2.0; double yc = (Myz * (Mxx - x) - Mxz * Mxy) / det / 2.0; double rr = xc * xc + yc * yc + Mz; if (rr <= 0) return false; cx = xc + xm; cy = yc + ym; r = std::sqrt(rr); return true; } // Axis = smallest-eigenvalue eigenvector of the normals' outer-product matrix: // surface normals on a cylinder are perpendicular to the axis. static Vec3 axisFromNormals(const std::vector& nrm) { double N[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; for (const auto& n : nrm) { double nn[3] = {n.x, n.y, n.z}; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) N[i][j] += nn[i] * nn[j]; } double ev[3], V[3][3]; geom::jacobiEigen3(N, ev, V); return normalize({V[0][0], V[1][0], V[2][0]}); } CylinderFit fitCylinderPoints(std::vector pts, std::vector nrm, double knownDiameter, const Vec3& axisHint) { CylinderFit f; if (pts.size() < 6) return f; // --- reject flat-face points adjacent to the hole: a wall point's normal is // perpendicular to the axis, a face point's normal is parallel to it. We seed // the axis from all normals, then keep only points whose normal is roughly // perpendicular to that seed and re-seed from the survivors. --- Vec3 axis = (norm(axisHint) > 1e-6) ? normalize(axisHint) : axisFromNormals(nrm); { std::vector wpts, wnrm; for (size_t i = 0; i < pts.size(); ++i) if (std::fabs(dot(nrm[i], axis)) < 0.6) { // |cos| < 0.6 (>53° off axis) wpts.push_back(pts[i]); wnrm.push_back(nrm[i]); } if (wpts.size() >= 6) { pts.swap(wpts); nrm.swap(wnrm); axis = axisFromNormals(nrm); } } Vec3 axisPt = centroid(pts); double r = (knownDiameter > 0) ? knownDiameter / 2.0 : 0.0; auto projectAndFit = [&](const Vec3& ax, const std::vector& P, Vec3& centerOut, double& rOut) -> bool { Vec3 uu, vv; geom::basisFromNormal(ax, uu, vv); Vec3 base = centroid(P); std::vector> q; q.reserve(P.size()); for (const auto& p : P) { Vec3 d = p - base; q.push_back({dot(d, uu), dot(d, vv)}); } double cx, cy, rr; if (!circleFit2D(q, cx, cy, rr)) return false; if (knownDiameter > 0) { // The unconstrained fit's center is biased on short/off-centre arcs because // center and radius trade off. With the radius known (calipers/thread), refine // the center alone to minimize Σ(‖q_i−c‖ − R)² via Gauss–Newton (a 2×2 solve). const double R = knownDiameter / 2.0; for (int it = 0; it < 8; ++it) { double a00 = 0, a01 = 0, a11 = 0, b0 = 0, b1 = 0; for (const auto& p : q) { double dx = p[0] - cx, dy = p[1] - cy; double d = std::sqrt(dx * dx + dy * dy); if (d < 1e-9) continue; double ux = dx / d, uy = dy / d, e = d - R; a00 += ux * ux; a01 += ux * uy; a11 += uy * uy; b0 += ux * e; b1 += uy * e; } double det = a00 * a11 - a01 * a01; if (std::fabs(det) < 1e-12) break; double dcx = (a11 * b0 - a01 * b1) / det; double dcy = (a00 * b1 - a01 * b0) / det; cx += dcx; cy += dcy; if (dcx * dcx + dcy * dcy < 1e-14) break; } rr = R; } centerOut = base + uu * cx + vv * cy; rOut = rr; return true; }; // Initial fit, then a couple of IRLS passes that drop radial outliers and // re-seed the axis from the inliers' normals. { Vec3 center; double rr; if (!projectAndFit(axis, pts, center, rr)) return f; axisPt = center; if (knownDiameter <= 0) r = rr; } for (int pass = 0; pass < 3; ++pass) { std::vector in, inN; double thresh = std::max(0.25 * r, 3.0 * (f.rms > 0 ? f.rms : 0.1)); for (size_t i = 0; i < pts.size(); ++i) { Vec3 d = pts[i] - axisPt; double t = dot(d, axis); double rd = norm(d - axis * t); if (std::fabs(rd - r) <= thresh) { in.push_back(pts[i]); inN.push_back(nrm[i]); } } if (in.size() < 6) break; axis = axisFromNormals(inN); Vec3 center; double rr; if (!projectAndFit(axis, in, center, rr)) break; axisPt = center; if (knownDiameter <= 0) r = rr; pts.swap(in); nrm.swap(inN); // recompute rms for the next threshold double s2 = 0; for (const auto& p : pts) { Vec3 d = p - axisPt; double rd = norm(d - axis * dot(d, axis)) - r; s2 += rd * rd; } f.rms = std::sqrt(s2 / pts.size()); } if (knownDiameter > 0) { r = knownDiameter / 2.0; f.radiusFixed = true; } if (r <= 0) return f; // axial extent + residual double tmin = 1e300, tmax = -1e300, s2 = 0; for (const auto& p : pts) { Vec3 d = p - axisPt; double t = dot(d, axis); tmin = std::min(tmin, t); tmax = std::max(tmax, t); Vec3 radial = d - axis * t; double rd = norm(radial) - r; s2 += rd * rd; } f.ok = true; f.axisDir = axis; f.axisPoint = axisPt; f.radius = r; f.diameter = 2 * r; f.tMin = tmin; f.tMax = tmax; f.p1 = axisPt + axis * tmin; f.p2 = axisPt + axis * tmax; f.rms = std::sqrt(s2 / pts.size()); f.npts = (int)pts.size(); return f; } CylinderFit fitCylinder(const mesh::Mesh& m, const Vec3& seed, double radius, double knownDiameter, const Vec3& axisHint) { auto ids = mesh::verticesInRadius(m, seed, radius); std::vector pts, nrm; pts.reserve(ids.size()); nrm.reserve(ids.size()); for (int i : ids) { pts.push_back(m.verts[i]); nrm.push_back(m.vnormals[i]); } return fitCylinderPoints(std::move(pts), std::move(nrm), knownDiameter, axisHint); } // ---------------------------------------------------------------- seat plane static bool insideRegion(const Vec3& p, const std::vector>& region) { for (const auto& pl : region) if (pl[0] * p.x + pl[1] * p.y + pl[2] * p.z + pl[3] > 1e-6) return false; return true; } // Iteratively trim points far from the current plane and refit. `nrm` may be // shorter than `pts` (cloud points carry no normals); orientation comes from the // available normals, falling back to viewDir. static PlaneFit trimRefit(std::vector pts, std::vector nrm, const Vec3& viewDir, int rounds) { PlaneFit f = fitPlanePoints(pts, nrm, viewDir); for (int it = 0; it < rounds && f.ok; ++it) { // 1.5×MAD band, floored so pristine synthetic data doesn't trim to nothing std::vector ad(pts.size()); for (size_t i = 0; i < pts.size(); ++i) ad[i] = std::fabs(dot(pts[i] - f.origin, f.normal)); std::vector tmp = ad; std::nth_element(tmp.begin(), tmp.begin() + tmp.size() / 2, tmp.end()); double band = std::max(3.0 * tmp[tmp.size() / 2], 0.05); std::vector in, inN; for (size_t i = 0; i < pts.size(); ++i) if (ad[i] <= band) { in.push_back(pts[i]); if (i < nrm.size()) inN.push_back(nrm[i]); } if (in.size() < 3 || in.size() == pts.size()) break; pts.swap(in); nrm.swap(inN); f = fitPlanePoints(pts, nrm, viewDir); } return f; } // Merge cloud points lying within a band of the plane and refit once. The mesh // normals still orient the result; cloud points only tighten position/tilt. static void mergeCloudAndRefit(PlaneFit& f, std::vector pts, std::vector nrm, const std::vector& cloudCandidates, const Vec3& viewDir, int& ncloudOut) { ncloudOut = 0; if (!f.ok || cloudCandidates.empty()) return; double band = std::max(2.0 * f.rms, 0.2); size_t nmesh = pts.size(); for (const auto& p : cloudCandidates) if (std::fabs(dot(p - f.origin, f.normal)) <= band) pts.push_back(p); ncloudOut = (int)(pts.size() - nmesh); if (ncloudOut == 0) return; PlaneFit g = fitPlanePoints(pts, nrm, viewDir); if (g.ok && dot(g.normal, f.normal) > 0.9) f = g; // sanity: don't let noise flip it else ncloudOut = 0; } SeatFit fitPlaneRegion(const mesh::Mesh& m, const std::vector& cloud, const std::vector>& region, const Vec3& viewDir) { SeatFit s; if (region.empty()) return s; std::vector pts, nrm; for (size_t i = 0; i < m.verts.size(); ++i) if (insideRegion(m.verts[i], region)) { // keep the camera-facing side only; the column also crosses the back if (norm(viewDir) > 1e-6 && dot(m.vnormals[i], viewDir) < 0.2) continue; pts.push_back(m.verts[i]); nrm.push_back(m.vnormals[i]); } if (pts.size() < 12) return s; // Dominant orientation among the front-facing points, then keep points whose // normal agrees (rejects hole walls and perpendicular flanges in the box). // Largest eigenvector of the normals' outer-product matrix = the direction // the normals cluster around. Vec3 n0; { double N[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; for (const auto& n : nrm) { double nn[3] = {n.x, n.y, n.z}; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) N[i][j] += nn[i] * nn[j]; } double ev[3], V[3][3]; geom::jacobiEigen3(N, ev, V); n0 = normalize({V[0][2], V[1][2], V[2][2]}); if (norm(viewDir) > 1e-6 && dot(n0, viewDir) < 0) n0 = n0 * -1.0; } std::vector fpts, fnrm; for (size_t i = 0; i < pts.size(); ++i) if (dot(nrm[i], n0) > 0.866) { // within 30° fpts.push_back(pts[i]); fnrm.push_back(nrm[i]); } if (fpts.size() < 12) { fpts = pts; fnrm = nrm; } // The column may still hold two parallel faces (e.g. near/far side of a tube): // keep the densest offset band along n0, preferring the one nearest the camera. { std::vector t(fpts.size()); double tmin = 1e300, tmax = -1e300; for (size_t i = 0; i < fpts.size(); ++i) { t[i] = dot(fpts[i], n0); tmin = std::min(tmin, t[i]); tmax = std::max(tmax, t[i]); } double span = tmax - tmin; if (span > 2.0) { // only bother when the spread suggests multiple surfaces const int NB = 64; std::vector hist(NB, 0); for (double ti : t) { int b = (int)((ti - tmin) / span * (NB - 1)); hist[b]++; } int best = 0; for (int b = 1; b < NB; ++b) if (hist[b] > hist[best]) best = b; double bw = span / NB; double lo = tmin + (best - 1.5) * bw, hi = tmin + (best + 2.5) * bw; std::vector bpts, bnrm; for (size_t i = 0; i < fpts.size(); ++i) if (t[i] >= lo && t[i] <= hi) { bpts.push_back(fpts[i]); bnrm.push_back(fnrm[i]); } if (bpts.size() >= 12) { fpts.swap(bpts); fnrm.swap(bnrm); } } } PlaneFit f = trimRefit(fpts, fnrm, viewDir, 3); if (!f.ok) return s; std::vector cc; for (const auto& p : cloud) if (insideRegion(p, region)) cc.push_back(p); int nc = 0; mergeCloudAndRefit(f, fpts, fnrm, cc, viewDir, nc); static_cast(s) = f; s.ncloud = nc; return s; } SeatFit fitPlaneRim(const mesh::Mesh& m, const std::vector& cloud, const Vec3& a, const Vec3& b, const Vec3& c, const Vec3& viewDir) { SeatFit s; Vec3 n = cross(b - a, c - a); if (norm(n) < 1e-9) return s; // colinear picks n = normalize(n); if (norm(viewDir) > 1e-6 && dot(n, viewDir) < 0) n = n * -1.0; Vec3 c0 = (a + b + c) / 3.0; double R = std::max({norm(a - c0), norm(b - c0), norm(c - c0)}); double searchR = R * 1.8 + 2.0; // face annulus around the opening // Points near the rim plane: the surrounding face joins, the bore wall // (perpendicular, quickly departing the plane) gets band-rejected. std::vector pts, nrm; for (int i : mesh::verticesInRadius(m, c0, searchR)) { if (std::fabs(dot(m.verts[i] - c0, n)) > 1.0) continue; if (dot(m.vnormals[i], n) < 0.5) continue; // keep face points, drop wall pts.push_back(m.verts[i]); nrm.push_back(m.vnormals[i]); } PlaneFit f; if (pts.size() >= 12) { f = trimRefit(pts, nrm, n, 3); if (f.ok && dot(f.normal, n) < 0.94) f.ok = false; // refit wandered >20° off the rim } if (!f.ok) { // fall back to the exact 3-point plane f.ok = true; f.origin = c0; f.normal = n; geom::basisFromNormal(n, f.u, f.v); f.rms = 0; f.npts = 3; pts.clear(); nrm.clear(); } std::vector cc; for (const auto& p : cloud) if (norm(p - c0) <= searchR) cc.push_back(p); int nc = 0; mergeCloudAndRefit(f, pts, nrm, cc, n, nc); static_cast(s) = f; s.ncloud = nc; return s; } SeatFit refitSeatParallel(const mesh::Mesh& m, const std::vector& cloud, const SeatFit& seat, const Vec3& n_in) { SeatFit s = seat; if (!seat.ok) return s; Vec3 n = normalize(n_in); if (dot(n, seat.normal) < 0) n = n * -1.0; // keep the seat's orientation sense // Re-select the seat's support (near the old plane) and fit only the offset // along the locked normal, with one trim round. double searchR = std::max(6.0, 4.0 * seat.rms + 6.0); std::vector t; auto collect = [&](const Vec3& p) { if (norm(p - seat.origin) > searchR * 4) return; // stay near the seat if (std::fabs(dot(p - seat.origin, seat.normal)) > 1.5) return; t.push_back(dot(p, n)); }; for (int i : mesh::verticesInRadius(m, seat.origin, searchR * 4)) { if (dot(m.vnormals[i], n) < 0.5) continue; collect(m.verts[i]); } int nmesh = (int)t.size(); for (const auto& p : cloud) collect(p); if (t.size() < 3) return s; std::nth_element(t.begin(), t.begin() + t.size() / 2, t.end()); double d = t[t.size() / 2]; // robust offset: median of projections double s2 = 0; for (double ti : t) s2 += (ti - d) * (ti - d); s.normal = n; geom::basisFromNormal(n, s.u, s.v); s.origin = s.origin + n * (d - dot(s.origin, n)); // slide origin onto the plane s.rms = std::sqrt(s2 / t.size()); s.npts = nmesh; s.ncloud = (int)t.size() - nmesh; return s; } CylinderFit fitCylinderLocked(const mesh::Mesh& m, const std::vector& cloud, const Vec3& seed, double radius, double knownDiameter, const Vec3& axis_in, const Vec3* seatOrigin) { CylinderFit f; Vec3 axis = normalize(axis_in); if (norm(axis_in) < 1e-9) return f; auto ids = mesh::verticesInRadius(m, seed, radius); std::vector pts; // Best seed for the circle: a thin slice just below the seat plane, where only // the bore wall exists. Face vertices (whose normals go unreliable on dense // noisy scans) can't reach it, and neither can the far face's rim. if (seatOrigin) { double seatD = dot(*seatOrigin, axis); auto slice = [&](double below0, double below1) { pts.clear(); for (int i : ids) { double t = dot(m.verts[i], axis); if (t < seatD - below0 && t > seatD - below1) pts.push_back(m.verts[i]); } }; slice(0.3, 1.5); if (pts.size() < 12) slice(0.2, 3.0); } // Fallback (no seat, or slice came up empty): wall points by normal, strict // first so tilted face normals don't drag the initial circle wide. if (pts.size() < 12) { pts.clear(); for (int i : ids) if (std::fabs(dot(m.vnormals[i], axis)) < 0.35) pts.push_back(m.verts[i]); } if (pts.size() < 12) { pts.clear(); for (int i : ids) if (std::fabs(dot(m.vnormals[i], axis)) < 0.6) pts.push_back(m.verts[i]); } if (pts.size() < 6) return f; Vec3 uu, vv; geom::basisFromNormal(axis, uu, vv); Vec3 base = centroid(pts); auto fitCircle = [&](const std::vector& P, Vec3& centerOut, double& rOut) -> bool { std::vector> q; q.reserve(P.size()); for (const auto& p : P) { Vec3 d = p - base; q.push_back({dot(d, uu), dot(d, vv)}); } double cx, cy, rr; if (!circleFit2D(q, cx, cy, rr)) return false; if (knownDiameter > 0) { const double R = knownDiameter / 2.0; for (int it = 0; it < 8; ++it) { // Gauss–Newton center-only refine double a00 = 0, a01 = 0, a11 = 0, b0 = 0, b1 = 0; for (const auto& p : q) { double dx = p[0] - cx, dy = p[1] - cy; double d = std::sqrt(dx * dx + dy * dy); if (d < 1e-9) continue; double ux = dx / d, uy = dy / d, e = d - R; a00 += ux * ux; a01 += ux * uy; a11 += uy * uy; b0 += ux * e; b1 += uy * e; } double det = a00 * a11 - a01 * a01; if (std::fabs(det) < 1e-12) break; cx += (a11 * b0 - a01 * b1) / det; cy += (a00 * b1 - a01 * b0) / det; } rr = R; } centerOut = base + uu * cx + vv * cy; rOut = rr; return true; }; Vec3 axisPt; double r = 0; if (!fitCircle(pts, axisPt, r)) return f; if (knownDiameter > 0) r = knownDiameter / 2.0; // IRLS candidate pool: the whole bore, not just the seed slice — every mesh // point below the seat plane (or wall-normal-filtered without one), plus cloud // points in the capture sphere. Each pass keeps the radial band and refits. std::vector cand; if (seatOrigin) { double seatD = dot(*seatOrigin, axis); for (int i : ids) if (dot(m.verts[i], axis) < seatD - 0.25) cand.push_back(m.verts[i]); } else { for (int i : ids) if (std::fabs(dot(m.vnormals[i], axis)) < 0.6) cand.push_back(m.verts[i]); } double r2 = radius * radius; for (const auto& p : cloud) { Vec3 d = p - seed; if (dot(d, d) <= r2) cand.push_back(p); } for (int pass = 0; pass < 3; ++pass) { double thresh = std::max(0.1 * r, 0.12); std::vector in; for (const auto& p : cand) { Vec3 d = p - axisPt; double rd = norm(d - axis * dot(d, axis)); if (std::fabs(rd - r) <= thresh) in.push_back(p); } if (in.size() < 6) break; Vec3 center; double rr; if (!fitCircle(in, center, rr)) break; axisPt = center; if (knownDiameter <= 0) r = rr; pts.swap(in); } if (r <= 0) return f; // Depth from the 2nd/98th percentile of the axial spread: face-ring stragglers // that happen to sit at the bore radius would otherwise inflate the extent. std::vector ts(pts.size()); double s2 = 0; for (size_t i = 0; i < pts.size(); ++i) { Vec3 d = pts[i] - axisPt; ts[i] = dot(d, axis); double rd = norm(d - axis * ts[i]) - r; s2 += rd * rd; } std::sort(ts.begin(), ts.end()); double tmin = ts[(size_t)(0.02 * (ts.size() - 1))]; double tmax = ts[(size_t)(0.98 * (ts.size() - 1))]; f.ok = true; f.axisDir = axis; f.axisPoint = axisPt; f.radius = r; f.diameter = 2 * r; f.tMin = tmin; f.tMax = tmax; f.p1 = axisPt + axis * tmin; f.p2 = axisPt + axis * tmax; f.rms = std::sqrt(s2 / std::max(1, pts.size())); f.npts = (int)pts.size(); f.radiusFixed = knownDiameter > 0; return f; } // Typical vertex spacing = median edge length over a triangle sample. The bbox/√n // heuristic fails badly on mixed-density meshes (coarse faces, dense feature rims). static double typicalSpacing(const mesh::Mesh& m) { if (m.tris.empty()) return 1.0; std::vector e; size_t stride = std::max(1, m.tris.size() / 2000); for (size_t t = 0; t < m.tris.size(); t += stride) { const auto& tr = m.tris[t]; e.push_back(norm(m.verts[tr[0]] - m.verts[tr[1]])); e.push_back(norm(m.verts[tr[1]] - m.verts[tr[2]])); e.push_back(norm(m.verts[tr[2]] - m.verts[tr[0]])); } std::nth_element(e.begin(), e.begin() + e.size() / 2, e.end()); return std::max(0.05, e[e.size() / 2]); } // Grow the connected planar patch from seed vertex ids: BFS by spatial proximity // (uniform grid) over plane-consistent candidate vertices. Proximity — not mesh // adjacency — because scan meshes fragment into islands and synthetic densified // meshes have T-junctions; both break 1-ring connectivity across a face. static std::vector growPatch(const mesh::Mesh& m, const Vec3& n, const Vec3& origin, const std::vector& seeds, double bandMM) { std::vector out; // Plane-consistent candidates. std::vector cand(m.verts.size(), 0); size_t candTotal = 0; for (size_t i = 0; i < m.verts.size(); ++i) if (dot(m.vnormals[i], n) > 0.82 && // ~35° cone std::fabs(dot(m.verts[i] - origin, n)) <= bandMM) { cand[i] = 1; ++candTotal; } struct KeyHash { size_t operator()(const std::array& k) const { return (size_t)(k[0] * 73856093ll ^ k[1] * 19349663ll ^ k[2] * 83492791ll); } }; // Hop radius ≈ a few times the typical vertex spacing. The global median edge // is wrong on a decimated mesh — QEM strips exactly the flat-region vertices, // so the face being grown can be far sparser than the mesh at large. When the // BFS stalls with most candidates unreached, double the hop and retry (bounded // by a fraction of the part so it can't bridge to a distant coplanar island). double h = std::min(5.0, std::max(0.5, typicalSpacing(m) * 2.2)); const double hMax = std::max(h, m.bboxDiag() * 0.04); for (;; h *= 2.0) { out.clear(); const double h2 = h * h; auto key = [&](const Vec3& p) { return std::array{(int64_t)std::floor(p.x / h), (int64_t)std::floor(p.y / h), (int64_t)std::floor(p.z / h)}; }; std::unordered_map, std::vector, KeyHash> grid; for (size_t i = 0; i < m.verts.size(); ++i) if (cand[i]) grid[key(m.verts[i])].push_back((int)i); std::vector seen(m.verts.size(), 0); std::vector stack; for (int s : seeds) if (cand[s] && !seen[s]) { seen[s] = 1; stack.push_back(s); out.push_back(s); } while (!stack.empty() && out.size() < 400000) { int v = stack.back(); stack.pop_back(); auto kv = key(m.verts[v]); for (int dx = -1; dx <= 1; ++dx) for (int dy = -1; dy <= 1; ++dy) for (int dz = -1; dz <= 1; ++dz) { auto it = grid.find({kv[0] + dx, kv[1] + dy, kv[2] + dz}); if (it == grid.end()) continue; for (int w : it->second) { if (seen[w]) continue; Vec3 d = m.verts[w] - m.verts[v]; if (dot(d, d) > h2) continue; seen[w] = 1; stack.push_back(w); out.push_back(w); } } } if (out.size() >= 30 || out.size() >= candTotal || h >= hMax) break; } return out; } SeatFit fitSeatFromPoints(const mesh::Mesh& m, const std::vector& cloud, const std::vector& picks, const Vec3& viewDir, std::vector* patchIds) { SeatFit s; if (picks.empty()) return s; double seedR = std::max(2.0, std::min(8.0, m.bboxDiag() * 0.005)); // Seed plane from the first pick's neighbourhood. A decimated flat face can // hold vertices tens of mm apart, so widen the query until the fit has real // support (dense scans exit on the first radius). const double seedRMax = std::max(seedR, m.bboxDiag() * 0.06); PlaneFit f; for (;; seedR *= 1.7) { f = fitPlane(m, picks[0], seedR, viewDir); if ((f.ok && f.npts >= 12) || seedR >= seedRMax) break; } if (!f.ok) return s; // Seed vertex set: plane-consistent verts around every pick. std::vector seeds; for (const auto& p : picks) for (int i : mesh::verticesInRadius(m, p, seedR)) if (dot(m.vnormals[i], f.normal) > 0.7 && std::fabs(dot(m.verts[i] - f.origin, f.normal)) < 1.0) seeds.push_back(i); if (seeds.empty()) return s; // Grow, refit, grow again with the refined plane (fillets and neighbouring // faces fall outside the tightened band on the second pass). std::vector patch; for (int pass = 0; pass < 2; ++pass) { double band = std::min(1.2, std::max(0.6, 4.0 * f.rms)); patch = growPatch(m, f.normal, f.origin, seeds, band); if (patch.size() < 12) break; // 12 verts still pin a plane; a decimated // flat face may legitimately have few more std::vector pts, nrm; pts.reserve(patch.size()); for (int i : patch) { pts.push_back(m.verts[i]); nrm.push_back(m.vnormals[i]); } PlaneFit g = trimRefit(std::move(pts), std::move(nrm), viewDir, 3); if (!g.ok) break; f = g; } if (!f.ok || patch.size() < 12) return s; // Merge cloud points lying on the patch (within its 2D bounds + plane band). Vec3 uu = f.u, vv = f.v; double umin = 1e300, umax = -1e300, vmin = 1e300, vmax = -1e300; std::vector pts, nrm; for (int i : patch) { const Vec3 d = m.verts[i] - f.origin; double a = dot(d, uu), b = dot(d, vv); umin = std::min(umin, a); umax = std::max(umax, a); vmin = std::min(vmin, b); vmax = std::max(vmax, b); pts.push_back(m.verts[i]); nrm.push_back(m.vnormals[i]); } std::vector cc; for (const auto& p : cloud) { const Vec3 d = p - f.origin; double a = dot(d, uu), b = dot(d, vv); if (a >= umin - 2 && a <= umax + 2 && b >= vmin - 2 && b <= vmax + 2 && std::fabs(dot(d, f.normal)) <= 1.5) cc.push_back(p); } int nc = 0; mergeCloudAndRefit(f, pts, nrm, cc, viewDir, nc); static_cast(s) = f; s.ncloud = nc; if (patchIds) *patchIds = std::move(patch); return s; } SeatFit fitSeatFromPaint(const mesh::Mesh& m, const std::vector& cloud, const std::vector& centers, double radius, const Vec3& viewDir, std::vector* patchIds) { SeatFit s; if (centers.empty() || radius <= 0) return s; // Union of brush stamps → unique painted vertex ids. std::vector in(m.verts.size(), 0); std::vector ids; for (const auto& c : centers) for (int i : mesh::verticesInRadius(m, c, radius)) if (!in[i]) { in[i] = 1; ids.push_back(i); } if (ids.size() < 30) return s; std::vector pts, nrm; pts.reserve(ids.size()); for (int i : ids) { pts.push_back(m.verts[i]); nrm.push_back(m.vnormals[i]); } PlaneFit f = fitPlanePoints(pts, nrm, viewDir); if (!f.ok) return s; // The brush is a volume: a stroke near an edge or hole also paints wall and // bore vertices. Two passes of normal-consistency (vertex normal within ~60° // of the fitted plane's) + residual-band filtering keep the face points only; // ids shrink in lockstep so the returned patch matches what was accepted. for (int pass = 0; pass < 2; ++pass) { double band = std::max(0.8, 4.0 * f.rms); std::vector kid; std::vector kp, kn; for (size_t k = 0; k < ids.size(); ++k) { if (dot(nrm[k], f.normal) < 0.5) continue; if (std::fabs(dot(pts[k] - f.origin, f.normal)) > band) continue; kid.push_back(ids[k]); kp.push_back(pts[k]); kn.push_back(nrm[k]); } if (kid.size() < 30) break; ids.swap(kid); pts.swap(kp); nrm.swap(kn); PlaneFit g = trimRefit(pts, nrm, viewDir, 2); if (!g.ok) break; f = g; } // Merge cloud points lying on the painted region (near a stamp + on the plane). // Stamp-bbox prefilter keeps the stamp scan off the vast majority of the cloud. std::vector cc; if (!cloud.empty()) { Vec3 lo = centers[0], hi = centers[0]; for (const auto& c : centers) { lo.x = std::min(lo.x, c.x); hi.x = std::max(hi.x, c.x); lo.y = std::min(lo.y, c.y); hi.y = std::max(hi.y, c.y); lo.z = std::min(lo.z, c.z); hi.z = std::max(hi.z, c.z); } const double pad = radius + 1.0, r2 = pad * pad; for (const auto& p : cloud) { if (p.x < lo.x - pad || p.x > hi.x + pad || p.y < lo.y - pad || p.y > hi.y + pad || p.z < lo.z - pad || p.z > hi.z + pad) continue; if (std::fabs(dot(p - f.origin, f.normal)) > 1.5) continue; for (const auto& c : centers) { Vec3 d = p - c; if (dot(d, d) <= r2) { cc.push_back(p); break; } } } } int nc = 0; mergeCloudAndRefit(f, pts, nrm, cc, viewDir, nc); static_cast(s) = f; s.ncloud = nc; if (patchIds) *patchIds = std::move(ids); return s; } std::vector detectHolesInSeat(const mesh::Mesh& m, const std::vector& cloud, const Vec3& seatOrigin, const Vec3& normal_in, const Vec3& seedPick, double minD, double maxD) { std::vector found; Vec3 n = normalize(normal_in); if (minD <= 0) minD = 2.0; if (maxD <= 0) maxD = 40.0; // Re-grow the patch around the seed with the seat plane held fixed. std::vector seeds; double seedR = std::max(2.0, std::min(8.0, m.bboxDiag() * 0.005)); for (int i : mesh::verticesInRadius(m, seedPick, seedR)) if (dot(m.vnormals[i], n) > 0.7 && std::fabs(dot(m.verts[i] - seatOrigin, n)) < 1.0) seeds.push_back(i); auto patch = growPatch(m, n, seatOrigin, seeds, 1.0); if (patch.size() < 60) return found; // 2D occupancy over the patch (mesh + cloud points on the plane). Vec3 uu, vv; geom::basisFromNormal(n, uu, vv); std::vector> q; double umin = 1e300, umax = -1e300, vmin = 1e300, vmax = -1e300; auto push2d = [&](const Vec3& p) { const Vec3 d = p - seatOrigin; double a = dot(d, uu), b = dot(d, vv); q.push_back({a, b}); umin = std::min(umin, a); umax = std::max(umax, a); vmin = std::min(vmin, b); vmax = std::max(vmax, b); }; for (int i : patch) push2d(m.verts[i]); size_t nMesh2d = q.size(); for (const auto& p : cloud) { if (std::fabs(dot(p - seatOrigin, n)) > 0.8) continue; const Vec3 d = p - seatOrigin; double a = dot(d, uu), b = dot(d, vv); if (a < umin - 1 || a > umax + 1 || b < vmin - 1 || b > vmax + 1) continue; q.push_back({a, b}); } (void)nMesh2d; // The occupancy cell must out-size the point spacing or solid surface reads // as void; it must under-size the hole or the hole vanishes. const double cell = std::min(std::max(0.3, minD / 4.5), std::max({0.3, minD / 6.0, typicalSpacing(m) * 0.9})); int nx = (int)((umax - umin) / cell) + 3, ny = (int)((vmax - vmin) / cell) + 3; if (nx <= 4 || ny <= 4 || (long)nx * ny > 4000000) return found; std::vector occ((size_t)nx * ny, 0); // 0 empty, 1 occupied for (const auto& p : q) { int ix = (int)((p[0] - umin) / cell) + 1, iy = (int)((p[1] - vmin) / cell) + 1; if (ix >= 0 && ix < nx && iy >= 0 && iy < ny) occ[(size_t)iy * nx + ix] = 1; } // Flood the outside; remaining empty cells enclosed by the patch are hole // candidates. std::vector label((size_t)nx * ny, -1); // -2 outside, >=0 component id std::vector> stack; auto floodOutside = [&](int x, int y) { if (occ[(size_t)y * nx + x] || label[(size_t)y * nx + x] == -2) return; stack.push_back({x, y}); while (!stack.empty()) { auto [cx2, cy2] = stack.back(); stack.pop_back(); size_t id = (size_t)cy2 * nx + cx2; if (occ[id] || label[id] == -2) continue; label[id] = -2; if (cx2 > 0) stack.push_back({cx2 - 1, cy2}); if (cx2 < nx - 1) stack.push_back({cx2 + 1, cy2}); if (cy2 > 0) stack.push_back({cx2, cy2 - 1}); if (cy2 < ny - 1) stack.push_back({cx2, cy2 + 1}); } }; for (int x = 0; x < nx; ++x) { floodOutside(x, 0); floodOutside(x, ny - 1); } for (int y = 0; y < ny; ++y) { floodOutside(0, y); floodOutside(nx - 1, y); } // Interior empty components → centroid hints. struct Comp { double sx = 0, sy = 0; int cells = 0; }; std::vector comps; for (int y = 1; y < ny - 1; ++y) for (int x = 1; x < nx - 1; ++x) { size_t id = (size_t)y * nx + x; if (occ[id] || label[id] != -1) continue; Comp c; int cid = (int)comps.size(); stack.push_back({x, y}); while (!stack.empty()) { auto [cx2, cy2] = stack.back(); stack.pop_back(); size_t id2 = (size_t)cy2 * nx + cx2; if (occ[id2] || label[id2] != -1) continue; label[id2] = cid; c.sx += cx2; c.sy += cy2; c.cells++; if (cx2 > 0) stack.push_back({cx2 - 1, cy2}); if (cx2 < nx - 1) stack.push_back({cx2 + 1, cy2}); if (cy2 > 0) stack.push_back({cx2, cy2 - 1}); if (cy2 < ny - 1) stack.push_back({cx2, cy2 + 1}); } comps.push_back(c); } const double cellArea = cell * cell; const double aMin = 0.3 * M_PI * (minD / 2) * (minD / 2); const double aMax = 2.0 * M_PI * (maxD / 2) * (maxD / 2); for (const auto& c : comps) { double area = c.cells * cellArea; if (area < aMin || area > aMax) continue; double a = umin + (c.sx / c.cells - 1 + 0.5) * cell; double b = vmin + (c.sy / c.cells - 1 + 0.5) * cell; Vec3 hint = seatOrigin + uu * a + vv * b; double searchR = std::sqrt(area / M_PI) * 2.2 + 2.0; auto hd = detectHoleInSeat(m, cloud, seatOrigin, n, hint, searchR, 0.0, minD, maxD); if (!hd.ok) continue; // Unattended scan: hold the Ø window strictly. The quantization margin in // detectHoleInSeat is for user-asserted clicks; here it would admit // sub-window phantoms from sparse-sampling voids. if (hd.diameter < minD * 0.95 || hd.diameter > maxD * 1.1) continue; bool dup = false; for (const auto& e : found) if (norm(e.center - hd.center) < (e.diameter + hd.diameter) * 0.25) { dup = true; break; } if (!dup) found.push_back(hd); } return found; } // ---------------------------------------------------------------- hole from gap HoleDetect detectHoleInSeat(const mesh::Mesh& m, const std::vector& cloud, const Vec3& seatOrigin, const Vec3& normal_in, const Vec3& hint, double searchR, double knownDiameter, double minD, double maxD) { HoleDetect h; if (maxD > 0) searchR = std::max(searchR, maxD * 0.75); // must see past the rim Vec3 n = normalize(normal_in); Vec3 h0 = hint - n * dot(hint - seatOrigin, n); // The seat plane came from a box drag somewhere on the face — on a real scan it // can sit a fraction of a mm off (or slightly tilted from) the surface right at // the hole. Re-fit the plane LOCALLY around the hint, seeded by the seat: take // points loosely near the seat plane, trim-refit, and adopt the result if it // stays close to the seat orientation. The seat orients; the local fit places. Vec3 planeO = h0; double localRms = 0.12; { std::vector lp; for (int i : mesh::verticesInRadius(m, h0, searchR)) { if (std::fabs(dot(m.verts[i] - seatOrigin, n)) > 2.0) continue; if (dot(m.vnormals[i], n) < 0.5) continue; // face points only, not bore wall lp.push_back(m.verts[i]); } for (const auto& p : cloud) { Vec3 d = p - h0; if (dot(d, d) > searchR * searchR) continue; if (std::fabs(dot(p - seatOrigin, n)) > 2.0) continue; lp.push_back(p); } if (lp.size() >= 30) { PlaneFit local = trimRefit(lp, {}, n, 3); if (local.ok && dot(local.normal, n) > 0.978) { // within ~12° of the seat n = local.normal; planeO = local.origin; localRms = local.rms; h0 = hint - n * dot(hint - planeO, n); } } } Vec3 uu, vv; geom::basisFromNormal(n, uu, vv); // Plane-band points around the hint, as 2D offsets from h0. Bore-wall points // dive below the plane and get band-rejected — by design, we don't need them. // Band scales with the local surface noise (tight bands under-read the rim, // loose ones let the top wall vertices sneak in). const double band = std::min(0.8, std::max(0.2, 2.5 * localRms)); std::vector> q; auto take = [&](const Vec3& p) { if (std::fabs(dot(p - planeO, n)) > band) return; Vec3 d = p - h0; double a = dot(d, uu), b = dot(d, vv); if (a * a + b * b <= searchR * searchR) q.push_back({a, b}); }; for (int i : mesh::verticesInRadius(m, h0, searchR + band)) take(m.verts[i]); for (const auto& p : cloud) take(p); h.npts = (int)q.size(); if (q.size() < 24) return h; // Iterate: per angular bin around the current center, the innermost point is // the gap edge; fit a circle to the edges and re-center. The bin count adapts // to the scan's point spacing — a Ø7 hole on a 1.5mm-spaced scan has only ~15 // rim points total, and demanding 72 populated bins would reject every real // hole the scanner ever saw. const double sp = typicalSpacing(m); double rEst = knownDiameter > 0 ? knownDiameter / 2.0 : (maxD > 0 ? maxD * 0.35 : searchR * 0.4); int NB = 24; double cx = 0, cy = 0, r = knownDiameter > 0 ? knownDiameter / 2.0 : 0; std::vector> rim; for (int iter = 0; iter < 6; ++iter) { NB = std::min(72, std::max(12, (int)(2 * M_PI * rEst / std::max(0.5, sp * 0.9)))); std::vector minR(NB, 1e300); std::vector> minP(NB); for (const auto& p : q) { double dx = p[0] - cx, dy = p[1] - cy; double rd = std::sqrt(dx * dx + dy * dy); if (rd < 0.15) continue; // stray speck inside the bore int bin = (int)((std::atan2(dy, dx) + M_PI) / (2 * M_PI) * NB) % NB; if (rd < minR[bin]) { minR[bin] = rd; minP[bin] = p; } } rim.clear(); for (int bb = 0; bb < NB; ++bb) if (minR[bb] < 1e299) rim.push_back(minP[bb]); if ((int)rim.size() < std::max(8, NB / 3)) return h; if (knownDiameter > 0) { // center-only Gauss–Newton at fixed radius const double R = knownDiameter / 2.0; for (int it = 0; it < 8; ++it) { double a00 = 0, a01 = 0, a11 = 0, b0 = 0, b1 = 0; for (const auto& p : rim) { double dx = p[0] - cx, dy = p[1] - cy; double d = std::sqrt(dx * dx + dy * dy); if (d < 1e-9) continue; double ux = dx / d, uy = dy / d, e = d - R; a00 += ux * ux; a01 += ux * uy; a11 += uy * uy; b0 += ux * e; b1 += uy * e; } double det = a00 * a11 - a01 * a01; if (std::fabs(det) < 1e-12) break; cx += (a11 * b0 - a01 * b1) / det; cy += (a00 * b1 - a01 * b0) / det; } r = R; } else { double ncx, ncy, nr; if (!circleFit2D(rim, ncx, ncy, nr)) return h; cx = ncx; cy = ncy; r = nr; } rEst = r; } if (r < 0.5 || r > searchR * 0.95) return h; // NOTE: gap-edge radii are a minimum statistic, so the diameter reads slightly // low (≈2σ of scan noise, plus up to a vertex spacing on sparse scans). Center // is unbiased. Setting a caliper/thread diameter re-solves center-only. // Diameter window with a quantization margin: on a sparse scan the nearest // vertex to the true rim can sit half a spacing inward. if (minD > 0 && 2 * r < minD * 0.85 - 0.5 * sp) return h; if (maxD > 0 && 2 * r > maxD * 1.15 + 0.5 * sp) return h; // Coverage + residual: how much of the gap edge actually lies on the circle. // Tolerances scale with vertex spacing — edge vertices land up to ~sp/2 off // the true rim by quantization alone, regardless of scanner noise. double tol = std::max({0.3, 0.12 * r, 0.55 * sp}); int onCircle = 0; double s2 = 0; for (const auto& p : rim) { double e = std::hypot(p[0] - cx, p[1] - cy) - r; if (std::fabs(e) <= tol) { onCircle++; s2 += e * e; } } h.coverage = (double)onCircle / NB; if (h.coverage < 0.55 || onCircle < 8) return h; h.rms = std::sqrt(s2 / onCircle); // Roundness: an elongated slot's edge won't sit on the circle — its residual // scales with the aspect difference. Reject sloppy, non-round gaps: a real // opening whose face actually scanned gives high coverage and a tight edge. if (h.rms > std::max({0.2, 0.06 * r, 0.35 * sp})) return h; h.center = h0 + uu * cx + vv * cy; h.normal = n; // the locally refined face normal, not the raw seat normal h.diameter = 2 * r; // Depth from whatever wall evidence exists below the seat (often none when the // laser couldn't see in — 0 lets the caller apply a default). { double seatD = dot(planeO, n); std::vector ts; auto probe = [&](const Vec3& p) { Vec3 d = p - h.center; double t = dot(p, n) - seatD; if (t > -0.2 || t < -60.0) return; double rd = norm(d - n * dot(d, n)); if (rd > 0.6 * r && rd < 1.2 * r) ts.push_back(t); }; for (int i : mesh::verticesInRadius(m, h.center, searchR + band)) probe(m.verts[i]); for (const auto& p : cloud) { Vec3 d = p - h.center; if (dot(d, d) <= (searchR + band) * (searchR + band)) probe(p); } if (ts.size() >= 12) { std::sort(ts.begin(), ts.end()); h.depth = -ts[(size_t)(0.05 * (ts.size() - 1))]; } } h.ok = true; return h; } } // namespace fit