printobserver_panels/alignment.rs
1//! The per-print check that the projection lands on the printed first layer.
2//!
3//! A projection can be wrong with the camera unmoved, so each print verifies
4//! it once its first object layer is down. The first object layer's whole
5//! toolpath — walls, brim and infill — is projected at the frame's print
6//! height and sampled every [`SAMPLE_PX`]; a band is sampled [`BAND_PX`]
7//! outside the projected path's convex hull. For every shift of the two
8//! within [`SEARCH_PX`], the score is how far the frame's mean grey on the
9//! path lies from its mean grey on the band — printed material against the
10//! sheet around it — smoothed over neighbouring shifts. `offset_px` is the
11//! length of the best shift: how far the printed first layer lies from where
12//! the calibration puts it. A nearest-edge score was measured and rejected:
13//! a first layer's infill and the parts beside it put an edge near almost
14//! any point, so a projection 49 px off scored as well as a right one.
15//!
16//! A first layer is *clearly found* ([`judge_first_layer`]) when its offset is
17//! at most the calibration's `alignment_max_offset_px` and the peak smoothed
18//! contrast — `match_strength`, in grey levels — is at least
19//! [`CLEARLY_FOUND_CONTRAST`], on a frame where the part is not covered. Every
20//! empty bed and every misplaced projection measured was found at the search's
21//! edge, and every visible layer within 21 px at a contrast of at least 19. A
22//! frame anything else is *inconclusive*, never a failure: the next check's
23//! frame is judged again.
24//!
25//! The toolhead itself is high-contrast and scores as a found layer, so
26//! coverage is not an image score. A frame is covered when the first layer is
27//! small enough for the toolhead to hide ([`TOOLHEAD_HIDES_MM`]) and the
28//! nozzle's planned position, projected at the nozzle's plane, lies within
29//! [`TOOLHEAD_MARGIN_PX`] of the first layer's hull projected where the bed has
30//! carried it at the frame's print height. As a small part grows, the bed
31//! carries its first layer down and away from the head in the camera's view; a
32//! large part's hull keeps the nozzle inside it at any height, while the head
33//! hides only a little of it.
34
35use image::GrayImage;
36use printobserver_core::LayerToolpath;
37
38use crate::calibration::CameraCalibration;
39use crate::compose::decode;
40use crate::drift::check_frame;
41use crate::error::ComposeError;
42use crate::geometry::{band_outside, convex_hull, project_toolpath, sample_along, signed_distance};
43use printobserver_types::schemars::JsonSchema;
44use printobserver_types::serde::{Deserialize, Serialize};
45
46/// How far apart the path's samples are, in pixels.
47pub const SAMPLE_PX: f64 = 4.0;
48
49/// How far outside the path's hull the band lies, in pixels.
50pub const BAND_PX: f64 = 10.0;
51
52/// How far the printed layer is looked for from where it was projected, in
53/// pixels: the largest `offset_px` there is.
54pub const SEARCH_PX: i32 = 60;
55
56/// The spacing of the shifts tried, in pixels.
57const SHIFT_STEP: i32 = 2;
58
59/// How many shifts either side each score is averaged over.
60const SMOOTHING: i32 = 2;
61
62/// The grey blur the frame is read through, in pixels.
63const BLUR_SIGMA: f32 = 1.5;
64
65/// The least peak smoothed contrast, in grey levels, at which a first layer
66/// counts as clearly found.
67pub const CLEARLY_FOUND_CONTRAST: f64 = 15.0;
68
69/// How near the projected nozzle may lie to the projected first layer's hull,
70/// in pixels, for the part to count as covered by the toolhead.
71///
72/// On the first shifted print the covered checks lay within 5.4 px of the hull
73/// and the visible ones at least 15.3 px from it; 10 px sits midway. Calling a
74/// covered part visible is the dangerous direction — a toolhead scored as the
75/// layer — and calling a visible part covered only waits a check longer.
76pub const TOOLHEAD_MARGIN_PX: f64 = 10.0;
77
78/// How far above its first layer a pass may stand for its found shift to be
79/// taken as the print's correction, in millimetres: one layer.
80///
81/// Higher, the first layer lies under the part's own body and the search scores
82/// that body, so its shift is the part's projected height rather than a camera
83/// shift: on the first shifted print a pass at 6.8 mm found -20 px of it, and
84/// drawing through that floated the outline above a healthy part, which the
85/// agent paused for. A pass from a taller frame corrects by nothing, which its
86/// offset — at most the calibration's threshold — bounds.
87pub const CORRECTION_TAKEN_WITHIN_MM: f64 = 0.3;
88
89/// The correction a pass with this search's `found` shift puts in force: the
90/// shift itself when the frame stood within [`CORRECTION_TAKEN_WITHIN_MM`] of
91/// the first layer, and no shift from any taller frame.
92#[must_use]
93pub fn correction_shift(
94 found: &AlignmentVerdict,
95 first_layer: &LayerToolpath,
96 print_z_mm: f64,
97) -> [f64; 2] {
98 if print_z_mm - f64::from(first_layer.z_mm) <= CORRECTION_TAKEN_WITHIN_MM + 1e-6 {
99 found.shift_px
100 } else {
101 [0.0, 0.0]
102 }
103}
104
105/// The largest first layer the toolhead can hide, in bed millimetres: the
106/// longer side of its extent on the bed. A first layer larger than this is
107/// never covered, and is judged on the image score alone.
108///
109/// The 20 mm box the margin was measured on spans 18.9 mm; the smallest other
110/// verified first layer, a jar top's, spans 82.5 mm, which the toolhead's hot
111/// end and duct cannot hide as they hide the box.
112pub const TOOLHEAD_HIDES_MM: f64 = 50.0;
113
114/// What the alignment check is given.
115#[derive(Debug, Clone, Copy)]
116pub struct AlignmentInputs<'a> {
117 /// One frame, past the first object layer.
118 pub frame_jpeg: &'a [u8],
119 /// The snapshot URL it came from.
120 pub camera_snapshot_url: &'a str,
121 /// The first object layer's toolpath.
122 pub first_layer: &'a LayerToolpath,
123 /// The print's height when the frame was taken, in millimetres.
124 pub print_z_mm: f64,
125 /// The printer's calibration.
126 pub calibration: &'a CameraCalibration,
127}
128
129/// How far the printed first layer lies from its projection.
130#[derive(Debug, Clone, Copy, PartialEq)]
131// llmlint: ignore[invalid_states_unrepresentable] See suppressions.toml.
132pub struct AlignmentVerdict {
133 /// The offset, in calibration pixels: the length of `shift_px`.
134 pub offset_px: f64,
135 /// The best shift, `[dx, dy]` calibration pixels: where the printed layer
136 /// lies from its projection.
137 pub shift_px: [f64; 2],
138 /// The peak smoothed contrast between the path and the band around it, in
139 /// grey levels.
140 pub match_strength: f64,
141 /// Whether the layer is clearly found: the offset at most the
142 /// calibration's `alignment_max_offset_px` and the contrast at least
143 /// [`CLEARLY_FOUND_CONTRAST`].
144 pub passed: bool,
145}
146
147/// Why a first layer was not clearly found on a frame.
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
149#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
150#[schemars(crate = "printobserver_types::schemars")]
151pub enum InconclusiveReason {
152 /// The toolhead stands over the part.
153 Covered,
154 /// The layer is not found within the threshold at the contrast it needs:
155 /// an empty bed, a layer found at the search's edge, or one projecting
156 /// nowhere in the frame.
157 NotClearlyFound,
158}
159
160impl InconclusiveReason {
161 /// The reason as the record spells it.
162 #[must_use]
163 pub const fn as_str(self) -> &'static str {
164 match self {
165 Self::Covered => "covered",
166 Self::NotClearlyFound => "not_clearly_found",
167 }
168 }
169}
170
171/// What one frame says of the first layer's place.
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub enum FirstLayerVerdict {
174 /// It is clearly found.
175 Passed,
176 /// It cannot be told on this frame; a later one is judged again.
177 Inconclusive(InconclusiveReason),
178}
179
180/// One judgement of the first layer on one frame.
181#[derive(Debug, Clone, Copy, PartialEq)]
182pub struct FirstLayerJudgement {
183 /// What it came to.
184 pub verdict: FirstLayerVerdict,
185 /// The search's finding, absent when the layer projects nowhere in the
186 /// frame.
187 pub found: Option<AlignmentVerdict>,
188}
189
190/// What the first-layer judgement is given beyond the alignment check's
191/// inputs.
192#[derive(Debug, Clone, Copy)]
193pub struct FirstLayerInputs<'a> {
194 /// The alignment check's inputs.
195 pub alignment: AlignmentInputs<'a>,
196 /// Where the plan has the nozzle at the frame's file position, in bed
197 /// millimetres; absent when the plan places it nowhere.
198 pub nozzle_xy_mm: Option<[f64; 2]>,
199}
200
201/// Judge whether one frame clearly finds the first layer, on the uncorrected
202/// projection, and whether the toolhead covers the part.
203///
204/// # Errors
205///
206/// [`ComposeError::FrameMismatch`] for a frame of another size or stream than
207/// the calibration's, and [`ComposeError::Undecodable`] for one that is no
208/// JPEG.
209pub fn judge_first_layer(
210 inputs: &FirstLayerInputs<'_>,
211) -> Result<FirstLayerJudgement, ComposeError> {
212 let alignment = &inputs.alignment;
213 let found = match verify_first_layer_alignment(alignment) {
214 Ok(found) => found,
215 Err(ComposeError::OutlineOffFrame) => {
216 return Ok(FirstLayerJudgement {
217 verdict: FirstLayerVerdict::Inconclusive(InconclusiveReason::NotClearlyFound),
218 found: None,
219 });
220 }
221 Err(other) => return Err(other),
222 };
223 let verdict = if covered(inputs) {
224 FirstLayerVerdict::Inconclusive(InconclusiveReason::Covered)
225 } else if found.passed {
226 FirstLayerVerdict::Passed
227 } else {
228 FirstLayerVerdict::Inconclusive(InconclusiveReason::NotClearlyFound)
229 };
230 Ok(FirstLayerJudgement {
231 verdict,
232 found: Some(found),
233 })
234}
235
236/// How far the projected nozzle lies outside the projected first layer's
237/// hull, in pixels, negative inside: what [`TOOLHEAD_MARGIN_PX`] is held
238/// against. Nothing when the plan places the nozzle nowhere, or either does
239/// not project.
240#[must_use]
241pub fn nozzle_from_first_layer_px(inputs: &FirstLayerInputs<'_>) -> Option<f64> {
242 let [x, y] = inputs.nozzle_xy_mm?;
243 let alignment = &inputs.alignment;
244 let projector = alignment.calibration.projector();
245 let nozzle = projector.pixel([x, y, 0.0])?;
246 let pieces = project_toolpath(&projector, alignment.first_layer, alignment.print_z_mm);
247 let hull = convex_hull(&sample_along(&pieces, SAMPLE_PX));
248 (hull.len() >= 3).then(|| signed_distance(nozzle, &hull))
249}
250
251/// The longer side of a first layer's extent on the bed, in millimetres.
252#[must_use]
253pub fn first_layer_span_mm(first_layer: &LayerToolpath) -> f64 {
254 let mut bounds: Option<[f64; 4]> = None;
255 for segment in &first_layer.segments {
256 for [x, y] in [segment.from_mm, segment.to_mm] {
257 let (x, y) = (f64::from(x), f64::from(y));
258 bounds = Some(bounds.map_or([x, y, x, y], |[x0, y0, x1, y1]| {
259 [x0.min(x), y0.min(y), x1.max(x), y1.max(y)]
260 }));
261 }
262 }
263 bounds.map_or(0.0, |[x0, y0, x1, y1]| (x1 - x0).max(y1 - y0))
264}
265
266/// Whether the toolhead covers the part on the frame: a first layer small
267/// enough to hide, with the projected nozzle near it.
268fn covered(inputs: &FirstLayerInputs<'_>) -> bool {
269 first_layer_span_mm(inputs.alignment.first_layer) <= TOOLHEAD_HIDES_MM
270 && nozzle_from_first_layer_px(inputs).is_some_and(|distance| distance <= TOOLHEAD_MARGIN_PX)
271}
272
273/// Find how far the printed first layer lies from where the calibration puts
274/// it, and whether that is within the calibration's threshold.
275///
276/// # Errors
277///
278/// [`ComposeError::FrameMismatch`] for a frame of another size or stream than
279/// the calibration's, [`ComposeError::Undecodable`] for one that is no JPEG,
280/// and [`ComposeError::OutlineOffFrame`] when no point of the layer lands in
281/// the frame.
282pub fn verify_first_layer_alignment(
283 inputs: &AlignmentInputs<'_>,
284) -> Result<AlignmentVerdict, ComposeError> {
285 let frame = decode(inputs.frame_jpeg)?;
286 check_frame(
287 inputs.calibration,
288 [frame.width(), frame.height()],
289 inputs.camera_snapshot_url,
290 )?;
291 let grey =
292 imageproc::filter::gaussian_blur_f32(&image::imageops::grayscale(&frame), BLUR_SIGMA);
293 let pieces = project_toolpath(
294 &inputs.calibration.projector(),
295 inputs.first_layer,
296 inputs.print_z_mm,
297 );
298 let (w, h) = (f64::from(frame.width()), f64::from(frame.height()));
299 let path: Vec<[f64; 2]> = sample_along(&pieces, SAMPLE_PX)
300 .into_iter()
301 .filter(|[x, y]| (0.0..w).contains(x) && (0.0..h).contains(y))
302 .collect();
303 if path.len() < 3 {
304 return Err(ComposeError::OutlineOffFrame);
305 }
306 let band = band_outside(&convex_hull(&path), BAND_PX, SAMPLE_PX);
307 let (match_strength, dx, dy) = best_shift(&grey, &path, &band);
308 let shift_px = [f64::from(dx), f64::from(dy)];
309 let offset_px = shift_px[0].hypot(shift_px[1]);
310 Ok(AlignmentVerdict {
311 offset_px,
312 shift_px,
313 match_strength,
314 passed: offset_px <= inputs.calibration.alignment_max_offset_px
315 && match_strength >= CLEARLY_FOUND_CONTRAST,
316 })
317}
318
319/// The shift at which the path and the band contrast most, and that
320/// contrast, smoothed.
321fn best_shift(grey: &GrayImage, path: &[[f64; 2]], band: &[[f64; 2]]) -> (f64, i32, i32) {
322 let side = usize::try_from(2 * SEARCH_PX / SHIFT_STEP + 1).unwrap_or(1);
323 let index = |shift: i32| usize::try_from((shift + SEARCH_PX) / SHIFT_STEP).unwrap_or(0);
324 let mut contrast = vec![0.0_f64; side * side];
325 let shifts = || (-SEARCH_PX..=SEARCH_PX).step_by(usize::try_from(SHIFT_STEP).unwrap_or(1));
326 for dx in shifts() {
327 for dy in shifts() {
328 let inside = mean_at(grey, path, dx, dy);
329 let outside = mean_at(grey, band, dx, dy);
330 contrast[index(dy) * side + index(dx)] = (inside - outside).abs();
331 }
332 }
333 let mut best = (f64::NEG_INFINITY, 0, 0);
334 for dx in shifts() {
335 for dy in shifts() {
336 if dx * dx + dy * dy > SEARCH_PX * SEARCH_PX {
337 continue;
338 }
339 let mut sum = 0.0;
340 let mut count = 0.0;
341 for ox in -SMOOTHING..=SMOOTHING {
342 for oy in -SMOOTHING..=SMOOTHING {
343 let x = (index(dx).cast_signed() + isize::try_from(ox).unwrap_or(0))
344 .clamp(0, side.cast_signed() - 1)
345 .cast_unsigned();
346 let y = (index(dy).cast_signed() + isize::try_from(oy).unwrap_or(0))
347 .clamp(0, side.cast_signed() - 1)
348 .cast_unsigned();
349 sum += contrast[y * side + x];
350 count += 1.0;
351 }
352 }
353 let score = sum / count;
354 if score > best.0 {
355 best = (score, dx, dy);
356 }
357 }
358 }
359 best
360}
361
362/// The mean grey at points shifted by `(dx, dy)`, each clamped into the frame.
363fn mean_at(grey: &GrayImage, points: &[[f64; 2]], dx: i32, dy: i32) -> f64 {
364 if points.is_empty() {
365 return 0.0;
366 }
367 let (w, h) = (f64::from(grey.width() - 1), f64::from(grey.height() - 1));
368 let mut sum = 0.0;
369 for [x, y] in points {
370 #[expect(
371 clippy::cast_possible_truncation,
372 clippy::cast_sign_loss,
373 reason = "clamped into the frame, whose size fits a u32"
374 )]
375 let (px, py) = (
376 (x + f64::from(dx)).round().clamp(0.0, w) as u32,
377 (y + f64::from(dy)).round().clamp(0.0, h) as u32,
378 );
379 sum += f64::from(grey.get_pixel(px, py).0[0]);
380 }
381 #[expect(
382 clippy::cast_precision_loss,
383 reason = "a path holds at most some tens of thousands of samples"
384 )]
385 let count = points.len() as f64;
386 sum / count
387}