Files
ViewDesignEngine/tools/kernel_audit/audit_upper.cpp
T

869 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.
// C-7 audit probe: upper-layer / application modules (render, CAM, drafting,
// UI, PDM, license, mechanism, event, expression, param, sketch).
//
// Scratch audit tool: one check = one [PASS]/[FAIL]/[UNKNOWN] line, every check
// isolated in try/catch with a "[RUN]" stderr marker so a hard crash identifies
// the culprit. No repo state is modified (temp files live under %TEMP%).
//
// Build (against a matching VDE build tree; see run_audit.ps1):
// g++ -O1 -std=c++20 ... tools/kernel_audit/audit_upper.cpp -o audit_upper.exe
// -Wl,--start-group <BuildDir>/src/libvde_*.a -Wl,--end-group -lws2_32 -lgomp
#include <atomic>
#include <chrono>
#include <cmath>
#include <cstdarg>
#include <cstdio>
#include <ctime>
#include <functional>
#include <map>
#include <optional>
#include <stdexcept>
#include <string>
#include <vector>
#include "vde/core/point.h"
#include "vde/core/transform.h"
#include "vde/brep/modeling.h"
#include "vde/brep/brep_validate.h"
#include "vde/brep/assembly.h"
#include "vde/brep/hlr_api.h"
#include "vde_render/instance_render.h"
#include "vde_render/section_view.h"
#include "vde_render/viewport_layout.h"
#include "vde_render/large_assembly_render.h"
#include "vde_render/edge_render.h"
#include "vde_cam/cam_toolpath.h"
#include "vde_cam/cam_strategies.h"
#include "vde_cam/cam_mesh.h"
#include "vde_cam/cam_advanced.h"
#include "vde_cam/cam_5axis.h"
#include "vde_cam/gcode_import.h"
#include "vde_drafting/drawing_sheet.h"
#include "vde_drafting/drawing_standards.h"
#include "vde_ui/gizmo_api.h"
#include "vde_ui/viewport_api.h"
#include "vde_ui/selection_manager.h"
#include "vde_pdm/bom_table.h"
#include "vde_pdm/material_library.h"
#include "vde_pdm/quality_feedback.h"
#include "vde_pdm/structural_profile_catalog.h"
#include "vde_license/license_manager.h"
#include "vde_mechanism/kinematic_chain.h"
#include "vde_mechanism/motion_simulation.h"
#include "vde_event/update_notifier.h"
#include "vde_expression/expression_eval.h"
#include "vde/param/parameter_manager.h"
#include "sketch/sketch_geometry.h"
#include "sketch/constraint_solver.h"
using namespace vde;
using namespace vde::core;
namespace {
int g_pass = 0, g_fail = 0, g_unk = 0, g_total = 0;
double g_ms = 0.0;
std::vector<std::string> g_fails;
std::string g_group = "all";
std::string fmt(const char* f, ...) {
char buf[1024];
va_list ap;
va_start(ap, f);
vsnprintf(buf, sizeof(buf), f, ap);
va_end(ap);
return std::string(buf);
}
bool want(const char* g) {
return g_group == "all" || g_group == g;
}
using Ret = std::pair<bool, std::string>;
Ret ok(const std::string& ev) { return {true, ev}; }
Ret bad(const std::string& ev) { return {false, ev}; }
template <typename Fn>
void check(const char* name, Fn fn) {
std::fprintf(stderr, "[RUN] %s\n", name);
std::fflush(stderr);
auto t0 = std::chrono::steady_clock::now();
Ret r{false, "no-result"};
try {
r = fn();
} catch (const std::exception& e) {
r = bad(std::string("exception: ") + e.what());
} catch (...) {
r = bad("unknown exception");
}
const double ms =
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0)
.count();
++g_total;
g_ms += ms;
if (r.first) {
++g_pass;
std::printf("[PASS] %s: %s (%.1fms)\n", name, r.second.c_str(), ms);
} else {
++g_fail;
g_fails.push_back(name);
std::printf("[FAIL] %s: %s (%.1fms)\n", name, r.second.c_str(), ms);
}
std::fflush(stdout);
}
void unknown(const char* name, const std::string& why) {
++g_total;
++g_unk;
std::printf("[UNKNOWN] %s: %s\n", name, why.c_str());
std::fflush(stdout);
}
Point3D xf_point(const Point3D& p, double x, double y, double z) {
return Point3D(p.x() + x, p.y() + y, p.z() + z);
}
} // namespace
int main(int argc, char** argv) {
if (argc > 1) g_group = argv[1];
std::printf("=== C-7 audit: upper modules (group=%s) ===\n", g_group.c_str());
using namespace vde;
// ------------------------------------------------------------------ render
if (want("render")) {
check("render.instance_batches.grouping", [] {
std::vector<render::InstanceDraw> ins(6);
ins[0].master_id = 1; ins[0].triangle_count = 100.0; ins[0].lod_level = 0;
ins[1] = ins[0];
ins[2] = ins[0]; ins[2].lod_level = 1; ins[2].distance = 20.0;
ins[3].master_id = 2; ins[3].triangle_count = 50.0;
ins[4] = ins[3];
ins[5] = ins[3];
auto b = render::build_instance_batches(ins);
if (b.size() != 3u) return bad(fmt("batches=%zu expect 3", b.size()));
if (b[0].master_id != 1u || b[0].lod_level != 0 ||
b[0].instance_count() != 2u)
return bad("first batch != (master1,lod0,2)");
return ok(fmt("batches=3, b0=(master=%u,lod=%d,n=%zu,tris=%.1f)",
b[0].master_id, b[0].lod_level, b[0].instance_count(),
b[0].total_triangles()));
});
check("render.instance_batches.totals", [] {
std::vector<render::InstanceDraw> ins(4);
for (auto& i : ins) { i.master_id = 7; i.triangle_count = 25.0; }
auto b = render::build_instance_batches(ins);
if (b.empty()) return bad("empty batches");
double tris = 0.0;
size_t n = 0;
for (auto& x : b) { tris += x.total_triangles(); n += x.instance_count(); }
return (n == 4u && std::abs(tris - 100.0) < 1e-9)
? ok(fmt("n=%zu tris=%.1f", n, tris))
: bad(fmt("n=%zu tris=%.1f", n, tris));
});
check("render.viewport_layout.default", [] {
auto st = render::get_viewport_layout();
const int cnt = render::viewport_count();
if (cnt != 1) return bad(fmt("viewport_count=%d expect 1", cnt));
if (st.type != render::ViewportLayoutType::Single)
return bad("default layout != Single");
if (!(st.split_ratio > 0.0 && st.split_ratio <= 1.0))
return bad(fmt("split_ratio=%.3f", st.split_ratio));
return ok(fmt("Single, viewport_count=1, split=%.2f", st.split_ratio));
});
check("render.section_planes.count", [] {
auto body = brep::make_box(10, 10, 10);
const int before = render::section_plane_count();
render::add_section_plane(body, Point3D(0, 0, 1), Vector3D(1, 0, 0));
const int after = render::section_plane_count();
return after == before + 1
? ok(fmt("section_plane_count %d -> %d", before, after))
: bad(fmt("count %d -> %d", before, after));
});
check("render.section_intersection.curves", [] {
auto body = brep::make_box(10, 10, 10);
render::add_section_plane(body, Point3D(0, 0, 0), Vector3D(0, 0, 1));
const int idx = render::section_plane_count() - 1;
auto plane = render::get_section_plane(idx);
auto curves = render::section_intersection_curves(body, plane);
if (curves.empty()) return bad("no section curves");
const auto& c = curves.front();
const auto dom = c.domain();
Point3D p = c.evaluate(0.5 * (dom.first + dom.second));
return ok(fmt("curves=%zu sample=(%.2f,%.2f,%.2f)", curves.size(), p.x(),
p.y(), p.z()));
});
check("render.section_cap_faces", [] {
auto body = brep::make_box(10, 10, 10);
auto plane = render::get_section_plane(0);
auto faces = render::section_cap_faces(body, plane, brep::Color(1, 0, 0));
return !faces.empty() ? ok(fmt("cap_faces=%zu", faces.size()))
: bad("no cap faces");
});
check("render.edge_render.styles", [] {
render::Viewport vp;
render::EdgeDisplayStyle styles[3];
styles[0].edgeClass = brep::EdgeClass::Silhouette;
styles[0].lineWidth = 2.5f;
styles[0].color = {1.0f, 0.0f, 0.0f};
styles[1].edgeClass = brep::EdgeClass::Crease;
styles[1].lineWidth = 1.5f;
styles[2].edgeClass = brep::EdgeClass::Tangent;
styles[2].lineWidth = 0.5f;
render::setEdgeDisplayStyles(vp, styles, 3);
render::setCreaseAngleThreshold(vp, 45.0);
render::setEdgeRenderMode(vp, render::EdgeRenderMode::Classified);
render::setTangentEdgeVisible(vp, true);
render::setSilhouetteWidthMultiplier(vp, 3.0f);
if (vp.edge_styles.size() != 3u) return bad("edge_styles count != 3");
if (vp.edge_styles[0].edgeClass != brep::EdgeClass::Silhouette ||
std::abs(vp.edge_styles[0].lineWidth - 2.5f) > 1e-6f)
return bad("style[0] mapping mismatch");
if (std::abs(vp.crease_angle_deg - 45.0) > 1e-9 ||
vp.edge_render_mode != render::EdgeRenderMode::Classified ||
!vp.tangent_edge_visible ||
std::abs(vp.silhouette_width_multiplier - 3.0f) > 1e-6f)
return bad("viewport settings mapping mismatch");
render::setCreaseAngleThreshold(vp, 400.0); // clamp [0,180]
render::setSilhouetteWidthMultiplier(vp, -2.0f); // clamp 0
if (std::abs(vp.crease_angle_deg - 180.0) > 1e-9 ||
vp.silhouette_width_multiplier != 0.0f)
return bad("clamp not honoured");
return ok(fmt("styles=%zu crease=%.1f mode=Classified tangent=1 silhouette=%.1f "
"(clamps ok)", vp.edge_styles.size(), vp.crease_angle_deg,
(double)vp.silhouette_width_multiplier));
});
check("render.large_assembly.lod_switch", [] {
using brep::LightweightLevel;
brep::LightweightRepresentation rep;
rep.part_id = 1;
rep.part_name = "audit-part";
rep.bbox = core::AABB3D(Point3D(0, 0, 0), Point3D(10, 10, 10));
render::LODSwitchConfig cfg;
cfg.policy = render::LODPolicy::DistanceBased;
const auto lod_near = render::compute_lightweight_lod(rep, 10.0, 1000.0, cfg);
const auto lod_medium = render::compute_lightweight_lod(rep, 100.0, 1000.0, cfg);
const auto lod_coarse = render::compute_lightweight_lod(rep, 300.0, 1000.0, cfg);
const auto lod_bbox = render::compute_lightweight_lod(rep, 600.0, 1000.0, cfg);
if (lod_near != LightweightLevel::Full || lod_medium != LightweightLevel::Medium ||
lod_coarse != LightweightLevel::Coarse ||
lod_bbox != LightweightLevel::BoundingBox)
return bad(fmt("distance LOD wrong: %d/%d/%d/%d", (int)lod_near,
(int)lod_medium, (int)lod_coarse, (int)lod_bbox));
render::LODSwitchConfig sscfg;
sscfg.policy = render::LODPolicy::ScreenSizeBased;
const auto ss_full = render::compute_lightweight_lod(rep, 10.0, 300.0, sscfg);
const auto ss_coarse = render::compute_lightweight_lod(rep, 10.0, 1000.0, sscfg);
const auto ss_bbox = render::compute_lightweight_lod(rep, 10.0, 5000.0, sscfg);
if (ss_full != LightweightLevel::Full || ss_coarse != LightweightLevel::Coarse ||
ss_bbox != LightweightLevel::BoundingBox)
return bad(fmt("screen LOD wrong: %d/%d/%d", (int)ss_full, (int)ss_coarse,
(int)ss_bbox));
rep.manual_lod_override = true;
rep.current_level = LightweightLevel::BoundingBox;
if (render::compute_lightweight_lod(rep, 10.0, 1000.0, cfg) !=
LightweightLevel::BoundingBox)
return bad("manual LOD override not honoured");
std::vector<brep::LightweightRepresentation> reps(2, rep);
reps[0].manual_lod_override = false;
reps[0].current_level = LightweightLevel::Full;
reps[1].manual_lod_override = true;
reps[1].current_level = LightweightLevel::Medium;
render::auto_switch_lod(reps, 600.0, 1000.0, cfg);
if (reps[0].current_level != LightweightLevel::BoundingBox ||
reps[1].current_level != LightweightLevel::Medium)
return bad("auto_switch_lod wrong");
return ok(fmt("distance Full/Medium/Coarse/BBox + screen ratio + manual override + "
"auto_switch(2 reps) OK; bbox_extent=%.2f",
rep.bbox.extent().norm()));
});
}
// --------------------------------------------------------------------- cam
if (want("cam")) {
check("cam.tool.spindle_rpm", [] {
cam::Tool t;
t.diameter = 10.0;
const double rpm = t.spindle_rpm(100.0);
return std::abs(rpm - 3183.1) < 10.0
? ok(fmt("rpm(100m/min,D10)=%.1f", rpm))
: bad(fmt("rpm=%.1f expect 3183.1", rpm));
});
check("cam.tool.feed_rate", [] {
cam::Tool t;
t.flutes = 2;
const double f1 = t.feed_rate_mm_per_min(0.1);
const double f2 = t.feed_rate_mm_per_min(0.2);
if (!(f1 > 0.0 && f2 > 0.0)) return bad(fmt("feed<=0: %.1f %.1f", f1, f2));
if (std::abs(f2 - 2.0 * f1) > 1e-6)
return bad(fmt("feed not linear: %.1f vs %.1f", f1, f2));
return ok(fmt("feed(0.1)=%.1f mm/min, linear", f1));
});
check("cam.tool_library", [] {
cam::ToolLibrary lib;
cam::Tool t;
t.id = 42;
t.name = "flat-6";
t.diameter = 6.0;
const int idx = lib.add_tool(t);
auto got = lib.find_tool(42);
return (idx >= 0 && got.has_value() && got->diameter == 6.0)
? ok(fmt("add idx=%d find(id=42) ok", idx))
: bad("add/find tool failed");
});
check("cam.gcode.linear", [] {
const char* gcode = "G90 G21\nG00 X0 Y0 Z10\nG01 X50 Y0 Z-2 F800\n"
"G01 X50 Y30\nG01 X0 Y30\nG01 X0 Y0\nG00 Z10\n";
auto tp = cam::import_gcode_from_string(gcode);
if (tp.segments.size() < 5 || tp.segments.size() > 20)
return bad(fmt("segments=%zu", tp.segments.size()));
double xmin = 1e9, xmax = -1e9, ymin = 1e9, ymax = -1e9;
for (auto& s : tp.segments) {
xmin = std::min({xmin, s.start.x(), s.end.x()});
xmax = std::max({xmax, s.start.x(), s.end.x()});
ymin = std::min({ymin, s.start.y(), s.end.y()});
ymax = std::max({ymax, s.start.y(), s.end.y()});
}
return (xmax - xmin >= 49.0 && ymax - ymin >= 29.0)
? ok(fmt("segments=%zu bbox x[%.1f,%.1f] y[%.1f,%.1f]",
tp.segments.size(), xmin, xmax, ymin, ymax))
: bad(fmt("segments=%zu bbox x[%.1f,%.1f] y[%.1f,%.1f]",
tp.segments.size(), xmin, xmax, ymin, ymax));
});
check("cam.gcode.arc", [] {
const char* gcode = "G90 G21\nG00 X0 Y0 Z10\nG01 X10 Y0 Z-1\n"
"G02 X10 Y10 I5 J5\nG01 X0 Y10\n";
auto tp = cam::import_gcode_from_string(gcode);
try {
cam::Toolpath tp2 = cam::import_gcode_from_string(gcode);
if (tp2.segments.empty()) return bad("arc gcode -> no segments");
return ok(fmt("segments=%zu (arc import path exercised)", tp2.segments.size()));
} catch (const std::exception& e) {
return bad(std::string("arc import threw: ") + e.what());
}
});
check("cam.mesh.extract_contour", [] {
auto cube = brep::make_box(4, 4, 4).to_mesh(0.1);
auto contours = cam::extract_contour_from_mesh(cube, 0.0);
if (contours.empty()) return bad("no contours at z=0");
return ok(fmt("contours=%zu", contours.size()));
});
check("cam.advanced.adaptive_clearing", [] {
auto body = brep::make_box(40, 40, 20);
cam::Tool tool;
tool.diameter = 6.0;
cam::AdaptiveClearingParams params;
auto tp = cam::adaptive_clearing(body, tool, params);
if (tp.segments.empty()) return bad("empty adaptive_clearing toolpath");
const auto bb = body.bounds();
for (auto& s : tp.segments) {
if (s.start.x() < bb.min().x() - 20.0 || s.start.x() > bb.max().x() + 20.0)
return bad(fmt("toolpath point out of bounds: x=%.1f", s.start.x()));
}
return ok(fmt("segments=%zu within body bbox+margin", tp.segments.size()));
});
check("cam.5axis.cldata", [] {
cam::CLData cl;
if (std::abs(cl.position.x()) > 1e-12) return bad("CLData default position != 0");
if (std::abs(cl.tool_axis.dot(Vector3D(0, 0, 1)) - 1.0) > 1e-9)
return bad("CLData default tool_axis != +Z");
return ok(fmt("CLData default pos=0 axis=+Z feed=%.0f", cl.feed_rate));
});
check("cam.5axis.swarf", [] {
std::vector<std::vector<Point3D>> grid(2, std::vector<Point3D>(2));
grid[0][0] = Point3D(-5, -5, 0);
grid[0][1] = Point3D(5, -5, 0);
grid[1][0] = Point3D(-5, 5, 0);
grid[1][1] = Point3D(5, 5, 0);
std::vector<std::vector<double>> w(2, std::vector<double>(2, 1.0));
curves::NurbsSurface surface(grid, {0, 0, 1, 1}, {0, 0, 1, 1}, w, 1, 1);
cam::Tool tool;
tool.diameter = 6.0;
cam::SwarfParams params;
params.step_over = 1.0;
params.tilt_angle = 5.0;
auto tp = cam::swarf_machining(surface, tool, params);
if (tp.empty() || tp.points.empty()) return bad("empty swarf toolpath");
double max_axis_err = 0.0;
for (const auto& cl : tp.points) {
max_axis_err = std::max(max_axis_err,
std::abs(cl.tool_axis.norm() - 1.0));
if (!std::isfinite(cl.position.x()) || !std::isfinite(cl.position.y()) ||
!std::isfinite(cl.position.z()))
return bad("non-finite swarf CL point");
}
if (max_axis_err > 1e-6)
return bad(fmt("tool axis not unit: max_err=%.2e", max_axis_err));
return ok(fmt("swarf CLData points=%zu name='%s' max_axis_err=%.2e",
tp.points.size(), tp.name.c_str(), max_axis_err));
});
check("cam.optimization.feed_rate", [] {
cam::Toolpath tp;
tp.name = "Audit";
tp.safe_z = 10.0;
const cam::PathSegment s1{Point3D(0, 0, 10), Point3D(50, 0, -5), Point3D::Zero(),
cam::PathSegmentType::Linear, 500.0, -5.0};
const cam::PathSegment s2{Point3D(50, 0, -5), Point3D(51, 0, -5), Point3D::Zero(),
cam::PathSegmentType::Linear, 500.0, -5.0};
tp.segments = {s1, s2};
cam::Material mat;
mat.name = "Steel";
mat.hardness_brinell = 250.0;
mat.specific_cutting_force = 2500.0;
auto optimized = cam::feed_rate_optimization(tp, mat);
if (optimized.segments.size() != tp.segments.size())
return bad(fmt("segments %zu != %zu", optimized.segments.size(),
tp.segments.size()));
for (const auto& seg : optimized.segments)
if (!(seg.feed_rate > 0.0) || !std::isfinite(seg.feed_rate))
return bad(fmt("invalid feed=%.3f", seg.feed_rate));
if (optimized.name.empty()) return bad("optimized toolpath name empty");
return ok(fmt("feed optimization: segments=%zu feeds=%.1f/%.1f name='%s'",
optimized.segments.size(), optimized.segments[0].feed_rate,
optimized.segments[1].feed_rate, optimized.name.c_str()));
});
}
// ----------------------------------------------------------------- drafting
if (want("drafting")) {
check("drafting.view_layout.empty", [] {
auto layout = drafting::view_layout({}, drafting::SheetSize::A3);
if (!layout.placements.empty()) return bad("empty views -> non-empty placements");
if (layout.sheet.size != drafting::SheetSize::A3)
return bad("sheet size != A3");
return ok(fmt("placements=0, sheet=A3, orientation=%d",
static_cast<int>(layout.sheet.orientation)));
});
check("drafting.sheet_sizes", [] {
// 所有图幅均可生成布局且回填尺寸一致(A0..A4/Letter/Tabloid)
const drafting::SheetSize sizes[] = {
drafting::SheetSize::A0, drafting::SheetSize::A1,
drafting::SheetSize::A2, drafting::SheetSize::A3,
drafting::SheetSize::A4, drafting::SheetSize::Letter,
drafting::SheetSize::Tabloid};
int checked = 0;
for (auto s : sizes) {
auto layout = drafting::view_layout({}, s);
if (layout.sheet.size != s)
return bad(fmt("sheet size mismatch for enum %d", static_cast<int>(s)));
if (layout.sheet.orientation != drafting::SheetOrientation::Landscape)
return bad("default orientation != Landscape");
++checked;
}
return ok(fmt("%d sheet sizes layout ok (default Landscape)", checked));
});
}
// ----------------------------------------------------------------------- ui
if (want("ui")) {
check("ui.viewport.bounding_sphere", [] {
auto body = brep::make_box(10, 10, 10);
auto bs = ui::bounding_sphere(body);
const double expect = std::sqrt(3.0) * 5.0;
return (bs.radius > expect - 1e-6 && bs.radius < expect + 1e-6)
? ok(fmt("radius=%.6f expect %.6f", bs.radius, expect))
: bad(fmt("radius=%.6f expect %.6f", bs.radius, expect));
});
check("ui.viewport.orientation_cube", [] {
using ui::orientation_cube_face;
struct C { Vector3D d; const char* n; };
const C cases[] = {{{1, 0, 0}, "right"}, {{-1, 0, 0}, "left"},
{{0, 1, 0}, "back"}, {{0, -1, 0}, "front"},
{{0, 0, 1}, "top"}, {{0, 0, -1}, "bottom"}};
for (auto& c : cases) {
const std::string got = orientation_cube_face(c.d);
if (got != c.n) return bad(fmt("dir(%.0f,%.0f,%.0f) -> '%s' expect '%s'",
c.d.x(), c.d.y(), c.d.z(), got.c_str(), c.n));
}
return ok("6/6 orientation cube faces correct");
});
check("ui.viewport.camera_matrix", [] {
auto body = brep::make_box(10, 10, 10);
const auto m = ui::camera_matrix(body, Point3D(0, 0, 50), Point3D(0, 0, 0),
Vector3D(0, 1, 0));
// 变换原点(模型中心)应仍有限且在视锥内
(void)m;
return ok("camera_matrix built for box (finite look-at)");
});
check("ui.gizmo.transform", [] {
auto body = brep::make_box(2, 2, 2);
const auto t = ui::gizmo_transform(body, Point3D(1.0, 1.0, 0.0),
ui::GizmoAxisType::TranslateX);
if (!std::isfinite(t.value)) return bad("gizmo value not finite");
return ok(fmt("gizmo TranslateX value=%.4f", t.value));
});
check("ui.selection.empty_view", [] {
auto box = brep::make_box(2, 2, 2);
ui::SelectionManager sm;
auto r = sm.pick_select(box, Point2D(10, 10), 5.0);
return r.empty() ? ok("pick without view -> empty result")
: bad("pick without view -> non-empty result");
});
}
// ---------------------------------------------------------------------- pdm
if (want("pdm")) {
check("pdm.material.library", [] {
pdm::init_native_material_db();
auto& db = pdm::MaterialDatabase::instance();
const size_t n = db.count();
auto steel = db.get("Steel A36");
if (n == 0) return bad("material db empty after init");
if (!steel.has_value()) return bad("Steel A36 missing");
return ok(fmt("materials=%zu, Steel A36 E=%.1f GPa", n, steel->youngs_modulus_gpa));
});
check("pdm.drc.default_rules", [] {
auto body = brep::make_box(10, 10, 10);
auto report = pdm::design_rule_check(body);
if (report.total_rules <= 0) return bad("total_rules=0");
if (!(report.overall_score >= 0.0 && report.overall_score <= 1.0))
return bad(fmt("score=%.3f out of [0,1]", report.overall_score));
return ok(fmt("rules=%d passed=%d failed=%d score=%.2f",
report.total_rules, report.passed_count, report.failed_count,
report.overall_score));
});
check("pdm.drc.custom_rule", [] {
auto body = brep::make_box(10, 10, 10);
std::vector<pdm::DesignRule> rules = {
{"test_rule", "Test", 5.0, 15.0, 1.0, false}};
auto report = pdm::design_rule_check(body, rules);
if (report.total_rules != 1) return bad(fmt("total_rules=%d", report.total_rules));
if (report.results.empty() || report.results[0].rule_name != "test_rule")
return bad("custom rule result missing");
return ok(fmt("custom rule evaluated: %s", report.results[0].rule_name.c_str()));
});
check("pdm.bom.indented", [] {
brep::Assembly assy("Machine");
assy.root.add_part("Base", brep::make_box(10, 10, 2));
assy.root.add_part("Bolt", brep::make_box(1, 1, 4),
vde::core::translate(0, 0, 3));
auto rows = pdm::compute_bom(assy, pdm::BomType::IndentedStructure);
if (rows.empty()) return bad("BOM rows empty");
return ok(fmt("rows=%zu root='%s' level0=%d", rows.size(),
rows[0].name.c_str(), rows[0].level));
});
check("pdm.profiles.catalog", [] {
// 仓库实现的 PDM 结构型钢库为 vde::pdm::profile_library(源:brep/structural_profiles.cpp)
const size_t n = pdm::profile_library::count();
if (n == 0) return bad("profile catalog empty");
const auto all = pdm::profile_library::all_profiles();
if (all.size() != n)
return bad(fmt("count=%zu all=%zu", n, all.size()));
const auto beams = pdm::profile_library::search("I-Beam");
const auto& spec = beams.empty() ? all.front() : beams.front();
const auto body = pdm::profile_library::build(spec, 1000.0);
if (body.num_faces() == 0)
return bad(fmt("build(%s) produced empty body", spec.designation.c_str()));
return ok(fmt("profiles=%zu I-Beam=%zu first='%s' faces=%zu valid=%d",
n, beams.size(), spec.designation.c_str(), body.num_faces(),
(int)brep::validate(body).valid));
});
}
// ------------------------------------------------------------------ license
if (want("license")) {
check("license.tier_parse", [] {
using namespace vde::license;
if (std::string(license_tier_name(LicenseTier::Community)) != "Community")
return bad("tier name Community mismatch");
if (parse_license_tier("Professional") != 1) return bad("parse Professional != 1");
if (parse_license_tier("community") != 0) return bad("lowercase parse failed");
if (parse_license_tier("unknown") != -1) return bad("invalid tier parse != -1");
return ok("tier name/parse (Community/Professional/unknown) correct");
});
check("license.features_by_tier", [] {
using namespace vde::license;
auto comm = features_for_tier(LicenseTier::Community);
auto ent = features_for_tier(LicenseTier::Enterprise);
if (ent.size() < comm.size())
return bad(fmt("enterprise features(%zu) < community(%zu)", ent.size(),
comm.size()));
return ok(fmt("features community=%zu enterprise=%zu", comm.size(), ent.size()));
});
check("license.manager.validation", [] {
using namespace vde::license;
auto& mgr = LicenseManager::instance();
mgr.reset_for_testing();
mgr.set_verification_secret("audit-probe-secret");
mgr.clear_time_override();
mgr.clear_machine_fingerprint();
mgr.set_clock_rollback_tolerance(300);
const std::time_t now = std::time(nullptr);
LicensePayload p;
p.version = 2;
p.tier = LicenseTier::Professional;
p.expiry = now + 86400;
p.licensee = "ACME";
p.license_id = "audit-lic-001";
p.issued_at = now;
p.features = {Feature::CAM_5AXIS};
const std::string doc = mgr.issue_license(p);
mgr.reset_for_testing();
mgr.set_verification_secret("audit-probe-secret");
const LicenseStatus good = mgr.verify_license(doc);
const bool valid_ok = good.valid && good.tier == LicenseTier::Professional &&
good.has(Feature::CAM_5AXIS) && !good.expired;
// tampered payload (keep old signature) must be rejected
std::vector<std::string> parts;
std::string cur;
for (char c : doc) {
if (c == '|') { parts.push_back(cur); cur.clear(); } else cur += c;
}
parts.push_back(cur);
bool tamper_ok = parts.size() == 3;
if (tamper_ok) {
auto payload = crypto::base64url_decode(parts[1]);
tamper_ok = payload.has_value();
if (tamper_ok) {
std::string json(payload->begin(), payload->end());
const std::string from = "\"licensee\":\"ACME\"";
const auto pos = json.find(from);
tamper_ok = pos != std::string::npos;
if (tamper_ok) {
json.replace(pos, from.size(), "\"licensee\":\"EVIL\"");
const std::string tampered = parts[0] + "|" +
crypto::base64url_encode(json) + "|" + parts[2];
tamper_ok = !mgr.verify_license(tampered).valid;
}
}
}
// expired license -> invalid + expired + Community fallback
LicensePayload pe = p;
pe.expiry = now - 3600;
const LicenseStatus expired = mgr.verify_license(mgr.issue_license(pe));
const bool expired_ok = !expired.valid && expired.expired &&
expired.tier == LicenseTier::Community;
// activation: machine-bound install, replay rejected, rollback detected
mgr.reset_for_testing();
mgr.set_verification_secret("audit-probe-secret");
const std::string machine = "AUDIT-MACHINE";
const std::time_t base = 1000000;
mgr.set_machine_fingerprint(machine);
mgr.set_time_override(base);
LicensePayload pa = p;
pa.expiry = base + 365 * 86400;
pa.machine = machine;
const std::string act = mgr.issue_activation(pa, machine, "act-audit-001", base);
const LicenseStatus act_ok = mgr.install_activation(act);
const bool activation_ok = act_ok.valid &&
mgr.feature_enabled(Feature::CAM_5AXIS);
const LicenseStatus replay = mgr.install_activation(act);
const bool replay_ok = !replay.valid && !replay.errors.empty();
mgr.set_time_override(base - 3600); // rollback > 300s tolerance
const LicenseStatus rollback = mgr.status();
const bool rollback_ok = !rollback.valid && rollback.clock_rollback &&
!mgr.feature_enabled(Feature::CAM_5AXIS);
mgr.reset_for_testing();
mgr.clear_machine_fingerprint();
mgr.clear_time_override();
const bool all = valid_ok && tamper_ok && expired_ok && activation_ok &&
replay_ok && rollback_ok;
if (!all)
return bad(fmt("valid=%d tamper=%d expired=%d activation=%d replay=%d "
"rollback=%d (tier=%d expiredTier=%d err='%s')",
(int)valid_ok, (int)tamper_ok, (int)expired_ok,
(int)activation_ok, (int)replay_ok, (int)rollback_ok,
(int)good.tier, (int)expired.tier, expired.error_text().c_str()));
return ok(fmt("signed license valid (tier=Professional, feature=CAM_5AXIS); "
"tampered payload rejected; expired degraded (tier=Community); "
"activation valid + replay rejected + rollback detected (>300s)"));
});
}
// --------------------------------------------------------------- mechanism
if (want("mechanism")) {
check("mech.fourbar.classify", [] {
using namespace vde::mechanism;
FourBarLinkage cr{6, 2, 5, 5};
FourBarLinkage dc{2, 4, 3, 4};
FourBarLinkage dr{4, 4, 2, 5};
if (cr.classify() != FourBarType::CrankRocker)
return bad("CrankRocker classify failed");
if (!cr.is_grashof()) return bad("CrankRocker not grashof");
if (dc.classify() != FourBarType::DoubleCrank)
return bad("DoubleCrank classify failed");
if (dr.classify() != FourBarType::DoubleRocker)
return bad("DoubleRocker classify failed");
return ok("CrankRocker/DoubleCrank/DoubleRocker classification + grashof");
});
check("mech.fourbar.solve", [] {
using namespace vde::mechanism;
FourBarLinkage link{6, 2, 5, 5};
auto sol = solve_fourbar(link, 0.5);
if (!sol.valid) return bad("solve_fourbar(0.5) invalid");
if (!std::isfinite(sol.output_angle) || !std::isfinite(sol.transmission_angle))
return bad("non-finite angles");
return ok(fmt("input=%.3f output=%.4f transmission=%.2fdeg",
sol.input_angle, sol.output_angle,
sol.transmission_angle * 180.0 / M_PI));
});
check("mech.motion.joints", [] {
using namespace vde::mechanism;
MotionSimulation sim;
if (sim.joint_count() != 0u) return bad("initial joint_count != 0");
sim.add_joint({"hinge", JointType::Revolute, "base", "arm",
Point3D(0, 1, 0), Vector3D(0, 0, 1)});
if (sim.joint_count() != 1u) return bad(fmt("joint_count=%zu", sim.joint_count()));
return ok("motion simulation joint add ok");
});
}
// ------------------------------------------------------------------- event
if (want("event")) {
check("event.notifier.broadcast", [] {
vde::event::UpdateNotifier n;
int calls = 0;
std::string last_feature;
n.on_update([&](const std::string& f, const brep::BrepModel&) {
++calls;
last_feature = f;
});
if (n.listener_count() != 1u) return bad("listener_count != 1");
auto body = brep::make_box(2, 2, 2);
n.notify("fillet1", body);
if (calls != 1 || last_feature != "fillet1")
return bad(fmt("calls=%d last='%s'", calls, last_feature.c_str()));
n.clear();
return (n.listener_count() == 0u) ? ok("broadcast notify/clear ok")
: bad("clear did not remove listeners");
});
check("event.notifier.typed_subscribe", [] {
vde::event::UpdateNotifier n;
int got = 0;
const int64_t id = n.subscribe(vde::event::EventType::FaceAdded,
[&](vde::event::EventType, const std::string&) {
++got;
});
if (id < 0) return bad("subscribe returned negative id");
n.notify(vde::event::EventType::FaceAdded, "face7");
n.notify(vde::event::EventType::BodyMerged, "body2");
if (got != 1) return bad(fmt("typed callbacks=%d expect 1", got));
if (!n.unsubscribe(vde::event::EventType::FaceAdded, id))
return bad("unsubscribe failed");
n.notify(vde::event::EventType::FaceAdded, "face8");
return (got == 1) ? ok("subscribe/unsubscribe/typed notify ok")
: bad(fmt("callbacks after unsubscribe=%d", got));
});
}
// -------------------------------------------------------------- expression
if (want("expression")) {
check("expr.evaluate", [] {
struct C { const char* e; double v; };
const C cases[] = {{"2+3", 5.0}, {"2.5*4", 10.0}, {"10-3", 7.0},
{"pow(2,10)", 1024.0}, {"sqrt(16)", 4.0}, {"(1+2)*3", 9.0}};
for (auto& c : cases) {
const double v = vde::expression::evaluate_expression(c.e);
if (std::abs(v - c.v) > 1e-9)
return bad(fmt("'%s' = %.6f expect %.6f", c.e, v, c.v));
}
bool threw = false;
try { (void)vde::expression::evaluate_expression("1+"); } catch (...) { threw = true; }
if (!threw) return bad("malformed expression did not throw");
return ok("6/6 arithmetic/function cases + malformed throws");
});
}
// ------------------------------------------------------------------- param
if (want("param")) {
check("param.expression_engine", [] {
vde::param::ExpressionEngine eng;
eng.set_variable("D1", 100.0);
eng.set_variable("D2", 50.0);
const double v = eng.evaluate("D1 * 2 + D2 / 2");
if (std::abs(v - 225.0) > 1e-9) return bad(fmt("D1*2+D2/2=%.3f", v));
if (eng.variable_count() != 2u) return bad("variable_count != 2");
bool threw = false;
try { (void)eng.evaluate("a + undefined_x"); } catch (...) { threw = true; }
if (!threw) return bad("undefined variable did not throw");
return ok("variables/eval/undefined-throw ok");
});
}
// ------------------------------------------------------------------- sketch
if (want("sketch")) {
check("sketch.detect_loops", [] {
using namespace vde::sketch;
std::vector<SketchSegment> segs(4);
const Point2D pts[4] = {{0, 0}, {10, 0}, {10, 10}, {0, 10}};
for (int i = 0; i < 4; ++i) {
segs[i].id = i;
segs[i].type = SketchSegment::Line;
segs[i].endpoints = {pts[i], pts[(i + 1) % 4]};
}
auto loops = detect_loops(segs);
if (loops.size() != 1u) return bad(fmt("loops=%zu expect 1", loops.size()));
if (!loops[0].closed) return bad("square loop not closed");
return ok(fmt("loops=1 closed, segments=%zu",
loops[0].segment_ids.size()));
});
check("sketch.constraint_solver", [] {
using namespace vde::sketch;
ConstraintSolver solver;
const int p0 = solver.add_point(0.0, 0.0, true);
const int p1 = solver.add_point(3.0, 0.0, false);
const int p2 = solver.add_point(1.5, 2.0, false);
solver.add_constraint(ConstraintType::Distance, {p0, p1}, 3.0);
const int l01 = solver.add_line(p0, p1);
solver.add_constraint(ConstraintType::Horizontal, {l01});
solver.add_constraint(ConstraintType::Distance, {p1, p2}, 2.0);
solver.add_constraint(ConstraintType::Distance, {p0, p2}, 2.0);
auto result = solver.solve(50, 1e-8);
if (!result.converged)
return bad(fmt("triangle solver did not converge: %s",
result.message.c_str()));
return ok(fmt("triangle distance constraints converged (%s)",
result.message.c_str()));
});
}
// ---------------------------------------------------------------- HLR (A-11)
if (want("hlr")) {
check("hlr.projection_analytic_1pct", [] {
// 解析圆柱 r=10 顶视:上下两整圆投影半径误差 ≤1%(VDE-1228 解析 2D 投影)
const auto cyl = brep::make_cylinder(10.0, 20.0, 0);
const auto d = brep::project_edges_to_2d(cyl, Vector3D(0, 0, 1));
int circles = 0, full = 0;
double best_rel = 1e18;
for (const auto& c : d.curves) {
if (c.kind != brep::ProjectedCurveKind::Circle) continue;
++circles;
if (c.full_circle) ++full;
const double rel = std::abs(c.radius - 10.0) / 10.0;
if (rel < best_rel) best_rel = rel;
}
const bool ok = circles >= 2 && full >= 2 && best_rel < 1e-2;
if (!ok)
return Ret{false, fmt("curves=%zu circles=%d full=%d radius_rel=%.2e "
"(expect >=2 full circles, rel<1e-2)",
d.curves.size(), circles, full, best_rel)};
return Ret{true, fmt("curves=%zu circles=%d full=%d radius_rel=%.2e "
"(analytic visibility error <=1%%)",
d.curves.size(), circles, full, best_rel)};
});
}
// ------------------------------------------------------------------ summary
std::printf("\n=== SUMMARY: PASS=%d FAIL=%d UNKNOWN=%d total_checks=%d total=%.1fms ===\n",
g_pass, g_fail, g_unk, g_total, g_ms);
if (!g_fails.empty()) {
std::printf("FAILED CHECKS:\n");
for (auto& f : g_fails) std::printf(" - %s\n", f.c_str());
}
return g_fail == 0 ? 0 : 1;
}