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.

fix(canvas): decide crop-all candidates before baking adjustments

Josh Corbett074628f8f6b1
diff --git a/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx b/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx
index b7cd08c581..486343a9a0 100644
--- a/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx
+++ b/docs/src/content/docs/Users Guide/07.Canvas/03.layers-panel.mdx
@@ -158,7 +158,7 @@ Their settings:
Things to know about Texture, Clarity and Dehaze:
* **They are computed in the background.** Each one looks at the whole layer, so the canvas computes it in the background and stays responsive. Meanwhile, the canvas shows the previous result, or the layer without them after you paint on it. A small spinner appears on the layer's row when the work takes more than a moment.
-* **Size limit.** They cannot run on content larger than 4096 × 4096 px (16.8 megapixels, measured over the area the layer's visible content spans, in the layer's own pixels before any scaling; for a group, at document resolution). A warning icon then appears on the layer's or group's row, the canvas leaves them out, and anything that uses the layer's pixels with them — generating, exporting, merging, rasterizing, filtering, copying or converting to a control layer, saving to PSD, painting on an image layer — is refused with a message naming the layer or group. Disable or remove them, or crop the content. The same warning appears when there is not enough canvas memory or the computation fails; hover over it for what to do, or select the adjustment to read it in Properties.
+* **Size limit.** They cannot run on content larger than 4096 × 4096 px (16.8 megapixels, measured over the area the layer's visible content spans, in the layer's own pixels before any scaling; for a group, at document resolution). A warning icon then appears on the layer's or group's row, the canvas leaves them out, and anything that uses the layer's pixels with them — generating, exporting, merging, rasterizing, filtering, copying or converting to a control layer, cropping to the frame (one layer, or all layers when this one reaches past the frame), saving to PSD, painting on an image layer — is refused with a message naming the layer or group. Disable or remove them, or crop the content. The same warning appears when there is not enough canvas memory or the computation fails; hover over it for what to do, or select the adjustment to read it in Properties.
* **What you see is what you get.** Generating, exporting, merging, rasterizing and saving to PSD use the same result as the canvas, computing it first if the canvas is still working on it. One exception: PSD has no group adjustments, so a group's Texture, Clarity and Dehaze are applied to each of its layers separately, and the PSD can look different from the canvas.
* **While you drag a selection**, the dragged pixels show without them; once placed, the layer is computed again with them.
* **Thumbnails** of layers the canvas has not shown yet can leave them out.
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.test.ts
index f9c6684f9b..ffb07eaaac 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.test.ts
@@ -1,4 +1,8 @@
-import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type {
+ CanvasAdjustmentsContract,
+ CanvasDocumentContractV3,
+ CanvasLayerContract,
+} from '@workbench/canvas-engine/contracts';
import type { AdjustmentRefusal } from '@workbench/canvas-engine/render/exactAdjustments';
import type { Rect } from '@workbench/canvas-engine/types';
@@ -134,21 +138,32 @@ const lockedPaint = (id: string, locked = true) =>
},
} as Partial<CanvasLayerContract>);
+const CLARITY: CanvasAdjustmentsContract = [{ amount: 90, id: 'clarity', isEnabled: true, size: 8, type: 'clarity' }];
+
const createCropAllHarness = (
options: {
+ /** Raster leaves carrying a Clarity stack. */
+ adjusted?: readonly string[];
historyBytes?: number;
onExport?: (layerId: string) => void;
+ /** Refuses the owner's bake; its raw export still succeeds. */
refusal?: AdjustmentRefusal;
} = {}
) => {
+ const raster = (id: string) =>
+ layerContract(
+ id,
+ 'raster',
+ options.adjusted?.includes(id) ? ({ adjustments: CLARITY } as Partial<CanvasLayerContract>) : {}
+ );
const document: CanvasDocumentContractV3 = {
background: 'transparent',
bbox: FRAME,
height: 100,
selectedLayerId: 'raster',
stacks: stacksFrom([
- layerContract('inside'),
- layerContract('raster'),
+ raster('inside'),
+ raster('raster'),
lockedPaint('locked'),
lockedPaint('lockedInside'),
groupContract('lockedGroup', [lockedPaint('lockedByGroup', false)], { isLocked: true }),
@@ -163,6 +178,7 @@ const createCropAllHarness = (
for (const [id, rect] of Object.entries(CACHE_RECTS)) {
h.layers.getOrCreateRect(id, rect);
}
+ // Raw reads of adjusted leaves are recorded as `<id>:raw`.
const exported: string[] = [];
const released: string[] = [];
// Reserved raster bytes when each export is read; every export holds its own reservation until released.
@@ -182,10 +198,11 @@ const createCropAllHarness = (
},
ctx: h.ctx,
discardPersisted,
- exportBaked: (layerId) => {
- exported.push(layerId);
+ exportBaked: (layerId, exportOptions) => {
+ const read = exportOptions?.applyAdjustments === false ? `${layerId}:raw` : layerId;
+ exported.push(read);
options.onExport?.(layerId);
- if (options.refusal?.ownerId === layerId) {
+ if (options.refusal?.ownerId === layerId && read === layerId) {
return Promise.resolve(options.refusal);
}
const entry = h.layers.get(layerId)!;
@@ -196,7 +213,7 @@ const createCropAllHarness = (
rect: { ...entry.rect },
release: () => {
reservation?.release();
- released.push(layerId);
+ released.push(read);
},
status: 'ok' as const,
surface: entry.surface,
@@ -210,19 +227,20 @@ const createCropAllHarness = (
describe('CropLayerController: crop all layers', () => {
it.each(['too-large', 'over-budget', 'error'] as const)(
- 'refuses the whole crop on a %s adjustment, releasing earlier copies',
+ 'refuses the whole crop on a %s adjustment of a leaf it must crop, releasing earlier copies',
async (reason) => {
const refusal: AdjustmentRefusal = {
- ownerId: 'control',
- ownerName: 'Control',
+ ownerId: 'raster',
+ ownerName: 'Raster',
reason,
status: 'adjustment-refused',
};
- const h = createCropAllHarness({ refusal });
+ const h = createCropAllHarness({ adjusted: ['raster'], refusal });
await expect(h.controller.cropAll()).resolves.toEqual(refusal);
- expect(h.exported).toEqual(['mask', 'region', 'control']);
- expect(h.released).toEqual(['mask', 'region']);
+ // The raw read shows the leaf reaches past the frame, so its stack must run.
+ expect(h.exported).toEqual(['mask', 'region', 'control', 'inside', 'raster:raw', 'raster']);
+ expect(h.released).toEqual(['mask', 'region', 'control', 'inside', 'raster:raw']);
expect(h.document()).toBe(h.original);
expect(h.dispatched).toEqual([]);
expect(h.history.canUndo()).toBe(false);
@@ -230,6 +248,36 @@ describe('CropLayerController: crop all layers', () => {
}
);
+ it('never runs the stack of an adjusted leaf already inside the frame', async () => {
+ const refusal: AdjustmentRefusal = {
+ ownerId: 'inside',
+ ownerName: 'Inside',
+ reason: 'too-large',
+ status: 'adjustment-refused',
+ };
+ const h = createCropAllHarness({ adjusted: ['inside'], refusal });
+
+ await expect(h.controller.cropAll()).resolves.toEqual({ cropped: 4, skippedLocked: 2, status: 'cropped' });
+ expect(h.exported).toEqual(['mask', 'region', 'control', 'inside:raw', 'raster']);
+ expect(getDocumentLayer(h.document(), 'inside')).toBe(getDocumentLayer(h.original, 'inside'));
+ expect(h.layers.get('raster')?.rect).toEqual(FRAME);
+ expect(h.reservedBytes()).toBe(0);
+ });
+
+ it('bakes an adjusted leaf it must crop, after releasing its raw read', async () => {
+ const h = createCropAllHarness({ adjusted: ['raster'] });
+
+ await expect(h.controller.cropAll()).resolves.toEqual({ cropped: 4, skippedLocked: 2, status: 'cropped' });
+ expect(h.exported).toEqual(['mask', 'region', 'control', 'inside', 'raster:raw', 'raster']);
+ // The raw read is released before the bake reserves, so the peak stays one export.
+ const croppedRegion = bytes({ height: 10, width: 5, x: 0, y: 0 });
+ const croppedControl = bytes({ height: 10, width: 15, x: 0, y: 0 });
+ expect(h.reservedAtExport.at(-1)).toBe(croppedRegion + croppedControl + bytes(CACHE_RECTS.raster!));
+ expect(getDocumentLayer(h.document(), 'raster')).not.toHaveProperty('adjustments');
+ expect(h.layers.get('raster')?.rect).toEqual(FRAME);
+ expect(h.reservedBytes()).toBe(0);
+ });
+
it('crops every unlocked leaf that reaches past the frame in one entry, and replays it as one', async () => {
const h = createCropAllHarness();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts
index 1a1ddc5cce..fdb0ed2150 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/cropLayerController.ts
@@ -1,4 +1,4 @@
-import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';
+import type { ExportBakedLayerPixelsOptions, LayerExportGuard } from '@workbench/canvas-engine/capabilities';
import type {
CanvasDocumentContractV3,
CanvasLayerContract,
@@ -13,6 +13,7 @@ import { getDocumentLayer } from '@workbench/canvas-engine/document/documentInde
import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';
import { collectHistoryMediaRefs, HISTORY_ENTRY_OVERHEAD_BYTES } from '@workbench/canvas-engine/history/history';
import { intersect, isEmpty, roundOut, transformBounds } from '@workbench/canvas-engine/math/rect';
+import { isIdentityAdjustments } from '@workbench/canvas-engine/render/adjustments';
import type { CanvasMutationContext, EditStep } from './mutationContext';
@@ -63,7 +64,10 @@ export interface CropLayerControllerOptions {
>;
readonly backend: RasterBackend;
readonly isSupportedSource: (source: CanvasLayerSourceContract) => boolean;
- readonly exportBaked: (layerId: string) => Promise<ExportResult>;
+ readonly exportBaked: (
+ layerId: string,
+ options?: Pick<ExportBakedLayerPixelsOptions, 'applyAdjustments'>
+ ) => Promise<ExportResult>;
readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;
readonly captureCache: (
layer: CanvasLayerContract,
@@ -265,19 +269,12 @@ export class CropLayerController {
const cropped: CroppedLeaf[] = [];
try {
for (const layer of candidates) {
- const exported = await this.deps.exportBaked(layer.id);
- if (exported.status === 'adjustment-refused') {
- return exported;
- }
- if (exported.status === 'missing') {
- return { status: 'stale' };
- }
- if (exported.status === 'not-ready' || exported.status === 'over-budget') {
- return { status: exported.status };
+ const exported = await this.exportForCrop(layer, frame);
+ if (exported.status === 'skip') {
+ continue;
}
if (exported.status !== 'ok') {
- // Empty, disabled-only or unsupported content has nothing to crop.
- continue;
+ return exported;
}
try {
guards.push(exported.guard);
@@ -327,6 +324,42 @@ export class CropLayerController {
}
}
+ /**
+ * A leaf's baked pixels for crop all, or `skip` when it has nothing to crop. A leaf with its own adjustment stack is
+ * first exported raw: adjustments never move pixels, so the raw rect is the baked one, and a leaf already inside the
+ * frame never runs its stack (a spatial job that could refuse the whole crop). Its guard still joins the staleness
+ * check, as every read leaf's does.
+ */
+ private async exportForCrop(
+ layer: CanvasLayerContract,
+ frame: Rect
+ ): Promise<Extract<ExportResult, { status: 'ok' }> | { status: 'skip' } | CropAllLayersResult> {
+ const settle = (
+ exported: ExportResult
+ ): Extract<ExportResult, { status: 'ok' }> | { status: 'skip' } | CropAllLayersResult => {
+ if (exported.status === 'ok' || exported.status === 'adjustment-refused') {
+ return exported;
+ }
+ if (exported.status === 'missing') {
+ return { status: 'stale' };
+ }
+ if (exported.status === 'not-ready' || exported.status === 'over-budget') {
+ return { status: exported.status };
+ }
+ // Empty, disabled-only or unsupported content has nothing to crop.
+ return { status: 'skip' };
+ };
+ if (layer.type !== 'raster' || isIdentityAdjustments(layer.adjustments)) {
+ return settle(await this.deps.exportBaked(layer.id));
+ }
+ const raw = settle(await this.deps.exportBaked(layer.id, { applyAdjustments: false }));
+ if (raw.status !== 'ok' || !cropRectFor(raw.rect, frame)) {
+ return raw;
+ }
+ raw.release();
+ return settle(await this.deps.exportBaked(layer.id));
+ }
+
private publishAll(
document: CanvasDocumentContractV3,
cropped: readonly CroppedLeaf[],
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 8f3db167c4..5081695955 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -2861,7 +2861,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
captureCache: captureLayerCache,
ctx: mutationContext,
discardPersisted: (layerId) => bitmapStore.discardLayer(layerId),
- exportBaked: (layerId) => exportBakedLayerPixelsForStructural(layerId, { includeDisabled: true }),
+ exportBaked: (layerId, options) =>
+ exportBakedLayerPixelsForStructural(layerId, { ...options, includeDisabled: true }),
isGuardCurrent: isLayerExportGuardCurrent,
isSupportedSource: isSupportedExportSource,
},
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
index 3dda85ba2f..a07e086ec0 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
@@ -126,7 +126,9 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTarget
const imageCache = imageSelected ? ctx.layers.peek(selected.id) : undefined;
if (imageSelected && isLeafPaintable(leaf) && imageCache && !imageCache.stale) {
// The brush paints a paintable, rasterized image in place the same way, under its transparency lock; a locked,
- // disabled or unready image keeps the brush's auto-created paint layer below.
+ // disabled or not yet rasterized image keeps the brush's auto-created paint layer below. A rasterized image whose
+ // spatial adjustments have not landed refuses `not-ready` (or names the stack that cannot run) and drops the
+ // stroke with a notice, as the eraser does.
const transparencyLocked = isLayerTransparencyLocked(selected);
const transaction = ctx.beginPixelEdit?.(selected.id) ?? null;
// No transform on purpose: materialization BAKES the layer's placement
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
index 4682da4751..9fcdb780c0 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
@@ -111,7 +111,7 @@ const makeEffects = (): LayerContextActionEffects => ({
fitToBbox: vi.fn(),
group: vi.fn(),
mergeDown: vi.fn(() => Promise.resolve()),
- mergeMasks: vi.fn(),
+ mergeMasks: vi.fn(() => Promise.resolve()),
mergeSelected: vi.fn(),
openProperties: vi.fn(),
openRename: vi.fn(),
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
index 2105dafaa9..c8f0321c09 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
@@ -158,7 +158,7 @@ export interface LayerContextActionEffects {
reorder(kind: LayerStackMoveKind, actionId: LayerContextActionId): void;
duplicate(): void;
mergeSelected(): void;
- mergeMasks(): void;
+ mergeMasks(): Promise<void>;
group(): void;
removeFromGroup(): void;
openRename(): void;