Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 50 ยท Ray Tracing and Rasterization Pipeline

Shadows, Reflections and Refraction

Add shadow rays, recursive mirror reflection and glass refraction with Snell's law and the Fresnel effect to your ray tracer, with a live recursive renderer.

The tracer from the previous lesson finds the nearest surface for each camera ray and shades it with a local lighting formula. That already looks like 3D, but it cannot tell whether a lamp is blocked by another object, it cannot show a mirror, and it cannot bend light through glass. All three need one new move: start more rays from the hit point.

Ray tracing handles them in a uniform way. A shadow ray asks "can this point see the light?". A reflection ray asks "what does the mirror show here?". A refraction ray asks "what is seen through the glass?". Because each of these questions is answered by calling the same trace function again, the algorithm is recursive, and a few lines of extra code give you effects that rasterizers have to fake.

Shadow rays

When a primary ray hits a surface at point P, shoot a new ray from P toward the light. If it hits any object before reaching the light, then P is in shadow, and the light contributes neither diffuse nor specular color there (only ambient light remains).

TEXT
shadowOrigin = P + N * epsilon          // nudge off the surface
toLight      = normalize(lightPos - P)
distance     = length(lightPos - P)
inShadow     = any object hit with 0 < t < distance

Two details matter. First, the epsilon offset prevents the shadow ray from immediately re-hitting the surface it starts on (the self-intersection problem from the last lesson, usually called shadow acne when it shows up as dark speckles). Second, you compare t against the distance to the light: an object behind the light should not cast a shadow on points in front of it. For a directional light, the distance is infinite, so any hit counts.

A shadow ray does not need the nearest hit, only the existence of one, so renderers stop at the first hit they find. This makes shadow tests cheaper than full traces.

Reflection

A perfect mirror sends the ray bouncing off the surface in a predictable direction. For an incoming direction D and a unit normal N:

TEXT
R = D - 2 (D . N) N

Trace a new ray from P along R, and mix the color it returns into the surface color:

TEXT
color = (1 - k) * localColor + k * trace(P, R, depth + 1)

The reflectivity k runs from 0 (matte) to 1 (perfect mirror). A polished floor might use 0.2, chrome 0.9. The recursion needs a stopping rule or two facing mirrors would bounce forever. The standard limit is a maximum depth of a handful of bounces (the demo below uses up to 5), plus a stop when a ray escapes into the sky.

flowchart TD
  A["trace(ray, depth)"] --> B{"Hit anything?"}
  B -->|no| C["Return sky color"]
  B -->|yes| D["Local color:<br/>ambient + diffuse + specular<br/>(shadow ray decides light)"]
  D --> E{"depth less than max?"}
  E -->|no| F["Return local color"]
  E -->|yes| G["Reflection ray: trace(R, depth + 1)"]
  E -->|yes| H["Refraction ray: trace(T, depth + 1)"]
  G --> I["Blend colors"]
  H --> I
  I --> J["Return final color"]

Reflection and refraction call the tracer again; the depth counter ends the recursion.

Refraction and Snell's law

Light slows down in glass, water and other transparent materials. The ratio of its speed in vacuum to its speed in a material is the index of refraction (IOR): about 1.0 for air, 1.33 for water, 1.5 for common glass, 2.4 for diamond. When light crosses the boundary between two materials, it bends according to Snell's law:

TEXT
n1 * sin(theta1) = n2 * sin(theta2)

theta1 is the angle between the incoming ray and the surface normal, theta2 the angle of the bent ray, again from the normal. Going into a denser material (n2 > n1) the ray bends toward the normal; coming out it bends away.

Going out of glass into air there is a limit. If sin(theta2) would have to be larger than 1, no refracted ray exists and all the light reflects back inside. This is total internal reflection, and it is why a diamond sparkles and why fiber optic cables work. The steepest angle that still escapes is the critical angle: asin(n2 / n1), about 41.8 degrees for glass to air.

In vector form, with eta = n1 / n2, a unit incoming direction D and a unit normal N that faces against the ray (cosI = -D . N is positive):

TEXT
k = 1 - eta^2 * (1 - cosI^2)
if k < 0:  total internal reflection, no refracted ray
else:      T = eta * D + (eta * cosI - sqrt(k)) * N

