diff --git a/CHANGELOG.md b/CHANGELOG.md index 911aecf..fd0a1db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 0.2.0 + +- `@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. All running morphs now share one `requestAnimationFrame` loop instead of one each. Planning a face→symbol morph takes about 0.16 ms, and a frame takes about 0.12 ms to compute and serialise. 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/package.json b/packages/morph/package.json index 70ddbc5..b98fd01 100644 --- a/packages/morph/package.json +++ b/packages/morph/package.json @@ -1,6 +1,6 @@ { "name": "@botharness/pixel-morph", - "version": "0.1.0", + "version": "0.2.0", "description": "Morph any pixel art into any other: pairing, arcs and grid-snapped frames, with an SVG renderer", "keywords": [ "animation", diff --git a/packages/morph/src/index.ts b/packages/morph/src/index.ts index 6b3df6d..eb28daf 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; @@ -95,12 +105,11 @@ export function escapeAttribute(value: string): string { return value.replace(/[&<>"']/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. - */ -export function pixelMarkup(cells: readonly PixelCell[]): string { +/** 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, +): void { const rows = new Map>(); for (const cell of cells) { if (!Number.isFinite(cell.x) || !Number.isFinite(cell.y)) continue; @@ -108,26 +117,73 @@ 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; } const active = new WeakMap(); +const tickers = new Set<(time: number) => void>(); +let loopId = 0; + +function loop(time: number): void { + for (const tick of [...tickers]) tick(time); + loopId = tickers.size > 0 ? requestAnimationFrame(loop) : 0; +} + +function addTicker(tick: (time: number) => void): void { + tickers.add(tick); + if (loopId === 0) loopId = requestAnimationFrame(loop); +} + +function removeTicker(tick: (time: number) => void): void { + tickers.delete(tick); + if (tickers.size === 0 && loopId !== 0) { + cancelAnimationFrame(loopId); + loopId = 0; + } +} /** - * 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 + * Plays a morph into an SVG group. Every running morph shares one `requestAnimationFrame` loop. `current()` returns the pixels + * 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,44 +191,45 @@ 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); - let frame = 0; + const frameMs = options.frameMs ?? 0; + const render = options.markup ?? pixelMarkup; let start = -1; + let step = -1; let shown: PixelCell[] = [...from]; let drawn = ''; let settle: (done: boolean) => void = () => undefined; const finished = new Promise((resolve) => { settle = resolve; }); - const tick = (time: number) => { + const stop = (done: boolean) => { + removeTicker(tick); + if (active.get(group) === run) active.delete(group); + settle(done); + }; + function tick(time: number): void { 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 = + 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); - const markup = pixelMarkup(shown); + const markup = render(shown); if (markup !== drawn) group.innerHTML = drawn = markup; - if (t >= 1) { - frame = 0; - if (active.get(group) === run) active.delete(group); - settle(true); - return; - } - frame = requestAnimationFrame(tick); - }; + if (t >= 1) stop(true); + } const run: PixelMorphRun = { current: () => shown, - cancel() { - if (frame) cancelAnimationFrame(frame); - frame = 0; - if (active.get(group) === run) active.delete(group); - settle(false); - }, + cancel: () => stop(false), finished, }; active.set(group, run); - frame = requestAnimationFrame(tick); + addTicker(tick); return run; } diff --git a/packages/morph/test/morph.test.ts b/packages/morph/test/morph.test.ts index 13f4261..5b45f57 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: '"/>