Ray Tracing with Voxels in C++ Series – Part 2

In this series we build a physically based renderer for a dynamic voxel world. From ‘Whitted-style’ ray tracing with shadows, glass and mirrors, we go all the way to ‘unbiased path tracing’ – and beyond, exploring advanced topics such as reprojection, denoising and blue noise. The accompanying source code is available on Github and is written in easy-to-read ‘sane C++’.

This series consists of nine articles. Contents: (tentative until finalized)

  1. Starting point: Voxel ray tracing template code. Lights and shadows.
  2. Whitted-style: Reflections, recursion, glass (this article).
  3. Stochastic techniques: Anti-aliasing and soft shadows.
  4. Noise reduction: Stratification, blue noise.
  5. Converging under movement: Reprojection.
  6. Path tracing: Basics first; then: Importance Sampling.
  7. Denoising fundamentals.
  8. Acceleration structures: Extending the grid to a multi-level grid.
  9. Acceleration structures: Adding a TLAS.

In This Article…

To the basic ray tracer of the first article we will now add reflections (including recursive reflections) and glass, to turn it into a full Whitted-style ray tracer. This requires the concept of materials, so we can differentiate between regular, mirror and glass voxels. We will test the new features in a fresh test scene, the code for which you will find in the next paragraph.

Starting Point

For this article we will use the unmodified template code as a starting point. You are encouraged to combine concepts from this second article with the lights and shadows introduced in the first article, but this is not required.

Let’s first make some modifications, for the purpose of this article. Replace the world creation code in Scene::Scene in file scene.cpp, line 30:

Next, replace the Renderer::Trace function in renderer.cpp with:

The result is a basic room scene with three floating cubes, each with a different color.

– o –

Reflections

In the first article we saw that ray tracing is all about light transport between light sources and the camera. A ray through a pixel finds an object; from there, a shadow ray attempts to reach the light source. If there is no obstacle, the object seen through the pixel is illuminated by the light source. But what if the object is a mirror?

Like other surfaces, a mirror reflects light. However: Only in very specific directions. In fact, for a perfect mirror, a single incoming direction is linked to a single outgoing direction. In the right image, one of the two rays that hit the mirror ball bounces to the green sphere. The corresponding pixel will thus show a green sphere, mirrored in a dark, shiny sphere.

Note that the green sphere reflects green light because it is visible from the light source. There is thus light transport: From the light to the green sphere, then via the mirror to the pixel, and finally to the camera.

To add reflections to the voxel ray tracer, we need two things:

  1. A way to calculate the reflected direction, so we can spawn a new ray;
  2. A way to detect that an object is reflective.

Regarding that second point on the list: We will introduce the concept of materials. A mirror is fundamentally different from our basic (‘diffuse’) material. And, later we will add a third type of material, which is used for glass and water.

Let’s take another look at the world creation code. We used four ‘HTML’ colors, which are in fact simply 24-bit hexadecimal numbers: 0xEEEEEE for (almost) white, 0xFF7777 for (pastel) red, 0xAAFFAA for green and 0x7777FF for blue. A voxel actually can store 32-bit data, so there’s some headroom. Let’s agree that 0x00xxxxxxxx means that we have a diffuse material with color xxxxxx, and that 0x01xxxxxx indicates that the material is in fact reflective. So, we can make the floor reflective by changing its color to 0x019999BB:

Now, in Renderer::Trace we can easily detect the mirror material. Replace the last line, which returns the shaded albedo, with the following construct:

The bitshift operator >> shifts the contents of the 32-bit ray.voxel variable to the right by the specified number of bits. This effectively makes the top 8 bits, in which we stored the material type, the only remaining bits.

To calculate the reflected color we need a reflection ray. The origin of this ray is simply the end of the primary ray. The direction is a bit more involved. The reflection direction depends on the orientation of the surface we hit, and thus we use the local normal vector, like we did with the calculation of the shading. The formula for vector reflection is:

R=D-2N(D \cdot N)

Here, D is the direction of the incoming ray and R is the reflected direction. The reflected ray can now be constructed:

Things get interesting when we actually use this new ray. Behold the final reflection code:

We use a recursive call to Renderer::Trace to handle the reflection. This is powerful: Whatever we find at the end of the reflected ray will be handled by code we already have. This will work if we find a diffuse surface: in that case, the existing code in Trace will cast a shadow ray. It will also work if we find another mirror. In that case, we just bounce again.

With great power comes great responsibility. It is not hard to setup a scene where rays may bounce infinitely (there’s a reason I suggested to make just the floor reflective). We’ll need to somehow limit how often we bounce. For that, we can use the optional ‘depth’ argument of Renderer::Trace. By default it is called with 0. We can increase it for each recursion step:

Now it is straight-forward to cap recursion. Just add a line at the start of the Trace function:

Instead of 5 you can use larger (or smaller) numbers. Just be careful: Many bounces will bring down the performance of the ray tracer.

– o –

Refraction

The final feature for this article is glass. In the real world, glass has surprisingly complex behavior. It transmits light, but it is also reflective. To make matters worse, reflection doesn’t just happen on the outside of a glass object, but also on the inside, when we try to leave the object.

Left: The water surface is reflective when seen from below. Right: Also when seen from above.

So, in order to add refraction to the ray tracer, we need three things:

  1. A reflected ray
  2. A refracted (or: transmitted) ray, into the glass or water
  3. A way to blend the two.

The reflection is easy: This is identical to the mirror functionality we already added.

