Files
ViewDesignEngine/python/src/vde_brep.cpp
T

616 lines
21 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.
#include <pybind11/pybind11.h>
#include <pybind11/eigen.h>
#include <pybind11/stl.h>
#include "vde/brep/brep.h"
#include "vde/brep/modeling.h"
#include "vde/brep/ssi_boolean.h"
#include "vde/brep/brep_heal.h"
#include "vde/brep/brep_validate.h"
#include "vde/brep/step_import.h"
#include "vde/brep/step_export.h"
#include "vde/brep/iges_import.h"
#include "vde/brep/iges_export.h"
#include "vde/brep/format_io.h"
namespace py = pybind11;
using namespace vde::brep;
void bind_brep(py::module& m) {
auto brep = m.def_submodule("brep",
"B-Rep (Boundary Representation) solid modeling");
// ── TopoVertex ─────────────────────────────────────
py::class_<TopoVertex>(brep, "TopoVertex",
R"pbdoc(
Topological vertex of a B-Rep model.
Attributes:
id: unique vertex ID
point: 3D coordinates (Point3D)
tolerance: geometric tolerance
)pbdoc")
.def_readonly("id", &TopoVertex::id)
.def_readonly("point", &TopoVertex::point)
.def_readwrite("tolerance", &TopoVertex::tolerance)
.def("__repr__", [](const TopoVertex& v) {
return "TopoVertex(id=" + std::to_string(v.id) + ")";
});
// ── TopoEdge ───────────────────────────────────────
py::class_<TopoEdge>(brep, "TopoEdge",
R"pbdoc(
Topological edge connecting two vertices.
Attributes:
id: unique edge ID
v_start, v_end: start and end vertex IDs
reversed: whether direction is reversed relative to curve
)pbdoc")
.def_readonly("id", &TopoEdge::id)
.def_readonly("v_start", &TopoEdge::v_start)
.def_readonly("v_end", &TopoEdge::v_end)
.def_readwrite("reversed", &TopoEdge::reversed)
.def("__repr__", [](const TopoEdge& e) {
return "TopoEdge(id=" + std::to_string(e.id) + ")";
});
// ── TopoLoop ───────────────────────────────────────
py::class_<TopoLoop>(brep, "TopoLoop",
R"pbdoc(
Closed loop of edges bounding a face.
Attributes:
id: unique loop ID
edges: ordered edge ID list
is_outer: True for outer loop, False for inner loop (hole)
)pbdoc")
.def_readonly("id", &TopoLoop::id)
.def_readonly("edges", &TopoLoop::edges)
.def_readwrite("is_outer", &TopoLoop::is_outer)
.def("__repr__", [](const TopoLoop& l) {
return "TopoLoop(id=" + std::to_string(l.id) + ")";
});
// ── TopoFace ───────────────────────────────────────
py::class_<TopoFace>(brep, "TopoFace",
R"pbdoc(
Face: a region on a surface bounded by loops.
Attributes:
id: unique face ID
surface_id: associated surface ID
loops: list of loop IDs (first is outer, rest are holes)
reversed: whether face normal is flipped
)pbdoc")
.def_readonly("id", &TopoFace::id)
.def_readonly("surface_id", &TopoFace::surface_id)
.def_readonly("loops", &TopoFace::loops)
.def_readwrite("reversed", &TopoFace::reversed)
.def("__repr__", [](const TopoFace& f) {
return "TopoFace(id=" + std::to_string(f.id) + ")";
});
// ── TopoShell ──────────────────────────────────────
py::class_<TopoShell>(brep, "TopoShell",
R"pbdoc(
A set of connected faces forming a closed or open shell.
Attributes:
id: unique shell ID
faces: list of face IDs
closed: True if shell is watertight
)pbdoc")
.def_readonly("id", &TopoShell::id)
.def_readonly("faces", &TopoShell::faces)
.def_readwrite("closed", &TopoShell::closed)
.def("__repr__", [](const TopoShell& s) {
return "TopoShell(id=" + std::to_string(s.id) + ")";
});
// ── TopoBody ───────────────────────────────────────
py::class_<TopoBody>(brep, "TopoBody",
R"pbdoc(
A topological body: one or more shells forming a solid.
Attributes:
id: unique body ID
shells: list of shell IDs
name: body name (PRODUCT name in STEP)
)pbdoc")
.def_readonly("id", &TopoBody::id)
.def_readonly("shells", &TopoBody::shells)
.def_readwrite("name", &TopoBody::name)
.def("__repr__", [](const TopoBody& b) {
return "TopoBody(id=" + std::to_string(b.id)
+ ", name=\"" + b.name + "\")";
});
// ── BrepModel ──────────────────────────────────────
py::class_<BrepModel>(brep, "BrepModel",
R"pbdoc(
B-Rep (Boundary Representation) solid model.
Represents a complete 3D geometric entity with topology hierarchy:
Body → Shell → Face → Loop → Edge → Vertex.
Construction:
model = BrepModel() # empty model
model = brep.make_box(10, 5, 3) # or use factory functions
The typical workflow uses high-level factory functions (make_box, make_cylinder,
make_sphere), boolean operations (union, intersect, diff), and STEP/IGES import.
)pbdoc")
.def(py::init<>(), "Create an empty B-Rep model")
// ── Topology construction ──
.def("add_vertex", &BrepModel::add_vertex,
py::arg("point"), "Add a vertex, returns its ID")
.def("add_vertex_unique", &BrepModel::add_vertex_unique,
py::arg("point"), py::arg("tolerance") = 1e-9,
"Add a vertex with deduplication")
.def("add_edge", py::overload_cast<int, int>(&BrepModel::add_edge),
py::arg("v0"), py::arg("v1"),
"Add a straight edge between two vertices")
.def("add_loop", &BrepModel::add_loop,
py::arg("edges"), py::arg("outer") = true,
"Add a loop from edge IDs")
.def("add_face", &BrepModel::add_face,
py::arg("surface_id"), py::arg("loops"),
"Add a face from surface and loops")
.def("add_shell", &BrepModel::add_shell,
py::arg("faces"), py::arg("closed") = true,
"Add a shell from face IDs")
.def("add_body", &BrepModel::add_body,
py::arg("shells"), py::arg("name") = "",
"Add a body from shell IDs")
// ── Count queries ──
.def_property_readonly("num_vertices", &BrepModel::num_vertices)
.def_property_readonly("num_edges", &BrepModel::num_edges)
.def_property_readonly("num_faces", &BrepModel::num_faces)
.def_property_readonly("num_bodies", &BrepModel::num_bodies)
.def_property_readonly("num_surfaces", &BrepModel::num_surfaces)
// ── Element access ──
.def("vertex", &BrepModel::vertex,
py::arg("id"), "Get vertex by array index")
.def("edge", &BrepModel::edge,
py::arg("id"), "Get edge by array index")
.def("face",
static_cast<const TopoFace& (BrepModel::*)(int) const>(&BrepModel::face),
py::arg("id"), "Get face by array index")
.def("surface", &BrepModel::surface,
py::arg("id"), "Get NURBS surface by index")
// ── Geometry queries ──
.def("bounds", &BrepModel::bounds,
"Compute axis-aligned bounding box")
.def("is_valid", &BrepModel::is_valid,
"Quick validity check")
.def("to_mesh",
static_cast<vde::mesh::HalfedgeMesh (BrepModel::*)(double) const>(
&BrepModel::to_mesh),
py::arg("deflection") = 0.01,
"Tessellate to HalfedgeMesh triangle mesh")
// ── Adjacency queries ──
.def("face_edges", &BrepModel::face_edges,
py::arg("face_id"), "Get all edges of a face")
.def("edge_faces", &BrepModel::edge_faces,
py::arg("edge_id"), "Get faces adjacent to an edge")
.def("vertex_edges", &BrepModel::vertex_edges,
py::arg("vertex_id"), "Get edges incident to a vertex")
.def("__repr__", [](const BrepModel& m) {
return "BrepModel(v=" + std::to_string(m.num_vertices())
+ ", e=" + std::to_string(m.num_edges())
+ ", f=" + std::to_string(m.num_faces())
+ ", bodies=" + std::to_string(m.num_bodies()) + ")";
});
// ── BrepModel factory functions ────────────────────
brep.def("make_box",
[](double w, double h, double d) { return make_box(w, h, d); },
py::arg("w"), py::arg("h"), py::arg("d"),
R"pbdoc(
Create an axis-aligned box centered at origin.
Args:
w: width (X direction), must be > 0
h: height (Y direction), must be > 0
d: depth (Z direction), must be > 0
Returns:
BrepModel: solid box B-Rep
Example:
>>> box = brep.make_box(10, 5, 3)
)pbdoc");
brep.def("make_cylinder",
[](double radius, double height, int segments) {
return make_cylinder(radius, height, segments);
},
py::arg("radius"), py::arg("height"),
py::arg("segments") = 32,
R"pbdoc(
Create a cylinder along Y axis, centered at origin.
Args:
radius: section radius, must be > 0
height: total height along Y axis
segments: number of facets (default 32, higher = smoother)
Returns:
BrepModel: solid cylinder B-Rep
Example:
>>> cyl = brep.make_cylinder(2.0, 10.0, 64)
)pbdoc");
brep.def("make_sphere",
[](double radius, int segments_u, int segments_v) {
return make_sphere(radius, segments_u, segments_v);
},
py::arg("radius"),
py::arg("segments_u") = 32,
py::arg("segments_v") = 16,
R"pbdoc(
Create a sphere centered at origin.
Args:
radius: sphere radius, must be > 0
segments_u: longitude segments (default 32)
segments_v: latitude segments (default 16)
Returns:
BrepModel: solid sphere B-Rep
Example:
>>> sphere = brep.make_sphere(5.0, 32, 32)
)pbdoc");
brep.def("extrude",
static_cast<BrepModel (*)(const vde::curves::NurbsCurve&, const Vector3D&)>(
&extrude),
py::arg("profile"), py::arg("dir"),
"Extrude a planar curve along a direction vector");
brep.def("revolve",
static_cast<BrepModel (*)(const vde::curves::NurbsCurve&, const Point3D&,
const Vector3D&, double)>(&revolve),
py::arg("profile"), py::arg("axis_origin"),
py::arg("axis_dir"), py::arg("angle_rad") = 2.0 * M_PI,
"Revolve a profile around an axis");
brep.def("fillet", &fillet,
py::arg("body"), py::arg("edge_id"), py::arg("radius"),
"Apply constant-radius fillet to an edge");
brep.def("chamfer", &chamfer,
py::arg("body"), py::arg("edge_id"), py::arg("distance"),
"Apply chamfer to an edge");
brep.def("shell", &shell,
py::arg("body"), py::arg("face_id"), py::arg("thickness"),
"Hollow out a solid body by removing a face");
// ── SSI Boolean operations ─────────────────────────
py::class_<SSIBooleanResult>(brep, "SSIBooleanResult",
R"pbdoc(
Result of an SSI (Surface-Surface Intersection) boolean operation.
Attributes:
result: the resulting BrepModel
error_message: empty string on success, error description on failure
num_ssi_curves: number of intersection curves computed
num_fragments: number of face fragments generated
num_kept: number of fragments kept in final result
total_time_ms: total computation time in milliseconds
)pbdoc")
.def_readonly("result", &SSIBooleanResult::result)
.def_readonly("error_message", &SSIBooleanResult::error_message)
.def_readonly("num_ssi_curves", &SSIBooleanResult::num_ssi_curves)
.def_readonly("num_fragments", &SSIBooleanResult::num_fragments)
.def_readonly("num_kept", &SSIBooleanResult::num_kept)
.def_property_readonly("total_time_ms", &SSIBooleanResult::total_time_ms)
.def("__repr__", [](const SSIBooleanResult& r) {
if (!r.error_message.empty())
return "SSIBooleanResult(error=\"" + r.error_message + "\")";
return "SSIBooleanResult(curves=" + std::to_string(r.num_ssi_curves)
+ ", kept=" + std::to_string(r.num_kept)
+ ", time=" + std::to_string(r.total_time_ms()) + "ms)";
});
brep.def("boolean_union", &ssi_boolean_union,
py::arg("a"), py::arg("b"),
R"pbdoc(
Boolean union: A ∪ B.
Combine two B-Rep solids into one via SSI pipeline.
Args:
a: first BrepModel
b: second BrepModel
Returns:
SSIBooleanResult with result model and diagnostics
Example:
>>> box = brep.make_box(2, 2, 2)
>>> sph = brep.make_sphere(1.5)
>>> r = brep.boolean_union(box, sph)
>>> if not r.error_message:
... union_body = r.result
)pbdoc");
brep.def("boolean_intersect", &ssi_boolean_intersection,
py::arg("a"), py::arg("b"),
R"pbdoc(
Boolean intersection: A ∩ B.
Keep only the region common to both solids.
Args:
a: first BrepModel
b: second BrepModel
Returns:
SSIBooleanResult with result model and diagnostics
)pbdoc");
brep.def("boolean_diff", &ssi_boolean_difference,
py::arg("a"), py::arg("b"),
R"pbdoc(
Boolean difference: A \\ B.
Subtract solid B from solid A.
Args:
a: BrepModel to subtract from
b: BrepModel to subtract
Returns:
SSIBooleanResult with result model and diagnostics
)pbdoc");
// ── Validation ─────────────────────────────────────
py::class_<ValidationResult>(brep, "ValidationResult",
R"pbdoc(
Comprehensive B-Rep validation result.
Attributes:
valid: True if model passes all checks
errors: list of error messages
warnings: list of warning messages
watertightness: ratio of edges with exactly 2 adjacent faces (1.0 = perfect)
non_manifold_edges: count of non-manifold edges
dangling_edges: count of dangling edges
total_edges: total edge count
total_faces: total face count
euler_characteristic: V - E + F
)pbdoc")
.def_readonly("valid", &ValidationResult::valid)
.def_readonly("errors", &ValidationResult::errors)
.def_readonly("warnings", &ValidationResult::warnings)
.def_readonly("watertightness", &ValidationResult::watertightness)
.def_readonly("non_manifold_edges", &ValidationResult::non_manifold_edges)
.def_readonly("dangling_edges", &ValidationResult::dangling_edges)
.def_readonly("total_edges", &ValidationResult::total_edges)
.def_readonly("total_faces", &ValidationResult::total_faces)
.def_readonly("euler_characteristic", &ValidationResult::euler_characteristic)
.def("__repr__", [](const ValidationResult& vr) {
return "ValidationResult(valid=" + std::string(vr.valid ? "True" : "False")
+ ", watertight=" + std::to_string(vr.watertightness)
+ ", errors=" + std::to_string(vr.errors.size()) + ")";
});
brep.def("validate",
[](const BrepModel& body) { return validate(body); },
py::arg("body"),
R"pbdoc(
Perform comprehensive validation of a B-Rep model.
Checks watertightness, orientation consistency, self-intersection,
edge quality, and shell closure.
Args:
body: BrepModel to validate
Returns:
ValidationResult with detailed report
Example:
>>> result = brep.validate(my_model)
>>> if not result.valid:
... for err in result.errors:
... print("Error:", err)
)pbdoc");
// ── Healing ────────────────────────────────────────
brep.def("heal_topology", &heal_topology,
py::arg("body"), py::arg("tolerance") = 1e-6,
R"pbdoc(
One-stop topology healing pipeline.
Runs heal_gaps → heal_slivers → heal_orientation, then validates.
Args:
body: BrepModel to heal (modified in place)
tolerance: vertex merge distance (default 1e-6)
Returns:
bool: True if model passes validation after healing
Example:
>>> brep.heal_topology(model, 1e-5)
)pbdoc");
brep.def("heal_gaps", &heal_gaps,
py::arg("body"), py::arg("tolerance") = 1e-6,
R"pbdoc(
Merge vertices within tolerance using BFS connected components.
Args:
body: BrepModel to heal (modified in place)
tolerance: vertex merge distance
Returns:
int: number of merged vertex pairs
)pbdoc");
brep.def("heal_slivers", &heal_slivers,
py::arg("body"),
R"pbdoc(
Detect and remove degenerate (sliver) faces.
Args:
body: BrepModel to heal (modified in place)
Returns:
int: number of removed sliver faces
)pbdoc");
brep.def("heal_orientation", &heal_orientation,
py::arg("body"),
R"pbdoc(
Unify face orientations (all outward-facing), verify with Euler characteristic.
Args:
body: BrepModel to heal (modified in place)
Returns:
int: number of flipped faces
)pbdoc");
brep.def("heal_step_import", &heal_step_import,
py::arg("body"),
R"pbdoc(
Auto-heal after STEP import using adaptive tolerance.
Args:
body: BrepModel from STEP import (modified in place)
Returns:
int: > 0 on success, 0 if no healing needed, < 0 on failure
)pbdoc");
// ── STEP Import / Export ───────────────────────────
brep.def("import_step",
[](const std::string& filepath) { return import_step(filepath); },
py::arg("filepath"),
R"pbdoc(
Import STEP file (AP203/AP214) and return list of B-Rep bodies.
Args:
filepath: path to .step or .stp file
Returns:
list of BrepModel, one per PRODUCT in the file
Example:
>>> bodies = brep.import_step("assembly.step")
>>> for b in bodies:
... print(b)
)pbdoc");
brep.def("import_step_from_string",
[](const std::string& data) { return import_step_from_string(data); },
py::arg("data"),
R"pbdoc(
Import STEP data from a string (for testing / embedded use).
Args:
data: complete STEP file content as string
Returns:
list of BrepModel
)pbdoc");
brep.def("export_step",
static_cast<std::string (*)(const std::vector<BrepModel>&)>(&export_step),
py::arg("bodies"),
R"pbdoc(
Export B-Rep bodies to STEP AP214 format string.
Args:
bodies: list of BrepModel to export
Returns:
str: STEP AP214 formatted string
)pbdoc");
brep.def("export_step_file",
static_cast<bool (*)(const std::string&, const std::vector<BrepModel>&)>(
&export_step_file),
py::arg("filepath"), py::arg("bodies"),
R"pbdoc(
Export B-Rep bodies to a STEP file.
Args:
filepath: output file path (.step or .stp)
bodies: list of BrepModel to export
)pbdoc");
// ── IGES Import / Export ───────────────────────────
brep.def("import_iges", &import_iges,
py::arg("filepath"),
R"pbdoc(
Import IGES file and return list of B-Rep bodies.
Args:
filepath: path to .igs or .iges file
Returns:
list of BrepModel
)pbdoc");
brep.def("import_iges_from_string", &import_iges_from_string,
py::arg("data"),
R"pbdoc(
Import IGES data from a string.
Args:
data: complete IGES file content as string
Returns:
list of BrepModel
)pbdoc");
brep.def("export_iges", &export_iges,
py::arg("bodies"),
R"pbdoc(
Export B-Rep bodies to IGES 5.3 format string.
Args:
bodies: list of BrepModel to export
Returns:
str: IGES formatted string
)pbdoc");
brep.def("export_iges_file", &export_iges_file,
py::arg("filepath"), py::arg("bodies"),
R"pbdoc(
Export B-Rep bodies to an IGES file.
Args:
filepath: output file path (.igs or .iges)
bodies: list of BrepModel to export
)pbdoc");
// ── Auto Import ────────────────────────────────────
brep.def("auto_import", &auto_import,
py::arg("filepath"),
R"pbdoc(
Smart import: auto-detect format (STEP/IGES) and import.
Args:
filepath: path to CAD file
Returns:
list of BrepModel
)pbdoc");
}