From 4bb6a72e4bb62a1d0c7242fb647b1e377d5dd4e8 Mon Sep 17 00:00:00 2001 From: Bill Thiede Date: Fri, 16 Jul 2021 22:25:48 -0700 Subject: [PATCH] eoc5: implement suggestiong at end of chapter 5. --- rtchallenge/examples/eoc5.rs | 41 ++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 rtchallenge/examples/eoc5.rs diff --git a/rtchallenge/examples/eoc5.rs b/rtchallenge/examples/eoc5.rs new file mode 100644 index 0000000..6e374f4 --- /dev/null +++ b/rtchallenge/examples/eoc5.rs @@ -0,0 +1,41 @@ +use core::f32; + +use anyhow::Result; + +use rtchallenge::{ + canvas::Canvas, + rays::Ray, + spheres::{intersect, Sphere}, + tuples::{Color, Tuple}, +}; + +fn main() -> Result<()> { + let w = 200; + let h = w; + let mut c = Canvas::new(w, h); + let ray_origin = Tuple::point(0., 0., -5.); + let wall_z = 10.; + let wall_size = 7.; + let pixel_size = wall_size / w as f32; + let half = wall_size / 2.; + let color = Color::new(1., 0., 0.); + let shape = Sphere::default(); + + for y in 0..h { + let world_y = half - pixel_size * y as f32; + for x in 0..w { + let world_x = -half + pixel_size * x as f32; + let position = Tuple::point(world_x, world_y, wall_z); + let r = Ray::new(ray_origin, (position - ray_origin).normalize()); + let xs = intersect(&shape, &r); + if xs.hit().is_some() { + c.set(x, y, color); + } + } + } + + let path = "/tmp/eoc5.png"; + println!("saving output to {}", path); + c.write_to_file(path)?; + Ok(()) +}