From 61627fb76c8edef0ef5abe024d082d477669d085 Mon Sep 17 00:00:00 2001 From: Fabien Freling Date: Mon, 26 Apr 2021 23:50:14 +0200 Subject: [PATCH] accumulate pixel values and display each sample run --- in_one_weekend/src/color.zig | 4 ++-- in_one_weekend/src/main.zig | 42 +++++++++++++++++++++--------------- 2 files changed, 27 insertions(+), 19 deletions(-) diff --git a/in_one_weekend/src/color.zig b/in_one_weekend/src/color.zig index bd04896..d15dadd 100644 --- a/in_one_weekend/src/color.zig +++ b/in_one_weekend/src/color.zig @@ -4,10 +4,10 @@ const Vec3 = @import("vec3.zig").Vec3; pub const Color = Vec3; -pub fn averageColor(pixelColor: Color, samplesPerPixel: i32) Color { +pub fn averageColor(pixelColor: *Color, samplesPerPixel: i32) Color { // Divide the color by the number of samples. // const scale = 1.0 / @intToFloat(f32, samplesPerPixel); - var scaledColor = pixelColor.div(@intToFloat(f32, samplesPerPixel)); + var scaledColor = pixelColor.*.div(@intToFloat(f32, samplesPerPixel)); return Color{ .x = math.clamp(scaledColor.x, 0, 0.999), diff --git a/in_one_weekend/src/main.zig b/in_one_weekend/src/main.zig index e7c252b..abec5c8 100644 --- a/in_one_weekend/src/main.zig +++ b/in_one_weekend/src/main.zig @@ -85,35 +85,43 @@ pub fn main() anyerror!void { }; var prng = std.rand.DefaultPrng.init(42); + var pixelAccu: [imageWidth * imageHeight]Color = undefined; + for (pixelAccu) |*pixel| { + pixel.* = Color{}; + } { _ = sdl.c.SDL_LockSurface(surface); - var j: usize = 0; - while (j < imageHeight) { - var i: usize = 0; - while (i < imageWidth) { - var pixelColor = Color{}; - var k: usize = 0; - while (k < samplesPerPixel) { + var k: usize = 0; + while (k < samplesPerPixel) { + _ = sdl.c.SDL_LockSurface(surface); + + var j: usize = 0; + while (j < imageHeight) { + var i: usize = 0; + while (i < imageWidth) { + var imageIndex = i + j * imageWidth; + var pixelColor = &pixelAccu[imageIndex]; + 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); - pixelColor = pixelColor.add(sample); + pixelColor.* = pixelColor.*.add(sample); - k += 1; + const averageColor = color.averageColor(pixelColor, @intCast(i32, k)); + // SDL coordinate system is flipped compared to the raytracer + sdl.setSurfacePixel(surface, i, imageHeight - 1 - j, averageColor); + + i += 1; } - - const averageColor = color.averageColor(pixelColor, samplesPerPixel); - // SDL coordinate system is flipped compared to the raytracer - sdl.setSurfacePixel(surface, i, imageHeight - 1 - j, averageColor); - - i += 1; + j += 1; } - j += 1; + sdl.c.SDL_UnlockSurface(surface); + _ = sdl.c.SDL_UpdateWindowSurface(window); + k += 1; } - defer sdl.c.SDL_UnlockSurface(surface); } if (sdl.c.SDL_UpdateWindowSurface(window) != 0) {