1use image::GrayImage;
22use printobserver_types::schemars::JsonSchema;
23use printobserver_types::serde::{Deserialize, Serialize};
24
25use crate::calibration::CameraCalibration;
26use crate::compose::decode;
27use crate::drift::{
28 HIDDEN_BELOW, Located, VIEW_SEARCH_RADIUS_PX, check_frame, locate_landmarks_within,
29};
30use crate::error::ComposeError;
31
32pub const AGREEMENT_PX: f64 = 25.0;
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
39#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
40#[schemars(crate = "printobserver_types::schemars")]
41pub enum ViewModel {
42 Translation,
44 Similarity,
46 Affine,
48 Homography,
50}
51
52#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
55#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
56#[schemars(crate = "printobserver_types::schemars")]
57pub struct ReferenceLandmark {
58 pub name: String,
60 pub offset_px: [f64; 2],
62 pub score: f64,
64}
65
66#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
68#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
69#[schemars(crate = "printobserver_types::schemars")]
70pub struct ViewCorrection {
71 pub model: ViewModel,
73 pub matrix: [[f64; 3]; 3],
76 pub landmarks: Vec<ReferenceLandmark>,
79 pub residual_px: f64,
82}
83
84impl ViewCorrection {
85 #[must_use]
87 pub fn translation(shift_px: [f64; 2], landmarks: Vec<ReferenceLandmark>) -> Self {
88 let squares: Vec<f64> = landmarks
89 .iter()
90 .map(|landmark| {
91 let (dx, dy) = (
92 landmark.offset_px[0] - shift_px[0],
93 landmark.offset_px[1] - shift_px[1],
94 );
95 dx * dx + dy * dy
96 })
97 .collect();
98 let residual_px = if squares.is_empty() {
99 0.0
100 } else {
101 (squares.iter().sum::<f64>() / f64::from(u32::try_from(squares.len()).unwrap_or(1)))
102 .sqrt()
103 };
104 Self {
105 model: ViewModel::Translation,
106 matrix: [
107 [1.0, 0.0, shift_px[0]],
108 [0.0, 1.0, shift_px[1]],
109 [0.0, 0.0, 1.0],
110 ],
111 landmarks,
112 residual_px,
113 }
114 }
115
116 #[must_use]
118 pub const fn shift_px(&self) -> [f64; 2] {
119 [self.matrix[0][2], self.matrix[1][2]]
120 }
121
122 #[must_use]
124 pub fn apply(&self, [x, y]: [f64; 2]) -> [f64; 2] {
125 let m = &self.matrix;
126 let w = m[2][0] * x + m[2][1] * y + m[2][2];
127 let w = if w.abs() < 1e-12 { 1.0 } else { w };
128 [
129 (m[0][0] * x + m[0][1] * y + m[0][2]) / w,
130 (m[1][0] * x + m[1][1] * y + m[1][2]) / w,
131 ]
132 }
133}
134
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
137#[serde(crate = "printobserver_types::serde", rename_all = "snake_case")]
138#[schemars(crate = "printobserver_types::schemars")]
139pub enum ViewOutcome {
140 Unshifted,
144 Refit,
147 LandmarksNotFound,
150 ViewRefitRejected,
154 FrameMismatch,
156}
157
158impl ViewOutcome {
159 #[must_use]
161 pub const fn drawable(self) -> bool {
162 matches!(self, Self::Unshifted | Self::Refit)
163 }
164}
165
166#[derive(Debug, Clone, PartialEq)]
168pub struct FoundLandmark {
169 pub name: String,
171 pub located: Located,
173}
174
175impl FoundLandmark {
176 #[must_use]
178 pub fn distance_px(&self) -> f64 {
179 self.located.offset_px[0].hypot(self.located.offset_px[1])
180 }
181
182 #[must_use]
184 pub fn visible(&self) -> bool {
185 self.located.score >= HIDDEN_BELOW
186 }
187}
188
189#[derive(Debug, Clone, PartialEq)]
191pub struct ViewJudgement {
192 pub outcome: ViewOutcome,
194 pub reason: Option<String>,
196 pub landmarks: Vec<FoundLandmark>,
199}
200
201impl ViewJudgement {
202 #[must_use]
206 pub fn agreeing(&self) -> Vec<ReferenceLandmark> {
207 let visible: Vec<&FoundLandmark> = self.landmarks.iter().filter(|l| l.visible()).collect();
208 let mut best: Vec<&FoundLandmark> = Vec::new();
209 let mut best_score = f64::NEG_INFINITY;
210 let count = visible.len().min(16);
211 for mask in 1_u32..(1 << count) {
212 let members: Vec<&FoundLandmark> = (0..count)
213 .filter(|bit| mask & (1 << bit) != 0)
214 .map(|bit| visible[bit])
215 .collect();
216 let agree = members.iter().enumerate().all(|(i, a)| {
217 members.iter().skip(i + 1).all(|b| {
218 (a.located.offset_px[0] - b.located.offset_px[0])
219 .hypot(a.located.offset_px[1] - b.located.offset_px[1])
220 <= AGREEMENT_PX
221 })
222 });
223 if !agree {
224 continue;
225 }
226 let score: f64 = members.iter().map(|l| f64::from(l.located.score)).sum();
227 if members.len() > best.len() || (members.len() == best.len() && score > best_score) {
228 best = members;
229 best_score = score;
230 }
231 }
232 best.into_iter()
233 .map(|landmark| ReferenceLandmark {
234 name: landmark.name.clone(),
235 offset_px: landmark.located.offset_px,
236 score: f64::from(landmark.located.score),
237 })
238 .collect()
239 }
240
241 #[must_use]
244 pub fn moved(&self, calibration: &CameraCalibration) -> bool {
245 self.landmarks
246 .iter()
247 .filter(|l| l.visible() && l.distance_px() > calibration.drift_tolerance_px)
248 .count()
249 >= 2
250 }
251}
252
253#[must_use]
257pub fn judge_view(
258 calibration: &CameraCalibration,
259 frame: &GrayImage,
260 correction: Option<&ViewCorrection>,
261) -> ViewJudgement {
262 judge_found(calibration, found_landmarks(calibration, frame), correction)
263}
264
265#[must_use]
268pub fn found_landmarks(calibration: &CameraCalibration, frame: &GrayImage) -> Vec<FoundLandmark> {
269 calibration
270 .landmarks
271 .iter()
272 .zip(locate_landmarks_within(
273 calibration,
274 frame,
275 VIEW_SEARCH_RADIUS_PX,
276 ))
277 .map(|(landmark, located)| FoundLandmark {
278 name: landmark.name.clone(),
279 located,
280 })
281 .collect()
282}
283
284#[must_use]
287pub fn judge_found(
288 calibration: &CameraCalibration,
289 landmarks: Vec<FoundLandmark>,
290 correction: Option<&ViewCorrection>,
291) -> ViewJudgement {
292 let tolerance = calibration.drift_tolerance_px;
293 let judged = |outcome: ViewOutcome, reason: Option<String>, landmarks: Vec<FoundLandmark>| {
294 ViewJudgement {
295 outcome,
296 reason,
297 landmarks,
298 }
299 };
300 let visible = landmarks.iter().filter(|l| l.visible()).count();
301 let Some(correction) = correction else {
302 if visible < 2 {
303 return judged(
304 ViewOutcome::LandmarksNotFound,
305 Some(LANDMARKS_NOT_FOUND.to_owned()),
306 landmarks,
307 );
308 }
309 let furthest = landmarks
310 .iter()
311 .filter(|l| l.visible() && l.distance_px() > tolerance)
312 .max_by(|a, b| a.distance_px().total_cmp(&b.distance_px()));
313 let moved = landmarks
314 .iter()
315 .filter(|l| l.visible() && l.distance_px() > tolerance)
316 .count();
317 if moved >= 2
318 && let Some(furthest) = furthest
319 {
320 let reason = format!(
321 "the camera has shifted since it was calibrated, {} being {:.1} px from where it was, and no correction taken from this print's first layer is in force yet",
322 furthest.name,
323 furthest.distance_px()
324 );
325 return judged(ViewOutcome::ViewRefitRejected, Some(reason), landmarks);
326 }
327 return judged(ViewOutcome::Unshifted, None, landmarks);
328 };
329 let again: Vec<(&ReferenceLandmark, &FoundLandmark)> = correction
330 .landmarks
331 .iter()
332 .filter_map(|reference| {
333 landmarks
334 .iter()
335 .find(|found| found.name == reference.name && found.visible())
336 .map(|found| (reference, found))
337 })
338 .collect();
339 if again.len() < 2 {
340 return judged(
341 ViewOutcome::LandmarksNotFound,
342 Some(LANDMARKS_NOT_FOUND_AGAIN.to_owned()),
343 landmarks,
344 );
345 }
346 let from_reference = |(reference, found): &(&ReferenceLandmark, &FoundLandmark)| {
347 (found.located.offset_px[0] - reference.offset_px[0])
348 .hypot(found.located.offset_px[1] - reference.offset_px[1])
349 };
350 let moved_again: Vec<(&str, f64)> = again
351 .iter()
352 .map(|pair| (pair.0.name.as_str(), from_reference(pair)))
353 .filter(|(_, distance)| *distance > tolerance)
354 .collect();
355 if moved_again.len() >= 2 {
356 let (name, distance) = moved_again
357 .iter()
358 .copied()
359 .fold(
360 moved_again[0],
361 |far, next| if next.1 > far.1 { next } else { far },
362 );
363 let reason = format!(
364 "the camera has moved again since this print's first-layer correction was taken: {name} is {distance:.1} px from where that correction's frame had it"
365 );
366 return judged(ViewOutcome::ViewRefitRejected, Some(reason), landmarks);
367 }
368 let shifted = landmarks
369 .iter()
370 .filter(|l| l.visible() && l.distance_px() > tolerance)
371 .count()
372 >= 2;
373 let outcome = if shifted {
374 ViewOutcome::Refit
375 } else {
376 ViewOutcome::Unshifted
377 };
378 judged(outcome, None, landmarks)
379}
380
381pub const LANDMARKS_NOT_FOUND: &str = "fewer than two of the calibration's landmarks are found in the frame, so whether the camera has shifted is unknown";
383
384pub const LANDMARKS_NOT_FOUND_AGAIN: &str = "fewer than two of the landmarks this print's first-layer correction was taken against are found in the frame, so whether the camera has moved again is unknown";
387
388pub fn landmarks_in_frame(
397 calibration: &CameraCalibration,
398 jpeg: &[u8],
399 camera_snapshot_url: &str,
400) -> Result<Vec<FoundLandmark>, ComposeError> {
401 let frame = decode(jpeg)?;
402 check_frame(
403 calibration,
404 [frame.width(), frame.height()],
405 camera_snapshot_url,
406 )?;
407 Ok(found_landmarks(
408 calibration,
409 &image::imageops::grayscale(&frame),
410 ))
411}