Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
perf(webv2): make stroke repaint proportional to what changed
joshistoast49e2ebf746ad
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex 178dd52229..cb2355f4c1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -3742,15 +3742,16 @@ describe('engine-owned history: undo/redo guarded during an active gesture', ()// (The live session itself may draw, so snapshot the put count after it opens.)overlay.fire('pointerdown', pointerAt(50, 50));overlay.fire('pointermove', pointerAt(60, 60));- const putsMidGesture = putImageDataCalls(surfaces).length;+ const putsMidGesture = putImageDataCalls(surfaces);- // Mid-gesture undo/redo must be no-ops: no history pop and no putImageData.+ // Mid-gesture undo/redo must be no-ops: no history pop, and not a single+ // additional putImageData. Comparing the whole log — rather than just its+ // length, or scanning it for the first stroke's snapshot — keeps this honest+ // whether or not the live session reuses one "before" snapshot across frames.engine.history.undo();engine.history.redo();expect(engine.stores.canUndo.get()).toBe(true);- expect(putImageDataCalls(surfaces).length).toBe(putsMidGesture);- // In particular, the first stroke's before pixels were never injected.- expect(putImageDataCalls(surfaces).some((call) => call.image === strokes[0]!.beforeImageData)).toBe(false);+ expect(putImageDataCalls(surfaces)).toEqual(putsMidGesture);// End the gesture; now undo works and writes the newest stroke's before pixels.overlay.fire('pointerup', pointerAt(60, 60, { buttons: 0 }));diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.tsindex ed281a8671..5ae536cf31 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/raster.testStub.ts@@ -100,6 +100,11 @@ const createStubCtx = (callLog: RasterCallLogEntry[]): OffscreenCanvasRenderingCaddColorStop: (...stopArgs: unknown[]) => log('addColorStop', stopArgs),} as unknown as CanvasGradient;},+ createImageData: (...args: unknown[]) => {+ const [width, height] = args as [number, number];+ log('createImageData', [width, height]);+ return createStubImageData(width, height);+ },drawImage: (...args: unknown[]) => log('drawImage', args),ellipse: (...args: unknown[]) => log('ellipse', args),fill: (...args: unknown[]) => log('fill', args),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.browser.test.tsnew file mode 100644index 0000000000..40d8f9bdc4--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.browser.test.ts@@ -0,0 +1,135 @@+import type { ToolContext } from '@workbench/canvas-engine/tools/tool';+import type { PointerInput, Rect } from '@workbench/canvas-engine/types';++import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';+import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';+import { createStrokeSession } from '@workbench/canvas-engine/tools/strokeSession';+import { describe, expect, it, vi } from 'vitest';++const pointer = (x: number, y: number): PointerInput => ({+ buttons: 1,+ documentPoint: { x, y },+ modifiers: { alt: false, ctrl: false, meta: false, shift: false },+ pointerType: 'mouse',+ pressure: 0.5,+ screenPoint: { x, y },+ timeStamp: 0,+});++/**+ * Paints `path` through a session, delivering it in batches of `batchSize`, and+ * returns the committed pixels plus the rect they cover.+ */+const paint = (+ path: PointerInput[],+ batchSize: number,+ opts: { opacity: number; size: number; thinning: number }+): { pixels: Uint8ClampedArray; rect: Rect } => {+ const backend = createDomRasterBackend();+ const layers = createLayerCacheStore(backend);+ layers.getOrCreate('L', 0, 0);+ const ctx = {+ backend,+ createPath2D: (d?: string) => new Path2D(d),+ emitStrokeCommitted: vi.fn(),+ invalidate: vi.fn(),+ layers,+ notifyLayerPainted: vi.fn(),+ } as unknown as ToolContext;+ const session = createStrokeSession({+ color: '#3b82f6',+ composite: 'source-over',+ ctx,+ layerId: 'L',+ opacity: opts.opacity,+ size: opts.size,+ thinning: opts.thinning,+ tool: 'brush',+ });+ for (let i = 0; i < path.length; i += batchSize) {+ session.addPoints(path.slice(i, i + batchSize));+ }+ const event = session.commit()!;+ return { pixels: event.afterImageData.data, rect: event.dirtyRect };+};++/**+ * The largest per-channel difference attributable to premultiplied-alpha+ * rounding. Structural errors (a gap, a seam, a double-composite) are one to two+ * orders of magnitude above this.+ */+const ROUNDING_TOLERANCE = 6;++const sweep = (): PointerInput[] => {+ const points: PointerInput[] = [];+ for (let i = 0; i < 240; i++) {+ points.push(pointer(200 + i * 6 + Math.sin(i / 9) * 40, 400 + Math.cos(i / 7) * 160));+ }+ return points;+};++describe('incremental compositing produces the same coverage as recompositing everything', () => {+ // The session restores and composites only the band where the outline moved,+ // and grows its "before" snapshot from the strips the region gains. If either+ // bound were too tight the stroke would come out with gaps, seams or doubled+ // opacity.+ //+ // The assertion is about COVERAGE, not bit-equality. Whether a given edge+ // pixel's antialiasing was laid down on this frame or three frames ago can+ // shift it by a subpixel, so a handful of boundary pixels legitimately differ+ // from a single-batch paint. What must not differ is the interior: any gap,+ // seam or double-composite shows up as an opaque pixel disagreeing by far more+ // than a rounding step, which is what these bounds catch.+ //+ // Calibrated by deliberately shrinking the band: 10px still passes (the vertex+ // diff carries that much natural slack at these sample rates), 30px fails all+ // four cases.+ const cases: { batchSize: number; label: string; opacity: number; size: number; thinning: number }[] = [+ { batchSize: 1, label: 'one sample per batch, opaque', opacity: 1, size: 220, thinning: 0 },+ { batchSize: 1, label: 'one sample per batch, semi-transparent', opacity: 0.4, size: 220, thinning: 0 },+ { batchSize: 3, label: 'coalesced batches with pressure thinning', opacity: 0.75, size: 400, thinning: 0.5 },+ { batchSize: 7, label: 'large brush, coarse batches', opacity: 1, size: 900, thinning: 0 },+ ];++ it.each(cases)('$label', ({ batchSize, opacity, size, thinning }) => {+ const path = sweep();+ const incremental = paint(path, batchSize, { opacity, size, thinning });+ const wholesale = paint(path, path.length, { opacity, size, thinning });++ expect(incremental.rect).toEqual(wholesale.rect);+ expect(incremental.pixels.length).toBe(wholesale.pixels.length);++ // Interior = a pixel both paints agree is essentially opaque. A gap or a+ // double-composite lands here; antialiasing never does.+ let interiorDiffering = 0;+ let interiorWorst = 0;+ let edgeDiffering = 0;+ for (let i = 0; i < incremental.pixels.length; i += 4) {+ const alphaA = incremental.pixels[i + 3]!;+ const alphaB = wholesale.pixels[i + 3]!;+ let delta = 0;+ for (let channel = 0; channel < 4; channel++) {+ delta = Math.max(delta, Math.abs(incremental.pixels[i + channel]! - wholesale.pixels[i + channel]!));+ }+ if (delta === 0) {+ continue;+ }+ if (alphaA > 250 && alphaB > 250) {+ interiorDiffering++;+ interiorWorst = Math.max(interiorWorst, delta);+ } else {+ edgeDiffering++;+ }+ }+ const total = incremental.pixels.length / 4;+ // Interior pixels may drift by a rounding step — compositing at an opacity+ // rounds premultiplied channels, and which frame did it changes nothing+ // else. What this rules out is structural error, which is nowhere near this+ // scale: an unpainted gap reads as a 255 difference and a double-composite+ // at opacity 0.4 as ~100.+ expect(interiorWorst).toBeLessThanOrEqual(ROUNDING_TOLERANCE);+ expect(interiorDiffering / total).toBeLessThan(0.001);+ // The antialiased boundary may land a subpixel differently, but only there.+ expect(edgeDiffering / total).toBeLessThan(0.005);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.tsindex bc0dc700bb..c041ee7c4e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.ts@@ -359,3 +359,79 @@ describe('strokeSession: cache version bump (live adjusted-surface invalidation)expect(entry.version).toBeGreaterThan(vBeforeCancel);});});++describe('incremental "before" snapshot', () => {+ const makeSession = (size: number) => {+ const { backend } = createCapturingBackend();+ const layers = createLayerCacheStore(backend);+ layers.getOrCreate('L', 0, 0);+ const ctx = {+ backend,+ createPath2D: (d?: string) => ({ d }) as unknown as Path2D,+ emitStrokeCommitted: vi.fn(),+ invalidate: vi.fn(),+ layers,+ notifyLayerPainted: vi.fn(),+ } as unknown as ToolContext;+ const session = createStrokeSession({+ color: '#ff0000',+ composite: 'source-over',+ ctx,+ layerId: 'L',+ opacity: 1,+ size,+ thinning: 0,+ tool: 'brush',+ });+ return { layers, session };+ };++ /** A long rightward drag, one sample per batch. */+ const drag = (session: ReturnType<typeof makeSession>['session'], to: number, step: number): void => {+ for (let x = 0; x <= to; x += step) {+ session.addPoints([pointer(x, 0)]);+ }+ };++ const surfaceOf = (layers: ReturnType<typeof createLayerCacheStore>) =>+ layers.get('L')!.surface as unknown as StubRasterSurface;++ it('reads only the strips the region gains, never the whole accumulated region', () => {+ const { layers, session } = makeSession(100);+ drag(session, 3000, 50);+ const region = layers.get('L')!.rect;+ // `growToRect` re-reads the surface when it reallocates (args are its own+ // full extent from the origin); the session's own snapshot reads are the+ // strips, and none of them may span the accumulated width.+ const stripReads = surfaceOf(layers)+ .callLog.filter((entry) => entry.op === 'getImageData')+ .filter((entry) => Number(entry.args[0]) !== 0 || Number(entry.args[1]) !== 0);+ expect(region.width).toBeGreaterThan(3000);+ expect(stripReads.length).toBeGreaterThan(0);+ for (const read of stripReads) {+ expect(Number(read.args[2])).toBeLessThan(region.width / 2);+ }+ });++ it('re-snapshots only when the region actually grows, not on every batch', () => {+ const { layers, session } = makeSession(100);+ // Many batches inside one chunk: the region never changes, so the retained+ // snapshot is reused and nothing is read back at all.+ session.addPoints([pointer(0, 0)]);+ const baseline = surfaceOf(layers).callLog.filter((e) => e.op === 'getImageData').length;+ for (let i = 0; i < 20; i++) {+ session.addPoints([pointer(1, 1)]);+ }+ const after = surfaceOf(layers).callLog.filter((e) => e.op === 'getImageData').length;+ expect(after).toBe(baseline);+ });++ it('reallocates less often for a wide brush than a fixed 64px grid would', () => {+ // The growth grid scales with the brush, so a 1200px brush crossing 4000px+ // of travel reallocates on a ~300px pitch rather than every 64px.+ const { layers, session } = makeSession(1200);+ drag(session, 4000, 100);+ const resizes = surfaceOf(layers).callLog.filter((entry) => entry.op === 'resize').length;+ expect(resizes).toBeLessThan(4000 / 200);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.tsindex 5b87c62318..8e76fa53f5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts@@ -14,15 +14,24 @@* pixels"). The eraser is refused entirely on a transparency-locked layer (it* would alter alpha), handled by the tool before a session is created.*- * ## Per-frame restore/recapture+ * ## Per-frame restore/recomposite** The cache is the live preview, so it must show `before ∪ stroke@opacity` each* frame. To recomposite without compounding opacity, every frame first restores- * the previously-painted region from the captured "before" pixels, then- * recaptures the pristine "before" for the (monotonically growing) dirty region,- * then composites the whole accumulated stroke once. This keeps `beforeImageData`- * exactly equal to the pre-stroke pixels over the final dirty rect — which is- * what commit hands to history — and makes cancel a single `putImageData`.+ * the painted region from the captured "before" pixels, then composites the+ * whole accumulated stroke once. This keeps `beforeImageData` exactly equal to+ * the pre-stroke pixels over the final dirty rect — which is what commit hands+ * to history — and makes cancel a single `putImageData`.+ *+ * The "before" snapshot is EXTENDED rather than recaptured (see+ * {@link extendBefore}). Re-reading the whole region every frame was by far the+ * most expensive thing this module did — a full-region `getImageData` costs+ * roughly ten times the rest of the frame put together, and it grows with the+ * area painted so far, which is exactly why covering a large area with a big+ * brush degraded the longer you painted. Since the stroke is never composited+ * outside the accumulated rect, the pixels the region gains are still pristine+ * and can simply be read as strips and stitched onto the snapshot we already+ * hold, leaving per-frame readback proportional to new area rather than total.** Everything flows through the {@link RasterSurface} `ctx` seam, so this runs* unchanged on the node test stub. Zero React, zero dispatch on the move path.@@ -31,10 +40,10 @@import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';import type { RasterSurface } from '@workbench/canvas-engine/render/raster';-import type { PlacedSurface, PointerInput, Rect } from '@workbench/canvas-engine/types';+import type { PlacedSurface, PointerInput, Rect, Vec2 } from '@workbench/canvas-engine/types';import { strokeToPath, type StrokeSamplePoint } from '@workbench/canvas-engine/freehand';-import { intersect, isEmpty, roundOut, union } from '@workbench/canvas-engine/math/rect';+import { expand, intersect, isEmpty, roundOut, union } from '@workbench/canvas-engine/math/rect';import type { StrokeCommittedEvent, ToolContext } from './tool';@@ -109,15 +118,177 @@ const toSample = (input: PointerInput): StrokeSamplePoint => ({*/const GROWTH_CHUNK = 64;-/** Rounds a rect OUTWARD to the {@link GROWTH_CHUNK} grid (integer, chunk-aligned). */-const padToChunk = (r: Rect): Rect => {- const x = Math.floor(r.x / GROWTH_CHUNK) * GROWTH_CHUNK;- const y = Math.floor(r.y / GROWTH_CHUNK) * GROWTH_CHUNK;- const right = Math.ceil((r.x + r.width) / GROWTH_CHUNK) * GROWTH_CHUNK;- const bottom = Math.ceil((r.y + r.height) / GROWTH_CHUNK) * GROWTH_CHUNK;+/**+ * Upper bound on the growth chunk. Reallocating the cache surface costs roughly+ * the same as a full-region readback — it is dominated by re-allocating the+ * backing canvas, not by preserving the pixels — so a wide brush wants a coarse+ * grid to cross fewer boundaries.+ */+const MAX_GROWTH_CHUNK = 512;++/**+ * Fraction of the brush diameter used as the growth chunk, above the+ * {@link GROWTH_CHUNK} floor.+ *+ * Scaling with the brush keeps the padding a constant FRACTION of the stroke+ * rather than a constant number of pixels. A fixed 64px grid means a 1200px+ * brush reallocates every 64px of travel, and each reallocation costs about as+ * much as a whole frame; scaled, it reallocates ~5× less often for the same+ * relative overhead. Small brushes keep the fine grid, so their history patches+ * (sized from this padded rect) stay small.+ */+const GROWTH_CHUNK_RATIO = 0.25;++/** The growth-grid pitch for a stroke of diameter `size`. */+const growthChunk = (size: number): number =>+ Math.min(+ MAX_GROWTH_CHUNK,+ Math.max(GROWTH_CHUNK, Math.round((size * GROWTH_CHUNK_RATIO) / GROWTH_CHUNK) * GROWTH_CHUNK)+ );++/** Rounds a rect OUTWARD to the growth grid for `chunk` (integer, chunk-aligned). */+const padToChunk = (r: Rect, chunk: number): Rect => {+ const x = Math.floor(r.x / chunk) * chunk;+ const y = Math.floor(r.y / chunk) * chunk;+ const right = Math.ceil((r.x + r.width) / chunk) * chunk;+ const bottom = Math.ceil((r.y + r.height) / chunk) * chunk;return { height: bottom - y, width: right - x, x, y };};+/** The 2D context flavour a {@link RasterSurface} exposes. */+type SurfaceContext = RasterSurface['ctx'];++/**+ * Extra slack (document units) around the changed geometry, covering the+ * antialiased edge and the outward rounding of the bounds themselves.+ */+const CHANGE_MARGIN = 2;++/**+ * Bounds of the vertices where two outline rings disagree, or `null` when they+ * are identical.+ *+ * This decides how little of the cache a frame has to rewrite, and it is+ * answered from the geometry itself rather than inferred from the input.+ * Bounding it by "a brush radius around the newest samples" is the intuitive+ * approach and it is wrong: the ring is+ * `left ++ endCap ++ reverse(right) ++ startCap`, so extending the stroke+ * appends to `left`, rewrites `endCap`, and — because the right side is+ * REVERSED — shifts the index of every vertex after it. Comparing the rings+ * directly costs one linear scan and assumes nothing about how far a new sample+ * can reach.+ *+ * The scan takes the longest common prefix and the longest common suffix; what+ * lies between is everything that moved, appeared or vanished. One vertex of+ * slack is added on each side, because a vertex is the control point of the+ * quadratic spanning its two neighbouring edge midpoints, so its influence on+ * the rendered curve reaches one vertex either way.+ */+const changedVertexBounds = (previous: readonly Vec2[], current: readonly Vec2[]): Rect | null => {+ const shortest = Math.min(previous.length, current.length);+ let head = 0;+ while (head < shortest && previous[head]!.x === current[head]!.x && previous[head]!.y === current[head]!.y) {+ head++;+ }+ let tail = 0;+ while (+ tail < shortest - head &&+ previous[previous.length - 1 - tail]!.x === current[current.length - 1 - tail]!.x &&+ previous[previous.length - 1 - tail]!.y === current[current.length - 1 - tail]!.y+ ) {+ tail++;+ }+ const from = Math.max(0, head - 1);+ let minX = Infinity,+ minY = Infinity,+ maxX = -Infinity,+ maxY = -Infinity;+ const cover = (ring: readonly Vec2[]): void => {+ for (let i = from; i < ring.length && i <= ring.length - tail; i++) {+ const p = ring[i]!;+ minX = Math.min(minX, p.x);+ minY = Math.min(minY, p.y);+ maxX = Math.max(maxX, p.x);+ maxY = Math.max(maxY, p.y);+ }+ };+ cover(previous);+ cover(current);+ if (minX > maxX) {+ return null;+ }+ return { height: maxY - minY, width: maxX - minX, x: minX, y: minY };+};++/** Whether two rects are identical. */+const sameRect = (a: Rect, b: Rect): boolean =>+ a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;++/**+ * Grows the pristine "before" snapshot from `previous` to cover `region`,+ * reading ONLY the newly-added area from the surface.+ *+ * The stroke has never been composited outside `previous` — every frame+ * composites within the accumulated rect — so the surface still holds pristine+ * pixels there and they can be read directly. Carrying the existing snapshot+ * forward by copy, instead of re-reading the whole region, is what keeps the+ * per-frame cost proportional to new area rather than total painted area.+ */+const extendBefore = (+ surfaceCtx: SurfaceContext,+ existing: ImageData | null,+ previous: Rect | null,+ region: Rect,+ originX: number,+ originY: number+): ImageData => {+ if (!existing || !previous || isEmpty(previous)) {+ return surfaceCtx.getImageData(region.x - originX, region.y - originY, region.width, region.height);+ }+ const grown = surfaceCtx.createImageData(region.width, region.height);++ /** Blits `source` (covering `rect`) into `grown` at its place in `region`. */+ const blit = (source: ImageData, rect: Rect): void => {+ const offsetX = rect.x - region.x;+ const offsetY = rect.y - region.y;+ const rowBytes = rect.width * 4;+ for (let row = 0; row < rect.height; row++) {+ const from = row * rowBytes;+ grown.data.set(source.data.subarray(from, from + rowBytes), ((row + offsetY) * region.width + offsetX) * 4);+ }+ };++ // Carry the pixels we already hold forward untouched...+ blit(existing, previous);+ // ...and read only the frame the growth exposed. The stroke has never been+ // composited out here, so the surface still holds pristine pixels.+ for (const strip of surroundingStrips(previous, region)) {+ blit(surfaceCtx.getImageData(strip.x - originX, strip.y - originY, strip.width, strip.height), strip);+ }+ return grown;+};++/**+ * Decomposes `outer` minus `inner` into up to four disjoint rects (top, bottom,+ * left, right), assuming `inner` is contained in `outer`.+ */+const surroundingStrips = (inner: Rect, outer: Rect): Rect[] => {+ const innerBottom = inner.y + inner.height;+ const outerBottom = outer.y + outer.height;+ const candidates: Rect[] = [+ { height: inner.y - outer.y, width: outer.width, x: outer.x, y: outer.y },+ { height: outerBottom - innerBottom, width: outer.width, x: outer.x, y: innerBottom },+ { height: inner.height, width: inner.x - outer.x, x: outer.x, y: inner.y },+ {+ height: inner.height,+ width: outer.x + outer.width - (inner.x + inner.width),+ x: inner.x + inner.width,+ y: inner.y,+ },+ ];+ return candidates.filter((r) => !isEmpty(r));+};+/** Creates a paint session that grows the target layer's content-sized cache. */export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession => {const { clipMask, clipRect, color, composite, createdLayer, ctx, layerId, opacity, size, thinning, tool } = config;@@ -132,6 +303,8 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession// (which only shifts the surface origin, not the layer-local geometry).let beforeImageData: ImageData | null = null;let accumRect: Rect | null = null;+ let previousPolygon: Vec2[] | null = null;+ const chunk = growthChunk(size);/** Ensures the scratch surface is at least `w`×`h`. */const ensureStroke = (w: number, h: number): RasterSurface => {@@ -147,7 +320,7 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessionif (points.length === 0) {return;}- const { bounds, path } = strokeToPath(points, { last, size, thinning }, ctx.createPath2D);+ const { bounds, path, polygon } = strokeToPath(points, { last, size, thinning }, ctx.createPath2D);let dirty: Rect | null = roundOut(bounds);// Selection clip: only the region inside the selection can ever change, so// bound the dirty/growth region to the mask extent (and skip empty results).@@ -169,7 +342,7 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession// and the reported dirty/before/after all use this same padded region so every// consumer stays coherent. When a selection clips the stroke, clamp the padded// region back to the mask so growth still never escapes the selection.- let region = padToChunk(accumRect ? roundOut(union(accumRect, dirty)) : dirty);+ let region = padToChunk(accumRect ? roundOut(union(accumRect, dirty)) : dirty, chunk);if (clipMask) {const clamped = intersect(region, clipMask.rect);if (clamped) {@@ -201,18 +374,52 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessionconst ox = entry.rect.x;const oy = entry.rect.y;- // 1. Restore the region painted last frame back to pristine "before" pixels,- // so recompositing the (larger) stroke doesn't compound its opacity.- if (accumRect && beforeImageData) {- targetCtx.putImageData(beforeImageData, accumRect.x - ox, accumRect.y - oy);+ // 1. Extend the pristine "before" snapshot over whatever the region just+ // gained, reading only the newly-exposed frame rather than re-reading+ // everything painted so far.+ const previousRect = accumRect;+ if (!beforeImageData || !previousRect || !sameRect(previousRect, region)) {+ beforeImageData = extendBefore(targetCtx, beforeImageData, previousRect, region, ox, oy);}- // 2. Recapture the pristine "before" for the grown region (in surface coords).- beforeImageData = targetCtx.getImageData(region.x - ox, region.y - oy, region.width, region.height);accumRect = region;- // 3. Render the whole accumulated stroke into the scratch surface at full+ // 2. Work out where the silhouette actually moved since the last frame, and+ // confine the rest of the frame to it. Outside this band the cache already+ // holds the correct composite and the shape has not changed, so redoing it+ // would only cost time — and rewriting the whole accumulated region every+ // frame is what made a long stroke get slower the longer it got.+ const moved = previousPolygon ? changedVertexBounds(previousPolygon, polygon) : null;+ const touched = previousRect && moved ? intersect(roundOut(expand(moved, CHANGE_MARGIN)), region) : region;+ // No intersection means the change fell outside the paintable region (a clip+ // can do that); fall back to the whole region rather than skip the frame.+ const changed = touched && !isEmpty(touched) ? touched : region;+ previousPolygon = polygon;++ // 3. Restore that band to pristine "before" pixels, so recompositing the+ // stroke over it doesn't compound its opacity. `putImageData`'s dirty-rect+ // arguments write only this window out of the full-region snapshot. On the+ // opening frame nothing has been composited yet, so there is nothing to undo.+ if (previousRect) {+ targetCtx.putImageData(+ beforeImageData,+ region.x - ox,+ region.y - oy,+ changed.x - region.x,+ changed.y - region.y,+ changed.width,+ changed.height+ );+ }++ // 4. Render the whole accumulated stroke into the scratch surface at full// alpha — one filled polygon, so no self-overlap darkening. The scratch is// region-local: translate the (layer-local) path by -region.origin.+ //+ // This stays whole-region rather than incremental: filling the complete+ // outline every frame is what guarantees the scratch holds ONE flat-alpha+ // silhouette. Accumulating it in pieces would let the antialiased edges of+ // successive batches blend into each other and leave seams inside the+ // stroke. It is also the cheap half of the frame — the readback was not.const scratch = ensureStroke(region.width, region.height);const strokeCtx = scratch.ctx;strokeCtx.setTransform(1, 0, 0, 1, -region.x, -region.y);@@ -222,7 +429,7 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessionstrokeCtx.fillStyle = color;strokeCtx.fill(path);- // 3b. Selection clip: keep only the stroke pixels inside the selection mask.+ // 4b. Selection clip: keep only the stroke pixels inside the selection mask.// The mask is a placed surface; draw it at (maskOrigin - regionOrigin) in// the scratch's region-local space.if (clipMask) {@@ -232,13 +439,14 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessionstrokeCtx.drawImage(clipMask.surface.canvas, clipMask.rect.x - region.x, clipMask.rect.y - region.y);}- // 4. Composite the scratch stroke into the cache over the region at the stroke- // opacity, using the tool's blend (brush over / eraser out). Both are in- // surface coords (region translated by the surface origin).+ // 5. Composite the scratch stroke into the cache at the stroke opacity, using+ // the tool's blend (brush over / eraser out), clipped to the band this+ // batch changed. The clip also confines the whole-canvas `drawImage` to+ // the region, which the scratch may exceed after a resize.targetCtx.save();targetCtx.setTransform(1, 0, 0, 1, 0, 0);targetCtx.beginPath();- targetCtx.rect(region.x - ox, region.y - oy, region.width, region.height);+ targetCtx.rect(changed.x - ox, changed.y - oy, changed.width, changed.height);targetCtx.clip();targetCtx.globalAlpha = opacity;targetCtx.globalCompositeOperation = composite;@@ -253,7 +461,12 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession// touch `thumbnailVersion` (only `notifyLayerPainted`/rasterize do), so// thumbnails don't churn mid-stroke.layers.publishPixels(layerId);- ctx.invalidate({ layers: [layerId] });+ // Report the region as damage so the frame repaints only these pixels+ // instead of re-resampling every doc-sized layer to screen scale — the cost+ // that grows with zoom. `region` is layer-local, which is exactly what the+ // compositor wants: it carries it to the screen through the layer's own+ // matrix, so this stays correct on a moved or scaled layer.+ ctx.invalidate({ damage: { layerId, rect: changed }, layers: [layerId] });};return {