printobserver-panels 0.20.2

Camera calibration, drift and alignment checks, and the check image's panels, for printobserver.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! The check image, as one JPEG: panels 1 and 2 at 1024x576, each under a
//! 40 px label band; and under them panel 3 at
//! [`PREVIOUS_WIDTH`]x[`PREVIOUS_HEIGHT`], its label in the column beside it.
//! Panel 3 is nine sixteenths of a full panel's width, the least that still
//! shows a part's place beside panel 1, so that the image costs a turn fewer
//! image tokens than the three full panels it replaced. The image carries no
//! text of the layer's: what panel 1's drawing means is told in the turn's
//! own text, from [`CheckImage::text`].
//!
//! 1. The current frame scaled whole, the current layer's whole plan drawn
//!    over it ([`crate::panel_one`]): what the job has sent bold in each
//!    kind's colour, what it has still to send thin and grey, thin dashes
//!    where the head or gantry may stand, and — when that layer lays supports
//!    alone — the nearest object layer below it in grey beneath, so the part
//!    still shows. The turn's text says the layer, its colour, the planned
//!    change nearest it, how far through it the job is, what is hidden, and
//!    what each colour drawn means.
//! 2. The current frame cropped to the active object's outline projected at
//!    the bed and at the current height, with a [`MARGIN_PX`] margin, widened
//!    to 16:9, never narrower than [`MIN_CROP_WIDTH_PX`] (so upscaled at most
//!    2x), clamped inside the frame; nothing drawn.
//! 3. The previous check's frame scaled whole, nothing drawn, or a
//!    placeholder on the print's first check.

use image::{Rgb, RgbImage, imageops::FilterType};
use imageproc::drawing::draw_filled_rect_mut;
use imageproc::rect::Rect;
use printobserver_core::{LayerFacts, LayerToolpath, ObjectOutline};
use printobserver_types::Timestamp;

use crate::calibration::CameraCalibration;
use crate::drift::{check_drift, check_frame};
use crate::error::ComposeError;
use crate::geometry::project_toolpath;
use crate::occlusion::Occluders;
use crate::panel_one;
use crate::text::draw_text;
use crate::view::ViewCorrection;

/// A panel's width.
pub const PANEL_WIDTH: u32 = 1024;
/// A panel's height.
pub const PANEL_HEIGHT: u32 = 576;
/// The label band above each panel.
pub const BAND_HEIGHT: u32 = 40;
/// Panel 3's width: the previous check's frame, scaled whole.
pub const PREVIOUS_WIDTH: u32 = 576;
/// Panel 3's height.
pub const PREVIOUS_HEIGHT: u32 = 324;
/// The whole image's height: panels 1 and 2 under their bands, and panel 3,
/// whose label stands beside it.
pub const IMAGE_HEIGHT: u32 = 2 * (BAND_HEIGHT + PANEL_HEIGHT) + PREVIOUS_HEIGHT;
/// The close-up's margin around the active object, in source pixels.
pub const MARGIN_PX: f64 = 48.0;
/// The close-up's least width, in source pixels.
pub const MIN_CROP_WIDTH_PX: f64 = 512.0;
/// The JPEG quality the image is written at.
const QUALITY: u8 = 90;
/// What panel 3 reads on a print's first check.
pub const NO_EARLIER_CHECK: &str = "no earlier check this print";

/// The grey the nearest object layer below a support-only layer is drawn in.
pub const BELOW_GREY: Rgb<u8> = Rgb([150, 150, 150]);
/// The label bands' background.
const BAND: Rgb<u8> = Rgb([24, 24, 24]);
/// The label text.
const TEXT: Rgb<u8> = Rgb([235, 235, 235]);

pub use crate::panel_one::colour_of;

