Skip to main content

kernel_api/
lib.rs

1//! printCAD's geometry interface: meshes, profiles and solid operations
2//! as plain data, with no geometry code. The app's kernel adapter answers
3//! it, and workbench packages build their solids as [`SolidOp`] plans
4//! through `printcad-bench-api`.
5//!
6//! Versions follow `printcad-bench-api`'s: 0.1.x speaks the workbench
7//! contract `printcad:workbench@0.1`, and a patch release only adds.
8//! [`FaceSurface`] and [`ProfileSegment`], which the app sends a package,
9//! are `#[non_exhaustive]` unless the `exhaustive` feature (printCAD's
10//! own) is on; [`SolidOp`] and the enums inside it keep their variants'
11//! fields within a minor version.
12
13use serde::{Deserialize, Serialize};
14use std::path::Path;
15use thiserror::Error;
16
17pub mod naming;
18pub use naming::TopoName;
19
20/// Convenience alias for kernel fallible operations.
21pub type KernelResult<T> = Result<T, KernelError>;
22
23/// Handle to a body managed by the kernel.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
25pub struct BodyHandle(pub u64);
26
27/// Request describing which features or bodies must be recomputed.
28#[derive(Debug, Clone, Default, Serialize, Deserialize)]
29pub struct RebuildRequest {
30    /// Feature identifiers that triggered the rebuild.
31    pub dirty_features: Vec<String>,
32    /// Whether dependent features should be recomputed automatically.
33    pub propagate: bool,
34}
35
36/// Response returned for every rebuild invocation.
37#[derive(Debug, Clone, Default, Serialize, Deserialize)]
38pub struct RebuildResponse {
39    /// Bodies that were modified or regenerated.
40    pub updated_bodies: Vec<BodyHandle>,
41    /// Kernel provided diagnostics or warnings.
42    pub diagnostics: Vec<String>,
43}
44
45/// How linear (chord) deflection is chosen for kernel meshing.
46///
47/// The default is **bbox-scaled** deflection: absolute chord height is derived
48/// from the sum of the shape's bounding-box extents and a dimensionless
49/// multiplier ([`TessellationSettings::mesh_deviation`], typically `0.2`).
50/// This produces visually consistent tessellation across small and large
51/// parts without per-model tuning.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
53#[serde(rename_all = "snake_case")]
54pub enum LinearDeflectionMode {
55    /// Bounding-box scaled: linear deflection = `(dx + dy + dz) / 300 ×`
56    /// [`TessellationSettings::mesh_deviation`].
57    #[default]
58    BboxScaled,
59    /// Fixed absolute linear deflection in model units (millimetres for STEP geometry).
60    AbsoluteMm,
61}
62
63/// Parameters controlling tessellation quality for viewport rendering.
64#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
65pub struct TessellationSettings {
66    #[serde(default)]
67    pub linear_deflection_mode: LinearDeflectionMode,
68    /// Dimensionless multiplier applied to the bbox-derived chord height when
69    /// [`Self::linear_deflection_mode`] is [`LinearDeflectionMode::BboxScaled`].
70    /// Typical range `0.05..=1.0`; smaller values yield finer triangulation.
71    #[serde(default = "default_mesh_deviation")]
72    pub mesh_deviation: f32,
73    /// Absolute chord height in model units when using [`LinearDeflectionMode::AbsoluteMm`].
74    pub chord_tolerance: f32,
75    pub angular_tolerance_deg: f32,
76    /// When true, the kernel collapses vertices that share a position across
77    /// multiple faces *and* whose face normals are within
78    /// [`Self::weld_angle_threshold_deg`] of each other. This typically
79    /// shrinks vertex counts by 4–6× on dense CAD models without flattening
80    /// genuine sharp edges, since dissimilar face normals stay separate.
81    #[serde(default = "default_weld_cross_face")]
82    pub weld_cross_face: bool,
83    /// Maximum angle between two face normals at a shared position for them
84    /// to be merged into a single welded vertex. Above this angle the kernel
85    /// keeps them separate so hard CAD edges stay crisp under shading.
86    /// Defaults to 30°.
87    #[serde(default = "default_weld_angle_threshold_deg")]
88    pub weld_angle_threshold_deg: f32,
89    /// When true, import keeps each body's shape snapshot in `brep_blob`
90    /// beside its mesh. Meshing happens during the import either way;
91    /// serializing the snapshots is most of the work of reading a large
92    /// assembly, and turning this off skips it. The STEP asset remains
93    /// available in the document regardless.
94    #[serde(default = "default_persist_brep_snapshot")]
95    pub persist_brep_snapshot: bool,
96    /// When true, compute mesh outline / edge segments for the viewport (face
97    /// boundaries). Skipping saves CPU on huge imports when outlines are not needed.
98    #[serde(default = "default_generate_boundary_edges")]
99    pub generate_boundary_edges: bool,
100}
101
102fn default_weld_cross_face() -> bool {
103    false
104}
105
106fn default_weld_angle_threshold_deg() -> f32 {
107    30.0
108}
109
110fn default_mesh_deviation() -> f32 {
111    0.2
112}
113
114fn default_persist_brep_snapshot() -> bool {
115    true
116}
117
118fn default_generate_boundary_edges() -> bool {
119    true
120}
121
122impl Default for TessellationSettings {
123    fn default() -> Self {
124        Self {
125            linear_deflection_mode: LinearDeflectionMode::default(),
126            mesh_deviation: default_mesh_deviation(),
127            chord_tolerance: 0.1,
128            angular_tolerance_deg: 28.65,
129            weld_cross_face: default_weld_cross_face(),
130            weld_angle_threshold_deg: default_weld_angle_threshold_deg(),
131            persist_brep_snapshot: default_persist_brep_snapshot(),
132            generate_boundary_edges: default_generate_boundary_edges(),
133        }
134    }
135}
136
137/// Triangular mesh generated from kernel bodies for viewports and export.
138#[derive(Debug, Clone, Default, Serialize, Deserialize)]
139pub struct TriMesh {
140    pub positions: Vec<[f32; 3]>,
141    pub normals: Vec<[f32; 3]>,
142    pub indices: Vec<u32>,
143    /// Optional line-list of feature edges that should be drawn as outlines on
144    /// top of the shaded surface (e.g. face boundaries from a STEP import).
145    /// Stored as flat pairs of indices into [`Self::positions`]; the slice
146    /// length is therefore always a multiple of two. Empty when the source has
147    /// no edge information available.
148    #[serde(default)]
149    pub edges: Vec<u32>,
150    /// Optional per-vertex linear RGB albedo in 0..1 (same length as [`Self::positions`] when set).
151    /// Empty means the renderer uses the body tint from push constants only.
152    #[serde(default)]
153    pub colors: Vec<[f32; 3]>,
154    /// Which kernel face each triangle was cut from: one entry per triangle
155    /// (`indices.len() / 3`), an index into the body's faces in the kernel's
156    /// own order. A curved face is many triangles with many normals, and
157    /// this is what lets a click on one of them select the whole face.
158    /// Empty when the source has no faces (a sketch, a datum, a mesh saved
159    /// before faces were recorded), and a consumer falls back to geometry.
160    #[serde(default)]
161    pub faces: Vec<u32>,
162    /// Which kernel edge each outline segment belongs to: one entry per
163    /// pair in [`Self::edges`], an index into the body's edges in the
164    /// kernel's own order. A curved edge is many segments, and this is what
165    /// lets a click on one of them select the whole edge. Empty when the
166    /// outline came from triangle boundaries rather than kernel edges.
167    #[serde(default)]
168    pub edge_ids: Vec<u32>,
169    /// The exact surface of each kernel face, indexed like [`Self::faces`]:
170    /// what a picked face is, beyond the triangles drawn for it. Empty when
171    /// the source has no faces.
172    #[serde(default, skip_serializing_if = "Vec::is_empty")]
173    pub face_surfaces: Vec<FaceSurface>,
174    /// The name of each kernel face, indexed like [`Self::faces`]: what a
175    /// pick keeps so a rebuild finds the face again. Zero where a face has
176    /// none; empty when the source names none.
177    #[serde(default, skip_serializing_if = "Vec::is_empty")]
178    pub face_names: Vec<TopoName>,
179    /// The names of the two faces each kernel edge runs between, indexed
180    /// like [`Self::edge_ids`].
181    #[serde(default, skip_serializing_if = "Vec::is_empty")]
182    pub edge_faces: Vec<[TopoName; 2]>,
183}
184
185/// The kind and placement of a kernel face's surface, in the mesh's frame.
186#[cfg_attr(not(feature = "exhaustive"), non_exhaustive)]
187#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
188pub enum FaceSurface {
189    /// A plane through `origin`, with the face's outward `normal`.
190    Plane { origin: [f32; 3], normal: [f32; 3] },
191    /// A circular cylinder about the line through `origin` along `axis`.
192    Cylinder {
193        origin: [f32; 3],
194        axis: [f32; 3],
195        radius: f32,
196    },
197    /// A circular cone about the line through `apex` along `axis`.
198    Cone { apex: [f32; 3], axis: [f32; 3] },
199    /// A sphere.
200    Sphere { center: [f32; 3], radius: f32 },
201    /// A torus about the line through `center` along `axis`.
202    Torus { center: [f32; 3], axis: [f32; 3] },
203    /// Any other surface: a spline, a sweep.
204    #[default]
205    Other,
206}
207
208impl FaceSurface {
209    /// The axis a turned face turns about, as a point on it and its
210    /// direction: a cylinder's, a cone's or a torus's.
211    pub fn axis(&self) -> Option<([f32; 3], [f32; 3])> {
212        match *self {
213            FaceSurface::Cylinder { origin, axis, .. } => Some((origin, axis)),
214            FaceSurface::Cone { apex, axis } => Some((apex, axis)),
215            FaceSurface::Torus { center, axis } => Some((center, axis)),
216            _ => None,
217        }
218    }
219
220    /// The same surface moved: `point` maps points, `direction` maps
221    /// directions (a rigid motion, so lengths stay).
222    pub fn moved(
223        &self,
224        point: impl Fn([f32; 3]) -> [f32; 3],
225        direction: impl Fn([f32; 3]) -> [f32; 3],
226    ) -> Self {
227        match *self {
228            FaceSurface::Plane { origin, normal } => FaceSurface::Plane {
229                origin: point(origin),
230                normal: direction(normal),
231            },
232            FaceSurface::Cylinder {
233                origin,
234                axis,
235                radius,
236            } => FaceSurface::Cylinder {
237                origin: point(origin),
238                axis: direction(axis),
239                radius,
240            },
241            FaceSurface::Cone { apex, axis } => FaceSurface::Cone {
242                apex: point(apex),
243                axis: direction(axis),
244            },
245            FaceSurface::Sphere { center, radius } => FaceSurface::Sphere {
246                center: point(center),
247                radius,
248            },
249            FaceSurface::Torus { center, axis } => FaceSurface::Torus {
250                center: point(center),
251                axis: direction(axis),
252            },
253            FaceSurface::Other => FaceSurface::Other,
254        }
255    }
256}
257
258impl TriMesh {
259    /// Compute axis-aligned bounding box `(min, max)` of the mesh, if non-empty.
260    pub fn bounds(&self) -> Option<([f32; 3], [f32; 3])> {
261        if self.positions.is_empty() {
262            return None;
263        }
264        let mut min = self.positions[0];
265        let mut max = self.positions[0];
266        for &[x, y, z] in &self.positions {
267            if x < min[0] {
268                min[0] = x;
269            }
270            if y < min[1] {
271                min[1] = y;
272            }
273            if z < min[2] {
274                min[2] = z;
275            }
276            if x > max[0] {
277                max[0] = x;
278            }
279            if y > max[1] {
280                max[1] = y;
281            }
282            if z > max[2] {
283                max[2] = z;
284            }
285        }
286        Some((min, max))
287    }
288}
289
290/// A single body produced by an external import (e.g. STEP).
291///
292/// The kernel returns one entry per placed body in the source file, meshed.
293/// [`Self::brep_blob`] is empty when no snapshot was kept:
294/// [`TessellationSettings::persist_brep_snapshot`] off, a full-mesh import,
295/// or a mesh file, which has no shape.
296#[derive(Debug, Clone, Serialize, Deserialize)]
297pub struct ImportedBody {
298    /// Optional name extracted from the source file (e.g. STEP product label).
299    pub name: Option<String>,
300    /// Tessellated mesh ready for the viewport.
301    #[serde(default)]
302    pub mesh: TriMesh,
303    /// Serialized shape snapshot for this body, when one was kept: ogeom
304    /// native-format text bytes (`ogeom::io::native`, one root shape per
305    /// blob).
306    #[serde(default, skip_serializing_if = "Vec::is_empty")]
307    pub brep_blob: Vec<u8>,
308    /// Per-face linear RGB albedo in face-exploration order
309    /// (`ogeom::topo::explore` with a Face filter) over the matching shape
310    /// snapshot.
311    #[serde(default, skip_serializing_if = "Vec::is_empty")]
312    pub face_colors: Vec<[f32; 3]>,
313    /// Axis-aligned bounds in millimetres from the raw BRep (before tessellation).
314    #[serde(default, skip_serializing_if = "Option::is_none")]
315    pub bounds_mm: Option<([f32; 3], [f32; 3])>,
316    /// What the kernel's checker found in the body's shape as read.
317    #[serde(default, skip_serializing_if = "Option::is_none")]
318    pub health: Option<ShapeHealth>,
319    /// The names of the layers the file puts the body on.
320    #[serde(default, skip_serializing_if = "Vec::is_empty")]
321    pub layers: Vec<String>,
322}
323
324/// What the kernel's checker found in a shape.
325///
326/// The checker sorts its findings in two: *broken*, where an algorithm
327/// reading the shape gets a wrong answer rather than an error, and
328/// *suspect*, out of order but harmless to every operation. Only broken
329/// findings ask for a repair.
330#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
331pub struct ShapeHealth {
332    /// Findings that make an algorithm reading the shape answer wrongly.
333    pub broken: usize,
334    /// Findings that are out of order but harmless.
335    pub suspect: usize,
336    /// The first findings, a sentence each, broken first.
337    #[serde(default, skip_serializing_if = "Vec::is_empty")]
338    pub findings: Vec<String>,
339    /// The kernel's repair has run on the shape these findings describe.
340    #[serde(default)]
341    pub repaired: bool,
342    /// The shape is a mesh converted as it is: its flat stretches are
343    /// faces and its curved ones still the mesh's facets, which a refine
344    /// can rebuild on the surfaces they approximate.
345    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
346    pub faceted: bool,
347}
348
349impl ShapeHealth {
350    /// How many findings a health record keeps as sentences.
351    pub const KEPT_FINDINGS: usize = 8;
352
353    /// Whether the shape has anything a repair is for.
354    pub fn is_broken(&self) -> bool {
355        self.broken > 0
356    }
357
358    /// One line for a tooltip: the counts, then the findings kept.
359    pub fn describe(&self) -> String {
360        let mut lines = Vec::new();
361        let counts = match (self.broken, self.suspect) {
362            (0, 0) => "The shape checks clean".to_string(),
363            (b, 0) => format!("{b} shape defect(s) that make operations answer wrongly"),
364            (0, s) => format!("{s} shape irregularity(ies), harmless to operations"),
365            (b, s) => format!(
366                "{b} shape defect(s) that make operations answer wrongly, \
367                 and {s} harmless irregularity(ies)"
368            ),
369        };
370        lines.push(counts);
371        if self.repaired && self.is_broken() {
372            lines.push("Repaired; these remain, beyond what the repair mends".to_string());
373        }
374        lines.extend(self.findings.iter().cloned());
375        let shown = self.findings.len();
376        let total = self.broken + self.suspect;
377        if total > shown {
378            lines.push(format!("… and {} more", total - shown));
379        }
380        lines.join("\n")
381    }
382}
383
384/// A shape run through the kernel's repair: the mended snapshot, its mesh,
385/// what the repair did, and what the checker finds afterwards.
386#[derive(Debug, Clone, Default)]
387pub struct RepairResult {
388    /// Native-format snapshot of the mended shape.
389    pub brep_blob: Vec<u8>,
390    /// Per-face colours for the mended shape, in its face order; empty when
391    /// the repair changed the faces too much to carry them over.
392    pub face_colors: Vec<[f32; 3]>,
393    /// Render mesh of the mended shape.
394    pub mesh: TriMesh,
395    /// Axis-aligned bounds in millimetres.
396    pub bounds_mm: Option<([f32; 3], [f32; 3])>,
397    /// The checker's findings on the mended shape, marked repaired.
398    pub health: ShapeHealth,
399    /// What was mended, a phrase each ("12 tolerances tightened").
400    pub mended: Vec<String>,
401}
402
403/// A mesh body turned into a B-rep by the kernel: the shape, its mesh, the
404/// checker's verdict, and what the conversion found.
405#[derive(Debug, Clone, Default)]
406pub struct MeshSolidResult {
407    /// Native-format snapshot of the shape.
408    pub brep_blob: Vec<u8>,
409    /// Per-face colours in the shape's face order: the mesh's colour on
410    /// every face when it had one colour, else empty.
411    pub face_colors: Vec<[f32; 3]>,
412    /// Render mesh of the shape, with its kernel faces and edges.
413    pub mesh: TriMesh,
414    /// Axis-aligned bounds in millimetres.
415    pub bounds_mm: Option<([f32; 3], [f32; 3])>,
416    /// The checker's findings on the shape.
417    pub health: ShapeHealth,
418    /// Every piece of the mesh closed and became a solid; otherwise the
419    /// shape is the open shell(s) the mesh makes.
420    pub closed: bool,
421    /// What the conversion did and where the mesh does not close, a phrase
422    /// each ("12 triangles into 6 faces", "3 hole edges").
423    pub summary: Vec<String>,
424}
425
426/// A body's measure: its volume, surface area and centre of mass, exact
427/// where the kernel has a closed form for its faces.
428#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
429pub struct PhysicalProperties {
430    /// Enclosed volume in mm³; `None` when the shape encloses none (an open
431    /// shell, a sheet) or its shell is wound inside out.
432    pub volume_mm3: Option<f64>,
433    /// Total surface area in mm².
434    pub area_mm2: f64,
435    /// Centre of mass at uniform density, in mm; the centre of the surface
436    /// when there is no volume.
437    pub centre_mm: [f64; 3],
438    /// Some face had no closed form, so the figures were integrated over a
439    /// tessellation and are close rather than exact (within a fraction of a
440    /// percent on curved walls).
441    #[serde(default)]
442    pub approximate: bool,
443}
444
445/// Node type emitted by STEP import hierarchy reconstruction.
446#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
447#[serde(rename_all = "snake_case")]
448pub enum ImportedNodeKind {
449    #[default]
450    Assembly,
451    Part,
452    Instance,
453    /// The group holding an import's annotations.
454    Annotations,
455    /// One annotation the file carries: a dimension, a tolerance, a datum
456    /// or a note.
457    Annotation,
458}
459
460/// What an imported annotation states.
461#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
462#[serde(rename_all = "snake_case")]
463pub enum AnnotationKind {
464    /// A size or a location, with its value.
465    Dimension,
466    /// A geometric tolerance: flatness, position, profile and their kin.
467    Tolerance,
468    /// A datum letter, or a target a datum is contacted at.
469    Datum,
470    /// Text with nothing measured behind it.
471    Note,
472    /// A drawn annotation the file does not say more about.
473    #[default]
474    Other,
475}
476
477impl AnnotationKind {
478    /// The kind as a word for the interface.
479    pub fn label(self) -> &'static str {
480        match self {
481            AnnotationKind::Dimension => "Dimension",
482            AnnotationKind::Tolerance => "Tolerance",
483            AnnotationKind::Datum => "Datum",
484            AnnotationKind::Note => "Note",
485            AnnotationKind::Other => "Annotation",
486        }
487    }
488}
489
490/// One annotation an imported file carries (a dimension, a tolerance, a
491/// datum or a note), with what it draws.
492///
493/// The polylines and the anchor are in document millimetres, placed where
494/// the file's bodies are placed, so an annotation drawn on an assembly's
495/// part sits on that part.
496#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
497pub struct ImportedAnnotation {
498    /// The name the file gives it (`Linear Size.3`, `Flatness.1`), or the
499    /// text it shows where the file names it by that.
500    pub name: String,
501    pub kind: AnnotationKind,
502    /// What a label shows: `Ø 35 ±0.2`, `Flatness 0.2`, `A`.
503    pub text: String,
504    /// The drawn geometry: leaders, frames, witness lines and whatever
505    /// strokes the file draws its text with.
506    #[serde(default, skip_serializing_if = "Vec::is_empty")]
507    pub polylines: Vec<Vec<[f32; 3]>>,
508    /// Where the label goes; `None` for an annotation that draws nothing.
509    #[serde(default, skip_serializing_if = "Option::is_none")]
510    pub anchor: Option<[f32; 3]>,
511    /// The body the annotation describes, as an index into
512    /// [`ImportedModel::bodies`], where the file says which.
513    #[serde(default, skip_serializing_if = "Option::is_none")]
514    pub body_index: Option<usize>,
515}
516
517/// One hierarchy node from the imported file's product structure.
518///
519/// Nodes can either be pure containers (`body_index = None`) or reference a
520/// renderable payload in [`ImportedModel::bodies`].
521#[derive(Debug, Clone, Serialize, Deserialize)]
522pub struct ImportedNode {
523    /// Stable id scoped to one import result.
524    pub id: u64,
525    /// Parent node id; None means root.
526    #[serde(default, skip_serializing_if = "Option::is_none")]
527    pub parent_id: Option<u64>,
528    /// Human-readable name from the file's product labels when available.
529    #[serde(default, skip_serializing_if = "Option::is_none")]
530    pub name: Option<String>,
531    /// Structural type of this node.
532    #[serde(default)]
533    pub kind: ImportedNodeKind,
534    /// Initial visibility from source file metadata (if available).
535    #[serde(default = "default_imported_node_visible")]
536    pub visible: bool,
537    /// Index into [`ImportedModel::bodies`] when this node owns geometry.
538    #[serde(default, skip_serializing_if = "Option::is_none")]
539    pub body_index: Option<usize>,
540    /// Local transform matrix (row-major) relative to parent, if known.
541    #[serde(default, skip_serializing_if = "Option::is_none")]
542    pub local_transform: Option<[[f32; 4]; 4]>,
543}
544
545fn default_imported_node_visible() -> bool {
546    true
547}
548
549/// Length unit declared by an imported source file.
550///
551/// This is a thin mirror of `core_document::Unit` that lives in `kernel_api`
552/// to avoid pulling document-side types into the kernel crate. App code is
553/// responsible for translating it into the document's display unit.
554#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
555#[serde(rename_all = "snake_case")]
556pub enum LengthUnit {
557    Millimetre,
558    Centimetre,
559    Metre,
560    Inch,
561    Foot,
562}
563
564/// Result of importing an external CAD file.
565#[derive(Debug, Clone, Default, Serialize, Deserialize)]
566pub struct ImportedModel {
567    /// One entry per top-level body in the source file.
568    pub bodies: Vec<ImportedBody>,
569    /// Everything the reader had to say about the file, kept whole so it
570    /// can be handed to whoever maintains the kernel rather than scrolled
571    /// past in a terminal.
572    #[serde(default)]
573    pub report: ImportReport,
574    /// Optional assembly/object tree reconstructed from the file's product
575    /// structure.
576    #[serde(default)]
577    pub nodes: Vec<ImportedNode>,
578    /// Length unit declared by the source file, when detectable. Geometry in
579    /// `bodies` is *always* expressed in millimetres regardless; this field
580    /// is purely informational and used by the UI to pick a display unit.
581    #[serde(default)]
582    pub source_unit: Option<LengthUnit>,
583    /// The file's annotations (dimensions, tolerances, datums and notes)
584    /// in file order, the drawn ones first.
585    #[serde(default, skip_serializing_if = "Vec::is_empty")]
586    pub annotations: Vec<ImportedAnnotation>,
587}
588
589/// What the reader had to say about a file.
590///
591/// A community STEP file routinely produces a thousand lines of "this edge
592/// misses its vertex by a micron"; each one is true and none is actionable
593/// on its own. The kernel counts them by kind, and the whole prose stays
594/// here for the report a user can send along with the file.
595#[derive(Debug, Clone, Default, Serialize, Deserialize)]
596pub struct ImportReport {
597    /// The kernel that read the file, by name and version.
598    pub kernel: String,
599    /// One entry per kind of imperfection, largest count first.
600    pub summary: Vec<ImportWarningKind>,
601    /// Every warning, one line each, in the order the reader met them.
602    pub warnings: Vec<String>,
603    /// STEP entity ids of faces that read without a complete trim, so they
604    /// draw with gaps unless healed.
605    pub untrimmed_faces: Vec<u64>,
606    /// Entity keywords the reader never visited, with counts. Presentation
607    /// and annotation land here by design; geometry landing here is a gap.
608    pub skipped: Vec<(String, usize)>,
609}
610
611impl ImportReport {
612    /// Whether there is anything worth writing down.
613    pub fn is_clean(&self) -> bool {
614        self.warnings.is_empty() && self.untrimmed_faces.is_empty()
615    }
616}
617
618/// One kind of imperfect import, counted rather than repeated.
619#[derive(Debug, Clone, Serialize, Deserialize)]
620pub struct ImportWarningKind {
621    /// Stable across runs: `vertex-miss`, `boundary-slop`, `fit-short`,
622    /// `untrimmed`.
623    pub kind: String,
624    pub count: usize,
625    /// The worst measured value among them, in millimetres, for the kinds
626    /// that measure one; zero otherwise.
627    pub worst: f64,
628    /// One entity id to look at first.
629    pub exemplar: u64,
630}
631
632/// One segment of a closed 2D profile wire, in sketch-plane coordinates
633/// (millimetres). Arcs are encoded as three on-curve points so consumers
634/// never have to agree on a winding convention.
635#[cfg_attr(not(feature = "exhaustive"), non_exhaustive)]
636#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
637pub enum ProfileSegment {
638    Line {
639        start: [f64; 2],
640        end: [f64; 2],
641    },
642    /// Circular arc through three points (start → mid → end).
643    Arc {
644        start: [f64; 2],
645        mid: [f64; 2],
646        end: [f64; 2],
647    },
648    Circle {
649        center: [f64; 2],
650        radius: f64,
651    },
652    /// Full ellipse. `major` is the vector from the center to a major-axis
653    /// vertex; the minor radius is `|major| * ratio` with `ratio` in (0, 1].
654    Ellipse {
655        center: [f64; 2],
656        major: [f64; 2],
657        ratio: f64,
658    },
659    /// Elliptical arc between two parameter angles (radians, counter-clockwise
660    /// in the ellipse frame where the major axis is at parameter 0).
661    EllipseArc {
662        center: [f64; 2],
663        major: [f64; 2],
664        ratio: f64,
665        start_param: f64,
666        end_param: f64,
667    },
668    /// Cubic B-spline through the given control points. A periodic spline
669    /// closes smoothly on itself; an open one runs first → last control point.
670    BSpline {
671        control_points: Vec<[f64; 2]>,
672        periodic: bool,
673    },
674    /// A B-spline of any degree over its own knots, rational when it has
675    /// weights: an exact conic arc, a spline drawn through points. An open
676    /// one's knots are clamped (`control points + degree + 1` of them), so
677    /// it runs first → last control point; a periodic one is a uniform ring
678    /// over its control points closing smoothly on itself, and its knots
679    /// are not used.
680    Nurbs {
681        degree: u32,
682        knots: Vec<f64>,
683        control_points: Vec<[f64; 2]>,
684        /// One per control point; empty when every weight is one.
685        #[serde(default, skip_serializing_if = "Vec::is_empty")]
686        weights: Vec<f64>,
687        #[serde(default)]
688        periodic: bool,
689    },
690}
691
692/// What a [`SolidOp::PipeThrough`] runs along.
693#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
694pub enum PipePath {
695    /// A sketch's wire.
696    Profile(Profile),
697    /// Edges of the running solid, joined end to end.
698    Edges(Vec<EdgeProbe>),
699    /// Edges of another solid (a native-format snapshot, moved by
700    /// `transform` into the body's frame), joined end to end; the probes
701    /// are in the body's frame.
702    EdgesOf {
703        shape: Vec<u8>,
704        transform: Option<Box<[[f64; 4]; 4]>>,
705        edges: Vec<EdgeProbe>,
706    },
707}
708
709/// One section of a [`SolidOp::LoftThrough`].
710#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
711pub enum LoftSection {
712    Profile(Profile),
713    /// The flat face of the running solid the probe finds, by its outer
714    /// and inner boundaries.
715    Face(FaceProbe),
716    /// A point the loft closes to, in the body's frame.
717    Point([f64; 3]),
718}
719
720/// A closed loop of profile segments. Consecutive segments share endpoints;
721/// a single `Circle` segment is a wire by itself.
722#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
723pub struct ProfileWire {
724    pub segments: Vec<ProfileSegment>,
725    /// The name of each segment, one per segment, by what it was drawn from
726    /// (a sketch element): the faces a feature sweeps from it are named by
727    /// it, so they keep their names while dimensions change. Empty, or a
728    /// zero, where a segment has no such name.
729    #[serde(default, skip_serializing_if = "Vec::is_empty")]
730    pub names: Vec<TopoName>,
731}
732
733impl ProfileWire {
734    /// A wire of `segments` with no names.
735    pub fn new(segments: Vec<ProfileSegment>) -> Self {
736        Self {
737            segments,
738            names: Vec::new(),
739        }
740    }
741
742    /// The name of segment `index`, when it has one.
743    pub fn name_of(&self, index: usize) -> Option<TopoName> {
744        self.names.get(index).copied().filter(|n| *n != 0)
745    }
746}
747
748/// The plane a profile lives on, in world coordinates (millimetres).
749#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
750pub struct ProfilePlane {
751    pub origin: [f64; 3],
752    pub x_axis: [f64; 3],
753    pub y_axis: [f64; 3],
754    pub normal: [f64; 3],
755}
756
757/// The XY plane through the origin.
758impl Default for ProfilePlane {
759    fn default() -> Self {
760        Self {
761            origin: [0.0; 3],
762            x_axis: [1.0, 0.0, 0.0],
763            y_axis: [0.0, 1.0, 0.0],
764            normal: [0.0, 0.0, 1.0],
765        }
766    }
767}
768
769/// How an extrusion combines with the body's existing solid.
770#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
771pub enum BooleanOp {
772    /// Replace / start the body's solid (first feature).
773    NewSolid,
774    /// Union with the existing solid (Pad on an existing body).
775    Fuse,
776    /// Subtract from the existing solid (Pocket).
777    Cut,
778    /// Keep only what the existing solid and the tool share.
779    Common,
780}
781
782/// A set of closed wires on one plane. The largest-area wire is the outer
783/// boundary, the rest become holes.
784#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
785pub struct Profile {
786    pub plane: ProfilePlane,
787    pub wires: Vec<ProfileWire>,
788}
789
790/// Where a one-directional extrusion stops.
791#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
792pub enum ExtrudeTermination {
793    /// Fixed length in millimetres.
794    Blind { distance: f64 },
795    /// Extend well past the base solid's bounding box in this direction.
796    ThroughAll,
797    /// Stop on the given world-space plane, shifted by `offset` along its
798    /// normal (a picked planar face plus an offset-to-face value).
799    UpToPlane {
800        point: [f64; 3],
801        normal: [f64; 3],
802        offset: f64,
803    },
804    /// Stop on the base solid's face named `name`, else the one nearest
805    /// `point` (a picked face, where it was picked), exactly on its surface
806    /// whatever its shape, pushed `offset` out along its outward normal.
807    /// With no base solid, or no face of it there, the plane through
808    /// `point` square to `normal`.
809    UpToFace {
810        point: [f64; 3],
811        normal: [f64; 3],
812        offset: f64,
813        #[serde(default)]
814        name: TopoName,
815    },
816    /// Stop at the first face of the base solid hit along the extrusion
817    /// direction, on its surface.
818    ToFirst,
819    /// Stop at the last face of the base solid hit along the extrusion
820    /// direction, on its surface.
821    ToLast,
822    /// Stop on a set of the base solid's faces: every line of the sweep
823    /// ends at the first of them it meets, moved `offset` further along the
824    /// sweep (a negative offset stops short).
825    UpToShape { faces: Vec<FaceProbe>, offset: f64 },
826    /// Stop on a face of another shape: the face of `shape` (a native-format
827    /// snapshot, moved by `transform`, a rigid row-major 4×4 matrix, into
828    /// the body's frame) nearest `point`, exactly on its surface whatever
829    /// its shape, pushed `offset` out along its outward normal.
830    UpToFaceOf {
831        shape: Vec<u8>,
832        transform: Option<Box<[[f64; 4]; 4]>>,
833        point: [f64; 3],
834        offset: f64,
835    },
836}
837
838/// Where a revolution stops turning.
839#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
840pub enum RevolveTermination {
841    /// Through the sweep's own angles.
842    #[default]
843    Angle,
844    /// On the first face of the base solid the profile's centre meets as it
845    /// turns.
846    ToFirst,
847    /// On the last face of the base solid the profile's centre meets as it
848    /// turns.
849    ToLast,
850    /// On the base solid's face nearest the probe.
851    UpToFace(FaceProbe),
852}
853
854/// How a profile is swept into a solid.
855#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
856pub enum SweepKind {
857    /// Linear extrusion along `plane.normal` (or `direction` when set).
858    Extrude {
859        termination: ExtrudeTermination,
860        /// Independent termination for the opposite side of the sketch plane
861        /// (two-sided extrusion). `None` extrudes one side only.
862        second_side: Option<ExtrudeTermination>,
863        /// Extrude half the blind distance to each side of the sketch plane.
864        symmetric: bool,
865        /// Swap which side of the sketch plane is "forward".
866        reversed: bool,
867        /// Draft angle applied along the sweep; positive widens the far end.
868        taper_deg: f64,
869        /// Custom world-space sweep direction; `None` uses the plane normal.
870        direction: Option<[f64; 3]>,
871    },
872    /// Revolution about an axis lying IN the sketch plane, given in sketch
873    /// 2D coordinates (point + direction). `angle_deg` in (0, 360].
874    Revolve {
875        axis_origin: [f64; 2],
876        axis_dir: [f64; 2],
877        angle_deg: f64,
878        /// Independent sweep angle for the opposite rotation direction.
879        second_angle_deg: Option<f64>,
880        /// Center the sweep on the sketch plane (half the angle each way).
881        midplane: bool,
882        reversed: bool,
883        /// Where the turn stops; anything but `Angle` takes the angle from
884        /// what the profile meets and leaves the angles above unused.
885        #[serde(default)]
886        termination: RevolveTermination,
887    },
888    /// Sweep the profile along a helix whose axis lies in the sketch plane.
889    /// A cone angle moves every point away from the axis by tan(angle) of
890    /// every pitch it climbs.
891    Helix {
892        axis_origin: [f64; 2],
893        axis_dir: [f64; 2],
894        pitch: f64,
895        height: f64,
896        left_handed: bool,
897        cone_angle_deg: f64,
898        reversed: bool,
899        /// How many turns, when given: the pitch is then `height / turns`
900        /// and `pitch` is not read. A height of 0 with turns and growth is
901        /// a flat spiral.
902        #[serde(default)]
903        turns: Option<f64>,
904        /// How far every point moves away from the axis per turn, when
905        /// given, in place of `cone_angle_deg`.
906        #[serde(default)]
907        growth: Option<f64>,
908    },
909    /// Sweep the profile along a helix whose axis runs square to the sketch
910    /// plane through `axis_origin` (sketch 2D coordinates): every point of
911    /// the profile climbs its own helix about it, the profile staying
912    /// level. The rest reads as for `Helix`.
913    HelixNormal {
914        axis_origin: [f64; 2],
915        pitch: f64,
916        height: f64,
917        left_handed: bool,
918        cone_angle_deg: f64,
919        reversed: bool,
920        #[serde(default)]
921        turns: Option<f64>,
922        #[serde(default)]
923        growth: Option<f64>,
924    },
925}
926
927/// How a pipe's section turns as it runs down its path.
928#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
929pub enum PipeFrame {
930    /// Rotation-minimizing: the section neither twists nor kinks where the
931    /// path bends.
932    #[default]
933    RotationMinimizing,
934    /// The path's own curvature frame, turning with it.
935    Frenet,
936    /// The section turns about the path so that one direction of it keeps
937    /// pointing at a second path running beside the first.
938    Auxiliary { path: Profile },
939    /// The section keeps a fixed binormal: the world-space direction square
940    /// to the path that the section's frame holds all the way.
941    Binormal { direction: [f64; 3] },
942    /// The section keeps its orientation in space: carried along the path
943    /// without ever turning, as it is drawn.
944    Fixed,
945}
946
947impl PipeFrame {
948    /// The frame an older `frenet` flag named.
949    pub fn from_frenet(frenet: bool) -> Self {
950        if frenet {
951            PipeFrame::Frenet
952        } else {
953            PipeFrame::RotationMinimizing
954        }
955    }
956}
957
958/// Reads a [`PipeFrame`] or the `frenet` flag it stands in for.
959pub fn deserialize_pipe_frame<'de, D>(deserializer: D) -> Result<PipeFrame, D::Error>
960where
961    D: serde::Deserializer<'de>,
962{
963    #[derive(Deserialize)]
964    #[serde(untagged)]
965    enum Stored {
966        Flag(bool),
967        Frame(PipeFrame),
968    }
969    Ok(match Stored::deserialize(deserializer)? {
970        Stored::Flag(frenet) => PipeFrame::from_frenet(frenet),
971        Stored::Frame(frame) => frame,
972    })
973}
974
975/// How a pipe's section turns a sharp corner of its path.
976#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
977pub enum PipeCorner {
978    /// The section is carried into the corner and sheared onto the plane
979    /// bisecting it: the two legs meet on that mitre.
980    #[default]
981    Transformed,
982    /// Each leg runs on straight past the corner and the two are fused,
983    /// leaving the outside of the corner square.
984    Right,
985    /// The section turns about the corner, the outside of it rounded.
986    Round,
987}
988
989/// Parametric primitive shapes (dimensions in millimetres, angles degrees).
990#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
991pub enum PrimitiveKind {
992    Box {
993        length: f64,
994        width: f64,
995        height: f64,
996    },
997    Cylinder {
998        radius: f64,
999        height: f64,
1000        angle_deg: f64,
1001    },
1002    Sphere {
1003        radius: f64,
1004        /// Latitude range and longitude sweep (three-angle parameterization).
1005        angle1_deg: f64,
1006        angle2_deg: f64,
1007        angle3_deg: f64,
1008    },
1009    Cone {
1010        radius1: f64,
1011        radius2: f64,
1012        height: f64,
1013        angle_deg: f64,
1014    },
1015    Torus {
1016        radius1: f64,
1017        radius2: f64,
1018        angle1_deg: f64,
1019        angle2_deg: f64,
1020        angle3_deg: f64,
1021    },
1022    /// An ellipsoid, cut as a sphere is: between two latitudes about its
1023    /// third axis and through a sweep round it.
1024    Ellipsoid {
1025        radius1: f64,
1026        radius2: f64,
1027        radius3: f64,
1028        #[serde(default = "south_pole")]
1029        angle1_deg: f64,
1030        #[serde(default = "north_pole")]
1031        angle2_deg: f64,
1032        #[serde(default = "full_turn")]
1033        angle3_deg: f64,
1034    },
1035    /// A regular prism, its top shifted by the skew angles: leaning that
1036    /// far from its axis toward its x and its y.
1037    Prism {
1038        sides: u32,
1039        circumradius: f64,
1040        height: f64,
1041        #[serde(default)]
1042        skew_x_deg: f64,
1043        #[serde(default)]
1044        skew_y_deg: f64,
1045    },
1046    /// Box with an independently sized top rectangle (zero top spans give a
1047    /// pyramid). Spans are along local X (`x2*`) and Z (`z2*`) at height Y.
1048    Wedge {
1049        xmin: f64,
1050        xmax: f64,
1051        ymin: f64,
1052        ymax: f64,
1053        zmin: f64,
1054        zmax: f64,
1055        x2min: f64,
1056        x2max: f64,
1057        z2min: f64,
1058        z2max: f64,
1059    },
1060}
1061
1062fn south_pole() -> f64 {
1063    -90.0
1064}
1065
1066fn north_pole() -> f64 {
1067    90.0
1068}
1069
1070fn full_turn() -> f64 {
1071    360.0
1072}
1073
1074/// A right-handed placement frame in world coordinates (millimetres).
1075#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1076pub struct Placement {
1077    pub origin: [f64; 3],
1078    pub x_axis: [f64; 3],
1079    pub z_axis: [f64; 3],
1080}
1081
1082impl Default for Placement {
1083    fn default() -> Self {
1084        Self {
1085            origin: [0.0; 3],
1086            x_axis: [1.0, 0.0, 0.0],
1087            z_axis: [0.0, 0.0, 1.0],
1088        }
1089    }
1090}
1091
1092/// Which edges of the current solid a dress-up applies to. Edges are
1093/// identified geometrically: by a face they border (sample point on the
1094/// face) or by a point near the edge itself.
1095#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1096pub enum EdgeSelection {
1097    All,
1098    OfFaces(Vec<[f64; 3]>),
1099    /// The edges bordering the picked faces, each found by its name when
1100    /// it has one.
1101    OfPickedFaces(Vec<FaceProbe>),
1102    Near(Vec<[f64; 3]>),
1103    /// Edges picked one by one: each the nearest edge to its point that
1104    /// runs along its direction there.
1105    Picked(Vec<EdgeProbe>),
1106}
1107
1108/// A picked edge, as a point beside it and the way it runs there, and the
1109/// names of the two faces it runs between. A rebuild finds the edge
1110/// between faces of those names, the point choosing among several; without
1111/// names, the nearest edge. A zero direction leaves the way open.
1112#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
1113pub struct EdgeProbe {
1114    pub point: [f64; 3],
1115    pub direction: [f64; 3],
1116    #[serde(default)]
1117    pub faces: [TopoName; 2],
1118}
1119
1120/// How a thickness's walls meet across an edge of the solid.
1121#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1122pub enum ThicknessJoin {
1123    /// The walls run on until they meet: sharp corners.
1124    #[default]
1125    Intersection,
1126    /// The walls round about the edge, the wall thickness its radius.
1127    Arc,
1128}
1129
1130impl ThicknessJoin {
1131    pub const ALL: [ThicknessJoin; 2] = [ThicknessJoin::Intersection, ThicknessJoin::Arc];
1132
1133    pub fn label(&self) -> &'static str {
1134        match self {
1135            ThicknessJoin::Intersection => "Intersection",
1136            ThicknessJoin::Arc => "Arc",
1137        }
1138    }
1139}
1140
1141/// Chamfer sizing, mirroring the three standard input styles.
1142#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1143pub enum ChamferSpec {
1144    EqualDistance { distance: f64 },
1145    TwoDistances { distance1: f64, distance2: f64 },
1146    DistanceAngle { distance: f64, angle_deg: f64 },
1147}
1148
1149/// Boolean between the running solid and an external tool solid.
1150#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1151pub enum BoolKind {
1152    Fuse,
1153    Cut,
1154    Common,
1155}
1156
1157/// One step in a body's build history. Shape-producing steps (`Sweep`,
1158/// `Loft`, `Pipe`, `Primitive`) carry a [`BooleanOp`]; the remaining steps
1159/// modify or combine the running solid directly.
1160///
1161/// A package builds these, so a variant keeps its fields for as long as
1162/// the contract's minor version holds: a new option comes as a new
1163/// variant, or as a new struct that derives `Default`.
1164#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1165pub enum SolidOp {
1166    /// Start the chain from a snapshot of another solid, in the native
1167    /// format `SolidBuildResult::brep_blob` carries. Only ever the first op.
1168    Shape { brep: Vec<u8> },
1169    Sweep {
1170        profile: Profile,
1171        kind: SweepKind,
1172        op: BooleanOp,
1173    },
1174    /// Extrude a flat face of the running solid: its outer and inner
1175    /// boundaries are the profile and its outward normal the sketch
1176    /// normal. `kind` is an `Extrude`.
1177    SweepFace {
1178        face: FaceProbe,
1179        kind: SweepKind,
1180        op: BooleanOp,
1181    },
1182    /// Extrude a flat face of another shape (native-format `shape`, moved by
1183    /// `transform` into this body's frame): the face of it at `point`, a
1184    /// face another body lends this one.
1185    SweepFaceOf {
1186        shape: Vec<u8>,
1187        transform: Option<Box<[[f64; 4]; 4]>>,
1188        point: [f64; 3],
1189        kind: SweepKind,
1190        op: BooleanOp,
1191    },
1192    /// Skin through two or more sections (in order), each a profile, a
1193    /// flat face of the running solid (its boundary) or a point, which
1194    /// only the first or last may be.
1195    LoftThrough {
1196        sections: Vec<LoftSection>,
1197        ruled: bool,
1198        closed: bool,
1199        op: BooleanOp,
1200    },
1201    /// Skin through two or more section profiles (in order).
1202    Loft {
1203        sections: Vec<Profile>,
1204        ruled: bool,
1205        closed: bool,
1206        op: BooleanOp,
1207    },
1208    /// Sweep a profile along an open or closed spine wire from another
1209    /// sketch, the section turning as `frame` says and turning its corners
1210    /// as `corner` says. With `sections`, the section changes shape down
1211    /// the path, passing through each of them where it crosses the path,
1212    /// in order, the profile first.
1213    Pipe {
1214        profile: Profile,
1215        spine: Profile,
1216        #[serde(default, alias = "frenet", deserialize_with = "deserialize_pipe_frame")]
1217        frame: PipeFrame,
1218        #[serde(default)]
1219        corner: PipeCorner,
1220        #[serde(default)]
1221        sections: Vec<Profile>,
1222        op: BooleanOp,
1223    },
1224    /// A pipe whose profile may be a flat face of the running solid, whose
1225    /// path may be edges of a solid, and whose last section may be a point
1226    /// it closes to; the rest reads as for `Pipe`.
1227    PipeThrough {
1228        profile: LoftSection,
1229        path: PipePath,
1230        #[serde(default)]
1231        frame: PipeFrame,
1232        #[serde(default)]
1233        corner: PipeCorner,
1234        #[serde(default)]
1235        sections: Vec<LoftSection>,
1236        op: BooleanOp,
1237    },
1238    Primitive {
1239        kind: PrimitiveKind,
1240        placement: Placement,
1241        op: BooleanOp,
1242    },
1243    /// Round the selected edges; with `follow_tangent`, every edge meeting
1244    /// one of them tangentially joins the selection, and so on along the
1245    /// chain.
1246    Fillet {
1247        radius: f64,
1248        edges: EdgeSelection,
1249        #[serde(default)]
1250        follow_tangent: bool,
1251    },
1252    /// Bevel the selected edges, taking tangent chains as a fillet does.
1253    Chamfer {
1254        spec: ChamferSpec,
1255        flip: bool,
1256        edges: EdgeSelection,
1257        #[serde(default)]
1258        follow_tangent: bool,
1259    },
1260    /// Tilt the selected faces by `angle_deg` about their intersection with
1261    /// the neutral plane.
1262    Draft {
1263        angle_deg: f64,
1264        neutral_point: [f64; 3],
1265        neutral_normal: [f64; 3],
1266        pull_dir: Option<[f64; 3]>,
1267        faces: Vec<[f64; 3]>,
1268        /// The name of each face, one per point, found by name first; empty
1269        /// or zero where a face has none.
1270        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1271        face_names: Vec<TopoName>,
1272    },
1273    /// Merge adjacent faces of the solid that lie on one plane: the split
1274    /// a fuse or cut leaves where two pieces meet flush.
1275    Refine,
1276    /// Offset faces of the running solid along their outward normals by
1277    /// `distance` (negative into the material), the faces around them
1278    /// following on their own surfaces.
1279    OffsetFaces {
1280        faces: Vec<[f64; 3]>,
1281        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1282        face_names: Vec<TopoName>,
1283        distance: f64,
1284    },
1285    /// Move faces of the running solid rigidly by `transform` (row-major,
1286    /// a translation or a rotation), the faces around them following.
1287    MoveFaces {
1288        faces: Vec<[f64; 3]>,
1289        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1290        face_names: Vec<TopoName>,
1291        transform: [[f64; 4]; 4],
1292    },
1293    /// Remove faces of the running solid and close the openings from the
1294    /// neighbouring faces' own geometry: a hole, a boss or a fillet taken
1295    /// away. Faces as points on them, named where they have names.
1296    RemoveFaces {
1297        faces: Vec<[f64; 3]>,
1298        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1299        face_names: Vec<TopoName>,
1300    },
1301    /// Hollow the solid, removing the faces sampled by `open_faces`.
1302    Thickness {
1303        value: f64,
1304        open_faces: Vec<[f64; 3]>,
1305        /// The name of each open face, one per point; empty or zero where
1306        /// a face has none.
1307        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1308        open_face_names: Vec<TopoName>,
1309        inward: bool,
1310        /// How the walls meet where the solid's faces meet.
1311        #[serde(default)]
1312        join: ThicknessJoin,
1313        /// The walls stand on both sides of the solid's faces, `value` each
1314        /// way, rather than on the one `inward` says.
1315        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1316        both_sides: bool,
1317    },
1318    /// Re-apply earlier steps' tool solids (or the whole current solid when
1319    /// `originals` is empty) under each transform, fusing additive tools and
1320    /// cutting subtractive ones. `originals` holds chain indices of earlier
1321    /// shape-producing steps.
1322    Transform {
1323        transforms: Vec<[[f64; 4]; 4]>,
1324        originals: Vec<usize>,
1325    },
1326    /// Boolean against an external solid (another body's shape snapshot,
1327    /// ogeom native-format text bytes).
1328    Boolean {
1329        tool_brep: Vec<u8>,
1330        kind: BoolKind,
1331        /// Where the tool sits in this chain's frame, when the two bodies
1332        /// are placed differently: a rigid row-major 4×4 matrix.
1333        #[serde(default)]
1334        tool_transform: Option<[[f64; 4]; 4]>,
1335    },
1336    /// A surface step: a sheet added to the body, or the body's sheets
1337    /// joined, trimmed or mirrored.
1338    Surface(SurfaceOp),
1339}
1340
1341/// A curve a surface is built from.
1342#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1343pub enum CurveSource {
1344    /// A chain of a sketch's curves, open or closed, on its plane.
1345    Sketch {
1346        plane: ProfilePlane,
1347        wire: ProfileWire,
1348    },
1349    /// An edge of the body's own shape as it stands where the step comes,
1350    /// found as a fillet's picked edges are.
1351    Edge(EdgeProbe),
1352}
1353
1354/// How a surface meets the faces beside it across a shared edge.
1355#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1356pub enum Continuity {
1357    /// Touching: no gap, a crease allowed.
1358    #[default]
1359    G0,
1360    /// Tangent: no crease.
1361    G1,
1362    /// Curvature continuous: no change in how sharply it bends.
1363    G2,
1364}
1365
1366/// The steps of surface modelling. A constructive step (every one but
1367/// `Sew`, `TrimByPlane` and `Mirror`) adds its sheet to the body beside
1368/// what is there; the rest act on all of the body's shape.
1369#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1370pub enum SurfaceOp {
1371    /// Each curve swept straight along `direction` by `length`, both ways
1372    /// by half of it when `symmetric`.
1373    Extrude {
1374        curves: Vec<CurveSource>,
1375        direction: [f64; 3],
1376        length: f64,
1377        #[serde(default)]
1378        symmetric: bool,
1379    },
1380    /// Each curve turned by `angle_deg` about the axis through `origin`
1381    /// along `axis`.
1382    Revolve {
1383        curves: Vec<CurveSource>,
1384        origin: [f64; 3],
1385        axis: [f64; 3],
1386        angle_deg: f64,
1387    },
1388    /// The flat face closed planar loops bound, a loop inside another a
1389    /// hole in it.
1390    PlanarFill { curves: Vec<CurveSource> },
1391    /// The surface curves meeting end to end bound, meeting the faces the
1392    /// boundary edges belong to with `continuity`.
1393    Fill {
1394        boundary: Vec<CurveSource>,
1395        #[serde(default)]
1396        continuity: Continuity,
1397    },
1398    /// The surface of straight lines between two curves, end to end.
1399    Ruled {
1400        first: CurveSource,
1401        second: CurveSource,
1402    },
1403    /// A surface through section curves in order, closing back to the first
1404    /// when `closed`.
1405    Loft {
1406        sections: Vec<CurveSource>,
1407        #[serde(default)]
1408        closed: bool,
1409    },
1410    /// A profile curve swept along a path.
1411    Sweep {
1412        profile: Vec<CurveSource>,
1413        path: Vec<CurveSource>,
1414        #[serde(default)]
1415        frame: PipeFrame,
1416    },
1417    /// Faces carried off along their normals by `distance`, as new faces.
1418    Offset {
1419        faces: Vec<FaceProbe>,
1420        distance: f64,
1421    },
1422    /// Faces carried past picked edges of their boundary by `length`.
1423    Extend {
1424        edges: Vec<EdgeProbe>,
1425        length: f64,
1426        #[serde(default)]
1427        continuity: Continuity,
1428    },
1429    /// A surface bridging two edges, meeting each edge's face with
1430    /// `continuity`.
1431    Blend {
1432        first: EdgeProbe,
1433        second: EdgeProbe,
1434        #[serde(default)]
1435        continuity: Continuity,
1436    },
1437    /// Picked faces split along curves projected onto them.
1438    Split {
1439        faces: Vec<FaceProbe>,
1440        curves: Vec<CurveSource>,
1441    },
1442    /// The body's faces joined where their edges meet, or come within
1443    /// `gap` of each other (0 for exactly); a shell that closes becomes a
1444    /// solid.
1445    Sew {
1446        #[serde(default)]
1447        gap: f64,
1448    },
1449    /// A round of `radius` along picked edges where two faces of a sheet
1450    /// meet.
1451    Fillet { edges: Vec<EdgeProbe>, radius: f64 },
1452    /// The body's sheets given `thickness` along their normals (both ways
1453    /// by half when `both_sides`): a solid.
1454    Thicken {
1455        thickness: f64,
1456        #[serde(default)]
1457        both_sides: bool,
1458    },
1459    /// The body's sheets cut by the plane through `origin`, the side
1460    /// `normal` points to kept.
1461    TrimByPlane { origin: [f64; 3], normal: [f64; 3] },
1462    /// The body's shape and its reflection in the plane through `origin`
1463    /// square to `normal`.
1464    Mirror { origin: [f64; 3], normal: [f64; 3] },
1465}
1466
1467impl SurfaceOp {
1468    /// Whether the step makes a new sheet (and so may begin a chain).
1469    pub fn constructs(&self) -> bool {
1470        !matches!(
1471            self,
1472            SurfaceOp::Sew { .. }
1473                | SurfaceOp::Fillet { .. }
1474                | SurfaceOp::Thicken { .. }
1475                | SurfaceOp::TrimByPlane { .. }
1476                | SurfaceOp::Mirror { .. }
1477                | SurfaceOp::Split { .. }
1478                | SurfaceOp::Extend { .. }
1479        )
1480    }
1481}
1482
1483impl SolidOp {
1484    /// Whether the step makes a shape of its own, so a chain may begin with
1485    /// it: a new solid, or a surface step that adds a sheet.
1486    pub fn starts_shape(&self) -> bool {
1487        match self {
1488            SolidOp::Surface(op) => op.constructs(),
1489            _ => self.boolean_op() == Some(BooleanOp::NewSolid),
1490        }
1491    }
1492
1493    /// The boolean role of a shape-producing step; `None` for modifiers.
1494    pub fn boolean_op(&self) -> Option<BooleanOp> {
1495        match self {
1496            SolidOp::Sweep { op, .. }
1497            | SolidOp::SweepFace { op, .. }
1498            | SolidOp::SweepFaceOf { op, .. }
1499            | SolidOp::Loft { op, .. }
1500            | SolidOp::LoftThrough { op, .. }
1501            | SolidOp::PipeThrough { op, .. }
1502            | SolidOp::Pipe { op, .. }
1503            | SolidOp::Primitive { op, .. } => Some(*op),
1504            // A snapshot is a solid in itself: it begins a chain.
1505            SolidOp::Shape { .. } => Some(BooleanOp::NewSolid),
1506            _ => None,
1507        }
1508    }
1509}
1510
1511/// Error from executing a body's solid-op chain, attributed to the failing
1512/// step so the caller can mark the matching feature.
1513#[derive(Debug, Clone, Error)]
1514#[error("op {op_index}: {message}")]
1515pub struct ChainError {
1516    pub op_index: usize,
1517    pub message: String,
1518}
1519
1520/// Result of executing a body's solid-op chain.
1521#[derive(Debug, Clone, Default)]
1522pub struct SolidBuildResult {
1523    /// Native-format shape snapshot of the final solid (for later
1524    /// re-tessellation, persistence, and downstream booleans).
1525    pub brep_blob: Vec<u8>,
1526    /// Render mesh of the final solid.
1527    pub mesh: TriMesh,
1528    /// Axis-aligned bounds in millimetres.
1529    pub bounds_mm: Option<([f32; 3], [f32; 3])>,
1530    /// What the feature being edited does, when the build was asked for it.
1531    pub preview: Option<Box<FeaturePreview>>,
1532    /// The answers to the chain's probes, in the order they were asked.
1533    pub probes: Vec<Result<ProbeAnswer, String>>,
1534}
1535
1536/// What a feature being edited does to its body, beside the body without
1537/// it: the view while it is edited.
1538#[derive(Debug, Clone, Default)]
1539pub struct FeaturePreview {
1540    /// The body to show meanwhile: as it stood before a feature that adds,
1541    /// after one that cuts. None when an adding feature is the body's
1542    /// first.
1543    pub shown: Option<Box<SolidBuildResult>>,
1544    /// The feature's own tool solid, meshed: the material it adds or takes.
1545    pub tool: TriMesh,
1546    /// The feature cuts.
1547    pub cuts: bool,
1548}
1549
1550/// Trait implemented by any geometry kernel that can serve the application.
1551pub trait Kernel: Send {
1552    /// Human-friendly identifier for logging purposes.
1553    fn name(&self) -> &str;
1554
1555    /// Called once before any geometry work happens.
1556    fn initialize(&mut self) -> KernelResult<()>;
1557
1558    /// Recompute dirty features/bodies and return the affected handles.
1559    fn rebuild(&mut self, request: &RebuildRequest) -> KernelResult<RebuildResponse>;
1560
1561    /// Produce a triangular mesh for the provided body handle.
1562    fn tessellate(&self, body: BodyHandle, detail: &TessellationSettings) -> KernelResult<TriMesh>;
1563
1564    /// Read a STEP/STP file from disk and return tessellated bodies.
1565    ///
1566    /// Implementations that do not support STEP import should return
1567    /// [`KernelError::Unsupported`].
1568    fn import_step(
1569        &mut self,
1570        _path: &Path,
1571        _detail: &TessellationSettings,
1572    ) -> KernelResult<ImportedModel> {
1573        Err(KernelError::Unsupported(
1574            "STEP import is not implemented by this kernel".into(),
1575        ))
1576    }
1577}
1578
1579/// An edge of a solid projected onto a plane, in the plane's own 2D
1580/// coordinates (along its `x_axis` and `y_axis`).
1581#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1582pub enum ProjectedEdge {
1583    /// The edge runs along the plane's normal, so it projects to a point.
1584    Point([f64; 2]),
1585    /// A segment.
1586    Line { start: [f64; 2], end: [f64; 2] },
1587    /// A circle or circular arc, `centre + radius (cos t, sin t)`, turning
1588    /// counter-clockwise from `range.0` to `range.1`; a full circle when the
1589    /// range spans a turn.
1590    Circle {
1591        centre: [f64; 2],
1592        radius: f64,
1593        range: (f64, f64),
1594    },
1595    /// An ellipse or elliptical arc, `centre + major cos t + minor sin t`,
1596    /// `minor` the major axis turned a quarter counter-clockwise and scaled
1597    /// by `ratio`, from `range.0` to `range.1`.
1598    Ellipse {
1599        centre: [f64; 2],
1600        major: [f64; 2],
1601        ratio: f64,
1602        range: (f64, f64),
1603    },
1604    /// A B-spline, as the kernel projects it: `degree`, its clamped
1605    /// `knots` (`control_points + degree + 1` of them), and a weight per
1606    /// control point when rational (empty when every weight is one).
1607    Spline {
1608        degree: u32,
1609        knots: Vec<f64>,
1610        control_points: Vec<[f64; 2]>,
1611        weights: Vec<f64>,
1612    },
1613    /// Any other curve, as points along it: exact at each point, straight
1614    /// between.
1615    Polyline(Vec<[f64; 2]>),
1616}
1617
1618/// The curves of a 2D drawing file, in the drawing's own coordinates.
1619#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1620pub struct Drawing2d {
1621    /// Millimetres per drawing unit, when the drawing names its unit.
1622    pub unit_mm: Option<f64>,
1623    /// Every curve, in the order the file has them.
1624    pub curves: Vec<DrawingCurve>,
1625}
1626
1627/// One curve of a drawing, and whether the drawing marks it hidden
1628/// (a hidden layer, or a dashed line type).
1629#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1630pub struct DrawingCurve {
1631    pub hidden: bool,
1632    pub shape: DrawingShape,
1633}
1634
1635/// The kinds of curve a drawing carries. Angles are radians, arcs run
1636/// counter-clockwise.
1637#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1638pub enum DrawingShape {
1639    /// Points in order, each segment a line, or an arc where the bulge of
1640    /// the segment starting at that point (the tangent of a quarter of its
1641    /// included angle, positive counter-clockwise) is not zero. `bulges`
1642    /// is as long as `points`, or empty for straight segments only.
1643    Polyline {
1644        points: Vec<[f64; 2]>,
1645        bulges: Vec<f64>,
1646        closed: bool,
1647    },
1648    Arc {
1649        centre: [f64; 2],
1650        radius: f64,
1651        start_angle: f64,
1652        end_angle: f64,
1653    },
1654    Circle {
1655        centre: [f64; 2],
1656        radius: f64,
1657    },
1658    /// Points `centre + major cos t + ratio perp(major) sin t` for `t`
1659    /// from `start_param` to `end_param`; the whole ellipse when those span
1660    /// a full turn.
1661    Ellipse {
1662        centre: [f64; 2],
1663        major: [f64; 2],
1664        ratio: f64,
1665        start_param: f64,
1666        end_param: f64,
1667    },
1668    /// A spline, as points along the exact curve.
1669    Spline {
1670        points: Vec<[f64; 2]>,
1671        closed: bool,
1672    },
1673}
1674
1675/// The solid two shapes share: its volume, its centre and its mesh, in
1676/// the first shape's frame.
1677#[derive(Debug, Clone)]
1678pub struct Overlap {
1679    pub volume_mm3: f64,
1680    pub centre_mm: [f64; 3],
1681    pub mesh: TriMesh,
1682}
1683
1684/// How near two shapes come: the distance between their boundaries and a
1685/// nearest point on each, in the first shape's frame. Zero where the
1686/// boundaries touch or cross.
1687#[derive(Debug, Clone, Copy, PartialEq)]
1688pub struct Gap {
1689    pub distance_mm: f64,
1690    pub on_a: [f64; 3],
1691    pub on_b: [f64; 3],
1692}
1693
1694/// A stretch of a region's medial axis, in the profile plane's own 2D
1695/// coordinates: points along one branch with the clearance at each, the
1696/// radius of the largest disc centred there that stays inside the region.
1697#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1698pub struct MedialPath {
1699    pub points: Vec<[f64; 2]>,
1700    /// One per point, in millimetres.
1701    pub clearance: Vec<f64>,
1702    /// Whether the first and the last point end the axis on the boundary
1703    /// (a corner, or a rounded end's centre) rather than meet other
1704    /// branches: towards such an end the clearance falls without the
1705    /// region getting thinner.
1706    pub boundary_ends: [bool; 2],
1707}
1708
1709/// Where a region is narrowest, and how narrow: the smallest clearance on
1710/// its medial axis away from the branch ends at its corners (where the
1711/// clearance runs down to nothing without the region getting any thinner).
1712/// The wall there is twice the clearance.
1713#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1714pub struct Narrowest {
1715    pub at: [f64; 2],
1716    pub clearance: f64,
1717}
1718
1719/// The medial axis of one region of a profile: an outer wire and its holes.
1720#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1721pub struct MedialRegion {
1722    /// The profile's wires that bound it, by index, the outer one first.
1723    pub wires: Vec<usize>,
1724    pub paths: Vec<MedialPath>,
1725    /// `None` only when the axis has no place away from the corners.
1726    pub narrowest: Option<Narrowest>,
1727}
1728
1729/// A picked face: its name, and a point on it with its outward normal.
1730/// A rebuild finds the face by its name, the point choosing among the
1731/// pieces of a face that split; without a name (or when no face bears it
1732/// any more), the face nearest the point.
1733#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
1734pub struct FaceProbe {
1735    pub point: [f64; 3],
1736    pub normal: [f64; 3],
1737    #[serde(default)]
1738    pub name: TopoName,
1739}
1740
1741/// A question about a solid a reference stands on, named geometrically so
1742/// it can be asked again of the solid a rebuild makes.
1743#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1744pub enum ShapeProbe {
1745    /// The face named `name`, else the face nearest `point` (among faces
1746    /// as near, the one whose outward normal agrees best with `normal`),
1747    /// and where on it `point` falls.
1748    Face {
1749        point: [f64; 3],
1750        normal: [f64; 3],
1751        #[serde(default)]
1752        name: TopoName,
1753    },
1754    /// The edge between faces named `faces`, else the edge nearest `point`
1755    /// that runs along `direction` there (a zero direction takes the
1756    /// nearest edge whichever way it runs).
1757    Edge {
1758        point: [f64; 3],
1759        direction: [f64; 3],
1760        #[serde(default)]
1761        faces: [TopoName; 2],
1762        /// A share along the edge from its start (0 to 1) whose point and
1763        /// tangent the answer also gives.
1764        #[serde(default, skip_serializing_if = "Option::is_none")]
1765        along: Option<f64>,
1766    },
1767    /// The solid's centre of mass and principal axes of inertia.
1768    Mass,
1769}
1770
1771/// What a solid answers to a [`ShapeProbe`], in the solid's own frame.
1772#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1773pub enum ProbeAnswer {
1774    /// The point of the face nearest the probe's, the face's outward normal
1775    /// there, and the face's surface.
1776    Face {
1777        point: [f64; 3],
1778        normal: [f64; 3],
1779        surface: FaceSurface,
1780    },
1781    /// The point of the edge nearest the probe's and the way the edge runs
1782    /// there, its two ends and its middle (halfway along its parameter,
1783    /// which is halfway along an arc), and the circle it runs round when
1784    /// it is a circle or an arc of one.
1785    Edge {
1786        point: [f64; 3],
1787        direction: [f64; 3],
1788        start: [f64; 3],
1789        end: [f64; 3],
1790        middle: [f64; 3],
1791        circle: Option<ProbedCircle>,
1792        /// The point and tangent the probe's share along gives, when it
1793        /// asked for one.
1794        #[serde(default, skip_serializing_if = "Option::is_none")]
1795        along: Option<([f64; 3], [f64; 3])>,
1796    },
1797    /// The centre of mass and the principal axes of inertia, the axis of
1798    /// the smallest moment first.
1799    Mass {
1800        centre: [f64; 3],
1801        axes: [[f64; 3]; 3],
1802    },
1803}
1804
1805/// The circle an edge runs round.
1806#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1807pub struct ProbedCircle {
1808    pub centre: [f64; 3],
1809    pub normal: [f64; 3],
1810    pub radius: f64,
1811}
1812
1813/// A probe asked part way through a solid-op chain: of the solid the first
1814/// `after_op` ops make.
1815#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1816pub struct ChainProbe {
1817    pub after_op: usize,
1818    pub probe: ShapeProbe,
1819}
1820
1821/// The centre line of a pipe-like solid between two of its faces.
1822#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1823pub struct CentreLine {
1824    /// Points along it, from the first face to the second, in the shape's
1825    /// frame.
1826    pub points: Vec<[f64; 3]>,
1827    /// Its length, in millimetres.
1828    pub length: f64,
1829    /// The largest distance measured from the centroid of a section cut
1830    /// square to the line to the line itself.
1831    pub deviation: f64,
1832    /// It is one straight segment.
1833    pub straight: bool,
1834}
1835
1836/// A round hole found in a solid: a full bore, open at one end (blind)
1837/// or both (through), closed by a flat bottom or a drill point.
1838#[derive(Debug, Clone, PartialEq)]
1839pub struct RecognizedHole {
1840    /// The centre of its opening, on its axis.
1841    pub entry: [f64; 3],
1842    /// Along its axis, into the material.
1843    pub direction: [f64; 3],
1844    pub diameter: f64,
1845    /// The bore's length from the opening, not counting a drill point.
1846    pub depth: f64,
1847    /// Open at both ends.
1848    pub through: bool,
1849    /// The included angle of the cone that ends a blind hole, degrees;
1850    /// `None` for a flat bottom or a through hole.
1851    pub drill_point_deg: Option<f64>,
1852    /// A point on each face the hole is made of (its bore, its bottom),
1853    /// with that face's outward normal.
1854    pub faces: Vec<([f64; 3], [f64; 3])>,
1855}
1856
1857/// Geometry questions a workbench may ask while it runs, answered by the
1858/// kernel at once. Shapes arrive as the snapshot bytes the document keeps.
1859/// How two faces of a shape meet across an edge they share: a point
1860/// halfway along it, in the shape's own frame, the largest gap between the
1861/// edge and the faces, and the largest angle between the faces' normals
1862/// along it (zero where they meet tangent).
1863#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1864pub struct EdgeContinuity {
1865    pub point: [f64; 3],
1866    pub gap: f64,
1867    pub angle_deg: f64,
1868}
1869
1870pub trait KernelQueries: Send + Sync {
1871    /// Every edge two faces of `brep` share, with how they meet there.
1872    fn continuity(&self, _brep: &[u8]) -> KernelResult<Vec<EdgeContinuity>> {
1873        Err(KernelError::Unsupported("continuity".into()))
1874    }
1875
1876    /// The edges bounding the face of `brep` nearest `near`: a point on
1877    /// each, halfway along, and its direction there, in the shape's own
1878    /// frame. A seam (the edge a round face meets itself along) and an
1879    /// edge with no curve (a pole) are left out.
1880    fn face_edges(&self, _brep: &[u8], _near: [f64; 3]) -> KernelResult<Vec<([f64; 3], [f64; 3])>> {
1881        Err(KernelError::Unsupported("face_edges".into()))
1882    }
1883
1884    /// The round holes of `brep`, in its own frame, and how many bores it
1885    /// has that are not holes it can describe (a counterbore, a slot).
1886    fn recognize_holes(&self, _brep: &[u8]) -> KernelResult<(Vec<RecognizedHole>, usize)> {
1887        Err(KernelError::Unsupported("recognize_holes".into()))
1888    }
1889
1890    /// What `a` and `b` share when `b` sits where `b_in_a` (a rigid
1891    /// row-major 4×4 matrix) puts it in `a`'s frame; `None` when they only
1892    /// touch or are apart.
1893    fn overlap(
1894        &self,
1895        _a: &[u8],
1896        _b: &[u8],
1897        _b_in_a: &[[f64; 4]; 4],
1898    ) -> KernelResult<Option<Overlap>> {
1899        Err(KernelError::Unsupported("overlap".into()))
1900    }
1901
1902    /// How near `a` and `b` come when `b` sits where `b_in_a` puts it in
1903    /// `a`'s frame.
1904    fn gap(&self, _a: &[u8], _b: &[u8], _b_in_a: &[[f64; 4]; 4]) -> KernelResult<Gap> {
1905        Err(KernelError::Unsupported("gap".into()))
1906    }
1907
1908    /// `brep` mirrored across the plane through `point` with `normal`, in
1909    /// its own frame, as a snapshot of its own.
1910    fn mirror(&self, _brep: &[u8], _point: [f64; 3], _normal: [f64; 3]) -> KernelResult<Vec<u8>> {
1911        Err(KernelError::Unsupported("mirror".into()))
1912    }
1913
1914    /// The volume, area and centre of mass of `brep`, in its own frame.
1915    fn measure(&self, _brep: &[u8]) -> KernelResult<PhysicalProperties> {
1916        Err(KernelError::Unsupported("measure".into()))
1917    }
1918
1919    /// The edge of `brep` nearest `near`, projected orthogonally onto
1920    /// `plane`. Both are in the shape's own frame.
1921    fn project_edge(
1922        &self,
1923        brep: &[u8],
1924        near: [f64; 3],
1925        plane: &ProfilePlane,
1926    ) -> KernelResult<ProjectedEdge>;
1927
1928    /// The face of `brep` nearest `near` (in the shape's own frame), as a
1929    /// native-format snapshot of its own: what a face taken from a solid
1930    /// keeps once the solid moves on.
1931    fn face_of(&self, _brep: &[u8], _near: [f64; 3]) -> KernelResult<Vec<u8>> {
1932        Err(KernelError::Unsupported(
1933            "taking a face out of a solid".into(),
1934        ))
1935    }
1936
1937    /// Where the face of `brep` nearest `near` crosses `plane`, as the
1938    /// curves the plane cuts from it, in the plane's own 2D coordinates:
1939    /// each the exact line, circle or ellipse it is, or points along any
1940    /// other. Empty when the face does not reach the plane. Both are in the
1941    /// shape's own frame.
1942    fn section_face(
1943        &self,
1944        _brep: &[u8],
1945        _near: [f64; 3],
1946        _plane: &ProfilePlane,
1947    ) -> KernelResult<Vec<ProjectedEdge>> {
1948        Err(KernelError::Unsupported("face section".into()))
1949    }
1950
1951    /// The curves of a DXF drawing, given as its text.
1952    fn read_dxf(&self, _text: &str) -> KernelResult<Drawing2d> {
1953        Err(KernelError::Unsupported("reading DXF".into()))
1954    }
1955
1956    /// The regions `profile` encloses, meshed where they stand in its
1957    /// plane: what a feature swept from it takes, holes left open.
1958    fn profile_mesh(&self, _profile: &Profile) -> KernelResult<TriMesh> {
1959        Err(KernelError::Unsupported("profile mesh".into()))
1960    }
1961
1962    /// The medial axis of each region of `profile`, held to `tolerance`
1963    /// (mm), in the profile plane's own 2D coordinates.
1964    fn medial_axis(&self, _profile: &Profile, _tolerance: f64) -> KernelResult<Vec<MedialRegion>> {
1965        Err(KernelError::Unsupported("medial axis".into()))
1966    }
1967
1968    /// The centre line of the solid in `brep` from the face `from` names to
1969    /// the face `to` names, held to `tolerance` (mm). Everything is in the
1970    /// shape's own frame.
1971    fn centre_line(
1972        &self,
1973        _brep: &[u8],
1974        _from: &FaceProbe,
1975        _to: &FaceProbe,
1976        _tolerance: f64,
1977    ) -> KernelResult<CentreLine> {
1978        Err(KernelError::Unsupported("centre line".into()))
1979    }
1980
1981    /// What the shape in `brep` answers to `probe`, in the shape's own
1982    /// frame.
1983    fn probe(&self, _brep: &[u8], _probe: &ShapeProbe) -> KernelResult<ProbeAnswer> {
1984        Err(KernelError::Unsupported("probing a shape".into()))
1985    }
1986}
1987
1988/// Standardized error type for kernel interactions.
1989#[derive(Debug, Error)]
1990pub enum KernelError {
1991    #[error("kernel initialization failed: {0}")]
1992    Initialization(String),
1993    #[error("kernel not initialized")]
1994    NotInitialized,
1995    #[error("operation unsupported: {0}")]
1996    Unsupported(String),
1997    #[error("invalid kernel input: {0}")]
1998    InvalidInput(String),
1999    #[error("import failed: {0}")]
2000    Import(String),
2001    #[error(transparent)]
2002    Other(#[from] anyhow::Error),
2003}
2004
2005#[cfg(test)]
2006mod tests {
2007    use super::*;
2008
2009    fn pipe_json(frame: &str) -> String {
2010        let plane = r#"{"origin":[0,0,0],"x_axis":[1,0,0],"y_axis":[0,1,0],"normal":[0,0,1]}"#;
2011        let profile = format!(
2012            r#"{{"plane":{plane},"wires":[{{"segments":[{{"Circle":{{"center":[0,0],"radius":1}}}}]}}]}}"#
2013        );
2014        format!(r#"{{"Pipe":{{"profile":{profile},"spine":{profile},{frame}"op":"NewSolid"}}}}"#)
2015    }
2016
2017    fn frame_of(json: &str) -> PipeFrame {
2018        match serde_json::from_str::<SolidOp>(json).unwrap() {
2019            SolidOp::Pipe { frame, .. } => frame,
2020            other => panic!("not a pipe: {other:?}"),
2021        }
2022    }
2023
2024    #[test]
2025    fn a_pipe_written_with_the_frenet_flag_reads_as_its_frame() {
2026        assert_eq!(frame_of(&pipe_json(r#""frenet":true,"#)), PipeFrame::Frenet);
2027        assert_eq!(
2028            frame_of(&pipe_json(r#""frenet":false,"#)),
2029            PipeFrame::RotationMinimizing
2030        );
2031        assert_eq!(frame_of(&pipe_json("")), PipeFrame::RotationMinimizing);
2032    }
2033
2034    #[test]
2035    fn a_pipe_frame_round_trips() {
2036        let frame = PipeFrame::Binormal {
2037            direction: [0.0, 0.0, 1.0],
2038        };
2039        let text = serde_json::to_string(&frame).unwrap();
2040        assert_eq!(frame_of(&pipe_json(&format!(r#""frame":{text},"#))), frame);
2041    }
2042}