C++ Ray Tracer
A C++ path tracer built step by step, up to Monte Carlo lighting.
- My role
- Personal learning project
- Timeline
- 2025
- Status
- Completed

01 / Context
Overview
I built a path tracer from scratch in C++, following the approach in Ray Tracing in One Weekend. It sends rays from the camera through each pixel into the scene and works out what colour each one should be.
I built it up in four stages, each adding one idea and checked with a render before moving on: first finding what a ray hits, then the surface’s orientation, then a sky, and finally how light bounces.
02 / Contribution
The work
Stage 1: rays and a sphere
Each ray is a parametric line, P(t) = O + t·d. Substituting it into the sphere’s equation gives a quadratic in t: the discriminant says whether the ray misses, grazes, or hits the sphere, and the smallest positive root is the point the camera sees.
For the first render, rays that hit the sphere were coloured red and rays that missed were black.
Stage 2: surface normals
To make the sphere look three-dimensional, each hit point needs a surface normal. For a sphere it is the direction from the centre to the hit point, (P − C) / R. Before adding any lighting, I checked the normals visually by mapping their x, y, and z components from [−1, 1] to red, green, and blue.
Stage 3: a sky
Next, I replaced the black background with a sky. Each ray that misses takes its colour from a linear blend between white and blue, based on how far up it points.
Stage 4: diffuse light and random sampling
Finally, I made the surfaces matte. When a ray hits one, it bounces off in a random direction and picks up colour from wherever it goes next. To choose the direction, I pick random points in a cube and keep the first one that falls inside a unit sphere. This is Monte Carlo path tracing.
With one random sample per pixel, the image was very noisy. Averaging many samples per pixel smooths out both the noise and the jagged edges, because the average converges to the true lighting as the number of samples grows. The cost is time: more samples meant much longer renders.
03 / Reflection
Outcome
The finished ray tracer turns vectors, quadratic equations, and random sampling into soft, realistic shading. It is limited to matte spheres, with no specular reflections, transparency, or other shapes yet. Natural next steps are ray–plane intersections and triangle meshes, which would allow more complex scenes.


