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(canvas): render live strokes at most once per frame
Josh Corbettdd0e5905b33d
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex 8507baa6d4..9cd148ea07 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -3819,6 +3819,61 @@ describe('engine-owned history: stroke → undo → redo', () => {return { bitmapStore, commitEdit, engine, strokes, surfaces };};+ it('renders a live stroke at most once per frame, flushing the final stroke on release', () => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ class FakePath2D {+ closePath() {}+ lineTo() {}+ moveTo() {}+ quadraticCurveTo() {}+ }+ vi.stubGlobal('Path2D', FakePath2D);+ const { store } = createReactiveStore(paintDoc());+ const base = createTestStubRasterBackend();+ const surfaces: StubRasterSurface[] = [];+ const engine = createCanvasEngine({+ backend: {+ ...base,+ createSurface: (w: number, h: number): StubRasterSurface => {+ const surface = base.createSurface(w, h);+ surfaces.push(surface);+ return surface;+ },+ },+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });+ const overlay = createInputCanvas();+ engine.surface.attach(createInputCanvas().element, overlay.element);+ engine.tools.setTool('brush');+ raf.flush();+ /** Stroke silhouettes filled so far; each live render fills the accumulated outline once. */+ const strokeRenders = (): number =>+ surfaces+ .flatMap((surface) => surface.callLog)+ .filter((entry) => entry.op === 'fill' && entry.args[0] instanceof FakePath2D).length;++ overlay.fire('pointerdown', pointerAt(20, 20));+ for (let x = 22; x <= 40; x += 2) {+ overlay.fire('pointermove', pointerAt(x, 20));+ }+ expect(strokeRenders()).toBe(0);+ raf.flush();+ expect(strokeRenders()).toBe(1);+ overlay.fire('pointermove', pointerAt(50, 30));+ overlay.fire('pointermove', pointerAt(60, 30));+ overlay.fire('pointerup', pointerAt(60, 30, { buttons: 0 }));+ expect(strokeRenders()).toBe(2);+ raf.flush();+ expect(strokeRenders()).toBe(2);+ expect(engine.stores.canUndo.get()).toBe(true);+ engine.lifecycle.dispose();+ });+it('records a stroke and restores before/after pixels on undo/redo', () => {const { bitmapStore, commitEdit, engine, strokes, surfaces } = drawStroke();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex ed06a89cdb..868cd1bc0e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -981,6 +981,14 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreCinvalidate: (payload) => scheduler.invalidate(payload),layers: layerCache,notifyLayerPainted,+ // Detached engines produce no frames; render immediately rather than hold work until the next attach.+ scheduleFrame: (task) => {+ if (scheduler.isPaused) {+ task();+ return () => undefined;+ }+ return scheduler.beforeNextFrame(task);+ },requestLayerRasterization: (layerId) => scheduleLayerRasterization([layerId]),getSamInteraction: () => stores.samInteraction.get(),openTextCreate: (docPoint) => openTextCreate(docPoint),diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.test.tsindex a8eb98ae06..52519443aa 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.test.ts@@ -2,6 +2,7 @@ import type { StrokeSamplePoint } from '@workbench/canvas-engine/freehand';import type { Vec2 } from '@workbench/canvas-engine/types';import {+ createSampleDecimator,decimateSamples,MAX_SAMPLE_SPACING,outlineSmoothing,@@ -170,6 +171,27 @@ describe('decimateSamples', () => {});});+describe('createSampleDecimator', () => {+ it('matches decimateSamples for every prefix, live and completed', () => {+ const jittery: StrokeSamplePoint[] = Array.from({ length: 120 }, (_, i) => ({+ pressure: 0.3 + (i % 7) / 10,+ x: i * 0.7 + Math.sin(i) * 0.9,+ y: Math.cos(i / 3) * 6,+ }));+ const decimator = createSampleDecimator(4);+ jittery.forEach((point, index) => {+ decimator.push(point);+ const prefix = jittery.slice(0, index + 1);+ expect(decimator.samples(false)).toEqual(decimateSamples(prefix, 4, false));+ expect(decimator.samples(true)).toEqual(decimateSamples(prefix, 4, true));+ });+ });++ it('reports nothing before the first sample', () => {+ expect(createSampleDecimator(4).samples(true)).toEqual([]);+ });+});+describe('sampleSpacing', () => {it('scales with the brush but stays within its floor and ceiling', () => {expect(sampleSpacing(10)).toBe(1);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.tsindex 9219c23d68..8c9640e909 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/freehand.ts@@ -114,23 +114,47 @@ export const decimateSamples = (};/**- * Pure document-space stroke outline. Separate perfect-freehand stages keep the start gate small while using the- * real diameter for outline width.+ * Appends samples one at a time while keeping {@link decimateSamples}' output for the prefix seen so far, so a+ * growing stroke never re-scans the samples it has already gated.*/-export const strokeOutlinePolygon = (points: readonly StrokeSamplePoint[], opts: FreehandOptions): Vec2[] => {- if (points.length === 0) {+export interface SampleDecimator {+ push(point: StrokeSamplePoint): void;+ /** Exactly `decimateSamples(pushed, spacing, last)`; the returned array must not be mutated. */+ samples(last: boolean): readonly StrokeSamplePoint[];+}++export const createSampleDecimator = (spacing: number): SampleDecimator => {+ const minDistance = spacing * spacing;+ const kept: StrokeSamplePoint[] = [];+ let final: StrokeSamplePoint | null = null;+ return {+ push: (point) => {+ final = point;+ const anchor = kept[kept.length - 1];+ if (!anchor || dist2(anchor, point) >= minDistance) {+ kept.push(point);+ }+ },+ samples: (last) => (last && final && kept[kept.length - 1] !== final ? [...kept, final] : kept),+ };+};++/**+ * Document-space outline of already-decimated samples. Separate perfect-freehand stages keep the start gate small+ * while using the real diameter for outline width.+ */+export const strokeOutlineFromSamples = (samples: readonly StrokeSamplePoint[], opts: FreehandOptions): Vec2[] => {+ const first = samples[0];+ if (!first) {return [];}const last = opts.last ?? false;- const samples = decimateSamples(points, sampleSpacing(opts.size), last);// perfect-freehand gives a lone sample a pen-oriented fallback dot whose// diameter bottoms out around 2.5px. Repeating the tap makes it use the real// outline size, which matters now that brushes can be smaller than one pixel.- if (samples.length === 1) {- samples.push(samples[0]!);- }+ const input = samples.length === 1 ? [first, first] : samples;const strokePoints = getStrokePoints(- samples.map((p) => [p.x, p.y, p.pressure]),+ input.map((p) => [p.x, p.y, p.pressure]),{last,size: Math.min(opts.size, START_GATE_SIZE),@@ -147,6 +171,10 @@ export const strokeOutlinePolygon = (points: readonly StrokeSamplePoint[], opts:return outline.map(([x, y]) => ({ x, y }));};+/** Pure document-space stroke outline of raw samples, decimated for `opts.size`. */+export const strokeOutlinePolygon = (points: readonly StrokeSamplePoint[], opts: FreehandOptions): Vec2[] =>+ strokeOutlineFromSamples(decimateSamples(points, sampleSpacing(opts.size), opts.last ?? false), opts);+/** Serializes an outline polygon to an SVG path string (`M … L … Z`). */export const polygonToSvgPath = (polygon: readonly Vec2[]): string => {if (polygon.length === 0) {@@ -217,6 +245,16 @@ export const polygonBounds = (polygon: readonly Vec2[]): Rect => {return { height: maxY - minY, width: maxX - minX, x: minX, y: minY };};+/** Traces an outline polygon into a fresh path and reports its bounds. */+export const polygonToPath = (+ polygon: Vec2[],+ createPath2D: CreatePath2D+): { path: Path2D; polygon: Vec2[]; bounds: Rect } => {+ const path = createPath2D();+ traceSmoothPolygon(path, polygon);+ return { bounds: polygonBounds(polygon), path, polygon };+};+/*** Builds the smooth stroke path through an injected Path2D factory and returns enclosing polygon bounds, avoiding* duplicate outline computation.@@ -225,9 +263,4 @@ export const strokeToPath = (points: readonly StrokeSamplePoint[],opts: FreehandOptions,createPath2D: CreatePath2D-): { path: Path2D; polygon: Vec2[]; bounds: Rect } => {- const polygon = strokeOutlinePolygon(points, opts);- const path = createPath2D();- traceSmoothPolygon(path, polygon);- return { bounds: polygonBounds(polygon), path, polygon };-};+): { path: Path2D; polygon: Vec2[]; bounds: Rect } => polygonToPath(strokeOutlinePolygon(points, opts), createPath2D);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/scheduler.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/scheduler.test.tsindex d93f1dbd43..5db859eb45 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/scheduler.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/scheduler.test.ts@@ -213,6 +213,83 @@ describe('createRenderScheduler', () => {});});+describe('beforeNextFrame', () => {+ it('runs tasks first so their invalidations render in the same frame', () => {+ const raf = createFakeRaf();+ const order: string[] = [];+ const render = vi.fn<(flags: RenderFlags) => void>(() => order.push('render'));+ const scheduler = createRenderScheduler({ cancelFrame: raf.cancelFrame, render, requestFrame: raf.requestFrame });++ scheduler.beforeNextFrame(() => {+ order.push('task');+ scheduler.invalidate({ layers: ['stroke'] });+ });+ expect(raf.pendingCount()).toBe(1);+ raf.flush();++ expect(order).toEqual(['task', 'render']);+ expect([...render.mock.calls[0]![0].layers]).toEqual(['stroke']);+ expect(raf.pendingCount()).toBe(0);+ });++ it('skips the render when tasks leave nothing invalidated, and a cancelled task never runs', () => {+ const raf = createFakeRaf();+ const render = vi.fn();+ const scheduler = createRenderScheduler({ cancelFrame: raf.cancelFrame, render, requestFrame: raf.requestFrame });+ const kept = vi.fn();+ const dropped = vi.fn();++ scheduler.beforeNextFrame(kept);+ scheduler.beforeNextFrame(dropped)();+ raf.flush();++ expect(kept).toHaveBeenCalledOnce();+ expect(dropped).not.toHaveBeenCalled();+ expect(render).not.toHaveBeenCalled();+ });++ it('keeps rendering the frame after a task throws', () => {+ const raf = createFakeRaf();+ const render = vi.fn();+ const reportError = vi.fn();+ vi.stubGlobal('reportError', reportError);+ try {+ const scheduler = createRenderScheduler({ cancelFrame: raf.cancelFrame, render, requestFrame: raf.requestFrame });+ const failure = new Error('task failed');+ scheduler.beforeNextFrame(() => {+ throw failure;+ });+ const later = vi.fn(() => scheduler.invalidate({ overlay: true }));+ scheduler.beforeNextFrame(later);+ raf.flush();++ expect(reportError).toHaveBeenCalledWith(failure);+ expect(later).toHaveBeenCalledOnce();+ expect(render).toHaveBeenCalledOnce();+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it('holds tasks while paused and drops them on dispose', () => {+ const raf = createFakeRaf();+ const scheduler = createRenderScheduler({+ cancelFrame: raf.cancelFrame,+ render: vi.fn(),+ requestFrame: raf.requestFrame,+ });+ const task = vi.fn();+ scheduler.pause();+ scheduler.beforeNextFrame(task);+ expect(raf.pendingCount()).toBe(0);+ scheduler.resume();+ expect(raf.pendingCount()).toBe(1);+ scheduler.dispose();+ raf.flush();+ expect(task).not.toHaveBeenCalled();+ });+});+describe('damage coalescing', () => {const setup = () => {const raf = createFakeRaf();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/scheduler.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/scheduler.tsindex b54f883111..500739352f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/scheduler.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/scheduler.ts@@ -36,6 +36,11 @@ export interface RenderSchedulerDeps {export interface RenderScheduler {/** Merge a partial invalidation into the pending flags and schedule a frame. */invalidate(payload: InvalidatePayload): void;+ /**+ * Runs `task` at the start of the next frame, before that frame's flags are taken, so its invalidations render+ * in the same frame. Returns an idempotent cancel.+ */+ beforeNextFrame(task: () => void): () => void;/** Suspend frame scheduling (e.g. widget detach); invalidations still accumulate. */pause(): void;/** Resume scheduling; flushes any invalidations accumulated while paused. */@@ -67,28 +72,46 @@ export const createRenderScheduler = (deps: RenderSchedulerDeps): RenderScheduleconst cancelFrame = deps.cancelFrame ?? defaultCancelFrame;let pending = createEmptyFlags();+ const frameTasks = new Set<() => void>();let frameHandle: number | null = null;let paused = false;let disposed = false;const runFrame = (): void => {- frameHandle = null;if (disposed) {+ frameHandle = null;return;}- // Snapshot then reset before invoking render, so invalidations made from- // within the render callback accumulate into a fresh frame rather than- // being wiped by the post-render reset.- const flags = pending;- pending = createEmptyFlags();- deps.render(flags);+ // The handle stays set while tasks run, so their invalidations join this frame instead of requesting another.+ const tasks = [...frameTasks];+ frameTasks.clear();+ for (const task of tasks) {+ try {+ task();+ } catch (error) {+ // One failed task must not starve the frame or the tasks after it.+ globalThis.reportError?.(error);+ }+ }+ frameHandle = null;+ if (!paused && !disposed && hasPending(pending)) {+ // Snapshot then reset before invoking render, so invalidations made from+ // within the render callback accumulate into a fresh frame rather than+ // being wiped by the post-render reset.+ const flags = pending;+ pending = createEmptyFlags();+ deps.render(flags);+ }+ if (frameTasks.size > 0) {+ schedule();+ }};const schedule = (): void => {if (disposed || paused || frameHandle !== null) {return;}- if (!hasPending(pending)) {+ if (!hasPending(pending) && frameTasks.size === 0) {return;}try {@@ -138,6 +161,19 @@ export const createRenderScheduler = (deps: RenderSchedulerDeps): RenderScheduleschedule();};+ const beforeNextFrame = (task: () => void): (() => void) => {+ if (disposed) {+ return () => undefined;+ }+ // A wrapper gives repeated registrations of one function separate identities.+ const entry = (): void => task();+ frameTasks.add(entry);+ schedule();+ return () => {+ frameTasks.delete(entry);+ };+ };+const pause = (): void => {if (disposed || paused) {return;@@ -162,6 +198,7 @@ export const createRenderScheduler = (deps: RenderSchedulerDeps): RenderSchedulereturn;}disposed = true;+ frameTasks.clear();if (frameHandle !== null) {cancelFrame(frameHandle);frameHandle = null;@@ -169,6 +206,7 @@ export const createRenderScheduler = (deps: RenderSchedulerDeps): RenderSchedule};return {+ beforeNextFrame,dispose,invalidate,get isPaused() {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.tsindex bd40ebb19b..6fdc558e78 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts@@ -357,6 +357,29 @@ describe('paint tool: target resolution', () => {expect(h.beginPixelEdit).toHaveBeenCalledTimes(2);});+ it('aborts the gesture when a deferred frame render fails', () => {+ const transaction = controlTransaction();+ const h = createHarness(makeDoc([controlPaintLayer('control')], 'control'), transaction);+ const frames: (() => void)[] = [];+ h.ctx.scheduleFrame = (task) => {+ frames.push(task);+ return () => frames.splice(frames.indexOf(task), 1);+ };+ const brush = createBrushTool();+ down(brush, h.ctx, pointer(10, 10));+ move(brush, h.ctx, pointer(20, 20), [pointer(20, 20)]);+ vi.spyOn(h.layers, 'growToRect').mockImplementation(() => {+ throw new Error('frame paint failed');+ });++ expect(() => frames.splice(0).forEach((task) => task())).toThrow('frame paint failed');++ expect(transaction.cancel).toHaveBeenCalledOnce();+ up(brush, h.ctx, pointer(30, 30));+ expect(transaction.commitStroke).not.toHaveBeenCalled();+ expect(h.strokes).toHaveLength(0);+ });+it('aborts the control transaction and releases the gesture after stroke finalization fails', () => {const transaction = controlTransaction();const h = createHarness(makeDoc([controlPaintLayer('control')], 'control'), transaction);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.tsindex 6ed93b808e..5ea4762319 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts@@ -282,6 +282,8 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {ctx,layerId: target.layerId,layerTransform,+ // A deferred frame render fails outside this handler; abandon the stroke there too.+ onRenderError: () => abortSession(),opacity: target.forceOpaque ? 1 : spec.opacity(ctx),// A mask stroke is an all-or-nothing alpha stencil, so pressure must not thin it —// a partially-transparent mask would silently attenuate the denoise strength.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.tsindex f386d35534..732f560ca9 100644--- 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.ts@@ -19,7 +19,15 @@ const pointer = (x: number, y: number, pressure = 0.5): PointerInput => ({const paint = (path: PointerInput[],batchSize: number,- opts: { opacity: number; size: number; thinning: number; hardness?: number; clipMaskRect?: Rect }+ opts: {+ opacity: number;+ size: number;+ thinning: number;+ hardness?: number;+ clipMaskRect?: Rect;+ /** Batches delivered per presented frame; 1 renders every batch. */+ batchesPerFrame?: number;+ }): { pixels: Uint8ClampedArray; rect: Rect } => {const backend = createDomRasterBackend();const layers = createLayerCacheStore(backend);@@ -32,6 +40,7 @@ const paint = (return { rect: opts.clipMaskRect, surface };})(): null;+ const frames: (() => void)[] = [];const ctx = {backend,createPath2D: (d?: string) => new Path2D(d),@@ -39,6 +48,15 @@ const paint = (invalidate: vi.fn(),layers,notifyLayerPainted: vi.fn(),+ scheduleFrame: (task: () => void) => {+ frames.push(task);+ return () => {+ const index = frames.indexOf(task);+ if (index >= 0) {+ frames.splice(index, 1);+ }+ };+ },} as unknown as ToolContext;const session = createStrokeSession({clipMask,@@ -53,8 +71,12 @@ const paint = (thinning: opts.thinning,tool: 'brush',});- for (let i = 0; i < path.length; i += batchSize) {+ const batchesPerFrame = opts.batchesPerFrame ?? 1;+ for (let i = 0, batch = 1; i < path.length; i += batchSize, batch += 1) {session.addPoints(path.slice(i, i + batchSize));+ if (batch % batchesPerFrame === 0) {+ frames.splice(0).forEach((task) => task());+ }}const event = session.commit()!;return { pixels: event.afterImageData.data, rect: event.dirtyRect };@@ -82,6 +104,10 @@ const tapCoverage = (invalidate: vi.fn(),layers,notifyLayerPainted: vi.fn(),+ scheduleFrame: (task: () => void) => {+ task();+ return () => undefined;+ },} as unknown as ToolContext;const session = createStrokeSession({color: '#3b82f6',@@ -186,16 +212,31 @@ describe('incremental compositing produces the same coverage as recompositing ev// Band updates and incremental before-snapshots must preserve interior coverage. Boundary antialiasing may// differ by subpixels across batches; interior gaps or compounded opacity may not. Deliberately shrinking the// band by 30px fails all four cases.- const cases: { batchSize: number; label: string; opacity: number; size: number; thinning: number }[] = [+ const cases: {+ batchSize: number;+ batchesPerFrame?: 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,+ batchesPerFrame: 5,+ label: 'several batches coalesced into each frame',+ opacity: 0.6,+ size: 220,+ thinning: 0.5,+ },{ 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 }) => {+ it.each(cases)('$label', ({ batchSize, batchesPerFrame, opacity, size, thinning }) => {const path = sweep();- const incremental = paint(path, batchSize, { opacity, size, thinning });+ const incremental = paint(path, batchSize, { batchesPerFrame, opacity, size, thinning });const wholesale = paint(path, path.length, { opacity, size, thinning });expect(incremental.rect).toEqual(wholesale.rect);@@ -230,3 +271,63 @@ describe('incremental compositing produces the same coverage as recompositing evexpect(edgeDiffering / total).toBeLessThan(0.005);});});++describe('dense stylus trace', () => {+ // A 240 Hz pen delivers about four batches per 60 Hz frame. Timings are informational; counts are the gate.+ const trace = Array.from({ length: 4000 }, (_, i) =>+ pointer(20 + i * 0.5, 300 + 120 * Math.sin(i / 60), 0.5 + 0.3 * Math.sin(i / 15))+ );+ const BATCH = 8;++ const run = (batchesPerFrame: number): { ms: number; renders: number } => {+ const backend = createDomRasterBackend();+ const layers = createLayerCacheStore(backend);+ layers.getOrCreate('L', 0, 0);+ const frames: (() => void)[] = [];+ const invalidate = vi.fn();+ const ctx = {+ backend,+ createPath2D: (d?: string) => new Path2D(d),+ emitStrokeCommitted: vi.fn(),+ invalidate,+ layers,+ notifyLayerPainted: vi.fn(),+ scheduleFrame: (task: () => void) => {+ frames.push(task);+ return () => frames.splice(0);+ },+ } as unknown as ToolContext;+ const session = createStrokeSession({+ clipMask: null,+ color: '#3b82f6',+ composite: 'source-over',+ ctx,+ hardness: 1,+ layerId: 'L',+ opacity: 1,+ pressureOpacity: false,+ size: 20,+ thinning: 0.5,+ tool: 'brush',+ });+ const start = performance.now();+ for (let i = 0, batch = 1; i < trace.length; i += BATCH, batch += 1) {+ session.addPoints(trace.slice(i, i + BATCH));+ if (batch % batchesPerFrame === 0) {+ frames.splice(0).forEach((task) => task());+ }+ }+ session.commit();+ return { ms: Math.round((performance.now() - start) * 10) / 10, renders: invalidate.mock.calls.length };+ };++ it('renders once per frame however many batches arrive between frames', async ({ annotate }) => {+ const batches = trace.length / BATCH;+ const everyBatch = run(1);+ const perFrame = run(4);++ expect(everyBatch.renders).toBe(batches + 1);+ expect(perFrame.renders).toBe(batches / 4 + 1);+ await annotate(`dense stroke ms: every batch ${everyBatch.ms}, per frame ${perFrame.ms}`);+ });+});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 f237edbea2..3dd1776044 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@@ -632,3 +632,106 @@ describe('tap collapse', () => {expect(sessionWithDrift(40)!.dirtyRect.width).toBeGreaterThan(clean.width);});});++describe('frame-coalesced rendering', () => {+ const makeFramedSession = () => {+ const backend = createTestStubRasterBackend();+ const layers = createLayerCacheStore(backend);+ layers.getOrCreate('L', 100, 100);+ const frames: (() => void)[] = [];+ const invalidate = vi.fn();+ const onRenderError = vi.fn();+ const ctx = {+ backend,+ createPath2D: () => {+ const path = { closePath: () => {}, lineTo: () => {}, moveTo: () => {}, quadraticCurveTo: () => {} };+ return path as unknown as Path2D;+ },+ emitStrokeCommitted: vi.fn(),+ invalidate,+ layers,+ notifyLayerPainted: vi.fn(),+ scheduleFrame: (task: () => void) => {+ frames.push(task);+ return () => {+ const index = frames.indexOf(task);+ if (index >= 0) {+ frames.splice(index, 1);+ }+ };+ },+ } as unknown as ToolContext;+ const session = createStrokeSession({+ clipMask: null,+ color: '#ff0000',+ composite: 'source-over',+ ctx,+ hardness: 1,+ layerId: 'L',+ onRenderError,+ opacity: 1,+ pressureOpacity: false,+ size: 20,+ thinning: 0,+ tool: 'brush',+ });+ /** Live stroke renders so far: each one reports its damage to the scheduler. */+ const renders = (): number => invalidate.mock.calls.length;+ const presentFrame = (): void => frames.splice(0).forEach((task) => task());+ return { frames, layers, onRenderError, presentFrame, renders, session };+ };++ it('renders the accumulated stroke at most once per presented frame', () => {+ const { frames, presentFrame, renders, session } = makeFramedSession();+ for (let frame = 0; frame < 4; frame++) {+ for (let batch = 0; batch < 6; batch++) {+ const x = 10 + frame * 12 + batch * 2;+ session.addPoints([pointer(x, 10), pointer(x + 1, 11)]);+ }+ expect(frames).toHaveLength(1);+ expect(renders()).toBe(frame);+ presentFrame();+ expect(renders()).toBe(frame + 1);+ }+ });++ it('commits the final stroke synchronously and withdraws the frame still scheduled', () => {+ const { frames, renders, session } = makeFramedSession();+ session.addPoints([pointer(10, 10)]);+ session.addPoints([pointer(60, 10)]);+ expect(renders()).toBe(0);++ const event = session.commit();++ expect(renders()).toBe(1);+ expect(frames).toHaveLength(0);+ expect(event?.dirtyRect.width).toBeGreaterThan(50);+ session.addPoints([pointer(80, 10)]);+ expect(frames).toHaveLength(0);+ });++ it('cancellation removes scheduled work and leaves the cache untouched', () => {+ const { frames, layers, renders, session } = makeFramedSession();+ const version = layers.version('L');+ session.addPoints([pointer(10, 10), pointer(40, 40)]);++ session.cancel();++ expect(frames).toHaveLength(0);+ expect(renders()).toBe(0);+ expect(layers.version('L')).toBe(version);+ expect(session.commit()).toBeNull();+ });++ it('hands a failed frame render to its owner before propagating it', () => {+ const { layers, onRenderError, presentFrame, session } = makeFramedSession();+ session.addPoints([pointer(10, 10)]);+ const failure = new Error('frame paint failed');+ vi.spyOn(layers, 'growToRect').mockImplementation(() => {+ throw failure;+ });++ expect(presentFrame).toThrow(failure);+ expect(onRenderError).toHaveBeenCalledWith(failure);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.tsindex 2aabccb9ab..f68b817979 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts@@ -1,6 +1,7 @@/*** Per-gesture brush/eraser sessions accumulate samples and draw one scratch silhouette, compositing at stroke- * opacity without overlap darkening. Brush uses source-over or transparency-locked source-atop; erase uses+ * opacity without overlap darkening. Samples append immediately; the accumulated stroke renders at most once per+ * frame and commit renders the final stroke synchronously. Brush uses source-over or transparency-locked source-atop; erase uses* destination-out and is refused under transparency lock.** Each preview restores affected pristine pixels before compositing the accumulated stroke. Extend@@ -14,7 +15,14 @@ import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCacheimport type { RasterSurface } from '@workbench/canvas-engine/render/raster';import type { Mat2d, PlacedSurface, PointerInput, Rect, Vec2 } from '@workbench/canvas-engine/types';-import { strokeToPath, type StrokeSamplePoint } from '@workbench/canvas-engine/freehand';+import {+ createSampleDecimator,+ polygonToPath,+ sampleSpacing,+ strokeOutlineFromSamples,+ strokeToPath,+ type StrokeSamplePoint,+} from '@workbench/canvas-engine/freehand';import { applyToPoint, getScale, identity, invert, multiply } from '@workbench/canvas-engine/math/mat2d';import { expand, intersect, isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';import { getPressureBands } from '@workbench/canvas-engine/pressureBands';@@ -64,11 +72,13 @@ export interface StrokeSessionConfig {* local. Absence uses identity.*/layerTransform?: Mat2d | null;+ /** Called when a scheduled frame render throws, before the error propagates; the owner aborts the stroke. */+ onRenderError?: (error: unknown) => void;}/** The imperative handle a tool drives across a gesture. */export interface StrokeSession {- /** Appends coalesced samples and repaints the accumulated stroke. */+ /** Appends coalesced samples and schedules one repaint of the accumulated stroke for the next frame. */addPoints(inputs: readonly PointerInput[]): void;/** Finalizes the stroke and returns the completed edit for its owner to publish. */commit(): StrokeCommittedEvent | null;@@ -107,6 +117,16 @@ const padToChunk = (r: Rect, chunk: number): Rect => {return { height: bottom - y, width: right - x, x, y };};+/** Runs `task` before the next animation frame; synchronous where no frames exist. */+const scheduleAnimationFrame = (task: () => void): (() => void) => {+ if (typeof requestAnimationFrame !== 'function') {+ task();+ return () => undefined;+ }+ const frame = requestAnimationFrame(() => task());+ return () => cancelAnimationFrame(frame);+};+/** The 2D context flavour a {@link RasterSurface} exposes. */type SurfaceContext = RasterSurface['ctx'];@@ -265,9 +285,15 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession// The feathered copy of the silhouette; allocated only when hardness < 1.let soft: RasterSurface | null = null;+ // Raw samples feed only the pressure bands; the outline reads the incrementally decimated samples.const points: StrokeSamplePoint[] = [];+ const decimator = createSampleDecimator(sampleSpacing(localSize));// Below the travel threshold, preserve the first aim point as a round dab rather than a short capsule.const tapCollapseLength = Math.max(2, localSize * 0.25);+ let travel = 0;+ const scheduleFrame = ctx.scheduleFrame ?? scheduleAnimationFrame;+ let cancelScheduledFrame: (() => void) | null = null;+ let closed = false;// Before pixels cover `accumRect` in stable layer-local coordinates, unaffected by backing-store origin shifts.let beforeImageData: ImageData | null = null;let accumRect: Rect | null = null;@@ -297,17 +323,12 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessionif (points.length === 0) {return;}- let effective: readonly StrokeSamplePoint[] = points;- if (points.length > 1) {- let travel = 0;- for (let i = 1; i < points.length && travel < tapCollapseLength; i++) {- travel += Math.hypot(points[i]!.x - points[i - 1]!.x, points[i]!.y - points[i - 1]!.y);- }- if (travel < tapCollapseLength) {- effective = [points[0]!];- }- }- const { bounds, path, polygon } = strokeToPath(effective, { last, size: localSize, thinning }, ctx.createPath2D);+ const isTap = travel < tapCollapseLength;+ const effective: readonly StrokeSamplePoint[] = isTap ? [points[0]!] : points;+ const { bounds, path, polygon } = polygonToPath(+ strokeOutlineFromSamples(isTap ? effective : decimator.samples(last), { last, size: localSize, thinning }),+ ctx.createPath2D+ );let dirty: Rect | null = roundOut(featherBleed > 0 ? expand(bounds, featherBleed) : bounds);// Limit dirty/growth bounds to selection coverage and skip empty intersections.if (clipMaskLocalRect) {@@ -499,14 +520,56 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSessionctx.invalidate({ damage: { layerId, rect: changed }, layers: [layerId] });};+ const append = (sample: StrokeSamplePoint): void => {+ const previous = points[points.length - 1];+ if (previous && travel < tapCollapseLength) {+ travel += Math.hypot(sample.x - previous.x, sample.y - previous.y);+ }+ points.push(sample);+ decimator.push(sample);+ };++ const unschedule = (): void => {+ cancelScheduledFrame?.();+ cancelScheduledFrame = null;+ };++ const renderFrame = (): void => {+ cancelScheduledFrame = null;+ if (closed) {+ return;+ }+ try {+ paint(false);+ } catch (error) {+ config.onRenderError?.(error);+ throw error;+ }+ };+return {addPoints: (inputs) => {+ if (closed) {+ return;+ }for (const input of inputs) {- points.push(toSample(input));+ append(toSample(input));+ }+ if (cancelScheduledFrame) {+ return;+ }+ let ran = false;+ const cancel = scheduleFrame(() => {+ ran = true;+ renderFrame();+ });+ if (!ran) {+ cancelScheduledFrame = cancel;}- paint(false);},cancel: () => {+ closed = true;+ unschedule();const entry = layers.get(layerId);if (entry && accumRect && beforeImageData) {entry.surface.ctx.putImageData(beforeImageData, accumRect.x - entry.rect.x, accumRect.y - entry.rect.y);@@ -522,6 +585,11 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession}},commit: () => {+ if (closed) {+ return null;+ }+ closed = true;+ unschedule();paint(true);const entry = layers.get(layerId);if (!entry || !accumRect || !beforeImageData) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.tsindex 5fc16e804c..7f6726b124 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts@@ -74,6 +74,11 @@ export interface ToolContext {getSelectedLayerIds?(): readonly string[];/** Requests a re-render for the given flags. */invalidate(payload: InvalidatePayload): void;+ /**+ * Runs `task` once before the next composited frame so its invalidations render in that frame; returns a cancel.+ * Absent, tools fall back to `requestAnimationFrame`, or run synchronously without one.+ */+ scheduleFrame?(task: () => void): () => void;/** Reducer bridge. Painting tools use it for the single gesture-start `addCanvasLayer`. */dispatch(action: CanvasProjectMutation): void;/** Where a layer the tool creates lands: above `aboveId` when it belongs to `stack`, else the stack top. */