Free to Learn

Build a tiny GPU

Which pixels does a triangle cover?

A free course: over nine units you write a small GPU in JavaScript for Node. Try two of its ideas below, or start the course.

A GPU draws a picture as triangles. For each pixel it tests the pixel's centre against the triangle's three edges, and it colours the pixels whose centres fall inside. Every grid on this page is drawn by that test, the same JavaScript the course's learners write in lesson 1.

1. Two triangles, one edge

A square of 8 by 8 pixels is cut along its diagonal into two triangles, blue below and orange above. The diagonal runs exactly through the centres of 8 pixels. For each edge the test gives a number, w, positive on the triangle's side and 0 on the edge itself. For those 8 centres w is 0, so the test can't say which side they are on.

Say the inside test is "on an edge counts as inside". Who draws the 8 pixels on the diagonal?

2. Drag a corner, count the warps

The course's GPU works out pixel colours, or shades them, a 4 by 2 block at a time. Each block is one warp of 8 lanes, one lane per pixel, all running the same instructions. Real GPUs use wider warps, 32 or 64 lanes. A lane whose pixel the triangle misses does no work, but the warp still carries it. The faint lines mark the blocks.

The big triangle keeps most of its lanes busy. A thin sliver, one pixel wide, crosses the grid. How busy will its lanes be?

What you build

Over nine units you write a GPU in JavaScript for Node. It takes a scene of triangles and makes a picture: it moves the corners into place on the screen, decides exactly which pixels each triangle covers, blends colours across it, keeps the nearest surface in front, and runs shaders, small programs that decide each pixel's colour, eight pixels at a time. Then you count the memory it reads and writes and the instructions it issues, and make those numbers smaller.

From unit 4 on, a local page draws the same scenes with your browser's GPU through WebGL, the browser's interface to it, and shows where your picture differs. The last unit, the capstone, is a scene no lesson shows, under a budget for shading and for memory.

Early edition. AI agents have taken the course from start to finish; no human learner has yet.

Start the course

You need Node.js 22 or newer and to write JavaScript comfortably: functions, loops and typed arrays. No graphics background is needed. On a computer, clone the public repository, make your own project folder and open lesson 1 in your terminal:

git clone https://github.com/itsHabib/free-to-learn.git
cd free-to-learn
git switch --detach ec2d659ea97b56bcb4e003eaf36b4e99e5c3ca89
cd courses/tiny-gpu
node lab.mjs start project
node lab.mjs lesson 1

Open the project on GitHub · Read lesson 1