← Back to the roomHow the room works

How the room works

The room is a single web page. There are no 3D model files behind it and no game engine. Every object is built from numbers when the page loads, lit and drawn about sixty times a second, and the sounds are worked out as you play them. This page explains how.

03D model files. Every shape is made in code.
1,585separate meshes in the scene
734,000triangles drawn each frame, shadows included
4,400lines of JavaScript in 12 files, with no build step

1three.js in one picture

A browser can draw 3D through WebGL, which talks to the graphics chip directly and deals only in triangles. three.js is a JavaScript library that sits on top of WebGL and lets a program talk about things instead: a scene, a camera, lights, and objects with a shape and a surface. The room uses version r170, loaded straight from a public server by an import map in the page, so there is nothing to install or compile.

Three ideas carry most of it. A mesh is a shape (its geometry, a list of triangles) plus a surface (its material: colour, roughness, how metallic it is). A group holds meshes and other groups, so the whole scene is one tree; move a group and everything inside it moves too. And a frame loop runs before every screen refresh: it moves whatever needs moving, then draws the scene from the camera's position.

SceneLightsSky domeRoom20 objectsGuitar riga groupTelecaster3 pedalsAmpone string = a Mesh = Geometry (its shape) + Material (its surface)Everything hangsoff one tree. Move agroup and all of itsparts move with it.1 Run the updatersspin, sway, play, decay2 Ease the cameraa little nearer its goal3 Draw the framescene, bloom, tone mapevery frame, about 60 times a second
The scene is a tree. A guitar string is a mesh inside the Telecaster group, inside the guitar rig group, inside the scene. On the right, the three things the page does for every frame.

The whole of the set-up and the loop is short:

const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
const scene    = new THREE.Scene();
const camera   = new THREE.PerspectiveCamera(42, 1, 0.1, 1500);

renderer.setAnimationLoop(() => {
	const dt = clock.getDelta();                       // seconds since the last frame
	for (const f of ctx.updaters) f(ctx.time, dt);     // everything that moves
	updateCamera(dt);
	composer.render();                                 // draw, bloom, tone map
});

ctx.updaters is a plain list of functions. Anything that moves adds one: the record turning, the bike chain, a vibrating string, the fading of the lights. Each is given the time since the last frame, dt, so that it moves at the same speed on a fast screen as on a slow one.

2A room measured in metres

One unit in the scene is one metre. The floor is at height zero, x runs from −4.5 to 4.5 and z from −3.5 to 3.5, so the room is nine metres by seven. Two walls are solid: brick on the left and concrete at the back, with a window 4.6 metres wide. The other two sides are left open, and the camera looks in through the open corner.

Working in real units is what lets things sit together believably. The Jupiter-X is 1,090 mm wide because the real one is. The Telecaster's strings are 648 mm long from bridge to nut. The bike has 26 mm tyres on 38 mm rims with 24 spokes each. Small things are laid out in millimetres inside a group that is then scaled by 0.001, which keeps the numbers in the code the same as the numbers on a ruler.

rugwindow, 4.6 m wide, onto the skybrick wall x = −4.5concrete wall z = −3.5xzfloor centre (0, 0, 0); y is up1 square = 1 metrecameraBloomberg TerminalWorld clocksiPhone appsTeapotCommodore 64Hello signFundraising gaugeBikeAlps photosCharitiesMedal cupboardBassSynthsEclipse printRecord deckTelecaster rigCameraOrreryBookSpaceship Unity
The room from above, with each of the twenty objects at its real position in the scene. Blue outlines are the desk, the keyboard stand, the bench and the coffee table.

Each object tells the page three things when it is added: where the camera should look, where it should stand, and what a click should do. That one call is all that ties an object to its story.

ctx.add('guitar', rig, {
	look:   v(0.02, 0.38, -3.15),     // the point the camera looks at
	from:   v(-1.0, 1.4, -1.55),      // where the camera stands
	action: tele.strum                // what a click on it does
});

3Shapes from numbers

