Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 50 ยท Projects, Practice and Review

Project: A Software 3D Engine

Build a tiny 3D engine without a GPU: mesh, rotation, perspective projection, z-buffer and Lambert shading, drawn pixel by pixel in plain JavaScript.

In the last chapter a GPU did the heavy lifting. In this project you take its job yourself. You will write a complete 3D renderer in about 100 lines of JavaScript: no WebGL, no libraries, just an array of pixels. It builds a mesh, rotates it, projects it with perspective, removes hidden surfaces with a z-buffer, and shades every triangle with the Lambert model.

Nothing here is new. Every stage comes from an earlier lesson, and the point of the project is to see them work together. If a stage feels shaky, the lesson to revisit is linked where the stage appears.

The pipeline you are building

A software engine is the same pipeline that a GPU runs, written out as loops. Each frame, for every triangle of the mesh:

flowchart LR
  A["Mesh<br/>vertices + triangles"] --> B["Transform<br/>rotate, move in front of camera"]
  B --> C["Light<br/>normal and Lambert term"]
  C --> D["Project<br/>perspective divide, to pixels"]
  D --> E["Rasterize<br/>barycentric test per pixel"]
  E --> F["Depth test<br/>nearest wins"]
  F --> G["Frame buffer<br/>putImageData"]

Each triangle flows through the same stages; the frame buffer is cleared once per frame.

We keep the data structures small. A mesh is an object with vertices (an array of [x, y, z]) and triangles (an array of three vertex indices), exactly like the indexed meshes in Polygon Meshes and Wireframe Rendering.

Stage 1: generating meshes

Typing vertices by hand does not scale, so we generate surfaces from a function f(u, v) that maps two parameters in the range 0 to 1 to a 3D point. A sphere, a torus and a cube are all grids of points, and we connect neighbouring points into two triangles per cell. For the sphere u goes around the equator and v from pole to pole; for the torus both parameters wrap around.

Stage 2: transform

We rotate every vertex about the y axis and then the x axis (the matrices from 3D Rotation, written out as plain formulas) and push the model away from the camera. The camera sits at the origin looking down the negative z axis, so after the push every visible vertex has a negative z.

Stage 3: lighting

For each triangle we compute the face normal with a cross product of two edges and normalize it. The Lambert term is the dot product of the normal with the direction to the light, clamped at zero, as in Light and Reflection Models:

TEXT
brightness = ambient + (1 - ambient) * max(0, n . l)

One subtle point: a generated mesh may have triangles wound the "wrong" way, which flips their normals. Our engine avoids the whole problem by turning each normal toward the camera before lighting. For closed solids that is correct, and the z-buffer hides the back faces anyway.

Stage 4: projection

A view-space point (x, y, z) with z < 0 lands on the screen at

TEXT
sx = W/2 + s * x / (-z)
sy = H/2 - s * y / (-z)

where s depends on the field of view (s = H/2 / tan(fov/2)). This is the perspective divide from Orthographic and Perspective Projection, with the y axis flipped because screen coordinates grow downward.

Stage 5: rasterization and the depth test

For each triangle we loop over its bounding box, compute barycentric weights for every pixel centre (see Triangle Rasterization) and skip pixels outside the triangle. For the depth test we store 1/(-z) per pixel. That quantity is linear in screen space, so interpolating it with the barycentric weights is exact, and a larger value means nearer. This is the z-buffer in its simplest form.

The engine

Choose a shape, turn the z-buffer off to see what happens without it (triangles then paint in index order, and the torus turns inside out), and drag the slider to change the field of view.

A complete software 3D engine

Watch the counter: with the z-buffer on, the torus writes more pixels than it shows, because far triangles are drawn first and overwritten (that is overdraw). Try the cube with the z-buffer off. Because the faces are drawn in index order, a back face is sometimes painted over a front face, and the cube looks wrong at certain angles.

Reading the result as text

The same algorithm works with letters instead of pixels. The second example renders a sphere into a grid of characters. The grid is the frame buffer, the character is chosen by the Lambert brightness, and we ask the sphere for the depth at each cell directly. It is a good way to check the math without any graphics output.

JS The pipeline as ASCII art

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

No output.

The small sphere was drawn first, yet it appears in front of the big one, because its cells have a larger z. Swap the order of the two entries in spheres and the picture does not change. That is the whole promise of the z-buffer.

Ideas for extending the engine

Each of these is a good afternoon of work, and each uses a lesson you already have:

  • Back-face culling. Fix the winding of your generated triangles, then skip triangles whose screen-space area is negative. You halve the rasterization work. See Back-Face Culling and the Painter's Algorithm.
  • Gouraud or Phong shading. Store a normal per vertex (for the sphere and torus it is a simple formula) and interpolate it with the barycentric weights. See Flat, Gouraud and Phong Shading.
  • Near-plane clipping. Right now a vertex behind the camera would break the divide. Clip triangles against z = -near first, as in Polygon Clipping.
  • A camera. Replace the fixed camera with the look-at matrix from The Camera and View Transformation and let the mouse orbit it.
  • Speed. Replace the bounding-box loop with incremental edge functions so each pixel costs two additions instead of several multiplications.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the engine store 1/(-z) in the depth buffer instead of z itself?

    Perspective divides by depth, so z is not linear in screen space but its reciprocal is. Interpolating 1/(-z) with screen-space barycentric weights gives the correct value at every pixel.
  2. 2. What does the engine do about triangles that are wound the wrong way?

    Flipping the normal toward the viewer makes the lighting independent of winding. The z-buffer still hides the real back faces.
  3. 3. With the z-buffer disabled, what decides which triangle is visible at a pixel?

    Without a depth test every covered pixel is simply overwritten, so the draw order wins, which is wrong for any shape that has surfaces behind other surfaces.
  4. 4. Which stage turns view-space coordinates into pixel positions?

    The perspective divide scales x and y by 1/(-z), and the viewport mapping moves the result to pixel coordinates with y flipped.

Summary

  • A software 3D engine is the GPU pipeline written as loops: mesh, transform, light, project, rasterize, depth test.
  • Meshes are generated from parametric functions and stored as vertex and triangle-index arrays.
  • Lambert shading uses the face normal and a light direction; flipping normals toward the camera removes winding worries.
  • Perspective divides x and y by the distance; 1/(-z) is the value that interpolates linearly across a screen-space triangle.
  • The z-buffer makes draw order irrelevant for opaque surfaces, at the cost of overdraw.

Next you build something interactive from the 2D chapters: Project: A Mini Paint Program.