Files
ViewDesignEngine/tests/benchmark/bench_kcp.cpp
T
hm d6cb92a1ef feat(corpus+bench): W4 语料规范/清单与 KCP-1.0 Wave1 基准 harness(B1/B2/B5/B6)
- corpus/:诚实语料清单(63 资产/513004B:61 合成 + 2 真实参照;corpus/real 与
  corpus/realfile 缺失登记为 missing 并双向校验),真实语料目录/获取/校验/licensing
  规范,manifest 生成与校验脚本(gen_manifest.py --check / verify_manifest.py --strict)
- tests/benchmark/bench_kcp.cpp:独立 CLI(不注册 ctest,不改既有测试结果),实现
  B1 STEP 布尔通过率(clean + 合成扰动 jitter/orientation)、B2 healing 恢复曲线
  (合成脏化 + 仓库真实脏夹具)、B5 拓扑/几何 IEEE bit-identical 与 OMP 线程加速比
- tools/bench_kcp/:run_kcp_bench.ps1(B1/B2/B5/B6 聚合 JSON/MD,PS5.1/7 兼容,
  B6 外部限时 bounded_pass 语义)、run_nightly_bench.ps1(语料门禁 + 4×450s≈30min
  fuzz + 历史归档)
- docs/planning/benchmarks-kcp-wave1.md:基准定义、字段契约、KC 覆盖、本地基线;
  docs/planning/benchmarks-nightly-integration.md:与 W1 CI nightly 对接的 YAML 片段
  与职责边界

本地样例(d2d50012,Release,24 逻辑核,报告
build/kcp_bench/run-20261119-214443/kcp_bench_20261119-214443.json):
B1 22/40(import 4/4,clean 9/12,perturbed 9/24);
B2 3/19(control 3/3,合成 gap/flip 0/15,真实脏夹具 0/1);
B5 13/16(threads=1 bit-identical,2/4/8 不一致,8T speedup 0.84x);
B6 4/4 bounded_pass(各 30s 无 FAILED/崩溃)。
真实语料为 0,B1/B2 真实数据 KPI 不成立;B5 暴露 KC-I12 多线程确定性/扩展性缺口,
本轮只报告不改内核。
2026-11-19 21:52:05 +08:00

