1use base64::Engine as _;
12use image::GrayImage;
13use nalgebra::{Rotation3, Vector3};
14use printobserver_types::schemars::JsonSchema;
15use printobserver_types::serde::{Deserialize, Serialize};
16
17pub const SCHEMA_VERSION: u32 = 1;
19
20pub const MAX_SEARCH_RADIUS_PX: u32 = 256;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
26#[serde(crate = "printobserver_types::serde")]
27#[schemars(crate = "printobserver_types::schemars")]
28pub enum Motion {
29 #[serde(rename = "bed-z")]
31 BedZ,
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
37#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
38#[schemars(crate = "printobserver_types::schemars")]
39pub struct Intrinsics {
40 pub fx: f64,
42 pub fy: f64,
44 pub cx: f64,
46 pub cy: f64,
48 pub k: [f64; 4],
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
56#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
57#[schemars(crate = "printobserver_types::schemars")]
58pub struct BedPose {
59 pub rotation_rodrigues: [f64; 3],
61 pub translation_mm: [f64; 3],
63}
64
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
67#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
68#[schemars(crate = "printobserver_types::schemars")]
69pub struct Landmark {
70 pub name: String,
72 pub center_px: [f64; 2],
74 pub patch_png_base64: String,
76 pub search_radius_px: u32,
78}
79
80#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
82#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
83#[schemars(crate = "printobserver_types::schemars")]
84pub struct Fit {
85 pub rms_reprojection_px: f64,
88 pub frames: u32,
90 pub calibrated_at: String,
93}
94
95#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
97#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
98#[schemars(crate = "printobserver_types::schemars")]
99pub struct CameraCalibration {
100 #[schemars(range(min = 1, max = 1))]
103 pub schema_version: u32,
104 pub motion: Motion,
106 pub image_size_px: [u32; 2],
109 pub intrinsics: Intrinsics,
111 pub bed_pose: BedPose,
113 pub landmarks: Vec<Landmark>,
115 pub drift_tolerance_px: f64,
118 pub camera_snapshot_url: String,
122 pub alignment_max_offset_px: f64,
124 pub fit: Fit,
126 #[serde(skip)]
128 #[schemars(skip)]
129 patches: Vec<GrayImage>,
130}
131
132#[derive(Debug, Clone, PartialEq, Eq)]
134pub enum CalibrationError {
135 Shape {
137 detail: String,
139 },
140 Invalid {
142 field: &'static str,
144 reason: String,
146 },
147}
148
149impl core::fmt::Display for CalibrationError {
150 fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
151 match self {
152 Self::Shape { detail } => write!(formatter, "not a camera calibration: {detail}"),
153 Self::Invalid { field, reason } => write!(formatter, "`{field}` {reason}"),
154 }
155 }
156}
157
158impl std::error::Error for CalibrationError {}
159
160fn invalid(field: &'static str, reason: impl Into<String>) -> CalibrationError {
162 CalibrationError::Invalid {
163 field,
164 reason: reason.into(),
165 }
166}
167
168fn is_date(text: &str) -> bool {
170 chrono::NaiveDate::parse_from_str(text, "%Y-%m-%d").is_ok() && text.len() == 10
171}
172
173fn finite(field: &'static str, values: &[f64], positive: bool) -> Result<(), CalibrationError> {
175 for value in values {
176 if !value.is_finite() {
177 return Err(invalid(field, "is not a finite number"));
178 }
179 if positive && *value <= 0.0 {
180 return Err(invalid(field, "must be above zero"));
181 }
182 }
183 Ok(())
184}
185
186impl CameraCalibration {
187 pub fn from_json(bytes: &[u8]) -> Result<Self, CalibrationError> {
197 let mut calibration: Self =
198 printobserver_types::serde_json::from_slice(bytes).map_err(|error| {
199 CalibrationError::Shape {
200 detail: error.to_string(),
201 }
202 })?;
203 if calibration.schema_version != SCHEMA_VERSION {
204 return Err(invalid(
205 "schema_version",
206 format!(
207 "is {}, and this program reads version {SCHEMA_VERSION}",
208 calibration.schema_version
209 ),
210 ));
211 }
212 if calibration.image_size_px.contains(&0) {
213 return Err(invalid("image_size_px", "names an empty frame"));
214 }
215 let lens = calibration.intrinsics;
216 finite("intrinsics.fx", &[lens.fx, lens.fy], true)?;
217 finite("intrinsics.cx", &[lens.cx, lens.cy], false)?;
218 finite("intrinsics.k", &lens.k, false)?;
219 finite(
220 "bed_pose.rotation_rodrigues",
221 &calibration.bed_pose.rotation_rodrigues,
222 false,
223 )?;
224 finite(
225 "bed_pose.translation_mm",
226 &calibration.bed_pose.translation_mm,
227 false,
228 )?;
229 finite(
230 "drift_tolerance_px",
231 &[calibration.drift_tolerance_px],
232 true,
233 )?;
234 finite(
235 "alignment_max_offset_px",
236 &[calibration.alignment_max_offset_px],
237 true,
238 )?;
239 printobserver_vision_api::WebAddress::new(&calibration.camera_snapshot_url)
240 .map_err(|why| invalid("camera_snapshot_url", why))?;
241 if !is_date(&calibration.fit.calibrated_at) {
242 return Err(invalid("fit.calibrated_at", "is not a YYYY-MM-DD date"));
243 }
244 let names: std::collections::BTreeSet<&str> = calibration
248 .landmarks
249 .iter()
250 .map(|landmark| landmark.name.as_str())
251 .collect();
252 if names.len() < 2 || names.len() != calibration.landmarks.len() {
253 return Err(invalid(
254 "landmarks",
255 "must name at least two chassis landmarks, each once",
256 ));
257 }
258 let mut patches = Vec::with_capacity(calibration.landmarks.len());
259 for landmark in &calibration.landmarks {
260 finite("landmarks.center_px", &landmark.center_px, false)?;
261 let [w, h] = calibration.image_size_px.map(f64::from);
262 if !((0.0..w).contains(&landmark.center_px[0])
263 && (0.0..h).contains(&landmark.center_px[1]))
264 {
265 return Err(invalid("landmarks.center_px", "lies outside the frame"));
266 }
267 if !(1..=MAX_SEARCH_RADIUS_PX).contains(&landmark.search_radius_px) {
268 return Err(invalid(
269 "landmarks.search_radius_px",
270 format!("must be from 1 to {MAX_SEARCH_RADIUS_PX}"),
271 ));
272 }
273 let png = base64::engine::general_purpose::STANDARD
274 .decode(&landmark.patch_png_base64)
275 .map_err(|error| invalid("landmarks.patch_png_base64", error.to_string()))?;
276 let patch = image::load_from_memory_with_format(&png, image::ImageFormat::Png)
277 .map_err(|error| invalid("landmarks.patch_png_base64", error.to_string()))?
278 .to_luma8();
279 if patch.width() < 2 || patch.height() < 2 {
280 return Err(invalid("landmarks.patch_png_base64", "is no patch"));
281 }
282 patches.push(patch);
283 }
284 calibration.patches = patches;
285 Ok(calibration)
286 }
287
288 pub(crate) fn patches(&self) -> &[GrayImage] {
290 &self.patches
291 }
292
293 #[must_use]
297 pub fn project(
298 &self,
299 points_mm: &[[f64; 3]],
300 print_z_mm: f64,
301 frame_size_px: [u32; 2],
302 ) -> Vec<Option<[f64; 2]>> {
303 let [w, h] = frame_size_px.map(f64::from);
304 let projector = self.projector();
305 points_mm
306 .iter()
307 .map(|point| {
308 projector
309 .pixel([point[0], point[1], point[2] - print_z_mm])
310 .filter(|[u, v]| (0.0..w).contains(u) && (0.0..h).contains(v))
311 })
312 .collect()
313 }
314
315 pub(crate) fn projector(&self) -> Projector {
317 let [rx, ry, rz] = self.bed_pose.rotation_rodrigues;
318 let [tx, ty, tz] = self.bed_pose.translation_mm;
319 Projector {
320 rotation: Rotation3::new(Vector3::new(rx, ry, rz)),
321 translation: Vector3::new(tx, ty, tz),
322 lens: self.intrinsics,
323 }
324 }
325
326 #[must_use]
329 pub fn camera_centre_mm(&self) -> [f64; 3] {
330 let projector = self.projector();
331 let centre = -(projector.rotation.inverse() * projector.translation);
332 [centre.x, centre.y, centre.z]
333 }
334
335 #[must_use]
337 pub fn with_bed_pose(&self, bed_pose: BedPose) -> Self {
338 Self {
339 bed_pose,
340 ..self.clone()
341 }
342 }
343}
344
345#[derive(Debug, Clone, Copy)]
347pub(crate) struct Projector {
348 rotation: Rotation3<f64>,
350 translation: Vector3<f64>,
352 lens: Intrinsics,
354}
355
356impl Projector {
357 pub(crate) fn pixel(&self, world: [f64; 3]) -> Option<[f64; 2]> {
360 let camera = self.rotation * Vector3::new(world[0], world[1], world[2]) + self.translation;
361 if camera.z <= 1e-6 {
362 return None;
363 }
364 let (a, b) = (camera.x / camera.z, camera.y / camera.z);
365 let r = a.hypot(b);
366 let theta = r.atan();
367 let t2 = theta * theta;
368 let [k1, k2, k3, k4] = self.lens.k;
369 let theta_d = theta * (1.0 + t2 * (k1 + t2 * (k2 + t2 * (k3 + t2 * k4))));
370 let scale = if r > 1e-12 { theta_d / r } else { 1.0 };
371 Some([
372 self.lens.fx * a * scale + self.lens.cx,
373 self.lens.fy * b * scale + self.lens.cy,
374 ])
375 }
376}