From 3296ea3e8128602a39c0ea11d7182b76bb4ed0d2 Mon Sep 17 00:00:00 2001 From: Fabien Freling Date: Tue, 11 May 2021 19:11:14 +0200 Subject: [PATCH] add alternate diffuse method --- in_one_weekend/src/main.zig | 2 +- in_one_weekend/src/vec3.zig | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/in_one_weekend/src/main.zig b/in_one_weekend/src/main.zig index c3f78ef..c9e1372 100644 --- a/in_one_weekend/src/main.zig +++ b/in_one_weekend/src/main.zig @@ -41,7 +41,7 @@ fn rayColor(ray: Ray, world: World, rng: *Random, depth: i32) Color { } if (world.hit(ray, 0.001, 99999)) |hit| { - const target = hit.p.add(hit.normal).add(vec3.random_in_unit_sphere(rng)); + const target = hit.p.add(vec3.random_in_hemisphere(rng, hit.normal)); const newRay = Ray{ .origin = hit.p, .direction = target.sub(hit.p)}; return rayColor(newRay, world, rng, depth - 1).div(2); } diff --git a/in_one_weekend/src/vec3.zig b/in_one_weekend/src/vec3.zig index 4b81de6..456204b 100644 --- a/in_one_weekend/src/vec3.zig +++ b/in_one_weekend/src/vec3.zig @@ -87,6 +87,20 @@ pub fn random_in_unit_sphere(rng: *Random) Vec3 { } } +pub fn random_unit_vector(rng: *Random) Vec3 { + return unitVector(random_in_unit_sphere(rng)); +} + +pub fn random_in_hemisphere(rng: *Random, normal: Vec3) Vec3 { + const in_unit_sphere = random_in_unit_sphere(rng); + if (in_unit_sphere.dot(normal) > 0) { + // In the same hemisphere as the normal + return in_unit_sphere; + } else { + return in_unit_sphere.mul(-1); + } +} + pub const Point3 = Vec3; const assert = @import("std").debug.assert;