diff --git a/rtchallenge/src/canvas.rs b/rtchallenge/src/canvas.rs new file mode 100644 index 0000000..df282a7 --- /dev/null +++ b/rtchallenge/src/canvas.rs @@ -0,0 +1,50 @@ +use crate::tuples::{color, Color}; + +pub struct Canvas { + pub height: usize, + pub width: usize, + pub pixels: Vec, +} + +fn canvas(width: usize, height: usize) -> Canvas { + let pixels = vec![color(0., 0., 0.); width * height]; + Canvas { + width, + height, + pixels, + } +} + +impl Canvas { + pub fn set(&mut self, x: usize, y: usize, c: Color) { + self.pixels[x + y * self.width] = c; + } + pub fn get(&mut self, x: usize, y: usize) -> Color { + self.pixels[x + y * self.width] + } +} +#[cfg(test)] +mod tests { + use super::canvas; + + use crate::tuples::color; + + #[test] + fn create_canvas() { + let c = canvas(10, 20); + assert_eq!(c.width, 10); + assert_eq!(c.height, 20); + let black = color(0., 0., 0.); + for (i, p) in c.pixels.iter().enumerate() { + assert_eq!(p, &black, "pixel {} not {:?}: {:?}", i, &black, p); + } + } + + #[test] + fn write_to_canvas() { + let mut c = canvas(10, 20); + let red = color(1., 0., 0.); + c.set(2, 3, red); + assert_eq!(c.get(2, 3), red); + } +} diff --git a/rtchallenge/src/lib.rs b/rtchallenge/src/lib.rs index eecba71..afabcff 100644 --- a/rtchallenge/src/lib.rs +++ b/rtchallenge/src/lib.rs @@ -1 +1,2 @@ +pub mod canvas; pub mod tuples; diff --git a/rtchallenge/src/tuples.rs b/rtchallenge/src/tuples.rs index 19116c2..de1e8ef 100644 --- a/rtchallenge/src/tuples.rs +++ b/rtchallenge/src/tuples.rs @@ -125,12 +125,12 @@ pub fn cross(a: Tuple, b: Tuple) -> Tuple { } #[derive(Copy, Clone, Debug, PartialEq)] -struct Color { +pub struct Color { red: f32, green: f32, blue: f32, } -fn color(red: f32, green: f32, blue: f32) -> Color { +pub fn color(red: f32, green: f32, blue: f32) -> Color { Color { red, green, blue } } impl Add for Color {