"use client";
import { C, Exhibit, monoFont, rng } from "./kit";
import { TORCH_LINES } from "./text";
export type TorchProps = {
/** Cone half-angle in degrees at rest; pressing narrows it to about half. */
angle?: number;
/** Reach in px at rest; pressing extends it by 65%. */
reach?: number;
};
const COLS = 60;
const ROWS = 24;
const X0 = 40;
const CW = 8.6;
const Y0 = 80;
const LH = 18;
const LAMP = { x: 300, y: 494 };
const NOISE = "abcdefghijklmnopqrstuvwxyz{}[]();:.,<>/\\|=+-_*~^!?";
/** A page of noise with sentences hidden in it, and a lamp you aim to read them. */
export function Torch({ angle = 24, reach = 340 }: TorchProps) {
return (
<Exhibit
title="Torch"
hint="aim the lamp · hold to focus"
formula="Iᵢ = cone(∠ᵢ − φ, α) · reach(dᵢ, L)"
spec={`α ${angle}° → ${Math.round(angle * 0.46)}° · L ${reach} → ${Math.round(reach * 1.65)}px`}
label="A field of random characters with sentences hidden in it. A lamp at the bottom aims at the pointer; characters inside its beam show the real text. Hold to narrow the beam and reach further. Arrow keys aim the lamp and holding Space focuses it."
cursor="crosshair"
params={{ angle, reach }}
create={(params) => {
const r = rng(5);
const truth: string[] = new Array(COLS * ROWS).fill(" ");
const noise: string[] = [];
const tone = new Float32Array(COLS * ROWS);
for (let i = 0; i < COLS * ROWS; i++) {
noise.push(NOISE[Math.floor(r() * NOISE.length)]);
tone[i] = r();
}
let total = 0;
for (const [row, col, s] of TORCH_LINES)
for (let i = 0; i < s.length; i++) {
truth[row * COLS + col + i] = s[i];
if (s[i] !== " ") total++;
}
const read = new Uint8Array(COLS * ROWS);
let nRead = 0;
let aim = -Math.PI / 2;
let av = 0;
let alpha = (angle * Math.PI) / 180;
let L = reach;
let lit = 0;
return {
frame(ctx, dt, p, time) {
const { angle: a0, reach: l0 } = params.current;
const target = p.inside ? Math.atan2(Math.min(p.y, LAMP.y - 20) - LAMP.y, p.x - LAMP.x) : -Math.PI / 2 + Math.sin(time * 0.35) * 0.7;
// A critically damped swing toward the target angle.
av += ((target - aim) * 90 - av * 19) * dt;
aim += av * dt;
const held = p.down;
alpha += (((held ? a0 * 0.46 : a0) * Math.PI) / 180 - alpha) * Math.min(1, dt * 8);
L += ((held ? l0 * 1.65 : l0) - L) * Math.min(1, dt * 8);
// Noise churns a little so the page feels alive.
for (let s = 0; s < 6; s++) noise[Math.floor(r() * noise.length)] = NOISE[Math.floor(r() * NOISE.length)];
ctx.font = monoFont(12.5);
ctx.textBaseline = "middle";
lit = 0;
for (let row = 0; row < ROWS; row++) {
const y = Y0 + row * LH;
for (let col = 0; col < COLS; col++) {
const i = row * COLS + col;
const x = X0 + col * CW;
const dx = x + CW / 2 - LAMP.x;
const dy = y - LAMP.y;
const d = Math.hypot(dx, dy);
let da = Math.atan2(dy, dx) - aim;
da = Math.atan2(Math.sin(da), Math.cos(da));
const inCone = Math.abs(da) < alpha && d < L;
if (inCone) {
const edge = Math.abs(da) > alpha * 0.82 || d > L * 0.92;
if (edge) {
ctx.fillStyle = C.accent;
if (tone[i] > 0.45) ctx.fillText(noise[i], x, y);
continue;
}
const ch = truth[i];
if (ch === " ") continue;
lit++;
if (!read[i]) {
read[i] = 1;
nRead++;
}
ctx.fillStyle = C.bright;
ctx.fillText(ch, x, y);
} else {
ctx.fillStyle = tone[i] > 0.66 ? "#4f4d46" : tone[i] > 0.33 ? "#3f3e39" : "#33322e";
ctx.fillText(noise[i], x, y);
}
}
}
// The lamp and its aim.
ctx.strokeStyle = "#4a4943";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.arc(LAMP.x, LAMP.y, 8, 0, Math.PI * 2);
ctx.stroke();
ctx.fillStyle = C.accent;
ctx.beginPath();
ctx.arc(LAMP.x, LAMP.y, 2.5, 0, Math.PI * 2);
ctx.fill();
ctx.save();
ctx.setLineDash([1, 4]);
ctx.strokeStyle = "#5a5852";
ctx.beginPath();
for (const s of [-1, 1]) {
ctx.moveTo(LAMP.x + Math.cos(aim + s * alpha) * 14, LAMP.y + Math.sin(aim + s * alpha) * 14);
ctx.lineTo(LAMP.x + Math.cos(aim + s * alpha) * 120, LAMP.y + Math.sin(aim + s * alpha) * 120);
}
ctx.stroke();
ctx.restore();
},
stats: () => {
const deg = Math.round(((aim + Math.PI / 2) * 180) / Math.PI);
return ["", `aim ${deg >= 0 ? "+" : "−"}${Math.abs(deg)}° · lit ${String(lit).padStart(3)} · read ${String(Math.round((nRead / total) * 100)).padStart(3)}%`];
},
};
}}
/>
);
}
/** Original copy used by the text exhibits. Written for sher.md, not taken from aiforui.dev. */
export const SMALL_PRINT = [
"Motion is a promise about where things live. When a panel slides in from the right,",
"it tells you the panel is still there, just off screen, waiting to slide back.",
"",
"Good easing is mostly about the last frames. The start can be quick; the end has",
"to land softly, or the eye reads the stop as a jolt rather than an arrival.",
"",
"Keep durations short. Anything a person triggers dozens of times a day should feel",
"instant, which in practice means under two hundred milliseconds, often less.",
"",
"Springs are easier to tune than curves because they answer to three numbers you can",
"feel: how stiff, how heavy, how much friction. Change one and the rest still makes sense.",
"",
"Reduced motion is not no motion. Fade instead of fly, shorten instead of skip, and keep",
"every state change visible so nobody is left guessing what just happened.",
"",
"The best interaction is often the one nobody notices: it simply does what the hand expected.",
];
/** Torch: sentences hidden in a field of noise, placed by [row, column]. */
export const TORCH_LINES: [number, number, string][] = [
[3, 33, "light finds what"],
[4, 33, "the page already knew."],
[8, 6, "shadow is a design tool too."],
[9, 6, "hide the rest; show the one"],
[10, 6, "thing that matters right now."],
[13, 28, "a narrow beam reads deeper,"],
[14, 28, "a wide one sees more."],
[17, 10, "hold still and the words come"],
[18, 10, "into focus."],
];
/** Palimpsest: the same paragraph as a rough draft and a final. */
export const DRAFT = [
"so the idea here is that we should probably try to",
"animate more stuff because it maybe looks nicer and",
"users like it i think, but also maybe not everything",
"",
"we could make things slower so people notice them,",
"like half a second or so, and add bounces to most of",
"the buttons and menus and every little tooltip too.",
"",
"need to check: does it work with reduced motion on?",
"and what about phones. todo: ask someone about this",
];
export const FINAL = [
"",
"Animate to explain, not to decorate.",
"",
"A transition should show where something came from",
"and where it went. If it cannot do that, remove it.",
"",
"Keep it short. Most interface motion belongs under",
"two hundred milliseconds, and things people do all",
"day should not animate at all.",
"",
"Respect reduced motion: fade, do not fly.",
];
"use client";
import { useEffect, useRef, useState, type MutableRefObject } from "react";
/** Every exhibit draws in a 600 × 600 coordinate space, whatever its rendered size. */
export const S = 600;
export const C = {
bg: "#10100e",
panel: "#161613",
line: "#34342f",
text: "#b9b4a8",
dim: "#6b6960",
bright: "#ece8dc",
accent: "#2b8cff",
};
export const MONO = '"Geist Mono", ui-monospace, SFMono-Regular, Menlo, monospace';
let fam = "";
export function monoFont(px: number, weight = 400) {
if (!fam && typeof window !== "undefined") fam = getComputedStyle(document.documentElement).getPropertyValue("--font-geist-mono").trim() || MONO;
return `${weight} ${px}px ${fam || MONO}, ui-monospace, monospace`;
}
/** Pointer (or keyboard probe) state, in exhibit coordinates. */
export type Ptr = {
x: number;
y: number;
inside: boolean;
down: boolean;
/** Velocity in px/s, smoothed. */
vx: number;
vy: number;
/** Seconds since the last press began. */
held: number;
/** "key" when the keyboard probe is driving it. */
source: "pointer" | "key";
};
export type Sim = {
/** Advance and draw one frame. dt is in seconds and capped at 1/30. */
frame: (ctx: CanvasRenderingContext2D, dt: number, p: Ptr, time: number) => void;
/** Footer texts that change: [top-right, bottom-right]. Polled about 8× a second. */
stats?: () => [string, string];
down?: (p: Ptr) => void;
up?: (p: Ptr) => void;
/** Pointer released without moving much: a tap or click. */
tap?: (p: Ptr) => void;
dispose?: () => void;
};
export type ExhibitProps<P> = {
title: string;
hint: string;
formula: string;
spec: string;
label: string;
cursor?: string;
params: P;
create: (params: MutableRefObject<P>) => Sim;
/** Extra line the screen-reader summary appends after the stats. */
className?: string;
};
export const reduced = () => typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
/**
* Frame shared by every Interaction Lab original: a square panel with a canvas,
* an SVG overlay for the bracketed title, hint, formula and live stats, and a
* keyboard probe so every exhibit can be driven without a pointer.
*/
export function Exhibit<P>({ title, hint, formula, spec, label, cursor = "crosshair", params, create, className }: ExhibitProps<P>) {
const wrap = useRef<HTMLDivElement>(null);
const canvas = useRef<HTMLCanvasElement>(null);
const paramsRef = useRef(params);
paramsRef.current = params;
const [stats, setStats] = useState<[string, string]>(["", ""]);
const [probe, setProbe] = useState<{ x: number; y: number; down: boolean } | null>(null);
const [said, setSaid] = useState("");
const api = useRef<{ ptr: Ptr; sim: Sim | null; engaged: number; keyMove: (dx: number, dy: number) => void; press: (on: boolean) => void; tap: () => void }>(null!);
useEffect(() => {
const cv = canvas.current!;
const el = wrap.current!;
const ctx = cv.getContext("2d")!;
const sim = create(paramsRef);
const ptr: Ptr = { x: S / 2, y: S / 2, inside: false, down: false, vx: 0, vy: 0, held: 0, source: "pointer" };
let raf = 0;
let last = 0;
let visible = true;
let engaged = 0; // seconds of activity left before a reduced-motion pause
let pressAt = { x: 0, y: 0 };
let lastMove = { x: 0, y: 0, t: 0 };
let statT = 0;
let time = 0;
const size = () => {
const r = el.getBoundingClientRect();
const dpr = Math.min(window.devicePixelRatio || 1, 2);
cv.width = Math.max(1, Math.round(r.width * dpr));
cv.height = Math.max(1, Math.round(r.height * dpr));
};
size();
const ro = new ResizeObserver(size);
ro.observe(el);
const loop = (now: number) => {
raf = 0;
const dt = Math.min(1 / 30, last ? (now - last) / 1000 : 1 / 60);
last = now;
time += dt;
if (ptr.down) ptr.held += dt;
if (now - lastMove.t > 80) {
ptr.vx *= 0.8;
ptr.vy *= 0.8;
}
ctx.setTransform(cv.width / S, 0, 0, cv.height / S, 0, 0);
ctx.fillStyle = C.bg;
ctx.fillRect(0, 0, S, S);
sim.frame(ctx, dt, ptr, time);
statT += dt;
if (statT > 0.12 && sim.stats) {
statT = 0;
const s = sim.stats();
setStats((o) => (o[0] === s[0] && o[1] === s[1] ? o : s));
}
engaged -= dt;
schedule();
};
const schedule = () => {
if (raf || !visible || document.hidden) return;
if (reduced() && engaged <= 0 && !ptr.inside && !ptr.down) return;
last = last && performance.now() - last > 200 ? 0 : last;
raf = requestAnimationFrame(loop);
};
const wake = () => {
engaged = 3;
schedule();
};
const io = new IntersectionObserver(([e]) => {
visible = e.isIntersecting;
if (visible) {
last = 0;
schedule();
}
});
io.observe(el);
const onVis = () => {
last = 0;
schedule();
};
document.addEventListener("visibilitychange", onVis);
const toLocal = (e: PointerEvent) => {
const r = el.getBoundingClientRect();
return { x: ((e.clientX - r.left) / r.width) * S, y: ((e.clientY - r.top) / r.height) * S };
};
const move = (x: number, y: number) => {
const t = performance.now();
const dts = Math.max(1, t - lastMove.t) / 1000;
if (lastMove.t && t - lastMove.t < 100) {
ptr.vx = ptr.vx * 0.6 + ((x - ptr.x) / dts) * 0.4;
ptr.vy = ptr.vy * 0.6 + ((y - ptr.y) / dts) * 0.4;
}
lastMove = { x, y, t };
ptr.x = x;
ptr.y = y;
};
const onMove = (e: PointerEvent) => {
const l = toLocal(e);
ptr.source = "pointer";
ptr.inside = true;
move(l.x, l.y);
wake();
};
const onDown = (e: PointerEvent) => {
if (e.button !== 0) return;
el.setPointerCapture(e.pointerId);
const l = toLocal(e);
ptr.source = "pointer";
ptr.inside = true;
move(l.x, l.y);
ptr.down = true;
ptr.held = 0;
pressAt = l;
sim.down?.(ptr);
wake();
};
const onUp = (e: PointerEvent) => {
if (!ptr.down) return;
const l = toLocal(e);
ptr.down = false;
sim.up?.(ptr);
if (Math.hypot(l.x - pressAt.x, l.y - pressAt.y) < 6) sim.tap?.(ptr);
if (e.pointerType !== "mouse") ptr.inside = false;
wake();
};
const onLeave = (e: PointerEvent) => {
if (ptr.down && el.hasPointerCapture(e.pointerId)) return;
ptr.inside = false;
wake();
};
el.addEventListener("pointermove", onMove);
el.addEventListener("pointerdown", onDown);
el.addEventListener("pointerup", onUp);
el.addEventListener("pointercancel", onUp);
el.addEventListener("pointerleave", onLeave);
api.current = {
ptr,
sim,
engaged,
keyMove: (dx, dy) => {
if (ptr.source !== "key" || !ptr.inside) {
ptr.source = "key";
ptr.inside = true;
}
const nx = Math.max(8, Math.min(S - 8, ptr.x + dx));
const ny = Math.max(8, Math.min(S - 8, ptr.y + dy));
ptr.vx = (nx - ptr.x) * 30;
ptr.vy = (ny - ptr.y) * 30;
ptr.x = nx;
ptr.y = ny;
lastMove.t = performance.now();
wake();
},
press: (on) => {
ptr.source = "key";
ptr.inside = true;
if (on && !ptr.down) {
ptr.down = true;
ptr.held = 0;
pressAt = { x: ptr.x, y: ptr.y };
sim.down?.(ptr);
} else if (!on && ptr.down) {
ptr.down = false;
sim.up?.(ptr);
if (Math.hypot(ptr.x - pressAt.x, ptr.y - pressAt.y) < 6) sim.tap?.(ptr);
}
wake();
},
tap: () => {
ptr.source = "key";
ptr.inside = true;
ptr.down = true;
ptr.held = 0;
sim.down?.(ptr);
ptr.down = false;
sim.up?.(ptr);
sim.tap?.(ptr);
wake();
},
};
// Draw one frame even when motion is reduced, so the exhibit is never blank.
engaged = reduced() ? 0.05 : 0;
raf = requestAnimationFrame(loop);
return () => {
cancelAnimationFrame(raf);
ro.disconnect();
io.disconnect();
document.removeEventListener("visibilitychange", onVis);
el.removeEventListener("pointermove", onMove);
el.removeEventListener("pointerdown", onDown);
el.removeEventListener("pointerup", onUp);
el.removeEventListener("pointercancel", onUp);
el.removeEventListener("pointerleave", onLeave);
sim.dispose?.();
};
// create is stable per exhibit; remount with a key to rebuild.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const announce = useRef<number>(0);
const sync = () => {
const p = api.current?.ptr;
if (!p) return;
setProbe({ x: p.x, y: p.y, down: p.down });
window.clearTimeout(announce.current);
announce.current = window.setTimeout(() => {
const s = api.current?.sim?.stats?.();
if (s) setSaid([s[0], s[1]].filter(Boolean).join(". "));
}, 700);
};
const onKeyDown = (e: React.KeyboardEvent) => {
const a = api.current;
if (!a) return;
const step = e.shiftKey ? 48 : 12;
const k = e.key;
if (k === "ArrowLeft" || k === "ArrowRight" || k === "ArrowUp" || k === "ArrowDown") {
e.preventDefault();
a.keyMove(k === "ArrowLeft" ? -step : k === "ArrowRight" ? step : 0, k === "ArrowUp" ? -step : k === "ArrowDown" ? step : 0);
sync();
} else if (k === " ") {
e.preventDefault();
if (!e.repeat) a.press(true);
sync();
} else if (k === "Enter") {
e.preventDefault();
if (!e.repeat) a.tap();
sync();
} else if (k === "Escape") {
if (a.ptr.down) a.press(false);
a.ptr.inside = false;
setProbe(null);
}
};
const onKeyUp = (e: React.KeyboardEvent) => {
if (e.key === " ") {
e.preventDefault();
api.current?.press(false);
sync();
}
};
return (
<section
className={"lab lab-exhibit relative aspect-square w-full touch-none select-none overflow-hidden [-webkit-touch-callout:none] " + (className ?? "")}
style={{ background: C.bg, boxShadow: `inset 0 0 0 1px ${C.panel}` }}
tabIndex={0}
role="group"
aria-roledescription="interactive demo"
aria-label={`${title}. ${label}`}
onKeyDown={onKeyDown}
onKeyUp={onKeyUp}
onBlur={() => {
api.current?.press(false);
if (api.current) api.current.ptr.inside = api.current.ptr.source === "pointer" && api.current.ptr.inside;
setProbe(null);
}}
>
<div ref={wrap} className="absolute inset-0 touch-none" style={{ cursor }}>
<canvas ref={canvas} aria-hidden="true" className="absolute inset-0 block h-full w-full" />
<svg viewBox={`0 0 ${S} ${S}`} aria-hidden="true" className="lab-mono pointer-events-none absolute inset-0 block h-full w-full">
<text x={hint ? 40 : 300} y="44" fill={C.accent} fontSize="13" letterSpacing="0.14em" textAnchor={hint ? "start" : "middle"}>{`[ ${title.toUpperCase()} ]`}</text>
<text x="560" y="44" fill={C.dim} fontSize="11" textAnchor="end" letterSpacing="0.06em">
{hint}
</text>
<line x1="40" x2="560" y1="524.5" y2="524.5" stroke={C.line} strokeDasharray="2 4" />
<text x="40" y="548" fill={C.text} fontSize="11" letterSpacing="0.06em" style={{ whiteSpace: "pre" }}>
{formula}
</text>
<text x="560" y="548" fill={C.text} fontSize="11" textAnchor="end" letterSpacing="0.06em" style={{ whiteSpace: "pre" }}>
{stats[0]}
</text>
<text x="40" y="568" fill={C.dim} fontSize="11" letterSpacing="0.06em" style={{ whiteSpace: "pre" }}>
{spec}
</text>
<text x="560" y="568" fill={C.dim} fontSize="11" textAnchor="end" letterSpacing="0.06em" style={{ whiteSpace: "pre" }}>
{stats[1]}
</text>
{probe && (
<g transform={`translate(${probe.x} ${probe.y})`} stroke={C.accent} strokeWidth="1.5" fill="none">
<circle r={probe.down ? 9 : 6} />
<path d="M-14 0h6M8 0h6M0 -14v6M0 8v6" />
</g>
)}
</svg>
</div>
<span aria-hidden="true" className="lab-corners pointer-events-none absolute inset-[6px]">
<span className="absolute left-0 top-0 size-3 border-l border-t" style={{ borderColor: C.accent }} />
<span className="absolute right-0 top-0 size-3 border-r border-t" style={{ borderColor: C.accent }} />
<span className="absolute bottom-0 left-0 size-3 border-b border-l" style={{ borderColor: C.accent }} />
<span className="absolute bottom-0 right-0 size-3 border-b border-r" style={{ borderColor: C.accent }} />
</span>
<span className="sr-only" aria-live="polite">
{said}
</span>
</section>
);
}
/* ---------- shared drawing + simulation helpers ---------- */
export const clamp = (v: number, a = 0, b = 1) => (v < a ? a : v > b ? b : v);
export const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
/** Small deterministic PRNG so every mount starts from the same picture. */
export function rng(seed = 1) {
let s = seed >>> 0 || 1;
return () => {
s ^= s << 13;
s ^= s >>> 17;
s ^= s << 5;
return (s >>> 0) / 4294967296;
};
}
/**
* Halftone: draws one square dot per grid cell, sized by the cell value (0–1).
* Cells are bucketed by brightness so the whole field is a handful of fills.
*/
export function halftone(
ctx: CanvasRenderingContext2D,
field: ArrayLike<number>,
gw: number,
gh: number,
pitch: number,
ox: number,
oy: number,
colors: string[],
opts: { min?: number; size?: (v: number, i: number) => number; tone?: (v: number, i: number) => number } = {}
) {
const min = opts.min ?? 0.04;
const n = colors.length;
const paths = colors.map(() => new Path2D());
for (let y = 0; y < gh; y++) {
for (let x = 0; x < gw; x++) {
const i = y * gw + x;
const v = field[i];
if (v < min) continue;
const s = opts.size ? opts.size(v, i) : pitch * (0.35 + 0.55 * clamp(v));
if (s <= 0.2) continue;
const tone = opts.tone ? opts.tone(v, i) : v;
const b = Math.min(n - 1, Math.max(0, Math.floor(clamp(tone) * n)));
const cx = ox + x * pitch + pitch / 2;
const cy = oy + y * pitch + pitch / 2;
paths[b].rect(cx - s / 2, cy - s / 2, s, s);
}
}
for (let b = 0; b < n; b++) {
ctx.fillStyle = colors[b];
ctx.fill(paths[b]);
}
}
/** Gray-Scott reaction–diffusion on a w × h grid (Karl Sims' discrete form). */
export class GrayScott {
w: number;
h: number;
u: Float32Array;
v: Float32Array;
nu: Float32Array;
nv: Float32Array;
mask: Uint8Array | null = null;
steps = 0;
constructor(w: number, h: number) {
this.w = w;
this.h = h;
const n = w * h;
this.u = new Float32Array(n).fill(1);
this.v = new Float32Array(n);
this.nu = new Float32Array(n);
this.nv = new Float32Array(n);
}
seed(r: () => number, count = 40, radius = 3) {
const { w, h } = this;
for (let s = 0; s < count; s++) {
const cx = Math.floor(r() * w);
const cy = Math.floor(r() * h);
this.blot(cx, cy, radius, 1);
}
}
/** Add (amount > 0) or erase (amount < 0) chemical V in a disc. */
blot(cx: number, cy: number, radius: number, amount: number) {
const { w, h, u, v } = this;
const r2 = radius * radius;
for (let y = Math.max(0, Math.floor(cy - radius)); y <= Math.min(h - 1, Math.ceil(cy + radius)); y++) {
for (let x = Math.max(0, Math.floor(cx - radius)); x <= Math.min(w - 1, Math.ceil(cx + radius)); x++) {
const d2 = (x - cx) ** 2 + (y - cy) ** 2;
if (d2 > r2) continue;
const i = y * w + x;
if (this.mask && !this.mask[i]) continue;
if (amount > 0) {
u[i] = 0.5;
v[i] = Math.max(v[i], 0.25 * amount + 0.25);
} else {
u[i] = 1;
v[i] = 0;
}
}
}
}
step(F: number, k: number, n = 1, Du = 1, Dv = 0.5) {
const { w, h, mask } = this;
for (let s = 0; s < n; s++) {
const u = this.u;
const v = this.v;
const nu = this.nu;
const nv = this.nv;
for (let y = 0; y < h; y++) {
const ym = (y === 0 ? h - 1 : y - 1) * w;
const yp = (y === h - 1 ? 0 : y + 1) * w;
const yc = y * w;
for (let x = 0; x < w; x++) {
const i = yc + x;
if (mask && !mask[i]) {
nu[i] = 1;
nv[i] = 0;
continue;
}
const xm = x === 0 ? w - 1 : x - 1;
const xp = x === w - 1 ? 0 : x + 1;
const uc = u[i];
const vc = v[i];
const lu =
0.2 * (u[yc + xm] + u[yc + xp] + u[ym + x] + u[yp + x]) + 0.05 * (u[ym + xm] + u[ym + xp] + u[yp + xm] + u[yp + xp]) - uc;
const lv =
0.2 * (v[yc + xm] + v[yc + xp] + v[ym + x] + v[yp + x]) + 0.05 * (v[ym + xm] + v[ym + xp] + v[yp + xm] + v[yp + xp]) - vc;
const uvv = uc * vc * vc;
nu[i] = uc + Du * lu - uvv + F * (1 - uc);
nv[i] = vc + Dv * lv + uvv - (F + k) * vc;
}
}
this.u = nu;
this.nu = u;
this.v = nv;
this.nv = v;
this.steps++;
}
}
}
/** Scrambles a line into same-length noise, stable for a given seed. */
const NOISE = "abcdefghijklmnopqrstuvwxyz{}[]();:.,<>/\\|=+-_*~^";
export function scramble(s: string, seed: number) {
let out = "";
let h = seed * 2654435761;
for (let i = 0; i < s.length; i++) {
const c = s[i];
h = (h ^ (h >>> 13)) * 1274126177;
h ^= h >>> 16;
out += c === " " ? " " : NOISE[(h >>> 0) % NOISE.length];
}
return out;
}
/** Thin dashed line in 600-space. */
export function dashed(ctx: CanvasRenderingContext2D, x1: number, y1: number, x2: number, y2: number, color = C.line, dash: number[] = [2, 4]) {
ctx.save();
ctx.strokeStyle = color;
ctx.lineWidth = 1;
ctx.setLineDash(dash);
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
ctx.restore();
}
/** CSS cubic-bezier(x1, y1, x2, y2) as a function of progress x (0–1). */
export function cubicBezier(x1: number, y1: number, x2: number, y2: number) {
const bx = (s: number) => 3 * (1 - s) * (1 - s) * s * x1 + 3 * (1 - s) * s * s * x2 + s * s * s;
const by = (s: number) => 3 * (1 - s) * (1 - s) * s * y1 + 3 * (1 - s) * s * s * y2 + s * s * s;
return (x: number) => {
if (x <= 0) return 0;
if (x >= 1) return 1;
let lo = 0;
let hi = 1;
let s = x;
for (let i = 0; i < 30; i++) {
s = (lo + hi) / 2;
if (bx(s) < x) lo = s;
else hi = s;
}
return by(s);
};
}
/** Rounded rectangle path helper. */
export function rrect(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number) {
ctx.beginPath();
ctx.roundRect(x, y, w, h, r);
}