Skip to content

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.

perf(canvas): adjust exported layers in layer-local space

Josh Corbettea3554ba93d4
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupAdjustmentComposite.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupAdjustmentComposite.browser.test.ts
index cc07dfc76a..69e6f1a653 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupAdjustmentComposite.browser.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupAdjustmentComposite.browser.test.ts
@@ -5,6 +5,7 @@ import type { Rect } from '@workbench/canvas-engine/types';
import { createCanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';
import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
import { identity } from '@workbench/canvas-engine/math/mat2d';
+import { createAdjustedSurfaceCache } from '@workbench/canvas-engine/render/adjustedSurfaceCache';
import { createColorSampler } from '@workbench/canvas-engine/render/colorSample';
import { compositeDocument } from '@workbench/canvas-engine/render/compositor';
import { createGroupSurfaceCache } from '@workbench/canvas-engine/render/groupSurfaceCache';
@@ -518,3 +519,122 @@ describe('group-scoped previews and partial refresh', () => {
expect(pixels).toEqual(allPixels(fresh.composite(floatAt(lifted(fresh.scene), 8))));
});
});
+
+describe('layer adjustments in export', () => {
+ /** A 16px gradient layer, scaled 3x and offset, with a non-linear stack. */
+ const adjustedScene = () => {
+ const scene = sceneFor({});
+ scene.caches.growToRect('graded', { height: 16, width: 16, x: 0, y: 0 });
+ const ctx = scene.caches.get('graded')!.surface.ctx;
+ for (let x = 0; x < 16; x += 1) {
+ ctx.fillStyle = `rgb(${x * 16}, ${255 - x * 16}, 128)`;
+ ctx.fillRect(x, 0, 1, 16);
+ }
+ scene.caches.publishPixels('graded');
+ const layer = raster('graded', {
+ adjustments: gammaStack('ga'),
+ transform: { rotation: 0, scaleX: 3, scaleY: 3, x: 5, y: 7 },
+ });
+ return { document: docWith([layer]), layer, scene };
+ };
+
+ it('matches the display pixel for pixel by adjusting layer-local pixels before resampling', async () => {
+ const { document, layer, scene } = adjustedScene();
+ const adjusted = createAdjustedSurfaceCache(scene.backend);
+ const screen = scene.backend.createSurface(WIDTH, HEIGHT);
+ compositeDocument(screen, document, scene.caches, identity(), {
+ adjustedSurface: (_layer, entry) => adjusted.get(layer.id, entry, layer.adjustments),
+ backend: scene.backend,
+ });
+ const exported = await renderRasterComposite(planBaseRasterComposite(document, BBOX), scene);
+
+ const display = screen.ctx.getImageData(0, 0, WIDTH, HEIGHT).data;
+ const exportedPixels = exported.ctx.getImageData(0, 0, WIDTH, HEIGHT).data;
+ let worst = 0;
+ for (let i = 0; i < display.length; i += 1) {
+ worst = Math.max(worst, Math.abs(display[i]! - exportedPixels[i]!));
+ }
+ expect(worst).toBeLessThanOrEqual(1);
+ });
+
+ it('allocates only the layer-local region the bbox can sample, not a bbox-sized intermediate', async () => {
+ const { document, scene } = adjustedScene();
+ const sizes: [number, number][] = [];
+ const backend = {
+ ...scene.backend,
+ createSurface: (width: number, height: number) => {
+ sizes.push([width, height]);
+ return scene.backend.createSurface(width, height);
+ },
+ };
+ const corner: Rect = { height: 8, width: 8, x: 5, y: 7 };
+ await renderRasterComposite(planBaseRasterComposite(document, corner), { ...scene, backend });
+
+ // The output surface plus a local copy covering about 8/3 source pixels (+1px resampling margin) a side.
+ expect(sizes).toEqual([
+ [8, 8],
+ [4, 4],
+ ]);
+ });
+
+ it('adjusts a downscaled layer after resampling, so the work never exceeds the output', async () => {
+ const { scene } = adjustedScene();
+ const shrunk = docWith([
+ raster('graded', {
+ adjustments: gammaStack('ga'),
+ transform: { rotation: 0, scaleX: 0.25, scaleY: 0.25, x: 0, y: 0 },
+ }),
+ ]);
+ const sizes: [number, number][] = [];
+ const backend = {
+ ...scene.backend,
+ createSurface: (width: number, height: number) => {
+ sizes.push([width, height]);
+ return scene.backend.createSurface(width, height);
+ },
+ };
+ await renderRasterComposite(planBaseRasterComposite(shrunk, { height: 2, width: 2, x: 0, y: 0 }), {
+ ...scene,
+ backend,
+ });
+
+ expect(sizes).toEqual([
+ [2, 2],
+ [2, 2],
+ ]);
+ });
+
+ it("draws the display's adjusted copy instead of adjusting again", async () => {
+ const { document, layer, scene } = adjustedScene();
+ const adjusted = createAdjustedSurfaceCache(scene.backend);
+ const display = adjusted.get(layer.id, scene.caches.get(layer.id)!, layer.adjustments)!;
+ const sizes: [number, number][] = [];
+ const backend = {
+ ...scene.backend,
+ createSurface: (width: number, height: number) => {
+ sizes.push([width, height]);
+ return scene.backend.createSurface(width, height);
+ },
+ };
+ const shared: RasterSurface[] = [];
+ const exported = await renderRasterComposite(planBaseRasterComposite(document, BBOX), {
+ ...scene,
+ adjustedSurface: (_layerId, surface) => {
+ shared.push(surface);
+ return display;
+ },
+ backend,
+ });
+
+ expect(shared).toEqual([scene.caches.get(layer.id)!.surface]);
+ expect(sizes).toEqual([[WIDTH, HEIGHT]]);
+ const screen = scene.backend.createSurface(WIDTH, HEIGHT);
+ compositeDocument(screen, document, scene.caches, identity(), {
+ adjustedSurface: () => display,
+ backend: scene.backend,
+ });
+ expect([...exported.ctx.getImageData(0, 0, WIDTH, HEIGHT).data]).toEqual([
+ ...screen.ctx.getImageData(0, 0, WIDTH, HEIGHT).data,
+ ]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts
index bd58b843a2..c13acf322e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts
@@ -12,8 +12,8 @@ import type { Mat2d, Rect } from '@workbench/canvas-engine/types';
import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';
import { getSourceContentRect } from '@workbench/canvas-engine/document/sources';
-import { fromTRS, multiply } from '@workbench/canvas-engine/math/mat2d';
-import { roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';
+import { fromTRS, invert, multiply } from '@workbench/canvas-engine/math/mat2d';
+import { expand, intersect, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';
import { adjustmentsKey, applyAdjustments, isIdentityAdjustments } from '@workbench/canvas-engine/render/adjustments';
import { blendToComposite } from '@workbench/canvas-engine/render/compositor';
import {
@@ -55,6 +55,12 @@ export interface RenderRasterCompositeDeps {
};
/** Owned access to a layer's pixels, released once they are drawn. */
getLayerSurface(layerId: string): Promise<{ surface: RasterSurface; rect: Rect; release(): void }>;
+ /** The display's memoized, layer-local adjusted copy of `surface`, or null when the owner keeps none for it. */
+ adjustedSurface?(
+ layerId: string,
+ surface: RasterSurface,
+ adjustments: CanvasAdjustmentsContract
+ ): RasterSurface | null;
readImageData?(surface: RasterSurface, rect: Rect): ImageData;
writeImageData?(surface: RasterSurface, imageData: ImageData, x: number, y: number): void;
}
@@ -239,33 +245,68 @@ export const renderRasterComposite = async (
}
};
+ /** Adjusts `[source at origin]` after resampling into an output-sized buffer; bounded by the output, not the layer. */
+ const drawAdjustedAtOutput = (
+ ctx: Ctx,
+ ref: CompositeLayerRef,
+ source: RasterSurface,
+ origin: Rect,
+ placed: Mat2d,
+ adjustments: CanvasAdjustmentsContract
+ ): void => {
+ const temp = deps.backend.createSurface(width, height);
+ setTransform(temp.ctx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
+ temp.ctx.clearRect(0, 0, width, height);
+ setTransform(temp.ctx, placed);
+ temp.ctx.drawImage(source.canvas, origin.x, origin.y);
+ const pixels = readImageData(temp, fullRect);
+ applyAdjustments(pixels, adjustments);
+ writeImageData(temp, pixels, 0, 0);
+ ctx.save();
+ setTransform(ctx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
+ ctx.globalAlpha = ref.opacity;
+ ctx.globalCompositeOperation = blendToComposite(ref.blendMode);
+ ctx.drawImage(temp.canvas, 0, 0);
+ ctx.restore();
+ };
+
const drawLayer = (ctx: Ctx, ref: CompositeLayerRef, layerSurface: { surface: RasterSurface; rect: Rect }): void => {
+ const placed = multiply(view, layerMatrix(ref));
+ let source = layerSurface.surface;
+ let origin: Rect = layerSurface.rect;
if (ref.adjustments) {
- // Bake adjustments into an isolated bbox surface before applying layer opacity/blend to generation output.
- const temp = deps.backend.createSurface(width, height);
- const tempCtx = temp.ctx;
- setTransform(tempCtx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
- tempCtx.clearRect(0, 0, width, height);
- setTransform(tempCtx, multiply(view, layerMatrix(ref)));
- tempCtx.drawImage(layerSurface.surface.canvas, layerSurface.rect.x, layerSurface.rect.y);
- const pixels = readImageData(temp, fullRect);
- applyAdjustments(pixels, ref.adjustments);
- writeImageData(temp, pixels, 0, 0);
- ctx.save();
- setTransform(ctx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
- ctx.globalAlpha = ref.opacity;
- ctx.globalCompositeOperation = blendToComposite(ref.blendMode);
- ctx.drawImage(temp.canvas, 0, 0);
- ctx.restore();
- return;
+ // Adjust layer-local pixels before resampling, as the display does: reuse the display's adjusted copy, else
+ // adjust only the region the output samples. A downscaled layer samples more pixels than the output holds,
+ // so it adjusts after resampling instead, keeping the work bounded by the output.
+ const shared = deps.adjustedSurface?.(ref.id, source, ref.adjustments) ?? null;
+ if (shared) {
+ source = shared;
+ } else {
+ const inverse = invert(placed);
+ const sampled = inverse ? intersect(roundOut(expand(transformBounds(inverse, fullRect), 1)), origin) : origin;
+ if (!sampled) {
+ return;
+ }
+ if (sampled.width * sampled.height > width * height) {
+ drawAdjustedAtOutput(ctx, ref, source, origin, placed, ref.adjustments);
+ return;
+ }
+ const local = deps.backend.createSurface(sampled.width, sampled.height);
+ setTransform(local.ctx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
+ local.ctx.drawImage(source.canvas, origin.x - sampled.x, origin.y - sampled.y);
+ const pixels = readImageData(local, { height: sampled.height, width: sampled.width, x: 0, y: 0 });
+ applyAdjustments(pixels, ref.adjustments);
+ writeImageData(local, pixels, 0, 0);
+ source = local;
+ origin = sampled;
+ }
}
ctx.save();
ctx.globalAlpha = ref.opacity;
ctx.globalCompositeOperation = blendToComposite(ref.blendMode);
- setTransform(ctx, multiply(view, layerMatrix(ref)));
- // Draw the cache at its layer-local content origin (content-sized paint
- // layers place their pixels off-zero).
- ctx.drawImage(layerSurface.surface.canvas, layerSurface.rect.x, layerSurface.rect.y);
+ setTransform(ctx, placed);
+ // Draw at the layer-local content origin (content-sized paint layers place their pixels off-zero).
+ ctx.drawImage(source.canvas, origin.x, origin.y);
ctx.restore();
};