T45b Site · Iso: isometric line miniatures on a canvas, hidden lines removed, cells on a marimba beat, playable under the pointer, still under reduced motion
This commit is contained in:
1 parent
ddcc8a4938
commit
02c2bbe0a1
13 files changed
+488
-15
No files matched your search
@@ -0,0 +1,27 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import { useMode } from "../theme";
|
||||
import { miniature } from "./draw";
|
||||
import type { Block } from "./engine";
|
||||
|
||||
/** Grows once it shows, and again when pressed. */
|
||||
export function Iso({ model, label, className }: { model: Block[]; label: string; className?: string }) {
|
||||
const canvas = useRef<HTMLCanvasElement>(null);
|
||||
const mini = useRef<ReturnType<typeof miniature> | null>(null);
|
||||
const theme = useMode();
|
||||
|
||||
useEffect(() => {
|
||||
const still = matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
const m = miniature(canvas.current!, model, still);
|
||||
mini.current = m;
|
||||
const seen = new IntersectionObserver(([e]) => e.isIntersecting && m.start(), { threshold: 0.35 });
|
||||
seen.observe(canvas.current!);
|
||||
return () => {
|
||||
seen.disconnect();
|
||||
m.stop();
|
||||
};
|
||||
}, [model]);
|
||||
|
||||
useEffect(() => mini.current?.repaint(), [theme]);
|
||||
|
||||
return <canvas ref={canvas} className={className} role="img" aria-label={label} onClick={() => mini.current?.replay()} />;
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import { bounds, faces, inside, painted, rise, type Block, type Point } from "./engine";
|
||||
import { BEAT, strike } from "./marimba";
|
||||
|
||||
const DRAW = BEAT * 2;
|
||||
const GROW = 320;
|
||||
const BUMP = 520;
|
||||
|
||||
interface Ink {
|
||||
ground: string;
|
||||
line: string;
|
||||
accent: string;
|
||||
side: string;
|
||||
shade: string;
|
||||
}
|
||||
|
||||
function ink(): Ink {
|
||||
const css = getComputedStyle(document.documentElement);
|
||||
const v = (name: string) => css.getPropertyValue(name).trim();
|
||||
return { ground: v("--bg"), line: v("--iso-line"), accent: v("--accent"), side: v("--iso-side"), shade: v("--iso-shade") };
|
||||
}
|
||||
|
||||
/** Grows cell by cell; a block under the pointer lifts and sounds. */
|
||||
export function miniature(canvas: HTMLCanvasElement, model: Block[], still: boolean) {
|
||||
const blocks = painted(model);
|
||||
const ctx = canvas.getContext("2d")!;
|
||||
let colors = ink();
|
||||
let started: number | null = still ? -Infinity : null;
|
||||
let struck = -1;
|
||||
let frame = 0;
|
||||
let view = { scale: 1, dx: 0, dy: 0 };
|
||||
const bumps = new Map<Block, number>();
|
||||
|
||||
const fit = () => {
|
||||
const dpr = Math.min(devicePixelRatio, 2);
|
||||
const { clientWidth: w, clientHeight: h } = canvas;
|
||||
canvas.width = Math.round(w * dpr);
|
||||
canvas.height = Math.round(h * dpr);
|
||||
const [x0, y0, x1, y1] = bounds(blocks);
|
||||
const scale = Math.min((w * 0.9) / (x1 - x0), (h * 0.86) / (y1 - y0));
|
||||
view = { scale: scale * dpr, dx: (w * dpr - (x1 + x0) * scale * dpr) / 2, dy: (h * dpr - (y1 + y0) * scale * dpr) / 2 };
|
||||
};
|
||||
|
||||
const at = ([x, y]: Point): Point => [x * view.scale + view.dx, y * view.scale + view.dy];
|
||||
|
||||
const path = (poly: Point[], upto = 1) => {
|
||||
ctx.beginPath();
|
||||
const pts = poly.map(at);
|
||||
ctx.moveTo(...pts[0]);
|
||||
// The footprint draws itself edge by edge.
|
||||
const edges = pts.length * upto;
|
||||
for (let i = 1; i <= Math.floor(edges); i++) ctx.lineTo(...pts[i % pts.length]);
|
||||
const part = edges - Math.floor(edges);
|
||||
if (part > 0 && edges < pts.length) {
|
||||
const [a, b] = [pts[Math.floor(edges) % pts.length], pts[(Math.floor(edges) + 1) % pts.length]];
|
||||
ctx.lineTo(a[0] + (b[0] - a[0]) * part, a[1] + (b[1] - a[1]) * part);
|
||||
}
|
||||
};
|
||||
|
||||
const draw = (now: number) => {
|
||||
frame = 0;
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0);
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
ctx.lineJoin = "round";
|
||||
ctx.lineWidth = Math.max(1, view.scale * 0.018);
|
||||
let moving = false;
|
||||
for (const b of blocks) {
|
||||
const since = started === null ? -1 : now - started - b.beat * BEAT;
|
||||
if (since < 0) {
|
||||
moving ||= started !== null;
|
||||
continue;
|
||||
}
|
||||
const drawn = Math.min(1, since / DRAW);
|
||||
const grown = rise((since - DRAW) / GROW);
|
||||
const bump = bumps.get(b);
|
||||
const lift = bump === undefined ? 0 : Math.max(0, 1 - (now - bump) / BUMP);
|
||||
if (bump !== undefined && lift === 0) bumps.delete(b);
|
||||
moving ||= drawn < 1 || since - DRAW < GROW || lift > 0;
|
||||
const h = Math.max(b.h * grown * (1 + 0.35 * Math.sin(lift * Math.PI)), 0.0001);
|
||||
const f = faces(b, h);
|
||||
const stroke = b.accent ? colors.accent : colors.line;
|
||||
if (drawn < 1) {
|
||||
ctx.strokeStyle = stroke;
|
||||
path(f.top, drawn);
|
||||
ctx.stroke();
|
||||
continue;
|
||||
}
|
||||
for (const [poly, fill] of [[f.right, colors.shade], [f.front, colors.side], [f.top, colors.ground]] as const) {
|
||||
path(poly);
|
||||
ctx.closePath();
|
||||
ctx.fillStyle = fill;
|
||||
ctx.fill();
|
||||
ctx.strokeStyle = stroke;
|
||||
ctx.stroke();
|
||||
}
|
||||
}
|
||||
if (started !== null && !still) {
|
||||
const beat = Math.floor((now - started) / BEAT);
|
||||
for (; struck < beat; ) {
|
||||
struck++;
|
||||
const first = blocks.find((b) => b.beat === struck);
|
||||
if (first) strike(struck + Math.round(first.h * 2));
|
||||
}
|
||||
}
|
||||
if (moving) request();
|
||||
};
|
||||
|
||||
const request = () => {
|
||||
if (!frame) frame = requestAnimationFrame(draw);
|
||||
};
|
||||
|
||||
const pointer = (e: PointerEvent) => {
|
||||
if (still) return;
|
||||
const r = canvas.getBoundingClientRect();
|
||||
const dpr = canvas.width / r.width;
|
||||
const p: Point = [((e.clientX - r.left) * dpr - view.dx) / view.scale, ((e.clientY - r.top) * dpr - view.dy) / view.scale];
|
||||
for (let i = blocks.length - 1; i >= 0; i--) {
|
||||
const b = blocks[i];
|
||||
const f = faces(b, b.h);
|
||||
if (inside(p, f.top) || inside(p, f.front) || inside(p, f.right)) {
|
||||
// The table itself stays put.
|
||||
if (b.y === 0) return;
|
||||
if (!bumps.has(b)) {
|
||||
bumps.set(b, performance.now());
|
||||
strike(Math.round(b.x + b.z + b.h * 2), 0.5);
|
||||
request();
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const resized = new ResizeObserver(() => (fit(), request()));
|
||||
resized.observe(canvas);
|
||||
canvas.addEventListener("pointermove", pointer);
|
||||
fit();
|
||||
request();
|
||||
return {
|
||||
start() {
|
||||
// Still, it stands grown from the first frame.
|
||||
if (started !== null) return;
|
||||
started = performance.now();
|
||||
struck = -1;
|
||||
request();
|
||||
},
|
||||
replay() {
|
||||
if (still) return;
|
||||
started = performance.now();
|
||||
struck = -1;
|
||||
request();
|
||||
},
|
||||
repaint() {
|
||||
colors = ink();
|
||||
request();
|
||||
},
|
||||
stop() {
|
||||
cancelAnimationFrame(frame);
|
||||
resized.disconnect();
|
||||
canvas.removeEventListener("pointermove", pointer);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { bounds, faces, inside, painted, project, rise, type Block } from "./engine.ts";
|
||||
|
||||
const block = (x: number, z: number, w: number, d: number, h: number, y = 0): Block => ({ x, z, w, d, h, y, beat: 0 });
|
||||
|
||||
test("the projection keeps vertical lines vertical and the axes at thirty degrees", () => {
|
||||
const [ox, oy] = project(0, 0, 0);
|
||||
const [ux, uy] = project(0, 1, 0);
|
||||
assert.equal(ux, ox);
|
||||
assert.equal(uy, oy - 1);
|
||||
const [xx, xy] = project(1, 0, 0);
|
||||
assert.ok(Math.abs(Math.atan2(xy, xx) - Math.PI / 6) < 1e-9);
|
||||
});
|
||||
|
||||
test("a block standing on a slab paints after it", () => {
|
||||
const slab = block(0, 0, 10, 10, 0.5);
|
||||
const tower = block(2, 2, 1, 1, 3, 0.5);
|
||||
assert.deepEqual(painted([tower, slab]), [slab, tower]);
|
||||
});
|
||||
|
||||
test("a block behind another paints first, on either axis", () => {
|
||||
const far = block(0, 0, 1, 1, 1);
|
||||
const nearX = block(2, 0, 1, 1, 1);
|
||||
const nearZ = block(0, 2, 1, 1, 1);
|
||||
assert.deepEqual(painted([nearX, far]), [far, nearX]);
|
||||
assert.deepEqual(painted([nearZ, far]), [far, nearZ]);
|
||||
});
|
||||
|
||||
test("blocks apart on both axes keep the order they came in", () => {
|
||||
const left = block(0, 3, 1, 1, 1);
|
||||
const right = block(3, 0, 1, 1, 1);
|
||||
assert.deepEqual(painted([left, right]), [left, right]);
|
||||
assert.deepEqual(painted([right, left]), [right, left]);
|
||||
});
|
||||
|
||||
test("a point inside a top face hits it, one outside misses", () => {
|
||||
const top = faces(block(0, 0, 2, 2, 1), 1).top;
|
||||
const centre = project(1, 1, 1);
|
||||
assert.ok(inside(centre, top));
|
||||
assert.ok(!inside(project(5, 1, 5), top));
|
||||
});
|
||||
|
||||
test("bounds hold every corner at full height", () => {
|
||||
const [x0, y0, x1, y1] = bounds([block(0, 0, 1, 1, 2)]);
|
||||
const top = project(0, 2, 0);
|
||||
assert.ok(top[1] >= y0 && top[1] <= y1 && top[0] >= x0 && top[0] <= x1);
|
||||
});
|
||||
|
||||
test("the rise starts at zero, overshoots, and settles at one", () => {
|
||||
assert.equal(rise(0), 0);
|
||||
assert.equal(rise(1), 1);
|
||||
assert.ok(Math.max(...Array.from({ length: 50 }, (_, i) => rise(i / 50))) > 1);
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
/** A box on the table, its accent, and its beat. */
|
||||
export interface Block {
|
||||
x: number;
|
||||
z: number;
|
||||
w: number;
|
||||
d: number;
|
||||
y: number;
|
||||
h: number;
|
||||
accent?: boolean;
|
||||
beat: number;
|
||||
}
|
||||
|
||||
export type Point = [number, number];
|
||||
|
||||
const COS = Math.cos(Math.PI / 6);
|
||||
|
||||
/** Isometric: x runs down-right, z down-left, y up. */
|
||||
export function project(x: number, y: number, z: number): Point {
|
||||
return [(x - z) * COS, (x + z) * 0.5 - y];
|
||||
}
|
||||
|
||||
const EPS = 1e-6;
|
||||
|
||||
/** Whether `a` paints before `b`: under or behind it. */
|
||||
function under(a: Block, b: Block): boolean {
|
||||
const apartX = a.x + a.w <= b.x + EPS || b.x + b.w <= a.x + EPS;
|
||||
const apartZ = a.z + a.d <= b.z + EPS || b.z + b.d <= a.z + EPS;
|
||||
if (!apartX && !apartZ) return a.y < b.y || (a.y === b.y && a.h < b.h);
|
||||
// Apart on both axes, they stand side by side.
|
||||
if (apartX && apartZ) return false;
|
||||
return apartX ? a.x + a.w <= b.x + EPS : a.z + a.d <= b.z + EPS;
|
||||
}
|
||||
|
||||
/** Back to front: each block after what it covers. */
|
||||
export function painted(blocks: Block[]): Block[] {
|
||||
const n = blocks.length;
|
||||
const after: number[][] = blocks.map(() => []);
|
||||
const waiting = new Array<number>(n).fill(0);
|
||||
for (let i = 0; i < n; i++) {
|
||||
for (let j = 0; j < n; j++) {
|
||||
if (i !== j && under(blocks[i], blocks[j])) {
|
||||
after[i].push(j);
|
||||
waiting[j]++;
|
||||
}
|
||||
}
|
||||
}
|
||||
const ready = blocks.map((_, i) => i).filter((i) => waiting[i] === 0);
|
||||
const out: Block[] = [];
|
||||
while (ready.length) {
|
||||
const i = ready.shift()!;
|
||||
out.push(blocks[i]);
|
||||
for (const j of after[i]) if (--waiting[j] === 0) ready.push(j);
|
||||
}
|
||||
if (out.length !== n) throw new Error(`iso: ${n - out.length} blocks overlap and have no painting order`);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The three faces the eye sees, at height `h`. */
|
||||
export function faces(b: Block, h: number): { top: Point[]; right: Point[]; front: Point[] } {
|
||||
const [x0, x1, z0, z1, y0, y1] = [b.x, b.x + b.w, b.z, b.z + b.d, b.y, b.y + h];
|
||||
return {
|
||||
top: [project(x0, y1, z0), project(x1, y1, z0), project(x1, y1, z1), project(x0, y1, z1)],
|
||||
right: [project(x1, y0, z0), project(x1, y0, z1), project(x1, y1, z1), project(x1, y1, z0)],
|
||||
front: [project(x0, y0, z1), project(x1, y0, z1), project(x1, y1, z1), project(x0, y1, z1)],
|
||||
};
|
||||
}
|
||||
|
||||
/** Whether `p` lies inside the convex polygon `poly`. */
|
||||
export function inside(p: Point, poly: Point[]): boolean {
|
||||
let sign = 0;
|
||||
for (let i = 0; i < poly.length; i++) {
|
||||
const [a, b] = [poly[i], poly[(i + 1) % poly.length]];
|
||||
const cross = (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]);
|
||||
if (cross === 0) continue;
|
||||
if (sign === 0) sign = Math.sign(cross);
|
||||
else if (Math.sign(cross) !== sign) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** The projected box that holds every block at full height. */
|
||||
export function bounds(blocks: Block[]): [number, number, number, number] {
|
||||
let [x0, y0, x1, y1] = [Infinity, Infinity, -Infinity, -Infinity];
|
||||
for (const b of blocks) {
|
||||
const f = faces(b, b.h);
|
||||
for (const [x, y] of [...f.top, ...f.right, ...f.front]) {
|
||||
[x0, y0, x1, y1] = [Math.min(x0, x), Math.min(y0, y), Math.max(x1, x), Math.max(y1, y)];
|
||||
}
|
||||
}
|
||||
return [x0, y0, x1, y1];
|
||||
}
|
||||
|
||||
/** Back-out easing: a block overshoots its height, then settles. */
|
||||
export function rise(t: number): number {
|
||||
if (t <= 0) return 0;
|
||||
if (t >= 1) return 1;
|
||||
const u = t - 1;
|
||||
return 1 + 2.4 * u ** 3 + 1.4 * u ** 2;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { useSyncExternalStore } from "react";
|
||||
|
||||
/** A sixteenth at 132 beats a minute. */
|
||||
export const BEAT = 60_000 / 132 / 4;
|
||||
|
||||
// C major pentatonic, C4 to E6.
|
||||
const SCALE = [0, 2, 4, 7, 9, 12, 14, 16, 19, 21, 24, 26, 28];
|
||||
const LISTENERS = new Set<(on: boolean) => void>();
|
||||
|
||||
let context: AudioContext | null = null;
|
||||
let bus: GainNode | null = null;
|
||||
let on = false;
|
||||
let last = 0;
|
||||
|
||||
export function soundOn(): boolean {
|
||||
return on;
|
||||
}
|
||||
|
||||
/** Turns sound on or off; browsers need a press first. */
|
||||
export function setSound(next: boolean): void {
|
||||
on = next;
|
||||
if (on && !context) {
|
||||
context = new AudioContext();
|
||||
bus = context.createGain();
|
||||
bus.gain.value = 0.28;
|
||||
const squeeze = context.createDynamicsCompressor();
|
||||
bus.connect(squeeze).connect(context.destination);
|
||||
console.info("marimba: audio started");
|
||||
}
|
||||
if (on) void context!.resume();
|
||||
LISTENERS.forEach((listen) => listen(on));
|
||||
}
|
||||
|
||||
export function onSound(listen: (on: boolean) => void): () => void {
|
||||
LISTENERS.add(listen);
|
||||
return () => LISTENERS.delete(listen);
|
||||
}
|
||||
|
||||
/** Strikes the scale's `step`th note; strikes within 30 ms merge. */
|
||||
export function strike(step: number, velocity = 0.7): void {
|
||||
if (!on || !context || !bus) return;
|
||||
const now = context.currentTime;
|
||||
if (now - last < 0.03) return;
|
||||
last = now;
|
||||
const index = ((step % SCALE.length) + SCALE.length) % SCALE.length;
|
||||
const hz = 261.63 * 2 ** (SCALE[index] / 12);
|
||||
// A struck bar: a fundamental, a partial, a click.
|
||||
for (const [ratio, gain, decay] of [
|
||||
[1, 1, 0.9],
|
||||
[3.93, 0.28, 0.18],
|
||||
[9.2, 0.06, 0.05],
|
||||
]) {
|
||||
const tone = context.createOscillator();
|
||||
const env = context.createGain();
|
||||
tone.type = "sine";
|
||||
tone.frequency.value = hz * ratio;
|
||||
env.gain.setValueAtTime(0, now);
|
||||
env.gain.linearRampToValueAtTime(gain * velocity, now + 0.004);
|
||||
env.gain.exponentialRampToValueAtTime(0.0001, now + decay);
|
||||
tone.connect(env).connect(bus);
|
||||
tone.start(now);
|
||||
tone.stop(now + decay + 0.05);
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether sound is on, redrawn when it turns. */
|
||||
export function useSound(): boolean {
|
||||
return useSyncExternalStore((listen) => onSound(listen), soundOn);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { Block } from "./engine";
|
||||
|
||||
const b = (x: number, z: number, w: number, d: number, h: number, y = 0, accent = false): Block => ({ x, z, w, d, h, y, accent, beat: 0 });
|
||||
|
||||
/** Beats from the far corner toward the eye. */
|
||||
const sweep = (blocks: Block[], pace: number) => blocks.map((k) => ({ ...k, beat: Math.round((k.x + k.z) * pace) }));
|
||||
|
||||
/** An app: title bar, sidebar, chart, chat, switch. */
|
||||
export function app(): Block[] {
|
||||
const s: Block[] = [b(0, 0, 18, 12, 0.5)];
|
||||
s.push(b(0.6, 0.6, 16.8, 1, 0.25, 0.5));
|
||||
for (let i = 0; i < 3; i++) s.push(b(1 + i * 0.8, 0.85, 0.45, 0.45, 0.25, 0.75, i === 0));
|
||||
for (let i = 0; i < 6; i++) s.push(b(0.8, 2.2 + i * 1.5, 3.4, 1, 0.25, 0.5, i === 1));
|
||||
s.push(b(5, 2.2, 7.4, 1, 0.2, 0.5));
|
||||
s.push(b(5, 3.8, 7.4, 6.4, 0.08, 0.5));
|
||||
[0.9, 1.5, 1.2, 2.1, 1.7, 2.8, 2.3, 3.2].forEach((h, i) => s.push(b(5.5 + i * 0.85, 7.6, 0.55, 1.2, h, 0.58, i === 5)));
|
||||
for (let i = 0; i < 4; i++) s.push(b(i % 2 ? 14.2 : 13, 2.2 + i * 1.7, i % 2 ? 2.8 : 3.6, 1.2, 0.4, 0.5, i === 3));
|
||||
s.push(b(13, 9.8, 1.6, 0.8, 0.3, 0.5), b(13.9, 9.8, 0.7, 0.8, 0.6, 0.5, true));
|
||||
return sweep(s, 0.9);
|
||||
}
|
||||
Reference in new issue
Block a user