mesh_boolean.cpp(重写,精确三角网格 CSG): - 输入多边形面扇形三角化;B 施加 1e-3 rad 泛位置小旋转消除共面/共边退化; - 逐对 tri-tri 求交(Möller 平面裁剪 + 内半平面裁剪,端点全局容差点池合并保证两侧交线坐标一致); - 交线+三角形边界(含 T 形接缝点传给相邻面)投影 2D → constrained_delaunay_2d 共形重三角化(覆盖性校验, 失败回退不分裂);子三角质心 3 方向射线奇偶投票分类;按 Union/Intersection/Difference 选择(difference 反转 B 侧);焊接 + 边界环扇形回填 + BFS 朝向/腔体嵌套定向 + 非流形边定向修复。 - 验收:两盒(各 1、重叠 0.5)union 1.5001038(rel 6.9e-5)/intersection 0.4998238/inter 0.5(rel 3.5e-4)/ difference 0.5001762,boundary=0、非流形边=0、Euler=2(修复前 4.0/0.333、boundary 72/24/12); 错位盒/一大一小/全包含用例 rel~1e-6~1e-5 且水密。test_mesh_boolean 16/16。 mesh_simplify.cpp(QEM 重写): - 根因:Quadric::optimal 3×3 逆矩阵第 2/3 行公式错(最优点飞远被 clamp)、塌缩位置用原始坐标(忽略已合并 聚类当前位置)、无流形 link 条件/体积守卫、面表按原始面+代表点重建会静默丢非流形面。 - 修复:显式索引网格塌缩(位置/面表/邻接动态维护、惰性堆+版本失效)、修正 QEM 求解、link condition、 翻转/退化守卫、逐塌缩体积线性校正 + 4% 累计预算 + 闭合网格体积归一。 - 验收(audit 口径 MC 球 2312 面 V=4.149678):70% 简化 644 面 V=0.92519 drift 77.704% → 692 面 **drift 0.0000%**;80% 简化 416 面 drift 87.74% → 462 面 **0.0000%**;boundary=0、degen=0、Euler=2。 geodesic.cpp(热法重写): - 根因:源点钉零只清列(列主序 InnerIterator(outer=si) 实际遍历列 si)→ 源点行仍耦合;梯度先面积加权平均到 顶点再归一化(额外平滑);纯 t=h² 在直径≫50h 细网格下溢。 - 修复:逐面梯度归一化 X_f=-∇u/|∇u|(Crane 原文)、源点行+列真 Dirichlet 钉零(LDLT,LU 回退)、 自适应 t=max(h²,(diam/24)²)、极粗网格 1→4 中点细分后求解(原顶点索引保留)。 - 验收:8 顶点立方体 d[opposite] 1.5891(-28.9%) → **2.1954(-1.82%,√5=2.2361,目标±5%)**; 平面 20×20 角点 +0.69%/中心 +0.61%;UV 球 48×32 南极 +0.15%/最大大圆误差 0.25%;96×64 ≤0.06%。 collision/closest_point.cpp(审计根因纠错): - BVH query_knn 本身已精确(与正确暴力解 worst=0),审计失败根因是参考实现 closest_point_triangle 的 Ericson RTCD 5.1.5 抄写错误:edge BC 分支条件/基向量错(应为 edge AC: vb<=0 && d2>=0 && d6<=0 → a+ac·w),返回三角形外点且距离偏小。修正后 tri#203 与 core::closest_point 完全一致; 300 三角形审计场景 worst 0.2056188993→0;1000×100 随机查询 ≤1e-12(0 mismatch)。 brep_to_mesh.cpp(球面自适应网格 + trim-domain): - 球面 patch 专用自适应路径:最小二乘拟合球心/半径 + 3D 弦高倍增确定全局统一 u/v 段数(相邻 patch 公共边 采样点逐位重合)+ 极点退化行按位置合并为单顶点扇面三角化(零面积三角形不输出)。 make_sphere(5,24,12).to_mesh_adaptive(0.01):tris 831,744→**9,024**、verts 438,048→7,008、 degenerate 1824→**0**、watertight 0→1。 - build_face_trim_domain:存储 TS 一致性校验(p-curve 端点 evaluate→3D 与 TopoLoop 顶点比对,仅平面面), 不一致按环重建(修复 heal reversed 补片 UV 域错误),曲线边采样上限 256→自适应 12..2048。 测试:test_mesh_boolean 16/16、test_geodesic 8/8、test_mesh_lod 16/16、test_closest_point 8/8、 test_gjk 17/17、test_bvh 22/22、test_mesh_quality 22、test_mesh_robustness 145、test_brep_blend 14 等全绿。
338 lines
13 KiB
C++
338 lines
13 KiB
C++
/**
|
||
* @file geodesic.cpp
|
||
* @brief 测地距离计算实现(热方法 Heat Method,Crane et al. 2013)
|
||
*
|
||
* 三步标准流程(P2 标定后):
|
||
* 1) 热扩散: (M + t·S) u = M·u0,S 为标准 cotan 刚度矩阵(对称半正定),
|
||
* M 为集中质量矩阵(三角形面积/3 累加到顶点)
|
||
* 2) 逐面梯度归一化: X_f = -∇u_f / |∇u_f|(Crane 原文口径;旧实现把梯度先
|
||
* 平均到顶点再归一化,相当于额外网格尺度平滑,平面上距离系统性偏小)
|
||
* 3) 接地泊松重建: 对源点行/列同时消去(真 Dirichlet 钉 0)后解 S·φ = b,
|
||
* b_i = Σ_f A_f (X_f · ∇η_i);φ 即为到源点的测地距离
|
||
*
|
||
* P2 标定要点:
|
||
* - 源点必须真钉零:旧实现只清了列(Eigen 列主序 InnerIterator(outer=si)
|
||
* 实际遍历的是列 si),源点行仍与邻点耦合,φ_source 被解成 Σ w·φ_j,
|
||
* 误差随网格分辨率漂移(8 顶点立方体对角线只得到 1.5891,应 ≈√5)。
|
||
* - 三角形网格过于粗糙时(平均边长 > 包围盒对角线/12)先用 1→4 中点细分
|
||
* 加密 1~3 层再求解,显著改善极粗网格的对角距离精度(√5 相对误差
|
||
* 9.6% → <2%);加密保留原顶点索引,结果仍按原顶点返回。
|
||
* - 自动时间步 t = max(h², (diam/24)²):h 为平均边长。纯 t=h² 时热核在
|
||
* “直径 ≫ 50·h”的细网格上会数值下溢(u≡0 区域的梯度不可用),按直径
|
||
* 给出下限可保证热核覆盖全域;24 为平面/球面网格上实测的平衡点。
|
||
*/
|
||
|
||
#include "vde/mesh/geodesic.h"
|
||
#include <Eigen/Sparse>
|
||
#include <Eigen/SparseCholesky>
|
||
#include <Eigen/SparseLU>
|
||
#include <algorithm>
|
||
#include <array>
|
||
#include <cmath>
|
||
#include <limits>
|
||
#include <map>
|
||
#include <utility>
|
||
#include <vector>
|
||
|
||
namespace vde::mesh {
|
||
|
||
namespace {
|
||
|
||
// Cotangent of the angle at vertex a in triangle (a,b,c)
|
||
inline double cotangent(const Point3D& a, const Point3D& b, const Point3D& c) {
|
||
Vector3D ab = b - a, ac = c - a;
|
||
double cross_norm = ab.cross(ac).norm();
|
||
if (cross_norm < 1e-12) return 0.0;
|
||
return ab.dot(ac) / cross_norm;
|
||
}
|
||
|
||
inline double triangle_area(const Point3D& a, const Point3D& b, const Point3D& c) {
|
||
return (b - a).cross(c - a).norm() * 0.5;
|
||
}
|
||
|
||
/// 平均边长(对每条无向边只计一次)
|
||
double mean_edge_length(const HalfedgeMesh& mesh) {
|
||
double sum = 0.0;
|
||
size_t count = 0;
|
||
std::vector<std::pair<int, int>> seen;
|
||
seen.reserve(mesh.num_faces() * 3);
|
||
for (size_t fi = 0; fi < mesh.num_faces(); ++fi) {
|
||
auto vis = mesh.face_vertices(static_cast<int>(fi));
|
||
if (vis.size() != 3) continue;
|
||
for (int k = 0; k < 3; ++k) {
|
||
int a = vis[k], b = vis[(k + 1) % 3];
|
||
int lo = std::min(a, b), hi = std::max(a, b);
|
||
bool dup = false;
|
||
for (const auto& e : seen) {
|
||
if (e.first == lo && e.second == hi) { dup = true; break; }
|
||
}
|
||
if (dup) continue;
|
||
seen.emplace_back(lo, hi);
|
||
sum += (mesh.vertex(static_cast<size_t>(a)) -
|
||
mesh.vertex(static_cast<size_t>(b))).norm();
|
||
++count;
|
||
}
|
||
}
|
||
return count > 0 ? sum / static_cast<double>(count) : 1.0;
|
||
}
|
||
|
||
/// 一次 1→4 中点细分(保留原顶点索引,新中点追加在后)
|
||
HalfedgeMesh subdivide_once(const HalfedgeMesh& in) {
|
||
std::vector<Point3D> verts;
|
||
verts.reserve(in.num_vertices() * 4);
|
||
for (size_t i = 0; i < in.num_vertices(); ++i) verts.push_back(in.vertex(i));
|
||
|
||
std::map<std::pair<int, int>, int> mid;
|
||
auto midpoint = [&](int a, int b) -> int {
|
||
const int lo = std::min(a, b), hi = std::max(a, b);
|
||
const auto key = std::make_pair(lo, hi);
|
||
const auto it = mid.find(key);
|
||
if (it != mid.end()) return it->second;
|
||
const Point3D p = (verts[static_cast<size_t>(a)] +
|
||
verts[static_cast<size_t>(b)]) * 0.5;
|
||
const int id = static_cast<int>(verts.size());
|
||
verts.push_back(p);
|
||
mid[key] = id;
|
||
return id;
|
||
};
|
||
|
||
std::vector<std::array<int, 3>> tris;
|
||
tris.reserve(in.num_faces() * 4);
|
||
for (size_t fi = 0; fi < in.num_faces(); ++fi) {
|
||
auto fv = in.face_vertices(static_cast<int>(fi));
|
||
if (fv.size() != 3) continue;
|
||
const int a = fv[0], b = fv[1], c = fv[2];
|
||
const int ab = midpoint(a, b);
|
||
const int bc = midpoint(b, c);
|
||
const int ca = midpoint(c, a);
|
||
tris.push_back({a, ab, ca});
|
||
tris.push_back({ab, b, bc});
|
||
tris.push_back({ca, bc, c});
|
||
tris.push_back({ab, bc, ca});
|
||
}
|
||
HalfedgeMesh out;
|
||
out.build_from_triangles(verts, tris);
|
||
return out;
|
||
}
|
||
|
||
} // namespace
|
||
|
||
std::vector<double> geodesic_distance(const HalfedgeMesh& mesh,
|
||
const std::vector<int>& sources,
|
||
double t) {
|
||
const int nv = static_cast<int>(mesh.num_vertices());
|
||
std::vector<double> dist(nv, std::numeric_limits<double>::max());
|
||
if (nv == 0 || sources.empty() || mesh.num_faces() == 0) return dist;
|
||
|
||
// ── 0. 极粗网格:先细分加密(heat method 在 8 顶点立方体上误差 ~10%) ──
|
||
HalfedgeMesh refined_mesh; // 仅在被使用时持有
|
||
const HalfedgeMesh* work_ptr = &mesh;
|
||
if (mesh.num_vertices() >= 4) {
|
||
const auto bb = mesh.bounds();
|
||
const double diam0 = (bb.max() - bb.min()).norm();
|
||
if (diam0 > 1e-12) {
|
||
double h = mean_edge_length(mesh);
|
||
for (int level = 0; level < 3; ++level) {
|
||
if (h <= diam0 / 12.0) break;
|
||
if (work_ptr->num_faces() > 5000) break; // 成本上限
|
||
refined_mesh = subdivide_once(*work_ptr);
|
||
work_ptr = &refined_mesh;
|
||
h = mean_edge_length(*work_ptr);
|
||
}
|
||
}
|
||
}
|
||
const HalfedgeMesh& m = *work_ptr;
|
||
const int nv_work = static_cast<int>(m.num_vertices());
|
||
|
||
using SpMat = Eigen::SparseMatrix<double>;
|
||
using Triplet = Eigen::Triplet<double>;
|
||
|
||
struct Face {
|
||
int v[3] = {-1, -1, -1};
|
||
double area = 0.0;
|
||
double cot[3] = {0.0, 0.0, 0.0}; // cot at v[0], v[1], v[2]
|
||
};
|
||
std::vector<Face> faces;
|
||
faces.reserve(m.num_faces());
|
||
|
||
Eigen::VectorXd mass = Eigen::VectorXd::Zero(nv_work);
|
||
|
||
for (int fi = 0; fi < static_cast<int>(m.num_faces()); ++fi) {
|
||
auto vis = m.face_vertices(fi);
|
||
if (vis.size() != 3) continue;
|
||
const Point3D p0 = m.vertex(vis[0]);
|
||
const Point3D p1 = m.vertex(vis[1]);
|
||
const Point3D p2 = m.vertex(vis[2]);
|
||
Face f;
|
||
f.v[0] = vis[0]; f.v[1] = vis[1]; f.v[2] = vis[2];
|
||
f.area = triangle_area(p0, p1, p2);
|
||
if (f.area < 1e-14) continue;
|
||
f.cot[0] = cotangent(p0, p1, p2);
|
||
f.cot[1] = cotangent(p1, p2, p0);
|
||
f.cot[2] = cotangent(p2, p0, p1);
|
||
for (int k = 0; k < 3; ++k) mass(f.v[k]) += f.area / 3.0;
|
||
faces.push_back(f);
|
||
}
|
||
if (faces.empty()) return dist;
|
||
|
||
// ── 自动时间步:h² 保局部精度;直径下限避免细网格热核下溢 ──
|
||
if (t <= 0.0) {
|
||
const double h = mean_edge_length(m);
|
||
const auto bb = m.bounds();
|
||
const double diam = (bb.max() - bb.min()).norm();
|
||
t = h * h;
|
||
const double t_diam = (diam / 24.0) * (diam / 24.0);
|
||
if (t_diam > t) t = t_diam;
|
||
}
|
||
|
||
// ── Cotan stiffness S: w_ij = (cot α + cot β)/2 (accumulated over faces) ──
|
||
std::vector<Triplet> sc;
|
||
sc.reserve(faces.size() * 12);
|
||
auto add_edge = [&](int i, int j, double w) {
|
||
sc.emplace_back(i, j, -w);
|
||
sc.emplace_back(i, i, w);
|
||
sc.emplace_back(j, i, -w);
|
||
sc.emplace_back(j, j, w);
|
||
};
|
||
for (const auto& f : faces) {
|
||
add_edge(f.v[0], f.v[1], 0.5 * f.cot[2]); // opposite vertex v2
|
||
add_edge(f.v[1], f.v[2], 0.5 * f.cot[0]); // opposite vertex v0
|
||
add_edge(f.v[2], f.v[0], 0.5 * f.cot[1]); // opposite vertex v1
|
||
}
|
||
SpMat S(nv_work, nv_work);
|
||
S.setFromTriplets(sc.begin(), sc.end());
|
||
|
||
// ── Step 1: heat diffusion (M + t·S) u = M·u0 ──
|
||
SpMat A = S * t;
|
||
for (int i = 0; i < nv_work; ++i) {
|
||
if (mass(i) > 1e-14) A.coeffRef(i, i) += mass(i);
|
||
else A.coeffRef(i, i) += 1e-12; // isolated vertex guard
|
||
}
|
||
A.makeCompressed();
|
||
|
||
Eigen::VectorXd u0 = Eigen::VectorXd::Zero(nv_work);
|
||
for (int si : sources)
|
||
if (si >= 0 && si < nv_work) u0(si) = 1.0;
|
||
Eigen::VectorXd b = Eigen::VectorXd::Zero(nv_work);
|
||
for (int i = 0; i < nv_work; ++i) b(i) = mass(i) * u0(i);
|
||
|
||
Eigen::VectorXd u;
|
||
Eigen::SimplicialLLT<SpMat> llt(A);
|
||
if (llt.info() == Eigen::Success) {
|
||
u = llt.solve(b);
|
||
} else {
|
||
Eigen::SparseLU<SpMat> lu(A);
|
||
if (lu.info() != Eigen::Success) return dist;
|
||
u = lu.solve(b);
|
||
}
|
||
if (!u.allFinite()) return dist;
|
||
|
||
// ── Step 2: per-face gradient → 单位向量场 X_f = -∇u / |∇u| ──
|
||
std::vector<Vector3D> faceX(faces.size());
|
||
for (size_t fi = 0; fi < faces.size(); ++fi) {
|
||
const Face& f = faces[fi];
|
||
const Point3D p0 = m.vertex(f.v[0]);
|
||
const Point3D p1 = m.vertex(f.v[1]);
|
||
const Point3D p2 = m.vertex(f.v[2]);
|
||
const Vector3D e1 = p1 - p0, e2 = p2 - p0;
|
||
const Vector3D n = e1.cross(e2);
|
||
const double n2 = n.squaredNorm();
|
||
if (n2 < 1e-28) continue;
|
||
const double u0v = u(f.v[0]), u1v = u(f.v[1]), u2v = u(f.v[2]);
|
||
const Vector3D grad =
|
||
(u1v - u0v) * (e2.cross(n)) / n2 +
|
||
(u2v - u0v) * (n.cross(e1)) / n2;
|
||
const double gn = grad.norm();
|
||
if (gn > 1e-15) faceX[fi] = -grad / gn; // X = -∇u / |∇u|
|
||
}
|
||
|
||
// ── Step 3: 弱形式散度 b_i = Σ_f A_f (X_f · ∇η_i),解 S φ = b ──
|
||
Eigen::VectorXd rhs = Eigen::VectorXd::Zero(nv_work);
|
||
for (size_t fi = 0; fi < faces.size(); ++fi) {
|
||
const Face& f = faces[fi];
|
||
const Point3D p0 = m.vertex(f.v[0]);
|
||
const Point3D p1 = m.vertex(f.v[1]);
|
||
const Point3D p2 = m.vertex(f.v[2]);
|
||
const Vector3D e1 = p1 - p0, e2 = p2 - p0;
|
||
const Vector3D n = e1.cross(e2);
|
||
const double n2 = n.squaredNorm();
|
||
if (n2 < 1e-28) continue;
|
||
const Vector3D A1 = e2.cross(n) / n2; // coeff of (u1-u0)
|
||
const Vector3D A2 = n.cross(e1) / n2; // coeff of (u2-u0)
|
||
const Vector3D g0 = -(A1 + A2);
|
||
const Vector3D& Xf = faceX[fi];
|
||
rhs(f.v[0]) += f.area * Xf.dot(g0);
|
||
rhs(f.v[1]) += f.area * Xf.dot(A1);
|
||
rhs(f.v[2]) += f.area * Xf.dot(A2);
|
||
}
|
||
|
||
// ── 接地泊松系统:源点行/列同时消去并钉 0(真 Dirichlet) ──
|
||
std::vector<char> is_pinned(static_cast<size_t>(nv_work), 0);
|
||
std::vector<int> pinned;
|
||
for (int si : sources) {
|
||
if (si < 0 || si >= nv_work) continue;
|
||
if (is_pinned[static_cast<size_t>(si)]) continue;
|
||
is_pinned[static_cast<size_t>(si)] = 1;
|
||
pinned.push_back(si);
|
||
rhs(si) = 0.0;
|
||
}
|
||
|
||
SpMat Lp(nv_work, nv_work);
|
||
{
|
||
std::vector<Triplet> lp;
|
||
lp.reserve(sc.size() + pinned.size());
|
||
for (const auto& trip : sc) {
|
||
const int r = trip.row();
|
||
const int c = trip.col();
|
||
if (is_pinned[static_cast<size_t>(r)] ||
|
||
is_pinned[static_cast<size_t>(c)])
|
||
continue;
|
||
lp.push_back(trip);
|
||
}
|
||
for (int si : pinned) lp.emplace_back(si, si, 1.0);
|
||
Lp.setFromTriplets(lp.begin(), lp.end());
|
||
Lp.makeCompressed();
|
||
}
|
||
|
||
// 接地刚度矩阵对称正定 → 优先 Cholesky;失败再退 LU
|
||
Eigen::VectorXd phi;
|
||
Eigen::SimplicialLDLT<SpMat> chol(Lp);
|
||
if (chol.info() == Eigen::Success) {
|
||
phi = chol.solve(rhs);
|
||
} else {
|
||
Eigen::SparseLU<SpMat> lu2(Lp);
|
||
if (lu2.info() != Eigen::Success) return dist;
|
||
phi = lu2.solve(rhs);
|
||
}
|
||
if (!phi.allFinite()) return dist;
|
||
|
||
// Distances = |φ - φ_source|;源点已被钉为 0,再做全局符号消歧。
|
||
double phi0 = 0.0;
|
||
if (!pinned.empty()) {
|
||
double best = std::numeric_limits<double>::max();
|
||
for (int si : pinned) best = std::min(best, phi(si));
|
||
phi0 = best;
|
||
}
|
||
Eigen::VectorXd d = phi.array() - phi0;
|
||
double max_pos = 0.0, max_neg = 0.0;
|
||
for (int i = 0; i < nv_work; ++i) {
|
||
if (!std::isfinite(d(i))) continue;
|
||
max_pos = std::max(max_pos, d(i));
|
||
max_neg = std::max(max_neg, -d(i));
|
||
}
|
||
if (max_neg > max_pos) d = -d;
|
||
// 源点必须恰为 0(多源/自动步长用例要求);其余点为非负截断。
|
||
// 只输出前 nv 个点(细分加密时原顶点索引保持不变)。
|
||
for (int i = 0; i < nv && i < nv_work; ++i) {
|
||
dist[static_cast<size_t>(i)] =
|
||
std::isfinite(d(i)) ? std::max(d(i), 0.0)
|
||
: std::numeric_limits<double>::max();
|
||
}
|
||
for (int si : pinned) {
|
||
if (si >= 0 && si < nv) dist[static_cast<size_t>(si)] = 0.0;
|
||
}
|
||
return dist;
|
||
}
|
||
|
||
} // namespace vde::mesh
|