Files
ViewDesignEngine/docs/reference/api-reference-foundation.md
T
hm 296dad126e feat(foundation): R13/R14 class 实体 MULTILEADER 解码覆盖扩展
- 新增 DwgMultiLeader 结构族(引线/折断/折线点/MLEADER_CONTEXT_DATA 文本或块内容/箭头/块标签),按 LibreDWG dwg2.spec:1348-1512 与 MLEADER_CONTEXT_DATA 宏 :1277-1342 实现 R14 读侧解码;
- 注册 MultiLeader=672(classes.c:298/1662)、is_entity_type、type_name、resolve_class_object 仅 R14 门控(R13 无实例、R2007+ 布局未取证,保持 unsupported 并告警,不产假数据);
- dwg_compare 增加 write_multi_leader 与 visitor,字段序与解码一致;
- 新增 3 个测试用例(R14 正向/布局不匹配降级/R13 门控),原负向用例改为 ACAD_TABLE;test_dwg_tables 57/57;
- 真实样本:example_r14、r14/Leader.dwg MULTILEADER 0/1→1/1、decoded+1、unsupported 各减 1、残差 0;example_r13 不变;
- 黄金字节 AC1015 4601B/FNV 0x3a0bbc39ae6f9ecb、AC1032 7977B/FNV 0xcc12865126b095e8 保持;写侧零改动。
2026-11-17 04:07:15 +08:00