There is no modelling program behind any of this. Each object is a function that assembles simple shapes, and nearly everything comes from six of them.

Boxamp, pedalsCylinderknobs, posts, legsLatherims, speaker conesExtrudeguitar bodies, gearsTubeleads, stringsInstanceskeys, frets, chain
A lathe spins a profile round an axis. An extrusion pushes a flat outline into depth. Instances draw one shape many times for the cost of one, which is how 122 synth keys and a whole bike chain stay cheap.

The Telecaster shows how far that goes. Its body starts as an outline of twelve curves, taken from the real guitar's dimensions. The outline is extruded into a slab. A second, thin slab on top carries the flame maple, which is a picture painted by code (next section). Then come the parts: two humbuckers made of boxes with twelve small cylinders each for the pole pieces, a bridge with six saddles, two knurled knobs, a selector switch, 22 frets placed by the same formula a guitar maker uses, and six strings of the right thicknesses.

1 An outlinetwelve curves, in millimetres2 Pushed into depthan extruded slab, 45 mm thick3 A flame toppainted on a canvas in code4 Hardware and stringsboxes, cylinders and tubes
The Telecaster body in four steps, drawn here from the same outline numbers the room uses.

The frets are a good example of a number doing the work. Each fret sits where it shortens the string by one semitone, so fret n is at 648 × (1 − 2−n/12) millimetres from the nut. Put that in a loop and the frets get closer together up the neck by themselves, exactly as on a real guitar.

The bass was done differently. Its body outline was traced from a photograph of Paul's own Warwick: the picture was scaled until the string length measured 864 mm, and the outline was read off as a list of points.

4Surfaces painted in code

A material can carry a picture, called a texture, that is wrapped over the shape. Some textures in the room are Paul's photographs: the sky, the framed prints, the book pages, the album cover, the medals. Most of the rest are painted when the page loads, onto an invisible HTML canvas with ordinary 2D drawing commands, and then handed to three.js as a texture.

The brick wall is rows of slightly varied rectangles with mortar between them, and a second, grey copy of the same bricks tells the light where the surface stands proud, so the mortar lines sit back. The oak floor is planks with grain lines and a little random tint. The flame maple on the guitars is stripes drawn across the grain and mirrored about the centre line, as two matched pieces of maple are on a real top, then darkened towards the edge, then given a cream binding line. The Jupiter-X front panel is one canvas 4,096 pixels wide, with every legend drawn as text, so the labels stay sharp when you zoom in.

Lettering on small parts uses the same idea. The names on the pedals, the logo on the amp and the maker's name on the pickups are each a small transparent canvas with text on it, placed a fraction of a millimetre above the surface.

Some canvases keep changing. The Bloomberg screens, the world clocks (which show the real time in each city) and the Commodore 64's monitor are textures that are redrawn while you watch.

5Light, and why only some things glow

The materials are physically based: each has a roughness and a metalness, and three.js works out how light leaves the surface from those. Chrome is fully metallic and smooth. The rug is rough and not metallic at all. Seven lights do the work: a soft light from above and below standing in for the sky, one directional light that casts the shadows (it draws the scene from its own position into a 2,048-pixel shadow map first), and the warm lamps in the room. A small blurred picture of a generic room is also used as a reflection, so that metal and lacquer have something to reflect.

The glow on the screens and bulbs comes from a trick with brightness. The scene is first drawn into a picture that stores colours as 16-bit floating-point numbers, so a colour can be brighter than white. A bloom pass then takes only the parts brighter than 1.0, blurs them and adds them back. Ordinary surfaces never reach 1.0, so they never glow. Screens, bulbs, the neon sign and the little red lights on the pedals are deliberately given colours far above it: a lit pedal light is red at 3.2. Last, a film-style tone curve brings everything back into the range a screen can show.

