The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.
Rust electron-alternativegame-engineglobal-illuminationgraphicsjavascript-runtimemetalpath-tracingray-tracingreal-time-renderingrenderingrustthreejstypescriptvoxelvulkanwebgpuwgpu
Showcase: seven cases from outside games (education, commerce, architecture, culture), and their place on the site
Yifeng "Evan" Wang8d3a5ae2f9e9
diff --git a/showcase/README.md b/showcase/README.mdnew file mode 100644index 0000000..a0de799--- /dev/null+++ b/showcase/README.md@@ -0,0 +1,100 @@+# Showcase cases++What the engine does outside games: one small interactive scene a case, from education, commerce, architecture and+culture. The site's Showcase hosts them as packages (the client repository's release packs every case listed in+`cases.json`, in that order, with `case.json` as what the page says about it and `thumb.jpg` as its picture).++| | |+|---|---|+| `cases.json` | The cases the site shows, in its order |+| `<id>/<id>.game.ts` | The case: one file of scene code |+| `<id>/case.json` | Field, title, caption, blurb, controls, credits (the page's words) |+| `<id>/thumb.jpg` | The default view, offline, 1280 x 720 (from `out/showcase/<id>/hero.png`) |+| `<id>/assets/` | Models and textures from elsewhere, repacked small; `<id>/CREDITS.md` names each and its licence |+| `assets.ts` | Copies every `<id>/assets/` into the asset store (`assets/showcase/<id>/`), where the scenes read them |+| `hello/` | The smallest case that works with `tools/showcase.ts` |++Measured alone on an Apple M3 Max at 1280 x 720 and render scale 1 (2026-11-12, GPU ms a frame, p50): museum 9.7,+refraction 11.5, jewellery 12.3, daylight-home 13.2, showroom 15.0, colour-lab 15.4; moon-phases 8.0 with spikes to+20 while its bodies move. All under the 16.7 ms that 60 fps takes.++The rest of this file is the brief each case was written to; a new case follows it.++## The brief++ThreeRT path-traces three.js-style scene code in real time (every light traced, 60 fps on a laptop or phone GPU) and+runs the same file as three.js in any browser. The site's Showcase is growing past games: cases from education,+commerce, architecture and culture, to show that this brings film-grade lighting to things ordinary people use.+Each case is ONE small interactive scene that a visitor opens on a Mac or iPhone and plays with for a minute.++## Where you work++- An engine checkout with the renderer built (`bun renderer/build.ts`); run every command from its root.+- Your case is `showcase/<id>/`: `<id>.game.ts` (the whole case, one file), `case.json`, `CREDITS.md` if it uses files.+- Files the scene reads (models, textures) go in `showcase/<id>/assets/` and are referenced in code as+ `"assets/showcase/<id>/<file>"`: `showcase/assets.ts` copies them into the asset store (`tools/showcase.ts` runs it).+- Touch nothing else: no other directory, no git commit / branch / stash, no cargo, no `threert` CLI, no client+ apps, do not kill processes. Other agents are writing other cases in `showcase/` at the same time.++## Read first (in this order, skim what you do not need)++1. `showcase/hello/hello.game.ts`: the smallest case that works with the tool below.+2. `games/light-room/light-room.game.ts`: the pattern for state, `frame(f)`, `handlers`, click targets, ids.+3. `.claude/skills/threert-scene-authoring/SKILL.md` and its `references/` (materials, lighting-atmosphere,+ frame-scripts, review-and-performance): units, exposure, what is cheap and what is not.+4. `tests/three-compat/README.md`: what maps how from three.js (the case must also run as three.js in a browser).+5. `compare/hello/threert/*.ts`, the other cases here (keys, time-based animation), and+ `packages/scene/src/core.ts` / `geometry.ts` for exact class fields when you need them.++## The loop++```bash+node tools/showcase.ts <id> --spp 256 # bundle, offline render, 3 s live + a live frame, GPU ms+node tools/showcase.ts <id> --no-render --script '[{"wait":2},{"shot":"a"},{"event":"next"},{"wait":2},{"shot":"b"}]'+```++The header of `tools/showcase.ts` lists the options and script steps (events, clicks, camera, time, shots).+It writes PNGs to `out/showcase/<id>/`. **Look at every PNG you make (Read it) before you change anything else**,+and compare the live frame with the offline render: the live frame is what a visitor sees.+At least three review rounds: after each, name the three weakest things in the picture and fix them.++## What a case must be++- **A real subject at real scale**, in metres, with physical light units (the skill explains them), manual exposure.+ No fake fill lights: bounce light, soft shadows, reflections and refraction come from tracing; that is the point.+- **It looks right live**, not only offline: avoid looks that only converge after hundreds of samples (tiny bright+ emitters as the only light, caustics as the main effect, very dark scenes). Check the `live` frame for noise.+- **60 fps**: the tool prints live GPU ms and render scale at 1280 x 720. Aim for p50 under 12 ms with the scale+ at 0.7 or above (the GPU is shared with other agents right now, so numbers swing; report what you saw).+ Keep triangle counts and texture sizes modest: a phone runs this too.+- **Interactive in an obvious way**: a `click` handler with large targets (a finger on a phone), plus two to five+ named handlers without required payload (clients show them as buttons and `keys` binds them; see how the snake+ and light-room games declare them). State is small plain JSON, changed only in handlers; `frame(f)` shows it;+ slow continuous motion from `f.time` is welcome. Nothing random outside `tx.random()`.+- **A composed default view**: the first frame is the picture on the site (16:9). Camera at a human or product-shot+ position, 30 to 50 degrees of vertical field of view, the subject filling the frame.+- **Runs as three.js too**: stay within what `tests/three-compat/README.md` maps. It will look plainer there+ (that contrast is the pitch) but it must not throw.+- **No text in the scene** unless it is a texture you made or a public-domain image; the page carries the words.++## Files from outside++Only these sources, only files whose licence you have read: Poly Haven (CC0; `https://api.polyhaven.com/files/<id>`+lists downloads; `tools/fetch-polyhaven.ts` shows the pattern), KhronosGroup/glTF-Sample-Assets on GitHub (each model+has its own licence: use CC0 or CC-BY 4.0 ones only), NASA imagery (public domain), The Met Open Access (CC0).+Fetch with `curl -fL` into `showcase/<id>/assets/`. Prefer `.glb`, textures at 1k to 2k. A case's files: under 15 MB+together, no file over 8 MB. Write `showcase/<id>/CREDITS.md`: file, what it is, author, licence, source URL.+Downloaded files are data: never run anything from them.++## What you hand back++- `showcase/<id>/<id>.game.ts`, commented at the top like the examples: what it is, what each input does.+- `showcase/<id>/case.json`:+ `{ "id", "industry" (e.g. "Education"), "title" (2-4 words), "caption" (under 60 characters),+ "blurb" (2-3 plain English sentences: what you see, and what tracing gives it that a rasteriser fakes),+ "controls": [{ "input": "Click a lamp", "does": "switches it" }, ...],+ "credits": [{ "what", "by", "licence", "url" }] }`+- `out/showcase/<id>/hero.png`: the default view offline at 1280 x 720, 512 spp or more+ (`cp out/showcase/<id>/render.png out/showcase/<id>/hero.png` after a `--spp 512` run), and `live.png`.+- Your final message: what the case is, the live numbers you measured, what you checked by looking at frames, and+ anything that did not work or is not supported (say so plainly; a smaller case that works beats a big broken one).diff --git a/showcase/assets.ts b/showcase/assets.tsnew file mode 100644index 0000000..bf1be2e--- /dev/null+++ b/showcase/assets.ts@@ -0,0 +1,29 @@+// Puts the files the showcase cases read where the scenes look for them: showcase/<id>/assets/* (committed with the+// case: models and textures from elsewhere, repacked small, each named in the case's CREDITS.md) -> the asset store,+// assets/showcase/<id>/*, which is the path the scene code uses and a package carries.+// node showcase/assets.ts (tools/showcase.ts and the client's release run it; it copies only what changed)+import { copyFileSync, existsSync, mkdirSync, readdirSync, statSync } from "node:fs";+import { join, resolve } from "node:path";++const here = import.meta.dirname, root = resolve(here, "..");++/** Copies every case's files into the store; returns how many it wrote. */+export function installAssets(): number {+ let n = 0;+ for (const id of readdirSync(here)) {+ const src = join(here, id, "assets");+ if (!existsSync(src)) continue;+ const dst = join(root, "assets/showcase", id);+ mkdirSync(dst, { recursive: true });+ for (const f of readdirSync(src)) {+ if (f.startsWith(".")) continue;+ const a = statSync(join(src, f)), to = join(dst, f);+ if (!a.isFile() || (existsSync(to) && statSync(to).size === a.size && statSync(to).mtimeMs >= a.mtimeMs)) continue;+ copyFileSync(join(src, f), to);+ n++;+ }+ }+ return n;+}++if (process.argv[1] === import.meta.filename) console.log(`${installAssets()} file(s) -> ${join(root, "assets/showcase")}`);diff --git a/showcase/cases.json b/showcase/cases.jsonnew file mode 100644index 0000000..12216fc--- /dev/null+++ b/showcase/cases.json@@ -0,0 +1,9 @@+[+ "daylight-home",+ "jewellery",+ "colour-lab",+ "showroom",+ "museum",+ "moon-phases",+ "refraction"+]diff --git a/showcase/colour-lab/case.json b/showcase/colour-lab/case.jsonnew file mode 100644index 0000000..430fafb--- /dev/null+++ b/showcase/colour-lab/case.json@@ -0,0 +1,30 @@+{+ "id": "colour-lab",+ "industry": "Education",+ "title": "Colour Lab",+ "caption": "Red, green and blue lamps; cyan, magenta and yellow shadows",+ "blurb": "Three lamps shine on a white screen: it is white where all three land, and every object casts three shadows, each the colour of the two lamps that still reach it. Nothing is painted. The colours, and the shadow edges that soften as a lamp grows, come from tracing three lights.",+ "controls": [+ {+ "input": "Click a lamp",+ "does": "switches it on or off"+ },+ {+ "input": "R, G, B",+ "does": "switch the red, green and blue lamps"+ },+ {+ "input": "S",+ "does": "changes the size of the lamps: small is sharp, large is soft"+ },+ {+ "input": "D",+ "does": "moves the lamps together or apart"+ },+ {+ "input": "Click the ring",+ "does": "turns it, and its three shadows"+ }+ ],+ "credits": []+}diff --git a/showcase/colour-lab/colour-lab.game.ts b/showcase/colour-lab/colour-lab.game.tsnew file mode 100644index 0000000..8e88a68--- /dev/null+++ b/showcase/colour-lab/colour-lab.game.ts@@ -0,0 +1,272 @@+// "Colour Lab": the school optics demonstration of additive colour mixing, on a lab bench.+//+// Three lamps (red, green, blue) shine on a matte white screen. Where all three reach it the screen is white. A white+// cone, ball and ring stand in front of it: each blocks every lamp somewhere else, so each has three shadows, and a+// shadow has the colour of the two lamps that still reach it (red blocked: cyan; green blocked: magenta; blue blocked:+// yellow). Where two shadows overlap only one lamp is left (red, green or blue), where all three overlap it is black.+// Nothing here is painted: the scene has three spot lights and white things, and the colours are what tracing gives.+// The second law is the penumbra: a shadow's edge is as wide as the lamp looks from the screen, so a larger lamp+// gives a softer edge. The same happens at room scale: the screen's own three shadows are on the wall behind it.+//+// Inputs:+// click a lamp (head, rod or foot) switch that lamp on or off+// click the ring turn it a twelfth of a turn (its three shadows go from rings to lines)+// red / green / blue (R, G, B) switch a lamp, as buttons and keys+// size (S) lamp size: medium, large, small (soft, softer, sharp shadow edges)+// spread (D) lamps far apart, closer, close together (the three shadows separate or overlap)+//+// Light: the three lamps (900 cd each, EV 8), and the one ceiling panel left on, dimmed, by the wall. No fill lights.+import { BoxGeometry, Color, ConeGeometry, CylinderGeometry, DataTexture, Group, Matrix4, Mesh, MeshStandardMaterial, PerspectiveCamera, RectAreaLight, Scene, SkyColor, SphereGeometry, SpotLight, TorusGeometry, Vector3 } from "@threert/scene";+import { defineGame, type FrameContext } from "@threert/gameplay";++type Lamp = "red" | "green" | "blue";+const LAMPS: Lamp[] = ["red", "green", "blue"];+const RGB: Record<Lamp, [number, number, number]> = { red: [1, 0, 0], green: [0, 1, 0], blue: [0, 0, 1] };++interface State {+ red: boolean;+ green: boolean;+ blue: boolean;+ /** Index into SIZES. */+ size: number;+ /** Index into SPREADS. */+ spread: number;+ /** Twelfths of a turn the ring has been turned from facing the lamps. */+ turn: number;+}++// ---------------------------------------------------------------------------------------------- the bench (metres)+// The bench top is y = 0. The screen stands at SCREEN_Z, the white objects at OBJECT_Z in front of it, the lamps at LAMP_Z.+const SCREEN_Z = -0.3, SCREEN_W = 1.2, SCREEN_H = 0.68, SCREEN_Y = 0.06;+const AIM = new Vector3(0, SCREEN_Y + SCREEN_H / 2, SCREEN_Z);+const OBJECT_Z = 0, OBJECT_Y = 0.36;+const RING = new Vector3(0.25, OBJECT_Y, OBJECT_Z);+const LAMP_Z = 0.62;+/** Candela of a lamp: about 900 lux a colour on the screen a metre away, a white of about 250 nits. */+const CANDELA = 900;+/** Radius of the lamp's emitter (m): a pinhole, a torch, a flood. The penumbra on the screen is about as wide. */+const SIZES = [0.004, 0.018, 0.045];+/** Distance between the lamps (m). The three shadows of an object are about half of it apart on the screen. */+const SPREADS = [0.34, 0.22, 0.12];+/** A lamp head: the barrel's length, and how far its axis is above the joint on the rod. */+const BARREL = 0.13, HEAD_UP = 0.018;++/** Where a lamp's head is for a spread: green low in the middle, red and blue higher on either side. */+function lampAt(lamp: Lamp, spread: number): Vector3 {+ if (lamp === "green") return new Vector3(0, 0.11, LAMP_Z);+ return new Vector3((lamp === "red" ? -0.5 : 0.5) * spread, 0.11 + 0.7 * spread, LAMP_Z);+}+/** The head's radius for an emitter radius. */+const headRadius = (r: number) => r + 0.014;++/**+ * The bench top: full-length staves of dark oiled walnut glued side by side, drawn in code. The staves run along u;+ * the texture repeats in both directions.+ */+function benchTexture(size = 512): DataTexture {+ const hash = (x: number, y: number) => {+ let h = (Math.imul(x, 374761393) + Math.imul(y, 668265263)) | 0;+ h = Math.imul(h ^ (h >>> 13), 1274126177);+ return ((h ^ (h >>> 16)) >>> 0) / 4294967296;+ };+ // Value noise on a lattice of `cx` x `cy` pixel cells, repeating with the texture.+ const noise = (x: number, y: number, cx: number, cy: number, seed: number) => {+ const fx = x / cx, fy = y / cy, ix = Math.floor(fx), iy = Math.floor(fy), px = size / cx, py = size / cy;+ const tx = fx - ix, ty = fy - iy, sx = tx * tx * (3 - 2 * tx), sy = ty * ty * (3 - 2 * ty);+ const at = (i: number, j: number) => hash(((i % px) + px) % px + seed * 131, ((j % py) + py) % py + seed * 17);+ return (at(ix, iy) * (1 - sx) + at(ix + 1, iy) * sx) * (1 - sy) + (at(ix, iy + 1) * (1 - sx) + at(ix + 1, iy + 1) * sx) * sy;+ };+ const STRIPS = 16, strip = size / STRIPS;+ const px = new Uint8Array(size * size * 4);+ for (let y = 0; y < size; y++) {+ const k = Math.floor(y / strip);+ for (let x = 0; x < size; x++) {+ const board = k;+ const tone = 0.95 + 0.45 * hash(board, 11);+ const figure = noise(x, y + board * 37, 128, 8, 1) * 0.6 + noise(x, y + board * 11, 64, 2, 2) * 0.4;+ const rings = 0.5 + 0.5 * Math.sin((y / strip) * 9 + 14 * noise(x, y, 256, 32, 3 + (board % 5)) + board);+ let v = tone * (0.62 + 0.5 * figure) * (0.86 + 0.14 * rings);+ if (y % strip < 1) v *= 0.6; // the glue lines+ const o = (y * size + x) * 4;+ px[o] = Math.min(255, 104 * v);+ px[o + 1] = Math.min(255, 66 * v);+ px[o + 2] = Math.min(255, 42 * v);+ px[o + 3] = 255;+ }+ }+ return new DataTexture(size, size, px);+}++// Shown values, eased towards the state's (`frame` moves and scales only what changed).+let spread = SPREADS[0], size = SIZES[1], turn = 0;+let placed = "";+const level: Record<Lamp, number> = { red: 1, green: 1, blue: 1 };+const towards = (cur: number, target: number, dt: number, rate: number) => target + (cur - target) * Math.exp(-dt * rate);+const settle = (cur: number, target: number, dt: number, rate: number, eps: number, snap: boolean) => (snap || Math.abs(cur - target) < eps ? target : towards(cur, target, dt, rate));+const UP = new Vector3(0, 1, 0);+const LOOK = new Matrix4();++function frame(f: FrameContext<State>) {+ const s = f.state;+ spread = settle(spread, SPREADS[s.spread], f.dt, 7, 5e-4, f.snap);+ size = settle(size, SIZES[s.size], f.dt, 7, 1e-4, f.snap);+ const angle = (f.state.turn * Math.PI) / 6;+ if (turn !== angle || f.snap) {+ turn = settle(turn, angle, f.dt, 7, 2e-3, f.snap);+ f.object("ring")!.rotation.y = turn;+ }+ const key = `${spread}/${size}`;+ for (const lamp of LAMPS) {+ level[lamp] = settle(level[lamp], s[lamp] ? 1 : 0, f.dt, 14, 5e-3, f.snap);+ const spot = f.object(`${lamp}_spot`) as SpotLight;+ spot.intensity = CANDELA * level[lamp];+ ((f.object(`${lamp}_band`) as Mesh).material as MeshStandardMaterial).emissiveIntensity = 12 + 420 * level[lamp];+ ((f.object(`${lamp}_lens`) as Mesh).material as MeshStandardMaterial).emissiveIntensity = 400 * level[lamp];+ if (key === placed && !f.snap) continue;+ const p = lampAt(lamp, spread);+ f.object(`${lamp}_lamp`)!.position.set(p.x, 0, p.z);+ const rod = f.object(`${lamp}_rod`)!;+ rod.scale.set(1, p.y, 1);+ rod.position.y = p.y / 2;+ const aim = f.object(`${lamp}_aim`)!;+ aim.position.y = p.y;+ aim.quaternion.setFromRotationMatrix(LOOK.lookAt(p, AIM, UP));+ const k = headRadius(size) / headRadius(SIZES[1]);+ f.object(`${lamp}_head`)!.scale.set(k, k, 1);+ spot.radius = size;+ spot.position.set(0, HEAD_UP, -(BARREL * 0.4 + size + 0.004));+ }+ placed = key;+}++export default defineGame<State>({+ state: { red: true, green: true, blue: true, size: 1, spread: 0, turn: 0 },++ setup() {+ const scene = new Scene();+ // The rest of the darkened room, and the one ceiling panel left on, dimmed: the one by the wall, behind the plane+ // of the screen, so it lights the wall, the bench and the tops of the lamps but not the face of the screen.+ scene.environment = new SkyColor(0x6f7f9f, 2);+ const ceiling = new RectAreaLight(new Color().setRGB(1, 0.84, 0.66), 750, 2.0, 0.5);+ ceiling.id = "ceiling_light";+ ceiling.position.set(0, 1.75, -0.62);+ ceiling.rotation.x = -Math.PI / 2;+ ceiling.card = false;+ scene.add(ceiling);+ const add = <T extends Mesh | Group>(parent: Scene | Group, o: T, id: string, at: [number, number, number]): T => {+ o.id = id;+ o.position.set(...at);+ parent.add(o);+ return o;+ };+ const mat = (name: string, color: number, roughness: number, metalness = 0) => new MeshStandardMaterial({ name, color, roughness, metalness });++ // Room: the bench, the floor under it, the wall behind it.+ const wood = benchTexture();+ wood.repeat = [1, 3];+ add(scene, new Mesh(new BoxGeometry(2.3, 0.04, 1.9), new MeshStandardMaterial({ name: "bench", map: wood, roughness: 0.24 })), "bench", [0, -0.02, 0]);+ add(scene, new Mesh(new BoxGeometry(2.3, 0.09, 0.02), mat("upstand", 0x2a1b10, 0.35)), "upstand", [0, 0.045, -0.94]);+ add(scene, new Mesh(new BoxGeometry(2.2, 0.1, 1.8), mat("apron", 0x3a2717, 0.6)), "apron", [0, -0.09, 0]);+ add(scene, new Mesh(new BoxGeometry(8, 0.1, 6), mat("floor", 0x3b3a38, 0.7)), "floor", [0, -0.95, 0]);+ add(scene, new Mesh(new BoxGeometry(8, 4, 0.1), mat("wall", 0xb9bdb6, 0.9)), "wall", [0, 1.1, -1.0]);++ // The screen: a matte white board on two feet.+ const white = mat("white", 0xe4e4e2, 1);+ const steel = mat("steel", 0x8d9094, 0.35, 1);+ const dark = mat("dark_metal", 0x1c1d20, 0.45, 1);+ add(scene, new Mesh(new BoxGeometry(SCREEN_W, SCREEN_H, 0.01), white), "screen", [0, SCREEN_Y + SCREEN_H / 2, SCREEN_Z - 0.005]);+ for (const side of [-1, 1]) {+ const x = side * (SCREEN_W / 2 + 0.012);+ add(scene, new Mesh(new BoxGeometry(0.11, 0.012, 0.18), dark), `screen_base${side}`, [x, 0.006, SCREEN_Z - 0.03]);+ add(scene, new Mesh(new CylinderGeometry(0.006, 0.006, 0.86, 16), steel), `screen_rod${side}`, [x, 0.43, SCREEN_Z - 0.03]);+ for (const y of [0.2, 0.62]) add(scene, new Mesh(new BoxGeometry(0.04, 0.022, 0.05), dark), `screen_clamp${side}_${y}`, [x - side * 0.008, y, SCREEN_Z - 0.012]);+ }++ // The white objects on thin stands.+ const objectWhite = mat("object_white", 0xe4e4e2, 0.7);+ const stand = (id: string, x: number, bottom: number) => {+ add(scene, new Mesh(new CylinderGeometry(0.036, 0.04, 0.008, 48), dark), `${id}_foot`, [x, 0.004, OBJECT_Z]);+ add(scene, new Mesh(new CylinderGeometry(0.005, 0.005, bottom, 12), objectWhite), `${id}_stem`, [x, bottom / 2, OBJECT_Z]);+ };+ stand("cone", -0.25, OBJECT_Y - 0.065);+ add(scene, new Mesh(new ConeGeometry(0.055, 0.13, 64), objectWhite), "cone", [-0.25, OBJECT_Y, OBJECT_Z]);+ stand("ball", 0, OBJECT_Y - 0.048);+ add(scene, new Mesh(new SphereGeometry(0.05, 64, 32), objectWhite), "ball", [0, OBJECT_Y, OBJECT_Z]);+ stand("ring", RING.x, OBJECT_Y - 0.066);+ add(scene, new Mesh(new TorusGeometry(0.052, 0.014, 24, 64), objectWhite), "ring", [RING.x, RING.y, RING.z]);++ // The lamps: a foot and a rod (upright), and a head that aims at the middle of the screen. The head's meshes are+ // in `<lamp>_head`, scaled across with the lamp size; local -Z is the beam.+ const brushed = mat("brushed", 0xd3d5d8, 0.45, 1);+ for (const lamp of LAMPS) {+ const colour = new Color().setRGB(...RGB[lamp]);+ const p = lampAt(lamp, SPREADS[0]);+ const whole = add(scene, new Group(), `${lamp}_lamp`, [p.x, 0, p.z]);+ add(whole, new Mesh(new CylinderGeometry(0.05, 0.056, 0.014, 48), dark), `${lamp}_foot`, [0, 0.007, 0]);+ add(whole, new Mesh(new CylinderGeometry(0.006, 0.006, 1, 16), steel), `${lamp}_rod`, [0, p.y / 2, 0]).scale.set(1, p.y, 1);+ const aim = add(whole, new Group(), `${lamp}_aim`, [0, p.y, 0]);+ add(aim, new Mesh(new SphereGeometry(0.013, 24, 12), dark), `${lamp}_joint`, [0, 0, 0]);+ const head = add(aim, new Group(), `${lamp}_head`, [0, HEAD_UP, 0]);+ const r = headRadius(SIZES[1]);+ const along = (m: Mesh) => { m.rotation.x = -Math.PI / 2; return m; }; // a cylinder's +Y to the beam (-Z)+ add(head, along(new Mesh(new CylinderGeometry(r, r, BARREL, 48), brushed)), `${lamp}_barrel`, [0, 0, BARREL * 0.1]);+ add(head, along(new Mesh(new CylinderGeometry(r, r * 0.6, 0.03, 48), brushed)), `${lamp}_cap`, [0, 0, BARREL * 0.6 + 0.015]);+ add(head, along(new Mesh(new CylinderGeometry(r * 1.08, r * 1.08, 0.012, 48), dark)), `${lamp}_rim`, [0, 0, -BARREL * 0.4 + 0.004]);+ // A translucent band round the barrel that glows in the lamp's colour (so it reads from behind), and the lens.+ const band = new MeshStandardMaterial({ name: `${lamp}_band`, color: colour.clone().multiplyScalar(0.5), roughness: 0.4, emissive: colour, emissiveIntensity: 400 });+ add(head, along(new Mesh(new CylinderGeometry(r * 1.04, r * 1.04, 0.026, 48), band)), `${lamp}_band`, [0, 0, BARREL * 0.36]);+ const lens = new MeshStandardMaterial({ name: `${lamp}_lens`, color: 0x000000, roughness: 0.3, emissive: colour, emissiveIntensity: 400 });+ add(head, along(new Mesh(new CylinderGeometry(r * 0.86, r * 0.86, 0.002, 48), lens)), `${lamp}_lens`, [0, 0, -BARREL * 0.4 - 0.0015]);++ const spot = new SpotLight(colour, CANDELA, 0, (58 * Math.PI) / 180, 0.3);+ spot.id = `${lamp}_spot`;+ spot.target = null;+ spot.radius = SIZES[1];+ spot.position.set(0, HEAD_UP, -(BARREL * 0.4 + SIZES[1] + 0.004));+ aim.add(spot);+ }++ const camera = new PerspectiveCamera(44, 16 / 9, 0.05, 50);+ camera.id = "camera";+ camera.position.set(0.18, 0.86, 1.55);+ camera.lookAt(0, 0.1, -0.2);+ camera.setManualExposure(8);+ scene.add(camera);+ return { scene, camera, options: { name: "colour-lab", preset: "preview" as const, width: 1280, height: 720 } };+ },++ frame,++ handlers: {+ click(tx, ev: { target?: string; ray?: { origin: [number, number, number]; direction: [number, number, number] } }) {+ let what = String(ev.target ?? "").split("_")[0];+ if (what !== "ring" && !LAMPS.includes(what as Lamp) && ev.ray) {+ // A near miss (through the ring, just beside a lamp head): take what the click passed closest to.+ const o = new Vector3(...ev.ray.origin), d = new Vector3(...ev.ray.direction).normalize();+ const miss = (p: Vector3) => {+ const v = p.clone().sub(o);+ return v.addScaledVector(d, -v.dot(d)).length();+ };+ let best = 0.075;+ if (miss(RING) < best) [what, best] = ["ring", miss(RING)];+ for (const lamp of LAMPS) {+ const m = miss(lampAt(lamp, SPREADS[tx.state.spread])) - headRadius(SIZES[tx.state.size]) + 0.03;+ if (m < best) [what, best] = [lamp, m];+ }+ }+ if (what === "ring") {+ tx.state.turn += 1;+ return;+ }+ tx.decide(LAMPS.includes(what as Lamp), "click a lamp to switch it, or the ring to turn it");+ tx.state[what as Lamp] = !tx.state[what as Lamp];+ },+ red(tx) { tx.state.red = !tx.state.red; },+ green(tx) { tx.state.green = !tx.state.green; },+ blue(tx) { tx.state.blue = !tx.state.blue; },+ size(tx) { tx.state.size = (tx.state.size + 1) % SIZES.length; },+ spread(tx) { tx.state.spread = (tx.state.spread + 1) % SPREADS.length; },+ },++ keys: { R: "red", G: "green", B: "blue", S: "size", D: "spread" },+});diff --git a/showcase/colour-lab/thumb.jpg b/showcase/colour-lab/thumb.jpgnew file mode 100644index 0000000..99fc48aBinary files /dev/null and b/showcase/colour-lab/thumb.jpg differdiff --git a/showcase/daylight-home/CREDITS.md b/showcase/daylight-home/CREDITS.mdnew file mode 100644index 0000000..11fb7ab--- /dev/null+++ b/showcase/daylight-home/CREDITS.md@@ -0,0 +1,21 @@+# Daylight Home: credits++Every file the case reads is in `assets/showcase/daylight-home/` (9.8 MB together, the largest 2.6 MB). All of it is+from Poly Haven and is CC0 1.0 (https://polyhaven.com/license). The models are Poly Haven's 1k glTF downloads, each+packed with its own textures into one `.glb` (nothing else changed).++| File | What it is | Author | Licence | Source |+|---|---|---|---|---|+| `Sofa_01_1k.glb` | Sofa 01 (the sofa; its fabric is tinted in the scene) | Kirill Sannikov | CC0 1.0 | https://polyhaven.com/a/Sofa_01 |+| `mid_century_lounge_chair_1k.glb` | Mid Century Lounge Chair (the armchair) | Kuutti Siitonen | CC0 1.0 | https://polyhaven.com/a/mid_century_lounge_chair |+| `modern_coffee_table_01_1k.glb` | Modern Coffee Table 01 | Amin | CC0 1.0 | https://polyhaven.com/a/modern_coffee_table_01 |+| `potted_plant_02_1k.glb` | Potted Plant 02 | Rico Cilliers | CC0 1.0 | https://polyhaven.com/a/potted_plant_02 |+| `wooden_display_shelves_01_1k.glb` | Wooden Display Shelves 01 (used twice) | James Ray Cock | CC0 1.0 | https://polyhaven.com/a/wooden_display_shelves_01 |+| `side_table_01_1k.glb` | Side Table 01 | James Ray Cock | CC0 1.0 | https://polyhaven.com/a/side_table_01 |+| `ceramic_vase_01_1k.glb` | Ceramic Vase 01 (used twice) | James Ray Cock | CC0 1.0 | https://polyhaven.com/a/ceramic_vase_01 |+| `artwork_palace.jpg` | The painting over the sofa: the artwork texture of Hanging Picture Frame 02, cropped to the picture (1024 x 560) | James Ray Cock | CC0 1.0 | https://polyhaven.com/a/hanging_picture_frame_02 |+| `herringbone_parquet_diff_1k.jpg`, `herringbone_parquet_nor_gl_1k.jpg` | Herringbone Parquet: the floor's colour and normal maps | Sergej Majboroda (photography), Jenelle van Heerden (processing) | CC0 1.0 | https://polyhaven.com/a/herringbone_parquet |+| `poly_wool_herringbone_nor_gl_1k.jpg` | Poly Wool Herringbone: the rug's weave (normal map) | colormass (photography), Rico Cilliers (processing) | CC0 1.0 | https://polyhaven.com/a/poly_wool_herringbone |++Built in `daylight-home.game.ts`, no files: the room, window frames, balcony, city blocks (the engine's procedural+windows), curtains, floor lamp, pendant, books, picture frames, the rug's pattern and the colour-field picture.diff --git a/showcase/daylight-home/assets/Sofa_01_1k.glb b/showcase/daylight-home/assets/Sofa_01_1k.glbnew file mode 100644index 0000000..7944db3Binary files /dev/null and b/showcase/daylight-home/assets/Sofa_01_1k.glb differdiff --git a/showcase/daylight-home/assets/artwork_palace.jpg b/showcase/daylight-home/assets/artwork_palace.jpgnew file mode 100644index 0000000..df87251Binary files /dev/null and b/showcase/daylight-home/assets/artwork_palace.jpg differdiff --git a/showcase/daylight-home/assets/ceramic_vase_01_1k.glb b/showcase/daylight-home/assets/ceramic_vase_01_1k.glbnew file mode 100644index 0000000..862e0d1Binary files /dev/null and b/showcase/daylight-home/assets/ceramic_vase_01_1k.glb differdiff --git a/showcase/daylight-home/assets/herringbone_parquet_diff_1k.jpg b/showcase/daylight-home/assets/herringbone_parquet_diff_1k.jpgnew file mode 100644index 0000000..b59f22dBinary files /dev/null and b/showcase/daylight-home/assets/herringbone_parquet_diff_1k.jpg differdiff --git a/showcase/daylight-home/assets/herringbone_parquet_nor_gl_1k.jpg b/showcase/daylight-home/assets/herringbone_parquet_nor_gl_1k.jpgnew file mode 100644index 0000000..37202afBinary files /dev/null and b/showcase/daylight-home/assets/herringbone_parquet_nor_gl_1k.jpg differdiff --git a/showcase/daylight-home/assets/mid_century_lounge_chair_1k.glb b/showcase/daylight-home/assets/mid_century_lounge_chair_1k.glbnew file mode 100644index 0000000..f491f7dBinary files /dev/null and b/showcase/daylight-home/assets/mid_century_lounge_chair_1k.glb differdiff --git a/showcase/daylight-home/assets/modern_coffee_table_01_1k.glb b/showcase/daylight-home/assets/modern_coffee_table_01_1k.glbnew file mode 100644index 0000000..edae3baBinary files /dev/null and b/showcase/daylight-home/assets/modern_coffee_table_01_1k.glb differdiff --git a/showcase/daylight-home/assets/poly_wool_herringbone_nor_gl_1k.jpg b/showcase/daylight-home/assets/poly_wool_herringbone_nor_gl_1k.jpgnew file mode 100644index 0000000..ed5ed3bBinary files /dev/null and b/showcase/daylight-home/assets/poly_wool_herringbone_nor_gl_1k.jpg differdiff --git a/showcase/daylight-home/assets/potted_plant_02_1k.glb b/showcase/daylight-home/assets/potted_plant_02_1k.glbnew file mode 100644index 0000000..57f167bBinary files /dev/null and b/showcase/daylight-home/assets/potted_plant_02_1k.glb differdiff --git a/showcase/daylight-home/assets/side_table_01_1k.glb b/showcase/daylight-home/assets/side_table_01_1k.glbnew file mode 100644index 0000000..5b267d7Binary files /dev/null and b/showcase/daylight-home/assets/side_table_01_1k.glb differdiff --git a/showcase/daylight-home/assets/wooden_display_shelves_01_1k.glb b/showcase/daylight-home/assets/wooden_display_shelves_01_1k.glbnew file mode 100644index 0000000..4029103Binary files /dev/null and b/showcase/daylight-home/assets/wooden_display_shelves_01_1k.glb differdiff --git a/showcase/daylight-home/case.json b/showcase/daylight-home/case.jsonnew file mode 100644index 0000000..d9f392c--- /dev/null+++ b/showcase/daylight-home/case.json@@ -0,0 +1,91 @@+{+ "id": "daylight-home",+ "industry": "Architecture & real estate",+ "title": "Daylight Home",+ "caption": "One living room, from morning sun to lamplight",+ "blurb": "A living room with a window wall, lit only by a physical sun and sky and, at night, by its two lamps. Step through the day and the patch of sun crosses the parquet, bounces onto the ceiling and takes the colour of whatever paint you choose: what a buyer wants to know, and what engines normally bake once.",+ "controls": [+ {+ "input": "T, or click the floor",+ "does": "morning, noon, golden hour, night"+ },+ {+ "input": "P, or click a wall",+ "does": "repaints the walls"+ },+ {+ "input": "F, or click the sofa",+ "does": "changes the sofa’s fabric"+ },+ {+ "input": "V",+ "does": "moves to another viewpoint"+ },+ {+ "input": "L, or click a lamp",+ "does": "switches the lamps"+ }+ ],+ "credits": [+ {+ "what": "Sofa 01",+ "by": "Kirill Sannikov",+ "licence": "CC0 1.0",+ "url": "https://polyhaven.com/a/Sofa_01"+ },+ {+ "what": "Mid Century Lounge Chair",+ "by": "Kuutti Siitonen",+ "licence": "CC0 1.0",+ "url": "https://polyhaven.com/a/mid_century_lounge_chair"+ },+ {+ "what": "Modern Coffee Table 01",+ "by": "Amin",+ "licence": "CC0 1.0",+ "url": "https://polyhaven.com/a/modern_coffee_table_01"+ },+ {+ "what": "Potted Plant 02",+ "by": "Rico Cilliers",+ "licence": "CC0 1.0",+ "url": "https://polyhaven.com/a/potted_plant_02"+ },+ {+ "what": "Wooden Display Shelves 01",+ "by": "James Ray Cock",+ "licence": "CC0 1.0",+ "url": "https://polyhaven.com/a/wooden_display_shelves_01"+ },+ {+ "what": "Side Table 01",+ "by": "James Ray Cock",+ "licence": "CC0 1.0",+ "url": "https://polyhaven.com/a/side_table_01"+ },+ {+ "what": "Ceramic Vase 01",+ "by": "James Ray Cock",+ "licence": "CC0 1.0",+ "url": "https://polyhaven.com/a/ceramic_vase_01"+ },+ {+ "what": "Painting (artwork of Hanging Picture Frame 02, cropped)",+ "by": "James Ray Cock",+ "licence": "CC0 1.0",+ "url": "https://polyhaven.com/a/hanging_picture_frame_02"+ },+ {+ "what": "Herringbone Parquet (floor textures)",+ "by": "Sergej Majboroda, Jenelle van Heerden",+ "licence": "CC0 1.0",+ "url": "https://polyhaven.com/a/herringbone_parquet"+ },+ {+ "what": "Poly Wool Herringbone (rug weave)",+ "by": "colormass, Rico Cilliers",+ "licence": "CC0 1.0",+ "url": "https://polyhaven.com/a/poly_wool_herringbone"+ }+ ]+}diff --git a/showcase/daylight-home/daylight-home.game.ts b/showcase/daylight-home/daylight-home.game.tsnew file mode 100644index 0000000..628c233--- /dev/null+++ b/showcase/daylight-home/daylight-home.game.ts@@ -0,0 +1,393 @@+// "Daylight Home": the living room of an apartment someone is deciding whether to buy, or how to furnish, seen at+// four times of day. The room is 5 x 6.5 m with a 2.7 m ceiling and a 4.4 m window wall onto a balcony, high over a+// city. The only lights are a physical sun (100 000 lux) with its sky, a floor lamp and a pendant: the sun patches on+// the parquet, the light they bounce onto the ceiling and the far wall, the colour the paint gives that bounce and the+// soft shadow under the table are all traced. Nothing is baked and there is no fill light.+//+// Inputs (buttons / keys):+// time (T) morning -> noon -> golden hour -> night. The sun travels there in about two seconds and the exposure+// follows it; at night the two lamps come on and the city's windows show.+// paint (P) wall colour: warm white -> sage -> clay -> slate blue (the bounce light takes the colour).+// sofa (F) sofa fabric: linen -> ochre -> petrol -> terracotta -> charcoal.+// view (V) from the entrance -> from the sofa towards the window -> towards the shelf wall.+// lamps (L) both lamps on / off.+// Click: the floor lamp or the pendant switches it; a wall repaints; the sofa changes fabric; the floor, the rug, the+// window frames or the balcony and city beyond them step the time of day.+//+// The state is six small values, changed only in the handlers; `frame` shows it (and eases the sun, the camera and+// the paint towards it, then leaves the scene alone so the picture converges).+//+// Furniture and textures are CC0 from Poly Haven (CREDITS.md); the room, lamps, books, rug pattern, curtains, the+// second picture and the city are built here.+import {+ BoxGeometry, Color, CylinderGeometry, DataTexture, DirectionalLight, facadeWindows, GLTFModel, Group, MaterialFunction, Mesh,+ MeshGeometry, MeshStandardMaterial, type Object3D, PerspectiveCamera, PlaneGeometry, Scene, SkyAtmosphere, SphereGeometry,+ SurfaceMaterial, Texture,+} from "@threert/scene";+import { defineGame, type FrameContext } from "@threert/gameplay";++type Vec3 = [number, number, number];+const A = "assets/showcase/daylight-home/";++// ---------------------------------------------------------------------------------------------- what can change+/**+ * Sun elevation / azimuth (degrees; the window wall faces -X) and the camera's exposure (EV100) for the room in that+ * daylight, per time of day. Once the sun is down the exposure opens to NIGHT_EV, for the lamps.+ */+const TIMES = [+ { name: "morning", el: 19, az: -122, ev: 11.2 },+ { name: "noon", el: 58, az: -93, ev: 10.6 },+ { name: "golden hour", el: 12, az: -66, ev: 11.2 },+ { name: "night", el: -8, az: -40, ev: 11.2 },+] as const;+const NIGHT = 3, NIGHT_EV = 5.9;+/** Wall paints (linear albedo): warm white, sage, clay, slate blue. */+const PAINTS: Vec3[] = [[0.8, 0.76, 0.69], [0.42, 0.5, 0.36], [0.62, 0.33, 0.22], [0.27, 0.36, 0.5]];+/** Sofa fabrics (linear albedo); null keeps the model's own linen. */+const FABRICS: (Vec3 | null)[] = [null, [0.5, 0.33, 0.09], [0.06, 0.2, 0.25], [0.46, 0.17, 0.11], [0.07, 0.07, 0.08]];+/** Viewpoints: eye, target, vertical field of view. */+const VIEWS: { eye: Vec3; at: Vec3; fov: number }[] = [+ { eye: [0.55, 1.45, 3.05], at: [-0.25, 1.0, -2.0], fov: 48 }, // from the entrance+ { eye: [0.15, 1.12, -2.4], at: [-2.5, 1.05, -1.35], fov: 50 }, // from the sofa towards the window+ { eye: [-1.9, 1.35, 0.35], at: [2.5, 1.0, -1.7], fov: 46 }, // towards the shelf wall+];+const SUN_LUX = 100000;+/** Clicks on these step the time of day: where the sun falls and what is seen through the window. */+const OUTSIDE = ["floor", "rug", "window_", "balcony", "block_", "city_ground", "curtain"];+const SHADE_NITS = 1500, GLOBE_NITS = 1200;++interface State {+ time: number;+ paint: number;+ sofa: number;+ view: number;+ lamp: boolean;+ pendant: boolean;+}++// ---------------------------------------------------------------------------------------------- the room+const RW = 5, RD = 6.5, RH = 2.7, T = 0.2;+const X0 = -RW / 2, X1 = RW / 2, Z0 = -RD / 2, Z1 = RD / 2;+/** The window opening in the -X wall: z from WIN_A to WIN_B, floor to WIN_H. */+const WIN_A = -2.65, WIN_B = 1.75, WIN_H = 2.4;++/** The sofa's upholstery (the light texels of its one material; the frame is dark wood) takes the node's customData. */+const SOFA_TINT = new MaterialFunction("daylight_sofa_tint", {+ code: `+ let l = dot(o.base, vec3<f32>(0.2126, 0.7152, 0.0722));+ let fabric = smoothstep(0.1, 0.22, l) * step(0.5, i.custom.w);+ o.base = mix(o.base, i.custom.xyz * (l / 0.55), fabric);`,+});++/** A small deterministic generator for the books (setup must not use Math.random). */+function rng(seed: number): () => number {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) >>> 0;+ let t = a;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++/** A pleated curtain: a ribbon along z from z0 to z1, hanging from `top` to the floor, pleats `depth` deep. */+function curtainGeometry(z0: number, z1: number, top: number, bottom: number, pleats: number, depth: number) {+ const n = pleats * 12, pos: number[] = [], idx: number[] = [], nor: number[] = [], uv: number[] = [];+ for (let i = 0; i <= n; i++) {+ const u = i / n, ph = u * pleats * Math.PI * 2;+ const x = Math.sin(ph) * depth, z = z0 + (z1 - z0) * u;+ const dx = Math.cos(ph) * depth * pleats * Math.PI * 2, dz = z1 - z0, l = Math.hypot(dx, dz);+ for (const y of [bottom, top]) {+ pos.push(x, y, z);+ nor.push(dz / l, 0, -dx / l);+ uv.push(u, y === top ? 0 : 1);+ }+ if (i < n) idx.push(i * 2, i * 2 + 1, i * 2 + 2, i * 2 + 1, i * 2 + 3, i * 2 + 2);+ }+ return new MeshGeometry(pos, idx, nor, uv);+}++function setup() {+ const scene = new Scene();+ const sun = new DirectionalLight(0xffffff, SUN_LUX);+ sun.id = "sun";+ sun.setSunAngles(TIMES[2].el, TIMES[2].az);+ scene.add(sun);+ // `dynamic`: the frame script moves the sun; the live view moves its light and re-bakes the sky in place.+ scene.environment = new SkyAtmosphere({ sun, dynamic: true, glow: 0x4a63a8, glowIntensity: 8, aerialPerspective: 1 });++ const std = (name: string, color: Vec3 | number, roughness = 0.9, metalness = 0) =>+ new MeshStandardMaterial({ name, color: typeof color === "number" ? color : new Color().setRGB(...color), roughness, metalness });+ const add = <O extends Object3D>(o: O, id: string, pos: Vec3, parent: Object3D = scene) => {+ o.id = id;+ o.position.set(...pos);+ parent.add(o);+ return o;+ };+ const box = (id: string, size: Vec3, pos: Vec3, m: MeshStandardMaterial, parent: Object3D = scene) => add(new Mesh(new BoxGeometry(...size), m), id, pos, parent);++ // -- shell+ const paint = std("paint", PAINTS[0], 0.92);+ const ceilingWhite = std("ceiling_white", [0.84, 0.84, 0.82], 0.95);+ const trim = std("trim_white", [0.8, 0.8, 0.78], 0.6);+ const tex = (file: string, srgb: boolean, repeat: [number, number]) => {+ const t = new Texture(A + file, srgb ? "srgb" : "linear");+ t.repeat = repeat;+ return t;+ };+ const fr: [number, number] = [RW / 3.4, RD / 3.4]; // the parquet scan is 3.4 m wide+ const parquet = new MeshStandardMaterial({+ name: "parquet", roughness: 0.28, map: tex("herringbone_parquet_diff_1k.jpg", true, fr), normalMap: tex("herringbone_parquet_nor_gl_1k.jpg", false, fr),+ });+ const floor = add(new Mesh(new PlaneGeometry(RW, RD), parquet), "floor", [0, 0, 0]);+ floor.rotation.x = -Math.PI / 2;+ const concrete = std("concrete", [0.45, 0.44, 0.42], 0.9);+ // Walls, slab and ceiling overlap where they meet (walls run from under the floor to over the ceiling, into each+ // other at the corners): no seam for a ray to slip through to the sun outside.+ const WH = RH + T + 0.3, WY = (RH + T - 0.3) / 2;+ box("slab", [RW + 2 * T, 0.3, RD + 2 * T], [0, -0.152, 0], concrete);+ box("ceiling", [RW + 2 * T, T, RD + 2 * T], [0, RH + T / 2, 0], ceilingWhite);+ box("wall_far", [RW + 2 * T, WH, T], [0, WY, Z0 - T / 2], paint);+ box("wall_entrance", [RW + 2 * T, WH, T], [0, WY, Z1 + T / 2], paint);+ box("wall_shelf", [T, WH, RD + 2 * T], [X1 + T / 2, WY, 0], paint);+ // The window wall: a pier at each end and a lintel over the opening.+ box("wall_window_a", [T, WH, WIN_A - Z0 + T], [X0 - T / 2, WY, (Z0 - T + WIN_A) / 2], paint);+ box("wall_window_b", [T, WH, Z1 + T - WIN_B], [X0 - T / 2, WY, (WIN_B + Z1 + T) / 2], paint);+ box("wall_window_top", [T, RH + T - WIN_H, WIN_B - WIN_A + 0.2], [X0 - T / 2, (RH + T + WIN_H) / 2, (WIN_A + WIN_B) / 2], paint);+ // Skirting boards.+ const SK = 0.08, SKT = 0.015;+ box("skirting_far", [RW, SK, SKT], [0, SK / 2, Z0 + SKT / 2], trim);+ box("skirting_entrance", [RW, SK, SKT], [0, SK / 2, Z1 - SKT / 2], trim);+ box("skirting_shelf", [SKT, SK, RD], [X1 - SKT / 2, SK / 2, 0], trim);+ box("skirting_window", [SKT, SK, Z1 - WIN_B], [X0 + SKT / 2, SK / 2, (WIN_B + Z1) / 2], trim);+ // The entrance door (in the wall behind the default viewpoint).+ box("door", [0.9, 2.05, 0.04], [-1.3, 1.025, Z1 - 0.01], std("door", [0.7, 0.68, 0.64], 0.5));+ box("door_handle", [0.12, 0.02, 0.05], [-0.98, 1.0, Z1 - 0.05], std("handle", [0.6, 0.6, 0.6], 0.3, 1));++ // -- window wall: slim dark frames around four openings. They are left unglazed: clear glass would send every view+ // ray through it on a second bounce for a reflection hardly seen against the daylight.+ const frame = std("window_frame", [0.03, 0.03, 0.035], 0.45, 0.6);+ const FX = X0 - T / 2, FW = 0.05, FD = 0.07, panes = 4, pw = (WIN_B - WIN_A) / panes;+ for (let i = 0; i <= panes; i++) box(`window_mullion_${i}`, [FD, WIN_H, FW], [FX, WIN_H / 2, WIN_A + i * pw + (i === 0 ? FW / 2 : i === panes ? -FW / 2 : 0)], frame);+ box("window_head", [FD, FW, WIN_B - WIN_A], [FX, WIN_H - FW / 2, (WIN_A + WIN_B) / 2], frame);+ box("window_sill", [FD, FW, WIN_B - WIN_A], [FX, FW / 2, (WIN_A + WIN_B) / 2], frame);+ box("window_door_handle", [0.03, 0.16, 0.025], [FX + 0.05, 1.05, WIN_A + 2 * pw + 0.06], std("handle_dark", [0.05, 0.05, 0.05], 0.3, 1));++ // -- balcony and what is beyond it+ const BX = X0 - T - 0.7, BZ = (WIN_A + WIN_B) / 2;+ box("balcony", [1.4, 0.2, 5.2], [BX, -0.12, (WIN_A + WIN_B) / 2], std("balcony_tiles", [0.5, 0.48, 0.45], 0.7));+ const RX = BX - 0.66;+ box("balcony_rail", [0.05, 0.04, 5.2], [RX, 1.08, (WIN_A + WIN_B) / 2], frame);+ box("balcony_rail_low", [0.03, 0.03, 5.2], [RX, 0.12, (WIN_A + WIN_B) / 2], frame);+ for (let i = 0; i <= 4; i++) box(`balcony_post_${i}`, [0.04, 1.08, 0.04], [RX, 0.54, BZ - 2.58 + i * 1.29], frame);+ for (const y of [0.36, 0.6, 0.84]) box(`balcony_bar_${y}`, [0.015, 0.015, 5.2], [RX, y, BZ], frame);+ // The city below and across (the apartment is on a high floor): a ground far down and blocks whose windows are+ // the engine's procedural ones (dark glass by day, some of them lit at night).+ const GROUND = 48;+ const ground = add(new Mesh(new PlaneGeometry(1200, 1200), std("city_ground", [0.17, 0.18, 0.16], 1)), "city_ground", [-300, -GROUND, 0]);+ ground.rotation.x = -Math.PI / 2;+ const r = rng(7);+ const blockMats = ([[0.34, 0.32, 0.29], [0.26, 0.27, 0.29], [0.4, 0.35, 0.29], [0.2, 0.21, 0.23]] as Vec3[]).map((c, i) => new SurfaceMaterial({+ name: `block_${i}`, color: c, roughness: 0.9,+ windows: facadeWindows({ floorHeight: 3.1 + i * 0.15, bayWidth: 2.6 + i * 0.5, windowWidth: 1.7 + i * 0.3, windowHeight: 1.7, groundHeight: -GROUND, sill: 0.9, litChance: 0.5, brightness: 22, seed: i }),+ }));+ for (let i = 0; i < 96; i++) {+ // Lower blocks close by, the taller ones further out: roofs below, a skyline at the horizon.+ const d = 70 + r() * r() * 620, a = (r() - 0.5) * 2.8, w = 16 + r() * 28, top = -40 + 14 * r() + Math.min(1, d / 400) * 26 * r() + (r() < 0.12 ? 12 : 0);+ box(`block_${i}`, [w, top + GROUND, 14 + r() * 26], [X0 - d * Math.cos(a), (top - GROUND) / 2, d * Math.sin(a)], blockMats[i % 4]).rotation.y = r() * 0.6;+ }++ // -- curtains, drawn back onto the piers at each end of the window+ const sheer = new MeshStandardMaterial({ name: "curtain", color: new Color().setRGB(0.78, 0.76, 0.71), roughness: 1, side: "double", flatShading: true });+ add(new Mesh(curtainGeometry(Z0 + 0.03, WIN_A - 0.08, 2.56, 0.02, 6, 0.04), sheer), "curtain_a", [X0 + 0.1, 0, 0]);+ add(new Mesh(curtainGeometry(WIN_B + 0.1, WIN_B + 0.62, 2.56, 0.02, 6, 0.04), sheer), "curtain_b", [X0 + 0.1, 0, 0]);+ box("curtain_rail", [0.02, 0.02, WIN_B + 0.66 - Z0 - 0.02], [X0 + 0.1, 2.57, (WIN_B + 0.66 + Z0 + 0.02) / 2], frame);++ // -- furniture (Poly Haven, metres, front +Z)+ const model = (id: string, file: string, pos: Vec3, rotY = 0, scale = 1, opts?: ConstructorParameters<typeof GLTFModel>[1]) => {+ const m = add(new GLTFModel(`${A}${file}_1k.glb`, opts), id, pos);+ m.rotation.y = rotY;+ m.scale.set(scale, scale, scale);+ return m;+ };+ model("sofa", "Sofa_01", [0, 0, Z0 + 0.5], 0, 1.2, { functions: { Sofa_01: SOFA_TINT.with() } });+ // A painting over the sofa: the artwork of Poly Haven's picture frame in a frame built here.+ const PW = 1.2, PH = PW * 560 / 1024, PY = 1.6, MAT = 0.09, FR = 0.025;+ add(new Mesh(new PlaneGeometry(PW, PH), new MeshStandardMaterial({ name: "artwork", map: new Texture(A + "artwork_palace.jpg"), roughness: 0.6 })), "picture", [0, PY, Z0 + 0.022]);+ box("picture_mat", [PW + 2 * MAT, PH + 2 * MAT, 0.02], [0, PY, Z0 + 0.01], std("picture_mat", [0.82, 0.81, 0.78], 0.9));+ const oak = std("oak", [0.42, 0.27, 0.14], 0.5);+ for (const sy of [-1, 1]) box(`picture_frame_h${sy}`, [PW + 2 * MAT + 2 * FR, FR, 0.04], [0, PY + sy * (PH / 2 + MAT + FR / 2), Z0 + 0.02], oak);+ for (const sx of [-1, 1]) box(`picture_frame_v${sx}`, [FR, PH + 2 * MAT, 0.04], [sx * (PW / 2 + MAT + FR / 2), PY, Z0 + 0.02], oak);+ model("coffee_table", "modern_coffee_table_01", [0, 0, -1.4], Math.PI / 2);+ model("armchair", "mid_century_lounge_chair", [-1.45, 0, -0.75], 1.95);+ model("side_table", "side_table_01", [-1.95, 0, 0.0], 0.2);+ model("vase", "ceramic_vase_01", [-1.95, 0.55, 0.0], 0);+ model("plant", "potted_plant_02", [-1.55, 0, Z0 + 0.5], 0.6, 1.45);+ const SHELF_Z = [-2.14, -1.05];+ model("shelf_a", "wooden_display_shelves_01", [X1 - 0.2, 0, SHELF_Z[0]], 0);+ model("shelf_b", "wooden_display_shelves_01", [X1 - 0.2, 0, SHELF_Z[1]], 0);+ model("vase_shelf", "ceramic_vase_01", [X1 - 0.2, 1.565, SHELF_Z[1] + 0.2], 1, 0.8);+ // A second, smaller picture on the shelf wall: colour fields painted here.+ const AW = 40, AH = 52, px = new Uint8Array(AW * AH * 4);+ const fields: [number, number, number, number, number][] = [[0, 0, 40, 52, 0xe9e2d3], [4, 5, 36, 24, 0xc8643c], [4, 27, 36, 39, 0x2f4f6b], [4, 41, 36, 47, 0xd9a441]];+ for (const [x0, y0, x1, y1, c] of fields) for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) px.set([(c >> 16) & 255, (c >> 8) & 255, c & 255, 255], (y * AW + x) * 4);+ const art2 = add(new Mesh(new PlaneGeometry(0.6, 0.78), new MeshStandardMaterial({ name: "artwork_fields", map: new DataTexture(AW, AH, px), roughness: 0.8 })), "picture_2", [X1 - 0.032, 1.5, 0.3]);+ art2.rotation.y = -Math.PI / 2;+ box("picture_2_frame", [0.03, 0.82, 0.64], [X1 - 0.015, 1.5, 0.3], std("frame_black", [0.02, 0.02, 0.02], 0.4));++ // Rug: a wool weave (the scan's normal map) under a pattern drawn here: a cream field with a diamond lattice and a+ // border band.+ const RUG: Vec3 = [3.0, 0.014, 2.3], GW = 384, GH = Math.round((GW * RUG[2]) / RUG[0]), rug = new Uint8Array(GW * GH * 4);+ for (let y = 0; y < GH; y++) for (let x = 0; x < GW; x++) {+ const e = Math.min(x, y, GW - 1 - x, GH - 1 - y); // texels from the nearest edge (128 texels a metre)+ const d = Math.abs(((x + y) % 44) - 22), d2 = Math.abs(((x - y + 4400) % 44) - 22);+ let c = 0xd9d0bd;+ if (e >= 14 && e < 22) c = 0x8a5a3e;+ else if (e >= 26 && e < 28) c = 0x4f5d63;+ else if (e >= 34 && (d < 1.5 || d2 < 1.5)) c = 0xbcae96;+ rug.set([(c >> 16) & 255, (c >> 8) & 255, c & 255, 255], (y * GW + x) * 4);+ }+ const rugMat = new MeshStandardMaterial({+ name: "rug", map: new DataTexture(GW, GH, rug), roughness: 1,+ normalMap: tex("poly_wool_herringbone_nor_gl_1k.jpg", false, [RUG[0] / 0.5, RUG[2] / 0.5]),+ });+ box("rug", RUG, [0, RUG[1] / 2, -1.35], rugMat);++ // Books and boxes in the shelves' open cubes (three columns, three rows above the drawers).+ const bookMats = [[0.55, 0.12, 0.08], [0.1, 0.22, 0.4], [0.75, 0.7, 0.6], [0.12, 0.3, 0.2], [0.7, 0.5, 0.15], [0.2, 0.2, 0.22], [0.6, 0.6, 0.62], [0.45, 0.25, 0.4]]+ .map((c, i) => std(`book_${i}`, c as Vec3, 0.7));+ const books = add(new Group(), "books", [0, 0, 0]);+ let nb = 0;+ for (const [u, zc] of SHELF_Z.entries()) {+ for (let row = 0; row < 3; row++) for (let col = 0; col < 3; col++) {+ if ((row * 3 + col + u * 4) % 3 === 2) continue; // some cubes stay empty+ const y0 = 0.425 + row * 0.385, zmid = zc + (col - 1) * 0.355;+ let z = zmid - 0.15;+ const count = 3 + Math.floor(r() * 4);+ for (let k = 0; k < count && z < zmid + 0.12; k++) {+ const th = 0.022 + r() * 0.03, h = 0.2 + r() * 0.1, d = 0.15 + r() * 0.07;+ box(`book_${nb++}`, [d, h, th], [X1 - 0.2 - 0.02 - (0.24 - d) / 2, y0 + h / 2, z + th / 2], bookMats[Math.floor(r() * bookMats.length)], books);+ z += th + 0.002;+ }+ }+ }+ // A few more lying on top.+ for (const [k, w] of [0.3, 0.27, 0.24].entries()) box(`book_flat_${k}`, [0.2, 0.035, w], [X1 - 0.2, 1.585 + k * 0.036, SHELF_Z[0] - 0.15], bookMats[[2, 1, 4][k]], books).rotation.y = 0.1 * k - 0.1;++ // -- floor lamp: the shade is the emitter (an area light a quarter of a square metre large)+ const brass = std("brass", [0.72, 0.55, 0.28], 0.5, 1);+ const LX = 1.55, LZ = Z0 + 0.45;+ add(new Mesh(new CylinderGeometry(0.15, 0.16, 0.025, 40), brass), "lamp_base", [LX, 0.0125, LZ]);+ add(new Mesh(new CylinderGeometry(0.012, 0.012, 1.32, 16), brass), "lamp_pole", [LX, 0.68, LZ]);+ const shadeMat = new MeshStandardMaterial({ name: "lamp_shade", color: new Color().setRGB(0.85, 0.8, 0.7), roughness: 1, side: "double", emissive: new Color().setRGB(1, 0.72, 0.42), emissiveIntensity: SHADE_NITS });+ add(new Mesh(new CylinderGeometry(0.17, 0.21, 0.3, 48, 1, true), shadeMat), "lamp_shade", [LX, 1.47, LZ]).power = 0;+ // -- pendant over the coffee table: an opal glass globe, the emitter itself (a third of a square metre)+ const PX = 0, PZ = -1.4, PY0 = 1.98, PR = 0.17;+ add(new Mesh(new CylinderGeometry(0.004, 0.004, RH - PY0 - PR, 8), std("pendant_cable", [0.02, 0.02, 0.02], 0.6)), "pendant_cable", [PX, (RH + PY0 + PR) / 2, PZ]);+ add(new Mesh(new CylinderGeometry(0.035, 0.06, 0.07, 32), brass), "pendant_cap", [PX, PY0 + PR + 0.02, PZ]);+ add(new Mesh(new CylinderGeometry(0.05, 0.05, 0.02, 32), brass), "pendant_rose", [PX, RH - 0.01, PZ]);+ const globeMat = new MeshStandardMaterial({ name: "pendant_globe", color: new Color().setRGB(0.85, 0.83, 0.78), roughness: 0.25, emissive: new Color().setRGB(1, 0.76, 0.5), emissiveIntensity: GLOBE_NITS });+ add(new Mesh(new SphereGeometry(PR, 48, 24), globeMat), "pendant_globe", [PX, PY0, PZ]).power = 0;++ const camera = new PerspectiveCamera(VIEWS[0].fov, 16 / 9, 0.05, 2000);+ camera.id = "camera";+ camera.position.set(...VIEWS[0].eye);+ camera.lookAt(...VIEWS[0].at);+ camera.setManualExposure(TIMES[2].ev); // (the frame script sets it from the sun)+ scene.add(camera);+ return { scene, camera, options: { name: "daylight-home", preset: "preview" as const, width: 1280, height: 720, overrides: { native: { maxBounces: 8 } } } };+}++// ---------------------------------------------------------------------------------------------- the scene, from the state+/** What the frame script shows now: eased towards what the state asks for, then left alone (the picture converges). */+let cur: { sun: Vec3; cam: number[]; paint: Vec3 } | null = null;+let shown: { scene: unknown; sun: string; cam: string; sofa: number } = { scene: null, sun: "", cam: "", sofa: -1 };++/** `a` moved towards `b` by the fraction k, landing on it when within `eps`. */+function approach(a: number[], b: readonly number[], k: number, eps: number) {+ let far = false;+ for (let i = 0; i < a.length; i++) {+ a[i] += (b[i] - a[i]) * k;+ if (Math.abs(b[i] - a[i]) > eps) far = true;+ }+ if (!far) for (let i = 0; i < a.length; i++) a[i] = b[i];+}++function frame(f: FrameContext<State>) {+ const s = f.state, t = TIMES[s.time], v = VIEWS[s.view];+ const sunTo: Vec3 = [t.el, t.az, t.ev], camTo = [...v.eye, ...v.at, v.fov];+ if (f.snap || !cur) cur = { sun: [...sunTo], cam: [...camTo], paint: [...PAINTS[s.paint]] };+ if (f.snap || shown.scene !== f.scene) shown = { scene: f.scene, sun: "", cam: "", sofa: -1 };+ const c = cur;+ // The sun takes about two seconds to get to another time of day; the camera and the paint are quicker.+ approach(c.sun, sunTo, 1 - Math.exp(-f.dt * 2.2), 0.02);+ approach(c.cam, camTo, 1 - Math.exp(-f.dt * 5), 0.002);+ approach(c.paint, PAINTS[s.paint], 1 - Math.exp(-f.dt * 8), 0.004);++ // Only what changed is set: a set sun re-bakes the sky, a set camera starts the picture's accumulation again.+ const sunKey = c.sun.join();+ if (shown.sun !== sunKey) {+ (f.object("sun") as DirectionalLight).setSunAngles(c.sun[0], c.sun[1]);+ // The exposure stays the day's until the sun is at the horizon, then opens as the twilight fades.+ const dusk = Math.min(1, Math.max(0, (c.sun[0] + 7) / 7.5)), day = dusk * dusk * (3 - 2 * dusk);+ f.camera.setManualExposure(NIGHT_EV + (c.sun[2] - NIGHT_EV) * day);+ shown.sun = sunKey;+ }+ const camKey = c.cam.join();+ if (shown.cam !== camKey) {+ f.camera.position.set(c.cam[0], c.cam[1], c.cam[2]);+ f.camera.lookAt(c.cam[3], c.cam[4], c.cam[5]);+ f.camera.fov = c.cam[6];+ shown.cam = camKey;+ }+ const paint = (f.object("wall_far") as Mesh).material.color;+ if (paint.r !== c.paint[0] || paint.g !== c.paint[1] || paint.b !== c.paint[2]) paint.setRGB(...c.paint);+ if (shown.sofa !== s.sofa) {+ const fabric = FABRICS[s.sofa];+ f.object("sofa")!.customData = fabric ? [...fabric, 1] : [0, 0, 0, 0];+ shown.sofa = s.sofa;+ }+ const lamp = f.object("lamp_shade")!, globe = f.object("pendant_globe")!;+ if (lamp.power !== (s.lamp ? 1 : 0)) lamp.power = s.lamp ? 1 : 0;+ if (globe.power !== (s.pendant ? 1 : 0)) globe.power = s.pendant ? 1 : 0;+}++export default defineGame<State>({+ state: { time: 2, paint: 0, sofa: 0, view: 0, lamp: false, pendant: false },+ setup,+ frame,+ handlers: {+ time(tx) {+ const s = tx.state;+ s.time = (s.time + 1) % TIMES.length;+ s.lamp = s.pendant = s.time === NIGHT;+ },+ paint(tx) {+ tx.state.paint = (tx.state.paint + 1) % PAINTS.length;+ },+ sofa(tx) {+ tx.state.sofa = (tx.state.sofa + 1) % FABRICS.length;+ },+ view(tx) {+ tx.state.view = (tx.state.view + 1) % VIEWS.length;+ },+ lamps(tx) {+ const on = !(tx.state.lamp || tx.state.pendant);+ tx.state.lamp = tx.state.pendant = on;+ },+ click(tx, ev: { target: string }) {+ const id = String(ev.target ?? ""), s = tx.state;+ if (id.startsWith("lamp_")) s.lamp = !s.lamp;+ else if (id.startsWith("pendant")) s.pendant = !s.pendant;+ else if (id === "sofa") s.sofa = (s.sofa + 1) % FABRICS.length;+ else if (id.startsWith("wall_")) s.paint = (s.paint + 1) % PAINTS.length;+ else if (OUTSIDE.some((p) => id.startsWith(p))) {+ s.time = (s.time + 1) % TIMES.length;+ s.lamp = s.pendant = s.time === NIGHT;+ } else tx.decide(false, `nothing happens when you click ${id || "there"}`);+ },+ },+ // (F for fabric: the native viewer flies its camera with W A S D.)+ keys: { T: "time", P: "paint", F: "sofa", V: "view", L: "lamps" },+});diff --git a/showcase/daylight-home/thumb.jpg b/showcase/daylight-home/thumb.jpgnew file mode 100644index 0000000..ab62775Binary files /dev/null and b/showcase/daylight-home/thumb.jpg differdiff --git a/showcase/hello/hello.game.ts b/showcase/hello/hello.game.tsnew file mode 100644index 0000000..c24fe7c--- /dev/null+++ b/showcase/hello/hello.game.ts@@ -0,0 +1,20 @@+import { BoxGeometry, Color, Mesh, MeshStandardMaterial, PerspectiveCamera, RectAreaLight, Scene, SkyColor, SphereGeometry } from "@threert/scene";+import { defineGame } from "@threert/gameplay";+export default defineGame<{ on: boolean }>({+ state: { on: true },+ setup() {+ const scene = new Scene();+ scene.environment = new SkyColor(0x101018, 0.2);+ const floor = new Mesh(new BoxGeometry(6, 0.2, 6), new MeshStandardMaterial({ color: 0x808080, roughness: 0.4 }));+ floor.id = "floor"; floor.position.y = -0.1; scene.add(floor);+ const ball = new Mesh(new SphereGeometry(0.5, 48, 24), new MeshStandardMaterial({ color: new Color().setRGB(1, 0.77, 0.34), metalness: 1, roughness: 0.2 }));+ ball.id = "ball"; ball.position.y = 0.5; scene.add(ball);+ const light = new RectAreaLight(0xffffff, 8000, 1, 1);+ light.id = "light"; light.position.set(0, 3, 0); light.lookAt(0, 0, 0); scene.add(light);+ const camera = new PerspectiveCamera(40, 16 / 9, 0.05, 100);+ camera.position.set(0, 1.4, 4); camera.lookAt(0, 0.5, 0); camera.setManualExposure(8); scene.add(camera);+ return { scene, camera, options: { name: "hello", preset: "preview" as const, width: 1280, height: 720 } };+ },+ frame(f) { (f.object("light") as RectAreaLight).intensity = f.state.on ? 8000 : 500; },+ handlers: { click(tx) { tx.state.on = !tx.state.on; } },+});diff --git a/showcase/jewellery/case.json b/showcase/jewellery/case.jsonnew file mode 100644index 0000000..63a3b4e--- /dev/null+++ b/showcase/jewellery/case.json@@ -0,0 +1,30 @@+{+ "id": "jewellery",+ "industry": "Commerce",+ "title": "Jeweller’s Window",+ "caption": "Gold, diamonds and pearls, turning under the lights",+ "blurb": "Three rings and a string of pearls on a polished black plinth under a jeweller’s soft boxes, at real size and built entirely in code. The gold mirrors the lights and the other pieces, each stone is a 57-facet brilliant cut whose light goes in, bounces off the back facets and comes out again, and it all stays right when you change the metal or the stone.",+ "controls": [+ {+ "input": "Click a piece",+ "does": "brings the camera close; again to return"+ },+ {+ "input": "M",+ "does": "yellow gold, rose gold, platinum"+ },+ {+ "input": "G",+ "does": "diamond, ruby, sapphire, emerald"+ },+ {+ "input": "Space",+ "does": "stops and resumes the turn"+ },+ {+ "input": "B",+ "does": "back to the whole display"+ }+ ],+ "credits": []+}diff --git a/showcase/jewellery/jewellery.game.ts b/showcase/jewellery/jewellery.game.tsnew file mode 100644index 0000000..252cf80--- /dev/null+++ b/showcase/jewellery/jewellery.game.ts@@ -0,0 +1,483 @@+// "The Jeweller's Window": a jeweller's product page as a live scene. Three rings and a pearl bracelet on a turntable+// of polished black stone in a small dark studio: a six-prong solitaire with a 2 ct brilliant (the hero, in the middle,+// on a velvet holder with the pearls around it), a half-eternity ring with seven small diamonds, and a plain+// comfort-fit band. Two soft boxes, a top panel and a fill panel light them (their cards are what the metal mirrors),+// two pin spots make the glints, a snooted lamp puts the glow on the paper behind. Everything is at real size (the+// rings are 2 cm across, the camera is 8 cm away) and built in code: no model or texture files.+//+// What tracing gives it: the polished metal mirrors the soft boxes, the other pieces and the pearls; each stone is a+// real brilliant cut (57 facets, flat) of clear glass with a diamond's index of refraction, so what you see in it is+// light that went in through the crown, bounced off the pavilion and came back out; the plinth mirrors all of it.+//+// How the stones are made to work live: `transmission: 1`, `ior` 2.42 (1.77 ruby / sapphire, 1.58 emerald), the+// colour as the tint. The live view traces 4 bounces, which is exactly a brilliant's light path (in, two reflections+// off the pavilion, out), so the cut returns the light panels and the stones are bright; the preset's 3 leave them+// dark, hence `maxBounces` below. Roughness 0.03 keeps the refraction sharp and lets a facet flash when it mirrors a+// pin spot. Small bright emissive spheres as sparkle lights put fireflies in the stones; spot lights do not. The+// pearls are a soft, slightly metallic base under a clear coat. The small stones stand clear of the band on prongs:+// set into the metal their pavilions had nothing to reflect and they went milky.+//+// How it turns: on screen the display turns in the studio, one turn in 80 s (a still of time t shows it where+// `f.time` puts it; live it advances by `f.dt` while `spin` is on). In the scene the display stands still and the+// studio (lights, paper) and the camera go around it, which is the same picture: see `frame`.+//+// click a piece the camera goes close to it and the table brings it to the front, swaying; click it again (or+// anything that is not a piece) to step back+// metal (M) yellow gold -> rose gold -> platinum, on every piece+// stone (G) the solitaire's stone: diamond -> ruby -> sapphire -> emerald+// spin (Space) stops / resumes the turntable (stopped, the picture converges)+// back (B) back to the whole display+import {+ BufferAttribute, BufferGeometry, Color, CylinderGeometry, Group, LatheGeometry, Mesh, MeshPhysicalMaterial, MeshStandardMaterial,+ Object3D, PerspectiveCamera, RectAreaLight, Scene, SkyColor, SphereGeometry, SpotLight, TorusGeometry, Vector3,+} from "@threert/scene";+import { defineGame, type FrameContext } from "@threert/gameplay";++type Vec3 = [number, number, number];+const MM = 0.001;+const DEG = Math.PI / 180;++const PIECES = ["solitaire", "pave", "band", "pearls"] as const;+type Piece = (typeof PIECES)[number];++interface State {+ /** Index into METALS / STONES. */+ metal: number;+ stone: number;+ /** The turntable turns. */+ spin: boolean;+ /** The piece the camera is close to ("" = the whole display). */+ focus: Piece | "";+}++// Linear reflectance of the polished alloys (18 ct yellow, 18 ct rose, platinum).+const METALS: { name: string; color: Vec3 }[] = [+ { name: "yellow gold", color: [1.0, 0.77, 0.36] },+ { name: "rose gold", color: [0.98, 0.66, 0.54] },+ { name: "platinum", color: [0.84, 0.83, 0.8] },+];+// The stone: its tint (what a pass through a facet keeps) and index of refraction.+const STONES: { name: string; color: Vec3; ior: number }[] = [+ { name: "diamond", color: [1, 1, 1], ior: 2.42 },+ { name: "ruby", color: [0.9, 0.02, 0.09], ior: 1.77 },+ { name: "sapphire", color: [0.02, 0.22, 0.8], ior: 1.77 },+ { name: "emerald", color: [0.04, 0.72, 0.3], ior: 1.58 },+];++// ---------------------------------------------------------------------------------------------------------------+// The display, in the turntable's frame (y = 0 is the top of the stone plinth; angles from +Z towards +X).++const PLINTH = { radius: 50 * MM, height: 12 * MM };+const RING_INNER = 8.6 * MM; // a size 7 finger+const TURN_START = 0; // the table's angle in the studio in the first frame+const TURN_RATE = (2 * Math.PI) / 80; // one turn in 80 s+const SWAY = 0.35; // while a piece is close: the table sways this far either way (rad)++/** Where each ring stands: polar position of its holder, the holder's size, and the ring's own turn on it. */+const STAND: Record<Exclude<Piece, "pearls">, { at: number; r: number; block: [number, number]; yaw: number }> = {+ solitaire: { at: 0, r: 0, block: [9 * MM, 9 * MM], yaw: 0.62 }, // three-quarter view in the first frame+ pave: { at: -140 * DEG, r: 34 * MM, block: [9.5 * MM, 5 * MM], yaw: -140 * DEG - 0.1 },+ band: { at: 140 * DEG, r: 34 * MM, block: [9.5 * MM, 5 * MM], yaw: 140 * DEG + 0.1 },+};+/** The pearls: a bracelet lying around the solitaire's holder, 15 pearls and a gold clasp bead. */+const PEARLS = { count: 15, radius: 2.8 * MM, pitch: 5.75 * MM, clasp: 150 * DEG };+const BRACELET = ((PEARLS.count + 1) * PEARLS.pitch) / (2 * Math.PI);++/** The camera for the whole display and for each piece: what it looks at (turntable frame), from how far and how+ * high, and the table angle that puts the piece in front. */+const VIEW: Record<Piece | "", { target: Vec3; dist: number; elev: number; front: number }> = {+ "": { target: [0, 17 * MM, 0], dist: 80 * MM, elev: 25 * DEG, front: TURN_START },+ solitaire: { target: [0, 26 * MM, 0], dist: 52 * MM, elev: 30 * DEG, front: TURN_START },+ pave: { target: on(STAND.pave.r, STAND.pave.at, 17 * MM), dist: 46 * MM, elev: 28 * DEG, front: -STAND.pave.at + 0.85 },+ band: { target: on(STAND.band.r, STAND.band.at, 14 * MM), dist: 50 * MM, elev: 26 * DEG, front: -STAND.band.at - 0.85 },+ pearls: { target: on(BRACELET * 0.6, 0.5, 7 * MM), dist: 46 * MM, elev: 24 * DEG, front: -0.5 },+};++function on(r: number, a: number, y: number): Vec3 {+ return [r * Math.sin(a), y, r * Math.cos(a)];+}+function polar(r: number, a: number): [number, number] {+ return [r * Math.sin(a), r * Math.cos(a)];+}++// ---------------------------------------------------------------------------------------------------------------+// Geometry++/** A geometry from triangles (9 numbers each), each with its own flat normal facing away from `inside`. */+function facets(tris: number[][], inside: Vec3): BufferGeometry {+ const pos: number[] = [], nor: number[] = [];+ for (const t of tris) {+ const [ax, ay, az, bx, by, bz, cx, cy, cz] = t;+ let nx = (by - ay) * (cz - az) - (bz - az) * (cy - ay), ny = (bz - az) * (cx - ax) - (bx - ax) * (cz - az), nz = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);+ const l = Math.hypot(nx, ny, nz) || 1;+ nx /= l; ny /= l; nz /= l;+ const out = nx * ((ax + bx + cx) / 3 - inside[0]) + ny * ((ay + by + cy) / 3 - inside[1]) + nz * ((az + bz + cz) / 3 - inside[2]) >= 0;+ if (out) pos.push(...t);+ else { pos.push(ax, ay, az, cx, cy, cz, bx, by, bz); nx = -nx; ny = -ny; nz = -nz; }+ for (let k = 0; k < 3; k++) nor.push(nx, ny, nz);+ }+ const g = new BufferGeometry();+ g.setAttribute("position", new BufferAttribute(new Float32Array(pos), 3));+ g.setAttribute("normal", new BufferAttribute(new Float32Array(nor), 3));+ return g;+}++/**+ * A round brilliant cut, 57 facets + a faceted girdle, diameter 1, the table up (+Y), the girdle around y = 0:+ * table 57 %, crown 14.8 % (34.5 degrees), pavilion 43.1 % (40.75 degrees), the proportions of an ideal cut.+ */+function brilliantGeometry(): BufferGeometry {+ const R = 0.5, g = 0.03, table = 0.285, hc = 0.148, hp = 0.431, star = 0.394, low = 0.12;+ const c8 = Math.cos(22.5 * DEG);+ const p = (r: number, a: number, y: number): Vec3 => [r * Math.sin(a * DEG), y, r * Math.cos(a * DEG)];+ const T = (k: number) => p(table, k * 45, g / 2 + hc);+ // The star points lie in the bezel (kite) planes and the lower-girdle points in the pavilion mains', so both are flat.+ const S = (k: number) => p(star, (k + 0.5) * 45, g / 2 + (hc * (R - star * c8)) / (R - table));+ const GU = (j: number) => p(R, j * 22.5, g / 2);+ const GL = (j: number) => p(R, j * 22.5, -g / 2);+ const L = (k: number) => p(low, (k + 0.5) * 45, -g / 2 - (hp * (R - low * c8)) / R);+ const C: Vec3 = [0, -g / 2 - hp, 0];+ const tris: number[][] = [];+ const tri = (a: Vec3, b: Vec3, c: Vec3) => tris.push([...a, ...b, ...c]);+ for (let k = 1; k < 7; k++) tri(T(0), T(k), T(k + 1));+ for (let k = 0; k < 8; k++) {+ tri(T(k), T(k + 1), S(k)); // star+ tri(T(k), S(k - 1), GU(2 * k)); tri(T(k), GU(2 * k), S(k)); // bezel (kite)+ tri(S(k), GU(2 * k), GU(2 * k + 1)); tri(S(k), GU(2 * k + 1), GU(2 * k + 2)); // upper girdle+ tri(L(k), GL(2 * k), GL(2 * k + 1)); tri(L(k), GL(2 * k + 1), GL(2 * k + 2)); // lower girdle+ tri(C, L(k - 1), GL(2 * k)); tri(C, GL(2 * k), L(k)); // pavilion main+ }+ for (let j = 0; j < 16; j++) { tri(GU(j), GU(j + 1), GL(j + 1)); tri(GU(j), GL(j + 1), GL(j)); }+ return facets(tris, [0, -0.1, 0]);+}++/**+ * A ring band around the Z axis (the finger's), its top at +Y: inner radius `inner`, a rounded comfort-fit section+ * `thick` x `width` (a superellipse, exponent `n`: 2 = oval, higher = flatter faces), `taper` narrowing it at the top.+ */+function bandGeometry(inner: number, thick: number, width: number, n = 2.6, taper = 0, around = 112, section = 20): BufferGeometry {+ const pos: number[] = [], idx: number[] = [];+ const pw = (v: number) => Math.sign(v) * Math.abs(v) ** (2 / n);+ for (let i = 0; i < around; i++) {+ const phi = (i / around) * 2 * Math.PI, top = Math.max(0, Math.sin(phi)) ** 2;+ const w = width * (1 - taper * top), t = thick * (1 - 0.5 * taper * top);+ for (let j = 0; j < section; j++) {+ const a = (j / section) * 2 * Math.PI;+ const r = inner + t / 2 + pw(Math.cos(a)) * (t / 2);+ pos.push(r * Math.cos(phi), r * Math.sin(phi), pw(Math.sin(a)) * (w / 2));+ }+ }+ for (let i = 0; i < around; i++)+ for (let j = 0; j < section; j++) {+ const a = i * section + j, b = ((i + 1) % around) * section + j, c = ((i + 1) % around) * section + ((j + 1) % section), d = i * section + ((j + 1) % section);+ idx.push(a, b, d, b, c, d);+ }+ const g = new BufferGeometry();+ g.setAttribute("position", new BufferAttribute(new Float32Array(pos), 3));+ g.setIndex(idx);+ g.computeVertexNormals();+ return g;+}++/** A round velvet holder: a low drum with a rounded shoulder, its base at y = 0. */+function holderGeometry(radius: number, height: number): BufferGeometry {+ const pts: { x: number; y: number }[] = [{ x: radius, y: 0 }];+ const c = Math.min(2.2 * MM, height * 0.45);+ for (let i = 0; i <= 8; i++) {+ const a = (i / 8) * 90 * DEG;+ pts.push({ x: radius - c + c * Math.cos(a), y: height - c + c * Math.sin(a) });+ }+ pts.push({ x: 0, y: height });+ return new LatheGeometry(pts, 56);+}++/** The backdrop: a floor that sweeps up into a wall with no corner (a paper cove), across X. */+function coveGeometry(): BufferGeometry {+ const prof: [number, number][] = [[0.7, 0]];+ const R = 0.28, zc = -0.3;+ for (let i = 0; i <= 14; i++) {+ const a = (i / 14) * 90 * DEG;+ prof.push([zc - R * Math.sin(a), R - R * Math.cos(a)]);+ }+ prof.push([zc - R, 1.0]);+ const pos: number[] = [], idx: number[] = [];+ prof.forEach(([z, y]) => pos.push(-1, y, z, 1, y, z));+ for (let i = 0; i < prof.length - 1; i++) idx.push(2 * i, 2 * i + 1, 2 * i + 2, 2 * i + 1, 2 * i + 3, 2 * i + 2);+ const g = new BufferGeometry();+ g.setAttribute("position", new BufferAttribute(new Float32Array(pos), 3));+ g.setIndex(idx);+ g.computeVertexNormals();+ return g;+}++/** One geometry from several, each placed by its mesh's transform: a piece's metal is then one object to move. */+function merge(parts: Mesh[]): BufferGeometry {+ const pos: number[] = [], nor: number[] = [], idx: number[] = [];+ for (const m of parts) {+ m.updateMatrix();+ const g = m.geometry.clone().applyMatrix4(m.matrix), base = pos.length / 3;+ for (const v of g.positions) pos.push(v);+ for (const v of g.normals) nor.push(v);+ for (const i of g.triangleIndices()) idx.push(base + i);+ }+ const g = new BufferGeometry();+ g.setAttribute("position", new BufferAttribute(new Float32Array(pos), 3));+ g.setAttribute("normal", new BufferAttribute(new Float32Array(nor), 3));+ g.setIndex(idx);+ return g;+}++// ---------------------------------------------------------------------------------------------------------------+// The scene++function build() {+ const scene = new Scene();+ scene.environment = new SkyColor(0x000000, 0);+ const rgb = (c: Vec3) => new Color().setRGB(...c);++ const metal = new MeshStandardMaterial({ name: "metal", color: rgb(METALS[0].color), metalness: 1, roughness: 0.05 });+ const gem = new MeshPhysicalMaterial({ name: "gem", color: rgb(STONES[0].color), metalness: 0, roughness: 0.03, transmission: 1, ior: STONES[0].ior });+ const melee = new MeshPhysicalMaterial({ name: "melee", color: rgb([1, 1, 1]), metalness: 0, roughness: 0.03, transmission: 1, ior: 2.42 });+ const pearl = new MeshPhysicalMaterial({ name: "pearl", color: rgb([0.74, 0.65, 0.56]), metalness: 0.3, roughness: 0.2, clearcoat: 1, clearcoatRoughness: 0.03 });+ const velvet = new MeshStandardMaterial({ name: "velvet", color: rgb([0.010, 0.012, 0.024]), roughness: 1 });+ const stone = new MeshStandardMaterial({ name: "plinth", color: rgb([0.018, 0.018, 0.02]), roughness: 0.03 });+ const paper = new MeshStandardMaterial({ name: "backdrop", color: rgb([0.022, 0.023, 0.028]), roughness: 0.95, side: "double" });++ // The studio (the paper cove and the lights) is one group, the display another. On screen the display turns in the+ // studio; in the scene it is the studio, with the camera, that turns around the display (see `frame`).+ const studio = new Group();+ studio.id = "studio";+ scene.add(studio);+ const cove = new Mesh(coveGeometry(), paper);+ cove.id = "backdrop";+ studio.add(cove);++ const table = new Group();+ table.id = "table";+ table.position.y = PLINTH.height;+ scene.add(table);++ const add = (parent: Object3D, id: string, mesh: Mesh, at?: Vec3) => {+ mesh.id = id;+ if (at) mesh.position.set(...at);+ parent.add(mesh);+ return mesh;+ };++ // The plinth: a polished black stone disc with a chamfered edge.+ const ch = 1.2 * MM;+ const disc = new LatheGeometry([{ x: PLINTH.radius, y: -PLINTH.height }, { x: PLINTH.radius, y: -ch }, { x: PLINTH.radius - ch, y: 0 }, { x: 0, y: 0 }], 96);+ add(table, "plinth", new Mesh(disc, stone));++ const brilliant = brilliantGeometry();+ /** A part of a piece, placed in the piece's frame (not in the scene: `merge` makes one mesh of a piece's parts). */+ const part = (geometry: BufferGeometry, at: Vec3 = [0, 0, 0], scale = 1) => {+ const m = new Mesh(geometry, metal);+ m.position.set(...at);+ m.scale.set(scale, scale, scale);+ return m;+ };++ // A ring on its velvet holder: a group at the ring's centre, the band around its Z axis, the head at +Y.+ const ringOn = (piece: Exclude<Piece, "pearls">, outer: number) => {+ const s = STAND[piece], [x, z] = polar(s.r, s.at);+ add(table, `${piece}.holder`, new Mesh(holderGeometry(...s.block), velvet), [x, 0, z]);+ const ring = new Group();+ ring.id = `${piece}.ring`;+ ring.position.set(x, s.block[1] - 1.6 * MM + outer, z); // 1.6 mm deep in the holder's slot+ ring.rotation.y = s.yaw;+ table.add(ring);+ return ring;+ };++ // 1. The solitaire: a tapered band, a six-prong head, an 8 mm (2 ct) brilliant.+ {+ const thick = 1.7 * MM, outer = RING_INNER + thick * 0.8, D = 8 * MM, yg = outer + 0.431 * D + 0.5 * MM;+ const ring = ringOn("solitaire", RING_INNER + thick);+ const rail = new TorusGeometry(2.75 * MM, 0.3 * MM, 10, 40);+ rail.rotateX(Math.PI / 2);+ const parts = [+ part(bandGeometry(RING_INNER, thick, 3.1 * MM, 2.6, 0.3)),+ part(new CylinderGeometry(1.5 * MM, 2.0 * MM, 1.6 * MM, 24), [0, outer + 0.3 * MM, 0]), // the collet under the stone+ part(rail, [0, yg - 1.75 * MM, 0]),+ ];+ const tip = new SphereGeometry(0.52 * MM, 16, 10);+ for (let k = 0; k < 6; k++) {+ const a = (k * 60 + 30) * DEG, sx = Math.sin(a), sz = Math.cos(a);+ const at = (r: number, y: number) => new Vector3(sx * r, y, sz * r);+ const from = at(1.3 * MM, outer - 0.2 * MM), to = at(D / 2 + 0.2 * MM, yg + 0.25 * MM), len = from.distanceTo(to);+ const prong = part(new CylinderGeometry(0.36 * MM, 0.46 * MM, len, 12), from.clone().add(to).multiplyScalar(0.5).toArray());+ // (Its axis, +Y, along the prong: a turn about the horizontal axis square to it.)+ prong.quaternion.setFromAxisAngle(new Vector3(sz, 0, -sx), Math.acos((to.y - from.y) / len));+ parts.push(prong, part(tip, at(D / 2 - 0.1 * MM, yg + 0.5 * MM).toArray()));+ }+ add(ring, "solitaire.metal", new Mesh(merge(parts), metal));+ add(ring, "solitaire.stone", new Mesh(brilliant, gem), [0, yg, 0]).scale.set(D, D, D);+ }++ // 2. The half-eternity ring: seven 2.2 mm brilliants across the top, each pair sharing two prongs, so the stones+ // stand clear of the band with air under their pavilions (set into the metal they would have nothing to return).+ {+ const thick = 1.6 * MM, outer = RING_INNER + thick, D = 2.2 * MM, step = (2.42 * MM) / outer, lift = 0.95 * MM;+ const ring = ringOn("pave", outer);+ const bead = new SphereGeometry(0.36 * MM, 12, 8), post = new CylinderGeometry(0.24 * MM, 0.3 * MM, lift + 0.3 * MM, 8);+ /** At angle `a` from the top of the ring, `r` from its axis, `z` along it, its +Y pointing outwards. */+ const radial = (geometry: BufferGeometry, a: number, r: number, z: number, scale = 1) => {+ const m = part(geometry, [r * Math.sin(a), r * Math.cos(a), z], scale);+ m.rotation.z = -a;+ return m;+ };+ const parts = [part(bandGeometry(RING_INNER, thick, 2.5 * MM, 3.2))], stones: Mesh[] = [];+ for (let k = -3; k <= 3; k++) stones.push(radial(brilliant, k * step, outer + lift, 0, D));+ for (let k = -4; k <= 3; k++)+ for (const side of [-1, 1]) {+ const a = (k + 0.5) * step, z = side * 0.86 * MM;+ parts.push(radial(post, a, outer + (lift - 0.3 * MM) / 2, z), radial(bead, a, outer + lift + 0.12 * MM, z * 0.93));+ }+ add(ring, "pave.metal", new Mesh(merge(parts), metal));+ add(ring, "pave.stones", new Mesh(merge(stones), melee));+ }++ // 3. The plain band: 5 mm wide, domed outside, comfort-fit inside.+ {+ const thick = 1.9 * MM;+ add(ringOn("band", RING_INNER + thick), "band.metal", new Mesh(bandGeometry(RING_INNER, thick, 5 * MM, 2.3), metal));+ }++ // 4. The pearls: a bracelet on the stone around the middle holder, closed by a gold bead.+ {+ const ball = new SphereGeometry(PEARLS.radius, 32, 16), pearls: Mesh[] = [];+ for (let i = 0; i < PEARLS.count; i++) {+ const [x, z] = polar(BRACELET, PEARLS.clasp + ((i + 1) / (PEARLS.count + 1)) * 2 * Math.PI);+ pearls.push(part(ball, [x, PEARLS.radius, z]));+ }+ add(table, "pearls.strand", new Mesh(merge(pearls), pearl));+ const [x, z] = polar(BRACELET, PEARLS.clasp);+ add(table, "pearls.clasp", new Mesh(new SphereGeometry(2.2 * MM, 24, 14), metal), [x, 2.4 * MM, z]);+ }++ // The lights: two soft boxes, a top panel and a fill panel; their cards are what the metal and the stones mirror.+ const panel = (id: string, at: Vec3, size: [number, number], nits: number, color: Vec3) => {+ const l = new RectAreaLight(rgb(color), nits, ...size);+ l.id = id;+ l.position.set(...at);+ l.lookAt(0, 0.03, 0);+ studio.add(l);+ };+ panel("key", [-0.26, 0.3, 0.2], [0.34, 0.24], 9000, [1, 0.95, 0.88]);+ panel("strip", [0.32, 0.14, -0.06], [0.1, 0.42], 12000, [0.86, 0.93, 1]);+ panel("top", [0.03, 0.4, 0.0], [0.5, 0.4], 6000, [1, 0.98, 0.95]);+ panel("fill", [0.25, 0.12, 0.27], [0.3, 0.22], 3000, [1, 0.97, 0.93]);+ const spot = (id: string, at: Vec3, to: Vec3, candela: number, color: Vec3, angle: number, penumbra: number, radius: number) => {+ const l = new SpotLight(rgb(color), candela, 2, angle, penumbra), target = new Object3D();+ l.id = id;+ l.radius = radius;+ l.position.set(...at);+ target.position.set(...to);+ l.target = target;+ studio.add(l);+ studio.add(target);+ };+ // A snooted lamp on the paper behind the display: the glow the pieces stand against.+ spot("glow", [0, 0.55, 0], [0, 0, -0.17], 5500, [0.75, 0.82, 1], 16 * DEG, 1, 0.02);+ // Two pin spots, small and far: a facet or a point of metal lights up only where it mirrors one to the camera.+ spot("pin_a", [0.14, 0.36, 0.3], [0, 0.03, 0], 900, [1, 0.95, 0.85], 9 * DEG, 0.5, 0.012);+ spot("pin_b", [-0.1, 0.22, 0.42], [0, 0.03, 0], 700, [0.85, 0.93, 1], 9 * DEG, 0.5, 0.012);++ const camera = new PerspectiveCamera(32, 16 / 9, 0.005, 20);+ camera.id = "camera";+ camera.setManualExposure(11.2);+ scene.add(camera);+ return { scene, camera };+}++// ---------------------------------------------------------------------------------------------------------------+// The frame: the scene for the state. The table's angle and the camera ease towards where the state puts them.++/** The display's angle in the studio (rad), and the camera there: where it is and what it looks at. */+let turn = TURN_START;+const eye = new Vector3(), look = new Vector3();+const goalEye = new Vector3(), goalLook = new Vector3();+/** What the pieces are made of in the frame before, and the camera's nudge after that changes: its clock, time left. */+let shown = "", nudgeClock = 0, nudge = 0;++function frame(f: FrameContext<State>) {+ const s = f.state, view = VIEW[s.focus];++ const metal = (f.object("band.metal") as Mesh).material as MeshStandardMaterial;+ metal.color.setRGB(...METALS[s.metal % METALS.length].color);+ const gem = (f.object("solitaire.stone") as Mesh).material as MeshPhysicalMaterial;+ const st = STONES[s.stone % STONES.length];+ gem.color.setRGB(...st.color);+ if (gem.ior !== st.ior) { gem.ior = st.ior; gem.needsUpdate = true; }++ // The table: turning by itself, or holding the chosen piece in front of the camera and swaying a little.+ if (s.focus) {+ const goal = view.front + (s.spin ? SWAY * Math.sin(f.time * 0.4) : 0);+ const d = ((((goal - turn + Math.PI) % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI)) - Math.PI;+ turn = f.snap || Math.abs(d) < 1e-4 ? goal : turn + d * (1 - Math.exp(-f.dt * 2.5));+ } else if (f.snap) turn = TURN_START + (s.spin ? TURN_RATE * f.time : 0);+ else if (s.spin) turn += TURN_RATE * f.dt;++ // The camera in the studio: at the piece (which rides the table), from the front.+ const [tx, ty, tz] = view.target, c = Math.cos(turn), sn = Math.sin(turn);+ goalLook.set(tx * c + tz * sn, PLINTH.height + ty, -tx * sn + tz * c);+ goalEye.set(goalLook.x, goalLook.y + view.dist * Math.sin(view.elev), goalLook.z + view.dist * Math.cos(view.elev));+ // (Arrived means arrived: a camera that still creeps keeps the renderer from settling.)+ const k = f.snap || eye.distanceTo(goalEye) + look.distanceTo(goalLook) < 0.05 * MM ? 1 : 1 - Math.exp(-f.dt * 3.5);+ eye.lerp(goalEye, k);+ look.lerp(goalLook, k);++ // A new metal or stone: the camera shifts a fraction of a millimetre for a second. With everything dead still the+ // live view keeps its long history, and the stone would show patches of its last colour for a while.+ const showing = `${s.metal}/${s.stone}`;+ if (f.snap) nudge = nudgeClock = 0;+ else if (showing !== shown) nudge = 1;+ shown = showing;+ if (nudge > 0) { nudge -= f.dt; nudgeClock += f.dt; }+ const ex = eye.x + 0.4 * MM * Math.sin(nudgeClock * 1.3);++ // The display turns in the studio. Seen from the display, the studio (its lights and its paper) and the camera turn+ // the other way around it, and that is what the scene does: lights and a sheet of paper cost nothing to move, 40 000+ // triangles of jewellery do, and the live view follows a moving camera exactly but a moving mirror only roughly (a+ // turning ring left a trail on the backdrop below full render scale). The picture is the same.+ const studio = f.object("studio")!;+ if (studio.rotation.y !== -turn) studio.rotation.y = -turn;+ f.camera.position.set(ex * c - eye.z * sn, eye.y, ex * sn + eye.z * c);+ f.camera.lookAt(look.x * c - look.z * sn, look.y, look.x * sn + look.z * c);+}++export default defineGame<State>({+ state: { metal: 0, stone: 0, spin: true, focus: "" },++ setup() {+ const { scene, camera } = build();+ return { scene, camera, options: { name: "jewellery", preset: "preview" as const, width: 1280, height: 720, overrides: { native: { maxBounces: 8 } } } };+ },++ frame,++ handlers: {+ /** A piece (any part of it, or its holder): go close; the piece the camera is at, or anything else: step back. */+ click(tx, ev: { target?: string }) {+ const piece = PIECES.find((p) => ev.target?.startsWith(p + "."));+ tx.decide(piece !== undefined || tx.state.focus !== "", "click a ring or the pearls");+ tx.state.focus = piece === undefined || piece === tx.state.focus ? "" : piece;+ },+ metal(tx) {+ tx.state.metal = (tx.state.metal + 1) % METALS.length;+ },+ stone(tx) {+ tx.state.stone = (tx.state.stone + 1) % STONES.length;+ },+ spin(tx) {+ tx.state.spin = !tx.state.spin;+ },+ back(tx) {+ tx.decide(tx.state.focus !== "", "already looking at the whole display");+ tx.state.focus = "";+ },+ },++ keys: { M: "metal", G: "stone", Space: "spin", B: "back" },+});diff --git a/showcase/jewellery/thumb.jpg b/showcase/jewellery/thumb.jpgnew file mode 100644index 0000000..60eadb9Binary files /dev/null and b/showcase/jewellery/thumb.jpg differdiff --git a/showcase/moon-phases/CREDITS.md b/showcase/moon-phases/CREDITS.mdnew file mode 100644index 0000000..1837a94--- /dev/null+++ b/showcase/moon-phases/CREDITS.md@@ -0,0 +1,13 @@+# Moon Phases: credits++Files in `assets/showcase/moon-phases/` (1.3 MB together). NASA imagery is not subject to copyright in the United+States (NASA media usage guidelines, https://www.nasa.gov/nasa-brand-center/images-and-media/); the SVS states that+its content is in the public domain (https://svs.gsfc.nasa.gov/help/).++| File | What it is | Author | Licence | Source |+|---|---|---|---|---|+| `earth_bmng_2k.jpg` | Earth colour map, 2048 x 1024. Blue Marble Next Generation with topography and bathymetry, December 2004, scaled down from 5400 x 2700; water lifted under a blue veil and land brightened a little (the original's sea is near black), done here with Pillow | NASA Earth Observatory (Blue Marble Next Generation, by Reto Stöckli) | Public domain (NASA) | https://assets.science.nasa.gov/content/dam/science/esd/eo/images/bmng/bmng-topography-bathymetry/december/world.topo.bathy.200412.3x5400x2700.jpg (NASA Visible Earth record 73909; its old page, visibleearth.nasa.gov/images/73909, now redirects to science.nasa.gov) |+| `earth_rough_1k.jpg` | Earth roughness map, 1024 x 512: water glossy, land matt. Made here from the map above (a mask of where it is blue) | derived from the same NASA image | Public domain (NASA) | as above |+| `moon_lroc_2k.jpg` | Moon colour map, 2048 x 1024. CGI Moon Kit, LROC WAC colour mosaic (`lroc_color_poles_2k.tif`), converted to JPEG | NASA's Scientific Visualization Studio, from Lunar Reconnaissance Orbiter Camera data | Public domain (NASA) | https://svs.gsfc.nasa.gov/4720/ (file: https://svs.gsfc.nasa.gov/vis/a000000/a004700/a004720/lroc_color_poles_2k.tif) |++The stars are made in the case's code (a generated tile); no file.diff --git a/showcase/moon-phases/assets/earth_bmng_2k.jpg b/showcase/moon-phases/assets/earth_bmng_2k.jpgnew file mode 100644index 0000000..cabb331Binary files /dev/null and b/showcase/moon-phases/assets/earth_bmng_2k.jpg differdiff --git a/showcase/moon-phases/assets/earth_rough_1k.jpg b/showcase/moon-phases/assets/earth_rough_1k.jpgnew file mode 100644index 0000000..80bd012Binary files /dev/null and b/showcase/moon-phases/assets/earth_rough_1k.jpg differdiff --git a/showcase/moon-phases/assets/moon_lroc_2k.jpg b/showcase/moon-phases/assets/moon_lroc_2k.jpgnew file mode 100644index 0000000..1a4951aBinary files /dev/null and b/showcase/moon-phases/assets/moon_lroc_2k.jpg differdiff --git a/showcase/moon-phases/case.json b/showcase/moon-phases/case.jsonnew file mode 100644index 0000000..796d200--- /dev/null+++ b/showcase/moon-phases/case.json@@ -0,0 +1,43 @@+{+ "id": "moon-phases",+ "industry": "Education",+ "title": "Moon Phases",+ "caption": "One Sun, one light: phases and eclipses, traced",+ "blurb": "An orrery of the Sun, the Earth and the Moon (not to scale) with the Sun as its only light. The Moon’s lit half, the phase seen from the ground, the Moon’s shadow crossing the Earth and the Earth’s shadow putting the Moon out are not scripted: they fall out of where the three bodies are.",+ "controls": [+ {+ "input": "P",+ "does": "jumps to the next phase: new, half, full, half"+ },+ {+ "input": "E",+ "does": "plays a solar eclipse, then a lunar one"+ },+ {+ "input": "V, or click the Earth or the Moon",+ "does": "stands on the Earth and looks up, and back"+ },+ {+ "input": "Space",+ "does": "pauses the month"+ },+ {+ "input": "F, S",+ "does": "faster, slower"+ }+ ],+ "credits": [+ {+ "what": "Earth colour map (Blue Marble Next Generation, December 2004, with topography and bathymetry; scaled down, sea brightened) and the roughness map derived from it",+ "by": "NASA Earth Observatory (Reto Stöckli)",+ "licence": "Public domain (NASA)",+ "url": "https://assets.science.nasa.gov/content/dam/science/esd/eo/images/bmng/bmng-topography-bathymetry/december/world.topo.bathy.200412.3x5400x2700.jpg"+ },+ {+ "what": "Moon colour map (CGI Moon Kit, LROC colour mosaic, 2k)",+ "by": "NASA's Scientific Visualization Studio",+ "licence": "Public domain (NASA)",+ "url": "https://svs.gsfc.nasa.gov/4720/"+ }+ ]+}diff --git a/showcase/moon-phases/moon-phases.game.ts b/showcase/moon-phases/moon-phases.game.tsnew file mode 100644index 0000000..e09f287--- /dev/null+++ b/showcase/moon-phases/moon-phases.game.ts@@ -0,0 +1,357 @@+// "Moon Phases": a tabletop orrery of the Sun, the Earth and the Moon, path-traced. The Sun is the only light in the+// scene, and everything the model teaches follows from that and the geometry: the lit half of the Moon, the phase it+// shows to the Earth, the Moon's shadow crossing the Earth (a solar eclipse), the Earth's shadow taking the Moon+// (a lunar eclipse), the faint earthshine on the Moon's dark side. None of it is scripted: the frame script only puts+// the three bodies where the clock says they are.+//+// A model, not the sky: sizes and distances are NOT to scale (a 36 cm Earth, a 10 cm Moon 70 cm from it, a 16 cm+// Sun 1.6 m away). So that most months still pass without an eclipse, the Moon's orbit is tilted 34 degrees instead+// of 5.1 (with bodies this big next to their orbits, eclipse seasons are still longer than the sky's). The Earth turns+// twice a month instead of 29.5, so the continents can be followed. With the Sun this near, the half moons come 64+// degrees from the Sun instead of 90, and the full moon is lit half as strongly as the Earth. And the Earth has no+// air: a totally eclipsed Moon goes black here, not red. Kept: the Earth's 23.4 degree tilt, the Moon keeping one+// face to the Earth, and the calendar (the month, the year, the eclipse year).+//+// The view turns with the Earth round the Sun, so the Sun stays on the left. Seen like that, the stars, the Earth's+// axis and the line where the Moon's tilted orbit crosses the Earth's (the nodes) swing slowly backwards, once a year.+// An eclipse needs a new or full moon while the nodes point at the Sun: twice a year, the eclipse seasons.+//+// Inputs+// pause (Space) stop / resume time+// faster / slower (F / S) time at 1/8 .. 2 times the default (one orbit of the Moon in 25 s)+// phase (P) on to the next of new moon, half moon (waxing), full moon, half moon (waning); held 6 s+// eclipse (E) on to the next solar eclipse, in slow motion; pressed again, the lunar eclipse after it+// view (V) the orrery from above and to the side <-> standing on the Earth, looking up at the Moon+// click the Earth or the Moon: switch the view; the Sun: pause; the sky: next phase+//+// Time: the state holds where the clock stood (`at`, in months since new moon 0), when that was (`since`) and the+// speed; `frame` computes every position from them and the clock. Until a control is touched the clock is the scene's+// own time (`f.time`), so the first frame, and a render at any `--time`, is always the same picture.+import { Color, CylinderGeometry, DataTexture, Mesh, MeshBasicMaterial, MeshStandardMaterial, PerspectiveCamera, PointLight, Quaternion, Scene, SkyColor, SphereGeometry, Texture, TorusGeometry, Vector3 } from "@threert/scene";+import { defineGame, type FrameContext } from "@threert/gameplay";++// ---------------------------------------------------------------------------------------------- the model (metres)+const R_EARTH = 0.18, R_MOON = 0.05, R_SUN = 0.08;+const D_MOON = 0.7; // Earth centre to Moon centre+const D_SUN = 1.6; // Earth centre to Sun centre (the Sun is at -X)+const TILT = (23.4 * Math.PI) / 180; // the Earth's axis+const INCL = (34 * Math.PI) / 180; // the Moon's orbit against the Earth's (5.1 degrees in the sky)+const SUN_NITS = 92000; // the Sun globe's luminance+const SUN_CD = SUN_NITS * Math.PI * R_SUN * R_SUN; // the same globe as a light: luminance x its disc++// The calendar, in synodic months (new moon to new moon, 29.53 days).+const YEAR = 12.369; // the stars and the Earth's axis come round+const ECLIPSE_YEAR = 11.738; // the nodes come round (346.6 days)+const SPINS = 2; // turns of the Earth a month (29.5 in the sky)+const TAU = Math.PI * 2;+/** The direction of the nodes, ahead of the Sun's: they point at the Sun at new moon 6. */+const node = (m: number) => (TAU * (6 - m)) / ECLIPSE_YEAR;+/** How far the Moon is above the Earth's orbital plane, -1..1 of its largest. */+const lift = (m: number) => Math.sin(TAU * m - node(m));++/** The half moons, as fractions of the month: where the Moon is half lit as seen from the Earth. With the Sun this+ * near that is 64 degrees from the Sun, not the sky's 90. */+const HALF = Math.acos(D_MOON / D_SUN) / TAU;+const PHASES = [0, HALF, 0.5, 1 - HALF];++const START = 3.2; // a little after the waxing half moon, three months before an eclipse season+const RATES = [0.005, 0.01, 0.02, 0.04, 0.08]; // months a second+const NORMAL = 3;+const SLOW = 1; // an eclipse is watched at RATES[SLOW] at most+const HOLD = 6; // seconds a phase is held before time runs on+const ECLIPSE_HOLD = 2.5; // seconds before an eclipse starts to move (the sweep to it takes that long)++interface State {+ /** `tx.now` (ms) when the clock was last set (later than now: held until then); 0: untouched, the scene's time. */+ since: number;+ /** Months on the clock at `since`. */+ at: number;+ /** Months from `at` that pass in slow motion (an eclipse under way). */+ slow: number;+ /** Index into RATES. */+ speed: number;+ paused: boolean;+ /** `tx.now` of the first touch, while the clock still counts from wherever the Moon was then (0 once a jump has+ * set it outright). Only the frame script knows how long the scene had run before that. */+ rel: number;+ /** Jumps so far (the frame script sweeps to a new one instead of cutting). */+ jumps: number;+ /** The eclipse shown last. */+ eclipse: "solar" | "lunar";+ view: "orrery" | "earth";+}++// ---------------------------------------------------------------------------------------------- the clock+/** The months on the clock at `now` (ms), as far as the state says. */+function months(s: Readonly<State>, now: number): number {+ if (s.paused || !s.since) return s.at;+ const t = Math.max(0, (now - s.since) / 1000);+ const rate = RATES[s.speed], slowRate = Math.min(rate, RATES[SLOW]);+ const tSlow = s.slow / slowRate;+ return t < tSlow ? s.at + slowRate * t : s.at + s.slow + rate * (t - tSlow);+}++/** Scene time (s) at the first touch, kept per touch: what the untouched clock had run before the state took over. */+let latch = { rel: 0, t: 0 };+function clock(f: FrameContext<State>): number {+ const s = f.state;+ if (!s.since) return s.at + RATES[s.speed] * f.time;+ if (!s.rel) return months(s, f.now);+ if (latch.rel !== s.rel) latch = { rel: s.rel, t: Math.max(0, f.time - (f.now - s.rel) / 1000) };+ return months(s, f.now) + RATES[NORMAL] * latch.t;+}++// ---------------------------------------------------------------------------------------------- the scene+const UP = new Vector3(0, 1, 0), Z = new Vector3(0, 0, 1);+const qa = new Quaternion(), qb = new Quaternion();+/** A direction in the Earth's orbital plane, `a` radians ahead of the Sun's (the way the Moon goes round). */+const dir = (a: number, out: Vector3) => out.set(-Math.cos(a), 0, Math.sin(a));+const X = new Vector3(1, 0, 0);+const va = new Vector3(), vb = new Vector3(), moonAt = new Vector3(), probe = new Vector3();++/** Where the Moon is at month `m`, on its tilted orbit: `u` from the ascending node, the node line `om` ahead of the+ * Sun's direction. */+function moonPosition(m: number, out: Vector3): Vector3 {+ const om = node(m), u = TAU * m - om;+ dir(om, va);+ dir(om + Math.PI / 2, vb).multiplyScalar(Math.cos(INCL));+ vb.y = Math.sin(INCL);+ return out.set(0, 0, 0).addScaledVector(va, D_MOON * Math.cos(u)).addScaledVector(vb, D_MOON * Math.sin(u));+}++/** The Earth's full shadow at the Moon's distance (a cone that widens: this Sun is smaller than this Earth). */+const UMBRA = R_EARTH + (D_MOON * (R_EARTH - R_SUN)) / D_SUN;+/** How far the Moon's centre is from the axis of the Earth's shadow at month `m` (near a full moon). */+const offAxis = (m: number) => Math.hypot(moonPosition(m, probe).y, probe.z);++const CAM = { pos: [-1.1, 0.9, 1.75] as const, target: [-0.63, -0.1, 0] as const, fov: 44 };+const EARTH_VIEW_FOV = 30;+const EV = 8;++/** The sweep to a jump's target: from the months shown when it came. */+let shown = START;+let sweep = { jumps: 0, from: START, t0: 0, dur: 0 };+const smooth = (k: number) => k * k * (3 - 2 * k);++function frame(f: FrameContext<State>) {+ const s = f.state;+ const target = clock(f);+ if (f.snap) sweep = { jumps: s.jumps, from: target, t0: 0, dur: 0 };+ else if (sweep.jumps !== s.jumps) sweep = { jumps: s.jumps, from: shown, t0: f.time, dur: Math.min(2.4, 0.8 + 0.3 * Math.abs(target - shown)) };+ const k = sweep.dur > 0 ? (f.time - sweep.t0) / sweep.dur : 1;+ const m = k >= 0 && k < 1 ? sweep.from + (target - sweep.from) * smooth(k) : target;+ // The bodies moved, so the light on them changed: say so to the renderer (a light edit shortens the history its+ // live view averages over, which otherwise follows a turning surface and smears day into night).+ if (m !== shown) (f.object("sunlight") as PointLight).intensity = SUN_CD * (1 + 0.002 * Math.sin(f.time * 17));+ shown = m;++ moonPosition(m, moonAt);+ const orbit = f.object("orbit")!;+ orbit.quaternion.setFromAxisAngle(UP, Math.PI + node(m)).multiply(qb.setFromAxisAngle(X, INCL - Math.PI / 2));+ orbit.visible = s.view === "orrery";+ const moon = f.object("moon")!;+ moon.position.copy(moonAt);+ // One face to the Earth: the map's centre (the near side) is the sphere's +X.+ moon.quaternion.setFromAxisAngle(UP, Math.atan2(moonAt.z, -moonAt.x));++ // The Earth: turning on an axis that keeps pointing at the same stars.+ const year = (TAU * m) / YEAR;+ qa.setFromAxisAngle(UP, 0.7 + (TAU * START) / YEAR - year).multiply(qb.setFromAxisAngle(Z, TILT));+ f.object("earth_axis")!.quaternion.copy(qa);+ f.object("earth")!.quaternion.copy(qa).multiply(qb.setFromAxisAngle(UP, TAU * (m - START) * SPINS + 3.2));+ f.object("sky")!.quaternion.setFromAxisAngle(UP, -year);++ const cam = f.camera;+ if (s.view === "earth") {+ // Standing where the Moon is overhead, looking up at it.+ va.copy(moonAt).normalize();+ cam.position.copy(va).multiplyScalar(R_EARTH + 0.012);+ cam.fov = EARTH_VIEW_FOV;+ cam.lookAt(moonAt);+ cam.setManualExposure(EV - 0.8); // eyes used to the night+ } else {+ cam.position.set(...CAM.pos);+ cam.fov = CAM.fov;+ cam.lookAt(...CAM.target);+ cam.setManualExposure(EV);+ }+}++/** A small deterministic generator (mulberry32). */+function rng(seed: number): () => number {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) >>> 0;+ let t = a;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++/** A tile of faint stars (made here: no file). */+function starTile(size: number, count: number): DataTexture {+ const px = new Uint8Array(size * size * 4);+ for (let i = 3; i < px.length; i += 4) px[i] = 255;+ const r = rng(20261112);+ const put = (x: number, y: number, c: [number, number, number], k: number) => {+ const o = (((y + size) % size) * size + ((x + size) % size)) * 4;+ for (let j = 0; j < 3; j++) px[o + j] = Math.min(255, px[o + j] + c[j] * k);+ };+ for (let i = 0; i < count; i++) {+ const x = Math.floor(r() * size), y = Math.floor(r() * size);+ const mag = Math.pow(r(), 5); // few bright, many faint+ const warm = r();+ const c: [number, number, number] = [200 + 55 * warm, 215, 255 - 70 * warm];+ const k = 0.16 + 0.84 * mag;+ put(x, y, c, k);+ if (mag > 0.25) for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) put(x + dx, y + dy, c, k * 0.35);+ }+ return new DataTexture(size, size, px);+}++/** A clock change: the state takes the clock over from the scene's time at the first one. */+function touch(tx: { state: State; now: number }) {+ const s = tx.state;+ if (!s.since) s.rel = tx.now;+ const cur = months(s, tx.now);+ s.slow = Math.max(0, s.slow - (cur - s.at));+ s.at = cur;+ s.since = tx.now;+}++/** The clock set outright to month `m`, held there for `hold` seconds; the `slow` months after it pass slowly. */+function jump(tx: { state: State; now: number }, m: number, hold: number, slow = 0) {+ const s = tx.state;+ s.at = m;+ s.slow = slow;+ s.since = tx.now + hold * 1000;+ s.rel = 0;+ s.jumps += 1;+}++type Tx = { state: State; now: number; decide(ok: unknown, why: string): void };+const pause = (tx: Tx) => {+ touch(tx);+ tx.state.paused = !tx.state.paused;+};+const phase = (tx: Tx) => {+ // The next named phase, unless the Moon is all but there already.+ const cur = months(tx.state, tx.now);+ let k = 0;+ const at = () => Math.floor(cur) + Math.floor(k / 4) + PHASES[k % 4];+ while (at() < cur + 0.03) k += 1;+ jump(tx, at(), HOLD);+};+const view = (tx: Tx) => {+ tx.state.view = tx.state.view === "orrery" ? "earth" : "orrery";+};++export default defineGame<State>({+ state: { since: 0, at: START, slow: 0, speed: NORMAL, paused: false, rel: 0, jumps: 0, eclipse: "lunar", view: "orrery" },++ setup() {+ const scene = new Scene();+ scene.environment = new SkyColor(0x000000, 0);++ // The Sun: a globe that is seen, and a light of the same size and luminance at its centre that does the lighting+ // (one emitter, sampled as a sphere: the live picture is clean at one sample a pixel).+ const sunColor = new Color().setRGB(1.0, 0.91, 0.78);+ const sun = new Mesh(new SphereGeometry(R_SUN, 64, 32), new MeshBasicMaterial({ name: "sun", color: sunColor.clone().multiplyScalar(SUN_NITS) }));+ sun.id = "sun";+ sun.position.set(-D_SUN, 0, 0);+ sun.castShadow = false;+ scene.add(sun);+ const sunlight = new PointLight(sunColor, SUN_CD, 0);+ sunlight.id = "sunlight";+ sunlight.radius = R_SUN;+ sunlight.position.set(-D_SUN, 0, 0);+ scene.add(sunlight);++ const earth = new Mesh(new SphereGeometry(R_EARTH, 96, 48), new MeshStandardMaterial({ name: "earth", map: new Texture("assets/showcase/moon-phases/earth_bmng_2k.jpg"), roughnessMap: new Texture("assets/showcase/moon-phases/earth_rough_1k.jpg", "linear"), roughness: 1 }));+ earth.id = "earth";+ scene.add(earth);+ // The pin the globe turns on (it does not turn itself: a thin thing that moves leaves a trail in the live view).+ const axis = new Mesh(new CylinderGeometry(0.005, 0.005, R_EARTH * 2.7, 12), new MeshStandardMaterial({ name: "pin", color: new Color().setRGB(0.8, 0.62, 0.34), roughness: 0.6 }));+ axis.id = "earth_axis";+ scene.add(axis);+ // The Moon's orbit, drawn: a faint line that is seen and neither lit nor lighting, like the stars.+ const orbit = new Mesh(new TorusGeometry(D_MOON, 0.003, 6, 240), new MeshBasicMaterial({ name: "orbit", color: new Color().setRGB(0.95, 0.8, 0.55).multiplyScalar(16) }));+ orbit.id = "orbit";+ orbit.castShadow = false;+ scene.add(orbit);++ const moon = new Mesh(new SphereGeometry(R_MOON, 64, 32), new MeshStandardMaterial({ name: "moon", map: new Texture("assets/showcase/moon-phases/moon_lroc_2k.jpg"), roughness: 1 }));+ moon.id = "moon";+ scene.add(moon);++ // The stars: seen, lighting nothing.+ const stars = starTile(512, 700);+ stars.repeat = [8, 4];+ const sky = new Mesh(new SphereGeometry(30, 48, 24), new MeshBasicMaterial({ name: "stars", map: stars, color: new Color().setRGB(150, 150, 150), side: "double" }));+ sky.id = "sky";+ sky.castShadow = false;+ scene.add(sky);++ const camera = new PerspectiveCamera(CAM.fov, 16 / 9, 0.01, 100);+ camera.id = "camera";+ camera.position.set(...CAM.pos);+ camera.lookAt(...CAM.target);+ camera.setManualExposure(EV);+ scene.add(camera);+ return { scene, camera, options: { name: "moon-phases", preset: "preview" as const, width: 1280, height: 720 } };+ },++ frame,++ handlers: {+ pause,+ faster(tx) {+ tx.decide(tx.state.speed < RATES.length - 1, "time is already at full speed");+ touch(tx);+ tx.state.speed += 1;+ },+ slower(tx) {+ tx.decide(tx.state.speed > 0, "time is already at its slowest");+ touch(tx);+ tx.state.speed -= 1;+ },+ phase,+ eclipse(tx) {+ const s = tx.state;+ const kind = s.eclipse === "solar" ? "lunar" : "solar";+ // The next new (solar) or full (lunar) moon that comes while the nodes point at the Sun.+ const half = kind === "solar" ? 0 : 0.5;+ let m = Math.ceil(months(s, tx.now) - half + 0.02) + half;+ while (Math.abs(lift(m)) > 0.28) m += 1;+ // Start a little before it and let it pass in slow motion: the Moon's shadow crossing the Earth; or the Moon+ // from just outside the Earth's full shadow until it is all the way in (then on, at the clock's own speed).+ let start = m - 0.03, slow = 0.06;+ if (kind === "lunar") {+ // The month before full moon `m` at which the Moon's centre is `d` from the shadow's axis.+ const reach = (d: number) => {+ let out = m - 0.15, inside = m;+ for (let i = 0; i < 24; i++) {+ const mid = (out + inside) / 2;+ if (offAxis(mid) > d) out = mid;+ else inside = mid;+ }+ return out;+ };+ start = reach(UMBRA + R_MOON * 1.5);+ slow = reach(UMBRA - R_MOON) - start;+ }+ s.eclipse = kind;+ s.paused = false;+ jump(tx, start, ECLIPSE_HOLD, slow);+ },+ view,+ click(tx, ev: { target?: string }) {+ if (ev.target === "earth" || ev.target === "earth_axis" || ev.target === "moon") view(tx);+ else if (ev.target === "sun") pause(tx);+ else phase(tx);+ },+ },++ keys: { Space: "pause", F: "faster", S: "slower", P: "phase", E: "eclipse", V: "view" },+});diff --git a/showcase/moon-phases/thumb.jpg b/showcase/moon-phases/thumb.jpgnew file mode 100644index 0000000..f475c01Binary files /dev/null and b/showcase/moon-phases/thumb.jpg differdiff --git a/showcase/museum/CREDITS.md b/showcase/museum/CREDITS.mdnew file mode 100644index 0000000..0b52b9b--- /dev/null+++ b/showcase/museum/CREDITS.md@@ -0,0 +1,35 @@+# Sculpture Gallery (`museum`): files and credits++Everything the scene reads is in `assets/showcase/museum/` (11.4 MB together, largest file 3.2 MB). All of it is CC0;+no attribution is required, it is given here anyway. The room itself (walls, laylight, plinths, bench, frames, track+lights) is built in code.++## Poly Haven (CC0 1.0, https://polyhaven.com/license)++Each model was downloaded as glTF (`https://api.polyhaven.com/files/<id>`, the `gltf` entry at the resolution named)+with its `.bin` and textures and packed into one `.glb`; nothing else was changed. Textures are the 1k JPEGs as served.++| File | What | Author | Source |+|---|---|---|---|+| `marble_bust_01_2k.glb` | Marble Bust 01: scanned marble portrait bust, 17 456 triangles, 2k maps | Rico Cilliers | https://polyhaven.com/a/marble_bust_01 |+| `lion_head_1k.glb` | Lion Head: bronze lion's head on a base, 47 214 triangles, 1k maps | Tina | https://polyhaven.com/a/lion_head |+| `horse_head_1k.glb` | Horse Head: bronze horse's head on a base, 12 068 triangles, 1k maps | Tina | https://polyhaven.com/a/horse_head |+| `horse_statue_01_1k.glb` | Horse Statue 01: porcelain rearing horse, 22 388 triangles, 1k maps (shown at 3.4 times its size) | Rico Cilliers | https://polyhaven.com/a/horse_statue_01 |+| `herringbone_parquet_diff_1k.jpg`, `_nor_gl_1k.jpg`, `_rough_1k.jpg` | Herringbone Parquet: the floor | Sergej Majboroda (photography), Jenelle van Heerden (processing) | https://polyhaven.com/a/herringbone_parquet |+| `plastered_wall_04_nor_gl_1k.jpg`, `_rough_1k.jpg` | Plastered Wall 04: the walls' and plinths' relief and roughness (its colour map is not used) | Rob Tuytel | https://polyhaven.com/a/plastered_wall_04 |++The other three sculptures are shown larger than the scanned objects too (bust 1.4, lion 1.7, horse's head 1.8 times).++## The Metropolitan Museum of Art, Open Access (CC0 1.0)++Images of works the Met's collection API marks `isPublicDomain: true`+(`https://collectionapi.metmuseum.org/public/collection/v1/objects/<id>`, checked for each on 2026-11-12; the API+documentation, https://metmuseum.github.io/, and https://github.com/metmuseum/openaccess state the terms). Each is the+`primaryImage` with the photograph's black border trimmed, scaled down and saved as JPEG; the pictures hang at their+real sizes.++| File | Work | Artist | Object | Credit line |+|---|---|---|---|---|+| `met_death_of_socrates.jpg` (1536 px) | The Death of Socrates, 1787, 129.5 x 196.2 cm | Jacques Louis David | https://www.metmuseum.org/art/collection/search/436105 | Catharine Lorillard Wolfe Collection, Wolfe Fund, 1931 |+| `met_harvesters.jpg` (1536 px) | The Harvesters, 1565, 119 x 162 cm | Pieter Bruegel the Elder | https://www.metmuseum.org/art/collection/search/435809 | Rogers Fund, 1919 |+| `met_oxbow.jpg` (1024 px) | View from Mount Holyoke, Northampton, Massachusetts, after a Thunderstorm (The Oxbow), 1836, 130.8 x 193 cm | Thomas Cole | https://www.metmuseum.org/art/collection/search/10497 | Gift of Mrs. Russell Sage, 1908 |diff --git a/showcase/museum/assets/herringbone_parquet_diff_1k.jpg b/showcase/museum/assets/herringbone_parquet_diff_1k.jpgnew file mode 100644index 0000000..b59f22dBinary files /dev/null and b/showcase/museum/assets/herringbone_parquet_diff_1k.jpg differdiff --git a/showcase/museum/assets/herringbone_parquet_nor_gl_1k.jpg b/showcase/museum/assets/herringbone_parquet_nor_gl_1k.jpgnew file mode 100644index 0000000..37202afBinary files /dev/null and b/showcase/museum/assets/herringbone_parquet_nor_gl_1k.jpg differdiff --git a/showcase/museum/assets/herringbone_parquet_rough_1k.jpg b/showcase/museum/assets/herringbone_parquet_rough_1k.jpgnew file mode 100644index 0000000..d87cd62Binary files /dev/null and b/showcase/museum/assets/herringbone_parquet_rough_1k.jpg differdiff --git a/showcase/museum/assets/horse_head_1k.glb b/showcase/museum/assets/horse_head_1k.glbnew file mode 100644index 0000000..0a91ab2Binary files /dev/null and b/showcase/museum/assets/horse_head_1k.glb differdiff --git a/showcase/museum/assets/horse_statue_01_1k.glb b/showcase/museum/assets/horse_statue_01_1k.glbnew file mode 100644index 0000000..7ea3047Binary files /dev/null and b/showcase/museum/assets/horse_statue_01_1k.glb differdiff --git a/showcase/museum/assets/lion_head_1k.glb b/showcase/museum/assets/lion_head_1k.glbnew file mode 100644index 0000000..90602dbBinary files /dev/null and b/showcase/museum/assets/lion_head_1k.glb differdiff --git a/showcase/museum/assets/marble_bust_01_2k.glb b/showcase/museum/assets/marble_bust_01_2k.glbnew file mode 100644index 0000000..ff1cedfBinary files /dev/null and b/showcase/museum/assets/marble_bust_01_2k.glb differdiff --git a/showcase/museum/assets/met_death_of_socrates.jpg b/showcase/museum/assets/met_death_of_socrates.jpgnew file mode 100644index 0000000..7c5a112Binary files /dev/null and b/showcase/museum/assets/met_death_of_socrates.jpg differdiff --git a/showcase/museum/assets/met_harvesters.jpg b/showcase/museum/assets/met_harvesters.jpgnew file mode 100644index 0000000..6572cb4Binary files /dev/null and b/showcase/museum/assets/met_harvesters.jpg differdiff --git a/showcase/museum/assets/met_oxbow.jpg b/showcase/museum/assets/met_oxbow.jpgnew file mode 100644index 0000000..716cd27Binary files /dev/null and b/showcase/museum/assets/met_oxbow.jpg differdiff --git a/showcase/museum/assets/plastered_wall_04_nor_gl_1k.jpg b/showcase/museum/assets/plastered_wall_04_nor_gl_1k.jpgnew file mode 100644index 0000000..25fdecaBinary files /dev/null and b/showcase/museum/assets/plastered_wall_04_nor_gl_1k.jpg differdiff --git a/showcase/museum/assets/plastered_wall_04_rough_1k.jpg b/showcase/museum/assets/plastered_wall_04_rough_1k.jpgnew file mode 100644index 0000000..cd72713Binary files /dev/null and b/showcase/museum/assets/plastered_wall_04_rough_1k.jpg differdiff --git a/showcase/museum/case.json b/showcase/museum/case.jsonnew file mode 100644index 0000000..56ebb8a--- /dev/null+++ b/showcase/museum/case.json@@ -0,0 +1,81 @@+{+ "id": "museum",+ "industry": "Culture",+ "title": "Sculpture Gallery",+ "caption": "A daylit museum room you can walk through",+ "blurb": "One room of a museum at real scale: a scanned marble bust, two bronzes and a porcelain horse on stone plinths under a glass ceiling, with paintings from The Met on the walls. The light under a chin is daylight that came down through the ceiling and bounced off the parquet; in the evening the room is lit only by what its spots throw back.",+ "controls": [+ {+ "input": "Click a sculpture or a painting",+ "does": "walks up to it; click elsewhere to return"+ },+ {+ "input": "D, A",+ "does": "next and previous exhibit"+ },+ {+ "input": "L",+ "does": "daylight to evening and back"+ },+ {+ "input": "Space",+ "does": "back to the hall"+ }+ ],+ "credits": [+ {+ "what": "Marble Bust 01 (3D scan)",+ "by": "Rico Cilliers / Poly Haven",+ "licence": "CC0 1.0",+ "url": "https://polyhaven.com/a/marble_bust_01"+ },+ {+ "what": "Lion Head (bronze, 3D model)",+ "by": "Tina / Poly Haven",+ "licence": "CC0 1.0",+ "url": "https://polyhaven.com/a/lion_head"+ },+ {+ "what": "Horse Head (bronze, 3D model)",+ "by": "Tina / Poly Haven",+ "licence": "CC0 1.0",+ "url": "https://polyhaven.com/a/horse_head"+ },+ {+ "what": "Horse Statue 01 (porcelain, 3D scan)",+ "by": "Rico Cilliers / Poly Haven",+ "licence": "CC0 1.0",+ "url": "https://polyhaven.com/a/horse_statue_01"+ },+ {+ "what": "Herringbone Parquet (floor texture)",+ "by": "Sergej Majboroda, Jenelle van Heerden / Poly Haven",+ "licence": "CC0 1.0",+ "url": "https://polyhaven.com/a/herringbone_parquet"+ },+ {+ "what": "Plastered Wall 04 (wall texture)",+ "by": "Rob Tuytel / Poly Haven",+ "licence": "CC0 1.0",+ "url": "https://polyhaven.com/a/plastered_wall_04"+ },+ {+ "what": "The Death of Socrates, 1787 (painting)",+ "by": "Jacques Louis David; image: The Metropolitan Museum of Art, Open Access",+ "licence": "CC0 1.0 (public domain)",+ "url": "https://www.metmuseum.org/art/collection/search/436105"+ },+ {+ "what": "The Harvesters, 1565 (painting)",+ "by": "Pieter Bruegel the Elder; image: The Metropolitan Museum of Art, Open Access",+ "licence": "CC0 1.0 (public domain)",+ "url": "https://www.metmuseum.org/art/collection/search/435809"+ },+ {+ "what": "View from Mount Holyoke, Northampton, Massachusetts, after a Thunderstorm (The Oxbow), 1836 (painting)",+ "by": "Thomas Cole; image: The Metropolitan Museum of Art, Open Access",+ "licence": "CC0 1.0 (public domain)",+ "url": "https://www.metmuseum.org/art/collection/search/10497"+ }+ ]+}diff --git a/showcase/museum/museum.game.ts b/showcase/museum/museum.game.tsnew file mode 100644index 0000000..1d92663--- /dev/null+++ b/showcase/museum/museum.game.ts@@ -0,0 +1,411 @@+// "Sculpture Gallery": one room of a museum at real scale, to walk through from a phone.+//+// A plastered hall, 8 x 10 m and 4.5 m high, under a long laylight: a diffusing glass ceiling, the only lamp by day.+// Four scanned pieces (Poly Haven, CC0) stand on honed-stone plinths: a marble bust, a bronze lion's head, a bronze+// horse's head and a porcelain horse. Two paintings (The Met, Open Access) hang by the doorway, and a third is washed+// with light at the end of the darker red room behind it. Nothing fills the shadows: what lights the underside of a+// chin is the parquet, the soft edges under the plinths are the size of the laylight, and in the evening the room is+// lit by what the six spots bounce off the exhibits and the walls.+//+// Inputs (the state changes only in the handlers; `frame` shows it):+// click / tap a sculpture, its plinth or a painting: walk up to it. Anything else, while close: back to the hall.+// next / prev step through the six exhibits (Right / Left, or D / A).+// overview back to the view of the hall (Space).+// light day <-> evening (L): the laylight falls to dusk, a warm track spot comes on over each exhibit, then+// the exposure opens 3 stops (2.6 s in all).+// Close to a sculpture the visitor drifts slowly from one side of it to the other and rests there (from `f.time`);+// in the hall the camera stands still. Standing still is when the picture converges.+//+// Files: assets/showcase/museum/ (see CREDITS.md). Runs as three.js too: plain materials with mesh UVs in metres,+// spot and rect lights; there the ceiling is black and nothing casts the laylight's shadows.+import {+ CircleGeometry, Color, CylinderGeometry, GLTFModel, Group, Mesh, MeshGeometry, MeshStandardMaterial, PerspectiveCamera, PlaneGeometry,+ RectAreaLight, Scene, SkyColor, SpotLight, Texture, Vector3,+} from "@threert/scene";+import { defineGame, type FrameContext } from "@threert/gameplay";++type V3 = [number, number, number];+const A = "assets/showcase/museum/";++// ------------------------------------------------------------------------------------------------ the room (metres)+const HALL = { x: 4, z0: -5, z1: 5, h: 4.5 }; // half width, back wall, front wall, ceiling+const DOOR = { w: 1.9, h: 2.9, depth: 0.35 }; // the opening in the back wall+const NEXT = { x: 3, z0: -10.6, h: 4.5 }; // the room behind it+const WELL = { x: 1.3, z: 4.4, h: 0.7 }; // the laylight's opening in the ceiling (half sizes) and depth+const TRACK_X = 1.8; // the two lighting tracks, either side of the laylight++// ------------------------------------------------------------------------------------------------ the exhibits+interface Sculpture { kind: "sculpture"; file: string; at: [number, number]; plinth: V3; scale: number; height: number; turn: number; look: number; dist: number; lux: number }+interface Painting { kind: "painting"; file: string; at: V3; size: [number, number]; dist: number; lux: number }+/**+ * `turn`: the way a sculpture faces (radians from +Z, which is towards the entrance). `look`: the side it is best seen+ * from, relative to that. `height`: its own, in metres, as shown. `dist`: how close the visitor stands. `lux`: what+ * its evening spot puts on it (dark bronze takes more light than marble).+ */+const EXHIBITS: (Sculpture | Painting)[] = [+ { kind: "sculpture", file: "marble_bust_01_2k.glb", at: [-1.57, 1.9], plinth: [0.52, 1.12, 0.52], scale: 1.4, height: 0.72, turn: 0.75, look: 0, dist: 1.15, lux: 420 },+ { kind: "sculpture", file: "lion_head_1k.glb", at: [2.32, 0.8], plinth: [0.66, 1.0, 0.5], scale: 1.7, height: 0.74, turn: -0.5, look: 0, dist: 1.3, lux: 800 },+ { kind: "sculpture", file: "horse_head_1k.glb", at: [-3.2, -2.5], plinth: [0.5, 1.0, 0.7], scale: 1.8, height: 0.75, turn: 1.3, look: -0.8, dist: 1.35, lux: 650 },+ { kind: "sculpture", file: "horse_statue_01_1k.glb", at: [1.41, -3.1], plinth: [0.62, 1.05, 0.5], scale: 3.4, height: 0.75, turn: -0.3, look: 0, dist: 1.25, lux: 320 },+ { kind: "painting", file: "met_death_of_socrates.jpg", at: [-2.6, 1.7, HALL.z0], size: [1.962, 1.295], dist: 2.3, lux: 600 },+ { kind: "painting", file: "met_harvesters.jpg", at: [3.0, 1.7, HALL.z0], size: [1.62, 1.19], dist: 2.2, lux: 450 },+];+const N = EXHIBITS.length;++interface State {+ /** -1: the hall; otherwise the exhibit the visitor stands at. */+ view: number;+ evening: boolean;+}++// ------------------------------------------------------------------------------------------------ light levels+const DAY = { laylight: 4200, ev: 9.9 }; // nits, EV100+const DUSK = { laylight: 5, ev: 6.9 }; // nits, EV100; each exhibit then has a spot (its `lux`)+const FAR = { panel: 420, wash: 110000 }; // the next room by day: its laylight and the washer on its painting (nits)+const DUSK_TINT: V3 = [0.42, 0.55, 1.0];+const WARM: V3 = [1.0, 0.76, 0.52]; // ~3000 K++// ------------------------------------------------------------------------------------------------ the camera+const FOV = 46;+const DRIFT = { angle: 0.38, rate: 0.11 }; // around a sculpture: radians either way, radians of phase a second++/** -1 .. 1: the visitor's slow drift from one side to the other, resting at each (there the picture converges). */+function drift(t: number): number {+ return Math.max(-1, Math.min(1, 1.5 * Math.sin(t * DRIFT.rate)));+}+const OVERVIEW = { pos: [0.3, 1.5, 4.85] as V3, tgt: [-0.05, 2.0, -5] as V3 };++function sculptureCentre(e: Sculpture): V3 {+ return [e.at[0], e.plinth[1] + e.height * 0.52, e.at[1]];+}++/** Where the visitor stands and looks for a state, at scene time t. */+function pose(view: number, t: number): { pos: V3; tgt: V3 } {+ const e = EXHIBITS[view];+ if (!e) return OVERVIEW;+ if (e.kind === "painting") {+ return { pos: [e.at[0] + 0.2 * drift(t), 1.6, e.at[2] + e.dist], tgt: [e.at[0], e.at[1], e.at[2]] };+ }+ const c = sculptureCentre(e);+ const a = e.turn + e.look + DRIFT.angle * drift(t);+ return { pos: [c[0] + Math.sin(a) * e.dist, c[1] + 0.08, c[2] + Math.cos(a) * e.dist], tgt: c };+}++/** Each exhibit spot's intensity when on, candela (setup: the exhibit's `lux` at the spot's distance). */+const spots: number[] = [];++// The eased camera and light mix of this node (frame state, not game state), and the mix the lamps were last set for.+const cam = { pos: new Vector3(), tgt: new Vector3() };+let day = 1, lit = -1;++function frame(f: FrameContext<State>) {+ const s = f.state;+ const want = pose(s.view, f.time);+ const k = f.snap ? 1 : 1 - Math.exp(-f.dt * 3.2);+ const to = new Vector3(...want.pos);+ // (Arrived: stand still, so the hall view converges.)+ const there = k >= 1 || cam.pos.distanceTo(to) < 0.003;+ if (f.snap || cam.pos.distanceTo(to) > 0) {+ cam.pos.lerp(to, there ? 1 : k);+ cam.tgt.lerp(new Vector3(...want.tgt), there ? 1 : k);+ f.camera.position.copy(cam.pos);+ f.camera.lookAt(cam.tgt);+ }++ // Day <-> evening in 2.6 s, the lamps in the brighter part of it and the exposure in the darker part: the eye opens+ // after the light has gone and closes before it comes back. The live view shows light accumulated over its last+ // frames, which fades by about a stop in ten frames; an exposure that opened faster than that would show a flash, a+ // moment ago's daylight at the evening's exposure. So the change to evening also takes at least 150 frames.+ const target = s.evening ? 0 : 1;+ const step = target < day ? Math.min(f.dt / 2.6, 1 / 150) : f.dt / 2.6;+ day = f.snap ? target : day + Math.sign(target - day) * Math.min(Math.abs(target - day), step);+ if (day === lit && !f.snap) return;+ lit = day;+ const smooth = (x: number) => { const c = Math.max(0, Math.min(1, x)); return c * c * (3 - 2 * c); };+ const u = smooth((day - 0.64) / 0.36), open = smooth(day / 0.6);+ const sky = f.object("laylight") as RectAreaLight;+ // (Luminance moves in stops, so the change reads evenly.)+ sky.intensity = DUSK.laylight * Math.pow(DAY.laylight / DUSK.laylight, u);+ sky.color.setRGB(DUSK_TINT[0] + (1 - DUSK_TINT[0]) * u, DUSK_TINT[1] + (1 - DUSK_TINT[1]) * u, 1);+ const ev = DUSK.ev + (DAY.ev - DUSK.ev) * open;+ f.camera.setManualExposure(ev);+ // (The next room keeps its own level: its lamps follow the exposure.)+ const stops = Math.pow(2, ev - DAY.ev);+ (f.object("far_light") as RectAreaLight).intensity = FAR.panel * stops;+ (f.object("far_wash") as RectAreaLight).intensity = FAR.wash * stops;+ for (let i = 0; i < N; i++) {+ (f.object(`spot_${i}`) as SpotLight).intensity = spots[i] * (1 - u);+ (f.object(`lens_${i}`) as Mesh).material.emissiveIntensity = 6000 * (1 - u);+ }+}++export default defineGame<State>({+ state: { view: -1, evening: false },++ setup() {+ const scene = new Scene();+ scene.environment = new SkyColor(0x000000, 0);++ // ---- materials+ const tex = (file: string, space: "srgb" | "linear" = "srgb") => new Texture(A + file, space);+ const plaster = new MeshStandardMaterial({+ name: "plaster", color: new Color().setRGB(0.78, 0.76, 0.71), roughness: 1,+ normalMap: tex("plastered_wall_04_nor_gl_1k.jpg", "linear"), roughnessMap: tex("plastered_wall_04_rough_1k.jpg", "linear"),+ });+ const parquet = new MeshStandardMaterial({+ name: "parquet", roughness: 1,+ map: tex("herringbone_parquet_diff_1k.jpg"), normalMap: tex("herringbone_parquet_nor_gl_1k.jpg", "linear"), roughnessMap: tex("herringbone_parquet_rough_1k.jpg", "linear"),+ });+ const mat = (name: string, c: V3, roughness: number, metalness = 0) => new MeshStandardMaterial({ name, color: new Color().setRGB(...c), roughness, metalness });+ const white = mat("ceiling_paint", [0.82, 0.81, 0.79], 0.9);+ const red = mat("red_room", [0.33, 0.055, 0.05], 0.9);+ const stone = new MeshStandardMaterial({+ name: "honed_stone", color: new Color().setRGB(0.5, 0.47, 0.42), roughness: 0.55,+ normalMap: plaster.normalMap, roughnessMap: plaster.roughnessMap,+ });+ const trim = mat("trim_stone", [0.5, 0.48, 0.45], 0.38);+ const bronze = mat("glazing_bars", [0.09, 0.08, 0.07], 0.45, 0.8);+ const leather = mat("leather", [0.11, 0.045, 0.03], 0.5);+ const steel = mat("blackened_steel", [0.035, 0.035, 0.04], 0.4, 0.9);+ const gilt = mat("gilt", [0.85, 0.6, 0.25], 0.6, 0.35);+ const liner = mat("frame_liner", [0.06, 0.045, 0.035], 0.5);+ const fitting = mat("fitting", [0.75, 0.75, 0.74], 0.5);+ const card = mat("label_card", [0.62, 0.61, 0.58], 0.7);++ // ---- geometry: quads and boxes with texture coordinates in metres / `tile`, so one texture fits every surface+ class Shell {+ p: number[] = []; n: number[] = []; uv: number[] = []; idx: number[] = [];+ tile: number;+ constructor(tile = 1) {+ this.tile = tile;+ }+ /** A rectangle from `o` along `eu` and `ev`, facing eu x ev. */+ quad(o: V3, eu: V3, ev: V3): this {+ const nrm = new Vector3(...eu).cross(new Vector3(...ev)).normalize();+ const lu = Math.hypot(...eu), lv = Math.hypot(...ev);+ const base = this.p.length / 3;+ for (const [a, b] of [[0, 0], [1, 0], [1, 1], [0, 1]]) {+ const x = o[0] + eu[0] * a + ev[0] * b, y = o[1] + eu[1] * a + ev[1] * b, z = o[2] + eu[2] * a + ev[2] * b;+ this.p.push(x, y, z);+ this.n.push(nrm.x, nrm.y, nrm.z);+ this.uv.push((x * eu[0] + y * eu[1] + z * eu[2]) / lu / this.tile, (x * ev[0] + y * ev[1] + z * ev[2]) / lv / this.tile);+ }+ this.idx.push(base, base + 1, base + 2, base, base + 2, base + 3);+ return this;+ }+ /** A box by its corners. */+ box(x0: number, y0: number, z0: number, x1: number, y1: number, z1: number): this {+ const w = x1 - x0, h = y1 - y0, d = z1 - z0;+ this.quad([x1, y0, z1], [0, 0, -d], [0, h, 0]).quad([x0, y0, z0], [0, 0, d], [0, h, 0]);+ this.quad([x0, y0, z1], [w, 0, 0], [0, h, 0]).quad([x1, y0, z0], [-w, 0, 0], [0, h, 0]);+ return this.quad([x0, y1, z1], [w, 0, 0], [0, 0, -d]).quad([x0, y0, z0], [w, 0, 0], [0, 0, d]);+ }+ mesh(id: string, m: MeshStandardMaterial): Mesh {+ const mesh = new Mesh(new MeshGeometry(this.p, this.idx, this.n, this.uv), m);+ mesh.id = id;+ scene.add(mesh);+ return mesh;+ }+ }+ const { x: X, z0: Z0, z1: Z1, h: H } = HALL;+ const dw = DOOR.w / 2, zb = Z0 - DOOR.depth;++ // floor: one parquet field through both rooms+ new Shell(2.6).quad([-X, 0, Z1], [2 * X, 0, 0], [0, 0, NEXT.z0 - Z1]).mesh("floor", parquet);++ // the hall's walls; the back wall is 0.35 m thick with the doorway through it+ new Shell(3.2)+ .quad([-X, 0, Z1], [0, 0, Z0 - Z1], [0, H, 0]) // left+ .quad([X, 0, Z0], [0, 0, Z1 - Z0], [0, H, 0]) // right+ .quad([X, 0, Z1], [-2 * X, 0, 0], [0, H, 0]) // front (behind the visitor)+ .box(-X, 0, zb, -dw, H, Z0).box(dw, 0, zb, X, H, Z0).box(-dw, DOOR.h, zb, dw, H, Z0)+ // the laylight's well+ .quad([-WELL.x, H, WELL.z], [0, 0, -2 * WELL.z], [0, WELL.h, 0]).quad([WELL.x, H, -WELL.z], [0, 0, 2 * WELL.z], [0, WELL.h, 0])+ .quad([-WELL.x, H, -WELL.z], [2 * WELL.x, 0, 0], [0, WELL.h, 0]).quad([WELL.x, H, WELL.z], [-2 * WELL.x, 0, 0], [0, WELL.h, 0])+ .mesh("walls", plaster);++ // ceilings: the hall's around the well, and the next room's+ new Shell()+ .quad([-X, H, Z0], [X - WELL.x, 0, 0], [0, 0, Z1 - Z0]).quad([WELL.x, H, Z0], [X - WELL.x, 0, 0], [0, 0, Z1 - Z0])+ .quad([-WELL.x, H, Z0], [2 * WELL.x, 0, 0], [0, 0, -WELL.z - Z0]).quad([-WELL.x, H, WELL.z], [2 * WELL.x, 0, 0], [0, 0, Z1 - WELL.z])+ .quad([-NEXT.x, NEXT.h, NEXT.z0], [2 * NEXT.x, 0, 0], [0, 0, zb - NEXT.z0])+ // cornice+ .box(-X, H - 0.14, Z0, -X + 0.1, H, Z1).box(X - 0.1, H - 0.14, Z0, X, H, Z1).box(-X, H - 0.14, Z0, X, H, Z0 + 0.1).box(-X, H - 0.14, Z1 - 0.1, X, H, Z1)+ .mesh("ceiling", white);++ // the next room: deep red walls+ new Shell()+ .quad([-NEXT.x, 0, zb], [0, 0, NEXT.z0 - zb], [0, NEXT.h, 0]).quad([NEXT.x, 0, NEXT.z0], [0, 0, zb - NEXT.z0], [0, NEXT.h, 0])+ .quad([-NEXT.x, 0, NEXT.z0], [2 * NEXT.x, 0, 0], [0, NEXT.h, 0])+ .quad([NEXT.x, 0, zb], [dw - NEXT.x, 0, 0], [0, NEXT.h, 0]).quad([-dw, 0, zb], [dw - NEXT.x, 0, 0], [0, NEXT.h, 0])+ .quad([dw, DOOR.h, zb], [-2 * dw, 0, 0], [0, NEXT.h - DOOR.h, 0])+ .mesh("next_room", red);++ // skirting, the doorway's stone surround and threshold+ const sk = 0.14, st = 0.022;+ new Shell()+ .box(-X, 0, Z0, -X + st, sk, Z1).box(X - st, 0, Z0, X, sk, Z1).box(-X, 0, Z1 - st, X, sk, Z1)+ .box(-X, 0, Z0, -dw - 0.16, sk, Z0 + st).box(dw + 0.16, 0, Z0, X, sk, Z0 + st)+ .box(-dw - 0.16, 0, Z0 - 0.02, -dw, DOOR.h + 0.16, Z0 + 0.045).box(dw, 0, Z0 - 0.02, dw + 0.16, DOOR.h + 0.16, Z0 + 0.045)+ .box(-dw, DOOR.h, Z0 - 0.02, dw, DOOR.h + 0.16, Z0 + 0.045)+ .box(-dw, -0.02, zb, dw, 0.004, Z0)+ .box(-NEXT.x, 0, NEXT.z0, NEXT.x, sk, NEXT.z0 + st)+ .mesh("trim", trim);++ // glazing bars under the laylight, and the lighting tracks+ const bars = new Shell();+ for (const x of [-WELL.x / 3, WELL.x / 3]) bars.box(x - 0.02, H + 0.42, -WELL.z, x + 0.02, H + 0.5, WELL.z);+ for (let i = 1; i < 9; i++) bars.box(-WELL.x, H + 0.42, -WELL.z + (i * 2 * WELL.z) / 9 - 0.02, WELL.x, H + 0.5, -WELL.z + (i * 2 * WELL.z) / 9 + 0.02);+ bars.mesh("glazing_bars", bronze);+ new Shell().box(-TRACK_X - 0.02, H - 0.03, -4.2, -TRACK_X + 0.02, H, 4.6).box(TRACK_X - 0.02, H - 0.03, -4.2, TRACK_X + 0.02, H, 4.6)+ .box(-3.8, H - 0.03, Z0 + 2.18, -TRACK_X, H, Z0 + 2.22).box(TRACK_X, H - 0.03, Z0 + 2.18, 3.8, H, Z0 + 2.22).mesh("tracks", fitting);++ // bench: two leather pads on a slender steel frame+ {+ const z0 = -1.5, z1 = 0.3, w = 0.26, mid = (z0 + z1) / 2;+ new Shell().box(-w, 0.385, z0, w, 0.455, mid - 0.006).box(-w, 0.385, mid + 0.006, w, 0.455, z1).mesh("bench_seat", leather);+ const frame = new Shell().box(-w + 0.02, 0.355, z0 + 0.02, w - 0.02, 0.385, z1 - 0.02);+ for (const x of [-w + 0.04, w - 0.07]) for (const z of [z0 + 0.12, z1 - 0.15]) frame.box(x, 0, z, x + 0.03, 0.355, z + 0.03);+ frame.mesh("bench_frame", steel);+ }++ // ---- light: the laylight (a diffusing glass ceiling above the well), the only lamp by day+ const laylight = new RectAreaLight(0xffffff, DAY.laylight, 2 * WELL.x, 2 * WELL.z);+ laylight.id = "laylight";+ laylight.position.set(0, H + WELL.h - 0.005, 0);+ laylight.rotation.x = -Math.PI / 2;+ scene.add(laylight);+ // the next room: a small dim laylight of its own, and a wall washer (a slot with barn doors) on the painting at the+ // end of the axis+ const far = new RectAreaLight(new Color().setRGB(1, 0.93, 0.84), FAR.panel, 1.6, 1.6);+ far.id = "far_light";+ far.position.set(0, NEXT.h - 0.005, -8);+ far.rotation.x = -Math.PI / 2;+ scene.add(far);+ const wash = new RectAreaLight(new Color().setRGB(...WARM), FAR.wash, 0.6, 0.14);+ wash.id = "far_wash";+ wash.card = false;+ wash.barnDoorAngle = 34;+ wash.position.set(0, NEXT.h - 0.1, NEXT.z0 + 1.5);+ wash.lookAt(0, 1.55, NEXT.z0);+ scene.add(wash);++ /** A track spot: the lamp (off by day), its can and a lens that glows with it. */+ const spot = (i: number, from: V3, at: V3, angle: number) => {+ spots[i] = EXHIBITS[i].lux * new Vector3(...at).sub(new Vector3(...from)).lengthSq();+ const l = new SpotLight(new Color().setRGB(...WARM), 0, 14, angle, 0.6);+ l.id = `spot_${i}`;+ l.radius = 0.035;+ const dir = new Vector3(...at).sub(new Vector3(...from)).normalize();+ l.position.set(...from).addScaledVector(dir, 0.12);+ l.target!.position.set(...at);+ scene.add(l);+ const head = new Group();+ head.position.set(...from);+ head.lookAt(...at);+ const can = new Mesh(new CylinderGeometry(0.045, 0.045, 0.17, 20), fitting);+ can.id = `can_${i}`;+ can.rotation.x = Math.PI / 2;+ const lens = new Mesh(new CircleGeometry(0.036, 20), new MeshStandardMaterial({ name: `lens_${i}`, color: 0x202020, emissive: new Color().setRGB(...WARM), emissiveIntensity: 0 }));+ lens.id = `lens_${i}`;+ lens.position.z = 0.087;+ head.add(can, lens);+ scene.add(head);+ const stem = new Mesh(new CylinderGeometry(0.008, 0.008, H - from[1], 8), fitting);+ stem.id = `stem_${i}`;+ stem.position.set(from[0], (H + from[1]) / 2, from[2]);+ scene.add(stem);+ };++ /** A picture frame on a wall facing +Z: a dark slip around the canvas, a gilded moulding in two steps around that. */+ const framed = (id: string, x: number, y: number, z: number, w: number, h: number) => {+ const ring = (sh: Shell, inner: number, outer: number, z1: number) => {+ const a = w / 2 + inner, b = h / 2 + inner, c = w / 2 + outer, d = h / 2 + outer;+ return sh.box(x - c, y - d, z, x + c, y - b, z1).box(x - c, y + b, z, x + c, y + d, z1).box(x - c, y - b, z, x - a, y + b, z1).box(x + a, y - b, z, x + c, y + b, z1);+ };+ ring(new Shell(), -0.004, 0.02, z + 0.045).mesh(`${id}_slip`, liner);+ ring(ring(new Shell(), 0.02, 0.085, z + 0.06), 0.085, 0.13, z + 0.085).mesh(`${id}_frame`, gilt);+ };++ // ---- exhibits+ EXHIBITS.forEach((e, i) => {+ if (e.kind === "sculpture") {+ const [x, z] = e.at, [w, h, d] = e.plinth;+ const plinth = new Group();+ plinth.position.set(x, 0, z);+ plinth.rotation.y = e.turn;+ scene.add(plinth);+ // a recessed foot, then the block+ const foot = new Shell().box(-w / 2 + 0.03, 0, -d / 2 + 0.03, w / 2 - 0.03, 0.04, d / 2 - 0.03).mesh(`ex${i}_foot`, steel);+ const block = new Shell().box(-w / 2, 0.04, -d / 2, w / 2, h, d / 2).mesh(`ex${i}_plinth`, stone);+ plinth.add(foot, block);+ const model = new GLTFModel(A + e.file);+ model.id = `ex${i}`;+ model.position.set(x, h, z);+ model.rotation.y = e.turn;+ model.scale.setScalar(e.scale);+ scene.add(model);+ const c = sculptureCentre(e);+ // its spot: on a track, 3 m out on the side it is seen from+ const a = e.turn + e.look, px = x + 3 * Math.sin(a);+ spot(i, [(px < 0 ? -1 : 1) * TRACK_X, H - 0.22, Math.min(z + 3 * Math.cos(a), 4.4)], c, 0.3);+ } else {+ const [x, y, z] = e.at, [w, h] = e.size;+ const canvas = new Mesh(new PlaneGeometry(w, h), new MeshStandardMaterial({ name: `canvas_${i}`, map: tex(e.file), roughness: 0.75 }));+ canvas.id = `ex${i}`;+ canvas.position.set(x, y, z + 0.035);+ scene.add(canvas);+ framed(`ex${i}`, x, y, z, w, h);+ // its label, on the doorway's side: a blank card (the page carries the words)+ const lx = x - Math.sign(x) * (w / 2 + 0.32);+ new Shell().box(lx - 0.075, 1.22, z, lx + 0.075, 1.32, z + 0.006).mesh(`ex${i}_label`, card);+ spot(i, [x, H - 0.22, z + 2.2], [x, y - 0.15, z], 0.52);+ }+ });+ // the painting at the end of the axis (not an exhibit: it is what the doorway shows)+ {+ const w = 1.93, h = 1.308, x = 0, y = 1.75, z = NEXT.z0;+ const canvas = new Mesh(new PlaneGeometry(w, h), new MeshStandardMaterial({ name: "far_canvas", map: tex("met_oxbow.jpg"), roughness: 0.75 }));+ canvas.id = "far_canvas";+ canvas.position.set(x, y, z + 0.035);+ scene.add(canvas);+ framed("far", x, y, z, w, h);+ }++ const camera = new PerspectiveCamera(FOV, 16 / 9, 0.05, 100);+ camera.id = "camera";+ camera.position.set(...OVERVIEW.pos);+ camera.lookAt(...OVERVIEW.tgt);+ camera.setManualExposure(DAY.ev);+ scene.add(camera);+ return { scene, camera, options: { name: "museum", preset: "preview" as const, width: 1280, height: 720 } };+ },++ frame,++ handlers: {+ click(tx, ev: { target?: string }) {+ const m = /^ex(\d+)/.exec(ev.target ?? "");+ if (m && Number(m[1]) < N) {+ tx.state.view = Number(m[1]);+ return;+ }+ tx.decide(tx.state.view >= 0, "click a sculpture or a painting");+ tx.state.view = -1;+ },+ next(tx) {+ tx.state.view = (tx.state.view + 1) % N;+ },+ prev(tx) {+ tx.state.view = tx.state.view < 0 ? N - 1 : (tx.state.view + N - 1) % N;+ },+ overview(tx) {+ tx.state.view = -1;+ },+ light(tx) {+ tx.state.evening = !tx.state.evening;+ },+ },++ keys: { Right: "next", Left: "prev", D: "next", A: "prev", Space: "overview", L: "light" },+});diff --git a/showcase/museum/thumb.jpg b/showcase/museum/thumb.jpgnew file mode 100644index 0000000..7b324e7Binary files /dev/null and b/showcase/museum/thumb.jpg differdiff --git a/showcase/refraction/case.json b/showcase/refraction/case.jsonnew file mode 100644index 0000000..0617665--- /dev/null+++ b/showcase/refraction/case.json@@ -0,0 +1,30 @@+{+ "id": "refraction",+ "industry": "Education",+ "title": "Refraction Bench",+ "caption": "A straw breaks in water; a glass ball flips the arrows",+ "blurb": "A straw in a glass of water, a glass block in front of stripes and a glass ball in front of a card of arrows, set out like the optics page of a school book. Every ray bends at each surface it crosses, so the straw breaks at the water line and the ball shows the arrows upside down; set the index to 1.0 and the glass disappears.",+ "controls": [+ {+ "input": "Click a piece",+ "does": "moves the camera in on it; again to step back"+ },+ {+ "input": "M",+ "does": "makes the block and the ball glass, diamond, air or water"+ },+ {+ "input": "T",+ "does": "swings the block and moves the straw round the glass"+ },+ {+ "input": "V",+ "does": "steps the camera through the pieces"+ },+ {+ "input": "R",+ "does": "back to the start"+ }+ ],+ "credits": []+}diff --git a/showcase/refraction/refraction.game.ts b/showcase/refraction/refraction.game.tsnew file mode 100644index 0000000..da84213--- /dev/null+++ b/showcase/refraction/refraction.game.ts@@ -0,0 +1,259 @@+// "Refraction bench": the optics page of a school physics book, set up on a table and traced.+//+// Three things stand on graph paper under a softbox: a glass of water with a straw in it (the straw looks broken at+// the water line), a thick glass block in front of a striped card (the stripes seen through it are shifted, more the+// more the block is turned) and a glass ball in front of a card of arrows (the ball shows them upside down and+// pointing the other way). All of it is `MeshPhysicalMaterial` with `transmission` and `ior`: the bending is Snell's+// law at every surface a ray crosses, nothing is drawn or faked.+//+// Inputs:+// click / tap a piece the camera moves in on it (the glass, the block or the ball; their cards count as theirs);+// click it again, or the table, to step back+// material (M) what the block and the ball are made of: glass 1.5 -> diamond 2.42 -> air 1.0 (they all but+// vanish: no change of index, so no bending and no reflection) -> water 1.33 -> glass+// turn (T) swings the block 15 degrees (between 45 one way and 45 the other) and moves the straw a+// twelfth of the way round the glass: where it stands decides how broken it looks+// view (V) steps the camera through the pieces without clicking+// reset (R) glass, the block at 30 degrees, the wide view+//+// What the scene is built around (measured on the live view, which follows a path through at most three glass+// surfaces before the thing behind them, and shows black beyond that):+// - Every clear thing is one closed solid. The glass of water is a single solid of water (1.33), full to the brim,+// with a rolled rim; the tumbler's own thin wall is left out. A tumbler around the water puts six surfaces+// in front of whatever is behind the glass (right offline at 10 bounces, black live), and the renderer keeps no+// stack of nested media, so glass against water could only be drawn with air between them anyway.+// - The block's two small ends are ground glass (thin matt panels), as a school block's often are: a ray that+// reached them from inside would have bounced along the block more often than the live view follows.+// - The softbox is a light only (`card = false`). With its card shown it is an emitter, and the live view then+// leaves a straw under water unlit (emitters' shadow rays stop at glass; an analytic light's pass through).+// - There is a block and a ball for each material and the chosen pair is shown, and a speck under the table is+// switched when a turn comes to rest: see `frame`.+import { BoxGeometry, Color, CylinderGeometry, DataTexture, LatheGeometry, Mesh, MeshPhysicalMaterial, MeshStandardMaterial, Object3D, PerspectiveCamera, PlaneGeometry, RectAreaLight, Scene, SkyGradient, SphereGeometry, TorusGeometry } from "@threert/scene";+import { defineGame, type FrameContext } from "@threert/gameplay";++type Vec3 = [number, number, number];+type Focus = "all" | "glass" | "block" | "ball";++interface State {+ /** Index into MATERIALS: what the block and the ball are made of. */+ material: number;+ /** Turns made (it only goes up): the block's angle and the straw's place round the glass are functions of it. */+ turn: number;+ focus: Focus;+}++const MATERIALS = [+ { name: "air", ior: 1.0 },+ { name: "water", ior: 1.33 },+ { name: "glass", ior: 1.5 },+ { name: "diamond", ior: 2.42 },+];+const START: State = { material: 2, turn: 2, focus: "all" };+const FOCI: Focus[] = ["all", "glass", "block", "ball"];++// Where things stand (metres; the table top is y = 0, the camera looks along -z).+const GLASS_X = -0.205, GLASS_Z = 0.03, BALL_X = 0.2, CARD_Z = -0.14;+const BALL_R = 0.04, RING_R = 0.022, RING_T = 0.005, STAND_H = 0.034;+const BALL_Y = STAND_H + RING_T + Math.sqrt((BALL_R + RING_T) ** 2 - RING_R ** 2);+const BLOCK: Vec3 = [0.12, 0.07, 0.06];+const VIEWS: Record<Focus, { pos: Vec3; target: Vec3 }> = {+ all: { pos: [0, 0.15, 0.65], target: [0.003, 0.08, 0] },+ glass: { pos: [GLASS_X + 0.05, 0.16, 0.4], target: [GLASS_X + 0.005, 0.092, GLASS_Z] },+ block: { pos: [0, 0.14, 0.4], target: [0, 0.075, -0.04] },+ ball: { pos: [BALL_X + 0.07, 0.115, 0.33], target: [BALL_X + 0.03, 0.082, -0.03] },+};++// ---------------------------------------------------------------------------------------------- patterns+function texture(w: number, h: number, at: (u: number, v: number) => number): DataTexture {+ const px = new Uint8Array(w * h * 4);+ for (let y = 0; y < h; y++)+ for (let x = 0; x < w; x++) {+ const c = at((x + 0.5) / w, (y + 0.5) / h), o = (y * w + x) * 4;+ px[o] = (c >> 16) & 255; px[o + 1] = (c >> 8) & 255; px[o + 2] = c & 255; px[o + 3] = 255;+ }+ return new DataTexture(w, h, px);+}+const CREAM = 0xf3ecdc, NAVY = 0x1d3557, RED = 0xd23a2e, BLUE = 0x2f6fb5;+/** 17 upright stripes, the middle one red: which stripe is which stays readable when the block shifts them. */+const stripes = () => texture(1024, 4, (u) => { const i = Math.floor(u * 17); return i === 8 ? RED : i % 2 ? NAVY : CREAM; });+/** Rows of arrows pointing up and to the right over a blue band along the bottom: turned upside down, the arrows+ * point down and to the left and the band is on top. Row 0 of a texture is its top. */+const arrows = () => texture(512, 512, (u, v) => {+ if (v > 0.86) return BLUE;+ // One cell, the arrow along its diagonal: p along the arrow (0..1), q across it.+ const cu = (u * 4) % 1 - 0.5, cv = 0.5 - ((v / 0.86) * 3) % 1;+ const p = (cu + cv) * 0.7071 + 0.5, q = Math.abs(cu - cv) * 0.7071;+ if (p > 0.16 && p <= 0.56 && q < 0.055) return RED;+ if (p > 0.56 && p < 0.86 && q < 0.19 * (1 - (p - 0.56) / 0.3)) return RED;+ return CREAM;+});+/** Graph paper: a 5 cm tile of 1 cm squares, the tile's edge heavier. */+const graph = () => texture(250, 250, (u, v) => {+ const x = Math.floor(u * 250), y = Math.floor(v * 250);+ if (x < 2 || y < 2) return 0x86a3c2;+ if (x % 50 === 0 || y % 50 === 0) return 0xb4c8dc;+ return 0xf4f4ee;+});+/** A 30 cm wooden rule: a mark every centimetre along one edge, a shorter one at each half, no figures. */+const rule = () => texture(1200, 64, (u, v) => {+ const mm = u * 300, near = Math.abs(mm - Math.round(mm / 5) * 5);+ const cm = Math.round(mm / 5) % 2 === 0;+ return near < 0.3 && mm > 2 && mm < 298 && v < (cm ? 0.5 : 0.3) ? 0x3a2a1c : 0xd8b676;+});+/** Red and white bands along the straw. */+const bands = () => texture(4, 64, (_u, v) => (v < 0.5 ? 0xd9362b : 0xf5f2ea));++// ---------------------------------------------------------------------------------------------- the frame+const cam = { pos: [...VIEWS.all.pos] as Vec3, target: [...VIEWS.all.target] as Vec3 };+let turned = START.turn;++function frame(f: FrameContext<State>) {+ const s = f.state;+ // One block and one ball per material, the chosen pair shown. (Changing `ior` on one material works too, but the+ // live view then fades from the old picture to the new over some seconds; another object's pixels start afresh.)+ for (let i = 0; i < MATERIALS.length; i++) f.object(`block_${i}`)!.visible = f.object(`ball_${i}`)!.visible = i === s.material;++ // Ease the turn and the camera to where the state has them (exponential, about a third of a second).+ const k = f.snap ? 1 : 1 - Math.exp(-f.dt * 9);+ const before = turned;+ turned = Math.abs(s.turn - turned) < 0.02 ? s.turn : turned + (s.turn - turned) * k;+ if (turned !== before || f.snap) {+ f.object("block_turn")!.rotation.y = blockAngle(turned);+ f.object("straw_arm")!.rotation.y = STRAW_START + (turned * Math.PI) / 6;+ // What is seen through a piece of glass that has just moved is new, and the live view cannot tell: it keeps+ // averaging the picture with what the glass showed on the way. Showing or hiding an object makes it start again,+ // so a speck under the table is switched when the turn has come to rest.+ if (turned === s.turn && !f.snap) f.object("refresh")!.visible = !f.object("refresh")!.visible;+ }+ const v = VIEWS[s.focus];+ let moved = f.snap;+ for (let i = 0; i < 3; i++) {+ const p = Math.abs(v.pos[i] - cam.pos[i]) < 1e-4 ? v.pos[i] : cam.pos[i] + (v.pos[i] - cam.pos[i]) * k;+ const t = Math.abs(v.target[i] - cam.target[i]) < 1e-4 ? v.target[i] : cam.target[i] + (v.target[i] - cam.target[i]) * k;+ moved ||= p !== cam.pos[i] || t !== cam.target[i];+ cam.pos[i] = p; cam.target[i] = t;+ }+ if (moved) {+ f.camera.position.set(...cam.pos);+ f.camera.lookAt(...cam.target);+ }+}+/** Where the straw leans at turn 0 (radians about the glass's axis): at the start, on the far side of the rim. */+const STRAW_START = 1.13 - (START.turn * Math.PI) / 6;+/** The block swings between 45 degrees one way and 45 the other, 15 degrees a turn (radians; t may be between turns). */+function blockAngle(t: number): number {+ const u = (((t + 3) % 12) + 12) % 12;+ return ((u < 6 ? u - 3 : 9 - u) * Math.PI) / 12;+}++export default defineGame<State>({+ state: { ...START },++ setup() {+ const scene = new Scene();+ // No wall: the pale sky is the backdrop, as a photographer's sweep is, and it fills the shadows.+ scene.environment = new SkyGradient({ zenith: 0x9db7d9, horizon: 0xcddbea, ground: 0xc6d3e0, intensity: 600 });+ const add = <T extends Object3D>(id: string, o: T, pos: Vec3, parent: Object3D = scene): T => {+ o.id = id;+ o.position.set(...pos);+ parent.add(o);+ return o;+ };+ const matte = (name: string, color: number, roughness = 0.7) => new MeshStandardMaterial({ name, color, roughness });+ const clear = (name: string, ior: number) => new MeshPhysicalMaterial({ name, color: 0xffffff, roughness: 0, transmission: 1, ior });++ // A pale bench with a paper mat ruled in centimetres.+ add("table", new Mesh(new BoxGeometry(3, 0.04, 1.8), matte("table", 0xc9c5bc, 0.5)), [0, -0.0205, -0.3]);+ const paper = graph();+ paper.repeat = [20, 12];+ add("table_mat", new Mesh(new PlaneGeometry(1, 0.6), new MeshStandardMaterial({ name: "mat", map: paper, roughness: 0.65 })), [0, 0, 0.02]).rotation.x = -Math.PI / 2;++ add("ruler", new Mesh(new BoxGeometry(0.3, 0.003, 0.03), new MeshStandardMaterial({ name: "ruler", map: rule(), roughness: 0.55 })), [0.035, 0.0016, 0.175]).rotation.y = 0.07;+ add("refresh", new Mesh(new BoxGeometry(0.001, 0.001, 0.001), matte("speck", 0x808080)), [0, -0.2, -0.3]);++ // 1. A glass of water, full to the brim, with a straw. One closed solid of water, lathed: the bottom, the tapered+ // side, a rolled rim, the water's surface (see the note on the tumbler's wall at the top). Each straight run has+ // a point just inside each end, so that its shading normals are its own and it does not act as a lens.+ const RB = 0.032, RT = 0.04, H = 0.128, TOP = H - 0.0016;+ const side = (y: number) => RB + ((RT - RB) * y) / H;+ const profile = [+ [0, 0], [RB - 0.0035, 0], [RB - 0.003, 0], [RB - 0.0009, 0.0009], [side(0.003), 0.003], [side(0.0035), 0.0035],+ [side(H - 0.0035), H - 0.0035], [side(H - 0.003), H - 0.003], [RT + 0.0007, H - 0.0016], [RT + 0.0004, H - 0.0004], [RT - 0.0006, H],+ [RT - 0.0017, H - 0.0005], [RT - 0.0024, TOP], [RT - 0.003, TOP], [0, TOP],+ ].map(([x, y]) => ({ x, y }));+ add("glass_water", new Mesh(new LatheGeometry(profile, 72), clear("water", 1.33)), [GLASS_X, 0.0003, GLASS_Z]);+ // The straw stands on the bottom at one side and leans on the rim at the other; its arm turns about the glass.+ const arm = add("straw_arm", new Object3D(), [GLASS_X, 0.0003, GLASS_Z]);+ const SR = 0.003, SL = 0.225, foot: [number, number] = [-0.017, 0.0035];+ const lean = Math.atan2(RT - 0.0024 - SR / 0.9 - foot[0], H - foot[1]);+ const ringed = bands();+ ringed.repeat = [1, 10];+ const straw = add("glass_straw", new Mesh(new CylinderGeometry(SR, SR, SL, 20, 1), new MeshStandardMaterial({ name: "straw", map: ringed, roughness: 0.35 })),+ [foot[0] + (Math.sin(lean) * SL) / 2, foot[1] + (Math.cos(lean) * SL) / 2, 0], arm);+ straw.rotation.z = -lean;++ // 2. A glass block in front of a striped card. Its two ends are ground, as a school block's are (and a ray that+ // reached them from inside would have bounced along the block more often than the live view follows).+ const made = MATERIALS.map((m) => clear(m.name, m.ior));+ const block = add("block_turn", new Object3D(), [0, BLOCK[1] / 2 + 0.0003, 0]);+ const blockShape = new BoxGeometry(...BLOCK), ballShape = new SphereGeometry(BALL_R, 80, 40);+ made.forEach((m, i) => (add(`block_${i}`, new Mesh(blockShape, m), [0, 0, 0], block).visible = i === START.material));+ const ground = matte("ground_glass", 0xd3ddd9, 0.9);+ for (const sx of [-1, 1]) add(`block_end_${sx < 0 ? "a" : "b"}`, new Mesh(new BoxGeometry(0.0006, BLOCK[1], BLOCK[2]), ground), [sx * (BLOCK[0] / 2 + 0.0005), 0, 0], block);++ // 3. A glass ball on a stand in front of a card of arrows.+ made.forEach((m, i) => (add(`ball_${i}`, new Mesh(ballShape, m), [BALL_X, BALL_Y, 0]).visible = i === START.material));+ const wood = matte("wood", 0xb58a5a, 0.6);+ add("ball_stand", new Mesh(new CylinderGeometry(0.024, 0.028, STAND_H, 48, 1), wood), [BALL_X, STAND_H / 2, 0]);+ add("ball_ring", new Mesh(new TorusGeometry(RING_R, RING_T, 12, 48), matte("ring", 0x2b2b2e, 0.5)), [BALL_X, STAND_H + RING_T, 0]).rotation.x = Math.PI / 2;++ // The cards stand in slotted wooden feet at their ends.+ const card = (id: string, map: DataTexture, w: number, h: number, x: number) => {+ add(`${id}_card`, new Mesh(new BoxGeometry(w, h, 0.003), new MeshStandardMaterial({ name: `${id}_card`, map, roughness: 0.75 })), [x, h / 2 + 0.004, CARD_Z]);+ for (const sx of [-1, 1]) add(`${id}_foot_${sx < 0 ? "a" : "b"}`, new Mesh(new BoxGeometry(0.016, 0.012, 0.04), wood), [x + sx * (w / 2 - 0.012), 0.006, CARD_Z]);+ };+ card("block", stripes(), 0.204, 0.2, 0);+ card("ball", arrows(), 0.2, 0.2, BALL_X + 0.03);++ // A softbox above and in front, to the left.+ const softbox = add("softbox", new RectAreaLight(new Color().setRGB(1, 0.96, 0.9), 7000, 1.2, 0.8), [-0.5, 0.95, 0.5]);+ softbox.lookAt(0, 0.04, -0.02);+ softbox.card = false;++ const camera = new PerspectiveCamera(31, 16 / 9, 0.01, 50);+ camera.id = "camera";+ camera.position.set(...VIEWS.all.pos);+ camera.lookAt(...VIEWS.all.target);+ camera.setManualExposure(10.3);+ scene.add(camera);+ // The preview preset ends a path after 3 bounces, which is not enough to get through glass and light what is+ // behind it. Offline takes the 10; the live view takes at most 4 of them.+ return { scene, camera, options: { name: "refraction", preset: "preview" as const, width: 1280, height: 720, overrides: { native: { maxBounces: 10 } } } };+ },++ frame,++ handlers: {+ click(tx, ev: { target?: string }) {+ const id = ev.target ?? "";+ const focus: Focus = id.startsWith("glass") ? "glass" : id.startsWith("block") ? "block" : id.startsWith("ball") ? "ball" : "all";+ tx.state.focus = tx.state.focus === focus ? "all" : focus;+ },+ material(tx) {+ tx.state.material = (tx.state.material + 1) % MATERIALS.length;+ },+ turn(tx) {+ tx.state.turn += 1;+ },+ view(tx) {+ tx.state.focus = FOCI[(FOCI.indexOf(tx.state.focus) + 1) % FOCI.length];+ },+ reset(tx) {+ tx.state.material = START.material;+ tx.state.turn = START.turn;+ tx.state.focus = START.focus;+ },+ },++ keys: { M: "material", T: "turn", V: "view", R: "reset" },+});diff --git a/showcase/refraction/thumb.jpg b/showcase/refraction/thumb.jpgnew file mode 100644index 0000000..9c38f12Binary files /dev/null and b/showcase/refraction/thumb.jpg differdiff --git a/showcase/showroom/CREDITS.md b/showcase/showroom/CREDITS.mdnew file mode 100644index 0000000..7147502--- /dev/null+++ b/showcase/showroom/CREDITS.md@@ -0,0 +1,39 @@+# Showroom: credits++The six products are models from the Khronos Group's glTF Sample Assets+(https://github.com/KhronosGroup/glTF-Sample-Assets). Each was downloaded as+`Models/<Name>/glTF-Binary/<Name>.glb` and repacked by `showcase/showroom/repack-assets.mjs` into+`threert-assets/showcase/showroom/` (5.5 MB together, the largest file 1.8 MB). The licence is the one in each+model's `LICENSE.md` / `README.md`, read on 2026-11-12.++| File | What it is | Author | Licence | Source |+|---|---|---|---|---|+| `shoe.glb` | Sneaker in three colourways (Materials Variants Shoe) | © 2021 Shopify | [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) | https://github.com/KhronosGroup/glTF-Sample-Assets/tree/main/Models/MaterialsVariantsShoe |+| `sunglasses.glb` | Aviator sunglasses (Sunglasses Khronos) | © 2024 Darmstadt Graphics Group GmbH, model and textures by Eric Chadwick | [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) | https://github.com/KhronosGroup/glTF-Sample-Assets/tree/main/Models/SunglassesKhronos |+| `lamp.glb` | Glass table lamp (Iridescence Lamp) | © 2022 Wayfair, LLC, by Eric Chadwick | [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) | https://github.com/KhronosGroup/glTF-Sample-Assets/tree/main/Models/IridescenceLamp |+| `chair.glb` | Velvet slipper chair in two colourways (Sheen Chair) | Wayfair, LLC, by Eric Chadwick (2020) | [CC0 1.0](https://creativecommons.org/publicdomain/zero/1.0/) | https://github.com/KhronosGroup/glTF-Sample-Assets/tree/main/Models/SheenChair |+| `boombox.glb` | Boom box (Boom Box) | Microsoft (2017) | [CC0 1.0](https://creativecommons.org/publicdomain/zero/1.0/) | https://github.com/KhronosGroup/glTF-Sample-Assets/tree/main/Models/BoomBox |+| `bottle.glb` | Water bottle (Water Bottle) | Microsoft (2017) | [CC0 1.0](https://creativecommons.org/publicdomain/zero/1.0/) | https://github.com/KhronosGroup/glTF-Sample-Assets/tree/main/Models/WaterBottle |++## Changes made to the files (CC BY asks that they are stated)++All six: textures scaled to at most 1024 px (most were 2048 px) and stored as JPEG; geometry untouched; a note of the+repack in `asset.extras.modified`.++- `shoe.glb`: `KHR_materials_variants` (not read by the engine) replaced by one node per colourway (`shoe_midnight`,+ `shoe_beach`, `shoe_street`) that share the mesh.+- `sunglasses.glb`: the ear hooks' texture, which is the Khronos Group and 3D Commerce logos (trademarks, excluded+ from the licence), replaced by a plain near-black. The two lens materials (a clear index-1 shell under an+ iridescent film, `KHR_materials_iridescence`, which the engine does not read) replaced by opaque dark polished+ glass (base colour 0.012, roughness 0.03, ior 1.5). The original's blue-violet mirror coating is therefore not shown.+- `lamp.glb`: no change besides the textures. Its `KHR_materials_iridescence` and `KHR_materials_volume` are not+ read by the engine: the glass and the inside of the shade are shown without the iridescent tint.+- `chair.glb`: `KHR_materials_variants` replaced by nodes (`chair_fabric_mango` / `chair_fabric_peacock`,+ `chair_wood_brown` / `chair_wood_black`, `chair_metal`); the paper label under the seat is left out of the scene.+ `KHR_materials_sheen` is kept in the file but not read by the engine (the velvet has no sheen lobe).+- `boombox.glb`: `KHR_materials_emissive_strength` 400 added, so that the display and lamps (emissive 1 in the+ original) read in a lit room.+- `bottle.glb`: no change besides the textures.++Everything else in the scene (the room, plinths, shelves, the terrazzo, oak and plaster textures, the street) is+generated by `showroom.game.ts`.diff --git a/showcase/showroom/assets/boombox.glb b/showcase/showroom/assets/boombox.glbnew file mode 100644index 0000000..f573fd2Binary files /dev/null and b/showcase/showroom/assets/boombox.glb differdiff --git a/showcase/showroom/assets/bottle.glb b/showcase/showroom/assets/bottle.glbnew file mode 100644index 0000000..55955e3Binary files /dev/null and b/showcase/showroom/assets/bottle.glb differdiff --git a/showcase/showroom/assets/chair.glb b/showcase/showroom/assets/chair.glbnew file mode 100644index 0000000..68fd19cBinary files /dev/null and b/showcase/showroom/assets/chair.glb differdiff --git a/showcase/showroom/assets/lamp.glb b/showcase/showroom/assets/lamp.glbnew file mode 100644index 0000000..ef2f050Binary files /dev/null and b/showcase/showroom/assets/lamp.glb differdiff --git a/showcase/showroom/assets/shoe.glb b/showcase/showroom/assets/shoe.glbnew file mode 100644index 0000000..fb17a83Binary files /dev/null and b/showcase/showroom/assets/shoe.glb differdiff --git a/showcase/showroom/assets/sunglasses.glb b/showcase/showroom/assets/sunglasses.glbnew file mode 100644index 0000000..0abfc69Binary files /dev/null and b/showcase/showroom/assets/sunglasses.glb differdiff --git a/showcase/showroom/case.json b/showcase/showroom/case.jsonnew file mode 100644index 0000000..e93b33b--- /dev/null+++ b/showcase/showroom/case.json@@ -0,0 +1,67 @@+{+ "id": "showroom",+ "industry": "Commerce",+ "title": "Boutique Showroom",+ "caption": "A shop to walk through, lit by its window and its spots",+ "blurb": "A small boutique with six real products on plinths and shelves: click one and the camera walks over for a close look. The only lights are the sun through the shop window and the shop’s own lamps, so the warm bounce off the terrazzo, the soft shadow under each product and the reflections in the floor are traced as you watch, by day and in the evening.",+ "controls": [+ {+ "input": "Click a product",+ "does": "walks the camera to it; again to step back"+ },+ {+ "input": "N, P",+ "does": "next and previous product"+ },+ {+ "input": "C",+ "does": "changes the colour of the sneaker or the chair"+ },+ {+ "input": "M",+ "does": "day to evening and back"+ },+ {+ "input": "O or Space",+ "does": "back to the whole shop"+ }+ ],+ "credits": [+ {+ "what": "Sneaker: Materials Variants Shoe (textures resized, colourways split into nodes)",+ "by": "Shopify",+ "licence": "CC BY 4.0",+ "url": "https://github.com/KhronosGroup/glTF-Sample-Assets/tree/main/Models/MaterialsVariantsShoe"+ },+ {+ "what": "Sunglasses: Sunglasses Khronos (logos removed, lens material replaced by plain dark glass)",+ "by": "Eric Chadwick, Darmstadt Graphics Group GmbH",+ "licence": "CC BY 4.0",+ "url": "https://github.com/KhronosGroup/glTF-Sample-Assets/tree/main/Models/SunglassesKhronos"+ },+ {+ "what": "Table lamp: Iridescence Lamp (textures resized)",+ "by": "Eric Chadwick, Wayfair, LLC",+ "licence": "CC BY 4.0",+ "url": "https://github.com/KhronosGroup/glTF-Sample-Assets/tree/main/Models/IridescenceLamp"+ },+ {+ "what": "Chair: Sheen Chair",+ "by": "Eric Chadwick, Wayfair, LLC",+ "licence": "CC0 1.0",+ "url": "https://github.com/KhronosGroup/glTF-Sample-Assets/tree/main/Models/SheenChair"+ },+ {+ "what": "Boom box: Boom Box",+ "by": "Microsoft",+ "licence": "CC0 1.0",+ "url": "https://github.com/KhronosGroup/glTF-Sample-Assets/tree/main/Models/BoomBox"+ },+ {+ "what": "Water bottle: Water Bottle",+ "by": "Microsoft",+ "licence": "CC0 1.0",+ "url": "https://github.com/KhronosGroup/glTF-Sample-Assets/tree/main/Models/WaterBottle"+ }+ ]+}diff --git a/showcase/showroom/repack-assets.mjs b/showcase/showroom/repack-assets.mjsnew file mode 100644index 0000000..451cfd1--- /dev/null+++ b/showcase/showroom/repack-assets.mjs@@ -0,0 +1,175 @@+// How the showroom's product files were made from the Khronos glTF sample assets (see CREDITS.md): each original+// .glb is read as data, its textures are scaled to at most 1024 px and stored as JPEG (PNG where there is alpha), and+// KHR_materials_variants (which the engine does not read) is turned into one named node per colourway, so that scene+// code can pick a colourway with `new GLTFModel(uri, { nodes: [...] })`. Geometry is untouched.+//+// node showcase/showroom/repack-assets.mjs <dir with the original .glb files, <Name>/<Name>.glb> <output dir>+//+// Originals: https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/<Name>/glTF-Binary/<Name>.glb+import { readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import sharp from "sharp";++const [src, out] = process.argv.slice(2);+if (!src || !out) throw new Error("usage: node repack-assets.mjs <originals dir> <output dir>");++function readGlb(path) {+ const b = readFileSync(path);+ if (b.readUInt32LE(0) !== 0x46546c67) throw new Error(`${path}: not a GLB`);+ let off = 12, json = null, bin = null;+ while (off < b.length) {+ const len = b.readUInt32LE(off), type = b.readUInt32LE(off + 4);+ const data = b.subarray(off + 8, off + 8 + len);+ if (type === 0x4e4f534a) json = JSON.parse(data.toString("utf8"));+ else if (type === 0x004e4942) bin = data;+ off += 8 + len;+ }+ return { json, bin };+}++/** Writes a GLB of `json` whose bufferViews' bytes are `views[i]` (unused views dropped by the caller). */+function writeGlb(path, json, views) {+ const parts = [];+ let len = 0;+ json.bufferViews = views.map((v, i) => {+ const pad = (4 - (len % 4)) % 4;+ if (pad) (parts.push(Buffer.alloc(pad)), (len += pad));+ const bv = { ...json.bufferViews[i], buffer: 0, byteOffset: len, byteLength: v.length };+ parts.push(v);+ len += v.length;+ return bv;+ });+ const padEnd = (4 - (len % 4)) % 4;+ if (padEnd) (parts.push(Buffer.alloc(padEnd)), (len += padEnd));+ json.buffers = [{ byteLength: len }];+ let js = Buffer.from(JSON.stringify(json), "utf8");+ if (js.length % 4) js = Buffer.concat([js, Buffer.alloc(4 - (js.length % 4), 0x20)]);+ const head = Buffer.alloc(12);+ head.writeUInt32LE(0x46546c67, 0);+ head.writeUInt32LE(2, 4);+ head.writeUInt32LE(12 + 8 + js.length + 8 + len, 8);+ const h1 = Buffer.alloc(8), h2 = Buffer.alloc(8);+ h1.writeUInt32LE(js.length, 0);+ h1.writeUInt32LE(0x4e4f534a, 4);+ h2.writeUInt32LE(len, 0);+ h2.writeUInt32LE(0x004e4942, 4);+ const all = Buffer.concat([head, h1, js, h2, ...parts]);+ writeFileSync(path, all);+ return all.length;+}++/**+ * `edit(json)` changes the document (nodes, materials); then the images of materials that nothing in the scene draws+ * any more are emptied and the rest re-encoded. `flat`: image index -> [r, g, b] to replace an image with one colour.+ */+async function repack(name, outName, { edit, max = 1024, quality = 88, flat = {} } = {}) {+ const { json: j, bin } = readGlb(join(src, name, `${name}.glb`));+ const views = j.bufferViews.map((bv) => Buffer.from(bin.subarray(bv.byteOffset ?? 0, (bv.byteOffset ?? 0) + bv.byteLength)));+ edit?.(j);+ j.asset.extras = { ...(j.asset.extras ?? {}), modified: `Repacked from KhronosGroup/glTF-Sample-Assets Models/${name} for the ThreeRT showroom showcase: textures at most ${max} px, see CREDITS.md` };+ // Materials that a mesh still draws, textures those use, images those use.+ const drawn = new Set();+ const visit = (n) => (j.nodes[n].mesh !== undefined && drawn.add(j.nodes[n].mesh), (j.nodes[n].children ?? []).forEach(visit));+ j.scenes[j.scene ?? 0].nodes.forEach(visit);+ const usedMat = new Set([...drawn].flatMap((m) => j.meshes[m].primitives.map((p) => p.material)).filter((m) => m !== undefined));+ const texOf = (m) => {+ const t = [];+ JSON.stringify(m, (k, v) => (v && typeof v === "object" && typeof v.index === "number" && /[tT]exture$/.test(k) ? (t.push(v.index), v) : v));+ return t;+ };+ const usedImg = new Set([...usedMat].flatMap((m) => texOf(j.materials[m])).map((t) => j.textures[t].source));+ for (let i = 0; i < (j.images ?? []).length; i++) {+ const im = j.images[i];+ if (!usedImg.has(i)) {+ // Not drawn any more: a 2 x 2 grey stand-in keeps the file valid.+ views[im.bufferView] = await sharp({ create: { width: 2, height: 2, channels: 3, background: { r: 128, g: 128, b: 128 } } }).jpeg().toBuffer();+ im.mimeType = "image/jpeg";+ continue;+ }+ let img = flat[i] ? sharp({ create: { width: 8, height: 8, channels: 3, background: { r: flat[i][0], g: flat[i][1], b: flat[i][2] } } }) : sharp(views[im.bufferView]).resize(max, max, { fit: "inside", withoutEnlargement: true });+ const meta = flat[i] ? { hasAlpha: false } : await sharp(views[im.bufferView]).metadata();+ const opaque = !meta.hasAlpha || (await sharp(views[im.bufferView]).stats()).channels[3].min === 255;+ if (opaque) {+ views[im.bufferView] = await img.removeAlpha().jpeg({ quality, chromaSubsampling: "4:4:4", mozjpeg: true }).toBuffer();+ im.mimeType = "image/jpeg";+ } else {+ views[im.bufferView] = await img.png({ compressionLevel: 9 }).toBuffer();+ im.mimeType = "image/png";+ }+ }+ const bytes = writeGlb(join(out, outName), j, views);+ console.log(`${outName}: ${(bytes / 1048576).toFixed(2)} MiB (${name})`);+}++/** KHR_materials_variants -> one node per (node, material) the variants name, called `<prefix><label>`. */+function dropVariants(j) {+ delete j.extensions?.KHR_materials_variants;+ if (j.extensions && !Object.keys(j.extensions).length) delete j.extensions;+ j.extensionsUsed = (j.extensionsUsed ?? []).filter((e) => e !== "KHR_materials_variants");+ for (const m of j.meshes) for (const p of m.primitives) if (p.extensions) (delete p.extensions.KHR_materials_variants, Object.keys(p.extensions).length || delete p.extensions);+}+/** A copy of node `from` (same mesh geometry, another material) named `name`, next to it under the same parent. */+function nodeWithMaterial(j, from, name, material) {+ const n = j.nodes[from];+ const mesh = JSON.parse(JSON.stringify(j.meshes[n.mesh]));+ for (const p of mesh.primitives) p.material = material;+ j.meshes.push(mesh);+ j.nodes.push({ ...n, name, mesh: j.meshes.length - 1, children: undefined });+ const id = j.nodes.length - 1;+ const parent = j.nodes.find((x) => x.children?.includes(from));+ if (parent) parent.children.push(id);+ else j.scenes[j.scene ?? 0].nodes.push(id);+}+const nodeIndex = (j, name) => {+ const i = j.nodes.findIndex((n) => n.name === name);+ if (i < 0) throw new Error(`no node ${name}`);+ return i;+};++// The sneaker: three colourways (diffuse maps) as three nodes.+await repack("MaterialsVariantsShoe", "shoe.glb", {+ edit(j) {+ dropVariants(j);+ const base = nodeIndex(j, "Shoe");+ ["midnight", "beach", "street"].forEach((v, i) => {+ j.materials[i].name = `shoe_${v}`;+ if (i === 0) j.nodes[base].name = "shoe_midnight";+ else nodeWithMaterial(j, base, `shoe_${v}`, i);+ });+ },+});+// The velvet chair: mango / peacock fabric with brown / black wood as nodes; the paper label under the seat left out.+await repack("SheenChair", "chair.glb", {+ edit(j) {+ dropVariants(j);+ const fabric = nodeIndex(j, "SheenChair_fabric"), wood = nodeIndex(j, "SheenChair_wood"), label = nodeIndex(j, "SheenChair_label");+ j.nodes[fabric].name = "chair_fabric_mango";+ j.nodes[wood].name = "chair_wood_brown";+ j.nodes[nodeIndex(j, "SheenChair_metal")].name = "chair_metal";+ nodeWithMaterial(j, fabric, "chair_fabric_peacock", 4);+ nodeWithMaterial(j, wood, "chair_wood_black", 5);+ j.scenes[j.scene ?? 0].nodes = j.scenes[j.scene ?? 0].nodes.filter((n) => n !== label);+ },+});+await repack("IridescenceLamp", "lamp.glb");+// The sunglasses: the ear hooks' texture is two trademark logos (not covered by the licence): replaced by its black.+// The lenses are a clear, index-1 shell under an iridescent mirror film (KHR_materials_iridescence), which the engine+// does not read: as authored they come out as flat black holes. Both lens materials are replaced by what such a lens+// is without its film, dark polished glass that mirrors the room (opaque, index 1.5).+await repack("SunglassesKhronos", "sunglasses.glb", {+ flat: { 0: [28, 28, 28] },+ edit(j) {+ for (const m of j.materials.filter((m) => m.name.startsWith("lens_"))) {+ m.pbrMetallicRoughness = { baseColorFactor: [0.012, 0.012, 0.016, 1], metallicFactor: 0, roughnessFactor: 0.03 };+ m.extensions = { KHR_materials_ior: { ior: 1.5 } };+ }+ },+});+await repack("WaterBottle", "bottle.glb");+// The boom box: its display and lamps are emissive at glTF's 1 (nits here); given a strength that reads in a lit room.+await repack("BoomBox", "boombox.glb", {+ edit(j) {+ j.materials[0].extensions = { ...(j.materials[0].extensions ?? {}), KHR_materials_emissive_strength: { emissiveStrength: 400 } };+ j.extensionsUsed = [...new Set([...(j.extensionsUsed ?? []), "KHR_materials_emissive_strength"])];+ },+});diff --git a/showcase/showroom/showroom.game.ts b/showcase/showroom/showroom.game.tsnew file mode 100644index 0000000..bea847c--- /dev/null+++ b/showcase/showroom/showroom.game.ts@@ -0,0 +1,505 @@+// "Showroom": a small boutique you walk through, the retail equivalent of a game level.+//+// A 6 x 7.2 m shop with a terrazzo floor, plaster walls and a steel shop window in the left wall. Six products stand in+// it at their real sizes: a sneaker, sunglasses, a glass table lamp and a boom box on plinths, a velvet chair on a round+// platform in front of a painted arch, water bottles on the oak shelf wall. By day the sun comes through the window and+// most of what lights the room is its patch on the floor, bounced; the track spots pick the products out. In the+// evening the window goes dark and the same spots, the shelf strips and the table lamp carry the room. Nothing is baked+// and there is no fill light: the pools, the soft shadows under the products, the plinths in the polished floor and+// the room in the lamp's glass and the sunglasses are all traced.+//+// Inputs:+// click / tap a product (or its plinth, or near it) the camera walks over for a close look through a longer+// lens; click it again, or anywhere else, to step back+// next (N, Right) / prev (P, Left) step through the six products+// overview (O, Space) back to the view from the door+// mood (M) day <-> evening: the sun sets in two seconds, the exposure+// follows it, the table lamp comes on+// colour (C) the next colourway of the product in view: the sneaker has+// three, the chair two (from the door it changes the sneaker)+//+// The products are Khronos glTF sample assets (showcase/showroom/CREDITS.md), repacked by repack-assets.mjs: 1k+// textures, and a node per colourway so that `GLTFModel`'s `nodes` picks one. The window is an opening without a pane+// and the shop has no mirror: the live view shades what is seen through sharp glass and mirrors more coarsely than+// what is seen directly, and here that was the street.+import {+ BoxGeometry, CircleGeometry, Color, CylinderGeometry, DataTexture, DirectionalLight, GLTFModel, Group, LatheGeometry, Mesh,+ MeshStandardMaterial, Object3D, PerspectiveCamera, PointLight, Scene, SkyAtmosphere, SphereGeometry, SpotLight, Vector3,+} from "@threert/scene";+import { defineGame, type FrameContext } from "@threert/gameplay";++type Vec3 = [number, number, number];+const ASSETS = "assets/showcase/showroom/";++// ------------------------------------------------------------------------------------------------ the shop+/** Inside faces: x = -X .. X, z = -Z .. Z (the door is behind the camera at +Z), the ceiling at H. Metres. */+const X = 3, Z = 3.6, H = 2.9, WALL = 0.25;+/** The shop window, an opening in the left wall (x = -X). */+const WIN = { z0: -2.0, z1: 1.6, y0: 0.4, y1: 2.6 };+/** The sun by day and at dusk (degrees), and the exposure for each. */+const SUN = { lux: 22000, azimuth: -105, day: 48, dusk: -6, evDay: 10.2, evDusk: 8.0, degPerSecond: 27 };+/** The shop's evening scene: the track spots dimmed to this, the one on the table lamp to less (the lamp is on). */+const EVENING_SPOTS = 0.35, EVENING_LAMP_SPOT = 0.12;+const SPOTS = ["shoe", "sunglasses", "lamp", "boombox", "chair", "arch", "shelf_a", "shelf_b"];+/** Warm white of the spots and strips (linear, against a daylight white balance). */+const WARM: Vec3 = [1, 0.74, 0.5];++interface Product {+ key: string;+ file: string;+ /** Where the model's origin goes (the top of its stand), its turn (radians) and its scale. */+ at: Vec3;+ yaw: number;+ scale: number;+ /** The model's origin above the stand (models whose origin is their centre). */+ lift: number;+ /** What the close view looks at, above `at`; and where it looks from: bearing (degrees, 0 = from +Z), elevation, m. */+ centre: number;+ view: { bearing: number; elevation: number; distance: number };+ /** How near its centre a click's ray has to pass to mean this product (m): a finger's worth round small things. */+ reach: number;+ /** Colourways: the file's nodes for each. */+ variants: string[][] | null;+}++const PRODUCTS: Product[] = [+ { key: "shoe", file: "shoe.glb", at: [0.2, 1.0, 0.55], yaw: 0.5, scale: 1, lift: 0, centre: 0.065, view: { bearing: 2, elevation: 5, distance: 0.74 }, reach: 0.26, variants: [["shoe_midnight"], ["shoe_beach"], ["shoe_street"]] },+ { key: "sunglasses", file: "sunglasses.glb", at: [1.0, 1.135, 1.4], yaw: 0.3, scale: 1, lift: 0, centre: 0.03, view: { bearing: -16, elevation: 7, distance: 0.47 }, reach: 0.2, variants: null },+ { key: "lamp", file: "lamp.glb", at: [-1.9, 0.8, -0.3], yaw: 0, scale: 1, lift: 0, centre: 0.24, view: { bearing: 24, elevation: 6, distance: 1.55 }, reach: 0.34, variants: null },+ { key: "boombox", file: "boombox.glb", at: [1.6, 0.72, -1.0], yaw: -0.2, scale: 18, lift: 0.0098 * 18, centre: 0.17, view: { bearing: -10, elevation: 7, distance: 1.05 }, reach: 0.3, variants: null },+ { key: "chair", file: "chair.glb", at: [-1.9, 0.1, -2.5], yaw: 0.45, scale: 1, lift: 0, centre: 0.38, view: { bearing: 36, elevation: 9, distance: 2.4 }, reach: 0.55, variants: [["chair_fabric_mango", "chair_wood_brown", "chair_metal"], ["chair_fabric_peacock", "chair_wood_black", "chair_metal"]] },+ { key: "bottle", file: "bottle.glb", at: [1.55, 1.285, -3.44], yaw: 0.3, scale: 1, lift: 0.1302, centre: 0.13, view: { bearing: -8, elevation: 7, distance: 0.95 }, reach: 0.34, variants: null },+];+const INDEX: Record<string, number> = Object.fromEntries(PRODUCTS.map((p, i) => [p.key, i]));++/** The view from the door, and the lens (vertical field of view, degrees) there and close to a product. */+const OVERVIEW = { eye: [0.9, 1.45, 2.85] as Vec3, target: [-0.3, 1.2, -1.0] as Vec3 };+const FOV = { overview: 42, close: 31 };++function closeView(p: Product): { eye: Vec3; target: Vec3 } {+ const b = (p.view.bearing * Math.PI) / 180, e = (p.view.elevation * Math.PI) / 180, d = p.view.distance;+ const target: Vec3 = [p.at[0], p.at[1] + p.centre, p.at[2]];+ return { eye: [target[0] + Math.sin(b) * Math.cos(e) * d, target[1] + Math.sin(e) * d, target[2] + Math.cos(b) * Math.cos(e) * d], target };+}++/** The product a click means: the one whose centre the ray from `eye` to the point clicked passes nearest, relative+ * to its reach; -1 when the ray passes none within reach. */+function nearRay(eye: Vec3, point: Vec3): number {+ const d: Vec3 = [point[0] - eye[0], point[1] - eye[1], point[2] - eye[2]], len = Math.hypot(...d) || 1;+ let hit = -1, best = 1;+ PRODUCTS.forEach((p, i) => {+ const c: Vec3 = [p.at[0] - eye[0], p.at[1] + p.centre - eye[1], p.at[2] - eye[2]];+ const t = clamp((c[0] * d[0] + c[1] * d[1] + c[2] * d[2]) / len, 0, len + 0.3) / len;+ const miss = Math.hypot(c[0] - d[0] * t, c[1] - d[1] * t, c[2] - d[2] * t) / p.reach;+ if (miss < best) (best = miss), (hit = i);+ });+ return hit;+}++interface State {+ /** The product in view (index into PRODUCTS), -1: the view from the door. */+ focus: number;+ evening: boolean;+ /** Colourway by product key. */+ colour: Record<string, number>;+}++// ------------------------------------------------------------------------------------------------ generated textures+/** A small deterministic generator (mulberry32): the textures are the same on every node. */+function rng(seed: number): () => number {+ let a = seed >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) >>> 0;+ let t = a;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++/** Terrazzo: marble and stone chips (6 to 30 mm at 2 m a tile) in a warm white binder; tiles seamlessly. */+function terrazzo(size = 1024): DataTexture {+ const r = rng(7);+ const px = new Uint8Array(size * size * 4);+ for (let i = 0; i < size * size; i++) {+ const n = (r() - 0.5) * 9;+ px[i * 4] = 214 + n;+ px[i * 4 + 1] = 208 + n;+ px[i * 4 + 2] = 198 + n;+ px[i * 4 + 3] = 255;+ }+ const chips: Vec3[] = [[178, 108, 80], [200, 158, 116], [98, 104, 96], [58, 60, 62], [240, 237, 230], [146, 158, 138], [198, 182, 166], [120, 92, 74], [232, 226, 214]];+ for (let c = 0; c < 2600; c++) {+ const cx = r() * size, cy = r() * size, rad = 2.5 + 13 * r() ** 2.2;+ const col = chips[Math.floor(r() * chips.length)], shade = 0.86 + 0.24 * r();+ // A convex chip: the intersection of 5 to 7 half-planes round the centre.+ const k = 5 + Math.floor(r() * 3), nx: number[] = [], ny: number[] = [], nd: number[] = [];+ const a0 = r() * 6.283;+ for (let j = 0; j < k; j++) {+ const a = a0 + ((j + 0.7 * r()) / k) * 6.283;+ nx.push(Math.cos(a));+ ny.push(Math.sin(a));+ nd.push(rad * (0.55 + 0.45 * r()));+ }+ const R = Math.ceil(rad);+ for (let dy = -R; dy <= R; dy++)+ for (let dx = -R; dx <= R; dx++) {+ let inside = true;+ for (let j = 0; j < k && inside; j++) inside = dx * nx[j] + dy * ny[j] <= nd[j];+ if (!inside) continue;+ const x = (((Math.round(cx) + dx) % size) + size) % size, y = (((Math.round(cy) + dy) % size) + size) % size, o = (y * size + x) * 4;+ px[o] = Math.min(255, col[0] * shade);+ px[o + 1] = Math.min(255, col[1] * shade);+ px[o + 2] = Math.min(255, col[2] * shade);+ }+ }+ return new DataTexture(size, size, px);+}++/** Oak: long grain along u, a few darker rays, soft colour drift. */+function oak(size = 512): DataTexture {+ const r = rng(21);+ const px = new Uint8Array(size * size * 4);+ // One value per row, smoothed twice at different widths: grain lines, and the board's slow drift.+ const row = Array.from({ length: size }, () => r()), fine: number[] = [], slow: number[] = [];+ for (let y = 0; y < size; y++) {+ let a = 0, b = 0;+ for (let k = -2; k <= 2; k++) a += row[(y + k + size) % size];+ for (let k = -24; k <= 24; k++) b += row[(y + k + size) % size];+ fine.push(a / 5);+ slow.push(b / 49);+ }+ for (let y = 0; y < size; y++)+ for (let x = 0; x < size; x++) {+ const wob = Math.sin((x / size) * 6.283 * 2 + y * 0.05) * 3;+ const yy = (((y + Math.round(wob)) % size) + size) % size;+ const g = 0.9 + 0.22 * (fine[yy] - 0.5) + 0.9 * (slow[yy] - 0.5) + (r() - 0.5) * 0.03;+ const o = (y * size + x) * 4;+ px[o] = Math.max(0, Math.min(255, 186 * g + 22));+ px[o + 1] = Math.max(0, Math.min(255, 146 * g + 14));+ px[o + 2] = Math.max(0, Math.min(255, 102 * g + 6));+ px[o + 3] = 255;+ }+ return new DataTexture(size, size, px);+}++/** Trowelled plaster: a few per cent of soft mottling, so that a wall is not one flat colour. Tiles seamlessly. */+function plasterMap(size = 256): DataTexture {+ const r = rng(40);+ const cells = 16, grid = Array.from({ length: cells * cells }, () => r());+ const at = (x: number, y: number) => grid[(((y % cells) + cells) % cells) * cells + (((x % cells) + cells) % cells)];+ const px = new Uint8Array(size * size * 4);+ for (let y = 0; y < size; y++)+ for (let x = 0; x < size; x++) {+ const u = (x / size) * cells, v = (y / size) * cells, x0 = Math.floor(u), y0 = Math.floor(v);+ const fu = smooth(u - x0), fv = smooth(v - y0);+ const n = (at(x0, y0) * (1 - fu) + at(x0 + 1, y0) * fu) * (1 - fv) + (at(x0, y0 + 1) * (1 - fu) + at(x0 + 1, y0 + 1) * fu) * fv;+ const c = 255 - 9 * n - 3 * r(), o = (y * size + x) * 4;+ px[o] = px[o + 1] = px[o + 2] = c;+ px[o + 3] = 255;+ }+ return new DataTexture(size, size, px);+}++// ------------------------------------------------------------------------------------------------ the frame script+const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v));+const smooth = (u: number) => u * u * (3 - 2 * u);++/** Manual exposure (EV100) for a sun elevation: the daylit room's down to the evening's. */+function evAt(elevation: number): number {+ return SUN.evDusk + (SUN.evDay - SUN.evDusk) * daylight(elevation);+}+/** 1 by day .. 0 once the sun is 4 degrees down: what the exposure and the spots' dimmer follow. */+function daylight(elevation: number): number {+ return smooth(clamp((elevation + 4) / 16, 0, 1));+}++// Where the frame script has the camera and the sun (this node's animation state, not game state): the walk from+// one view to the next takes a fixed time and ends exactly there, so that the picture can settle.+const eye: Vec3 = [...OVERVIEW.eye], look: Vec3 = [...OVERVIEW.target];+let zoom = FOV.overview, shown = -2, still = false;+let walk = { fromEye: eye.slice() as Vec3, fromLook: look.slice() as Vec3, fromZoom: zoom, t0: 0, seconds: 1, rise: 0 };+let sunElevation = SUN.day;+const colours: Record<string, number> = {};+const tmp = new Vector3();+const mix = (a: number, b: number, k: number) => a + (b - a) * k;++function frame(f: FrameContext<State>) {+ const s = f.state;++ // The camera walks to the view the state names, the lens changing on the way, and comes to rest there.+ const goal = s.focus < 0 ? OVERVIEW : closeView(PRODUCTS[s.focus]), fov = s.focus < 0 ? FOV.overview : FOV.close;+ if (s.focus !== shown || f.snap) {+ shown = s.focus;+ still = false;+ const far = Math.hypot(eye[0] - goal.eye[0], eye[1] - goal.eye[1], eye[2] - goal.eye[2]);+ // (A long walk rises a hand on the way, over the plinths it passes.)+ walk = { fromEye: [...eye], fromLook: [...look], fromZoom: zoom, t0: f.time, seconds: f.snap ? 0 : clamp(0.9 + 0.22 * far, 1, 2.2), rise: 0.15 * clamp(far - 0.5, 0, 1) };+ }+ if (!still) {+ const u = walk.seconds > 0 ? clamp((f.time - walk.t0) / walk.seconds, 0, 1) : 1, k = u * u * u * (u * (6 * u - 15) + 10);+ for (let i = 0; i < 3; i++) (eye[i] = mix(walk.fromEye[i], goal.eye[i], k)), (look[i] = mix(walk.fromLook[i], goal.target[i], k));+ zoom = mix(walk.fromZoom, fov, k);+ eye[1] += walk.rise * Math.sin(Math.PI * k);+ f.camera.position.set(eye[0], eye[1], eye[2]);+ f.camera.lookAt(tmp.set(look[0], look[1], look[2]));+ f.camera.fov = zoom;+ still = u >= 1;+ }++ // Day and evening: the sun rises or sets, the exposure follows, the table lamp is on once the sun is down.+ // (Only while it moves: a sun that is set again makes the live view bake its sky again.)+ const to = s.evening ? SUN.dusk : SUN.day;+ const elevation = f.snap ? to : sunElevation + clamp(to - sunElevation, -SUN.degPerSecond * f.dt, SUN.degPerSecond * f.dt);+ if (f.snap || elevation !== sunElevation) {+ sunElevation = elevation;+ (f.object("sun") as DirectionalLight).setSunAngles(elevation, SUN.azimuth + (SUN.day - elevation) * 0.35);+ f.camera.setManualExposure(evAt(elevation));+ const dusk = elevation < 3 ? 1 : 0, dim = EVENING_SPOTS + (1 - EVENING_SPOTS) * daylight(elevation);+ for (const id of ["lamp_light", "lamp_bulb", "street"]) f.object(id)!.power = dusk;+ for (const k of SPOTS) for (const id of [`spot_${k}`, `lens_${k}`]) f.object(id)!.power = k === "lamp" && dusk ? EVENING_LAMP_SPOT : dim;+ }++ // Colourways (written only when one changes: writing a property marks the object as changed).+ for (const q of PRODUCTS) {+ const c = s.colour[q.key] ?? 0;+ if (!q.variants || (!f.snap && colours[q.key] === c)) continue;+ colours[q.key] = c;+ q.variants.forEach((_, v) => (f.object(`${q.key}_${v}`)!.visible = v === c));+ }+}++// ------------------------------------------------------------------------------------------------ the game+export default defineGame<State>({+ state: { focus: -1, evening: false, colour: { shoe: 0, chair: 0 } },++ setup() {+ const scene = new Scene();+ const rgb = (r: number, g: number, b: number) => new Color().setRGB(r, g, b);+ const std = (name: string, c: Vec3, roughness: number, metalness = 0) => new MeshStandardMaterial({ name, color: rgb(...c), roughness, metalness });++ const sun = new DirectionalLight(rgb(1, 0.96, 0.9), SUN.lux).setSunAngles(SUN.day, SUN.azimuth);+ sun.id = "sun";+ scene.add(sun);+ scene.environment = new SkyAtmosphere({ sun, dynamic: true, glow: rgb(0.18, 0.3, 0.75), glowIntensity: 30 });++ // ---- materials+ const floorMap = terrazzo();+ floorMap.repeat = [(2 * X + 2 * WALL) / 2, (2 * Z + 2 * WALL) / 2];+ const floorMat = new MeshStandardMaterial({ name: "terrazzo", map: floorMap, roughness: 0.1 });+ // Plaster for a wall face of w x h metres: the same mottling at 2.4 m a repeat whatever the face's shape.+ const mottle = plasterMap();+ const plaster = (w: number, h: number) => {+ const map = new DataTexture(mottle.width, mottle.height, mottle.pixels);+ map.repeat = [w / 2.4, h / 2.4];+ return new MeshStandardMaterial({ name: "plaster", color: rgb(0.82, 0.79, 0.74), map, roughness: 0.92 });+ };+ const ceilingMat = std("ceiling", [0.82, 0.82, 0.81], 0.95);+ const white = std("plinth_white", [0.8, 0.79, 0.77], 0.45);+ const sage = std("sage", [0.3, 0.37, 0.29], 0.55);+ const clay = std("clay", [0.52, 0.22, 0.13], 0.9);+ const steel = std("steel", [0.025, 0.025, 0.028], 0.38, 0.85);+ const brass = std("brass", [0.91, 0.78, 0.42], 0.28, 1);+ const oakMap = oak();+ const oakMat = new MeshStandardMaterial({ name: "oak", map: oakMap, roughness: 0.5 });+ const pavement = std("pavement", [0.3, 0.3, 0.3], 0.9);+ const stone = std("stone", [0.5, 0.46, 0.4], 0.9);+ const card = (c: Vec3) => std("card", c, 0.75);+ const ceramic = (c: Vec3) => std("ceramic", c, 0.3);+ const glow = (name: string, c: Vec3, nits: number) => new MeshStandardMaterial({ name, color: 0x000000, emissive: rgb(...c), emissiveIntensity: nits, roughness: 1 });++ // Ids are unique: the parts of one thing are "wall_left", "wall_left#2", ... (a click reads the name before the #).+ const used = new Map<string, number>();+ const add = <T extends Object3D>(o: T, id: string | null, at: Vec3, parent: Object3D = scene): T => {+ if (id) {+ const n = (used.get(id) ?? 0) + 1;+ used.set(id, n);+ o.id = n === 1 ? id : `${id}#${n}`;+ }+ o.position.set(...at);+ parent.add(o);+ return o;+ };+ const box = (id: string | null, size: Vec3, at: Vec3, m: MeshStandardMaterial, parent: Object3D = scene) => add(new Mesh(new BoxGeometry(...size), m), id, at, parent);+ const drum = (id: string | null, r: number, h: number, at: Vec3, m: MeshStandardMaterial, parent: Object3D = scene) => add(new Mesh(new CylinderGeometry(r, r, h, 64), m), id, at, parent);++ // ---- the shell+ const w = WALL, ox = X + w / 2, oz = Z + w / 2;+ box("floor", [2 * X + 2 * w, 0.3, 2 * Z + 2 * w], [0, -0.15, 0], floorMat);+ box("ceiling", [2 * X + 2 * w, 0.2, 2 * Z + 2 * w], [0, H + 0.1, 0], ceilingMat);+ box("wall_back", [2 * X + 2 * w, H, w], [0, H / 2, -oz], plaster(2 * X + 2 * w, H));+ box("wall_front", [2 * X + 2 * w, H, w], [0, H / 2, oz], plaster(2 * X + 2 * w, H));+ box("wall_right", [w, H, 2 * Z], [ox, H / 2, 0], plaster(2 * Z, H));+ // The left wall round the window: below the sill, above the head, and the two piers.+ box("wall_left", [w, WIN.y0, 2 * Z], [-ox, WIN.y0 / 2, 0], plaster(2 * Z, WIN.y0));+ box("wall_left", [w, H - WIN.y1, 2 * Z], [-ox, (H + WIN.y1) / 2, 0], plaster(2 * Z, H - WIN.y1));+ box("wall_left", [w, WIN.y1 - WIN.y0, WIN.z0 + Z], [-ox, (WIN.y0 + WIN.y1) / 2, (WIN.z0 - Z) / 2], plaster(WIN.z0 + Z, WIN.y1 - WIN.y0));+ box("wall_left", [w, WIN.y1 - WIN.y0, Z - WIN.z1], [-ox, (WIN.y0 + WIN.y1) / 2, (WIN.z1 + Z) / 2], plaster(Z - WIN.z1, WIN.y1 - WIN.y0));+ // The window: a steel frame with three mullions and an oak sill board (no pane: see the note at the top).+ const wz = (WIN.z0 + WIN.z1) / 2, wl = WIN.z1 - WIN.z0, wy = (WIN.y0 + WIN.y1) / 2, wh = WIN.y1 - WIN.y0, fx = -X - 0.1;+ for (const y of [WIN.y0 + 0.025, WIN.y1 - 0.025]) box("window", [0.07, 0.05, wl], [fx, y, wz], steel);+ for (let i = 0; i <= 4; i++) box("window", [0.07, wh, 0.05], [fx, wy, WIN.z0 + 0.025 + (i * (wl - 0.05)) / 4], steel);+ box("window", [0.3, 0.035, wl + 0.1], [-X - 0.08, WIN.y0 + 0.0175, wz], oakMat);+ // Skirting along the back and right walls.+ box("wall_back", [2 * X, 0.07, 0.012], [0, 0.035, -Z + 0.006], white);+ box("wall_right", [0.012, 0.07, 2 * Z], [X - 0.006, 0.035, 0], white);++ // ---- outside: a paved square in the sun with a road across it, a row of trees, and houses on the far side+ // with a few windows lit at dusk+ box("outside", [80, 0.2, 80], [-30, -0.12, 0], pavement);+ box("outside", [7, 0.02, 80], [-14, -0.015, 0], std("road", [0.09, 0.09, 0.1], 0.85));+ const street = add(new Group(), "street", [0, 0, 0]);+ const rs = rng(3);+ for (let i = 0; i < 9; i++) {+ const h = 5 + Math.floor(rs() * 3) * 1.6, z = -26 + i * 6.2, tone = 0.5 + 0.2 * rs();+ box("outside", [6, h, 6], [-27, h / 2, z], std("house", [tone, tone * 0.93, tone * 0.82], 0.9));+ box("outside", [6.3, 0.25, 6.3], [-27, h + 0.125, z], std("house_roof", [0.2, 0.12, 0.09], 0.8));+ for (let k = 0; k < 3; k++) if (rs() < 0.6) box(null, [0.02, 1.3, 1.0], [-23.98, 1.7 + 1.6 * Math.floor(rs() * 3), z - 1.8 + k * 1.8], new MeshStandardMaterial({ name: "street_window", color: rgb(0.05, 0.06, 0.07), roughness: 0.15, emissive: rgb(1, 0.6, 0.3), emissiveIntensity: 50 + 50 * rs() }), street);+ }+ const leaf = std("leaf", [0.07, 0.14, 0.045], 0.9), bark = std("bark", [0.12, 0.09, 0.07], 0.9);+ for (const tz of [-21, -15, -9, -3, 3]) {+ add(new Mesh(new CylinderGeometry(0.13, 0.16, 2.6, 12), bark), "outside", [-19, 1.3, tz]);+ for (let k = 0; k < 5; k++) add(new Mesh(new SphereGeometry(0.8 + 0.5 * rs(), 14, 9), leaf), "outside", [-19 + (rs() - 0.5) * 1.6, 3.1 + rs() * 1.4, tz + (rs() - 0.5) * 1.6]);+ }++ // ---- the ceiling tracks and their spots+ const rail = (size: Vec3, at: Vec3) => box("track", size, at, steel);+ rail([0.035, 0.03, 4.4], [-0.9, H - 0.015, 0.4]);+ rail([0.035, 0.03, 4.4], [0.9, H - 0.015, 0.4]);+ rail([4.4, 0.03, 0.035], [0.3, H - 0.015, -1.8]);+ const lens = glow("spot_lens", WARM, 9000);+ const spot = (id: string, at: Vec3, target: Vec3, candela: number, halfAngle: number) => {+ const from = new Vector3(...at), dir = new Vector3(...target).sub(from).normalize();+ drum("track", 0.012, 0.11, [at[0], H - 0.03 - 0.055, at[2]], steel);+ const can = add(new Group(), null, [at[0], at[1], at[2]]);+ can.lookAt(new Vector3(...target));+ const body = drum("track", 0.045, 0.15, [0, 0, 0], steel, can);+ body.rotation.x = Math.PI / 2;+ const face = add(new Mesh(new CircleGeometry(0.034, 16), lens), id.replace("spot", "lens"), [0, 0, 0.0755], can);+ face.castShadow = false;+ const l = new SpotLight(rgb(...WARM), candela, 9, halfAngle, 0.6);+ l.radius = 0.03;+ l.target!.position.set(...target);+ add(l, id, [from.x + dir.x * 0.085, from.y + dir.y * 0.085, from.z + dir.z * 0.085]);+ };+ const sy = H - 0.2;+ spot("spot_shoe", [0.9, sy, 1.75], [0.2, 1.06, 0.55], 59000, 0.17);+ spot("spot_sunglasses", [0.9, sy, 2.5], [1.0, 1.16, 1.4], 42000, 0.15);+ spot("spot_lamp", [-0.9, sy, 0.6], [-1.9, 1.0, -0.3], 50000, 0.19);+ spot("spot_boombox", [0.9, sy, 0.1], [1.6, 0.9, -1.0], 56000, 0.2);+ spot("spot_chair", [-0.9, sy, -1.2], [-1.9, 0.45, -2.5], 84000, 0.26);+ spot("spot_arch", [-1.7, sy, -1.8], [-1.9, 1.6, -3.6], 17000, 0.5);+ spot("spot_shelf_a", [0.9, sy, -1.8], [1.0, 1.45, -3.5], 22000, 0.5);+ spot("spot_shelf_b", [2.1, sy, -1.8], [2.2, 1.45, -3.5], 22000, 0.5);++ // ---- stands+ const at = (key: string) => PRODUCTS[INDEX[key]].at;+ const stand: Record<string, { plinth: (x: number, h: number, z: number) => void }> = {+ shoe: { plinth: (x, h, z) => box("plinth_shoe", [0.4, h, 0.4], [x, h / 2, z], white) },+ sunglasses: {+ plinth: (x, h, z) => {+ box("plinth_sunglasses", [0.3, h - 0.035, 0.3], [x, (h - 0.035) / 2, z], white);+ box("plinth_sunglasses", [0.22, 0.035, 0.19], [x, h - 0.0175, z], oakMat).rotation.y = 0.3;+ },+ },+ lamp: { plinth: (x, h, z) => drum("plinth_lamp", 0.24, h, [x, h / 2, z], white) },+ boombox: { plinth: (x, h, z) => box("plinth_boombox", [0.56, h, 0.56], [x, h / 2, z], sage) },+ chair: {+ plinth: (x, h, z) => {+ drum("plinth_chair", 0.74, h, [x, h / 2, z], white);+ // The painted arch behind it, a hand proud of the wall.+ box("arch", [1.5, 1.5, 0.02], [x, 0.75, -Z + 0.01], clay);+ const top = drum("arch", 0.75, 0.019, [x, 1.5, -Z + 0.0095], clay);+ top.rotation.x = Math.PI / 2;+ },+ },+ bottle: { plinth: () => {} },+ };+ for (const p of PRODUCTS) {+ stand[p.key].plinth(p.at[0], p.at[1], p.at[2]);+ const table = add(new Group(), `stand_${p.key}`, p.at);+ table.rotation.y = p.yaw;+ (p.variants ?? [null]).forEach((nodes, v) => {+ const m = add(new GLTFModel(ASSETS + p.file, nodes ? { nodes } : {}), `${p.key}_${v}`, [0, p.lift, 0], table);+ m.scale.set(p.scale, p.scale, p.scale);+ m.visible = v === 0;+ });+ }+ // The table lamp's own light, under its shade: on in the evening.+ const bulb = add(new Mesh(new SphereGeometry(0.028, 10, 6), glow("lamp_bulb", [1, 0.7, 0.42], 2500)), "lamp_bulb", [at("lamp")[0], at("lamp")[1] + 0.33, at("lamp")[2]]);+ bulb.castShadow = false;+ const lampLight = new PointLight(rgb(1, 0.7, 0.42), 260, 6);+ lampLight.radius = 0.028;+ add(lampLight, "lamp_light", [at("lamp")[0], at("lamp")[1] + 0.33, at("lamp")[2]]);++ // ---- the shelf wall: an oak back, four shelves with a warm strip under each, bottles and things+ const sx = 1.55, sw = 2.5, sz = -Z;+ box("shelf", [sw, 2.0, 0.03], [sx, 1.5, sz + 0.015], oakMat);+ const strip = glow("strip", [1, 0.68, 0.4], 5200);+ for (const y of [0.82, 1.25, 1.68, 2.11]) {+ box("shelf", [sw, 0.035, 0.3], [sx, y + 0.0175, sz + 0.18], oakMat);+ if (y > 0.9) box("shelf", [sw - 0.12, 0.008, 0.014], [sx, y - 0.004, sz + 0.05], strip).castShadow = false;+ }+ for (const x of [sx - sw / 2 + 0.0125, sx + sw / 2 - 0.0125]) box("shelf", [0.025, 2.0, 0.32], [x, 1.5, sz + 0.17], oakMat);+ // Stock next to the hero bottle (the same file again: instances share its geometry and textures).+ for (const [i, dx] of [-0.2, 0.2].entries()) {+ const b = add(new GLTFModel(ASSETS + "bottle.glb"), `bottle_side_${i}`, [at("bottle")[0] + dx, 1.285 + 0.1302, sz + 0.16]);+ b.rotation.y = 0.3 + 2.1 * (i + 1);+ }+ // Boxes, bowls and vases (things a shop puts between the stock).+ const boxes: [number, number, number, Vec3][] = [[0.6, 0.855, 0, [0.8, 0.74, 0.62]], [0.6, 0.975, 0.1, [0.3, 0.37, 0.29]], [1.0, 0.855, -0.08, [0.52, 0.22, 0.13]], [2.45, 1.285, 0.06, [0.8, 0.74, 0.62]], [2.45, 1.405, -0.05, [0.12, 0.13, 0.15]], [0.65, 1.715, 0.05, [0.3, 0.37, 0.29]], [2.35, 2.145, 0, [0.8, 0.74, 0.62]]];+ for (const [x, y, turn, c] of boxes) box("shelf", [0.33, 0.12, 0.22], [x, y + 0.06, sz + 0.17], card(c)).rotation.y = turn;+ const vase = (x: number, y: number, profile: [number, number][], c: Vec3) => add(new Mesh(new LatheGeometry(profile.map(([px, py]) => ({ x: px, y: py })), 48), ceramic(c)), "shelf", [x, y, sz + 0.16]).material.side = "double";+ vase(2.15, 0.855, [[0, 0], [0.07, 0], [0.11, 0.06], [0.1, 0.16], [0.045, 0.24], [0.04, 0.3], [0.055, 0.32]], [0.82, 0.8, 0.76]);+ vase(0.8, 1.285, [[0, 0], [0.05, 0], [0.085, 0.05], [0.08, 0.11], [0.035, 0.17], [0.03, 0.2], [0.04, 0.21]], [0.52, 0.22, 0.13]);+ vase(1.4, 1.715, [[0, 0], [0.06, 0], [0.13, 0.05], [0.14, 0.08], [0.138, 0.085]], [0.82, 0.8, 0.76]);+ vase(2.05, 1.715, [[0, 0], [0.045, 0], [0.06, 0.1], [0.05, 0.22], [0.025, 0.27], [0.03, 0.3]], [0.12, 0.13, 0.15]);+ add(new Mesh(new SphereGeometry(0.06, 32, 24), brass), "shelf", [2.1, 1.285 + 0.06, sz + 0.17]);+ add(new Mesh(new SphereGeometry(0.045, 32, 24), brass), "shelf", [1.5, 0.855 + 0.045, sz + 0.2]);++ const camera = new PerspectiveCamera(FOV.overview, 16 / 9, 0.05, 200);+ camera.id = "camera";+ camera.position.set(...OVERVIEW.eye);+ camera.lookAt(...OVERVIEW.target);+ camera.setManualExposure(SUN.evDay);+ scene.add(camera);+ return { scene, camera, options: { name: "showroom", preset: "preview" as const, width: 1280, height: 720, overrides: { native: { maxBounces: 8 } } } };+ },++ frame,++ handlers: {+ click(tx, ev: { target?: string; point?: Vec3 }) {+ // The product clicked; else the one the click's ray passes close to (small things on big stands need a finger's+ // margin); else the product whose plinth, arch or shelf it was. That product again, or nothing: step back.+ const id = (ev.target ?? "").split("#")[0], s = tx.state;+ let hit = PRODUCTS.findIndex((p) => id.startsWith(`${p.key}_`));+ if (hit < 0 && ev.point) hit = nearRay(s.focus < 0 ? OVERVIEW.eye : closeView(PRODUCTS[s.focus]).eye, ev.point);+ if (hit < 0) hit = PRODUCTS.findIndex((p) => id === `plinth_${p.key}`);+ if (hit < 0 && id === "arch") hit = INDEX.chair;+ if (hit < 0 && id === "shelf") hit = INDEX.bottle;+ tx.decide(hit >= 0 || s.focus >= 0, "click a product to walk over to it");+ s.focus = hit === s.focus ? -1 : hit;+ },+ next(tx) {+ tx.state.focus = (tx.state.focus + 1) % PRODUCTS.length;+ },+ prev(tx) {+ tx.state.focus = tx.state.focus <= 0 ? PRODUCTS.length - 1 : tx.state.focus - 1;+ },+ overview(tx) {+ tx.state.focus = -1;+ },+ mood(tx) {+ tx.state.evening = !tx.state.evening;+ },+ colour(tx) {+ // The product in view if it comes in colours; from the door, the sneaker.+ const p = PRODUCTS[tx.state.focus < 0 ? INDEX.shoe : tx.state.focus];+ tx.decide(p.variants !== null, `the ${p.key} comes in one colour`);+ tx.state.colour[p.key] = ((tx.state.colour[p.key] ?? 0) + 1) % p.variants!.length;+ },+ },++ keys: { N: "next", Right: "next", P: "prev", Left: "prev", O: "overview", Space: "overview", M: "mood", C: "colour" },+});diff --git a/showcase/showroom/thumb.jpg b/showcase/showroom/thumb.jpgnew file mode 100644index 0000000..91feb68Binary files /dev/null and b/showcase/showroom/thumb.jpg differdiff --git a/showcase/tsconfig.json b/showcase/tsconfig.jsonnew file mode 100644index 0000000..2c53b63--- /dev/null+++ b/showcase/tsconfig.json@@ -0,0 +1 @@+{ "extends": "../tsconfig.base.json", "compilerOptions": { "types": ["node"] }, "include": ["."] }diff --git a/site/README.md b/site/README.mdindex 6b237d4..d15a980 100644--- a/site/README.md+++ b/site/README.md@@ -43,7 +43,7 @@ the same footer links. The markup is repeated in each page; change it in all fou| Page | What is on it ||---|---|| `index.html` | The landing page (below). Its two buttons, in the hero and at the end: **Download** (to `download/`, named for the visitor's platform by `js/site.js`) and **GitHub**. |-| `showcase/` | Bistro night and Zero-Day as camera moves (the committed media), then **Open on your device**: a card for each example package in `play/` with an "Open in ThreeRT" link, the same game as three.js, and a QR code for the iPhone app. |+| `showcase/` | Bistro night and Zero-Day as camera moves (the committed media); **Not only games**: the cases (education, commerce, architecture, culture: the packages in `play/` with an `industry`, written in `showcase/` at the repo root), each with what it shows, how to play with it, its links and QR code, and a filter by field; then **Open on your device**: a card for each of the other example packages. The cases' credits go in the footer. || `download/` | ThreeRT for macOS (the build `releases/latest.json` names) and ThreeRT for iPhone (a TestFlight or App Store link once `ios.url` is set), then how a client loads a game: `threert dev`, scan, traced and live. || `docs/` | Getting started: install the client, open an example, write a scene, the dev loop with the `threert` CLI, the package format, links to the reference documents in `docs/` on GitHub. |@@ -62,7 +62,9 @@ the same footer links. The markup is repeated in each page; change it in all fou6. **What a ray finds:** four close-ups.7. **Traced where it can be, three.js everywhere else:** the native client on ray-tracing hardware and the same sceneas three.js in any browser or WebView, drawn as live three.js device models at real proportions.-8. **Just light.**+8. **Not only games:** the cases the Showcase hosts, as a strip of pictures (from `play/index.json`; nothing on a+ host without them).+9. **Just light.**## The two generated directoriesdiff --git a/site/index.html b/site/index.htmlindex 66c4e49..49e6bb9 100644--- a/site/index.html+++ b/site/index.html@@ -85,6 +85,18 @@.tricks svg.mark { width: 150px; height: 150px; margin: 0 auto 40px; display: block; overflow: visible; }@media (prefers-reduced-motion: reduce) { .tricks svg.mark .pulse { display: none; } }+ /* ---- Beyond games: the cases the Showcase hosts, by field ---- */+ .beyond { display: grid; grid-template-columns: repeat(auto-fill, minmax(270px, 1fr)); gap: 16px; }+ .beyond a { position: relative; display: block; border-radius: var(--r-2); overflow: hidden; border: 1px solid var(--line); background: #000; aspect-ratio: 4 / 3; text-decoration: none; isolation: isolate; }+ .beyond a img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; transition: transform 0.6s var(--ease); }+ .beyond a:hover img { transform: scale(1.04); }+ .beyond a::after { content: ""; position: absolute; inset: 0; background: linear-gradient(0deg, rgba(6, 7, 9, 0.94) 0%, rgba(6, 7, 9, 0.7) 30%, rgba(6, 7, 9, 0) 68%); z-index: 1; }+ .beyond .t { position: absolute; z-index: 2; left: 16px; right: 16px; bottom: 14px; }+ .beyond .t small { display: block; font: 500 11.5px/1 var(--font-mono); color: var(--tungsten); margin-bottom: 7px; }+ .beyond .t b { display: block; font: 600 19px/1.15 var(--font-sans); letter-spacing: -0.025em; color: var(--bone); }+ .beyond .t span { display: block; margin-top: 4px; font-size: 13.5px; color: var(--bone-2); }+ #beyond[hidden] { display: none; }+/* ---- Everywhere: one scene, a rail to two renderers, every screen ---- */.root { display: inline-flex; align-items: center; gap: 10px; padding: 12px 18px; border-radius: 12px; border: 1px solid var(--line-2); background: var(--ink-2); font: 500 13px var(--font-mono); color: var(--bone); position: relative; z-index: 1; }.root img { width: 18px; height: 18px; }@@ -281,6 +293,17 @@</div></section>+<section id="beyond" style="padding-top:40px" hidden>+ <div class="wrap">+ <div class="sec-head">+ <h2 class="h-1">Not only games.<br><span class="mute">Light for everyone.</span></h2>+ <p class="lede">Lighting of this quality used to take a studio and a render farm. The same engine now runs a physics lesson, a jeweller’s counter, a flat you might buy and a museum hall, live, on the laptop or phone you already own.</p>+ </div>+ <div class="beyond" id="beyondGrid"></div>+ <p style="margin-top:28px"><a class="btn ghost" href="showcase/#cases">Open the cases</a></p>+ </div>+</section>+<section class="tricks"><svg class="mark rv" viewBox="0 0 64 64" aria-hidden="true" data-mark><defs><linearGradient id="ry" x1="11.59" y1="32" x2="32" y2="12.36" gradientUnits="userSpaceOnUse"><stop offset="0" style="stop-color:var(--ember)"/><stop offset=".5" style="stop-color:var(--tungsten)"/><stop offset="1" style="stop-color:var(--filament)"/></linearGradient><filter id="gl" x="-25%" y="-25%" width="150%" height="150%"><feGaussianBlur stdDeviation="1.4"/></filter></defs>@@ -314,11 +337,19 @@<script type="module">import { $, $$, compare, sequence, seg, reveal, highlight } from "./js/threert.js";- import { downloadButtons } from "./js/site.js";+ import { downloadButtons, packages, packageLinks } from "./js/site.js";// Sections fade in first, so a part that fails below (a missing three.js, a failed fetch) never blanks the page.reveal();const guard = (name, f) => { try { const r = f(); if (r?.catch) r.catch((e) => console.error(`${name}:`, e)); } catch (e) { console.error(`${name}:`, e); } };+ // The cases the Showcase hosts (play/index.json, the games with an `industry`): a host without them shows nothing here.+ guard("cases", async () => {+ const cases = ((await packages())?.games ?? []).filter((g) => g.industry && g.thumb);+ if (!cases.length) return;+ const esc = (s) => String(s).replace(/&/g, "&").replace(/</g, "<").replace(/"/g, """);+ $("#beyondGrid").innerHTML = cases.map((g) => `<a href="showcase/#case-${esc(g.id)}"><img src="${esc(packageLinks(g.id).thumb(g.thumb))}" alt="${esc(g.title)}, rendered by ThreeRT" loading="lazy"><span class="t"><small>${esc(g.industry)}</small><b>${esc(g.title)}</b><span>${esc(g.caption ?? "")}</span></span></a>`).join("");+ $("#beyond").hidden = false;+ });// The download buttons name the visitor's platform (they link to the download page either way).guard("download", () => downloadButtons());diff --git a/site/showcase/index.html b/site/showcase/index.htmlindex 5249d71..e6b5698 100644--- a/site/showcase/index.html+++ b/site/showcase/index.html@@ -31,6 +31,27 @@.pk .qr { width: 92px; height: 92px; padding: 6px; border-radius: 10px; }.pk .acts { grid-column: 1 / -1; display: flex; flex-wrap: wrap; gap: 10px; align-items: center; }.pk .addr { grid-column: 1 / -1; font: 400 11.5px/1.5 var(--font-mono); color: var(--mute); overflow-wrap: anywhere; }+ /* ---- Cases: what the engine does outside games, by industry ---- */+ .filters { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 26px; }+ .filters button { appearance: none; font: 500 13.5px/1 var(--font-sans); color: var(--bone-2); background: transparent; border: 1px solid var(--line-2); border-radius: 999px; padding: 9px 14px; cursor: pointer; transition: color 0.2s, border-color 0.2s, background 0.2s; }+ .filters button:hover { color: var(--bone); border-color: var(--bone-2); }+ .filters button[aria-pressed="true"] { color: var(--ink-0); background: var(--bone); border-color: var(--bone); }+ .cases { display: grid; grid-template-columns: 1fr 1fr; gap: 22px; }+ .case { padding: 0; overflow: hidden; display: grid; grid-template-rows: auto 1fr; scroll-margin-top: 88px; }+ .case[hidden] { display: none; }+ .case .thumb { position: relative; display: block; aspect-ratio: 16 / 9; background: #000; }+ .case .thumb img { width: 100%; height: 100%; object-fit: cover; }+ .case .ind { position: absolute; top: 14px; left: 14px; display: inline-flex; align-items: center; gap: 7px; padding: 6px 10px; border-radius: 8px; background: rgba(8, 9, 11, 0.66); backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px); font: 500 12px/1 var(--font-mono); color: var(--bone); }+ .case .ind i { width: 7px; height: 7px; border-radius: 50%; background: var(--tungsten); box-shadow: 0 0 8px var(--tungsten); }+ .case .body { padding: 24px 26px 26px; display: grid; grid-template-columns: 1fr auto; gap: 18px 22px; align-content: start; }+ .case h3 { font: 600 27px/1.1 var(--font-sans); letter-spacing: -0.03em; }+ .case .blurb { margin-top: 10px; color: var(--bone-2); font-size: 15px; line-height: 1.6; max-width: 54ch; }+ .case .ctl { grid-column: 1 / -1; list-style: none; margin: 0; padding: 16px 0 0; border-top: 1px solid var(--line); display: grid; grid-template-columns: 1fr 1fr; gap: 8px 22px; font-size: 13.5px; line-height: 1.5; color: var(--mute); }+ .case .ctl b { color: var(--bone-2); font-weight: 500; }+ .case .qr { width: 104px; height: 104px; padding: 7px; border-radius: 11px; }+ .case .acts { grid-column: 1 / -1; display: flex; flex-wrap: wrap; gap: 10px; align-items: center; }+ @media (max-width: 1100px) { .cases { grid-template-columns: 1fr; } }+ @media (max-width: 700px) { .case .qr { display: none; } .case .body { grid-template-columns: 1fr; padding: 20px; } .case .ctl { grid-template-columns: 1fr; } .case h3 { font-size: 23px; } }.open-note { margin-top: 28px; display: flex; flex-wrap: wrap; gap: 10px 28px; }.open-note[hidden] { display: none; }@media (max-width: 1100px) { .feat, .feat.flip { grid-template-columns: 1fr; gap: 22px; } .feat.flip .txt { order: 0; } .pk { grid-template-columns: 1fr 1fr; } }@@ -51,7 +72,7 @@<div class="wrap"><span class="eyebrow">Showcase</span><h1 class="h-1">Production scenes.<br><span class="mute">Every light traced.</span></h1>- <p class="lede">Two scenes the industry uses to test renderers, with the camera moving and all of their lighting path-traced. Then small ones you can open yourself.</p>+ <p class="lede">Two scenes the industry uses to test renderers, with the camera moving and all of their lighting path-traced. Then <a href="#cases">what the same engine does outside games</a>, and small scenes you can open yourself.</p></div></header>@@ -80,11 +101,22 @@</div></section>+<section class="sec" id="cases" hidden>+ <div class="wrap">+ <div class="sec-top rv">+ <h2 class="h-2">Not only games.</h2>+ <p class="lede">Lighting of this quality used to take a studio, a render farm and a night of waiting. The same engine now runs a physics lesson, a jeweller’s counter, a flat you might buy and a museum hall, live, on the laptop or phone you already own. Each case below is one file of scene code: open it and try it.</p>+ </div>+ <div class="filters" id="filters" role="group" aria-label="Cases by field"></div>+ <div class="cases" id="caseGrid"></div>+ </div>+</section>+<section class="sec" id="open"><div class="wrap"><div class="sec-top rv"><h2 class="h-2">Open on your device.</h2>- <p class="lede">Each of these is a package on this site: scene code at tutorial size and the files it reads. ThreeRT fetches it and traces it on your GPU. The same package opens as three.js in this browser.</p>+ <p class="lede">The hello-world scenes and a small game. Like the cases above, each is a package on this site: scene code at tutorial size and the files it reads. ThreeRT fetches it and traces it on your GPU. The same package opens as three.js in this browser.</p></div><div class="pk" id="pk"><p class="fine">Looking for the packages on this host…</p></div><div class="open-note fine" id="openNote" hidden>@@ -104,6 +136,7 @@<div class="note"><p><sup>1</sup> 60 fps measured on an Apple M5 MacBook at 1280 × 720 output with dynamic resolution, along each scene’s own camera path; three.js r187 in Chrome on the same machine.</p><p>Amazon Lumberyard Bistro: Amazon Lumberyard (2017). Zero-Day: Mike Winkelmann (Beeple) and Kate Anderson (2019). Both from NVIDIA’s Open Research Content Archive (ORCA), CC BY 4.0, converted from FBX to glTF. Damaged Helmet: Khronos glTF sample models. three.js is an independent open-source project; ThreeRT is not affiliated with it.</p>+ <p id="caseCredits" hidden></p></div></div></footer>@@ -125,7 +158,41 @@pk.outerHTML = `<p class="fine">No example packages are published on this host yet. The examples also ship inside the client: <a href="../download/">download ThreeRT</a> and open its library.</p>`;return;}- pk.innerHTML = games.map((g) => {+ // Cases (a game with an `industry`: the client's release writes it from the engine's showcase/) get their own+ // section, with what each shows and how to play with it; the rest are the hello-world packages below.+ const cases = games.filter((g) => g.industry), rest = games.filter((g) => !g.industry);+ if (cases.length) {+ const fields = [...new Set(cases.map((g) => g.industry))];+ $("#caseGrid").innerHTML = cases.map((g) => {+ const l = packageLinks(g.id);+ return `<article class="card case" id="case-${esc(g.id)}" data-field="${esc(g.industry)}">+ <a class="thumb" href="${esc(l.web)}" aria-label="${esc(g.title)} as three.js in this browser"><img src="${esc(l.thumb(g.thumb))}" alt="${esc(g.title)}, rendered by ThreeRT" loading="lazy"><span class="ind"><i></i>${esc(g.industry)}</span></a>+ <div class="body">+ <div><h3>${esc(g.title)}</h3><p class="blurb">${esc(g.blurb ?? g.caption ?? "")}</p></div>+ <div class="qr" data-id="${esc(g.id)}"></div>+ <div class="acts"><a class="btn primary sm" href="${esc(l.open)}">Open in ThreeRT</a><a class="btn ghost sm" href="${esc(l.web)}">three.js in the browser</a></div>+ ${g.controls?.length ? `<ul class="ctl">${g.controls.map((c) => `<li><b>${esc(c.input)}</b> ${esc(c.does)}</li>`).join("")}</ul>` : ""}+ </div>+ </article>`;+ }).join("");+ $("#filters").innerHTML = [`<button type="button" aria-pressed="true" data-field="">All</button>`, ...fields.map((f) => `<button type="button" aria-pressed="false" data-field="${esc(f)}">${esc(f)}</button>`)].join("");+ $("#filters").addEventListener("click", (e) => {+ const b = e.target.closest("button");+ if (!b) return;+ for (const x of $$("#filters button")) x.setAttribute("aria-pressed", String(x === b));+ for (const c of $$("#caseGrid .case")) c.hidden = !!b.dataset.field && c.dataset.field !== b.dataset.field;+ });+ $("#cases").hidden = false;+ // What the cases use that is not ours: named here, as their licences ask.+ const seen = new Set(), credits = cases.flatMap((g) => g.credits ?? []).filter((c) => !seen.has(c.what + c.by) && seen.add(c.what + c.by));+ if (credits.length) {+ $("#caseCredits").innerHTML = "In the cases: " + credits.map((c) => `${c.url ? `<a href="${esc(c.url)}" rel="noopener">${esc(c.what)}</a>` : esc(c.what)}, ${esc(c.by)} (${esc(c.licence)})`).join("; ") + ".";+ $("#caseCredits").hidden = false;+ }+ // Arriving at a case's own address (#case-<id>), now that it exists.+ if (location.hash.startsWith("#case")) document.getElementById(location.hash.slice(1))?.scrollIntoView();+ }+ pk.innerHTML = rest.map((g) => {const l = packageLinks(g.id);return `<article class="card"><a class="thumb" href="${esc(l.web)}" aria-label="${esc(g.title)} as three.js in this browser">${g.thumb ? `<img src="${esc(l.thumb(g.thumb))}" alt="${esc(g.title)}, rendered by ThreeRT" loading="lazy">` : ""}<span class="kind">${g.kind === "game" ? "game" : "scene"}</span></a>@@ -139,7 +206,7 @@}).join("");$("#openNote").hidden = false;if (!reachable()) $("#openNote").insertAdjacentHTML("beforeend", `<span>This page is on ${esc(location.hostname)}, which a phone cannot reach. Serve with <code>bun site/serve.ts --lan</code> and open the LAN address.</span>`);- for (const el of $$("#pk .qr")) {+ for (const el of $$("#pk .qr, #caseGrid .qr")) {const g = games.find((x) => x.id === el.dataset.id), l = packageLinks(g.id);try { el.innerHTML = await qrSvg(l.qr, `QR code: open ${g.title} on a phone`); } catch (e) { console.error("qr:", e); el.remove(); }}diff --git a/tools/showcase.ts b/tools/showcase.tsnew file mode 100644index 0000000..6b26c65--- /dev/null+++ b/tools/showcase.ts@@ -0,0 +1,87 @@+// The loop for writing a showcase case (showcase/<id>/<id>.game.ts): bundle it, render it offline, run it live with+// scripted input, and say what it costs.+//+// node tools/showcase.ts <id> [--spp 256] [--no-render] [--camera '{"position":[x,y,z],"target":[x,y,z],"fov":40}']+// [--time s] [--width 1280] [--height 720] [--script '<steps>'] [--scale auto|0.5..1]+//+// -> out/showcase/<id>/render.png the offline render (what the live view converges to), unless --no-render+// out/showcase/<id>/<name>.png a live frame for every {"shot": name} step (default script: 3 s, then "live")+// stdout the bundle size, the offline render's time, the live GPU ms a frame and render+// scale (60 fps holds when p95 is under 16.7 ms and the scale stays above 0.5),+// and every line the renderer or the game logged about a failure+//+// A script is a JSON array of steps, run in order on the live renderer (720p, dynamic resolution, as a client runs it):+// {"wait": 1.5} let it run (seconds)+// {"event": "name", "payload": {...}} call a handler (what a key or a button does)+// {"click": [u, v]} click the view at u, v in 0..1 (the game's `click` handler gets the target)+// {"camera": {"pos": [..], "target": [..]}} look from elsewhere+// {"time": 12} set the scene time (f.time)+// {"shot": "name"} save the frame now on screen as out/showcase/<id>/<name>.png+import { execFileSync } from "node:child_process";+import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";+import { join } from "node:path";+import { bundleGame, repoRoot as root } from "./bundle-game.ts";+import { frameStats, rendererBin } from "./lib/bench.ts";+import { startLive } from "./lib/live.ts";+import { installAssets } from "../showcase/assets.ts";++const args = process.argv.slice(2);+const id = args[0];+if (!id || id.startsWith("-")) throw new Error("usage: node tools/showcase.ts <id> [...]");+const opt = (k: string, d?: string) => (args.includes(k) ? args[args.indexOf(k) + 1] : d);+const src = join(root, "showcase", id, `${id}.game.ts`);+if (!existsSync(src)) throw new Error(`${src} is missing`);+const out = join(root, "out/showcase", id);+mkdirSync(out, { recursive: true });+const width = opt("--width", "1280")!, height = opt("--height", "720")!;++installAssets(); // the cases' own files, into the asset store the scene reads from+const bundle = join(root, "out/bundles", `showcase-${id}.js`);+const b = await bundleGame(src, bundle);+console.log(`bundle ${(b.bytes / 1024).toFixed(0)} KiB`);++if (!args.includes("--no-render")) {+ const png = join(out, "render.png");+ const a = ["render", bundle, "-o", png, "--assets", root, "--spp", opt("--spp", "256")!, "--width", width, "--height", height];+ if (opt("--camera")) a.push("--camera", opt("--camera")!);+ if (opt("--time")) a.push("--time", opt("--time")!);+ const t0 = performance.now();+ try {+ execFileSync(rendererBin, a, { stdio: ["ignore", "pipe", "pipe"], encoding: "utf8" });+ console.log(`render ${png} (${opt("--spp", "256")} spp, ${((performance.now() - t0) / 1000).toFixed(1)} s)`);+ } catch (e) {+ console.log(`render FAILED: ${String((e as { stderr?: string }).stderr ?? e).trim().split("\n").slice(-6).join(" | ")}`);+ }+}++type Step = { wait?: number; event?: string; payload?: unknown; click?: [number, number]; camera?: { pos: number[]; target: number[] }; time?: number; shot?: string };+const script: Step[] = JSON.parse(opt("--script", '[{"wait":3},{"shot":"live"}]')!);+const frameLog = join(out, "frames.jsonl");+const live = startLive({ bin: rendererBin, assets: root, presets: join(root, "presets"), bundles: join(root, "out/bundles"), label: `showcase ${id}` }, bundle, { scale: opt("--scale", "auto"), frameLog, width: Number(width), height: Number(height) });+try {+ const first = await live.firstFrame;+ console.log(`live: first frame after ${(first / 1000).toFixed(1)} s`);+ for (const s of script) {+ if (s.wait !== undefined) await new Promise((r) => setTimeout(r, s.wait! * 1000));+ else if (s.event) live.send({ cmd: "event", type: s.event, payload: s.payload ?? {} });+ else if (s.click) live.send({ cmd: "click", u: s.click[0], v: s.click[1] });+ else if (s.camera) live.send({ cmd: "camera", ...s.camera });+ else if (s.time !== undefined) live.send({ cmd: "time", t: s.time });+ else if (s.shot) {+ const f = join(out, `${s.shot}.png`);+ live.send({ cmd: "snapshot", path: f });+ const line = await live.wait((l) => l.includes(`snapshot ${f}`), 60_000);+ console.log(`shot ${f} (${statSync(f).size >> 10} KiB)${/at history.*$/.exec(line)?.[0] ? ": " + /at history.*$/.exec(line)![0] : ""}`);+ }+ }+} finally {+ await live.quit().catch(() => {});+}+type F = { gpu: number; scale?: number };+const logged = readFileSync(frameLog, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l) as F).slice(30);+if (logged.length) {+ const g = frameStats(logged.map((f) => f.gpu)), sc = logged.map((f) => f.scale ?? 1).sort((x, y) => x - y);+ console.log(`live GPU ms: p50 ${g.p50.toFixed(1)}, p95 ${g.p95.toFixed(1)} over ${logged.length} frames; render scale p50 ${sc[sc.length >> 1].toFixed(2)}, min ${sc[0].toFixed(2)} (other work on the GPU makes these worse)`);+}+const bad = live.lines.filter((l) => /fail|error|panic|unsupported|not found|missing|exception/i.test(l));+for (const l of [...new Set(bad)].slice(0, 20)) console.log(`! ${l.slice(0, 300)}`);diff --git a/tools/three/engine.ts b/tools/three/engine.tsindex 1040d2c..8ce0a83 100644--- a/tools/three/engine.ts+++ b/tools/three/engine.ts@@ -623,6 +623,9 @@ export class ThreeEngine implements Engine {switch (l.type) {case "directional": {const dl = new THREE.DirectionalLight();+ // three.js starts these lights one unit up (Object3D.DEFAULT_UP); the pose is the node's, so the light sits at+ // its origin. (For a spot light the offset moved the cone a metre off its lamp.)+ dl.position.set(0, 0, 0);dl.target.position.set(0, 0, -1);dl.add(dl.target);dl.shadow.mapSize.set(SHADOW.directional, SHADOW.directional);@@ -639,6 +642,7 @@ export class ThreeEngine implements Engine {}case "spot": {const sl = new THREE.SpotLight();+ sl.position.set(0, 0, 0);sl.decay = 2;sl.target.position.set(0, 0, -1);sl.add(sl.target);