accumulate pixel values and display each sample run

master
Fabien Freling 2021-04-26 23:50:14 +02:00
parent b0ce3eecec
commit 61627fb76c
2 changed files with 27 additions and 19 deletions

View File

@ -4,10 +4,10 @@ const Vec3 = @import("vec3.zig").Vec3;
pub const Color = 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. // Divide the color by the number of samples.
// const scale = 1.0 / @intToFloat(f32, samplesPerPixel); // const scale = 1.0 / @intToFloat(f32, samplesPerPixel);
var scaledColor = pixelColor.div(@intToFloat(f32, samplesPerPixel)); var scaledColor = pixelColor.*.div(@intToFloat(f32, samplesPerPixel));
return Color{ return Color{
.x = math.clamp(scaledColor.x, 0, 0.999), .x = math.clamp(scaledColor.x, 0, 0.999),

View File

@ -85,35 +85,43 @@ pub fn main() anyerror!void {
}; };
var prng = std.rand.DefaultPrng.init(42); var prng = std.rand.DefaultPrng.init(42);
var pixelAccu: [imageWidth * imageHeight]Color = undefined;
for (pixelAccu) |*pixel| {
pixel.* = Color{};
}
{ {
_ = sdl.c.SDL_LockSurface(surface); _ = sdl.c.SDL_LockSurface(surface);
var j: usize = 0; var k: usize = 0;
while (j < imageHeight) { while (k < samplesPerPixel) {
var i: usize = 0; _ = sdl.c.SDL_LockSurface(surface);
while (i < imageWidth) {
var pixelColor = Color{}; var j: usize = 0;
var k: usize = 0; while (j < imageHeight) {
while (k < samplesPerPixel) { 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 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 v = (@intToFloat(f32, j) + prng.random.float(f32)) / @intToFloat(f32, (imageHeight - 1));
const r = camera.getRay(u, v); const r = camera.getRay(u, v);
const sample = rayColor(r, world); 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;
} }
j += 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; 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) { if (sdl.c.SDL_UpdateWindowSurface(window) != 0) {