1027 lines
43 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// KCP-1.0 Wave 1 / W4「语料与基准」:B1 / B2 / B5 基准 harness 命令行入口。
//
// 本文件是一个**独立可执行**(非 gtest),不注册 ctest 用例,因此不会改变
// 既有 ctest 结果;由 tools/bench_kcp/run_kcp_bench.ps1(或其它脚本)驱动。
//
// 子命令(--suite):
// b1 STEP 布尔通过率:fixtures 目录内全部 .step/.stp -> import_step ->
// bbox 派生 box cutter 上的 3 个布尔 op(union/intersection/difference),
// 干净集 + 合成扰动集(P1 顶点确定性抖动 / P2 面方向翻转)。
// b2 healing 恢复曲线:box/cylinder/sphere 控制集 + 合成脏模型
// (逐面克隆顶点/边的 detach 缺陷,gap 严重度 0/1e-5/1e-4/1e-3 相对最大尺寸;
// 以及 detach+隔面翻转) -> validate -> automatic_heal -> validate。
// 另加仓库内真实脏夹具 tests/data/w0_body87_open_5dangling.vde(存在才跑)。
// b5 确定性/加速比:固定工作负载多轮跑布尔流水线,输出拓扑+几何 IEEE-754
// bit digest;线程数由 driver 以 OMP_NUM_THREADS + --threads 双设定。
//
// 输出:JSON(字段 bench/suite/pass/total/elapsed_ms/env/git_sha/params/cases)。
// 用法:bench_kcp --suite b1 --fixtures-root <repo>/tests/data/fixtures
// --json-out build/kcp_b1.json [--rounds 3] [--threads 4]
// [--git-sha <sha>] [--workload box_cylinder] [--verbose]
//
// 约束(诚实性):
// - 不伪造“真实语料”:B1 的语料只有仓库内 fixtures(合成 STEP + 1 个 OCCT
// 官方回归模型),manifest/README 中如实标注;本 harness 不生成任何“真实模型”。
// - 只读测试数据,不写回仓库。
#include "vde/brep/brep.h"
#include "vde/brep/brep_boolean.h"
#include "vde/brep/brep_heal.h"
#include "vde/brep/brep_validate.h"
#include "vde/brep/modeling.h"
#include "vde/brep/parallel_boolean.h"
#include "vde/brep/step_import.h"
#include "vde/foundation/vde_format.h"
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <locale>
#include <sstream>
#include <string>
#include <thread>
#include <unordered_map>
#include <utility>
#include <vector>
namespace fs = std::filesystem;
using vde::core::Point3D;
using vde::brep::BooleanCheckResult;
using vde::brep::BrepModel;
using vde::brep::ValidationResult;
namespace {
constexpr const char* kBenchId = "KCP-1.0-Wave1-W4";
constexpr const char* kHarnessVersion = "0.1.0";
// ───────────────────────────── 基础工具 ─────────────────────────────
double now_ms() {
using clock = std::chrono::steady_clock;
static const auto t0 = clock::now();
return std::chrono::duration<double, std::milli>(clock::now() - t0).count();
}
std::string getenv_str(const char* key) {
const char* v = std::getenv(key);
return v ? std::string(v) : std::string();
}
std::string lower_ascii(std::string s) {
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
return s;
}
std::string escape_json(const std::string& in) {
std::string out;
out.reserve(in.size() + 16);
for (unsigned char c : in) {
switch (c) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (c < 0x20) {
char buf[8];
std::snprintf(buf, sizeof(buf), "\\u%04x", static_cast<unsigned>(c));
out += buf;
} else {
out.push_back(static_cast<char>(c));
}
}
}
return out;
}
std::string jstr(const std::string& v) { return "\"" + escape_json(v) + "\""; }
std::string jnum(double v, int precision = 6) {
if (!std::isfinite(v)) return "null";
std::ostringstream os;
os.imbue(std::locale::classic());
os << std::fixed << std::setprecision(precision) << v;
return os.str();
}
std::string jint(long long v) {
std::ostringstream os;
os.imbue(std::locale::classic());
os << v;
return os.str();
}
// ───────────────────────────── 用例结果 ─────────────────────────────
struct CaseResult {
std::string id;
std::string group;
bool pass = false;
double elapsed_ms = 0.0;
std::string detail;
std::vector<std::pair<std::string, double>> metrics;
std::vector<std::pair<std::string, std::string>> notes;
void metric(const std::string& name, double value) { metrics.emplace_back(name, value); }
void note(const std::string& name, const std::string& value) { notes.emplace_back(name, value); }
};
std::string case_json(const CaseResult& c) {
std::ostringstream os;
os.imbue(std::locale::classic());
os << "{\"id\":" << jstr(c.id) << ",\"group\":" << jstr(c.group)
<< ",\"status\":" << jstr(c.pass ? "pass" : "fail")
<< ",\"elapsed_ms\":" << jnum(c.elapsed_ms, 3)
<< ",\"detail\":" << jstr(c.detail);
if (!c.metrics.empty()) {
os << ",\"metrics\":{";
bool first = true;
for (const auto& kv : c.metrics) {
if (!first) os << ",";
first = false;
os << jstr(kv.first) << ":" << jnum(kv.second, 6);
}
os << "}";
}
if (!c.notes.empty()) {
os << ",\"notes\":{";
bool first = true;
for (const auto& kv : c.notes) {
if (!first) os << ",";
first = false;
os << jstr(kv.first) << ":" << jstr(kv.second);
}
os << "}";
}
os << "}";
return os.str();
}
// ───────────────────────────── 命令行 ─────────────────────────────
struct Cli {
std::string suite;
std::string json_out;
std::string fixtures_root = "tests/data/fixtures";
std::string test_data_root;
std::string git_sha;
std::string workload = "box_cylinder";
int rounds = 3;
int threads = 0;
bool verbose = false;
bool help = false;
std::string exe_path;
};
void print_usage() {
std::cout
<< "bench_kcp " << kHarnessVersion << " — KCP-1.0 W1/W4 corpus benchmark harness\n"
<< "usage: bench_kcp --suite <b1|b2|b5> [options]\n"
<< " --suite <b1|b2|b5> required; benchmark suite\n"
<< " --fixtures-root <dir> corpus root to scan (default tests/data/fixtures)\n"
<< " --test-data-root <dir> tests/data root (for w0_body87 dirty fixture)\n"
<< " --json-out <file> write JSON report to file\n"
<< " --git-sha <sha> git commit of the checked-out tree\n"
<< " --rounds <n> b5 repeat count (default 3)\n"
<< " --threads <n> b5 thread hint (0 = library default)\n"
<< " --workload <name> b5 workload: box_cylinder | box_cylinder_sphere | torus_box\n"
<< " --verbose print per-case progress to stderr\n"
<< " --help this message\n";
}
Cli parse_cli(int argc, char** argv) {
Cli c;
c.exe_path = (argc > 0) ? argv[0] : "";
for (int i = 1; i < argc; ++i) {
const std::string arg = argv[i];
auto value = [&](const char* name) -> std::string {
if (i + 1 >= argc) {
std::cerr << "missing value for " << name << "\n";
std::exit(2);
}
return argv[++i];
};
if (arg == "--suite") c.suite = value("--suite");
else if (arg == "--json-out") c.json_out = value("--json-out");
else if (arg == "--fixtures-root") c.fixtures_root = value("--fixtures-root");
else if (arg == "--test-data-root") c.test_data_root = value("--test-data-root");
else if (arg == "--git-sha") c.git_sha = value("--git-sha");
else if (arg == "--workload") c.workload = value("--workload");
else if (arg == "--rounds") c.rounds = std::stoi(value("--rounds"));
else if (arg == "--threads") c.threads = std::stoi(value("--threads"));
else if (arg == "--verbose") c.verbose = true;
else if (arg == "--help" || arg == "-h") c.help = true;
else {
std::cerr << "unknown argument: " << arg << "\n";
print_usage();
std::exit(2);
}
}
if (c.suite.empty()) {
std::cerr << "--suite is required\n";
print_usage();
std::exit(2);
}
if (c.test_data_root.empty()) {
// fixtures-root 默认 <repo>/tests/data/fixtures,则 tests/data 为其父目录。
fs::path p(c.fixtures_root);
c.test_data_root = p.parent_path().string();
}
return c;
}
// ───────────────────────────── 报告 ─────────────────────────────
std::string env_json(const Cli& c) {
std::ostringstream os;
os.imbue(std::locale::classic());
os << "{\"os\":\"windows\""
<< ",\"cpu_threads\":" << std::thread::hardware_concurrency()
<< ",\"omp_num_threads\":" << jstr(getenv_str("OMP_NUM_THREADS"))
<< ",\"omp_dynamic\":" << jstr(getenv_str("OMP_DYNAMIC"))
<< ",\"omp_thread_limit\":" << jstr(getenv_str("OMP_THREAD_LIMIT"))
<< ",\"arg_threads\":" << c.threads
<< ",\"parallel_thread_count\":" << vde::brep::parallel_thread_count()
<< ",\"cwd\":" << jstr(fs::current_path().string())
<< ",\"exe\":" << jstr(c.exe_path)
<< ",\"harness_version\":" << jstr(kHarnessVersion)
<< "}";
return os.str();
}
std::string params_json(const Cli& c) {
std::ostringstream os;
os.imbue(std::locale::classic());
os << "{\"fixtures_root\":" << jstr(c.fixtures_root)
<< ",\"test_data_root\":" << jstr(c.test_data_root)
<< ",\"rounds\":" << c.rounds
<< ",\"threads\":" << c.threads
<< ",\"workload\":" << jstr(c.workload);
os << "}";
return os.str();
}
struct SuiteResult {
std::string suite;
std::vector<CaseResult> cases;
double elapsed_ms = 0.0;
std::string summary_json = "{}";
std::vector<std::string> notes;
};
std::string report_json(const Cli& c, const SuiteResult& r) {
int pass = 0;
for (const auto& cs : r.cases) pass += cs.pass ? 1 : 0;
std::ostringstream os;
os.imbue(std::locale::classic());
os << "{\"bench\":" << jstr(kBenchId)
<< ",\"suite\":" << jstr(r.suite)
<< ",\"pass\":" << pass
<< ",\"total\":" << static_cast<int>(r.cases.size())
<< ",\"elapsed_ms\":" << jnum(r.elapsed_ms, 3)
<< ",\"git_sha\":" << jstr(c.git_sha)
<< ",\"env\":" << env_json(c)
<< ",\"params\":" << params_json(c)
<< ",\"summary\":" << r.summary_json
<< ",\"notes\":[";
for (size_t i = 0; i < r.notes.size(); ++i) {
if (i) os << ",";
os << jstr(r.notes[i]);
}
os << "],\"cases\":[";
for (size_t i = 0; i < r.cases.size(); ++i) {
if (i) os << ",";
os << case_json(r.cases[i]);
}
os << "]}";
return os.str();
}
bool write_text_file(const std::string& path, const std::string& content) {
if (path.empty()) return false;
fs::path p(path);
std::error_code ec;
if (p.has_parent_path()) fs::create_directories(p.parent_path(), ec);
std::ofstream f(p, std::ios::binary | std::ios::trunc);
if (!f) return false;
f << content;
return static_cast<bool>(f);
}
// ───────────────────────────── STEP 发现 ─────────────────────────────
struct StepFile {
fs::path path;
std::string rel;
};
std::vector<StepFile> discover_step_files(const std::string& root) {
std::vector<StepFile> files;
std::error_code ec;
if (!fs::exists(root, ec)) return files;
for (const auto& entry : fs::recursive_directory_iterator(
root, fs::directory_options::skip_permission_denied, ec)) {
if (ec) { ec.clear(); continue; }
if (!entry.is_regular_file(ec) || ec) { ec.clear(); continue; }
const std::string ext = lower_ascii(entry.path().extension().string());
if (ext != ".step" && ext != ".stp") continue;
StepFile f;
f.path = entry.path();
std::error_code rel_ec;
fs::path rel = fs::relative(entry.path(), root, rel_ec);
f.rel = rel_ec ? entry.path().filename().string() : rel.generic_string();
files.push_back(std::move(f));
}
std::sort(files.begin(), files.end(),
[](const StepFile& a, const StepFile& b) { return a.rel < b.rel; });
return files;
}
// ───────────────────────────── b1:STEP 布尔通过率 ─────────────────────────────
BooleanCheckResult run_boolean_op(const std::string& op, const BrepModel& a, const BrepModel& b) {
if (op == "union") return vde::brep::brep_union_checked(a, b);
if (op == "intersection") return vde::brep::brep_intersection_checked(a, b);
return vde::brep::brep_difference_checked(a, b);
}
// 用 A 的包围盒派生盒体 cutter 集;返回 {op, cutter}。
std::vector<std::pair<std::string, BrepModel>> make_cutters(const BrepModel& a) {
std::vector<std::pair<std::string, BrepModel>> cutters;
const auto bb = a.bounds();
const Point3D mn = bb.min();
const Point3D mx = bb.max();
const double ex = mx.x() - mn.x();
const double ey = mx.y() - mn.y();
const double ez = mx.z() - mn.z();
if (!(ex > 1e-9) || !(ey > 1e-9) || !(ez > 1e-9)) return cutters;
const Point3D c = bb.center();
// union:沿 +X/+Y 偏移的大盒,与 A 部分重叠并外伸,保证结果非退化。
cutters.emplace_back(
"union", vde::brep::make_box(ex * 0.8, ey * 0.8, ez * 0.8,
Point3D(c.x() + ex * 0.15, c.y() + ey * 0.15, c.z())));
// intersection:切一小角,结果既非空也非全 A。
cutters.emplace_back(
"intersection", vde::brep::make_box(ex * 0.5, ey * 0.5, ez * 0.5,
Point3D(c.x() + ex * 0.35, c.y() + ey * 0.35, c.z())));
// difference:切掉一角。
cutters.emplace_back(
"difference", vde::brep::make_box(ex * 0.5, ey * 0.5, ez * 0.6,
Point3D(c.x() + ex * 0.45, c.y() + ey * 0.45, c.z())));
return cutters;
}
void run_b1_ops(const BrepModel& a,
const std::vector<std::pair<std::string, BrepModel>>& cutters,
const std::string& file_rel,
const std::string& variant,
const std::string& group,
std::vector<CaseResult>& out,
bool verbose) {
for (const auto& op : cutters) {
CaseResult cs;
cs.id = file_rel + "::" + variant + "::" + op.first;
cs.group = group;
const double t0 = now_ms();
BooleanCheckResult r;
try {
r = run_boolean_op(op.first, a, op.second);
} catch (const std::exception& e) {
cs.elapsed_ms = now_ms() - t0;
cs.pass = false;
cs.detail = std::string("exception: ") + e.what();
out.push_back(std::move(cs));
if (verbose) std::cerr << "[b1] " << cs.id << " EXCEPTION\n";
continue;
}
cs.elapsed_ms = now_ms() - t0;
cs.pass = r.ok() && !r.quality.empty;
cs.metric("result_faces", static_cast<double>(r.quality.faces));
cs.metric("result_empty", r.quality.empty ? 1.0 : 0.0);
cs.metric("watertightness", r.quality.watertightness);
cs.metric("dangling_edges", static_cast<double>(r.quality.dangling_edges));
cs.metric("non_manifold_edges", static_cast<double>(r.quality.non_manifold_edges));
cs.metric("quality_ok", r.ok() ? 1.0 : 0.0);
if (!cs.pass) {
std::string why = r.quality.reason.empty() ? "quality_gate_failed" : r.quality.reason;
if (r.quality.empty) why = "empty_result";
cs.detail = why + " (wt=" + jnum(r.quality.watertightness, 4) +
", dangling=" + jint(static_cast<long long>(r.quality.dangling_edges)) + ")";
} else {
cs.detail = "ok";
}
if (verbose) {
std::cerr << "[b1] " << cs.id << " " << (cs.pass ? "pass" : "FAIL")
<< " " << jnum(cs.elapsed_ms, 1) << "ms\n";
}
out.push_back(std::move(cs));
}
}
void add_failure_case(std::vector<CaseResult>& out, const std::string& id,
const std::string& group, const std::string& detail) {
CaseResult cs;
cs.id = id;
cs.group = group;
cs.pass = false;
cs.detail = detail;
out.push_back(std::move(cs));
}
std::string build_b1_summary(const std::vector<CaseResult>& cases) {
int clean_pass = 0, clean_total = 0, pert_pass = 0, pert_total = 0;
int import_pass = 0, import_total = 0;
for (const auto& c : cases) {
if (c.group == "import") { import_total++; import_pass += c.pass ? 1 : 0; }
else if (c.group == "clean") { clean_total++; clean_pass += c.pass ? 1 : 0; }
else if (c.group.rfind("perturbed_", 0) == 0) {
pert_total++;
pert_pass += c.pass ? 1 : 0;
}
}
auto pct = [](int p, int t) { return t > 0 ? (100.0 * p / t) : 100.0; };
std::ostringstream os;
os.imbue(std::locale::classic());
os << "{\"import\":{\"pass\":" << import_pass << ",\"total\":" << import_total
<< ",\"rate_pct\":" << jnum(pct(import_pass, import_total), 2)
<< "},\"clean\":{\"pass\":" << clean_pass << ",\"total\":" << clean_total
<< ",\"rate_pct\":" << jnum(pct(clean_pass, clean_total), 2)
<< "},\"perturbed\":{\"pass\":" << pert_pass << ",\"total\":" << pert_total
<< ",\"rate_pct\":" << jnum(pct(pert_pass, pert_total), 2) << "}}";
return os.str();
}
void run_b1(const Cli& c, SuiteResult& result) {
const double t_suite = now_ms();
const auto files = discover_step_files(c.fixtures_root);
if (files.empty()) {
add_failure_case(result.cases, "discover::step", "infra",
"no .step/.stp files under fixtures root: " + c.fixtures_root);
result.notes.push_back("corpus_missing: fixtures root contains no STEP files");
result.elapsed_ms = now_ms() - t_suite;
result.summary_json = build_b1_summary(result.cases);
return;
}
for (const auto& f : files) {
// import
CaseResult ic;
ic.id = f.rel + "::import";
ic.group = "import";
const double ti = now_ms();
std::vector<BrepModel> bodies;
std::string import_err;
try {
bodies = vde::brep::import_step(f.path.string());
} catch (const std::exception& e) {
import_err = std::string("exception: ") + e.what();
}
ic.elapsed_ms = now_ms() - ti;
if (bodies.empty()) {
if (import_err.empty()) {
import_err = "empty_result";
try {
import_err += " step_error=" + std::to_string(
static_cast<int>(vde::brep::step_last_error()));
import_err += " msg=" + vde::brep::step_last_error_message();
} catch (...) {
import_err += " (step error detail unavailable)";
}
}
ic.pass = false;
ic.detail = import_err;
result.cases.push_back(std::move(ic));
if (c.verbose) std::cerr << "[b1] " << f.rel << " IMPORT FAILED: " << import_err << "\n";
continue;
}
ic.pass = true;
ic.metric("bodies", static_cast<double>(bodies.size()));
ic.detail = "bodies=" + jint(static_cast<long long>(bodies.size()));
result.cases.push_back(std::move(ic));
const BrepModel& a = bodies.front();
ic.metric("first_body_faces", static_cast<double>(a.num_faces()));
auto cutters = make_cutters(a);
if (cutters.empty()) {
add_failure_case(result.cases, f.rel + "::bounds", "infra",
"degenerate bbox on first imported body");
continue;
}
if (a.num_faces() == 0 || a.num_edges() == 0) {
add_failure_case(result.cases, f.rel + "::topology", "infra",
"imported body has no faces/edges");
continue;
}
// 干净集
run_b1_ops(a, cutters, f.rel, "clean", "clean", result.cases, c.verbose);
// P1 合成扰动:每 5 个顶点沿确定性方向移动 1e-5 * bbox 对角长。
{
BrepModel& m = bodies.front();
std::vector<Point3D> original;
original.reserve(m.num_vertices());
for (const auto& v : m.all_vertices()) original.push_back(v.point);
const auto bb = m.bounds();
const double diag = (bb.max() - bb.min()).norm();
const double amp = 1e-5 * (diag > 0.0 ? diag : 1.0);
for (size_t i = 0; i < original.size(); ++i) {
if (i % 5 != 0) continue;
const double a1 = static_cast<double>(i) * 12.9898;
const double b1 = static_cast<double>(i) * 78.233;
const double c1 = static_cast<double>(i) * 37.719;
Point3D dir(std::sin(a1), std::cos(b1), std::sin(c1));
const double len = dir.norm();
if (len < 1e-12) continue;
dir /= len;
m.set_vertex_point(static_cast<int>(i), original[i] + dir * amp);
}
run_b1_ops(m, cutters, f.rel, "jitter", "perturbed_jitter", result.cases, c.verbose);
for (size_t i = 0; i < original.size(); ++i) {
m.set_vertex_point(static_cast<int>(i), original[i]);
}
}
// P2 合成扰动:翻转若干面方向(拓扑不变,方向语义被破坏)。
{
BrepModel& m = bodies.front();
const size_t nf = m.num_faces();
if (nf == 0) continue;
std::vector<size_t> flipped;
for (size_t idx : {size_t{0}, nf / 3, (2 * nf) / 3}) {
if (idx < nf) flipped.push_back(idx);
}
std::sort(flipped.begin(), flipped.end());
flipped.erase(std::unique(flipped.begin(), flipped.end()), flipped.end());
for (size_t idx : flipped) {
m.set_face_reversed(static_cast<int>(idx), !m.all_faces()[idx].reversed);
}
run_b1_ops(m, cutters, f.rel, "orientation", "perturbed_orientation", result.cases,
c.verbose);
for (size_t idx : flipped) {
m.set_face_reversed(static_cast<int>(idx), !m.all_faces()[idx].reversed);
}
}
}
result.elapsed_ms = now_ms() - t_suite;
result.summary_json = build_b1_summary(result.cases);
result.notes.push_back("b1 corpus = repository fixtures only (synthetic STEP + 1 OCCT "
"regression model); no real-customer corpus is present or fabricated");
result.notes.push_back("perturbations are synthetic deformations (P1 vertex jitter 1e-5*diag, "
"P2 deterministic face-orientation flips)");
}
// ───────────────────────────── b2:healing 恢复曲线 ─────────────────────────────
BrepModel make_primitive(const std::string& name) {
if (name == "box") return vde::brep::make_box(4.0, 3.0, 2.0);
if (name == "cylinder") return vde::brep::make_cylinder(1.5, 4.0, 24);
if (name == "sphere") return vde::brep::make_sphere(1.5, 12, 6);
return vde::brep::make_box(2.0, 2.0, 2.0);
}
// 把 clean 的每个面“撕开”:每个面拥有独立的顶点/边副本(不共享),并沿
// “体中心 -> 面质心”方向整体平移 gap_abs(0 表示只撕开不分离)。这是可控、
// 可复现的合成脏模型来源:gap 严重度决定缝合难度。
BrepModel detach_faces(const BrepModel& clean, double gap_abs) {
BrepModel dirty;
for (size_t s = 0; s < clean.num_surfaces(); ++s) {
dirty.add_surface(clean.surface(static_cast<int>(s)));
}
const auto bb = clean.bounds();
const Point3D center = bb.center();
const auto& faces = clean.all_faces();
const auto& loops = clean.all_loops();
const auto& edges = clean.all_edges();
const auto& verts = clean.all_vertices();
for (size_t fi = 0; fi < faces.size(); ++fi) {
const auto& face = faces[fi];
Point3D fc(0.0, 0.0, 0.0);
size_t cnt = 0;
for (int li : face.loops) {
if (li < 0 || static_cast<size_t>(li) >= loops.size()) continue;
for (int ei : loops[static_cast<size_t>(li)].edges) {
if (ei < 0 || static_cast<size_t>(ei) >= edges.size()) continue;
const auto& e = edges[static_cast<size_t>(ei)];
fc += verts[static_cast<size_t>(e.v_start)].point;
fc += verts[static_cast<size_t>(e.v_end)].point;
cnt += 2;
}
}
Point3D offset(0.0, 0.0, 0.0);
if (gap_abs != 0.0 && cnt > 0) {
fc /= static_cast<double>(cnt);
Point3D dir = fc - center;
const double len = dir.norm();
if (len > 1e-12) offset = (dir / len) * gap_abs;
}
std::unordered_map<int, int> vmap;
std::vector<int> new_loops;
for (int li : face.loops) {
if (li < 0 || static_cast<size_t>(li) >= loops.size()) continue;
const auto& loop = loops[static_cast<size_t>(li)];
std::vector<int> new_edges;
for (int ei : loop.edges) {
if (ei < 0 || static_cast<size_t>(ei) >= edges.size()) continue;
const auto& e = edges[static_cast<size_t>(ei)];
auto get_vertex = [&](int ov) -> int {
auto it = vmap.find(ov);
if (it != vmap.end()) return it->second;
const int nv = dirty.add_vertex(
verts[static_cast<size_t>(ov)].point + offset);
vmap[ov] = nv;
return nv;
};
const int nv0 = get_vertex(e.v_start);
const int nv1 = get_vertex(e.v_end);
const int ne = e.curve ? dirty.add_edge(nv0, nv1, *e.curve)
: dirty.add_edge(nv0, nv1);
new_edges.push_back(ne);
}
new_loops.push_back(dirty.add_loop(new_edges, loop.is_outer));
}
const int nf = dirty.add_face(face.surface_id, new_loops);
dirty.set_face_reversed(nf, face.reversed);
}
dirty.rebuild_single_shell(true);
return dirty;
}
struct HealOutcome {
bool recovered = false;
ValidationResult before;
ValidationResult after;
int healed_items = 0;
int heal_score = 0;
int heal_steps = 0;
bool heal_degraded = false;
double elapsed_ms = 0.0;
};
HealOutcome heal_and_evaluate(BrepModel& body) {
HealOutcome o;
const double t0 = now_ms();
o.before = vde::brep::validate(body);
const auto rep = vde::brep::automatic_heal(body);
o.after = vde::brep::validate(body);
o.elapsed_ms = now_ms() - t0;
o.healed_items = rep.total_fixed();
o.heal_score = rep.overall_score;
o.heal_steps = rep.successful_steps();
o.heal_degraded = rep.degraded;
o.recovered = o.after.valid && o.after.watertightness >= 0.999 &&
o.after.dangling_edges == 0;
return o;
}
CaseResult make_heal_case(const std::string& id, const std::string& group,
const std::string& severity_note, BrepModel& body) {
CaseResult cs;
cs.id = id;
cs.group = group;
const HealOutcome o = heal_and_evaluate(body);
cs.elapsed_ms = o.elapsed_ms;
cs.pass = o.recovered;
cs.metric("before_valid", o.before.valid ? 1.0 : 0.0);
cs.metric("before_watertightness", o.before.watertightness);
cs.metric("before_dangling_edges", static_cast<double>(o.before.dangling_edges));
cs.metric("before_non_manifold_edges", static_cast<double>(o.before.non_manifold_edges));
cs.metric("before_errors", static_cast<double>(o.before.errors.size()));
cs.metric("after_valid", o.after.valid ? 1.0 : 0.0);
cs.metric("after_watertightness", o.after.watertightness);
cs.metric("after_dangling_edges", static_cast<double>(o.after.dangling_edges));
cs.metric("after_non_manifold_edges", static_cast<double>(o.after.non_manifold_edges));
cs.metric("after_errors", static_cast<double>(o.after.errors.size()));
cs.metric("healed_items", static_cast<double>(o.healed_items));
cs.metric("heal_score", static_cast<double>(o.heal_score));
cs.metric("heal_steps", static_cast<double>(o.heal_steps));
cs.metric("heal_degraded", o.heal_degraded ? 1.0 : 0.0);
cs.metric("recovered", o.recovered ? 1.0 : 0.0);
cs.note("severity", severity_note);
cs.detail = std::string(o.recovered ? "recovered" : "not_recovered") +
" (before wt=" + jnum(o.before.watertightness, 4) +
" dangling=" + jint(static_cast<long long>(o.before.dangling_edges)) +
"; after wt=" + jnum(o.after.watertightness, 4) +
" dangling=" + jint(static_cast<long long>(o.after.dangling_edges)) + ")";
return cs;
}
std::string build_b2_summary(const std::vector<CaseResult>& cases) {
// 按 group/severity 聚合恢复率,形成 “gap 严重度 -> 恢复率” 曲线。
struct Agg { int pass = 0; int total = 0; };
std::vector<std::pair<std::string, Agg>> ordered;
auto key_of = [](const CaseResult& c) {
std::string sev;
for (const auto& n : c.notes) {
if (n.first == "severity") sev = n.second;
}
return c.group + "|" + sev;
};
for (const auto& c : cases) {
const std::string key = key_of(c);
auto it = std::find_if(ordered.begin(), ordered.end(),
[&](const auto& kv) { return kv.first == key; });
if (it == ordered.end()) {
ordered.emplace_back(key, Agg{});
it = ordered.end() - 1;
}
it->second.total++;
it->second.pass += c.pass ? 1 : 0;
}
std::ostringstream os;
os.imbue(std::locale::classic());
os << "{\"curve\":[";
bool first = true;
for (const auto& kv : ordered) {
if (!first) os << ",";
first = false;
const auto sep = kv.first.find('|');
const std::string group = kv.first.substr(0, sep);
const std::string sev = sep == std::string::npos ? "" : kv.first.substr(sep + 1);
os << "{\"group\":" << jstr(group) << ",\"severity\":" << jstr(sev)
<< ",\"pass\":" << kv.second.pass << ",\"total\":" << kv.second.total
<< ",\"rate_pct\":"
<< jnum(kv.second.total > 0 ? 100.0 * kv.second.pass / kv.second.total : 0.0, 2)
<< "}";
}
os << "]}";
return os.str();
}
void run_b2(const Cli& c, SuiteResult& result) {
const double t_suite = now_ms();
const std::vector<std::string> prims = {"box", "cylinder", "sphere"};
for (const auto& name : prims) {
// 控制集:干净模型 heal 后应保持有效(恢复率基线)。
{
BrepModel clean = make_primitive(name);
CaseResult cs = make_heal_case(name + "::clean_control", "control", "clean", clean);
result.cases.push_back(std::move(cs));
}
// gap 严重度曲线:detach 缺陷 + 径向分离。
for (double rel : {0.0, 1e-5, 1e-4, 1e-3}) {
BrepModel clean = make_primitive(name);
const auto bb = clean.bounds();
const Point3D ext = bb.extent();
const double maxdim = std::max({std::abs(ext.x()), std::abs(ext.y()), std::abs(ext.z())});
BrepModel dirty = detach_faces(clean, rel * (maxdim > 0.0 ? maxdim : 1.0));
std::ostringstream sev;
sev.imbue(std::locale::classic());
sev << "gap_rel=" << rel;
CaseResult cs = make_heal_case(name + "::detach_gap_" + std::to_string(rel),
"detach_gap", sev.str(), dirty);
result.cases.push_back(std::move(cs));
}
// detach + 隔面翻转:同时考验缝合与方向统一。
{
BrepModel clean = make_primitive(name);
BrepModel dirty = detach_faces(clean, 0.0);
for (size_t i = 1; i < dirty.num_faces(); i += 2) {
dirty.set_face_reversed(static_cast<int>(i), !dirty.all_faces()[i].reversed);
}
CaseResult cs = make_heal_case(name + "::detach_flip", "detach_flip",
"gap_rel=0+flip_every_other", dirty);
result.cases.push_back(std::move(cs));
}
}
// 仓库内真实脏夹具(开放体 + 5 悬挂边):存在才跑,缺失如实标注。
{
const fs::path fixture = fs::path(c.test_data_root) / "w0_body87_open_5dangling.vde";
if (fs::exists(fixture)) {
try {
BrepModel body = vde::foundation::load_vde(fixture.string());
CaseResult cs = make_heal_case("w0_body87_open_5dangling::heal",
"fixture_real_dirty", "repository_fixture", body);
result.cases.push_back(std::move(cs));
} catch (const std::exception& e) {
add_failure_case(result.cases, "w0_body87_open_5dangling::load",
"fixture_real_dirty", std::string("load_vde exception: ") + e.what());
}
} else {
result.notes.push_back("fixture missing: " + fixture.string() + " (skipped, not fabricated)");
}
}
result.elapsed_ms = now_ms() - t_suite;
result.summary_json = build_b2_summary(result.cases);
result.notes.push_back("dirty models are synthetic, deterministic deformations of primitives "
"(per-face detached vertices/edges; radial gap = rel*max_dim)");
result.notes.push_back("recovered := validate().valid && watertightness>=0.999 && "
"dangling_edges==0 after automatic_heal()");
}
// ───────────────────────────── b5:确定性 digest / 加速比 ─────────────────────────────
struct BitDigest {
uint64_t hash = 1469598103934665603ULL; // FNV-1a offset basis
size_t vertices = 0, edges = 0, loops = 0, faces = 0, shells = 0;
void mix(uint64_t v) {
hash ^= v;
hash *= 1099511628211ULL;
}
void mix_int(int v) { mix(static_cast<uint64_t>(static_cast<int64_t>(v))); }
void mix_double(double d) {
uint64_t u = 0;
std::memcpy(&u, &d, sizeof(u));
mix(u);
}
std::string hex() const {
std::ostringstream os;
os.imbue(std::locale::classic());
os << std::hex << std::setw(16) << std::setfill('0') << hash;
return os.str();
}
};
BitDigest compute_digest(const BrepModel& m) {
BitDigest d;
d.vertices = m.num_vertices();
d.edges = m.num_edges();
d.loops = m.all_loops().size();
d.faces = m.num_faces();
d.shells = m.all_shells().size();
d.mix_int(static_cast<int>(d.vertices));
d.mix_int(static_cast<int>(d.edges));
d.mix_int(static_cast<int>(d.loops));
d.mix_int(static_cast<int>(d.faces));
d.mix_int(static_cast<int>(d.shells));
for (const auto& v : m.all_vertices()) {
d.mix_double(v.point.x());
d.mix_double(v.point.y());
d.mix_double(v.point.z());
d.mix_double(v.tolerance);
}
for (const auto& e : m.all_edges()) {
d.mix_int(e.v_start);
d.mix_int(e.v_end);
d.mix_int(e.reversed ? 1 : 0);
// 只掺入“是否有曲线几何”这一位;不掺指针地址(ASLR 会破坏跨轮确定性)。
d.mix_int(e.curve ? 1 : 0);
}
for (const auto& l : m.all_loops()) {
d.mix_int(l.is_outer ? 1 : 0);
d.mix_int(static_cast<int>(l.edges.size()));
for (int ei : l.edges) d.mix_int(ei);
}
for (const auto& f : m.all_faces()) {
d.mix_int(f.surface_id);
d.mix_int(f.trimmed_surface_id);
d.mix_int(f.reversed ? 1 : 0);
d.mix_int(f.visible ? 1 : 0);
d.mix_int(static_cast<int>(f.loops.size()));
for (int li : f.loops) d.mix_int(li);
}
for (const auto& s : m.all_shells()) {
d.mix_int(s.closed ? 1 : 0);
d.mix_int(static_cast<int>(s.faces.size()));
for (int fi : s.faces) d.mix_int(fi);
}
for (const auto& b : m.all_bodies()) {
d.mix_int(static_cast<int>(b.shells.size()));
for (int si : b.shells) d.mix_int(si);
}
return d;
}
BrepModel make_workload(const std::string& name) {
if (name == "torus_box") {
BrepModel t = vde::brep::make_torus(4.0, 1.2, 48, 24);
BrepModel cut = vde::brep::make_box(6.0, 6.0, 4.0, Point3D(3.0, 0.0, 0.0));
return vde::brep::brep_difference(t, cut);
}
if (name == "box_cylinder_sphere") {
BrepModel a = vde::brep::make_box(10.0, 8.0, 6.0);
BrepModel b = vde::brep::make_cylinder(3.0, 14.0, 64, Point3D(2.0, 1.0, 0.0));
BrepModel c = vde::brep::make_sphere(3.0, 24, 12, Point3D(-2.0, -1.0, 1.0));
BrepModel ab = vde::brep::brep_union(a, b);
BrepModel abc = vde::brep::brep_union(ab, c);
BrepModel cutter = vde::brep::make_box(4.0, 4.0, 8.0, Point3D(3.0, 2.0, 0.0));
return vde::brep::brep_difference(abc, cutter);
}
// 默认 box_cylinder
BrepModel a = vde::brep::make_box(10.0, 8.0, 6.0);
BrepModel b = vde::brep::make_cylinder(3.0, 14.0, 64, Point3D(2.0, 1.0, 0.0));
BrepModel ab = vde::brep::brep_union(a, b);
BrepModel cutter = vde::brep::make_box(4.0, 4.0, 8.0, Point3D(3.0, 2.0, 0.0));
return vde::brep::brep_difference(ab, cutter);
}
std::string build_b5_summary(const std::vector<BitDigest>& digests,
const std::vector<double>& round_ms) {
bool identical = true;
for (size_t i = 1; i < digests.size(); ++i) {
if (digests[i].hash != digests[0].hash) identical = false;
}
double tmin = 1e300;
std::vector<double> sorted = round_ms;
std::sort(sorted.begin(), sorted.end());
for (double t : round_ms) tmin = std::min(tmin, t);
const double median = sorted.empty() ? 0.0 : sorted[sorted.size() / 2];
std::ostringstream os;
os.imbue(std::locale::classic());
os << "{\"bit_identical\":" << (identical ? "true" : "false")
<< ",\"digest\":" << jstr(digests.empty() ? "" : digests[0].hex())
<< ",\"rounds\":" << static_cast<int>(digests.size())
<< ",\"t_min_ms\":" << jnum(tmin, 3)
<< ",\"t_median_ms\":" << jnum(median, 3)
<< ",\"topology\":{\"vertices\":" << static_cast<long long>(digests.empty() ? 0 : digests[0].vertices)
<< ",\"edges\":" << static_cast<long long>(digests.empty() ? 0 : digests[0].edges)
<< ",\"loops\":" << static_cast<long long>(digests.empty() ? 0 : digests[0].loops)
<< ",\"faces\":" << static_cast<long long>(digests.empty() ? 0 : digests[0].faces)
<< ",\"shells\":" << static_cast<long long>(digests.empty() ? 0 : digests[0].shells)
<< "}}";
return os.str();
}
void run_b5(const Cli& c, SuiteResult& result) {
const double t_suite = now_ms();
if (c.threads > 0) {
vde::brep::set_parallel_threads(c.threads);
}
const int rounds = std::max(1, c.rounds);
std::vector<BitDigest> digests;
std::vector<double> round_ms;
for (int r = 0; r < rounds; ++r) {
const double t0 = now_ms();
BrepModel body = make_workload(c.workload);
const double ms = now_ms() - t0;
const BitDigest d = compute_digest(body);
CaseResult cs;
cs.id = "round_" + std::to_string(r + 1);
cs.group = "round";
cs.pass = d.faces > 0;
cs.elapsed_ms = ms;
cs.metric("faces", static_cast<double>(d.faces));
cs.metric("vertices", static_cast<double>(d.vertices));
cs.note("digest", d.hex());
cs.detail = d.hex();
result.cases.push_back(std::move(cs));
digests.push_back(d);
round_ms.push_back(ms);
}
// 确定性用例:多轮 digest 必须全部相同。
CaseResult det;
det.id = "bit_identical";
det.group = "determinism";
bool identical = true;
for (size_t i = 1; i < digests.size(); ++i) {
if (digests[i].hash != digests[0].hash) identical = false;
}
det.pass = identical;
det.detail = identical ? "all rounds produced identical topology+geometry digest"
: "digest mismatch across rounds";
det.metric("rounds", static_cast<double>(rounds));
det.metric("bit_identical", identical ? 1.0 : 0.0);
result.cases.push_back(std::move(det));
result.elapsed_ms = now_ms() - t_suite;
result.summary_json = build_b5_summary(digests, round_ms);
result.notes.push_back("digest covers topology indices + IEEE-754 bits of vertex coordinates "
"and tolerances; threads set via --threads and OMP_NUM_THREADS");
result.notes.push_back("speedup is computed by the driver comparing --threads 1 vs N");
}
} // namespace
int main(int argc, char** argv) {
Cli cli = parse_cli(argc, argv);
if (cli.help) { print_usage(); return 0; }
SuiteResult result;
if (cli.suite == "b1") { result.suite = "B1"; run_b1(cli, result); }
else if (cli.suite == "b2") { result.suite = "B2"; run_b2(cli, result); }
else if (cli.suite == "b5") { result.suite = "B5"; run_b5(cli, result); }
else {
std::cerr << "unknown suite: " << cli.suite << "\n";
print_usage();
return 2;
}
const std::string json = report_json(cli, result);
if (!cli.json_out.empty()) {
if (!write_text_file(cli.json_out, json)) {
std::cerr << "failed to write JSON report: " << cli.json_out << "\n";
return 3;
}
}
int pass = 0;
for (const auto& cs : result.cases) pass += cs.pass ? 1 : 0;
std::cout << "BENCH " << result.suite << " pass=" << pass << "/" << result.cases.size()
<< " elapsed_ms=" << jnum(result.elapsed_ms, 1)
<< (cli.json_out.empty() ? "" : (" json=" + cli.json_out)) << "\n";
if (!cli.json_out.empty()) {
std::cout << json << "\n";
}
return 0;
}