Landed
Merge web/music-box-hero into main
Landed as b635e01
authored by oscabriel · committed by the platform · parents 3de7ae7, 445c651 · Browse files · 18 files·+4889 added−348 removed
18 files changed+4889 added−348 removed
added:apps/web/src/features/landing/music-box/art.tsx+278 added
1+/**2+ * The music box in painter's order, drawn at one pose. The parts the motion3+ * moves are groups named by `data-part`; everything else never changes.4+ */5+import { memo } from "react";6+7+import { Marks } from "./draw.tsx";8+import {9+ drumPins,10+ liveFrame,11+ rulesPins,12+ tapeEntries,13+ toothState,14+} from "./frame.ts";15+import { HEIGHT, STATIONS, TEETH, WIDTH, toothX } from "./layout.ts";16+import { solid } from "./marks.ts";17+import type { Pose } from "./model.ts";18+import {19+ armBack,20+ armFront,21+ armStrip,22+ askFlag,23+ bell,24+ bench,25+ carriage,26+ caseBack,27+ claimClip,28+ combBlock,29+ combRoot,30+ crank,31+ drum,32+ feeler,33+ flag,34+ follower,35+ glassWall,36+ governorFan,37+ hinges,38+ lever,39+ lid,40+ lipAndRuler,41+ movementBack,42+ movementEnd,43+ movementFront,44+ pawl,45+ pillars,46+ printer,47+ railBack,48+ ratchetTeeth,49+ rulesLink,50+ rulesTrack,51+ slip,52+ stationFronts,53+ strip,54+ tape,55+ template,56+ testTeeth,57+ tooth,58+ trayBacks,59+ trayFronts,60+ trayOpening,61+} from "./parts.ts";62+63+const STATIC = {64+ bench: bench(),65+ caseBack: caseBack(),66+ combBlock: combBlock(),67+ combRoot: combRoot(),68+ drum: drum(),69+ follower: follower(),70+ glassWall: glassWall(),71+ hinges: hinges(),72+ lid: lid(),73+ lipAndRuler: lipAndRuler(),74+ movementBack: movementBack(),75+ movementEnd: movementEnd(),76+ movementFront: movementFront(),77+ pawl: pawl(),78+ pillars: pillars(),79+ printer: printer(),80+ railBack: railBack(),81+ rulesLink: rulesLink(),82+ rulesTrack: rulesTrack(),83+ stations: stationFronts(),84+ tape: tape(),85+ teeth: Array.from({ length: TEETH }, (_, index) => [86+ solid(tooth(index), "hi", { crease: "lo" }),87+ ]),88+ trayBacks: trayBacks(),89+ trayFronts: trayFronts(),90+} as const;91+92+const MOVING = {93+ bell: bell(),94+ carriage: carriage(),95+ claim: claimClip(),96+ feeler: feeler(),97+ flags: STATIONS.map((x) => [solid(flag(x), "mid")]),98+ lever: lever(),99+ slip: slip(STATIONS[1]),100+ strayStrip: strip(true),101+ strip: strip(false),102+ template: template(),103+ testTeeth: testTeeth(),104+} as const;105+106+const PIN_ALPHAS = [0, 1, 2, 3] as const;107+108+const Pins = ({109+ name,110+ ds,111+}: {112+ readonly name: string;113+ readonly ds: readonly string[];114+}) => (115+ <g className="mbx-pins" data-part={name}>116+ {PIN_ALPHAS.map((alpha) => (117+ <path d={ds[alpha] ?? ""} data-alpha={alpha} key={alpha} />118+ ))}119+ </g>120+);121+122+/** The first answer: on the carriage, then in its tray. */123+const Stray = ({ frame }: { readonly frame: ReturnType<typeof liveFrame> }) => (124+ <g125+ data-fault={frame.fault ? "" : undefined}126+ data-part="stray"127+ opacity={frame.strayOpacity.toFixed(3)}128+ transform={frame.stray}129+ >130+ <Marks marks={MOVING.strayStrip} />131+ </g>132+);133+134+/** Everything, painted back to front, with the moving parts at `pose`. */135+const Drawing = ({ pose }: { readonly pose: Pose }) => {136+ const frame = liveFrame(pose);137+ const pins = drumPins(pose);138+ const rules = rulesPins(pose.drum);139+140+ return (141+ <svg142+ aria-hidden="true"143+ className="mbx-svg"144+ viewBox={`0 0 ${WIDTH} ${HEIGHT}`}145+ >146+ <Marks marks={STATIC.bench} />147+ <Marks marks={STATIC.lid} />148+ <Marks marks={STATIC.hinges} />149+ <Marks marks={STATIC.caseBack} />150+ <Marks marks={STATIC.movementBack} />151+ <g data-part="fan">152+ <Marks marks={governorFan(frame.fan)} />153+ </g>154+ <Marks marks={STATIC.drum} />155+ <Pins ds={pins.tune} name="pins" />156+ <path className="mbx-pin" d={pins.ask} data-part="sour" />157+ <path158+ className="mbx-pin"159+ d={pins.fixed}160+ data-part="fixed"161+ data-state="landed"162+ />163+ <Marks marks={STATIC.movementFront} />164+ <Marks marks={STATIC.rulesTrack} />165+ <Pins ds={rules} name="rules" />166+ <Marks marks={STATIC.movementEnd} />167+ <path168+ className="mbx-line"169+ d={ratchetTeeth(frame.ratchet)}170+ data-part="ratchet"171+ data-tone="lo"172+ />173+ <Marks marks={STATIC.pawl} />174+ <Marks marks={STATIC.combBlock} />175+ {STATIC.teeth.map((marks, index) => (176+ <g177+ data-part="tooth"178+ data-state={toothState(pose, index)}179+ key={toothX(index)}180+ transform={frame.teeth[index]}181+ >182+ <Marks marks={marks} />183+ </g>184+ ))}185+ <Marks marks={STATIC.combRoot} />186+ <Marks marks={STATIC.follower} />187+ <Marks marks={STATIC.lipAndRuler} />188+ <g189+ data-part="claim"190+ opacity={frame.claimOpacity.toFixed(3)}191+ transform={frame.claim}192+ >193+ <Marks marks={MOVING.claim} />194+ </g>195+ <g data-part="flag" transform={frame.flag}>196+ <Marks marks={askFlag(0)} />197+ </g>198+ <Marks marks={STATIC.pillars} />199+ <Marks marks={STATIC.railBack} />200+ <g data-part="carriage" transform={frame.carriage}>201+ <Marks marks={MOVING.carriage} />202+ <g data-part="strip" opacity={frame.stripOpacity.toFixed(3)}>203+ <Marks marks={MOVING.strip} />204+ </g>205+ </g>206+ <g data-part="carriage-slot">207+ {pose.drop > 0 ? null : <Stray frame={frame} />}208+ </g>209+ {STATIC.stations.map((marks, index) => (210+ <g data-station={index} key={STATIONS[index]}>211+ <Marks marks={marks} />212+ <g data-flag={index} data-state={pose.flags[index]}>213+ <Marks marks={MOVING.flags[index] ?? []} />214+ </g>215+ </g>216+ ))}217+ <g data-part="template" transform={frame.template}>218+ <Marks marks={MOVING.template} />219+ </g>220+ <g data-part="feeler" transform={frame.feeler}>221+ <Marks marks={MOVING.feeler} />222+ </g>223+ <g data-part="test-comb" transform={frame.testComb}>224+ <Marks marks={MOVING.testTeeth} />225+ </g>226+ <g227+ data-part="bell"228+ data-state={pose.bell > 0.05 ? "sealed" : undefined}229+ transform={frame.bell}230+ >231+ <Marks marks={MOVING.bell} />232+ </g>233+ <Marks marks={MOVING.lever} />234+ <Marks marks={STATIC.trayBacks} />235+ <g data-part="tray-layer">236+ {pose.drop > 0 ? <Stray frame={frame} /> : null}237+ </g>238+ <clipPath id="mbx-tray">239+ <path d={trayOpening(STATIONS[1])} />240+ </clipPath>241+ <g clipPath="url(#mbx-tray)">242+ <g243+ data-part="slip"244+ opacity={pose.slip.toFixed(3)}245+ transform={frame.slip}246+ >247+ <Marks marks={MOVING.slip} />248+ </g>249+ </g>250+ <Marks marks={STATIC.trayFronts} />251+ <g data-part="arm-back">252+ <Marks marks={armBack(pose.arm)} />253+ </g>254+ <g data-part="arm-strip" opacity={frame.heldOpacity.toFixed(3)}>255+ <Marks marks={armStrip(pose.arm)} />256+ </g>257+ <g data-part="arm-front">258+ <Marks marks={armFront(pose.arm)} />259+ </g>260+ <Marks marks={STATIC.rulesLink} />261+ <Marks marks={STATIC.glassWall} />262+ <g data-part="crank">263+ <Marks marks={crank(pose.drum)} />264+ </g>265+ <Marks marks={STATIC.printer} />266+ <Marks marks={STATIC.tape} />267+ <path268+ className="mbx-line"269+ d={tapeEntries(pose)}270+ data-free=""271+ data-part="entries"272+ data-tone="lo"273+ />274+ </svg>275+ );276+};277+278+export const Art = memo(Drawing);added:apps/web/src/features/landing/music-box/draw.tsx+144 added
1+/**2+ * Marks as SVG. Every solid draws the same nine paths whatever it holds, so3+ * the motion can repaint a part that changes shape by writing each path's4+ * `d` in order, and never re-renders.5+ */6+import type { Solid } from "./iso.ts";7+import type { LineMark, Mark, SolidMark } from "./marks.ts";8+9+const Line = ({ mark }: { readonly mark: LineMark }) => (10+ <path11+ className="mbx-line"12+ d={mark.d}13+ data-free={mark.free === true ? "" : undefined}14+ data-tone={mark.tone}15+ style={mark.width === undefined ? undefined : { strokeWidth: mark.width }}16+ />17+);18+19+const SHADES = [0, 1, 2, 3] as const;20+21+const SolidPaths = ({ mark }: { readonly mark: SolidMark }) => {22+ const crease = mark.crease ?? "faint";23+24+ return (25+ <g26+ className="mbx-solid"27+ data-flat={mark.flat === true ? "" : undefined}28+ data-glass={mark.glass === true ? "" : undefined}29+ data-lit={mark.lit === true ? "" : undefined}30+ >31+ <path className="mbx-fill" d={mark.solid.fill} />32+ {SHADES.map((shade) => (33+ <path34+ className="mbx-shade"35+ d={mark.solid.shades[shade]}36+ data-shade={shade}37+ key={shade}38+ />39+ ))}40+ <path className="mbx-top" d={mark.solid.top} />41+ <path42+ className="mbx-line mbx-crease"43+ d={crease === "none" ? "" : mark.solid.crease}44+ data-tone={crease}45+ />46+ <path47+ className="mbx-line mbx-bevel"48+ d={crease === "none" ? "" : mark.solid.bevel}49+ data-tone={crease}50+ />51+ {(mark.inner ?? []).map((inner) => (52+ <Line key={inner.d} mark={inner} />53+ ))}54+ <path55+ className="mbx-line mbx-edge"56+ d={mark.solid.outline}57+ data-tone={mark.tone}58+ />59+ </g>60+ );61+};62+63+const markKey = (mark: Mark, index: number) => {64+ if (mark.kind === "solid") {65+ return `${index}:${mark.solid.outline.slice(0, 24)}`;66+ }67+68+ return `${index}:${mark.kind === "line" ? mark.d.slice(0, 24) : mark.points.length}`;69+};70+71+const keyed = (marks: readonly Mark[]) =>72+ marks.map((mark, index) => ({ key: markKey(mark, index), mark }));73+74+const Dots = ({ mark }: { readonly mark: Extract<Mark, { kind: "dots" }> }) => (75+ <g className="mbx-dots" data-tone={mark.tone}>76+ {mark.points.map(([x, y]) => (77+ <circle78+ cx={Math.round(x * 10) / 10}79+ cy={Math.round(y * 10) / 10}80+ key={`${Math.round(x * 10)},${Math.round(y * 10)}`}81+ r={mark.size}82+ />83+ ))}84+ </g>85+);86+87+/** A list of marks, painted in order. */88+export const Marks = ({ marks }: { readonly marks: readonly Mark[] }) => (89+ <>90+ {keyed(marks).map(({ key, mark }) => {91+ if (mark.kind === "solid") {92+ return <SolidPaths key={key} mark={mark} />;93+ }94+95+ if (mark.kind === "line") {96+ return <Line key={key} mark={mark} />;97+ }98+99+ return <Dots key={key} mark={mark} />;100+ })}101+ </>102+);103+104+const solidDs = (solid: Solid, mark: SolidMark) => {105+ const crease = mark.crease ?? "faint";106+107+ return [108+ solid.fill,109+ ...solid.shades,110+ solid.top,111+ crease === "none" ? "" : solid.crease,112+ crease === "none" ? "" : solid.bevel,113+ ...(mark.inner ?? []).map((inner) => inner.d),114+ solid.outline,115+ ];116+};117+118+/**119+ * Repaints a group drawn from marks of the same kinds, in the same order,120+ * with new paths: a turning crank, the press's arm, the governor's fan.121+ */122+export const repaint = (group: SVGGElement | null, marks: readonly Mark[]) => {123+ if (group === null) {124+ return;125+ }126+127+ const ds = marks.flatMap((mark) => {128+ if (mark.kind === "solid") {129+ return solidDs(mark.solid, mark);130+ }131+132+ return mark.kind === "line" ? [mark.d] : [];133+ });134+135+ const paths = group.querySelectorAll("path");136+137+ for (const [index, d] of ds.entries()) {138+ const path = paths.item(index);139+140+ if (path.getAttribute("d") !== d) {141+ path.setAttribute("d", d);142+ }143+ }144+};added:apps/web/src/features/landing/music-box/frame.ts+165 added
1+/**2+ * What changes from one frame to the next: transforms, the pins on the3+ * turning cylinder, the tape's printed entries. Pure functions of a pose, so4+ * the server's still picture and the browser's first frame are the same.5+ */6+import { translateBy } from "./iso.ts";7+import {8+ CAMERA,9+ CARRIAGE_TOP,10+ SECTION,11+ STATIONS,12+ TAPE,13+ TEETH,14+ TEETH_PER_SECTION,15+ TRAY_Y,16+ STRIP_Y,17+ toothX,18+} from "./layout.ts";19+import { ASKS } from "./model.ts";20+import type { Pose } from "./model.ts";21+import { RULES, TUNE, entry, pinAt, pinPast, pluck } from "./parts.ts";22+import type { Pin } from "./parts.ts";23+24+const C = CAMERA;25+26+const move = (x: number, y: number, z: number) => translateBy(C, [x, y, z]);27+28+/** Each ask's tooth, its sour pin and the pin that corrects it. */29+const ASK_PINS = ASKS.map((offset, index) => {30+ const x = toothX(SECTION * TEETH_PER_SECTION + offset);31+32+ return {33+ fixed: { angle: 1.1 + index * 1.7 + 0.9, x },34+ sour: { angle: 1.1 + index * 1.7, x },35+ };36+});37+38+const cycleOf = (pose: Pose) => pose.ask;39+40+/** Where each of the four pin tones begins, by how squarely a pin faces the viewer. */41+const PIN_TONES = [0.14, 0.28, 0.45] as const;42+43+const buckets = (pins: readonly Pin[], turn: number) => {44+ const ds = ["", "", "", ""];45+46+ for (const pin of pins) {47+ const { base, facing, tip } = pinAt(pin, turn);48+49+ if (facing > 0.02) {50+ const bucket = PIN_TONES.filter((edge) => facing >= edge).length;51+52+ ds[bucket] +=53+ `M${base[0].toFixed(1)} ${base[1].toFixed(1)}L${tip[0].toFixed(1)} ${tip[1].toFixed(1)}`;54+ }55+ }56+57+ return ds;58+};59+60+const one = (pin: Pin, turn: number) => buckets([pin], turn).join("");61+62+/** The pins of the tune, the ask's sour pin and its correction, at the cylinder's angle. */63+export const drumPins = (pose: Pose) => {64+ const current = cycleOf(pose);65+66+ const done = ASK_PINS.slice(0, Math.max(0, current)).map(67+ (pins) => pins.fixed68+ );69+70+ const ask = ASK_PINS[current];71+72+ return {73+ ask: ask !== undefined && pose.fixed < 1 ? one(ask.sour, pose.drum) : "",74+ fixed: ask !== undefined && pose.fixed > 0 ? one(ask.fixed, pose.drum) : "",75+ tune: buckets([...TUNE, ...done], pose.drum),76+ };77+};78+79+/** Every pin the cylinder carries now, for the teeth they pluck. */80+const pinsNow = (pose: Pose) => {81+ const current = cycleOf(pose);82+ const ask = ASK_PINS[current];83+84+ return [85+ ...TUNE,86+ ...ASK_PINS.slice(0, Math.max(0, current)).map((pins) => pins.fixed),87+ ...(ask === undefined ? [] : [pose.fixed < 0.5 ? ask.sour : ask.fixed]),88+ ];89+};90+91+export const rulesPins = (turn: number) => buckets(RULES, turn);92+93+const TOOTH_STATES = [94+ ["ask", (pose: Pose) => pose.fixed < 0.5],95+ ["landed", (pose: Pose) => pose.fresh > 0.5],96+] as const;97+98+/** How each tooth reads: the ask's tooth lit while it plays sour, green just after it lands. */99+export const toothState = (pose: Pose, index: number) =>100+ index === pose.tooth101+ ? TOOTH_STATES.find(([, when]) => when(pose))?.[0]102+ : undefined;103+104+const TOOTH_LIFT = C.k * C.cosE;105+106+/** The motion's transforms and paths at a pose. */107+export const liveFrame = (pose: Pose) => {108+ const lifts = Array.from({ length: TEETH }, () => 0);109+110+ for (const pin of pinsNow(pose)) {111+ const index = Math.round((pin.x - toothX(0)) / (toothX(1) - toothX(0)));112+ const lift = pluck(pinPast(pin, pose.drum));113+114+ if (Math.abs(lift) > Math.abs(lifts[index] ?? 0)) {115+ lifts[index] = lift;116+ }117+ }118+119+ const stray =120+ pose.round === 1 && pose.drop === 0 ? pose.carriage : STATIONS[1];121+122+ return {123+ bell: move(Math.sin(pose.bell * 18) * 0.5 * pose.bell, 0, 0),124+ carriage: move(pose.carriage, 0, 0),125+ claim: move((1 - pose.claim) * 26, 0, 0),126+ claimOpacity: pose.claim,127+ fan: pose.drum * 14,128+ /** The stray pin, once the shape stage has found it. */129+ fault: pose.drop > 0 || pose.flags.includes("refused"),130+ feeler: move(0, 0, -pose.feeler * 1.6),131+ flag: move(toothX(pose.tooth), 0, 0),132+ ratchet: -pose.ratchet * ((Math.PI * 2) / 18),133+ slip: move(0, 0, (pose.slip - 1) * 10),134+ stray: move(135+ stray,136+ pose.drop * (TRAY_Y[0] + 9 - (STRIP_Y[0] + STRIP_Y[1]) / 2),137+ -pose.drop * (CARRIAGE_TOP - 1.4)138+ ),139+ strayOpacity:140+ pose.round === 1 || pose.drop > 0 ? pose.dropped * pose.arrive : 0,141+ /** The second answer fades in at the intake; the press's copy fades as it pins it. */142+ stripOpacity: pose.round === 2 ? pose.arrive : 0,143+ heldOpacity: pose.holding ? 1 - pose.fixed : 0,144+ teeth: lifts.map((lift) =>145+ lift === 0146+ ? undefined147+ : `translate(0 ${(-lift * TOOTH_LIFT * 0.6).toFixed(2)})`148+ ),149+ template: move(0, 0, -pose.template * 1.7),150+ testComb: move(Math.sin(pose.testComb * 30) * 0.3 * pose.testComb, 0, 0),151+ };152+};153+154+/** The tape's printed entries: one per landing, sliding out as each prints. */155+export const tapeEntries = (pose: Pose) => {156+ const landed = Math.floor(pose.entries / 2);157+158+ const shift =159+ pose.printing < 1 && pose.printing > 0 ? (pose.printing - 1) * 7 : 0;160+161+ return Array.from({ length: landed }, (_, newest) => newest * 7 + shift)162+ .filter((out) => out >= 0 && out < TAPE.d - 8)163+ .map((out) => entry(out))164+ .join("");165+};added:apps/web/src/features/landing/music-box/iso.ts+1063 added
1+/**2+ * The isometric camera, solids and lines the music box is drawn with.3+ *4+ * Ported from the anatomy skill's kit (`kit/iso-kit.ts` and `kit/lathe.mjs`),5+ * and changed freely since:6+ *7+ * MIT License8+ *9+ * Copyright (c) 2026 Ryan10+ *11+ * Permission is hereby granted, free of charge, to any person obtaining a copy12+ * of this software and associated documentation files (the "Software"), to deal13+ * in the Software without restriction, including without limitation the rights14+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell15+ * copies of the Software, and to permit persons to whom the Software is16+ * furnished to do so, subject to the following conditions:17+ *18+ * The above copyright notice and this permission notice shall be included in19+ * all copies or substantial portions of the Software.20+ *21+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR22+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,23+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE24+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER25+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,26+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE27+ * SOFTWARE.28+ */29+30+/** A point on the screen, in the drawing's viewBox. */31+export type Flat = readonly [number, number];32+33+/** A point in the world: x and y on the floor, z up, in units of about a pixel. */34+export type Point = readonly [number, number, number];35+36+/** A rounded rectangle on the floor. */37+export interface Plan {38+ readonly x: number;39+ readonly y: number;40+ readonly w: number;41+ readonly d: number;42+ readonly r: number;43+}44+45+/** Where the camera stands, fitted to the drawing's box. */46+export interface Camera {47+ readonly ox: number;48+ readonly oy: number;49+ readonly k: number;50+ readonly sinA: number;51+ readonly cosA: number;52+ readonly sinE: number;53+ readonly cosE: number;54+}55+56+/** A frame for parts along any axis: its origin, its axis and two radial directions. */57+export interface Frame {58+ readonly o: Point;59+ readonly a: Point;60+ readonly u: Point;61+ readonly v: Point;62+}63+64+/**65+ * A solid's paths, painted in this order: the paper fill that hides what is66+ * behind, four side tones by how each face meets the light, the top, the67+ * crease where top meets side, an optional bevel, and the silhouette.68+ */69+export interface Solid {70+ readonly fill: string;71+ readonly shades: readonly [string, string, string, string];72+ readonly top: string;73+ readonly crease: string;74+ readonly bevel: string;75+ readonly outline: string;76+}77+78+export const EMPTY_SOLID: Solid = {79+ bevel: "",80+ crease: "",81+ fill: "",82+ outline: "",83+ shades: ["", "", "", ""],84+ top: "",85+};86+87+const ORIGIN: Flat = [0, 0];88+89+const RADIANS = Math.PI / 180;90+91+const TAU = Math.PI * 2;92+93+const UNIT = Math.sqrt(1.6);94+95+const LIGHT_UP = 1.2;96+97+/** The light's score at which each of the five tones begins: four sides, then the top. */98+const BANDS = [0, 0.2, 0.42, 0.62] as const;99+100+const VISIBLE = 1e-6;101+102+export const add = (a: Point, b: Point): Point => [103+ a[0] + b[0],104+ a[1] + b[1],105+ a[2] + b[2],106+];107+108+export const sub = (a: Point, b: Point): Point => [109+ a[0] - b[0],110+ a[1] - b[1],111+ a[2] - b[2],112+];113+114+export const times = (a: Point, by: number): Point => [115+ a[0] * by,116+ a[1] * by,117+ a[2] * by,118+];119+120+export const dot = (a: Point, b: Point) =>121+ a[0] * b[0] + a[1] * b[1] + a[2] * b[2];122+123+export const cross = (a: Point, b: Point): Point => [124+ a[1] * b[2] - a[2] * b[1],125+ a[2] * b[0] - a[0] * b[2],126+ a[0] * b[1] - a[1] * b[0],127+];128+129+export const unit = (a: Point): Point => {130+ const length = Math.hypot(a[0], a[1], a[2]) || 1;131+132+ return [a[0] / length, a[1] / length, a[2] / length];133+};134+135+const trig = (azimuth: number, elevation: number) => ({136+ cosA: Math.cos(azimuth * RADIANS),137+ cosE: Math.cos(elevation * RADIANS),138+ sinA: Math.sin(azimuth * RADIANS),139+ sinE: Math.sin(elevation * RADIANS),140+});141+142+/** World to screen. */143+export const at = ([x, y, z]: Point, camera: Camera): Flat => [144+ camera.ox + (x * camera.sinA - y * camera.cosA) * camera.k,145+ camera.oy +146+ ((x * camera.cosA + y * camera.sinA) * camera.sinE - z * camera.cosE) *147+ camera.k,148+];149+150+/** The unit direction toward the viewer: a larger dot with it is nearer. */151+export const view = (camera: Camera): Point => [152+ camera.cosA * camera.cosE,153+ camera.sinA * camera.cosE,154+ camera.sinE,155+];156+157+/** The kit's light: from the viewer's upper left. */158+export const light = (camera: Camera): Point =>159+ unit([-camera.sinA, camera.cosA, LIGHT_UP]);160+161+/** Larger is nearer the viewer; paint in ascending order. */162+export const depth = (point: Point, camera: Camera) => dot(point, view(camera));163+164+/**165+ * A camera that centres these points in a box of `width` by `height`, `pad`166+ * clear of every edge.167+ */168+export const fitCamera = (169+ points: readonly Point[],170+ box: {171+ readonly width: number;172+ readonly height: number;173+ readonly pad: number;174+ readonly azimuth: number;175+ readonly elevation: number;176+ }177+): Camera => {178+ const angles = trig(box.azimuth, box.elevation);179+ const probe: Camera = { ...angles, k: 1, ox: 0, oy: 0 };180+ const flat = points.map((point) => at(point, probe));181+ const xs = flat.map(([x]) => x);182+ const ys = flat.map(([, y]) => y);183+ const left = Math.min(...xs);184+ const right = Math.max(...xs);185+ const up = Math.min(...ys);186+ const down = Math.max(...ys);187+188+ const scale = Math.min(189+ (box.width - box.pad * 2) / (right - left),190+ (box.height - box.pad * 2) / (down - up)191+ );192+193+ return {194+ ...angles,195+ k: scale,196+ ox: box.width / 2 - ((left + right) / 2) * scale,197+ oy: box.height / 2 - ((up + down) / 2) * scale,198+ };199+};200+201+/** The screen scale of one world unit, for line widths and dot sizes. */202+export const unitScale = (camera: Camera) => camera.k / UNIT;203+204+const tenth = (value: number) => {205+ const text = (Math.round(value * 10) / 10).toFixed(1).replace(/\.0$/u, "");206+207+ return text === "-0" ? "0" : text;208+};209+210+export const pathOf = (points: readonly Flat[], closed = false) =>211+ points.length === 0212+ ? ""213+ : `${points214+ .map(215+ ([x, y], index) => `${index === 0 ? "M" : "L"}${tenth(x)} ${tenth(y)}`216+ )217+ .join("")}${closed ? "Z" : ""}`;218+219+const signedArea = (points: readonly Flat[]) => {220+ let area = 0;221+222+ for (const [index, [ax, ay]] of points.entries()) {223+ const [bx, by] = points[(index + 1) % points.length] ?? [ax, ay];224+225+ area += ax * by - bx * ay;226+ }227+228+ return area / 2;229+};230+231+const counterClockwise = (points: readonly Flat[]) =>232+ signedArea(points) < 0 ? points.toReversed() : points;233+234+const turn = (o: Flat, a: Flat, b: Flat) =>235+ (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);236+237+/** Andrew's monotone chain. */238+export const hullOf = (points: readonly Flat[]): readonly Flat[] => {239+ const sorted = points.toSorted((a, b) => a[0] - b[0] || a[1] - b[1]);240+241+ if (sorted.length < 3) {242+ return sorted;243+ }244+245+ const chain = (list: readonly Flat[]) => {246+ const kept: Flat[] = [];247+248+ for (const point of list) {249+ while (250+ kept.length >= 2 &&251+ turn(kept.at(-2) ?? point, kept.at(-1) ?? point, point) <= 0252+ ) {253+ kept.pop();254+ }255+256+ kept.push(point);257+ }258+259+ return kept;260+ };261+262+ return [263+ ...chain(sorted).slice(0, -1),264+ ...chain(sorted.toReversed()).slice(0, -1),265+ ];266+};267+268+/** Runs of consecutive indices (closing round the ring) whose flag is `want`. */269+const runsOf = (flags: readonly boolean[], want: boolean) => {270+ const count = flags.length;271+272+ const start = flags.findIndex(273+ (flag, index) => flag !== flags[(index + count - 1) % count]274+ );275+276+ if (start === -1) {277+ return flags[0] === want278+ ? [Array.from({ length: count + 1 }, (_, index) => index % count)]279+ : [];280+ }281+282+ const runs: number[][] = [];283+ let run: number[] | undefined;284+285+ for (const step of Array.from({ length: count }, (_, index) => index)) {286+ const index = (start + step) % count;287+288+ if (flags[index] === want) {289+ run ??= [index];290+ run.push((index + 1) % count);291+ } else if (run !== undefined) {292+ runs.push(run);293+ run = undefined;294+ }295+ }296+297+ if (run !== undefined) {298+ runs.push(run);299+ }300+301+ return runs;302+};303+304+const toneOf = (normal: Point, camera: Camera) => {305+ const score = dot(unit(normal), light(camera));306+307+ return BANDS.filter((band) => score >= band).length;308+};309+310+const bucketed = (311+ faces: readonly { readonly tone: number; readonly d: string }[]312+) => {313+ const tones = [0, 1, 2, 3, 4].map((tone) =>314+ faces.flatMap((face) => (face.tone === tone ? [face.d] : [])).join("")315+ );316+317+ return {318+ shades: [319+ tones[0] ?? "",320+ tones[1] ?? "",321+ tones[2] ?? "",322+ tones[3] ?? "",323+ ] as const,324+ top: tones[4] ?? "",325+ };326+};327+328+/** A rounded rectangle as a ring of floor points, counter-clockwise. */329+export const roundedRing = (plan: Plan, steps = 8): readonly Flat[] => {330+ const radius = Math.max(0, Math.min(plan.r, plan.w / 2, plan.d / 2));331+ const count = radius > 0 ? steps : 0;332+333+ const corners = [334+ [plan.x + plan.w - radius, plan.y + radius, -90],335+ [plan.x + plan.w - radius, plan.y + plan.d - radius, 0],336+ [plan.x + radius, plan.y + plan.d - radius, 90],337+ [plan.x + radius, plan.y + radius, 180],338+ ] as const;339+340+ return corners.flatMap(([cx, cy, start]) =>341+ Array.from({ length: count + 1 }, (_, step) => {342+ const angle =343+ (start + (count === 0 ? 45 : (90 * step) / count)) * RADIANS;344+345+ return [346+ cx + radius * Math.cos(angle),347+ cy + radius * Math.sin(angle),348+ ] as const;349+ })350+ );351+};352+353+/** A circle as a ring of floor points. */354+export const circle = (355+ radius: number,356+ steps: number,357+ centre: Flat = [0, 0]358+): readonly Flat[] =>359+ Array.from({ length: steps }, (_, step) => {360+ const angle = (step / steps) * TAU;361+362+ return [363+ centre[0] + radius * Math.cos(angle),364+ centre[1] + radius * Math.sin(angle),365+ ] as const;366+ });367+368+export const insetPlan = (plan: Plan, by: number): Plan => ({369+ d: plan.d - by * 2,370+ r: Math.max(0, plan.r - by),371+ w: plan.w - by * 2,372+ x: plan.x + by,373+ y: plan.y + by,374+});375+376+/** Four floor points inset from a plan's corners, for feet and screws. */377+export const cornersOf = (plan: Plan, inset: number): readonly Flat[] => [378+ [plan.x + inset, plan.y + inset],379+ [plan.x + plan.w - inset, plan.y + inset],380+ [plan.x + inset, plan.y + plan.d - inset],381+ [plan.x + plan.w - inset, plan.y + plan.d - inset],382+];383+384+/** A plan's eight corners between two heights, for fitting the camera. */385+export const boxCorners = (plan: Plan, z0: number, z1: number) =>386+ [plan.x, plan.x + plan.w].flatMap((x) =>387+ [plan.y, plan.y + plan.d].flatMap((y) =>388+ [z0, z1].map((z): Point => [x, y, z])389+ )390+ );391+392+/**393+ * A floor outline stood straight up from `z` by `height`. The outline is394+ * split into the runs that face the viewer and those that don't, so the395+ * silhouette, the crease and the bevel each end where the faces turn away.396+ */397+export const extrude = (398+ ring: readonly Flat[],399+ z: number,400+ height: number,401+ camera: Camera,402+ bevelBy = 0403+): Solid => {404+ const count = ring.length;405+ const counter = signedArea(ring) > 0;406+ const toward = view(camera);407+408+ const normals = ring.map(([ax, ay], index): Flat => {409+ const [bx, by] = ring[(index + 1) % count] ?? [ax, ay];410+ const length = Math.hypot(bx - ax, by - ay) || 1;411+412+ return counter413+ ? [(by - ay) / length, -(bx - ax) / length]414+ : [-(by - ay) / length, (bx - ax) / length];415+ });416+417+ const facing = normals.map(418+ ([nx, ny]) => nx * toward[0] + ny * toward[1] > 1e-9419+ );420+421+ const top = ring.map(([x, y]) => at([x, y, z + height], camera));422+ const bottom = ring.map(([x, y]) => at([x, y, z], camera));423+424+ const pick = (list: readonly Flat[], run: readonly number[]) =>425+ run.map((index) => list[index] ?? ORIGIN);426+427+ const outline = [428+ ...runsOf(facing, false).map((run) => pathOf(pick(top, run))),429+ ...(height > 0430+ ? runsOf(facing, true).map((run) => pathOf(pick(bottom, run)))431+ : []),432+ ...(height > 0433+ ? ring.flatMap((_, index) =>434+ facing[(index + count - 1) % count] === facing[index]435+ ? []436+ : [pathOf([top[index] ?? ORIGIN, bottom[index] ?? ORIGIN])]437+ )438+ : []),439+ ].join("");440+441+ const crease = runsOf(facing, true)442+ .map((run) => pathOf(pick(top, run)))443+ .join("");444+445+ const faces =446+ height > 0447+ ? ring.flatMap((_, index) => {448+ if (facing[index] !== true) {449+ return [];450+ }451+452+ const next = (index + 1) % count;453+ const [nx, ny] = normals[index] ?? ORIGIN;454+455+ return [456+ {457+ d: pathOf(458+ counterClockwise([459+ top[index] ?? ORIGIN,460+ top[next] ?? ORIGIN,461+ bottom[next] ?? ORIGIN,462+ bottom[index] ?? ORIGIN,463+ ]),464+ true465+ ),466+ tone: Math.min(3, toneOf([nx, ny, 0], camera)),467+ },468+ ];469+ })470+ : [];471+472+ const { shades } = bucketed(faces);473+474+ const bevel =475+ bevelBy > 0476+ ? runsOf(facing, true)477+ .map((run) => {478+ const inset = run.slice(1, -1).map((index) => {479+ const [ax, ay] = normals[(index + count - 1) % count] ?? ORIGIN;480+ const [bx, by] = normals[index] ?? ORIGIN;481+ const length = Math.hypot(ax + bx, ay + by) || 1;482+ const [x, y] = ring[index] ?? ORIGIN;483+484+ return at(485+ [486+ x - ((ax + bx) / length) * bevelBy,487+ y - ((ay + by) / length) * bevelBy,488+ z + height,489+ ],490+ camera491+ );492+ });493+494+ return pathOf([495+ top[run[0] ?? 0] ?? ORIGIN,496+ ...inset,497+ top[run.at(-1) ?? 0] ?? ORIGIN,498+ ]);499+ })500+ .join("")501+ : "";502+503+ return {504+ bevel,505+ crease,506+ fill: pathOf(hullOf([...top, ...bottom]), true),507+ outline,508+ shades,509+ top: pathOf(counterClockwise(top), true),510+ };511+};512+513+/** A rounded box. */514+export const slab = (515+ plan: Plan,516+ z: number,517+ height: number,518+ camera: Camera,519+ options: { readonly steps?: number; readonly bevel?: number } = {}520+) =>521+ extrude(522+ roundedRing(plan, options.steps ?? 4),523+ z,524+ height,525+ camera,526+ options.bevel ?? 0527+ );528+529+/** A round post, puck, foot or knob standing on the floor. */530+export const post = (531+ centre: Flat,532+ radius: number,533+ z: number,534+ height: number,535+ camera: Camera,536+ steps = 28537+) => extrude(circle(radius, steps, centre), z, height, camera);538+539+/** A frame on axis `a` through `o`, with radial directions chosen for it. */540+export const frameAlong = (o: Point, a: Point): Frame => {541+ const axis = unit(a);542+ const helper: Point = Math.abs(axis[2]) > 0.9 ? [1, 0, 0] : [0, 0, 1];543+ const u = unit(cross(helper, axis));544+545+ return { a: axis, o, u, v: cross(axis, u) };546+};547+548+/** A point `s` along a frame's axis, at `x` and `y` in its radial plane. */549+export const inFrame = (frame: Frame, s: number, [x, y]: Flat): Point =>550+ add(551+ add(frame.o, times(frame.a, s)),552+ add(times(frame.u, x), times(frame.v, y))553+ );554+555+/**556+ * Any convex polygon in a frame's radial plane, extruded along its axis from557+ * `s0` to `s1`: rods, discs, bars and plates at any angle.558+ */559+export const prism = (560+ frame: Frame,561+ polygon: readonly Flat[],562+ s0: number,563+ s1: number,564+ camera: Camera565+): Solid => {566+ const toward = view(camera);567+ const ring = counterClockwise(polygon);568+ const count = ring.length;569+ const low = ring.map((point) => at(inFrame(frame, s0, point), camera));570+ const high = ring.map((point) => at(inFrame(frame, s1, point), camera));571+572+ const sides = ring.map((point, index) => {573+ const next = ring[(index + 1) % count] ?? point;574+575+ const normal = unit(576+ add(577+ times(frame.u, next[1] - point[1]),578+ times(frame.v, -(next[0] - point[0]))579+ )580+ );581+582+ return { normal, seen: dot(normal, toward) > VISIBLE };583+ });584+585+ const ends = [586+ { normal: times(frame.a, -1), points: low },587+ { normal: frame.a, points: high },588+ ].map((end) => ({ ...end, seen: dot(end.normal, toward) > VISIBLE }));589+590+ const faces = [591+ ...sides.flatMap(({ normal, seen }, index) => {592+ const next = (index + 1) % count;593+594+ return seen595+ ? [596+ {597+ d: pathOf(598+ [599+ low[index] ?? ORIGIN,600+ low[next] ?? ORIGIN,601+ high[next] ?? ORIGIN,602+ high[index] ?? ORIGIN,603+ ],604+ true605+ ),606+ tone: toneOf(normal, camera),607+ },608+ ]609+ : [];610+ }),611+ ...ends.flatMap((end) =>612+ end.seen613+ ? [{ d: pathOf(end.points, true), tone: toneOf(end.normal, camera) }]614+ : []615+ ),616+ ];617+618+ const sharp = ring.map((point, index) => {619+ const before = ring[(index + count - 1) % count] ?? point;620+ const after = ring[(index + 1) % count] ?? point;621+ const ax = point[0] - before[0];622+ const ay = point[1] - before[1];623+ const bx = after[0] - point[0];624+ const by = after[1] - point[1];625+626+ return (627+ (ax * bx + ay * by) / (Math.hypot(ax, ay) * Math.hypot(bx, by) || 1) <628+ Math.cos(0.35)629+ );630+ });631+632+ const crease = [633+ ...ring.flatMap((_, index) =>634+ sharp[index] === true &&635+ sides[index]?.seen === true &&636+ sides[(index + count - 1) % count]?.seen === true637+ ? [pathOf([low[index] ?? ORIGIN, high[index] ?? ORIGIN])]638+ : []639+ ),640+ ...ends.flatMap((end) =>641+ end.seen642+ ? ring.flatMap((_, index) =>643+ sides[index]?.seen === true644+ ? [645+ pathOf([646+ end.points[index] ?? ORIGIN,647+ end.points[(index + 1) % count] ?? ORIGIN,648+ ]),649+ ]650+ : []651+ )652+ : []653+ ),654+ ].join("");655+656+ const hull = pathOf(hullOf([...low, ...high]), true);657+658+ return { ...bucketed(faces), bevel: "", crease, fill: hull, outline: hull };659+};660+661+/** A round rod or disc along a frame's axis. */662+export const rod = (663+ frame: Frame,664+ s0: number,665+ s1: number,666+ radius: number,667+ camera: Camera,668+ steps = 32669+) => prism(frame, circle(radius, steps), s0, s1, camera);670+671+/**672+ * A convex body of revolution from a profile of `[s, r]` points along a673+ * frame's axis: a bell, a cone, the halves of a sand-glass. Its rings at674+ * interior points draw as creases on the side that faces the viewer.675+ */676+export const turned = (677+ frame: Frame,678+ profile: readonly Flat[],679+ camera: Camera,680+ steps = 32681+): Solid => {682+ const toward = view(camera);683+684+ const angles = Array.from(685+ { length: steps },686+ (_, index) => (index / steps) * TAU687+ );688+689+ const rings = profile.map(([s, r]) =>690+ angles.map((angle) =>691+ at(inFrame(frame, s, [r * Math.cos(angle), r * Math.sin(angle)]), camera)692+ )693+ );694+695+ const bands = profile.slice(0, -1).flatMap(([s0, r0], row) => {696+ const [s1, r1] = profile[row + 1] ?? [s0, r0];697+ const low = rings[row] ?? [];698+ const high = rings[row + 1] ?? [];699+700+ return angles.map((angle, index) => {701+ const middle = angle + Math.PI / steps;702+703+ const radial = add(704+ times(frame.u, Math.cos(middle)),705+ times(frame.v, Math.sin(middle))706+ );707+708+ const normal = unit(709+ add(times(radial, s1 - s0), times(frame.a, -(r1 - r0)))710+ );711+712+ const next = (index + 1) % steps;713+714+ return {715+ d: pathOf(716+ [717+ low[index] ?? ORIGIN,718+ low[next] ?? ORIGIN,719+ high[next] ?? ORIGIN,720+ high[index] ?? ORIGIN,721+ ],722+ true723+ ),724+ index,725+ normal,726+ row,727+ seen: dot(normal, toward) > VISIBLE && Math.abs(r0) + Math.abs(r1) > 0,728+ };729+ });730+ });731+732+ const caps = [733+ {734+ normal: times(frame.a, -1),735+ points: rings[0] ?? [],736+ radius: profile[0]?.[1] ?? 0,737+ },738+ {739+ normal: frame.a,740+ points: rings.at(-1) ?? [],741+ radius: profile.at(-1)?.[1] ?? 0,742+ },743+ ].filter((cap) => cap.radius > 0 && dot(cap.normal, toward) > VISIBLE);744+745+ const faces = [746+ ...bands.flatMap((band) =>747+ band.seen ? [{ d: band.d, tone: toneOf(band.normal, camera) }] : []748+ ),749+ ...caps.map((cap) => ({750+ d: pathOf(cap.points, true),751+ tone: toneOf(cap.normal, camera),752+ })),753+ ];754+755+ const crease = profile756+ .slice(1, -1)757+ .map((_, offset) => {758+ const row = offset + 1;759+ const points = rings[row] ?? [];760+761+ const seen = angles.map((_angle, index) =>762+ bands.some(763+ (band) =>764+ band.seen &&765+ band.index === index &&766+ (band.row === row || band.row === row - 1)767+ )768+ );769+770+ return runsOf(seen, true)771+ .map((run) => pathOf(run.map((index) => points[index] ?? ORIGIN)))772+ .join("");773+ })774+ .join("");775+776+ const hull = pathOf(hullOf(rings.flat()), true);777+778+ return { ...bucketed(faces), bevel: "", crease, fill: hull, outline: hull };779+};780+781+/** A polyline on a horizontal face at height `z`. */782+export const onTop = (783+ points: readonly Flat[],784+ z: number,785+ camera: Camera,786+ closed = false787+) =>788+ pathOf(789+ points.map(([x, y]) => at([x, y, z], camera)),790+ closed791+ );792+793+export const segment = (from: Point, to: Point, camera: Camera) =>794+ pathOf([at(from, camera), at(to, camera)]);795+796+export const polyline = (797+ points: readonly Point[],798+ camera: Camera,799+ closed = false800+) =>801+ pathOf(802+ points.map((point) => at(point, camera)),803+ closed804+ );805+806+export const planOutline = (plan: Plan, z: number, camera: Camera, steps = 4) =>807+ onTop(roundedRing(plan, steps), z, camera, true);808+809+export const ringOnTop = (810+ centre: Flat,811+ radius: number,812+ z: number,813+ camera: Camera,814+ steps = 24815+) => onTop(circle(radius, steps, centre), z, camera, true);816+817+/** The near half of a horizontal circle on a post's side: a seam or a band. */818+export const sideArc = (819+ centre: Flat,820+ radius: number,821+ z: number,822+ camera: Camera,823+ steps = 20824+) => {825+ const facing = Math.atan2(camera.sinA, camera.cosA);826+827+ return pathOf(828+ Array.from({ length: steps + 1 }, (_, step) => {829+ const angle = facing - Math.PI / 2 + (step / steps) * Math.PI;830+831+ return at(832+ [833+ centre[0] + radius * Math.cos(angle),834+ centre[1] + radius * Math.sin(angle),835+ z,836+ ],837+ camera838+ );839+ })840+ );841+};842+843+/**844+ * A seam round a box at height `z`: the near half of its plan, wrapping the845+ * corners and ending on the slab's own silhouette edges.846+ */847+export const sideSeam = (plan: Plan, z: number, camera: Camera, steps = 4) => {848+ const ring = roundedRing(plan, steps);849+ const count = ring.length;850+ const toward = view(camera);851+ const counter = signedArea(ring) > 0;852+853+ const facing = ring.map(([ax, ay], index) => {854+ const [bx, by] = ring[(index + 1) % count] ?? [ax, ay];855+ const [nx, ny] = counter ? [by - ay, -(bx - ax)] : [-(by - ay), bx - ax];856+857+ return nx * toward[0] + ny * toward[1] > 1e-9;858+ });859+860+ return runsOf(facing, true)861+ .map((run) =>862+ pathOf(863+ run.map((index) => {864+ const [x, y] = ring[index] ?? ORIGIN;865+866+ return at([x, y, z], camera);867+ })868+ )869+ )870+ .join("");871+};872+873+/** Vertical lines on the near half of a post: a knurl. */874+export const knurl = (875+ centre: Flat,876+ radius: number,877+ span: Flat,878+ count: number,879+ camera: Camera880+) =>881+ Array.from({ length: count }, (_, index) => (index / count) * TAU)882+ .filter(883+ (angle) =>884+ Math.cos(angle) * camera.cosA + Math.sin(angle) * camera.sinA > 0.15885+ )886+ .map((angle) => {887+ const x = centre[0] + radius * Math.cos(angle);888+ const y = centre[1] + radius * Math.sin(angle);889+890+ return segment([x, y, span[0] + 0.3], [x, y, span[1] - 0.3], camera);891+ })892+ .join("");893+894+/** The visible arc of a ring round a frame's axis, ending at the limbs. */895+export const arcOn = (896+ frame: Frame,897+ s: number,898+ radius: number,899+ camera: Camera,900+ steps = 40901+) => {902+ const toward = view(camera);903+904+ const seen = Array.from({ length: steps }, (_, index) => {905+ const angle = ((index + 0.5) / steps) * TAU;906+907+ return (908+ dot(909+ add(times(frame.u, Math.cos(angle)), times(frame.v, Math.sin(angle))),910+ toward911+ ) > 0.02912+ );913+ });914+915+ const point = (index: number) => {916+ const angle = (index / steps) * TAU;917+918+ return at(919+ inFrame(frame, s, [radius * Math.cos(angle), radius * Math.sin(angle)]),920+ camera921+ );922+ };923+924+ return runsOf(seen, true)925+ .map((run) => pathOf(run.map(point)))926+ .join("");927+};928+929+/** Axial lines on the side of a round part that faces the viewer: gear teeth, a knurl. */930+export const ribsOn = (931+ frame: Frame,932+ span: Flat,933+ radius: number,934+ count: number,935+ camera: Camera936+) => {937+ const toward = view(camera);938+939+ return Array.from({ length: count }, (_, index) => (index / count) * TAU)940+ .flatMap((angle) => {941+ const radial = add(942+ times(frame.u, Math.cos(angle)),943+ times(frame.v, Math.sin(angle))944+ );945+946+ if (dot(radial, toward) < 0.18) {947+ return [];948+ }949+950+ const point: Flat = [radius * Math.cos(angle), radius * Math.sin(angle)];951+952+ return [953+ pathOf([954+ at(inFrame(frame, span[0], point), camera),955+ at(inFrame(frame, span[1], point), camera),956+ ]),957+ ];958+ })959+ .join("");960+};961+962+/** A whole ring in a frame's radial plane: a face ring, a bore, a bezel. */963+export const ringOn = (964+ frame: Frame,965+ s: number,966+ radius: number,967+ camera: Camera,968+ steps = 32969+) =>970+ pathOf(971+ circle(radius, steps).map((point) => at(inFrame(frame, s, point), camera)),972+ true973+ );974+975+export interface Ticks {976+ readonly minor: string;977+ readonly major: string;978+}979+980+/** Ruler ticks along x on a top face, each grown from the line `edge` toward +y. */981+export const ticksAlongX = (982+ stations: readonly number[],983+ every: number,984+ edge: number,985+ z: number,986+ lengths: Flat,987+ camera: Camera988+): Ticks => {989+ const marks = stations.map((x, index) => {990+ const major = index % every === 0;991+992+ return {993+ d: onTop(994+ [995+ [x, edge],996+ [x, edge + (major ? lengths[1] : lengths[0])],997+ ],998+ z,999+ camera1000+ ),1001+ major,1002+ };1003+ });1004+1005+ return {1006+ major: marks.flatMap((mark) => (mark.major ? [mark.d] : [])).join(""),1007+ minor: marks.flatMap((mark) => (mark.major ? [] : [mark.d])).join(""),1008+ };1009+};1010+1011+/**1012+ * A coil spring round a vertical axis, split into the half behind the rod1013+ * and the half in front, so it paints back, rod, front.1014+ */1015+export const coil = (1016+ centre: Flat,1017+ radius: number,1018+ span: Flat,1019+ turns: number,1020+ camera: Camera1021+) => {1022+ const count = Math.max(1, Math.round(turns * 16));1023+ const toward = view(camera);1024+1025+ const samples = Array.from({ length: count + 1 }, (_, index) => {1026+ const share = index / count;1027+ const angle = share * turns * TAU;1028+ const nx = Math.cos(angle);1029+ const ny = Math.sin(angle);1030+1031+ return {1032+ flat: at(1033+ [1034+ centre[0] + radius * nx,1035+ centre[1] + radius * ny,1036+ span[0] + (span[1] - span[0]) * share,1037+ ],1038+ camera1039+ ),1040+ near: nx * toward[0] + ny * toward[1] > 0,1041+ };1042+ });1043+1044+ const pieces = samples.slice(1).map((sample, index) => ({1045+ d: pathOf([samples[index]?.flat ?? sample.flat, sample.flat]),1046+ near: sample.near && samples[index]?.near === true,1047+ }));1048+1049+ return {1050+ back: pieces.flatMap((piece) => (piece.near ? [] : [piece.d])).join(""),1051+ front: pieces.flatMap((piece) => (piece.near ? [piece.d] : [])).join(""),1052+ };1053+};1054+1055+const fine = (value: number) => Math.round(value * 100) / 100;1056+1057+/** A screen offset that moves a group built at rest by a world offset. */1058+export const translateBy = (camera: Camera, by: Point) => {1059+ const [x0, y0] = at([0, 0, 0], camera);1060+ const [x1, y1] = at(by, camera);1061+1062+ return `translate(${fine(x1 - x0)} ${fine(y1 - y0)})`;1063+};added:apps/web/src/features/landing/music-box/layout.ts+189 added
1+/**2+ * Where every part of the music box sits, in world units: x along the3+ * cylinder, y toward the viewer, z up. One camera serves the static art and4+ * every frame of the motion.5+ */6+import { boxCorners, fitCamera } from "./iso.ts";7+import type { Flat, Plan, Point } from "./iso.ts";8+9+export const WIDTH = 760;10+11+export const HEIGHT = 470;12+13+/** The bench everything stands on. */14+export const BASE: Plan = { d: 196, r: 8, w: 368, x: -200, y: -106 };15+16+export const BASE_H = 12;17+18+export const FOOT_H = 5;19+20+/** The music box's case, its front left open so the comb shows. */21+export const CASE: Plan = { d: 96, r: 2, w: 284, x: -172, y: -98 };22+23+export const CASE_FLOOR = 5;24+25+export const WALL = 6;26+27+export const WALL_TOP = 58;28+29+/** The brass bedplate the movement is built on. */30+export const BED: Plan = { d: 74, r: 2, w: 252, x: -160, y: -88 };31+32+export const BED_TOP = 9;33+34+/** The cylinder's axis, along x. */35+export const AXIS: Flat = [-50, 33];36+37+export const DRUM_R = 19;38+39+export const PIN_LENGTH = 2.2;40+41+export const TEETH = 40;42+43+export const PITCH = 4.35;44+45+export const FIRST_TOOTH = -120;46+47+export const TEETH_PER_SECTION = 4;48+49+export const toothX = (tooth: number) => FIRST_TOOTH + tooth * PITCH;50+51+/** Where the tune's surface runs, flange to flange. */52+export const DRUM_FROM = toothX(0) - 3.2;53+54+export const DRUM_TO = toothX(TEETH - 1) + 3.2;55+56+/** The rules track: a short drum of its own on the same arbor, whose pins drive the gate. */57+export const RULES_FROM = DRUM_TO + 5;58+59+export const RULES_TO = RULES_FROM + 11;60+61+export const ARBOR_FROM = -150;62+63+export const ARBOR_TO = 121;64+65+export const BRIDGES = [-140, 84] as const;66+67+export const BRIDGE_W = 7;68+69+/** The comb: teeth tips just clear of the pins, root on a cast block. */70+export const TOOTH_TIP = -29.8;71+72+export const TOOTH_ROOT = -16;73+74+export const COMB_BACK = -10;75+76+export const COMB_Z = 30;77+78+export const COMB_T = 1.4;79+80+export const TOOTH_W = 3.3;81+82+/** The section an ask names: its territory, four teeth wide. */83+export const SECTION = 9;84+85+export const sectionFrom = (section: number) =>86+ toothX(section * TEETH_PER_SECTION) - PITCH / 2;87+88+export const sectionTo = (section: number) =>89+ toothX(section * TEETH_PER_SECTION + TEETH_PER_SECTION - 1) + PITCH / 2;90+91+export const SECTION_MID = (sectionFrom(SECTION) + sectionTo(SECTION)) / 2;92+93+/** The front lip of the case, with the ruler of teeth and sections on top. */94+export const LIP: Plan = { d: 6, r: 1, w: 272, x: -166, y: -8 };95+96+export const LIP_TOP = 11;97+98+/** The gate: a rail along the front, one bridge per stage over it. */99+export const RAIL_BED: Plan = { d: 18, r: 2, w: 268, x: -192, y: 28 };100+101+export const RAIL_BED_TOP = 5;102+103+export const RAILS = [31, 41] as const;104+105+export const RAIL_TOP = 8;106+107+export const CARRIAGE_HALF = 15;108+109+export const CARRIAGE_TOP = 11;110+111+export const STRIP_Y: Flat = [34, 40];112+113+export const STRIP_T = 1.2;114+115+/** Where the carriage takes an answer in, and where the press takes it from. */116+export const INTAKE_X = -174;117+118+export const PRESS_X = SECTION_MID;119+120+/** The seven stages, cheapest first, each a bridge over the rail. */121+export const STATIONS = [-146, -120, -94, -68, -42, -16, 10] as const;122+123+export const BRIDGE_POSTS = [24, 48] as const;124+125+export const BRIDGE_TOP = 30;126+127+/** One tray per stage, in front of its bridge: every refused answer ends in exactly one. */128+export const TRAY_Y: Flat = [56, 78];129+130+export const TRAY_HALF = 10;131+132+export const TRAY_H = 10;133+134+/** The press: two arms that swing an answer over the comb onto the cylinder. */135+export const PIVOT: Flat = [-7, 33.8];136+137+export const ARM_XS = [SECTION_MID - 11.5, SECTION_MID + 11.5] as const;138+139+/** Where the arm's cradle holds the strip: on the carriage, and on the cylinder's top. */140+export const GRIP_LOW: Flat = [37, 12.2];141+142+export const ARM_R = Math.hypot(GRIP_LOW[0] - PIVOT[0], GRIP_LOW[1] - PIVOT[1]);143+144+export const ARM_DOWN = Math.atan2(145+ GRIP_LOW[1] - PIVOT[1],146+ GRIP_LOW[0] - PIVOT[0]147+);148+149+export const ARM_OVER = ARM_DOWN + Math.PI;150+151+export const ARM_PARK = (96 * Math.PI) / 180;152+153+/** The lid, hinged on the back wall and opened past upright. */154+export const HINGE: Flat = [CASE.y + WALL / 2, WALL_TOP];155+156+export const LID_OPEN = (112 * Math.PI) / 180;157+158+export const LID_DEPTH = 74;159+160+/** The ledger: a printer whose paper tape runs out toward the viewer. */161+export const PRINTER: Plan = { d: 26, r: 2, w: 36, x: 104, y: 12 };162+163+export const TAPE: Plan = { d: 44, r: 0, w: 14, x: 115, y: 38 };164+165+/** The rules follower and the rod it pushes to the gate's cam box. */166+export const FOLLOWER_X = (RULES_FROM + RULES_TO) / 2;167+168+export const CAM_BOX: Plan = { d: 18, r: 1.5, w: 16, x: 60, y: 28 };169+170+/** The crank, outside the right wall, on the arbor. */171+export const CRANK_X = ARBOR_TO - 2;172+173+export const CRANK_R = 15;174+175+const lidTop: Point = [176+ CASE.x,177+ HINGE[0] + Math.cos(LID_OPEN) * LID_DEPTH,178+ HINGE[1] + Math.sin(LID_OPEN) * LID_DEPTH,179+];180+181+export const CAMERA = fitCamera(182+ [183+ ...boxCorners(BASE, -BASE_H - FOOT_H, 0),184+ lidTop,185+ [CASE.x + CASE.w, lidTop[1], lidTop[2]],186+ [SECTION_MID, PIVOT[0], PIVOT[1] + ARM_R + 4],187+ ],188+ { azimuth: 58, elevation: 30, height: HEIGHT, pad: 22, width: WIDTH }189+);added:apps/web/src/features/landing/music-box/marks.ts+62 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162/** * What the drawing is made of: solids, lines and dots, each with its tone, * built as data so the server and the browser draw the same paths. */import type { Flat, Solid } from "./iso.ts";
/** Base and feet are `lo`, structure `mid`, the subject `hi`, grooves `faint`. */export type Tone = "hi" | "mid" | "lo" | "faint";
/** A state colour, always beside the readout's word for it. */export type State = "landed" | "refused" | "sealed" | "checking";
export interface SolidMark { readonly kind: "solid"; readonly solid: Solid; readonly tone: Tone; readonly crease?: Tone | "none"; /** The one accent: the part the reader should watch. */ readonly lit?: boolean; /** No side tones: a floor or an inlay thinner than a unit. */ readonly flat?: boolean; /** Glass: a pale pane the parts behind show through. */ readonly glass?: boolean; /** Seams and bands that sit under the silhouette. */ readonly inner?: readonly LineMark[];}
export interface LineMark { readonly kind: "line"; readonly d: string; readonly tone: Tone | "lit"; /** An end meant to stop on a bare face: rule lines that stand for print. */ readonly free?: boolean; readonly width?: number;}
export interface DotsMark { readonly kind: "dots"; readonly points: readonly Flat[]; readonly size: number; readonly tone: Tone;}
export type Mark = SolidMark | LineMark | DotsMark;
export const solid = ( paths: Solid, tone: Tone, options: Omit<SolidMark, "kind" | "solid" | "tone"> = {}): SolidMark => ({ kind: "solid", solid: paths, tone, ...options });
export const line = ( d: string, tone: Tone | "lit" = "lo", options: Omit<LineMark, "kind" | "d" | "tone"> = {}): LineMark => ({ d, kind: "line", tone, ...options });
export const dots = ( points: readonly Flat[], size = 0.5, tone: Tone = "mid"): DotsMark => ({ kind: "dots", points, size, tone });added:apps/web/src/features/landing/music-box/model.ts+387 added
1+/**2+ * The music box's story as a pure function of time: an ask is claimed, a3+ * first answer is refused at the shape stage, a second passes every stage and4+ * the press pins it onto the cylinder. Every part's place and every word in5+ * the readout come from `poseAt`, so the tour, a key press and the still6+ * picture under reduced motion all agree.7+ */8+import { StageName } from "@repo/protocol/domain/outcome";9+10+import {11+ ARM_DOWN,12+ ARM_OVER,13+ ARM_PARK,14+ INTAKE_X,15+ PRESS_X,16+ SECTION,17+ STATIONS,18+ TEETH_PER_SECTION,19+} from "./layout.ts";20+21+/** One cycle of the story, in seconds; three asks in turn make the whole loop. */22+export const CYCLE = 26;23+24+export const ASKS = [2, 0, 3] as const;25+26+export const LOOP = CYCLE * ASKS.length;27+28+/** The cylinder turns once in this many seconds while the tune plays. */29+const TURN = 9;30+31+/** The stage that refuses the first answer, as the landing page's transcript does. */32+const REFUSED_AT = 1;33+34+export type FlagState = "idle" | "checking" | "landed" | "refused" | "sealed";35+36+export interface Pose {37+ /** Which of the asks in turn this cycle shows. */38+ readonly ask: number;39+ /** The cylinder's angle, in radians. */40+ readonly drum: number;41+ /** The ask's tooth, counted from the bass end. */42+ readonly tooth: number;43+ /** How far the ask's corrected pin has come in, 0 to 1, and how green it still is. */44+ readonly fixed: number;45+ readonly fresh: number;46+ /** The claim's clip: 0 off the ruler, 1 on it. */47+ readonly claim: number;48+ readonly carriage: number;49+ /** How far the carriage's answer has come in at the intake, 0 to 1. */50+ readonly arrive: number;51+ /** Which answer the carriage holds: none, the first or the second. */52+ readonly round: 0 | 1 | 2;53+ /** The first answer's slide off the carriage into its tray, 0 to 1, and its fade at the reset. */54+ readonly drop: number;55+ readonly dropped: number;56+ readonly slip: number;57+ readonly template: number;58+ readonly feeler: number;59+ readonly testComb: number;60+ readonly bell: number;61+ readonly flags: readonly FlagState[];62+ readonly arm: number;63+ /** The arm holds the second answer from the grip until the press takes it in. */64+ readonly holding: boolean;65+ readonly entries: number;66+ readonly printing: number;67+ readonly ratchet: number;68+ readonly readout: string;69+ /** The phase in words, for the figure's accessible value. */70+ readonly phase: string;71+}72+73+const clamp = (value: number, low = 0, high = 1) =>74+ Math.min(high, Math.max(low, value));75+76+const smooth = (from: number, to: number, value: number) => {77+ const share = clamp((value - from) / (to - from));78+79+ return share * share * (3 - 2 * share);80+};81+82+const between = (from: number, to: number, value: number) =>83+ value >= from && value < to;84+85+/** A one-off envelope: up over `rise`, down over `fall`. */86+const pulse = (start: number, rise: number, fall: number, value: number) =>87+ value < start88+ ? 089+ : smooth(start, start + rise, value) *90+ (1 - smooth(start + rise, start + rise + fall, value));91+92+const ROUND_ONE = 2.6;93+94+const ROUND_TWO = 8.6;95+96+const STEP = 1.25;97+98+const DWELL = 0.75;99+100+/** When the second answer reaches each stage. */101+const arrival = (stage: number) => ROUND_TWO + 0.8 + stage * STEP;102+103+const AT_PRESS = arrival(StageName.literals.length - 1) + DWELL + 0.75;104+105+const GRIP = AT_PRESS + 0.7;106+107+const OVER = GRIP + 1.3;108+109+const PRESSED = OVER + 0.4;110+111+const PARKED = PRESSED + 1.4;112+113+const RESET = 24;114+115+/** The tune's speed: full, slowing to a stop for the press, then full again. */116+const speed = (t: number) =>117+ 1 -118+ smooth(AT_PRESS - 0.8, AT_PRESS, t) +119+ smooth(PARKED - 0.6, PARKED + 0.4, t);120+121+/** The cylinder's angle over one cycle, integrated once on a fine grid. */122+const ANGLES = (() => {123+ const step = 0.01;124+ const count = Math.ceil(CYCLE / step) + 1;125+ const omega = (Math.PI * 2) / TURN;126+127+ const angles = [0];128+129+ for (const index of Array.from({ length: count - 1 }, (_, at) => at + 1)) {130+ angles.push(131+ (angles[index - 1] ?? 0) + speed(index * step - step / 2) * omega * step132+ );133+ }134+135+ return angles;136+})();137+138+const angleIn = (t: number) => {139+ const at = t / 0.01;140+ const low = Math.floor(at);141+ const share = at - low;142+143+ return (144+ (ANGLES[low] ?? 0) * (1 - share) +145+ (ANGLES[low + 1] ?? ANGLES[low] ?? 0) * share146+ );147+};148+149+const PER_CYCLE = ANGLES.at(-1) ?? 0;150+151+/** The carriage's x: out from the intake, stage by stage, and home again. */152+const carriageAt = (t: number) => {153+ if (t < ROUND_ONE + 0.4) {154+ return INTAKE_X;155+ }156+157+ if (t < ROUND_TWO) {158+ const toFirst =159+ smooth(ROUND_ONE + 0.4, ROUND_ONE + 1.2, t) * (STATIONS[0] - INTAKE_X);160+161+ const toSecond =162+ smooth(ROUND_ONE + 1.7, ROUND_ONE + 2.4, t) *163+ (STATIONS[REFUSED_AT] - STATIONS[0]);164+165+ const home =166+ smooth(ROUND_ONE + 4.4, ROUND_ONE + 5.4, t) *167+ (INTAKE_X - STATIONS[REFUSED_AT]);168+169+ return INTAKE_X + toFirst + toSecond + home;170+ }171+172+ const legs = [...STATIONS, PRESS_X].map((x, index) => {173+ const from = index === 0 ? INTAKE_X : (STATIONS[index - 1] ?? INTAKE_X);174+ const start = index === 0 ? ROUND_TWO + 0.2 : arrival(index - 1) + DWELL;175+176+ return (177+ smooth(start, start + (index === 0 ? 0.6 : STEP - DWELL), t) * (x - from)178+ );179+ });180+181+ const home = smooth(PRESSED + 0.4, PRESSED + 1.9, t) * (INTAKE_X - PRESS_X);182+183+ return INTAKE_X + legs.reduce((sum, leg) => sum + leg, 0) + home;184+};185+186+const armAt = (t: number) => {187+ const down = smooth(AT_PRESS - 0.1, GRIP, t) * (ARM_DOWN - ARM_PARK);188+ const over = smooth(GRIP + 0.1, OVER, t) * (ARM_OVER - ARM_DOWN);189+ const press = pulse(OVER, 0.18, 0.22, t) * 0.035;190+ const home = smooth(PRESSED + 0.2, PARKED, t) * (ARM_PARK - ARM_OVER);191+192+ return ARM_PARK + down + over + press + home;193+};194+195+/** A stage's flag while the first answer is in the gate: one pass, then the refusal. */196+const firstRound = (index: number, t: number): FlagState => {197+ if (index === 0) {198+ if (t >= ROUND_ONE + 1.55) {199+ return "landed";200+ }201+202+ return t >= ROUND_ONE + 1.1 ? "checking" : "idle";203+ }204+205+ if (index === REFUSED_AT) {206+ if (t >= ROUND_ONE + 2.9) {207+ return "refused";208+ }209+210+ return t >= ROUND_ONE + 2.3 ? "checking" : "idle";211+ }212+213+ return "idle";214+};215+216+/** A stage's flag while the second answer passes through: checking, then passed. */217+const secondRound = (stage: StageName, index: number, t: number): FlagState => {218+ const reached = arrival(index);219+220+ if (t < reached) {221+ return "idle";222+ }223+224+ if (t < reached + DWELL - 0.15) {225+ return "checking";226+ }227+228+ return stage === "heldBack" ? "sealed" : "landed";229+};230+231+/** The flag of each stage, by how far each answer has come. */232+const flagsAt = (t: number): readonly FlagState[] =>233+ StageName.literals.map((stage, index) => {234+ if (t >= RESET + 0.6) {235+ return "idle";236+ }237+238+ return t < ROUND_TWO ? firstRound(index, t) : secondRound(stage, index, t);239+ });240+241+const roundAt = (t: number): Pose["round"] => {242+ if (t >= ROUND_ONE && t < ROUND_ONE + 4) {243+ return 1;244+ }245+246+ return between(ROUND_TWO, GRIP, t) ? 2 : 0;247+};248+249+const stageWord = (index: number) =>250+ ["Parse", "Shape", "Merge", "Cheap", "Checks", "Held-back", "Maintainer"][251+ index252+ ] ?? "";253+254+/** The readout's few words, and the same moment in a sentence. */255+interface Words {256+ readonly text: string;257+ readonly phase: string;258+}259+260+const readoutAt = (t: number, tooth: number): Words => {261+ const section = SECTION + 1;262+ const note = `tooth ${tooth + 1}`;263+264+ if (t < ROUND_ONE - 1.4) {265+ return {266+ phase: `An ask is open: ${note}, in section ${section}, plays sour.`,267+ text: `ask open · ${note} plays sour`,268+ };269+ }270+271+ if (t < ROUND_ONE) {272+ return {273+ phase: `Claimed: the clip is on section ${section}, its sand running.`,274+ text: `claimed · section ${section}`,275+ };276+ }277+278+ if (t < ROUND_ONE + 2.9) {279+ const stage = t < ROUND_ONE + 1.7 ? 0 : 1;280+281+ return {282+ phase: `Round 1 is at the ${stageWord(stage)} stage.`,283+ text: `round 1 · checking · ${stageWord(stage)}`,284+ };285+ }286+287+ if (t < ROUND_TWO) {288+ return {289+ phase:290+ "Round 1 is refused at the Shape stage: a pin outside its section, OutOfScope.",291+ text: "round 1 · refused · OutOfScope",292+ };293+ }294+295+ if (t < AT_PRESS) {296+ const stage = Math.max(297+ 0,298+ StageName.literals.findLastIndex((_, index) => t >= arrival(index))299+ );300+301+ const word = stageWord(stage);302+303+ return {304+ phase: `Round 2 is at the ${word} stage.`,305+ text: `round 2 · checking · ${word}`,306+ };307+ }308+309+ if (t < PRESSED) {310+ return {311+ phase: "Round 2 passed every stage; the press is pinning it.",312+ text: "round 2 · landing",313+ };314+ }315+316+ if (t < RESET) {317+ return {318+ phase: `Round 2 landed: ${note} plays true, and the tape printed its credit.`,319+ text: `landed · ${note} plays true`,320+ };321+ }322+323+ return { phase: "The next ask opens.", text: "next ask" };324+};325+326+/** Where the story stands at `time` seconds into the loop. */327+export const poseAt = (time: number): Pose => {328+ const looped = ((time % LOOP) + LOOP) % LOOP;329+ const cycle = Math.floor(looped / CYCLE);330+ const t = looped - cycle * CYCLE;331+ const tooth = SECTION * TEETH_PER_SECTION + (ASKS[cycle] ?? 0);332+ const words = readoutAt(t, tooth);333+ const fixed = smooth(PRESSED - 0.2, PRESSED + 0.2, t);334+335+ return {336+ arm: armAt(t),337+ arrive:338+ t >= ROUND_TWO339+ ? smooth(ROUND_TWO, ROUND_TWO + 0.35, t)340+ : smooth(ROUND_ONE, ROUND_ONE + 0.35, t),341+ ask: cycle,342+ bell: pulse(arrival(5) + 0.2, 0.05, 0.6, t),343+ carriage: carriageAt(t),344+ claim:345+ smooth(ROUND_ONE - 1.4, ROUND_ONE - 0.6, t) *346+ (1 - smooth(RESET, RESET + 0.8, t)),347+ drop: smooth(ROUND_ONE + 3.3, ROUND_ONE + 4, t),348+ dropped: 1 - smooth(RESET, RESET + 0.8, t),349+ drum: angleIn(t) + cycle * PER_CYCLE,350+ entries: cycle * 2 + (t >= PRESSED ? 2 : 0),351+ feeler:352+ pulse(arrival(3) + 0.1, 0.12, 0.3, t) +353+ pulse(arrival(3) + 0.42, 0.12, 0.2, t),354+ fixed,355+ flags: flagsAt(t),356+ fresh: fixed * (1 - smooth(RESET - 2, RESET, t)),357+ holding: between(GRIP, PRESSED + 0.25, t),358+ phase: words.phase,359+ printing: smooth(PRESSED, PRESSED + 0.6, t),360+ ratchet: cycle + smooth(PRESSED + 0.3, PRESSED + 0.45, t),361+ readout: words.text,362+ round: roundAt(t),363+ slip:364+ smooth(ROUND_ONE + 4, ROUND_ONE + 4.5, t) *365+ (1 - smooth(RESET, RESET + 0.6, t)),366+ template:367+ pulse(ROUND_ONE + 2.4, 0.35, 0.5, t) +368+ pulse(arrival(1) + 0.05, 0.3, 0.35, t),369+ testComb: pulse(arrival(4) + 0.15, 0.1, 0.5, t),370+ tooth,371+ };372+};373+374+/** The still picture: round 1 in its tray, round 2 landed, the tape printed. */375+export const REST = 22.6;376+377+/** The moments a key press steps between. */378+export const BEATS = [379+ 0.4,380+ 1.8,381+ ROUND_ONE + 1.4,382+ ROUND_ONE + 4.6,383+ arrival(1) + 0.3,384+ arrival(5) + 0.3,385+ OVER + 0.2,386+ REST,387+] as const;added:apps/web/src/features/landing/music-box/music-box.tsx+392 added
1+/**2+ * The landing's hero: the platform as a cylinder music box that only its own3+ * press can pin. The server draws the still picture (round 1 refused in its4+ * tray, round 2 landed); in the browser one loop plays the story through5+ * `poseAt`, writing transforms and paths on the parts it names, and never6+ * re-renders. It stops off screen, and under reduced motion it moves only7+ * when a key or a click asks it to, straight to the next moment.8+ */9+import { useEffect, useRef } from "react";10+import type { KeyboardEvent } from "react";11+12+import { Art } from "./art.tsx";13+import { repaint } from "./draw.tsx";14+import {15+ drumPins,16+ liveFrame,17+ rulesPins,18+ tapeEntries,19+ toothState,20+} from "./frame.ts";21+import { BEATS, CYCLE, REST, poseAt } from "./model.ts";22+import type { Pose } from "./model.ts";23+import {24+ armBack,25+ armFront,26+ armStrip,27+ crank,28+ governorFan,29+ ratchetTeeth,30+} from "./parts.ts";31+import { FIGURE, KEYS } from "./words.ts";32+33+const REST_POSE = poseAt(REST);34+35+/** How long after the reader's last key or click the tour plays on by itself. */36+const QUIET = 3.6;37+38+interface Parts {39+ readonly svg: SVGSVGElement;40+ readonly one: (name: string) => SVGGElement | null;41+ readonly teeth: readonly SVGGElement[];42+ readonly flags: readonly SVGGElement[];43+ readonly trayLayer: SVGGElement | null;44+ readonly readout: HTMLElement | null;45+}46+47+const set = (48+ element: Element | null,49+ name: string,50+ value: string | undefined51+) => {52+ if (element === null) {53+ return;54+ }55+56+ if (value === undefined) {57+ if (element.hasAttribute(name)) {58+ element.removeAttribute(name);59+ }60+61+ return;62+ }63+64+ if (element.getAttribute(name) !== value) {65+ element.setAttribute(name, value);66+ }67+};68+69+const paths = (group: Element | null, ds: readonly string[]) => {70+ for (const [index, path] of [71+ ...(group?.querySelectorAll("path") ?? []),72+ ].entries()) {73+ set(path, "d", ds[index] ?? "");74+ }75+};76+77+/** Writes one pose onto the drawing. */78+const paint = (parts: Parts, pose: Pose, last: Pose | undefined) => {79+ const frame = liveFrame(pose);80+ const pins = drumPins(pose);81+82+ paths(parts.one("pins"), pins.tune);83+ set(parts.one("sour"), "d", pins.ask);84+ set(parts.one("fixed"), "d", pins.fixed);85+ set(86+ parts.one("fixed"),87+ "data-state",88+ pose.fresh > 0.4 ? "landed" : undefined89+ );90+ paths(parts.one("rules"), rulesPins(pose.drum));91+ repaint(parts.one("fan"), governorFan(frame.fan));92+ repaint(parts.one("crank"), crank(pose.drum));93+ set(parts.one("ratchet"), "d", ratchetTeeth(frame.ratchet));94+95+ for (const [index, tooth] of parts.teeth.entries()) {96+ set(tooth, "transform", frame.teeth[index]);97+ set(tooth, "data-state", toothState(pose, index));98+ }99+100+ for (const [index, flag] of parts.flags.entries()) {101+ set(flag, "data-state", pose.flags[index]);102+ }103+104+ set(parts.one("claim"), "transform", frame.claim);105+ set(parts.one("claim"), "opacity", frame.claimOpacity.toFixed(3));106+ set(parts.one("flag"), "transform", frame.flag);107+ set(parts.one("carriage"), "transform", frame.carriage);108+ set(parts.one("strip"), "opacity", frame.stripOpacity.toFixed(3));109+110+ const stray = parts.one("stray");111+112+ if (stray !== null) {113+ const inTray = pose.drop > 0;114+115+ if (inTray !== (stray.parentElement === parts.trayLayer)) {116+ const home = inTray ? parts.trayLayer : parts.one("carriage-slot");117+118+ // oxlint-disable-next-line unicorn/prefer-dom-node-append -- the Worker's types merge HTMLRewriter's Element into the DOM's, so `append` there takes only text, streams and responses119+ home?.appendChild(stray);120+ }121+122+ set(stray, "data-fault", frame.fault ? "" : undefined);123+ set(stray, "transform", frame.stray);124+ set(stray, "opacity", frame.strayOpacity.toFixed(3));125+ }126+127+ set(parts.one("template"), "transform", frame.template);128+ set(parts.one("feeler"), "transform", frame.feeler);129+ set(parts.one("test-comb"), "transform", frame.testComb);130+ set(parts.one("bell"), "transform", frame.bell);131+ set(parts.one("bell"), "data-state", pose.bell > 0.05 ? "sealed" : undefined);132+ set(parts.one("slip"), "transform", frame.slip);133+ set(parts.one("slip"), "opacity", pose.slip.toFixed(3));134+135+ if (last?.arm !== pose.arm) {136+ repaint(parts.one("arm-back"), armBack(pose.arm));137+ repaint(parts.one("arm-strip"), armStrip(pose.arm));138+ repaint(parts.one("arm-front"), armFront(pose.arm));139+ }140+141+ set(parts.one("arm-strip"), "opacity", frame.heldOpacity.toFixed(3));142+ set(parts.one("entries"), "d", tapeEntries(pose));143+144+ if (parts.readout !== null && parts.readout.textContent !== pose.readout) {145+ parts.readout.textContent = pose.readout;146+ }147+};148+149+const partsOf = (stage: HTMLElement, svg: SVGSVGElement): Parts => ({150+ flags: [...svg.querySelectorAll<SVGGElement>("[data-flag]")],151+ one: (name) => svg.querySelector<SVGGElement>(`[data-part="${name}"]`),152+ readout:153+ stage.closest("figure")?.querySelector<HTMLElement>("[data-readout]") ??154+ null,155+ svg,156+ teeth: [...svg.querySelectorAll<SVGGElement>('[data-part="tooth"]')],157+ trayLayer: svg.querySelector<SVGGElement>('[data-part="tray-layer"]'),158+});159+160+/** The next moment worth stopping at, after `time`, or the one before it. */161+const beatFrom = (time: number, step: 1 | -1) => {162+ const start = Math.floor(time / CYCLE) * CYCLE;163+164+ const all = [-1, 0, 1].flatMap((cycle) =>165+ BEATS.map((beat) => start + cycle * CYCLE + beat)166+ );167+168+ return step === 1169+ ? (all.find((beat) => beat > time + 0.05) ?? time)170+ : (all.findLast((beat) => beat < time - 0.05) ?? time);171+};172+173+interface Clock {174+ time: number;175+ target: number;176+ touring: boolean;177+ quiet: number;178+}179+180+type Step = 1 | -1 | "first" | "rest";181+182+/** Arrows step between moments; Space and Enter press the button, which steps forward. */183+const KEY_STEPS = new Map<string, Step>([184+ ["ArrowDown", 1],185+ ["ArrowLeft", -1],186+ ["ArrowRight", 1],187+ ["ArrowUp", -1],188+ ["End", "rest"],189+ ["Home", "first"],190+]);191+192+/** Starts the loop on the drawing, and returns what stops it. */193+const start = (194+ element: HTMLElement,195+ svg: SVGSVGElement,196+ clock: Clock,197+ kick: { current: (() => void) | null }198+) => {199+ const parts = partsOf(element, svg);200+ const still = globalThis.matchMedia("(prefers-reduced-motion: reduce)");201+ let frame = 0;202+ let previous = 0;203+ let visible = false;204+ let last: Pose | undefined;205+206+ const tick = (now: number) => {207+ const dt =208+ previous === 0 ? 1 / 60 : Math.min((now - previous) / 1000, 1 / 30);209+210+ const calm = still.matches;211+212+ previous = now;213+ clock.quiet += dt;214+215+ if (!clock.touring && !calm && clock.quiet > QUIET) {216+ clock.touring = true;217+ }218+219+ if (clock.touring && !calm) {220+ clock.time += dt;221+ clock.target = clock.time;222+ } else {223+ clock.time = calm224+ ? clock.target225+ : clock.time + (clock.target - clock.time) * (1 - Math.exp(-dt / 0.3));226+ }227+228+ const pose = poseAt(clock.time);229+230+ paint(parts, pose, last);231+ last = pose;232+233+ const settled = calm && Math.abs(clock.target - clock.time) < 1e-3;234+235+ frame = visible && !settled ? globalThis.requestAnimationFrame(tick) : 0;236+ };237+238+ const run = () => {239+ if (frame === 0 && visible) {240+ previous = 0;241+ frame = globalThis.requestAnimationFrame(tick);242+ }243+ };244+245+ kick.current = run;246+ clock.touring = !still.matches;247+248+ const watcher = new IntersectionObserver(249+ (entries) => {250+ visible = entries.at(-1)?.isIntersecting ?? false;251+252+ if (visible) {253+ run();254+ }255+ },256+ { rootMargin: "120px 0px" }257+ );258+259+ watcher.observe(element);260+261+ return () => {262+ watcher.disconnect();263+ globalThis.cancelAnimationFrame(frame);264+ };265+};266+267+const useMusicBox = () => {268+ const stage = useRef<HTMLButtonElement>(null);269+ const phase = useRef<HTMLSpanElement>(null);270+271+ const clock = useRef<Clock>({272+ quiet: 0,273+ target: REST,274+ time: REST,275+ touring: true,276+ });277+278+ const kick = useRef<(() => void) | null>(null);279+280+ useEffect(() => {281+ const element = stage.current;282+ const svg = element?.querySelector("svg") ?? null;283+284+ return element === null || svg === null285+ ? undefined286+ : start(element, svg, clock.current, kick);287+ }, []);288+289+ const step = (direction: Step) => {290+ const state = clock.current;291+ const cycle = Math.floor(state.time / CYCLE) * CYCLE;292+293+ state.touring = false;294+ state.quiet = 0;295+296+ if (direction === "first") {297+ state.target = cycle + (BEATS[0] ?? 0);298+ } else if (direction === "rest") {299+ state.target = cycle + REST;300+ } else {301+ state.target = beatFrom(state.target, direction);302+ }303+304+ if (phase.current !== null) {305+ phase.current.textContent = poseAt(state.target).phase;306+ }307+308+ kick.current?.();309+ };310+311+ const onKeyDown = (event: KeyboardEvent<HTMLButtonElement>) => {312+ const direction = KEY_STEPS.get(event.key);313+314+ if (direction !== undefined) {315+ event.preventDefault();316+ step(direction);317+ }318+ };319+320+ return {321+ onClick: () => {322+ step(1);323+ },324+ onKeyDown,325+ phase,326+ stage,327+ };328+};329+330+const Swatch = ({ mark }: { readonly mark: string }) => (331+ <svg332+ aria-hidden="true"333+ className="mbx-swatch"334+ data-mark={mark}335+ viewBox="0 0 16 10"336+ >337+ <path d="M2 4.5 8 1.5 14 4.5 14 6 8 9 2 6Z" />338+ <path className="mbx-swatch-crease" d="M2 4.5 8 7.5 14 4.5" />339+ </svg>340+);341+342+/** Fig 1: the music box, its card, its live readout and the legend under it. */343+export const MusicBox = () => {344+ const { onClick, onKeyDown, phase, stage } = useMusicBox();345+346+ return (347+ <figure className="mbx flex flex-col gap-3" data-figure="music-box">348+ <div className="bg-card border-rule tablet:px-6 relative overflow-hidden rounded-md border px-3 pt-12 pb-14">349+ <div350+ aria-hidden="true"351+ className="text-label text-muted-foreground tablet:inset-x-5 pointer-events-none absolute inset-x-4 top-4 flex justify-between gap-4"352+ >353+ <span className="text-foreground">{FIGURE.fig}</span>354+ <span className="text-right">{FIGURE.title}</span>355+ </div>356+ <button357+ aria-label={FIGURE.label}358+ className="mbx-stage block w-full"359+ onClick={onClick}360+ onKeyDown={onKeyDown}361+ ref={stage}362+ type="button"363+ >364+ <Art pose={REST_POSE} />365+ </button>366+ <span aria-live="polite" className="sr-only" ref={phase} />367+ <div className="text-label text-muted-foreground tablet:inset-x-5 pointer-events-none absolute inset-x-4 bottom-4 flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">368+ <span aria-hidden="true">{FIGURE.hint}</span>369+ <span className="text-foreground tabular-nums" data-readout="">370+ {REST_POSE.readout}371+ </span>372+ </div>373+ </div>374+ <figcaption className="flex flex-col gap-3">375+ <dl className="tablet:grid-cols-2 columns:grid-cols-3 grid gap-x-8 gap-y-2.5">376+ {KEYS.map((key) => (377+ <div className="text-ui" data-key={key.word} key={key.word}>378+ <dt className="inline font-medium">379+ <Swatch mark={key.mark} />380+ {key.word}381+ </dt>{" "}382+ <dd className="text-muted-foreground inline">{key.part}</dd>383+ </div>384+ ))}385+ </dl>386+ <p className="text-ui text-muted-foreground max-w-(--measure)">387+ {FIGURE.caption}388+ </p>389+ </figcaption>390+ </figure>391+ );392+};added:apps/web/src/features/landing/music-box/parts.ts+1740 added
1+/**2+ * The music box's parts, built once as data. Static parts are whole lists of3+ * marks; a part that turns or changes shape is a function of its angle, which4+ * the art draws at rest and the motion calls every frame.5+ */6+import {7+ arcOn,8+ ribsOn,9+ at,10+ coil,11+ cornersOf,12+ frameAlong,13+ inFrame,14+ insetPlan,15+ knurl,16+ onTop,17+ planOutline,18+ polyline,19+ post,20+ prism,21+ ringOn,22+ ringOnTop,23+ rod,24+ segment,25+ sideSeam,26+ slab,27+ ticksAlongX,28+ turned,29+ view,30+ dot,31+ hullOf,32+ pathOf,33+ sub,34+} from "./iso.ts";35+import type { Flat, Frame, Plan, Point } from "./iso.ts";36+import {37+ ARBOR_FROM,38+ ARM_DOWN,39+ ARM_R,40+ ARM_XS,41+ AXIS,42+ BASE,43+ BASE_H,44+ BED,45+ BED_TOP,46+ BRIDGE_POSTS,47+ BRIDGE_TOP,48+ BRIDGE_W,49+ BRIDGES,50+ CAMERA,51+ CAM_BOX,52+ CARRIAGE_HALF,53+ CARRIAGE_TOP,54+ CASE,55+ CASE_FLOOR,56+ COMB_BACK,57+ COMB_T,58+ COMB_Z,59+ CRANK_R,60+ CRANK_X,61+ DRUM_FROM,62+ DRUM_R,63+ DRUM_TO,64+ FOLLOWER_X,65+ FOOT_H,66+ HINGE,67+ LID_DEPTH,68+ LID_OPEN,69+ LIP,70+ LIP_TOP,71+ PIN_LENGTH,72+ PIVOT,73+ PRINTER,74+ RAIL_BED,75+ RAIL_BED_TOP,76+ RAIL_TOP,77+ RAILS,78+ RULES_FROM,79+ RULES_TO,80+ SECTION,81+ SECTION_MID,82+ STATIONS,83+ STRIP_T,84+ STRIP_Y,85+ TAPE,86+ TEETH,87+ TEETH_PER_SECTION,88+ TOOTH_ROOT,89+ TOOTH_TIP,90+ TOOTH_W,91+ TRAY_H,92+ TRAY_HALF,93+ TRAY_Y,94+ WALL,95+ WALL_TOP,96+ sectionFrom,97+ sectionTo,98+ toothX,99+} from "./layout.ts";100+import { dots, line, solid } from "./marks.ts";101+import type { Mark, Tone } from "./marks.ts";102+103+const C = CAMERA;104+105+const CHEAP_X = STATIONS.at(3) ?? 0;106+107+const HELD_X = STATIONS.at(5) ?? 0;108+109+const HUMAN_X = STATIONS.at(6) ?? 0;110+111+const flat = (point: Point) => at(point, C);112+113+const X: Point = [1, 0, 0];114+115+const Y: Point = [0, 1, 0];116+117+const Z: Point = [0, 0, 1];118+119+/** The cylinder's frame: along x, angle 0 toward the viewer (+y), turning up. */120+export const DRUM_FRAME: Frame = { a: X, o: [0, AXIS[0], AXIS[1]], u: Y, v: Z };121+122+const screws = (points: readonly Point[], size = 0.5) =>123+ dots(points.map(flat), size, "mid");124+125+const box = (126+ from: Point,127+ to: Point,128+ tone: Tone,129+ options: { readonly r?: number; readonly bevel?: number } = {}130+) =>131+ solid(132+ slab(133+ {134+ d: to[1] - from[1],135+ r: options.r ?? 0.8,136+ w: to[0] - from[0],137+ x: from[0],138+ y: from[1],139+ },140+ from[2],141+ to[2] - from[2],142+ C,143+ { bevel: options.bevel ?? 0, steps: 3 }144+ ),145+ tone146+ );147+148+/** The bench: feet, a bevelled top with a groove, corner screws and a label plate. */149+/** A ruler along the bench's front edge, ticked every 4 units. */150+const RULER: Plan = {151+ d: 4.6,152+ r: 0.8,153+ w: 244,154+ x: -146,155+ y: BASE.y + BASE.d - 10.6,156+};157+158+const rulerTicks = ticksAlongX(159+ Array.from({ length: 60 }, (_, index) => RULER.x + 4 + index * 4),160+ 5,161+ RULER.y + 0.4,162+ 0.6,163+ [1.4, 2.8],164+ C165+);166+167+export const bench = (): readonly Mark[] => {168+ const feet = cornersOf(BASE, 24).toSorted(169+ (a, b) => a[0] * C.cosA + a[1] * C.sinA - (b[0] * C.cosA + b[1] * C.sinA)170+ );171+172+ const corner = cornersOf(BASE, 10);173+174+ const label: Plan = {175+ d: 14,176+ r: 1,177+ w: 34,178+ x: BASE.x + 14,179+ y: BASE.y + BASE.d - 24,180+ };181+182+ return [183+ ...feet.flatMap((foot) => [184+ solid(post(foot, 8, -BASE_H - FOOT_H, 1.6, C), "lo"),185+ solid(post(foot, 6.2, -BASE_H - FOOT_H + 1.6, FOOT_H - 1.6, C), "mid"),186+ ]),187+ solid(slab(BASE, -BASE_H, BASE_H, C, { bevel: 1.6, steps: 8 }), "mid", {188+ inner: [line(sideSeam(BASE, -BASE_H + 4, C, 8), "faint")],189+ }),190+ line(planOutline(insetPlan(BASE, 5), 0, C, 8), "lo"),191+ line(corner.map((point) => ringOnTop(point, 2.2, 0, C, 16)).join(""), "lo"),192+ screws(corner.map(([x, y]) => [x, y, 0])),193+ solid(slab(RULER, 0, 0.6, C, { steps: 2 }), "lo", { crease: "none" }),194+ line(rulerTicks.minor, "lo"),195+ line(rulerTicks.major, "mid"),196+ screws(197+ [198+ [RULER.x + 2, RULER.y + RULER.d / 2, 0.6],199+ [RULER.x + RULER.w - 2, RULER.y + RULER.d / 2, 0.6],200+ ],201+ 0.42202+ ),203+ solid(slab(label, 0, 0.8, C, { steps: 2 }), "lo", { crease: "none" }),204+ line(planOutline(insetPlan(label, 1.6), 0.8, C, 2), "faint"),205+ line(206+ onTop(207+ [208+ [label.x + 4, label.y + 4.5],209+ [label.x + 26, label.y + 4.5],210+ ],211+ 0.8,212+ C213+ ),214+ "lo",215+ { free: true }216+ ),217+ line(218+ onTop(219+ [220+ [label.x + 4, label.y + 7.5],221+ [label.x + 20, label.y + 7.5],222+ ],223+ 0.8,224+ C225+ ),226+ "lo",227+ { free: true }228+ ),229+ line(230+ onTop(231+ [232+ [label.x + 4, label.y + 10.5],233+ [label.x + 23, label.y + 10.5],234+ ],235+ 0.8,236+ C237+ ),238+ "lo",239+ { free: true }240+ ),241+ screws(242+ [243+ [label.x + 30.5, label.y + 3.5, 0.8],244+ [label.x + 30.5, label.y + 10.5, 0.8],245+ ],246+ 0.45247+ ),248+ ];249+};250+251+/** The lid's own frame: along its thickness, x across, its depth up and back. */252+const LID: Frame = {253+ a: [0, -Math.sin(LID_OPEN), Math.cos(LID_OPEN)],254+ o: [CASE.x, HINGE[0], HINGE[1]],255+ u: X,256+ v: [0, Math.cos(LID_OPEN), Math.sin(LID_OPEN)],257+};258+259+const LID_BAR = 7;260+261+/** Where the lid's glass turns frosted: the right of it holds a layer. */262+const FROST_FROM = 196;263+264+const rect = (265+ u0: number,266+ v0: number,267+ u1: number,268+ v1: number269+): readonly Flat[] => [270+ [u0, v0],271+ [u1, v0],272+ [u1, v1],273+ [u0, v1],274+];275+276+/** The glass lid, open: a frame, a clear pane, a frosted panel, hinges and a stay. */277+export const lid = (): readonly Mark[] => {278+ const width = CASE.w;279+ const thick = 3.6;280+281+ const bar = (u0: number, v0: number, u1: number, v1: number) =>282+ solid(prism(LID, rect(u0, v0, u1, v1), -thick, 0, C), "mid");283+284+ const pane = (u0: number, u1: number) =>285+ prism(LID, rect(u0, LID_BAR, u1, LID_DEPTH - LID_BAR), -2.2, -1.4, C);286+287+ const frost = Array.from({ length: 10 }, (_row, row) =>288+ Array.from({ length: 11 }, (_column, column) =>289+ flat(290+ inFrame(LID, -1.4, [291+ FROST_FROM + 3.5 + column * 6.6 + (row % 2) * 3.3,292+ LID_BAR + 4 + row * 6,293+ ])294+ )295+ )296+ ).flat();297+298+ // Glints run bar to bar, their ends under the frame.299+ const glint = (u: number) =>300+ polyline(301+ [302+ inFrame(LID, -1.4, [u, LID_BAR - 1]),303+ inFrame(LID, -1.4, [304+ u + (LID_DEPTH - LID_BAR * 2 + 2) * 0.45,305+ LID_DEPTH - LID_BAR + 1,306+ ]),307+ ],308+ C309+ );310+311+ return [312+ solid(pane(LID_BAR, FROST_FROM), "faint", { crease: "none", glass: true }),313+ solid(pane(FROST_FROM, width - LID_BAR), "faint", {314+ crease: "none",315+ glass: true,316+ }),317+ dots(frost, 0.42, "lo"),318+ line(glint(40), "faint"),319+ line(glint(52), "faint"),320+ bar(0, 0, width, LID_BAR),321+ bar(0, LID_DEPTH - LID_BAR, width, LID_DEPTH),322+ bar(0, LID_BAR, LID_BAR, LID_DEPTH - LID_BAR),323+ bar(width - LID_BAR, LID_BAR, width, LID_DEPTH - LID_BAR),324+ bar(FROST_FROM - 1.5, LID_BAR, FROST_FROM + 1.5, LID_DEPTH - LID_BAR),325+ screws(326+ [327+ inFrame(LID, 0, [3.5, 3.5]),328+ inFrame(LID, 0, [width - 3.5, 3.5]),329+ inFrame(LID, 0, [3.5, LID_DEPTH - 3.5]),330+ inFrame(LID, 0, [width - 3.5, LID_DEPTH - 3.5]),331+ ],332+ 0.45333+ ),334+ ];335+};336+337+const knuckle = (x: number) =>338+ solid(339+ rod(frameAlong([0, HINGE[0], HINGE[1] + 0.4], X), x, x + 14, 2.2, C, 18),340+ "mid"341+ );342+343+/** The hinges between lid and back wall, and the stay that holds the lid open. */344+export const hinges = (): readonly Mark[] => {345+ const low: Point = [CASE.x + WALL + 1.2, CASE.y + 44, WALL_TOP - 6];346+ const high = inFrame(LID, 0.6, [WALL + 1.2, 38]);347+ const stay = frameAlong(low, sub(high, low));348+ const length = Math.hypot(...sub(high, low));349+350+ return [351+ knuckle(CASE.x + 30),352+ knuckle(CASE.x + CASE.w - 44),353+ solid(rod(stay, 0, length, 0.8, C, 10), "mid", { crease: "none" }),354+ screws([low, high], 0.55),355+ ];356+};357+358+/** The tune card pinned inside the back wall, as every cylinder box has one: printed lines. */359+const tuneCard = (): readonly Mark[] => {360+ const face = CASE.y + WALL + 0.4;361+ const from = CASE.x + WALL + 8;362+ const to = from + 26;363+364+ const rule = (z: number, length: number) =>365+ line(366+ polyline(367+ [368+ [from + 3, face, z],369+ [from + 3 + length, face, z],370+ ],371+ C372+ ),373+ "lo",374+ { free: true }375+ );376+377+ return [378+ box([from, CASE.y + WALL, 22], [to, face, 50], "hi"),379+ rule(45.5, 16),380+ rule(41.5, 20),381+ rule(38, 13),382+ rule(34.5, 19),383+ rule(31, 9),384+ rule(27.5, 17),385+ screws(386+ [387+ [from + 2, face, 48],388+ [to - 2, face, 48],389+ ],390+ 0.45391+ ),392+ ];393+};394+395+/** The case behind the movement: floor, back wall, far end wall, bedplate. */396+export const caseBack = (): readonly Mark[] => {397+ const floor = CASE;398+ const back: Plan = { d: WALL, r: 1, w: CASE.w, x: CASE.x, y: CASE.y };399+400+ const end: Plan = {401+ d: CASE.d - WALL,402+ r: 1,403+ w: WALL,404+ x: CASE.x,405+ y: CASE.y + WALL,406+ };407+408+ const bedScrews = cornersOf(BED, 5);409+410+ return [411+ solid(slab(floor, 0, CASE_FLOOR, C, { bevel: 0.6, steps: 3 }), "mid"),412+ solid(413+ slab(back, CASE_FLOOR, WALL_TOP - CASE_FLOOR, C, {414+ bevel: 0.6,415+ steps: 3,416+ }),417+ "mid",418+ {419+ inner: [line(sideSeam(back, WALL_TOP - 9, C, 3), "faint")],420+ }421+ ),422+ solid(423+ slab(end, CASE_FLOOR, WALL_TOP - CASE_FLOOR, C, { bevel: 0.6, steps: 3 }),424+ "mid",425+ {426+ inner: [line(sideSeam(end, WALL_TOP - 9, C, 3), "faint")],427+ }428+ ),429+ line(430+ polyline(431+ [432+ [CASE.x + WALL, CASE.y + WALL + 6, CASE_FLOOR + 7],433+ [CASE.x + WALL, CASE.y + CASE.d - 6, CASE_FLOOR + 7],434+ [CASE.x + WALL, CASE.y + CASE.d - 6, WALL_TOP - 14],435+ [CASE.x + WALL, CASE.y + WALL + 6, WALL_TOP - 14],436+ ],437+ C,438+ true439+ ),440+ "lo"441+ ),442+ ...tuneCard(),443+ solid(444+ slab(BED, CASE_FLOOR, BED_TOP - CASE_FLOOR, C, { bevel: 0.6, steps: 3 }),445+ "lo"446+ ),447+ line(planOutline(insetPlan(BED, 2.4), BED_TOP, C, 3), "faint"),448+ screws(bedScrews.map(([x, y]) => [x, y, BED_TOP])),449+ ];450+};451+452+const TOOTH_ANGLE = Math.atan2(COMB_Z + COMB_T - AXIS[1], TOOTH_TIP - AXIS[0]);453+454+/** A pin's place on the cylinder, by its tooth and its angle. */455+export interface Pin {456+ readonly x: number;457+ readonly angle: number;458+}459+460+/** A tune that never changes between server and browser: a fixed hash, no randomness. */461+const hash = (seed: number) => {462+ const mixed = Math.sin(seed * 12.9898 + 78.233) * 43_758.5453;463+464+ return mixed - Math.floor(mixed);465+};466+467+/** The tune: two to five pins per tooth, spaced round the cylinder. */468+export const TUNE: readonly Pin[] = Array.from(469+ { length: TEETH },470+ (_, tooth) => {471+ const count = 2 + Math.floor(hash(tooth + 1) * 4);472+473+ return Array.from({ length: count }, (_pin, index) => ({474+ angle:475+ ((index + hash(tooth * 7 + index * 3 + 2) * 0.6) / count) * Math.PI * 2,476+ x: toothX(tooth),477+ }));478+ }479+).flat();480+481+/** The rules track's pins: a short fixed program that drives the gate's cams. */482+export const RULES: readonly Pin[] = Array.from({ length: 12 }, (_, index) => ({483+ angle: (index / 12) * Math.PI * 2 + (index % 3) * 0.08,484+ x: RULES_FROM + 3 + (index % 2) * 5,485+}));486+487+/** A pin's base and tip on screen at the cylinder's angle, and how squarely it faces the viewer. */488+export const pinAt = (pin: Pin, turnAngle: number) => {489+ const angle = pin.angle + turnAngle;490+ const radial: Point = [0, Math.cos(angle), Math.sin(angle)];491+492+ const base: Point = [493+ pin.x,494+ AXIS[0] + radial[1] * DRUM_R,495+ AXIS[1] + radial[2] * DRUM_R,496+ ];497+498+ return {499+ base: flat(base),500+ facing: dot(radial, view(C)),501+ tip: flat([502+ pin.x,503+ base[1] + radial[1] * PIN_LENGTH,504+ base[2] + radial[2] * PIN_LENGTH,505+ ]),506+ };507+};508+509+/** How far a tooth's tip is lifted when a pin has just passed it, by the pin's angle past the tip. */510+export const pluck = (past: number) => {511+ const wrapped = Math.atan2(Math.sin(past), Math.cos(past));512+513+ if (wrapped < -0.14 || wrapped > 1.2) {514+ return 0;515+ }516+517+ return wrapped <= 0518+ ? ((wrapped + 0.14) / 0.14) * 0.9519+ : 0.9 * Math.exp(-wrapped / 0.18) * Math.cos(wrapped * 70);520+};521+522+export const pinPast = (pin: Pin, turnAngle: number) =>523+ pin.angle + turnAngle - TOOTH_ANGLE;524+525+/** A standard that carries the arbor: a slab with a bearing boss. */526+const bridge = (x: number): readonly Mark[] => {527+ const plan: Plan = { d: 22, r: 1.5, w: BRIDGE_W, x, y: AXIS[0] - 11 };528+529+ return [530+ solid(531+ slab(plan, BED_TOP, AXIS[1] + 6 - BED_TOP, C, { bevel: 0.5, steps: 3 }),532+ "mid"533+ ),534+ solid(rod(DRUM_FRAME, x - 1, x + BRIDGE_W + 1, 6, C, 32), "mid"),535+ line(ringOn(DRUM_FRAME, x + BRIDGE_W + 1, 3.6, C, 24), "lo"),536+ screws(537+ [538+ [x + BRIDGE_W / 2, plan.y + 3, AXIS[1] + 6],539+ [x + BRIDGE_W / 2, plan.y + plan.d - 3, AXIS[1] + 6],540+ ],541+ 0.42542+ ),543+ ];544+};545+546+/** The far side of the movement: governor, gear, arbor, left bridge and flange. */547+export const movementBack = (): readonly Mark[] => {548+ const governor: Flat = [BRIDGES[0] - 12, AXIS[0] - 14];549+ const bridgeLeft = bridge(BRIDGES[0]);550+551+ return [552+ solid(post(governor, 4.5, BED_TOP, 3, C, 20), "mid"),553+ solid(post(governor, 1.3, BED_TOP + 3, 32, C, 12), "mid", {554+ crease: "none",555+ }),556+ solid(post(governor, 2.6, BED_TOP + 12, 9, C, 18), "mid"),557+ line(knurl(governor, 2.6, [BED_TOP + 12, BED_TOP + 21], 14, C), "lo"),558+ solid(rod(DRUM_FRAME, ARBOR_FROM, BRIDGES[0], 2.4, C, 20), "mid"),559+ solid(rod(DRUM_FRAME, ARBOR_FROM + 2, ARBOR_FROM + 6, 9, C, 40), "mid", {560+ inner: [561+ line(562+ ribsOn(DRUM_FRAME, [ARBOR_FROM + 2.3, ARBOR_FROM + 5.7], 9, 36, C),563+ "lo"564+ ),565+ ],566+ }),567+ ...bridgeLeft,568+ solid(rod(DRUM_FRAME, BRIDGES[0] + BRIDGE_W, DRUM_FROM, 2.4, C, 20), "mid"),569+ solid(rod(DRUM_FRAME, DRUM_FROM - 2, DRUM_FROM, DRUM_R + 2, C, 64), "mid"),570+ ];571+};572+573+/** The governor's fan, turning fast while the tune plays. */574+export const governorFan = (angle: number): readonly Mark[] => {575+ const centre: Point = [BRIDGES[0] - 12, AXIS[0] - 14, BED_TOP + 33];576+ const across: Point = [Math.cos(angle), Math.sin(angle), 0];577+578+ const vane: Frame = {579+ a: across,580+ o: centre,581+ u: [-Math.sin(angle), Math.cos(angle), 0],582+ v: Z,583+ };584+585+ return [586+ solid(prism(vane, rect(-0.35, -3, 0.35, 3), -9, -1.5, C), "mid"),587+ solid(prism(vane, rect(-0.35, -3, 0.35, 3), 1.5, 9, C), "mid"),588+ solid(589+ post([centre[0], centre[1]], 1.7, centre[2] - 3.4, 6.8, C, 14),590+ "mid"591+ ),592+ ];593+};594+595+const sectionSeams = () =>596+ Array.from({ length: TEETH / TEETH_PER_SECTION - 1 }, (_, index) =>597+ arcOn(DRUM_FRAME, sectionFrom(index + 1), DRUM_R, C)598+ ).join("");599+600+/** The cylinder itself, seamed at every section's edge. */601+export const drum = (): readonly Mark[] => [602+ solid(rod(DRUM_FRAME, DRUM_FROM, DRUM_TO, DRUM_R, C, 72), "hi", {603+ inner: [line(sectionSeams(), "faint")],604+ }),605+];606+607+/** The near side of the movement: flange, rules track, right bridge, ratchet. */608+export const movementFront = (): readonly Mark[] => [609+ solid(rod(DRUM_FRAME, DRUM_TO, DRUM_TO + 2, DRUM_R + 2, C, 64), "mid", {610+ inner: [line(ringOn(DRUM_FRAME, DRUM_TO + 2, DRUM_R - 4, C, 48), "faint")],611+ }),612+ solid(rod(DRUM_FRAME, DRUM_TO + 2, RULES_FROM - 1, 2.4, C, 20), "mid"),613+ solid(614+ rod(DRUM_FRAME, RULES_FROM - 1, RULES_FROM, DRUM_R + 1.5, C, 56),615+ "mid"616+ ),617+];618+619+export const rulesTrack = (): readonly Mark[] => [620+ solid(rod(DRUM_FRAME, RULES_FROM, RULES_TO, DRUM_R, C, 64), "hi"),621+];622+623+export const movementEnd = (): readonly Mark[] => [624+ solid(rod(DRUM_FRAME, RULES_TO, RULES_TO + 1, DRUM_R + 1.5, C, 56), "mid"),625+ solid(rod(DRUM_FRAME, RULES_TO + 1, BRIDGES[1], 2.4, C, 20), "mid"),626+ ...bridge(BRIDGES[1]),627+ solid(628+ rod(629+ DRUM_FRAME,630+ BRIDGES[1] + BRIDGE_W + 1,631+ BRIDGES[1] + BRIDGE_W + 4,632+ 14,633+ C,634+ 56635+ ),636+ "mid"637+ ),638+];639+640+const RATCHET_S = BRIDGES[1] + BRIDGE_W + 4;641+642+const RATCHET_TEETH = 18;643+644+/** The ratchet's saw teeth on its face, at its angle: a landing clicks it one tooth down. */645+export const ratchetTeeth = (angle: number) =>646+ polyline(647+ Array.from({ length: RATCHET_TEETH * 2 + 1 }, (_, index) => {648+ const tooth = Math.floor(index / 2);649+650+ const a =651+ angle + (tooth / RATCHET_TEETH) * Math.PI * 2 + (index % 2) * 0.02;652+653+ const r = index % 2 === 0 ? 12.6 : 9.8;654+655+ return inFrame(DRUM_FRAME, RATCHET_S, [r * Math.cos(a), r * Math.sin(a)]);656+ }),657+ C658+ );659+660+/** The pawl that holds the ratchet, and its click spring. */661+export const pawl = (): readonly Mark[] => {662+ const pivot: Point = [RATCHET_S + 1.2, AXIS[0] + 10, AXIS[1] + 18];663+ const frame = frameAlong([RATCHET_S, pivot[1], pivot[2]], X);664+665+ return [666+ solid(667+ post(668+ [RATCHET_S + 1.5, AXIS[0] + 10],669+ 1.6,670+ BED_TOP,671+ pivot[2] - BED_TOP,672+ C,673+ 12674+ ),675+ "mid",676+ {677+ crease: "none",678+ }679+ ),680+ solid(681+ prism(682+ frame,683+ [684+ [-2.2, -1.6],685+ [2.2, -1.6],686+ [0.6, -7.4],687+ [-1, -6.8],688+ ],689+ 0,690+ 2.4,691+ C692+ ),693+ "mid"694+ ),695+ solid(rod(frame, 2.4, 3.2, 1.2, C, 12), "mid"),696+ ];697+};698+699+/** The comb's cast block and the lead weights under its bass teeth. */700+export const combBlock = (): readonly Mark[] => {701+ const from = toothX(0) - 3;702+ const to = toothX(TEETH - 1) + 3;703+704+ const block: Plan = {705+ d: COMB_BACK - (TOOTH_ROOT - 2),706+ r: 1,707+ w: to - from,708+ x: from,709+ y: TOOTH_ROOT - 2,710+ };711+712+ return [713+ solid(714+ slab(block, BED_TOP, COMB_Z - BED_TOP, C, { bevel: 0.5, steps: 3 }),715+ "mid",716+ {717+ inner: [line(sideSeam(block, COMB_Z - 5, C, 3), "faint")],718+ }719+ ),720+ box([from + 10, COMB_BACK, 13], [from + 34, COMB_BACK + 0.5, 21.5], "hi"),721+ line(722+ polyline(723+ [724+ [from + 13, COMB_BACK + 0.5, 19],725+ [from + 29, COMB_BACK + 0.5, 19],726+ ],727+ C728+ ),729+ "lo",730+ { free: true }731+ ),732+ line(733+ polyline(734+ [735+ [from + 13, COMB_BACK + 0.5, 16.5],736+ [from + 24, COMB_BACK + 0.5, 16.5],737+ ],738+ C739+ ),740+ "lo",741+ { free: true }742+ ),743+ screws(744+ [745+ [from + 12, COMB_BACK + 0.5, 21],746+ [from + 32, COMB_BACK + 0.5, 21],747+ ...Array.from(748+ { length: TEETH / TEETH_PER_SECTION },749+ (_section, section): Point => [750+ (sectionFrom(section) + sectionTo(section)) / 2,751+ COMB_BACK,752+ COMB_Z - 2.5,753+ ]754+ ),755+ ],756+ 0.45757+ ),758+ ...Array.from({ length: 8 }, (_, tooth) =>759+ box(760+ [761+ toothX(tooth) - TOOTH_W / 2 + 0.2,762+ TOOTH_TIP + 1.5,763+ COMB_Z - 3.2 + tooth * 0.2,764+ ],765+ [toothX(tooth) + TOOTH_W / 2 - 0.2, TOOTH_TIP + 6.5, COMB_Z],766+ "lo"767+ )768+ ),769+ ];770+};771+772+/** One tooth of the comb, built at rest; the motion lifts its group when a pin plucks it. */773+export const tooth = (index: number) =>774+ slab(775+ {776+ d: TOOTH_ROOT - TOOTH_TIP,777+ r: 0.5,778+ w: TOOTH_W,779+ x: toothX(index) - TOOTH_W / 2,780+ y: TOOTH_TIP,781+ },782+ COMB_Z,783+ COMB_T,784+ C,785+ { steps: 2 }786+ );787+788+/** The comb's root plate over the block, screwed down once a section. */789+export const combRoot = (): readonly Mark[] => {790+ const from = toothX(0) - 3;791+ const to = toothX(TEETH - 1) + 3;792+793+ const root: Plan = {794+ d: COMB_BACK - TOOTH_ROOT,795+ r: 0.8,796+ w: to - from,797+ x: from,798+ y: TOOTH_ROOT,799+ };800+801+ return [802+ solid(slab(root, COMB_Z, COMB_T, C, { bevel: 0.4, steps: 2 }), "hi", {803+ crease: "lo",804+ }),805+ screws(806+ Array.from({ length: TEETH / TEETH_PER_SECTION }, (_, section): Point => [807+ (sectionFrom(section) + sectionTo(section)) / 2,808+ (TOOTH_ROOT + COMB_BACK) / 2,809+ COMB_Z + COMB_T,810+ ]),811+ 0.55812+ ),813+ ];814+};815+816+/** The rules follower: a roller on the rules track and the lever it rocks. */817+export const follower = (): readonly Mark[] => {818+ const x = FOLLOWER_X;819+820+ return [821+ box([x - 4, -22, CASE_FLOOR], [x + 4, -12, BED_TOP + 3], "mid"),822+ solid(823+ rod(frameAlong([x - 3.5, -17, BED_TOP + 3], X), 0, 7, 2, C, 16),824+ "mid"825+ ),826+ solid(827+ prism(828+ frameAlong([x - 1.2, 0, 0], X),829+ [830+ [-17.4, BED_TOP + 2],831+ [-15.8, BED_TOP + 4],832+ [AXIS[0] + DRUM_R + 4.4, AXIS[1] - 1.8],833+ [AXIS[0] + DRUM_R + 2.2, AXIS[1] - 3.2],834+ ],835+ 0,836+ 2.4,837+ C838+ ),839+ "mid"840+ ),841+ solid(842+ rod(843+ frameAlong([x - 2, AXIS[0] + DRUM_R + 3, AXIS[1] - 2.2], X),844+ 0,845+ 4,846+ 2.6,847+ C,848+ 20849+ ),850+ "mid"851+ ),852+ solid(853+ prism(854+ frameAlong([x - 1, 0, 0], X),855+ [856+ [-17, BED_TOP + 3],857+ [-15.6, BED_TOP + 2],858+ [-9, 14.6],859+ [-10.4, 15.6],860+ ],861+ 0,862+ 2,863+ C864+ ),865+ "mid"866+ ),867+ ];868+};869+870+/** The front lip, its ruler of teeth and sections, the pillars of the press. */871+export const lipAndRuler = (): readonly Mark[] => {872+ const strip: Plan = {873+ d: 4,874+ r: 0.6,875+ w: sectionTo(TEETH / TEETH_PER_SECTION - 1) - sectionFrom(0) + 2,876+ x: sectionFrom(0) - 1,877+ y: -7,878+ };879+880+ const ticks = ticksAlongX(881+ Array.from({ length: TEETH + 1 }, (_, index) => toothX(index) - 4.35 / 2),882+ TEETH_PER_SECTION,883+ strip.y + 0.4,884+ LIP_TOP + 0.5,885+ [1.2, 2.6],886+ C887+ );888+889+ return [890+ solid(891+ slab(LIP, CASE_FLOOR, LIP_TOP - CASE_FLOOR, C, { bevel: 0.5, steps: 2 }),892+ "mid"893+ ),894+ solid(slab(strip, LIP_TOP, 0.5, C, { steps: 2 }), "lo", { crease: "none" }),895+ line(ticks.minor, "lo"),896+ line(ticks.major, "mid"),897+ ];898+};899+900+/** The press's two pillars on the lip, each with its pivot boss. */901+export const pillars = (): readonly Mark[] =>902+ ARM_XS.flatMap((x, index) => {903+ const outward = index === 0 ? -1 : 1;904+ const px = x + outward * 3.2;905+906+ return [907+ solid(post([px, PIVOT[0]], 2.6, LIP_TOP, 2, C, 18), "mid"),908+ solid(909+ post([px, PIVOT[0]], 1.8, LIP_TOP + 2, PIVOT[1] - LIP_TOP - 2, C, 16),910+ "mid",911+ {912+ crease: "none",913+ }914+ ),915+ solid(916+ rod(frameAlong([px - 2.2, PIVOT[0], PIVOT[1]], X), 0, 4.4, 3, C, 20),917+ "mid"918+ ),919+ ];920+ });921+922+/** The rail bed, its two rails and the back posts of every stage's bridge. */923+export const railBack = (): readonly Mark[] => [924+ solid(slab(RAIL_BED, 0, RAIL_BED_TOP, C, { bevel: 0.6, steps: 3 }), "mid"),925+ ...RAILS.map((y) =>926+ solid(927+ slab(928+ { d: 2.4, r: 0.6, w: RAIL_BED.w - 8, x: RAIL_BED.x + 4, y: y - 1.2 },929+ RAIL_BED_TOP,930+ RAIL_TOP - RAIL_BED_TOP,931+ C,932+ { bevel: 0.3, steps: 2 }933+ ),934+ "mid"935+ )936+ ),937+ screws(938+ RAILS.flatMap((y) =>939+ [RAIL_BED.x + 8, RAIL_BED.x + RAIL_BED.w - 8].map((x): Point => [940+ x,941+ y,942+ RAIL_TOP,943+ ])944+ ),945+ 0.4946+ ),947+ ...STATIONS.map((x) =>948+ box(949+ [x - 2.5, BRIDGE_POSTS[0] - 2, 0],950+ [x + 2.5, BRIDGE_POSTS[0] + 2, BRIDGE_TOP],951+ "mid"952+ )953+ ),954+ box(955+ [RAIL_BED.x + 1.5, 29, RAIL_BED_TOP],956+ [RAIL_BED.x + 4.5, 45, RAIL_BED_TOP + 7],957+ "mid",958+ { bevel: 0.3 }959+ ),960+];961+962+/** The carriage that takes an answer down the rail, built at x = 0. */963+export const carriage = (): readonly Mark[] => {964+ const plan: Plan = {965+ d: 16,966+ r: 1.5,967+ w: CARRIAGE_HALF * 2,968+ x: -CARRIAGE_HALF,969+ y: 29,970+ };971+972+ return [973+ ...[-CARRIAGE_HALF + 3, CARRIAGE_HALF - 7].flatMap((x) =>974+ RAILS.map((y) =>975+ box([x, y - 2.4, RAIL_TOP - 1], [x + 4, y + 2.4, RAIL_TOP + 1], "mid")976+ )977+ ),978+ solid(979+ slab(plan, RAIL_TOP + 0.6, CARRIAGE_TOP - RAIL_TOP - 0.6, C, {980+ bevel: 0.5,981+ steps: 3,982+ }),983+ "mid"984+ ),985+ line(986+ onTop(987+ [988+ [-CARRIAGE_HALF, STRIP_Y[0] - 1],989+ [CARRIAGE_HALF, STRIP_Y[0] - 1],990+ ],991+ CARRIAGE_TOP,992+ C993+ ),994+ "faint"995+ ),996+ line(997+ onTop(998+ [999+ [-CARRIAGE_HALF, STRIP_Y[1] + 1],1000+ [CARRIAGE_HALF, STRIP_Y[1] + 1],1001+ ],1002+ CARRIAGE_TOP,1003+ C1004+ ),1005+ "faint"1006+ ),1007+ screws(1008+ [-11, -4, 4, 11].map((x): Point => [1009+ x,1010+ plan.y + plan.d - 1.8,1011+ CARRIAGE_TOP,1012+ ]),1013+ 0.41014+ ),1015+ ];1016+};1017+1018+/** A strip's own frame on the carriage, at x = 0: along x, across y, up z. */1019+const ON_CARRIAGE: Frame = {1020+ a: Z,1021+ o: [0, (STRIP_Y[0] + STRIP_Y[1]) / 2, CARRIAGE_TOP],1022+ u: X,1023+ v: Y,1024+};1025+1026+export const STRIP_HALF = (TEETH_PER_SECTION * 4.35) / 2 + 1;1027+1028+/**1029+ * An answer: a brass strip of pins for one section, in its own frame. A stray1030+ * pin past its end is what the shape stage refuses.1031+ */1032+export const strip = (1033+ stray: boolean,1034+ frame: Frame = ON_CARRIAGE1035+): readonly Mark[] => {1036+ const across = (STRIP_Y[1] - STRIP_Y[0]) / 2;1037+ const strayX = STRIP_HALF + 2.4;1038+ const length = stray ? STRIP_HALF + 4.6 : STRIP_HALF;1039+1040+ const pins = [1041+ ...[-1.5, -0.5, 0.5, 1.5].map((index) => index * 4.35),1042+ ...(stray ? [strayX] : []),1043+ ].map((x, index) => {1044+ const y = index % 2 === 0 ? -1.2 : 1.2;1045+1046+ return line(1047+ polyline(1048+ [1049+ inFrame(frame, STRIP_T, [x, y]),1050+ inFrame(frame, STRIP_T + 1.8, [x, y]),1051+ ],1052+ C1053+ ),1054+ x === strayX ? "lit" : "hi",1055+ { width: 1.1 }1056+ );1057+ });1058+1059+ const plate = solid(1060+ prism(frame, rect(-STRIP_HALF, -across, length, across), 0, STRIP_T, C),1061+ "hi",1062+ {1063+ crease: "lo",1064+ }1065+ );1066+1067+ // Pins that point away from the viewer hide behind their plate. Both sets1068+ // are always drawn, one of them empty, so a turning strip keeps its paths.1069+ const facing = dot(frame.a, view(C)) > 0;1070+ const hidden = pins.map((pin) => ({ ...pin, d: "" }));1071+1072+ return [...(facing ? hidden : pins), plate, ...(facing ? pins : hidden)];1073+};1074+1075+const bridgeTop = (x: number): readonly Mark[] => [1076+ box(1077+ [x - 4, BRIDGE_POSTS[0] - 3, BRIDGE_TOP],1078+ [x + 4, BRIDGE_POSTS[1] + 3, BRIDGE_TOP + 4],1079+ "mid",1080+ { bevel: 0.4 }1081+ ),1082+ screws(1083+ [BRIDGE_POSTS[0], BRIDGE_POSTS[1]].map((y): Point => [1084+ x,1085+ y,1086+ BRIDGE_TOP + 4,1087+ ]),1088+ 0.421089+ ),1090+];1091+1092+const frontPost = (x: number) =>1093+ box(1094+ [x - 2.5, BRIDGE_POSTS[1] - 2, RAIL_BED_TOP - 5],1095+ [x + 2.5, BRIDGE_POSTS[1] + 2, BRIDGE_TOP],1096+ "mid"1097+ );1098+1099+const hanger = (x: number, low: number) =>1100+ solid(post([x, 36], 1, low, BRIDGE_TOP - low, C, 10), "mid", {1101+ crease: "none",1102+ });1103+1104+/** Each stage's bridge front, crossbar and fixed instrument, by stage. */1105+export const stationFronts = (): readonly (readonly Mark[])[] => [1106+ // Parse: a slot gauge the strip must pass under.1107+ [1108+ frontPost(STATIONS[0]),1109+ box([STATIONS[0] - 6, 30, 16], [STATIONS[0] + 6, 42, BRIDGE_TOP], "mid", {1110+ bevel: 0.4,1111+ }),1112+ line(1113+ polyline(1114+ [1115+ [STATIONS[0] - 4, 42, 18],1116+ [STATIONS[0] + 4, 42, 18],1117+ [STATIONS[0] + 4, 42, 20],1118+ [STATIONS[0] - 4, 42, 20],1119+ ],1120+ C,1121+ true1122+ ),1123+ "lo"1124+ ),1125+ ...bridgeTop(STATIONS[0]),1126+ ],1127+ // Shape: the template's guide; the template itself moves.1128+ [frontPost(STATIONS[1]), ...bridgeTop(STATIONS[1])],1129+ // Merge: a roller in a fork that rolls the strip against main.1130+ [1131+ frontPost(STATIONS[2]),1132+ box([STATIONS[2] - 5, 30, 21], [STATIONS[2] + 5, 31.6, BRIDGE_TOP], "mid"),1133+ solid(rod(frameAlong([STATIONS[2], 31.6, 18], Y), 0, 9, 4.2, C, 28), "hi"),1134+ line(arcOn(frameAlong([STATIONS[2], 31.6, 18], Y), 4.5, 4.2, C), "faint"),1135+ box(1136+ [STATIONS[2] - 5, 40.6, 21],1137+ [STATIONS[2] + 5, 42.2, BRIDGE_TOP],1138+ "mid"1139+ ),1140+ ...bridgeTop(STATIONS[2]),1141+ ],1142+ // Cheap: the feeler's guide; the feeler itself moves.1143+ [1144+ frontPost(STATIONS[3]),1145+ ...bridgeTop(STATIONS[3]),1146+ box([STATIONS[3] - 3, 33, 24], [STATIONS[3] + 3, 39, BRIDGE_TOP], "mid"),1147+ ],1148+ // Checks: a small test comb under the bar; its teeth move.1149+ [1150+ frontPost(STATIONS[4]),1151+ box([STATIONS[4] - 7, 30, 24], [STATIONS[4] + 7, 34, BRIDGE_TOP], "mid"),1152+ ...bridgeTop(STATIONS[4]),1153+ ],1154+ // Held back: a sealed box under a frosted top; its bell moves.1155+ [1156+ frontPost(STATIONS[5]),1157+ box([STATIONS[5] - 7, 29, 17], [STATIONS[5] + 7, 43, BRIDGE_TOP], "mid", {1158+ bevel: 0.5,1159+ }),1160+ dots(1161+ Array.from({ length: 5 }, (_row, row) =>1162+ Array.from({ length: 4 }, (_column, column) =>1163+ flat([1164+ STATIONS[5] - 5.2 + column * 3.5 + (row % 2) * 1.6,1165+ 30.6 + row * 2.8,1166+ BRIDGE_TOP,1167+ ])1168+ )1169+ ).flat(),1170+ 0.38,1171+ "lo"1172+ ),1173+ ...bridgeTop(STATIONS[5]),1174+ ],1175+ // Maintainer: a decision lever with its sand-glass, taken only when a person must choose.1176+ [frontPost(STATIONS[6]), ...bridgeTop(STATIONS[6])],1177+];1178+1179+/** A template plate that drops onto the strip: its window is the section's territory. */1180+export const template = (): readonly Mark[] => {1181+ const [, x] = STATIONS;1182+ const plate: Plan = { d: 10, r: 0.8, w: 22, x: x - 11, y: 32 };1183+1184+ return [1185+ hanger(x, 18),1186+ solid(slab(plate, 16, 1.6, C, { bevel: 0.3, steps: 2 }), "hi", {1187+ crease: "lo",1188+ }),1189+ line(1190+ planOutline({ d: 6, r: 0.4, w: 18.4, x: x - 9.2, y: 34 }, 17.6, C, 2),1191+ "lo"1192+ ),1193+ ];1194+};1195+1196+/** The feeler: a sprung plunger that taps every pin for one bent flat. */1197+export const feeler = (): readonly Mark[] => {1198+ const x = CHEAP_X;1199+ const spring = coil([x, 36], 1.8, [19, 24], 4, C);1200+1201+ return [1202+ line(spring.back, "lo"),1203+ solid(post([x, 36], 0.9, 15, 9.5, C, 10), "hi", { crease: "none" }),1204+ solid(post([x, 36], 1.6, 18, 1, C, 14), "mid"),1205+ line(spring.front, "mid"),1206+ ];1207+};1208+1209+/** The test comb's five teeth, pointing down at the strip. */1210+export const testTeeth = (): readonly Mark[] =>1211+ Array.from({ length: 5 }, (_, index) => {1212+ const x = STATIONS[4] - 5 + index * 2.5;1213+1214+ return solid(1215+ slab({ d: 1.4, r: 0.3, w: 1.6, x: x - 0.8, y: 32 }, 15.5, 8.5, C, {1216+ steps: 1,1217+ }),1218+ "hi",1219+ { crease: "lo" }1220+ );1221+ });1222+1223+/** The held-back stage's bell, on a post above its sealed box. */1224+export const bell = (): readonly Mark[] => {1225+ const x = HELD_X;1226+ const centre: Point = [x, 36, BRIDGE_TOP + 4];1227+ const frame = frameAlong(centre, Z);1228+1229+ return [1230+ solid(post([x, 36], 0.8, BRIDGE_TOP + 4, 4, C, 10), "mid", {1231+ crease: "none",1232+ }),1233+ solid(1234+ turned(1235+ frame,1236+ [1237+ [4, 5.6],1238+ [5, 5.4],1239+ [7, 4.2],1240+ [9.4, 3.2],1241+ [11, 2],1242+ [11.6, 0],1243+ ],1244+ C,1245+ 281246+ ),1247+ "hi",1248+ { crease: "lo" }1249+ ),1250+ ];1251+};1252+1253+/** A small sand-glass: two cones between two plates, on three posts. */1254+export const sandGlass = (1255+ centre: Flat,1256+ z: number,1257+ height = 91258+): readonly Mark[] => {1259+ const frame = frameAlong([centre[0], centre[1], z], Z);1260+ const half = height / 2;1261+1262+ return [1263+ solid(post(centre, 2.6, z, 0.8, C, 16), "mid"),1264+ solid(1265+ turned(1266+ frame,1267+ [1268+ [0.8, 2.1],1269+ [half - 0.3, 0.35],1270+ [half, 0.3],1271+ ],1272+ C,1273+ 181274+ ),1275+ "faint",1276+ { crease: "none" }1277+ ),1278+ solid(1279+ turned(1280+ frame,1281+ [1282+ [half, 0.3],1283+ [half + 0.3, 0.35],1284+ [height - 0.8, 2.1],1285+ ],1286+ C,1287+ 181288+ ),1289+ "faint",1290+ { crease: "none" }1291+ ),1292+ ...[0, 2.1, 4.2].map((angle) =>1293+ solid(1294+ post(1295+ [1296+ centre[0] + 2.1 * Math.cos(angle),1297+ centre[1] + 2.1 * Math.sin(angle),1298+ ],1299+ 0.3,1300+ z + 0.8,1301+ height - 1.6,1302+ C,1303+ 61304+ ),1305+ "mid",1306+ { crease: "none" }1307+ )1308+ ),1309+ solid(post(centre, 2.6, z + height - 0.8, 0.8, C, 16), "mid"),1310+ ];1311+};1312+1313+/** The maintainer's lever and sand-glass: left at its default, since this ask needs no person. */1314+export const lever = (): readonly Mark[] => {1315+ const x = HUMAN_X;1316+ const frame = frameAlong([x, 36, BRIDGE_TOP + 4], [0.55, 0, 0.83]);1317+1318+ return [1319+ solid(post([x, 36], 2.4, BRIDGE_TOP + 4, 2, C, 16), "mid"),1320+ solid(rod(frame, 1, 12, 0.8, C, 10), "mid"),1321+ solid(rod(frame, 12, 15, 1.7, C, 14), "hi"),1322+ ...sandGlass([x - 1, 26.5], BRIDGE_TOP + 4),1323+ ];1324+};1325+1326+/** A stage's flag on its crossbar: drawn by state, never coloured without its word. */1327+export const flag = (x: number) =>1328+ slab(1329+ { d: 1, r: 0.2, w: 6, x: x - 3, y: BRIDGE_POSTS[1] + 1 },1330+ BRIDGE_TOP + 4,1331+ 4.5,1332+ C,1333+ { steps: 1 }1334+ );1335+1336+/** The trays, one per stage: their backs and floors, behind whatever lands in them. */1337+export const trayBacks = (): readonly Mark[] =>1338+ STATIONS.flatMap((x) => [1339+ box([x - TRAY_HALF, TRAY_Y[0], 0], [x + TRAY_HALF, TRAY_Y[1], 1.4], "lo"),1340+ box(1341+ [x - TRAY_HALF, TRAY_Y[0], 1.4],1342+ [x + TRAY_HALF, TRAY_Y[0] + 1.2, TRAY_H],1343+ "mid"1344+ ),1345+ box(1346+ [x - TRAY_HALF, TRAY_Y[0] + 1.2, 1.4],1347+ [x - TRAY_HALF + 1.2, TRAY_Y[1] - 1.2, TRAY_H - 2],1348+ "mid"1349+ ),1350+ ]);1351+1352+/** The trays' near walls, each with a label holder. */1353+export const trayFronts = (): readonly Mark[] =>1354+ STATIONS.flatMap((x) => [1355+ box(1356+ [x + TRAY_HALF - 1.2, TRAY_Y[0] + 1.2, 1.4],1357+ [x + TRAY_HALF, TRAY_Y[1] - 1.2, TRAY_H - 2],1358+ "mid"1359+ ),1360+ box(1361+ [x - TRAY_HALF, TRAY_Y[1] - 1.2, 1.4],1362+ [x + TRAY_HALF, TRAY_Y[1], TRAY_H - 3],1363+ "mid",1364+ { bevel: 0.3 }1365+ ),1366+ line(1367+ polyline(1368+ [1369+ [x - 5, TRAY_Y[1], 3],1370+ [x + 5, TRAY_Y[1], 3],1371+ [x + 5, TRAY_Y[1], 5.6],1372+ [x - 5, TRAY_Y[1], 5.6],1373+ ],1374+ C,1375+ true1376+ ),1377+ "lo"1378+ ),1379+ line(1380+ segment([x - 3.6, TRAY_Y[1], 4.3], [x + 1.6, TRAY_Y[1], 4.3], C),1381+ "faint",1382+ { free: true }1383+ ),1384+ ]);1385+1386+/** Everything above a tray's floor, on screen: a slip rising in it shows only there. */1387+export const trayOpening = (x: number) => {1388+ const floor = [1389+ [x - TRAY_HALF + 1.2, TRAY_Y[0] + 1.2],1390+ [x + TRAY_HALF - 1.2, TRAY_Y[0] + 1.2],1391+ [x + TRAY_HALF - 1.2, TRAY_Y[1] - 1.2],1392+ [x - TRAY_HALF + 1.2, TRAY_Y[1] - 1.2],1393+ ].map(([px = 0, py = 0]) => flat([px, py, 1.4]));1394+1395+ return pathOf(1396+ hullOf([...floor, ...floor.map(([sx, sy]): Flat => [sx, sy - 80])]),1397+ true1398+ );1399+};1400+1401+/** A refusal's printed slip, built sunk in its tray; the motion raises it. */1402+export const slip = (x: number): readonly Mark[] => {1403+ const frame: Frame = {1404+ a: [0, 0.97, 0.26],1405+ o: [x, TRAY_Y[0] + 6, 1.4],1406+ u: X,1407+ v: [0, -0.26, 0.97],1408+ };1409+1410+ const rule = (v: number, from: number, to: number) =>1411+ polyline([inFrame(frame, 0.5, [from, v]), inFrame(frame, 0.5, [to, v])], C);1412+1413+ return [1414+ solid(prism(frame, rect(-6, 0, 6, 13), 0, 0.5, C), "hi", { crease: "lo" }),1415+ line(rule(11, -4.5, 3.5), "lo", { free: true }),1416+ line(rule(9, -4.5, 4.5), "lo", { free: true }),1417+ line(rule(7, -4.5, 1), "lo", { free: true }),1418+ ];1419+};1420+1421+const armTip = (angle: number): Flat => [1422+ PIVOT[0] + Math.cos(angle) * ARM_R,1423+ PIVOT[1] + Math.sin(angle) * ARM_R,1424+];1425+1426+const link = (x: number, angle: number) => {1427+ const frame: Frame = {1428+ a: [0, Math.cos(angle), Math.sin(angle)],1429+ o: [x, PIVOT[0], PIVOT[1]],1430+ u: X,1431+ v: [0, -Math.sin(angle), Math.cos(angle)],1432+ };1433+1434+ return solid(1435+ prism(frame, rect(-1.1, -1.8, 1.1, 1.8), -3, ARM_R + 1.5, C),1436+ "mid"1437+ );1438+};1439+1440+/** The press's far arm and the cradle between the arms, at the arms' angle. */1441+export const armBack = (angle: number): readonly Mark[] => {1442+ const tip = armTip(angle);1443+ const along: Point = [0, Math.cos(angle), Math.sin(angle)];1444+1445+ const cradle: Frame = {1446+ a: X,1447+ o: [0, tip[0] - along[1] * 5, tip[1] - along[2] * 5],1448+ u: along,1449+ v: [0, -Math.sin(angle), Math.cos(angle)],1450+ };1451+1452+ return [1453+ link(ARM_XS[0], angle),1454+ solid(1455+ prism(1456+ cradle,1457+ rect(-1.4, -1.4, 1.4, 1.4),1458+ ARM_XS[0] + 1.1,1459+ ARM_XS[1] - 1.1,1460+ C1461+ ),1462+ "mid"1463+ ),1464+ ];1465+};1466+1467+/** The strip the press holds: turned over with the arms, its pins down onto the cylinder. */1468+export const armStrip = (angle: number) => {1469+ const over = angle - ARM_DOWN;1470+ const up: Point = [0, -Math.sin(over), Math.cos(over)];1471+ const tip = armTip(angle);1472+1473+ return strip(false, {1474+ a: up,1475+ o: [SECTION_MID, tip[0] - up[1] * STRIP_T, tip[1] - up[2] * STRIP_T],1476+ u: X,1477+ v: [0, Math.cos(over), Math.sin(over)],1478+ });1479+};1480+1481+/** The press's near arm. */1482+export const armFront = (angle: number): readonly Mark[] => [1483+ link(ARM_XS[1], angle),1484+];1485+1486+/** The rod the rules follower pushes, and the cam box at the end of the rail it drives. */1487+export const rulesLink = (): readonly Mark[] => [1488+ solid(1489+ rod(1490+ frameAlong([FOLLOWER_X, -11, 14.6], Y),1491+ 0,1492+ CAM_BOX.y + 2 + 11,1493+ 1,1494+ C,1495+ 121496+ ),1497+ "mid",1498+ { crease: "none" }1499+ ),1500+ solid(slab(CAM_BOX, 0, 16, C, { bevel: 0.5, steps: 3 }), "mid", {1501+ inner: [line(sideSeam(CAM_BOX, 11, C, 3), "faint")],1502+ }),1503+ line(1504+ ringOnTop(1505+ [CAM_BOX.x + CAM_BOX.w / 2, CAM_BOX.y + CAM_BOX.d / 2],1506+ 4.4,1507+ 16,1508+ C,1509+ 281510+ ),1511+ "lo"1512+ ),1513+ screws(1514+ cornersOf(CAM_BOX, 2.4).map(([x, y]) => [x, y, 16]),1515+ 0.421516+ ),1517+];1518+1519+/** The near end wall: a framed glass pane the right end of the movement shows through. */1520+export const glassWall = (): readonly Mark[] => {1521+ const x = CASE.x + CASE.w - WALL;1522+ const frame: Frame = { a: X, o: [x, 0, 0], u: Y, v: Z };1523+1524+ const bar = (y0: number, z0: number, y1: number, z1: number) =>1525+ solid(prism(frame, rect(y0, z0, y1, z1), 0, WALL, C), "mid");1526+1527+ const front = CASE.y + CASE.d;1528+1529+ return [1530+ solid(1531+ prism(1532+ frame,1533+ rect(CASE.y + 5, CASE_FLOOR + 4, front - 5, WALL_TOP - 4),1534+ 2.6,1535+ 3.4,1536+ C1537+ ),1538+ "faint",1539+ {1540+ crease: "none",1541+ glass: true,1542+ }1543+ ),1544+ line(1545+ polyline(1546+ [1547+ [x + 3.4, front - 22, CASE_FLOOR + 3],1548+ [x + 3.4, front - 46, WALL_TOP - 3],1549+ ],1550+ C1551+ ),1552+ "faint"1553+ ),1554+ line(1555+ polyline(1556+ [1557+ [x + 3.4, front - 14, CASE_FLOOR + 3],1558+ [x + 3.4, front - 38, WALL_TOP - 3],1559+ ],1560+ C1561+ ),1562+ "faint"1563+ ),1564+ bar(CASE.y, CASE_FLOOR, CASE.y + 5, WALL_TOP),1565+ bar(CASE.y + 5, CASE_FLOOR, front - 5, CASE_FLOOR + 4),1566+ bar(CASE.y + 5, WALL_TOP - 4, front - 5, WALL_TOP),1567+ bar(front - 5, CASE_FLOOR, front, WALL_TOP),1568+ screws(1569+ [1570+ [x + WALL, CASE.y + 2.5, WALL_TOP - 2],1571+ [x + WALL, front - 2.5, WALL_TOP - 2],1572+ [x + WALL, CASE.y + 2.5, CASE_FLOOR + 2],1573+ [x + WALL, front - 2.5, CASE_FLOOR + 2],1574+ ],1575+ 0.451576+ ),1577+ ];1578+};1579+1580+/** The crank outside the glass, on the arbor, at its angle. */1581+export const crank = (angle: number): readonly Mark[] => {1582+ const hub: Point = [CRANK_X, AXIS[0], AXIS[1]];1583+ const along: Point = [0, Math.cos(angle), Math.sin(angle)];1584+1585+ const end: Point = [1586+ CRANK_X + 1.5,1587+ AXIS[0] + along[1] * CRANK_R,1588+ AXIS[1] + along[2] * CRANK_R,1589+ ];1590+1591+ const armFrame: Frame = {1592+ a: along,1593+ o: hub,1594+ u: X,1595+ v: [0, -Math.sin(angle), Math.cos(angle)],1596+ };1597+1598+ return [1599+ solid(rod(DRUM_FRAME, CASE.x + CASE.w, CRANK_X, 2.4, C, 18), "mid"),1600+ solid(rod(DRUM_FRAME, CRANK_X - 1, CRANK_X + 2, 4, C, 22), "mid"),1601+ solid(prism(armFrame, rect(-0.2, -2, 3, 2), 0, CRANK_R, C), "mid"),1602+ solid(rod(frameAlong(end, X), 1.5, 3, 2.2, C, 16), "mid"),1603+ solid(rod(frameAlong(end, X), 3, 11, 2, C, 18), "hi"),1604+ line(arcOn(frameAlong(end, X), 7, 2, C, 18), "faint"),1605+ ];1606+};1607+1608+/** The ledger's printer and its roll, with the tape running out over the bench. */1609+export const printer = (): readonly Mark[] => {1610+ const roll = frameAlong([PRINTER.x + 4, PRINTER.y + 10, 28], X);1611+1612+ const slot: Plan = {1613+ d: 1.4,1614+ r: 0.4,1615+ w: TAPE.w + 2,1616+ x: TAPE.x - 1,1617+ y: PRINTER.y + PRINTER.d - 0.7,1618+ };1619+1620+ return [1621+ solid(slab(PRINTER, 0, 20, C, { bevel: 0.6, steps: 3 }), "mid", {1622+ inner: [line(sideSeam(PRINTER, 15, C, 3), "faint")],1623+ }),1624+ line(planOutline(slot, 20, C, 2), "lo"),1625+ line(1626+ polyline(1627+ [1628+ [TAPE.x - 1, PRINTER.y + PRINTER.d, 0.6],1629+ [TAPE.x + TAPE.w + 1, PRINTER.y + PRINTER.d, 0.6],1630+ [TAPE.x + TAPE.w + 1, PRINTER.y + PRINTER.d, 2.4],1631+ [TAPE.x - 1, PRINTER.y + PRINTER.d, 2.4],1632+ ],1633+ C,1634+ true1635+ ),1636+ "lo"1637+ ),1638+ box(1639+ [PRINTER.x + 2, PRINTER.y + 6, 20],1640+ [PRINTER.x + 6, PRINTER.y + 14, 28],1641+ "mid"1642+ ),1643+ box(1644+ [PRINTER.x + PRINTER.w - 6, PRINTER.y + 6, 20],1645+ [PRINTER.x + PRINTER.w - 2, PRINTER.y + 14, 28],1646+ "mid"1647+ ),1648+ solid(rod(roll, -1, PRINTER.w - 6, 7, C, 40), "hi"),1649+ line(ringOn(roll, PRINTER.w - 6, 2, C, 16), "lo"),1650+ screws(1651+ cornersOf(PRINTER, 2.5).map(([x, y]) => [x, y, 20]),1652+ 0.421653+ ),1654+ ];1655+};1656+1657+/** The paper tape on the bench: a thin flat strip, printed by the motion. */1658+export const tape = (): readonly Mark[] => [1659+ solid(slab(TAPE, 0, 0.3, C, { steps: 1 }), "lo", {1660+ crease: "none",1661+ flat: true,1662+ }),1663+ line(1664+ polyline(1665+ [1666+ [TAPE.x, PRINTER.y + PRINTER.d, 0.3],1667+ [TAPE.x, TAPE.y, 0.3],1668+ ],1669+ C1670+ ),1671+ "lo"1672+ ),1673+];1674+1675+/** One printed entry on the tape, at its distance out from the printer: two rule lines. */1676+export const entry = (out: number) => {1677+ const y = TAPE.y + 3 + out;1678+1679+ return [1680+ onTop(1681+ [1682+ [TAPE.x + 2.5, y],1683+ [TAPE.x + 11, y],1684+ ],1685+ 0.3,1686+ C1687+ ),1688+ onTop(1689+ [1690+ [TAPE.x + 2.5, y + 2.2],1691+ [TAPE.x + 8, y + 2.2],1692+ ],1693+ 0.3,1694+ C1695+ ),1696+ ].join("");1697+};1698+1699+/** The claim: a clip on the ruler over its section, carrying a sand-glass. */1700+export const claimClip = (): readonly Mark[] => {1701+ const from = sectionFrom(SECTION) + 0.6;1702+ const to = sectionTo(SECTION) - 0.6;1703+1704+ return [1705+ box([from, -7.6, LIP_TOP + 0.5], [to, -2.6, LIP_TOP + 2], "hi"),1706+ line(1707+ onTop(1708+ [1709+ [from + 2, -5.1],1710+ [to - 7, -5.1],1711+ ],1712+ LIP_TOP + 2,1713+ C1714+ ),1715+ "faint",1716+ { free: true }1717+ ),1718+ ...sandGlass([to - 3.4, -5.1], LIP_TOP + 2, 8),1719+ ];1720+};1721+1722+/** The ask's flag on its pin, at the sour tooth. */1723+export const askFlag = (x: number): readonly Mark[] => [1724+ solid(post([x, -4.6], 1.3, LIP_TOP + 0.5, 1.2, C, 14), "mid"),1725+ solid(post([x, -4.6], 0.5, LIP_TOP + 1.7, 21, C, 8), "mid", {1726+ crease: "none",1727+ }),1728+ solid(1729+ prism(1730+ frameAlong([x + 0.5, -4.6, LIP_TOP + 16.5], X),1731+ rect(-0.25, 0, 0.25, 6),1732+ 0,1733+ 8,1734+ C1735+ ),1736+ "hi",1737+ { crease: "lo", lit: true }1738+ ),1739+ solid(post([x, -4.6], 0.9, LIP_TOP + 22.7, 0.9, C, 10), "mid"),1740+];added:apps/web/src/features/landing/music-box/words.ts+70 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970/** The music box's card and legend: what each part stands for, in GLOSSARY.md's words. */
export const FIGURE = { caption: "Everything on main is public, under glass. A project states each change it wants as a tooth that plays sour; anyone can claim it and push an answer. The gate checks every answer, cheapest stage first: a refused answer drops into that stage's tray with its reason, and one that passes every stage is pinned by the press, which alone writes the cylinder.", fig: "Fig 1", hint: "Click or press Space for the next step", label: "A cylinder music box under an open glass lid, with a seven-stage gate along its front. The ask is a comb tooth that plays sour. A first answer, a strip of pins, is refused at the second stage and drops into its tray with a printed slip; a second passes all seven, and the press turns it onto the cylinder while a tape prints its credit. Arrow keys step through the story.", title: "A music box only its own press can pin",} as const;
export type KeyMark = | "raised" | "lit" | "landed" | "refused" | "sealed" | "glass";
export interface Key { readonly word: string; readonly part: string; readonly mark: KeyMark;}
export const KEYS: readonly Key[] = [ { mark: "raised", part: "the pinned cylinder; only the press writes it.", word: "main", }, { mark: "glass", part: "the glass lid. A frosted panel is a layer.", word: "Public", }, { mark: "lit", part: "the lit tooth, a note that plays sour.", word: "Ask" }, { mark: "raised", part: "that tooth's section of the comb.", word: "Territory", }, { mark: "raised", part: "the clip on the section, with its sand-glass.", word: "Claim", }, { mark: "raised", part: "a strip of pins on the carriage.", word: "Answer" }, { mark: "raised", part: "seven bridges over the rail, cheapest first.", word: "Gate", }, { mark: "sealed", part: "the sealed box: one bell, pass or fail.", word: "Held-back check", }, { mark: "refused", part: "the tray under the stage that refused, and its slip.", word: "Refusal", }, { mark: "landed", part: "the press turns the strip onto the cylinder; the tape prints the credit.", word: "Landing", },];deleted:apps/web/src/features/landing/comparison.tsx-206 removed
1-/**2- * The hero's two panels: the usual flow by its mechanism under an X, and an3- * ask landing through the gate under a check. Each flow is drawn as inline4- * SVG at its own size, never scaled, so its text keeps the type floor: on a5- * phone too narrow for it the drawing scrolls inside its panel. Each is named6- * in full for a screen reader. No product is named.7- */8-import { Check, X } from "lucide-react";9-import type { LucideIcon } from "lucide-react";10-import type { CSSProperties } from "react";11-12-interface Step {13- readonly name: string;14- readonly says: string;15- /** Drawn in the landed colour: the step that puts the change on main. */16- readonly onMain?: boolean;17-}18-19-interface Flow {20- readonly id: "usual" | "gate";21- readonly title: string;22- readonly says: string;23- readonly mark: LucideIcon;24- readonly steps: readonly Step[];25- /** The step a loop goes back to, from the step after it. */26- readonly loop: { readonly from: number; readonly to: number };27-}28-29-const FLOWS: readonly Flow[] = [30- {31- id: "usual",32- loop: { from: 3, to: 2 },33- mark: X,34- says: "A person reads each change and approves it, as many rounds as it takes.",35- steps: [36- { name: "issue", says: "a change described in prose" },37- { name: "branch", says: "a contributor's copy to work on" },38- { name: "pull request", says: "the diff waits for a reader" },39- { name: "review comments", says: "rounds until a reader approves" },40- { name: "merge button", says: "whoever has the right presses it" },41- { name: "main", says: "what a reader approved" },42- ],43- title: "The usual flow",44- },45- {46- id: "gate",47- loop: { from: 3, to: 2 },48- mark: Check,49- says: "The project states the change as a check, and the gate runs it on the exact tree that would land.",50- steps: [51- { name: "ask", says: "a check that fails on main today" },52- { name: "claim", says: "one claimant, a fork of their own" },53- { name: "answer", says: "a commit, pushed with plain git" },54- { name: "gate", says: "seven stages; a refusal goes back" },55- {56- name: "main",57- onMain: true,58- says: "lands as a commit, with credit",59- },60- ],61- title: "Through the gate",62- },63-];64-65-const WIDTH = 288;66-67-const STEP = 52;68-69-const TOP = 14;70-71-const LINE_X = 28;72-73-const at = (index: number) => TOP + index * STEP;74-75-/** Each step settles in turn, once, where motion is welcome. */76-const settling = (index: number): CSSProperties => ({77- animationDelay: `${index * 140}ms`,78-});79-80-const Loop = ({ flow }: { readonly flow: Flow }) => {81- const from = at(flow.loop.from);82- const to = at(flow.loop.to);83-84- return (85- <g86- className={flow.id === "gate" ? "stroke-refused" : "stroke-foreground"}87- fill="none"88- strokeDasharray={flow.id === "gate" ? "4 3" : undefined}89- strokeWidth={1.5}90- >91- <path92- d={`M${LINE_X - 6} ${from} C4 ${from} 4 ${to} ${LINE_X - 7} ${to}`}93- />94- <path95- d={`M${LINE_X - 12} ${to - 4} L${LINE_X - 7} ${to} L${LINE_X - 12} ${to + 4}`}96- strokeDasharray="none"97- />98- </g>99- );100-};101-102-const FlowDrawing = ({ flow }: { readonly flow: Flow }) => {103- const height = at(flow.steps.length - 1) + 30;104-105- return (106- <svg107- aria-hidden="true"108- className="shrink-0"109- height={height}110- viewBox={`0 0 ${WIDTH} ${height}`}111- width={WIDTH}112- >113- <line114- className="stroke-rule"115- strokeWidth={2}116- x1={LINE_X}117- x2={LINE_X}118- y1={at(0)}119- y2={at(flow.steps.length - 1)}120- />121- <Loop flow={flow} />122- {flow.steps.map((step, index) => (123- <g data-step={step.name} key={step.name}>124- <circle125- className={`${126- step.onMain === true127- ? "fill-landed stroke-landed"128- : "fill-card stroke-foreground"129- } origin-center [transform-box:fill-box] ${130- flow.id === "gate" ? "motion-safe:animate-stamp" : ""131- }`}132- cx={LINE_X}133- cy={at(index)}134- r={6}135- strokeWidth={1.75}136- style={flow.id === "gate" ? settling(index) : undefined}137- />138- <text139- className="fill-foreground text-ui font-medium"140- x={LINE_X + 18}141- y={at(index) + 5}142- >143- {step.name}144- </text>145- <text146- className="fill-muted-foreground text-label font-normal"147- x={LINE_X + 18}148- y={at(index) + 24}149- >150- {step.says}151- </text>152- </g>153- ))}154- </svg>155- );156-};157-158-const Panel = ({ flow }: { readonly flow: Flow }) => {159- const Mark = flow.mark;160-161- return (162- <section163- aria-labelledby={`flow-${flow.id}`}164- className="bg-card border-rule flex min-w-0 flex-col gap-4 rounded-md border p-4"165- data-flow={flow.id}166- >167- <div className="flex items-center gap-2.5">168- <Mark169- aria-hidden="true"170- className="text-foreground motion-safe:animate-stamp size-6 shrink-0"171- strokeWidth={2}172- />173- <h2 className="text-title" id={`flow-${flow.id}`}>174- {flow.title}175- </h2>176- </div>177- <p className="text-ui text-muted-foreground max-w-(--measure)">178- {flow.says}179- </p>180- <div className="overflow-x-auto">181- <FlowDrawing flow={flow} />182- </div>183- <ol className="sr-only">184- {flow.steps.map((step) => (185- <li key={step.name}>186- {step.name}: {step.says}187- </li>188- ))}189- </ol>190- </section>191- );192-};193-194-/**195- * Side by side once two drawings fit at their own size (288 px each, inside196- * a card's padding, beside the gap and the gutters: about 704 px), so only a197- * phone, or a width just past one, stacks them. `tablet` (640 px) would be198- * too soon: each drawing would scroll inside its panel.199- */200-export const Comparison = () => (201- <div className="diffsplit:grid-cols-2 grid gap-5">202- {FLOWS.map((flow) => (203- <Panel flow={flow} key={flow.id} />204- ))}205- </div>206-);modified:apps/web/src/features/landing/gate-drawing.tsx+7 added-86 removed
1 /**2- * The gate as arcs over a track: an answer enters on the left, meets the3- * seven stages in order, and either leaves the track at the first that4- * refuses it or reaches main. Inline SVG with no text in it; the stages'5- * names sit in the page beneath their ticks, one column each.2+ * The gate in words and in git's own output: the seven stages in order, one3+ * column each, the bridges of the music box above, then a refused push and a4+ * landed one as a terminal prints them.5 */6 import { StageName } from "@repo/protocol/domain/outcome";8-import type { CSSProperties, ReactNode } from "react";7+import type { ReactNode } from "react";8 9 import { stageNames, stageRuns } from "../shared/status-line.tsx";10 import { landedPush, refusedPush } from "./transcript.ts";11 import type { Transcript as Printed } from "./transcript.ts";12 14-const COLUMN = 100;15-16-const WIDTH = COLUMN * StageName.literals.length;17-18-const TRACK = 92;19-20-const HEIGHT = 124;21-22-/** The stage that refuses the drawn answer: an `OutOfScope`, the shape stage's. */23-const REFUSED_AT = StageName.literals.indexOf("shape");24-25-const tickX = (index: number) => COLUMN / 2 + index * COLUMN;26-27-/** Each stage settles in turn, once, where motion is welcome. */28-const settling = (index: number): CSSProperties => ({29- animationDelay: `${index * 120}ms`,30-});31-32-const arch = (inset: number, top: number) =>33- `M${inset} ${TRACK} V${top + 36} C${inset} ${top + 8} ${inset + 90} ${top} ${WIDTH / 2} ${top} C${WIDTH - inset - 90} ${top} ${WIDTH - inset} ${top + 8} ${WIDTH - inset} ${top + 36} V${TRACK}`;34-35-const Drawing = () => {36- const refusedX = tickX(REFUSED_AT);37-38- return (39- <svg40- aria-hidden="true"41- className="h-auto w-full"42- preserveAspectRatio="xMidYMid meet"43- viewBox={`0 0 ${WIDTH} ${HEIGHT}`}44- >45- <g className="stroke-rule" fill="none" strokeWidth={2}>46- <path d={arch(14, 8)} />47- <path d={arch(30, 20)} />48- </g>49- <path50- className="stroke-muted-foreground"51- d={arch(46, 32)}52- fill="none"53- strokeWidth={2}54- />55- <line56- className="stroke-foreground"57- strokeWidth={2}58- x1={0}59- x2={WIDTH - 14}60- y1={TRACK}61- y2={TRACK}62- />63- <path64- className="stroke-landed"65- d={`M${WIDTH - 22} ${TRACK - 7} L${WIDTH - 12} ${TRACK} L${WIDTH - 22} ${TRACK + 7}`}66- fill="none"67- strokeWidth={2}68- />69- <path70- className="stroke-refused"71- d={`M${refusedX} ${TRACK} C${refusedX + 24} ${TRACK} ${refusedX + 30} ${HEIGHT - 6} ${refusedX + 64} ${HEIGHT - 6} H${refusedX + 110}`}72- fill="none"73- strokeDasharray="5 4"74- strokeWidth={2}75- />76- {StageName.literals.map((stage, index) => (77- <circle78- className="fill-card stroke-foreground motion-safe:animate-stamp origin-center [transform-box:fill-box]"79- cx={tickX(index)}80- cy={TRACK}81- key={stage}82- r={7}83- strokeWidth={2}84- style={settling(index)}85- />86- ))}87- </svg>88- );89-};90-13 const Stages = () => (14 <ol className="tablet:grid-cols-7 grid grid-cols-1 gap-x-3 gap-y-3">15 {StageName.literals.map((stage, index) => (16 <li79 unmodified lines96 readonly platformUrl: string;97 }) => (98 <div className="flex flex-col gap-8">99 <figure className="flex flex-col gap-4">178- <Drawing />100 <Stages />101 <figcaption className="text-ui text-muted-foreground max-w-(--measure)">181- An answer meets the stages in order, cheapest first. The first stage182- that fails refuses it, with every reason that stage found; an answer183- that passes them all lands on main.102+ The seven bridges of Fig 1, in order, cheapest first. The first stage103+ that fails refuses the answer, with every reason that stage found; an104+ answer that passes them all lands on main.105 </figcaption>106 </figure>107 <div className="columns:grid-cols-2 grid gap-5">108 <Output12 unmodified linesmodified:apps/web/src/features/landing/landing-page.tsx+2 added-2 removed
5 unmodified lines6 import { CommandLine } from "../shared/command.tsx";7 import { AppLink } from "../shared/link.tsx";8 import { ASKS_PATH, EXPLORE_PATH, INSTALL_PATH } from "../shared/paths.ts";9 import { GUTTER } from "../shared/shell/gutter.ts";10-import { Comparison } from "./comparison.tsx";10 import { GateDrawing } from "./gate-drawing.tsx";11 import { LandingNowList } from "./landing-now-list.tsx";12 import type { LandingNow } from "./landing-now.ts";13+import { MusicBox } from "./music-box/music-box.tsx";14 import { WaysIn } from "./ways-in.tsx";15 import { HEADLINE, HERO_LEDE } from "./words.ts";16 17 const PRIMARY = buttonVariants({ className: "no-underline", size: "lg" });128 unmodified lines146 <div className="max-w-full min-w-0">147 <CommandLine command={installCommand(webUrl)} />148 </div>149 </div>150- <Comparison />150+ <MusicBox />151 </div>152 153 <Part id="gate" title="The gate">154 <GateDrawing platformUrl={platformUrl} />23 unmodified linesmodified:apps/web/src/features/landing/ways-in.tsx+3 added-3 removed
2 unmodified lines34567789101112131415151617181920202122232418 unmodified lines2 unmodified linesimport { commands } from "../agents/catalog.ts";import { AppLink } from "../shared/link.tsx";import { INSTALL_PATH } from "../shared/paths.ts";
/** Every way in that works today, each a card that opens its place on the Install page. *//** Every way in that works today, each a link to its place on the Install page. */export const WaysIn = ({ platformUrl, webUrl,}: { readonly platformUrl: string; readonly webUrl: string;}) => ( <ul className="tablet:grid-cols-2 columns:grid-cols-3 grid gap-5"> <ul className="tablet:grid-cols-2 columns:grid-cols-3 grid gap-x-8 gap-y-6"> {installChannels({ commands, platformUrl, webUrl }) .filter(({ planned }) => !planned) .map(({ audience, id, summary, title }) => ( <li className="bg-card border-rule flex min-w-0 flex-col gap-2 rounded-md border p-4" className="border-rule flex min-w-0 flex-col gap-1.5 border-t pt-4" data-way={id} key={id} > <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">18 unmodified linesmodified:apps/web/src/styles.css+271 added
726 unmodified lines727 --tw-prose-pre-bg: var(--surface);728 --tw-prose-th-borders: var(--input);729 --tw-prose-td-borders: var(--rule);730 }731+732+/*733+ The landing's music box (features/landing/music-box): an isometric drawing734+ in the page's own inks. Every fill and stroke reads one of these tokens,735+ each a mix of the card and the ink, so both schemes come from the page's736+ palette. Sides take four tones by how they meet the light, tops the737+ lightest; lines run from the ink (hi) down to a groove (faint). State738+ colours appear only on a stage's flag, the held-back bell, the landed pin739+ and tooth, and the stray pin, each beside the readout's word for it.740+*/741+.mbx {742+ --mbx-paper: var(--card);743+ --mbx-top: var(--card);744+ --mbx-shade-0: color-mix(in oklab, var(--card) 84%, var(--foreground));745+ --mbx-shade-1: color-mix(in oklab, var(--card) 88.5%, var(--foreground));746+ --mbx-shade-2: color-mix(in oklab, var(--card) 92.5%, var(--foreground));747+ --mbx-shade-3: color-mix(in oklab, var(--card) 96%, var(--foreground));748+ --mbx-lit-top: var(--card);749+ --mbx-lit-shade: color-mix(in oklab, var(--card) 93%, var(--foreground));750+ --mbx-hi: color-mix(in oklab, var(--foreground) 88%, var(--card));751+ --mbx-mid: color-mix(in oklab, var(--foreground) 50%, var(--card));752+ --mbx-lo: color-mix(in oklab, var(--foreground) 30%, var(--card));753+ --mbx-faint: color-mix(in oklab, var(--foreground) 16%, var(--card));754+ --mbx-lit: var(--foreground);755+ --mbx-glass: color-mix(in oklab, var(--foreground) 5%, transparent);756+ --mbx-dot: var(--foreground);757+758+ @variant dark {759+ --mbx-top: color-mix(in oklab, var(--card) 88%, white);760+ --mbx-shade-0: color-mix(in oklab, var(--card) 82%, black);761+ --mbx-shade-1: color-mix(in oklab, var(--card) 91%, black);762+ --mbx-shade-2: var(--card);763+ --mbx-shade-3: color-mix(in oklab, var(--card) 94%, white);764+ --mbx-lit-top: color-mix(in oklab, var(--card) 80%, white);765+ --mbx-lit-shade: color-mix(in oklab, var(--card) 90%, white);766+ --mbx-hi: color-mix(in oklab, var(--foreground) 80%, var(--card));767+ --mbx-mid: color-mix(in oklab, var(--foreground) 44%, var(--card));768+ --mbx-lo: color-mix(in oklab, var(--foreground) 26%, var(--card));769+ --mbx-faint: color-mix(in oklab, var(--foreground) 15%, var(--card));770+ --mbx-glass: color-mix(in oklab, var(--foreground) 6%, transparent);771+ }772+}773+774+.mbx-svg {775+ display: block;776+ width: 100%;777+ height: auto;778+ overflow: visible;779+}780+781+.mbx-svg path,782+.mbx-svg circle {783+ vector-effect: non-scaling-stroke;784+}785+786+.mbx-fill {787+ fill: var(--mbx-paper);788+}789+790+.mbx-shade,791+.mbx-top {792+ stroke: none;793+}794+795+.mbx-shade[data-shade="0"] {796+ fill: var(--mbx-shade-0);797+}798+799+.mbx-shade[data-shade="1"] {800+ fill: var(--mbx-shade-1);801+}802+803+.mbx-shade[data-shade="2"] {804+ fill: var(--mbx-shade-2);805+}806+807+.mbx-shade[data-shade="3"] {808+ fill: var(--mbx-shade-3);809+}810+811+.mbx-top {812+ fill: var(--mbx-top);813+}814+815+.mbx-solid[data-flat] > :is(.mbx-shade, .mbx-top) {816+ display: none;817+}818+819+.mbx-solid[data-glass] > :is(.mbx-fill, .mbx-shade, .mbx-top) {820+ fill: var(--mbx-glass);821+}822+823+.mbx-solid[data-lit] > .mbx-top,824+[data-state="ask"] .mbx-top {825+ fill: var(--mbx-lit-top);826+}827+828+.mbx-solid[data-lit] > .mbx-shade,829+[data-state="ask"] .mbx-shade {830+ fill: var(--mbx-lit-shade);831+}832+833+.mbx-line {834+ fill: none;835+ stroke: var(--mbx-lo);836+ stroke-width: 0.6px;837+ stroke-linecap: round;838+ stroke-linejoin: round;839+}840+841+.mbx-line[data-tone="hi"] {842+ stroke: var(--mbx-hi);843+}844+845+.mbx-line[data-tone="mid"] {846+ stroke: var(--mbx-mid);847+}848+849+.mbx-line[data-tone="faint"] {850+ stroke: var(--mbx-faint);851+}852+853+.mbx-line[data-tone="lit"],854+.mbx-solid[data-lit] > .mbx-edge,855+[data-state="ask"] .mbx-edge {856+ stroke: var(--mbx-lit);857+ stroke-width: 1px;858+}859+860+.mbx-dots circle {861+ fill: var(--mbx-dot);862+ opacity: 0.45;863+}864+865+.mbx-dots[data-tone="lo"] circle {866+ opacity: 0.24;867+}868+869+.mbx-pins path,870+.mbx-pin {871+ fill: none;872+ stroke: var(--mbx-hi);873+ stroke-width: 1.3px;874+ stroke-linecap: round;875+}876+877+.mbx-pins [data-alpha="0"] {878+ opacity: 0.2;879+}880+881+.mbx-pins [data-alpha="1"] {882+ opacity: 0.45;883+}884+885+.mbx-pins [data-alpha="2"] {886+ opacity: 0.7;887+}888+889+.mbx-pin[data-part="sour"] {890+ stroke: var(--mbx-lit);891+ stroke-width: 1.6px;892+}893+894+/* A state's colour, beside the readout's word for it, eased in as the stage reports it. */895+.mbx [data-flag] path,896+.mbx [data-part="bell"] path,897+.mbx [data-part="tooth"] path {898+ transition:899+ fill 160ms ease-out,900+ stroke 160ms ease-out;901+}902+903+.mbx [data-state="landed"] :is(.mbx-fill, .mbx-shade, .mbx-top),904+.mbx [data-state="refused"] :is(.mbx-fill, .mbx-shade, .mbx-top),905+.mbx [data-state="sealed"] :is(.mbx-fill, .mbx-shade, .mbx-top),906+.mbx [data-state="checking"] :is(.mbx-fill, .mbx-shade, .mbx-top) {907+ fill: var(--mbx-state);908+}909+910+.mbx [data-state] .mbx-edge {911+ stroke: var(--mbx-state, var(--mbx-mid));912+}913+914+.mbx [data-state="landed"],915+.mbx-pin[data-state="landed"] {916+ --mbx-state: var(--landed);917+ stroke: var(--landed);918+}919+920+.mbx [data-state="refused"] {921+ --mbx-state: var(--refused);922+}923+924+.mbx [data-state="sealed"] {925+ --mbx-state: var(--sealed);926+}927+928+.mbx [data-state="checking"] {929+ --mbx-state: var(--checking);930+}931+932+.mbx [data-state="idle"] {933+ --mbx-state: var(--mbx-mid);934+}935+936+.mbx [data-state="ask"] {937+ --mbx-state: var(--mbx-lit);938+}939+940+/* The stray pin the shape stage refused, beside the readout's OutOfScope. */941+.mbx [data-fault] .mbx-line[data-tone="lit"] {942+ stroke: var(--refused);943+}944+945+.mbx-stage {946+ cursor: pointer;947+ touch-action: pan-y;948+}949+950+.mbx-swatch {951+ display: inline-block;952+ width: 16px;953+ height: 10px;954+ margin-inline-end: 0.5rem;955+ overflow: visible;956+ vertical-align: 0;957+}958+959+/* On a phone the bench's margins go, so the machine is drawn larger. */960+@media (width < 40rem) {961+ .mbx-stage .mbx-svg {962+ width: 130%;963+ margin-inline: -15%;964+ }965+}966+967+.mbx-swatch path {968+ fill: var(--card);969+ stroke: var(--mbx-mid);970+ stroke-width: 1px;971+ stroke-linejoin: round;972+ vector-effect: non-scaling-stroke;973+}974+975+.mbx-swatch[data-mark="lit"] path {976+ stroke: var(--mbx-lit);977+}978+979+.mbx-swatch[data-mark="landed"] path:first-child {980+ fill: var(--landed);981+ stroke: var(--landed);982+}983+984+.mbx-swatch[data-mark="refused"] path:first-child {985+ fill: var(--refused);986+ stroke: var(--refused);987+}988+989+.mbx-swatch[data-mark="sealed"] path:first-child {990+ fill: var(--sealed);991+ stroke: var(--sealed);992+}993+994+.mbx-swatch[data-mark="glass"] path:first-child {995+ fill: var(--mbx-glass);996+}997+998+.mbx-swatch .mbx-swatch-crease {999+ fill: none;1000+ stroke: var(--mbx-lo);1001+}modified:apps/web/test/landing.test.tsx+28 added-45 removed
8 unmodified lines9 10 import glossary from "../../../GLOSSARY.md?raw";11 import { LandingNow } from "../src/features/landing/landing-now.ts";12 import { LandingView } from "../src/features/landing/landing-page.tsx";13+import { REST, poseAt } from "../src/features/landing/music-box/model.ts";14+import { KEYS } from "../src/features/landing/music-box/words.ts";15 import { readLandingNow } from "../src/features/landing/read.ts";16 import { LEDE } from "../src/features/landing/words.ts";17 import { landingHead } from "../src/routes/index.tsx";18 import { allInOrder, textIn } from "./markup.ts";83 unmodified lines102 sha: LandedSha.make(String(index).repeat(40)),103 })104 );105 104-/** One of the hero's two panels, by its flow. */105-const panelOf = (markup: string, flow: string) =>106- new RegExp(107- `<section\\b[^>]*data-flow="${flow}"[\\s\\S]*?</section>`,108- "u"109- ).exec(markup)?.[0] ?? "";106+/** The hero's figure: the music box, its card and its legend. */107+const figureOf = (markup: string) =>108+ /<figure\b[^>]*data-figure="music-box"[\s\S]*?<\/figcaption>/u.exec(109+ markup110+ )?.[0] ?? "";111 111-const stepsIn = (panel: string) =>112- [...panel.matchAll(/data-step="(?<step>[^"]+)"/gu)].map(113- (found) => found.groups?.step114- );115-116-/** Code hosts and forges by name: the comparison describes the usual flow by mechanism alone. */112+/** Code hosts and forges by name: the page describes the platform by mechanism alone. */113 const PRODUCTS =114 /github|gitlab|bitbucket|gerrit|gitea|forgejo|codeberg|sourcehut/iu;115 116 /** A word's definition in GLOSSARY.md, the line under its bold head. */125 unmodified lines242 })243 );244 245 it.effect(250- "compares the usual flow, by its mechanism under an X, with an ask landing through the gate under a check",246+ "draws the platform as a music box, its legend naming the parts by GLOSSARY.md's words and no product",247 () =>248 Effect.gen(function* () {249 const markup = yield* pageWith(landed);254- const usual = panelOf(markup, "usual");255- const gate = panelOf(markup, "gate");250+ const figure = figureOf(markup);251 257- expect(stepsIn(usual)).toStrictEqual([258- "issue",259- "branch",260- "pull request",261- "review comments",262- "merge button",263- "main",264- ]);265- expect(stepsIn(gate)).toStrictEqual([266- "ask",267- "claim",268- "answer",269- "gate",270- "main",271- ]);252 expect(273- [usual, gate].map((panel) => /lucide-(?:x|check)\b/u.exec(panel)?.[0])274- ).toStrictEqual(["lucide-x", "lucide-check"]);275- expect(textIn(usual + gate)).not.toMatch(PRODUCTS);253+ [...figure.matchAll(/data-key="(?<word>[^"]+)"/gu)].map(254+ (found) => found.groups?.word255+ )256+ ).toStrictEqual(KEYS.map((key) => key.word));257+ expect(258+ KEYS.map((key) => key.word)259+ .filter((word) => word !== "main" && word !== "Public")260+ .filter((word) => defined(word) === undefined)261+ ).toStrictEqual([]);262+ expect(textIn(figure)).toContain(poseAt(REST).readout);263+ expect(textIn(figure)).not.toMatch(PRODUCTS);264 })265 );266 267 it.effect(280- "uses no banned word outside the usual flow's panel, and no shadowed, gradient or rounder surface than a card's",268+ "uses no banned word, and no shadowed, gradient or rounder surface than a card's",269 () =>270 Effect.gen(function* () {271 const markup = yield* pageWith(landed);284- const usual = panelOf(markup, "usual");285- const text = textIn(markup.replace(usual, "")).toLowerCase();272+ const text = textIn(markup).toLowerCase();273 287- // DESIGN.md's list, and the glossary's words to avoid. "Merge" is banned for a landing; Inbox and Explore are page names now.274+ // DESIGN.md's list, and the glossary's words to avoid. "Merge" is banned for a landing, and stays the name of a stage; Inbox and Explore are page names now.275 expect(276 [277 "review",278 "approve",20 unmodified lines299 })300 );301 302 it.effect(316- "draws the comparison and the gate as inline SVG, and moves only where motion is welcome",303+ "draws the music box as inline SVG with the gate's stages beneath it, and moves only where motion is welcome",304 () =>305 Effect.gen(function* () {306 const markup = yield* pageWith(landed);307 const main = mainOf(markup);308 322- expect(323- ["usual", "gate"].map((flow) =>324- panelOf(markup, flow).includes("<svg")325- )326- ).toStrictEqual([true, true]);327- expect(main.slice(main.indexOf('aria-labelledby="gate"'))).toContain(328- "<svg"309+ expect(figureOf(markup)).toContain("<svg");310+ expect(main.indexOf('data-figure="music-box"')).toBeLessThan(311+ main.indexOf('aria-labelledby="gate"')312 );313 expect(314 [...main.matchAll(/class="(?<names>[^"]*)"/gu)].flatMap((found) =>315 (found.groups?.names ?? "")146 unmodified linesadded:apps/web/test/music-box.test.ts+82 added
1+import { describe, expect, it } from "@effect/vitest";2+import { StageName } from "@repo/protocol/domain/outcome";3+4+import {5+ BEATS,6+ CYCLE,7+ LOOP,8+ REST,9+ poseAt,10+} from "../src/features/landing/music-box/model.ts";11+import { refusedPush } from "../src/features/landing/transcript.ts";12+13+/** The stage that refuses the first answer, as the transcript's refusal does. */14+const REFUSING = StageName.literals.indexOf("shape");15+16+/** Every tenth of a second of one cycle. */17+const CYCLE_TIMES = Array.from(18+ { length: CYCLE * 10 },19+ (_, index) => index / 1020+);21+22+/** When a stage's flag first reads checking for the second answer. */23+const firstChecked = (stage: number) =>24+ CYCLE_TIMES.find(25+ (time) => time > BEATS[3] + 2 && poseAt(time).flags[stage] === "checking"26+ ) ?? Number.POSITIVE_INFINITY;27+28+describe(poseAt, () => {29+ it("is a pure function of time that loops", () => {30+ expect(poseAt(7.3)).toStrictEqual(poseAt(7.3));31+ expect(poseAt(7.3 + LOOP).readout).toBe(poseAt(7.3).readout);32+ expect(poseAt(7.3 + LOOP).flags).toStrictEqual(poseAt(7.3).flags);33+ });34+35+ it("refuses the first answer at the shape stage with the tag the transcript prints", () => {36+ const refused = poseAt(BEATS[3]);37+ const { tag } = refusedPush("https://platform.example");38+39+ expect(refused.flags[REFUSING]).toBe("refused");40+ expect(refused.flags.slice(0, REFUSING)).toStrictEqual(["landed"]);41+ expect(42+ refused.flags.slice(REFUSING + 1).every((flag) => flag === "idle")43+ ).toBeTruthy();44+ expect(refused.readout).toBe(`round 1 · refused · ${tag}`);45+ });46+47+ it("passes the second answer through every stage in order, cheapest first", () => {48+ const order = StageName.literals.map((_, stage) => firstChecked(stage));49+50+ expect(order).toStrictEqual(order.toSorted((a, b) => a - b));51+ expect(order.every(Number.isFinite)).toBeTruthy();52+ });53+54+ it("reports the held-back stage by one bit in the sealed colour, and every other stage as passed", () => {55+ const { flags } = poseAt(REST);56+57+ expect(flags).toStrictEqual(58+ StageName.literals.map((stage) =>59+ stage === "heldBack" ? "sealed" : "landed"60+ )61+ );62+ });63+64+ it("lets the press hold an answer only once every stage has passed it", () => {65+ const held = CYCLE_TIMES.filter((time) => poseAt(time).holding);66+ const lastStage = StageName.literals.length - 1;67+68+ expect(held.length).toBeGreaterThan(0);69+ expect(70+ held.every((time) => poseAt(time).flags[lastStage] === "landed")71+ ).toBeTruthy();72+ });73+74+ it("rests with the refused answer in its tray and the second landed", () => {75+ const rest = poseAt(REST);76+77+ expect(rest.drop).toBe(1);78+ expect(rest.slip).toBeGreaterThan(0.9);79+ expect(rest.fixed).toBe(1);80+ expect(rest.readout).toMatch(/^landed · tooth \d+ plays true$/u);81+ });82+});modified:DESIGN.md+6 added-6 removed
250 unmodified lines251 **Creative North Star: "Four shells on warm paper"**252 253 The web serves four jobs, and each gets its own frame: a site that explains the platform and lists its projects, a project with one header and its tabs, a docs site, and a focused card for signing in. All four share the top bar's contents, so moving between them never reads as a different app. Every screen still answers three questions in this order: what state is it in, whose move is it, and what runs next. The answer to the last one is a command you can copy, shown once.254 255-The pages are for operating, with one page that persuades: the landing at `/`, which compares the usual issue and pull-request flow with an ask landing through the gate, and leads to the open asks. Density is set by a maintainer clearing the inbox on a phone and a contributor reading a refusal beside a terminal: two-line rows (64 px), 14 px metadata, a 13 px floor. Colour means state, and always sits beside a word and a mark, so a page read in grayscale, by a screen reader or in a terminal says the same thing. In a list the colour sits on the mark and the word stays ink. The one colour that is not a state is the sage primary: the page's main action and the focus ring.255+The pages are for operating, with one page that persuades: the landing at `/`, which draws the platform as a music box whose cylinder only its own press can pin, and leads to the open asks. Density is set by a maintainer clearing the inbox on a phone and a contributor reading a refusal beside a terminal: two-line rows (64 px), 14 px metadata, a 13 px floor. Colour means state, and always sits beside a word and a mark, so a page read in grayscale, by a screen reader or in a terminal says the same thing. In a list the colour sits on the mark and the word stays ink. The one colour that is not a state is the sage primary: the page's main action and the focus ring.256 257 Rejected on purpose: the dashboard look (stat tiles, big numbers over small labels, a blue link colour, pill badges, avatar stacks, coloured file icons), its glossy cousin (dark glass, blur, glows, gradients), and the terminal costume (green on black, monospace for everything). Rejected too: a logomark of any kind (crest, gate, doorway); a display serif; a coloured strip on the edge of a card; an eyebrow over a headline; a filled pill or tinted square that carries a state without its word; shadows and glows; `outline: none`; text at 12 px and greys under 4.5:1; avatars and activity sparklines; a command box that ellipsises; a column of code blocks; and spinners and shimmer in content. Monospace appears only where the text is what a terminal prints or takes: commands, refusal transcripts, trailers, SHAs, paths, ids, env keys and code.258 259 **Key Characteristics:**2 unmodified lines262 - A project has one header and eight tabs, and opens on Overview.263 - State is a mark, then a word, then a colour; red belongs to refusals, violet to sealed things, green to what is on main, olive to waiting, blue to checking. In a row the colour is the mark's; the word is ink, except Refused and Landed.264 - Every action is a command to copy, shown once per screen. The only web controls that change anything are a maintainer's choices, proposing an ask (and asking the platform's agent to draft it), the theme preference, and signing in or out.265 - Light and dark follow the system setting, or its opposite by the reader's choice on `/settings` (ADR 0042).266-- Motion carries state, never decoration: transitions of 120 to 200 ms, and the landing's stamp.266+- Motion carries state, never decoration: transitions of 120 to 200 ms, the landing's stamp, and the landing's music box, whose every move is a step of an answer through the gate.267 268 ## Colors269 270 The maintainer's "sage garden": warm paper, navy ink, a sage primary, soft sage fills, and five state roles that never appear as decoration. Its values sit on the web's own token names, so no component changed its classes. Every state role measures at least 5:1 against paper, the field surface and the pressed surface, in both schemes; body ink measures 15.3:1 in light and 18.2:1 in dark. `apps/web/test/tokens.test.ts` holds every pair, and holds the tokens to the pasted palette (a token taken unchanged equals the pasted value; a nudged one differs from it in lightness alone).167 unmodified lines438 - **Visibility:** posture, layers, held-back checks, the environment (once "Env shape") and the ledger, one tab.439 440 ### Cards441 442-- **Shape:** a plain bordered surface: `--card` ground, a hairline border all round, the 2 px radius, 16 px padding, no shadow. Nothing on one edge (the No Fingernail Rule). Used where a page lists things that are each a small document (Explore's projects, Install's channels, the landing's comparison panels), never for a list of rows.442+- **Shape:** a plain bordered surface: `--card` ground, a hairline border all round, the 2 px radius, 16 px padding, no shadow. Nothing on one edge (the No Fingernail Rule). Used where a page lists things that are each a small document (Explore's projects, Install's channels) or holds one figure (the landing's music box), never for a list of rows.443 444 ### Row (`Row`, `AskRow`) and row group (`RowGroup`)445 446 - **Character:** one anatomy for every list (asks, decisions, landings, commits, refs, forks, credits, rounds, history).113 unmodified lines560 561 ### The landing562 563 - **Where:** `/`, in the site shell (ADR 0041 amends ADR 0030's bare page). A reader who carries a session is sent to `/inbox`.564-- **Hero:** one primary action (the open asks) and the install command, then a two-panel comparison as inline SVG: on the left the usual flow by its mechanism (issue, branch, pull request, review comments, merge button) under an X mark; on the right an ask, an answer and the gate under a check mark. Two cards side by side from `diffsplit`, where both drawings fit at their own size, and stacked below it; no product is named. It honours `prefers-reduced-motion`.565-- **Below:** the seven-stage gate with a refused and a landed output beside it, the four words, landings as they happen, and every way in (linking `/install`). Its evidence is real output, set in mono as a terminal prints it. "Landing now" lists the latest landings and refused answers across public projects, the latest first and at most six, from `recentLandings`, the platform's one bounded read of them (at most 20, kept in D1 as they happen, never a replay of a project's events). Each row is a mark, the project over the ask's want (a landing with no ask shows its short SHA), linking the landed commit or the refused ask, and when. A refusal names its tag and its area, never a held-back check's name, a suite, a lane, a path or a log.564+- **Hero:** one primary action (the open asks) and the install command, then Fig 1, the music box (`features/landing/music-box`): an isometric drawing in inline SVG, in the page's own inks, of a cylinder music box under an open glass lid with the gate along its front. The cylinder is `main`; the glass is everything public, a frosted panel a layer; the lit comb tooth that plays sour is an ask, its section of the comb the territory; a clip on the ruler is the claim; a strip of pins is an answer, carried along a rail under seven bridges, one per stage, cheapest first. A first answer is refused at the shape stage and drops into that stage's tray with a printed slip; a second passes every stage, the held-back stage's sealed box ringing one bell, and the press, the only thing that writes the cylinder, turns it over onto the cylinder while a paper tape prints its credit. The card is a plain card with Fig 1 and a title in its top corners, the hint and a live readout in its bottom corners, and a legend under it that names each part by its word in `GLOSSARY.md`. State colours appear only on a stage's flag, the held-back bell, the stray pin the shape stage refused, and the landed pin and tooth, each beside the readout's word. The server draws the still picture (the refused answer in its tray, the second landed); in the browser one loop plays the story from a pure model of time (`model.ts`), stops off screen, and under `prefers-reduced-motion` moves only when a click or a key asks it to, straight to the next moment. The camera and solids are ported from the anatomy skill's kit (`music-box/iso.ts`, with its MIT notice).565+- **Below:** the seven stages in words, one column each, with a refused and a landed output beneath them, the four words, landings as they happen, and every way in (linking `/install`), each a heading over a hairline rather than a card. Its evidence is real output, set in mono as a terminal prints it. "Landing now" lists the latest landings and refused answers across public projects, the latest first and at most six, from `recentLandings`, the platform's one bounded read of them (at most 20, kept in D1 as they happen, never a replay of a project's events). Each row is a mark, the project over the ask's want (a landing with no ask shows its short SHA), linking the landed commit or the refused ask, and when. A refusal names its tag and its area, never a held-back check's name, a suite, a lane, a path or a log.566 567 ### Install568 569 - **Where:** `/install`, in the site shell; the old `/agents` is a 301 to it, and `/agents.md`, `/llms.txt` and `/llms-full.txt` keep answering.45 unmodified lines615 - **Don't** use red for anything but a refusal, violet for anything but sealed things, green for anything but on main, the sage primary for a state, or colour without a word; a diff uses its own teal and rose.616 - **Don't** use monospace for prose, labels, buttons, headings or commit bodies.617 - **Don't** show an env value, or the placeholder an answer sees, anywhere.618 - **Don't** add a form for something git or the CLI does (claim, push, check, land, env set), a light/dark toggle beyond the two-way preference, a cookie for any preference, or a second component kit.619-- **Don't** put on screen the words review, approve, PR, pull request, issue (for an ask), merge (for a landing), lease, reputation, queue, dashboard or trending. Inbox and Explore are page names now (ADR 0041). The landing's comparison panel is the one place that names the usual flow by its mechanism (issue, branch, pull request, review comments, merge button), and only to contrast it.619+- **Don't** put on screen the words review, approve, PR, pull request, issue (for an ask), merge (for a landing), lease, reputation, queue, dashboard or trending. Inbox and Explore are page names now (ADR 0041). A stage keeps its name, Merge included.620 - **Don't** use shimmer, spinners in content, page-load choreography or toasts as the only feedback.