The scene, litcolours can pass 1.0HDR picturestored as 16-bit floatsBloombright parts blurred, addedTone mappingACES film curveScreen0.01.02.03.0bloom threshold: 1.0brickoakwhite keysgauge columnscreens and bulbspedal lightordinary surfaces: never bloomdrawn brighter than white on purpose: these glow
Each frame goes through four stages. The dashed line is the bloom threshold: glowing is a property of how bright a thing is, with no special cases in the code.

The light switch on the back wall uses the same numbers. Turning it off fades the lamps down over about a second and turns the sky up, so the aurora lights the room instead.

6The sky

The sky is one of four photographs of the aurora that Paul took from aircraft windows. It is drawn on the inside of a sphere 400 metres in radius with the room at its centre. A photograph only covers part of a sphere, so a short program that runs on the graphics chip for every pixel of sky (a shader) works out which way that pixel faces, turns the direction into two angles, and looks up the matching place in the photo. Beyond the photo's edges it fades into the photo's own edge colours, so there is no visible border.

the roomthe photograph95 degrees acrossbeyond its edges:the photo's edge coloursa sphere 400 m in radius,seen from the insidedirection of this pixelfrom the centre of the spheretwo anglesround (azimuth) and up (elevation)a place in the photographu across, v up
The photograph covers 95 degrees of the horizon, centred on the direction the camera normally looks. Clicking the camera on the tripod changes the photograph.

7The camera

The camera always looks at a target point, and its position is described by two angles and a distance from that target. Dragging changes the angles. Scrolling or pinching changes the distance. Clicking an object sets all four to the values that object asked for.

Nothing ever jumps, because the page keeps two copies of those numbers: where the camera is (the view) and where it should be (the goal). Input only ever changes the goal. Every frame, the view closes a fixed share of the remaining gap:

const k = 1 - Math.exp(-dt * 3.2);      // the share of the gap to close this frame
view.target.lerp(goal.target, k);
view.theta += (goal.theta - view.theta) * k;
view.phi   += (goal.phi   - view.phi)   * k;
view.dist  += (goal.dist  - view.dist)  * k;

The exponential is what makes it independent of frame rate: two short frames move the camera exactly as far as one long frame of the same total time. The result is a move that starts quickly and settles gently, with no animation timeline to manage.

targetcameraφθdFour numbers place the camera:a target, two angles and a distancegoalview00.5 s1 s1.5 sEach frame the view closes afixed share of the gap to its goalthe point underyour pointerZooming slides the camera along theline to that point, so it stays put
Left: the four numbers. Middle: how the view approaches a new goal. Right: zooming in goes towards the point under the pointer, or between your fingers.

Try it

Move the pointer along the line, or tap it. The ring is the goal; the green dot is the view, following by the same rule as the camera.

Zooming in aims at whatever is under the pointer. The page finds that point on the surface, then moves the target towards it in proportion to the change in distance, which keeps the point still on the screen while everything else grows around it:

// keep the point under the pointer where it is on the screen
goal.target.sub(anchor).multiplyScalar(next / old).add(anchor);
goal.dist = next;

The camera stops 30 cm from what it is looking at. Zooming back out returns the target to the object's own framing, so you cannot get lost.

8Knowing what you touched

A click is a point on a flat screen. To find out what is under it, the page fires an imaginary straight line, a ray, from the camera through that point into the scene and asks three.js for everything the ray passes through, nearest first. The first thing it meets is what you clicked.

What you clicked is usually a small part: one key, one string, one pedal. So the page climbs from that part up through its parents, collecting what each has to say. A part may carry its own action. Further up, the group that was registered as an object carries the name of its story. One click can therefore both pluck a string and open the guitar's story.

camerathe screenyour clickguitar bodystring, 0.25 mmits invisible boxhit boxclick: pluck itTelecaster(nothing)guitar rigstory: guitarThen up through its parents,collecting what each one says
A guitar string is a quarter of a millimetre thick, far too thin to hit. Each string has an invisible box around it, nearly as wide as the gap to the next string, and it is the box that catches the ray.
ray.setFromCamera(pointer, camera);
for (const hit of ray.intersectObjects(scene.children, true)) {
	let o = hit.object;
	const res = { id: null, click: null };
	for (; o; o = o.parent) {              // climb to the top of the tree
		if (!res.click && o.userData.click) res.click = o.userData.click;
		if (!res.id && o.userData.hot) res.id = o.userData.hot;
	}
	// anything else in the way (a wall, the floor) blocks the click
	return res.id || res.click ? res : null;
}

