printobserver-panels 0.20.0

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
452
453
454
455
456
457
458
//! Panel 1: the current frame with the current layer's whole plan drawn over
//! it, split where the job's file position stands; and the lines the turn is
//! told of it, saying what the drawing shows and what each colour means. The
//! image itself carries no text of the layer's.
//!
//! Every segment the job has sent is drawn bold in its kind's colour ([`style`]):
//! walls and the like as lines, sparse infill as lines thick enough to see at
//! the panel's width, and solid and top solid infill at their own
//! extrusion width, part-transparent so the plastic's own colour shows
//! through. Every segment still to send is drawn thin and light grey under
//! them. A segment is sent once the file position has passed the end of the
//! line laying it, counted in the print's own spooled copy of its file, which
//! is the copy the printer's position counts.
//!
//! What the head or the gantry stands over wherever along the queued moves
//! the head is ([`Occluders`]) is drawn thin and dashed, in its kind's colour
//! once sent and grey before, rather than bold, and the text says how much of
//! the layer lies there and that it is not visible, and where the queued
//! moves reach. It is drawn rather than left out because a layer drawn
//! nowhere leaves nothing to hold a part against: a part off its walls, or
//! bare sheet inside them, then reads as a head in the way. No mark is drawn
//! for the head unless the printer reported where it is: the last move sent
//! can be far from it while the printer works through its queue.

use image::{GrayImage, Luma, Rgb, RgbImage};
use imageproc::drawing::{draw_hollow_circle_mut, draw_line_segment_mut, draw_polygon_mut};
use imageproc::point::Point;
use printobserver_core::{ExtrusionKind, LayerFacts};

use crate::geometry::Projected;
use crate::occlusion::Occluders;

/// The colour a segment the job has still to send is drawn in.
pub const TO_PRINT_GREY: Rgb<u8> = Rgb([215, 215, 215]);

/// How long each dash of a path the head or gantry hides is, and each
/// gap after it, in panel pixels.
pub const HIDDEN_DASH_PX: [f32; 2] = [4.0, 4.0];

/// The colour a reported head position is ringed in.
pub const HEAD_MARK: Rgb<u8> = Rgb([255, 255, 255]);

/// How wide sparse infill the job has sent is drawn, in panel pixels: wide
/// enough to see at the panel's 1024 px.
pub const SPARSE_WIDTH_PX: f32 = 3.0;

/// How wide a wall, overhang, support or other line the job has sent is
/// drawn, in panel pixels.
pub const LINE_WIDTH_PX: f32 = 2.0;

/// The width drawn for an extrusion the file states none for, in millimetres.
const NOMINAL_WIDTH_MM: f64 = 0.45;

/// The colour each kind is drawn in once sent.
#[must_use]
pub const fn colour_of(kind: ExtrusionKind) -> Rgb<u8> {
    match kind {
        ExtrusionKind::Wall => Rgb([255, 40, 40]),
        ExtrusionKind::SparseInfill => Rgb([70, 140, 255]),
        ExtrusionKind::SolidInfill => Rgb([255, 214, 0]),
        ExtrusionKind::TopSolidInfill => Rgb([255, 128, 0]),
        ExtrusionKind::Support => Rgb([0, 200, 255]),
        ExtrusionKind::Bridge => Rgb([255, 0, 255]),
        ExtrusionKind::Overhang => Rgb([0, 230, 0]),
        ExtrusionKind::Other => Rgb([255, 255, 255]),
    }
}

/// How a sent segment of one kind is drawn.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Stroke {
    /// A line this many panel pixels wide.
    Line(f32),
    /// The segment's own extrusion width, projected.
    Extrusion,
}

/// How a sent segment of each kind is drawn, and how opaque.
#[must_use]
pub const fn style(kind: ExtrusionKind) -> (Stroke, u8) {
    match kind {
        ExtrusionKind::SparseInfill => (Stroke::Line(SPARSE_WIDTH_PX), 230),
        ExtrusionKind::SolidInfill | ExtrusionKind::TopSolidInfill => (Stroke::Extrusion, 150),
        ExtrusionKind::Wall
        | ExtrusionKind::Bridge
        | ExtrusionKind::Overhang
        | ExtrusionKind::Support
        | ExtrusionKind::Other => (Stroke::Line(LINE_WIDTH_PX), 255),
    }
}

/// The order sent kinds are drawn in, the last on top: walls over the infill
/// they bound.
const DRAW_ORDER: [ExtrusionKind; 8] = [
    ExtrusionKind::SparseInfill,
    ExtrusionKind::SolidInfill,
    ExtrusionKind::TopSolidInfill,
    ExtrusionKind::Bridge,
    ExtrusionKind::Support,
    ExtrusionKind::Other,
    ExtrusionKind::Overhang,
    ExtrusionKind::Wall,
];

