Skip to content

Free open-source image editor for the browser

Add luminance and color range masks with Intersect (#74)

Rodrigo Belfioreec624209247a
diff --git a/API.md b/API.md
index 43d3ce7..e32fa46 100644
--- a/API.md
+++ b/API.md
@@ -80,7 +80,7 @@ Edits update the scene and history synchronously. Rendering may finish later, pa
Images own basic adjustments and a tone curve. Processing layers edit the source image in stack order; the image layer's adjustments and curve then tone the composite, so a local exposure can recover light that the global exposure pushes past white. An effect processes the image below, then its children. A mask processes its basic adjustments, its tone curve, and child effects, then blends that result with its input using coverage × opacity. A neutral mask with no effects does nothing. Hidden layers and zero opacity bypass the complete branch.
-Direct mask children of another mask modify coverage instead of processing image pixels: Add sums coverage, Subtract removes it, clamping to 0–1 after each child in stored order. Each child's opacity scales its contribution. Its stored basic adjustments are inactive in this position. Other children process the image within the combined mask. Layer opacity always controls effect strength, preserving the input image's alpha.
+Direct mask children of another mask modify coverage instead of processing image pixels: Add sums coverage, Subtract removes it, clamping to 0–1 after each child in stored order, and Intersect keeps it only where the child covers. Each child's opacity scales its contribution; an Intersect child at opacity `o` keeps `1 − o × (1 − child)` of the coverage. A brush child that has not painted yet takes no part. Its stored basic adjustments are inactive in this position. Other children process the image within the combined mask. Layer opacity always controls effect strength, preserving the input image's alpha.
| Method | Behavior |
| --- | --- |
@@ -88,8 +88,8 @@ Direct mask children of another mask modify coverage instead of processing image
| `selectLayer(id)` | Selects any layer. |
| `setLayer(id, change)` | Updates processing-layer `name`, `visible`, or `opacity` (0–1). |
| `setExposure(id, value)` | Sets an Exposure layer to -5…5 EV. |
-| `setLayerMask(id, mask)` | Replaces a mask layer's mask: `{ kind: "linear", start, end }`, `{ kind: "radial", center, radius, angle, feather }`, or `{ kind: "brush", strokes }`. Geometry uses source pixels; radial angle is degrees and feather is 0–1. |
-| `setMaskOperation(id, operation)` | Sets `"add"` or `"subtract"`; used when this mask is inside another mask. |
+| `setLayerMask(id, mask)` | Replaces a mask layer's mask: `{ kind: "linear", start, end }`, `{ kind: "radial", center, radius, angle, feather }`, `{ kind: "brush", strokes }`, or a [range](#ranges), `{ kind: "luminance-range", low, high, smoothness }` or `{ kind: "color-range", color, tolerance }`. Geometry uses source pixels; radial angle is degrees and feather is 0–1. |
+| `setMaskOperation(id, operation)` | Sets `"add"`, `"subtract"`, or `"intersect"`; used when this mask is inside another mask. |
| `duplicateLayer(id)` | Copies a processing layer and its children above itself with independent IDs; selects and returns the new ID. |
| `moveLayer(id, index, parentId?)` | Moves to a final sibling index, bottom to top. Omit the parent for the root stack, where index 0 is reserved for the image. Image parents, cycles, and third-level nesting are rejected. |
| `deleteLayer(id)` | Removes a processing layer and its children; undo restores them. |
@@ -98,6 +98,12 @@ A linear gradient has full coverage at `start`, zero at `end`; its points must b
A brush mask is a list of strokes, over the pixels earlier strokes settled into, as a Paint layer's are: in the editor they settle every 100 strokes, and `getState()` shows the mask's `raster` ID. `setLayerMask` keeps a `raster` only if it names the document's own settled pixels. Each stroke has `mode` (`"paint"` or `"erase"`), `size` (diameter in source pixels), `feather` and `flow` (0–1), and `points`, each `[x, y, pressure]` in source pixels with pressure 0–1. A paint stroke adds `flow × pressure` of the remaining coverage every quarter diameter along the points, and an erase stroke removes that share of the existing coverage; dabs land sixteen times per diameter, each laying a fraction of that, so soft edges show no ripples. The renderer rasterizes strokes into a cached coverage texture at half the photo's resolution each way and only stamps new points, so appending to the last stroke is cheap and undo replays at most 99. A brush inside another mask keeps its own coverage, paint and erase strokes alike, which the mask adds or subtracts scaled by the brush layer's opacity. A mask with no painted coverage and nothing added to it is bypassed.
+### Ranges
+
+A range mask selects pixels of the image below its mask group, before the group's own adjustments, rather than by position. `{ kind: "luminance-range", low, high, smoothness }` selects the pixels whose CIE lightness lies from `low` to `high`, 0 black to 100 white, fading out over `smoothness` past either end; headroom above white counts as white. `{ kind: "color-range", color, tolerance }` selects the pixels whose hue and saturation are near `color`, `#rrggbb` sRGB, however light or dark, more of them as `tolerance` grows. Set `color` to `null` for an unpicked range with no coverage. Every value runs from 0 to 100, and `low` cannot exceed `high`. As a mask's own shape, a range covers the whole photo within it; as a child, it adds, subtracts, or intersects like any mask, so a gradient intersected with a color range darkens only that color across the gradient. Range coverage follows the photo's edges at its full resolution.
+
+The Add menu's **Luminance Range** starts at 50 to 100 with smoothness 25. **Color Range**, including a mask's Add, Subtract, or Intersect entry for one, creates and selects an unpicked mask immediately with tolerance 30. A click on the photo picks its color, averaged over 5 × 5 rendered texels, and a drag keeps picking as one edit. Picks read the image below the mask group as the screen would show it, so the mask's own edit never changes them. Once a color is chosen, the swatch beside the eyedropper opens the browser's color picker. Selecting another kind of layer or deleting the range leaves the picker.
+
## LUTs
A LUT layer grades the image below it with a 3D lookup table, stored in the layer as `lut: { size, domain: [min, max], table }`: `table` holds `size`³ RGB triplets, red varying fastest, then green, then blue, for inputs spread evenly across the domain. The layer's opacity sets its strength.
@@ -143,6 +149,8 @@ try {
| `shadows` | Show shadow clipping | `false` |
| `highlights` | Show highlight clipping | `false` |
+The editor also manages `maskOverlay` for the selected mask and `rangeSource` for the mask group being sampled. These transient fields are visible in `getState().preview`; leave them to the active tool.
+
## Export
`exportImage(options)` returns `Promise<File>` containing the edited image, named after the source file. Preview settings do not affect export.
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 002321c..8bd8ac9 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -78,8 +78,9 @@ Dependencies point downward. Features do not import each other; `app/` connects
- The image layer's adjustments and tone curve develop the photo first; its children and the layers above process that result in stack order. Paint colors therefore follow the photo's adjustments. Working textures stay floating-point through composition; display and export encode the final result.
- Preserve HDR headroom through exposure, curves, and vibrance. Exposure multiplies linear RGB by `2^EV`, without clipping, so +3 EV followed by -3 EV recovers the original light even when intermediate values exceed 1.
- The adjustment shader's parameters use UI units; its fitted constants are calibration data.
-- Strokes are scene content; the renderer caches their rasterized coverage, or a Paint layer's premultiplied 8-bit color, at half the source's resolution each way, a quarter of its pixels, which the passes that read them sample back to full size, and stamps only appended dabs. A Paint layer's raster comes with its first paint and stays, cleared if need be, until the layer goes, so painting and undoing allocate nothing. A photo holds up to 4 Paint layers and 10 brush masks.
+- Strokes are scene content; the renderer caches their rasterized coverage, or a Paint layer's premultiplied 8-bit color, at half the source's resolution each way, a quarter of its pixels, which the passes that read them sample back to full size, and stamps only appended dabs. A Paint layer's or brush mask's raster comes with its first paint and stays, cleared if need be, until the layer goes, so painting and undoing allocate nothing. A photo holds up to 4 Paint layers and 10 brush masks.
- A mask's or Paint layer's latest stroke builds up in a half-float stroke buffer at the same resolution, one stroke at a time; its raster takes it in one pass when the next stroke starts, so it rounds to 8 bits once, however many moves drew it. Until then a Paint layer composes the buffer over its raster, and a mask's readers get its raster with the stroke laid over, in a view redrawn where the stroke grows. A Healing patch's hard stroke rounds the same either way, so it stamps straight into a raster over only the 256 px tiles it reaches.
-- A brush mask paints coverage as a Paint layer paints color: both are a painting, the latest strokes over settled pixels, in one raster module (r8 for coverage, rgba8 for color), which also owns the open stroke coverage view. The mask module combines that coverage with child masks. Gradient masks need no texture; the mix pass computes them. At 100 strokes, once no gesture is open, the renderer reads a painting's raster band by band through one mapped buffer, and the pixels, deflated, become a document resource the layer names in place of its strokes, without a history step. Rendering waits until both the scene and cached raster accept the settled pixels. History scenes name the pixels they drew over, so undo reaches past a settle: the renderer loads those pixels, inflating them band by band through a staging texture, and draws the strokes again. Resources go once no retained scene names them.
+- A brush mask paints coverage as a Paint layer paints color: both are a painting, the latest strokes over settled pixels, in one raster module (r8 for coverage, rgba8 for color), which also owns the open stroke coverage view. At 100 strokes, once no gesture is open, the renderer reads a painting's raster band by band through one mapped buffer, and the pixels, deflated, become a document resource the layer names in place of its strokes, without a history step. Rendering waits until both the scene and cached raster accept the settled pixels. History scenes name the pixels they drew over, so undo reaches past a settle: the renderer loads those pixels, inflating them band by band through a staging texture, and draws the strokes again. Resources go once no retained scene names them.
+- A mask that only gradients shape needs no texture: the mix pass computes it, children included. A mask with a painted brush or a range combines in the render graph: each child's coverage, a brush's cached raster, a gradient drawn by a node, or a range read from the image below the mask, folds into the group's in stored order through one combine pass, and the mix pass shares its add, subtract, and intersect. The group takes the image's resolution when a range takes part, since a range follows the photo's edges, and the brushes' otherwise. The renderer gives it out, with each range's own coverage, for the overlay and thumbnails. While a color is picked, renders also keep the image below the mask group, which the picker reads through one GPU pass and 16 bytes of readback per pick.
- Open history groups render a reduced proxy. Every render image carries `scale`, its source pixels per texel; shaders that take document coordinates or radii apply it.
- TIFF and camera RAW decode through `raw-webgpu`; OpenLight adapts its resources to document ownership.
diff --git a/CONTEXT.md b/CONTEXT.md
index 38bb911..6c0ac5e 100644
--- a/CONTEXT.md
+++ b/CONTEXT.md
@@ -6,8 +6,9 @@ OpenLight edits documents containing image content and adjustments.
| --- | --- |
| **Document** | An independent editing session with its own canvas, history, and resources. Opening an image creates a document containing that image. |
| **Scene** | The document's serializable content: canvas geometry, image-source references, and adjustments. Files and GPU resources live outside it. |
-| **Layer** | A source, effect, or mask in the composition. Image layers own basic adjustments; effects process the image below; masks scope their basic adjustments and child effects. Linear, radial, and brush child masks add or subtract coverage. A Paint layer is an effect that lays its strokes' colors over the image with a blend mode. Layers compose render nodes without owning textures. |
+| **Layer** | A source, effect, or mask in the composition. Image layers own basic adjustments; effects process the image below; masks scope their basic adjustments and child effects. Linear, radial, brush, and range child masks add, subtract, or intersect coverage. A Paint layer is an effect that lays its strokes' colors over the image with a blend mode. Layers compose render nodes without owning textures. |
| **Stroke** | One brush drag: paint or erase, size, feather, flow, and points with pressure in source pixels; a Paint layer's strokes also carry a color. Strokes are content; the renderer rasterizes them into a cached texture at half the source's resolution, coverage for a mask and premultiplied color for a Paint layer, and the latest stroke into a shared stroke buffer until the next one starts. A Paint layer's or brush mask's strokes settle into pixels every 100 strokes, which it then paints over; undo still reaches every stroke. A Healing patch stores a hard stroke, rasterized over only the tiles it reaches, and feathers its accumulated shape separately. |
+| **Range** | A mask that selects pixels of the image below its mask group by lightness, a luminance range, or by color, a color range, rather than by position. A new color range has no coverage until it takes a color from a click on the photo. |
| **Healing patch** | One painted, non-destructive repair in a Healing layer. It copies a nearby donor, found automatically or set by hand, with a bounded boundary color correction. Patches replay in order and each sees the result of the preceding patches. Size belongs to the recorded hard stroke; feather and opacity remain editable on its accumulated shape. |
| **Image source** | An image used as input to the document's composition. It is content within a document. |
| **LUT** | A 3D color lookup table, such as a creative grade, read from a `.cube` file. A LUT layer holds one and applies it to the image below, at the layer's opacity. |
diff --git a/biome.json b/biome.json
index a433d4f..d8db6dd 100644
--- a/biome.json
+++ b/biome.json
@@ -14,6 +14,12 @@
},
"linter": {
"rules": {
+ "a11y": {
+ "noLabelWithoutControl": {
+ "level": "error",
+ "options": { "inputComponents": ["ColorInput"] }
+ }
+ },
"style": {
"noRestrictedImports": {
"level": "error",
diff --git a/src/app/commands.ts b/src/app/commands.ts
index f30e801..b8e345f 100644
--- a/src/app/commands.ts
+++ b/src/app/commands.ts
@@ -141,7 +141,7 @@ export const commands = {
}),
),
"add-mask": command(
- "Adds a mask layer on top of the stack with optional adjustments, as one edit, and returns its layerId. Coordinates are source pixels, unaffected by crop. A linear mask covers fully at start and fades out at end; a radial mask covers an ellipse around center with radius [x, y], angle in degrees, and feather from 0 to 1.",
+ "Adds a mask layer on top of the stack with optional adjustments, as one edit, and returns its layerId. Coordinates are source pixels, unaffected by crop. A linear mask covers fully at start and fades out at end; a radial mask covers an ellipse around center with radius [x, y], angle in degrees, and feather from 0 to 1. A luminance-range mask selects pixels of the photo whose lightness lies from low to high, 0 black to 100 white, fading over smoothness; a color-range mask selects pixels near a #rrggbb color in hue and saturation, however light, within tolerance from 0 to 100. A null color has no coverage until a color is chosen.",
z.strictObject({
mask: maskSchema,
adjustments: z.optional(change(adjustmentsSchema)),
diff --git a/src/app/controls.ts b/src/app/controls.ts
index dfab81b..a79d160 100644
--- a/src/app/controls.ts
+++ b/src/app/controls.ts
@@ -21,6 +21,7 @@ import type {
Fill,
Grain,
Mask,
+ MaskLayer,
PaintStroke,
Preview,
ToneCurve,
@@ -171,7 +172,7 @@ export function createControls(
setExposure(workspace.getDocument(), id, exposure),
setLayerMask: (id: string, mask: Mask) =>
setLayerMask(workspace.getDocument(), id, mask),
- setMaskOperation: (id: string, operation: "add" | "subtract") =>
+ setMaskOperation: (id: string, operation: MaskLayer["operation"]) =>
setMaskOperation(workspace.getDocument(), id, operation),
duplicateLayer: (id: string) => duplicateLayer(workspace.getDocument(), id),
deleteLayer: (id: string) => deleteLayer(workspace.getDocument(), id),
diff --git a/src/app/editor/layers.ts b/src/app/editor/layers.ts
index 339126b..5d06c70 100644
--- a/src/app/editor/layers.ts
+++ b/src/app/editor/layers.ts
@@ -118,6 +118,8 @@ const maskNames: Record<Mask["kind"], string> = {
linear: "Linear Gradient",
radial: "Radial Gradient",
brush: "Brush",
+ "luminance-range": "Luminance Range",
+ "color-range": "Color Range",
};
export function createMask(
diff --git a/src/app/editor/mask-overlay.tsx b/src/app/editor/mask-overlay.tsx
index 5c7e451..f81c5cb 100644
--- a/src/app/editor/mask-overlay.tsx
+++ b/src/app/editor/mask-overlay.tsx
@@ -40,9 +40,11 @@ export function MaskOverlaySync() {
// A mask inside a mask has no effects of its own; its group decides.
const group =
location?.parent?.kind === "mask" ? location.parent : layer;
+ // A luminance range has no tool on the canvas, so selecting it is editing it.
+ const edited = editing || layer.mask.kind === "luminance-range";
if (
overlay === "shown" ||
- (overlay === "auto" && editing && maskNeutral(group))
+ (overlay === "auto" && edited && maskNeutral(group))
) {
next = {
mask: layer.mask,
diff --git a/src/app/editor/renderer.ts b/src/app/editor/renderer.ts
index 5a0ab9a..1a86141 100644
--- a/src/app/editor/renderer.ts
+++ b/src/app/editor/renderer.ts
@@ -26,6 +26,7 @@ import { vignette } from "@/features/vignette/pass";
type Branch = {
image: RenderImage;
input?: RenderImage;
+ rangeSource?: RenderImage;
};
function composeLayer(
@@ -41,12 +42,19 @@ function composeLayer(
layer.id === composition.inputId ||
(layer.kind === "heal" &&
layer.patches.some((patch) => patch.id === composition.inputId));
- if (bypassed && !inspected) {
- return { image: below };
- }
+ // A mask's ranges read the image below it, hidden or not.
+ const rangeSource =
+ layer.id === composition.rangeSourceId ? below : undefined;
const masks = layer.kind === "mask" ? maskModifiers(layer) : [];
const coverage =
- layer.kind === "mask" ? composition.coverage(layer) : undefined;
+ layer.kind === "mask" ? composition.coverage(layer, below) : undefined;
+ // Masks under a hidden effect still preview and pick the processed image they select when shown.
+ const holdsMasks =
+ layer.kind !== "mask" &&
+ layer.children.some((child) => child.kind === "mask");
+ if (bypassed && !inspected && !holdsMasks) {
+ return { image: below, rangeSource };
+ }
let input: RenderImage | undefined;
let edited = below;
switch (layer.kind) {
@@ -120,7 +128,11 @@ function composeLayer(
masks,
coverage,
);
- return { image, input: input ?? children.input };
+ return {
+ image,
+ input: input ?? children.input,
+ rangeSource: rangeSource ?? children.rangeSource,
+ };
}
function composeLayers(
@@ -130,12 +142,14 @@ function composeLayers(
): Branch {
let image = below;
let input: RenderImage | undefined;
+ let rangeSource: RenderImage | undefined;
for (const layer of layers) {
const branch = composeLayer(image, layer, composition);
image = branch.image;
input ??= branch.input;
+ rangeSource ??= branch.rangeSource;
}
- return { image, input };
+ return { image, input, rangeSource };
}
/**
@@ -183,6 +197,7 @@ export function createEditorRenderer(
composition.inputId === sourceLayer.id
? adjusted
: (children.input ?? composite.input),
+ rangeSource: children.rangeSource ?? composite.rangeSource,
};
},
timer,
diff --git a/src/app/editor/tools.tsx b/src/app/editor/tools.tsx
index 5cd1c88..13654cd 100644
--- a/src/app/editor/tools.tsx
+++ b/src/app/editor/tools.tsx
@@ -12,14 +12,17 @@ import { AdjustIcon } from "@/components/icons/adjust";
import { BrushIcon } from "@/components/icons/brush";
import { CropIcon } from "@/components/icons/crop";
import { ExportIcon } from "@/components/icons/export";
+import { EyedropperIcon } from "@/components/icons/eyedropper";
import { HealIcon } from "@/components/icons/heal";
import { LinearGradientIcon } from "@/components/icons/linear-gradient";
import { RadialGradientIcon } from "@/components/icons/radial-gradient";
+import { findLayer } from "@/core/document";
import { CropEditor } from "@/features/crop/view";
import { HealOptions } from "@/features/heal/options";
import { HealOverlay } from "@/features/heal/overlay";
import { addLayer } from "@/features/layers/edits";
import { GradientOverlay } from "@/features/layers/gradient-overlay";
+import { RangePicker } from "@/features/layers/range-picker";
import { useShortcuts } from "@/hooks/use-shortcuts";
import { BrushToolCanvas, BrushToolOptions } from "./brush";
import { ExportMode } from "./export";
@@ -132,6 +135,16 @@ export const tools = [
group: "edit",
View: CropEditor,
},
+ {
+ id: "color-range",
+ label: "Color range",
+ shortLabel: "Color",
+ key: "k",
+ Icon: EyedropperIcon,
+ // Color ranges pick from the canvas, but their masks come from the layer menus, not the rail.
+ group: "mask",
+ Canvas: RangePicker,
+ },
exportTool,
] as const;
@@ -144,7 +157,15 @@ export type Tool = (typeof tools)[number];
export function ToolProvider({ children }: { children: ReactNode }) {
const [tool, setTool] = useState<Tool>(adjust);
const brush = useBrushTool();
+ const document = useDocument();
function select(entry: Tool) {
+ if (entry.id === "color-range") {
+ const selected = document.selection.getState().layerId;
+ const layer = findLayer(document.scene.getState().layers, selected);
+ if (layer?.kind !== "mask" || layer.mask.kind !== "color-range") {
+ return;
+ }
+ }
if (entry === tool && entry.id === "brush") {
brush.update({
mode: brush.settings.mode === "color" ? "mask" : "color",
diff --git a/src/components/editor/color-input.tsx b/src/components/editor/color-input.tsx
new file mode 100644
index 0000000..7f54818
--- /dev/null
+++ b/src/components/editor/color-input.tsx
@@ -0,0 +1,26 @@
+import { ColorSwatch } from "@/components/ui/color-swatch";
+import { useDocument } from "./session";
+
+/** A color swatch that edits the document: a pass through the browser's color picker is one edit. */
+export function ColorInput({
+ label,
+ value,
+ onChange,
+}: {
+ label: string;
+ value: string;
+ onChange: (color: string) => void;
+}) {
+ const document = useDocument();
+ return (
+ <ColorSwatch
+ label={label}
+ value={value}
+ onChange={(color) => {
+ document.history.begin();
+ onChange(color);
+ }}
+ onClose={document.history.commit}
+ />
+ );
+}
diff --git a/src/components/editor/pipeline.tsx b/src/components/editor/pipeline.tsx
index 06da406..d9ff7dd 100644
--- a/src/components/editor/pipeline.tsx
+++ b/src/components/editor/pipeline.tsx
@@ -64,6 +64,7 @@ export function RendererProvider({
let active = true;
let requestedScene: ReturnType<typeof document.scene.getState> | undefined;
let requestedInput: string | undefined;
+ let requestedSource: string | undefined;
let requestedInteractive = false;
const render = () => {
const scene = document.scene.getState();
@@ -72,21 +73,24 @@ export function RendererProvider({
document.selection.getState().layerId,
);
const input = target && "toneCurve" in target ? target.id : undefined;
+ const source = document.preview.getState().rangeSource;
// An open gesture renders a proxy; its end renders the same scene in full.
const interactive = document.history.status.getState().editing;
- // A dropped input can stay live; only a new one needs a render.
+ // A dropped input or source can stay live; only a new one needs a render.
if (
scene === requestedScene &&
(input === requestedInput || !input) &&
+ (source === requestedSource || !source) &&
interactive === requestedInteractive
) {
return;
}
requestedScene = scene;
requestedInput = input;
+ requestedSource = source;
requestedInteractive = interactive;
setError(undefined);
- renderer.update(scene, input, interactive).catch((error) => {
+ renderer.update(scene, input, interactive, source).catch((error) => {
if (active) {
setError(String(error));
}
@@ -95,12 +99,14 @@ export function RendererProvider({
const unsubscribeScene = document.scene.subscribe(render);
const unsubscribeSelection = document.selection.subscribe(render);
const unsubscribeHistory = document.history.status.subscribe(render);
+ const unsubscribePreview = document.preview.subscribe(render);
render();
return () => {
active = false;
unsubscribeScene();
unsubscribeSelection();
unsubscribeHistory();
+ unsubscribePreview();
};
}, [renderer, document]);
diff --git a/src/components/icons/eyedropper-cursor.svg b/src/components/icons/eyedropper-cursor.svg
new file mode 100644
index 0000000..720f3e5
--- /dev/null
+++ b/src/components/icons/eyedropper-cursor.svg
@@ -0,0 +1,7 @@
+<svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round">
+ <defs>
+ <path id="pipette" d="M7.75 6.25V4a2.25 2.25 0 0 1 4.5 0v2.25M6.25 6.25h7.5M8.5 6.25V13l1.5 3.5 1.5-3.5V6.25M8.5 11h3" transform="translate(-3.485 3.485) scale(1.2) rotate(45 10 10)"/>
+ </defs>
+ <use href="#pipette" stroke="#171717" stroke-width="2.9"/>
+ <use href="#pipette" stroke="#fafafa" stroke-width="1.7"/>
+</svg>
diff --git a/src/components/icons/eyedropper-cursor.ts b/src/components/icons/eyedropper-cursor.ts
new file mode 100644
index 0000000..320d2af
--- /dev/null
+++ b/src/components/icons/eyedropper-cursor.ts
@@ -0,0 +1,4 @@
+import svg from "./eyedropper-cursor.svg?raw";
+
+/** An eyedropper cursor that picks at its tip, with a crosshair fallback. */
+export const eyedropperCursor = `url("data:image/svg+xml,${encodeURIComponent(svg)}") 3 21, crosshair`;
diff --git a/src/components/icons/eyedropper.tsx b/src/components/icons/eyedropper.tsx
index 1b8b4a8..685bc7f 100644
--- a/src/components/icons/eyedropper.tsx
+++ b/src/components/icons/eyedropper.tsx
@@ -3,7 +3,9 @@ import { Icon, type IconProps } from "./icon";
export function EyedropperIcon(props: IconProps) {
return (
<Icon viewBox="0 0 20 20" {...props}>
- <path d="m11 6 3 3M9.5 7.5l-5 5a2 2 0 0 0-.5 1.5v2h2a2 2 0 0 0 1.5-.5l5-5M10 5l1.5-1.5a2.1 2.1 0 0 1 3 0l2 2a2.1 2.1 0 0 1 0 3L15 10" />
+ <g transform="rotate(45 10 10)">
+ <path d="M7.75 6.25V4a2.25 2.25 0 0 1 4.5 0v2.25M6.25 6.25h7.5M8.5 6.25V13l1.5 3.5 1.5-3.5V6.25M8.5 11h3" />
+ </g>
</Icon>
);
}
diff --git a/src/components/ui/color-swatch.tsx b/src/components/ui/color-swatch.tsx
new file mode 100644
index 0000000..27968b8
--- /dev/null
+++ b/src/components/ui/color-swatch.tsx
@@ -0,0 +1,49 @@
+import { cn } from "cn";
+import { type ComponentProps, useEffect, useRef } from "react";
+
+/**
+ * A raised square of a color that opens the browser's color picker. The picker streams changes while
+ * it moves, and `onClose` follows the last of them.
+ */
+export function ColorSwatch({
+ label,
+ value,
+ onChange,
+ onClose,
+ className,
+ ...props
+}: Omit<ComponentProps<"span">, "onChange"> & {
+ label: string;
+ value: string;
+ onChange: (color: string) => void;
+ onClose?: () => void;
+}) {
+ const input = useRef<HTMLInputElement>(null);
+ useEffect(() => {
+ const element = input.current;
+ if (!element || !onClose) {
+ return;
+ }
+ element.addEventListener("change", onClose);
+ return () => element.removeEventListener("change", onClose);
+ }, [onClose]);
+ return (
+ <span
+ {...props}
+ className={cn(
+ "relative block size-5 shrink-0 rounded-sm surface-control focus-ring",
+ className,
+ )}
+ style={{ backgroundColor: value }}
+ >
+ <input
+ ref={input}
+ type="color"
+ aria-label={label}
+ value={value}
+ className="absolute inset-0 size-full cursor-pointer opacity-0"
+ onChange={(event) => onChange(event.currentTarget.value)}
+ />
+ </span>
+ );
+}
diff --git a/src/core/document/index.ts b/src/core/document/index.ts
index 84e7599..e111415 100644
--- a/src/core/document/index.ts
+++ b/src/core/document/index.ts
@@ -11,6 +11,7 @@ export type {
BrushMask,
BrushStroke,
ColorMixer,
+ ColorRange,
CurvePoint,
Details,
EffectLayer,
@@ -22,6 +23,7 @@ export type {
Layer,
LinearGradient,
LookupTable,
+ LuminanceRange,
Mask,
MaskLayer,
MaskModifier,
@@ -30,6 +32,7 @@ export type {
PaintStroke,
ProcessingLayer,
RadialGradient,
+ RangeMask,
Scene,
StrokePoint,
ToneCurve,
@@ -40,6 +43,7 @@ export {
editLayer,
findLayer,
hasPaint,
+ isRangeMask,
locateLayer,
maskModifiers,
paintingOf,
@@ -61,6 +65,8 @@ export type Preview = {
/** The layer's opacity, which scales the tint like it scales the effect. */
readonly opacity?: number;
};
+ /** The mask whose ranges' image, the one below it, renders keep while a color is picked from it. */
+ rangeSource?: string;
};
/** Scenes contain only plain values; unchanged branches keep their identity. */
diff --git a/src/core/document/scene.ts b/src/core/document/scene.ts
index bdd1694..3460a4b 100644
--- a/src/core/document/scene.ts
+++ b/src/core/document/scene.ts
@@ -123,7 +123,29 @@ export type HealPatch = {
readonly opacity: number;
readonly offset: Point;
};
-export type Mask = Gradient | BrushMask;
+/**
+ * The pixels of the image below the mask group whose lightness, in 0..100 UI units from black to
+ * white, lies within `low` to `high`, fading out over `smoothness` past either end.
+ */
+export type LuminanceRange = {
+ readonly kind: "luminance-range";
+ readonly low: number;
+ readonly high: number;
+ readonly smoothness: number;
+};
+/**
+ * The pixels of the image below the mask group whose hue and saturation are near `color`, `#rrggbb`
+ * sRGB, however light or dark; `null` covers nothing until a color is chosen. `tolerance`, 0..100,
+ * widens the selection.
+ */
+export type ColorRange = {
+ readonly kind: "color-range";
+ readonly color: string | null;
+ readonly tolerance: number;
+};
+/** A mask that selects by the image below it rather than by position. */
+export type RangeMask = LuminanceRange | ColorRange;
+export type Mask = Gradient | BrushMask | RangeMask;
export type ProcessingLayer = {
readonly id: string;
readonly name: string;
@@ -142,7 +164,8 @@ export type ProcessingLayer = {
| ({ readonly kind: "paint"; readonly blend: Blend } & Painting<PaintStroke>)
| {
readonly kind: "mask";
- readonly operation: "add" | "subtract";
+ /** How a mask inside another mask shapes its coverage. */
+ readonly operation: "add" | "subtract" | "intersect";
readonly mask: Mask;
readonly adjustments: Readonly<Adjustments>;
readonly toneCurve: ToneCurve;
@@ -150,7 +173,7 @@ export type ProcessingLayer = {
);
export type MaskLayer = Extract<ProcessingLayer, { kind: "mask" }>;
export type PaintLayer = Extract<ProcessingLayer, { kind: "paint" }>;
-/** A child mask that adds to or subtracts from its parent's coverage. */
+/** A child mask that adds to, subtracts from, or intersects its parent's coverage. */
export type MaskModifier = Pick<
MaskLayer,
"id" | "mask" | "operation" | "opacity"
diff --git a/src/core/document/tree.ts b/src/core/document/tree.ts
index 3576367..f91795f 100644
--- a/src/core/document/tree.ts
+++ b/src/core/document/tree.ts
@@ -1,9 +1,11 @@
import type { EditorDocument } from "./index";
import type {
Layer,
+ Mask,
MaskLayer,
Painting,
ProcessingLayer,
+ RangeMask,
Scene,
} from "./scene";
@@ -55,6 +57,11 @@ export function maskModifiers(layer: MaskLayer) {
);
}
+/** Whether a mask selects by the image below it rather than by position. */
+export function isRangeMask(mask: Mask): mask is RangeMask {
+ return mask.kind === "luminance-range" || mask.kind === "color-range";
+}
+
/** Whether a painting holds anything: settled pixels or strokes over them. */
export function hasPaint(painting: Painting) {
return painting.raster !== undefined || painting.strokes.length > 0;
diff --git a/src/core/image/color.wgsl b/src/core/image/color.wgsl
index fda36cd..3b2c2b2 100644
--- a/src/core/image/color.wgsl
+++ b/src/core/image/color.wgsl
@@ -23,6 +23,21 @@ export const rec2020ToSrgb = mat3x3f(
-0.0728, -0.0083, 1.1187,
);
+// Linear sRGB to Oklab, with Bjorn Ottosson's public-domain 2021 matrices:
+// https://bottosson.github.io/posts/oklab/
+export fn toOklab(rgb: vec3f) -> vec3f {
+ let lms = mat3x3f(
+ 0.4122214708, 0.2119034982, 0.0883024619,
+ 0.5363325363, 0.6806995451, 0.2817188376,
+ 0.0514459929, 0.1073969566, 0.6299787005,
+ ) * rgb;
+ return mat3x3f(
+ 0.2104542553, 1.9779984951, 0.0259040371,
+ 0.7936177850, -2.4285922050, 0.7827717662,
+ -0.0040720468, 0.4505937099, -0.8086757660,
+ ) * (sign(lms) * pow(abs(lms), vec3f(1.0 / 3.0)));
+}
+
/**
* Luminance-preserving gamut clip: a color the target cannot show slides toward the gray of its own
* luminance until it fits, so brightness and hue hold and only saturation is lost. This is the
diff --git a/src/core/renderer/blend/coverage.wgsl b/src/core/renderer/blend/coverage.wgsl
index b6be11c..993c27b 100644
--- a/src/core/renderer/blend/coverage.wgsl
+++ b/src/core/renderer/blend/coverage.wgsl
@@ -9,3 +9,13 @@ export fn gradientCoverage(position: vec2f, first: vec2f, second: vec2f, kind: u
let direction = second - first;
return 1.0 - clamp(dot(position - first, direction) / dot(direction, direction), 0.0, 1.0);
}
+
+// A child mask's coverage applied to its group's, at the child's opacity: operation 0 adds, 1
+// subtracts, and 2 intersects, keeping the group only where the child covers.
+export fn combineCoverage(group: f32, child: f32, operation: u32, opacity: f32) -> f32 {
+ if (operation == 2u) {
+ return group * (1.0 - opacity * (1.0 - child));
+ }
+ let sign = select(1.0, -1.0, operation == 1u);
+ return clamp(group + sign * opacity * child, 0.0, 1.0);
+}
diff --git a/src/core/renderer/blend/index.ts b/src/core/renderer/blend/index.ts
index e8f6717..bf0279b 100644
--- a/src/core/renderer/blend/index.ts
+++ b/src/core/renderer/blend/index.ts
@@ -1,16 +1,23 @@
-import type { Mask, MaskModifier } from "@/core/document";
-import {
- merge,
- node,
- type RenderImage,
- type RenderInput,
-} from "@/core/renderer/node";
+import type { Gradient, Mask, MaskLayer, MaskModifier } from "@/core/document";
+import { merge, node, type RenderImage } from "@/core/renderer/node";
import shader from "./mix.wgsl";
import rasterShader from "./raster.wgsl";
-const emptyModifiers = new Float32Array(8);
+const emptyModifiers = new Float32Array(12);
-/** Uniform fields for one gradient; kind 0 means full coverage. Brush masks have no analytical form. */
+/** Mask operations as the shaders number them. */
+export const operations: Record<MaskLayer["operation"], number> = {
+ add: 0,
+ subtract: 1,
+ intersect: 2,
+};
+
+/** Whether a mask has an analytical form; brushes and ranges only exist in a raster. */
+export function isGradient(mask: Mask): mask is Gradient {
+ return mask.kind === "linear" || mask.kind === "radial";
+}
+
+/** Uniform fields for one gradient; kind 0 means full coverage. */
export function gradientParams(mask?: Mask) {
if (mask?.kind === "radial") {
return {
@@ -30,30 +37,34 @@ export function gradientParams(mask?: Mask) {
};
}
-/** The modifiers with an analytical form; brush children only exist inside a raster. */
+/** The modifiers with an analytical form. */
export function gradientModifiers(modifiers: readonly MaskModifier[]) {
- return modifiers.filter(({ mask }) => mask.kind !== "brush");
+ return modifiers.filter(({ mask }) => isGradient(mask));
}
-/** Two vec4 per gradient modifier: geometry, then signed strength, kind, feather, and angle. */
+/** Three vec4 per gradient modifier: geometry; strength, kind, feather, and angle; then operation. */
export function modifierData(modifiers: readonly MaskModifier[]) {
const gradients = gradientModifiers(modifiers);
if (!gradients.length) {
return emptyModifiers;
}
- const data = new Float32Array(gradients.length * 8);
+ const data = new Float32Array(gradients.length * 12);
gradients.forEach(({ mask, opacity, operation }, index) => {
const { first, second, kind, feather, angle } = gradientParams(mask);
data.set(
[
...first,
...second,
- operation === "add" ? opacity : -opacity,
+ opacity,
kind,
feather,
angle,
+ operations[operation],
+ 0,
+ 0,
+ 0,
],
- index * 8,
+ index * 12,
);
});
return data;
@@ -61,7 +72,8 @@ export function modifierData(modifiers: readonly MaskModifier[]) {
/**
* Interpolates an adjustment result without changing image coverage or HDR headroom.
- * Rasterized coverage replaces the analytical gradients when a brush is involved.
+ * Rasterized coverage replaces the analytical gradients when a brush or range is involved; without it,
+ * such a mask covers nothing yet.
*/
export function mixAdjustment(
name: string,
@@ -70,7 +82,7 @@ export function mixAdjustment(
opacity: number,
mask?: Mask,
modifiers: readonly MaskModifier[] = [],
- coverage?: RenderInput,
+ coverage?: RenderImage,
) {
if (original === edited || opacity === 0) {
return original;
@@ -89,7 +101,7 @@ export function mixAdjustment(
}),
);
}
- if (mask?.kind === "brush") {
+ if (mask && !isGradient(mask)) {
return original;
}
const gradients = gradientModifiers(modifiers);
@@ -119,7 +131,7 @@ export function maskInput(
image: RenderImage,
mask: Mask,
modifiers: readonly MaskModifier[] = [],
- coverage?: RenderInput,
+ coverage?: RenderImage,
) {
if (coverage) {
return merge(
@@ -132,7 +144,7 @@ export function maskInput(
}),
);
}
- if (mask.kind === "brush") {
+ if (!isGradient(mask)) {
return image;
}
const gradients = gradientModifiers(modifiers);
diff --git a/src/core/renderer/blend/mix.wgsl b/src/core/renderer/blend/mix.wgsl
index d8383b7..f109396 100644
--- a/src/core/renderer/blend/mix.wgsl
+++ b/src/core/renderer/blend/mix.wgsl
@@ -1,4 +1,4 @@
-import { gradientCoverage } from "./coverage.wgsl";
+import { combineCoverage, gradientCoverage } from "./coverage.wgsl";
struct Params {
opacity: f32,
@@ -26,9 +26,10 @@ struct Params {
let at = position.xy * params.scale;
coverage = gradientCoverage(at, params.first, params.second, params.kind, params.feather, params.angle);
for (var i = 0u; i < params.modifierCount; i++) {
- let points = modifiers[i * 2u];
- let settings = modifiers[i * 2u + 1u];
- coverage = clamp(coverage + gradientCoverage(at, points.xy, points.zw, u32(settings.y), settings.z, settings.w) * settings.x, 0.0, 1.0);
+ let points = modifiers[i * 3u];
+ let settings = modifiers[i * 3u + 1u];
+ let child = gradientCoverage(at, points.xy, points.zw, u32(settings.y), settings.z, settings.w);
+ coverage = combineCoverage(coverage, child, u32(modifiers[i * 3u + 2u].x), settings.x);
}
}
if (params.mode == 1u) {
diff --git a/src/core/renderer/display/image.wgsl b/src/core/renderer/display/image.wgsl
index c70aa7a..9555520 100644
--- a/src/core/renderer/display/image.wgsl
+++ b/src/core/renderer/display/image.wgsl
@@ -1,6 +1,6 @@
import { View, imagePoint, previewColor, background, maskTint } from "./display.wgsl";
import { Transform, sourcePoint } from "../transform/transform.wgsl";
-import { gradientCoverage } from "../blend/coverage.wgsl";
+import { combineCoverage, gradientCoverage } from "../blend/coverage.wgsl";
struct MaskOverlay {
kind: u32,
@@ -34,9 +34,10 @@ fn overlayCoverage(uv: vec2f) -> f32 {
let position = point * overlay.sourceSize;
var coverage = gradientCoverage(position, overlay.first, overlay.second, overlay.kind, overlay.feather, overlay.angle);
for (var i = 0u; i < overlay.modifierCount; i++) {
- let points = modifiers[i * 2u];
- let settings = modifiers[i * 2u + 1u];
- coverage = clamp(coverage + gradientCoverage(position, points.xy, points.zw, u32(settings.y), settings.z, settings.w) * settings.x, 0.0, 1.0);
+ let points = modifiers[i * 3u];
+ let settings = modifiers[i * 3u + 1u];
+ let child = gradientCoverage(position, points.xy, points.zw, u32(settings.y), settings.z, settings.w);
+ coverage = combineCoverage(coverage, child, u32(modifiers[i * 3u + 2u].x), settings.x);
}
return coverage * overlay.opacity;
}
diff --git a/src/core/renderer/index.ts b/src/core/renderer/index.ts
index e4294f3..830f646 100644
--- a/src/core/renderer/index.ts
+++ b/src/core/renderer/index.ts
@@ -1,6 +1,7 @@
import type { Gpu, Target, Timer } from "vgpu";
import {
type BrushStroke,
+ hasPaint,
type MaskLayer,
type PaintLayer,
paintingOf,
@@ -10,9 +11,9 @@ import {
import type { ImageSource, WhiteBalance } from "@/core/image";
import type { Point } from "@/core/image/frame";
import { createRenderGraph } from "./graph";
-import { createMaskRaster } from "./mask";
+import { createMaskCoverage } from "./mask";
import { createPatchRaster, type PatchInput } from "./mask/patches";
-import { input, type RenderImage, type RenderInput } from "./node";
+import { input, type RenderImage } from "./node";
import {
type AcceptPainting,
createPaintRaster,
@@ -52,10 +53,15 @@ export { createRenderGraph };
export type Composition = {
inputId?: string;
+ /** The mask whose ranges' image, the one below it, to keep for picking colors from it. */
+ rangeSourceId?: string;
/** Keep one stable composition instance and its render-graph resources reusable. */
retain: (id: string) => void;
- /** Rasterized coverage of a mask that paints with brushes, prepared before composition. */
- coverage: (layer: MaskLayer) => RenderInput | undefined;
+ /**
+ * A mask's coverage over `below`, the image it applies to, when a brush or range takes part;
+ * gradients alone leave it to the mix pass.
+ */
+ coverage: (layer: MaskLayer, below: RenderImage) => RenderImage | undefined;
/** Rasterized paint of a paint layer, prepared before composition. */
paint: (layer: PaintLayer) => PaintInput | undefined;
/** Rasterized coverage of an effect's own stroke, such as a Healing patch. */
@@ -72,11 +78,13 @@ export type SceneProcessing = (
full: RenderImage;
output: RenderImage;
input?: RenderImage;
+ rangeSource?: RenderImage;
};
type RenderRequest = {
scene: Scene;
inputId?: string;
+ rangeSourceId?: string;
/** Source pixels per texel of the composition's source; above 1 renders a reduced proxy. */
factor: number;
};
@@ -102,7 +110,7 @@ export function createRenderer(
const graph = createRenderGraph(gpu, timer);
const strokes = createStrokes(gpu);
const brushes = createPaintRaster(gpu, strokes, "r8unorm");
- const masks = createMaskRaster(gpu, brushes);
+ const masks = createMaskCoverage(brushes);
const patches = createPatchRaster(gpu, strokes);
const paints = createPaintRaster(gpu, strokes, "rgba8unorm");
const proxy = createProxy(gpu);
@@ -114,6 +122,9 @@ export function createRenderer(
let rendered = false;
let output = source;
let inspected: { id: string; image: Target } | undefined;
+ let kept: { id: string; image: Target } | undefined;
+ /** Mask coverage the graph rendered for the overlay and thumbnails, by layer ID. */
+ let shown = new Map<string, Target>();
let balance = resource.raw?.asShot;
/** Counts developments, so the proxy follows white-balance changes. */
let version = 0;
@@ -126,21 +137,22 @@ export function createRenderer(
let disposed = false;
let instances = new Set<string>();
function render(request: RenderRequest) {
- const { scene, inputId, factor } = request;
+ const { scene, inputId, rangeSourceId, factor } = request;
if (
last &&
last.scene === scene &&
last.inputId === inputId &&
+ last.rangeSourceId === rangeSourceId &&
last.factor === factor
) {
return;
}
const active = new Set<string>();
const developed = raw?.render() ?? source;
- // Every mask and paint layer updates once, bypassed or not, so a hidden one keeps its raster; child masks only shape their parent's coverage.
- for (const { layer, parent } of walkLayers(scene.layers)) {
- if (layer.kind === "mask" && parent?.kind !== "mask") {
- masks.update(layer, developed.size);
+ // Every brush and paint layer updates once, bypassed or not, so hidden layers keep their rasters.
+ for (const { layer } of walkLayers(scene.layers)) {
+ if (layer.kind === "mask" && layer.mask.kind === "brush") {
+ brushes.draw(layer.id, layer.mask, developed.size);
}
if (layer.kind === "paint") {
paints.draw(layer.id, layer, developed.size);
@@ -148,10 +160,27 @@ export function createRenderer(
}
const image =
factor > 1 ? proxy.render(developed, factor, version) : input(developed);
+ const covered = new Map<string, RenderImage>();
+ // Read brush views after every raster has updated, including inactive submasks.
+ for (const { layer } of walkLayers(scene.layers)) {
+ if (
+ layer.kind === "mask" &&
+ layer.mask.kind === "brush" &&
+ hasPaint(layer.mask)
+ ) {
+ const coverage = brushes.coverage(layer.id);
+ if (coverage) covered.set(layer.id, coverage);
+ }
+ }
const images = compose(image, scene, {
inputId,
+ rangeSourceId,
retain: (id) => active.add(id),
- coverage: (layer) => masks.coverage(layer.id),
+ coverage: (layer, below) =>
+ masks.coverage(layer, below, {
+ retain: (id) => active.add(id),
+ show: (id, coverage) => covered.set(id, coverage),
+ }),
paint: (layer) => paints.input(layer),
patch: (id, stroke) => patches.patch(id, stroke, developed.size),
});
@@ -164,15 +193,28 @@ export function createRenderer(
patches.sweep();
paints.sweep();
strokes.sweep();
+ // Every render shows three images; the inspected input, the range source, and coverage follow.
+ const inputs = images.input ? [images.input] : [];
+ const sources = images.rangeSource ? [images.rangeSource] : [];
const targets = graph.render([
images.original,
images.full,
images.output,
- ...(images.input ? [images.input] : []),
+ ...inputs,
+ ...sources,
+ ...covered.values(),
]);
[original, full, output] = targets;
+ const [inputTarget] = targets.slice(3, 3 + inputs.length);
+ const [sourceTarget] = targets.slice(3 + inputs.length);
+ const coverages = targets.slice(3 + inputs.length + sources.length);
inspected =
- inputId && targets[3] ? { id: inputId, image: targets[3] } : undefined;
+ inputId && images.input ? { id: inputId, image: inputTarget } : undefined;
+ kept =
+ rangeSourceId && images.rangeSource
+ ? { id: rangeSourceId, image: sourceTarget }
+ : undefined;
+ shown = new Map([...covered.keys()].map((id, i) => [id, coverages[i]]));
rendered = true;
last = request;
for (const listener of listeners) {
@@ -229,22 +271,27 @@ export function createRenderer(
}
}
}
- /** Interactive updates render at a proxy resolution matched to the display scale. */
+ /**
+ * Interactive updates render at a proxy resolution matched to the display scale. `inputId` keeps a
+ * layer's curve input, and `rangeSourceId` a mask's range source, for reading them.
+ */
async function update(
scene: Scene,
inputId?: string,
interactive = false,
+ rangeSourceId?: string,
): Promise<void> {
if (disposed) {
throw Error("Renderer is closed.");
}
const factor = interactive ? Math.max(1, Math.floor(1 / displayScale)) : 1;
+ const request = { scene, inputId, rangeSourceId, factor };
// Renders wait, in order, for a settle, a RAW development, or settled paint to load.
if (!raw && !pending && !settling && !stalePaint(scene).length) {
- render({ scene, inputId, factor });
+ render(request);
return;
}
- next = { scene, inputId, factor };
+ next = request;
pending ??= develop()
.catch((error) => {
if (!next) {
@@ -254,7 +301,8 @@ export function createRenderer(
.finally(() => {
pending = undefined;
if (next && !disposed) {
- return update(next.scene, next.inputId, next.factor > 1);
+ const { scene, inputId, factor, rangeSourceId } = next;
+ return update(scene, inputId, factor > 1, rangeSourceId);
}
});
return pending;
@@ -277,12 +325,14 @@ export function createRenderer(
outputImage: () => output,
inputImage: (id: string) =>
inspected?.id === id ? inspected.image : undefined,
+ /** The image below a mask, which its ranges read, while an update keeps it. */
+ rangeSource: (id: string) => (kept?.id === id ? kept.image : undefined),
/**
* A raster by ID and where it sits in the photo: a mask's coverage, for the display overlay and
* thumbnails, a Healing patch's, or a paint layer's.
*/
coverage(id: string): { target: Target; origin: Point } | undefined {
- const target = masks.coverage(id)?.target ?? paints.get(id);
+ const target = shown.get(id) ?? paints.get(id);
return target ? { target, origin: [0, 0] } : patches.raster(id);
},
/** Device pixels shown per source pixel; interactive renders reduce the source to about this density. */
diff --git a/src/core/renderer/mask/brush.wgsl b/src/core/renderer/mask/brush.wgsl
deleted file mode 100644
index 520bd6b..0000000
--- a/src/core/renderer/mask/brush.wgsl
+++ /dev/null
@@ -1,11 +0,0 @@
-// One brush's rasterized coverage scaled by its strength; the pass blend adds or subtracts it from its group.
-struct Params {
- opacity: f32,
-}
-@group(0) @binding(0) var coverage: texture_2d<f32>;
-@group(0) @binding(1) var<uniform> params: Params;
-
-@fragment fn fs_main(@builtin(position) position: vec4f) -> @location(0) vec4f {
- let value = textureLoad(coverage, vec2i(position.xy), 0).r;
- return vec4f(value * params.opacity, 0.0, 0.0, 1.0);
-}
diff --git a/src/core/renderer/mask/combine.wgsl b/src/core/renderer/mask/combine.wgsl
new file mode 100644
index 0000000..ef59a93
--- /dev/null
+++ b/src/core/renderer/mask/combine.wgsl
@@ -0,0 +1,17 @@
+import { combineCoverage } from "../blend/coverage.wgsl";
+
+// Folds a child mask's coverage into its group's; either may come at another resolution, sampled by position.
+struct Params {
+ operation: u32,
+ opacity: f32,
+}
+@group(0) @binding(0) var group: texture_2d<f32>;
+@group(0) @binding(1) var coverage: texture_2d<f32>;
+@group(0) @binding(2) var coverageSampler: sampler;
+@group(0) @binding(3) var<uniform> params: Params;
+
+@fragment fn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {
+ let current = textureSampleLevel(group, coverageSampler, uv, 0.0).r;
+ let child = textureSampleLevel(coverage, coverageSampler, uv, 0.0).r;
+ return vec4f(combineCoverage(current, child, params.operation, params.opacity), 0.0, 0.0, 1.0);
+}
diff --git a/src/core/renderer/mask/empty.wgsl b/src/core/renderer/mask/empty.wgsl
new file mode 100644
index 0000000..19914b6
--- /dev/null
+++ b/src/core/renderer/mask/empty.wgsl
@@ -0,0 +1,4 @@
+// A group that covers nothing yet, such as an unpainted brush that children add to.
+@fragment fn fs_main() -> @location(0) vec4f {
+ return vec4f(0.0, 0.0, 0.0, 1.0);
+}
diff --git a/src/core/renderer/mask/gradient.wgsl b/src/core/renderer/mask/gradient.wgsl
index a342d4c..fa6cc2c 100644
--- a/src/core/renderer/mask/gradient.wgsl
+++ b/src/core/renderer/mask/gradient.wgsl
@@ -1,19 +1,18 @@
import { gradientCoverage } from "../blend/coverage.wgsl";
-// One gradient's coverage in a mask's group, scaled by its strength; the pass blend adds or subtracts it.
+// One gradient's coverage, for a mask whose group combines in the render graph.
struct Params {
kind: u32,
first: vec2f,
second: vec2f,
feather: f32,
angle: f32,
- opacity: f32,
- // Photo pixels per group texel, so the gradient lands where it does on the photo.
+ // Photo pixels per texel, so the gradient lands where it does on the photo.
scale: vec2f,
}
@group(0) @binding(0) var<uniform> params: Params;
@fragment fn fs_main(@builtin(position) position: vec4f) -> @location(0) vec4f {
let coverage = gradientCoverage(position.xy * params.scale, params.first, params.second, params.kind, params.feather, params.angle);
- return vec4f(coverage * params.opacity, 0.0, 0.0, 1.0);
+ return vec4f(coverage, 0.0, 0.0, 1.0);
}
diff --git a/src/core/renderer/mask/index.ts b/src/core/renderer/mask/index.ts
index 3853f4b..404c54b 100644
--- a/src/core/renderer/mask/index.ts
+++ b/src/core/renderer/mask/index.ts
@@ -1,22 +1,24 @@
-import { type BlendOptions, effect, frame, type Gpu, type Target } from "vgpu";
import {
hasPaint,
+ isRangeMask,
type MaskLayer,
type MaskModifier,
maskModifiers,
+ type RangeMask,
} from "@/core/document";
-import { gradientParams } from "@/core/renderer/blend";
-import { input, type RenderInput } from "@/core/renderer/node";
+import { parseColor } from "@/core/image/blend";
+import { gradientParams, isGradient, operations } from "@/core/renderer/blend";
+import { generate, merge, node, type RenderImage } from "@/core/renderer/node";
import { type PaintRaster, paintingSize } from "@/core/renderer/paint";
-import { createRasterCache } from "@/core/renderer/raster-cache";
-import brushShader from "./brush.wgsl";
+import combineShader from "./combine.wgsl";
+import emptyShader from "./empty.wgsl";
import gradientShader from "./gradient.wgsl";
+import rangeShader from "./range.wgsl";
-type Size = readonly [number, number];
-/** A mask's own coverage combined with the children that shape it. */
-type Group = {
- target: Target;
- ops: readonly MaskModifier[];
+/** Where a render keeps what a mask's coverage made: pass instances to keep, and coverage to show. */
+type CoverageOutputs = {
+ retain: (instance: string) => void;
+ show: (id: string, coverage: RenderImage) => void;
};
/** A mask's own coverage followed by the children that shape it, in stored order. */
@@ -27,150 +29,118 @@ function maskOps(layer: MaskLayer): readonly MaskModifier[] {
];
}
-/** Whether an op can cover pixels: a gradient always does, a brush once it has paint. */
-function covers(op: MaskModifier) {
- return op.mask.kind !== "brush" || hasPaint(op.mask);
-}
-
-function sameOps(a: readonly MaskModifier[], b: readonly MaskModifier[]) {
- return (
- a.length === b.length &&
- a.every(
- (op, i) =>
- op.mask === b[i].mask &&
- op.operation === b[i].operation &&
- op.opacity === b[i].opacity,
- )
- );
+/** Uniform fields for a range, its UI units scaled to 0..1. */
+function rangeParams(mask: RangeMask) {
+ if (mask.kind === "luminance-range") {
+ const { low, high, smoothness } = mask;
+ return { kind: 1, range: [low, high, smoothness, 0].map((v) => v / 100) };
+ }
+ if (mask.color === null) {
+ return { kind: 0, range: [0, 0, 0, 0] };
+ }
+ return {
+ kind: 2,
+ range: [...parseColor(mask.color), mask.tolerance / 100],
+ };
}
-const add: BlendOptions = { color: { src: "one", dst: "one" } };
-const subtract: BlendOptions = {
- color: { src: "one", dst: "one", op: "reverse-subtract" },
+const linear: GPUSamplerDescriptor = {
+ minFilter: "linear",
+ magFilter: "linear",
};
/**
- * Brings masks' coverage together at half the photo's resolution, as paintings keep theirs. A brush paints its coverage as a paint layer
- * paints color, into an r8unorm raster of `brushes`; a mask shaped by children combines its own
- * coverage with theirs in a second texture, rebuilt whenever any of them changes. Gradients alone
- * need no texture: the mix pass computes them.
+ * Mask coverage. A brush paints its coverage as a paint layer paints color, into a cached r8 raster
+ * of `brushes`. A mask that only gradients shape needs no texture: the mix pass computes it. Any
+ * other mask folds its children's coverage into its own in the render graph, one pass per child in
+ * stored order, at the image's resolution when a range takes part, since a range follows the photo's
+ * edges, and at the brushes' otherwise.
*/
-export function createMaskRaster(gpu: Gpu, brushes: PaintRaster) {
- const groups = createRasterCache<Group>(gpu, "r8unorm", (target) => ({
- target,
- ops: [],
- }));
- /** Each mask layer's coverage as its last update left it: its brush's, its group's, or none. */
- const shown = new Map<string, Target | Group | undefined>();
- const updated = new Set<string>();
- const gradientAdd = effect(gpu, gradientShader, { blend: add });
- const gradientSubtract = effect(gpu, gradientShader, { blend: subtract });
- const brushAdd = effect(gpu, brushShader, { blend: add });
- const brushSubtract = effect(gpu, brushShader, { blend: subtract });
-
- /** The pass that adds or subtracts one op's coverage, or nothing for a brush without strokes. */
- function opPass(op: MaskModifier, scale: Size) {
- if (op.mask.kind !== "brush") {
- const pass = op.operation === "add" ? gradientAdd : gradientSubtract;
- return pass.set({
- params: { ...gradientParams(op.mask), opacity: op.opacity, scale },
- });
- }
- const brush = covers(op) ? brushes.coverage(op.id) : undefined;
- if (!brush) {
- return undefined;
- }
- const pass = op.operation === "add" ? brushAdd : brushSubtract;
- return pass.set({
- coverage: brush.target.color,
- params: { opacity: op.opacity },
- });
- }
-
- /** Combines a mask's own coverage with its children's in stored order, once any of them changed. */
- function updateGroup(id: string, ops: readonly MaskModifier[], source: Size) {
- const size = paintingSize(source);
- const group = groups.reserve(id, size);
- // Gradients evaluate at photo pixels, and the group keeps the brushes' resolution.
- const scale = [source[0] / size[0], source[1] / size[1]] as const;
- if (sameOps(group.ops, ops)) {
- return group;
- }
- frame(gpu, (frame) =>
- frame.pass({ target: group.target, clear: true }, () => {}),
- );
- for (const op of ops) {
- const pass = opPass(op, scale);
- if (pass) {
- // One frame per pass: uniform writes land in queue order, before the pass that reads them.
- frame(gpu, (frame) =>
- frame.pass({ target: group.target, clear: false }, pass),
- );
- }
- }
- group.ops = ops;
- return group;
- }
-
- /** Brings a mask layer's rasters up to date and returns the one that holds its coverage, if any. */
- function updateLayer(layer: MaskLayer, size: Size) {
- const [own, ...children] = maskOps(layer);
- const active = children.filter(covers);
- const ops = [own, ...active];
- for (const op of ops) {
- if (op.mask.kind === "brush" && covers(op)) {
- brushes.draw(op.id, op.mask, size);
- }
- }
- if (own.mask.kind !== "brush") {
- // Gradient children combine in the mix pass; a painted brush child needs a raster.
- return active.some((op) => op.mask.kind === "brush")
- ? updateGroup(layer.id, ops, size)
- : undefined;
- }
- if (active.length === 0) {
- // Nothing shapes the brush, so its own coverage is the mask's; without strokes the layer is bypassed.
- return covers(own) ? brushes.get(own.id) : undefined;
- }
- if (!covers(own) && !active.some((op) => op.operation === "add")) {
- return undefined;
- }
- return updateGroup(layer.id, ops, size);
- }
-
+export function createMaskCoverage(brushes: PaintRaster) {
return {
- /** Brings a mask layer's rasters up to date; `coverage` reads them once every layer has. */
- update(layer: MaskLayer, size: Size) {
- shown.set(layer.id, updateLayer(layer, size));
- updated.add(layer.id);
- },
/**
- * A mask layer's coverage, or a brush's own, if any. Read it once every layer updated: drawing one
- * brush can close another's stroke.
+ * A mask's coverage over `below`, the image it applies to, or nothing when the mix pass computes
+ * it or, as for a brush yet to paint with nothing added, it covers nothing. Read it after all brush
+ * rasters have updated.
*/
- coverage(id: string): RenderInput | undefined {
- const raster = shown.has(id) ? shown.get(id) : brushes.get(id);
- if (!raster) {
+ coverage(
+ layer: MaskLayer,
+ below: RenderImage,
+ { retain, show }: CoverageOutputs,
+ ): RenderImage | undefined {
+ const ops = maskOps(layer);
+ const [own, ...children] = ops;
+ const ranged = ops.some(({ mask }) => isRangeMask(mask));
+ const painted = ops.some(
+ ({ mask }) => mask.kind === "brush" && hasPaint(mask),
+ );
+ if (isGradient(own.mask) && !ranged && !painted) {
return undefined;
}
- return "ops" in raster ? input(raster.target) : brushes.coverage(id);
- },
- /** Releases the rasters that no update used since the previous sweep, including their painting views. */
- sweep() {
- for (const id of shown.keys()) {
- if (!updated.has(id)) {
- shown.delete(id);
+ const size = ranged ? below.size : paintingSize(below.size);
+ const scale = [
+ (below.scale[0] * below.size[0]) / size[0],
+ (below.scale[1] * below.size[1]) / size[1],
+ ] as const;
+ const output = { size, format: "r8unorm" as const, scale };
+ /** One op's own coverage, or nothing for a brush yet to paint. */
+ function covered(name: string, { id, mask }: MaskModifier) {
+ if (mask.kind === "brush") {
+ return hasPaint(mask) ? brushes.coverage(id) : undefined;
+ }
+ if (isGradient(mask)) {
+ return generate(
+ output,
+ node(`${name}/gradient`, gradientShader, {
+ set: { params: { ...gradientParams(mask), scale } },
+ }),
+ );
}
+ const range = merge(
+ { image: below },
+ node(`${name}/range`, rangeShader, {
+ ...output,
+ set: { params: rangeParams(mask) },
+ }),
+ );
+ show(id, range);
+ return range;
}
- updated.clear();
- brushes.sweep();
- groups.sweep();
- },
- inspect: () => [...brushes.inspect(), ...groups.inspect("/group")],
- dispose() {
- brushes.dispose();
- groups.dispose();
- shown.clear();
+ const name = (id: string) => {
+ retain(`mask/${id}`);
+ return `mask/${id}`;
+ };
+ let group = covered(name(layer.id), own);
+ for (const child of children) {
+ const coverage = covered(name(child.id), child);
+ // A brush yet to paint takes no part, and a group that covers nothing yet only takes additions.
+ if (!coverage || (!group && child.operation !== "add")) {
+ continue;
+ }
+ const start =
+ group ??
+ generate(output, node(`${name(layer.id)}/empty`, emptyShader));
+ group = merge(
+ { group: start, coverage },
+ node(`${name(child.id)}/combine`, combineShader, {
+ ...output,
+ samplers: { coverageSampler: linear },
+ set: {
+ params: {
+ operation: operations[child.operation],
+ opacity: child.opacity,
+ },
+ },
+ }),
+ );
+ }
+ if (group) {
+ show(layer.id, group);
+ }
+ return group;
},
+ sweep: () => brushes.sweep(),
+ inspect: () => brushes.inspect(),
+ dispose: () => brushes.dispose(),
};
}
diff --git a/src/core/renderer/mask/range.wgsl b/src/core/renderer/mask/range.wgsl
new file mode 100644
index 0000000..4727dba
--- /dev/null
+++ b/src/core/renderer/mask/range.wgsl
@@ -0,0 +1,40 @@
+import { srgbToLinear3 } from "@vgpu/wgsl-std/color";
+import { luminance, rec2020ToSrgb, toOklab } from "../../image/color.wgsl";
+
+// A range mask's coverage: how much it keeps of each pixel of the image below its group.
+struct Params {
+ // 0 is an unpicked color with no coverage; 1 is luminance; 2 is a chosen color.
+ kind: u32,
+ range: vec4f,
+}
+@group(0) @binding(0) var image: texture_2d<f32>;
+@group(0) @binding(1) var<uniform> params: Params;
+
+// CIE lightness of a working color, 0 black to 1 white; headroom above white counts as white.
+fn lightness(color: vec3f) -> f32 {
+ let y = clamp(luminance(color), 0.0, 1.0);
+ return select(y * 9.033, 1.16 * pow(y, 1.0 / 3.0) - 0.16, y > 0.008856);
+}
+
+// Hue and saturation of a linear sRGB color, as Oklab chroma over lightness, which exposure leaves unchanged.
+fn tint(srgb: vec3f) -> vec2f {
+ let lab = toOklab(srgb);
+ return lab.yz / max(lab.x, 0.02);
+}
+
+fn kept(color: vec3f) -> f32 {
+ if (params.kind == 0u) {
+ return 0.0;
+ }
+ if (params.kind == 1u) {
+ let light = lightness(color);
+ let soft = max(params.range.z, 0.0001);
+ return smoothstep(params.range.x - soft, params.range.x, light) * (1.0 - smoothstep(params.range.y, params.range.y + soft, light));
+ }
+ let radius = mix(0.01, 0.25, params.range.w);
+ return 1.0 - smoothstep(radius * 0.5, radius, distance(tint(rec2020ToSrgb * color), tint(srgbToLinear3(params.range.xyz))));
+}
+
+@fragment fn fs_main(@builtin(position) position: vec4f) -> @location(0) vec4f {
+ return vec4f(kept(textureLoad(image, vec2i(position.xy), 0).rgb), 0.0, 0.0, 1.0);
+}
diff --git a/src/core/renderer/node.ts b/src/core/renderer/node.ts
index ffc28d9..fc25571 100644
--- a/src/core/renderer/node.ts
+++ b/src/core/renderer/node.ts
@@ -55,6 +55,14 @@ export function node(
return { ...options, name, shader };
}
+/** A node that draws from its settings alone, such as a gradient's coverage, into an image of `output`'s kind. */
+export function generate(
+ output: Pick<RenderNode, "size" | "format" | "scale">,
+ definition: NodeDefinition,
+): RenderNode {
+ return { ...definition, ...output, inputs: {} };
+}
+
/** Connects named shader inputs; the shader defines how to combine them. */
export function merge(
inputs: RenderNode["inputs"],
diff --git a/src/features/color-mixer/mixer.wgsl b/src/features/color-mixer/mixer.wgsl
index 0422f5c..04b7e7f 100644
--- a/src/features/color-mixer/mixer.wgsl
+++ b/src/features/color-mixer/mixer.wgsl
@@ -1,4 +1,4 @@
-import { luminance, rec2020ToSrgb, srgbToRec2020 } from "../../core/image/color.wgsl";
+import { luminance, rec2020ToSrgb, srgbToRec2020, toOklab } from "../../core/image/color.wgsl";
// Selective color in Oklab: at +/-100 a range turns hue 30 degrees, scales chroma 0..2x or moves luminance one stop.
// The import above is relative because the shader loader does not resolve the `@/` alias.
@@ -6,21 +6,7 @@ import { luminance, rec2020ToSrgb, srgbToRec2020 } from "../../core/image/color.
@group(0) @binding(0) var source: texture_2d<f32>;
@group(0) @binding(1) var<storage, read> settings: array<vec4f>;
-// Bjorn Ottosson's public-domain Oklab transforms (2021 matrices):
-// https://bottosson.github.io/posts/oklab/
-fn toOklab(rgb: vec3f) -> vec3f {
- let lms = mat3x3f(
- 0.4122214708, 0.2119034982, 0.0883024619,
- 0.5363325363, 0.6806995451, 0.2817188376,
- 0.0514459929, 0.1073969566, 0.6299787005,
- ) * rgb;
- return mat3x3f(
- 0.2104542553, 1.9779984951, 0.0259040371,
- 0.7936177850, -2.4285922050, 0.7827717662,
- -0.0040720468, 0.4505937099, -0.8086757660,
- ) * (sign(lms) * pow(abs(lms), vec3f(1.0 / 3.0)));
-}
-
+// The inverse of toOklab, with the same public-domain matrices.
fn fromOklab(lab: vec3f) -> vec3f {
let lms = mat3x3f(
1.0, 1.0, 1.0,
diff --git a/src/features/fill/controls.tsx b/src/features/fill/controls.tsx
index eda51cf..a0f41f4 100644
--- a/src/features/fill/controls.tsx
+++ b/src/features/fill/controls.tsx
@@ -1,5 +1,5 @@
import { Select } from "@roprgm/ui/select";
-import { useEffect, useRef } from "react";
+import { ColorInput } from "@/components/editor/color-input";
import { useDocument } from "@/components/editor/session";
import type { Fill } from "@/core/document";
import { blends } from "@/core/image/blend";
@@ -7,14 +7,6 @@ import { setFill } from "./edits";
export function FillControls({ id, fill }: { id: string; fill: Fill }) {
const document = useDocument();
- const picker = useRef<HTMLInputElement>(null);
- // The picker streams input events while dragging; its native change event closes the gesture.
- useEffect(() => {
- const input = picker.current;
- const commit = () => document.history.commit();
- input?.addEventListener("change", commit);
- return () => input?.removeEventListener("change", commit);
- }, [document]);
return (
<section className="flex flex-col gap-3 p-3.5">
<label className="flex items-center justify-between text-secondary">
@@ -23,16 +15,10 @@ export function FillControls({ id, fill }: { id: string; fill: Fill }) {
<span className="text-foreground uppercase tabular-nums">
{fill.color}
</span>
- <input
- ref={picker}
- type="color"
- aria-label="Color"
+ <ColorInput
+ label="Color"
value={fill.color}
- className="h-6 w-9 cursor-pointer rounded surface-field p-0.5"
- onChange={(event) => {
- document.history.begin();
- setFill(document, { color: event.currentTarget.value }, id);
- }}
+ onChange={(color) => setFill(document, { color }, id)}
/>
</span>
</label>
diff --git a/src/features/layers/color-sample.ts b/src/features/layers/color-sample.ts
new file mode 100644
index 0000000..253f77f
--- /dev/null
+++ b/src/features/layers/color-sample.ts
@@ -0,0 +1,79 @@
+import { compute, type Gpu, type Target } from "vgpu";
+import type { Point } from "@/core/image/frame";
+import { weakMemo } from "@/lib/weak-memo";
+import shader from "./color-sample.wgsl";
+
+/** `GPUMapMode.READ`, which the page's WebGPU types leave out. */
+const mapRead = 1;
+/** One color and the count of texels it averages. */
+const bytes = 16;
+
+const samplePass = weakMemo((gpu: Gpu) =>
+ compute(gpu, shader, { entry: "sample" }),
+);
+
+function hex(channel: number) {
+ return Math.round(channel * 255)
+ .toString(16)
+ .padStart(2, "0");
+}
+
+/**
+ * Reads colors from images on the GPU, which averages the texels around a point so only 16 bytes
+ * cross to the CPU, through one buffer the pass writes and one the CPU maps, so sampling allocates
+ * nothing. Reads take turns, and one still waiting when a newer one comes is dropped, so a pointer
+ * that moves faster than reads complete gets its latest color.
+ */
+export function createColorSampler(gpu: Gpu) {
+ const color = gpu.device.createBuffer({
+ size: bytes,
+ usage: ["storage", "copy_src"],
+ });
+ const staging = gpu.device.createBuffer({
+ size: bytes,
+ usage: ["copy_dst", "map_read"],
+ });
+ let turn: Promise<unknown> = Promise.resolve();
+ let latest = 0;
+ async function read(image: Target, point: Point) {
+ samplePass(gpu)
+ .set({ source: image.color, params: { point }, color })
+ .dispatch(1);
+ const encoder = gpu.gpu.createCommandEncoder();
+ encoder.copyBufferToBuffer(color.gpu, 0, staging.gpu, 0, bytes);
+ gpu.gpu.queue.submit([encoder.finish()]);
+ await staging.gpu.mapAsync(mapRead, 0, bytes);
+ try {
+ const [r, g, b, count] = new Float32Array(
+ staging.gpu.getMappedRange(0, bytes).slice(0),
+ );
+ return count > 0 ? `#${hex(r)}${hex(g)}${hex(b)}` : undefined;
+ } finally {
+ staging.gpu.unmap();
+ }
+ }
+ return {
+ /**
+ * The color around `point`, a fraction of the width and height of the image `image` returns when
+ * this read's turn comes, as the screen shows it in `#rrggbb`; nothing outside the image, without
+ * one, or for a read a newer one replaced.
+ */
+ sample(image: () => Target | undefined, point: Point) {
+ const request = ++latest;
+ const result = turn.then(() => {
+ const source = image();
+ return request === latest && source ? read(source, point) : undefined;
+ });
+ turn = result.catch(() => {});
+ return result;
+ },
+ dispose() {
+ latest++;
+ // A read in flight keeps its buffers until it finishes.
+ void turn.then(() => {
+ color.dispose();
+ staging.dispose();
+ });
+ },
+ };
+}
diff --git a/src/features/layers/color-sample.wgsl b/src/features/layers/color-sample.wgsl
new file mode 100644
index 0000000..1630b5e
--- /dev/null
+++ b/src/features/layers/color-sample.wgsl
@@ -0,0 +1,36 @@
+import { display } from "../../core/image/color.wgsl";
+
+// The average of the texels around a point, as the screen shows it: sRGB, clipped to its gamut, encoded.
+struct Params {
+ // The point as a fraction of the image's width and height.
+ point: vec2f,
+}
+@group(0) @binding(0) var source: texture_2d<f32>;
+@group(0) @binding(1) var<uniform> params: Params;
+@group(0) @binding(2) var<storage, read_write> color: vec4f;
+
+fn inside(texel: vec2i, size: vec2i) -> bool {
+ return all(texel >= vec2i(0)) && all(texel < size);
+}
+
+@compute @workgroup_size(1) fn sample() {
+ let size = vec2i(textureDimensions(source));
+ let center = vec2i(floor(params.point * vec2f(size)));
+ // A point off the image picks nothing, even with texels of it in reach.
+ if (!inside(center, size)) {
+ color = vec4f(0.0);
+ return;
+ }
+ var total = vec3f(0.0);
+ var count = 0.0;
+ for (var y = -2; y <= 2; y++) {
+ for (var x = -2; x <= 2; x++) {
+ let texel = center + vec2i(x, y);
+ if (inside(texel, size)) {
+ total += textureLoad(source, texel, 0).rgb;
+ count += 1.0;
+ }
+ }
+ }
+ color = vec4f(display(total / count), count);
+}
diff --git a/src/features/layers/controls.tsx b/src/features/layers/controls.tsx
index 6d82cf5..36ae0a3 100644
--- a/src/features/layers/controls.tsx
+++ b/src/features/layers/controls.tsx
@@ -1,7 +1,13 @@
import { DragToggle } from "@roprgm/ui/drag-toggle";
import { IconButton } from "@roprgm/ui/icon-button";
import { ListItem, ListItemAction } from "@roprgm/ui/list-item";
-import { Menu, MenuContent, MenuItem, MenuTrigger } from "@roprgm/ui/menu";
+import {
+ Menu,
+ MenuContent,
+ MenuItem,
+ MenuSeparator,
+ MenuTrigger,
+} from "@roprgm/ui/menu";
import { ScrollArea } from "@roprgm/ui/scroll-area";
import { Tooltip, TooltipContent, TooltipTrigger } from "@roprgm/ui/tooltip";
import { cn } from "cn";
@@ -23,7 +29,12 @@ import {
type TreeDrop,
useTreeDragItem,
} from "@/components/ui/tree-drag";
-import { type EffectLayer, findLayer, type Layer } from "@/core/document";
+import {
+ type EffectLayer,
+ findLayer,
+ type Layer,
+ type MaskLayer,
+} from "@/core/document";
import { useShortcuts } from "@/hooks/use-shortcuts";
import { layerDrop } from "./drop";
import { deleteLayer, moveLayer, setLayer } from "./edits";
@@ -41,6 +52,16 @@ export type EffectKind = {
readonly addable: boolean;
};
+/** How a submask's row shows what it does to its parent mask. */
+const submaskOperations: Record<
+ MaskLayer["operation"],
+ { sign: string; effect: string }
+> = {
+ add: { sign: "+", effect: "Adds to" },
+ subtract: { sign: "−", effect: "Subtracts from" },
+ intersect: { sign: "∩", effect: "Intersects with" },
+};
+
function LayerThumbnail({
layer,
effects,
@@ -103,9 +124,10 @@ const LayerRow = memo(function LayerRow({
});
const dragHandle = isImage ? {} : drag.handle;
const chevronStyle = { transform: expanded ? "rotate(90deg)" : undefined };
- const isSubmask = layer.kind === "mask" && parent?.kind === "mask";
- const maskSign =
- layer.kind === "mask" && layer.operation === "subtract" ? "−" : "+";
+ const operation =
+ layer.kind === "mask" && parent?.kind === "mask"
+ ? submaskOperations[layer.operation]
+ : undefined;
const expandLabel = `${expanded ? "Collapse" : "Expand"} ${layer.name}`;
return (
<>
@@ -158,19 +180,17 @@ const LayerRow = memo(function LayerRow({
onSelect={() => onSelect(layer.id)}
dragHandle={dragHandle}
/>
- {isSubmask && (
+ {operation && (
<Tooltip>
<TooltipTrigger
render={
<span className="grid size-6 shrink-0 place-items-center text-secondary">
- {maskSign}
+ {operation.sign}
</span>
}
/>
<TooltipContent>
- {maskSign === "+"
- ? `Adds to ${parent?.name}`
- : `Subtracts from ${parent?.name}`}
+ {operation.effect} {parent?.name}
</TooltipContent>
</Tooltip>
)}
@@ -323,6 +343,13 @@ export function LayersControls({
{label}
</MenuItem>
))}
+ <MenuSeparator />
+ <MenuItem onClick={() => tool.add("luminance-range")}>
+ Luminance Range
+ </MenuItem>
+ <MenuItem onClick={() => tool.add("color-range")}>
+ Color Range
+ </MenuItem>
</MenuContent>
</Menu>
}
diff --git a/src/features/layers/gradient-overlay.tsx b/src/features/layers/gradient-overlay.tsx
index f9c542c..3b4c071 100644
--- a/src/features/layers/gradient-overlay.tsx
+++ b/src/features/layers/gradient-overlay.tsx
@@ -41,8 +41,12 @@ export function GradientOverlay({ shape }: { shape: Gradient["kind"] }) {
const item = findLayer(scene.layers, selected);
return item?.kind === "mask" ? item : undefined;
});
- /** Only gradients have guides; a brush mask keeps the deletion shortcuts. */
- const mask = layer?.mask.kind === "brush" ? undefined : layer?.mask;
+ /** Only gradients have guides; other masks keep the deletion shortcuts. */
+ const selectedMask = layer?.mask;
+ const mask =
+ selectedMask?.kind === "linear" || selectedMask?.kind === "radial"
+ ? selectedMask
+ : undefined;
const [draft, setDraft] = useState<Gradient | null>(null);
const dragging = useRef<Drag | null>(null);
const [dragCursor, setDragCursor] = useState<string>();
diff --git a/src/features/layers/mask-options.tsx b/src/features/layers/mask-options.tsx
index 9858a64..2cd5481 100644
--- a/src/features/layers/mask-options.tsx
+++ b/src/features/layers/mask-options.tsx
@@ -3,19 +3,29 @@ import { Separator } from "@roprgm/ui/separator";
import { Slider } from "@roprgm/ui/slider";
import { useDocument, useScene } from "@/components/editor/session";
import { barSlider, useBarDensity } from "@/components/editor/toolbar-density";
-import { locateLayer, type MaskLayer } from "@/core/document";
+import { isRangeMask, locateLayer, type MaskLayer } from "@/core/document";
import { setLayerMask, setMaskOperation } from "./edits";
+import { RangeOptions } from "./range-options";
-/** The selected mask's options in the canvas bar: a radial feather and a child's operation. Its overlay toggles in the stack. */
+const operations = [
+ { value: "add", label: "Add" },
+ { value: "subtract", label: "Subtract" },
+ { value: "intersect", label: "Intersect" },
+] as const;
+
+/**
+ * The selected mask's options in the canvas bar: a radial feather, a range's color and numbers, and a
+ * child's operation. Its overlay toggles in the stack.
+ */
export function MaskOptions({ layer }: { layer: MaskLayer }) {
const document = useDocument();
const density = useBarDensity();
const parent = useScene(
(scene) => locateLayer(scene.layers, layer.id)?.parent,
);
- const radial = layer.mask.kind === "radial";
+ const { mask } = layer;
const child = parent?.kind === "mask";
- if (!radial && !child) {
+ if (mask.kind !== "radial" && !isRangeMask(mask) && !child) {
return null;
}
return (
@@ -43,6 +53,7 @@ export function MaskOptions({ layer }: { layer: MaskLayer }) {
}}
/>
)}
+ {isRangeMask(mask) && <RangeOptions id={layer.id} mask={mask} />}
{child && (
<Select
raised
@@ -50,10 +61,7 @@ export function MaskOptions({ layer }: { layer: MaskLayer }) {
aria-label="Mask operation"
tooltip="Combine with the parent mask"
value={layer.operation}
- items={[
- { value: "add", label: "Add" },
- { value: "subtract", label: "Subtract" },
- ]}
+ items={operations}
onValueChange={(operation) =>
operation && setMaskOperation(document, layer.id, operation)
}
diff --git a/src/features/layers/mask-tool.tsx b/src/features/layers/mask-tool.tsx
index 475f317..3db9250 100644
--- a/src/features/layers/mask-tool.tsx
+++ b/src/features/layers/mask-tool.tsx
@@ -8,25 +8,27 @@ import {
} from "react";
import { createStore, type StoreApi } from "zustand/vanilla";
import { useDocument } from "@/components/editor/session";
-import type { Gradient, Mask } from "@/core/document";
+import type { Gradient, Mask, MaskLayer } from "@/core/document";
import { blurActive } from "@/lib/dom";
+import { defaultLuminanceRange, defaultTolerance } from "./model";
-/** Where a new mask goes: inside a mask group, adding or subtracting coverage. */
+/** Where a new mask goes: inside a mask group, combined with its coverage, or else on top. */
export type Nesting = {
parentId?: string;
- operation: "add" | "subtract";
+ operation: MaskLayer["operation"];
};
-type Pending = Nesting & { shape: Mask["kind"] };
+/** The masks a tool on the canvas draws or picks; a luminance range needs none. */
+type DrawnShape = Exclude<Mask["kind"], "luminance-range">;
+type Pending = Nesting & { shape: Exclude<DrawnShape, "color-range"> };
type OverlayChoice = "auto" | "shown" | "hidden";
const MaskTool = createContext<{
- /** Chosen from a mask's Add or Subtract menu; the next mask of that shape goes there. */
+ /** Chosen from a menu; the next mask of that shape goes there. */
pending: Pending | null;
- add: (
- parentId: string,
- operation: Nesting["operation"],
- shape: Mask["kind"],
- ) => void;
+ /**
+ * Starts a range mask at once, or chooses where the next brush or gradient goes.
+ */
+ add: (shape: Mask["kind"], nesting?: Nesting) => void;
/** Adds the mask where `nesting` says, else where a pending choice says, else on top. */
create: (mask: Mask, nesting?: Nesting) => void;
/**
@@ -37,7 +39,10 @@ const MaskTool = createContext<{
showOverlay: (shown: boolean) => void;
/** A gradient being drawn, not yet in the scene, tinted like a mask. */
draft: StoreApi<Gradient | null>;
- /** Enters editing with the tool of a shape, or leaves it: the layer stays selected, its guides go. */
+ /**
+ * Enters editing with the tool of a shape, or leaves it: the layer stays selected, its guides go.
+ * A luminance range has no tool, so it leaves too.
+ */
edit: (shape?: Mask["kind"]) => void;
} | null>(null);
@@ -57,8 +62,8 @@ export function MaskToolProvider({
}: {
children: ReactNode;
onCreate: (mask: Mask, nesting: Nesting) => void;
- /** Activates the tool that draws the shape. */
- onTool?: (shape: Mask["kind"]) => void;
+ /** Activates the tool that draws or picks the shape. */
+ onTool?: (shape: DrawnShape) => void;
/** Returns to the tool without a mask canvas. */
onDone?: () => void;
}) {
@@ -71,12 +76,35 @@ export function MaskToolProvider({
() => document.selection.subscribe(() => setPending(null)),
[document],
);
+ function edit(shape?: Mask["kind"]) {
+ setPending(null);
+ // Keys after entering or leaving belong to the canvas, not to the row or tab that asked.
+ blurActive();
+ if (shape && shape !== "luminance-range") {
+ onTool?.(shape);
+ } else {
+ onDone?.();
+ }
+ }
return (
<MaskTool
value={{
pending,
- add: (parentId, operation, shape) => {
- setPending({ parentId, operation, shape });
+ add: (shape, nesting = { operation: "add" }) => {
+ if (shape === "luminance-range") {
+ edit();
+ onCreate(defaultLuminanceRange, nesting);
+ return;
+ }
+ if (shape === "color-range") {
+ onCreate(
+ { kind: "color-range", color: null, tolerance: defaultTolerance },
+ nesting,
+ );
+ edit(shape);
+ return;
+ }
+ setPending({ ...nesting, shape });
onTool?.(shape);
},
create: (mask, nesting) => {
@@ -88,16 +116,7 @@ export function MaskToolProvider({
overlay,
showOverlay: (shown) => setOverlay(shown ? "shown" : "hidden"),
draft,
- edit: (shape) => {
- setPending(null);
- // Keys after entering or leaving belong to the canvas, not to the row or tab that asked.
- blurActive();
- if (shape) {
- onTool?.(shape);
- } else {
- onDone?.();
- }
- },
+ edit,
}}
>
{children}
diff --git a/src/features/layers/menu.tsx b/src/features/layers/menu.tsx
index 32a2bdf..a3db8b9 100644
--- a/src/features/layers/menu.tsx
+++ b/src/features/layers/menu.tsx
@@ -116,13 +116,16 @@ const shapes = [
["linear", "Linear gradient"],
["radial", "Radial gradient"],
["brush", "Brush"],
+ ["luminance-range", "Luminance range"],
+ ["color-range", "Color range"],
] as const;
const nestings = [
["add", "Add to mask"],
["subtract", "Subtract from mask"],
+ ["intersect", "Intersect with mask"],
] as const;
-/** Chooses the shape of the next mask and nests it inside this one, adding or subtracting coverage. */
+/** Chooses the shape of the next mask and nests it inside this one, combined with its coverage. */
function NestingItems({ layer }: { layer: MaskLayer }) {
const document = useDocument();
const tool = useMaskTool();
@@ -139,7 +142,7 @@ function NestingItems({ layer }: { layer: MaskLayer }) {
disabled={shape === "brush" && full}
onClick={() => {
document.selectLayer(layer.id);
- tool.add(layer.id, operation, shape);
+ tool.add(shape, { parentId: layer.id, operation });
}}
>
{name}
diff --git a/src/features/layers/model.ts b/src/features/layers/model.ts
index 784720b..132c0c5 100644
--- a/src/features/layers/model.ts
+++ b/src/features/layers/model.ts
@@ -1,9 +1,15 @@
import { z } from "zod/mini";
-import type { Mask, MaskLayer } from "@/core/document";
+import type {
+ ColorRange,
+ LuminanceRange,
+ Mask,
+ MaskLayer,
+} from "@/core/document";
import { strokeSchema } from "@/core/document/brush";
-import { point, unit } from "@/lib/parse";
+import { hexColor, point, range, unit } from "@/lib/parse";
const positive = z.number().check(z.positive());
+const percent = range(0, 100);
export const maskSchema = z.discriminatedUnion("kind", [
z
@@ -26,13 +32,43 @@ export const maskSchema = z.discriminatedUnion("kind", [
raster: z.optional(z.string().check(z.minLength(1))),
strokes: z.array(strokeSchema),
}),
+ z
+ .object({
+ kind: z.literal("luminance-range"),
+ low: percent,
+ high: percent,
+ smoothness: percent,
+ })
+ .check(
+ z.refine(
+ ({ low, high }) => low <= high,
+ "A luminance range needs low at or below high",
+ ),
+ ),
+ z.object({
+ kind: z.literal("color-range"),
+ color: z.nullable(hexColor),
+ tolerance: percent,
+ }),
]) satisfies z.ZodMiniType<Mask>;
export const maskOperation = z.enum([
"add",
"subtract",
+ "intersect",
]) satisfies z.ZodMiniType<MaskLayer["operation"]>;
+/** A new luminance range: the brighter half of the tones. */
+export const defaultLuminanceRange: LuminanceRange = {
+ kind: "luminance-range",
+ low: 50,
+ high: 100,
+ smoothness: 25,
+};
+
+/** A new color range's tolerance; its color comes from the photo. */
+export const defaultTolerance: ColorRange["tolerance"] = 30;
+
export const layerSettings = z.object({
name: z.string().check(z.trim(), z.minLength(1)),
visible: z.boolean(),
diff --git a/src/features/layers/range-options.tsx b/src/features/layers/range-options.tsx
new file mode 100644
index 0000000..0839620
--- /dev/null
+++ b/src/features/layers/range-options.tsx
@@ -0,0 +1,116 @@
+import { IconButton } from "@roprgm/ui/icon-button";
+import { Slider } from "@roprgm/ui/slider";
+import { ColorInput } from "@/components/editor/color-input";
+import type { Parameter } from "@/components/editor/parameter";
+import { useDocument } from "@/components/editor/session";
+import { barSlider, useBarDensity } from "@/components/editor/toolbar-density";
+import { EyedropperIcon } from "@/components/icons/eyedropper";
+import type { EditorDocument, RangeMask } from "@/core/document";
+import { setLayerMask } from "./edits";
+import { useMaskTool } from "./mask-tool";
+import { defaultLuminanceRange, defaultTolerance } from "./model";
+
+const tones = ["#000000", "#ffffff"];
+
+/** A range's numbers: its tones from low to high and their smoothness, or a color's tolerance. */
+function rangeParameters(
+ document: EditorDocument,
+ id: string,
+ mask: RangeMask,
+): Parameter[] {
+ const percent = { min: 0, max: 100 };
+ if (mask.kind === "color-range") {
+ return [
+ {
+ ...percent,
+ id: "tolerance",
+ label: "Tolerance",
+ value: mask.tolerance,
+ defaultValue: defaultTolerance,
+ onChange: (tolerance) =>
+ setLayerMask(document, id, { ...mask, tolerance }),
+ },
+ ];
+ }
+ const { low, high, smoothness } = defaultLuminanceRange;
+ // Either end pushes the other along rather than crossing it.
+ return [
+ {
+ ...percent,
+ id: "low",
+ label: "Low",
+ value: mask.low,
+ stops: tones,
+ defaultValue: low,
+ onChange: (value) =>
+ setLayerMask(document, id, {
+ ...mask,
+ low: value,
+ high: Math.max(mask.high, value),
+ }),
+ },
+ {
+ ...percent,
+ id: "high",
+ label: "High",
+ value: mask.high,
+ stops: tones,
+ defaultValue: high,
+ onChange: (value) =>
+ setLayerMask(document, id, {
+ ...mask,
+ high: value,
+ low: Math.min(mask.low, value),
+ }),
+ },
+ {
+ ...percent,
+ id: "smoothness",
+ label: "Smoothness",
+ value: mask.smoothness,
+ defaultValue: smoothness,
+ onChange: (value) =>
+ setLayerMask(document, id, { ...mask, smoothness: value }),
+ },
+ ];
+}
+
+/** A range mask's options in the canvas bar: its color, chosen or picked from the photo, and its numbers. */
+export function RangeOptions({ id, mask }: { id: string; mask: RangeMask }) {
+ const document = useDocument();
+ const density = useBarDensity();
+ const tool = useMaskTool();
+ return (
+ <>
+ {mask.kind === "color-range" && (
+ <span className="flex items-center gap-1">
+ {mask.color !== null && (
+ <ColorInput
+ label="Range color"
+ value={mask.color}
+ onChange={(color) =>
+ setLayerMask(document, id, { ...mask, color })
+ }
+ />
+ )}
+ <IconButton
+ label="Pick a color from the photo"
+ size="icon-sm"
+ className="rounded-full"
+ onClick={() => tool.edit("color-range")}
+ >
+ <EyedropperIcon className="size-4.5" />
+ </IconButton>
+ </span>
+ )}
+ {rangeParameters(document, id, mask).map(({ id, ...parameter }) => (
+ <Slider
+ key={id}
+ {...parameter}
+ valueWidth={3}
+ variant={barSlider(density)}
+ />
+ ))}
+ </>
+ );
+}
diff --git a/src/features/layers/range-picker.tsx b/src/features/layers/range-picker.tsx
new file mode 100644
index 0000000..d380a08
--- /dev/null
+++ b/src/features/layers/range-picker.tsx
@@ -0,0 +1,239 @@
+import { type PointerEvent, useEffect, useRef, useState } from "react";
+import { useGpu } from "vgpu-react";
+import { useStore } from "zustand";
+import { CanvasHint } from "@/components/editor/canvas-hint";
+import { useDocumentMapping } from "@/components/editor/mapping";
+import { useRenderer } from "@/components/editor/pipeline";
+import { useDocument, useScene } from "@/components/editor/session";
+import { useViewport } from "@/components/editor/viewport";
+import { eyedropperCursor } from "@/components/icons/eyedropper-cursor";
+import { findLayer, locateLayer } from "@/core/document";
+import { useDisposable } from "@/hooks/use-disposable";
+import { useShortcuts } from "@/hooks/use-shortcuts";
+import { createColorSampler } from "./color-sample";
+import { setLayerMask } from "./edits";
+import { useMaskTool } from "./mask-tool";
+
+type Drag = {
+ pointer: number;
+ /** The viewport bounds measured once; pointer capture keeps them valid for the drag. */
+ box: DOMRect;
+ target: string;
+ opened: boolean;
+ /** Whether the drag was cancelled, so colors still to land change nothing. */
+ cancelled: boolean;
+ /** The latest color to land, which the drag waits for before it ends. */
+ landed: Promise<void>;
+};
+
+/**
+ * Picks colors from the photo for the selected color range; a drag is one edit.
+ * Colors come from the image below the range's mask group, the one it selects from, so its own edit
+ * never feeds back. Enter or Escape leaves.
+ */
+export function RangePicker() {
+ const gpu = useGpu();
+ const document = useDocument();
+ const renderer = useRenderer();
+ const camera = useViewport();
+ const mapping = useDocumentMapping();
+ const tool = useMaskTool();
+ const sampler = useDisposable(() => createColorSampler(gpu), [gpu]);
+ const selected = useStore(document.selection, (state) => state.layerId);
+ const editing = useScene((scene) => {
+ const layer = findLayer(scene.layers, selected);
+ return layer?.kind === "mask" && layer.mask.kind === "color-range";
+ });
+ const group = useScene((scene) => {
+ const parent = locateLayer(scene.layers, selected)?.parent;
+ return parent?.kind === "mask" ? parent.id : selected;
+ });
+ const size = document.resources.get(
+ useScene((scene) => scene.layers[0].source),
+ ).image.size;
+ const [error, setError] = useState("");
+ const live = useRef(true);
+ useEffect(() => {
+ if (!editing) {
+ tool.edit();
+ return;
+ }
+ document.preview.setState({ rangeSource: group });
+ return () => document.preview.setState({ rangeSource: undefined });
+ }, [document, editing, group, tool.edit]);
+ const drag = useRef<Drag | null>(null);
+ const inFlight = useRef(new Set<Drag>());
+ /** The previous drag's end, which a new drag's colors wait for so the two edits never overlap. */
+ const ended = useRef<Promise<void>>(Promise.resolve());
+ function cancelDrag(current: Drag) {
+ current.cancelled = true;
+ if (current.opened) {
+ current.opened = false;
+ document.history.cancel();
+ }
+ }
+ /** Gives the drag's color range a color, while it is one. */
+ function recolor(id: string, color: string) {
+ const layer = findLayer(document.scene.getState().layers, id);
+ if (layer?.kind === "mask" && layer.mask.kind === "color-range") {
+ setLayerMask(document, id, { ...layer.mask, color });
+ }
+ }
+ /** Picks the color under the pointer and waits for the previous pick to land. */
+ function pick(current: Drag, event: PointerEvent) {
+ const [x, y] = mapping.toDocument(
+ event.clientX,
+ event.clientY,
+ current.box,
+ );
+ const image = () => renderer.rangeSource(group);
+ const color = sampler.sample(image, [x / size[0], y / size[1]]);
+ current.landed = Promise.all([current.landed, color])
+ .then(([, color]) => {
+ if (!color || current.cancelled || document.closed) {
+ return;
+ }
+ if (document.selection.getState().layerId !== current.target) {
+ cancelDrag(current);
+ return;
+ }
+ if (!current.opened) {
+ if (document.history.status.getState().editing) {
+ current.cancelled = true;
+ if (live.current) {
+ setError("Finish the current edit before picking a color.");
+ }
+ return;
+ }
+ current.opened = document.history.begin();
+ }
+ recolor(current.target, color);
+ })
+ .catch(() => {
+ cancelDrag(current);
+ if (live.current) {
+ setError("Couldn't pick a color. Try again.");
+ }
+ });
+ }
+ function end(cancel: boolean) {
+ const current = drag.current;
+ if (!current) {
+ return;
+ }
+ drag.current = null;
+ if (cancel) {
+ cancelDrag(current);
+ }
+ ended.current = current.landed.then(() => {
+ inFlight.current.delete(current);
+ if (current.opened) {
+ current.opened = false;
+ document.history.commit();
+ }
+ });
+ }
+ useEffect(() => {
+ live.current = true;
+ const selection = document.selection.subscribe(({ layerId }) => {
+ for (const current of inFlight.current) {
+ if (current.target !== layerId) {
+ cancelDrag(current);
+ }
+ }
+ });
+ const history = document.history.status.subscribe(({ editing }) => {
+ if (!editing) {
+ for (const current of inFlight.current) {
+ if (current.opened) {
+ current.opened = false;
+ current.cancelled = true;
+ }
+ }
+ }
+ });
+ return () => {
+ live.current = false;
+ selection();
+ history();
+ end(true);
+ for (const current of inFlight.current) {
+ cancelDrag(current);
+ }
+ };
+ }, [document]);
+ useShortcuts({
+ escape: () => (drag.current ? end(true) : tool.edit()),
+ enter: () => {
+ if (!drag.current) {
+ tool.edit();
+ }
+ },
+ });
+ function start(event: PointerEvent<HTMLDivElement>) {
+ const box = camera.ref.current?.getBoundingClientRect();
+ if (
+ event.button !== 0 ||
+ !event.isPrimary ||
+ !box ||
+ !editing ||
+ drag.current
+ ) {
+ return;
+ }
+ event.stopPropagation();
+ event.currentTarget.setPointerCapture(event.pointerId);
+ const current: Drag = {
+ pointer: event.pointerId,
+ box,
+ target: selected,
+ opened: false,
+ cancelled: false,
+ landed: ended.current,
+ };
+ drag.current = current;
+ inFlight.current.add(current);
+ setError("");
+ pick(current, event);
+ }
+ function move(event: PointerEvent<HTMLDivElement>) {
+ const current = drag.current;
+ if (current?.pointer === event.pointerId) {
+ pick(current, event);
+ }
+ }
+ function finish(event: PointerEvent<HTMLDivElement>) {
+ if (drag.current?.pointer !== event.pointerId) {
+ return;
+ }
+ event.currentTarget.releasePointerCapture(event.pointerId);
+ end(false);
+ }
+ return (
+ <div
+ role="application"
+ aria-label="Color range canvas"
+ className="absolute inset-0 touch-none data-[pan=true]:pointer-events-none"
+ style={{ cursor: eyedropperCursor }}
+ data-pan={camera.panMode}
+ onDoubleClick={(event) => event.stopPropagation()}
+ onPointerDown={start}
+ onPointerMove={move}
+ onPointerUp={finish}
+ onPointerCancel={(event) => {
+ if (drag.current?.pointer === event.pointerId) {
+ end(true);
+ }
+ }}
+ onLostPointerCapture={(event) => {
+ if (drag.current?.pointer === event.pointerId) {
+ end(false);
+ }
+ }}
+ >
+ <CanvasHint>
+ {error || "Click or drag over the photo to pick the color to select"}
+ </CanvasHint>
+ </div>
+ );
+}
diff --git a/src/features/layers/thumbnails.tsx b/src/features/layers/thumbnails.tsx
index b9528a2..8c3a451 100644
--- a/src/features/layers/thumbnails.tsx
+++ b/src/features/layers/thumbnails.tsx
@@ -4,7 +4,13 @@ import { useGpu } from "vgpu-react";
import { CoverageThumbnail } from "@/components/editor/coverage-thumbnail";
import { useDocument, useScene } from "@/components/editor/session";
import { Icon } from "@/components/icons/icon";
-import type { MaskLayer } from "@/core/document";
+import {
+ type Gradient,
+ isRangeMask,
+ type Mask,
+ type MaskLayer,
+ maskModifiers,
+} from "@/core/document";
import { renderBitmap } from "@/core/renderer";
import { MaskFill } from "./mask-fill";
@@ -61,40 +67,81 @@ export function ImageThumbnail() {
);
}
-/** A mask's coverage from the renderer's raster; an unpainted brush shows its tool and a gradient draws itself. */
-export function MaskThumbnail({ layer }: { layer: MaskLayer }) {
+function GradientThumbnail({ mask }: { mask: Gradient }) {
const id = useId();
const document = useDocument();
const sourceId = useScene((scene) => scene.layers[0].source);
- const size = document.resources.get(sourceId).image.size;
- const fallback =
- layer.mask.kind === "brush" ? (
- <span
- role="img"
- aria-label="Empty brush thumbnail"
- className={`grid place-items-center text-secondary ${frame}`}
- >
- <Icon className="size-4">
- <path d="M10 14a3 3 0 0 1-3 3c-1.5 0-3-1-3-1s2-1 2-2.5c0-1.5 1-2.5 2.5-2.5M11 13l7-7a1.4 1.4 0 0 0-2-2l-7 7" />
- </Icon>
- </span>
- ) : (
- <svg
- aria-label="Gradient mask thumbnail"
- role="img"
- viewBox={`0 0 ${size[0]} ${size[1]}`}
- className={frame}
- >
- <defs>
- <MaskFill id={id} mask={layer.mask} />
- </defs>
- <rect width={size[0]} height={size[1]} fill={`url(#${id})`} />
- </svg>
- );
+ const [width, height] = document.resources.get(sourceId).image.size;
+ return (
+ <svg
+ aria-label="Gradient mask thumbnail"
+ role="img"
+ viewBox={`0 0 ${width} ${height}`}
+ className={frame}
+ >
+ <defs>
+ <MaskFill id={id} mask={mask} />
+ </defs>
+ <rect width={width} height={height} fill={`url(#${id})`} />
+ </svg>
+ );
+}
+
+/** What a mask shows until it has coverage: an unpainted brush its tool, a gradient itself, a range what it selects. */
+function MaskFallback({ mask }: { mask: Mask }) {
+ switch (mask.kind) {
+ case "brush":
+ return (
+ <span
+ role="img"
+ aria-label="Empty brush thumbnail"
+ className={`grid place-items-center text-secondary ${frame}`}
+ >
+ <Icon className="size-4">
+ <path d="M10 14a3 3 0 0 1-3 3c-1.5 0-3-1-3-1s2-1 2-2.5c0-1.5 1-2.5 2.5-2.5M11 13l7-7a1.4 1.4 0 0 0-2-2l-7 7" />
+ </Icon>
+ </span>
+ );
+ case "luminance-range":
+ return (
+ <span
+ role="img"
+ aria-label="Luminance range thumbnail"
+ className={`bg-linear-to-r from-black to-white ${frame}`}
+ />
+ );
+ case "color-range":
+ return (
+ <span
+ role="img"
+ aria-label={
+ mask.color === null
+ ? "Unpicked color range thumbnail"
+ : "Color range thumbnail"
+ }
+ className={frame}
+ style={{ backgroundColor: mask.color ?? undefined }}
+ />
+ );
+ default:
+ return <GradientThumbnail mask={mask} />;
+ }
+}
+
+/**
+ * A mask's coverage from the renderer's raster, or its fallback. A range selects from the image
+ * below, so any edit to the scene can change a mask that holds one.
+ */
+export function MaskThumbnail({ layer }: { layer: MaskLayer }) {
+ const ranged = [layer, ...maskModifiers(layer)].some(({ mask }) =>
+ isRangeMask(mask),
+ );
+ const version = useScene((scene) => (ranged ? scene : layer));
+ const fallback = <MaskFallback mask={layer.mask} />;
return (
<CoverageThumbnail
id={layer.id}
- version={layer}
+ version={version}
label="Mask thumbnail"
fallback={fallback}
/>
diff --git a/src/features/paint/colors.tsx b/src/features/paint/colors.tsx
index f4e9b7d..32b64f1 100644
--- a/src/features/paint/colors.tsx
+++ b/src/features/paint/colors.tsx
@@ -4,6 +4,7 @@ import { cn } from "cn";
import { defaultColors, useBrushTool } from "@/components/editor/brush-tool";
import { EyedropperIcon } from "@/components/icons/eyedropper";
import { SwapIcon } from "@/components/icons/swap";
+import { ColorSwatch } from "@/components/ui/color-swatch";
import { hexColor } from "@/lib/parse";
/** The brush's primary and secondary colors, and the actions Photoshop keys to X, D, and I. */
@@ -50,21 +51,12 @@ function Swatch({
<Tooltip>
<TooltipTrigger
render={
- <label
- className={cn(
- "absolute size-4.5 cursor-pointer rounded-sm surface-control focus-ring",
- className,
- )}
- style={{ backgroundColor: value }}
- >
- <input
- type="color"
- aria-label={label}
- value={value}
- className="sr-only"
- onChange={(event) => onChange(event.currentTarget.value)}
- />
- </label>
+ <ColorSwatch
+ label={label}
+ value={value}
+ className={cn("absolute size-4.5", className)}
+ onChange={onChange}
+ />
}
/>
<TooltipContent side={side}>{label}</TooltipContent>
diff --git a/tests/brush.test.ts b/tests/brush.test.ts
index 8f84689..1c91f68 100644
--- a/tests/brush.test.ts
+++ b/tests/brush.test.ts
@@ -1,6 +1,6 @@
import { expect, mock, test } from "bun:test";
import { init, target } from "vgpu/mock";
-import { createImageLayer, createMask } from "@/app/editor/layers";
+import { createImageLayer, createLayer, createMask } from "@/app/editor/layers";
import { createEditorRenderer } from "@/app/editor/renderer";
import type { BrushStroke, StrokePoint } from "@/core/document";
import { createDocument, createResources, findLayer } from "@/core/document";
@@ -12,9 +12,11 @@ import {
addLayer,
deleteLayer,
extendStroke,
+ moveLayer,
paintStroke,
setLayer,
setLayerMask,
+ setMaskOperation,
} from "@/features/layers/edits";
import { defaultGradient } from "@/features/layers/gradient";
@@ -154,6 +156,15 @@ test("brush strokes stamp incrementally, replay after undo, and render a proxy d
expect(layer.mask.strokes).toHaveLength(1);
expect(layer.mask.strokes[0].points).toHaveLength(2);
}
+ document.history.undo();
+ await render();
+ expect(renderer.coverage(mask)).toBeUndefined();
+ expect(
+ renderer.inspect().rasters.some((raster) => raster.id === mask),
+ ).toBe(true);
+ document.history.redo();
+ await render();
+ expect(renderer.coverage(mask)).toBeDefined();
// A brush subtracting from a gradient turns the whole mask into a raster.
const gradient = addLayer(document, createMask(defaultGradient([64, 32])));
setAdjustments(document, { exposure: -1 }, gradient);
@@ -185,15 +196,40 @@ test("brush strokes stamp incrementally, replay after undo, and render a proxy d
expect(renderer.inspect().passes).toContain(
`layer/${gradient}/raster-input`,
);
- // The child keeps its own coverage for its preview; the gradient combines it into a second texture.
+ // The child keeps its own coverage for its preview; the graph folds it into the gradient's.
expect(renderer.inspect().rasters.map((raster) => raster.id)).toEqual([
mask,
child,
"stroke view",
- `${gradient}/group`,
"stroke buffer",
]);
+ expect(renderer.inspect().passes).toEqual(
+ expect.arrayContaining([
+ `mask/${gradient}/gradient`,
+ `mask/${child}/combine`,
+ ]),
+ );
+ expect(renderer.coverage(child)?.target.size).toEqual([32, 16]);
+ expect(renderer.coverage(gradient)?.target.size).toEqual([32, 16]);
+ setLayer(document, child, { visible: false });
+ await render();
expect(renderer.coverage(child)?.target.size).toEqual([32, 16]);
+ expect(renderer.inspect().passes).not.toContain(`mask/${child}/combine`);
+ setLayer(document, child, { visible: true, opacity: 0 });
+ await render();
+ expect(renderer.coverage(child)?.target.size).toEqual([32, 16]);
+ setLayerMask(document, child, { kind: "brush", strokes: [] });
+ await render();
+ expect(renderer.coverage(child)).toBeUndefined();
+ document.history.undo();
+ setLayer(document, child, { opacity: 1 });
+ // Hiding a group bypasses its effect, but preserves the combined coverage shown in its row.
+ setLayer(document, gradient, { visible: false });
+ await render();
+ expect(renderer.coverage(gradient)?.target.size).toEqual([32, 16]);
+ expect(renderer.inspect().passes).toContain(`mask/${child}/combine`);
+ expect(renderer.inspect().passes).not.toContain(`layer/${gradient}/raster`);
+ setLayer(document, gradient, { visible: true });
// Erasing inside the child stamps its own raster only, and the group recombines.
const stampedBefore = renderer.inspect().stamped;
paintStroke(document, child, { ...stroke, mode: "erase" });
@@ -225,3 +261,73 @@ test("brush strokes stamp incrementally, replay after undo, and render a proxy d
gpu.dispose();
}
});
+
+test("a brush yet to paint takes no part in its group", async () => {
+ const gpu = await init();
+ const source = createImageSource(
+ target(gpu, { size: [64, 32], format: "rgba16float" }),
+ );
+ const resources = createResources();
+ const sourceId = resources.add(new File([], "photo.png"), source);
+ const document = createDocument(
+ {
+ frame: imageFrame(source.image.size),
+ layers: [createImageLayer(sourceId, "Photo")],
+ },
+ resources,
+ );
+ const renderer = createEditorRenderer(gpu, source);
+ const passes = async () => {
+ await renderer.update(document.scene.getState());
+ return renderer.inspect().passes;
+ };
+ try {
+ const brush = addLayer(
+ document,
+ createMask({ kind: "brush", strokes: [] }),
+ );
+ setAdjustments(document, { exposure: 1 }, brush);
+ const gradient = addLayer(
+ document,
+ createMask(defaultGradient([64, 32]), "subtract"),
+ { inside: brush },
+ );
+ // Taking away from nothing leaves nothing, so the mask is bypassed.
+ expect(await passes()).toEqual([]);
+ // Adding to it starts from nothing covered.
+ setMaskOperation(document, gradient, "add");
+ expect(await passes()).toEqual(
+ expect.arrayContaining([
+ `mask/${brush}/empty`,
+ `mask/${gradient}/combine`,
+ `layer/${brush}/raster`,
+ ]),
+ );
+ // Intersecting a gradient, it leaves the gradient whole until it paints.
+ const shaped = addLayer(document, createMask(defaultGradient([64, 32])));
+ setAdjustments(document, { exposure: 1 }, shaped);
+ const child = addLayer(
+ document,
+ createMask({ kind: "brush", strokes: [] }, "intersect"),
+ { inside: shaped },
+ );
+ expect(await passes()).toContain(`layer/${shaped}/mix`);
+ paintStroke(document, child, stroke);
+ expect(await passes()).toEqual(
+ expect.arrayContaining([
+ `mask/${shaped}/gradient`,
+ `mask/${child}/combine`,
+ `layer/${shaped}/raster`,
+ ]),
+ );
+ const effect = addLayer(document, createLayer("exposure"));
+ moveLayer(document, child, 0, effect);
+ setLayer(document, effect, { visible: false });
+ await passes();
+ expect(renderer.coverage(child)?.target.size).toEqual([32, 16]);
+ } finally {
+ renderer.dispose();
+ document.dispose();
+ gpu.dispose();
+ }
+});
diff --git a/tests/commands.test.ts b/tests/commands.test.ts
index 8ccc14d..bf71f5e 100644
--- a/tests/commands.test.ts
+++ b/tests/commands.test.ts
@@ -3,7 +3,13 @@ import { init, target } from "vgpu/mock";
import { createControls } from "@/app/controls";
import { createImageLayer } from "@/app/editor/layers";
import { createWorkspace } from "@/app/workspace";
-import { createDocument, createResources } from "@/core/document";
+import {
+ type ColorRange,
+ createDocument,
+ createResources,
+ findLayer,
+ type LuminanceRange,
+} from "@/core/document";
import { createImageSource } from "@/core/image";
import { imageFrame } from "@/core/image/frame";
@@ -65,3 +71,65 @@ test("commands validate their input, return the layer they edit, and reset as on
run({ type: "undo" });
expect(document.scene.getState()).toEqual(edited);
});
+
+test("range masks select tones or a color, validate their bounds, and intersect other masks", async () => {
+ const gpu = await init();
+ const source = createImageSource(
+ target(gpu, { size: [32, 16], format: "rgba16float" }),
+ );
+ const resources = createResources();
+ const sourceId = resources.add(new File([], "photo.png"), source);
+ const document = createDocument(
+ {
+ frame: imageFrame(source.image.size),
+ layers: [createImageLayer(sourceId, "Photo")],
+ },
+ resources,
+ );
+ const workspace = createWorkspace();
+ await workspace.open("photo.png", async () => document);
+ const api = createControls(gpu, workspace);
+ const layer = (id: string) => findLayer(document.scene.getState().layers, id);
+
+ const shadows: LuminanceRange = {
+ kind: "luminance-range",
+ low: 0,
+ high: 30,
+ smoothness: 10,
+ };
+ const { layerId = "" } = api.run({
+ type: "add-mask",
+ mask: shadows,
+ adjustments: { exposure: 1 },
+ });
+ expect(layer(layerId)).toMatchObject({
+ name: "Luminance Range",
+ mask: shadows,
+ adjustments: { exposure: 1 },
+ });
+ expect(() =>
+ api.run({ type: "add-mask", mask: { ...shadows, low: 40 } }),
+ ).toThrow("A luminance range needs low at or below high");
+
+ // A color range inside the luminance range keeps only the shadows of that color.
+ const blue: ColorRange = {
+ kind: "color-range",
+ color: "#6FA8DC",
+ tolerance: 30,
+ };
+ const child = api.addLayer("mask", { inside: layerId });
+ api.setLayerMask(child, blue);
+ api.setMaskOperation(child, "intersect");
+ expect(layer(child)).toMatchObject({
+ mask: { ...blue, color: "#6fa8dc" },
+ operation: "intersect",
+ });
+ api.setLayerMask(child, { ...blue, color: null });
+ expect(layer(child)).toMatchObject({
+ mask: { kind: "color-range", color: null },
+ });
+ expect(() =>
+ Reflect.apply(api.setMaskOperation, undefined, [child, "union"]),
+ ).toThrow("Invalid mask operation");
+ expect(document.history.status.getState().undoCount).toBe(5);
+});
diff --git a/tests/mask-range.e2e.ts b/tests/mask-range.e2e.ts
new file mode 100644
index 0000000..227d29c
--- /dev/null
+++ b/tests/mask-range.e2e.ts
@@ -0,0 +1,233 @@
+import type { Page } from "@playwright/test";
+import { expect, test } from "./fixtures";
+import { readImage } from "./images";
+import { box } from "./pointer";
+
+// Dark and light grays over blue and orange, whose lightness falls between them.
+const quadrants = Buffer.from(
+ `<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
+ <rect width="100" height="100" fill="#303030"/>
+ <rect x="100" width="100" height="100" fill="#d0d0d0"/>
+ <rect y="100" width="100" height="100" fill="#2060d0"/>
+ <rect x="100" y="100" width="100" height="100" fill="#e07020"/>
+ </svg>`,
+);
+
+async function open(page: Page) {
+ await page.goto("/");
+ await page.locator('input[type="file"]').setInputFiles({
+ name: "quadrants.svg",
+ mimeType: "image/svg+xml",
+ buffer: quadrants,
+ });
+ await expect(
+ page.getByRole("textbox", { name: "Exposure", exact: true }),
+ ).toHaveValue("0.00");
+}
+
+/** The exported dark, light, blue, and orange quadrants. */
+async function quadrantColors(page: Page) {
+ const { samples } = await readImage(page, undefined, [
+ [50, 50],
+ [150, 50],
+ [50, 150],
+ [150, 150],
+ ]);
+ const [dark, light, blue, orange] = samples ?? [];
+ return { dark, light, blue, orange };
+}
+
+async function setField(page: Page, name: string, value: string) {
+ const field = page.getByRole("textbox", { name, exact: true });
+ await field.fill(value);
+ await field.press("Enter");
+}
+
+async function addEffect(page: Page, name: string) {
+ await page.getByRole("button", { name: "Add effect", exact: true }).click();
+ await page.getByRole("menuitem", { name, exact: true }).click();
+}
+
+test("luminance and color range masks select tones and a picked color", async ({
+ page,
+}) => {
+ await open(page);
+ const original = await quadrantColors(page);
+
+ await addEffect(page, "Luminance Range");
+ await expect(
+ page.getByRole("button", { name: "Mask overlay", exact: true }),
+ ).toHaveAttribute("aria-pressed", "true");
+ await setField(page, "Low", "75");
+ await setField(page, "Smoothness", "5");
+ await setField(page, "Exposure", "-2");
+ const darkened = await quadrantColors(page);
+ expect(darkened.light[0]).toBeLessThan(original.light[0] - 60);
+ expect({ ...darkened, light: original.light }).toEqual(original);
+
+ await addEffect(page, "Color Range");
+ const picker = page.getByRole("application", { name: "Color range canvas" });
+ await expect(picker).toContainText("drag over the photo to pick the color");
+ const canvas = await box(picker);
+ // Just past the center, on the orange and blue quadrants, whatever the zoom.
+ const orange = [
+ canvas.x + canvas.width / 2 + 20,
+ canvas.y + canvas.height / 2 + 20,
+ ];
+ const blue = [
+ canvas.x + canvas.width / 2 - 20,
+ canvas.y + canvas.height / 2 + 20,
+ ];
+ const color = page.getByLabel("Range color", { exact: true });
+ await page.mouse.click(orange[0], orange[1]);
+ await expect(color).toHaveValue("#e07020");
+ await page.keyboard.press("Escape");
+ await expect(picker).toHaveCount(0);
+ await setField(page, "Saturation", "-100");
+ const gray = await quadrantColors(page);
+ expect(Math.abs(gray.orange[0] - gray.orange[2])).toBeLessThan(12);
+ expect({ ...gray, orange: darkened.orange }).toEqual(darkened);
+
+ // Picking again reads the photo below the mask, so its own edit doesn't change the color.
+ await page
+ .getByRole("button", { name: "Pick a color from the photo", exact: true })
+ .click();
+ await page.mouse.click(orange[0], orange[1]);
+ await expect(color).toHaveValue("#e07020");
+ // A drag keeps picking, as one edit.
+ await page.mouse.move(orange[0], orange[1]);
+ await page.mouse.down();
+ await page.mouse.move(blue[0], blue[1], { steps: 4 });
+ await page.mouse.up();
+ await expect(color).toHaveValue("#2060d0");
+ const recolored = await quadrantColors(page);
+ expect(Math.abs(recolored.blue[0] - recolored.blue[2])).toBeLessThan(12);
+ expect(recolored.orange).toEqual(darkened.orange);
+ await page.getByRole("button", { name: "Undo", exact: true }).click();
+ await expect(color).toHaveValue("#e07020");
+ expect(await quadrantColors(page)).toEqual(gray);
+});
+
+test("a range intersects, or is shaped by, gradient and brush masks", async ({
+ page,
+}) => {
+ await open(page);
+ const original = await quadrantColors(page);
+ const darkened = (colors: Awaited<ReturnType<typeof quadrantColors>>) =>
+ Object.entries(colors)
+ .filter(([name, color]) => color[0] < original[name as "light"][0] - 40)
+ .map(([name]) => name);
+ // The right half, light above orange: intersected with the light tones, only the light quadrant.
+ const id = await page.evaluate(() => {
+ const api = window.openlight;
+ const id = api.addLayer("mask");
+ api.setLayerMask(id, {
+ kind: "linear",
+ start: [101, 100],
+ end: [99, 100],
+ });
+ api.setAdjustments({ exposure: -2 }, id);
+ return id;
+ });
+ await page
+ .getByRole("button", { name: "Linear Gradient actions", exact: true })
+ .click();
+ await page
+ .getByRole("menuitem", { name: "Intersect with mask", exact: true })
+ .click();
+ await page
+ .getByRole("menuitem", { name: "Luminance range", exact: true })
+ .click();
+ await setField(page, "Low", "75");
+ await setField(page, "Smoothness", "5");
+ expect(darkened(await quadrantColors(page))).toEqual(["light"]);
+
+ // A brush over the right half, intersected the same way.
+ await page.evaluate((id) => {
+ window.openlight.setLayerMask(id, {
+ kind: "brush",
+ strokes: [
+ {
+ mode: "paint",
+ size: 100,
+ feather: 0,
+ flow: 1,
+ points: [
+ [150, -50, 1],
+ [150, 250, 1],
+ ],
+ },
+ ],
+ });
+ }, id);
+ expect(darkened(await quadrantColors(page))).toEqual(["light"]);
+
+ // The light and orange tones, less a gradient over the bottom half: the light quadrant again.
+ await page.evaluate((id) => {
+ const api = window.openlight;
+ api.setLayerMask(id, {
+ kind: "luminance-range",
+ low: 50,
+ high: 100,
+ smoothness: 5,
+ });
+ const [range] = api.getState().scene?.layers.at(-1)?.children ?? [];
+ api.setLayerMask(range.id, {
+ kind: "linear",
+ start: [100, 101],
+ end: [100, 99],
+ });
+ api.setMaskOperation(range.id, "subtract");
+ }, id);
+ expect(darkened(await quadrantColors(page))).toEqual(["light"]);
+});
+
+test("an unpicked color range has no coverage, including as an intersection", async ({
+ page,
+}) => {
+ await open(page);
+ const original = await quadrantColors(page);
+ await addEffect(page, "Color Range");
+ const state = await page.evaluate(() => window.openlight.getState());
+ expect(state.scene?.layers.at(-1)).toMatchObject({
+ kind: "mask",
+ mask: { kind: "color-range", color: null },
+ });
+ expect(state.selectedLayerId).toBe(state.scene?.layers.at(-1)?.id);
+ await expect(page.getByLabel("Range color")).toHaveCount(0);
+ await setField(page, "Exposure", "-2");
+ expect(await quadrantColors(page)).toEqual(original);
+ await page.keyboard.press("Escape");
+
+ const child = await page.evaluate(() => {
+ const api = window.openlight;
+ const parent = api.addLayer("mask");
+ api.setLayerMask(parent, {
+ kind: "linear",
+ start: [101, 100],
+ end: [99, 100],
+ });
+ api.setAdjustments({ exposure: -2 }, parent);
+ const child = api.addLayer("mask", { inside: parent });
+ api.setLayerMask(child, {
+ kind: "color-range",
+ color: null,
+ tolerance: 30,
+ });
+ api.setMaskOperation(child, "intersect");
+ return child;
+ });
+ expect(await quadrantColors(page)).toEqual(original);
+ await page.evaluate(
+ (id) => window.openlight.setMaskOperation(id, "subtract"),
+ child,
+ );
+ const subtracted = await quadrantColors(page);
+ expect(subtracted.light[0]).toBeLessThan(original.light[0] - 60);
+ expect(subtracted.orange[0]).toBeLessThan(original.orange[0] - 60);
+ await page.evaluate(
+ (id) => window.openlight.setMaskOperation(id, "add"),
+ child,
+ );
+ expect(await quadrantColors(page)).toEqual(subtracted);
+});
diff --git a/tests/range-picker.e2e.ts b/tests/range-picker.e2e.ts
new file mode 100644
index 0000000..7cf83a5
--- /dev/null
+++ b/tests/range-picker.e2e.ts
@@ -0,0 +1,444 @@
+import type { Page } from "@playwright/test";
+import { expect, test } from "./fixtures";
+import { readImage } from "./images";
+import { box } from "./pointer";
+
+declare global {
+ interface Window {
+ rangeSampleGate: {
+ waiting: boolean;
+ settled: number;
+ pauseNext: () => void;
+ release: () => void;
+ reject: () => void;
+ };
+ }
+}
+
+const photo = Buffer.from(
+ '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><rect width="200" height="200" fill="#e07020"/></svg>',
+);
+
+async function open(page: Page, buffer = photo) {
+ await page.addInitScript(() => {
+ const mapAsync = GPUBuffer.prototype.mapAsync;
+ let paused = false;
+ let settled = 0;
+ let release: (() => void) | undefined;
+ let reject: (() => void) | undefined;
+ window.rangeSampleGate = {
+ get waiting() {
+ return Boolean(release);
+ },
+ get settled() {
+ return settled;
+ },
+ pauseNext() {
+ paused = true;
+ },
+ release() {
+ release?.();
+ },
+ reject() {
+ reject?.();
+ },
+ };
+ GPUBuffer.prototype.mapAsync = function (mode, offset, size) {
+ if (!paused || this.size !== 16) {
+ return mapAsync.call(this, mode, offset, size);
+ }
+ paused = false;
+ return new Promise<void>((resolve, fail) => {
+ release = () => {
+ release = undefined;
+ reject = undefined;
+ mapAsync.call(this, mode, offset, size).then(() => {
+ settled++;
+ resolve();
+ }, fail);
+ };
+ reject = () => {
+ release = undefined;
+ reject = undefined;
+ fail(new Error("Injected sample failure"));
+ };
+ });
+ };
+ });
+ await page.goto("/");
+ await page.locator('input[type="file"]').setInputFiles({
+ name: "orange.svg",
+ mimeType: "image/svg+xml",
+ buffer,
+ });
+ await expect(page.getByRole("textbox", { name: "Exposure" })).toHaveValue(
+ "0.00",
+ );
+}
+
+async function pick(page: Page) {
+ const picker = page.getByRole("application", { name: "Color range canvas" });
+ const canvas = await box(picker);
+ await page.mouse.click(
+ canvas.x + canvas.width / 2,
+ canvas.y + canvas.height / 2,
+ );
+}
+
+test.describe("mixed pointers", () => {
+ test.use({ hasTouch: true });
+
+ test("a touch cannot replace an active mouse pick", async ({ page }) => {
+ await open(
+ page,
+ Buffer.from(
+ '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><rect width="100" height="200" fill="#e07020"/><rect x="100" width="100" height="200" fill="#2060d0"/></svg>',
+ ),
+ );
+ await page.getByRole("button", { name: "Add effect" }).click();
+ await page.getByRole("menuitem", { name: "Color Range" }).click();
+ const canvas = await box(
+ page.getByRole("application", { name: "Color range canvas" }),
+ );
+ const x = canvas.x + canvas.width / 2 - 20;
+ const y = canvas.y + canvas.height / 2;
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await expect(page.getByLabel("Range color")).toHaveValue("#e07020");
+ await page.touchscreen.tap(x, y);
+ await page.mouse.move(x + 40, y);
+ await expect(page.getByLabel("Range color")).toHaveValue("#2060d0");
+ await page.mouse.up();
+ await expect
+ .poll(() =>
+ page.evaluate(() => {
+ const { history } = window.openlight.getState();
+ return "editing" in history && history.editing;
+ }),
+ )
+ .toBe(false);
+ await page.getByRole("button", { name: "Undo", exact: true }).click();
+ await expect(page.getByLabel("Range color")).toHaveCount(0);
+ });
+});
+
+test("a range inside a hidden effect can still pick its source color", async ({
+ page,
+}) => {
+ await open(page);
+ const original = (await readImage(page)).center;
+ const parent = await page.evaluate(() => {
+ const api = window.openlight;
+ const parent = api.addLayer("exposure");
+ api.setExposure(parent, -1);
+ const child = api.addLayer("mask", { inside: parent });
+ api.setLayerMask(child, {
+ kind: "color-range",
+ color: null,
+ tolerance: 30,
+ });
+ return parent;
+ });
+ const exposed = (await readImage(page)).center;
+ await page.evaluate(
+ (id) => window.openlight.setLayer(id, { visible: false }),
+ parent,
+ );
+ const before = await page.evaluate(
+ () => window.openlight.getState().history.undoCount,
+ );
+ await page
+ .getByRole("button", { name: "Pick a color from the photo" })
+ .click();
+ await pick(page);
+ const color = `#${exposed
+ .slice(0, 3)
+ .map((channel) => channel.toString(16).padStart(2, "0"))
+ .join("")}`;
+ await expect(page.getByLabel("Range color")).toHaveValue(color);
+ expect((await readImage(page)).center).toEqual(original);
+ expect(
+ await page.evaluate(() => window.openlight.getState().history.undoCount),
+ ).toBe(before + 1);
+});
+
+test("a delayed pick stays with its original selection", async ({ page }) => {
+ await open(page);
+ const { first, second } = await page.evaluate(() => {
+ const api = window.openlight;
+ const first = api.addLayer("mask");
+ api.setLayerMask(first, {
+ kind: "color-range",
+ color: "#000000",
+ tolerance: 20,
+ });
+ const second = api.addLayer("mask");
+ api.setLayerMask(second, {
+ kind: "color-range",
+ color: "#ffffff",
+ tolerance: 20,
+ });
+ api.selectLayer(first);
+ return { first, second };
+ });
+ await page
+ .getByRole("button", { name: "Pick a color from the photo" })
+ .click();
+ await page.evaluate(() => window.rangeSampleGate.pauseNext());
+ await pick(page);
+ await page.waitForFunction(() => window.rangeSampleGate.waiting);
+ await page.evaluate((id) => window.openlight.selectLayer(id), second);
+ await expect(
+ page.getByRole("application", { name: "Color range canvas" }),
+ ).toBeVisible();
+ await page.evaluate(() => window.rangeSampleGate.release());
+ await page.waitForFunction(() => window.rangeSampleGate.settled > 0);
+ await expect
+ .poll(() =>
+ page.evaluate(() => {
+ const { history } = window.openlight.getState();
+ return "editing" in history && history.editing;
+ }),
+ )
+ .toBe(false);
+ const colors = await page.evaluate(
+ ([a, b]) =>
+ [a, b].map((id) => {
+ const layer = window.openlight
+ .getState()
+ .scene?.layers.find((item) => item.id === id);
+ return layer?.kind === "mask" && layer.mask.kind === "color-range"
+ ? layer.mask.color
+ : undefined;
+ }),
+ [first, second],
+ );
+ expect(colors).toEqual(["#000000", "#ffffff"]);
+});
+
+test("leaving the picker cancels a delayed pick but keeps its new mask", async ({
+ page,
+}) => {
+ await open(page);
+ await page.getByRole("button", { name: "Add effect" }).click();
+ await page.getByRole("menuitem", { name: "Color Range" }).click();
+ const initial = await page.evaluate(() => window.openlight.getState());
+ expect(initial.scene?.layers.at(-1)).toMatchObject({
+ kind: "mask",
+ mask: { kind: "color-range", color: null },
+ });
+ expect(initial.selectedLayerId).toBe(initial.scene?.layers.at(-1)?.id);
+ await page.evaluate(() => window.rangeSampleGate.pauseNext());
+ await pick(page);
+ await page.waitForFunction(() => window.rangeSampleGate.waiting);
+ await page.keyboard.press("Escape");
+ await expect(
+ page.getByRole("application", { name: "Color range canvas" }),
+ ).toHaveCount(0);
+ await page.evaluate(() => window.rangeSampleGate.release());
+ await page.waitForFunction(() => window.rangeSampleGate.settled > 0);
+ await expect
+ .poll(() =>
+ page.evaluate(() => {
+ const { history } = window.openlight.getState();
+ return "editing" in history && history.editing;
+ }),
+ )
+ .toBe(false);
+ const mask = await page.evaluate(() =>
+ window.openlight.getState().scene?.layers.at(-1),
+ );
+ expect(mask).toMatchObject({
+ kind: "mask",
+ mask: { kind: "color-range", color: null },
+ });
+});
+
+test("adding another color range and selecting an existing one retargets the picker", async ({
+ page,
+}) => {
+ await open(page);
+ const add = async () => {
+ await page.getByRole("button", { name: "Add effect" }).click();
+ await page.getByRole("menuitem", { name: "Color Range" }).click();
+ return page.evaluate(() => window.openlight.getState().selectedLayerId);
+ };
+ const first = await add();
+ const second = await add();
+ expect(second).not.toBe(first);
+ const picker = page.getByRole("application", { name: "Color range canvas" });
+ await expect(picker).toBeVisible();
+ await pick(page);
+ await expect
+ .poll(() =>
+ page.evaluate(() => window.openlight.getState().scene?.layers.at(-1)),
+ )
+ .toMatchObject({ mask: { color: "#e07020" } });
+ await page
+ .getByRole("button", { name: "Select Color Range", exact: true })
+ .last()
+ .click();
+ await expect(picker).toBeVisible();
+ await pick(page);
+ await expect
+ .poll(() =>
+ page.evaluate((id) => {
+ const layer = window.openlight
+ .getState()
+ .scene?.layers.find((item) => item.id === id);
+ return layer?.kind === "mask" && layer.mask.kind === "color-range"
+ ? layer.mask.color
+ : undefined;
+ }, first),
+ )
+ .toBe("#e07020");
+ const colors = await page.evaluate(
+ ([a, b]) =>
+ [a, b].map((id) => {
+ const layer = window.openlight
+ .getState()
+ .scene?.layers.find((item) => item.id === id);
+ return layer?.kind === "mask" && layer.mask.kind === "color-range"
+ ? layer.mask.color
+ : undefined;
+ }),
+ [first, second],
+ );
+ expect(colors).toEqual(["#e07020", "#e07020"]);
+});
+
+test("selection away or deletion leaves the picker, and K needs a color range", async ({
+ page,
+}) => {
+ await open(page);
+ const picker = page.getByRole("application", { name: "Color range canvas" });
+ await page.keyboard.press("k");
+ await expect(picker).toHaveCount(0);
+ await page.getByRole("button", { name: "Add effect" }).click();
+ await page.getByRole("menuitem", { name: "Color Range" }).click();
+ const id = await page.evaluate(
+ () => window.openlight.getState().selectedLayerId ?? "",
+ );
+ expect(id).not.toBe("");
+ await expect(picker).toBeVisible();
+ await page.evaluate(() => {
+ const api = window.openlight;
+ api.selectLayer(api.getState().scene?.layers[0].id ?? "");
+ });
+ await expect(picker).toHaveCount(0);
+ await page
+ .getByRole("button", { name: "Select Color Range", exact: true })
+ .last()
+ .click();
+ await expect(picker).toBeVisible();
+ await page.evaluate(() => window.rangeSampleGate.pauseNext());
+ await pick(page);
+ await page.waitForFunction(() => window.rangeSampleGate.waiting);
+ await page.evaluate((layerId) => window.openlight.deleteLayer(layerId), id);
+ await expect(picker).toHaveCount(0);
+ await page.evaluate(() => window.rangeSampleGate.release());
+ await page.waitForFunction(() => window.rangeSampleGate.settled > 0);
+ expect(
+ await page.evaluate(
+ (layerId) =>
+ window.openlight
+ .getState()
+ .scene?.layers.some((layer) => layer.id === layerId),
+ id,
+ ),
+ ).toBe(false);
+ await page.getByRole("button", { name: "Undo", exact: true }).click();
+ await expect(picker).toHaveCount(0);
+ await page
+ .getByRole("button", { name: "Select Color Range", exact: true })
+ .click();
+ await expect(picker).toBeVisible();
+ await page.getByRole("button", { name: "Undo", exact: true }).click();
+ await expect(picker).toHaveCount(0);
+});
+
+test("an old pending pick cannot cancel a new gesture's history", async ({
+ page,
+}) => {
+ await open(page);
+ await page.evaluate(() => {
+ const api = window.openlight;
+ const id = api.addLayer("mask");
+ api.setLayerMask(id, {
+ kind: "color-range",
+ color: "#000000",
+ tolerance: 20,
+ });
+ });
+ const button = page.getByRole("button", {
+ name: "Pick a color from the photo",
+ });
+ await button.click();
+ const picker = page.getByRole("application", { name: "Color range canvas" });
+ const canvas = await box(picker);
+ const x = canvas.x + canvas.width / 2;
+ const y = canvas.y + canvas.height / 2;
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await expect(page.getByLabel("Range color")).toHaveValue("#e07020");
+ await page.evaluate(() => window.rangeSampleGate.pauseNext());
+ await page.mouse.move(x + 5, y);
+ await page.waitForFunction(() => window.rangeSampleGate.waiting);
+ await page.mouse.up();
+ await page.keyboard.press("Escape");
+ await expect(picker).toHaveCount(0);
+ await button.click();
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await page.waitForFunction(() => {
+ const { history } = window.openlight.getState();
+ return "editing" in history && history.editing;
+ });
+ await page.evaluate(() => window.rangeSampleGate.release());
+ await page.waitForFunction(() => window.rangeSampleGate.settled > 0);
+ const editing = await page.evaluate(() => {
+ const { history } = window.openlight.getState();
+ return "editing" in history && history.editing;
+ });
+ expect(editing).toBe(true);
+ await page.mouse.up();
+});
+
+test("a failed read reports the error and the next pick succeeds", async ({
+ page,
+}) => {
+ await open(page);
+ const id = await page.evaluate(() => {
+ const api = window.openlight;
+ const id = api.addLayer("mask");
+ api.setLayerMask(id, {
+ kind: "color-range",
+ color: "#000000",
+ tolerance: 20,
+ });
+ return id;
+ });
+ await page
+ .getByRole("button", { name: "Pick a color from the photo" })
+ .click();
+ await page.evaluate(() => window.rangeSampleGate.pauseNext());
+ await pick(page);
+ await page.waitForFunction(() => window.rangeSampleGate.waiting);
+ await page.evaluate(() => window.rangeSampleGate.reject());
+ await expect(
+ page.getByText("Couldn't pick a color. Try again."),
+ ).toBeVisible();
+ await pick(page);
+ await expect
+ .poll(() =>
+ page.evaluate((id) => {
+ const layer = window.openlight
+ .getState()
+ .scene?.layers.find((item) => item.id === id);
+ return layer?.kind === "mask" && layer.mask.kind === "color-range"
+ ? layer.mask.color
+ : undefined;
+ }, id),
+ )
+ .toBe("#e07020");
+});
diff --git a/tests/rendering-benchmark.ts b/tests/rendering-benchmark.ts
index 965eac5..92fe0bb 100644
--- a/tests/rendering-benchmark.ts
+++ b/tests/rendering-benchmark.ts
@@ -27,6 +27,9 @@ export type Workload =
| "masked-exposure"
| "radial-exposure"
| "brush-exposure"
+ | "brush-group"
+ | "luminance-range"
+ | "color-range"
| "layer-stack"
| "fill"
| "lut"
@@ -48,10 +51,12 @@ function summarize(values: number[]) {
};
}
-const rasterPixelBytes: Record<string, number> = {
+const pixelBytes: Record<string, number> = {
r8unorm: 1,
r16float: 2,
rgba8unorm: 4,
+ rgba16float: 8,
+ rgba32float: 16,
};
/** Wavy strokes across the image, three painted and one erased. */
@@ -78,9 +83,16 @@ function benchmarkMask(workload: Workload, size: [number, number]): Mask {
feather: 0.5,
};
}
- if (workload === "brush-exposure") {
+ if (workload === "brush-exposure" || workload === "brush-group") {
return { kind: "brush", strokes: brushStrokes(size) };
}
+ // What the Add menu's range masks select at first: the brighter half, or a sky blue.
+ if (workload === "luminance-range") {
+ return { kind: "luminance-range", low: 50, high: 100, smoothness: 25 };
+ }
+ if (workload === "color-range") {
+ return { kind: "color-range", color: "#6fa8dc", tolerance: 30 };
+ }
return {
kind: "linear",
start: [0, size[1] * 0.2],
@@ -169,16 +181,22 @@ export async function benchmarkRendering(
workload === "masked-exposure" ||
workload === "radial-exposure" ||
workload === "brush-exposure" ||
+ workload === "brush-group" ||
+ workload === "luminance-range" ||
+ workload === "color-range" ||
workload === "layer-stack"
) {
+ const mask = {
+ adjustments: defaultAdjustments,
+ toneCurve: defaultCurve,
+ kind: "mask",
+ } as const;
effects.push({
...common,
+ ...mask,
id: "benchmark-gradient",
name: "Gradient",
- kind: "mask",
operation: "add",
- adjustments: defaultAdjustments,
- toneCurve: defaultCurve,
opacity: 0.75,
mask: benchmarkMask(workload, size),
children: [
@@ -189,6 +207,19 @@ export async function benchmarkRendering(
kind: "exposure",
exposure: 1,
},
+ // A brush that a gradient takes away from, so the group combines its children.
+ ...(workload === "brush-group"
+ ? [
+ {
+ ...common,
+ ...mask,
+ id: "benchmark-subtract",
+ name: "Linear Gradient",
+ operation: "subtract",
+ mask: benchmarkMask("masked-exposure", size),
+ } as const,
+ ]
+ : []),
],
});
}
@@ -405,16 +436,14 @@ export async function benchmarkRendering(
pixelHash: [...pixelHash]
.map((value) => value.toString(16).padStart(2, "0"))
.join(""),
- // Image targets use rgba16float. Source and driver memory are excluded.
+ // Source and driver memory are excluded.
intermediateBytes: storage.textures.reduce(
- (sum, { size, format }) =>
- sum + size[0] * size[1] * (format === "rgba32float" ? 16 : 8),
+ (sum, { size, format }) => sum + size[0] * size[1] * pixelBytes[format],
0,
),
// Brush rasters, paint, and the stroke buffer, at source resolution, outside the graph.
rasterBytes: storage.rasters.reduce(
- (sum, { size, format }) =>
- sum + size[0] * size[1] * rasterPixelBytes[format],
+ (sum, { size, format }) => sum + size[0] * size[1] * pixelBytes[format],
0,
),
image: [...new Uint8Array(await blob.arrayBuffer())],
diff --git a/tests/rendering.bench.ts b/tests/rendering.bench.ts
index 5e37f80..0abe130 100644
--- a/tests/rendering.bench.ts
+++ b/tests/rendering.bench.ts
@@ -15,6 +15,9 @@ for (const workload of [
"masked-exposure",
"radial-exposure",
"brush-exposure",
+ "brush-group",
+ "luminance-range",
+ "color-range",
"layer-stack",
"fill",
"lut",
diff --git a/tests/scene-file.test.ts b/tests/scene-file.test.ts
index a0ebb90..47e7fac 100644
--- a/tests/scene-file.test.ts
+++ b/tests/scene-file.test.ts
@@ -82,6 +82,22 @@ test("scene files reopen the photo with every layer for further editing", async
],
});
api.setAdjustments({ shadows: 40 }, mask);
+ const tones = api.addLayer("mask", { inside: mask });
+ api.setLayerMask(tones, {
+ kind: "luminance-range",
+ low: 20,
+ high: 80,
+ smoothness: 10,
+ });
+ api.setMaskOperation(tones, "intersect");
+ api.run({
+ type: "add-mask",
+ mask: { kind: "color-range", color: "#336699", tolerance: 40 },
+ });
+ api.run({
+ type: "add-mask",
+ mask: { kind: "color-range", color: null, tolerance: 30 },
+ });
api.setDetails({ clarity: 30 }, api.addLayer("details", { inside: mask }));
const subtract = api.addLayer("mask", { inside: mask });
api.setLayerMask(subtract, {