use base64::Engine as _;
use image::GrayImage;
use nalgebra::{Rotation3, Vector3};
use printobserver_types::schemars::JsonSchema;
use printobserver_types::serde::{Deserialize, Serialize};
pub const SCHEMA_VERSION: u32 = 1;
pub const MAX_SEARCH_RADIUS_PX: u32 = 256;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde")]
#[schemars(crate = "printobserver_types::schemars")]
pub enum Motion {
#[serde(rename = "bed-z")]
BedZ,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct Intrinsics {
pub fx: f64,
pub fy: f64,
pub cx: f64,
pub cy: f64,
pub k: [f64; 4],
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct BedPose {
pub rotation_rodrigues: [f64; 3],
pub translation_mm: [f64; 3],
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct Landmark {
pub name: String,
pub center_px: [f64; 2],
pub patch_png_base64: String,
pub search_radius_px: u32,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct Fit {
pub rms_reprojection_px: f64,
pub frames: u32,
pub calibrated_at: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(crate = "printobserver_types::serde", deny_unknown_fields)]
#[schemars(crate = "printobserver_types::schemars")]
pub struct CameraCalibration {
#[schemars(range(min = 1, max = 1))]
pub schema_version: u32,
pub motion: Motion,
pub image_size_px: [u32; 2],
pub intrinsics: Intrinsics,
pub bed_pose: BedPose,
pub landmarks: Vec<Landmark>,
pub drift_tolerance_px: f64,
pub camera_snapshot_url: String,
pub alignment_max_offset_px: f64,
pub fit: Fit,
#[serde(skip)]
#[schemars(skip)]
patches: Vec<GrayImage>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CalibrationError {
Shape {
detail: String,
},
Invalid {
field: &'static str,
reason: String,
},
}
impl core::fmt::Display for CalibrationError {
fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Shape { detail } => write!(formatter, "not a camera calibration: {detail}"),
Self::Invalid { field, reason } => write!(formatter, "`{field}` {reason}"),
}
}
}
impl std::error::Error for CalibrationError {}
fn invalid(field: &'static str, reason: impl Into<String>) -> CalibrationError {
CalibrationError::Invalid {
field,
reason: reason.into(),
}
}
fn is_date(text: &str) -> bool {
chrono::NaiveDate::parse_from_str(text, "%Y-%m-%d").is_ok() && text.len() == 10
}
fn finite(field: &'static str, values: &[f64], positive: bool) -> Result<(), CalibrationError> {
for value in values {
if !value.is_finite() {
return Err(invalid(field, "is not a finite number"));
}
if positive && *value <= 0.0 {
return Err(invalid(field, "must be above zero"));
}
}
Ok(())
}
impl CameraCalibration {
pub fn from_json(bytes: &[u8]) -> Result<Self, CalibrationError> {
let mut calibration: Self =
printobserver_types::serde_json::from_slice(bytes).map_err(|error| {
CalibrationError::Shape {
detail: error.to_string(),
}
})?;
if calibration.schema_version != SCHEMA_VERSION {
return Err(invalid(
"schema_version",
format!(
"is {}, and this program reads version {SCHEMA_VERSION}",
calibration.schema_version
),
));
}
if calibration.image_size_px.contains(&0) {
return Err(invalid("image_size_px", "names an empty frame"));
}
let lens = calibration.intrinsics;
finite("intrinsics.fx", &[lens.fx, lens.fy], true)?;
finite("intrinsics.cx", &[lens.cx, lens.cy], false)?;
finite("intrinsics.k", &lens.k, false)?;
finite(
"bed_pose.rotation_rodrigues",
&calibration.bed_pose.rotation_rodrigues,
false,
)?;
finite(
"bed_pose.translation_mm",
&calibration.bed_pose.translation_mm,
false,
)?;
finite(
"drift_tolerance_px",
&[calibration.drift_tolerance_px],
true,
)?;
finite(
"alignment_max_offset_px",
&[calibration.alignment_max_offset_px],
true,
)?;
printobserver_vision_api::WebAddress::new(&calibration.camera_snapshot_url)
.map_err(|why| invalid("camera_snapshot_url", why))?;
if !is_date(&calibration.fit.calibrated_at) {
return Err(invalid("fit.calibrated_at", "is not a YYYY-MM-DD date"));
}
let names: std::collections::BTreeSet<&str> = calibration
.landmarks
.iter()
.map(|landmark| landmark.name.as_str())
.collect();
if names.len() < 2 || names.len() != calibration.landmarks.len() {
return Err(invalid(
"landmarks",
"must name at least two chassis landmarks, each once",
));
}
let mut patches = Vec::with_capacity(calibration.landmarks.len());
for landmark in &calibration.landmarks {
finite("landmarks.center_px", &landmark.center_px, false)?;
let [w, h] = calibration.image_size_px.map(f64::from);
if !((0.0..w).contains(&landmark.center_px[0])
&& (0.0..h).contains(&landmark.center_px[1]))
{
return Err(invalid("landmarks.center_px", "lies outside the frame"));
}
if !(1..=MAX_SEARCH_RADIUS_PX).contains(&landmark.search_radius_px) {
return Err(invalid(
"landmarks.search_radius_px",
format!("must be from 1 to {MAX_SEARCH_RADIUS_PX}"),
));
}
let png = base64::engine::general_purpose::STANDARD
.decode(&landmark.patch_png_base64)
.map_err(|error| invalid("landmarks.patch_png_base64", error.to_string()))?;
let patch = image::load_from_memory_with_format(&png, image::ImageFormat::Png)
.map_err(|error| invalid("landmarks.patch_png_base64", error.to_string()))?
.to_luma8();
if patch.width() < 2 || patch.height() < 2 {
return Err(invalid("landmarks.patch_png_base64", "is no patch"));
}
patches.push(patch);
}
calibration.patches = patches;
Ok(calibration)
}
pub(crate) fn patches(&self) -> &[GrayImage] {
&self.patches
}
#[must_use]
pub fn project(
&self,
points_mm: &[[f64; 3]],
print_z_mm: f64,
frame_size_px: [u32; 2],
) -> Vec<Option<[f64; 2]>> {
let [w, h] = frame_size_px.map(f64::from);
let projector = self.projector();
points_mm
.iter()
.map(|point| {
projector
.pixel([point[0], point[1], point[2] - print_z_mm])
.filter(|[u, v]| (0.0..w).contains(u) && (0.0..h).contains(v))
})
.collect()
}
pub(crate) fn projector(&self) -> Projector {
let [rx, ry, rz] = self.bed_pose.rotation_rodrigues;
let [tx, ty, tz] = self.bed_pose.translation_mm;
Projector {
rotation: Rotation3::new(Vector3::new(rx, ry, rz)),
translation: Vector3::new(tx, ty, tz),
lens: self.intrinsics,
}
}
#[must_use]
pub fn camera_centre_mm(&self) -> [f64; 3] {
let projector = self.projector();
let centre = -(projector.rotation.inverse() * projector.translation);
[centre.x, centre.y, centre.z]
}
#[must_use]
pub fn with_bed_pose(&self, bed_pose: BedPose) -> Self {
Self {
bed_pose,
..self.clone()
}
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Projector {
rotation: Rotation3<f64>,
translation: Vector3<f64>,
lens: Intrinsics,
}
impl Projector {
pub(crate) fn pixel(&self, world: [f64; 3]) -> Option<[f64; 2]> {
let camera = self.rotation * Vector3::new(world[0], world[1], world[2]) + self.translation;
if camera.z <= 1e-6 {
return None;
}
let (a, b) = (camera.x / camera.z, camera.y / camera.z);
let r = a.hypot(b);
let theta = r.atan();
let t2 = theta * theta;
let [k1, k2, k3, k4] = self.lens.k;
let theta_d = theta * (1.0 + t2 * (k1 + t2 * (k2 + t2 * (k3 + t2 * k4))));
let scale = if r > 1e-12 { theta_d / r } else { 1.0 };
Some([
self.lens.fx * a * scale + self.lens.cx,
self.lens.fy * b * scale + self.lens.cy,
])
}
}