Files

483 lines
21 KiB
C++
Raw Permalink 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.
#pragma once
/**
* @file feature_tree.h
* @brief 特征树 / 历史式建模 (E4b) — vde::feature
*
* 参数化建模基础设施(VDE-583):以有序特征列表描述零件建模历史,
* 每次编辑/重排后按序重放(rebuild)得到最新几何,支持:
* - CRUD:add / insert / reorder / edit / delete / suppress
* - 历史导航:rollback_to / rollforward_to / current_position
* - 拓扑命名:特征产生的面/边在参数变化后仍可跨重建解析
* - 持久化:文本序列化 / 反序列化
*
* 特征求值使用真实 B-Rep 内核(modeling + SSI 布尔),取代旧的
* AABB 占位实现。特征按列表顺序依次作用于"运行模型":
* - 基本体 / 挤出 / 布尔并 → 与运行模型做并集(组合式建模)
* - 圆角 / 倒角 / 抽壳 → 直接修改运行模型
* - 布尔交 / 差 → 运行模型与工具体(FeatureParams::tool_body)运算
*
* @ingroup feature
*/
#include "vde/brep/brep.h"
#include "vde/brep/topo_naming.h"
#include <istream>
#include <ostream>
#include <string>
#include <vector>
namespace vde::feature {
/**
* @brief 特征类型
*
* 覆盖 VDE-583 中当前内核可真实求值的特征子集。
*/
enum class FeatureType {
PrimitiveBox, ///< 长方体(w, h, d)
PrimitiveCylinder, ///< 圆柱(radius, height[, segments])
PrimitiveSphere, ///< 球(radius[, seg_u, seg_v])
Extrude, ///< 挤出(radius, height)→ 圆轮廓挤出为柱体
Fillet, ///< 圆角(edge_id, radius)
Chamfer, ///< 倒角(edge_id, distance)
Shell, ///< 抽壳(face_id, thickness)
BooleanUnion, ///< 布尔并(工具体 tool_body)
BooleanIntersection, ///< 布尔交(工具体 tool_body)
BooleanDifference ///< 布尔差(工具体 tool_body)
};
/// 类型名(诊断 / 序列化)
[[nodiscard]] const char* feature_type_name(FeatureType t);
/**
* @brief 特征参数
*
* values 为数值参数(按特征类型约定顺序),int_values 为整数参数
* (edge/face 索引、曲面分段数等)。布尔特征通过 tool_body 携带
* 工具体(has_tool 标记存在性)。
*/
struct FeatureParams {
std::vector<double> values; ///< 数值参数
std::vector<int> int_values; ///< 整数参数
std::string name; ///< 操作名(可选)
brep::BrepModel tool_body; ///< 布尔运算工具体
bool has_tool = false; ///< 是否携带工具体
};
/**
* @brief 特征引用(P1-4)
*
* 特征对其它特征拓扑元素(面/边)的声明式引用。解析主路径为拓扑名
* (topo_name,跨参数重建/重排稳定);无拓扑名时退化为 elem_idx 直连。
* 供 Fillet/Chamfer 引用"上一特征产生的边"、Shell 引用"面"等场景。
*/
struct FeatureReference {
int target_feature_id = -1; ///< 被引用特征 id(-1 = 仅按拓扑名解析)
int elem_type = 0; ///< 元素类型:FeatureTree::kFace / kEdge / kVertex
int elem_idx = -1; ///< 引用时的元素索引(诊断 / 直连回退)
std::string topo_name; ///< 拓扑名(解析主路径;空则退化 elem_idx 直连)
};
/**
* @brief 特征定义
*
* 特征树中的单个特征。id 在加入树时由 FeatureTree 分配(也可预置
* 正数 id);parent_id 为可选的树形父子关系(当前求值为顺序模型,
* 仅用于结构信息与依赖推导)。
*/
struct FeatureDefinition {
int id = -1; ///< 特征 id(树内唯一)
int parent_id = -1; ///< 父特征 id(-1 = 无)
std::string name; ///< 特征名
FeatureType type = FeatureType::PrimitiveBox;
bool suppressed = false; ///< 抑制(重建时跳过)
FeatureParams params; ///< 特征参数
std::vector<FeatureReference> refs; ///< 本特征声明的拓扑引用(P1-4)
};
/**
* @brief 特征依赖关系(P1-4)
*
* 由特征引用(refs)与 parent_id 推导的直接依赖边。方向:
* dependent(依赖方,后出现)→ dependency(被依赖方,先出现)。
*/
struct FeatureDependency {
int dependent = -1; ///< 依赖方特征 id
int dependency = -1; ///< 被依赖方特征 id
std::string via; ///< 依赖来源:"ref:<kFace|kEdge|kVertex>" 或 "parent"
};
/// 重排校验结果(P1-4 / B-6)
struct ReorderCheck {
bool ok = true;
std::string issue; ///< 不允许时的原因(ok=true 时为空)
std::vector<int> suggested_order; ///< 合法求值顺序(依赖拓扑序,B-6)
};
/// 抑制/恢复结果(P1-4)
struct SuppressResult {
bool ok = false;
std::vector<int> affected; ///< 实际被设置的 id(含级联)
std::string issue; ///< 失败原因(ok=false 时非空)
};
/// 特征树完整性校验报告(P1-4)
struct FeatureValidationReport {
bool ok = true;
std::vector<std::string> issues;
};
// ═══════════════════════════════════════════════════════════
// B-6:特征冲突检测与消解
// ═══════════════════════════════════════════════════════════
/// 冲突类型(B-6)
enum class FeatureConflictType {
None = 0,
FilletHoleOverlap, ///< 圆角与孔/薄壁重叠(圆角面吃穿孔壁)
ShellExceedsThickness, ///< 抽壳厚度 ≥ 实体最小厚度(零/负壁厚)
PatternOutOfBounds, ///< 阵列副本/工具体越界(完全落在当前实体之外)
DeleteParentWithChildren, ///< 删除仍有(间接)依赖者的父特征
RebuildCycle, ///< parent_id/refs 形成依赖环(重建循环引用)
ReferenceBroken, ///< 拓扑引用断裂(重解析失效项)
};
/// 冲突类型名(诊断 / 序列化)
[[nodiscard]] const char* feature_conflict_type_name(FeatureConflictType t);
/// 单条冲突(类型 + 涉及特征 + 可执行建议)
struct FeatureConflict {
FeatureConflictType type = FeatureConflictType::None;
std::vector<int> feature_ids; ///< 涉及特征 id
std::string message; ///< 冲突描述
std::string suggestion; ///< 可执行建议(如 "reduce radius to <= 2.5")
double suggested_value = 0.0; ///< 参数降级目标值(ClampParameters 用;0=无)
bool auto_resolvable = false; ///< 是否可用 resolve_conflicts 自动消解
};
/// 冲突报告(不静默:新建/编辑/删除均可返回)
struct ConflictReport {
std::vector<FeatureConflict> conflicts;
[[nodiscard]] bool ok() const { return conflicts.empty(); }
[[nodiscard]] size_t size() const { return conflicts.size(); }
[[nodiscard]] std::string to_string() const;
};
/// 消解策略(B-6)
enum class ConflictResolution {
SuppressFeatures, ///< 抑制冲突特征(级联,保留树)
DeleteFeatures, ///< 删除冲突特征(依赖者优先,不丢其它特征)
ClampParameters, ///< 参数降级(圆角半径/抽壳厚度),无法降级者抑制
};
/// 消解结果
struct ConflictResolutionResult {
bool ok = false;
std::vector<int> affected; ///< 被抑制/删除/改参的特征 id
std::vector<std::string> actions; ///< 可审计动作列表
std::string issue; ///< ok=false 时剩余冲突说明
};
// ═══════════════════════════════════════════════════════════
// B-6:父子依赖重解析
// ═══════════════════════════════════════════════════════════
/// 引用重解析统计(B-6)
struct ReferenceResolutionStats {
int total = 0; ///< 引用总数
int resolved = 0; ///< 拓扑名重解析成功
int fallback = 0; ///< 无拓扑名 → elem_idx 直连有效
int broken = 0; ///< 失效(断裂)
std::vector<int> broken_feature_ids; ///< 含失效引用的特征 id
[[nodiscard]] double success_rate() const {
return total == 0 ? 1.0
: static_cast<double>(resolved + fallback) / total;
}
[[nodiscard]] std::string to_string() const;
};
// ═══════════════════════════════════════════════════════════
// B-6:重建失败恢复
// ═══════════════════════════════════════════════════════════
/// 单条重建诊断
struct RebuildDiagnostic {
int feature_id = -1;
std::string reason;
};
/// 带恢复的重建结果:保留最后成功状态 + 失败项诊断
struct RebuildRecoveryResult {
bool ok = true; ///< 全部特征成功
brep::BrepModel model; ///< 最后成功状态(失败项被跳过)
int last_successful_feature_id = -1; ///< 最后成功应用的特征 id
int failed_count = 0;
std::vector<RebuildDiagnostic> diagnostics;
std::vector<int> failed_feature_ids;
[[nodiscard]] std::string to_string() const;
};
/**
* @brief 特征树
*
* 有序特征列表 + 重放求值 + 拓扑命名 + 序列化(VDE-583)。
*
* @code{.cpp}
* FeatureTree tree;
* FeatureDefinition base;
* base.type = FeatureType::PrimitiveBox;
* base.params.values = {10, 5, 3};
* int id = tree.add_feature(base); // 盒子
* FeatureDefinition hole;
* hole.type = FeatureType::BooleanDifference;
* hole.params.tool_body = make_cylinder(1.0, 6.0);
* hole.params.has_tool = true;
* tree.add_feature(hole); // 打孔
* auto model = tree.rebuild(); // 重放求值
* @endcode
*
* @ingroup feature
*/
class FeatureTree {
public:
/// 拓扑元素类型常量(与 TopoElementType 的底层值一致)
static constexpr int kFace = 0;
static constexpr int kEdge = 1;
static constexpr int kVertex = 2;
// ── CRUD ───────────────────────────────────────────
/// 追加特征(def.id < 0 时自动分配),返回分配后的 id
int add_feature(const FeatureDefinition& def);
/// 在位置 pos 插入特征(pos ∈ [0, size],越界自动钳制),返回 true
bool insert_feature(int pos, const FeatureDefinition& def);
/// 将 from 位置的特征移动到 to 位置(重排历史),返回 true
bool reorder_feature(int from, int to);
/// 用 new_def 替换指定 id 的特征(保留树内 id),返回 true
bool edit_feature(int id, const FeatureDefinition& new_def);
/// 删除指定 id 的特征,返回 true
bool delete_feature(int id);
/// 设置特征的抑制状态,返回 true(基础操作;级联用 suppress_feature)
bool set_suppressed(int id, bool suppressed);
// ── 依赖关系 (P1-4) ─────────────────────────────
/// 该特征直接依赖的特征 id 集合(refs + parent_id 推导)
[[nodiscard]] std::vector<int> dependencies_of(int feature_id) const;
/// 直接依赖该特征的特征 id 集合(反向)
[[nodiscard]] std::vector<int> dependents_of(int feature_id) const;
/// 全部直接依赖关系
[[nodiscard]] std::vector<FeatureDependency> dependencies() const;
// ── 重排校验 (P1-4) ─────────────────────────────
/**
* @brief 检查把 from 位置的特征移动到 to 是否破坏依赖序
*
* 依赖方必须保持在被依赖方之后;破坏时返回 issue 说明原因。
* 注意:reorder_feature(基础操作)不做校验,仅列表移动。
*/
[[nodiscard]] ReorderCheck check_reorder(int from, int to) const;
// ── 级联抑制/恢复 (P1-4) ────────────────────────
/**
* @brief 抑制特征(默认级联)
* @param id 特征 id
* @param cascade true=连带抑制其(间接)依赖者;false=存在依赖者时拒绝
* @return ok=false 时 issue 说明原因;affected 为实际被抑制的 id 列表
*/
SuppressResult suppress_feature(int id, bool cascade = true);
/**
* @brief 恢复特征(默认级联)
* @param id 特征 id
* @param cascade true=连带恢复"其依赖均已恢复"的被抑制特征
* @return affected 为实际被恢复的 id 列表
*/
SuppressResult unsuppress_feature(int id, bool cascade = true);
// ── 校验 (P1-4) ─────────────────────────────────
/**
* @brief 完整性校验
*
* 检查:parent_id 指向自身/不存在/后方的特征、引用指向不存在的特征、
* 前向引用(引用后出现的特征)、引用缺少解析依据、依赖环。
*/
[[nodiscard]] FeatureValidationReport validate() const;
// ── 冲突检测与消解 (B-6) ───────────────────────
/// 扫描整棵树的冲突(不改树)
[[nodiscard]] ConflictReport detect_conflicts() const;
/// 预检:若加入(replace_id<0)或替换(replace_id>=0)该定义是否产生冲突
[[nodiscard]] ConflictReport check_candidate(const FeatureDefinition& def,
int replace_id = -1) const;
/// 预检:删除该特征是否影响依赖者
[[nodiscard]] ConflictReport check_delete(int feature_id) const;
/// 按策略消解冲突(改树:抑制/删除/参数降级),返回审计结果
ConflictResolutionResult resolve_conflicts(const ConflictReport& report,
ConflictResolution strategy);
/// 带冲突检查的追加:冲突时拒绝并返回 -1(report 可选输出)
int add_feature_checked(const FeatureDefinition& def,
ConflictReport* report = nullptr);
/// 带冲突检查 + 父子引用自动修复的编辑;失败时回滚原定义
bool edit_feature_checked(int id, const FeatureDefinition& new_def,
ConflictReport* report = nullptr,
ReferenceResolutionStats* stats = nullptr);
/// 带依赖检查的删除(cascade=true 时连依赖者一起删)
bool delete_feature_checked(int id, bool cascade = true,
ConflictReport* report = nullptr);
// ── 父子依赖重解析 (B-6) ────────────────────────
/**
* @brief 编辑父特征并级联重解析全树拓扑引用(修复 elem_idx)
*
* 成功路径:ref.topo_name 在新状态下重解析(自动更新 elem_idx);
* 失效路径:解析失败 → 计入 stats.broken/broken_feature_ids 并显式报告。
* @return 全部引用可解析且重建模型 valid
*/
bool edit_feature_with_repair(int id, const FeatureDefinition& new_def,
ReferenceResolutionStats* stats = nullptr,
ConflictReport* report = nullptr);
/// 扫描全树引用并重解析(不修改特征定义),返回统计
[[nodiscard]] ReferenceResolutionStats resolve_all_references() const;
// ── 重排语义 (B-6) ──────────────────────────────
/// 合法求值顺序(依赖拓扑序,稳定)
[[nodiscard]] std::vector<int> suggested_order() const;
/// 校验后重排:非法重排拒绝并返回建议顺序
bool reorder_feature_checked(int from, int to, ReorderCheck* check = nullptr);
// ── 重建失败恢复 (B-6) ──────────────────────────
/**
* @brief 带恢复的重建:失败特征跳过(默认)或停止在上一个成功状态
*
* 不丢树:失败项仅记录诊断;可用 suppress_feature 抑制后继续。
* last_result() 更新为恢复后的最后成功模型。
*/
[[nodiscard]] RebuildRecoveryResult rebuild_with_recovery(
bool skip_failed = true) const;
/// 最近一次 rebuild_with_recovery 的结果
[[nodiscard]] const RebuildRecoveryResult& last_recovery_result() const {
return last_recovery_;
}
// ── 历史导航 ───────────────────────────────────────
/**
* @brief 重放全部特征,返回最终模型
*
* 每次重建都会以特征 id 为代际记录拓扑命名,供后续解析。
*/
brep::BrepModel rebuild() const;
/// 回滚到指定特征(含)为止的状态
brep::BrepModel rollback_to(int feature_id) const;
/// 前进到指定特征(含)为止的状态
brep::BrepModel rollforward_to(int feature_id) const;
/// 当前位置:已应用(非抑制)的特征数
[[nodiscard]] int current_position() const { return current_position_; }
// ── 拓扑命名 (VDE-583) ─────────────────────────────
/**
* @brief 生成指定特征状态下某元素的拓扑名
* @param feature_id 特征 id(元素取自该特征重建后的模型)
* @param elem_type kFace / kEdge / kVertex
* @param elem_idx 元素索引
* @return 文本拓扑名;无效输入返回空串
*/
[[nodiscard]] std::string topological_name(
int feature_id, int elem_type, int elem_idx) const;
/**
* @brief 解析文本拓扑名到当前模型的元素
* @param name 拓扑名文本
* @param elem_type [out] 元素类型(kFace/kEdge/kVertex)
* @return 元素索引;无匹配返回 -1
*/
[[nodiscard]] int resolve_topological_name(
const std::string& name, int& elem_type) const;
/**
* @brief 在指定模型状态下解析一个特征引用(P1-4)
*
* 主路径:ref.topo_name(拓扑名 → 签名匹配);退化路径:elem_idx 直连
* (校验类型与范围)。解析失败返回 -1(引用断裂)。
*/
[[nodiscard]] int resolve_reference(
const FeatureReference& ref, const brep::BrepModel& model) const;
// ── 持久化 ─────────────────────────────────────────
/// 文本序列化(特征定义,不含工具体几何)
bool serialize(std::ostream& os) const;
/// 从文本流反序列化,返回是否成功
bool deserialize(std::istream& is);
// ── 查询 ───────────────────────────────────────────
/// 特征数量
[[nodiscard]] size_t feature_count() const { return features_.size(); }
/// 全部特征(按求值顺序)
[[nodiscard]] const std::vector<FeatureDefinition>& features() const {
return features_;
}
/// 按 id 查找特征,未找到返回 nullptr
[[nodiscard]] const FeatureDefinition* find(int id) const;
/// 最近一次重建/导航得到的模型
[[nodiscard]] brep::BrepModel last_result() const { return last_result_; }
private:
/// 单个特征作用于运行模型
brep::BrepModel evaluate_feature(const FeatureDefinition& f,
const brep::BrepModel& running) const;
/// 解析特征声明中指定类型的拓扑引用:
/// ≥0 已解析索引;-1 引用声明但断裂(应跳过特征);-2 无该类型引用(用原始索引)
int resolve_slot(const FeatureDefinition& f, int elem_type,
const brep::BrepModel& running) const;
/// 组合式并集(运行模型为空时直接返回新体)
brep::BrepModel merge_add(const brep::BrepModel& running,
const brep::BrepModel& added) const;
/// 求值到 end_index(含)为止的状态并记录拓扑命名代际
brep::BrepModel state_after_index(int end_index) const;
/// 按 id 查下标(无返回 -1)
int index_of(int feature_id) const;
std::vector<FeatureDefinition> features_;
mutable brep::TopoNamingManager naming_; ///< 重建时按特征 id 记录代际
int next_id_ = 1;
mutable int current_position_ = 0;
mutable brep::BrepModel last_result_;
mutable RebuildRecoveryResult last_recovery_;
};
} // namespace vde::feature