/// What each colour drawn means, as the turn is told it, in its order: each
/// kind, and the colour it is drawn in once sent, named.
pub const KEY: [(&str, ExtrusionKind, &str); 7] = [
    ("wall", ExtrusionKind::Wall, "red"),
    ("sparse infill", ExtrusionKind::SparseInfill, "blue"),
    ("solid infill", ExtrusionKind::SolidInfill, "yellow"),
    ("top solid", ExtrusionKind::TopSolidInfill, "orange"),
    ("bridge", ExtrusionKind::Bridge, "magenta"),
    ("support", ExtrusionKind::Support, "cyan"),
    ("overhang", ExtrusionKind::Overhang, "green"),
];

/// What panel 1 draws over its frame.
#[derive(Clone, Copy)]
pub(crate) struct Plan<'a> {
    /// The current layer's pieces, projected and corrected.
    pub(crate) drawn: &'a [Projected],
    /// The object layer below a support-only layer, drawn grey beneath.
    pub(crate) below: &'a [Projected],
    /// The job's file position, when known: with none, every segment is
    /// drawn as sent.
    pub(crate) file_position_bytes: Option<u64>,
    /// What hides the nozzle's plane wherever the nozzle is, when where it is
    /// can be bounded.
    pub(crate) occluders: Option<&'a Occluders>,
    /// The head's reported position, in source pixels.
    pub(crate) reported_head_px: Option<[f64; 2]>,
    /// Source pixels to panel pixels, in X and Y.
    pub(crate) scale: [f64; 2],
    /// Where a point of the nozzle's plane lands in the frame, in source
    /// pixels, through the correction when there is one.
    pub(crate) project: &'a dyn Fn([f64; 2]) -> Option<[f64; 2]>,
}

/// Whether a piece is sent at a file position.
const fn sent(piece: &Projected, position: Option<u64>) -> bool {
    match position {
        Some(position) => piece.ends_at <= position,
        None => true,
    }
}

/// What drawing panel 1 found: the share of the layer's path the head or
/// gantry hides.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Drawn {
    /// The path length under the head or gantry, in millimetres.
    pub(crate) hidden_mm: f64,
    /// The layer's whole path length, in millimetres.
    pub(crate) total_mm: f64,
}

/// A colour layer painted over a panel, with its own coverage, so that a
/// part-transparent stroke tints the frame rather than replacing it.
struct Overlay {
    /// What is painted.
    colour: RgbImage,
    /// How opaque, per pixel.
    alpha: GrayImage,
}

impl Overlay {
    /// Nothing painted over a panel of this size.
    fn over(panel: &RgbImage) -> Self {
        Self {
            colour: RgbImage::new(panel.width(), panel.height()),
            alpha: GrayImage::new(panel.width(), panel.height()),
        }
    }

    /// One stroke from `a` to `b`, `width` panel pixels wide.
    fn stroke(&mut self, a: [f32; 2], b: [f32; 2], width: f32, colour: Rgb<u8>, alpha: u8) {
        let length = (b[0] - a[0]).hypot(b[1] - a[1]);
        if width <= 1.5 || length < 1e-3 {
            draw_line_segment_mut(&mut self.colour, (a[0], a[1]), (b[0], b[1]), colour);
            draw_line_segment_mut(&mut self.alpha, (a[0], a[1]), (b[0], b[1]), Luma([alpha]));
            return;
        }
        let (nx, ny) = (
            -(b[1] - a[1]) / length * width / 2.0,
            (b[0] - a[0]) / length * width / 2.0,
        );
        #[expect(
            clippy::cast_possible_truncation,
            reason = "a panel pixel; one far off the panel is clipped by the drawing call"
        )]
        let at = |x: f32, y: f32| Point::new(x.round() as i32, y.round() as i32);
        let corners = [
            at(a[0] + nx, a[1] + ny),
            at(b[0] + nx, b[1] + ny),
            at(b[0] - nx, b[1] - ny),
            at(a[0] - nx, a[1] - ny),
        ];
        if corners[0] == corners[3] || corners[1] == corners[2] {
            draw_line_segment_mut(&mut self.colour, (a[0], a[1]), (b[0], b[1]), colour);
            draw_line_segment_mut(&mut self.alpha, (a[0], a[1]), (b[0], b[1]), Luma([alpha]));
            return;
        }
        draw_polygon_mut(&mut self.colour, &corners, colour);
        draw_polygon_mut(&mut self.alpha, &corners, Luma([alpha]));
    }

    /// A quadrilateral, its corners in panel pixels, filled.
    fn fill(&mut self, corners: [[f32; 2]; 4], colour: Rgb<u8>, alpha: u8) {
        #[expect(
            clippy::cast_possible_truncation,
            reason = "a panel pixel; one far off the panel is clipped by the drawing call"
        )]
        let points = corners.map(|[x, y]| Point::new(x.round() as i32, y.round() as i32));
        if points[0] == points[3] || points[1] == points[2] {
            let (a, b) = (corners[0], corners[1]);
            draw_line_segment_mut(&mut self.colour, (a[0], a[1]), (b[0], b[1]), colour);
            draw_line_segment_mut(&mut self.alpha, (a[0], a[1]), (b[0], b[1]), Luma([alpha]));
            return;
        }
        draw_polygon_mut(&mut self.colour, &points, colour);
        draw_polygon_mut(&mut self.alpha, &points, Luma([alpha]));
    }

    /// Blend what is painted over the panel.
    fn blend(&self, panel: &mut RgbImage) {
        for ((pixel, painted), Luma([alpha])) in panel
            .pixels_mut()
            .zip(self.colour.pixels())
            .zip(self.alpha.pixels())
        {
            if *alpha == 0 {
                continue;
            }
            let a = u16::from(*alpha);
            for channel in 0..3 {
                let mixed = (u16::from(pixel.0[channel]) * (255 - a)
                    + u16::from(painted.0[channel]) * a
                    + 127)
                    / 255;
                pixel.0[channel] = u8::try_from(mixed).unwrap_or(u8::MAX);
            }
        }
    }
}

