From f2c68e0b6f05f2b7e25d421333ca92566ace5fc6 Mon Sep 17 00:00:00 2001 From: Bill Thiede Date: Sun, 31 Jul 2022 16:47:59 -0700 Subject: [PATCH] Use hit_sphere to draw red circle. --- zigrtiow/src/main.zig | 12 ++++++++++++ zigrtiow/src/vec.zig | 4 ++++ 2 files changed, 16 insertions(+) diff --git a/zigrtiow/src/main.zig b/zigrtiow/src/main.zig index 6756454..ae6ace6 100644 --- a/zigrtiow/src/main.zig +++ b/zigrtiow/src/main.zig @@ -10,7 +10,19 @@ const info = std.log.info; const write_color = color.write_color; const Ray = ray.Ray; +fn hit_sphere(center: Point3, radius: f32, r: Ray) bool { + const oc = r.origin().sub(center); + const a = Vec3.dot(r.direction(), r.direction()); + const b = Vec3.dot(oc, r.direction()) * 2; + const c = Vec3.dot(oc, oc) - radius * radius; + const discriminant = b * b - 4 * a * c; + return discriminant > 0; +} + fn ray_color(r: Ray) Color { + if (hit_sphere(Point3.init(0, 0, -1), 0.5, r)) { + return Color.init(1, 0, 0); + } var unit_direction = r.direction().unit(); var t = 0.5 * (unit_direction.y() + 1); return Color.init(1, 1, 1).scale(1 - t).add(Color.init(0.5, 0.7, 1.0).scale(t)); diff --git a/zigrtiow/src/vec.zig b/zigrtiow/src/vec.zig index 2a67544..cb98032 100644 --- a/zigrtiow/src/vec.zig +++ b/zigrtiow/src/vec.zig @@ -32,6 +32,10 @@ pub const Vec3 = struct { pub fn unit(vec: Vec3) Vec3 { return vec.scale(1 / vec.length()); } + pub fn dot(u: Vec3, v: Vec3) f32 { + const t = u.v * v.v; + return t[0] + t[1] + t[2]; + } }; pub const Color = Vec3; pub const Point3 = Vec3;