diff options
author | Tom Barrett <tom@tombarrett.xyz> | 2022-12-19 16:04:21 +0100 |
---|---|---|
committer | Tom Barrett <tom@tombarrett.xyz> | 2022-12-19 16:04:21 +0100 |
commit | 1dd46df3cec9814534f13d3808014b5ae698df4f (patch) | |
tree | 26bb9770d14ca7babeb005c578d50019f86b871f /src/main.zig | |
parent | 875a863a41f7ad46d4cfb63f421907e16e90c228 (diff) |
5.2
Diffstat (limited to 'src/main.zig')
-rw-r--r-- | src/main.zig | 16 |
1 files changed, 16 insertions, 0 deletions
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 { |