From 60592281229a8c6ff4f440e2b16ed4ff7bb1af20 Mon Sep 17 00:00:00 2001
From: Tom Barrett <tom@tombarrett.xyz>
Date: Mon, 19 Dec 2022 17:34:33 +0100
Subject: 6.1

---
 src/main.zig | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)

diff --git a/src/main.zig b/src/main.zig
index 7012bfb..c55bc06 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -6,8 +6,9 @@ pub fn unit_vector(v: vec) vec {
 }
 
 pub fn ray_color(r: ray) vec {
-    if (hit_sphere(vec{ 0, 0, -1 }, 0.5, r)) {
-        return vec{ 1.0, 0, 0 };
+    if (hit_sphere(vec{ 0, 0, -1 }, 0.5, r)) |t| {
+        const n = unit_vector(r.origin + scalar(t) * r.direction - vec{ 0, 0, -1 });
+        return scalar(0.5) * vec{ n[0] + 1, n[1] + 1, n[2] + 1 };
     }
     const direction = unit_vector(r.direction);
     const t = 0.5 * (direction[1] + 1.0);
@@ -21,13 +22,17 @@ pub fn write_color(stdout: anytype, v: vec) !void {
     try stdout.print("{} {} {}\n", .{ r, g, b });
 }
 
-pub fn hit_sphere(center: vec, radius: f32, r: ray) bool {
+pub fn hit_sphere(center: vec, radius: f32, r: ray) ?f32 {
     const oc = r.origin - center;
     const a = dot(r.direction, r.direction);
     const b = 2 * dot(oc, r.direction);
     const c = dot(oc, oc) - radius * radius;
     const discriminant = b * b - 4 * a * c;
-    return discriminant > 0;
+    if (discriminant < 0) {
+        return null;
+    } else {
+        return (-b - @sqrt(discriminant)) / (2 * a);
+    }
 }
 
 const vec = @Vector(3, f32);
-- 
cgit v1.2.3