Sergio’s Room v0.1 — from a flat sketch to a 3D room with Three.js (camera, rays and a book that opens)

This project started as a 3D desk. Today it is “Sergio’s Room”, a story-driven game set in my room; this post tells how it started.

The first thing I did when I opened the prototype was to grab a simulator disc and see what it did. It rose, flew to the tower, the tray swallowed it and the monitor lit up with the simulator. And what I liked most was that the keyboard actually worked: each key sinks and whatever you type shows up on the screen. In this chapter I tell you how that first room is built, piece by piece. The code was written by Claude, Anthropic’s AI, from what I described (in chapter 1 I explain how we work); here I explain all of it, line by line, so you can follow it even if you have never touched JavaScript.

Sergio’s Room series · chapter 2 of 11. You are coming from chapter 1: the idea. The whole project is in the Sergio’s Room report.

In short

Version 0.1 is the proof that the idea works in a browser: a 3D room seen from the chair, the camera following the mouse and each object with its own action. It all fits into a single 925-line HTML file, with no external models: the walls, the desk, the books and the tower are boxes, cylinders and cones in the website’s colours.

Version 0.1: I look at the shelf, the whiteboard, the tower and the drawer; I pick up the IC1 book, it opens and I turn two pages. The white dot is the mouse.

The clip still shows buttons at the bottom (“Turn page”, “Put the book down”, “Objects”). They are exactly what version 0.2 removes. But for a first version, something else mattered: checking that looking, pointing and grabbing feel right.

What it had to achieve

There was one goal: check that the idea works in a browser, in a single file, with nothing to install. To know whether I had made it, each requirement had its own way of being checked:

RequirementHow it was checkedMet?
A 3D room seen from the chair, in one HTML file and with no external modelsThe file opens and draws the sceneYes
The camera follows the mouse: up the shelf, down the drawer, left the whiteboard, right the towerScreenshots and clipYes
Every object lights up when hovered and has its actionClip and screenshotsYes
Books you can pick up and openClipYes, but turned pages vanish under the cover
A monitor that boots SergioLearns OSAutomated test with PlaywrightYes
An accessible alternative“Objects” menu and EscYes, but with buttons on screen

Two rows say “yes, but”. Those two are the ones that open the next version.

Design before code

v0.1 was built in a single day, 3 November 2026, before deciding that the design would be saved while building. My design was the description: the Five Nights at Freddy’s reference and what had to be on each side of the chair. So the plan below is not an earlier sketch: Claude took it from the code for this chapter, with the real position of each object in metres.

Floor plan of the v0.1 roomTop view with the positions from the code: the 1.9 by 0.75 m desk, the shelf on the back wall, the whiteboard on the left wall, the monitor and keyboard in the center, the tower on the right, the lamp and mug on the left, the drawer under the desk and the camera 55 cm from the edge, able to turn 60 degrees each way.desk (0.74 m high)shelf (1.63 and 2.01 m)whiteboardmonitorkeyboardtowerdisc drive 1.10 mlampmugdrawerdiscs±60°camera: eyes at 1.22 m1 mTop viewmeasures from the coderoom of2.5 × 2.4 m
Everything fits inside the ±60° turn: that is why v0.1 needed no turning round.

Look at the violet arc: the camera turns 60 degrees each way, and everything important (whiteboard, shelf, monitor, tower) fits inside that fan. That is why v0.1 did not need to turn all the way round. The measurements have a reason too: the desk is 0.74 m high, the height of an ordinary desk, and the eyes are at 1.22 m, the height of someone sitting down.

This is what the room looks like when you look up and to the left:

3D prototype v0.1 looking up: the two shelves with the first-year and second-year books3D prototype v0.1 looking left: the whiteboard with the January 2027 calendar and the question of the day
Above, the two shelves: first-year and second-year books. On the left, the whiteboard with the calendar and the question of the day.

The discarded idea was the 2.5D sketch from the previous chapter: flat layers with no depth. The decision to move to real 3D is what gives meaning to everything that follows.

Before you start: HTML, JavaScript and three.js in five minutes

If you already write JavaScript, skip this section. If not (like me before this project), here is the minimum to read the rest.

The HTML: the page that holds the room

The whole prototype is one .html file. The important part is at the end:

