Ray Tracer icon

Active2025 – now

Ray Tracer

A progressive path tracer running as a GPU compute shader on Dahlia.

  • C++20
  • GLSL compute
  • Dahlia
  • Metal
  • Vulkan
  • Path tracing
  • Dear ImGui
After 717 accumulated frames. Glass spheres refract and reflect by the Fresnel equations, and the small sphere is a light source.
64 Rays per pixel per frame
10 Bounces per ray
100 Frames per second (Metal, M4 Pro)
2 Backends (Metal, Vulkan)

Every pixel traces 64 light paths per frame, bouncing up to ten times between diffuse, mirror and glass spheres. The frames are averaged as they arrive, so the noisy first frame converges to a clean image in under a second.

The ray tracer is a compute shader (RayTrace.comp) running on Dahlia, so it works on both of Dahlia's compute backends: Metal by default, or Vulkan with --vulkan. It began as a Metal fragment shader following Sebastian Lague's Ray Tracing series. It was later ported to GLSL compute, so the engine's SPIR-V pipeline could take it to either API.

How a frame is made

One invocation runs per pixel. Each one traces 64 paths through the scene. At every hit, the material decides where the path goes next:

  • Diffuse: a random direction around the surface normal, drawn from a cosine-weighted distribution.
  • Specular: a mirror reflection. The specular factor picks between the two at random, so values between 0 and 1 give glossy surfaces.
  • Glass: reflection or refraction, chosen with probability given by Schlick's approximation of the Fresnel equations (refractive index 1.33), with total internal reflection handled.
  • Emissive: the surface adds light, which is how the small sphere lights the scene.

A path that escapes picks up light from a sky gradient and the ground. Random numbers come from a PCG hash seeded per pixel and per frame, so the noise changes every frame and averages away.

Progressive accumulation

Each frame's result is folded into a running average in a storage buffer, then written to a storage image that Dear ImGui displays:

\[ \bar{L}_n = \bar{L}_{n-1} + \frac{L_n - \bar{L}_{n-1}}{n} \]

While the camera and spheres are still, the image converges: after a few hundred frames there is no visible noise. Pressing Space animates the spheres and restarts the average every frame. That's useful for seeing what one frame really looks like.

Small details that matter

  • NaN guards. A diffuse direction that cancels the normal would normalise to NaN. One NaN would then poison that pixel's average forever, so it's caught before it can happen.
  • Unbiased random numbers. Uniform values use the top 24 bits of the PCG output, so converting to float can never round up to exactly 1.0, which would make log(1 − u) infinite.
  • The first frame overwrites. The accumulation buffer starts undefined, so the first frame replaces it rather than blending, since mix(NaN, x, 1) would still be NaN.