1use std::path::{Path, PathBuf};
22use std::sync::atomic::{AtomicU64, Ordering};
23
24use std::sync::Arc;
25
26use printobserver_core::check_image::PlanPosition;
27use printobserver_core::{CheckImageRequest, CheckImages, GcodeIndex, ImageUse, ShownImage};
28use printobserver_panels::growth::MIN_RISE_MM;
29use printobserver_panels::{
30 CameraCalibration, CheckImage, CheckImageInputs, ComposeError, GrowthInputs,
31 WHOLE_FRAME_HEIGHT, WHOLE_FRAME_WIDTH, compose_check_image, measure_growth, whole_frame,
32};
33use printobserver_types::{PrintId, Timestamp};
34
35use crate::alignment::{AlignmentFailure, Alignments, CheckedFrame, PreviousCheck, PrintAlignment};
36
37static WRITES: AtomicU64 = AtomicU64::new(0);
40
41pub const CHECK_IMAGES_DIRECTORY: &str = "check-images";
43
44#[derive(Debug, Clone)]
46pub struct WholeFrames {
47 directory: PathBuf,
49}
50
51impl WholeFrames {
52 #[must_use]
54 pub fn under(state_dir: &Path) -> Self {
55 Self {
56 directory: state_dir.join(CHECK_IMAGES_DIRECTORY),
57 }
58 }
59
60 fn destination(&self, frame: &Path) -> PathBuf {
63 let named = |part: Option<&std::ffi::OsStr>| {
64 part.map_or_else(String::new, |part| part.to_string_lossy().into_owned())
65 };
66 let parent = named(frame.parent().and_then(Path::file_name));
67 let file = named(frame.file_name());
68 self.directory.join(format!(
69 "{parent}-{file}-{WHOLE_FRAME_WIDTH}x{WHOLE_FRAME_HEIGHT}.jpg"
70 ))
71 }
72}
73
74impl CheckImages for WholeFrames {
75 fn check_image(&self, _print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String> {
76 let destination = self.destination(frame);
77 if destination.is_file() {
78 return Ok(destination);
79 }
80 let bytes = std::fs::read(frame)
81 .map_err(|error| format!("{} is unreadable: {error}", frame.display()))?;
82 let scaled = whole_frame(&bytes).map_err(|error| error.to_string())?;
83 if !scaled.scaled {
84 return Ok(frame.to_path_buf());
85 }
86 write_image(&self.directory, &destination, &scaled.jpeg)?;
87 Ok(destination)
88 }
89}
90
91fn write_image(directory: &Path, destination: &Path, bytes: &[u8]) -> Result<(), String> {
95 std::fs::create_dir_all(directory)
96 .map_err(|error| format!("{} cannot be made: {error}", directory.display()))?;
97 let partial = destination.with_extension(format!(
98 "{}-{}.partial",
99 std::process::id(),
100 WRITES.fetch_add(1, Ordering::Relaxed)
101 ));
102 let written =
103 std::fs::write(&partial, bytes).and_then(|()| std::fs::rename(&partial, destination));
104 written.map_err(|error| {
105 let _ = std::fs::remove_file(&partial);
107 format!("{} cannot be written: {error}", destination.display())
108 })
109}
110
111pub const COMPOSITE_NOTE: &str = "the three-panel check image";
114
115pub const WHOLE_FRAME_NOTE: &str = "the whole camera frame";
117
118#[derive(Debug, Clone, PartialEq)]
120pub enum WholeFrameReason {
121 NoPrint,
124 NoCalibration,
126 NoStream,
129 NoPosition,
132 NoObject,
135 NoLayer,
137 ToolpathUnread(String),
139 AlignmentPending,
141 AlignmentUnavailable,
143 AlignmentFailed(AlignmentFailure),
145 Refused(ComposeError),
147}
148
149impl core::fmt::Display for WholeFrameReason {
150 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
151 match self {
152 Self::NoPrint => formatter
153 .write_str("no print is named, so there is no planned toolpath to draw on it"),
154 Self::NoCalibration => formatter.write_str("no camera calibration is configured"),
155 Self::NoStream => formatter.write_str(
156 "no camera snapshot address is configured, so the frame's stream is unknown",
157 ),
158 Self::NoPosition => formatter.write_str(
159 "the print's G-code index gives no file position for this check",
160 ),
161 Self::NoObject => formatter.write_str(
162 "the print's G-code names no extruded object laid at this point",
163 ),
164 Self::NoLayer => formatter.write_str("the print's G-code names no layer at this point"),
165 Self::ToolpathUnread(detail) => write!(
166 formatter,
167 "the layer's planned toolpath could not be read from the print's spool: {detail}"
168 ),
169 Self::AlignmentPending => formatter.write_str(
170 "the print's first-layer alignment is pending: its first object layer is not down, or no frame of it has been judged yet",
171 ),
172 Self::AlignmentUnavailable => {
173 formatter.write_str("the print's G-code lays no object to align")
174 }
175 Self::AlignmentFailed(AlignmentFailure::Offset { offset_px }) => write!(
176 formatter,
177 "the print's first-layer alignment failed: the printed first layer lies {offset_px:.1} px from where the calibration projects it"
178 ),
179 Self::AlignmentFailed(AlignmentFailure::Resolution { expected, got }) => write!(
180 formatter,
181 "the print's first-layer alignment failed: the camera's frames are {}x{} and the calibration's {}x{}",
182 got[0], got[1], expected[0], expected[1]
183 ),
184 Self::AlignmentFailed(AlignmentFailure::Stream) => formatter.write_str(
185 "the print's first-layer alignment failed: the camera is not the stream the calibration was fitted on",
186 ),
187 Self::Refused(error) => error.fmt(formatter),
188 }
189 }
190}
191
192#[must_use]
194pub fn whole_frame_note(reason: &WholeFrameReason) -> String {
195 format!(
196 "{WHOLE_FRAME_NOTE}, scaled to fit {WHOLE_FRAME_WIDTH}x{WHOLE_FRAME_HEIGHT} and uncropped, because {reason}"
197 )
198}
199
200const CAMERA_HOLDS: &str = "the camera does not shift in regular operation and the drawing already accounts for the bed's travel, so ";
204
205#[must_use]
217pub fn composite_note(
218 made_for: ImageUse,
219 current_at: Timestamp,
220 previous_at: Option<Timestamp>,
221) -> String {
222 let (current, previous, moved) = match (made_for, previous_at) {
223 (ImageUse::Look, at) => (
224 "this layer's planned toolpath drawn on the frame".to_owned(),
225 if at.is_none() {
226 "panel 3 empty, no earlier check's frame being at hand".to_owned()
227 } else {
228 "panel 3 the previous check's frame".to_owned()
229 },
230 String::new(),
231 ),
232 (ImageUse::Check, None) => (
233 format!(
234 "this check's own frame, captured {current_at}, with this layer's planned toolpath drawn on it"
235 ),
236 "panel 3 empty, no earlier check's frame being at hand".to_owned(),
237 format!(
238 "; {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"
239 ),
240 ),
241 (ImageUse::Check, Some(at)) => (
242 format!(
243 "this check's own frame, captured {current_at}, with this layer's planned toolpath drawn on it"
244 ),
245 format!("panel 3 the previous check's frame, captured {at}"),
246 format!(
247 "; {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"
248 ),
249 ),
250 };
251 format!(
252 "{COMPOSITE_NOTE}, {}x{}: panel 1 {current}, panel 2 a close-up of the part being printed, {previous}{moved}",
253 printobserver_panels::compose::PANEL_WIDTH,
254 printobserver_panels::compose::IMAGE_HEIGHT
255 )
256}
257
258#[must_use]
262pub fn not_grown_note(since: Timestamp, rise_mm: f64) -> String {
263 format!(
264 "; measured against the check frame captured {since}, {rise_mm:.1} mm lower in the plan: the parts this layer lays have not risen as planned, sitting where that frame had them, carried down with the bed, so nothing has been laid on them since"
265 )
266}
267
268fn plan_z(plan: &PlanPosition) -> Option<f64> {
270 plan.index
271 .layer_at(plan.file_position_bytes)
272 .and_then(|layer| plan.index.layer_z_mm(layer))
273}
274
275#[derive(Debug, Clone, Copy)]
278pub struct PlanAt<'a> {
279 pub index: &'a GcodeIndex,
281 pub file_position_bytes: u64,
283}
284
285pub fn compose_at(
296 plan: PlanAt<'_>,
297 current: (&[u8], Timestamp),
298 previous: Option<(&[u8], Timestamp)>,
299 camera_snapshot_url: &str,
300 calibration: &CameraCalibration,
301) -> Result<CheckImage, WholeFrameReason> {
302 let index = plan.index;
303 let position = plan.file_position_bytes;
304 let active_object = index
305 .object_at(position)
306 .filter(|object| *object < index.object_outlines().len())
307 .ok_or(WholeFrameReason::NoObject)?;
308 let layer = index.layer_at(position).ok_or(WholeFrameReason::NoLayer)?;
309 let print_z_mm = index.layer_z_mm(layer).ok_or(WholeFrameReason::NoLayer)?;
310 let unread =
311 |error: printobserver_core::SpoolError| WholeFrameReason::ToolpathUnread(error.to_string());
312 let toolpath = index.layer_toolpath(layer).map_err(unread)?;
313 let below = if toolpath.carries_object_extrusion() {
314 None
315 } else {
316 index
317 .object_layer_at_or_below(layer)
318 .map(|below| index.layer_toolpath(below))
319 .transpose()
320 .map_err(unread)?
321 };
322 compose_check_image(&CheckImageInputs {
323 current_jpeg: current.0,
324 current_at: current.1,
325 camera_snapshot_url,
326 previous,
327 outlines: index.object_outlines(),
328 active_object,
329 toolpath: &toolpath,
330 object_layer_below: below.as_ref(),
331 print_z_mm,
332 calibration,
333 })
334 .map_err(WholeFrameReason::Refused)
335}
336
337pub struct PanelImages {
340 whole: WholeFrames,
342 alignments: Arc<Alignments>,
344 camera_snapshot_url: Option<String>,
347}
348
349impl core::fmt::Debug for PanelImages {
350 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
351 formatter
352 .debug_struct("PanelImages")
353 .field("whole", &self.whole)
354 .field("camera_snapshot_url", &self.camera_snapshot_url)
355 .finish_non_exhaustive()
356 }
357}
358
359impl PanelImages {
360 #[must_use]
362 pub fn new(
363 state_dir: &Path,
364 alignments: Arc<Alignments>,
365 camera_snapshot_url: Option<String>,
366 ) -> Self {
367 Self {
368 whole: WholeFrames::under(state_dir),
369 alignments,
370 camera_snapshot_url,
371 }
372 }
373
374 fn whole_frame(&self, frame: &Path, reason: &WholeFrameReason) -> Result<ShownImage, String> {
376 Ok(ShownImage {
377 path: self.whole.check_image(None, frame)?,
378 note: Some(whole_frame_note(reason)),
379 composite: false,
380 })
381 }
382
383 fn composite(
386 &self,
387 print_id: PrintId,
388 request: &CheckImageRequest<'_>,
389 previous: Option<&PreviousCheck>,
390 ) -> Result<Result<ShownImage, WholeFrameReason>, String> {
391 let Some(calibration) = self.alignments.calibration() else {
392 return Ok(Err(WholeFrameReason::NoCalibration));
393 };
394 let Some(url) = self.camera_snapshot_url.as_deref() else {
395 return Ok(Err(WholeFrameReason::NoStream));
396 };
397 let Some(plan) = &request.plan else {
398 return Ok(Err(WholeFrameReason::NoPosition));
399 };
400 let at = PlanAt {
401 index: &plan.index,
402 file_position_bytes: plan.file_position_bytes,
403 };
404 if at.index.object_at(at.file_position_bytes).is_none()
405 || at.index.object_outlines().is_empty()
406 {
407 return Ok(Err(WholeFrameReason::NoObject));
408 }
409 if at.index.layer_at(at.file_position_bytes).is_none() {
410 return Ok(Err(WholeFrameReason::NoLayer));
411 }
412 match self.alignments.print_alignment(print_id) {
413 PrintAlignment::Passed { .. } => {}
414 PrintAlignment::Pending => return Ok(Err(WholeFrameReason::AlignmentPending)),
415 PrintAlignment::Unavailable => {
416 return Ok(Err(WholeFrameReason::AlignmentUnavailable));
417 }
418 PrintAlignment::Failed { reason } => {
419 return Ok(Err(WholeFrameReason::AlignmentFailed(reason)));
420 }
421 }
422 let current = std::fs::read(request.frame)
423 .map_err(|error| format!("{} is unreadable: {error}", request.frame.display()))?;
424 let earlier = previous.and_then(|check| {
428 std::fs::read(&check.frame)
429 .ok()
430 .filter(|bytes| whole_frame(bytes).is_ok())
431 .map(|bytes| (bytes, check.captured_at))
432 });
433 let composed = match compose_at(
434 at,
435 (¤t, request.captured_at),
436 earlier.as_ref().map(|(bytes, at)| (bytes.as_slice(), *at)),
437 url,
438 calibration,
439 ) {
440 Ok(composed) => composed,
441 Err(WholeFrameReason::Refused(
447 ComposeError::Undecodable { detail } | ComposeError::Encode { detail },
448 )) => return Err(detail),
449 Err(reason) => return Ok(Err(reason)),
450 };
451 let destination = self.composite_destination(request.frame, previous);
452 write_image(&self.whole.directory, &destination, &composed.jpeg)?;
453 let mut note = composite_note(
454 request.made_for,
455 request.captured_at,
456 earlier.as_ref().map(|(_, at)| *at),
457 );
458 if request.made_for == ImageUse::Check
459 && let Some(clause) = self.growth_clause(print_id, plan, ¤t, url, calibration)
460 {
461 note.push_str(&clause);
462 }
463 Ok(Ok(ShownImage {
464 path: destination,
465 note: Some(note),
466 composite: true,
467 }))
468 }
469
470 fn growth_clause(
477 &self,
478 print_id: PrintId,
479 plan: &PlanPosition,
480 current: &[u8],
481 url: &str,
482 calibration: &CameraCalibration,
483 ) -> Option<String> {
484 let layer = plan.index.layer_at(plan.file_position_bytes)?;
485 let print_z_mm = plan.index.layer_z_mm(layer)?;
486 let reference = self
487 .alignments
488 .growth_reference(print_id, print_z_mm, MIN_RISE_MM)?;
489 let earlier = std::fs::read(&reference.frame).ok()?;
490 let toolpath = plan.index.layer_toolpath(layer).ok()?;
491 let measured = measure_growth(&GrowthInputs {
492 earlier_jpeg: &earlier,
493 earlier_print_z_mm: reference.print_z_mm,
494 current_jpeg: current,
495 current_print_z_mm: print_z_mm,
496 camera_snapshot_url: url,
497 toolpath: &toolpath,
498 calibration,
499 })
500 .ok()??;
501 let not_grown = measured.not_grown();
502 eprintln!(
503 "printobserver: print {print_id}: growth from Z {:.1} ({}) to Z {print_z_mm:.1}: carried {:.2}, held {:.2}, {:.0}% carried over {} samples {:.1} px apart: {}",
504 reference.print_z_mm,
505 reference.captured_at,
506 measured.carried,
507 measured.held,
508 measured.carried_share * 100.0,
509 measured.samples,
510 measured.separation_px,
511 if not_grown { "not grown" } else { "no verdict" }
512 );
513 not_grown.then(|| not_grown_note(reference.captured_at, print_z_mm - reference.print_z_mm))
514 }
515
516 fn composite_destination(&self, frame: &Path, previous: Option<&PreviousCheck>) -> PathBuf {
519 let named = |frame: &Path| {
520 let part = |part: Option<&std::ffi::OsStr>| {
521 part.map_or_else(String::new, |part| part.to_string_lossy().into_owned())
522 };
523 format!(
524 "{}-{}",
525 part(frame.parent().and_then(Path::file_name)),
526 part(frame.file_name())
527 )
528 };
529 let after = previous.map_or_else(|| "first".to_owned(), |check| named(&check.frame));
530 self.whole
531 .directory
532 .join(format!("{}-composite-after-{after}.jpg", named(frame)))
533 }
534}
535
536impl CheckImages for PanelImages {
537 fn check_image(&self, print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String> {
538 self.whole.check_image(print_id, frame)
539 }
540
541 fn composes(&self, print_id: PrintId) -> bool {
542 self.alignments.calibration().is_some()
543 && self.camera_snapshot_url.is_some()
544 && matches!(
545 self.alignments.print_alignment(print_id),
546 PrintAlignment::Passed { .. }
547 )
548 }
549
550 fn shown_image(&self, request: &CheckImageRequest<'_>) -> Result<ShownImage, String> {
551 let Some(print_id) = request.print_id else {
552 return self.whole_frame(request.frame, &WholeFrameReason::NoPrint);
553 };
554 let previous = self.alignments.previous_check(print_id);
555 let shown = match self.composite(print_id, request, previous.as_ref())? {
556 Ok(composite) => composite,
557 Err(reason) => self.whole_frame(request.frame, &reason)?,
558 };
559 if request.made_for == ImageUse::Check {
560 self.alignments.record_check(
561 print_id,
562 &PreviousCheck {
563 frame: request.frame.to_path_buf(),
564 captured_at: request.captured_at,
565 },
566 );
567 if let Some(print_z_mm) = request.plan.as_ref().and_then(plan_z) {
568 self.alignments.record_checked_frame(
569 print_id,
570 CheckedFrame {
571 frame: request.frame.to_path_buf(),
572 captured_at: request.captured_at,
573 print_z_mm,
574 },
575 MIN_RISE_MM,
576 );
577 }
578 }
579 Ok(shown)
580 }
581}