<div id="loading" aria-live="polite"><div>~/escritorio <span class="dollar">$</span> cargando la habitación<span class="cur">_</span></div></div>
<div id="fallback" hidden></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>
(function () {
'use strict';
LineWhat it does
<div id="loading" …>A box with the text “loading the room” (in Spanish, like the whole prototype). id is its name, so JavaScript can find it; aria-live makes a screen reader read the text when it changes
<div id="fallback" hidden>The error box, hidden (hidden) until it is needed. Watch out for it: it is the first bug of the version
<script src="…three.min.js">Downloads the three.js library from the internet (from cdnjs)
<script>The program starts here, written in JavaScript inside the page itself
(function () { … })();A function that runs as soon as it is defined. It keeps the program’s variables from mixing with the page’s
'use strict';Asks the browser to report errors instead of letting them slip through silently

The minimum of JavaScript

What you seeWhat it means
var x = 5;A variable: a named box (x) holding a value (5)
function box(w, h) { … }A function: a named piece of code that takes data (w, h) and does something. You use it like this: box(1.9, 0.04)
{ yaw: 0, pitch: -0.12 }An object: several variables together, each with its name. cam.yaw reads the one called yaw
[1, 2, 3] and list[0]A list (array) and its first element (counting starts at 0)
a ? b : cIf a is true, it is b; otherwise c. An if in one line
Math.sin(x), Math.exp(x)Maths functions that come with the language
new THREE.Mesh(…)Creates a new object of a type (here, a three.js mesh)
function (e) { … } passed to another functionA function that will run later, when something happens (an animation ends, the mouse moves…)

The minimum of three.js

three.js organises everything into three pieces: a scene (everything that exists), a camera (where it is seen from) and a renderer (which draws the scene, seen from the camera, onto a canvas on the page).

The pieces of three.jsAt the top, the three pieces of three.js: the renderer, which draws on the canvas; the scene, with everything that exists; and the camera, where it is seen from. renderer.render(scene, camera) draws the scene seen from the camera. Inside the scene there are meshes (shape plus material), lights and groups of parts. A box mesh is a BoxGeometry with a MeshStandardMaterial.rendererdraws on the <canvas>sceneeverything that existscamerawhere it is seen fromrenderer.render(scene, camera)Meshmesh = shape + materialLightlightGroupgroup of partsBoxGeometrythe shape (a box)MeshStandardMaterialcolour and lightEvery frame (60 timesa second) it is drawn again
One scene, one camera and a renderer to draw it: everything else is pieces inside the scene.

This is how the prototype creates the renderer:

var canvas = $('#gl'), renderer;                 // the page's <canvas id="gl">
try {
  renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true });   // antialias: smooth edges, no jaggies
  if (!renderer.getContext()) throw new Error('sin WebGL');                  // if the browser cannot draw in 3D, jump to catch
} catch (e) {
  // …show the error box with the links to the normal website and stop
}
renderer.toneMappingExposure = 0.9;              // slightly lower exposure: the room is at night

And the scene and the camera:

var scene = new THREE.Scene();                                  // the scene: empty for now
scene.background = new THREE.Color(0x141221);                   // the background, almost black (the website's colour, at night)
var camera = new THREE.PerspectiveCamera(62, 1, 0.02, 20);      // 62° field of view; it sees from 2 cm to 20 m
var BASE = new THREE.Vector3(0, 1.22, 0.55);                    // where the eyes are: 1.22 m high, 55 cm behind the edge of the desk

A mesh is an object you can see: a shape (geometry, for example a box) plus a material (its colour and how light hits it). And since something that moves has to be drawn again, the program has a loop: a function that calls itself about 60 times a second with requestAnimationFrame.

function loop(now) {                                         // now: the clock, in milliseconds
  var dt = Math.min(0.05, (now - last) / 1000); last = now;  // seconds since the previous frame (0.05 at most)
  runTweens(now); updateKeys(now); applyCamera(dt);           // move animations, keys and camera forward
  if (needPick && (mode === 'free' || mode === 'drawer' || mode === 'board')) { needPick = false; setHover(pick()); }  // what is under the mouse?
  // …
  if ($('#os').hidden) renderer.render(scene, camera);       // draw (unless the operating system is open)
  requestAnimationFrame(loop);                               // and ask the browser to call loop again
}

