From c16ba06a53c4a023f834650ee141e7a72be0eda7 Mon Sep 17 00:00:00 2001 From: Bill Thiede Date: Sat, 8 Sep 2018 21:53:15 -0700 Subject: [PATCH] Normal shading of sphere. Doesn't quite work right. --- rtiow/src/bin/tracer_norm_shade.rs | 51 ++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 rtiow/src/bin/tracer_norm_shade.rs diff --git a/rtiow/src/bin/tracer_norm_shade.rs b/rtiow/src/bin/tracer_norm_shade.rs new file mode 100644 index 0000000..7f65e77 --- /dev/null +++ b/rtiow/src/bin/tracer_norm_shade.rs @@ -0,0 +1,51 @@ +extern crate rtiow; + +use rtiow::ray::Ray; +use rtiow::vec3::dot; +use rtiow::vec3::Vec3; + +fn hit_sphere(center: Vec3, radius: f32, r: Ray) -> f32 { + let oc = r.origin() - center; + let a = dot(r.direction(), r.direction()); + let b = 2. * dot(oc, r.direction()); + let c = dot(oc, oc) - radius * radius; + let discriminant = b * b - 4. * a * c; + if discriminant < 0. { + return -1.; + } + -b - discriminant.sqrt() / (2. * a) +} + +fn color(r: Ray) -> Vec3 { + let t = hit_sphere(Vec3::new(0., 0., -1.), 0.5, r); + if t > 0. { + let n = (r.point_at_parameter(t) - Vec3::new(0., 0., -1.)).unit_vector(); + return (n + 1.) * 0.5; + } + let unit_direction = r.direction().unit_vector(); + let t = 0.5 * (unit_direction.y + 1.); + Vec3::new(1., 1., 1.) * (1. - t) + Vec3::new(0.5, 0.7, 1.) * t +} + +fn main() -> Result<(), std::io::Error> { + let nx = 200; + let ny = 100; + println!("P3\n{} {}\n255", nx, ny); + let lower_left_corner = Vec3::new(-2., -1., -1.); + let horizontal = Vec3::new(4., 0., 0.); + let vertical = Vec3::new(0., 2., 0.); + let origin: Vec3 = Default::default(); + for j in (0..ny).rev() { + for i in 0..nx { + let u = i as f32 / nx as f32; + let v = j as f32 / ny as f32; + let r = Ray::new(origin, lower_left_corner + horizontal * u + vertical * v); + let col = color(r); + let ir = (255.99 * col[0]) as u32; + let ig = (255.99 * col[1]) as u32; + let ib = (255.99 * col[2]) as u32; + println!("{} {} {}", ir, ig, ib); + } + } + Ok(()) +}