For the direction of a refracted ray we need to look at the work of an old Dutch scientist, named Willebrord Snel van Royen, better known as ‘Snellius’, or just ‘Snell’. Snell has a physics law named after him that looks like this:

\frac{sin \theta_i}{sin \theta_o} = \frac{v_1}{v_2}

Here, \theta_i (“theta i”) is the angle at which a ray arrives at a surface (relative to the normal); \theta_o is the angle at which the ray leaves the surface at the other side, and v_1 and v_2 are the speeds at which light travels on either side of the surface. Instead of v_1 and v_2 we can also use n_1 and n_2, i.e. the refraction indices of the media on either sides of the surface.

That’s great, but we are looking for a vector, not an angle. To obtain the refracted vector, we can borrow some formulas from the glsl reference manual, which states that it is calculated as follows:

And that is actually useful for our purposes. Variable ‘eta’, by the way, is calculated as n_1 / n_2. For air, n_1 is simply 1.0. For glass, n_2 is approximately 1.46. So, when going from air to glass, eta is 1/1.46. But, in the opposite direction eta is 1.46/1. This is relevant when we leave a block of glass on the other side.

Refractive indices of more materials can be found here.

The final ingredient is the blending of energy returned by the reflected and refracted rays. Another scientist studied this topic: His name is Fresnel. His ‘Fresnel Equations’ are intimidating, but luckily, someone (mr. Schlick) made a simpler approximation, which is gets pretty close:

f=R_0+(1-R_0)(1-(D \cdot N))^5, where R_0=(\frac{n_1-n_2}{n_1+n_2})^2

We can now put everything together in the ray tracer. Let’s label the new ‘glass’ material ‘02‘ in the scene, to differentiate it from the regular material ‘00‘ and the mirror material ‘01‘. To make the green cube a glass cube we change its color to 0x02AAFFAA. We then detect the new material in Renderer::Trace:

We start the new material code with specifying n_1 and n_2. And note: If we hit the plane that separates air and glass from within the glass, we need to swap n_1 and n_2. In the template, we can just ‘ask’ the ray if this is the case.

Next, we prepare for calculating the refracted ray direction. Efficiently calculating k requires some care. The dot product between N and -ray.D is used a few times and should thus be precalculated. Also note that, instead of the generic ‘std::powf’ function (which is very costly), we use a simple function from the template to calculate the square of the dot product.

Now we can trace the refracted ray, if k is greater than 0.

As discussed, glass also is reflective. This uses the same logic we have seen before.

And finally, we blend reflection and refraction using Fresnel. Something special happens when refraction is not possible: We get total internal reflection. In that case, the reflected ray gets a 1.0 weight. We can detect this situation by looking at variable k, which should be greater than 0.

And there it is… A pretty complex block, with light going in, changing direction, getting reflected on the inside, and so on. At each surface interaction the path splits off a reflected and refracted ray, so be gentle with that recursion depth!

– o –

Whitted

We now have a full implementation of the famous paper by Turner Whitted, which he wrote in 1980: “An Improved Illumination Model for Shaded Display”. You can find a copy of the paper here. The groundbreaking idea of the paper is that we can ‘do graphics’ by applying principles from the field of optics, including shadows, reflection and refraction. The technique is ever since known as Whitted-style ray tracing. Now you know!

– o –

Challenges

Challenge 1: Combine the concepts of this article with those from the first article. In short, add point lights and shadows, and make them work together with the recursive reflections and refractions.

Challenge 2: The way we blended between refraction and reflection can also be applied to materials that are partially diffuse and partially reflective. Create a material for which a shadow ray and a reflection ray is cast, and blend the two layers using a weight of 50% for each.

Challenge 3: The template comes with ImGui integration. Use this to make the refraction index of the glass configurable at run-time. Find a way to change properties of other materials via the interface as well.

Etc.

If you want to share some of your work, consider posting on X about it. You can also follow me there (@j_bikker), or contact me at bikker.j@gmail.com.

Want to read more about computer graphics? Also on this blog:

Other articles in the “Ray Tracing with Voxels in C++” series:

  1. Starting point: Voxel ray tracing template code. Lights and shadows.
  2. Whitted-style: Reflections, recursion, glass (this article).
  3. Stochastic techniques: Anti-aliasing and soft shadows.
  4. Noise reduction: Stratification, blue noise.
  5. Converging under movement: Reprojection.
  6. Path tracing: Basics first; then: Importance Sampling.
  7. Denoising fundamentals.
  8. Acceleration structures: Extending the grid to a multi-level grid.
  9. Acceleration structures: Adding a TLAS.
Author: jbikker

7 thoughts on “Ray Tracing with Voxels in C++ Series – Part 2”

  1. A slight grammar mistake at the third block of text in the Reflections paragraph: “Note that the green sphere is green is reflects green light because it is visible from the light source.”

  2. Hi Jacco!

    After double-checking with my friends and the wikipedia page on Snell’s law, I think there is a minor mistake in the refracted ray direction calculation. I believe a plus and minus sign are swapped. This caused my refractions not to work properly (at least not on a ray going from inside to outside a dielectric object).

    The formula:
    float3 R = eta * ray.D – (eta * d + sqrtf( k )) * N;
    I believe should be:
    float3 R = eta * ray.D + (eta * d – sqrtf( k )) * N;

  3. After the change in the article, I think the last image showing how the glass works is a little deceiving since it shows how the old formula works, instead of for example what I see with the correct one. Please check this out 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.