With this you can already read everything else: each piece below is something created in the scene or something the loop does on every frame.

How the code is organised

A single file, top to bottom: first the engine is set up, then the room is built, then the objects you can touch are registered and finally a loop runs on every frame.

How the v0.1 code is organisedA single 925-line file with seven parts: engine and scene, room, objects registered with reg(), camera, pointer with the ray, animations with tweens and an interface with buttons. A loop calls the animations, the camera, the ray and the rendering every frame.escritorio-3d.html · 925 lines · a single fileengine and scenerenderer · scene · camera · mat() · box()roomwalls, desk, drawer, monitor, keyboard, towerobjectsreg(key, meshes, label, onClick) · books · discscameraapplyCamera(dt) · focuspointerRaycaster · pick() · setHover()animationstween(dur, fn, done) · ease()interfacebuttons, "Objects" menu, SergioLearns OSlooprunTweensapplyCamerapickrenderEvery frame, the loop calls the pieces in this order.
In violet, the two pieces that v0.2 turns into the registry and the state machine.
PieceWhat it doesWho it talks to
Engine and sceneCreates the renderer, the scene, the camera and the mat() and box() helpersEveryone uses it
RoomWalls, desk, drawer, monitor, keyboard, tower, lamp and shelfObjects and loop
Objectsreg() records each thing you can touch: its name, its meshes and what a click doesPointer
CameraapplyCamera() turns the mouse into where to lookLoop
PointerThe ray (Raycaster) and pick() tell which object is under the mouse; setHover() lights it upObjects
Animationstween() moves, turns and scales with a smooth curveBooks, discs, drawer
InterfaceThe buttons, the “Objects” menu and SergioLearns OSObjects

Read the table top to bottom and you get the order of the file. In a long single-file program, that order is the only thing that stops you getting lost; in v0.2 I turn it into modules.

How it is built, piece by piece

The room made of boxes

Everything you see is built with two small functions. mat() creates a material (the colour and how it reflects light) and box() creates a box of that material at a position.

// A "standard" material: it reacts to light like a real object.
// r = roughness (0 shines like a mirror, 1 is matte), m = how metallic it looks,
// e and ei = colour and strength of the light the object gives off by itself (the coral glow uses it).
function mat(color, o) {
  o = o || {};
  return new THREE.MeshStandardMaterial({ color: color, roughness: o.r !== undefined ? o.r : 0.82, metalness: o.m || 0.04,
    emissive: o.e || 0x000000, emissiveIntensity: o.ei || 0, map: o.map || null, transparent: !!o.t, opacity: o.op !== undefined ? o.op : 1, side: o.side || THREE.FrontSide });
}
// A box w wide, h high and d deep (in metres), centred on (x, y, z).
// By default it hangs from the scene; if parent is given, it hangs from that group and moves with it.
function box(w, h, d, m, x, y, z, parent) {
  var mesh = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), m);
  mesh.position.set(x || 0, y || 0, z || 0);
  (parent || scene).add(mesh);
  return mesh;
}

Line by line:

CodeWhat it does
o = o || {};If no options are passed, use an empty object (so o.r does not fail)
o.r !== undefined ? o.r : 0.82The roughness: the one passed in or, if not, 0.82 (almost matte)
new THREE.BoxGeometry(w, h, d)The shape: a box with those measurements
new THREE.Mesh(shape, material)The mesh: the shape with its material
mesh.position.set(x, y, z)Where its center is, in metres
(parent || scene).add(mesh)Hangs it from the group passed in or, if not, from the scene
return mesh;Returns the box so it can be moved later

With that, the desk is one line: box(1.9, 0.04, 0.75, deskM, 0, 0.72, -0.35). A board 1.9 m wide, 4 cm thick and 75 cm deep, with its center at a height of 0.72 m. Since the box grows 2 cm up and 2 cm down from its center, the top ends up at 0.74 m: the height on the plan.

ObjectCallWhat it means
Deskbox(1.9, 0.04, 0.75, …, 0, 0.72, -0.35)1.9 × 0.75 m board; its top at 0.72 + 0.02 = 0.74 m
Towerbox(0.2, 0.46, 0.4, …, 0.82, 0.97, -0.42)20 × 46 × 40 cm, on the right (x = 0.82)
Back wallplane(2.5, 2.6, …, 0, 1.3, -1.2)2.5 m wide and 2.6 m high, 1.2 m in front of the chair

