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, SheetEdgesInputs,
31 WHOLE_FRAME_HEIGHT, WHOLE_FRAME_WIDTH, compose_check_image, measure_growth, sheet_edges,
32 whole_frame,
33};
34use printobserver_types::{PrintId, Timestamp};
35
36use printobserver_panels::{InconclusiveReason, ViewCorrection, ViewOutcome};
37use printobserver_supervisor_api::{ImageFallback, WholeFrameReasonCode};
38
39use crate::alignment::{
40 AlignmentFailure, AlignmentJudging, Alignments, CheckedFrame, Judged, Judging, LastCheckImage,
41 PreviousCheck, PrintAlignment, failure_sentence,
42};
43
44static WRITES: AtomicU64 = AtomicU64::new(0);
47
48pub const CHECK_IMAGES_DIRECTORY: &str = "check-images";
50
51#[derive(Debug, Clone)]
53pub struct WholeFrames {
54 directory: PathBuf,
56}
57
58impl WholeFrames {
59 #[must_use]
61 pub fn under(state_dir: &Path) -> Self {
62 Self {
63 directory: state_dir.join(CHECK_IMAGES_DIRECTORY),
64 }
65 }
66
67 fn destination(&self, frame: &Path) -> PathBuf {
70 let named = |part: Option<&std::ffi::OsStr>| {
71 part.map_or_else(String::new, |part| part.to_string_lossy().into_owned())
72 };
73 let parent = named(frame.parent().and_then(Path::file_name));
74 let file = named(frame.file_name());
75 self.directory.join(format!(
76 "{parent}-{file}-{WHOLE_FRAME_WIDTH}x{WHOLE_FRAME_HEIGHT}.jpg"
77 ))
78 }
79}
80
81impl WholeFrames {
82 fn sheet_edges_destination(&self, frame: &Path) -> PathBuf {
84 let scaled = self.destination(frame);
85 let stem = scaled
86 .file_stem()
87 .map_or_else(String::new, |stem| stem.to_string_lossy().into_owned());
88 self.directory.join(format!("{stem}-sheet-edges.jpg"))
89 }
90}
91
92impl CheckImages for WholeFrames {
93 fn check_image(&self, _print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String> {
94 let destination = self.destination(frame);
95 if destination.is_file() {
96 return Ok(destination);
97 }
98 let bytes = std::fs::read(frame)
99 .map_err(|error| format!("{} is unreadable: {error}", frame.display()))?;
100 let scaled = whole_frame(&bytes).map_err(|error| error.to_string())?;
101 if !scaled.scaled {
102 return Ok(frame.to_path_buf());
103 }
104 write_image(&self.directory, &destination, &scaled.jpeg)?;
105 Ok(destination)
106 }
107}
108
109fn write_image(directory: &Path, destination: &Path, bytes: &[u8]) -> Result<(), String> {
113 std::fs::create_dir_all(directory)
114 .map_err(|error| format!("{} cannot be made: {error}", directory.display()))?;
115 let partial = destination.with_extension(format!(
116 "{}-{}.partial",
117 std::process::id(),
118 WRITES.fetch_add(1, Ordering::Relaxed)
119 ));
120 let written =
121 std::fs::write(&partial, bytes).and_then(|()| std::fs::rename(&partial, destination));
122 written.map_err(|error| {
123 let _ = std::fs::remove_file(&partial);
125 format!("{} cannot be written: {error}", destination.display())
126 })
127}
128
129pub const COMPOSITE_NOTE: &str = "the three-panel check image";
132
133pub const WHOLE_FRAME_NOTE: &str = "the whole camera frame";
135
136#[derive(Debug, Clone, PartialEq)]
138pub enum WholeFrameReason {
139 NoPrint,
142 NoCalibration,
144 NoStream,
147 NoPosition,
150 NoObject,
153 NoLayer,
155 ToolpathUnread(String),
157 AlignmentPending,
159 AlignmentInconclusive(InconclusiveReason),
162 AlignmentUnavailable,
164 AlignmentFailed(AlignmentFailure),
166 LandmarksNotFound(String),
169 ViewRefitRejected(String),
171 CalibrationStale,
175 FrameMismatch(String),
177 Paused,
180 Refused(ComposeError),
182}
183
184impl WholeFrameReason {
185 #[must_use]
187 pub const fn code(&self) -> WholeFrameReasonCode {
188 match self {
189 Self::NoPrint => WholeFrameReasonCode::NoPrint,
190 Self::NoCalibration => WholeFrameReasonCode::NoCalibration,
191 Self::NoStream => WholeFrameReasonCode::NoStream,
192 Self::NoPosition => WholeFrameReasonCode::NoPosition,
193 Self::NoObject => WholeFrameReasonCode::NoObject,
194 Self::NoLayer => WholeFrameReasonCode::NoLayer,
195 Self::ToolpathUnread(_) => WholeFrameReasonCode::ToolpathUnread,
196 Self::AlignmentPending => WholeFrameReasonCode::AlignmentPending,
197 Self::AlignmentInconclusive(_) => WholeFrameReasonCode::AlignmentInconclusive,
198 Self::AlignmentUnavailable => WholeFrameReasonCode::AlignmentUnavailable,
199 Self::AlignmentFailed(_) => WholeFrameReasonCode::AlignmentFailed,
200 Self::LandmarksNotFound(_) | Self::Refused(ComposeError::DriftUnverified) => {
201 WholeFrameReasonCode::LandmarksNotFound
202 }
203 Self::ViewRefitRejected(_) | Self::Refused(ComposeError::CameraMoved { .. }) => {
204 WholeFrameReasonCode::ViewRefitRejected
205 }
206 Self::FrameMismatch(_) | Self::Refused(ComposeError::FrameMismatch { .. }) => {
207 WholeFrameReasonCode::FrameMismatch
208 }
209 Self::CalibrationStale => WholeFrameReasonCode::CalibrationStale,
210 Self::Paused => WholeFrameReasonCode::Paused,
211 Self::Refused(_) => WholeFrameReasonCode::Refused,
212 }
213 }
214}
215
216impl core::fmt::Display for WholeFrameReason {
217 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
218 match self {
219 Self::NoPrint => formatter
220 .write_str("no print is named, so there is no planned toolpath to draw on it"),
221 Self::NoCalibration => formatter.write_str("no camera calibration is configured"),
222 Self::NoStream => formatter.write_str(
223 "no camera snapshot address is configured, so the frame's stream is unknown",
224 ),
225 Self::NoPosition => formatter.write_str(
226 "the print's G-code index gives no file position for this check",
227 ),
228 Self::NoObject => formatter.write_str(
229 "the print's G-code names no extruded object laid at this point",
230 ),
231 Self::NoLayer => formatter.write_str("the print's G-code names no layer at this point"),
232 Self::ToolpathUnread(detail) => write!(
233 formatter,
234 "the layer's planned toolpath could not be read from the print's spool: {detail}"
235 ),
236 Self::AlignmentPending => formatter.write_str(
237 "the print's first-layer alignment is pending: its first object layer is not down, or no frame of it has been judged yet",
238 ),
239 Self::AlignmentInconclusive(why) => write!(
240 formatter,
241 "the print's first-layer alignment is inconclusive on the frame judged last: {}, so a later check's frame is judged again; this is no evidence of a defect",
242 match why {
243 InconclusiveReason::Covered => "the toolhead covers the part, which sits hidden under the head on this frame: bare sheet beside the head alone is no sign the part is gone, but a part seen moved, loose or in spaghetti is",
244 InconclusiveReason::NotClearlyFound => "the printed first layer was not clearly found",
245 }
246 ),
247 Self::AlignmentUnavailable => {
248 formatter.write_str("the print's G-code lays no object to align")
249 }
250 Self::AlignmentFailed(failure) => write!(
251 formatter,
252 "the print's first-layer alignment failed: {}",
253 failure_sentence(failure)
254 ),
255 Self::LandmarksNotFound(reason) | Self::ViewRefitRejected(reason) | Self::FrameMismatch(reason) => {
256 formatter.write_str(reason)
257 }
258 Self::CalibrationStale => formatter.write_str(CALIBRATION_STALE),
259 Self::Paused => formatter.write_str(
260 "the printer reports the print paused, so its bed may stand off the plan's height and nothing is drawn",
261 ),
262 Self::Refused(error) => error.fmt(formatter),
263 }
264 }
265}
266
267pub const CALIBRATION_STALE: &str = "the camera has moved since its calibration, so the outline cannot be drawn reliably; recalibrate this camera";
270
271pub const UNSEEN_RISE_BOUND_MM: f64 = 5.0;
278
279#[must_use]
286pub fn whole_frame_note(reason: &WholeFrameReason) -> String {
287 let bound = match reason {
288 WholeFrameReason::CalibrationStale | WholeFrameReason::AlignmentInconclusive(_) => format!(
289 "; on this frame a part that is not plainly higher is no grounds to pause on its own until the plan's rise since the frame it is compared against exceeds {UNSEEN_RISE_BOUND_MM:.0} mm"
290 ),
291 _ => String::new(),
292 };
293 format!(
294 "{WHOLE_FRAME_NOTE}, scaled to fit {WHOLE_FRAME_WIDTH}x{WHOLE_FRAME_HEIGHT} and uncropped, because {reason}{bound}"
295 )
296}
297
298pub const NO_SHEET_CLAUSE: &str =
301 "; no sheet was found in it, so no close-up of the sheet's edges is shown";
302
303#[must_use]
307pub fn sheet_edges_note(reason: &WholeFrameReason) -> String {
308 format!(
309 "{WHOLE_FRAME_NOTE}, scaled to fit {WHOLE_FRAME_WIDTH}x{WHOLE_FRAME_HEIGHT} and uncropped, because {reason}, as panel 1; panel 2 under it is a close-up of the sheet's edges and clips at twice that scale, cut from the full frame, each edge unrolled into a strip named by the way it faces, outside up and sheet down"
310 )
311}
312
313const CAMERA_HOLDS: &str = "the camera holds still and the drawing follows the bed, so ";
317
318#[must_use]
330pub fn composite_note(
331 made_for: ImageUse,
332 current_at: Timestamp,
333 previous_at: Option<Timestamp>,
334) -> String {
335 let (current, previous, moved) = match (made_for, previous_at) {
336 (ImageUse::Look, at) => (
337 "this layer's planned toolpath drawn on the frame".to_owned(),
338 if at.is_none() {
339 "panel 3 empty, no earlier frame at hand".to_owned()
340 } else {
341 "panel 3 the previous check's frame".to_owned()
342 },
343 String::new(),
344 ),
345 (ImageUse::Check, None) => (
346 format!(
347 "this check's frame, captured {current_at}, with this layer's planned toolpath drawn"
348 ),
349 "panel 3 empty, no earlier frame at hand".to_owned(),
350 format!(
351 "; {CAMERA_HOLDS}a part off its drawn walls in panel 1 has moved unless strongly shown otherwise; no later frame undoes that"
352 ),
353 ),
354 (ImageUse::Check, Some(at)) => (
355 format!(
356 "this check's frame, captured {current_at}, with this layer's planned toolpath drawn"
357 ),
358 format!("panel 3 the last check's frame, captured {at}"),
359 format!(
360 "; {CAMERA_HOLDS}a part off its drawn walls in panel 1, or moved since panel 3, has moved unless strongly shown otherwise; no later frame undoes that"
361 ),
362 ),
363 };
364 format!(
365 "{COMPOSITE_NOTE}, {}x{}: panel 1 {current}, panel 2 a close-up of the part, {previous}{moved}",
366 printobserver_panels::compose::PANEL_WIDTH,
367 printobserver_panels::compose::IMAGE_HEIGHT
368 )
369}
370
371#[must_use]
375pub fn not_grown_note(since: Timestamp, rise_mm: f64) -> String {
376 format!(
377 "; 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"
378 )
379}
380
381fn plan_z(plan: &PlanPosition) -> Option<f64> {
383 plan.index
384 .layer_at(plan.file_position_bytes)
385 .and_then(|layer| plan.index.layer_z_mm(layer))
386}
387
388#[derive(Debug, Clone, Copy)]
391pub struct PlanAt<'a> {
392 pub index: &'a GcodeIndex,
394 pub file_position_bytes: u64,
396}
397
398pub fn compose_at(
410 plan: PlanAt<'_>,
411 current: (&[u8], Timestamp),
412 previous: Option<(&[u8], Timestamp)>,
413 camera_snapshot_url: &str,
414 calibration: &CameraCalibration,
415 correction: Option<&ViewCorrection>,
416) -> Result<CheckImage, WholeFrameReason> {
417 let index = plan.index;
418 let position = plan.file_position_bytes;
419 let active_object = index
420 .object_at(position)
421 .filter(|object| *object < index.object_outlines().len())
422 .ok_or(WholeFrameReason::NoObject)?;
423 let layer = index.layer_at(position).ok_or(WholeFrameReason::NoLayer)?;
424 let print_z_mm = index.layer_z_mm(layer).ok_or(WholeFrameReason::NoLayer)?;
425 let unread =
426 |error: printobserver_core::SpoolError| WholeFrameReason::ToolpathUnread(error.to_string());
427 let toolpath = index.layer_toolpath(layer).map_err(unread)?;
428 let below = if toolpath.carries_object_extrusion() {
429 None
430 } else {
431 index
432 .object_layer_at_or_below(layer)
433 .map(|below| index.layer_toolpath(below))
434 .transpose()
435 .map_err(unread)?
436 };
437 let facts = index.layer_facts(position, &toolpath);
438 let head_trail_mm = index
442 .planned_heads_before(position, printobserver_panels::occlusion::QUEUED_MOVES)
443 .ok()
444 .flatten()
445 .map(|heads| heads.trail)
446 .unwrap_or_default();
447 compose_check_image(&CheckImageInputs {
448 current_jpeg: current.0,
449 current_at: current.1,
450 camera_snapshot_url,
451 previous,
452 outlines: index.object_outlines(),
453 active_object,
454 toolpath: &toolpath,
455 object_layer_below: below.as_ref(),
456 print_z_mm,
457 calibration,
458 correction,
459 file_position_bytes: Some(position),
460 facts: facts.as_ref(),
461 head_trail_mm: &head_trail_mm,
462 reported_head_mm: None,
466 })
467 .map_err(WholeFrameReason::Refused)
468}
469
470#[must_use]
473pub fn panel_one_clause(text: &[String]) -> String {
474 if text.is_empty() {
475 return String::new();
476 }
477 format!("; panel 1: {}", text.join("; "))
478}
479
480fn refusal_of(judged: &Judged) -> Result<(), WholeFrameReason> {
487 if let Some(reason) = &judged.rejected {
488 return Err(WholeFrameReason::ViewRefitRejected(reason.clone()));
489 }
490 if judged.camera_check.is_some() {
491 return refusal_under_check(judged);
492 }
493 match &judged.alignment {
494 PrintAlignment::Passed { .. } => {}
495 PrintAlignment::Pending => {
496 return Err(judged.inconclusive.map_or(
497 WholeFrameReason::AlignmentPending,
498 WholeFrameReason::AlignmentInconclusive,
499 ));
500 }
501 PrintAlignment::Unavailable => return Err(WholeFrameReason::AlignmentUnavailable),
502 PrintAlignment::Failed { reason } => {
503 return Err(WholeFrameReason::AlignmentFailed(reason.clone()));
504 }
505 }
506 if let Some(reason) = &judged.mismatch {
507 return Err(WholeFrameReason::FrameMismatch(reason.clone()));
508 }
509 let said = |reason: &Option<String>| reason.clone().unwrap_or_default();
510 match &judged.view {
511 Some((ViewOutcome::LandmarksNotFound, reason)) => {
512 Err(WholeFrameReason::LandmarksNotFound(said(reason)))
513 }
514 Some((ViewOutcome::ViewRefitRejected, reason)) => {
515 Err(WholeFrameReason::ViewRefitRejected(said(reason)))
516 }
517 Some((ViewOutcome::FrameMismatch, reason)) => {
518 Err(WholeFrameReason::FrameMismatch(said(reason)))
519 }
520 Some((ViewOutcome::Refit, _)) => Err(WholeFrameReason::CalibrationStale),
521 Some((ViewOutcome::Unshifted, _)) | None => Ok(()),
522 }
523}
524
525fn refusal_under_check(judged: &Judged) -> Result<(), WholeFrameReason> {
532 if let Some(reason) = &judged.mismatch {
533 return Err(WholeFrameReason::FrameMismatch(reason.clone()));
534 }
535 let said = |reason: &Option<String>| reason.clone().unwrap_or_default();
536 match &judged.view {
537 Some((ViewOutcome::LandmarksNotFound, reason)) => {
538 Err(WholeFrameReason::LandmarksNotFound(said(reason)))
539 }
540 Some((ViewOutcome::ViewRefitRejected, reason)) => {
541 Err(WholeFrameReason::ViewRefitRejected(said(reason)))
542 }
543 Some((ViewOutcome::FrameMismatch, reason)) => {
544 Err(WholeFrameReason::FrameMismatch(said(reason)))
545 }
546 Some((ViewOutcome::Refit | ViewOutcome::Unshifted, _)) | None => Ok(()),
547 }
548}
549
550#[derive(Debug, Clone, Copy)]
552pub struct Shown<'a> {
553 pub frame: &'a Path,
555 pub captured_at: Timestamp,
557 pub made_for: ImageUse,
559 pub plan: Option<&'a PlanPosition>,
561 pub paused: bool,
563}
564
565pub struct PanelImages {
568 whole: WholeFrames,
570 alignments: Arc<Alignments>,
572 camera_snapshot_url: Option<String>,
575}
576
577impl core::fmt::Debug for PanelImages {
578 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
579 formatter
580 .debug_struct("PanelImages")
581 .field("whole", &self.whole)
582 .field("camera_snapshot_url", &self.camera_snapshot_url)
583 .finish_non_exhaustive()
584 }
585}
586
587impl PanelImages {
588 #[must_use]
590 pub fn new(
591 state_dir: &Path,
592 alignments: Arc<Alignments>,
593 camera_snapshot_url: Option<String>,
594 ) -> Self {
595 Self {
596 whole: WholeFrames::under(state_dir),
597 alignments,
598 camera_snapshot_url,
599 }
600 }
601
602 #[must_use]
604 pub fn calibration(&self) -> Option<&CameraCalibration> {
605 self.alignments.calibration()
606 }
607
608 pub fn write_camera_check_image(
615 &self,
616 camera_check: printobserver_core::CameraCheckId,
617 jpeg: &[u8],
618 ) -> Result<PathBuf, String> {
619 let destination = self
620 .whole
621 .directory
622 .join(format!("camera-check-{camera_check}.jpg"));
623 write_image(&self.whole.directory, &destination, jpeg)?;
624 Ok(destination)
625 }
626
627 #[must_use]
629 pub fn alignment(&self, print_id: PrintId) -> PrintAlignment {
630 self.alignments.print_alignment(print_id)
631 }
632
633 #[must_use]
635 pub fn last_check_image(&self, print_id: PrintId) -> Option<LastCheckImage> {
636 self.alignments.last_check_image(print_id)
637 }
638
639 fn whole_frame(&self, frame: &Path, reason: &WholeFrameReason) -> Result<ShownImage, String> {
641 Ok(ShownImage {
642 fallback: Some(ImageFallback {
643 code: reason.code(),
644 message: reason.to_string(),
645 }),
646 ..ShownImage::plain(
647 self.whole.check_image(None, frame)?,
648 Some(whole_frame_note(reason)),
649 )
650 })
651 }
652
653 fn printer_look(&self, frame: &Path, own_camera: bool) -> Result<ShownImage, String> {
664 let reason = WholeFrameReason::NoPrint;
665 let destination = self.whole.sheet_edges_destination(frame);
666 if !destination.is_file() {
667 let bytes = std::fs::read(frame)
668 .map_err(|error| format!("{} is unreadable: {error}", frame.display()))?;
669 let calibration = if own_camera {
670 self.alignments
671 .calibration()
672 .zip(self.camera_snapshot_url.as_deref())
673 } else {
674 None
675 };
676 let made = sheet_edges(&SheetEdgesInputs {
677 frame_jpeg: &bytes,
678 calibration,
679 });
680 match made {
681 Ok(Some(edges)) => write_image(&self.whole.directory, &destination, &edges.jpeg)?,
682 Ok(None) => {
683 let mut shown = self.whole_frame(frame, &reason)?;
684 shown.note = shown.note.map(|note| format!("{note}{NO_SHEET_CLAUSE}"));
685 return Ok(shown);
686 }
687 Err(error) => return Err(error.to_string()),
691 }
692 }
693 Ok(ShownImage {
694 fallback: Some(ImageFallback {
695 code: reason.code(),
696 message: reason.to_string(),
697 }),
698 ..ShownImage::plain(destination, Some(sheet_edges_note(&reason)))
699 })
700 }
701
702 pub fn adopt_camera_check(
705 &self,
706 print_id: PrintId,
707 record: Option<&printobserver_types::EventRecord>,
708 ) {
709 if let Some(record) = record {
710 self.alignments.adopt_camera_check(print_id, record);
711 }
712 }
713
714 #[must_use]
719 pub fn judge_frame(
720 &self,
721 print_id: PrintId,
722 frame: &[u8],
723 frame_sha256: &str,
724 plan: Option<&PlanPosition>,
725 alignment: AlignmentJudging,
726 ) -> Option<Judged> {
727 self.alignments.calibration()?;
728 let url = self.camera_snapshot_url.as_deref()?;
729 Some(self.alignments.judge(
730 print_id,
731 &Judging {
732 frame_jpeg: frame,
733 frame_sha256,
734 camera_snapshot_url: url,
735 plan,
736 alignment,
737 },
738 ))
739 }
740
741 pub fn image_of(
750 &self,
751 print_id: PrintId,
752 shown: &Shown<'_>,
753 judged: Option<&Judged>,
754 ) -> Result<ShownImage, String> {
755 let previous = self.alignments.previous_check(print_id);
756 match self.chosen(print_id, shown, judged, previous.as_ref())? {
757 Ok(composite) => Ok(composite),
758 Err(reason) => self.whole_frame(shown.frame, &reason),
759 }
760 }
761
762 fn chosen(
765 &self,
766 print_id: PrintId,
767 shown: &Shown<'_>,
768 judged: Option<&Judged>,
769 previous: Option<&PreviousCheck>,
770 ) -> Result<Result<ShownImage, WholeFrameReason>, String> {
771 let Some(calibration) = self.alignments.calibration() else {
772 return Ok(Err(WholeFrameReason::NoCalibration));
773 };
774 let Some(url) = self.camera_snapshot_url.as_deref() else {
775 return Ok(Err(WholeFrameReason::NoStream));
776 };
777 if shown.paused {
778 return Ok(Err(WholeFrameReason::Paused));
779 }
780 let Some(judged) = judged else {
781 return Ok(Err(WholeFrameReason::AlignmentPending));
782 };
783 if let Some(detail) = &judged.unreadable {
784 return Err(detail.clone());
785 }
786 let Some(plan) = shown.plan else {
787 return Ok(Err(WholeFrameReason::NoPosition));
788 };
789 let at = PlanAt {
790 index: &plan.index,
791 file_position_bytes: plan.file_position_bytes,
792 };
793 if at.index.object_at(at.file_position_bytes).is_none()
794 || at.index.object_outlines().is_empty()
795 {
796 return Ok(Err(WholeFrameReason::NoObject));
797 }
798 if at.index.layer_at(at.file_position_bytes).is_none() {
799 return Ok(Err(WholeFrameReason::NoLayer));
800 }
801 if let Err(reason) = refusal_of(judged) {
802 return Ok(Err(reason));
803 }
804 let current = std::fs::read(shown.frame)
805 .map_err(|error| format!("{} is unreadable: {error}", shown.frame.display()))?;
806 let earlier = previous.and_then(|check| {
810 std::fs::read(&check.frame)
811 .ok()
812 .filter(|bytes| whole_frame(bytes).is_ok())
813 .map(|bytes| (bytes, check.captured_at))
814 });
815 let composed = match compose_at(
816 at,
817 (¤t, shown.captured_at),
818 earlier.as_ref().map(|(bytes, at)| (bytes.as_slice(), *at)),
819 url,
820 calibration,
821 judged.correction.as_ref(),
822 ) {
823 Ok(composed) => composed,
824 Err(WholeFrameReason::Refused(
830 ComposeError::Undecodable { detail } | ComposeError::Encode { detail },
831 )) => return Err(detail),
832 Err(reason) => return Ok(Err(reason)),
833 };
834 let destination = self.composite_destination(shown.frame, previous);
835 write_image(&self.whole.directory, &destination, &composed.jpeg)?;
836 let mut note = composite_note(
837 shown.made_for,
838 shown.captured_at,
839 earlier.as_ref().map(|(_, at)| *at),
840 );
841 note.push_str(&panel_one_clause(&composed.text));
842 if shown.made_for == ImageUse::Check
843 && let Some(clause) = self.growth_clause(print_id, plan, ¤t, url, calibration)
844 {
845 note.push_str(&clause);
846 }
847 Ok(Ok(ShownImage {
848 composite: true,
849 ..ShownImage::plain(destination, Some(note))
850 }))
851 }
852
853 fn growth_clause(
860 &self,
861 print_id: PrintId,
862 plan: &PlanPosition,
863 current: &[u8],
864 url: &str,
865 calibration: &CameraCalibration,
866 ) -> Option<String> {
867 let layer = plan.index.layer_at(plan.file_position_bytes)?;
868 let print_z_mm = plan.index.layer_z_mm(layer)?;
869 let reference = self
870 .alignments
871 .growth_reference(print_id, print_z_mm, MIN_RISE_MM)?;
872 let earlier = std::fs::read(&reference.frame).ok()?;
873 let toolpath = plan.index.layer_toolpath(layer).ok()?;
874 let measured = measure_growth(&GrowthInputs {
875 earlier_jpeg: &earlier,
876 earlier_print_z_mm: reference.print_z_mm,
877 current_jpeg: current,
878 current_print_z_mm: print_z_mm,
879 camera_snapshot_url: url,
880 toolpath: &toolpath,
881 calibration,
882 })
883 .ok()??;
884 let not_grown = measured.not_grown();
885 eprintln!(
886 "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: {}",
887 reference.print_z_mm,
888 reference.captured_at,
889 measured.carried,
890 measured.held,
891 measured.carried_share * 100.0,
892 measured.samples,
893 measured.separation_px,
894 if not_grown { "not grown" } else { "no verdict" }
895 );
896 not_grown.then(|| not_grown_note(reference.captured_at, print_z_mm - reference.print_z_mm))
897 }
898
899 fn composite_destination(&self, frame: &Path, previous: Option<&PreviousCheck>) -> PathBuf {
902 let named = |frame: &Path| {
903 let part = |part: Option<&std::ffi::OsStr>| {
904 part.map_or_else(String::new, |part| part.to_string_lossy().into_owned())
905 };
906 format!(
907 "{}-{}",
908 part(frame.parent().and_then(Path::file_name)),
909 part(frame.file_name())
910 )
911 };
912 let after = previous.map_or_else(|| "first".to_owned(), |check| named(&check.frame));
913 self.whole
914 .directory
915 .join(format!("{}-composite-after-{after}.jpg", named(frame)))
916 }
917}
918
919impl CheckImages for PanelImages {
920 fn check_image(&self, print_id: Option<PrintId>, frame: &Path) -> Result<PathBuf, String> {
921 self.whole.check_image(print_id, frame)
922 }
923
924 fn restart_growth(&self, print_id: PrintId) {
925 self.alignments.restart_growth(print_id);
926 }
927
928 fn composes(&self, print_id: PrintId) -> bool {
929 self.alignments.calibration().is_some()
930 && self.camera_snapshot_url.is_some()
931 && (self.alignments.started_under_a_camera_check(print_id)
932 || matches!(
933 self.alignments.print_alignment(print_id),
934 PrintAlignment::Passed { .. }
935 ))
936 }
937
938 fn shown_image(&self, request: &CheckImageRequest<'_>) -> Result<ShownImage, String> {
939 let Some(print_id) = request.print_id else {
940 return self.printer_look(request.frame, request.own_camera);
941 };
942 if let Some(record) = &request.camera_check {
943 self.alignments.adopt_camera_check(print_id, record);
944 }
945 let judged = if request.paused {
948 None
949 } else {
950 let alignment = if request.made_for == ImageUse::Check && request.own_camera {
951 AlignmentJudging::WhilePending
952 } else {
953 AlignmentJudging::Never
954 };
955 match std::fs::read(request.frame) {
956 Ok(current) => self.judge_frame(
957 print_id,
958 ¤t,
959 request.frame_sha256,
960 request.plan.as_ref(),
961 alignment,
962 ),
963 Err(error) => {
964 return Err(format!(
965 "{} is unreadable: {error}",
966 request.frame.display()
967 ));
968 }
969 }
970 };
971 let shown = Shown {
972 frame: request.frame,
973 captured_at: request.captured_at,
974 made_for: request.made_for,
975 plan: request.plan.as_ref(),
976 paused: request.paused,
977 };
978 let mut image = self.image_of(print_id, &shown, judged.as_ref())?;
979 image.records = judged.map(|judged| judged.records).unwrap_or_default();
980 if request.made_for == ImageUse::Check && request.own_camera {
985 self.alignments.record_check(
986 print_id,
987 &PreviousCheck {
988 frame: request.frame.to_path_buf(),
989 captured_at: request.captured_at,
990 },
991 );
992 if let Some(print_z_mm) = request.plan.as_ref().and_then(plan_z) {
993 self.alignments.record_checked_frame(
994 print_id,
995 CheckedFrame {
996 frame: request.frame.to_path_buf(),
997 captured_at: request.captured_at,
998 print_z_mm,
999 },
1000 MIN_RISE_MM,
1001 );
1002 }
1003 }
1004 if request.made_for == ImageUse::Check {
1005 image.records.extend(self.alignments.note_check_image(
1006 print_id,
1007 LastCheckImage {
1008 at: request.captured_at,
1009 kind: image.kind(),
1010 fallback: image.fallback.clone(),
1011 },
1012 request.frame_sha256,
1013 ));
1014 }
1015 Ok(image)
1016 }
1017}