From 67628ec0832a2b2f5d61473b8213dd45cb268864 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Wed, 18 Mar 2020 15:42:45 +0100 Subject: [PATCH] library: render: object: add deserialization By using `enum_dispatch` and deserializing the enums, you can very easily represent the `Object` in serialized form. --- src/render/object.rs | 47 +++++++++++++++++++++++++++++++++++--------- 1 file changed, 38 insertions(+), 9 deletions(-) diff --git a/src/render/object.rs b/src/render/object.rs index b97b098..eefaacd 100644 --- a/src/render/object.rs +++ b/src/render/object.rs @@ -1,9 +1,10 @@ use crate::material::MaterialEnum; use crate::shape::ShapeEnum; use crate::texture::TextureEnum; +use serde::Deserialize; /// An object being rendered in the scene. -#[derive(Debug, PartialEq)] +#[derive(Debug, PartialEq, Deserialize)] pub struct Object { pub shape: ShapeEnum, pub material: MaterialEnum, @@ -29,22 +30,28 @@ mod test { use crate::texture::UniformTexture; use crate::Point; - #[test] - fn new_works() { - let shape = Sphere::new(Point::origin(), 1.); + fn simple_object() -> Object { + let shape = Sphere::new(Point::new(5., 0., 0.), 1.); let material = UniformMaterial::new( LinearColor::new(0.5, 0.5, 0.5), LinearColor::new(1., 1., 1.), 0.5, ); let texture = UniformTexture::new(LinearColor::new(0.25, 0.5, 1.)); - let object = Object::new( - shape.clone().into(), - material.clone().into(), - texture.clone().into(), + Object::new(shape.into(), material.into(), texture.into()) + } + + #[test] + fn new_works() { + let shape = Sphere::new(Point::new(5., 0., 0.), 1.); + let material = UniformMaterial::new( + LinearColor::new(0.5, 0.5, 0.5), + LinearColor::new(1., 1., 1.), + 0.5, ); + let texture = UniformTexture::new(LinearColor::new(0.25, 0.5, 1.)); assert_eq!( - object, + simple_object(), Object { shape: shape.into(), material: material.into(), @@ -52,4 +59,26 @@ mod test { } ) } + + #[test] + fn deserialization_works() { + let yaml = r#" + shape: + type: sphere + inverted: false + center: [5., 0.0, 0.0] + radius: 1.0 + material: + type: uniform + diffuse: {r: 0.5, g: 0.5, b: 0.5} + specular: {r: 1., g: 1., b: 1.} + reflectivity: 0.5 + texture: + type: uniform + color: {r: 0.25, g: 0.5, b: 1.} + "#; + let object: Object = serde_yaml::from_str(yaml).unwrap(); + let expected = simple_object(); + assert_eq!(object, expected) + } }