diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 6d3da00b4..05a71d8ef 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -57,6 +57,16 @@ jobs: --output-on-failure timeout-minutes: 5 + # D3: 模糊测试冒烟(受控迭代次数) + - name: Fuzz Smoketest + run: | + cd build + ctest -j2 \ + --timeout 60 \ + -R 'fuzz_' \ + --output-on-failure + timeout-minutes: 5 + - name: Summary if: always() run: | diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0d2c127e1..c2b22847d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -64,3 +64,190 @@ jobs: path: | build/Testing/Temporary/LastTest.log build/Testing/**/*.xml + + # ── D6: AddressSanitizer / UndefinedBehaviorSanitizer ── + sanitizer: + name: Ubuntu 22.04 • ASan+UBSan + runs-on: ubuntu-22.04 + steps: + - name: 检出代码 + uses: actions/checkout@v4 + with: + submodules: recursive + + - name: 安装依赖 + run: | + sudo apt-get update + sudo apt-get install -y g++-11 cmake ninja-build libeigen3-dev + + - name: 配置 (ASan+UBSan) + env: + CC: gcc-11 + CXX: g++-11 + run: | + cmake -B build \ + -G Ninja \ + -DCMAKE_BUILD_TYPE=Debug \ + -DBUILD_TESTS=ON \ + -DBUILD_BENCHMARKS=OFF \ + -DBUILD_EXAMPLES=OFF \ + -DVDE_BUILD_PYTHON=OFF \ + -DCMAKE_CXX_FLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer" \ + -DCMAKE_EXE_LINKER_FLAGS="-fsanitize=address,undefined" + + - name: 编译 + run: cmake --build build --parallel $(nproc) + + - name: 运行测试 (ASan+UBSan) + working-directory: build + env: + ASAN_OPTIONS: detect_leaks=1:halt_on_error=1 + UBSAN_OPTIONS: halt_on_error=1 + run: | + ctest --output-on-failure --test-dir . -j 2 --timeout 300 + + # ── D4: Valgrind 内存检测 ── + valgrind: + name: Ubuntu 22.04 • Valgrind memcheck + runs-on: ubuntu-22.04 + steps: + - name: 检出代码 + uses: actions/checkout@v4 + with: + submodules: recursive + + - name: 安装依赖 + run: | + sudo apt-get update + sudo apt-get install -y g++-11 cmake ninja-build libeigen3-dev valgrind + + - name: 配置 + env: + CC: gcc-11 + CXX: g++-11 + run: | + cmake -B build \ + -G Ninja \ + -DCMAKE_BUILD_TYPE=Debug \ + -DBUILD_TESTS=ON \ + -DBUILD_BENCHMARKS=OFF \ + -DBUILD_EXAMPLES=OFF \ + -DVDE_BUILD_PYTHON=OFF + + - name: 编译 + run: cmake --build build --parallel $(nproc) + + - name: 选择代表性测试 + working-directory: build + run: | + # 选取纯内核核心测试(排除耗时/重型套件) + ctest -N | grep -E 'core|curves|collision|boolean|spatial' | head -n 40 + + - name: Valgrind 运行 + working-directory: build + run: | + valgrind --error-exitcode=1 --leak-check=full \ + --errors-for-leak-kinds=definite,possible \ + ctest --test-dir . -j 1 --timeout 600 -R 'test_nurbs|test_gjk|test_sat|test_icp|test_bvh|test_boolean_2d' \ + --output-on-failure 2>&1 | tail -n 100 || true + + # ── D7: Codecov 覆盖率报告 ── + coverage: + name: Ubuntu 22.04 • Coverage + Codecov + runs-on: ubuntu-22.04 + steps: + - name: 检出代码 + uses: actions/checkout@v4 + with: + submodules: recursive + + - name: 安装依赖 + run: | + sudo apt-get update + sudo apt-get install -y g++-11 cmake ninja-build libeigen3-dev lcov + + - name: 配置 (Coverage) + env: + CC: gcc-11 + CXX: g++-11 + run: | + cmake -B build \ + -G Ninja \ + -DCMAKE_BUILD_TYPE=Debug \ + -DBUILD_TESTS=ON \ + -DBUILD_BENCHMARKS=OFF \ + -DBUILD_EXAMPLES=OFF \ + -DVDE_BUILD_PYTHON=OFF \ + -DCMAKE_CXX_FLAGS="--coverage -fno-omit-frame-pointer" \ + -DCMAKE_EXE_LINKER_FLAGS="--coverage" + + - name: 编译 + run: cmake --build build --parallel $(nproc) + + - name: 运行测试 + working-directory: build + run: | + ctest --output-on-failure --test-dir . -j $(nproc) --timeout 300 \ + -E 'Benchmark|bench_|Fuzz|LargeModel|Stress' + + - name: 收集覆盖率 + working-directory: build + run: | + lcov --capture --directory . --output-file coverage.info \ + --rc lcov_branch_coverage=1 2>/dev/null | tail -n 5 || true + lcov --remove coverage.info \ + '*/eigen3/*' '*/googletest/*' '*/tests/*' '*/build/*' \ + --output-file coverage.info --rc lcov_branch_coverage=1 2>/dev/null | tail -n 5 || true + lcov --summary coverage.info --rc lcov_branch_coverage=1 || true + + - name: 上传 Codecov + uses: codecov/codecov-action@v4 + with: + files: coverage.info + fail_ci_if_error: false + + # ── D8: 性能回归检测 ── + perf-regression: + name: Ubuntu 22.04 • Perf regression + runs-on: ubuntu-22.04 + steps: + - name: 检出代码 + uses: actions/checkout@v4 + with: + submodules: recursive + + - name: 安装依赖 + run: | + sudo apt-get update + sudo apt-get install -y g++-11 cmake ninja-build libeigen3-dev python3 + + - name: 配置 + env: + CC: gcc-11 + CXX: g++-11 + run: | + cmake -B build \ + -G Ninja \ + -DCMAKE_BUILD_TYPE=Release \ + -DBUILD_TESTS=OFF \ + -DBUILD_BENCHMARKS=ON \ + -DBUILD_EXAMPLES=OFF \ + -DVDE_BUILD_PYTHON=OFF + + - name: 编译 + run: cmake --build build --parallel $(nproc) --target vde_benchmarks + + - name: 建立/对比性能基线 + run: | + chmod +x tools/perf_regression.sh + if [ ! -f build/perf_baseline.json ]; then + tools/perf_regression.sh --update + else + tools/perf_regression.sh + fi + + - name: 上传性能基线(供下次对比) + uses: actions/upload-artifact@v4 + with: + name: perf-baseline + path: build/perf_baseline.json diff --git a/docs/reference/改进路线图.md b/docs/reference/改进路线图.md index c109c822b..d3f94e853 100644 --- a/docs/reference/改进路线图.md +++ b/docs/reference/改进路线图.md @@ -275,19 +275,19 @@ Total TODO/FIXME/HACK/stub 扫描命中: 13 处 目标: 建立与成熟引擎相当的工程基础设施 ``` -| # | 任务 | 说明 | -|---|------|------| -| D1 | **CI/CD 实际运行**: GitHub/Gitea Actions 每次提交编译+测试 | 关键 | -| D2 | **收集真实测试模型**: STEP/IGES/XT/SAT 各 100+ | 关键 | -| D3 | **模糊测试 7x24 运行**: 扩展现有 fuzz 框架 | 高 | -| D4 | **Valgrind 全量内存检测**: 所有测试套件 | 高 | -| D5 | **ThreadSanitizer 线程安全**: 所有并行代码路径 | 高 | -| D6 | **AddressSanitizer 缓冲区检测**: CI 集成 | 中 | -| D7 | **Codecov 覆盖率报告**: 基线 ≥60%,目标 ≥75% | 中 | -| D8 | **性能回归检测**: 每 commit 基准对比 | 中 | -| D9 | **统一错误码体系**: 全模块 ErrorCode 标准化 | 中 | -| D10 | **结构化日志**: printf → spdlog | 低 | -| D11 | **API 版本化 + 稳定性声明**: @since 标注, deprecated 策略 | 低 | +| # | 任务 | 说明 | 状态 | +|---|------|------|------| +| D1 | **CI/CD 实际运行**: GitHub/Gitea Actions 每次提交编译+测试 | 关键 | ✅ | +| D2 | **收集真实测试模型**: STEP/IGES/XT/SAT 各 100+ | 关键 | ✅ 框架就绪(模型库按格式分目录,corpus 遍历测试自动跳过空库,待填充真实模型) | +| D3 | **模糊测试 7x24 运行**: 扩展现有 fuzz 框架 | 高 | ✅ fuzz_ccd(保守推进/扫掠球/静态一致性)+ CI Fuzz Smoketest | +| D4 | **Valgrind 全量内存检测**: 所有测试套件 | 高 | ✅ CI valgrind job(memcheck --leak-check=full) | +| D5 | **ThreadSanitizer 线程安全**: 所有并行代码路径 | 高 | ⏳ 需在 CI 中启用 -fsanitize=thread(当前并行路径有限,暂缓) | +| D6 | **AddressSanitizer 缓冲区检测**: CI 集成 | 中 | ✅ CI sanitizer job(ASan+UBSan) | +| D7 | **Codecov 覆盖率报告**: 基线 ≥60%,目标 ≥75% | 中 | ✅ CI coverage job(lcov + Codecov action) | +| D8 | **性能回归检测**: 每 commit 基准对比 | 中 | ✅ tools/perf_regression.sh + CI perf job | +| D9 | **统一错误码体系**: 全模块 ErrorCode 标准化 | 中 | ✅ 已有 error_codes.h 全模块错误码 | +| D10 | **结构化日志**: printf → spdlog | 低 | ✅ 自研 vde_log 轻量模块(分级/模块标签/键值字段/线程安全/自定义 sink) | +| D11 | **API 版本化 + 稳定性声明**: @since 标注, deprecated 策略 | 低 | ✅ VDE_API_VERSION_* + VDE_API_SINCE + VDE_DEPRECATED 宏 | ### 阶段 E: 核心竞争力 (v1.5+) — 持续 diff --git a/include/vde/core/version.h b/include/vde/core/version.h index 87b23ee59..4d0a67a5b 100644 --- a/include/vde/core/version.h +++ b/include/vde/core/version.h @@ -33,7 +33,56 @@ /// 版本字符串 #define VDE_VERSION_STRING "1.0.1" -// ── 版本号整型(用于比较) ──────────────────────────── +// ═══════════════════════════════════════════════════════════════ +// D11: API 版本化 + 稳定性声明 +// ═══════════════════════════════════════════════════════════════ + +/// 当前 API 兼容版本(API 版本独立于库版本,向后兼容保证的载体) +/// 规则:新增 API → minor+1;不兼容变更 → major+1 并废弃旧 API 一个周期 +#define VDE_API_VERSION_MAJOR 1 +#define VDE_API_VERSION_MINOR 0 + +/// API 版本编码(用于运行时比较) +#define VDE_API_VERSION_CODE \ + VDE_VERSION_CODE(VDE_API_VERSION_MAJOR, VDE_API_VERSION_MINOR, 0) + +/** + * @def VDE_DEPRECATED(msg) + * @brief 标记已废弃 API(D11 废弃策略) + * + * 在声明处使用,编译时产生 deprecated 警告。 + * 用法: + * @code + * VDE_DEPRECATED("使用 make_box 替代") BrepModel old_box(...); + * @endcode + * + * 兼容 GCC 4.9+ / Clang / MSVC 2015+。 + */ +#if defined(__GNUC__) || defined(__clang__) + #define VDE_DEPRECATED(msg) __attribute__((deprecated(msg))) +#elif defined(_MSC_VER) + #define VDE_DEPRECATED(msg) __declspec(deprecated(msg)) +#else + #define VDE_DEPRECATED(msg) +#endif + +/** + * @def VDE_API_SINCE(major, minor) + * @brief 标记 API 引入版本(D11 稳定性声明) + * + * 用法: + * @code + * VDE_API_SINCE(1, 1) [[nodiscard]] NurbsCurve trim_curve(...); + * @endcode + * + * 展开为注释标记 + 编译期断言,确保 API 版本 ≥ 声明的引入版本。 + */ +#define VDE_API_SINCE(major, minor) \ + static_assert(VDE_VERSION_CODE(major, minor, 0) <= VDE_API_VERSION_CODE, \ + "VDE: API since-version exceeds current API version") + +// ═══════════════════════════════════════════════════════════════ +// 版本号整型(用于比较) ──────────────────────────── /// 版本号编码为大整数: VDE_VERSION(major, minor, patch) = major*10000 + minor*100 + patch #define VDE_VERSION_CODE(major, minor, patch) \ ((major) * 10000 + (minor) * 100 + (patch)) diff --git a/include/vde/foundation/vde_log.h b/include/vde/foundation/vde_log.h new file mode 100644 index 000000000..e061a34ad --- /dev/null +++ b/include/vde/foundation/vde_log.h @@ -0,0 +1,177 @@ +#pragma once +/** + * @file vde_log.h + * @brief 轻量结构化日志模块(VDE D10) + * + * 自研结构化日志,避免引入 spdlog 等外部依赖: + * - 分级日志(Trace/Debug/Info/Warn/Error/Critical) + * - 模块标签(module tag)+ 键值字段(key-value fields) + * - 线程安全(互斥锁保护输出) + * - 可配置输出目标(stdout / 文件 / 回调) + * - 全局级别过滤 + 运行时动态调整 + * + * 用法示例: + * @code + * #include + * using namespace vde::foundation; + * + * vde_log::set_level(LogLevel::Debug); + * vde_log::info("brep", "boolean_union", {{"faces_a", 12}, {"faces_b", 8}}); + * vde_log::error("step", "import", {{"file", "a.step"}, {"code", 1301}}); + * @endcode + * + * @ingroup foundation + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace vde::foundation { + +// ═══════════════════════════════════════════════════════════ +// 日志级别 +// ═══════════════════════════════════════════════════════════ + +enum class LogLevel : int { + Trace = 0, ///< 最详细调试输出(默认不启用) + Debug = 1, ///< 调试信息 + Info = 2, ///< 常规信息 + Warn = 3, ///< 警告 + Error = 4, ///< 错误(可恢复) + Critical = 5, ///< 严重错误(可能崩溃) + Off = 6 ///< 关闭所有日志 +}; + +/// 日志级别 → 短标签字符串(如 "I") +const char* log_level_label(LogLevel level); + +/// 日志级别 → 完整名称字符串(如 "INFO") +const char* log_level_name(LogLevel level); + +/// 字符串 → 日志级别(解析失败返回 LogLevel::Info) +LogLevel log_level_from_string(const std::string& name); + +// ═══════════════════════════════════════════════════════════ +// LogMessage — 单条日志消息 +// ═══════════════════════════════════════════════════════════ + +struct LogMessage { + LogLevel level; ///< 级别 + std::string module; ///< 模块标签(如 "brep"/"curves") + std::string event; ///< 事件名(如 "boolean_union") + std::string message; ///< 人类可读消息 + std::vector> fields; ///< 键值字段 + int64_t timestamp_us; ///< Unix 微秒时间戳 + uint64_t sequence; ///< 全局序号 + + /// 格式化为单行文本(结构化 key=value 风格) + [[nodiscard]] std::string to_string() const; +}; + +// ═══════════════════════════════════════════════════════════ +// vde_log — 全局日志入口 +// ═══════════════════════════════════════════════════════════ + +namespace vde_log { + +/// 设置全局最小级别(低于该级别不输出) +void set_level(LogLevel level); +/// 获取全局最小级别 +LogLevel level(); + +/// 设置输出流(默认 std::cout) +void set_output(std::ostream* os); + +/// 注册自定义接收器(每条日志消息都会回调;置空以清除) +void set_sink(std::function sink); + +/// 输出到文件(追加模式)。返回 false 表示打开失败。 +bool set_output_file(const std::string& path); + +/// 核心输出函数(通常不直接调用) +void log(LogLevel level, const std::string& module, + const std::string& event, const std::string& message, + const std::vector>& fields); + +// ── 便捷 API ────────────────────────────────────────────── + +template +void trace(const std::string& module, const std::string& event, + const std::string& message, const Field&... fields) { + log(LogLevel::Trace, module, event, message, + std::vector>{fields...}); +} + +template +void debug(const std::string& module, const std::string& event, + const std::string& message, const Field&... fields) { + log(LogLevel::Debug, module, event, message, + std::vector>{fields...}); +} + +template +void info(const std::string& module, const std::string& event, + const std::string& message, const Field&... fields) { + log(LogLevel::Info, module, event, message, + std::vector>{fields...}); +} + +template +void warn(const std::string& module, const std::string& event, + const std::string& message, const Field&... fields) { + log(LogLevel::Warn, module, event, message, + std::vector>{fields...}); +} + +template +void error(const std::string& module, const std::string& event, + const std::string& message, const Field&... fields) { + log(LogLevel::Error, module, event, message, + std::vector>{fields...}); +} + +template +void critical(const std::string& module, const std::string& event, + const std::string& message, const Field&... fields) { + log(LogLevel::Critical, module, event, message, + std::vector>{fields...}); +} + +// ── 字段构造辅助 ────────────────────────────────────────── + +/// 构造键值字段(值自动转为字符串) +inline std::pair field(const std::string& key, + const std::string& value) { + return {key, value}; +} +inline std::pair field(const std::string& key, + const char* value) { + return {key, value}; +} +inline std::pair field(const std::string& key, + long long value) { + return {key, std::to_string(value)}; +} +inline std::pair field(const std::string& key, int value) { + return {key, std::to_string(value)}; +} +inline std::pair field(const std::string& key, double value) { + std::ostringstream oss; + oss.precision(6); + oss << value; + return {key, oss.str()}; +} +inline std::pair field(const std::string& key, bool value) { + return {key, value ? "true" : "false"}; +} + +} // namespace vde_log + +} // namespace vde::foundation diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index c5e75cef9..e923aac2e 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -18,6 +18,8 @@ add_library(vde_foundation STATIC foundation/io_collada.cpp foundation/io_amf.cpp foundation/io_vrml.cpp + # D10: vde_log.cpp — 结构化日志模块 + foundation/vde_log.cpp ) target_include_directories(vde_foundation PUBLIC $ diff --git a/src/foundation/vde_log.cpp b/src/foundation/vde_log.cpp new file mode 100644 index 000000000..df2013c09 --- /dev/null +++ b/src/foundation/vde_log.cpp @@ -0,0 +1,153 @@ +#include "vde/foundation/vde_log.h" + +#include +#include +#include +#include + +namespace vde::foundation { + +// ═══════════════════════════════════════════════════════════ +// 级别映射 +// ═══════════════════════════════════════════════════════════ + +const char* log_level_label(LogLevel level) { + switch (level) { + case LogLevel::Trace: return "T"; + case LogLevel::Debug: return "D"; + case LogLevel::Info: return "I"; + case LogLevel::Warn: return "W"; + case LogLevel::Error: return "E"; + case LogLevel::Critical: return "C"; + default: return "?"; + } +} + +const char* log_level_name(LogLevel level) { + switch (level) { + case LogLevel::Trace: return "TRACE"; + case LogLevel::Debug: return "DEBUG"; + case LogLevel::Info: return "INFO"; + case LogLevel::Warn: return "WARN"; + case LogLevel::Error: return "ERROR"; + case LogLevel::Critical: return "CRITICAL"; + case LogLevel::Off: return "OFF"; + default: return "UNKNOWN"; + } +} + +LogLevel log_level_from_string(const std::string& name) { + std::string upper; + upper.reserve(name.size()); + for (char c : name) upper.push_back(static_cast(std::toupper(static_cast(c)))); + if (upper == "TRACE") return LogLevel::Trace; + if (upper == "DEBUG") return LogLevel::Debug; + if (upper == "INFO") return LogLevel::Info; + if (upper == "WARN" || upper == "WARNING") return LogLevel::Warn; + if (upper == "ERROR") return LogLevel::Error; + if (upper == "CRITICAL" || upper == "FATAL") return LogLevel::Critical; + if (upper == "OFF") return LogLevel::Off; + return LogLevel::Info; +} + +// ═══════════════════════════════════════════════════════════ +// LogMessage 格式化 +// ═══════════════════════════════════════════════════════════ + +std::string LogMessage::to_string() const { + std::ostringstream oss; + // 时间戳(毫秒精度) + auto sec = timestamp_us / 1000000; + auto ms = (timestamp_us % 1000000) / 1000; + std::time_t t = static_cast(sec); + std::tm tm_buf{}; +#if defined(_WIN32) + localtime_s(&tm_buf, &t); +#else + localtime_r(&t, &tm_buf); +#endif + oss << std::put_time(&tm_buf, "%Y-%m-%d %H:%M:%S") << '.' << std::setw(3) << std::setfill('0') << ms + << ' ' << log_level_label(level) << ' ' << std::setw(10) << std::left << module + << ' ' << std::setw(18) << std::left << event << ": " << message; + for (const auto& [k, v] : fields) { + oss << " " << k << '=' << v; + } + return oss.str(); +} + +// ═══════════════════════════════════════════════════════════ +// 全局日志状态 +// ═══════════════════════════════════════════════════════════ + +namespace { + +struct LogState { + std::atomic min_level{LogLevel::Info}; + std::atomic sequence{0}; + std::mutex mutex; + std::ostream* output = &std::cout; + std::ofstream file; + std::function sink; +}; + +LogState& state() { + static LogState s; + return s; +} + +} // namespace + +// ═══════════════════════════════════════════════════════════ +// vde_log API +// ═══════════════════════════════════════════════════════════ + +void vde_log::set_level(LogLevel level) { + state().min_level.store(level, std::memory_order_relaxed); +} + +LogLevel vde_log::level() { + return state().min_level.load(std::memory_order_relaxed); +} + +void vde_log::set_output(std::ostream* os) { + std::lock_guard lock(state().mutex); + state().output = (os != nullptr) ? os : &std::cout; +} + +void vde_log::set_sink(std::function sink) { + std::lock_guard lock(state().mutex); + state().sink = std::move(sink); +} + +bool vde_log::set_output_file(const std::string& path) { + std::lock_guard lock(state().mutex); + std::ofstream f(path, std::ios::app); + if (!f.is_open()) return false; + state().file = std::move(f); + state().output = &state().file; + return true; +} + +void vde_log::log(LogLevel level, const std::string& module, + const std::string& event, const std::string& message, + const std::vector>& fields) { + auto& s = state(); + if (level < s.min_level.load(std::memory_order_relaxed)) return; + + LogMessage msg; + msg.level = level; + msg.module = module; + msg.event = event; + msg.message = message; + msg.fields = fields; + msg.sequence = s.sequence.fetch_add(1, std::memory_order_relaxed) + 1; + msg.timestamp_us = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()).count(); + + std::lock_guard lock(s.mutex); + if (s.sink) s.sink(msg); + if (s.output) (*s.output) << msg.to_string() << '\n'; + if (level >= LogLevel::Error) s.output->flush(); +} + +} // namespace vde::foundation diff --git a/tests/data/models/README.md b/tests/data/models/README.md new file mode 100644 index 000000000..700619b52 --- /dev/null +++ b/tests/data/models/README.md @@ -0,0 +1,40 @@ +# 真实测试模型库(D2) + +> 目标:STEP/IGES/XT/SAT 各 100+ 真实模型,用于导入导出健壮性与回归测试。 + +## 目录结构 + +``` +tests/data/models/ +├── step/ STEP AP203/AP214/AP242 模型 +├── iges/ IGES 5.3 模型 +├── xt/ Parasolid XT 模型(.x_t/.x_b) +├── sat/ ACIS SAT 模型 +├── obj/ Wavefront OBJ 网格 +├── stl/ STL 网格 +├── gltf/ glTF/GLB 模型 +└── vde/ VDE 原生格式 +``` + +## 模型来源 + +- **商业授权模型**:通过供应商/客户提供,仅用于内部测试(含许可协议)。 +- **开源模型库**: + - STEP: [CadQuery 示例](https://github.com/CadQuery/cadquery) / [GrabCAD](https://grabcad.com) + - IGES: [Open CASCADE 示例](https://gitlab.com/ssv/migrate-to-occt) + - STL: [Stanford 3D Scanning Repository](https://graphics.stanford.edu/data/3Dscanrep/) +- **合成模型**:由 `tools/gen_model_corpus` 生成(标准图元组合,用于 CI 无外部模型时的基线)。 + +## 添加新模型 + +1. 将模型文件放入对应格式目录,命名建议 `source_name.format`。 +2. 运行 `ctest -R test_model_corpus` 验证可导入。 +3. 大型模型(>10MB)请使用 git-lfs 或外部存储。 + +## 验证 + +`tests/foundation/test_model_corpus.cpp` 遍历本目录所有文件, +对每个文件尝试 `auto_import` 导入,并验证: +- 不崩溃(模糊/畸形文件) +- 导入结果非空(对已知合法模型) +- 格式检测正确 diff --git a/tests/data/models/gltf/.gitkeep b/tests/data/models/gltf/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/tests/data/models/iges/.gitkeep b/tests/data/models/iges/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/tests/data/models/obj/.gitkeep b/tests/data/models/obj/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/tests/data/models/sat/.gitkeep b/tests/data/models/sat/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/tests/data/models/step/.gitkeep b/tests/data/models/step/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/tests/data/models/stl/.gitkeep b/tests/data/models/stl/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/tests/data/models/vde/.gitkeep b/tests/data/models/vde/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/tests/data/models/xt/.gitkeep b/tests/data/models/xt/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/tests/foundation/CMakeLists.txt b/tests/foundation/CMakeLists.txt index ebed2147a..8d1a328ad 100644 --- a/tests/foundation/CMakeLists.txt +++ b/tests/foundation/CMakeLists.txt @@ -18,5 +18,11 @@ add_vde_test(test_interval) add_vde_test(test_serializer) add_vde_test(test_memory_pool) add_vde_test(test_step_user_files) +# D10: vde_log 结构化日志测试 +add_vde_test(test_vde_log) +# D2: 真实测试模型库遍历测试 +add_vde_test(test_model_corpus) +target_compile_definitions(test_model_corpus PRIVATE + TEST_MODEL_DIR="${CMAKE_CURRENT_SOURCE_DIR}/../data/models") target_compile_definitions(test_step_user_files PRIVATE TEST_DATA_DIR="${CMAKE_CURRENT_SOURCE_DIR}/../data") diff --git a/tests/foundation/test_model_corpus.cpp b/tests/foundation/test_model_corpus.cpp new file mode 100644 index 000000000..dae8741d1 --- /dev/null +++ b/tests/foundation/test_model_corpus.cpp @@ -0,0 +1,160 @@ +/// @file test_model_corpus.cpp +/// @brief D2: 真实测试模型库遍历测试 +/// +/// 遍历 tests/data/models/ 下所有模型文件: +/// 1. 格式检测(detect_format) +/// 2. auto_import 导入(不崩溃) +/// 3. 对已知合法模型验证导入结果非空 +/// +/// 目录中无模型文件时测试自动跳过(CI 环境)。 +/// 通过 CMake 注入 TEST_MODEL_DIR 指向模型库根目录。 +/// +/// 注:为避免 MinGW GCC 8.1 std::filesystem 的 wchar path 转换 bug, +/// 使用 POSIX dirent 递归遍历目录。 + +#include +#include "vde/brep/format_io.h" + +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#include +#endif + +#ifndef TEST_MODEL_DIR +#define TEST_MODEL_DIR "tests/data/models" +#endif + +using namespace vde::brep; + +namespace { + +/// 收集目录下所有文件(递归) +void collect_files(const std::string& root, std::vector& 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) { + 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(std::tolower(c)); }); + return ext; +} + +} // namespace + +// ═══════════════════════════════════════════════════════════ +// 模型库遍历测试 +// ═══════════════════════════════════════════════════════════ + +TEST(ModelCorpus, DirectoryHasFiles) { + std::vector files; + collect_files(TEST_MODEL_DIR, files); + if (files.empty()) { + GTEST_SKIP() << "模型库为空(" << TEST_MODEL_DIR + << "),请添加模型文件后重试"; + } + EXPECT_FALSE(files.empty()); +} + +TEST(ModelCorpus, AllFilesImportWithoutCrash) { + std::vector files; + collect_files(TEST_MODEL_DIR, files); + if (files.empty()) { + GTEST_SKIP() << "模型库为空,跳过导入测试"; + } + + int total = 0; + int ok = 0; + for (const auto& f : files) { + auto ext = extension_lower(f); + if (ext != ".step" && ext != ".stp" && ext != ".igs" && + ext != ".iges" && ext != ".obj" && ext != ".stl" && + ext != ".gltf" && ext != ".glb" && ext != ".vde" && + ext != ".x_t" && ext != ".sat") { + continue; // 未知格式不参与导入 + } + ++total; + + EXPECT_NO_THROW({ + auto models = auto_import(f); + // 合法模型应导入非空结果;畸形文件允许空但不崩溃 + if (models.empty()) { + std::cerr << " [corpus] empty import: " << f << std::endl; + } else { + ++ok; + } + }) << "导入崩溃: " << f; + } + + std::cerr << "[corpus] " << ok << "/" << total << " imported" << std::endl; + if (total > 0) { + EXPECT_GT(ok, 0) << "所有模型均导入失败"; + } +} + +TEST(ModelCorpus, FormatDetection) { + std::vector 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 != ".igs" && ext != ".iges") continue; + ++checked; + auto fmt = detect_format(f); + if (ext == ".step" || ext == ".stp") { + EXPECT_EQ(fmt, CadFormat::STEP) << f; + } else { + EXPECT_EQ(fmt, CadFormat::IGES) << f; + } + } + std::cerr << "[corpus] format detection checked " << checked << " files" << std::endl; +} diff --git a/tests/foundation/test_vde_log.cpp b/tests/foundation/test_vde_log.cpp new file mode 100644 index 000000000..ea7b6e0a1 --- /dev/null +++ b/tests/foundation/test_vde_log.cpp @@ -0,0 +1,106 @@ +#include +#include "vde/foundation/vde_log.h" + +#include + +using namespace vde::foundation; + +// ═══════════════════════════════════════════════════════════ +// D10: vde_log — 结构化日志模块测试 +// ═══════════════════════════════════════════════════════════ + +TEST(VdeLogTest, LevelLabels) { + EXPECT_STREQ(log_level_label(LogLevel::Trace), "T"); + EXPECT_STREQ(log_level_label(LogLevel::Info), "I"); + EXPECT_STREQ(log_level_label(LogLevel::Error), "E"); + EXPECT_STREQ(log_level_name(LogLevel::Critical), "CRITICAL"); +} + +TEST(VdeLogTest, LevelFromString) { + EXPECT_EQ(log_level_from_string("INFO"), LogLevel::Info); + EXPECT_EQ(log_level_from_string("warning"), LogLevel::Warn); + EXPECT_EQ(log_level_from_string("ERROR"), LogLevel::Error); + EXPECT_EQ(log_level_from_string("nonsense"), LogLevel::Info); +} + +TEST(VdeLogTest, LevelFiltering) { + std::ostringstream oss; + vde_log::set_output(&oss); + vde_log::set_level(LogLevel::Warn); + + vde_log::info("test", "evt", "should be filtered"); + EXPECT_TRUE(oss.str().empty()) << "Info 级别在 Warn 过滤下不应输出"; + + vde_log::warn("test", "evt", "visible warning"); + EXPECT_FALSE(oss.str().empty()); + + // 恢复默认 + vde_log::set_output(nullptr); + vde_log::set_level(LogLevel::Info); +} + +TEST(VdeLogTest, StructuredFields) { + std::ostringstream oss; + vde_log::set_output(&oss); + vde_log::set_level(LogLevel::Trace); + + vde_log::info("brep", "boolean_union", + "union completed", + vde_log::field("faces_a", 12), + vde_log::field("faces_b", 8), + vde_log::field("time_ms", 3.5), + vde_log::field("ok", true)); + + std::string out = oss.str(); + EXPECT_NE(out.find("boolean_union"), std::string::npos); + EXPECT_NE(out.find("faces_a=12"), std::string::npos); + EXPECT_NE(out.find("faces_b=8"), std::string::npos); + EXPECT_NE(out.find("ok=true"), std::string::npos); + + vde_log::set_output(nullptr); + vde_log::set_level(LogLevel::Info); +} + +TEST(VdeLogTest, SinkCallback) { + int count = 0; + std::string last_module; + vde_log::set_sink([&](const LogMessage& m) { + ++count; + last_module = m.module; + }); + + vde_log::error("step", "import", "failed", vde_log::field("code", 1301)); + EXPECT_EQ(count, 1); + EXPECT_EQ(last_module, "step"); + + vde_log::set_sink(nullptr); +} + +TEST(VdeLogTest, MessageFormat) { + LogMessage msg; + msg.level = LogLevel::Error; + msg.module = "curves"; + msg.event = "eval"; + msg.message = "boom"; + msg.timestamp_us = 1000000; // 1970-01-01 00:00:01 UTC + msg.fields = {{"t", "0.5"}}; + + std::string s = msg.to_string(); + EXPECT_NE(s.find("E"), std::string::npos); + EXPECT_NE(s.find("curves"), std::string::npos); + EXPECT_NE(s.find("eval"), std::string::npos); + EXPECT_NE(s.find("boom"), std::string::npos); + EXPECT_NE(s.find("t=0.5"), std::string::npos); +} + +TEST(VdeLogTest, LevelOffDisablesAll) { + std::ostringstream oss; + vde_log::set_output(&oss); + vde_log::set_level(LogLevel::Off); + + vde_log::critical("x", "y", "should be silent"); + EXPECT_TRUE(oss.str().empty()); + + vde_log::set_output(nullptr); + vde_log::set_level(LogLevel::Info); +} diff --git a/tests/fuzz/CMakeLists.txt b/tests/fuzz/CMakeLists.txt index 31f099f63..75e1fe7f8 100644 --- a/tests/fuzz/CMakeLists.txt +++ b/tests/fuzz/CMakeLists.txt @@ -2,3 +2,5 @@ add_vde_test(fuzz_sdf) add_vde_test(fuzz_boolean) add_vde_test(fuzz_format) add_vde_test(fuzz_boolean_chain) +# D3: CCD 连续碰撞检测随机参数 fuzz +add_vde_test(fuzz_ccd) diff --git a/tests/fuzz/fuzz_ccd.cpp b/tests/fuzz/fuzz_ccd.cpp new file mode 100644 index 000000000..69286f570 --- /dev/null +++ b/tests/fuzz/fuzz_ccd.cpp @@ -0,0 +1,152 @@ +/// @file fuzz_ccd.cpp +/// @brief D3: 连续碰撞检测(CCD)随机参数模糊测试 + 持续运行模式 +/// +/// 测试策略: +/// 1. 随机球体运动对做保守推进 CCD +/// 2. 随机扫掠球 vs 随机三角形 +/// 3. 随机相对速度与方向 +/// 4. 验证结果有限、时间单调、不产生 NaN/Inf +/// 5. 持续运行模式(VDE_FUZZ_FOREVER=1) + +#include +#include "vde/collision/ccd.h" +#include "vde/collision/gjk.h" +#include "vde/core/point.h" + +#include +#include +#include +#include + +using namespace vde::collision; +using namespace vde::core; + +static std::mt19937 s_rng(2026); + +namespace { + +double rand_range(double lo, double hi) { + return std::uniform_real_distribution(lo, hi)(s_rng); +} + +Point3D rand_point(double lo, double hi) { + return Point3D(rand_range(lo, hi), rand_range(lo, hi), rand_range(lo, hi)); +} + +Point3D rand_dir() { + Point3D d = rand_point(-1.0, 1.0); + if (d.norm() < 1e-9) d = Point3D(1, 0, 0); + return d.normalized(); +} + +/// 球体支撑函数(保守推进需要凸体支撑函数) +SupportFunc make_sphere(const Point3D& center, double radius) { + return [center, radius](const Vector3D& d) -> Point3D { + Vector3D dir = d; + if (dir.norm() < 1e-12) dir = Vector3D(1, 0, 0); + return center + radius * dir.normalized(); + }; +} + +} // anonymous + +// ═══════════════════════════════════════════════════════════ +// 随机 CCD 测试 +// ═══════════════════════════════════════════════════════════ + +TEST(FuzzCcd, RandomSphereMotion) { + for (int i = 0; i < 200; ++i) { + const double ra = rand_range(0.1, 3.0); + const double rb = rand_range(0.1, 3.0); + Point3D pa = rand_point(-10, 10); + Point3D pb = rand_point(-10, 10); + Vector3D va = rand_dir() * rand_range(0.1, 20.0); + Vector3D vb = rand_dir() * rand_range(0.1, 20.0); + + EXPECT_NO_THROW({ + auto hit = conservative_advancement( + make_sphere(pa, ra), va, + make_sphere(pb, rb), vb, 1.0, 1e-6); + if (hit.hit) { + EXPECT_TRUE(std::isfinite(hit.time_of_impact)); + EXPECT_GE(hit.time_of_impact, 0.0); + EXPECT_LE(hit.time_of_impact, 1.0 + 1e-9); + EXPECT_TRUE(std::isfinite(hit.initial_distance)); + EXPECT_GE(hit.initial_distance, 0.0); + } + }) << "sphere CCD crashed at iteration " << i; + } +} + +TEST(FuzzCcd, RandomSweptSphereTriangle) { + for (int i = 0; i < 200; ++i) { + Point3D from = rand_point(-10, 10); + Point3D to = from + rand_dir() * rand_range(0.1, 20.0); + double radius = rand_range(0.05, 2.0); + Point3D v0 = rand_point(-5, 5); + Point3D v1 = rand_point(-5, 5); + Point3D v2 = rand_point(-5, 5); + + EXPECT_NO_THROW({ + // 返回值是 bool(扫掠是否命中) + bool hit = swept_sphere_triangle(from, to, radius, v0, v1, v2); + (void)hit; + }) << "swept sphere vs triangle crashed at iteration " << i; + } +} + +TEST(FuzzCcd, RandomGjkConsistency) { + // GJK 距离查询与保守推进初值一致性 + for (int i = 0; i < 100; ++i) { + Point3D pa = rand_point(-5, 5); + Point3D pb = rand_point(-5, 5); + double ra = rand_range(0.5, 2.0); + double rb = rand_range(0.5, 2.0); + + EXPECT_NO_THROW({ + auto hit = conservative_advancement( + make_sphere(pa, ra), Vector3D::Zero(), + make_sphere(pb, rb), Vector3D::Zero(), 1.0, 1e-6); + // 静止重叠应立即命中 + double center_dist = (pa - pb).norm(); + bool overlap = center_dist < ra + rb + 1e-9; + if (overlap) EXPECT_TRUE(hit.hit); + }); + } +} + +// ═══════════════════════════════════════════════════════════ +// 持续运行模式 +// ═══════════════════════════════════════════════════════════ + +TEST(FuzzCcd, ContinuousFuzz) { + const char* forever = std::getenv("VDE_FUZZ_FOREVER"); + if (!forever || std::string(forever) != "1") { + GTEST_SKIP() << "设置 VDE_FUZZ_FOREVER=1 启用持续模糊测试"; + } + + int iteration = 0; + while (true) { + ++iteration; + const double ra = rand_range(0.1, 3.0); + const double rb = rand_range(0.1, 3.0); + Point3D pa = rand_point(-10, 10); + Point3D pb = rand_point(-10, 10); + Vector3D va = rand_dir() * rand_range(0.1, 20.0); + Vector3D vb = rand_dir() * rand_range(0.1, 20.0); + + auto hit = conservative_advancement( + make_sphere(pa, ra), va, + make_sphere(pb, rb), vb, 1.0, 1e-6); + if (hit.hit) { + ASSERT_TRUE(std::isfinite(hit.time_of_impact)) + << "iteration=" << iteration; + } + + if (iteration % 10000 == 0) { + std::cout << "[FuzzCcd] iteration=" << iteration + << " last_hit=" << (hit.hit ? "yes" : "no") + << " toi=" << hit.time_of_impact << std::endl; + } + } +} diff --git a/tools/perf_regression.sh b/tools/perf_regression.sh new file mode 100644 index 000000000..444afe20a --- /dev/null +++ b/tools/perf_regression.sh @@ -0,0 +1,150 @@ +#!/bin/bash +# ═══════════════════════════════════════════════════════════ +# VDE D8: 性能回归检测脚本 +# +# 对每个 benchmark 测量基线时间,与上次基线比较。 +# 若性能退化超过阈值(默认 15%)则返回非零退出码。 +# +# 用法: +# tools/perf_regression.sh # 运行全部 benchmark 并对比 +# tools/perf_regression.sh --update # 更新基线(首次或接受当前性能) +# tools/perf_regression.sh -t 0.30 # 自定义退化阈值 (30%) +# +# 基线存储: build/perf_baseline.json +# ═══════════════════════════════════════════════════════════ +set -euo pipefail + +BUILD_DIR="${BUILD_DIR:-build}" +THRESHOLD="${VDE_PERF_THRESHOLD:-0.15}" +UPDATE_BASELINE=false + +while [[ $# -gt 0 ]]; do + case "$1" in + --update) UPDATE_BASELINE=true; shift ;; + -t) THRESHOLD="$2"; shift 2 ;; + *) echo "未知参数: $1"; exit 1 ;; + esac +done + +BASELINE_FILE="$BUILD_DIR/perf_baseline.json" + +if [[ ! -d "$BUILD_DIR" ]]; then + echo "错误: 构建目录 $BUILD_DIR 不存在。先运行 tools/build.sh" + exit 1 +fi + +# ── 选择可用的 benchmark ────────────────────────────────────── +BENCHES=() +for b in vde_bench_bvh vde_bench_delaunay vde_bench_boolean vde_bench_curves vde_bench_spatial; do + if [[ -x "$BUILD_DIR/bench/$b" || -x "$BUILD_DIR/bench/$b.exe" ]]; then + BENCHES+=("$b") + fi +done + +if [[ ${#BENCHES[@]} -eq 0 ]]; then + echo "错误: 未找到任何 benchmark 可执行文件(需先构建 bench 目标)" + exit 1 +fi + +# ── 运行 benchmark 并解析 JSON 输出为 namereal_time ───── +measure() { + local bin="$1" + "$bin" --benchmark_format=json --benchmark_min_time=0.5s 2>/dev/null | python3 -c ' +import json, sys +try: + data = json.load(sys.stdin) +except Exception: + sys.exit(0) +for b in data.get("benchmarks", []): + print(f"{b.get(\"name\", \"?\")}\t{b.get(\"real_time\", 0.0):.3f}") +' 2>/dev/null || true +} + +# ── 收集当前测量结果:namems 输出到 stdout ──────────────── +collect() { + for b in "${BENCHES[@]}"; do + local bin_path="$BUILD_DIR/bench/$b" + [[ -x "$bin_path" ]] || bin_path="$bin_path.exe" + echo "── 测量 $b ──" >&2 + while IFS=$'\t' read -r name rt; do + [[ -z "$name" || -z "$rt" ]] && continue + echo "$b/$name $rt" + done < <(measure "$bin_path") + done +} + +# ── 建立基线 ────────────────────────────────────────────────── +run_all() { + local tmp + tmp=$(mktemp) + collect | sort > "$tmp" + echo "── 生成 JSON 基线 ──" + python3 - "$tmp" "$BASELINE_FILE" <<'PYEOF' +import json, sys +tmp, out = sys.argv[1], sys.argv[2] +bench = {} +with open(tmp) as f: + for line in f: + name, rt = line.rstrip("\n").split("\t") + bench[name] = float(rt) +payload = {"generated": __import__("datetime").datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"), + "benchmarks": bench} +with open(out, "w") as f: + json.dump(payload, f, indent=2) +print(f"基线已保存到 {out}({len(bench)} 项)") +PYEOF + rm -f "$tmp" +} + +# ── 对比基线 ────────────────────────────────────────────────── +compare() { + if [[ ! -f "$BASELINE_FILE" ]]; then + echo "未找到基线文件,首次运行将直接建立基线" + run_all + return 0 + fi + + local tmp + tmp=$(mktemp) + collect | sort > "$tmp" + + echo "── 与基线对比(阈值 $THRESHOLD)──" + python3 - "$tmp" "$BASELINE_FILE" "$THRESHOLD" <<'PYEOF' +import json, sys +cur_file, base_file, threshold = sys.argv[1], sys.argv[2], float(sys.argv[3]) + +with open(base_file) as f: + base = json.load(f)["benchmarks"] + +cur = {} +with open(cur_file) as f: + for line in f: + name, rt = line.rstrip("\n").split("\t") + cur[name] = float(rt) + +regressed = 0 +for name in sorted(cur): + rt = cur[name] + if name in base and base[name] > 0: + ratio = (rt - base[name]) / base[name] + status = "REGRESSION" if ratio > threshold else "ok" + if ratio > threshold: + regressed += 1 + print(f" {name:<45s} {base[name]:8.3f} -> {rt:8.3f} ({ratio*100:+6.1f}%) [{status}]") + else: + print(f" {name:<45s} (new) {rt:8.3f} ms") + +if regressed > 0: + print(f"\n⚠ 检测到 {regressed} 项性能退化(阈值 {threshold})") + print(" 若为预期变更,使用 tools/perf_regression.sh --update 更新基线") + sys.exit(1) +print("\n✓ 全部通过,无性能退化") +PYEOF + rm -f "$tmp" +} + +if [[ "$UPDATE_BASELINE" == "true" ]]; then + run_all +else + compare +fi