From 1dd46df3cec9814534f13d3808014b5ae698df4f Mon Sep 17 00:00:00 2001 From: Tom Barrett Date: Mon, 19 Dec 2022 16:04:21 +0100 Subject: 5.2 --- src/main.zig | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) (limited to 'src/main.zig') diff --git a/src/main.zig b/src/main.zig index 7ae5c9e..7012bfb 100644 --- a/src/main.zig +++ b/src/main.zig @@ -6,6 +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 }; + } const direction = unit_vector(r.direction); const t = 0.5 * (direction[1] + 1.0); return scalar(1.0 - t) * vec{ 1.0, 1.0, 1.0 } + scalar(t) * vec{ 0.5, 0.7, 1.0 }; @@ -18,11 +21,24 @@ 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 { + 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; +} + const vec = @Vector(3, f32); pub fn scalar(x: f32) vec { return @splat(3, x); } +pub fn dot(x: vec, y: vec) f32 { + return x[0] * y[0] + x[1] * y[1] + x[2] * y[2]; +} + const ray = struct { origin: vec, direction: vec }; pub fn main() !void { -- cgit v1.2.3