1114 lines
55 KiB
Markdown
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.
# Foundation 模块 API 参考
> 基础模块 — 16 种 CAD/网格/BIM 格式的导入导出 + 数学/容差/谓词/日志基础设施
## 模块概述
foundation 模块是 ViewDesignEngine 的基础设施与格式转换层,提供:
- **网格格式**:STL、OBJ、PLY、glTF/GLB、3MF、COLLADA、AMF、VRML 的导入导出
- **工业 CAD 格式**:JT (ISO 14306)、Parasolid XT、ACIS SAT/SAB、STEP AP242(含 PMI)、PDF 3D (U3D)
- **BIM / CAD 2D 格式**:IFC (ISO 16739)、DXF
- **VDE 原生格式**:`.vde`(B-Rep 完整数据二进制读写)与 `VDEGEOM` 网格二进制序列化
- **基础设施**:数学类型(Point/Vector/Matrix)、分层容差管理、几何谓词(自适应双精度 + 可选 GMP 后端)、区间算术验证、内存池、结构化日志、统一错误码
---
## 头文件列表
| 头文件 | 说明 |
|--------|------|
| `io_gltf.h` | glTF 2.0 / GLB 导入导出(网格 + B-Rep 导出、网格导入) |
| `io_dxf.h` | DXF ASCII 解析(12 实体类型)+ DWG 导入/导出通道(`import_dwg` / `export_dwg`) |
| `io_dwg.h` | DWG 原生版本识别(R12–R2018 魔数)+ 外部转换器发现 + DWG↔DXF 转换通道 |
| `io_dwg_plugin.h` | DWG 插件接口(DwgImporter / DwgBridge,外部 .so/.dll) |
| `io_stl.h` | STL 读写(自动检测 ASCII / 二进制,含 float 精度变体) |
| `io_obj.h` | Wavefront OBJ 解析与写出 |
| `io_collada.h` | COLLADA DAE 导入导出(B-Rep 列表) |
| `io_amf.h` | AMF 增材制造格式(ISO/ASTM 52915)导入导出 |
| `io_vrml.h` | VRML WRL 导入导出(VRML 1.0 / VRML97) |
| `io_ply.h` | PLY 网格读写(ASCII + 二进制小端) |
| `io_3mf.h` | 3MF 格式(3D 打印,含逐顶点颜色) |
| `industrial_formats.h` | JT / Parasolid XT / ACIS SAT / IFC / STEP AP242 / PDF 3D |
| `serializer.h` | 网格二进制序列化(BinarySerializer) |
| `vde_format.h` | VDE 原生格式(.vde)B-Rep 二进制读写 |
| `format_utils.h` | 格式工具函数(CAD 精度浮点格式化 / IGES 行) |
| `math_types.h` | 基础数学类型(Point/Vector/Matrix 别名) |
| `tolerance.h` | 分层容差管理(Tolerance / ToleranceScope) |
| `error_codes.h` | 统一错误码体系 |
| `interval.h` | 双精度区间算术与谓词验证 |
| `predicates.h` | 统一几何谓词接口(编译时选择后端) |
| `exact_predicates.h` | 自适应精度谓词(Shewchuk 算法) |
| `exact_predicates_gmp.h` | GMP 精确谓词后端(可选,`VDE_USE_GMP` 时编译) |
| `memory_pool.h` | 固定块内存池 |
| `vde_log.h` | 轻量结构化日志(VDE D10) |
---
## 详细 API
### `io_gltf.h` — glTF 2.0 / GLB
```cpp
namespace vde::foundation {
// 导出选项
struct GltfOptions {
bool binary = true; // GLB 单文件 / JSON+bin 分离
bool include_normals = true; // 顶点法线
bool include_colors = false; // 顶点颜色
std::vector<float> vertex_colors; // 逐顶点 RGB(include_colors 时使用)
};
// glTF 导出
bool write_gltf(const std::string& filepath, const mesh::HalfedgeMesh& mesh,
const GltfOptions& options = GltfOptions{});
bool write_brep_gltf(const std::string& filepath, const brep::BrepModel& model,
int tessellation_res = 32);
// glTF 导入(VDE-082)
struct GltfImportResult {
std::vector<mesh::HalfedgeMesh> meshes; // 按 glTF mesh 索引
std::vector<std::string> mesh_names;
size_t total_vertices = 0, total_triangles = 0;
bool success = false;
std::string error_message;
};
[[nodiscard]] GltfImportResult import_gltf(const std::string& path); // 文件导入
[[nodiscard]] GltfImportResult import_gltf_binary(const uint8_t* data, size_t size); // 内存导入
} // namespace vde::foundation
```
### `io_dxf.h` — DXF 格式
```cpp
namespace vde::foundation {
// === 实体类型(12 种) ===
struct DxfLine { Point3D start, end; std::string layer; };
struct DxfCircle { Point3D center; double radius; std::string layer; };
struct DxfArc { Point3D center; double radius, start_angle, end_angle; std::string layer; };
struct DxfLwPolyline{ struct Vertex { double x,y,bulge; }; std::vector<Vertex> vertices; bool closed; double constant_width, elevation, thickness; std::string layer; };
struct DxfPolyline { struct Vertex { Point3D position; double bulge, start_width, end_width; }; std::vector<Vertex> vertices; bool closed, is_3d; std::string layer; };
struct DxfPoint { Point3D position; std::string layer; };
struct DxfText { std::string text_value; Point3D insertion_point; double height, rotation, width_factor; Point3D bbox_min, bbox_max; bool is_mtext; std::string layer; };
struct DxfInsert { std::string block_name; Point3D insertion_point; double scale_x, scale_y, scale_z, rotation; int column_count, row_count; double column_spacing, row_spacing; std::string layer; };
struct DxfEllipse { Point3D center, major_axis_endpoint; double axis_ratio, start_param, end_param; std::string layer; };
struct DxfSpline { std::vector<Point3D> control_points; std::vector<double> knots, weights; int degree; bool closed, periodic, rational; std::vector<Point3D> fit_points; double fit_tolerance; std::string layer; };
struct Dxf3DFace { Point3D corners[4]; bool invisible[4]; std::string layer; };
struct DxfHatch { struct BoundaryLoop { std::vector<Point3D> points; bool is_closed; }; std::vector<BoundaryLoop> boundary_loops; std::string pattern_name; double pattern_scale, pattern_angle; bool is_solid; std::string layer; };
using DxfEntity = std::variant<DxfLine, DxfCircle, DxfArc, DxfLwPolyline, DxfPolyline, DxfPoint, DxfText, DxfInsert, DxfEllipse, DxfSpline, Dxf3DFace, DxfHatch>;
// 图层/块
struct DxfLayer {
std::string name; int color; std::string linetype;
bool frozen, locked, off, plot; // 70 位 1 / 70 位 4 / 62 负色号 / 290
bool frozen_in_new = false; // 70 位 2(新视口冻结)
int lineweight = -3; // 370:-3 ByDefault、-2 ByBlock、-1 ByLayer、
// 0/5/9/.../211(百分之一 mm 标准表)
int true_color = 0; // 420:0x00RRGGBB;0 = 未设置(按 ACI)
};
struct DxfBlock { std::string name; Point3D base_point; std::vector<DxfEntity> entities; };
// 版本
enum class DxfVersion { Unknown, R12, R14, R2000, R2004, R2007, R2010, R2013, R2018 };
// 文档
struct DxfDocument {
DxfVersion version; std::string version_string; int insunits;
std::vector<DxfLayer> layers; std::vector<DxfBlock> blocks; std::vector<DxfEntity> entities;
core::AABB3D extents; int entities_parsed, entities_skipped;
[[nodiscard]] bool valid() const; // version 已知且实体列表非空
};
// API
[[nodiscard]] DxfDocument import_dxf(const std::string& filepath); // 文件导入
[[nodiscard]] DxfDocument import_dxf_string(const std::string& data); // 字符串导入
[[nodiscard]] mesh::HalfedgeMesh to_mesh(const DxfDocument& document); // 3DFACE/闭合多段线 → 网格
[[nodiscard]] const char* dxf_version_name(DxfVersion version);
// DWG 导入/导出(原生识别 + 外部转换器通道;详见 io_dwg.h)
struct DwgImportResult {
std::vector<std::string> messages; // 错误/指引/诊断
std::vector<brep::BrepModel> bodies; // 插件解析出的 B-Rep(无插件时为空)
std::string metadata_json; // 插件返回的元数据(JSON)
bool success = false;
bool plugin_used = false; // 是否经由运行时插件完成
DwgVersion dwg_version = DwgVersion::Unknown; // 原生识别版本
std::string dwg_version_name; // "R2018" 等
bool converter_used = false; // 是否经由外部转换器(DWG→DXF)
bool has_drawing = false; // drawing 是否有效
DxfDocument drawing; // 转换后的 DXF 图元
// ---- DWG HEADER 变量区(读侧;字段缺失/未解析时为默认值,不猜测)----
std::uint16_t dwg_code_page = 0; // 容器头代码页(30 = ANSI_1252)
bool dwg_header_ok = false; // HEADER 变量区是否解析成功
std::uint32_t dwg_header_unknown_variables = 0; // 规范 unknown_* 字段数(安全跳过)
std::uint32_t dwg_header_named_references = 0; // HEADER 引用的表句柄数
std::uint32_t dwg_header_resolved_names = 0; // 其中已解析出名称的数量
double dwg_insbase[3] = {0, 0, 0}; // $INSBASE
double dwg_extmin[3] = {0, 0, 0}; // $EXTMIN(模型空间)
double dwg_extmax[3] = {0, 0, 0}; // $EXTMAX(模型空间)
double dwg_ltscale = 1.0; // $LTSCALE
double dwg_textsize = 0.0; // $TEXTSIZE
std::string dwg_clayer_name; // $CLAYER → LAYER 名(未解析为空)
std::string dwg_celtype_name; // $CELTYPE → LTYPE 名
std::string dwg_textstyle_name; // $TEXTSTYLE → STYLE 名
std::string dwg_dimstyle_name; // $DIMSTYLE → DIMSTYLE 名
// ---- 原生对象层实体解码统计(R13–R2018 位流路径与 R12 字节路径同口径)----
std::uint64_t dwg_entity_objects = 0; // is_entity_type 为真的对象数(含失败)
std::uint64_t dwg_entity_decoded = 0; // 其中 decoded == true
std::uint64_t dwg_entity_consistent = 0; // 其中 decoded 且数据流位残留为 0
std::uint64_t dwg_entity_class_objects = 0; // CLASSES item_class_id==0x1F2 的类实体数
std::uint64_t dwg_entity_unsupported = 0; // 其中类型未实现(decoded == false)
};
[[nodiscard]] DwgImportResult import_dwg(const std::string& filepath);
bool export_dwg(const std::string& filepath, const std::vector<brep::BrepModel>& bodies);
// DxfDocument 直写 DWG(M3.8):R2000 / R2018,不经三维投影
struct DwgDrawingWriteOptions { DwgVersion version = DwgVersion::R2000; };
struct DwgDrawingWriteReport {
bool ok = false;
std::string error;
int entities_written = 0, entities_skipped = 0, non_ascii_text_skipped = 0;
int block_entities_written = 0, block_entities_skipped = 0;
std::size_t layers_written = 0, blocks_written = 0;
// 图层状态桥降级计数(与 warnings 中的逐条说明一一对应;R12 无 LAYER
// plotflag、AC1015 无法表达真彩色、未知线型回退都计入这里;R12 的
// frozen/frozen_in_new/locked/off 现已可表达,对应的四项恒为 0):
int layers_plottable_skipped = 0, layers_off_skipped = 0,
layers_frozen_in_new_skipped = 0, layers_frozen_skipped = 0,
layers_locked_skipped = 0, layers_linetype_skipped = 0,
layers_lineweight_skipped = 0, layers_true_color_skipped = 0;
};
bool export_dwg_drawing(const std::string& filepath, const DxfDocument& drawing,
const DwgDrawingWriteOptions& options = {},
DwgDrawingWriteReport* report = nullptr);
} // namespace vde::foundation
```
> **LAYER 状态桥(D-21/D-22)**:`DxfLayer` 与 DWG 的 `DwgLayer` /
> `DwgWriteLayer` 双向互转时按规范一一映射:frozen / frozen_in_new / locked
> ↔ DXF LAYER 组码 70 位 1 / 位 2 / 位 4 ↔ DWG R2000+ LAYER flag0 位 0 /
> 位 2 / 位 3(R12 表记录首字节 flag 位 0 / 位 1 / 位 2;LibreDWG `dwg.spec`
> `DWG_TABLE (LAYER)` 的 `PRE (R_13b1)` DECODER 原文
> `frozen = flag & 1; frozen_in_new = flag & 2; locked = flag & 4`);
> off ↔ DXF 组码 62 负色号 ↔ R2000+ flag0 位 1(R12 同样用 62 负色号表达:
> 表记录颜色写成负值,原文 `off = color.index < 0`,不是 flag 位);
> plot ↔ 组码 290 ↔ R2000+ flag0 位 4(R12 表记录无该位:LibreDWG 的
> plotflag 自 `SINCE (R_2000b)` 才出现);lineweight ↔ 组码 370 ↔ flag0
> 位 5–9 的线宽索引;true_color ↔ 组码 420 ↔ AC1032 的 CMC 0xC2;linetype
> 经 LTYPE 句柄 ↔ 线型名互转(DXF 侧大写名、DWG 侧句柄,悬空句柄回退
> CONTINUOUS/Continuous)。目标格式无法表达时按字段降级:R12 无 plotflag /
> 370 / 420 槽位,AC1015 无真彩色 CMC——一律计数 + 告警
> (`DwgDrawingWriteReport` / `DxfTablesWriteReport`),不静默丢弃。
> 默认值与未设置字段不写组码/不置位,既有 DWG 黄金字节(AC1015 4601B、
> AC1032 7977B)保持不变。
>
> **R13/R14 LAYER 布局**:R13/R14(AC1012/AC1014)的 LAYER 记录没有合并
> flag0,frozen / off / frozen_in_new / locked 是四个独立 1 bit 字段(文件
> 位序即此顺序),无 plotflag / 370 线宽、CMC 只有 BS 索引;off 除独立位外
> 还由 62 负色号 OR 表达(LibreDWG `dwg.spec:3274-3279`、`:3296`、
> `:3371-3375`)。VDE 读侧已按该布局解码(`DwgLayer::values` 恒为 0,
> 打印/线宽保持默认),写出目标仍只有 AC1009 / AC1015 / AC1032,没有
> R13/R14 写目标。
>
> **R13/R14 HEADER 变量区**:R13/R14(AC1012/AC1014)的 HEADER 节与 R2000
> 同框(16 B 节起始哨兵(`kHeaderBegin`)+ RL 声明长度 + 字节对齐位流 + CRC16 +
> 16 B 结束哨兵;LibreDWG `src/decode.c` 的 `decode_R13_R2000`:
> `pvz = section.address + 16; size = bit_read_RL(); dat->bit = 0;`),变量
> 顺序共用 `dwg_decode_header_variables`,按 `src/header_variables.spec` 的
> 门控裁剪(VERSIONS(R_13b1,R_14) / UNTIL(R_14) / VERSIONS(R_13b1,R_2000)
> 等)。VDE 现已解析并暴露 $INSBASE / $EXTMIN / $EXTMAX / $LTSCALE /
> $TEXTSIZE 与 $CLAYER/$CELTYPE/$TEXTSTYLE/$DIMSTYLE 句柄(名称在对象层
> 解码完成后按句柄回填,对象缺失时不猜名),规范中语义未明的 `unknown_*`
> 字段按位安全跳过并计数(`unknown_variable_count`:R13 = 3,R14 = 3 + 4)。
> 注意两个诚实的已知限制:(a) R13/R14 位流按规范读完后总位长天然为 8k+4
> (紧凑编码 BS/BD/BL/TV 恒 2 mod 8 位、B 为 1 mod 8 位),写入端按字节
> 对齐会补位,因此 `header_bits_consumed != header_bits_declared` 在 R13/R14
> 上属预期现象(真实 R14 样本为 4 位差;R13 样本另有约 80 位未知扩展写入,
> 仍以 "HEADER 变量位长与声明不一致" 告警暴露,不静默吞掉);(b) R13/R14
> 无 $DWGCODEPAGE 变量解码,代码页取自容器头(`DwgImportResult::
> dwg_code_page`,30 = ANSI_1252)。`native_dwg_to_drawing` 只映射有把握的
> 字段:INSUNITS 与 HEADER 标量/名称进 `DwgImportResult`;当实体包围盒为空
> 且 HEADER extents 有效时,R13/R14 用 $EXTMIN/$EXTMAX 兜底 2D extents
> (R2000/R2018 输出不变);其余未知变量只计数 + 告警,不伪造语义。
>
> **R13/R14 实体位流(round-57)**:R13/R14(AC1012/AC1014)实体沿用 R2000 的
> "MS size → 类型 → 自句柄 → EED → 公共实体数据 → bitsize RL → 数据流/句柄流" 帧,
> 但公共实体数据与各实体字段的版本门控与 R2000+ 不同:R13/R14 无
> ltype_flags/plotstyle BB(LibreDWG `src/common_entity_data.spec:506-515`,
> `SINCE(R_2000b)`)与 lineweight RC(`:553-567`);BT/BE 无前导默认位
> (LibreDWG `src/bits.c:1321-1330` `bit_read_BT`、`:1170-1189` `bit_read_BE`
> 只在 `from_version >= R_2000` 时读 1 bit)。此前 VDE 对 R13/R14 无条件读这
> 三处、并按 R2000 语义读 BT/BE,导致每条实体数据流多读 12+1 bit 而整体错位
> (真实样本表现为 LINE 坐标 NaN 与 ~1e168 巨值、extents 达 ~1e250)。现按
> `src/dwg.spec` 的 `VERSIONS(R_13b1,R_14)` 分支修正:TEXT/ATTRIB/ATTDEF 文本
> 字段(BD + 2RD + 2RD + 3BD + BD 系列,`dwg.spec:80-97`)、LINE 尾部的
> BT0+BE(`:1438-1441`)、LWPOLYLINE 顶点 2RD(`:5579-5584`)、MTEXT 无
> linespace 三字段(`:2851-2864`,`SINCE(R_2000b)`)、INSERT 无 scale_flag
> 而直接 3BD(`src/insert.spec:78-81`)。写侧(AC1015 4601B / AC1032 7977B
> 黄金字节)未改动。实体计数经 `DwgObjectDocument::entity_objects /
> entity_decoded / entity_consistent` 汇总,原生导入路径复制到
> `DwgImportResult::dwg_entity_*`;`consistent` 语义是
> `decoded && data_residual_bits == 0`(数据流逐字段恰好读完,不构成几何
> 正确性证明)。真实样本(LibreDWG example_r13/r14):R13 实体
> 5285/5285/5282(3DSOLID×1、REGION×2 的 ACIS 载荷仍不解析,属模型几何
> 而非实体字段位残留),R14 实体 244/244/244;两样本 `drawing.extents` 从
> ~1e250 回落到万级坐标范围。
>
> **复杂实体/类实体(round-58)**:(1) CLASSES 记录的 `item_class_id == 0x1F2`
> 是类实体唯一判定依据(LibreDWG `src/dwg.c:2095-2099` `dwg_class_is_entity`);
> 此前 VDE 只按内置类型码判定 `is_entity`,R13/R14 中 HATCH/LWPOLYLINE/
> MULTILEADER/ARC_DIMENSION 等类实体被静默跳过。现按 item_class_id 识别,并
> 新增 `DwgObject::class_entity`、`DwgObjectDocument::entity_class_objects /
> entity_unsupported` 计数;已实现的类映射补 `HATCH/AcDbHatch`、
> `LWPOLYLINE/AcDbPolyline`(真实 R14 样本 HATCH 1、LWPOLYLINE 11 从不可见变为
> 逐字段一致解码,坐标与同文件 DXF ENTITIES 段吻合),其余类实体(MULTILEADER、
> WIPEOUT、ACAD_TABLE、LIGHT、ARC_DIMENSION)记为 unsupported 并告警,
> 不再静默丢失。(2) 3DSOLID/REGION/BODY 线框段:`num_silhouettes` BL 在
> `isoline_present` 为假时仍存在,应无条件读取(ACadSharp
> `ACadSharp/DwgObjectReader.Entities.cs:197-198`);修复 R13 真实样本 3 个
> ACIS 实体数据流 `-2` bit 残留(R14 值恰为 0、不受影响)。(3) IMAGE/
> IMAGEDEF 的 `class_version` 按规范限定 0–10,越界告警并拒绝
> (LibreDWG `src/dwg.spec:5155-5160`、`:5213-5219`)。(4) HATCH 种子点数量按
> 剩余位数截断(LibreDWG `src/dwg.spec:4862-4878` DECODER `max_seeds =
> avail_bits/128`),避免伪造尾流。写侧黄金字节(AC1015 4601B /
> FNV 0x3a0bbc39ae6f9ecb、AC1032 7977B / 0xcc12865126b095e8)未改动。
>
> **R13/R14 类实体扩展(D-14 尾项)**:补 WIPEOUT(AcDbWipeout)与 LIGHT
> (AcDbLight)两类 CLASSES 类实体的 R13/R14 解码。WIPEOUT 数据流与 IMAGE
> 同构(LibreDWG `src/dwg2.spec:1615-1672`,规范注释 `:1619` "this must be
> an exact copy of AcDbRasterImage"):BL class_version(0–10 越界拒绝)→
> 3BD pt0 / uvec / vvec → 2RD image_size → BS display_props → B clipping →
> RC brightness/contrast/fade →(R2010+)B clip_mode → BS clip_boundary_type
> (1 = 矩形固定 4 个 RD;2 = BL 数量 + N×2RD)→ 句柄流 imagedef(340) →
> imagedefreactor(360);开头的 `HANDLE_UNKNOWN_BITS`(`:1617`)在 LibreDWG
> 解码器里只做日志并复位位流(`src/decode.c:6011-6040`),不消费位。LIGHT
> 基础段按 `src/dwg2.spec:2374-2408`:BL class_version → T name → BL type →
> B status → CMC light_color → B plot_glyph → BD intensity → 3BD position /
> target → BL attenuation_type → B use_attenuation_limits → BD start/end →
> BD hotspot/falloff → B cast_shadows → BL shadow_type → BS shadow_map_size →
> RCd shadow_map_softness;其后的 photometric 段是否存在由 NOD 变量字典
> `LIGHTINGUNITS == "2"` 决定(`:2410-2418` 的 DECODER 读变量字典而非位流
> 字段),解码侧按"基础段后是否仍有剩余位"判定:有则先读 B
> has_photometric_data,再按 `:2422-2452` 读 IES 段,读完必须与数据区终点
> 按位对齐,否则拒绝该对象并告警,不猜测。类型码取 LibreDWG 规范类号
> Wipeout=731 / Light=658(`src/classes.c:1721` / `:1648`)作读侧判别值,
> 写入器 CLASSES 注册表不登记这两类、写侧字节不变。类名映射仅在 R13/R14
> 生效,其余版本保持 Unused(仍计入 `entity_unsupported` 并逐条告警);
> 已映射类型字段解码失败时写"类实体 <name> 解码失败(字段布局不匹配)"
> 告警,对象仍计入 `entity_objects`(`decoded=false`),不静默丢弃。真实
> 样本(LibreDWG example_r13/r14):R13 `entity_decoded` 5286→5289、
> `entity_consistent` 5286→5289、`entity_unsupported` 4→1(WIPEOUT 2/2、
> LIGHT 1/1 残差 0;ACAD_TABLE 仍 unsupported);R14 257→260、5→2
> (WIPEOUT 2/2、LIGHT 1/1;MULTILEADER/ACAD_TABLE 保持 unsupported)。
> 写侧黄金字节(AC1015 4601B / FNV 0x3a0bbc39ae6f9ecb、AC1032 7977B /
> 0xcc12865126b095e8)未改动;`test_dwg_tables` 新增 4 用例(WIPEOUT
> R13/R14 多边形、LIGHT R13 基础段 / R14 photometric 段)锁定字段布局。
>
> **MULTILEADER(D-14 收尾)**:补 `MULTILEADER`(`AcDbMLeader`;标准类号
> 672,LibreDWG `src/classes.c:298` / `:1662`)的 R14 CLASSES 类实体解码,
> 字段顺序照 `src/dwg2.spec:1348-1512`(`DWG_ENTITY (MULTILEADER)`)的二进制
> 路径:`num_leaders` BL → 每条引线(lastleaderlinepoint / dogleg_vector、
> break 表、branch_index、dogleg_length、折线点与 break、line_index)→
> 注记上下文(宏 `MLEADER_CONTEXT_DATA_fields` `:1277-1342`:scale_factor /
> 基线 / 字高 / 箭头尺寸 / 间距、`has_content_txt` 的 MTEXT 字段与文本样式
> 句柄、或 `has_content_blk` 的块表句柄与 4×4 变换、base / base_dir /
> base_vert)→ 基础字段(mleaderstyle / 标志 / 类型 / 颜色 / 线型 / 线宽 /
> 引线与文本对齐 / 块 / 注释性)→ 箭头表(`VERSIONS(R_14,R_2007)`)→ 块标签
> 表(`SINCE(R_14)`)→ 尾部对齐字段;开头的 `HANDLE_UNKNOWN_BITS`(`:1350`)
> 在 LibreDWG 解码器只记日志并复位位流、不消费位(`src/decode.c:6011-6040`)。
> 句柄流按 "公共实体句柄 → 实体专属句柄"(`src/decode.c:4455-4565`):
> 上下文内容句柄 → mleaderstyle / line_ltype / 箭头 / 文本 / 块样式及箭头、
> 块标签句柄。类名映射仅在 **R14** 生效:R2010b+ 另有 class_version、引线
> 扩展段、attach_* 等布局未用真实样本验证;R13 真实样本只有 CLASSES 注册而
> 无实例,故 R13/其余版本保持 Unused(计入 `entity_unsupported` 并逐条
> 告警)。读完字段后必须与数据区终点按位精确对齐,否则写
> "MULTILEADER 数据区残差 N 位(字段布局不匹配)"并拒绝该对象,不返回
> 半成品。真实样本(LibreDWG example_r13/r14、r14/Leader):R14
> `entity_decoded` 260→261、`entity_consistent` 260→261、
> `entity_unsupported` 2→1(MULTILEADER 1/1、数据区残差 0,文本内容
> `xx\P\pxt1;xx`;仅剩 ACAD_TABLE 未支持);`r14/Leader.dwg` 20→21、1→0
> (MULTILEADER 1/1、残差 0,文本内容 "LEADER");R13 5289/5289 不变
> (MULTILEADER 仅有 CLASSES 注册、无实例)。`dwg_compare` 新增 MULTILEADER
> 字段签名(比较/导出通道);写侧黄金字节(AC1015 4601B /
> FNV 0x3a0bbc39ae6f9ecb、AC1032 7977B / 0xcc12865126b095e8)未改动;
> `test_dwg_tables` 新增 3 用例(R14 正向、布局不匹配拒绝、R13 门控)锁定
> 字段布局与降级路径。
### `io_dwg.h` — DWG 原生识别 + 转换通道
```cpp
namespace vde::foundation {
enum class DwgVersion { Unknown, R12, R13, R14, R2000, R2004, R2007, R2010, R2013, R2018 };
const char* dwg_version_name(DwgVersion); // "R2018"
const char* dwg_version_magic(DwgVersion); // "AC1032"
DwgVersion dwg_version_from_magic(const char* magic6); // 6 字节 ASCII → 版本
DwgVersion dwg_version_from_bytes(const uint8_t* data, std::size_t size);
bool dwg_version_is_r2004_plus(DwgVersion); // R2004 起有加密节表+压缩段
struct DwgFileInfo { // inspect_dwg 结果
DwgVersion version; std::string version_magic, version_name;
std::uint64_t file_size; bool is_dwg, r2004_plus; std::string error;
bool valid() const;
};
DwgFileInfo inspect_dwg(const std::string& filepath); // 读文件头
DwgFileInfo inspect_dwg_memory(const uint8_t* data, std::size_t size); // 读内存头
struct DwgConverterInfo { bool found; std::string executable, engine, license, command; };
DwgConverterInfo find_dwg_reader(); // DWG→DXF:VDE_DWG_READ_CMD → PATH 上的 dwg2dxf
DwgConverterInfo find_dwg_writer(); // DXF→DWG:VDE_DWG_WRITE_CMD → PATH 上的 dxf2dwg
std::string find_executable_on_path(const std::string& name);
std::string expand_converter_command(const std::string& tmpl, const std::string& in, const std::string& out);
struct DwgConvertResult { bool success; std::string output_path, tool; int exit_code; std::vector<std::string> messages; };
DwgConvertResult convert_dwg_to_dxf(const std::string& dwg, const std::string& dxf);
DwgConvertResult convert_dxf_to_dwg(const std::string& dxf, const std::string& dwg);
} // namespace vde::foundation
```
> **三层策略**:①原生识别(`inspect_dwg`,零依赖,始终执行)②通道层
> (`convert_dwg_to_dxf` / `convert_dxf_to_dwg`,**独立子进程**调用外部工具,
> GPLv3 不传染)③插件层(`DwgBridge::load`,运行时加载)。外部转换器可通过
> 环境变量 `VDE_DWG_READ_CMD` / `VDE_DWG_WRITE_CMD` 注入自定义模板,占位符
> 为 `{in}` / `{out}`。
### `io_dwg_plugin.h` — DWG 插件接口
```cpp
namespace vde::foundation {
struct DwgResult {
bool success = false;
std::vector<brep::BrepModel> bodies;
std::string metadata_json; // 图层/线型/标注等元数据(JSON)
std::string error_message;
};
class DwgImporter { // 抽象导入器接口(Apache 2.0,外部插件实现)
public:
virtual ~DwgImporter() = default;
virtual const char* name() const = 0; // "libreDWG 0.14" / "ODA 2026"
virtual const char* license() const = 0; // "GPLv3" / "Commercial"
virtual DwgResult read_file(const std::string& path) = 0;
virtual DwgResult read_memory(const uint8_t* data, size_t size) = 0;
};
class DwgBridge { // DWG 桥接器:动态加载外部插件
public:
static bool load(const std::string& plugin_path); // 加载插件 .so/.dll
static void unload();
static bool is_loaded();
static DwgResult import(const std::string& path); // 委托给已加载插件
static std::string plugin_name();
static std::string plugin_license();
};
DwgResult import_dwg_plugin(const std::string& path); // 便捷导入(未加载插件时返回安装指引)
} // namespace vde::foundation
```
### `io_stl.h` — STL 格式
```cpp
namespace vde::foundation {
struct StlTriangle {
Vector3D normal; // 单位法向量
Point3D v0, v1, v2; // 三个顶点(右手法则 CCW 顺序)
// 便捷分量访问:v0x(), v0y(), v0z(), v1x(), ..., v2z()
};
std::vector<StlTriangle> read_stl(const std::string& filepath); // 自动检测 ASCII/二进制;失败抛 std::runtime_error
bool write_stl(const std::string& filepath, const std::vector<StlTriangle>& tris); // 二进制
bool write_stl_ascii(const std::string& filepath, const std::vector<StlTriangle>& tris); // ASCII
// float 精度变体(避免 double↔float 显式转换)
struct StlTrianglef { Vector3f normal; Point3f v0, v1, v2; };
StlTrianglef to_stl_trianglef(const StlTriangle& t);
StlTriangle from_stl_trianglef(const StlTrianglef& t);
} // namespace vde::foundation
```
### `io_obj.h` — Wavefront OBJ
```cpp
namespace vde::foundation {
struct ObjMeshData {
std::vector<Point3D> vertices;
std::vector<Point2D> texcoords; // 可能为空
std::vector<Vector3D> normals; // 可能为空
std::vector<std::vector<int>> faces; // 0-based 顶点索引(始终填充)
std::vector<std::vector<int>> face_texcoords; // 与 faces 等长;无纹理时为空
std::vector<std::vector<int>> face_normals; // 与 faces 等长;无法线时为空
std::vector<std::string> face_materials; // usemtl 材质名
[[nodiscard]] bool has_texcoords() const;
};
ObjMeshData read_obj(const std::string& filepath); // 失败抛 std::runtime_error
bool write_obj(const std::string& filepath, const ObjMeshData& data); // 输出 1-based 索引
} // namespace vde::foundation
```
### `io_collada.h` — COLLADA DAE
```cpp
namespace vde::foundation {
// 材质颜色信息(Phong 模型参数)
struct ColladaMaterial {
std::string name, effect_id;
float diffuse_r = 0.8f, diffuse_g = 0.8f, diffuse_b = 0.8f;
float specular_r = 0.0f, specular_g = 0.0f, specular_b = 0.0f;
float ambient_r = 0.2f, ambient_g = 0.2f, ambient_b = 0.2f;
float emission_r = 0.0f, emission_g = 0.0f, emission_b = 0.0f;
float shininess = 1.0f, transparency = 1.0f; // 1.0 = 不透明
};
// 导入:每个 geometry 节点生成一个 BrepModel(支持 COLLADA 1.4 / 1.5)
[[nodiscard]] std::vector<brep::BrepModel> import_collada(const std::string& path);
// 导出:每个 BrepModel 对应一个 geometry → visual_scene 节点
bool export_collada(const std::vector<brep::BrepModel>& bodies,
const std::string& path,
const std::vector<ColladaMaterial>& materials = {});
} // namespace vde::foundation
```
### `io_amf.h` — AMF 格式(ISO/ASTM 52915)
```cpp
namespace vde::foundation {
struct AmfMesh {
mesh::HalfedgeMesh mesh;
std::string name; // 对象名称
std::string material_name; // 材质名称
float diffuse_r = 0.8f, diffuse_g = 0.8f, diffuse_b = 0.8f, diffuse_a = 1.0f; // RGBA 0.0-1.0
std::string description, author, license; // 元数据
};
[[nodiscard]] brep::BrepModel import_amf(const std::string& path); // 首个 object
[[nodiscard]] std::vector<AmfMesh> import_amf_all(const std::string& path); // 多对象
bool export_amf(const brep::BrepModel& body, const std::string& path,
const std::string& name = "Model");
bool export_amf_multi(const std::vector<AmfMesh>& meshes, const std::string& path);
} // namespace vde::foundation
```
### `io_vrml.h` — VRML
```cpp
namespace vde::foundation {
struct VrmlMaterial {
std::string name;
float diffuse_r = 0.8f, diffuse_g = 0.8f, diffuse_b = 0.8f;
float specular_r = 0.0f, specular_g = 0.0f, specular_b = 0.0f;
float emissive_r = 0.0f, emissive_g = 0.0f, emissive_b = 0.0f;
float ambient_intensity = 0.2f, shininess = 0.2f, transparency = 0.0f; // 0.0 = 不透明
};
struct VrmlMeshData {
mesh::HalfedgeMesh mesh;
VrmlMaterial material;
std::string name;
};
[[nodiscard]] brep::BrepModel import_vrml(const std::string& path); // 首个 IndexedFaceSet
[[nodiscard]] std::vector<VrmlMeshData> import_vrml_all(const std::string& path); // 多 Shape
bool export_vrml(const brep::BrepModel& body, const std::string& path,
const VrmlMaterial& material = VrmlMaterial{}); // VRML 2.0 (VRML97)
bool export_vrml_multi(const std::vector<VrmlMeshData>& meshes, const std::string& path);
} // namespace vde::foundation
```
### `io_ply.h` — PLY 格式
```cpp
namespace vde::foundation {
// 支持 ASCII 与二进制(小端序);元素:vertex(位置/法线/颜色)、face
mesh::HalfedgeMesh read_ply(const std::string& filepath); // 失败抛 std::runtime_error
void write_ply(const std::string& filepath, const mesh::HalfedgeMesh& mesh); // ASCII 输出
} // namespace vde::foundation
```
### `io_3mf.h` — 3MF 格式
```cpp
namespace vde::foundation {
struct ThreeMFMesh {
mesh::HalfedgeMesh mesh;
std::string name;
std::vector<float> vertex_colors; // 可选逐顶点 RGB(3*nv 个 float)
};
[[nodiscard]] std::vector<ThreeMFMesh> read_3mf(const std::string& filepath);
bool write_3mf(const std::string& filepath,
const std::vector<ThreeMFMesh>& meshes,
const std::string& creator = "ViewDesignEngine"); // creator 写入元数据
} // namespace vde::foundation
```
### `industrial_formats.h` — 工业格式(JT/Parasolid/ACIS/IFC/STEP AP242/PDF 3D)
```cpp
namespace vde::io {
// === JT (ISO 14306) ===
enum class JTSegmentType : uint8_t { LogicalSceneGraph=1, Part=2, Instance=3, MeshLOD=4, Brep=5, MetaData=6, PMI=7 };
struct JtSegmentHeader { uint32_t segment_type, segment_offset, segment_length, attributes; };
struct JTOptions { bool load_brep=true, load_mesh=true; int max_lod=3; bool load_pmi=false, load_meta=false; };
[[nodiscard]] brep::BrepModel import_jt(const std::string& path, const JTOptions& opts = {});
[[nodiscard]] brep::BrepModel import_jt_binary(const uint8_t* data, size_t size, const JTOptions& opts = {});
bool export_jt(const brep::BrepModel& body, const std::string& path);
// === Parasolid XT ===
enum class ParasolidFormat { Binary, Text, Neutral };
struct XtBinaryHeader { char magic[4]; uint32_t version, float_count, int_count, entity_count, float_offset, int_offset, entity_offset, endian_check; /* parse()/encode() */ };
struct XtBinaryEntity { uint32_t type; uint32_t float_start, float_len; uint32_t int_start, int_len; std::vector<uint32_t> refs; };
[[nodiscard]] brep::BrepModel import_parasolid_xt(const std::string& path); // .x_t / .x_b
[[nodiscard]] brep::BrepModel import_parasolid_xt_binary(const uint8_t* data, size_t size);
void export_parasolid_xt(const brep::BrepModel& body, const std::string& path); // 文本
void export_parasolid_xt_binary(const brep::BrepModel& body, const std::string& path); // 二进制文件
[[nodiscard]] std::string export_parasolid_xt_binary_str(const brep::BrepModel& body); // 二进制字符串
// === ACIS SAT ===
enum class ACISVersion { V7=700, V16=1600, V21=2100, V27=2700, R2024=2900 };
struct SabHeader { char magic[4]; uint32_t data_size, version, str_table_size; };
[[nodiscard]] brep::BrepModel import_acis_sat(const std::string& path); // .sat / .sab
[[nodiscard]] brep::BrepModel import_acis_sat_binary(const uint8_t* data, size_t size);
void export_acis_sat(const brep::BrepModel& body, const std::string& path,
ACISVersion version = ACISVersion::V27);
// === IFC (ISO 16739) ===
enum class IfcEntityType { Unknown, IfcProject, IfcSite, IfcBuilding, IfcWall, IfcSlab, IfcBeam, IfcColumn, IfcDoor, /* ... */ };
[[nodiscard]] std::vector<brep::BrepModel> import_ifc(const std::string& path); // 每个产品一个体
void export_ifc(const std::vector<brep::BrepModel>& bodies, const std::string& path); // 轴对齐盒→ExtrudedAreaSolid,其余→FacetedBrep
// === STEP AP242 ===
struct StepPMIAnnotation { std::string type, id, description; double nominal_value, upper_tolerance, lower_tolerance; std::string datum_system; };
struct StepAP242Options { bool include_pmi=true, include_tolerance=true, include_material=true, include_validation=true; };
struct StepAP242ImportResult { std::vector<brep::BrepModel> bodies; std::vector<StepPMIAnnotation> annotations; };
[[nodiscard]] std::string export_step_ap242(const std::vector<brep::BrepModel>& bodies, const std::vector<StepPMIAnnotation>& annotations = {}, const StepAP242Options& opts = {});
void export_step_ap242_file(const std::string& path, const std::vector<brep::BrepModel>& bodies, const std::vector<StepPMIAnnotation>& annotations = {}, const StepAP242Options& opts = {});
[[nodiscard]] StepAP242ImportResult import_step_ap242_from_string(const std::string& step_data);
[[nodiscard]] StepAP242ImportResult import_step_ap242(const std::string& path); // .stp / .step
// === PDF 3D ===
struct Pdf3dPmiEntity { std::string id, label, type, text; core::Point3D position; core::Vector3D normal; double nominal_value, tolerance_upper, tolerance_lower; std::string unit, datum_references; };
inline constexpr uint32_t kU3DPmiBlockType = 0xFFFFFFF1u; // U3D 语义实体块(PMI),ECMA-363 未知块可跳过
[[nodiscard]] std::vector<uint8_t> export_pdf3d(const brep::BrepModel& body); // U3D 嵌入 (ECMA-363)
[[nodiscard]] std::vector<uint8_t> export_pdf3d(const brep::BrepModel& body, const std::vector<Pdf3dPmiEntity>& pmi); // 网格声明块后追加 PMI 语义实体块
void export_pdf3d_file(const std::string& path, const brep::BrepModel& body);
void export_pdf3d_file(const std::string& path, const brep::BrepModel& body, const std::vector<Pdf3dPmiEntity>& pmi);
} // namespace vde::io
```
### `serializer.h` — 网格二进制序列化
```cpp
namespace vde::foundation {
// 扁平化网格数据(全部三角形,face_valence 固定为 3)
struct SerializedMesh {
uint32_t vertex_count, face_count;
std::vector<double> vertices; // x0 y0 z0 x1 y1 z1 ...
std::vector<int32_t> face_indices; // v0_0 v0_1 v0_2 v1_0 ...
std::vector<int32_t> face_valence; // 每面顶点数(当前固定为 3)
};
// 二进制序列化器:魔数 "VDEGEOM\0" + 版本号 + 标志位 + 网格数据
class BinarySerializer {
public:
static std::vector<uint8_t> serialize(const mesh::HalfedgeMesh& mesh);
static mesh::HalfedgeMesh deserialize(const std::vector<uint8_t>& data); // 校验失败抛异常
static bool write_file(const std::string& path, const mesh::HalfedgeMesh& mesh);
static mesh::HalfedgeMesh read_file(const std::string& path); // 失败抛异常
};
constexpr uint64_t VDE_MAGIC = 0x56444547454F4D00ULL; // "VDEGEOM\0"
constexpr uint32_t VDE_FORMAT_VERSION = 1;
} // namespace vde::foundation
```
### `vde_format.h` — VDE 原生格式(.vde)
```cpp
namespace vde::foundation {
constexpr uint32_t VDE_MAGIC_FOURCC = 0x31454456; // "VDE1"(小端序)
constexpr uint32_t VDE_FILE_VERSION = 1;
constexpr uint32_t VDE_FLAG_HAS_HISTORY = 0x00000001; // 含建模历史
constexpr uint32_t VDE_FLAG_HAS_ATTRIBUTES = 0x00000002; // 含属性数据
constexpr uint32_t VDE_FLAG_HAS_TRIMMED = 0x00000004; // 含裁剪曲面
// 32 字节文件头:magic(4) + version(4) + flags(4) + data_offset(4) + reserved(16)
struct VdeHeader {
uint32_t magic, version, flags, data_offset;
uint8_t reserved[16];
VdeHeader();
static VdeHeader parse(const uint8_t* data, size_t size);
void encode(std::vector<uint8_t>& buf) const;
[[nodiscard]] bool is_valid() const;
};
// 序列化段类型(每段 [section_id:uint16][section_size:uint64][data...])
enum class SerializationSection : uint16_t {
SECTION_HEADER = 0, SECTION_TOPOLOGY = 1, SECTION_GEOMETRY = 2,
SECTION_TOLERANCE = 3, SECTION_ATTRIBUTES = 4, SECTION_HISTORY = 5,
};
// 属性数据结构
struct VdeVertexAttribute { int vertex_id = -1; std::string name; uint32_t color_rgba = 0xFFFFFFFF; std::string custom_data; };
struct VdeEdgeAttribute { int edge_id = -1; std::string name; uint32_t color_rgba = 0xFFFFFFFF; std::string custom_data; };
struct VdeFaceAttribute { int face_id = -1; std::string name; uint32_t color_rgba = 0xFFFFFFFF; std::string custom_data; };
struct VdeBodyAttribute { int body_id = -1; std::string name; std::string custom_data; };
struct VdeAttributes {
std::vector<VdeVertexAttribute> vertex_attrs;
std::vector<VdeEdgeAttribute> edge_attrs;
std::vector<VdeFaceAttribute> face_attrs;
std::vector<VdeBodyAttribute> body_attrs;
};
// 主 API(失败抛 std::runtime_error)
bool save_vde(const brep::BrepModel& body, const std::string& path,
const VdeAttributes& attrs = {},
const std::vector<brep::FeatureNode>* history = nullptr);
[[nodiscard]] brep::BrepModel load_vde(const std::string& path);
[[nodiscard]] brep::BrepModel load_vde_with_attrs(const std::string& path, VdeAttributes& out_attrs);
bool save_vde_json(const brep::BrepModel& body, const std::string& path,
const VdeAttributes& attrs = {}); // 人类可读 JSON(调试用)
[[nodiscard]] std::vector<uint8_t> serialize_vde(const brep::BrepModel& body,
const VdeAttributes& attrs = {},
const std::vector<brep::FeatureNode>* history = nullptr);
[[nodiscard]] brep::BrepModel deserialize_vde(const std::vector<uint8_t>& data);
} // namespace vde::foundation
```
### `format_utils.h` — 格式工具函数
```cpp
namespace vde::foundation {
std::string fmt_double(double v, int precision = 12); // 科学计数法,12 位有效数字;NaN→"0.0",Inf→"1e30"/"-1e30"
std::string fmt_iges_real(double v, int precision = 12); // 同 fmt_double,但指数用 'D' 标记(IGES 标准)
std::string fmt_point(const core::Point3D& p, bool use_d = false); // "x,y,z" 逗号分隔
std::string pad72(const std::string& s); // 补齐/截断到恰好 72 字符(IGES 行宽)
std::string format_iges_line(const std::string& data, char section_char, int seq); // 72 列数据 + 8 列序号 + '\n'
} // namespace vde::foundation
```
### `math_types.h` — 基础数学类型
```cpp
namespace vde::foundation {
// 通用模板(Eigen 列向量)
template <typename T, size_t Dim> using Point = Eigen::Matrix<T, Dim, 1>;
template <typename T, size_t Dim> using Vector = Eigen::Matrix<T, Dim, 1>; // 语义区分点(位置)/向量(方向)
template <typename T> using Matrix3 = Eigen::Matrix<T, 3, 3>;
template <typename T> using Matrix4 = Eigen::Matrix<T, 4, 4>;
using Point2D = Point<double, 2>; using Point3D = Point<double, 3>;
using Point2f = Point<float, 2>; using Point3f = Point<float, 3>;
using Point4D = Eigen::Matrix<double, 4, 1>; // 齐次点(仿射变换)
using Vector2D = Vector<double, 2>; using Vector3D = Vector<double, 3>;
using Vector2f = Vector<float, 2>; using Vector3f = Vector<float, 3>;
using Matrix3D = Matrix3<double>; using Matrix4D = Matrix4<double>;
} // namespace vde::foundation
```
### `tolerance.h` — 分层容差管理
```cpp
namespace vde::foundation {
class Tolerance {
public:
Tolerance(double absolute = 1e-6, double relative = 1e-8,
double angular = 1e-8, double snapping = 1e-4);
// 判定
bool points_equal(const Eigen::MatrixXd& a, const Eigen::MatrixXd& b) const; // 欧氏距离 < absolute
template <typename T> bool is_zero(T value) const; // |value| < absolute
template <typename T> bool equals(T a, T b) const; // |a-b| < absolute + relative*max(|a|,|b|)
// 访问
double absolute() const; double relative() const; double angular() const; double snapping() const;
// 分层:继承并缩放
Tolerance tighten(double factor = 0.1) const; // 收紧(factor < 1)
Tolerance relax(double factor = 10.0) const; // 放宽(factor > 1)
static Tolerance min(const Tolerance& a, const Tolerance& b); // 每项取 min(更严格)
// 全局实例(线程局部存储)
static Tolerance& global();
static void set_global(const Tolerance& tol);
// 预设精度等级
static constexpr double Modeling() { return 1e-6; } // 建模级
static constexpr double Fitting() { return 1e-3; } // 拟合级
static constexpr double Intersection() { return 1e-8; } // 求交级
static constexpr double Snapping() { return 1e-4; } // 吸附级
};
// 局部容差作用域(RAII:构造设置、析构自动恢复)
class ToleranceScope {
public:
explicit ToleranceScope(const Tolerance& tol);
~ToleranceScope();
};
} // namespace vde::foundation
```
### `error_codes.h` — 统一错误码
```cpp
namespace vde::foundation {
// 分段编码:0=成功;1xxx=foundation;2xxx=core;3xxx=curves;4xxx=mesh;5xxx=brep;6xxx=sdf;7xxx=capi
enum class ErrorCode : int32_t {
SUCCESS = 0,
// 1xxx foundation(文件/格式 IO)
ERR_FILE_NOT_FOUND = 1001, ERR_FILE_OPEN_FAILED = 1002, ERR_FILE_WRITE_FAILED = 1003,
ERR_FILE_READ_FAILED = 1004, /* ... */ ERR_FILE_ALREADY_EXISTS = 1008,
ERR_FORMAT_INVALID = 1101, ERR_FORMAT_UNSUPPORTED = 1102, /* ... */ ERR_FORMAT_MAGIC_MISMATCH = 1106,
ERR_VDE_HEADER_INVALID = 1201, /* ... */ ERR_VDE_DESERIALIZE_FAILED = 1207,
ERR_STEP_PARSE = 1301, /* ... */ ERR_DXF_PARSE = 1371,
// 2xxx core(几何计算 / CAM / 并发)
ERR_DEGENERATE_GEOMETRY = 2001, /* ... */ ERR_TRIANGULATION_FAILED = 2106,
ERR_CAM_TOOLPATH_GENERATION = 2201, /* ... */ ERR_TRANSACTION_ROLLBACK = 2305,
// 3xxx curves(曲线 / 曲面 / IGA)
ERR_CURVE_DEGREE_INVALID = 3001, /* ... */ ERR_SURFACE_FAIRING = 3110,
ERR_IGA_MESH_INVALID = 3201, ERR_IGA_REFINEMENT_FAILED = 3202,
// 4xxx mesh
ERR_MESH_EMPTY = 4001, /* ... */ ERR_POINT_CLOUD_NOISE = 4205,
// 5xxx brep(拓扑 / 布尔 / 特征 / 装配 / 钣金 / PMI / FFD)
ERR_BREP_TOPOLOGY_INVALID = 5001, /* ... */ ERR_FFD_INVALID = 5601,
// 6xxx sdf
ERR_SDF_EVALUATE_FAILED = 6001, /* ... */ ERR_SDF_PRIMITIVE_INVALID = 6006,
// 7xxx capi
ERR_CAPI_NULL_HANDLE = 7001, /* ... */ ERR_CAPI_UNKNOWN_ERROR = 7999,
};
struct ErrorInfo {
ErrorCode code; std::string message; // 中文错误描述
std::string module; // 所属模块
std::string file; int line; // 源位置
ErrorInfo(); // 默认 SUCCESS
ErrorInfo(ErrorCode c, std::string msg, std::string mod, std::string f = "", int l = 0);
};
std::string error_message(ErrorCode code); // 错误码 → 中文描述
constexpr bool is_error(ErrorCode code) noexcept; // != SUCCESS
constexpr bool is_success(ErrorCode code) noexcept; // == SUCCESS
std::string error_module(ErrorCode code); // 错误码 → 所属模块名
} // namespace vde::foundation
```
### `interval.h` — 区间算术与谓词验证
```cpp
namespace vde::foundation {
class Interval {
public:
double lo, hi;
Interval(); // 空区间 [0, 0]
Interval(double v); // 点区间 [v, v]
Interval(double l, double h); // 自动交换保证 lo ≤ hi
[[nodiscard]] double mid() const; // (lo+hi)/2
[[nodiscard]] double width() const; // hi-lo
[[nodiscard]] bool contains(double v) const; // lo ≤ v ≤ hi
[[nodiscard]] bool is_exact(double eps = 1e-12) const; // 宽度 < eps
[[nodiscard]] bool overlaps(const Interval& o) const;
[[nodiscard]] int cmp(const Interval& o) const; // -1 确定小于 / 1 确定大于 / 0 重叠无法确定
Interval operator+(const Interval& o) const; // [lo+o.lo, hi+o.hi]
Interval operator-(const Interval& o) const; // [lo-o.hi, hi-o.lo]
Interval operator*(const Interval& o) const; // 四项乘积取 min/max
Interval operator/(const Interval& o) const; // 除区间跨零时返回极大区间
Interval operator-() const;
[[nodiscard]] Interval sqrt() const;
static Interval from_double(double v, double error = 0); // 含误差带
static Interval from_coord(double v); // 含 ULP 误差带:|v|*2.22e-16 + 1e-300
};
// 二维定向行列式的区间验证
inline Interval orient_2d_interval(double ax, double ay, double bx, double by, double cx, double cy);
inline int orient_2d_verified(double ax, double ay, double bx, double by, double cx, double cy);
// 返回 -1 = 确认 Clockwise;1 = 确认 CounterClockwise;0 = 无法确定(需升级 GMP/自适应精度)
} // namespace vde::foundation
```
### `predicates.h` — 统一谓词接口
```cpp
namespace vde::foundation {
// 编译时选择后端:定义 VDE_USE_GMP → exact::GmpExact(零误差),否则 AdaptiveDouble(默认)
struct Predicates {
using Backend = /* exact::GmpExact 或 AdaptiveDouble */;
static exact::Orientation orient_2d(const Point2D& a, const Point2D& b, const Point2D& c);
static exact::Orientation orient_3d(const Point3D& a, const Point3D& b, const Point3D& c, const Point3D& d);
static exact::CircleTest in_circle(const Point2D& a, const Point2D& b, const Point2D& c, const Point2D& d);
};
// 便捷封装(推荐的对外 API)
inline exact::Orientation orient(const Point2D& a, const Point2D& b, const Point2D& c);
inline exact::Orientation orient(const Point3D& a, const Point3D& b, const Point3D& c, const Point3D& d);
inline exact::CircleTest in_circle(const Point2D& a, const Point2D& b, const Point2D& c, const Point2D& d);
} // namespace vde::foundation
```
### `exact_predicates.h` — 自适应精度谓词(Shewchuk 算法)
```cpp
namespace vde::foundation::exact {
enum class Orientation { Clockwise, CounterClockwise, Collinear };
enum class CircleTest { Inside, On, Outside };
// 自适应浮点精度:先用双精度计算行列式,结果不可靠时逐步提高精度直至确定符号
Orientation orient_2d(const Point2D& a, const Point2D& b, const Point2D& c);
Orientation orient_3d(const Point3D& a, const Point3D& b, const Point3D& c, const Point3D& d);
CircleTest in_circle(const Point2D& a, const Point2D& b, const Point2D& c, const Point2D& d);
// 另有标量重载:orient_2d(ax,ay,bx,by,cx,cy) 等,避免构造临时 Point
} // namespace vde::foundation::exact
namespace vde::foundation {
// 自适应双精度后端(默认),封装 exact::* 函数
struct AdaptiveDouble {
static exact::Orientation orient_2d(const Point2D& a, const Point2D& b, const Point2D& c);
static exact::Orientation orient_3d(const Point3D& a, const Point3D& b, const Point3D& c, const Point3D& d);
static exact::CircleTest in_circle(const Point2D& a, const Point2D& b, const Point2D& c, const Point2D& d);
};
} // namespace vde::foundation
```
### `exact_predicates_gmp.h` — GMP 精确谓词后端(可选)
```cpp
// 仅在定义 VDE_USE_GMP 宏且链接 GMP 库时编译(性能约为自适应双精度的 1/10 ~ 1/50)
namespace vde::foundation::exact {
struct GmpExact { // 基于 mpq_class 有理数运算,零舍入误差
using Rational = mpq_class;
static Orientation orient_2d(const Point2D& a, const Point2D& b, const Point2D& c);
static Orientation orient_3d(const Point3D& a, const Point3D& b, const Point3D& c, const Point3D& d);
static CircleTest in_circle(const Point2D& a, const Point2D& b, const Point2D& c, const Point2D& d);
};
} // namespace vde::foundation::exact
```
### `memory_pool.h` — 固定块内存池
```cpp
namespace vde::foundation {
// 空闲链表实现 O(1) 分配/释放;不调用构造函数/析构函数,仅管理原始内存
// 适合 POD 类型或通过 placement new 手动管理生命周期的对象(如半边网格的顶点/面)
template <typename T>
class MemoryPool {
public:
explicit MemoryPool(size_t chunk_size = 1024); // 每块可容纳对象数
~MemoryPool(); // 统一释放所有 chunk
T* allocate(size_t n = 1); // O(1);空闲链表为空时自动分配新 chunk
void deallocate(T* p, size_t = 1); // O(1);归还到空闲链表头部
};
} // namespace vde::foundation
```
### `vde_log.h` — 轻量结构化日志(VDE D10)
```cpp
namespace vde::foundation {
enum class LogLevel : int { Trace = 0, Debug = 1, Info = 2, Warn = 3, Error = 4, Critical = 5, Off = 6 };
const char* log_level_label(LogLevel level); // 短标签:"I" / "W" / "E"
const char* log_level_name(LogLevel level); // 完整名称:"INFO" / "WARN"
LogLevel log_level_from_string(const std::string& name); // 解析失败返回 Info
struct LogMessage {
LogLevel level;
std::string module, event, message; // 模块标签 / 事件名 / 消息
std::vector<std::pair<std::string, std::string>> fields; // 键值字段
int64_t timestamp_us; // Unix 微秒时间戳
uint64_t sequence; // 全局序号
[[nodiscard]] std::string to_string() const; // 单行 key=value 风格
};
namespace vde_log {
void set_level(LogLevel level); // 全局最小级别
LogLevel level();
void set_output(std::ostream* os); // 默认 std::cout;nullptr 关闭
void set_sink(std::function<void(const LogMessage&)> sink); // 自定义接收器;空函数清除
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<std::pair<std::string, std::string>>& fields);
// 便捷 API(模块标签 + 事件名 + 消息 + 可选字段)
template <typename... Field>
void trace(const std::string& module, const std::string& event,
const std::string& message, const Field&... fields);
// debug / info / warn / error / critical 同构
// 字段构造辅助(std::string / const char* / long long / int / double / bool 重载)
inline std::pair<std::string, std::string> field(const std::string& key, const std::string& value);
// field(key, value) 用法:vde_log::info("brep", "boolean_union", "ok", vde_log::field("faces", 12));
} // namespace vde_log
} // namespace vde::foundation
```
---
## 代码示例
### 示例 1: glTF 导入与再导出
```cpp
#include <vde/foundation/io_gltf.h>
#include <vde/mesh/halfedge_mesh.h>
using namespace vde;
// 导入 glTF
auto result = foundation::import_gltf("model.glb");
if (result.success) {
for (auto& mesh : result.meshes) {
std::cout << "Faces: " << mesh.num_faces() << "\n";
}
// 重新导出为 GLB(含法线)
foundation::GltfOptions opts;
opts.binary = true;
opts.include_normals = true;
foundation::write_gltf("model_out.glb", result.meshes[0], opts);
}
```
### 示例 2: DXF 解析与处理
```cpp
#include <vde/foundation/io_dxf.h>
using namespace vde;
// 解析 DXF
auto doc = foundation::import_dxf("floor_plan.dxf");
std::cout << "DXF 版本: " << foundation::dxf_version_name(doc.version) << "\n";
std::cout << "实体数量: " << doc.entities.size() << "\n";
std::cout << "图层数量: " << doc.layers.size() << "\n";
// 统计各类型实体
for (auto& ent : doc.entities) {
std::visit([](const auto& e) {
using T = std::decay_t<decltype(e)>;
if constexpr (std::is_same_v<T, foundation::DxfLine>) {
// 线段实体
} else if constexpr (std::is_same_v<T, foundation::DxfCircle>) {
// 圆形实体
}
}, ent);
}
// 转为网格
auto mesh = foundation::to_mesh(doc);
```
### 示例 3: 工业格式导入
```cpp
#include <vde/foundation/industrial_formats.h>
using namespace vde;
// JT 导入
auto jt_model = io::import_jt("assembly.jt");
// Parasolid 导入
auto xt_model = io::import_parasolid_xt("part.x_t");
// IFC BIM 导入
auto ifc_bodies = io::import_ifc("building.ifc");
// STEP AP242 导出(含 PMI)
std::vector<io::StepPMIAnnotation> annotations = { /* ... */ };
auto step_data = io::export_step_ap242({jt_model}, annotations);
```
### 示例 4: 结构化日志
```cpp
#include <vde/foundation/vde_log.h>
using namespace vde;
// 设置全局级别并写文件
foundation::vde_log::set_level(foundation::LogLevel::Debug);
foundation::vde_log::set_output_file("vde.log");
// 结构化输出(模块标签 + 事件名 + 键值字段)
foundation::vde_log::info("brep", "boolean_union", "union completed",
foundation::vde_log::field("faces_a", 12),
foundation::vde_log::field("faces_b", 8),
foundation::vde_log::field("duration_ms", 3.25));
```