Skip to content

Realistic watercolor drawings

TypeScript paintwatercolor

working

Maksim75ef0b321d63
diff --git a/README.md b/README.md
index 05b27c1..28546c6 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
# Watercolor
-A watercolour painting app in plain TypeScript and WebGL2, with no runtime dependencies.
+A watercolour painting app in plain TypeScript and WebGL2, with almost no runtime dependencies.
It combines ideas from two projects:
- **[inkwash](https://github.com/johnowhitaker/inkwash)**: the GPU fluid simulation (velocity /
@@ -15,10 +15,10 @@ npm run dev # http://localhost:5173
npm run build # static site in dist/
```
-No runtime dependencies. Vite and TypeScript are only used at build time; the UI is plain DOM,
+Two small runtime dependencies (vpype-js for SVG import, q-floodfill for the bucket fill). Vite and TypeScript are only used at build time; the UI is plain DOM,
and the simulation, colour science and rendering are TypeScript + GLSL.
-## Text
+## Text and shapes
The **Text** tool (T) writes a line of text with whatever brush and pigment are selected. The letters
come from single-stroke plotter fonts (Hershey, EMS, Cutlings, Relief, Shriinivas, Routed Gothic;
@@ -28,6 +28,24 @@ scripted samples, so the strokes get the same spacing, speed thinning, bleeding
and one word is one undo step. Options: font, size, speed, pressure, taper at stroke ends, letter spacing,
hand wobble, anchor (left / centre / right of the tap) and whether to draw with the brush, pen or water.
+The **Shape** tool (G) draws lines, arrows, rectangles, ellipses, triangles, regular polygons and stars
+the same way: drag a box on the paper (hold Shift, or turn on Lock, for squares, circles and 45° lines)
+and the outline is drawn stroke by stroke when you let go (`src/shapes/`). The eighth shape, **SVG**,
+traces a file of your own: pick it from the panel or drop an `.svg` anywhere on the page, then drag a
+box to size it (Lock keeps the file's proportions; Rotate turns it). Paths, rects, circles, ellipses,
+lines and polygons are read with [vpype-js](https://github.com/plottertools/vpype-js), merged and sorted
+to shorten pen hops (`src/shapes/svgImport.ts`); text and images in the file are ignored. Undo removes
+a whole word or shape; Redo (⇧⌘Z) brings it back. Undo and redo are symmetric tile swaps in `src/engine/history.ts`.
+
+The **Fill** tool (K) is a paint bucket that behaves like a wash. Tap the paper and the area of similar
+colour around the tap (found with [q-floodfill](https://github.com/pavelkukov/q-floodfill) on a flat
+render of the sheet, without paper grain or wet tint; `src/fill/region.ts`) is covered by pigment and water
+that spread out from the tap in real time rather than appearing at once. A distance field over the area
+(how far the wash has travelled from the tap, and how far it is from the edge) goes to the GPU, and each
+frame the engine lays down the next band of it into the live simulation (`fillStep` in `src/engine/Engine.ts`),
+so the wash blooms, pools and leaves tide lines like a hand-painted one. Options: tolerance, speed, water,
+amount, a soft edge, and whether to lay down paint or clear water. One fill is one undo step.
+
## Colour mixing
Pigment is stored as a **spectrum** rather than RGB, so mixes behave like paint:
@@ -112,6 +130,7 @@ Drop an image anywhere on the page to import it.
| **W** Water | clear water: wets paper, pushes paint around |
| **P** Pen | ink line, feathers into wet areas |
| **L** Lift | blot with a tissue: lifts wet (unfixed) paint |
+| **K** Fill | paint bucket: a wash spreads from the tap over the area of one colour |
| **D** Dry | flash-dry and fix paint into the paper, so you can glaze over it |
| **1–9, 0** | pigments; the last is white gouache |
| **[ ]** | size |
diff --git a/package-lock.json b/package-lock.json
index 6191938..9608dff 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -7,6 +7,10 @@
"": {
"name": "watercolor",
"version": "0.1.0",
+ "dependencies": {
+ "q-floodfill": "^1.3.1",
+ "vpype-js": "^0.1.0"
+ },
"devDependencies": {
"typescript": "^7.0.2",
"vite": "^8.3.2"
@@ -22,6 +26,15 @@
"url": "https://github.com/sponsors/oxc-project"
}
},
+ "node_modules/@rgrove/parse-xml": {
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/@rgrove/parse-xml/-/parse-xml-4.2.3.tgz",
+ "integrity": "sha512-Jhlb+0zYez1T1yXUQs3F1qAtFuJljBVNdy9TKmLDauAXkxsOXopKYOyQ5Wm6SvP3fycav0GviX4Y15WWhGetMw==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
"node_modules/@rolldown/binding-android-arm-eabi": {
"version": "1.2.12",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.12.tgz",
@@ -1026,6 +1039,12 @@
"node": "^10 || ^12 || >=14"
}
},
+ "node_modules/q-floodfill": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/q-floodfill/-/q-floodfill-1.3.1.tgz",
+ "integrity": "sha512-jYRhxQBHNsaj6d5nMQbHOeQ/8R0Wbw5QC2dKU2YDowsrAM4Bv28amoMLfqB6btV1eU3ngsWnRnLNc4a2QZIs2g==",
+ "license": "MIT"
+ },
"node_modules/rolldown": {
"version": "1.2.12",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.12.tgz",
@@ -1060,6 +1079,18 @@
"@rolldown/binding-win32-x64-msvc": "1.2.12"
}
},
+ "node_modules/smol-toml": {
+ "version": "1.9.0",
+ "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.9.0.tgz",
+ "integrity": "sha512-hpd+HLON7HdZXqYchMM/+LaTTbdK0AU3NngIJ4KVyWbY9bfQqdL9cD+4yf6dUoU2Ap4VsU0JkQi6FxAI1B2mXQ==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">= 18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/cyyynthia"
+ }
+ },
"node_modules/source-map-js": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
@@ -1070,6 +1101,15 @@
"node": ">=0.10.0"
}
},
+ "node_modules/svgpath": {
+ "version": "2.6.0",
+ "resolved": "https://registry.npmjs.org/svgpath/-/svgpath-2.6.0.tgz",
+ "integrity": "sha512-OIWR6bKzXvdXYyO4DK/UWa1VA1JeKq8E+0ug2DG98Y/vOmMpfZNj+TIG988HjfYSqtcy/hFOtZq/n/j5GSESNg==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/fontello/svg2ttf?sponsor=1"
+ }
+ },
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
@@ -1199,6 +1239,23 @@
"optional": true
}
}
+ },
+ "node_modules/vpype-js": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/vpype-js/-/vpype-js-0.1.0.tgz",
+ "integrity": "sha512-PrZLhtpli3DsA6gxB2oEjp/aA9i3uQkOMxX2ojuM6ZoVYzFjg5dpIX+szivaBPj53CZcwgrZJ4H4bGZ2VQn+IQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@rgrove/parse-xml": "^4.2.0",
+ "smol-toml": "^1.6.1",
+ "svgpath": "^2.6.0"
+ },
+ "bin": {
+ "vpype-js": "dist/cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ }
}
}
}
diff --git a/package.json b/package.json
index 094ac2f..2433b37 100644
--- a/package.json
+++ b/package.json
@@ -12,5 +12,9 @@
"devDependencies": {
"typescript": "^7.0.2",
"vite": "^8.3.2"
+ },
+ "dependencies": {
+ "q-floodfill": "^1.3.1",
+ "vpype-js": "^0.1.0"
}
}
diff --git a/src/text/TextWriter.ts b/src/draw/StrokeWriter.ts
similarity index 82%
rename from src/text/TextWriter.ts
rename to src/draw/StrokeWriter.ts
index 73047e4..2a426ec 100644
--- a/src/text/TextWriter.ts
+++ b/src/draw/StrokeWriter.ts
@@ -1,14 +1,19 @@
import type { Tool, WatercolorEngine } from '../engine/Engine';
-import type { TextLayout } from './layout';
-// Writes laid-out text onto the paper stroke by stroke, in real time, by feeding
-// the engine scripted samples: the brush actually travels the pen paths, so the
+// Draws pen paths (text, shapes) onto the paper stroke by stroke, in real time, by
+// feeding the engine scripted samples: the brush actually travels the paths, so the
// marks get the same spacing, speed thinning, bleeding and drying as hand strokes.
+/** A pen-down ... pen-up run of points. */
+export type Polyline = [number, number][];
+
+/** Pen speed in document heights per second from a 0..1 slider. */
+export const penSpeed = (v: number) => 0.05 * Math.pow(40, v);
+
export interface WriteOptions {
tool: Tool;
- /** Em height, in document heights. */
- size: number;
+ /** Reference length (em height, shape size) that wobble and jitter scale with, in document heights. */
+ ref: number;
/** Pen speed along the path, in document heights per second. */
speed: number;
/** Base pen pressure 0..1. */
@@ -31,7 +36,7 @@ const STEP = 0.0015; // sample spacing along the path (doc heights)
const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
const smooth = (a: number, b: number, x: number) => { const t = clamp((x - a) / (b - a), 0, 1); return t * t * (3 - 2 * t); };
-export class TextWriter {
+export class StrokeWriter {
private raf = 0;
private runs: Run[] = [];
private index = 0;
@@ -48,17 +53,20 @@ export class TextWriter {
get busy() { return this.raf !== 0; }
- /** Start writing `layout` with its anchor at document uv (x, y). Cancels any writing in progress. */
- write(layout: TextLayout, anchor: [number, number], opts: WriteOptions, cb: WriteCallbacks = {}) {
+ /**
+ * Start drawing `strokes`, given in document heights relative to `anchor` (document uv,
+ * y up), in order. Cancels any drawing in progress.
+ */
+ write(strokes: Polyline[], anchor: [number, number], opts: WriteOptions, cb: WriteCallbacks = {}) {
this.cancel();
- const { size, wobble } = opts;
+ const { ref, wobble } = opts;
this.runs = [];
- for (const pl of layout.strokes) {
- const pts = pl.map(([x, y]) => [x * size, -y * size] as [number, number]);
+ for (const pl of strokes) {
+ const pts = pl.map(([x, y]) => [x, y] as [number, number]);
const cum = [0];
for (let i = 1; i < pts.length; i++) cum.push(cum[i - 1] + Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]));
const len = cum[cum.length - 1];
- const j = wobble * size * 0.015;
+ const j = wobble * ref * 0.015;
this.runs.push({ pts, cum, len, ph: [Math.random() * 7, Math.random() * 7], jx: (Math.random() - 0.5) * j, jy: (Math.random() - 0.5) * j });
}
if (!this.runs.length) { cb.onDone?.(false); return; }
@@ -97,11 +105,11 @@ export class TextWriter {
const t = clamp((d - cum[i - 1]) / seg, 0, 1);
let x = pts[i - 1][0] + (pts[i][0] - pts[i - 1][0]) * t;
let y = pts[i - 1][1] + (pts[i][1] - pts[i - 1][1]) * t;
- const { wobble, size } = this.opts;
+ const { wobble, ref } = this.opts;
if (wobble > 0) {
- // perpendicular tremor: a slow sway plus a faster shiver, in proportion to the letter size
+ // perpendicular tremor: a slow sway plus a faster shiver, in proportion to the reference size
const tx = (pts[i][0] - pts[i - 1][0]) / seg, ty = (pts[i][1] - pts[i - 1][1]) / seg;
- const w = wobble * size * 0.035 * (0.6 * Math.sin((d / (size * 0.3)) * Math.PI * 2 + r.ph[0]) + 0.4 * Math.sin((d / (size * 0.08)) * Math.PI * 2 + r.ph[1]));
+ const w = wobble * ref * 0.035 * (0.6 * Math.sin((d / (ref * 0.3)) * Math.PI * 2 + r.ph[0]) + 0.4 * Math.sin((d / (ref * 0.08)) * Math.PI * 2 + r.ph[1]));
x += -ty * w; y += tx * w;
}
const a = this.engine.aspect;
diff --git a/src/draw/ghost.ts b/src/draw/ghost.ts
new file mode 100644
index 0000000..6e7bc5a
--- /dev/null
+++ b/src/draw/ghost.ts
@@ -0,0 +1,20 @@
+// A dashed outline over the paper showing where a scripted drawing will land.
+
+export interface Ghost {
+ /** Show the given SVG path (client-space coordinates). */
+ set(d: string): void;
+ hide(): void;
+}
+
+export function createGhost(root: HTMLElement): Ghost {
+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ svg.setAttribute('class', 'ghost');
+ svg.innerHTML = '<path/>';
+ svg.style.display = 'none';
+ root.appendChild(svg);
+ const path = svg.querySelector('path')!;
+ return {
+ set(d) { path.setAttribute('d', d); svg.style.display = ''; },
+ hide() { svg.style.display = 'none'; },
+ };
+}
diff --git a/src/engine/Engine.ts b/src/engine/Engine.ts
index 9788bc3..2012cd4 100644
--- a/src/engine/Engine.ts
+++ b/src/engine/Engine.ts
@@ -23,7 +23,7 @@ export const DEFAULT_PARAMS: Params = {
};
export interface EngineCallbacks {
- onHistoryChange?(canUndo: boolean): void;
+ onHistoryChange?(canUndo: boolean, canRedo: boolean): void;
/** The active tool changed for the current stroke (pencil barrel / finger-as-water). */
onStrokeTool?(tool: Tool | null): void;
}
@@ -57,6 +57,10 @@ const HALF_FLOAT_RG: Format = { internal: WebGL2RenderingContext.RG16F, format:
const HALF_FLOAT_R: Format = { internal: WebGL2RenderingContext.R16F, format: WebGL2RenderingContext.RED, type: WebGL2RenderingContext.HALF_FLOAT };
const HALF_FLOAT_RGBA: Format = { internal: WebGL2RenderingContext.RGBA16F, format: WebGL2RenderingContext.RGBA, type: WebGL2RenderingContext.HALF_FLOAT };
const RGBA8: Format = { internal: WebGL2RenderingContext.RGBA8, format: WebGL2RenderingContext.RGBA, type: WebGL2RenderingContext.UNSIGNED_BYTE };
+const FLOAT_RG: Format = { internal: WebGL2RenderingContext.RG32F, format: WebGL2RenderingContext.RG, type: WebGL2RenderingContext.FLOAT };
+const FILL_WATER_LEAD = 10; // px the water runs ahead of the pigment in a bucket fill
+const FILL_WIDTH = 24; // px over which a bucket fill's front ramps up
+const FILL_JITTER = 3; // px the paper grain roughens a bucket fill's front
const SIM_BASE = 256; // short side of the velocity / pressure grid
const PRESSURE_ITERATIONS = 20;
@@ -120,6 +124,7 @@ export class WatercolorEngine {
// input
private stroke: Stroke | null = null;
+ private fill: { tex: WebGLTexture; bbox: Rect } | null = null; // a paint-bucket wash in progress
private queue: Sample[] = [];
private pencilSeen = false;
private hover = { x: 0, y: 0, inside: false, type: 'mouse' };
@@ -140,6 +145,7 @@ export class WatercolorEngine {
this.programs = {
splat: this.g.program(S.splatFS),
stamp: this.g.program(S.stampFS),
+ fill: this.g.program(S.fillFS),
advectVelocity: this.g.program(S.advectVelocityFS),
divergence: this.g.program(S.divergenceFS),
pressure: this.g.program(S.pressureFS),
@@ -214,7 +220,7 @@ export class WatercolorEngine {
this.wetPeak = 0;
this.fixTimer = 0;
this.fitView();
- this.callbacks.onHistoryChange?.(false);
+ this.callbacks.onHistoryChange?.(false, false);
}
/* ------------------------------------------------------------- public API */
@@ -233,6 +239,100 @@ export class WatercolorEngine {
return [r.left + (this.view.x + x * this.view.w) / this.dpr, r.top + (this.canvasSize[1] - this.view.y - y * this.view.h) / this.dpr];
}
+ /** Document size in texels. */
+ get docSize(): [number, number] { return [this.dw, this.dh]; }
+
+ /* ------------------------------------------------- paint-bucket fills (fill) */
+
+ /** Is a bucket fill in progress? */
+ get filling() { return this.fill !== null; }
+
+ /** How far (px) past the farthest field distance a fill must run so its roughened front covers everything. */
+ get fillMargin() { return FILL_WIDTH + FILL_JITTER + 1; }
+
+ /**
+ * The document as a flat image: pigment on plain paper with no relief, grain, edge
+ * darkening or wet tint, so areas of one colour read as one colour. RGBA8, row 0 is
+ * document y = 0 (uv is y-up, so no flip is needed to index it by texel).
+ */
+ readFlat(): Uint8Array { return this.readback(true); }
+
+ /**
+ * Start a bucket fill: `field` is RG per document texel (distance from the tap in
+ * px, -1 outside the area; distance to the area's edge), `bbox` the half-open texel
+ * rect around it. Opens one undo step for the whole wash. False while a stroke is
+ * still on the paper.
+ */
+ fillBegin(field: Float32Array, bbox: Rect): boolean {
+ if (this.stroke) return false;
+ if (field.length !== this.dw * this.dh * 2) throw new Error('fill field does not match the document');
+ this.beginStep(); // also drops any previous fill
+ const tex = this.g.texture(this.dw, this.dh, FLOAT_RG, field, this.gl.NEAREST);
+ this.fill = { tex, bbox: { ...bbox } };
+ return true;
+ }
+
+ /**
+ * Deposit the band `from < distance <= to` of the current fill: pigment (if `paint`)
+ * and water, feathered over `soft` px at the area's edge. False once the fill is
+ * gone (undo, clear, another action), in which case the caller should stop.
+ */
+ fillStep(from: number, to: number, o: { strength: number; water: number; soft: number; paint: boolean }): boolean {
+ const f = this.fill;
+ if (!f) return false;
+ const { gl, g } = this;
+ const P = this.params;
+ this.touch(f.bbox);
+ const p = this.programs.fill;
+ p.bind();
+ gl.uniform1i(p.u.uField, g.bindTex(0, f.tex));
+ gl.uniform1i(p.u.uPaper, g.bindTex(1, this.paper.tex[0]));
+ gl.uniform1f(p.u.uSoft, Math.max(0, o.soft));
+ gl.uniform1f(p.u.uGrainThr, 0.5);
+ gl.uniform1f(p.u.uJitter, FILL_JITTER);
+ gl.uniform1f(p.u.uWidth, FILL_WIDTH);
+ gl.enable(gl.BLEND);
+ if (o.paint) {
+ // a steady stroke's density (brush case of stamp(), full reservoir, medium pressure)
+ const conc = 0.15 * Math.exp(P.load * 2.8) * 0.84;
+ const amount = conc * o.strength;
+ const c = this.pigment.coeffs;
+ gl.uniform1i(p.u.uCumulative, 0);
+ gl.uniform1f(p.u.uFrom, from);
+ gl.uniform1f(p.u.uTo, to);
+ gl.uniform1f(p.u.uGrain, 0.12);
+ gl.uniform4f(p.u.uColor0, c[0] * amount, c[1] * amount, c[2] * amount, c[3] * amount);
+ gl.uniform4f(p.u.uColor1, c[4] * amount, c[5] * amount, c[6] * amount, this.pigment.white * amount * 1.6);
+ gl.blendEquation(gl.FUNC_ADD);
+ gl.blendFunc(gl.ONE, gl.ONE);
+ g.draw(this.ink.read, f.bbox);
+ }
+ // the water runs a little ahead of the pigment, as a real wash does
+ const wetAmt = (0.25 + 0.75 * o.water) * 0.9;
+ gl.uniform1i(p.u.uCumulative, 1);
+ gl.uniform1f(p.u.uTo, to + FILL_WATER_LEAD);
+ gl.uniform1f(p.u.uGrain, 0);
+ gl.uniform4f(p.u.uColor0, wetAmt, 0, 0, 0);
+ gl.uniform4f(p.u.uColor1, 0, 0, 0, 0);
+ gl.blendEquation(gl.MAX);
+ g.draw(this.wet.read, f.bbox);
+ gl.blendEquation(gl.FUNC_ADD);
+ gl.disable(gl.BLEND);
+ this.wetPeak = Math.max(this.wetPeak * this.wetDecay(), wetAmt);
+ this.lastWet = performance.now();
+ this.schedule();
+ return true;
+ }
+
+ /** Finish (or stop) the current fill; what has been laid down stays. */
+ fillEnd() { this.dropFill(); }
+
+ private dropFill() {
+ if (!this.fill) return;
+ this.gl.deleteTexture(this.fill.tex);
+ this.fill = null;
+ }
+
/* -------------------------------------------------- scripted strokes (text) */
/** Is a code-driven stroke in progress? */
@@ -318,22 +418,33 @@ export class WatercolorEngine {
clear() {
this.stroke = null;
+ this.dropFill();
this.queue = [];
this.createDocument();
this.schedule();
}
- undo() {
- if (!this.history.canUndo) return;
+ undo() { if (this.history.canUndo) this.travel('undo'); }
+
+ redo() { if (this.history.canRedo) this.travel('redo'); }
+
+ get canUndo() { return this.history.canUndo; }
+ get canRedo() { return this.history.canRedo; }
+
+ /** Step through history in either direction. */
+ private travel(dir: 'undo' | 'redo') {
this.stroke = null;
+ this.dropFill();
this.queue = [];
this.fixTimer = 0;
+ const metaNow = this.currentMeta();
this.sleep();
const ink = this.ink, wet = this.wet;
- const res = this.history.undo([
+ const layers = [
[[ink.read.views[0], ink.write.views[0]], [ink.read.views[1], ink.write.views[1]], [wet.read.views[0], wet.write.views[0]]],
[[this.fixed.views[0]], [this.fixed.views[1]]],
- ]);
+ ];
+ const res = dir === 'undo' ? this.history.undo(layers, metaNow) : this.history.redo(layers, metaNow);
if (!res) return;
const meta = res.meta as HistoryMeta;
const now = performance.now();
@@ -345,23 +456,20 @@ export class WatercolorEngine {
this.dirty = union(this.dirty, res.rect);
this.painted = union(this.painted, res.rect);
}
- this.callbacks.onHistoryChange?.(this.history.canUndo);
+ this.notifyHistory();
this.schedule();
}
- get canUndo() { return this.history.canUndo; }
+ private notifyHistory() { this.callbacks.onHistoryChange?.(this.history.canUndo, this.history.canRedo); }
+
+ private currentMeta(): HistoryMeta {
+ return { wetAgo: performance.now() - this.lastWet, wetPeak: this.wetPeak, active: this.active ? { ...this.active } : null };
+ }
/** Render the document at full resolution and return it as a PNG. */
async exportPNG(): Promise<Blob> {
- const { gl, g, dw, dh } = this;
- const out = g.target(dw, dh, [RGBA8], gl.NEAREST);
- this.drawDisplay(out, { x: 0, y: 0, w: dw, h: dh }, null);
- const px = new Uint8Array(dw * dh * 4);
- gl.bindFramebuffer(gl.FRAMEBUFFER, out.fbo);
- gl.readPixels(0, 0, dw, dh, gl.RGBA, gl.UNSIGNED_BYTE, px);
- gl.deleteFramebuffer(out.fbo);
- out.views.forEach(v => gl.deleteFramebuffer(v));
- gl.deleteTexture(out.tex[0]);
+ const { dw, dh } = this;
+ const px = this.readback(false);
const c = document.createElement('canvas');
c.width = dw; c.height = dh;
const ctx = c.getContext('2d')!;
@@ -372,6 +480,20 @@ export class WatercolorEngine {
return new Promise((resolve, reject) => c.toBlob(b => (b ? resolve(b) : reject(new Error('export failed'))), 'image/png'));
}
+ /** The composited document at full resolution as RGBA8 bytes, bottom row first. */
+ private readback(flat: boolean): Uint8Array {
+ const { gl, g, dw, dh } = this;
+ const out = g.target(dw, dh, [RGBA8], gl.NEAREST);
+ this.drawDisplay(out, { x: 0, y: 0, w: dw, h: dh }, null, flat);
+ const px = new Uint8Array(dw * dh * 4);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, out.fbo);
+ gl.readPixels(0, 0, dw, dh, gl.RGBA, gl.UNSIGNED_BYTE, px);
+ gl.deleteFramebuffer(out.fbo);
+ out.views.forEach(v => gl.deleteFramebuffer(v));
+ gl.deleteTexture(out.tex[0]);
+ return px;
+ }
+
resize() {
this.fitCanvas();
this.schedule();
@@ -379,6 +501,7 @@ export class WatercolorEngine {
destroy() {
cancelAnimationFrame(this.raf);
+ this.dropFill();
this.disposers.forEach(d => d());
this.tipTextures.forEach(t => this.gl.deleteTexture(t));
this.tipTextures.clear();
@@ -815,11 +938,10 @@ export class WatercolorEngine {
}
private beginStep() {
- const now = performance.now();
- const meta: HistoryMeta = { wetAgo: now - this.lastWet, wetPeak: this.wetPeak, active: this.active ? { ...this.active } : null };
- this.history.begin(meta);
+ this.dropFill(); // a new action ends a running fill; its remaining bands never land in this step
+ this.history.begin(this.currentMeta());
if (this.active) this.history.protect(0, this.active, this.snapshotLayers());
- this.callbacks.onHistoryChange?.(true);
+ this.notifyHistory();
}
private step(dt: number) {
@@ -953,7 +1075,7 @@ export class WatercolorEngine {
/* -------------------------------------------------------------- display */
- private drawDisplay(target: Target | null, view: { x: number; y: number; w: number; h: number }, scissor: Rect | null) {
+ private drawDisplay(target: Target | null, view: { x: number; y: number; w: number; h: number }, scissor: Rect | null, flat = false) {
const { gl, g } = this;
const p = this.programs.display;
p.bind();
@@ -967,6 +1089,7 @@ export class WatercolorEngine {
gl.uniform2f(p.u.uTexel, 1 / this.dw, 1 / this.dh);
gl.uniform1f(p.u.uGranulation, this.params.granulation * 0.55);
gl.uniform1f(p.u.uEdgeDarken, 0.8);
+ gl.uniform1f(p.u.uFlat, flat ? 1 : 0);
gl.uniform3fv(p.u.uDesk, DESK);
g.draw(target, scissor, this.canvasSize);
}
diff --git a/src/engine/gl.ts b/src/engine/gl.ts
index ef37905..5610d3c 100644
--- a/src/engine/gl.ts
+++ b/src/engine/gl.ts
@@ -156,6 +156,21 @@ export class GL {
if (rect) gl.disable(gl.SCISSOR_TEST);
}
+ /** Upload a CPU image as a texture. The caller owns it (it is not freed by disposeTargets). */
+ texture(w: number, h: number, f: Format, data: ArrayBufferView | null, filter: number): WebGLTexture {
+ const { gl } = this;
+ const t = gl.createTexture()!;
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, t);
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
+ gl.texImage2D(gl.TEXTURE_2D, 0, f.internal, w, h, 0, f.format, f.type, data);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ return t;
+ }
+
bindTex(unit: number, tex: WebGLTexture): number {
const { gl } = this;
gl.activeTexture(gl.TEXTURE0 + unit);
diff --git a/src/engine/history.ts b/src/engine/history.ts
index dea8900..4234915 100644
--- a/src/engine/history.ts
+++ b/src/engine/history.ts
@@ -38,6 +38,7 @@ export class History {
private tilesX: number;
private tilesY: number;
private steps: Step[] = [];
+ private redoSteps: Step[] = [];
private maxSteps = 50;
/** `groups[i]` lists a pool's layer formats and its capacity in documents' worth of tiles. */
@@ -49,8 +50,10 @@ export class History {
}
get canUndo() { return this.steps.length > 0; }
+ get canRedo() { return this.redoSteps.length > 0; }
begin(meta: unknown) {
+ this.clearRedo(); // a new action forks history
this.steps.push({ tiles: this.pools.map(() => new Map()), meta });
while (this.steps.length > this.maxSteps) this.dropOldest();
}
@@ -66,8 +69,7 @@ export class History {
for (let tx = tx0; tx <= tx1; tx++) {
const id = ty * this.tilesX + tx;
if (saved.has(id)) continue;
- while (!pool.free.length && this.steps.length > 1) this.dropOldest();
- const slot = pool.free.pop();
+ const slot = this.allocSlot(pool, 'protect');
if (slot === undefined) return; // a pool holds at least one whole document
saved.set(id, slot);
this.copyTile(pool, id, slot, layers, true);
@@ -77,15 +79,38 @@ export class History {
/**
* Restore the last step. `layers[p][i]` lists every framebuffer that should receive
- * layer i of pool p (both halves of a ping-pong pair). Returns the step's meta.
+ * layer i of pool p (both halves of a ping-pong pair; the first is read from when the
+ * current content is saved for redo). `metaNow` is the engine state to come back to
+ * on redo. Returns the step's meta and the document rect that changed.
*/
- undo(layers: WebGLFramebuffer[][][]): { meta: unknown; rect: Rect | null } | null {
- const step = this.steps.pop();
+ undo(layers: WebGLFramebuffer[][][], metaNow: unknown) {
+ return this.swap(this.steps, this.redoSteps, layers, metaNow, 0);
+ }
+
+ /** Re-apply the last undone step. */
+ redo(layers: WebGLFramebuffer[][][], metaNow: unknown) {
+ return this.swap(this.redoSteps, this.steps, layers, metaNow, 1);
+ }
+
+ /**
+ * Undo and redo are the same move in opposite directions: pop a step from `from`,
+ * save the tiles it covers as they are now, restore its tiles, and push the saved
+ * ones onto `to`. `keep` says which stack is protected when slots run short.
+ */
+ private swap(from: Step[], to: Step[], layers: WebGLFramebuffer[][][], metaNow: unknown, keep: 0 | 1): { meta: unknown; rect: Rect | null } | null {
+ const step = from.pop();
if (!step) return null;
+ const back: Step = { tiles: this.pools.map(() => new Map()), meta: metaNow };
+ let complete = true;
let rect: Rect | null = null;
step.tiles.forEach((saved, p) => {
const pool = this.pools[p];
for (const [id, slot] of saved) {
+ if (complete) {
+ const now = this.allocSlot(pool, keep === 0 ? 'undo' : 'redo');
+ if (now === undefined) complete = false;
+ else { this.copyTile(pool, id, now, layers[p].map(l => l[0]), true); back.tiles[p].set(id, now); }
+ }
const copies = Math.max(...layers[p].map(l => l.length));
for (let c = 0; c < copies; c++)
this.copyTile(pool, id, slot, layers[p].map(l => l[Math.min(c, l.length - 1)]), false);
@@ -95,12 +120,39 @@ export class History {
pool.free.push(slot);
}
});
+ // without room for every tile the way back is lost: drop it rather than restore half a step later
+ if (complete) to.push(back); else this.release(back);
return { meta: step.meta, rect };
}
+ /**
+ * A free slot of `pool`, making room if needed. While recording or undoing, redo
+ * steps go first (newest first: they are the cheapest to lose), then the oldest
+ * undo steps; the step being recorded is never dropped. While redoing, old undo
+ * steps go before the remaining redo steps.
+ */
+ private allocSlot(pool: Pool, mode: 'protect' | 'undo' | 'redo'): number | undefined {
+ while (!pool.free.length) {
+ if (mode !== 'redo' && this.redoSteps.length) this.release(this.redoSteps.pop()!);
+ else if (this.steps.length > (mode === 'protect' ? 1 : 0)) this.release(this.steps.shift()!);
+ else if (mode === 'redo' && this.redoSteps.length) this.release(this.redoSteps.pop()!);
+ else break;
+ }
+ return pool.free.pop();
+ }
+
private dropOldest() {
const s = this.steps.shift();
- if (s) s.tiles.forEach((saved, p) => { for (const slot of saved.values()) this.pools[p].free.push(slot); });
+ if (s) this.release(s);
+ }
+
+ private clearRedo() {
+ for (const s of this.redoSteps) this.release(s);
+ this.redoSteps = [];
+ }
+
+ private release(s: Step) {
+ s.tiles.forEach((saved, p) => { for (const slot of saved.values()) this.pools[p].free.push(slot); });
}
private copyTile(pool: Pool, id: number, slot: number, layers: WebGLFramebuffer[], save: boolean) {
diff --git a/src/engine/shaders.ts b/src/engine/shaders.ts
index 3da9a94..1875c36 100644
--- a/src/engine/shaders.ts
+++ b/src/engine/shaders.ts
@@ -273,6 +273,35 @@ void main(){
o = vec4(lit, h, fibre, 1.0);
}`;
+// Paint-bucket wash. uField holds, per document texel, the distance travelled from the
+// tap through the chosen area (r, px; -1 outside it) and the distance to the area's edge
+// (g, px). The front is a ramp uWidth px wide: a texel at distance r has received the
+// fraction ramp(t - r) of its deposit once the front has reached t, so the frame that
+// moves the front from uFrom to uTo lays down the difference. Summed over all frames
+// that is exactly one deposit per texel, with no frame boundary to leave a tide line.
+// Water is drawn with MAX blending, so it gets the cumulative ramp instead. MRT like splatFS.
+export const fillFS = `${HEADER}
+layout(location=0) out vec4 o0;
+layout(location=1) out vec4 o1;
+uniform highp sampler2D uField;
+uniform sampler2D uPaper;
+uniform float uFrom, uTo, uWidth, uSoft, uGrain, uGrainThr, uJitter;
+uniform int uCumulative;
+uniform vec4 uColor0, uColor1;
+float ramp(float x){ return smoothstep(0.0, 1.0, clamp(x / uWidth, 0.0, 1.0)); }
+void main(){
+ vec2 f = texture(uField, vUv).rg;
+ if (f.r < 0.0) discard;
+ float h = texture(uPaper, vUv).g;
+ float r = max(0.0, f.r + (h - 0.5) * uJitter);
+ float w = ramp(uTo - r) - (uCumulative == 1 ? 0.0 : ramp(uFrom - r));
+ if (w <= 0.0) discard;
+ float edge = uSoft > 0.0 ? smoothstep(0.0, uSoft, f.g + 0.5) : 1.0;
+ w *= edge * mix(1.0, smoothstep(uGrainThr - 0.08, uGrainThr + 0.08, h), uGrain);
+ o0 = uColor0 * w;
+ o1 = uColor1 * w;
+}`;
+
/** Final composite: spectral reconstruction of pigment on paper. */
export const displayFS = `${HEADER}
out vec4 o;
@@ -280,6 +309,7 @@ uniform sampler2D uInkA, uInkB, uFixedA, uFixedB, uWet, uPaper;
uniform vec4 uView; // canvas px -> document uv: uv = (fragCoord - xy) / zw
uniform vec2 uTexel; // document texel size
uniform float uGranulation, uEdgeDarken;
+uniform float uFlat; // 1: ignore the paper's relief, grain and wetness (for region picking)
uniform vec3 uDesk;
vec3 toSRGB(vec3 c){
@@ -292,7 +322,7 @@ void main(){
vec2 uv = (gl_FragCoord.xy - uView.xy) / uView.zw;
if (uv.x < 0.0 || uv.y < 0.0 || uv.x > 1.0 || uv.y > 1.0){ o = vec4(uDesk, 1.0); return; }
- vec4 paper = texture(uPaper, uv);
+ vec4 paper = mix(texture(uPaper, uv), vec4(0.5), uFlat);
vec4 iB = texture(uInkB, uv);
vec4 a = texture(uInkA, uv) + texture(uFixedA, uv);
vec3 b = iB.rgb + texture(uFixedB, uv).rgb;
@@ -304,7 +334,7 @@ void main(){
float l = density(uv - vec2(uTexel.x, 0.0)), r = density(uv + vec2(uTexel.x, 0.0));
float bt = density(uv - vec2(0.0, uTexel.y)), t = density(uv + vec2(0.0, uTexel.y));
float edge = min(length(vec2(r - l, t - bt)) / (d0 + 1.0), 1.0);
- float k = gran * (1.0 + uEdgeDarken * edge);
+ float k = mix(gran * (1.0 + uEdgeDarken * edge), 1.0, uFlat);
a *= k; b *= k;
vec3 rgb = vec3(0.0);
@@ -321,7 +351,7 @@ ${displayBasisGLSL()}
col = mix(col, vec3(0.96, 0.955, 0.94) * (0.96 + 0.05 * paper.r), cov);
// Wet paper reads darker and slightly cool.
- float ws = smoothstep(0.02, 0.7, texture(uWet, uv).x);
+ float ws = smoothstep(0.02, 0.7, texture(uWet, uv).x) * (1.0 - uFlat);
col *= vec3(1.0) - ws * vec3(0.12, 0.11, 0.08);
o = vec4(toSRGB(col), 1.0);
diff --git a/src/fill/fillTool.ts b/src/fill/fillTool.ts
new file mode 100644
index 0000000..fdf2b49
--- /dev/null
+++ b/src/fill/fillTool.ts
@@ -0,0 +1,233 @@
+import type { WatercolorEngine } from '../engine/Engine';
+import { icon } from '../ui/icons';
+import { distanceField, pickRegion } from './region';
+
+// The Fill tool (paint bucket): tap an area of the paper and a wash of the current
+// pigment spreads out from the tap across every connected pixel of similar colour.
+// q-floodfill picks the region on a flat readback of the paper; the engine then
+// deposits pigment and water band by band along a distance field, so the fill is
+// animated and the live wet simulation bleeds it like any other wash.
+
+export interface FillSettings {
+ mode: 'paint' | 'water';
+ tolerance: number; // 0..1 -> colour difference
+ water: number; // 0..1 wetness of the wash
+ strength: number; // 0..1.5 pigment amount
+ speed: number; // 0..1 -> px / s
+ soft: number; // 0..1 -> feathered edge width
+}
+
+const KEY = 'watercolor.fill';
+const DEFAULTS: FillSettings = { mode: 'paint', tolerance: 0.25, water: 0.6, strength: 1, speed: 0.5, soft: 0.3 };
+
+const SLIDERS: { key: keyof FillSettings; label: string; min: number; max: number; step: number; hint: string }[] = [
+ { key: 'tolerance', label: 'Tolerance', min: 0, max: 1, step: 0.01, hint: 'How different a colour may be and still count as the same area' },
+ { key: 'speed', label: 'Speed', min: 0, max: 1, step: 0.01, hint: 'How fast the wash spreads' },
+ { key: 'water', label: 'Water', min: 0, max: 1, step: 0.01, hint: 'How wet the wash is' },
+ { key: 'strength', label: 'Amount', min: 0, max: 1.5, step: 0.01, hint: 'Pigment laid down (on top of the Pigment setting)' },
+ { key: 'soft', label: 'Soft edge', min: 0, max: 1, step: 0.01, hint: 'Feather the wash at the edge of the area' },
+];
+
+const MODES: { id: FillSettings['mode']; label: string }[] = [{ id: 'paint', label: 'Paint' }, { id: 'water', label: 'Water' }];
+
+/** Slider 0..1 -> px/s of front travel (about 120 .. 3000). */
+const fillSpeed = (v: number) => 120 * Math.pow(25, v);
+const EDGE_CAP = 48;
+
+export interface FillToolHandle {
+ panel: HTMLElement;
+ activate(): void;
+ deactivate(): void;
+ /** Stop a running fill (the paint laid so far stays). Returns whether anything was stopped. */
+ stop(): boolean;
+ readonly active: boolean;
+ readonly busy: boolean;
+}
+
+export function createFillTool(engine: WatercolorEngine, root: HTMLElement, canvas: HTMLCanvasElement, toast: (s: string) => void): FillToolHandle {
+ let settings: FillSettings = { ...DEFAULTS, ...load() };
+ if (!MODES.some(m => m.id === settings.mode)) settings.mode = DEFAULTS.mode;
+ let active = false;
+ let press: { id: number; x: number; y: number } | null = null;
+ let run: { raf: number; from: number; maxDist: number; last: number } | null = null;
+ let picking = false;
+
+ /* ---------------------------------------------------------------- markup */
+
+ const panel = document.createElement('div');
+ panel.className = 'panel text fill';
+ panel.hidden = true;
+ panel.setAttribute('role', 'dialog');
+ panel.setAttribute('aria-label', 'Fill');
+ panel.innerHTML = `
+ <div class="library-head">
+ <span>Fill</span>
+ <span class="sub">Tap an area of the paper; a wash of the current pigment spreads out from the tap until it meets a different colour.</span>
+ <button class="icon" data-action="fill-close" title="Close">${icon('close', 16)}</button>
+ </div>
+ <div class="text-body">
+ <div class="text-rows">
+ <label class="slider"><span>Fill with</span><div class="seg" data-opt="mode" role="radiogroup">${MODES.map(m => `<button role="radio" data-value="${m.id}">${m.label}</button>`).join('')}</div></label>
+ ${SLIDERS.map(s => `<label class="slider" data-slider="${s.key}" title="${s.hint}"><span>${s.label}</span><input type="range" min="${s.min}" max="${s.max}" step="${s.step}" data-opt="${s.key}"></label>`).join('')}
+ </div>
+ <div class="text-foot">
+ <span class="status"></span>
+ <button class="stop" data-action="fill-stop" hidden>${icon('close', 14)}<span>Stop</span></button>
+ </div>
+ </div>`;
+ root.appendChild(panel);
+
+ const status = panel.querySelector<HTMLElement>('.status')!;
+ const stopBtn = panel.querySelector<HTMLButtonElement>('.stop')!;
+ const sliders = [...panel.querySelectorAll<HTMLInputElement>('input[type="range"][data-opt]')];
+
+ /* ------------------------------------------------------------- rendering */
+
+ function render() {
+ for (const s of sliders) s.value = String(settings[s.dataset.opt as keyof FillSettings]);
+ panel.querySelector<HTMLElement>('[data-slider="strength"]')!.hidden = settings.mode === 'water';
+ for (const b of panel.querySelectorAll<HTMLElement>('.seg button')) {
+ const on = b.dataset.value === settings.mode;
+ b.classList.toggle('on', on);
+ b.setAttribute('aria-checked', String(on));
+ }
+ renderStatus();
+ }
+
+ function renderStatus() {
+ stopBtn.hidden = !run;
+ if (run) status.textContent = `Filling… ${Math.round(Math.min(1, Math.max(0, run.from) / Math.max(run.maxDist, 1e-6)) * 100)}%`;
+ else if (picking) status.textContent = 'Finding the area…';
+ else if (!active) status.textContent = '';
+ else status.textContent = settings.mode === 'water' ? 'Tap an area to wet it' : 'Tap an area to fill it';
+ }
+
+ /* --------------------------------------------------------------- actions */
+
+ function save() {
+ try { localStorage.setItem(KEY, JSON.stringify(settings)); } catch { /* storage blocked */ }
+ }
+
+ function set(p: Partial<FillSettings>) {
+ settings = { ...settings, ...p };
+ save();
+ render();
+ }
+
+ const busy = () => !!run || picking;
+
+ function fillAt(clientX: number, clientY: number) {
+ const [u, v] = engine.clientToDoc(clientX, clientY);
+ if (u < 0 || v < 0 || u > 1 || v > 1) return;
+ const [dw, dh] = engine.docSize;
+ const px = Math.min(dw - 1, Math.floor(u * dw)), py = Math.min(dh - 1, Math.floor(v * dh));
+ picking = true;
+ renderStatus();
+ // let the status paint before the synchronous region search
+ requestAnimationFrame(() => {
+ picking = false;
+ if (!active) { renderStatus(); return; }
+ const flat = engine.readFlat();
+ const tol = Math.round(settings.tolerance * settings.tolerance * 255); // 0.25 -> 16 of 255 per channel
+ const mask = pickRegion({ width: dw, height: dh, data: new Uint8ClampedArray(flat.buffer) }, px, py, tol);
+ if (!mask) { toast('Nothing to fill here'); renderStatus(); return; }
+ const region = distanceField(mask, dw, dh, px, py, EDGE_CAP);
+ if (region.count < 4) { toast('That area is too small to fill'); renderStatus(); return; }
+ if (!engine.fillBegin(region.field, region.bbox)) { toast('Wait for the stroke to finish'); renderStatus(); return; }
+ run = { raf: 0, from: -0.5, maxDist: region.maxDist + engine.fillMargin, last: performance.now() };
+ run.raf = requestAnimationFrame(frame);
+ renderStatus();
+ });
+ }
+
+ function frame(now: number) {
+ if (!run) return;
+ const dt = Math.min(0.1, Math.max(0, (now - run.last) / 1000));
+ run.last = now;
+ const to = Math.min(run.maxDist, run.from + fillSpeed(settings.speed) * dt);
+ const ok = engine.fillStep(run.from, to, {
+ strength: settings.strength, water: settings.water, soft: settings.soft * 40, paint: settings.mode === 'paint',
+ });
+ if (!ok) { finish(); return; } // undone, cleared or interrupted by another action
+ run.from = to;
+ if (to >= run.maxDist) { engine.fillEnd(); finish(); return; }
+ run.raf = requestAnimationFrame(frame);
+ renderStatus();
+ }
+
+ function finish() {
+ if (run) cancelAnimationFrame(run.raf);
+ run = null;
+ renderStatus();
+ }
+
+ function cancel(): boolean {
+ if (!run) return false;
+ engine.fillEnd();
+ finish();
+ return true;
+ }
+
+ /* ---------------------------------------------------------------- wiring */
+
+ panel.addEventListener('input', e => {
+ const s = e.target as HTMLInputElement;
+ if (s.type === 'range' && s.dataset.opt) set({ [s.dataset.opt]: Number(s.value) } as Partial<FillSettings>);
+ });
+
+ panel.addEventListener('click', e => {
+ const el = (e.target as Element).closest<HTMLElement>('.seg button, [data-action]');
+ if (!el) return;
+ if (el.dataset.value !== undefined) set({ mode: el.dataset.value as FillSettings['mode'] });
+ else if (el.dataset.action === 'fill-stop') cancel();
+ });
+
+ canvas.addEventListener('pointerdown', e => {
+ if (!active || press) return;
+ if (busy()) { toast('Still filling… press Stop or Esc'); return; }
+ try { canvas.setPointerCapture(e.pointerId); } catch { /* pointer already gone */ }
+ press = { id: e.pointerId, x: e.clientX, y: e.clientY };
+ });
+ const up = (e: PointerEvent) => {
+ if (!active || !press || e.pointerId !== press.id) return;
+ const p = press;
+ press = null;
+ try { canvas.releasePointerCapture(p.id); } catch { /* already released */ }
+ if (e.type === 'pointercancel') return;
+ if (Math.hypot(e.clientX - p.x, e.clientY - p.y) > 6) { toast('Tap, rather than drag, to fill an area'); return; }
+ fillAt(e.clientX, e.clientY);
+ };
+ canvas.addEventListener('pointerup', up);
+ canvas.addEventListener('pointercancel', up);
+
+ render();
+
+ return {
+ panel,
+ get active() { return active; },
+ get busy() { return busy(); },
+ activate() {
+ active = true;
+ panel.hidden = false;
+ canvas.classList.add('placing');
+ renderStatus();
+ },
+ deactivate() {
+ active = false;
+ press = null;
+ cancel();
+ panel.hidden = true;
+ canvas.classList.remove('placing');
+ },
+ stop: () => cancel(),
+ };
+}
+
+function load(): Partial<FillSettings> {
+ try {
+ const raw = localStorage.getItem(KEY);
+ return raw ? (JSON.parse(raw) as Partial<FillSettings>) : {};
+ } catch {
+ return {};
+ }
+}
diff --git a/src/fill/region.ts b/src/fill/region.ts
new file mode 100644
index 0000000..11e1f82
--- /dev/null
+++ b/src/fill/region.ts
@@ -0,0 +1,163 @@
+import FloodFill from 'q-floodfill';
+import type { Rect } from '../engine/gl';
+
+// Region picking for the Fill tool: q-floodfill finds the connected run of similar
+// colour around the tap, then two chamfer-distance passes turn that mask into the
+// field the engine animates: distance travelled from the tap (the spreading front)
+// and distance to the region's edge (for feathering).
+
+/** A flat RGBA8 image as q-floodfill expects it (row 0 = document y 0). */
+export interface FlatImage { width: number; height: number; data: Uint8ClampedArray }
+
+export interface FillRegion {
+ w: number;
+ h: number;
+ /** Half-open texel rect around the region. */
+ bbox: Rect;
+ /** Region pixels. */
+ count: number;
+ /** Farthest (wobbled) distance from the seed (px). */
+ maxDist: number;
+ /** RG per pixel: r = distance from the seed (px, -1 outside the region), g = distance to the edge (px). */
+ field: Float32Array;
+}
+
+/**
+ * The connected area of similar colour around (x, y). `tolerance` is a per-channel
+ * difference in 0..255. Mutates `img` (it is a throwaway readback). Null if empty.
+ */
+export function pickRegion(img: FlatImage, x: number, y: number, tolerance: number): Uint8Array | null {
+ const { width, height, data } = img;
+ if (x < 0 || y < 0 || x >= width || y >= height) return null;
+ // The flat render is opaque everywhere, so alpha 0 is a sentinel no real pixel matches
+ // (for any tolerance below 255); afterwards the region is simply "alpha == 0".
+ const ff = new FloodFill(img as unknown as ImageData);
+ ff.fill('rgba(0,0,0,0)', x, y, Math.min(254, Math.max(0, Math.round(tolerance))));
+ if (!ff.modifiedPixelsCount) return null;
+ const mask = new Uint8Array(width * height);
+ for (let i = 0, n = width * height; i < n; i++) mask[i] = data[i * 4 + 3] === 0 ? 1 : 0;
+ return mask;
+}
+
+const AX = 5, DI = 7, KN = 11; // chamfer weights (axial / diagonal / knight's move): near-circular fronts
+
+/**
+ * Chamfer distance over the mask from a set of sources, as integer fifths of a pixel.
+ * Pixels outside the mask or beyond `cap` stay at -1.
+ */
+function chamfer(mask: Uint8Array, w: number, h: number, sources: Int32Array, cap: number): Int32Array {
+ const dist = new Int32Array(w * h).fill(-1);
+ // Dial's algorithm: one bucket per integer distance, so no priority queue is needed.
+ const buckets: (Int32Array | undefined)[] = [];
+ const counts: number[] = [];
+ const push = (d: number, i: number) => {
+ let b = buckets[d];
+ if (!b) { b = buckets[d] = new Int32Array(64); counts[d] = 0; }
+ if (counts[d] === b.length) { const n = new Int32Array(b.length * 2); n.set(b); b = buckets[d] = n; }
+ b[counts[d]++] = i;
+ };
+ const relax = (j: number, nd: number) => {
+ if (!mask[j]) return;
+ const cur = dist[j];
+ if (cur !== -1 && cur <= nd) return;
+ dist[j] = nd;
+ push(nd, j);
+ };
+ for (let k = 0; k < sources.length; k++) { dist[sources[k]] = 0; push(0, sources[k]); }
+ const limit = cap * AX;
+ for (let d = 0; d < buckets.length && d <= limit; d++) {
+ const b = buckets[d];
+ if (!b) continue;
+ for (let k = 0, n = counts[d]; k < n; k++) {
+ const i = b[k];
+ if (dist[i] !== d) continue; // a shorter path got here first
+ const x = i % w, y = (i - x) / w;
+ const l = x > 0, r = x < w - 1, u = y > 0, dn = y < h - 1;
+ const l2 = x > 1, r2 = x < w - 2, u2 = y > 1, dn2 = y < h - 2;
+ if (l) relax(i - 1, d + AX);
+ if (r) relax(i + 1, d + AX);
+ if (u) relax(i - w, d + AX);
+ if (dn) relax(i + w, d + AX);
+ if (l && u) relax(i - w - 1, d + DI);
+ if (r && u) relax(i - w + 1, d + DI);
+ if (l && dn) relax(i + w - 1, d + DI);
+ if (r && dn) relax(i + w + 1, d + DI);
+ // knight's moves (2, 1): they round off the octagon a plain 5-7 chamfer gives
+ if (u2 && l) relax(i - 2 * w - 1, d + KN);
+ if (u2 && r) relax(i - 2 * w + 1, d + KN);
+ if (dn2 && l) relax(i + 2 * w - 1, d + KN);
+ if (dn2 && r) relax(i + 2 * w + 1, d + KN);
+ if (l2 && u) relax(i - w - 2, d + KN);
+ if (l2 && dn) relax(i + w - 2, d + KN);
+ if (r2 && u) relax(i - w + 2, d + KN);
+ if (r2 && dn) relax(i + w + 2, d + KN);
+ }
+ buckets[d] = undefined; // free as we go
+ }
+ return dist;
+}
+
+/**
+ * Distance from the seed through the region, and distance to the region's edge
+ * (capped at `edgeCap` px; the paper's border does not count as an edge).
+ */
+export function distanceField(mask: Uint8Array, w: number, h: number, sx: number, sy: number, edgeCap = 64, wobble = 8): FillRegion {
+ const seed = sy * w + sx;
+ if (!mask[seed]) throw new Error('seed is outside the region');
+ const fromSeed = chamfer(mask, w, h, Int32Array.of(seed), Number.MAX_SAFE_INTEGER / AX);
+
+ // edge pixels: inside the mask with a 4-neighbour outside it (but inside the image)
+ const edges: number[] = [];
+ let count = 0;
+ let x0 = w, y0 = h, x1 = 0, y1 = 0;
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ const i = y * w + x;
+ if (!mask[i] || fromSeed[i] < 0) { mask[i] = 0; continue; } // drop disconnected bits
+ count++;
+ if (x < x0) x0 = x; if (x >= x1) x1 = x + 1;
+ if (y < y0) y0 = y; if (y >= y1) y1 = y + 1;
+ if ((x > 0 && !mask[i - 1]) || (x < w - 1 && !mask[i + 1]) || (y > 0 && !mask[i - w]) || (y < h - 1 && !mask[i + w])) edges.push(i);
+ }
+ }
+ const fromEdge = chamfer(mask, w, h, Int32Array.from(edges), edgeCap);
+
+ // a little low-frequency wobble so the front is organic rather than geometric
+ const noise = valueNoise(w, h, 48, 2);
+ const field = new Float32Array(w * h * 2);
+ let maxDist = 0;
+ for (let i = 0, n = w * h; i < n; i++) {
+ const d = fromSeed[i];
+ if (d < 0) { field[i * 2] = -1; field[i * 2 + 1] = 0; continue; }
+ const r = Math.max(0, d / AX + (noise[i] - 0.5) * 2 * wobble);
+ if (r > maxDist) maxDist = r;
+ field[i * 2] = r;
+ const e = fromEdge[i];
+ field[i * 2 + 1] = e < 0 ? edgeCap : e / AX;
+ }
+ return { w, h, bbox: { x0, y0, x1, y1 }, count, maxDist, field };
+}
+
+/** Smooth random values in 0..1 with features about `cell` px across (`octaves` of bilinear value noise). */
+function valueNoise(w: number, h: number, cell: number, octaves: number): Float32Array {
+ const out = new Float32Array(w * h);
+ let amp = 0.5, total = 0;
+ for (let o = 0; o < octaves; o++, cell /= 2, amp /= 2) {
+ const gw = Math.ceil(w / cell) + 2, gh = Math.ceil(h / cell) + 2;
+ const grid = new Float32Array(gw * gh);
+ for (let i = 0; i < grid.length; i++) grid[i] = Math.random();
+ for (let y = 0; y < h; y++) {
+ const fy = y / cell, gy = Math.floor(fy), ty = smooth(fy - gy);
+ for (let x = 0; x < w; x++) {
+ const fx = x / cell, gx = Math.floor(fx), tx = smooth(fx - gx);
+ const a = grid[gy * gw + gx], b = grid[gy * gw + gx + 1], c = grid[(gy + 1) * gw + gx], d = grid[(gy + 1) * gw + gx + 1];
+ out[y * w + x] += amp * ((a + (b - a) * tx) + ((c + (d - c) * tx) - (a + (b - a) * tx)) * ty);
+ }
+ }
+ total += amp;
+ }
+ for (let i = 0; i < out.length; i++) out[i] /= total;
+ return out;
+}
+
+const smooth = (t: number) => t * t * (3 - 2 * t);
diff --git a/src/main.ts b/src/main.ts
index ebe8bfc..b7667a8 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -6,10 +6,14 @@ import { loadCustomBrushes, makeCustomBrush, saveCustomBrushes, tipFromImage } f
import { icon } from './ui/icons';
import { drawStroke, drawThumb, forgetTipImages } from './ui/preview';
import { createTextTool } from './text/textTool';
+import { createShapeTool } from './shapes/shapeTool';
+import { createFillTool } from './fill/fillTool';
+import { isSvgFile } from './shapes/svgImport';
import './styles.css';
-/** Engine tools plus the text tool, which drives the engine itself. */
-type UiTool = Tool | 'text';
+/** Engine tools plus the text, shape and fill tools, which drive the engine themselves. */
+type UiTool = Tool | 'text' | 'shape' | 'fill';
+type PanelTool = Exclude<UiTool, Tool>;
const TOOLS: { id: UiTool; label: string; key: string; hint: string }[] = [
{ id: 'brush', label: 'Brush', key: 'B', hint: 'Wet paint: pigment and water' },
@@ -17,6 +21,8 @@ const TOOLS: { id: UiTool; label: string; key: string; hint: string }[] = [
{ id: 'pen', label: 'Pen', key: 'P', hint: 'Ink line in the current colour' },
{ id: 'lift', label: 'Lift', key: 'L', hint: 'Blot with a tissue: lifts wet paint' },
{ id: 'text', label: 'Text', key: 'T', hint: 'Write a line of text, drawn slowly with the current brush' },
+ { id: 'shape', label: 'Shape', key: 'G', hint: 'Drag a line, arrow, rectangle, ellipse, polygon or star, drawn slowly with the current brush' },
+ { id: 'fill', label: 'Fill', key: 'K', hint: 'Tap an area to flood it with a wash of the current pigment' },
];
const SLIDERS: { key: keyof Params; label: string }[] = [
@@ -71,6 +77,7 @@ root.innerHTML = `
</div>
<div class="panel actions">
${button('undo', 'undo', 'Undo', 'Undo (⌘Z)')}
+ ${button('redo', 'redo', 'Redo', 'Redo (⇧⌘Z)')}
${button('dry', 'dry', 'Dry', 'Dry and fix the painting into the paper (D)')}
${button('clear', 'clear', 'Clear', 'Clear the paper')}
${button('save', 'save', 'Save', 'Save PNG (S)')}
@@ -100,6 +107,7 @@ const pickBtn = $('.tool.pick');
const pickThumb = $<HTMLCanvasElement>('.tool.pick .thumb');
const fileInput = $<HTMLInputElement>('.library input[type="file"]');
const undoBtn = $<HTMLButtonElement>('[data-action="undo"]');
+const redoBtn = $<HTMLButtonElement>('[data-action="redo"]');
const clearBtn = $('[data-action="clear"]');
const settingsBtn = $('[data-action="settings"]');
const customSwatch = $('.swatch.custom');
@@ -127,7 +135,7 @@ let brush: Brush = builtIn[0];
try {
engine = new WatercolorEngine(canvas, $('.cursor'), {
- onHistoryChange: can => { undoBtn.disabled = !can; },
+ onHistoryChange: (canUndo, canRedo) => { undoBtn.disabled = !canUndo; redoBtn.disabled = !canRedo; },
onStrokeTool: t => { strokeTool = t; renderTools(); },
});
} catch (e) {
@@ -137,6 +145,11 @@ try {
if (import.meta.env.DEV) (window as unknown as { engine: WatercolorEngine }).engine = engine;
const textTool = createTextTool(engine, root, canvas, showToast);
+const shapeTool = createShapeTool(engine, root, canvas, showToast);
+const fillTool = createFillTool(engine, root, canvas, showToast);
+/** Tools with their own panel that drive the engine themselves. */
+const panelTools: Record<PanelTool, { active: boolean; activate(): void; deactivate(): void; stop(): boolean }> = { text: textTool, shape: shapeTool, fill: fillTool };
+const isPanelTool = (t: UiTool): t is PanelTool => t in panelTools;
/* ------------------------------------------------------------ rendering */
@@ -207,13 +220,13 @@ function renderBrush() {
/* -------------------------------------------------------------- actions */
function setTool(t: UiTool) {
- if (t === 'text' && tool !== 'text') toggleLibrary(false);
+ if (isPanelTool(t) && t !== tool) toggleLibrary(false);
tool = t;
- if (t === 'text') {
+ for (const [id, p] of Object.entries(panelTools)) if (p.active && id !== t) p.deactivate();
+ if (isPanelTool(t)) {
engine.interactive = false;
- textTool.activate();
+ panelTools[t].activate();
} else {
- if (textTool.active) textTool.deactivate();
engine.interactive = true;
engine.setTool(t);
}
@@ -329,6 +342,7 @@ root.addEventListener('click', e => {
else if (el.dataset.index) choose(PALETTE[Number(el.dataset.index)]);
else switch (el.dataset.action) {
case 'undo': engine.undo(); break;
+ case 'redo': engine.redo(); break;
case 'dry': engine.fix(); break;
case 'clear': clear(); break;
case 'save': void save(); break;
@@ -336,7 +350,7 @@ root.addEventListener('click', e => {
case 'library': toggleLibrary(); break;
case 'import': fileInput.click(); break;
case 'reset': setParams(DEFAULT_PARAMS); break;
- case 'text-close': setTool('brush'); break;
+ case 'text-close': case 'shape-close': case 'fill-close': setTool('brush'); break;
}
});
@@ -350,14 +364,21 @@ brushList.addEventListener('keydown', e => {
fileInput.addEventListener('change', () => {
const f = fileInput.files?.[0];
fileInput.value = '';
- if (f) void importTexture(f);
+ if (!f) return;
+ if (isSvgFile(f)) void shapeTool.loadSvg(f).then(ok => { if (ok) setTool('shape'); });
+ else void importTexture(f);
});
// drop an image anywhere to make a brush from it
root.addEventListener('dragover', e => { if (e.dataTransfer?.types.includes('Files')) e.preventDefault(); });
root.addEventListener('drop', e => {
const f = e.dataTransfer?.files?.[0];
- if (f && f.type.startsWith('image/')) { e.preventDefault(); void importTexture(f); }
+ if (!f) return;
+ if (isSvgFile(f)) {
+ // an SVG's paths become a shape to trace, not a brush tip
+ e.preventDefault();
+ void shapeTool.loadSvg(f).then(ok => { if (ok) setTool('shape'); });
+ } else if (f.type.startsWith('image/')) { e.preventDefault(); void importTexture(f); }
});
settings.addEventListener('input', e => {
@@ -376,9 +397,10 @@ window.addEventListener('resize', () => { engine.resize(); renderPreviews(); });
window.addEventListener('keydown', e => {
if (e.target instanceof HTMLInputElement && e.target.type !== 'range') return;
const k = e.key.toLowerCase();
- if ((e.metaKey || e.ctrlKey) && k === 'z') { e.preventDefault(); engine.undo(); return; }
+ if ((e.metaKey || e.ctrlKey) && k === 'z') { e.preventDefault(); if (e.shiftKey) engine.redo(); else engine.undo(); return; }
+ if ((e.metaKey || e.ctrlKey) && k === 'y') { e.preventDefault(); engine.redo(); return; }
if (e.metaKey || e.ctrlKey || e.altKey) return;
- if (k === 'escape') { if (!textTool.stop()) { toggleLibrary(false); toggleSettings(false); } return; }
+ if (k === 'escape') { if (!Object.values(panelTools).some(p => p.stop())) { toggleLibrary(false); toggleSettings(false); } return; }
const t = TOOLS.find(x => x.key.toLowerCase() === k);
if (t) setTool(t.id);
else if (k === '[' || k === ']') setParams({ size: Math.min(1, Math.max(0, params.size + (k === ']' ? 0.05 : -0.05))) });
@@ -398,6 +420,7 @@ window.addEventListener('keydown', e => {
engine.setPigment(current.pigment);
engine.setBrush(brush);
undoBtn.disabled = true;
+redoBtn.disabled = true;
renderTools();
renderParams();
renderPalette();
diff --git a/src/shapes/shapeTool.ts b/src/shapes/shapeTool.ts
new file mode 100644
index 0000000..3f2f11f
--- /dev/null
+++ b/src/shapes/shapeTool.ts
@@ -0,0 +1,323 @@
+import type { Tool, WatercolorEngine } from '../engine/Engine';
+import { icon } from '../ui/icons';
+import { penSpeed, StrokeWriter } from '../draw/StrokeWriter';
+import { createGhost } from '../draw/ghost';
+import { constrain, fitSvg, hasRotation, hasSides, SHAPES, shapeStrokes, type ShapeKind } from './shapes';
+import { importSvg, type ImportedSvg } from './svgImport';
+
+// The Shape tool: pick a shape, drag a box on the paper (a dashed ghost follows),
+// and on release the StrokeWriter draws the outline slowly with the current brush.
+
+export interface ShapeSettings {
+ kind: ShapeKind;
+ tool: Tool;
+ lock: boolean; // keep squares square / circles round / lines on 45° steps
+ speed: number; // 0..1 slider
+ pressure: number; // 0.05..1
+ taper: number; // 0..1
+ wobble: number; // 0..1
+ sides: number; // 3..12
+ inner: number; // 0.2..0.9
+ rotation: number; // 0..360
+}
+
+const KEY = 'watercolor.shape';
+const DEFAULTS: ShapeSettings = {
+ kind: 'rect', tool: 'brush', lock: false,
+ speed: 0.5, pressure: 0.6, taper: 0.4, wobble: 0.2, sides: 5, inner: 0.45, rotation: 0,
+};
+
+const SLIDERS: { key: keyof ShapeSettings; label: string; min: number; max: number; step: number; hint: string; show?: (k: ShapeKind) => boolean }[] = [
+ { key: 'speed', label: 'Speed', min: 0, max: 1, step: 0.01, hint: 'How fast the brush travels' },
+ { key: 'pressure', label: 'Pressure', min: 0.05, max: 1, step: 0.01, hint: 'How hard the brush presses' },
+ { key: 'taper', label: 'Taper', min: 0, max: 1, step: 0.01, hint: 'Lighter touch at the ends of each stroke' },
+ { key: 'wobble', label: 'Wobble', min: 0, max: 1, step: 0.01, hint: 'Hand tremor' },
+ { key: 'sides', label: 'Sides', min: 3, max: 12, step: 1, hint: 'Polygon sides / star points', show: hasSides },
+ { key: 'inner', label: 'Inner', min: 0.2, max: 0.9, step: 0.01, hint: 'Star inner radius', show: k => k === 'star' },
+ { key: 'rotation', label: 'Rotate', min: 0, max: 360, step: 1, hint: 'Rotation in degrees', show: hasRotation },
+];
+
+const TOOLS: { id: Tool; label: string }[] = [{ id: 'brush', label: 'Brush' }, { id: 'pen', label: 'Pen' }, { id: 'water', label: 'Water' }];
+
+/** Small outline glyphs for the shape grid (24×24 viewBox). */
+const GLYPHS: Record<ShapeKind, string> = {
+ line: 'M5 19 19 5',
+ arrow: 'M5 19 19 5 M11 5h8v8',
+ rect: 'M4.5 6.5h15v11h-15Z',
+ ellipse: 'M12 5.5c4.4 0 8 2.9 8 6.5s-3.6 6.5-8 6.5-8-2.9-8-6.5 3.6-6.5 8-6.5Z',
+ triangle: 'M12 5 20 19H4Z',
+ polygon: 'M12 4.5 19.5 10l-2.9 9H7.4L4.5 10Z',
+ star: 'M12 4.5l2.2 5 5.3.5-4 3.6 1.2 5.3L12 16.1l-4.7 2.8 1.2-5.3-4-3.6 5.3-.5Z',
+ svg: 'M7 3.5h7l4 4V20.5H7Z M14 3.5v4h4 M9.5 16.5c1.5-4 3.5-4 5 0',
+};
+
+const esc = (s: string) => s.replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]!);
+type Pt = [number, number];
+
+export interface ShapeToolHandle {
+ panel: HTMLElement;
+ activate(): void;
+ deactivate(): void;
+ /** Cancel a drag or stop drawing. Returns whether anything was stopped. */
+ stop(): boolean;
+ /** Load an SVG file as the `svg` shape. Resolves false (after a toast) if it could not be read. */
+ loadSvg(file: File): Promise<boolean>;
+ readonly active: boolean;
+}
+
+export function createShapeTool(engine: WatercolorEngine, root: HTMLElement, canvas: HTMLCanvasElement, toast: (s: string) => void): ShapeToolHandle {
+ let settings: ShapeSettings = { ...DEFAULTS, ...load() };
+ // the imported file lives for the session only, so a saved `svg` kind starts empty
+ if (!SHAPES.some(s => s.id === settings.kind) || settings.kind === 'svg') settings.kind = DEFAULTS.kind;
+ let svg: ImportedSvg | null = null;
+ let active = false;
+ let drag: { id: number; a: Pt; b: Pt; shift: boolean } | null = null;
+ const writer = new StrokeWriter(engine);
+ const ghost = createGhost(root);
+
+ /* ---------------------------------------------------------------- markup */
+
+ const panel = document.createElement('div');
+ panel.className = 'panel text shape';
+ panel.hidden = true;
+ panel.setAttribute('role', 'dialog');
+ panel.setAttribute('aria-label', 'Shapes');
+ panel.innerHTML = `
+ <div class="library-head">
+ <span>Shapes</span>
+ <span class="sub">Drag a box on the paper; when you let go the outline is drawn stroke by stroke with the current brush and pigment.</span>
+ <button class="icon" data-action="shape-close" title="Close">${icon('close', 16)}</button>
+ </div>
+ <div class="text-body">
+ <div class="shapes" role="radiogroup" aria-label="Shape">
+ ${SHAPES.map(s => `<button role="radio" data-kind="${s.id}" title="${esc(s.hint)}"><svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${GLYPHS[s.id]}"/></svg><span>${s.short ?? s.label}</span></button>`).join('')}
+ </div>
+ <div class="text-rows">
+ <div class="slider svg-row" hidden><span>File</span><div class="svg-file"><span class="svg-name"></span><button class="svg-pick" data-action="svg-pick">Choose…</button></div></div>
+ <label class="slider"><span>Draw with</span><div class="seg" data-opt="tool" role="radiogroup">${TOOLS.map(t => `<button role="radio" data-value="${t.id}">${t.label}</button>`).join('')}</div></label>
+ <label class="slider"><span>Lock</span><div class="seg" data-opt="lock" role="radiogroup" title="Keep squares square, circles round, lines on 45° steps and SVGs in their own proportions (or hold Shift)"><button role="radio" data-value="false">Free</button><button role="radio" data-value="true">1 : 1</button></div></label>
+ ${SLIDERS.map(s => `<label class="slider" data-slider="${s.key}" title="${s.hint}"><span>${s.label}</span><input type="range" min="${s.min}" max="${s.max}" step="${s.step}" data-opt="${s.key}"></label>`).join('')}
+ </div>
+ <div class="text-foot">
+ <span class="status"></span>
+ <button class="stop" data-action="shape-stop" hidden>${icon('close', 14)}<span>Stop</span></button>
+ </div>
+ </div>
+ <input type="file" accept=".svg,image/svg+xml" hidden>`;
+ root.appendChild(panel);
+
+ const status = panel.querySelector<HTMLElement>('.status')!;
+ const stopBtn = panel.querySelector<HTMLButtonElement>('.stop')!;
+ const sliders = [...panel.querySelectorAll<HTMLInputElement>('input[type="range"][data-opt]')];
+ const svgRow = panel.querySelector<HTMLElement>('.svg-row')!;
+ const svgName = panel.querySelector<HTMLElement>('.svg-name')!;
+ const svgPick = panel.querySelector<HTMLButtonElement>('.svg-pick')!;
+ const fileInput = panel.querySelector<HTMLInputElement>('input[type="file"]')!;
+ /** Shape parameters including the imported file. */
+ const params = () => ({ ...settings, svg });
+
+ /* ------------------------------------------------------------- rendering */
+
+ function render() {
+ for (const s of sliders) s.value = String(settings[s.dataset.opt as keyof ShapeSettings]);
+ for (const s of SLIDERS) panel.querySelector<HTMLElement>(`[data-slider="${s.key}"]`)!.hidden = s.show ? !s.show(settings.kind) : false;
+ svgRow.hidden = settings.kind !== 'svg';
+ svgName.textContent = svg ? `${svg.name} · ${svg.count} ${svg.count === 1 ? 'stroke' : 'strokes'}` : 'No file yet';
+ svgName.title = svg ? svg.name : '';
+ svgPick.textContent = svg ? 'Replace…' : 'Choose…';
+ for (const b of panel.querySelectorAll<HTMLElement>('.shapes button')) {
+ const on = b.dataset.kind === settings.kind;
+ b.classList.toggle('on', on);
+ b.setAttribute('aria-checked', String(on));
+ }
+ for (const el of panel.querySelectorAll<HTMLElement>('.seg')) {
+ const v = String(settings[el.dataset.opt as 'tool' | 'lock']);
+ for (const b of el.querySelectorAll<HTMLElement>('button')) {
+ b.classList.toggle('on', b.dataset.value === v);
+ b.setAttribute('aria-checked', String(b.dataset.value === v));
+ }
+ }
+ renderStatus();
+ }
+
+ function renderStatus(progress?: [number, number]) {
+ stopBtn.hidden = !writer.busy;
+ const name = SHAPES.find(s => s.id === settings.kind)!.label.toLowerCase();
+ if (writer.busy) status.textContent = progress && progress[1] > 1 ? `Drawing… ${progress[0]} / ${progress[1]} strokes` : 'Drawing…';
+ else if (drag) status.textContent = 'Let go to draw';
+ else if (!active) status.textContent = '';
+ else if (settings.kind === 'svg') status.textContent = svg ? `Drag on the paper to place ${svg.name}` : 'Choose an SVG file, or drop one on the paper';
+ else status.textContent = `Drag on the paper to draw a ${name}`;
+ }
+
+ /** The drag end, constrained if the lock (or Shift) is on. */
+ function endPoint(d: { a: Pt; b: Pt; shift: boolean }): Pt {
+ const boxAspect = settings.kind === 'svg' && svg ? svg.aspect : 1;
+ return settings.lock !== d.shift ? constrain(settings.kind, d.a, d.b, engine.aspect, boxAspect) : d.b;
+ }
+
+ /** Strokes for the ghost: the thinned copy for SVGs, the real thing otherwise. */
+ function ghostStrokes(a: Pt, b: Pt, aspect: number) {
+ if (settings.kind !== 'svg') return shapeStrokes(settings.kind, a, b, params(), aspect);
+ return svg ? fitSvg(svg.ghost, (b[0] - a[0]) * aspect, b[1] - a[1], settings.rotation) : [];
+ }
+
+ function renderGhost() {
+ if (!active || !drag || writer.busy) { ghost.hide(); return; }
+ const a = engine.aspect;
+ const [ax, ay] = drag.a;
+ let d = '';
+ for (const pl of ghostStrokes(drag.a, endPoint(drag), a)) {
+ pl.forEach(([x, y], i) => {
+ const [cx, cy] = engine.docToClient(ax + x / a, ay + y);
+ d += `${i ? 'L' : 'M'}${cx.toFixed(1)} ${cy.toFixed(1)}`;
+ });
+ }
+ ghost.set(d);
+ }
+
+ /* --------------------------------------------------------------- actions */
+
+ function save() {
+ try { localStorage.setItem(KEY, JSON.stringify(settings)); } catch { /* storage blocked */ }
+ }
+
+ function set(p: Partial<ShapeSettings>) {
+ settings = { ...settings, ...p };
+ save();
+ render();
+ renderGhost();
+ }
+
+ function draw(d: { a: Pt; b: Pt; shift: boolean }) {
+ const b = endPoint(d);
+ const aspect = engine.aspect;
+ const w = Math.abs(b[0] - d.a[0]) * aspect, h = Math.abs(b[1] - d.a[1]);
+ const strokes = shapeStrokes(settings.kind, d.a, b, params(), aspect);
+ if (!strokes.length) return;
+ const ref = settings.kind === 'line' || settings.kind === 'arrow' ? Math.hypot(w, h) * 0.5 : Math.max(0.01, Math.min(w, h));
+ writer.write(strokes, d.a, {
+ tool: settings.tool, ref, speed: penSpeed(settings.speed),
+ pressure: settings.pressure, taper: settings.taper, wobble: settings.wobble,
+ }, {
+ onProgress: (done, total) => renderStatus([done, total]),
+ onDone: () => { renderStatus(); renderGhost(); },
+ });
+ renderStatus([0, strokes.length]);
+ renderGhost();
+ }
+
+ async function loadSvg(file: File): Promise<boolean> {
+ try {
+ svg = await importSvg(file);
+ } catch (e) {
+ toast(e instanceof Error ? e.message : 'Could not read that SVG');
+ return false;
+ }
+ set({ kind: 'svg' });
+ return true;
+ }
+
+ function cancelDrag() {
+ if (!drag) return false;
+ try { canvas.releasePointerCapture(drag.id); } catch { /* already released */ }
+ drag = null;
+ renderGhost();
+ renderStatus();
+ return true;
+ }
+
+ /* ---------------------------------------------------------------- wiring */
+
+ panel.addEventListener('input', e => {
+ const s = e.target as HTMLInputElement;
+ if (s.type === 'range' && s.dataset.opt) set({ [s.dataset.opt]: Number(s.value) } as Partial<ShapeSettings>);
+ });
+
+ panel.addEventListener('click', e => {
+ const el = (e.target as Element).closest<HTMLElement>('[data-kind], .seg button, [data-action]');
+ if (!el) return;
+ if (el.dataset.kind) {
+ const kind = el.dataset.kind as ShapeKind;
+ set({ kind });
+ if (kind === 'svg' && !svg) fileInput.click();
+ } else if (el.dataset.value !== undefined) {
+ const opt = el.parentElement!.dataset.opt!;
+ set({ [opt]: opt === 'lock' ? el.dataset.value === 'true' : el.dataset.value } as Partial<ShapeSettings>);
+ } else if (el.dataset.action === 'shape-stop') writer.cancel();
+ else if (el.dataset.action === 'svg-pick') fileInput.click();
+ });
+
+ fileInput.addEventListener('change', () => {
+ const f = fileInput.files?.[0];
+ fileInput.value = '';
+ if (f) void loadSvg(f);
+ });
+
+ canvas.addEventListener('pointerdown', e => {
+ if (!active || drag) return;
+ if (writer.busy) { toast('Still drawing… press Stop or Esc'); return; }
+ try { canvas.setPointerCapture(e.pointerId); } catch { /* pointer already gone */ }
+ const a = engine.clientToDoc(e.clientX, e.clientY);
+ drag = { id: e.pointerId, a, b: a, shift: e.shiftKey };
+ renderStatus();
+ });
+ canvas.addEventListener('pointermove', e => {
+ if (!active || !drag || e.pointerId !== drag.id) return;
+ drag.b = engine.clientToDoc(e.clientX, e.clientY);
+ drag.shift = e.shiftKey;
+ renderGhost();
+ });
+ const up = (e: PointerEvent) => {
+ if (!active || !drag || e.pointerId !== drag.id) return;
+ const d = drag;
+ d.b = engine.clientToDoc(e.clientX, e.clientY);
+ d.shift = e.shiftKey;
+ cancelDrag();
+ if (e.type === 'pointercancel') return;
+ const [x0, y0] = engine.docToClient(...d.a), [x1, y1] = engine.docToClient(...d.b);
+ if (settings.kind === 'svg' && !svg) { fileInput.click(); return; }
+ if (Math.hypot(x1 - x0, y1 - y0) < 6) { toast('Drag to size the shape'); return; }
+ draw(d);
+ };
+ canvas.addEventListener('pointerup', up);
+ canvas.addEventListener('pointercancel', up);
+ window.addEventListener('resize', renderGhost);
+
+ render();
+
+ return {
+ panel,
+ get active() { return active; },
+ activate() {
+ active = true;
+ panel.hidden = false;
+ canvas.classList.add('placing');
+ renderStatus();
+ },
+ deactivate() {
+ active = false;
+ cancelDrag();
+ writer.cancel();
+ panel.hidden = true;
+ canvas.classList.remove('placing');
+ ghost.hide();
+ },
+ stop() {
+ if (cancelDrag()) return true;
+ if (!writer.busy) return false;
+ writer.cancel();
+ return true;
+ },
+ loadSvg,
+ };
+}
+
+function load(): Partial<ShapeSettings> {
+ try {
+ const raw = localStorage.getItem(KEY);
+ if (!raw) return {};
+ const v = JSON.parse(raw) as Partial<ShapeSettings>;
+ return typeof v === 'object' && v ? v : {};
+ } catch { return {}; }
+}
diff --git a/src/shapes/shapes.ts b/src/shapes/shapes.ts
new file mode 100644
index 0000000..06578cc
--- /dev/null
+++ b/src/shapes/shapes.ts
@@ -0,0 +1,128 @@
+import type { Polyline } from '../draw/StrokeWriter';
+import type { ImportedSvg } from './svgImport';
+
+// Geometric outlines as pen paths, fitted to a dragged box. Coordinates are in
+// document heights (y up); the box corners are the drag's start `a` and end `b`.
+
+export type ShapeKind = 'line' | 'arrow' | 'rect' | 'ellipse' | 'triangle' | 'polygon' | 'star' | 'svg';
+
+export interface ShapeParams {
+ /** Polygon sides / star points. */
+ sides: number;
+ /** Star inner radius as a fraction of the outer. */
+ inner: number;
+ /** Degrees, anticlockwise. */
+ rotation: number;
+ /** The imported file for the `svg` kind. */
+ svg?: ImportedSvg | null;
+}
+
+/** `short` is the grid caption; `label` is used in prose. */
+export const SHAPES: { id: ShapeKind; label: string; short?: string; hint: string }[] = [
+ { id: 'line', label: 'Line', hint: 'A straight stroke from where you press to where you let go' },
+ { id: 'arrow', label: 'Arrow', hint: 'A line with a head at the end' },
+ { id: 'rect', label: 'Rectangle', short: 'Rect', hint: 'Four sides in one stroke' },
+ { id: 'ellipse', label: 'Ellipse', short: 'Oval', hint: 'An oval fitted to the box' },
+ { id: 'triangle', label: 'Triangle', short: 'Tri', hint: 'Apex up, fitted to the box' },
+ { id: 'polygon', label: 'Polygon', short: 'Poly', hint: 'A regular shape with the chosen number of sides' },
+ { id: 'star', label: 'Star', hint: 'Points and an inner radius of your choosing' },
+ { id: 'svg', label: 'SVG', hint: 'Import an SVG file and trace its paths' },
+];
+
+const DEG = Math.PI / 180;
+type Pt = [number, number];
+
+/** Does the shape have a rotation / sides control? */
+export const hasRotation = (k: ShapeKind) => k !== 'line' && k !== 'arrow';
+export const hasSides = (k: ShapeKind) => k === 'polygon' || k === 'star';
+
+/**
+ * Snap the drag end so the box is square (or the line lies on a 45° step) when
+ * the aspect lock is on. `aspect` is the document's width / height; `boxAspect`
+ * is the width / height the box should keep (1 for presets, the file's for SVGs).
+ */
+export function constrain(kind: ShapeKind, a: Pt, b: Pt, aspect: number, boxAspect = 1): Pt {
+ const dx = (b[0] - a[0]) * aspect, dy = b[1] - a[1];
+ if (kind === 'line' || kind === 'arrow') {
+ const len = Math.hypot(dx, dy), ang = Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) * (Math.PI / 4);
+ return [a[0] + (Math.cos(ang) * len) / aspect, a[1] + Math.sin(ang) * len];
+ }
+ const m = Math.max(Math.abs(dx) / boxAspect, Math.abs(dy));
+ return [a[0] + (Math.sign(dx) * m * boxAspect) / aspect, a[1] + Math.sign(dy) * m];
+}
+
+/**
+ * Fit normalised SVG strokes (0..1, y up) into the signed box `w` × `h`, never
+ * mirrored however the box was dragged, then rotated about the box centre.
+ */
+export function fitSvg(strokes: Polyline[], w: number, h: number, rotationDeg: number): Polyline[] {
+ const ox = Math.min(0, w), oy = Math.min(0, h), sx = Math.abs(w), sy = Math.abs(h);
+ const cx = w / 2, cy = h / 2, rot = rotationDeg * DEG, c = Math.cos(rot), s = Math.sin(rot);
+ return strokes.map(pl => pl.map(([x, y]) => {
+ const dx = ox + x * sx - cx, dy = oy + y * sy - cy;
+ return [cx + dx * c - dy * s, cy + dx * s + dy * c] as Pt;
+ }));
+}
+
+/**
+ * Strokes of the shape, in document heights relative to `a`. `a` and `b` are in
+ * document uv; the box is converted with `aspect` so circles stay round.
+ */
+export function shapeStrokes(kind: ShapeKind, a: Pt, b: Pt, p: ShapeParams, aspect: number): Polyline[] {
+ const w = (b[0] - a[0]) * aspect, h = b[1] - a[1]; // box extents from a (signed)
+ const cx = w / 2, cy = h / 2, rx = Math.abs(w) / 2, ry = Math.abs(h) / 2;
+ const rot = p.rotation * DEG;
+ const onEllipse = (ang: number, k = 1): Pt => [cx + Math.cos(ang + rot) * rx * k, cy + Math.sin(ang + rot) * ry * k];
+
+ switch (kind) {
+ case 'line': return [[[0, 0], [w, h]]];
+ case 'arrow': {
+ const len = Math.hypot(w, h);
+ if (len < 1e-6) return [[[0, 0], [w, h]]];
+ const ux = w / len, uy = h / len;
+ const head = Math.min(len * 0.3, Math.max(0.012, len * 0.18));
+ const c = Math.cos(28 * DEG) * head, s = Math.sin(28 * DEG) * head;
+ const tip: Pt = [w, h];
+ const l: Pt = [w - ux * c + uy * s, h - uy * c - ux * s];
+ const r: Pt = [w - ux * c - uy * s, h - uy * c + ux * s];
+ return [[[0, 0], tip], [l, tip, r]];
+ }
+ case 'rect': return [closed([[0, 0], [w, 0], [w, h], [0, h]])];
+ case 'triangle': {
+ // apex at the top of the box, then rotated about the centre
+ const pts: Pt[] = [[cx, cy + ry], [cx + rx, cy - ry], [cx - rx, cy - ry]].map(([x, y]) => {
+ const dx = x - cx, dy = y - cy;
+ return [cx + dx * Math.cos(rot) - dy * Math.sin(rot), cy + dx * Math.sin(rot) + dy * Math.cos(rot)];
+ });
+ return [closed(startNearOrigin(pts))];
+ }
+ case 'ellipse': {
+ const n = Math.round(Math.min(160, Math.max(48, (Math.PI * (rx + ry)) / 0.004)));
+ const pts: Pt[] = [];
+ for (let i = 0; i < n; i++) pts.push(onEllipse((i / n) * Math.PI * 2));
+ return [closed(startNearOrigin(pts))];
+ }
+ case 'polygon': {
+ const n = Math.max(3, Math.round(p.sides));
+ const pts: Pt[] = [];
+ for (let i = 0; i < n; i++) pts.push(onEllipse(Math.PI / 2 + (i / n) * Math.PI * 2));
+ return [closed(startNearOrigin(pts))];
+ }
+ case 'star': {
+ const n = Math.max(3, Math.round(p.sides)), k = Math.min(0.95, Math.max(0.1, p.inner));
+ const pts: Pt[] = [];
+ for (let i = 0; i < n * 2; i++) pts.push(onEllipse(Math.PI / 2 + (i / (n * 2)) * Math.PI * 2, i % 2 ? k : 1));
+ return [closed(startNearOrigin(pts))];
+ }
+ case 'svg': return p.svg ? fitSvg(p.svg.strokes, w, h, p.rotation) : [];
+ }
+}
+
+const closed = (pts: Pt[]): Polyline => [...pts, pts[0]];
+
+/** Rotate the vertex list so the pen starts at the vertex nearest the drag origin. */
+function startNearOrigin(pts: Pt[]): Pt[] {
+ let best = 0, d = Infinity;
+ pts.forEach(([x, y], i) => { const m = x * x + y * y; if (m < d) { d = m; best = i; } });
+ return [...pts.slice(best), ...pts.slice(0, best)];
+}
diff --git a/src/shapes/svgImport.ts b/src/shapes/svgImport.ts
new file mode 100644
index 0000000..f897557
--- /dev/null
+++ b/src/shapes/svgImport.ts
@@ -0,0 +1,78 @@
+import { linemerge, linesort, linePoints, readSvg } from 'vpype-js';
+import type { Polyline } from '../draw/StrokeWriter';
+
+// Turns an SVG file into pen paths for the Shape tool. vpype-js does the heavy
+// lifting (transforms, arcs, <use>, viewBox and units); we then merge touching
+// lines, sort them to shorten pen-up hops, and normalise to a unit box.
+
+export interface ImportedSvg {
+ name: string;
+ /** Content width / height. */
+ aspect: number;
+ /** Strokes with x and y in 0..1, y pointing up, fitted to the content bounds. */
+ strokes: Polyline[];
+ /** A thinned copy for the live ghost preview. */
+ ghost: Polyline[];
+ /** Number of strokes (pen-down runs). */
+ count: number;
+}
+
+const GHOST_POINTS = 3000;
+
+export const isSvgFile = (f: File) => f.type === 'image/svg+xml' || /\.svg$/i.test(f.name);
+
+export async function importSvg(file: File): Promise<ImportedSvg> {
+ const text = await file.text();
+ let lines;
+ try {
+ // A coarse first pass just to learn the page size, then resample curves
+ // finely relative to it (the writer resamples again at drawing time).
+ const { width, height } = readSvg(text, 1000, { crop: false });
+ const q = Math.max(0.05, Math.max(width, height) / 800);
+ lines = readSvg(text, q, { crop: false }).lines;
+ lines = linesort(linemerge(lines, { tolerance: q * 2, flip: true }), { flip: true });
+ } catch (e) {
+ throw new Error(e instanceof Error && /xml|parse|svg/i.test(e.message) ? 'That file is not a valid SVG' : 'Could not read that SVG');
+ }
+
+ const polys: Polyline[] = [];
+ for (const line of lines) {
+ const pts = linePoints(line).filter(([x, y]) => Number.isFinite(x) && Number.isFinite(y)) as Polyline;
+ if (pts.length >= 2) polys.push(pts);
+ }
+ if (!polys.length) throw new Error('No paths found in that SVG (text and images are ignored)');
+
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
+ for (const pl of polys) for (const [x, y] of pl) {
+ if (x < x0) x0 = x; if (x > x1) x1 = x;
+ if (y < y0) y0 = y; if (y > y1) y1 = y;
+ }
+ const w = Math.max(x1 - x0, 1e-9), h = Math.max(y1 - y0, 1e-9);
+ const strokes = polys.map(pl => pl.map(([x, y]) => [(x - x0) / w, 1 - (y - y0) / h] as [number, number]));
+
+ return {
+ name: file.name.replace(/\.svg$/i, '') || 'SVG',
+ aspect: w / h,
+ strokes,
+ ghost: thin(strokes, GHOST_POINTS),
+ count: strokes.length,
+ };
+}
+
+/** Keep roughly `budget` points in total, always keeping each stroke's end points. */
+function thin(strokes: Polyline[], budget: number): Polyline[] {
+ const total = strokes.reduce((n, pl) => n + pl.length, 0);
+ if (total <= budget) return strokes;
+ const keep = budget / total;
+ return strokes.map(pl => {
+ if (pl.length <= 2) return pl;
+ const out: Polyline = [pl[0]];
+ let acc = 0;
+ for (let i = 1; i < pl.length - 1; i++) {
+ acc += keep;
+ if (acc >= 1) { acc -= 1; out.push(pl[i]); }
+ }
+ out.push(pl[pl.length - 1]);
+ return out;
+ });
+}
diff --git a/src/styles.css b/src/styles.css
index 5eaa0a0..9f4feae 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -248,6 +248,14 @@ input[type="range"]::-moz-range-thumb { width: 11px; height: 11px; border-radius
.fontrow i { display: block; width: 260px; height: 32px; max-width: 100%; background-repeat: no-repeat; background-size: 260px auto; opacity: 0.85; }
.fontrow span { display: block; font-size: 12px; line-height: 32px; }
+.shapes { display: grid; grid-template-columns: repeat(8, minmax(0, 1fr)); gap: 2px; }
+.svg-file { display: flex; align-items: center; gap: 6px; min-width: 0; }
+.svg-name { flex: 1; min-width: 0; font-size: 12px; color: var(--ink); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.panel .svg-pick { flex: 0 0 auto; padding: 5px 9px; border-radius: 7px; font-size: 9px; letter-spacing: 0.12em; text-transform: uppercase; background: rgba(255, 255, 255, 0.85); color: var(--ink); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06); }
+.panel .shapes button { padding: 6px 2px; gap: 2px; min-width: 0; }
+.panel .shapes button span { font-size: 8px; letter-spacing: 0.06em; white-space: nowrap; }
+.panel .shapes button.on { color: var(--ink); background: rgba(255, 255, 255, 0.85); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06); }
+
.text-rows { display: flex; flex-direction: column; gap: 7px; }
.text-rows .slider { grid-template-columns: 58px 1fr; }
.seg { display: flex; gap: 2px; padding: 2px; border-radius: 9px; background: rgba(42, 42, 51, 0.06); }
diff --git a/src/text/fontLoader.ts b/src/text/fontLoader.ts
index e49cf76..d34890f 100644
--- a/src/text/fontLoader.ts
+++ b/src/text/fontLoader.ts
@@ -4,8 +4,8 @@
// flattened to polylines in em units (1 = the em height), baseline at y = 0,
// y down, ready to be driven along by a brush.
-/** A pen-down ... pen-up run of points, in em units. */
-export type Polyline = [number, number][];
+import type { Polyline } from '../draw/StrokeWriter';
+export type { Polyline };
export interface Glyph {
strokes: Polyline[];
diff --git a/src/text/textTool.ts b/src/text/textTool.ts
index 414453b..2cc3842 100644
--- a/src/text/textTool.ts
+++ b/src/text/textTool.ts
@@ -3,7 +3,8 @@ import { icon } from '../ui/icons';
import { ATLAS, DEFAULT_FONT, FONTS, fontGroups, fontLabel, fontUrl } from './fonts';
import { loadFont, type Font } from './fontLoader';
import { layoutText, type Align, type TextLayout } from './layout';
-import { TextWriter } from './TextWriter';
+import { penSpeed, StrokeWriter } from '../draw/StrokeWriter';
+import { createGhost } from '../draw/ghost';
// The Text tool: a panel to compose one line of text in a single-stroke font,
// a ghost of it under the pointer, and on tap the TextWriter draws it on the
@@ -42,8 +43,6 @@ const ALIGNS: { id: Align; label: string }[] = [{ id: 'left', label: 'Left' }, {
/** Em height in document heights. */
export const emSize = (v: number) => 0.03 * Math.pow(12, v);
-/** Pen speed in document heights per second. */
-export const penSpeed = (v: number) => 0.05 * Math.pow(40, v);
const esc = (s: string) => s.replace(/[&<>"]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]!);
@@ -64,7 +63,7 @@ export function createTextTool(engine: WatercolorEngine, root: HTMLElement, canv
let layout: TextLayout | null = null;
let active = false;
let hover: [number, number] | null = null; // document uv under the pointer
- const writer = new TextWriter(engine);
+ const writer = new StrokeWriter(engine);
/* ---------------------------------------------------------------- markup */
@@ -103,12 +102,7 @@ export function createTextTool(engine: WatercolorEngine, root: HTMLElement, canv
</div>`;
root.appendChild(panel);
- // ghost of the text under the pointer
- const ghost = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- ghost.setAttribute('class', 'ghost');
- ghost.innerHTML = '<path/>';
- root.appendChild(ghost);
- const ghostPath = ghost.querySelector('path')!;
+ const ghost = createGhost(root); // the text under the pointer
const input = panel.querySelector<HTMLInputElement>('.text-input')!;
const fontList = panel.querySelector<HTMLElement>('.fontlist')!;
@@ -154,7 +148,7 @@ export function createTextTool(engine: WatercolorEngine, root: HTMLElement, canv
/** Client-space path of the ghost at the hovered anchor. */
function renderGhost() {
- if (!active || !layout || !hover || writer.busy) { ghost.style.display = 'none'; return; }
+ if (!active || !layout || !hover || writer.busy) { ghost.hide(); return; }
const em = emSize(settings.size), a = engine.aspect;
const [ax, ay] = hover;
let d = '';
@@ -167,8 +161,7 @@ export function createTextTool(engine: WatercolorEngine, root: HTMLElement, canv
// baseline tick at the anchor
const [bx, by] = engine.docToClient(ax, ay);
d += `M${(bx - 6).toFixed(1)} ${by.toFixed(1)}h12M${bx.toFixed(1)} ${(by - 6).toFixed(1)}v12`;
- ghostPath.setAttribute('d', d);
- ghost.style.display = '';
+ ghost.set(d);
}
/* --------------------------------------------------------------- actions */
@@ -211,11 +204,14 @@ export function createTextTool(engine: WatercolorEngine, root: HTMLElement, canv
function writeAt(anchor: [number, number]) {
if (!layout?.strokes.length || writer.busy) return;
+ const em = emSize(settings.size);
const opts = {
- tool: settings.tool, size: emSize(settings.size), speed: penSpeed(settings.speed),
+ tool: settings.tool, ref: em, speed: penSpeed(settings.speed),
pressure: settings.pressure, taper: settings.taper, wobble: settings.wobble,
};
- writer.write(layout, anchor, opts, {
+ // em units (y down) -> document heights relative to the anchor (y up)
+ const strokes = layout.strokes.map(pl => pl.map(([x, y]) => [x * em, -y * em] as [number, number]));
+ writer.write(strokes, anchor, opts, {
onProgress: (done, total) => renderStatus([done, total]),
onDone: () => { renderStatus(); renderGhost(); },
});
diff --git a/src/ui/icons.ts b/src/ui/icons.ts
index 1dd61b0..8e88a13 100644
--- a/src/ui/icons.ts
+++ b/src/ui/icons.ts
@@ -5,6 +5,9 @@ const PATHS: Record<string, string> = {
text: 'M5 7.5V5h14v2.5 M12 5v14 M9.5 19h5',
lift: 'M5 8.5c2-1.5 4-1.5 6 0s4 1.5 6 0l2 9c-2 1.5-4 1.5-6 0s-4-1.5-6 0l-2-9Z M8 3.5c1 .8 2 .8 3 0',
undo: 'M9 5.5 4 10.5l5 5 M4 10.5h10a4.75 4.75 0 0 1 0 9.5h-3',
+ redo: 'M15 5.5 20 10.5l-5 5 M20 10.5H10a4.75 4.75 0 0 0 0 9.5h3',
+ shape: 'M4 4.5h8v8H4Z M15.5 11.5a4.5 4.5 0 1 1 0 9 4.5 4.5 0 0 1 0-9Z',
+ fill: 'M10 3.5 4.5 9l7 7 5.5-5.5Z M4.5 9c2 .5 4 .5 6-1 M10 3.5 7.5 1.5 M19 13c1.3 1.8 2 3 2 3.9a2 2 0 0 1-4 0c0-.9.7-2.1 2-3.9Z',
dry: 'M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8Z M12 2v2.5 M12 19.5V22 M2 12h2.5 M19.5 12H22 M4.9 4.9l1.8 1.8 M17.3 17.3l1.8 1.8 M4.9 19.1l1.8-1.8 M17.3 6.7l1.8-1.8',
clear: 'M5 7h14 M10 7V4.5h4V7 M7 7l1 13h8l1-13',
save: 'M12 4v11 M7.5 10.5 12 15l4.5-4.5 M5 19.5h14',