Languages: C++
Technologies:
Skills: Multithreading, Monte-Carlo sampling
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.
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).
Ray intersection was implemented for:
Splatting rays to the image was implemented with multiple filters:
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:
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.
I implemented two models for Plastics, toggled with the PlasticPhong define.
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 🙂.
The layered material simulates covering a material with a homogenous dielectric participating media of uniform thickness, supporting single-scattering and Beer’s Law.
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:
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.
I implemented MIS using the power heuristic \(w = \frac{p_1^2}{p_1^2 + p_2^2}\)
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();
}
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]);
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.
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.
I implemented 3 tonemappers:
These functions are then wrapped by tonemap() in Imaging.h, which handles the averaging per sample, gamma correction and clamping.
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.