diff --git a/AGENTS.md b/AGENTS.md index 2f974bf64..4807dabdd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,7 +13,7 @@ It is standalone (not Eurorack), powered from a 5 V power bank through a screw t - `hardware/` — Hardware designs. `case/` (Blender source in `source/`, STLs by printer bed size, `knobs/`, `legacy_v2/` for the v2.x board, `legacy_lasercut/` for the v1/v2 acrylic drawings, and `remixes/` — community enclosures, one folder each, whose README is its license header), `pcb/` (KiCad 10.0 source, Gerbers per revision, schematic PDF), `bom/` (`bom_v3.9.csv` — **the BOM source of truth**; the guide's table is derived from it. `bom_v3.0.csv` is kept for the previous board). - `web/` — Next.js site at patternflow.work: landing page (`/`, `/pattern`, `/build`, `/inside` are tabs of one view), the interactive guide (`/guide` is a hub over `/guide/build`, `/guide/play`, `/guide/make` and `/guide/audio`, each with a `/ko` twin; one 3D stage in `components/guide/`, the firmware simulator in `lib/guide/`), Pattern Lab (`/pattern-lab`), community (`/community/**`, SQLite + Drizzle + Better Auth, only on the Pi deployment), browser flasher (no page of its own: the **Flash Patternflow** button on `/pattern` and in the Play guide, installing `public/flash/manifest.json` and the images in `public/flash/bin/`; the bare `/flash` redirects to `/guide/play#flash`), the edition shelf (`/editions`; `/variants` redirects there), the feature catalogue (`/features`, reels per feature), device update handoff (`/update`), journal, roadmap. `lib/pattern/` is the pattern runtime and annotations, `lib/lab/` the Pattern Lab, `lib/community/` the community, `lib/ai/` the prompt Pattern Lab's Copy prompt puts on the clipboard (the site calls no AI service). Architecture doc: `web/ARCHITECTURE.md`. The JS presets in `web/src/lib/presets/` are the source of truth for firmware preset headers. - `shared/` — `constants.json`, the values the firmware and the site both carry: the panel geometries `PANEL_GEOMETRY` picks from, the knob count, the encoder's 24 detents a turn, the bus maximum and the button timings. Two files are generated from it, `firmware/patternflow/src/core_shared.h` (each key with `PF_SHARED_` in front) and `web/src/lib/shared/constants.ts`, and neither is edited by hand. It exists because the lab counted 20 detents a turn, against the encoder's 24, until 31 July 2026. -- `tools/` — desktop-side helpers: `patternflow-audio-extension` (the browser audio-react extension — also the authoring source the device's `/audio-in` console page is assembled from), `patternflow-audio-android` (phone capture app), `rtpmidi-probe`, `case-models` (builds the /build preview's per-case 3D models, `web/public/cases//model.glb`, from the case files in the repo; run by hand, not by the site build), and `virtual-panel`. `virtual-panel` is the one that is not a client: a Patternflow with no board, the guide's `DeviceSim` (`web/src/lib/guide/deviceSim.ts`) behind the ports the firmware listens on, with the five contracts in `transports/`. It runs each pattern's JS twin, never a `.pfm` module. The vector suites replay against it, so a change to `DeviceSim` is a change to the panel they test. It is a test fixture, and Wi-Fi and firmware updates are not part of it. +- `tools/` — desktop-side helpers: `patternflow-audio-extension` (the browser audio-react extension — also the authoring source the device's `/audio-in` console page is assembled from), `patternflow-audio-android` (phone capture app), `rtpmidi-probe`, `case-models` (builds the /build preview's per-case 3D models from the case files in the repo, `web/public/cases//model.glb` and the light `light.glb` beside it that the Build tab's shelf is made of; run by hand, not by the site build), and `virtual-panel`. `virtual-panel` is the one that is not a client: a Patternflow with no board, the guide's `DeviceSim` (`web/src/lib/guide/deviceSim.ts`) behind the ports the firmware listens on, with the five contracts in `transports/`. It runs each pattern's JS twin, never a `.pfm` module. The vector suites replay against it, so a change to `DeviceSim` is a change to the panel they test. It is a test fixture, and Wi-Fi and firmware updates are not part of it. - `integrations/` — host-software integrations, each with its own README. `integrations/ableton/` is the Max for Live bridge (knobs → Live parameters over OSC). The Home Assistant integration left this repository on 2026-09-03; its author maintains it separately. Integrations are built against the contracts in `docs/` (`rest-api.md`, `osc-spec.md`, `midi-spec.md`), not against the firmware source. `docs/rest-api.md` also has the table for choosing between HTTP, OSC and MQTT, and the rules that make the device's single-connection web server easy to knock over. ## Hard rules (do not violate) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b50afcd0..1e62ada33 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,21 @@ All notable changes to Patternflow will be documented in this file, newest first ### Web - **Pattern Lab previews the time from the browser's clock.** The guide and the virtual panel give a pattern `timeValid` false, as a board without the clock does ([#540](https://github.com/engmung/Patternflow/pull/540) by [@didusee](https://github.com/didusee)). +- **The home page's nav is a row of its own on a phone.** Below 901px Guide, Journal, Community, Shop and Instagram were 11px words in the corner over the wordmark, 18px tall to a finger. They are the hero's first row now, 12px words in entries 44px tall, from the column's left edge to its right. Get One is where it was on a 375×667 screen, and pages from 901px up are unchanged. +- **Build, Pattern and Inside start 24px from a phone's edge, not 46px.** The panel's own 22px came on top of the page's 24px, so a 390px phone had a 298px column. It has 342px now, on the hero's and the journal's gutter. On a 375px phone the Inside list's count goes under its heading, where each used to break in two beside the other. +- **The shop is one word in the nav.** It was a box in the nav and a poster with a New tab under the hero's buttons, and it sold next to nothing. The poster is gone from the home page and Shop is drawn as Guide, Journal and Community are. The Inside panel's last row still links it. +- **The phone's section bar marks its open tab with ✕.** A second tap on the open tab goes back to the home page, where the phone's links to Guide, Journal and Community are, and nothing on the bar said so. The bar's words are ink now, not the grey of a caption. +- **The hero's two-line texts share their words on a phone.** Each left a word or two alone on its second line, "them." under 44 characters. They balance their lines below 901px, and the kicker breaks between its two sentences. +- **Small links take a finger on a phone.** Terms & Privacy in the footer was 17px tall and looked like the text around it without a pointer over it. Below 901px it is underlined and 46px tall, and the three links at the foot of the Inside panel are 44px tall, up from 20px. +- **The Build tab's 3D view opens on a shelf of all five cases.** It opened on the official case alone, with arrows to the others. The cases now stand on two boards at one scale, each with its name under it, and its panel lit. Picking one, by the case, by its name or with the keyboard, takes it from the shelf to where the device stands, and All cases brings the shelf back. A case named by the panel's switch, the arrows or a `/build?case=` address is shown by itself as before. +- **The shelf's boards float, and it turns under a drag.** The two side posts are gone, a drag turns and tilts the shelf a little, and only the official case's panel runs until a pointer is on another. mbchars, lying the long way, faces straight out. +- **Each case has a light model that shows before its full one.** `light.glb` is the device standing assembled, 14 to 55 KB where the full model is 317 to 563 KB and needs the Draco decoder. The light one stands where the device stands until the full one has arrived, which is then drawn in the same place at the same size and turn while the light one fades out over it. The Build tab fetches 154 KB for its 3D view where it fetched 568 KB. +- **The home page no longer fetches the device.** The official case's model and the Draco decoder, 568 KB, loaded with every tab of the home view, the hero's globe included. A full model is now fetched when its case is first shown by itself. +- **The globe turns at one speed on every screen.** A picked place came round by 8% of what was left each frame: 0.46 s to 90% at 60 Hz, 0.23 s on a 120 Hz phone, 0.92 s at 30 Hz. It is 0.46 s at any rate, and so is the camera closing in. +- **Dragging the globe follows the finger, and a flick keeps it turning.** The drag added up each event's `movementX`, which a touch does not always carry, and turned 0.006 radians a pixel whatever the globe's size. It now follows the pointer that began it, one radian for one radius of drag, and lets go with the speed the hand left it, which runs down into the idle drift. +- **The globe's links grow out of their pins.** They draw on over 1.4 s when the map is first seen and when a filter changes them. The dots on them are at least 2.2px across on a phone, where they were 1px. +- **The globe stops drawing when it is off screen.** A phone that had opened Inside and gone back to the home page kept drawing the hidden globe: 14,400 draw calls in 3 s. It is none now. +- **The home view's own moves hold still for reduced motion.** The page rising as it loads, a tab's panel rising, and on a phone the 3D view dropping in and the section bar riding up under it are in place at once. So is a case picked from the shelf. - **Build map:** the Anbu and Ajman MQTT pins link to engmung/patternflow-exhibition-2026, the exhibition setup and the flowlocal source, now public. - **Journal text on a phone starts 24px from the screen's edge, not 48px.** The cream gutter and the white panel's padding added up, so 15px text got 17.6 characters a line at 360px. The panel now reaches the screen's edges, and the masthead, the text and both footers start on one 24px line. Pages from 721px up are unchanged. - **The journal archive's dates and reading times are 13px on a phone, not 10.5px.** They were the smallest text on /journal below 721px, under the 13px the journal's other dates and labels keep. No row's date wraps or meets its post number at 360px, and pages from 721px up are unchanged. @@ -32,6 +47,10 @@ All notable changes to Patternflow will be documented in this file, newest first - **The journal's stylesheet drops 61 lines that matched nothing.** No component or post used `.journal-list-number` or `.journal-figure` with its `-wide` and `-full`, the cover slots never held the `span` two rules styled, and two rules switched off a `::before` nothing switched on. Every journal page renders as before. - **The site nav links the shop.** Shop sits between Community and Instagram at the top right of the home page, boxed in ink like the hero's outline button, and opens shop.patternflow.work in a new tab. The Inside panel's last row of links carries it too. +### Tools + +- **`tools/case-models/light.mjs` makes each case's light model from its full one.** It leaves out what nobody sees while the case is closed, cuts what stays to a triangle budget with meshoptimizer, keeps the LED panel's lit face and the material names, and writes with meshopt compression. `build.sh` runs it after `assemble.mjs`. + ## [3.12.0] - 2026-10-27 ### Firmware diff --git a/tools/case-models/README.md b/tools/case-models/README.md index a764bfe7d..b5e15ff0e 100644 --- a/tools/case-models/README.md +++ b/tools/case-models/README.md @@ -12,13 +12,17 @@ The 3D models the [/build](https://patternflow.work/build) page's preview shows, Run `./build.sh` to make all five again (or `./build.sh ` for one). The models are committed; nothing here runs when the site builds. Every step is deterministic: the same files in give the same bytes out. -| Model | Size | Loads | -| :--- | ---: | :--- | -| `official/model.glb` | 317 KB | with the page (the guide uses it too) | -| `besoiobiy-printed/model.glb` | 345 KB | when its tab is hovered or picked | -| `simonepda-lasercut/model.glb` | 332 KB | when its tab is hovered or picked | -| `mbchars-horizontal-desktop-printed/model.glb` | 380 KB | when its tab is hovered or picked | -| `jof-patternflood/model.glb` | 563 KB | when its tab is hovered or picked | +Each case has two models. `model.glb` is the full one, every part its own node, which the preview takes apart. `light.glb` is made from it by `light.mjs` (below): the same device standing assembled, small enough that all five load with the tab. + +| Case | `model.glb` | `light.glb` | +| :--- | ---: | ---: | +| `official` | 317 KB | 14 KB | +| `besoiobiy-printed` | 345 KB | 30 KB | +| `simonepda-lasercut` | 332 KB | 33 KB | +| `mbchars-horizontal-desktop-printed` | 380 KB | 22 KB | +| `jof-patternflood` | 563 KB | 55 KB | + +The five light models load with the Build or Pattern tab, 154 KB between them. A full model loads when its case is first shown by itself, or when a pointer is on it on the way. The landing page's model before these, `web/public/3dforweb.glb` (a v3.0 device), was 1,155 KB and loaded with the page. @@ -123,11 +127,33 @@ Then it checks the result: 410.28 × 176.16 × 42 mm against the README's "appro Into the model frame it is a half turn about y, 10 mm to the unit, the outline centred and the front face set where the official case's are. The panel lies the long way across here, a quarter turn from the other three, so `ledTurn` turns it a quarter turn clockwise, which puts the top of the pattern at the top as the author mounts the panel (its arrows point up in the rear photo). The board is centred on the encoder holes and bears on the inside of the control section's 3 mm front, as in the official case; the panel's face is flush with the front, on tabs 17.8 mm behind it. Each part is one node: `outer_frame`, `inner_frame`, `rear_display_cover`, `rear_control_cover` and the four `joint_bar_*` in `pla_white`; `control_section`, `usb_retainer`, `stand_left` and `stand_right` in `pla_orange`, the orange of the author's 3MF. Normals as on Besoiobiy's case (`crease_shaded`, imported from `besoiobiy.py`). +## The light models: `light.mjs` + +`light.glb` is a case as two nodes: `l`, the lit face of the LED panel with its UVs, and `body`, everything else, one primitive per material. The Build tab opens on a shelf of all five. A picked case's light model then stands where the device stands until its full model has arrived, so the page draws a case before it has fetched 317 KB of it or the Draco decoder. + +`node light.mjs` makes all five from their full models (`node light.mjs ` for one), and `build.sh` runs it after `assemble.mjs`. + +- It leaves out what nobody sees while the case is closed, by node name (`CASES` in the script): the board and the DevKit, mbchars' joint bars, Patternflood's braces and wiring, SimonePDA's loose feet. SimonePDA's case is clear, so its board and DevKit stay, cut down to 260 triangles each. +- It cuts each part that stays to a budget with meshoptimizer: 900 triangles for a part of the shell, 96 for a knob. +- It drops the normals and welds vertices by position. The page works the normals out again from the faces (`toCreasedNormals` in `web/src/components/3d/lightCase.ts`), with an edge wherever two faces meet at more than 36°. +- It keeps the LED panel's lit face as it is, the triangles whose UVs are the LED grid, and gives them the one normal the pattern's shader takes for an LED (`ledPanel` in `patterns/common.ts`). +- It writes the full model's box into the scene's `extras`, so a light model is centred exactly where its full model is, dropped parts or not. +- It writes with `EXT_meshopt_compression`, whose decoder is built into three's loader. Nothing else is fetched before a light model draws. + +| Case | Triangles, full | Triangles, light | +| :--- | ---: | ---: | +| `official` | 104,377 | 2,900 | +| `besoiobiy-printed` | 107,154 | 7,946 | +| `simonepda-lasercut` | 103,320 | 3,640 | +| `mbchars-horizontal-desktop-printed` | 125,806 | 5,222 | +| `jof-patternflood` | 110,956 | 10,551 | + ## How the preview uses a model `web/src/components/3d/HeroScene.tsx` with `heroCase.ts` draws whichever model the Build panel's case switch is on. -- **Loading.** Only the official model is preloaded with the page. A remix's model loads when it is picked, or when its tab is hovered (`preloadCaseModel.ts`). The current case stays on screen until the new model has arrived. A model that fails to load is caught, and the official case stays up. +- **Loading.** No full model loads with the page. A case's full model loads when the case is first shown by itself, or when a pointer is on it on the shelf, on its tab or on the arrow that leads to it (`preloadCaseModel.ts`). Until it has arrived the case's light model stands in its place. The full one then takes over in the same place, at the same size and turn, and the light one fades out over it (`CaseShelf.tsx`). A model that fails to load is caught, and the official case stays up. +- **The shelf.** The Build tab's view opens on all five light models standing on two boards, at one scale (`shelfLayout.ts`). A case picked there, by its model or by the name under it, goes from its place on the shelf to where the device stands, and All cases takes it back. - **Its own copy.** The preview works on a deep clone of drei's cached scene, with its own copy of each material, so it never changes the cached scene, which the guide may be given too. It finds the parts by the node names above; every other top-level node is treated as a piece of the case. - **Placement.** The model is measured once when it arrives and centred on the preview's orbit target. Every case is drawn at the same scale: the LED panel is the same part in each (and the knobs, except Besoiobiy's own caps), so it is the same size on screen, and what differs is the case round it (up to 4% across the front's diagonal among the three that stand upright; Besoiobiy's case is 8% wider than the official one). mbchars' case lies the long way and is two thirds wider than the official one: on a view too narrow for it, a desktop's tall one, it is drawn smaller, by as little as keeps it within 72% of the view's width, clear of the arrows (`fitAcross` in `buildPose.ts`). On a phone all four fit at the one scale, and on a desktop the other three do. A script does not need to match the official case's origin, only the frame's axes and units. - **The Build steps** use what `web/src/components/3d/cases/.ts` gives: step 1 shows the case pieces and knobs at 40% of their explode vectors; step 2 shows the board and DevKit, framed on their box; step 3 moves every top-level node by its explode vector times the panel's slider. @@ -137,7 +163,7 @@ Into the model frame it is a half turn about y, 10 mm to the unit, the outline c ## Adding a case -A remix with 3D files (or a drawing exact enough to stand up) gets a model the same way: a script in this folder that writes a shell and a `placement.json` in the frame above, a line in `build.sh`, an entry in `web/src/components/3d/cases/`, and the case's card in `web/src/components/sections/build-cases-data.ts`. +A remix with 3D files (or a drawing exact enough to stand up) gets a model the same way: a script in this folder that writes a shell and a `placement.json` in the frame above, a line in `build.sh`, a line in `light.mjs`'s `CASES` saying which of its nodes the light model leaves out, an entry in `web/src/components/3d/cases/`, and the case's card in `web/src/components/sections/build-cases-data.ts`. ## License diff --git a/tools/case-models/build.sh b/tools/case-models/build.sh index 7ecb50aa3..cc36fe7f6 100755 --- a/tools/case-models/build.sh +++ b/tools/case-models/build.sh @@ -1,5 +1,6 @@ #!/usr/bin/env bash -# Makes every case model again: web/public/cases//model.glb. +# Makes every case model again: web/public/cases//model.glb and, from +# it, the light model beside it, light.glb. # # tools/case-models/build.sh # all five # tools/case-models/build.sh official # one @@ -45,4 +46,6 @@ for id in "${cases[@]}"; do exit 1 ;; esac + # The light model is made from the full one, so it follows it. + node light.mjs "$id" done diff --git a/tools/case-models/light.mjs b/tools/case-models/light.mjs new file mode 100644 index 000000000..5c37121df --- /dev/null +++ b/tools/case-models/light.mjs @@ -0,0 +1,397 @@ +// Makes each case's light model from its full one, for the /build page's shelf. +// +// node light.mjs every case in web/public/cases/ +// node light.mjs ... those cases +// +// The full model (model.glb, assemble.mjs) is every part of a case as its own +// node, with the board and the DevKit inside: about 105,000 triangles, 320 to +// 560 KB, Draco compressed, so the page waits for it and for the decoder. The +// preview takes it apart, part by part. +// +// The light model (light.glb) is the same device standing assembled and +// nothing else. The page shows all five on a shelf the moment the Build tab +// opens, and each stands in for its full model until that has arrived. What +// goes: +// - the parts nobody sees while the case is closed (CASES below): the board +// and the DevKit, a case's inner braces and wiring, the loose feet; +// - most of the triangles of what stays: a part keeps at most BUDGET of +// them (meshoptimizer), and what only shows through clear acrylic is cut +// down further, without regard for its shape's fine detail; +// - the normals: the page works them out again from the faces (lightCase.ts, +// toCreasedNormals), so vertices weld on position alone; +// - the parts as separate things: everything is baked into one node, +// `body`, one primitive per material. +// What stays as it is: the lit face of the LED panel, `l`, with its UVs (the +// pattern is drawn on it), the material names (the page swaps a case's finish +// by name) and the model frame, so a light model stands exactly where its +// full one does. The full model's box is written into the scene's extras for +// that, since the light one's own box no longer has the dropped parts in it. +// +// Written with EXT_meshopt_compression, not Draco: three's loader has that +// decoder built in, so nothing else is fetched before a light model draws. +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { Document } from '@gltf-transform/core'; +import { EXTMeshoptCompression, KHRMeshQuantization } from '@gltf-transform/extensions'; +import { dedup, meshopt, prune, quantize } from '@gltf-transform/functions'; +import { MeshoptDecoder, MeshoptEncoder, MeshoptSimplifier } from 'meshoptimizer'; +import { getIO, worldBounds, fmt } from './lib/io.mjs'; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const CASES_DIR = path.resolve(HERE, '../../web/public/cases'); + +/** The LED panel's node. Its lit face is kept whole; the rest of it is cut down like a part inside. */ +const LED = 'l'; +/** + * The lit face is the part of the panel whose UVs are the LED grid: the unit + * square, to this much. The rest of the panel's UVs are parked outside it. + */ +const LED_UV_SLACK = 0.01; +/** + * The lit face's normal, as the file has it. The pattern's shader takes a + * fragment of the panel for an LED when its normal, as stored, points along + * -y (web/src/components/3d/patterns/common.ts, ledPanel: the full models' + * panel lies that way round in its own node), and for the panel's frame + * otherwise. A light model has no other normals; this one is the mark. + */ +const LED_NORMAL = [0, -1, 0]; + +/** + * The most triangles a top-level node keeps, by what it is. A knob is a + * cylinder two millimetres across on the shelf; a shell part keeps its holes + * and its edges; what is inside only has to be there. + */ +const BUDGET = { knob: 96, shell: 900, inside: 260, panel: 220 }; +/** How far a surface may move, as a share of the part's size (meshoptimizer's error). */ +const ERROR = { knob: 0.05, shell: 0.01, inside: 0.2, panel: 0.02 }; +/** Vertices closer than this are one vertex: a tenth of a millimetre (a unit is 10 mm). */ +const WELD = 1e-3; + +/** + * What each case leaves out, by top-level node (a trailing * matches the rest + * of a name), and what it keeps coarse because it only shows through + * something: `inside`. + */ +const CASES = { + official: { drop: ['pcb_v39', 'devkit'] }, + 'besoiobiy-printed': { drop: ['pcb_v39', 'devkit'] }, + // Clear acrylic: the board and the DevKit show through it, so they stay, + // coarse. The three feet are for laying it flat and are not on it. + 'simonepda-lasercut': { drop: ['foot_*'], inside: ['pcb_v39', 'devkit'] }, + // The joint bars and the USB retainer are behind the rear covers. + 'mbchars-horizontal-desktop-printed': { drop: ['pcb_v39', 'devkit', 'joint_bar_*', 'usb_retainer'] }, + // A closed birch box: the braces, rails, doublers, trays and everything + // wired inside are behind the bezel, the walls and the back cover. + 'jof-patternflood': { + drop: [ + 'brace_*', 'rail_*', 'back_doubler', 'shelf', 'doubler_*', 'knob_rib_*', 'tray_*', 'bezel_inner', + 'colorlight', 'pi5', 'encoders', 'psu', 'power_bus', 'panel_connectors', 'wiring', + ], + }, +}; + +const matches = (name, patterns = []) => + patterns.some((p) => (p.endsWith('*') ? name.startsWith(p.slice(0, -1)) : name === p)); + +/** p' = M p, for a column-major 4x4. */ +function point(m, v) { + return [ + m[0] * v[0] + m[4] * v[1] + m[8] * v[2] + m[12], + m[1] * v[0] + m[5] * v[1] + m[9] * v[2] + m[13], + m[2] * v[0] + m[6] * v[1] + m[10] * v[2] + m[14], + ]; +} + +/** Triangles in the model's frame: positions, with or without UVs. */ +class Soup { + positions = []; + uvs = []; + indices = []; + + get triangles() { + return this.indices.length / 3; + } + + /** Adds another soup's triangles after this one's. */ + append(other) { + const base = this.positions.length / 3; + for (const p of other.positions) this.positions.push(p); + for (const t of other.uvs) this.uvs.push(t); + for (const i of other.indices) this.indices.push(base + i); + } + + /** One vertex where several share a place. Only for soups without UVs. */ + weld() { + const seen = new Map(); + const positions = []; + const remap = new Uint32Array(this.positions.length / 3); + for (let i = 0; i < remap.length; i += 1) { + const [x, y, z] = this.positions.slice(i * 3, i * 3 + 3); + const key = `${Math.round(x / WELD)},${Math.round(y / WELD)},${Math.round(z / WELD)}`; + let at = seen.get(key); + if (at === undefined) { + at = positions.length / 3; + seen.set(key, at); + positions.push(x, y, z); + } + remap[i] = at; + } + const indices = []; + for (let i = 0; i < this.indices.length; i += 3) { + const [a, b, c] = [remap[this.indices[i]], remap[this.indices[i + 1]], remap[this.indices[i + 2]]]; + if (a !== b && b !== c && a !== c) indices.push(a, b, c); + } + this.positions = positions; + this.indices = indices; + } + + /** Down to `target` triangles: by collapsing edges, or `sloppy`, by merging whatever is near. */ + simplify(target, error, sloppy) { + if (this.triangles <= target) return; + const indices = new Uint32Array(this.indices); + const positions = new Float32Array(this.positions); + const [next] = sloppy + ? MeshoptSimplifier.simplifySloppy(indices, positions, 3, null, target * 3, error) + : MeshoptSimplifier.simplify(indices, positions, 3, target * 3, error, ['Prune']); + this.indices = Array.from(next); + this.compact(); + } + + /** Drops the vertices no triangle uses. */ + compact() { + const remap = new Map(); + const positions = []; + const uvs = []; + const hasUv = this.uvs.length > 0; + this.indices = this.indices.map((i) => { + let at = remap.get(i); + if (at === undefined) { + at = positions.length / 3; + remap.set(i, at); + positions.push(this.positions[i * 3], this.positions[i * 3 + 1], this.positions[i * 3 + 2]); + if (hasUv) uvs.push(this.uvs[i * 2], this.uvs[i * 2 + 1]); + } + return at; + }); + this.positions = positions; + this.uvs = uvs; + } + + /** `normal`, when given, is written for every vertex. */ + primitive(doc, buffer, material, normal) { + const count = this.positions.length / 3; + const accessor = (type, array) => doc.createAccessor().setType(type).setArray(array).setBuffer(buffer); + const prim = doc + .createPrimitive() + .setMaterial(material) + .setAttribute('POSITION', accessor('VEC3', new Float32Array(this.positions))) + .setIndices(accessor('SCALAR', count > 65535 ? new Uint32Array(this.indices) : new Uint16Array(this.indices))); + if (this.uvs.length) prim.setAttribute('TEXCOORD_0', accessor('VEC2', new Float32Array(this.uvs))); + if (normal) { + const normals = new Float32Array(count * 3); + for (let i = 0; i < count; i += 1) normals.set(normal, i * 3); + prim.setAttribute('NORMAL', accessor('VEC3', normals)); + } + return prim; + } +} + +/** The determinant of a column-major 4x4's rotation and scale: below zero, the transform mirrors. */ +const handedness = (m) => + m[0] * (m[5] * m[10] - m[9] * m[6]) - m[4] * (m[1] * m[10] - m[9] * m[2]) + m[8] * (m[1] * m[6] - m[5] * m[2]); + +/** A top-level node's triangles, by material name, in the model's frame. `uv` keeps TEXCOORD_0. */ +function gather(node, uv) { + const soups = new Map(); + const materials = new Map(); + node.traverse((n) => { + const mesh = n.getMesh(); + if (!mesh) return; + const matrix = n.getWorldMatrix(); + // A mirrored node (the LED panel's is) turns its triangles inside out + // once they are baked, so they are wound the other way round. + const mirrored = handedness(matrix) < 0; + for (const prim of mesh.listPrimitives()) { + const name = prim.getMaterial()?.getName() ?? 'none'; + materials.set(name, prim.getMaterial()); + if (!soups.has(name)) soups.set(name, new Soup()); + const soup = soups.get(name); + const position = prim.getAttribute('POSITION'); + const texcoord = uv ? prim.getAttribute('TEXCOORD_0') : null; + const base = soup.positions.length / 3; + const v = [0, 0, 0]; + const t = [0, 0]; + for (let i = 0; i < position.getCount(); i += 1) { + soup.positions.push(...point(matrix, position.getElement(i, v))); + if (uv) soup.uvs.push(...(texcoord ? texcoord.getElement(i, t) : [0, 0])); + } + const index = prim.getIndices(); + const count = index ? index.getCount() : position.getCount(); + const at = (i) => base + (index ? index.getScalar(i) : i); + for (let i = 0; i < count; i += 3) { + if (mirrored) soup.indices.push(at(i), at(i + 2), at(i + 1)); + else soup.indices.push(at(i), at(i + 1), at(i + 2)); + } + } + }); + return { soups, materials }; +} + +/** Splits the LED panel's triangles into the lit face (its UVs in the unit square) and the rest. */ +function litFace(soup) { + const face = new Soup(); + const rest = new Soup(); + face.positions = soup.positions; + face.uvs = soup.uvs; + rest.positions = soup.positions; + const onGrid = (k) => { + const [u, v] = [soup.uvs[k * 2], soup.uvs[k * 2 + 1]]; + return u >= -LED_UV_SLACK && u <= 1 + LED_UV_SLACK && v >= -LED_UV_SLACK && v <= 1 + LED_UV_SLACK; + }; + for (let i = 0; i < soup.indices.length; i += 3) { + const [a, b, c] = [soup.indices[i], soup.indices[i + 1], soup.indices[i + 2]]; + (onGrid(a) && onGrid(b) && onGrid(c) ? face : rest).indices.push(a, b, c); + } + face.compact(); + rest.uvs = []; + rest.compact(); + return { face, rest }; +} + +async function lighten(id) { + const io = (await getIO()).registerDependencies({ 'meshopt.encoder': MeshoptEncoder, 'meshopt.decoder': MeshoptDecoder }); + const rules = CASES[id]; + if (!rules) throw new Error(`light.mjs has no rules for ${id}: add it to CASES`); + const source = await io.read(path.join(CASES_DIR, id, 'model.glb')); + const scene = source.getRoot().listScenes()[0]; + await Promise.all([MeshoptSimplifier.ready, MeshoptEncoder.ready, MeshoptDecoder.ready]); + + // The full device's box, every node of it: where the page centres a case. + const box = { min: [Infinity, Infinity, Infinity], max: [-Infinity, -Infinity, -Infinity] }; + for (const node of scene.listChildren()) { + const b = worldBounds(node); + for (let k = 0; k < 3; k += 1) { + box.min[k] = Math.min(box.min[k], b.min[k]); + box.max[k] = Math.max(box.max[k], b.max[k]); + } + } + + const out = new Document(); + const buffer = out.createBuffer(); + const materials = new Map(); + const materialFor = (name, from) => { + if (!materials.has(name)) { + const to = out.createMaterial(name); + if (from) { + to.setBaseColorFactor(from.getBaseColorFactor()) + .setRoughnessFactor(from.getRoughnessFactor()) + .setMetallicFactor(from.getMetallicFactor()) + .setEmissiveFactor(from.getEmissiveFactor()) + .setAlphaMode(from.getAlphaMode()) + .setAlpha(from.getAlpha()) + .setDoubleSided(from.getDoubleSided()); + } + materials.set(name, to); + } + return materials.get(name); + }; + + const body = new Map(); // material name → Soup + const led = new Map(); + let before = 0; + const dropped = []; + + /** Cuts a node's soups to its budget, each to its share by size. What is left joins the body. */ + const keep = (soups, kind) => { + let total = 0; + for (const soup of soups.values()) { + soup.weld(); + total += soup.triangles; + } + for (const [name, soup] of soups) { + if (!soup.triangles) continue; + const target = Math.max(4, Math.round((BUDGET[kind] * soup.triangles) / Math.max(1, total))); + soup.simplify(target, ERROR[kind], kind === 'inside'); + if (!soup.triangles) continue; + if (!body.has(name)) body.set(name, new Soup()); + body.get(name).append(soup); + } + }; + + for (const node of scene.listChildren()) { + const name = node.getName(); + const isLed = name === LED; + const { soups, materials: used } = gather(node, isLed); + for (const soup of soups.values()) before += soup.triangles; + if (matches(name, rules.drop)) { + dropped.push(name); + continue; + } + for (const [key, from] of used) materialFor(key, from); + + if (isLed) { + // The lit face as it is; the panel's back and sides cut down. + const behind = new Map(); + for (const [key, soup] of soups) { + const { face, rest } = litFace(soup); + if (face.triangles) { + if (!led.has(key)) led.set(key, new Soup()); + led.get(key).append(face); + } + if (rest.triangles) behind.set(key, rest); + } + keep(behind, 'panel'); + continue; + } + keep(soups, /^c[1-4]$/.test(name) ? 'knob' : matches(name, rules.inside) ? 'inside' : 'shell'); + } + + const outScene = out.createScene(id).setExtras({ box: { min: fmt(box.min), max: fmt(box.max) } }); + let kept = 0; + const build = (name, soups, normal) => { + // The mesh has no name of its own: three's loader keeps names unique, and + // a mesh called `l` would take the name before its node could. + const mesh = out.createMesh(); + for (const [key, soup] of soups) { + if (!soup.triangles) continue; + kept += soup.triangles; + mesh.addPrimitive(soup.primitive(out, buffer, materials.get(key), normal)); + } + if (mesh.listPrimitives().length) outScene.addChild(out.createNode(name).setMesh(mesh)); + }; + build(LED, led, LED_NORMAL); + build('body', body); + + out.createExtension(KHRMeshQuantization).setRequired(true); + out.createExtension(EXTMeshoptCompression).setRequired(true); + await out.transform( + // keepAttributes: the panel's UVs have no texture on them, which is what + // prune takes for unused. The pattern's shader reads them. + prune({ keepAttributes: true }), + // keepUniqueNames: two materials that look alike are still two when their + // names differ. The page lights the four knob lights one by one, by name. + dedup({ keepUniqueNames: true }), + // 14 bits of position is 0.02 mm on these models. The panel's UVs are the + // LED grid, 128 across: 12 bits puts a texel within 1/32 of an LED. + quantize({ quantizePosition: 14, quantizeTexcoord: 12, quantizeNormal: 8 }), + meshopt({ encoder: MeshoptEncoder, level: 'medium' }), + ); + + const file = path.join(CASES_DIR, id, 'light.glb'); + await io.write(file, out); + const size = fs.statSync(file).size; + const full = fs.statSync(path.join(CASES_DIR, id, 'model.glb')).size; + console.log( + `${id}: ${Math.round(before).toLocaleString('en')} → ${Math.round(kept).toLocaleString('en')} triangles, ` + + `${(full / 1000).toFixed(0)} KB → ${(size / 1000).toFixed(1)} KB` + + `, ${outScene.listChildren().map((n) => n.getName()).join(' + ')}` + + `, left out: ${dropped.length} nodes`, + ); +} + +const asked = process.argv.slice(2); +const ids = asked.length + ? asked + : fs.readdirSync(CASES_DIR).filter((name) => fs.existsSync(path.join(CASES_DIR, name, 'model.glb'))).sort(); +for (const id of ids) await lighten(id); diff --git a/web/ARCHITECTURE.md b/web/ARCHITECTURE.md index 270f4d6f0..8fcebaa23 100644 --- a/web/ARCHITECTURE.md +++ b/web/ARCHITECTURE.md @@ -38,6 +38,7 @@ The `web/` app is the Patternflow site at [patternflow.work](https://patternflow HomeView (src/components/HomeView.tsx) ├── ViewerPanel (components/3d/) ← sticky 3D panel │ ├── HeroScene.tsx ← Canvas, the picked case's GLB (public/cases//model.glb), LED ShaderMaterial +│ ├── CaseShelf.tsx + shelfLayout.ts ← the Build tab's shelf: every case's light model (public/cases//light.glb) on two boards; a picked one stands in for its full model until that arrives │ ├── caseModels.ts + cases/ ← one model per case on the Build panel's switch: URL, node names, exploded view, finishes. The GLBs are built by tools/case-models │ ├── LedMatrixTexture.ts ← renders JS patterns into a texture for the 3D LED mesh │ └── patterns/ ← GLSL pattern ports (common.ts = shared vertex shader + registry) diff --git a/web/public/cases/besoiobiy-printed/light.glb b/web/public/cases/besoiobiy-printed/light.glb new file mode 100644 index 000000000..4bbcc60d6 Binary files /dev/null and b/web/public/cases/besoiobiy-printed/light.glb differ diff --git a/web/public/cases/jof-patternflood/light.glb b/web/public/cases/jof-patternflood/light.glb new file mode 100644 index 000000000..434141bcd Binary files /dev/null and b/web/public/cases/jof-patternflood/light.glb differ diff --git a/web/public/cases/mbchars-horizontal-desktop-printed/light.glb b/web/public/cases/mbchars-horizontal-desktop-printed/light.glb new file mode 100644 index 000000000..03bfaaa0f Binary files /dev/null and b/web/public/cases/mbchars-horizontal-desktop-printed/light.glb differ diff --git a/web/public/cases/official/light.glb b/web/public/cases/official/light.glb new file mode 100644 index 000000000..dfcf87cfe Binary files /dev/null and b/web/public/cases/official/light.glb differ diff --git a/web/public/cases/simonepda-lasercut/light.glb b/web/public/cases/simonepda-lasercut/light.glb new file mode 100644 index 000000000..72f4ed2f6 Binary files /dev/null and b/web/public/cases/simonepda-lasercut/light.glb differ diff --git a/web/src/app/globals.css b/web/src/app/globals.css index 5ad748f3b..02000d6d5 100644 --- a/web/src/app/globals.css +++ b/web/src/app/globals.css @@ -494,8 +494,8 @@ /* At laptop height the column — wordmark, video, the two facts, the buttons — can be taller than the window with the full 80px above it, and the buttons' note falls below the fold. Take the difference from the top. The nav is out - of flow, top-right, and goes up 8px with it, so the Shop box keeps clear - of the wordmark's f and l. */ + of flow, top-right, and goes up 8px with it, so the Instagram mark keeps + clear of the wordmark's f and l. */ @media (min-width: 901px) and (max-height: 860px) { .hero { padding-top: 48px; } .hero .hero-top-links { top: 16px; } @@ -511,19 +511,28 @@ .hero-cta { width: 100%; } } @media (max-width: 900px) { + /* Its first child is the nav, a 44px row in the flow (the rules are at + the end of this file), so nothing is kept clear over the wordmark and + there is no gap between the row and the copy. */ .hero { display: flex; flex-direction: column; align-items: stretch; - padding: 36px 0 60px; - gap: 24px; + padding: 0 0 60px; + gap: 0; min-height: auto; } - .hero-copy h1 { font-size: 50px; margin-bottom: 12px; } - .hero-copy .kicker { font-size: 20px; margin-bottom: 8px; } - .hero-spec { font-size: 14.5px; margin: 0 0 20px; } - .hero-copy p.lede { font-size: 17.5px; margin-bottom: 12px; } + /* 10 and 14, not 12 and 20: the nav row put the wordmark 8px lower, and + these give the 8px back, so Get One is still on the first screen of a + 667px-tall phone. */ + .hero-copy h1 { font-size: 50px; margin-bottom: 10px; } + /* Each of these is two lines on a phone, and the second was a word or + two: "them.", "we make.", "so far." Balanced, the two lines share the + words, and the kicker breaks between its two sentences. */ + .hero-copy .kicker { font-size: 20px; margin-bottom: 8px; text-wrap: balance; } + .hero-spec { font-size: 14.5px; margin: 0 0 14px; text-wrap: balance; } + .hero-copy p.lede { font-size: 17.5px; margin-bottom: 12px; text-wrap: balance; } /* Single column — keep the note directly under Get One rather than letting it fall to the bottom of the stack. */ .hero-cta-row { gap: 8px; grid-template-columns: 1fr; margin-top: 20px; } @@ -911,9 +920,19 @@ color: var(--ink-muted); } footer em { font-style: italic; font-weight: 400; } - /* Same reasoning as .sponsor above — matches .hero dropping to a 0 gutter. */ + /* Same reasoning as .sponsor above — matches .hero dropping to a 0 gutter. + Terms & Privacy is the footer's one link, and it shows that only under a + pointer. A phone has none, so here it carries its line all the time, and + 12px above and below for a finger. */ @media (max-width: 900px) { footer { padding-left: 0; padding-right: 0; } + footer .foot-row a { + display: inline-block; + padding: 12px 0; + text-decoration: underline; + text-underline-offset: 3px; + text-decoration-thickness: 1px; + } } @media (max-width: 640px) { footer { padding: 30px 0 34px; } @@ -961,22 +980,6 @@ fill: currentColor; display: block; } - /* The shop: an outline box in ink, filled on hover like Build it — GitHub. - The accent stays for live signals. The negative margin puts its word on - the same line as Guide, Journal and Community, which sit 2px off the - bottom. */ - .hero-top-links .shop-link { - color: var(--ink); - border: 1px solid var(--ink); - padding: 4px 9px 3px; - margin-bottom: -2px; - transition: background-color 0.15s ease, color 0.15s ease; - } - .hero-top-links .shop-link:hover { - background: var(--ink); - color: var(--cream); - text-decoration: none; - } /* Business */ .business-page { @@ -2073,7 +2076,9 @@ font-weight: 500; letter-spacing: 0.12em; text-transform: uppercase; - color: var(--ink-muted); + /* Ink, not muted: on a phone this bar is the one way to Build, Pattern + and Inside, and in the grey of a caption it read as a footer. */ + color: var(--ink); cursor: pointer; transition: color 0.2s ease, background-color 0.2s ease; } @@ -2084,6 +2089,12 @@ color: var(--cream); background: var(--ink); } + /* The open tab's ✕: a second tap on it closes the section. */ + .mobile-bottom-nav .mb-close { + margin-right: 8px; + font-size: 11px; + letter-spacing: 0; + } /* Hero (closed): keep the footer clear of the parked nav at the bottom. */ .content-panel { padding-bottom: calc(var(--mb-nav-h) + env(safe-area-inset-bottom, 0px)); @@ -2094,32 +2105,68 @@ padding-bottom: 40px; } - /* Force mobile override for top header links by placing it at the end of the file */ + /* The site's pages are the hero's first row on a phone: in the flow above + the wordmark, from the column's left edge to its right, Instagram last. + They were 11px words in the corner over the wordmark, 18px tall to a + finger. Each entry is 44px tall now and the words are 12px. The 6px at + each side of an entry is finger room too, and the row's negative margin + puts the first and last word back on the column's edges. These rules + are at the end of the file so that they follow the desktop ones. */ .hero-top-links { - position: absolute !important; - top: 14px !important; - right: -8px !important; - font-size: 11px !important; - gap: 12px !important; + position: static; + justify-content: space-between; + align-items: center; + gap: 0; + margin: 0 -6px; + /* The copy under it stops at 580px, and so does the row on a tablet: + 580px and the 6px it reaches out at each side. */ + max-width: 592px; + font-size: 12px; + } + .hero-top-links a { + display: inline-flex; + align-items: center; + min-height: 44px; + padding: 0 6px; } .hero-top-links .instagram-link svg { - width: 20px !important; - height: 20px !important; + width: 22px; + height: 22px; } - /* Shorter on a phone, where the nav sits right over the wordmark. Its - word still lines up with the others, now with no margin to do it. */ - .hero-top-links .shop-link { - padding: 2px 6px 1px; - margin-bottom: 0; + /* One gutter. A tab's panel had 22px of its own inside .deck-content's + 24px (40px inside it from 761px up), so Build, Pattern and Inside began + 46px from a phone's edge and the hero and the journal 24px. At 390px + that was a 298px column, and it is 342px now. */ + .pf-section-panel { + padding-left: 0; + padding-right: 0; } } - /* Five entries need about 270px. Below 340px the gaps close up so the row - still starts inside the screen at 280px, a folded phone's width. */ + /* Someone who has asked their system for less motion gets the home view's + panels and bars in place at once. The globe, the device and the hero's + video already hold still for them (useReducedMotion). These are the moves + the stylesheet makes: the page rising 10px as it loads, a tab's panel + rising 16px, the 3D view dropping in on a phone and the section bar + riding up under it. */ + @media (prefers-reduced-motion: reduce) { + .deck-content { animation: none; } + .panel-wrapper { transition: none; transform: none; } + .viewer-panel.is-open { animation: none; } + .mobile-bottom-nav { transition: none; } + } + + /* Five entries need about 290px at 12px. Below 340px the words go back to + 11px, set closer, with 3px at each side, and the row fits a 280px screen, + a folded phone's width. */ @media (max-width: 340px) { .hero-top-links { - gap: 8px !important; + margin: 0 -3px; + font-size: 11px; letter-spacing: 0.04em; } + .hero-top-links a { + padding: 0 3px; + } } diff --git a/web/src/app/homePhoneCss.test.ts b/web/src/app/homePhoneCss.test.ts new file mode 100644 index 000000000..433a2ea97 --- /dev/null +++ b/web/src/app/homePhoneCss.test.ts @@ -0,0 +1,131 @@ +// jsdom applies no stylesheet, so the home view's phone rules are read from +// globals.css. On 15 November 2026, at 390px, the site's nav was 11px words +// 18px tall in the corner over the wordmark, and Build, Pattern and Inside +// began 46px from the screen's edge where the hero began 24px. The shop had a +// box in the nav and a poster under the hero's buttons, and had sold next to +// nothing. + +import { readFileSync } from 'node:fs'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; + +const css = readFileSync(path.resolve(__dirname, 'globals.css'), 'utf8').replace(/\/\*[\s\S]*?\*\//g, ''); + +interface Rule { + selectors: string[]; + body: string; + /** Where the rule starts in the stylesheet, for "this one comes later". */ + at: number; +} + +function rules(source: string, offset = 0): Rule[] { + return [...source.matchAll(/([^{}]+)\{([^{}]*)\}/g)].map((m) => ({ + selectors: m[1].split(',').map((s) => s.trim().replace(/\s+/g, ' ')), + body: m[2], + at: offset + (m.index ?? 0), + })); +} + +/** The rules inside every `@media (max-width: 900px)` block, by matching braces. */ +function below900(): Rule[] { + const out: Rule[] = []; + const open = /@media \(max-width: 900px\)\s*\{/g; + for (let m = open.exec(css); m; m = open.exec(css)) { + const start = m.index + m[0].length; + let depth = 1; + let i = start; + while (depth > 0 && i < css.length) { + if (css[i] === '{') depth++; + if (css[i] === '}') depth--; + i++; + } + out.push(...rules(css.slice(start, i - 1), start)); + } + return out; +} + +function declaration(body: string, property: string) { + return body.match(new RegExp(`(?:^|;)\\s*${property}:\\s*([^;]+)`))?.[1].trim(); +} + +const phone = below900(); +const own = (selector: string) => phone.filter((r) => r.selectors.includes(selector)); + +describe('the home view on a phone', () => { + it('puts the site nav in the flow, as a row over the wordmark', () => { + const nav = own('.hero-top-links'); + expect(nav.some((r) => declaration(r.body, 'position') === 'static')).toBe(true); + expect(nav.some((r) => declaration(r.body, 'justify-content') === 'space-between')).toBe(true); + // No rule pins it back over the wordmark. + expect(css).not.toMatch(/position:\s*absolute\s*!important/); + }); + + it('makes each nav entry 44px tall to a finger', () => { + expect(own('.hero-top-links a').some((r) => declaration(r.body, 'min-height') === '44px')).toBe(true); + }); + + it('keeps nothing clear over the wordmark, now the nav is a row of its own', () => { + const hero = own('.hero').find((r) => declaration(r.body, 'padding')); + expect(declaration(hero!.body, 'padding')).toBe('0 0 60px'); + expect(declaration(hero!.body, 'gap')).toBe('0'); + }); + + it('gives a tab panel no side padding of its own, after the rules that gave it some', () => { + const [flat] = own('.pf-section-panel'); + expect(flat, 'no .pf-section-panel rule below 900px').toBeDefined(); + expect(declaration(flat.body, 'padding-left')).toBe('0'); + expect(declaration(flat.body, 'padding-right')).toBe('0'); + const padded = rules(css).filter( + (r) => r.selectors.includes('.pf-section-panel') && declaration(r.body, 'padding'), + ); + expect(padded.length).toBeGreaterThan(0); + for (const rule of padded) expect(flat.at).toBeGreaterThan(rule.at); + }); + + it('draws the section bar in ink, and its open tab reversed', () => { + const [tab] = own('.mobile-bottom-nav .mb-tab'); + expect(declaration(tab.body, 'color')).toBe('var(--ink)'); + const [active] = own('.mobile-bottom-nav .mb-tab.active'); + expect(declaration(active.body, 'color')).toBe('var(--cream)'); + expect(declaration(active.body, 'background')).toBe('var(--ink)'); + }); + + it('underlines the footer link, which a phone cannot hover over', () => { + const [link] = own('footer .foot-row a'); + expect(declaration(link.body, 'text-decoration')).toBe('underline'); + expect(declaration(link.body, 'padding')).toBe('12px 0'); + }); +}); + +// The globe, the device and the hero's video hold still for someone who has +// asked for less motion. The stylesheet's own moves did not: the page rose +// 10px as it loaded, a tab's panel 16px, and on a phone the 3D view dropped +// in and the section bar rode up under it. +describe('the home view with less motion', () => { + const start = css.indexOf('@media (prefers-reduced-motion: reduce)'); + const end = css.indexOf('\n }\n', start); + const still = rules(css.slice(start, end)); + const body = (selector: string) => still.find((r) => r.selectors.includes(selector))?.body ?? ''; + + it('has a block for it', () => { + expect(start).toBeGreaterThan(-1); + }); + + it('puts the page and a tab panel in place at once', () => { + expect(declaration(body('.deck-content'), 'animation')).toBe('none'); + expect(declaration(body('.panel-wrapper'), 'transition')).toBe('none'); + expect(declaration(body('.panel-wrapper'), 'transform')).toBe('none'); + }); + + it('does not slide the 3D view or the section bar on a phone', () => { + expect(declaration(body('.viewer-panel.is-open'), 'animation')).toBe('none'); + expect(declaration(body('.mobile-bottom-nav'), 'transition')).toBe('none'); + }); +}); + +describe('the shop on the home view', () => { + it('has no box in the nav and no poster in the hero', () => { + expect(css).not.toContain('.shop-link'); + expect(css).not.toContain('.hero-shop'); + }); +}); diff --git a/web/src/components/3d/CaseShelf.tsx b/web/src/components/3d/CaseShelf.tsx new file mode 100644 index 000000000..6f4987d40 --- /dev/null +++ b/web/src/components/3d/CaseShelf.tsx @@ -0,0 +1,403 @@ +'use client'; + +/* eslint-disable react-hooks/immutability -- + Three.js objects are imperative: the frame loop moves, scales and repaints + them, as HeroScene's does, and none of it feeds back into React rendering. */ + +import { useGLTF } from '@react-three/drei'; +import { useFrame, type ThreeEvent } from '@react-three/fiber'; +import { + Component, + Suspense, + useEffect, + useLayoutEffect, + useMemo, + useRef, + type ReactNode, + type RefObject, +} from 'react'; +import * as THREE from 'three'; +import { BUILD_CASES, type CaseId } from '@/components/sections/build-cases-data'; +import { CASE_MODELS, lightUrl, type CaseFinish } from './caseModels'; +import { disposeLight, paintLight, prepareLight, type PreparedLight } from './lightCase'; +import { + CLEAR_SECONDS, + FLY_SECONDS, + HANDOFF_SECONDS, + glide, + planShelf, + walk, + type ShelfItem, +} from './shelfLayout'; + +// The Build tab's shelf, and the light models it is made of. +// +// Every case has two models (caseModels.ts): the full one the preview takes +// apart, 317 to 563 KB and a decoder to fetch first, and a light one of the +// same device standing assembled, 14 to 55 KB. The light ones are all here +// from the start. With the shelf open they stand on its two boards, to pick +// from. With a case picked, that case's light model goes from its place on +// the shelf to where the device stands, and stands in for the full model +// until that has arrived: the full one is then drawn in the same place, at +// the same size and turn, and the light one fades away over it. Going back +// to the shelf is the same the other way. Nothing is ever swapped for a blank. + +/** What the shelf and the preview tell each other, a frame at a time. */ +export interface Handoff { + /** The shelf's: the staged case's width, in model units, once its light model is in. */ + width: number | null; + /** The shelf's: the staged case's light model has reached the stage. */ + arrived: boolean; + /** The shelf's: a light model that runs its case's own demo is on screen. */ + demoShown: boolean; + /** The preview's: the full model of the staged case is the one being drawn. */ + fullShown: boolean; +} + +export const newHandoff = (): Handoff => ({ width: null, arrived: false, demoShown: false, fullShown: false }); + +/** The cases on the shelf, in the Build panel's order: the first ones stand on the top board. */ +const ORDER = BUILD_CASES.map((item) => item.id); +/** A case whose light model is not in yet is planned for at the official case's size. */ +const UNMEASURED = { width: 24.7, height: 32.6, depth: 5.6 }; + +/** The cases on the shelf face a little to the reader's left, as the device does at rest. */ +const SHELF_TURN = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), -0.32); +/** + * Except a case that lies the long way across: turned, its far end runs off + * into the board and it reads as standing crooked. It faces straight out. + */ +const FACING_FRONT = new THREE.Quaternion(); +const turnOf = (id: CaseId) => (id === 'mbchars-horizontal-desktop-printed' ? FACING_FRONT : SHELF_TURN); +/** + * The case whose panel runs while the shelf is only looked at. The others + * hold a still frame of theirs until a pointer or the focus is on them. + */ +const RUNNING_AT_REST: CaseId = 'official'; +/** A press that moved more than this many pixels turned the view; it picks nothing. */ +const DRAG_PIXELS = 4; +/** How much a case under the pointer grows, and how far it rises, in world units. */ +const HOVER_GROW = 0.06; +const HOVER_RISE = 0.05; +const HOVER_SECONDS = 0.16; + +const BOARD_COLOUR = '#e9e2d2'; + +interface Motion { + /** 0 on the shelf, 1 on the stage. */ + fly: number; + /** 0 gone, 1 there: the cases that were not picked leave, and come back. */ + here: number; + /** 1 drawn in full, 0 faded away over the full model. */ + fade: number; + hover: number; +} + +/** A light model that would not load is left off the shelf; its case can still be picked on the panel. */ +class LightGuard extends Component<{ children: ReactNode }, { failed: boolean }> { + override state = { failed: false }; + static getDerivedStateFromError() { + return { failed: true }; + } + override render() { + return this.state.failed ? null : this.props.children; + } +} + +function LightModel({ + id, + register, + handlers, +}: { + id: CaseId; + register: (id: CaseId, light: PreparedLight | null) => void; + handlers: { + onPointerOver?: (e: ThreeEvent) => void; + onPointerOut?: (e: ThreeEvent) => void; + onClick?: (e: ThreeEvent) => void; + }; +}) { + const model = CASE_MODELS[id]; + // No Draco: a light model is written with meshopt, whose decoder is in the + // loader, so nothing else is fetched before it draws. + const { scene } = useGLTF(lightUrl(model), false); + const light = useMemo(() => prepareLight(scene, model), [scene, model]); + + useLayoutEffect(() => { + register(id, light); + return () => register(id, null); + }, [id, light, register]); + useEffect(() => () => disposeLight(light), [light]); + + // dispose={null}: the panel's geometry is drei's cache's; disposeLight lets go of the rest. + return ; +} + +export default function CaseShelf({ + open, + all, + staged, + stage, + handoff, + viewHeight, + centreY, + paint, + finishOf, + tags, + hovered, + still, + onPick, + onIntent, +}: { + /** The shelf is what the view shows. */ + open: boolean; + /** + * Every case's light model is wanted: the view is on the tab that has the + * shelf. Elsewhere only the staged case's is fetched, to stand in for it. + */ + all: boolean; + /** The case on the stage when it is not. */ + staged: CaseId; + /** Where the device stands: the preview's own group, as it moves it. */ + stage: RefObject; + handoff: RefObject; + /** How tall the view is where the device stands, in world units, and where its middle is. */ + viewHeight: number; + centreY: number; + /** + * Lights a light model's panel and knobs as its full model's would be: on + * the shelf, or on the stage. `running`: its panel moves this frame, or + * holds where it was. + */ + paint: (light: PreparedLight, onStage: boolean, running: boolean) => void; + finishOf: (id: CaseId) => CaseFinish | undefined; + /** + * Each case's name: a button over the canvas (HeroScene), kept on the front + * edge of the board the case stands on. A canvas has nothing a keyboard can + * reach, so the buttons are how the shelf is picked from without a pointer. + */ + tags: RefObject>; + /** The case a pointer or the focus is on, whether on its model or on its name. */ + hovered: RefObject; + /** The reader has asked for less motion: a case is on the shelf or on the stage, and never on its way. */ + still: boolean; + onPick: (id: CaseId) => void; + /** A pointer is on a case: its full model may as well start on its way. */ + onIntent: (id: CaseId) => void; +}) { + const lights = useRef(new Map()); + const motions = useRef(new Map()); + const before = useRef<{ open: boolean; staged: CaseId } | null>(null); + const rack = useRef(open ? 1 : 0); + + const boardRefs = useRef<(THREE.Mesh | null)[]>([]); + const boardMaterial = useMemo( + () => new THREE.MeshStandardMaterial({ color: BOARD_COLOUR, roughness: 0.82, metalness: 0 }), + [], + ); + useEffect(() => () => boardMaterial.dispose(), [boardMaterial]); + + const register = useMemo( + () => (id: CaseId, light: PreparedLight | null) => { + if (light) lights.current.set(id, light); + else lights.current.delete(id); + }, + [], + ); + + // A pointer's hand goes back when the shelf closes under it. + useEffect(() => { + if (!open) document.body.style.cursor = ''; + }, [open]); + useEffect(() => () => { document.body.style.cursor = ''; }, []); + + const scratch = useMemo( + () => ({ + shelfAt: new THREE.Vector3(), + stageAt: new THREE.Vector3(), + offset: new THREE.Vector3(), + stageTurn: new THREE.Quaternion(), + tagAt: new THREE.Vector3(), + }), + [], + ); + + useFrame((state, rawDelta) => { + // With less motion asked for, every move below is over in its first frame. + const delta = still ? Infinity : Math.min(Math.max(rawDelta, 0), 0.1); + const group = stage.current; + const was = before.current; + before.current = { open, staged }; + + // A case changed while the shelf is shut (the arrows, the panel's switch + // on another tab) is a cut, as it always was: the new one is on the stage + // at once. So is the first frame of a page that opens on a case. + const cut = !open && (!was || (!was.open && was.staged !== staged)); + const motion = (id: CaseId) => { + let m = motions.current.get(id); + if (!m) { + const onStage = !open && id === staged; + m = { fly: onStage ? 1 : 0, here: open || onStage ? 1 : 0, fade: 1, hover: 0 }; + motions.current.set(id, m); + } + return m; + }; + + // The shelf, for the view as it is and the cases as they measure. + const items: ShelfItem[] = ORDER.map((id) => { + const size = lights.current.get(id)?.size; + return size ? { id, width: size.x, height: size.y, depth: size.z } : { id, ...UNMEASURED }; + }); + const viewWidth = viewHeight * (state.size.width / Math.max(1, state.size.height)); + const plan = planShelf(items, viewWidth, viewHeight, centreY); + + // Coming back to the shelf, the boards and the other cases wait until the + // case that was on the stage is half way home. Sooner, and it flew back + // through cases already standing in its way. + const homing = motions.current.get(staged)?.fly ?? 0; + const shelfUp = open && homing < 0.5; + + rack.current = walk(rack.current, shelfUp ? 1 : 0, delta, CLEAR_SECONDS); + const rackShare = glide(rack.current); + boardMaterial.opacity = rackShare; + boardMaterial.transparent = rackShare < 1; + boardMaterial.depthWrite = rackShare >= 1; + // Two boards and nothing holding them: each floats, as a shelf on a wall does. + plan.boards.forEach((board, index) => { + const mesh = boardRefs.current[index]; + if (!mesh) return; + mesh.visible = rackShare > 0.01; + mesh.position.set(0, board.y - board.thickness / 2, 0); + mesh.scale.set(board.width, board.thickness, board.depth); + }); + + let arrived = false; + let demoShown = false; + for (const id of ORDER) { + const m = motion(id); + const onStage = !open && id === staged; + if (cut) { + m.fly = onStage ? 1 : 0; + m.here = onStage ? 1 : 0; + m.fade = 1; + } + m.fly = walk(m.fly, onStage ? 1 : 0, delta, FLY_SECONDS); + m.here = walk(m.here, shelfUp || id === staged ? 1 : 0, delta, CLEAR_SECONDS); + // Opening the shelf, the light model is whole at once, in the place the + // full one has just left. + m.fade = open ? 1 : walk(m.fade, onStage && handoff.current.fullShown ? 0 : 1, delta, HANDOFF_SECONDS); + const hot = open && hovered.current === id; + m.hover = walk(m.hover, hot ? 1 : 0, delta, HOVER_SECONDS); + if (onStage && m.fly >= 1) arrived = true; + + const slot = plan.slots.find((s) => s.id === id); + const tag = tags.current.get(id); + const board = slot && plan.boards[slot.tier]; + if (tag && slot && board) { + // On the front edge of its board, under its case, in canvas pixels. + scratch.tagAt.set(slot.x, slot.y - board.thickness / 2, board.depth / 2).project(state.camera); + const x = (scratch.tagAt.x * 0.5 + 0.5) * state.size.width; + const y = (scratch.tagAt.y * -0.5 + 0.5) * state.size.height; + tag.style.transform = `translate3d(${x.toFixed(1)}px, ${y.toFixed(1)}px, 0) translate(-50%, -50%)`; + const mark = hot ? '1' : '0'; + if (tag.dataset.hot !== mark) tag.dataset.hot = mark; + // Until now it sat in the frame's corner, where it takes no pointer. + if (tag.dataset.placed !== '1') tag.dataset.placed = '1'; + // A name is up with the board it is on, not before it. + const up = shelfUp ? '1' : '0'; + if (tag.dataset.up !== up) tag.dataset.up = up; + } + + const light = lights.current.get(id); + if (!light || !slot) continue; + + // On the shelf: standing on its board by the middle of its underside. + const lift = glide(m.hover); + const shelfScale = plan.scale * glide(m.here) * (1 + HOVER_GROW * lift); + const shelfTurn = turnOf(id); + scratch.offset.copy(light.foot).multiplyScalar(shelfScale).applyQuaternion(shelfTurn); + scratch.shelfAt.set(slot.x, slot.y + HOVER_RISE * lift, 0).sub(scratch.offset); + + // On the stage: where the preview's group has the device this frame, + // centred as the full model is (fitPosition). + let stageScale = shelfScale; + scratch.stageAt.copy(scratch.shelfAt); + scratch.stageTurn.copy(shelfTurn); + if (group) { + stageScale = group.scale.x; + scratch.stageTurn.copy(group.quaternion); + scratch.offset.copy(light.fitPosition).multiplyScalar(stageScale).applyQuaternion(group.quaternion); + scratch.stageAt.copy(group.position).add(scratch.offset); + } + + const share = glide(m.fly); + const root = light.root; + root.position.lerpVectors(scratch.shelfAt, scratch.stageAt, share); + root.quaternion.slerpQuaternions(shelfTurn, scratch.stageTurn, share); + root.scale.setScalar(THREE.MathUtils.lerp(shelfScale, stageScale, share)); + root.visible = m.fade > 0.01 && root.scale.x > 1e-4; + if (!root.visible) continue; + + // Off the shelf, or on its way, a case runs; on it, the one at rest + // does and the one under the pointer. + const running = !open || share > 0 || id === RUNNING_AT_REST || hot; + paintLight(light, finishOf(id), m.fade); + paint(light, share > 0.5, running); + if (light.model.demo && running) demoShown = true; + } + + const h = handoff.current; + // A light model that is not in yet holds nothing up. + h.arrived = arrived || !lights.current.has(staged); + h.width = lights.current.get(staged)?.size.x ?? null; + h.demoShown = demoShown; + }); + + const handlersFor = (id: CaseId) => + open + ? { + onPointerOver: (e: ThreeEvent) => { + e.stopPropagation(); + document.body.style.cursor = 'pointer'; + hovered.current = id; + onIntent(id); + }, + onPointerOut: () => { + document.body.style.cursor = ''; + if (hovered.current === id) hovered.current = null; + }, + onClick: (e: ThreeEvent) => { + e.stopPropagation(); + // A drag that started and ended on a case was the view turning. + if (e.delta > DRAG_PIXELS) return; + document.body.style.cursor = ''; + hovered.current = null; + onPick(id); + }, + } + : {}; + + return ( + <> + {[0, 1].map((index) => ( + { boardRefs.current[index] = mesh; }} + material={boardMaterial} + visible={false} + castShadow + receiveShadow + > + + + ))} + {ORDER.filter((id) => all || id === staged).map((id) => ( + + + + + + ))} + + ); +} diff --git a/web/src/components/3d/HeroScene.module.css b/web/src/components/3d/HeroScene.module.css index 9cdb16d6a..71f98a86e 100644 --- a/web/src/components/3d/HeroScene.module.css +++ b/web/src/components/3d/HeroScene.module.css @@ -125,3 +125,105 @@ height: 44px; } } + +/* The shelf's cases by name: a button each, on the front edge of the board + its case stands on (CaseShelf.tsx moves them there every frame, so they + start at the frame's corner and are placed by a transform). The kicker type + on the page's ground, so a name reads over the board; the one a pointer or + the focus is on goes to ink. They leave with the shelf. */ + +.shelfTags { + position: absolute; + inset: 0; + z-index: 9; + overflow: hidden; + pointer-events: none; +} + +.shelfTag { + position: absolute; + top: 0; + left: 0; + padding: 5px 8px 4px; + border: 0; + background: var(--cream); + color: #6B655A; + font-family: var(--mono); + font-size: 10.5px; + font-weight: 500; + letter-spacing: 0.1em; + line-height: 1.3; + text-transform: uppercase; + white-space: nowrap; + cursor: pointer; + opacity: 0; + visibility: hidden; + transition: opacity 0.25s ease, visibility 0s 0.25s, color 0.15s ease, background-color 0.15s ease; +} + +/* Only once it has been placed: before the first frame every name is in the + frame's corner, one on another, and a pointer resting there would be + taken for one on the top one's case. And only while its board is up: on + the way back from a case the boards wait for that case to be half way + home, and the names wait with them. */ +.shelfTags[data-on='1'] .shelfTag[data-placed='1'][data-up='1'] { + opacity: 1; + visibility: visible; + pointer-events: auto; + transition: opacity 0.25s ease 0.1s, visibility 0s, color 0.15s ease, background-color 0.15s ease; +} + +.shelfTag[data-hot='1'], +.shelfTag:hover { + background: var(--ink); + color: var(--cream); +} + +.shelfTag:focus-visible { + outline: 2px solid var(--pf-led); + outline-offset: 2px; +} + +/* Back to the shelf from a case, in the frame's top left corner: an outline + in ink that fills under the pointer, as the hero's Build it does. */ + +.allCases { + position: absolute; + top: 16px; + left: 16px; + z-index: 11; + min-height: 36px; + padding: 0 12px; + border: 1px solid var(--ink); + background: var(--cream); + color: var(--ink); + font-family: var(--mono); + font-size: 11px; + font-weight: 500; + letter-spacing: 0.12em; + text-transform: uppercase; + cursor: pointer; + transition: background-color 0.15s ease, color 0.15s ease; +} + +.allCases:hover { + background: var(--ink); + color: var(--cream); +} + +.allCases:focus-visible { + outline: 2px solid var(--pf-led); + outline-offset: 2px; +} + +/* On a phone the top of the frame is the case's name and the hint under it, + so the button goes to the bottom left corner, beside the finish switch and + nearer a thumb, 44px tall. */ +@media (max-width: 900px) { + .allCases { + top: auto; + bottom: 10px; + left: 10px; + min-height: 44px; + } +} diff --git a/web/src/components/3d/HeroScene.tsx b/web/src/components/3d/HeroScene.tsx index be9f84c3d..f3add2a0f 100644 --- a/web/src/components/3d/HeroScene.tsx +++ b/web/src/components/3d/HeroScene.tsx @@ -20,18 +20,19 @@ import { } from 'react'; import * as THREE from 'three'; import { useGLTF, ContactShadows, Environment, Lightformer, OrbitControls } from '@react-three/drei'; +import type { OrbitControls as OrbitControlsImpl } from 'three-stdlib'; import { EffectComposer, Bloom, ToneMapping } from '@react-three/postprocessing'; import { ToneMappingMode } from 'postprocessing'; import { LED_GRID, ledPanel, ledVert } from './patterns/common'; import patterns from './patterns'; -import { useAppStore } from '@/store/useAppStore'; +import { useAppStore, type HomeTabType } from '@/store/useAppStore'; import { LedMatrixTexture } from './LedMatrixTexture'; import { ObraDemo } from './demos/obra'; import { LOGICAL_KNOB_RANGES, LOGICAL_KNOB_TO_WEB_KNOB, LOGICAL_KNOB_WRAP, holdKnobValue, knobUnitsPerTurn } from '@/lib/pattern/controls'; import { BUILD_CASES, findCase, stepCase, writeCaseToUrl, type CaseId } from '@/components/sections/build-cases-data'; import { captureEvent } from '@/lib/posthogEvents'; import { useReducedMotion } from '@/lib/hooks/useReducedMotion'; -import { CASE_MODELS, DRACO_DECODER, type CaseFinish } from './caseModels'; +import { CASE_MODELS, DRACO_DECODER, type CaseFinish, type CaseModel } from './caseModels'; import { preloadCaseModel } from './preloadCaseModel'; import { FRAME_CENTRE, @@ -42,8 +43,10 @@ import { type KnobRig, type PreparedCase, } from './heroCase'; -import { fitAcross, poseFor, shows } from './buildPose'; +import { REST_SCALE, fitAcross, poseFor, shows } from './buildPose'; import CaseFinishSwitch from './CaseFinishSwitch'; +import CaseShelf, { newHandoff, type Handoff } from './CaseShelf'; +import type { PreparedLight } from './lightCase'; import { PageAlpha, StraightAlpha } from './canvasAlpha'; import { NeutralToeBack } from './neutralToe'; import styles from './HeroScene.module.css'; @@ -51,9 +54,14 @@ import styles from './HeroScene.module.css'; // The product preview on the Build and Pattern tabs: the device in the case // the Build panel's switch is on (caseModels.ts), its LED panel running the // pattern, its knobs turning the pattern's controls, and the Build panel's -// four steps acted out on it. Each case is its own model; the official one -// loads with the page, a remix's when it is picked, and until it has arrived -// the case on screen stays. +// four steps acted out on it. +// +// Each case has two models. The light one is small and is there at once: the +// Build tab opens on a shelf of all five (CaseShelf.tsx), and a picked case's +// light model stands where the device stands until its full model has +// arrived. The full one is what the steps take apart and whose knobs turn; +// it is fetched when its case is first shown, and takes over from the light +// one in the same place. const customFragmentShader = ` uniform sampler2D uTex; @@ -106,9 +114,10 @@ void main() { } `; -// Only the official case comes with the page; a remix's model is fetched -// when it is picked, or when its tab is hovered on the way (preloadCaseModel). -useGLTF.preload(CASE_MODELS.official.url, DRACO_DECODER); +// No full model comes with the page any more. The official one did, 317 KB +// and the Draco decoder, on every home page, the globe's included. A case's +// full model is fetched when it is first shown, or when a pointer is on it on +// the way (preloadCaseModel); its light model covers until then. type KnobId = 'c1' | 'c2' | 'c3' | 'c4'; @@ -133,7 +142,12 @@ const Y_AXIS = new THREE.Vector3(0, 1, 0); /** The camera as the page opens: where it stands, and its vertical field of view. */ const CAMERA_POSITION: [number, number, number] = [0.0, 6.0, 10.3]; +const CAMERA_REST = new THREE.Vector3(...CAMERA_POSITION); const CAMERA_FOV = 28; +/** The shelf's middle: a little under the device's, since the top of the frame is the hint's. */ +const SHELF_CENTRE_Y = TARGET.y - 0.25; +/** The width a case is fitted across before its light model has said its own: the official case's. */ +const UNMEASURED_WIDTH = 24.7; /** * How tall the view is where the device stands, with the camera at rest, in * world units; times the canvas's aspect, how wide (buildPose.ts, fitAcross). @@ -150,6 +164,22 @@ const REST_VIEW_HEIGHT = */ const BOARD_SPAN = 3.1; +/** A light model's own copies of the panel's materials, and the clock its pattern runs on. */ +interface LightPanelSet { + pattern: THREE.ShaderMaterial; + custom: THREE.ShaderMaterial; + demo: THREE.ShaderMaterial; + /** Seconds into its pattern. */ + clock: number; + /** Whether the clock moves: said by the shelf each frame the case is drawn. */ + running: boolean; +} +/** Where a case's pattern holds before it has run: a few seconds in, a different moment for each. */ +const STILL_FRAME_AT = 5; +const STILL_FRAME_STEP = 11.3; +/** How far into Obra the first frame drawn is, for a demo that holds still before it has run. */ +const OBRA_STILL_SECONDS = 0.1; + /** A per-frame easing factor (as at 60 fps) made independent of the frame rate. */ const ease = (perFrame: number, dt: number) => 1 - Math.pow(1 - perFrame, Math.min(dt, 0.5) * 60); @@ -235,15 +265,39 @@ function CaseDevice({ */ function ProductPreview({ caseId, + staged, + shelfOpen, + shelfTab, finish, + finishOf, + tags, + hovered, onFailed, + onPick, }: { - caseId: CaseId; + /** The case whose full model is on the stage, or on its way there; none before the stage is first used. */ + caseId: CaseId | null; + /** The case the stage is for: its light model stands there until the full one is `caseId` and has arrived. */ + staged: CaseId; + /** The Build tab's shelf is what the view shows. */ + shelfOpen: boolean; + /** The view is on the tab that has the shelf, open or not. */ + shelfTab: boolean; finish: CaseFinish | undefined; + finishOf: (id: CaseId) => CaseFinish | undefined; + /** The shelf's name buttons and the case a pointer is on (CaseShelf.tsx). */ + tags: RefObject>; + hovered: RefObject; onFailed: (id: CaseId) => void; + onPick: (id: CaseId) => void; }) { const groupRef = useRef(null); const deviceRef = useRef(null); + // What this preview and the shelf's light models tell each other (CaseShelf.tsx). + const handoff = useRef(newHandoff()); + // Whether the device on the stage has power this frame: a light model + // standing there is lit, or dark, as the full one would be. + const stageLit = useRef(true); // Where the view is centred, in the group's own frame; eased like the rest. const focus = useRef(FRAME_CENTRE.clone()); const lift = useRef(0); @@ -315,6 +369,7 @@ function ProductPreview({ // Patternflood's Obra, for a case whose model names it (CaseModel.demo); // it draws only while that case is lit on the Build tab. const obra = useMemo(() => new ObraDemo(), []); + const obraDrawn = useRef(false); useEffect(() => () => obra.texture.dispose(), [obra]); const demoMat = useMemo(() => new THREE.ShaderMaterial({ uniforms: { @@ -328,6 +383,63 @@ function ProductPreview({ const blackMat = useMemo(() => new THREE.MeshStandardMaterial({ color: 0x050505, roughness: 0.8 }), []); + // The light models' panels show what a full model's would: the pattern, the + // editor's code or the case's own demo. The three materials above carry one + // grid between them, the staged device's, and the shelf has every case on + // it at once, so each case gets its own copies, on its own grid. They read + // the same textures and the same knobs. Each runs on a clock of its own, + // which moves only while its case is running (CaseShelf.tsx): on the shelf, + // the official case and the one under the pointer; the rest hold a frame, + // each a different one, and go on from it when they run again. + const lightPanels = useMemo(() => { + const byCase = new Map(); + return { + byCase, + of(model: CaseModel) { + let set = byCase.get(model.id); + if (!set) { + const grid = model.ledGrid ?? LED_GRID; + set = { + pattern: ledMat.clone(), + custom: customMat.clone(), + demo: demoMat.clone(), + clock: STILL_FRAME_AT + byCase.size * STILL_FRAME_STEP, + running: false, + }; + for (const m of [set.pattern, set.custom, set.demo]) m.uniforms.uGrid.value = new THREE.Vector2(grid[0], grid[1]); + byCase.set(model.id, set); + } + return set; + }, + }; + }, [ledMat, customMat, demoMat]); + useEffect( + () => () => lightPanels.byCase.forEach((set) => [set.pattern, set.custom, set.demo].forEach((m) => m.dispose())), + [lightPanels], + ); + + // Lights a light model as its full model would be lit: every case on the + // shelf has power, and one on the stage has it when the step does. + const paintLight = useCallback((light: PreparedLight, onStage: boolean, running: boolean) => { + const lit = onStage ? stageLit.current : true; + const demo = useAppStore.getState().homeTab === 'build' && light.model.demo === 'obra'; + const panels = lightPanels.of(light.model); + panels.running = running; + // On the stage it is the full model's stand-in, on the full model's clock, + // so the one fades over the other showing the same frame. + if (onStage) panels.clock = ledMat.uniforms.uTime.value; + const target = !lit ? blackMat : demo ? panels.demo : activePatternId === 'custom' ? panels.custom : panels.pattern; + for (const mesh of light.led) { + if (mesh.material !== target) mesh.material = target; + } + light.knobLights.forEach((m, k) => { + const c = !lit ? null : demo ? obra.lights()[k] : KNOB_LIGHT_IDLE; + if (c) m.emissive.setRGB(c[0], c[1], c[2], THREE.SRGBColorSpace); + else m.emissive.setRGB(0, 0, 0); + m.emissiveIntensity = KNOB_LIGHT_GAIN; + }); + }, [lightPanels, blackMat, activePatternId, obra, ledMat]); + // --- Knob Interaction Logic --- const drag = useRef<{ rig: KnobRig; knob: KnobId; cx: number; cy: number; lastAngle: number } | null>(null); @@ -453,6 +565,8 @@ function ProductPreview({ // On the Build tab a case with a demo of its own shows that, not the // pattern picked on the Pattern tab. const caseDemo = homeTab === 'build' && deviceRef.current?.model.demo === 'obra'; + // ...and so does its light model, on the shelf or standing in. + const lightDemo = homeTab === 'build' && handoff.current.demoShown; // The pattern on the panel. if (caseDemo) { @@ -468,21 +582,70 @@ function ProductPreview({ ledMat.uniforms.uParam4.value = knobValues[LOGICAL_KNOB_TO_WEB_KNOB[3]]; // Freq/Offset } + // The light models' panels run on the same knobs, each on its own clock. + lightPanels.byCase.forEach((set) => { + if (set.running) set.clock += Math.min(Math.max(delta, 0), 0.1); + const to = set.pattern.uniforms; + const from = ledMat.uniforms; + to.uTime.value = set.clock; + to.uSpeed.value = from.uSpeed.value; + to.uParam1.value = from.uParam1.value; + to.uParam3.value = from.uParam3.value; + to.uParam4.value = from.uParam4.value; + }); + const group = groupRef.current; - const device = deviceRef.current; - if (!group || !device) return; + if (!group) return; + const kView = ease(0.05, delta); + const pose = poseFor(buildStep, explode, t, still, CASE_MODELS[staged].boardless); + stageLit.current = pose.lit; + // The case's own demo, drawn once a frame for whichever is showing it. + if ((caseDemo && pose.lit) || lightDemo) { + obra.render(delta, knobValues, prevKnobValues.current); + obraDrawn.current = true; + } else if (homeTab === 'build' && !obraDrawn.current) { + // Held still on the shelf, a demo still shows a frame of itself, not a blank panel. + obra.render(OBRA_STILL_SECONDS, knobValues, knobValues); + obraDrawn.current = true; + } + if (caseDemo || lightDemo) prevKnobValues.current = { ...knobValues }; + + // The full model is drawn once it is the staged case's and that case's + // light model has reached the stage: until then the light one stands + // there, and the full one, loaded or not, stays out of sight. + const loaded = deviceRef.current; + const device = loaded && loaded.model.id === staged ? loaded : null; + const fullShown = !!device && !shelfOpen && handoff.current.arrived; + handoff.current.fullShown = fullShown; + if (loaded) loaded.root.visible = loaded === device && fullShown; + + if (!device) { + // A light model on the stage, or on its way there: the stage is kept + // where the full model will stand at this step, so the one can take + // over from the other without either moving. A light model is the + // device assembled, so it is framed whole whatever the step. + const width = handoff.current.width ?? UNMEASURED_WIDTH; + const scale = + (pose.board ? REST_SCALE : pose.scale) * + fitAcross(width, REST_VIEW_HEIGHT * (state.size.width / state.size.height)); + group.rotation.y = THREE.MathUtils.lerp(group.rotation.y, pose.turn, kView); + const nextScale = THREE.MathUtils.lerp(group.scale.x, scale, kView); + group.scale.setScalar(nextScale); + focus.current.lerp(FRAME_CENTRE, kView); + lift.current = THREE.MathUtils.lerp(lift.current, pose.lift, kView); + tmp.v.copy(focus.current).multiplyScalar(nextScale).applyAxisAngle(Y_AXIS, group.rotation.y); + group.position.copy(TARGET).sub(tmp.v); + group.position.y += lift.current; + return; + } - const pose = poseFor(buildStep, explode, t, still, device.model.boardless); // A model that has just arrived starts where the step has everything, // not assembled and easing out from there: a swap is a cut, not a move. const fresh = !device.root.userData.settled; device.root.userData.settled = true; const kPart = fresh ? 1 : ease(0.08, delta); - const kView = ease(0.05, delta); // The panel: the pattern while there is power, black while it is being built. - if (caseDemo && pose.lit) obra.render(delta, knobValues, prevKnobValues.current); - if (caseDemo) prevKnobValues.current = { ...knobValues }; const ledTarget = !pose.lit ? blackMat : caseDemo ? demoMat : activePatternId === 'custom' ? customMat : ledMat; // The knobs' lights, where the case has them: the demo's colours while // it runs, a soft white with any other pattern, dark without power. @@ -559,26 +722,99 @@ function ProductPreview({ }); return ( - - onFailed(caseId)}> - - - - - + <> + + {caseId && ( + onFailed(caseId)}> + + + + + )} + + + ); } +/** + * As the shelf opens the camera goes back to where the page opened it: the + * shelf is laid out for that view (shelfLayout.ts), and a view someone had + * turned round the device would show it from behind. From there the shelf can + * be turned and tilted a little (SHELF_ORBIT); a hand on the view stops the + * way back. + */ +function ShelfCamera({ open, controls }: { open: boolean; controls: RefObject }) { + const homing = useRef(open); + useEffect(() => { + if (open) homing.current = true; + }, [open]); + useEffect(() => { + const c = controls.current; + if (!c) return; + const stop = () => { homing.current = false; }; + c.addEventListener('start', stop); + return () => c.removeEventListener('start', stop); + }, [controls]); + useFrame((state, delta) => { + if (!open || !homing.current) return; + state.camera.position.lerp(CAMERA_REST, ease(0.14, delta)); + if (state.camera.position.distanceToSquared(CAMERA_REST) < 1e-4) { + state.camera.position.copy(CAMERA_REST); + homing.current = false; + } + controls.current?.update(); + }); + return null; +} + +/** + * How far the shelf turns under a drag, either side of straight on, and how + * far it tilts, as OrbitControls' polar angle (the camera at rest is 1.17). + */ +const SHELF_ORBIT = { azimuth: 0.6, polarMin: 0.85, polarMax: 1.45 }; + const caseName = (id: CaseId) => BUILD_CASES.find((c) => c.id === id)?.tab ?? id; -export default function HeroScene() { +/** + * `tab` is the tab the viewer is on, from the panel that mounts this scene + * (ViewerPanel). The store learns the page's tab one render late, and read + * from there /build opened as if on the home page: off the shelf, with the + * official case's full model sent for. + */ +export default function HeroScene({ tab }: { tab?: HomeTabType }) { const isDraggingKnob = useAppStore((state) => state.isDraggingKnob); const activeKnobId = useAppStore((state) => state.activeKnobId); const buildCase = useAppStore((state) => state.buildCase); const setBuildCase = useAppStore((state) => state.setBuildCase); - const homeTab = useAppStore((state) => state.homeTab); + const storeTab = useAppStore((state) => state.homeTab); + const homeTab = tab ?? storeTab; const caseFinish = useAppStore((state) => state.caseFinish); const setCaseFinish = useAppStore((state) => state.setCaseFinish); + const buildShelf = useAppStore((state) => state.buildShelf); + const setBuildShelf = useAppStore((state) => state.setBuildShelf); + // The shelf is the Build tab's. The Pattern tab shows the device alone, + // since it is there for its knobs. + const shelfOpen = homeTab === 'build' && buildShelf; + const controlsRef = useRef(null); + // The shelf's name buttons, and the case a pointer or the focus is on. + const shelfTags = useRef(new Map()); + const shelfHover = useRef(null); const [hasInteracted, setHasInteracted] = useState(false); // Latch on first knob interaction — adjusting state during render (guarded) // avoids an extra effect-driven render pass. @@ -586,10 +822,13 @@ export default function HeroScene() { setHasInteracted(true); } - // The case on screen, and the one wanted: the picked case once its model is - // in, the official one for a case whose model would not load. While the - // wanted one loads, the shown one stays. - const [shown, setShown] = useState(() => (arrived.has(buildCase) ? buildCase : 'official')); + // The case whose full model is on the stage, and the one wanted: the picked + // case once its model is in, the official one for a case whose model would + // not load. While the wanted one loads, the shown one stays mounted, out of + // sight, and the wanted case's light model stands on the stage. No full + // model is shown, or fetched, until the view first shows a case and not the + // shelf. + const [shown, setShown] = useState(() => (arrived.has(buildCase) ? buildCase : null)); const [failed, setFailed] = useState([]); // Picking a case whose model failed tries it again: its failure was let go // of in drei's cache (onFailed), so this is a fresh request. Adjusted during @@ -600,7 +839,12 @@ export default function HeroScene() { if (failed.includes(buildCase)) setFailed(failed.filter((id) => id !== buildCase)); } const wanted: CaseId = failed.includes(buildCase) ? 'official' : buildCase; - const loading = wanted !== shown; + // The first case the stage is used for is fetched as the one shown: there + // is no other on it to keep. Adjusted during render, guarded, as above. + // Only on a tab that shows the product: this scene is still mounted for the + // fifth of a second the viewer takes to fade to the globe. + if (!shelfOpen && shown === null && (homeTab === 'build' || homeTab === 'pattern')) setShown(wanted); + const loading = shown !== null && wanted !== shown; const onReady = useCallback((id: CaseId) => setShown(id), []); const onFailed = useCallback((id: CaseId) => { // suspend-react keeps a failed load as a thrown error; without this, the @@ -613,33 +857,50 @@ export default function HeroScene() { setShown((current) => (current === id || id === 'official' ? 'official' : current)); }, []); - const finishes = CASE_MODELS[shown].finishes ?? []; - const finishId = caseFinish[shown] ?? finishes[0]?.id; - const finish = finishes.find((f) => f.id === finishId); - - // Under the device: the picked case on its way, or why it is not there. - const note = loading - ? `Loading ${caseName(wanted)}…` - : failed.includes(buildCase) - ? `${caseName(buildCase)}’s model did not load` - : null; + // The finish each case is shown in: the reader's pick, or its first. The + // switch is for the case on the stage, whose light model takes a finish as + // its full one does, so it is there before the full model is. + const finishOf = useCallback( + (id: CaseId) => { + const all = CASE_MODELS[id].finishes ?? []; + return all.find((f) => f.id === (caseFinish[id] ?? all[0]?.id)); + }, + [caseFinish], + ); + const finishes = CASE_MODELS[wanted].finishes ?? []; + const finishId = caseFinish[wanted] ?? finishes[0]?.id; + + // Under the device: the picked case's full model on its way, or why it is + // not there. + const note = shelfOpen + ? null + : loading + ? `Loading ${caseName(wanted)}…` + : failed.includes(buildCase) + ? `${caseName(buildCase)}’s model did not load` + : null; // On the Build tab, arrows either side of the device step through the // cases, as the Inside globe's step through the builds. It is the Build // panel's switch from the other side: the card, the address and the model - // follow it the same way. - const pickCase = (id: CaseId) => { - setBuildCase(id); - if (window.location.pathname === '/build') writeCaseToUrl(id); - captureEvent('build_case_selected', { case_id: id, interaction: 'click', surface: 'product_preview' }); - }; + // follow it the same way. So does a case picked off the shelf. + const pickCase = useCallback( + (id: CaseId, surface: 'product_preview' | 'case_shelf' = 'product_preview') => { + setBuildCase(id); + if (window.location.pathname === '/build') writeCaseToUrl(id); + captureEvent('build_case_selected', { case_id: id, interaction: 'click', surface }); + }, + [setBuildCase], + ); + const pickFromShelf = useCallback((id: CaseId) => pickCase(id, 'case_shelf'), [pickCase]); // Over the device on the Build tab, whose case it is, in the build map's // label: the name on its tab of the panel's switch, and nothing else. It // changes with the pick, as the tab does, ahead of a model still loading // (the note under the device says so), and reads Official for a case whose - // model did not load, since that is the one drawn. - const titled = homeTab === 'build' ? findCase(wanted) : undefined; + // model did not load, since that is the one drawn. The shelf has a name + // under each case and no title. + const titled = homeTab === 'build' && !shelfOpen ? findCase(wanted) : undefined; return (
@@ -663,19 +924,57 @@ export default function HeroScene() { letterSpacing: '0.14em', textTransform: 'uppercase', pointerEvents: 'none', - opacity: hasInteracted ? 0 : 1, + opacity: shelfOpen || !hasInteracted ? 1 : 0, transition: 'opacity 1.5s ease-in-out', zIndex: 10, }} > - Rotate the knobs to explore + {shelfOpen ? 'Pick a case' : 'Rotate the knobs to explore'}
+ {/* The shelf's cases by name, each a button on the front edge of its + board (CaseShelf places them every frame). They are the shelf for a + keyboard or a screen reader, which the canvas gives nothing to. */} + {homeTab === 'build' && ( +
+ {BUILD_CASES.map((item) => ( + + ))} +
+ )} + + {homeTab === 'build' && !shelfOpen && ( + + )} +
{note}
- {homeTab === 'build' && BUILD_CASES.length > 1 && [-1, 1].map((step) => { + {homeTab === 'build' && !shelfOpen && BUILD_CASES.length > 1 && [-1, 1].map((step) => { const target = stepCase(buildCase, step); return ( ))} diff --git a/web/src/store/useAppStore.ts b/web/src/store/useAppStore.ts index 6005e262b..47cdeb607 100644 --- a/web/src/store/useAppStore.ts +++ b/web/src/store/useAppStore.ts @@ -52,6 +52,11 @@ interface AppState { // product, so the case a reader picked stays the one they look at. buildCase: CaseId; setBuildCase: (id: CaseId) => void; + // The Build tab's 3D view opens on the shelf: every case standing on it, + // small, to pick from. Picking one (there, on the panel's switch, by its + // address) takes the view to that case, and All cases brings the shelf back. + buildShelf: boolean; + setBuildShelf: (open: boolean) => void; // For a case that comes in more than one finish (caseModels.ts: finishes), // which one the preview shows. Kept per case, so going back to it keeps the // reader's pick; a case without an entry shows its first finish. @@ -129,7 +134,10 @@ export function draw(display, params, globalTime) { explode: 1, setExplode: (val) => set({ explode: val }), buildCase: 'official', - setBuildCase: (id) => set({ buildCase: id }), + // Naming a case is asking to see it, so the shelf steps aside. + setBuildCase: (id) => set({ buildCase: id, buildShelf: false }), + buildShelf: true, + setBuildShelf: (open) => set({ buildShelf: open }), caseFinish: {}, setCaseFinish: (id, finish) => set((state) => ({ caseFinish: { ...state.caseFinish, [id]: finish } })),