Files
ViewDesignEngine/tests/foundation/test_model_corpus.cpp
T
hm 849ce5e4ff feat(brep): STEP 曲面集(CBS)/未裁剪曲面/镶嵌面导入覆盖 + conic trim 口径修复
- CURVE_BOUNDED_SURFACE 开放薄壳导入:按 representation group 建 sheet body;
  环曲线端点按 placement+半径解析求值(不依赖 NURBS 非整象限估值)、相对尺度
  链缝合容差、允许 2 段双弧孔环 → occ__wgehaeuse_surface 30/30 groups、
  2817/2823 patches 源面片 1:1 映射(仅 6 个 0.006-0.024mm 文件写精度缝 drop)
- 未裁剪曲面集(GBSR/GEOMETRIC_SET)与 AP242 TESSELLATED 网格表示导入通道,
  不再因无壳/面拓扑静默空开,并输出导入降级报告
- conic trim 弧度/角度惯例自动判别(ensure_conic_trim_convention)与边界
  .T./.F. 方向修正
- 追踪开关 VDE_TRACE_CBS / VDE_REPAIR_DEBUG / VDE_REPAIR_LIST /
  VDE_TIMING_STEP / VDE_IMPORT_DUMP_WARN,清理无条件调试输出
- vde_step_probe 扩展 --diag-only/--mesh-only/--analytic-only/--roundtrip;
  扩充 roundtrip/语料/网格回归测试
2026-09-09 12:36:59 +08:00

