Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 50 ยท Projects, Practice and Review

Project: A Ray-Traced Scene

Build a complete ray tracer in JavaScript: spheres, a checkered floor, a point light, hard shadows, recursive reflections and antialiasing, rendered live.

Rasterization asks "which pixels does this triangle cover?" Ray tracing asks the opposite question: "what does the light travelling to this pixel come from?" For each pixel you shoot a ray from the camera, find what it hits, and ask that surface how bright it is. Shadows and mirrors fall out almost for free, because they are just more rays.

This project assembles the whole ray tracer in one page of JavaScript: spheres and a floor, a point light with diffuse and specular shading, hard shadows, recursive reflections and 2 by 2 antialiasing. It uses the ideas from Ray Tracing: Rays, Spheres and Planes and Shadows, Reflections and Refraction; if a formula looks unfamiliar, start there.

The structure of the tracer

The whole program is one recursive function, trace(origin, direction, depth), that returns a color. Everything else supports it.

flowchart TD
  A["Camera ray through a pixel"] --> B["Find the nearest hit<br/>spheres and floor"]
  B -->|no hit| S["Sky gradient"]
  B -->|hit| C["Surface color<br/>(checkers for the floor)"]
  C --> D["Shadow ray to the light<br/>blocked?"]
  D --> E["Ambient + diffuse + specular<br/>(only if not in shadow)"]
  E --> F{"Reflective and<br/>depth left?"}
  F -->|yes| G["trace(reflected ray, depth + 1)"]
  G --> H["Mix local color and reflection"]
  F -->|no| H
  S --> I["Pixel color"]
  H --> I

One function, called recursively: reflection rays go through exactly the same code as camera rays.

Rays and intersections

A ray is P(t) = O + t D with a unit direction D. For a sphere with centre C and radius r, substituting the ray into |P - C|^2 = r^2 gives a quadratic in t. With b = (O - C) . D and c = |O - C|^2 - r^2, the discriminant is b^2 - c. If it is negative the ray misses; otherwise the nearer hit is t = -b - sqrt(b^2 - c). If that value is not positive (the origin is inside the sphere or the hit is behind), try the other root. For the floor plane y = -1 the solution is simply t = (-1 - O.y) / D.y.

We always look for the nearest positive t among all objects, and we ignore hits closer than a tiny epsilon (here 0.0001). That epsilon is the classic fix for shadow acne: a ray starting on a surface would otherwise "hit" that same surface at t = 0.0000001 because of rounding and shadow itself with speckles.

Shading

At a hit point P with unit normal N, unit vector L toward the light and unit vector V toward the viewer, the local color is the Phong/Blinn model from Light and Reflection Models:

TEXT
color = base * (ambient + diffuse * max(N . L, 0)) + specular * max(N . H, 0)^shininess

where H is the unit half-vector between L and V. For a sphere N = (P - C) / r; for the floor N = (0, 1, 0). The floor's base alternates between two colors depending on the parity of floor(x) + floor(z), which gives the checkerboard and a very good sense of perspective.

Shadows

Before adding the diffuse and specular parts, cast a shadow ray from P (nudged along N by epsilon) toward the light. If any object is hit at a distance shorter than the distance to the light, the point is in shadow and gets only the ambient term. One extra ray per hit gives crisp, physically plausible shadows.

Reflections

A mirror-like surface adds the color of what it reflects. The reflected direction is R = D - 2 (D . N) N. We call trace again with R and depth + 1, and blend: final = local * (1 - k) + reflected * k, where k is the reflectivity of the object. The recursion is limited by a maximum depth (3 here); without a limit, two facing mirrors would recurse forever.

Antialiasing

A single ray through the centre of each pixel produces jagged edges, as in Aliasing and Antialiasing. Supersampling fires several rays per pixel at different positions inside it and averages them. Here we use a regular 2 by 2 pattern, which costs 4 times the rays and removes most of the stair-stepping. Finally, we apply a simple gamma curve (sqrt) before writing the pixel, because our lighting math happens in linear light (see HSV, HSL, Gamma and Perceptual Color).

The renderer

Press Render after toggling shadows, reflections and antialiasing. The ray count shows what each feature costs. Notice that without shadows the spheres seem to float, and without reflections the blue and green spheres look like painted plastic.

A ray-traced scene

Following one ray by hand

The renderer hides the story of a single pixel. The second example uses the same math and prints it: the camera ray, the nearest hit, the shadow test and the reflection. It also draws an ASCII map of the scene: O is a sphere, . is lit floor, : is floor in shadow, and a space is sky.

JS One ray, step by step, and a shadow map

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

No output.

The shadow patches point away from the light, which sits up and to the left, so the shadows fall to the right of the spheres. Move LIGHT in the code and watch them swing around.

Making it better

  • Soft shadows. Replace the point light with a small sphere and cast several shadow rays to random points on it. The fraction that is blocked gives the penumbra.
  • Refraction. Add a transparent sphere using Snell's law from Shadows, Reflections and Refraction.
  • Triangles. Add a ray-triangle test (the Moller-Trumbore algorithm) and render the meshes from the 3D chapters.
  • Speed. Skip the shadow ray when N . L <= 0, test bounding spheres first, and move the render into a Web Worker so the page never freezes. Ray tracing costs time proportional to pixels, samples and recursion depth, which is why real-time engines mostly rasterize.
  • Random sampling. Replace the regular 2 by 2 pattern with random jitter and more samples to turn aliasing into soft noise.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why do we ignore intersections with t smaller than a small epsilon?

    Floating-point rounding can put a hit point slightly inside its own surface. The epsilon (and offsetting the origin along the normal) prevents self-intersection.
  2. 2. How is the reflected ray direction computed from the incoming direction D and the unit normal N?

    Subtracting twice the component of D along the normal mirrors the vector about the surface.
  3. 3. What does a shadow ray test?

    If something is hit closer than the light, the light cannot reach the point, so only ambient light is applied.
  4. 4. Why does the recursion have a maximum depth?

    Each bounce adds less light, so after a few bounces the contribution is negligible. A depth limit guarantees that the trace terminates.
  5. 5. How many camera rays per pixel does 2 by 2 supersampling use, and why?

    Four rays at different positions inside the pixel are averaged, so an edge that covers half of the pixel gives about half of the color, instead of all or nothing.

Summary

  • A ray tracer is one recursive trace function: find the nearest hit, shade it, optionally recurse for reflections.
  • Ray-sphere intersection solves a quadratic; the floor plane is a one-line formula.
  • Shadow rays test whether the path to the light is blocked; an epsilon avoids self-shadowing.
  • Reflections reuse trace with the mirrored direction and a depth limit.
  • Supersampling trades more rays for smooth edges, and gamma correction makes the result look right on screen.

The last project returns to the complex plane: Project: A Fractal Explorer.