Sergio’s Room v0.2 — grab, turn, drag and drop: a room with no buttons (a state machine, springs and a page that curls)

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 version 0.2 was to open the drawer and grab a folder. I pulled the handle, the drawer slid out with its weight, went a little too far and came back; I took out the Python folder, carried it to the desk and it opened by itself. Not a single button on screen. That is what v0.1 was missing, and this chapter tells how it is done, with all the code explained line by line. As in the previous version, the idea and the decisions are mine and the code is Claude’s, Anthropic’s AI; at the end I tell you how we worked on this version.

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

In short

In version 0.2 the room is used with your hands. You grab an object with a click and it comes to your hand, where you can turn it to look at it from every side; the E key uses it and Esc puts it back. If you hold the button down and drag, you carry it across the desk: near the place where it fits, that place glows coral and, when you let go, it slots in by itself with its animation.

The discs are the mock exams and go into the disc drive; the USB sticks are the simulators and go into the tower’s port; the folders come out of the drawer; the books open in front of you and their pages curl as you turn them; the whiteboard is written on with a marker; the steam from the mug is Sergio Bot. And if you turn all the way round, behind you there is the door back to the website.

I carry the FP1 disc from the case to the disc drive: the tray slides out and glows, the disc drops with a bounce and the monitor loads the mock exam. Then I pick up the FP1 book, turn it in my hand, open it with E and turn the pages.

What it had to achieve

Remove every button from v0.1 and give everything its own animation: the disc dropping into the tray, the page curling, the marker writing, the drawer with weight. The requirements were written at the start and ticked off at the end; “test” means an automated script that moves the mouse, takes pictures and writes to the console which state the program is in.

RequirementHow it is checkedMet?
A current Three.js as a module, with a fixed versionLoads with no errors in the testYes: 0.186.1
No buttons or interface text visible outside the PCScreenshots of every modeYes
A dot instead of the cursor, which changes shape with the actionScreenshots with hand, fist, turn, marker, page and linkYes
Grab, drag and drop: the zone glows as you get close and the object slots inTest: state ocupado when dropping and monitor afterwardsYes
Discs into the drive (mock exams) and USB sticks into the port (simulators)Tests: the monitor shows the mock exam and the simulatorYes
Inspect mode: click grabs, drag turns, wheel brings closer, E uses, Esc puts backTest: state inspeccion and the book turned in the screenshotYes
Folders that come out of the drawer and open on the deskTest: state carpetaYes
Pages that curl and stay on the leftScreenshot halfway through; the page does not stretch (script)Yes
Whiteboard with marker, eraser and a T/F answer written stroke by strokeTest: free stroke, F written and explanationYes
A mug with Sergio Bot in the steamTest: state bot and an answer in the steamYes, with sample answers
Drawer with weight, lamp switch, steam and dust in the lightScreenshots; the drawer is a springYes
Esc always goes one step backEvery mode goes back to libre with EscYes
A manual on the shelf and LEEME.txt on the PCScreenshot of the open manualYes
Tab goes through the objects, Enter grabs, E uses; announcements for screen readersKeyboard testYes
“Reduce motion”: nothing moves by itselfTwo screenshots at rest: 0 pixels differentYes
Outside the PC, everything is physical, no terminal commandsReview of spines, labels, whiteboard and posterYes
Full turn and a door back to the websiteTest: heading π and the door ajarYes
A way for the recording scripts to aim at the objectsThe scripts aim with itYes
No console errorsThe tests print the errorsYes
The website’s palette and fonts; code without ligaturesCSS reviewYes

Design before code

My decisions at the start

Before programming, Claude asked me a single round of questions, and I answered more than I was asked:

  • The mug opens Sergio Bot in the steam.
  • The whiteboard has free drawing with a marker and a guided answer (you tap T or F and the marker writes it), in the Caveat font.
  • The discs go in a case that opens as you get close and the USB sticks in a pen pot, so the desk does not fill up.
  • An inspect mode like in Resident Evil: the object comes to your hand, you turn it by dragging and its action is on a key.
  • Outside the PC, everything is physical: no terminal commands on books, folders or the whiteboard. The terminal belongs only to the computer.
  • The camera turns all the way round and behind you is the door, the way out to the website.

The Resident Evil part has a reason: I thought of the remakes because I remembered that mechanic of inspecting objects. And when I talked about games where you “grab things”, I was thinking of those mystery games where, when you inspect an object, you find clues, codes… That is what I wanted for the room: objects that hide details.

The new floor plan

Floor plan of the v0.2 roomThe same room with what is new in v0.2: the disc case and the pen pot with the USB sticks on the desk, the green plane where objects are dragged, the camera's full turn and the door on the back wall, moved 1.25 m away from the chair.desk (0.74 m high)shelf (1.63 and 2.01 m)whiteboardmonitorkeyboardtowerdisc drive 1.10 mlampmugdrawer (slides out to 0.30 m)disc caseUSBfull turncamera: eyes at 1.22 mdoor: back to the websitedrag plane (0.765 m)1 mTop viewmeasures from the codeback wall 1.25 mfrom the chair (v0.2)
In green, where an object can be carried; in coral, the full turn and the door.

Compare it with the v0.1 plan. There are three new things: the disc case and the pen pot on the desk, the green plane where objects are dragged (at 0.765 m, slightly above the desktop) and the door, on a back wall that was moved out to 1.25 m from the chair so that it could be seen whole when you turn round.

One single gesture system

The most important drawing of this version was made before writing a single line: what each gesture means at each moment. A click does not do the same thing when your hand is empty as when you are inspecting a book. That is a state machine: the program is always in one state and each gesture takes it to another.

