library: core: camera: add deserialization

This commit is contained in:
Bruno BELANYI 2020-03-18 13:03:12 +01:00
parent 0644d453b8
commit 076118edaa

View file

@ -1,5 +1,6 @@
use super::film::Film; use super::film::Film;
use crate::{Point, Vector}; use crate::{Point, Vector};
use serde::{Deserialize, Deserializer};
/// Represent an abstract camera to observe the scene. /// Represent an abstract camera to observe the scene.
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
@ -19,7 +20,7 @@ impl Camera {
dist_to_image: f32, dist_to_image: f32,
x: u32, x: u32,
y: u32, y: u32,
) -> Camera { ) -> Self {
let right = forward.cross(&up); let right = forward.cross(&up);
let center = origin + forward.normalize() * dist_to_image; let center = origin + forward.normalize() * dist_to_image;
let screen_size = 2. * f32::tan(fov / 2.) * dist_to_image; let screen_size = 2. * f32::tan(fov / 2.) * dist_to_image;
@ -36,6 +37,41 @@ impl Camera {
} }
} }
#[derive(Debug, Deserialize)]
struct SerializedCamera {
origin: Point,
forward: Vector,
up: Vector,
fov: f32,
distance_to_image: f32,
x: u32,
y: u32,
}
impl From<SerializedCamera> for Camera {
fn from(cam: SerializedCamera) -> Self {
Camera::new(
cam.origin,
cam.forward,
cam.up,
std::f32::consts::PI * cam.fov / 180.,
cam.distance_to_image,
cam.x,
cam.y,
)
}
}
impl<'de> Deserialize<'de> for Camera {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let cam: SerializedCamera = Deserialize::deserialize(deserializer)?;
Ok(cam.into())
}
}
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use super::*; use super::*;
@ -66,4 +102,32 @@ mod test {
} }
) )
} }
#[test]
fn deserialization_works() {
let yaml = r#"
origin: [-1.0, 0.0, 0.0]
forward: [ 1.0, 0.0, 0.0]
up: [0.0, 1.0, 0.0]
fov: 90.0
distance_to_image: 1.0
x: 1080
y: 1080
"#;
let cam: Camera = serde_yaml::from_str(yaml).unwrap();
assert_eq!(
cam,
Camera {
origin: Point::new(-1., 0., 0.),
film: Film::new(
1080,
1080,
2.,
Point::origin(),
Vector::new(0., 1., 0.),
Vector::new(0., 0., 1.),
)
}
)
}
} }