The code can tell whether a ray is entering or leaving a solid by the sign of D . N with the geometric outward normal: if it is positive, the ray is inside, so flip N and swap the two indices. The first demo tabulates Snell's law and the Schlick approximation, which we meet next.

JS Snell's law, critical angle and Schlick reflectance

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice how the reflected share at normal incidence is only 4% for glass, yet it reaches 41% at 80 degrees and approaches 100% at truly grazing angles. That brings us to Fresnel.

The Fresnel effect

Look straight down into a clear pond and you see the bottom; look across it at a shallow angle and you see the sky mirrored. The share of light that reflects rather than refracts depends on the angle, and this is the Fresnel effect. The exact equations involve polarization, but ray tracers nearly always use Schlick's approximation:

TEXT
R0 = ((n1 - n2) / (n1 + n2))^2
R  = R0 + (1 - R0) * (1 - cosTheta)^5

R0 is the reflectance when looking straight on, and R is the reflected fraction at the given angle. For a glass object, the color becomes R * reflectionColor + (1 - R) * refractionColor. This is the reason glass spheres in good renders show a bright mirror-like rim and a see-through middle.

Putting it all together

The demo traces a scene with a mirror sphere (left), a glass sphere (front) and a red matte sphere (right) on a checker floor that is slightly reflective. Everything described above runs per pixel: Blinn-Phong lighting from a point light, shadow rays, recursive reflection and Fresnel-weighted refraction. Try the toggles:

  • Turn Shadows off and the spheres float; turn it on and they sit on the floor.
  • Reduce Max bounces to 0, 1, 2 and watch the mirror first lose its reflections, then show an incomplete world inside the glass.
  • With Refraction off, the glass sphere becomes just another mirror ball.

The image is small (240 by 160) so it computes in a moment; each change re-traces everything.

A recursive ray tracer

A real glass sphere acts like a strong lens, so the checker floor and the other spheres appear upside down inside it. That inversion falls out of the math with no special code: it is just two refractions, one on entering and one on leaving.

Costs and limits

Every extra effect multiplies the work. With s shadow rays per hit and two children (reflection and refraction) per glass hit, the number of rays can grow exponentially with depth. Production renderers keep this under control with depth limits, Russian roulette (randomly stopping low-contribution paths), and a stop when the remaining contribution is too small to matter.

Also note what this classic Whitted-style ray tracer cannot do: soft shadows, glossy reflections, color bleeding from one diffuse wall to the next, and caustics. Those need many random rays per pixel (path tracing), but the building blocks are exactly the ones you just used. Compare the whole approach with the GPU's method in the rasterization pipeline.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is a shadow ray?

    If the shadow ray hits any object before reaching the light, the point is in shadow and gets no direct light.
  2. 2. Why are shadow and reflection rays started slightly off the surface (P + N * epsilon)?

    Without an offset, the new ray often hits its own surface at t close to 0, which produces dark speckles known as shadow acne.
  3. 3. What does the maximum depth control in a recursive ray tracer?

    Each reflection or refraction calls trace again with depth + 1. The limit prevents infinite recursion between mirrors.
  4. 4. A ray travels inside glass (n = 1.5) toward air at a steep angle where sin(theta2) would exceed 1. What happens?

    Snell's law has no solution beyond the critical angle (about 41.8 degrees for glass to air), so the light is entirely reflected.
  5. 5. What does the Fresnel effect say about a glass surface?

    At normal incidence glass reflects only about 4%, but the reflected share rises steeply toward 100% as the viewing angle becomes shallow.

Summary

  • Shadows, reflections and refraction all come from tracing more rays starting at the hit point.
  • A shadow ray points at the light; any hit closer than the light means the point is shadowed. Offset ray origins by a small epsilon along the normal.
  • The mirror direction is R = D - 2 (D . N) N, blended by a reflectivity k; a maximum depth ends the recursion.
  • Snell's law n1 sin(theta1) = n2 sin(theta2) bends rays at material boundaries; beyond the critical angle only total internal reflection remains.
  • The Fresnel effect, approximated by Schlick's formula, mixes reflection and refraction by viewing angle.
  • Whitted-style tracing is exponential in the worst case and cannot do soft shadows or color bleeding; path tracing extends it with random sampling.

Next, see how GPUs draw images without tracing rays in The Rasterization Pipeline.