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.

feat(canvas): add baked layer export primitive

joshistoastfa36f6f35536
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
index 31081b84bc..433e047432 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -308,6 +308,68 @@ describe('createCanvasEngine', () => {
engine.dispose();
});
+ it('exportBakedLayerPixels draws the cache through the layer transform into a document-space surface', async () => {
+ const layer = {
+ ...rasterLayer('a'),
+ transform: { rotation: 0, scaleX: 2, scaleY: 3, x: 5, y: 6 },
+ };
+ const { store } = createFakeStore({ ...makeDoc(), layers: [layer] });
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: 'p1',
+ store,
+ });
+
+ const result = await engine.exportBakedLayerPixels('a');
+
+ expect(result.status).toBe('ok');
+ if (result.status === 'ok') {
+ expect(result.rect).toEqual({ height: 30, width: 20, x: 5, y: 6 });
+ expect(result.surface.width).toBe(20);
+ expect(result.surface.height).toBe(30);
+ expect((result.surface as StubRasterSurface).callLog).toEqual(
+ expect.arrayContaining([
+ { args: [1, 0, 0, 1, 0, 0], op: 'setTransform' },
+ { args: [2, 0, 0, 3, 0, 0], op: 'setTransform' },
+ expect.objectContaining({ op: 'drawImage' }),
+ ])
+ );
+ }
+ engine.dispose();
+ });
+
+ it('exportBakedLayerPixels bakes raster adjustments into the exported surface only', async () => {
+ const layer = {
+ ...rasterLayer('a'),
+ adjustments: { brightness: 0.25, contrast: 0, saturation: 0 },
+ };
+ const { store } = createFakeStore({ ...makeDoc(), layers: [layer] });
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId: 'p1',
+ store,
+ });
+
+ const raw = await engine.exportLayerPixels('a');
+ const baked = await engine.exportBakedLayerPixels('a');
+
+ expect(raw.status).toBe('ok');
+ expect(baked.status).toBe('ok');
+ if (raw.status === 'ok' && baked.status === 'ok') {
+ expect(baked.surface).not.toBe(raw.surface);
+ expect((raw.surface as StubRasterSurface).callLog.some((entry) => entry.op === 'putImageData')).toBe(false);
+ expect((baked.surface as StubRasterSurface).callLog).toEqual(
+ expect.arrayContaining([
+ { args: [0, 0, 10, 10], op: 'getImageData' },
+ expect.objectContaining({ op: 'putImageData' }),
+ ])
+ );
+ }
+ engine.dispose();
+ });
+
it('setTool switches the active tool and updates the store', () => {
const { engine } = createEngine();
const listener = vi.fn();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 5aafd9f943..0b4db00ee2 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -45,9 +45,10 @@ import { createEngineStores, type EngineStores, type TextToolOptions } from '@wo
import { executePsdExport, planPsdExport } from '@workbench/canvas-engine/export/psdExport';
import { createPointerPipeline, type PointerPipeline } from '@workbench/canvas-engine/input/pointerPipeline';
import { createWheelHandler } from '@workbench/canvas-engine/input/wheel';
-import { invert as invertMatrix } from '@workbench/canvas-engine/math/mat2d';
+import { fromTRS, invert as invertMatrix } from '@workbench/canvas-engine/math/mat2d';
import { intersect, isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';
import { createAdjustedSurfaceCache } from '@workbench/canvas-engine/render/adjustedSurfaceCache';
+import { applyAdjustments } from '@workbench/canvas-engine/render/adjustments';
import {
blendToComposite,
compositeDocument,
@@ -147,6 +148,13 @@ export type ExportLayerPixelsResult =
| { status: 'ok'; surface: RasterSurface; rect: Rect }
| { status: 'missing' | 'disabled' | 'unsupported' | 'empty' | 'not-ready' };
+export interface ExportBakedLayerPixelsOptions extends ExportLayerPixelsOptions {
+ /** Defaults true. When false, leaves raster adjustments non-destructive. */
+ applyAdjustments?: boolean;
+}
+
+export type ExportBakedLayerPixelsResult = ExportLayerPixelsResult;
+
/** The minimal workbench store the engine depends on. */
export interface EngineStore {
getState(): WorkbenchState;
@@ -290,6 +298,15 @@ export interface CanvasEngine {
* an already in-flight rasterize, so callers never export stale/blank pixels.
*/
exportLayerPixels(layerId: string, options?: ExportLayerPixelsOptions): Promise<ExportLayerPixelsResult>;
+ /**
+ * Exports a layer as a new world-space surface: its cache is drawn through the
+ * layer transform into the returned document-space rect, and raster adjustments
+ * are baked by default. Opacity/blend are intentionally not baked.
+ */
+ exportBakedLayerPixels(
+ layerId: string,
+ options?: ExportBakedLayerPixelsOptions
+ ): Promise<ExportBakedLayerPixelsResult>;
/**
* Rasterizes a parametric (shape/gradient/text) layer to a paint layer: bakes its
* current appearance into a content-sized paint bitmap (persisted through the
@@ -1076,6 +1093,47 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
return { rect: entry.rect, status: 'ok', surface: entry.surface };
};
+ const exportBakedLayerPixels = async (
+ layerId: string,
+ options: ExportBakedLayerPixelsOptions = {}
+ ): Promise<ExportBakedLayerPixelsResult> => {
+ const raw = await rasterizeLayerPixels(layerId, options);
+ if (raw.status !== 'ok') {
+ return raw;
+ }
+ const doc = mirror.getDocument();
+ const layer = doc?.layers.find((candidate) => candidate.id === layerId);
+ if (!doc || !layer) {
+ return { status: 'missing' };
+ }
+
+ const matrix = fromTRS(
+ { x: layer.transform.x, y: layer.transform.y },
+ layer.transform.rotation,
+ layer.transform.scaleX,
+ layer.transform.scaleY
+ );
+ const worldRect = roundOut(transformBounds(matrix, raw.rect));
+ if (isEmpty(worldRect)) {
+ return { status: 'empty' };
+ }
+
+ const surface = backend.createSurface(worldRect.width, worldRect.height);
+ const ctx = surface.ctx;
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ ctx.clearRect(0, 0, worldRect.width, worldRect.height);
+ ctx.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.e - worldRect.x, matrix.f - worldRect.y);
+ ctx.drawImage(raw.surface.canvas, raw.rect.x, raw.rect.y);
+
+ if (options.applyAdjustments !== false && layer.type === 'raster' && layer.adjustments) {
+ const imageData = ctx.getImageData(0, 0, worldRect.width, worldRect.height);
+ applyAdjustments(imageData, layer.adjustments);
+ ctx.putImageData(imageData, 0, 0);
+ }
+
+ return { rect: worldRect, status: 'ok', surface };
+ };
+
/**
* Rasterizes a single layer on demand and returns its cache surface plus the
* content rect (layer-local origin/size) those pixels occupy, for the
@@ -3117,6 +3175,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
drawLayerThumbnail,
eraseSelection,
exportRasterLayersToPsd,
+ exportBakedLayerPixels,
exportLayerPixels: rasterizeLayerPixels,
fillSelection,
fitToView,