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.

fix(canvas): harden select object tool lifecycle

joshistoast335564f95cc0
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
index a662f2864f..ec7d2c63ca 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -11865,8 +11865,17 @@ describe('Select Object canvas engine integration', () => {
} = {}
) => {
const raf = createControllableRaf();
+ const windowListeners = new Map<string, Set<(event: Event) => void>>();
vi.stubGlobal('requestAnimationFrame', raf.requestFrame);
vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);
+ vi.stubGlobal('addEventListener', (type: string, listener: (event: Event) => void) => {
+ const listeners = windowListeners.get(type) ?? new Set();
+ listeners.add(listener);
+ windowListeners.set(type, listeners);
+ });
+ vi.stubGlobal('removeEventListener', (type: string, listener: (event: Event) => void) => {
+ windowListeners.get(type)?.delete(listener);
+ });
const reactive = createReactiveStore(samDocument(options.layers));
const engine = createCanvasEngine({
backend: options.backend ?? createTestStubRasterBackend(),
@@ -11885,7 +11894,12 @@ describe('Select Object canvas engine integration', () => {
raf.flush();
await flushMicrotasks();
raf.flush();
- return { ...reactive, engine, overlay, raf, screen };
+ const fireKey = (type: 'keydown' | 'keyup', code: string, key: string): void => {
+ for (const listener of windowListeners.get(type) ?? []) {
+ listener({ code, key, preventDefault: vi.fn(), repeat: false, target: null } as unknown as Event);
+ }
+ };
+ return { ...reactive, engine, fireKey, overlay, raf, screen };
};
it('starts on the selected supported source, activates the real sam tool, and edits overlay-only', async () => {
@@ -11912,6 +11926,20 @@ describe('Select Object canvas engine integration', () => {
h.engine.dispose();
});
+ it('processes a sole near-edge point after canonicalizing it to the last source pixel', async () => {
+ const runGraph = vi.fn(() => Promise.resolve({ imageName: 'sam-mask.png', origin: 'test' }));
+ const h = await createSamHarness({ runGraph });
+ h.engine.startSelectObjectSession();
+
+ h.overlay.fire('pointerdown', pointerAt(19.8, 19.7));
+ h.overlay.fire('pointerup', pointerAt(19.8, 19.7, { buttons: 0 }));
+
+ expect(h.engine.stores.samSession.get()?.input.includePoints).toEqual([{ x: 19, y: 19 }]);
+ await expect(h.engine.processSelectObjectSession()).resolves.toBe('published');
+ expect(runGraph).toHaveBeenCalledOnce();
+ h.engine.dispose();
+ });
+
it('rejects missing and unsupported selections without activating sam', async () => {
const mask: CanvasInpaintMaskLayerContract = {
...samLayer('mask'),
@@ -11987,6 +12015,44 @@ describe('Select Object canvas engine integration', () => {
h.engine.dispose();
});
+ it('renders a captured disabled source during isolation without mutating its visibility', async () => {
+ const backend = createRecordingRasterBackend();
+ backend.createImageBitmap = vi.fn(() => Promise.resolve(recordingBitmap('sam-mask')));
+ const source: CanvasRasterLayerContractV2 = {
+ ...samLayer('source'),
+ isEnabled: false,
+ source: {
+ fill: '#fff',
+ height: 12_000,
+ kind: 'rect',
+ stroke: null,
+ strokeWidth: 0,
+ type: 'shape',
+ width: 12_000,
+ },
+ };
+ const h = await createSamHarness({ backend, layers: [source, samLayer('other', 30)] });
+ expect(await h.engine.exportLayerPixels(source.id, { includeDisabled: true })).toMatchObject({ status: 'ok' });
+ expect(h.engine.startSelectObjectSession()).toBe('started');
+ h.engine.updateSelectObjectSession({
+ input: { bbox: null, excludePoints: [], includePoints: [{ x: 5, y: 5 }], type: 'visual' },
+ });
+
+ await h.engine.processSelectObjectSession();
+ h.screen.surface.callLog.length = 0;
+ h.raf.flush();
+
+ expect(h.screen.surface.callLog.filter((entry) => entry.op === 'drawImage')).toHaveLength(1);
+ expect(h.engine.getDocument()!.layers.find((layer) => layer.id === source.id)?.isEnabled).toBe(false);
+ expect(h.engine.stores.samSession.get()).toMatchObject({ hasPreview: true });
+
+ h.screen.surface.callLog.length = 0;
+ h.engine.stores.checkerboard.set(false);
+ h.raf.flush();
+ expect(h.screen.surface.callLog.filter((entry) => entry.op === 'drawImage')).toHaveLength(1);
+ h.engine.dispose();
+ });
+
it('tears down the session when its captured source contract changes', async () => {
const h = await createSamHarness();
h.engine.startSelectObjectSession();
@@ -12036,4 +12102,36 @@ describe('Select Object canvas engine integration', () => {
expect(h.engine.stores.samSession.get()).toBeNull();
h.engine.dispose();
});
+
+ it('does not restore sessionless sam when Escape closes the session during a Space hold', async () => {
+ const h = await createSamHarness();
+ h.engine.startSelectObjectSession();
+ h.overlay.fire('pointerenter', {});
+ h.fireKey('keydown', 'Space', ' ');
+ expect(h.engine.stores.activeTool.get()).toBe('view');
+
+ h.fireKey('keydown', 'Escape', 'Escape');
+ h.fireKey('keyup', 'Space', ' ');
+
+ expect(h.engine.stores.samSession.get()).toBeNull();
+ expect(h.engine.stores.activeTool.get()).toBe('view');
+ h.engine.dispose();
+ });
+
+ it('does not restore sessionless sam when source invalidation closes the session during a Space hold', async () => {
+ const h = await createSamHarness();
+ h.engine.startSelectObjectSession();
+ h.overlay.fire('pointerenter', {});
+ h.fireKey('keydown', 'Space', ' ');
+
+ h.setDocument({
+ ...h.engine.getDocument()!,
+ layers: [{ ...h.engine.getDocument()!.layers[0]!, opacity: 0.5 }],
+ });
+ h.fireKey('keyup', 'Space', ' ');
+
+ expect(h.engine.stores.samSession.get()).toBeNull();
+ expect(h.engine.stores.activeTool.get()).toBe('view');
+ h.engine.dispose();
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index c5fcd23666..b7248e8b4b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -2214,6 +2214,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
if (needsComposite) {
ensureLayerCaches(doc);
const stagedPlacement = stagedPreview?.placement;
+ const isolatedLayerId = samPreview?.isolated ? samPreview.guard.layerId : null;
compositeDocument(screen, doc, layerCache, view, {
// Memoized adjusted surfaces for raster layers with brightness/contrast/
// saturation/curves (not recomputed per frame — see adjustedSurfaceCache).
@@ -2228,7 +2229,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
filterPreviews.size > 0
? new Map(Array.from(filterPreviews, ([id, decoded]) => [id, decoded.surface]))
: null,
- onlyLayerId: samPreview?.isolated ? samPreview.guard.layerId : null,
+ onlyLayerId: isolatedLayerId,
// Feed the cached checkerboard tile only while the toggle is ON; passing
// `null` renders transparent documents without a checkerboard.
checkerboardTile: stores.checkerboard.get() ? getCheckerboardTile() : null,
@@ -2257,7 +2258,9 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
transformOverrides: transformOverrides.size > 0 ? transformOverrides : null,
});
- const visibleIds = doc.layers.filter(isRenderableLayer).map((layer) => layer.id);
+ const visibleIds = doc.layers
+ .filter((layer) => layer.id === isolatedLayerId || isRenderableLayer(layer))
+ .map((layer) => layer.id);
const evicted = layerCache.evictHidden(visibleIds);
// Prune version-keyed dependents for every evicted id (mirrors dropLayer):
// the evicted layer's surface is gone, so its adjusted-surface memo and
@@ -2766,6 +2769,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {
};
const clearOwnedSelectObjectSession = (): void => {
+ pipeline.replaceTemporaryRestoreTool('sam', 'view');
const session = selectObjectSession;
selectObjectSession = null;
selectObjectUnsubscribe?.();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts
index 068066f8a6..d6947d58d8 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts
@@ -397,6 +397,31 @@ describe('pointer pipeline: temporary modifier tools', () => {
expect(h.setTool).toHaveBeenLastCalledWith('brush', { temporary: true });
});
+ it('replaces a matching pending restore target when its session closes', () => {
+ const h = createHarness({ tools: ['view', 'brush', 'sam'] });
+ h.deps.setTool('sam');
+ h.pipeline.onPointerEnter();
+ h.pipeline.onKeyDown(makeKeyEvent({ code: 'Space' }));
+ expect(h.setTool).toHaveBeenLastCalledWith('view', { temporary: true });
+
+ h.pipeline.replaceTemporaryRestoreTool('sam', 'view');
+ h.pipeline.onKeyUp(makeKeyEvent({ code: 'Space' }));
+
+ expect(h.setTool).toHaveBeenLastCalledWith('view', { temporary: true });
+ expect(h.setTool).not.toHaveBeenCalledWith('sam', { temporary: true });
+ });
+
+ it('does not replace an unrelated temporary restore target', () => {
+ const h = createHarness({ tools: ['view', 'brush', 'sam'] });
+ h.pipeline.onPointerEnter();
+ h.pipeline.onKeyDown(makeKeyEvent({ code: 'Space' }));
+
+ h.pipeline.replaceTemporaryRestoreTool('sam', 'view');
+ h.pipeline.onKeyUp(makeKeyEvent({ code: 'Space' }));
+
+ expect(h.setTool).toHaveBeenLastCalledWith('brush', { temporary: true });
+ });
+
it('does not switch on space when the pointer is not over the canvas', () => {
const h = createHarness();
h.pipeline.onKeyDown(makeKeyEvent({ code: 'Space' }));
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts
index 282dd3f77e..322b974aea 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts
@@ -96,6 +96,8 @@ export interface PointerPipeline {
* so a mid-drag swap can't commit against the outgoing document on pointer-up.
*/
cancelActiveGesture(): void;
+ /** Replaces a matching tool id that a currently-held temporary tool would restore on release. */
+ replaceTemporaryRestoreTool(current: ToolId, replacement: ToolId): void;
/** Clears hover/gesture/temp-tool state, cancelling any in-flight gesture (called on detach/blur). */
reset(): void;
}
@@ -432,6 +434,11 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
endTempTool();
}
},
+ replaceTemporaryRestoreTool: (current, replacement) => {
+ if (tempHold && priorToolId === current) {
+ priorToolId = replacement;
+ }
+ },
reset: () => {
clearBboxTapTimer();
if (tempHold) {
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.ts
index 26e5cbe6ed..e9f1db3dc0 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
@@ -132,6 +132,52 @@ describe('compositeDocument', () => {
expect(drawImages[0]!.args[0]).toBe(caches.get('b')!.surface.canvas);
});
+ it('isolates the named layer even when disabled and suppresses unrelated staged content', () => {
+ const backend = createTestStubRasterBackend();
+ const caches = createLayerCacheStore(backend);
+ const isolated = caches.getOrCreate('isolated', 10, 10);
+ caches.getOrCreate('other', 10, 10);
+ const filterPreview = backend.createSurface(10, 10);
+ const staged = backend.createSurface(10, 10);
+ const target = backend.createSurface(200, 200);
+
+ compositeDocument(
+ target,
+ makeDoc([rasterLayer('isolated', { isEnabled: false }), rasterLayer('other')]),
+ caches,
+ VIEW,
+ {
+ layerPreviews: new Map([['isolated', filterPreview]]),
+ onlyLayerId: 'isolated',
+ stagedPreview: { rect: { height: 10, width: 10, x: 0, y: 0 }, surface: staged },
+ }
+ );
+
+ const drawImages = target.callLog.filter((entry) => entry.op === 'drawImage');
+ expect(drawImages).toHaveLength(1);
+ expect(drawImages[0]!.args[0]).toBe(isolated.surface.canvas);
+ });
+
+ it('preserves disabled-layer and staged-preview semantics when isolation is absent', () => {
+ const backend = createTestStubRasterBackend();
+ const caches = createLayerCacheStore(backend);
+ caches.getOrCreate('disabled', 10, 10);
+ const visible = caches.getOrCreate('visible', 10, 10);
+ const staged = backend.createSurface(10, 10);
+ const target = backend.createSurface(200, 200);
+
+ compositeDocument(
+ target,
+ makeDoc([rasterLayer('disabled', { isEnabled: false }), rasterLayer('visible')]),
+ caches,
+ VIEW,
+ { stagedPreview: { rect: { height: 10, width: 10, x: 0, y: 0 }, surface: staged } }
+ );
+
+ const drawImages = target.callLog.filter((entry) => entry.op === 'drawImage');
+ expect(drawImages.map((entry) => entry.args[0])).toEqual([visible.surface.canvas, staged.canvas]);
+ });
+
it('skips the layer named by skipLayerId (open text-edit session)', () => {
const backend = createTestStubRasterBackend();
const caches = createLayerCacheStore(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 d96ad61323..b540f4b085 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/compositor.ts
@@ -136,7 +136,7 @@ export interface CompositeOptions {
* `null`/absent ⇒ no previews.
*/
layerPreviews?: ReadonlyMap<string, RasterSurface> | null;
- /** When set, transiently composites only this layer without mutating document visibility. */
+ /** When set, transiently composites only this layer (even if disabled) and suppresses staged content. */
onlyLayerId?: string | null;
/**
* Returns a raster layer's ADJUSTED cache surface (brightness/contrast/
@@ -279,7 +279,7 @@ const drawCachedLayer = (
// The cache surface holds pixels for `entry.rect` in layer-local space; draw
// it at that local origin (offset paint/mask layers place their content off-zero).
const origin = { x: entry.rect.x, y: entry.rect.y };
- const preview = opts.layerPreviews?.get(layer.id) ?? null;
+ const preview = opts.onlyLayerId ? null : (opts.layerPreviews?.get(layer.id) ?? null);
if (preview) {
// Non-destructive filter preview: stretch the filtered image over the layer's
// content footprint (through the already-applied layer transform).
@@ -342,7 +342,7 @@ export const compositeDocument = (
const layer = doc.layers[i];
if (
!layer ||
- !layer.isEnabled ||
+ (!layer.isEnabled && layer.id !== opts.onlyLayerId) ||
layer.id === opts.skipLayerId ||
(opts.onlyLayerId && layer.id !== opts.onlyLayerId) ||
layerGroupRank(layer) !== rank
@@ -364,7 +364,7 @@ export const compositeDocument = (
// Staged generation preview over its bbox (document space), with a subtle
// dashed outline so the pending result reads distinctly from committed pixels.
- const staged = opts.stagedPreview;
+ const staged = opts.onlyLayerId ? null : opts.stagedPreview;
if (staged) {
ctx.save();
setTransformFromMat(ctx, view);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/samCoordinates.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/samCoordinates.ts
new file mode 100644
index 0000000000..9292913799
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/samCoordinates.ts
@@ -0,0 +1,37 @@
+import type { Rect, Vec2 } from '@workbench/canvas-engine/types';
+
+const clamp = (value: number, min: number, max: number): number => Math.min(max, Math.max(min, value));
+
+const isPixelRect = (rect: Rect): boolean =>
+ Number.isFinite(rect.x) &&
+ Number.isFinite(rect.y) &&
+ Number.isInteger(rect.width) &&
+ Number.isInteger(rect.height) &&
+ rect.width > 0 &&
+ rect.height > 0;
+
+/** Converts a document point to the export's canonical half-open integer pixel domain. */
+export const documentToExportLocalSamPoint = (point: Vec2, exportRect: Rect, clampOutside = false): Vec2 | null => {
+ if (!isPixelRect(exportRect) || !Number.isFinite(point.x) || !Number.isFinite(point.y)) {
+ return null;
+ }
+ if (
+ !clampOutside &&
+ (point.x < exportRect.x ||
+ point.x >= exportRect.x + exportRect.width ||
+ point.y < exportRect.y ||
+ point.y >= exportRect.y + exportRect.height)
+ ) {
+ return null;
+ }
+ return {
+ x: clamp(Math.round(point.x - exportRect.x), 0, exportRect.width - 1),
+ y: clamp(Math.round(point.y - exportRect.y), 0, exportRect.height - 1),
+ };
+};
+
+/** Canonicalizes a document point while retaining document-space coordinates. */
+export const canonicalizeDocumentSamPoint = (point: Vec2, exportRect: Rect, clampOutside = false): Vec2 | null => {
+ const local = documentToExportLocalSamPoint(point, exportRect, clampOutside);
+ return local ? { x: exportRect.x + local.x, y: exportRect.y + local.y } : null;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samHitTest.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samHitTest.test.ts
index 6c2d7c8995..d46e13ad0f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samHitTest.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samHitTest.test.ts
@@ -63,7 +63,7 @@ describe('SAM bbox geometry', () => {
});
it('clips points and bbox moves without changing bbox size', () => {
- expect(clipPointToRect({ x: -5, y: 200 }, source)).toEqual({ x: 10, y: 100 });
+ expect(clipPointToRect({ x: -5, y: 200 }, source)).toEqual({ x: 10, y: 99 });
expect(moveSamBbox({ height: 20, width: 30, x: 20, y: 30 }, 500, -500, source)).toEqual({
height: 20,
width: 30,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samHitTest.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samHitTest.ts
index 122faef6cb..463f1cd32b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samHitTest.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samHitTest.ts
@@ -2,6 +2,7 @@ import type { Mat2d, Rect, Vec2 } from '@workbench/canvas-engine/types';
import { applyToPoint } from '@workbench/canvas-engine/math/mat2d';
import { transformBounds } from '@workbench/canvas-engine/math/rect';
+import { canonicalizeDocumentSamPoint } from '@workbench/canvas-engine/samCoordinates';
import { BBOX_HANDLES, bboxHandleAt, type BboxHandle, isInsideRect } from './bboxHitTest';
@@ -51,10 +52,8 @@ export const samHitTest = (options: SamHitTestOptions): SamHitTarget | null => {
const clamp = (value: number, min: number, max: number): number => Math.min(max, Math.max(min, value));
-export const clipPointToRect = (point: Vec2, bounds: Rect): Vec2 => ({
- x: clamp(point.x, bounds.x, bounds.x + bounds.width),
- y: clamp(point.y, bounds.y, bounds.y + bounds.height),
-});
+export const clipPointToRect = (point: Vec2, bounds: Rect): Vec2 =>
+ canonicalizeDocumentSamPoint(point, bounds, true) ?? { x: bounds.x, y: bounds.y };
export const clipRectToRect = (rect: Rect, bounds: Rect): Rect => {
const left = clamp(rect.x, bounds.x, bounds.x + bounds.width);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samTool.test.ts
index 5229a40d3e..ea12842adb 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samTool.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samTool.test.ts
@@ -124,6 +124,19 @@ describe('createSamTool', () => {
expect(h.stores.samSession.get()?.input.bbox).toBeNull();
});
+ it('accepts and canonicalizes a near-edge point but rejects the exact right and bottom edges', () => {
+ const h = createHarness();
+
+ down(h, pointer(99.8, 99.6));
+ up(h, pointer(99.8, 99.6, { buttons: 0 }));
+ down(h, pointer(100, 50));
+ up(h, pointer(100, 50, { buttons: 0 }));
+ down(h, pointer(50, 100));
+ up(h, pointer(50, 100, { buttons: 0 }));
+
+ expect(h.stores.samSession.get()?.input.includePoints).toEqual([{ x: 99, y: 99 }]);
+ });
+
it('moves the bbox body and resizes a handle while clipping to source bounds', () => {
const h = createHarness(
visualSnapshot({
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samTool.ts
index 5417b1e3f7..13de50ddf0 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/samTool.ts
@@ -1,6 +1,8 @@
import type { SamVisualInput } from '@workbench/canvas-engine/engineStores';
import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';
+import { canonicalizeDocumentSamPoint } from '@workbench/canvas-engine/samCoordinates';
+
import type { SamHitTarget } from './samHitTest';
import type { Tool, ToolContext } from './tool';
@@ -24,9 +26,6 @@ const cloneInput = (input: SamVisualInput): SamVisualInput => ({
type: 'visual',
});
-const isInside = (point: Vec2, rect: { x: number; y: number; width: number; height: number }): boolean =>
- point.x >= rect.x && point.x <= rect.x + rect.width && point.y >= rect.y && point.y <= rect.y + rect.height;
-
const flippedLabel = (label: 'include' | 'exclude'): 'include' | 'exclude' =>
label === 'include' ? 'exclude' : 'include';
@@ -82,7 +81,7 @@ export const createSamTool = (): Tool => {
gesture ||
!snapshot ||
(input.buttons & PRIMARY_BUTTON) === 0 ||
- !isInside(input.documentPoint, snapshot.sourceRect)
+ !canonicalizeDocumentSamPoint(input.documentPoint, snapshot.sourceRect)
) {
return;
}
diff --git a/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.ts b/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.ts
index 756ef67664..cc6ad89c74 100644
--- a/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.ts
+++ b/invokeai/frontend/webv2/src/workbench/generation/canvas/samGraph.ts
@@ -1,6 +1,7 @@
import type { Rect, Vec2 } from '@workbench/canvas-engine/types';
import type { BackendGraphContract } from '@workbench/types';
+import { documentToExportLocalSamPoint } from '@workbench/canvas-engine/samCoordinates';
import { addEdge, addNode } from '@workbench/generation/graphBuilder';
export type SamModel = 'segment-anything-2-large' | 'segment-anything-huge';
@@ -88,16 +89,11 @@ export const documentToExportLocalSamInput = (input: SamInput, exportRect: Rect)
return { bbox: null, excludePoints: [], includePoints: [], type: 'visual' };
}
- const convertPoint = ({ x, y }: Vec2): Vec2 => ({
- x: clamp(Math.round(x - exportRect.x), 0, exportRect.width - 1),
- y: clamp(Math.round(y - exportRect.y), 0, exportRect.height - 1),
- });
- const isPointInsideExport = ({ x, y }: Vec2): boolean =>
- isFinitePoint({ x, y }) &&
- x >= exportRect.x &&
- x < exportRect.x + exportRect.width &&
- y >= exportRect.y &&
- y < exportRect.y + exportRect.height;
+ const convertPoints = (points: readonly Vec2[]): Vec2[] =>
+ points.flatMap((point) => {
+ const converted = documentToExportLocalSamPoint(point, exportRect);
+ return converted ? [converted] : [];
+ });
let bbox: Rect | null = null;
if (input.bbox && isFiniteBox(input.bbox)) {
const xMin = clamp(Math.round(input.bbox.x - exportRect.x), 0, exportRect.width);
@@ -111,8 +107,8 @@ export const documentToExportLocalSamInput = (input: SamInput, exportRect: Rect)
return {
bbox,
- excludePoints: input.excludePoints.filter(isPointInsideExport).map(convertPoint),
- includePoints: input.includePoints.filter(isPointInsideExport).map(convertPoint),
+ excludePoints: convertPoints(input.excludePoints),
+ includePoints: convertPoints(input.includePoints),
type: 'visual',
};
};