// Brush engine + painting tools (brush, pencil, eraser). // Paint goes into a doc-sized stroke buffer which the compositor previews live; // on pointer-up the buffer is merged into the layer with one undo entry. import { createCanvas, Rect, clamp } from '../core/util.js'; import { PixelEdit } from '../core/history.js'; import { blendOp } from '../core/layer.js'; import { applyStroke } from '../render/compositor.js'; import { Tool } from './tool.js'; // ---------------------------------------------------------------- stamps const stampCache = new Map(); /** Soft round brush tip of `diameter` px, color css, hardness 0..1. */ export function softStamp(diameter, hardness, color) { const d = Math.max(1, Math.ceil(diameter)); const key = `s|${d}|${hardness.toFixed(2)}|${color}`; let c = stampCache.get(key); if (c) return c; c = createCanvas(d, d); const ctx = c.getContext('2d'); const r = d / 2; if (hardness >= 0.999) { ctx.fillStyle = color; ctx.beginPath(); ctx.arc(r, r, r, 0, Math.PI * 2); ctx.fill(); } else { const g = ctx.createRadialGradient(r, r, 0, r, r, r); const inner = clamp(hardness, 0, 0.99); g.addColorStop(0, color); g.addColorStop(inner, color); // ease-out falloff via a couple of extra stops const transparent = colorWithAlpha(color, 0); g.addColorStop(inner + (1 - inner) * 0.5, colorWithAlpha(color, 0.35)); g.addColorStop(1, transparent); ctx.fillStyle = g; ctx.fillRect(0, 0, d, d); } cacheStamp(key, c); return c; } /** Aliased (hard pixel) round or square tip. */ export function pixelStamp(diameter, color, square = false) { const d = Math.max(1, Math.round(diameter)); const key = `p|${d}|${square}|${color}`; let c = stampCache.get(key); if (c) return c; c = createCanvas(d, d); const ctx = c.getContext('2d'); ctx.fillStyle = color; if (square || d <= 2) { ctx.fillRect(0, 0, d, d); } else { const r = d / 2; for (let y = 0; y < d; y++) { for (let x = 0; x < d; x++) { const dx = x + 0.5 - r, dy = y + 0.5 - r; if (dx * dx + dy * dy <= r * r) ctx.fillRect(x, y, 1, 1); } } } cacheStamp(key, c); return c; } function cacheStamp(key, c) { if (stampCache.size > 48) stampCache.delete(stampCache.keys().next().value); stampCache.set(key, c); } function colorWithAlpha(css, a) { const m = css.match(/rgba?\(([^)]+)\)/); if (m) { const [r, g, b] = m[1].split(',').map((s) => parseFloat(s)); return `rgba(${r},${g},${b},${a})`; } return css; } // ---------------------------------------------------------------- live stroke export class LiveStroke { /** * @param doc document * @param target {layer, key} * @param opts {opacity, composite, label} */ constructor(doc, target, { opacity = 1, composite = 'source-over', label = 'Paint' } = {}) { this.doc = doc; this.target = target; this.label = label; this.buffer = createCanvas(doc.width, doc.height); this.ctx = this.buffer.getContext('2d'); this.dirty = null; this.edit = new PixelEdit(doc, target.layer, target.key); doc.stroke = { buffer: this.buffer, opacity, composite, layer: target.layer, key: target.key }; } set opacity(v) { this.doc.stroke.opacity = v; } addDirty(r) { this.dirty = Rect.union(this.dirty, r); } clearBuffer() { this.ctx.clearRect(0, 0, this.buffer.width, this.buffer.height); this.dirty = null; } update() { this.doc.markDirty(); } commit() { const doc = this.doc; const stroke = doc.stroke; doc.stroke = null; if (!this.dirty) { doc.markDirty(); return null; } const { layer, key } = this.target; applyStroke(layer[key].getContext('2d'), stroke, doc.selection); return this.edit.commit(this.label, this.dirty); } cancel() { this.doc.stroke = null; this.doc.markDirty(); } } // ---------------------------------------------------------------- dab spacing /** Emits evenly spaced dabs along a polyline, interpolating pressure. */ export class Dabber { constructor(spacingFn) { this.spacingFn = spacingFn; // pressure -> spacing in px this.last = null; this.carry = 0; // (negative) distance already covered since the last dab } start(p, emit) { this.last = p; this.carry = 0; emit(p); } to(p, emit) { const a = this.last; if (!a) return this.start(p, emit); const dx = p.x - a.x, dy = p.y - a.y; const dist = Math.hypot(dx, dy); let t = this.carry; let spacing = Math.max(0.5, this.spacingFn(a.pressure)); if (dist === 0) return; while (t + spacing <= dist) { t += spacing; const k = t / dist; const pr = a.pressure + (p.pressure - a.pressure) * k; emit({ x: a.x + dx * k, y: a.y + dy * k, pressure: pr }); spacing = Math.max(0.5, this.spacingFn(pr)); } // remaining distance carried to next segment this.carry = -(dist - t); this.last = p; } } /** Top-left pixel of a d×d hard tip centred on the pixel containing p (odd d) or nearest corner (even d). */ function pixelOrigin(p, d) { if (d % 2) return [Math.floor(p.x) - (d - 1) / 2, Math.floor(p.y) - (d - 1) / 2]; return [Math.round(p.x) - d / 2, Math.round(p.y) - d / 2]; } export function pointerPressure(e) { if (e.pointerType === 'mouse' || !e.pressure) return 1; return clamp(e.pressure, 0.05, 1); } // ---------------------------------------------------------------- symmetry export const SYMMETRY_FIELD = { key: 'symmetry', label: 'Mirror', type: 'select', default: 'off', title: 'Symmetry painting around the canvas center', options: [ { value: 'off', label: 'Off' }, { value: 'x', label: 'Left ↔ Right' }, { value: 'y', label: 'Top ↕ Bottom' }, { value: 'xy', label: '4-way' }, { value: 'r6', label: 'Radial ×6' }, { value: 'r8', label: 'Radial ×8' }, ], }; /** All points a dab at p paints with the given symmetry mode (p itself first). */ export function mirrorPoints(p, mode, w, h) { if (!mode || mode === 'off') return [p]; const cx = w / 2, cy = h / 2; const mx = { ...p, x: 2 * cx - p.x }, my = { ...p, y: 2 * cy - p.y }; if (mode === 'x') return [p, mx]; if (mode === 'y') return [p, my]; if (mode === 'xy') return [p, mx, my, { ...p, x: 2 * cx - p.x, y: 2 * cy - p.y }]; const n = Number(mode.slice(1)) || 6; const dx = p.x - cx, dy = p.y - cy; const out = [p]; for (let i = 1; i < n; i++) { const a = (i * 2 * Math.PI) / n, c = Math.cos(a), s = Math.sin(a); out.push({ ...p, x: cx + dx * c - dy * s, y: cy + dx * s + dy * c }); } return out; } /** Faint dashed symmetry axes over the view. */ export function drawSymmetryAxes(ctx, view, doc, mode) { if (!mode || mode === 'off') return; const c = view.docToScreen({ x: doc.width / 2, y: doc.height / 2 }, doc); const R = Math.hypot(view.width, view.height); const angles = mode === 'x' ? [Math.PI / 2] : mode === 'y' ? [0] : mode === 'xy' ? [0, Math.PI / 2] : Array.from({ length: Number(mode.slice(1)) || 6 }, (_, i) => -Math.PI / 2 + (i * 2 * Math.PI) / (Number(mode.slice(1)) || 6)); ctx.save(); ctx.setLineDash([6, 5]); ctx.lineWidth = 1; ctx.strokeStyle = 'rgba(255, 47, 208, 0.65)'; ctx.beginPath(); for (const a of angles) { const radial = mode.startsWith('r'); ctx.moveTo(radial ? c.x : c.x - Math.cos(a) * R, radial ? c.y : c.y - Math.sin(a) * R); ctx.lineTo(c.x + Math.cos(a) * R, c.y + Math.sin(a) * R); } ctx.stroke(); ctx.restore(); } // ---------------------------------------------------------------- tools const BRUSH_SCHEMA = [ { key: 'size', label: 'Size', type: 'range', min: 1, max: 500, default: 20, unit: 'px', scale: 'log' }, { key: 'hardness', label: 'Hardness', type: 'range', min: 0, max: 100, default: 80, unit: '%' }, { key: 'opacity', label: 'Opacity', type: 'range', min: 1, max: 100, default: 100, unit: '%' }, { key: 'flow', label: 'Flow', type: 'range', min: 1, max: 100, default: 100, unit: '%' }, SYMMETRY_FIELD, { key: 'smoothing', label: 'Smoothing', type: 'range', min: 0, max: 95, default: 0, unit: '%', more: true }, { key: 'spacing', label: 'Spacing', type: 'range', min: 1, max: 200, default: 12, unit: '%', more: true }, { key: 'pressureSize', label: 'Pressure → size', type: 'checkbox', default: true, more: true }, { key: 'pressureOpacity', label: 'Pressure → flow', type: 'checkbox', default: false, more: true }, ]; export class BrushTool extends Tool { static id = 'brush'; static label = 'Brush'; static icon = 'brush'; static shortcut = 'B'; static schema = [ ...BRUSH_SCHEMA, { key: 'mode', label: 'Mode', type: 'select', default: 'normal', options: 'blend' }, ]; get cursor() { return 'none'; } cursorRadius() { return this.options.size / 2; } get hint() { return 'Shift+click: straight line · [ ] size · Alt: pick color'; } /** Paint one dab plus its mirror images. */ paintAt(p) { const pts = mirrorPoints(p, this.options.symmetry, this.doc.width, this.doc.height); for (let i = 0; i < pts.length; i++) { this.mirrorIndex = i; this.dab(pts[i]); } this.mirrorIndex = 0; } drawOverlay(ctx, view, doc) { drawSymmetryAxes(ctx, view, doc, this.options.symmetry); } /** Color the brush paints with (grayscale on masks). */ paintColor() { const target = this.doc.editTarget; const c = this.app.colors.fg; return (target?.key === 'mask' ? c.toGray() : c).clone(); } strokeOptions(target) { const layer = target.layer; let composite = blendOp(this.options.mode || 'normal'); if (layer.alphaLock && target.key === 'canvas') composite = 'source-atop'; const color = this.paintColor(); const opacity = (this.options.opacity / 100) * color.a; color.a = 1; return { composite, opacity, color: color.toCSS() }; } /** Draw one dab into the stroke buffer. */ dab(p) { const o = this.options; const size = Math.max(0.5, o.size * (o.pressureSize ? p.pressure : 1)); const flow = (o.flow / 100) * (o.pressureOpacity ? p.pressure : 1); const ctx = this.stroke.ctx; const stamp = softStamp(o.size, o.hardness / 100, this.color); ctx.globalAlpha = flow; ctx.drawImage(stamp, p.x - size / 2, p.y - size / 2, size, size); this.stroke.addDirty({ x: p.x - size / 2, y: p.y - size / 2, w: size, h: size }); } spacing(pressure) { const o = this.options; const size = Math.max(1, o.size * (o.pressureSize ? pressure : 1)); return Math.max(0.5, (size * o.spacing) / 100); } /** Paints with the foreground color (Alt picks a color, use is remembered). */ get usesColor() { return true; } onPointerDown(e, p) { if (e.altKey && this.usesColor) { this.app.pickColorAt(p, false); return; } const target = this.requireEditable(); if (!target) return; this.beginStroke?.(target, e); const so = this.strokeOptions(target); this.color = so.color; if (this.usesColor && target.key === 'canvas') this.app.noteColorUsed(this.app.colors.fg); this.stroke = new LiveStroke(this.doc, target, { opacity: so.opacity, composite: so.composite, label: so.label || this.label }); this.dabber = new Dabber((pr) => this.spacing(pr)); const pt = { x: p.x, y: p.y, pressure: pointerPressure(e) }; this.smoothed = { ...pt }; if (e.shiftKey && this.lastPoint) { this.dabber.start(this.lastPoint, (d) => this.paintAt(d)); this.dabber.to(pt, (d) => this.paintAt(d)); } else { this.dabber.start(pt, (d) => this.paintAt(d)); } this.stroke.update(); } onPointerMove(e, p) { if (!this.stroke) return; const events = e.getCoalescedEvents ? e.getCoalescedEvents() : []; const pts = events.length ? events.map((ev) => ({ ...this.app.eventToDoc(ev), pressure: pointerPressure(ev) })) : [{ x: p.x, y: p.y, pressure: pointerPressure(e) }]; const k = 1 - this.options.smoothing / 100; for (const pt of pts) { const s = this.smoothed; s.x += (pt.x - s.x) * k; s.y += (pt.y - s.y) * k; s.pressure = pt.pressure; this.dabber.to({ ...s }, (d) => this.paintAt(d)); } this.stroke.update(); } onPointerUp(e, p) { if (!this.stroke) return; // finish the smoothing tail so the stroke reaches the pointer if (this.options.smoothing > 0) this.dabber.to({ x: p.x, y: p.y, pressure: this.smoothed.pressure }, (d) => this.paintAt(d)); this.lastPoint = { x: p.x, y: p.y, pressure: 1 }; this.stroke.commit(); this.stroke = null; } cancel() { this.stroke?.cancel(); this.stroke = null; } onKeyDown(e) { if (e.key === '[' || e.key === ']') { const s = this.options.size; const step = s < 10 ? 1 : s < 50 ? 5 : s < 200 ? 10 : 25; this.setOption('size', clamp(s + (e.key === ']' ? step : -step), 1, 500)); this.app.ui.toolOptions.refresh(); return true; } return false; } } export class PencilTool extends BrushTool { static id = 'pencil'; static label = 'Pencil'; static icon = 'pencil'; static shortcut = 'N'; static schema = [ { key: 'size', label: 'Size', type: 'range', min: 1, max: 100, default: 1, unit: 'px' }, { key: 'opacity', label: 'Opacity', type: 'range', min: 1, max: 100, default: 100, unit: '%' }, { key: 'square', label: 'Square tip', type: 'checkbox', default: false }, { key: 'mode', label: 'Mode', type: 'select', default: 'normal', options: 'blend' }, SYMMETRY_FIELD, ]; get cursor() { return this.options.size <= 3 ? 'crosshair' : 'none'; } cursorRadius() { return this.options.size > 3 ? this.options.size / 2 : 0; } spacing() { return Math.max(0.5, Math.min(1, this.options.size / 3)); } dab(p) { const d = Math.round(this.options.size); const [x, y] = pixelOrigin(p, d); const key = `${x},${y}`; const i = this.mirrorIndex || 0; if (key === this._lastKeys[i]) return; this._lastKeys[i] = key; const ctx = this.stroke.ctx; ctx.globalAlpha = 1; ctx.drawImage(pixelStamp(d, this.color, this.options.square), x, y); this.stroke.addDirty({ x, y, w: d, h: d }); } onPointerDown(e, p) { this._lastKeys = []; this.options.pressureSize = false; this.options.smoothing = 0; super.onPointerDown(e, p); } } export class EraserTool extends BrushTool { static id = 'eraser'; static label = 'Eraser'; static icon = 'eraser'; static shortcut = 'E'; static schema = [ ...BRUSH_SCHEMA, { key: 'pixel', label: 'Hard pixels', type: 'checkbox', default: false }, ]; get hint() { return 'On locked transparency, paints the background color · Shift+click: line'; } get usesColor() { return false; } strokeOptions(target) { const layer = target.layer; if (target.key === 'mask') { return { composite: 'source-over', opacity: this.options.opacity / 100, color: 'rgba(0,0,0,1)' }; } if (layer.alphaLock) { const bg = this.app.colors.bg.clone(); bg.a = 1; return { composite: 'source-atop', opacity: this.options.opacity / 100, color: bg.toCSS() }; } return { composite: 'destination-out', opacity: this.options.opacity / 100, color: 'rgba(0,0,0,1)' }; } dab(p) { if (!this.options.pixel) return super.dab(p); const d = Math.max(1, Math.round(this.options.size * (this.options.pressureSize ? p.pressure : 1))); const [x, y] = pixelOrigin(p, d); this.stroke.ctx.globalAlpha = 1; this.stroke.ctx.drawImage(pixelStamp(d, this.color, false), x, y); this.stroke.addDirty({ x, y, w: d, h: d }); } }