1use 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
46pub const SHEET_TOLERANCE_PX: f64 = 10.0;
49
50pub const MAX_RESIDUAL_PX: f64 = 5.0;
55
56pub const MIN_SUPPORT: f64 = 0.6;
58
59pub const NO_SHEET_BELOW: f64 = 0.25;
61
62pub const MIN_EDGES_SEEN: usize = 3;
64
65pub const MIN_SAMPLES_PER_EDGE: usize = 6;
67
68const EDGE_MIN_STRENGTH: f64 = 2.0;
70
71const IN_VIEW_MARGIN_PX: f64 = 20.0;
73
74const BLUR_SIGMA: f64 = 2.0;
76
77const SEARCH_STEP_PX: f64 = 0.5;
79
80const ALONG_EDGE_PX: f64 = 3.0;
82
83const HUBER_PX: f64 = 1.5;
85
86const HOLE_DARKER_BY: f64 = 25.0;
88
89const HOLE_MIN_AREA: usize = 20;
91
92#[derive(Debug, Clone, PartialEq, Deserialize)]
95#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
96pub struct SheetEdge {
97 pub name: String,
99 pub from_mm: [f64; 2],
101 pub to_mm: [f64; 2],
103 pub outward: [f64; 2],
105 pub profile_t_across_mm: Vec<[f64; 2]>,
109}
110
111#[derive(Debug, Clone, PartialEq, Deserialize)]
113#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
114pub struct SheetOutline {
115 pub sheet: String,
117 pub source: String,
119 pub plane: String,
121 pub edges: Vec<SheetEdge>,
123 pub hole_mm: Option<[f64; 2]>,
125}
126
127const 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 #[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 #[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#[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 TooLittleSheetInView,
169 NoSheetFound,
171 SheetOccluded,
173 LandmarksHidden,
175 FitInconsistent,
177}
178
179impl UnjudgeableCause {
180 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
197pub enum SheetVerdict {
198 Aligned,
200 NotAligned,
203 Unjudgeable(UnjudgeableCause),
205}
206
207#[derive(Debug, Clone, PartialEq)]
209pub struct SheetFit {
210 pub verdict: SheetVerdict,
212 pub shift_px: Option<[f64; 2]>,
215 pub residual_px: Option<f64>,
218 pub support: f64,
220 pub edges_seen: usize,
222 pub landmarks_moved: usize,
224 pub landmarks_visible: usize,
226 pub hole_found: bool,
228 pub correction: Option<ViewCorrection>,
231 pub drawn_jpeg: Vec<u8>,
234}
235
236impl SheetFit {
237 #[must_use]
239 pub fn offset_px(&self) -> Option<f64> {
240 self.shift_px.map(|[dx, dy]| dx.hypot(dy))
241 }
242}
243
244#[derive(Debug, Clone, Copy)]
246pub struct SheetInputs<'a> {
247 pub frame_jpeg: &'a [u8],
249 pub camera_snapshot_url: &'a str,
251 pub calibration: &'a CameraCalibration,
253 pub sheet: &'a SheetOutline,
255 pub bed_z_mm: f64,
257}
258
259pub 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
312const OUTLINE_SEARCH_TOP_MM: u32 = 220;
315
316const OUTLINE_SEARCH_STEP_MM: u32 = 2;
320
321pub(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
385fn 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
411fn 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
438fn 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
451struct Gradients {
453 width: usize,
455 height: usize,
457 grey: Vec<f64>,
459 gx: Vec<f64>,
461 gy: Vec<f64>,
463}
464
465impl Gradients {
466 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 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 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
530pub(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
575struct Samples {
578 points: Vec<[f64; 2]>,
580 normals: Vec<[f64; 2]>,
582 edge: Vec<usize>,
584 edges: usize,
586 hole: Option<[f64; 2]>,
588}
589
590impl Samples {
591 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 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
669struct Measured {
671 unfitted: Option<UnjudgeableCause>,
673 support: f64,
675 edges_seen: usize,
677 offsets: Vec<Option<f64>>,
679 hole: Option<[f64; 2]>,
681 shift: Option<[f64; 2]>,
683 residual: Option<f64>,
685}
686
687fn 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
745fn 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
755fn 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
808fn 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
889fn 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 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
930fn 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
952fn 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}