Isometric line figures that answer the pointer. For React and for anything with a DOM.
Port: the six engines from lucasmarkes.com at edfebe9, with Riffle's button made methods
Lucas Marques8441cc65d02c
diff --git a/packages/hairline/package.json b/packages/hairline/package.jsonindex 48097f1..05d9449 100644--- a/packages/hairline/package.json+++ b/packages/hairline/package.json@@ -33,7 +33,7 @@"build": "rm -rf dist && tsup","dev": "tsup --watch","typecheck": "tsc --noEmit",- "test": "vitest run --passWithNoTests",+ "test": "vitest run","clean": "rm -rf dist .turbo","test:browser": "playwright test","capture": "node test/parity/capture.mjs",diff --git a/packages/hairline/src/core/iso.ts b/packages/hairline/src/core/iso.tsnew file mode 100644index 0000000..02eea2b--- /dev/null+++ b/packages/hairline/src/core/iso.ts@@ -0,0 +1,211 @@+/**+ * Hairline — the drawing maths every figure shares, with no DOM. Ported from+ * the study (design/lab-hairline/cartilha-v2.html) arithmetic-for-arithmetic,+ * so a figure here can be diffed against its IIFE there by eye.+ *+ * Everything is in viewBox units: every figure is drawn in a 400 × 320 box and+ * scaled to its column by the svg, so no number here depends on the viewport.+ * World space is x/y on the ground and z up; the camera turns the ground by an+ * azimuth, then squashes y by sin(el) and lifts z by cos(el). There is no+ * perspective and no hidden-line removal: plates are filled with the ground+ * colour and painted back to front, so a nearer one simply covers.+ */++export type Vec2 = [number, number];+export type Vec3 = [number, number, number];++/** A sample on a rounded outline, with its outward normal on the ground plane. */+export type Sample = { u: number; v: number; nu: number; nv: number };+export type Ring = Sample[];++/**+ * An orthographic camera. `az` is in radians, `k` is sin(elevation) (.5 is+ * the 2:1 view every figure rests at), `S` is the scale, and `ox`/`oy` the+ * screen offset `fit` computes. Mutable on purpose: the turntable turns it.+ */+export type Camera = { az: number; k: number; S: number; ox: number; oy: number };+export type Projector = (x: number, y: number, z: number) => Vec2;++/** Two lines of a solid: its bright silhouette and the one dim crease inside it. */+export type PrismPaths = { sil: string; crease: string };++export const clamp = (v: number, a: number, b: number) => Math.max(a, Math.min(b, v));+export const lerp = (a: number, b: number, t: number) => a + (b - a) * t;+export const rad = (d: number) => (d * Math.PI) / 180;+/** Two decimals: enough for a hairline at any zoom, and path strings stay short. */+export const r2 = (n: number) => Math.round(n * 100) / 100;++/** A closed path through the points. */+export const poly = (pts: readonly Vec2[]) =>+ "M" + pts.map((p) => r2(p[0]) + " " + r2(p[1])).join("L") + "Z";+/** One straight segment, as its own subpath, so several can be joined into one `d`. */+export const seg = (a: Vec2, b: Vec2) => `M${r2(a[0])} ${r2(a[1])}L${r2(b[0])} ${r2(b[1])}`;+/** An open polyline; empty for fewer than two points. */+export const open = (pts: readonly Vec2[]) =>+ pts.length < 2 ? "" : "M" + pts.map((p) => r2(p[0]) + " " + r2(p[1])).join("L");++/* ---------- projection ---------- */++export const Cam = (azDeg: number, k: number, S: number): Camera => ({ az: rad(azDeg), k, S, ox: 0, oy: 0 });++/**+ * The projector for the camera as it is now. Figures that move the camera+ * (the turntable) call this again each frame; the rest call it once.+ */+export function proj(C: Camera): Projector {+ const c = Math.cos(C.az), s = Math.sin(C.az), zf = Math.sqrt(1 - C.k * C.k);+ return (x, y, z) => {+ const X = x * c - y * s, Y = x * s + y * c;+ return [C.ox + C.S * X, C.oy + C.S * (Y * C.k - z * zf)];+ };+}++/**+ * The ground-plane inverse: the world x/y under a screen point, on the plane+ * at height z. This is how the pointer reaches the drawing — every hover in+ * the figures is tested in world units, never in pixels.+ */+export function unproj(C: Camera, sx: number, sy: number, z: number): [number, number] {+ const c = Math.cos(C.az), s = Math.sin(C.az), zf = Math.sqrt(1 - C.k * C.k);+ const X = (sx - C.ox) / C.S, Y = ((sy - C.oy) / C.S + z * zf) / C.k;+ return [X * c + Y * s, -X * s + Y * c];+}++/** Sets the camera's offset so the bounding box of `pts` is centred on (cx, cy). */+export function fit(C: Camera, pts: readonly Vec3[], cx: number, cy: number) {+ C.ox = 0; C.oy = 0;+ const P = proj(C);+ let a = 1e9, b = -1e9, c = 1e9, d = -1e9;+ for (const p of pts) {+ const q = P(p[0], p[1], p[2]);+ a = Math.min(a, q[0]); b = Math.max(b, q[0]); c = Math.min(c, q[1]); d = Math.max(d, q[1]);+ }+ C.ox = cx - (a + b) / 2; C.oy = cy - (c + d) / 2;+}++/* ---------- rounded solids ---------- */++/**+ * A rounded rectangle, sampled. Each sample carries its outward normal, so a+ * caller can keep just the run that faces the camera. `n` samples per corner.+ */+export function rrect(u0: number, v0: number, u1: number, v1: number, r: number, n = 4): Ring {+ r = Math.max(0, Math.min(r, (u1 - u0) / 2, (v1 - v0) / 2));+ const out: Ring = [];+ for (const [cu, cv, a0] of [[u1 - r, v1 - r, 0], [u0 + r, v1 - r, 90], [u0 + r, v0 + r, 180], [u1 - r, v0 + r, 270]])+ for (let k = 0; k <= n; k++) {+ const a = rad(a0 + (90 * k) / n), ca = Math.cos(a), sa = Math.sin(a);+ out.push({ u: cu + r * ca, v: cv + r * sa, nu: ca, nv: sa });+ }+ return out;+}++/** A circle of radius R about the origin, sampled the same way. */+export function circ(R: number, n = 96): Ring {+ const out: Ring = [];+ for (let k = 0; k < n; k++) {+ const a = (k / n) * Math.PI * 2, ca = Math.cos(a), sa = Math.sin(a);+ out.push({ u: R * ca, v: R * sa, nu: ca, nv: sa });+ }+ return out;+}++/** Convex hull (monotone chain), counter-clockwise in screen space. */+export function hull(input: readonly Vec2[]): Vec2[] {+ const pts = input.slice().sort((a, b) => a[0] - b[0] || a[1] - b[1]);+ const x = (o: Vec2, a: Vec2, b: Vec2) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);+ const lo: Vec2[] = [], up: Vec2[] = [];+ for (const p of pts) { while (lo.length > 1 && x(lo[lo.length - 2], lo[lo.length - 1], p) <= 0) lo.pop(); lo.push(p); }+ for (let i = pts.length - 1; i >= 0; i--) { const p = pts[i]; while (up.length > 1 && x(up[up.length - 2], up[up.length - 1], p) <= 0) up.pop(); up.push(p); }+ lo.pop(); up.pop();+ return lo.concat(up);+}++/** A ring laid flat at height z, projected. */+export const ringAt = (P: Projector, ring: readonly Sample[], z: number): Vec2[] => ring.map((q) => P(q.u, q.v, z));++/**+ * The samples whose normal faces the camera. The world direction of+ * screen-down is (sin az, cos az), so facing is a dot product with it.+ */+export const facing = (C: Camera) => {+ const s = Math.sin(C.az), c = Math.cos(C.az);+ return (q: Sample) => q.nu * s + q.nv * c >= -1e-6;+};++/** The one cyclic run of samples that pass `keep`, in ring order. */+export function run(ring: readonly Sample[], keep: (q: Sample) => boolean): Ring {+ const n = ring.length;+ let s = -1;+ for (let i = 0; i < n; i++) if (keep(ring[i]) && !keep(ring[(i + n - 1) % n])) { s = i; break; }+ if (s < 0) return keep(ring[0]) ? ring.slice() : [];+ const out: Ring = [];+ for (let k = 0; k < n && keep(ring[(s + k) % n]); k++) out.push(ring[(s + k) % n]);+ return out;+}++/**+ * A prism standing from z0 to z1. Its silhouette is the hull of the two rings,+ * so the vertical corners are never drawn; its only inner line is the crease,+ * the front run of an inset ring on the lid, which reads as a bevel.+ */+export function prism(+ P: Projector,+ front: (q: Sample) => boolean,+ ring: readonly Sample[],+ inner: readonly Sample[] | null | undefined,+ z0: number,+ z1: number,+): PrismPaths {+ return {+ sil: poly(hull(ringAt(P, ring, z1).concat(ringAt(P, ring, z0)))),+ crease: inner ? open(ringAt(P, run(inner, front), z1)) : "",+ };+}++/** A rounded footprint and its crease ring, inset by b. */+export const rings = (x0: number, y0: number, x1: number, y1: number, r: number, b: number): [Ring, Ring] => [+ rrect(x0, y0, x1, y1, r),+ rrect(x0 + b, y0 + b, x1 - b, y1 - b, Math.max(0.3, r - b)),+];++/** The leftmost, rightmost and nearest samples of a ring: where construction lines drop from. */+export function extremes(P: Projector, ring: readonly Sample[]): [Sample, Sample, Sample] {+ const pr = ring.map((q) => P(q.u, q.v, 0));+ let a = 0, b = 0, c = 0;+ pr.forEach((p, k) => { if (p[0] < pr[a][0]) a = k; if (p[0] > pr[b][0]) b = k; if (p[1] > pr[c][1]) c = k; });+ return [ring[a], ring[b], ring[c]];+}++/** Rounds every vertex of a closed polygon with a quadratic through the vertex; r per vertex. */+export function fillet(pts: readonly Vec2[], rs: readonly number[], n = 4): Vec2[] {+ const m = pts.length, out: Vec2[] = [];+ for (let i = 0; i < m; i++) {+ const a = pts[(i + m - 1) % m], p = pts[i], b = pts[(i + 1) % m];+ const la = Math.hypot(a[0] - p[0], a[1] - p[1]), lb = Math.hypot(b[0] - p[0], b[1] - p[1]);+ const t = Math.min(rs[i], la / 2, lb / 2);+ const p1 = [p[0] + ((a[0] - p[0]) / la) * t, p[1] + ((a[1] - p[1]) / la) * t];+ const p2 = [p[0] + ((b[0] - p[0]) / lb) * t, p[1] + ((b[1] - p[1]) / lb) * t];+ for (let k = 0; k <= n; k++) {+ const s = k / n, w = 1 - s;+ out.push([w * w * p1[0] + 2 * w * s * p[0] + s * s * p2[0], w * w * p1[1] + 2 * w * s * p[1] + s * s * p2[1]]);+ }+ }+ return out;+}++/**+ * A prism's mirror under its floor, as a path: the far edge of the reflection+ * and its two sides. `y0`/`y1` are where its fade starts (the floor's top) and+ * ends (just past the reflection's lowest point).+ */+export function ghost(+ P: Projector, front: (q: Sample) => boolean, ring: readonly Sample[], z0: number, depth: number,+): { d: string; y0: number; y1: number } {+ const f = run(ring, front), lowP = ringAt(P, f, z0 - depth);+ return {+ d: open(lowP) + [f[0], f[f.length - 1]].map((q) => seg(P(q.u, q.v, z0), P(q.u, q.v, z0 - depth))).join(""),+ y0: Math.min(...ringAt(P, f, z0).map((p) => p[1])),+ y1: Math.max(...lowP.map((p) => p[1])) + 2,+ };+}diff --git a/packages/hairline/src/core/motion.ts b/packages/hairline/src/core/motion.tsnew file mode 100644index 0000000..14866be--- /dev/null+++ b/packages/hairline/src/core/motion.ts@@ -0,0 +1,90 @@+import { clamp } from "./iso";++/**+ * Hairline — the two clocks, with no DOM. A discrete change (which card) gets+ * a long ease-out on a tween; a continuous input (where the pointer is) gets+ * a spring, because its target moves every frame and a timed ease would+ * always be chasing it. Both from the study (design/lab-hairline/cartilha-v2.html).+ *+ * Reduced motion is one flag here rather than a `matchMedia` call, so this+ * file stays pure and a test can flip it. The stage (components/hairline/+ * stage.ts) owns the only media query and writes the flag through+ * `setReducedMotion` before any figure ticks; figures read it with+ * `reducedMotion()`. With it on, springs and tweens land on their target in+ * one step.+ */++let reduced = false;+export const setReducedMotion = (on: boolean) => { reduced = on; };+export const reducedMotion = () => reduced;++export type Spring = { x: number; v: number; t: number; k: number; c: number; m: number; eps: number };+export type SpringOptions = { k?: number; c?: number; m?: number; eps?: number };++/** A spring at rest on x. k 100 · c 18 · m 1 unless told otherwise; `eps` is when it counts as settled. */+export function spring(x: number, o: SpringOptions = {}): Spring {+ return { x, v: 0, t: x, k: o.k ?? 100, c: o.c ?? 18, m: o.m ?? 1, eps: o.eps ?? 0.01 };+}++/**+ * Advances a spring by dt seconds toward `sp.t`, substepped at 240 Hz so a+ * long frame can't make it overshoot. Returns whether it is still moving.+ */+export function stepS(sp: Spring, dt: number): boolean {+ if (reduced) { sp.x = sp.t; sp.v = 0; return false; }+ const n = Math.max(1, Math.ceil(dt * 240)), h = dt / n;+ for (let i = 0; i < n; i++) {+ const a = (-sp.k * (sp.x - sp.t) - sp.c * sp.v) / sp.m;+ sp.v += a * h; sp.x += sp.v * h;+ }+ if (Math.abs(sp.x - sp.t) < sp.eps && Math.abs(sp.v) < sp.eps * 10) { sp.x = sp.t; sp.v = 0; return false; }+ return true;+}++/** A CSS cubic-bezier as a function of progress: Newton first, bisection if it strays. */+export function bezier(x1: number, y1: number, x2: number, y2: number): (t: number) => number {+ const cx = 3 * x1, bx = 3 * (x2 - x1) - cx, ax = 1 - cx - bx;+ const cy = 3 * y1, by = 3 * (y2 - y1) - cy, ay = 1 - cy - by;+ const X = (u: number) => ((ax * u + bx) * u + cx) * u;+ const Y = (u: number) => ((ay * u + by) * u + cy) * u;+ const dX = (u: number) => (3 * ax * u + 2 * bx) * u + cx;+ return (t) => {+ if (t <= 0) return 0;+ if (t >= 1) return 1;+ let u = t;+ for (let i = 0; i < 8; i++) {+ const e = X(u) - t;+ if (Math.abs(e) < 1e-5) break;+ const d = dX(u);+ if (Math.abs(d) < 1e-6) break;+ u -= e / d;+ }+ if (!(u >= 0 && u <= 1) || Math.abs(X(u) - t) > 1e-4) {+ let lo = 0, hi = 1;+ u = t;+ for (let i = 0; i < 24; i++) { if (X(u) < t) lo = u; else hi = u; u = (lo + hi) / 2; }+ }+ return Y(u);+ };+}++/** Linear's lift curve, 700ms (.32, .72, 0, 1): the discrete clock. */+export const EASE_LIFT = bezier(0.32, 0.72, 0, 1);++/**+ * A tween on EASE_LIFT. `t0` is when it starts (it may be in the future: that+ * is how a stagger delays it), `dur` how long it runs, in ms of `now`.+ */+export type Tween = { from: number; to: number; t0: number; dur: number };+export const tween = (v: number, dur = 700): Tween => ({ from: v, to: v, t0: -1e9, dur });+/** Where the tween is at `now`. */+export const tval = (tw: Tween, now: number) => {+ const p = clamp((now - tw.t0) / tw.dur, 0, 1);+ return tw.from + (tw.to - tw.from) * (reduced ? 1 : EASE_LIFT(p));+};+/** Retargets from wherever it is now, starting after `delay` ms. A no-op if the target is unchanged. */+export const tset = (tw: Tween, to: number, now: number, delay: number) => {+ if (tw.to === to) return;+ tw.from = tval(tw, now); tw.to = to; tw.t0 = now + delay;+};+export const tdone = (tw: Tween, now: number) => reduced || now >= tw.t0 + tw.dur;diff --git a/packages/hairline/src/core/stage.ts b/packages/hairline/src/core/stage.tsnew file mode 100644index 0000000..35dd292--- /dev/null+++ b/packages/hairline/src/core/stage.ts@@ -0,0 +1,240 @@+import {+ ghost, r2,+ type Camera, type PrismPaths, type Projector, type Sample, type Vec2,+} from "./iso";+import { setReducedMotion } from "./motion";++/**+ * Hairline — the DOM side every figure shares: making svg nodes, the helpers+ * that write a solid or a dot into them, one frame loop for all six figures,+ * the pointer, and the only reduced-motion query.+ *+ * Everything comes apart. A page navigates away and back, and React's+ * StrictMode mounts twice. So `register` hands back an unregister, `pointer`+ * a disposer, and `disposer()` collects them so a figure's `destroy` is one+ * call. Once the last figure is unregistered no frame, observer or media+ * listener is left behind, and the next `register` starts them again.+ *+ * Nothing here touches `window` at import: the module is evaluated during+ * a server render too, so the loop, the observer and the media query are+ * created by the first `register`.+ */++/* ---------- the contract ---------- */++/** Where an engine writes its caption. Only `textContent` is ever touched, so it need not be an element. */+export type Readout = { textContent: string | null };+export type FigureEls = { stage: HTMLElement; svg: SVGSVGElement; read: Readout };+export type FigureHandle = { set(value: number): void; destroy(): void };+export type FigureMount = (els: FigureEls, value: number) => FigureHandle;++/* ---------- svg ---------- */++const NS = "http://www.w3.org/2000/svg";+export type Attrs = Record<string, string | number>;++/** One svg element, with its attributes, appended to `parent` when there is one. */+export function mk<K extends keyof SVGElementTagNameMap>(tag: K, attrs?: Attrs | null, parent?: Element | null): SVGElementTagNameMap[K] {+ const e = document.createElementNS(NS, tag);+ if (attrs) for (const k in attrs) e.setAttribute(k, String(attrs[k]));+ if (parent) parent.appendChild(e);+ return e;+}++/** A solid's two paths in one group: the silhouette (`.sil`) and its crease (`.nf.lo`). */+export type Solid = { g: SVGGElement; sil: SVGPathElement; cr: SVGPathElement };+export function solid(parent: Element): Solid {+ const g = mk("g", {}, parent);+ return { g, sil: mk("path", { class: "sil" }, g), cr: mk("path", { class: "nf lo" }, g) };+}+/** Writes a prism's paths into a solid. */+export const put = (el: Solid, s: PrismPaths) => { el.sil.setAttribute("d", s.sil); el.cr.setAttribute("d", s.crease); };++/** A dot lying flat on a horizontal plane: an ellipse squashed by the camera. Position it with `place`. */+export const flatDot = (parent: Element, C: Camera, r: number, cls: string) =>+ mk("ellipse", { rx: r2(r * C.S), ry: r2(r * C.S * C.k), class: cls }, parent);+export const place = (el: SVGElement, q: Vec2) => { el.setAttribute("cx", String(r2(q[0]))); el.setAttribute("cy", String(r2(q[1]))); };++/** A vertical fade, as a mask, for reflections. Returns the `url(#…)` to put in a `mask` attribute. */+let fid = 0;+export function fade(svg: SVGSVGElement, y0: number, y1: number, a0 = 0.7): string {+ const id = "hl-fd" + ++fid, defs = mk("defs", {}, svg);+ const lg = mk("linearGradient", { id: id + "g", gradientUnits: "userSpaceOnUse", x1: 0, y1: r2(y0), x2: 0, y2: r2(y1) }, defs);+ mk("stop", { offset: 0, "stop-color": "#fff", "stop-opacity": a0 }, lg);+ mk("stop", { offset: 1, "stop-color": "#fff", "stop-opacity": 0 }, lg);+ const m = mk("mask", { id, maskUnits: "userSpaceOnUse", x: 0, y: 0, width: 400, height: 320 }, defs);+ mk("rect", { x: 0, y: 0, width: 400, height: 320, fill: `url(#${id}g)` }, m);+ return `url(#${id})`;+}++/** A prism's mirror under its floor: the far edge of the reflection and its two sides, fading out. */+export function reflect(+ svg: SVGSVGElement, parent: Element, P: Projector, front: (q: Sample) => boolean,+ ring: readonly Sample[], z0: number, depth: number,+) {+ const r = ghost(P, front, ring, z0, depth);+ const gh = mk("g", { class: "ghost", mask: fade(svg, r.y0, r.y1) }, parent);+ mk("path", { d: r.d }, gh);+}++/* ---------- one loop, asleep offscreen ---------- */++/** A figure's frame: dt in seconds (capped at 50ms), now in ms. Returns whether it wants another frame. */+export type Tick = (dt: number, now: number) => boolean | void;+export type Loop = {+ /** Ask for frames again after input; the loop runs until the tick returns false. */+ wake(): void;+ /** Leave the loop and the observer. Idempotent. */+ unregister(): void;+};+type Board = { stage: Element; tick: Tick; vis: boolean; awake: boolean };++let boards: Board[] = [];+const byStage = new Map<Element, Board>();+let raf = 0, last = 0;+let io: IntersectionObserver | null = null;+let rm: MediaQueryList | null = null;++function frame(now: number) {+ const dt = Math.min(0.05, Math.max(0, (now - last) / 1000));+ last = now;+ let any = false;+ for (const b of boards.slice()) if (b.vis && b.awake) { b.awake = !!b.tick(dt, now); any = any || b.awake; }+ raf = any ? requestAnimationFrame(frame) : 0;+}++function wake(b: Board) {+ b.awake = true;+ if (!raf) { last = performance.now(); raf = requestAnimationFrame(frame); }+}++const onMotion = () => { setReducedMotion(!!rm?.matches); boards.forEach(wake); };++/** The observer and the media query exist while at least one figure is registered. */+function start() {+ if (io) return;+ io = new IntersectionObserver((es) => {+ for (const e of es) {+ const b = byStage.get(e.target);+ if (!b) continue;+ b.vis = e.isIntersecting;+ if (b.vis) wake(b);+ }+ }, { rootMargin: "80px" });+ rm = matchMedia("(prefers-reduced-motion: reduce)");+ setReducedMotion(rm.matches);+ rm.addEventListener("change", onMotion);+}++function stop() {+ if (raf) cancelAnimationFrame(raf);+ raf = 0;+ io?.disconnect(); io = null;+ rm?.removeEventListener("change", onMotion); rm = null;+}++/**+ * Joins the shared loop. The tick runs once now, so the figure is drawn+ * before it is ever on screen, then on every frame while its stage is within+ * 80px of the viewport and it keeps returning true. Offscreen it sleeps.+ */+export function register(stage: Element, tick: Tick): Loop {+ start();+ const b: Board = { stage, tick, vis: false, awake: true };+ boards.push(b);+ byStage.set(stage, b);+ io!.observe(stage);+ tick(0, performance.now());+ let gone = false;+ return {+ wake: () => { if (!gone) wake(b); },+ unregister: () => {+ if (gone) return;+ gone = true;+ boards = boards.filter((x) => x !== b);+ if (byStage.get(stage) === b) { byStage.delete(stage); io?.unobserve(stage); }+ if (!boards.length) stop();+ },+ };+}++/* ---------- pointer ---------- */++export type PointerHandlers = {+ /** The pointer in viewBox units (400 × 320). */+ move(p: Vec2, e: PointerEvent): void;+ /** A press; `move` when absent. */+ down?(p: Vec2, e: PointerEvent): void;+ leave(e: PointerEvent): void;+};++/**+ * Pointer input in viewBox units. A mouse leaving acts at once; a finger+ * lifting holds the pose for 1.4s first, so a tap reads as a look rather than+ * a flash. Touch releases its capture on press, so dragging across the stage+ * keeps sending moves. Returns the disposer.+ */+export function pointer(stage: HTMLElement, on: PointerHandlers): () => void {+ let tm = 0;+ const pt = (e: PointerEvent): Vec2 => {+ const r = stage.getBoundingClientRect();+ return [((e.clientX - r.left) / r.width) * 400, ((e.clientY - r.top) / r.height) * 320];+ };+ const move = (e: PointerEvent) => { clearTimeout(tm); on.move(pt(e), e); };+ const down = (e: PointerEvent) => {+ clearTimeout(tm);+ if (e.pointerType !== "mouse") stage.releasePointerCapture?.(e.pointerId);+ if (on.down) on.down(pt(e), e); else on.move(pt(e), e);+ };+ const leave = (e: PointerEvent) => {+ clearTimeout(tm);+ tm = window.setTimeout(() => on.leave(e), e.pointerType === "mouse" ? 0 : 1400);+ };+ stage.addEventListener("pointermove", move);+ stage.addEventListener("pointerdown", down);+ stage.addEventListener("pointerleave", leave);+ return () => {+ clearTimeout(tm);+ stage.removeEventListener("pointermove", move);+ stage.removeEventListener("pointerdown", down);+ stage.removeEventListener("pointerleave", leave);+ };+}++/* ---------- tear-down ---------- */++export type Disposer = {+ /** Something to run on dispose: a Loop's unregister, pointer()'s return, a clearTimeout. */+ add(fn: () => void): void;+ /** addEventListener, removed on dispose. */+ on<K extends keyof HTMLElementEventMap>(target: HTMLElement, type: K, fn: (e: HTMLElementEventMap[K]) => void, opts?: AddEventListenerOptions): void;+ /** Runs everything added, last first, once. */+ dispose(): void;+};++/**+ * Collects a figure's tear-down, so its `destroy` can be `bag.dispose`:+ *+ * const bag = disposer();+ * const B = register(stage, tick); bag.add(B.unregister);+ * bag.add(pointer(stage, { move, leave }));+ * bag.on(stage, "keydown", onKey);+ * bag.add(() => svg.replaceChildren());+ * return { set, destroy: bag.dispose };+ */+export function disposer(): Disposer {+ let fns: Array<() => void> = [];+ return {+ add: (fn) => { fns.push(fn); },+ on: (target, type, fn, opts) => {+ const h = fn as EventListener;+ target.addEventListener(type, h, opts);+ fns.push(() => target.removeEventListener(type, h, opts));+ },+ dispose: () => {+ const run = fns;+ fns = [];+ for (let i = run.length - 1; i >= 0; i--) run[i]();+ },+ };+}diff --git a/packages/hairline/src/figures/exploded.ts b/packages/hairline/src/figures/exploded.tsnew file mode 100644index 0000000..9273d40--- /dev/null+++ b/packages/hairline/src/figures/exploded.ts@@ -0,0 +1,119 @@+import {+ Cam, clamp, extremes, facing, fit, poly, prism, proj, ringAt, rings, rrect, seg,+ type Ring, type Sample, type Vec2,+} from "../core/iso";+import { spring, stepS } from "../core/motion";+import { disposer, flatDot, mk, place, pointer, put, register, solid, type FigureMount, type Solid } from "../core/stage";++/**+ * Exploded — an app window taken apart into surface, sidebar, card and+ * popover. The pointer's x scrubs the gap through a spring; its y picks a+ * layer, which gets the bright edge, and its name and lift go to the+ * read-out. The bright edge is the whole callout. From the study's third+ * figure (design/lab-hairline/cartilha-v2.html).+ *+ * Picking is tested against the target gap, not the gap on screen, so the+ * layer under the pointer is the one it will be under once the spring lands.+ * Each layer's dashed drops (from its outermost points down to the layer+ * below) are painted before its plate, so a plate hides the guides behind it.+ */++type Rect = [number, number, number, number];+type Layer = {+ name: string;+ /** Footprint, window units: x0, y0, x1, y1. */+ r: Rect;+ rad: number;+ /** Content marks drawn on the top face. */+ segs: [Vec2, Vec2][];+ /** Traffic-light dots (surface only). */+ dots?: Vec2[];+ /** A selected row outlined in the silhouette's stroke (popover only). */+ sel?: Rect;+};++const LAY: Layer[] = [+ { name: "surface", r: [0, 0, 132, 96], rad: 7, segs: [[[1.5, 12], [130.5, 12]]], dots: [[7, 6], [13, 6], [19, 6]] },+ { name: "sidebar", r: [5, 17, 38, 91], rad: 4, segs: [[[10, 25], [28, 25]], [[10, 33], [32, 33]], [[10, 41], [24, 41]], [[10, 49], [30, 49]], [[10, 83], [22, 83]]] },+ { name: "card", r: [48, 22, 120, 62], rad: 5, segs: [[[54, 30], [92, 30]], [[54, 38], [112, 38]], [[54, 46], [104, 46]], [[54, 54], [80, 54]]] },+ { name: "popover", r: [80, 50, 126, 86], rad: 4, segs: [[[86, 58], [118, 58]], [[86, 74], [116, 74]], [[86, 80], [108, 80]]], sel: [83, 62, 123, 70] },+];++/** The gap's share of the max at rest (pointer away), and each slab's thickness. */+const REST = 0.18, TK = 2.4;++/** Even-odd point-in-polygon. */+function inside(pt: Vec2, pg: readonly Vec2[]) {+ let c = false;+ for (let i = 0, j = pg.length - 1; i < pg.length; j = i++) {+ const [xi, yi] = pg[i], [xj, yj] = pg[j];+ if ((yi > pt[1]) !== (yj > pt[1]) && pt[0] < ((xj - xi) * (pt[1] - yi)) / (yj - yi) + xi) c = !c;+ }+ return c;+}++export const mount: FigureMount = ({ stage, svg, read }, value) => {+ const bag = disposer();+ let GAP = value, act = -1, lastP: Vec2 | null = null;+ const e = spring(REST, { eps: 0.002 });+ const C = Cam(45, 0.5, 1.42);+ fit(C, [[0, 0, 0], [132, 96, 0], [132, 0, 0], [0, 96, 0], [0, 0, 3 * 34 + TK], [132, 0, 3 * 34 + TK]], 180, 166);+ const P = proj(C), front = facing(C);+ const g = mk("g", {}, svg);++ const els = LAY.map((L, i) => {+ const [ring, inner] = rings(...L.r, L.rad, 1.3);+ const ext: Sample[] = extremes(P, ring);+ // The guide goes in before the plate: paint order is what hides it.+ const guide = i > 0 ? mk("path", { class: "nf dash" }, g) : null;+ const el: Solid = solid(g);+ const marks = mk("path", { class: "nf" }, el.g);+ const selRing: Ring | null = L.sel ? rrect(...L.sel, 2) : null;+ const selEl = L.sel ? mk("path", { class: "nf sil" }, el.g) : null;+ const dotEls = L.dots ? L.dots.map(() => flatDot(el.g, C, 1.6, "nf")) : null;+ return { ring, inner, ext, guide, el, marks, selRing, selEl, dotEls };+ });++ const corners = ([x0, y0, x1, y1]: Rect, z: number): Vec2[] => [P(x0, y0, z), P(x1, y0, z), P(x1, y1, z), P(x0, y1, z)];+ /** The topmost layer under the pointer, tested where the layers are going (target gap), not where they are. */+ function pick(p: Vec2 | null) {+ if (!p) return -1;+ for (let i = LAY.length - 1; i >= 0; i--) if (inside(p, corners(LAY[i].r, i * GAP * e.t + TK))) return i;+ return -1;+ }+ function setAct(a: number) {+ if (a === act) return;+ act = a;+ els.forEach((E, i) => E.el.sil.classList.toggle("hi", i === a));+ B.wake();+ }++ const B = register(stage, (dt) => {+ const m = stepS(e, dt), z = (i: number) => i * GAP * e.x;+ LAY.forEach((L, i) => {+ const E = els[i], zi = z(i), zt = zi + TK;+ put(E.el, prism(P, front, E.ring, E.inner, zi, zt));+ E.marks.setAttribute("d", L.segs.map(([a, b]) => seg(P(a[0], a[1], zt), P(b[0], b[1], zt))).join(""));+ if (E.selEl && E.selRing) E.selEl.setAttribute("d", poly(ringAt(P, E.selRing, zt)));+ if (E.dotEls && L.dots) L.dots.forEach(([dx, dy], k) => place(E.dotEls![k], P(dx, dy, zt)));+ if (E.guide) {+ const zp = z(i - 1) + TK;+ E.guide.setAttribute("d", E.ext.map((q) => seg(P(q.u, q.v, zi), P(q.u, q.v, zp))).join(""));+ }+ });+ read.textContent = act >= 0 ? `0${act + 1} · ${LAY[act].name} · z ${z(act).toFixed(1)}` : `gap ${(GAP * e.x).toFixed(1)}`;+ return m;+ });+ bag.add(B.unregister);++ bag.add(pointer(stage, {+ move: (p) => { lastP = p; e.t = REST + (1 - REST) * clamp((p[0] - 60) / 280, 0, 1); setAct(pick(p)); B.wake(); },+ leave: () => { lastP = null; e.t = REST; setAct(-1); B.wake(); },+ }));+ bag.add(() => svg.replaceChildren());++ return {+ set: (v) => { GAP = v; if (lastP) setAct(pick(lastP)); B.wake(); },+ destroy: bag.dispose,+ };+};diff --git a/packages/hairline/src/figures/phosphor.ts b/packages/hairline/src/figures/phosphor.tsnew file mode 100644index 0000000..1ba35bb--- /dev/null+++ b/packages/hairline/src/figures/phosphor.ts@@ -0,0 +1,116 @@+import {+ Cam, fit, proj, unproj, facing, rings, prism, rrect, ringAt, extremes, poly, seg, clamp, lerp,+ type Vec2,+} from "../core/iso";+import { reducedMotion } from "../core/motion";+import {+ mk, solid, put, flatDot, place, reflect, register, pointer, disposer,+ type FigureMount,+} from "../core/stage";++/**+ * Phosphor (Fig 9.4): a 7 × 7 dot matrix you can paint on. Each dot holds an+ * intensity that decays with persistence τ (the slider, in ms). At idle a+ * loop of frames, seven row bytes each, excites the dots; the pointer+ * excites them instead, and the loop fades back in 1.2s after it leaves.+ * Ambient: the tick always asks for another frame, so it runs whenever the+ * stage is on screen and the shared observer puts it to sleep when it isn't.+ * Ported from the study's `#phosphor` (design/lab-hairline/cartilha-v2.html).+ */++const N = 7, PITCH = 10, M = 8, EXT = M * 2 + PITCH * (N - 1), T = 5, R = 2.5, DROP = 15, BT = 4, BO = 7;+/** The loop, seven row bytes per frame (MSB = left column): a ripple out from the centre, a pause, a diagonal sweep, a pause. */+const LOOP = [+ [0, 0, 0, 8, 0, 0, 0], [0, 0, 8, 20, 8, 0, 0], [0, 28, 34, 34, 34, 28, 0], [28, 34, 65, 65, 65, 34, 28], [65, 0, 0, 0, 0, 0, 65],+ [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0],+ [64, 0, 0, 0, 0, 0, 0], [32, 64, 0, 0, 0, 0, 0], [16, 32, 64, 0, 0, 0, 0], [8, 16, 32, 64, 0, 0, 0], [4, 8, 16, 32, 64, 0, 0], [2, 4, 8, 16, 32, 64, 0], [1, 2, 4, 8, 16, 32, 64],+ [0, 1, 2, 4, 8, 16, 32], [0, 0, 1, 2, 4, 8, 16], [0, 0, 0, 1, 2, 4, 8], [0, 0, 0, 0, 1, 2, 4], [0, 0, 0, 0, 0, 1, 2], [0, 0, 0, 0, 0, 0, 1],+ [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0],+];+const FRAME_MS = 110;+/** The loop waits this long after the pointer leaves, then fades its gain in over RAMP. */+const RESUME = 1200, RAMP = 400;+/** A painted dot at full, its four neighbours at this share. */+const SPLASH: readonly [number, number, number][] = [[0, 0, 1], [1, 0, 0.45], [-1, 0, 0.45], [0, 1, 0.45], [0, -1, 0.45]];++const lit = (f: number, r: number, c: number) => (LOOP[f][r] >> (N - 1 - c)) & 1;++export const mount: FigureMount = ({ stage, svg, read }, value) => {+ const bag = disposer();+ let tau = value, clock = 0, lastFrame = -1, leftAt = -1e9, painting = false;+ let prev: Vec2 | null = null;++ const C = Cam(45, 0.5, 2.12), ZB = -DROP - BT;+ fit(C, [[-BO, -BO, ZB], [EXT + BO, EXT + BO, ZB - 6], [EXT + BO, -BO, ZB], [-BO, EXT + BO, ZB], [0, 0, T]], 200, 160);+ const P = proj(C), front = facing(C);+ const g = mk("g", {}, svg);++ // base plate, its reflection, then the dashed drops, then the tile over them+ const [br, bi] = rings(-BO, -BO, EXT + BO, EXT + BO, 11, 1.8);+ reflect(svg, g, P, front, br, ZB, 12);+ put(solid(g), prism(P, front, br, bi, ZB, -DROP));+ const [tr, ti] = rings(0, 0, EXT, EXT, 7, 1.3);+ mk("path", { d: extremes(P, tr).map((q) => seg(P(q.u, q.v, 0), P(q.u, q.v, -DROP))).join(""), class: "nf dash" }, g);+ put(solid(g), prism(P, front, tr, ti, 0, T));+ mk("path", { d: poly(ringAt(P, rrect(3.5, 3.5, EXT - 3.5, EXT - 3.5, 4.5, 5), T)), class: "nf lo" }, g);++ const I = new Float32Array(N * N);+ const dots: SVGEllipseElement[] = [];+ for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) {+ const d = flatDot(g, C, R, "dot");+ place(d, P(M + c * PITCH, M + r * PITCH, T));+ dots.push(d);+ }++ /** Lights the cell nearest a point on the tile, and its neighbours less, never dimming what is brighter. */+ function excite(x: number, y: number, amt: number) {+ const c = Math.round((x - M) / PITCH), r = Math.round((y - M) / PITCH);+ for (const [dr, dc, k] of SPLASH) {+ const rr = r + dr, cc = c + dc;+ if (rr < 0 || rr >= N || cc < 0 || cc >= N) continue;+ I[rr * N + cc] = Math.max(I[rr * N + cc], amt * k);+ }+ }++ const B = register(stage, (dt, now) => {+ if (reducedMotion() && !painting) {+ // no loop: settle on a composed still, the ripple's widest ring+ for (let i = 0; i < N * N; i++) I[i] = Math.max(I[i] * Math.exp((-dt * 1000) / tau), lit(3, Math.floor(i / N), i % N) * 0.8);+ } else {+ const decay = Math.exp((-dt * 1000) / tau);+ for (let i = 0; i < N * N; i++) I[i] *= decay;+ const gain = painting ? 0 : clamp((now - leftAt - RESUME) / RAMP, 0, 1);+ if (gain > 0) {+ clock += dt * 1000;+ const f = Math.floor(clock / FRAME_MS) % LOOP.length;+ if (f !== lastFrame) {+ lastFrame = f;+ for (let r = 0; r < N; r++) for (let c = 0; c < N; c++) if (lit(f, r, c)) I[r * N + c] = Math.max(I[r * N + c], gain);+ }+ read.textContent = `loop · ${String(f + 1).padStart(2, "0")}/${LOOP.length}`;+ } else read.textContent = painting ? "paint" : "afterglow";+ }+ for (let i = 0; i < N * N; i++) dots[i].setAttribute("opacity", (0.14 + 0.86 * clamp(I[i], 0, 1)).toFixed(3));+ return true;+ });+ bag.add(B.unregister);++ bag.add(pointer(stage, {+ move: (p) => {+ painting = true;+ const q = unproj(C, p[0], p[1], T);+ // fill in between moves, so a fast stroke leaves a line rather than dots+ if (prev) {+ const n = Math.ceil(Math.hypot(q[0] - prev[0], q[1] - prev[1]) / 3);+ for (let k = 1; k <= n; k++) excite(lerp(prev[0], q[0], k / n), lerp(prev[1], q[1], k / n), 1);+ } else excite(q[0], q[1], 1);+ prev = q;+ B.wake();+ },+ // the resume is a timestamp the tick reads, not a timer, so re-entering or tearing down has nothing to cancel+ leave: () => { painting = false; prev = null; leftAt = performance.now(); clock = 0; lastFrame = -1; B.wake(); },+ }));++ bag.add(() => svg.replaceChildren());+ return { set: (v) => { tau = v; }, destroy: bag.dispose };+};diff --git a/packages/hairline/src/figures/riffle-geometry.ts b/packages/hairline/src/figures/riffle-geometry.tsnew file mode 100644index 0000000..a543420--- /dev/null+++ b/packages/hairline/src/figures/riffle-geometry.ts@@ -0,0 +1,97 @@+import {+ Cam, facing, fillet, fit, hull, open, poly, proj, rad, ringAt, rrect, run, seg,+ type Camera, type Projector, type Ring, type Sample, type Vec2,+} from "../core/iso";++/**+ * Riffle's drawing, with no DOM: the camera, the tray and a card in any pose,+ * as path strings. The engine (riffle.ts) writes these into its svg on every+ * frame.+ */++export const N = 8, W = 84, H = 54, G = 13, TW = 22, TH = 7, TABS = [6, 31, 56], TK = 1.4;+export const REST = -12, BACK = -24, FWD = 20, LIFT = 16;+export const X0 = -5, X1 = W + 5, Y0 = -9, Y1 = (N - 1) * G + 9, WH = 20, WR = 6, WT = 2.4;++/** The camera, fitted to the tray with a card lifted, so nothing leaves the frame in any pose. */+export function camera(): Camera {+ const C = Cam(45, 0.5, 1.62);+ fit(C, [[X0, Y0, 0], [X1, Y1, -8], [X1, Y0, 0], [X0, Y1, 0], [X0, Y0, H + TH], [X1, Y0, H + TH + LIFT]], 200, 166);+ return C;+}++/** The tray's outline and the rim's inner edge. */+export const trayRings = (): { outer: Ring; inner: Ring } => ({+ outer: rrect(X0, Y0, X1, Y1, WR, 6),+ inner: rrect(X0 + WT, Y0 + WT, X1 - WT, Y1 - WT, WR - WT, 6),+});++/** A run of points ordered left to right on screen. */+const LR = (pts: Vec2[]) => (pts[0][0] <= pts[pts.length - 1][0] ? pts : pts.slice().reverse());++/**+ * The tray's paths, which never move. `far` is painted before the cards, `near`+ * after them; each entry is [d, class].+ */+export function tray(P: Projector, front: (q: Sample) => boolean, outer: Ring, inner: Ring) {+ // far half: body, the rim's inner edge, and the floor seam along the far walls+ const far: [string, string][] = [+ [poly(hull(ringAt(P, outer, 0).concat(ringAt(P, outer, WH)))), "sil"],+ [poly(ringAt(P, inner, WH)), "nf"],+ [open(ringAt(P, run(inner, (q) => !front(q)), 2.5)), "nf lo"],+ ];+ // near half: one opaque piece from the rim's inner edge down to the floor+ const iF = LR(ringAt(P, run(inner, front), WH)), oT = LR(ringAt(P, run(outer, front), WH)), oB = LR(ringAt(P, run(outer, front), 0));+ // a finger pull, set into the front+ const hx = (X0 + X1) / 2, onFront = (ring: Ring) => ring.map((q) => P(q.u, Y1, q.v));+ const near: [string, string][] = [+ [poly([...iF, oT[oT.length - 1], ...oB.slice().reverse(), oT[0]]), "fo"],+ [open(oT), "nf lo"],+ [open(iF), "nf"],+ [open([oT[0], ...oB, oT[oT.length - 1]]), "nf sil"],+ [poly(onFront(rrect(hx - 11, 6.5, hx + 11, 12.5, 3, 5))), "nf"],+ [poly(onFront(rrect(hx - 9.4, 8, hx + 9.4, 11, 1.5, 5))), "nf lo"],+ ];+ return { far, near };+}++/**+ * Card i, back to front: its number (8 at the back), which of the three tab+ * positions it takes, and its filleted outline, drawn upright in its own plane.+ */+export function card(i: number) {+ const n = N - i, t0 = TABS[(N - 1 - i) % 3];+ const shape = fillet(+ [[0, 0], [W, 0], [W, H], [t0 + TW, H], [t0 + TW, H + TH], [t0, H + TH], [t0, H], [0, H]],+ [1, 1, 3.2, 1.8, 2.4, 2.4, 1.8, 3.2],+ );+ return { n, t0, shape };+}++export type CardPose = { back: string; face: string; head: string; rules: string; punch: Vec2[] };++/**+ * Card i leaning th degrees (negative leans back) and lifted by `lift`: its+ * back edge, face, heading and rules as paths, and where each of the eight+ * punches of its number sits, in a 4 × 2 grid on the tab.+ */+export function pose(P: Projector, i: number, t0: number, shape: readonly Vec2[], th: number, lift: number): CardPose {+ const yb = i * G, s = Math.sin(rad(th)), c = Math.cos(rad(th));+ const w = (u: number, v: number) => P(u, yb + v * s, v * c + lift);+ const wb = (u: number, v: number) => P(u, yb + v * s - TK * c, v * c + TK * s + lift);+ const punch: Vec2[] = [];+ for (let k = 0; k < 8; k++) punch.push(w(t0 + TW / 2 + ((k % 4) - 1.5) * 3.6, H + TH / 2 + (0.5 - Math.floor(k / 4)) * 2.8));+ return {+ back: poly(shape.map((p) => wb(p[0], p[1]))),+ face: poly(shape.map((p) => w(p[0], p[1]))),+ head: seg(w(6, H - 11), w(W - 6, H - 11)),+ rules: [H - 18, H - 25, H - 32, H - 39].map((v) => seg(w(6, v), w(W - 6, v))).join(""),+ punch,+ };+}++/** The fitted camera, its projector and facing test, and the tray's rings: what both the engine and the still start from. */+export function scene() {+ const C = camera();+ return { C, P: proj(C), front: facing(C), ...trayRings() };+}diff --git a/packages/hairline/src/figures/riffle.ts b/packages/hairline/src/figures/riffle.tsnew file mode 100644index 0000000..37af295--- /dev/null+++ b/packages/hairline/src/figures/riffle.ts@@ -0,0 +1,133 @@+import { clamp, poly, rad, type Vec2 } from "../core/iso";+import { tdone, tset, tval, tween, type Tween } from "../core/motion";+import { BACK, FWD, G, H, LIFT, N, REST, W, card, pose, scene, tray } from "./riffle-geometry";+import { disposer, mk, place, pointer, reflect, register, type FigureEls, type FigureHandle } from "../core/stage";++/**+ * Riffle (Fig 9.1) — a rounded tray holding eight cards. The card under the pointer stands up and lifts; the ones in front+ * lean forward and the ones behind lean back, staggered outwards from it on+ * the 700ms lift curve. A discrete figure, so every card runs on tweens.+ *+ * Selection never reads the posed cards: it comes from static oblique bands+ * along the resting top edges, so a card moving out from under the pointer+ * can't flip the choice back and forth. `bands(true)` shows them. The stage+ * is a focusable group; the arrow keys walk the cards and the read-out names+ * the one pulled: its number, and its name when `labels` gave it one.+ *+ * The drawing itself — camera, tray, a card in any pose — is pure and lives in+ * riffle-geometry.ts; this file is the DOM, the tweens and the input.+ */++export type RiffleHandle = FigureHandle & {+ /** Shows or hides the hit bands. */+ bands(on: boolean): void;+ /** Names for the cards, card 01 first. A card without a name is read out by its number alone. */+ labels(list: readonly string[]): void;+};++type Card = {+ n: number; t0: number; shape: Vec2[];+ back: SVGPathElement; face: SVGPathElement; head: SVGPathElement; rules: SVGPathElement;+ punch: SVGCircleElement[];+ /** Lean in degrees, and lift. */+ a: Tween; z: Tween;+};++export const mount = ({ stage, svg, read }: FigureEls, value: number): RiffleHandle => {+ const bag = disposer();+ let stag = value;+ let names: readonly string[] = [];++ const { P, front, outer, inner } = scene();+ const paths = tray(P, front, outer, inner);++ const g = mk("g", {}, svg);+ reflect(svg, g, P, front, outer, 0, 14);+ for (const [d, cls] of paths.far) mk("path", { d, class: cls }, g);++ const cards: Card[] = [];+ for (let i = 0; i < N; i++) {+ const { n, t0, shape } = card(i);+ const grp = mk("g", {}, g);+ const back = mk("path", { class: "lo" }, grp), face = mk("path", { class: "sil" }, grp);+ const head = mk("path", { class: "nf" }, grp), rules = mk("path", { class: "nf lo" }, grp);+ // the card's number, punched in a 4 × 2 grid on its tab+ const punch: SVGCircleElement[] = [];+ for (let k = 0; k < 8; k++) punch.push(mk("circle", { r: 1.05, class: "dot " + (k === n - 1 ? "m" : "off") }, grp));+ cards.push({ n, t0, shape, back, face, head, rules, punch, a: tween(REST), z: tween(0) });+ }++ for (const [d, cls] of paths.near) mk("path", { d, class: cls }, g);++ // hit bands: oblique strips along the RESTING top edges. They never move.+ const top = (i: number) => P(W / 2, i * G + H * Math.sin(rad(REST)), H * Math.cos(rad(REST)));+ const c0 = top(0), c1 = top(1), d = [c1[0] - c0[0], c1[1] - c0[1]];+ const px0 = P(0, 0, 0), px1 = P(1, 0, 0), ex = [px1[0] - px0[0], px1[1] - px0[1]];+ const HALF = W / 2 + 6, det = d[0] * ex[1] - d[1] * ex[0];+ const bandG = mk("g", { class: "bands" }, g), bands: SVGPathElement[] = [];+ const at = (s: number, r: number): Vec2 => [c0[0] + s * d[0] + r * ex[0], c0[1] + s * d[1] + r * ex[1]];+ for (let i = 0; i < N; i++) bands.push(mk("path", { d: poly([at(i - 0.5, -HALF), at(i - 0.5, HALF), at(i + 0.5, HALF), at(i + 0.5, -HALF)]) }, bandG));++ /** The card whose band holds the point, in the band's own (s, r) coordinates; -1 outside. */+ function hit([x, y]: Vec2) {+ const qx = x - c0[0], qy = y - c0[1];+ const s = (qx * ex[1] - qy * ex[0]) / det, r = (d[0] * qy - d[1] * qx) / det;+ if (Math.abs(r) > HALF || s < -0.5 || s > N + 1) return -1;+ return clamp(Math.round(s), 0, N - 1);+ }++ function draw(i: number, th: number, lift: number) {+ const cd = cards[i], q = pose(P, i, cd.t0, cd.shape, th, lift);+ cd.back.setAttribute("d", q.back);+ cd.face.setAttribute("d", q.face);+ cd.head.setAttribute("d", q.head);+ cd.rules.setAttribute("d", q.rules);+ cd.punch.forEach((el, k) => place(el, q.punch[k]));+ }++ const B = register(stage, (_dt, now) => {+ let moving = false;+ cards.forEach((cd, i) => { draw(i, tval(cd.a, now), tval(cd.z, now)); if (!tdone(cd.a, now) || !tdone(cd.z, now)) moving = true; });+ return moving;+ });+ bag.add(B.unregister);++ let act = -1;+ const caption = (a: number) => {+ if (a < 0) return "rest";+ const n = N - a, name = names[n - 1];+ return String(n).padStart(2, "0") + (name ? ` · ${name}` : "");+ };+ /** Pulls card a (-1 puts them all back). The stagger spreads out from the card pulled, or the one let go. */+ function setActive(a: number) {+ if (a === act) return;+ const now = performance.now(), from = a >= 0 ? a : act;+ act = a;+ cards.forEach((cd, i) => {+ const delay = Math.abs(i - from) * stag;+ const th = a < 0 ? REST : i < a ? BACK : i > a ? FWD : 0;+ tset(cd.a, th, now, delay); tset(cd.z, a === i ? LIFT : 0, now, delay);+ cd.face.classList.toggle("hi", i === a); cd.head.classList.toggle("hi", i === a); cd.punch[cd.n - 1].classList.toggle("m", i !== a);+ });+ bands.forEach((b, i) => b.classList.toggle("on", i === a));+ read.textContent = caption(a);+ B.wake();+ }++ bag.add(pointer(stage, { move: (p) => setActive(hit(p)), leave: () => setActive(-1) }));+ bag.on(stage, "keydown", (e) => {+ if (e.key === "ArrowLeft" || e.key === "ArrowDown") { setActive(act < 0 ? N - 1 : Math.min(N - 1, act + 1)); e.preventDefault(); }+ else if (e.key === "ArrowRight" || e.key === "ArrowUp") { setActive(act < 0 ? N - 1 : Math.max(0, act - 1)); e.preventDefault(); }+ // Escape puts a pulled card back and claims the key; at rest it passes on to the page.+ else if (e.key === "Escape" && act >= 0) { setActive(-1); e.preventDefault(); }+ });+ bag.on(stage, "blur", () => setActive(-1));+ bag.add(() => svg.replaceChildren());++ return {+ set: (v) => { stag = v; },+ bands: (on) => { bandG.classList.toggle("show", on); },+ labels: (list) => { names = list; if (act >= 0) read.textContent = caption(act); },+ destroy: bag.dispose,+ };+};diff --git a/packages/hairline/src/figures/slow.ts b/packages/hairline/src/figures/slow.tsnew file mode 100644index 0000000..a1e704e--- /dev/null+++ b/packages/hairline/src/figures/slow.ts@@ -0,0 +1,143 @@+import { Cam, fit, proj, unproj, facing, rings, prism, clamp, r2, seg, type Vec2 } from "../core/iso";+import { spring, stepS, reducedMotion } from "../core/motion";+import {+ mk, solid, put, flatDot, place, register, pointer, disposer,+ type FigureMount, type Solid,+} from "../core/stage";++/**+ * Fig 9.5, Slow — hover dilates the clock. Crates ride a belt through a gate,+ * growing in at one end and out at the other, each lid carrying its serial as+ * a 3 × 3 dot code. Hovering never stops the world: it springs the clock's+ * rate down to the slider's value, so everything keeps moving, just slowly+ * enough to read. The crate nearest the pointer lifts and its serial goes to+ * the read-out. The gate's two posts and lintel are depth-sorted with the+ * crates, and brighten as a crate passes under them. Ported from the study's `#slow`+ * (design/lab-hairline/cartilha-v2.html).+ *+ * Ambient: the loop runs every frame while the stage is on screen (the stage+ * puts it to sleep offscreen). Under reduced motion the resting rate is 0, so+ * the belt stands still until hovered, when it creeps at the slider's rate.+ */++const L = 210, BW = 26, BT = 5, CUBE = 15, NC = 6, SPEED = 1 / 9, GATE = L * 0.62, GH = 38;++type Crate = Solid & { dots: SVGEllipseElement[] };+type Item = { j: number; x: number; s: number; serial: number };++/** How big a crate is at belt position u (0..1): smoothstep in over the first 8%, out over the last. */+const size = (u: number) => { const a = clamp(Math.min(u, 1 - u) / 0.08, 0, 1); return a * a * (3 - 2 * a); };++/**+ * How lit the gate is by a crate at x: a cos² swell, full under the lintel. It+ * rises over half the gap between crates (about .75s at full speed) and falls+ * over half that once the crate is through (about .37s), so the gate breathes+ * in and lets go. Read off the belt, not a timer, so it slows with the clock.+ */+const RISE = L / NC / 2, FALL = RISE / 2;+const glow = (x: number) => {+ const d = x - GATE, w = d < 0 ? RISE : FALL;+ return Math.abs(d) >= w ? 0 : Math.cos((Math.PI / 2) * (Math.abs(d) / w)) ** 2;+};++export const mount: FigureMount = ({ stage, svg, read }, value) => {+ const bag = disposer();+ let slow = value, over: Vec2 | null = null, clock = 2.4;+ const rate = spring(1, { eps: 0.002 });+ const C = Cam(45, 0.5, 1.8);+ fit(C, [[0, 0, 0], [L, BW, 0], [L, 0, 0], [0, BW, 0], [0, 0, GH], [GATE, -8, GH]], 200, 168);+ const P = proj(C), front = facing(C);+ const g = mk("g", {}, svg);+ const [bR, bI] = rings(0, 0, L, BW, 5, 1.3);+ put(solid(g), prism(P, front, bR, bI, 0, BT));+ const slats = mk("path", { class: "nf lo" }, g);+ // crates and the gate share one layer, re-sorted by depth (x + y at 45°) every frame+ const layer = mk("g", {}, g);+ const pool: Crate[] = [];+ for (let j = 0; j < NC; j++) {+ const el: Crate = { ...solid(layer), dots: [] };+ for (let k = 0; k < 9; k++) el.dots.push(flatDot(el.g, C, 1, "dot off"));+ pool.push(el);+ }+ // the lintel's key is past both posts and every crate under it, so it paints last among its neighbours+ const gate = ([[-8, -3, 0, GH - 4, GATE - 5.5], [BW + 3, BW + 8, 0, GH - 4, GATE + BW + 5.5], [-8, BW + 8, GH - 4, GH, GATE + BW + 8.5]] as const)+ .map(([y0, y1, z0, z1, key]) => {+ const el = solid(layer), [rg, ig] = rings(GATE - 1.6, y0, GATE + 1.6, y1, 1.4, 0.6);+ put(el, prism(P, front, rg, ig, z0, z1));+ // the glow is driven every frame from the belt; the stroke's CSS transition would only lag it+ el.sil.style.transition = "none";+ return { el, key };+ });+ const lifts = Array.from({ length: NC }, () => spring(0, { eps: 0.03 }));+ let hot = -1, order = "", gatePct = 0;++ const B = register(stage, (dt) => {+ let m = stepS(rate, dt);+ const base = reducedMotion() ? 0 : 1;+ if (!over) rate.t = base;+ clock += dt * rate.x;+ const items: Item[] = [];+ for (let j = 0; j < NC; j++) {+ const q = j / NC + clock * SPEED, u = q - Math.floor(q), lap = Math.floor(q);+ items.push({ j, x: u * L, s: size(u), serial: 141 + lap * NC + j });+ }+ // nearest crate to the pointer, on the belt plane+ let want = -1;+ if (over) {+ let best = 34;+ for (const it of items) if (it.s > 0.6 && Math.abs(it.x - over[0]) < best) { best = Math.abs(it.x - over[0]); want = it.j; }+ }+ hot = want;+ lifts.forEach((sp, j) => { sp.t = j === hot ? 11 : 0; if (stepS(sp, dt)) m = true; });+ items.sort((a, b) => a.x - b.x);+ let gateGlow = 0, hotSerial = 0;+ // stable ids, so the layer is only re-appended when the order actually changes+ const draw: { id: string | number; key: number; g: SVGGElement }[] = gate.map((p, i) => ({ id: "g" + i, key: p.key, g: p.el.g }));+ items.forEach((it, k) => {+ const el = pool[k], sz = CUBE * it.s, x0 = it.x - sz / 2, x1 = it.x + sz / 2, y0 = BW / 2 - sz / 2, y1 = BW / 2 + sz / 2;+ const z0 = BT + lifts[it.j].x, z1 = z0 + sz;+ draw.push({ id: k, key: it.x + BW / 2, g: el.g });+ if (sz < 0.3) { el.g.setAttribute("visibility", "hidden"); return; }+ el.g.removeAttribute("visibility");+ const [rg, ig] = rings(x0, y0, x1, y1, 2.6 * it.s, 0.9 * it.s);+ put(el, prism(P, front, rg, ig, z0, z1));+ const isHot = it.j === hot;+ el.sil.classList.toggle("hi", isHot);+ // the serial, as a 3 × 3 code on the lid (bit 0 top-left)+ const pitch = sz * 0.2, rr = r2(0.55 * it.s * C.S);+ el.dots.forEach((d, b) => {+ place(d, P(it.x + ((b % 3) - 1) * pitch, BW / 2 + (Math.floor(b / 3) - 1) * pitch, z1));+ d.setAttribute("rx", String(rr)); d.setAttribute("ry", String(r2(rr * C.k)));+ d.setAttribute("class", (it.serial >> b) & 1 ? (isHot ? "dot" : "dot m") : "dot off");+ });+ if (isHot) hotSerial = it.serial;+ gateGlow = Math.max(gateGlow, glow(it.x) * it.s);+ });+ draw.sort((a, b) => a.key - b.key);+ const sig = draw.map((d) => d.id).join();+ if (sig !== order) { order = sig; draw.forEach((d) => layer.appendChild(d.g)); }+ // the edge colour mixed toward the lit one; written only when the percent changes+ const pct = Math.round(gateGlow * 100);+ if (pct !== gatePct) {+ gatePct = pct;+ const stroke = pct ? `color-mix(in srgb, var(--hl-hi) ${pct}%, var(--hl-edge))` : "";+ gate.forEach((p) => { p.el.sil.style.stroke = stroke; });+ }+ const off = (((clock * SPEED * L) % 21) + 21) % 21, sl: string[] = [];+ for (let x = off; x < L; x += 21) if (x > 5 && x < L - 5) sl.push(seg(P(x, 4, BT), P(x, BW - 4, BT)));+ slats.setAttribute("d", sl.join(""));+ read.textContent = `rate ${rate.x.toFixed(2)}×` + (hot >= 0 ? ` · #${String(hotSerial).padStart(4, "0")}` : "");+ // The study asks for every frame. Under reduced motion at rest the belt is+ // stopped, so the frame would repeat itself: sleep until input or a change+ // of preference wakes it (both do). Visually the same.+ if (reducedMotion() && !over && rate.x === 0) return m;+ return true;+ });+ bag.add(B.unregister);+ bag.add(pointer(stage, {+ move: (p) => { over = unproj(C, p[0], p[1], BT); rate.t = slow; B.wake(); },+ leave: () => { over = null; B.wake(); },+ }));+ bag.add(() => svg.replaceChildren());+ return { set: (v) => { slow = v; if (over) rate.t = v; B.wake(); }, destroy: bag.dispose };+};diff --git a/packages/hairline/src/figures/terrain.ts b/packages/hairline/src/figures/terrain.tsnew file mode 100644index 0000000..ff7c7ea--- /dev/null+++ b/packages/hairline/src/figures/terrain.ts@@ -0,0 +1,99 @@+import { Cam, clamp, facing, fit, prism, proj, rings, unproj, type Ring } from "../core/iso";+import { spring, stepS, type Spring } from "../core/motion";+import { flatDot, mk, place, pointer, put, register, disposer, solid, type FigureMount, type Solid } from "../core/stage";++/**+ * Terrain (Fig 9.2): Fig 0.3's falloff in two dimensions. The pointer is+ * projected back onto the ground, and each of 81 pillars on a rounded plinth+ * takes its height from its radial distance to it, each on its own spring. At+ * rest the field is a designed dune with two rises. A 3 × 3 dot mark rides the+ * lid of the pillar under the pointer, or the peak at rest; pillars above half+ * height take the bright stroke. The slider is the radius, in cells.+ * Ported from the study's `#terrain` (design/lab-hairline/cartilha-v2.html).+ */++const N = 9, CELL = 14, FOOT = 11, HMAX = 58, EXT = N * CELL, PB = 5;++/** Linear's ratios, as a fraction of the radius: 1 → .31 at 42% → .09 at the edge and beyond. */+const falloff = (u: number) =>+ u <= 0 ? 1 : u <= 0.417 ? 1 - (u / 0.417) * 0.6875 : u <= 1 ? 0.3125 - ((u - 0.417) / 0.583) * 0.2185 : 0.094;++type Col = { i: number; j: number; h0: number; ring: Ring; inner: Ring; sp: Spring; el: Solid; drawn: number };++export const mount: FigureMount = ({ stage, svg, read }, value) => {+ const bag = disposer();+ const C = Cam(45, 0.5, 1.58);+ fit(C, [[-6, -6, -PB], [EXT + 6, EXT + 6, -PB], [EXT + 6, -6, -PB], [-6, EXT + 6, -PB], [0, 0, HMAX * 0.75]], 200, 166);+ const P = proj(C), front = facing(C);+ let R = value * CELL, over: [number, number] | null = null;++ const g = mk("g", {}, svg), cols: Col[] = [];+ const [pr, pi] = rings(-6, -6, EXT + 6, EXT + 6, 9, 2.2);+ put(solid(g), prism(P, front, pr, pi, -PB, 0));+ // Diagonal by diagonal from the back corner, so appending is painting back to front.+ for (let s = 0; s <= 2 * (N - 1); s++) for (let i = 0; i < N; i++) {+ const j = s - i;+ if (j < 0 || j >= N) continue;+ const u = i / (N - 1), v = j / (N - 1);+ const h0 = 4 + 25 * Math.exp(-((u - 0.22) ** 2 + (v - 0.74) ** 2) / 0.07) + 12 * Math.exp(-((u - 0.8) ** 2 + (v - 0.26) ** 2) / 0.035);+ const x0 = i * CELL + (CELL - FOOT) / 2, y0 = j * CELL + (CELL - FOOT) / 2;+ const [ring, inner] = rings(x0, y0, x0 + FOOT, y0 + FOOT, 2.6, 0.9);+ cols.push({ i, j, h0, ring, inner, sp: spring(h0, { eps: 0.04 }), el: solid(g), drawn: NaN });+ }++ // The mark: a 3 × 3 of dots riding the lid of one pillar, moved in the paint+ // order to just after it, so the pillars in front still cover it.+ const mark = mk("g", {}, g), md: SVGEllipseElement[] = [];+ for (let k = 0; k < 9; k++) md.push(flatDot(mark, C, 0.55, k === 4 ? "dot" : "dot m"));+ const peak = cols.reduce((a, b) => (b.h0 > a.h0 ? b : a));+ const byCell = new Map<string, Col>();+ cols.forEach((c) => byCell.set(c.i + "," + c.j, c));+ let mc: Col | null = null, want = peak;++ function drawMark() {+ if (want !== mc) { mc = want; mc.el.g.after(mark); }+ const cx = (mc.i + 0.5) * CELL, cy = (mc.j + 0.5) * CELL, h = Math.max(0.6, mc.sp.x);+ md.forEach((el, k) => place(el, P(cx + ((k % 3) - 1) * 2.5, cy + (Math.floor(k / 3) - 1) * 2.5, h)));+ }+ // A pillar whose spring hasn't moved keeps its paths: most of the 81 are still on most frames.+ function drawCol(c: Col) {+ const h = Math.max(0.6, c.sp.x);+ if (h === c.drawn) return;+ c.drawn = h;+ put(c.el, prism(P, front, c.ring, c.inner, 0, h));+ c.el.sil.classList.toggle("hi", h > HMAX * 0.5);+ }++ const B = register(stage, (dt) => {+ let m = false;+ for (const c of cols) { if (stepS(c.sp, dt)) m = true; drawCol(c); }+ drawMark();+ return m;+ });+ bag.add(B.unregister);++ function retarget() {+ for (const c of cols) {+ if (!over) { c.sp.t = c.h0; continue; }+ const dx = (c.i + 0.5) * CELL - over[0], dy = (c.j + 0.5) * CELL - over[1];+ c.sp.t = HMAX * falloff(Math.hypot(dx, dy) / R);+ }+ if (over) {+ const i = clamp(Math.floor(over[0] / CELL), 0, N - 1), j = clamp(Math.floor(over[1] / CELL), 0, N - 1);+ want = byCell.get(i + "," + j)!;+ read.textContent = `cell ${i}·${j}`;+ } else { want = peak; read.textContent = "rest"; }+ B.wake();+ }++ bag.add(pointer(stage, {+ move: (p) => { over = unproj(C, p[0], p[1], 0); retarget(); },+ leave: () => { over = null; retarget(); },+ }));+ bag.add(() => svg.replaceChildren());++ return {+ set: (v) => { R = v * CELL; if (over) retarget(); },+ destroy: bag.dispose,+ };+};diff --git a/packages/hairline/src/figures/turntable-geometry.ts b/packages/hairline/src/figures/turntable-geometry.tsnew file mode 100644index 0000000..a568a1f--- /dev/null+++ b/packages/hairline/src/figures/turntable-geometry.ts@@ -0,0 +1,88 @@+/**+ * Turntable — the blocks on the platter and the order they are painted in,+ * with no DOM, so the one part of the figure that can go wrong all the way+ * round (tests/hairline-geometry.spec.ts sweeps it) is checked without a+ * browser. From the study's sixth figure (design/lab-hairline/cartilha-v2.html).+ *+ * The camera turns and the blocks stand still, so which block is in front+ * changes with the azimuth and is worked out again every frame. `s` and `c`+ * are sin and cos of the azimuth, `k` is sin(elevation).+ */++/** One axis-aligned block: [x0, y0, z0, x1, y1, z1, column]. A column is blocks stacked on one footprint. */+export type Blk = readonly [number, number, number, number, number, number, number];++export const BLK: readonly Blk[] = [+ [-42, -42, 0, -12, -12, 14, 0], [-36, -36, 14, -18, -18, 34, 0],+ [0, -46, 0, 16, -6, 10, 1],+ [24, -32, 0, 40, -16, 44, 2],+ [-44, 4, 0, -4, 18, 22, 3],+ [8, 6, 0, 40, 38, 8, 4], [16, 14, 8, 28, 26, 20, 4],+ [-30, 28, 0, -16, 42, 12, 5],+];++/** The azimuth the figure is drawn at, and the quarter turn between its detents. */+export const HOME = 45;+export const DETENT = 90;++/** The nearest quarter-turn detent to an angle, in degrees: every stop is 2:1 again. */+export const detent = (a: number) => HOME + DETENT * Math.round((a - HOME) / DETENT);++/** A sort key for blocks no plane separates: farther is smaller. */+export const depth = (b: Blk, s: number, c: number) => (b[0] + b[3]) * s + (b[1] + b[4]) * c + (b[2] + b[5]) * 0.01;++/**+ * Whether A is painted before B. Two blocks in one column stack, lower first;+ * otherwise any axis plane between their footprints says which one is behind.+ */+export function behind(A: Blk, B: Blk, s: number, c: number): boolean {+ if (A[6] === B[6]) return A[2] < B[2];+ if (A[3] <= B[0]) return s > 0;+ if (B[3] <= A[0]) return s < 0;+ if (A[4] <= B[1]) return c > 0;+ if (B[4] <= A[1]) return c < 0;+ return depth(A, s, c) < depth(B, s, c);+}++/** A block's screen box at unit scale and no offset: [x0, y0, x1, y1]. */+export function scr(b: Blk, s: number, c: number, k: number): [number, number, number, number] {+ const zf = Math.sqrt(1 - k * k);+ let x0 = 1e9, x1 = -1e9, y0 = 1e9, y1 = -1e9;+ for (const x of [b[0], b[3]]) for (const y of [b[1], b[4]]) for (const z of [b[2], b[5]]) {+ const X = x * c - y * s, Y = (x * s + y * c) * k - z * zf;+ x0 = Math.min(x0, X); x1 = Math.max(x1, X); y0 = Math.min(y0, Y); y1 = Math.max(y1, Y);+ }+ return [x0, y0, x1, y1];+}++/**+ * The painter's order and how many picks had to break a cycle. Only pairs+ * whose screen boxes overlap are constrained (far pairs could otherwise chain+ * into a cycle), then a topological sort draws the farthest free block first.+ * If no block is free, the farthest waiting one is forced; `forced` counts+ * those, and for BLK it should stay 0 at every angle.+ */+export function paintOrder(bs: readonly Blk[], s: number, c: number, k: number): { order: number[]; forced: number } {+ const n = bs.length, bx = bs.map((b) => scr(b, s, c, k));+ const next: number[][] = bs.map(() => []), wait = bs.map(() => 0);+ for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) {+ const a = bx[i], b = bx[j];+ if (i === j || a[2] <= b[0] || b[2] <= a[0] || a[3] <= b[1] || b[3] <= a[1]) continue;+ if (behind(bs[i], bs[j], s, c)) { next[i].push(j); wait[j]++; }+ }+ const out: number[] = [], done = bs.map(() => false);+ let forced = 0;+ while (out.length < n) {+ let pick = -1, pass = 0;+ for (; pass < 2 && pick < 0; pass++)+ for (let i = 0; i < n; i++)+ if (!done[i] && (pass || !wait[i]) && (pick < 0 || depth(bs[i], s, c) < depth(bs[pick], s, c))) pick = i;+ if (pass === 2) forced++;+ done[pick] = true; out.push(pick);+ for (const j of next[pick]) wait[j]--;+ }+ return { order: out, forced };+}++/** Indices into `bs`, back to front. */+export const order = (bs: readonly Blk[], s: number, c: number, k: number) => paintOrder(bs, s, c, k).order;diff --git a/packages/hairline/src/figures/turntable.ts b/packages/hairline/src/figures/turntable.tsnew file mode 100644index 0000000..2f4f01a--- /dev/null+++ b/packages/hairline/src/figures/turntable.ts@@ -0,0 +1,128 @@+import { Cam, circ, clamp, facing, lerp, prism, proj, r2, rad, rings, seg, type Ring } from "../core/iso";+import { reducedMotion, spring, stepS } from "../core/motion";+import { BLK, HOME, detent, order, type Blk } from "./turntable-geometry";+import { disposer, flatDot, mk, place, pointer, put, register, solid, type FigureMount, type Solid } from "../core/stage";++/**+ * Turntable — flick it round. The camera is the variable: moving across the+ * platter pushes its near edge, friction bleeds the spin off, and once it is+ * slow a spring pulls it into the nearest quarter-turn detent, so every stop+ * is 2:1 again. Pointer y springs the elevation. The blocks are re-ordered+ * every frame (lib/hairline/turntable-geometry.ts). From the study's sixth+ * figure (design/lab-hairline/cartilha-v2.html).+ *+ * The slider is `coast`: the friction's time constant, in ms.+ */++const RING = 70, PT = 4, WMAX = 540, ON_INDEX = 14;++type Block = { b: Blk; ring: Ring; inner: Ring };++export const mount: FigureMount = ({ stage, svg, read }, value) => {+ const bag = disposer();+ let coast = value;++ // The platter's angle in degrees, its angular velocity, and whether it is coasting, settling or at rest.+ const spin = { a: HOME, w: 0, mode: "rest" as "rest" | "coast" | "settle", tgt: HOME };+ const kk = spring(0.5, { eps: 0.0005 });+ let lastX: number | null = null, lastT = 0, lastMove = -1e9;++ /** Coast under friction, then spring into the detent; 240Hz substeps so a long frame can't overshoot. */+ function stepSpin(dt: number, now: number) {+ if (spin.mode === "rest") return false;+ const n = Math.max(1, Math.ceil(dt * 240)), h = dt / n;+ for (let i = 0; i < n; i++) {+ if (spin.mode === "coast") {+ spin.w *= Math.exp((-h * 1000) / coast); spin.a += spin.w * h;+ if (Math.abs(spin.w) < 45 && now - lastMove > 90) { spin.mode = "settle"; spin.tgt = detent(spin.a + spin.w * 0.2); }+ } else { spin.w += (-90 * (spin.a - spin.tgt) - 16 * spin.w) * h; spin.a += spin.w * h; }+ }+ if (spin.mode === "settle" && Math.abs(spin.a - spin.tgt) < 0.02 && Math.abs(spin.w) < 0.3) { spin.a = spin.tgt; spin.w = 0; spin.mode = "rest"; }+ return spin.mode !== "rest";+ }++ const C = Cam(HOME, 0.5, 1.85); C.ox = 200; C.oy = 184;+ const plat = circ(RING), platIn = circ(RING - 1.5);+ const blocks: Block[] = BLK.map((b) => { const [ring, inner] = rings(b[0], b[1], b[3], b[4], 3, 1.1); return { b, ring, inner }; });+ const TALL = blocks.find((k) => k.b[5] >= 40)!;+ // each column lights by its top block only+ const tops: Record<number, Block> = {};+ blocks.forEach((k) => { if (!tops[k.b[6]] || k.b[5] > tops[k.b[6]].b[5]) tops[k.b[6]] = k; });+ const base: Record<number, [number, number]> = {};+ blocks.forEach((k) => { if (k.b[2] === 0) base[k.b[6]] = [(k.b[0] + k.b[3]) / 2, (k.b[1] + k.b[4]) / 2]; });++ const g = mk("g", {}, svg);+ const platter = solid(g), ticks = mk("path", { class: "nf lo" }, g), major = mk("path", { class: "nf" }, g);+ const north = flatDot(g, C, 1.7, "dot m");+ const index = mk("path", { class: "nf" }, g);+ const pool = BLK.map(() => solid(g));+ // The tall block's dot code: a 4 × 4 grid less its corners, the rim dots medium. It rides that block's lid,+ // so it is moved to just after whichever pool group the tall block is drawn in.+ const acc = mk("g", {}, g), accD: { r: number; q: number; el: SVGEllipseElement }[] = [];+ for (let k = 0; k < 16; k++) {+ const r = Math.floor(k / 4), q = k % 4, edge = r % 3 === 0, side = q % 3 === 0;+ if (edge && side) continue;+ accD.push({ r, q, el: flatDot(acc, C, 0.6, edge || side ? "dot m" : "dot") });+ }+ let accAt: Solid | null = null;++ const B = register(stage, (dt, now) => {+ let m = stepSpin(dt, now);+ if (stepS(kk, dt)) m = true;+ C.az = rad(spin.a); C.k = kk.x;+ const P = proj(C), front = facing(C), c = Math.cos(C.az), s = Math.sin(C.az);+ put(platter, prism(P, front, plat, platIn, -PT, 0));+ const tk: string[] = [], mj: string[] = [];+ for (let d = 0; d < 360; d += 15) {+ const a = rad(d), long = d % 90 === 0, r0 = long ? RING - 12 : RING - 8;+ (long ? mj : tk).push(seg(P(Math.cos(a) * r0, Math.sin(a) * r0, 0), P(Math.cos(a) * (RING - 4.5), Math.sin(a) * (RING - 4.5), 0)));+ }+ ticks.setAttribute("d", tk.join("")); major.setAttribute("d", mj.join(""));+ place(north, P(0, -(RING - 17), 0)); north.setAttribute("ry", String(r2(1.7 * C.S * C.k)));+ const bottom = C.oy + RING * C.S * C.k + PT * C.S * Math.sqrt(1 - C.k * C.k);+ index.setAttribute("d", `M${C.ox - 4} ${r2(bottom + 10)}L${C.ox} ${r2(bottom + 4)}L${C.ox + 4} ${r2(bottom + 10)}`);+ // while the platter is handled or turning, the column passing the index mark lights; at rest nothing does+ let lit = -1, best = ON_INDEX;+ if (lastX !== null || spin.mode !== "rest")+ for (const col in base) {+ const [x, y] = base[col], off = (Math.abs(Math.atan2(x * c - y * s, x * s + y * c)) * 180) / Math.PI;+ if (off < best) { best = off; lit = +col; }+ }+ order(BLK, s, c, C.k).forEach((j, i) => {+ const k = blocks[j];+ put(pool[i], prism(P, front, k.ring, k.inner, k.b[2], k.b[5]));+ pool[i].sil.classList.toggle("hi", k === tops[lit]);+ if (k === TALL && accAt !== pool[i]) { accAt = pool[i]; accAt.g.after(acc); }+ });+ const [x0, y0, , x1, y1, z1] = TALL.b, cx = (x0 + x1) / 2, cy = (y0 + y1) / 2;+ accD.forEach(({ r, q, el }) => {+ place(el, P(cx + (q - 1.5) * 2.6, cy + (r - 1.5) * 2.6, z1));+ el.setAttribute("ry", String(r2(0.6 * C.S * C.k)));+ });+ read.textContent = `az ${String(Math.round(((spin.a % 360) + 360) % 360)).padStart(3, "0")}° · el ${Math.round((Math.asin(kk.x) * 180) / Math.PI)}°`;+ return m;+ });+ bag.add(B.unregister);++ bag.add(pointer(stage, {+ move: (p) => {+ const now = performance.now();+ kk.t = lerp(Math.sin(rad(40)), Math.sin(rad(20)), clamp(p[1] / 320, 0, 1));+ if (lastX !== null) {+ const dx = p[0] - lastX;+ if (reducedMotion()) spin.a -= dx * 0.9;+ else {+ // pushing the near edge: the platter's front follows the pointer+ const vp = dx / Math.max(0.008, (now - lastT) / 1000);+ spin.w = clamp(lerp(spin.w, -vp * 0.9, 0.35), -WMAX, WMAX); spin.mode = "coast";+ }+ if (Math.abs(dx) > 0.5) lastMove = now;+ }+ lastX = p[0]; lastT = now; B.wake();+ },+ leave: () => { lastX = null; kk.t = 0.5; if (reducedMotion()) spin.a = detent(spin.a); B.wake(); },+ }));++ bag.add(() => svg.replaceChildren());+ return { set: (v) => { coast = v; B.wake(); }, destroy: bag.dispose };+};diff --git a/packages/hairline/test/geometry.test.ts b/packages/hairline/test/geometry.test.tsnew file mode 100644index 0000000..cbb9053--- /dev/null+++ b/packages/hairline/test/geometry.test.ts@@ -0,0 +1,69 @@+import { expect, test } from "vitest";+import { Cam, fit, proj, rad, unproj } from "../src/core/iso";+import { BLK, DETENT, HOME, detent, paintOrder } from "../src/figures/turntable-geometry";++/**+ * The parts of Hairline that can be checked without a browser. The painter's+ * order is the one that can go wrong somewhere in a full turn and look right+ * everywhere else, so it is swept all the way round at the three elevations+ * the turntable reaches (20° to 40°, resting at 30°).+ */+const close = (a: number, b: number, eps = 1e-6) => expect(Math.abs(a - b)).toBeLessThan(eps);++test("turntable order is a full permutation with no forced pick, all the way round", () => {+ for (const el of [20, 30, 40]) {+ const k = Math.sin(rad(el));+ for (let az = 0; az <= 360; az += 0.5) {+ const { order, forced } = paintOrder(BLK, Math.sin(rad(az)), Math.cos(rad(az)), k);+ expect(forced, `cycle at az ${az} el ${el}`).toBe(0);+ expect(order.slice().sort((a, b) => a - b)).toEqual(BLK.map((_, i) => i));+ }+ }+});++test("a stacked column paints bottom first", () => {+ // blocks 0 and 1 are column 0, and 5 and 6 are column 4; lower first at every angle+ for (let az = 0; az < 360; az += 7.5) {+ const o = paintOrder(BLK, Math.sin(rad(az)), Math.cos(rad(az)), 0.5).order;+ expect(o.indexOf(0)).toBeLessThan(o.indexOf(1));+ expect(o.indexOf(5)).toBeLessThan(o.indexOf(6));+ }+});++test("detent seats on the nearest quarter turn from HOME", () => {+ expect(HOME).toBe(45);+ expect(DETENT).toBe(90);+ expect(detent(45)).toBe(45);+ expect(detent(89)).toBe(45);+ expect(detent(91)).toBe(135);+ expect(detent(200)).toBe(225);+ expect(detent(-44)).toBe(-45);+ expect(detent(400)).toBe(405);+ for (let a = -720; a <= 720; a += 3.7) {+ const d = detent(a);+ expect(Math.abs(d - a)).toBeLessThanOrEqual(45);+ expect((((d - HOME) % 90) + 90) % 90).toBe(0);+ }+});++test("unproj inverts proj on the plane it is given", () => {+ for (const [az, k, S] of [[45, 0.5, 1.62], [0, 0.34, 2], [123, 0.64, 1.3], [-80, 0.5, 1.85]]) {+ const C = Cam(az, k, S);+ fit(C, [[0, 0, 0], [100, 80, 0], [0, 0, 40]], 200, 160);+ const P = proj(C);+ for (const [x, y, z] of [[0, 0, 0], [12.5, -40, 0], [80, 33, 17], [-20, 60, -9]]) {+ const [sx, sy] = P(x, y, z);+ const [ux, uy] = unproj(C, sx, sy, z);+ close(ux, x); close(uy, y);+ }+ }+});++test("fit centres the box it is given", () => {+ const C = Cam(45, 0.5, 1.58);+ const pts: [number, number, number][] = [[-6, -6, -5], [132, 132, -5], [132, -6, -5], [-6, 132, -5], [0, 0, 43.5]];+ fit(C, pts, 200, 166);+ const P = proj(C), xs = pts.map((p) => P(...p)[0]), ys = pts.map((p) => P(...p)[1]);+ close((Math.min(...xs) + Math.max(...xs)) / 2, 200);+ close((Math.min(...ys) + Math.max(...ys)) / 2, 166);+});