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
feat(canvas): add boolean raster operations
joshistoast2213173a08fb
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 470ac9cbff..b50d10f9ab 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1132,9 +1132,13 @@"convertToInpaintMask": "Convert to inpaint mask","convertToRaster": "Convert to raster layer","convertToRegionalGuidance": "Convert to regional guidance",+ "cutaway": "Cutaway with layer below",+ "cutout": "Cutout with layer below","delete": "Delete layer","duplicate": "Duplicate layer",+ "exclude": "Exclude layer below","hide": "Hide layer",+ "intersect": "Intersect with layer below","lock": "Lock layer","mergeDown": "Merge down","moveBackward": "Move backward",diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex e308e0cb2b..54efd63ad5 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -1858,6 +1858,108 @@ describe('mergeLayerDown', () => {});});+describe('boolean raster operations', () => {+ const setup = () => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ const { projectId, store } = createReducerBackedStore(twoPaintDoc());+ const base = createTestStubRasterBackend();+ const surfaces: StubRasterSurface[] = [];+ const backend = {+ ...base,+ createSurface: (width: number, height: number): StubRasterSurface => {+ const surface = base.createSurface(width, height);+ surfaces.push(surface);+ return surface;+ },+ };+ const engine = createCanvasEngine({+ backend,+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });+ const screen = createFakeCanvas();+ const overlay = createFakeCanvas();+ engine.attach(screen.element, overlay.element);+ return { engine, raf, surfaces };+ };++ it.each([+ ['intersect', 'source-in'],+ ['cutout', 'destination-in'],+ ['cutaway', 'source-out'],+ ['exclude', 'xor'],+ ] as const)('applies %s with %s, preserves its sources, and supports undo/redo', async (operation, composite) => {+ const { engine, raf, surfaces } = setup();+ raf.flush();+ await flushMicrotasks();+ raf.flush();++ expect(await engine.booleanMergeRasterLayers('upper', operation)).toBe('merged');++ const resultSurface = surfaces.find((surface) =>+ surface.callLog.some(+ (entry) => entry.op === 'set' && entry.args[0] === 'globalCompositeOperation' && entry.args[1] === composite+ )+ );+ expect(resultSurface).toBeDefined();+ expect(resultSurface!.callLog.filter((entry) => entry.op === 'drawImage')).toHaveLength(2);++ const merged = engine.getDocument()!;+ const result = merged.layers.find((layer) => layer.id !== 'upper' && layer.id !== 'below');+ expect(result).toMatchObject({+ isEnabled: true,+ source: { bitmap: null, offset: { x: 10, y: 20 }, type: 'paint' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster',+ });+ expect(merged.layers.find((layer) => layer.id === 'upper')?.isEnabled).toBe(false);+ expect(merged.layers.find((layer) => layer.id === 'below')?.isEnabled).toBe(false);++ engine.undo();+ expect(engine.getDocument()!.layers.map((layer) => [layer.id, layer.isEnabled])).toEqual([+ ['upper', true],+ ['below', true],+ ]);++ engine.redo();+ expect(engine.getDocument()!.layers.map((layer) => [layer.id, layer.isEnabled])).toEqual([+ [result!.id, true],+ ['upper', false],+ ['below', false],+ ]);+ engine.dispose();+ });++ it('refuses the operation until both raster caches are ready', async () => {+ const { engine, raf } = setup();+ raf.flush();++ expect(await engine.booleanMergeRasterLayers('upper', 'intersect')).toBe('not-ready');+ expect(engine.getDocument()!.layers.map((layer) => layer.id)).toEqual(['upper', 'below']);+ engine.dispose();+ });++ it('rejects unsupported and missing layer pairs without modifying the document', async () => {+ const doc = twoPaintDoc();+ doc.layers[1] = maskLayer('below');+ const { projectId, store } = createReducerBackedStore(doc);+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId,+ store,+ });++ expect(await engine.booleanMergeRasterLayers('upper', 'exclude')).toBe('unsupported');+ expect(await engine.booleanMergeRasterLayers('missing', 'exclude')).toBe('missing');+ expect(engine.getDocument()!.layers).toEqual(doc.layers);+ engine.dispose();+ });+});+// ---- mergeVisibleRasterLayers: whole-fold pre-flight + interleave-safe fold ----/**diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 8d19124626..1d41372edb 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -131,6 +131,9 @@ export type StagedPreviewInput = { imageName: string } | { dataUrl: string; widt*/export type MergeVisibleResult = 'merged' | 'not-ready' | 'nothing';+export type BooleanRasterOperation = 'intersect' | 'cutout' | 'cutaway' | 'exclude';+export type BooleanRasterResult = 'merged' | 'missing' | 'unsupported' | 'not-ready' | 'busy' | 'empty';+/*** Result of {@link CanvasEngine.exportRasterLayersToPsd}: `'exported'` on* success, `'nothing'` when there are no raster layers with content, `'too-large'`@@ -268,6 +271,12 @@ export interface CanvasEngine {* engine's undo history (the inverse would need the discarded pixels).*/mergeLayerDown(upperLayerId: string): boolean;+ /**+ * Applies a Canvas2D boolean operation to an adjacent raster pair, inserts the+ * paint-backed result above them, and disables (but preserves) both sources.+ * The complete change is one engine-history entry.+ */+ booleanMergeRasterLayers(upperLayerId: string, operation: BooleanRasterOperation): Promise<BooleanRasterResult>;/*** Folds ALL visible mergeable raster layers together (the raster group-header* "merge visible" action; legacy `mergeVisibleOfType`). Plans runs via the pure@@ -2025,6 +2034,113 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return !!entry && !entry.stale && !inFlight.has(layer.id);};+ const booleanCompositeModes: Record<BooleanRasterOperation, GlobalCompositeOperation> = {+ cutaway: 'source-out',+ cutout: 'destination-in',+ exclude: 'xor',+ intersect: 'source-in',+ };++ const seedGeneratedPaintCache = (layerId: string, rect: Rect, pixels: RasterSurface): void => {+ layerCache.delete(layerId);+ adjustedSurfaceCache.delete(layerId);+ const target = layerCache.getOrCreateRect(layerId, rect);+ target.surface.ctx.drawImage(pixels.canvas, 0, 0);+ target.stale = false;+ notifyLayerPainted(layerId);+ bitmapStore.markLayerDirty(layerId);+ };++ const booleanMergeRasterLayers = async (+ upperLayerId: string,+ operation: BooleanRasterOperation+ ): Promise<BooleanRasterResult> => {+ if (pipeline.isGestureActive()) {+ return 'busy';+ }+ endNudgeBurst();+ const doc = mirror.getDocument();+ if (!doc) {+ return 'missing';+ }+ const upperIndex = doc.layers.findIndex((layer) => layer.id === upperLayerId);+ if (upperIndex < 0) {+ return 'missing';+ }+ const upper = doc.layers[upperIndex];+ const below = doc.layers[upperIndex + 1];+ if (!upper || !below) {+ return 'missing';+ }+ if (!isMergeableRasterLayer(upper) || !isMergeableRasterLayer(below)) {+ return 'unsupported';+ }+ if (!isLayerCacheReadyForOp(upper, doc) || !isLayerCacheReadyForOp(below, doc)) {+ return 'not-ready';+ }++ const [upperPixels, belowPixels] = await Promise.all([+ exportBakedLayerPixels(upper.id),+ exportBakedLayerPixels(below.id),+ ]);+ if (upperPixels.status !== 'ok' || belowPixels.status !== 'ok') {+ if (upperPixels.status === 'not-ready' || belowPixels.status === 'not-ready') {+ return 'not-ready';+ }+ return 'empty';+ }++ const resultRect = roundOut(union(upperPixels.rect, belowPixels.rect));+ if (isEmpty(resultRect)) {+ return 'empty';+ }+ const resultPixels = backend.createSurface(resultRect.width, resultRect.height);+ const ctx = resultPixels.ctx;+ ctx.setTransform(1, 0, 0, 1, 0, 0);+ ctx.clearRect(0, 0, resultRect.width, resultRect.height);+ ctx.globalAlpha = below.opacity;+ ctx.globalCompositeOperation = 'source-over';+ ctx.drawImage(belowPixels.surface.canvas, belowPixels.rect.x - resultRect.x, belowPixels.rect.y - resultRect.y);+ ctx.globalAlpha = upper.opacity;+ ctx.globalCompositeOperation = booleanCompositeModes[operation];+ ctx.drawImage(upperPixels.surface.canvas, upperPixels.rect.x - resultRect.x, upperPixels.rect.y - resultRect.y);++ const resultId = createLayerId();+ const resultLayer: CanvasLayerContract = {+ blendMode: 'normal',+ id: resultId,+ isEnabled: true,+ isLocked: false,+ name: `${upper.name} ${operation}`,+ opacity: 1,+ source: { bitmap: null, offset: { x: resultRect.x, y: resultRect.y }, type: 'paint' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster',+ };+ const originalEnabled = [+ { id: upper.id, isEnabled: upper.isEnabled },+ { id: below.id, isEnabled: below.isEnabled },+ ];+ const disabled = originalEnabled.map(({ id }) => ({ id, isEnabled: false }));+ const apply = (): void => {+ store.dispatch({ index: upperIndex, layer: resultLayer, type: 'addCanvasLayer' });+ seedGeneratedPaintCache(resultId, resultRect, resultPixels);+ store.dispatch({ type: 'setCanvasLayersEnabled', updates: disabled });+ };++ apply();+ history.push({+ bytes: resultRect.width * resultRect.height * 4 + 256,+ label: `Boolean ${operation}`,+ redo: apply,+ undo: () => {+ store.dispatch({ ids: [resultId], type: 'removeCanvasLayers' });+ store.dispatch({ type: 'setCanvasLayersEnabled', updates: originalEnabled });+ },+ });+ return 'merged';+ };+const mergeLayerDown = (upperLayerId: string): boolean => {// No-op mid-gesture (a mod+e mashed during a paint drag): merging writes// pixels and dispatches a structural collapse under the open stroke session.@@ -3289,6 +3405,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return {applyTransform,+ booleanMergeRasterLayers,clearCaches,clearHistory,contextMenuLayerIdAt,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex 68555dcf15..8400d6492b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -380,6 +380,13 @@ const LayerMenu = ({void engine?.cropLayerToBbox(layer.id);}, [engine, layer.id]);+ const handleBooleanRaster = useCallback(+ (operation: 'intersect' | 'cutout' | 'cutaway' | 'exclude') => {+ void engine?.booleanMergeRasterLayers(layer.id, operation);+ },+ [engine, layer.id]+ );+const handleCopyToRaster = useCallback(() => {if (layer.type === 'control') {addCopy(copyControlToRaster(layer, createLayerId()), getActionLabel('copy-to-raster'));@@ -484,6 +491,12 @@ const LayerMenu = ({case 'crop-to-bbox':handleCropToBbox();break;+ case 'intersect':+ case 'cutout':+ case 'cutaway':+ case 'exclude':+ handleBooleanRaster(id);+ break;case 'copy-to-raster':handleCopyToRaster();break;@@ -533,6 +546,7 @@ const LayerMenu = ({handleConvertToInpaintMask,handleConvertToRegionalGuidance,handleConvertToRaster,+ handleBooleanRaster,handleCopyToControl,handleCopyToClipboard,handleCopyToInpaintMask,@@ -733,11 +747,15 @@ const LAYER_ACTION_ICONS: Record<LayerContextActionId, LucideIcon> = {'convert-to-inpaint-mask': ImageIcon,'convert-to-raster': ImageIcon,'convert-to-regional-guidance': ImageIcon,+ cutaway: MergeIcon,+ cutout: MergeIcon,delete: Trash2Icon,duplicate: CopyIcon,+ exclude: MergeIcon,'fit-to-bbox': ImageIcon,'inpaint-denoise-limit': SlidersHorizontalIcon,'inpaint-noise': SlidersHorizontalIcon,+ intersect: MergeIcon,'merge-down': MergeIcon,'move-backward': ArrowDownIcon,'move-forward': ArrowUpIcon,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.tsindex c009e6eefd..5f4f598b2b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts@@ -129,4 +129,16 @@ describe('getLayerContextActions', () => {expect(actions.find((action) => action.id === 'crop-to-bbox')?.isDisabled).toBe(true);});++ it('exposes boolean raster actions only for an adjacent mergeable raster pair', () => {+ const upper = paintLayer('upper');+ const below = paintLayer('below');+ const operations = ['intersect', 'cutout', 'cutaway', 'exclude'];++ expect(idsFor(upper, [upper, below])).toEqual(expect.arrayContaining(operations));+ expect(idsFor(below, [upper, below])).toEqual(expect.not.arrayContaining(operations));+ expect(idsFor(upper, [upper, createInpaintMaskLayer('Mask', 'mask')])).toEqual(+ expect.not.arrayContaining(operations)+ );+ });});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.tsindex d4f8ac8de6..5f7e9483b1 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts@@ -15,6 +15,10 @@ export type LayerContextActionId =| 'save-to-assets'| 'copy-to-clipboard'| 'crop-to-bbox'+ | 'intersect'+ | 'cutout'+ | 'cutaway'+ | 'exclude'| 'copy-to-raster'| 'copy-to-control'| 'copy-to-inpaint-mask'@@ -143,6 +147,34 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefiniisDisabled: (ctx) => !ctx.hasEngine || ctx.layer.isLocked,labelKey: 'widgets.layers.actions.cropLayerToBbox',},+ {+ defaultLabel: 'Intersect with layer below',+ group: 'edit',+ id: 'intersect',+ isVisible: (ctx) => canMergeLayerDown(ctx.layers, ctx.index, ctx.hasEngine),+ labelKey: 'widgets.layers.actions.intersect',+ },+ {+ defaultLabel: 'Cutout with layer below',+ group: 'edit',+ id: 'cutout',+ isVisible: (ctx) => canMergeLayerDown(ctx.layers, ctx.index, ctx.hasEngine),+ labelKey: 'widgets.layers.actions.cutout',+ },+ {+ defaultLabel: 'Cutaway with layer below',+ group: 'edit',+ id: 'cutaway',+ isVisible: (ctx) => canMergeLayerDown(ctx.layers, ctx.index, ctx.hasEngine),+ labelKey: 'widgets.layers.actions.cutaway',+ },+ {+ defaultLabel: 'Exclude layer below',+ group: 'edit',+ id: 'exclude',+ isVisible: (ctx) => canMergeLayerDown(ctx.layers, ctx.index, ctx.hasEngine),+ labelKey: 'widgets.layers.actions.exclude',+ },{defaultLabel: 'Copy to raster layer',group: 'convert',