For the curious. In three.js, x points right, y points up and z points towards you. That is why everything in front of the chair has a negative z: the back wall is at z = −1.2 and the camera at z = 0.55.

Looking with the mouse: from a point to two angles

This is the piece that makes the idea work. The mouse is somewhere on the screen; the camera has to look somewhere. The bridge is two angles:

  • the yaw: how far you look left or right;
  • the pitch: how far you look up or down.

First, the mouse position becomes two numbers between −1 and 1, mx and my. The center of the screen is (0, 0); the left edge is mx = −1; the top edge is my = 1. That way it does not matter whether your screen is 1280 or 1920 pixels wide.

From the mouse position to two anglesOn the left, the screen with the mx and my axes from −1 to 1 and the mouse at (0.5, 0.5). On the right, the v0.1 formulas: the turn is −mx times 1.05 radians and the tilt is −0.12 plus my times 0.75 upwards or 0.85 downwards. With the mouse at (0.5, 0.5), the camera turns 30 degrees right and tilts 15 up.Where the mouse ismx = −1mx = 1my = 1my = −1(0.5, 0.5)Where the camera looksyaw = −mx · 1.05turn: −60° to 60°pitch = −0.12 + my · 0.75if my > 0: up to 36° (shelf)pitch = −0.12 + my · 0.85if my < 0: down to −56° (drawer)With the mouse at (0.5, 0.5):yaw = −0.53 rad (30° right)pitch = 0.26 rad (15° up)mx and my go from −1 to 1: the center of thescreen is (0, 0) and looks at the monitor.
Two multiplications turn a point on the screen into where you look.

Then each number is multiplied by a limit. This is the real code:

// ax: the target yaw. Mouse on the left (mx = −1) → +1.05 rad: the camera looks left.
var ax = isTouch ? dragYaw : -mx * 1.05;
// ay: the target pitch. Upwards it goes less far (0.75) than downwards (0.85),
// because the drawer is lower down than the shelf is high up. −0.12 = looking slightly at the desk at rest.
var ay = isTouch ? dragPitch : (my > 0 ? -0.12 + my * 0.75 : -0.12 + my * 0.85);
CodeWhat it does
isTouch ? dragYaw : …On a phone (touch) you look by dragging your finger, so the angle accumulated by the drag is used; with a mouse, the mouse position
-mx * 1.05Turns mx (−1 to 1) into a yaw from −1.05 to 1.05 radians (about 60°)
my > 0 ? … : …Picks the upper limit (0.75) or the lower one (0.85) depending on where the mouse is
-0.12 + my * …Starts from looking slightly down (−0.12 rad, about 7°) and adds or subtracts

Why the minus sign in -mx? Because in three.js a positive yaw turns to the left, and a mouse on the left has a negative mx. The minus makes them agree.

These are the values you get by running those formulas with node:

Mouse (mx, my)YawPitchWhat you see
(0, 0)0°−6.9°The monitor
(−1, 0)60.2°−6.9°The whiteboard (left)
(1, 0)−60.2°−6.9°The tower (right)
(0, 1)0°36.1°The shelf (up)
(0, −1)0°−55.6°The drawer (down)
(0.5, 0.5)−30.1°14.6°Between the monitor and the tower, slightly up

Check one by hand: with my = 1, the pitch is −0.12 + 1 · 0.75 = 0.63 radians. One radian is 180/π ≈ 57.3 degrees, so 0.63 · 57.3 ≈ 36.1°. It adds up.

With the two angles, the camera needs a point to look at. That is what sine and cosine are for:

var cp = Math.cos(cam.pitch);   // how much of the gaze is "horizontal"
// A point 1 m in front of the eyes, in the direction of the two angles
camera.lookAt(cam.pos.x - Math.sin(cam.yaw) * cp,   // left/right
              cam.pos.y + Math.sin(cam.pitch),        // up/down
              cam.pos.z - Math.cos(cam.yaw) * cp);    // forwards (negative z)