A few rules on top make it feel right:

Keys and strings sound when the button goes down, like the real thing. Everything else waits for the button to come up, so that a drag to turn the view is never mistaken for a click.

Instruments only play once you are at them. From across the room, the first click on the keyboards takes you there and plays nothing. Finding out that the keys work is left for you to discover.

A click is only a click if the pointer barely moved. For a mouse that means less than 6 pixels in under 0.6 seconds. A fingertip wobbles more and rests longer, so a touch is allowed 20 pixels and 0.9 seconds.

9Sound from arithmetic

Apart from the 45-second extracts of the album, there are no recordings in the room. Every note is calculated by the browser's Web Audio system as it is played. The buttons in this section run the room's own sound code, so what you hear is exactly what the room plays.

A guitar string

The strings use a method published by Kevin Karplus and Alex Strong in 1983. Fill a short buffer with noise, exactly one period of the note long: that is the pluck. Then play the buffer round and round, and each time round replace every sample with the average of itself and its neighbour, turned down very slightly. Averaging removes a little of the high frequencies on every pass, which is what a real string does as it rings: it starts bright and dies away to a pure, dull tone.

A burst of noiseone period of the note longDelay linen samples: n sets the pitchAverage with its neighbourthen multiply by 0.9975outround again, a little duller and a little quieter each timeThe first three periodsthe noise itself, repeating: bright and harshThe same string two and a half seconds laterquieter, and most of the high harmonics have gone
The loop, and what it produces. Both waveforms are from the room's own formula for the A string, 110 Hz.
const n = Math.round(44100 / f - 0.5);       // whole samples in one period
const rate = f * (n + 0.5);                  // this buffer's own sample rate
for (let i = 0; i < n; i++) d[i] = noise();  // the pluck
for (let i = n; i < len; i++)                // the string
	d[i] = keep * (0.5 * d[i - n] + 0.5 * d[i - n - 1]);

There is one problem with the method. The buffer must be a whole number of samples long, so most notes come out slightly out of tune. The usual cure is extra filtering. The room does something simpler: it gives each note's buffer its own sample rate, chosen so that the whole number of samples lasts exactly one period. The averaging adds a delay of half a sample, which is where the n + 0.5 comes from.

Try it: the Telecaster and its pedals

Strings
Pickup
Pedals
Bass

Pedals and an amplifier

The guitar's signal then goes through a chain of small processing blocks wired the way the real pedals are.

Stringssix loopsSelectorwhich pickupGuv'norboost into a clipChoruswavering copyDelay380 ms repeatsAmpclip, speakerEach pedal is in the path all the time. Its switch turns a volume control up or down, so there is no click.

The pickup selector is a filter. The bridge pickup hears the string near its end, where the high harmonics are strong, so it is left bright. The neck pickup hears it nearer the middle, so the top is rolled off at 1,600 Hz and the body of the note is lifted a little.

The Guv'nor multiplies the signal by sixteen and pushes it into a curve that flattens the peaks, a little more on one side than the other. Flattened peaks are what distortion is. The chorus adds a copy of the signal delayed by about 13 thousandths of a second, with the delay drifting up and down, which sounds like a second guitar that is never quite in time. The delay feeds the signal into a 380 ms echo that feeds back into itself, each repeat quieter and duller. The amp clips softly and then filters the result the way a small speaker would. Switch the amp off in the room and you hear only the bare strings, thin and quiet.

The bass uses the same string loop with two changes. It starts from a smooth triangle in place of noise, which is the shape a finger leaves in a string, and it is one note at a time: a new note stops the last one, as a player's hand does.

The Jupiter-X arpeggio

