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): render group adjustment stacks across every composite path

Josh Corbett25cd0b4bcd81
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index 4439be9d29..278258f9f5 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -2,10 +2,10 @@
"build": {
"launchpad": {
"baseline": {
- "brotliBytes": 841574,
+ "brotliBytes": 841579,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 840585,
+ "gzipBytes": 840575,
"imageRawBytes": 156376,
"initialRawBytes": 1959360,
"largestAssetRawBytes": 746376,
@@ -291,10 +291,10 @@
]
},
"limits": {
- "brotliBytes": 849990,
+ "brotliBytes": 849995,
"cssRawBytes": 2181,
"fontRawBytes": 221675,
- "gzipBytes": 848991,
+ "gzipBytes": 848981,
"imageRawBytes": 157940,
"initialRawBytes": 1978954,
"largestAssetRawBytes": 753840,
@@ -309,12 +309,12 @@
},
"editor": {
"baseline": {
- "brotliBytes": 1102144,
+ "brotliBytes": 1103113,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 1097730,
+ "gzipBytes": 1098700,
"imageRawBytes": 156376,
- "initialRawBytes": 2749535,
+ "initialRawBytes": 2752773,
"largestAssetRawBytes": 746376,
"otherAssetRawBytes": 0,
"ownedRawBytes": 114628,
@@ -732,6 +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/maskFill.ts",
"source:src/workbench/canvas-engine/render/rasterComposite.ts",
"source:src/workbench/canvas-engine/render/rasterizers/textRasterizer.ts",
@@ -933,12 +934,12 @@
]
},
"limits": {
- "brotliBytes": 1113166,
+ "brotliBytes": 1114145,
"cssRawBytes": 2181,
"fontRawBytes": 221675,
- "gzipBytes": 1108708,
+ "gzipBytes": 1109687,
"imageRawBytes": 157940,
- "initialRawBytes": 2777031,
+ "initialRawBytes": 2780301,
"largestAssetRawBytes": 753840,
"otherAssetRawBytes": 0,
"ownedRawBytes": 114628,
@@ -950,7 +951,7 @@
"source": "src/app/WorkbenchApp.tsx"
}
},
- "capturedAt": "2026-09-01",
+ "capturedAt": "2026-09-02",
"developmentInvalidation": {
"platformUiBarrel": {
"specifier": "@platform/ui",
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 59f7c83f4f..2e9012e602 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -1,6 +1,6 @@
{
"browserExecutable": "/home/toast/.cache/ms-playwright/chromium-1234/chrome-linux64/chrome",
- "capturedAt": "2026-09-01",
+ "capturedAt": "2026-09-02",
"routes": [
{
"activatedResourceBaseline": {
@@ -25,13 +25,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 123.40000000596046,
+ "domContentLoadedMedianMs": 120.3999999910593,
"id": "launchpad",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 123.59999999403954,
- "longestTaskMaxMs": 73,
+ "loadMedianMs": 120.59999999403954,
+ "longestTaskMaxMs": 70,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -58,7 +58,7 @@
"scriptRequestCount": 34,
"totalRawBytes": 1839703
},
- "routeReadyMedianMs": 273.79999999701977,
+ "routeReadyMedianMs": 262.5,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "empty"
},
@@ -85,13 +85,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 125,
+ "domContentLoadedMedianMs": 121.29999999701977,
"id": "launchpad",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 125.1000000089407,
- "longestTaskMaxMs": 76,
+ "loadMedianMs": 121.3999999910593,
+ "longestTaskMaxMs": 75,
"owner": "app",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:launchpad",
@@ -118,7 +118,7 @@
"scriptRequestCount": 34,
"totalRawBytes": 1839703
},
- "routeReadyMedianMs": 289.40000000596046,
+ "routeReadyMedianMs": 308.09999999403954,
"scriptSourceOwnerSet": "launchpad-static",
"stateProfile": "representative"
},
@@ -145,15 +145,15 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 127.19999998807907,
+ "domContentLoadedMedianMs": 116.8999999910593,
"id": "editor-minimal",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 127.29999999701977,
- "longestTaskMaxMs": 138,
+ "loadMedianMs": 117,
+ "longestTaskMaxMs": 102,
"owner": "workbench",
- "projectSwitchMedianMs": 40.5,
+ "projectSwitchMedianMs": 38.29999999701977,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -163,9 +163,9 @@
"largestAssetRawBytes": 746376,
"otherRawBytes": 160278,
"requestCount": 115,
- "scriptRawBytes": 3273182,
+ "scriptRawBytes": 3279305,
"scriptRequestCount": 110,
- "totalRawBytes": 3615659
+ "totalRawBytes": 3621782
},
"resourceLimits": {
"cssRawBytes": 2181,
@@ -174,11 +174,11 @@
"largestAssetRawBytes": 753840,
"otherRawBytes": 161881,
"requestCount": 115,
- "scriptRawBytes": 3305914,
+ "scriptRawBytes": 3312099,
"scriptRequestCount": 110,
- "totalRawBytes": 3651816
+ "totalRawBytes": 3658000
},
- "routeReadyMedianMs": 692.7000000029802,
+ "routeReadyMedianMs": 668,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -205,15 +205,15 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 124.09999999403954,
+ "domContentLoadedMedianMs": 117.59999999403954,
"id": "editor-minimal",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 0,
- "loadMedianMs": 124.29999999701977,
- "longestTaskMaxMs": 196,
+ "loadMedianMs": 117.79999999701977,
+ "longestTaskMaxMs": 193,
"owner": "workbench",
- "projectSwitchMedianMs": 75.70000000298023,
+ "projectSwitchMedianMs": 72.5,
"readyMark": "invokeai:ready:widget:center:preview",
"remediationTicket": "deepen-widget-registry-loading",
"resourceBaseline": {
@@ -223,9 +223,9 @@
"largestAssetRawBytes": 746376,
"otherRawBytes": 160278,
"requestCount": 115,
- "scriptRawBytes": 3273182,
+ "scriptRawBytes": 3279305,
"scriptRequestCount": 110,
- "totalRawBytes": 3615659
+ "totalRawBytes": 3621782
},
"resourceLimits": {
"cssRawBytes": 2181,
@@ -234,11 +234,11 @@
"largestAssetRawBytes": 753840,
"otherRawBytes": 161881,
"requestCount": 115,
- "scriptRawBytes": 3305914,
+ "scriptRawBytes": 3312099,
"scriptRequestCount": 110,
- "totalRawBytes": 3651816
+ "totalRawBytes": 3658000
},
- "routeReadyMedianMs": 469.59999999403954,
+ "routeReadyMedianMs": 449.09999999403954,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
},
@@ -247,31 +247,31 @@
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 290304,
+ "largestAssetRawBytes": 290332,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 449083,
+ "scriptRawBytes": 449111,
"scriptRequestCount": 7,
- "totalRawBytes": 449083
+ "totalRawBytes": 449111
},
"activatedResourceLimits": {
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 293208,
+ "largestAssetRawBytes": 293236,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 453574,
+ "scriptRawBytes": 453603,
"scriptRequestCount": 7,
- "totalRawBytes": 453574
+ "totalRawBytes": 453603
},
- "domContentLoadedMedianMs": 123.40000000596046,
+ "domContentLoadedMedianMs": 117,
"id": "editor-canvas",
- "layoutAckMedianMs": 2.2999999970197678,
- "layoutReturnSwitchMedianMs": 56.6000000089407,
- "layoutSwitchMedianMs": 97.5,
- "loadMedianMs": 123.5,
- "longestTaskMaxMs": 135,
+ "layoutAckMedianMs": 2,
+ "layoutReturnSwitchMedianMs": 56.400000005960464,
+ "layoutSwitchMedianMs": 96.79999999701977,
+ "loadMedianMs": 117.19999998807907,
+ "longestTaskMaxMs": 142,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -283,9 +283,9 @@
"largestAssetRawBytes": 746376,
"otherRawBytes": 160278,
"requestCount": 122,
- "scriptRawBytes": 3722265,
+ "scriptRawBytes": 3728416,
"scriptRequestCount": 117,
- "totalRawBytes": 4064742
+ "totalRawBytes": 4070893
},
"resourceLimits": {
"cssRawBytes": 2181,
@@ -294,11 +294,11 @@
"largestAssetRawBytes": 753840,
"otherRawBytes": 161881,
"requestCount": 122,
- "scriptRawBytes": 3759488,
+ "scriptRawBytes": 3765701,
"scriptRequestCount": 117,
- "totalRawBytes": 4105390
+ "totalRawBytes": 4111602
},
- "routeReadyMedianMs": 1069.7999999970198,
+ "routeReadyMedianMs": 1057.2000000029802,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "empty"
},
@@ -307,31 +307,31 @@
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 290304,
+ "largestAssetRawBytes": 290332,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 449083,
+ "scriptRawBytes": 449111,
"scriptRequestCount": 7,
- "totalRawBytes": 449083
+ "totalRawBytes": 449111
},
"activatedResourceLimits": {
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 293208,
+ "largestAssetRawBytes": 293236,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 453574,
+ "scriptRawBytes": 453603,
"scriptRequestCount": 7,
- "totalRawBytes": 453574
+ "totalRawBytes": 453603
},
- "domContentLoadedMedianMs": 122.09999999403954,
+ "domContentLoadedMedianMs": 118.69999998807907,
"id": "editor-canvas",
- "layoutAckMedianMs": 2.6000000089406967,
- "layoutReturnSwitchMedianMs": 47.20000000298023,
- "layoutSwitchMedianMs": 80.70000000298023,
- "loadMedianMs": 122.20000000298023,
- "longestTaskMaxMs": 199,
+ "layoutAckMedianMs": 2.4000000059604645,
+ "layoutReturnSwitchMedianMs": 45.400000005960464,
+ "layoutSwitchMedianMs": 82.3999999910593,
+ "loadMedianMs": 118.8999999910593,
+ "longestTaskMaxMs": 180,
"owner": "canvas",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:canvas",
@@ -343,9 +343,9 @@
"largestAssetRawBytes": 746376,
"otherRawBytes": 160278,
"requestCount": 122,
- "scriptRawBytes": 3722265,
+ "scriptRawBytes": 3728416,
"scriptRequestCount": 117,
- "totalRawBytes": 4064742
+ "totalRawBytes": 4070893
},
"resourceLimits": {
"cssRawBytes": 2181,
@@ -354,11 +354,11 @@
"largestAssetRawBytes": 753840,
"otherRawBytes": 161881,
"requestCount": 122,
- "scriptRawBytes": 3759488,
+ "scriptRawBytes": 3765701,
"scriptRequestCount": 117,
- "totalRawBytes": 4105390
+ "totalRawBytes": 4111602
},
- "routeReadyMedianMs": 1165.0999999940395,
+ "routeReadyMedianMs": 1151.5,
"scriptSourceOwnerSet": "editor-canvas-static",
"stateProfile": "representative"
},
@@ -385,13 +385,13 @@
"scriptRequestCount": 6,
"totalRawBytes": 383461
},
- "domContentLoadedMedianMs": 117.29999999701977,
+ "domContentLoadedMedianMs": 117.79999999701977,
"id": "editor-workflow",
- "layoutAckMedianMs": 2.2000000029802322,
- "layoutReturnSwitchMedianMs": 34.5,
- "layoutSwitchMedianMs": 92.8999999910593,
- "loadMedianMs": 117.5,
- "longestTaskMaxMs": 101,
+ "layoutAckMedianMs": 2.3999999910593033,
+ "layoutReturnSwitchMedianMs": 33,
+ "layoutSwitchMedianMs": 90,
+ "loadMedianMs": 117.79999999701977,
+ "longestTaskMaxMs": 99,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -403,9 +403,9 @@
"largestAssetRawBytes": 746376,
"otherRawBytes": 160278,
"requestCount": 122,
- "scriptRawBytes": 3637433,
+ "scriptRawBytes": 3643556,
"scriptRequestCount": 116,
- "totalRawBytes": 3995323
+ "totalRawBytes": 4001446
},
"resourceLimits": {
"cssRawBytes": 17748,
@@ -414,11 +414,11 @@
"largestAssetRawBytes": 753840,
"otherRawBytes": 161881,
"requestCount": 122,
- "scriptRawBytes": 3673808,
+ "scriptRawBytes": 3679992,
"scriptRequestCount": 116,
- "totalRawBytes": 4035277
+ "totalRawBytes": 4041461
},
- "routeReadyMedianMs": 1056.7000000029802,
+ "routeReadyMedianMs": 1056.2000000029802,
"scriptSourceOwnerSet": "editor-workflow-static",
"stateProfile": "empty"
},
@@ -445,13 +445,13 @@
"scriptRequestCount": 6,
"totalRawBytes": 383461
},
- "domContentLoadedMedianMs": 119.70000000298023,
+ "domContentLoadedMedianMs": 119.19999998807907,
"id": "editor-workflow",
- "layoutAckMedianMs": 2.5999999940395355,
- "layoutReturnSwitchMedianMs": 41,
- "layoutSwitchMedianMs": 123.59999999403954,
- "loadMedianMs": 119.79999999701977,
- "longestTaskMaxMs": 357,
+ "layoutAckMedianMs": 2.5,
+ "layoutReturnSwitchMedianMs": 41.19999998807907,
+ "layoutSwitchMedianMs": 127.40000000596046,
+ "loadMedianMs": 119.29999999701977,
+ "longestTaskMaxMs": 351,
"owner": "workflow",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:workflow",
@@ -463,9 +463,9 @@
"largestAssetRawBytes": 746376,
"otherRawBytes": 160278,
"requestCount": 122,
- "scriptRawBytes": 3637433,
+ "scriptRawBytes": 3643556,
"scriptRequestCount": 116,
- "totalRawBytes": 3995323
+ "totalRawBytes": 4001446
},
"resourceLimits": {
"cssRawBytes": 17748,
@@ -474,11 +474,11 @@
"largestAssetRawBytes": 753840,
"otherRawBytes": 161881,
"requestCount": 122,
- "scriptRawBytes": 3673808,
+ "scriptRawBytes": 3679992,
"scriptRequestCount": 116,
- "totalRawBytes": 4035277
+ "totalRawBytes": 4041461
},
- "routeReadyMedianMs": 1181.0999999940395,
+ "routeReadyMedianMs": 1178.2999999970198,
"scriptSourceOwnerSet": "editor-workflow-static",
"stateProfile": "representative"
},
@@ -505,13 +505,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 118.79999999701977,
+ "domContentLoadedMedianMs": 119,
"id": "editor-gallery",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
- "layoutSwitchMedianMs": 24.5,
- "loadMedianMs": 118.90000000596046,
- "longestTaskMaxMs": 98,
+ "layoutSwitchMedianMs": 25.30000001192093,
+ "loadMedianMs": 119.1000000089407,
+ "longestTaskMaxMs": 100,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -523,9 +523,9 @@
"largestAssetRawBytes": 746376,
"otherRawBytes": 160278,
"requestCount": 115,
- "scriptRawBytes": 3273182,
+ "scriptRawBytes": 3279305,
"scriptRequestCount": 110,
- "totalRawBytes": 3615659
+ "totalRawBytes": 3621782
},
"resourceLimits": {
"cssRawBytes": 2181,
@@ -534,11 +534,11 @@
"largestAssetRawBytes": 753840,
"otherRawBytes": 161881,
"requestCount": 115,
- "scriptRawBytes": 3305914,
+ "scriptRawBytes": 3312099,
"scriptRequestCount": 110,
- "totalRawBytes": 3651816
+ "totalRawBytes": 3658000
},
- "routeReadyMedianMs": 1277.6000000089407,
+ "routeReadyMedianMs": 1271.6000000089407,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "empty"
},
@@ -565,13 +565,13 @@
"scriptRequestCount": 0,
"totalRawBytes": 0
},
- "domContentLoadedMedianMs": 119.40000000596046,
+ "domContentLoadedMedianMs": 116.90000000596046,
"id": "editor-gallery",
"layoutAckMedianMs": 0,
"layoutReturnSwitchMedianMs": 0,
"layoutSwitchMedianMs": 89.5,
- "loadMedianMs": 119.5,
- "longestTaskMaxMs": 178,
+ "loadMedianMs": 117.20000000298023,
+ "longestTaskMaxMs": 179,
"owner": "gallery",
"projectSwitchMedianMs": 0,
"readyMark": "invokeai:ready:widget:center:gallery",
@@ -583,9 +583,9 @@
"largestAssetRawBytes": 746376,
"otherRawBytes": 160278,
"requestCount": 115,
- "scriptRawBytes": 3273182,
+ "scriptRawBytes": 3279305,
"scriptRequestCount": 110,
- "totalRawBytes": 3615659
+ "totalRawBytes": 3621782
},
"resourceLimits": {
"cssRawBytes": 2181,
@@ -594,11 +594,11 @@
"largestAssetRawBytes": 753840,
"otherRawBytes": 161881,
"requestCount": 115,
- "scriptRawBytes": 3305914,
+ "scriptRawBytes": 3312099,
"scriptRequestCount": 110,
- "totalRawBytes": 3651816
+ "totalRawBytes": 3658000
},
- "routeReadyMedianMs": 1460.5,
+ "routeReadyMedianMs": 1450.6000000089407,
"scriptSourceOwnerSet": "editor-minimal-static",
"stateProfile": "representative"
}
@@ -1547,6 +1547,8 @@
"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/groupSurfaceCache.ts",
"source:src/workbench/canvas-engine/render/layerCache.ts",
"source:src/workbench/canvas-engine/render/layerDisplayEffect.ts",
"source:src/workbench/canvas-engine/render/maskFill.ts",
@@ -2505,6 +2507,8 @@
"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/groupSurfaceCache.ts",
"source:src/workbench/canvas-engine/render/layerCache.ts",
"source:src/workbench/canvas-engine/render/layerDisplayEffect.ts",
"source:src/workbench/canvas-engine/render/maskFill.ts",
@@ -3663,6 +3667,8 @@
"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/groupSurfaceCache.ts",
"source:src/workbench/canvas-engine/render/layerCache.ts",
"source:src/workbench/canvas-engine/render/layerDisplayEffect.ts",
"source:src/workbench/canvas-engine/render/maskFill.ts",
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts
index 52e43c6c38..75fabc68cb 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts
@@ -1,11 +1,16 @@
import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';
-import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type {
+ CanvasDocumentContractV3,
+ CanvasLayerContract,
+ CanvasNodeContract,
+} from '@workbench/canvas-engine/contracts';
import type { CanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';
import type { CanvasNodeInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';
import type { CanvasEditConcurrency } from '@workbench/canvas-engine/editConcurrency';
import type { History } from '@workbench/canvas-engine/history/history';
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
+import type { CompositeOptions } from '@workbench/canvas-engine/render/compositor';
import type { DerivedSurfaceCache } from '@workbench/canvas-engine/render/derivedSurfaceCache';
import type {
LayerCacheEntry,
@@ -17,7 +22,7 @@ import type { Rect } from '@workbench/canvas-engine/types';
import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';
import { getDocumentLayer, getDocumentLeaves, isNodeAbsent } from '@workbench/canvas-engine/document/documentIndex';
-import { createEmptyStacks } from '@workbench/canvas-engine/document/documentTree';
+import { createEmptyStacks, isGroupNode } from '@workbench/canvas-engine/document/documentTree';
import { getSourceContentRect } from '@workbench/canvas-engine/document/sources';
import { isEmpty } from '@workbench/canvas-engine/math/rect';
import { compositeDocument } from '@workbench/canvas-engine/render/compositor';
@@ -46,6 +51,7 @@ export interface ExtractMaskedAreaControllerOptions {
readonly rasterize: (layerId: string) => Promise<ExportResult>;
readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;
readonly getAdjustedSurface: (layer: CanvasLayerContract, entry: LayerCacheEntry) => RasterSurface | null;
+ readonly getGroupSurface?: CompositeOptions['groupSurface'];
readonly getMaskPattern: (style: string, color: string) => RasterSurface | null;
readonly createLayerId: () => string;
readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => CanvasNodeInsertionAnchor;
@@ -58,8 +64,20 @@ export interface ExtractMaskedAreaControllerOptions {
) => void;
}
-/** Owns guarded extraction of raster content through an inpaint mask. */
-/** Contributing raster leaves with content, top first, with ancestor state applied. */
+/**
+ * The raster forest reduced to `keep` leaves with the GROUP topology intact:
+ * an adjusted group's stack must apply to the extracted composite exactly as
+ * it applies on screen, so groups cannot be flattened away here.
+ */
+const filterRasterForest = (nodes: readonly CanvasNodeContract[], keep: ReadonlySet<string>): CanvasNodeContract[] =>
+ nodes.flatMap((node): CanvasNodeContract[] => {
+ if (isGroupNode(node)) {
+ const children = filterRasterForest(node.children, keep);
+ return children.length > 0 ? [{ ...node, children }] : [];
+ }
+ return keep.has(node.id) ? [node] : [];
+ });
+
const contributingRasters = (
document: CanvasDocumentContractV3,
hasContent: (layerId: string) => boolean
@@ -68,6 +86,7 @@ const contributingRasters = (
.filter((leaf) => leaf.stack === 'raster' && leaf.contributionEnabled && hasContent(leaf.id))
.map((leaf) => leaf.layer);
+/** Owns guarded extraction of raster content through an inpaint mask. */
export class ExtractMaskedAreaController {
private disposed = false;
constructor(private readonly deps: ExtractMaskedAreaControllerOptions) {}
@@ -177,11 +196,18 @@ export class ExtractMaskedAreaController {
const pixels = this.deps.backend.createSurface(rect.width, rect.height);
compositeDocument(
pixels,
- { ...document, stacks: { ...createEmptyStacks(), raster: contributors } },
+ {
+ ...document,
+ stacks: {
+ ...createEmptyStacks(),
+ raster: filterRasterForest(document.stacks.raster, new Set(contributors.map((layer) => layer.id))),
+ },
+ },
this.deps.layers,
{ a: 1, b: 0, c: 0, d: 1, e: -rect.x, f: -rect.y },
{
adjustedSurface: this.deps.getAdjustedSurface,
+ groupSurface: this.deps.getGroupSurface,
backend: this.deps.backend,
derivedSurfaces: this.deps.derived,
diagnostics: this.deps.diagnostics,
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 f77ccdd55c..265d6e5058 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts
@@ -15,9 +15,15 @@ import { removeNodes } from '@workbench/canvas-engine/document/documentTree';
import { insertNodesAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
import { haveSameStructure } from '@workbench/canvas-engine/document/layerStacks';
import { mergeDownMatrix } from '@workbench/canvas-engine/document/mergeDown';
-import { canMergeSelectedRasters, getMergeVisibleRasterLayers } from '@workbench/canvas-engine/document/mergeVisible';
+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 { blendToComposite } from '@workbench/canvas-engine/render/compositor';
+import {
+ collectAdjustedGroups,
+ planGroupAdjustmentScopes,
+ type GroupAdjustmentScope,
+} from '@workbench/canvas-engine/render/groupAdjustmentScopes';
import type { CanvasMutationContext } from './mutationContext';
@@ -141,7 +147,11 @@ export class MergeLayerController {
if (!document) {
return 'nothing';
}
- const contributors = getMergeVisibleRasterLayers(compileDocumentLeaves(document), this.deps.hasExportableContent);
+ const contributorLeaves = getMergeVisibleRasterLeaves(
+ compileDocumentLeaves(document),
+ this.deps.hasExportableContent
+ );
+ const contributors = contributorLeaves.map((leaf) => leaf.layer);
if (contributors.length < 2) {
return 'nothing';
}
@@ -187,16 +197,25 @@ export class MergeLayerController {
}
const liveDocument = this.deps.ctx.getDocument();
- const liveContributors = liveDocument
- ? getMergeVisibleRasterLayers(compileDocumentLeaves(liveDocument), this.deps.hasExportableContent)
+ const liveLeaves = liveDocument
+ ? getMergeVisibleRasterLeaves(compileDocumentLeaves(liveDocument), this.deps.hasExportableContent)
: [];
if (
!liveDocument ||
- liveContributors.length !== contributors.length ||
- liveContributors.some((layer, index) => layer !== contributors[index])
+ liveLeaves.length !== contributors.length ||
+ liveLeaves.some((leaf, index) => leaf.layer !== contributors[index])
) {
return 'not-ready';
}
+ // Leaf identity alone misses two mid-await edits this feature introduces:
+ // an ancestor group's STACK changing (leaf objects untouched), and a
+ // re-parent in/out of an adjusted group that keeps the flat order. The
+ // scope plan folds both, so compare it against the pre-export plan.
+ const scopes = planGroupAdjustmentScopes(contributorLeaves, collectAdjustedGroups(document));
+ const liveScopes = planGroupAdjustmentScopes(liveLeaves, collectAdjustedGroups(liveDocument));
+ if (JSON.stringify(liveScopes) !== JSON.stringify(scopes)) {
+ return 'not-ready';
+ }
const successful = exports as Extract<ExportResult, { status: 'ok' }>[];
let rect = successful[0]!.rect;
@@ -211,13 +230,43 @@ export class MergeLayerController {
const context = pixels.ctx;
context.setTransform(1, 0, 0, 1, 0, 0);
context.clearRect(0, 0, rect.width, rect.height);
- for (let index = successful.length - 1; index >= 0; index -= 1) {
- const exported = successful[index]!;
- const contributor = contributors[index]!;
- context.globalAlpha = contributor.opacity;
- context.globalCompositeOperation = blendToComposite(contributor.blendMode);
- context.drawImage(exported.surface.canvas, exported.rect.x - rect.x, exported.rect.y - rect.y);
- }
+ // Contributors inside an adjusted group composite through an isolated
+ // buffer with the group's stack applied, exactly as the screen draws
+ // them — merged pixels must reproduce the screen, and a per-leaf bake
+ // cannot under member opacity/blending.
+ const drawMerged = (
+ target: RasterSurface['ctx'],
+ from: number,
+ to: number,
+ range: readonly GroupAdjustmentScope[]
+ ): void => {
+ let scopeIndex = range.length - 1;
+ for (let index = to - 1; index >= from;) {
+ const scope = scopeIndex >= 0 ? range[scopeIndex]! : null;
+ if (scope && index >= scope.start && index < scope.end) {
+ const buffer = this.deps.backend.createSurface(rect.width, rect.height);
+ 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';
+ target.drawImage(buffer.canvas, 0, 0);
+ index = scope.start - 1;
+ scopeIndex -= 1;
+ continue;
+ }
+ const exported = successful[index]!;
+ const contributor = contributors[index]!;
+ target.globalAlpha = contributor.opacity;
+ target.globalCompositeOperation = blendToComposite(contributor.blendMode);
+ target.drawImage(exported.surface.canvas, exported.rect.x - rect.x, exported.rect.y - rect.y);
+ index -= 1;
+ }
+ };
+ drawMerged(context, 0, successful.length, scopes);
context.globalAlpha = 1;
context.globalCompositeOperation = 'source-over';
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 c2542c7899..61d66d3625 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/psdExportController.ts
@@ -1,5 +1,5 @@
import type { CanvasDocumentSnapshot, PsdExportResult } from '@workbench/canvas-engine/capabilities';
-import type { CanvasNodeContract } from '@workbench/canvas-engine/contracts';
+import type { CanvasAdjustmentsContract, CanvasNodeContract } from '@workbench/canvas-engine/contracts';
import type {
CanvasDetachedLayerSurface,
CaptureRasterSnapshotResult,
@@ -93,12 +93,24 @@ export class PsdExportController {
// The raster tree as it stands, minus leaves with nothing captured; the planner derives
// effective visibility from the own flags, the same way Photoshop will.
let missing: string | null = null;
- const toInputs = (nodes: readonly CanvasNodeContract[]): PsdExportNodeInput[] =>
+ // PSD has no representation for a GROUP's adjustment stack, so each
+ // enclosing stack is baked into every descendant leaf (own stack
+ // first, then innermost ancestor outward). Exact for opaque
+ // source-over members; under member opacity/blending it is the
+ // accepted approximation — and the merged preview flattens the same
+ // baked pixels, so the file stays self-consistent.
+ const toInputs = (
+ nodes: readonly CanvasNodeContract[],
+ ancestorStacks: readonly CanvasAdjustmentsContract[] = []
+ ): PsdExportNodeInput[] =>
nodes.flatMap((node): PsdExportNodeInput[] => {
if (isGroupNode(node)) {
+ const stacks = isIdentityAdjustments(node.adjustments)
+ ? ancestorStacks
+ : [...ancestorStacks, node.adjustments!];
return [
{
- children: toInputs(node.children),
+ children: toInputs(node.children, stacks),
id: node.id,
isEnabled: node.isEnabled,
name: node.name,
@@ -116,11 +128,14 @@ export class PsdExportController {
}
return [];
}
+ const combined = [
+ ...(node.type === 'raster' ? (node.adjustments ?? []) : []),
+ ...[...ancestorStacks].reverse().flat(),
+ ];
return [
{
// Identity-aware: an emptied stack must not trigger the executor's bake writeback.
- adjustments:
- node.type === 'raster' && !isIdentityAdjustments(node.adjustments) ? node.adjustments : undefined,
+ adjustments: isIdentityAdjustments(combined) ? undefined : combined,
blendMode: node.blendMode,
contentRect: detached.rect,
id: node.id,
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 525eb25071..97ca8b0636 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
@@ -93,6 +93,7 @@ const spyCallbacks = () => ({
onDocumentReplaced: vi.fn<DocumentMirrorCallbacks['onDocumentReplaced']>(),
onLayerOrderChanged: vi.fn<DocumentMirrorCallbacks['onLayerOrderChanged']>(),
onLayersChanged: vi.fn<DocumentMirrorCallbacks['onLayersChanged']>(),
+ onLayersRecomposite: vi.fn<NonNullable<DocumentMirrorCallbacks['onLayersRecomposite']>>(),
onSelectionChanged: vi.fn<NonNullable<DocumentMirrorCallbacks['onSelectionChanged']>>(),
onStagingChanged: vi.fn<DocumentMirrorCallbacks['onStagingChanged']>(),
});
@@ -493,7 +494,7 @@ describe('createDocumentMirror: groups', () => {
expect(callbacks.onLayerOrderChanged).not.toHaveBeenCalled();
});
- it('fans a group adjustment-stack edit out to every descendant leaf, appearance-only', () => {
+ it('fans a group adjustment-stack edit out to descendants on the non-destructive recomposite channel', () => {
const a = rasterLayer('a');
const b = rasterLayer('b');
const c = rasterLayer('c');
@@ -505,7 +506,10 @@ describe('createDocumentMirror: groups', () => {
...doc,
stacks: stacksFrom([groupContract('g', [a, groupContract('h', [b])], { adjustments: stack }), c]),
});
- expect(callbacks.onLayersChanged).toHaveBeenLastCalledWith(['a', 'b'], []);
+ // The descendants' own pixels/flags are untouched, so the destructive
+ // onLayersChanged reactions (float and pixel-edit cancellation) must not run.
+ expect(callbacks.onLayersChanged).not.toHaveBeenCalled();
+ expect(callbacks.onLayersRecomposite).toHaveBeenLastCalledWith(['a', 'b']);
expect(callbacks.onLayerOrderChanged).not.toHaveBeenCalled();
});
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 9489fcb3c0..7b2965e178 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts
@@ -26,6 +26,14 @@ export interface DocumentMirrorCallbacks {
* keeps its raster cache.
*/
onLayersChanged(changed: string[], sourceChanged: string[]): void;
+ /**
+ * Leaves whose rendered contribution changed ONLY because an ancestor
+ * group's adjustment stack did: their pixels, sources, and effective flags
+ * are untouched, so the engine must recomposite them but must NOT run the
+ * destructive reactions `onLayersChanged` carries (float and pixel-edit
+ * cancellation). Optional so minimal harnesses need not care.
+ */
+ onLayersRecomposite?(ids: string[]): void;
/** The forests were restructured without any leaf changing: recomposite with the new order. */
onLayerOrderChanged(): void;
/** The document was replaced wholesale (dims/background change, appear/disappear) — full invalidate. */
@@ -75,6 +83,8 @@ const effectiveKey = (entry: CanvasNodeEntry): string =>
interface ForestDiff {
changed: string[];
sourceChanged: string[];
+ /** Ancestor-adjustment fan-out only; disjoint from `changed`. */
+ recompositeOnly: string[];
restructured: boolean;
}
@@ -86,6 +96,7 @@ interface ForestDiff {
const diffForests = (prev: CanvasDocumentIndex, next: CanvasDocumentIndex): ForestDiff => {
const changed = new Set<string>();
const sourceChanged = new Set<string>();
+ const recompositeOnly = new Set<string>();
// A group whose adjustment stack changed re-renders every leaf beneath it.
// `next.nodes` is preorder, so these ids are collected before their leaves.
const adjustedGroups = new Set<string>();
@@ -114,11 +125,10 @@ const diffForests = (prev: CanvasDocumentIndex, next: CanvasDocumentIndex): Fore
if (rasterSourceRef(before.node as CanvasLayerContract) !== rasterSourceRef(entry.node)) {
sourceChanged.add(entry.node.id);
}
- } else if (
- effectiveKey(before) !== effectiveKey(entry) ||
- entry.path.some((ancestorId) => adjustedGroups.has(ancestorId))
- ) {
+ } else if (effectiveKey(before) !== effectiveKey(entry)) {
changed.add(entry.node.id);
+ } else if (entry.path.some((ancestorId) => adjustedGroups.has(ancestorId))) {
+ recompositeOnly.add(entry.node.id);
}
}
for (const entry of prev.nodes) {
@@ -129,7 +139,12 @@ const diffForests = (prev: CanvasDocumentIndex, next: CanvasDocumentIndex): Fore
}
}
}
- return { changed: [...changed], restructured, sourceChanged: [...sourceChanged] };
+ return {
+ changed: [...changed],
+ recompositeOnly: [...recompositeOnly].filter((id) => !changed.has(id)),
+ restructured,
+ sourceChanged: [...sourceChanged],
+ };
};
/**
@@ -186,6 +201,9 @@ export const createDocumentMirror = (
} else if (diff.restructured) {
callbacks.onLayerOrderChanged();
}
+ if (diff.recompositeOnly.length > 0) {
+ callbacks.onLayersRecomposite?.(diff.recompositeOnly);
+ }
}
if (!bboxEqual(prevDoc.bbox, doc.bbox)) {
callbacks.onBboxChanged();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.ts
index 06054b0288..f732a7b367 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/mergeVisible.ts
@@ -7,13 +7,17 @@ import { isLayerEditable } from './layerEligibility';
export type HasMergeVisibleContent = (layerId: string) => boolean;
/** Contributing raster leaves with content, top first. */
+export const getMergeVisibleRasterLeaves = (
+ leaves: readonly SemanticLeaf[],
+ hasContent: HasMergeVisibleContent
+): SemanticLeaf[] =>
+ leaves.filter((leaf) => leaf.stack === 'raster' && leaf.contributionEnabled && hasContent(leaf.id));
+
+/** Contributing raster layers with content, top first. */
export const getMergeVisibleRasterLayers = (
leaves: readonly SemanticLeaf[],
hasContent: HasMergeVisibleContent
-): CanvasLayerContract[] =>
- leaves
- .filter((leaf) => leaf.stack === 'raster' && leaf.contributionEnabled && hasContent(leaf.id))
- .map((leaf) => leaf.layer);
+): CanvasLayerContract[] => getMergeVisibleRasterLeaves(leaves, hasContent).map((leaf) => leaf.layer);
/** Whether the raster stack's merge-visible action has at least two contributors. */
export const canMergeVisibleRasters = (leaves: readonly SemanticLeaf[], hasContent: HasMergeVisibleContent): boolean =>
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index a089c263f1..92ed69bff4 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -114,7 +114,7 @@ import {
createDocumentModel,
type CanvasDocumentModel,
} from '@workbench/canvas-engine/document-model/documentModel';
-import { getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';
+import { getDocumentIndex, getDocumentLayer, getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';
import {
createEngineStores,
type EngineStores,
@@ -130,8 +130,13 @@ import {
import { createPointerPipeline, type PointerPipeline } from '@workbench/canvas-engine/input/pointerPipeline';
import { createWheelHandler } from '@workbench/canvas-engine/input/wheel';
import { isEmpty, union } from '@workbench/canvas-engine/math/rect';
-import { compositeDocument, createCheckerboardTile } from '@workbench/canvas-engine/render/compositor';
+import {
+ compositeDocument,
+ createCheckerboardTile,
+ type CompositeOptions,
+} from '@workbench/canvas-engine/render/compositor';
import { createFontLoader, domFontLoadApi } from '@workbench/canvas-engine/render/fontLoader';
+import { createGroupSurfaceCache } from '@workbench/canvas-engine/render/groupSurfaceCache';
import { hasLayerDisplayEffect } from '@workbench/canvas-engine/render/layerDisplayEffect';
import { createMaskPatternTile } from '@workbench/canvas-engine/render/maskFill';
import { renderOverlay } from '@workbench/canvas-engine/render/overlayRenderer';
@@ -526,6 +531,17 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
return rasterController.getAdjustedSurface(layer, entry);
};
+ // Memoized document-space composites of adjusted GROUPS. Members draw
+ // through the guarded `getAdjustedSurface` above, so a member's own stack
+ // (and the pixel-edit double-apply guard) behave identically inside a group.
+ const groupSurfaces = createGroupSurfaceCache({
+ createSurface: (width, height) => backend.createSurface(width, height),
+ getAdjustedSurface: (layer, entry) => getAdjustedSurface(layer, entry),
+ getCacheEntry: (layerId) => layerCache.get(layerId),
+ });
+ const getGroupSurface: NonNullable<CompositeOptions['groupSurface']> = (scope, members, matrices, excludeIds) =>
+ groupSurfaces.get(scope, members, matrices, excludeIds);
+
/**
* Re-reads the live cache sizes into the memory budget. Both caches change
* outside the budget's knowledge (a rasterize grows one, an eviction shrinks
@@ -534,7 +550,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
*/
const syncMemoryBaselines = (): void => {
rasterController.memory.setBaseBytes(layerCache.byteSize());
- rasterController.memory.setDerivedBytes(derivedSurfaceCache.byteSize());
+ // Group surfaces are derived pixels too: they must count against the same
+ // budget or an adjusted group's doc-space composite is invisible memory.
+ rasterController.memory.setDerivedBytes(derivedSurfaceCache.byteSize() + groupSurfaces.byteSize());
};
// Completed-stroke subscribers (persistence P2.2, history P2.3).
@@ -1076,6 +1094,11 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
getSamInteraction: () => stores.samInteraction.get(),
openTextCreate: (docPoint) => openTextCreate(docPoint),
openTextEdit: (layerId) => openTextEdit(layerId),
+ sampleProviders: {
+ adjustedSurface: getAdjustedSurface,
+ derivedSurfaces: derivedSurfaceCache,
+ groupSurface: getGroupSurface,
+ },
resolveColorSample: (hex) => {
if (pendingColorSample) {
pendingColorSample.sampledHex = hex;
@@ -1418,6 +1441,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
derivedSurfaceCache,
diagnostics,
getAdjustedSurface,
+ getGroupSurface,
getCheckerboardTile,
getMaskPatternTile,
layerCache,
@@ -1477,6 +1501,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
},
onDocumentReplaced: () => {
const cleanup = createCleanupAccumulator();
+ cleanup.run(() => groupSurfaces.clear());
cleanup.run(() => editingController.invalidateDocument());
cleanup.run(() => pipeline.cancelActiveGesture());
cleanup.run(cancelOpenPixelEdit);
@@ -1556,10 +1581,23 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
cleanup.throwIfFailed();
},
onLayerOrderChanged: () => {
+ const doc = mirror.getDocument();
+ groupSurfaces.prune(doc ? new Set(getDocumentIndex(doc).byId.keys()) : new Set());
scheduler.invalidate({ all: true });
},
+ onLayersRecomposite: (ids) => {
+ // An ancestor group's stack changed: leaf pixels and caches are intact,
+ // and the group surface rebuilds itself off its key. Only recomposite.
+ scheduler.invalidate({ layers: ids });
+ },
onLayersChanged: (ids, sourceChangedIds) => {
const cleanup = createCleanupAccumulator();
+ // A removal that deletes a group together with its leaves reports leaf
+ // ids here (not onLayerOrderChanged), so the group cache prunes on both.
+ {
+ const doc = mirror.getDocument();
+ cleanup.run(() => groupSurfaces.prune(doc ? new Set(getDocumentIndex(doc).byId.keys()) : new Set()));
+ }
const floatLayerId = floatingSelection.get()?.layerId;
if (floatLayerId && ids.includes(floatLayerId)) {
// The float's layer was replaced or removed. Drop the float rather than
@@ -2803,6 +2841,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
endBurst: () => endNudgeBurst(),
exportBaked: (layerId, includeDisabled) => exportBakedLayerPixelsForStructural(layerId, { includeDisabled }),
getAdjustedSurface,
+ getGroupSurface,
getDocument: () => mirror.getDocument(),
getMaskPattern: getMaskPatternTile,
getReducerDocument,
@@ -3052,6 +3091,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
backend,
checkerboardTile: null,
derivedSurfaces: derivedSurfaceCache,
+ groupSurface: getGroupSurface,
imageSmoothing: true,
maskPatternTile: getMaskPatternTile,
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.ts
index 87cfb11750..fe8991c0b8 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/exportRasterComposite.ts
@@ -4,6 +4,7 @@ import type { Rect } from '@workbench/canvas-engine/types';
import { isEmpty } from '@workbench/canvas-engine/math/rect';
import {
+ type CompositeEntry,
getBaseRasterContentBounds,
planBaseRasterComposite,
renderRasterComposite,
@@ -44,6 +45,9 @@ export interface ExportRasterCompositeDeps extends RenderRasterCompositeDeps {
pin?(layerIds: readonly string[]): { release(): void };
}
+const countGroupScopes = (scopes: CompositeEntry['groupScopes']): number =>
+ (scopes ?? []).reduce((total, scope) => total + 1 + countGroupScopes(scope.children), 0);
+
export const exportRasterComposite = async (
request: RasterCompositeExportRequest,
deps: ExportRasterCompositeDeps
@@ -65,8 +69,11 @@ export const exportRasterComposite = async (
}
// Each adjusted layer needs both a temporary surface and a same-sized
- // ImageData buffer in addition to the final composite surface.
- const surfaceCount = 1 + entry.layers.filter((layer) => layer.adjustments !== undefined).length * 2;
+ // ImageData buffer in addition to the final composite surface; each adjusted
+ // GROUP scope likewise isolates into a buffer plus an ImageData pass.
+ const surfaceCount =
+ 1 +
+ (entry.layers.filter((layer) => layer.adjustments !== undefined).length + countGroupScopes(entry.groupScopes)) * 2;
const reservation = deps.reserve?.(rect.width * rect.height * 4 * surfaceCount);
if (reservation?.status === 'over-budget') {
return { status: 'over-budget' };
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.ts
index 47407e9958..1f37589ac9 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/colorSample.ts
@@ -19,7 +19,7 @@ import type { Mat2d, Vec2 } from '@workbench/canvas-engine/types';
import type { LayerCacheStore } from './layerCache';
import type { RasterBackend } from './raster';
-import { compositeDocument } from './compositor';
+import { compositeDocument, type CompositeOptions } from './compositor';
/** An RGBA sample, channels in `[0, 255]`. */
export interface RgbaSample {
@@ -40,7 +40,8 @@ export const sampleDocumentColor = (
doc: CanvasDocumentContractV3,
layers: LayerCacheStore,
backend: RasterBackend,
- docPoint: Vec2
+ docPoint: Vec2,
+ providers: Pick<CompositeOptions, 'adjustedSurface' | 'derivedSurfaces' | 'groupSurface'> = {}
): RgbaSample | null => {
const px = Math.floor(docPoint.x);
const py = Math.floor(docPoint.y);
@@ -53,7 +54,10 @@ export const sampleDocumentColor = (
// Reuse the canonical compositor so sampling shares its layer ordering,
// cache-origin placement, transforms, blend modes, and display effects.
// Omitting a checkerboard tile and staged preview keeps empty space transparent.
- compositeDocument(scratch, doc, layers, view, { backend });
+ // The providers make the sample WYSIWYG: layer and group adjustment stacks
+ // apply exactly as the screen draws them. Absent (minimal harnesses), the
+ // sample reads raw cached pixels.
+ compositeDocument(scratch, doc, layers, view, { backend, ...providers });
const { data } = scratch.ctx.getImageData(0, 0, 1, 1);
const alpha = data[3] ?? 0;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.ts
index a8aebdc342..919f9fae69 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.test.ts
@@ -78,6 +78,7 @@ const makeHarness = (): Harness => {
derivedSurfaceCache: { byteSize: () => 0 } as CreateCompositeFrameDeps['derivedSurfaceCache'],
diagnostics: {} as CreateCompositeFrameDeps['diagnostics'],
getAdjustedSurface: () => null,
+ getGroupSurface: () => null,
getCheckerboardTile: () => surface(8, 8),
getMaskPatternTile: () => null,
layerCache: {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts
index bfa289fd92..0ad50c2277 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts
@@ -15,7 +15,11 @@ import type { Viewport } from '@workbench/canvas-engine/viewport';
import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';
import { isLayerContributing } from '@workbench/canvas-engine/document/layerEligibility';
import { getSourceContentRect, isRenderableLayer, renderableSourceOf } from '@workbench/canvas-engine/document/sources';
-import { compositeDocument, shouldSmoothAtZoom } from '@workbench/canvas-engine/render/compositor';
+import {
+ compositeDocument,
+ shouldSmoothAtZoom,
+ type CompositeOptions,
+} from '@workbench/canvas-engine/render/compositor';
import { calculateActiveFrameLayerIds } from '@workbench/canvas-engine/render/frameDemand';
import { enforceSurfaceBudget } from '@workbench/canvas-engine/render/surfaceBudget';
@@ -33,6 +37,7 @@ export interface CreateCompositeFrameDeps {
readonly viewport: Viewport;
readonly transformOverrides: LayerTransformOverrides;
readonly getAdjustedSurface: (layer: CanvasLayerContract, entry: LayerCacheEntry) => RasterSurface | null;
+ readonly getGroupSurface: NonNullable<CompositeOptions['groupSurface']>;
readonly getMaskPatternTile: (style: string, color: string) => RasterSurface | null;
readonly getCheckerboardTile: () => RasterSurface;
/** Starts (or joins) the rasterization of a layer whose cache is stale. */
@@ -186,6 +191,7 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeF
// refreshes only the band the stroke reported writing, rather than
// re-deriving from the whole layer (see adjustedSurfaceCache).
adjustedSurface: deps.getAdjustedSurface,
+ groupSurface: deps.getGroupSurface,
// The raster backend + mask fill tile resolver drive the mask colorize
// path (alpha stencil → source-in fill colour/pattern, above all layers).
backend: deps.backend,
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 e6e37ec9b0..fa7750aacf 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
@@ -31,10 +31,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 { LayerCacheEntry, LayerCacheStore } from './layerCache';
import type { RasterBackend, RasterSurface } from './raster';
import { renderControlTransparency } from './controlTransparency';
+import { collectAdjustedGroups, planGroupAdjustmentScopes } from './groupAdjustmentScopes';
import { colorizeMask } from './maskFill';
/** Screen-space size (px) of each checkerboard square for transparent backgrounds. */
@@ -189,6 +191,23 @@ export interface CompositeOptions {
floatingSelection?: { layerId: string; surface: RasterSurface; rect: Rect; matrix: Mat2d } | null;
/** Optional deterministic render counters; omitted in the normal zero-overhead path. */
diagnostics?: CanvasDiagnostics | null;
+ /**
+ * Returns an adjusted GROUP's document-space composite (its members drawn,
+ * the group's stack applied), or `null` when the group currently has no
+ * drawable content. The engine wires a memoizing {@link
+ * import('./groupSurfaceCache').GroupSurfaceCache}. Members named in
+ * `excludeIds` are left out of the composite so the caller can draw them
+ * separately (pixel-edit skips, filter previews). Absent ⇒ group stacks are
+ * ignored and members draw flat (a bare test call).
+ */
+ groupSurface?:
+ | ((
+ scope: GroupAdjustmentScope,
+ members: readonly SemanticLeaf[],
+ memberMatrices: readonly Mat2d[],
+ excludeIds: ReadonlySet<string>
+ ) => { surface: RasterSurface; rect: Rect } | null)
+ | null;
}
type Ctx = RasterSurface['ctx'];
@@ -548,10 +567,16 @@ export const compositeDocument = (
isolationLayerId: opts.isolationLayerId ?? null,
showOverlayStacks: ALL_OVERLAY_STACKS_SHOWN,
});
- for (const leaf of plan.leaves) {
- if (leaf.id === opts.skipLayerId) {
- continue;
- }
+ // Adjusted-group scopes: their members composite through an isolated,
+ // stack-adjusted surface instead of drawing flat. Isolation mode inspects
+ // raw members, so scopes are bypassed while it is active; without a
+ // provider (bare test calls, color sampling in minimal harnesses) members
+ // draw flat too.
+ const scopes =
+ opts.groupSurface && !isIsolated(opts) ? planGroupAdjustmentScopes(plan.leaves, collectAdjustedGroups(doc)) : [];
+ let scopeIndex = 0;
+
+ const drawLeafFlat = (leaf: SemanticLeaf): void => {
opts.diagnostics?.increment('layersConsidered');
const float = opts.floatingSelection?.layerId === leaf.id ? opts.floatingSelection : null;
const entry = caches.get(leaf.id);
@@ -562,17 +587,68 @@ export const compositeDocument = (
if (float) {
drawFloatingSelection(ctx, leaf, view, opts, float);
}
- continue;
+ return;
}
if (isDefinitelyOffscreen(leaf, entry, view, target, opts) && !float) {
opts.diagnostics?.increment('layersCulled');
- continue;
+ return;
}
drawCachedLayer(ctx, leaf, entry, view, opts);
if (float) {
drawFloatingSelection(ctx, leaf, view, opts, float);
}
opts.diagnostics?.increment('layersDrawn');
+ };
+
+ for (let index = 0; index < plan.leaves.length; index += 1) {
+ const scope = scopeIndex < scopes.length ? scopes[scopeIndex]! : null;
+ if (scope && index === scope.start) {
+ const members = plan.leaves.slice(scope.start, scope.end);
+ const matrices = members.map((member) => getEffectiveLayerMatrix(member, opts));
+ // Members the caller draws through other channels are left out of the
+ // composite: a pixel-edit skip target, and filter-preview targets (the
+ // preview replaces the member's pixels and draws separately, without the
+ // group stack — a transient divergence that ends with the operation).
+ const excluded = new Set<string>();
+ for (const member of members) {
+ if (member.id === opts.skipLayerId || opts.layerPreviews?.has(member.id)) {
+ excluded.add(member.id);
+ }
+ }
+ const result = opts.groupSurface!(scope, members, matrices, excluded);
+ if (result) {
+ ctx.save();
+ ctx.globalAlpha = 1;
+ ctx.globalCompositeOperation = 'source-over';
+ setTransformFromMat(ctx, view);
+ ctx.drawImage(result.surface.canvas, result.rect.x, result.rect.y);
+ ctx.restore();
+ opts.diagnostics?.increment('layersDrawn');
+ // Excluded members and in-flight floats still draw on top. A float
+ // whose member IS in the composite draws alone — its member's pixels
+ // are already in the group surface.
+ for (const member of members) {
+ if (member.id === opts.skipLayerId) {
+ continue;
+ }
+ if (excluded.has(member.id)) {
+ drawLeafFlat(member);
+ } else if (opts.floatingSelection?.layerId === member.id) {
+ drawFloatingSelection(ctx, member, view, opts, opts.floatingSelection);
+ }
+ }
+ index = scope.end - 1;
+ scopeIndex += 1;
+ continue;
+ }
+ // No drawable content (or no cache yet): fall through to flat drawing.
+ scopeIndex += 1;
+ }
+ const leaf = plan.leaves[index]!;
+ if (leaf.id === opts.skipLayerId) {
+ continue;
+ }
+ drawLeafFlat(leaf);
}
if (opts.clipRect) {
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
new file mode 100644
index 0000000000..8fc94bf811
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupAdjustmentComposite.browser.test.ts
@@ -0,0 +1,207 @@
+import type { CanvasAdjustmentsContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';
+import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
+import type { Rect } from '@workbench/canvas-engine/types';
+
+import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { identity } from '@workbench/canvas-engine/math/mat2d';
+import { sampleDocumentColor } from '@workbench/canvas-engine/render/colorSample';
+import { compositeDocument } from '@workbench/canvas-engine/render/compositor';
+import { createGroupSurfaceCache } from '@workbench/canvas-engine/render/groupSurfaceCache';
+import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';
+import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';
+import { planBaseRasterComposite, renderRasterComposite } from '@workbench/canvas-engine/render/rasterComposite';
+import { describe, expect, it } from 'vitest';
+
+const WIDTH = 64;
+const HEIGHT = 64;
+const BBOX: Rect = { height: HEIGHT, width: WIDTH, x: 0, y: 0 };
+
+const raster = (id: string, overrides: Partial<CanvasRasterLayerContractV2> = {}): CanvasRasterLayerContractV2 => ({
+ blendMode: 'normal',
+ id,
+ isEnabled: true,
+ isLocked: false,
+ name: id,
+ opacity: 1,
+ source: { bitmap: { height: HEIGHT, imageName: id, width: WIDTH }, type: 'paint' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type: 'raster',
+ ...overrides,
+});
+
+/** Midtone-lifting levels (gamma 2): deliberately NON-affine, so applying it to a
+ * composite differs measurably from applying it to each member before blending. */
+const gammaStack = (id: string): CanvasAdjustmentsContract => [
+ { gamma: 2, id, inBlack: 0, inWhite: 255, isEnabled: true, outBlack: 0, outWhite: 255, type: 'levels' },
+];
+const invertStack = (id: string): CanvasAdjustmentsContract => [{ id, isEnabled: true, type: 'invert' }];
+
+const sceneFor = (fills: Record<string, string>) => {
+ const backend = createDomRasterBackend();
+ const caches = createLayerCacheStore(backend);
+ for (const [id, color] of Object.entries(fills)) {
+ caches.growToRect(id, BBOX);
+ const surface = caches.get(id)!.surface;
+ surface.ctx.setTransform(1, 0, 0, 1, 0, 0);
+ surface.ctx.fillStyle = color;
+ surface.ctx.fillRect(0, 0, WIDTH, HEIGHT);
+ caches.publishPixels(id);
+ }
+ return {
+ backend,
+ caches,
+ getLayerSurface: (layerId: string) => {
+ const entry = caches.get(layerId)!;
+ return Promise.resolve({ rect: entry.rect, surface: entry.surface });
+ },
+ };
+};
+
+const centerPixel = (surface: RasterSurface): number[] => [
+ ...surface.ctx.getImageData(WIDTH / 2, HEIGHT / 2, 1, 1).data,
+];
+
+const docWith = (nodes: Parameters<typeof stacksFrom>[0]) => ({
+ background: 'transparent' as const,
+ bbox: BBOX,
+ height: HEIGHT,
+ selectedLayerId: null,
+ stacks: stacksFrom(nodes),
+ version: 3 as const,
+ width: WIDTH,
+});
+
+describe('group adjustment composite', () => {
+ it('applies the stack to the group composite, not to each member (the per-leaf bake is measurably wrong)', async () => {
+ // 50% red over white inside the group → pink (255,~127,~127);
+ // gamma-2 on the COMPOSITE lifts g/b to ~180. Per-member baking would
+ // leave g/b near ~127 (gamma fixes 0 and 255), 50+ levels away.
+ const document = docWith([
+ groupContract('g', [raster('red', { opacity: 0.5 }), raster('white')], {
+ adjustments: gammaStack('ga'),
+ } as never),
+ ]);
+ const scene = sceneFor({ red: '#ff0000', white: '#ffffff' });
+ const entry = planBaseRasterComposite(document, BBOX);
+ expect(entry.groupScopes).toHaveLength(1);
+
+ const surface = await renderRasterComposite(entry, scene);
+ const [r, g, b, a] = centerPixel(surface);
+ expect(a).toBe(255);
+ expect(r).toBe(255);
+ expect(Math.abs(g! - 180)).toBeLessThanOrEqual(3);
+ expect(Math.abs(b! - 180)).toBeLessThanOrEqual(3);
+ });
+
+ it('applies nested stacks inner-first', async () => {
+ // Inner group inverts mid-gray 25% red-over-white... keep it simple:
+ // inner invert turns white → black; outer gamma-2 keeps black at 0.
+ // Reversed order (gamma then invert) would give 255 − 255·sqrt(1) = 0 too,
+ // so use a mid value: member is 25% gray (64). invert → 191; gamma-2 on
+ // 191 → 255·sqrt(191/255) ≈ 221. Reversed: gamma-2(64) ≈ 128, invert → 127.
+ const document = docWith([
+ groupContract('outer', [groupContract('inner', [raster('gray')], { adjustments: invertStack('ia') } as never)], {
+ adjustments: gammaStack('oa'),
+ } as never),
+ ]);
+ const scene = sceneFor({ gray: '#404040' });
+ const surface = await renderRasterComposite(planBaseRasterComposite(document, BBOX), scene);
+ const [r] = centerPixel(surface);
+ expect(Math.abs(r! - 221)).toBeLessThanOrEqual(3);
+ });
+
+ it('draws the same pixels on screen (group surface cache) as the export renderer', async () => {
+ const document = docWith([
+ groupContract('g', [raster('red', { blendMode: 'multiply', opacity: 0.6 }), raster('white')], {
+ adjustments: gammaStack('ga'),
+ } as never),
+ raster('under'),
+ ]);
+ const scene = sceneFor({ red: '#ff4040', under: '#2040c0', white: '#c0c0c0' });
+ 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 exported = await renderRasterComposite(planBaseRasterComposite(document, BBOX), scene);
+
+ 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);
+ }
+ // And a second composite reuses the cached group surface (same pixels).
+ const again = scene.backend.createSurface(WIDTH, HEIGHT);
+ compositeDocument(again, document, scene.caches, identity(), {
+ backend: scene.backend,
+ groupSurface: (scope, members, matrices, exclude) => groupSurfaces.get(scope, members, matrices, exclude),
+ });
+ expect(centerPixel(again)).toEqual(screenPx);
+ });
+
+ it('resolves sibling scopes nested inside a parent scope with correct member indexing', async () => {
+ // outer gamma-2 group holding: invert-group [a], plain b, invert-group [d].
+ // a=#404040 → invert 191 → outer gamma ≈221. b=#404040 → outer gamma ≈128.
+ // d covers nothing at centre (checked via left pixel below).
+ const document = docWith([
+ groupContract(
+ 'outer',
+ [
+ groupContract('i1', [raster('a')], { adjustments: invertStack('ia') } as never),
+ raster('b', { opacity: 0.0 }),
+ groupContract('i2', [raster('d', { opacity: 0.0 })], { adjustments: invertStack('ib') } as never),
+ ],
+ { adjustments: gammaStack('oa') } as never
+ ),
+ ]);
+ const scene = sceneFor({ a: '#404040', b: '#404040', d: '#404040' });
+ const exported = await renderRasterComposite(planBaseRasterComposite(document, BBOX), scene);
+ const [r] = centerPixel(exported);
+ expect(Math.abs(r! - 221)).toBeLessThanOrEqual(3);
+
+ 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),
+ });
+ expect(Math.abs(centerPixel(screen)[0]! - 221)).toBeLessThanOrEqual(3);
+ });
+
+ it('color-samples through a group stack when the providers are wired', () => {
+ const document = docWith([groupContract('g', [raster('gray')], { adjustments: invertStack('ia') } as never)]);
+ const scene = sceneFor({ gray: '#404040' });
+ const groupSurfaces = createGroupSurfaceCache({
+ createSurface: (w, h) => scene.backend.createSurface(w, h),
+ getAdjustedSurface: () => null,
+ getCacheEntry: (id) => scene.caches.get(id),
+ });
+ const point = { x: WIDTH / 2, y: HEIGHT / 2 };
+ const raw = sampleDocumentColor(document, scene.caches, scene.backend, point);
+ expect(raw?.r).toBe(0x40);
+ const adjusted = sampleDocumentColor(document, scene.caches, scene.backend, point, {
+ groupSurface: (scope, members, matrices, exclude) => groupSurfaces.get(scope, members, matrices, exclude),
+ });
+ expect(adjusted?.r).toBe(255 - 0x40);
+ });
+
+ it('keeps identity and pass-through groups on the flat path and keys the plan by group stacks', () => {
+ const flat = docWith([groupContract('g', [raster('white')])]);
+ expect(planBaseRasterComposite(flat, BBOX).groupScopes).toBeUndefined();
+
+ const adjusted = docWith([groupContract('g', [raster('white')], { adjustments: gammaStack('ga') } as never)]);
+ const inverted = docWith([groupContract('g', [raster('white')], { adjustments: invertStack('ia') } as never)]);
+ expect(planBaseRasterComposite(adjusted, BBOX).key).not.toBe(planBaseRasterComposite(flat, BBOX).key);
+ expect(planBaseRasterComposite(adjusted, BBOX).key).not.toBe(planBaseRasterComposite(inverted, BBOX).key);
+ });
+});
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
new file mode 100644
index 0000000000..f2ea3224f4
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupAdjustmentScopes.test.ts
@@ -0,0 +1,91 @@
+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') } as never)],
+ raster: [
+ groupContract('g1', [layerContract('r1')], { adjustments: stack('b') } as never),
+ groupContract('g2', [layerContract('r2')], { adjustments: identityStack } as never),
+ 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
new file mode 100644
index 0000000000..8868e6a758
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupAdjustmentScopes.ts
@@ -0,0 +1,98 @@
+/**
+ * Group adjustment scopes: which contiguous runs of a flat drawn-leaf list
+ * must composite through an isolated buffer so a group's adjustment stack can
+ * apply to the composite (not to each member). Both renderers — the screen
+ * compositor and the export/generation raster composite — consume the same
+ * scope shape, so their isolation semantics cannot drift.
+ *
+ * The planners rely on one structural fact: any list derived from the
+ * document's preorder (or its reversal) keeps every subtree contiguous, so a
+ * group's drawn members always form one run.
+ */
+
+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 adjustment stacks contribute (enabled group,
+ * non-identity stack). Disabled groups drop out of drawing entirely upstream;
+ * an identity stack composites pass-through by definition.
+ */
+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 the nested scopes covering `items` (a flat drawn list; each item
+ * carries its ancestor chain outermost-first). Items outside every adjusted
+ * group produce no scope. Returns 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));
+ // Keep the still-matching prefix of open scopes, close the rest, open the new tail.
+ 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/groupSurfaceCache.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupSurfaceCache.ts
new file mode 100644
index 0000000000..bb1a1fc603
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupSurfaceCache.ts
@@ -0,0 +1,211 @@
+/**
+ * Document-space composites of adjusted groups, memoized per group. The
+ * screen compositor draws one cached surface per adjusted group instead of
+ * the group's members, so pans and zooms cost one blit while member edits
+ * rebuild only the owning group's surface.
+ *
+ * The cache key folds in everything the pixels depend on: the group's stack,
+ * nested scopes, and every drawn member's cache version, appearance, and
+ * effective matrix (transform overrides included — a transform session inside
+ * an adjusted group rebuilds per tick, which is correct, just not free).
+ *
+ * Accepted fidelity tradeoff: the surface is document-resolution, so a
+ * transformed member resamples twice (into doc space, then through the view),
+ * and zoom > 100% upscales the group from doc resolution while flat layers
+ * sample their caches in one pass. Buying per-frame LUT application on the
+ * viewport back with per-edit memoization is the point; sharper zoomed-in
+ * group rendering is a measured follow-up, not a default.
+ */
+
+import type { CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';
+import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';
+import type { LayerCacheEntry } from '@workbench/canvas-engine/render/layerCache';
+import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
+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 { blendToComposite } from '@workbench/canvas-engine/render/compositor';
+
+import type { GroupAdjustmentScope } from './groupAdjustmentScopes';
+
+export interface GroupSurfaceResult {
+ readonly surface: RasterSurface;
+ /** Document-space placement of the surface. */
+ readonly rect: Rect;
+}
+
+export interface GroupSurfaceDeps {
+ createSurface(width: number, height: number): RasterSurface;
+ getCacheEntry(layerId: string): LayerCacheEntry | undefined;
+ /** The member's own adjusted pixels (its personal stack), or null for raw. */
+ getAdjustedSurface(layer: CanvasRasterLayerContractV2, entry: LayerCacheEntry): RasterSurface | null;
+}
+
+export interface GroupSurfaceCache {
+ /** Total RGBA bytes the cached group surfaces hold, for the memory budget. */
+ byteSize(): number;
+ get(
+ scope: GroupAdjustmentScope,
+ members: readonly SemanticLeaf[],
+ memberMatrices: readonly Mat2d[],
+ excludeIds: ReadonlySet<string>
+ ): GroupSurfaceResult | null;
+ /** Drops every cached group not named; call when document structure changes. */
+ prune(liveGroupIds: ReadonlySet<string>): void;
+ clear(): void;
+}
+
+const matKey = (m: Mat2d): string => `${m.a},${m.b},${m.c},${m.d},${m.e},${m.f}`;
+
+/** The stack surface budget: an adjusted group holds one doc-space surface. */
+export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCache => {
+ const cache = new Map<string, { key: string; result: GroupSurfaceResult }>();
+
+ const scopeShapeKey = (scope: GroupAdjustmentScope): string =>
+ `${scope.id}@${scope.start}-${scope.end}:${adjustmentsKey(scope.adjustments)}(${scope.children
+ .map(scopeShapeKey)
+ .join(',')})`;
+
+ const buildKey = (
+ scope: GroupAdjustmentScope,
+ members: readonly SemanticLeaf[],
+ memberMatrices: readonly Mat2d[],
+ excludeIds: ReadonlySet<string>
+ ): string => {
+ const memberKeys = members.map((leaf, index) => {
+ const layer = leaf.layer;
+ const entry = deps.getCacheEntry(leaf.id);
+ const own = layer.type === 'raster' ? adjustmentsKey(layer.adjustments) : '-';
+ return `${leaf.id}:${entry?.version ?? -1}:${layer.opacity}:${layer.blendMode}:${matKey(memberMatrices[index]!)}:${own}`;
+ });
+ return `${scopeShapeKey(scope)}|${memberKeys.join('|')}|x:${[...excludeIds].sort().join(',')}`;
+ };
+
+ /**
+ * Draws `[from, to)` (absolute plan indices; list order = bottom first) onto
+ * `ctx`. `baseIndex` is the absolute index of `members[0]`.
+ */
+ const drawRange = (
+ ctx: RasterSurface['ctx'],
+ view: Mat2d,
+ members: readonly SemanticLeaf[],
+ memberMatrices: readonly Mat2d[],
+ excludeIds: ReadonlySet<string>,
+ baseIndex: number,
+ from: number,
+ to: number,
+ children: readonly GroupAdjustmentScope[]
+ ): void => {
+ let childIndex = 0;
+ for (let i = from; i < to;) {
+ const child = childIndex < children.length ? children[childIndex]! : null;
+ if (child && i >= child.start && i < child.end) {
+ // Nested adjusted group: isolate it exactly like the parent.
+ const nested = build(child, members, memberMatrices, excludeIds, baseIndex);
+ if (nested) {
+ ctx.save();
+ ctx.globalAlpha = 1;
+ ctx.globalCompositeOperation = 'source-over';
+ 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();
+ }
+ i = child.end;
+ childIndex += 1;
+ continue;
+ }
+ const leaf = members[i - baseIndex]!;
+ const matrix = memberMatrices[i - baseIndex]!;
+ i += 1;
+ if (excludeIds.has(leaf.id) || leaf.layer.type !== 'raster') {
+ continue;
+ }
+ const entry = deps.getCacheEntry(leaf.id);
+ if (!entry || entry.rect.width <= 0 || entry.rect.height <= 0) {
+ continue;
+ }
+ const adjusted = deps.getAdjustedSurface(leaf.layer, entry);
+ ctx.save();
+ ctx.globalAlpha = leaf.layer.opacity;
+ ctx.globalCompositeOperation = blendToComposite(leaf.layer.blendMode);
+ const m = multiply(view, matrix);
+ ctx.setTransform(m.a, m.b, m.c, m.d, m.e, m.f);
+ ctx.drawImage((adjusted ?? entry.surface).canvas, entry.rect.x, entry.rect.y);
+ ctx.restore();
+ }
+ };
+
+ const build = (
+ scope: GroupAdjustmentScope,
+ members: readonly SemanticLeaf[],
+ memberMatrices: readonly Mat2d[],
+ excludeIds: ReadonlySet<string>,
+ baseIndex: number
+ ): GroupSurfaceResult | null => {
+ // Document-space bounds of the drawn members.
+ let bounds: Rect | null = null;
+ for (let i = scope.start; i < scope.end; i += 1) {
+ const leaf = members[i - baseIndex]!;
+ if (excludeIds.has(leaf.id) || leaf.layer.type !== 'raster') {
+ continue;
+ }
+ const entry = deps.getCacheEntry(leaf.id);
+ if (!entry || entry.rect.width <= 0 || entry.rect.height <= 0) {
+ continue;
+ }
+ const memberBounds = transformBounds(memberMatrices[i - baseIndex]!, entry.rect);
+ bounds = bounds === null ? memberBounds : union(bounds, memberBounds);
+ }
+ if (bounds === null) {
+ return null;
+ }
+ const rect = roundOut(bounds);
+ if (rect.width <= 0 || rect.height <= 0) {
+ return null;
+ }
+ const surface = deps.createSurface(rect.width, rect.height);
+ const ctx = surface.ctx;
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ 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);
+ return { rect, surface };
+ };
+
+ return {
+ byteSize: () => {
+ let bytes = 0;
+ for (const { result } of cache.values()) {
+ bytes += result.rect.width * result.rect.height * 4;
+ }
+ return bytes;
+ },
+ clear: () => cache.clear(),
+ get: (scope, members, memberMatrices, excludeIds) => {
+ const key = buildKey(scope, members, memberMatrices, excludeIds);
+ const cached = cache.get(scope.id);
+ if (cached && cached.key === key) {
+ return cached.result;
+ }
+ const result = build(scope, members, memberMatrices, excludeIds, scope.start);
+ if (result) {
+ cache.set(scope.id, { key, result });
+ } else {
+ cache.delete(scope.id);
+ }
+ return result;
+ },
+ prune: (liveGroupIds) => {
+ for (const id of cache.keys()) {
+ if (!liveGroupIds.has(id)) {
+ cache.delete(id);
+ }
+ }
+ },
+ };
+};
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 17f0ba96f2..8e0a0ac64e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterComposite.ts
@@ -6,6 +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 { RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { Mat2d, Rect } from '@workbench/canvas-engine/types';
@@ -14,6 +15,10 @@ import { fromTRS, multiply } from '@workbench/canvas-engine/math/mat2d';
import { roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';
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';
type Ctx = RasterSurface['ctx'];
@@ -33,6 +38,13 @@ export interface CompositeLayerRef {
export interface CompositeEntry {
bbox: Rect;
layers: readonly CompositeLayerRef[];
+ /**
+ * Adjusted-group isolation scopes over `layers` (index ranges, top-first,
+ * nested). A scope's members composite into an isolated buffer, the group's
+ * stack applies to the buffer, and the buffer composites onward — the
+ * pixels a pass-through walk cannot produce. Absent ⇒ fully pass-through.
+ */
+ groupScopes?: readonly GroupAdjustmentScope[];
}
export interface BaseRasterCompositeEntry extends CompositeEntry {
@@ -152,16 +164,20 @@ 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(',')})`;
+
/** Plans the enabled base-raster layers over an exact document-space rectangle. */
export const planBaseRasterComposite = (document: CanvasDocumentContractV3, rect: Rect): BaseRasterCompositeEntry => {
- const layers = compileDocumentLeaves(document)
- .filter(isBaseRasterLeaf)
- .map((leaf) => toLayerRef(leaf.layer, document));
+ const drawn = compileDocumentLeaves(document).filter(isBaseRasterLeaf);
+ const layers = drawn.map((leaf) => toLayerRef(leaf.layer, document));
+ const groupScopes = planGroupAdjustmentScopes(drawn, collectAdjustedGroups(document));
return {
bbox: rect,
- key: `base-raster|${rectKey(rect)}|${layers.map(layerKey).join('|')}`,
+ key: `base-raster|${rectKey(rect)}|${layers.map(layerKey).join('|')}|${groupScopes.map(scopeKey).join('|')}`,
kind: 'base-raster',
layers,
+ ...(groupScopes.length > 0 ? { groupScopes } : {}),
};
};
@@ -196,21 +212,12 @@ export const renderRasterComposite = async (
const { bbox } = entry;
const width = Math.max(0, bbox.width);
const height = Math.max(0, bbox.height);
- const surface = deps.backend.createSurface(width, height);
- const ctx = surface.ctx;
const readImageData = deps.readImageData ?? defaultReadImageData;
const writeImageData = deps.writeImageData ?? defaultWriteImageData;
-
- setTransform(ctx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
- ctx.clearRect(0, 0, surface.width, surface.height);
-
const view = bboxView(bbox);
- // Layers are stored top-first (index 0 = top-most); draw bottom→top.
- for (let i = entry.layers.length - 1; i >= 0; i--) {
- const ref = entry.layers[i];
- if (!ref) {
- continue;
- }
+ const fullRect: Rect = { height, width, x: 0, y: 0 };
+
+ const drawRef = async (ctx: Ctx, ref: CompositeLayerRef): Promise<void> => {
const layerSurface = await deps.getLayerSurface(ref.id);
if (ref.adjustments) {
// Bake non-destructive adjustments so the generated image matches what the
@@ -222,7 +229,6 @@ export const renderRasterComposite = async (
tempCtx.clearRect(0, 0, width, height);
setTransform(tempCtx, multiply(view, layerMatrix(ref)));
tempCtx.drawImage(layerSurface.surface.canvas, layerSurface.rect.x, layerSurface.rect.y);
- const fullRect: Rect = { height, width, x: 0, y: 0 };
const pixels = readImageData(temp, fullRect);
applyAdjustments(pixels, ref.adjustments);
writeImageData(temp, pixels, 0, 0);
@@ -232,7 +238,7 @@ export const renderRasterComposite = async (
ctx.globalCompositeOperation = blendToComposite(ref.blendMode);
ctx.drawImage(temp.canvas, 0, 0);
ctx.restore();
- continue;
+ return;
}
ctx.save();
ctx.globalAlpha = ref.opacity;
@@ -242,7 +248,52 @@ export const renderRasterComposite = async (
// layers place their pixels off-zero).
ctx.drawImage(layerSurface.surface.canvas, layerSurface.rect.x, layerSurface.rect.y);
ctx.restore();
- }
+ };
+
+ /**
+ * Draws `[start, end)` bottom→top onto `ctx`. A scope's members render into
+ * an isolated bbox-sized buffer first, the group's stack applies to that
+ * composite, and the buffer lands source-over — the group-adjustment
+ * semantics a per-leaf bake cannot reproduce under member opacity/blending.
+ */
+ const renderRange = async (
+ ctx: Ctx,
+ start: number,
+ end: number,
+ scopes: readonly GroupAdjustmentScope[]
+ ): Promise<void> => {
+ let scopeIndex = scopes.length - 1;
+ for (let i = end - 1; i >= start;) {
+ const scope = scopeIndex >= 0 ? scopes[scopeIndex]! : null;
+ if (scope && i >= scope.start && i < scope.end) {
+ const buffer = deps.backend.createSurface(width, height);
+ 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);
+ ctx.save();
+ setTransform(ctx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
+ ctx.globalAlpha = 1;
+ ctx.globalCompositeOperation = 'source-over';
+ ctx.drawImage(buffer.canvas, 0, 0);
+ ctx.restore();
+ i = scope.start - 1;
+ scopeIndex -= 1;
+ continue;
+ }
+ const ref = entry.layers[i];
+ if (ref) {
+ await drawRef(ctx, ref);
+ }
+ i -= 1;
+ }
+ };
+ const surface = deps.backend.createSurface(width, height);
+ setTransform(surface.ctx, { a: 1, b: 0, c: 0, d: 1, e: 0, f: 0 });
+ surface.ctx.clearRect(0, 0, surface.width, surface.height);
+ await renderRange(surface.ctx, 0, entry.layers.length, entry.groupScopes ?? []);
return surface;
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.ts
index 91c81b7bde..016588a503 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.ts
@@ -41,7 +41,7 @@ const pickColorAt = (ctx: ToolContext, input: PointerInput): void => {
if (!doc) {
return;
}
- const sample = sampleDocumentColor(doc, ctx.layers, ctx.backend, input.documentPoint);
+ const sample = sampleDocumentColor(doc, ctx.layers, ctx.backend, input.documentPoint, ctx.sampleProviders);
if (!sample) {
return;
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
index 9b311e48e2..81015b44ef 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
@@ -20,6 +20,7 @@ import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStac
import type { EngineStores } from '@workbench/canvas-engine/engineStores';
import type { CreatePath2D } from '@workbench/canvas-engine/freehand';
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
+import type { CompositeOptions } from '@workbench/canvas-engine/render/compositor';
import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';
import type { OverlayCursor } from '@workbench/canvas-engine/render/overlayRenderer';
import type { RasterBackend } from '@workbench/canvas-engine/render/raster';
@@ -172,6 +173,12 @@ export interface ToolContext {
* engine-standalone behavior. Absent in minimal test harnesses.
*/
resolveColorSample?(hex: string): boolean;
+ /**
+ * The compositor providers that make color sampling WYSIWYG (layer and
+ * group adjustment stacks, display effects). Absent in minimal harnesses;
+ * the sampler then reads raw cached pixels.
+ */
+ sampleProviders?: Pick<CompositeOptions, 'adjustedSurface' | 'derivedSurfaces' | 'groupSurface'>;
/**
* Settles a pending one-shot sample request with the latest color the
* gesture stashed via `resolveColorSample`. The color-picker tool calls this
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.ts
index 8dbc2d2499..ffe2c4f755 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/compositeForGeneration.ts
@@ -270,10 +270,12 @@ const executeRasterEntry = async (
};
}
+ const countGroupScopes = (scopes: typeof entry.groupScopes): number =>
+ (scopes ?? []).reduce((total, scope) => total + 1 + countGroupScopes(scope.children), 0);
const reservation = reserveComposite(
entry,
deps,
- entry.layers.filter((layer) => layer.adjustments !== undefined).length
+ entry.layers.filter((layer) => layer.adjustments !== undefined).length + countGroupScopes(entry.groupScopes)
);
try {
const surface = await renderRasterComposite(entry, deps);