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`, its
198    /// wall `half_angle` (radians, positive) off the axis.
199    Cone {
200        apex: [f32; 3],
201        axis: [f32; 3],
202        #[serde(default)]
203        half_angle: f32,
204    },
205    /// A sphere.
206    Sphere { center: [f32; 3], radius: f32 },
207    /// A torus about the line through `center` along `axis`: its tube's
208    /// centre `major_radius` from the axis, the tube `minor_radius` round.
209    Torus {
210        center: [f32; 3],
211        axis: [f32; 3],
212        #[serde(default)]
213        major_radius: f32,
214        #[serde(default)]
215        minor_radius: f32,
216    },
217    /// Any other surface: a spline, a sweep.
218    #[default]
219    Other,
220}
221
222impl FaceSurface {
223    /// The axis a turned face turns about, as a point on it and its
224    /// direction: a cylinder's, a cone's or a torus's.
225    pub fn axis(&self) -> Option<([f32; 3], [f32; 3])> {
226        match *self {
227            FaceSurface::Cylinder { origin, axis, .. } => Some((origin, axis)),
228            FaceSurface::Cone { apex, axis, .. } => Some((apex, axis)),
229            FaceSurface::Torus { center, axis, .. } => Some((center, axis)),
230            _ => None,
231        }
232    }
233
234    /// The same surface moved: `point` maps points, `direction` maps
235    /// directions (a rigid motion, so lengths stay).
236    pub fn moved(
237        &self,
238        point: impl Fn([f32; 3]) -> [f32; 3],
239        direction: impl Fn([f32; 3]) -> [f32; 3],
240    ) -> Self {
241        match *self {
242            FaceSurface::Plane { origin, normal } => FaceSurface::Plane {
243                origin: point(origin),
244                normal: direction(normal),
245            },
246            FaceSurface::Cylinder {
247                origin,
248                axis,
249                radius,
250            } => FaceSurface::Cylinder {
251                origin: point(origin),
252                axis: direction(axis),
253                radius,
254            },
255            FaceSurface::Cone {
256                apex,
257                axis,
258                half_angle,
259            } => FaceSurface::Cone {
260                apex: point(apex),
261                axis: direction(axis),
262                half_angle,
263            },
264            FaceSurface::Sphere { center, radius } => FaceSurface::Sphere {
265                center: point(center),
266                radius,
267            },
268            FaceSurface::Torus {
269                center,
270                axis,
271                major_radius,
272                minor_radius,
273            } => FaceSurface::Torus {
274                center: point(center),
275                axis: direction(axis),
276                major_radius,
277                minor_radius,
278            },
279            FaceSurface::Other => FaceSurface::Other,
280        }
281    }
282}
283
284impl TriMesh {
285    /// Compute axis-aligned bounding box `(min, max)` of the mesh, if non-empty.
286    pub fn bounds(&self) -> Option<([f32; 3], [f32; 3])> {
287        if self.positions.is_empty() {
288            return None;
289        }
290        let mut min = self.positions[0];
291        let mut max = self.positions[0];
292        for &[x, y, z] in &self.positions {
293            if x < min[0] {
294                min[0] = x;
295            }
296            if y < min[1] {
297                min[1] = y;
298            }
299            if z < min[2] {
300                min[2] = z;
301            }
302            if x > max[0] {
303                max[0] = x;
304            }
305            if y > max[1] {
306                max[1] = y;
307            }
308            if z > max[2] {
309                max[2] = z;
310            }
311        }
312        Some((min, max))
313    }
314}
315
316/// A single body produced by an external import (e.g. STEP).
317///
318/// The kernel returns one entry per placed body in the source file, meshed.
319/// [`Self::brep_blob`] is empty when no snapshot was kept:
320/// [`TessellationSettings::persist_brep_snapshot`] off, a full-mesh import,
321/// or a mesh file, which has no shape.
322#[derive(Debug, Clone, Serialize, Deserialize)]
323pub struct ImportedBody {
324    /// Optional name extracted from the source file (e.g. STEP product label).
325    pub name: Option<String>,
326    /// Tessellated mesh ready for the viewport.
327    #[serde(default)]
328    pub mesh: TriMesh,
329    /// Serialized shape snapshot for this body, when one was kept: ogeom
330    /// native-format text bytes (`ogeom::io::native`, one root shape per
331    /// blob).
332    #[serde(default, skip_serializing_if = "Vec::is_empty")]
333    pub brep_blob: Vec<u8>,
334    /// Per-face linear RGB albedo in face-exploration order
335    /// (`ogeom::topo::explore` with a Face filter) over the matching shape
336    /// snapshot.
337    #[serde(default, skip_serializing_if = "Vec::is_empty")]
338    pub face_colors: Vec<[f32; 3]>,
339    /// Axis-aligned bounds in millimetres from the raw BRep (before tessellation).
340    #[serde(default, skip_serializing_if = "Option::is_none")]
341    pub bounds_mm: Option<([f32; 3], [f32; 3])>,
342    /// What the kernel's checker found in the body's shape as read.
343    #[serde(default, skip_serializing_if = "Option::is_none")]
344    pub health: Option<ShapeHealth>,
345    /// The names of the layers the file puts the body on.
346    #[serde(default, skip_serializing_if = "Vec::is_empty")]
347    pub layers: Vec<String>,
348}
349
350/// What the kernel's checker found in a shape.
351///
352/// The checker sorts its findings in two: *broken*, where an algorithm
353/// reading the shape gets a wrong answer rather than an error, and
354/// *suspect*, out of order but harmless to every operation. Only broken
355/// findings ask for a repair.
356#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
357pub struct ShapeHealth {
358    /// Findings that make an algorithm reading the shape answer wrongly.
359    pub broken: usize,
360    /// Findings that are out of order but harmless.
361    pub suspect: usize,
362    /// The first findings, a sentence each, broken first.
363    #[serde(default, skip_serializing_if = "Vec::is_empty")]
364    pub findings: Vec<String>,
365    /// The kernel's repair has run on the shape these findings describe.
366    #[serde(default)]
367    pub repaired: bool,
368    /// The shape is a mesh converted as it is: its flat stretches are
369    /// faces and its curved ones still the mesh's facets, which a refine
370    /// can rebuild on the surfaces they approximate.
371    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
372    pub faceted: bool,
373}
374
375impl ShapeHealth {
376    /// How many findings a health record keeps as sentences.
377    pub const KEPT_FINDINGS: usize = 8;
378
379    /// Whether the shape has anything a repair is for.
380    pub fn is_broken(&self) -> bool {
381        self.broken > 0
382    }
383
384    /// One line for a tooltip: the counts, then the findings kept.
385    pub fn describe(&self) -> String {
386        let mut lines = Vec::new();
387        let counts = match (self.broken, self.suspect) {
388            (0, 0) => "The shape checks clean".to_string(),
389            (b, 0) => format!("{b} shape defect(s) that make operations answer wrongly"),
390            (0, s) => format!("{s} shape irregularity(ies), harmless to operations"),
391            (b, s) => format!(
392                "{b} shape defect(s) that make operations answer wrongly, \
393                 and {s} harmless irregularity(ies)"
394            ),
395        };
396        lines.push(counts);
397        if self.repaired && self.is_broken() {
398            lines.push("Repaired; these remain, beyond what the repair mends".to_string());
399        }
400        lines.extend(self.findings.iter().cloned());
401        let shown = self.findings.len();
402        let total = self.broken + self.suspect;
403        if total > shown {
404            lines.push(format!("… and {} more", total - shown));
405        }
406        lines.join("\n")
407    }
408}
409
410/// A shape run through the kernel's repair: the mended snapshot, its mesh,
411/// what the repair did, and what the checker finds afterwards.
412#[derive(Debug, Clone, Default, Serialize, Deserialize)]
413pub struct RepairResult {
414    /// Native-format snapshot of the mended shape.
415    pub brep_blob: Vec<u8>,
416    /// Per-face colours for the mended shape, in its face order; empty when
417    /// the repair changed the faces too much to carry them over.
418    pub face_colors: Vec<[f32; 3]>,
419    /// Render mesh of the mended shape.
420    pub mesh: TriMesh,
421    /// Axis-aligned bounds in millimetres.
422    pub bounds_mm: Option<([f32; 3], [f32; 3])>,
423    /// The checker's findings on the mended shape, marked repaired.
424    pub health: ShapeHealth,
425    /// What was mended, a phrase each ("12 tolerances tightened").
426    pub mended: Vec<String>,
427}
428
429/// A mesh body turned into a B-rep by the kernel: the shape, its mesh, the
430/// checker's verdict, and what the conversion found.
431#[derive(Debug, Clone, Default, Serialize, Deserialize)]
432pub struct MeshSolidResult {
433    /// Native-format snapshot of the shape.
434    pub brep_blob: Vec<u8>,
435    /// Per-face colours in the shape's face order: the mesh's colour on
436    /// every face when it had one colour, else empty.
437    pub face_colors: Vec<[f32; 3]>,
438    /// Render mesh of the shape, with its kernel faces and edges.
439    pub mesh: TriMesh,
440    /// Axis-aligned bounds in millimetres.
441    pub bounds_mm: Option<([f32; 3], [f32; 3])>,
442    /// The checker's findings on the shape.
443    pub health: ShapeHealth,
444    /// Every piece of the mesh closed and became a solid; otherwise the
445    /// shape is the open shell(s) the mesh makes.
446    pub closed: bool,
447    /// What the conversion did and where the mesh does not close, a phrase
448    /// each ("12 triangles into 6 faces", "3 hole edges").
449    pub summary: Vec<String>,
450}
451
452/// A body's measure: its volume, surface area and centre of mass, exact
453/// where the kernel has a closed form for its faces.
454#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
455pub struct PhysicalProperties {
456    /// Enclosed volume in mm³; `None` when the shape encloses none (an open
457    /// shell, a sheet) or its shell is wound inside out.
458    pub volume_mm3: Option<f64>,
459    /// Total surface area in mm².
460    pub area_mm2: f64,
461    /// Centre of mass at uniform density, in mm; the centre of the surface
462    /// when there is no volume.
463    pub centre_mm: [f64; 3],
464    /// Some face had no closed form, so the figures were integrated over a
465    /// tessellation and are close rather than exact (within a fraction of a
466    /// percent on curved walls).
467    #[serde(default)]
468    pub approximate: bool,
469    /// The inertia of the volume at unit density, when there is one.
470    #[serde(default)]
471    pub inertia: Option<Inertia>,
472}
473
474/// A solid's inertia at unit density, in mm⁵ (times a density in mass per
475/// mm³ gives mass times mm²), in the solid's frame.
476#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
477pub struct Inertia {
478    /// The inertia tensor about the centre of mass, row by row.
479    pub about_centre: [[f64; 3]; 3],
480    /// The principal moments, smallest first, each with its axis through
481    /// the centre of mass (unit length; right-handed in that order).
482    pub principal: [(f64, [f64; 3]); 3],
483}
484
485/// Node type emitted by STEP import hierarchy reconstruction.
486#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
487#[serde(rename_all = "snake_case")]
488pub enum ImportedNodeKind {
489    #[default]
490    Assembly,
491    Part,
492    Instance,
493    /// The group holding an import's annotations.
494    Annotations,
495    /// One annotation the file carries: a dimension, a tolerance, a datum
496    /// or a note.
497    Annotation,
498}
499
500/// What an imported annotation states.
501#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
502#[serde(rename_all = "snake_case")]
503pub enum AnnotationKind {
504    /// A size or a location, with its value.
505    Dimension,
506    /// A geometric tolerance: flatness, position, profile and their kin.
507    Tolerance,
508    /// A datum letter, or a target a datum is contacted at.
509    Datum,
510    /// Text with nothing measured behind it.
511    Note,
512    /// A drawn annotation the file does not say more about.
513    #[default]
514    Other,
515}
516
517impl AnnotationKind {
518    /// The kind as a word for the interface.
519    pub fn label(self) -> &'static str {
520        match self {
521            AnnotationKind::Dimension => "Dimension",
522            AnnotationKind::Tolerance => "Tolerance",
523            AnnotationKind::Datum => "Datum",
524            AnnotationKind::Note => "Note",
525            AnnotationKind::Other => "Annotation",
526        }
527    }
528}
529
530/// One annotation an imported file carries (a dimension, a tolerance, a
531/// datum or a note), with what it draws.
532///
533/// The polylines and the anchor are in document millimetres, placed where
534/// the file's bodies are placed, so an annotation drawn on an assembly's
535/// part sits on that part.
536#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
537pub struct ImportedAnnotation {
538    /// The name the file gives it (`Linear Size.3`, `Flatness.1`), or the
539    /// text it shows where the file names it by that.
540    pub name: String,
541    pub kind: AnnotationKind,
542    /// What a label shows: `Ø 35 ±0.2`, `Flatness 0.2`, `A`.
543    pub text: String,
544    /// The drawn geometry: leaders, frames, witness lines and whatever
545    /// strokes the file draws its text with.
546    #[serde(default, skip_serializing_if = "Vec::is_empty")]
547    pub polylines: Vec<Vec<[f32; 3]>>,
548    /// Where the label goes; `None` for an annotation that draws nothing.
549    #[serde(default, skip_serializing_if = "Option::is_none")]
550    pub anchor: Option<[f32; 3]>,
551    /// The body the annotation describes, as an index into
552    /// [`ImportedModel::bodies`], where the file says which.
553    #[serde(default, skip_serializing_if = "Option::is_none")]
554    pub body_index: Option<usize>,
555}
556
557/// One hierarchy node from the imported file's product structure.
558///
559/// Nodes can either be pure containers (`body_index = None`) or reference a
560/// renderable payload in [`ImportedModel::bodies`].
561#[derive(Debug, Clone, Serialize, Deserialize)]
562pub struct ImportedNode {
563    /// Stable id scoped to one import result.
564    pub id: u64,
565    /// Parent node id; None means root.
566    #[serde(default, skip_serializing_if = "Option::is_none")]
567    pub parent_id: Option<u64>,
568    /// Human-readable name from the file's product labels when available.
569    #[serde(default, skip_serializing_if = "Option::is_none")]
570    pub name: Option<String>,
571    /// Structural type of this node.
572    #[serde(default)]
573    pub kind: ImportedNodeKind,
574    /// Initial visibility from source file metadata (if available).
575    #[serde(default = "default_imported_node_visible")]
576    pub visible: bool,
577    /// Index into [`ImportedModel::bodies`] when this node owns geometry.
578    #[serde(default, skip_serializing_if = "Option::is_none")]
579    pub body_index: Option<usize>,
580    /// Local transform matrix (row-major) relative to parent, if known.
581    #[serde(default, skip_serializing_if = "Option::is_none")]
582    pub local_transform: Option<[[f32; 4]; 4]>,
583}
584
585fn default_imported_node_visible() -> bool {
586    true
587}
588
589/// Length unit declared by an imported source file.
590///
591/// This is a thin mirror of `core_document::Unit` that lives in `kernel_api`
592/// to avoid pulling document-side types into the kernel crate. App code is
593/// responsible for translating it into the document's display unit.
594#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
595#[serde(rename_all = "snake_case")]
596pub enum LengthUnit {
597    Millimetre,
598    Centimetre,
599    Metre,
600    Inch,
601    Foot,
602}
603
604/// Result of importing an external CAD file.
605#[derive(Debug, Clone, Default, Serialize, Deserialize)]
606pub struct ImportedModel {
607    /// One entry per top-level body in the source file.
608    pub bodies: Vec<ImportedBody>,
609    /// Everything the reader had to say about the file, kept whole so it
610    /// can be handed to whoever maintains the kernel rather than scrolled
611    /// past in a terminal.
612    #[serde(default)]
613    pub report: ImportReport,
614    /// Optional assembly/object tree reconstructed from the file's product
615    /// structure.
616    #[serde(default)]
617    pub nodes: Vec<ImportedNode>,
618    /// Length unit declared by the source file, when detectable. Geometry in
619    /// `bodies` is *always* expressed in millimetres regardless; this field
620    /// is purely informational and used by the UI to pick a display unit.
621    #[serde(default)]
622    pub source_unit: Option<LengthUnit>,
623    /// The file's annotations (dimensions, tolerances, datums and notes)
624    /// in file order, the drawn ones first.
625    #[serde(default, skip_serializing_if = "Vec::is_empty")]
626    pub annotations: Vec<ImportedAnnotation>,
627}
628
629/// What the reader had to say about a file.
630///
631/// A community STEP file routinely produces a thousand lines of "this edge
632/// misses its vertex by a micron"; each one is true and none is actionable
633/// on its own. The kernel counts them by kind, and the whole prose stays
634/// here for the report a user can send along with the file.
635#[derive(Debug, Clone, Default, Serialize, Deserialize)]
636pub struct ImportReport {
637    /// The kernel that read the file, by name and version.
638    pub kernel: String,
639    /// One entry per kind of imperfection, largest count first.
640    pub summary: Vec<ImportWarningKind>,
641    /// Every warning, one line each, in the order the reader met them.
642    pub warnings: Vec<String>,
643    /// STEP entity ids of faces that read without a complete trim, so they
644    /// draw with gaps unless healed.
645    pub untrimmed_faces: Vec<u64>,
646    /// Entity keywords the reader never visited, with counts. Presentation
647    /// and annotation land here by design; geometry landing here is a gap.
648    pub skipped: Vec<(String, usize)>,
649}
650
651impl ImportReport {
652    /// Whether there is anything worth writing down.
653    pub fn is_clean(&self) -> bool {
654        self.warnings.is_empty() && self.untrimmed_faces.is_empty()
655    }
656}
657
658/// One kind of imperfect import, counted rather than repeated.
659#[derive(Debug, Clone, Serialize, Deserialize)]
660pub struct ImportWarningKind {
661    /// Stable across runs: `vertex-miss`, `boundary-slop`, `fit-short`,
662    /// `untrimmed`.
663    pub kind: String,
664    pub count: usize,
665    /// The worst measured value among them, in millimetres, for the kinds
666    /// that measure one; zero otherwise.
667    pub worst: f64,
668    /// One entity id to look at first.
669    pub exemplar: u64,
670}
671
672/// One segment of a closed 2D profile wire, in sketch-plane coordinates
673/// (millimetres). Arcs are encoded as three on-curve points so consumers
674/// never have to agree on a winding convention.
675#[cfg_attr(not(feature = "exhaustive"), non_exhaustive)]
676#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
677pub enum ProfileSegment {
678    Line {
679        start: [f64; 2],
680        end: [f64; 2],
681    },
682    /// Circular arc through three points (start → mid → end).
683    Arc {
684        start: [f64; 2],
685        mid: [f64; 2],
686        end: [f64; 2],
687    },
688    Circle {
689        center: [f64; 2],
690        radius: f64,
691    },
692    /// Full ellipse. `major` is the vector from the center to a major-axis
693    /// vertex; the minor radius is `|major| * ratio` with `ratio` in (0, 1].
694    Ellipse {
695        center: [f64; 2],
696        major: [f64; 2],
697        ratio: f64,
698    },
699    /// Elliptical arc between two parameter angles (radians, counter-clockwise
700    /// in the ellipse frame where the major axis is at parameter 0).
701    EllipseArc {
702        center: [f64; 2],
703        major: [f64; 2],
704        ratio: f64,
705        start_param: f64,
706        end_param: f64,
707    },
708    /// Cubic B-spline through the given control points. A periodic spline
709    /// closes smoothly on itself; an open one runs first → last control point.
710    BSpline {
711        control_points: Vec<[f64; 2]>,
712        periodic: bool,
713    },
714    /// A B-spline of any degree over its own knots, rational when it has
715    /// weights: an exact conic arc, a spline drawn through points. An open
716    /// one's knots are clamped (`control points + degree + 1` of them), so
717    /// it runs first → last control point; a periodic one is a uniform ring
718    /// over its control points closing smoothly on itself, and its knots
719    /// are not used.
720    Nurbs {
721        degree: u32,
722        knots: Vec<f64>,
723        control_points: Vec<[f64; 2]>,
724        /// One per control point; empty when every weight is one.
725        #[serde(default, skip_serializing_if = "Vec::is_empty")]
726        weights: Vec<f64>,
727        #[serde(default)]
728        periodic: bool,
729    },
730}
731
732/// What a [`SolidOp::PipeThrough`] runs along.
733#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
734pub enum PipePath {
735    /// A sketch's wire.
736    Profile(Profile),
737    /// Edges of the running solid, joined end to end.
738    Edges(Vec<EdgeProbe>),
739    /// Edges of another solid (a native-format snapshot, moved by
740    /// `transform` into the body's frame), joined end to end; the probes
741    /// are in the body's frame.
742    EdgesOf {
743        shape: Vec<u8>,
744        transform: Option<Box<[[f64; 4]; 4]>>,
745        edges: Vec<EdgeProbe>,
746    },
747}
748
749/// One section of a [`SolidOp::LoftThrough`].
750#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
751pub enum LoftSection {
752    Profile(Profile),
753    /// The flat face of the running solid the probe finds, by its outer
754    /// and inner boundaries.
755    Face(FaceProbe),
756    /// A point the loft closes to, in the body's frame.
757    Point([f64; 3]),
758}
759
760/// A closed loop of profile segments. Consecutive segments share endpoints;
761/// a single `Circle` segment is a wire by itself.
762#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
763pub struct ProfileWire {
764    pub segments: Vec<ProfileSegment>,
765    /// The name of each segment, one per segment, by what it was drawn from
766    /// (a sketch element): the faces a feature sweeps from it are named by
767    /// it, so they keep their names while dimensions change. Empty, or a
768    /// zero, where a segment has no such name.
769    #[serde(default, skip_serializing_if = "Vec::is_empty")]
770    pub names: Vec<TopoName>,
771}
772
773impl ProfileWire {
774    /// A wire of `segments` with no names.
775    pub fn new(segments: Vec<ProfileSegment>) -> Self {
776        Self {
777            segments,
778            names: Vec::new(),
779        }
780    }
781
782    /// The name of segment `index`, when it has one.
783    pub fn name_of(&self, index: usize) -> Option<TopoName> {
784        self.names.get(index).copied().filter(|n| *n != 0)
785    }
786}
787
788/// The plane a profile lives on, in world coordinates (millimetres).
789#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
790pub struct ProfilePlane {
791    pub origin: [f64; 3],
792    pub x_axis: [f64; 3],
793    pub y_axis: [f64; 3],
794    pub normal: [f64; 3],
795}
796
797/// The XY plane through the origin.
798impl Default for ProfilePlane {
799    fn default() -> Self {
800        Self {
801            origin: [0.0; 3],
802            x_axis: [1.0, 0.0, 0.0],
803            y_axis: [0.0, 1.0, 0.0],
804            normal: [0.0, 0.0, 1.0],
805        }
806    }
807}
808
809/// How an extrusion combines with the body's existing solid.
810#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
811pub enum BooleanOp {
812    /// Replace / start the body's solid (first feature).
813    NewSolid,
814    /// Union with the existing solid (Pad on an existing body).
815    Fuse,
816    /// Subtract from the existing solid (Pocket).
817    Cut,
818    /// Keep only what the existing solid and the tool share.
819    Common,
820}
821
822/// A set of closed wires on one plane. The largest-area wire is the outer
823/// boundary, the rest become holes.
824#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
825pub struct Profile {
826    pub plane: ProfilePlane,
827    pub wires: Vec<ProfileWire>,
828}
829
830/// Where a one-directional extrusion stops.
831#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
832pub enum ExtrudeTermination {
833    /// Fixed length in millimetres.
834    Blind { distance: f64 },
835    /// Extend well past the base solid's bounding box in this direction.
836    ThroughAll,
837    /// Stop on the given world-space plane, shifted by `offset` along its
838    /// normal (a picked planar face plus an offset-to-face value).
839    UpToPlane {
840        point: [f64; 3],
841        normal: [f64; 3],
842        offset: f64,
843    },
844    /// Stop on the base solid's face named `name`, else the one nearest
845    /// `point` (a picked face, where it was picked), exactly on its surface
846    /// whatever its shape, pushed `offset` out along its outward normal.
847    /// With no base solid, or no face of it there, the plane through
848    /// `point` square to `normal`.
849    UpToFace {
850        point: [f64; 3],
851        normal: [f64; 3],
852        offset: f64,
853        #[serde(default)]
854        name: TopoName,
855    },
856    /// Stop at the first face of the base solid hit along the extrusion
857    /// direction, on its surface.
858    ToFirst,
859    /// Stop at the last face of the base solid hit along the extrusion
860    /// direction, on its surface.
861    ToLast,
862    /// Stop on a set of the base solid's faces: every line of the sweep
863    /// ends at the first of them it meets, moved `offset` further along the
864    /// sweep (a negative offset stops short).
865    UpToShape { faces: Vec<FaceProbe>, offset: f64 },
866    /// Stop on a face of another shape: the face of `shape` (a native-format
867    /// snapshot, moved by `transform`, a rigid row-major 4×4 matrix, into
868    /// the body's frame) nearest `point`, exactly on its surface whatever
869    /// its shape, pushed `offset` out along its outward normal.
870    UpToFaceOf {
871        shape: Vec<u8>,
872        transform: Option<Box<[[f64; 4]; 4]>>,
873        point: [f64; 3],
874        offset: f64,
875    },
876    /// Stop on a set of faces as `UpToShape` does, some of them the base
877    /// solid's (`faces`) and some of other shapes (`others`, faces other
878    /// bodies lend this one). Needs no base solid when every face is
879    /// another shape's.
880    UpToShapeOf {
881        faces: Vec<FaceProbe>,
882        others: Vec<FacesOf>,
883        offset: f64,
884    },
885}
886
887/// Faces of another shape: the faces of `shape` (a native-format snapshot,
888/// moved by `transform`, a rigid row-major 4×4 matrix, into the body's
889/// frame) nearest each of `points`.
890#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
891pub struct FacesOf {
892    pub shape: Vec<u8>,
893    pub transform: Option<Box<[[f64; 4]; 4]>>,
894    pub points: Vec<[f64; 3]>,
895}
896
897/// Where a revolution stops turning.
898#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
899pub enum RevolveTermination {
900    /// Through the sweep's own angles.
901    #[default]
902    Angle,
903    /// On the first face of the base solid the profile's centre meets as it
904    /// turns.
905    ToFirst,
906    /// On the last face of the base solid the profile's centre meets as it
907    /// turns.
908    ToLast,
909    /// On the base solid's face nearest the probe.
910    UpToFace(FaceProbe),
911}
912
913/// How a profile is swept into a solid.
914#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
915pub enum SweepKind {
916    /// Linear extrusion along `plane.normal` (or `direction` when set).
917    Extrude {
918        termination: ExtrudeTermination,
919        /// Independent termination for the opposite side of the sketch plane
920        /// (two-sided extrusion). `None` extrudes one side only.
921        second_side: Option<ExtrudeTermination>,
922        /// Extrude half the blind distance to each side of the sketch plane.
923        symmetric: bool,
924        /// Swap which side of the sketch plane is "forward".
925        reversed: bool,
926        /// Draft angle applied along the sweep; positive widens the far end.
927        taper_deg: f64,
928        /// Custom world-space sweep direction; `None` uses the plane normal.
929        direction: Option<[f64; 3]>,
930    },
931    /// Revolution about an axis lying IN the sketch plane, given in sketch
932    /// 2D coordinates (point + direction). `angle_deg` in (0, 360].
933    Revolve {
934        axis_origin: [f64; 2],
935        axis_dir: [f64; 2],
936        angle_deg: f64,
937        /// Independent sweep angle for the opposite rotation direction.
938        second_angle_deg: Option<f64>,
939        /// Center the sweep on the sketch plane (half the angle each way).
940        midplane: bool,
941        reversed: bool,
942        /// Where the turn stops; anything but `Angle` takes the angle from
943        /// what the profile meets and leaves the angles above unused.
944        #[serde(default)]
945        termination: RevolveTermination,
946    },
947    /// Sweep the profile along a helix whose axis lies in the sketch plane.
948    /// A cone angle moves every point away from the axis by tan(angle) of
949    /// every pitch it climbs.
950    Helix {
951        axis_origin: [f64; 2],
952        axis_dir: [f64; 2],
953        pitch: f64,
954        height: f64,
955        left_handed: bool,
956        cone_angle_deg: f64,
957        reversed: bool,
958        /// How many turns, when given: the pitch is then `height / turns`
959        /// and `pitch` is not read. A height of 0 with turns and growth is
960        /// a flat spiral.
961        #[serde(default)]
962        turns: Option<f64>,
963        /// How far every point moves away from the axis per turn, when
964        /// given, in place of `cone_angle_deg`.
965        #[serde(default)]
966        growth: Option<f64>,
967    },
968    /// Sweep the profile along a helix whose axis runs square to the sketch
969    /// plane through `axis_origin` (sketch 2D coordinates): every point of
970    /// the profile climbs its own helix about it, the profile staying
971    /// level. The rest reads as for `Helix`.
972    HelixNormal {
973        axis_origin: [f64; 2],
974        pitch: f64,
975        height: f64,
976        left_handed: bool,
977        cone_angle_deg: f64,
978        reversed: bool,
979        #[serde(default)]
980        turns: Option<f64>,
981        #[serde(default)]
982        growth: Option<f64>,
983    },
984}
985
986/// How a pipe's section turns as it runs down its path.
987#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
988pub enum PipeFrame {
989    /// Rotation-minimizing: the section neither twists nor kinks where the
990    /// path bends.
991    #[default]
992    RotationMinimizing,
993    /// The path's own curvature frame, turning with it.
994    Frenet,
995    /// The section turns about the path so that one direction of it keeps
996    /// pointing at a second path running beside the first.
997    Auxiliary { path: Profile },
998    /// The section keeps a fixed binormal: the world-space direction square
999    /// to the path that the section's frame holds all the way.
1000    Binormal { direction: [f64; 3] },
1001    /// The section keeps its orientation in space: carried along the path
1002    /// without ever turning, as it is drawn.
1003    Fixed,
1004}
1005
1006impl PipeFrame {
1007    /// The frame an older `frenet` flag named.
1008    pub fn from_frenet(frenet: bool) -> Self {
1009        if frenet {
1010            PipeFrame::Frenet
1011        } else {
1012            PipeFrame::RotationMinimizing
1013        }
1014    }
1015}
1016
1017/// Reads a [`PipeFrame`] or the `frenet` flag it stands in for.
1018pub fn deserialize_pipe_frame<'de, D>(deserializer: D) -> Result<PipeFrame, D::Error>
1019where
1020    D: serde::Deserializer<'de>,
1021{
1022    #[derive(Deserialize)]
1023    #[serde(untagged)]
1024    enum Stored {
1025        Flag(bool),
1026        Frame(PipeFrame),
1027    }
1028    Ok(match Stored::deserialize(deserializer)? {
1029        Stored::Flag(frenet) => PipeFrame::from_frenet(frenet),
1030        Stored::Frame(frame) => frame,
1031    })
1032}
1033
1034/// How a pipe's section turns a sharp corner of its path.
1035#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1036pub enum PipeCorner {
1037    /// The section is carried into the corner and sheared onto the plane
1038    /// bisecting it: the two legs meet on that mitre.
1039    #[default]
1040    Transformed,
1041    /// Each leg runs on straight past the corner and the two are fused,
1042    /// leaving the outside of the corner square.
1043    Right,
1044    /// The section turns about the corner, the outside of it rounded.
1045    Round,
1046}
1047
1048/// Parametric primitive shapes (dimensions in millimetres, angles degrees).
1049#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1050pub enum PrimitiveKind {
1051    Box {
1052        length: f64,
1053        width: f64,
1054        height: f64,
1055    },
1056    Cylinder {
1057        radius: f64,
1058        height: f64,
1059        angle_deg: f64,
1060    },
1061    Sphere {
1062        radius: f64,
1063        /// Latitude range and longitude sweep (three-angle parameterization).
1064        angle1_deg: f64,
1065        angle2_deg: f64,
1066        angle3_deg: f64,
1067    },
1068    Cone {
1069        radius1: f64,
1070        radius2: f64,
1071        height: f64,
1072        angle_deg: f64,
1073    },
1074    Torus {
1075        radius1: f64,
1076        radius2: f64,
1077        angle1_deg: f64,
1078        angle2_deg: f64,
1079        angle3_deg: f64,
1080    },
1081    /// An ellipsoid, cut as a sphere is: between two latitudes about its
1082    /// third axis and through a sweep round it.
1083    Ellipsoid {
1084        radius1: f64,
1085        radius2: f64,
1086        radius3: f64,
1087        #[serde(default = "south_pole")]
1088        angle1_deg: f64,
1089        #[serde(default = "north_pole")]
1090        angle2_deg: f64,
1091        #[serde(default = "full_turn")]
1092        angle3_deg: f64,
1093    },
1094    /// A regular prism, its top shifted by the skew angles: leaning that
1095    /// far from its axis toward its x and its y.
1096    Prism {
1097        sides: u32,
1098        circumradius: f64,
1099        height: f64,
1100        #[serde(default)]
1101        skew_x_deg: f64,
1102        #[serde(default)]
1103        skew_y_deg: f64,
1104    },
1105    /// Box with an independently sized top rectangle (zero top spans give a
1106    /// pyramid). Spans are along local X (`x2*`) and Z (`z2*`) at height Y.
1107    Wedge {
1108        xmin: f64,
1109        xmax: f64,
1110        ymin: f64,
1111        ymax: f64,
1112        zmin: f64,
1113        zmax: f64,
1114        x2min: f64,
1115        x2max: f64,
1116        z2min: f64,
1117        z2max: f64,
1118    },
1119}
1120
1121fn south_pole() -> f64 {
1122    -90.0
1123}
1124
1125fn north_pole() -> f64 {
1126    90.0
1127}
1128
1129fn full_turn() -> f64 {
1130    360.0
1131}
1132
1133/// A right-handed placement frame in world coordinates (millimetres).
1134#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1135pub struct Placement {
1136    pub origin: [f64; 3],
1137    pub x_axis: [f64; 3],
1138    pub z_axis: [f64; 3],
1139}
1140
1141impl Default for Placement {
1142    fn default() -> Self {
1143        Self {
1144            origin: [0.0; 3],
1145            x_axis: [1.0, 0.0, 0.0],
1146            z_axis: [0.0, 0.0, 1.0],
1147        }
1148    }
1149}
1150
1151/// Which edges of the current solid a dress-up applies to. Edges are
1152/// identified geometrically: by a face they border (sample point on the
1153/// face) or by a point near the edge itself.
1154#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1155pub enum EdgeSelection {
1156    All,
1157    OfFaces(Vec<[f64; 3]>),
1158    /// The edges bordering the picked faces, each found by its name when
1159    /// it has one.
1160    OfPickedFaces(Vec<FaceProbe>),
1161    Near(Vec<[f64; 3]>),
1162    /// Edges picked one by one: each the nearest edge to its point that
1163    /// runs along its direction there.
1164    Picked(Vec<EdgeProbe>),
1165}
1166
1167/// A picked edge, as a point beside it and the way it runs there, and the
1168/// names of the two faces it runs between. A rebuild finds the edge
1169/// between faces of those names, the point choosing among several; without
1170/// names, the nearest edge. A zero direction leaves the way open.
1171#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
1172pub struct EdgeProbe {
1173    pub point: [f64; 3],
1174    pub direction: [f64; 3],
1175    #[serde(default)]
1176    pub faces: [TopoName; 2],
1177}
1178
1179/// How a thickness's walls meet across an edge of the solid.
1180#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1181pub enum ThicknessJoin {
1182    /// The walls run on until they meet: sharp corners.
1183    #[default]
1184    Intersection,
1185    /// The walls round about the edge, the wall thickness its radius.
1186    Arc,
1187}
1188
1189impl ThicknessJoin {
1190    pub const ALL: [ThicknessJoin; 2] = [ThicknessJoin::Intersection, ThicknessJoin::Arc];
1191
1192    pub fn label(&self) -> &'static str {
1193        match self {
1194            ThicknessJoin::Intersection => "Intersection",
1195            ThicknessJoin::Arc => "Arc",
1196        }
1197    }
1198}
1199
1200/// Chamfer sizing, mirroring the three standard input styles.
1201#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
1202pub enum ChamferSpec {
1203    EqualDistance { distance: f64 },
1204    TwoDistances { distance1: f64, distance2: f64 },
1205    DistanceAngle { distance: f64, angle_deg: f64 },
1206}
1207
1208/// Boolean between the running solid and an external tool solid.
1209#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1210pub enum BoolKind {
1211    Fuse,
1212    Cut,
1213    Common,
1214}
1215
1216/// One step in a body's build history. Shape-producing steps (`Sweep`,
1217/// `Loft`, `Pipe`, `Primitive`) carry a [`BooleanOp`]; the remaining steps
1218/// modify or combine the running solid directly.
1219///
1220/// A package builds these, so a variant keeps its fields for as long as
1221/// the contract's minor version holds: a new option comes as a new
1222/// variant, or as a new struct that derives `Default`.
1223#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1224pub enum SolidOp {
1225    /// Start the chain from a snapshot of another solid, in the native
1226    /// format `SolidBuildResult::brep_blob` carries. Only ever the first op.
1227    Shape { brep: Vec<u8> },
1228    Sweep {
1229        profile: Profile,
1230        kind: SweepKind,
1231        op: BooleanOp,
1232    },
1233    /// Extrude a flat face of the running solid: its outer and inner
1234    /// boundaries are the profile and its outward normal the sketch
1235    /// normal. `kind` is an `Extrude`.
1236    SweepFace {
1237        face: FaceProbe,
1238        kind: SweepKind,
1239        op: BooleanOp,
1240    },
1241    /// Extrude a flat face of another shape (native-format `shape`, moved by
1242    /// `transform` into this body's frame): the face of it at `point`, a
1243    /// face another body lends this one.
1244    SweepFaceOf {
1245        shape: Vec<u8>,
1246        transform: Option<Box<[[f64; 4]; 4]>>,
1247        point: [f64; 3],
1248        kind: SweepKind,
1249        op: BooleanOp,
1250    },
1251    /// Revolve a profile until it meets a face of another shape
1252    /// (native-format `shape`, moved by `transform` into this body's frame):
1253    /// the face of it nearest `point`, a face another body lends this one.
1254    /// `kind` is a `Revolve`, whose own termination is not read.
1255    RevolveToFaceOf {
1256        profile: Profile,
1257        kind: SweepKind,
1258        shape: Vec<u8>,
1259        transform: Option<Box<[[f64; 4]; 4]>>,
1260        point: [f64; 3],
1261        op: BooleanOp,
1262    },
1263    /// Skin through two or more sections (in order), each a profile, a
1264    /// flat face of the running solid (its boundary) or a point, which
1265    /// only the first or last may be.
1266    LoftThrough {
1267        sections: Vec<LoftSection>,
1268        ruled: bool,
1269        closed: bool,
1270        op: BooleanOp,
1271    },
1272    /// Skin through two or more section profiles (in order).
1273    Loft {
1274        sections: Vec<Profile>,
1275        ruled: bool,
1276        closed: bool,
1277        op: BooleanOp,
1278    },
1279    /// Sweep a profile along an open or closed spine wire from another
1280    /// sketch, the section turning as `frame` says and turning its corners
1281    /// as `corner` says. With `sections`, the section changes shape down
1282    /// the path, passing through each of them where it crosses the path,
1283    /// in order, the profile first.
1284    Pipe {
1285        profile: Profile,
1286        spine: Profile,
1287        #[serde(default, alias = "frenet", deserialize_with = "deserialize_pipe_frame")]
1288        frame: PipeFrame,
1289        #[serde(default)]
1290        corner: PipeCorner,
1291        #[serde(default)]
1292        sections: Vec<Profile>,
1293        op: BooleanOp,
1294    },
1295    /// A pipe whose profile may be a flat face of the running solid, whose
1296    /// path may be edges of a solid, and whose last section may be a point
1297    /// it closes to; the rest reads as for `Pipe`.
1298    PipeThrough {
1299        profile: LoftSection,
1300        path: PipePath,
1301        #[serde(default)]
1302        frame: PipeFrame,
1303        #[serde(default)]
1304        corner: PipeCorner,
1305        #[serde(default)]
1306        sections: Vec<LoftSection>,
1307        op: BooleanOp,
1308    },
1309    Primitive {
1310        kind: PrimitiveKind,
1311        placement: Placement,
1312        op: BooleanOp,
1313    },
1314    /// Round the selected edges; with `follow_tangent`, every edge meeting
1315    /// one of them tangentially joins the selection, and so on along the
1316    /// chain.
1317    Fillet {
1318        radius: f64,
1319        edges: EdgeSelection,
1320        #[serde(default)]
1321        follow_tangent: bool,
1322    },
1323    /// Bevel the selected edges, taking tangent chains as a fillet does.
1324    Chamfer {
1325        spec: ChamferSpec,
1326        flip: bool,
1327        edges: EdgeSelection,
1328        #[serde(default)]
1329        follow_tangent: bool,
1330    },
1331    /// Tilt the selected faces by `angle_deg` about their intersection with
1332    /// the neutral plane.
1333    Draft {
1334        angle_deg: f64,
1335        neutral_point: [f64; 3],
1336        neutral_normal: [f64; 3],
1337        pull_dir: Option<[f64; 3]>,
1338        faces: Vec<[f64; 3]>,
1339        /// The name of each face, one per point, found by name first; empty
1340        /// or zero where a face has none.
1341        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1342        face_names: Vec<TopoName>,
1343    },
1344    /// Merge adjacent faces of the solid that lie on one plane: the split
1345    /// a fuse or cut leaves where two pieces meet flush.
1346    Refine,
1347    /// Offset faces of the running solid along their outward normals by
1348    /// `distance` (negative into the material), the faces around them
1349    /// following on their own surfaces.
1350    OffsetFaces {
1351        faces: Vec<[f64; 3]>,
1352        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1353        face_names: Vec<TopoName>,
1354        distance: f64,
1355    },
1356    /// Move faces of the running solid rigidly by `transform` (row-major,
1357    /// a translation or a rotation), the faces around them following.
1358    MoveFaces {
1359        faces: Vec<[f64; 3]>,
1360        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1361        face_names: Vec<TopoName>,
1362        transform: [[f64; 4]; 4],
1363    },
1364    /// Remove faces of the running solid and close the openings from the
1365    /// neighbouring faces' own geometry: a hole, a boss or a fillet taken
1366    /// away. Faces as points on them, named where they have names.
1367    RemoveFaces {
1368        faces: Vec<[f64; 3]>,
1369        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1370        face_names: Vec<TopoName>,
1371    },
1372    /// Hollow the solid, removing the faces sampled by `open_faces`.
1373    Thickness {
1374        value: f64,
1375        open_faces: Vec<[f64; 3]>,
1376        /// The name of each open face, one per point; empty or zero where
1377        /// a face has none.
1378        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1379        open_face_names: Vec<TopoName>,
1380        inward: bool,
1381        /// How the walls meet where the solid's faces meet.
1382        #[serde(default)]
1383        join: ThicknessJoin,
1384        /// The walls stand on both sides of the solid's faces, `value` each
1385        /// way, rather than on the one `inward` says.
1386        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1387        both_sides: bool,
1388    },
1389    /// Re-apply earlier steps' tool solids (or the whole current solid when
1390    /// `originals` is empty) under each transform, fusing additive tools and
1391    /// cutting subtractive ones. `originals` holds chain indices of earlier
1392    /// shape-producing steps.
1393    Transform {
1394        transforms: Vec<[[f64; 4]; 4]>,
1395        originals: Vec<usize>,
1396    },
1397    /// [`SolidOp::Transform`] with the originals themselves left out: the
1398    /// steps `originals` names build their tools without adding or cutting
1399    /// them, so only the transformed copies go in. With `originals` empty
1400    /// the running solid gives way to its copies.
1401    TransformCopies {
1402        transforms: Vec<[[f64; 4]; 4]>,
1403        originals: Vec<usize>,
1404    },
1405    /// [`SolidOp::Transform`] whose transforms the chain works out from
1406    /// `steps` where the op stands, so a step may follow an edge of the
1407    /// solid as it is there. Occurrence 0 is the original; with it among
1408    /// `skipped`, only the copies go in, as [`SolidOp::TransformCopies`].
1409    Pattern {
1410        steps: Vec<PatternStep>,
1411        originals: Vec<usize>,
1412        /// Occurrences left out, by index: 0 the original, then each copy
1413        /// in the order the steps make them.
1414        #[serde(default, skip_serializing_if = "Vec::is_empty")]
1415        skipped: Vec<u32>,
1416    },
1417    /// Boolean against an external solid (another body's shape snapshot,
1418    /// ogeom native-format text bytes).
1419    Boolean {
1420        tool_brep: Vec<u8>,
1421        kind: BoolKind,
1422        /// Where the tool sits in this chain's frame, when the two bodies
1423        /// are placed differently: a rigid row-major 4×4 matrix.
1424        #[serde(default)]
1425        tool_transform: Option<[[f64; 4]; 4]>,
1426    },
1427    /// A surface step: a sheet added to the body, or the body's sheets
1428    /// joined, trimmed or mirrored.
1429    Surface(SurfaceOp),
1430    /// `op` with its booleans run at a stated tolerance: geometry within
1431    /// `tolerance` mm of touching counts as touching, so faces that nearly
1432    /// meet are joined rather than left with a gap or a sliver between
1433    /// them. The op keeps its place in the chain, as a pattern's
1434    /// `originals` count it.
1435    WithTolerance { tolerance: f64, op: Box<SolidOp> },
1436    /// A sketch carried along its plane's normal onto faces of the running
1437    /// solid, each face split along the curves where they land; `mode`
1438    /// says whether the regions the curves enclose then stand out of the
1439    /// faces or sink into them by `height`.
1440    Project {
1441        profile: Profile,
1442        faces: Vec<FaceProbe>,
1443        mode: ProjectMode,
1444        height: f64,
1445    },
1446    /// A sketch unrolled onto the cylinder or cone its `faces` lie on, so
1447    /// its lengths are kept on the surface: the sketch's middle lands where
1448    /// a straight projection along its plane's normal puts it, and the
1449    /// rest is laid round the surface from there, the way across the
1450    /// axis turning about it and the way along the axis following it.
1451    /// Otherwise as [`SolidOp::Project`].
1452    Wrap {
1453        profile: Profile,
1454        faces: Vec<FaceProbe>,
1455        mode: ProjectMode,
1456        height: f64,
1457    },
1458}
1459
1460/// What a [`SolidOp::Project`] makes of the faces a sketch lands on.
1461#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1462pub enum ProjectMode {
1463    /// The faces split along the sketch's curves, the solid's shape
1464    /// unchanged: lines later features and face colours can use.
1465    #[default]
1466    Split,
1467    /// The regions the curves enclose raised out of the faces.
1468    Emboss,
1469    /// The regions the curves enclose sunk into the faces.
1470    Deboss,
1471}
1472
1473impl ProjectMode {
1474    pub const ALL: [ProjectMode; 3] =
1475        [ProjectMode::Split, ProjectMode::Emboss, ProjectMode::Deboss];
1476
1477    pub fn label(&self) -> &'static str {
1478        match self {
1479            ProjectMode::Split => "Split lines",
1480            ProjectMode::Emboss => "Emboss",
1481            ProjectMode::Deboss => "Deboss",
1482        }
1483    }
1484}
1485
1486/// A curve a surface is built from.
1487#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1488pub enum CurveSource {
1489    /// A chain of a sketch's curves, open or closed, on its plane.
1490    Sketch {
1491        plane: ProfilePlane,
1492        wire: ProfileWire,
1493    },
1494    /// An edge of the body's own shape as it stands where the step comes,
1495    /// found as a fillet's picked edges are.
1496    Edge(EdgeProbe),
1497    /// An edge of another body's shape: `brep` is that body's snapshot,
1498    /// `edge` finds the edge in its own frame, and `transform` (a rigid
1499    /// row-major 4×4 matrix) carries it to where it sits in this chain's
1500    /// frame, when the two bodies are placed differently.
1501    BodyEdge {
1502        brep: Vec<u8>,
1503        edge: EdgeProbe,
1504        #[serde(default)]
1505        transform: Option<Box<[[f64; 4]; 4]>>,
1506    },
1507}
1508
1509/// How a surface meets the faces beside it across a shared edge.
1510#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
1511pub enum Continuity {
1512    /// Touching: no gap, a crease allowed.
1513    #[default]
1514    G0,
1515    /// Tangent: no crease.
1516    G1,
1517    /// Curvature continuous: no change in how sharply it bends.
1518    G2,
1519}
1520
1521/// The steps of surface modelling. A constructive step (every one but
1522/// `Sew`, `TrimByPlane` and `Mirror`) adds its sheet to the body beside
1523/// what is there; the rest act on all of the body's shape.
1524#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1525pub enum SurfaceOp {
1526    /// Each curve swept straight along `direction` by `length`, both ways
1527    /// by half of it when `symmetric`.
1528    Extrude {
1529        curves: Vec<CurveSource>,
1530        direction: [f64; 3],
1531        length: f64,
1532        #[serde(default)]
1533        symmetric: bool,
1534    },
1535    /// Each curve turned by `angle_deg` about the axis through `origin`
1536    /// along `axis`.
1537    Revolve {
1538        curves: Vec<CurveSource>,
1539        origin: [f64; 3],
1540        axis: [f64; 3],
1541        angle_deg: f64,
1542    },
1543    /// The flat face closed planar loops bound, a loop inside another a
1544    /// hole in it.
1545    PlanarFill { curves: Vec<CurveSource> },
1546    /// The surface curves meeting end to end bound, meeting the faces the
1547    /// boundary edges belong to with `continuity`.
1548    Fill {
1549        boundary: Vec<CurveSource>,
1550        #[serde(default)]
1551        continuity: Continuity,
1552    },
1553    /// The surface of straight lines between two curves, end to end.
1554    Ruled {
1555        first: CurveSource,
1556        second: CurveSource,
1557    },
1558    /// A surface through section curves in order, closing back to the first
1559    /// when `closed`.
1560    Loft {
1561        sections: Vec<CurveSource>,
1562        #[serde(default)]
1563        closed: bool,
1564    },
1565    /// A profile curve swept along a path.
1566    Sweep {
1567        profile: Vec<CurveSource>,
1568        path: Vec<CurveSource>,
1569        #[serde(default)]
1570        frame: PipeFrame,
1571    },
1572    /// A surface through section curves in order that also follows guide
1573    /// curves, each crossing every section once: one face.
1574    GuidedLoft {
1575        sections: Vec<CurveSource>,
1576        guides: Vec<CurveSource>,
1577    },
1578    /// A profile running from the first rail's start to the second's,
1579    /// swept along both: at each point along them it is turned and scaled
1580    /// so its ends ride the rails.
1581    SweepTwoRails {
1582        profile: Vec<CurveSource>,
1583        first_rail: Vec<CurveSource>,
1584        second_rail: Vec<CurveSource>,
1585    },
1586    /// Faces carried off along their normals by `distance`, as new faces.
1587    Offset {
1588        faces: Vec<FaceProbe>,
1589        distance: f64,
1590    },
1591    /// Faces carried past picked edges of their boundary by `length`.
1592    Extend {
1593        edges: Vec<EdgeProbe>,
1594        length: f64,
1595        #[serde(default)]
1596        continuity: Continuity,
1597    },
1598    /// A surface bridging two edges, meeting each edge's face with
1599    /// `continuity`.
1600    Blend {
1601        first: EdgeProbe,
1602        second: EdgeProbe,
1603        #[serde(default)]
1604        continuity: Continuity,
1605    },
1606    /// Picked faces split along curves projected onto them.
1607    Split {
1608        faces: Vec<FaceProbe>,
1609        curves: Vec<CurveSource>,
1610    },
1611    /// The body's faces joined where their edges meet, or come within
1612    /// `gap` of each other (0 for exactly); a shell that closes becomes a
1613    /// solid.
1614    Sew {
1615        #[serde(default)]
1616        gap: f64,
1617    },
1618    /// A round of `radius` along picked edges where two faces of a sheet
1619    /// meet.
1620    Fillet { edges: Vec<EdgeProbe>, radius: f64 },
1621    /// A round of `radius` between two faces of the body that need share
1622    /// no edge, such as two separate surfaces, each cut back to where it
1623    /// meets the round. The ball rolls on the side each face's normal
1624    /// points to, on the other where `flip` says so.
1625    FilletFaces {
1626        first: FaceProbe,
1627        second: FaceProbe,
1628        radius: f64,
1629        #[serde(default)]
1630        flip: [bool; 2],
1631    },
1632    /// The body's sheets given `thickness` along their normals (both ways
1633    /// by half when `both_sides`): a solid.
1634    Thicken {
1635        thickness: f64,
1636        #[serde(default)]
1637        both_sides: bool,
1638    },
1639    /// The body's sheets cut by the plane through `origin`, the side
1640    /// `normal` points to kept.
1641    TrimByPlane { origin: [f64; 3], normal: [f64; 3] },
1642    /// The body's shape and its reflection in the plane through `origin`
1643    /// square to `normal`.
1644    Mirror { origin: [f64; 3], normal: [f64; 3] },
1645}
1646
1647impl SurfaceOp {
1648    /// Whether the step makes a new sheet (and so may begin a chain).
1649    pub fn constructs(&self) -> bool {
1650        !matches!(
1651            self,
1652            SurfaceOp::Sew { .. }
1653                | SurfaceOp::Fillet { .. }
1654                | SurfaceOp::FilletFaces { .. }
1655                | SurfaceOp::Thicken { .. }
1656                | SurfaceOp::TrimByPlane { .. }
1657                | SurfaceOp::Mirror { .. }
1658                | SurfaceOp::Split { .. }
1659                | SurfaceOp::Extend { .. }
1660        )
1661    }
1662}
1663
1664/// One step of a [`SolidOp::Pattern`]: each applies to every occurrence of
1665/// the steps before it, the original among them, which stands first.
1666#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1667pub enum PatternStep {
1668    /// A copy under each transform (rigid or not, row-major), the
1669    /// original, untransformed, left out.
1670    Transforms(Vec<[[f64; 4]; 4]>),
1671    /// Copies along a path.
1672    Path(PathLayout),
1673}
1674
1675/// The path a [`PathLayout`] runs along, in the chain's frame.
1676#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1677pub enum PatternPath {
1678    /// A chain of curves on a plane, walked from its first segment's
1679    /// start.
1680    Wire {
1681        plane: ProfilePlane,
1682        wire: ProfileWire,
1683    },
1684    /// The edge of the solid, where the step stands, that the probe finds,
1685    /// walked from its curve's start.
1686    Edge(EdgeProbe),
1687}
1688
1689/// Occurrences at stations along a path by arc length, the original at
1690/// the first: occurrence k is moved from where the first station stands
1691/// to where the k-th does, turned as the path turns between them when
1692/// `align`.
1693#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1694pub struct PathLayout {
1695    pub path: PatternPath,
1696    /// Occurrences, the original counted.
1697    pub count: u32,
1698    /// Millimetres between neighbours along the path; `None` spreads them
1699    /// over the whole of it, evenly round it when it closes.
1700    #[serde(default, skip_serializing_if = "Option::is_none")]
1701    pub spacing: Option<f64>,
1702    /// Walk the path from its end.
1703    #[serde(default)]
1704    pub reversed: bool,
1705    /// Turn each copy as the path's direction turns from the first
1706    /// station to its own, carried along the path without twisting.
1707    #[serde(default)]
1708    pub align: bool,
1709}
1710
1711impl SolidOp {
1712    /// The op itself, out of any [`SolidOp::WithTolerance`] around it.
1713    pub fn inner(&self) -> &SolidOp {
1714        match self {
1715            SolidOp::WithTolerance { op, .. } => op.inner(),
1716            op => op,
1717        }
1718    }
1719
1720    /// The tolerance the op's booleans run at, when one is stated: the
1721    /// outermost [`SolidOp::WithTolerance`]'s.
1722    pub fn boolean_tolerance(&self) -> Option<f64> {
1723        match self {
1724            SolidOp::WithTolerance { tolerance, .. } => Some(*tolerance),
1725            _ => None,
1726        }
1727    }
1728
1729    /// The op with its booleans run at `tolerance`, or as it is with none.
1730    pub fn with_boolean_tolerance(self, tolerance: Option<f64>) -> SolidOp {
1731        match tolerance {
1732            Some(tolerance) => SolidOp::WithTolerance {
1733                tolerance,
1734                op: Box::new(self),
1735            },
1736            None => self,
1737        }
1738    }
1739
1740    /// Whether the step makes a shape of its own, so a chain may begin with
1741    /// it: a new solid, or a surface step that adds a sheet.
1742    pub fn starts_shape(&self) -> bool {
1743        match self.inner() {
1744            SolidOp::Surface(op) => op.constructs(),
1745            _ => self.boolean_op() == Some(BooleanOp::NewSolid),
1746        }
1747    }
1748
1749    /// The boolean role of a shape-producing step; `None` for modifiers.
1750    pub fn boolean_op(&self) -> Option<BooleanOp> {
1751        match self.inner() {
1752            SolidOp::Sweep { op, .. }
1753            | SolidOp::SweepFace { op, .. }
1754            | SolidOp::SweepFaceOf { op, .. }
1755            | SolidOp::RevolveToFaceOf { op, .. }
1756            | SolidOp::Loft { op, .. }
1757            | SolidOp::LoftThrough { op, .. }
1758            | SolidOp::PipeThrough { op, .. }
1759            | SolidOp::Pipe { op, .. }
1760            | SolidOp::Primitive { op, .. } => Some(*op),
1761            // A snapshot is a solid in itself: it begins a chain.
1762            SolidOp::Shape { .. } => Some(BooleanOp::NewSolid),
1763            _ => None,
1764        }
1765    }
1766}
1767
1768/// Error from executing a body's solid-op chain, attributed to the failing
1769/// step so the caller can mark the matching feature.
1770#[derive(Debug, Clone, Error)]
1771#[error("op {op_index}: {message}")]
1772pub struct ChainError {
1773    pub op_index: usize,
1774    pub message: String,
1775}
1776
1777/// Result of executing a body's solid-op chain.
1778#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1779pub struct SolidBuildResult {
1780    /// Native-format shape snapshot of the final solid (for later
1781    /// re-tessellation, persistence, and downstream booleans).
1782    pub brep_blob: Vec<u8>,
1783    /// Render mesh of the final solid.
1784    pub mesh: TriMesh,
1785    /// Axis-aligned bounds in millimetres.
1786    pub bounds_mm: Option<([f32; 3], [f32; 3])>,
1787    /// What the feature being edited does, when the build was asked for it.
1788    pub preview: Option<Box<FeaturePreview>>,
1789    /// The answers to the chain's probes, in the order they were asked.
1790    pub probes: Vec<Result<ProbeAnswer, String>>,
1791    /// The curves the chain's projections came to, in the order they were
1792    /// asked.
1793    #[serde(default)]
1794    pub projections: Vec<Result<Vec<ProjectedEdge>, String>>,
1795}
1796
1797/// What a feature being edited does to its body, beside the body without
1798/// it: the view while it is edited.
1799#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1800pub struct FeaturePreview {
1801    /// The body to show meanwhile: as it stood before a feature that adds,
1802    /// after one that cuts. None when an adding feature is the body's
1803    /// first.
1804    pub shown: Option<Box<SolidBuildResult>>,
1805    /// The feature's own tool solid, meshed: the material it adds or takes.
1806    pub tool: TriMesh,
1807    /// The feature cuts.
1808    pub cuts: bool,
1809}
1810
1811/// Trait implemented by any geometry kernel that can serve the application.
1812pub trait Kernel: Send {
1813    /// Human-friendly identifier for logging purposes.
1814    fn name(&self) -> &str;
1815
1816    /// Called once before any geometry work happens.
1817    fn initialize(&mut self) -> KernelResult<()>;
1818
1819    /// Recompute dirty features/bodies and return the affected handles.
1820    fn rebuild(&mut self, request: &RebuildRequest) -> KernelResult<RebuildResponse>;
1821
1822    /// Produce a triangular mesh for the provided body handle.
1823    fn tessellate(&self, body: BodyHandle, detail: &TessellationSettings) -> KernelResult<TriMesh>;
1824
1825    /// Read a STEP/STP file from disk and return tessellated bodies.
1826    ///
1827    /// Implementations that do not support STEP import should return
1828    /// [`KernelError::Unsupported`].
1829    fn import_step(
1830        &mut self,
1831        _path: &Path,
1832        _detail: &TessellationSettings,
1833    ) -> KernelResult<ImportedModel> {
1834        Err(KernelError::Unsupported(
1835            "STEP import is not implemented by this kernel".into(),
1836        ))
1837    }
1838}
1839
1840/// An edge of a solid projected onto a plane, in the plane's own 2D
1841/// coordinates (along its `x_axis` and `y_axis`).
1842#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1843pub enum ProjectedEdge {
1844    /// The edge runs along the plane's normal, so it projects to a point.
1845    Point([f64; 2]),
1846    /// A segment.
1847    Line { start: [f64; 2], end: [f64; 2] },
1848    /// A circle or circular arc, `centre + radius (cos t, sin t)`, turning
1849    /// counter-clockwise from `range.0` to `range.1`; a full circle when the
1850    /// range spans a turn.
1851    Circle {
1852        centre: [f64; 2],
1853        radius: f64,
1854        range: (f64, f64),
1855    },
1856    /// An ellipse or elliptical arc, `centre + major cos t + minor sin t`,
1857    /// `minor` the major axis turned a quarter counter-clockwise and scaled
1858    /// by `ratio`, from `range.0` to `range.1`.
1859    Ellipse {
1860        centre: [f64; 2],
1861        major: [f64; 2],
1862        ratio: f64,
1863        range: (f64, f64),
1864    },
1865    /// A piece of a parabola, `vertex + axis s² / (4 focal) + side s`,
1866    /// `axis` a unit vector the way it opens and `side` it turned a quarter
1867    /// counter-clockwise, from `s = range.0` to `range.1`.
1868    Parabola {
1869        vertex: [f64; 2],
1870        axis: [f64; 2],
1871        focal: f64,
1872        range: (f64, f64),
1873    },
1874    /// A piece of one branch of a hyperbola, `centre + major cosh s +
1875    /// minor sinh s`, `major` (centre to the branch's vertex) square to
1876    /// `minor`, from `s = range.0` to `range.1`.
1877    Hyperbola {
1878        centre: [f64; 2],
1879        major: [f64; 2],
1880        minor: [f64; 2],
1881        range: (f64, f64),
1882    },
1883    /// A B-spline, as the kernel projects it: `degree`, its clamped
1884    /// `knots` (`control_points + degree + 1` of them), and a weight per
1885    /// control point when rational (empty when every weight is one).
1886    Spline {
1887        degree: u32,
1888        knots: Vec<f64>,
1889        control_points: Vec<[f64; 2]>,
1890        weights: Vec<f64>,
1891    },
1892    /// Any other curve, as points along it: exact at each point, straight
1893    /// between.
1894    Polyline(Vec<[f64; 2]>),
1895}
1896
1897/// One curve where a plane crosses a shape.
1898#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1899pub struct SectionCurve {
1900    /// The exact curve, in the plane's own 2D coordinates.
1901    pub curve: ProjectedEdge,
1902    /// Points along it, in the shape's own frame, in the order its run
1903    /// goes.
1904    pub points: Vec<[f64; 3]>,
1905    /// The run goes against the way `curve` runs.
1906    #[serde(default)]
1907    pub reversed: bool,
1908}
1909
1910/// Curves where a plane crosses a shape, end to end: a closed loop round
1911/// a solid's cut, or an open run where a sheet's edge stops it.
1912#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1913pub struct SectionRun {
1914    pub curves: Vec<SectionCurve>,
1915    pub closed: bool,
1916}
1917
1918/// One edge of a face's boundary loop.
1919#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1920pub struct LoopEdge {
1921    /// Points along it, in the shape's own frame, in the order the loop
1922    /// walks it.
1923    pub points: Vec<[f64; 3]>,
1924    /// The edge a round face meets itself along: it turns up twice in
1925    /// its loop, once each way.
1926    #[serde(default)]
1927    pub seam: bool,
1928}
1929
1930/// The curves of a 2D drawing file, in the drawing's own coordinates.
1931#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
1932pub struct Drawing2d {
1933    /// Millimetres per drawing unit, when the drawing names its unit.
1934    pub unit_mm: Option<f64>,
1935    /// Every curve, in the order the file has them.
1936    pub curves: Vec<DrawingCurve>,
1937}
1938
1939/// One curve of a drawing, and whether the drawing marks it hidden
1940/// (a hidden layer, or a dashed line type).
1941#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1942pub struct DrawingCurve {
1943    pub hidden: bool,
1944    pub shape: DrawingShape,
1945}
1946
1947/// The kinds of curve a drawing carries. Angles are radians, arcs run
1948/// counter-clockwise.
1949#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1950pub enum DrawingShape {
1951    /// Points in order, each segment a line, or an arc where the bulge of
1952    /// the segment starting at that point (the tangent of a quarter of its
1953    /// included angle, positive counter-clockwise) is not zero. `bulges`
1954    /// is as long as `points`, or empty for straight segments only.
1955    Polyline {
1956        points: Vec<[f64; 2]>,
1957        bulges: Vec<f64>,
1958        closed: bool,
1959    },
1960    Arc {
1961        centre: [f64; 2],
1962        radius: f64,
1963        start_angle: f64,
1964        end_angle: f64,
1965    },
1966    Circle {
1967        centre: [f64; 2],
1968        radius: f64,
1969    },
1970    /// Points `centre + major cos t + ratio perp(major) sin t` for `t`
1971    /// from `start_param` to `end_param`; the whole ellipse when those span
1972    /// a full turn.
1973    Ellipse {
1974        centre: [f64; 2],
1975        major: [f64; 2],
1976        ratio: f64,
1977        start_param: f64,
1978        end_param: f64,
1979    },
1980    /// A spline, as points along the exact curve.
1981    Spline {
1982        points: Vec<[f64; 2]>,
1983        closed: bool,
1984    },
1985}
1986
1987/// The solid two shapes share: its volume, its centre and its mesh, in
1988/// the first shape's frame.
1989#[derive(Debug, Clone)]
1990pub struct Overlap {
1991    pub volume_mm3: f64,
1992    pub centre_mm: [f64; 3],
1993    pub mesh: TriMesh,
1994}
1995
1996/// How near two shapes come: the distance between their boundaries and a
1997/// nearest point on each, in the first shape's frame. Zero where the
1998/// boundaries touch or cross.
1999#[derive(Debug, Clone, Copy, PartialEq)]
2000pub struct Gap {
2001    pub distance_mm: f64,
2002    pub on_a: [f64; 3],
2003    pub on_b: [f64; 3],
2004}
2005
2006/// A stretch of a region's medial axis, in the profile plane's own 2D
2007/// coordinates: points along one branch with the clearance at each, the
2008/// radius of the largest disc centred there that stays inside the region.
2009#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2010pub struct MedialPath {
2011    pub points: Vec<[f64; 2]>,
2012    /// One per point, in millimetres.
2013    pub clearance: Vec<f64>,
2014    /// Whether the first and the last point end the axis on the boundary
2015    /// (a corner, or a rounded end's centre) rather than meet other
2016    /// branches: towards such an end the clearance falls without the
2017    /// region getting thinner.
2018    pub boundary_ends: [bool; 2],
2019}
2020
2021/// Where a region is narrowest, and how narrow: the smallest clearance on
2022/// its medial axis away from the branch ends at its corners (where the
2023/// clearance runs down to nothing without the region getting any thinner).
2024/// The wall there is twice the clearance.
2025#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
2026pub struct Narrowest {
2027    pub at: [f64; 2],
2028    pub clearance: f64,
2029}
2030
2031/// The medial axis of one region of a profile: an outer wire and its holes.
2032#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2033pub struct MedialRegion {
2034    /// The profile's wires that bound it, by index, the outer one first.
2035    pub wires: Vec<usize>,
2036    pub paths: Vec<MedialPath>,
2037    /// `None` only when the axis has no place away from the corners.
2038    pub narrowest: Option<Narrowest>,
2039}
2040
2041/// A picked face: its name, and a point on it with its outward normal.
2042/// A rebuild finds the face by its name, the point choosing among the
2043/// pieces of a face that split; without a name (or when no face bears it
2044/// any more), the face nearest the point.
2045#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
2046pub struct FaceProbe {
2047    pub point: [f64; 3],
2048    pub normal: [f64; 3],
2049    #[serde(default)]
2050    pub name: TopoName,
2051}
2052
2053/// A question about a solid a reference stands on, named geometrically so
2054/// it can be asked again of the solid a rebuild makes.
2055#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
2056pub enum ShapeProbe {
2057    /// The face named `name`, else the face nearest `point` (among faces
2058    /// as near, the one whose outward normal agrees best with `normal`),
2059    /// and where on it `point` falls.
2060    Face {
2061        point: [f64; 3],
2062        normal: [f64; 3],
2063        #[serde(default)]
2064        name: TopoName,
2065    },
2066    /// The edge between faces named `faces`, else the edge nearest `point`
2067    /// that runs along `direction` there (a zero direction takes the
2068    /// nearest edge whichever way it runs).
2069    Edge {
2070        point: [f64; 3],
2071        direction: [f64; 3],
2072        #[serde(default)]
2073        faces: [TopoName; 2],
2074        /// A share along the edge from its start (0 to 1) whose point and
2075        /// tangent the answer also gives.
2076        #[serde(default, skip_serializing_if = "Option::is_none")]
2077        along: Option<f64>,
2078    },
2079    /// The solid's centre of mass and principal axes of inertia.
2080    Mass,
2081}
2082
2083/// What a solid answers to a [`ShapeProbe`], in the solid's own frame.
2084#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
2085pub enum ProbeAnswer {
2086    /// The point of the face nearest the probe's, the face's outward normal
2087    /// there, and the face's surface.
2088    Face {
2089        point: [f64; 3],
2090        normal: [f64; 3],
2091        surface: FaceSurface,
2092    },
2093    /// The point of the edge nearest the probe's and the way the edge runs
2094    /// there, its two ends and its middle (halfway along its parameter,
2095    /// which is halfway along an arc), and the circle it runs round when
2096    /// it is a circle or an arc of one.
2097    Edge {
2098        point: [f64; 3],
2099        direction: [f64; 3],
2100        start: [f64; 3],
2101        end: [f64; 3],
2102        middle: [f64; 3],
2103        circle: Option<ProbedCircle>,
2104        /// The point and tangent the probe's share along gives, when it
2105        /// asked for one.
2106        #[serde(default, skip_serializing_if = "Option::is_none")]
2107        along: Option<([f64; 3], [f64; 3])>,
2108    },
2109    /// The centre of mass and the principal axes of inertia, the axis of
2110    /// the smallest moment first.
2111    Mass {
2112        centre: [f64; 3],
2113        axes: [[f64; 3]; 3],
2114    },
2115}
2116
2117/// The circle an edge runs round.
2118#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
2119pub struct ProbedCircle {
2120    pub centre: [f64; 3],
2121    pub normal: [f64; 3],
2122    pub radius: f64,
2123}
2124
2125/// A probe asked part way through a solid-op chain: of the solid the first
2126/// `after_op` ops make.
2127#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
2128pub struct ChainProbe {
2129    pub after_op: usize,
2130    pub probe: ShapeProbe,
2131}
2132
2133/// A solid's edge projected onto a plane, or the curves where one of its
2134/// faces crosses the plane: what a sketch takes from the solid it stands
2135/// on, asked again of the solid a rebuild makes.
2136#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
2137pub struct ProjectionProbe {
2138    /// A point on the edge (on the face, for a section), in the solid's
2139    /// own frame.
2140    pub point: [f64; 3],
2141    /// The names of the two faces the edge runs between: the edge is found
2142    /// by them first, `point` choosing among its pieces, and by `point`
2143    /// alone without them or when no edge runs between them.
2144    #[serde(default)]
2145    pub faces: [TopoName; 2],
2146    /// The face nearest `point` is cut by the plane, in place of an edge
2147    /// projected onto it.
2148    #[serde(default)]
2149    pub section: bool,
2150    /// The plane, in the solid's own frame: the curves come in its own 2D
2151    /// coordinates.
2152    pub plane: ProfilePlane,
2153}
2154
2155/// A projection asked part way through a solid-op chain: of the solid the
2156/// first `after_op` ops make.
2157#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
2158pub struct ChainProjection {
2159    pub after_op: usize,
2160    pub probe: ProjectionProbe,
2161}
2162
2163/// The centre line of a pipe-like solid between two of its faces.
2164#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2165pub struct CentreLine {
2166    /// Points along it, from the first face to the second, in the shape's
2167    /// frame.
2168    pub points: Vec<[f64; 3]>,
2169    /// Its length, in millimetres.
2170    pub length: f64,
2171    /// The largest distance measured from the centroid of a section cut
2172    /// square to the line to the line itself.
2173    pub deviation: f64,
2174    /// It is one straight segment.
2175    pub straight: bool,
2176}
2177
2178/// A round hole found in a solid: a full bore, open at one end (blind)
2179/// or both (through), closed by a flat bottom or a drill point.
2180#[derive(Debug, Clone, PartialEq)]
2181pub struct RecognizedHole {
2182    /// The centre of its opening, on its axis.
2183    pub entry: [f64; 3],
2184    /// Along its axis, into the material.
2185    pub direction: [f64; 3],
2186    pub diameter: f64,
2187    /// The bore's length from the opening, not counting a drill point.
2188    pub depth: f64,
2189    /// Open at both ends.
2190    pub through: bool,
2191    /// The included angle of the cone that ends a blind hole, degrees;
2192    /// `None` for a flat bottom or a through hole.
2193    pub drill_point_deg: Option<f64>,
2194    /// A point on each face the hole is made of (its bore, its bottom),
2195    /// with that face's outward normal.
2196    pub faces: Vec<([f64; 3], [f64; 3])>,
2197}
2198
2199/// Geometry questions a workbench may ask while it runs, answered by the
2200/// kernel at once. Shapes arrive as the snapshot bytes the document keeps.
2201/// How two faces of a shape meet across an edge they share: a point
2202/// halfway along it, in the shape's own frame, the largest gap between the
2203/// edge and the faces, the largest angle between the faces' normals along
2204/// it (zero where they meet tangent), and the largest difference in how
2205/// sharply they bend square to it (1/mm; zero where they meet curvature
2206/// continuous, `None` where it could not be read).
2207#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
2208pub struct EdgeContinuity {
2209    pub point: [f64; 3],
2210    pub gap: f64,
2211    pub angle_deg: f64,
2212    #[serde(default)]
2213    pub curvature: Option<f64>,
2214}
2215
2216/// A face of a shape, named by a point inside it, and points on it, each
2217/// with the normal its curvature is signed against.
2218pub type FacePoints = ([f64; 3], Vec<([f64; 3], [f64; 3])>);
2219
2220/// A point on a path and the way the path runs there.
2221#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
2222pub struct PathFrame {
2223    pub point: [f64; 3],
2224    /// A unit vector along the path, the way it is walked.
2225    pub tangent: [f64; 3],
2226}
2227
2228/// Stations along a path, by arc length: what is repeated along a curve
2229/// stands at them.
2230#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2231pub struct PathFrames {
2232    /// The path's whole length, mm.
2233    pub length: f64,
2234    /// Whether the path ends where it starts.
2235    pub closed: bool,
2236    /// One per station asked for, in the order asked.
2237    pub frames: Vec<PathFrame>,
2238}
2239
2240pub trait KernelQueries: Send + Sync {
2241    /// Every edge two faces of `brep` share, with how they meet there.
2242    fn continuity(&self, _brep: &[u8]) -> KernelResult<Vec<EdgeContinuity>> {
2243        Err(KernelError::Unsupported("continuity".into()))
2244    }
2245
2246    /// The principal curvatures of `brep`'s faces at points on them. Each
2247    /// entry names a face by a point inside it (the face nearest that
2248    /// point) and lists points on it, each with the normal it is signed
2249    /// against, in the shape's own frame; the answer gives, per point, the
2250    /// largest and the smallest normal curvature (1/mm): negative where the
2251    /// face bulges toward that normal, positive where it hollows away.
2252    /// `None` where the surface has no normal (a pole, an apex).
2253    fn curvature(
2254        &self,
2255        _brep: &[u8],
2256        _faces: &[FacePoints],
2257    ) -> KernelResult<Vec<Vec<Option<[f64; 2]>>>> {
2258        Err(KernelError::Unsupported("curvature".into()))
2259    }
2260
2261    /// The edges bounding the face of `brep` nearest `near`: a point on
2262    /// each, halfway along, and its direction there, in the shape's own
2263    /// frame. A seam (the edge a round face meets itself along) and an
2264    /// edge with no curve (a pole) are left out.
2265    fn face_edges(&self, _brep: &[u8], _near: [f64; 3]) -> KernelResult<Vec<([f64; 3], [f64; 3])>> {
2266        Err(KernelError::Unsupported("face_edges".into()))
2267    }
2268
2269    /// The round holes of `brep`, in its own frame, and how many bores it
2270    /// has that are not holes it can describe (a counterbore, a slot).
2271    fn recognize_holes(&self, _brep: &[u8]) -> KernelResult<(Vec<RecognizedHole>, usize)> {
2272        Err(KernelError::Unsupported("recognize_holes".into()))
2273    }
2274
2275    /// What `a` and `b` share when `b` sits where `b_in_a` (a rigid
2276    /// row-major 4×4 matrix) puts it in `a`'s frame; `None` when they only
2277    /// touch or are apart.
2278    fn overlap(
2279        &self,
2280        _a: &[u8],
2281        _b: &[u8],
2282        _b_in_a: &[[f64; 4]; 4],
2283    ) -> KernelResult<Option<Overlap>> {
2284        Err(KernelError::Unsupported("overlap".into()))
2285    }
2286
2287    /// How near `a` and `b` come when `b` sits where `b_in_a` puts it in
2288    /// `a`'s frame.
2289    fn gap(&self, _a: &[u8], _b: &[u8], _b_in_a: &[[f64; 4]; 4]) -> KernelResult<Gap> {
2290        Err(KernelError::Unsupported("gap".into()))
2291    }
2292
2293    /// `brep` mirrored across the plane through `point` with `normal`, in
2294    /// its own frame, as a snapshot of its own.
2295    fn mirror(&self, _brep: &[u8], _point: [f64; 3], _normal: [f64; 3]) -> KernelResult<Vec<u8>> {
2296        Err(KernelError::Unsupported("mirror".into()))
2297    }
2298
2299    /// The volume, area and centre of mass of `brep`, in its own frame.
2300    fn measure(&self, _brep: &[u8]) -> KernelResult<PhysicalProperties> {
2301        Err(KernelError::Unsupported("measure".into()))
2302    }
2303
2304    /// The edge of `brep` nearest `near`, projected orthogonally onto
2305    /// `plane`. Both are in the shape's own frame.
2306    fn project_edge(
2307        &self,
2308        brep: &[u8],
2309        near: [f64; 3],
2310        plane: &ProfilePlane,
2311    ) -> KernelResult<ProjectedEdge>;
2312
2313    /// Points and tangents along the edge of `brep` nearest `near` (within
2314    /// a pick's reach of it), from the start of its curve: one per entry of
2315    /// `stations`, each a fraction of the edge's length (0 its start, 1 its
2316    /// end) placed by arc length, not by the curve's parameter. Everything
2317    /// is in the shape's own frame.
2318    fn edge_frames(
2319        &self,
2320        _brep: &[u8],
2321        _near: [f64; 3],
2322        _stations: &[f64],
2323    ) -> KernelResult<PathFrames> {
2324        Err(KernelError::Unsupported("points along an edge".into()))
2325    }
2326
2327    /// Points and tangents along `wire` on `plane`, walked from its first
2328    /// segment's start: one per entry of `stations`, each a fraction of the
2329    /// wire's whole length placed by arc length, as `edge_frames`.
2330    fn wire_frames(
2331        &self,
2332        _plane: &ProfilePlane,
2333        _wire: &ProfileWire,
2334        _stations: &[f64],
2335    ) -> KernelResult<PathFrames> {
2336        Err(KernelError::Unsupported("points along a wire".into()))
2337    }
2338
2339    /// Where every occurrence of a [`SolidOp::Pattern`] with `steps` stands,
2340    /// as row-major transforms from the original's place, the original's
2341    /// (the identity) first: what the chain works out, with `brep` (in the
2342    /// pattern's frame) as the solid a step's edge is found on.
2343    fn pattern_transforms(
2344        &self,
2345        _brep: Option<&[u8]>,
2346        _steps: &[PatternStep],
2347    ) -> KernelResult<Vec<[[f64; 4]; 4]>> {
2348        Err(KernelError::Unsupported("pattern transforms".into()))
2349    }
2350
2351    /// The face of `brep` nearest `near` (in the shape's own frame), as a
2352    /// native-format snapshot of its own: what a face taken from a solid
2353    /// keeps once the solid moves on.
2354    fn face_of(&self, _brep: &[u8], _near: [f64; 3]) -> KernelResult<Vec<u8>> {
2355        Err(KernelError::Unsupported(
2356            "taking a face out of a solid".into(),
2357        ))
2358    }
2359
2360    /// The edge of `brep` nearest `near` (in the shape's own frame), as a
2361    /// native-format snapshot of its own.
2362    fn edge_of(&self, _brep: &[u8], _near: [f64; 3]) -> KernelResult<Vec<u8>> {
2363        Err(KernelError::Unsupported(
2364            "taking an edge out of a solid".into(),
2365        ))
2366    }
2367
2368    /// Where the face of `brep` nearest `near` crosses `plane`, as the
2369    /// curves the plane cuts from it, in the plane's own 2D coordinates:
2370    /// each the exact line, circle or ellipse it is, or points along any
2371    /// other. Empty when the face does not reach the plane. Both are in the
2372    /// shape's own frame.
2373    fn section_face(
2374        &self,
2375        _brep: &[u8],
2376        _near: [f64; 3],
2377        _plane: &ProfilePlane,
2378    ) -> KernelResult<Vec<ProjectedEdge>> {
2379        Err(KernelError::Unsupported("face section".into()))
2380    }
2381
2382    /// Where `plane` crosses `brep`, chained end to end, each curve exact
2383    /// in the plane's own 2D coordinates and drawn in the shape's own
2384    /// frame: the whole shape's section, or with `near` only the face
2385    /// nearest it. Empty when the plane misses.
2386    fn section(
2387        &self,
2388        _brep: &[u8],
2389        _plane: &ProfilePlane,
2390        _near: Option<[f64; 3]>,
2391    ) -> KernelResult<Vec<SectionRun>> {
2392        Err(KernelError::Unsupported("section".into()))
2393    }
2394
2395    /// The boundary loops of the face of `brep` nearest `near`, the outer
2396    /// one first, each edge in loop order, in the shape's own frame.
2397    fn face_loops(&self, _brep: &[u8], _near: [f64; 3]) -> KernelResult<Vec<Vec<LoopEdge>>> {
2398        Err(KernelError::Unsupported("face loops".into()))
2399    }
2400
2401    /// The curves of a DXF drawing, given as its text.
2402    fn read_dxf(&self, _text: &str) -> KernelResult<Drawing2d> {
2403        Err(KernelError::Unsupported("reading DXF".into()))
2404    }
2405
2406    /// The regions `profile` encloses, meshed where they stand in its
2407    /// plane: what a feature swept from it takes, holes left open.
2408    fn profile_mesh(&self, _profile: &Profile) -> KernelResult<TriMesh> {
2409        Err(KernelError::Unsupported("profile mesh".into()))
2410    }
2411
2412    /// The medial axis of each region of `profile`, held to `tolerance`
2413    /// (mm), in the profile plane's own 2D coordinates.
2414    fn medial_axis(&self, _profile: &Profile, _tolerance: f64) -> KernelResult<Vec<MedialRegion>> {
2415        Err(KernelError::Unsupported("medial axis".into()))
2416    }
2417
2418    /// The centre line of the solid in `brep` from the face `from` names to
2419    /// the face `to` names, held to `tolerance` (mm). Everything is in the
2420    /// shape's own frame.
2421    fn centre_line(
2422        &self,
2423        _brep: &[u8],
2424        _from: &FaceProbe,
2425        _to: &FaceProbe,
2426        _tolerance: f64,
2427    ) -> KernelResult<CentreLine> {
2428        Err(KernelError::Unsupported("centre line".into()))
2429    }
2430
2431    /// What the shape in `brep` answers to `probe`, in the shape's own
2432    /// frame.
2433    fn probe(&self, _brep: &[u8], _probe: &ShapeProbe) -> KernelResult<ProbeAnswer> {
2434        Err(KernelError::Unsupported("probing a shape".into()))
2435    }
2436}
2437
2438/// Standardized error type for kernel interactions.
2439#[derive(Debug, Error)]
2440pub enum KernelError {
2441    #[error("kernel initialization failed: {0}")]
2442    Initialization(String),
2443    #[error("kernel not initialized")]
2444    NotInitialized,
2445    #[error("operation unsupported: {0}")]
2446    Unsupported(String),
2447    #[error("invalid kernel input: {0}")]
2448    InvalidInput(String),
2449    #[error("import failed: {0}")]
2450    Import(String),
2451    #[error(transparent)]
2452    Other(#[from] anyhow::Error),
2453}
2454
2455#[cfg(test)]
2456mod tests {
2457    use super::*;
2458
2459    fn pipe_json(frame: &str) -> String {
2460        let plane = r#"{"origin":[0,0,0],"x_axis":[1,0,0],"y_axis":[0,1,0],"normal":[0,0,1]}"#;
2461        let profile = format!(
2462            r#"{{"plane":{plane},"wires":[{{"segments":[{{"Circle":{{"center":[0,0],"radius":1}}}}]}}]}}"#
2463        );
2464        format!(r#"{{"Pipe":{{"profile":{profile},"spine":{profile},{frame}"op":"NewSolid"}}}}"#)
2465    }
2466
2467    fn frame_of(json: &str) -> PipeFrame {
2468        match serde_json::from_str::<SolidOp>(json).unwrap() {
2469            SolidOp::Pipe { frame, .. } => frame,
2470            other => panic!("not a pipe: {other:?}"),
2471        }
2472    }
2473
2474    #[test]
2475    fn a_pipe_written_with_the_frenet_flag_reads_as_its_frame() {
2476        assert_eq!(frame_of(&pipe_json(r#""frenet":true,"#)), PipeFrame::Frenet);
2477        assert_eq!(
2478            frame_of(&pipe_json(r#""frenet":false,"#)),
2479            PipeFrame::RotationMinimizing
2480        );
2481        assert_eq!(frame_of(&pipe_json("")), PipeFrame::RotationMinimizing);
2482    }
2483
2484    #[test]
2485    fn a_pipe_frame_round_trips() {
2486        let frame = PipeFrame::Binormal {
2487            direction: [0.0, 0.0, 1.0],
2488        };
2489        let text = serde_json::to_string(&frame).unwrap();
2490        assert_eq!(frame_of(&pipe_json(&format!(r#""frame":{text},"#))), frame);
2491    }
2492}