Press a key on the Jupiter-X in the room and it holds that note for sixteen beats while a pattern runs above it in D natural minor. Paul gave the pattern as eight letters: from D it goes D E F A C A C A, twice. From any other key it takes the same steps up the scale from that note.

Each note also goes into an echo set one and a half beats long. Because the echo is not a whole number of beats, every repeat lands halfway between two played notes, and the single line turns into an interlocking pattern twice as busy as what was played. The tempo is 228 beats a minute, so a beat is 0.263 seconds and the echo is 0.395.

DEFACbeat 1beat 5beat 9beat 13held Da note, on the beatits echoes, one and a half beats later: they land between the notes

Try it

The filled notes light as they play. Listen for the echoes filling the gaps between them.

The Prophet's sync sweep

The Prophet '08 in the room plays a sound that analogue synths are known for. Two oscillators run at different speeds, and every time the first completes a cycle it forces the second to start again. The pitch you hear is the first oscillator's. The second, cut off partway through its cycle, sets the tone, and as its speed is swept downwards the tone moves through a series of hard, vocal colours.

Firstsets the noteSecondruns fastereach time the first restarts, it forces the second to restart too1x2x3x4x5x00.5 s1 s1.5 sspeed of the second, through one note

Web Audio has no way to make one oscillator restart another, so the room calculates the waveform one sample at a time and plays the result. It works at twice the sample rate and averages pairs of samples, which removes some of the harshness that the sudden restarts would otherwise add.

master += step;
if (master >= 1) { master -= 1; slave = master * ratio; }   // the first restarts the second
slave += step * ratio;
if (slave >= 1) slave -= Math.floor(slave);
out = (2 * slave - 1) * 0.62 + (2 * master - 1) * 0.3;

Try it

10The Commodore 64 is running the real game

The game on the monitor is Chaos in Space, which Paul wrote in machine code and had published in 1988. The room does not play a video of it. It runs the original program.

The Commodore 64's processor is a version of the 6502, a simple chip with 56 kinds of instruction. The room contains a 6502 written in JavaScript: a table of small functions, one for each instruction code, and a loop that fetches the next byte of the program, runs the matching function and counts the time the real chip would have taken. It is given the game's 64 kilobytes of memory exactly as they stood when the game started, and it runs at the speed of a British C64, 985,248 cycles a second, with the 50-times-a-second interrupt that the game uses as its clock.

64K of memorythe game's own bytes6502 processor985,248 cycles a secondVideo chip picturea 384 x 272 canvasMonitor glassthe canvas as a textureAutopilotsteers the ship and firesYour keys: Z X Spacetake over for 6 secondsWatch pointsnew wave, life lost, game overThe page knows what the game is doing from wherethe processor is in the program, not from the picture.every other frame
The emulator is about 245 lines. It includes only what this one game needs: the processor, a few registers of the video and input chips, and a routine that turns the video memory into a picture.
while (cycles < end) {
	const h = watch[PC]; if (h) hook(h);       // a place we are watching?
	const op = ram[PC];                        // fetch
	PC = (PC + 1) & 0xFFFF; cycles += CYC[op];
	OPS[op]();                                 // execute
	if (cycles >= nextIrq) { nextIrq += 19656; irq(); }      // 50 times a second
}

The picture is worked out from the same memory the real video chip would read: the character screen, the sprites and the colours. It is painted onto a 384 by 272 canvas, and that canvas is the texture on the monitor's glass.

Most of what you see is characters. The ship, the ranks of aliens and the bombs they drop are printed on the Commodore's 40 by 25 character screen. The things that have to move smoothly are sprites: your shot, and any alien that leaves its rank to swoop at you. A sprite is a small picture that the Commodore's video chip lays over the screen at any pixel. The room has no video chip, so the emulator does that job in software, from the same numbers the game stores for the real chip.

Try it: play the game and watch the sprites

Collision register 00000000

