Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

masks layers improved etc

sora846d0f2f6f66
diff --git a/src/App.tsx b/src/App.tsx
index be485ce..4a77516 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -15,6 +15,9 @@ import {
FrameSettings,
ExpressionColor,
LiquifySettings,
+ WandSettings,
+ AdjustmentLayerData,
+ FilterType,
} from './types/editor';
import { applyLiquifyStep, createLiquifySelectionMask, DirtyRect } from './utils/liquifyEngine';
import { PerspectiveRuler, ConstraintAxis } from './types/perspective';
@@ -26,7 +29,21 @@ import {
commitFloatingSelection,
computePolygonBounds,
getCanvasContentBounds,
+ floodSelectWand,
+ expandSelection,
+ contractSelection,
+ featherSelection,
+ invertSelection,
+ selectionToMask,
+ maskToBounds,
+ maskToSvgPath,
} from './utils/selectionUtils';
+import {
+ renderPerspectiveQuad,
+ renderMeshWarp,
+ createDefaultPerspectiveQuad,
+ createDefaultMeshPoints,
+} from './utils/transformEngine';
import { applyScreentone } from './utils/screentoneEngine';
import { applyLayerEffects } from './utils/layerEffectsEngine';
import { useCanvasDrawing } from './hooks/useCanvasDrawing';
@@ -57,6 +74,8 @@ import { ClipboardInviteToast } from './components/ClipboardInviteToast';
import { WebLandingModal } from './components/WebLandingModal';
import { WelcomeScreen } from './components/WelcomeScreen';
import { FirstTimeNameModal } from './components/FirstTimeNameModal';
+import { AdjustmentModal } from './components/AdjustmentModal';
+import { applyFilter } from './utils/filterEngine';
import { saveRecentDocument, RecentDocument } from './utils/recentDocumentsManager';
import {
renderCompleteStroke,
@@ -118,6 +137,11 @@ import {
Lock,
Unlock,
Box,
+ Maximize2,
+ Minimize2,
+ Feather,
+ BoxSelect,
+ X,
} from 'lucide-react';
import { parseSutFile } from './utils/sutParser';
import {
@@ -168,6 +192,21 @@ export function App() {
// Free Transform session state
const [transformSession, setTransformSession] = useState<TransformSession | null>(null);
+ // Magic Wand tool settings
+ const [wandSettings, setWandSettings] = useState<WandSettings>({
+ tolerance: 32,
+ contiguous: true,
+ antiAlias: true,
+ referMode: 'active',
+ });
+ const selectionMaskCanvasRef = useRef<HTMLCanvasElement | null>(null);
+ const selectionPenDrawingRef = useRef<{
+ isDrawing: boolean;
+ lastPt: { x: number; y: number };
+ maskCanvas: HTMLCanvasElement;
+ ctx: CanvasRenderingContext2D;
+ } | null>(null);
+
// Fill tool settings
const [fillSettings, setFillSettings] = useState<FillSettings>({
method: 'refer-all',
@@ -410,6 +449,7 @@ export function App() {
// Layer Management System
const {
layers,
+ setLayers,
activeLayerId,
setActiveLayerId,
activeLayer,
@@ -462,8 +502,77 @@ export function App() {
toggleAlphaLock,
convertLayer,
fillScreentoneSelection,
+ addLayerMask,
+ removeLayerMask,
+ toggleLayerMask,
+ toggleMaskLinked,
+ updateMaskThumbnail,
+ addAdjustmentLayer,
+ updateAdjustmentData,
} = useLayerManager({ dimensions });
+ // Active edit target for painting/erasing ('layer' content vs 'mask')
+ const [activeEditTarget, setActiveEditTarget] = useState<'layer' | 'mask'>('layer');
+
+ // Adjustment Layer Modal state
+ const [adjustmentModalState, setAdjustmentModalState] = useState<{
+ isOpen: boolean;
+ layerId?: string | null;
+ initialType?: 'curves' | 'gradient-map' | 'levels' | 'color-balance';
+ }>({
+ isOpen: false,
+ });
+
+ const handleOpenAdjustmentModal = useCallback(
+ (layerId?: string, initialType: 'curves' | 'gradient-map' | 'levels' | 'color-balance' = 'curves') => {
+ setAdjustmentModalState({
+ isOpen: true,
+ layerId: layerId || null,
+ initialType,
+ });
+ },
+ []
+ );
+
+ const handleApplyAdjustment = useCallback(
+ (type: 'curves' | 'gradient-map' | 'levels' | 'color-balance', data: AdjustmentLayerData) => {
+ if (adjustmentModalState.layerId) {
+ updateAdjustmentData(adjustmentModalState.layerId, data);
+ showToast(`Updated ${data.type} adjustment layer`);
+ } else {
+ addAdjustmentLayer(type, data);
+ showToast(`Created new ${data.type} adjustment layer`);
+ }
+ setAdjustmentModalState({ isOpen: false });
+ },
+ [adjustmentModalState.layerId, updateAdjustmentData, addAdjustmentLayer, showToast]
+ );
+
+ const handleApplyFilter = useCallback(
+ (type: FilterType, params?: any) => {
+ if (!hasOpenDocument || !activeLayer || activeLayer.type !== 'raster' || activeLayer.locked) {
+ showToast('Select an unlocked raster layer to apply filter');
+ return;
+ }
+ const canvas = layerCanvasesRef.current.get(activeLayerId);
+ if (!canvas) return;
+ const ctx = get2DContext(canvas);
+ if (!ctx) return;
+
+ const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ const filtered = applyFilter(imgData, type, params);
+ ctx.putImageData(filtered, 0, 0);
+
+ const isMono = colorMode === 'monochrome' || activeLayer.expressionColor === 'monochrome';
+ const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
+ globalTileGrid.writeImageData(activeLayerId, filtered, 0, 0, targetFormat);
+ globalTileGrid.notifyChange(true);
+ updateLayerThumbnail(activeLayerId, true);
+ showToast(`Filter applied: ${type.replace('-', ' ')}`);
+ },
+ [hasOpenDocument, activeLayer, activeLayerId, layerCanvasesRef, colorMode, updateLayerThumbnail, showToast]
+ );
+
const {
viewportRef,
zoom,
@@ -1066,6 +1175,8 @@ export function App() {
layerSourceCanvasesRef,
layers: hasOpenDocument ? layers : [],
onUpdateLayerThumbnail: updateLayerThumbnail,
+ isMaskMode: activeEditTarget === 'mask',
+ onUpdateMaskThumbnail: updateMaskThumbnail,
draftCanvasRef,
strokeCanvasRef,
onCollabStrokeStart: (strokeId, layerId, bs, t, startPt) => {
@@ -1298,7 +1409,26 @@ export function App() {
const c = get2DContext(target);
if (!c) return;
c.save();
- if (selection.type === 'rect') {
+ if (selection.mask && selection.maskWidth && selection.maskHeight) {
+ const maskCanvas = document.createElement('canvas');
+ maskCanvas.width = target.width;
+ maskCanvas.height = target.height;
+ const mCtx = maskCanvas.getContext('2d');
+ if (mCtx) {
+ const mImg = mCtx.createImageData(target.width, target.height);
+ for (let i = 0; i < selection.mask.length; i++) {
+ mImg.data[i * 4 + 3] = selection.mask[i];
+ }
+ mCtx.putImageData(mImg, 0, 0);
+ if (activeLayerId === 'layer-bg') {
+ c.fillStyle = '#ffffff';
+ c.fillRect(selection.bounds.x, selection.bounds.y, selection.bounds.width, selection.bounds.height);
+ } else {
+ c.globalCompositeOperation = 'destination-out';
+ c.drawImage(maskCanvas, 0, 0);
+ }
+ }
+ } else if (selection.type === 'rect') {
if (activeLayerId === 'layer-bg') {
c.fillStyle = '#ffffff';
c.fillRect(selection.bounds.x, selection.bounds.y, selection.bounds.width, selection.bounds.height);
@@ -1352,17 +1482,34 @@ export function App() {
const c = get2DContext(target);
if (!c) return;
c.save();
- c.fillStyle = primaryColor;
- if (selection.type === 'rect') {
- c.fillRect(selection.bounds.x, selection.bounds.y, selection.bounds.width, selection.bounds.height);
- } else if (selection.type === 'lasso' && selection.polygon && selection.polygon.length >= 3) {
- c.beginPath();
- c.moveTo(selection.polygon[0].x, selection.polygon[0].y);
- for (let i = 1; i < selection.polygon.length; i++) {
- c.lineTo(selection.polygon[i].x, selection.polygon[i].y);
+ if (selection.mask && selection.maskWidth && selection.maskHeight) {
+ const maskCanvas = document.createElement('canvas');
+ maskCanvas.width = target.width;
+ maskCanvas.height = target.height;
+ const mCtx = maskCanvas.getContext('2d');
+ if (mCtx) {
+ mCtx.fillStyle = primaryColor;
+ mCtx.fillRect(0, 0, target.width, target.height);
+ const mImg = mCtx.getImageData(0, 0, target.width, target.height);
+ for (let i = 0; i < selection.mask.length; i++) {
+ mImg.data[i * 4 + 3] = Math.round((mImg.data[i * 4 + 3] * selection.mask[i]) / 255);
+ }
+ mCtx.putImageData(mImg, 0, 0);
+ c.drawImage(maskCanvas, 0, 0);
+ }
+ } else {
+ c.fillStyle = primaryColor;
+ if (selection.type === 'rect') {
+ c.fillRect(selection.bounds.x, selection.bounds.y, selection.bounds.width, selection.bounds.height);
+ } else if (selection.type === 'lasso' && selection.polygon && selection.polygon.length >= 3) {
+ c.beginPath();
+ c.moveTo(selection.polygon[0].x, selection.polygon[0].y);
+ for (let i = 1; i < selection.polygon.length; i++) {
+ c.lineTo(selection.polygon[i].x, selection.polygon[i].y);
+ }
+ c.closePath();
+ c.fill();
}
- c.closePath();
- c.fill();
}
c.restore();
};
@@ -1386,15 +1533,131 @@ export function App() {
);
}, [selection, getActiveCanvas, primaryColor, activeLayerId, activeLayer, layerSourceCanvasesRef, dimensions.dpi, updateLayerThumbnail, pushHistoryStep]);
+ const handleExpandSelection = useCallback(
+ (pixels = 5) => {
+ if (!selection) return;
+ const w = dimensions.width;
+ const h = dimensions.height;
+ const currentMask = selectionToMask(selection, w, h);
+ const expanded = expandSelection(currentMask, w, h, pixels);
+ const b = maskToBounds(expanded, w, h);
+ if (!b) {
+ setSelection(null);
+ return;
+ }
+ const svg = maskToSvgPath(expanded, w, h);
+ setSelection({
+ type: 'mask',
+ bounds: b,
+ mask: expanded,
+ maskWidth: w,
+ maskHeight: h,
+ svgPath: svg,
+ });
+ showToast(`Expanded Selection (+${pixels}px)`);
+ },
+ [selection, dimensions, showToast]
+ );
+
+ const handleContractSelection = useCallback(
+ (pixels = 5) => {
+ if (!selection) return;
+ const w = dimensions.width;
+ const h = dimensions.height;
+ const currentMask = selectionToMask(selection, w, h);
+ const contracted = contractSelection(currentMask, w, h, pixels);
+ const b = maskToBounds(contracted, w, h);
+ if (!b) {
+ setSelection(null);
+ showToast('Selection contracted to empty');
+ return;
+ }
+ const svg = maskToSvgPath(contracted, w, h);
+ setSelection({
+ type: 'mask',
+ bounds: b,
+ mask: contracted,
+ maskWidth: w,
+ maskHeight: h,
+ svgPath: svg,
+ });
+ showToast(`Contracted Selection (-${pixels}px)`);
+ },
+ [selection, dimensions, showToast]
+ );
+
+ const handleFeatherSelection = useCallback(
+ (radius = 5) => {
+ if (!selection) return;
+ const w = dimensions.width;
+ const h = dimensions.height;
+ const currentMask = selectionToMask(selection, w, h);
+ const feathered = featherSelection(currentMask, w, h, radius);
+ const b = maskToBounds(feathered, w, h);
+ if (!b) {
+ setSelection(null);
+ return;
+ }
+ const svg = maskToSvgPath(feathered, w, h);
+ setSelection({
+ type: 'mask',
+ bounds: b,
+ mask: feathered,
+ maskWidth: w,
+ maskHeight: h,
+ svgPath: svg,
+ });
+ showToast(`Feathered Selection (${radius}px)`);
+ },
+ [selection, dimensions, showToast]
+ );
+
const handleInvertSelection = useCallback(() => {
- if (!selection) return;
+ const w = dimensions.width;
+ const h = dimensions.height;
+ const currentMask = selection ? selectionToMask(selection, w, h) : new Uint8Array(w * h);
+ const inverted = invertSelection(currentMask, w, h);
+ const b = maskToBounds(inverted, w, h);
+ if (!b) {
+ setSelection(null);
+ showToast('Inverted Selection (Empty)');
+ return;
+ }
+ const svg = maskToSvgPath(inverted, w, h);
setSelection({
- type: 'rect',
- bounds: { x: 0, y: 0, width: dimensions.width, height: dimensions.height },
+ type: 'mask',
+ bounds: b,
+ mask: inverted,
+ maskWidth: w,
+ maskHeight: h,
+ svgPath: svg,
});
showToast('Inverted Selection');
}, [selection, dimensions, showToast]);
+ const handleSelectAll = useCallback(() => {
+ const w = dimensions.width;
+ const h = dimensions.height;
+ const mask = new Uint8Array(w * h);
+ mask.fill(255);
+ const svg = `M 0 0 H ${w} V ${h} H 0 Z`;
+ setSelection({
+ type: 'rect',
+ bounds: { x: 0, y: 0, width: w, height: h },
+ mask,
+ maskWidth: w,
+ maskHeight: h,
+ svgPath: svg,
+ });
+ showToast('Selected All (Ctrl+A)');
+ }, [dimensions, showToast]);
+
+ const handleToggleReferenceLayer = useCallback((layerId: string) => {
+ setLayers((prev) =>
+ prev.map((l) => (l.id === layerId ? { ...l, isReference: !l.isReference } : l))
+ );
+ }, [setLayers]);
+
const getTonalLabel = useCallback((type: TonalCorrectionType) => {
switch (type) {
case 'brightness-contrast':
@@ -1780,6 +2043,7 @@ export function App() {
updateLayerThumbnail(activeLayerId, true);
}
+ const quad = createDefaultPerspectiveQuad(floatX, floatY, floatCanvas.width, floatCanvas.height, 0);
setTransformSession({
active: true,
layerId: activeLayerId,
@@ -1794,6 +2058,11 @@ export function App() {
flipH: false,
flipV: false,
isSelection: true,
+ mode: 'affine',
+ perspectiveQuad: quad,
+ meshCols: 4,
+ meshRows: 4,
+ meshPoints: createDefaultMeshPoints(quad, 4, 4),
});
setSelection(null);
} else {
@@ -1840,6 +2109,7 @@ export function App() {
updateLayerThumbnail(activeLayerId, true);
+ const quad = createDefaultPerspectiveQuad(b.x, b.y, b.width, b.height, 0);
setTransformSession({
active: true,
layerId: activeLayerId,
@@ -1854,6 +2124,11 @@ export function App() {
flipH: false,
flipV: false,
isSelection: false,
+ mode: 'affine',
+ perspectiveQuad: quad,
+ meshCols: 4,
+ meshRows: 4,
+ meshPoints: createDefaultMeshPoints(quad, 4, 4),
});
}
setTool('transform');
@@ -1866,52 +2141,49 @@ export function App() {
const ctx = get2DContext(canvas);
if (!ctx) return;
- ctx.save();
- const cx = transformSession.x + transformSession.width / 2;
- const cy = transformSession.y + transformSession.height / 2;
- ctx.translate(cx, cy);
- ctx.rotate((transformSession.rotation * Math.PI) / 180);
- ctx.scale(transformSession.flipH ? -1 : 1, transformSession.flipV ? -1 : 1);
- ctx.drawImage(
- transformSession.sourceCanvas,
- -transformSession.width / 2,
- -transformSession.height / 2,
- transformSession.width,
- transformSession.height
- );
- ctx.restore();
-
const sourceCanvas = layerSourceCanvasesRef.current?.get(transformSession.layerId);
- if (sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- if (sCtx) {
- sCtx.save();
- sCtx.translate(cx, cy);
- sCtx.rotate((transformSession.rotation * Math.PI) / 180);
- sCtx.scale(transformSession.flipH ? -1 : 1, transformSession.flipV ? -1 : 1);
- sCtx.drawImage(
+
+ const drawTransformed = (targetCtx: CanvasRenderingContext2D) => {
+ targetCtx.save();
+ if (transformSession.mode === 'perspective' && transformSession.perspectiveQuad) {
+ renderPerspectiveQuad(targetCtx, transformSession.sourceCanvas, transformSession.perspectiveQuad, 24);
+ } else if (transformSession.mode === 'mesh' && transformSession.meshPoints) {
+ renderMeshWarp(targetCtx, transformSession.sourceCanvas, transformSession.meshPoints, 6);
+ } else {
+ const cx = transformSession.x + transformSession.width / 2;
+ const cy = transformSession.y + transformSession.height / 2;
+ targetCtx.translate(cx, cy);
+ targetCtx.rotate((transformSession.rotation * Math.PI) / 180);
+ targetCtx.scale(transformSession.flipH ? -1 : 1, transformSession.flipV ? -1 : 1);
+ targetCtx.drawImage(
transformSession.sourceCanvas,
-transformSession.width / 2,
-transformSession.height / 2,
transformSession.width,
transformSession.height
);
- sCtx.restore();
}
+ targetCtx.restore();
+ };
- const layer = layers.find((l) => l.id === transformSession.layerId);
- if (layer?.toneEnabled) {
- applyScreentone(
- sourceCanvas,
- canvas,
- {
- frequency: layer.toneFrequency ?? 60,
- angle: layer.toneAngle ?? 45,
- dotShape: layer.toneDotShape ?? 'circle',
- dpi: dimensions.dpi ?? 600,
- }
- );
- }
+ drawTransformed(ctx);
+ if (sourceCanvas) {
+ const sCtx = get2DContext(sourceCanvas);
+ if (sCtx) drawTransformed(sCtx);
+ }
+
+ const layer = layers.find((l) => l.id === transformSession.layerId);
+ if (layer?.toneEnabled && sourceCanvas) {
+ applyScreentone(
+ sourceCanvas,
+ canvas,
+ {
+ frequency: layer.toneFrequency ?? 60,
+ angle: layer.toneAngle ?? 45,
+ dotShape: layer.toneDotShape ?? 'circle',
+ dpi: dimensions.dpi ?? 600,
+ }
+ );
}
const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
@@ -2255,6 +2527,146 @@ export function App() {
return;
}
+ if (tool === 'select-wand') {
+ e.preventDefault();
+ if (selection?.floating) {
+ handleCommitFloatingSelection();
+ }
+
+ const px = Math.floor(pt.x);
+ const py = Math.floor(pt.y);
+ if (px < 0 || px >= dimensions.width || py < 0 || py >= dimensions.height) return;
+
+ let sampleCanvas: HTMLCanvasElement | null = null;
+ if (wandSettings.referMode === 'all') {
+ sampleCanvas = compositeVisibleLayers(layers, layerCanvasesRef.current, dimensions);
+ } else if (wandSettings.referMode === 'reference') {
+ const refLayer = layers.find((l) => l.isReference && l.visible);
+ if (refLayer) {
+ sampleCanvas = layerCanvasesRef.current.get(refLayer.id) || null;
+ } else {
+ sampleCanvas = layerCanvasesRef.current.get(activeLayerId) || getActiveCanvas();
+ }
+ } else {
+ sampleCanvas = layerCanvasesRef.current.get(activeLayerId) || getActiveCanvas();
+ }
+
+ if (!sampleCanvas) return;
+ const sCtx = get2DContext(sampleCanvas);
+ if (!sCtx) return;
+
+ const w = dimensions.width;
+ const h = dimensions.height;
+ const sampleImageData = sCtx.getImageData(0, 0, w, h);
+ const { mask, bounds } = floodSelectWand(
+ sampleImageData,
+ w,
+ h,
+ px,
+ py,
+ wandSettings
+ );
+
+ if (!bounds || bounds.width === 0 || bounds.height === 0) {
+ setSelection(null);
+ return;
+ }
+
+ const svgPath = maskToSvgPath(mask, w, h);
+ setSelection({
+ type: 'wand',
+ bounds,
+ mask,
+ maskWidth: w,
+ maskHeight: h,
+ svgPath,
+ });
+ return;
+ }
+
+ if (tool === 'select-pen' || tool === 'select-eraser') {
+ e.preventDefault();
+ if (selection?.floating) {
+ handleCommitFloatingSelection();
+ }
+
+ const w = dimensions.width;
+ const h = dimensions.height;
+ let maskCanvas = selectionMaskCanvasRef.current;
+ if (!maskCanvas || maskCanvas.width !== w || maskCanvas.height !== h) {
+ maskCanvas = document.createElement('canvas');
+ maskCanvas.width = w;
+ maskCanvas.height = h;
+ selectionMaskCanvasRef.current = maskCanvas;
+ }
+
+ const mCtx = get2DContext(maskCanvas);
+ if (!mCtx) return;
+
+ mCtx.clearRect(0, 0, w, h);
+ if (selection) {
+ const currentMask = selectionToMask(selection, w, h);
+ const imgData = mCtx.createImageData(w, h);
+ for (let i = 0; i < currentMask.length; i++) {
+ const val = currentMask[i];
+ const idx = i * 4;
+ imgData.data[idx] = val;
+ imgData.data[idx + 1] = val;
+ imgData.data[idx + 2] = val;
+ imgData.data[idx + 3] = val > 0 ? 255 : 0;
+ }
+ mCtx.putImageData(imgData, 0, 0);
+ }
+
+ const brushSize = brushSettings.size;
+ mCtx.save();
+ mCtx.lineCap = 'round';
+ mCtx.lineJoin = 'round';
+ mCtx.lineWidth = brushSize;
+ if (tool === 'select-pen') {
+ mCtx.globalCompositeOperation = 'source-over';
+ mCtx.fillStyle = '#ffffff';
+ mCtx.strokeStyle = '#ffffff';
+ } else {
+ mCtx.globalCompositeOperation = 'destination-out';
+ mCtx.fillStyle = '#000000';
+ mCtx.strokeStyle = '#000000';
+ }
+
+ mCtx.beginPath();
+ mCtx.arc(pt.x, pt.y, brushSize / 2, 0, Math.PI * 2);
+ mCtx.fill();
+ mCtx.restore();
+
+ selectionPenDrawingRef.current = {
+ isDrawing: true,
+ lastPt: pt,
+ maskCanvas,
+ ctx: mCtx,
+ };
+
+ const mImgData = mCtx.getImageData(0, 0, w, h);
+ const newMask = new Uint8Array(w * h);
+ for (let i = 0; i < newMask.length; i++) {
+ newMask[i] = mImgData.data[i * 4 + 3] > 0 ? 255 : 0;
+ }
+ const b = maskToBounds(newMask, w, h);
+ if (b) {
+ const svg = maskToSvgPath(newMask, w, h);
+ setSelection({
+ type: 'mask',
+ bounds: b,
+ mask: newMask,
+ maskWidth: w,
+ maskHeight: h,
+ svgPath: svg,
+ });
+ } else {
+ setSelection(null);
+ }
+ return;
+ }
+
if (tool === 'select-rect' || tool === 'select-lasso') {
e.preventDefault();
if (selection && isPointInSelection(pt.x, pt.y, selection)) {
@@ -2406,6 +2818,9 @@ export function App() {
pushHistoryStep,
textSettings,
handleSampleColor,
+ wandSettings,
+ brushSettings.size,
+ dimensions,
]
);
@@ -2498,6 +2913,53 @@ export function App() {
const pt = getCanvasCoords(e);
+ if ((tool === 'select-pen' || tool === 'select-eraser') && selectionPenDrawingRef.current?.isDrawing) {
+ const { ctx: mCtx, lastPt } = selectionPenDrawingRef.current;
+ const brushSize = brushSettings.size;
+ mCtx.save();
+ mCtx.lineCap = 'round';
+ mCtx.lineJoin = 'round';
+ mCtx.lineWidth = brushSize;
+ if (tool === 'select-pen') {
+ mCtx.globalCompositeOperation = 'source-over';
+ mCtx.strokeStyle = '#ffffff';
+ } else {
+ mCtx.globalCompositeOperation = 'destination-out';
+ mCtx.strokeStyle = '#000000';
+ }
+
+ mCtx.beginPath();
+ mCtx.moveTo(lastPt.x, lastPt.y);
+ mCtx.lineTo(pt.x, pt.y);
+ mCtx.stroke();
+ mCtx.restore();
+
+ selectionPenDrawingRef.current.lastPt = pt;
+
+ const w = dimensions.width;
+ const h = dimensions.height;
+ const mImgData = mCtx.getImageData(0, 0, w, h);
+ const newMask = new Uint8Array(w * h);
+ for (let i = 0; i < newMask.length; i++) {
+ newMask[i] = mImgData.data[i * 4 + 3] > 0 ? 255 : 0;
+ }
+ const b = maskToBounds(newMask, w, h);
+ if (b) {
+ const svg = maskToSvgPath(newMask, w, h);
+ setSelection({
+ type: 'mask',
+ bounds: b,
+ mask: newMask,
+ maskWidth: w,
+ maskHeight: h,
+ svgPath: svg,
+ });
+ } else {
+ setSelection(null);
+ }
+ return;
+ }
+
if (selectionDragRef.current?.isDragging) {
const dx = pt.x - selectionDragRef.current.startX;
const dy = pt.y - selectionDragRef.current.startY;
@@ -2560,7 +3022,7 @@ export function App() {
return;
}
},
- [tool, handleCanvasDrawingPointerMove, getCanvasCoords, fillSettings.method, handleSampleColor]
+ [tool, handleCanvasDrawingPointerMove, getCanvasCoords, fillSettings.method, handleSampleColor, brushSettings.size, dimensions]
);
const handlePointerUp = useCallback(
@@ -2627,6 +3089,33 @@ export function App() {
const pt = getCanvasCoords(e);
+ if ((tool === 'select-pen' || tool === 'select-eraser') && selectionPenDrawingRef.current?.isDrawing) {
+ const { ctx: mCtx } = selectionPenDrawingRef.current;
+ selectionPenDrawingRef.current = null;
+ const w = dimensions.width;
+ const h = dimensions.height;
+ const mImgData = mCtx.getImageData(0, 0, w, h);
+ const newMask = new Uint8Array(w * h);
+ for (let i = 0; i < newMask.length; i++) {
+ newMask[i] = mImgData.data[i * 4 + 3] > 0 ? 255 : 0;
+ }
+ const b = maskToBounds(newMask, w, h);
+ if (b) {
+ const svg = maskToSvgPath(newMask, w, h);
+ setSelection({
+ type: 'mask',
+ bounds: b,
+ mask: newMask,
+ maskWidth: w,
+ maskHeight: h,
+ svgPath: svg,
+ });
+ } else {
+ setSelection(null);
+ }
+ return;
+ }
+
if (selectionDragRef.current?.isDragging) {
selectionDragRef.current = null;
return;
@@ -2753,6 +3242,7 @@ export function App() {
pushHistoryStep,
frameSettings,
handleSampleColor,
+ dimensions,
]
);
@@ -3406,6 +3896,13 @@ export function App() {
handleStartTransform();
return;
}
+ // Select All: Ctrl+A
+ if (!e.shiftKey && (key === 'a' || e.code === 'KeyA')) {
+ if (!hasOpenDocument) return;
+ e.preventDefault();
+ handleSelectAll();
+ return;
+ }
// Deselect: Ctrl+D
if (!e.shiftKey && (key === 'd' || e.code === 'KeyD')) {
if (!hasOpenDocument) return;
@@ -3474,6 +3971,8 @@ export function App() {
handleSelectTool('brush');
} else if (key === 'e') {
handleSelectTool('eraser');
+ } else if (key === 'w') {
+ handleSelectTool('select-wand');
} else if (key === 'm') {
handleSelectTool('select-rect');
} else if (key === 'l') {
@@ -3540,6 +4039,7 @@ export function App() {
handleUndo,
handleStartTransform,
handleDeselect,
+ handleSelectAll,
handleInvertSelection,
handleClearSelection,
handleCancelTransform,
@@ -3939,6 +4439,75 @@ export function App() {
},
],
},
+ {
+ id: 'select',
+ label: 'Select',
+ items: [
+ {
+ id: 'select-all',
+ label: 'Select All',
+ shortcut: 'Ctrl+A',
+ icon: <BoxSelect className="w-3.5 h-3.5 text-sky-400" />,
+ disabled: !hasOpenDocument,
+ onClick: handleSelectAll,
+ },
+ {
+ id: 'select-deselect',
+ label: 'Deselect',
+ shortcut: 'Ctrl+D',
+ icon: <X className="w-3.5 h-3.5 text-rose-400" />,
+ disabled: !hasOpenDocument || !selection,
+ onClick: handleDeselect,
+ },
+ {
+ id: 'select-invert',
+ label: 'Invert Selection',
+ shortcut: 'Ctrl+Shift+I',
+ icon: <RotateCcw className="w-3.5 h-3.5 text-amber-400" />,
+ disabled: !hasOpenDocument,
+ onClick: handleInvertSelection,
+ },
+ {
+ id: 'select-div-1',
+ label: '',
+ divider: true,
+ },
+ {
+ id: 'select-expand',
+ label: 'Expand (+5px)...',
+ icon: <Maximize2 className="w-3.5 h-3.5 text-indigo-400" />,
+ disabled: !hasOpenDocument || !selection,
+ onClick: () => handleExpandSelection(5),
+ },
+ {
+ id: 'select-contract',
+ label: 'Contract (-5px)...',
+ icon: <Minimize2 className="w-3.5 h-3.5 text-emerald-400" />,
+ disabled: !hasOpenDocument || !selection,
+ onClick: () => handleContractSelection(5),
+ },
+ {
+ id: 'select-feather',
+ label: 'Feather (5px)...',
+ icon: <Feather className="w-3.5 h-3.5 text-purple-400" />,
+ disabled: !hasOpenDocument || !selection,
+ onClick: () => handleFeatherSelection(5),
+ },
+ {
+ id: 'select-div-2',
+ label: '',
+ divider: true,
+ },
+ {
+ id: 'select-transform',
+ label: 'Transform Selection',
+ shortcut: 'Ctrl+T',
+ icon: <Scaling className="w-3.5 h-3.5 text-cyan-400" />,
+ disabled: !hasOpenDocument || !selection,
+ onClick: handleStartTransform,
+ },
+ ],
+ },
{
id: 'layer',
label: 'Layer',
@@ -3964,6 +4533,65 @@ export function App() {
disabled: !hasOpenDocument,
onClick: () => setIs3DLayerOpen(true),
},
+ {
+ id: 'layer-new-adjustment',
+ label: 'New Adjustment Layer',
+ disabled: !hasOpenDocument,
+ submenu: [
+ {
+ id: 'layer-adj-curves',
+ label: 'Tone Curves...',
+ onClick: () => handleOpenAdjustmentModal(undefined, 'curves'),
+ },
+ {
+ id: 'layer-adj-gradient-map',
+ label: 'Gradient Map...',
+ onClick: () => handleOpenAdjustmentModal(undefined, 'gradient-map'),
+ },
+ {
+ id: 'layer-adj-levels',
+ label: 'Levels...',
+ onClick: () => handleOpenAdjustmentModal(undefined, 'levels'),
+ },
+ {
+ id: 'layer-adj-color-balance',
+ label: 'Color Balance...',
+ onClick: () => handleOpenAdjustmentModal(undefined, 'color-balance'),
+ },
+ ],
+ },
+ {
+ id: 'layer-mask-submenu',
+ label: 'Layer Mask',
+ disabled: !hasOpenDocument || !activeLayer || activeLayer.type === 'folder',
+ submenu: [
+ {
+ id: 'layer-mask-add',
+ label: activeLayer?.maskCanvas ? 'Mask Already Present' : 'Add Layer Mask (Reveal All)',
+ disabled: Boolean(activeLayer?.maskCanvas),
+ onClick: () => addLayerMask(activeLayerId),
+ },
+ {
+ id: 'layer-mask-delete',
+ label: 'Delete Layer Mask',
+ danger: true,
+ disabled: !activeLayer?.maskCanvas,
+ onClick: () => removeLayerMask(activeLayerId),
+ },
+ {
+ id: 'layer-mask-toggle',
+ label: activeLayer?.maskEnabled === false ? 'Enable Layer Mask' : 'Disable Layer Mask',
+ disabled: !activeLayer?.maskCanvas,
+ onClick: () => toggleLayerMask(activeLayerId),
+ },
+ {
+ id: 'layer-mask-link',
+ label: activeLayer?.maskLinked === false ? 'Link Mask to Layer' : 'Unlink Mask from Layer',
+ disabled: !activeLayer?.maskCanvas,
+ onClick: () => toggleMaskLinked(activeLayerId),
+ },
+ ],
+ },
{
id: 'layer-duplicate',
label: 'Duplicate Layer',
@@ -4079,6 +4707,64 @@ export function App() {
},
],
},
+ {
+ id: 'filter',
+ label: 'Filter',
+ items: [
+ {
+ id: 'filter-gaussian-blur',
+ label: 'Gaussian Blur...',
+ disabled: !hasOpenDocument || !activeLayer || activeLayer.type !== 'raster' || activeLayer.locked,
+ onClick: () => {
+ const r = window.prompt('Gaussian Blur Radius (px, 1-100):', '5');
+ if (r !== null) {
+ const radius = Math.max(1, Math.min(100, parseFloat(r) || 5));
+ handleApplyFilter('gaussian-blur', { radius });
+ }
+ },
+ },
+ {
+ id: 'filter-motion-blur',
+ label: 'Motion Blur...',
+ disabled: !hasOpenDocument || !activeLayer || activeLayer.type !== 'raster' || activeLayer.locked,
+ onClick: () => {
+ const d = window.prompt('Motion Blur Distance (px, 1-100):', '15');
+ const a = d !== null ? window.prompt('Motion Blur Angle (degrees, 0-360):', '0') : null;
+ if (d !== null && a !== null) {
+ const distance = Math.max(1, Math.min(100, parseFloat(d) || 15));
+ const angle = Math.max(0, Math.min(360, parseFloat(a) || 0));
+ handleApplyFilter('motion-blur', { distance, angle });
+ }
+ },
+ },
+ {
+ id: 'filter-unsharp-mask',
+ label: 'Unsharp Mask...',
+ disabled: !hasOpenDocument || !activeLayer || activeLayer.type !== 'raster' || activeLayer.locked,
+ onClick: () => {
+ const r = window.prompt('Unsharp Mask Radius (px, 0.5-20):', '2');
+ const a = r !== null ? window.prompt('Amount factor (0.1-5.0):', '1.5') : null;
+ if (r !== null && a !== null) {
+ const radius = Math.max(0.5, Math.min(20, parseFloat(r) || 2));
+ const amount = Math.max(0.1, Math.min(5, parseFloat(a) || 1.5));
+ handleApplyFilter('unsharp-mask', { radius, amount, threshold: 0 });
+ }
+ },
+ },
+ {
+ id: 'filter-film-grain',
+ label: 'Film Grain...',
+ disabled: !hasOpenDocument || !activeLayer || activeLayer.type !== 'raster' || activeLayer.locked,
+ onClick: () => {
+ const i = window.prompt('Film Grain Intensity (% 1-100):', '25');
+ if (i !== null) {
+ const intensity = Math.max(1, Math.min(100, parseFloat(i) || 25));
+ handleApplyFilter('film-grain', { intensity, size: 1, monochromatic: true });
+ }
+ },
+ },
+ ],
+ },
{
id: 'ruler',
label: 'Ruler',
@@ -4527,6 +5213,12 @@ export function App() {
onFillScreentone={handleFillScreentone}
liquifySettings={liquifySettings}
onUpdateLiquifySettings={handleUpdateLiquifySettings}
+ wandSettings={wandSettings}
+ onUpdateWandSettings={(newSettings) => setWandSettings((prev) => ({ ...prev, ...newSettings }))}
+ onExpandSelection={handleExpandSelection}
+ onContractSelection={handleContractSelection}
+ onFeatherSelection={handleFeatherSelection}
+ onInvertSelection={handleInvertSelection}
/>
{/* Center Workspace: Document Tab Bar (Projects) + Canvas Area */}
@@ -4585,6 +5277,9 @@ export function App() {
onFillColor={handleFillSelectionColor}
onClearSelection={handleClearSelection}
onInvertSelection={handleInvertSelection}
+ onExpandSelection={handleExpandSelection}
+ onContractSelection={handleContractSelection}
+ onFeatherSelection={handleFeatherSelection}
transformSession={transformSession}
onUpdateTransformSession={(updater) =>
setTransformSession((prev) => (prev ? updater(prev) : null))
@@ -4651,6 +5346,7 @@ export function App() {
onMoveLayer={moveLayer}
onMoveLayerToFolder={moveLayerToFolder}
onReorderLayers={reorderLayers}
+ onToggleReferenceLayer={handleToggleReferenceLayer}
onToggleTone={toggleTone}
onSetToneFrequency={setToneFrequency}
onSetToneAngle={setToneAngle}
@@ -4665,6 +5361,13 @@ export function App() {
onSetLayerMonoExpressMode={setLayerMonoExpressMode}
onApplyExpressionColor={handleApplyExpressionColor}
onApplyLayerColor={handleApplyLayerColor}
+ activeEditTarget={activeEditTarget}
+ onSelectEditTarget={setActiveEditTarget}
+ onAddLayerMask={addLayerMask}
+ onRemoveLayerMask={removeLayerMask}
+ onToggleLayerMask={toggleLayerMask}
+ onToggleMaskLinked={toggleMaskLinked}
+ onOpenAdjustmentModal={handleOpenAdjustmentModal}
width={rightSidebarWidth}
onWidthChange={handleRightSidebarWidthChange}
/>
@@ -4727,6 +5430,22 @@ export function App() {
onPreviewChange={handleTonalPreviewChange}
/>
+ {/* Non-destructive Adjustment Layer Modal (Curves, Gradient Map, Levels, Color Balance) */}
+ {adjustmentModalState.isOpen && (
+ <AdjustmentModal
+ isOpen={adjustmentModalState.isOpen}
+ initialType={adjustmentModalState.initialType || 'curves'}
+ initialData={
+ adjustmentModalState.layerId
+ ? layers.find((l) => l.id === adjustmentModalState.layerId)?.adjustmentData
+ : undefined
+ }
+ editingLayerId={adjustmentModalState.layerId}
+ onApply={handleApplyAdjustment}
+ onClose={() => setAdjustmentModalState({ isOpen: false })}
+ />
+ )}
+
{/* Clip Studio Paint Simple Tone Settings Modal */}
<SimpleToneModal
isOpen={isToneModalOpen}
diff --git a/src/components/AdjustmentModal.tsx b/src/components/AdjustmentModal.tsx
new file mode 100644
index 0000000..c3a5e87
--- /dev/null
+++ b/src/components/AdjustmentModal.tsx
@@ -0,0 +1,1018 @@
+import React, { useState, useEffect, useRef, useMemo } from 'react';
+import { X, RotateCcw, Check, SlidersHorizontal, Trash2 } from 'lucide-react';
+import {
+ AdjustmentLayerData,
+ CurvesAdjustmentData,
+ GradientMapAdjustmentData,
+ LevelsAdjustmentData,
+ ColorBalanceAdjustmentData,
+ GradientStop,
+ ToneCurvePoints,
+} from '../types/editor';
+import {
+ buildMonotonicCubicSplineLut,
+ computeHistogram,
+ buildGradientMapLut,
+} from '../utils/tonalEngine';
+
+export interface AdjustmentModalProps {
+ isOpen: boolean;
+ onClose: () => void;
+ onApply: (type: 'curves' | 'gradient-map' | 'levels' | 'color-balance', data: AdjustmentLayerData) => void;
+ initialType?: 'curves' | 'gradient-map' | 'levels' | 'color-balance';
+ initialData?: AdjustmentLayerData;
+ editingLayerId?: string | null;
+ onPreviewChange?: (data: AdjustmentLayerData | null, enabled: boolean) => void;
+ histogramImageData?: ImageData | null;
+}
+
+const DEFAULT_CURVES: ToneCurvePoints = {
+ rgb: [[0, 0], [255, 255]],
+ r: [[0, 0], [255, 255]],
+ g: [[0, 0], [255, 255]],
+ b: [[0, 0], [255, 255]],
+};
+
+const DEFAULT_GRADIENT_STOPS: GradientStop[] = [
+ { position: 0, color: '#000000' },
+ { position: 1, color: '#ffffff' },
+];
+
+const GRADIENT_PRESETS: { name: string; stops: GradientStop[]; interpolation: 'linear' | 'smooth' }[] = [
+ {
+ name: 'B&W',
+ stops: [{ position: 0, color: '#000000' }, { position: 1, color: '#ffffff' }],
+ interpolation: 'linear',
+ },
+ {
+ name: 'Sepia',
+ stops: [
+ { position: 0, color: '#1a0f00' },
+ { position: 0.35, color: '#704214' },
+ { position: 0.75, color: '#d2b48c' },
+ { position: 1, color: '#fffff0' },
+ ],
+ interpolation: 'smooth',
+ },
+ {
+ name: 'Sunset',
+ stops: [
+ { position: 0, color: '#0f051d' },
+ { position: 0.3, color: '#591a4f' },
+ { position: 0.6, color: '#c83e4d' },
+ { position: 0.85, color: '#f4b251' },
+ { position: 1, color: '#fff1b0' },
+ ],
+ interpolation: 'smooth',
+ },
+ {
+ name: 'Cyberpunk',
+ stops: [
+ { position: 0, color: '#03001e' },
+ { position: 0.35, color: '#7303c0' },
+ { position: 0.75, color: '#ec38bc' },
+ { position: 1, color: '#fdeff9' },
+ ],
+ interpolation: 'smooth',
+ },
+ {
+ name: 'Emerald',
+ stops: [
+ { position: 0, color: '#051c09' },
+ { position: 0.35, color: '#114b1e' },
+ { position: 0.7, color: '#2ca048' },
+ { position: 1, color: '#9be88b' },
+ ],
+ interpolation: 'smooth',
+ },
+ {
+ name: 'Inferno',
+ stops: [
+ { position: 0, color: '#000004' },
+ { position: 0.3, color: '#51127c' },
+ { position: 0.65, color: '#b73779' },
+ { position: 0.9, color: '#fb8861' },
+ { position: 1, color: '#fcfdbf' },
+ ],
+ interpolation: 'smooth',
+ },
+];
+
+export const AdjustmentModal: React.FC<AdjustmentModalProps> = ({
+ isOpen,
+ onClose,
+ onApply,
+ initialType = 'curves',
+ initialData,
+ editingLayerId,
+ onPreviewChange,
+ histogramImageData,
+}) => {
+ const [activeTab, setActiveTab] = useState<'curves' | 'gradient-map' | 'levels' | 'color-balance'>(initialType);
+ const [previewEnabled, setPreviewEnabled] = useState(true);
+
+ // Curves State
+ const [curves, setCurves] = useState<ToneCurvePoints>(DEFAULT_CURVES);
+ const [curveChannel, setCurveChannel] = useState<'rgb' | 'r' | 'g' | 'b'>('rgb');
+ const [selectedPointIdx, setSelectedPointIdx] = useState<number | null>(null);
+
+ // Gradient Map State
+ const [gradientStops, setGradientStops] = useState<GradientStop[]>(DEFAULT_GRADIENT_STOPS);
+ const [gradientInterpolation, setGradientInterpolation] = useState<'linear' | 'smooth'>('smooth');
+ const [selectedStopIdx, setSelectedStopIdx] = useState<number>(0);
+
+ // Levels State
+ const [levels, setLevels] = useState<{
+ blackPoint: number;
+ gamma: number;
+ whitePoint: number;
+ outputMin: number;
+ outputMax: number;
+ channel: 'rgb' | 'r' | 'g' | 'b';
+ }>({
+ blackPoint: 0,
+ gamma: 1.0,
+ whitePoint: 255,
+ outputMin: 0,
+ outputMax: 255,
+ channel: 'rgb',
+ });
+
+ // Color Balance State
+ const [colorBalance, setColorBalance] = useState<{
+ shadows: [number, number, number];
+ midtones: [number, number, number];
+ highlights: [number, number, number];
+ preserveLuminosity: boolean;
+ }>({
+ shadows: [0, 0, 0],
+ midtones: [0, 0, 0],
+ highlights: [0, 0, 0],
+ preserveLuminosity: true,
+ });
+ const [cbRange, setCbRange] = useState<'shadows' | 'midtones' | 'highlights'>('midtones');
+
+ // Load initial data
+ useEffect(() => {
+ if (initialType) {
+ setActiveTab(initialType);
+ }
+ if (initialData) {
+ if (initialData.type === 'curves') {
+ setCurves(JSON.parse(JSON.stringify(initialData.curves)));
+ } else if (initialData.type === 'gradient-map') {
+ setGradientStops(JSON.parse(JSON.stringify(initialData.stops)));
+ setGradientInterpolation(initialData.interpolation || 'smooth');
+ } else if (initialData.type === 'levels') {
+ setLevels({
+ blackPoint: initialData.blackPoint,
+ gamma: initialData.gamma,
+ whitePoint: initialData.whitePoint,
+ outputMin: initialData.outputMin ?? 0,
+ outputMax: initialData.outputMax ?? 255,
+ channel: initialData.channel || 'rgb',
+ });
+ } else if (initialData.type === 'color-balance') {
+ setColorBalance({
+ shadows: [...initialData.shadows],
+ midtones: [...initialData.midtones],
+ highlights: [...initialData.highlights],
+ preserveLuminosity: initialData.preserveLuminosity ?? true,
+ });
+ }
+ }
+ }, [initialType, initialData, isOpen]);
+
+ // Current adjustment data object
+ const currentAdjustmentData: AdjustmentLayerData = useMemo(() => {
+ switch (activeTab) {
+ case 'curves':
+ return { type: 'curves', curves } as CurvesAdjustmentData;
+ case 'gradient-map':
+ return {
+ type: 'gradient-map',
+ stops: gradientStops,
+ interpolation: gradientInterpolation,
+ } as GradientMapAdjustmentData;
+ case 'levels':
+ return {
+ type: 'levels',
+ ...levels,
+ } as LevelsAdjustmentData;
+ case 'color-balance':
+ return {
+ type: 'color-balance',
+ ...colorBalance,
+ } as ColorBalanceAdjustmentData;
+ }
+ }, [activeTab, curves, gradientStops, gradientInterpolation, levels, colorBalance]);
+
+ // Notify preview changes
+ useEffect(() => {
+ if (isOpen && onPreviewChange) {
+ onPreviewChange(currentAdjustmentData, previewEnabled);
+ }
+ }, [currentAdjustmentData, previewEnabled, isOpen, onPreviewChange]);
+
+ // Compute histogram for Tone Curve / Levels background
+ const histogramData = useMemo(() => {
+ if (!histogramImageData) return null;
+ return computeHistogram(histogramImageData, curveChannel);
+ }, [histogramImageData, curveChannel]);
+
+ const maxHistogramCount = useMemo(() => {
+ if (!histogramData) return 1;
+ let max = 1;
+ for (let i = 0; i < 256; i++) {
+ if (histogramData[i] > max) max = histogramData[i];
+ }
+ return max;
+ }, [histogramData]);
+
+ // Tone Curve calculation for selected channel
+ const currentPts = curves[curveChannel];
+ const curveLut = useMemo(() => {
+ return buildMonotonicCubicSplineLut(currentPts);
+ }, [currentPts]);
+
+ // SVG path for active curve
+ const curveSvgPath = useMemo(() => {
+ let d = `M 0 ${256 - curveLut[0]}`;
+ for (let x = 1; x < 256; x++) {
+ d += ` L ${x} ${256 - curveLut[x]}`;
+ }
+ return d;
+ }, [curveLut]);
+
+ // Handle Tone Curve control point drag
+ const curveSvgRef = useRef<SVGSVGElement | null>(null);
+ const [isDraggingPoint, setIsDraggingPoint] = useState(false);
+
+ const handleCurvePointerDown = (e: React.PointerEvent<SVGSVGElement>) => {
+ const svg = curveSvgRef.current;
+ if (!svg) return;
+ const rect = svg.getBoundingClientRect();
+ const x = Math.max(0, Math.min(255, Math.round(((e.clientX - rect.left) / rect.width) * 255)));
+ const y = Math.max(0, Math.min(255, Math.round((1 - (e.clientY - rect.top) / rect.height) * 255)));
+
+ // Check if clicked near an existing control point
+ const pts = curves[curveChannel];
+ let clickedIdx = -1;
+ for (let i = 0; i < pts.length; i++) {
+ const dx = pts[i][0] - x;
+ const dy = pts[i][1] - y;
+ if (Math.sqrt(dx * dx + dy * dy) < 14) {
+ clickedIdx = i;
+ break;
+ }
+ }
+
+ if (clickedIdx >= 0) {
+ setSelectedPointIdx(clickedIdx);
+ setIsDraggingPoint(true);
+ (e.target as Element).setPointerCapture(e.pointerId);
+ } else {
+ // Add new point
+ const newPts = [...pts, [x, y] as [number, number]].sort((a, b) => a[0] - b[0]);
+ const newIdx = newPts.findIndex((p) => p[0] === x && p[1] === y);
+ setCurves((prev) => ({
+ ...prev,
+ [curveChannel]: newPts,
+ }));
+ setSelectedPointIdx(newIdx);
+ setIsDraggingPoint(true);
+ svg.setPointerCapture(e.pointerId);
+ }
+ };
+
+ const handleCurvePointerMove = (e: React.PointerEvent<SVGSVGElement>) => {
+ if (!isDraggingPoint || selectedPointIdx === null) return;
+ const svg = curveSvgRef.current;
+ if (!svg) return;
+ const rect = svg.getBoundingClientRect();
+ let x = Math.max(0, Math.min(255, Math.round(((e.clientX - rect.left) / rect.width) * 255)));
+ const y = Math.max(0, Math.min(255, Math.round((1 - (e.clientY - rect.top) / rect.height) * 255)));
+
+ const pts = [...curves[curveChannel]];
+ // Lock X coordinate for endpoint 0 and last endpoint
+ if (selectedPointIdx === 0) x = 0;
+ else if (selectedPointIdx === pts.length - 1) x = 255;
+ else {
+ // Constrain X between neighbor points
+ const minX = pts[selectedPointIdx - 1][0] + 1;
+ const maxX = pts[selectedPointIdx + 1][0] - 1;
+ x = Math.max(minX, Math.min(maxX, x));
+ }
+
+ pts[selectedPointIdx] = [x, y];
+ setCurves((prev) => ({
+ ...prev,
+ [curveChannel]: pts,
+ }));
+ };
+
+ const handleCurvePointerUp = (e: React.PointerEvent<SVGSVGElement>) => {
+ if (isDraggingPoint) {
+ setIsDraggingPoint(false);
+ try {
+ (e.target as Element).releasePointerCapture(e.pointerId);
+ } catch (_) {}
+ }
+ };
+
+ const deleteSelectedCurvePoint = () => {
+ if (selectedPointIdx === null) return;
+ const pts = curves[curveChannel];
+ if (pts.length <= 2) return; // Keep at least 2 points
+ if (selectedPointIdx === 0 || selectedPointIdx === pts.length - 1) return; // Don't delete endpoints
+
+ const nextPts = pts.filter((_, i) => i !== selectedPointIdx);
+ setCurves((prev) => ({
+ ...prev,
+ [curveChannel]: nextPts,
+ }));
+ setSelectedPointIdx(null);
+ };
+
+ // Gradient Map Stop Handlers
+ const gradientRampRef = useRef<HTMLDivElement | null>(null);
+ const [isDraggingStop, setIsDraggingStop] = useState(false);
+
+ const handleRampPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
+ const ramp = gradientRampRef.current;
+ if (!ramp) return;
+ const rect = ramp.getBoundingClientRect();
+ const pos = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
+
+ // Sample color from current gradient at this position
+ const lut = buildGradientMapLut(gradientStops, gradientInterpolation);
+ const lumIdx = Math.round(pos * 255) * 4;
+ const r = lut[lumIdx].toString(16).padStart(2, '0');
+ const g = lut[lumIdx + 1].toString(16).padStart(2, '0');
+ const b = lut[lumIdx + 2].toString(16).padStart(2, '0');
+ const newColor = `#${r}${g}${b}`;
+
+ const newStop: GradientStop = { position: Number(pos.toFixed(3)), color: newColor };
+ const nextStops = [...gradientStops, newStop].sort((a, b) => a.position - b.position);
+ const newIdx = nextStops.findIndex((s) => s.position === newStop.position);
+ setGradientStops(nextStops);
+ setSelectedStopIdx(newIdx);
+ };
+
+ const handleStopPointerDown = (idx: number, e: React.PointerEvent) => {
+ e.stopPropagation();
+ setSelectedStopIdx(idx);
+ setIsDraggingStop(true);
+ (e.target as Element).setPointerCapture(e.pointerId);
+ };
+
+ const handleStopPointerMove = (e: React.PointerEvent) => {
+ if (!isDraggingStop) return;
+ const ramp = gradientRampRef.current;
+ if (!ramp) return;
+ const rect = ramp.getBoundingClientRect();
+ const pos = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
+
+ setGradientStops((prev) => {
+ const stops = [...prev];
+ stops[selectedStopIdx] = {
+ ...stops[selectedStopIdx],
+ position: Number(pos.toFixed(3)),
+ };
+ return stops;
+ });
+ };
+
+ const handleStopPointerUp = (e: React.PointerEvent) => {
+ if (isDraggingStop) {
+ setIsDraggingStop(false);
+ try {
+ (e.target as Element).releasePointerCapture(e.pointerId);
+ } catch (_) {}
+ // Re-sort stops
+ setGradientStops((prev) => [...prev].sort((a, b) => a.position - b.position));
+ }
+ };
+
+ const deleteSelectedStop = () => {
+ if (gradientStops.length <= 2) return;
+ setGradientStops((prev) => {
+ const next = prev.filter((_, i) => i !== selectedStopIdx);
+ return next.sort((a, b) => a.position - b.position);
+ });
+ setSelectedStopIdx(0);
+ };
+
+ const handleResetCurrent = () => {
+ if (activeTab === 'curves') {
+ setCurves(DEFAULT_CURVES);
+ setSelectedPointIdx(null);
+ } else if (activeTab === 'gradient-map') {
+ setGradientStops(DEFAULT_GRADIENT_STOPS);
+ setGradientInterpolation('smooth');
+ setSelectedStopIdx(0);
+ } else if (activeTab === 'levels') {
+ setLevels({
+ blackPoint: 0,
+ gamma: 1.0,
+ whitePoint: 255,
+ outputMin: 0,
+ outputMax: 255,
+ channel: 'rgb',
+ });
+ } else if (activeTab === 'color-balance') {
+ setColorBalance({
+ shadows: [0, 0, 0],
+ midtones: [0, 0, 0],
+ highlights: [0, 0, 0],
+ preserveLuminosity: true,
+ });
+ }
+ };
+
+ const handleApply = () => {
+ onApply(activeTab, currentAdjustmentData);
+ onClose();
+ };
+
+ if (!isOpen) return null;
+
+ const channelColor =
+ curveChannel === 'r' ? '#ef4444' : curveChannel === 'g' ? '#22c55e' : curveChannel === 'b' ? '#3b82f6' : '#ffffff';
+
+ return (
+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-xs select-none">
+ <div className="bg-[#1c1c1c] border border-[#383838] rounded-lg shadow-2xl w-[480px] max-w-[95vw] overflow-hidden flex flex-col text-[#cccccc] text-xs">
+ {/* Header */}
+ <div className="flex items-center justify-between px-4 py-3 border-b border-[#2d2d2d] bg-[#222222]">
+ <div className="flex items-center space-x-2">
+ <SlidersHorizontal className="w-4 h-4 text-blue-400" />
+ <span className="font-semibold text-white text-sm">
+ {editingLayerId ? 'Edit Adjustment Layer' : 'New Adjustment Layer'}
+ </span>
+ </div>
+ <button
+ onClick={onClose}
+ className="p-1 text-[#888888] hover:text-white rounded hover:bg-[#333333] transition-colors"
+ >
+ <X className="w-4 h-4" />
+ </button>
+ </div>
+
+ {/* Tab Selector */}
+ <div className="flex border-b border-[#2d2d2d] bg-[#1e1e1e] p-1 gap-1">
+ <button
+ onClick={() => setActiveTab('curves')}
+ className={`flex-1 py-1.5 px-2 rounded font-medium transition-colors ${
+ activeTab === 'curves' ? 'bg-[#2b2b2b] text-white shadow-xs' : 'text-[#888888] hover:text-white'
+ }`}
+ >
+ Tone Curves
+ </button>
+ <button
+ onClick={() => setActiveTab('gradient-map')}
+ className={`flex-1 py-1.5 px-2 rounded font-medium transition-colors ${
+ activeTab === 'gradient-map' ? 'bg-[#2b2b2b] text-white shadow-xs' : 'text-[#888888] hover:text-white'
+ }`}
+ >
+ Gradient Map
+ </button>
+ <button
+ onClick={() => setActiveTab('levels')}
+ className={`flex-1 py-1.5 px-2 rounded font-medium transition-colors ${
+ activeTab === 'levels' ? 'bg-[#2b2b2b] text-white shadow-xs' : 'text-[#888888] hover:text-white'
+ }`}
+ >
+ Levels
+ </button>
+ <button
+ onClick={() => setActiveTab('color-balance')}
+ className={`flex-1 py-1.5 px-2 rounded font-medium transition-colors ${
+ activeTab === 'color-balance' ? 'bg-[#2b2b2b] text-white shadow-xs' : 'text-[#888888] hover:text-white'
+ }`}
+ >
+ Color Balance
+ </button>
+ </div>
+
+ {/* Body Content */}
+ <div className="p-4 space-y-4 max-h-[75vh] overflow-y-auto">
+ {/* TAB 1: TONE CURVES */}
+ {activeTab === 'curves' && (
+ <div className="space-y-3">
+ {/* Channel Selector */}
+ <div className="flex items-center justify-between">
+ <span className="text-xs text-[#888888]">Channel:</span>
+ <div className="flex bg-[#161616] rounded p-0.5 border border-[#333333]">
+ {(['rgb', 'r', 'g', 'b'] as const).map((ch) => (
+ <button
+ key={ch}
+ onClick={() => {
+ setCurveChannel(ch);
+ setSelectedPointIdx(null);
+ }}
+ className={`px-3 py-1 rounded text-[11px] font-semibold transition-colors ${
+ curveChannel === ch
+ ? ch === 'r'
+ ? 'bg-red-900/60 text-red-300 ring-1 ring-red-500'
+ : ch === 'g'
+ ? 'bg-green-900/60 text-green-300 ring-1 ring-green-500'
+ : ch === 'b'
+ ? 'bg-blue-900/60 text-blue-300 ring-1 ring-blue-500'
+ : 'bg-[#3a3a3a] text-white'
+ : 'text-[#888888] hover:text-white'
+ }`}
+ >
+ {ch.toUpperCase()}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Interactive Curve SVG Grid */}
+ <div className="relative w-full aspect-square bg-[#141414] rounded border border-[#333333] overflow-hidden flex items-center justify-center shadow-inner">
+ {/* Histogram Overlay */}
+ {histogramData && (
+ <svg
+ viewBox="0 0 256 256"
+ className="absolute inset-0 w-full h-full pointer-events-none opacity-25"
+ preserveAspectRatio="none"
+ >
+ {Array.from({ length: 256 }).map((_, i) => {
+ const hVal = (histogramData[i] / maxHistogramCount) * 256;
+ return (
+ <rect
+ key={i}
+ x={i}
+ y={256 - hVal}
+ width={1}
+ height={hVal}
+ fill={channelColor}
+ />
+ );
+ })}
+ </svg>
+ )}
+
+ {/* Grid Lines & Labels */}
+ <svg
+ ref={curveSvgRef}
+ viewBox="0 0 256 256"
+ className="w-full h-full cursor-crosshair"
+ onPointerDown={handleCurvePointerDown}
+ onPointerMove={handleCurvePointerMove}
+ onPointerUp={handleCurvePointerUp}
+ >
+ {/* Grid Lines at 25%, 50%, 75% */}
+ {[64, 128, 192].map((coord) => (
+ <React.Fragment key={coord}>
+ <line x1={coord} y1={0} x2={coord} y2={256} stroke="#2a2a2a" strokeWidth={1} />
+ <line x1={0} y1={coord} x2={256} y2={coord} stroke="#2a2a2a" strokeWidth={1} />
+ </React.Fragment>
+ ))}
+
+ {/* Diagonal Reference Baseline */}
+ <line x1={0} y1={256} x2={256} y2={0} stroke="#383838" strokeDasharray="3 3" strokeWidth={1} />
+
+ {/* Curve Path */}
+ <path d={curveSvgPath} fill="none" stroke={channelColor} strokeWidth={2.5} strokeLinecap="round" />
+
+ {/* Control Points */}
+ {currentPts.map(([px, py], idx) => {
+ const isSelected = selectedPointIdx === idx;
+ return (
+ <g key={idx}>
+ <circle
+ cx={px}
+ cy={256 - py}
+ r={isSelected ? 6 : 4.5}
+ fill={isSelected ? '#3b82f6' : '#ffffff'}
+ stroke="#141414"
+ strokeWidth={2}
+ className="cursor-pointer transition-transform hover:scale-125"
+ />
+ </g>
+ );
+ })}
+ </svg>
+ </div>
+
+ {/* Point Inspector & Actions */}
+ <div className="flex items-center justify-between text-xs pt-1">
+ <div className="flex items-center space-x-2">
+ <span className="text-[#888888]">
+ {selectedPointIdx !== null
+ ? `In: ${currentPts[selectedPointIdx][0]} Out: ${currentPts[selectedPointIdx][1]}`
+ : 'Click curve to add points'}
+ </span>
+ </div>
+ {selectedPointIdx !== null && selectedPointIdx > 0 && selectedPointIdx < currentPts.length - 1 && (
+ <button
+ onClick={deleteSelectedCurvePoint}
+ className="flex items-center space-x-1 px-2 py-0.5 bg-red-950/40 text-red-400 hover:bg-red-900/60 rounded border border-red-800/40"
+ >
+ <Trash2 className="w-3 h-3" />
+ <span>Delete Point</span>
+ </button>
+ )}
+ </div>
+ </div>
+ )}
+
+ {/* TAB 2: GRADIENT MAP */}
+ {activeTab === 'gradient-map' && (
+ <div className="space-y-4">
+ {/* Gradient Preview Bar */}
+ <div className="space-y-1.5">
+ <div className="flex items-center justify-between text-xs">
+ <span className="text-[#888888]">Color Ramp (Click to add stop):</span>
+ <div className="flex items-center space-x-1 text-[11px]">
+ <span className="text-[#888888]">Blend:</span>
+ <button
+ onClick={() => setGradientInterpolation('linear')}
+ className={`px-1.5 py-0.5 rounded ${
+ gradientInterpolation === 'linear' ? 'bg-[#383838] text-white' : 'text-[#777777]'
+ }`}
+ >
+ Linear
+ </button>
+ <button
+ onClick={() => setGradientInterpolation('smooth')}
+ className={`px-1.5 py-0.5 rounded ${
+ gradientInterpolation === 'smooth' ? 'bg-[#383838] text-white' : 'text-[#777777]'
+ }`}
+ >
+ Smooth
+ </button>
+ </div>
+ </div>
+
+ <div
+ ref={gradientRampRef}
+ onClick={handleRampPointerDown}
+ className="relative h-9 rounded border border-[#444444] cursor-pointer shadow-inner overflow-visible"
+ style={{
+ background: `linear-gradient(to right, ${gradientStops
+ .map((s) => `${s.color} ${s.position * 100}%`)
+ .join(', ')})`,
+ }}
+ >
+ {/* Draggable Stop Pins */}
+ {gradientStops.map((stop, idx) => {
+ const isSelected = selectedStopIdx === idx;
+ return (
+ <div
+ key={idx}
+ onPointerDown={(e) => handleStopPointerDown(idx, e)}
+ onPointerMove={handleStopPointerMove}
+ onPointerUp={handleStopPointerUp}
+ style={{ left: `${stop.position * 100}%` }}
+ className={`absolute -bottom-3.5 -translate-x-1/2 w-4 h-5 flex flex-col items-center cursor-ew-resize z-20 group`}
+ title={`Stop ${idx + 1}: ${stop.color} (${Math.round(stop.position * 100)}%)`}
+ >
+ <div
+ className={`w-0 h-0 border-l-[4px] border-l-transparent border-r-[4px] border-r-transparent border-b-[5px] ${
+ isSelected ? 'border-b-blue-400' : 'border-b-white'
+ }`}
+ />
+ <div
+ className={`w-3.5 h-3.5 rounded-[2px] border ${
+ isSelected ? 'border-blue-400 ring-2 ring-blue-500/50' : 'border-white'
+ } shadow-md`}
+ style={{ backgroundColor: stop.color }}
+ />
+ </div>
+ );
+ })}
+ </div>
+ </div>
+
+ {/* Selected Stop Controls */}
+ <div className="flex items-center justify-between p-2.5 bg-[#171717] rounded border border-[#2d2d2d] mt-4">
+ <div className="flex items-center space-x-3">
+ <div className="flex items-center space-x-1.5">
+ <span className="text-[#888888]">Color:</span>
+ <input
+ type="color"
+ value={gradientStops[selectedStopIdx]?.color || '#ffffff'}
+ onChange={(e) => {
+ const val = e.target.value;
+ setGradientStops((prev) => {
+ const stops = [...prev];
+ stops[selectedStopIdx] = { ...stops[selectedStopIdx], color: val };
+ return stops;
+ });
+ }}
+ className="w-7 h-7 rounded border border-[#444444] bg-transparent cursor-pointer p-0"
+ />
+ <input
+ type="text"
+ value={gradientStops[selectedStopIdx]?.color || ''}
+ onChange={(e) => {
+ const val = e.target.value;
+ setGradientStops((prev) => {
+ const stops = [...prev];
+ stops[selectedStopIdx] = { ...stops[selectedStopIdx], color: val };
+ return stops;
+ });
+ }}
+ className="w-18 bg-[#222222] border border-[#383838] rounded px-1.5 py-0.5 text-xs text-white"
+ />
+ </div>
+ <div className="flex items-center space-x-1">
+ <span className="text-[#888888]">Pos:</span>
+ <span className="text-white font-mono">
+ {Math.round((gradientStops[selectedStopIdx]?.position || 0) * 100)}%
+ </span>
+ </div>
+ </div>
+
+ {gradientStops.length > 2 && (
+ <button
+ onClick={deleteSelectedStop}
+ className="p-1 text-[#888888] hover:text-red-400 hover:bg-red-950/30 rounded"
+ title="Delete Stop"
+ >
+ <Trash2 className="w-3.5 h-3.5" />
+ </button>
+ )}
+ </div>
+
+ {/* Preset Ramps */}
+ <div className="space-y-1.5">
+ <span className="text-[#888888] text-[11px]">Presets:</span>
+ <div className="grid grid-cols-3 gap-1.5">
+ {GRADIENT_PRESETS.map((p) => (
+ <button
+ key={p.name}
+ onClick={() => {
+ setGradientStops(JSON.parse(JSON.stringify(p.stops)));
+ setGradientInterpolation(p.interpolation);
+ setSelectedStopIdx(0);
+ }}
+ className="flex items-center space-x-2 p-1.5 rounded bg-[#1e1e1e] hover:bg-[#2a2a2a] border border-[#333333] transition-colors text-left"
+ >
+ <div
+ className="w-5 h-5 rounded-[2px] shrink-0 border border-[#444444]"
+ style={{
+ background: `linear-gradient(to right, ${p.stops
+ .map((s) => `${s.color} ${s.position * 100}%`)
+ .join(', ')})`,
+ }}
+ />
+ <span className="text-[11px] truncate">{p.name}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* TAB 3: LEVELS */}
+ {activeTab === 'levels' && (
+ <div className="space-y-3.5">
+ <div className="flex items-center justify-between">
+ <span className="text-xs text-[#888888]">Channel:</span>
+ <div className="flex bg-[#161616] rounded p-0.5 border border-[#333333]">
+ {(['rgb', 'r', 'g', 'b'] as const).map((ch) => (
+ <button
+ key={ch}
+ onClick={() => setLevels((prev) => ({ ...prev, channel: ch }))}
+ className={`px-3 py-1 rounded text-[11px] font-semibold transition-colors ${
+ levels.channel === ch ? 'bg-[#3a3a3a] text-white' : 'text-[#888888] hover:text-white'
+ }`}
+ >
+ {ch.toUpperCase()}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* Input Black Point Slider */}
+ <div className="space-y-1">
+ <div className="flex justify-between text-xs">
+ <span className="text-[#888888]">Shadows (Black Point):</span>
+ <span className="font-mono text-white">{levels.blackPoint}</span>
+ </div>
+ <input
+ type="range"
+ min={0}
+ max={Math.min(253, levels.whitePoint - 1)}
+ value={levels.blackPoint}
+ onChange={(e) => setLevels((prev) => ({ ...prev, blackPoint: Number(e.target.value) }))}
+ className="w-full accent-blue-500"
+ />
+ </div>
+
+ {/* Gamma Slider */}
+ <div className="space-y-1">
+ <div className="flex justify-between text-xs">
+ <span className="text-[#888888]">Midtones (Gamma):</span>
+ <span className="font-mono text-white">{levels.gamma.toFixed(2)}</span>
+ </div>
+ <input
+ type="range"
+ min={0.1}
+ max={5.0}
+ step={0.05}
+ value={levels.gamma}
+ onChange={(e) => setLevels((prev) => ({ ...prev, gamma: Number(e.target.value) }))}
+ className="w-full accent-blue-500"
+ />
+ </div>
+
+ {/* Input White Point Slider */}
+ <div className="space-y-1">
+ <div className="flex justify-between text-xs">
+ <span className="text-[#888888]">Highlights (White Point):</span>
+ <span className="font-mono text-white">{levels.whitePoint}</span>
+ </div>
+ <input
+ type="range"
+ min={Math.max(2, levels.blackPoint + 1)}
+ max={255}
+ value={levels.whitePoint}
+ onChange={(e) => setLevels((prev) => ({ ...prev, whitePoint: Number(e.target.value) }))}
+ className="w-full accent-blue-500"
+ />
+ </div>
+
+ {/* Output Min / Max */}
+ <div className="grid grid-cols-2 gap-3 pt-2 border-t border-[#2d2d2d]">
+ <div className="space-y-1">
+ <div className="flex justify-between text-xs">
+ <span className="text-[#888888]">Out Min:</span>
+ <span className="font-mono text-white">{levels.outputMin}</span>
+ </div>
+ <input
+ type="range"
+ min={0}
+ max={255}
+ value={levels.outputMin}
+ onChange={(e) => setLevels((prev) => ({ ...prev, outputMin: Number(e.target.value) }))}
+ className="w-full accent-blue-500"
+ />
+ </div>
+ <div className="space-y-1">
+ <div className="flex justify-between text-xs">
+ <span className="text-[#888888]">Out Max:</span>
+ <span className="font-mono text-white">{levels.outputMax}</span>
+ </div>
+ <input
+ type="range"
+ min={0}
+ max={255}
+ value={levels.outputMax}
+ onChange={(e) => setLevels((prev) => ({ ...prev, outputMax: Number(e.target.value) }))}
+ className="w-full accent-blue-500"
+ />
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* TAB 4: COLOR BALANCE */}
+ {activeTab === 'color-balance' && (
+ <div className="space-y-4">
+ {/* Range Selector */}
+ <div className="flex border border-[#333333] rounded p-0.5 bg-[#161616]">
+ {(['shadows', 'midtones', 'highlights'] as const).map((r) => (
+ <button
+ key={r}
+ onClick={() => setCbRange(r)}
+ className={`flex-1 py-1 rounded text-[11px] font-medium capitalize transition-colors ${
+ cbRange === r ? 'bg-[#333333] text-white shadow-xs' : 'text-[#888888] hover:text-white'
+ }`}
+ >
+ {r}
+ </button>
+ ))}
+ </div>
+
+ {/* Cyan - Red Slider */}
+ <div className="space-y-1">
+ <div className="flex justify-between text-xs">
+ <span className="text-cyan-400">Cyan</span>
+ <span className="font-mono text-white">{colorBalance[cbRange][0]}</span>
+ <span className="text-red-400">Red</span>
+ </div>
+ <input
+ type="range"
+ min={-100}
+ max={100}
+ value={colorBalance[cbRange][0]}
+ onChange={(e) => {
+ const val = Number(e.target.value);
+ setColorBalance((prev) => {
+ const arr: [number, number, number] = [...prev[cbRange]];
+ arr[0] = val;
+ return { ...prev, [cbRange]: arr };
+ });
+ }}
+ className="w-full accent-red-500"
+ />
+ </div>
+
+ {/* Magenta - Green Slider */}
+ <div className="space-y-1">
+ <div className="flex justify-between text-xs">
+ <span className="text-fuchsia-400">Magenta</span>
+ <span className="font-mono text-white">{colorBalance[cbRange][1]}</span>
+ <span className="text-green-400">Green</span>
+ </div>
+ <input
+ type="range"
+ min={-100}
+ max={100}
+ value={colorBalance[cbRange][1]}
+ onChange={(e) => {
+ const val = Number(e.target.value);
+ setColorBalance((prev) => {
+ const arr: [number, number, number] = [...prev[cbRange]];
+ arr[1] = val;
+ return { ...prev, [cbRange]: arr };
+ });
+ }}
+ className="w-full accent-green-500"
+ />
+ </div>
+
+ {/* Yellow - Blue Slider */}
+ <div className="space-y-1">
+ <div className="flex justify-between text-xs">
+ <span className="text-yellow-400">Yellow</span>
+ <span className="font-mono text-white">{colorBalance[cbRange][2]}</span>
+ <span className="text-blue-400">Blue</span>
+ </div>
+ <input
+ type="range"
+ min={-100}
+ max={100}
+ value={colorBalance[cbRange][2]}
+ onChange={(e) => {
+ const val = Number(e.target.value);
+ setColorBalance((prev) => {
+ const arr: [number, number, number] = [...prev[cbRange]];
+ arr[2] = val;
+ return { ...prev, [cbRange]: arr };
+ });
+ }}
+ className="w-full accent-blue-500"
+ />
+ </div>
+
+ {/* Preserve Luminosity Toggle */}
+ <label className="flex items-center space-x-2 text-xs text-[#aaaaaa] cursor-pointer pt-1">
+ <input
+ type="checkbox"
+ checked={colorBalance.preserveLuminosity}
+ onChange={(e) => setColorBalance((prev) => ({ ...prev, preserveLuminosity: e.target.checked }))}
+ className="rounded bg-[#222222] border-[#444444] text-blue-500"
+ />
+ <span>Preserve Luminosity</span>
+ </label>
+ </div>
+ )}
+ </div>
+
+ {/* Footer */}
+ <div className="flex items-center justify-between px-4 py-3 border-t border-[#2d2d2d] bg-[#202020]">
+ <div className="flex items-center space-x-3">
+ <button
+ onClick={handleResetCurrent}
+ className="flex items-center space-x-1 px-2.5 py-1 text-[#888888] hover:text-white hover:bg-[#333333] rounded transition-colors"
+ >
+ <RotateCcw className="w-3.5 h-3.5" />
+ <span>Reset</span>
+ </button>
+ <label className="flex items-center space-x-1.5 text-xs text-[#888888] cursor-pointer">
+ <input
+ type="checkbox"
+ checked={previewEnabled}
+ onChange={(e) => setPreviewEnabled(e.target.checked)}
+ className="rounded bg-[#222222] border-[#444444] text-blue-500"
+ />
+ <span>Preview</span>
+ </label>
+ </div>
+
+ <div className="flex items-center space-x-2">
+ <button
+ onClick={onClose}
+ className="px-3 py-1.5 text-xs text-[#aaaaaa] hover:text-white hover:bg-[#333333] rounded transition-colors"
+ >
+ Cancel
+ </button>
+ <button
+ onClick={handleApply}
+ className="flex items-center space-x-1 px-4 py-1.5 text-xs bg-blue-600 hover:bg-blue-500 text-white font-medium rounded shadow-sm transition-colors"
+ >
+ <Check className="w-3.5 h-3.5" />
+ <span>{editingLayerId ? 'Update' : 'Create Layer'}</span>
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/src/components/CanvasArea.tsx b/src/components/CanvasArea.tsx
index ce03cc0..c2e6895 100644
--- a/src/components/CanvasArea.tsx
+++ b/src/components/CanvasArea.tsx
@@ -66,6 +66,9 @@ interface CanvasAreaProps {
onFillColor?: () => void;
onClearSelection?: () => void;
onInvertSelection?: () => void;
+ onExpandSelection?: (pixels: number) => void;
+ onContractSelection?: (pixels: number) => void;
+ onFeatherSelection?: (radius: number) => void;
transformSession?: TransformSession | null;
onUpdateTransformSession?: (updater: (prev: TransformSession) => TransformSession) => void;
onApplyTransform?: () => void;
@@ -129,6 +132,9 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
onFillColor,
onClearSelection,
onInvertSelection,
+ onExpandSelection,
+ onContractSelection,
+ onFeatherSelection,
transformSession = null,
onUpdateTransformSession,
onApplyTransform,
@@ -261,7 +267,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
isRotating ||
isRotateModifier ||
isResizingBrush ||
- (tool !== 'brush' && tool !== 'eraser' && tool !== 'liquify')
+ (tool !== 'brush' && tool !== 'eraser' && tool !== 'liquify' && tool !== 'select-pen' && tool !== 'select-eraser')
) {
ring.style.display = 'none';
return;
@@ -583,7 +589,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
if (tool === 'text') {
return { cursor: 'text' };
}
- if (tool === 'select-rect' || tool === 'select-lasso' || tool === 'fill' || tool === 'frame') {
+ if (tool === 'select-rect' || tool === 'select-lasso' || tool === 'select-wand' || tool === 'fill' || tool === 'frame') {
return { cursor: 'crosshair' };
}
if (tool === 'liquify') {
@@ -592,7 +598,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
if (tool === 'transform') {
return { cursor: 'default' };
}
- if (tool === 'brush' || tool === 'eraser') {
+ if (tool === 'brush' || tool === 'eraser' || tool === 'select-pen' || tool === 'select-eraser') {
return { cursor: isOverCanvas ? 'none' : 'default' };
}
return { cursor: isOverCanvas ? 'crosshair' : 'default' };
@@ -640,7 +646,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
{/* Artboard Container with 2D Affine Transformation (Pan, Zoom, and Rotation) */}
<div
- className="absolute origin-top-left select-none"
+ className="absolute origin-top-left select-none z-20"
style={{
width: dimensions.width,
height: dimensions.height,
@@ -735,6 +741,9 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
onFillColor={onFillColor || (() => {})}
onClearSelection={onClearSelection || (() => {})}
onInvertSelection={onInvertSelection || (() => {})}
+ onExpandSelection={onExpandSelection}
+ onContractSelection={onContractSelection}
+ onFeatherSelection={onFeatherSelection}
/>
)}
diff --git a/src/components/LeftPanel.tsx b/src/components/LeftPanel.tsx
index d4f3def..a88fb1b 100644
--- a/src/components/LeftPanel.tsx
+++ b/src/components/LeftPanel.tsx
@@ -35,6 +35,9 @@ import {
Undo2,
CornerUpLeft,
CornerUpRight,
+ Wand2,
+ PenTool,
+ Feather,
} from 'lucide-react';
import {
ToolType,
@@ -46,6 +49,7 @@ import {
FrameSettings,
LiquifySettings,
LiquifyMode,
+ WandSettings,
} from '../types/editor';
import { LiquifyIcon } from './LiquifyIcon';
import { PENCIL_CONFIGS, PencilGrade } from '../utils/pencilEngine';
@@ -102,6 +106,12 @@ interface LeftPanelProps {
onFillScreentone?: () => void;
liquifySettings?: LiquifySettings;
onUpdateLiquifySettings?: (newSettings: Partial<LiquifySettings>) => void;
+ wandSettings?: WandSettings;
+ onUpdateWandSettings?: (newSettings: Partial<WandSettings>) => void;
+ onExpandSelection?: (pixels: number) => void;
+ onContractSelection?: (pixels: number) => void;
+ onFeatherSelection?: (radius: number) => void;
+ onInvertSelection?: () => void;
}
export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({
@@ -130,6 +140,12 @@ export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({
onFillScreentone: _onFillScreentone,
liquifySettings,
onUpdateLiquifySettings,
+ wandSettings,
+ onUpdateWandSettings,
+ onExpandSelection,
+ onContractSelection,
+ onFeatherSelection,
+ onInvertSelection,
}) => {
const [showAdvanced, setShowAdvanced] = useState(false);
@@ -189,6 +205,9 @@ export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({
if (currentTool === 'pipette') return 'Eyedropper';
if (currentTool === 'select-rect') return 'Marquee';
if (currentTool === 'select-lasso') return 'Lasso';
+ if (currentTool === 'select-wand') return 'Magic Wand';
+ if (currentTool === 'select-pen') return 'Selection Pen';
+ if (currentTool === 'select-eraser') return 'Selection Eraser';
if (currentTool === 'fill') return 'Fill';
if (currentTool === 'text') return 'Text';
if (currentTool === 'frame') return 'Frame Border';
@@ -591,15 +610,42 @@ export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({
);
}
- if (currentTool === 'select-rect' || currentTool === 'select-lasso') {
+ const isSelectionTool =
+ currentTool === 'select-rect' ||
+ currentTool === 'select-lasso' ||
+ currentTool === 'select-wand' ||
+ currentTool === 'select-pen' ||
+ currentTool === 'select-eraser';
+
+ if (isSelectionTool) {
+ const activeWand = wandSettings || {
+ tolerance: 32,
+ contiguous: true,
+ antiAlias: true,
+ referMode: 'active' as const,
+ };
+
+ const selectionTitle =
+ currentTool === 'select-rect'
+ ? 'Rectangular Marquee (M)'
+ : currentTool === 'select-lasso'
+ ? 'Lasso Selection (L)'
+ : currentTool === 'select-wand'
+ ? 'Magic Wand (W)'
+ : currentTool === 'select-pen'
+ ? 'Selection Pen'
+ : 'Selection Eraser';
+
return (
<div className="flex-1 flex flex-col overflow-y-auto">
<div className="h-9 px-3 flex items-center justify-between border-b border-[#2b2d31] bg-[#1a1b1e] shrink-0">
<div className="flex items-center space-x-2">
- {currentTool === 'select-rect' ? <BoxSelect className="w-4 h-4 text-cyan-400" /> : <Lasso className="w-4 h-4 text-cyan-400" />}
- <span className="text-xs font-semibold text-white">
- {currentTool === 'select-rect' ? 'Rectangular Marquee (M)' : 'Lasso Selection (L)'}
- </span>
+ {currentTool === 'select-rect' && <BoxSelect className="w-4 h-4 text-cyan-400" />}
+ {currentTool === 'select-lasso' && <Lasso className="w-4 h-4 text-cyan-400" />}
+ {currentTool === 'select-wand' && <Wand2 className="w-4 h-4 text-cyan-400" />}
+ {currentTool === 'select-pen' && <PenTool className="w-4 h-4 text-cyan-400" />}
+ {currentTool === 'select-eraser' && <Eraser className="w-4 h-4 text-cyan-400" />}
+ <span className="text-xs font-semibold text-white">{selectionTitle}</span>
</div>
<button onClick={onToggleHidden} className="p-1 text-[#828690] hover:text-rose-400 rounded cursor-pointer">
<X className="w-3.5 h-3.5" />
@@ -619,7 +665,7 @@ export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({
}`}
>
<BoxSelect className="w-3.5 h-3.5" />
- <span>Rectangle</span>
+ <span>Marquee</span>
</button>
<button
@@ -633,16 +679,184 @@ export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({
<Lasso className="w-3.5 h-3.5" />
<span>Lasso</span>
</button>
+
+ <button
+ onClick={() => onSelectTool('select-wand')}
+ className={`py-1.5 px-2 rounded text-xs text-center transition-colors cursor-pointer flex items-center justify-center space-x-1 ${
+ currentTool === 'select-wand'
+ ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] font-medium'
+ : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white border border-transparent'
+ }`}
+ >
+ <Wand2 className="w-3.5 h-3.5" />
+ <span>Wand</span>
+ </button>
+
+ <button
+ onClick={() => onSelectTool('select-pen')}
+ className={`py-1.5 px-2 rounded text-xs text-center transition-colors cursor-pointer flex items-center justify-center space-x-1 ${
+ currentTool === 'select-pen'
+ ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] font-medium'
+ : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white border border-transparent'
+ }`}
+ >
+ <PenTool className="w-3.5 h-3.5" />
+ <span>Sel Pen</span>
+ </button>
+
+ <button
+ onClick={() => onSelectTool('select-eraser')}
+ className={`col-span-2 py-1.5 px-2 rounded text-xs text-center transition-colors cursor-pointer flex items-center justify-center space-x-1 ${
+ currentTool === 'select-eraser'
+ ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] font-medium'
+ : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white border border-transparent'
+ }`}
+ >
+ <Eraser className="w-3.5 h-3.5" />
+ <span>Selection Eraser</span>
+ </button>
</div>
</div>
- <div className="space-y-2 pt-2 border-t border-[#26282c]">
- <label className="text-[11px] font-medium text-[#aaaaaa] block">Selection Actions:</label>
+ {/* Magic Wand Specific Settings */}
+ {currentTool === 'select-wand' && (
+ <div className="space-y-3 pt-2 border-t border-[#26282c]">
+ <div>
+ <div className="flex items-center justify-between text-xs mb-1">
+ <span className="text-[#aaaaaa]">Tolerance:</span>
+ <span className="text-white font-mono">{activeWand.tolerance}</span>
+ </div>
+ <input
+ type="range"
+ min="0"
+ max="255"
+ value={activeWand.tolerance}
+ onChange={(e) => onUpdateWandSettings?.({ tolerance: Number(e.target.value) })}
+ className="w-full accent-cyan-400"
+ />
+ </div>
+
+ <div className="flex items-center justify-between text-xs py-1">
+ <span className="text-[#cccccc]">Contiguous</span>
+ <input
+ type="checkbox"
+ checked={activeWand.contiguous}
+ onChange={(e) => onUpdateWandSettings?.({ contiguous: e.target.checked })}
+ className="accent-cyan-400 rounded cursor-pointer"
+ />
+ </div>
+
+ <div className="flex items-center justify-between text-xs py-1">
+ <span className="text-[#cccccc]">Anti-Aliasing</span>
+ <input
+ type="checkbox"
+ checked={activeWand.antiAlias}
+ onChange={(e) => onUpdateWandSettings?.({ antiAlias: e.target.checked })}
+ className="accent-cyan-400 rounded cursor-pointer"
+ />
+ </div>
+
+ <div className="space-y-1">
+ <span className="text-[11px] text-[#aaaaaa] block">Reference Source:</span>
+ <div className="grid grid-cols-3 gap-1">
+ {(['active', 'all', 'reference'] as const).map((mode) => (
+ <button
+ key={mode}
+ onClick={() => onUpdateWandSettings?.({ referMode: mode })}
+ className={`py-1 px-1.5 rounded text-[11px] text-center capitalize cursor-pointer transition-colors ${
+ activeWand.referMode === mode
+ ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] font-medium'
+ : 'bg-[#202226] text-[#aaaaaa] hover:bg-[#282a2e] hover:text-white'
+ }`}
+ >
+ {mode === 'active' ? 'Active' : mode === 'all' ? 'All' : 'Ref Layer'}
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+ )}
+
+ {/* Selection Pen / Eraser Size */}
+ {(currentTool === 'select-pen' || currentTool === 'select-eraser') && (
+ <div className="space-y-3 pt-2 border-t border-[#26282c]">
+ <div>
+ <div className="flex items-center justify-between text-xs mb-1">
+ <span className="text-[#aaaaaa]">Pen Size:</span>
+ <span className="text-white font-mono">{Math.round(brushSettings.size)} px</span>
+ </div>
+ <input
+ type="range"
+ min="1"
+ max="300"
+ value={brushSettings.size}
+ onChange={(e) => onUpdateBrushSettings({ size: Number(e.target.value) })}
+ className="w-full accent-cyan-400"
+ />
+ </div>
+
+ <div>
+ <div className="flex items-center justify-between text-xs mb-1">
+ <span className="text-[#aaaaaa]">Stabilization:</span>
+ <span className="text-white font-mono">{brushSettings.stabilization ?? 10}</span>
+ </div>
+ <input
+ type="range"
+ min="0"
+ max="50"
+ value={brushSettings.stabilization ?? 10}
+ onChange={(e) => onUpdateBrushSettings({ stabilization: Number(e.target.value) })}
+ className="w-full accent-cyan-400"
+ />
+ </div>
+ </div>
+ )}
+
+ {/* Selection Boundary Modifiers & Actions */}
+ <div className="space-y-1.5 pt-2 border-t border-[#26282c]">
+ <label className="text-[11px] font-medium text-[#aaaaaa] block mb-1">Boundary Modifiers:</label>
+ <div className="grid grid-cols-3 gap-1">
+ <button
+ onClick={() => onExpandSelection?.(5)}
+ title="Expand Selection by 5px"
+ className="py-1.5 px-1 bg-[#202226] hover:bg-[#282a2e] text-[#cccccc] hover:text-white rounded text-[11px] transition-colors flex items-center justify-center space-x-1 cursor-pointer border border-[#2f323a]"
+ >
+ <Maximize2 className="w-3 h-3 text-cyan-400" />
+ <span>Expand</span>
+ </button>
+
+ <button
+ onClick={() => onContractSelection?.(5)}
+ title="Contract Selection by 5px"
+ className="py-1.5 px-1 bg-[#202226] hover:bg-[#282a2e] text-[#cccccc] hover:text-white rounded text-[11px] transition-colors flex items-center justify-center space-x-1 cursor-pointer border border-[#2f323a]"
+ >
+ <Minimize2 className="w-3 h-3 text-cyan-400" />
+ <span>Contract</span>
+ </button>
+
+ <button
+ onClick={() => onFeatherSelection?.(5)}
+ title="Feather Selection (5px)"
+ className="py-1.5 px-1 bg-[#202226] hover:bg-[#282a2e] text-[#cccccc] hover:text-white rounded text-[11px] transition-colors flex items-center justify-center space-x-1 cursor-pointer border border-[#2f323a]"
+ >
+ <Feather className="w-3 h-3 text-cyan-400" />
+ <span>Feather</span>
+ </button>
+ </div>
+
+ <button
+ onClick={onInvertSelection}
+ className="w-full py-1.5 px-2 bg-[#202226] hover:bg-[#282a2e] text-[#cccccc] hover:text-white rounded text-xs transition-colors flex items-center justify-center space-x-1.5 cursor-pointer border border-[#2f323a]"
+ >
+ <RotateCcw className="w-3.5 h-3.5 text-amber-400" />
+ <span>Invert Selection (Ctrl+Shift+I)</span>
+ </button>
+
<button
onClick={onTransformSelection}
className="w-full py-1.5 px-2 bg-[#202226] hover:bg-[#282a2e] text-[#cccccc] hover:text-white rounded text-xs transition-colors flex items-center justify-center space-x-1.5 cursor-pointer border border-[#2f323a]"
>
- <Scaling className="w-3.5 h-3.5 text-cyan-400" />
+ <Scaling className="w-3.5 h-3.5 text-emerald-400" />
<span>Transform Selection (Ctrl+T)</span>
</button>
@@ -1040,6 +1254,54 @@ export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({
</div>
</button>
+ {/* Magic Wand (W) */}
+ <button
+ onClick={() => onSelectTool('select-wand')}
+ title="Magic Wand (W)"
+ className={`w-9 h-9 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${
+ currentTool === 'select-wand'
+ ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] shadow-xs'
+ : 'text-[#8c9099] hover:text-[#d0d3d9] hover:bg-[#25272a]'
+ }`}
+ >
+ <Wand2 className="w-4 h-4" />
+ <div className="absolute left-11 bg-[#18191b] text-[#cccccc] text-xs px-2 py-1 rounded border border-[#33353b] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 shadow-md">
+ Magic Wand (W)
+ </div>
+ </button>
+
+ {/* Selection Pen */}
+ <button
+ onClick={() => onSelectTool('select-pen')}
+ title="Selection Pen"
+ className={`w-9 h-9 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${
+ currentTool === 'select-pen'
+ ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] shadow-xs'
+ : 'text-[#8c9099] hover:text-[#d0d3d9] hover:bg-[#25272a]'
+ }`}
+ >
+ <PenTool className="w-4 h-4" />
+ <div className="absolute left-11 bg-[#18191b] text-[#cccccc] text-xs px-2 py-1 rounded border border-[#33353b] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 shadow-md">
+ Selection Pen
+ </div>
+ </button>
+
+ {/* Selection Eraser */}
+ <button
+ onClick={() => onSelectTool('select-eraser')}
+ title="Selection Eraser"
+ className={`w-9 h-9 rounded flex items-center justify-center transition-colors relative group cursor-pointer ${
+ currentTool === 'select-eraser'
+ ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b] shadow-xs'
+ : 'text-[#8c9099] hover:text-[#d0d3d9] hover:bg-[#25272a]'
+ }`}
+ >
+ <Eraser className="w-4 h-4" />
+ <div className="absolute left-11 bg-[#18191b] text-[#cccccc] text-xs px-2 py-1 rounded border border-[#33353b] opacity-0 pointer-events-none group-hover:opacity-100 transition-opacity whitespace-nowrap z-50 shadow-md">
+ Selection Eraser
+ </div>
+ </button>
+
<div className="w-5 h-px bg-[#2b2d31] my-0.5" />
{/* Fill Tool (G) */}
diff --git a/src/components/MenuBar.tsx b/src/components/MenuBar.tsx
index e8e730e..0d76be9 100644
--- a/src/components/MenuBar.tsx
+++ b/src/components/MenuBar.tsx
@@ -5,6 +5,7 @@ import { MenuSection, MenuItem } from '../types/editor';
export const DEFAULT_MENU_SECTIONS: MenuSection[] = [
{ id: 'file', label: 'File', items: [] },
{ id: 'edit', label: 'Edit', items: [] },
+ { id: 'select', label: 'Select', items: [] },
{ id: 'layer', label: 'Layer', items: [] },
{ id: 'ruler', label: 'Ruler', items: [] },
{ id: 'view', label: 'View', items: [] },
diff --git a/src/components/RightSidebar.tsx b/src/components/RightSidebar.tsx
index 4452ad9..cc96476 100644
--- a/src/components/RightSidebar.tsx
+++ b/src/components/RightSidebar.tsx
@@ -24,6 +24,10 @@ import {
FolderOutput,
Box,
GripVertical,
+ Compass,
+ SquareDot,
+ Link2,
+ SlidersHorizontal,
} from 'lucide-react';
import { HistoryItemMeta, LayerItem, BlendMode, ToolType, CanvasColorMode, ExpressionColor } from '../types/editor';
import { BLEND_MODES } from '../utils/canvasUtils';
@@ -61,7 +65,16 @@ interface RightSidebarProps {
onRenameLayer: (id: string, name: string) => void;
onMoveLayer?: (id: string, direction: 'up' | 'down') => void;
onMoveLayerToFolder: (id: string, targetFolderId: string | null) => void;
+ // Non-destructive Layer Mask & Adjustment Props
+ activeEditTarget?: 'layer' | 'mask';
+ onSelectEditTarget?: (target: 'layer' | 'mask') => void;
+ onAddLayerMask?: (layerId: string) => void;
+ onRemoveLayerMask?: (layerId: string, apply?: boolean) => void;
+ onToggleLayerMask?: (layerId: string) => void;
+ onToggleMaskLinked?: (layerId: string) => void;
+ onOpenAdjustmentModal?: (layerId?: string, initialType?: 'curves' | 'gradient-map' | 'levels' | 'color-balance') => void;
onReorderLayers?: (draggedId: string, targetId: string, position: 'above' | 'below' | 'inside') => void;
+ onToggleReferenceLayer?: (id: string) => void;
// Tone (Screentone) Effect Props
onToggleTone?: (id: string) => void;
onSetToneFrequency?: (id: string, frequency: number) => void;
@@ -195,6 +208,14 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
onRenameLayer,
onMoveLayerToFolder,
onReorderLayers,
+ activeEditTarget = 'layer',
+ onSelectEditTarget,
+ onAddLayerMask,
+ onRemoveLayerMask,
+ onToggleLayerMask,
+ onToggleMaskLinked,
+ onOpenAdjustmentModal,
+ onToggleReferenceLayer,
onToggleTone,
onSetToneFrequency,
onSetToneAngle,
@@ -237,6 +258,30 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
return () => window.removeEventListener('mousedown', handlePointerDown);
}, [isExpressionMenuOpen]);
+ // Right-click layer context menu state
+ const [contextMenu, setContextMenu] = useState<{ layerId: string; x: number; y: number } | null>(null);
+ const contextMenuRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (!contextMenu) return;
+ const handleOutsideClick = (e: MouseEvent) => {
+ if (contextMenuRef.current && !contextMenuRef.current.contains(e.target as Node)) {
+ setContextMenu(null);
+ }
+ };
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ setContextMenu(null);
+ }
+ };
+ window.addEventListener('pointerdown', handleOutsideClick);
+ window.addEventListener('keydown', handleKeyDown);
+ return () => {
+ window.removeEventListener('pointerdown', handleOutsideClick);
+ window.removeEventListener('keydown', handleKeyDown);
+ };
+ }, [contextMenu]);
+
// Top Section (Color Panel) Height & Resizer
const [topHeight, setTopHeight] = useState<number>(() => {
const saved = localStorage.getItem('sora_paint_right_color_height');
@@ -1259,6 +1304,25 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
</button>
)}
+ {/* Toggle Reference Layer */}
+ {activeLayer && (
+ <button
+ onClick={() => onToggleReferenceLayer?.(activeLayer.id)}
+ title={
+ activeLayer.isReference
+ ? 'Unset as Reference Layer'
+ : 'Set as Reference Layer (Sampled by Magic Wand / Fill)'
+ }
+ className={`p-1 rounded-[2px] transition-colors ${
+ activeLayer.isReference
+ ? 'text-cyan-400 bg-cyan-950/50 ring-1 ring-cyan-500/60 shadow-xs'
+ : 'text-[#888888] hover:text-white hover:bg-[#333333]'
+ }`}
+ >
+ <Compass className="w-3.5 h-3.5" />
+ </button>
+ )}
+
{/* Toggle Lock */}
{activeLayer && (
<button
@@ -1315,6 +1379,24 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
onClick={() => {
if (justDraggedRef.current) return;
onSelectLayer(layer.id);
+ if (activeEditTarget === 'mask' && !layer.maskCanvas && layer.maskEnabled === undefined) {
+ onSelectEditTarget?.('layer');
+ }
+ }}
+ onDoubleClick={() => {
+ if (layer.type === 'adjustment') {
+ onOpenAdjustmentModal?.(layer.id, layer.adjustmentData?.type);
+ }
+ }}
+ onContextMenu={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ onSelectLayer(layer.id);
+ setContextMenu({
+ layerId: layer.id,
+ x: e.clientX,
+ y: e.clientY,
+ });
}}
className={`group relative flex items-center space-x-1.5 px-2 py-1.5 rounded-[2px] transition-colors border select-none ${
isInsideFolder ? 'ml-4 border-l-2 border-l-[#444444]' : ''
@@ -1401,7 +1483,7 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
</button>
)}
- {/* Layer Icon: Folder icon for folders, Layers icon for raster layers */}
+ {/* Layer Icon: Folder icon for folders, Sliders for adjustment, Layers for raster */}
{isFolder ? (
<div className="w-4 h-4 flex items-center justify-center shrink-0 text-amber-400">
{layer.collapsed ? (
@@ -1410,47 +1492,142 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
<FolderOpen className="w-4 h-4" />
)}
</div>
+ ) : layer.type === 'adjustment' ? (
+ <div className="w-4 h-4 flex items-center justify-center shrink-0 text-cyan-400">
+ <SlidersHorizontal className="w-3.5 h-3.5" />
+ </div>
) : (
<div className="w-4 h-4 flex items-center justify-center shrink-0 text-[#888888] group-hover:text-blue-400 transition-colors">
<Layers className={`w-3.5 h-3.5 ${isActive ? 'text-blue-400' : ''}`} />
</div>
)}
- {/* Live Layer Thumbnail Preview next to Layer Icon (for raster layers) */}
+ {/* Live Layer Thumbnail & Secondary Mask Thumbnail Preview */}
{!isFolder && (
- <div
- className="w-10 h-7 rounded-[2px] border border-[#484848] overflow-hidden shrink-0 relative flex items-center justify-center shadow-inner"
- style={{
- backgroundColor: '#1e1e1e',
- backgroundImage:
- layer.id === 'layer-bg'
- ? 'none'
- : 'conic-gradient(#2d2d2d 90deg, #1f1f1f 90deg 180deg, #2d2d2d 180deg 270deg, #1f1f1f 270deg)',
- backgroundSize: '6px 6px',
- }}
- title={`Layer content preview for ${layer.name}`}
- >
- {layer.thumbnailUrl ? (
- <img
- src={layer.thumbnailUrl}
- alt={layer.name}
- className="w-full h-full object-cover"
- />
+ <div className="flex items-center space-x-1 shrink-0">
+ {/* Primary Layer Thumbnail */}
+ {layer.type === 'adjustment' ? (
+ <div
+ onClick={(e) => {
+ e.stopPropagation();
+ onSelectLayer(layer.id);
+ onSelectEditTarget?.('layer');
+ }}
+ onDoubleClick={(e) => {
+ e.stopPropagation();
+ onOpenAdjustmentModal?.(layer.id, layer.adjustmentData?.type);
+ }}
+ className={`w-10 h-7 rounded-[2px] border border-[#484848] overflow-hidden shrink-0 relative flex items-center justify-center shadow-inner cursor-pointer bg-linear-to-br from-[#1a2332] to-[#0e1726] ${
+ isActive && activeEditTarget !== 'mask' ? 'ring-2 ring-blue-500 border-blue-400' : ''
+ }`}
+ title="Adjustment Layer (Double-click to edit parameters)"
+ >
+ <SlidersHorizontal className="w-3.5 h-3.5 text-cyan-400" />
+ </div>
) : (
<div
- className="w-full h-full"
+ onClick={(e) => {
+ e.stopPropagation();
+ onSelectLayer(layer.id);
+ onSelectEditTarget?.('layer');
+ }}
+ className={`w-10 h-7 rounded-[2px] border border-[#484848] overflow-hidden shrink-0 relative flex items-center justify-center shadow-inner cursor-pointer ${
+ isActive && activeEditTarget !== 'mask' ? 'ring-2 ring-blue-500 border-blue-400' : ''
+ }`}
style={{
- backgroundColor: layer.id === 'layer-bg' ? '#ffffff' : 'transparent',
+ backgroundColor: '#1e1e1e',
+ backgroundImage:
+ layer.id === 'layer-bg'
+ ? 'none'
+ : 'conic-gradient(#2d2d2d 90deg, #1f1f1f 90deg 180deg, #2d2d2d 180deg 270deg, #1f1f1f 270deg)',
+ backgroundSize: '6px 6px',
}}
- />
+ title={`Layer content preview for ${layer.name}`}
+ >
+ {layer.thumbnailUrl ? (
+ <img
+ src={layer.thumbnailUrl}
+ alt={layer.name}
+ className="w-full h-full object-cover"
+ />
+ ) : (
+ <div
+ className="w-full h-full"
+ style={{
+ backgroundColor: layer.id === 'layer-bg' ? '#ffffff' : 'transparent',
+ }}
+ />
+ )}
+
+ {/* Clipping Mask Left Indicator Stripe (CSP style) */}
+ {layer.clipped && (
+ <div
+ className="absolute left-0 top-0 bottom-0 w-1 bg-blue-500 rounded-l-[1px] z-10 shadow-xs"
+ title="Clipped to layer below"
+ />
+ )}
+ </div>
)}
- {/* Clipping Mask Left Indicator Stripe (CSP style) */}
- {layer.clipped && (
- <div
- className="absolute left-0 top-0 bottom-0 w-1 bg-blue-500 rounded-l-[1px] z-10 shadow-xs"
- title="Clipped to layer below"
- />
+ {/* Secondary Mask Thumbnail (if layer has mask) */}
+ {(layer.maskCanvas || layer.maskEnabled !== undefined || layer.maskThumbnailUrl) && (
+ <>
+ {/* Link Toggle Icon */}
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ onToggleMaskLinked?.(layer.id);
+ }}
+ title={layer.maskLinked !== false ? 'Mask Linked to Layer (Click to Unlink)' : 'Mask Unlinked (Click to Link)'}
+ className={`p-0.5 transition-colors ${
+ layer.maskLinked !== false ? 'text-zinc-400 hover:text-white' : 'text-zinc-600 hover:text-zinc-400'
+ }`}
+ >
+ <Link2 className={`w-2.5 h-2.5 ${layer.maskLinked === false ? 'opacity-30' : ''}`} />
+ </button>
+
+ {/* Mask Thumbnail */}
+ <div
+ onClick={(e) => {
+ e.stopPropagation();
+ onSelectLayer(layer.id);
+ onSelectEditTarget?.('mask');
+ }}
+ onContextMenu={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ onSelectLayer(layer.id);
+ onSelectEditTarget?.('mask');
+ setContextMenu({
+ layerId: layer.id,
+ x: e.clientX,
+ y: e.clientY,
+ });
+ }}
+ className={`w-10 h-7 rounded-[2px] border border-[#484848] overflow-hidden shrink-0 relative flex items-center justify-center shadow-inner cursor-pointer bg-black ${
+ isActive && activeEditTarget === 'mask' ? 'ring-2 ring-blue-500 border-blue-400' : ''
+ }`}
+ title={`Layer Mask for ${layer.name} (Click to paint on mask, Right-click to toggle enabled)`}
+ >
+ {layer.maskThumbnailUrl ? (
+ <img
+ src={layer.maskThumbnailUrl}
+ alt={`${layer.name} Mask`}
+ className="w-full h-full object-cover"
+ />
+ ) : (
+ <div className="w-full h-full bg-white" />
+ )}
+
+ {/* Red slash when mask is disabled */}
+ {layer.maskEnabled === false && (
+ <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
+ <div className="w-[140%] h-[1.5px] bg-red-500 rotate-45 transform shadow-xs" />
+ </div>
+ )}
+ </div>
+ </>
)}
</div>
)}
@@ -1541,6 +1718,22 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
{layer.expressionColor === 'monochrome' ? '1-bit' : 'Gray'}
</span>
)}
+
+ {/* Adjustment Layer Tag */}
+ {layer.type === 'adjustment' && (
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ onOpenAdjustmentModal?.(layer.id, layer.adjustmentData?.type);
+ }}
+ className="text-[9px] px-1.5 py-0.5 rounded bg-cyan-950/60 border border-cyan-600/50 text-cyan-300 font-mono flex items-center gap-1 shrink-0 hover:border-cyan-400 hover:text-cyan-200 transition-colors cursor-pointer"
+ title="Click to edit adjustment parameters"
+ >
+ <SlidersHorizontal className="w-2.5 h-2.5" />
+ <span className="capitalize">{layer.adjustmentData?.type?.replace('-', ' ') || 'Adjustment'}</span>
+ </button>
+ )}
</div>
{/* Alpha Lock Indicator Tag */}
@@ -1558,6 +1751,21 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
</button>
)}
+ {/* Reference Layer Indicator */}
+ {layer.isReference && (
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ onToggleReferenceLayer?.(layer.id);
+ }}
+ className="p-0.5 text-cyan-400 hover:text-cyan-300 shrink-0"
+ title="Reference Layer (Click to toggle)"
+ >
+ <Compass className="w-3.5 h-3.5" />
+ </button>
+ )}
+
{/* Lock Indicator */}
{layer.locked && (
<Lock className="w-3 h-3 text-[#777777] shrink-0" />
@@ -1565,6 +1773,20 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
{/* Hover Quick Actions: Single-Click Duplicate, Move to/from folder, Delete */}
<div className="flex items-center space-x-0.5 opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
+ {/* Delete Layer Mask Quick Action */}
+ {(layer.maskCanvas || layer.maskEnabled !== undefined) && onRemoveLayerMask && (
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ onRemoveLayerMask(layer.id);
+ }}
+ title="Delete Layer Mask"
+ className="p-1 hover:text-rose-400 hover:bg-[#333333] rounded-[2px] text-zinc-400"
+ >
+ <SquareDot className="w-3 h-3 text-rose-400/80" />
+ </button>
+ )}
+
{/* Single-Click Duplicate Button */}
<button
onClick={(e) => {
@@ -1746,6 +1968,185 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
</div>
)}
</section>
+
+ {/* Right-Click Layer Context Menu */}
+ {contextMenu && (() => {
+ const targetLayer = layers.find((l) => l.id === contextMenu.layerId);
+ if (!targetLayer) return null;
+ const hasMask = Boolean(targetLayer.maskCanvas || targetLayer.maskEnabled !== undefined || targetLayer.maskThumbnailUrl);
+ const isAdj = targetLayer.type === 'adjustment';
+
+ return (
+ <div
+ ref={contextMenuRef}
+ className="fixed z-50 min-w-52 bg-[#222225] border border-[#3e3e42] rounded-md shadow-2xl py-1 text-xs text-[#cccccc] select-none animate-in fade-in duration-75"
+ style={{
+ left: Math.max(10, Math.min(contextMenu.x, window.innerWidth - 220)),
+ top: Math.max(10, Math.min(contextMenu.y, window.innerHeight - 360)),
+ }}
+ onClick={(e) => e.stopPropagation()}
+ onContextMenu={(e) => e.preventDefault()}
+ >
+ {/* Header / Layer info */}
+ <div className="px-3 py-1 text-[10px] text-[#777777] font-semibold uppercase tracking-wider border-b border-[#2d2d30] mb-0.5 truncate flex items-center justify-between">
+ <span className="truncate">{targetLayer.name}</span>
+ {isAdj && <span className="text-cyan-400 font-mono text-[9px] lowercase">adjustment</span>}
+ </div>
+
+ {/* --- MASK OPTIONS --- */}
+ {targetLayer.type !== 'folder' && (
+ <>
+ <div className="px-3 py-1 text-[10px] text-[#888888] font-semibold tracking-wide flex items-center space-x-1">
+ <SquareDot className="w-3 h-3 text-emerald-400" />
+ <span>Layer Mask</span>
+ </div>
+ {!hasMask ? (
+ <button
+ onClick={() => {
+ onAddLayerMask?.(targetLayer.id);
+ setContextMenu(null);
+ }}
+ className="w-full text-left px-3 py-1.5 pl-6 flex items-center space-x-2 hover:bg-[#333333] hover:text-white transition-colors"
+ >
+ <span>Add Layer Mask</span>
+ </button>
+ ) : (
+ <>
+ <button
+ onClick={() => {
+ onToggleLayerMask?.(targetLayer.id);
+ setContextMenu(null);
+ }}
+ className="w-full text-left px-3 py-1.5 pl-6 flex items-center justify-between hover:bg-[#333333] hover:text-white transition-colors"
+ >
+ <span>{targetLayer.maskEnabled === false ? 'Enable Mask' : 'Disable Mask'}</span>
+ <span className="text-[10px] font-mono text-zinc-400">
+ {targetLayer.maskEnabled === false ? 'OFF' : 'ON'}
+ </span>
+ </button>
+ <button
+ onClick={() => {
+ onToggleMaskLinked?.(targetLayer.id);
+ setContextMenu(null);
+ }}
+ className="w-full text-left px-3 py-1.5 pl-6 flex items-center justify-between hover:bg-[#333333] hover:text-white transition-colors"
+ >
+ <span>{targetLayer.maskLinked === false ? 'Link Mask' : 'Unlink Mask'}</span>
+ <Link2 className={`w-3 h-3 ${targetLayer.maskLinked === false ? 'text-zinc-600' : 'text-zinc-400'}`} />
+ </button>
+ <button
+ onClick={() => {
+ onRemoveLayerMask?.(targetLayer.id);
+ setContextMenu(null);
+ }}
+ className="w-full text-left px-3 py-1.5 pl-6 flex items-center space-x-2 hover:bg-rose-950/40 text-rose-400 hover:text-rose-300 transition-colors"
+ >
+ <span>Delete Mask</span>
+ </button>
+ </>
+ )}
+ <div className="my-1 border-t border-[#2d2d30]" />
+ </>
+ )}
+
+ {/* --- ADJUSTMENT OPTIONS --- */}
+ {isAdj && (
+ <>
+ <button
+ onClick={() => {
+ onOpenAdjustmentModal?.(targetLayer.id, targetLayer.adjustmentData?.type);
+ setContextMenu(null);
+ }}
+ className="w-full text-left px-3 py-1.5 flex items-center space-x-2 hover:bg-[#333333] text-cyan-400 hover:text-cyan-300 transition-colors"
+ >
+ <SlidersHorizontal className="w-3.5 h-3.5" />
+ <span className="font-medium">Edit Adjustment Parameters...</span>
+ </button>
+ <div className="my-1 border-t border-[#2d2d30]" />
+ </>
+ )}
+
+ {onOpenAdjustmentModal && (
+ <>
+ <div className="px-3 py-1 text-[10px] text-[#888888] font-semibold tracking-wide flex items-center space-x-1">
+ <SlidersHorizontal className="w-3 h-3 text-cyan-400" />
+ <span>New Adjustment Layer</span>
+ </div>
+ <button
+ onClick={() => {
+ onOpenAdjustmentModal(undefined, 'curves');
+ setContextMenu(null);
+ }}
+ className="w-full text-left px-3 py-1.5 pl-6 flex items-center space-x-2 hover:bg-[#333333] hover:text-white transition-colors"
+ >
+ <span>Tone Curves...</span>
+ </button>
+ <button
+ onClick={() => {
+ onOpenAdjustmentModal(undefined, 'gradient-map');
+ setContextMenu(null);
+ }}
+ className="w-full text-left px-3 py-1.5 pl-6 flex items-center space-x-2 hover:bg-[#333333] hover:text-white transition-colors"
+ >
+ <span>Gradient Map...</span>
+ </button>
+ <button
+ onClick={() => {
+ onOpenAdjustmentModal(undefined, 'levels');
+ setContextMenu(null);
+ }}
+ className="w-full text-left px-3 py-1.5 pl-6 flex items-center space-x-2 hover:bg-[#333333] hover:text-white transition-colors"
+ >
+ <span>Levels...</span>
+ </button>
+ <button
+ onClick={() => {
+ onOpenAdjustmentModal(undefined, 'color-balance');
+ setContextMenu(null);
+ }}
+ className="w-full text-left px-3 py-1.5 pl-6 flex items-center space-x-2 hover:bg-[#333333] hover:text-white transition-colors"
+ >
+ <span>Color Balance...</span>
+ </button>
+ <div className="my-1 border-t border-[#2d2d30]" />
+ </>
+ )}
+
+ {/* --- GENERAL ACTIONS --- */}
+ <button
+ onClick={() => {
+ onDuplicateLayer(targetLayer.id);
+ setContextMenu(null);
+ }}
+ className="w-full text-left px-3 py-1.5 flex items-center space-x-2 hover:bg-[#333333] hover:text-white transition-colors"
+ >
+ <Copy className="w-3.5 h-3.5 text-zinc-400" />
+ <span>Duplicate</span>
+ </button>
+ <button
+ onClick={() => {
+ startRename(targetLayer);
+ setContextMenu(null);
+ }}
+ className="w-full text-left px-3 py-1.5 flex items-center space-x-2 hover:bg-[#333333] hover:text-white transition-colors"
+ >
+ <span>Rename</span>
+ </button>
+ {targetLayer.id !== 'layer-bg' && (
+ <button
+ onClick={() => {
+ onDeleteLayer(targetLayer.id);
+ setContextMenu(null);
+ }}
+ className="w-full text-left px-3 py-1.5 flex items-center space-x-2 hover:bg-rose-950/40 text-rose-400 hover:text-rose-300 transition-colors"
+ >
+ <Trash2 className="w-3.5 h-3.5 text-rose-400" />
+ <span>Delete</span>
+ </button>
+ )}
+ </div>
+ );
+ })()}
</aside>
);
});
diff --git a/src/components/SelectionOverlay.tsx b/src/components/SelectionOverlay.tsx
index ec6249f..296f86e 100644
--- a/src/components/SelectionOverlay.tsx
+++ b/src/components/SelectionOverlay.tsx
@@ -1,4 +1,4 @@
-import React, { useEffect, useRef } from 'react';
+import React, { useEffect, useRef, useMemo } from 'react';
import { createPortal } from 'react-dom';
import {
CanvasSelection,
@@ -11,7 +11,11 @@ import {
Trash2,
Sparkles,
RotateCcw,
+ Maximize2,
+ Minimize2,
+ Feather,
} from 'lucide-react';
+import { maskToSvgPath } from '../utils/selectionUtils';
interface SelectionOverlayProps {
selection: CanvasSelection | null;
@@ -23,18 +27,24 @@ interface SelectionOverlayProps {
onFillColor: () => void;
onClearSelection: () => void;
onInvertSelection: () => void;
+ onExpandSelection?: (pixels: number) => void;
+ onContractSelection?: (pixels: number) => void;
+ onFeatherSelection?: (radius: number) => void;
}
export const SelectionOverlay: React.FC<SelectionOverlayProps> = ({
selection,
dimensions,
- zoom: _zoom,
+ zoom,
onDeselect,
onTransformSelection,
onFillScreentone,
onFillColor,
onClearSelection,
onInvertSelection,
+ onExpandSelection,
+ onContractSelection,
+ onFeatherSelection,
}) => {
const floatingCanvasContainerRef = useRef<HTMLDivElement>(null);
@@ -48,17 +58,29 @@ export const SelectionOverlay: React.FC<SelectionOverlayProps> = ({
}
}, [selection?.floating?.canvas]);
- if (!selection) return null;
+ const { bounds, type, polygon, floating, mask, maskWidth, maskHeight, svgPath } = selection || {};
- const { bounds, type, polygon, floating } = selection;
+ // Build SVG path for marching ants
+ const pathD = useMemo(() => {
+ if (!selection) return '';
+ if (svgPath) return svgPath;
+ if (mask) {
+ const mw = maskWidth || dimensions.width;
+ const mh = maskHeight || dimensions.height;
+ return maskToSvgPath(mask, mw, mh);
+ }
+ if (type === 'rect' && bounds) {
+ return `M ${bounds.x} ${bounds.y} H ${bounds.x + bounds.width} V ${bounds.y + bounds.height} H ${bounds.x} Z`;
+ }
+ if (type === 'lasso' && polygon && polygon.length > 2) {
+ return `M ${polygon[0].x} ${polygon[0].y} ` + polygon.slice(1).map((p) => `L ${p.x} ${p.y}`).join(' ') + ' Z';
+ }
+ return '';
+ }, [selection, svgPath, mask, maskWidth, maskHeight, type, bounds, polygon, dimensions.width, dimensions.height]);
- // Build SVG path for lasso or rect
- let pathD = '';
- if (type === 'rect') {
- pathD = `M ${bounds.x} ${bounds.y} H ${bounds.x + bounds.width} V ${bounds.y + bounds.height} H ${bounds.x} Z`;
- } else if (type === 'lasso' && polygon && polygon.length > 2) {
- pathD = `M ${polygon[0].x} ${polygon[0].y} ` + polygon.slice(1).map((p) => `L ${p.x} ${p.y}`).join(' ') + ' Z';
- }
+ if (!selection || !bounds) return null;
+
+ const invZoom = zoom > 0 ? 1 / zoom : 1;
return (
<>
@@ -113,7 +135,82 @@ export const SelectionOverlay: React.FC<SelectionOverlayProps> = ({
)}
</svg>
- {/* 3. CSP-Style Selection Launcher Bar (Fixed at bottom center of viewport) */}
+ {/* 3. Floating Quick-Action Bar directly above active selection */}
+ <div
+ className="absolute z-26 pointer-events-auto select-none"
+ style={{
+ left: `${bounds.x + bounds.width / 2}px`,
+ top: `${bounds.y}px`,
+ transform: `translate(-50%, calc(-100% - ${8 * invZoom}px)) scale(${invZoom})`,
+ transformOrigin: 'bottom center',
+ }}
+ onPointerDown={(e) => e.stopPropagation()}
+ >
+ <div className="bg-[#18191b] border border-[#33353b] rounded shadow-2xl px-2 py-1 flex items-center space-x-1 whitespace-nowrap text-xs text-[#cccccc]">
+ {/* Expand */}
+ <button
+ onClick={() => onExpandSelection?.(5)}
+ title="Expand Selection (+5px)"
+ className="px-1.5 py-0.5 hover:text-white hover:bg-[#25272a] rounded flex items-center space-x-1 cursor-pointer transition-colors"
+ >
+ <Maximize2 className="w-3 h-3 text-cyan-400" />
+ <span>Expand</span>
+ </button>
+
+ {/* Contract */}
+ <button
+ onClick={() => onContractSelection?.(5)}
+ title="Contract Selection (-5px)"
+ className="px-1.5 py-0.5 hover:text-white hover:bg-[#25272a] rounded flex items-center space-x-1 cursor-pointer transition-colors"
+ >
+ <Minimize2 className="w-3 h-3 text-cyan-400" />
+ <span>Contract</span>
+ </button>
+
+ {/* Feather */}
+ <button
+ onClick={() => onFeatherSelection?.(5)}
+ title="Feather Selection (5px)"
+ className="px-1.5 py-0.5 hover:text-white hover:bg-[#25272a] rounded flex items-center space-x-1 cursor-pointer transition-colors"
+ >
+ <Feather className="w-3 h-3 text-cyan-400" />
+ <span>Feather</span>
+ </button>
+
+ <div className="w-px h-3.5 bg-[#33353b]" />
+
+ {/* Invert */}
+ <button
+ onClick={onInvertSelection}
+ title="Invert Selection (Ctrl+Shift+I)"
+ className="px-1.5 py-0.5 hover:text-white hover:bg-[#25272a] rounded flex items-center space-x-1 cursor-pointer transition-colors"
+ >
+ <RotateCcw className="w-3 h-3 text-amber-400" />
+ <span>Invert</span>
+ </button>
+
+ {/* Transform */}
+ <button
+ onClick={onTransformSelection}
+ title="Transform Selection (Ctrl+T)"
+ className="px-1.5 py-0.5 hover:text-white hover:bg-[#25272a] rounded flex items-center space-x-1 cursor-pointer transition-colors"
+ >
+ <Scaling className="w-3 h-3 text-emerald-400" />
+ <span>Transform</span>
+ </button>
+
+ {/* Deselect */}
+ <button
+ onClick={onDeselect}
+ title="Deselect (Ctrl+D)"
+ className="p-1 hover:text-rose-400 hover:bg-[#25272a] rounded cursor-pointer transition-colors"
+ >
+ <X className="w-3.5 h-3.5 text-rose-400" />
+ </button>
+ </div>
+ </div>
+
+ {/* 4. CSP-Style Selection Launcher Bar (Fixed at bottom center of viewport) */}
{createPortal(
<div
className="fixed bottom-10 left-1/2 -translate-x-1/2 z-50 bg-[#1e1f22] border border-[#383a40] rounded shadow-2xl px-2 py-1.5 flex items-center space-x-1.5 select-none animate-in fade-in slide-in-from-bottom-2 duration-150"
diff --git a/src/components/TransformOverlay.tsx b/src/components/TransformOverlay.tsx
index edd4158..f79f50e 100644
--- a/src/components/TransformOverlay.tsx
+++ b/src/components/TransformOverlay.tsx
@@ -1,12 +1,23 @@
-import React, { useRef, useLayoutEffect, useEffect } from 'react';
-import { TransformSession } from '../types/editor';
+import React, { useRef, useLayoutEffect, useEffect, useMemo } from 'react';
+import { TransformSession, Point2D, TransformMode } from '../types/editor';
import {
Check,
X,
FlipHorizontal,
FlipVertical,
RotateCcw,
+ BoxSelect,
+ Grid3X3,
+ Square,
} from 'lucide-react';
+import {
+ renderPerspectiveQuad,
+ renderMeshWarp,
+ createDefaultPerspectiveQuad,
+ createDefaultMeshPoints,
+ getPointsBounds,
+ evaluateMeshSurface,
+} from '../utils/transformEngine';
interface TransformOverlayProps {
session: TransformSession;
@@ -27,50 +38,280 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({
}) => {
const containerRef = useRef<HTMLDivElement>(null);
const previewCanvasRef = useRef<HTMLCanvasElement>(null);
+ const activeDragCleanupRef = useRef<(() => void) | null>(null);
+
+ useEffect(() => {
+ return () => {
+ if (activeDragCleanupRef.current) {
+ activeDragCleanupRef.current();
+ }
+ };
+ }, []);
+
+ const mode: TransformMode = session.mode || 'affine';
+
+ // Ensure perspectiveQuad exists
+ const quad: [Point2D, Point2D, Point2D, Point2D] = useMemo(() => {
+ if (session.perspectiveQuad) return session.perspectiveQuad;
+ return createDefaultPerspectiveQuad(
+ session.x,
+ session.y,
+ session.width,
+ session.height,
+ session.rotation
+ );
+ }, [session.perspectiveQuad, session.x, session.y, session.width, session.height, session.rotation]);
+
+ // Ensure meshPoints exists
+ const meshPoints: Point2D[][] = useMemo(() => {
+ if (session.meshPoints) return session.meshPoints;
+ const cols = session.meshCols || 4;
+ const rows = session.meshRows || 4;
+ return createDefaultMeshPoints(quad, cols, rows);
+ }, [session.meshPoints, quad, session.meshCols, session.meshRows]);
+
+ // Compute bounding box for perspective or mesh mode
+ const nonAffineBounds = useMemo(() => {
+ if (mode === 'perspective') {
+ return getPointsBounds(quad);
+ }
+ if (mode === 'mesh') {
+ const flat: Point2D[] = [];
+ for (const row of meshPoints) {
+ for (const pt of row) flat.push(pt);
+ }
+ return getPointsBounds(flat);
+ }
+ if (session.rotation) {
+ const cx = session.x + session.width / 2;
+ const cy = session.y + session.height / 2;
+ const hw = session.width / 2;
+ const hh = session.height / 2;
+ const rad = (session.rotation * Math.PI) / 180;
+ const cos = Math.cos(rad);
+ const sin = Math.sin(rad);
+ const corners: Point2D[] = [
+ { x: -hw, y: -hh },
+ { x: hw, y: -hh },
+ { x: hw, y: hh },
+ { x: -hw, y: hh },
+ ].map((p) => ({
+ x: cx + p.x * cos - p.y * sin,
+ y: cy + p.x * sin + p.y * cos,
+ }));
+ return getPointsBounds(corners);
+ }
+ return {
+ minX: session.x,
+ minY: session.y,
+ maxX: session.x + session.width,
+ maxY: session.y + session.height,
+ width: session.width,
+ height: session.height,
+ };
+ }, [mode, quad, meshPoints, session.x, session.y, session.width, session.height, session.rotation]);
- // Synchronously draw the sourceCanvas into the preview canvas before paint
+ // Synchronously draw preview in layout effect
useLayoutEffect(() => {
const canvas = previewCanvasRef.current;
if (!canvas || !session.sourceCanvas) return;
- canvas.width = session.sourceCanvas.width;
- canvas.height = session.sourceCanvas.height;
+
const ctx = canvas.getContext('2d');
if (!ctx) return;
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- try {
- const sCtx = session.sourceCanvas.getContext('2d');
- if (sCtx) {
- const imgData = sCtx.getImageData(0, 0, session.sourceCanvas.width, session.sourceCanvas.height);
- ctx.putImageData(imgData, 0, 0);
- } else {
+
+ if (mode === 'affine') {
+ canvas.width = session.sourceCanvas.width;
+ canvas.height = session.sourceCanvas.height;
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ try {
+ const sCtx = session.sourceCanvas.getContext('2d');
+ if (sCtx) {
+ const imgData = sCtx.getImageData(0, 0, session.sourceCanvas.width, session.sourceCanvas.height);
+ ctx.putImageData(imgData, 0, 0);
+ } else {
+ ctx.drawImage(session.sourceCanvas, 0, 0);
+ }
+ } catch {
ctx.drawImage(session.sourceCanvas, 0, 0);
}
- } catch {
- ctx.drawImage(session.sourceCanvas, 0, 0);
+ } else if (mode === 'perspective') {
+ const bw = Math.max(10, nonAffineBounds.width);
+ const bh = Math.max(10, nonAffineBounds.height);
+ canvas.width = bw;
+ canvas.height = bh;
+ ctx.clearRect(0, 0, bw, bh);
+
+ // Shift quad into local canvas coordinates
+ const localQuad: [Point2D, Point2D, Point2D, Point2D] = [
+ { x: quad[0].x - nonAffineBounds.minX, y: quad[0].y - nonAffineBounds.minY },
+ { x: quad[1].x - nonAffineBounds.minX, y: quad[1].y - nonAffineBounds.minY },
+ { x: quad[2].x - nonAffineBounds.minX, y: quad[2].y - nonAffineBounds.minY },
+ { x: quad[3].x - nonAffineBounds.minX, y: quad[3].y - nonAffineBounds.minY },
+ ];
+
+ renderPerspectiveQuad(ctx, session.sourceCanvas, localQuad, 16);
+ } else if (mode === 'mesh') {
+ const bw = Math.max(10, nonAffineBounds.width);
+ const bh = Math.max(10, nonAffineBounds.height);
+ canvas.width = bw;
+ canvas.height = bh;
+ ctx.clearRect(0, 0, bw, bh);
+
+ // Shift mesh into local canvas coordinates
+ const localMesh: Point2D[][] = meshPoints.map((row) =>
+ row.map((pt) => ({
+ x: pt.x - nonAffineBounds.minX,
+ y: pt.y - nonAffineBounds.minY,
+ }))
+ );
+
+ renderMeshWarp(ctx, session.sourceCanvas, localMesh, 4);
}
- }, [session.sourceCanvas]);
-
- const activeDragCleanupRef = useRef<(() => void) | null>(null);
+ }, [mode, session.sourceCanvas, nonAffineBounds, quad, meshPoints]);
+
+ // Mode switching handler
+ const handleSwitchMode = (newMode: TransformMode) => {
+ if (newMode === mode) return;
+
+ onUpdateSession((prev) => {
+ const q = prev.perspectiveQuad || createDefaultPerspectiveQuad(prev.x, prev.y, prev.width, prev.height, prev.rotation);
+ const cols = prev.meshCols || 4;
+ const rows = prev.meshRows || 4;
+ const m = prev.meshPoints || createDefaultMeshPoints(q, cols, rows);
+
+ return {
+ ...prev,
+ mode: newMode,
+ perspectiveQuad: q,
+ meshCols: cols,
+ meshRows: rows,
+ meshPoints: m,
+ };
+ });
+ };
- useEffect(() => {
- return () => {
- if (activeDragCleanupRef.current) {
- activeDragCleanupRef.current();
+ // Mesh resolution change handler
+ const handleChangeMeshGrid = (size: number) => {
+ onUpdateSession((prev) => {
+ const existingMesh = prev.meshPoints || meshPoints;
+ const newMesh: Point2D[][] = [];
+
+ for (let r = 0; r < size; r++) {
+ const v = size > 1 ? r / (size - 1) : 0;
+ const row: Point2D[] = [];
+ for (let c = 0; c < size; c++) {
+ const u = size > 1 ? c / (size - 1) : 0;
+ // Resample position from existing surface
+ const evaluated = evaluateMeshSurface(existingMesh, u, v);
+ row.push({ x: Math.round(evaluated.x), y: Math.round(evaluated.y) });
+ }
+ newMesh.push(row);
}
+
+ return {
+ ...prev,
+ meshCols: size,
+ meshRows: size,
+ meshPoints: newMesh,
+ };
+ });
+ };
+
+ // Convert screen delta to un-rotated canvas coordinates
+ const screenDeltaToCanvas = (dxScreen: number, dyScreen: number): { dx: number; dy: number } => {
+ const canvasRotRad = (-canvasRotation * Math.PI) / 180;
+ const cCos = Math.cos(canvasRotRad);
+ const cSin = Math.sin(canvasRotRad);
+ return {
+ dx: (dxScreen * cCos - dyScreen * cSin) / zoom,
+ dy: (dxScreen * cSin + dyScreen * cCos) / zoom,
};
- }, []);
+ };
+
+ // Start dragging a perspective corner pin
+ const startDragPerspectiveCorner = (index: number, e: React.PointerEvent) => {
+ e.stopPropagation();
+ e.preventDefault();
+
+ if (activeDragCleanupRef.current) activeDragCleanupRef.current();
+
+ const startX = e.clientX;
+ const startY = e.clientY;
+ const initialPoint = { ...quad[index] };
+
+ const handlePointerMove = (ev: PointerEvent) => {
+ const { dx, dy } = screenDeltaToCanvas(ev.clientX - startX, ev.clientY - startY);
+ onUpdateSession((prev) => {
+ const currentQuad = prev.perspectiveQuad ? [...prev.perspectiveQuad] : [...quad];
+ currentQuad[index] = {
+ x: Math.round(initialPoint.x + dx),
+ y: Math.round(initialPoint.y + dy),
+ };
+ return {
+ ...prev,
+ perspectiveQuad: currentQuad as [Point2D, Point2D, Point2D, Point2D],
+ };
+ });
+ };
+
+ const handlePointerUp = () => {
+ window.removeEventListener('pointermove', handlePointerMove);
+ window.removeEventListener('pointerup', handlePointerUp);
+ activeDragCleanupRef.current = null;
+ };
+
+ activeDragCleanupRef.current = handlePointerUp;
+ window.addEventListener('pointermove', handlePointerMove);
+ window.addEventListener('pointerup', handlePointerUp);
+ };
+
+ // Start dragging a mesh control point
+ const startDragMeshPoint = (row: number, col: number, e: React.PointerEvent) => {
+ e.stopPropagation();
+ e.preventDefault();
+
+ if (activeDragCleanupRef.current) activeDragCleanupRef.current();
+
+ const startX = e.clientX;
+ const startY = e.clientY;
+ const initialPoint = { ...meshPoints[row][col] };
+
+ const handlePointerMove = (ev: PointerEvent) => {
+ const { dx, dy } = screenDeltaToCanvas(ev.clientX - startX, ev.clientY - startY);
+ onUpdateSession((prev) => {
+ const currentMesh = (prev.meshPoints || meshPoints).map((r) => [...r]);
+ currentMesh[row][col] = {
+ x: Math.round(initialPoint.x + dx),
+ y: Math.round(initialPoint.y + dy),
+ };
+ return {
+ ...prev,
+ meshPoints: currentMesh,
+ };
+ });
+ };
+
+ const handlePointerUp = () => {
+ window.removeEventListener('pointermove', handlePointerMove);
+ window.removeEventListener('pointerup', handlePointerUp);
+ activeDragCleanupRef.current = null;
+ };
+
+ activeDragCleanupRef.current = handlePointerUp;
+ window.addEventListener('pointermove', handlePointerMove);
+ window.addEventListener('pointerup', handlePointerUp);
+ };
- const startDrag = (
- mode: 'move' | 'rotate' | 'scale',
+ // Start dragging affine handles (Move, Rotate, Scale)
+ const startDragAffine = (
+ dragMode: 'move' | 'rotate' | 'scale',
e: React.PointerEvent,
handle?: string
) => {
e.stopPropagation();
e.preventDefault();
- if (activeDragCleanupRef.current) {
- activeDragCleanupRef.current();
- }
+ if (activeDragCleanupRef.current) activeDragCleanupRef.current();
const startX = e.clientX;
const startY = e.clientY;
@@ -81,39 +322,27 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({
const initRot = session.rotation;
const handlePointerMove = (ev: PointerEvent) => {
- const dxScreen = ev.clientX - startX;
- const dyScreen = ev.clientY - startY;
-
- // Un-rotate by viewport canvas rotation and scale by zoom
- const canvasRotRad = (-canvasRotation * Math.PI) / 180;
- const cCos = Math.cos(canvasRotRad);
- const cSin = Math.sin(canvasRotRad);
- const dxCanvas = (dxScreen * cCos - dyScreen * cSin) / zoom;
- const dyCanvas = (dxScreen * cSin + dyScreen * cCos) / zoom;
-
- if (mode === 'move') {
- let finalDx = dxCanvas;
- let finalDy = dyCanvas;
+ const { dx, dy } = screenDeltaToCanvas(ev.clientX - startX, ev.clientY - startY);
+
+ if (dragMode === 'move') {
+ let finalDx = dx;
+ let finalDy = dy;
if (ev.shiftKey) {
- // Axis-lock to horizontal or vertical
- if (Math.abs(finalDx) > Math.abs(finalDy)) {
- finalDy = 0;
- } else {
- finalDx = 0;
- }
+ if (Math.abs(finalDx) > Math.abs(finalDy)) finalDy = 0;
+ else finalDx = 0;
}
onUpdateSession((prev) => ({
...prev,
x: Math.round(initX + finalDx),
y: Math.round(initY + finalDy),
}));
- } else if (mode === 'rotate') {
+ } else if (dragMode === 'rotate') {
const centerX = initX + initW / 2;
const centerY = initY + initH / 2;
- const cursorCanvasX = centerX + dxCanvas;
- const cursorCanvasY = centerY + dyCanvas;
+ const cursorCanvasX = centerX + dx;
+ const cursorCanvasY = centerY + dy;
const angleRad = Math.atan2(cursorCanvasY - centerY, cursorCanvasX - centerX);
- let angleDeg = (angleRad * 180) / Math.PI + 90; // stem is on top (-90 deg from center)
+ let angleDeg = (angleRad * 180) / Math.PI + 90;
if (ev.shiftKey) {
angleDeg = Math.round(angleDeg / 15) * 15;
}
@@ -121,13 +350,12 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({
...prev,
rotation: Math.round(((angleDeg % 360) + 360) % 360),
}));
- } else if (mode === 'scale' && handle) {
- // Convert canvas delta into object's local rotated coordinate frame
+ } else if (dragMode === 'scale' && handle) {
const objRotRad = (-initRot * Math.PI) / 180;
const oCos = Math.cos(objRotRad);
const oSin = Math.sin(objRotRad);
- const dxLocal = dxCanvas * oCos - dyCanvas * oSin;
- const dyLocal = dxCanvas * oSin + dyCanvas * oCos;
+ const dxLocal = dx * oCos - dy * oSin;
+ const dyLocal = dx * oSin + dy * oCos;
const isLeft = handle.includes('w');
const isRight = handle.includes('e');
@@ -156,9 +384,7 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({
}
if (ev.shiftKey && (isLeft || isRight) && (isTop || isBottom)) {
- const scaleW = newW / initW;
- const scaleH = newH / initH;
- const scale = Math.max(scaleW, scaleH);
+ const scale = Math.max(newW / initW, newH / initH);
newW = Math.max(10, Math.round(initW * scale));
newH = Math.max(10, Math.round(initH * scale));
du = isRight ? (newW - initW) / 2 : -(newW - initW) / 2;
@@ -169,15 +395,10 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({
const dCenterX = du * Math.cos(objRotAngle) - dv * Math.sin(objRotAngle);
const dCenterY = du * Math.sin(objRotAngle) + dv * Math.cos(objRotAngle);
- const initCenterX = initX + initW / 2;
- const initCenterY = initY + initH / 2;
- const newCenterX = initCenterX + dCenterX;
- const newCenterY = initCenterY + dCenterY;
-
onUpdateSession((prev) => ({
...prev,
- x: Math.round(newCenterX - newW / 2),
- y: Math.round(newCenterY - newH / 2),
+ x: Math.round(initX + initW / 2 + dCenterX - newW / 2),
+ y: Math.round(initY + initH / 2 + dCenterY - newH / 2),
width: Math.round(newW),
height: Math.round(newH),
}));
@@ -190,12 +411,7 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({
activeDragCleanupRef.current = null;
};
- activeDragCleanupRef.current = () => {
- window.removeEventListener('pointermove', handlePointerMove);
- window.removeEventListener('pointerup', handlePointerUp);
- activeDragCleanupRef.current = null;
- };
-
+ activeDragCleanupRef.current = handlePointerUp;
window.addEventListener('pointermove', handlePointerMove);
window.addEventListener('pointerup', handlePointerUp);
};
@@ -209,190 +425,303 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({
};
const handleReset = () => {
- onUpdateSession((prev) => ({
- ...prev,
- x: prev.bounds.x,
- y: prev.bounds.y,
- width: prev.bounds.width,
- height: prev.bounds.height,
- rotation: 0,
- flipH: false,
- flipV: false,
- }));
+ onUpdateSession((prev) => {
+ const defQuad = createDefaultPerspectiveQuad(prev.bounds.x, prev.bounds.y, prev.bounds.width, prev.bounds.height, 0);
+ return {
+ ...prev,
+ x: prev.bounds.x,
+ y: prev.bounds.y,
+ width: prev.bounds.width,
+ height: prev.bounds.height,
+ rotation: 0,
+ flipH: false,
+ flipV: false,
+ perspectiveQuad: defQuad,
+ meshPoints: createDefaultMeshPoints(defQuad, prev.meshCols || 4, prev.meshRows || 4),
+ };
+ });
};
const invZoom = zoom > 0 ? 1 / zoom : 1;
const handleSize = 8;
+ const pinSize = 10;
return (
- <div
- ref={containerRef}
- className="absolute select-none z-30"
- style={{
- left: `${session.x}px`,
- top: `${session.y}px`,
- width: `${session.width}px`,
- height: `${session.height}px`,
- transform: `rotate(${session.rotation}deg)`,
- transformOrigin: '50% 50%',
- }}
- >
- {/* Transformed Content Preview */}
- <canvas
- ref={previewCanvasRef}
- className="w-full h-full pointer-events-none block"
- style={{
- transform: `scale(${session.flipH ? -1 : 1}, ${session.flipV ? -1 : 1})`,
- imageRendering: 'pixelated',
- }}
- />
-
- {/* Transform Bounding Box Outline (Drag Body to Move) */}
- <div
- onPointerDown={(e) => startDrag('move', e)}
- className="absolute inset-0 border-2 border-cyan-400 bg-cyan-400/5 cursor-move"
- title="Drag to Move (Shift to drag axis-locked)"
- />
-
- {/* Rotation Stem & Handle */}
- <div
- className="absolute left-1/2 top-0 flex flex-col items-center pointer-events-auto"
- style={{
- transform: `translateX(-50%) translateY(calc(-100% - ${4 * invZoom}px)) scale(${invZoom})`,
- transformOrigin: 'bottom center',
- }}
- onPointerDown={(e) => startDrag('rotate', e)}
- title="Drag to Rotate (Shift snaps to 15°)"
- >
- <div className="w-3.5 h-3.5 rounded-full bg-cyan-400 border border-white shadow-md cursor-grab active:cursor-grabbing hover:scale-125 transition-transform" />
- <div className="w-0.5 h-2.5 bg-cyan-400" />
- </div>
-
- {/* Center Pivot Point */}
- <div
- className="absolute left-1/2 top-1/2 w-2 h-2 rounded-full border border-cyan-400 bg-white pointer-events-none shadow-xs"
- style={{
- transform: `translate(-50%, -50%) scale(${invZoom})`,
- transformOrigin: 'center',
- }}
- />
-
- {/* 8 Resize Scale Handles */}
- {/* Top-Left */}
- <div
- onPointerDown={(e) => startDrag('scale', e, 'nw')}
- className="absolute bg-white border border-cyan-500 shadow-sm cursor-nwse-resize hover:scale-125 pointer-events-auto"
- style={{
- left: 0,
- top: 0,
- width: `${handleSize}px`,
- height: `${handleSize}px`,
- transform: `translate(-50%, -50%) scale(${invZoom})`,
- transformOrigin: 'center',
- }}
- />
- {/* Top-Middle */}
- <div
- onPointerDown={(e) => startDrag('scale', e, 'n')}
- className="absolute bg-white border border-cyan-500 shadow-sm cursor-ns-resize hover:scale-125 pointer-events-auto"
- style={{
- left: '50%',
- top: 0,
- width: `${handleSize}px`,
- height: `${handleSize}px`,
- transform: `translate(-50%, -50%) scale(${invZoom})`,
- transformOrigin: 'center',
- }}
- />
- {/* Top-Right */}
- <div
- onPointerDown={(e) => startDrag('scale', e, 'ne')}
- className="absolute bg-white border border-cyan-500 shadow-sm cursor-nesw-resize hover:scale-125 pointer-events-auto"
- style={{
- left: '100%',
- top: 0,
- width: `${handleSize}px`,
- height: `${handleSize}px`,
- transform: `translate(-50%, -50%) scale(${invZoom})`,
- transformOrigin: 'center',
- }}
- />
- {/* Right-Middle */}
- <div
- onPointerDown={(e) => startDrag('scale', e, 'e')}
- className="absolute bg-white border border-cyan-500 shadow-sm cursor-ew-resize hover:scale-125 pointer-events-auto"
- style={{
- left: '100%',
- top: '50%',
- width: `${handleSize}px`,
- height: `${handleSize}px`,
- transform: `translate(-50%, -50%) scale(${invZoom})`,
- transformOrigin: 'center',
- }}
- />
- {/* Bottom-Right */}
- <div
- onPointerDown={(e) => startDrag('scale', e, 'se')}
- className="absolute bg-white border border-cyan-500 shadow-sm cursor-nwse-resize hover:scale-125 pointer-events-auto"
- style={{
- left: '100%',
- top: '100%',
- width: `${handleSize}px`,
- height: `${handleSize}px`,
- transform: `translate(-50%, -50%) scale(${invZoom})`,
- transformOrigin: 'center',
- }}
- />
- {/* Bottom-Middle */}
- <div
- onPointerDown={(e) => startDrag('scale', e, 's')}
- className="absolute bg-white border border-cyan-500 shadow-sm cursor-ns-resize hover:scale-125 pointer-events-auto"
- style={{
- left: '50%',
- top: '100%',
- width: `${handleSize}px`,
- height: `${handleSize}px`,
- transform: `translate(-50%, -50%) scale(${invZoom})`,
- transformOrigin: 'center',
- }}
- />
- {/* Bottom-Left */}
- <div
- onPointerDown={(e) => startDrag('scale', e, 'sw')}
- className="absolute bg-white border border-cyan-500 shadow-sm cursor-nesw-resize hover:scale-125 pointer-events-auto"
- style={{
- left: 0,
- top: '100%',
- width: `${handleSize}px`,
- height: `${handleSize}px`,
- transform: `translate(-50%, -50%) scale(${invZoom})`,
- transformOrigin: 'center',
- }}
- />
- {/* Left-Middle */}
- <div
- onPointerDown={(e) => startDrag('scale', e, 'w')}
- className="absolute bg-white border border-cyan-500 shadow-sm cursor-ew-resize hover:scale-125 pointer-events-auto"
- style={{
- left: 0,
- top: '50%',
- width: `${handleSize}px`,
- height: `${handleSize}px`,
- transform: `translate(-50%, -50%) scale(${invZoom})`,
- transformOrigin: 'center',
- }}
- />
-
- {/* Floating Action Bar (Directly below transform box) */}
+ <>
+ {/* 1. Affine Mode Container */}
+ {mode === 'affine' && (
+ <div
+ ref={containerRef}
+ className="absolute select-none z-30"
+ style={{
+ left: `${session.x}px`,
+ top: `${session.y}px`,
+ width: `${session.width}px`,
+ height: `${session.height}px`,
+ transform: `rotate(${session.rotation}deg)`,
+ transformOrigin: '50% 50%',
+ }}
+ >
+ {/* Preview Canvas */}
+ <canvas
+ ref={previewCanvasRef}
+ className="w-full h-full pointer-events-none block"
+ style={{
+ transform: `scale(${session.flipH ? -1 : 1}, ${session.flipV ? -1 : 1})`,
+ imageRendering: 'pixelated',
+ }}
+ />
+
+ {/* Bounding Box Outline (Drag Body to Move) */}
+ <div
+ onPointerDown={(e) => startDragAffine('move', e)}
+ className="absolute inset-0 border-2 border-cyan-400 bg-cyan-400/5 cursor-move"
+ title="Drag to Move"
+ />
+
+ {/* Rotation Stem & Handle */}
+ <div
+ className="absolute left-1/2 top-0 flex flex-col items-center pointer-events-auto"
+ style={{
+ transform: `translateX(-50%) translateY(calc(-100% - ${4 * invZoom}px)) scale(${invZoom})`,
+ transformOrigin: 'bottom center',
+ }}
+ onPointerDown={(e) => startDragAffine('rotate', e)}
+ title="Drag to Rotate"
+ >
+ <div className="w-3.5 h-3.5 rounded-full bg-cyan-400 border border-white shadow-md cursor-grab active:cursor-grabbing hover:scale-125 transition-transform" />
+ <div className="w-0.5 h-2.5 bg-cyan-400" />
+ </div>
+
+ {/* Center Pivot Point */}
+ <div
+ className="absolute left-1/2 top-1/2 w-2 h-2 rounded-full border border-cyan-400 bg-white pointer-events-none shadow-xs"
+ style={{
+ transform: `translate(-50%, -50%) scale(${invZoom})`,
+ transformOrigin: 'center',
+ }}
+ />
+
+ {/* 8 Resize Scale Handles */}
+ {(['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'] as const).map((h) => {
+ const left = h.includes('w') ? '0%' : h.includes('e') ? '100%' : '50%';
+ const top = h.includes('n') ? '0%' : h.includes('s') ? '100%' : '50%';
+ const cursor =
+ h === 'nw' || h === 'se'
+ ? 'nwse-resize'
+ : h === 'ne' || h === 'sw'
+ ? 'nesw-resize'
+ : h === 'n' || h === 's'
+ ? 'ns-resize'
+ : 'ew-resize';
+
+ return (
+ <div
+ key={h}
+ onPointerDown={(e) => startDragAffine('scale', e, h)}
+ className={`absolute bg-white border border-cyan-500 shadow-sm cursor-${cursor} hover:scale-125 pointer-events-auto`}
+ style={{
+ left,
+ top,
+ width: `${handleSize}px`,
+ height: `${handleSize}px`,
+ transform: `translate(-50%, -50%) scale(${invZoom})`,
+ transformOrigin: 'center',
+ }}
+ />
+ );
+ })}
+ </div>
+ )}
+
+ {/* 2. Perspective or Mesh Warp Preview Canvas & Handles Container */}
+ {(mode === 'perspective' || mode === 'mesh') && (
+ <>
+ {/* Deformed Preview Canvas */}
+ <div
+ className="absolute pointer-events-none z-30"
+ style={{
+ left: `${nonAffineBounds.minX}px`,
+ top: `${nonAffineBounds.minY}px`,
+ width: `${nonAffineBounds.width}px`,
+ height: `${nonAffineBounds.height}px`,
+ }}
+ >
+ <canvas ref={previewCanvasRef} className="w-full h-full block" />
+ </div>
+
+ {/* SVG Overlay for Quad or Mesh Lattice Lines */}
+ <svg
+ className="absolute inset-0 pointer-events-none z-31 overflow-visible"
+ style={{ width: '100%', height: '100%' }}
+ >
+ {mode === 'perspective' && (
+ <>
+ {/* Perspective Quad Polygon Outline */}
+ <polygon
+ points={`${quad[0].x},${quad[0].y} ${quad[1].x},${quad[1].y} ${quad[2].x},${quad[2].y} ${quad[3].x},${quad[3].y}`}
+ fill="none"
+ stroke="#22d3ee"
+ strokeWidth={1.5 * invZoom}
+ strokeDasharray={`${4 * invZoom} ${4 * invZoom}`}
+ />
+ </>
+ )}
+
+ {mode === 'mesh' && (
+ <>
+ {/* Horizontal Mesh Lattice Lines */}
+ {meshPoints.map((row, r) => (
+ <polyline
+ key={`h-${r}`}
+ points={row.map((p) => `${p.x},${p.y}`).join(' ')}
+ fill="none"
+ stroke="#22d3ee"
+ strokeWidth={1.2 * invZoom}
+ strokeDasharray={`${3 * invZoom} ${3 * invZoom}`}
+ />
+ ))}
+
+ {/* Vertical Mesh Lattice Lines */}
+ {meshPoints[0]?.map((_, c) => (
+ <polyline
+ key={`v-${c}`}
+ points={meshPoints.map((row) => `${row[c].x},${row[c].y}`).join(' ')}
+ fill="none"
+ stroke="#22d3ee"
+ strokeWidth={1.2 * invZoom}
+ strokeDasharray={`${3 * invZoom} ${3 * invZoom}`}
+ />
+ ))}
+ </>
+ )}
+ </svg>
+
+ {/* Perspective Corner Pin Control Handles */}
+ {mode === 'perspective' &&
+ quad.map((pt, idx) => (
+ <div
+ key={idx}
+ onPointerDown={(e) => startDragPerspectiveCorner(idx, e)}
+ className="absolute z-33 bg-white border-2 border-cyan-500 rounded-full shadow-md cursor-grab active:cursor-grabbing hover:scale-125 transition-transform pointer-events-auto"
+ style={{
+ left: `${pt.x}px`,
+ top: `${pt.y}px`,
+ width: `${pinSize}px`,
+ height: `${pinSize}px`,
+ transform: `translate(-50%, -50%) scale(${invZoom})`,
+ transformOrigin: 'center',
+ }}
+ title={`Corner Pin ${idx + 1}`}
+ />
+ ))}
+
+ {/* Mesh Warp Control Handles */}
+ {mode === 'mesh' &&
+ meshPoints.map((row, r) =>
+ row.map((pt, c) => (
+ <div
+ key={`${r}-${c}`}
+ onPointerDown={(e) => startDragMeshPoint(r, c, e)}
+ className={`absolute z-33 rounded-full border shadow-sm cursor-grab active:cursor-grabbing hover:scale-125 pointer-events-auto ${
+ r === 0 || r === meshPoints.length - 1 || c === 0 || c === row.length - 1
+ ? 'bg-cyan-400 border-white'
+ : 'bg-white border-cyan-500'
+ }`}
+ style={{
+ left: `${pt.x}px`,
+ top: `${pt.y}px`,
+ width: `${handleSize}px`,
+ height: `${handleSize}px`,
+ transform: `translate(-50%, -50%) scale(${invZoom})`,
+ transformOrigin: 'center',
+ }}
+ title={`Mesh Handle [${r}, ${c}]`}
+ />
+ ))
+ )}
+ </>
+ )}
+
+ {/* 3. Floating Transform Toolbar (Pinned below transform boundary) */}
<div
- className="absolute left-1/2 top-full bg-[#1b1c1e] border border-[#33353b] rounded shadow-xl px-2 py-1 flex items-center space-x-1.5 z-40 whitespace-nowrap"
+ className="absolute z-40 bg-[#18191b] border border-[#33353b] rounded shadow-2xl px-2 py-1 flex items-center space-x-1.5 whitespace-nowrap select-none text-xs"
style={{
+ left: `${nonAffineBounds.minX + nonAffineBounds.width / 2}px`,
+ top: `${nonAffineBounds.maxY}px`,
transform: `translateX(-50%) translateY(${16 * invZoom}px) scale(${invZoom})`,
transformOrigin: 'top center',
}}
onPointerDown={(e) => e.stopPropagation()}
>
- {/* Confirm (Enter) */}
+ {/* Mode Switchers */}
+ <div className="flex items-center space-x-0.5 bg-[#202226] p-0.5 rounded border border-[#2b2d31]">
+ <button
+ onClick={() => handleSwitchMode('affine')}
+ title="Free Transform (Affine Scale & Rotate)"
+ className={`px-1.5 py-1 rounded text-[11px] font-medium flex items-center space-x-1 cursor-pointer transition-colors ${
+ mode === 'affine'
+ ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b]'
+ : 'text-[#888888] hover:text-white'
+ }`}
+ >
+ <BoxSelect className="w-3.5 h-3.5" />
+ <span>Free</span>
+ </button>
+
+ <button
+ onClick={() => handleSwitchMode('perspective')}
+ title="Perspective Quad (4-Point Homography)"
+ className={`px-1.5 py-1 rounded text-[11px] font-medium flex items-center space-x-1 cursor-pointer transition-colors ${
+ mode === 'perspective'
+ ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b]'
+ : 'text-[#888888] hover:text-white'
+ }`}
+ >
+ <Square className="w-3.5 h-3.5" />
+ <span>Perspective</span>
+ </button>
+
+ <button
+ onClick={() => handleSwitchMode('mesh')}
+ title="Mesh Warp (Catmull-Rom Bezier Lattice)"
+ className={`px-1.5 py-1 rounded text-[11px] font-medium flex items-center space-x-1 cursor-pointer transition-colors ${
+ mode === 'mesh'
+ ? 'bg-[#293d45] text-[#5ce1e6] border border-[#3e5e6b]'
+ : 'text-[#888888] hover:text-white'
+ }`}
+ >
+ <Grid3X3 className="w-3.5 h-3.5" />
+ <span>Mesh Warp</span>
+ </button>
+ </div>
+
+ {/* Mesh Grid Density Selector (when in mesh mode) */}
+ {mode === 'mesh' && (
+ <>
+ <div className="w-px h-4 bg-[#33353b]" />
+ <div className="flex items-center space-x-1 text-[11px] text-[#aaaaaa]">
+ <span>Grid:</span>
+ {[3, 4, 5, 6, 8].map((size) => (
+ <button
+ key={size}
+ onClick={() => handleChangeMeshGrid(size)}
+ className={`px-1 py-0.5 rounded cursor-pointer transition-colors ${
+ (session.meshCols || 4) === size
+ ? 'bg-cyan-500/30 text-cyan-300 font-bold'
+ : 'hover:text-white hover:bg-[#25272a]'
+ }`}
+ >
+ {size}x{size}
+ </button>
+ ))}
+ </div>
+ </>
+ )}
+
+ <div className="w-px h-4 bg-[#33353b]" />
+
+ {/* Apply */}
<button
onClick={onApply}
title="Apply Transform (Enter)"
@@ -402,7 +731,7 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({
<span>Apply</span>
</button>
- {/* Cancel (Esc) */}
+ {/* Cancel */}
<button
onClick={onCancel}
title="Cancel Transform (Esc)"
@@ -445,6 +774,6 @@ export const TransformOverlay: React.FC<TransformOverlayProps> = ({
<RotateCcw className="w-3.5 h-3.5" />
</button>
</div>
- </div>
+ </>
);
};
diff --git a/src/hooks/useCanvasDrawing.ts b/src/hooks/useCanvasDrawing.ts
index 1bdade4..c083efa 100644
--- a/src/hooks/useCanvasDrawing.ts
+++ b/src/hooks/useCanvasDrawing.ts
@@ -67,6 +67,8 @@ interface UseCanvasDrawingProps {
layerSourceCanvasesRef?: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
layers?: LayerItem[];
onUpdateLayerThumbnail: (layerId: string) => void;
+ isMaskMode?: boolean;
+ onUpdateMaskThumbnail?: (layerId: string) => void;
draftCanvasRef?: React.RefObject<HTMLCanvasElement | null>;
strokeCanvasRef?: React.RefObject<HTMLCanvasElement | null>;
onCollabStrokeStart?: (strokeId: string, layerId: string, brushSettings: BrushSettings, tool: ToolType, startPoint: Point) => void;
@@ -94,6 +96,8 @@ export function useCanvasDrawing({
layerSourceCanvasesRef,
layers,
onUpdateLayerThumbnail,
+ isMaskMode = false,
+ onUpdateMaskThumbnail,
draftCanvasRef,
strokeCanvasRef,
onCollabStrokeStart,
@@ -132,6 +136,8 @@ export function useCanvasDrawing({
const activeLayerLockedRef = useRef(activeLayerLocked);
const activeLayerVisibleRef = useRef(activeLayerVisible);
const dimensionsRef = useRef(dimensions);
+ const isMaskModeRef = useRef(isMaskMode);
+ const onUpdateMaskThumbnailRef = useRef(onUpdateMaskThumbnail);
// Synchronously keep refs fresh during render execution
panRef.current = pan;
@@ -145,6 +151,8 @@ export function useCanvasDrawing({
activeLayerVisibleRef.current = activeLayerVisible;
dimensionsRef.current = dimensions;
layersRef.current = layers;
+ isMaskModeRef.current = isMaskMode;
+ onUpdateMaskThumbnailRef.current = onUpdateMaskThumbnail;
const onCollabStrokeStartRef = useRef(onCollabStrokeStart);
const onCollabStrokeChunkRef = useRef(onCollabStrokeChunk);
@@ -169,6 +177,8 @@ export function useCanvasDrawing({
activeLayerVisibleRef.current = activeLayerVisible;
dimensionsRef.current = dimensions;
layersRef.current = layers;
+ isMaskModeRef.current = isMaskMode;
+ onUpdateMaskThumbnailRef.current = onUpdateMaskThumbnail;
rulerRef.current = perspectiveRuler;
onActiveConstraintAxisChangeRef.current = onActiveConstraintAxisChange;
@@ -287,6 +297,12 @@ export function useCanvasDrawing({
const getActiveCanvas = useCallback(() => {
const targetId = activeLayerIdRef.current || activeLayerId;
+ if (isMaskModeRef.current) {
+ const activeLayer = layersRef.current?.find((l) => l.id === targetId);
+ if (activeLayer?.maskCanvas) {
+ return activeLayer.maskCanvas;
+ }
+ }
return (
layerCanvasesRef.current.get(targetId) ||
layerCanvasesRef.current.get('layer-1') ||
@@ -978,7 +994,23 @@ export function useCanvasDrawing({
const isTone = isToneStrokeRef.current;
const sourceCanvas = isTone ? layerSourceCanvasesRef?.current?.get(currentLayerId) : null;
- const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, isMonochrome ? 'monochrome' : mode);
+ let strokeColor: string;
+ if (isMaskModeRef.current) {
+ if (isEraser) {
+ strokeColor = '#000000';
+ } else {
+ let clean = bs.color.replace('#', '');
+ if (clean.length === 3) clean = clean.split('').map((c) => c + c).join('');
+ const r = parseInt(clean.slice(0, 2), 16) || 0;
+ const g = parseInt(clean.slice(2, 4), 16) || 0;
+ const b = parseInt(clean.slice(4, 6), 16) || 0;
+ const gray = Math.round(0.299 * r + 0.587 * g + 0.114 * b);
+ const hexVal = gray.toString(16).padStart(2, '0');
+ strokeColor = `#${hexVal}${hexVal}${hexVal}`;
+ }
+ } else {
+ strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, isMonochrome ? 'monochrome' : mode);
+ }
const strokeHardness = isMonochrome ? 1.0 : (bs.hardness ?? 1.0);
const strokeFlow = bs.flow ?? 1.0;
const strokeSpacing = bs.spacing ?? 0.08;
@@ -1495,7 +1527,23 @@ export function useCanvasDrawing({
maxY: Math.min(dims.height, Math.ceil(startPoint.y + r)),
};
- const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, isMonochrome ? 'monochrome' : mode);
+ let strokeColor: string;
+ if (isMaskModeRef.current) {
+ if (isEraser) {
+ strokeColor = '#000000';
+ } else {
+ let clean = bs.color.replace('#', '');
+ if (clean.length === 3) clean = clean.split('').map((c) => c + c).join('');
+ const r = parseInt(clean.slice(0, 2), 16) || 0;
+ const g = parseInt(clean.slice(2, 4), 16) || 0;
+ const b = parseInt(clean.slice(4, 6), 16) || 0;
+ const gray = Math.round(0.299 * r + 0.587 * g + 0.114 * b);
+ const hexVal = gray.toString(16).padStart(2, '0');
+ strokeColor = `#${hexVal}${hexVal}${hexVal}`;
+ }
+ } else {
+ strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, isMonochrome ? 'monochrome' : mode);
+ }
const strokeHardness = isMonochrome ? 1.0 : (bs.hardness ?? 1.0);
const strokeFlow = bs.flow ?? 1.0;
@@ -1878,7 +1926,23 @@ export function useCanvasDrawing({
? get2DContext(sourceCanvas)
: (drewDirectlyOnLayerCanvasRef.current && canvas ? get2DContext(canvas) : draftCtx);
- const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, isMonochrome ? 'monochrome' : mode);
+ let strokeColor: string;
+ if (isMaskModeRef.current) {
+ if (isEraser) {
+ strokeColor = '#000000';
+ } else {
+ let clean = bs.color.replace('#', '');
+ if (clean.length === 3) clean = clean.split('').map((c) => c + c).join('');
+ const r = parseInt(clean.slice(0, 2), 16) || 0;
+ const g = parseInt(clean.slice(2, 4), 16) || 0;
+ const b = parseInt(clean.slice(4, 6), 16) || 0;
+ const gray = Math.round(0.299 * r + 0.587 * g + 0.114 * b);
+ const hexVal = gray.toString(16).padStart(2, '0');
+ strokeColor = `#${hexVal}${hexVal}${hexVal}`;
+ }
+ } else {
+ strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, isMonochrome ? 'monochrome' : mode);
+ }
const strokeHardness = isMonochrome ? 1.0 : (bs.hardness ?? 1.0);
if (targetTailCtx && pts.length >= 2) {
@@ -2401,7 +2465,12 @@ export function useCanvasDrawing({
snapSessionRef.current.endStroke();
onActiveConstraintAxisChangeRef.current?.(null);
- onUpdateLayerThumbnail(currentLayerId);
+ if (isMaskModeRef.current) {
+ onUpdateMaskThumbnailRef.current?.(currentLayerId);
+ globalTileGrid.notifyChange(true);
+ } else {
+ onUpdateLayerThumbnail(currentLayerId);
+ }
},
[
applyStabilizedPointAndRender,
diff --git a/src/hooks/useLayerManager.ts b/src/hooks/useLayerManager.ts
index a7d01e3..4a43728 100644
--- a/src/hooks/useLayerManager.ts
+++ b/src/hooks/useLayerManager.ts
@@ -1,5 +1,5 @@
import { useState, useRef, useCallback, useEffect } from 'react';
-import { LayerItem, BlendMode, CanvasDimensions, CanvasColorMode, LoadedDocument, ExpressionColor, CanvasSelection, DirtyRect } from '../types/editor';
+import { LayerItem, BlendMode, CanvasDimensions, CanvasColorMode, LoadedDocument, ExpressionColor, CanvasSelection, DirtyRect, AdjustmentLayerData } from '../types/editor';
import { ResizeCanvasOptions } from '../types/settings';
import { createCanvasThumbnail, get2DContext } from '../utils/canvasUtils';
import { applyLayerEffects, applyExpressionColorToImageData } from '../utils/layerEffectsEngine';
@@ -173,10 +173,10 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
}
}, []);
- // Add a new raster layer or folder
+ // Add a new raster layer, folder, or adjustment layer
const addLayer = useCallback(
(
- type: 'raster' | 'folder' | 'vector' | 'frame' = 'raster',
+ type: 'raster' | 'folder' | 'vector' | 'frame' | 'adjustment' = 'raster',
explicitParentId?: string | null,
customName?: string,
customId?: string
@@ -206,7 +206,8 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
const prefix =
type === 'folder' ? 'Folder ' :
type === 'vector' ? 'Vector ' :
- type === 'frame' ? 'Frame ' : 'Layer ';
+ type === 'frame' ? 'Frame ' :
+ type === 'adjustment' ? 'Adjustment ' : 'Layer ';
prev.forEach((l) => {
if (l.type === type && l.name.startsWith(prefix)) {
const num = parseInt(l.name.replace(prefix, ''), 10);
@@ -360,11 +361,25 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
layerSourceCanvasesRef.current.set(newId, newSource);
}
+ let newMaskCanvas: HTMLCanvasElement | undefined;
+ let newMaskThumb: string | undefined;
+ if (source.maskCanvas) {
+ newMaskCanvas = document.createElement('canvas');
+ newMaskCanvas.width = source.maskCanvas.width;
+ newMaskCanvas.height = source.maskCanvas.height;
+ const mCtx = get2DContext(newMaskCanvas);
+ if (mCtx) mCtx.drawImage(source.maskCanvas, 0, 0);
+ newMaskThumb = source.maskThumbnailUrl;
+ }
+
const newLayer: LayerItem = {
...source,
id: newId,
name: `${source.name} Copy`,
thumbnailUrl: source.thumbnailUrl,
+ maskCanvas: newMaskCanvas,
+ maskThumbnailUrl: newMaskThumb,
+ adjustmentData: source.adjustmentData ? JSON.parse(JSON.stringify(source.adjustmentData)) : undefined,
};
const nextLayers = [...prev];
@@ -489,6 +504,220 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
);
}, []);
+ // Add a non-destructive grayscale Layer Mask
+ const addLayerMask = useCallback((layerId: string) => {
+ setLayers((prev) =>
+ prev.map((l) => {
+ if (l.id !== layerId) return l;
+ if (l.maskCanvas) return l; // Already has mask
+
+ const mask = document.createElement('canvas');
+ mask.width = _dimensions.width;
+ mask.height = _dimensions.height;
+ const mCtx = get2DContext(mask);
+ if (mCtx) {
+ mCtx.fillStyle = '#ffffff';
+ mCtx.fillRect(0, 0, mask.width, mask.height);
+ }
+ const thumb = createCanvasThumbnail(mask, false);
+ return {
+ ...l,
+ maskCanvas: mask,
+ maskEnabled: true,
+ maskLinked: true,
+ maskThumbnailUrl: thumb,
+ };
+ })
+ );
+ globalTileGrid.notifyChange(true);
+ }, [_dimensions]);
+
+ // Remove or apply layer mask
+ const removeLayerMask = useCallback(
+ (layerId: string, apply: boolean = false) => {
+ setLayers((prev) =>
+ prev.map((l) => {
+ if (l.id !== layerId || !l.maskCanvas) return l;
+
+ if (apply) {
+ const c = layerCanvasesRef.current.get(layerId);
+ if (c) {
+ const ctx = get2DContext(c);
+ const mCtx = get2DContext(l.maskCanvas);
+ if (ctx && mCtx) {
+ const imgData = ctx.getImageData(0, 0, c.width, c.height);
+ const maskData = mCtx.getImageData(0, 0, c.width, c.height).data;
+ const d = imgData.data;
+ for (let i = 0; i < d.length; i += 4) {
+ if (d[i + 3] === 0) continue;
+ const maskLum =
+ ((0.299 * maskData[i] + 0.587 * maskData[i + 1] + 0.114 * maskData[i + 2]) / 255) *
+ (maskData[i + 3] / 255);
+ d[i + 3] = Math.round(d[i + 3] * maskLum);
+ }
+ ctx.putImageData(imgData, 0, 0);
+ updateLayerThumbnail(layerId, true);
+ }
+ }
+ }
+
+ return {
+ ...l,
+ maskCanvas: undefined,
+ maskEnabled: undefined,
+ maskLinked: undefined,
+ maskThumbnailUrl: undefined,
+ };
+ })
+ );
+ globalTileGrid.notifyChange(true);
+ },
+ [updateLayerThumbnail]
+ );
+
+ // Toggle layer mask enabled state
+ const toggleLayerMask = useCallback((layerId: string) => {
+ setLayers((prev) =>
+ prev.map((l) => (l.id === layerId ? { ...l, maskEnabled: !l.maskEnabled } : l))
+ );
+ globalTileGrid.notifyChange(true);
+ }, []);
+
+ // Toggle mask linked state
+ const toggleMaskLinked = useCallback((layerId: string) => {
+ setLayers((prev) =>
+ prev.map((l) => (l.id === layerId ? { ...l, maskLinked: !l.maskLinked } : l))
+ );
+ }, []);
+
+ // Update mask thumbnail
+ const updateMaskThumbnail = useCallback((layerId: string, immediate: boolean = false) => {
+ const run = () => {
+ const target = layersRef.current.find((l) => l.id === layerId);
+ if (!target?.maskCanvas) return;
+ const thumb = createCanvasThumbnail(target.maskCanvas, false);
+ setLayers((prev) =>
+ prev.map((l) => (l.id === layerId ? { ...l, maskThumbnailUrl: thumb } : l))
+ );
+ };
+
+ if (immediate) {
+ run();
+ } else {
+ setTimeout(run, 150);
+ }
+ }, []);
+
+ // Add non-destructive adjustment layer
+ const addAdjustmentLayer = useCallback(
+ (
+ type: 'curves' | 'gradient-map' | 'levels' | 'color-balance',
+ customData?: AdjustmentLayerData
+ ): LayerItem => {
+ let createdLayer: LayerItem | null = null;
+ const id = `adjustment-${Date.now()}-${Math.random().toString(36).substring(2, 6)}`;
+
+ let defaultData: AdjustmentLayerData;
+ let layerName: string;
+
+ switch (type) {
+ case 'curves':
+ layerName = 'Curves 1';
+ defaultData = customData || {
+ type: 'curves',
+ curves: {
+ rgb: [[0, 0], [255, 255]],
+ r: [[0, 0], [255, 255]],
+ g: [[0, 0], [255, 255]],
+ b: [[0, 0], [255, 255]],
+ },
+ };
+ break;
+ case 'gradient-map':
+ layerName = 'Gradient Map 1';
+ defaultData = customData || {
+ type: 'gradient-map',
+ stops: [
+ { position: 0, color: '#000000' },
+ { position: 1, color: '#ffffff' },
+ ],
+ interpolation: 'smooth',
+ };
+ break;
+ case 'levels':
+ layerName = 'Levels 1';
+ defaultData = customData || {
+ type: 'levels',
+ blackPoint: 0,
+ gamma: 1.0,
+ whitePoint: 255,
+ outputMin: 0,
+ outputMax: 255,
+ channel: 'rgb',
+ };
+ break;
+ case 'color-balance':
+ layerName = 'Color Balance 1';
+ defaultData = customData || {
+ type: 'color-balance',
+ shadows: [0, 0, 0],
+ midtones: [0, 0, 0],
+ highlights: [0, 0, 0],
+ preserveLuminosity: true,
+ };
+ break;
+ }
+
+ setLayers((prev) => {
+ const activeIdx = prev.findIndex((l) => l.id === activeLayerId);
+ const activeLayer = prev[activeIdx];
+ const parentId = activeLayer ? (activeLayer.type === 'folder' ? activeLayer.id : activeLayer.parentId) : null;
+
+ let count = 1;
+ const base = layerName.replace(/ \d+$/, '');
+ prev.forEach((l) => {
+ if (l.name.startsWith(base)) {
+ const num = parseInt(l.name.replace(`${base} `, ''), 10);
+ if (!isNaN(num) && num >= count) count = num + 1;
+ }
+ });
+ const name = `${base} ${count}`;
+
+ const newLayer: LayerItem = {
+ id,
+ name,
+ type: 'adjustment',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ collapsed: false,
+ parentId,
+ adjustmentData: defaultData,
+ };
+ createdLayer = newLayer;
+
+ const insertIndex = activeIdx >= 0 ? activeIdx : 0;
+ const next = [...prev];
+ next.splice(insertIndex, 0, newLayer);
+ return next;
+ });
+
+ setActiveLayerId(id);
+ globalTileGrid.notifyChange(true);
+ return createdLayer!;
+ },
+ [activeLayerId]
+ );
+
+ // Update adjustment layer data
+ const updateAdjustmentData = useCallback((layerId: string, data: AdjustmentLayerData) => {
+ setLayers((prev) =>
+ prev.map((l) => (l.id === layerId ? { ...l, adjustmentData: data } : l))
+ );
+ globalTileGrid.notifyChange(true);
+ }, []);
+
// Ensure offscreen source canvas exists for non-destructive operations
const ensureSourceCanvas = useCallback(
(id: string, copyFromDisplay = true, forceCopy = false) => {
@@ -1704,6 +1933,13 @@ export function useLayerManager({ dimensions: _dimensions }: UseLayerManagerProp
},
clearDocument,
loadDocument,
+ addLayerMask,
+ removeLayerMask,
+ toggleLayerMask,
+ toggleMaskLinked,
+ updateMaskThumbnail,
+ addAdjustmentLayer,
+ updateAdjustmentData,
};
}
diff --git a/src/types/editor.ts b/src/types/editor.ts
index fc50f81..2509161 100644
--- a/src/types/editor.ts
+++ b/src/types/editor.ts
@@ -7,6 +7,9 @@ export type ToolType =
| 'transform'
| 'select-rect'
| 'select-lasso'
+ | 'select-wand'
+ | 'select-pen'
+ | 'select-eraser'
| 'fill'
| 'text'
| 'frame'
@@ -258,10 +261,28 @@ export interface FrameSettings {
fillColor: string;
}
+export interface WandSettings {
+ tolerance: number; // 0 - 255
+ contiguous: boolean;
+ antiAlias: boolean;
+ referMode: 'active' | 'all' | 'reference';
+}
+
+export interface Point2D {
+ x: number;
+ y: number;
+}
+
+export type TransformMode = 'affine' | 'perspective' | 'mesh';
+
export interface CanvasSelection {
- type: 'rect' | 'lasso';
+ type: 'rect' | 'lasso' | 'wand' | 'mask';
bounds: { x: number; y: number; width: number; height: number };
polygon?: Array<{ x: number; y: number }>;
+ mask?: Uint8Array;
+ maskWidth?: number;
+ maskHeight?: number;
+ svgPath?: string;
floating?: {
canvas: HTMLCanvasElement;
x: number;
@@ -287,6 +308,11 @@ export interface TransformSession {
flipH: boolean;
flipV: boolean;
isSelection?: boolean;
+ mode: TransformMode;
+ perspectiveQuad?: [Point2D, Point2D, Point2D, Point2D];
+ meshCols?: number;
+ meshRows?: number;
+ meshPoints?: Point2D[][];
}
export type BlendMode =
@@ -376,10 +402,59 @@ export interface HistoryItem extends HistoryItemMeta {
export type ExpressionColor = 'color' | 'gray' | 'monochrome';
+export type FilterType = 'gaussian-blur' | 'motion-blur' | 'unsharp-mask' | 'film-grain';
+
+export interface ToneCurvePoints {
+ rgb: [number, number][];
+ r: [number, number][];
+ g: [number, number][];
+ b: [number, number][];
+}
+
+export interface GradientStop {
+ position: number; // 0.0 to 1.0
+ color: string; // hex color (#rrggbb)
+}
+
+export interface CurvesAdjustmentData {
+ type: 'curves';
+ curves: ToneCurvePoints;
+}
+
+export interface GradientMapAdjustmentData {
+ type: 'gradient-map';
+ stops: GradientStop[];
+ interpolation?: 'linear' | 'smooth';
+}
+
+export interface LevelsAdjustmentData {
+ type: 'levels';
+ blackPoint: number; // 0 to 253
+ gamma: number; // 0.1 to 9.99
+ whitePoint: number; // 2 to 255
+ outputMin?: number; // 0 to 255
+ outputMax?: number; // 0 to 255
+ channel?: 'rgb' | 'r' | 'g' | 'b';
+}
+
+export interface ColorBalanceAdjustmentData {
+ type: 'color-balance';
+ shadows: [number, number, number]; // Cyan-Red, Magenta-Green, Yellow-Blue (-100 to 100)
+ midtones: [number, number, number]; // Cyan-Red, Magenta-Green, Yellow-Blue (-100 to 100)
+ highlights: [number, number, number]; // Cyan-Red, Magenta-Green, Yellow-Blue (-100 to 100)
+ preserveLuminosity?: boolean;
+}
+
+export type AdjustmentLayerData =
+ | CurvesAdjustmentData
+ | GradientMapAdjustmentData
+ | LevelsAdjustmentData
+ | ColorBalanceAdjustmentData;
+
export interface LayerItem {
id: string;
name: string;
- type: 'raster' | 'folder' | 'vector' | 'frame';
+ type: 'raster' | 'folder' | 'vector' | 'frame' | 'adjustment';
visible: boolean;
opacity: number; // 0.0 to 1.0
blendMode: BlendMode;
@@ -389,6 +464,7 @@ export interface LayerItem {
collapsed?: boolean;
parentId: string | null; // null for root, or folder id
thumbnailUrl?: string; // live layer thumbnail data URL
+ isReference?: boolean; // Clip Studio Paint Reference Layer toggle
// Screentone (CSP Tone Effect)
toneEnabled?: boolean;
toneFrequency?: number; // Lines / LPI (20 to 85, default: 60)
@@ -405,6 +481,13 @@ export interface LayerItem {
monoThreshold?: number; // 1 to 255 (default: 128)
monoExpressBlack?: boolean; // Express black in monochrome (default: true)
monoExpressWhite?: boolean; // Express white in monochrome (default: true)
+ // Non-destructive Layer Mask
+ maskCanvas?: HTMLCanvasElement;
+ maskEnabled?: boolean;
+ maskLinked?: boolean;
+ maskThumbnailUrl?: string;
+ // Non-destructive Adjustment Layer
+ adjustmentData?: AdjustmentLayerData;
// Vector Layer Data
vectorStrokes?: VectorStroke[];
// Comic Frame Data
diff --git a/src/utils/__tests__/selectionAndTransform.test.ts b/src/utils/__tests__/selectionAndTransform.test.ts
new file mode 100644
index 0000000..2f382e3
--- /dev/null
+++ b/src/utils/__tests__/selectionAndTransform.test.ts
@@ -0,0 +1,172 @@
+import { describe, it, expect } from 'vitest';
+import {
+ expandSelection,
+ contractSelection,
+ featherSelection,
+ invertSelection,
+ maskToBounds,
+ maskToSvgPath,
+ floodSelectWand,
+} from '../selectionUtils';
+import {
+ solveUnitSquareToQuad,
+ evaluateHomography,
+ createDefaultPerspectiveQuad,
+ createDefaultMeshPoints,
+ evaluateMeshSurface,
+} from '../transformEngine';
+
+describe('Selection Boundary Modifiers and Wand', () => {
+ it('correctly expands a 10x10 binary mask by 2 pixels', () => {
+ const w = 20;
+ const h = 20;
+ const mask = new Uint8Array(w * h);
+ // Draw a 4x4 square in the center (x: 8..11, y: 8..11)
+ for (let y = 8; y <= 11; y++) {
+ for (let x = 8; x <= 11; x++) {
+ mask[y * w + x] = 255;
+ }
+ }
+
+ const expanded = expandSelection(mask, w, h, 2);
+ // Bounds before: 4x4
+ const boundsBefore = maskToBounds(mask, w, h);
+ expect(boundsBefore).toEqual({ x: 8, y: 8, width: 4, height: 4 });
+
+ // Bounds after: 8x8 (expanded by 2 on all sides)
+ const boundsAfter = maskToBounds(expanded, w, h);
+ expect(boundsAfter).toEqual({ x: 6, y: 6, width: 8, height: 8 });
+ });
+
+ it('correctly contracts an 8x8 square by 2 pixels', () => {
+ const w = 20;
+ const h = 20;
+ const mask = new Uint8Array(w * h);
+ for (let y = 6; y <= 13; y++) {
+ for (let x = 6; x <= 13; x++) {
+ mask[y * w + x] = 255;
+ }
+ }
+
+ const contracted = contractSelection(mask, w, h, 2);
+ const boundsAfter = maskToBounds(contracted, w, h);
+ expect(boundsAfter).toEqual({ x: 8, y: 8, width: 4, height: 4 });
+ });
+
+ it('inverts an 8-bit selection mask', () => {
+ const w = 4;
+ const h = 4;
+ const mask = new Uint8Array(w * h);
+ mask[0] = 255;
+ mask[5] = 128;
+
+ const inverted = invertSelection(mask, w, h);
+ expect(inverted[0]).toBe(0);
+ expect(inverted[1]).toBe(255);
+ expect(inverted[5]).toBe(127);
+ });
+
+ it('feathers selection mask boundary with Gaussian blur', () => {
+ const w = 16;
+ const h = 16;
+ const mask = new Uint8Array(w * h);
+ for (let y = 4; y <= 11; y++) {
+ for (let x = 4; x <= 11; x++) {
+ mask[y * w + x] = 255;
+ }
+ }
+
+ const feathered = featherSelection(mask, w, h, 2);
+ // Center pixel should remain relatively high
+ expect(feathered[8 * w + 8]).toBeGreaterThan(200);
+ // Boundary adjacent pixel outside should now have non-zero feathered alpha
+ expect(feathered[3 * w + 8]).toBeGreaterThan(0);
+ expect(feathered[3 * w + 8]).toBeLessThan(255);
+ });
+
+ it('converts mask to closed SVG polygon path', () => {
+ const w = 10;
+ const h = 10;
+ const mask = new Uint8Array(w * h);
+ for (let y = 2; y <= 5; y++) {
+ for (let x = 2; x <= 5; x++) {
+ mask[y * w + x] = 255;
+ }
+ }
+ const svg = maskToSvgPath(mask, w, h);
+ expect(svg.startsWith('M ')).toBe(true);
+ expect(svg.endsWith('Z')).toBe(true);
+ });
+
+ it('flood selects contiguous area with tolerance', () => {
+ const w = 10;
+ const h = 10;
+ const imgData = new Uint8ClampedArray(w * h * 4);
+ // Fill all with red (255, 0, 0, 255)
+ for (let i = 0; i < w * h; i++) {
+ imgData[i * 4] = 255;
+ imgData[i * 4 + 1] = 0;
+ imgData[i * 4 + 2] = 0;
+ imgData[i * 4 + 3] = 255;
+ }
+ // Set a 2x2 green area
+ for (let y = 4; y <= 5; y++) {
+ for (let x = 4; x <= 5; x++) {
+ const idx = (y * w + x) * 4;
+ imgData[idx] = 0;
+ imgData[idx + 1] = 255;
+ imgData[idx + 2] = 0;
+ }
+ }
+
+ const wandRes = floodSelectWand(imgData, w, h, 4, 4, {
+ tolerance: 10,
+ contiguous: true,
+ antiAlias: false,
+ referMode: 'active',
+ });
+
+ expect(wandRes.bounds).toEqual({ x: 4, y: 4, width: 2, height: 2 });
+ expect(wandRes.mask[4 * w + 4]).toBe(255);
+ expect(wandRes.mask[0]).toBe(0);
+ });
+});
+
+describe('Perspective and Mesh Transformation Engine', () => {
+ it('solves homography and correctly maps unit square to destination quad', () => {
+ const quad = [
+ { x: 10, y: 10 },
+ { x: 110, y: 10 },
+ { x: 110, y: 110 },
+ { x: 10, y: 110 },
+ ];
+ const H = solveUnitSquareToQuad(quad[0], quad[1], quad[2], quad[3]);
+ expect(H).not.toBeNull();
+
+ // Map unit corners (0,0), (1,0), (1,1), (0,1)
+ const p00 = evaluateHomography(H, 0, 0);
+ const p10 = evaluateHomography(H, 1, 0);
+ const p11 = evaluateHomography(H, 1, 1);
+ const p01 = evaluateHomography(H, 0, 1);
+
+ expect(p00.x).toBeCloseTo(10, 3);
+ expect(p00.y).toBeCloseTo(10, 3);
+ expect(p10.x).toBeCloseTo(110, 3);
+ expect(p10.y).toBeCloseTo(10, 3);
+ expect(p11.x).toBeCloseTo(110, 3);
+ expect(p11.y).toBeCloseTo(110, 3);
+ expect(p01.x).toBeCloseTo(10, 3);
+ expect(p01.y).toBeCloseTo(110, 3);
+ });
+
+ it('generates bicubic mesh lattice and samples surface', () => {
+ const quad = createDefaultPerspectiveQuad(0, 0, 100, 100, 0);
+ const mesh = createDefaultMeshPoints(quad, 4, 4);
+ expect(mesh.length).toBe(4);
+ expect(mesh[0].length).toBe(4);
+
+ const mid = evaluateMeshSurface(mesh, 0.5, 0.5);
+ expect(mid.x).toBeCloseTo(50, 1);
+ expect(mid.y).toBeCloseTo(50, 1);
+ });
+});
diff --git a/src/utils/compositor.ts b/src/utils/compositor.ts
index 8fa6ed8..8aff3ff 100644
--- a/src/utils/compositor.ts
+++ b/src/utils/compositor.ts
@@ -10,6 +10,13 @@
import { LayerItem, CanvasDimensions, BlendMode, CanvasColorMode } from '../types/editor';
import { SparseTileGrid, TILE_SIZE, TileBuffer, globalTileGrid } from './tileEngine';
+import {
+ buildCurvesCombinedLut,
+ buildGradientMapLut,
+ buildLevelsLut,
+ evaluateColorBalancePixel,
+ applyAdjustment,
+} from './tonalEngine';
export interface ViewportTransform {
pan: { x: number; y: number };
@@ -138,6 +145,11 @@ uniform int u_layerColorEnabled;
uniform vec3 u_layerColor;
uniform vec3 u_layerSubColor;
+// Layer Mask Uniforms
+uniform vec2 u_docDimensions;
+uniform sampler2D u_maskTexture;
+uniform int u_maskEnabled;
+
out vec4 fragColor;
float fractVal(float x) {
@@ -239,6 +251,13 @@ void main() {
finalColor = applyLayerTint(finalColor);
}
+ if (u_maskEnabled == 1) {
+ vec2 maskCoord = clamp(v_docCoord / u_docDimensions, 0.0, 1.0);
+ vec4 maskPixel = texture(u_maskTexture, maskCoord);
+ float maskLum = dot(maskPixel.rgb, vec3(0.299, 0.587, 0.114)) * maskPixel.a;
+ finalColor.a *= maskLum;
+ }
+
finalColor.a *= u_layerOpacity;
if (finalColor.a < 0.002) {
@@ -249,6 +268,60 @@ void main() {
}
`;
+// Fragment Shader: Non-Destructive Adjustment Layers with Real-Time LUT Transform
+export const ADJUSTMENT_FRAGMENT_SHADER = `#version 300 es
+precision highp float;
+
+in vec2 v_texCoord;
+in vec2 v_docCoord;
+
+uniform sampler2D u_snapshotTexture;
+uniform sampler2D u_lutTexture;
+uniform int u_adjMode; // 0: per-channel LUT (Curves/Levels), 1: luminance mapping (Gradient Map)
+uniform float u_layerOpacity;
+uniform int u_maskEnabled;
+uniform sampler2D u_maskTexture;
+uniform vec2 u_docDimensions;
+uniform vec2 u_viewportSize;
+
+out vec4 fragColor;
+
+void main() {
+ vec2 screenUV = gl_FragCoord.xy / u_viewportSize;
+ vec4 baseColor = texture(u_snapshotTexture, screenUV);
+
+ if (baseColor.a < 0.001) {
+ discard;
+ }
+
+ vec3 unPremult = baseColor.rgb / max(0.001, baseColor.a);
+ vec3 adjusted;
+
+ if (u_adjMode == 1) {
+ // Gradient map: map luminance to LUT
+ float lum = clamp(dot(unPremult, vec3(0.299, 0.587, 0.114)), 0.0, 1.0);
+ adjusted = texture(u_lutTexture, vec2(lum, 0.5)).rgb;
+ } else {
+ // Curves / Levels / Color Balance
+ float r = texture(u_lutTexture, vec2(clamp(unPremult.r, 0.0, 1.0), 0.5)).r;
+ float g = texture(u_lutTexture, vec2(clamp(unPremult.g, 0.0, 1.0), 0.5)).g;
+ float b = texture(u_lutTexture, vec2(clamp(unPremult.b, 0.0, 1.0), 0.5)).b;
+ adjusted = vec3(r, g, b);
+ }
+
+ float maskFactor = u_layerOpacity;
+ if (u_maskEnabled == 1) {
+ vec2 maskCoord = clamp(v_docCoord / u_docDimensions, 0.0, 1.0);
+ vec4 maskPixel = texture(u_maskTexture, maskCoord);
+ float maskLum = dot(maskPixel.rgb, vec3(0.299, 0.587, 0.114)) * maskPixel.a;
+ maskFactor *= maskLum;
+ }
+
+ vec3 finalRgb = mix(unPremult, adjusted, maskFactor);
+ fragColor = vec4(finalRgb * baseColor.a, baseColor.a);
+}
+`;
+
export interface CompositorOptions {
dimensions: CanvasDimensions;
colorMode?: CanvasColorMode;
@@ -354,6 +427,33 @@ export class ViewportCompositor {
private uLayerColorLoc: WebGLUniformLocation | null = null;
private uLayerSubColorLoc: WebGLUniformLocation | null = null;
+ // Mask uniform locations
+ private uMaskTextureLoc: WebGLUniformLocation | null = null;
+ private uMaskEnabledLoc: WebGLUniformLocation | null = null;
+ private maskTextureCache: Map<string, { texture: WebGLTexture }> = new Map();
+
+ // Adjustment program & uniforms
+ private adjProgram: WebGLProgram | null = null;
+ private uAdjTileOriginLoc: WebGLUniformLocation | null = null;
+ private uAdjTileSizeLoc: WebGLUniformLocation | null = null;
+ private uAdjDocDimensionsLoc: WebGLUniformLocation | null = null;
+ private uAdjViewportSizeLoc: WebGLUniformLocation | null = null;
+ private uAdjPanLoc: WebGLUniformLocation | null = null;
+ private uAdjZoomLoc: WebGLUniformLocation | null = null;
+ private uAdjRotationRadLoc: WebGLUniformLocation | null = null;
+ private uAdjDprLoc: WebGLUniformLocation | null = null;
+ private uAdjSnapshotLoc: WebGLUniformLocation | null = null;
+ private uAdjLutLoc: WebGLUniformLocation | null = null;
+ private uAdjModeLoc: WebGLUniformLocation | null = null;
+ private uAdjOpacityLoc: WebGLUniformLocation | null = null;
+ private uAdjMaskEnabledLoc: WebGLUniformLocation | null = null;
+ private uAdjMaskTextureLoc: WebGLUniformLocation | null = null;
+
+ private snapshotTexture: WebGLTexture | null = null;
+ private snapshotWidth: number = 0;
+ private snapshotHeight: number = 0;
+ private lutTexture: WebGLTexture | null = null;
+
// Tile texture cache: tileKey -> { texture, version }
private textureCache: Map<string, { texture: WebGLTexture; version: number; lastUsed: number }> = new Map();
private fallbackTileCanvas: HTMLCanvasElement | null = null;
@@ -441,6 +541,43 @@ export class ViewportCompositor {
this.uLayerColorLoc = gl.getUniformLocation(prog, 'u_layerColor');
this.uLayerSubColorLoc = gl.getUniformLocation(prog, 'u_layerSubColor');
+ this.uMaskTextureLoc = gl.getUniformLocation(prog, 'u_maskTexture');
+ this.uMaskEnabledLoc = gl.getUniformLocation(prog, 'u_maskEnabled');
+
+ // Compile Adjustment Shader Program
+ const adjFs = gl.createShader(gl.FRAGMENT_SHADER);
+ if (adjFs) {
+ gl.shaderSource(adjFs, ADJUSTMENT_FRAGMENT_SHADER);
+ gl.compileShader(adjFs);
+ if (gl.getShaderParameter(adjFs, gl.COMPILE_STATUS)) {
+ const aProg = gl.createProgram();
+ if (aProg) {
+ gl.attachShader(aProg, vs);
+ gl.attachShader(aProg, adjFs);
+ gl.linkProgram(aProg);
+ if (gl.getProgramParameter(aProg, gl.LINK_STATUS)) {
+ this.adjProgram = aProg;
+ this.uAdjTileOriginLoc = gl.getUniformLocation(aProg, 'u_tileOrigin');
+ this.uAdjTileSizeLoc = gl.getUniformLocation(aProg, 'u_tileSize');
+ this.uAdjDocDimensionsLoc = gl.getUniformLocation(aProg, 'u_docDimensions');
+ this.uAdjViewportSizeLoc = gl.getUniformLocation(aProg, 'u_viewportSize');
+ this.uAdjPanLoc = gl.getUniformLocation(aProg, 'u_pan');
+ this.uAdjZoomLoc = gl.getUniformLocation(aProg, 'u_zoom');
+ this.uAdjRotationRadLoc = gl.getUniformLocation(aProg, 'u_rotationRad');
+ this.uAdjDprLoc = gl.getUniformLocation(aProg, 'u_dpr');
+ this.uAdjSnapshotLoc = gl.getUniformLocation(aProg, 'u_snapshotTexture');
+ this.uAdjLutLoc = gl.getUniformLocation(aProg, 'u_lutTexture');
+ this.uAdjModeLoc = gl.getUniformLocation(aProg, 'u_adjMode');
+ this.uAdjOpacityLoc = gl.getUniformLocation(aProg, 'u_layerOpacity');
+ this.uAdjMaskEnabledLoc = gl.getUniformLocation(aProg, 'u_maskEnabled');
+ this.uAdjMaskTextureLoc = gl.getUniformLocation(aProg, 'u_maskTexture');
+ }
+ }
+ } else {
+ console.error('Adjustment FS error:', gl.getShaderInfoLog(adjFs));
+ }
+ }
+
// Create Unit Quad Buffer [0, 1]
const quad = gl.createBuffer();
if (!quad) return false;
@@ -664,6 +801,19 @@ export class ViewportCompositor {
continue;
}
+ if (baseLayer.type === 'adjustment' && baseLayer.adjustmentData) {
+ this.renderAdjustmentLayer(
+ gl,
+ baseLayer,
+ transform,
+ dimensions,
+ viewportW,
+ viewportH,
+ dpr
+ );
+ continue;
+ }
+
const activeClippedLayers = group.clippedLayers.filter(
(cl) => cl.visible && cl.opacity > 0.001 && cl.type !== 'folder'
);
@@ -702,6 +852,170 @@ export class ViewportCompositor {
}
}
+ /**
+ * Get or upload a WebGLTexture for a layer's mask canvas.
+ */
+ private getMaskTexture(layer: LayerItem): WebGLTexture | null {
+ if (!this.gl || !layer.maskCanvas) return null;
+ const gl = this.gl;
+ let cached = this.maskTextureCache.get(layer.id);
+ if (!cached) {
+ const tex = gl.createTexture();
+ if (!tex) return null;
+ cached = { texture: tex };
+ this.maskTextureCache.set(layer.id, cached);
+ }
+
+ gl.bindTexture(gl.TEXTURE_2D, cached.texture);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
+ gl.texImage2D(
+ gl.TEXTURE_2D,
+ 0,
+ gl.RGBA,
+ gl.RGBA,
+ gl.UNSIGNED_BYTE,
+ layer.maskCanvas
+ );
+
+ return cached.texture;
+ }
+
+ /**
+ * Evaluates non-destructive adjustment layers via GPU snapshot and real-time LUT evaluation.
+ */
+ private renderAdjustmentLayer(
+ gl: WebGL2RenderingContext,
+ layer: LayerItem,
+ transform: ViewportTransform,
+ dimensions: CanvasDimensions,
+ viewportW: number,
+ viewportH: number,
+ dpr: number
+ ): void {
+ if (!this.adjProgram || !layer.adjustmentData) return;
+
+ // 1. Snapshot lower composite
+ if (!this.snapshotTexture || this.snapshotWidth !== viewportW || this.snapshotHeight !== viewportH) {
+ if (this.snapshotTexture) gl.deleteTexture(this.snapshotTexture);
+ this.snapshotTexture = gl.createTexture();
+ this.snapshotWidth = viewportW;
+ this.snapshotHeight = viewportH;
+ gl.bindTexture(gl.TEXTURE_2D, this.snapshotTexture);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, viewportW, viewportH, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
+ }
+
+ gl.bindTexture(gl.TEXTURE_2D, this.snapshotTexture);
+ gl.copyTexSubImage2D(gl.TEXTURE_2D, 0, 0, 0, 0, 0, viewportW, viewportH);
+
+ // 2. Prepare 256x1 LUT
+ if (!this.lutTexture) {
+ this.lutTexture = gl.createTexture();
+ }
+ const adj = layer.adjustmentData;
+ let lutData: Uint8Array;
+ let adjMode = 0; // 0 = per-channel, 1 = gradient map
+
+ if (adj.type === 'curves') {
+ const { rLut, gLut, bLut } = buildCurvesCombinedLut(adj.curves);
+ lutData = new Uint8Array(256 * 4);
+ for (let i = 0; i < 256; i++) {
+ const off = i * 4;
+ lutData[off] = rLut[i];
+ lutData[off + 1] = gLut[i];
+ lutData[off + 2] = bLut[i];
+ lutData[off + 3] = 255;
+ }
+ } else if (adj.type === 'gradient-map') {
+ adjMode = 1;
+ const gMap = buildGradientMapLut(adj.stops, adj.interpolation || 'linear');
+ lutData = new Uint8Array(gMap.buffer, gMap.byteOffset, gMap.byteLength);
+ } else if (adj.type === 'levels') {
+ const lLut = buildLevelsLut(adj.blackPoint, adj.whitePoint, adj.gamma, adj.outputMin ?? 0, adj.outputMax ?? 255);
+ lutData = new Uint8Array(256 * 4);
+ for (let i = 0; i < 256; i++) {
+ const off = i * 4;
+ lutData[off] = lLut[i];
+ lutData[off + 1] = lLut[i];
+ lutData[off + 2] = lLut[i];
+ lutData[off + 3] = 255;
+ }
+ } else { // color-balance
+ lutData = new Uint8Array(256 * 4);
+ for (let i = 0; i < 256; i++) {
+ const [r, g, b] = evaluateColorBalancePixel(i, i, i, adj);
+ const off = i * 4;
+ lutData[off] = r;
+ lutData[off + 1] = g;
+ lutData[off + 2] = b;
+ lutData[off + 3] = 255;
+ }
+ }
+
+ gl.activeTexture(gl.TEXTURE3);
+ gl.bindTexture(gl.TEXTURE_2D, this.lutTexture);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 256, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, lutData);
+
+ // 3. Switch to Adjustment Program
+ gl.useProgram(this.adjProgram);
+
+ // Uniforms
+ gl.uniform2f(this.uAdjViewportSizeLoc, viewportW, viewportH);
+ gl.uniform2f(this.uAdjDocDimensionsLoc, dimensions.width, dimensions.height);
+ gl.uniform2f(this.uAdjPanLoc, transform.pan.x, transform.pan.y);
+ gl.uniform1f(this.uAdjZoomLoc, transform.zoom);
+ const rotRad = (transform.rotation * Math.PI) / 180;
+ gl.uniform1f(this.uAdjRotationRadLoc, rotRad);
+ gl.uniform1f(this.uAdjDprLoc, dpr);
+
+ gl.uniform2f(this.uAdjTileOriginLoc, 0, 0);
+ gl.uniform2f(this.uAdjTileSizeLoc, dimensions.width, dimensions.height);
+
+ gl.activeTexture(gl.TEXTURE2);
+ gl.bindTexture(gl.TEXTURE_2D, this.snapshotTexture);
+ gl.uniform1i(this.uAdjSnapshotLoc, 2);
+
+ gl.activeTexture(gl.TEXTURE3);
+ gl.bindTexture(gl.TEXTURE_2D, this.lutTexture);
+ gl.uniform1i(this.uAdjLutLoc, 3);
+
+ gl.uniform1i(this.uAdjModeLoc, adjMode);
+ gl.uniform1f(this.uAdjOpacityLoc, layer.opacity);
+
+ // Mask for adjustment layer
+ const hasMask = Boolean(layer.maskCanvas && layer.maskEnabled !== false);
+ gl.uniform1i(this.uAdjMaskEnabledLoc, hasMask ? 1 : 0);
+ if (hasMask && layer.maskCanvas) {
+ const maskTex = this.getMaskTexture(layer);
+ if (maskTex) {
+ gl.activeTexture(gl.TEXTURE1);
+ gl.bindTexture(gl.TEXTURE_2D, maskTex);
+ gl.uniform1i(this.uAdjMaskTextureLoc, 1);
+ }
+ }
+
+ // Blend: overwrite lower composite with filtered result
+ gl.blendFunc(gl.ONE, gl.ZERO);
+ gl.drawArrays(gl.TRIANGLES, 0, 6);
+
+ // Revert program and blend func
+ gl.useProgram(this.program);
+ gl.enable(gl.BLEND);
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ }
+
/**
* Renders all visible tiles of a single layer onto WebGL2 context.
*/
@@ -747,6 +1061,20 @@ export class ViewportCompositor {
gl.uniform3f(this.uLayerSubColorLoc, sub[0], sub[1], sub[2]);
}
+ // Configure Layer Mask
+ const hasMask = Boolean(layer.maskCanvas && layer.maskEnabled !== false);
+ gl.uniform1i(this.uMaskEnabledLoc, hasMask ? 1 : 0);
+ if (hasMask && layer.maskCanvas) {
+ const maskTex = this.getMaskTexture(layer);
+ if (maskTex) {
+ gl.activeTexture(gl.TEXTURE1);
+ gl.bindTexture(gl.TEXTURE_2D, maskTex);
+ gl.uniform1i(this.uMaskTextureLoc, 1);
+ } else {
+ gl.uniform1i(this.uMaskEnabledLoc, 0);
+ }
+ }
+
// Query tiles intersecting frustum
const visibleTiles = grid.getTilesInBounds(
layer.id,
@@ -767,6 +1095,10 @@ export class ViewportCompositor {
gl.uniform2f(this.uTileOriginLoc, tile.tileX * TILE_SIZE, tile.tileY * TILE_SIZE);
gl.drawArrays(gl.TRIANGLES, 0, 6);
}
+
+ if (hasMask) {
+ gl.uniform1i(this.uMaskEnabledLoc, 0);
+ }
}
/**
@@ -802,11 +1134,26 @@ export class ViewportCompositor {
'source-over';
const tiles = grid.getLayerTiles(layer.id);
+ const hasMask = Boolean(layer.maskCanvas && layer.maskEnabled !== false);
+ const maskCtx = hasMask && layer.maskCanvas ? layer.maskCanvas.getContext('2d', { willReadFrequently: true }) : null;
+
for (const tile of tiles) {
if (!tileCtx || !this.fallbackTileCanvas) continue;
const rgba = grid.getTileAsRGBA(tile);
const imgData = tileCtx.createImageData(TILE_SIZE, TILE_SIZE);
imgData.data.set(rgba);
+
+ if (hasMask && maskCtx) {
+ const maskImgData = maskCtx.getImageData(tile.tileX * TILE_SIZE, tile.tileY * TILE_SIZE, TILE_SIZE, TILE_SIZE);
+ const md = maskImgData.data;
+ const d = imgData.data;
+ for (let i = 0; i < d.length; i += 4) {
+ if (d[i + 3] === 0) continue;
+ const maskLum = (0.299 * md[i] + 0.587 * md[i + 1] + 0.114 * md[i + 2]) / 255 * (md[i + 3] / 255);
+ d[i + 3] = Math.round(d[i + 3] * maskLum);
+ }
+ }
+
tileCtx.putImageData(imgData, 0, 0);
targetCtx.drawImage(this.fallbackTileCanvas, tile.tileX * TILE_SIZE, tile.tileY * TILE_SIZE);
}
@@ -860,6 +1207,13 @@ export class ViewportCompositor {
const baseLayer = group.baseLayer;
if (!baseLayer.visible || baseLayer.opacity <= 0.001 || baseLayer.type === 'folder') continue;
+ if (baseLayer.type === 'adjustment' && baseLayer.adjustmentData) {
+ const imgData = ctx.getImageData(0, 0, viewportW, viewportH);
+ applyAdjustment(imgData, baseLayer.adjustmentData, baseLayer.maskCanvas, baseLayer.opacity);
+ ctx.putImageData(imgData, 0, 0);
+ continue;
+ }
+
const activeClipped = group.clippedLayers.filter(
(cl) => cl.visible && cl.opacity > 0.001 && cl.type !== 'folder'
);
@@ -925,6 +1279,18 @@ export class ViewportCompositor {
this.gl.deleteTexture(item.texture);
}
this.textureCache.clear();
+ for (const item of this.maskTextureCache.values()) {
+ this.gl.deleteTexture(item.texture);
+ }
+ this.maskTextureCache.clear();
+ if (this.snapshotTexture) {
+ this.gl.deleteTexture(this.snapshotTexture);
+ this.snapshotTexture = null;
+ }
+ if (this.lutTexture) {
+ this.gl.deleteTexture(this.lutTexture);
+ this.lutTexture = null;
+ }
if (this.quadBuffer) {
this.gl.deleteBuffer(this.quadBuffer);
this.quadBuffer = null;
@@ -933,6 +1299,10 @@ export class ViewportCompositor {
this.gl.deleteProgram(this.program);
this.program = null;
}
+ if (this.adjProgram) {
+ this.gl.deleteProgram(this.adjProgram);
+ this.adjProgram = null;
+ }
}
if (this.fallbackTileCanvas) {
this.fallbackTileCanvas = null;
diff --git a/src/utils/filterEngine.ts b/src/utils/filterEngine.ts
new file mode 100644
index 0000000..4e7b2c8
--- /dev/null
+++ b/src/utils/filterEngine.ts
@@ -0,0 +1,472 @@
+import { FilterType } from '../types/editor';
+
+export interface GaussianBlurParams {
+ radius: number; // Blur radius in pixels (1 to 100)
+}
+
+export interface MotionBlurParams {
+ distance: number; // Distance in pixels (1 to 100)
+ angle: number; // Angle in degrees (0 to 360)
+}
+
+export interface UnsharpMaskParams {
+ radius: number; // Radius in pixels (0.5 to 20)
+ amount: number; // Amount factor (0.1 to 5.0, e.g. 1.0 = 100%)
+ threshold?: number;// Threshold (0 to 255, default: 0)
+}
+
+export interface FilmGrainParams {
+ intensity: number; // Intensity percentage (0 to 100)
+ size?: number; // Grain particle size in pixels (1 to 10, default: 1)
+ monochromatic?: boolean;// True for B&W grain, false for RGB chromatic noise
+ seed?: number; // Optional PRNG seed
+}
+
+/**
+ * Calculates optimal 3-pass box blur radii that approximate Gaussian blur with sigma.
+ * Based on Peter Kovesi's fast box blur approximation (Central Limit Theorem).
+ */
+function boxesForGauss(sigma: number, n: number = 3): number[] {
+ const wIdeal = Math.sqrt((12 * sigma * sigma / n) + 1);
+ let wl = Math.floor(wIdeal);
+ if (wl % 2 === 0) wl--;
+ const wu = wl + 2;
+
+ const mIdeal = (12 * sigma * sigma - n * wl * wl - 4 * n * wl - 3 * n) / (-4 * wl - 4);
+ const m = Math.round(mIdeal);
+
+ const sizes: number[] = [];
+ for (let i = 0; i < n; i++) {
+ sizes.push(i < m ? wl : wu);
+ }
+ return sizes;
+}
+
+/**
+ * 1D Horizontal Box Blur pass using sliding window accumulator (O(N) runtime).
+ */
+function boxBlurHorizontal(
+ src: Uint8ClampedArray,
+ dst: Uint8ClampedArray,
+ w: number,
+ h: number,
+ r: number
+): void {
+ const iarr = 1 / (r + r + 1);
+ for (let y = 0; y < h; y++) {
+ const rowOffset = y * w;
+ let ti = rowOffset * 4;
+ let li = rowOffset;
+ let ri = rowOffset + r;
+
+ const fvR = src[rowOffset * 4];
+ const fvG = src[rowOffset * 4 + 1];
+ const fvB = src[rowOffset * 4 + 2];
+ const fvA = src[rowOffset * 4 + 3];
+
+ const lvR = src[(rowOffset + w - 1) * 4];
+ const lvG = src[(rowOffset + w - 1) * 4 + 1];
+ const lvB = src[(rowOffset + w - 1) * 4 + 2];
+ const lvA = src[(rowOffset + w - 1) * 4 + 3];
+
+ let valR = (r + 1) * fvR;
+ let valG = (r + 1) * fvG;
+ let valB = (r + 1) * fvB;
+ let valA = (r + 1) * fvA;
+
+ for (let j = 0; j < r; j++) {
+ const idx = (rowOffset + Math.min(w - 1, j)) * 4;
+ valR += src[idx];
+ valG += src[idx + 1];
+ valB += src[idx + 2];
+ valA += src[idx + 3];
+ }
+
+ for (let j = 0; j <= r; j++) {
+ const rIdx = (rowOffset + Math.min(w - 1, ri++ - rowOffset)) * 4;
+ valR += src[rIdx] - fvR;
+ valG += src[rIdx + 1] - fvG;
+ valB += src[rIdx + 2] - fvB;
+ valA += src[rIdx + 3] - fvA;
+ dst[ti] = Math.round(valR * iarr);
+ dst[ti + 1] = Math.round(valG * iarr);
+ dst[ti + 2] = Math.round(valB * iarr);
+ dst[ti + 3] = Math.round(valA * iarr);
+ ti += 4;
+ }
+
+ for (let j = r + 1; j < w - r; j++) {
+ const rIdx = (rowOffset + (ri++ - rowOffset)) * 4;
+ const lIdx = (rowOffset + (li++ - rowOffset)) * 4;
+ valR += src[rIdx] - src[lIdx];
+ valG += src[rIdx + 1] - src[lIdx + 1];
+ valB += src[rIdx + 2] - src[lIdx + 2];
+ valA += src[rIdx + 3] - src[lIdx + 3];
+ dst[ti] = Math.round(valR * iarr);
+ dst[ti + 1] = Math.round(valG * iarr);
+ dst[ti + 2] = Math.round(valB * iarr);
+ dst[ti + 3] = Math.round(valA * iarr);
+ ti += 4;
+ }
+
+ for (let j = w - r; j < w; j++) {
+ const lIdx = (rowOffset + Math.max(0, li++ - rowOffset)) * 4;
+ valR += lvR - src[lIdx];
+ valG += lvG - src[lIdx + 1];
+ valB += lvB - src[lIdx + 2];
+ valA += lvA - src[lIdx + 3];
+ dst[ti] = Math.round(valR * iarr);
+ dst[ti + 1] = Math.round(valG * iarr);
+ dst[ti + 2] = Math.round(valB * iarr);
+ dst[ti + 3] = Math.round(valA * iarr);
+ ti += 4;
+ }
+ }
+}
+
+/**
+ * 1D Vertical Box Blur pass using sliding window accumulator (O(N) runtime).
+ */
+function boxBlurVertical(
+ src: Uint8ClampedArray,
+ dst: Uint8ClampedArray,
+ w: number,
+ h: number,
+ r: number
+): void {
+ const iarr = 1 / (r + r + 1);
+ for (let x = 0; x < w; x++) {
+ let ti = x * 4;
+ let li = ti;
+ let ri = ti + r * w * 4;
+
+ const fvR = src[ti];
+ const fvG = src[ti + 1];
+ const fvB = src[ti + 2];
+ const fvA = src[ti + 3];
+
+ const bottomIdx = (x + (h - 1) * w) * 4;
+ const lvR = src[bottomIdx];
+ const lvG = src[bottomIdx + 1];
+ const lvB = src[bottomIdx + 2];
+ const lvA = src[bottomIdx + 3];
+
+ let valR = (r + 1) * fvR;
+ let valG = (r + 1) * fvG;
+ let valB = (r + 1) * fvB;
+ let valA = (r + 1) * fvA;
+
+ for (let j = 0; j < r; j++) {
+ const idx = (x + Math.min(h - 1, j) * w) * 4;
+ valR += src[idx];
+ valG += src[idx + 1];
+ valB += src[idx + 2];
+ valA += src[idx + 3];
+ }
+
+ for (let j = 0; j <= r; j++) {
+ const rIdx = (x + Math.min(h - 1, Math.floor(ri / (w * 4)))) * 4;
+ ri += w * 4;
+ valR += src[rIdx] - fvR;
+ valG += src[rIdx + 1] - fvG;
+ valB += src[rIdx + 2] - fvB;
+ valA += src[rIdx + 3] - fvA;
+ dst[ti] = Math.round(valR * iarr);
+ dst[ti + 1] = Math.round(valG * iarr);
+ dst[ti + 2] = Math.round(valB * iarr);
+ dst[ti + 3] = Math.round(valA * iarr);
+ ti += w * 4;
+ }
+
+ for (let j = r + 1; j < h - r; j++) {
+ valR += src[ri] - src[li];
+ valG += src[ri + 1] - src[li + 1];
+ valB += src[ri + 2] - src[li + 2];
+ valA += src[ri + 3] - src[li + 3];
+ ri += w * 4;
+ li += w * 4;
+ dst[ti] = Math.round(valR * iarr);
+ dst[ti + 1] = Math.round(valG * iarr);
+ dst[ti + 2] = Math.round(valB * iarr);
+ dst[ti + 3] = Math.round(valA * iarr);
+ ti += w * 4;
+ }
+
+ for (let j = h - r; j < h; j++) {
+ const lIdx = (x + Math.max(0, Math.floor(li / (w * 4)))) * 4;
+ li += w * 4;
+ valR += lvR - src[lIdx];
+ valG += lvG - src[lIdx + 1];
+ valB += lvB - src[lIdx + 2];
+ valA += lvA - src[lIdx + 3];
+ dst[ti] = Math.round(valR * iarr);
+ dst[ti + 1] = Math.round(valG * iarr);
+ dst[ti + 2] = Math.round(valB * iarr);
+ dst[ti + 3] = Math.round(valA * iarr);
+ ti += w * 4;
+ }
+ }
+}
+
+/**
+ * Separable 3-pass Gaussian Blur in O(N) runtime regardless of radius size.
+ */
+export function applyGaussianBlur(imageData: ImageData, radius: number): ImageData {
+ const r = Math.max(0.1, radius);
+ const w = imageData.width;
+ const h = imageData.height;
+
+ const output = new ImageData(w, h);
+ const temp = new Uint8ClampedArray(imageData.data);
+ const buf = new Uint8ClampedArray(imageData.data.length);
+
+ const bxs = boxesForGauss(r, 3);
+
+ // Pass 1
+ boxBlurHorizontal(temp, buf, w, h, (bxs[0] - 1) / 2);
+ boxBlurVertical(buf, temp, w, h, (bxs[0] - 1) / 2);
+
+ // Pass 2
+ boxBlurHorizontal(temp, buf, w, h, (bxs[1] - 1) / 2);
+ boxBlurVertical(buf, temp, w, h, (bxs[1] - 1) / 2);
+
+ // Pass 3
+ boxBlurHorizontal(temp, buf, w, h, (bxs[2] - 1) / 2);
+ boxBlurVertical(buf, output.data, w, h, (bxs[2] - 1) / 2);
+
+ return output;
+}
+
+/**
+ * Directional Motion Blur convolution filter.
+ */
+export function applyMotionBlur(
+ imageData: ImageData,
+ distance: number,
+ angle: number
+): ImageData {
+ const dist = Math.max(1, distance);
+ const w = imageData.width;
+ const h = imageData.height;
+ const src = imageData.data;
+ const output = new ImageData(w, h);
+ const dst = output.data;
+
+ const rad = (angle * Math.PI) / 180;
+ const cosA = Math.cos(rad);
+ const sinA = Math.sin(rad);
+
+ const halfSteps = Math.max(1, Math.floor(dist / 2));
+ const numSamples = halfSteps * 2 + 1;
+ const invSamples = 1 / numSamples;
+
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ let accR = 0;
+ let accG = 0;
+ let accB = 0;
+ let accA = 0;
+
+ for (let s = -halfSteps; s <= halfSteps; s++) {
+ const factor = s * (dist / numSamples);
+ const sx = Math.max(0, Math.min(w - 1, Math.round(x + cosA * factor)));
+ const sy = Math.max(0, Math.min(h - 1, Math.round(y + sinA * factor)));
+ const idx = (sy * w + sx) * 4;
+
+ accR += src[idx];
+ accG += src[idx + 1];
+ accB += src[idx + 2];
+ accA += src[idx + 3];
+ }
+
+ const outIdx = (y * w + x) * 4;
+ dst[outIdx] = Math.round(accR * invSamples);
+ dst[outIdx + 1] = Math.round(accG * invSamples);
+ dst[outIdx + 2] = Math.round(accB * invSamples);
+ dst[outIdx + 3] = Math.round(accA * invSamples);
+ }
+ }
+
+ return output;
+}
+
+/**
+ * Unsharp Mask Filter: Output = Original + (Original - Blurred) * Amount.
+ */
+export function applyUnsharpMask(
+ imageData: ImageData,
+ radius: number,
+ amount: number,
+ threshold: number = 0
+): ImageData {
+ const blurred = applyGaussianBlur(imageData, radius);
+ const w = imageData.width;
+ const h = imageData.height;
+ const total = w * h;
+ const src = imageData.data;
+ const blr = blurred.data;
+ const output = new ImageData(w, h);
+ const dst = output.data;
+
+ const safeThresh = Math.max(0, threshold);
+
+ for (let p = 0; p < total; p++) {
+ const i = p * 4;
+ const diffR = src[i] - blr[i];
+ const diffG = src[i + 1] - blr[i + 1];
+ const diffB = src[i + 2] - blr[i + 2];
+
+ const maxDiff = Math.max(Math.abs(diffR), Math.abs(diffG), Math.abs(diffB));
+
+ if (maxDiff >= safeThresh) {
+ dst[i] = Math.max(0, Math.min(255, Math.round(src[i] + diffR * amount)));
+ dst[i + 1] = Math.max(0, Math.min(255, Math.round(src[i + 1] + diffG * amount)));
+ dst[i + 2] = Math.max(0, Math.min(255, Math.round(src[i + 2] + diffB * amount)));
+ } else {
+ dst[i] = src[i];
+ dst[i + 1] = src[i + 1];
+ dst[i + 2] = src[i + 2];
+ }
+ dst[i + 3] = src[i + 3];
+ }
+
+ return output;
+}
+
+/**
+ * High-performance PRNG (Mulberry32) for deterministic procedural grain.
+ */
+function createPrng(seed: number) {
+ let s = seed | 0;
+ return function () {
+ s = (s + 0x6d2b79f5) | 0;
+ let t = Math.imul(s ^ (s >>> 15), 1 | s);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+/**
+ * Procedural Film Grain Filter (Monochromatic / Chromatic, with Particle Size scaling).
+ */
+export function applyFilmGrain(
+ imageData: ImageData,
+ intensity: number,
+ size: number = 1,
+ monochromatic: boolean = true,
+ seed: number = 1337
+): ImageData {
+ const w = imageData.width;
+ const h = imageData.height;
+ const src = imageData.data;
+ const output = new ImageData(w, h);
+ const dst = output.data;
+
+ const prng = createPrng(seed);
+ const scale = (intensity / 100) * 128;
+ const grainSize = Math.max(1, Math.min(10, Math.round(size)));
+
+ if (grainSize === 1) {
+ const totalPixels = w * h;
+ for (let p = 0; p < totalPixels; p++) {
+ const i = p * 4;
+ if (src[i + 3] === 0) {
+ dst[i + 3] = 0;
+ continue;
+ }
+
+ if (monochromatic) {
+ // Uniform noise mapped to [-1, 1]
+ const noise = (prng() * 2 - 1) * scale;
+ dst[i] = Math.max(0, Math.min(255, Math.round(src[i] + noise)));
+ dst[i + 1] = Math.max(0, Math.min(255, Math.round(src[i + 1] + noise)));
+ dst[i + 2] = Math.max(0, Math.min(255, Math.round(src[i + 2] + noise)));
+ } else {
+ const nR = (prng() * 2 - 1) * scale;
+ const nG = (prng() * 2 - 1) * scale;
+ const nB = (prng() * 2 - 1) * scale;
+ dst[i] = Math.max(0, Math.min(255, Math.round(src[i] + nR)));
+ dst[i + 1] = Math.max(0, Math.min(255, Math.round(src[i + 1] + nG)));
+ dst[i + 2] = Math.max(0, Math.min(255, Math.round(src[i + 2] + nB)));
+ }
+ dst[i + 3] = src[i + 3];
+ }
+ } else {
+ // Clustered grain blocks for custom particle size
+ const blocksW = Math.ceil(w / grainSize);
+ const blocksH = Math.ceil(h / grainSize);
+ const noiseMap = new Float32Array(blocksW * blocksH * (monochromatic ? 1 : 3));
+
+ for (let i = 0; i < noiseMap.length; i++) {
+ noiseMap[i] = (prng() * 2 - 1) * scale;
+ }
+
+ for (let y = 0; y < h; y++) {
+ const by = Math.floor(y / grainSize);
+ const bRow = by * blocksW;
+ const rowOffset = y * w;
+
+ for (let x = 0; x < w; x++) {
+ const bx = Math.floor(x / grainSize);
+ const bIdx = bRow + bx;
+ const i = (rowOffset + x) * 4;
+
+ if (src[i + 3] === 0) {
+ dst[i + 3] = 0;
+ continue;
+ }
+
+ if (monochromatic) {
+ const noise = noiseMap[bIdx];
+ dst[i] = Math.max(0, Math.min(255, Math.round(src[i] + noise)));
+ dst[i + 1] = Math.max(0, Math.min(255, Math.round(src[i + 1] + noise)));
+ dst[i + 2] = Math.max(0, Math.min(255, Math.round(src[i + 2] + noise)));
+ } else {
+ const cIdx = bIdx * 3;
+ dst[i] = Math.max(0, Math.min(255, Math.round(src[i] + noiseMap[cIdx])));
+ dst[i + 1] = Math.max(0, Math.min(255, Math.round(src[i + 1] + noiseMap[cIdx + 1])));
+ dst[i + 2] = Math.max(0, Math.min(255, Math.round(src[i + 2] + noiseMap[cIdx + 2])));
+ }
+ dst[i + 3] = src[i + 3];
+ }
+ }
+ }
+
+ return output;
+}
+
+/**
+ * Universal dispatcher for convolution filters.
+ */
+export function applyFilter(
+ imageData: ImageData,
+ type: FilterType,
+ params: any
+): ImageData {
+ switch (type) {
+ case 'gaussian-blur': {
+ const p = params as GaussianBlurParams;
+ return applyGaussianBlur(imageData, p.radius || 5);
+ }
+ case 'motion-blur': {
+ const p = params as MotionBlurParams;
+ return applyMotionBlur(imageData, p.distance || 15, p.angle || 0);
+ }
+ case 'unsharp-mask': {
+ const p = params as UnsharpMaskParams;
+ return applyUnsharpMask(imageData, p.radius || 2, p.amount || 1.5, p.threshold || 0);
+ }
+ case 'film-grain': {
+ const p = params as FilmGrainParams;
+ return applyFilmGrain(
+ imageData,
+ p.intensity || 25,
+ p.size || 1,
+ p.monochromatic ?? true,
+ p.seed || 1337
+ );
+ }
+ default:
+ return imageData;
+ }
+}
diff --git a/src/utils/selectionUtils.ts b/src/utils/selectionUtils.ts
index 2327ce1..613f31b 100644
--- a/src/utils/selectionUtils.ts
+++ b/src/utils/selectionUtils.ts
@@ -1,4 +1,4 @@
-import { CanvasSelection, DirtyRect } from '../types/editor';
+import { CanvasSelection, DirtyRect, WandSettings } from '../types/editor';
/**
* Checks whether a 2D point lies within an arbitrary polygon using ray-casting.
@@ -46,6 +46,14 @@ export function isPointInSelection(
return false;
}
+ // If pixel mask is defined, sample mask directly
+ if (selection.mask && selection.maskWidth && selection.maskHeight) {
+ const ix = Math.floor(x);
+ const iy = Math.floor(y);
+ if (ix < 0 || ix >= selection.maskWidth || iy < 0 || iy >= selection.maskHeight) return false;
+ return selection.mask[iy * selection.maskWidth + ix] >= 128;
+ }
+
if (selection.type === 'lasso' && selection.polygon) {
return isPointInPolygon(x, y, selection.polygon);
}
@@ -82,8 +90,599 @@ export function computePolygonBounds(
}
/**
- * Computes the tight bounding box of all non-transparent pixels on a canvas.
- * Returns null if the canvas is completely transparent/blank.
+ * Computes tight bounding box from an 8-bit mask buffer.
+ */
+export function maskToBounds(
+ mask: Uint8Array,
+ width: number,
+ height: number
+): { x: number; y: number; width: number; height: number } | null {
+ let minX = width;
+ let minY = height;
+ let maxX = -1;
+ let maxY = -1;
+
+ for (let y = 0; y < height; y++) {
+ const rowOffset = y * width;
+ for (let x = 0; x < width; x++) {
+ if (mask[rowOffset + x] >= 128) {
+ if (x < minX) minX = x;
+ if (x > maxX) maxX = x;
+ if (y < minY) minY = y;
+ if (y > maxY) maxY = y;
+ }
+ }
+ }
+
+ if (maxX < 0 || maxY < 0) return null;
+
+ return {
+ x: minX,
+ y: minY,
+ width: maxX - minX + 1,
+ height: maxY - minY + 1,
+ };
+}
+
+/**
+ * Converts any selection (rect, lasso, or existing mask) into a full Uint8Array 8-bit mask.
+ */
+export function selectionToMask(
+ selection: CanvasSelection,
+ width: number,
+ height: number
+): Uint8Array {
+ if (selection.mask && selection.maskWidth === width && selection.maskHeight === height) {
+ return new Uint8Array(selection.mask);
+ }
+
+ const mask = new Uint8Array(width * height);
+ if (selection.type === 'rect') {
+ const b = selection.bounds;
+ const x0 = Math.max(0, Math.floor(b.x));
+ const y0 = Math.max(0, Math.floor(b.y));
+ const x1 = Math.min(width, Math.ceil(b.x + b.width));
+ const y1 = Math.min(height, Math.ceil(b.y + b.height));
+ for (let y = y0; y < y1; y++) {
+ const row = y * width;
+ for (let x = x0; x < x1; x++) {
+ mask[row + x] = 255;
+ }
+ }
+ } else if (selection.type === 'lasso' && selection.polygon && selection.polygon.length >= 3) {
+ // Rasterize polygon onto offscreen 2D canvas
+ const offCanvas = document.createElement('canvas');
+ offCanvas.width = width;
+ offCanvas.height = height;
+ const offCtx = offCanvas.getContext('2d');
+ if (offCtx) {
+ offCtx.fillStyle = '#ffffff';
+ offCtx.beginPath();
+ offCtx.moveTo(selection.polygon[0].x, selection.polygon[0].y);
+ for (let i = 1; i < selection.polygon.length; i++) {
+ offCtx.lineTo(selection.polygon[i].x, selection.polygon[i].y);
+ }
+ offCtx.closePath();
+ offCtx.fill();
+ const imgData = offCtx.getImageData(0, 0, width, height);
+ for (let i = 0; i < width * height; i++) {
+ mask[i] = imgData.data[i * 4 + 3];
+ }
+ }
+ }
+
+ return mask;
+}
+
+/**
+ * Felzenszwalb-Huttenlocher 1D squared Euclidean Distance Transform.
+ */
+function edt1D(
+ f: Float64Array,
+ n: number,
+ d: Float64Array,
+ v: Int32Array,
+ z: Float64Array
+): void {
+ let k = 0;
+ v[0] = 0;
+ z[0] = -1e12;
+ z[1] = 1e12;
+
+ for (let q = 1; q < n; q++) {
+ let s = (f[q] + q * q - (f[v[k]] + v[k] * v[k])) / (2 * (q - v[k]));
+ while (s <= z[k]) {
+ k--;
+ s = (f[q] + q * q - (f[v[k]] + v[k] * v[k])) / (2 * (q - v[k]));
+ }
+ k++;
+ v[k] = q;
+ z[k] = s;
+ z[k + 1] = 1e12;
+ }
+
+ k = 0;
+ for (let q = 0; q < n; q++) {
+ while (z[k + 1] < q) {
+ k++;
+ }
+ const dq = q - v[k];
+ d[q] = dq * dq + f[v[k]];
+ }
+}
+
+/**
+ * Computes 2D squared Euclidean Distance Transform in O(W * H) linear time.
+ */
+function computeEuclideanDistanceTransformSquared(
+ mask: Uint8Array,
+ width: number,
+ height: number,
+ isFeature: (val: number, x: number, y: number) => boolean
+): Float64Array {
+ const INF = 1e11;
+ const distSq = new Float64Array(width * height);
+
+ for (let y = 0; y < height; y++) {
+ const row = y * width;
+ for (let x = 0; x < width; x++) {
+ distSq[row + x] = isFeature(mask[row + x], x, y) ? 0 : INF;
+ }
+ }
+
+ const maxDim = Math.max(width, height);
+ const f = new Float64Array(maxDim);
+ const d = new Float64Array(maxDim);
+ const v = new Int32Array(maxDim);
+ const z = new Float64Array(maxDim + 1);
+
+ // Column pass
+ for (let x = 0; x < width; x++) {
+ for (let y = 0; y < height; y++) {
+ f[y] = distSq[y * width + x];
+ }
+ edt1D(f, height, d, v, z);
+ for (let y = 0; y < height; y++) {
+ distSq[y * width + x] = d[y];
+ }
+ }
+
+ // Row pass
+ for (let y = 0; y < height; y++) {
+ const rowOffset = y * width;
+ for (let x = 0; x < width; x++) {
+ f[x] = distSq[rowOffset + x];
+ }
+ edt1D(f, width, d, v, z);
+ for (let x = 0; x < width; x++) {
+ distSq[rowOffset + x] = d[x];
+ }
+ }
+
+ return distSq;
+}
+
+/**
+ * Binary morphological dilation using separable Euclidean distance transform.
+ */
+export function expandSelection(
+ mask: Uint8Array,
+ width: number,
+ height: number,
+ pixels: number
+): Uint8Array {
+ if (pixels <= 0) return new Uint8Array(mask);
+
+ // Feature points are pixels inside the selection (mask >= 128)
+ const distSq = computeEuclideanDistanceTransformSquared(
+ mask,
+ width,
+ height,
+ (val) => val >= 128
+ );
+
+ const radiusSq = pixels * pixels;
+ const out = new Uint8Array(width * height);
+
+ for (let i = 0; i < width * height; i++) {
+ out[i] = distSq[i] <= radiusSq ? 255 : 0;
+ }
+
+ return out;
+}
+
+/**
+ * Binary morphological erosion using separable Euclidean distance transform.
+ */
+export function contractSelection(
+ mask: Uint8Array,
+ width: number,
+ height: number,
+ pixels: number
+): Uint8Array {
+ if (pixels <= 0) return new Uint8Array(mask);
+
+ // Feature points are pixels outside the selection OR outside canvas boundaries
+ const distSq = computeEuclideanDistanceTransformSquared(
+ mask,
+ width,
+ height,
+ (val, x, y) => val < 128 || x === 0 || y === 0 || x === width - 1 || y === height - 1
+ );
+
+ const radiusSq = pixels * pixels;
+ const out = new Uint8Array(width * height);
+
+ for (let i = 0; i < width * height; i++) {
+ out[i] = distSq[i] > radiusSq && mask[i] >= 128 ? 255 : 0;
+ }
+
+ return out;
+}
+
+/**
+ * Separable Gaussian blur over the selection mask.
+ */
+export function featherSelection(
+ mask: Uint8Array,
+ width: number,
+ height: number,
+ radius: number
+): Uint8Array {
+ if (radius <= 0) return new Uint8Array(mask);
+
+ const sigma = Math.max(0.5, radius / 2);
+ const kRadius = Math.ceil(sigma * 2.5);
+ const kSize = kRadius * 2 + 1;
+ const kernel = new Float32Array(kSize);
+ let sum = 0;
+ for (let i = -kRadius; i <= kRadius; i++) {
+ const w = Math.exp(-(i * i) / (2 * sigma * sigma));
+ kernel[i + kRadius] = w;
+ sum += w;
+ }
+ for (let i = 0; i < kSize; i++) {
+ kernel[i] /= sum;
+ }
+
+ const temp = new Float32Array(width * height);
+ const out = new Uint8Array(width * height);
+
+ // Horizontal pass
+ for (let y = 0; y < height; y++) {
+ const rowOffset = y * width;
+ for (let x = 0; x < width; x++) {
+ let acc = 0;
+ for (let k = -kRadius; k <= kRadius; k++) {
+ const sx = Math.min(width - 1, Math.max(0, x + k));
+ acc += mask[rowOffset + sx] * kernel[k + kRadius];
+ }
+ temp[rowOffset + x] = acc;
+ }
+ }
+
+ // Vertical pass
+ for (let x = 0; x < width; x++) {
+ for (let y = 0; y < height; y++) {
+ let acc = 0;
+ for (let k = -kRadius; k <= kRadius; k++) {
+ const sy = Math.min(height - 1, Math.max(0, y + k));
+ acc += temp[sy * width + x] * kernel[k + kRadius];
+ }
+ out[y * width + x] = Math.round(Math.min(255, Math.max(0, acc)));
+ }
+ }
+
+ return out;
+}
+
+/**
+ * Inverts the selection mask buffer.
+ */
+export function invertSelection(
+ mask: Uint8Array,
+ width: number,
+ height: number
+): Uint8Array {
+ const out = new Uint8Array(width * height);
+ for (let i = 0; i < width * height; i++) {
+ out[i] = 255 - mask[i];
+ }
+ return out;
+}
+
+/**
+ * Magic Wand flood selection on an 8-bit selection mask buffer.
+ * Supports tolerance, contiguous scanline fill, anti-alias boundary smoothing.
+ */
+export function floodSelectWand(
+ sourceData: ImageData | Uint8ClampedArray,
+ width: number,
+ height: number,
+ startX: number,
+ startY: number,
+ settings: WandSettings
+): {
+ mask: Uint8Array;
+ bounds: { x: number; y: number; width: number; height: number };
+} {
+ const rawData = 'data' in sourceData ? sourceData.data : sourceData;
+ const mask = new Uint8Array(width * height);
+
+ if (startX < 0 || startX >= width || startY < 0 || startY >= height) {
+ return { mask, bounds: { x: 0, y: 0, width: 0, height: 0 } };
+ }
+
+ const seedOffset = (startY * width + startX) * 4;
+ const sR = rawData[seedOffset];
+ const sG = rawData[seedOffset + 1];
+ const sB = rawData[seedOffset + 2];
+ const sA = rawData[seedOffset + 3];
+
+ const tolerance = settings.tolerance;
+
+ // Calculates color distance normalized to [0, 255]
+ const colorDiff = (x: number, y: number): number => {
+ const idx = (y * width + x) * 4;
+ const r = rawData[idx];
+ const g = rawData[idx + 1];
+ const b = rawData[idx + 2];
+ const a = rawData[idx + 3];
+
+ if (a === 0 && sA === 0) return 0;
+
+ const dr = r - sR;
+ const dg = g - sG;
+ const db = b - sB;
+ const da = a - sA;
+
+ return Math.sqrt(dr * dr + dg * dg + db * db + da * da) / 2;
+ };
+
+ const matches = (x: number, y: number): boolean => {
+ return colorDiff(x, y) <= tolerance;
+ };
+
+ let minX = width;
+ let maxX = -1;
+ let minY = height;
+ let maxY = -1;
+
+ const markPixel = (x: number, y: number) => {
+ mask[y * width + x] = 255;
+ if (x < minX) minX = x;
+ if (x > maxX) maxX = x;
+ if (y < minY) minY = y;
+ if (y > maxY) maxY = y;
+ };
+
+ if (!settings.contiguous) {
+ // Non-contiguous: sample everywhere on canvas matching seed color
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ if (matches(x, y)) {
+ markPixel(x, y);
+ }
+ }
+ }
+ } else {
+ // Contiguous: optimized scanline flood fill
+ const stack: number[] = [startX, startY];
+
+ while (stack.length > 0) {
+ const cy = stack.pop()!;
+ const cx = stack.pop()!;
+
+ if (mask[cy * width + cx] !== 0 || !matches(cx, cy)) {
+ continue;
+ }
+
+ // Scan left
+ let left = cx;
+ while (left > 0 && mask[cy * width + (left - 1)] === 0 && matches(left - 1, cy)) {
+ left--;
+ }
+
+ // Scan right
+ let right = cx;
+ while (right < width - 1 && mask[cy * width + (right + 1)] === 0 && matches(right + 1, cy)) {
+ right++;
+ }
+
+ // Fill scanline interval
+ for (let x = left; x <= right; x++) {
+ markPixel(x, cy);
+ }
+
+ // Inspect scanline above and below
+ const checkScanline = (ny: number) => {
+ if (ny < 0 || ny >= height) return;
+ let inRun = false;
+ for (let x = left; x <= right; x++) {
+ if (mask[ny * width + x] === 0 && matches(x, ny)) {
+ if (!inRun) {
+ stack.push(x, ny);
+ inRun = true;
+ }
+ } else {
+ inRun = false;
+ }
+ }
+ };
+
+ checkScanline(cy - 1);
+ checkScanline(cy + 1);
+ }
+ }
+
+ // Anti-alias edge softening if enabled
+ if (settings.antiAlias && maxX >= minX && maxY >= minY) {
+ const featherBuffer = featherSelection(mask, width, height, 1);
+ for (let y = Math.max(0, minY - 1); y <= Math.min(height - 1, maxY + 1); y++) {
+ const row = y * width;
+ for (let x = Math.max(0, minX - 1); x <= Math.min(width - 1, maxX + 1); x++) {
+ if (mask[row + x] === 0 && featherBuffer[row + x] > 0) {
+ const diff = colorDiff(x, y);
+ if (diff <= tolerance + 4) {
+ mask[row + x] = featherBuffer[row + x];
+ }
+ }
+ }
+ }
+ }
+
+ const bounds =
+ maxX >= minX && maxY >= minY
+ ? { x: minX, y: minY, width: maxX - minX + 1, height: maxY - minY + 1 }
+ : { x: 0, y: 0, width: 0, height: 0 };
+
+ return { mask, bounds };
+}
+
+/**
+ * Traces the boundary contour of an 8-bit selection mask into an optimized SVG path.
+ * Collapses collinear segments for peak rendering performance.
+ */
+export function maskToSvgPath(
+ mask: Uint8Array,
+ width: number,
+ height: number,
+ threshold = 128
+): string {
+ if (width <= 0 || height <= 0) return '';
+
+ // Edge encoding: horizontal edges (HE) and vertical edges (VE)
+ // Vertex coordinates (x, y) range from [0, width] x [0, height].
+ // Directed edges ensuring the inside of the selection is always on the right:
+ // - Top of cell (x, y): from (x+1, y) to (x, y)
+ // - Bottom of cell (x, y): from (x, y+1) to (x+1, y+1)
+ // - Left of cell (x, y): from (x, y) to (x, y+1)
+ // - Right of cell (x, y): from (x+1, y+1) to (x+1, y)
+
+ const isInside = (x: number, y: number): boolean => {
+ if (x < 0 || x >= width || y < 0 || y >= height) return false;
+ return mask[y * width + x] >= threshold;
+ };
+
+ const vertexKey = (x: number, y: number): number => y * (width + 1) + x;
+ const keyToVertex = (k: number): { x: number; y: number } => ({
+ x: k % (width + 1),
+ y: Math.floor(k / (width + 1)),
+ });
+
+ // Outgoing edge list: Map from start vertex key to array of end vertex keys
+ const adj = new Map<number, number[]>();
+
+ const addEdge = (x1: number, y1: number, x2: number, y2: number) => {
+ const k1 = vertexKey(x1, y1);
+ const k2 = vertexKey(x2, y2);
+ const list = adj.get(k1);
+ if (!list) {
+ adj.set(k1, [k2]);
+ } else {
+ list.push(k2);
+ }
+ };
+
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const inCurrent = isInside(x, y);
+
+ // Top edge
+ if (inCurrent !== isInside(x, y - 1)) {
+ if (inCurrent) {
+ addEdge(x + 1, y, x, y);
+ } else {
+ addEdge(x, y, x + 1, y);
+ }
+ }
+
+ // Left edge
+ if (inCurrent !== isInside(x - 1, y)) {
+ if (inCurrent) {
+ addEdge(x, y, x, y + 1);
+ } else {
+ addEdge(x, y + 1, x, y);
+ }
+ }
+
+ // Bottom edge (only needed at border y === height - 1)
+ if (y === height - 1 && inCurrent) {
+ addEdge(x, y + 1, x + 1, y + 1);
+ }
+
+ // Right edge (only needed at border x === width - 1)
+ if (x === width - 1 && inCurrent) {
+ addEdge(x + 1, y + 1, x + 1, y);
+ }
+ }
+ }
+
+ if (adj.size === 0) return '';
+
+ let pathD = '';
+
+ // Trace closed loops
+ for (const [startK] of adj) {
+ while (true) {
+ const outEdges = adj.get(startK);
+ if (!outEdges || outEdges.length === 0) break;
+
+ const nextK = outEdges.pop()!;
+ if (outEdges.length === 0) adj.delete(startK);
+
+ const loop: Array<{ x: number; y: number }> = [
+ keyToVertex(startK),
+ keyToVertex(nextK),
+ ];
+
+ let currK = nextK;
+ while (currK !== startK) {
+ const nextList = adj.get(currK);
+ if (!nextList || nextList.length === 0) break;
+ const nk = nextList.pop()!;
+ if (nextList.length === 0) adj.delete(currK);
+ loop.push(keyToVertex(nk));
+ currK = nk;
+ }
+
+ if (loop.length < 3) continue;
+
+ // Collinear segment reduction
+ const simplified: Array<{ x: number; y: number }> = [loop[0]];
+ for (let i = 1; i < loop.length; i++) {
+ const prev = simplified[simplified.length - 1];
+ const curr = loop[i];
+ const next = loop[(i + 1) % loop.length];
+
+ const dx1 = curr.x - prev.x;
+ const dy1 = curr.y - prev.y;
+ const dx2 = next.x - curr.x;
+ const dy2 = next.y - curr.y;
+
+ // Check if current point is strictly collinear between prev and next
+ if (dx1 * dy2 === dy1 * dx2 && Math.sign(dx1) === Math.sign(dx2) && Math.sign(dy1) === Math.sign(dy2)) {
+ continue;
+ }
+ simplified.push(curr);
+ }
+
+ if (simplified.length < 3) continue;
+
+ let subPath = `M ${simplified[0].x} ${simplified[0].y} `;
+ for (let i = 1; i < simplified.length; i++) {
+ subPath += `L ${simplified[i].x} ${simplified[i].y} `;
+ }
+ subPath += 'Z ';
+ pathD += subPath;
+ }
+ }
+
+ return pathD.trim();
+}
+
+/**
+ * Computes tight bounding box of all non-transparent pixels on a canvas.
*/
export function getCanvasContentBounds(
canvas: HTMLCanvasElement,
@@ -163,11 +762,10 @@ export function liftSelectionToFloating(
return null;
}
- // 1. Snapshot the entire targetCanvas synchronously for undo/cancel
+ // 1. Snapshot entire targetCanvas synchronously for undo/cancel
const beforeImageData = targetCtx.getImageData(0, 0, targetCanvas.width, targetCanvas.height);
- // 2. Extract selection rectangle pixels directly using synchronous getImageData
- // This guarantees zero GPU command race conditions before clearRect!
+ // 2. Extract selection rectangle pixels directly
const extractedImageData = targetCtx.getImageData(b.x, b.y, b.width, b.height);
const floatingCanvas = document.createElement('canvas');
@@ -178,11 +776,35 @@ export function liftSelectionToFloating(
return null;
}
- // Put extracted pixels into floating canvas
floatCtx.putImageData(extractedImageData, 0, 0);
- // If lasso selection, mask to polygon using destination-in
- if (selection.type === 'lasso' && selection.polygon && selection.polygon.length >= 3) {
+ // 3. Mask floating canvas
+ if (selection.mask && selection.maskWidth && selection.maskHeight) {
+ const maskSub = document.createElement('canvas');
+ maskSub.width = b.width;
+ maskSub.height = b.height;
+ const mCtx = maskSub.getContext('2d');
+ if (mCtx) {
+ const mImg = mCtx.createImageData(b.width, b.height);
+ const mw = selection.maskWidth;
+ for (let y = 0; y < b.height; y++) {
+ const srcRow = (b.y + y) * mw;
+ const dstRow = y * b.width * 4;
+ for (let x = 0; x < b.width; x++) {
+ const val = selection.mask[srcRow + (b.x + x)] ?? 0;
+ mImg.data[dstRow + x * 4] = 255;
+ mImg.data[dstRow + x * 4 + 1] = 255;
+ mImg.data[dstRow + x * 4 + 2] = 255;
+ mImg.data[dstRow + x * 4 + 3] = val;
+ }
+ }
+ mCtx.putImageData(mImg, 0, 0);
+ floatCtx.save();
+ floatCtx.globalCompositeOperation = 'destination-in';
+ floatCtx.drawImage(maskSub, 0, 0);
+ floatCtx.restore();
+ }
+ } else if (selection.type === 'lasso' && selection.polygon && selection.polygon.length >= 3) {
floatCtx.save();
floatCtx.globalCompositeOperation = 'destination-in';
floatCtx.beginPath();
@@ -196,76 +818,69 @@ export function liftSelectionToFloating(
floatCtx.restore();
}
- // 3. Erase the extracted area from the base layer
- targetCtx.save();
- if (isBackground) {
- targetCtx.fillStyle = '#ffffff';
- if (selection.type === 'rect') {
- targetCtx.fillRect(b.x, b.y, b.width, b.height);
- } else if (selection.type === 'lasso' && selection.polygon) {
- targetCtx.beginPath();
- const poly = selection.polygon;
- targetCtx.moveTo(poly[0].x, poly[0].y);
- for (let i = 1; i < poly.length; i++) {
- targetCtx.lineTo(poly[i].x, poly[i].y);
+ // 4. Erase selected area from base layer
+ const eraseFromContext = (ctx: CanvasRenderingContext2D) => {
+ ctx.save();
+ if (selection.mask && selection.maskWidth && selection.maskHeight) {
+ const maskCanvas = document.createElement('canvas');
+ maskCanvas.width = targetCanvas.width;
+ maskCanvas.height = targetCanvas.height;
+ const mCtx = maskCanvas.getContext('2d');
+ if (mCtx) {
+ const mImg = mCtx.createImageData(targetCanvas.width, targetCanvas.height);
+ for (let i = 0; i < selection.mask.length; i++) {
+ mImg.data[i * 4] = 0;
+ mImg.data[i * 4 + 1] = 0;
+ mImg.data[i * 4 + 2] = 0;
+ mImg.data[i * 4 + 3] = selection.mask[i];
+ }
+ mCtx.putImageData(mImg, 0, 0);
+ if (isBackground) {
+ ctx.fillStyle = '#ffffff';
+ ctx.fillRect(b.x, b.y, b.width, b.height);
+ } else {
+ ctx.globalCompositeOperation = 'destination-out';
+ ctx.drawImage(maskCanvas, 0, 0);
+ }
}
- targetCtx.closePath();
- targetCtx.fill();
- }
- } else {
- if (selection.type === 'rect') {
- targetCtx.clearRect(b.x, b.y, b.width, b.height);
- } else if (selection.type === 'lasso' && selection.polygon) {
- targetCtx.globalCompositeOperation = 'destination-out';
- targetCtx.fillStyle = 'rgba(0, 0, 0, 1)';
- targetCtx.beginPath();
- const poly = selection.polygon;
- targetCtx.moveTo(poly[0].x, poly[0].y);
- for (let i = 1; i < poly.length; i++) {
- targetCtx.lineTo(poly[i].x, poly[i].y);
+ } else if (isBackground) {
+ ctx.fillStyle = '#ffffff';
+ if (selection.type === 'rect') {
+ ctx.fillRect(b.x, b.y, b.width, b.height);
+ } else if (selection.type === 'lasso' && selection.polygon) {
+ ctx.beginPath();
+ const poly = selection.polygon;
+ ctx.moveTo(poly[0].x, poly[0].y);
+ for (let i = 1; i < poly.length; i++) {
+ ctx.lineTo(poly[i].x, poly[i].y);
+ }
+ ctx.closePath();
+ ctx.fill();
+ }
+ } else {
+ if (selection.type === 'rect') {
+ ctx.clearRect(b.x, b.y, b.width, b.height);
+ } else if (selection.type === 'lasso' && selection.polygon) {
+ ctx.globalCompositeOperation = 'destination-out';
+ ctx.fillStyle = 'rgba(0, 0, 0, 1)';
+ ctx.beginPath();
+ const poly = selection.polygon;
+ ctx.moveTo(poly[0].x, poly[0].y);
+ for (let i = 1; i < poly.length; i++) {
+ ctx.lineTo(poly[i].x, poly[i].y);
+ }
+ ctx.closePath();
+ ctx.fill();
}
- targetCtx.closePath();
- targetCtx.fill();
}
- }
- targetCtx.restore();
+ ctx.restore();
+ };
+
+ eraseFromContext(targetCtx);
if (sourceCanvas) {
const sCtx = sourceCanvas.getContext('2d');
- if (sCtx) {
- sCtx.save();
- if (isBackground) {
- sCtx.fillStyle = '#ffffff';
- if (selection.type === 'rect') {
- sCtx.fillRect(b.x, b.y, b.width, b.height);
- } else if (selection.type === 'lasso' && selection.polygon) {
- sCtx.beginPath();
- const poly = selection.polygon;
- sCtx.moveTo(poly[0].x, poly[0].y);
- for (let i = 1; i < poly.length; i++) {
- sCtx.lineTo(poly[i].x, poly[i].y);
- }
- sCtx.closePath();
- sCtx.fill();
- }
- } else {
- if (selection.type === 'rect') {
- sCtx.clearRect(b.x, b.y, b.width, b.height);
- } else if (selection.type === 'lasso' && selection.polygon) {
- sCtx.globalCompositeOperation = 'destination-out';
- sCtx.fillStyle = 'rgba(0, 0, 0, 1)';
- sCtx.beginPath();
- const poly = selection.polygon;
- sCtx.moveTo(poly[0].x, poly[0].y);
- for (let i = 1; i < poly.length; i++) {
- sCtx.lineTo(poly[i].x, poly[i].y);
- }
- sCtx.closePath();
- sCtx.fill();
- }
- }
- sCtx.restore();
- }
+ if (sCtx) eraseFromContext(sCtx);
}
return { floatingCanvas, beforeImageData };
diff --git a/src/utils/tonalEngine.ts b/src/utils/tonalEngine.ts
index fa230c5..fe80fc8 100644
--- a/src/utils/tonalEngine.ts
+++ b/src/utils/tonalEngine.ts
@@ -1,4 +1,10 @@
-import { CanvasSelection } from '../types/editor';
+import {
+ CanvasSelection,
+ AdjustmentLayerData,
+ ToneCurvePoints,
+ GradientStop,
+ ColorBalanceAdjustmentData,
+} from '../types/editor';
export type TonalCorrectionType =
| 'brightness-contrast'
@@ -539,3 +545,406 @@ export function applyTonalFilter(
}
}
}
+
+/**
+ * Builds a monotonic cubic spline lookup table (256 entries) using Fritsch-Carlson algorithm.
+ * Guarantees zero overshoot and strictly preserves monotonicity of control points.
+ */
+export function buildMonotonicCubicSplineLut(points: [number, number][]): Uint8Array {
+ const lut = new Uint8Array(256);
+ if (!points || points.length === 0) {
+ for (let i = 0; i < 256; i++) lut[i] = i;
+ return lut;
+ }
+
+ // Sort by X coordinate and remove duplicates
+ const sorted = [...points].sort((a, b) => a[0] - b[0]);
+ const unique: [number, number][] = [];
+ for (const pt of sorted) {
+ if (unique.length > 0 && unique[unique.length - 1][0] === pt[0]) {
+ unique[unique.length - 1] = pt; // replace duplicate with later one
+ } else {
+ unique.push([pt[0], pt[1]]);
+ }
+ }
+
+ const n = unique.length;
+ if (n === 1) {
+ const val = Math.max(0, Math.min(255, Math.round(unique[0][1])));
+ lut.fill(val);
+ return lut;
+ }
+
+ // Secants Delta_k
+ const deltas = new Float64Array(n - 1);
+ for (let k = 0; k < n - 1; k++) {
+ const dx = unique[k + 1][0] - unique[k][0];
+ const dy = unique[k + 1][1] - unique[k][1];
+ deltas[k] = dx === 0 ? 0 : dy / dx;
+ }
+
+ // Initial tangents m_k
+ const m = new Float64Array(n);
+ m[0] = deltas[0];
+ m[n - 1] = deltas[n - 2];
+ for (let k = 1; k < n - 1; k++) {
+ m[k] = (deltas[k - 1] + deltas[k]) / 2;
+ }
+
+ // Fritsch-Carlson monotonicity condition
+ for (let k = 0; k < n - 1; k++) {
+ if (deltas[k] === 0) {
+ m[k] = 0;
+ m[k + 1] = 0;
+ } else {
+ const alpha = m[k] / deltas[k];
+ const beta = m[k + 1] / deltas[k];
+ if (alpha < 0) m[k] = 0;
+ if (beta < 0) m[k + 1] = 0;
+ const hypSq = alpha * alpha + beta * beta;
+ if (hypSq > 9) {
+ const tau = 3 / Math.sqrt(hypSq);
+ m[k] = tau * alpha * deltas[k];
+ m[k + 1] = tau * beta * deltas[k];
+ }
+ }
+ }
+
+ // Sample Hermite cubic spline for x = 0..255
+ for (let x = 0; x < 256; x++) {
+ if (x <= unique[0][0]) {
+ lut[x] = Math.max(0, Math.min(255, Math.round(unique[0][1])));
+ continue;
+ }
+ if (x >= unique[n - 1][0]) {
+ lut[x] = Math.max(0, Math.min(255, Math.round(unique[n - 1][1])));
+ continue;
+ }
+
+ // Locate segment
+ let k = 0;
+ while (k < n - 1 && x > unique[k + 1][0]) {
+ k++;
+ }
+
+ const x0 = unique[k][0];
+ const x1 = unique[k + 1][0];
+ const y0 = unique[k][1];
+ const y1 = unique[k + 1][1];
+ const h = x1 - x0;
+ const t = h === 0 ? 0 : (x - x0) / h;
+ const t2 = t * t;
+ const t3 = t2 * t;
+
+ const h00 = 2 * t3 - 3 * t2 + 1;
+ const h10 = t3 - 2 * t2 + t;
+ const h01 = -2 * t3 + 3 * t2;
+ const h11 = t3 - t2;
+
+ const y = h00 * y0 + h10 * h * m[k] + h01 * y1 + h11 * h * m[k + 1];
+ lut[x] = Math.max(0, Math.min(255, Math.round(y)));
+ }
+
+ return lut;
+}
+
+/**
+ * Combines channel curves (R, G, B) with Master RGB curve into unified 256-entry channel LUTs.
+ */
+export function buildCurvesCombinedLut(curveData: ToneCurvePoints): {
+ rLut: Uint8Array;
+ gLut: Uint8Array;
+ bLut: Uint8Array;
+} {
+ const masterLut = buildMonotonicCubicSplineLut(curveData.rgb || [[0, 0], [255, 255]]);
+ const rLutRaw = buildMonotonicCubicSplineLut(curveData.r || [[0, 0], [255, 255]]);
+ const gLutRaw = buildMonotonicCubicSplineLut(curveData.g || [[0, 0], [255, 255]]);
+ const bLutRaw = buildMonotonicCubicSplineLut(curveData.b || [[0, 0], [255, 255]]);
+
+ const rLut = new Uint8Array(256);
+ const gLut = new Uint8Array(256);
+ const bLut = new Uint8Array(256);
+
+ for (let i = 0; i < 256; i++) {
+ rLut[i] = masterLut[rLutRaw[i]];
+ gLut[i] = masterLut[gLutRaw[i]];
+ bLut[i] = masterLut[bLutRaw[i]];
+ }
+
+ return { rLut, gLut, bLut };
+}
+
+/**
+ * Parses hex color to RGB tuple [0-255].
+ */
+export function parseHexToRgb(hex: string): [number, number, number] {
+ let clean = hex.replace('#', '');
+ if (clean.length === 3) {
+ clean = clean.split('').map((c) => c + c).join('');
+ }
+ const val = parseInt(clean, 16);
+ if (isNaN(val)) return [0, 0, 0];
+ return [(val >> 16) & 255, (val >> 8) & 255, val & 255];
+}
+
+/**
+ * Precomputes 256-entry RGBA LUT for Gradient Map.
+ * Maps normalized luminosity [0, 1] through custom color stops.
+ */
+export function buildGradientMapLut(
+ stops: GradientStop[],
+ interpolation: 'linear' | 'smooth' = 'linear'
+): Uint8ClampedArray {
+ const lut = new Uint8ClampedArray(256 * 4); // RGBA format
+ if (!stops || stops.length === 0) {
+ // Default grayscale gradient
+ for (let i = 0; i < 256; i++) {
+ const offset = i * 4;
+ lut[offset] = i;
+ lut[offset + 1] = i;
+ lut[offset + 2] = i;
+ lut[offset + 3] = 255;
+ }
+ return lut;
+ }
+
+ const sorted = [...stops].sort((a, b) => a.position - b.position);
+ const parsedStops = sorted.map((s) => ({
+ pos: Math.max(0, Math.min(1, s.position)),
+ rgb: parseHexToRgb(s.color),
+ }));
+
+ for (let i = 0; i < 256; i++) {
+ const t = i / 255;
+ const offset = i * 4;
+
+ if (t <= parsedStops[0].pos) {
+ const [r, g, b] = parsedStops[0].rgb;
+ lut[offset] = r;
+ lut[offset + 1] = g;
+ lut[offset + 2] = b;
+ lut[offset + 3] = 255;
+ continue;
+ }
+
+ if (t >= parsedStops[parsedStops.length - 1].pos) {
+ const [r, g, b] = parsedStops[parsedStops.length - 1].rgb;
+ lut[offset] = r;
+ lut[offset + 1] = g;
+ lut[offset + 2] = b;
+ lut[offset + 3] = 255;
+ continue;
+ }
+
+ // Locate segment
+ let sIdx = 0;
+ while (sIdx < parsedStops.length - 1 && t > parsedStops[sIdx + 1].pos) {
+ sIdx++;
+ }
+
+ const s0 = parsedStops[sIdx];
+ const s1 = parsedStops[sIdx + 1];
+ const span = s1.pos - s0.pos;
+ let factor = span <= 0 ? 0 : (t - s0.pos) / span;
+
+ if (interpolation === 'smooth') {
+ factor = factor * factor * (3 - 2 * factor); // smoothstep
+ }
+
+ const r = Math.round(s0.rgb[0] + (s1.rgb[0] - s0.rgb[0]) * factor);
+ const g = Math.round(s0.rgb[1] + (s1.rgb[1] - s0.rgb[1]) * factor);
+ const b = Math.round(s0.rgb[2] + (s1.rgb[2] - s0.rgb[2]) * factor);
+
+ lut[offset] = Math.max(0, Math.min(255, r));
+ lut[offset + 1] = Math.max(0, Math.min(255, g));
+ lut[offset + 2] = Math.max(0, Math.min(255, b));
+ lut[offset + 3] = 255;
+ }
+
+ return lut;
+}
+
+/**
+ * Applies Color Balance adjustment to a single RGB pixel.
+ * Shadows, midtones, and highlights shifts for Cyan-Red, Magenta-Green, Yellow-Blue.
+ */
+export function evaluateColorBalancePixel(
+ r: number,
+ g: number,
+ b: number,
+ params: ColorBalanceAdjustmentData
+): [number, number, number] {
+ const lum = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
+
+ // Weight curves: shadows peak at 0, midtones peak at 0.5, highlights peak at 1
+ const wShad = Math.pow(Math.max(0, 1.0 - lum * 2.0), 2);
+ const wHigh = Math.pow(Math.max(0, lum * 2.0 - 1.0), 2);
+ const wMid = Math.max(0, 1.0 - wShad - wHigh);
+
+ const deltaR = (params.shadows[0] * wShad + params.midtones[0] * wMid + params.highlights[0] * wHigh) * 1.28;
+ const deltaG = (params.shadows[1] * wShad + params.midtones[1] * wMid + params.highlights[1] * wHigh) * 1.28;
+ const deltaB = (params.shadows[2] * wShad + params.midtones[2] * wMid + params.highlights[2] * wHigh) * 1.28;
+
+ let newR = Math.max(0, Math.min(255, r + deltaR));
+ let newG = Math.max(0, Math.min(255, g + deltaG));
+ let newB = Math.max(0, Math.min(255, b + deltaB));
+
+ if (params.preserveLuminosity) {
+ const origLum = lum * 255;
+ const newLum = 0.299 * newR + 0.587 * newG + 0.114 * newB;
+ if (newLum > 0.001) {
+ const scale = origLum / newLum;
+ newR = Math.max(0, Math.min(255, newR * scale));
+ newG = Math.max(0, Math.min(255, newG * scale));
+ newB = Math.max(0, Math.min(255, newB * scale));
+ }
+ }
+
+ return [Math.round(newR), Math.round(newG), Math.round(newB)];
+}
+
+/**
+ * Universal evaluator for non-destructive adjustment layers directly on ImageData.
+ * Used for 2D compositor fallback, caching, or layer flattening.
+ */
+export function applyAdjustment(
+ imageData: ImageData,
+ adjustment: AdjustmentLayerData,
+ maskCanvas?: HTMLCanvasElement | null,
+ opacity: number = 1.0
+): void {
+ const d = imageData.data;
+ const w = imageData.width;
+ const h = imageData.height;
+ const totalPixels = w * h;
+
+ // Extract mask luminosity data if maskCanvas is provided
+ let maskData: Uint8ClampedArray | null = null;
+ if (maskCanvas) {
+ const mCtx = maskCanvas.getContext('2d', { willReadFrequently: true });
+ if (mCtx) {
+ maskData = mCtx.getImageData(0, 0, w, h).data;
+ }
+ }
+
+ if (adjustment.type === 'curves') {
+ const { rLut, gLut, bLut } = buildCurvesCombinedLut(adjustment.curves);
+ for (let p = 0; p < totalPixels; p++) {
+ const i = p * 4;
+ if (d[i + 3] === 0) continue;
+
+ let maskFactor = opacity;
+ if (maskData) {
+ const maskLum = (0.299 * maskData[i] + 0.587 * maskData[i + 1] + 0.114 * maskData[i + 2]) / 255 * (maskData[i + 3] / 255);
+ maskFactor *= maskLum;
+ }
+ if (maskFactor <= 0.001) continue;
+
+ const targetR = rLut[d[i]];
+ const targetG = gLut[d[i + 1]];
+ const targetB = bLut[d[i + 2]];
+
+ if (maskFactor >= 0.999) {
+ d[i] = targetR;
+ d[i + 1] = targetG;
+ d[i + 2] = targetB;
+ } else {
+ d[i] = Math.round(d[i] + (targetR - d[i]) * maskFactor);
+ d[i + 1] = Math.round(d[i + 1] + (targetG - d[i + 1]) * maskFactor);
+ d[i + 2] = Math.round(d[i + 2] + (targetB - d[i + 2]) * maskFactor);
+ }
+ }
+ return;
+ }
+
+ if (adjustment.type === 'gradient-map') {
+ const lut = buildGradientMapLut(adjustment.stops, adjustment.interpolation || 'linear');
+ for (let p = 0; p < totalPixels; p++) {
+ const i = p * 4;
+ if (d[i + 3] === 0) continue;
+
+ let maskFactor = opacity;
+ if (maskData) {
+ const maskLum = (0.299 * maskData[i] + 0.587 * maskData[i + 1] + 0.114 * maskData[i + 2]) / 255 * (maskData[i + 3] / 255);
+ maskFactor *= maskLum;
+ }
+ if (maskFactor <= 0.001) continue;
+
+ const lum = Math.round(0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2]);
+ const lutOffset = Math.max(0, Math.min(255, lum)) * 4;
+ const targetR = lut[lutOffset];
+ const targetG = lut[lutOffset + 1];
+ const targetB = lut[lutOffset + 2];
+
+ if (maskFactor >= 0.999) {
+ d[i] = targetR;
+ d[i + 1] = targetG;
+ d[i + 2] = targetB;
+ } else {
+ d[i] = Math.round(d[i] + (targetR - d[i]) * maskFactor);
+ d[i + 1] = Math.round(d[i + 1] + (targetG - d[i + 1]) * maskFactor);
+ d[i + 2] = Math.round(d[i + 2] + (targetB - d[i + 2]) * maskFactor);
+ }
+ }
+ return;
+ }
+
+ if (adjustment.type === 'levels') {
+ const lut = buildLevelsLut(
+ adjustment.blackPoint,
+ adjustment.whitePoint,
+ adjustment.gamma,
+ adjustment.outputMin ?? 0,
+ adjustment.outputMax ?? 255
+ );
+ const channel = adjustment.channel || 'rgb';
+ for (let p = 0; p < totalPixels; p++) {
+ const i = p * 4;
+ if (d[i + 3] === 0) continue;
+
+ let maskFactor = opacity;
+ if (maskData) {
+ const maskLum = (0.299 * maskData[i] + 0.587 * maskData[i + 1] + 0.114 * maskData[i + 2]) / 255 * (maskData[i + 3] / 255);
+ maskFactor *= maskLum;
+ }
+ if (maskFactor <= 0.001) continue;
+
+ if (channel === 'rgb') {
+ const tR = lut[d[i]];
+ const tG = lut[d[i + 1]];
+ const tB = lut[d[i + 2]];
+ d[i] = Math.round(d[i] + (tR - d[i]) * maskFactor);
+ d[i + 1] = Math.round(d[i + 1] + (tG - d[i + 1]) * maskFactor);
+ d[i + 2] = Math.round(d[i + 2] + (tB - d[i + 2]) * maskFactor);
+ } else if (channel === 'r') {
+ d[i] = Math.round(d[i] + (lut[d[i]] - d[i]) * maskFactor);
+ } else if (channel === 'g') {
+ d[i + 1] = Math.round(d[i + 1] + (lut[d[i + 1]] - d[i + 1]) * maskFactor);
+ } else if (channel === 'b') {
+ d[i + 2] = Math.round(d[i + 2] + (lut[d[i + 2]] - d[i + 2]) * maskFactor);
+ }
+ }
+ return;
+ }
+
+ if (adjustment.type === 'color-balance') {
+ for (let p = 0; p < totalPixels; p++) {
+ const i = p * 4;
+ if (d[i + 3] === 0) continue;
+
+ let maskFactor = opacity;
+ if (maskData) {
+ const maskLum = (0.299 * maskData[i] + 0.587 * maskData[i + 1] + 0.114 * maskData[i + 2]) / 255 * (maskData[i + 3] / 255);
+ maskFactor *= maskLum;
+ }
+ if (maskFactor <= 0.001) continue;
+
+ const [tR, tG, tB] = evaluateColorBalancePixel(d[i], d[i + 1], d[i + 2], adjustment);
+ d[i] = Math.round(d[i] + (tR - d[i]) * maskFactor);
+ d[i + 1] = Math.round(d[i + 1] + (tG - d[i + 1]) * maskFactor);
+ d[i + 2] = Math.round(d[i + 2] + (tB - d[i + 2]) * maskFactor);
+ }
+ return;
+ }
+}
+
diff --git a/src/utils/transformEngine.ts b/src/utils/transformEngine.ts
new file mode 100644
index 0000000..f7b10a3
--- /dev/null
+++ b/src/utils/transformEngine.ts
@@ -0,0 +1,416 @@
+import { Point2D } from '../types/editor';
+
+/**
+ * Computes the 3x3 projective transformation (homography) parameters
+ * mapping unit square [0,1]^2 to quadrilateral (p0, p1, p2, p3).
+ * Uses Heckbert's closed-form algorithm.
+ */
+export function solveUnitSquareToQuad(
+ p0: Point2D,
+ p1: Point2D,
+ p2: Point2D,
+ p3: Point2D
+): { a: number; b: number; c: number; d: number; e: number; f: number; g: number; h: number } {
+ const dx1 = p1.x - p2.x;
+ const dx2 = p3.x - p2.x;
+ const sx = p0.x - p1.x + p2.x - p3.x;
+
+ const dy1 = p1.y - p2.y;
+ const dy2 = p3.y - p2.y;
+ const sy = p0.y - p1.y + p2.y - p3.y;
+
+ if (Math.abs(sx) < 1e-7 && Math.abs(sy) < 1e-7) {
+ // Affine mapping
+ return {
+ a: p1.x - p0.x,
+ b: p3.x - p0.x,
+ c: p0.x,
+ d: p1.y - p0.y,
+ e: p3.y - p0.y,
+ f: p0.y,
+ g: 0,
+ h: 0,
+ };
+ }
+
+ const det = dx1 * dy2 - dy1 * dx2;
+ const g = Math.abs(det) > 1e-7 ? (sx * dy2 - sy * dx2) / det : 0;
+ const h = Math.abs(det) > 1e-7 ? (dx1 * sy - dy1 * sx) / det : 0;
+
+ return {
+ a: p1.x - p0.x + g * p1.x,
+ b: p3.x - p0.x + h * p3.x,
+ c: p0.x,
+ d: p1.y - p0.y + g * p1.y,
+ e: p3.y - p0.y + h * p3.y,
+ f: p0.y,
+ g,
+ h,
+ };
+}
+
+/**
+ * Maps normalized coordinates (u, v) in [0, 1]^2 to target coordinates (x, y)
+ * using solved homography.
+ */
+export function evaluateHomography(
+ h: { a: number; b: number; c: number; d: number; e: number; f: number; g: number; h: number },
+ u: number,
+ v: number
+): Point2D {
+ const denom = h.g * u + h.h * v + 1;
+ const safeDenom = Math.abs(denom) < 1e-5 ? (denom < 0 ? -1e-5 : 1e-5) : denom;
+ return {
+ x: (h.a * u + h.b * v + h.c) / safeDenom,
+ y: (h.d * u + h.e * v + h.f) / safeDenom,
+ };
+}
+
+/**
+ * 1D Catmull-Rom spline evaluation passing through p1 and p2.
+ */
+function catmullRom1D(p0: number, p1: number, p2: number, p3: number, t: number): number {
+ const t2 = t * t;
+ const t3 = t2 * t;
+ return 0.5 * (
+ 2 * p1 +
+ (-p0 + p2) * t +
+ (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 +
+ (-p0 + 3 * p1 - 3 * p2 + p3) * t3
+ );
+}
+
+/**
+ * Evaluates 2D Catmull-Rom surface point at normalized parameter (u, v) in [0, 1]^2.
+ */
+export function evaluateMeshSurface(
+ meshPoints: Point2D[][],
+ u: number,
+ v: number
+): Point2D {
+ const rows = meshPoints.length;
+ const cols = meshPoints[0]?.length || 0;
+ if (rows < 2 || cols < 2) return { x: 0, y: 0 };
+
+ const clampedU = Math.max(0, Math.min(1, u));
+ const clampedV = Math.max(0, Math.min(1, v));
+
+ const scaledU = clampedU * (cols - 1);
+ const colIdx = Math.min(Math.floor(scaledU), cols - 2);
+ const t = scaledU - colIdx;
+
+ const scaledV = clampedV * (rows - 1);
+ const rowIdx = Math.min(Math.floor(scaledV), rows - 2);
+ const s = scaledV - rowIdx;
+
+ // Helper to safely get point with border clamping
+ const getP = (r: number, c: number): Point2D => {
+ const cr = Math.max(0, Math.min(rows - 1, r));
+ const cc = Math.max(0, Math.min(cols - 1, c));
+ return meshPoints[cr][cc];
+ };
+
+ // Interpolate 4 row spans across u
+ const rowPoints: Point2D[] = [];
+ for (let r = rowIdx - 1; r <= rowIdx + 2; r++) {
+ const p0 = getP(r, colIdx - 1);
+ const p1 = getP(r, colIdx);
+ const p2 = getP(r, colIdx + 1);
+ const p3 = getP(r, colIdx + 2);
+
+ rowPoints.push({
+ x: catmullRom1D(p0.x, p1.x, p2.x, p3.x, t),
+ y: catmullRom1D(p0.y, p1.y, p2.y, p3.y, t),
+ });
+ }
+
+ // Interpolate across v
+ return {
+ x: catmullRom1D(rowPoints[0].x, rowPoints[1].x, rowPoints[2].x, rowPoints[3].x, s),
+ y: catmullRom1D(rowPoints[0].y, rowPoints[1].y, rowPoints[2].y, rowPoints[3].y, s),
+ };
+}
+
+/**
+ * Renders an affine-mapped triangle from sourceCanvas onto destination context.
+ */
+export function drawAffineTriangle(
+ ctx: CanvasRenderingContext2D,
+ sourceCanvas: HTMLCanvasElement,
+ sx0: number, sy0: number,
+ sx1: number, sy1: number,
+ sx2: number, sy2: number,
+ dx0: number, dy0: number,
+ dx1: number, dy1: number,
+ dx2: number, dy2: number
+): void {
+ const du1 = sx1 - sx0;
+ const du2 = sx2 - sx0;
+ const dv1 = sy1 - sy0;
+ const dv2 = sy2 - sy0;
+ const det = du1 * dv2 - du2 * dv1;
+ if (Math.abs(det) < 1e-6) return;
+
+ const dx1_0 = dx1 - dx0;
+ const dx2_0 = dx2 - dx0;
+ const dy1_0 = dy1 - dy0;
+ const dy2_0 = dy2 - dy0;
+
+ const a = (dx1_0 * dv2 - dx2_0 * dv1) / det;
+ const c = (du1 * dx2_0 - du2 * dx1_0) / det;
+ const e = dx0 - a * sx0 - c * sy0;
+
+ const b = (dy1_0 * dv2 - dy2_0 * dv1) / det;
+ const d = (du1 * dy2_0 - du2 * dy1_0) / det;
+ const f = dy0 - b * sx0 - d * sy0;
+
+ ctx.save();
+ ctx.beginPath();
+ // Expand triangle slightly towards centroid to avoid subpixel seam artifacts
+ const cx = (dx0 + dx1 + dx2) / 3;
+ const cy = (dy0 + dy1 + dy2) / 3;
+ const expand = 0.5;
+
+ const ex0 = dx0 + Math.sign(dx0 - cx) * expand;
+ const ey0 = dy0 + Math.sign(dy0 - cy) * expand;
+ const ex1 = dx1 + Math.sign(dx1 - cx) * expand;
+ const ey1 = dy1 + Math.sign(dy1 - cy) * expand;
+ const ex2 = dx2 + Math.sign(dx2 - cx) * expand;
+ const ey2 = dy2 + Math.sign(dy2 - cy) * expand;
+
+ ctx.moveTo(ex0, ey0);
+ ctx.lineTo(ex1, ey1);
+ ctx.lineTo(ex2, ey2);
+ ctx.closePath();
+ ctx.clip();
+
+ ctx.transform(a, b, c, d, e, f);
+ ctx.drawImage(sourceCanvas, 0, 0);
+ ctx.restore();
+}
+
+/**
+ * Renders sourceCanvas deformed into a Perspective Quad using homography triangle slicing.
+ */
+export function renderPerspectiveQuad(
+ ctx: CanvasRenderingContext2D,
+ sourceCanvas: HTMLCanvasElement,
+ quad: [Point2D, Point2D, Point2D, Point2D],
+ subdivisions = 16
+): void {
+ const sw = sourceCanvas.width;
+ const sh = sourceCanvas.height;
+ if (sw <= 0 || sh <= 0) return;
+
+ const homography = solveUnitSquareToQuad(quad[0], quad[1], quad[2], quad[3]);
+
+ // Precompute grid vertices
+ const grid: Point2D[][] = [];
+ for (let j = 0; j <= subdivisions; j++) {
+ const row: Point2D[] = [];
+ const v = j / subdivisions;
+ for (let i = 0; i <= subdivisions; i++) {
+ const u = i / subdivisions;
+ row.push(evaluateHomography(homography, u, v));
+ }
+ grid.push(row);
+ }
+
+ // Draw two triangles for each quad cell
+ for (let j = 0; j < subdivisions; j++) {
+ const v0 = (j / subdivisions) * sh;
+ const v1 = ((j + 1) / subdivisions) * sh;
+ for (let i = 0; i < subdivisions; i++) {
+ const u0 = (i / subdivisions) * sw;
+ const u1 = ((i + 1) / subdivisions) * sw;
+
+ const p00 = grid[j][i];
+ const p10 = grid[j][i + 1];
+ const p11 = grid[j + 1][i + 1];
+ const p01 = grid[j + 1][i];
+
+ // Triangle 1: (0,0) - (1,0) - (0,1)
+ drawAffineTriangle(
+ ctx, sourceCanvas,
+ u0, v0, u1, v0, u0, v1,
+ p00.x, p00.y, p10.x, p10.y, p01.x, p01.y
+ );
+
+ // Triangle 2: (1,0) - (1,1) - (0,1)
+ drawAffineTriangle(
+ ctx, sourceCanvas,
+ u1, v0, u1, v1, u0, v1,
+ p10.x, p10.y, p11.x, p11.y, p01.x, p01.y
+ );
+ }
+ }
+}
+
+/**
+ * Renders sourceCanvas deformed via 2D Catmull-Rom Bicubic Mesh Lattice.
+ */
+export function renderMeshWarp(
+ ctx: CanvasRenderingContext2D,
+ sourceCanvas: HTMLCanvasElement,
+ meshPoints: Point2D[][],
+ subPerCell = 4
+): void {
+ const sw = sourceCanvas.width;
+ const sh = sourceCanvas.height;
+ if (sw <= 0 || sh <= 0) return;
+
+ const rows = meshPoints.length;
+ const cols = meshPoints[0]?.length || 0;
+ if (rows < 2 || cols < 2) return;
+
+ const totalCols = (cols - 1) * subPerCell;
+ const totalRows = (rows - 1) * subPerCell;
+
+ // Precompute evaluated surface vertices
+ const grid: Point2D[][] = [];
+ for (let j = 0; j <= totalRows; j++) {
+ const row: Point2D[] = [];
+ const v = j / totalRows;
+ for (let i = 0; i <= totalCols; i++) {
+ const u = i / totalCols;
+ row.push(evaluateMeshSurface(meshPoints, u, v));
+ }
+ grid.push(row);
+ }
+
+ // Draw triangles for each sub-cell
+ for (let j = 0; j < totalRows; j++) {
+ const v0 = (j / totalRows) * sh;
+ const v1 = ((j + 1) / totalRows) * sh;
+ for (let i = 0; i < totalCols; i++) {
+ const u0 = (i / totalCols) * sw;
+ const u1 = ((i + 1) / totalCols) * sw;
+
+ const p00 = grid[j][i];
+ const p10 = grid[j][i + 1];
+ const p11 = grid[j + 1][i + 1];
+ const p01 = grid[j + 1][i];
+
+ // Triangle 1: (0,0) - (1,0) - (0,1)
+ drawAffineTriangle(
+ ctx, sourceCanvas,
+ u0, v0, u1, v0, u0, v1,
+ p00.x, p00.y, p10.x, p10.y, p01.x, p01.y
+ );
+
+ // Triangle 2: (1,0) - (1,1) - (0,1)
+ drawAffineTriangle(
+ ctx, sourceCanvas,
+ u1, v0, u1, v1, u0, v1,
+ p10.x, p10.y, p11.x, p11.y, p01.x, p01.y
+ );
+ }
+ }
+}
+
+/**
+ * Creates default 4 perspective corner pins from bounds.
+ * Order: [TL, TR, BR, BL]
+ */
+export function createDefaultPerspectiveQuad(
+ x: number,
+ y: number,
+ width: number,
+ height: number,
+ rotation = 0
+): [Point2D, Point2D, Point2D, Point2D] {
+ if (rotation === 0) {
+ return [
+ { x, y },
+ { x: x + width, y },
+ { x: x + width, y: y + height },
+ { x, y: y + height },
+ ];
+ }
+
+ const cx = x + width / 2;
+ const cy = y + height / 2;
+ const rad = (rotation * Math.PI) / 180;
+ const cos = Math.cos(rad);
+ const sin = Math.sin(rad);
+
+ const rotate = (px: number, py: number): Point2D => {
+ const rx = px - cx;
+ const ry = py - cy;
+ return {
+ x: Math.round(cx + rx * cos - ry * sin),
+ y: Math.round(cy + rx * sin + ry * cos),
+ };
+ };
+
+ return [
+ rotate(x, y),
+ rotate(x + width, y),
+ rotate(x + width, y + height),
+ rotate(x, y + height),
+ ];
+}
+
+/**
+ * Creates a default grid of (rows x cols) control points interpolated from 4 corners.
+ */
+export function createDefaultMeshPoints(
+ quad: [Point2D, Point2D, Point2D, Point2D],
+ cols = 4,
+ rows = 4
+): Point2D[][] {
+ const [q0, q1, q2, q3] = quad;
+ const points: Point2D[][] = [];
+
+ for (let r = 0; r < rows; r++) {
+ const v = rows > 1 ? r / (rows - 1) : 0;
+ const row: Point2D[] = [];
+ for (let c = 0; c < cols; c++) {
+ const u = cols > 1 ? c / (cols - 1) : 0;
+ // Bilinear interpolation across corners
+ const x = (1 - u) * (1 - v) * q0.x + u * (1 - v) * q1.x + u * v * q2.x + (1 - u) * v * q3.x;
+ const y = (1 - u) * (1 - v) * q0.y + u * (1 - v) * q1.y + u * v * q2.y + (1 - u) * v * q3.y;
+ row.push({ x: Math.round(x), y: Math.round(y) });
+ }
+ points.push(row);
+ }
+
+ return points;
+}
+
+/**
+ * Calculates tight bounding box of a perspective quad or mesh point set.
+ */
+export function getPointsBounds(points: Point2D[]): {
+ minX: number;
+ minY: number;
+ maxX: number;
+ maxY: number;
+ width: number;
+ height: number;
+} {
+ if (points.length === 0) {
+ return { minX: 0, minY: 0, maxX: 0, maxY: 0, width: 0, height: 0 };
+ }
+ let minX = points[0].x;
+ let maxX = points[0].x;
+ let minY = points[0].y;
+ let maxY = points[0].y;
+
+ for (let i = 1; i < points.length; i++) {
+ const p = points[i];
+ if (p.x < minX) minX = p.x;
+ if (p.x > maxX) maxX = p.x;
+ if (p.y < minY) minY = p.y;
+ if (p.y > maxY) maxY = p.y;
+ }
+
+ return {
+ minX: Math.floor(minX),
+ minY: Math.floor(minY),
+ maxX: Math.ceil(maxX),
+ maxY: Math.ceil(maxY),
+ width: Math.max(1, Math.ceil(maxX - minX)),
+ height: Math.max(1, Math.ceil(maxY - minY)),
+ };
+}