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(webv2): separate pressure width and opacity

joshistoastde2583ab2380
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index ab5c44f0f8..209da62b49 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1497,7 +1497,8 @@
"opacity": "Opacity",
"positionX": "X",
"positionY": "Y",
- "pressureSensitivity": "Pressure sensitivity",
+ "pressureAffectsOpacity": "Pen pressure affects opacity",
+ "pressureAffectsWidth": "Pen pressure affects width",
"rotation": "Rotation",
"scaleHeight": "H %",
"scaleWidth": "W %",
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
index 2e36f0a708..916d3e8e35 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
@@ -32,7 +32,14 @@ export interface BrushOptions {
/** Per-stroke opacity in [0, 1]. */
opacity: number;
/** Whether pen pressure modulates the stroke width. */
- pressureSensitivity: boolean;
+ pressureAffectsWidth: boolean;
+ /**
+ * Whether pen pressure modulates the stroke's alpha along its length.
+ *
+ * Off by default: unlike width, it costs a full-region scratch refill per frame (see
+ * `strokeSession`), and it changes how a stroke reads rather than just its shape.
+ */
+ pressureAffectsOpacity: boolean;
}
/** Eraser tool options. */
@@ -190,7 +197,8 @@ export const MAX_BRUSH_SIZE = 2000;
export const DEFAULT_BRUSH_OPTIONS: BrushOptions = {
color: '#000000',
opacity: 1,
- pressureSensitivity: true,
+ pressureAffectsOpacity: false,
+ pressureAffectsWidth: true,
size: 50,
};
@@ -547,7 +555,8 @@ const brushOptionsEqual = (a: BrushOptions, b: BrushOptions): boolean =>
a.size === b.size &&
a.color === b.color &&
a.opacity === b.opacity &&
- a.pressureSensitivity === b.pressureSensitivity;
+ a.pressureAffectsWidth === b.pressureAffectsWidth &&
+ a.pressureAffectsOpacity === b.pressureAffectsOpacity;
const eraserOptionsEqual = (a: EraserOptions, b: EraserOptions): boolean =>
a.size === b.size && a.opacity === b.opacity;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/pressureBands.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/pressureBands.test.ts
new file mode 100644
index 0000000000..a7252c2717
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/pressureBands.test.ts
@@ -0,0 +1,102 @@
+import { describe, expect, it } from 'vitest';
+
+import type { StrokeSamplePoint } from './freehand';
+
+import {
+ BAND_OVERLAP_SAMPLES,
+ getPressureBands,
+ MIN_PRESSURE_ALPHA,
+ PRESSURE_ALPHA_STEPS,
+ toPressureAlpha,
+} from './pressureBands';
+
+const point = (x: number, pressure: number): StrokeSamplePoint => ({ pressure, x, y: 0 });
+
+describe('toPressureAlpha', () => {
+ it('quantizes to the configured step count', () => {
+ expect(toPressureAlpha(1)).toBe(1);
+ expect(toPressureAlpha(0.5)).toBe(0.5);
+ // 0.53 snaps to the nearest 1/16 (0.5) rather than staying exact.
+ expect(toPressureAlpha(0.53)).toBe(0.5);
+ expect(toPressureAlpha(0.5 + 1 / PRESSURE_ALPHA_STEPS)).toBeCloseTo(0.5625, 6);
+ });
+
+ it('never returns zero, so a zero-pressure sample still paints', () => {
+ // Devices commonly report 0 for a stroke's first sample; a 0-alpha band would leave a gap.
+ expect(toPressureAlpha(0)).toBe(MIN_PRESSURE_ALPHA);
+ expect(toPressureAlpha(0.001)).toBe(MIN_PRESSURE_ALPHA);
+ });
+
+ it('clamps out-of-range pressure instead of producing alpha outside (0, 1]', () => {
+ expect(toPressureAlpha(-1)).toBe(MIN_PRESSURE_ALPHA);
+ expect(toPressureAlpha(5)).toBe(1);
+ expect(toPressureAlpha(Number.NaN)).toBe(MIN_PRESSURE_ALPHA);
+ });
+});
+
+describe('getPressureBands', () => {
+ it('returns nothing for an empty stroke', () => {
+ expect(getPressureBands([])).toEqual([]);
+ });
+
+ it('keeps a single sample as one band, so a tap still paints a dot', () => {
+ const bands = getPressureBands([point(0, 1)]);
+
+ expect(bands).toHaveLength(1);
+ expect(bands[0]).toMatchObject({ alpha: 1 });
+ expect(bands[0]?.points).toHaveLength(1);
+ });
+
+ it('collapses a constant-pressure stroke into one band', () => {
+ const bands = getPressureBands([point(0, 1), point(1, 1), point(2, 1)]);
+
+ expect(bands).toHaveLength(1);
+ expect(bands[0]?.points).toHaveLength(3);
+ });
+
+ it('collapses samples that quantize to the same level, keeping band count low', () => {
+ // 0.50 / 0.51 / 0.52 all snap to 0.5, so they must not each become a band.
+ const bands = getPressureBands([point(0, 0.5), point(1, 0.51), point(2, 0.52)]);
+
+ expect(bands).toHaveLength(1);
+ expect(bands[0]?.alpha).toBe(0.5);
+ });
+
+ it('splits on a level change and shares a sample so outlines abut', () => {
+ const bands = getPressureBands([point(0, 1), point(1, 1), point(2, 0.5)]);
+
+ expect(bands).toHaveLength(2);
+ expect(bands[0]).toMatchObject({ alpha: 1 });
+ expect(bands[1]).toMatchObject({ alpha: 0.5 });
+ // The second band repeats the first band's last sample; without it the two outlines
+ // would leave a hairline gap at the level change.
+ expect(bands[1]?.points[0]).toBe(bands[0]?.points.at(-1));
+ expect(bands[1]?.points).toHaveLength(BAND_OVERLAP_SAMPLES + 1);
+ });
+
+ it('preserves stroke order across many level changes', () => {
+ const pressures = [1, 0.75, 0.5, 0.25, 0.5, 1];
+ const bands = getPressureBands(pressures.map((pressure, index) => point(index, pressure)));
+
+ expect(bands.map((band) => band.alpha)).toEqual([1, 0.75, 0.5, 0.25, 0.5, 1]);
+ });
+
+ it('covers every sample across the returned bands', () => {
+ const points = [point(0, 1), point(1, 0.5), point(2, 0.5), point(3, 0.25)];
+ const bands = getPressureBands(points);
+ const covered = new Set(bands.flatMap((band) => band.points));
+
+ for (const sample of points) {
+ expect(covered.has(sample)).toBe(true);
+ }
+ });
+
+ it('does not mutate the input samples', () => {
+ const points = [point(0, 1), point(1, 0.5)];
+ const snapshot = structuredClone(points);
+
+ getPressureBands(points);
+
+ expect(points).toEqual(snapshot);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/pressureBands.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/pressureBands.ts
new file mode 100644
index 0000000000..af20c44994
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/pressureBands.ts
@@ -0,0 +1,108 @@
+/**
+ * Splits a pressure-sampled stroke into contiguous constant-alpha bands.
+ *
+ * ## Why bands, and why they must not overlap-blend
+ *
+ * `strokeSession` fills the whole stroke into a scratch surface at full alpha and composites
+ * it into the layer exactly once at the stroke opacity. That single composite is what stops
+ * overlapping segments *within one stroke* from darkening each other — a slow drag revisits
+ * the same pixels dozens of times, and `source-over` at partial alpha would compound every
+ * one of them into a dark blob.
+ *
+ * Pressure-dependent opacity breaks that model, because alpha now varies along the stroke and
+ * cannot be one `globalAlpha` on one composite. The fix is to fill the stroke as a sequence of
+ * bands, each a contiguous run of samples at one quantized alpha, and to paint each band into
+ * the scratch as *replace* (`destination-out` the band's own path, then `source-over` it at the
+ * band's alpha) rather than as a blend. Replace keeps the no-compounding guarantee: where two
+ * bands overlap, the later one wins outright, which is also the behaviour a stroke wants — the
+ * newer sample's pressure is the current one.
+ *
+ * Bands are quantized rather than per-sample because each band is a separate outline
+ * computation and two extra canvas fills. Quantizing to {@link PRESSURE_ALPHA_STEPS} levels
+ * keeps a normal drag to a handful of bands while staying below the ~2% alpha difference an
+ * eye can pick out of a soft edge.
+ *
+ * Consecutive bands share a sample ({@link BAND_OVERLAP_SAMPLES}) so their outlines abut
+ * instead of leaving a hairline gap where the pressure level changes.
+ *
+ * Zero React, zero import-time side effects.
+ */
+
+import type { StrokeSamplePoint } from '@workbench/canvas-engine/freehand';
+
+/** Quantization levels for band alpha. */
+export const PRESSURE_ALPHA_STEPS = 16;
+
+/**
+ * Samples a band repeats from the previous one. One is enough: `perfect-freehand` derives a
+ * segment's outline from its endpoints, so sharing an endpoint makes the outlines meet.
+ */
+export const BAND_OVERLAP_SAMPLES = 1;
+
+/**
+ * Floor on band alpha. A zero-pressure sample would otherwise contribute an invisible band,
+ * and some devices report 0 for the first sample of a stroke before pressure ramps up — which
+ * would leave a gap at the stroke's start.
+ */
+export const MIN_PRESSURE_ALPHA = 1 / PRESSURE_ALPHA_STEPS;
+
+/** A contiguous run of samples painted at one alpha. */
+export interface PressureBand {
+ /** Samples for this band's outline, including the shared sample from the previous band. */
+ points: StrokeSamplePoint[];
+ /** Quantized alpha in (0, 1]. */
+ alpha: number;
+}
+
+/**
+ * Quantizes pressure to a band alpha in (0, 1].
+ *
+ * Non-finite pressure floors to {@link MIN_PRESSURE_ALPHA} rather than propagating: clamping
+ * alone would let NaN through to `globalAlpha`, where a non-finite value is ignored and the
+ * band would silently paint at full alpha — the opposite of the lightest possible touch.
+ */
+export const toPressureAlpha = (pressure: number): number => {
+ if (!Number.isFinite(pressure)) {
+ return MIN_PRESSURE_ALPHA;
+ }
+
+ const clamped = Math.min(1, Math.max(0, pressure));
+ const quantized = Math.round(clamped * PRESSURE_ALPHA_STEPS) / PRESSURE_ALPHA_STEPS;
+
+ return Math.max(MIN_PRESSURE_ALPHA, quantized);
+};
+
+/**
+ * Groups samples into constant-alpha bands, in stroke order.
+ *
+ * A single sample yields a single band — `perfect-freehand` renders a lone point as a dot, and
+ * dropping it would make a tap invisible. An empty input yields no bands.
+ */
+export const getPressureBands = (points: readonly StrokeSamplePoint[]): PressureBand[] => {
+ if (points.length === 0) {
+ return [];
+ }
+
+ const bands: PressureBand[] = [];
+ let current: PressureBand = { alpha: toPressureAlpha(points[0]!.pressure), points: [points[0]!] };
+
+ for (let index = 1; index < points.length; index += 1) {
+ const point = points[index]!;
+ const alpha = toPressureAlpha(point.pressure);
+
+ if (alpha === current.alpha) {
+ current.points.push(point);
+ continue;
+ }
+
+ // The level changed. Close the current band, then open the next one seeded with the
+ // shared sample so the two outlines abut rather than leaving a seam.
+ bands.push(current);
+ const overlap = current.points.slice(-BAND_OVERLAP_SAMPLES);
+ current = { alpha, points: [...overlap, point] };
+ }
+
+ bands.push(current);
+
+ return bands;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/brushTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/brushTool.ts
index 2d99e2ee33..d24d6bb289 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/brushTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/brushTool.ts
@@ -22,5 +22,6 @@ export const createBrushTool = (): Tool =>
id: 'brush',
opacity: (ctx) => ctx.stores.brushOptions.get().opacity,
size: (ctx) => ctx.stores.brushOptions.get().size,
- thinning: (ctx) => (ctx.stores.brushOptions.get().pressureSensitivity ? PRESSURE_THINNING : 0),
+ pressureOpacity: (ctx) => ctx.stores.brushOptions.get().pressureAffectsOpacity,
+ thinning: (ctx) => (ctx.stores.brushOptions.get().pressureAffectsWidth ? PRESSURE_THINNING : 0),
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/eraserTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/eraserTool.ts
index 8914ae6116..282162f27c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/eraserTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/eraserTool.ts
@@ -20,6 +20,9 @@ export const createEraserTool = (): Tool =>
composite: 'destination-out',
id: 'eraser',
opacity: (ctx) => ctx.stores.eraserOptions.get().opacity,
+ // Upstream keeps eraser pressure width-only too; a pressure-faded erase reads as a
+ // failed erase rather than a soft one.
+ pressureOpacity: () => false,
size: (ctx) => ctx.stores.eraserOptions.get().size,
thinning: () => 0,
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
index 2bc6350744..12218fc2b3 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
@@ -36,6 +36,8 @@ export interface PaintToolSpec {
color(ctx: ToolContext): string;
/** Freehand thinning for this gesture; 0 disables pressure sensitivity. */
thinning(ctx: ToolContext): number;
+ /** Whether pen pressure modulates alpha along the stroke. Absent means never (eraser). */
+ pressureOpacity?(ctx: ToolContext): boolean;
}
/** Colour brush strokes paint into a MASK cache: an opaque stencil (only alpha matters). */
@@ -236,6 +238,9 @@ export const createPaintTool = (spec: PaintToolSpec): Tool => {
// Mask strokes are forced opaque (an alpha stencil is all-or-nothing); a
// brush-opacity mask stroke would silently attenuate the denoise strength.
opacity: target.forceOpaque ? 1 : spec.opacity(ctx),
+ // A mask stroke is an all-or-nothing alpha stencil, so pressure must not thin it —
+ // a partially-transparent mask would silently attenuate the denoise strength.
+ pressureOpacity: !target.forceOpaque && (spec.pressureOpacity?.(ctx) ?? false),
size: spec.size(ctx),
thinning: spec.thinning(ctx),
tool: spec.id,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.browser.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.browser.test.ts
index 40d8f9bdc4..ac0c351be0 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.browser.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.browser.test.ts
@@ -43,6 +43,7 @@ const paint = (
layerId: 'L',
opacity: opts.opacity,
size: opts.size,
+ pressureOpacity: false,
thinning: opts.thinning,
tool: 'brush',
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.ts
index 093f1da4a9..205210c928 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.test.ts
@@ -66,6 +66,7 @@ const runStroke = (opts: { withMask: boolean }) => {
layerId: 'L',
opacity: 1,
size: 20,
+ pressureOpacity: false,
thinning: 0,
tool: 'brush',
});
@@ -141,6 +142,7 @@ describe('strokeSession: bbox-clipped painting', () => {
layerId: 'L',
opacity: 1,
size: 20,
+ pressureOpacity: false,
thinning: 0,
tool: 'brush',
});
@@ -223,6 +225,7 @@ describe('strokeSession: content-sized cache growth', () => {
layerId: 'L',
opacity: 1,
size: 20,
+ pressureOpacity: false,
thinning: 0,
tool: 'brush',
});
@@ -344,6 +347,7 @@ describe('strokeSession: cache version bump (live adjusted-surface invalidation)
layerId: 'L',
opacity: 1,
size: 20,
+ pressureOpacity: false,
thinning: 0,
tool: 'brush',
});
@@ -395,6 +399,7 @@ describe('incremental "before" snapshot', () => {
layerId: 'L',
opacity: 1,
size,
+ pressureOpacity: false,
thinning: 0,
tool: 'brush',
});
@@ -450,3 +455,98 @@ describe('incremental "before" snapshot', () => {
expect(resizes).toBeLessThan(4000 / 200);
});
});
+
+describe('strokeSession: pressure-dependent opacity', () => {
+ const pointerAt = (x: number, y: number, pressure: number): PointerInput => ({
+ ...pointer(x, y),
+ pressure,
+ });
+
+ const runPressureStroke = (pressureOpacity: boolean, pressures: number[]) => {
+ const { backend, created } = createCapturingBackend();
+ const layers = createLayerCacheStore(backend);
+ layers.getOrCreate('L', 100, 100);
+ const ctx = {
+ backend,
+ createPath2D: () => {
+ const path = { closePath: () => {}, lineTo: () => {}, moveTo: () => {}, quadraticCurveTo: () => {} };
+ return path as unknown as Path2D;
+ },
+ emitStrokeCommitted: vi.fn(),
+ invalidate: vi.fn(),
+ layers,
+ notifyLayerPainted: vi.fn(),
+ } as unknown as ToolContext;
+
+ created.length = 0;
+ const session = createStrokeSession({
+ clipMask: null,
+ color: '#ff0000',
+ composite: 'source-over',
+ ctx,
+ layerId: 'L',
+ opacity: 1,
+ pressureOpacity,
+ size: 20,
+ thinning: 0,
+ tool: 'brush',
+ });
+ session.addPoints(pressures.map((pressure, index) => pointerAt(10 + index * 10, 10, pressure)));
+ const scratch = created[0]!;
+ // A session repaints on every batch and once more on commit. Measuring the whole gesture
+ // would couple these assertions to the batch count, so clear the log and let commit's
+ // single repaint be the one under test.
+ scratch.callLog.length = 0;
+ session.commit();
+
+ return scratch;
+ };
+
+ const alphaValues = (surface: StubRasterSurface): number[] =>
+ surface.callLog.filter((e) => e.op === 'set' && e.args[0] === 'globalAlpha').map((e) => e.args[1] as number);
+
+ it('fills the stroke once at full alpha when pressure opacity is off', () => {
+ const scratch = runPressureStroke(false, [0.25, 0.5, 1]);
+
+ // One fill for the whole outline: overlapping parts of the stroke union instead of
+ // compounding, which is the guarantee the single-composite design provides.
+ expect(scratch.callLog.filter((e) => e.op === 'fill')).toHaveLength(1);
+ expect(alphaValues(scratch).every((alpha) => alpha === 1)).toBe(true);
+ });
+
+ it('paints one punch-and-fill pair per pressure band when enabled', () => {
+ const scratch = runPressureStroke(true, [1, 0.5, 0.25]);
+
+ // Three distinct levels => three bands => two fills each (destination-out, then source-over).
+ expect(scratch.callLog.filter((e) => e.op === 'fill')).toHaveLength(6);
+ expect(compositeOps(scratch).filter((op) => op === 'destination-out')).toHaveLength(3);
+ });
+
+ it('replaces rather than blends each band, so overlaps cannot compound alpha', () => {
+ const scratch = runPressureStroke(true, [1, 0.5]);
+ const ops = scratch.callLog.filter(
+ (e) =>
+ e.op === 'fill' || (e.op === 'set' && (e.args[0] === 'globalCompositeOperation' || e.args[0] === 'globalAlpha'))
+ );
+ const signature = ops.map((e) => (e.op === 'fill' ? 'fill' : `${String(e.args[0])}=${String(e.args[1])}`));
+
+ // Every band punches its own footprint at alpha 1 before refilling at the band alpha.
+ // Without the destination-out the second band would blend into the first and darken it.
+ expect(signature.join(' ')).toContain(
+ 'globalCompositeOperation=destination-out globalAlpha=1 fill globalCompositeOperation=source-over'
+ );
+ });
+
+ it('drives band alpha from pen pressure', () => {
+ const scratch = runPressureStroke(true, [1, 0.5]);
+
+ expect(alphaValues(scratch)).toContain(1);
+ expect(alphaValues(scratch)).toContain(0.5);
+ });
+
+ it('collapses a constant-pressure stroke to a single band', () => {
+ const scratch = runPressureStroke(true, [0.5, 0.5, 0.5]);
+
+ expect(scratch.callLog.filter((e) => e.op === 'fill')).toHaveLength(2);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts
index 00cd3770a7..9cd5d0a148 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts
@@ -44,6 +44,7 @@ import type { PlacedSurface, PointerInput, Rect, Vec2 } from '@workbench/canvas-
import { strokeToPath, type StrokeSamplePoint } from '@workbench/canvas-engine/freehand';
import { expand, intersect, isEmpty, roundOut, union } from '@workbench/canvas-engine/math/rect';
+import { getPressureBands } from '@workbench/canvas-engine/pressureBands';
import type { StrokeCommittedEvent, ToolContext } from './tool';
@@ -58,6 +59,11 @@ export interface StrokeSessionConfig {
opacity: number;
/** Freehand thinning; 0 disables pressure sensitivity. */
thinning: number;
+ /**
+ * Whether pen pressure modulates alpha along the stroke. Costs a full-region scratch
+ * refill per frame (see the band fill below), so it is opt-in.
+ */
+ pressureOpacity: boolean;
/** Fill color (brush only; ignored for the eraser). */
color: string;
/**
@@ -291,7 +297,20 @@ const surroundingStrips = (inner: Rect, outer: Rect): Rect[] => {
/** Creates a paint session that grows the target layer's content-sized cache. */
export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession => {
- const { clipMask, clipRect, color, composite, createdLayer, ctx, layerId, opacity, size, thinning, tool } = config;
+ const {
+ clipMask,
+ clipRect,
+ color,
+ composite,
+ createdLayer,
+ ctx,
+ layerId,
+ opacity,
+ pressureOpacity,
+ size,
+ thinning,
+ tool,
+ } = config;
const layers: LayerCacheStore = ctx.layers;
// A per-frame scratch surface for the filled stroke, sized to the paint region.
@@ -423,8 +442,13 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession
// one already sitting there — so re-clearing and re-filling the whole
// region was redrawing pixels to their existing values. A region change
// resizes the scratch, which clears it, so that case still refills whole.
+ //
+ // Pressure-opacity forces the whole region to refresh instead. Bands are painted as
+ // replace, so a band straddling the changed strip would be half-punched by a partial
+ // refill and lose its earlier half. Refilling whole keeps the band sequence intact,
+ // at the cost of the per-frame saving above — which is why it stays opt-in.
const scratchCleared = !previousRect || !sameRect(previousRect, region);
- const refresh = scratchCleared ? region : changed;
+ const refresh = scratchCleared || pressureOpacity ? region : changed;
const scratch = ensureStroke(region.width, region.height);
const strokeCtx = scratch.ctx;
strokeCtx.setTransform(1, 0, 0, 1, -region.x, -region.y);
@@ -433,10 +457,30 @@ export const createStrokeSession = (config: StrokeSessionConfig): StrokeSession
strokeCtx.rect(refresh.x, refresh.y, refresh.width, refresh.height);
strokeCtx.clip();
strokeCtx.clearRect(refresh.x, refresh.y, refresh.width, refresh.height);
- strokeCtx.globalCompositeOperation = 'source-over';
- strokeCtx.globalAlpha = 1;
strokeCtx.fillStyle = color;
- strokeCtx.fill(path);
+
+ if (pressureOpacity) {
+ // Each band replaces its own footprint rather than blending into it: punch the band's
+ // outline out of whatever is already there, then fill it at the band's alpha. Blending
+ // would compound alpha wherever bands overlap — the exact darkening the single
+ // full-alpha fill below exists to prevent. Replacing means the later (newer) band wins
+ // in the overlap, which is the pressure the user is applying now.
+ for (const band of getPressureBands(points)) {
+ const bandPath = strokeToPath(band.points, { last, size, thinning }, ctx.createPath2D).path;
+
+ strokeCtx.globalCompositeOperation = 'destination-out';
+ strokeCtx.globalAlpha = 1;
+ strokeCtx.fill(bandPath);
+ strokeCtx.globalCompositeOperation = 'source-over';
+ strokeCtx.globalAlpha = band.alpha;
+ strokeCtx.fill(bandPath);
+ }
+ } else {
+ strokeCtx.globalCompositeOperation = 'source-over';
+ strokeCtx.globalAlpha = 1;
+ strokeCtx.fill(path);
+ }
+
strokeCtx.restore();
// 4b. Selection clip: keep only the stroke pixels inside the selection mask.
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BrushOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BrushOptions.tsx
index a89f0d32f3..c5df6e82b1 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BrushOptions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BrushOptions.tsx
@@ -69,8 +69,13 @@ export const BrushOptions = ({ engine }: ToolOptionsComponentProps) => {
[engine, options]
);
- const onPressureToggle = useCallback(
- (checked: boolean) => engine.interaction.set('brushOptions', { ...options, pressureSensitivity: checked }),
+ const onPressureWidthToggle = useCallback(
+ (checked: boolean) => engine.interaction.set('brushOptions', { ...options, pressureAffectsWidth: checked }),
+ [engine, options]
+ );
+
+ const onPressureOpacityToggle = useCallback(
+ (checked: boolean) => engine.interaction.set('brushOptions', { ...options, pressureAffectsOpacity: checked }),
[engine, options]
);
@@ -114,10 +119,21 @@ export const BrushOptions = ({ engine }: ToolOptionsComponentProps) => {
w="6rem"
onValueChange={onOpacityChange}
/>
+ {/*
+ Two independent dots rather than one pressure switch: width and opacity are separate
+ pressure responses, and opacity additionally costs a full scratch refill per frame.
+ Each ToggleDot is an aria-labelled button, so unlike sibling switches sharing a
+ Field.Root they cannot collide on a hidden-input id.
+ */}
+ <ToggleDot
+ checked={options.pressureAffectsWidth}
+ label={t('widgets.canvas.toolOptions.pressureAffectsWidth')}
+ onCheckedChange={onPressureWidthToggle}
+ />
<ToggleDot
- checked={options.pressureSensitivity}
- label={t('widgets.canvas.toolOptions.pressureSensitivity')}
- onCheckedChange={onPressureToggle}
+ checked={options.pressureAffectsOpacity}
+ label={t('widgets.canvas.toolOptions.pressureAffectsOpacity')}
+ onCheckedChange={onPressureOpacityToggle}
/>
</HStack>
);