This is the room's emulator running in this page. The picture is its canvas. The eight boxes are the video chip's eight sprites. A box lights when the game switches that sprite on, and shows its shape and position. Sprite 0 is your shot, and sprites 2 and up are swooping aliens. The line above reports when two sprites are touching, which is how the game knows that a shot has hit. The autopilot plays until you hold Left, Right or Fire.

How the game plays

You fly a ship that moves left and right and fires at waves of aliens, which drop bombs and, in some waves, swoop down at you. Left to itself, the room plays the game with an autopilot. The autopilot reads the ship's position straight from the game's memory, sweeps it from side to side and presses fire in bursts, by setting the same bits a real joystick would set. It is not a good player, and it loses lives and games in the ordinary way.

Click the computer and you tap the fire button. Hold Z or X to move and Space to fire, and the autopilot hands over to you until six seconds after your last key. One byte of the original program has been changed, so that the swooping aliens attack from the first wave and there is something to see straight away.

The page follows the game without looking at the picture. Five addresses in the program are marked, and when the processor reaches one the page knows that a new pass of the main loop has begun, a life has been lost, or the game is over.

The appendix at the end of this page has more for anyone who wants it: how a sprite is stored and drawn, how a hit is found to the pixel, and how the swooping aliens choose their paths.

11Machines that move correctly

Several things in the room move the way the real mechanism does, because the mechanism is modelled and the motion follows from it.

The bike

The bike is Paul's Specialized Tarmac SL7. Its gears have real teeth. A bicycle chain has a pitch of 12.7 mm from pin to pin, which fixes the size of every sprocket: a ring of n teeth has a radius of 12.7 / (2 sin(π / n)) millimetres. The chainrings have 52 and 36 teeth and the chain sits on the 15-tooth cog.

The chain's route is worked out as a belt problem: straight runs that touch each wheel at a tangent, joined by arcs round the chainring, the two small jockey wheels of the rear derailleur and the cog. The route is measured, divided into links 12.7 mm long, and one small box is placed for each link. To make the chain run, every link is moved a little further along the route each frame.

tyrechainring: 52 teethcog: 15 teethtwo jockey wheels keep the chain tautone small box for each link
The drivetrain, drawn with the room's own formulas: a chain round a 52-tooth chainring, two jockey wheels and a 15-tooth cog. Every wheel turns at the speed the chain gives it.

Click the bike and the pedals turn once a second for four seconds. The chain speed follows from the chainring, the cog's speed from the chain, and the back wheel turns 52 ÷ 15 = 3.47 times for each turn of the pedals. When the pedalling stops, the pedals and chain stop but the wheel keeps turning and slows down gradually, because a real hub has a freewheel.

The record deck

The record turns at 33⅓ revolutions a minute. When you start it, the arm swings across to the edge of the record, and the music begins only when the stylus has arrived. While the extract plays, the arm tracks slowly inwards and is close to the label when the music ends.

Smaller things

The world clocks show the actual time in each city. The speaker cones on the studio monitors move a few millimetres with the level of the sound. Plucked strings vibrate and die away. The fundraising gauge reads its total from the front page of the main site, so there is one figure to keep up to date.

12Phones

The same page runs on a phone, with some allowances. Phone screens are tall, so the camera stands further back to fit the same view across. The story card becomes a short strip at the bottom that opens on request. The sky uses smaller copies of the photographs, and the page never draws more than two pixels per screen point.

Touch needed the most care. A phone will not start any sound except from inside a touch, and it starts it at the end of the touch, so on a phone the keys and strings sound when the finger lifts. A phone also puts a page's sound to sleep when it has been idle, so every tap wakes it again. Pinching zooms towards the point between your two fingers, and two fingers moving together slide the view, which is how you get close enough to pick a single guitar string.

13Testing a room

A page like this can break in ways that are easy to miss, so it tests itself. Adding a word to the page's address makes it run a check and write the result to the browser's console. One check opens every story and performs every action a visitor can: each key, string, pedal and switch, each button, dragging, scrolling, pinching and zooming. Another clicks where each object should be in the whole-room view and confirms the right story opens. Another makes every kind of sound once.

