diff --git a/zigrtiow/src/main.zig b/zigrtiow/src/main.zig index 3c794d4..9494faf 100644 --- a/zigrtiow/src/main.zig +++ b/zigrtiow/src/main.zig @@ -15,8 +15,7 @@ const Point3 = vec.Point3; const Ray = ray.Ray; const Sphere = sphere.Sphere; const Vec3 = vec.Vec3; -const random_unit_vector = vec.random_unit_vector; -const random_in_unit_sphere = vec.random_in_unit_sphere; +const random_in_hemisphere = vec.random_in_hemisphere; const info = std.log.info; const write_color = color.write_color; @@ -26,7 +25,7 @@ fn ray_color(r: Ray, world: Hittable, depth: isize) Color { var hit = world.hit(r, 0.0001, std.math.inf(f32)); if (hit) |rec| { - const target = rec.p.add(rec.normal.add(random_unit_vector())); + const target = rec.p.add(rec.normal.add(random_in_hemisphere(rec.normal))); return ray_color(Ray.init(rec.p, target.sub(rec.p)), world, depth - 1).scale(0.5); } var unit_direction = r.direction().unit(); diff --git a/zigrtiow/src/vec.zig b/zigrtiow/src/vec.zig index df190da..298547d 100644 --- a/zigrtiow/src/vec.zig +++ b/zigrtiow/src/vec.zig @@ -64,6 +64,14 @@ pub fn random_in_unit_sphere() Vec3 { pub fn random_unit_vector() Vec3 { return random_in_unit_sphere().unit(); } +pub fn random_in_hemisphere(normal: Vec3) Vec3 { + const in_unit_sphere = random_in_unit_sphere(); + if (in_unit_sphere.dot(normal) > 0.0) { // In the same hemisphere as the normal + return in_unit_sphere; + } else { + return in_unit_sphere.scale(-1); + } +} pub const Color = Vec3; pub const Point3 = Vec3;