use serde::{Deserialize, Serialize};
use std::path::Path;
use thiserror::Error;
pub mod naming;
pub mod pmi;
pub use naming::TopoName;
pub use pmi::{PmiDatum, PmiDimension, PmiTolerance, SemanticPmi};
pub type KernelResult<T> = Result<T, KernelError>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct BodyHandle(pub u64);
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RebuildRequest {
pub dirty_features: Vec<String>,
pub propagate: bool,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RebuildResponse {
pub updated_bodies: Vec<BodyHandle>,
pub diagnostics: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum LinearDeflectionMode {
#[default]
BboxScaled,
AbsoluteMm,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TessellationSettings {
#[serde(default)]
pub linear_deflection_mode: LinearDeflectionMode,
#[serde(default = "default_mesh_deviation")]
pub mesh_deviation: f32,
pub chord_tolerance: f32,
pub angular_tolerance_deg: f32,
#[serde(default = "default_weld_cross_face")]
pub weld_cross_face: bool,
#[serde(default = "default_weld_angle_threshold_deg")]
pub weld_angle_threshold_deg: f32,
#[serde(default = "default_persist_brep_snapshot")]
pub persist_brep_snapshot: bool,
#[serde(default = "default_generate_boundary_edges")]
pub generate_boundary_edges: bool,
}
fn default_weld_cross_face() -> bool {
false
}
fn default_weld_angle_threshold_deg() -> f32 {
30.0
}
fn default_mesh_deviation() -> f32 {
0.2
}
fn default_persist_brep_snapshot() -> bool {
true
}
fn default_generate_boundary_edges() -> bool {
true
}
impl Default for TessellationSettings {
fn default() -> Self {
Self {
linear_deflection_mode: LinearDeflectionMode::default(),
mesh_deviation: default_mesh_deviation(),
chord_tolerance: 0.1,
angular_tolerance_deg: 28.65,
weld_cross_face: default_weld_cross_face(),
weld_angle_threshold_deg: default_weld_angle_threshold_deg(),
persist_brep_snapshot: default_persist_brep_snapshot(),
generate_boundary_edges: default_generate_boundary_edges(),
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct TriMesh {
pub positions: Vec<[f32; 3]>,
pub normals: Vec<[f32; 3]>,
pub indices: Vec<u32>,
#[serde(default)]
pub edges: Vec<u32>,
#[serde(default)]
pub colors: Vec<[f32; 3]>,
#[serde(default)]
pub faces: Vec<u32>,
#[serde(default)]
pub edge_ids: Vec<u32>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub face_surfaces: Vec<FaceSurface>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub face_names: Vec<TopoName>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub face_makers: Vec<TopoName>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub edge_faces: Vec<[TopoName; 2]>,
}
#[cfg_attr(not(feature = "exhaustive"), non_exhaustive)]
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
pub enum FaceSurface {
Plane { origin: [f32; 3], normal: [f32; 3] },
Cylinder {
origin: [f32; 3],
axis: [f32; 3],
radius: f32,
},
Cone {
apex: [f32; 3],
axis: [f32; 3],
#[serde(default)]
half_angle: f32,
},
Sphere { center: [f32; 3], radius: f32 },
Torus {
center: [f32; 3],
axis: [f32; 3],
#[serde(default)]
major_radius: f32,
#[serde(default)]
minor_radius: f32,
},
#[default]
Other,
}
impl FaceSurface {
pub fn axis(&self) -> Option<([f32; 3], [f32; 3])> {
match *self {
FaceSurface::Cylinder { origin, axis, .. } => Some((origin, axis)),
FaceSurface::Cone { apex, axis, .. } => Some((apex, axis)),
FaceSurface::Torus { center, axis, .. } => Some((center, axis)),
_ => None,
}
}
pub fn moved(
&self,
point: impl Fn([f32; 3]) -> [f32; 3],
direction: impl Fn([f32; 3]) -> [f32; 3],
) -> Self {
match *self {
FaceSurface::Plane { origin, normal } => FaceSurface::Plane {
origin: point(origin),
normal: direction(normal),
},
FaceSurface::Cylinder {
origin,
axis,
radius,
} => FaceSurface::Cylinder {
origin: point(origin),
axis: direction(axis),
radius,
},
FaceSurface::Cone {
apex,
axis,
half_angle,
} => FaceSurface::Cone {
apex: point(apex),
axis: direction(axis),
half_angle,
},
FaceSurface::Sphere { center, radius } => FaceSurface::Sphere {
center: point(center),
radius,
},
FaceSurface::Torus {
center,
axis,
major_radius,
minor_radius,
} => FaceSurface::Torus {
center: point(center),
axis: direction(axis),
major_radius,
minor_radius,
},
FaceSurface::Other => FaceSurface::Other,
}
}
}
impl TriMesh {
pub fn bounds(&self) -> Option<([f32; 3], [f32; 3])> {
if self.positions.is_empty() {
return None;
}
let mut min = self.positions[0];
let mut max = self.positions[0];
for &[x, y, z] in &self.positions {
if x < min[0] {
min[0] = x;
}
if y < min[1] {
min[1] = y;
}
if z < min[2] {
min[2] = z;
}
if x > max[0] {
max[0] = x;
}
if y > max[1] {
max[1] = y;
}
if z > max[2] {
max[2] = z;
}
}
Some((min, max))
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImportedBody {
pub name: Option<String>,
#[serde(default)]
pub mesh: TriMesh,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub brep_blob: Vec<u8>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub face_colors: Vec<[f32; 3]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub bounds_mm: Option<([f32; 3], [f32; 3])>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub health: Option<ShapeHealth>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub layers: Vec<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ShapeHealth {
pub broken: usize,
pub suspect: usize,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub findings: Vec<String>,
#[serde(default)]
pub repaired: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub faceted: bool,
}
impl ShapeHealth {
pub const KEPT_FINDINGS: usize = 8;
pub fn is_broken(&self) -> bool {
self.broken > 0
}
pub fn describe(&self) -> String {
let mut lines = Vec::new();
let counts = match (self.broken, self.suspect) {
(0, 0) => "The shape checks clean".to_string(),
(b, 0) => format!("{b} shape defect(s) that make operations answer wrongly"),
(0, s) => format!("{s} shape irregularity(ies), harmless to operations"),
(b, s) => format!(
"{b} shape defect(s) that make operations answer wrongly, \
and {s} harmless irregularity(ies)"
),
};
lines.push(counts);
if self.repaired && self.is_broken() {
lines.push("Repaired; these remain, beyond what the repair mends".to_string());
}
lines.extend(self.findings.iter().cloned());
let shown = self.findings.len();
let total = self.broken + self.suspect;
if total > shown {
lines.push(format!("… and {} more", total - shown));
}
lines.join("\n")
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RepairResult {
pub brep_blob: Vec<u8>,
pub face_colors: Vec<[f32; 3]>,
pub mesh: TriMesh,
pub bounds_mm: Option<([f32; 3], [f32; 3])>,
pub health: ShapeHealth,
pub mended: Vec<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MeshSolidResult {
pub brep_blob: Vec<u8>,
pub face_colors: Vec<[f32; 3]>,
pub mesh: TriMesh,
pub bounds_mm: Option<([f32; 3], [f32; 3])>,
pub health: ShapeHealth,
pub closed: bool,
pub summary: Vec<String>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct PhysicalProperties {
pub volume_mm3: Option<f64>,
pub area_mm2: f64,
pub centre_mm: [f64; 3],
#[serde(default)]
pub approximate: bool,
#[serde(default)]
pub inertia: Option<Inertia>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct Inertia {
pub about_centre: [[f64; 3]; 3],
pub principal: [(f64, [f64; 3]); 3],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ImportedNodeKind {
#[default]
Assembly,
Part,
Instance,
Annotations,
Annotation,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum AnnotationKind {
Dimension,
Tolerance,
Datum,
Note,
#[default]
Other,
}
impl AnnotationKind {
pub fn label(self) -> &'static str {
match self {
AnnotationKind::Dimension => "Dimension",
AnnotationKind::Tolerance => "Tolerance",
AnnotationKind::Datum => "Datum",
AnnotationKind::Note => "Note",
AnnotationKind::Other => "Annotation",
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct ImportedAnnotation {
pub name: String,
pub kind: AnnotationKind,
pub text: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub polylines: Vec<Vec<[f32; 3]>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub anchor: Option<[f32; 3]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub body_index: Option<usize>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImportedNode {
pub id: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub parent_id: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(default)]
pub kind: ImportedNodeKind,
#[serde(default = "default_imported_node_visible")]
pub visible: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub body_index: Option<usize>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub local_transform: Option<[[f32; 4]; 4]>,
}
fn default_imported_node_visible() -> bool {
true
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LengthUnit {
Millimetre,
Centimetre,
Metre,
Inch,
Foot,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ImportedModel {
pub bodies: Vec<ImportedBody>,
#[serde(default)]
pub report: ImportReport,
#[serde(default)]
pub nodes: Vec<ImportedNode>,
#[serde(default)]
pub source_unit: Option<LengthUnit>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub annotations: Vec<ImportedAnnotation>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ImportReport {
pub kernel: String,
pub summary: Vec<ImportWarningKind>,
pub warnings: Vec<String>,
pub untrimmed_faces: Vec<u64>,
pub skipped: Vec<(String, usize)>,
}
impl ImportReport {
pub fn is_clean(&self) -> bool {
self.warnings.is_empty() && self.untrimmed_faces.is_empty()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImportWarningKind {
pub kind: String,
pub count: usize,
pub worst: f64,
pub exemplar: u64,
}
#[cfg_attr(not(feature = "exhaustive"), non_exhaustive)]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ProfileSegment {
Line {
start: [f64; 2],
end: [f64; 2],
},
Arc {
start: [f64; 2],
mid: [f64; 2],
end: [f64; 2],
},
Circle {
center: [f64; 2],
radius: f64,
},
Ellipse {
center: [f64; 2],
major: [f64; 2],
ratio: f64,
},
EllipseArc {
center: [f64; 2],
major: [f64; 2],
ratio: f64,
start_param: f64,
end_param: f64,
},
BSpline {
control_points: Vec<[f64; 2]>,
periodic: bool,
},
Nurbs {
degree: u32,
knots: Vec<f64>,
control_points: Vec<[f64; 2]>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
weights: Vec<f64>,
#[serde(default)]
periodic: bool,
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum PipePath {
Profile(Profile),
Edges(Vec<EdgeProbe>),
EdgesOf {
shape: Vec<u8>,
transform: Option<Box<[[f64; 4]; 4]>>,
edges: Vec<EdgeProbe>,
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum LoftSection {
Profile(Profile),
Face(FaceProbe),
Point([f64; 3]),
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct ProfileWire {
pub segments: Vec<ProfileSegment>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub names: Vec<TopoName>,
}
impl ProfileWire {
pub fn new(segments: Vec<ProfileSegment>) -> Self {
Self {
segments,
names: Vec::new(),
}
}
pub fn name_of(&self, index: usize) -> Option<TopoName> {
self.names.get(index).copied().filter(|n| *n != 0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ProfilePlane {
pub origin: [f64; 3],
pub x_axis: [f64; 3],
pub y_axis: [f64; 3],
pub normal: [f64; 3],
}
impl Default for ProfilePlane {
fn default() -> Self {
Self {
origin: [0.0; 3],
x_axis: [1.0, 0.0, 0.0],
y_axis: [0.0, 1.0, 0.0],
normal: [0.0, 0.0, 1.0],
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum BooleanOp {
NewSolid,
Fuse,
Cut,
Common,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Profile {
pub plane: ProfilePlane,
pub wires: Vec<ProfileWire>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ExtrudeTermination {
Blind { distance: f64 },
ThroughAll,
UpToPlane {
point: [f64; 3],
normal: [f64; 3],
offset: f64,
},
UpToFace {
point: [f64; 3],
normal: [f64; 3],
offset: f64,
#[serde(default)]
name: TopoName,
},
ToFirst,
ToLast,
UpToShape { faces: Vec<FaceProbe>, offset: f64 },
UpToFaceOf {
shape: Vec<u8>,
transform: Option<Box<[[f64; 4]; 4]>>,
point: [f64; 3],
offset: f64,
},
UpToShapeOf {
faces: Vec<FaceProbe>,
others: Vec<FacesOf>,
offset: f64,
},
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct FacesOf {
pub shape: Vec<u8>,
pub transform: Option<Box<[[f64; 4]; 4]>>,
pub points: Vec<[f64; 3]>,
}
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
pub enum RevolveTermination {
#[default]
Angle,
ToFirst,
ToLast,
UpToFace(FaceProbe),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum SweepKind {
Extrude {
termination: ExtrudeTermination,
second_side: Option<ExtrudeTermination>,
symmetric: bool,
reversed: bool,
taper_deg: f64,
direction: Option<[f64; 3]>,
},
Revolve {
axis_origin: [f64; 2],
axis_dir: [f64; 2],
angle_deg: f64,
second_angle_deg: Option<f64>,
midplane: bool,
reversed: bool,
#[serde(default)]
termination: RevolveTermination,
},
Helix {
axis_origin: [f64; 2],
axis_dir: [f64; 2],
pitch: f64,
height: f64,
left_handed: bool,
cone_angle_deg: f64,
reversed: bool,
#[serde(default)]
turns: Option<f64>,
#[serde(default)]
growth: Option<f64>,
},
HelixNormal {
axis_origin: [f64; 2],
pitch: f64,
height: f64,
left_handed: bool,
cone_angle_deg: f64,
reversed: bool,
#[serde(default)]
turns: Option<f64>,
#[serde(default)]
growth: Option<f64>,
},
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub enum PipeFrame {
#[default]
RotationMinimizing,
Frenet,
Auxiliary { path: Profile },
Binormal { direction: [f64; 3] },
Fixed,
}
impl PipeFrame {
pub fn from_frenet(frenet: bool) -> Self {
if frenet {
PipeFrame::Frenet
} else {
PipeFrame::RotationMinimizing
}
}
}
pub fn deserialize_pipe_frame<'de, D>(deserializer: D) -> Result<PipeFrame, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(untagged)]
enum Stored {
Flag(bool),
Frame(PipeFrame),
}
Ok(match Stored::deserialize(deserializer)? {
Stored::Flag(frenet) => PipeFrame::from_frenet(frenet),
Stored::Frame(frame) => frame,
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum PipeCorner {
#[default]
Transformed,
Right,
Round,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum PrimitiveKind {
Box {
length: f64,
width: f64,
height: f64,
},
Cylinder {
radius: f64,
height: f64,
angle_deg: f64,
},
Sphere {
radius: f64,
angle1_deg: f64,
angle2_deg: f64,
angle3_deg: f64,
},
Cone {
radius1: f64,
radius2: f64,
height: f64,
angle_deg: f64,
},
Torus {
radius1: f64,
radius2: f64,
angle1_deg: f64,
angle2_deg: f64,
angle3_deg: f64,
},
Ellipsoid {
radius1: f64,
radius2: f64,
radius3: f64,
#[serde(default = "south_pole")]
angle1_deg: f64,
#[serde(default = "north_pole")]
angle2_deg: f64,
#[serde(default = "full_turn")]
angle3_deg: f64,
},
Prism {
sides: u32,
circumradius: f64,
height: f64,
#[serde(default)]
skew_x_deg: f64,
#[serde(default)]
skew_y_deg: f64,
},
Tube { outer: f64, inner: f64, height: f64 },
Wedge {
xmin: f64,
xmax: f64,
ymin: f64,
ymax: f64,
zmin: f64,
zmax: f64,
x2min: f64,
x2max: f64,
z2min: f64,
z2max: f64,
},
}
fn south_pole() -> f64 {
-90.0
}
fn north_pole() -> f64 {
90.0
}
fn full_turn() -> f64 {
360.0
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Placement {
pub origin: [f64; 3],
pub x_axis: [f64; 3],
pub z_axis: [f64; 3],
}
impl Default for Placement {
fn default() -> Self {
Self {
origin: [0.0; 3],
x_axis: [1.0, 0.0, 0.0],
z_axis: [0.0, 0.0, 1.0],
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum EdgeSelection {
All,
OfFaces(Vec<[f64; 3]>),
OfPickedFaces(Vec<FaceProbe>),
Near(Vec<[f64; 3]>),
Picked(Vec<EdgeProbe>),
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct EdgeProbe {
pub point: [f64; 3],
pub direction: [f64; 3],
#[serde(default)]
pub faces: [TopoName; 2],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum ThicknessJoin {
#[default]
Intersection,
Arc,
}
impl ThicknessJoin {
pub const ALL: [ThicknessJoin; 2] = [ThicknessJoin::Intersection, ThicknessJoin::Arc];
pub fn label(&self) -> &'static str {
match self {
ThicknessJoin::Intersection => "Intersection",
ThicknessJoin::Arc => "Arc",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum ChamferSpec {
EqualDistance { distance: f64 },
TwoDistances { distance1: f64, distance2: f64 },
DistanceAngle { distance: f64, angle_deg: f64 },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum BoolKind {
Fuse,
Cut,
Common,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum SolidOp {
Shape { brep: Vec<u8> },
Sweep {
profile: Profile,
kind: SweepKind,
op: BooleanOp,
},
SweepFace {
face: FaceProbe,
kind: SweepKind,
op: BooleanOp,
},
SweepFaceOf {
shape: Vec<u8>,
transform: Option<Box<[[f64; 4]; 4]>>,
point: [f64; 3],
kind: SweepKind,
op: BooleanOp,
},
RevolveToFaceOf {
profile: Profile,
kind: SweepKind,
shape: Vec<u8>,
transform: Option<Box<[[f64; 4]; 4]>>,
point: [f64; 3],
op: BooleanOp,
},
LoftThrough {
sections: Vec<LoftSection>,
ruled: bool,
closed: bool,
op: BooleanOp,
},
Loft {
sections: Vec<Profile>,
ruled: bool,
closed: bool,
op: BooleanOp,
},
Pipe {
profile: Profile,
spine: Profile,
#[serde(default, alias = "frenet", deserialize_with = "deserialize_pipe_frame")]
frame: PipeFrame,
#[serde(default)]
corner: PipeCorner,
#[serde(default)]
sections: Vec<Profile>,
op: BooleanOp,
},
PipeThrough {
profile: LoftSection,
path: PipePath,
#[serde(default)]
frame: PipeFrame,
#[serde(default)]
corner: PipeCorner,
#[serde(default)]
sections: Vec<LoftSection>,
op: BooleanOp,
},
Primitive {
kind: PrimitiveKind,
placement: Placement,
op: BooleanOp,
},
Fillet {
radius: f64,
edges: EdgeSelection,
#[serde(default)]
follow_tangent: bool,
},
BlendFaces { radius: f64, faces: [FaceProbe; 2] },
Chamfer {
spec: ChamferSpec,
flip: bool,
edges: EdgeSelection,
#[serde(default)]
follow_tangent: bool,
},
Draft {
angle_deg: f64,
neutral_point: [f64; 3],
neutral_normal: [f64; 3],
pull_dir: Option<[f64; 3]>,
faces: Vec<[f64; 3]>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
face_names: Vec<TopoName>,
},
Refine,
OffsetFaces {
faces: Vec<[f64; 3]>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
face_names: Vec<TopoName>,
distance: f64,
},
MoveFaces {
faces: Vec<[f64; 3]>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
face_names: Vec<TopoName>,
transform: [[f64; 4]; 4],
},
RemoveFaces {
faces: Vec<[f64; 3]>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
face_names: Vec<TopoName>,
},
Thickness {
value: f64,
open_faces: Vec<[f64; 3]>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
open_face_names: Vec<TopoName>,
inward: bool,
#[serde(default)]
join: ThicknessJoin,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
both_sides: bool,
},
Transform {
transforms: Vec<[[f64; 4]; 4]>,
originals: Vec<usize>,
},
TransformCopies {
transforms: Vec<[[f64; 4]; 4]>,
originals: Vec<usize>,
},
Pattern {
steps: Vec<PatternStep>,
originals: Vec<usize>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
skipped: Vec<u32>,
},
Boolean {
tool_brep: Vec<u8>,
kind: BoolKind,
#[serde(default)]
tool_transform: Option<[[f64; 4]; 4]>,
},
Surface(SurfaceOp),
WithTolerance { tolerance: f64, op: Box<SolidOp> },
Project {
profile: Profile,
faces: Vec<FaceProbe>,
mode: ProjectMode,
height: f64,
},
Wrap {
profile: Profile,
faces: Vec<FaceProbe>,
mode: ProjectMode,
height: f64,
},
HalfSpace { origin: [f64; 3], normal: [f64; 3] },
OffsetSolid { distance: f64 },
Scale {
factors: [f64; 3],
centre: Option<[f64; 3]>,
},
KeepPiece { near: [f64; 3] },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum ProjectMode {
#[default]
Split,
Emboss,
Deboss,
}
impl ProjectMode {
pub const ALL: [ProjectMode; 3] =
[ProjectMode::Split, ProjectMode::Emboss, ProjectMode::Deboss];
pub fn label(&self) -> &'static str {
match self {
ProjectMode::Split => "Split lines",
ProjectMode::Emboss => "Emboss",
ProjectMode::Deboss => "Deboss",
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum CurveSource {
Sketch {
plane: ProfilePlane,
wire: ProfileWire,
},
Edge(EdgeProbe),
BodyEdge {
brep: Vec<u8>,
edge: EdgeProbe,
#[serde(default)]
transform: Option<Box<[[f64; 4]; 4]>>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum Continuity {
#[default]
G0,
G1,
G2,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum SurfaceOp {
Extrude {
curves: Vec<CurveSource>,
direction: [f64; 3],
length: f64,
#[serde(default)]
symmetric: bool,
},
Revolve {
curves: Vec<CurveSource>,
origin: [f64; 3],
axis: [f64; 3],
angle_deg: f64,
},
PlanarFill { curves: Vec<CurveSource> },
Fill {
boundary: Vec<CurveSource>,
#[serde(default)]
continuity: Continuity,
},
Ruled {
first: CurveSource,
second: CurveSource,
},
Loft {
sections: Vec<CurveSource>,
#[serde(default)]
closed: bool,
},
Sweep {
profile: Vec<CurveSource>,
path: Vec<CurveSource>,
#[serde(default)]
frame: PipeFrame,
},
GuidedLoft {
sections: Vec<CurveSource>,
guides: Vec<CurveSource>,
},
SweepTwoRails {
profile: Vec<CurveSource>,
first_rail: Vec<CurveSource>,
second_rail: Vec<CurveSource>,
},
Offset {
faces: Vec<FaceProbe>,
distance: f64,
},
Extend {
edges: Vec<EdgeProbe>,
length: f64,
#[serde(default)]
continuity: Continuity,
},
Blend {
first: EdgeProbe,
second: EdgeProbe,
#[serde(default)]
continuity: Continuity,
},
Split {
faces: Vec<FaceProbe>,
curves: Vec<CurveSource>,
},
Sew {
#[serde(default)]
gap: f64,
},
Fillet { edges: Vec<EdgeProbe>, radius: f64 },
FilletFaces {
first: FaceProbe,
second: FaceProbe,
radius: f64,
#[serde(default)]
flip: [bool; 2],
},
Thicken {
thickness: f64,
#[serde(default)]
both_sides: bool,
},
TrimByPlane { origin: [f64; 3], normal: [f64; 3] },
Mirror { origin: [f64; 3], normal: [f64; 3] },
TrimByScan {
scan: Vec<[f32; 3]>,
triangles: Vec<u32>,
tolerance: f64,
share: f64,
},
FitScattered {
points: Vec<[f64; 3]>,
tolerance: f64,
},
FitNetwork {
curves: Vec<CurveSource>,
polylines: Vec<Vec<[f64; 3]>>,
#[serde(default)]
patches: Vec<[i32; 4]>,
#[serde(default)]
chained: Vec<[Vec<i32>; 4]>,
#[serde(default)]
corrections: u32,
points: Vec<[f64; 3]>,
tolerance: f64,
smoothing: f64,
creases: Vec<u32>,
},
}
impl SurfaceOp {
pub fn constructs(&self) -> bool {
!matches!(
self,
SurfaceOp::Sew { .. }
| SurfaceOp::Fillet { .. }
| SurfaceOp::FilletFaces { .. }
| SurfaceOp::Thicken { .. }
| SurfaceOp::TrimByPlane { .. }
| SurfaceOp::Mirror { .. }
| SurfaceOp::Split { .. }
| SurfaceOp::Extend { .. }
| SurfaceOp::TrimByScan { .. }
)
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum PatternStep {
Transforms(Vec<[[f64; 4]; 4]>),
Path(PathLayout),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum PatternPath {
Wire {
plane: ProfilePlane,
wire: ProfileWire,
},
Edge(EdgeProbe),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PathLayout {
pub path: PatternPath,
pub count: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub spacing: Option<f64>,
#[serde(default)]
pub reversed: bool,
#[serde(default)]
pub align: bool,
}
impl SolidOp {
pub fn inner(&self) -> &SolidOp {
match self {
SolidOp::WithTolerance { op, .. } => op.inner(),
op => op,
}
}
pub fn boolean_tolerance(&self) -> Option<f64> {
match self {
SolidOp::WithTolerance { tolerance, .. } => Some(*tolerance),
_ => None,
}
}
pub fn with_boolean_tolerance(self, tolerance: Option<f64>) -> SolidOp {
match tolerance {
Some(tolerance) => SolidOp::WithTolerance {
tolerance,
op: Box::new(self),
},
None => self,
}
}
pub fn starts_shape(&self) -> bool {
match self.inner() {
SolidOp::Surface(op) => op.constructs(),
_ => self.boolean_op() == Some(BooleanOp::NewSolid),
}
}
pub fn boolean_op(&self) -> Option<BooleanOp> {
match self.inner() {
SolidOp::Sweep { op, .. }
| SolidOp::SweepFace { op, .. }
| SolidOp::SweepFaceOf { op, .. }
| SolidOp::RevolveToFaceOf { op, .. }
| SolidOp::Loft { op, .. }
| SolidOp::LoftThrough { op, .. }
| SolidOp::PipeThrough { op, .. }
| SolidOp::Pipe { op, .. }
| SolidOp::Primitive { op, .. } => Some(*op),
SolidOp::Shape { .. } => Some(BooleanOp::NewSolid),
_ => None,
}
}
}
#[derive(Debug, Clone, Default, Error)]
#[error("op {op_index}: {message}")]
pub struct ChainError {
pub op_index: usize,
pub message: String,
pub edges: EdgeRefusal,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct EdgeRefusal {
pub request: Vec<EdgeProbe>,
pub failing: Vec<FailingEdge>,
#[serde(default)]
pub fits: Option<f64>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct FailingEdge {
pub index: usize,
pub of: usize,
pub probe: EdgeProbe,
pub points: Vec<[f64; 3]>,
pub reason: String,
#[serde(default)]
pub fits: Option<f64>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SolidBuildResult {
pub brep_blob: Vec<u8>,
pub mesh: TriMesh,
pub bounds_mm: Option<([f32; 3], [f32; 3])>,
pub preview: Option<Box<FeaturePreview>>,
pub probes: Vec<Result<ProbeAnswer, String>>,
#[serde(default)]
pub projections: Vec<Result<Vec<ProjectedEdge>, String>>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct FeaturePreview {
pub shown: Option<Box<SolidBuildResult>>,
pub tool: TriMesh,
pub cuts: bool,
}
pub trait Kernel: Send {
fn name(&self) -> &str;
fn initialize(&mut self) -> KernelResult<()>;
fn rebuild(&mut self, request: &RebuildRequest) -> KernelResult<RebuildResponse>;
fn tessellate(&self, body: BodyHandle, detail: &TessellationSettings) -> KernelResult<TriMesh>;
fn import_step(
&mut self,
_path: &Path,
_detail: &TessellationSettings,
) -> KernelResult<ImportedModel> {
Err(KernelError::Unsupported(
"STEP import is not implemented by this kernel".into(),
))
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ProjectedEdge {
Point([f64; 2]),
Line { start: [f64; 2], end: [f64; 2] },
Circle {
centre: [f64; 2],
radius: f64,
range: (f64, f64),
},
Ellipse {
centre: [f64; 2],
major: [f64; 2],
ratio: f64,
range: (f64, f64),
},
Parabola {
vertex: [f64; 2],
axis: [f64; 2],
focal: f64,
range: (f64, f64),
},
Hyperbola {
centre: [f64; 2],
major: [f64; 2],
minor: [f64; 2],
range: (f64, f64),
},
Spline {
degree: u32,
knots: Vec<f64>,
control_points: Vec<[f64; 2]>,
weights: Vec<f64>,
},
Polyline(Vec<[f64; 2]>),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SectionCurve {
pub curve: ProjectedEdge,
pub points: Vec<[f64; 3]>,
#[serde(default)]
pub reversed: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SectionRun {
pub curves: Vec<SectionCurve>,
pub closed: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LoopEdge {
pub points: Vec<[f64; 3]>,
#[serde(default)]
pub seam: bool,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Drawing2d {
pub unit_mm: Option<f64>,
pub curves: Vec<DrawingCurve>,
#[serde(default)]
pub texts: Vec<DrawingText>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DrawingCurve {
pub hidden: bool,
pub shape: DrawingShape,
#[serde(default)]
pub layer: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DrawingText {
pub at: [f64; 2],
pub height: f64,
pub angle: f64,
pub text: String,
#[serde(default)]
pub layer: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum DrawingShape {
Polyline {
points: Vec<[f64; 2]>,
bulges: Vec<f64>,
closed: bool,
},
Arc {
centre: [f64; 2],
radius: f64,
start_angle: f64,
end_angle: f64,
},
Circle {
centre: [f64; 2],
radius: f64,
},
Ellipse {
centre: [f64; 2],
major: [f64; 2],
ratio: f64,
start_param: f64,
end_param: f64,
},
Spline {
points: Vec<[f64; 2]>,
closed: bool,
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct VolumeRegion {
pub missing: bool,
pub volume: f64,
pub depth: f64,
pub layer: bool,
pub min: [f64; 3],
pub max: [f64; 3],
pub unsure: bool,
}
#[derive(Debug, Clone)]
pub struct Overlap {
pub volume_mm3: f64,
pub centre_mm: [f64; 3],
pub mesh: TriMesh,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Gap {
pub distance_mm: f64,
pub on_a: [f64; 3],
pub on_b: [f64; 3],
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MedialPath {
pub points: Vec<[f64; 2]>,
pub clearance: Vec<f64>,
pub boundary_ends: [bool; 2],
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Narrowest {
pub at: [f64; 2],
pub clearance: f64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct MedialRegion {
pub wires: Vec<usize>,
pub paths: Vec<MedialPath>,
pub narrowest: Option<Narrowest>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct FaceProbe {
pub point: [f64; 3],
pub normal: [f64; 3],
#[serde(default)]
pub name: TopoName,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum ShapeProbe {
Face {
point: [f64; 3],
normal: [f64; 3],
#[serde(default)]
name: TopoName,
},
Edge {
point: [f64; 3],
direction: [f64; 3],
#[serde(default)]
faces: [TopoName; 2],
#[serde(default, skip_serializing_if = "Option::is_none")]
along: Option<f64>,
},
Mass,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum ProbeAnswer {
Face {
point: [f64; 3],
normal: [f64; 3],
surface: FaceSurface,
},
Edge {
point: [f64; 3],
direction: [f64; 3],
start: [f64; 3],
end: [f64; 3],
middle: [f64; 3],
circle: Option<ProbedCircle>,
#[serde(default, skip_serializing_if = "Option::is_none")]
along: Option<([f64; 3], [f64; 3])>,
},
Mass {
centre: [f64; 3],
axes: [[f64; 3]; 3],
},
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ProbedCircle {
pub centre: [f64; 3],
pub normal: [f64; 3],
pub radius: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ChainProbe {
pub after_op: usize,
pub probe: ShapeProbe,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
pub struct ProjectionProbe {
pub point: [f64; 3],
#[serde(default)]
pub faces: [TopoName; 2],
#[serde(default)]
pub section: bool,
pub plane: ProfilePlane,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ChainProjection {
pub after_op: usize,
pub probe: ProjectionProbe,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct CentreLine {
pub points: Vec<[f64; 3]>,
pub length: f64,
pub deviation: f64,
pub straight: bool,
}
#[derive(Debug, Clone, PartialEq)]
pub struct RecognizedHole {
pub entry: [f64; 3],
pub direction: [f64; 3],
pub diameter: f64,
pub depth: f64,
pub through: bool,
pub drill_point_deg: Option<f64>,
pub faces: Vec<([f64; 3], [f64; 3])>,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct EdgeContinuity {
pub point: [f64; 3],
pub gap: f64,
pub angle_deg: f64,
#[serde(default)]
pub curvature: Option<f64>,
}
pub type FacePoints = ([f64; 3], Vec<([f64; 3], [f64; 3])>);
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct PathFrame {
pub point: [f64; 3],
pub tangent: [f64; 3],
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PathFrames {
pub length: f64,
pub closed: bool,
pub frames: Vec<PathFrame>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FitMethod {
#[default]
LeastSquares,
MinimumZone,
Inscribed,
Circumscribed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum FitKind {
Plane,
Sphere,
Cylinder,
Cone,
Torus,
Circle,
Line,
}
impl FitKind {
pub const ALL: [FitKind; 7] = [
FitKind::Plane,
FitKind::Sphere,
FitKind::Cylinder,
FitKind::Cone,
FitKind::Torus,
FitKind::Circle,
FitKind::Line,
];
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FitRequest {
pub kind: FitKind,
pub points: Vec<[f64; 3]>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub normals: Vec<[f64; 3]>,
#[serde(default)]
pub sigma_cutoff: Option<f64>,
#[serde(default)]
pub fixed_radius: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum FittedShape {
Plane {
origin: [f64; 3],
normal: [f64; 3],
},
Sphere {
centre: [f64; 3],
radius: f64,
},
Cylinder {
point: [f64; 3],
axis: [f64; 3],
radius: f64,
},
Cone {
apex: [f64; 3],
axis: [f64; 3],
half_angle: f64,
},
Torus {
centre: [f64; 3],
axis: [f64; 3],
major: f64,
minor: f64,
},
Circle {
centre: [f64; 3],
normal: [f64; 3],
radius: f64,
},
Line {
point: [f64; 3],
direction: [f64; 3],
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FitAnswer {
pub shape: FittedShape,
pub sigma: f64,
pub form: (f64, f64),
pub used: Vec<bool>,
pub residuals: Vec<f64>,
pub converged: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GrowRequest {
pub kind: FitKind,
pub seeds: Vec<[f64; 3]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sigma_cutoff: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub normal_limit_deg: Option<f64>,
#[serde(default)]
pub peel: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_triangles: Option<usize>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GrowAnswer {
pub fit: FitAnswer,
pub triangles: Vec<u32>,
pub vertices: Vec<u32>,
pub seeds_in_region: Vec<bool>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct DistanceRequest {
pub points: Vec<[f64; 3]>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub normals: Vec<[f64; 3]>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub facing_limit_deg: Option<f64>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct RegisterRequest {
pub points: Vec<[f64; 3]>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub normals: Vec<[f64; 3]>,
#[serde(default)]
pub search: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_distance: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub facing_limit_deg: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Registration {
pub transform: [[f64; 4]; 3],
pub rms: f64,
pub inliers: usize,
pub sampled: usize,
pub converged: bool,
#[serde(default)]
pub free: Vec<FreeMotion>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FreeMotion {
pub about: [f64; 3],
pub rotation: [f64; 3],
pub translation: [f64; 3],
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ThicknessRequest {
pub points: Vec<[f64; 3]>,
pub normals: Vec<[f64; 3]>,
#[serde(default)]
pub sphere: bool,
#[serde(default)]
pub cone_deg: f64,
#[serde(default)]
pub rays: u32,
#[serde(default)]
pub facing_limit_deg: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max: Option<f64>,
}
#[derive(Debug, Clone, Copy)]
pub enum DistanceTarget<'a> {
Mesh(&'a TriMesh),
Shape(&'a [u8]),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Orientation {
pub origin: [f64; 3],
pub x_axis: [f64; 3],
pub z_axis: [f64; 3],
pub said: String,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct SectionChain {
pub points: Vec<[f64; 3]>,
pub outward: Vec<[f64; 3]>,
pub closed: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ShadowRequest {
pub plane: ProfilePlane,
pub play: f64,
pub tolerance: f64,
pub round_below_deg: f64,
#[serde(default)]
pub fill_below: f64,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct ShadowAnswer {
pub silhouette: Vec<Vec<[f64; 2]>>,
pub outline: Vec<ProfileWire>,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ChainFit {
pub tolerance: f64,
pub corners: bool,
pub axis_snap_deg: Option<f64>,
pub min_bow: f64,
pub closed: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum MeshRegion {
All,
Box {
min: [f64; 3],
max: [f64; 3],
},
Ball {
centre: [f64; 3],
radius: f64,
},
Vertices(Vec<u32>),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(not(feature = "exhaustive"), non_exhaustive)]
pub enum MeshOp {
RemoveIslands { smaller_than: f64 },
Delete { region: MeshRegion },
Flip { region: MeshRegion },
Fill {
holes_up_to: f64,
#[serde(default)]
near: Option<[f64; 3]>,
#[serde(default)]
fairing: MeshFairing,
},
Smooth {
region: MeshRegion,
bumps_up_to: f64,
move_at_most: f64,
#[serde(default)]
keep_edges_deg: Option<f64>,
},
Offset { region: MeshRegion, distance: f64 },
Boolean {
operand: MeshOperand,
operation: BooleanOp,
chord: f64,
},
Shell {
thickness: f64,
#[serde(default)]
side: MeshSide,
},
Reduce {
tolerance: f64,
triangle_limit: usize,
},
Cut {
origin: [f64; 3],
normal: [f64; 3],
keep_above: bool,
close: bool,
bridge: f64,
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum MeshOperand {
Shape {
brep: String,
transform: [[f64; 4]; 4],
},
Primitive {
kind: PrimitiveKind,
placement: Placement,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
pub enum MeshSide {
Inward,
Outward,
#[default]
Both,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrimRequest {
pub solid: Vec<u8>,
pub scan: TriMesh,
pub depth: f64,
pub gap: f64,
pub away: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TrimAnswer {
pub brep: Vec<u8>,
pub volume: f64,
pub mating_area: f64,
pub gap_median: f64,
pub gap_range: [f64; 2],
}
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
pub enum MeshFairing {
#[default]
Curved,
Flat,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum MeshStepReport {
Cut {
capped_loops: usize,
bridged: usize,
open_loops: usize,
},
Boolean {
cut_triangles: usize,
volume: f64,
},
Shell {
hollow: bool,
volume: f64,
},
Smooth {
max: f64,
rms: f64,
},
Reduce {
within_share: f64,
p999: f64,
furthest: [f64; 3],
max: f64,
rms: f64,
target_met: bool,
},
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct MeshStep {
pub faces: usize,
pub note: String,
#[serde(default)]
pub report: Option<MeshStepReport>,
}
#[derive(Debug, Clone, Default)]
pub struct MeshChainAnswer {
pub mesh: TriMesh,
pub sources: Vec<Option<u32>>,
pub steps: Vec<MeshStep>,
pub failed: Option<(usize, String)>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ConstructionShape {
Point([f64; 3]),
Axis {
origin: [f64; 3],
z: [f64; 3],
x: [f64; 3],
},
Polyline {
points: Vec<[f64; 3]>,
closed: bool,
},
Circle {
centre: [f64; 3],
normal: [f64; 3],
radius: f64,
},
Plane {
origin: [f64; 3],
normal: [f64; 3],
x_axis: [f64; 3],
u: [f64; 2],
v: [f64; 2],
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ConstructionItem {
pub name: String,
pub shape: ConstructionShape,
}
#[derive(Debug, Clone, Default)]
pub struct IgesExport {
pub text: String,
pub warnings: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SymmetryPlane {
pub point: [f64; 3],
pub normal: [f64; 3],
pub rms: f64,
}
pub trait KernelQueries: Send + Sync {
fn thickness(
&self,
_target: DistanceTarget<'_>,
_request: &ThicknessRequest,
) -> KernelResult<Vec<f64>> {
Err(KernelError::Unsupported("thickness".into()))
}
fn mesh_sections(
&self,
_mesh: &TriMesh,
_origin: [f64; 3],
_normal: [f64; 3],
_offsets: &[f64],
) -> KernelResult<Vec<Vec<SectionChain>>> {
Err(KernelError::Unsupported("mesh_sections".into()))
}
fn mesh_shadow(&self, _mesh: &TriMesh, _request: &ShadowRequest) -> KernelResult<ShadowAnswer> {
Err(KernelError::Unsupported("mesh_shadow".into()))
}
fn fit_chain_2d(&self, _points: &[[f64; 2]], _fit: &ChainFit) -> KernelResult<DrawingShape> {
Err(KernelError::Unsupported("fit_chain_2d".into()))
}
fn build_mesh_chain(&self, _start: &TriMesh, _ops: &[MeshOp]) -> KernelResult<MeshChainAnswer> {
Err(KernelError::Unsupported("build_mesh_chain".into()))
}
fn write_mesh(&self, _mesh: &TriMesh, _format: &str) -> KernelResult<Vec<u8>> {
Err(KernelError::Unsupported("write_mesh".into()))
}
fn trim_to_scan(&self, _request: &TrimRequest) -> KernelResult<TrimAnswer> {
Err(KernelError::Unsupported("trim_to_scan".into()))
}
fn write_dxf(
&self,
_visible: &[Vec<[f64; 2]>],
_hidden: &[Vec<[f64; 2]>],
) -> KernelResult<String> {
Err(KernelError::Unsupported("write_dxf".into()))
}
fn write_dxf_drawing(&self, _drawing: &Drawing2d) -> KernelResult<String> {
Err(KernelError::Unsupported("write_dxf_drawing".into()))
}
fn write_construction_step(
&self,
_part: &str,
_items: &[ConstructionItem],
) -> KernelResult<Vec<u8>> {
Err(KernelError::Unsupported("write_construction_step".into()))
}
fn write_construction_iges(
&self,
_part: &str,
_items: &[ConstructionItem],
) -> KernelResult<IgesExport> {
Err(KernelError::Unsupported("write_construction_iges".into()))
}
fn orient(&self, _mesh: &TriMesh) -> KernelResult<Orientation> {
Err(KernelError::Unsupported("orient".into()))
}
fn symmetry_plane(&self, _mesh: &TriMesh) -> KernelResult<SymmetryPlane> {
Err(KernelError::Unsupported("symmetry_plane".into()))
}
fn register(
&self,
_target: DistanceTarget<'_>,
_request: &RegisterRequest,
) -> KernelResult<Registration> {
Err(KernelError::Unsupported("register".into()))
}
fn volume_difference(
&self,
_scan: &TriMesh,
_solid: &[u8],
_cell: f64,
) -> KernelResult<Vec<VolumeRegion>> {
Err(KernelError::Unsupported("volume_difference".into()))
}
fn signed_distance(
&self,
_target: DistanceTarget<'_>,
_request: &DistanceRequest,
) -> KernelResult<Vec<f64>> {
Err(KernelError::Unsupported("signed_distance".into()))
}
fn grow(&self, _mesh: &TriMesh, _request: &GrowRequest) -> KernelResult<GrowAnswer> {
Err(KernelError::Unsupported("grow".into()))
}
fn continuity(&self, _brep: &[u8]) -> KernelResult<Vec<EdgeContinuity>> {
Err(KernelError::Unsupported("continuity".into()))
}
fn fit(&self, _request: &FitRequest) -> KernelResult<FitAnswer> {
Err(KernelError::Unsupported("fit".into()))
}
fn zone_fit(
&self,
_kind: FitKind,
_method: FitMethod,
_points: &[[f64; 3]],
) -> KernelResult<FitAnswer> {
Err(KernelError::Unsupported("zone_fit".into()))
}
fn curvature(
&self,
_brep: &[u8],
_faces: &[FacePoints],
) -> KernelResult<Vec<Vec<Option<[f64; 2]>>>> {
Err(KernelError::Unsupported("curvature".into()))
}
fn face_edges(&self, _brep: &[u8], _near: [f64; 3]) -> KernelResult<Vec<([f64; 3], [f64; 3])>> {
Err(KernelError::Unsupported("face_edges".into()))
}
fn recognize_holes(&self, _brep: &[u8]) -> KernelResult<(Vec<RecognizedHole>, usize)> {
Err(KernelError::Unsupported("recognize_holes".into()))
}
fn overlap(
&self,
_a: &[u8],
_b: &[u8],
_b_in_a: &[[f64; 4]; 4],
) -> KernelResult<Option<Overlap>> {
Err(KernelError::Unsupported("overlap".into()))
}
fn gap(&self, _a: &[u8], _b: &[u8], _b_in_a: &[[f64; 4]; 4]) -> KernelResult<Gap> {
Err(KernelError::Unsupported("gap".into()))
}
fn mirror(&self, _brep: &[u8], _point: [f64; 3], _normal: [f64; 3]) -> KernelResult<Vec<u8>> {
Err(KernelError::Unsupported("mirror".into()))
}
fn measure(&self, _brep: &[u8]) -> KernelResult<PhysicalProperties> {
Err(KernelError::Unsupported("measure".into()))
}
fn project_edge(
&self,
brep: &[u8],
near: [f64; 3],
plane: &ProfilePlane,
) -> KernelResult<ProjectedEdge>;
fn edge_frames(
&self,
_brep: &[u8],
_near: [f64; 3],
_stations: &[f64],
) -> KernelResult<PathFrames> {
Err(KernelError::Unsupported("points along an edge".into()))
}
fn wire_frames(
&self,
_plane: &ProfilePlane,
_wire: &ProfileWire,
_stations: &[f64],
) -> KernelResult<PathFrames> {
Err(KernelError::Unsupported("points along a wire".into()))
}
fn pattern_transforms(
&self,
_brep: Option<&[u8]>,
_steps: &[PatternStep],
) -> KernelResult<Vec<[[f64; 4]; 4]>> {
Err(KernelError::Unsupported("pattern transforms".into()))
}
fn face_of(&self, _brep: &[u8], _near: [f64; 3]) -> KernelResult<Vec<u8>> {
Err(KernelError::Unsupported(
"taking a face out of a solid".into(),
))
}
fn edge_of(&self, _brep: &[u8], _near: [f64; 3]) -> KernelResult<Vec<u8>> {
Err(KernelError::Unsupported(
"taking an edge out of a solid".into(),
))
}
fn section_face(
&self,
_brep: &[u8],
_near: [f64; 3],
_plane: &ProfilePlane,
) -> KernelResult<Vec<ProjectedEdge>> {
Err(KernelError::Unsupported("face section".into()))
}
fn solid_pieces(&self, _brep: &[u8]) -> KernelResult<Vec<[f64; 3]>> {
Err(KernelError::Unsupported("solid pieces".into()))
}
fn section(
&self,
_brep: &[u8],
_plane: &ProfilePlane,
_near: Option<[f64; 3]>,
) -> KernelResult<Vec<SectionRun>> {
Err(KernelError::Unsupported("section".into()))
}
fn face_loops(&self, _brep: &[u8], _near: [f64; 3]) -> KernelResult<Vec<Vec<LoopEdge>>> {
Err(KernelError::Unsupported("face loops".into()))
}
fn read_dxf(&self, _text: &str) -> KernelResult<Drawing2d> {
Err(KernelError::Unsupported("reading DXF".into()))
}
fn profile_mesh(&self, _profile: &Profile) -> KernelResult<TriMesh> {
Err(KernelError::Unsupported("profile mesh".into()))
}
fn medial_axis(&self, _profile: &Profile, _tolerance: f64) -> KernelResult<Vec<MedialRegion>> {
Err(KernelError::Unsupported("medial axis".into()))
}
fn centre_line(
&self,
_brep: &[u8],
_from: &FaceProbe,
_to: &FaceProbe,
_tolerance: f64,
) -> KernelResult<CentreLine> {
Err(KernelError::Unsupported("centre line".into()))
}
fn probe(&self, _brep: &[u8], _probe: &ShapeProbe) -> KernelResult<ProbeAnswer> {
Err(KernelError::Unsupported("probing a shape".into()))
}
}
#[derive(Debug, Error)]
pub enum KernelError {
#[error("kernel initialization failed: {0}")]
Initialization(String),
#[error("kernel not initialized")]
NotInitialized,
#[error("operation unsupported: {0}")]
Unsupported(String),
#[error("invalid kernel input: {0}")]
InvalidInput(String),
#[error("import failed: {0}")]
Import(String),
#[error(transparent)]
Other(#[from] anyhow::Error),
}
#[cfg(test)]
mod tests {
use super::*;
fn pipe_json(frame: &str) -> String {
let plane = r#"{"origin":[0,0,0],"x_axis":[1,0,0],"y_axis":[0,1,0],"normal":[0,0,1]}"#;
let profile = format!(
r#"{{"plane":{plane},"wires":[{{"segments":[{{"Circle":{{"center":[0,0],"radius":1}}}}]}}]}}"#
);
format!(r#"{{"Pipe":{{"profile":{profile},"spine":{profile},{frame}"op":"NewSolid"}}}}"#)
}
fn frame_of(json: &str) -> PipeFrame {
match serde_json::from_str::<SolidOp>(json).unwrap() {
SolidOp::Pipe { frame, .. } => frame,
other => panic!("not a pipe: {other:?}"),
}
}
#[test]
fn a_pipe_written_with_the_frenet_flag_reads_as_its_frame() {
assert_eq!(frame_of(&pipe_json(r#""frenet":true,"#)), PipeFrame::Frenet);
assert_eq!(
frame_of(&pipe_json(r#""frenet":false,"#)),
PipeFrame::RotationMinimizing
);
assert_eq!(frame_of(&pipe_json("")), PipeFrame::RotationMinimizing);
}
#[test]
fn a_pipe_frame_round_trips() {
let frame = PipeFrame::Binormal {
direction: [0.0, 0.0, 1.0],
};
let text = serde_json::to_string(&frame).unwrap();
assert_eq!(frame_of(&pipe_json(&format!(r#""frame":{text},"#))), frame);
}
}