ACTIONTEST 190 checks (29 stories with their actions, 142 clickable parts, 19 controls): all passed
SELFTEST 20 objects, found 20 ...
SOUNDTEST context running: jupiter ok, hold ok, arpeggio ok, prophet ok, guitar ok, bass ok, pedals ok, pickups ok ...
STATS objects 1826, meshes 1585, lights 7, triangles drawn 733518, textures 125

The checks run in a browser with no window, started from the command line, after every change and again against the live site after each upload. They confirm that everything responds and nothing throws an error. They cannot judge how the room looks or sounds. That part was done by looking and listening.

14How it was made

The room was built in conversation over two days in November 2026. Paul described what he wanted one request at a time, and supplied photographs of his own things: the guitars, the bike, the synths, the medals. Claude, Anthropic's AI model, working in Claude Code, wrote the code, ran the page in a windowless browser, read the screenshots and test results, and changed it until they were right.

Claude cannot hear, so every sound was tuned by Paul's ear, a request at a time: a bass that stops short like a muted string, an arpeggio a little slower, an echo of one and a half beats and not two. The rule Paul set for the objects was that anything standing for a real thing should be the real thing, at its real size, in careful detail.

If you would like to look further, everything is in the page's own source. The files are plain JavaScript with comments, and your browser's developer tools will show all of them.

AAppendix: sprites and swoopers in detail

This appendix adds to section 10. It covers how the emulator reproduces the Commodore 64's sprites, and how Chaos in Space flies its swooping aliens. The figures are drawn from the game's own memory.

How the sprites are done

On a real Commodore 64, sprites are a feature of the video chip. The chip can lay up to eight small pictures over the screen, each 24 pixels wide and 21 high, and put any of them at any pixel. A program does not draw them. It stores a few numbers in the chip's registers and the chip does the rest, fifty times a second.

The room has no video chip, so the emulator stands in for one in software. The game's code is unchanged: it still stores the same numbers at the same addresses. The emulator keeps those numbers in an array, and each time the room wants a picture it reads the array and does what the chip would have done.

The ship and the ranks of aliens are characters: the game points the video chip at a character set of its own and prints them on the 40 by 25 character screen. An alien that leaves its rank to swoop becomes a sprite, and so does your shot. The game keeps sprite 0 for the shot and sprites 2 to 7 for swoopers. In ten minutes of the autopilot's play only 2 and 3 were needed, and sprite 1 never came on. An explosion is not another sprite. When a swooper is hit, the game changes that sprite's shape number from 225 to 226 and the alien becomes a burst of dots. You can watch it happen in boxes 2 and 3 of the viewer in section 10.

Shape 225: 63 bytes starting at $384021 rows of 3 bytes; a 1 bit is a pixelrow 5 is these three bytes11111011$FB11011111$DF00000000$00What the game sets for sprite 2$D004, $D005where it is: X and Y$D010, bit 2a ninth bit for X, past 255$D015, bit 2switched on or off$D029its colour$07FAwhich shape: 225, then 226 when it is hitShape number x 64 is the address: 225 x 64 = 14,400, which is $3840.224: the shotsprite 0225: a swoopersprites 2 to 7226: an explosionthe same sprite, when hit
The swooping alien as the game stores it, read from the game's own memory. Each row is three bytes and each 1 bit is a pixel. On the right is everything the game sets to put the alien on the screen. It is drawn here in a lighter red than the Commodore's, to show up on this page.

A frame is built in three passes over a grid of 384 by 272 pixels. The first fills it with the border colour. The second draws the thousand characters. The third goes through the eight sprites. For each one that is switched on, it reads the shape number, multiplies it by 64 to find the shape's 63 bytes, and paints a pixel for every 1 bit, in that sprite's colour, at the position held in its two registers. Sprite positions are measured from a point above and to the left of the screen, so that a sprite can slide in from off the edge: X 24, Y 50 is the screen's top left corner.

