Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(canvas): place gradients from the drag

Josh Corbett1ea0e35e2165
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts
index 1600881230..e4827c50ef 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts
@@ -152,6 +152,16 @@ export type CanvasLayerSourceContract =
*/
width?: number;
height?: number;
+ /**
+ * Where the gradient sits in the extent (layer-local px): the midpoint of
+ * a linear ramp, or the radial center. Absent = the extent center.
+ */
+ center?: { x: number; y: number };
+ /**
+ * Linear: the distance between the 0 and 1 stops; radial: the radius.
+ * Absent = a ramp fitted to the extent (the legacy, fixed-center look).
+ */
+ span?: number;
};
/** Photoshop's layer-color palette; also the PSD `layerColor` vocabulary. */
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
index a7684849d5..2438447f2c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
@@ -130,6 +130,13 @@ export interface GradientToolOptions {
stops: GradientStop[];
}
+/** The gradient tool's in-flight drag: start → end in document space. */
+export interface GradientPreview {
+ kind: 'linear' | 'radial';
+ start: Vec2;
+ end: Vec2;
+}
+
/** Sensible starting gradient options: the FG→BG preset, horizontal linear. */
export const DEFAULT_GRADIENT_OPTIONS: GradientToolOptions = {
angle: 0,
@@ -477,11 +484,10 @@ export interface EngineStores {
shapePreview: ScalarStore<{ rect: Rect; kind: ParametricShapeKind } | null>;
/**
* The live gradient-tool drag preview: the drag vector's start/end points in
- * document space, drawn on the overlay as a direction indicator (a gradient
- * necessarily fills the document, so only its ANGLE is previewed, not a
- * bounding box). `null` when idle; cleared on commit/cancel.
+ * document space. The overlay draws a linear ramp as the vector and a radial
+ * one as the circle it will fill. `null` when idle; cleared on commit/cancel.
*/
- gradientPreview: ScalarStore<{ start: Vec2; end: Vec2 } | null>;
+ gradientPreview: ScalarStore<GradientPreview | null>;
/**
* Whether a pixel selection currently exists. React reads it to enable the
* fill/erase/invert/deselect controls and the engine gates selection hotkeys
@@ -643,11 +649,17 @@ const rectShapePreviewEqual = (
);
};
-const gradientPreviewEqual = (a: { start: Vec2; end: Vec2 } | null, b: { start: Vec2; end: Vec2 } | null): boolean => {
+const gradientPreviewEqual = (a: GradientPreview | null, b: GradientPreview | null): boolean => {
if (a === null || b === null) {
return a === b;
}
- return a.start.x === b.start.x && a.start.y === b.start.y && a.end.x === b.end.x && a.end.y === b.end.y;
+ return (
+ a.kind === b.kind &&
+ a.start.x === b.start.x &&
+ a.start.y === b.start.y &&
+ a.end.x === b.end.x &&
+ a.end.y === b.end.y
+ );
};
const bboxPreviewEqual = (a: Rect | null, b: Rect | null): boolean => {
@@ -726,7 +738,7 @@ export const createEngineStores = (initialTool: ToolId = 'view'): EngineStores =
{ ...DEFAULT_GRADIENT_OPTIONS, stops: DEFAULT_GRADIENT_OPTIONS.stops.map((s) => ({ ...s })) },
gradientOptionsEqual
),
- gradientPreview: createScalarStore<{ start: Vec2; end: Vec2 } | null>(null, gradientPreviewEqual),
+ gradientPreview: createScalarStore<GradientPreview | null>(null, gradientPreviewEqual),
lassoOptions: createScalarStore<LassoToolOptions>({ ...DEFAULT_LASSO_OPTIONS }, lassoOptionsEqual),
lassoPreview: createScalarStore<readonly Vec2[] | null>(null),
marqueeOptions: createScalarStore<MarqueeToolOptions>({ ...DEFAULT_MARQUEE_OPTIONS }, marqueeOptionsEqual),
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
index c5f82a913a..ec1b6a563d 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.ts
@@ -256,7 +256,7 @@ describe('settings pass-through', () => {
});
it('forwards the in-progress tool previews', () => {
- const gradient = { end: { x: 1, y: 1 }, start: { x: 0, y: 0 } };
+ const gradient = { end: { x: 1, y: 1 }, kind: 'linear' as const, 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 } };
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.ts
index a980d8d6ca..1637368e80 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.ts
@@ -135,6 +135,28 @@ describe('renderOverlay', () => {
expect(moveTos).toHaveLength(4);
});
+ it.each([
+ ['radial', 1],
+ ['linear', 0],
+ ] as const)('previews a %s gradient drag as its vector plus %s screen-space circle', (kind, circles) => {
+ const backend = createTestStubRasterBackend();
+ const target = backend.createSurface(200, 200);
+ renderOverlay(
+ target,
+ baseState({
+ gradientPreview: { end: { x: 13, y: 14 }, kind, start: { x: 10, y: 10 } },
+ showBbox: false,
+ view: { a: 2, b: 0, c: 0, d: 2, e: 0, f: 0 },
+ })
+ );
+ // The endpoint dots are 3px arcs; the radius circle spans the screen-space drag.
+ const arcs = target.callLog.filter((e) => e.op === 'arc').map((e) => e.args);
+ expect(arcs.filter((args) => args[2] !== 3)).toHaveLength(circles);
+ if (circles > 0) {
+ expect(arcs.find((args) => args[2] !== 3)?.slice(0, 3)).toEqual([20, 20, 10]);
+ }
+ });
+
it('draws the dedicated SAM mask preview before its bbox, handles, and colored points', () => {
const backend = createTestStubRasterBackend();
const target = backend.createSurface(200, 200);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts
index 2d4a28b34f..057470e156 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts
@@ -116,10 +116,10 @@ export interface OverlayState {
*/
marqueePreview?: RectShapePreview | null;
/**
- * The in-progress gradient-tool drag vector (document-space start/end),
- * drawn as a direction indicator. Absent/`null` when idle.
+ * The in-progress gradient-tool drag (document-space start/end): a linear
+ * ramp's vector, or a radial one's center and radius. Absent/`null` when idle.
*/
- gradientPreview?: { start: Vec2; end: Vec2 } | null;
+ gradientPreview?: { kind: 'linear' | 'radial'; start: Vec2; end: Vec2 } | null;
/** Dedicated Select Object mask preview, already colorized by the engine. */
samPreview?: {
surface: RasterSurface;
@@ -366,7 +366,10 @@ const drawRectShapePreview = (ctx: Ctx, state: OverlayState, preview: RectShapeP
ctx.restore();
};
-/** Draws the gradient-tool drag vector (a line with endpoint dots) in screen space. */
+/**
+ * Draws the gradient-tool drag in screen space: the vector with endpoint dots,
+ * plus the circle a radial gradient will fill.
+ */
const drawGradientPreview = (ctx: Ctx, state: OverlayState): void => {
const preview = state.gradientPreview;
if (!preview) {
@@ -383,6 +386,13 @@ const drawGradientPreview = (ctx: Ctx, state: OverlayState): void => {
ctx.moveTo(start.x, start.y);
ctx.lineTo(end.x, end.y);
ctx.stroke();
+ if (preview.kind === 'radial') {
+ ctx.setLineDash([...BBOX_DASH]);
+ ctx.beginPath();
+ ctx.arc(start.x, start.y, Math.hypot(end.x - start.x, end.y - start.y), 0, Math.PI * 2);
+ ctx.stroke();
+ ctx.setLineDash([]);
+ }
for (const point of [start, end]) {
ctx.beginPath();
ctx.arc(point.x, point.y, 3, 0, Math.PI * 2);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/gradientRasterizer.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/gradientRasterizer.test.ts
index 2cb0660a7a..ad760123be 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/gradientRasterizer.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/gradientRasterizer.test.ts
@@ -53,7 +53,35 @@ describe('rasterizeGradientSource — extent', () => {
});
});
+const gradientCall = (surface: StubRasterSurface, op: string) => surface.callLog.find((e) => e.op === op)?.args;
+
describe('rasterizeGradientSource — linear', () => {
+ it('fits an unplaced ramp through the extent center, covering the box', async () => {
+ const deps = makeDeps();
+ const surface = (await rasterizeGradientSource(grad({ angle: 90, height: 100, width: 40 }), deps))
+ .surface as StubRasterSurface;
+ const [x0, y0, x1, y1] = gradientCall(surface, 'createLinearGradient') as number[];
+ expect(x0).toBeCloseTo(20);
+ expect(y0).toBeCloseTo(0);
+ expect(x1).toBeCloseTo(20);
+ expect(y1).toBeCloseTo(100);
+ });
+
+ it('runs a placed ramp through its center for its span', async () => {
+ const deps = makeDeps();
+ const surface = (
+ await rasterizeGradientSource(
+ grad({ angle: 0, center: { x: 30, y: 10 }, height: 100, span: 20, width: 100 }),
+ deps
+ )
+ ).surface as StubRasterSurface;
+ const [x0, y0, x1, y1] = gradientCall(surface, 'createLinearGradient') as number[];
+ expect(x0).toBeCloseTo(20);
+ expect(y0).toBeCloseTo(10);
+ expect(x1).toBeCloseTo(40);
+ expect(y1).toBeCloseTo(10);
+ });
+
it('creates a linear gradient and applies every stop', async () => {
const deps = makeDeps();
const surface = (await rasterizeGradientSource(grad({ angle: 90 }), deps)).surface as StubRasterSurface;
@@ -77,10 +105,20 @@ describe('rasterizeGradientSource — radial', () => {
const surface = (await rasterizeGradientSource(grad({ kind: 'radial' }), deps)).surface as StubRasterSurface;
expect(ops(surface)).toContain('createRadialGradient');
expect(ops(surface)).not.toContain('createLinearGradient');
+ const [cx, cy, r0, , , r1] = gradientCall(surface, 'createRadialGradient') as number[];
+ expect([cx, cy, r0]).toEqual([150, 100, 0]);
+ expect(r1).toBeCloseTo(Math.hypot(150, 100));
const stops = surface.callLog.filter((e) => e.op === 'addColorStop');
expect(stops).toHaveLength(2);
});
+ it('centers a placed radial gradient on its center with its span as the radius', async () => {
+ const deps = makeDeps();
+ const surface = (await rasterizeGradientSource(grad({ center: { x: 30, y: 40 }, kind: 'radial', span: 25 }), deps))
+ .surface as StubRasterSurface;
+ expect(gradientCall(surface, 'createRadialGradient')).toEqual([30, 40, 0, 30, 40, 25]);
+ });
+
it('supports more than two stops', async () => {
const deps = makeDeps();
const surface = (
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/gradientRasterizer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/gradientRasterizer.ts
index baf5bfc502..7fa0b52c2b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/gradientRasterizer.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/rasterizers/gradientRasterizer.ts
@@ -6,9 +6,10 @@
* default to the document dims (see {@link RasterizeDeps.documentSize}), so they
* render identically. The compositor positions the extent via the layer transform.
*
- * Linear: the gradient line runs through the extent center along `angle`
- * (degrees; 0° = left→right), long enough to cover the box corners. Radial:
- * centered on the extent, radius reaching the farthest corner.
+ * Linear: the gradient line runs through `center` along `angle` (degrees;
+ * 0° = left→right) for `span` px. Radial: `span` is the radius around `center`.
+ * Without an anchor the ramp is centered on the extent and fitted to its
+ * corners (how gradients looked before the drag placed them).
*
* Zero React, zero import-time side effects.
*/
@@ -23,20 +24,20 @@ type Ctx = RasterSurface['ctx'];
/** Builds the CSS-like gradient for the source across a `width`×`height` box. */
const buildGradient = (ctx: Ctx, source: GradientSource, width: number, height: number): CanvasGradient => {
- const cx = width / 2;
- const cy = height / 2;
+ const cx = source.center?.x ?? width / 2;
+ const cy = source.center?.y ?? height / 2;
let gradient: CanvasGradient;
if (source.kind === 'radial') {
- const radius = Math.hypot(width / 2, height / 2);
+ const radius = source.span ?? Math.hypot(width / 2, height / 2);
gradient = ctx.createRadialGradient(cx, cy, 0, cx, cy, radius);
} else {
const rad = (source.angle * Math.PI) / 180;
const dx = Math.cos(rad);
const dy = Math.sin(rad);
- // Half-length along the direction that just covers the box (projection of
- // the box's half-extents onto the gradient direction).
- const half = (Math.abs(dx) * width + Math.abs(dy) * height) / 2;
+ // Fitted fallback: the projection of the box's half-extents onto the
+ // gradient direction, so the ramp just covers the corners.
+ const half = source.span !== undefined ? source.span / 2 : (Math.abs(dx) * width + Math.abs(dy) * height) / 2;
gradient = ctx.createLinearGradient(cx - dx * half, cy - dy * half, cx + dx * half, cy + dy * half);
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts
index 61a849d243..35e5c0593a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts
@@ -9,7 +9,7 @@ import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/docum
import { createEngineStores } from '@workbench/canvas-engine/engineStores';
import { describe, expect, it, vi } from 'vitest';
-import { angleFromDrag, createGradientTool } from './gradientTool';
+import { createGradientTool, placementFromDrag } from './gradientTool';
const gradientLayer = (over: Partial<CanvasLayerContract> = {}): CanvasLayerContract =>
({
@@ -97,23 +97,38 @@ const down = (t: Tool, ctx: ToolContext, i: PointerInput): void => t.onPointerDo
const move = (t: Tool, ctx: ToolContext, i: PointerInput): void => t.onPointerMove?.(ctx, i, [i]);
const up = (t: Tool, ctx: ToolContext, i: PointerInput): void => t.onPointerUp?.(ctx, i);
-describe('angleFromDrag', () => {
- it('is 0° for a left→right drag and 90° for a top→bottom drag', () => {
- expect(angleFromDrag({ x: 0, y: 0 }, { x: 10, y: 0 })).toBeCloseTo(0);
- expect(angleFromDrag({ x: 0, y: 0 }, { x: 0, y: 10 })).toBeCloseTo(90);
+describe('placementFromDrag', () => {
+ it('centers a linear ramp on the drag midpoint, as long as the drag, along its angle', () => {
+ expect(placementFromDrag('linear', { x: 10, y: 20 }, { x: 10, y: 120 })).toEqual({
+ angle: 90,
+ center: { x: 10, y: 70 },
+ span: 100,
+ });
+ });
+
+ it('centers a radial gradient on the press point with the drag length as radius', () => {
+ expect(placementFromDrag('radial', { x: 10, y: 20 }, { x: 40, y: 60 })).toEqual({
+ angle: expect.any(Number),
+ center: { x: 10, y: 20 },
+ span: 50,
+ });
+ });
+
+ it('never yields a zero span', () => {
+ expect(placementFromDrag('linear', { x: 5, y: 5 }, { x: 5, y: 5 }).span).toBe(1);
});
});
describe('gradient tool: create when no gradient selected', () => {
- it('creates a document-covering gradient layer with the drag angle', () => {
- const h = createHarness(makeDoc());
+ it('creates a bbox-sized gradient layer placed where the drag went', () => {
+ const h = createHarness(makeDoc({ bbox: { height: 96, width: 96, x: 100, y: 200 } }));
const tool = createGradientTool();
- down(tool, h.ctx, pointer(10, 10));
- move(tool, h.ctx, pointer(10, 110));
- expect(h.previewOf()).toEqual({ end: { x: 10, y: 110 }, start: { x: 10, y: 10 } });
+ down(tool, h.ctx, pointer(110, 210));
+ move(tool, h.ctx, pointer(110, 310));
+ expect(h.previewOf()).toEqual({ end: { x: 110, y: 310 }, kind: 'linear', start: { x: 110, y: 210 } });
- up(tool, h.ctx, pointer(10, 110));
+ up(tool, h.ctx, pointer(110, 310));
expect(h.dispatched).toHaveLength(0);
expect(h.commits).toHaveLength(1);
@@ -126,7 +141,11 @@ describe('gradient tool: create when no gradient selected', () => {
) {
expect(forward.layer.source.angle).toBeCloseTo(90);
expect(forward.layer.source.kind).toBe('linear');
- expect(forward.layer.transform).toEqual({ rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 });
+ // Layer-local: the drag minus the bbox origin the layer sits at.
+ expect(forward.layer.source.center).toEqual({ x: 10, y: 60 });
+ expect(forward.layer.source.span).toBe(100);
+ expect(forward.layer.source.width).toBe(96);
+ expect(forward.layer.transform).toEqual({ rotation: 0, scaleX: 1, scaleY: 1, x: 100, y: 200 });
} else {
throw new Error('expected a gradient layer');
}
@@ -193,7 +212,7 @@ describe('gradient tool: create when no gradient selected', () => {
});
describe('gradient tool: edit selected gradient layer', () => {
- it('commits ONE updateCanvasLayerSource with the new angle (kind/stops preserved)', () => {
+ it('commits ONE updateCanvasLayerSource with the new placement (kind/stops preserved)', () => {
const layer = gradientLayer();
const doc = makeDoc({ stacks: stacksFrom([layer]), selectedLayerId: 'grad-existing' });
const h = createHarness(doc);
@@ -210,6 +229,8 @@ describe('gradient tool: edit selected gradient layer', () => {
if (forward?.type === 'updateCanvasLayerSource' && forward.source.type === 'gradient') {
expect(forward.id).toBe('grad-existing');
expect(forward.source.angle).toBeCloseTo(0);
+ expect(forward.source.center).toEqual({ x: 50, y: 0 });
+ expect(forward.source.span).toBe(100);
expect(forward.source.kind).toBe('linear');
expect(forward.source.stops).toHaveLength(2);
} else {
@@ -238,7 +259,30 @@ describe('gradient tool: edit selected gradient layer', () => {
expect(h.previewOf()).toBeNull();
});
- it('is a no-op when the selected gradient layer is radial (angle has no visual effect)', () => {
+ it("reads the drag in the layer's local space when it is moved, scaled and rotated", () => {
+ // Local +x points down the document after a quarter turn: a downward
+ // document drag of 200px is a 100px local drag along +x at scale 2.
+ const layer = gradientLayer({ transform: { rotation: Math.PI / 2, scaleX: 2, scaleY: 2, x: 100, y: 100 } });
+ const doc = makeDoc({ stacks: stacksFrom([layer]), selectedLayerId: 'grad-existing' });
+ const h = createHarness(doc);
+ const tool = createGradientTool();
+
+ down(tool, h.ctx, pointer(100, 100));
+ move(tool, h.ctx, pointer(100, 300));
+ up(tool, h.ctx, pointer(100, 300));
+
+ const forward = h.commits[0]?.forward;
+ if (forward?.type === 'updateCanvasLayerSource' && forward.source.type === 'gradient') {
+ expect(forward.source.angle).toBeCloseTo(0);
+ expect(forward.source.center?.x).toBeCloseTo(50);
+ expect(forward.source.center?.y).toBeCloseTo(0);
+ expect(forward.source.span).toBeCloseTo(100);
+ } else {
+ throw new Error('expected an updateCanvasLayerSource gradient edit');
+ }
+ });
+
+ it('re-centers a selected radial gradient on the press point with the drag as its radius', () => {
const layer = gradientLayer({
source: {
angle: 0,
@@ -254,15 +298,20 @@ describe('gradient tool: edit selected gradient layer', () => {
const h = createHarness(doc);
const tool = createGradientTool();
- down(tool, h.ctx, pointer(0, 0));
- move(tool, h.ctx, pointer(100, 0));
- up(tool, h.ctx, pointer(100, 0));
+ down(tool, h.ctx, pointer(20, 30));
+ move(tool, h.ctx, pointer(50, 70));
+ expect(h.previewOf()?.kind).toBe('radial');
+ up(tool, h.ctx, pointer(50, 70));
- // A radial gradient ignores `angle`, so dragging on one would only ever
- // produce an angle-only, visually-inert commit. Skipped entirely: no
- // commit, no dispatch, no dangling preview.
- expect(h.commits).toHaveLength(0);
- expect(h.dispatched).toHaveLength(0);
+ expect(h.commits).toHaveLength(1);
+ const forward = h.commits[0]?.forward;
+ if (forward?.type === 'updateCanvasLayerSource' && forward.source.type === 'gradient') {
+ expect(forward.source.kind).toBe('radial');
+ expect(forward.source.center).toEqual({ x: 20, y: 30 });
+ expect(forward.source.span).toBe(50);
+ } else {
+ throw new Error('expected an updateCanvasLayerSource gradient edit');
+ }
expect(h.previewOf()).toBeNull();
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts
index 2c3185edc6..615d2379fe 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts
@@ -1,5 +1,7 @@
/**
- * The gradient tool: drag to set a gradient's ANGLE from the drag vector.
+ * The gradient tool: drag to place a gradient. A linear ramp runs from the
+ * press point (stop 0) to the release point (stop 1); a radial one is centered
+ * on the press point with the drag length as its radius.
*
* Interaction contract (CANVAS_PLAN Phase 6.1):
* - **Pointer-down** (primary button) starts a gesture at the press point.
@@ -7,32 +9,38 @@
* preview (`stores.gradientPreview`, the drag vector) — it never dispatches.
* - **Commit** (pointer-up after a real drag): exactly ONE commit.
* - A gradient layer is selected (unlocked + visible) → one `commitStructural`
- * with `updateCanvasLayerSource` (new/old angle; kind + stops preserved).
- * - Otherwise → create a new bbox-sized gradient layer (angle from the drag,
- * kind + stops from the tool options, extent = the generation frame) via
- * `addCanvasLayer`.
+ * with `updateCanvasLayerSource` (new angle/center/span; kind + stops and
+ * the extent preserved). The drag is read in the layer's local space, so a
+ * moved/rotated/scaled gradient still lands where the pointer went.
+ * - Otherwise → create a new bbox-sized gradient layer (placement from the
+ * drag, kind + stops from the tool options, extent = the generation frame)
+ * via `addCanvasLayer`.
* - A selected gradient layer that is locked/hidden is a no-op (don't silently
* spawn a new layer over it), mirroring the paint tool's locked-target rule.
* - **Cancel** (Esc / pointercancel): drops the preview, no dispatch.
*
- * Gradient layers are content-sized via the contract's explicit `width`/`height`
- * extent — set at creation (bbox-sized) and preserved across angle edits — so
- * only the ANGLE is derived from the drag, not a bounding box. The selection
- * mask does NOT constrain gradient layers (parametric, not pixels).
+ * The selection mask does NOT constrain gradient layers (parametric, not pixels).
*
* Zero React, zero import-time side effects.
*/
-import type { CanvasLayerSourceContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';
+import type {
+ CanvasLayerBaseContract,
+ CanvasLayerSourceContract,
+ CanvasRasterLayerContractV2,
+} from '@workbench/canvas-engine/contracts';
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
import type { Vec2 } from '@workbench/canvas-engine/types';
import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';
import { getDocumentLeaves } from '@workbench/canvas-engine/document/documentIndex';
import { isLeafEditable } from '@workbench/canvas-engine/document/layerEligibility';
+import { applyToPoint, invert } from '@workbench/canvas-engine/math/mat2d';
import type { Tool, ToolContext } from './tool';
+import { layerMatrix } from './moveHitTest';
+
/** Bit for the primary (usually left) mouse button in `PointerEvent.buttons`. */
const PRIMARY_BUTTON = 1;
@@ -40,15 +48,42 @@ const PRIMARY_BUTTON = 1;
export const GRADIENT_DRAG_THRESHOLD_PX = 3;
interface GestureState {
+ /** What the drag will place: the selected gradient's kind, else the tool option. */
+ kind: 'linear' | 'radial';
startDoc: Vec2;
startScreen: Vec2;
moved: boolean;
}
/** Degrees of the vector from `start` to `end` (0° = left→right). */
-export const angleFromDrag = (start: Vec2, end: Vec2): number =>
+const angleFromDrag = (start: Vec2, end: Vec2): number =>
(Math.atan2(end.y - start.y, end.x - start.x) * 180) / Math.PI;
+/**
+ * The placement a drag from `start` to `end` (layer-local px) gives a gradient:
+ * a linear ramp is centered on the drag's midpoint and as long as the drag; a
+ * radial one is centered on the press point with the drag length as radius.
+ */
+export const placementFromDrag = (
+ kind: 'linear' | 'radial',
+ start: Vec2,
+ end: Vec2
+): { angle: number; center: Vec2; span: number } => ({
+ angle: angleFromDrag(start, end),
+ center: kind === 'radial' ? start : { x: (start.x + end.x) / 2, y: (start.y + end.y) / 2 },
+ span: Math.max(1, Math.hypot(end.x - start.x, end.y - start.y)),
+});
+
+/** Maps a document-space drag into a layer's local space; null when the transform is degenerate. */
+const toLayerLocal = (
+ transform: CanvasLayerBaseContract['transform'],
+ start: Vec2,
+ end: Vec2
+): [start: Vec2, end: Vec2] | null => {
+ const inverse = invert(layerMatrix(transform));
+ return inverse ? [applyToPoint(inverse, start), applyToPoint(inverse, end)] : null;
+};
+
/** Creates a fresh gradient tool with its own gesture state. */
export const createGradientTool = (): Tool => {
let state: GestureState | null = null;
@@ -79,10 +114,16 @@ export const createGradientTool = (): Tool => {
if (state || (input.buttons & PRIMARY_BUTTON) === 0) {
return;
}
- if (!ctx.getDocument()) {
+ const doc = ctx.getDocument();
+ if (!doc) {
return;
}
- state = { moved: false, startDoc: input.documentPoint, startScreen: input.screenPoint };
+ const selected = doc.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId)?.layer : null;
+ const kind =
+ selected?.type === 'raster' && selected.source.type === 'gradient'
+ ? selected.source.kind
+ : ctx.stores.gradientOptions.get().kind;
+ state = { kind, moved: false, startDoc: input.documentPoint, startScreen: input.screenPoint };
},
onPointerMove: (ctx, input) => {
if (!state) {
@@ -96,7 +137,7 @@ export const createGradientTool = (): Tool => {
}
state.moved = true;
}
- ctx.stores.gradientPreview.set({ end: input.documentPoint, start: state.startDoc });
+ ctx.stores.gradientPreview.set({ end: input.documentPoint, kind: state.kind, start: state.startDoc });
ctx.invalidate({ overlay: true });
},
onPointerUp: (ctx, input) => {
@@ -116,27 +157,22 @@ export const createGradientTool = (): Tool => {
clearPreview(ctx);
return;
}
- const angle = angleFromDrag(current.startDoc, input.documentPoint);
const leaf = doc.selectedLayerId ? lookupDocumentLeaf(doc, doc.selectedLayerId) : null;
const selected = leaf?.layer;
if (leaf && selected && selected.type === 'raster' && selected.source.type === 'gradient') {
// Edit the selected gradient layer — unless it's locked/disabled (no-op).
- if (!isLeafEditable(leaf)) {
+ const local = isLeafEditable(leaf)
+ ? toLayerLocal(selected.transform, current.startDoc, input.documentPoint)
+ : null;
+ if (!local) {
clearPreview(ctx);
return;
}
const old = selected.source;
- // A radial gradient's rendering ignores `angle` entirely — dragging on
- // one would only ever change that inert field, producing a commit with
- // zero visual effect and a useless history entry. Skip it.
- if (old.kind === 'radial') {
- clearPreview(ctx);
- return;
- }
const forward: CanvasProjectMutation = {
id: selected.id,
- source: { ...old, angle },
+ source: { ...old, ...placementFromDrag(old.kind, ...local) },
type: 'updateCanvasLayerSource',
};
const inverse: CanvasProjectMutation = { id: selected.id, source: old, type: 'updateCanvasLayerSource' };
@@ -145,10 +181,9 @@ export const createGradientTool = (): Tool => {
return;
}
- // Create a new bbox-sized gradient layer. The document rect is retired, so
- // creation covers the generation frame (bbox): the extent is the bbox size,
- // positioned at the bbox origin via the layer transform. Angle-drag edits on
- // an existing gradient preserve its extent (the `...old` spread above).
+ // Create a new bbox-sized gradient layer: the extent is the bbox size,
+ // positioned at the bbox origin via the layer transform, so the drag maps
+ // to layer space by that offset alone.
const options = ctx.stores.gradientOptions.get();
// The built-in FG→BG preset resolves the pair now; custom stops are
// explicit and independent of later pair edits.
@@ -161,8 +196,13 @@ export const createGradientTool = (): Tool => {
]
: options.stops.map((stop) => ({ ...stop }));
const layerId = ctx.createLayerId();
+ const origin = { x: doc.bbox.x, y: doc.bbox.y };
const source: CanvasLayerSourceContract = {
- angle,
+ ...placementFromDrag(
+ options.kind,
+ { x: current.startDoc.x - origin.x, y: current.startDoc.y - origin.y },
+ { x: input.documentPoint.x - origin.x, y: input.documentPoint.y - origin.y }
+ ),
height: doc.bbox.height,
kind: options.kind,
stops,
diff --git a/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts b/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts
index 50508fb25c..ac1478af34 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts
@@ -131,6 +131,31 @@ describe('loadCanvasState', () => {
expect(kinds).toEqual(['triangle', 'star']);
});
+ it('round-trips a placed gradient without rounding its anchor, and refuses a zero span', () => {
+ const gradient = (span: number) => ({
+ ...createEmptyPaintLayer('Gradient', 'gradient'),
+ source: {
+ angle: 30,
+ center: { x: 12.5, y: 7 },
+ height: 64,
+ kind: 'radial',
+ span,
+ stops: [
+ { color: '#000000ff', offset: 0 },
+ { color: '#00000000', offset: 1 },
+ ],
+ type: 'gradient',
+ width: 64,
+ },
+ });
+ const loaded = load(withNodes([gradient(40)])).document.stacks.raster[0];
+ expect(loaded?.type === 'raster' ? loaded.source : null).toMatchObject({ center: { x: 12.5, y: 7 }, span: 40 });
+ expect(refusal(withNodes([gradient(0)]))).toMatchObject({
+ diagnostics: [{ message: expect.stringContaining('span'), path: 'document.stacks.raster[0]' }],
+ status: 'invalid',
+ });
+ });
+
it('round-trips group adjustments in the raster stack, strips them from overlay groups, and drops a malformed group stack', () => {
const stack = [{ brightness: 0.1, contrast: 0, id: 'ga1', isEnabled: true, type: 'brightness-contrast' }];
const rasterGroup = {
diff --git a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts b/invokeai/frontend/webv2/src/workbench/canvasMigration.ts
index 018e2decc0..99f2b374f0 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasMigration.ts
@@ -68,8 +68,10 @@ const zLayerSource = z.discriminatedUnion('type', [
}),
z.object({
angle: zFiniteNumber,
+ center: zCoordinate.optional(),
height: zFiniteNumber.positive().optional(),
kind: z.enum(['linear', 'radial']),
+ span: zFiniteNumber.positive().optional(),
stops: z.array(z.object({ color: z.string(), offset: zFiniteNumber })),
type: z.literal('gradient'),
width: zFiniteNumber.positive().optional(),
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx
index 61ab35205a..8d05fe3f7a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx
@@ -8,6 +8,7 @@ import type {
import { Box } from '@chakra-ui/react';
import { Toolbar, ToolbarButton } from '@platform/ui/Toolbar';
import {
+ BlendIcon,
BrushIcon,
CircleIcon,
EraserIcon,
@@ -15,7 +16,6 @@ import {
HandIcon,
LassoIcon,
MoveIcon,
- PaintBucketIcon,
Rotate3dIcon,
SquareDashedIcon,
SquareIcon,
@@ -225,7 +225,7 @@ const ToolStripRoot = ({
<ShapeFamilyButton engine={engine} isInteractionLocked={isInteractionLocked} />
<ToolStripButton
engine={engine}
- icon={PaintBucketIcon}
+ icon={BlendIcon}
isInteractionLocked={isInteractionLocked}
label={t('widgets.canvas.tools.gradient')}
toolId="gradient"