Skip to main content

printobserver_panels/
sheet.rs

1//! Whether the camera is still aligned with its calibration, judged on one
2//! frame of the empty build sheet, before anything is printed.
3//!
4//! Two gates answer it, and `aligned` needs both.
5//!
6//! - **The landmarks** say whether the camera moved: the calibration's own
7//!   landmarks, found as every check finds them ([`crate::found_landmarks`]).
8//!   Two or more visible beyond the calibration's `drift_tolerance_px` mean the
9//!   camera moved, whatever the sheet says; fewer than two visible cannot say.
10//! - **The sheet** says whether the projection and the bed height the caller
11//!   read back still put the sheet where it is. Every sample of the sheet's
12//!   outline ([`SheetOutline`]) is projected at that height and searched for
13//!   only within [`SHEET_TOLERANCE_PX`] of where it lands, along its outward
14//!   normal, for an edge light inside and dark outside; the sheet's hole is
15//!   searched for as a dark blob just as near. A translation is fitted to what
16//!   is found, with Huber weights.
17//!
18//! The band is deliberately no wider than the tolerance, so the sheet alone
19//! cannot see a camera moved further than it: it finds nothing, or a nearby
20//! edge. Measured on the 2026-11-28 empty-sheet frames, the sheet alone passed
21//! 9 of 14 copies shifted 20 px and all 14 rotated 0.5°, and the two gates
22//! together passed none of them while passing every frame as captured, at bed
23//! heights 2 to 150 mm. A camera that has clearly moved is therefore answered
24//! as moved before the sheet is asked, so a frame on which the sheet cannot be
25//! found is still sent to a calibration when its landmarks show the move.
26//!
27//! The fit cannot find the bed's height: the outline moves only 1.9 to 3.6 px
28//! per millimetre of it, so a sheet reseated 1–2 mm is worth several
29//! millimetres, and a height is caught wrong only when it is about 10 mm off.
30//! It is the caller's, read back from the printer while idle.
31
32use std::sync::OnceLock;
33
34use image::{GrayImage, Rgb, RgbImage};
35use imageproc::drawing::{draw_cross_mut, draw_hollow_rect_mut};
36use imageproc::rect::Rect;
37use printobserver_types::schemars::JsonSchema;
38use printobserver_types::serde::{Deserialize, Serialize};
39
40use crate::calibration::{CameraCalibration, Projector};
41use crate::compose::decode;
42use crate::drift::check_frame;
43use crate::error::ComposeError;
44use crate::view::{FoundLandmark, ReferenceLandmark, ViewCorrection, found_landmarks};
45
46/// How far from the calibration's projection the sheet is searched for, and
47/// the largest translation an aligned camera may need, in pixels.
48pub const SHEET_TOLERANCE_PX: f64 = 10.0;
49
50/// The largest RMS distance, in pixels, of the found edges from the
51/// translated outline at which the fit is trusted. The worst frame measured
52/// as captured, the smooth sheet at bed Z 150, leaves 4.68 px of the
53/// calibration's own error above the heights it was fitted over.
54pub const MAX_RESIDUAL_PX: f64 = 5.0;
55
56/// The least share of the outline samples in view that must be found.
57pub const MIN_SUPPORT: f64 = 0.6;
58
59/// Below this share found, no sheet is in view at all.
60pub const NO_SHEET_BELOW: f64 = 0.25;
61
62/// How many edges must each show [`MIN_SAMPLES_PER_EDGE`] samples.
63pub const MIN_EDGES_SEEN: usize = 3;
64
65/// How many samples an edge needs, in view or found, to count.
66pub const MIN_SAMPLES_PER_EDGE: usize = 6;
67
68/// The least edge strength, in grey levels per pixel, that counts as an edge.
69const EDGE_MIN_STRENGTH: f64 = 2.0;
70
71/// How far inside the frame's border a sample must project to be in view.
72const IN_VIEW_MARGIN_PX: f64 = 20.0;
73
74/// The blur the frame's grey is read through before its gradient.
75const BLUR_SIGMA: f64 = 2.0;
76
77/// The spacing of the offsets an edge is searched at, in pixels.
78const SEARCH_STEP_PX: f64 = 0.5;
79
80/// How far either side along the edge each sample is averaged over.
81const ALONG_EDGE_PX: f64 = 3.0;
82
83/// A residual beyond which a Huber weight starts to fall, in pixels.
84const HUBER_PX: f64 = 1.5;
85
86/// How much darker than its neighbourhood the hole must be, in grey levels.
87const HOLE_DARKER_BY: f64 = 25.0;
88
89/// The fewest pixels the hole's blob may hold.
90const HOLE_MIN_AREA: usize = 20;
91
92/// One edge of a sheet: a straight line in bed millimetres at the sheet's
93/// surface, its outward normal, and where along it the real edge lies.
94#[derive(Debug, Clone, PartialEq, Deserialize)]
95#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
96pub struct SheetEdge {
97    /// Which edge, as the camera's bed frame names it.
98    pub name: String,
99    /// Where the line starts.
100    pub from_mm: [f64; 2],
101    /// Where it ends.
102    pub to_mm: [f64; 2],
103    /// The unit normal pointing off the sheet.
104    pub outward: [f64; 2],
105    /// `[t, across]`: at `t` mm along the line, how far outward of it the
106    /// real edge lies. Rounded corners, notches, pin cut-outs and the
107    /// label's edge are left out.
108    pub profile_t_across_mm: Vec<[f64; 2]>,
109}
110
111/// One build sheet's outline and its hole, in bed millimetres at its surface.
112#[derive(Debug, Clone, PartialEq, Deserialize)]
113#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
114pub struct SheetOutline {
115    /// The sheet id, as the server's sheet table names it.
116    pub sheet: String,
117    /// Where the geometry came from.
118    pub source: String,
119    /// The plane it lies in.
120    pub plane: String,
121    /// Its four edges.
122    pub edges: Vec<SheetEdge>,
123    /// The centre of its round hole, when it has one.
124    pub hole_mm: Option<[f64; 2]>,
125}
126
127/// The sheets this crate carries an outline of: the two PEI sheets of the
128/// CORE One, back-projected through its 2026-11-27 calibration, since no
129/// dimensioned drawing of them is published.
130const COMMITTED: [&str; 2] = [
131    include_str!("../sheets/core-one-smooth-pei.json"),
132    include_str!("../sheets/core-one-textured-pei.json"),
133];
134
135impl SheetOutline {
136    /// The committed outline of one sheet, by its id; nothing for a sheet this
137    /// crate carries no outline of.
138    #[must_use]
139    pub fn committed(sheet: &str) -> Option<&'static Self> {
140        static PARSED: OnceLock<Vec<SheetOutline>> = OnceLock::new();
141        PARSED
142            .get_or_init(|| {
143                COMMITTED
144                    .iter()
145                    .filter_map(|text| printobserver_types::serde_json::from_str(text).ok())
146                    .collect()
147            })
148            .iter()
149            .find(|outline| outline.sheet == sheet)
150    }
151
152    /// Every sheet id this crate carries an outline of.
153    #[must_use]
154    pub fn committed_sheets() -> Vec<&'static str> {
155        ["smooth-pei", "textured-pei"]
156            .into_iter()
157            .filter(|sheet| Self::committed(sheet).is_some())
158            .collect()
159    }
160}
161
162/// Why a frame could not show whether the camera is aligned.
163#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
164#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
165#[schemars(crate = "printobserver_types::schemars")]
166pub enum UnjudgeableCause {
167    /// Too few of the outline's samples project into the frame.
168    TooLittleSheetInView,
169    /// Almost none of the outline is found: no sheet, or no picture.
170    NoSheetFound,
171    /// Too little of the outline is found, or on too few edges.
172    SheetOccluded,
173    /// Fewer than two of the calibration's landmarks are found.
174    LandmarksHidden,
175    /// The found edges disagree with any one translation of the outline.
176    FitInconsistent,
177}
178
179impl UnjudgeableCause {
180    /// The cause as a sentence's clause.
181    #[must_use]
182    pub const fn said(self) -> &'static str {
183        match self {
184            Self::TooLittleSheetInView => "too little of the sheet is in the camera's view",
185            Self::NoSheetFound => "no sheet was found in the frame",
186            Self::SheetOccluded => "too much of the sheet's outline is hidden",
187            Self::LandmarksHidden => {
188                "fewer than two of the calibration's landmarks are found, so whether the camera moved cannot be told"
189            }
190            Self::FitInconsistent => "the sheet's edges fit no one shift of its outline",
191        }
192    }
193}
194
195/// What the two gates found of one frame.
196#[derive(Debug, Clone, Copy, PartialEq, Eq)]
197pub enum SheetVerdict {
198    /// Both gates pass.
199    Aligned,
200    /// The landmarks show the camera moved, or the sheet is shifted beyond
201    /// the tolerance.
202    NotAligned,
203    /// The frame cannot show it.
204    Unjudgeable(UnjudgeableCause),
205}
206
207/// One judgement of the camera on an empty sheet.
208#[derive(Debug, Clone, PartialEq)]
209pub struct SheetFit {
210    /// What it came to.
211    pub verdict: SheetVerdict,
212    /// The fitted translation, `[dx, dy]` pixels; nothing when the sheet could
213    /// not be fitted.
214    pub shift_px: Option<[f64; 2]>,
215    /// The RMS distance of the found edges from the translated outline;
216    /// nothing when the sheet could not be fitted.
217    pub residual_px: Option<f64>,
218    /// The share of the in-view samples found.
219    pub support: f64,
220    /// How many edges showed enough found samples.
221    pub edges_seen: usize,
222    /// How many visible landmarks lie beyond the drift tolerance.
223    pub landmarks_moved: usize,
224    /// How many landmarks are visible.
225    pub landmarks_visible: usize,
226    /// Whether the sheet's hole was found.
227    pub hole_found: bool,
228    /// The correction an aligned frame puts in force: its translation, with
229    /// the landmarks found on this frame as its reference.
230    pub correction: Option<ViewCorrection>,
231    /// The frame with the projected outline, the fitted one and the found
232    /// landmarks drawn, as a JPEG.
233    pub drawn_jpeg: Vec<u8>,
234}
235
236impl SheetFit {
237    /// The fitted translation's length.
238    #[must_use]
239    pub fn offset_px(&self) -> Option<f64> {
240        self.shift_px.map(|[dx, dy]| dx.hypot(dy))
241    }
242}
243
244/// What the camera check is given.
245#[derive(Debug, Clone, Copy)]
246pub struct SheetInputs<'a> {
247    /// The frame.
248    pub frame_jpeg: &'a [u8],
249    /// The snapshot URL it came from.
250    pub camera_snapshot_url: &'a str,
251    /// The printer's calibration.
252    pub calibration: &'a CameraCalibration,
253    /// The sheet on the bed.
254    pub sheet: &'a SheetOutline,
255    /// The bed's height as the printer read it back, in millimetres.
256    pub bed_z_mm: f64,
257}
258
259/// Judge whether the camera is still aligned with its calibration on one frame
260/// of the empty sheet.
261///
262/// # Errors
263///
264/// [`ComposeError::Undecodable`] for a frame that is no JPEG,
265/// [`ComposeError::FrameMismatch`] for one of another size or stream than the
266/// calibration's, and [`ComposeError::Encode`] when the drawn frame cannot be
267/// encoded.
268pub fn fit_sheet(inputs: &SheetInputs<'_>) -> Result<SheetFit, ComposeError> {
269    let frame = decode(inputs.frame_jpeg)?;
270    check_frame(
271        inputs.calibration,
272        [frame.width(), frame.height()],
273        inputs.camera_snapshot_url,
274    )?;
275    let grey = image::imageops::grayscale(&frame);
276    let landmarks = found_landmarks(inputs.calibration, &grey);
277    let gradients = Gradients::of(&grey);
278    let samples = Samples::projected(
279        &inputs.calibration.projector(),
280        inputs.sheet,
281        inputs.bed_z_mm,
282        [frame.width(), frame.height()],
283    );
284    let measured = measure(&gradients, &samples);
285    let visible = landmarks.iter().filter(|found| found.visible()).count();
286    let moved = landmarks
287        .iter()
288        .filter(|found| {
289            found.visible() && found.distance_px() > inputs.calibration.drift_tolerance_px
290        })
291        .count();
292    let verdict = ruled(&measured, visible, moved);
293    let correction = (verdict == SheetVerdict::Aligned)
294        .then_some(measured.shift)
295        .flatten()
296        .map(|shift| ViewCorrection::translation(shift, reference(&landmarks)));
297    let drawn_jpeg = drawn(frame, &samples, &measured, &landmarks, inputs.calibration)?;
298    Ok(SheetFit {
299        verdict,
300        shift_px: measured.shift,
301        residual_px: measured.residual,
302        support: measured.support,
303        edges_seen: measured.edges_seen,
304        landmarks_moved: moved,
305        landmarks_visible: visible,
306        hole_found: measured.hole.is_some(),
307        correction,
308        drawn_jpeg,
309    })
310}
311
312/// The highest bed height, in millimetres, [`calibrated_outline`] looks for
313/// the sheet at: no printer this crate carries a sheet for lowers it further.
314const OUTLINE_SEARCH_TOP_MM: u32 = 220;
315
316/// The step between the bed heights [`calibrated_outline`] tries, in
317/// millimetres: at most 3.6 px of the outline's move per millimetre, so every
318/// height lies within [`SHEET_TOLERANCE_PX`] of one tried.
319const OUTLINE_SEARCH_STEP_MM: u32 = 2;
320
321/// Where the sheet's outline lies on a frame of a calibration's own size and
322/// stream, in frame pixels, when the frame shows it: the committed sheet and
323/// bed height whose projection the frame's edges support best, shifted by the
324/// translation fitted to them. Nothing when the frame is not the
325/// calibration's, when its landmarks show the camera moved, or when no sheet
326/// and height is fitted by [`MIN_SUPPORT`] of its samples within
327/// [`MAX_RESIDUAL_PX`].
328///
329/// A look at the printer names neither the sheet nor the bed's height, so
330/// both are searched for; the height is found only roughly, which is all a
331/// close-up cut around the outline needs.
332pub(crate) fn calibrated_outline(
333    frame: &RgbImage,
334    camera_snapshot_url: &str,
335    calibration: &CameraCalibration,
336) -> Option<Vec<[f64; 2]>> {
337    let size = [frame.width(), frame.height()];
338    check_frame(calibration, size, camera_snapshot_url).ok()?;
339    let grey = image::imageops::grayscale(frame);
340    let moved = found_landmarks(calibration, &grey)
341        .iter()
342        .filter(|found| found.visible() && found.distance_px() > calibration.drift_tolerance_px)
343        .count();
344    if moved >= 2 {
345        return None;
346    }
347    let gradients = Gradients::of(&grey);
348    let projector = calibration.projector();
349    let mut best: Option<(f64, f64, &SheetOutline, f64, [f64; 2])> = None;
350    for sheet in SheetOutline::committed_sheets() {
351        let Some(outline) = SheetOutline::committed(sheet) else {
352            continue;
353        };
354        for step in 0..=OUTLINE_SEARCH_TOP_MM / OUTLINE_SEARCH_STEP_MM {
355            let bed_z_mm = f64::from(step * OUTLINE_SEARCH_STEP_MM);
356            let samples = Samples::projected(&projector, outline, bed_z_mm, size);
357            let measured = measure(&gradients, &samples);
358            let (Some(shift), Some(residual)) = (measured.shift, measured.residual) else {
359                continue;
360            };
361            if measured.unfitted.is_some() || residual > MAX_RESIDUAL_PX {
362                continue;
363            }
364            if best.is_none_or(|(support, least, ..)| {
365                measured
366                    .support
367                    .total_cmp(&support)
368                    .then(least.total_cmp(&residual))
369                    .is_gt()
370            }) {
371                best = Some((measured.support, residual, outline, bed_z_mm, shift));
372            }
373        }
374    }
375    let (_, _, outline, bed_z_mm, [dx, dy]) = best?;
376    Some(
377        outline_points_mm(outline)
378            .into_iter()
379            .filter_map(|[x, y]| projector.pixel([x, y, -bed_z_mm]))
380            .map(|[u, v]| [u + dx, v + dy])
381            .collect(),
382    )
383}
384
385/// Every point of a sheet's outline the committed geometry places, in bed
386/// millimetres: each edge's two ends and each point of its profile.
387fn outline_points_mm(sheet: &SheetOutline) -> Vec<[f64; 2]> {
388    let mut points = Vec::new();
389    for edge in &sheet.edges {
390        let (dx, dy) = (
391            edge.to_mm[0] - edge.from_mm[0],
392            edge.to_mm[1] - edge.from_mm[1],
393        );
394        let length = dx.hypot(dy);
395        if length <= 0.0 {
396            continue;
397        }
398        let direction = [dx / length, dy / length];
399        points.push(edge.from_mm);
400        points.extend(edge.profile_t_across_mm.iter().map(|[t, across]| {
401            [
402                edge.from_mm[0] + t * direction[0] + across * edge.outward[0],
403                edge.from_mm[1] + t * direction[1] + across * edge.outward[1],
404            ]
405        }));
406        points.push(edge.to_mm);
407    }
408    points
409}
410
411/// Which verdict the two gates come to, the camera's own evidence first: two
412/// or more moved landmarks are a moved camera whatever the sheet found.
413fn ruled(measured: &Measured, visible: usize, moved: usize) -> SheetVerdict {
414    if moved >= 2 {
415        return SheetVerdict::NotAligned;
416    }
417    if let Some(cause) = measured.unfitted {
418        return SheetVerdict::Unjudgeable(cause);
419    }
420    if visible < 2 {
421        return SheetVerdict::Unjudgeable(UnjudgeableCause::LandmarksHidden);
422    }
423    if measured
424        .residual
425        .is_some_and(|residual| residual > MAX_RESIDUAL_PX)
426    {
427        return SheetVerdict::Unjudgeable(UnjudgeableCause::FitInconsistent);
428    }
429    if measured
430        .shift
431        .is_some_and(|[dx, dy]| dx.hypot(dy) > SHEET_TOLERANCE_PX)
432    {
433        return SheetVerdict::NotAligned;
434    }
435    SheetVerdict::Aligned
436}
437
438/// The visible landmarks of a frame, as a correction's reference.
439fn reference(landmarks: &[FoundLandmark]) -> Vec<ReferenceLandmark> {
440    landmarks
441        .iter()
442        .filter(|found| found.visible())
443        .map(|found| ReferenceLandmark {
444            name: found.name.clone(),
445            offset_px: found.located.offset_px,
446            score: f64::from(found.located.score),
447        })
448        .collect()
449}
450
451/// A frame's blurred grey and its gradient, in grey levels per pixel.
452struct Gradients {
453    /// Its width.
454    width: usize,
455    /// Its height.
456    height: usize,
457    /// The blurred grey, row by row.
458    grey: Vec<f64>,
459    /// The gradient along X.
460    gx: Vec<f64>,
461    /// The gradient along Y.
462    gy: Vec<f64>,
463}
464
465impl Gradients {
466    /// A grey frame's, blurred by [`BLUR_SIGMA`], with the 3×3 Sobel
467    /// gradient scaled to grey levels per pixel.
468    fn of(frame: &GrayImage) -> Self {
469        let (width, height) = (frame.width() as usize, frame.height() as usize);
470        let raw: Vec<f64> = frame
471            .as_raw()
472            .iter()
473            .map(|value| f64::from(*value))
474            .collect();
475        let grey = blurred(&raw, width, height, BLUR_SIGMA);
476        let mut gx = vec![0.0; width * height];
477        let mut gy = vec![0.0; width * height];
478        let at = |x: usize, y: usize| grey[y * width + x];
479        for y in 0..height {
480            let (up, down) = (y.saturating_sub(1), (y + 1).min(height - 1));
481            for x in 0..width {
482                let (left, right) = (x.saturating_sub(1), (x + 1).min(width - 1));
483                gx[y * width + x] = ((at(right, up) - at(left, up))
484                    + 2.0 * (at(right, y) - at(left, y))
485                    + (at(right, down) - at(left, down)))
486                    / 8.0;
487                gy[y * width + x] = ((at(left, down) - at(left, up))
488                    + 2.0 * (at(x, down) - at(x, up))
489                    + (at(right, down) - at(right, up)))
490                    / 8.0;
491            }
492        }
493        Self {
494            width,
495            height,
496            grey,
497            gx,
498            gy,
499        }
500    }
501
502    /// One plane's value at a point, bilinearly, its nearest edge pixel
503    /// outside the frame.
504    fn sample(&self, plane: &[f64], [x, y]: [f64; 2]) -> f64 {
505        let most = |size: usize| f64::from(u32::try_from(size - 1).unwrap_or(0));
506        let (x, y) = (
507            x.clamp(0.0, most(self.width)),
508            y.clamp(0.0, most(self.height)),
509        );
510        let (x0, y0) = (x.floor(), y.floor());
511        let (fx, fy) = (x - x0, y - y0);
512        #[expect(
513            clippy::cast_possible_truncation,
514            clippy::cast_sign_loss,
515            reason = "clamped into the frame above"
516        )]
517        let (x0, y0) = (x0 as usize, y0 as usize);
518        let (x1, y1) = ((x0 + 1).min(self.width - 1), (y0 + 1).min(self.height - 1));
519        let value = |x: usize, y: usize| plane[y * self.width + x];
520        (value(x0, y0) * (1.0 - fx) + value(x1, y0) * fx) * (1.0 - fy)
521            + (value(x0, y1) * (1.0 - fx) + value(x1, y1) * fx) * fy
522    }
523
524    /// The grey's derivative along `normal` at a point.
525    fn along(&self, point: [f64; 2], normal: [f64; 2]) -> f64 {
526        self.sample(&self.gx, point) * normal[0] + self.sample(&self.gy, point) * normal[1]
527    }
528}
529
530/// A separable Gaussian blur of a grey plane, its border replicated.
531pub(crate) fn blurred(plane: &[f64], width: usize, height: usize, sigma: f64) -> Vec<f64> {
532    let radius = (sigma * 4.0).ceil();
533    #[expect(
534        clippy::cast_possible_truncation,
535        clippy::cast_sign_loss,
536        reason = "a few times a small sigma"
537    )]
538    let reach = radius as usize;
539    let weights: Vec<f64> = (0..=2 * reach)
540        .map(|k| {
541            let d = f64::from(u32::try_from(k).unwrap_or(0)) - radius;
542            (-(d * d) / (2.0 * sigma * sigma)).exp()
543        })
544        .collect();
545    let total: f64 = weights.iter().sum();
546    let weights: Vec<f64> = weights.iter().map(|weight| weight / total).collect();
547    let mut across = vec![0.0; plane.len()];
548    for y in 0..height {
549        let row = &plane[y * width..(y + 1) * width];
550        for x in 0..width {
551            across[y * width + x] = weights
552                .iter()
553                .enumerate()
554                .map(|(k, weight)| {
555                    let at = (x + k).saturating_sub(reach).min(width - 1);
556                    row[at] * weight
557                })
558                .sum();
559        }
560    }
561    let mut out = vec![0.0; plane.len()];
562    for y in 0..height {
563        for (k, weight) in weights.iter().enumerate() {
564            let from = (y + k).saturating_sub(reach).min(height - 1);
565            let source = &across[from * width..(from + 1) * width];
566            let target = &mut out[y * width..(y + 1) * width];
567            for (value, add) in target.iter_mut().zip(source) {
568                *value += add * weight;
569            }
570        }
571    }
572    out
573}
574
575/// The outline's samples in view at one bed height: each point, its outward
576/// normal in the image, and the edge it is of.
577struct Samples {
578    /// The projected points.
579    points: Vec<[f64; 2]>,
580    /// Their outward normals, unit length.
581    normals: Vec<[f64; 2]>,
582    /// Which edge each is of.
583    edge: Vec<usize>,
584    /// How many edges the outline has.
585    edges: usize,
586    /// The hole's projection, when it has one in view.
587    hole: Option<[f64; 2]>,
588}
589
590impl Samples {
591    /// The samples of `sheet` projected with the bed at `bed_z_mm`, those
592    /// within [`IN_VIEW_MARGIN_PX`] of the frame's border left out.
593    fn projected(
594        projector: &Projector,
595        sheet: &SheetOutline,
596        bed_z_mm: f64,
597        size: [u32; 2],
598    ) -> Self {
599        let [w, h] = size.map(f64::from);
600        let in_view = |[u, v]: [f64; 2]| {
601            u > IN_VIEW_MARGIN_PX
602                && u < w - IN_VIEW_MARGIN_PX
603                && v > IN_VIEW_MARGIN_PX
604                && v < h - IN_VIEW_MARGIN_PX
605        };
606        let mut samples = Self {
607            points: Vec::new(),
608            normals: Vec::new(),
609            edge: Vec::new(),
610            edges: sheet.edges.len(),
611            hole: sheet
612                .hole_mm
613                .and_then(|[x, y]| projector.pixel([x, y, -bed_z_mm])),
614        };
615        for (index, edge) in sheet.edges.iter().enumerate() {
616            let (dx, dy) = (
617                edge.to_mm[0] - edge.from_mm[0],
618                edge.to_mm[1] - edge.from_mm[1],
619            );
620            let length = dx.hypot(dy);
621            if length <= 0.0 {
622                continue;
623            }
624            let direction = [dx / length, dy / length];
625            for [t, across] in &edge.profile_t_across_mm {
626                let bed = [
627                    edge.from_mm[0] + t * direction[0] + across * edge.outward[0],
628                    edge.from_mm[1] + t * direction[1] + across * edge.outward[1],
629                ];
630                let (Some(point), Some(outer)) = (
631                    projector.pixel([bed[0], bed[1], -bed_z_mm]),
632                    projector.pixel([
633                        bed[0] + edge.outward[0],
634                        bed[1] + edge.outward[1],
635                        -bed_z_mm,
636                    ]),
637                ) else {
638                    continue;
639                };
640                let normal = [outer[0] - point[0], outer[1] - point[1]];
641                let norm = normal[0].hypot(normal[1]);
642                if !in_view(point) || norm <= 1e-9 {
643                    continue;
644                }
645                samples.points.push(point);
646                samples.normals.push([normal[0] / norm, normal[1] / norm]);
647                samples.edge.push(index);
648            }
649        }
650        samples
651    }
652
653    /// How many edges have at least [`MIN_SAMPLES_PER_EDGE`] of the samples
654    /// `kept` marks.
655    fn edges_with(&self, kept: &[bool]) -> usize {
656        (0..self.edges)
657            .filter(|edge| {
658                self.edge
659                    .iter()
660                    .zip(kept)
661                    .filter(|(of, kept)| **of == *edge && **kept)
662                    .count()
663                    >= MIN_SAMPLES_PER_EDGE
664            })
665            .count()
666    }
667}
668
669/// What the sheet gate measured.
670struct Measured {
671    /// Why the sheet could not be fitted at all.
672    unfitted: Option<UnjudgeableCause>,
673    /// The share of in-view samples found.
674    support: f64,
675    /// How many edges showed enough found samples.
676    edges_seen: usize,
677    /// Each in-view sample's found offset along its normal.
678    offsets: Vec<Option<f64>>,
679    /// Where the hole was found.
680    hole: Option<[f64; 2]>,
681    /// The fitted translation.
682    shift: Option<[f64; 2]>,
683    /// Its residual.
684    residual: Option<f64>,
685}
686
687/// Search the band, then fit the translation to what it found.
688fn measure(gradients: &Gradients, samples: &Samples) -> Measured {
689    let mut measured = Measured {
690        unfitted: None,
691        support: 0.0,
692        edges_seen: 0,
693        offsets: Vec::new(),
694        hole: None,
695        shift: None,
696        residual: None,
697    };
698    let all = vec![true; samples.points.len()];
699    if samples.points.len() < MIN_EDGES_SEEN * MIN_SAMPLES_PER_EDGE
700        || samples.edges_with(&all) < MIN_EDGES_SEEN
701    {
702        measured.unfitted = Some(UnjudgeableCause::TooLittleSheetInView);
703        measured.edges_seen = samples.edges_with(&all);
704        return measured;
705    }
706    measured.offsets = samples
707        .points
708        .iter()
709        .zip(&samples.normals)
710        .map(|(point, normal)| edge_offset(gradients, *point, *normal, SHEET_TOLERANCE_PX))
711        .collect();
712    let found: Vec<bool> = measured.offsets.iter().map(Option::is_some).collect();
713    let count = found.iter().filter(|found| **found).count();
714    measured.support = ratio(count, found.len());
715    measured.edges_seen = samples.edges_with(&found);
716    if measured.support < NO_SHEET_BELOW {
717        measured.unfitted = Some(UnjudgeableCause::NoSheetFound);
718        return measured;
719    }
720    if measured.support < MIN_SUPPORT || measured.edges_seen < MIN_EDGES_SEEN {
721        measured.unfitted = Some(UnjudgeableCause::SheetOccluded);
722        return measured;
723    }
724    let mut rows: Vec<([f64; 2], f64)> = samples
725        .normals
726        .iter()
727        .zip(&measured.offsets)
728        .filter_map(|(normal, offset)| offset.map(|offset| (*normal, offset)))
729        .collect();
730    let outline_rows = rows.len();
731    measured.hole = samples
732        .hole
733        .and_then(|hole| dark_blob(gradients, hole, SHEET_TOLERANCE_PX).map(|at| (hole, at)))
734        .map(|(hole, at)| {
735            rows.push(([1.0, 0.0], at[0] - hole[0]));
736            rows.push(([0.0, 1.0], at[1] - hole[1]));
737            at
738        });
739    let (shift, residuals) = huber_translation(&rows);
740    measured.shift = Some(shift);
741    measured.residual = Some(rms_inliers(&residuals[..outline_rows]));
742    measured
743}
744
745/// A count's share of a total.
746fn ratio(count: usize, total: usize) -> f64 {
747    let as_f64 = |n: usize| f64::from(u32::try_from(n).unwrap_or(u32::MAX));
748    if total == 0 {
749        0.0
750    } else {
751        as_f64(count) / as_f64(total)
752    }
753}
754
755/// Along one sample's outward normal, within `window`, where the strongest
756/// edge light inside and dark outside lies, averaged over
757/// [`ALONG_EDGE_PX`] either side along the edge; nothing when none reaches
758/// [`EDGE_MIN_STRENGTH`] or the strongest lies on the window's border.
759fn edge_offset(
760    gradients: &Gradients,
761    point: [f64; 2],
762    normal: [f64; 2],
763    window: f64,
764) -> Option<f64> {
765    let tangent = [-normal[1], normal[0]];
766    #[expect(
767        clippy::cast_possible_truncation,
768        clippy::cast_sign_loss,
769        reason = "a window of a few pixels"
770    )]
771    let steps = (2.0 * window / SEARCH_STEP_PX).round() as usize + 1;
772    let profile: Vec<f64> = (0..steps)
773        .map(|step| {
774            let d = -window + SEARCH_STEP_PX * f64::from(u32::try_from(step).unwrap_or(0));
775            let total: f64 = [-ALONG_EDGE_PX, 0.0, ALONG_EDGE_PX]
776                .iter()
777                .map(|t| {
778                    gradients.along(
779                        [
780                            point[0] + d * normal[0] + t * tangent[0],
781                            point[1] + d * normal[1] + t * tangent[1],
782                        ],
783                        normal,
784                    )
785                })
786                .sum();
787            -total / 3.0
788        })
789        .collect();
790    let (best, strength) = profile
791        .iter()
792        .copied()
793        .enumerate()
794        .reduce(|best, next| if next.1 > best.1 { next } else { best })?;
795    if best == 0 || best + 1 == steps || strength < EDGE_MIN_STRENGTH {
796        return None;
797    }
798    let (left, right) = (profile[best - 1], profile[best + 1]);
799    let curve = left - 2.0 * strength + right;
800    let refined = if curve.abs() > 1e-9 {
801        0.5 * SEARCH_STEP_PX * (left - right) / curve
802    } else {
803        0.0
804    };
805    Some(-window + SEARCH_STEP_PX * f64::from(u32::try_from(best).unwrap_or(0)) + refined)
806}
807
808/// The centroid of the largest dark blob within `window` of `guess`: pixels
809/// [`HOLE_DARKER_BY`] below the neighbourhood's median grey, connected.
810fn dark_blob(gradients: &Gradients, guess: [f64; 2], window: f64) -> Option<[f64; 2]> {
811    #[expect(
812        clippy::cast_possible_truncation,
813        reason = "a projected point of a frame of a few thousand pixels"
814    )]
815    let (x, y) = (guess[0].round() as i64, guess[1].round() as i64);
816    #[expect(
817        clippy::cast_possible_truncation,
818        reason = "a tolerance of a few pixels"
819    )]
820    let reach = window as i64 + 12;
821    let (width, height) = (
822        i64::try_from(gradients.width).ok()?,
823        i64::try_from(gradients.height).ok()?,
824    );
825    if x - reach < 0 || y - reach < 0 || x + reach >= width || y + reach >= height {
826        return None;
827    }
828    let side = usize::try_from(2 * reach + 1).ok()?;
829    let value = |dx: usize, dy: usize| {
830        let at = usize::try_from((y - reach) * width + x - reach).unwrap_or(0)
831            + dy * gradients.width
832            + dx;
833        gradients.grey[at]
834    };
835    let mut values: Vec<f64> = (0..side * side)
836        .map(|k| value(k % side, k / side))
837        .collect();
838    let mut sorted = values.clone();
839    sorted.sort_by(f64::total_cmp);
840    let median = sorted[sorted.len() / 2];
841    for value in &mut values {
842        *value = if *value < median - HOLE_DARKER_BY {
843            1.0
844        } else {
845            0.0
846        };
847    }
848    let mut seen = vec![false; side * side];
849    let mut best: Option<(usize, [f64; 2])> = None;
850    let reach_f = f64::from(u32::try_from(reach).unwrap_or(0));
851    for start in 0..side * side {
852        if values[start] < 0.5 || seen[start] {
853            continue;
854        }
855        let mut stack = vec![start];
856        seen[start] = true;
857        let (mut area, mut sum) = (0_usize, [0.0, 0.0]);
858        while let Some(at) = stack.pop() {
859            area += 1;
860            let (cx, cy) = (at % side, at / side);
861            sum[0] += f64::from(u32::try_from(cx).unwrap_or(0));
862            sum[1] += f64::from(u32::try_from(cy).unwrap_or(0));
863            for (nx, ny) in [
864                (cx.wrapping_sub(1), cy),
865                (cx + 1, cy),
866                (cx, cy.wrapping_sub(1)),
867                (cx, cy + 1),
868            ] {
869                if nx < side && ny < side && values[ny * side + nx] > 0.5 && !seen[ny * side + nx] {
870                    seen[ny * side + nx] = true;
871                    stack.push(ny * side + nx);
872                }
873            }
874        }
875        let count = f64::from(u32::try_from(area).unwrap_or(u32::MAX));
876        let centre = [sum[0] / count - reach_f, sum[1] / count - reach_f];
877        if centre[0].hypot(centre[1]) <= window
878            && area >= HOLE_MIN_AREA
879            && best.is_none_or(|(most, _)| area > most)
880        {
881            best = Some((area, centre));
882        }
883    }
884    let x_f = f64::from(i32::try_from(x).ok()?);
885    let y_f = f64::from(i32::try_from(y).ok()?);
886    best.map(|(_, centre)| [x_f + centre[0], y_f + centre[1]])
887}
888
889/// The translation `s` minimising `Σ ρ(n·s − d)` over rows `(n, d)` with a
890/// Huber `ρ`, by reweighted least squares, and each row's residual.
891fn huber_translation(rows: &[([f64; 2], f64)]) -> ([f64; 2], Vec<f64>) {
892    let mut weights = vec![1.0; rows.len()];
893    let mut shift = [0.0, 0.0];
894    for _ in 0..10 {
895        // The normal equations' matrix `[[xx, xy], [xy, yy]]` and right side.
896        let (mut xx, mut xy, mut yy) = (0.0, 0.0, 0.0);
897        let mut right = [0.0, 0.0];
898        for ((normal, target), weight) in rows.iter().zip(&weights) {
899            let squared = weight * weight;
900            xx += squared * normal[0] * normal[0];
901            xy += squared * normal[0] * normal[1];
902            yy += squared * normal[1] * normal[1];
903            right[0] += squared * normal[0] * target;
904            right[1] += squared * normal[1] * target;
905        }
906        let determinant = xx * yy - xy * xy;
907        if determinant.abs() < 1e-12 {
908            break;
909        }
910        shift = [
911            (yy * right[0] - xy * right[1]) / determinant,
912            (xx * right[1] - xy * right[0]) / determinant,
913        ];
914        for ((normal, target), weight) in rows.iter().zip(weights.iter_mut()) {
915            let residual = (target - (normal[0] * shift[0] + normal[1] * shift[1])).abs();
916            *weight = if residual <= HUBER_PX {
917                1.0
918            } else {
919                (HUBER_PX / residual.max(1e-9)).sqrt()
920            };
921        }
922    }
923    let residuals = rows
924        .iter()
925        .map(|(normal, target)| target - (normal[0] * shift[0] + normal[1] * shift[1]))
926        .collect();
927    (shift, residuals)
928}
929
930/// The RMS of the residuals within three robust deviations, and a pixel, of
931/// zero: a few edges found on a fibre or a scratch do not count against it.
932fn rms_inliers(residuals: &[f64]) -> f64 {
933    if residuals.is_empty() {
934        return 0.0;
935    }
936    let mut sizes: Vec<f64> = residuals.iter().map(|r| r.abs()).collect();
937    sizes.sort_by(f64::total_cmp);
938    let median = sizes[sizes.len() / 2];
939    let bound = 3.0 * 1.4826 * median + 1.0;
940    let inliers: Vec<f64> = residuals
941        .iter()
942        .copied()
943        .filter(|r| r.abs() < bound)
944        .collect();
945    if inliers.is_empty() {
946        return 0.0;
947    }
948    let count = f64::from(u32::try_from(inliers.len()).unwrap_or(u32::MAX));
949    (inliers.iter().map(|r| r * r).sum::<f64>() / count).sqrt()
950}
951
952/// The frame with the outline where the calibration projects it in red, where
953/// the fit puts it in green, the hole found in yellow, and each landmark
954/// found in cyan, or in red when it lies beyond the drift tolerance.
955fn drawn(
956    mut frame: RgbImage,
957    samples: &Samples,
958    measured: &Measured,
959    landmarks: &[FoundLandmark],
960    calibration: &CameraCalibration,
961) -> Result<Vec<u8>, ComposeError> {
962    const RED: Rgb<u8> = Rgb([255, 40, 40]);
963    const GREEN: Rgb<u8> = Rgb([40, 255, 40]);
964    const YELLOW: Rgb<u8> = Rgb([255, 230, 0]);
965    const CYAN: Rgb<u8> = Rgb([0, 230, 255]);
966    #[expect(
967        clippy::cast_possible_truncation,
968        reason = "a pixel of a frame of a few thousand pixels"
969    )]
970    let pixel = |[x, y]: [f64; 2]| (x.round() as i32, y.round() as i32);
971    for point in &samples.points {
972        let (x, y) = pixel(*point);
973        draw_cross_mut(&mut frame, RED, x, y);
974    }
975    if let Some(shift) = measured.shift {
976        for point in &samples.points {
977            let (x, y) = pixel([point[0] + shift[0], point[1] + shift[1]]);
978            draw_cross_mut(&mut frame, GREEN, x, y);
979        }
980    }
981    if let Some(hole) = measured.hole {
982        let (x, y) = pixel(hole);
983        draw_hollow_rect_mut(&mut frame, Rect::at(x - 6, y - 6).of_size(13, 13), YELLOW);
984    }
985    for (found, landmark) in landmarks.iter().zip(&calibration.landmarks) {
986        if !found.visible() {
987            continue;
988        }
989        let (x, y) = pixel([
990            landmark.center_px[0] + found.located.offset_px[0],
991            landmark.center_px[1] + found.located.offset_px[1],
992        ]);
993        let colour = if found.distance_px() > calibration.drift_tolerance_px {
994            RED
995        } else {
996            CYAN
997        };
998        draw_hollow_rect_mut(&mut frame, Rect::at(x - 24, y - 24).of_size(49, 49), colour);
999    }
1000    let mut jpeg = Vec::new();
1001    image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 85)
1002        .encode_image(&frame)
1003        .map_err(|error| ComposeError::Encode {
1004            detail: error.to_string(),
1005        })?;
1006    Ok(jpeg)
1007}
1008
1009#[cfg(test)]
1010mod tests {
1011    use super::{SheetOutline, huber_translation, rms_inliers};
1012
1013    #[test]
1014    fn both_committed_sheets_are_read_and_no_other_is_named() {
1015        assert_eq!(
1016            SheetOutline::committed_sheets(),
1017            ["smooth-pei", "textured-pei"]
1018        );
1019        for sheet in ["smooth-pei", "textured-pei"] {
1020            let outline = SheetOutline::committed(sheet).expect("committed");
1021            assert_eq!(outline.edges.len(), 4);
1022            assert!(outline.hole_mm.is_some());
1023            assert!(
1024                outline
1025                    .edges
1026                    .iter()
1027                    .all(|edge| edge.profile_t_across_mm.len() >= 6)
1028            );
1029        }
1030        assert!(SheetOutline::committed("satin-pei").is_none());
1031    }
1032
1033    #[test]
1034    fn the_huber_fit_finds_a_known_shift_through_an_outlier() {
1035        let shift = [3.0, -2.0];
1036        let mut rows: Vec<([f64; 2], f64)> = [[1.0, 0.0], [0.0, 1.0], [-1.0, 0.0], [0.0, -1.0]]
1037            .iter()
1038            .cycle()
1039            .take(40)
1040            .map(|normal: &[f64; 2]| (*normal, normal[0] * shift[0] + normal[1] * shift[1]))
1041            .collect();
1042        rows.push(([1.0, 0.0], 40.0));
1043        let (found, residuals) = huber_translation(&rows);
1044        assert!(
1045            (found[0] - 3.0).abs() < 0.2 && (found[1] + 2.0).abs() < 0.2,
1046            "{found:?}"
1047        );
1048        assert!(rms_inliers(&residuals) < 0.5);
1049    }
1050}