/// What the check image is composed from.
#[derive(Debug, Clone, Copy)]
pub struct CheckImageInputs<'a> {
    /// The frame this check was given.
    pub current_jpeg: &'a [u8],
    /// When it was captured. Panel 1 is always the frame being checked, so
    /// its label names no time; the field is the one the previous frame's
    /// label is read against by the check that keeps both.
    pub current_at: Timestamp,
    /// The snapshot URL it came from.
    pub camera_snapshot_url: &'a str,
    /// The previous check's frame and when it was captured; absent on the
    /// print's first check.
    pub previous: Option<(&'a [u8], Timestamp)>,
    /// Every object's outline.
    pub outlines: &'a [ObjectOutline],
    /// The object being laid, an index into `outlines`.
    pub active_object: usize,
    /// The current layer's toolpath.
    pub toolpath: &'a LayerToolpath,
    /// The nearest object layer below, given when `toolpath` lays supports
    /// alone.
    pub object_layer_below: Option<&'a LayerToolpath>,
    /// The print's height, in millimetres.
    pub print_z_mm: f64,
    /// The printer's calibration.
    pub calibration: &'a CameraCalibration,
    /// The correction every drawn pixel goes through, taken from this print's
    /// own first layer. With one, the caller has judged the frame's view
    /// against its reference, and the composer judges no drift of its own;
    /// with none, the composer refuses a frame the drift check refuses.
    pub correction: Option<&'a ViewCorrection>,
    /// The job's file position, counted in the print's own spooled copy of
    /// its file: what splits the layer into sent and still to send. With
    /// none, the whole layer is drawn as sent.
    pub file_position_bytes: Option<u64>,
    /// What the turn's text says of the layer, when the index answers it.
    pub facts: Option<&'a LayerFacts>,
    /// Where the plan has had the nozzle over the moves the printer may still
    /// hold queued, in bed millimetres: where the head and gantry may stand.
    /// Empty when that is not known.
    pub head_trail_mm: &'a [[f64; 2]],
    /// Where the printer reported the head, in bed millimetres: the only
    /// place a head mark is drawn at.
    pub reported_head_mm: Option<[f64; 2]>,
}

/// The composed check image.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CheckImage {
    /// The JPEG.
    pub jpeg: Vec<u8>,
    /// Its width: [`PANEL_WIDTH`].
    pub width: u32,
    /// Its height: [`IMAGE_HEIGHT`].
    pub height: u32,
    /// Panel 2's source, `[x, y, w, h]` in current-frame pixels.
    pub close_up_source_rect: [u32; 4],
    /// What panel 1's drawing shows, in lines a check's turn is told: the
    /// layer's facts, what is hidden, and what each colour drawn means.
    pub text: Vec<String>,
}

/// Decode a frame: a JPEG, as a camera serves one, or a PNG, as a lossless
/// frame derived from one is kept. Anything else is undecodable.
pub(crate) fn decode(frame: &[u8]) -> Result<RgbImage, ComposeError> {
    let format = if frame.starts_with(b"\x89PNG\r\n\x1a\n") {
        image::ImageFormat::Png
    } else {
        image::ImageFormat::Jpeg
    };
    image::load_from_memory_with_format(frame, format)
        .map(|frame| frame.to_rgb8())
        .map_err(|error| ComposeError::Undecodable {
            detail: error.to_string(),
        })
}

/// Compose the check image.
///
/// # Errors
///
/// In the order they are checked: [`ComposeError::Undecodable`] for a frame
/// that is no JPEG; [`ComposeError::FrameMismatch`] for a current or previous
/// frame of another size, or a stream, other than the calibration's;
/// [`ComposeError::CameraMoved`] or [`ComposeError::DriftUnverified`] from
/// the drift check; and
/// [`ComposeError::OutlineOffFrame`] when neither the toolpath nor the active
/// object lands in the frame.
pub fn compose_check_image(inputs: &CheckImageInputs<'_>) -> Result<CheckImage, ComposeError> {
    let current = decode(inputs.current_jpeg)?;
    let size = [current.width(), current.height()];
    check_frame(inputs.calibration, size, inputs.camera_snapshot_url)?;
    if inputs.correction.is_none() {
        check_drift(inputs.calibration, &image::imageops::grayscale(&current))?;
    }
    let previous = inputs
        .previous
        .map(|(jpeg, at)| decode(jpeg).map(|frame| (frame, at)))
        .transpose()?;
    if let Some((frame, _)) = &previous {
        // Panel 3 is scaled by the current frame's factors, so a previous
        // frame of another size would be drawn distorted rather than refused.
        check_frame(
            inputs.calibration,
            [frame.width(), frame.height()],
            inputs.camera_snapshot_url,
        )?;
    }

    let (drawn, below) = drawn_pieces(inputs);
    let rect = close_up_rect(inputs, size);
    let in_frame = |[x, y]: [f64; 2]| {
        (0.0..f64::from(size[0])).contains(&x) && (0.0..f64::from(size[1])).contains(&y)
    };
    if rect.is_none() && !drawn.iter().chain(&below).any(|piece| in_frame(piece.from)) {
        return Err(ComposeError::OutlineOffFrame);
    }
    let rect = rect.unwrap_or_else(|| whole_width_rect(size));

    let mut image = RgbImage::from_pixel(PANEL_WIDTH, IMAGE_HEIGHT, BAND);
    let scale = f64::from(PANEL_WIDTH) / f64::from(size[0]);
    let scale_y = f64::from(PANEL_HEIGHT) / f64::from(size[1]);

    let (whole, text) = first_panel(inputs, &current, &drawn, &below, [scale, scale_y]);
    paste(&mut image, &whole, 0);
    band(
        &mut image,
        0,
        "1 NOW: this layer's plan, sent bold, to print grey",
    );

    paste(&mut image, &scaled(&current, Some(rect)), 1);
    band(&mut image, 1, "2 NOW: close-up, nothing drawn");

    let third = panel_top(2);
    if let Some((frame, at)) = &previous {
        let whole =
            image::imageops::resize(frame, PREVIOUS_WIDTH, PREVIOUS_HEIGHT, FilterType::Triangle);
        image::imageops::replace(&mut image, &whole, 0, i64::from(third));
        let local = at.as_utc().with_timezone(&chrono::Local).format("%H:%M:%S");
        beside_panel_three(
            &mut image,
            &[
                "3 PREVIOUS CHECK",
                &local.to_string(),
                "whole view,",
                "nothing drawn",
            ],
        );
    } else {
        draw_filled_rect_mut(
            &mut image,
            Rect::at(0, signed(third)).of_size(PREVIOUS_WIDTH, PREVIOUS_HEIGHT),
            Rgb([48, 48, 48]),
        );
        draw_text(
            &mut image,
            TEXT,
            40,
            signed(third + PREVIOUS_HEIGHT / 2 - 16),
            32.0,
            NO_EARLIER_CHECK,
        );
        beside_panel_three(&mut image, &["3 PREVIOUS CHECK:", "none"]);
    }

    let mut jpeg = Vec::new();
    image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, QUALITY)
        .encode_image(&image)
        .map_err(|error| ComposeError::Encode {
            detail: error.to_string(),
        })?;
    Ok(CheckImage {
        jpeg,
        width: PANEL_WIDTH,
        height: IMAGE_HEIGHT,
        close_up_source_rect: rect,
        text,
    })
}

