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): opacity and blend modes on raster-stack groups

Josh Corbett2465a2316848
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index 278258f9f5..8c784704fc 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -2,12 +2,12 @@
"build": {
"launchpad": {
"baseline": {
- "brotliBytes": 841579,
+ "brotliBytes": 841899,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 840575,
+ "gzipBytes": 840891,
"imageRawBytes": 156376,
- "initialRawBytes": 1959360,
+ "initialRawBytes": 1960354,
"largestAssetRawBytes": 746376,
"otherAssetRawBytes": 0,
"ownedRawBytes": 70904,
@@ -291,12 +291,12 @@
]
},
"limits": {
- "brotliBytes": 849995,
+ "brotliBytes": 850318,
"cssRawBytes": 2181,
"fontRawBytes": 221675,
- "gzipBytes": 848981,
+ "gzipBytes": 849300,
"imageRawBytes": 157940,
- "initialRawBytes": 1978954,
+ "initialRawBytes": 1979958,
"largestAssetRawBytes": 753840,
"otherAssetRawBytes": 0,
"ownedRawBytes": 70904,
@@ -309,12 +309,12 @@
},
"editor": {
"baseline": {
- "brotliBytes": 1103113,
+ "brotliBytes": 1104007,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 1098700,
+ "gzipBytes": 1099574,
"imageRawBytes": 156376,
- "initialRawBytes": 2752773,
+ "initialRawBytes": 2755775,
"largestAssetRawBytes": 746376,
"otherAssetRawBytes": 0,
"ownedRawBytes": 114628,
@@ -732,7 +732,7 @@
"source:src/workbench/canvas-engine/render/adjustments.ts",
"source:src/workbench/canvas-engine/render/compositor.ts",
"source:src/workbench/canvas-engine/render/controlTransparency.ts",
- "source:src/workbench/canvas-engine/render/groupAdjustmentScopes.ts",
+ "source:src/workbench/canvas-engine/render/groupCompositeScopes.ts",
"source:src/workbench/canvas-engine/render/maskFill.ts",
"source:src/workbench/canvas-engine/render/rasterComposite.ts",
"source:src/workbench/canvas-engine/render/rasterizers/textRasterizer.ts",
@@ -934,12 +934,12 @@
]
},
"limits": {
- "brotliBytes": 1114145,
+ "brotliBytes": 1115048,
"cssRawBytes": 2181,
"fontRawBytes": 221675,
- "gzipBytes": 1109687,
+ "gzipBytes": 1110570,
"imageRawBytes": 157940,
- "initialRawBytes": 2780301,
+ "initialRawBytes": 2783333,
"largestAssetRawBytes": 753840,
"otherAssetRawBytes": 0,
"ownedRawBytes": 114628,
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 735b5245b3..bb78c0f6a3 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -25,13 +25,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 116.70000000298023,
+ "domContentLoadedMedianMs": 118.6000000089407,
"id": "launchpad",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 116.79999999701977,
- "longestTaskMaxMs": 71,
+ "loadMedianMs": 118.70000000298023,
+ "longestTaskMaxMs": 69,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -58,7 +58,7 @@
"scriptRequestCount": 34,
"totalRawBytes": 1841162
},
- "routeReadyMedianMs": 261.59999999403954,
+ "routeReadyMedianMs": 260.90000000596046,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "empty"
},
@@ -85,13 +85,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 113.70000000298023,
+ "domContentLoadedMedianMs": 117.79999999701977,
"id": "launchpad",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 113.80000001192093,
- "longestTaskMaxMs": 67,
+ "loadMedianMs": 117.8999999910593,
+ "longestTaskMaxMs": 70,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -118,7 +118,7 @@
"scriptRequestCount": 34,
"totalRawBytes": 1841162
},
- "routeReadyMedianMs": 271.8999999910593,
+ "routeReadyMedianMs": 277.09999999403954,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "representative"
},
@@ -145,15 +145,15 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 114.5,
+ "domContentLoadedMedianMs": 117.79999999701977,
"id": "editor-minimal",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 114.59999999403954,
- "longestTaskMaxMs": 96,
+ "loadMedianMs": 118,
+ "longestTaskMaxMs": 113,
"owner": "workbench",
- "projectSwitchMedianMs": 36.79999999701977,
+ "projectSwitchMedianMs": 37.69999998807907,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -163,9 +163,9 @@
"largestAssetRawBytes": 746376,
"otherRawBytes": 160728,
"requestCount": 115,
- "scriptRawBytes": 3283435,
+ "scriptRawBytes": 3286283,
"scriptRequestCount": 110,
- "totalRawBytes": 3626362
+ "totalRawBytes": 3629210
},
"resourceLimits": {
"cssRawBytes": 2181,
@@ -174,11 +174,11 @@
"largestAssetRawBytes": 753840,
"otherRawBytes": 162336,
"requestCount": 115,
- "scriptRawBytes": 3316270,
+ "scriptRawBytes": 3319146,
"scriptRequestCount": 110,
- "totalRawBytes": 3662626
+ "totalRawBytes": 3665503
},
- "routeReadyMedianMs": 660.7999999970198,
+ "routeReadyMedianMs": 671.2000000029802,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -205,15 +205,15 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 113.5,
+ "domContentLoadedMedianMs": 119.5,
"id": "editor-minimal",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 113.6000000089407,
- "longestTaskMaxMs": 179,
+ "loadMedianMs": 119.6000000089407,
+ "longestTaskMaxMs": 200,
"owner": "workbench",
- "projectSwitchMedianMs": 67.20000000298023,
+ "projectSwitchMedianMs": 70.90000000596046,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -223,9 +223,9 @@
"largestAssetRawBytes": 746376,
"otherRawBytes": 160728,
"requestCount": 115,
- "scriptRawBytes": 3283435,
+ "scriptRawBytes": 3286283,
"scriptRequestCount": 110,
- "totalRawBytes": 3626362
+ "totalRawBytes": 3629210
},
"resourceLimits": {
"cssRawBytes": 2181,
@@ -234,11 +234,11 @@
"largestAssetRawBytes": 753840,
"otherRawBytes": 162336,
"requestCount": 115,
- "scriptRawBytes": 3316270,
+ "scriptRawBytes": 3319146,
"scriptRequestCount": 110,
- "totalRawBytes": 3662626
+ "totalRawBytes": 3665503
},
- "routeReadyMedianMs": 438.5,
+ "routeReadyMedianMs": 448.70000000298023,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
},
@@ -247,31 +247,31 @@
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 297147,
+ "largestAssetRawBytes": 297203,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 455507,
+ "scriptRawBytes": 455563,
"scriptRequestCount": 7,
- "totalRawBytes": 455507
+ "totalRawBytes": 455563
},
"activatedResourceLimits": {
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 300119,
+ "largestAssetRawBytes": 300176,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 460063,
+ "scriptRawBytes": 460119,
"scriptRequestCount": 7,
- "totalRawBytes": 460063
+ "totalRawBytes": 460119
},
- "domContentLoadedMedianMs": 114.09999999403954,
+ "domContentLoadedMedianMs": 117.8999999910593,
"id": "editor-canvas",
- "layoutAckMedianMs": 2.2999999970197678,
- "layoutReturnSwitchMedianMs": 54.20000000298023,
- "layoutSwitchMedianMs": 94.29999999701977,
- "loadMedianMs": 114.20000000298023,
- "longestTaskMaxMs": 123,
+ "layoutAckMedianMs": 2.2000000029802322,
+ "layoutReturnSwitchMedianMs": 54.8999999910593,
+ "layoutSwitchMedianMs": 93.70000000298023,
+ "loadMedianMs": 118,
+ "longestTaskMaxMs": 135,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -283,9 +283,9 @@
"largestAssetRawBytes": 746376,
"otherRawBytes": 160728,
"requestCount": 122,
- "scriptRawBytes": 3738942,
+ "scriptRawBytes": 3741846,
"scriptRequestCount": 117,
- "totalRawBytes": 4081869
+ "totalRawBytes": 4084773
},
"resourceLimits": {
"cssRawBytes": 2181,
@@ -294,11 +294,11 @@
"largestAssetRawBytes": 753840,
"otherRawBytes": 162336,
"requestCount": 122,
- "scriptRawBytes": 3776332,
+ "scriptRawBytes": 3779265,
"scriptRequestCount": 117,
- "totalRawBytes": 4122688
+ "totalRawBytes": 4125621
},
- "routeReadyMedianMs": 1047.5,
+ "routeReadyMedianMs": 1060.3999999910593,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "empty"
},
@@ -307,31 +307,31 @@
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 297147,
+ "largestAssetRawBytes": 297203,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 455507,
+ "scriptRawBytes": 455563,
"scriptRequestCount": 7,
- "totalRawBytes": 455507
+ "totalRawBytes": 455563
},
"activatedResourceLimits": {
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 300119,
+ "largestAssetRawBytes": 300176,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 460063,
+ "scriptRawBytes": 460119,
"scriptRequestCount": 7,
- "totalRawBytes": 460063
+ "totalRawBytes": 460119
},
- "domContentLoadedMedianMs": 116.29999999701977,
+ "domContentLoadedMedianMs": 117.59999999403954,
"id": "editor-canvas",
- "layoutAckMedianMs": 2.5,
- "layoutReturnSwitchMedianMs": 51.20000000298023,
- "layoutSwitchMedianMs": 92.29999999701977,
- "loadMedianMs": 116.40000000596046,
- "longestTaskMaxMs": 175,
+ "layoutAckMedianMs": 2.4000000059604645,
+ "layoutReturnSwitchMedianMs": 45.5,
+ "layoutSwitchMedianMs": 92,
+ "loadMedianMs": 117.69999998807907,
+ "longestTaskMaxMs": 185,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -343,9 +343,9 @@
"largestAssetRawBytes": 746376,
"otherRawBytes": 160728,
"requestCount": 122,
- "scriptRawBytes": 3738942,
+ "scriptRawBytes": 3741846,
"scriptRequestCount": 117,
- "totalRawBytes": 4081869
+ "totalRawBytes": 4084773
},
"resourceLimits": {
"cssRawBytes": 2181,
@@ -354,11 +354,11 @@
"largestAssetRawBytes": 753840,
"otherRawBytes": 162336,
"requestCount": 122,
- "scriptRawBytes": 3776332,
+ "scriptRawBytes": 3779265,
"scriptRequestCount": 117,
- "totalRawBytes": 4122688
+ "totalRawBytes": 4125621
},
- "routeReadyMedianMs": 1138.9000000059605,
+ "routeReadyMedianMs": 1155.699999988079,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "representative"
},
@@ -385,12 +385,12 @@
"scriptRequestCount": 6,
"totalRawBytes": 383461
},
- "domContentLoadedMedianMs": 113.59999999403954,
+ "domContentLoadedMedianMs": 118.09999999403954,
"id": "editor-workflow",
- "layoutAckMedianMs": 2.300000011920929,
+ "layoutAckMedianMs": 2.2999999970197678,
"layoutReturnSwitchMedianMs": 33.79999999701977,
- "layoutSwitchMedianMs": 91.29999999701977,
- "loadMedianMs": 113.69999998807907,
+ "layoutSwitchMedianMs": 91.5,
+ "loadMedianMs": 118.29999999701977,
"longestTaskMaxMs": 98,
"owner": "workflow",
"projectSwitchMedianMs": 0,
@@ -403,9 +403,9 @@
"largestAssetRawBytes": 746376,
"otherRawBytes": 160728,
"requestCount": 122,
- "scriptRawBytes": 3647686,
+ "scriptRawBytes": 3650534,
"scriptRequestCount": 116,
- "totalRawBytes": 4006026
+ "totalRawBytes": 4008874
},
"resourceLimits": {
"cssRawBytes": 17748,
@@ -414,11 +414,11 @@
"largestAssetRawBytes": 753840,
"otherRawBytes": 162336,
"requestCount": 122,
- "scriptRawBytes": 3684163,
+ "scriptRawBytes": 3687040,
"scriptRequestCount": 116,
- "totalRawBytes": 4046087
+ "totalRawBytes": 4048963
},
- "routeReadyMedianMs": 1044,
+ "routeReadyMedianMs": 1056,
"scriptSourceOwnerSet": "editor-workflow-static",
"stateProfile": "empty"
},
@@ -445,13 +445,13 @@
"scriptRequestCount": 6,
"totalRawBytes": 383461
},
- "domContentLoadedMedianMs": 120.5,
+ "domContentLoadedMedianMs": 119.8999999910593,
"id": "editor-workflow",
- "layoutAckMedianMs": 2.9000000059604645,
- "layoutReturnSwitchMedianMs": 41.099999994039536,
- "layoutSwitchMedianMs": 125.20000000298023,
- "loadMedianMs": 120.70000000298023,
- "longestTaskMaxMs": 359,
+ "layoutAckMedianMs": 2.7000000029802322,
+ "layoutReturnSwitchMedianMs": 40.599999994039536,
+ "layoutSwitchMedianMs": 133.40000000596046,
+ "loadMedianMs": 120,
+ "longestTaskMaxMs": 358,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -463,9 +463,9 @@
"largestAssetRawBytes": 746376,
"otherRawBytes": 160728,
"requestCount": 122,
- "scriptRawBytes": 3647686,
+ "scriptRawBytes": 3650534,
"scriptRequestCount": 116,
- "totalRawBytes": 4006026
+ "totalRawBytes": 4008874
},
"resourceLimits": {
"cssRawBytes": 17748,
@@ -474,11 +474,11 @@
"largestAssetRawBytes": 753840,
"otherRawBytes": 162336,
"requestCount": 122,
- "scriptRawBytes": 3684163,
+ "scriptRawBytes": 3687040,
"scriptRequestCount": 116,
- "totalRawBytes": 4046087
+ "totalRawBytes": 4048963
},
- "routeReadyMedianMs": 1189.5,
+ "routeReadyMedianMs": 1173.1000000089407,
"scriptSourceOwnerSet": "editor-workflow-static",
"stateProfile": "representative"
},
@@ -505,13 +505,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 114.79999999701977,
+ "domContentLoadedMedianMs": 121,
"id": "editor-gallery",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
- "layoutSwitchMedianMs": 24.899999991059303,
- "loadMedianMs": 114.90000000596046,
- "longestTaskMaxMs": 101,
+ "layoutSwitchMedianMs": 25.900000005960464,
+ "loadMedianMs": 121.09999999403954,
+ "longestTaskMaxMs": 100,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -523,9 +523,9 @@
"largestAssetRawBytes": 746376,
"otherRawBytes": 160728,
"requestCount": 115,
- "scriptRawBytes": 3283435,
+ "scriptRawBytes": 3286283,
"scriptRequestCount": 110,
- "totalRawBytes": 3626362
+ "totalRawBytes": 3629210
},
"resourceLimits": {
"cssRawBytes": 2181,
@@ -534,11 +534,11 @@
"largestAssetRawBytes": 753840,
"otherRawBytes": 162336,
"requestCount": 115,
- "scriptRawBytes": 3316270,
+ "scriptRawBytes": 3319146,
"scriptRequestCount": 110,
- "totalRawBytes": 3662626
+ "totalRawBytes": 3665503
},
- "routeReadyMedianMs": 1262.699999988079,
+ "routeReadyMedianMs": 1274.300000011921,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -565,13 +565,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 116.20000000298023,
+ "domContentLoadedMedianMs": 117.29999999701977,
"id": "editor-gallery",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
- "layoutSwitchMedianMs": 88.59999999403954,
- "loadMedianMs": 116.40000000596046,
- "longestTaskMaxMs": 177,
+ "layoutSwitchMedianMs": 89.3999999910593,
+ "loadMedianMs": 117.5,
+ "longestTaskMaxMs": 190,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -583,9 +583,9 @@
"largestAssetRawBytes": 746376,
"otherRawBytes": 160728,
"requestCount": 115,
- "scriptRawBytes": 3283435,
+ "scriptRawBytes": 3286283,
"scriptRequestCount": 110,
- "totalRawBytes": 3626362
+ "totalRawBytes": 3629210
},
"resourceLimits": {
"cssRawBytes": 2181,
@@ -594,11 +594,11 @@
"largestAssetRawBytes": 753840,
"otherRawBytes": 162336,
"requestCount": 115,
- "scriptRawBytes": 3316270,
+ "scriptRawBytes": 3319146,
"scriptRequestCount": 110,
- "totalRawBytes": 3662626
+ "totalRawBytes": 3665503
},
- "routeReadyMedianMs": 1452.0999999940395,
+ "routeReadyMedianMs": 1454.0999999940395,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
}
@@ -1547,7 +1547,7 @@
"source:src/workbench/canvas-engine/render/floatingSelectionFrame.ts",
"source:src/workbench/canvas-engine/render/fontLoader.ts",
"source:src/workbench/canvas-engine/render/frameDemand.ts",
- "source:src/workbench/canvas-engine/render/groupAdjustmentScopes.ts",
+ "source:src/workbench/canvas-engine/render/groupCompositeScopes.ts",
"source:src/workbench/canvas-engine/render/groupSurfaceCache.ts",
"source:src/workbench/canvas-engine/render/layerCache.ts",
"source:src/workbench/canvas-engine/render/layerDisplayEffect.ts",
@@ -2507,7 +2507,7 @@
"source:src/workbench/canvas-engine/render/floatingSelectionFrame.ts",
"source:src/workbench/canvas-engine/render/fontLoader.ts",
"source:src/workbench/canvas-engine/render/frameDemand.ts",
- "source:src/workbench/canvas-engine/render/groupAdjustmentScopes.ts",
+ "source:src/workbench/canvas-engine/render/groupCompositeScopes.ts",
"source:src/workbench/canvas-engine/render/groupSurfaceCache.ts",
"source:src/workbench/canvas-engine/render/layerCache.ts",
"source:src/workbench/canvas-engine/render/layerDisplayEffect.ts",
@@ -3668,7 +3668,7 @@
"source:src/workbench/canvas-engine/render/floatingSelectionFrame.ts",
"source:src/workbench/canvas-engine/render/fontLoader.ts",
"source:src/workbench/canvas-engine/render/frameDemand.ts",
- "source:src/workbench/canvas-engine/render/groupAdjustmentScopes.ts",
+ "source:src/workbench/canvas-engine/render/groupCompositeScopes.ts",
"source:src/workbench/canvas-engine/render/groupSurfaceCache.ts",
"source:src/workbench/canvas-engine/render/layerCache.ts",
"source:src/workbench/canvas-engine/render/layerDisplayEffect.ts",
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/browserRaster.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/browserRaster.browser.test.ts
index e7b45e885b..4983662699 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/browserRaster.browser.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/browserRaster.browser.test.ts
@@ -286,4 +286,61 @@ describe('real browser raster acceptance', () => {
expect(Array.from(parsed.imageData!.data)).toEqual(expected);
expect(parsed.children?.map((child) => child.name)).toEqual(['Base', 'Group']);
});
+
+ it('writes folder opacity/blend natively and isolates the folder in the merged preview', async () => {
+ const backend = createDomRasterBackend();
+ const fill = (color: string) => {
+ const surface = backend.createSurface(2, 2);
+ surface.ctx.fillStyle = color;
+ surface.ctx.fillRect(0, 0, 2, 2);
+ return surface;
+ };
+ const surfaces = { base: fill('#0000ff'), red: fill('#ff0000'), white: fill('#ffffff') };
+ const leaf = (id: string, name: string) => ({
+ blendMode: 'normal' as const,
+ contentRect: { height: 2, width: 2, x: 0, y: 0 },
+ id,
+ isEnabled: true,
+ name,
+ opacity: 1,
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ });
+ // Opaque red over opaque white inside a 50% folder over a blue base. The
+ // FOLDER composite is pure red, so the preview must be red 50% over blue —
+ // per-leaf flattening would let white bleed through.
+ const plan = planPsdExport([
+ {
+ blendMode: 'normal',
+ children: [leaf('red', 'Red'), leaf('white', 'White')],
+ id: 'g',
+ isEnabled: true,
+ name: 'Faded',
+ opacity: 0.5,
+ type: 'group',
+ },
+ leaf('base', 'Base'),
+ ]);
+ let bytes: ArrayBuffer | null = null;
+ await executePsdExport(plan, 'folder-opacity.psd', {
+ backend,
+ download: (data) => {
+ bytes = data;
+ },
+ getLayerSurface: (id) =>
+ Promise.resolve({ rect: { height: 2, width: 2, x: 0, y: 0 }, surface: surfaces[id as keyof typeof surfaces] }),
+ });
+
+ const reference = backend.createSurface(2, 2);
+ reference.ctx.drawImage(surfaces.base.canvas, 0, 0);
+ reference.ctx.globalAlpha = 0.5;
+ reference.ctx.drawImage(surfaces.red.canvas, 0, 0);
+ const expected = Array.from(reference.ctx.getImageData(0, 0, 2, 2).data);
+
+ const { readPsd } = await import('ag-psd');
+ const parsed = readPsd(bytes!, { useImageData: true });
+ expect(Array.from(parsed.imageData!.data)).toEqual(expected);
+ const folder = parsed.children!.find((child) => child.name === 'Faded')!;
+ expect(folder.opacity).toBeCloseTo(0.5, 2);
+ expect(folder.blendMode).toBe('normal');
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts
index 006f797988..7daf424d54 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts
@@ -356,6 +356,10 @@ export interface CanvasGroupContract {
isEnabled: boolean;
isLocked: boolean;
isHidden?: boolean;
+ /** Raster-stack groups only; absent means 1. Applies to the group's isolated composite. */
+ opacity?: number;
+ /** Raster-stack groups only; absent means 'normal'. Applies to the group's isolated composite. */
+ blendMode?: CanvasBlendMode;
adjustments?: CanvasAdjustmentsContract;
/** Index 0 is the top-most child. */
children: CanvasNodeContract[];
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts
index b0084d3d94..c0c6742246 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts
@@ -17,13 +17,13 @@ import { haveSameStructure } from '@workbench/canvas-engine/document/layerStacks
import { mergeDownMatrix } from '@workbench/canvas-engine/document/mergeDown';
import { canMergeSelectedRasters, getMergeVisibleRasterLeaves } from '@workbench/canvas-engine/document/mergeVisible';
import { isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';
-import { applyAdjustments } from '@workbench/canvas-engine/render/adjustments';
+import { applyAdjustments, isIdentityAdjustments } from '@workbench/canvas-engine/render/adjustments';
import { blendToComposite } from '@workbench/canvas-engine/render/compositor';
import {
- collectAdjustedGroups,
- planGroupAdjustmentScopes,
- type GroupAdjustmentScope,
-} from '@workbench/canvas-engine/render/groupAdjustmentScopes';
+ collectCompositedGroups,
+ planGroupCompositeScopes,
+ type GroupCompositeScope,
+} from '@workbench/canvas-engine/render/groupCompositeScopes';
import type { CanvasMutationContext } from './mutationContext';
@@ -209,8 +209,8 @@ export class MergeLayerController {
}
// Leaf identity misses a mid-await ancestor-stack edit or an order-preserving
// re-parent; the scope plan folds both.
- const scopes = planGroupAdjustmentScopes(contributorLeaves, collectAdjustedGroups(document));
- const liveScopes = planGroupAdjustmentScopes(liveLeaves, collectAdjustedGroups(liveDocument));
+ const scopes = planGroupCompositeScopes(contributorLeaves, collectCompositedGroups(document));
+ const liveScopes = planGroupCompositeScopes(liveLeaves, collectCompositedGroups(liveDocument));
if (JSON.stringify(liveScopes) !== JSON.stringify(scopes)) {
return 'not-ready';
}
@@ -234,7 +234,7 @@ export class MergeLayerController {
target: RasterSurface['ctx'],
from: number,
to: number,
- range: readonly GroupAdjustmentScope[]
+ range: readonly GroupCompositeScope[]
): void => {
let scopeIndex = range.length - 1;
for (let index = to - 1; index >= from;) {
@@ -244,11 +244,13 @@ export class MergeLayerController {
buffer.ctx.setTransform(1, 0, 0, 1, 0, 0);
buffer.ctx.clearRect(0, 0, rect.width, rect.height);
drawMerged(buffer.ctx, scope.start, scope.end, scope.children);
- const scoped = buffer.ctx.getImageData(0, 0, rect.width, rect.height);
- applyAdjustments(scoped, scope.adjustments);
- buffer.ctx.putImageData(scoped, 0, 0);
- target.globalAlpha = 1;
- target.globalCompositeOperation = 'source-over';
+ if (!isIdentityAdjustments(scope.adjustments)) {
+ const scoped = buffer.ctx.getImageData(0, 0, rect.width, rect.height);
+ applyAdjustments(scoped, scope.adjustments);
+ buffer.ctx.putImageData(scoped, 0, 0);
+ }
+ target.globalAlpha = scope.opacity;
+ target.globalCompositeOperation = blendToComposite(scope.blendMode);
target.drawImage(buffer.canvas, 0, 0);
index = scope.start - 1;
scopeIndex -= 1;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts
index 6b380db2ac..70af53fbc2 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts
@@ -14,6 +14,7 @@ import {
type ExecutePsdExportDeps,
type PsdExportNodeInput,
type PsdExportPlan,
+ type PsdPlanNode,
} from '@workbench/canvas-engine/export/psdExport';
import { isExportableRasterLayer } from '@workbench/canvas-engine/layerExportGuards';
import { isIdentityAdjustments } from '@workbench/canvas-engine/render/adjustments';
@@ -41,8 +42,19 @@ export const PSD_ALLOCATION_BYTES_PER_PIXEL = 8;
export const derivePsdPixelAreaLimit = (availableBytes: number): number =>
Math.max(0, Math.floor(availableBytes / PSD_ALLOCATION_BYTES_PER_PIXEL));
+const countIsolatedFolders = (nodes: readonly PsdPlanNode[]): number =>
+ nodes.reduce(
+ (total, node) =>
+ node.kind === 'folder'
+ ? total +
+ countIsolatedFolders(node.children) +
+ (node.opacity !== 1 || node.compositeBlend !== 'source-over' ? 1 : 0)
+ : total,
+ 0
+ );
+
const getRequiredAllocationPixelArea = (plan: Extract<PsdExportPlan, { status: 'ok' }>): number =>
- plan.width * plan.height +
+ plan.width * plan.height * (1 + countIsolatedFolders(plan.tree)) +
plan.layers.reduce((total, layer) => total + layer.worldRect.width * layer.worldRect.height, 0);
/** Owns immutable PSD snapshot capture, budget reservation, execution, and cancellation. */
@@ -107,10 +119,12 @@ export class PsdExportController {
: [...ancestorStacks, node.adjustments!];
return [
{
+ blendMode: node.blendMode,
children: toInputs(node.children, stacks),
id: node.id,
isEnabled: node.isEnabled,
name: node.name,
+ opacity: node.opacity,
type: 'group',
},
];
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts
index 6f3635c0ea..dd030397a3 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts
@@ -623,15 +623,47 @@ describe('createDocumentModel', () => {
});
expect(after.canvas.document.stacks.raster[1]).toMatchObject({ isEnabled: false, name: 'Folder' });
expect(edit.inverse).toEqual({ id: 'G', patch: { isEnabled: true, name: 'G' }, type: 'updateCanvasLayer' });
- expect(modelOf(project).prepare({ id: 'G', patch: { opacity: 0.5 }, type: 'patch' })).toMatchObject({
- actual: 'group',
- status: 'wrong-type',
- });
expect(modelOf(project).prepare({ id: 'G', patch: { transform: { x: 1 } }, type: 'patch' })).toMatchObject({
status: 'wrong-type',
});
});
+ it('patches opacity and blend on a raster-stack group, with an inverse restoring absence', () => {
+ const project = projectWith(tree(), 'G');
+ const { after, edit } = roundTrip(project, {
+ id: 'G',
+ patch: { blendMode: 'multiply', opacity: 0.5 },
+ type: 'patch',
+ });
+ expect(after.canvas.document.stacks.raster[1]).toMatchObject({ blendMode: 'multiply', opacity: 0.5 });
+ expect(edit.inverse).toEqual({
+ id: 'G',
+ patch: { blendMode: undefined, opacity: undefined },
+ type: 'updateCanvasLayer',
+ });
+ });
+
+ it('refuses opacity and blend on an overlay-stack group and on a locked group', () => {
+ const overlay = projectWith([group('OG', [layer('c1', 'control')])], null);
+ expect(modelOf(overlay).prepare({ id: 'OG', patch: { opacity: 0.5 }, type: 'patch' })).toEqual({
+ operation: 'blend an overlay-stack group',
+ status: 'unsupported',
+ });
+ expect(modelOf(overlay).prepare({ id: 'OG', patch: { blendMode: 'multiply' }, type: 'patch' })).toEqual({
+ operation: 'blend an overlay-stack group',
+ status: 'unsupported',
+ });
+ // Renaming a locked group stays allowed; its appearance does not.
+ const locked = projectWith([group('LG', [layer('r1')], { isLocked: true })], null);
+ expect(modelOf(locked).prepare({ id: 'LG', patch: { opacity: 0.5 }, type: 'patch' })).toEqual({
+ ids: ['LG'],
+ status: 'locked',
+ });
+ expect(modelOf(locked).prepare({ id: 'LG', patch: { name: 'renamed' }, type: 'patch' })).toMatchObject({
+ status: 'prepared',
+ });
+ });
+
it('takes a pre-gesture baseline so a previewed patch still records a real inverse', () => {
const previewed = applyCanvasProjectMutation(projectWith(flat(), 'r1'), {
id: 'r1',
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts
index 2fcc784845..81de16c12d 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts
@@ -42,7 +42,7 @@ import {
reorderSiblings,
} from '@workbench/canvas-engine/document/layerStacks';
import { repairSelectedLayerId } from '@workbench/canvas-engine/document/selectionRepair';
-import { GROUP_PATCH_KEYS } from '@workbench/canvas-engine/mutationContracts';
+import { GROUP_PATCH_KEYS, LOCK_EXEMPT_PATCH_KEYS } from '@workbench/canvas-engine/mutationContracts';
import type {
DocumentCommand,
@@ -1122,11 +1122,21 @@ export const createDocumentModel = (
status: 'wrong-type',
};
}
+ // Opacity/blend apply to a group's isolated composite; overlay groups
+ // composite coverage, so the fields are meaningless there (the same rule
+ // as group adjustments).
+ if ((command.patch.opacity !== undefined || command.patch.blendMode !== undefined) && entry.stack !== 'raster') {
+ return { operation: 'blend an overlay-stack group', status: 'unsupported' };
+ }
}
if (command.before && !sameKeys(command.before, command.patch, PATCH_CONTAINERS)) {
return { operation: 'patch baseline names other fields', status: 'unsupported' };
}
- if ((Object.keys(command.patch) as (keyof CanvasLayerBasePatch)[]).some((key) => !GROUP_PATCH_KEYS.includes(key))) {
+ if (
+ (Object.keys(command.patch) as (keyof CanvasLayerBasePatch)[]).some(
+ (key) => !LOCK_EXEMPT_PATCH_KEYS.includes(key)
+ )
+ ) {
const locked = frozenBy(index, entry);
if (locked.length > 0) {
return { ids: locked, status: 'locked' };
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/postconditions.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/postconditions.ts
index 14f1327742..a3e1ec6bd8 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/postconditions.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/postconditions.ts
@@ -55,7 +55,10 @@ export const sameValue = (left: unknown, right: unknown): boolean => {
export const isPatchApplied = (node: CanvasNodeContract, patch: CanvasLayerBasePatch): boolean =>
(Object.keys(patch) as (keyof CanvasLayerBasePatch)[]).every((key) => {
if (isGroupNode(node)) {
- return GROUP_PATCH_KEYS.includes(key) && node[key as 'name' | 'isEnabled' | 'isLocked'] === patch[key];
+ return (
+ GROUP_PATCH_KEYS.includes(key) &&
+ node[key as 'name' | 'isEnabled' | 'isLocked' | 'opacity' | 'blendMode'] === patch[key]
+ );
}
return key === 'transform'
? (Object.keys(patch.transform ?? {}) as (keyof CanvasLayerContract['transform'])[]).every(
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.ts
index 97ca8b0636..95645149ff 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.ts
@@ -234,7 +234,7 @@ describe('createDocumentMirror', () => {
const sourceSwap: CanvasDocumentContractV3 = {
...doc,
stacks: stacksFrom([
- { ...swapped, source: { image: { height: 10, imageName: 'a-v2', width: 10 }, type: 'image' } },
+ { ...swapped, source: { image: { height: 10, imageName: 'a-v2', width: 10 }, type: 'image' as const } },
]),
};
store.setState({ projects: [{ canvas: { ...canvas, document: sourceSwap }, id: 'p1' }] });
@@ -263,7 +263,7 @@ describe('createDocumentMirror', () => {
// changed but NOT source-changed — invalidating would clear unflushed strokes.
const fillEdit: CanvasDocumentContractV3 = {
...doc,
- stacks: stacksFrom([{ ...mask, mask: { bitmap: null, fill: { color: '#00ff00', style: 'grid' } } }]),
+ stacks: stacksFrom([{ ...mask, mask: { bitmap: null, fill: { color: '#00ff00', style: 'grid' as const } } }]),
};
store.setState({ projects: [{ canvas: { ...canvas, document: fillEdit }, id: 'p1' }] });
expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['m'], []);
@@ -513,6 +513,26 @@ describe('createDocumentMirror: groups', () => {
expect(callbacks.onLayerOrderChanged).not.toHaveBeenCalled();
});
+ it('fans a group opacity or blend edit out to descendants on the same recomposite channel', () => {
+ const a = rasterLayer('a');
+ const b = rasterLayer('b');
+ const doc = makeDoc([groupContract('g', [a, groupContract('h', [b])])]);
+ const { callbacks, set } = setup(doc);
+
+ set({ ...doc, stacks: stacksFrom([groupContract('g', [a, groupContract('h', [b])], { opacity: 0.5 })]) });
+ expect(callbacks.onLayersChanged).not.toHaveBeenCalled();
+ expect(callbacks.onLayersRecomposite).toHaveBeenLastCalledWith(['a', 'b']);
+
+ set({
+ ...doc,
+ stacks: stacksFrom([
+ groupContract('g', [a, groupContract('h', [b], { blendMode: 'multiply' })], { opacity: 0.5 }),
+ ]),
+ });
+ expect(callbacks.onLayersChanged).not.toHaveBeenCalled();
+ expect(callbacks.onLayersRecomposite).toHaveBeenLastCalledWith(['b']);
+ });
+
it('stays silent on a group rename that changes no leaf and no structure', () => {
const a = rasterLayer('a');
const doc = makeDoc([groupContract('g', [a])]);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts
index fa512ab041..4551414ced 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts
@@ -112,7 +112,13 @@ const diffForests = (prev: CanvasDocumentIndex, next: CanvasDocumentIndex): Fore
restructured = true;
}
if (isGroupNode(entry.node)) {
- if (before.node !== entry.node && (before.node as typeof entry.node).adjustments !== entry.node.adjustments) {
+ const beforeGroup = before.node as typeof entry.node;
+ if (
+ before.node !== entry.node &&
+ (beforeGroup.adjustments !== entry.node.adjustments ||
+ beforeGroup.opacity !== entry.node.opacity ||
+ beforeGroup.blendMode !== entry.node.blendMode)
+ ) {
adjustedGroups.add(entry.node.id);
}
continue;
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 df629a10c0..120faadaa3 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -1887,7 +1887,7 @@ describe('createCanvasEngine', () => {
stacks: stacksFrom([
{
...layer,
- source: { bitmap: { height: 20, imageName: 'paint-pixels', width: 20 }, type: 'paint' },
+ source: { bitmap: { height: 20, imageName: 'paint-pixels', width: 20 }, type: 'paint' as const },
},
]),
};
@@ -4963,7 +4963,7 @@ describe('requestLayerThumbnail', () => {
setDocument({
...doc,
stacks: stacksFrom([
- { ...second, source: { bitmap: { height: 10, imageName: 'new', width: 10 }, type: 'paint' } },
+ { ...second, source: { bitmap: { height: 10, imageName: 'new', width: 10 }, type: 'paint' as const } },
]),
});
expect(bitmap.close).toHaveBeenCalledTimes(1);
@@ -5428,7 +5428,9 @@ describe('mergeLayerDown', () => {
...doc,
stacks: stacksFrom(
getDocumentLeaves(doc).map((layer) =>
- layer.id === emptyId ? { ...layer, source: { bitmap: null, offset: { x: 0, y: 0 }, type: 'paint' } } : layer
+ layer.id === emptyId
+ ? { ...layer, source: { bitmap: null, offset: { x: 0, y: 0 }, type: 'paint' as const } }
+ : layer
)
),
};
@@ -5826,7 +5828,7 @@ describe('extract masked canvas area', () => {
...maskLayer('mask'),
mask: {
bitmap: { height: 20, imageName: 'mask-bitmap', width: 20 },
- fill: { color: '#e07575', style: 'diagonal' },
+ fill: { color: '#e07575', style: 'diagonal' as const },
offset: { x: 15, y: 25 },
},
},
@@ -6046,7 +6048,7 @@ describe('extract masked canvas area', () => {
source: {
bitmap: { height: 40, imageName: 'upper-v2', width: 40 },
offset: { x: 0, y: 0 },
- type: 'paint',
+ type: 'paint' as const,
},
}
: layer
@@ -14072,7 +14074,10 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',
stacks: stacksFrom([
{
...layer,
- source: { bitmap: { contentHash: 'h', height: 100, imageName: 'persisted', width: 100 }, type: 'paint' },
+ source: {
+ bitmap: { contentHash: 'h', height: 100, imageName: 'persisted', width: 100 },
+ type: 'paint' as const,
+ },
},
]),
});
@@ -14122,7 +14127,7 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',
setDocument({
...doc2,
stacks: stacksFrom([
- { ...imgLayer, source: { image: { height: 10, imageName: 'a-v2', width: 10 }, type: 'image' } },
+ { ...imgLayer, source: { image: { height: 10, imageName: 'a-v2', width: 10 }, type: 'image' as const } },
]),
});
raf.flush();
@@ -14349,7 +14354,7 @@ describe('hasExportableLayerContent', () => {
// cache synchronously. Do not run the scheduled frame that would rebuild it.
setDocument({
...doc,
- stacks: stacksFrom([{ ...layer, source: { bitmap: null, type: 'paint' } }]),
+ stacks: stacksFrom([{ ...layer, source: { bitmap: null, type: 'paint' as const } }]),
});
const { target } = createThumbnailTarget();
expect(engine.previews.drawLayerThumbnail('stale-paint', target, 96)).toBe(true);
@@ -18042,7 +18047,7 @@ describe('Select Object canvas engine integration', () => {
stacks: stacksFrom([
{
...outside,
- source: { image: { height: 10, imageName: 'inside.png', width: 10 }, type: 'image' },
+ source: { image: { height: 10, imageName: 'inside.png', width: 10 }, type: 'image' as const },
},
]),
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.test.ts
index 33f872f564..8b1d269cb4 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.test.ts
@@ -234,6 +234,83 @@ describe('planPsdExport — folders', () => {
expect(names(plan.tree)).toEqual(['Root']);
});
+ it('plans folder opacity and blend (defaulting when absent) and reports unmapped folder blends', () => {
+ const plan = planPsdExport([
+ group('plain', [layer({ id: 'p1' })]),
+ { ...group('styled', [layer({ id: 's1' })]), blendMode: 'multiply', opacity: 0.25 },
+ { ...group('odd', [layer({ id: 'o1' })]), blendMode: 'plasma' as CanvasBlendMode },
+ ]);
+ if (plan.status !== 'ok') {
+ throw new Error(plan.status);
+ }
+ const folders = plan.tree.filter((node): node is PsdPlanFolder => node.kind === 'folder');
+ // A default group is pass-through; writing 'normal' would isolate it in
+ // Photoshop and change how members blend with layers below the group.
+ expect(folders.find((f) => f.id === 'plain')).toMatchObject({
+ blendMode: 'pass through',
+ compositeBlend: 'source-over',
+ opacity: 1,
+ });
+ expect(folders.find((f) => f.id === 'styled')).toMatchObject({
+ blendMode: 'multiply',
+ compositeBlend: 'multiply',
+ opacity: 0.25,
+ });
+ // An unmapped blend still isolates (it is non-normal); only the KEY falls back.
+ expect(folders.find((f) => f.id === 'odd')).toMatchObject({ blendMode: 'normal' });
+ expect(plan.unmappedBlends).toEqual(['plasma']);
+ });
+
+ it('round-trips folder opacity and blend through ag-psd', async () => {
+ const plan = planPsdExport([
+ { ...group('Styled', [layer({ id: 'in', name: 'In' })]), blendMode: 'screen', opacity: 0.5 },
+ layer({ id: 'base', name: 'Base' }),
+ ]);
+ const backend = createTestStubRasterBackend();
+ const imageDataOf = (width: number, height: number): ImageData =>
+ ({ data: new Uint8ClampedArray(width * height * 4), height, width }) as ImageData;
+ let bytes: ArrayBuffer | null = null;
+ await executePsdExport(plan, 'styled.psd', {
+ backend,
+ download: (data) => {
+ bytes = data;
+ },
+ getLayerSurface: () =>
+ Promise.resolve({ rect: { height: 50, width: 100, x: 0, y: 0 }, surface: backend.createSurface(100, 50) }),
+ readImageData: (_surface, rect) => imageDataOf(rect.width, rect.height),
+ writeImageData: () => undefined,
+ writePsd: (psd) => Promise.resolve(writePsd(psd, { generateThumbnail: false })),
+ });
+ const parsed = readPsd(bytes!, { skipCompositeImageData: true, skipLayerImageData: true, skipThumbnail: true });
+ const folder = parsed.children!.find((child) => child.name === 'Styled')!;
+ expect(folder.blendMode).toBe('screen');
+ expect(folder.opacity).toBeCloseTo(0.5, 2);
+ });
+
+ it('round-trips a default folder as pass-through', async () => {
+ const plan = planPsdExport([
+ group('Plain', [layer({ id: 'in', name: 'In' })]),
+ layer({ id: 'base', name: 'Base' }),
+ ]);
+ const backend = createTestStubRasterBackend();
+ const imageDataOf = (width: number, height: number): ImageData =>
+ ({ data: new Uint8ClampedArray(width * height * 4), height, width }) as ImageData;
+ let bytes: ArrayBuffer | null = null;
+ await executePsdExport(plan, 'plain.psd', {
+ backend,
+ download: (data) => {
+ bytes = data;
+ },
+ getLayerSurface: () =>
+ Promise.resolve({ rect: { height: 50, width: 100, x: 0, y: 0 }, surface: backend.createSurface(100, 50) }),
+ readImageData: (_surface, rect) => imageDataOf(rect.width, rect.height),
+ writeImageData: () => undefined,
+ writePsd: (psd) => Promise.resolve(writePsd(psd, { generateThumbnail: false })),
+ });
+ const parsed = readPsd(bytes!, { skipCompositeImageData: true, skipLayerImageData: true, skipThumbnail: true });
+ expect(parsed.children!.find((child) => child.name === 'Plain')!.blendMode).toBe('pass through');
+ });
+
it('round-trips folder hierarchy, order, names and leaf properties through ag-psd', async () => {
const plan = planPsdExport([
group('Shading', [layer({ blendMode: 'multiply', id: 'shade', name: 'Shade', opacity: 0.5 })], false),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.ts
index 0cf4b24f37..ae5f62f283 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/export/psdExport.ts
@@ -111,13 +111,17 @@ export interface PsdExportLayerInput {
adjustments?: CanvasAdjustmentsContract;
}
-/** A raster group: a pass-through folder in the PSD, children top-first. */
+/** A raster group: a folder in the PSD, children top-first. */
export interface PsdExportGroupInput {
type: 'group';
id: string;
name: string;
/** The group's own flag; a disabled group is a hidden folder. */
isEnabled: boolean;
+ /** 0..1; PSD folders carry opacity natively. Absent means 1. */
+ opacity?: number;
+ /** PSD folders carry a blend mode natively. Absent means 'normal'. */
+ blendMode?: CanvasBlendMode;
children: readonly PsdExportNodeInput[];
}
@@ -159,6 +163,11 @@ export interface PsdPlanFolder {
id: string;
name: string;
hidden: boolean;
+ /** 0..1; written onto the folder, and applied when the preview isolates it. */
+ opacity: number;
+ blendMode: BlendMode;
+ /** Canvas `globalCompositeOperation` for the flattened composite preview. */
+ compositeBlend: GlobalCompositeOperation;
children: PsdPlanNode[];
}
@@ -289,7 +298,27 @@ export const planPsdExport = (
if (isGroupInput(node)) {
const children = buildTree(node.children);
if (children.length > 0) {
- out.push({ children, hidden: !node.isEnabled, id: node.id, kind: 'folder', name: node.name });
+ const blendMode = node.blendMode ?? 'normal';
+ const opacity = clamp01(node.opacity ?? 1);
+ // A default group is PASS-THROUGH: its members blend with what is
+ // below the group. Photoshop's folder default is the same, so only a
+ // group that actually composites in isolation (opacity or blend)
+ // gets an isolating folder blend key.
+ const isolated = opacity !== 1 || blendMode !== 'normal';
+ const mapped = BLEND_MODE_TO_PSD[blendMode];
+ if (!mapped) {
+ unmappedBlends.add(blendMode);
+ }
+ out.push({
+ blendMode: isolated ? (mapped ?? 'normal') : 'pass through',
+ children,
+ compositeBlend: blendToComposite(blendMode),
+ hidden: !node.isEnabled,
+ id: node.id,
+ kind: 'folder',
+ name: node.name,
+ opacity,
+ });
}
continue;
}
@@ -456,26 +485,58 @@ export const executePsdExport = async (
const toChildren = (nodes: readonly PsdPlanNode[]): AgPsdLayer[] =>
nodes.map((node) =>
node.kind === 'folder'
- ? { children: toChildren(node.children), hidden: node.hidden, name: node.name, opened: true }
+ ? {
+ blendMode: node.blendMode,
+ children: toChildren(node.children),
+ hidden: node.hidden,
+ name: node.name,
+ opacity: node.opacity,
+ opened: true,
+ }
: bakedById.get(node.id)!
);
const children = toChildren(plan.tree);
- // Flatten the contributing layers (bottom-to-top = plan order) into the merged
- // composite the PSD carries as its full-document preview.
+ // Flatten the contributing tree (bottom-to-top at every level) into the merged
+ // composite the PSD carries as its full-document preview. A folder with
+ // non-default opacity/blend is isolated into a buffer first — readers apply
+ // those properties to the folder's composite, and the preview must match the
+ // file's own layers.
throwIfAborted(deps.signal);
+ const surfaceById = new Map(baked.map(({ planLayer, surface }) => [planLayer.id, surface]));
+ const drawPreview = (ctx: Ctx, nodes: readonly PsdPlanNode[]): void => {
+ for (const node of nodes) {
+ if (node.hidden) {
+ continue;
+ }
+ if (node.kind === 'folder') {
+ if (node.opacity === 1 && node.compositeBlend === 'source-over') {
+ drawPreview(ctx, node.children);
+ continue;
+ }
+ const buffer = deps.backend.createSurface(plan.width, plan.height);
+ setTransform(buffer.ctx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
+ buffer.ctx.clearRect(0, 0, plan.width, plan.height);
+ drawPreview(buffer.ctx, node.children);
+ ctx.globalAlpha = node.opacity;
+ ctx.globalCompositeOperation = node.compositeBlend;
+ ctx.drawImage(buffer.canvas, 0, 0);
+ continue;
+ }
+ const surface = surfaceById.get(node.id);
+ if (!surface) {
+ continue;
+ }
+ ctx.globalAlpha = node.opacity;
+ ctx.globalCompositeOperation = node.compositeBlend;
+ ctx.drawImage(surface.canvas, node.left, node.top);
+ }
+ };
const composite = deps.backend.createSurface(plan.width, plan.height);
const cctx = composite.ctx;
setTransform(cctx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
cctx.clearRect(0, 0, plan.width, plan.height);
- for (const { planLayer, surface } of baked) {
- if (!planLayer.contributes) {
- continue;
- }
- cctx.globalAlpha = planLayer.opacity;
- cctx.globalCompositeOperation = planLayer.compositeBlend;
- cctx.drawImage(surface.canvas, planLayer.left, planLayer.top);
- }
+ drawPreview(cctx, plan.tree);
cctx.globalAlpha = 1;
cctx.globalCompositeOperation = 'source-over';
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts
index 5e3c277d84..477f717b7d 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts
@@ -25,13 +25,22 @@ import type {
import type { CanvasNodeInsertion, CanvasNodeInsertionAnchor, CanvasNodeMove } from './document/insertionAnchors';
import type { ReorderSiblingsCommand } from './document/layerStacks';
-/** Base fields a node accepts; a group takes only `name`, `isEnabled` and `isLocked`. */
+/** Base fields a node accepts; a group takes `name`, `isEnabled`, `isLocked`, `opacity` and `blendMode`. */
export type CanvasLayerBasePatch = Partial<
Pick<CanvasLayerBaseContract, 'name' | 'isEnabled' | 'isLocked' | 'opacity' | 'blendMode'>
> & { transform?: Partial<CanvasLayerBaseContract['transform']> };
/** The base fields a group carries; anything else in a patch does not apply to it. */
-export const GROUP_PATCH_KEYS: readonly (keyof CanvasLayerBasePatch)[] = ['name', 'isEnabled', 'isLocked'];
+export const GROUP_PATCH_KEYS: readonly (keyof CanvasLayerBasePatch)[] = [
+ 'name',
+ 'isEnabled',
+ 'isLocked',
+ 'opacity',
+ 'blendMode',
+];
+
+/** Patch keys allowed on a locked node (renaming or unlocking never needs the lock lifted first). */
+export const LOCK_EXEMPT_PATCH_KEYS: readonly (keyof CanvasLayerBasePatch)[] = ['name', 'isEnabled', 'isLocked'];
export type CanvasLayerConfigPatch =
| {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
index 807740860d..aee8f2d1d3 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
@@ -32,12 +32,12 @@ import { fromTRS, multiply } from '@workbench/canvas-engine/math/mat2d';
import { intersect, isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';
import type { DerivedSurfaceCache } from './derivedSurfaceCache';
-import type { GroupAdjustmentScope } from './groupAdjustmentScopes';
+import type { GroupCompositeScope } from './groupCompositeScopes';
import type { LayerCacheEntry, LayerCacheStore } from './layerCache';
import type { RasterBackend, RasterSurface } from './raster';
import { renderControlTransparency } from './controlTransparency';
-import { collectAdjustedGroups, planGroupAdjustmentScopes } from './groupAdjustmentScopes';
+import { collectCompositedGroups, planGroupCompositeScopes } from './groupCompositeScopes';
import { colorizeMask } from './maskFill';
/** Screen-space size (px) of each checkerboard square for transparent backgrounds. */
@@ -207,7 +207,7 @@ export interface CompositeOptions {
*/
groupSurface?:
| ((
- scope: GroupAdjustmentScope,
+ scope: GroupCompositeScope,
members: readonly SemanticLeaf[],
memberMatrices: readonly Mat2d[],
excludeIds: ReadonlySet<string>
@@ -622,7 +622,7 @@ export const compositeDocument = (
});
// Isolation mode inspects raw members, so scopes are bypassed while active.
const scopes =
- opts.groupSurface && !isIsolated(opts) ? planGroupAdjustmentScopes(plan.leaves, collectAdjustedGroups(doc)) : [];
+ opts.groupSurface && !isIsolated(opts) ? planGroupCompositeScopes(plan.leaves, collectCompositedGroups(doc)) : [];
let scopeIndex = 0;
const drawLeafFlat = (leaf: SemanticLeaf): void => {
@@ -664,8 +664,8 @@ export const compositeDocument = (
const result = opts.groupSurface!(scope, members, matrices, excluded);
if (result) {
ctx.save();
- ctx.globalAlpha = 1;
- ctx.globalCompositeOperation = 'source-over';
+ ctx.globalAlpha = scope.opacity;
+ ctx.globalCompositeOperation = blendToComposite(scope.blendMode);
setTransformFromMat(ctx, view);
ctx.drawImage(result.surface.canvas, result.rect.x, result.rect.y);
ctx.restore();
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 f7916e4587..89265e7103 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
@@ -195,6 +195,104 @@ describe('group adjustment composite', () => {
expect(adjusted?.r).toBe(255 - 0x40);
});
+ it('applies group opacity to the isolated composite, matching the export renderer', async () => {
+ // Opaque red over opaque white inside a 50%-opacity group, over a blue
+ // base: the GROUP composite is pure red (white hidden underneath), so the
+ // result is red 50% over blue. Per-leaf opacity instead would let white
+ // bleed through inside the group.
+ const document = docWith([groupContract('g', [raster('red'), raster('white')], { opacity: 0.5 }), raster('under')]);
+ const scene = sceneFor({ red: '#ff0000', under: '#0000ff', white: '#ffffff' });
+ const plan = planBaseRasterComposite(document, BBOX);
+ expect(plan.groupScopes).toHaveLength(1);
+ const exported = await renderRasterComposite(plan, scene);
+ const [r, g, b] = centerPixel(exported);
+ expect(Math.abs(r! - 128)).toBeLessThanOrEqual(2);
+ expect(g).toBe(0);
+ expect(Math.abs(b! - 128)).toBeLessThanOrEqual(2);
+
+ const groupSurfaces = createGroupSurfaceCache({
+ createSurface: (w, h) => scene.backend.createSurface(w, h),
+ getAdjustedSurface: () => null,
+ getCacheEntry: (id) => scene.caches.get(id),
+ });
+ const screen = scene.backend.createSurface(WIDTH, HEIGHT);
+ compositeDocument(screen, document, scene.caches, identity(), {
+ backend: scene.backend,
+ groupSurface: (scope, members, matrices, exclude) => groupSurfaces.get(scope, members, matrices, exclude),
+ });
+ const screenPx = centerPixel(screen);
+ const exportPx = centerPixel(exported);
+ for (let channel = 0; channel < 4; channel += 1) {
+ expect(Math.abs(screenPx[channel]! - exportPx[channel]!)).toBeLessThanOrEqual(1);
+ }
+ });
+
+ it('applies group blend mode when the isolated composite lands, on screen and in export', async () => {
+ // Mid-gray group multiplied over a white base: 0x80 × 0xff = 0x80. A
+ // per-leaf multiply would be identical here, so also nest: outer normal
+ // group holding a multiply group proves the landing applies INSIDE parents.
+ const document = docWith([groupContract('g', [raster('gray')], { blendMode: 'multiply' }), raster('under')]);
+ const scene = sceneFor({ gray: '#808080', under: '#ffffff' });
+ const exported = await renderRasterComposite(planBaseRasterComposite(document, BBOX), scene);
+ expect(Math.abs(centerPixel(exported)[0]! - 0x80)).toBeLessThanOrEqual(1);
+
+ const nested = docWith([
+ groupContract('outer', [groupContract('inner', [raster('gray')], { blendMode: 'multiply' }), raster('mid')], {
+ adjustments: invertStack('oa'),
+ }),
+ ]);
+ const nestedScene = sceneFor({ gray: '#808080', mid: '#c0c0c0' });
+ // inner multiplies onto mid inside outer's buffer: 0x80×0xc0/0xff ≈ 0x60;
+ // outer's invert flips it to ≈ 0x9f.
+ const nestedExport = await renderRasterComposite(planBaseRasterComposite(nested, BBOX), nestedScene);
+ expect(Math.abs(centerPixel(nestedExport)[0]! - (255 - 0x60))).toBeLessThanOrEqual(3);
+
+ const groupSurfaces = createGroupSurfaceCache({
+ createSurface: (w, h) => nestedScene.backend.createSurface(w, h),
+ getAdjustedSurface: () => null,
+ getCacheEntry: (id) => nestedScene.caches.get(id),
+ });
+ const screen = nestedScene.backend.createSurface(WIDTH, HEIGHT);
+ compositeDocument(screen, nested, nestedScene.caches, identity(), {
+ backend: nestedScene.backend,
+ groupSurface: (scope, members, matrices, exclude) => groupSurfaces.get(scope, members, matrices, exclude),
+ });
+ const screenPx = centerPixel(screen);
+ const exportPx = centerPixel(nestedExport);
+ for (let channel = 0; channel < 4; channel += 1) {
+ expect(Math.abs(screenPx[channel]! - exportPx[channel]!)).toBeLessThanOrEqual(1);
+ }
+ });
+
+ it('reuses the cached group surface across an opacity scrub (only the landing changes)', () => {
+ const scene = sceneFor({ red: '#ff0000' });
+ let builds = 0;
+ const groupSurfaces = createGroupSurfaceCache({
+ createSurface: (w, h) => {
+ builds += 1;
+ return scene.backend.createSurface(w, h);
+ },
+ getAdjustedSurface: () => null,
+ getCacheEntry: (id) => scene.caches.get(id),
+ });
+ const compositeAt = (opacity: number) => {
+ const document = docWith([groupContract('g', [raster('red')], { opacity })]);
+ const screen = scene.backend.createSurface(WIDTH, HEIGHT);
+ compositeDocument(screen, document, scene.caches, identity(), {
+ backend: scene.backend,
+ groupSurface: (scope, members, matrices, exclude) => groupSurfaces.get(scope, members, matrices, exclude),
+ });
+ return centerPixel(screen);
+ };
+ const at30 = compositeAt(0.3);
+ const at60 = compositeAt(0.6);
+ const at90 = compositeAt(0.9);
+ expect(builds).toBe(1);
+ expect(Math.abs(at30[3]! - 77)).toBeLessThanOrEqual(2);
+ expect(Math.abs(at60[3]! - 153)).toBeLessThanOrEqual(2);
+ expect(Math.abs(at90[3]! - 230)).toBeLessThanOrEqual(2);
+ });
+
it('holds two keys per group so alternating consumers (frame vs overview) stop rebuilding', () => {
// A transform session makes the frame composite session matrices while the
// overview composites the settled contract: two keys for one group, forever
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupAdjustmentScopes.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupAdjustmentScopes.test.ts
deleted file mode 100644
index bb3cbe3239..0000000000
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupAdjustmentScopes.test.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-import type { CanvasAdjustmentsContract } from '@workbench/canvas-engine/contracts';
-
-import {
- documentFrom,
- groupContract,
- layerContract,
-} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
-import { describe, expect, it } from 'vitest';
-
-import { collectAdjustedGroups, planGroupAdjustmentScopes } from './groupAdjustmentScopes';
-
-const stack = (id: string): CanvasAdjustmentsContract => [
- { brightness: 0.2, contrast: 0, id, isEnabled: true, type: 'brightness-contrast' },
-];
-const identityStack: CanvasAdjustmentsContract = [
- { brightness: 0, contrast: 0, id: 'noop', isEnabled: true, type: 'brightness-contrast' },
-];
-
-describe('collectAdjustedGroups', () => {
- it('collects only raster-stack groups with contributing stacks', () => {
- const doc = documentFrom({
- control: [groupContract('og', [layerContract('c1', 'control')], { adjustments: stack('a') })],
- raster: [
- groupContract('g1', [layerContract('r1')], { adjustments: stack('b') }),
- groupContract('g2', [layerContract('r2')], { adjustments: identityStack }),
- groupContract('g3', [layerContract('r3')]),
- ],
- });
- expect([...collectAdjustedGroups(doc).keys()]).toEqual(['g1']);
- });
-});
-
-describe('planGroupAdjustmentScopes', () => {
- const adjusted = new Map<string, CanvasAdjustmentsContract>([
- ['g', stack('g')],
- ['h', stack('h')],
- ]);
-
- it('returns no scopes when nothing is adjusted', () => {
- expect(planGroupAdjustmentScopes([{ parentIds: [] }, { parentIds: ['x'] }], new Map())).toEqual([]);
- });
-
- it('covers a contiguous run and ignores non-adjusted ancestors', () => {
- const scopes = planGroupAdjustmentScopes(
- [{ parentIds: [] }, { parentIds: ['plain', 'g'] }, { parentIds: ['plain', 'g'] }, { parentIds: [] }],
- adjusted
- );
- expect(scopes).toEqual([{ adjustments: stack('g'), children: [], end: 3, id: 'g', start: 1 }]);
- });
-
- it('nests an inner adjusted group inside its outer scope', () => {
- const scopes = planGroupAdjustmentScopes(
- [{ parentIds: ['g'] }, { parentIds: ['g', 'h'] }, { parentIds: ['g', 'h'] }, { parentIds: ['g'] }],
- adjusted
- );
- expect(scopes).toEqual([
- {
- adjustments: stack('g'),
- children: [{ adjustments: stack('h'), children: [], end: 3, id: 'h', start: 1 }],
- end: 4,
- id: 'g',
- start: 0,
- },
- ]);
- });
-
- it('closes a scope that runs to the end of the list and separates sibling scopes', () => {
- const scopes = planGroupAdjustmentScopes(
- [{ parentIds: ['g'] }, { parentIds: [] }, { parentIds: ['h'] }, { parentIds: ['h'] }],
- adjusted
- );
- expect(scopes).toEqual([
- { adjustments: stack('g'), children: [], end: 1, id: 'g', start: 0 },
- { adjustments: stack('h'), children: [], end: 4, id: 'h', start: 2 },
- ]);
- });
-
- it('works identically on a reversed (bottom-first) list, as subtrees stay contiguous', () => {
- const items = [{ parentIds: [] }, { parentIds: ['g'] }, { parentIds: ['g', 'h'] }, { parentIds: ['g'] }];
- const scopes = planGroupAdjustmentScopes([...items].reverse(), adjusted);
- expect(scopes).toEqual([
- {
- adjustments: stack('g'),
- children: [{ adjustments: stack('h'), children: [], end: 2, id: 'h', start: 1 }],
- end: 3,
- id: 'g',
- start: 0,
- },
- ]);
- });
-});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupAdjustmentScopes.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupAdjustmentScopes.ts
deleted file mode 100644
index 4f446c4962..0000000000
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupAdjustmentScopes.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-/**
- * Nested contiguous [start, end) scopes over a flat drawn list, one per
- * adjusted group; both renderers consume the same shape. Relies on preorder
- * (or its reversal) keeping every subtree contiguous.
- */
-
-import type { CanvasAdjustmentsContract, CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';
-
-import { getDocumentIndex } from '@workbench/canvas-engine/document/documentIndex';
-import { isGroupNode } from '@workbench/canvas-engine/document/documentTree';
-
-import { isIdentityAdjustments } from './adjustments';
-
-export interface GroupAdjustmentScope {
- readonly id: string;
- readonly adjustments: CanvasAdjustmentsContract;
- /** Contiguous [start, end) index range over the flat drawn list. */
- readonly start: number;
- readonly end: number;
- /** Nested scopes, each fully inside [start, end), in list order. */
- readonly children: readonly GroupAdjustmentScope[];
-}
-
-/** The raster-stack groups whose stacks contribute (non-identity; disabled groups never draw). */
-export const collectAdjustedGroups = (
- document: CanvasDocumentContractV3
-): ReadonlyMap<string, CanvasAdjustmentsContract> => {
- const adjusted = new Map<string, CanvasAdjustmentsContract>();
- for (const entry of getDocumentIndex(document).nodes) {
- if (
- entry.stack === 'raster' &&
- isGroupNode(entry.node) &&
- entry.node.adjustments &&
- !isIdentityAdjustments(entry.node.adjustments)
- ) {
- adjusted.set(entry.node.id, entry.node.adjustments);
- }
- }
- return adjusted;
-};
-
-interface OpenScope {
- id: string;
- adjustments: CanvasAdjustmentsContract;
- start: number;
- children: GroupAdjustmentScope[];
-}
-
-/** Plans nested scopes over `items` (ancestor chains outermost-first); outermost scopes in list order. */
-export const planGroupAdjustmentScopes = (
- items: readonly { readonly parentIds: readonly string[] }[],
- adjusted: ReadonlyMap<string, CanvasAdjustmentsContract>
-): readonly GroupAdjustmentScope[] => {
- if (adjusted.size === 0) {
- return [];
- }
- const roots: GroupAdjustmentScope[] = [];
- const open: OpenScope[] = [];
-
- const closeTo = (depth: number, end: number): void => {
- while (open.length > depth) {
- const scope = open.pop()!;
- const closed: GroupAdjustmentScope = { ...scope, end };
- const parent = open[open.length - 1];
- (parent ? parent.children : roots).push(closed);
- }
- };
-
- items.forEach((item, index) => {
- const chain = item.parentIds.filter((id) => adjusted.has(id));
- let shared = 0;
- while (shared < open.length && shared < chain.length && open[shared]!.id === chain[shared]) {
- shared += 1;
- }
- closeTo(shared, index);
- for (let depth = shared; depth < chain.length; depth += 1) {
- const id = chain[depth]!;
- open.push({ adjustments: adjusted.get(id)!, children: [], id, start: index });
- }
- });
- closeTo(0, items.length);
- return roots;
-};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupCompositeScopes.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupCompositeScopes.test.ts
new file mode 100644
index 0000000000..c7d96b77d6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupCompositeScopes.test.ts
@@ -0,0 +1,122 @@
+import type { CanvasAdjustmentsContract } from '@workbench/canvas-engine/contracts';
+
+import {
+ documentFrom,
+ groupContract,
+ layerContract,
+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { describe, expect, it } from 'vitest';
+
+import type { GroupCompositeFacts } from './groupCompositeScopes';
+
+import { collectCompositedGroups, planGroupCompositeScopes } from './groupCompositeScopes';
+
+const stack = (id: string): CanvasAdjustmentsContract => [
+ { brightness: 0.2, contrast: 0, id, isEnabled: true, type: 'brightness-contrast' },
+];
+const identityStack: CanvasAdjustmentsContract = [
+ { brightness: 0, contrast: 0, id: 'noop', isEnabled: true, type: 'brightness-contrast' },
+];
+const facts = (
+ adjustments: CanvasAdjustmentsContract,
+ overrides: Partial<GroupCompositeFacts> = {}
+): GroupCompositeFacts => ({
+ adjustments,
+ blendMode: 'normal',
+ opacity: 1,
+ ...overrides,
+});
+
+describe('collectCompositedGroups', () => {
+ it('collects only raster-stack groups with contributing stacks', () => {
+ const doc = documentFrom({
+ control: [groupContract('og', [layerContract('c1', 'control')], { adjustments: stack('a') })],
+ raster: [
+ groupContract('g1', [layerContract('r1')], { adjustments: stack('b') }),
+ groupContract('g2', [layerContract('r2')], { adjustments: identityStack }),
+ groupContract('g3', [layerContract('r3')]),
+ ],
+ });
+ expect([...collectCompositedGroups(doc).keys()]).toEqual(['g1']);
+ });
+
+ it('collects raster-stack groups scoped only by opacity or blend, with an empty stack', () => {
+ const doc = documentFrom({
+ raster: [
+ groupContract('faded', [layerContract('r1')], { opacity: 0.5 }),
+ groupContract('mult', [layerContract('r2')], { blendMode: 'multiply' }),
+ groupContract('plain', [layerContract('r3')], { blendMode: 'normal', opacity: 1 }),
+ groupContract('identity', [layerContract('r4')], { adjustments: identityStack, opacity: 0.25 }),
+ ],
+ });
+ const composited = collectCompositedGroups(doc);
+ expect([...composited.keys()]).toEqual(['faded', 'mult', 'identity']);
+ expect(composited.get('faded')).toEqual(facts([], { opacity: 0.5 }));
+ expect(composited.get('mult')).toEqual(facts([], { blendMode: 'multiply' }));
+ // An identity stack contributes nothing: the scope keeps an EMPTY stack so
+ // renderers can skip the pixel pass, but the opacity still isolates it.
+ expect(composited.get('identity')).toEqual(facts([], { opacity: 0.25 }));
+ });
+});
+
+describe('planGroupCompositeScopes', () => {
+ const adjusted = new Map<string, GroupCompositeFacts>([
+ ['g', facts(stack('g'))],
+ ['h', facts(stack('h'), { blendMode: 'multiply', opacity: 0.5 })],
+ ]);
+ const scopeG = { adjustments: stack('g'), blendMode: 'normal', opacity: 1 } as const;
+ const scopeH = { adjustments: stack('h'), blendMode: 'multiply', opacity: 0.5 } as const;
+
+ it('returns no scopes when nothing is composited', () => {
+ expect(planGroupCompositeScopes([{ parentIds: [] }, { parentIds: ['x'] }], new Map())).toEqual([]);
+ });
+
+ it('covers a contiguous run and ignores non-composited ancestors', () => {
+ const scopes = planGroupCompositeScopes(
+ [{ parentIds: [] }, { parentIds: ['plain', 'g'] }, { parentIds: ['plain', 'g'] }, { parentIds: [] }],
+ adjusted
+ );
+ expect(scopes).toEqual([{ ...scopeG, children: [], end: 3, id: 'g', start: 1 }]);
+ });
+
+ it('nests an inner composited group inside its outer scope, carrying its opacity and blend', () => {
+ const scopes = planGroupCompositeScopes(
+ [{ parentIds: ['g'] }, { parentIds: ['g', 'h'] }, { parentIds: ['g', 'h'] }, { parentIds: ['g'] }],
+ adjusted
+ );
+ expect(scopes).toEqual([
+ {
+ ...scopeG,
+ children: [{ ...scopeH, children: [], end: 3, id: 'h', start: 1 }],
+ end: 4,
+ id: 'g',
+ start: 0,
+ },
+ ]);
+ });
+
+ it('closes a scope that runs to the end of the list and separates sibling scopes', () => {
+ const scopes = planGroupCompositeScopes(
+ [{ parentIds: ['g'] }, { parentIds: [] }, { parentIds: ['h'] }, { parentIds: ['h'] }],
+ adjusted
+ );
+ expect(scopes).toEqual([
+ { ...scopeG, children: [], end: 1, id: 'g', start: 0 },
+ { ...scopeH, children: [], end: 4, id: 'h', start: 2 },
+ ]);
+ });
+
+ it('works identically on a reversed (bottom-first) list, as subtrees stay contiguous', () => {
+ const items = [{ parentIds: [] }, { parentIds: ['g'] }, { parentIds: ['g', 'h'] }, { parentIds: ['g'] }];
+ const scopes = planGroupCompositeScopes([...items].reverse(), adjusted);
+ expect(scopes).toEqual([
+ {
+ ...scopeG,
+ children: [{ ...scopeH, children: [], end: 2, id: 'h', start: 1 }],
+ end: 3,
+ id: 'g',
+ start: 0,
+ },
+ ]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupCompositeScopes.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupCompositeScopes.ts
new file mode 100644
index 0000000000..87b31e2864
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupCompositeScopes.ts
@@ -0,0 +1,116 @@
+/**
+ * Nested contiguous [start, end) scopes over a flat drawn list, one per
+ * composited group — a group whose output must be built in isolation because it
+ * carries a contributing adjustment stack, an opacity below 1, or a non-normal
+ * blend mode. Both renderers consume the same shape. Relies on preorder (or its
+ * reversal) keeping every subtree contiguous.
+ */
+
+import type {
+ CanvasAdjustmentsContract,
+ CanvasBlendMode,
+ CanvasDocumentContractV3,
+} from '@workbench/canvas-engine/contracts';
+
+import { getDocumentIndex } from '@workbench/canvas-engine/document/documentIndex';
+import { isGroupNode } from '@workbench/canvas-engine/document/documentTree';
+
+import { isIdentityAdjustments } from './adjustments';
+
+export interface GroupCompositeScope {
+ readonly id: string;
+ readonly adjustments: CanvasAdjustmentsContract;
+ /** Applied when the scope's composite lands in its parent; 1 when absent on the group. */
+ readonly opacity: number;
+ /** Applied when the scope's composite lands in its parent; 'normal' when absent on the group. */
+ readonly blendMode: CanvasBlendMode;
+ /** Contiguous [start, end) index range over the flat drawn list. */
+ readonly start: number;
+ readonly end: number;
+ /** Nested scopes, each fully inside [start, end), in list order. */
+ readonly children: readonly GroupCompositeScope[];
+}
+
+export interface GroupCompositeFacts {
+ readonly adjustments: CanvasAdjustmentsContract;
+ readonly opacity: number;
+ readonly blendMode: CanvasBlendMode;
+}
+
+const EMPTY_ADJUSTMENTS: CanvasAdjustmentsContract = [];
+
+/** The raster-stack groups that must composite in isolation (disabled groups never draw). */
+export const collectCompositedGroups = (
+ document: CanvasDocumentContractV3
+): ReadonlyMap<string, GroupCompositeFacts> => {
+ const composited = new Map<string, GroupCompositeFacts>();
+ for (const entry of getDocumentIndex(document).nodes) {
+ if (entry.stack !== 'raster' || !isGroupNode(entry.node)) {
+ continue;
+ }
+ const opacity = entry.node.opacity ?? 1;
+ const blendMode = entry.node.blendMode ?? 'normal';
+ const adjusted = entry.node.adjustments !== undefined && !isIdentityAdjustments(entry.node.adjustments);
+ if (adjusted || opacity !== 1 || blendMode !== 'normal') {
+ composited.set(entry.node.id, {
+ adjustments: adjusted ? entry.node.adjustments! : EMPTY_ADJUSTMENTS,
+ blendMode,
+ opacity,
+ });
+ }
+ }
+ return composited;
+};
+
+interface OpenScope {
+ id: string;
+ adjustments: CanvasAdjustmentsContract;
+ opacity: number;
+ blendMode: CanvasBlendMode;
+ start: number;
+ children: GroupCompositeScope[];
+}
+
+/** Plans nested scopes over `items` (ancestor chains outermost-first); outermost scopes in list order. */
+export const planGroupCompositeScopes = (
+ items: readonly { readonly parentIds: readonly string[] }[],
+ composited: ReadonlyMap<string, GroupCompositeFacts>
+): readonly GroupCompositeScope[] => {
+ if (composited.size === 0) {
+ return [];
+ }
+ const roots: GroupCompositeScope[] = [];
+ const open: OpenScope[] = [];
+
+ const closeTo = (depth: number, end: number): void => {
+ while (open.length > depth) {
+ const scope = open.pop()!;
+ const closed: GroupCompositeScope = { ...scope, end };
+ const parent = open[open.length - 1];
+ (parent ? parent.children : roots).push(closed);
+ }
+ };
+
+ items.forEach((item, index) => {
+ const chain = item.parentIds.filter((id) => composited.has(id));
+ let shared = 0;
+ while (shared < open.length && shared < chain.length && open[shared]!.id === chain[shared]) {
+ shared += 1;
+ }
+ closeTo(shared, index);
+ for (let depth = shared; depth < chain.length; depth += 1) {
+ const id = chain[depth]!;
+ const facts = composited.get(id)!;
+ open.push({
+ adjustments: facts.adjustments,
+ blendMode: facts.blendMode,
+ children: [],
+ id,
+ opacity: facts.opacity,
+ start: index,
+ });
+ }
+ });
+ closeTo(0, items.length);
+ return roots;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupSurfaceCache.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupSurfaceCache.ts
index 01e8147b88..e5f52e0bb8 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupSurfaceCache.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupSurfaceCache.ts
@@ -1,9 +1,11 @@
/**
- * Per-group memoized document-space composites of adjusted groups. Keyed on
- * the scope shape plus every drawn member's cache version, appearance, and
- * effective matrix (so a transform session inside an adjusted group rebuilds
- * per tick). Accepted tradeoff: document resolution, so transformed members
- * resample twice and zoom > 100% upscales the group surface.
+ * Per-group memoized document-space composites of composited groups (adjustment
+ * stack, opacity, or blend mode). Keyed on the scope shape plus every drawn
+ * member's cache version, appearance, and effective matrix (so a transform
+ * session inside a composited group rebuilds per tick); the scope's own
+ * opacity/blend land at draw time and stay out of the key. Accepted tradeoff:
+ * document resolution, so transformed members resample twice and zoom > 100%
+ * upscales the group surface.
*/
import type { CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';
@@ -14,10 +16,10 @@ import type { Mat2d, Rect } from '@workbench/canvas-engine/types';
import { multiply } from '@workbench/canvas-engine/math/mat2d';
import { roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';
-import { adjustmentsKey, applyAdjustments } from '@workbench/canvas-engine/render/adjustments';
+import { adjustmentsKey, applyAdjustments, isIdentityAdjustments } from '@workbench/canvas-engine/render/adjustments';
import { blendToComposite } from '@workbench/canvas-engine/render/compositor';
-import type { GroupAdjustmentScope } from './groupAdjustmentScopes';
+import type { GroupCompositeScope } from './groupCompositeScopes';
export interface GroupSurfaceResult {
readonly surface: RasterSurface;
@@ -36,7 +38,7 @@ export interface GroupSurfaceCache {
/** Total RGBA bytes the cached group surfaces hold, for the memory budget. */
byteSize(): number;
get(
- scope: GroupAdjustmentScope,
+ scope: GroupCompositeScope,
members: readonly SemanticLeaf[],
memberMatrices: readonly Mat2d[],
excludeIds: ReadonlySet<string>
@@ -56,13 +58,19 @@ const SLOTS_PER_GROUP = 2;
export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCache => {
const cache = new Map<string, { key: string; result: GroupSurfaceResult }[]>();
- const scopeShapeKey = (scope: GroupAdjustmentScope): string =>
+ // A scope's OWN opacity/blend are applied by the consumer when the surface
+ // lands, so they stay out of its shape key (an opacity scrub reuses the
+ // surface); a CHILD scope's opacity/blend are baked in here by `drawRange`,
+ // so children key with them.
+ const childScopeKey = (scope: GroupCompositeScope): string =>
+ `${scopeShapeKey(scope)}:${scope.opacity}:${scope.blendMode}`;
+ const scopeShapeKey = (scope: GroupCompositeScope): string =>
`${scope.id}@${scope.start}-${scope.end}:${adjustmentsKey(scope.adjustments)}(${scope.children
- .map(scopeShapeKey)
+ .map(childScopeKey)
.join(',')})`;
const buildKey = (
- scope: GroupAdjustmentScope,
+ scope: GroupCompositeScope,
members: readonly SemanticLeaf[],
memberMatrices: readonly Mat2d[],
excludeIds: ReadonlySet<string>
@@ -86,7 +94,7 @@ export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCac
baseIndex: number,
from: number,
to: number,
- children: readonly GroupAdjustmentScope[]
+ children: readonly GroupCompositeScope[]
): void => {
let childIndex = 0;
for (let i = from; i < to;) {
@@ -95,8 +103,8 @@ export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCac
const nested = build(child, members, memberMatrices, excludeIds, baseIndex);
if (nested) {
ctx.save();
- ctx.globalAlpha = 1;
- ctx.globalCompositeOperation = 'source-over';
+ ctx.globalAlpha = child.opacity;
+ ctx.globalCompositeOperation = blendToComposite(child.blendMode);
ctx.setTransform(view.a, view.b, view.c, view.d, view.e, view.f);
ctx.drawImage(nested.surface.canvas, nested.rect.x, nested.rect.y);
ctx.restore();
@@ -127,7 +135,7 @@ export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCac
};
const build = (
- scope: GroupAdjustmentScope,
+ scope: GroupCompositeScope,
members: readonly SemanticLeaf[],
memberMatrices: readonly Mat2d[],
excludeIds: ReadonlySet<string>,
@@ -159,9 +167,13 @@ export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCac
ctx.clearRect(0, 0, rect.width, rect.height);
const view: Mat2d = { a: 1, b: 0, c: 0, d: 1, e: -rect.x, f: -rect.y };
drawRange(ctx, view, members, memberMatrices, excludeIds, baseIndex, scope.start, scope.end, scope.children);
- const pixels = ctx.getImageData(0, 0, rect.width, rect.height);
- applyAdjustments(pixels, scope.adjustments);
- ctx.putImageData(pixels, 0, 0);
+ // A group scoped only for opacity/blend has an identity stack: skip the
+ // full-surface pixel round trip.
+ if (!isIdentityAdjustments(scope.adjustments)) {
+ const pixels = ctx.getImageData(0, 0, rect.width, rect.height);
+ applyAdjustments(pixels, scope.adjustments);
+ ctx.putImageData(pixels, 0, 0);
+ }
return { rect, surface };
};
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 1dda71518a..0afc11bc9f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts
@@ -6,7 +6,7 @@ import type {
CanvasRasterLayerContractV2,
} from '@workbench/canvas-engine/contracts';
import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';
-import type { GroupAdjustmentScope } from '@workbench/canvas-engine/render/groupAdjustmentScopes';
+import type { GroupCompositeScope } from '@workbench/canvas-engine/render/groupCompositeScopes';
import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { Mat2d, Rect } from '@workbench/canvas-engine/types';
@@ -16,9 +16,9 @@ import { roundOut, transformBounds, union } from '@workbench/canvas-engine/math/
import { adjustmentsKey, applyAdjustments, isIdentityAdjustments } from '@workbench/canvas-engine/render/adjustments';
import { blendToComposite } from '@workbench/canvas-engine/render/compositor';
import {
- collectAdjustedGroups,
- planGroupAdjustmentScopes,
-} from '@workbench/canvas-engine/render/groupAdjustmentScopes';
+ collectCompositedGroups,
+ planGroupCompositeScopes,
+} from '@workbench/canvas-engine/render/groupCompositeScopes';
type Ctx = RasterSurface['ctx'];
@@ -39,7 +39,7 @@ export interface CompositeEntry {
bbox: Rect;
layers: readonly CompositeLayerRef[];
/** Adjusted-group isolation scopes over `layers` (top-first, nested). Absent ⇒ fully pass-through. */
- groupScopes?: readonly GroupAdjustmentScope[];
+ groupScopes?: readonly GroupCompositeScope[];
}
export interface BaseRasterCompositeEntry extends CompositeEntry {
@@ -159,14 +159,14 @@ export const getCompositeLayerBounds = (layers: readonly CompositeLayerRef[]): R
return bounds;
};
-const scopeKey = (scope: GroupAdjustmentScope): string =>
- `${scope.id}@${scope.start}-${scope.end}:${adjustmentsKey(scope.adjustments)}(${scope.children.map(scopeKey).join(',')})`;
+const scopeKey = (scope: GroupCompositeScope): string =>
+ `${scope.id}@${scope.start}-${scope.end}:${adjustmentsKey(scope.adjustments)}:${scope.opacity}:${scope.blendMode}(${scope.children.map(scopeKey).join(',')})`;
/** Plans the enabled base-raster layers over an exact document-space rectangle. */
export const planBaseRasterComposite = (document: CanvasDocumentContractV3, rect: Rect): BaseRasterCompositeEntry => {
const drawn = compileDocumentLeaves(document).filter(isBaseRasterLeaf);
const layers = drawn.map((leaf) => toLayerRef(leaf.layer, document));
- const groupScopes = planGroupAdjustmentScopes(drawn, collectAdjustedGroups(document));
+ const groupScopes = planGroupCompositeScopes(drawn, collectCompositedGroups(document));
return {
bbox: rect,
key: `base-raster|${rectKey(rect)}|${layers.map(layerKey).join('|')}|${groupScopes.map(scopeKey).join('|')}`,
@@ -250,7 +250,7 @@ export const renderRasterComposite = async (
ctx: Ctx,
start: number,
end: number,
- scopes: readonly GroupAdjustmentScope[]
+ scopes: readonly GroupCompositeScope[]
): Promise<void> => {
let scopeIndex = scopes.length - 1;
for (let i = end - 1; i >= start;) {
@@ -260,13 +260,15 @@ export const renderRasterComposite = async (
setTransform(buffer.ctx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
buffer.ctx.clearRect(0, 0, width, height);
await renderRange(buffer.ctx, scope.start, scope.end, scope.children);
- const pixels = readImageData(buffer, fullRect);
- applyAdjustments(pixels, scope.adjustments);
- writeImageData(buffer, pixels, 0, 0);
+ if (!isIdentityAdjustments(scope.adjustments)) {
+ const pixels = readImageData(buffer, fullRect);
+ applyAdjustments(pixels, scope.adjustments);
+ writeImageData(buffer, pixels, 0, 0);
+ }
ctx.save();
setTransform(ctx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
- ctx.globalAlpha = 1;
- ctx.globalCompositeOperation = 'source-over';
+ ctx.globalAlpha = scope.opacity;
+ ctx.globalCompositeOperation = blendToComposite(scope.blendMode);
ctx.drawImage(buffer.canvas, 0, 0);
ctx.restore();
i = scope.start - 1;
diff --git a/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts b/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts
index 34228737ba..4e9056acb2 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts
@@ -146,6 +146,36 @@ describe('loadCanvasState', () => {
expect(loadedMalformed?.type === 'group' ? loadedMalformed.children.length : 0).toBe(1);
});
+ it('round-trips group opacity and blend in the raster stack, strips them from overlay groups, and drops malformed values', () => {
+ const rasterGroup = {
+ blendMode: 'multiply',
+ children: [createEmptyPaintLayer('Inside', 'inside')],
+ id: 'rg',
+ isEnabled: true,
+ isLocked: false,
+ name: 'Faded',
+ opacity: 0.5,
+ type: 'group',
+ };
+ const rasterLoaded = load(withNodes([rasterGroup]));
+ const loadedGroup = rasterLoaded.document.stacks.raster[0];
+ expect(loadedGroup?.type === 'group' ? loadedGroup.opacity : null).toBe(0.5);
+ expect(loadedGroup?.type === 'group' ? loadedGroup.blendMode : null).toBe('multiply');
+
+ const overlayGroup = { ...rasterGroup, children: [], id: 'og' };
+ const overlayLoaded = load(withNodes([overlayGroup], 'control'));
+ const loadedOverlay = overlayLoaded.document.stacks.control[0];
+ expect(loadedOverlay?.type === 'group' ? Object.hasOwn(loadedOverlay, 'opacity') : null).toBe(false);
+ expect(loadedOverlay?.type === 'group' ? Object.hasOwn(loadedOverlay, 'blendMode') : null).toBe(false);
+
+ const malformed = { ...rasterGroup, blendMode: 'plasma', id: 'mg', opacity: 7 };
+ const malformedLoaded = load(withNodes([malformed]));
+ const loadedMalformed = malformedLoaded.document.stacks.raster[0];
+ expect(loadedMalformed?.type === 'group' ? loadedMalformed.opacity : null).toBeUndefined();
+ expect(loadedMalformed?.type === 'group' ? loadedMalformed.blendMode : null).toBeUndefined();
+ expect(loadedMalformed?.type === 'group' ? loadedMalformed.children.length : 0).toBe(1);
+ });
+
it('round-trips a valid adjustment stack, drops the pre-stack object shape, and drops a stack with one malformed entry', () => {
const stack = [
{ brightness: 0.2, contrast: -0.1, id: 'a1', isEnabled: true, type: 'brightness-contrast' },
diff --git a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts b/invokeai/frontend/webv2/src/workbench/canvasMigration.ts
index 505cbacd72..9f08d7aca9 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasMigration.ts
@@ -178,25 +178,26 @@ const zReferenceImage = z.object({
id: z.string(),
isEnabled: z.boolean(),
});
+const zBlendMode = z.enum([
+ 'normal',
+ 'multiply',
+ 'screen',
+ 'overlay',
+ 'darken',
+ 'lighten',
+ 'color-dodge',
+ 'color-burn',
+ 'hard-light',
+ 'soft-light',
+ 'difference',
+ 'exclusion',
+ 'hue',
+ 'saturation',
+ 'color',
+ 'luminosity',
+]);
const zLayerBase = z.object({
- blendMode: z.enum([
- 'normal',
- 'multiply',
- 'screen',
- 'overlay',
- 'darken',
- 'lighten',
- 'color-dodge',
- 'color-burn',
- 'hard-light',
- 'soft-light',
- 'difference',
- 'exclusion',
- 'hue',
- 'saturation',
- 'color',
- 'luminosity',
- ]),
+ blendMode: zBlendMode,
id: z.string(),
isEnabled: z.boolean(),
isLocked: z.boolean(),
@@ -448,11 +449,13 @@ const describeIssue = (value: Record<string, unknown>, path: string, issues: rea
const zGroupShell = z.object({
// Like the raster arm: a malformed stack drops without failing the document.
adjustments: zAdjustments.optional().catch(undefined),
+ blendMode: zBlendMode.optional().catch(undefined),
id: z.string(),
isEnabled: z.boolean(),
isHidden: z.boolean().optional(),
isLocked: z.boolean(),
name: z.string(),
+ opacity: z.number().min(0).max(1).optional().catch(undefined),
type: z.literal('group'),
});
@@ -526,13 +529,15 @@ const parseNode = (value: unknown, path: string, depth: number, context: ParseCo
if (context.stack === 'raster' || shell.data.isHidden === false) {
delete shell.data.isHidden;
}
- // Adjustments are the raster-stack mirror of the isHidden rule: overlay
- // groups composite coverage, not color, so a stack there is meaningless.
- // Stripped SILENTLY, unlike isHidden: diagnostics are fatal to the whole
- // parse, and rejecting a document over a meaningless stack is worse than
- // dropping the stack.
+ // Adjustments, opacity and blend are the raster-stack mirror of the isHidden
+ // rule: overlay groups composite coverage, not color, so all three are
+ // meaningless there. Stripped SILENTLY, unlike isHidden: diagnostics are
+ // fatal to the whole parse, and rejecting a document over a meaningless
+ // property is worse than dropping it.
if (context.stack !== 'raster') {
delete shell.data.adjustments;
+ delete shell.data.blendMode;
+ delete shell.data.opacity;
}
if (depth >= CANVAS_MAX_NODE_DEPTH) {
context.diagnostics.push({ message: `group nests deeper than ${CANVAS_MAX_NODE_DEPTH} levels`, path });
diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts
index 6760d4dfbd..887752c030 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts
@@ -13,6 +13,7 @@ import {
type CanvasRasterLayerContractV2,
type CanvasStackForests,
type CanvasStateContractV3,
+ type LayerStackKind,
type ReorderSiblingsCommand,
CANVAS_MAX_NODE_COUNT,
CANVAS_MAX_NODE_DEPTH,
@@ -502,10 +503,19 @@ const reorderCanvasSiblings = (
return withStacks(document, stacks);
};
-const patchNode = (node: CanvasNodeContract, patch: CanvasLayerBasePatch): CanvasNodeContract => {
+/** Opacity/blend apply only to raster-stack groups, even from unvalidated dispatchers (previews, replays). */
+const patchNode = (
+ node: CanvasNodeContract,
+ patch: CanvasLayerBasePatch,
+ stack: LayerStackKind
+): CanvasNodeContract => {
if (isGroupNode(node)) {
const allowed = Object.fromEntries(
- Object.entries(patch).filter(([key]) => GROUP_PATCH_KEYS.includes(key as keyof CanvasLayerBasePatch))
+ Object.entries(patch).filter(
+ ([key]) =>
+ GROUP_PATCH_KEYS.includes(key as keyof CanvasLayerBasePatch) &&
+ (stack === 'raster' || (key !== 'opacity' && key !== 'blendMode'))
+ )
);
return Object.keys(allowed).length === 0 ? node : { ...node, ...allowed };
}
@@ -832,7 +842,9 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasPro
return updateCanvasDocument(project, (document) => reorderCanvasSiblings(document, mutation.orders));
case 'updateCanvasLayer':
return updateCanvasDocument(project, (document) =>
- mapNode(document, mutation.id, (node) => patchNode(node, mutation.patch))
+ mapNode(document, mutation.id, (node) =>
+ patchNode(node, mutation.patch, getDocumentIndex(document).byId.get(mutation.id)?.stack ?? 'raster')
+ )
);
case 'replaceCanvasLayer':
return mutation.layer.id === mutation.layerId
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.test.ts
index bdcf8f1f90..1aff8334a4 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.test.ts
@@ -1,7 +1,12 @@
+import {
+ documentFrom,
+ groupContract,
+ layerContract,
+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
import { createEmptyPaintLayer } from '@workbench/widgets/layers/layerOps';
import { describe, expect, it } from 'vitest';
-import { isLayerEditingDisabled } from './LayerBlendRow';
+import { isLayerEditingDisabled, selectBlendTarget } from './LayerBlendRow';
describe('LayerBlendRow editing state', () => {
it('disables layer controls without a selection or while engine editing is locked', () => {
@@ -11,3 +16,23 @@ describe('LayerBlendRow editing state', () => {
expect(isLayerEditingDisabled(layer, false)).toBe(false);
});
});
+
+describe('selectBlendTarget', () => {
+ const projectFor = (nodes: Parameters<typeof documentFrom>[0], selectedLayerId: string | null) => ({
+ canvas: { document: documentFrom(nodes, selectedLayerId) },
+ });
+
+ it('targets a selected leaf and a selected raster-stack group', () => {
+ const leaf = layerContract('r1');
+ const group = groupContract('g', [layerContract('r2')], { blendMode: 'multiply', opacity: 0.5 });
+ expect(selectBlendTarget(projectFor([leaf, group], 'r1'))).toBe(leaf);
+ expect(selectBlendTarget(projectFor([leaf, group], 'g'))).toBe(group);
+ });
+
+ it('returns null for an overlay-stack group, a missing id, and no selection', () => {
+ const overlayGroup = groupContract('og', [layerContract('c1', 'control')]);
+ expect(selectBlendTarget(projectFor([overlayGroup], 'og'))).toBeNull();
+ expect(selectBlendTarget(projectFor([layerContract('r1')], 'gone'))).toBeNull();
+ expect(selectBlendTarget(projectFor([layerContract('r1')], null))).toBeNull();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.tsx
index e2f72938b3..479a2f3e2b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerBlendRow.tsx
@@ -1,10 +1,10 @@
import type { NumberInput as ChakraNumberInput, SelectValueChangeDetails } from '@chakra-ui/react';
-import type { CanvasBlendMode, CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/api';
+import type { CanvasBlendMode, CanvasDocumentContractV3, CanvasNodeContract } from '@workbench/canvas-engine/api';
import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';
import { createListCollection, Flex, HStack, NumberInput } from '@chakra-ui/react';
import { Select } from '@platform/ui';
-import { getDocumentLayer } from '@workbench/canvas-engine/api';
+import { getDocumentIndex, isGroupNode } from '@workbench/canvas-engine/api';
import { useCanvasDocumentEditingLocked } from '@workbench/widgets/canvas/engineStoreHooks';
import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { applyStructuralPreview, CANVAS_BLEND_MODES } from '@workbench/widgets/layers/layerOps';
@@ -21,21 +21,32 @@ const OPACITY_INPUT_PROPS = { fontSize: 'xs', h: '7' } as const;
const clamp01 = (value: number): number => Math.min(1, Math.max(0, value));
// Reference equality is exact: the document index hands back the same node
-// object until the layer itself changes.
-const selectSelectedLayer = (project: {
+// object until the node itself changes. A raster-stack GROUP is a valid target
+// (opacity/blend on its isolated composite); overlay-stack groups are not.
+export const selectBlendTarget = (project: {
canvas: { document: Pick<CanvasDocumentContractV3, 'stacks' | 'selectedLayerId'> };
-}): CanvasLayerContract | null => getDocumentLayer(project.canvas.document, project.canvas.document.selectedLayerId);
+}): CanvasNodeContract | null => {
+ const document = project.canvas.document;
+ if (!document.selectedLayerId) {
+ return null;
+ }
+ const entry = getDocumentIndex(document).byId.get(document.selectedLayerId);
+ if (!entry) {
+ return null;
+ }
+ return isGroupNode(entry.node) && entry.stack !== 'raster' ? null : entry.node;
+};
-export const isLayerEditingDisabled = (layer: CanvasLayerContract | null, editingLocked: boolean): boolean =>
+export const isLayerEditingDisabled = (layer: CanvasNodeContract | null, editingLocked: boolean): boolean =>
!layer || editingLocked;
/**
* The fixed blend-mode + opacity row above the layer tree, Photoshop-style. It
- * edits the selected layer and simply disables without one — the row never
- * appears or disappears.
+ * edits the selected layer or raster-stack group and simply disables without
+ * one — the row never appears or disappears.
*/
export const LayerBlendRow = ({ engine }: { engine: LayerBlendRowEngine | null }) => {
- const layer = useActiveProjectSelector(selectSelectedLayer);
+ const layer = useActiveProjectSelector(selectBlendTarget);
const editingLocked = useCanvasDocumentEditingLocked(engine);
return (
@@ -58,7 +69,7 @@ const BlendModeControl = ({
}: {
editingLocked: boolean;
engine: LayerBlendRowEngine | null;
- layer: CanvasLayerContract | null;
+ layer: CanvasNodeContract | null;
}) => {
const commitPrepared = usePreparedCommit(engine);
const { t } = useTranslation();
@@ -76,7 +87,7 @@ const BlendModeControl = ({
const handleBlendChange = useCallback(
({ value }: SelectValueChangeDetails<BlendModeOption>) => {
const mode = value[0] as CanvasBlendMode | undefined;
- if (!layer || !mode || mode === layer.blendMode) {
+ if (!layer || !mode || mode === (layer.blendMode ?? 'normal')) {
return;
}
commitPrepared(t('widgets.layers.actions.blendMode'), (model) =>
@@ -111,7 +122,7 @@ const OpacityRow = ({
}: {
editingLocked: boolean;
engine: LayerBlendRowEngine | null;
- layer: CanvasLayerContract | null;
+ layer: CanvasNodeContract | null;
}) => {
const commitPrepared = usePreparedCommit(engine);
const { t } = useTranslation();
@@ -163,7 +174,7 @@ const OpacityRow = ({
return;
}
if (pendingRef.current === null) {
- pendingRef.current = { before: layer.opacity, id: layer.id, latest: next };
+ pendingRef.current = { before: layer.opacity ?? 1, id: layer.id, latest: next };
} else {
pendingRef.current.latest = next;
}