For the curious. Picture a 1 m stick coming out of your eyes. If you tilt it up by an angle pitch, its tip rises by sin(pitch) and its shadow on the floor measures cos(pitch). That shadow is what gets split between left-right (sin(yaw)) and forwards (cos(yaw)). That is why cp multiplies both: the more you look up, the shorter the shadow. These are spherical coordinates, explained with a stick.

Smoothing: no jerky camera

If the camera jumped to the new angle on every mouse movement, every small tremor of your hand would be a jolt in the image. The fix is to make the camera chase the target angle, covering on each frame a share of what is left:

var rate = focus && focus.rate ? focus.rate : 5;   // 5 = how fast the smoothing is
// k: the share of the remaining way covered in this frame.
// It depends on dt (the time since the previous frame), so it behaves the same on any screen.
var k = reduced ? 1 : 1 - Math.exp(-dt * rate);    // with "reduce motion", k = 1: it arrives at once
cam.yaw += (ty - cam.yaw) * k;                     // current yaw += what is left · k
cam.pitch += (tp - cam.pitch) * k;
The camera's exponential smoothingGraph of the share of the way covered against time when the mouse jumps to the right edge: a dashed line jumps straight to 100 per cent (no smoothing) and the violet curve rises fast at first and slows down at the end: 39.3 per cent at 0.1 seconds, 91.8 at 0.5 and 99.3 after one second.0 %25 %50 %75 %100 %0 s0.25 s0.5 s0.75 s1 s39.3 %91.8 %Every frame:k = 1 − e^(−dt · 5)turn += (goal − turn)·kIt covers a share of whatis left: fast at first,gentle at the end.no smoothing: a jumpwith smoothingshare of the way to the tower (a 1.05 rad turn), at 60 fps
Look at the shape: it never jumps and it is nearly there in half a second.

The numbers come from simulating with node a sudden turn to the tower (1.05 rad) at 60 frames per second:

TimeYawShare of the way
0.1 s−0.413 rad39.3 %
0.2 s−0.664 rad63.2 %
0.5 s−0.964 rad91.8 %
1.0 s−1.043 rad99.3 %

At first it goes fast (in a tenth of a second it has done almost 40 %) and at the end it slows down. That slowing down is what the eye reads as “smooth”.

For the curious. Why 1 − e^(−dt·5) and not a fixed number like 0.08? With a fixed number, a 144 Hz screen would take 144 steps a second and a 60 Hz one would take 60: the camera would be more than twice as fast on the first. With the exponential, two frames of dt/2 cover exactly the same as one frame of dt, because e^(−a)·e^(−b) = e^(−(a+b)). The next chapter checks it with node: after 0.5 s, 91.8 % of the way at 30, 60 and 144 fps.

Knowing what you point at: the ray

To light up the object under the mouse, the program casts a ray from the camera through the mouse point on the screen. The first object it hits is the one you are pointing at.

How the program knows what you point atA ray leaves the camera through the mouse point on the screen. The first object it hits, a book, is the one that lights up; it also hits the wall behind, but further away, so it is ignored.camerascreenthe mouse becomes −1…1 (ndc)bookfirst hit:lights up in coralwall
The ray goes through everything, but only the first object it touches counts.
function pick() {
  raycaster.setFromCamera(ndc, camera);                    // the ray: from the camera, through the mouse point (ndc, −1 to 1)
  var hits = raycaster.intersectObjects(pickables, false); // everything it hits, sorted from nearest to furthest
  for (var i = 0; i < hits.length; i++) {
    var k = hits[i].object.userData.key;                   // every mesh knows which object it belongs to (reg() noted it)
    if (k && objs[k] && objs[k].enabled()) return k;       // the first one that can be used right now
  }
  return null;                                             // you are not pointing at anything
}

Why loop through the list instead of always taking hits[0]? Because sometimes the nearest thing cannot be used at that moment (for example, a disc when there is already another one inside). This way, the ray “goes through” whatever does not count.

Once found, setHover() changes the colour of the light it gives off to coral (0xFF6B4A) and its command appears next to the mouse. It first stores the original colour so it can give it back when the mouse leaves.

Animations with tweens

An animation is a number that goes from 0 to 1 over a given time. The tween (from in-between) works out that number on every frame and passes it to a function that moves whatever it needs to:

