Unlock custom brushes, natural fill effects and intuitive hatching in p5.js
autoresearch: add benchmark and session files
acamposuribe18336271fa13
diff --git a/autoresearch.md b/autoresearch.mdnew file mode 100644index 0000000..954878d--- /dev/null+++ b/autoresearch.md@@ -0,0 +1,62 @@+# Autoresearch: p5.brush Performance Optimization++## Objective+Optimize the core computational hot paths in p5.brush for maximum speed with **zero visual changes**.+The library renders generative brush strokes, watercolor fills, and hatch patterns. We optimize the+pure math and data structure operations that run thousands of times per frame.++## Metrics+- **Primary**: `total_ms` (ms, lower is better) — sum of all hot-path timings+- **Secondary**: `trig_ms`, `gauss_ms`, `plot_ms`, `hatch_ms`, `intersect_ms`, `intersect_lines_ms`++## How to Run+```+./autoresearch.sh+```+Outputs `METRIC name=value` lines. Tests must pass. Benchmark imports from actual source files.++## Files in Scope+- `src/core/utils.js` — Math utilities: cos/sin lookup tables, random number generators, gaussian, intersectLines, map, constrain, rotate, dist+- `src/core/plot.js` — Plot class: calcIndex (O(n) linear scan), angle(), pressure(), curving() interpolation+- `src/core/polygon.js` — Polygon class: intersect() with cache+- `src/hatch/hatch.js` — scanlineHatch(): edge-list intersection, scanline generation+- `src/fill/fill.js` — FillPoly: grow(), trim(), scatter() — watercolor simulation hot path+- `benchmark/bench.mjs` — Benchmark script (imports from source)+- `benchmark/loader.mjs` — ESM loader stub for .vert/.frag files++## Off Limits+- `src/stroke/gl_draw.js` — WebGL rendering, not benchmarked+- `src/core/color.js` — Compositor/color management+- `test/` — Tests must keep passing unchanged+- No new dependencies++## Constraints+- All 50 existing tests must pass after every change+- Visual output must be identical (same RNG sequence, same math results within float precision)+- No algorithmic changes that alter output values++## What's Been Tried++### Baseline+- Established benchmark: total_ms ≈ 36-37ms+- trig_ms ≈ 7ms (lookup table already in place)+- gauss_ms ≈ 3ms (Box-Muller with trig lookup)+- plot_ms ≈ 13ms (Plot.calcIndex is O(n) linear scan)+- hatch_ms ≈ 6ms (scanlineHatch with edge intersections)+- intersect_ms ≈ 5ms (Polygon.intersect with cache)+- intersect_lines_ms ≈ 2ms++### Key Observations+1. **plot_ms dominates** at ~35% of total. Plot.calcIndex() does a linear scan through segments on every angle/pressure query. This is called thousands of times per stroke.+2. **trig lookup tables** are already implemented (good optimization already in place)+3. **Polygon.intersect cache** already uses string key caching+4. **gaussian()** uses Box-Muller with cos() lookup — could pool pre-computed values+5. **intersectLines()** uses early exit checks — pretty lean already++### Ideas to Try+- [ ] Plot.calcIndex(): Use binary search instead of linear scan (O(log n) vs O(n))+- [ ] Plot: Cache cumulative segment lengths for faster binary search+- [ ] Polygon.intersect: Replace string key with numeric hash for cache lookup+- [ ] scanlineHatch: Avoid repeated rotation math per scanline+- [ ] intersectLines: Simplify with direct computations+- [ ] gaussian pool: Pre-compute pool at seed time, use cycling indexdiff --git a/autoresearch.sh b/autoresearch.shnew file mode 100755index 0000000..6ed68fc--- /dev/null+++ b/autoresearch.sh@@ -0,0 +1,8 @@+#!/bin/bash+set -euo pipefail++# Correctness check first (fast)+npm test --silent 2>&1 | grep -E "passed|failed|error" | tail -3++# Run benchmark (imports actual source files)+node --experimental-loader ./benchmark/loader.mjs benchmark/bench.mjs 2>/dev/nulldiff --git a/benchmark/bench.mjs b/benchmark/bench.mjsnew file mode 100644index 0000000..70a7f7a--- /dev/null+++ b/benchmark/bench.mjs@@ -0,0 +1,149 @@+/**+ * p5.brush Performance Benchmark+ * ================================+ * Imports directly from source files to ensure benchmark always reflects+ * the actual implementation. Uses a custom ESM loader to stub GLSL shaders.+ *+ * Run via: node --experimental-loader ./benchmark/loader.mjs benchmark/bench.mjs+ * Outputs METRIC lines for autoresearch.+ */++import { performance } from "perf_hooks";+import { setTargetState } from "../src/core/target.js";+import {+ cos, sin, gaussian, map, rr, randInt, constrain, dist, rotate, intersectLines, seed,+} from "../src/core/utils.js";+import { Plot } from "../src/core/plot.js";+import { Polygon } from "../src/core/polygon.js";+import { hatch, getHatchLines } from "../src/hatch/hatch.js";++// Setup minimal environment+setTargetState({ Cwidth: 800, Cheight: 600, Density: 1 });+seed(42);++// ============================================================+// BENCHMARK RUNNER+// ============================================================++function bench(fn, iterations) {+ // Warmup+ for (let i = 0; i < Math.min(Math.ceil(iterations / 10), 100); i++) fn();+ // Timed run+ const t0 = performance.now();+ for (let i = 0; i < iterations; i++) fn();+ return performance.now() - t0;+}++function medianOf(arr) {+ const sorted = [...arr].sort((a, b) => a - b);+ const mid = Math.floor(sorted.length / 2);+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;+}++const RUNS = 7;++// ============================================================+// 1. TRIG LOOKUP (cos/sin from utils.js)+// ============================================================+function benchTrig() {+ let sum = 0;+ for (let i = 0; i < 10000; i++) {+ sum += cos(i * 0.1) + sin(i * 0.1 + 45.3);+ }+ return sum;+}+const trigMs = medianOf(Array.from({ length: RUNS }, () => bench(benchTrig, 100)));++// ============================================================+// 2. GAUSSIAN RANDOM (Box-Muller from utils.js)+// ============================================================+function benchGaussian() {+ let sum = 0;+ for (let i = 0; i < 1000; i++) sum += gaussian(0, 1);+ return sum;+}+const gaussMs = medianOf(Array.from({ length: RUNS }, () => bench(benchGaussian, 200)));++// ============================================================+// 3. PLOT: calcIndex + angle + pressure+// ============================================================+const testPlot = new Plot("curve");+for (let i = 0; i < 20; i++) testPlot.addSegment(i * 18, 50, 0.8);+testPlot.endPlot(0, 1.0);++function benchPlot() {+ let sum = 0;+ for (let d = 0; d < testPlot.length; d += 2) {+ sum += testPlot.angle(d) + testPlot.pressure(d);+ }+ return sum;+}+const plotMs = medianOf(Array.from({ length: RUNS }, () => bench(benchPlot, 2000)));++// ============================================================+// 4. HATCH: scanlineHatch (via getHatchLines)+// ============================================================+const hatchPolyPts = [];+for (let i = 0; i < 200; i++) {+ const a = (i / 200) * 2 * Math.PI;+ hatchPolyPts.push([Math.cos(a) * 200, Math.sin(a) * 200]);+}+const hatchPolygon = new Polygon(hatchPolyPts);+hatch(8, 45);++function benchHatch() {+ return getHatchLines([hatchPolygon]);+}+const hatchMs = medianOf(Array.from({ length: RUNS }, () => bench(benchHatch, 200)));++// ============================================================+// 5. POLYGON: intersect (via cached intersection)+// ============================================================+const bigPolygon = (() => {+ const pts = [];+ for (let i = 0; i < 60; i++) {+ const a = (i / 60) * 2 * Math.PI;+ pts.push([Math.cos(a) * 150, Math.sin(a) * 150]);+ }+ return new Polygon(pts);+})();++function benchIntersect() {+ // Clear cache to force fresh computation+ bigPolygon._intersectionCache = {};+ let count = 0;+ for (let y = -120; y < 120; y += 10) {+ const line = { point1: { x: -200, y }, point2: { x: 200, y } };+ count += bigPolygon.intersect(line).length;+ }+ return count;+}+const intersectMs = medianOf(Array.from({ length: RUNS }, () => bench(benchIntersect, 500)));++// ============================================================+// 6. INTERSECT LINES: raw intersectLines() from utils.js+// ============================================================+function benchIntersectLines() {+ let count = 0;+ const p1 = { x: -200, y: 0 }, p2 = { x: 200, y: 0 };+ for (let i = 0; i < 1000; i++) {+ const a = { x: i * 0.5 - 100, y: -50 };+ const b = { x: i * 0.3 + 50, y: 50 };+ if (intersectLines(p1, p2, a, b)) count++;+ }+ return count;+}+const intersectLinesMs = medianOf(Array.from({ length: RUNS }, () => bench(benchIntersectLines, 500)));++// ============================================================+// TOTAL (primary metric)+// ============================================================+const total_ms = trigMs + gaussMs + plotMs + hatchMs + intersectMs + intersectLinesMs;++console.log(`METRIC total_ms=${total_ms.toFixed(3)}`);+console.log(`METRIC trig_ms=${trigMs.toFixed(3)}`);+console.log(`METRIC gauss_ms=${gaussMs.toFixed(3)}`);+console.log(`METRIC plot_ms=${plotMs.toFixed(3)}`);+console.log(`METRIC hatch_ms=${hatchMs.toFixed(3)}`);+console.log(`METRIC intersect_ms=${intersectMs.toFixed(3)}`);+console.log(`METRIC intersect_lines_ms=${intersectLinesMs.toFixed(3)}`);diff --git a/benchmark/loader.mjs b/benchmark/loader.mjsnew file mode 100644index 0000000..8965cb0--- /dev/null+++ b/benchmark/loader.mjs@@ -0,0 +1,10 @@+/**+ * Custom ESM loader that stubs .vert and .frag GLSL files so that+ * source modules can be imported in Node.js without a browser/WebGL context.+ */+export async function load(url, context, nextLoad) {+ if (url.endsWith('.vert') || url.endsWith('.frag')) {+ return { format: 'module', source: 'export default "";', shortCircuit: true };+ }+ return nextLoad(url, context);+}