997 lines
42 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.
/// @file test_model_corpus.cpp
/// @brief D2: 真实测试模型库遍历测试
///
/// 遍历仓库根 corpus/ 下所有模型文件,按格式分发到对应导入器:
/// 1. STEP (.step/.stp/.p21) -> import_step
/// 2. IGES (.igs/.iges) -> import_iges
/// 3. STL (.stl) -> read_stl
/// 4. 3MF (.3mf) -> read_3mf
/// 5. GLB (.glb/.gltf) -> import_gltf
/// 6. DXF (.dxf) -> import_dxf
/// 7. SAT (.sat) -> import_acis_sat
/// 8. XT (.x_t/.xt) -> import_parasolid_xt(若可用)
///
/// 对每个文件:
/// - 导入过程不允许崩溃(异常也算失败,但先捕获记录)
/// - 统计每种格式的成功率,输出失败明细供分析
///
/// 另含 M1 网格三格式导入率基线(ModelCorpus.MeshImportRateBaseline),
/// 通过 VDE_MESH_BATCH_DIR 指向 corpus/stl|3mf|glb 全量语料(~30.5k)跑
/// STL/3MF/GLB 导入率基线;仅评导入率(网格无 heal/validate 语义)。
///
/// 目录中无模型文件时测试自动跳过(CI 环境)。
/// 通过 CMake 注入 TEST_MODEL_DIR 指向模型库根目录。
///
/// 注:为避免 MinGW GCC 8.1 std::filesystem 的 wchar path 转换 bug,
/// 使用 POSIX dirent 递归遍历目录。
#include <gtest/gtest.h>
#include "vde/brep/format_io.h"
#include "vde/brep/step_import.h"
#include "vde/brep/iges_import.h"
#include "vde/brep/dxf_import.h"
#include "vde/brep/brep_heal.h"
#include "vde/brep/brep_validate.h"
#include "vde/brep/brep_boolean.h"
#include "vde/brep/modeling.h"
#include "vde/brep/advanced_blend.h"
#include "vde/foundation/io_stl.h"
#include "vde/foundation/io_3mf.h"
#include "vde/foundation/io_gltf.h"
#include "vde/foundation/industrial_formats.h"
#include <algorithm>
#include <cctype>
#include <chrono>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <map>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
#ifdef _WIN32
#include <windows.h>
#else
#include <dirent.h>
#include <sys/stat.h>
#endif
#ifndef TEST_MODEL_DIR
#define TEST_MODEL_DIR "corpus"
#endif
/// 真实工业模型库(用户交付的 STEP/IGES 等真实零件,G1 realfile 接入)
#ifndef TEST_REALFILE_DIR
#define TEST_REALFILE_DIR "corpus/realfile"
#endif
/// M5/M6 语料(3800+ 真实工业 CAD 模型,H1 通过率基准)
#ifndef TEST_REAL_CORPUS_DIR
#define TEST_REAL_CORPUS_DIR "corpus/real"
#endif
/// G1 三率测试参数(真实模型体积大,导入/修复/验证耗时不可控):
/// - 单文件大小上限:超过则跳过(记为 too_large,不参与三率统计)
/// - 全局时间预算:累计耗时超过则提前结束(防止 CI 卡死)
static const double kRealfileMaxMB = 5.0;
static const double kRealfileBudgetSec = 600.0;
/// 全局时间预算(秒)。默认 600(CI 卡死保护);全量基线/手工验收可设
/// 环境变量 VDE_REAL_BUDGET_SEC 覆盖(如 3600),逐文件耗时 ~10-70s 不等。
double realfile_budget_sec() {
if (const char* e = std::getenv("VDE_REAL_BUDGET_SEC")) {
char* end = nullptr;
const double v = std::strtod(e, &end);
if (end != e && v > 0.0) return v;
}
return kRealfileBudgetSec;
}
// 可选运行时"新投放批次"目录:用户每投放一批新真实模型后,不必重编译即可
// 把该目录并入真实文件报告(31-追赶OCCT执行方案.md 第五/0.5 节协作约定)。
// VDE_REAL_BATCH_DIR 批次目录(不设置则空跑)
// VDE_REAL_BATCH_MAX 参与文件数上限(默认 60,仅对抽样测试生效;
// 三率测试仍受 VDE_REAL_BUDGET_SEC 时间预算约束)
std::string realfile_batch_dir() {
if (const char* e = std::getenv("VDE_REAL_BATCH_DIR")) return e;
return std::string();
}
int realfile_batch_max() {
if (const char* e = std::getenv("VDE_REAL_BATCH_MAX")) {
char* end = nullptr;
const int v = static_cast<int>(std::strtol(e, &end, 10));
if (end != e && v > 0) return v;
}
return 60;
}
/// M1 网格三格式(STL/3MF/GLB)导入率基线参数(2026-09 用户新投放 ~30.5k 语料):
/// VDE_MESH_BATCH_DIR 参与目录,';' 分隔(建议给绝对路径)
/// VDE_MESH_BUDGET_SEC 全局时间预算(默认 1800,防解析器死循环拖死批跑)
/// VDE_MESH_MAX_MB 单文件大小上限(默认 200MB;超出跳过,不参与统计)
/// VDE_CORPUS_FAIL_LIST 全量失败名单落盘路径([empty]/[error] 行式,免重编译分类)
double mesh_budget_sec() {
if (const char* e = std::getenv("VDE_MESH_BUDGET_SEC")) {
char* end = nullptr;
const double v = std::strtod(e, &end);
if (end != e && v > 0.0) return v;
}
return 1800.0;
}
double mesh_max_mb() {
if (const char* e = std::getenv("VDE_MESH_MAX_MB")) {
char* end = nullptr;
const double v = std::strtod(e, &end);
if (end != e && v > 0.0) return v;
}
return 200.0;
}
/// 按分隔符切分环境变量目录列表
std::vector<std::string> split_env_list(const std::string& s, char sep) {
std::vector<std::string> out;
size_t start = 0;
while (start < s.size()) {
size_t pos = s.find(sep, start);
if (pos == std::string::npos) { out.push_back(s.substr(start)); break; }
out.push_back(s.substr(start, pos - start));
start = pos + 1;
}
return out;
}
/// 文件大小(字节);获取失败返回 -1
long long file_size_bytes(const std::string& path) {
#ifdef _WIN32
WIN32_FILE_ATTRIBUTE_DATA ad;
if (GetFileAttributesExA(path.c_str(), GetFileExInfoStandard, &ad))
return (static_cast<long long>(ad.nFileSizeHigh) << 32) + ad.nFileSizeLow;
return -1;
#else
struct stat st;
if (stat(path.c_str(), &st) == 0) return st.st_size;
return -1;
#endif
}
using namespace vde::brep;
using namespace vde::foundation;
namespace {
/// 收集目录下所有文件(递归)
void collect_files(const std::string& root, std::vector<std::string>& out) {
#ifdef _WIN32
// Windows: 使用 FindFirstFile 递归(兼容 MinGW 无 dirent 的环境)
std::string pattern = root + "/*";
WIN32_FIND_DATAA fd;
HANDLE h = FindFirstFileA(pattern.c_str(), &fd);
if (h == INVALID_HANDLE_VALUE) return;
do {
std::string name = fd.cFileName;
if (name == "." || name == "..") continue;
std::string full = root + "/" + name;
if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
if (name != "generated") // generated/ 为生成脚本中间产物,跳过
collect_files(full, out);
} else if (name != ".gitkeep") {
out.push_back(full);
}
} while (FindNextFileA(h, &fd));
FindClose(h);
#else
DIR* dir = opendir(root.c_str());
if (!dir) return;
struct dirent* ent;
while ((ent = readdir(dir)) != nullptr) {
std::string name = ent->d_name;
if (name == "." || name == "..") continue;
std::string full = root + "/" + name;
struct stat st;
if (stat(full.c_str(), &st) == 0) {
if (S_ISDIR(st.st_mode)) {
collect_files(full, out);
} else if (name != ".gitkeep") {
out.push_back(full);
}
}
}
closedir(dir);
#endif
}
/// 获取扩展名(小写,含点号)
std::string extension_lower(const std::string& path) {
auto pos = path.find_last_of(".\\/");
std::string ext;
if (pos != std::string::npos && path[pos] == '.') {
ext = path.substr(pos);
}
std::transform(ext.begin(), ext.end(), ext.begin(),
[](unsigned char c) { return static_cast<char>(std::tolower(c)); });
return ext;
}
/// 每种格式的统计
struct FormatStats {
std::string name;
bool require_ok = true; ///< 为 true 时断言该格式至少成功导入 1 个
int total = 0;
int ok = 0;
int empty = 0; ///< 导入完成但结果为空(可能是不支持的特性)
int error = 0; ///< 抛出异常
std::vector<std::string> failed_files;
std::vector<std::string> error_files;
void report() const {
std::cerr << " [" << name << "] " << ok << "/" << total
<< " imported (" << empty << " empty, " << error << " error)\n";
const size_t kMaxList = 50;
size_t shown = 0;
for (const auto& f : failed_files) {
if (shown >= kMaxList) break;
std::cerr << " [empty] " << f << "\n";
++shown;
}
if (failed_files.size() > shown)
std::cerr << " ... 另有 " << (failed_files.size() - shown)
<< " 个 empty 未列出\n";
shown = 0;
for (const auto& f : error_files) {
if (shown >= kMaxList) break;
std::cerr << " [error] " << f << "\n";
++shown;
}
if (error_files.size() > shown)
std::cerr << " ... 另有 " << (error_files.size() - shown)
<< " 个 error 未列出\n";
}
};
/// 按格式分发导入。返回 true 表示导入结果非空。
/// 异常会向外抛出(由调用方捕获记录)。
bool import_by_format(const std::string& f, const std::string& ext) {
if (ext == ".step" || ext == ".stp" || ext == ".p21") {
auto models = import_step(f);
return !models.empty();
}
if (ext == ".igs" || ext == ".iges") {
auto models = import_iges(f);
return !models.empty();
}
if (ext == ".stl") {
auto tris = read_stl(f);
return !tris.empty();
}
if (ext == ".3mf") {
auto meshes = read_3mf(f);
return !meshes.empty();
}
if (ext == ".glb" || ext == ".gltf") {
auto res = import_gltf(f);
if (!res.success || res.meshes.empty()) {
if (!res.error_message.empty())
throw std::runtime_error("gltf: " + res.error_message);
return false;
}
return true;
}
if (ext == ".dxf") {
auto res = import_dxf(f);
return res.entities_parsed > 0 && !res.contours.empty();
}
if (ext == ".sat") {
auto m = vde::io::import_acis_sat(f);
return m.num_faces() > 0;
}
if (ext == ".xt" || ext == ".x_t") {
auto m = vde::io::import_parasolid_xt(f);
return m.num_faces() > 0;
}
return false; // 未知格式
}
/// 判断扩展名是否参与批量导入
bool is_known_format(const std::string& ext) {
return ext == ".step" || ext == ".stp" || ext == ".p21" ||
ext == ".igs" || ext == ".iges" || ext == ".stl" ||
ext == ".3mf" || ext == ".glb" || ext == ".gltf" ||
ext == ".dxf" || ext == ".sat" || ext == ".xt" || ext == ".x_t";
}
/// 导入 → 自动修复 → 验证 三率流水线(G1 真实模型验收)。
/// 返回 true 表示导入非空;healed 记录 automatic_heal 无异常且修复后面数>0;
/// validated 记录修复后 validate() 水密通过(valid 且 watertightness>0.99)。
/// residual_out(可选):文件级整体未通过验证时,输出首个失败 body 的紧凑残余
/// 描述(faces/wt/error 数+首条),作为"明确降级报告"供 fail_valid 归类。
/// 非 STEP/IGES 格式只统计导入率(healed/validated 置 true,不做深查)。
/// 设环境变量 VDE_REAL_TIMING=1 时按文件打印 import/heal/validate 三阶段耗时
/// (用于定位真实模型逐文件 ~70s 的热点,见 31-追赶OCCT执行方案.md §六·A)。
bool import_heal_validate(const std::string& f, const std::string& ext,
bool& healed, bool& validated,
std::string* residual_out = nullptr,
bool* empty_source_out = nullptr) {
healed = false;
validated = false;
if (residual_out) residual_out->clear();
if (empty_source_out) *empty_source_out = false;
const bool timing = std::getenv("VDE_REAL_TIMING") != nullptr;
auto t0 = std::chrono::steady_clock::now();
std::vector<BrepModel> models;
if (ext == ".step" || ext == ".stp" || ext == ".p21") {
models = import_step(f);
} else if (ext == ".igs" || ext == ".iges") {
models = import_iges(f);
} else {
bool ok = import_by_format(f, ext);
if (ok) { healed = true; validated = true; }
return ok;
}
auto t1 = std::chrono::steady_clock::now();
if (models.empty()) {
// 解析成功但文件中没有任何实体几何(如仅含曲线线框/构造数据的源文件,
// technic42006 ARM、纯 2D 图纸等)→ 空壳源:打开成功、无 B-Rep 可导入,
// 由调用方按"明确降级报告"归类,而非当作引擎导入失败。
if (empty_source_out) *empty_source_out = true;
return false;
}
long long heal_ms = 0, valid_ms = 0;
for (auto& m : models) {
auto th0 = std::chrono::steady_clock::now();
automatic_heal(m);
auto th1 = std::chrono::steady_clock::now();
healed = true;
auto vr = validate(m);
auto tv1 = std::chrono::steady_clock::now();
if (vr.valid && vr.watertightness > 0.99) {
validated = true;
} else if (residual_out && residual_out->empty()) {
// 记录首个未通过 body 的残余(不打断循环;若后续 body 通过则整体
// validated=true,调用方据此忽略 residual)
std::ostringstream rs;
rs << "faces=" << m.num_faces()
<< " wt=" << vr.watertightness
<< " err=" << vr.errors.size()
<< " warn=" << vr.warnings.size();
if (!vr.errors.empty())
rs << " [" << vr.errors.front() << "]";
if (!vr.warnings.empty())
rs << " {" << vr.warnings.front() << "}";
*residual_out = rs.str();
}
heal_ms += std::chrono::duration_cast<std::chrono::milliseconds>(th1 - th0).count();
valid_ms += std::chrono::duration_cast<std::chrono::milliseconds>(tv1 - th1).count();
}
if (timing) {
const auto import_ms = std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count();
std::cerr << "[timing] " << f << " models=" << models.size()
<< " import=" << import_ms << "ms heal=" << heal_ms
<< "ms validate=" << valid_ms << "ms\n";
}
return true;
}
} // namespace
// ═══════════════════════════════════════════════════════════
// 模型库遍历测试
// ═══════════════════════════════════════════════════════════
TEST(ModelCorpus, DirectoryHasFiles) {
std::vector<std::string> files;
collect_files(TEST_MODEL_DIR, files);
if (files.empty()) {
GTEST_SKIP() << "模型库为空(" << TEST_MODEL_DIR
<< "),请添加模型文件后重试";
}
EXPECT_FALSE(files.empty());
}
TEST(ModelCorpus, AllFilesImportWithoutCrash) {
std::vector<std::string> files;
collect_files(TEST_MODEL_DIR, files);
if (files.empty()) {
GTEST_SKIP() << "模型库为空,跳过导入测试";
}
std::map<std::string, FormatStats> stats;
auto init_stats = [](const char* name) {
FormatStats s; s.name = name; return s;
};
stats[".step"] = init_stats("STEP"); stats[".stp"] = init_stats("STEP"); stats[".p21"] = init_stats("STEP");
stats[".igs"] = init_stats("IGES"); stats[".iges"] = init_stats("IGES");
stats[".stl"] = init_stats("STL");
stats[".3mf"] = init_stats("3MF");
stats[".glb"] = init_stats("GLB"); stats[".gltf"] = init_stats("GLB");
stats[".dxf"] = init_stats("DXF");
stats[".sat"] = init_stats("SAT");
stats[".xt"] = init_stats("XT"); stats[".x_t"] = init_stats("XT");
int total = 0, ok = 0;
for (const auto& f : files) {
auto ext = extension_lower(f);
if (!is_known_format(ext)) continue; // README / 未知格式不参与导入
++total;
auto& st = stats[ext];
++st.total;
try {
bool imported = import_by_format(f, ext);
if (imported) {
++ok; ++st.ok;
} else {
++st.empty;
st.failed_files.push_back(f);
}
} catch (const std::exception& e) {
++st.error;
st.error_files.push_back(f + " (" + e.what() + ")");
} catch (...) {
++st.error;
st.error_files.push_back(f + " (unknown exception)");
}
}
// 汇总:先按格式打印,去重 STEP/IGES 等合并条目
std::cerr << "[corpus] " << ok << "/" << total << " imported\n";
std::map<std::string, FormatStats> merged;
for (auto& kv : stats) {
if (kv.second.total == 0) continue;
auto& m = merged[kv.second.name];
m.name = kv.second.name;
m.require_ok = m.require_ok && kv.second.require_ok;
m.total += kv.second.total;
m.ok += kv.second.ok;
m.empty += kv.second.empty;
m.error += kv.second.error;
m.failed_files.insert(m.failed_files.end(),
kv.second.failed_files.begin(), kv.second.failed_files.end());
m.error_files.insert(m.error_files.end(),
kv.second.error_files.begin(), kv.second.error_files.end());
}
for (auto& kv : merged) kv.second.report();
if (total > 0) {
EXPECT_GT(ok, 0) << "所有模型均导入失败";
// 每种格式至少成功导入 1 个(用于发现某格式导入器整体失效)
for (auto& kv : merged) {
if (!kv.second.require_ok) continue;
SCOPED_TRACE("格式 " + kv.second.name);
EXPECT_GT(kv.second.ok, 0)
<< "格式 " << kv.second.name << " 全部导入失败,共 "
<< kv.second.total << " 个文件";
}
}
}
TEST(ModelCorpus, FormatDetection) {
std::vector<std::string> files;
collect_files(TEST_MODEL_DIR, files);
int checked = 0;
for (const auto& f : files) {
auto ext = extension_lower(f);
if (ext != ".step" && ext != ".stp" && ext != ".p21" &&
ext != ".igs" && ext != ".iges") continue;
++checked;
auto fmt = detect_format(f);
if (ext == ".step" || ext == ".stp" || ext == ".p21") {
EXPECT_EQ(fmt, CadFormat::STEP) << f;
} else {
EXPECT_EQ(fmt, CadFormat::IGES) << f;
}
}
std::cerr << "[corpus] format detection checked " << checked << " files" << std::endl;
}
// ═══════════════════════════════════════════════════════════
// G1: 真实工业模型库三率报告(realfile)
// ═══════════════════════════════════════════════════════════
TEST(ModelCorpus, RealFileThreeRates) {
std::vector<std::string> files;
collect_files(TEST_REALFILE_DIR, files);
std::string batch = realfile_batch_dir();
if (!batch.empty()) collect_files(batch, files);
if (files.empty()) {
GTEST_SKIP() << "realfile 模型库为空(" << TEST_REALFILE_DIR
<< "),请添加真实模型后重试";
}
int total = 0, imported = 0, healed = 0, validated = 0, skipped_large = 0, skipped_budget = 0;
std::vector<std::string> fail_import, fail_heal, fail_valid, too_large;
std::vector<std::string> empty_sources; // 空壳源(打开成功、无实体几何)
std::map<std::string, std::string> residual_by_file; // fail_valid 残余降级报告
auto t_start = std::chrono::steady_clock::now();
double elapsed_sec = 0.0;
for (const auto& f : files) {
auto ext = extension_lower(f);
if (!is_known_format(ext)) continue; // README / DWG 等未接入格式
// 全局时间预算:超时提前结束,防止 CI 卡死
elapsed_sec = std::chrono::duration<double>(std::chrono::steady_clock::now() - t_start).count();
if (elapsed_sec > realfile_budget_sec()) {
++skipped_budget;
continue;
}
// 大小过滤:真实装配体普遍 >5MB,超出部分跳过(不参与三率)
long long sz = file_size_bytes(f);
if (sz > static_cast<long long>(kRealfileMaxMB * 1024 * 1024)) {
++skipped_large;
too_large.push_back(f);
continue;
}
++total;
bool h = false, v = false;
bool empty_src = false;
std::string residual;
try {
bool ok = import_heal_validate(f, ext, h, v, &residual, &empty_src);
if (ok) {
++imported;
if (h) ++healed; else fail_heal.push_back(f);
if (v) ++validated; else {
fail_valid.push_back(f);
if (!residual.empty()) residual_by_file[f] = residual;
}
} else if (empty_src) {
empty_sources.push_back(f); // 打开成功但源无实体 → 降级报告,非失败
} else {
fail_import.push_back(f);
}
} catch (const std::exception& e) {
fail_import.push_back(f + " (" + e.what() + ")");
} catch (...) {
fail_import.push_back(f + " (unknown exception)");
}
}
std::cerr << "[realfile] total=" << total
<< " 导入率 " << imported << "/" << total
<< " 修复率 " << healed << "/" << imported
<< " 验证率 " << validated << "/" << imported
<< " (空壳源 " << empty_sources.size() << " 个: 打开成功、源无实体几何, 已降级非失败; "
<< "跳过 " << skipped_large << " 个大文件, "
<< skipped_budget << " 个超预算)" << "\n";
const size_t kMaxList = 30;
size_t shown = 0;
for (const auto& s : fail_import) {
if (shown >= kMaxList) break;
std::cerr << " [import] " << s << "\n";
++shown;
}
if (fail_import.size() > shown)
std::cerr << " ... 另有 " << (fail_import.size() - shown)
<< " 个导入失败未列出\n";
shown = 0;
for (const auto& s : fail_heal) {
if (shown >= kMaxList) break;
std::cerr << " [heal] " << s << "\n";
++shown;
}
shown = 0;
for (const auto& s : empty_sources) {
if (shown >= kMaxList) break;
std::cerr << " [empty] " << s << "\n";
++shown;
}
shown = 0;
for (const auto& s : fail_valid) {
if (shown >= kMaxList) break;
auto it = residual_by_file.find(s);
std::cerr << " [valid] " << s;
if (it != residual_by_file.end())
std::cerr << " (" << it->second << ")";
std::cerr << "\n";
++shown;
}
if (skipped_large > 0) {
std::cerr << " [too_large] 共 " << skipped_large << " 个文件 > "
<< kRealfileMaxMB << "MB 未纳入统计,示例:" << "\n";
shown = 0;
for (const auto& s : too_large) {
if (shown >= 10) break;
std::cerr << " " << s << "\n";
++shown;
}
}
if (skipped_budget > 0) {
std::cerr << " [budget] 达到全局时间预算,提前结束,剩余 "
<< skipped_budget << " 个文件未处理\n";
}
if (total > 0) {
EXPECT_GT(imported, 0) << "realfile 所有真实模型均导入失败";
}
// Phase 1 失败清单落盘(免重编译诊断):VDE_REAL_FAIL_LIST=<path>
// 日志仅打印前 30 条,全量名单写文件便于逐模型归类(A/B/C/D 分类)。
if (const char* fl = std::getenv("VDE_REAL_FAIL_LIST")) {
std::ofstream ofs(fl, std::ios::binary);
if (ofs) {
for (const auto& s : fail_import) ofs << "[import]\t" << s << "\n";
for (const auto& s : fail_heal) ofs << "[heal]\t" << s << "\n";
for (const auto& s : empty_sources) ofs << "[empty]\t" << s << "\n";
for (const auto& s : fail_valid) {
ofs << "[valid]\t" << s;
auto it = residual_by_file.find(s);
if (it != residual_by_file.end())
ofs << "\t" << it->second;
ofs << "\n";
}
}
}
}
// ═══════════════════════════════════════════════════════════
// H1: 真实模型 corner_blend 通过率基准(M5/M6 语料验收)
// 对 realfile 每个 ≤5MB STEP 模型导入+修复后,抽样若干条边做
// corner_blend(半径 ∝ 模型尺度),统计边级/模型级通过率并输出。
// "通过" = 产物面数增加(未回退原体)且 validate() 拓扑有效。
// 首次运行记录基线(打印到 stderr);断言仅要求至少 1 条边成功,
// 避免因真实几何退化(孔/多环面/非流形)而脆断。
// ═══════════════════════════════════════════════════════════
TEST(ModelCorpus, RealFileCornerBlendPassRate) {
const int kMaxEdgesPerModel = 6; // 每模型抽样边数
const int kMaxFacesPerModel = 1500; // 大面数模型 blend 全量复制过慢,跳过
// 语料:realfile(用户交付,全量)+ corpus/real(M5/M6 3800+,抽样 40)
// + VDE_REAL_BATCH_DIR(新投放批次,抽样上限 VDE_REAL_BATCH_MAX)
std::vector<std::pair<std::string, int>> dirs = {
{TEST_REALFILE_DIR, 100000},
{TEST_REAL_CORPUS_DIR, 40},
};
std::string batch = realfile_batch_dir();
if (!batch.empty()) dirs.push_back({batch, realfile_batch_max()});
int models = 0, models_ok = 0;
int edges_total = 0, edges_ok = 0, edges_wt = 0;
int skipped_large = 0, skipped_budget = 0, skipped_faces = 0;
std::vector<std::string> fail_models;
auto t_start = std::chrono::steady_clock::now();
double elapsed_sec = 0.0;
for (const auto& d : dirs) {
std::vector<std::string> files;
collect_files(d.first, files);
int processed = 0;
for (const auto& f : files) {
auto ext = extension_lower(f);
if (ext != ".step" && ext != ".stp" && ext != ".p21") continue;
if (processed >= d.second) break;
++processed;
elapsed_sec = std::chrono::duration<double>(
std::chrono::steady_clock::now() - t_start).count();
if (elapsed_sec > realfile_budget_sec()) { ++skipped_budget; continue; }
long long sz = file_size_bytes(f);
if (sz > static_cast<long long>(kRealfileMaxMB * 1024 * 1024)) {
++skipped_large; continue;
}
std::vector<BrepModel> imported;
try { imported = import_step(f); } catch (...) { continue; }
if (imported.empty()) continue;
std::vector<BrepModel> mset;
for (auto& m0 : imported) {
BrepModel m = m0;
try { (void)automatic_heal(m); } catch (...) { continue; }
if (static_cast<int>(m.num_faces()) > kMaxFacesPerModel) {
++skipped_faces; continue;
}
mset.push_back(std::move(m));
}
if (mset.empty()) continue;
++models;
bool model_ok = false;
for (auto& m : mset) {
if (m.num_edges() < 3) continue;
auto bb = m.bounds();
double scale = (bb.max() - bb.min()).norm();
if (!(scale > 1e-6)) continue;
double r = 0.01 * scale;
if (r > 0.5) r = 0.5; // 上限防大半径自交
int ne = static_cast<int>(m.num_edges());
int step = std::max(1, ne / kMaxEdgesPerModel);
for (int ei = 0; ei < ne && ei / step < kMaxEdgesPerModel; ei += step) {
++edges_total;
BrepModel res;
try {
res = corner_blend(m, {ei}, r);
} catch (...) { continue; }
if (res.num_faces() <= m.num_faces()) continue; // 回退原体
auto vr = validate(res);
if (!vr.valid) continue;
++edges_ok;
if (vr.watertightness > 0.99) ++edges_wt;
model_ok = true;
}
}
if (model_ok) ++models_ok; else fail_models.push_back(f);
}
}
std::cerr << "[realfile corner_blend] 模型级 " << models_ok << "/" << models
<< " 边级 " << edges_ok << "/" << edges_total
<< " 边级水密(>0.99) " << edges_wt << "/" << edges_total
<< " (跳过 " << skipped_large << " 个大文件, "
<< skipped_faces << " 个高面数, " << skipped_budget << " 个超预算)\n";
const size_t kMaxList = 30;
size_t shown = 0;
for (const auto& s : fail_models) {
if (shown >= kMaxList) break;
std::cerr << " [no edge] " << s << "\n";
++shown;
}
if (fail_models.size() > shown)
std::cerr << " ... 另有 " << (fail_models.size() - shown)
<< " 个模型无成功边未列出\n";
if (edges_total > 0) {
EXPECT_GT(edges_ok, 0)
<< "corner_blend 对真实模型全部回退原体(通过率为 0,需排查)";
}
}
// ═══════════════════════════════════════════════════════════
// H2: 真实模型布尔通过率基准(31-追赶OCCT执行方案 Phase 0.2)
// 对 realfile + corpus/real 每个 ≤5MB STEP 模型:导入 → 逐实体 heal →
// 仅对 heal 后水密的实体做「中心 box 交集」(工具盒 = 0.5×包围盒,
// 位于包围盒中心,裁剪布尔会实际触发 SSI 求交),结果 validate 有效
// 且面数增加记为成功。布尔鲁棒性是相对 OCCT 的核心差距(30-严谨差距
// 分析.md:布尔专项测试 20 vs 5,000+),此测试给出真实数据上的通过率。
// 断言仅要求至少 1 个模型布尔成功,避免真实脏数据导致脆断;失败明细
// 输出到 stderr 供逐模型收敛(Phase 1)。
// ═══════════════════════════════════════════════════════════
TEST(ModelCorpus, RealFileBooleanPassRate) {
const int kMaxModelsPerDir = 25; // corpus/real(3800+)抽样上限
const int kMaxFacesPerModel = 1500; // 大面数模型布尔过慢,跳过
const double kToolRel = 0.5; // 工具盒边长 = 该轴包围盒尺寸 × 此比例
// 语料:realfile(全量)+ corpus/real(抽样 25)+ VDE_REAL_BATCH_DIR(新批次,上限 VDE_REAL_BATCH_MAX)
std::vector<std::pair<std::string, int>> dirs = {
{TEST_REALFILE_DIR, 100000},
{TEST_REAL_CORPUS_DIR, kMaxModelsPerDir},
};
std::string batch = realfile_batch_dir();
if (!batch.empty()) dirs.push_back({batch, realfile_batch_max()});
int models = 0, models_ok = 0; // 模型级:含水密实体的模型 / 至少一次布尔成功
int solids_total = 0, solids_ok = 0; // 实体级:水密实体数 / 布尔成功数
int skipped_large = 0, skipped_budget = 0, skipped_faces = 0, skipped_open = 0;
std::vector<std::string> fail_models;
auto t_start = std::chrono::steady_clock::now();
double elapsed_sec = 0.0;
for (const auto& d : dirs) {
std::vector<std::string> files;
collect_files(d.first, files);
int processed = 0;
for (const auto& f : files) {
auto ext = extension_lower(f);
if (ext != ".step" && ext != ".stp" && ext != ".p21") continue;
if (processed >= d.second) break;
++processed;
elapsed_sec = std::chrono::duration<double>(
std::chrono::steady_clock::now() - t_start).count();
if (elapsed_sec > realfile_budget_sec()) { ++skipped_budget; continue; }
long long sz = file_size_bytes(f);
if (sz > static_cast<long long>(kRealfileMaxMB * 1024 * 1024)) {
++skipped_large; continue;
}
std::vector<BrepModel> imported;
try { imported = import_step(f); } catch (...) { continue; }
if (imported.empty()) continue;
std::vector<BrepModel> mset;
for (auto& m0 : imported) {
BrepModel m = m0;
try { (void)automatic_heal(m); } catch (...) { continue; }
if (static_cast<int>(m.num_faces()) > kMaxFacesPerModel) {
++skipped_faces; continue;
}
mset.push_back(std::move(m));
}
if (mset.empty()) continue;
bool solid_seen = false, model_ok = false;
for (auto& m : mset) {
// 布尔仅对水密实体有定义语义:先验证,非水密(开面壳/缝隙)跳过
auto v0 = validate(m);
if (!(v0.valid && v0.watertightness > 0.99)) { ++skipped_open; continue; }
solid_seen = true;
auto bb = m.bounds();
auto mn = bb.min(), mx = bb.max();
Vector3D e = mx - mn;
if (!(e.x() > 1e-9 && e.y() > 1e-9 && e.z() > 1e-9)) continue; // NaN/退化
Point3D c((mn.x() + mx.x()) * 0.5,
(mn.y() + mx.y()) * 0.5,
(mn.z() + mx.z()) * 0.5);
++solids_total;
BrepModel tool = make_box(e.x() * kToolRel, e.y() * kToolRel,
e.z() * kToolRel, c);
BrepModel res;
try { res = brep_intersection(m, tool); }
catch (...) { continue; }
if (res.num_faces() <= 0) continue;
auto vr = validate(res);
if (!(vr.valid && vr.watertightness > 0.99)) continue;
++solids_ok;
model_ok = true;
}
if (!solid_seen) continue;
++models;
if (model_ok) ++models_ok; else fail_models.push_back(f);
}
}
std::cerr << "[realfile boolean] 模型级 " << models_ok << "/" << models
<< " 实体级 " << solids_ok << "/" << solids_total
<< " (跳过 " << skipped_large << " 个大文件, "
<< skipped_faces << " 个高面数, " << skipped_open
<< " 个非水密实体, " << skipped_budget << " 个超预算)\n";
const size_t kMaxList = 30;
size_t shown = 0;
for (const auto& s : fail_models) {
if (shown >= kMaxList) break;
std::cerr << " [no boolean] " << s << "\n";
++shown;
}
if (fail_models.size() > shown)
std::cerr << " ... 另有 " << (fail_models.size() - shown)
<< " 个模型无成功布尔未列出\n";
if (models > 0) {
EXPECT_GT(models_ok, 0)
<< "布尔对真实水密实体全部失败(通过率为 0,需排查 SSI/布尔链路)";
}
}
// ═══════════════════════════════════════════════════════════
// M1: 网格三格式导入率基线(STL / 3MF / GLB)
// 2026-09 用户新投放 ~30.5k 跨格式网格语料(corpus/stl|3mf|glb,同模型族
// 的 STL/3MF/GLB 三表达)。只评导入率——网格格式无 heal/validate 语义,
// 与 31 文档中 STEP 三率口径区分(跨格式比对:同 ID 在 STEP 侧失败而网格
// 侧可导 = 网格导入不是瓶颈的旁证)。
// 运行方式(避免污染 AllFilesImportWithoutCrash 的 fixture 统计):
// VDE_MESH_BATCH_DIR="<abs>/corpus/stl;<abs>/corpus/3mf;<abs>/corpus/glb"
// VDE_CORPUS_FAIL_LIST="<abs>/mesh_fail.txt"
// test_model_corpus --gtest_filter=ModelCorpus.MeshImportRateBaseline
// 输出 [mesh3] 逐格式导入率 + 失败模式分类(异常前缀 Top-N)。
// ═══════════════════════════════════════════════════════════
TEST(ModelCorpus, MeshImportRateBaseline) {
const char* env_dirs = std::getenv("VDE_MESH_BATCH_DIR");
if (!env_dirs || !*env_dirs) {
GTEST_SKIP() << "VDE_MESH_BATCH_DIR 未设置,跳过网格三格式导入率基线";
}
const double budget_sec = mesh_budget_sec();
const double max_mb = mesh_max_mb();
const std::string fail_list_path =
std::getenv("VDE_CORPUS_FAIL_LIST") ? std::getenv("VDE_CORPUS_FAIL_LIST")
: std::string();
std::vector<std::string> dirs = split_env_list(env_dirs, ';');
std::vector<std::string> files;
for (const auto& d : dirs) {
if (d.empty()) continue;
size_t before = files.size();
collect_files(d, files);
std::cerr << "[mesh3] dir " << d << " -> "
<< (files.size() - before) << " files\n";
}
if (files.empty()) {
GTEST_SKIP() << "VDE_MESH_BATCH_DIR 目录均为空,跳过";
}
std::map<std::string, FormatStats> stats;
auto init_stats = [](const char* name) {
FormatStats s; s.name = name; return s;
};
stats[".stl"] = init_stats("STL");
stats[".3mf"] = init_stats("3MF");
stats[".glb"] = init_stats("GLB"); stats[".gltf"] = init_stats("GLB");
// 失败名单落盘(免重编译分类失败模式;error 行附异常 what())
std::ofstream fail_list;
if (!fail_list_path.empty()) fail_list.open(fail_list_path, std::ios::binary);
// 失败模式分类:异常 what() 首段(到 ':'/ '(' / 引号 / 空白 为止)
auto exc_class = [](const std::string& w) {
std::string c;
for (char ch : w) {
if (ch == '(' || ch == ':' || ch == '"' ||
ch == '\r' || ch == '\n' || ch == '\t') break;
c.push_back(ch);
}
while (!c.empty() && c.back() == ' ') c.pop_back();
if (c.size() > 48) c.resize(48);
return c;
};
std::map<std::string, int> exc_counts;
int skipped_large = 0, skipped_budget = 0;
auto t_start = std::chrono::steady_clock::now();
for (const auto& f : files) {
const std::string ext = extension_lower(f);
if (!is_known_format(ext)) continue;
if (stats.find(ext) == stats.end()) continue; // 只统计本基线格式
const double elapsed = std::chrono::duration<double>(
std::chrono::steady_clock::now() - t_start).count();
if (elapsed > budget_sec) { ++skipped_budget; continue; }
const long long sz = file_size_bytes(f);
if (sz > static_cast<long long>(max_mb * 1024 * 1024)) {
++skipped_large;
continue;
}
auto& st = stats[ext];
++st.total;
try {
if (import_by_format(f, ext)) {
++st.ok;
} else {
++st.empty;
st.failed_files.push_back(f);
if (fail_list) fail_list << "[empty]\t" << f << "\n";
}
} catch (const std::exception& e) {
++st.error;
st.error_files.push_back(f);
const std::string cls = exc_class(e.what());
if (fail_list) fail_list << "[error]\t" << f << "\t" << e.what() << "\n";
++exc_counts[cls.empty() ? "(empty-what)" : cls];
} catch (...) {
++st.error;
st.error_files.push_back(f);
if (fail_list) fail_list << "[error]\t" << f << "\t(unknown exception)\n";
++exc_counts["(unknown exception)"];
}
}
if (fail_list) fail_list.close();
// 汇总:按格式打印(与 AllFilesImportWithoutCrash 相同口径)
int total = 0, ok = 0;
for (auto& kv : stats) { total += kv.second.total; ok += kv.second.ok; }
std::cerr << "[mesh3] " << ok << "/" << total << " imported"
<< " (跳过 " << skipped_large << " 个大文件, "
<< skipped_budget << " 个超预算)\n";
std::map<std::string, FormatStats> merged;
for (auto& kv : stats) {
if (kv.second.total == 0) continue;
auto& m = merged[kv.second.name];
m.name = kv.second.name;
m.total += kv.second.total;
m.ok += kv.second.ok;
m.empty += kv.second.empty;
m.error += kv.second.error;
m.failed_files.insert(m.failed_files.end(),
kv.second.failed_files.begin(), kv.second.failed_files.end());
m.error_files.insert(m.error_files.end(),
kv.second.error_files.begin(), kv.second.error_files.end());
}
for (auto& kv : merged) kv.second.report();
if (!exc_counts.empty()) {
std::cerr << "[mesh3] 失败模式分类(异常 what() 前缀 Top-10):\n";
size_t n = 0;
for (const auto& kv : exc_counts) {
if (n >= 10) break;
std::cerr << " " << kv.second << "x " << kv.first << "\n";
++n;
}
}
if (skipped_budget > 0)
std::cerr << "[mesh3] 达到全局时间预算(" << budget_sec << "s),剩余 "
<< skipped_budget << " 个文件未处理(可调 VDE_MESH_BUDGET_SEC)\n";
if (!fail_list_path.empty())
std::cerr << "[mesh3] 全量失败名单已写 " << fail_list_path << "\n";
// 断言:各格式至少成功导入 1 个(整格式导入器失效时响亮失败)
for (auto& kv : merged) {
SCOPED_TRACE("格式 " + kv.second.name);
EXPECT_GT(kv.second.ok, 0)
<< "格式 " << kv.second.name << " 全部导入失败,共 "
<< kv.second.total << " 个文件";
}
}