Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
Feat(UI): Add linear and radial gradient tools to canvas (#8774)
DustyShoeb7d7cd074893
diff --git a/invokeai/frontend/web/public/locales/en.json b/invokeai/frontend/web/public/locales/en.jsonindex b1ab43456e..d2ec5b7352 100644--- a/invokeai/frontend/web/public/locales/en.json+++ b/invokeai/frontend/web/public/locales/en.json@@ -2433,10 +2433,16 @@"horizontal": "Horizontal","diagonal": "Diagonal"},+ "gradient": {+ "linear": "Linear",+ "radial": "Radial",+ "clip": "Clip Gradient"+ },"tool": {"brush": "Brush","eraser": "Eraser","rectangle": "Rectangle",+ "gradient": "Gradient","bbox": "Bbox","move": "Move","view": "View",diff --git a/invokeai/frontend/web/src/features/controlLayers/components/Tool/GradientIcons.tsx b/invokeai/frontend/web/src/features/controlLayers/components/Tool/GradientIcons.tsxnew file mode 100644index 0000000000..b09e46d732--- /dev/null+++ b/invokeai/frontend/web/src/features/controlLayers/components/Tool/GradientIcons.tsx@@ -0,0 +1,81 @@+import { Box } from '@invoke-ai/ui-library';+import { memo, useId } from 'react';++export const GradientToolIcon = memo(() => {+ const id = useId();+ const gradientId = `${id}-gradient-tool-horizontal`;+ return (+ <Box as="svg" viewBox="0 0 24 24" boxSize={6} aria-hidden focusable={false} display="block">+ <defs>+ <linearGradient id={gradientId} x1="0" y1="0.5" x2="1" y2="0.5">+ <stop offset="0%" stopColor="currentColor" stopOpacity="0.0" />+ <stop offset="100%" stopColor="currentColor" stopOpacity="0.85" />+ </linearGradient>+ </defs>+ <rect+ x="3"+ y="6"+ width="18"+ height="12"+ rx="2"+ fill={`url(#${gradientId})`}+ stroke="currentColor"+ strokeOpacity="0.9"+ strokeWidth="1"+ />+ </Box>+ );+});+GradientToolIcon.displayName = 'GradientToolIcon';++export const GradientLinearIcon = memo(() => {+ const id = useId();+ const gradientId = `${id}-gradient-linear-diagonal`;+ return (+ <Box as="svg" viewBox="0 0 24 24" boxSize="22px" aria-hidden focusable={false} display="block">+ <defs>+ <linearGradient id={gradientId} x1="0" y1="1" x2="1" y2="0">+ <stop offset="0%" stopColor="currentColor" stopOpacity="0.0" />+ <stop offset="100%" stopColor="currentColor" stopOpacity="0.85" />+ </linearGradient>+ </defs>+ <rect+ x="4"+ y="4"+ width="16"+ height="16"+ rx="2"+ fill={`url(#${gradientId})`}+ stroke="currentColor"+ strokeOpacity="0.9"+ strokeWidth="1"+ />+ </Box>+ );+});+GradientLinearIcon.displayName = 'GradientLinearIcon';++export const GradientRadialIcon = memo(() => {+ const id = useId();+ const gradientId = `${id}-gradient-radial`;+ return (+ <Box as="svg" viewBox="0 0 24 24" boxSize="22px" aria-hidden focusable={false} display="block">+ <defs>+ <radialGradient id={gradientId} cx="0.5" cy="0.5" r="0.5">+ <stop offset="0%" stopColor="currentColor" stopOpacity="0.0" />+ <stop offset="100%" stopColor="currentColor" stopOpacity="0.85" />+ </radialGradient>+ </defs>+ <circle+ cx="12"+ cy="12"+ r="8"+ fill={`url(#${gradientId})`}+ stroke="currentColor"+ strokeOpacity="0.9"+ strokeWidth="1"+ />+ </Box>+ );+});+GradientRadialIcon.displayName = 'GradientRadialIcon';diff --git a/invokeai/frontend/web/src/features/controlLayers/components/Tool/ToolChooser.tsx b/invokeai/frontend/web/src/features/controlLayers/components/Tool/ToolChooser.tsxindex d2b35ced8a..b065221000 100644--- a/invokeai/frontend/web/src/features/controlLayers/components/Tool/ToolChooser.tsx+++ b/invokeai/frontend/web/src/features/controlLayers/components/Tool/ToolChooser.tsx@@ -2,6 +2,7 @@ import { ButtonGroup } from '@invoke-ai/ui-library';import { ToolBboxButton } from 'features/controlLayers/components/Tool/ToolBboxButton';import { ToolBrushButton } from 'features/controlLayers/components/Tool/ToolBrushButton';import { ToolColorPickerButton } from 'features/controlLayers/components/Tool/ToolColorPickerButton';+import { ToolGradientButton } from 'features/controlLayers/components/Tool/ToolGradientButton';import { ToolMoveButton } from 'features/controlLayers/components/Tool/ToolMoveButton';import { ToolRectButton } from 'features/controlLayers/components/Tool/ToolRectButton';import React from 'react';@@ -16,6 +17,7 @@ export const ToolChooser: React.FC = () => {<ToolBrushButton /><ToolEraserButton /><ToolRectButton />+ <ToolGradientButton /><ToolMoveButton /><ToolViewButton /><ToolBboxButton />diff --git a/invokeai/frontend/web/src/features/controlLayers/components/Tool/ToolGradientButton.tsx b/invokeai/frontend/web/src/features/controlLayers/components/Tool/ToolGradientButton.tsxnew file mode 100644index 0000000000..3227539918--- /dev/null+++ b/invokeai/frontend/web/src/features/controlLayers/components/Tool/ToolGradientButton.tsx@@ -0,0 +1,30 @@+import { IconButton, Tooltip } from '@invoke-ai/ui-library';+import { GradientToolIcon } from 'features/controlLayers/components/Tool/GradientIcons';+import { useSelectTool, useToolIsSelected } from 'features/controlLayers/components/Tool/hooks';+import { memo, useCallback } from 'react';+import { useTranslation } from 'react-i18next';++export const ToolGradientButton = memo(() => {+ const { t } = useTranslation();+ const isSelected = useToolIsSelected('gradient');+ const selectGradient = useSelectTool('gradient');+ // clicking selects the gradient tool; mode switching is handled in the top toolbar+ const handleClick = useCallback(() => selectGradient(), [selectGradient]);++ const gradientLabel = t('controlLayers.tool.gradient', { defaultValue: 'Gradient' });++ return (+ <Tooltip label={gradientLabel} placement="end">+ <IconButton+ aria-label={gradientLabel}+ icon={<GradientToolIcon />}+ isActive={isSelected}+ colorScheme={isSelected ? 'invokeBlue' : 'base'}+ variant="solid"+ onClick={handleClick}+ />+ </Tooltip>+ );+});++ToolGradientButton.displayName = 'ToolGradientButton';diff --git a/invokeai/frontend/web/src/features/controlLayers/components/Tool/ToolGradientClipToggle.tsx b/invokeai/frontend/web/src/features/controlLayers/components/Tool/ToolGradientClipToggle.tsxnew file mode 100644index 0000000000..a89ef6a470--- /dev/null+++ b/invokeai/frontend/web/src/features/controlLayers/components/Tool/ToolGradientClipToggle.tsx@@ -0,0 +1,36 @@+import { IconButton, Tooltip } from '@invoke-ai/ui-library';+import { useAppDispatch, useAppSelector } from 'app/store/storeHooks';+import {+ selectGradientClipEnabled,+ settingsGradientClipToggled,+} from 'features/controlLayers/store/canvasSettingsSlice';+import { memo, useCallback } from 'react';+import { useTranslation } from 'react-i18next';+import { PiCropBold } from 'react-icons/pi';++export const ToolGradientClipToggle = memo(() => {+ const { t } = useTranslation();+ const isEnabled = useAppSelector(selectGradientClipEnabled);+ const dispatch = useAppDispatch();++ const onClick = useCallback(() => {+ dispatch(settingsGradientClipToggled());+ }, [dispatch]);++ const label = t('controlLayers.gradient.clip', { defaultValue: 'Clip Gradient' });++ return (+ <Tooltip label={label}>+ <IconButton+ aria-label={label}+ icon={<PiCropBold size={16} />}+ size="sm"+ variant="solid"+ colorScheme={isEnabled ? 'invokeBlue' : 'base'}+ onClick={onClick}+ />+ </Tooltip>+ );+});++ToolGradientClipToggle.displayName = 'ToolGradientClipToggle';diff --git a/invokeai/frontend/web/src/features/controlLayers/components/Tool/ToolGradientModeToggle.tsx b/invokeai/frontend/web/src/features/controlLayers/components/Tool/ToolGradientModeToggle.tsxnew file mode 100644index 0000000000..03b18c466e--- /dev/null+++ b/invokeai/frontend/web/src/features/controlLayers/components/Tool/ToolGradientModeToggle.tsx@@ -0,0 +1,40 @@+import { ButtonGroup, IconButton, Tooltip } from '@invoke-ai/ui-library';+import { useAppDispatch, useAppSelector } from 'app/store/storeHooks';+import { GradientLinearIcon, GradientRadialIcon } from 'features/controlLayers/components/Tool/GradientIcons';+import { selectGradientType, settingsGradientTypeChanged } from 'features/controlLayers/store/canvasSettingsSlice';+import { memo, useCallback } from 'react';+import { useTranslation } from 'react-i18next';++export const ToolGradientModeToggle = memo(() => {+ const { t } = useTranslation();+ const gradientType = useAppSelector(selectGradientType);+ const dispatch = useAppDispatch();++ const onLinearClick = useCallback(() => dispatch(settingsGradientTypeChanged('linear')), [dispatch]);+ const onRadialClick = useCallback(() => dispatch(settingsGradientTypeChanged('radial')), [dispatch]);++ return (+ <ButtonGroup isAttached size="sm">+ <Tooltip label={t('controlLayers.gradient.linear', { defaultValue: 'Linear' })}>+ <IconButton+ aria-label={t('controlLayers.gradient.linear', { defaultValue: 'Linear' })}+ icon={<GradientLinearIcon />}+ colorScheme={gradientType === 'linear' ? 'invokeBlue' : 'base'}+ variant="solid"+ onClick={onLinearClick}+ />+ </Tooltip>+ <Tooltip label={t('controlLayers.gradient.radial', { defaultValue: 'Radial' })}>+ <IconButton+ aria-label={t('controlLayers.gradient.radial', { defaultValue: 'Radial' })}+ icon={<GradientRadialIcon />}+ colorScheme={gradientType === 'radial' ? 'invokeBlue' : 'base'}+ variant="solid"+ onClick={onRadialClick}+ />+ </Tooltip>+ </ButtonGroup>+ );+});++ToolGradientModeToggle.displayName = 'ToolGradientModeToggle';diff --git a/invokeai/frontend/web/src/features/controlLayers/components/Toolbar/CanvasToolbar.tsx b/invokeai/frontend/web/src/features/controlLayers/components/Toolbar/CanvasToolbar.tsxindex 979eea95d7..91976cb55d 100644--- a/invokeai/frontend/web/src/features/controlLayers/components/Toolbar/CanvasToolbar.tsx+++ b/invokeai/frontend/web/src/features/controlLayers/components/Toolbar/CanvasToolbar.tsx@@ -1,7 +1,9 @@-import { Divider, Flex } from '@invoke-ai/ui-library';+import { Box, Divider, Flex } from '@invoke-ai/ui-library';import { CanvasSettingsPopover } from 'features/controlLayers/components/Settings/CanvasSettingsPopover';import { useToolIsSelected } from 'features/controlLayers/components/Tool/hooks';import { ToolFillColorPicker } from 'features/controlLayers/components/Tool/ToolFillColorPicker';+import { ToolGradientClipToggle } from 'features/controlLayers/components/Tool/ToolGradientClipToggle';+import { ToolGradientModeToggle } from 'features/controlLayers/components/Tool/ToolGradientModeToggle';import { ToolWidthPicker } from 'features/controlLayers/components/Tool/ToolWidthPicker';import { CanvasToolbarFitBboxToLayersButton } from 'features/controlLayers/components/Toolbar/CanvasToolbarFitBboxToLayersButton';import { CanvasToolbarFitBboxToMasksButton } from 'features/controlLayers/components/Toolbar/CanvasToolbarFitBboxToMasksButton';@@ -26,6 +28,7 @@ import { memo, useMemo } from 'react';export const CanvasToolbar = memo(() => {const isBrushSelected = useToolIsSelected('brush');const isEraserSelected = useToolIsSelected('eraser');+ const isGradientSelected = useToolIsSelected('gradient');const showToolWithPicker = useMemo(() => {return isBrushSelected || isEraserSelected;}, [isBrushSelected, isEraserSelected]);@@ -45,6 +48,12 @@ export const CanvasToolbar = memo(() => {<Flex w="full" gap={2} alignItems="center" px={2}><Flex alignItems="center" h="full" flexGrow={1}><ToolFillColorPicker />+ {isGradientSelected && (+ <Box ms={2} mt="-2px" display="flex" alignItems="center" gap={2}>+ <ToolGradientClipToggle />+ <ToolGradientModeToggle />+ </Box>+ )}{showToolWithPicker && <ToolWidthPicker />}</Flex><Flex alignItems="center" h="full">diff --git a/invokeai/frontend/web/src/features/controlLayers/konva/CanvasEntity/CanvasEntityBufferObjectRenderer.ts b/invokeai/frontend/web/src/features/controlLayers/konva/CanvasEntity/CanvasEntityBufferObjectRenderer.tsindex 2dc5bdab26..ef5cee8d89 100644--- a/invokeai/frontend/web/src/features/controlLayers/konva/CanvasEntity/CanvasEntityBufferObjectRenderer.ts+++ b/invokeai/frontend/web/src/features/controlLayers/konva/CanvasEntity/CanvasEntityBufferObjectRenderer.ts@@ -6,6 +6,7 @@ import { CanvasObjectBrushLine } from 'features/controlLayers/konva/CanvasObjectimport { CanvasObjectBrushLineWithPressure } from 'features/controlLayers/konva/CanvasObject/CanvasObjectBrushLineWithPressure';import { CanvasObjectEraserLine } from 'features/controlLayers/konva/CanvasObject/CanvasObjectEraserLine';import { CanvasObjectEraserLineWithPressure } from 'features/controlLayers/konva/CanvasObject/CanvasObjectEraserLineWithPressure';+import { CanvasObjectGradient } from 'features/controlLayers/konva/CanvasObject/CanvasObjectGradient';import { CanvasObjectImage } from 'features/controlLayers/konva/CanvasObject/CanvasObjectImage';import { CanvasObjectRect } from 'features/controlLayers/konva/CanvasObject/CanvasObjectRect';import type { AnyObjectRenderer, AnyObjectState } from 'features/controlLayers/konva/CanvasObject/types';@@ -151,6 +152,15 @@ export class CanvasEntityBufferObjectRenderer extends CanvasModuleBase {this.konva.group.add(this.renderer.konva.group);}+ didRender = this.renderer.update(this.state, true);+ } else if (this.state.type === 'gradient') {+ assert(this.renderer instanceof CanvasObjectGradient || !this.renderer);++ if (!this.renderer) {+ this.renderer = new CanvasObjectGradient(this.state, this);+ this.konva.group.add(this.renderer.konva.group);+ }+didRender = this.renderer.update(this.state, true);} else if (this.state.type === 'image') {assert(this.renderer instanceof CanvasObjectImage || !this.renderer);@@ -237,6 +247,9 @@ export class CanvasEntityBufferObjectRenderer extends CanvasModuleBase {case 'rect':this.manager.stateApi.addRect({ entityIdentifier, rect: this.state });break;+ case 'gradient':+ this.manager.stateApi.addGradient({ entityIdentifier, gradient: this.state });+ break;}}diff --git a/invokeai/frontend/web/src/features/controlLayers/konva/CanvasEntity/CanvasEntityObjectRenderer.ts b/invokeai/frontend/web/src/features/controlLayers/konva/CanvasEntity/CanvasEntityObjectRenderer.tsindex 114542cdb9..b33a4aaa87 100644--- a/invokeai/frontend/web/src/features/controlLayers/konva/CanvasEntity/CanvasEntityObjectRenderer.ts+++ b/invokeai/frontend/web/src/features/controlLayers/konva/CanvasEntity/CanvasEntityObjectRenderer.ts@@ -8,6 +8,7 @@ import { CanvasObjectBrushLine } from 'features/controlLayers/konva/CanvasObjectimport { CanvasObjectBrushLineWithPressure } from 'features/controlLayers/konva/CanvasObject/CanvasObjectBrushLineWithPressure';import { CanvasObjectEraserLine } from 'features/controlLayers/konva/CanvasObject/CanvasObjectEraserLine';import { CanvasObjectEraserLineWithPressure } from 'features/controlLayers/konva/CanvasObject/CanvasObjectEraserLineWithPressure';+import { CanvasObjectGradient } from 'features/controlLayers/konva/CanvasObject/CanvasObjectGradient';import { CanvasObjectImage } from 'features/controlLayers/konva/CanvasObject/CanvasObjectImage';import { CanvasObjectRect } from 'features/controlLayers/konva/CanvasObject/CanvasObjectRect';import type { AnyObjectRenderer, AnyObjectState } from 'features/controlLayers/konva/CanvasObject/types';@@ -400,6 +401,16 @@ export class CanvasEntityObjectRenderer extends CanvasModuleBase {this.konva.objectGroup.add(renderer.konva.group);}+ didRender = renderer.update(objectState, force || isFirstRender);+ } else if (objectState.type === 'gradient') {+ assert(renderer instanceof CanvasObjectGradient || !renderer);++ if (!renderer) {+ renderer = new CanvasObjectGradient(objectState, this);+ this.renderers.set(renderer.id, renderer);+ this.konva.objectGroup.add(renderer.konva.group);+ }+didRender = renderer.update(objectState, force || isFirstRender);} else if (objectState.type === 'image') {assert(renderer instanceof CanvasObjectImage || !renderer);diff --git a/invokeai/frontend/web/src/features/controlLayers/konva/CanvasObject/CanvasObjectGradient.ts b/invokeai/frontend/web/src/features/controlLayers/konva/CanvasObject/CanvasObjectGradient.tsnew file mode 100644index 0000000000..3dfb281c66--- /dev/null+++ b/invokeai/frontend/web/src/features/controlLayers/konva/CanvasObject/CanvasObjectGradient.ts@@ -0,0 +1,149 @@+import { rgbaColorToString } from 'common/util/colorCodeTransformers';+import { deepClone } from 'common/util/deepClone';+import type { CanvasEntityBufferObjectRenderer } from 'features/controlLayers/konva/CanvasEntity/CanvasEntityBufferObjectRenderer';+import type { CanvasEntityObjectRenderer } from 'features/controlLayers/konva/CanvasEntity/CanvasEntityObjectRenderer';+import type { CanvasManager } from 'features/controlLayers/konva/CanvasManager';+import { CanvasModuleBase } from 'features/controlLayers/konva/CanvasModuleBase';+import type { CanvasGradientState } from 'features/controlLayers/store/types';+import Konva from 'konva';+import type { Logger } from 'roarr';++export class CanvasObjectGradient extends CanvasModuleBase {+ readonly type = 'object_gradient';+ readonly id: string;+ readonly path: string[];+ readonly parent: CanvasEntityObjectRenderer | CanvasEntityBufferObjectRenderer;+ readonly manager: CanvasManager;+ readonly log: Logger;++ state: CanvasGradientState;+ konva: {+ group: Konva.Group;+ rect: Konva.Rect;+ };+ isFirstRender: boolean = false;++ constructor(state: CanvasGradientState, parent: CanvasEntityObjectRenderer | CanvasEntityBufferObjectRenderer) {+ super();+ this.id = state.id;+ this.parent = parent;+ this.manager = parent.manager;+ this.path = this.manager.buildPath(this);+ this.log = this.manager.buildLogger(this);++ this.log.debug({ state }, 'Creating module');++ this.konva = {+ group: new Konva.Group({ name: `${this.type}:group`, listening: false }),+ rect: new Konva.Rect({ name: `${this.type}:rect`, listening: false, perfectDrawEnabled: false }),+ };+ this.konva.group.add(this.konva.rect);+ this.state = state;+ }++ update(state: CanvasGradientState, force = false): boolean {+ if (force || this.state !== state) {+ this.isFirstRender = false;++ const { rect, fgColor, bgColor } = state;+ const fg = rgbaColorToString(fgColor);+ const bg = rgbaColorToString(bgColor);++ this.log.trace({ state }, 'Updating gradient');+ this.konva.rect.setAttrs({+ x: rect.x,+ y: rect.y,+ width: rect.width,+ height: rect.height,+ });++ this.konva.group.clipFunc((ctx) => {+ ctx.beginPath();+ ctx.rect(state.bboxRect.x, state.bboxRect.y, state.bboxRect.width, state.bboxRect.height);+ ctx.clip();+ if (state.clipEnabled) {+ ctx.beginPath();+ if (state.gradientType === 'linear') {+ const startX = state.rect.x + state.start.x;+ const startY = state.rect.y + state.start.y;+ const endX = state.rect.x + state.end.x;+ const endY = state.rect.y + state.end.y;+ const dirX = Math.cos(state.clipAngle);+ const dirY = Math.sin(state.clipAngle);+ const perpX = -dirY;+ const perpY = dirX;+ const clipExtent = Math.max(Math.hypot(state.bboxRect.width, state.bboxRect.height) * 2, 1);+ const drawHalfPlane = (originX: number, originY: number, dirSign: number) => {+ const dX = dirX * dirSign;+ const dY = dirY * dirSign;+ const p1x = originX + perpX * clipExtent;+ const p1y = originY + perpY * clipExtent;+ const p2x = originX - perpX * clipExtent;+ const p2y = originY - perpY * clipExtent;+ const p3x = p2x + dX * clipExtent;+ const p3y = p2y + dY * clipExtent;+ const p4x = p1x + dX * clipExtent;+ const p4y = p1y + dY * clipExtent;+ ctx.moveTo(p1x, p1y);+ ctx.lineTo(p2x, p2y);+ ctx.lineTo(p3x, p3y);+ ctx.lineTo(p4x, p4y);+ ctx.closePath();+ };+ drawHalfPlane(startX, startY, 1);+ ctx.clip();+ ctx.beginPath();+ drawHalfPlane(endX, endY, -1);+ } else {+ ctx.arc(state.clipCenter.x, state.clipCenter.y, state.clipRadius, 0, Math.PI * 2);+ }+ ctx.clip();+ }+ });++ if (state.gradientType === 'linear') {+ this.konva.rect.setAttrs({+ fillPriority: 'linear-gradient',+ fillLinearGradientStartPoint: { x: state.start.x, y: state.start.y },+ fillLinearGradientEndPoint: { x: state.end.x, y: state.end.y },+ fillLinearGradientColorStops: [0, fg, 1, bg],+ });+ } else {+ this.konva.rect.setAttrs({+ fillPriority: 'radial-gradient',+ fillRadialGradientStartPoint: { x: state.center.x, y: state.center.y },+ fillRadialGradientEndPoint: { x: state.center.x, y: state.center.y },+ fillRadialGradientStartRadius: 0,+ fillRadialGradientEndRadius: state.radius,+ fillRadialGradientColorStops: [0, fg, 1, bg],+ });+ }++ this.state = state;+ return true;+ }++ return false;+ }++ setVisibility(isVisible: boolean): void {+ this.log.trace({ isVisible }, 'Setting gradient visibility');+ this.konva.group.visible(isVisible);+ }++ destroy = () => {+ this.log.debug('Destroying module');+ this.konva.group.destroy();+ };++ repr = () => {+ return {+ id: this.id,+ type: this.type,+ path: this.path,+ parent: this.parent.id,+ isFirstRender: this.isFirstRender,+ state: deepClone(this.state),+ };+ };+}diff --git a/invokeai/frontend/web/src/features/controlLayers/konva/CanvasObject/types.ts b/invokeai/frontend/web/src/features/controlLayers/konva/CanvasObject/types.tsindex eb17bf7e13..31a2bfee07 100644--- a/invokeai/frontend/web/src/features/controlLayers/konva/CanvasObject/types.ts+++ b/invokeai/frontend/web/src/features/controlLayers/konva/CanvasObject/types.ts@@ -2,6 +2,7 @@ import type { CanvasObjectBrushLine } from 'features/controlLayers/konva/CanvasOimport type { CanvasObjectBrushLineWithPressure } from 'features/controlLayers/konva/CanvasObject/CanvasObjectBrushLineWithPressure';import type { CanvasObjectEraserLine } from 'features/controlLayers/konva/CanvasObject/CanvasObjectEraserLine';import type { CanvasObjectEraserLineWithPressure } from 'features/controlLayers/konva/CanvasObject/CanvasObjectEraserLineWithPressure';+import type { CanvasObjectGradient } from 'features/controlLayers/konva/CanvasObject/CanvasObjectGradient';import type { CanvasObjectImage } from 'features/controlLayers/konva/CanvasObject/CanvasObjectImage';import type { CanvasObjectRect } from 'features/controlLayers/konva/CanvasObject/CanvasObjectRect';import type {@@ -9,6 +10,7 @@ import type {CanvasBrushLineWithPressureState,CanvasEraserLineState,CanvasEraserLineWithPressureState,+ CanvasGradientState,CanvasImageState,CanvasRectState,} from 'features/controlLayers/store/types';@@ -23,7 +25,9 @@ export type AnyObjectRenderer =| CanvasObjectEraserLine| CanvasObjectEraserLineWithPressure| CanvasObjectRect- | CanvasObjectImage; /**+ | CanvasObjectImage+ | CanvasObjectGradient;+/*** Union of all object states.*/export type AnyObjectState =@@ -32,4 +36,5 @@ export type AnyObjectState =| CanvasEraserLineState| CanvasEraserLineWithPressureState| CanvasImageState- | CanvasRectState;+ | CanvasRectState+ | CanvasGradientState;diff --git a/invokeai/frontend/web/src/features/controlLayers/konva/CanvasStateApiModule.ts b/invokeai/frontend/web/src/features/controlLayers/konva/CanvasStateApiModule.tsindex dc2c0b1504..e00ade1f8b 100644--- a/invokeai/frontend/web/src/features/controlLayers/konva/CanvasStateApiModule.ts+++ b/invokeai/frontend/web/src/features/controlLayers/konva/CanvasStateApiModule.ts@@ -20,6 +20,7 @@ import {controlLayerAdded,entityBrushLineAdded,entityEraserLineAdded,+ entityGradientAdded,entityMovedBy,entityMovedTo,entityRasterized,@@ -40,6 +41,7 @@ import type {CanvasState,EntityBrushLineAddedPayload,EntityEraserLineAddedPayload,+ EntityGradientAddedPayload,EntityIdentifierPayload,EntityMovedByPayload,EntityMovedToPayload,@@ -173,6 +175,13 @@ export class CanvasStateApiModule extends CanvasModuleBase {this.store.dispatch(entityRectAdded(arg));};+ /**+ * Adds a gradient to an entity, pushing state to redux.+ */+ addGradient = (arg: EntityGradientAddedPayload) => {+ this.store.dispatch(entityGradientAdded(arg));+ };+/*** Adds a raster layer to the canvas, pushing state to redux.*/diff --git a/invokeai/frontend/web/src/features/controlLayers/konva/CanvasTool/CanvasGradientToolModule.ts b/invokeai/frontend/web/src/features/controlLayers/konva/CanvasTool/CanvasGradientToolModule.tsnew file mode 100644index 0000000000..745a541735--- /dev/null+++ b/invokeai/frontend/web/src/features/controlLayers/konva/CanvasTool/CanvasGradientToolModule.ts@@ -0,0 +1,219 @@+import type { CanvasManager } from 'features/controlLayers/konva/CanvasManager';+import { CanvasModuleBase } from 'features/controlLayers/konva/CanvasModuleBase';+import type { CanvasToolModule } from 'features/controlLayers/konva/CanvasTool/CanvasToolModule';+import { getPrefixedId, offsetCoord } from 'features/controlLayers/konva/util';+import type { KonvaEventObject } from 'konva/lib/Node';+import type { Logger } from 'roarr';++export class CanvasGradientToolModule extends CanvasModuleBase {+ readonly type = 'gradient_tool';+ readonly id: string;+ readonly path: string[];+ readonly parent: CanvasToolModule;+ readonly manager: CanvasManager;+ readonly log: Logger;++ private startPoint: { x: number; y: number } | null = null;+ private lastPoint: { x: number; y: number } | null = null;+ private gradientId: string | null = null;++ constructor(parent: CanvasToolModule) {+ super();+ this.id = getPrefixedId(this.type);+ this.parent = parent;+ this.manager = this.parent.manager;+ this.path = this.manager.buildPath(this);+ this.log = this.manager.buildLogger(this);++ this.log.debug('Creating module');+ }++ syncCursorStyle = () => {+ const selectedEntity = this.manager.stateApi.getSelectedEntityAdapter();+ if (!selectedEntity || selectedEntity.state.type !== 'raster_layer') {+ this.manager.stage.setCursor('not-allowed');+ return;+ }+ this.manager.stage.setCursor('crosshair');+ };++ onStagePointerDown = async (_e: KonvaEventObject<PointerEvent>) => {+ const cursorPos = this.parent.$cursorPos.get();+ const isPrimaryPointerDown = this.parent.$isPrimaryPointerDown.get();+ const selectedEntity = this.manager.stateApi.getSelectedEntityAdapter();++ if (!cursorPos || !isPrimaryPointerDown || !selectedEntity || selectedEntity.state.type !== 'raster_layer') {+ return;+ }++ if (selectedEntity.bufferRenderer.hasBuffer()) {+ selectedEntity.bufferRenderer.commitBuffer();+ }++ const normalizedPoint = offsetCoord(cursorPos.relative, selectedEntity.state.position);+ this.startPoint = normalizedPoint;+ this.lastPoint = normalizedPoint;+ this.gradientId = getPrefixedId('gradient');++ await this.updateGradientBuffer(normalizedPoint, normalizedPoint);+ };++ onStagePointerMove = async (_e: KonvaEventObject<PointerEvent>) => {+ const cursorPos = this.parent.$cursorPos.get();++ if (!cursorPos || !this.parent.$isPrimaryPointerDown.get()) {+ return;+ }++ const selectedEntity = this.manager.stateApi.getSelectedEntityAdapter();++ if (!selectedEntity || selectedEntity.state.type !== 'raster_layer') {+ return;+ }++ const bufferState = selectedEntity.bufferRenderer.state;+ if (!bufferState || bufferState.type !== 'gradient' || !this.startPoint) {+ return;+ }++ const normalizedPoint = offsetCoord(cursorPos.relative, selectedEntity.state.position);+ this.lastPoint = normalizedPoint;+ await this.updateGradientBuffer(this.startPoint, normalizedPoint);+ };++ onStagePointerUp = (_e: KonvaEventObject<PointerEvent>) => {+ const selectedEntity = this.manager.stateApi.getSelectedEntityAdapter();+ if (!selectedEntity) {+ this.resetState();+ return;+ }++ const shouldCommit = this.startPoint && this.lastPoint && this.getRadius(this.startPoint, this.lastPoint) > 1;+ if (selectedEntity.bufferRenderer.state?.type === 'gradient' && selectedEntity.bufferRenderer.hasBuffer()) {+ if (shouldCommit) {+ selectedEntity.bufferRenderer.commitBuffer();+ } else {+ selectedEntity.bufferRenderer.clearBuffer();+ }+ }++ this.resetState();+ };++ private resetState = () => {+ this.startPoint = null;+ this.lastPoint = null;+ this.gradientId = null;+ };++ private getRadius = (start: { x: number; y: number }, end: { x: number; y: number }) => {+ return Math.hypot(end.x - start.x, end.y - start.y);+ };++ private updateGradientBuffer = async (start: { x: number; y: number }, end: { x: number; y: number }) => {+ const selectedEntity = this.manager.stateApi.getSelectedEntityAdapter();+ if (!selectedEntity || selectedEntity.state.type !== 'raster_layer') {+ return;+ }++ const settings = this.manager.stateApi.getSettings();+ const { rect: bboxRect } = this.manager.stateApi.getBbox();+ const bboxInLayer = {+ x: bboxRect.x - selectedEntity.state.position.x,+ y: bboxRect.y - selectedEntity.state.position.y,+ width: bboxRect.width,+ height: bboxRect.height,+ };+ const radius = this.getRadius(start, end);+ const angle = Math.atan2(end.y - start.y, end.x - start.x);+ let rect = {+ x: start.x - radius,+ y: start.y - radius,+ width: radius * 2,+ height: radius * 2,+ };++ if (settings.gradientType === 'linear') {+ const bboxCenter = {+ x: bboxInLayer.x + bboxInLayer.width / 2,+ y: bboxInLayer.y + bboxInLayer.height / 2,+ };+ const cos = Math.cos(angle);+ const sin = Math.sin(angle);+ const halfWidth = (Math.abs(bboxInLayer.width * cos) + Math.abs(bboxInLayer.height * sin)) / 2;+ const halfHeight = (Math.abs(bboxInLayer.width * sin) + Math.abs(bboxInLayer.height * cos)) / 2;+ rect = {+ x: bboxCenter.x - halfWidth,+ y: bboxCenter.y - halfHeight,+ width: Math.max(halfWidth * 2, 1),+ height: Math.max(halfHeight * 2, 1),+ };+ }++ const startInRect = offsetCoord(start, { x: rect.x, y: rect.y });+ const endInRect = offsetCoord(end, { x: rect.x, y: rect.y });++ const id = this.gradientId ?? getPrefixedId('gradient');+ if (!this.gradientId) {+ this.gradientId = id;+ }++ const activeColor = settings.activeColor === 'bgColor' ? settings.bgColor : settings.fgColor;+ const inactiveColor = settings.activeColor === 'bgColor' ? settings.fgColor : settings.bgColor;+ const clipEnabled = settings.gradientClipEnabled;++ if (settings.gradientType === 'radial') {+ let radialRect = rect;+ let radialCenter = startInRect;+ let radialRadius = Math.max(1, radius);+ if (!clipEnabled) {+ radialRect = bboxInLayer;+ radialCenter = offsetCoord(start, { x: radialRect.x, y: radialRect.y });+ }+ await selectedEntity.bufferRenderer.setBuffer({+ id,+ type: 'gradient',+ gradientType: 'radial',+ rect: radialRect,+ center: radialCenter,+ radius: radialRadius,+ clipCenter: start,+ clipRadius: Math.max(1, radius),+ clipEnabled,+ bboxRect: bboxInLayer,+ fgColor: activeColor,+ bgColor: inactiveColor,+ });+ } else {+ const endPoint = {+ x: endInRect.x === startInRect.x && endInRect.y === startInRect.y ? endInRect.x + 1 : endInRect.x,+ y: endInRect.x === startInRect.x && endInRect.y === startInRect.y ? endInRect.y : endInRect.y,+ };+ await selectedEntity.bufferRenderer.setBuffer({+ id,+ type: 'gradient',+ gradientType: 'linear',+ rect,+ start: startInRect,+ end: endPoint,+ clipCenter: start,+ clipRadius: Math.max(1, radius),+ clipAngle: angle,+ clipEnabled,+ bboxRect: bboxInLayer,+ fgColor: activeColor,+ bgColor: inactiveColor,+ });+ }+ };++ repr = () => {+ return {+ id: this.id,+ type: this.type,+ path: this.path,+ startPoint: this.startPoint,+ gradientId: this.gradientId,+ };+ };+}diff --git a/invokeai/frontend/web/src/features/controlLayers/konva/CanvasTool/CanvasToolModule.ts b/invokeai/frontend/web/src/features/controlLayers/konva/CanvasTool/CanvasToolModule.tsindex b9b8adae9b..1477f1b097 100644--- a/invokeai/frontend/web/src/features/controlLayers/konva/CanvasTool/CanvasToolModule.ts+++ b/invokeai/frontend/web/src/features/controlLayers/konva/CanvasTool/CanvasToolModule.ts@@ -4,6 +4,7 @@ import { CanvasBboxToolModule } from 'features/controlLayers/konva/CanvasTool/Caimport { CanvasBrushToolModule } from 'features/controlLayers/konva/CanvasTool/CanvasBrushToolModule';import { CanvasColorPickerToolModule } from 'features/controlLayers/konva/CanvasTool/CanvasColorPickerToolModule';import { CanvasEraserToolModule } from 'features/controlLayers/konva/CanvasTool/CanvasEraserToolModule';+import { CanvasGradientToolModule } from 'features/controlLayers/konva/CanvasTool/CanvasGradientToolModule';import { CanvasMoveToolModule } from 'features/controlLayers/konva/CanvasTool/CanvasMoveToolModule';import { CanvasRectToolModule } from 'features/controlLayers/konva/CanvasTool/CanvasRectToolModule';import { CanvasViewToolModule } from 'features/controlLayers/konva/CanvasTool/CanvasViewToolModule';@@ -60,6 +61,7 @@ export class CanvasToolModule extends CanvasModuleBase {brush: CanvasBrushToolModule;eraser: CanvasEraserToolModule;rect: CanvasRectToolModule;+ gradient: CanvasGradientToolModule;colorPicker: CanvasColorPickerToolModule;bbox: CanvasBboxToolModule;view: CanvasViewToolModule;@@ -117,6 +119,7 @@ export class CanvasToolModule extends CanvasModuleBase {brush: new CanvasBrushToolModule(this),eraser: new CanvasEraserToolModule(this),rect: new CanvasRectToolModule(this),+ gradient: new CanvasGradientToolModule(this),colorPicker: new CanvasColorPickerToolModule(this),bbox: new CanvasBboxToolModule(this),view: new CanvasViewToolModule(this),@@ -194,6 +197,8 @@ export class CanvasToolModule extends CanvasModuleBase {this.tools.move.syncCursorStyle();} else if (tool === 'rect') {this.tools.rect.syncCursorStyle();+ } else if (tool === 'gradient') {+ this.tools.gradient.syncCursorStyle();}} else if (this.manager.stateApi.getRenderedEntityCount() === 0) {stage.setCursor('not-allowed');@@ -336,7 +341,11 @@ export class CanvasToolModule extends CanvasModuleBase {const tool = this.$tool.get();const selectedEntity = this.manager.stateApi.getSelectedEntityAdapter();- if (selectedEntity?.bufferRenderer.state?.type !== 'rect' && selectedEntity?.bufferRenderer.hasBuffer()) {+ if (+ selectedEntity?.bufferRenderer.state?.type !== 'rect' &&+ selectedEntity?.bufferRenderer.state?.type !== 'gradient' &&+ selectedEntity?.bufferRenderer.hasBuffer()+ ) {selectedEntity.bufferRenderer.commitBuffer();return;}@@ -375,6 +384,8 @@ export class CanvasToolModule extends CanvasModuleBase {await this.tools.eraser.onStagePointerDown(e);} else if (tool === 'rect') {await this.tools.rect.onStagePointerDown(e);+ } else if (tool === 'gradient') {+ await this.tools.gradient.onStagePointerDown(e);}} finally {this.render();@@ -405,6 +416,8 @@ export class CanvasToolModule extends CanvasModuleBase {this.tools.eraser.onStagePointerUp(e);} else if (tool === 'rect') {this.tools.rect.onStagePointerUp(e);+ } else if (tool === 'gradient') {+ this.tools.gradient.onStagePointerUp(e);}} finally {this.render();@@ -436,6 +449,8 @@ export class CanvasToolModule extends CanvasModuleBase {await this.tools.eraser.onStagePointerMove(e);} else if (tool === 'rect') {await this.tools.rect.onStagePointerMove(e);+ } else if (tool === 'gradient') {+ await this.tools.gradient.onStagePointerMove(e);} else {this.manager.stateApi.getSelectedEntityAdapter()?.bufferRenderer.clearBuffer();}@@ -462,6 +477,7 @@ export class CanvasToolModule extends CanvasModuleBase {if (selectedEntity &&selectedEntity.bufferRenderer.state?.type !== 'rect' &&+ selectedEntity.bufferRenderer.state?.type !== 'gradient' &&selectedEntity.bufferRenderer.hasBuffer()) {selectedEntity.bufferRenderer.commitBuffer();@@ -629,6 +645,7 @@ export class CanvasToolModule extends CanvasModuleBase {eraser: this.tools.eraser.repr(),colorPicker: this.tools.colorPicker.repr(),rect: this.tools.rect.repr(),+ gradient: this.tools.gradient.repr(),bbox: this.tools.bbox.repr(),view: this.tools.view.repr(),move: this.tools.move.repr(),diff --git a/invokeai/frontend/web/src/features/controlLayers/store/canvasSettingsSlice.ts b/invokeai/frontend/web/src/features/controlLayers/store/canvasSettingsSlice.tsindex f76654d4c8..91428b4521 100644--- a/invokeai/frontend/web/src/features/controlLayers/store/canvasSettingsSlice.ts+++ b/invokeai/frontend/web/src/features/controlLayers/store/canvasSettingsSlice.ts@@ -12,6 +12,8 @@ export type AutoSwitchMode = z.infer<typeof zAutoSwitchMode>;const zTransformSmoothingMode = z.enum(['bilinear', 'bicubic', 'hamming', 'lanczos']);export type TransformSmoothingMode = z.infer<typeof zTransformSmoothingMode>;+const zGradientType = z.enum(['linear', 'radial']);+const zCanvasSettingsState = z.object({/*** Whether to show HUD (Heads-Up Display) on the canvas.@@ -108,6 +110,14 @@ const zCanvasSettingsState = z.object({* Whether the fill color picker UI is pinned (persistently shown in the canvas overlay).*/fillColorPickerPinned: z.boolean(),+ /**+ * The gradient tool type.+ */+ gradientType: zGradientType.default('linear'),+ /**+ * Whether the gradient tool clips to the drag gesture.+ */+ gradientClipEnabled: z.boolean().default(true),});type CanvasSettingsState = z.infer<typeof zCanvasSettingsState>;@@ -136,6 +146,8 @@ const getInitialState = (): CanvasSettingsState => ({fillColorPickerPinned: false,transformSmoothingEnabled: false,transformSmoothingMode: 'bicubic',+ gradientType: 'linear',+ gradientClipEnabled: true,});const slice = createSlice({@@ -227,6 +239,12 @@ const slice = createSlice({settingsFillColorPickerPinnedSet: (state, action: PayloadAction<boolean>) => {state.fillColorPickerPinned = action.payload;},+ settingsGradientTypeChanged: (state, action: PayloadAction<CanvasSettingsState['gradientType']>) => {+ state.gradientType = action.payload;+ },+ settingsGradientClipToggled: (state) => {+ state.gradientClipEnabled = !state.gradientClipEnabled;+ },},});@@ -256,6 +274,8 @@ export const {settingsTransformSmoothingModeChanged,settingsStagingAreaAutoSwitchChanged,settingsFillColorPickerPinnedSet,+ settingsGradientTypeChanged,+ settingsGradientClipToggled,} = slice.actions;export const canvasSettingsSliceConfig: SliceConfig<typeof slice> = {@@ -295,3 +315,5 @@ export const selectTransformSmoothingEnabled = createCanvasSettingsSelector((settings) => settings.transformSmoothingEnabled);export const selectTransformSmoothingMode = createCanvasSettingsSelector((settings) => settings.transformSmoothingMode);+export const selectGradientType = createCanvasSettingsSelector((settings) => settings.gradientType);+export const selectGradientClipEnabled = createCanvasSettingsSelector((settings) => settings.gradientClipEnabled);diff --git a/invokeai/frontend/web/src/features/controlLayers/store/canvasSlice.ts b/invokeai/frontend/web/src/features/controlLayers/store/canvasSlice.tsindex 868e2aa2b7..126b61bcc2 100644--- a/invokeai/frontend/web/src/features/controlLayers/store/canvasSlice.ts+++ b/invokeai/frontend/web/src/features/controlLayers/store/canvasSlice.ts@@ -63,6 +63,7 @@ import type {ControlNetConfig,EntityBrushLineAddedPayload,EntityEraserLineAddedPayload,+ EntityGradientAddedPayload,EntityIdentifierPayload,EntityMovedToPayload,EntityRasterizedPayload,@@ -1510,6 +1511,17 @@ const slice = createSlice({// re-render it (reference equality check). I don't like this behaviour.entity.objects.push({ ...rect });},+ entityGradientAdded: (state, action: PayloadAction<EntityGradientAddedPayload>) => {+ const { entityIdentifier, gradient } = action.payload;+ const entity = selectEntity(state, entityIdentifier);+ if (!entity) {+ return;+ }++ // TODO(psyche): If we add the object without splatting, the renderer will see it as the same object and not+ // re-render it (reference equality check). I don't like this behaviour.+ entity.objects.push({ ...gradient });+ },entityDeleted: (state, action: PayloadAction<EntityIdentifierPayload>) => {const { entityIdentifier } = action.payload;@@ -1738,6 +1750,7 @@ export const {entityBrushLineAdded,entityEraserLineAdded,entityRectAdded,+ entityGradientAdded,// Raster layer adjustmentsrasterLayerAdjustmentsSet,rasterLayerAdjustmentsCancel,@@ -1862,7 +1875,7 @@ export const canvasSliceConfig: SliceConfig<typeof slice> = {},};-const doNotGroupMatcher = isAnyOf(entityBrushLineAdded, entityEraserLineAdded, entityRectAdded);+const doNotGroupMatcher = isAnyOf(entityBrushLineAdded, entityEraserLineAdded, entityRectAdded, entityGradientAdded);// Store rapid actions of the same type at most once every x time.// See: https://github.com/omnidan/redux-undo/blob/master/examples/throttled-drag/util/undoFilter.jsdiff --git a/invokeai/frontend/web/src/features/controlLayers/store/types.ts b/invokeai/frontend/web/src/features/controlLayers/store/types.tsindex 59d6868bb1..ff0e13a6e3 100644--- a/invokeai/frontend/web/src/features/controlLayers/store/types.ts+++ b/invokeai/frontend/web/src/features/controlLayers/store/types.ts@@ -105,7 +105,7 @@ const zIPMethodV2 = z.enum(['full', 'style', 'composition', 'style_strong', 'styexport type IPMethodV2 = z.infer<typeof zIPMethodV2>;export const isIPMethodV2 = (v: unknown): v is IPMethodV2 => zIPMethodV2.safeParse(v).success;-const _zTool = z.enum(['brush', 'eraser', 'move', 'rect', 'view', 'bbox', 'colorPicker']);+const _zTool = z.enum(['brush', 'eraser', 'move', 'rect', 'gradient', 'view', 'bbox', 'colorPicker']);export type Tool = z.infer<typeof _zTool>;const zPoints = z.array(z.number()).refine((points) => points.length % 2 === 0, {@@ -260,6 +260,42 @@ const zCanvasRectState = z.object({});export type CanvasRectState = z.infer<typeof zCanvasRectState>;+// Gradient state includes clip metadata so the tool can optionally clip to drag gesture.+const zCanvasLinearGradientState = z.object({+ id: zId,+ type: z.literal('gradient'),+ gradientType: z.literal('linear'),+ rect: zRect,+ start: zCoordinate,+ end: zCoordinate,+ clipCenter: zCoordinate,+ clipRadius: z.number().min(0),+ clipAngle: z.number(),+ clipEnabled: z.boolean().default(true),+ bboxRect: zRect,+ fgColor: zRgbaColor,+ bgColor: zRgbaColor,+});+const zCanvasRadialGradientState = z.object({+ id: zId,+ type: z.literal('gradient'),+ gradientType: z.literal('radial'),+ rect: zRect,+ center: zCoordinate,+ radius: z.number().min(0),+ clipCenter: zCoordinate,+ clipRadius: z.number().min(0),+ clipEnabled: z.boolean().default(true),+ bboxRect: zRect,+ fgColor: zRgbaColor,+ bgColor: zRgbaColor,+});+const zCanvasGradientState = z.discriminatedUnion('gradientType', [+ zCanvasLinearGradientState,+ zCanvasRadialGradientState,+]);+export type CanvasGradientState = z.infer<typeof zCanvasGradientState>;+const zCanvasImageState = z.object({id: zId,type: z.literal('image'),@@ -275,6 +311,7 @@ const zCanvasObjectState = z.union([zCanvasRectState,zCanvasBrushLineWithPressureState,zCanvasEraserLineWithPressureState,+ zCanvasGradientState,]);export type CanvasObjectState = z.infer<typeof zCanvasObjectState>;@@ -830,6 +867,7 @@ export type EntityEraserLineAddedPayload = EntityIdentifierPayload<{eraserLine: CanvasEraserLineState | CanvasEraserLineWithPressureState;}>;export type EntityRectAddedPayload = EntityIdentifierPayload<{ rect: CanvasRectState }>;+export type EntityGradientAddedPayload = EntityIdentifierPayload<{ gradient: CanvasGradientState }>;export type EntityRasterizedPayload = EntityIdentifierPayload<{imageObject: CanvasImageState;position: Coordinate;