9. Ray Tracing Basics
Casting rays, intersecting spheres, and producing shadows and reflections from first principles
Rasterization asks "which pixels does this triangle cover?" Ray tracing flips the question: "what does this pixel see?" For each pixel, we cast a ray into the scene and find what it hits. This simple reversal makes shadows, reflections, and refractions almost trivial to implement.
The Core Idea
Imagine standing behind a window grid — one cell per pixel. For each cell, you look through it and note what you see. That's ray tracing.
for each pixel (x, y):
ray = camera through pixel (x, y)
color = trace(ray, scene)
image[x][y] = color
The trace function finds the closest intersection with any object in the scene, then computes the color at that point using lighting, and optionally spawns more rays for reflections and shadows.
Generating Camera Rays
We need to convert each pixel coordinate into a 3D ray. The ray has an origin (the camera position) and a direction (from the camera through the pixel on the image plane).
Given an image of width w and height h, field of view fov, and camera at the origin looking down -z:
aspect = w / h
scale = tan(fov / 2)
// For pixel (px, py):
ndc_x = (px + 0.5) / w // [0, 1]
ndc_y = (py + 0.5) / h // [0, 1]
screen_x = (2 * ndc_x - 1) * aspect * scale
screen_y = (1 - 2 * ndc_y) * scale
direction = normalize(screen_x, screen_y, -1)
The +0.5 centers the ray in the pixel. The Y axis is flipped because screen coordinates go top-to-bottom but world coordinates go bottom-to-top.
Ray-Sphere Intersection
The sphere is the "hello world" of ray tracing because it has a clean, closed-form intersection test.
A ray is defined as:
P(t) = O + t * D
Where O is the origin, D is the direction, and t >= 0 is the distance along the ray.
A sphere centered at C with radius r satisfies:
|P - C|² = r²
Substituting the ray equation:
|O + t*D - C|² = r²
Let L = O - C. Expanding:
(D · D)t² + 2(D · L)t + (L · L - r²) = 0
This is a quadratic in t. The discriminant tells us everything:
discriminant < 0— ray misses the spherediscriminant = 0— ray grazes the sphere (one intersection)discriminant > 0— ray passes through (two intersections — take the smaller positivet)
discriminant = b² - 4ac
t = (-b - sqrt(discriminant)) / 2a
The Quadratic Formula Does All the Work
Ray-sphere intersection reduces to solving a quadratic equation. The discriminant tells you hit/miss, and the roots give you the intersection distances.
The normal at the hit point is simply:
n = normalize(P_hit - C)
Ray-Plane Intersection
A plane defined by a point P0 and normal n:
t = (P0 - O) · n / (D · n)
If the denominator is near zero, the ray is parallel to the plane. This is useful for ground planes and for building ray-triangle intersection.
Ray-Triangle Intersection
Triangles are the building blocks of 3D models. The Moller-Trumbore algorithm intersects a ray with a triangle efficiently using barycentric coordinates:
edge1 = v1 - v0
edge2 = v2 - v0
h = cross(D, edge2)
a = dot(edge1, h)
if |a| < epsilon: return miss // ray parallel to triangle
f = 1 / a
s = O - v0
u = f * dot(s, h)
if u < 0 or u > 1: return miss
q = cross(s, edge1)
v = f * dot(D, q)
if v < 0 or u + v > 1: return miss
t = f * dot(edge2, q)
if t > epsilon: return hit at t with barycentric (1-u-v, u, v)
return miss
This computes the intersection point and barycentric coordinates in one pass, with early exits at each step.
Shading the Hit Point
Once we find the closest intersection, we compute the color using the same Phong/Blinn-Phong model from the lighting article. We have the hit point, the normal, the light position, and the view direction — everything we need.
hit_point = ray.origin + t * ray.direction
normal = sphere_normal(hit_point)
color = ambient + diffuse(normal, light_dir) + specular(normal, light_dir, view_dir)
Shadows
Here's where ray tracing really shines. To determine if a point is in shadow, cast a shadow ray from the hit point toward the light:
shadow_origin = hit_point + epsilon * normal // offset to avoid self-intersection
shadow_dir = normalize(light_pos - shadow_origin)
shadow_ray = Ray(shadow_origin, shadow_dir)
if intersects_anything(shadow_ray, scene):
// point is in shadow — use only ambient
else:
// point is lit — compute full Phong shading
The epsilon offset along the normal prevents the ray from immediately hitting the same surface it originated from — a common bug called shadow acne.
Reflections
Reflective surfaces are equally simple — compute the reflection direction and trace another ray:
r = d - 2(d · n)n
reflect_dir = reflect(ray.direction, normal)
reflect_ray = Ray(hit_point + epsilon * normal, reflect_dir)
reflect_color = trace(reflect_ray, scene, depth + 1)
color = (1 - reflectivity) * local_color + reflectivity * reflect_color
This is recursive — a reflected ray can hit another reflective surface, spawning another reflection ray. We limit recursion depth to prevent infinite bouncing.
The Complete Ray Tracer
Putting it all together:
function trace(ray, scene, depth):
if depth > MAX_DEPTH: return background_color
hit = find_closest_intersection(ray, scene)
if no hit: return background_color
color = ambient_term
for each light:
shadow_ray = ray toward light from hit.point
if not blocked(shadow_ray, scene):
color += diffuse(hit.normal, light_dir)
color += specular(hit.normal, light_dir, view_dir)
if hit.material.reflective:
reflect_ray = reflect ray off hit.normal
color += hit.material.reflectivity * trace(reflect_ray, scene, depth + 1)
return color
That's a complete ray tracer in ~15 lines of pseudocode. With just spheres and planes, you can render scenes with shadows, reflections, and proper perspective.
Performance
Ray tracing is expensive — for a 1920x1080 image, you cast over 2 million primary rays, each of which might spawn shadow and reflection rays. Each ray tests against every object in the scene.
Acceleration structures reduce the work dramatically:
- Bounding Volume Hierarchies (BVH) — organize objects in a tree of bounding boxes. A ray tests the box first; if it misses, it skips all objects inside. This turns O(n) intersection tests into O(log n).
- Spatial grids / octrees — divide space into cells and only test objects in cells the ray passes through.
Modern GPUs (RTX, RDNA2+) have dedicated hardware for BVH traversal and ray-triangle intersection, making real-time ray tracing practical.
Ray Tracing vs. Rasterization
| Rasterization | Ray Tracing | |
|---|---|---|
| Approach | For each triangle, find covered pixels | For each pixel, find visible geometry |
| Shadows | Shadow maps (approximate) | Shadow rays (exact) |
| Reflections | Environment maps (approximate) | Recursive rays (exact) |
| Speed | Very fast on GPUs | Slower, but hardware is catching up |
| Global illumination | Requires hacks (SSAO, light probes) | Path tracing handles it naturally |
In practice, modern engines use a hybrid approach — rasterize the primary visibility, then use ray tracing for shadows, reflections, and global illumination where it matters most.
What's Next
This article covered the basics — primary rays, shadows, and mirror reflections. The next step is path tracing: instead of tracing perfect reflections, trace rays in random directions weighted by a material's BRDF. Thousands of random bounces per pixel converge to a physically accurate image. That's how offline renderers like Pixar's RenderMan produce photorealistic frames — but that's a topic for another article.