/// Panel 1: the current frame scaled whole with the layer's plan drawn over
/// it, and the lines its turn is told of it.
fn first_panel(
    inputs: &CheckImageInputs<'_>,
    current: &RgbImage,
    drawn: &[crate::geometry::Projected],
    below: &[crate::geometry::Projected],
    [scale, scale_y]: [f64; 2],
) -> (RgbImage, Vec<String>) {
    let mut whole = scaled(current, None);
    let occluders = Occluders::along(inputs.calibration, inputs.head_trail_mm);
    let projector = inputs.calibration.projector();
    let project = |[x, y]: [f64; 2]| {
        projector
            .pixel([x, y, 0.0])
            .map(|pixel| inputs.correction.map_or(pixel, |c| c.apply(pixel)))
    };
    let reported_head_px = inputs.reported_head_mm.and_then(project);
    let painted = panel_one::draw(
        &mut whole,
        &panel_one::Plan {
            drawn,
            below,
            file_position_bytes: inputs.file_position_bytes,
            occluders: occluders.as_ref(),
            reported_head_px,
            scale: [scale, scale_y],
            project: &project,
        },
    );
    let text = panel_one::lines(
        inputs.facts,
        occluders.as_ref().map(Occluders::span_mm),
        painted,
        reported_head_px.is_some(),
    );
    (whole, text)
}

/// The current layer's toolpath and, when it lays supports alone, the object
/// layer below, projected and taken through the correction when there is one.
fn drawn_pieces(
    inputs: &CheckImageInputs<'_>,
) -> (
    Vec<crate::geometry::Projected>,
    Vec<crate::geometry::Projected>,
) {
    let projector = inputs.calibration.projector();
    let corrected = |mut pieces: Vec<crate::geometry::Projected>| {
        if let Some(correction) = inputs.correction {
            for piece in &mut pieces {
                piece.from = correction.apply(piece.from);
                piece.to = correction.apply(piece.to);
            }
        }
        pieces
    };
    let drawn = corrected(project_toolpath(
        &projector,
        inputs.toolpath,
        inputs.print_z_mm,
    ));
    let below = inputs
        .object_layer_below
        .map(|layer| corrected(project_toolpath(&projector, layer, inputs.print_z_mm)))
        .unwrap_or_default();
    (drawn, below)
}

/// A pixel row as the drawing calls take it.
fn signed(value: u32) -> i32 {
    i32::try_from(value).unwrap_or(i32::MAX)
}

/// Where panel `n`'s label starts: panel 1's band at the top, panel 2's below
/// panel 1, and panel 3's in the column beside panel 3, level with its top.
#[must_use]
pub const fn band_top(panel: u32) -> u32 {
    match panel {
        0 => 0,
        1 => BAND_HEIGHT + PANEL_HEIGHT,
        _ => panel_top(2),
    }
}

