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 copy layer to raster
joshistoast0d5add5fda61
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex ee824013d3..e308e0cb2b 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -471,6 +471,67 @@ describe('createCanvasEngine', () => {engine.dispose();});+ it('copyLayerToRaster adds a baked paint copy directly above the source layer', async () => {+ const doc = { ...makeDoc(), layers: [rasterLayer('top'), rasterLayer('a')] };+ const { store } = createFakeStore(doc);+ const dispatch = store.dispatch as Mock;+ const base = createTestStubRasterBackend();+ const surfaces: StubRasterSurface[] = [];+ const engine = createCanvasEngine({+ backend: {+ ...base,+ createSurface: (width, height) => {+ const surface = base.createSurface(width, height);+ surfaces.push(surface);+ return surface;+ },+ },+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });++ const newId = await engine.copyLayerToRaster('a');++ expect(newId).toMatch(/^layer-/);+ const add = dispatch.mock.calls+ .map((call) => call[0] as WorkbenchAction)+ .find((action) => action.type === 'addCanvasLayer');+ expect(add).toBeDefined();+ if (add?.type === 'addCanvasLayer' && add.layer.type === 'raster') {+ expect(add.index).toBe(1);+ expect(add.layer.id).toBe(newId);+ expect(add.layer.name).toBe('a copy');+ expect(add.layer.source).toEqual({ bitmap: null, offset: { x: 0, y: 0 }, type: 'paint' });+ expect(add.layer.transform).toEqual({ rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 });+ } else {+ throw new Error('expected addCanvasLayer with raster copy');+ }+ expect(+ surfaces.some(+ (surface) =>+ surface.width === 10 && surface.height === 10 && surface.callLog.some((entry) => entry.op === 'drawImage')+ )+ ).toBe(true);+ engine.dispose();+ });++ it('copyLayerToRaster returns null for empty layers', async () => {+ const empty = { ...rasterLayer('empty'), source: { bitmap: null, type: 'paint' } as const };+ const { store } = createFakeStore({ ...makeDoc(), layers: [empty] });+ const dispatch = store.dispatch as Mock;+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });++ expect(await engine.copyLayerToRaster('empty')).toBeNull();+ expect(dispatch).not.toHaveBeenCalled();+ 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.tsindex 14d5df41db..8d19124626 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -319,6 +319,8 @@ export interface CanvasEngine {* through the normal bitmap-store path. A no-op for locked/missing/unsupported layers.*/cropLayerToBbox(layerId: string): Promise<boolean>;+ /** Creates a new raster paint layer above `layerId` from that layer's baked pixels. */+ copyLayerToRaster(layerId: string): Promise<string | null>;/*** Rasterizes a parametric (shape/gradient/text) layer to a paint layer: bakes its* current appearance into a content-sized paint bitmap (persisted through the@@ -1221,6 +1223,47 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return true;};+ const copyLayerToRaster = async (layerId: string): Promise<string | null> => {+ if (pipeline.isGestureActive()) {+ return null;+ }+ endNudgeBurst();+ const doc = mirror.getDocument();+ const sourceLayer = doc?.layers.find((candidate) => candidate.id === layerId);+ if (!doc || !sourceLayer) {+ return null;+ }+ const sourceIndex = doc.layers.findIndex((layer) => layer.id === layerId);+ if (sourceIndex < 0) {+ return null;+ }+ const baked = await exportBakedLayerPixels(layerId, { includeDisabled: true });+ if (baked.status !== 'ok') {+ return null;+ }++ const newId = createLayerId();+ const layer: CanvasLayerContract = {+ blendMode: 'normal',+ id: newId,+ isEnabled: true,+ isLocked: false,+ name: `${sourceLayer.name} copy`,+ opacity: 1,+ source: { bitmap: null, offset: { x: baked.rect.x, y: baked.rect.y }, type: 'paint' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster',+ };+ store.dispatch({ index: sourceIndex, layer, type: 'addCanvasLayer' });++ const target = layerCache.getOrCreateRect(newId, baked.rect);+ target.surface.ctx.drawImage(baked.surface.canvas, 0, 0);+ target.stale = false;+ notifyLayerPainted(newId);+ bitmapStore.markLayerDirty(newId);+ return newId;+ };+/*** Rasterizes a single layer on demand and returns its cache surface plus the* content rect (layer-local origin/size) those pixels occupy, for the@@ -3257,6 +3300,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {commitStructural,commitTextEdit,cropLayerToBbox,+ copyLayerToRaster,deselect,detach,dispose,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex fc386524e7..9424c70327 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -336,6 +336,10 @@ const LayerMenu = ({void engine?.cropLayerToBbox(layer.id);}, [engine, layer.id]);+ const handleCopyToRaster = useCallback(() => {+ void engine?.copyLayerToRaster(layer.id);+ }, [engine, layer.id]);+const handleLayerConfigAction = useCallback((id: LayerContextActionId) => {if (id === 'control-transparency-effect' && layer.type === 'control') {@@ -400,6 +404,9 @@ const LayerMenu = ({case 'crop-to-bbox':handleCropToBbox();break;+ case 'copy-to-raster':+ handleCopyToRaster();+ break;case 'rasterize':handleRasterize();break;@@ -430,6 +437,7 @@ const LayerMenu = ({handleConvertToControl,handleConvertToRaster,handleCopyToClipboard,+ handleCopyToRaster,handleCropToBbox,handleDelete,handleDuplicate,@@ -616,6 +624,7 @@ const LAYER_ACTION_GROUPS: readonly LayerContextAction['group'][] = [const LAYER_ACTION_ICONS: Record<LayerContextActionId, LucideIcon> = {'control-transparency-effect': SlidersHorizontalIcon,'copy-to-clipboard': CopyIcon,+ 'copy-to-raster': CopyIcon,'crop-to-bbox': CropIcon,'convert-to-control': SlidersHorizontalIcon,'convert-to-raster': ImageIcon,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.tsindex 5ae891867e..cc7b661fb7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts@@ -58,7 +58,13 @@ describe('getLayerContextActions', () => {it('exposes control-only transparency and raster conversion actions', () => {const layer = createControlLayer('Control', 'control');- expect(idsFor(layer)).toEqual(expect.arrayContaining(['control-transparency-effect', 'convert-to-raster']));+ expect(idsFor(layer)).toEqual(+ expect.arrayContaining(['control-transparency-effect', 'convert-to-raster', 'copy-to-raster'])+ );+ });++ it('does not expose copy-to-raster for raster layers', () => {+ expect(idsFor(paintLayer('raster'))).not.toContain('copy-to-raster');});it('exposes regional guidance add actions only for missing prompts', () => {@@ -86,6 +92,10 @@ describe('getLayerContextActions', () => {expect(actions.find((action) => action.id === 'copy-to-clipboard')?.isDisabled).toBe(true);expect(actions.find((action) => action.id === 'crop-to-bbox')?.isDisabled).toBe(true);expect(actions.find((action) => action.id === 'merge-down')?.isDisabled).toBe(true);++ const control = createControlLayer('Control', 'control');+ const controlActions = getLayerContextActions({ hasEngine: false, index: 0, layer: control, layers: [control] });+ expect(controlActions.find((action) => action.id === 'copy-to-raster')?.isDisabled).toBe(true);});it('disables crop-to-bbox for locked layers', () => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.tsindex 63d59cffff..4544605248 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts@@ -15,6 +15,7 @@ export type LayerContextActionId =| 'save-to-assets'| 'copy-to-clipboard'| 'crop-to-bbox'+ | 'copy-to-raster'| 'rasterize'| 'convert-to-control'| 'convert-to-raster'@@ -133,6 +134,14 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefiniisDisabled: (ctx) => !ctx.hasEngine || ctx.layer.isLocked,labelKey: 'widgets.layers.actions.cropLayerToBbox',},+ {+ defaultLabel: 'Copy to raster layer',+ group: 'convert',+ id: 'copy-to-raster',+ isDisabled: (ctx) => !ctx.hasEngine,+ isVisible: (ctx) => ctx.layer.type !== 'raster',+ labelKey: 'widgets.layers.actions.copyToRasterLayer',+ },{defaultLabel: 'Rasterize',group: 'convert',