diff options
| author | Gabriel Schneider <[email protected]> | 2026-10-30 21:34:41 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-12 13:22:02 -0300 |
| commit | 2348776791e9dd17afeb12a06ba42a4a71917bcf (patch) | |
| tree | 780c4b12b76c8b97a28408dd40944d65f159fdc7 /tools | |
| parent | 590ba7b9b579b97e34b51ab7e3460ebc85713343 (diff) | |
| download | sketchbook-2348776791e9dd17afeb12a06ba42a4a71917bcf.tar.gz sketchbook-2348776791e9dd17afeb12a06ba42a4a71917bcf.zip | |
sketchbook: a drawing layer on top, host fixes for replay and migration
Diffstat (limited to 'tools')
| -rw-r--r-- | tools/chrome.mjs | 119 | ||||
| -rw-r--r-- | tools/reload_edit.zig | 49 | ||||
| -rw-r--r-- | tools/render_web.mjs | 13 | ||||
| -rw-r--r-- | tools/shapes_web.mjs | 41 | ||||
| -rw-r--r-- | tools/spirv_strip.zig | 33 | ||||
| -rw-r--r-- | tools/wasi_run.mjs | 9 |
6 files changed, 264 insertions, 0 deletions
diff --git a/tools/chrome.mjs b/tools/chrome.mjs new file mode 100644 index 0000000..e3361e9 --- /dev/null +++ b/tools/chrome.mjs @@ -0,0 +1,119 @@ +// Headless Chrome (software Canvas2D, no GPU needed) on a built web page, +// for tests: serves `dir` (plus `extra` files by URL path), opens it at +// `width` x `height`, waits for `window.sketch`, and hands `run` an +// `evaluate(expression)` that returns the value. Uncaught page errors fail. +import {spawn} from 'node:child_process'; +import {createServer} from 'node:http'; +import {mkdtemp, readFile, rm} from 'node:fs/promises'; +import {tmpdir} from 'node:os'; +import {extname, join} from 'node:path'; +import assert from 'node:assert/strict'; + +export async function withPage({dir, extra = {}, width, height, chromePath}, run) { + const types = {'.html': 'text/html', '.js': 'text/javascript', '.wasm': 'application/wasm', '.png': 'image/png'}; + const server = createServer(async (request, response) => { + const path = new URL(request.url, 'http://x').pathname; + try { + const body = extra[path] ? await readFile(extra[path]) : await readFile(join(dir, path === '/' ? 'index.html' : path)); + response.writeHead(200, {'content-type': types[extname(path)] ?? 'text/html'}); + response.end(body); + } catch { + response.writeHead(404); + response.end(); + } + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const url = `http://127.0.0.1:${server.address().port}/`; + const profile = await mkdtemp(join(tmpdir(), 'sketchbook-chrome-')); + const chrome = spawn(chromePath || process.env.CHROME || 'google-chrome-stable', ['--headless=new', '--no-sandbox', '--disable-gpu', '--no-first-run', + '--disable-background-networking', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'], {stdio: ['ignore', 'ignore', 'pipe']}); + const sleep = ms => new Promise(r => setTimeout(r, ms)); + let socket, stderr = '', sequence = 0; + const pending = new Map(), errors = []; + try { + chrome.stderr.on('data', b => stderr += b); + let endpoint; + for (let i = 0; i < 100 && !endpoint; i++) { + endpoint = stderr.match(/DevTools listening on (ws:\/\/\S+)/)?.[1]; + if (chrome.exitCode !== null) throw new Error(stderr); + if (!endpoint) await sleep(100); + } + assert.ok(endpoint, 'Chrome did not start'); + const tabs = await (await fetch(`${endpoint.replace(/^ws:/, 'http:').split('/devtools/')[0]}/json/list`)).json(); + socket = new WebSocket(tabs.find(t => t.type === 'page').webSocketDebuggerUrl); + await new Promise((resolve, reject) => { socket.onopen = resolve; socket.onerror = reject; }); + socket.onmessage = e => { + const m = JSON.parse(e.data); + if (m.id) { const p = pending.get(m.id); pending.delete(m.id); m.error ? p.reject(new Error(JSON.stringify(m.error))) : p.resolve(m.result); } + else if (m.method === 'Runtime.exceptionThrown') errors.push(m.params.exceptionDetails); + }; + const send = (method, params = {}) => new Promise((resolve, reject) => { const id = ++sequence; pending.set(id, {resolve, reject}); socket.send(JSON.stringify({id, method, params})); }); + const evaluate = async expression => { + const r = await send('Runtime.evaluate', {expression, returnByValue: true, awaitPromise: true}); + if (r.exceptionDetails) throw new Error(JSON.stringify(r.exceptionDetails)); + return r.result.value; + }; + await send('Runtime.enable'); + await send('Emulation.setDeviceMetricsOverride', {width, height, deviceScaleFactor: 1, mobile: false}); + await send('Page.navigate', {url}); + let ready = false; + for (let i = 0; i < 100 && !ready; i++) { ready = await evaluate(`!!window.sketch`); if (!ready) await sleep(100); } + assert.ok(ready, 'the sketch did not start'); + await run(evaluate); + assert.deepEqual(errors, []); + } finally { + socket?.close(); + chrome.kill('SIGTERM'); + await new Promise(r => chrome.exitCode !== null ? r() : chrome.once('exit', r)); + await rm(profile, {recursive: true, force: true, maxRetries: 10, retryDelay: 100}); + server.close(); + } +} + +// Page code comparing the canvas with `native.png`: pixels away from edges +// (neither picture changes by more than 8 within a pixel) must agree within +// `tolerance`; pixels next to edges are only counted, by how far apart. +export const compareScript = (width, height, tolerance, points) => `(async () => { + const W = ${width}, H = ${height}; + const canvas = document.querySelector('canvas'); + if (canvas.width !== W || canvas.height !== H) return {error: 'canvas is ' + canvas.width + 'x' + canvas.height}; + const web = canvas.getContext('2d').getImageData(0, 0, W, H).data; + const image = new Image(); + image.src = 'native.png'; + await image.decode(); + const scratch = new OffscreenCanvas(W, H).getContext('2d'); + scratch.drawImage(image, 0, 0); + const native = scratch.getImageData(0, 0, W, H).data; + const at = (d, x, y) => [0, 1, 2].map(c => d[(y * W + x) * 4 + c]); + const edge = (x, y) => { + for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) { + const nx = x + dx, ny = y + dy; + if (nx < 0 || ny < 0 || nx >= W || ny >= H) continue; + for (const d of [native, web]) { + const a = at(d, x, y), b = at(d, nx, ny); + if (a.some((v, c) => Math.abs(v - b[c]) > 8)) return true; + } + } + return false; + }; + let compared = 0, differing = 0, worst = 0, first = null, edges = 0, edgeOver16 = 0, edgeOver48 = 0, edgeSum = 0; + for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) { + const a = at(native, x, y), b = at(web, x, y); + const d = Math.max(...a.map((v, c) => Math.abs(v - b[c]))); + if (edge(x, y)) { edges++; edgeSum += d; if (d > 16) edgeOver16++; if (d > 48) edgeOver48++; continue; } + compared++; + worst = Math.max(worst, d); + if (d > ${tolerance}) { differing++; first ??= {x, y, native: a, web: b}; } + } + const sampled = {}; + for (const [name, [x, y]] of Object.entries(${JSON.stringify(points)})) sampled[name] = {native: at(native, x, y), web: at(web, x, y)}; + return {compared, edges, differing, worst, first, sampled, edgeOver16, edgeOver48, edgeMean: edges ? edgeSum / edges : 0}; +})()`; + +export function report(result, tolerance) { + assert.ok(!result.error, result.error); + console.log(`compared ${result.compared} pixels away from edges: ${result.differing} differ by more than ${tolerance}, worst ${result.worst}`); + console.log(`next to edges ${result.edges}: mean difference ${result.edgeMean.toFixed(1)}, ${result.edgeOver16} over 16, ${result.edgeOver48} over 48`); + for (const [name, {native, web}] of Object.entries(result.sampled)) console.log(` ${name.padEnd(8)} native ${native.join(',').padEnd(12)} web ${web.join(',')}`); + assert.equal(result.differing, 0, `first difference: ${JSON.stringify(result.first)}`); +} diff --git a/tools/reload_edit.zig b/tools/reload_edit.zig new file mode 100644 index 0000000..0fe2bf3 --- /dev/null +++ b/tools/reload_edit.zig @@ -0,0 +1,49 @@ +//! Copies a source tree and applies textual edits to the copy, for +//! `addReloadCheck`: `reload_edit <in dir> <out dir> [<file> <old> <new>]...`. +//! Each `old` must occur exactly once in its file (relative to the tree), +//! or nothing is written and the edit is reported. +const std = @import("std"); + +pub fn main(init: std.process.Init) !void { + const io = init.io; + const arena = init.arena.allocator(); + var args = init.minimal.args.iterate(); + _ = args.skip(); + const in_path = args.next() orelse return error.Usage; + const out_path = args.next() orelse return error.Usage; + const cwd = std.Io.Dir.cwd(); + + var input = try cwd.openDir(io, in_path, .{ .iterate = true }); + defer input.close(io); + var output = try cwd.createDirPathOpen(io, out_path, .{}); + defer output.close(io); + + var walker = try input.walk(arena); + defer walker.deinit(); + while (try walker.next(io)) |entry| switch (entry.kind) { + .directory => try output.createDirPath(io, entry.path), + .file, .sym_link => try input.copyFile(entry.path, output, entry.path, io, .{}), + else => {}, + }; + + var failed = false; + while (args.next()) |file| { + const old = args.next() orelse return error.Usage; + const new = args.next() orelse return error.Usage; + const source = output.readFileAlloc(io, file, arena, .limited(64 << 20)) catch |err| { + std.log.err("edit {s}: {t}", .{ file, err }); + failed = true; + continue; + }; + const count = std.mem.count(u8, source, old); + if (count != 1) { + std.log.err("edit {s}: the text to replace occurs {d} times, not once:\n{s}", .{ file, count, old }); + failed = true; + continue; + } + const at = std.mem.indexOf(u8, source, old).?; + const edited = try std.mem.concat(arena, u8, &.{ source[0..at], new, source[at + old.len ..] }); + try output.writeFile(io, .{ .sub_path = file, .data = edited }); + } + if (failed) std.process.exit(1); +} diff --git a/tools/render_web.mjs b/tools/render_web.mjs new file mode 100644 index 0000000..1327310 --- /dev/null +++ b/tools/render_web.mjs @@ -0,0 +1,13 @@ +// Draws test/render.zig (targets, blend modes, image placement and tint, +// colours per subpath, antialiased edges) in headless Chrome and compares +// it with the native host's screenshot of the same frame. +// usage: node tools/render_web.mjs <web dir> <native.png> [chrome] +import {withPage, compareScript, report} from './chrome.mjs'; + +const [dir, nativePng, chromePath] = process.argv.slice(2); +const points = {target: [30, 70], tinted: [140, 70], targetBlue: [20, 80], turned: [300, 60], add: [80, 175], addRect: [160, 150], + addImage: [156, 196], colors: [230, 160], ring: [350, 137], soft: [236, 236], softTint: [286, 236], line: [100, 280]}; +await withPage({dir, extra: {'/native.png': nativePng}, width: 400, height: 300, chromePath}, async evaluate => { + const tolerance = 3; + report(await evaluate(`(async () => { sketch.frame(performance.now()); sketch.frame(performance.now() + 16); return await ${compareScript(400, 300, tolerance, points)}; })()`), tolerance); +}); diff --git a/tools/shapes_web.mjs b/tools/shapes_web.mjs new file mode 100644 index 0000000..913bc8b --- /dev/null +++ b/tools/shapes_web.mjs @@ -0,0 +1,41 @@ +// Draws test/shapes.zig in headless Chrome (software Canvas2D, no GPU +// needed) and compares it with the native host's screenshot of the same +// frame: equal within a small tolerance everywhere except next to edges, +// which both antialias, differently. Then times 5000 +// circles a frame, one shape each and batched into one. +// usage: node tools/shapes_web.mjs <web dir> <native.png> [chrome] +import {withPage, compareScript, report} from './chrome.mjs'; +import assert from 'node:assert/strict'; + +const [dir, nativePng, chromePath] = process.argv.slice(2); +await withPage({dir, extra: {'/native.png': nativePng}, width: 400, height: 400, chromePath}, async evaluate => { + // One frame drawn now, then both pictures compared in the page. + const points = {circle: [60, 80], overlap: [110, 80], polygon: [300, 40], notch: [300, 120], join: [60, 228], ring: [300, 212], hole: [300, 240], line: [300, 300], above: [300, 299]}; + const result = await evaluate(`(async () => { sketch.frame(performance.now()); return await ${compareScript(400, 400, 3, points)}; })()`); + report(result, 3); + // The 1 px line at full intensity, as natively (a body thinned for an + // antialiasing fringe would give half). + assert.deepEqual(result.sampled.line.web, [0, 0, 0]); + assert.deepEqual(result.sampled.above.web, [255, 255, 255]); + + // Frame time with 5000 circles, raster included (getImageData waits for it). + const timing = await evaluate(`(() => { + const ctx = document.querySelector('canvas').getContext('2d'); + const time = line => { + sketch.command(line); + const times = []; + for (let i = 0; i < 12; i++) { + const t0 = performance.now(); + sketch.frame(t0); + ctx.getImageData(0, 0, 1, 1); + times.push(performance.now() - t0); + } + times.sort((a, b) => a - b); + return times[times.length >> 1]; + }; + return {separate: time('circles 5000'), batched: time('batched 5000')}; + })()`); + console.log(`5000 circles a frame, median: ${timing.separate.toFixed(1)} ms as 5000 shapes, ${timing.batched.toFixed(1)} ms batched into one`); + const budget = Number(process.env.SHAPES_BUDGET_MS ?? 16); + for (const [how, ms] of Object.entries(timing)) assert.ok(ms < budget, `5000 circles (${how}) took ${ms.toFixed(1)} ms, over ${budget} ms`); +}); diff --git a/tools/spirv_strip.zig b/tools/spirv_strip.zig new file mode 100644 index 0000000..e10711a --- /dev/null +++ b/tools/spirv_strip.zig @@ -0,0 +1,33 @@ +//! Drops memory-access operands (`Aligned 4`) from OpLoad/OpStore: Zig +//! emits them, Vulkan accepts them, naga's SPIR-V reader does not. +const std = @import("std"); + +pub fn main(init: std.process.Init) !void { + var args = init.minimal.args.iterate(); + _ = args.skip(); + const in_path = args.next().?; + const out_path = args.next().?; + const cwd = std.Io.Dir.cwd(); + const arena = init.arena.allocator(); + const bytes = try cwd.readFileAlloc(init.io, in_path, arena, .limited(16 << 20)); + const words: []const u32 = @alignCast(std.mem.bytesAsSlice(u32, bytes)); + if (words.len < 5 or words[0] != 0x07230203) return error.NotSpirv; + var out: std.ArrayList(u32) = .empty; + try out.appendSlice(arena, words[0..5]); + var i: usize = 5; + while (i < words.len) { + const count = words[i] >> 16; + const opcode = words[i] & 0xffff; + if (count == 0 or i + count > words.len) return error.Malformed; + // OpLoad: op, type, id, pointer; OpStore: op, pointer, object. + const keep: u32 = switch (opcode) { + 61 => @min(count, 4), + 62 => @min(count, 3), + else => count, + }; + try out.append(arena, (keep << 16) | opcode); + try out.appendSlice(arena, words[i + 1 .. i + keep]); + i += count; + } + try cwd.writeFile(init.io, .{ .sub_path = out_path, .data = std.mem.sliceAsBytes(out.items) }); +} diff --git a/tools/wasi_run.mjs b/tools/wasi_run.mjs new file mode 100644 index 0000000..ab5d95a --- /dev/null +++ b/tools/wasi_run.mjs @@ -0,0 +1,9 @@ +// Runs a wasm32-wasi program (a Zig test binary) under Node's WASI, with +// the rest of the arguments as its own; exits with its exit code. +// usage: node tools/wasi_run.mjs program.wasm [args...] +import {readFile} from 'node:fs/promises'; +import {WASI} from 'node:wasi'; + +const wasi = new WASI({version: 'preview1', args: process.argv.slice(2), env: {}, returnOnExit: true}); +const module = await WebAssembly.compile(await readFile(process.argv[2])); +process.exitCode = wasi.start(await WebAssembly.instantiate(module, wasi.getImportObject())); |