/// Where panel `n` itself starts: panels 1 and 2 under their bands, and
/// panel 3 straight under panel 2.
#[must_use]
pub const fn panel_top(panel: u32) -> u32 {
    match panel {
        0 => BAND_HEIGHT,
        1 => band_top(1) + BAND_HEIGHT,
        _ => panel_top(1) + PANEL_HEIGHT,
    }
}

/// Copy a panel under its band.
fn paste(image: &mut RgbImage, panel: &RgbImage, n: u32) {
    image::imageops::replace(image, panel, 0, i64::from(panel_top(n)));
}

/// A frame, or a rectangle of it, scaled to one panel.
fn scaled(frame: &RgbImage, rect: Option<[u32; 4]>) -> RgbImage {
    let source = match rect {
        Some([x, y, w, h]) => image::imageops::crop_imm(frame, x, y, w, h).to_image(),
        None => frame.clone(),
    };
    image::imageops::resize(&source, PANEL_WIDTH, PANEL_HEIGHT, FilterType::Triangle)
}

/// One label band's text.
fn band(image: &mut RgbImage, n: u32, text: &str) {
    draw_text(image, TEXT, 8, signed(band_top(n)) + 9, 20.0, text);
}

/// Panel 3's label, one line under another in the column beside it.
fn beside_panel_three(image: &mut RgbImage, lines: &[&str]) {
    let mut y = signed(panel_top(2)) + 9;
    for line in lines {
        draw_text(image, TEXT, signed(PREVIOUS_WIDTH) + 10, y, 20.0, line);
        y += 28;
    }
}

/// The whole frame's width at 16:9, centred: what panel 2 shows when the
/// active object lands nowhere in the frame.
fn whole_width_rect(size: [u32; 2]) -> [u32; 4] {
    fit_rect([0.0, 0.0, f64::from(size[0]), f64::from(size[1])], size)
}

/// The close-up's source rectangle: the box holding the active object's
/// outline projected at the bed and at the current height, with its margin,
/// widened to 16:9 and to the least width, clamped inside the frame. Nothing
/// when no vertex of the outline projects at all.
fn close_up_rect(inputs: &CheckImageInputs<'_>, size: [u32; 2]) -> Option<[u32; 4]> {
    let outline = inputs.outlines.get(inputs.active_object)?;
    let projector = inputs.calibration.projector();
    let points: Vec<[f64; 2]> = outline
        .hull_mm
        .iter()
        .flat_map(|vertex| {
            let (x, y) = (f64::from(vertex[0]), f64::from(vertex[1]));
            [
                projector.pixel([x, y, -inputs.print_z_mm]),
                projector.pixel([x, y, 0.0]),
            ]
        })
        .flatten()
        .map(|pixel| inputs.correction.map_or(pixel, |c| c.apply(pixel)))
        .collect();
    let first = points.first()?;
    let (mut x0, mut y0, mut x1, mut y1) = (first[0], first[1], first[0], first[1]);
    for [x, y] in &points {
        x0 = x0.min(*x);
        y0 = y0.min(*y);
        x1 = x1.max(*x);
        y1 = y1.max(*y);
    }
    let (w, h) = (f64::from(size[0]), f64::from(size[1]));
    if x1 < 0.0 || y1 < 0.0 || x0 >= w || y0 >= h {
        return None;
    }
    Some(fit_rect(
        [
            x0 - MARGIN_PX,
            y0 - MARGIN_PX,
            x1 + MARGIN_PX,
            y1 + MARGIN_PX,
        ],
        size,
    ))
}

/// A box `[x0, y0, x1, y1]` widened about its centre to 16:9 and to the least
/// width, then moved — and only if it must, shrunk at 16:9 — inside the frame.
fn fit_rect(bounds: [f64; 4], size: [u32; 2]) -> [u32; 4] {
    let (frame_w, frame_h) = (f64::from(size[0]), f64::from(size[1]));
    let centre = [
        f64::midpoint(bounds[0], bounds[2]),
        f64::midpoint(bounds[1], bounds[3]),
    ];
    let mut width = (bounds[2] - bounds[0])
        .max((bounds[3] - bounds[1]) * 16.0 / 9.0)
        .max(MIN_CROP_WIDTH_PX);
    width = width.min(frame_w).min(frame_h * 16.0 / 9.0);
    let height = width * 9.0 / 16.0;
    let x = (centre[0] - width / 2.0).clamp(0.0, frame_w - width);
    let y = (centre[1] - height / 2.0).clamp(0.0, frame_h - height);
    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "each is clamped inside the frame, whose size fits a u32"
    )]
    let whole = |value: f64| value.round() as u32;
    let (rx, ry) = (whole(x), whole(y));
    let rw = whole(width).min(size[0] - rx);
    let rh = whole(height).min(size[1] - ry);
    [rx, ry, rw, rh]
}