/// A source pixel in panel pixels.
#[expect(
    clippy::cast_possible_truncation,
    reason = "a projected pixel is a few thousand at most; one far off the panel is clipped by the drawing call"
)]
fn at_panel([x, y]: [f64; 2], [sx, sy]: [f64; 2]) -> [f32; 2] {
    [(x * sx) as f32, (y * sy) as f32]
}

/// Draw panel 1's plan over its scaled frame.
pub(crate) fn draw(panel: &mut RgbImage, plan: &Plan<'_>) -> Drawn {
    let hidden = |piece: &Projected| {
        plan.occluders
            .is_some_and(|occluders| occluders.hides(piece.middle_mm))
    };
    let mut drawn = Drawn {
        hidden_mm: 0.0,
        total_mm: 0.0,
    };
    for piece in plan.drawn {
        drawn.total_mm += piece.length_mm;
        if hidden(piece) {
            drawn.hidden_mm += piece.length_mm;
        }
    }

    let mut overlay = Overlay::over(panel);
    let mut dashes = Dashes::default();
    for piece in plan.below {
        let (a, b) = (
            at_panel(piece.from, plan.scale),
            at_panel(piece.to, plan.scale),
        );
        if hidden(piece) {
            dashes.stroke(&mut overlay, a, b, crate::compose::BELOW_GREY);
        } else {
            overlay.stroke(a, b, 1.0, crate::compose::BELOW_GREY, 255);
        }
    }
    for piece in plan
        .drawn
        .iter()
        .filter(|piece| !sent(piece, plan.file_position_bytes) && !hidden(piece))
    {
        let (a, b) = (
            at_panel(piece.from, plan.scale),
            at_panel(piece.to, plan.scale),
        );
        overlay.stroke(a, b, 1.0, TO_PRINT_GREY, 200);
    }
    for piece in plan.drawn.iter().filter(|piece| hidden(piece)) {
        let (a, b) = (
            at_panel(piece.from, plan.scale),
            at_panel(piece.to, plan.scale),
        );
        let colour = if sent(piece, plan.file_position_bytes) {
            colour_of(piece.kind)
        } else {
            TO_PRINT_GREY
        };
        dashes.stroke(&mut overlay, a, b, colour);
    }
    for kind in DRAW_ORDER {
        let (stroke, alpha) = style(kind);
        for piece in plan.drawn.iter().filter(|piece| {
            piece.kind == kind && sent(piece, plan.file_position_bytes) && !hidden(piece)
        }) {
            let (a, b) = (
                at_panel(piece.from, plan.scale),
                at_panel(piece.to, plan.scale),
            );
            match stroke {
                Stroke::Line(width) => overlay.stroke(a, b, width, colour_of(kind), alpha),
                Stroke::Extrusion => match extrusion_corners(piece, plan) {
                    Some(corners) => overlay.fill(corners, colour_of(kind), alpha),
                    None => overlay.stroke(a, b, 1.0, colour_of(kind), alpha),
                },
            }
        }
    }
    overlay.blend(panel);
    if let Some(head) = plan.reported_head_px {
        mark_head(panel, at_panel(head, plan.scale));
    }
    drawn
}

