Skip to main content

kernel_api/
fit.rs

1//! Fitting and measuring: shapes fitted to points, region growing,
2//! distances, registration, thickness, orientation, shadows and symmetry.
3
4use serde::{Deserialize, Serialize};
5
6use crate::*;
7
8/// How a shape is fitted to measured points.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
10#[serde(rename_all = "snake_case")]
11pub enum FitMethod {
12    /// Orthogonal least squares: the mean shape.
13    #[default]
14    LeastSquares,
15    /// The middle of the narrowest zone holding every point (flatness,
16    /// straightness, circularity, cylindricity, sphericity).
17    MinimumZone,
18    /// The largest circle or cylinder with every point outside it (a
19    /// hole's mating size).
20    Inscribed,
21    /// The smallest circle or cylinder with every point inside it (a
22    /// boss's mating size).
23    Circumscribed,
24}
25
26/// What shape a set of measured points is fitted to.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
28pub enum FitKind {
29    Plane,
30    Sphere,
31    Cylinder,
32    Cone,
33    Torus,
34    /// A circle in space: its plane and its round together.
35    Circle,
36    Line,
37}
38
39impl FitKind {
40    pub const ALL: [FitKind; 7] = [
41        FitKind::Plane,
42        FitKind::Sphere,
43        FitKind::Cylinder,
44        FitKind::Cone,
45        FitKind::Torus,
46        FitKind::Circle,
47        FitKind::Line,
48    ];
49}
50
51/// Points to fit a shape to, and how.
52#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
53pub struct FitRequest {
54    pub kind: FitKind,
55    /// In millimetres, in whatever frame the answer is wanted in.
56    pub points: Vec<[f64; 3]>,
57    /// A normal per point, out of the material, or empty.
58    #[serde(default, skip_serializing_if = "Vec::is_empty")]
59    pub normals: Vec<[f64; 3]>,
60    /// Points farther than this many sigmas from the fit are left out and
61    /// it is fitted again, until what is kept stops changing; `None` keeps
62    /// every point.
63    #[serde(default)]
64    pub sigma_cutoff: Option<f64>,
65    /// A sphere, cylinder or circle's radius held, only the rest fitted.
66    #[serde(default)]
67    pub fixed_radius: Option<f64>,
68}
69
70/// A fitted shape, in the request's frame. Directions are unit length.
71#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
72pub enum FittedShape {
73    Plane {
74        origin: [f64; 3],
75        normal: [f64; 3],
76    },
77    Sphere {
78        centre: [f64; 3],
79        radius: f64,
80    },
81    Cylinder {
82        point: [f64; 3],
83        axis: [f64; 3],
84        radius: f64,
85    },
86    /// `half_angle` in radians, between the axis and the wall.
87    Cone {
88        apex: [f64; 3],
89        axis: [f64; 3],
90        half_angle: f64,
91    },
92    Torus {
93        centre: [f64; 3],
94        axis: [f64; 3],
95        major: f64,
96        minor: f64,
97    },
98    Circle {
99        centre: [f64; 3],
100        normal: [f64; 3],
101        radius: f64,
102    },
103    Line {
104        point: [f64; 3],
105        direction: [f64; 3],
106    },
107}
108
109/// A least-squares fit and what it rests on.
110#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
111pub struct FitAnswer {
112    pub shape: FittedShape,
113    /// RMS distance of the points used from the shape.
114    pub sigma: f64,
115    /// The most negative and most positive signed distance of the points
116    /// used: the form error is their difference.
117    pub form: (f64, f64),
118    /// Which points the fit used, one per point given.
119    pub used: Vec<bool>,
120    /// Each point's signed distance from the shape, used or not.
121    pub residuals: Vec<f64>,
122    pub converged: bool,
123}
124
125/// A region to grow over a mesh from points near it, and how.
126#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
127pub struct GrowRequest {
128    /// The surface to grow: a plane, sphere, cylinder, cone or torus.
129    pub kind: FitKind,
130    /// Points on or near the mesh the region starts from.
131    pub seeds: Vec<[f64; 3]>,
132    /// Points farther from the fit than this many sigmas are left out and
133    /// stop growth; the kernel's own gate when `None`.
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub sigma_cutoff: Option<f64>,
136    /// The largest turn, in degrees, between a triangle's normal and the
137    /// surface's for the triangle to join; the kernel's default when
138    /// `None`.
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub normal_limit_deg: Option<f64>,
141    /// Take off the rim while it turns away from the surface (a face's
142    /// rounds).
143    #[serde(default)]
144    pub peel: bool,
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub max_triangles: Option<usize>,
147}
148
149/// A grown region and its fit.
150#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
151pub struct GrowAnswer {
152    /// The fit; its `used` and `residuals` go with `vertices`.
153    pub fit: FitAnswer,
154    /// The mesh's triangles in the region.
155    pub triangles: Vec<u32>,
156    /// The mesh vertex each of the fit's points is.
157    pub vertices: Vec<u32>,
158    /// Whether each seed's triangle ended up in the region.
159    pub seeds_in_region: Vec<bool>,
160}
161
162/// Points to measure to a reference surface, and how.
163#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
164pub struct DistanceRequest {
165    pub points: Vec<[f64; 3]>,
166    /// One per point, or none; needed for `facing_limit_deg`.
167    #[serde(default, skip_serializing_if = "Vec::is_empty")]
168    pub normals: Vec<[f64; 3]>,
169    /// A point with nothing nearer reads unmeasured; any distance when
170    /// `None`.
171    #[serde(default, skip_serializing_if = "Option::is_none")]
172    pub max: Option<f64>,
173    /// Only surface turned within this many degrees of a point's own
174    /// normal counts for it.
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub facing_limit_deg: Option<f64>,
177}
178
179/// Points to bring onto a reference surface by a rigid motion, and how.
180#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
181pub struct RegisterRequest {
182    pub points: Vec<[f64; 3]>,
183    /// One per point, or none.
184    #[serde(default, skip_serializing_if = "Vec::is_empty")]
185    pub normals: Vec<[f64; 3]>,
186    /// Try every way of matching the points' principal axes with the
187    /// reference's as well as the points where they are, and keep the best.
188    #[serde(default)]
189    pub search: bool,
190    /// Pairs farther apart than this are not used.
191    #[serde(default, skip_serializing_if = "Option::is_none")]
192    pub max_distance: Option<f64>,
193    /// Pair a point only with reference surface turned within this many
194    /// degrees of its own normal.
195    #[serde(default, skip_serializing_if = "Option::is_none")]
196    pub facing_limit_deg: Option<f64>,
197}
198
199/// A rigid motion that brings points onto a reference, and how well.
200#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
201pub struct Registration {
202    /// Row-major, the last row left out: the points' frame to where they
203    /// fit.
204    pub transform: [[f64; 4]; 3],
205    /// RMS distance of the pairs kept, mm.
206    pub rms: f64,
207    pub inliers: usize,
208    pub sampled: usize,
209    pub converged: bool,
210    /// Motions the fit cannot pin down (a cylinder turning about its axis,
211    /// a plane sliding along itself), each a turn about `about` with a
212    /// slide; empty when the fit is held every way.
213    #[serde(default)]
214    pub free: Vec<FreeMotion>,
215}
216
217#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
218pub struct FreeMotion {
219    pub about: [f64; 3],
220    pub rotation: [f64; 3],
221    pub translation: [f64; 3],
222}
223
224/// Points on a part whose wall thickness is read, and how.
225#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
226pub struct ThicknessRequest {
227    pub points: Vec<[f64; 3]>,
228    /// Outward, one per point.
229    pub normals: Vec<[f64; 3]>,
230    /// The largest ball touching the point inside the material, in place
231    /// of rays.
232    #[serde(default)]
233    pub sphere: bool,
234    /// Rays spread within this many degrees of the inward normal, the
235    /// shortest kept; along the normal alone at 0.
236    #[serde(default)]
237    pub cone_deg: f64,
238    #[serde(default)]
239    pub rays: u32,
240    /// Surfaces within this many degrees of edge-on to a ray are passed
241    /// over.
242    #[serde(default)]
243    pub facing_limit_deg: f64,
244    /// A wall thicker than this reads unmeasured.
245    #[serde(default, skip_serializing_if = "Option::is_none")]
246    pub max: Option<f64>,
247}
248
249/// What distances are measured to.
250#[derive(Debug, Clone, Copy)]
251pub enum DistanceTarget<'a> {
252    /// Triangles, closed or not.
253    Mesh(&'a TriMesh),
254    /// A native-format solid, meshed finely by curvature for the purpose.
255    Shape(&'a [u8]),
256}
257
258/// A scan's proposed upright frame, expressed in its own coordinates.
259#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
260pub struct Orientation {
261    /// Bounding-box centre on the standing face.
262    pub origin: [f64; 3],
263    pub x_axis: [f64; 3],
264    pub z_axis: [f64; 3],
265    /// What supports the proposal, including a principal-axis fallback.
266    pub said: String,
267}
268
269/// One connected polyline of a mesh's section by a plane, in the mesh's
270/// own frame.
271#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
272pub struct SectionChain {
273    /// In order along the chain; a closed chain does not repeat its first
274    /// point.
275    pub points: Vec<[f64; 3]>,
276    /// At each point, the unit direction in the plane pointing out of the
277    /// material.
278    pub outward: Vec<[f64; 3]>,
279    pub closed: bool,
280}
281
282/// The shadow a mesh casts on a plane, and an outline fitted around it.
283#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
284pub struct ShadowRequest {
285    /// The plane, in the mesh's frame; the answer's points are along its
286    /// `x_axis` and `y_axis` from its `origin`.
287    pub plane: ProfilePlane,
288    /// The outline's least clearance from the shadow, mm; negative inside
289    /// it, a press fit.
290    pub play: f64,
291    /// Half the outline's band: every point of it lies between `play` and
292    /// `play + 2 tolerance` outside the shadow.
293    pub tolerance: f64,
294    /// Corners turning less than this, degrees, take the largest tangent
295    /// arc that fits the band.
296    pub round_below_deg: f64,
297    /// Holes and notches no wider across than this, mm, are filled before
298    /// the outline is fitted (its inner corners rounded to half of it);
299    /// 0 fills nothing.
300    #[serde(default)]
301    pub fill_below: f64,
302}
303
304/// What a mesh's shadow is: its loops as traced (outer boundaries
305/// counter-clockwise, holes clockwise) and the outline of lines, arcs and
306/// circles fitted around them.
307#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
308pub struct ShadowAnswer {
309    pub silhouette: Vec<Vec<[f64; 2]>>,
310    pub outline: Vec<ProfileWire>,
311}
312
313/// How a chain of points is fitted with lines and arcs.
314#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
315pub struct ChainFit {
316    /// Every point lies within this distance of its piece, mm.
317    pub tolerance: f64,
318    /// Pieces turning against each other meet where their curves cross,
319    /// bringing back a corner the points round off.
320    pub corners: bool,
321    /// Lines within this many degrees of the plane's axes are turned onto
322    /// them where they still hold their points.
323    pub axis_snap_deg: Option<f64>,
324    /// An arc bowing from its chord by no more than this is taken as
325    /// lines, mm.
326    pub min_bow: f64,
327    pub closed: bool,
328}
329
330/// A scan's mirror plane, expressed in its own coordinates.
331#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
332pub struct SymmetryPlane {
333    pub point: [f64; 3],
334    pub normal: [f64; 3],
335    /// RMS mirror residual in millimetres.
336    pub rms: f64,
337}