< Back

CPU Pathtracer

The kitchen scene, denoised at 16spp

The bathroom scene, denoised at 16spp

The glass-of-water scene, denoised at 16spp

The staircase scene, denoised at 16spp

Languages: C++

Technologies:

Skills: Multithreading, Monte-Carlo sampling

Overview

This CPU-based ray-tracer implements:

As a coursework assessment it utilised a skeleton project which handled rendering to the screen, scene-loading and provided a starting structure.

Images

In order to save repo space and improve load times the embedded images are compressed .webp files unless otherwise mentioned. I have verified that the compressed images still convey the necessary details, even if they may not be 1:1 with the uncompressed versions. All figures can be full-screened by clicking on them (including the comparisons).

Technical Details

Core Loop

Ray Intersection

Ray intersection was implemented for:

Splatting

Splatting rays to the image was implemented with multiple filters:

Materials

Materials are implemented using BSDFs. These provide sample(), evaluate() and PDF() methods to evaluate the BSDF for given input and output vectors. 8 Material BSDFs were implemented:

Oren-Nayar

Oren Nayar spheres in MaterialsScene at 32spp, with alpha values ranging from 0 to 0.6 (left to right)
Figure 1: Oren Nayar spheres in MaterialsScene at 32spp, with alpha values ranging from 0 to 0.6 (left to right)

Glass

Glass spheres in MaterialsScene at 32spp, with interior IoR values ranging from 1 to 2.25 (left to right, NB 1 is basically invisible)
Figure 2: Glass spheres in MaterialsScene at 32spp, with interior IoR values ranging from 1 to 2.25 (left to right, NB 1 is basically invisible)

Conductors

Conductor spheres in MaterialsScene at 32spp, with roughness 0, 0.01, 0.02, 0.04, 0.06, 0.08
Figure 3: Conductor spheres in MaterialsScene at 32spp, with roughness 0, 0.01, 0.02, 0.04, 0.06, 0.08

Dielectrics

Dielectric spheres in MaterialsScene at 32spp.<br>**Horizontal:** $$\eta$$ alternates between $$2/3$$ and $$1/2$$, and roughness is in pairs of 0.01, 0.04, 0.08.<br>**Vertical:** demonstrates different absorption factors: the top has uniform absorption no matter the distance travelled, followed by factors of 1, 5, 10 and 100
Figure 4: Dielectric spheres in MaterialsScene at 32spp.
Horizontal: \(\eta\) alternates between \(2/3\) and \(1/2\), and roughness is in pairs of 0.01, 0.04, 0.08.
Vertical: demonstrates different absorption factors: the top has uniform absorption no matter the distance travelled, followed by factors of 1, 5, 10 and 100

The provided SceneLoader and scenes did not include absorption parameters for Dielectric materials. As such, I came up with two different methods for approximating the effect when testing the material.

Plastic

I implemented two models for Plastics, toggled with the PlasticPhong define.

  1. A simple Phong + Lambert model.
  2. Dielectric reflections, but replacing transmission rays with Lambert diffuse.

I came up with #2 myself, and I haven’t checked whether it’s fully energy-conserving (I suspect it’s not), but it looks pretty 🙂.

A comparison of the Phong (top) and dielectric (bottom) models using spheres in MaterialsScene at 32spp.<br>**Horizontal:** $$\eta$$ alternates between $$2/3$$ and $$1/2$$, and roughness is in pairs of 0.01, 0.04, 0.08.<br>
Figure 5: A comparison of the Phong (top) and dielectric (bottom) models using spheres in MaterialsScene at 32spp.
Horizontal: \(\eta\) alternates between \(2/3\) and \(1/2\), and roughness is in pairs of 0.01, 0.04, 0.08.
A comparison of the Phong (top) and dielectric (bottom) models in the Kitchen scene
Figure 6: A comparison of the Phong (top) and dielectric (bottom) models in the Kitchen scene

Layered

Conductor spheres with roughness 0.007 covered by a dielectric layer in MaterialsScene at 32spp.<br>**Top:** Covering roughness of 0 and thickness of 0, 0.1, 0.25, 0.5, 1.<br>**Bottom:** Left is reference (0 thickness), then 5 spheres with a covering thickness of 1 and increasing interior IoR values ranging from 1.25 to 2.25
Figure 7: Conductor spheres with roughness 0.007 covered by a dielectric layer in MaterialsScene at 32spp.
Top: Covering roughness of 0 and thickness of 0, 0.1, 0.25, 0.5, 1.
Bottom: Left is reference (0 thickness), then 5 spheres with a covering thickness of 1 and increasing interior IoR values ranging from 1.25 to 2.25

The layered material simulates covering a material with a homogenous dielectric participating media of uniform thickness, supporting single-scattering and Beer’s Law.

Sampling

Importance Sampling

When sampling area lights each light is weighted by its integrated power divided by the square of its distance to the shaded point (\(P/d^2\)). This reduces variance significantly, cancelling the emitted radiance term in the rendering equation as well as the division by \(d^2\) in the geometry term. This is shown well by the kitchen scene:

A comparison of the different importance sampling methods in the Kitchen scene.<br>**Horizontal:** Left is uniform, middle is $$P/d^2$$, right is $$P$$
Figure 8: A comparison of the different importance sampling methods in the Kitchen scene.
Horizontal: Left is uniform, middle is \(P/d^2\), right is \(P\)

If there are over 100 lights in the same, uniform sampling is used instead as the higher quality sampling method requires a linear loop (or a complicated acceleration structure which I did not have time to implement).

Importance sampling for environment maps was implemented using two acceleration tables. One holds the cumulative pdfs of each row going down, and the other holds the cumulative pdfs of each row going across. These can be queried in O(log n) time using binary search.

However, the implementation is currently commented out and instead uses cosine sphere sampling as a fallback, as there is a bug (or multiple..) resulting in rendering errors that I was unable to find in the time constraints.

Multiple Importance Sampling

I implemented MIS using the power heuristic \(w = \frac{p_1^2}{p_1^2 + p_2^2}\)

A comparison of the staircase2 scene at 4SPP without (left) and with (right) MIS
Figure 9: A comparison of the staircase2 scene at 4SPP without (left) and with (right) MIS

Optimisations

Multithreading

class TaskThread
{
  std::jthread myThread;

  std::mutex mtx;
  std::condition_variable waitOnQueue;
  std::condition_variable waitOnTask;
  //std:: snipped to avoid wrapping
  queue<function<void(stop_token)>> taskQueue;
  std::atomic<unsigned int> tasksCompleted;
  std::atomic<unsigned int> tasksQueued;

  void loop(std::stop_token stop);

public:

  TaskThread();
  ~TaskThread(); //std:: snipped to avoid wrapping
  uint QueueTask(function<void(stop_token)> task);
  void Join(unsigned int targetTask);
  void Stop();
}
Code Snippet 1: An overview of the TaskThread class from ThreadHelper.h.

Multithreading was implemented with a thread pool, defined in ThreadHelper.h. The TaskThread class, detailed in Code Snippet 1, wraps thread execution. Each TaskThread has a queue of tasks (void function pointers), and two condition variables.

When a task is queued, it is pushed to the end of taskQueue and the waitOnQueue condition variable is notified. This will wake the TaskThread if it was previously idle. Tasks are given an unsigned int as an id when queued, and this is returned by the Queue method.

When a task is completed, the waitOnTask condition variable is notified. Threads can wait on specific tasks to be completed by calling the Join(int target) method, which will be woken in this situation.

std::atomic<int> tileCount = 0;

for (int i = 0; i < threads.size(); i++)
{
    auto renderT = [&, i](std::stop_token stop)
    {
        unsigned int myTile;
        while ((myTile = tileCount++) < maxTiles
                && !stop.stop_requested())
        {
            renderTile(myTile, &(samplers[i]));
        }
    };
    taskIDs[i] = threads[i]->QueueTask(renderT);
}

for (int i = 0; i < threads.size(); i++)
    threads[i]->Join(taskIDs[i]);
Code Snippet 2: The tile-based loop for pure pathtracing, located in Renderer.h as part of renderMT().

The renderer used tile-based multithreading with a fixed tile size of 16x16 pixels. Tiles are assigned to each thread by an increment on an atomic int. This avoids the need for slower locking mechanisms and provides load-balancing between threads, at the cost of reduced locality. An overview of this can be seen in Code Snippet 2

The implementation is not a complete thread pool, since there is no manager for the threads (they are instead indexed directly as part of the threads array), but this had no effect on the overall program as rendering is the only situation where the threads are used.

Bounding Volume Hierarchy (BVH)

I constructed scene BVHs with a binned Surface Area Heuristic algorithm. I settled on a fixed 10 bins, as I found this performed similarly to 30 and 100+ bins in the tested scenes, while drastically reducing the time required to build the BVH. I also disregard the SAH evaluation when considering 4 or fewer nodes, instead forcibly creating leaves, as below this count the the AABB ray intersection check is unlikely to save time compared to simply checking the intersection of the 4 triangles.

The BVH is constructed using an indices vector, which maps to the scene triangles vector passed in. This allows each BVHNode to simply store a pointer to the indices array alongside a length. However, it does necessitate that the scene objects cannot change after BVH construction. Each BVHNode stores an AABB which is extended to encompass all vertices of a node’s triangles. The SAH cost is then computed for each bin along the X, Y and Z axes. The indices array is then re-arranged so that triangles on the left and right of the chosen split position are at the beginning and end of the segment being operated on.

Post-processing

Tone-mapping

I implemented 3 tonemappers:

\[C(x) = \frac{x\cdot(A\cdot x+ C\cdot B) + D\cdot E}{x\cdot(A\cdot x + B) + D\cdot F}-\frac{E}{F}\]

These functions are then wrapped by tonemap() in Imaging.h, which handles the averaging per sample, gamma correction and clamping.

Denoising

Figure 10: Staircase2 denoised output at 1spp

Denoising is implemented via the Intel® Open Image Denoise library. When enabled rays also sample the albedo and normal of the hit material. Purely specular materials instead pass the ray along, using the fresnel blend of reflected and refracted (glass only) rays. This has a maximum depth of 5 to avoid infinite loops.