// The curve: starts slowly, speeds up and slows down (cubic ease in and out)
function ease(x) { return x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2; }
// tween(duration in ms, what to do with the progress, what to do at the end)
function tween(dur, fn, done) { var t = { t0: performance.now(), dur: reduced ? 1 : dur, fn: fn, done: done }; tweens.push(t); return t; }
function runTweens(now) {
  for (var i = tweens.length - 1; i >= 0; i--) {               // back to front: items can be removed without skipping any
    var t = tweens[i], p = Math.min(1, (now - t.t0) / t.dur);  // p: how much time has passed, from 0 to 1
    t.fn(ease(p), p);                                           // it moves according to the curve, not to the time
    if (p >= 1) { tweens.splice(i, 1); if (t.done) t.done(); }  // finished: remove it and let us know
  }
}

The book table below shows the curve in action. What matters is the shape: halfway through the time (p = 0.5) the movement is exactly halfway, but at 10 % of the time it has barely started (0.4 %).

To chain animations, each tween carries the next one inside its done. With three steps it is readable; with six (putting a disc in), the code drifts to the right and is hard to follow. It is the first warning of what v0.2 fixes with promises.

The book and its hinge

A v0.1 book is a group: several pieces that move together. To make the cover open at the spine, like a real book, you do not turn the cover: you turn a hinge, an empty group placed right on the spine, and the cover hangs from it.

The book's hingeOn the left, the book seen from above: the block of pages, the spine and the cover, which turns around a point on the spine down to −167.4 degrees (−π times 0.93). On the right, the group tree: the whole book, its fixed parts, the "pivot" hinge with the cover, and the "flipPivot" hinge with the page that turns.The book, seen from abovepagesspineopen cover: −167.4°(−π · 0.93)closed coverHow it is builtgthe whole bookspine, covers, pagespivothinge at the spinecoverturns with the hingeflipPivothinge of the pagepageonly while turning
Turning the hinge, not the cover, is what makes the cover open at the spine.
// The hinge (pivot) sits on the edge of the spine: x = t/2 (the cover side), z = d/2 (the spine)
var pivot = new THREE.Group(); pivot.position.set(t / 2, 0, d / 2); g.add(pivot);
// The cover hangs from the hinge, shifted −d/2 in z: so its edge lines up with the hinge axis
var cover = box(0.005, hgt, d, bodyM, 0.0025, 0, -d / 2, pivot);
// …and opening it means turning the hinge: −π · 0.93 = −167.4° (almost flat, without reaching 180°)
tween(620, function (e) { o.pivot.rotation.y = -Math.PI * 0.93 * e; }, …);
CodeWhat it does
new THREE.Group()An empty group: it is invisible, it is only there to hang things from
pivot.position.set(t / 2, 0, d / 2)Places it at the spine corner (half the thickness t and half the depth d)
g.add(pivot)The hinge is part of the book: it moves with it
box(…, 0.0025, 0, -d / 2, pivot)The cover hangs from the hinge, shifted half the depth back: its edge sits right on the hinge
o.pivot.rotation.y = -Math.PI * 0.93 * eTurns the hinge about the vertical axis; e goes from 0 to 1 along the curve, so the angle goes from 0 to −167.4°

If you turned the cover directly, it would turn around its center, like a door hinged in the middle. Hanging it from a point on the spine makes it turn around its edge. These are the angles of the cover as it opens, worked out with node from the same curve:

Time (p)ease(p)Cover angle
00.0000°
0.250.063−10.5°
0.50.500−83.7°
0.750.938−156.9°
11.000−167.4°
3D prototype v0.1: the IC1 book picked up and open in front of the camera, with the buttons at the bottom
The IC1 book open in front of the camera. At the bottom, the buttons that v0.2 removes.

Why 0.93 and not 1? At exactly 180°, the cover would lie in the same plane as the pages and the two surfaces would “fight” when drawn (in 3D graphics this is called z-fighting: they flicker). Leaving it at 167° avoids the problem and also looks more natural.

Putting a disc in: changing parent without moving

When you choose a disc, the tray slides out, the disc rises, flies over it, drops in and the tray closes with it inside. The trick is at one specific moment: when the disc is over the tray, it becomes its child.

