From 26f9f80a885eeb58b9b4c1e4fdc01a8dd61ea413 Mon Sep 17 00:00:00 2001 From: DoodleBear Date: Mon, 5 Oct 2026 18:24:13 +0900 Subject: [PATCH 1/3] feat(morph): step morphs at frameMs and draw one path per colour morphPixels takes frameMs, which advances in fixed steps and draws only when the step changes, and markup, which chooses the renderer. The new pixelPathMarkup draws one per colour. Defaults and pixelMarkup output are unchanged, so the golden hashes still hold. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 4 ++ packages/morph/README.md | 2 +- packages/morph/src/index.ts | 68 +++++++++++++++++++++++++++---- packages/morph/test/morph.test.ts | 38 +++++++++++++++++ 4 files changed, 102 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 911aecf..306ec8f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## Unreleased + +- `@botharness/pixel-morph`: `morphPixels` takes `frameMs` to advance in fixed steps and only draw when the step changes, and `markup` to choose the renderer; the new `pixelPathMarkup` draws one `` per colour. Defaults and `pixelMarkup` output are unchanged. In BotHarness this cut 32 simultaneous pixel morphs from about 1 s to about 0.2 s of main-thread work per second. + ## 0.1.0 - `@botharness/pixel-morph`: pixel pairing, frames, SVG markup and a `requestAnimationFrame` player, extracted from BotHarness; grid size is now an option. diff --git a/packages/morph/README.md b/packages/morph/README.md index 1b786aa..478252c 100644 --- a/packages/morph/README.md +++ b/packages/morph/README.md @@ -23,4 +23,4 @@ const pairs = planPixels(from, to); const svgRects = pixelMarkup(pixelFrame(pairs, 0.5)); ``` -Grids default to 32×32; pass `{ size }` to `planPixels`, `pixelFrame` and `morphPixels` for others. `run.current()` returns the pixels on screen, so a new morph can start mid-flight. +Grids default to 32×32; pass `{ size }` to `planPixels`, `pixelFrame` and `morphPixels` for others. When many morphs run at once, pass `{ frameMs: 50, markup: pixelPathMarkup }` to `morphPixels`: it steps at a pixel-art 20 fps and draws one `` per colour instead of one `` per run. `run.current()` returns the pixels on screen, so a new morph can start mid-flight. diff --git a/packages/morph/src/index.ts b/packages/morph/src/index.ts index 6b3df6d..8682f00 100644 --- a/packages/morph/src/index.ts +++ b/packages/morph/src/index.ts @@ -18,6 +18,16 @@ export interface PixelGridOptions { size?: number; } +export interface PixelMorphOptions extends PixelGridOptions { + /** + * Advance the morph in steps of this many milliseconds, computing and drawing a frame only + * when the step changes (50 gives a pixel-art 20 fps). 0, the default, draws every display frame. + */ + frameMs?: number; + /** Turns cells into SVG markup. Defaults to `pixelMarkup`; `pixelPathMarkup` creates fewer nodes. */ + markup?: (cells: readonly PixelCell[]) => string; +} + export interface PixelMorphRun { current(): PixelCell[]; cancel(): void; @@ -100,7 +110,10 @@ export function escapeAttribute(value: string): string { * cells whose coordinates are not finite numbers are skipped, so the markup is safe to assign to * `innerHTML` whatever the cells contain. */ -export function pixelMarkup(cells: readonly PixelCell[]): string { +function colourRuns( + cells: readonly PixelCell[], + emit: (x: number, y: number, width: number, colour: string) => void, +): void { const rows = new Map>(); for (const cell of cells) { if (!Number.isFinite(cell.x) || !Number.isFinite(cell.y)) continue; @@ -108,18 +121,44 @@ export function pixelMarkup(cells: readonly PixelCell[]): string { if (!row) rows.set(cell.y, (row = new Map())); row.set(cell.x, cell.c); } - let markup = ''; for (const [y, row] of rows) { const xs = [...row.keys()].sort((a, b) => a - b); for (let i = 0; i < xs.length;) { const x = xs[i]!; - const color = row.get(x)!; + const colour = row.get(x)!; let width = 1; - while (xs[i + width] === x + width && row.get(x + width) === color) width++; - markup += ``; + while (xs[i + width] === x + width && row.get(x + width) === colour) width++; + emit(x, y, width, colour); i += width; } } +} + +/** + * SVG `` markup for cells, merging horizontal runs of one colour. Colours are escaped and + * cells whose coordinates are not finite numbers are skipped, so the markup is safe to assign to + * `innerHTML` whatever the cells contain. + */ +export function pixelMarkup(cells: readonly PixelCell[]): string { + let markup = ''; + colourRuns(cells, (x, y, width, colour) => { + markup += ``; + }); + return markup; +} + +/** + * The same pixels as `pixelMarkup`, drawn as one `` per colour. A frame becomes a handful + * of SVG nodes instead of one per run, which keeps many simultaneous morphs cheap. Escaping and + * coordinate checks match `pixelMarkup`. + */ +export function pixelPathMarkup(cells: readonly PixelCell[]): string { + const paths = new Map(); + colourRuns(cells, (x, y, width, colour) => { + paths.set(colour, `${paths.get(colour) ?? ''}M${x} ${y}h${width}v1h-${width}z`); + }); + let markup = ''; + for (const [colour, d] of paths) markup += ``; return markup; } @@ -127,7 +166,8 @@ const active = new WeakMap(); /** * Plays a morph into an SVG group with `requestAnimationFrame`. `current()` returns the pixels - * on screen, so a new morph can start from mid-flight. Starting a morph on a group cancels the + * on screen, so a new morph can start from mid-flight. `frameMs` steps the morph at a fixed + * rate and `markup` chooses the renderer. Starting a morph on a group cancels the * one already running there, so only the newest run draws. */ export function morphPixels( @@ -135,12 +175,15 @@ export function morphPixels( from: readonly PixelCell[], to: readonly PixelCell[], duration: number, - options: PixelGridOptions = {}, + options: PixelMorphOptions = {}, ): PixelMorphRun { active.get(group)?.cancel(); const pairs = planPixels(from, to, options); + const frameMs = options.frameMs ?? 0; + const render = options.markup ?? pixelMarkup; let frame = 0; let start = -1; + let step = -1; let shown: PixelCell[] = [...from]; let drawn = ''; let settle: (done: boolean) => void = () => undefined; @@ -149,9 +192,16 @@ export function morphPixels( }); const tick = (time: number) => { if (start < 0) start = time; - const t = Math.min(1, (time - start) / duration); + const elapsed = time - start; + const next = frameMs > 0 ? Math.floor(elapsed / frameMs) : elapsed; + const t = Math.min(1, (frameMs > 0 ? next * frameMs : elapsed) / duration); + if (next === step && t < 1) { + frame = requestAnimationFrame(tick); + return; + } + step = next; shown = t >= 1 ? [...to] : pixelFrame(pairs, t, options); - const markup = pixelMarkup(shown); + const markup = render(shown); if (markup !== drawn) group.innerHTML = drawn = markup; if (t >= 1) { frame = 0; diff --git a/packages/morph/test/morph.test.ts b/packages/morph/test/morph.test.ts index 13f4261..b4a1639 100644 --- a/packages/morph/test/morph.test.ts +++ b/packages/morph/test/morph.test.ts @@ -4,6 +4,7 @@ import { morphPixels, pixelFrame, pixelMarkup, + pixelPathMarkup, planPixels, type PixelCell, } from '../src/index.js'; @@ -66,6 +67,21 @@ describe('pixelMarkup', () => { }); }); +describe('pixelPathMarkup', () => { + it('draws one path per colour covering the same runs', () => { + expect(pixelPathMarkup(cellsFromRows(['AAB', 'A'], { A: '#000000', B: '#ffffff' }))).toBe( + '', + ); + }); + + it('escapes colours and skips non-finite coordinates like pixelMarkup', () => { + const hostile = { x: '0" onload="alert(1)', y: 0, c: '#000000' } as unknown as PixelCell; + expect(pixelPathMarkup([hostile, { x: 1, y: Number.NaN, c: '#000000' }])).toBe(''); + const markup = pixelPathMarkup([{ x: 0, y: 0, c: '"/>"']/gu, (char) => `&#${char.charCodeAt(0)};`); } -/** - * SVG `` markup for cells, merging horizontal runs of one colour. Colours are escaped and - * cells whose coordinates are not finite numbers are skipped, so the markup is safe to assign to - * `innerHTML` whatever the cells contain. - */ +/** Walks cells row by row, merging horizontal runs of one colour, and skips non-finite coordinates. */ function colourRuns( cells: readonly PixelCell[], emit: (x: number, y: number, width: number, colour: string) => void, @@ -218,7 +214,8 @@ export function morphPixels( if (start < 0) start = time; const elapsed = time - start; const next = frameMs > 0 ? Math.floor(elapsed / frameMs) : elapsed; - const t = Math.min(1, (frameMs > 0 ? next * frameMs : elapsed) / duration); + const t = + elapsed >= duration ? 1 : Math.min(1, (frameMs > 0 ? next * frameMs : elapsed) / duration); if (next === step && t < 1) return; step = next; shown = t >= 1 ? [...to] : pixelFrame(pairs, t, options);