The pointer state machineEight states: free, over, pressed, inspecting, carrying, use, snap in and goes back. From free, the pointer over an object moves to over; pressing moves to pressed; a click leads to inspecting and moving more than 6 pixels leads to carrying. While inspecting, E uses the object and Esc puts it back; while carrying, dropping on the zone snaps it in and dropping far away sends it back to its place, and from there back to free.pointer overpressclickmove > 6 pxEdropEscdrop far awayFREElook · dotOVERglows · handPRESSEDclick or drag?INSPECTINGturn · wheelCARRYINGfollows the pointerUSEits animationSNAP INzone nearbyGOES BACKto its place
The same gesture means something different depending on the state; in coral, what each object does.

Follow a path with your finger: in FREE you move the mouse over a book (OVER: it glows), you press (PRESSED), and if you let go without moving it is a click: INSPECTING. If instead you move more than 6 pixels with the button held down, you go to CARRYING. Same fingers, two results. And leaving is always the same: Esc goes one step back.

The disc’s journey

The disc's journeyFive steps: passing over the case opens the lid, dragging the disc makes it follow the pointer, near the tower the tray slides out and glows, on dropping the disc falls with a bounce and, once inside, the monitor loads the mock exam. Below, the same sequence in code with await.1Over the casethe lid opens2Dragfollows the pointer3Near the towerthe tray comes out4Dropfalls with a bounce5Insidethe monitor loadsawait mueveBandeja(1) → await anim(fall, bounce)→ tray.attach(disc) → await mueveBandeja(0)
Each step waits for the previous one: that is how the code reads, top to bottom.

Each object also has its own states. Some from the design table:

ObjectStatesGesture → animation
Disc caseclosed · openPointer over it → the lid lifts with a bounce
Discin the case · in your hand · carried · in the tray · insideNear the tower → the tray slides out and glows · drop → it falls with a bounce and goes in
Drawerclosed · openClick → it opens on a spring · drag the handle → it follows with its weight
Bookon the shelf · in your hand · openE → it opens in front of you · drag the page → it curls and stays on the left
Doorclosed · ajarClick → it opens a crack with light from the hallway · click on the light → the normal website

Discarded ideas

IdeaWhy not
Discs and USB sticks loose on the desk, as in v0.1With four mock exams and four simulators, the desk filled up
Making the click perform the action directlyYou miss the details; I prefer inspecting and using with E
Terminal commands on the physical objects (ls ~/apuntes on the drawer)Outside the PC, everything belongs to real life
A camera limited to ±60°I want to turn all the way round and see the door
Recognising a hand-drawn T or FUnreliable with a mouse and frustrating when it fails
An animation library (GSAP, Tween.js)The curves we need fit in about 40 lines of our own
Real physics (Rapier, cannon-es)Hundreds of kB, and nothing falls here: things are carried, slot in or go back

Before you start: what is new in JavaScript in this version

v0.2 is written in more modern JavaScript than v0.1. If you are coming from the previous chapter, this is what changes:

What you seeWhat it means
const x = 5; / let y = 0;Variables. const cannot be reassigned (almost everything); let can (counters, states). They replace v0.1’s var
x => x * 2An arrow function: a short function. It is the same as function (x) { return x * 2; }
class Muelle { constructor(…) { … } paso(dt) { … } }A class: a mould for creating objects with their data and functions. new Muelle(0, 70, 11, 1.3) creates one (Muelle means spring)
new Map() · objetos.set(clave, o)A dictionary: it stores values by name
x ?? yIf x does not exist (null or undefined), it is y
new Promise(resolve => …)A promise: an object that says “this will finish later” and lets you know (resolve) when it does
async function f() { await something(); }A function that can wait for a promise with await before moving on to the next line
import * as THREE from 'three';A module: loads a library by name

three.js as a module

In v0.1, three.js was loaded with a <script src>. v0.2 uses the modern way, with an importmap that says where each library comes from:

<script type="importmap">
{ "imports": { "three": "https://cdn.jsdelivr.net/npm/three@0.186.1/build/three.module.js" } }
</script>
<!-- … -->
<script type="module">
import * as THREE from 'three';                                   // "three" = the address in the importmap
const reduced = !!(window.matchMedia && matchMedia('(prefers-reduced-motion: reduce)').matches);  // does the person want less motion?
const $ = s => document.querySelector(s);                         // shortcut: $('#velo') finds the element with id "velo"
LineWhat it does
<script type="importmap">A table of names: when the code says 'three', the browser downloads it from that address, with the fixed version 0.186.1
<script type="module">The program is a module: it can use import
import * as THREE from 'three'Brings in the whole library and calls it THREE (that is why everything starts with THREE.)
matchMedia('(prefers-reduced-motion: reduce)')Asks the system whether the person has turned on “reduce motion”; reduced stores it as true or false
const $ = s => …A one-line arrow function to avoid writing document.querySelector every time

A promise, step by step

It is the most important thing in this version, so it deserves a small example. Imagine three animations that have to run one after another. With promises:

await mueveBandeja(1);    // 1. wait for the tray to slide all the way out…
await anim(420, …);       // 2. …then move the disc…
await mueveBandeja(0);    // 3. …and then slide the tray in

Each await “pauses” the program inside that function until the animation ends, but the rest of the page keeps working (the camera, the steam from the mug…). When the animation finishes, it calls resolve() and the function carries on with the next line. You will see it for real in “Putting a disc in, now as a list”.

How the code is organised

