1use image::{Rgb, RgbImage, imageops::FilterType};
26use imageproc::drawing::draw_filled_rect_mut;
27use imageproc::rect::Rect;
28use printobserver_core::{LayerFacts, LayerToolpath, ObjectOutline};
29use printobserver_types::Timestamp;
30
31use crate::calibration::CameraCalibration;
32use crate::drift::{check_drift, check_frame};
33use crate::error::ComposeError;
34use crate::geometry::project_toolpath;
35use crate::occlusion::Occluders;
36use crate::panel_one;
37use crate::text::draw_text;
38use crate::view::ViewCorrection;
39
40pub const PANEL_WIDTH: u32 = 1024;
42pub const PANEL_HEIGHT: u32 = 576;
44pub const BAND_HEIGHT: u32 = 40;
46pub const PREVIOUS_WIDTH: u32 = 576;
48pub const PREVIOUS_HEIGHT: u32 = 324;
50pub const IMAGE_HEIGHT: u32 = 2 * (BAND_HEIGHT + PANEL_HEIGHT) + PREVIOUS_HEIGHT;
53pub const MARGIN_PX: f64 = 48.0;
55pub const MIN_CROP_WIDTH_PX: f64 = 512.0;
57const QUALITY: u8 = 90;
59pub const NO_EARLIER_CHECK: &str = "no earlier check this print";
61
62pub const BELOW_GREY: Rgb<u8> = Rgb([150, 150, 150]);
64const BAND: Rgb<u8> = Rgb([24, 24, 24]);
66const TEXT: Rgb<u8> = Rgb([235, 235, 235]);
68
69pub use crate::panel_one::colour_of;
70
71#[derive(Debug, Clone, Copy)]
73pub struct CheckImageInputs<'a> {
74 pub current_jpeg: &'a [u8],
76 pub current_at: Timestamp,
80 pub camera_snapshot_url: &'a str,
82 pub previous: Option<(&'a [u8], Timestamp)>,
85 pub outlines: &'a [ObjectOutline],
87 pub active_object: usize,
89 pub toolpath: &'a LayerToolpath,
91 pub object_layer_below: Option<&'a LayerToolpath>,
94 pub print_z_mm: f64,
96 pub calibration: &'a CameraCalibration,
98 pub correction: Option<&'a ViewCorrection>,
103 pub file_position_bytes: Option<u64>,
107 pub facts: Option<&'a LayerFacts>,
109 pub head_trail_mm: &'a [[f64; 2]],
113 pub reported_head_mm: Option<[f64; 2]>,
116}
117
118#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct CheckImage {
121 pub jpeg: Vec<u8>,
123 pub width: u32,
125 pub height: u32,
127 pub close_up_source_rect: [u32; 4],
129 pub text: Vec<String>,
132}
133
134pub(crate) fn decode(frame: &[u8]) -> Result<RgbImage, ComposeError> {
137 let format = if frame.starts_with(b"\x89PNG\r\n\x1a\n") {
138 image::ImageFormat::Png
139 } else {
140 image::ImageFormat::Jpeg
141 };
142 image::load_from_memory_with_format(frame, format)
143 .map(|frame| frame.to_rgb8())
144 .map_err(|error| ComposeError::Undecodable {
145 detail: error.to_string(),
146 })
147}
148
149pub fn compose_check_image(inputs: &CheckImageInputs<'_>) -> Result<CheckImage, ComposeError> {
161 let current = decode(inputs.current_jpeg)?;
162 let size = [current.width(), current.height()];
163 check_frame(inputs.calibration, size, inputs.camera_snapshot_url)?;
164 if inputs.correction.is_none() {
165 check_drift(inputs.calibration, &image::imageops::grayscale(¤t))?;
166 }
167 let previous = inputs
168 .previous
169 .map(|(jpeg, at)| decode(jpeg).map(|frame| (frame, at)))
170 .transpose()?;
171 if let Some((frame, _)) = &previous {
172 check_frame(
175 inputs.calibration,
176 [frame.width(), frame.height()],
177 inputs.camera_snapshot_url,
178 )?;
179 }
180
181 let (drawn, below) = drawn_pieces(inputs);
182 let rect = close_up_rect(inputs, size);
183 let in_frame = |[x, y]: [f64; 2]| {
184 (0.0..f64::from(size[0])).contains(&x) && (0.0..f64::from(size[1])).contains(&y)
185 };
186 if rect.is_none() && !drawn.iter().chain(&below).any(|piece| in_frame(piece.from)) {
187 return Err(ComposeError::OutlineOffFrame);
188 }
189 let rect = rect.unwrap_or_else(|| whole_width_rect(size));
190
191 let mut image = RgbImage::from_pixel(PANEL_WIDTH, IMAGE_HEIGHT, BAND);
192 let scale = f64::from(PANEL_WIDTH) / f64::from(size[0]);
193 let scale_y = f64::from(PANEL_HEIGHT) / f64::from(size[1]);
194
195 let (whole, text) = first_panel(inputs, ¤t, &drawn, &below, [scale, scale_y]);
196 paste(&mut image, &whole, 0);
197 band(
198 &mut image,
199 0,
200 "1 NOW: this layer's plan, sent bold, to print grey",
201 );
202
203 paste(&mut image, &scaled(¤t, Some(rect)), 1);
204 band(&mut image, 1, "2 NOW: close-up, nothing drawn");
205
206 let third = panel_top(2);
207 if let Some((frame, at)) = &previous {
208 let whole =
209 image::imageops::resize(frame, PREVIOUS_WIDTH, PREVIOUS_HEIGHT, FilterType::Triangle);
210 image::imageops::replace(&mut image, &whole, 0, i64::from(third));
211 let local = at.as_utc().with_timezone(&chrono::Local).format("%H:%M:%S");
212 beside_panel_three(
213 &mut image,
214 &[
215 "3 PREVIOUS CHECK",
216 &local.to_string(),
217 "whole view,",
218 "nothing drawn",
219 ],
220 );
221 } else {
222 draw_filled_rect_mut(
223 &mut image,
224 Rect::at(0, signed(third)).of_size(PREVIOUS_WIDTH, PREVIOUS_HEIGHT),
225 Rgb([48, 48, 48]),
226 );
227 draw_text(
228 &mut image,
229 TEXT,
230 40,
231 signed(third + PREVIOUS_HEIGHT / 2 - 16),
232 32.0,
233 NO_EARLIER_CHECK,
234 );
235 beside_panel_three(&mut image, &["3 PREVIOUS CHECK:", "none"]);
236 }
237
238 let mut jpeg = Vec::new();
239 image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, QUALITY)
240 .encode_image(&image)
241 .map_err(|error| ComposeError::Encode {
242 detail: error.to_string(),
243 })?;
244 Ok(CheckImage {
245 jpeg,
246 width: PANEL_WIDTH,
247 height: IMAGE_HEIGHT,
248 close_up_source_rect: rect,
249 text,
250 })
251}
252
253fn first_panel(
256 inputs: &CheckImageInputs<'_>,
257 current: &RgbImage,
258 drawn: &[crate::geometry::Projected],
259 below: &[crate::geometry::Projected],
260 [scale, scale_y]: [f64; 2],
261) -> (RgbImage, Vec<String>) {
262 let mut whole = scaled(current, None);
263 let occluders = Occluders::along(inputs.calibration, inputs.head_trail_mm);
264 let projector = inputs.calibration.projector();
265 let project = |[x, y]: [f64; 2]| {
266 projector
267 .pixel([x, y, 0.0])
268 .map(|pixel| inputs.correction.map_or(pixel, |c| c.apply(pixel)))
269 };
270 let reported_head_px = inputs.reported_head_mm.and_then(project);
271 let painted = panel_one::draw(
272 &mut whole,
273 &panel_one::Plan {
274 drawn,
275 below,
276 file_position_bytes: inputs.file_position_bytes,
277 occluders: occluders.as_ref(),
278 reported_head_px,
279 scale: [scale, scale_y],
280 project: &project,
281 },
282 );
283 let text = panel_one::lines(
284 inputs.facts,
285 occluders.as_ref().map(Occluders::span_mm),
286 painted,
287 reported_head_px.is_some(),
288 );
289 (whole, text)
290}
291
292fn drawn_pieces(
295 inputs: &CheckImageInputs<'_>,
296) -> (
297 Vec<crate::geometry::Projected>,
298 Vec<crate::geometry::Projected>,
299) {
300 let projector = inputs.calibration.projector();
301 let corrected = |mut pieces: Vec<crate::geometry::Projected>| {
302 if let Some(correction) = inputs.correction {
303 for piece in &mut pieces {
304 piece.from = correction.apply(piece.from);
305 piece.to = correction.apply(piece.to);
306 }
307 }
308 pieces
309 };
310 let drawn = corrected(project_toolpath(
311 &projector,
312 inputs.toolpath,
313 inputs.print_z_mm,
314 ));
315 let below = inputs
316 .object_layer_below
317 .map(|layer| corrected(project_toolpath(&projector, layer, inputs.print_z_mm)))
318 .unwrap_or_default();
319 (drawn, below)
320}
321
322fn signed(value: u32) -> i32 {
324 i32::try_from(value).unwrap_or(i32::MAX)
325}
326
327#[must_use]
330pub const fn band_top(panel: u32) -> u32 {
331 match panel {
332 0 => 0,
333 1 => BAND_HEIGHT + PANEL_HEIGHT,
334 _ => panel_top(2),
335 }
336}
337
338#[must_use]
341pub const fn panel_top(panel: u32) -> u32 {
342 match panel {
343 0 => BAND_HEIGHT,
344 1 => band_top(1) + BAND_HEIGHT,
345 _ => panel_top(1) + PANEL_HEIGHT,
346 }
347}
348
349fn paste(image: &mut RgbImage, panel: &RgbImage, n: u32) {
351 image::imageops::replace(image, panel, 0, i64::from(panel_top(n)));
352}
353
354fn scaled(frame: &RgbImage, rect: Option<[u32; 4]>) -> RgbImage {
356 let source = match rect {
357 Some([x, y, w, h]) => image::imageops::crop_imm(frame, x, y, w, h).to_image(),
358 None => frame.clone(),
359 };
360 image::imageops::resize(&source, PANEL_WIDTH, PANEL_HEIGHT, FilterType::Triangle)
361}
362
363fn band(image: &mut RgbImage, n: u32, text: &str) {
365 draw_text(image, TEXT, 8, signed(band_top(n)) + 9, 20.0, text);
366}
367
368fn beside_panel_three(image: &mut RgbImage, lines: &[&str]) {
370 let mut y = signed(panel_top(2)) + 9;
371 for line in lines {
372 draw_text(image, TEXT, signed(PREVIOUS_WIDTH) + 10, y, 20.0, line);
373 y += 28;
374 }
375}
376
377fn whole_width_rect(size: [u32; 2]) -> [u32; 4] {
380 fit_rect([0.0, 0.0, f64::from(size[0]), f64::from(size[1])], size)
381}
382
383fn close_up_rect(inputs: &CheckImageInputs<'_>, size: [u32; 2]) -> Option<[u32; 4]> {
388 let outline = inputs.outlines.get(inputs.active_object)?;
389 let projector = inputs.calibration.projector();
390 let points: Vec<[f64; 2]> = outline
391 .hull_mm
392 .iter()
393 .flat_map(|vertex| {
394 let (x, y) = (f64::from(vertex[0]), f64::from(vertex[1]));
395 [
396 projector.pixel([x, y, -inputs.print_z_mm]),
397 projector.pixel([x, y, 0.0]),
398 ]
399 })
400 .flatten()
401 .map(|pixel| inputs.correction.map_or(pixel, |c| c.apply(pixel)))
402 .collect();
403 let first = points.first()?;
404 let (mut x0, mut y0, mut x1, mut y1) = (first[0], first[1], first[0], first[1]);
405 for [x, y] in &points {
406 x0 = x0.min(*x);
407 y0 = y0.min(*y);
408 x1 = x1.max(*x);
409 y1 = y1.max(*y);
410 }
411 let (w, h) = (f64::from(size[0]), f64::from(size[1]));
412 if x1 < 0.0 || y1 < 0.0 || x0 >= w || y0 >= h {
413 return None;
414 }
415 Some(fit_rect(
416 [
417 x0 - MARGIN_PX,
418 y0 - MARGIN_PX,
419 x1 + MARGIN_PX,
420 y1 + MARGIN_PX,
421 ],
422 size,
423 ))
424}
425
426fn fit_rect(bounds: [f64; 4], size: [u32; 2]) -> [u32; 4] {
429 let (frame_w, frame_h) = (f64::from(size[0]), f64::from(size[1]));
430 let centre = [
431 f64::midpoint(bounds[0], bounds[2]),
432 f64::midpoint(bounds[1], bounds[3]),
433 ];
434 let mut width = (bounds[2] - bounds[0])
435 .max((bounds[3] - bounds[1]) * 16.0 / 9.0)
436 .max(MIN_CROP_WIDTH_PX);
437 width = width.min(frame_w).min(frame_h * 16.0 / 9.0);
438 let height = width * 9.0 / 16.0;
439 let x = (centre[0] - width / 2.0).clamp(0.0, frame_w - width);
440 let y = (centre[1] - height / 2.0).clamp(0.0, frame_h - height);
441 #[expect(
442 clippy::cast_possible_truncation,
443 clippy::cast_sign_loss,
444 reason = "each is clamped inside the frame, whose size fits a u32"
445 )]
446 let whole = |value: f64| value.round() as u32;
447 let (rx, ry) = (whole(x), whole(y));
448 let rw = whole(width).min(size[0] - rx);
449 let rh = whole(height).min(size[1] - ry);
450 [rx, ry, rw, rh]
451}