1use std::path::{Path, PathBuf};
15use std::sync::atomic::{AtomicU64, Ordering};
16
17use std::sync::Arc;
18
19use printobserver_core::{CheckImageRequest, CheckImages, GcodeIndex, ImageUse, ShownImage};
20use printobserver_panels::{
21 CameraCalibration, CheckImage, CheckImageInputs, ComposeError, WHOLE_FRAME_HEIGHT,
22 WHOLE_FRAME_WIDTH, compose_check_image, whole_frame,
23};
24use printobserver_types::{PrintId, Timestamp};
25
26use crate::alignment::{AlignmentFailure, Alignments, PreviousCheck, PrintAlignment};
27
28static WRITES: AtomicU64 = AtomicU64::new(0);
31
32pub const CHECK_IMAGES_DIRECTORY: &str = "check-images";
34
35#[derive(Debug, Clone)]
37pub struct WholeFrames {
38 directory: PathBuf,
40}
41
42impl WholeFrames {
43 #[must_use]
45 pub fn under(state_dir: &Path) -> Self {
46 Self {
47 directory: state_dir.join(CHECK_IMAGES_DIRECTORY),
48 }
49 }
50
51 fn destination(&self, frame: &Path) -> PathBuf {
54 let named = |part: Option<&std::ffi::OsStr>| {
55 part.map_or_else(String::new, |part| part.to_string_lossy().into_owned())
56 };
57 let parent = named(frame.parent().and_then(Path::file_name));
58 let file = named(frame.file_name());
59 self.directory.join(format!(
60 "{parent}-{file}-{WHOLE_FRAME_WIDTH}x{WHOLE_FRAME_HEIGHT}.jpg"
61 ))
62 }
63}
64
65impl CheckImages for WholeFrames {
66 fn check_image(&self, _print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String> {
67 let destination = self.destination(frame);
68 if destination.is_file() {
69 return Ok(destination);
70 }
71 let bytes = std::fs::read(frame)
72 .map_err(|error| format!("{} is unreadable: {error}", frame.display()))?;
73 let scaled = whole_frame(&bytes).map_err(|error| error.to_string())?;
74 if !scaled.scaled {
75 return Ok(frame.to_path_buf());
76 }
77 write_image(&self.directory, &destination, &scaled.jpeg)?;
78 Ok(destination)
79 }
80}
81
82fn write_image(directory: &Path, destination: &Path, bytes: &[u8]) -> Result<(), String> {
86 std::fs::create_dir_all(directory)
87 .map_err(|error| format!("{} cannot be made: {error}", directory.display()))?;
88 let partial = destination.with_extension(format!(
89 "{}-{}.partial",
90 std::process::id(),
91 WRITES.fetch_add(1, Ordering::Relaxed)
92 ));
93 let written =
94 std::fs::write(&partial, bytes).and_then(|()| std::fs::rename(&partial, destination));
95 written.map_err(|error| {
96 let _ = std::fs::remove_file(&partial);
98 format!("{} cannot be written: {error}", destination.display())
99 })
100}
101
102pub const COMPOSITE_NOTE: &str = "the three-panel check image";
105
106pub const WHOLE_FRAME_NOTE: &str = "the whole camera frame";
108
109#[derive(Debug, Clone, PartialEq)]
111pub enum WholeFrameReason {
112 NoPrint,
115 NoCalibration,
117 NoStream,
120 NoPosition,
123 NoObject,
126 NoLayer,
128 ToolpathUnread(String),
130 AlignmentPending,
132 AlignmentUnavailable,
134 AlignmentFailed(AlignmentFailure),
136 Refused(ComposeError),
138}
139
140impl core::fmt::Display for WholeFrameReason {
141 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
142 match self {
143 Self::NoPrint => formatter
144 .write_str("no print is named, so there is no planned toolpath to draw on it"),
145 Self::NoCalibration => formatter.write_str("no camera calibration is configured"),
146 Self::NoStream => formatter.write_str(
147 "no camera snapshot address is configured, so the frame's stream is unknown",
148 ),
149 Self::NoPosition => formatter.write_str(
150 "the print's G-code index gives no file position for this check",
151 ),
152 Self::NoObject => formatter.write_str(
153 "the print's G-code names no extruded object laid at this point",
154 ),
155 Self::NoLayer => formatter.write_str("the print's G-code names no layer at this point"),
156 Self::ToolpathUnread(detail) => write!(
157 formatter,
158 "the layer's planned toolpath could not be read from the print's spool: {detail}"
159 ),
160 Self::AlignmentPending => formatter.write_str(
161 "the print's first-layer alignment is pending: its first object layer is not down, or no frame of it has been judged yet",
162 ),
163 Self::AlignmentUnavailable => {
164 formatter.write_str("the print's G-code lays no object to align")
165 }
166 Self::AlignmentFailed(AlignmentFailure::Offset { offset_px }) => write!(
167 formatter,
168 "the print's first-layer alignment failed: the printed first layer lies {offset_px:.1} px from where the calibration projects it"
169 ),
170 Self::AlignmentFailed(AlignmentFailure::Resolution { expected, got }) => write!(
171 formatter,
172 "the print's first-layer alignment failed: the camera's frames are {}x{} and the calibration's {}x{}",
173 got[0], got[1], expected[0], expected[1]
174 ),
175 Self::AlignmentFailed(AlignmentFailure::Stream) => formatter.write_str(
176 "the print's first-layer alignment failed: the camera is not the stream the calibration was fitted on",
177 ),
178 Self::Refused(error) => error.fmt(formatter),
179 }
180 }
181}
182
183#[must_use]
185pub fn whole_frame_note(reason: &WholeFrameReason) -> String {
186 format!(
187 "{WHOLE_FRAME_NOTE}, scaled to fit {WHOLE_FRAME_WIDTH}x{WHOLE_FRAME_HEIGHT} and uncropped, because {reason}"
188 )
189}
190
191const CAMERA_HOLDS: &str = "the camera does not shift in regular operation and the drawing already accounts for the bed's travel, so ";
195
196#[must_use]
208pub fn composite_note(
209 made_for: ImageUse,
210 current_at: Timestamp,
211 previous_at: Option<Timestamp>,
212) -> String {
213 let (current, previous, moved) = match (made_for, previous_at) {
214 (ImageUse::Look, at) => (
215 "this layer's planned toolpath drawn on the frame".to_owned(),
216 if at.is_none() {
217 "panel 3 empty, no earlier check's frame being at hand".to_owned()
218 } else {
219 "panel 3 the previous check's frame".to_owned()
220 },
221 String::new(),
222 ),
223 (ImageUse::Check, None) => (
224 format!(
225 "this check's own frame, captured {current_at}, with this layer's planned toolpath drawn on it"
226 ),
227 "panel 3 empty, no earlier check's frame being at hand".to_owned(),
228 format!(
229 "; {CAMERA_HOLDS}a part off its drawn walls in panel 1 has moved unless there is strong evidence otherwise, and no later frame undoes that"
230 ),
231 ),
232 (ImageUse::Check, Some(at)) => (
233 format!(
234 "this check's own frame, captured {current_at}, with this layer's planned toolpath drawn on it"
235 ),
236 format!("panel 3 the previous check's frame, captured {at}"),
237 format!(
238 "; {CAMERA_HOLDS}a part off its drawn walls in panel 1, or moved since panel 3, has moved unless there is strong evidence otherwise, and no later frame undoes that"
239 ),
240 ),
241 };
242 format!(
243 "{COMPOSITE_NOTE}, {}x{}: panel 1 {current}, panel 2 a close-up of the part being printed, {previous}{moved}",
244 printobserver_panels::compose::PANEL_WIDTH,
245 printobserver_panels::compose::IMAGE_HEIGHT
246 )
247}
248
249#[derive(Debug, Clone, Copy)]
252pub struct PlanAt<'a> {
253 pub index: &'a GcodeIndex,
255 pub file_position_bytes: u64,
257}
258
259pub fn compose_at(
270 plan: PlanAt<'_>,
271 current: (&[u8], Timestamp),
272 previous: Option<(&[u8], Timestamp)>,
273 camera_snapshot_url: &str,
274 calibration: &CameraCalibration,
275) -> Result<CheckImage, WholeFrameReason> {
276 let index = plan.index;
277 let position = plan.file_position_bytes;
278 let active_object = index
279 .object_at(position)
280 .filter(|object| *object < index.object_outlines().len())
281 .ok_or(WholeFrameReason::NoObject)?;
282 let layer = index.layer_at(position).ok_or(WholeFrameReason::NoLayer)?;
283 let print_z_mm = index.layer_z_mm(layer).ok_or(WholeFrameReason::NoLayer)?;
284 let unread =
285 |error: printobserver_core::SpoolError| WholeFrameReason::ToolpathUnread(error.to_string());
286 let toolpath = index.layer_toolpath(layer).map_err(unread)?;
287 let below = if toolpath.carries_object_extrusion() {
288 None
289 } else {
290 index
291 .object_layer_at_or_below(layer)
292 .map(|below| index.layer_toolpath(below))
293 .transpose()
294 .map_err(unread)?
295 };
296 compose_check_image(&CheckImageInputs {
297 current_jpeg: current.0,
298 current_at: current.1,
299 camera_snapshot_url,
300 previous,
301 outlines: index.object_outlines(),
302 active_object,
303 toolpath: &toolpath,
304 object_layer_below: below.as_ref(),
305 print_z_mm,
306 calibration,
307 })
308 .map_err(WholeFrameReason::Refused)
309}
310
311pub struct PanelImages {
314 whole: WholeFrames,
316 alignments: Arc<Alignments>,
318 camera_snapshot_url: Option<String>,
321}
322
323impl core::fmt::Debug for PanelImages {
324 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
325 formatter
326 .debug_struct("PanelImages")
327 .field("whole", &self.whole)
328 .field("camera_snapshot_url", &self.camera_snapshot_url)
329 .finish_non_exhaustive()
330 }
331}
332
333impl PanelImages {
334 #[must_use]
336 pub fn new(
337 state_dir: &Path,
338 alignments: Arc<Alignments>,
339 camera_snapshot_url: Option<String>,
340 ) -> Self {
341 Self {
342 whole: WholeFrames::under(state_dir),
343 alignments,
344 camera_snapshot_url,
345 }
346 }
347
348 fn whole_frame(&self, frame: &Path, reason: &WholeFrameReason) -> Result<ShownImage, String> {
350 Ok(ShownImage {
351 path: self.whole.check_image(None, frame)?,
352 note: Some(whole_frame_note(reason)),
353 composite: false,
354 })
355 }
356
357 fn composite(
360 &self,
361 print_id: PrintId,
362 request: &CheckImageRequest<'_>,
363 previous: Option<&PreviousCheck>,
364 ) -> Result<Result<ShownImage, WholeFrameReason>, String> {
365 let Some(calibration) = self.alignments.calibration() else {
366 return Ok(Err(WholeFrameReason::NoCalibration));
367 };
368 let Some(url) = self.camera_snapshot_url.as_deref() else {
369 return Ok(Err(WholeFrameReason::NoStream));
370 };
371 let Some(plan) = &request.plan else {
372 return Ok(Err(WholeFrameReason::NoPosition));
373 };
374 let at = PlanAt {
375 index: &plan.index,
376 file_position_bytes: plan.file_position_bytes,
377 };
378 if at.index.object_at(at.file_position_bytes).is_none()
379 || at.index.object_outlines().is_empty()
380 {
381 return Ok(Err(WholeFrameReason::NoObject));
382 }
383 if at.index.layer_at(at.file_position_bytes).is_none() {
384 return Ok(Err(WholeFrameReason::NoLayer));
385 }
386 match self.alignments.print_alignment(print_id) {
387 PrintAlignment::Passed { .. } => {}
388 PrintAlignment::Pending => return Ok(Err(WholeFrameReason::AlignmentPending)),
389 PrintAlignment::Unavailable => {
390 return Ok(Err(WholeFrameReason::AlignmentUnavailable));
391 }
392 PrintAlignment::Failed { reason } => {
393 return Ok(Err(WholeFrameReason::AlignmentFailed(reason)));
394 }
395 }
396 let current = std::fs::read(request.frame)
397 .map_err(|error| format!("{} is unreadable: {error}", request.frame.display()))?;
398 let earlier = previous.and_then(|check| {
402 std::fs::read(&check.frame)
403 .ok()
404 .filter(|bytes| whole_frame(bytes).is_ok())
405 .map(|bytes| (bytes, check.captured_at))
406 });
407 let composed = match compose_at(
408 at,
409 (¤t, request.captured_at),
410 earlier.as_ref().map(|(bytes, at)| (bytes.as_slice(), *at)),
411 url,
412 calibration,
413 ) {
414 Ok(composed) => composed,
415 Err(WholeFrameReason::Refused(
421 ComposeError::Undecodable { detail } | ComposeError::Encode { detail },
422 )) => return Err(detail),
423 Err(reason) => return Ok(Err(reason)),
424 };
425 let destination = self.composite_destination(request.frame, previous);
426 write_image(&self.whole.directory, &destination, &composed.jpeg)?;
427 Ok(Ok(ShownImage {
428 path: destination,
429 note: Some(composite_note(
430 request.made_for,
431 request.captured_at,
432 earlier.as_ref().map(|(_, at)| *at),
433 )),
434 composite: true,
435 }))
436 }
437
438 fn composite_destination(&self, frame: &Path, previous: Option<&PreviousCheck>) -> PathBuf {
441 let named = |frame: &Path| {
442 let part = |part: Option<&std::ffi::OsStr>| {
443 part.map_or_else(String::new, |part| part.to_string_lossy().into_owned())
444 };
445 format!(
446 "{}-{}",
447 part(frame.parent().and_then(Path::file_name)),
448 part(frame.file_name())
449 )
450 };
451 let after = previous.map_or_else(|| "first".to_owned(), |check| named(&check.frame));
452 self.whole
453 .directory
454 .join(format!("{}-composite-after-{after}.jpg", named(frame)))
455 }
456}
457
458impl CheckImages for PanelImages {
459 fn check_image(&self, print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String> {
460 self.whole.check_image(print_id, frame)
461 }
462
463 fn composes(&self, print_id: PrintId) -> bool {
464 self.alignments.calibration().is_some()
465 && self.camera_snapshot_url.is_some()
466 && matches!(
467 self.alignments.print_alignment(print_id),
468 PrintAlignment::Passed { .. }
469 )
470 }
471
472 fn shown_image(&self, request: &CheckImageRequest<'_>) -> Result<ShownImage, String> {
473 let Some(print_id) = request.print_id else {
474 return self.whole_frame(request.frame, &WholeFrameReason::NoPrint);
475 };
476 let previous = self.alignments.previous_check(print_id);
477 let shown = match self.composite(print_id, request, previous.as_ref())? {
478 Ok(composite) => composite,
479 Err(reason) => self.whole_frame(request.frame, &reason)?,
480 };
481 if request.made_for == ImageUse::Check {
482 self.alignments.record_check(
483 print_id,
484 &PreviousCheck {
485 frame: request.frame.to_path_buf(),
486 captured_at: request.captured_at,
487 },
488 );
489 }
490 Ok(shown)
491 }
492}