for (let n = 0; n < 8; n++) {
	if (!((io[0x15] >> n) & 1)) continue;               // $D015: is sprite n on?
	const x = io[n * 2] | (((io[0x10] >> n) & 1) << 8); // X, with its ninth bit
	const y = io[n * 2 + 1];
	const shape = ram[0x07F8 + n] * 64;                 // shape number, times 64
	const colour = PALETTE[io[0x27 + n] & 15];
	for (let row = 0; row < 21; row++) {
		const at = shape + row * 3;                      // three bytes make 24 bits
		const bits = (ram[at] << 16) | (ram[at + 1] << 8) | ram[at + 2];
		for (let col = 0; col < 24; col++)
			if ((bits >> (23 - col)) & 1) plot(x - 24 + col, y - 50 + row, colour);
	}
}

The game also asks the chip a question. Reading address $D01E, the chip's collision register, returns a byte with one bit set for every sprite that is touching another sprite, and Chaos in Space reads it and tests the shot's bit to find out whether the shot has hit a swooper. The real chip notices an overlap while it is drawing. The emulator works out the answer at the moment the game asks. For each pair of sprites whose rectangles overlap, it lines up their rows, shifts one sideways by the distance between them, and looks for a pixel that is set in both.

Row 5 of the alien, shot 8 pixels to its rightalienshotboth2 pixels in both: $D01E reads 00000101 (sprites 0 and 2)Row 11 of the alien, shot 7 pixels to its rightalienshotbothno pixel in both: $D01E reads 00000000
One row of the test, twice. On the left the shot overlaps the alien's body, and both sprites are reported. On the right the shot is between its legs, and that row reports nothing. The test is exact to the pixel, so the empty corners of a sprite's rectangle never count as a hit.

The stand-in is not a whole video chip. It builds the picture in one go, where the real chip works down the screen a line at a time. Where two sprites overlap it draws the higher-numbered one on top, which is the opposite of the real chip. It leaves out double-size sprites, sprites that pass behind characters, and collisions between sprites and characters. The game does not ask for the first two of those: in the same ten minutes it left both registers at zero.

How the swoopers fly

The swoopers' behaviour is in the game's code, which can be read from the same memory image. Nothing about a dive is worked out as it happens. The game holds sixteen flight paths, each a list of X and Y positions ending in a marker byte, and a table that says which path an alien takes.

The character screen, 320 by 200 pixels16 pathsfor 35 table entrieswhere a dive startsshortest: 27 stepslongest: 237 stepsEvery path ends near thebottom, at the ship's level.
The sixteen dive paths, drawn from the lists in the game's memory. Each starts in the formation and ends at the bottom of the screen. Some join another path partway and share the rest of it.

There are six swooper slots, tied to sprites 2 to 7. On a timer, the game checks whether fewer swoopers are in the air than the current limit. If so, it picks a place in the 40-strong formation at random and moves along until it finds an alien that is still alive. It looks up that alien's path, marks its place in the formation as empty, and switches on a free slot's sprite at the start of the path, in the alien's own colour. On a second timer, every swooper in the air moves one step along its list. A swooper that reaches the end of its list without being shot has its sprite switched off and goes back to its place in the formation.

The limit starts at two. Swoopers come in every other wave, and each time one of those waves is cleared the limit goes up by one, to at most six, and you are given another life if you have fewer than four. The byte that was changed for the room is the starting value of the switch between the two kinds of wave, which is why the room's first wave has swoopers and the original's did not.

The two kinds of hit are found in different ways. A shot hitting a swooper is the video chip's business: the game reads $D01E, tests the shot's bit, then tests the bit of each of the six swooper sprites to see which one it was. That sprite's shape number becomes 226, and its colour steps through red, yellow, orange and white for eleven ticks before it is switched off. A swooper hitting the ship cannot be found that way, because the ship is made of characters. The game does it by arithmetic: once a swooper is low on its path, it compares the swooper's X with the ship's.

The bombs the aliens drop are not sprites either. Up to ten can be falling at once, and each is a character that moves down the screen one row at a time.