library: shape: triangle: add deserialization

This commit is contained in:
Bruno BELANYI 2020-03-18 14:46:30 +01:00
parent 8060262ce0
commit ccc9eaf423

View file

@ -2,6 +2,7 @@ use super::Shape;
use crate::{Point, Point2D, Vector};
use bvh::aabb::{Bounded, AABB};
use bvh::ray::Ray;
use serde::{Deserialize, Deserializer};
/// Represent a triangle inside the scene.
#[derive(Debug, PartialEq)]
@ -89,6 +90,31 @@ impl Shape for Triangle {
}
}
#[derive(Debug, Deserialize)]
struct SerializedTriangle {
corners: [Point; 3],
}
impl From<SerializedTriangle> for Triangle {
fn from(triangle: SerializedTriangle) -> Self {
Triangle::new(
triangle.corners[0],
triangle.corners[1],
triangle.corners[2],
)
}
}
impl<'de> Deserialize<'de> for Triangle {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let cam: SerializedTriangle = Deserialize::deserialize(deserializer)?;
Ok(cam.into())
}
}
#[cfg(test)]
mod test {
use super::*;
@ -180,4 +206,23 @@ mod test {
let ans = triangle.project_texel(&Point::origin());
assert!((ans - Point2D::new(0.5, 0.5)).norm() < 1e-5);
}
#[test]
fn deserialization_works() {
let yaml = r#"
corners:
- [0.0, 0.0, 0.0]
- [0.0, 1.0, 1.0]
- [0.0, 1.0, 0.0]
"#;
let triangle: Triangle = serde_yaml::from_str(yaml).unwrap();
assert_eq!(
triangle,
Triangle::new(
Point::origin(),
Point::new(0., 1., 1.),
Point::new(0., 1., 0.)
)
)
}
}