Skip to main content

kernel_api/
solid_op.rs

1//! Solid operations as plain data: profiles, sweeps, primitives, dress-ups,
2//! patterns, surface steps and the op enum a chain runs.
3
4use serde::{Deserialize, Serialize};
5
6use crate::*;
7
8/// One segment of a closed 2D profile wire, in sketch-plane coordinates
9/// (millimetres). Arcs are encoded as three on-curve points so consumers
10/// never have to agree on a winding convention.
11#[cfg_attr(not(feature = "exhaustive"), non_exhaustive)]
12#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
13pub enum ProfileSegment {
14    Line {
15        start: [f64; 2],
16        end: [f64; 2],
17    },
18    /// Circular arc through three points (start → mid → end).
19    Arc {
20        start: [f64; 2],
21        mid: [f64; 2],
22        end: [f64; 2],
23    },
24    Circle {
25        center: [f64; 2],
26        radius: f64,
27    },
28    /// Full ellipse. `major` is the vector from the center to a major-axis
29    /// vertex; the minor radius is `|major| * ratio` with `ratio` in (0, 1].
30    Ellipse {
31        center: [f64; 2],
32        major: [f64; 2],
33        ratio: f64,
34    },
35    /// Elliptical arc between two parameter angles (radians, counter-clockwise
36    /// in the ellipse frame where the major axis is at parameter 0).
37    EllipseArc {
38        center: [f64; 2],
39        major: [f64; 2],
40        ratio: f64,
41        start_param: f64,
42        end_param: f64,
43    },
44    /// Cubic B-spline through the given control points. A periodic spline
45    /// closes smoothly on itself; an open one runs first → last control point.
46    BSpline {
47        control_points: Vec<[f64; 2]>,
48        periodic: bool,
49    },
50    /// A B-spline of any degree over its own knots, rational when it has
51    /// weights: an exact conic arc, a spline drawn through points. An open
52    /// one's knots are clamped (`control points + degree + 1` of them), so
53    /// it runs first → last control point; a periodic one is a uniform ring
54    /// over its control points closing smoothly on itself, and its knots
55    /// are not used.
56    Nurbs {
57        degree: u32,
58        knots: Vec<f64>,
59        control_points: Vec<[f64; 2]>,
60        /// One per control point; empty when every weight is one.
61        #[serde(default, skip_serializing_if = "Vec::is_empty")]
62        weights: Vec<f64>,
63        #[serde(default)]
64        periodic: bool,
65    },
66}
67
68/// What a [`SolidOp::PipeThrough`] runs along.
69#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
70pub enum PipePath {
71    /// A sketch's wire.
72    Profile(Profile),
73    /// Edges of the running solid, joined end to end.
74    Edges(Vec<EdgeProbe>),
75    /// Edges of another solid (a native-format snapshot, moved by
76    /// `transform` into the body's frame), joined end to end; the probes
77    /// are in the body's frame.
78    EdgesOf {
79        shape: Vec<u8>,
80        transform: Option<Box<[[f64; 4]; 4]>>,
81        edges: Vec<EdgeProbe>,
82    },
83}
84
85/// One section of a [`SolidOp::LoftThrough`].
86#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
87pub enum LoftSection {
88    Profile(Profile),
89    /// The flat face of the running solid the probe finds, by its outer
90    /// and inner boundaries.
91    Face(FaceProbe),
92    /// A point the loft closes to, in the body's frame.
93    Point([f64; 3]),
94}
95
96/// A closed loop of profile segments. Consecutive segments share endpoints;
97/// a single `Circle` segment is a wire by itself.
98#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
99pub struct ProfileWire {
100    pub segments: Vec<ProfileSegment>,
101    /// The name of each segment, one per segment, by what it was drawn from
102    /// (a sketch element): the faces a feature sweeps from it are named by
103    /// it, so they keep their names while dimensions change. Empty, or a
104    /// zero, where a segment has no such name.
105    #[serde(default, skip_serializing_if = "Vec::is_empty")]
106    pub names: Vec<TopoName>,
107}
108
109impl ProfileWire {
110    /// A wire of `segments` with no names.
111    pub fn new(segments: Vec<ProfileSegment>) -> Self {
112        Self {
113            segments,
114            names: Vec::new(),
115        }
116    }
117
118    /// The name of segment `index`, when it has one.
119    pub fn name_of(&self, index: usize) -> Option<TopoName> {
120        self.names.get(index).copied().filter(|n| *n != 0)
121    }
122}
123
124/// The plane a profile lives on, in world coordinates (millimetres).
125#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
126pub struct ProfilePlane {
127    pub origin: [f64; 3],
128    pub x_axis: [f64; 3],
129    pub y_axis: [f64; 3],
130    pub normal: [f64; 3],
131}
132
133/// The XY plane through the origin.
134impl Default for ProfilePlane {
135    fn default() -> Self {
136        Self {
137            origin: [0.0; 3],
138            x_axis: [1.0, 0.0, 0.0],
139            y_axis: [0.0, 1.0, 0.0],
140            normal: [0.0, 0.0, 1.0],
141        }
142    }
143}
144
145/// How an extrusion combines with the body's existing solid.
146#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
147pub enum BooleanOp {
148    /// Replace / start the body's solid (first feature).
149    NewSolid,
150    /// Union with the existing solid (Pad on an existing body).
151    Fuse,
152    /// Subtract from the existing solid (Pocket).
153    Cut,
154    /// Keep only what the existing solid and the tool share.
155    Common,
156}
157
158/// A set of closed wires on one plane. The largest-area wire is the outer
159/// boundary, the rest become holes.
160#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
161pub struct Profile {
162    pub plane: ProfilePlane,
163    pub wires: Vec<ProfileWire>,
164}
165
166/// Where a one-directional extrusion stops.
167#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
168pub enum ExtrudeTermination {
169    /// Fixed length in millimetres.
170    Blind { distance: f64 },
171    /// Extend well past the base solid's bounding box in this direction.
172    ThroughAll,
173    /// Stop on the given world-space plane, shifted by `offset` along its
174    /// normal (a picked planar face plus an offset-to-face value).
175    UpToPlane {
176        point: [f64; 3],
177        normal: [f64; 3],
178        offset: f64,
179    },
180    /// Stop on the base solid's face named `name`, else the one nearest
181    /// `point` (a picked face, where it was picked), exactly on its surface
182    /// whatever its shape, pushed `offset` out along its outward normal.
183    /// With no base solid, or no face of it there, the plane through
184    /// `point` square to `normal`.
185    UpToFace {
186        point: [f64; 3],
187        normal: [f64; 3],
188        offset: f64,
189        #[serde(default)]
190        name: TopoName,
191    },
192    /// Stop at the first face of the base solid hit along the extrusion
193    /// direction, on its surface.
194    ToFirst,
195    /// Stop at the last face of the base solid hit along the extrusion
196    /// direction, on its surface.
197    ToLast,
198    /// Stop on a set of the base solid's faces: every line of the sweep
199    /// ends at the first of them it meets, moved `offset` further along the
200    /// sweep (a negative offset stops short).
201    UpToShape { faces: Vec<FaceProbe>, offset: f64 },
202    /// Stop on a face of another shape: the face of `shape` (a native-format
203    /// snapshot, moved by `transform`, a rigid row-major 4×4 matrix, into
204    /// the body's frame) nearest `point`, exactly on its surface whatever
205    /// its shape, pushed `offset` out along its outward normal.
206    UpToFaceOf {
207        shape: Vec<u8>,
208        transform: Option<Box<[[f64; 4]; 4]>>,
209        point: [f64; 3],
210        offset: f64,
211    },
212    /// Stop on a set of faces as `UpToShape` does, some of them the base
213    /// solid's (`faces`) and some of other shapes (`others`, faces other
214    /// bodies lend this one). Needs no base solid when every face is
215    /// another shape's.
216    UpToShapeOf {
217        faces: Vec<FaceProbe>,
218        others: Vec<FacesOf>,
219        offset: f64,
220    },
221}
222
223/// Faces of another shape: the faces of `shape` (a native-format snapshot,
224/// moved by `transform`, a rigid row-major 4×4 matrix, into the body's
225/// frame) nearest each of `points`.
226#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
227pub struct FacesOf {
228    pub shape: Vec<u8>,
229    pub transform: Option<Box<[[f64; 4]; 4]>>,
230    pub points: Vec<[f64; 3]>,
231}
232
233/// Where a revolution stops turning.
234#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize, Deserialize)]
235pub enum RevolveTermination {
236    /// Through the sweep's own angles.
237    #[default]
238    Angle,
239    /// On the first face of the base solid the profile's centre meets as it
240    /// turns.
241    ToFirst,
242    /// On the last face of the base solid the profile's centre meets as it
243    /// turns.
244    ToLast,
245    /// On the base solid's face nearest the probe.
246    UpToFace(FaceProbe),
247}
248
249/// How a profile is swept into a solid.
250#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
251pub enum SweepKind {
252    /// Linear extrusion along `plane.normal` (or `direction` when set).
253    Extrude {
254        termination: ExtrudeTermination,
255        /// Independent termination for the opposite side of the sketch plane
256        /// (two-sided extrusion). `None` extrudes one side only.
257        second_side: Option<ExtrudeTermination>,
258        /// Extrude half the blind distance to each side of the sketch plane.
259        symmetric: bool,
260        /// Swap which side of the sketch plane is "forward".
261        reversed: bool,
262        /// Draft angle applied along the sweep; positive widens the far end.
263        taper_deg: f64,
264        /// Custom world-space sweep direction; `None` uses the plane normal.
265        direction: Option<[f64; 3]>,
266    },
267    /// Revolution about an axis lying IN the sketch plane, given in sketch
268    /// 2D coordinates (point + direction). `angle_deg` in (0, 360].
269    Revolve {
270        axis_origin: [f64; 2],
271        axis_dir: [f64; 2],
272        angle_deg: f64,
273        /// Independent sweep angle for the opposite rotation direction.
274        second_angle_deg: Option<f64>,
275        /// Center the sweep on the sketch plane (half the angle each way).
276        midplane: bool,
277        reversed: bool,
278        /// Where the turn stops; anything but `Angle` takes the angle from
279        /// what the profile meets and leaves the angles above unused.
280        #[serde(default)]
281        termination: RevolveTermination,
282    },
283    /// Sweep the profile along a helix whose axis lies in the sketch plane.
284    /// A cone angle moves every point away from the axis by tan(angle) of
285    /// every pitch it climbs.
286    Helix {
287        axis_origin: [f64; 2],
288        axis_dir: [f64; 2],
289        pitch: f64,
290        height: f64,
291        left_handed: bool,
292        cone_angle_deg: f64,
293        reversed: bool,
294        /// How many turns, when given: the pitch is then `height / turns`
295        /// and `pitch` is not read. A height of 0 with turns and growth is
296        /// a flat spiral.
297        #[serde(default)]
298        turns: Option<f64>,
299        /// How far every point moves away from the axis per turn, when
300        /// given, in place of `cone_angle_deg`.
301        #[serde(default)]
302        growth: Option<f64>,
303    },
304    /// Sweep the profile along a helix whose axis runs square to the sketch
305    /// plane through `axis_origin` (sketch 2D coordinates): every point of
306    /// the profile climbs its own helix about it, the profile staying
307    /// level. The rest reads as for `Helix`.
308    HelixNormal {
309        axis_origin: [f64; 2],
310        pitch: f64,
311        height: f64,
312        left_handed: bool,
313        cone_angle_deg: f64,
314        reversed: bool,
315        #[serde(default)]
316        turns: Option<f64>,
317        #[serde(default)]
318        growth: Option<f64>,
319    },
320}
321
322/// How a pipe's section turns as it runs down its path.
323#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
324pub enum PipeFrame {
325    /// Rotation-minimizing: the section neither twists nor kinks where the
326    /// path bends.
327    #[default]
328    RotationMinimizing,
329    /// The path's own curvature frame, turning with it.
330    Frenet,
331    /// The section turns about the path so that one direction of it keeps
332    /// pointing at a second path running beside the first.
333    Auxiliary { path: Profile },
334    /// The section keeps a fixed binormal: the world-space direction square
335    /// to the path that the section's frame holds all the way.
336    Binormal { direction: [f64; 3] },
337    /// The section keeps its orientation in space: carried along the path
338    /// without ever turning, as it is drawn.
339    Fixed,
340}
341
342impl PipeFrame {
343    /// The frame an older `frenet` flag named.
344    pub fn from_frenet(frenet: bool) -> Self {
345        if frenet {
346            PipeFrame::Frenet
347        } else {
348            PipeFrame::RotationMinimizing
349        }
350    }
351}
352
353/// Reads a [`PipeFrame`] or the `frenet` flag it stands in for.
354pub fn deserialize_pipe_frame<'de, D>(deserializer: D) -> Result<PipeFrame, D::Error>
355where
356    D: serde::Deserializer<'de>,
357{
358    #[derive(Deserialize)]
359    #[serde(untagged)]
360    enum Stored {
361        Flag(bool),
362        Frame(PipeFrame),
363    }
364    Ok(match Stored::deserialize(deserializer)? {
365        Stored::Flag(frenet) => PipeFrame::from_frenet(frenet),
366        Stored::Frame(frame) => frame,
367    })
368}
369
370/// How a pipe's section turns a sharp corner of its path.
371#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
372pub enum PipeCorner {
373    /// The section is carried into the corner and sheared onto the plane
374    /// bisecting it: the two legs meet on that mitre.
375    #[default]
376    Transformed,
377    /// Each leg runs on straight past the corner and the two are fused,
378    /// leaving the outside of the corner square.
379    Right,
380    /// The section turns about the corner, the outside of it rounded.
381    Round,
382}
383
384/// Parametric primitive shapes (dimensions in millimetres, angles degrees).
385#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
386pub enum PrimitiveKind {
387    Box {
388        length: f64,
389        width: f64,
390        height: f64,
391    },
392    Cylinder {
393        radius: f64,
394        height: f64,
395        angle_deg: f64,
396    },
397    Sphere {
398        radius: f64,
399        /// Latitude range and longitude sweep (three-angle parameterization).
400        angle1_deg: f64,
401        angle2_deg: f64,
402        angle3_deg: f64,
403    },
404    Cone {
405        radius1: f64,
406        radius2: f64,
407        height: f64,
408        angle_deg: f64,
409    },
410    Torus {
411        radius1: f64,
412        radius2: f64,
413        angle1_deg: f64,
414        angle2_deg: f64,
415        angle3_deg: f64,
416    },
417    /// An ellipsoid, cut as a sphere is: between two latitudes about its
418    /// third axis and through a sweep round it.
419    Ellipsoid {
420        radius1: f64,
421        radius2: f64,
422        radius3: f64,
423        #[serde(default = "south_pole")]
424        angle1_deg: f64,
425        #[serde(default = "north_pole")]
426        angle2_deg: f64,
427        #[serde(default = "full_turn")]
428        angle3_deg: f64,
429    },
430    /// A regular prism, its top shifted by the skew angles: leaning that
431    /// far from its axis toward its x and its y.
432    Prism {
433        sides: u32,
434        circumradius: f64,
435        height: f64,
436        #[serde(default)]
437        skew_x_deg: f64,
438        #[serde(default)]
439        skew_y_deg: f64,
440    },
441    /// A hollow cylinder: a wall between the radii `inner` and `outer`
442    /// about its axis, `height` tall. The inner radius is above zero and
443    /// below the outer.
444    Tube { outer: f64, inner: f64, height: f64 },
445    /// Box with an independently sized top rectangle (zero top spans give a
446    /// pyramid). Spans are along local X (`x2*`) and Z (`z2*`) at height Y.
447    Wedge {
448        xmin: f64,
449        xmax: f64,
450        ymin: f64,
451        ymax: f64,
452        zmin: f64,
453        zmax: f64,
454        x2min: f64,
455        x2max: f64,
456        z2min: f64,
457        z2max: f64,
458    },
459}
460
461fn south_pole() -> f64 {
462    -90.0
463}
464
465fn north_pole() -> f64 {
466    90.0
467}
468
469fn full_turn() -> f64 {
470    360.0
471}
472
473/// A right-handed placement frame in world coordinates (millimetres).
474#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
475pub struct Placement {
476    pub origin: [f64; 3],
477    pub x_axis: [f64; 3],
478    pub z_axis: [f64; 3],
479}
480
481impl Default for Placement {
482    fn default() -> Self {
483        Self {
484            origin: [0.0; 3],
485            x_axis: [1.0, 0.0, 0.0],
486            z_axis: [0.0, 0.0, 1.0],
487        }
488    }
489}
490
491/// Which edges of the current solid a dress-up applies to. Edges are
492/// identified geometrically: by a face they border (sample point on the
493/// face) or by a point near the edge itself.
494#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
495pub enum EdgeSelection {
496    All,
497    OfFaces(Vec<[f64; 3]>),
498    /// The edges bordering the picked faces, each found by its name when
499    /// it has one.
500    OfPickedFaces(Vec<FaceProbe>),
501    Near(Vec<[f64; 3]>),
502    /// Edges picked one by one: each the nearest edge to its point that
503    /// runs along its direction there.
504    Picked(Vec<EdgeProbe>),
505}
506
507/// A picked edge, as a point beside it and the way it runs there, and the
508/// names of the two faces it runs between. A rebuild finds the edge
509/// between faces of those names, the point choosing among several; without
510/// names, the nearest edge. A zero direction leaves the way open.
511#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
512pub struct EdgeProbe {
513    pub point: [f64; 3],
514    pub direction: [f64; 3],
515    #[serde(default)]
516    pub faces: [TopoName; 2],
517}
518
519/// How a thickness's walls meet across an edge of the solid.
520#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
521pub enum ThicknessJoin {
522    /// The walls run on until they meet: sharp corners.
523    #[default]
524    Intersection,
525    /// The walls round about the edge, the wall thickness its radius.
526    Arc,
527}
528
529impl ThicknessJoin {
530    pub const ALL: [ThicknessJoin; 2] = [ThicknessJoin::Intersection, ThicknessJoin::Arc];
531
532    pub fn label(&self) -> &'static str {
533        match self {
534            ThicknessJoin::Intersection => "Intersection",
535            ThicknessJoin::Arc => "Arc",
536        }
537    }
538}
539
540/// Chamfer sizing, mirroring the three standard input styles.
541#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
542pub enum ChamferSpec {
543    EqualDistance { distance: f64 },
544    TwoDistances { distance1: f64, distance2: f64 },
545    DistanceAngle { distance: f64, angle_deg: f64 },
546}
547
548/// Boolean between the running solid and an external tool solid.
549#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
550pub enum BoolKind {
551    Fuse,
552    Cut,
553    Common,
554}
555
556/// One step in a body's build history. Shape-producing steps (`Sweep`,
557/// `Loft`, `Pipe`, `Primitive`) carry a [`BooleanOp`]; the remaining steps
558/// modify or combine the running solid directly.
559///
560/// A package builds these, so a variant keeps its fields for as long as
561/// the contract's minor version holds: a new option comes as a new
562/// variant, or as a new struct that derives `Default`.
563#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
564pub enum SolidOp {
565    /// Start the chain from a snapshot of another solid, in the native
566    /// format `SolidBuildResult::brep_blob` carries. Only ever the first op.
567    Shape { brep: Vec<u8> },
568    Sweep {
569        profile: Profile,
570        kind: SweepKind,
571        op: BooleanOp,
572    },
573    /// Extrude a flat face of the running solid: its outer and inner
574    /// boundaries are the profile and its outward normal the sketch
575    /// normal. `kind` is an `Extrude`.
576    SweepFace {
577        face: FaceProbe,
578        kind: SweepKind,
579        op: BooleanOp,
580    },
581    /// Extrude a flat face of another shape (native-format `shape`, moved by
582    /// `transform` into this body's frame): the face of it at `point`, a
583    /// face another body lends this one.
584    SweepFaceOf {
585        shape: Vec<u8>,
586        transform: Option<Box<[[f64; 4]; 4]>>,
587        point: [f64; 3],
588        kind: SweepKind,
589        op: BooleanOp,
590    },
591    /// Revolve a profile until it meets a face of another shape
592    /// (native-format `shape`, moved by `transform` into this body's frame):
593    /// the face of it nearest `point`, a face another body lends this one.
594    /// `kind` is a `Revolve`, whose own termination is not read.
595    RevolveToFaceOf {
596        profile: Profile,
597        kind: SweepKind,
598        shape: Vec<u8>,
599        transform: Option<Box<[[f64; 4]; 4]>>,
600        point: [f64; 3],
601        op: BooleanOp,
602    },
603    /// Skin through two or more sections (in order), each a profile, a
604    /// flat face of the running solid (its boundary) or a point, which
605    /// only the first or last may be.
606    LoftThrough {
607        sections: Vec<LoftSection>,
608        ruled: bool,
609        closed: bool,
610        op: BooleanOp,
611    },
612    /// Skin through two or more section profiles (in order).
613    Loft {
614        sections: Vec<Profile>,
615        ruled: bool,
616        closed: bool,
617        op: BooleanOp,
618    },
619    /// Sweep a profile along an open or closed spine wire from another
620    /// sketch, the section turning as `frame` says and turning its corners
621    /// as `corner` says. With `sections`, the section changes shape down
622    /// the path, passing through each of them where it crosses the path,
623    /// in order, the profile first.
624    Pipe {
625        profile: Profile,
626        spine: Profile,
627        #[serde(default, alias = "frenet", deserialize_with = "deserialize_pipe_frame")]
628        frame: PipeFrame,
629        #[serde(default)]
630        corner: PipeCorner,
631        #[serde(default)]
632        sections: Vec<Profile>,
633        op: BooleanOp,
634    },
635    /// A pipe whose profile may be a flat face of the running solid, whose
636    /// path may be edges of a solid, and whose last section may be a point
637    /// it closes to; the rest reads as for `Pipe`.
638    PipeThrough {
639        profile: LoftSection,
640        path: PipePath,
641        #[serde(default)]
642        frame: PipeFrame,
643        #[serde(default)]
644        corner: PipeCorner,
645        #[serde(default)]
646        sections: Vec<LoftSection>,
647        op: BooleanOp,
648    },
649    Primitive {
650        kind: PrimitiveKind,
651        placement: Placement,
652        op: BooleanOp,
653    },
654    /// Round the selected edges; with `follow_tangent`, every edge meeting
655    /// one of them tangentially joins the selection, and so on along the
656    /// chain.
657    Fillet {
658        radius: f64,
659        edges: EdgeSelection,
660        #[serde(default)]
661        follow_tangent: bool,
662    },
663    /// Round between two faces of the running solid, which need share no
664    /// edge: the ball rolling between them, its round filling or taking off
665    /// what lies between it and the faces' meeting (a step across a groove).
666    BlendFaces { radius: f64, faces: [FaceProbe; 2] },
667    /// Bevel the selected edges, taking tangent chains as a fillet does.
668    Chamfer {
669        spec: ChamferSpec,
670        flip: bool,
671        edges: EdgeSelection,
672        #[serde(default)]
673        follow_tangent: bool,
674    },
675    /// Tilt the selected faces by `angle_deg` about their intersection with
676    /// the neutral plane.
677    Draft {
678        angle_deg: f64,
679        neutral_point: [f64; 3],
680        neutral_normal: [f64; 3],
681        pull_dir: Option<[f64; 3]>,
682        faces: Vec<[f64; 3]>,
683        /// The name of each face, one per point, found by name first; empty
684        /// or zero where a face has none.
685        #[serde(default, skip_serializing_if = "Vec::is_empty")]
686        face_names: Vec<TopoName>,
687    },
688    /// Merge adjacent faces of the solid that lie on one plane: the split
689    /// a fuse or cut leaves where two pieces meet flush.
690    Refine,
691    /// Offset faces of the running solid along their outward normals by
692    /// `distance` (negative into the material), the faces around them
693    /// following on their own surfaces.
694    OffsetFaces {
695        faces: Vec<[f64; 3]>,
696        #[serde(default, skip_serializing_if = "Vec::is_empty")]
697        face_names: Vec<TopoName>,
698        distance: f64,
699    },
700    /// Move faces of the running solid rigidly by `transform` (row-major,
701    /// a translation or a rotation), the faces around them following.
702    MoveFaces {
703        faces: Vec<[f64; 3]>,
704        #[serde(default, skip_serializing_if = "Vec::is_empty")]
705        face_names: Vec<TopoName>,
706        transform: [[f64; 4]; 4],
707    },
708    /// Remove faces of the running solid and close the openings from the
709    /// neighbouring faces' own geometry: a hole, a boss or a fillet taken
710    /// away. Faces as points on them, named where they have names.
711    RemoveFaces {
712        faces: Vec<[f64; 3]>,
713        #[serde(default, skip_serializing_if = "Vec::is_empty")]
714        face_names: Vec<TopoName>,
715    },
716    /// Hollow the solid, removing the faces sampled by `open_faces`.
717    Thickness {
718        value: f64,
719        open_faces: Vec<[f64; 3]>,
720        /// The name of each open face, one per point; empty or zero where
721        /// a face has none.
722        #[serde(default, skip_serializing_if = "Vec::is_empty")]
723        open_face_names: Vec<TopoName>,
724        inward: bool,
725        /// How the walls meet where the solid's faces meet.
726        #[serde(default)]
727        join: ThicknessJoin,
728        /// The walls stand on both sides of the solid's faces, `value` each
729        /// way, rather than on the one `inward` says.
730        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
731        both_sides: bool,
732    },
733    /// Re-apply earlier steps' tool solids (or the whole current solid when
734    /// `originals` is empty) under each transform, fusing additive tools and
735    /// cutting subtractive ones. `originals` holds chain indices of earlier
736    /// shape-producing steps.
737    Transform {
738        transforms: Vec<[[f64; 4]; 4]>,
739        originals: Vec<usize>,
740    },
741    /// [`SolidOp::Transform`] with the originals themselves left out: the
742    /// steps `originals` names build their tools without adding or cutting
743    /// them, so only the transformed copies go in. With `originals` empty
744    /// the running solid gives way to its copies.
745    TransformCopies {
746        transforms: Vec<[[f64; 4]; 4]>,
747        originals: Vec<usize>,
748    },
749    /// [`SolidOp::Transform`] whose transforms the chain works out from
750    /// `steps` where the op stands, so a step may follow an edge of the
751    /// solid as it is there. Occurrence 0 is the original; with it among
752    /// `skipped`, only the copies go in, as [`SolidOp::TransformCopies`].
753    Pattern {
754        steps: Vec<PatternStep>,
755        originals: Vec<usize>,
756        /// Occurrences left out, by index: 0 the original, then each copy
757        /// in the order the steps make them.
758        #[serde(default, skip_serializing_if = "Vec::is_empty")]
759        skipped: Vec<u32>,
760    },
761    /// Boolean against an external solid (another body's shape snapshot,
762    /// ogeom native-format text bytes).
763    Boolean {
764        tool_brep: Vec<u8>,
765        kind: BoolKind,
766        /// Where the tool sits in this chain's frame, when the two bodies
767        /// are placed differently: a rigid row-major 4×4 matrix.
768        #[serde(default)]
769        tool_transform: Option<[[f64; 4]; 4]>,
770    },
771    /// A surface step: a sheet added to the body, or the body's sheets
772    /// joined, trimmed or mirrored.
773    Surface(SurfaceOp),
774    /// `op` with its booleans run at a stated tolerance: geometry within
775    /// `tolerance` mm of touching counts as touching, so faces that nearly
776    /// meet are joined rather than left with a gap or a sliver between
777    /// them. The op keeps its place in the chain, as a pattern's
778    /// `originals` count it.
779    WithTolerance { tolerance: f64, op: Box<SolidOp> },
780    /// A sketch carried along its plane's normal onto faces of the running
781    /// solid, each face split along the curves where they land; `mode`
782    /// says whether the regions the curves enclose then stand out of the
783    /// faces or sink into them by `height`.
784    Project {
785        profile: Profile,
786        faces: Vec<FaceProbe>,
787        mode: ProjectMode,
788        height: f64,
789    },
790    /// A sketch wrapped onto the curved surface its `faces` lie on: the
791    /// sketch's middle lands where a straight projection along its plane's
792    /// normal puts it, and the rest is laid onto the surface from there.
793    /// A cylinder or cone is unrolled, every length kept, the way across
794    /// the axis turning about it and the way along the axis following it;
795    /// any other surface takes it as a flat sheet laid by geodesic polar
796    /// coordinates, lengths out from the middle kept and lengths across
797    /// them stretched by the surface's curvature. Otherwise as
798    /// [`SolidOp::Project`].
799    Wrap {
800        profile: Profile,
801        faces: Vec<FaceProbe>,
802        mode: ProjectMode,
803        height: f64,
804    },
805    /// Keep the running solid's material on one side of a plane: the side
806    /// `normal` points to from `origin`. A plane that leaves nothing on
807    /// that side fails, saying so.
808    HalfSpace { origin: [f64; 3], normal: [f64; 3] },
809    /// Grow the running solid by `distance` everywhere along its faces'
810    /// outward normals, or shrink it with a negative one: every face moved
811    /// that far and the faces around it following, its topology kept.
812    OffsetSolid { distance: f64 },
813    /// Scale the running solid by `factors` along the body's X, Y and Z
814    /// about `centre`, or about the middle of its bounding box when that
815    /// is `None`. Equal factors keep its surfaces' kinds; unequal ones
816    /// restate them as the kernel's general transform does.
817    Scale {
818        factors: [f64; 3],
819        centre: Option<[f64; 3]>,
820    },
821    /// Keep one piece of the running shape: of its solids, the one
822    /// nearest `near`, the others left out.
823    KeepPiece { near: [f64; 3] },
824}
825
826/// What a [`SolidOp::Project`] makes of the faces a sketch lands on.
827#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
828pub enum ProjectMode {
829    /// The faces split along the sketch's curves, the solid's shape
830    /// unchanged: lines later features and face colours can use.
831    #[default]
832    Split,
833    /// The regions the curves enclose raised out of the faces.
834    Emboss,
835    /// The regions the curves enclose sunk into the faces.
836    Deboss,
837}
838
839impl ProjectMode {
840    pub const ALL: [ProjectMode; 3] =
841        [ProjectMode::Split, ProjectMode::Emboss, ProjectMode::Deboss];
842
843    pub fn label(&self) -> &'static str {
844        match self {
845            ProjectMode::Split => "Split lines",
846            ProjectMode::Emboss => "Emboss",
847            ProjectMode::Deboss => "Deboss",
848        }
849    }
850}
851
852/// A curve a surface is built from.
853#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
854pub enum CurveSource {
855    /// A chain of a sketch's curves, open or closed, on its plane.
856    Sketch {
857        plane: ProfilePlane,
858        wire: ProfileWire,
859    },
860    /// An edge of the body's own shape as it stands where the step comes,
861    /// found as a fillet's picked edges are.
862    Edge(EdgeProbe),
863    /// An edge of another body's shape: `brep` is that body's snapshot,
864    /// `edge` finds the edge in its own frame, and `transform` (a rigid
865    /// row-major 4×4 matrix) carries it to where it sits in this chain's
866    /// frame, when the two bodies are placed differently.
867    BodyEdge {
868        brep: Vec<u8>,
869        edge: EdgeProbe,
870        #[serde(default)]
871        transform: Option<Box<[[f64; 4]; 4]>>,
872    },
873}
874
875/// How a surface meets the faces beside it across a shared edge.
876#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
877pub enum Continuity {
878    /// Touching: no gap, a crease allowed.
879    #[default]
880    G0,
881    /// Tangent: no crease.
882    G1,
883    /// Curvature continuous: no change in how sharply it bends.
884    G2,
885}
886
887/// The steps of surface modelling. A constructive step (every one but
888/// `Sew`, `TrimByPlane` and `Mirror`) adds its sheet to the body beside
889/// what is there; the rest act on all of the body's shape.
890#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
891pub enum SurfaceOp {
892    /// Each curve swept straight along `direction` by `length`, both ways
893    /// by half of it when `symmetric`.
894    Extrude {
895        curves: Vec<CurveSource>,
896        direction: [f64; 3],
897        length: f64,
898        #[serde(default)]
899        symmetric: bool,
900    },
901    /// Each curve turned by `angle_deg` about the axis through `origin`
902    /// along `axis`.
903    Revolve {
904        curves: Vec<CurveSource>,
905        origin: [f64; 3],
906        axis: [f64; 3],
907        angle_deg: f64,
908    },
909    /// The flat face closed planar loops bound, a loop inside another a
910    /// hole in it.
911    PlanarFill { curves: Vec<CurveSource> },
912    /// The surface curves meeting end to end bound, meeting the faces the
913    /// boundary edges belong to with `continuity`.
914    Fill {
915        boundary: Vec<CurveSource>,
916        #[serde(default)]
917        continuity: Continuity,
918    },
919    /// The surface of straight lines between two curves, end to end.
920    Ruled {
921        first: CurveSource,
922        second: CurveSource,
923    },
924    /// A surface through section curves in order, closing back to the first
925    /// when `closed`.
926    Loft {
927        sections: Vec<CurveSource>,
928        #[serde(default)]
929        closed: bool,
930    },
931    /// A profile curve swept along a path.
932    Sweep {
933        profile: Vec<CurveSource>,
934        path: Vec<CurveSource>,
935        #[serde(default)]
936        frame: PipeFrame,
937    },
938    /// A surface through section curves in order that also follows guide
939    /// curves, each crossing every section once: one face.
940    GuidedLoft {
941        sections: Vec<CurveSource>,
942        guides: Vec<CurveSource>,
943    },
944    /// A profile running from the first rail's start to the second's,
945    /// swept along both: at each point along them it is turned and scaled
946    /// so its ends ride the rails.
947    SweepTwoRails {
948        profile: Vec<CurveSource>,
949        first_rail: Vec<CurveSource>,
950        second_rail: Vec<CurveSource>,
951    },
952    /// Faces carried off along their normals by `distance`, as new faces.
953    Offset {
954        faces: Vec<FaceProbe>,
955        distance: f64,
956    },
957    /// Faces carried past picked edges of their boundary by `length`.
958    Extend {
959        edges: Vec<EdgeProbe>,
960        length: f64,
961        #[serde(default)]
962        continuity: Continuity,
963    },
964    /// A surface bridging two edges, meeting each edge's face with
965    /// `continuity`.
966    Blend {
967        first: EdgeProbe,
968        second: EdgeProbe,
969        #[serde(default)]
970        continuity: Continuity,
971    },
972    /// Picked faces split along curves projected onto them.
973    Split {
974        faces: Vec<FaceProbe>,
975        curves: Vec<CurveSource>,
976    },
977    /// The body's faces joined where their edges meet, or come within
978    /// `gap` of each other (0 for exactly); a shell that closes becomes a
979    /// solid.
980    Sew {
981        #[serde(default)]
982        gap: f64,
983    },
984    /// A round of `radius` along picked edges where two faces of a sheet
985    /// meet.
986    Fillet { edges: Vec<EdgeProbe>, radius: f64 },
987    /// A round of `radius` between two faces of the body that need share
988    /// no edge, such as two separate surfaces, each cut back to where it
989    /// meets the round. The ball rolls on the side each face's normal
990    /// points to, on the other where `flip` says so.
991    FilletFaces {
992        first: FaceProbe,
993        second: FaceProbe,
994        radius: f64,
995        #[serde(default)]
996        flip: [bool; 2],
997    },
998    /// The body's sheets given `thickness` along their normals (both ways
999    /// by half when `both_sides`): a solid.
1000    Thicken {
1001        thickness: f64,
1002        #[serde(default)]
1003        both_sides: bool,
1004    },
1005    /// The body's sheets cut by the plane through `origin`, the side
1006    /// `normal` points to kept.
1007    TrimByPlane { origin: [f64; 3], normal: [f64; 3] },
1008    /// The body's shape and its reflection in the plane through `origin`
1009    /// square to `normal`.
1010    Mirror { origin: [f64; 3], normal: [f64; 3] },
1011    /// The body's sheets cut by each other, the faces lying on `scan`
1012    /// kept (at least `share` of each face's area within `tolerance` of
1013    /// it) and sewn: a closed shell becomes a solid. The scan's
1014    /// triangles, `scan` vertices taken three by three from `triangles`,
1015    /// are in the body's frame.
1016    TrimByScan {
1017        scan: Vec<[f32; 3]>,
1018        triangles: Vec<u32>,
1019        tolerance: f64,
1020        share: f64,
1021    },
1022    /// A free-form (B-spline) sheet fitted to scattered `points`, such as
1023    /// a region of a scan, within `tolerance` of them where it can.
1024    FitScattered {
1025        points: Vec<[f64; 3]>,
1026        tolerance: f64,
1027    },
1028    /// A network of B-spline patches fitted to `points` at once, each
1029    /// patch bounded by curves of the network and meeting its neighbours
1030    /// across them without a gap, tangent unless the curve is a crease.
1031    /// The network's curves are `curves`, one chain each, then
1032    /// `polylines`; a patch names its sides in order round it as curve
1033    /// numbers from 1, negative where the curve runs against the walk and 0
1034    /// for a side shrunk to a point.
1035    FitNetwork {
1036        curves: Vec<CurveSource>,
1037        polylines: Vec<Vec<[f64; 3]>>,
1038        #[serde(default)]
1039        patches: Vec<[i32; 4]>,
1040        /// Additional patches with each side a chain in walking order.
1041        /// An empty side is shrunk to a point; chain entries are nonzero
1042        /// signed curve numbers, as in `patches`.
1043        #[serde(default)]
1044        chained: Vec<[Vec<i32>; 4]>,
1045        /// Parameter-correction passes after refinement.
1046        #[serde(default)]
1047        corrections: u32,
1048        points: Vec<[f64; 3]>,
1049        tolerance: f64,
1050        smoothing: f64,
1051        /// The curves, numbered from 1, the patches meet across creased.
1052        creases: Vec<u32>,
1053    },
1054}
1055
1056impl SurfaceOp {
1057    /// Whether the step makes a new sheet (and so may begin a chain).
1058    pub fn constructs(&self) -> bool {
1059        !matches!(
1060            self,
1061            SurfaceOp::Sew { .. }
1062                | SurfaceOp::Fillet { .. }
1063                | SurfaceOp::FilletFaces { .. }
1064                | SurfaceOp::Thicken { .. }
1065                | SurfaceOp::TrimByPlane { .. }
1066                | SurfaceOp::Mirror { .. }
1067                | SurfaceOp::Split { .. }
1068                | SurfaceOp::Extend { .. }
1069                | SurfaceOp::TrimByScan { .. }
1070        )
1071    }
1072}
1073
1074/// One step of a [`SolidOp::Pattern`]: each applies to every occurrence of
1075/// the steps before it, the original among them, which stands first.
1076#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1077pub enum PatternStep {
1078    /// A copy under each transform (rigid or not, row-major), the
1079    /// original, untransformed, left out.
1080    Transforms(Vec<[[f64; 4]; 4]>),
1081    /// Copies along a path.
1082    Path(PathLayout),
1083}
1084
1085/// The path a [`PathLayout`] runs along, in the chain's frame.
1086#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1087pub enum PatternPath {
1088    /// A chain of curves on a plane, walked from its first segment's
1089    /// start.
1090    Wire {
1091        plane: ProfilePlane,
1092        wire: ProfileWire,
1093    },
1094    /// The edge of the solid, where the step stands, that the probe finds,
1095    /// walked from its curve's start.
1096    Edge(EdgeProbe),
1097}
1098
1099/// Occurrences at stations along a path by arc length, the original at
1100/// the first: occurrence k is moved from where the first station stands
1101/// to where the k-th does, turned as the path turns between them when
1102/// `align`.
1103#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1104pub struct PathLayout {
1105    pub path: PatternPath,
1106    /// Occurrences, the original counted.
1107    pub count: u32,
1108    /// Millimetres between neighbours along the path; `None` spreads them
1109    /// over the whole of it, evenly round it when it closes.
1110    #[serde(default, skip_serializing_if = "Option::is_none")]
1111    pub spacing: Option<f64>,
1112    /// Walk the path from its end.
1113    #[serde(default)]
1114    pub reversed: bool,
1115    /// Turn each copy as the path's direction turns from the first
1116    /// station to its own, carried along the path without twisting.
1117    #[serde(default)]
1118    pub align: bool,
1119}
1120
1121impl SolidOp {
1122    /// The op itself, out of any [`SolidOp::WithTolerance`] around it.
1123    pub fn inner(&self) -> &SolidOp {
1124        match self {
1125            SolidOp::WithTolerance { op, .. } => op.inner(),
1126            op => op,
1127        }
1128    }
1129
1130    /// The tolerance the op's booleans run at, when one is stated: the
1131    /// outermost [`SolidOp::WithTolerance`]'s.
1132    pub fn boolean_tolerance(&self) -> Option<f64> {
1133        match self {
1134            SolidOp::WithTolerance { tolerance, .. } => Some(*tolerance),
1135            _ => None,
1136        }
1137    }
1138
1139    /// The op with its booleans run at `tolerance`, or as it is with none.
1140    pub fn with_boolean_tolerance(self, tolerance: Option<f64>) -> SolidOp {
1141        match tolerance {
1142            Some(tolerance) => SolidOp::WithTolerance {
1143                tolerance,
1144                op: Box::new(self),
1145            },
1146            None => self,
1147        }
1148    }
1149
1150    /// Whether the step makes a shape of its own, so a chain may begin with
1151    /// it: a new solid, or a surface step that adds a sheet.
1152    pub fn starts_shape(&self) -> bool {
1153        match self.inner() {
1154            SolidOp::Surface(op) => op.constructs(),
1155            _ => self.boolean_op() == Some(BooleanOp::NewSolid),
1156        }
1157    }
1158
1159    /// The boolean role of a shape-producing step; `None` for modifiers.
1160    pub fn boolean_op(&self) -> Option<BooleanOp> {
1161        match self.inner() {
1162            SolidOp::Sweep { op, .. }
1163            | SolidOp::SweepFace { op, .. }
1164            | SolidOp::SweepFaceOf { op, .. }
1165            | SolidOp::RevolveToFaceOf { op, .. }
1166            | SolidOp::Loft { op, .. }
1167            | SolidOp::LoftThrough { op, .. }
1168            | SolidOp::PipeThrough { op, .. }
1169            | SolidOp::Pipe { op, .. }
1170            | SolidOp::Primitive { op, .. } => Some(*op),
1171            // A snapshot is a solid in itself: it begins a chain.
1172            SolidOp::Shape { .. } => Some(BooleanOp::NewSolid),
1173            _ => None,
1174        }
1175    }
1176}