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.

refactor(webv2): extract the overlay frame projection from the engine

joshistoast1b4bd0c5f073
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index e082779526..46ef3e037b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -102,6 +102,7 @@ import type { LayerCacheEntry, LayerCacheStore } from '@workbench/canvas-engine/
import type { OverlayCursor } from '@workbench/canvas-engine/render/overlayRenderer';
import type { RenderScheduler } from '@workbench/canvas-engine/render/scheduler';
import type { SamVisualInput } from '@workbench/canvas-engine/samInteraction';
+import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';
import type { Rect, RenderFlags, ToolId, Vec2 } from '@workbench/canvas-engine/types';
import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';
@@ -143,7 +144,6 @@ import {
} from '@workbench/canvas-engine/exportRasterComposite';
import { createPointerPipeline, type PointerPipeline } from '@workbench/canvas-engine/input/pointerPipeline';
import { createWheelHandler } from '@workbench/canvas-engine/input/wheel';
-import { applyToPoint } from '@workbench/canvas-engine/math/mat2d';
import { isEmpty, union } from '@workbench/canvas-engine/math/rect';
import {
compositeDocument,
@@ -167,14 +167,13 @@ import { createEraserTool } from '@workbench/canvas-engine/tools/eraserTool';
import { createGradientTool } from '@workbench/canvas-engine/tools/gradientTool';
import { createLassoTool } from '@workbench/canvas-engine/tools/lassoTool';
import { createMarqueeTool } from '@workbench/canvas-engine/tools/marqueeTool';
-import { hittableLayerRect, layerMatrix, layerOutlineCorners } from '@workbench/canvas-engine/tools/moveHitTest';
+import { layerMatrix } from '@workbench/canvas-engine/tools/moveHitTest';
import { createMoveTool } from '@workbench/canvas-engine/tools/moveTool';
import { stepBrushSize } from '@workbench/canvas-engine/tools/paintConstants';
import { createSamTool } from '@workbench/canvas-engine/tools/samTool';
import { createShapeTool } from '@workbench/canvas-engine/tools/shapeTool';
import { createTextTool } from '@workbench/canvas-engine/tools/textTool';
import { createTransformTool } from '@workbench/canvas-engine/tools/transformTool';
-import { type LayerTransform, transformOverlayGeometry } from '@workbench/canvas-engine/transform/transformMath';
import { createViewport, MAX_DPR, type Viewport } from '@workbench/canvas-engine/viewport';
import type { ImagePatchApply } from './history/imagePatch';
@@ -189,6 +188,7 @@ import { createLayerRasterizer } from './layerRasterizer';
import { createPreviewPublisher } from './previewPublisher';
import { createRasterSnapshotCapture } from './rasterSnapshotCapture';
import { floatingSelectionFrame } from './render/floatingSelectionFrame';
+import { createOverlayFrame } from './render/overlayFrame';
import { createSelectObjectBridge } from './selectObjectBridge';
import { createStrokeCommit } from './strokeCommit';
import { createViewTool } from './tools/viewTool';
@@ -1170,66 +1170,15 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
// ---- Render loop --------------------------------------------------------
- /**
- * The selected-layer bounds outline for the move overlay, or `null`. Only the
- * move tool draws it; a layer mid-drag (with a live override) is preferred over
- * the committed selection so the marquee tracks the preview.
- */
- const moveOutlineCorners = (doc: CanvasDocumentContractV2): readonly { x: number; y: number }[] | null => {
- if (interactionController.getActiveToolId() !== 'move') {
- return null;
- }
- const overridden = doc.layers.find((layer) => transformOverrides.has(layer.id));
- const target = overridden ?? doc.layers.find((layer) => layer.id === doc.selectedLayerId);
- if (!target) {
- return null;
- }
- return layerOutlineCorners(target, doc, transformOverrides.get(target.id) ?? null);
- };
-
- /** The transform-tool frame (rotated bounds + handles + rotation nub), or `null`. */
- const transformFrameOverlay = (
- doc: CanvasDocumentContractV2
- ): {
- corners: { x: number; y: number }[];
- handles: { x: number; y: number }[];
- center: { x: number; y: number };
- rotationAnchor: { x: number; y: number };
- } | null => {
- if (interactionController.getActiveToolId() !== 'transform') {
- return null;
- }
- const float = floatingSelection.get();
- if (float) {
- // The float frames its own pixels. Its rect and transform are LAYER-LOCAL,
- // so the resulting geometry is projected out through the layer's matrix to
- // reach the document space the overlay draws in.
- const floatLayer = doc.layers.find((candidate) => candidate.id === float.layerId);
- if (!floatLayer) {
- return null;
- }
- const toDocument = layerMatrix(floatLayer.transform);
- const geometry = transformOverlayGeometry(float.transform, float.pixels.rect);
- return {
- center: applyToPoint(toDocument, geometry.center),
- corners: geometry.corners.map((point) => applyToPoint(toDocument, point)),
- handles: geometry.handles.map((point) => applyToPoint(toDocument, point)),
- rotationAnchor: applyToPoint(toDocument, geometry.rotationAnchor),
- };
- }
- const session = stores.transformSession.get();
- if (!session) {
- return null;
- }
- const layer = doc.layers.find((candidate) => candidate.id === session.layerId);
- // The layer's LOCAL content rect (off-origin aware): the frame must wrap the
- // pixels where the compositor draws them, not an assumed origin-anchored box.
- const rect = layer ? hittableLayerRect(layer, doc) : null;
- if (!rect) {
- return null;
- }
- return transformOverlayGeometry(session.transform, rect);
- };
+ const overlayFrame = createOverlayFrame({
+ getActiveToolId: () => interactionController.getActiveToolId(),
+ getAntsPhase: () => antsPhase,
+ getFloatingSelection: () => floatingSelection.get(),
+ getOverlayCursor: () => overlayCursor,
+ selection,
+ stores,
+ transformOverrides,
+ });
const render = (flags: RenderFlags): void => {
const screen = renderController.getScreen();
@@ -1371,39 +1320,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
// The overlay is cheap (a handful of screen-space strokes, independent of
// zoom and document size) and shares the `view` transform with the composite,
// so redraw it whenever any frame runs — including overlay-only frames.
- // While the bbox tool drags, the transient preview stands in for the
- // committed frame so the overlay (rect + handles) tracks the gesture.
- const bboxPreview = stores.bboxPreview.get();
- const samSession = stores.samInteraction.get();
- renderOverlay(overlay, {
- bbox: bboxPreview ?? doc.bbox,
- bboxHandles: interactionController.getActiveToolId() === 'bbox',
- cursor: overlayCursor,
- // The grid spans the whole viewport at the bbox snap size when the setting
- // is on (the document rect no longer bounds it).
- gridSize: stores.bboxGrid.get(),
- layerOutline: moveOutlineCorners(doc),
- // The in-progress lasso path (transient) and the committed selection's
- // animated marching ants. Both are overlay chrome; ants advance via the
- // ants animator's overlay-only ticks.
- gradientPreview: stores.gradientPreview.get(),
- lassoPreview: stores.lassoPreview.get(),
- marchingAnts: selection.hasSelection()
- ? { matrix: floatRender?.ants ?? null, paths: selection.antsPaths(), phase: antsPhase }
- : null,
- marqueePreview: stores.marqueePreview.get(),
- samInput: samSession?.input.type === 'visual' ? samSession.input : null,
- samPreview: samPreview ? { opacity: 0.45, rect: samPreview.rect, surface: samPreview.data } : null,
- bboxOverlay: stores.bboxOverlay.get(),
- ruleOfThirds: stores.ruleOfThirds.get(),
- shapePreview: stores.shapePreview.get(),
- // The passive bbox frame follows the setting, but always renders while the
- // bbox tool is active so its handles have a frame to attach to (editable).
- showBbox: stores.showBbox.get() || interactionController.getActiveToolId() === 'bbox',
- showGrid: stores.showGrid.get(),
- transformFrame: transformFrameOverlay(doc),
- view,
- });
+ renderOverlay(overlay, overlayFrame.describe(doc, view, floatRender, samPreview));
};
const renderController = new RenderController({
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.ts
new file mode 100644
index 0000000000..f4890a2ea5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.ts
@@ -0,0 +1,269 @@
+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';
+import type { SamPreviewState } from '@workbench/canvas-engine/controllers/previewStateController';
+import type { FloatingSelection } from '@workbench/canvas-engine/selection/floatingSelection';
+import type { Mat2d, ToolId } from '@workbench/canvas-engine/types';
+
+import { createEngineStores } from '@workbench/canvas-engine/engineStores';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { FloatingSelectionFrame } from './floatingSelectionFrame';
+
+import { createOverlayFrame, type CreateOverlayFrameDeps } from './overlayFrame';
+
+const VIEW = [1, 0, 0, 1, 0, 0] as unknown as Mat2d;
+
+const layer = (id: string, overrides: Record<string, unknown> = {}) => ({
+ id,
+ isEnabled: true,
+ name: id,
+ source: { image: { height: 8, imageName: `${id}.png`, width: 8 }, type: 'image' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type: 'raster',
+ ...overrides,
+});
+
+const documentOf = (layerIds: readonly string[] = ['a'], overrides: Record<string, unknown> = {}) =>
+ ({
+ bbox: { height: 32, width: 32, x: 0, y: 0 },
+ height: 64,
+ layers: layerIds.map((id) => layer(id)),
+ selectedLayerId: layerIds[0] ?? null,
+ width: 64,
+ ...overrides,
+ }) as unknown as CanvasDocumentContractV2;
+
+interface Harness {
+ deps: CreateOverlayFrameDeps;
+ stores: ReturnType<typeof createEngineStores>;
+ overrides: Map<string, { x: number; y: number; scaleX?: number; scaleY?: number; rotation?: number }>;
+ state: { tool: ToolId; cursor: { point: { x: number; y: number }; radiusDoc: number } | null; phase: number };
+ float: { value: FloatingSelection | null };
+ selection: { hasSelection: ReturnType<typeof vi.fn>; antsPaths: ReturnType<typeof vi.fn> };
+}
+
+let harness: Harness;
+
+const makeHarness = (): Harness => {
+ const stores = createEngineStores();
+ const overrides = new Map<string, { x: number; y: number; scaleX?: number; scaleY?: number; rotation?: number }>();
+ const state: Harness['state'] = { cursor: null, phase: 0, tool: 'view' };
+ const float: Harness['float'] = { value: null };
+ const selection = { antsPaths: vi.fn(() => []), hasSelection: vi.fn(() => false) };
+ return {
+ deps: {
+ getActiveToolId: () => state.tool,
+ getAntsPhase: () => state.phase,
+ getFloatingSelection: () => float.value,
+ getOverlayCursor: () => state.cursor,
+ selection: selection as unknown as CreateOverlayFrameDeps['selection'],
+ stores,
+ transformOverrides: overrides,
+ },
+ float,
+ overrides,
+ selection,
+ state,
+ stores,
+ };
+};
+
+const describeOverlay = (doc = documentOf(), floatFrame: FloatingSelectionFrame | null = null, sam = null) =>
+ createOverlayFrame(harness.deps).describe(doc, VIEW, floatFrame, sam);
+
+beforeEach(() => {
+ harness = makeHarness();
+});
+
+describe('the bbox', () => {
+ it('shows the committed frame when nothing is being dragged', () => {
+ expect(describeOverlay().bbox).toEqual({ height: 32, width: 32, x: 0, y: 0 });
+ });
+
+ it('lets a live drag preview stand in for the committed frame', () => {
+ harness.stores.bboxPreview.set({ height: 4, width: 4, x: 9, y: 9 });
+ expect(describeOverlay().bbox).toEqual({ height: 4, width: 4, x: 9, y: 9 });
+ });
+
+ it('draws handles only while the bbox tool is active', () => {
+ expect(describeOverlay().bboxHandles).toBe(false);
+ harness.state.tool = 'bbox';
+ expect(describeOverlay().bboxHandles).toBe(true);
+ });
+
+ it('forces the frame visible under the bbox tool even with the setting off', () => {
+ harness.stores.showBbox.set(false);
+ expect(describeOverlay().showBbox).toBe(false);
+ harness.state.tool = 'bbox';
+ // Without a frame the handles would have nothing to attach to.
+ expect(describeOverlay().showBbox).toBe(true);
+ });
+});
+
+describe('the move outline', () => {
+ it('is absent for every tool but move', () => {
+ expect(describeOverlay().layerOutline).toBeNull();
+ });
+
+ it('outlines the selected layer under the move tool', () => {
+ harness.state.tool = 'move';
+ expect(describeOverlay(documentOf(['a', 'b']))?.layerOutline).toBeTruthy();
+ });
+
+ it('prefers a layer mid-drag over the committed selection', () => {
+ harness.state.tool = 'move';
+ harness.overrides.set('b', { x: 100, y: 100 });
+ const doc = documentOf(['a', 'b']);
+ const dragged = describeOverlay(doc)?.layerOutline;
+ harness.overrides.clear();
+ const committed = describeOverlay(doc)?.layerOutline;
+ // 'a' is selected, but 'b' carries the live override, so the marquee tracks
+ // 'b' rather than lagging on the selection.
+ expect(dragged).not.toEqual(committed);
+ });
+
+ it('is absent when the selected layer is gone', () => {
+ harness.state.tool = 'move';
+ expect(describeOverlay(documentOf([], { selectedLayerId: 'missing' }))?.layerOutline).toBeNull();
+ });
+});
+
+describe('the transform frame', () => {
+ it('is absent for every tool but transform', () => {
+ harness.stores.transformSession.set({
+ layerId: 'a',
+ start: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ } as never);
+ expect(describeOverlay().transformFrame).toBeNull();
+ });
+
+ it('frames the open session under the transform tool', () => {
+ harness.state.tool = 'transform';
+ harness.stores.transformSession.set({
+ layerId: 'a',
+ start: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ } as never);
+ expect(describeOverlay().transformFrame).toMatchObject({ corners: expect.any(Array) });
+ });
+
+ it('frames the float instead when pixels are lifted', () => {
+ harness.state.tool = 'transform';
+ harness.float.value = {
+ layerId: 'a',
+ pixels: { rect: { height: 4, width: 4, x: 0, y: 0 } },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ } as unknown as FloatingSelection;
+ // No transform session at all — the float alone drives the frame.
+ expect(describeOverlay().transformFrame).toMatchObject({ corners: expect.any(Array) });
+ });
+
+ it('is absent when the float layer is gone rather than framed at the origin', () => {
+ harness.state.tool = 'transform';
+ harness.float.value = {
+ layerId: 'missing',
+ pixels: { rect: { height: 4, width: 4, x: 0, y: 0 } },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ } as unknown as FloatingSelection;
+ expect(describeOverlay().transformFrame).toBeNull();
+ });
+
+ it('is absent when the session layer is gone', () => {
+ harness.state.tool = 'transform';
+ harness.stores.transformSession.set({
+ layerId: 'missing',
+ start: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ } as never);
+ expect(describeOverlay().transformFrame).toBeNull();
+ });
+});
+
+describe('the marching ants', () => {
+ it('are absent without a selection', () => {
+ expect(describeOverlay().marchingAnts).toBeNull();
+ });
+
+ it('carry the live phase so an overlay-only tick animates them', () => {
+ harness.selection.hasSelection.mockReturnValue(true);
+ harness.state.phase = 12;
+ expect(describeOverlay().marchingAnts).toMatchObject({ phase: 12 });
+ });
+
+ it('ride the float matrix so they track lifted pixels, not the layer', () => {
+ harness.selection.hasSelection.mockReturnValue(true);
+ const ants = [2, 0, 0, 2, 5, 5] as unknown as Mat2d;
+ expect(describeOverlay(documentOf(), { ants } as FloatingSelectionFrame).marchingAnts).toMatchObject({
+ matrix: ants,
+ });
+ });
+
+ it('fall back to no matrix when nothing is floating', () => {
+ harness.selection.hasSelection.mockReturnValue(true);
+ expect(describeOverlay().marchingAnts).toMatchObject({ matrix: null });
+ });
+});
+
+describe('SAM', () => {
+ it('reports no input when the session is not a visual one', () => {
+ harness.stores.samInteraction.set({ input: { prompt: 'a cat', type: 'text' } } as never);
+ expect(describeOverlay().samInput).toBeNull();
+ });
+
+ it('passes a visual session through', () => {
+ const input = { points: [], type: 'visual' };
+ harness.stores.samInteraction.set({ input } as never);
+ expect(describeOverlay().samInput).toBe(input);
+ });
+
+ it('draws the preview semi-transparent over the region it describes', () => {
+ const sam = {
+ data: { id: 'mask' },
+ rect: { height: 4, width: 4, x: 1, y: 1 },
+ } as unknown as SamPreviewState;
+ expect(createOverlayFrame(harness.deps).describe(documentOf(), VIEW, null, sam).samPreview).toEqual({
+ opacity: 0.45,
+ rect: { height: 4, width: 4, x: 1, y: 1 },
+ surface: sam.data,
+ });
+ });
+});
+
+describe('settings pass-through', () => {
+ it('forwards each display toggle from its store', () => {
+ harness.stores.bboxGrid.set(16);
+ harness.stores.bboxOverlay.set(true);
+ harness.stores.ruleOfThirds.set(true);
+ harness.stores.showGrid.set(true);
+ expect(describeOverlay()).toMatchObject({
+ bboxOverlay: true,
+ gridSize: 16,
+ ruleOfThirds: true,
+ showGrid: true,
+ });
+ });
+
+ it('forwards the in-progress tool previews', () => {
+ const gradient = { end: { x: 1, y: 1 }, start: { x: 0, y: 0 } };
+ const lasso = [{ x: 0, y: 0 }];
+ const marquee = { kind: 'rect' as const, rect: { height: 2, width: 2, x: 0, y: 0 } };
+ const shape = { kind: 'ellipse' as const, rect: { height: 3, width: 3, x: 1, y: 1 } };
+ harness.stores.gradientPreview.set(gradient);
+ harness.stores.lassoPreview.set(lasso);
+ harness.stores.marqueePreview.set(marquee);
+ harness.stores.shapePreview.set(shape);
+ expect(describeOverlay()).toMatchObject({
+ gradientPreview: gradient,
+ lassoPreview: lasso,
+ marqueePreview: marquee,
+ shapePreview: shape,
+ });
+ });
+
+ it('forwards the cursor ring and the view transform', () => {
+ harness.state.cursor = { point: { x: 3, y: 4 }, radiusDoc: 5 };
+ const overlay = describeOverlay();
+ expect(overlay.cursor).toEqual({ point: { x: 3, y: 4 }, radiusDoc: 5 });
+ expect(overlay.view).toBe(VIEW);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts
new file mode 100644
index 0000000000..07ddb034e2
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.ts
@@ -0,0 +1,153 @@
+import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';
+import type { SamPreviewState } from '@workbench/canvas-engine/controllers/previewStateController';
+import type { EngineStores } from '@workbench/canvas-engine/engineStores';
+import type {
+ OverlayCursor,
+ OverlayState,
+ TransformFrameOverlay,
+} from '@workbench/canvas-engine/render/overlayRenderer';
+import type { FloatingSelection } from '@workbench/canvas-engine/selection/floatingSelection';
+import type { SelectionState } from '@workbench/canvas-engine/selection/selectionState';
+import type { Mat2d, ToolId, Vec2 } from '@workbench/canvas-engine/types';
+
+import { applyToPoint } from '@workbench/canvas-engine/math/mat2d';
+import { hittableLayerRect, layerMatrix, layerOutlineCorners } from '@workbench/canvas-engine/tools/moveHitTest';
+import { transformOverlayGeometry } from '@workbench/canvas-engine/transform/transformMath';
+
+import type { FloatingSelectionFrame } from './floatingSelectionFrame';
+
+/** The SAM preview's fixed overlay opacity — it sits over the layer it describes. */
+const SAM_PREVIEW_OPACITY = 0.45;
+
+export type LayerTransformOverrides = ReadonlyMap<
+ string,
+ { x: number; y: number; scaleX?: number; scaleY?: number; rotation?: number }
+>;
+
+export interface CreateOverlayFrameDeps {
+ readonly stores: EngineStores;
+ readonly selection: SelectionState;
+ readonly transformOverrides: LayerTransformOverrides;
+ readonly getActiveToolId: () => ToolId;
+ readonly getFloatingSelection: () => FloatingSelection | null;
+ readonly getOverlayCursor: () => OverlayCursor | null;
+ readonly getAntsPhase: () => number;
+}
+
+export interface OverlayFrame {
+ /** Everything the overlay renderer draws this frame, gathered from live state. */
+ describe(
+ doc: CanvasDocumentContractV2,
+ view: Mat2d,
+ floatFrame: FloatingSelectionFrame | null,
+ samPreview: SamPreviewState | null
+ ): OverlayState;
+}
+
+/**
+ * Projects engine state into the overlay renderer's descriptor.
+ *
+ * The overlay is chrome — bbox, grid, cursor ring, marching ants, tool
+ * previews — and every part of it is derived, never owned. Keeping the
+ * projection pure means the overlay's rules can be tested without a canvas:
+ * which tool shows which affordance, that a live drag preview stands in for
+ * committed state so the overlay tracks the gesture, and that a frame is
+ * suppressed rather than drawn against stale geometry.
+ */
+export const createOverlayFrame = (deps: CreateOverlayFrameDeps): OverlayFrame => {
+ const { getActiveToolId, selection, stores, transformOverrides } = deps;
+
+ /**
+ * The selected layer's bounds outline for the move tool. A layer mid-drag
+ * (carrying a live override) wins over the committed selection so the marquee
+ * tracks the preview rather than lagging a frame behind it.
+ */
+ const moveOutlineCorners = (doc: CanvasDocumentContractV2): readonly Vec2[] | null => {
+ if (getActiveToolId() !== 'move') {
+ return null;
+ }
+ const overridden = doc.layers.find((layer) => transformOverrides.has(layer.id));
+ const target = overridden ?? doc.layers.find((layer) => layer.id === doc.selectedLayerId);
+ if (!target) {
+ return null;
+ }
+ return layerOutlineCorners(target, doc, transformOverrides.get(target.id) ?? null);
+ };
+
+ /** The transform-tool frame (rotated bounds + handles + rotation nub), or `null`. */
+ const transformFrame = (doc: CanvasDocumentContractV2): TransformFrameOverlay | null => {
+ if (getActiveToolId() !== 'transform') {
+ return null;
+ }
+ const float = deps.getFloatingSelection();
+ if (float) {
+ // The float frames its own pixels. Its rect and transform are LAYER-LOCAL,
+ // so the resulting geometry is projected out through the layer's matrix to
+ // reach the document space the overlay draws in.
+ const floatLayer = doc.layers.find((candidate) => candidate.id === float.layerId);
+ if (!floatLayer) {
+ return null;
+ }
+ const toDocument = layerMatrix(floatLayer.transform);
+ const geometry = transformOverlayGeometry(float.transform, float.pixels.rect);
+ return {
+ center: applyToPoint(toDocument, geometry.center),
+ corners: geometry.corners.map((point) => applyToPoint(toDocument, point)),
+ handles: geometry.handles.map((point) => applyToPoint(toDocument, point)),
+ rotationAnchor: applyToPoint(toDocument, geometry.rotationAnchor),
+ };
+ }
+ const session = stores.transformSession.get();
+ if (!session) {
+ return null;
+ }
+ const layer = doc.layers.find((candidate) => candidate.id === session.layerId);
+ // The layer's LOCAL content rect (off-origin aware): the frame must wrap the
+ // pixels where the compositor draws them, not an assumed origin-anchored box.
+ const rect = layer ? hittableLayerRect(layer, doc) : null;
+ if (!rect) {
+ return null;
+ }
+ return transformOverlayGeometry(session.transform, rect);
+ };
+
+ return {
+ describe: (doc, view, floatFrame, samPreview) => {
+ const activeTool = getActiveToolId();
+ // While the bbox tool drags, the transient preview stands in for the
+ // committed frame so the rect and its handles track the gesture.
+ const bboxPreview = stores.bboxPreview.get();
+ const samSession = stores.samInteraction.get();
+ return {
+ bbox: bboxPreview ?? doc.bbox,
+ bboxHandles: activeTool === 'bbox',
+ bboxOverlay: stores.bboxOverlay.get(),
+ cursor: deps.getOverlayCursor(),
+ gradientPreview: stores.gradientPreview.get(),
+ // The grid spans the whole viewport at the bbox snap size when the
+ // setting is on; the document rect no longer bounds it.
+ gridSize: stores.bboxGrid.get(),
+ lassoPreview: stores.lassoPreview.get(),
+ layerOutline: moveOutlineCorners(doc),
+ // Ants advance via the animator's overlay-only ticks, and ride the
+ // float's matrix so they track lifted pixels rather than the layer.
+ marchingAnts: selection.hasSelection()
+ ? { matrix: floatFrame?.ants ?? null, paths: selection.antsPaths(), phase: deps.getAntsPhase() }
+ : null,
+ marqueePreview: stores.marqueePreview.get(),
+ ruleOfThirds: stores.ruleOfThirds.get(),
+ samInput: samSession?.input.type === 'visual' ? samSession.input : null,
+ samPreview: samPreview
+ ? { opacity: SAM_PREVIEW_OPACITY, rect: samPreview.rect, surface: samPreview.data }
+ : null,
+ shapePreview: stores.shapePreview.get(),
+ // The passive bbox frame follows the setting, but always renders while
+ // the bbox tool is active so its handles have a frame to attach to.
+ showBbox: stores.showBbox.get() || activeTool === 'bbox',
+ showGrid: stores.showGrid.get(),
+ transformFrame: transformFrame(doc),
+ view,
+ };
+ },
+ };
+};