Group local mask shapes into editable components.

A local adjustment is now a list of shapes composited in order (add, subtract,
intersect) instead of a single shape, so dodging and burning can be built from
several brushes, gradients and auto masks without spending layer channels.
Existing edits migrate on load: the flat layer fields become components[0],
keeping geometry, invert, feather and the layer's blend mode unchanged. The
panel gains a shape list with active-shape editing, and the render gate now
asserts a subtract shape clears the group while an intersect keeps it.
This commit is contained in:
2026-11-28 16:09:14 +00:00
parent acf582251f
commit b884616889
10 changed files with 666 additions and 183 deletions
+52 -4
View File
@@ -96,7 +96,7 @@ const PAGE_HTML = `<!doctype html>
<script type="module">
import { parsePreview16 } from '/src/lib/preview16.ts';
import { Renderer } from '/src/gl/renderer.ts';
import { defaultEdits, defaultLocalLayer } from '/src/lib/edits.ts';
import { defaultEdits, defaultLocalComponent, defaultLocalLayer } from '/src/lib/edits.ts';
const pre = document.getElementById('out');
const half = (bits) => {
const s = bits >> 15 ? -1 : 1;
@@ -229,16 +229,48 @@ try {
// curve and then with one that halves the output. The mask must leave the
// frame alone with the identity curve and darken it with the real one.
const maskLayer = defaultLocalLayer('radial', 0);
maskLayer.feather = 0;
maskLayer.radial = { cx: 0.5, cy: 0.5, rx: 1.2, ry: 1.2 };
const maskShape = maskLayer.components[0];
maskShape.feather = 0;
maskShape.radial = { cx: 0.5, cy: 0.5, rx: 1.2, ry: 1.2 };
const darkCurve = [
{ x: 0, y: 0 },
{ x: 1, y: 0.4 },
];
const maskedEdits = defaultEdits();
maskedEdits.local = [{ ...maskLayer, curve: [{ x: 0, y: 0 }, { x: 1, y: 1 }] }];
renderer.render(maskedEdits, { width: w, height: h });
const maskIdentityPixel = sampleBand(2);
maskedEdits.local = [{ ...maskLayer, curve: [{ x: 0, y: 0 }, { x: 1, y: 0.4 }] }];
maskedEdits.local = [{ ...maskLayer, curve: darkCurve }];
renderer.render(maskedEdits, { width: w, height: h });
const maskCurvePixel = sampleBand(2);
// Mask groups: a second shape has to composite into the layer's own mask.
// Subtracting a frame-wide shape from an equally wide add shape clears the
// group, so the darkened curve must stop touching the frame; intersecting
// with the same shape keeps full coverage, so it must still darken.
const groupShape = defaultLocalComponent('radial');
groupShape.feather = 0;
groupShape.radial = { cx: 0.5, cy: 0.5, rx: 1.2, ry: 1.2 };
const groupEdits = defaultEdits();
groupEdits.local = [
{
...maskLayer,
curve: darkCurve,
components: [maskShape, { ...groupShape, mode: 'subtract' }],
},
];
renderer.render(groupEdits, { width: w, height: h });
const maskGroupSubtractPixel = sampleBand(2);
groupEdits.local = [
{
...maskLayer,
curve: darkCurve,
components: [maskShape, { ...groupShape, mode: 'intersect' }],
},
];
renderer.render(groupEdits, { width: w, height: h });
const maskGroupIntersectPixel = sampleBand(2);
pre.textContent = 'RESULT ' + JSON.stringify({
clipPixels,
clipRed: near(clipPixels[0], RED_MARK),
@@ -261,6 +293,10 @@ try {
maskCurvePixel,
maskIdentityFlat: near(maskIdentityPixel, [61, 71, 89]),
maskCurveDarkens: maskCurvePixel[0] < maskIdentityPixel[0] * 0.75,
maskGroupSubtractPixel,
maskGroupSubtractCleared: near(maskGroupSubtractPixel, maskIdentityPixel),
maskGroupIntersectPixel,
maskGroupIntersectDarkens: maskGroupIntersectPixel[0] < maskIdentityPixel[0] * 0.75,
flagHonouredForBitmap: !same(proxyTop, proxyNoFlipTop),
proxyTop: +proxyTop.toFixed(4),
sidecarTop: +sideTop.toFixed(4),
@@ -419,6 +455,10 @@ async function main() {
`render check: mask curve identity=${JSON.stringify(result.maskIdentityPixel)}` +
` darkened=${JSON.stringify(result.maskCurvePixel)}`,
);
console.log(
`render check: mask group subtract=${JSON.stringify(result.maskGroupSubtractPixel)}` +
` intersect=${JSON.stringify(result.maskGroupIntersectPixel)}`,
);
if (!result.matchTop || !result.matchBottom) {
console.error(
result.reversed
@@ -450,6 +490,14 @@ async function main() {
);
return 1;
}
if (!result.maskGroupSubtractCleared || !result.maskGroupIntersectDarkens) {
console.error(
'render check FAILED: mask group shapes are not compositing ' +
`(subtract=${JSON.stringify(result.maskGroupSubtractPixel)}, ` +
`intersect=${JSON.stringify(result.maskGroupIntersectPixel)}).`,
);
return 1;
}
if (!result.shadowFollowsExposure) {
console.error(
'render check FAILED: the shadow clipping overlay does not follow Exposure; ' +
+184 -70
View File
@@ -2,8 +2,10 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
ASPECTS,
defaultEdits,
defaultLocalComponent,
defaultLocalLayer,
MAX_HEAL_SPOTS,
MAX_LOCAL_COMPONENTS,
MAX_LOCAL_LAYERS,
} from '../lib/edits';
import { subscribeClipPreview } from '../lib/clipPreview';
@@ -35,6 +37,7 @@ import type {
EventRecord,
Flag,
HealSpot,
LocalComponent,
LocalLayer,
LocalMaskKind,
LocalStroke,
@@ -105,16 +108,21 @@ const EMPTY_GEO: Geometry = {
function cloneLocalLayer(layer: LocalLayer): LocalLayer {
return {
...layer,
brush: {
strokes: layer.brush.strokes.map((stroke) => ({
...stroke,
points: stroke.points.map((point) => ({ ...point })),
})),
},
linear: { ...layer.linear },
radial: { ...layer.radial },
components: layer.components.map((component) => ({
...component,
brush: {
strokes: component.brush.strokes.map((stroke) => ({
...stroke,
points: stroke.points.map((point) => ({ ...point })),
})),
},
linear: { ...component.linear },
radial: { ...component.radial },
...(component.raster ? { raster: { ...component.raster } } : {}),
})),
adjust: { ...layer.adjust },
range: { ...layer.range },
curve: layer.curve.map((point) => ({ ...point })),
};
}
@@ -253,6 +261,7 @@ export default function Develop({
const healDrag = useRef<{ index: number; mode: 'target' | 'source'; spot: HealSpot } | null>(null);
const [localSelected, setLocalSelected] = useState<string | null>(null);
const [localComponentSelected, setLocalComponentSelected] = useState<string | null>(null);
const [localMode, setLocalMode] = useState(false);
const [autoMaskBusy, setAutoMaskBusy] = useState(false);
const [localBrush, setLocalBrush] = useState(72);
@@ -266,7 +275,8 @@ export default function Develop({
error: null,
});
const localDrag = useRef<{
id: string;
layerId: string;
componentId: string;
mode: 'brush' | 'center' | 'edge' | 'edgeX' | 'edgeY' | 'start' | 'end';
stroke: LocalStroke | null;
} | null>(null);
@@ -280,6 +290,10 @@ export default function Develop({
[photos, photo.meta?.camera],
);
const activeLocal = (edits.local ?? []).find((layer) => layer.id === localSelected) ?? null;
const activeComponent =
activeLocal?.components.find((component) => component.id === localComponentSelected) ??
activeLocal?.components[0] ??
null;
const zoomed = zoom.pct !== 'fit';
// The filmstrip has its own Lightroom-style cull filter so you can narrow the
@@ -740,7 +754,7 @@ export default function Develop({
if ((e.target as HTMLElement | null)?.closest('.loupe-adjust')) return;
if (cropMode) return;
// While painting a mask, the wheel sizes the brush instead of zooming.
if (localMode && activeLocal?.kind === 'brush') {
if (localMode && activeComponent?.kind === 'brush') {
e.preventDefault();
setLocalBrush((v) => clampNum(v * Math.exp(-e.deltaY * 0.0015), 8, 320));
return;
@@ -760,7 +774,7 @@ export default function Develop({
};
el.addEventListener('wheel', onWheel, { passive: false });
return () => el.removeEventListener('wheel', onWheel);
}, [cropMode, applyZoom, healMode, localMode, activeLocal]);
}, [cropMode, applyZoom, healMode, localMode, activeComponent]);
const beginPan = (e: React.PointerEvent<HTMLCanvasElement>) => {
if (picking || rangePicking || cropMode || healMode || localMode || !zoomed || e.button !== 0) return;
@@ -1013,6 +1027,26 @@ export default function Develop({
[commitLocal, photo.edits.local],
);
/** Updates one shape inside a layer's mask group. */
const patchComponent = useCallback(
(layerId: string, componentId: string, patch: Partial<LocalComponent>, label = 'Local adjustment') => {
commitLocal(
(photo.edits.local ?? []).map((layer) =>
layer.id === layerId
? {
...layer,
components: layer.components.map((component) =>
component.id === componentId ? { ...component, ...patch } : component,
),
}
: layer,
),
label,
);
},
[commitLocal, photo.edits.local],
);
const addLocalLayer = useCallback(
(kind: LocalMaskKind) => {
const layers = edits.local ?? [];
@@ -1020,6 +1054,7 @@ export default function Develop({
const layer = defaultLocalLayer(kind, layers.length);
commitLocal([...layers, layer], 'Add local adjustment');
setLocalSelected(layer.id);
setLocalComponentSelected(layer.components[0]?.id ?? null);
setLocalMode(true);
setCropMode(false);
setHealMode(false);
@@ -1037,10 +1072,14 @@ export default function Develop({
const raster = await buildAutoMask(source, kind);
const layer = defaultLocalLayer('raster', layers.length);
layer.name = `Auto ${kind}`;
layer.raster = raster;
layer.feather = 30;
const shape = layer.components[0];
if (shape) {
shape.raster = raster;
shape.feather = 30;
}
commitLocal([...layers, layer], `Auto ${kind} mask`);
setLocalSelected(layer.id);
setLocalComponentSelected(layer.components[0]?.id ?? null);
setLocalMode(false);
setCropMode(false);
setHealMode(false);
@@ -1109,6 +1148,7 @@ export default function Develop({
(id: string) => {
commitLocal((edits.local ?? []).filter((layer) => layer.id !== id), 'Delete local adjustment');
setLocalSelected(null);
setLocalComponentSelected(null);
setLocalMode(false);
},
[commitLocal, edits.local],
@@ -1127,6 +1167,7 @@ export default function Develop({
};
commitLocal([...layers, copy], 'Duplicate local adjustment');
setLocalSelected(copy.id);
setLocalComponentSelected(copy.components[0]?.id ?? null);
},
[commitLocal, edits.local],
);
@@ -1146,11 +1187,39 @@ export default function Develop({
};
commitLocal([...layers, copy], 'Paste local adjustment');
setLocalSelected(copy.id);
setLocalComponentSelected(copy.components[0]?.id ?? null);
setLocalMode(true);
setCropMode(false);
setHealMode(false);
}, [commitLocal, edits.local, localClipboard]);
const addLocalComponent = useCallback(
(kind: LocalMaskKind) => {
if (!activeLocal) return;
if (activeLocal.components.length >= MAX_LOCAL_COMPONENTS) return;
const component = defaultLocalComponent(kind);
patchLocal(activeLocal.id, { components: [...activeLocal.components, component] }, 'Add mask shape');
setLocalComponentSelected(component.id);
setLocalMode(true);
setCropMode(false);
setHealMode(false);
setPicking(false);
},
[activeLocal, patchLocal],
);
const deleteLocalComponent = useCallback(
(componentId: string) => {
// A layer is its group: removing the last shape would leave an adjustment
// with no mask, so Delete layer is the way to remove it.
if (!activeLocal || activeLocal.components.length <= 1) return;
const remaining = activeLocal.components.filter((component) => component.id !== componentId);
patchLocal(activeLocal.id, { components: remaining }, 'Delete mask shape');
setLocalComponentSelected(remaining[0]?.id ?? null);
},
[activeLocal, patchLocal],
);
const toggleLocalMode = useCallback(() => {
if (!activeLocal) return;
setLocalMode((v) => !v);
@@ -1160,21 +1229,21 @@ export default function Develop({
}, [activeLocal]);
const startLocalMask = (e: React.PointerEvent<HTMLCanvasElement>) => {
if (!localMode || !activeLocal || !bitmap) return;
if (!localMode || !activeLocal || !activeComponent || !bitmap) return;
const p = sourcePointFromEvent(e);
if (!p) return;
e.preventDefault();
e.currentTarget.setPointerCapture(e.pointerId);
if (activeLocal.kind === 'brush') {
if (activeComponent.kind === 'brush') {
const stroke: LocalStroke = { points: [p], size: localRadius(), erase: e.altKey };
localDrag.current = { id: activeLocal.id, mode: 'brush', stroke };
localDrag.current = { layerId: activeLocal.id, componentId: activeComponent.id, mode: 'brush', stroke };
setLocalDraft(stroke);
return;
}
if (activeLocal.kind === 'radial') {
if (activeComponent.kind === 'radial') {
const aspect = bitmap.height / bitmap.width;
const nx = (p.x - activeLocal.radial.cx) / Math.max(0.001, activeLocal.radial.rx);
const ny = ((p.y - activeLocal.radial.cy) * aspect) / Math.max(0.001, activeLocal.radial.ry);
const nx = (p.x - activeComponent.radial.cx) / Math.max(0.001, activeComponent.radial.rx);
const ny = ((p.y - activeComponent.radial.cy) * aspect) / Math.max(0.001, activeComponent.radial.ry);
const mode =
Math.abs(nx) > 0.82 && Math.abs(ny) < 0.65
? 'edgeX'
@@ -1183,12 +1252,23 @@ export default function Develop({
: Math.hypot(nx, ny) > 0.82
? 'edge'
: 'center';
localDrag.current = { id: activeLocal.id, mode, stroke: null };
localDrag.current = { layerId: activeLocal.id, componentId: activeComponent.id, mode, stroke: null };
return;
}
const ds = Math.hypot(p.x - activeLocal.linear.x1, (p.y - activeLocal.linear.y1) * (bitmap.height / bitmap.width));
const de = Math.hypot(p.x - activeLocal.linear.x2, (p.y - activeLocal.linear.y2) * (bitmap.height / bitmap.width));
localDrag.current = { id: activeLocal.id, mode: ds <= de ? 'start' : 'end', stroke: null };
const ds = Math.hypot(
p.x - activeComponent.linear.x1,
(p.y - activeComponent.linear.y1) * (bitmap.height / bitmap.width),
);
const de = Math.hypot(
p.x - activeComponent.linear.x2,
(p.y - activeComponent.linear.y2) * (bitmap.height / bitmap.width),
);
localDrag.current = {
layerId: activeLocal.id,
componentId: activeComponent.id,
mode: ds <= de ? 'start' : 'end',
stroke: null,
};
};
const moveLocalMask = (e: React.PointerEvent<HTMLCanvasElement>) => {
@@ -1198,8 +1278,9 @@ export default function Develop({
setLocalHover(p);
const drag = localDrag.current;
if (!drag) return;
const layer = (photo.edits.local ?? []).find((item) => item.id === drag.id);
if (!layer) return;
const layer = (photo.edits.local ?? []).find((item) => item.id === drag.layerId);
const shape = layer?.components.find((item) => item.id === drag.componentId);
if (!layer || !shape) return;
if (drag.mode === 'brush' && drag.stroke) {
const last = drag.stroke.points[drag.stroke.points.length - 1];
if (last && Math.hypot((p.x - last.x) * bitmap.width, (p.y - last.y) * bitmap.height) < 1.2) return;
@@ -1209,46 +1290,51 @@ export default function Develop({
return;
}
if (drag.mode === 'center') {
patchLocal(layer.id, { radial: { ...layer.radial, cx: p.x, cy: p.y } }, 'Move local mask');
patchComponent(layer.id, shape.id, { radial: { ...shape.radial, cx: p.x, cy: p.y } }, 'Move local mask');
} else if (drag.mode === 'edgeX') {
patchLocal(
patchComponent(
layer.id,
{ radial: { ...layer.radial, rx: clampNum(Math.abs(p.x - layer.radial.cx), 0.01, 1.5) } },
shape.id,
{ radial: { ...shape.radial, rx: clampNum(Math.abs(p.x - shape.radial.cx), 0.01, 1.5) } },
'Resize local mask',
);
} else if (drag.mode === 'edgeY') {
patchLocal(
patchComponent(
layer.id,
{ radial: { ...layer.radial, ry: clampNum(Math.abs(p.y - layer.radial.cy), 0.01, 1.5) } },
shape.id,
{ radial: { ...shape.radial, ry: clampNum(Math.abs(p.y - shape.radial.cy), 0.01, 1.5) } },
'Resize local mask',
);
} else if (drag.mode === 'edge') {
patchLocal(
patchComponent(
layer.id,
shape.id,
{
radial: {
...layer.radial,
rx: clampNum(Math.abs(p.x - layer.radial.cx), 0.01, 1.5),
ry: clampNum(Math.abs(p.y - layer.radial.cy), 0.01, 1.5),
...shape.radial,
rx: clampNum(Math.abs(p.x - shape.radial.cx), 0.01, 1.5),
ry: clampNum(Math.abs(p.y - shape.radial.cy), 0.01, 1.5),
},
},
'Resize local mask',
);
} else if (drag.mode === 'start') {
patchLocal(layer.id, { linear: { ...layer.linear, x1: p.x, y1: p.y } }, 'Move local gradient');
patchComponent(layer.id, shape.id, { linear: { ...shape.linear, x1: p.x, y1: p.y } }, 'Move local gradient');
} else if (drag.mode === 'end') {
patchLocal(layer.id, { linear: { ...layer.linear, x2: p.x, y2: p.y } }, 'Move local gradient');
patchComponent(layer.id, shape.id, { linear: { ...shape.linear, x2: p.x, y2: p.y } }, 'Move local gradient');
}
};
const endLocalMask = (e: React.PointerEvent<HTMLCanvasElement>) => {
const drag = localDrag.current;
if (drag?.mode === 'brush' && drag.stroke?.points.length) {
const layer = (photo.edits.local ?? []).find((item) => item.id === drag.id);
if (layer) {
patchLocal(
const layer = (photo.edits.local ?? []).find((item) => item.id === drag.layerId);
const shape = layer?.components.find((item) => item.id === drag.componentId);
if (layer && shape) {
patchComponent(
layer.id,
{ brush: { strokes: [...layer.brush.strokes, drag.stroke].slice(-300) } },
shape.id,
{ brush: { strokes: [...shape.brush.strokes, drag.stroke].slice(-300) } },
drag.stroke.erase ? 'Erase local mask' : 'Paint local mask',
);
}
@@ -1281,6 +1367,7 @@ export default function Develop({
useEffect(() => {
setLocalSelected(null);
setLocalComponentSelected(null);
setLocalMode(false);
setLocalDraft(null);
localDrag.current = null;
@@ -1289,10 +1376,19 @@ export default function Develop({
useEffect(() => {
if (!(edits.local ?? []).some((layer) => layer.id === localSelected)) {
setLocalSelected(null);
setLocalComponentSelected(null);
setLocalMode(false);
}
}, [edits.local, localSelected]);
// Keep a shape selected, so Edit mask always has something to route the
// pointer to after a layer switch or a shape delete.
useEffect(() => {
if (!activeLocal) return;
if (activeLocal.components.some((component) => component.id === localComponentSelected)) return;
setLocalComponentSelected(activeLocal.components[0]?.id ?? null);
}, [activeLocal, localComponentSelected]);
// Escape cancels the picker without touching the edit.
useEffect(() => {
if (!picking) return;
@@ -1528,6 +1624,10 @@ export default function Develop({
set={setEdits}
activeId={localSelected}
onSelect={(id) => setLocalSelected(id)}
componentId={localComponentSelected}
onSelectComponent={setLocalComponentSelected}
onAddComponent={addLocalComponent}
onDeleteComponent={deleteLocalComponent}
onAdd={addLocalLayer}
onDelete={deleteLocalLayer}
onDuplicate={duplicateLocalLayer}
@@ -2074,7 +2174,7 @@ export default function Develop({
</svg>
);
})()}
{localMode && bitmap && activeLocal && (() => {
{localMode && bitmap && activeComponent && (() => {
const geo = geoRef.current;
const view = geo.view;
const marker = (p: { x: number; y: number }) => {
@@ -2103,11 +2203,11 @@ export default function Develop({
const canvasW = canvasEl?.clientWidth || 1;
const canvasH = canvasEl?.clientHeight || 1;
const strokes = localDraft
? [...activeLocal.brush.strokes, localDraft]
: activeLocal.brush.strokes;
? [...activeComponent.brush.strokes, localDraft]
: activeComponent.brush.strokes;
return (
<svg className="local-layer" viewBox="0 0 100 100" preserveAspectRatio="none">
{activeLocal.kind === 'brush' &&
{activeComponent.kind === 'brush' &&
strokes.map((stroke, i) => {
if (!stroke.points.length) return null;
const points = stroke.points.map(marker).map((p) => `${p.x},${p.y}`).join(' ');
@@ -2122,23 +2222,23 @@ export default function Develop({
/>
);
})}
{activeLocal.kind === 'radial' && (() => {
const c = marker({ x: activeLocal.radial.cx, y: activeLocal.radial.cy });
{activeComponent.kind === 'radial' && (() => {
const c = marker({ x: activeComponent.radial.cx, y: activeComponent.radial.cy });
const edge = marker({
x: activeLocal.radial.cx + activeLocal.radial.rx,
y: activeLocal.radial.cy,
x: activeComponent.radial.cx + activeComponent.radial.rx,
y: activeComponent.radial.cy,
});
const edgeY = marker({
x: activeLocal.radial.cx,
y: activeLocal.radial.cy + activeLocal.radial.ry,
x: activeComponent.radial.cx,
y: activeComponent.radial.cy + activeComponent.radial.ry,
});
// Sample the perimeter so the guide follows the same warp
// as the picture instead of staying a screen-space ellipse.
const ring = Array.from({ length: 72 }, (_, i) => {
const angle = (i / 72) * Math.PI * 2;
const p = marker({
x: activeLocal.radial.cx + Math.cos(angle) * activeLocal.radial.rx,
y: activeLocal.radial.cy + Math.sin(angle) * activeLocal.radial.ry,
x: activeComponent.radial.cx + Math.cos(angle) * activeComponent.radial.rx,
y: activeComponent.radial.cy + Math.sin(angle) * activeComponent.radial.ry,
});
return `${p.x},${p.y}`;
}).join(' ');
@@ -2155,9 +2255,9 @@ export default function Develop({
</g>
);
})()}
{activeLocal.kind === 'linear' && (() => {
const a = marker({ x: activeLocal.linear.x1, y: activeLocal.linear.y1 });
const b = marker({ x: activeLocal.linear.x2, y: activeLocal.linear.y2 });
{activeComponent.kind === 'linear' && (() => {
const a = marker({ x: activeComponent.linear.x1, y: activeComponent.linear.y1 });
const b = marker({ x: activeComponent.linear.x2, y: activeComponent.linear.y2 });
return (
<g>
<line x1={a.x} y1={a.y} x2={b.x} y2={b.y} className="local-line" vectorEffect="non-scaling-stroke" />
@@ -2166,7 +2266,7 @@ export default function Develop({
</g>
);
})()}
{activeLocal.kind === 'brush' && localHover && !localDrag.current && (
{activeComponent.kind === 'brush' && localHover && !localDrag.current && (
<ellipse
cx={marker(localHover).x}
cy={marker(localHover).y}
@@ -2192,10 +2292,10 @@ export default function Develop({
)}
</div>
)}
{localMode && activeLocal && !error && (
{localMode && activeLocal && activeComponent && !error && (
<div className="heal-hud local-hud">
<span className="heal-hud-title">Local · {activeLocal.kind}</span>
{activeLocal.kind === 'brush' && (
<span className="heal-hud-title">Local · {activeComponent.kind}</span>
{activeComponent.kind === 'brush' && (
<>
<label className="heal-field">
Size
@@ -2211,7 +2311,7 @@ export default function Develop({
<span className="heal-read">{Math.round(localBrush)}px</span>
</>
)}
{activeLocal.kind !== 'linear' && (
{activeComponent.kind !== 'linear' && (
<>
<label className="heal-field">
Feather
@@ -2220,27 +2320,41 @@ export default function Develop({
min={0}
max={100}
step={1}
value={activeLocal.feather}
onChange={(e) => patchLocal(activeLocal.id, { feather: Number(e.target.value) }, 'Local feather')}
value={activeComponent.feather}
onChange={(e) =>
patchComponent(
activeLocal.id,
activeComponent.id,
{ feather: Number(e.target.value) },
'Local feather',
)
}
/>
</label>
<span className="heal-read">{Math.round(activeLocal.feather)}%</span>
<span className="heal-read">{Math.round(activeComponent.feather)}%</span>
</>
)}
<button
className="heal-act"
onClick={() => {
if (activeLocal.kind === 'brush') {
patchLocal(activeLocal.id, { brush: { strokes: [] } }, 'Clear local mask');
} else if (activeLocal.kind === 'radial') {
patchLocal(
if (activeComponent.kind === 'brush') {
patchComponent(
activeLocal.id,
activeComponent.id,
{ brush: { strokes: [] } },
'Clear local mask',
);
} else if (activeComponent.kind === 'radial') {
patchComponent(
activeLocal.id,
activeComponent.id,
{ radial: { cx: 0.5, cy: 0.5, rx: 0.25, ry: 0.3 } },
'Reset local mask',
);
} else {
patchLocal(
patchComponent(
activeLocal.id,
activeComponent.id,
{ linear: { x1: 0.5, y1: 0.2, x2: 0.5, y2: 0.8 } },
'Reset local mask',
);
@@ -2253,9 +2367,9 @@ export default function Develop({
Done
</button>
<span className="heal-tip">
{activeLocal.kind === 'brush'
{activeComponent.kind === 'brush'
? 'Paint the mask · Alt paints an erase stroke · wheel sizes the brush'
: activeLocal.kind === 'radial'
: activeComponent.kind === 'radial'
? 'Drag the centre or the edge handle · wheel zooms'
: 'Drag either end of the gradient'}
</span>
+119 -18
View File
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { ASPECTS, BW_FILTERS, HUE_BANDS, identityCurve, MAX_LOCAL_LAYERS } from '../lib/edits';
import { ASPECTS, BW_FILTERS, HUE_BANDS, identityCurve, MAX_LOCAL_COMPONENTS, MAX_LOCAL_LAYERS } from '../lib/edits';
import { computeAutoEdits, computeAutoWhiteBalance } from '../lib/auto';
import { autoNoiseFor } from '../lib/noiseProfile';
import { clearDenoised, getDenoiseJob, startDenoise } from '../lib/api';
@@ -9,6 +9,7 @@ import type {
Edits,
EventRecord,
HistoryEntry,
LocalComponent,
LocalLayer,
LocalMaskKind,
MetadataPreset,
@@ -1494,6 +1495,10 @@ export function LocalPanel({
set,
activeId,
onSelect,
componentId,
onSelectComponent,
onAddComponent,
onDeleteComponent,
onAdd,
onDelete,
onDuplicate,
@@ -1510,6 +1515,11 @@ export function LocalPanel({
}: PanelSetProps & {
activeId: string | null;
onSelect: (id: string) => void;
/** Shape inside the active layer that the mask controls edit. */
componentId: string | null;
onSelectComponent: (id: string) => void;
onAddComponent: (kind: LocalMaskKind) => void;
onDeleteComponent: (id: string) => void;
onAdd: (kind: LocalMaskKind) => void;
onDelete: (id: string) => void;
onDuplicate: (id: string) => void;
@@ -1527,11 +1537,31 @@ export function LocalPanel({
}) {
const layers = edits.local ?? [];
const active = layers.find((layer) => layer.id === activeId) ?? null;
const shapes = active?.components ?? [];
const shape = shapes.find((component) => component.id === componentId) ?? shapes[0] ?? null;
const patch = (next: Partial<LocalLayer>, label: string) => {
if (!active) return;
set({ local: layers.map((layer) => (layer.id === active.id ? { ...layer, ...next } : layer)) }, label);
};
const patchShape = (next: Partial<LocalComponent>, label: string) => {
if (!active || !shape) return;
set(
{
local: layers.map((layer) =>
layer.id === active.id
? {
...layer,
components: layer.components.map((component) =>
component.id === shape.id ? { ...component, ...next } : component,
),
}
: layer,
),
},
label,
);
};
const adjust = (key: keyof LocalLayer['adjust'], value: number) =>
active && patch({ adjust: { ...active.adjust, [key]: value } }, `Local ${key}`);
const range = (key: keyof LocalLayer['range'], value: number | boolean) =>
@@ -1594,21 +1624,55 @@ export function LocalPanel({
className={`local-item ${layer.id === activeId ? 'on' : ''}`}
onClick={() => onSelect(layer.id)}
>
<span className="local-icon">{LOCAL_ICON[layer.kind]}</span>
<span className="local-icon">{LOCAL_ICON[layer.components[0]?.kind ?? 'brush']}</span>
<span className="local-name">{layer.name}</span>
<span className="local-kind">{layer.kind}</span>
<span className="local-kind">
{layer.components.length > 1
? `${layer.components.length} shapes`
: (layer.components[0]?.kind ?? 'mask')}
</span>
</button>
))}
</div>
{active && (
<div className="local-subhead">Mask shapes</div>
<div className="local-list shapes">
{shapes.map((component, index) => (
<button
key={component.id}
className={`local-item ${component.id === shape?.id ? 'on' : ''}`}
onClick={() => onSelectComponent(component.id)}
>
<span className="local-icon">{LOCAL_ICON[component.kind]}</span>
<span className="local-name">Shape {index + 1}</span>
<span className="local-kind">
{component.mode === 'add' ? component.kind : `${component.kind} · ${component.mode}`}
</span>
</button>
))}
</div>
<div className="btn-row local-add">
{(['brush', 'linear', 'radial'] as const).map((kind) => (
<button
key={kind}
className="btn ghost small"
onClick={() => onAddComponent(kind)}
disabled={shapes.length >= MAX_LOCAL_COMPONENTS}
title="Add a shape to this mask group"
>
+ {LOCAL_ICON[kind]} {kind}
</button>
))}
</div>
{active && shape && (
<>
<div className="btn-row local-actions">
<button
className={`btn ghost small ${maskMode ? 'on' : ''}`}
onClick={onEditMask}
disabled={active.kind === 'raster'}
title={active.kind === 'raster' ? 'Auto masks are generated, not painted' : undefined}
disabled={shape.kind === 'raster'}
title={shape.kind === 'raster' ? 'Auto masks are generated, not painted' : undefined}
>
{maskMode ? 'Done mask' : 'Edit mask'}
</button>
@@ -1620,13 +1684,13 @@ export function LocalPanel({
</button>
</div>
{active.kind === 'raster' && (
{shape.kind === 'raster' && (
<p className="muted small panel-hint">
Auto mask · adjust the feather, invert it, paint it away by adding a brush layer, or regenerate from the buttons above.
</p>
)}
{active.kind === 'brush' && (
{shape.kind === 'brush' && (
<Slider
label="Brush size"
min={8}
@@ -1638,19 +1702,56 @@ export function LocalPanel({
/>
)}
{active.kind !== 'linear' && (
{shape.kind !== 'linear' && (
<Slider
label="Feather"
min={0}
max={100}
value={active.feather}
value={shape.feather}
def={50}
onChange={(v) => patch({ feather: v }, 'Local feather')}
onChange={(v) => patchShape({ feather: v }, 'Local feather')}
format={(v) => `${Math.round(v)}%`}
/>
)}
<div className="local-subhead">Combine</div>
<div className="local-subhead">Shape blend</div>
<div className="btn-row local-modes">
{(['add', 'subtract', 'intersect'] as const).map((mode) => (
<button
key={mode}
className={`chip tiny ${shape.mode === mode ? 'on' : ''}`}
disabled={shapes[0]?.id === shape.id && mode !== 'add'}
title={
shapes[0]?.id === shape.id
? 'The first shape starts the group, so it always adds'
: mode === 'add'
? 'Union this shape into the group'
: mode === 'subtract'
? 'Cut this shape out of the shapes before it'
: 'Keep only where this shape overlaps the shapes before it'
}
onClick={() => patchShape({ mode }, `Shape ${mode}`)}
>
{mode === 'add' ? 'Add' : mode === 'subtract' ? 'Subtract' : 'Intersect'}
</button>
))}
</div>
<div className="btn-row">
<button
className="btn ghost small danger"
onClick={() => onDeleteComponent(shape.id)}
disabled={shapes.length <= 1}
title={
shapes.length <= 1
? 'A layer needs one shape; delete the layer instead'
: 'Remove this shape from the group'
}
>
Delete shape
</button>
</div>
<div className="local-subhead">Layer blend</div>
<div className="btn-row local-modes">
{(['add', 'subtract', 'intersect'] as const).map((mode) => (
<button
@@ -1658,12 +1759,12 @@ export function LocalPanel({
className={`chip tiny ${active.mode === mode ? 'on' : ''}`}
title={
mode === 'add'
? 'Apply this adjustment inside the mask'
? 'Apply this layer inside its mask'
: mode === 'subtract'
? 'Apply it outside this mask, within the layer above'
: 'Apply it only where this mask overlaps the layer above'
? 'Apply it outside its mask, within the layer above'
: 'Apply it only where the mask overlaps the layer above'
}
onClick={() => patch({ mode }, `Mask ${mode}`)}
onClick={() => patch({ mode }, `Layer ${mode}`)}
>
{mode === 'add' ? 'Add' : mode === 'subtract' ? 'Subtract' : 'Intersect'}
</button>
@@ -1823,8 +1924,8 @@ export function LocalPanel({
<div className="btn-row">
<button
className={`btn ghost small ${active.inverted ? 'on' : ''}`}
onClick={() => patch({ inverted: !active.inverted }, 'Invert mask')}
className={`btn ghost small ${shape.inverted ? 'on' : ''}`}
onClick={() => patchShape({ inverted: !shape.inverted }, 'Invert mask')}
>
Invert mask
</button>
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, it } from 'vitest';
import { blendCoverage } from './masks';
/** Coverage values are 0–1 inside the baker, which this keeps readable. */
describe('mask group compositing', () => {
it('starts a group with the first shape whatever its mode says', () => {
expect(blendCoverage(0, 0.6, 'subtract', true)).toBe(0.6);
expect(blendCoverage(0, 0.6, 'intersect', true)).toBe(0.6);
});
it('unions added shapes instead of stacking them', () => {
expect(blendCoverage(0.4, 0.7, 'add', false)).toBe(0.7);
expect(blendCoverage(0.7, 0.4, 'add', false)).toBe(0.7);
});
it('subtracts coverage from the group', () => {
expect(blendCoverage(1, 0.25, 'subtract', false)).toBeCloseTo(0.75, 6);
expect(blendCoverage(1, 1, 'subtract', false)).toBe(0);
});
it('keeps only the overlap for an intersect shape', () => {
expect(blendCoverage(0.8, 0.5, 'intersect', false)).toBeCloseTo(0.4, 6);
expect(blendCoverage(0.8, 0, 'intersect', false)).toBe(0);
});
});
+87 -52
View File
@@ -1,11 +1,13 @@
import type { LocalLayer } from '../types';
import type { LocalComponent, LocalLayer } from '../types';
import { MAX_LOCAL_LAYERS } from '../lib/edits';
/**
* Local masks are baked on the CPU into two RGBA textures, one layer per
* channel, so the grade shader can apply up to eight adjustments in a single
* pass. The mask is source-space, which keeps brushes and gradients attached to
* the picture through crops, straightening, zoom and lens correction.
* pass. A layer's mask is a group of shapes composited in order: add unions,
* subtract cuts a hole, intersect keeps the overlap. The mask is source-space,
* which keeps brushes and gradients attached to the picture through crops,
* straightening, zoom and lens correction.
*/
export interface PackedMasks {
@@ -23,19 +25,22 @@ export function maskSignature(layers: LocalLayer[], srcW: number, srcH: number)
srcW,
srcH,
layers: layers.slice(0, MAX_LOCAL_LAYERS).map((layer) => ({
kind: layer.kind,
inverted: layer.inverted,
feather: layer.feather,
brush: layer.brush,
linear: layer.linear,
radial: layer.radial,
raster: layer.raster
? {
width: layer.raster.width,
height: layer.raster.height,
hash: rasterHash(layer.raster.data),
}
: null,
components: (layer.components ?? []).map((component) => ({
kind: component.kind,
mode: component.mode,
inverted: component.inverted,
feather: component.feather,
brush: component.brush,
linear: component.linear,
radial: component.radial,
raster: component.raster
? {
width: component.raster.width,
height: component.raster.height,
hash: rasterHash(component.raster.data),
}
: null,
})),
})),
});
}
@@ -49,8 +54,8 @@ function rasterHash(data: string) {
return `${data.length}:${hash >>> 0}`;
}
function drawRaster(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) {
const mask = layer.raster;
function drawRaster(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
const mask = component.raster;
if (!mask) return;
try {
const binary = atob(mask.data);
@@ -82,13 +87,13 @@ function makeCanvas(w: number, h: number) {
return canvas;
}
function drawRadial(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) {
const { cx, cy, rx, ry } = layer.radial;
function drawRadial(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
const { cx, cy, rx, ry } = component.radial;
ctx.save();
ctx.translate(cx * w, cy * h);
ctx.scale(Math.max(1, rx * w), Math.max(1, ry * h));
const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, 1);
const inner = Math.max(0, Math.min(0.98, 1 - layer.feather / 100));
const inner = Math.max(0, Math.min(0.98, 1 - component.feather / 100));
gradient.addColorStop(0, 'rgba(255,255,255,1)');
if (inner > 0.001) gradient.addColorStop(inner, 'rgba(255,255,255,1)');
gradient.addColorStop(1, 'rgba(255,255,255,0)');
@@ -99,8 +104,8 @@ function drawRadial(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number,
ctx.restore();
}
function drawLinear(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) {
const { x1, y1, x2, y2 } = layer.linear;
function drawLinear(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
const { x1, y1, x2, y2 } = component.linear;
const gradient = ctx.createLinearGradient(x1 * w, y1 * h, x2 * w, y2 * h);
gradient.addColorStop(0, 'rgba(255,255,255,1)');
gradient.addColorStop(1, 'rgba(255,255,255,0)');
@@ -108,10 +113,10 @@ function drawLinear(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number,
ctx.fillRect(0, 0, w, h);
}
function drawBrush(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number, h: number) {
function drawBrush(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
for (const stroke of layer.brush.strokes) {
for (const stroke of component.brush.strokes) {
if (!stroke.points.length) continue;
const width = Math.max(1, stroke.size * 2 * w);
ctx.globalCompositeOperation = stroke.erase ? 'destination-out' : 'source-over';
@@ -134,6 +139,13 @@ function drawBrush(ctx: CanvasRenderingContext2D, layer: LocalLayer, w: number,
ctx.globalCompositeOperation = 'source-over';
}
function drawComponent(ctx: CanvasRenderingContext2D, component: LocalComponent, w: number, h: number) {
if (component.kind === 'radial') drawRadial(ctx, component, w, h);
else if (component.kind === 'linear') drawLinear(ctx, component, w, h);
else if (component.kind === 'raster') drawRaster(ctx, component, w, h);
else drawBrush(ctx, component, w, h);
}
/**
* Softens a mask rim without thinning what was painted. A plain blur pulls the
* stroke edge inward and drops thin strokes below full coverage, which reads as
@@ -155,6 +167,23 @@ function featherMask(canvas: HTMLCanvasElement, radius: number) {
return out;
}
/**
* How one shape's coverage joins the accumulated mask inside its layer. The
* first shape starts the group, so its mode is ignored: there is nothing to
* subtract from or intersect with yet.
*/
export function blendCoverage(
acc: number,
value: number,
mode: LocalComponent['mode'],
first: boolean,
) {
if (first) return value;
if (mode === 'subtract') return acc * (1 - value);
if (mode === 'intersect') return acc * value;
return Math.max(acc, value);
}
export function buildLocalMasks(layers: LocalLayer[], srcW: number, srcH: number): PackedMasks {
const w = 800;
const h = Math.max(120, Math.min(1400, Math.round((w * Math.max(1, srcH)) / Math.max(1, srcW))));
@@ -165,40 +194,46 @@ export function buildLocalMasks(layers: LocalLayer[], srcW: number, srcH: number
for (let index = 0; index < count; index++) {
const layer = layers[index];
const canvas = makeCanvas(w, h);
const ctx = canvas.getContext('2d');
if (!ctx) continue;
ctx.clearRect(0, 0, w, h);
const components = layer.components ?? [];
const acc = new Uint8Array(w * h);
let first = true;
if (layer.kind === 'radial') drawRadial(ctx, layer, w, h);
else if (layer.kind === 'linear') drawLinear(ctx, layer, w, h);
else if (layer.kind === 'raster') drawRaster(ctx, layer, w, h);
else drawBrush(ctx, layer, w, h);
for (const component of components) {
const canvas = makeCanvas(w, h);
const ctx = canvas.getContext('2d');
if (!ctx) continue;
ctx.clearRect(0, 0, w, h);
drawComponent(ctx, component, w, h);
let source = canvas;
if (layer.kind === 'brush') {
// Feather follows the brush, not the frame: 100% softens the edge by
// roughly three quarters of the stroke's half width, so a small dab and a
// wide sweep both feel the same under the slider.
let widest = 0;
for (const stroke of layer.brush.strokes) {
widest = Math.max(widest, stroke.size * 2 * w);
let source = canvas;
if (component.kind === 'brush') {
// Feather follows the brush, not the frame: 100% softens the edge by
// roughly three quarters of the stroke's half width, so a small dab and a
// wide sweep both feel the same under the slider.
let widest = 0;
for (const stroke of component.brush.strokes) {
widest = Math.max(widest, stroke.size * 2 * w);
}
source = featherMask(canvas, (component.feather / 100) * widest * 0.75);
} else if (component.kind === 'raster') {
// Generated masks are low-resolution coverage, so their feather is tied
// to the frame width and only ever loosens the outside edge.
source = featherMask(canvas, ((component.feather / 100) * w) / 16);
}
source = featherMask(canvas, (layer.feather / 100) * widest * 0.75);
} else if (layer.kind === 'raster') {
// Generated masks are low-resolution coverage, so their feather is tied
// to the frame width and only ever loosens the outside edge.
source = featherMask(canvas, ((layer.feather / 100) * w) / 16);
const pixels = source.getContext('2d')?.getImageData(0, 0, w, h).data;
if (!pixels) continue;
for (let p = 0, o = 0; p < pixels.length; p += 4, o++) {
let value = pixels[p + 3] / 255;
if (component.inverted) value = 1 - value;
acc[o] = Math.round(blendCoverage(acc[o] / 255, value, component.mode, first) * 255);
}
first = false;
}
const pixels = source.getContext('2d')?.getImageData(0, 0, w, h).data;
if (!pixels) continue;
const channel = index % 4;
const target = index < 4 ? out : out2;
for (let p = 0, o = 0; p < pixels.length; p += 4, o += 4) {
const alpha = pixels[p + 3];
target[o + channel] = layer.inverted ? 255 - alpha : alpha;
}
for (let o = 0; o < acc.length; o++) target[o * 4 + channel] = acc[o];
}
return { data: out, data2: out2, w, h };
+65 -26
View File
@@ -6,6 +6,7 @@ import type {
Edits,
Flag,
HealSpot,
LocalComponent,
LocalLayer,
LocalMaskKind,
LocalPoint,
@@ -99,6 +100,9 @@ export const MAX_HEAL_SPOTS = 24;
/** Eight masks are packed into two RGBA textures. */
export const MAX_LOCAL_LAYERS = 8;
/** More shapes than this in one group stops being quicker than a second layer. */
export const MAX_LOCAL_COMPONENTS = 8;
export function defaultLocalAdjust(): LocalLayer['adjust'] {
return {
exposure: 0,
@@ -119,10 +123,9 @@ export function defaultLocalAdjust(): LocalLayer['adjust'] {
};
}
export function defaultLocalLayer(kind: LocalMaskKind, index: number): LocalLayer {
export function defaultLocalComponent(kind: LocalMaskKind): LocalComponent {
return {
id: `local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
name: `Local ${index + 1}`,
id: `shape-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
kind,
mode: 'add',
inverted: false,
@@ -130,6 +133,15 @@ export function defaultLocalLayer(kind: LocalMaskKind, index: number): LocalLaye
brush: { strokes: [] },
linear: { x1: 0.5, y1: 0.2, x2: 0.5, y2: 0.8 },
radial: { cx: 0.5, cy: 0.5, rx: 0.25, ry: 0.3 },
};
}
export function defaultLocalLayer(kind: LocalMaskKind, index: number): LocalLayer {
return {
id: `local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`,
name: `Local ${index + 1}`,
mode: 'add',
components: [defaultLocalComponent(kind)],
range: { enabled: false, lumaMin: 0, lumaMax: 100, hue: 30, hueRange: 180, satMin: 0 },
curve: identityCurve(),
adjust: defaultLocalAdjust(),
@@ -287,40 +299,67 @@ function localCurve(input: unknown): CurvePoint[] {
return points.length >= 2 ? points : identityCurve();
}
/**
* One shape from stored edits. It also reads the pre-group flat layout, where
* the layer itself carried kind/feather/brush/...: that is how every mask saved
* before mask groups existed migrates into `components[0]`.
*/
function localComponent(input: unknown, index: number): LocalComponent | null {
if (!input || typeof input !== 'object') return null;
const shape = input as Partial<LocalComponent> & { kind?: unknown };
const kind: LocalMaskKind =
shape.kind === 'linear' || shape.kind === 'radial' || shape.kind === 'raster' ? shape.kind : 'brush';
const linear = (shape.linear ?? {}) as Partial<LocalComponent['linear']>;
const radial = (shape.radial ?? {}) as Partial<LocalComponent['radial']>;
const raster = kind === 'raster' ? rasterMask(shape.raster) : undefined;
// A raster shape without its coverage would composite an empty hole, so it
// falls back to a brush shape that can at least be painted over.
const resolved: LocalMaskKind = kind === 'raster' && !raster ? 'brush' : kind;
return {
id: typeof shape.id === 'string' && shape.id ? shape.id.slice(0, 60) : `shape-${index}`,
kind: resolved,
mode: shape.mode === 'subtract' || shape.mode === 'intersect' ? shape.mode : 'add',
inverted: !!shape.inverted,
feather: num(shape.feather, 50, 0, 100),
brush: { strokes: localStrokes(shape.brush?.strokes) },
raster: resolved === 'raster' ? raster : undefined,
linear: {
x1: clamp01(num(linear.x1, 0.5, 0, 1)),
y1: clamp01(num(linear.y1, 0.2, 0, 1)),
x2: clamp01(num(linear.x2, 0.5, 0, 1)),
y2: clamp01(num(linear.y2, 0.8, 0, 1)),
},
radial: {
cx: clamp01(num(radial.cx, 0.5, 0, 1)),
cy: clamp01(num(radial.cy, 0.5, 0, 1)),
rx: num(radial.rx, 0.25, 0.01, 1.5),
ry: num(radial.ry, 0.3, 0.01, 1.5),
},
};
}
function localLayers(input: unknown): LocalLayer[] {
if (!Array.isArray(input)) return [];
const out: LocalLayer[] = [];
for (const raw of input.slice(0, MAX_LOCAL_LAYERS)) {
if (!raw || typeof raw !== 'object') continue;
const layer = raw as Partial<LocalLayer>;
const kind: LocalMaskKind =
layer.kind === 'linear' || layer.kind === 'radial' || layer.kind === 'raster' ? layer.kind : 'brush';
const adjust = (layer.adjust ?? {}) as Partial<LocalLayer['adjust']>;
const range = (layer.range ?? {}) as Partial<LocalLayer['range']>;
const linear = (layer.linear ?? {}) as Partial<LocalLayer['linear']>;
const radial = (layer.radial ?? {}) as Partial<LocalLayer['radial']>;
const stored = Array.isArray(layer.components) && layer.components.length ? layer.components : [layer];
const components: LocalComponent[] = [];
for (const entry of stored.slice(0, MAX_LOCAL_COMPONENTS)) {
const component = localComponent(entry, components.length);
if (component) components.push(component);
}
// A layer must keep at least one shape, or it would adjust nothing with no
// way to tell why from the panel.
if (!components.length) components.push(defaultLocalComponent('brush'));
out.push({
id: typeof layer.id === 'string' && layer.id ? layer.id : `local-${out.length}`,
name: typeof layer.name === 'string' && layer.name.trim() ? layer.name.slice(0, 40) : `Local ${out.length + 1}`,
kind,
mode:
layer.mode === 'subtract' || layer.mode === 'intersect' ? layer.mode : 'add',
inverted: !!layer.inverted,
feather: num(layer.feather, 50, 0, 100),
brush: { strokes: localStrokes(layer.brush?.strokes) },
raster: kind === 'raster' ? rasterMask(layer.raster) : undefined,
linear: {
x1: clamp01(num(linear.x1, 0.5, 0, 1)),
y1: clamp01(num(linear.y1, 0.2, 0, 1)),
x2: clamp01(num(linear.x2, 0.5, 0, 1)),
y2: clamp01(num(linear.y2, 0.8, 0, 1)),
},
radial: {
cx: clamp01(num(radial.cx, 0.5, 0, 1)),
cy: clamp01(num(radial.cy, 0.5, 0, 1)),
rx: num(radial.rx, 0.25, 0.01, 1.5),
ry: num(radial.ry, 0.3, 0.01, 1.5),
},
mode: layer.mode === 'subtract' || layer.mode === 'intersect' ? layer.mode : 'add',
components,
range: {
enabled: !!range.enabled,
lumaMin: num(range.lumaMin, 0, 0, 100),
+106
View File
@@ -0,0 +1,106 @@
import { describe, expect, it } from 'vitest';
import { defaultLocalLayer, MAX_LOCAL_COMPONENTS, normalizeEdits } from './edits';
/** Stored edits as they look before mask groups: geometry on the layer itself. */
function legacyLayer() {
return {
id: 'local-1',
name: 'Sky',
kind: 'gradientish' as unknown as string,
mode: 'subtract',
inverted: true,
feather: 20,
brush: { strokes: [] },
linear: { x1: 0.1, y1: 0.2, x2: 0.3, y2: 0.9 },
radial: { cx: 0.4, cy: 0.6, rx: 0.2, ry: 0.3 },
range: { enabled: false, lumaMin: 0, lumaMax: 100, hue: 30, hueRange: 180, satMin: 0 },
curve: [
{ x: 0, y: 0 },
{ x: 1, y: 1 },
],
adjust: {},
};
}
describe('mask groups', () => {
it('migrates a flat layer into a single component without changing the mask', () => {
const edits = normalizeEdits({ local: [legacyLayer()] as never });
const layer = edits.local[0];
expect(layer.components).toHaveLength(1);
const shape = layer.components[0];
// An unknown kind is a brush, as it always was; geometry and the layer's
// combine mode move onto the shape, layer mode stays for blending layers.
expect(shape.kind).toBe('brush');
expect(shape.mode).toBe('subtract');
expect(shape.inverted).toBe(true);
expect(shape.feather).toBe(20);
expect(shape.linear.x2).toBe(0.3);
expect(shape.radial.ry).toBe(0.3);
expect(layer.mode).toBe('subtract');
expect(layer.name).toBe('Sky');
});
it('keeps a stored component list in order with its own modes', () => {
const edit = normalizeEdits({
local: [
{
id: 'local-a',
name: 'Group',
mode: 'add',
components: [
{ id: 's1', kind: 'radial', mode: 'add', radial: { cx: 0.5, cy: 0.5, rx: 0.4, ry: 0.4 } },
{ id: 's2', kind: 'linear', mode: 'subtract', feather: 0, linear: { x1: 0, y1: 0, x2: 1, y2: 1 } },
{ id: 's3', kind: 'brush', mode: 'intersect', brush: { strokes: [] } },
],
curve: [],
adjust: {},
},
],
} as never);
const shapes = edit.local[0].components;
expect(shapes.map((shape) => shape.id)).toEqual(['s1', 's2', 's3']);
expect(shapes.map((shape) => shape.mode)).toEqual(['add', 'subtract', 'intersect']);
expect(shapes[1].kind).toBe('linear');
expect(shapes[2].kind).toBe('brush');
});
it('drops a raster component that lost its coverage instead of baking an empty mask', () => {
const edit = normalizeEdits({
local: [
{
id: 'local-r',
name: 'Raster',
mode: 'add',
components: [{ id: 's1', kind: 'raster', mode: 'add' }],
curve: [],
adjust: {},
},
],
} as never);
expect(edit.local[0].components[0].kind).toBe('brush');
expect(edit.local[0].components[0].raster).toBeUndefined();
});
it('always leaves a layer with at least one shape and caps the group', () => {
const many = Array.from({ length: MAX_LOCAL_COMPONENTS + 4 }, (_, i) => ({
id: `s${i}`,
kind: 'radial',
mode: 'add',
}));
const edit = normalizeEdits({
local: [
{ id: 'local-m', name: 'Many', mode: 'add', components: many, curve: [], adjust: {} },
{ id: 'local-e', name: 'Empty', mode: 'add', components: [], curve: [], adjust: {} },
],
} as never);
expect(edit.local[0].components).toHaveLength(MAX_LOCAL_COMPONENTS);
expect(edit.local[1].components).toHaveLength(1);
});
it('creates new layers with one shape so the panel always has something to edit', () => {
const layer = defaultLocalLayer('linear', 0);
expect(layer.components).toHaveLength(1);
expect(layer.components[0].kind).toBe('linear');
expect(layer.components[0].mode).toBe('add');
});
});
+4 -8
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { defaultEdits, normalizeEdits } from './edits';
import { defaultEdits, defaultLocalLayer, normalizeEdits } from './edits';
import { editsToXmp, xmpFileName, xmpToEdits } from './xmp';
describe('xmp sidecars', () => {
@@ -12,13 +12,9 @@ describe('xmp sidecars', () => {
edits.parametric.darks = -17;
edits.hsl.hue[3] = 12;
edits.grain.roughness = 71;
edits.local = [
{
...defaultEdits().local[0],
kind: 'linear',
linear: { x1: 0.1, y1: 0.2, x2: 0.8, y2: 0.9 },
},
];
const mask = defaultLocalLayer('linear', 0);
if (mask.components[0]) mask.components[0].linear = { x1: 0.1, y1: 0.2, x2: 0.8, y2: 0.9 };
edits.local = [mask];
const xml = editsToXmp(edits);
const back = xmpToEdits(xml, defaultEdits());
+10
View File
@@ -4693,6 +4693,16 @@ figcaption {
margin-bottom: 7px;
}
/* Shapes sit under their layer, indented so the group reads as a child list. */
.local-list.shapes {
margin-bottom: 4px;
padding-left: 8px;
}
.local-list.shapes .local-item {
font-size: 11px;
}
.local-item {
display: flex;
align-items: center;
+14 -5
View File
@@ -63,12 +63,11 @@ export interface LocalStroke {
erase?: boolean;
}
/** One non-destructive local adjustment layer. Mask geometry is in source uv. */
export interface LocalLayer {
/** One shape inside a local adjustment layer's mask group. */
export interface LocalComponent {
id: string;
name: string;
kind: LocalMaskKind;
/** How this mask combines with the layer above it in the list. */
/** How this shape combines with the shapes before it inside the layer. */
mode: 'add' | 'subtract' | 'intersect';
inverted: boolean;
/** softness of the mask edge, 0–100 */
@@ -77,7 +76,17 @@ export interface LocalLayer {
linear: { x1: number; y1: number; x2: number; y2: number };
radial: { cx: number; cy: number; rx: number; ry: number };
raster?: RasterMask;
/** luminance and colour limits applied on top of the shape */
}
/** One non-destructive local adjustment layer. Mask geometry is in source uv. */
export interface LocalLayer {
id: string;
name: string;
/** How the whole layer combines with the layer above it in the list. */
mode: 'add' | 'subtract' | 'intersect';
/** Shapes composited in order into this layer's mask. */
components: LocalComponent[];
/** luminance and colour limits applied on top of the shape group */
range: {
enabled: boolean;
lumaMin: number;