v0.1 was a single 790-line block of JavaScript. v0.2 is written as 12 modules (src/01-nucleo.js … src/12-bucle.js) that a script, construir.js, joins into a single HTML file. Why join them? Because JavaScript modules do not load when you open a file with a double click (file://): Chromium blocks them. This way the code is written tidily and it opens just as easily.

The 12 modules of v0.2At the top, the core every module uses. Below it, data, room and the object registry. In the center, in coral, the gesture state machine, which calls what each object declares and hands the pointer to the plugged-in modes: actions, book, whiteboard and screen. At the bottom, the camera, accessibility and the loop, plus a strip with the bus events.01 corethree.js · anim() with promises · curves · Spring · event bus · storage02 databooks, folders,discs, USB, bot03 roomwalls, desk,tower, door…04 objects · the REGISTRYregistrar(key, {name, meshes, movable,onClick, onDrag…}) · discs, drawer, books…06 gestures · STATE MACHINEfree → pressed → inspecting / carryingtarget zones · go back homehands pointer and keys to the active modemodes and USES (plugged in)07 actions: disc drive, port, drawer, mug…08 book · 09 whiteboard10 screen: monitor, keyboard and OS05 cameraturn = heading + look · focusexponential smoothing11 accessibility · 12 loopTab, aria-live, keys · the frameanimations → springs → camera → rendercalls onClickbus: grab · drop · hover · state · back (modules notify each other without knowing each other)
The gestures do not know which objects exist: they call what each one declares in the registry.
PieceWhat it doesWho it talks to
01 coreEngine, curves, anim() with promises, Muelle (spring) and the event busEveryone
02 dataBooks, folders, mock exams, simulators, manual and bot04, 08, 09, 10
03 roomThe fixed parts: walls, desk, tower, lamp, shelf, door07, 10, 12
04 objectsThe registry: each object says its name and what it does06, 07, 08
05 cameraTurn = heading + look, the focus and the smoothing06 to 09
06 gesturesThe state machine, inspecting, carrying and the zonesCalls what the objects declare
07 actionsDisc drive, port, monitor, drawer, folder, mug, lamp, doorFills in the uses
08 book · 09 whiteboard · 10 screenThe open book, the whiteboard and the monitor with SergioLearns OSPlugged in as modes
11 accessibilityTab, keys and announcements for screen readersThe modes
12 loopThe frame and the start-upEveryone

The golden rule: the gestures do not know which objects exist. To add a new object you do not touch 06-gestos.js: you just register it.

How it is built, piece by piece

Animations that read like a list

In v0.1, chaining animations meant putting one tween inside another. In v0.2, anim() returns a promise: an object that is “fulfilled” when the animation ends. With await in front, the program waits for it to finish before moving on.

// The curves: they take the time progress x (from 0 to 1) and return how far it has moved
const curva = {
  suave: x => (x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2),   // eases in and out (the v0.1 one)
  sale: x => 1 - Math.pow(1 - x, 3),                                        // starts fast and slows down at the end
  retroceso: x => { const c1 = 1.70158, c3 = c1 + 1; return 1 + c3 * Math.pow(x - 1, 3) + c1 * Math.pow(x - 1, 2); }, // overshoots and comes back
  rebote: x => {                                                             // falls and bounces, like the disc in the tray
    const n = 7.5625, d = 2.75;                                              // three ever-smaller parabolas
    if (x < 1 / d) return n * x * x;
    if (x < 2 / d) return n * (x -= 1.5 / d) * x + 0.75;
    if (x < 2.5 / d) return n * (x -= 2.25 / d) * x + 0.9375;
    return n * (x -= 2.625 / d) * x + 0.984375;
  }
};
// anim(duration in ms, what to move, curve) → a promise fulfilled when it ends
function anim(dur, fn, ease = curva.suave) {
  return new Promise(resolve => {
    // with "reduce motion", the animation lasts 1 ms: it arrives in one frame
    const a = { t0: performance.now(), dur: reduced ? Math.min(dur, 1) : dur, fn, ease, resolve, vivo: true };
    anims.push(a);                       // the loop advances it every frame and calls resolve() at the end
  });
}
The four animation curvesFour curves of movement progress against time: smooth starts and stops gently, out starts fast and slows down, back overshoots 1 up to 1.099 and returns, and bounce rises, drops a little and bounces before reaching 1.00.5100.51time (0 to 1)smoothout (slows)back (overshoots)bounceThe dashed line is 1:the back curve reaches 1.099.
Same time, same start and end; what changes is the path.

The values, taken from running these same curves with node:

Timesmoothoutbackbounce
0.10.0040.2710.4090.076
0.30.1080.6570.9070.681
0.50.5000.8751.0880.766
0.70.8920.9731.0800.931
0.90.9960.9991.0140.988

Line by line, the key parts of anim():

CodeWhat it does
curva = { suave: x => …, … }An object with four arrow functions; each one turns time progress into movement progress
ease = curva.suaveIf no curve is given, the smooth one
return new Promise(resolve => { … })Returns a promise and keeps its resolve to call it at the end
dur: reduced ? Math.min(dur, 1) : durWith “reduce motion”, the animation lasts 1 ms
anims.push(a)Adds it to the list; the loop moves it forward every frame and, when it ends, calls a.resolve()

Notice two details. The back curve goes past 1 (it reaches 1.099 at 0.6): that is why it “overshoots and comes back”. And the bounce drops from 0.910 to 0.766 between 0.4 and 0.5: that is the first bounce.

The drawer with weight: a spring

A real drawer does not move at a constant speed: it starts, picks up speed, goes slightly too far and comes back. That is a damped spring, and it is programmed with three numbers: stiffness (k), damping (c) and mass (m).

// Damped spring: F = −k·(x − target) − c·v
class Muelle {
  constructor(x = 0, k = 120, c = 16, m = 1) { this.x = x; this.v = 0; this.obj = x; this.k = k; this.c = c; this.m = m; }
  paso(dt) {
    if (reduced) { this.x = this.obj; this.v = 0; return this.x; }   // reduce motion: it arrives at once
    const sub = Math.ceil(dt / 0.008), h = dt / sub;                   // split the frame into steps of at most 8 ms
    for (let i = 0; i < sub; i++) {
      const a = (-this.k * (this.x - this.obj) - this.c * this.v) / this.m;  // acceleration = force / mass
      this.v += a * h; this.x += this.v * h;                           // velocity first, then position
    }
    return this.x;
  }
}
const cajonM = new Muelle(0, 70, 11, 1.3);    // heavy: low stiffness and a little bounce
CodeWhat it does
constructor(x = 0, k = 120, c = 16, m = 1)Creates the spring: starting position and its three numbers (with default values)
this.v = 0; this.obj = x;It starts still, with the target where it is
Math.ceil(dt / 0.008)How many 8 ms pieces this frame is split into (a 16 ms frame is 2 pieces)
const a = (… ) / this.m;The acceleration: force divided by mass
this.v += a * h; this.x += this.v * h;First the velocity changes and then the position, using the new velocity
return this.x;The new position: the loop uses it to move the drawer (drawer.position.z = cajonM.paso(dt))

The important line is the force. −k·(x − obj) pulls towards the target, harder the further away you are (a stretched spring). −c·v brakes, harder the faster you go (like air or friction). The acceleration is that force divided by the mass, and it is used to update the velocity and then the position.

The drawer on a springGraph of the drawer position against time with the spring of stiffness 70, damping 11 and mass 1.3: it rises from 0, overshoots the 30 centimetre target up to 33.1 at 0.52 seconds and settles back at 30 around 1.4 seconds.0 cm10 cm20 cm30 cm0 s0.5 s1 s1.5 s33.1 cm at 0.52 starget: 30 cmThe springk = 70 c = 11 m = 1.3F = −k·(x − obj) − c·va = F / mζ = 0.577 < 1It overshoots by 3.1 cmand comes back: weight.
That small overshoot and the way back are what make the drawer feel heavy.
TimePositionVelocity
0.1 s6.3 cm100.9 cm/s
0.3 s26.4 cm72.7 cm/s
0.5 s33.1 cm (3.1 too far)3.9 cm/s
0.7 s31.6 cm−11.7 cm/s
1.0 s29.7 cm−0.9 cm/s
1.5 s30.0 cm0.2 cm/s

Why does it overshoot? Because of the damping ratio, ζ = c / (2·√(k·m)) = 11 / (2·√(70 · 1.3)) = 11 / (2 · 9.54) = 0.577. If ζ were 1 or more, it would arrive without overshooting (like a door with a closer); at 0.577, it goes slightly past and comes back. That small overshoot is what the eye reads as “weight”.

For the curious. “Velocity first, then position” has a name: semi-implicit Euler. If you do it the other way round (explicit Euler), the spring gains a little energy on every step and, with long frames, ends up oscillating more and more. That is also why the frame is split into 8 ms steps: the smaller the step, the more stable it is.

And the handle: when you drag it, the drawer does not move, the spring’s target does. The drawer follows it with its delay, and that is why it feels heavy:

alArrastrar: {
  empieza(p) { this.y0 = p.y; this.z0 = cajonM.obj > 0.15 ? CAJON_ABIERTO : 0; },        // where the pull starts from
  mueve(e) { cajonM.obj = clamp(this.z0 + (e.clientY - this.y0) * 0.0016, 0, 0.33); },   // 1 px = 1.6 mm of target, at most 33 cm
  suelta() { if (cajonM.obj > 0.14) abreCajon(); else cierraCajon(); }                    // on release: fully open or fully closed
}
I pull the drawer (it opens with its weight), carry the Python folder to the desk (it opens by itself) and then write on the whiteboard and answer F: the marker writes the letter and the explanation.
Desk v0.2 in 3D: the drawer open with the coloured folders of notes stacked insideDesk v0.2 in 3D: the Python folder of notes open on the desk, with the website address written on it
The open drawer with the seven folders, and the Python one already open on the desk. The labels are on the front edge, which is the part that peeks out.

The camera that turns all the way round

In v0.1 the turn was −mx · 1.05: 60° each way at most. To turn all the way round you need to separate two ideas: where your body is facing (the heading) and how far you turn your head (the look). The final turn is the sum.

Turning all the way: heading plus lookOn the left, the screen with two strips at the edges where the heading turns on its own. On the right, the room from above: a violet arrow for the heading, a coral one for the final turn, which is the heading plus the look, and the door behind the chair.The screenlook = −mx · 1.05(as in v0.1)strips: |mx| > 0.86 → the heading turns on its ownA and D (or ← →) turn it tooFrom abovedeskdoorheadingturnturn = heading + look
The heading is where your body faces; the look is how far you turn your head.
// the heading only turns if the mouse ENTERED the edge while free (otherwise, dropping something near the edge made the room spin by itself)
if (Math.abs(rig.mx) <= BORDE) rig.bordeListo = gesto.estado === 'libre';
const puedeGirar = rig.bordeListo && gesto.estado === 'libre' && !gesto.pulsado && !teclado.activo;
// inside the edge strip (|mx| > 0.86), the heading turns faster the closer the mouse is to the edge
if (puedeGirar && Math.abs(rig.mx) > BORDE) rig.rumbo -= Math.sign(rig.mx) * VEL_BORDE * ((Math.abs(rig.mx) - BORDE) / (1 - BORDE)) * dt;
rig.rumbo -= rig.teclaGiro * VEL_TECLA * dt;            // A and D (or the arrow keys) turn it too
ty = rig.rumbo - rig.mx * 1.05 * rig.sensib;           // turn = heading + look (the v0.1 one)
CodeWhat it does
rig.bordeListo = gesto.estado === 'libre'While the mouse is outside the edge, it notes whether you are free; that is how it knows you entered the edge while free
puedeGirar = … && !gesto.pulsado && !teclado.activoIt only turns if you are not doing something else with the mouse or using the keyboard
rig.rumbo -= Math.sign(rig.mx) * VEL_BORDE * (…) * dtTurns the heading towards the mouse side, faster the closer to the edge, multiplied by dt so it behaves the same at any frame rate
rig.rumbo -= rig.teclaGiro * VEL_TECLA * dtteclaGiro is −1, 0 or 1 depending on whether you press A, nothing or D
ty = rig.rumbo - rig.mx * 1.05 * rig.sensibThe final turn: heading + look; sensib drops to 0.45 while you are carrying something

With BORDE = 0.86 and VEL_BORDE = 1.6 rad/s, the “strength” goes from 0 to 1 across the edge strip:

Mouse (mx)StrengthTurning speed
0.860.000 °/s
0.900.2926.2 °/s
0.950.6458.9 °/s
1.001.0091.7 °/s

The 0.95 row worked out: strength = (0.95 − 0.86) / 0.14 = 0.64; speed = 1.6 · 0.64 = 1.03 rad/s, which is 1.03 · 57.3 ≈ 58.9 °/s. With the mouse right at the edge, a full turn (360°) takes about 4 seconds.

For the curious. When you press Esc, the camera goes back to looking at the desk. But if you have turned round twice, the heading is 4π, and animating it down to 0 would spin you twice the other way. rumboACero() first subtracts the whole turns (Math.round(heading / 2π) · 2π) so it goes back the short way.

Desk v0.2 in 3D: the door behind the chair, which leads back to the website
Behind the chair, the door: it opens a crack with light from the hallway, and that light leads to the normal website.

A registry, a state machine and a bus

The heart of this version is three small pieces. The first, the registry: each object signs up with its name, its meshes and what it does.

/* registrar(key, {nombre, mallas, raiz, movil, alClic, alUsar, alArrastrar, insp, activo}) */
function registrar(clave, o) {
  o.clave = clave;
  o.activo = o.activo || (() => gesto.estado === 'libre');   // by default, it can only be touched while free
  objetos.set(clave, o);
  o.mallas.forEach(m => {
    m.userData.clave = clave; pickables.push(m);               // the ray will know which object each mesh belongs to
    // each object clones its materials: that way its coral glow does not spread to others sharing the material
    m.material = Array.isArray(m.material) ? m.material.map(x => x.clone()) : m.material.clone();
  });
  if (o.raiz) guardaCasa(o);                                   // records its "home": where it goes back to with Esc
  return o;
}
CodeWhat it does
o.activo = o.activo || (() => gesto.estado === 'libre')If the object does not say when it can be touched, it can only be touched while free
objetos.set(clave, o)Stores it in the registry by name ('cajon', 'disco-fp1'…)
m.userData.clave = clave; pickables.push(m)Each mesh records which object it belongs to, and joins the list of things the ray can touch
m.material.clone()Each object has its own materials, so its glow does not spread
guardaCasa(o)Records its parent, position and rotation: its “home”, where it goes back to

The second, the state machine. The state is a string (libre, inspeccion, llevar, lectura, pizarra, ocupado…) and each special mode is plugged in with modo():

const gesto = { estado: 'cargando', pulsado: null, hover: null, obj: null, arrastre: null };
const modos = {};
function modo(nombre, h) { modos[nombre] = h; }        // a mode = what to do on press, move, release, keys and Esc
function cambia(estado) { gesto.estado = estado; rig.bordeListo = false; bus.emit('estado', estado); actualizaPunto(); }

When you press the mouse button, the gesture system looks up the mode for the current state and hands it the event. The open book, the whiteboard and the mug know nothing about each other: each one is a mode. And ocupado (busy) is a special state that does nothing: it blocks input while an animation lasts, so you cannot pick up a book while the disc is going in.

The third, the event bus: modules notify each other without knowing each other.

const bus = {
  oy: {},                                                             // who listens to each event
  on(ev, fn) { (this.oy[ev] = this.oy[ev] || []).push(fn); },         // "let me know when ev happens"
  emit(ev, dato) { (this.oy[ev] || []).forEach(fn => fn(dato)); }     // "ev has happened": notify everyone
};

The disc case listens to hover to open when you get close, without the gesture system knowing the case exists. It is the same pattern as browser events (addEventListener), done in five lines.

Inspecting: turning the object in your hand

When you grab an object, it comes in front of the camera and the room darkens around it. Dragging turns it. It sounds simple, but there is a catch: turn it about which axes?

Turning the object in camera spaceOn the left, the screen with its vertical and horizontal axes: dragging sideways turns about the vertical one and dragging up or down about the horizontal one. On the right, the object's orientation as a product of three rotations: the camera, the person's turn and the base pose; each drag is multiplied on the left of the person's turn.your screenvertical axishorizontal axisdrag → → turns about the verticaldrag ↑ ↓ turns about the horizontalOrientation of the object in your handcamera·your turn·base poseEach drag multiplies a small turn on theLEFT of "your turn" (premultiply): it is appliedon the screen axes, not on the object's.On the right (multiply) it would turn about theobject's axes, which change with every turn.
That is why "drag right" turns right, however the object is facing.
function poseInspeccion(o, salidaPos, salidaQuat) {
  camera.getWorldDirection(_v);                                    // where the camera is looking
  salidaPos.copy(camera.position).addScaledVector(_v, insp.dist);  // the object, "dist" metres in front (the wheel changes it)
  _q2.setFromEuler(o.insp.rot);                                    // its base pose: how it is shown at first
  salidaQuat.copy(camera.quaternion).multiply(insp.q).multiply(_q2); // camera · your turn · base pose
}
function giraInspeccion(dx, dy) {
  // turning in camera space: dragging right turns about the SCREEN's vertical axis
  _q.setFromAxisAngle(new THREE.Vector3(0, 1, 0), dx); insp.q.premultiply(_q);  // premultiply = on the left
  _q.setFromAxisAngle(new THREE.Vector3(1, 0, 0), dy); insp.q.premultiply(_q);
}
CodeWhat it does
camera.getWorldDirection(_v)Stores in _v where the camera is looking (an arrow of length 1)
salidaPos.copy(camera.position).addScaledVector(_v, insp.dist)The position in your hand: from the eyes, dist metres in that direction
_q2.setFromEuler(o.insp.rot)The object’s base pose (for example, the book with its cover facing you)
camera.quaternion · insp.q · _q2The final rotation: the camera’s, then yours, then the base pose
setFromAxisAngle(new THREE.Vector3(0, 1, 0), dx)A rotation of dx radians about the vertical axis
insp.q.premultiply(_q)Adds it to your turn, on the left

3D rotations are stored as quaternions (four numbers that represent a rotation) and they are combined by multiplying them. The order matters: multiplying on the left (premultiply) applies the new turn after the previous ones, on the fixed axes of the screen. Multiplying on the right would apply it on the object’s axes, which are already turned: after half a turn, “drag right” would turn it left.

For the curious. Why quaternions and not three angles? With angles (Euler), after turning 90° about one axis, the other two can line up and you lose a degree of freedom: the famous gimbal lock. Quaternions do not have that problem and they also interpolate nicely with slerp, which is what the animation uses so the object flies smoothly into your hand.

Desk v0.2 in 3D in inspect mode: the FP1 book in the hand, turned, with the room darkened behind it
The FP1 book in your hand, turned: the room darkens so you focus on the object.

Putting a disc in, now as a list

Compare with v0.1: six levels of tween inside tween. With promises, the same sequence reads top to bottom:

async function meteDisco(o) {
  cambia('ocupado'); gesto.obj = o;                        // block input while it lasts
  if (torre.disco && torre.disco !== o) await sacaDisco(false);   // if there was another one, it comes out first
  if (torre.bandeja < 1) await mueveBandeja(1);            // 1. the tray slides out
  scene.attach(o.raiz);
  tray.updateMatrixWorld(true);
  // two points in tray coordinates, converted to the world: 5 cm above it and inside the slot
  const encima = new THREE.Vector3(0, 0.05, 0).applyMatrix4(tray.matrixWorld), dentro = new THREE.Vector3(0, 0.006, 0).applyMatrix4(tray.matrixWorld);
  const p0 = o.raiz.position.clone(), q0 = o.raiz.quaternion.clone(), q1 = new THREE.Quaternion();
  await anim(420, e => { o.raiz.position.lerpVectors(p0, encima, e); o.raiz.quaternion.slerpQuaternions(q0, q1, e); }, curva.suave); // 2. it flies above, straightening up
  await anim(420, e => o.raiz.position.lerpVectors(encima, dentro, e), curva.rebote);   // 3. it falls and bounces
  tray.attach(o.raiz);                                     // 4. from here on it moves with the tray
  await mueveBandeja(0, 460);                              // 5. it goes in
  torre.disco = o; gesto.obj = null; $('#velo').classList.remove('on');
  pantalla.pon('simulacro', o.datos); parpadeoLed(1400);   // 6. the monitor loads the mock exam and the LED blinks
}
CodeWhat it does
async function meteDisco(o)async: it can use await inside (meteDisco means “put the disc in”)
cambia('ocupado')The state machine switches to “busy”: no other gestures while it lasts
if (torre.disco && torre.disco !== o) await sacaDisco(false)If there was another disc inside, it takes it out first, and waits
.applyMatrix4(tray.matrixWorld)Converts a point from tray coordinates (5 cm above, 6 mm inside) to world coordinates
lerpVectors(p0, encima, e)Blends two positions: with e = 0 it is at p0; with e = 1, at encima (above)
slerpQuaternions(q0, q1, e)The same with the rotation: the disc straightens up as it flies
curva.reboteThe fall uses the bouncing curve
pantalla.pon('simulacro', o.datos)The monitor shows that disc’s mock exam

Each await waits for the line before it to finish. The code says exactly what you see, in the same order. The attach in step 4 is the same trick as in v0.1.

Desk v0.2 in 3D: the monitor shows the FP1 mock exam after its disc goes into the towerDesk v0.2 in 3D: a USB stick plugged into the tower and the monitor showing the preview of the scheduling simulator
With the disc inside, the monitor loads the FP1 mock exam and says whether it is published yet. With a USB stick in the port, it shows the simulator preview.

Target zones: “close” is measured on screen

While you carry a disc, the program has to know whether you are close to the disc drive to make it glow. The first attempt measured that distance on the desk plane: where the mouse ray hits the desk compared with where the drive is. And the disc never fitted.

"Close" on the desk versus "close" on screenSide view along the ray that leaves the eyes, at 1.22 metres, and passes through the disc drive slot, at 1.10 metres and 1.2 metres away. The ray drops so little that it does not hit the desk plane until 4.4 metres, behind the tower and the wall. That is why, measured on the desk, the drive was never close; measured on screen, the mouse and the slot are at the same point.desk plane (0.765 m)towerwalleyes 1.22 mslot 1.10 mthe ray reaches the desk at 4.4 m(3.8 times further than the slot)On the desk: never "close"On screen: mouse and slot coincideSide view along the ray (horizontal distance from the eyes).
From the chair, the slot and the red point are on the same line: on screen they coincide.

The reason is geometric. The slot is 1.10 m high and your eyes are at 1.22 m: the ray from your eyes to the slot drops only 12 cm over 1.17 m. To drop down to the desk (0.765 m) it has to travel 3.8 times that distance: it hits the desk at 4.4 m, far behind the tower and outside the room. When you aim at the slot, “your point on the desk” is miles away from the slot.

The fix is to measure where you measure: on screen. The zone is projected onto the screen and compared with the mouse:

// close = close ON SCREEN: compare where the mouse points with where the zone appears
_v.copy(z.punto).project(camera);                                  // the zone's 3D point → screen coordinates (−1 to 1)
const d = Math.hypot((ndc.x - _v.x) * camera.aspect, ndc.y - _v.y); // distance to the mouse; · aspect so it is a circle, not an ellipse
z.prox = _v.z < 1 ? clamp(1 - d / z.radio, 0, 1) : 0;              // 1 = right on it, 0 = outside the radius (or behind the camera)
CodeWhat it does
_v.copy(z.punto).project(camera)Projects the zone’s 3D point (the slot) onto the screen: x and y from −1 to 1, like the mouse
(ndc.x - _v.x) * camera.aspectThe horizontal distance, corrected for how wide the screen is (otherwise the circle would be squashed)
Math.hypot(a, b)The straight-line distance: √(a² + b²)
_v.z < 1 ? … : 0If the zone is behind the camera, it does not count
clamp(1 - d / z.radio, 0, 1)1 if the mouse is right on it, 0 at a distance of radio or more, and in between otherwise

With that closeness, prox, three things happen at once: the zone glows more (1.4 + 2.4·prox, with a small pulse), the object rises towards the zone’s height and turns the way it is going to fit. So you can see it “is going to go in” before you let go.

“Close” in 3D depends on where you are looking from. If what matters is where the person is pointing, measure on screen (with project()), not in the world. It took a failed test to realise it, and it is the most useful mistake of this version.

There was a second part to the same bug: while you carried the disc, it hid behind the tower (and inside it). Now the plane it is dragged on has limits: always in front of the tower and the monitor.

The page that curls

In v0.1, turning a page meant rotating a flat sheet, which also vanished under the cover. In v0.2 the page bends as it turns, and does not stretch. The trick is to build it as a chain of 24 equal pieces, each one at a slightly different angle:

// a(s) = θ − β·sin(πp)·(s/W)^1.5   (s = distance from the spine, W = page width, p = turning progress)
const s = (i + 0.5) * ds, a = th - beta * Math.sin(Math.PI * p) * Math.pow(s / W, 1.5);
x += Math.cos(a) * ds; z += Math.sin(a) * ds;   // move one piece of length ds in direction a

Read it like this: θ = π·p is the angle at the root, next to the spine, which goes from 0° to 180°. The second term delays the tip: sin(πp) is 0 at the start and at the end (flat page) and 1 halfway through (maximum curl), and (s/W)^1.5 makes the delay grow towards the tip. Since every piece has the same length (ds), the whole page is always the same length: it does not stretch.

The page that curls as it turnsFive positions of the same page drawn with the book model: flat on the right (p = 0), curled at a quarter, with the tip lagging far behind halfway, curled at three quarters and flat on the left (p = 1). All of them are 15.800 centimetres long.spinep = 0p = 0.25p = 0.5p = 0.75p = 1a(s) = θ − β · sin(πp) · (s/W)^1.5Every curve is 15.800 cm long: the page bends, it does not stretch.
Look at the middle one: the root is already upright and the tip is still behind.
Progress pRootTipTip xTip zLength
00°0°15.80 cm0.00 cm15.800 cm
0.2545°8.5°13.38 cm7.86 cm15.800 cm
0.590°38.4°5.35 cm14.26 cm15.800 cm
0.75135°98.5°−7.86 cm13.38 cm15.800 cm
1180°180°−15.80 cm0.00 cm15.800 cm

These numbers were checked with node before being used. The last column is the proof: 15.800 cm throughout the turn. Halfway (p = 0.5) the root is already upright (90°), but the tip is at 38.4°: 0.9 · 1 · 1 = 0.9 rad less, which is 51.6° behind.

Desk v0.2 in 3D: an open book showing the contents page, with a page halfway through turningDesk v0.2 in 3D: an open book in front of the camera with a fact about the website and the link to the subject
A page halfway through its turn and the book open as if on a lectern. The blocks of pages change thickness as you go.

For the curious. If you grab the page by a corner, β changes with the height of each row (1 + 0.55·grip·y) and the page bends diagonally. And the back of the page uses the same texture mirrored (repeat.x = −1), so there is no need to draw each page twice.

The whiteboard, the mug and the keyboard

The whiteboard has three layers that are combined into one texture: the background (calendar, countdown and question of the day), what you write freehand and the answer. That way the eraser rubs out your writing without rubbing out the calendar. When you tap T or F, the marker goes to the box and writes the letter stroke by stroke: each letter is a list of points (a polyline) that is followed along its length.

Desk v0.2 in 3D: the whiteboard up close, handwritten with the calendar, the countdown and the answered question of the day
The whiteboard up close, in the Caveat font: the calendar, the countdown to FP1 and the question of the day answered with an F.

The mug is grabbed like any other object; with E you bring it closer, the steam thickens and forms the conversation with Sergio Bot. For now it replies with sample answers: the real bot lives on the website, with its key and its quota, and the prototype is not there yet.

Desk v0.2 in 3D: the coral mug in the hand, in inspect modeDesk v0.2 in 3D: the steam from the mug forms the conversation with Sergio Bot
The mug in your hand and, with E, Sergio Bot in the steam.

Accessibility with no visible buttons

Removing the buttons cannot leave out people who use the keyboard or a screen reader. The solution is an invisible list: one button per object (36), with its name, which only appears when it gets the focus. Tab goes through the objects, the camera looks at each one, it glows and its name is announced; Enter grabs it and E uses it. The first Tab shows “Go to the normal website, without 3D”.

Desk v0.2 in 3D with the keyboard: the Tab key has reached the manual on the shelf and its name is shownDesk v0.2 in 3D: the shelf manual open, with the "Look" and "Grab and use" pages
With Tab, the camera looks at the object and its name appears. The manual on the shelf explains the gestures and the keys.

A recording caught a serious bug: when leaving the mug, the keyboard focus jumped back to the top of the page, and the next Tab + Enter took you out of the room. The function that fixes it:

// when leaving a mode that types (mug, keyboard), the focus goes back to its object in the list (if the keyboard was in use)
// or to the canvas, so the next Tab carries on through the objects and does not jump to the link at the top
function devuelveFoco(clave) {
  const b = teclado.activo && nav.querySelector('[data-clave="' + clave + '"]');
  if (b) b.focus({ preventScroll: true }); else canvas.focus({ preventScroll: true });
}

The decisions

DecisionAlternativesWhy this one
No buttons; a dot instead of the cursor; a manual inside the world (mine)Buttons as in v0.1The clean experience I imagined
Inspect mode like in Resident Evil (mine)Making the click perform the actionDiscovering details in the objects
Outside the PC everything is physical (mine)A terminal look everywhereThe terminal belongs to the virtual world
Full turn and a door behind (mine)A ±60° turnIt is the way out and the start of the v0.5 arrival
Three.js 0.186.1 as a module, with importmapr128 (v0.1); 0.187.0A current version; 0.187.0 was five days old and we use one at least two weeks old
12 modules joined into one HTMLSeveral .js files served separatelyModules do not load from file://
State machine + registry + busLots of scattered ifsOne place for each gesture; objects that do not know each other
anim() with promisesNested tweensSequences read top to bottom
Home-made curvesGSAP, Tween.jsAbout 15 lines, no dependencies or licences
Spring (semi-implicit Euler, 8 ms steps)A fixed curve; a physics engineWeight without hundreds of kB
Zones measured on screenOn the desk planeOn the desk it never fitted
The page as a chain of 24 piecesA flat sheet; a shaderIt does not stretch and it is easy to explain
An invisible list for TabA visible menuKeyboard and screen reader with no interface on show

Testing and performance

All measured with scripts (Playwright and node):

Whatv0.1v0.2
escritorio-3d.html925 lines · 68.8 kB2,149 lines · 142.9 kB
Compressed (brotli)18.5 kB37.9 kB
three.js compressed (brotli)118.0 kB (r128)306 kB (0.186.1: module + core)
Draw calls107197
Triangles3,4484,194
Time to ready (headless, 1280 × 720)—1.8 s
Console errors00

Smoothness: on my laptop, v0.2 runs at about 60 frames per second, sometimes dropping to 57. The headless browser used in the tests, which draws with the processor, gives between 4 and 11: that is why real measurements have to be taken on a real computer.

197 draw calls is a lot for only 4,194 triangles: every box is a mesh and every mesh is a call. That gets fixed in v0.4, when the meshes are merged into Blender models.

Accessibility:

CheckResult
First Tab“Go to the normal website, without 3D”
Objects in the Tab order36, each with its name
Screen readersAn aria-live region with the name and what to do
“Reduce motion”Two screenshots at rest 1.5 s apart: 0 pixels different
ContrastEvery text passes AA (4.5:1); the tightest, the whiteboard’s red marker, 4.51:1

What went wrong (and how I fixed it)

  • The disc never fitted. Closeness was measured on the desk and the disc drive is 34 cm higher. Now it is measured on screen (you saw it above) and the disc never goes behind the tower.
  • The room spun by itself when you dropped a disc into the tower: the mouse was left on the right edge, which is the turning zone. Now the edge only turns if the mouse enters it while free.
  • A comment ate half a line. When a // comment was added at the end of the line that placed each folder, what came after it on that same line (drawer.add(g)) got commented out: the folders were not in the drawer and putting one back crashed the program (Cannot read properties of null). The clip recording caught it.
  • Tab took you out of the room when leaving the mug (fixed with devuelveFoco). A recording caught that one too.
  • The whiteboard wrote mirrored. It is rotated 90° and the canvas coordinate grows towards −z; the first calculation had the sign the wrong way round.
  • The pages were hard to read: with the hand light, the paper came out almost white and the text grey. The light was lowered and the text made darker and bolder.
  • The mug’s text came out backwards (a mirrored texture that was not needed) and what you typed got scrambled with accents and “¿”. Now normal letters are picked up from the key press and composed ones from the input event.
  • The folder labels could not be seen: they were in the middle of the cover, hidden by the folder on top. Now they are on the front edge.

A // at the end of a line comments out everything after it on that line, even if it is code. If you write several statements on one line, put the comment on the line above. This bug gave no error on load: only when putting a folder back.

And one thing that is not a code bug, but a content one: the objects’ trivia fell short. It is too shallow, and I want it to tell real details about the website. I am noting it down for the next version.

How I worked with the AI in this version

  • What I asked for: the list I wrote after testing v0.1 (no buttons, a manual inside the world, discs you drag, pages that do not vanish, folders you can pick up, a use for the mug…) and, in the round of questions, my decisions: the mug with Sergio Bot, the whiteboard, the disc case and the pen pot, inspecting like in Resident Evil, everything physical outside the PC and the door behind you.
  • What Claude did: before coding, it drew the sketches and wrote the requirements; then, the 12 modules; and it tested everything with scripts that move the mouse, write to the console which state the program is in and record the clips. Three of this version’s bugs were caught by those recordings. At the end, it measured the performance and documented everything for this chapter.
  • What I did: test it. First, opening the drawer and grabbing a folder. Measuring the frame rate on my laptop (about 60). And noting what did not convince me: the objects’ trivia is too shallow, and I wrote a new list of improvements that became version 0.2.1.
  • What I learnt from the process: the more concrete the decision, the better the result. “Let me inspect it like in Resident Evil” says much more than “let me pick things up”.

What I have learnt

  • A state machine brings order to an interface with no buttons: each gesture means something different depending on the state, and Esc gets you out by itself.
  • Promises turn a multi-step animation into a list that reads top to bottom.
  • A spring gives weight without a physics engine: stiffness, damping and mass.
  • “Close” is measured on screen, not in the world, when what matters is where the person is pointing.
  • Recording is testing: three bugs in this version were caught by the recording scripts, not by eye.
  • With AI, deciding well is half the work: concrete decisions turn into code much better than vague ideas.

The full code

On GitHub, in sergiolearns-codigo/proyectos/escritorio/v0.2: escritorio-3d.html (the prototype ready to open with a double click, with internet for three.js and the fonts), the src/ folder with the 12 modules (edit there) and construir.js, which joins them (node construir.js).

What comes next

Version 0.3 brings SergioLearns OS: a computer inside the screen with its own system, its own cursor and its apps, video games that teach something from the degree and achievements as discoveries (the objects’ clues, like the back of a disc or the bottom of the mug, will finally unlock something). Before that comes v0.2.1, with fixes (the disc you carry looks small, for example) and a new room: a window behind the monitor showing the time in the Canary Islands, the shelf on the right-hand wall and more furniture. Both are told together in chapter 4.

It is all in chapter 4: from a fixed camera to a room you walk around (and play), which goes up to v0.2.5. Meanwhile, the Sergio’s Room report has the status of the whole project.

Keep goingAll Sergio's Room articles

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