From ac585e0710a84eb7ccfa62d44358605ff8b2c8bc Mon Sep 17 00:00:00 2001 From: hm-thinkbook14p Date: Thu, 15 Oct 2026 08:32:02 +0800 Subject: [PATCH] =?UTF-8?q?perf(brep):=20Stress=5FDoubleBooleanChain=20?= =?UTF-8?q?=E4=BA=8C=E8=BD=AE=E5=8A=A0=E9=80=9F=20=E2=80=94=E2=80=94=20?= =?UTF-8?q?=E6=B6=88=E9=99=A4=E5=B8=83=E5=B0=94=E7=83=AD=E8=B7=AF=E5=BE=84?= =?UTF-8?q?=E7=9A=84=E9=94=81/=E7=BC=93=E5=AD=98/=E5=85=B3=E9=94=AE?= =?UTF-8?q?=E8=B7=AF=E5=BE=84=E7=93=B6=E9=A2=88=EF=BC=88VDE-1217=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 首轮修复后本用例单跑 90.28 s,但在审计口径 ctest --timeout 120 -j 8 下为 90.94 s(余量仅 ~29 s)。二轮定位得四条独立缺陷并修复: 1) get_body_mesh 用单一全局 mesh_build_mutex 把 A/B 两个独立网格体化串行化(锁等待 ~137 s 线程时间)→ 改 per-body 锁。 2) ssi_cached 键为有序对,A/B 面循环方向相反 → 同一曲面对被算两次(rev_hit=1124, 31% 重复)→ 键归一为无序对 (min,max)。 3) ssi_cached 缓存为 thread_local → A/B 面循环跨线程碎片化(T=1 实算 2501 vs T=4 3362)→ 改进程级共享缓存 + 互斥(锁只护查找/插入)。 4) A 体网格只被 B 面循环消费却压在串行关键路径(cop ~19 s)→ 新增 MeshPrefetch 后台预取,与 A 面循环重叠。 另含 classify_point_mesh 热路径裸 double 化(等价改写,非主因)。 结果:单跑 T=1 171.2→95.2 s、T=4 76.6→52.5 s;ctest -j 8 --timeout 120 -R TolerantEdgeCases 下本项 90.94→64.36 s,整包 112/112。回归 brep_boolean 21/21、ssi_boolean 53/53、boolean_robustness 15/15、surface_intersection 22/22、advanced_healing 33/33、nurbs 9/9。 --- docs/feedback/VDE-1217.md | 62 ++++++++ docs/reference/audit-feedback.md | 13 ++ src/brep/brep_boolean.cpp | 233 ++++++++++++++++++++++--------- 3 files changed, 243 insertions(+), 65 deletions(-) diff --git a/docs/feedback/VDE-1217.md b/docs/feedback/VDE-1217.md index 2c3b1c22..05190d8b 100644 --- a/docs/feedback/VDE-1217.md +++ b/docs/feedback/VDE-1217.md @@ -105,3 +105,65 @@ 仅对 slit / 分离体这两类**原本会产生错误或不必要工作**的情形提前收敛。 - 收益是全局的:`evaluate`/`evaluate_with_derivs` 是 SSI、投影链、布尔裁剪的公共原子热点, 该改动同时加速所有依赖曲面求值的路径。 + +--- + +## 二轮加速(2026-10-15):`ctest -j 8` 余量 + +### 背景 + +首轮修复后本用例单跑 **90.28 s**。§5 回归的审计口径是 `ctest --timeout 120 -j 8`; +在 8 路并发负载下该项实测 **90.94 s** —— 距 120 s 超时线仅 ~29 s 余量,偏紧。 +本文件首轮结论"SSI 热路径 Eigen 临时对象"已不再是并发下的主瓶颈,故做二轮定位。 + +### 定位(临时 TEMP-PROF 埋点,已移除) + +- 线程敏感性:**T=1 → 171.2 s、T=4 → 76.6 s、T=8 → 77.3 s**。4 线程后饱和 ⇒ **~45 s 落在串行关键路径**。 +- T=1 干净分解:`tot=106.4 s`,其中 `cop=18.5 s`、A 面循环 `67.1 s`、B 面循环 `20.5 s`。 + SSI 主导:`curv=85.9 s`(3625 次实算 @ ≈40 ms,**全部为曲面-曲面,flat=0**)。 + +### 根因与修复(四条独立缺陷) + +1. **网格构建锁串行化 A/B 两个独立网格体化** —— `get_body_mesh` 原先用**单一全局 + `mesh_build_mutex`** 防"惊群"(N 个 OpenMP 线程同时冷启动同一个网格)。但每次 + `brep_union` 都要构建 A、B 两份网格,一把全局锁把它们**串行化**:实测锁等待 + ≈ **137 s 线程时间(~28 % 墙钟)**,其余 OpenMP worker 全部空转。 + 改为 **per-body 锁**(`std::map>`), + 只对"同一个 body"去重,A 与 B 可并发体化。 +2. **SSI 缓存键序敏感 ⇒ 同一曲面对被算两次** —— `ssi_cached` 键为**有序对** `(ha,hb)`, + 而 A 面循环调 `SSI(surfA,surfB)`、B 面循环调 `SSI(surfB,surfA)`,同一对曲面 + 两个方向各算一次。实测 3625 次实算中 **1124 次(31 %)是"反向键已缓存"的重复** + (`rev_hit`),每次 ≈40 ms ⇒ 白白多花 ~45 s。 + 键**归一为无序对** `(min(ha,hb), max(ha,hb))`。依据:下游只消费 `curve.points` + (3D 采样点),不消费 `params_a/params_b`,故两个方向复用同一份 3D 交线几何等价。 +3. **SSI 缓存 `thread_local` 跨线程碎片化** —— 缓存原为 `thread_local`,而 A 面循环与 + B 面循环各由**不同的 OpenMP 工作线程**执行,两个方向互相命中不到对方的条目: + 实测 T=1 实算 2501 次、T=4 涨到 3362 次(**+34 %**),SSI 线程时间 86 s → 158 s。 + 改为**进程级共享缓存 + 互斥**;互斥只护查找/插入,真正的 ~40 ms SSI 计算在锁外, + 争用可忽略。容量 2048 → 8192。 +4. **A 体网格落在串行关键路径** —— A 的网格**只被 B 面循环消费**(B 面循环在 A 面循环 + 之后),但原先在主线程 A 面循环**之前**就构建,正好压在关键路径上 + (`cop` ≈ 19 s = 串行化的体化时间)。新增 `MeshPrefetch`:用后台 `std::thread` + 构建 A 体网格,与独立的 A 面循环**重叠**,在 B 面循环前 `join()`。 + +另含一处小优化:`classify_point_mesh` 热路径裸 `double` 化(同 VDE-1215/1217 的等价改写)。 +实测收益仅 ~3 % —— 它**不是**主要瓶颈,主要瓶颈是上面 4 条锁/缓存/关键路径问题。 + +### 结果 + +| 项 | 二轮前 | 二轮后 | +|----|--------|--------| +| 单跑(T=1) | 171.2 s | **95.2 s** | +| 单跑(T=4) | 76.6 s | **52.5 s** | +| `ctest --timeout 120 -j 8 -R TolerantEdgeCases` 下本项 | **90.94 s** | **64.36 s** | +| `test_tolerant_edge_cases` 整包 | — | **112/112 PASSED(总计 64.87 s)** | + +回归(均全绿):`test_brep_boolean` **21/21**、`test_ssi_boolean` **53/53**、 +`test_boolean_robustness` **15/15**、`test_surface_intersection` **22/22**、 +`test_advanced_healing` **33/33**、`test_nurbs` **9/9**。 + +### 影响 + +- **无 API 变化**。并发化只影响**体化/SSI 缓存**的调度,判定逻辑与首轮一致; + 缓存键无序归一不改变交线几何(见 ② 依据);`MeshPrefetch` 只提前/重叠体化, + `brep_union`/`brep_intersection`/`brep_difference` 的语义与结果不变。 diff --git a/docs/reference/audit-feedback.md b/docs/reference/audit-feedback.md index 15e3e614..ce5ef68d 100644 --- a/docs/reference/audit-feedback.md +++ b/docs/reference/audit-feedback.md @@ -198,6 +198,19 @@ CLOSED 的 Out of Scope 主体(约 601 份)为成批自动分诊 ≤5 s、`FeatureTreeTest.*` ≤3 s、`SheetMetalDesignTest.FormingToolsAddGeometry` 0.06 s、 `BooleanFallbackTest.ExceptionSafety_AllOperations` 34.8 s、`FormatRoundtripTest.StepGeometryPlateWithHoles` 44.5 s。详见 [VDE-1219](feedback/VDE-1219.md)。**§5.2 过滤回归 Timeout 项至此全部清零**。 +- **Timeout 项余量收紧(2026-10-15,VDE-1217 二轮)**:`TolerantEdgeCases.Stress_DoubleBooleanChain` + 首轮修复后单跑 90.28 s,但在审计口径 `ctest --timeout 120 -j 8` 下实测 **90.94 s**(余量仅 ~29 s)。 + 二轮定位(TEMP-PROF 埋点,已移除)得四条独立缺陷:①`get_body_mesh` 全局 `mesh_build_mutex` + 把 A/B 两个独立网格体化**串行化**(锁等待 ≈137 s 线程时间,~28 % 墙钟)⇒ 改 **per-body 锁**; + ②SSI 缓存键为**有序对**,A/B 面循环方向相反 ⇒ 同一曲面对被算两次(`rev_hit=1124`,31 % 重复) + ⇒ 键归一为**无序对**;③SSI 缓存为 `thread_local` ⇒ A/B 面循环由不同 OMP 线程执行, + 跨线程碎片化(T=1 实算 2501 次 vs T=4 3362 次,+34 %)⇒ 改**进程级共享缓存 + 互斥**(锁只护查找/插入); + ④A 体网格只被 B 面循环消费却压在串行关键路径上(`cop` ≈19 s)⇒ 新增 `MeshPrefetch` + 后台线程与 A 面循环重叠。实测单跑 T=1 **171.2 → 95.2 s**、T=4 **76.6 → 52.5 s**; + `ctest -j 8 --timeout 120 -R TolerantEdgeCases` 下本项 **90.94 → 64.36 s**, + 整包 **112/112(总计 64.87 s)**。回归 `test_brep_boolean` 21/21、`test_ssi_boolean` 53/53、 + `test_boolean_robustness` 15/15、`test_surface_intersection` 22/22、`test_advanced_healing` 33/33、 + `test_nurbs` 9/9。详见 [VDE-1217](feedback/VDE-1217.md)。 ### 5.3 `test_mesh_lod` 2 项失败 —— `generate_lod` 过早截断 LOD 层级 ✅ 已修复(VDE-1216,2026-10-07) diff --git a/src/brep/brep_boolean.cpp b/src/brep/brep_boolean.cpp index 21d7d926..e2529d76 100644 --- a/src/brep/brep_boolean.cpp +++ b/src/brep/brep_boolean.cpp @@ -21,6 +21,8 @@ #include #include #include +#include +#include #ifdef VDE_USE_OPENMP #include @@ -74,9 +76,15 @@ struct BodyMeshCache { static std::map mesh_cache; static std::mutex mesh_cache_mutex; -// Serializes construction: prevents N OpenMP threads from all building the -// same mesh when the cache is cold ("thundering herd"). -static std::mutex mesh_build_mutex; +// Per-body build lock: prevents N OpenMP threads from all building the same +// mesh when the cache is cold ("thundering herd"), while still allowing +// INDEPENDENT bodies (A and B) to tessellate **concurrently**. A single global +// build mutex serialized the two independent tessellations — and each +// `brep_union` call builds both — so on the Stress_DoubleBooleanChain chain +// (100 sequential unions) every call paid 2× the tessellation on the critical +// path and left the other OpenMP workers idle on the lock (measured +// lockwait ≈ 137 s of thread-time, ~28 % of wall). +static std::map> mesh_build_locks; /// Build the (y,z) triangle bucket index over a tessellated mesh. static MeshCellIndex build_mesh_cell_index(const vde::mesh::HalfedgeMesh& mesh) { @@ -151,32 +159,59 @@ static MeshCellIndex build_mesh_cell_index(const vde::mesh::HalfedgeMesh& mesh) /// Get (building if needed) the cached tessellation + spatial index for a body. static const BodyMeshCache& get_body_mesh(const BrepModel& body) { + // Fetch (or create) this body's dedicated build lock. Holding a shared_ptr + // keeps the mutex alive even if reset_mesh_cache() clears the registry. + std::shared_ptr build_lock; { std::lock_guard lock(mesh_cache_mutex); auto it = mesh_cache.find(&body); if (it != mesh_cache.end()) return it->second; + auto& lp = mesh_build_locks[&body]; + if (!lp) lp = std::make_shared(); + build_lock = lp; } - std::lock_guard build_lock(mesh_build_mutex); { - // Double-check: another thread may have completed while we waited. + std::lock_guard lk(*build_lock); + { + // Double-check: another thread may have completed while we waited. + std::lock_guard lock(mesh_cache_mutex); + auto it = mesh_cache.find(&body); + if (it != mesh_cache.end()) return it->second; + } + BodyMeshCache entry; + entry.mesh = body.to_mesh(0.05); + entry.index = build_mesh_cell_index(entry.mesh); std::lock_guard lock(mesh_cache_mutex); - auto it = mesh_cache.find(&body); - if (it != mesh_cache.end()) return it->second; + auto [inserted_it, _] = mesh_cache.emplace(&body, std::move(entry)); + return inserted_it->second; } - BodyMeshCache entry; - entry.mesh = body.to_mesh(0.05); - entry.index = build_mesh_cell_index(entry.mesh); - std::lock_guard lock(mesh_cache_mutex); - auto [inserted_it, _] = mesh_cache.emplace(&body, std::move(entry)); - return inserted_it->second; } +/// Background prefetch of one operand's tessellation, joined on demand. +/// +/// The A-face pass classifies against B and therefore needs B's mesh up front, +/// while the B-face pass (which runs *after* the A-face pass) is the only +/// consumer of A's mesh. Building A's mesh on the main thread before the loops +/// puts it squarely on the critical path (~18 s of the 64 s +/// Stress_DoubleBooleanChain wall — measured `cop` ≈ 19 s, which is exactly the +/// serialised tessellation). Starting it in the background lets it overlap the +/// independent A-face pass instead. +struct MeshPrefetch { + std::thread worker; + explicit MeshPrefetch(const BrepModel& body) { + worker = std::thread([&body] { (void)get_body_mesh(body); }); + } + void join() { if (worker.joinable()) worker.join(); } + ~MeshPrefetch() { join(); } +}; + /// 清空网格缓存。缓存以 BrepModel 指针为 key,若不清空,对象销毁后地址 /// 复用会命中过期缓存(返回旧对象的网格)→ 偶发错误分类。 /// 在每次布尔操作的入口调用,把缓存生命周期限制在单次布尔调用内。 static void reset_mesh_cache() { std::lock_guard lock(mesh_cache_mutex); mesh_cache.clear(); + mesh_build_locks.clear(); } /// Minimum signed distance from point p to the mesh. @@ -215,6 +250,11 @@ ClassResult classify_point_mesh(const BrepModel& body, const Point3D& p, } // ── First: check if point lies ON the mesh surface ── + // 裸 double 热路径(同 VDE-1215/1217):Debug -O0 下 Point3D/Vector3D 的 + // 逐分量与临时对象(v1-v0、.dot()、.squaredNorm())全为未内联函数调用, + // 开销远超算术本身。本循环按每采样点 ~150 个候选三角形 × (min-dist + 射线) + // 两遍执行,是布尔分类的单点最大热点。逐式改写为标量,算术次序不变。 + const double px = p.x(), py = p.y(), pz = p.z(); double min_dist_sq = std::numeric_limits::max(); for (int cf : cand) { const size_t fi = static_cast(cf); @@ -223,61 +263,73 @@ ClassResult classify_point_mesh(const BrepModel& body, const Point3D& p, int h1 = mesh.halfedge(h0).next_index; int h2 = mesh.halfedge(h1).next_index; - Point3D v0 = mesh.vertex(mesh.halfedge(h0).vertex_index); - Point3D v1 = mesh.vertex(mesh.halfedge(h1).vertex_index); - Point3D v2 = mesh.vertex(mesh.halfedge(h2).vertex_index); + const Point3D& V0 = mesh.vertex(mesh.halfedge(h0).vertex_index); + const Point3D& V1 = mesh.vertex(mesh.halfedge(h1).vertex_index); + const Point3D& V2 = mesh.vertex(mesh.halfedge(h2).vertex_index); + const double v0x = V0.x(), v0y = V0.y(), v0z = V0.z(); + const double v1x = V1.x(), v1y = V1.y(), v1z = V1.z(); + const double v2x = V2.x(), v2y = V2.y(), v2z = V2.z(); // Compute closest point on triangle to p - Vector3D e0 = v1 - v0; - Vector3D e1 = v2 - v0; - Vector3D dv = v0 - p; + const double e0x = v1x - v0x, e0y = v1y - v0y, e0z = v1z - v0z; + const double e1x = v2x - v0x, e1y = v2y - v0y, e1z = v2z - v0z; + const double dvx = v0x - px, dvy = v0y - py, dvz = v0z - pz; - double a = e0.dot(e0); - double b = e0.dot(e1); - double c = e1.dot(e1); - double d = e0.dot(dv); - double e = e1.dot(dv); + double a = e0x * e0x + e0y * e0y + e0z * e0z; + double b = e0x * e1x + e0y * e1y + e0z * e1z; + double c = e1x * e1x + e1y * e1y + e1z * e1z; + double d = e0x * dvx + e0y * dvy + e0z * dvz; + double e = e1x * dvx + e1y * dvy + e1z * dvz; double det = a * c - b * b; double s = b * e - c * d; double t = b * d - a * e; + auto sqdist = [&](double cx, double cy, double cz) { + const double gx = cx - px, gy = cy - py, gz = cz - pz; + return gx * gx + gy * gy + gz * gz; + }; + if (s + t <= det) { if (s < 0) { if (t < 0) { // Region 4: closest to v0 - double dist = dv.squaredNorm(); - min_dist_sq = std::min(min_dist_sq, dist); + min_dist_sq = std::min(min_dist_sq, sqdist(v0x, v0y, v0z)); } else { // Region 3: closest to edge v0-v2 - double dist = (v0 + (t/det) * e1 - p).squaredNorm(); - min_dist_sq = std::min(min_dist_sq, dist); + const double k = t / det; + min_dist_sq = std::min(min_dist_sq, + sqdist(v0x + k * e1x, v0y + k * e1y, v0z + k * e1z)); } } else if (t < 0) { // Region 5: closest to edge v0-v1 - double dist = (v0 + (s/det) * e0 - p).squaredNorm(); - min_dist_sq = std::min(min_dist_sq, dist); + const double k = s / det; + min_dist_sq = std::min(min_dist_sq, + sqdist(v0x + k * e0x, v0y + k * e0y, v0z + k * e0z)); } else { // Region 0: inside triangle - double dist = (v0 + e0 * (s/det) + e1 * (t/det) - p).squaredNorm(); - min_dist_sq = std::min(min_dist_sq, dist); + const double ks = s / det, kt = t / det; + min_dist_sq = std::min(min_dist_sq, + sqdist(v0x + e0x * ks + e1x * kt, + v0y + e0y * ks + e1y * kt, + v0z + e0z * ks + e1z * kt)); } } else { if (s < 0) { // Region 2: closest to v2 - double dist = (v2 - p).squaredNorm(); - min_dist_sq = std::min(min_dist_sq, dist); + min_dist_sq = std::min(min_dist_sq, sqdist(v2x, v2y, v2z)); } else if (t < 0) { // Region 6: closest to v1 - double dist = (v1 - p).squaredNorm(); - min_dist_sq = std::min(min_dist_sq, dist); + min_dist_sq = std::min(min_dist_sq, sqdist(v1x, v1y, v1z)); } else { // Region 1: closest to edge v1-v2 double numer = a + d - b - e; - double denom = a - 2*b + c; + double denom = a - 2 * b + c; double w = (denom > 1e-12) ? std::clamp(numer / denom, 0.0, 1.0) : 0.0; - double dist = (v1 + w * (v2 - v1) - p).squaredNorm(); - min_dist_sq = std::min(min_dist_sq, dist); + min_dist_sq = std::min(min_dist_sq, + sqdist(v1x + w * (v2x - v1x), + v1y + w * (v2y - v1y), + v1z + w * (v2z - v1z))); } } } @@ -299,9 +351,9 @@ ClassResult classify_point_mesh(const BrepModel& body, const Point3D& p, // ON); (b) co-located hits are clustered by t and counted once, which is // the robust guarantee against grid-aligned rays. const double jit = 1e-9; - const double jy = jit * (1.0 + 0.5 * std::sin(p.x() * 127.1 + p.y() * 311.7 + p.z() * 74.7)); - const double jz = jit * (1.0 + 0.5 * std::cos(p.x() * 269.5 + p.y() * 183.3 + p.z() * 246.1)); - Ray3Dd ray(p, Vector3D(1.0, jy, jz)); + const double jy = jit * (1.0 + 0.5 * std::sin(px * 127.1 + py * 311.7 + pz * 74.7)); + const double jz = jit * (1.0 + 0.5 * std::cos(px * 269.5 + py * 183.3 + pz * 246.1)); + const double dx = 1.0, dy = jy, dz = jz; std::vector hit_ts; for (int cf : cand) { @@ -311,29 +363,35 @@ ClassResult classify_point_mesh(const BrepModel& body, const Point3D& p, int h1 = mesh.halfedge(h0).next_index; int h2 = mesh.halfedge(h1).next_index; - Point3D v0 = mesh.vertex(mesh.halfedge(h0).vertex_index); - Point3D v1 = mesh.vertex(mesh.halfedge(h1).vertex_index); - Point3D v2 = mesh.vertex(mesh.halfedge(h2).vertex_index); + const Point3D& V0 = mesh.vertex(mesh.halfedge(h0).vertex_index); + const Point3D& V1 = mesh.vertex(mesh.halfedge(h1).vertex_index); + const Point3D& V2 = mesh.vertex(mesh.halfedge(h2).vertex_index); + const double v0x = V0.x(), v0y = V0.y(), v0z = V0.z(); - // Möller–Trumbore ray-triangle intersection - Vector3D e1 = v1 - v0; - Vector3D e2 = v2 - v0; - Vector3D h = ray.direction().cross(e2); - double a = e1.dot(h); + // Möller–Trumbore ray-triangle intersection(裸 double,同 VDE-1215/1217) + const double e1x = V1.x() - v0x, e1y = V1.y() - v0y, e1z = V1.z() - v0z; + const double e2x = V2.x() - v0x, e2y = V2.y() - v0y, e2z = V2.z() - v0z; + + const double hx = dy * e2z - dz * e2y; + const double hy = dz * e2x - dx * e2z; + const double hz = dx * e2y - dy * e2x; + const double a = e1x * hx + e1y * hy + e1z * hz; if (std::abs(a) < tol) continue; - double f = 1.0 / a; - Vector3D s = ray.origin() - v0; - double u = f * s.dot(h); + const double f = 1.0 / a; + const double sx = px - v0x, sy = py - v0y, sz = pz - v0z; + const double u = f * (sx * hx + sy * hy + sz * hz); if (u < 0.0 || u > 1.0) continue; - Vector3D q = s.cross(e1); - double v = f * ray.direction().dot(q); + const double qx = sy * e1z - sz * e1y; + const double qy = sz * e1x - sx * e1z; + const double qz = sx * e1y - sy * e1x; + const double v = f * (dx * qx + dy * qy + dz * qz); if (v < 0.0 || u + v > 1.0) continue; - double t = f * e2.dot(q); + const double t = f * (e2x * qx + e2y * qy + e2z * qz); if (t > tol) hit_ts.push_back(t); } @@ -1742,24 +1800,48 @@ static uint64_t hash_nurbs_surface(const curves::NurbsSurface& s) { // 返回按值拷贝:调用方会长期持有(valid_curve 指针、max_dev 扫描), // 引用会因缓存插入重分配而失效。曲线本身只有数十点,拷贝远小于 SSI 重算。 +// +// 键按**无序对** (min(ha,hb), max(ha,hb)) 归一:两张面的交线集合在 A/B 互换下 +// 几何同一,而 A 面循环调 SSI(surfA,surfB)、B 面循环调 SSI(surfB,surfA) —— 同一 +// 对曲面被两个方向各算一次。Stress_DoubleBooleanChain 实测 3625 次实算中有 +// 1124 次(31%)是"反向键已缓存"的重复(rev_hit),每次 ~40 ms ⇒ 白白多花 ~45 s。 +// 下游只取 curve.points(3D 采样点),不消费 params_a/params_b,故两个方向 +// 复用同一份 3D 交线即几何等价。 +// +// 缓存为**进程级共享**(非 thread_local):A 面循环与 B 面循环各由不同的 OpenMP +// 工作线程执行,thread_local 缓存会让两个方向各自命中不到对方的条目 —— +// 实测 T=1 实算 2501 次、T=4 涨到 3362 次(+34%),SSI 线程时间 86 s → 158 s。 +// 共享缓存 + 互斥锁把无序键的复用还原到单线程水平(互斥只护查找/插入,真正的 +// 40 ms SSI 计算在锁外,争用可忽略)。 static std::vector ssi_cached( const curves::NurbsSurface& sa, const curves::NurbsSurface& sb, int depth, double tol) { struct Entry { - uint64_t ha, hb; + uint64_t hlo, hhi; int depth; double tol; std::vector v; }; - static thread_local std::vector cache; + static std::mutex cache_mutex; + static std::vector cache; const uint64_t ha = hash_nurbs_surface(sa); const uint64_t hb = hash_nurbs_surface(sb); - for (const auto& e : cache) - if (e.ha == ha && e.hb == hb && e.depth == depth && e.tol == tol) + const uint64_t hlo = std::min(ha, hb); + const uint64_t hhi = std::max(ha, hb); + { + std::lock_guard lock(cache_mutex); + for (const auto& e : cache) + if (e.hlo == hlo && e.hhi == hhi && e.depth == depth && e.tol == tol) + return e.v; + } + std::vector v = + curves::intersect_surfaces(sa, sb, depth, tol); + std::lock_guard lock(cache_mutex); + for (const auto& e : cache) // another thread may have inserted meanwhile + if (e.hlo == hlo && e.hhi == hhi && e.depth == depth && e.tol == tol) return e.v; - auto v = curves::intersect_surfaces(sa, sb, depth, tol); - if (cache.size() >= 2048) cache.clear(); - cache.push_back({ha, hb, depth, tol, v}); + if (cache.size() >= 8192) cache.clear(); + cache.push_back({hlo, hhi, depth, tol, v}); return v; } @@ -1787,7 +1869,7 @@ static std::vector split_face_by_face_ssi_impl( AABB3D bb_a; for (size_t vi = 0; vi < frag_a.num_vertices(); ++vi) bb_a.expand(frag_a.vertex(static_cast(vi)).point); - auto bb_b = face_bounds(body_b, face_b_id); + AABB3D bb_b = face_bounds(body_b, face_b_id); if (!bb_a.intersects(bb_b)) { // No split → caller reuses the original fragment (see the // `splits.size() > 1` contract at every call site). Returning an @@ -1946,7 +2028,8 @@ static std::vector split_face_by_face_ssi_impl( } // Split the fragment by the cutting plane - auto split_result = split_face_by_plane(frag_a, 0, plane_pt, plane_n); + std::vector split_result = + split_face_by_plane(frag_a, 0, plane_pt, plane_n); if (split_result.empty()) { // Plane cut produced nothing → fragment unchanged (no deep copy). @@ -2119,6 +2202,11 @@ BrepModel brep_union(const BrepModel& a, const BrepModel& b) { // Disjoint: merge both bodies return sew_faces({a, b}); } + // B's tessellation is needed by the A-face pass below: build it now. + (void)get_body_mesh(b); + // A's tessellation is only consumed by the later B-face pass — build it on a + // background thread so it overlaps the A-face pass. + MeshPrefetch a_mesh(a); // ── v3.6 SSI-based approach ── // For each face of A: split against each face of B using SSI, @@ -2192,6 +2280,7 @@ BrepModel brep_union(const BrepModel& a, const BrepModel& b) { } // B faces: SSI-split against A, classify, keep OUT only (ON from A already) + a_mesh.join(); // A's tessellation is needed by the B-face pass below #ifdef VDE_USE_OPENMP #pragma omp parallel for schedule(dynamic) #endif @@ -2251,6 +2340,12 @@ BrepModel brep_intersection(const BrepModel& a, const BrepModel& b) { // Quick AABB check for disjoint bodies if (!a.bounds().intersects(b.bounds())) return BrepModel(); + // B's tessellation is needed by the A-face pass below: build it now. + (void)get_body_mesh(b); + // A's tessellation is only consumed by the later B-face pass — build it on a + // background thread so it overlaps the A-face pass. + MeshPrefetch a_mesh(a); + // ── v3.6 SSI-based approach ── // For intersection: keep fragments IN the other body, // and fragments ON the boundary (only from A to avoid duplicates). @@ -2307,6 +2402,7 @@ BrepModel brep_intersection(const BrepModel& a, const BrepModel& b) { } // B faces: SSI-split against A, classify, keep IN only + a_mesh.join(); // A's tessellation is needed by the B-face pass below #ifdef VDE_USE_OPENMP #pragma omp parallel for schedule(dynamic) #endif @@ -2368,6 +2464,12 @@ BrepModel brep_difference(const BrepModel& a, const BrepModel& b) { // Quick AABB check for disjoint bodies if (!a.bounds().intersects(b.bounds())) return copy_brep(a); + // B's tessellation is needed by the A-face pass below: build it now. + (void)get_body_mesh(b); + // A's tessellation is only consumed by the later B-face pass — build it on a + // background thread so it overlaps the A-face pass. + MeshPrefetch a_mesh(a); + // ── v3.6 SSI-based approach ── // For difference A \ B: // - Keep A fragments that are OUT of B (discard IN and ON) @@ -2425,6 +2527,7 @@ BrepModel brep_difference(const BrepModel& a, const BrepModel& b) { } // B faces: SSI-split against A, classify, keep IN (forms inner cut surface) + a_mesh.join(); // A's tessellation is needed by the B-face pass below #ifdef VDE_USE_OPENMP #pragma omp parallel for schedule(dynamic) #endif