bounce rays around

This commit is contained in:
Fabien Freling 2021-05-10 23:30:34 +02:00
parent a3df9a7707
commit 58f710c967
3 changed files with 42 additions and 8 deletions

View file

@ -1,5 +1,6 @@
const std = @import("std");
const print = std.debug.print;
const Random = std.rand.Random;
const sdl = @import("sdl.zig");
const vec3 = @import("vec3.zig");
const Vec3 = vec3.Vec3;
@ -33,9 +34,16 @@ fn hitSphere(center: Point3, radius: f32, ray: Ray) f32 {
}
}
fn rayColor(ray: Ray, world: World) Color {
if (world.hit(ray, 0, 99999)) |hit| {
return hit.normal.add(Vec3{ .x = 1, .y = 1, .z = 1}).div(2);
fn rayColor(ray: Ray, world: World, rng: *Random, depth: i32) Color {
// If we've exceeded the ray bounce limit, no more light is gathered.
if (depth <= 0) {
return Color{ .x = 0, .y = 0, .z = 0 };
}
if (world.hit(ray, 0.001, 99999)) |hit| {
const target = hit.p.add(hit.normal).add(vec3.random_in_unit_sphere(rng));
const newRay = Ray{ .origin = hit.p, .direction = target.sub(hit.p)};
return rayColor(newRay, world, rng, depth - 1).div(2);
}
const unitDirection = vec3.unitVector(ray.direction);
const t = 0.5 * (unitDirection.y + 1.0);
@ -76,6 +84,7 @@ pub fn main() anyerror!void {
const imageWidth = 600;
const imageHeight = @floatToInt(usize, imageWidth / aspectRatio);
const samplesPerPixel = 100;
const maxDepth = 5;
// World
const spheres = [_]Sphere{
@ -143,7 +152,7 @@ pub fn main() anyerror!void {
const u = (@intToFloat(f32, i) + prng.random.float(f32)) / @intToFloat(f32, (imageWidth - 1));
const v = (@intToFloat(f32, j) + prng.random.float(f32)) / @intToFloat(f32, (imageHeight - 1));
const r = camera.getRay(u, v);
const sample = rayColor(r, world);
const sample = rayColor(r, world, &prng.random, maxDepth);
pixelColor.* = pixelColor.*.add(sample);
const averageColor = color.averageColor(pixelColor, @intCast(i32, k));