attach: changing parent without movingTwo scene trees. Before, the disc and the tray both hang from the scene. After tray.attach(disc), the disc hangs from the tray, so when the tray slides into the tower, the disc goes in with it.Before: the disc is loosescenedisctrayattachAfter: it is a child of the trayscenetraydiscIt does not move in the world: its position inside the tray is recalculated.
From the attach on, moving the tray also moves the disc.
tween(420, function (e) { tray.position.z = -0.287 + 0.13 * e; }, function () {               // 1. the tray slides out 13 cm
  tween(420, function (e) { o.mesh.position.lerpVectors(p0, up, e); o.mesh.rotation.y = o.rotHome + e * 3; }, function () { // 2. the disc rises, spinning
    tween(520, function (e) { o.mesh.position.lerpVectors(up, over, e); }, function () {     // 3. it flies over the tray
      tray.attach(o.mesh);                                // 4. now it is a child of the tray: it will move with it
      var q = o.mesh.position.clone();                    //    its position is now in tray coordinates
      tween(260, function (e) { o.mesh.position.lerpVectors(q, inTray, e); }, function () {  // 5. it drops into its slot
        tween(420, function (e) { tray.position.z = -0.157 - 0.13 * e; }, …);              // 6. the tray goes in with the disc

attach is different from add. add would change the parent and keep the same position numbers, which would now be measured from the tray: the disc would jump somewhere else. attach recalculates those numbers so that in the world it stays exactly where it was. From that moment on, moving the tray moves the disc.

And there you also have the problem with nested animations: six levels of tween inside tween. It works, but it is hard to read.

The keyboard: 56 keys, a single mesh

What I liked most about the prototype. The keyboard has 14 × 4 = 56 keys. If each one were its own mesh, that would be 56 draw calls (56 times the processor asks the graphics card for something). With an instanced mesh (InstancedMesh), all 56 are drawn at once: the same shape, repeated with a different position for each.

var KC = 14, KR = 4, keyGeo = new THREE.BoxGeometry(0.026, 0.01, 0.026);           // a 2.6 × 2.6 cm key
var keys = new THREE.InstancedMesh(keyGeo, mat(0x3A3552, { r: 0.6 }), KC * KR);     // 56 copies, one single mesh
for (var r = 0; r < KR; r++) for (var c2 = 0; c2 < KC; c2++) {
  var i = r * KC + c2, kx = -0.198 + c2 * 0.0305 + (r % 2) * 0.008, kz = -0.248 + r * 0.032; // every other row shifted 8 mm
  keyBase.push([kx, 0.762, kz]); dummy.position.set(kx, 0.762, kz); dummy.updateMatrix(); keys.setMatrixAt(i, dummy.matrix);
}
// On a key press: the key drops 6 mm for 70 ms and comes back up over the next 90 ms
var dt = now - keyPress[k], d = dt < 70 ? -0.006 : (dt < 160 ? -0.006 * (1 - (dt - 70) / 90) : 0);
Time since you pressed itHow far it is pressed down
0 ms6.0 mm
70 ms6.0 mm
100 ms4.0 mm
130 ms2.0 mm
160 ms0 mm

The 100 ms row worked out: 6 · (1 − (100 − 70) / 90) = 6 · (1 − 1/3) = 4 mm. What you type appears on the monitor and, if you type startx and press Enter, the computer turns on.

The decisions

DecisionAlternativesWhy this one
three.js r128 from cdnjs, in a single fileA current version with modules; Babylon.jsIt fitted into one HTML file for the prototype published on claude.ai. v0.2 moves to a current version with modules
Basic shapes in the website’s coloursBlender modelsTest the interaction first; the models arrive in v0.4
Text drawn on canvases (CanvasTexture)3D text; HTML on topSharp, with the brand fonts and no extra geometry
Home-made tweens with a cubic curveAn animation libraryFew animations and no dependencies
Keyboard as a single instanced meshOne mesh per key56 keys in a single draw call
Camera with two angles and exponential smoothingOrbit controlsA fixed position with no controls to learn was the idea

Testing and performance

The measurements come from a Playwright script (headless Chromium), the same method used for v0.2:

WhatMeasurement
escritorio-3d.html925 lines · 68.8 kB (21.3 kB with gzip and 18.5 with brotli, which is what actually travels)
three.js r128 (three.min.js)589.3 kB (145.9 kB with gzip and 118.0 with brotli)
Draw calls per frame107
Triangles3,448
Geometries and textures100 and 26
JavaScript memory9.5 MB
Console errors0

Do not trust the frames per second of a headless test. The test browser draws with the processor (there is no graphics card) and gives 2 fps at 1280 × 720 and 10.6 at 640 × 360: they say nothing about a laptop with a graphics card (the v0.2 figures, measured on my laptop, are in chapter 3). What does help are the draw calls and the triangles, which do not depend on the computer.

This is how it was tested:

  • That it works: a Playwright test that opens the file, waits for the room to load, turns on the monitor and checks SergioLearns OS.
  • That it looks right: the screenshots and the clip, recorded with a script that moves the mouse like a person.
  • Accessibility: there was an “Objects” menu with every object and Esc to go back. It worked with the keyboard, but with buttons on screen, which is exactly what the project does not want. It is redone in v0.2.

What went wrong (and how I fixed it)

In the headless test, everything came out black. The room was being drawn correctly, but there was an error screen covering it. The culprit was a CSS rule:

/* The error screen (<div id="fallback" hidden>) had display: grid to center its content… */
#fallback { position: fixed; inset: 0; z-index: 31; display: grid; place-items: center; /* … */ }
/* …and that beat the hidden attribute, which the browser applies with a plain display: none.
   The rule below puts things right: anything with hidden is never shown. */
[hidden] { display: none !important; }

The HTML hidden attribute is not magic: the browser turns it into display: none with the lowest possible priority. Any rule of yours that sets display on that element shows it again. If you use hidden, add [hidden]{display:none!important} to your CSS. It is a real mistake that can happen to anyone who builds websites.

The first lighting was too bright and the room looked like daytime. The renderer exposure (down to 0.9) and the ambient light were lowered, and the walls were darkened to bring back the night-time feel.

The hover glow failed on the discs. A disc has a different material for each face (edge, top and bottom), so its material is a list, not a single one. Now each object clones its materials when it is registered and the glow goes through all of them with mats(m).

How I worked with the AI in this version

  • What I asked for: after dropping the 2.5D sketch, I described what I wanted in 3D: the fixed position of Five Nights at Freddy’s, the shelf above, the drawer below, the whiteboard on the left, the tower on the right, picking up books and flipping their pages, putting discs into the tower for the mock exams.
  • What Claude did: the whole prototype in one conversation, in a single file, and it published it as a claude.ai artifact so I could open it in the browser. It tested it with a headless browser, which is how the black screen bug (the hidden attribute) showed up, and it fixed it.
  • What I did: test it. First, grabbing a disc; what I liked most, the keyboard. And then writing the list of what I wanted to change, which is version 0.2.
  • What I learnt from the process: a quick prototype helps you find out what you want. The list of changes (including removing every button) came from using it.

What I have learnt

  • Two angles are enough to look around, and sine and cosine turn those angles into a point to look at.
  • Exponential smoothing depends on time, not on frames: it behaves the same on any screen.
  • A hinge is an empty group placed where you want something to turn.
  • attach changes the parent without moving the object; add does not.
  • Nested animations work, but they do not scale: with six steps they are already hard to read.
  • Testing a prototype shows you what you want: the list of changes came from using it, not from thinking about it.

The full code

It is on GitHub, in sergiolearns-codigo/proyectos/escritorio/v0.1: a single file, escritorio-3d.html. To open it, download it and double-click it: it opens in your browser. It needs an internet connection the first time, because three.js and the fonts are loaded from the web.

What comes next

After testing v0.1 I made a list of what I wanted to change: more detailed models, no buttons on screen (a manual as a book), more animations (writing on the whiteboard, dragging the discs yourself with the disc drive glowing, pages that do not vanish under the cover, folders you can pick up), closing things with a key, a more polished PC interface, a dot as the pointer, a use for the mug and a transition for arriving at the desk.

Most of that list is version 0.2, and it is chapter 3: grab, turn, drag and drop. There, the room loses all its buttons. See you there.

Keep goingAll Sergio's Room articles

Did this article help you? Here is how you can support SergioLearns →