/// A piece laid at its extrusion width, as the four corners of that strip on
/// the nozzle's plane projected into panel pixels: across the bed's own
/// millimetres, which the camera's oblique view foreshortens differently
/// from along them. Nothing when a corner does not project.
fn extrusion_corners(piece: &Projected, plan: &Plan<'_>) -> Option<[[f32; 2]; 4]> {
    let width_mm = if piece.width_mm > 0.0 {
        f64::from(piece.width_mm)
    } else {
        NOMINAL_WIDTH_MM
    };
    let [dx, dy] = piece.direction_mm;
    let (half_length, half_width) = (piece.length_mm / 2.0, width_mm / 2.0);
    let [mx, my] = piece.middle_mm;
    let corner = |along: f64, across: f64| {
        (plan.project)([mx + dx * along - dy * across, my + dy * along + dx * across])
            .map(|pixel| at_panel(pixel, plan.scale))
    };
    Some([
        corner(-half_length, half_width)?,
        corner(half_length, half_width)?,
        corner(half_length, -half_width)?,
        corner(-half_length, -half_width)?,
    ])
}

/// A dashed line drawn thin, its dashes carried on from one segment to the
/// next so that a path cut into many short segments still reads as dashed.
#[derive(Default)]
struct Dashes {
    /// How far along the dash pattern the last segment ended, in panel pixels.
    walked: f32,
}

impl Dashes {
    /// One segment from `a` to `b`, dashed.
    fn stroke(&mut self, overlay: &mut Overlay, a: [f32; 2], b: [f32; 2], colour: Rgb<u8>) {
        let [on, off] = HIDDEN_DASH_PX;
        let period = on + off;
        let length = (b[0] - a[0]).hypot(b[1] - a[1]);
        let mut along = 0.0_f32;
        while along < length {
            let phase = self.walked.rem_euclid(period);
            let (drawing, left) = if phase < on {
                (true, on - phase)
            } else {
                (false, period - phase)
            };
            let step = left.min(length - along);
            if drawing {
                let at = |t: f32| [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t];
                overlay.stroke(
                    at(along / length),
                    at((along + step) / length),
                    1.0,
                    colour,
                    255,
                );
            }
            along += step;
            self.walked += step;
        }
    }
}

/// Ring the head at its reported position.
fn mark_head(panel: &mut RgbImage, [x, y]: [f32; 2]) {
    #[expect(
        clippy::cast_possible_truncation,
        reason = "a panel pixel; one off the panel is clipped by the drawing call"
    )]
    let centre = (x.round() as i32, y.round() as i32);
    draw_hollow_circle_mut(panel, centre, 14, Rgb([0, 0, 0]));
    draw_hollow_circle_mut(panel, centre, 13, HEAD_MARK);
    draw_hollow_circle_mut(panel, centre, 12, HEAD_MARK);
}

/// The lines a check's turn is told of panel 1: the layer's facts, one line
/// of what is hidden and whether the head is marked, and one of what each
/// colour drawn means.
#[must_use]
pub(crate) fn lines(
    facts: Option<&LayerFacts>,
    queued_span_mm: Option<[[f64; 2]; 2]>,
    drawn: Drawn,
    head_marked: bool,
) -> Vec<String> {
    let mut lines = facts.map(LayerFacts::lines).unwrap_or_default();
    let head = if head_marked {
        "white ring: head as reported"
    } else {
        "no head mark: no position reported"
    };
    lines.push(format!("{}; {head}", hidden_line(queued_span_mm, drawn)));
    lines.push(key_line());
    lines
}

/// What each colour drawn means, in one line.
fn key_line() -> String {
    let kinds = KEY
        .iter()
        .map(|(name, _, colour)| format!("{colour} {name}"))
        .collect::<Vec<_>>()
        .join(", ");
    format!("colours, sent: {kinds}; thin grey: to print; dashed: hidden")
}

/// What the text says of the head and gantry: how much of the layer they
/// hide wherever along the queued moves the head is, and where those moves
/// reach.
fn hidden_line(queued_span_mm: Option<[[f64; 2]; 2]>, drawn: Drawn) -> String {
    let Some([[x0, x1], [y0, y1]]) = queued_span_mm else {
        return "head/gantry place unknown: any of the layer may be hidden".to_owned();
    };
    let reach = format!(
        "head somewhere along queued moves X {x0:.0} to {x1:.0}, Y {y0:.0} to {y1:.0} mm: \
         what it covers is not visible; judge plastic in view, the head seen is the head"
    );
    if drawn.hidden_mm <= 0.0 || drawn.total_mm <= 0.0 {
        return format!("head/gantry hide none of the layer wherever it is; {reach}");
    }
    let share = (100.0 * drawn.hidden_mm / drawn.total_mm)
        .round()
        .clamp(1.0, 100.0);
    format!("dashed, under head/gantry wherever it is: {share:.0}%, not visible; {reach}")
}