Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
fix(canvas): refresh group surfaces exactly under scaled members and float drags
Josh Corbett39e9177b2f94
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.mdindex 6293c8ca5b..42b4da5f76 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md@@ -97,7 +97,7 @@ Canvas invocation first crosses the paint-flush barrier, then captures the post-## Frame demand before allocation-Each frame is described once by a `CompositePreparation` (`render/compositor.ts`): the leaves drawn bottom first, each leaf's effective matrix with transient transform overrides applied, the isolated group scopes, and each leaf's document-space bounds (persisted source bounds joined with any larger live cache rect, through that matrix). `compositeFrame` reuses the description until the document identity, isolation or override contents change, and each leaf's bounds until its contract, matrix or live cache extent does. Frame demand, compositing and color sampling all read the same description, so placement is never recomputed per consumer.+Each frame is described once by a `CompositePreparation` (`render/compositor.ts`): the leaves drawn bottom first, each leaf's effective matrix with transient transform overrides applied, the isolated group scopes, and each leaf's document-space bounds (persisted source bounds joined with any larger live cache rect, through that matrix). `compositeFrame` reuses the description until the document identity, isolation or override contents change, and each leaf's bounds until its contract, matrix, live cache extent or the document size does. Frame demand and the screen composite read that one description; frame demand also keeps every filter-previewed layer resident, since its preview draws through the layer's cache entry. The color sampler, overview and extraction prepare their own descriptions of the committed document without transient overrides.`calculateActiveFrameLayerIds` is the pure pre-allocation pass over that description: it intersects each drawable leaf's bounds with the document-space viewport. An explicitly isolated operation target is the one exception to normal document visibility: it remains demanded and drawable when disabled or display-hidden because the user is acting on that named layer directly.@@ -138,11 +138,11 @@ Staged results use a separate compressed-Blob cache rather than retaining a deco## Composition, damage and overlays-Damage is explicit: `FrameDamage` is a full repaint, no visible repaint, or layer-local regions. The scheduler widens to full on any invalidation without a region, a viewport change or a forced repaint. The compositor resolves regions through the frame's matrices into one padded screen rect: regions entirely off the target clear and draw nothing, and a bounded repaint clips to the rect and culls every leaf, group scope and staged preview whose screen bounds miss it. Unknown layers or non-finite geometry repaint everything.+Damage is explicit: `FrameDamage` is a full repaint, no visible repaint, or layer-local regions. The scheduler widens to full on any invalidation without a region, a viewport change or a forced repaint. The compositor resolves regions through the frame's matrices into one padded screen rect: regions entirely off the target draw nothing, and a bounded repaint clips to the rect and culls every leaf, group scope and staged preview whose screen bounds miss it. Unknown layers or non-finite geometry repaint everything.-Compositing always renders through the canonical `RasterBackend`; there is no approximate backend-free path. Filter previews and the floating selection of a grouped member compose inside the group's isolated surface, under the group's opacity, blend and adjustments, exactly as the member's committed pixels would; display, sampling and export share one set of composition semantics.+Compositing always renders through the canonical `RasterBackend`; there is no approximate backend-free path. Filter previews and the floating selection of a grouped member compose inside the group's isolated surface, under the group's opacity, blend and adjustments, exactly as the member's committed pixels would. Committed content composes with the same semantics for display, sampling and export; previews and floats are display-only.-A group surface is keyed by everything except its members' pixels (scope shape, member appearance and matrices, in-scope previews and float). While that key and the bounds hold, the cache refreshes in place: it unions the damage each member's cache recorded since the version it last drew, clears that region (padded for resampling) and redraws every contributor there, then applies the group's per-pixel adjustments to the region alone. Unknown member damage, a changed member set or new bounds redraw the whole surface, reallocating only when its size changed; a new key reuses the least-recently-used of a group's two slots once both are taken.+A group surface is keyed by everything except its members' pixels and the float's placement (scope shape, member appearance and matrices, in-scope previews, the float's surface). While that key and the bounds hold, the cache refreshes in place: it unions the damage each member's cache recorded since the version it last drew, padded by one source pixel before the member's matrix maps it (bilinear reach at any scale), plus the old and new landing of a moved float, clears that region with one pixel of antialiasing margin and redraws every contributor there, then applies the group's per-pixel adjustments to the region alone. Unknown member damage, a changed member set or new bounds redraw the whole surface, reallocating only when its size changed; a new key reuses the least-recently-used of a group's two slots once both are taken.The overlay renders in CSS pixels. It receives the document→CSS view, the CSS viewport size and the device-pixel ratio, clears the backing store in device pixels, then draws every handle, nub, dash and cursor under a DPR base transform (nested image and path transforms compose with it), so chrome keeps its CSS size at any ratio and matches the CSS-pixel hit tests. The viewport owns the ratio (capped at `MAX_DPR`, sub-one ratios kept) and both the backing-store size and the composite view matrix derive from it.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.test.tsindex 3f2ebcd35f..9b16db6d26 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/rasterController.test.ts@@ -1,16 +1,17 @@import type { CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';import type { SemanticLeaf } from '@workbench/canvas-engine/document-model/semanticLeaf';-import type { GroupCompositeScope } from '@workbench/canvas-engine/render/groupCompositeScopes';+import type { GroupCompositeScope, GroupSurfaceContent } from '@workbench/canvas-engine/render/groupCompositeScopes';import { createCanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';import { createBitmapStore } from '@workbench/canvas-engine/document/bitmapStore';import { identity } from '@workbench/canvas-engine/math/mat2d';-import { NO_GROUP_CONTENT } from '@workbench/canvas-engine/render/groupSurfaceCache';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { describe, expect, it, vi } from 'vitest';import { RasterController } from './rasterController';+const NO_GROUP_CONTENT: GroupSurfaceContent = { excludeIds: new Set(), float: null, previews: null };+const RECT = { height: 10, width: 10, x: 0, y: 0 };const SURFACE_BYTES = 400;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.resources.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.resources.test.tsindex 90df0f55b9..fdb1995376 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.resources.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.resources.test.ts@@ -1,4 +1,5 @@import type { BitmapStore } from '@workbench/canvas-engine/document/bitmapStore';+import type { GroupSurfaceContent } from '@workbench/canvas-engine/render/groupCompositeScopes';import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';import {@@ -7,7 +8,6 @@ import {layerContract,} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { compileDocumentLeaves } from '@workbench/canvas-engine/document-model/documentModel';-import { NO_GROUP_CONTENT } from '@workbench/canvas-engine/render/groupSurfaceCache';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { describe, expect, it, vi } from 'vitest';@@ -16,6 +16,8 @@ import type { RasterController } from './controllers/rasterController';import { createCanvasEngine } from './engine';+const NO_GROUP_CONTENT: GroupSurfaceContent = { excludeIds: new Set(), float: null, previews: null };+const owners = vi.hoisted(() => ({ raster: null as RasterController | null }));// Captures the engine's real raster owner; its behavior is unchanged.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex 473227d2ad..a13b83a1d4 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -2515,6 +2515,23 @@ describe('createCanvasEngine', () => {}});+ it('draws overlay chrome under the device-pixel base transform', () => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ const { engine } = createEngine();+ const screen = createFakeCanvas();+ const overlay = createFakeCanvas();+ engine.surface.attach(screen.element, overlay.element);+ engine.surface.resize(100, 80, 2);+ overlay.surface.callLog.length = 0;+ raf.flush();++ const transforms = overlay.surface.callLog.filter((entry) => entry.op === 'setTransform');+ expect(transforms.map((entry) => entry.args)).toContainEqual([2, 0, 0, 2, 0, 0]);+ engine.lifecycle.dispose();+ });+it('dispose removes both store subscriptions', () => {const { engine, unsubscribe } = createEngine();expect(unsubscribe).not.toHaveBeenCalled();diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.budget.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.budget.test.tsindex 64e37ceeb1..f40816f488 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.budget.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.budget.test.ts@@ -5,17 +5,21 @@ import { PreviewStateController } from '@workbench/canvas-engine/controllers/preimport { RasterController } from '@workbench/canvas-engine/controllers/rasterController';import { createCanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';import {+ createLargeTreeDocument,documentFrom,groupContract,layerContract,} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { updateNodeValues } from '@workbench/canvas-engine/document/documentIndex';import { createEngineStores } from '@workbench/canvas-engine/engineStores';import { identity } from '@workbench/canvas-engine/math/mat2d';import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';import { createViewport } from '@workbench/canvas-engine/viewport';-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import { createCompositeFrame } from './compositeFrame';+import * as compositor from './compositor';+import * as frameDemand from './frameDemand';const SURFACE_BYTES = 10 * 10 * 4;@@ -105,3 +109,48 @@ describe('composite frame working set under steady overage', () => {});});});++describe('frame description over 2,000 nodes', () => {+ it('prepares once per document and re-derives bounds only for the edited leaf', () => {+ const backend = createTestStubRasterBackend();+ const raster = new RasterController({ backend, diagnostics: createCanvasDiagnostics(true) });+ const viewport = createViewport();+ viewport.setViewportSize(100, 100, 1);+ const frame = createCompositeFrame({+ backend,+ derivedSurfaceCache: raster.derived,+ diagnostics: createCanvasDiagnostics(true),+ getAdjustedSurface: () => null,+ getCheckerboardTile: () => backend.createSurface(1, 1),+ getGroupSurface: () => null,+ getMaskPatternTile: () => null,+ layerCache: raster.layers,+ previews: new PreviewStateController(),+ raster,+ rasterizeLayer: () => undefined,+ stores: createEngineStores(),+ transformOverrides: new Map(),+ viewport,+ });+ const screen = backend.createSurface(100, 100);+ const prepare = vi.spyOn(compositor, 'prepareComposite');+ const bounds = vi.spyOn(frameDemand, 'committedLeafBounds');+ const document = createLargeTreeDocument(2_000);++ frame.draw(screen, document, identity(), null, null);+ const leafCount = bounds.mock.calls.length;+ expect(leafCount).toBeGreaterThan(1_000);+ frame.draw(screen, document, identity(), null, null, { kind: 'none' });+ expect(prepare).toHaveBeenCalledTimes(1);+ expect(bounds).toHaveBeenCalledTimes(leafCount);++ const edited = {+ ...document,+ stacks: updateNodeValues(document.stacks, new Map([['l7', (node) => ({ ...node, opacity: 0.5 })]])),+ };+ frame.draw(screen, edited, identity(), null, null);+ expect(prepare).toHaveBeenCalledTimes(2);+ expect(bounds.mock.calls.slice(leafCount).map(([leaf]) => leaf.id)).toEqual(['l7']);+ raster.dispose();+ });+});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.tsindex f466f43319..d11ec3f225 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@@ -264,6 +264,37 @@ describe('compositor options', () => {});describe('the surface budget', () => {+ const workingSet = () => harness.enforce.mock.calls.at(-1)![0] as Set<string>;++ it('keeps a filter-previewed layer resident while only its preview is on screen', () => {+ const offscreen = documentOf([layer('a', { transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 500, y: 0 } })]);+ draw(offscreen);+ expect(workingSet().has('a')).toBe(false);++ harness.previews.publishFilter('a', harness.previews.beginGuardedFilter('a'), {+ guard: { layerId: 'a' },+ rect: { height: 8, width: 8, x: -500, y: 0 },+ surface: surface(8, 8),+ } as never);+ draw(offscreen);+ expect(workingSet().has('a')).toBe(true);+ });++ it('re-derives a document-sized layer when the document grows around it', () => {+ harness.entries.clear();+ const gradient = layer('g', {+ source: { angle: 0, kind: 'linear', stops: [], type: 'gradient' },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: -100, y: 0 },+ });+ const frame = createCompositeFrame(harness.deps);+ frame.draw(surface(), documentOf([gradient]), VIEW, null, null);+ expect(workingSet().has('g')).toBe(false);++ const grown = { ...documentOf([gradient]), width: 200 } as CanvasDocumentContractV3;+ frame.draw(surface(), grown, VIEW, null, null);+ expect(workingSet().has('g')).toBe(true);+ });+it('hands the raster owner the layers this frame demanded and the usage captured before drawing', () => {draw();const [workingSet, usage] = harness.enforce.mock.calls.at(-1) as [Set<string>, typeof FRAME_USAGE];diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.tsindex 1e29e60015..d20695d054 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositeFrame.ts@@ -65,6 +65,9 @@ interface LeafBoundsMemo {readonly matrix: Mat2d;readonly live: Rect | undefined;readonly bounds: Rect | null;+ // Legacy gradients without an extent are document-sized.+ readonly documentWidth: number;+ readonly documentHeight: number;}const sameOptionalRect = (a: Rect | undefined, b: Rect | undefined): boolean =>@@ -118,7 +121,7 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeF};// The frame description is reused until the document, isolation or override contents change; each leaf's- // bounds until its contract, placement or live cache extent does.+ // bounds until its contract, placement, live cache extent or the document size does.let preparation: CompositePreparation | null = null;// A bounded or empty repaint reads only part of the working set; the usage window stays open from the last full// repaint so artifacts it skipped are not evicted as unused.@@ -148,10 +151,17 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeFconst live = layerCache.peek(leaf.id)?.rect;const previous = boundsMemo.get(leaf.id);const memo =- previous && previous.layer === leaf.layer && previous.matrix === matrix && sameOptionalRect(previous.live, live)+ previous &&+ previous.layer === leaf.layer &&+ previous.matrix === matrix &&+ previous.documentWidth === doc.width &&+ previous.documentHeight === doc.height &&+ sameOptionalRect(previous.live, live)? previous: {bounds: committedLeafBounds(leaf, matrix, doc, live),+ documentHeight: doc.height,+ documentWidth: doc.width,layer: leaf.layer,live: live && { ...live },matrix,@@ -182,11 +192,17 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeFconst isolatedGuard = samPreview?.isolated ? samPreview.guard : null;const overrides = !isolatedGuard && transformOverrides.size > 0 ? transformOverrides : null;const frame = describeFrame(doc, isolatedGuard?.layerId ?? null, overrides);+ // Snapshot filter previews only when active, avoiding an empty map allocation every frame.+ const layerPreviews = !isolatedGuard && previews.filterCount() > 0 ? previews.filterSnapshot() : null;const activeFrameLayerIds = calculateActiveFrameLayerIds({document: doc,preparation: frame,viewport: visibleDocumentRect(screen),});+ // A previewed layer draws through its cache entry even when only the preview is on screen.+ for (const layerId of layerPreviews?.keys() ?? []) {+ activeFrameLayerIds.add(layerId);+ }ensureLayerCaches(doc, frame, activeFrameLayerIds);const frameDamage = isolatedGuard ? FULL_DAMAGE : (damage ?? FULL_DAMAGE);const usage = raster.beginFrame();@@ -207,8 +223,7 @@ export const createCompositeFrame = (deps: CreateCompositeFrameDeps): CompositeFfloatingSelection: isolatedGuard ? null : (floatFrame?.composite ?? null),imageSmoothing: shouldSmoothAtZoom(viewport.getZoom()),isolationLayerId: isolatedGuard?.layerId ?? null,- // Snapshot filter previews only when active, avoiding an empty map allocation every frame.- layerPreviews: !isolatedGuard && previews.filterCount() > 0 ? previews.filterSnapshot() : null,+ layerPreviews,maskPatternTile: deps.getMaskPatternTile,preparation: frame,// Screen frames are display-time: the region tint may draw.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.tsindex 7fd14de552..c8cc7a84ef 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.test.ts@@ -858,7 +858,7 @@ describe('compositeDocument — damage', () => {};it('performs no clears and no draws when every damaged region is offscreen', () => {- const { backend, caches, doc, ops, target } = scene();+ const { backend, caches, doc, target } = scene();const diagnostics = createCanvasDiagnostics(true);compositeDocument(target, doc, caches, VIEW, {@@ -869,7 +869,6 @@ describe('compositeDocument — damage', () => {compositeDocument(target, doc, caches, VIEW, { backend, damage: { kind: 'none' }, diagnostics });expect(target.callLog).toEqual([]);- expect(ops('clearRect')).toEqual([]);expect(diagnostics.snapshot().compositeFrames).toBe(0);});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.tsindex 0f405626e6..43596943ac 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts@@ -20,7 +20,7 @@ import {planScreenComposition,} from '@workbench/canvas-engine/document-model/screenComposition';import { fromTRS, multiply } from '@workbench/canvas-engine/math/mat2d';-import { intersect, isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';+import { expand, intersect, isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';import type { DerivedSurfaceCache } from './derivedSurfaceCache';import type { GroupCompositeScope, GroupSurfaceContent } from './groupCompositeScopes';@@ -654,7 +654,8 @@ export const compositeDocument = (// Draw staged preview in document space with a dashed outline distinguishing pending pixels.const staged = isIsolated(opts) ? null : opts.stagedPreview;- if (staged && reaches(staged.rect, view, repaint)) {+ // Half the outline lands outside the rect, so a repaint beside it must still redraw that half.+ if (staged && reaches(staged.rect, view, expand(repaint, STAGED_PREVIEW_OUTLINE_WIDTH))) {ctx.save();setTransformFromMat(ctx, view);ctx.globalAlpha = staged.opacity ?? 1;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositorDamage.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositorDamage.browser.test.tsindex 21265e0be7..d50c8750cb 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositorDamage.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositorDamage.browser.test.ts@@ -88,12 +88,13 @@ describe('damage-clipped compositing matches a full repaint', () => {backend: ReturnType<typeof createDomRasterBackend>,view: Mat2d,steps: (() => LayerDamage)[],- checkerboard: boolean+ checkerboard: boolean,+ extra: Partial<Parameters<typeof compositeDocument>[4]> = {}) => {const full = backend.createSurface(SCREEN_W, SCREEN_H);const clipped = backend.createSurface(SCREEN_W, SCREEN_H);const tile = checkerboard ? createCheckerboardTile(backend, { a: '#2a2a2a', b: '#363636' }) : null;- const opts = { backend, checkerboardTile: tile, imageSmoothing: false };+ const opts = { backend, checkerboardTile: tile, imageSmoothing: false, ...extra };// Seed both with an identical full composite.compositeDocument(full, doc, caches, view, opts);@@ -205,4 +206,20 @@ describe('damage-clipped compositing matches a full repaint', () => {const { clipped, full } = run(doc, caches, backend, IDENTITY_VIEW, steps, false);expect(countDifferences(full, clipped)).toEqual({ differing: 0, worst: 0 });});++ it('redraws the staged outline half that lies outside its rect beside the damage', () => {+ const layers = [rasterLayer('a')];+ const rects = { a: { height: 200, width: 300, x: 40, y: 30 } };+ const { backend, caches } = scene(layers, rects, { a: '#a855f7' });+ const doc = { stacks: stacksFrom(layers) } as unknown as CanvasDocumentContractV3;+ const staged = backend.createSurface(50, 50);+ staged.ctx.fillStyle = '#22c55e';+ staged.ctx.fillRect(0, 0, 50, 50);+ // The padded damage ends exactly at the staged rect's left edge, inside the outline's outer half.+ const steps = [() => repaint(caches, 'a', { height: 10, width: 4, x: 195, y: 110 }, '#ef4444')];+ const { clipped, full } = run(doc, caches, backend, IDENTITY_VIEW, steps, true, {+ stagedPreview: { rect: { height: 50, width: 50, x: 200, y: 100 }, surface: staged },+ });+ expect(countDifferences(full, clipped)).toEqual({ differing: 0, worst: 0 });+ });});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.tsindex 498bdf255f..108f89591c 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@@ -7,7 +7,7 @@ import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-modimport { identity } from '@workbench/canvas-engine/math/mat2d';import { createColorSampler } from '@workbench/canvas-engine/render/colorSample';import { compositeDocument } from '@workbench/canvas-engine/render/compositor';-import { createGroupSurfaceCache, NO_GROUP_CONTENT } from '@workbench/canvas-engine/render/groupSurfaceCache';+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';@@ -347,7 +347,7 @@ describe('group adjustment composite', () => {compositeDocument(screen, docAt(1), scene.caches, identity(), {backend: scene.backend,groupSurface: (scope, members, matrices) =>- groupSurfaces.get(scope, members, matrices, { ...NO_GROUP_CONTENT, excludeIds: new Set(['red']) }),+ groupSurfaces.get(scope, members, matrices, { excludeIds: new Set(['red']), float: null, previews: null }),});composite(1);expect(draws()).toEqual({ allocations: 2, rebuilds: 2 });@@ -365,15 +365,39 @@ describe('group adjustment composite', () => {});describe('group-scoped previews and partial refresh', () => {- const groupedScene = () => {- const scene = sceneFor({ member: '#00ff00', under: '#0000ff' });+ interface GroupedSceneOptions {+ /** Member cache extent in source pixels; the transform maps it into the document. */+ memberRect?: Rect;+ member?: Partial<CanvasRasterLayerContractV2>;+ group?: Parameters<typeof groupContract>[2];+ nested?: boolean;+ }++ const groupedScene = ({+ group = { opacity: 0.5 },+ member = {},+ memberRect = BBOX,+ nested = false,+ }: GroupedSceneOptions = {}) => {+ const scene = sceneFor({ under: '#0000ff' });+ scene.caches.growToRect('member', memberRect);+ const memberSurface = scene.caches.get('member')!.surface;+ memberSurface.ctx.fillStyle = '#00ff00';+ memberSurface.ctx.fillRect(0, 0, memberRect.width, memberRect.height);+ scene.caches.publishPixels('member');+ const diagnostics = createCanvasDiagnostics(true);const groupSurfaces = createGroupSurfaceCache({createSurface: (w, h) => scene.backend.createSurface(w, h),damageSince: (id, version) => scene.caches.damageSince(id, version),+ diagnostics,getAdjustedSurface: () => null,getCacheEntry: (id) => scene.caches.get(id),});- const document = docWith([groupContract('g', [raster('member')], { opacity: 0.5 }), raster('under')]);+ const memberNode = raster('member', member);+ const document = docWith([+ groupContract('g', [nested ? groupContract('inner', [memberNode], { opacity: 0.8 }) : memberNode], group),+ raster('under'),+ ]);const composite = (options: Partial<Parameters<typeof compositeDocument>[4]> = {}) => {const screen = scene.backend.createSurface(WIDTH, HEIGHT);compositeDocument(screen, document, scene.caches, identity(), {@@ -383,9 +407,19 @@ describe('group-scoped previews and partial refresh', () => {});return screen;};- return { composite, groupSurfaces, scene };+ /** Paints a magenta dot into the member cache and publishes only that damage. */+ const paintDot = (bounded: boolean) => {+ const entry = scene.caches.get('member')!;+ const dot = { height: 1, width: 1, x: 3, y: 4 };+ entry.surface.ctx.fillStyle = '#ff00ff';+ entry.surface.ctx.fillRect(dot.x, dot.y, dot.width, dot.height);+ scene.caches.publishPixels('member', bounded ? dot : undefined);+ };+ return { composite, diagnostics, groupSurfaces, paintDot, scene };};+ const allPixels = (surface: RasterSurface): number[] => [...surface.ctx.getImageData(0, 0, WIDTH, HEIGHT).data];+it('draws a member filter preview inside its group, under the group opacity', () => {const { composite, scene } = groupedScene();const committed = centerPixel(composite());@@ -428,21 +462,50 @@ describe('group-scoped previews and partial refresh', () => {expect(Math.abs(b! - 255)).toBeLessThanOrEqual(2);});- it('refreshes a damaged member region to the same pixels as a full rebuild', () => {- const { composite, scene } = groupedScene();- composite();- const entry = scene.caches.get('member')!;- entry.surface.ctx.fillStyle = '#ff00ff';- entry.surface.ctx.fillRect(10, 12, 7, 5);- scene.caches.publishPixels('member', { height: 5, width: 7, x: 10, y: 12 });-- const refreshed = composite().ctx.getImageData(0, 0, WIDTH, HEIGHT).data;- const rebuilt = groupedScene();- const fresh = rebuilt.scene.caches.get('member')!;- fresh.surface.ctx.fillStyle = '#ff00ff';- fresh.surface.ctx.fillRect(10, 12, 7, 5);- rebuilt.scene.caches.publishPixels('member');-- expect([...refreshed]).toEqual([...rebuilt.composite().ctx.getImageData(0, 0, WIDTH, HEIGHT).data]);+ it.each<[string, GroupedSceneOptions]>([+ ['an untransformed member', {}],+ [+ 'a member scaled 8x',+ {+ member: { transform: { rotation: 0, scaleX: 8, scaleY: 8, x: 0, y: 0 } },+ memberRect: { height: 8, width: 8, x: 0, y: 0 },+ },+ ],+ ['an inverted group', { group: { adjustments: invertStack('ga'), opacity: 0.5 } }],+ ['a group with levels', { group: { adjustments: gammaStack('ga') } }],+ ['a member inside a nested group', { nested: true }],+ ])('refreshes a damaged region of %s to the same pixels as a full rebuild', (_, options) => {+ const refreshed = groupedScene(options);+ refreshed.composite();+ refreshed.paintDot(true);+ const pixels = allPixels(refreshed.composite());+ expect(refreshed.diagnostics.snapshot().groupSurfaceRefreshes).toBeGreaterThan(0);++ const rebuilt = groupedScene(options);+ rebuilt.paintDot(false);+ expect(pixels).toEqual(allPixels(rebuilt.composite()));+ });++ it('moves a floating selection inside a group by refreshing only the old and new landing', () => {+ const lifted = (scene: ReturnType<typeof groupedScene>['scene']) => {+ const surface = scene.backend.createSurface(8, 8);+ surface.ctx.fillStyle = '#ffffff';+ surface.ctx.fillRect(0, 0, 8, 8);+ return surface;+ };+ const floatAt = (surface: RasterSurface, x: number) => ({+ floatingSelection: { layerId: 'member', matrix: identity(), rect: { height: 8, width: 8, x, y: 20 }, surface },+ });+ const dragged = groupedScene();+ const surface = lifted(dragged.scene);+ dragged.composite(floatAt(surface, 10));+ const before = dragged.diagnostics.snapshot();+ const pixels = allPixels(dragged.composite(floatAt(surface, 30)));+ const after = dragged.diagnostics.snapshot();++ expect(after.groupSurfaceRebuilds).toBe(before.groupSurfaceRebuilds);+ expect(after.groupSurfaceRefreshes).toBe(before.groupSurfaceRefreshes + 1);+ const fresh = groupedScene();+ expect(pixels).toEqual(allPixels(fresh.composite(floatAt(lifted(fresh.scene), 30))));});});diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupSurfaceCache.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupSurfaceCache.tsindex 991ce972c7..dff364ca33 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupSurfaceCache.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/groupSurfaceCache.ts@@ -13,7 +13,7 @@ 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 { intersect, isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';+import { expand, intersect, isEmpty, 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';@@ -55,15 +55,15 @@ export interface GroupSurfaceCache {clear(): void;}-export const NO_GROUP_CONTENT: GroupSurfaceContent = { excludeIds: new Set(), float: null, previews: null };-const matKey = (m: Mat2d): string => `${m.a},${m.b},${m.c},${m.d},${m.e},${m.f}`;const rectKey = (r: Rect): string => `${r.x},${r.y},${r.width},${r.height}`;const sameRect = (a: Rect, b: Rect): boolean =>a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;-/** Destination pixels a changed source pixel can reach through interpolation. */-const RESAMPLE_MARGIN = 2;+// A changed source pixel reaches one source pixel further through bilinear sampling, whatever the member's scale,+// plus one destination pixel of edge antialiasing.+const SOURCE_FILTER_RADIUS = 1;+const ANTIALIAS_MARGIN = 1;// The frame composites with live session matrices while the overview composites// the settled contract, so one group legitimately holds two keys at once; two@@ -76,9 +76,25 @@ interface GroupSlot {readonly surface: RasterSurface;/** Cache version of every member pixel source the surface currently shows. */versions: ReadonlyMap<string, number>;+ /** Placement of the floating selection the surface shows, so a drag refreshes in place. */+ float: DrawnFloat | null;lastUsed: number;}+interface DrawnFloat {+ readonly placement: string;+ /** Document-space bounds the float covers. */+ readonly landing: Rect;+}++interface DrawnEntry {+ readonly leaf: SemanticLeaf;+ readonly matrix: Mat2d;+ readonly entry: LayerCacheEntry | null;+ readonly bounds: Rect | null;+ readonly float: DrawnFloat | null;+}+const surfaceBytes = (surface: RasterSurface): number => surface.width * surface.height * 4;export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCache => {@@ -120,7 +136,7 @@ export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCac.map(childScopeKey).join(',')})`;- /** Everything a surface depends on except member pixels, which are tracked by version and damage. */+ /** Everything a surface depends on except member pixels and float placement, which are tracked as damage. */const shapeKeyOf = (scope: GroupCompositeScope,members: readonly SemanticLeaf[],@@ -140,7 +156,7 @@ export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCacconst preview = content.previews?.get(leaf.id);const float = content.float?.layerId === leaf.id ? content.float : null;const previewKey = preview ? `:p${objectId(preview.surface)}@${rectKey(preview.rect)}` : '';- const floatKey = float ? `:f${objectId(float.surface)}@${rectKey(float.rect)}*${matKey(float.matrix)}` : '';+ const floatKey = float ? `:f${objectId(float.surface)}` : '';const appearance = `${layer.opacity}:${layer.blendMode}:${matKey(memberMatrices[i - baseIndex]!)}:${own}`;memberKeys.push(`${leaf.id}:${appearance}${previewKey}${floatKey}`);}@@ -154,8 +170,8 @@ export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCacmemberMatrices: readonly Mat2d[],content: GroupSurfaceContent,baseIndex: number- ): { leaf: SemanticLeaf; matrix: Mat2d; entry: LayerCacheEntry | null; bounds: Rect | null }[] => {- const drawn: { leaf: SemanticLeaf; matrix: Mat2d; entry: LayerCacheEntry | null; bounds: Rect | null }[] = [];+ ): DrawnEntry[] => {+ const drawn: DrawnEntry[] = [];for (let i = scope.start; i < scope.end; i += 1) {const leaf = members[i - baseIndex]!;if (content.excludeIds.has(leaf.id) || leaf.layer.type !== 'raster') {@@ -167,11 +183,13 @@ export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCacconst pixels = preview ? preview.rect : entry && !isEmpty(entry.rect) ? entry.rect : null;let bounds = pixels ? transformBounds(matrix, pixels) : null;const float = content.float?.layerId === leaf.id ? content.float : null;+ let drawnFloat: DrawnFloat | null = null;if (float && !isEmpty(float.rect)) {const landing = transformBounds(multiply(matrix, float.matrix), float.rect);bounds = bounds ? union(bounds, landing) : landing;+ drawnFloat = { landing, placement: `${rectKey(float.rect)}*${matKey(float.matrix)}` };}- drawn.push({ bounds, entry: preview ? null : entry, leaf, matrix });+ drawn.push({ bounds, entry: preview ? null : entry, float: drawnFloat, leaf, matrix });}return drawn;};@@ -263,11 +281,19 @@ export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCac};/** Document-space region the members changed since the slot was drawn; null when only a full redraw is safe. */- const damagedRegion = (slot: GroupSlot, drawn: ReturnType<typeof drawnEntries>): { region: Rect | null } | null => {+ const damagedRegion = (slot: GroupSlot, drawn: readonly DrawnEntry[]): { region: Rect | null } | null => {if (drawn.filter((item) => item.entry).length !== slot.versions.size) {return null;}let region: Rect | null = null;+ const float = drawn.find((item) => item.float)?.float ?? null;+ if (float?.placement !== slot.float?.placement) {+ for (const landing of [slot.float?.landing, float?.landing]) {+ if (landing) {+ region = region ? union(region, landing) : landing;+ }+ }+ }for (const { entry, leaf, matrix } of drawn) {if (!entry) {continue;@@ -283,18 +309,19 @@ export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCacif (!local) {return null;}- const changed = transformBounds(matrix, {- height: local.height,- width: local.width,- x: entry.rect.x + local.x,- y: entry.rect.y + local.y,- });+ const changed = transformBounds(+ matrix,+ expand(+ { height: local.height, width: local.width, x: entry.rect.x + local.x, y: entry.rect.y + local.y },+ SOURCE_FILTER_RADIUS+ )+ );region = region ? union(region, changed) : changed;}return { region };};- const versionsOf = (drawn: ReturnType<typeof drawnEntries>): ReadonlyMap<string, number> =>+ const versionsOf = (drawn: readonly DrawnEntry[]): ReadonlyMap<string, number> =>new Map(drawn.flatMap(({ entry, leaf }) => (entry ? [[leaf.id, entry.version] as const] : [])));function resolve(@@ -332,12 +359,9 @@ export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCacconst region = damage? damage.region &&intersect(- roundOut({- height: damage.region.height + RESAMPLE_MARGIN * 2,- width: damage.region.width + RESAMPLE_MARGIN * 2,- x: damage.region.x - rect.x - RESAMPLE_MARGIN,- y: damage.region.y - rect.y - RESAMPLE_MARGIN,- }),+ roundOut(+ expand({ ...damage.region, x: damage.region.x - rect.x, y: damage.region.y - rect.y }, ANTIALIAS_MARGIN)+ ),whole): whole;@@ -363,6 +387,7 @@ export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCaclastUsed: clock,rect,shapeKey,+ float: null,surface: deps.createSurface(rect.width, rect.height),versions: new Map(),};@@ -373,6 +398,7 @@ export const createGroupSurfaceCache = (deps: GroupSurfaceDeps): GroupSurfaceCaccache.set(scope.id, slots);}slot.versions = versionsOf(drawn);+ slot.float = drawn.find((item) => item.float)?.float ?? null;slot.lastUsed = clock;const index = slots.indexOf(slot);if (index > 0) {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.browser.test.tsindex bf750f5177..431836f95f 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.browser.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.browser.test.ts@@ -1,4 +1,6 @@+import { transformBounds } from '@workbench/canvas-engine/math/rect';import { createDomRasterBackend } from '@workbench/canvas-engine/render/raster';+import { bboxHandleAt } from '@workbench/canvas-engine/tools/bboxHitTest';import { transformOverlayGeometry, transformTargetAt } from '@workbench/canvas-engine/transform/transformMath';import { createViewport } from '@workbench/canvas-engine/viewport';import { describe, expect, it } from 'vitest';@@ -28,22 +30,24 @@ const renderAt = (dpr: number) => {return { target, viewport };};-/** Opaque white backing pixels across one row through the west bbox handle. */-const whiteRunAt = (target: ReturnType<typeof renderAt>['target'], dpr: number): number => {- const y = Math.round(75 * dpr);- const row = target.ctx.getImageData(Math.round(40 * dpr), y, Math.round(20 * dpr), 1).data;- let white = 0;+const DPRS = [0.75, 1, 1.5, 2];++/** Backing columns of opaque white across one row through the west bbox handle. */+const whiteColumnsAt = (target: ReturnType<typeof renderAt>['target'], dpr: number): number[] => {+ const left = Math.round(40 * dpr);+ const row = target.ctx.getImageData(left, Math.round(75 * dpr), Math.round(20 * dpr), 1).data;+ const columns: number[] = [];for (let i = 0; i < row.length; i += 4) {if (row[i] === 255 && row[i + 1] === 255 && row[i + 2] === 255 && row[i + 3] === 255) {- white += 1;+ columns.push(left + i / 4);}}- return white;+ return columns;};describe('overlay chrome across device-pixel ratios', () => {- it('keeps handle sizes constant in CSS pixels at DPR 1, 1.5 and 2', () => {- const cssWidths = [1, 1.5, 2].map((dpr) => whiteRunAt(renderAt(dpr).target, dpr) / dpr);+ it('keeps handle sizes constant in CSS pixels across ratios', () => {+ const cssWidths = DPRS.map((dpr) => whiteColumnsAt(renderAt(dpr).target, dpr).length / dpr);expect(cssWidths[0]).toBeGreaterThan(0);for (const width of cssWidths) {@@ -51,8 +55,19 @@ describe('overlay chrome across device-pixel ratios', () => {}});+ it('draws the west bbox handle where pointer hit testing finds it', () => {+ for (const dpr of DPRS) {+ const { target, viewport } = renderAt(dpr);+ const columns = whiteColumnsAt(target, dpr);+ const centerCss = { x: (columns[0]! + columns.at(-1)! + 1) / 2 / dpr, y: 75 };++ expect(bboxHandleAt(transformBounds(viewport.viewMatrix(1), RECT), centerCss)).toBe('w');+ expect(Math.abs(centerCss.x - RECT.x)).toBeLessThanOrEqual(1);+ }+ });+it('draws the rotation knob where pointer hit testing finds the rotate target', () => {- for (const dpr of [1, 1.5, 2]) {+ for (const dpr of DPRS) {const { target, viewport } = renderAt(dpr);// The knob is the only white fill between the canvas top and the north scale handle (top edge at 46 CSS px).const x = Math.round(75 * dpr);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.tsindex 5af03155d5..804b4a20ee 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts@@ -465,7 +465,7 @@ const drawSamGeometry = (ctx: Ctx, state: OverlayState): void => {* Even-odd viewport/bbox fill shades outside the generation frame; globalAlpha controls opacity independently of* theme color.*/-const drawBboxOverlayShade = (ctx: Ctx, state: OverlayState): void => {+const drawBboxOverlayShade = (ctx: Ctx, target: RasterSurface, state: OverlayState): void => {if (!state.bboxOverlay) {return;}@@ -474,7 +474,8 @@ const drawBboxOverlayShade = (ctx: Ctx, state: OverlayState): void => {ctx.globalAlpha = BBOX_OVERLAY_ALPHA;ctx.fillStyle = state.bboxOverlayColor ?? BBOX_OVERLAY_FILL;ctx.beginPath();- ctx.rect(0, 0, state.viewportSize.width, state.viewportSize.height);+ // The backing store rounds its device size, so cover it whole rather than the CSS viewport.+ ctx.rect(0, 0, target.width / state.dpr, target.height / state.dpr);ctx.rect(bboxScreen.x, bboxScreen.y, bboxScreen.width, bboxScreen.height);ctx.fill('evenodd');ctx.restore();@@ -533,7 +534,7 @@ export const renderOverlay = (target: RasterSurface, state: OverlayState): voidctx.setTransform(base.a, base.b, base.c, base.d, base.e, base.f);// Shade outside bbox first, then draw overlay chrome above it. The unbounded plane has no document outline.- drawBboxOverlayShade(ctx, state);+ drawBboxOverlayShade(ctx, target, state);// Grid next (behind the bbox), spanning the whole viewport.if (state.showGrid) {