Skip to content

Free open-source image editor for the browser

Refactor tone curves

Rodrigo19850c541d76
diff --git a/src/app/editor/renderer/renderer.ts b/src/app/editor/renderer/renderer.ts
index bde96e2..f43272f 100644
--- a/src/app/editor/renderer/renderer.ts
+++ b/src/app/editor/renderer/renderer.ts
@@ -7,28 +7,18 @@ import {
target,
} from "vgpu";
import type { Scene } from "@/app/scene";
+import { createToneCurves } from "@/features/tone-curves/pass";
import type { View } from "@/hooks/use-pan-zoom";
import adjustmentsShader from "@/lib/adjustments/adjustments.wgsl";
-import { sampleCurve } from "@/lib/curves";
-import curvesShader from "@/lib/curves/curves.wgsl";
import shader from "./renderer.wgsl";
-const curveSize = 1024;
-
/** Owns scene passes and intermediate textures for one decoded source. */
export function createRenderer(gpu: Gpu, source: Target) {
const adjusted = target(gpu, { size: source.size, format: source.format });
- const curved = target(gpu, { size: source.size, format: source.format });
const adjust = effect(gpu, adjustmentsShader, {
set: { sourceSampler: sampler(gpu) },
});
- const curve = gpu.device.createBuffer({
- size: curveSize * Float32Array.BYTES_PER_ELEMENT,
- usage: ["storage", "copy_dst"],
- });
- const applyCurve = effect(gpu, curvesShader, {
- set: { source: adjusted.color, curve },
- });
+ const toneCurves = createToneCurves(gpu, adjusted);
const display = effect(gpu, shader, {
set: {
sourceSampler: sampler(gpu, { magFilter: "linear", minFilter: "linear" }),
@@ -52,12 +42,7 @@ export function createRenderer(gpu: Gpu, source: Target) {
adjusted,
adjust.set({ source: source.color, adjustments: scene.adjustments }),
);
- output = adjusted;
- if (scene.curve.some((point) => point.x !== point.y)) {
- curve.write(sampleCurve(scene.curve, curveSize));
- frame.pass(curved, applyCurve);
- output = curved;
- }
+ output = toneCurves.render(frame, scene.curve);
for (const { canvas, view } of canvases) {
frame.pass(
canvas,
@@ -76,8 +61,7 @@ export function createRenderer(gpu: Gpu, source: Target) {
dispose() {
canvases.clear();
adjusted.color.dispose();
- curved.color.dispose();
- curve.dispose();
+ toneCurves.dispose();
},
};
}
diff --git a/src/app/editor/sidebar/index.tsx b/src/app/editor/sidebar/index.tsx
index 996e443..277aa7b 100644
--- a/src/app/editor/sidebar/index.tsx
+++ b/src/app/editor/sidebar/index.tsx
@@ -1,14 +1,39 @@
import { useEffect, useMemo } from "react";
import { useGpu } from "vgpu-react";
import { useRenderer } from "@/app/editor/renderer/provider";
+import { useScene } from "@/app/scene";
import ResizablePanel from "@/components/ui/resizable-panel";
import { Histogram } from "@/features/histogram";
import { createHistogram } from "@/features/histogram/histogram";
+import { ToneCurves } from "@/features/tone-curves/tone-curves";
import AdjustmentControls from "./adjustment-controls";
-import { Curves } from "./curves";
import ExportButton from "./export-button";
const histogramColors = ["#f25445", "#6bd175", "#5c8ffa"] as const;
+const curveHistogramColors = ["#a3a3a3"] as const;
+
+function ToneCurvesPanel({
+ histogram,
+}: {
+ histogram: ReturnType<typeof createHistogram>;
+}) {
+ const renderer = useRenderer();
+ const curve = useScene((scene) => scene.curve);
+ const setCurve = useScene((scene) => scene.setCurve);
+ return (
+ <ToneCurves points={curve} onChange={setCurve}>
+ <Histogram
+ histogram={histogram}
+ image={renderer.inputImage}
+ colors={curveHistogramColors}
+ working
+ fillOpacity={0.65}
+ aria-label="input histogram"
+ className="pointer-events-none absolute inset-0 h-full w-full opacity-25"
+ />
+ </ToneCurves>
+ );
+}
export function Sidebar() {
const gpu = useGpu();
@@ -30,7 +55,7 @@ export function Sidebar() {
/>
</section>
<AdjustmentControls />
- <Curves histogram={histogram} />
+ <ToneCurvesPanel histogram={histogram} />
</div>
<ExportButton />
</div>
diff --git a/src/app/scene/index.ts b/src/app/scene/index.ts
index 705106a..d483620 100644
--- a/src/app/scene/index.ts
+++ b/src/app/scene/index.ts
@@ -1,6 +1,10 @@
import type { Gpu, Target } from "vgpu";
import { create } from "zustand";
-import type { Curve } from "@/lib/curves";
+import {
+ type Curve,
+ defaultCurve,
+ validateCurve,
+} from "@/features/tone-curves/curve";
import decode from "@/lib/decode";
/** Non-destructive edits: exposure in stops, the rest -100..100. */
@@ -31,11 +35,6 @@ export const adjustmentLimits: Adjustments = {
saturation: 100,
};
-export const defaultCurve: Curve = [
- { x: 0, y: 0 },
- { x: 1, y: 1 },
-];
-
export type Source = { file: File; image?: Target; error?: string };
export type Scene = { source?: Source; adjustments: Adjustments; curve: Curve };
type SceneStore = Scene & {
@@ -83,6 +82,7 @@ export const useScene = create<SceneStore>((set, get) => ({
if (!get().source) {
throw new Error("Load an image before changing the curve.");
}
+ validateCurve(curve);
set({ curve: curve.map((point) => ({ ...point })) });
},
}));
diff --git a/src/features/tone-curves/curve.ts b/src/features/tone-curves/curve.ts
new file mode 100644
index 0000000..6c0a3f4
--- /dev/null
+++ b/src/features/tone-curves/curve.ts
@@ -0,0 +1,116 @@
+import { clamp, interpolatePchip } from "@/lib/math";
+
+export type CurvePoint = { readonly x: number; readonly y: number };
+export type Curve = readonly CurvePoint[];
+
+export const defaultCurve: Curve = [
+ { x: 0, y: 0 },
+ { x: 1, y: 1 },
+];
+
+const gap = 1 / 1024;
+
+export function validateCurve(points: Curve) {
+ if (!Array.isArray(points) || points.length < 2) {
+ throw new Error("A curve needs at least two points.");
+ }
+ for (const [index, point] of points.entries()) {
+ if (
+ !point ||
+ !Number.isFinite(point.x) ||
+ !Number.isFinite(point.y) ||
+ point.x < 0 ||
+ point.x > 1 ||
+ point.y < 0 ||
+ point.y > 1
+ ) {
+ throw new Error(
+ "Curve coordinates must be finite numbers between 0 and 1.",
+ );
+ }
+ if (index > 0 && point.x < points[index - 1].x + gap) {
+ throw new Error(
+ "Curve points must be ordered with a minimum x gap of 1/1024.",
+ );
+ }
+ }
+ const first = points[0];
+ const last = points[points.length - 1];
+ if ((first.x !== 0 && first.y !== 0) || (last.x !== 1 && last.y !== 1)) {
+ throw new Error(
+ "Curve endpoints must follow the lower-left and upper-right edges.",
+ );
+ }
+}
+
+export function moveCurvePoint(
+ points: Curve,
+ index: number,
+ point: CurvePoint,
+): Curve {
+ if (!points[index]) {
+ return points;
+ }
+ let x = clamp(point.x);
+ let y = clamp(point.y);
+ if (index === 0) {
+ x = Math.min(x, points[1].x - gap);
+ if (x < y) {
+ x = 0;
+ } else {
+ y = 0;
+ }
+ } else if (index === points.length - 1) {
+ x = Math.max(x, points[index - 1].x + gap);
+ if (x > y) {
+ x = 1;
+ } else {
+ y = 1;
+ }
+ } else {
+ x = clamp(x, points[index - 1].x + gap, points[index + 1].x - gap);
+ }
+ return points.with(index, { x, y });
+}
+
+export function removeCurvePoint(points: Curve, index: number): Curve {
+ if (index <= 0 || index >= points.length - 1) {
+ return points;
+ }
+ return points.toSpliced(index, 1);
+}
+
+/** Uniform samples over 0..1, including both endpoints; size must be at least two. */
+export function sampleCurve(points: Curve, size = 1024) {
+ const evaluate = interpolatePchip(points);
+ return Float32Array.from({ length: size }, (_, i) =>
+ evaluate(i / (size - 1)),
+ );
+}
+
+function midpoint(points: Curve): CurvePoint {
+ let widest = 0;
+ for (let i = 1; i < points.length - 1; i++) {
+ if (
+ points[i + 1].x - points[i].x >
+ points[widest + 1].x - points[widest].x
+ ) {
+ widest = i;
+ }
+ }
+ const x = (points[widest].x + points[widest + 1].x) / 2;
+ return { x, y: interpolatePchip(points)(x) };
+}
+
+/** Without a position, insert on the curve in its widest interval. */
+export function insertCurvePoint(points: Curve, point = midpoint(points)) {
+ const index = points.findIndex((next) => next.x > point.x);
+ if (
+ index <= 0 ||
+ point.x - points[index - 1].x < gap ||
+ points[index].x - point.x < gap
+ ) {
+ return null;
+ }
+ return { curve: points.toSpliced(index, 0, point), index };
+}
diff --git a/src/lib/curves/curves.wgsl b/src/features/tone-curves/curves.wgsl
similarity index 100%
rename from src/lib/curves/curves.wgsl
rename to src/features/tone-curves/curves.wgsl
diff --git a/src/app/editor/sidebar/curves/graph.tsx b/src/features/tone-curves/graph.tsx
similarity index 72%
rename from src/app/editor/sidebar/curves/graph.tsx
rename to src/features/tone-curves/graph.tsx
index 85eef2f..e34e541 100644
--- a/src/app/editor/sidebar/curves/graph.tsx
+++ b/src/features/tone-curves/graph.tsx
@@ -2,17 +2,17 @@ import {
type KeyboardEvent,
type MouseEvent,
type PointerEvent,
- useRef,
useState,
} from "react";
+import { clamp } from "@/lib/math";
import {
type Curve,
type CurvePoint,
- interpolateCurve,
+ insertCurvePoint,
+ moveCurvePoint,
+ removeCurvePoint,
sampleCurve,
-} from "@/lib/curves";
-
-const gap = 1 / 1024;
+} from "./curve";
function gridLines(spacing: number) {
return Array.from({ length: 256 / spacing - 1 }, (_, index) => {
@@ -21,10 +21,6 @@ function gridLines(spacing: number) {
}).join(" ");
}
-function clamp(value: number, min = 0, max = 1) {
- return Math.min(max, Math.max(min, value));
-}
-
function position(event: MouseEvent<SVGSVGElement>): CurvePoint {
const bounds = event.currentTarget.getBoundingClientRect();
return {
@@ -35,41 +31,19 @@ function position(event: MouseEvent<SVGSVGElement>): CurvePoint {
type GraphProps = { points: Curve; onChange: (points: Curve) => void };
-export default function Graph({ points, onChange }: GraphProps) {
+export function Graph({ points, onChange }: GraphProps) {
const [selected, select] = useState<number | null>(null);
- const dragging = useRef<number | null>(null);
const line = Array.from(
sampleCurve(points, 257),
(y, x) => `${x},${256 * (1 - y)}`,
).join(" ");
function move(index: number, point: CurvePoint) {
- if (!points[index]) {
- return;
- }
- let x = clamp(point.x);
- let y = clamp(point.y);
- if (index === 0) {
- x = Math.min(x, points[1].x - gap);
- if (x < y) {
- x = 0;
- } else {
- y = 0;
- }
- } else if (index === points.length - 1) {
- x = Math.max(x, points[index - 1].x + gap);
- if (x > y) {
- x = 1;
- } else {
- y = 1;
- }
- } else {
- x = clamp(x, points[index - 1].x + gap, points[index + 1].x - gap);
- }
- onChange(points.with(index, { x, y }));
+ onChange(moveCurvePoint(points, index, point));
}
function remove(index: number) {
- if (index > 0 && index < points.length - 1) {
- onChange(points.toSpliced(index, 1));
+ const curve = removeCurvePoint(points, index);
+ if (curve !== points) {
+ onChange(curve);
select(null);
}
}
@@ -91,18 +65,14 @@ export default function Graph({ points, onChange }: GraphProps) {
remove(index);
}
}
- function insert(point: CurvePoint) {
- const index = points.findIndex((next) => next.x > point.x);
- if (
- index <= 0 ||
- point.x - points[index - 1].x < gap ||
- points[index].x - point.x < gap
- ) {
+ function insert(point?: CurvePoint) {
+ const inserted = insertCurvePoint(points, point);
+ if (!inserted) {
return null;
}
- onChange(points.toSpliced(index, 0, point));
- select(index);
- return index;
+ onChange(inserted.curve);
+ select(inserted.index);
+ return inserted.index;
}
function start(event: PointerEvent<SVGSVGElement>) {
if (event.button !== 0) {
@@ -120,23 +90,12 @@ export default function Graph({ points, onChange }: GraphProps) {
index = added;
}
select(index);
- dragging.current = index;
event.currentTarget.setPointerCapture(event.pointerId);
}
function keyDown(event: KeyboardEvent<SVGSVGElement>) {
if (event.key === "Enter") {
event.preventDefault();
- let widest = 0;
- for (let i = 1; i < points.length - 1; i++) {
- if (
- points[i + 1].x - points[i].x >
- points[widest + 1].x - points[widest].x
- ) {
- widest = i;
- }
- }
- const x = (points[widest].x + points[widest + 1].x) / 2;
- insert({ x, y: interpolateCurve(points)(x) });
+ insert();
return;
}
if (selected === null || !points[selected]) {
@@ -173,13 +132,13 @@ export default function Graph({ points, onChange }: GraphProps) {
className="absolute inset-0 h-full w-full cursor-crosshair touch-none overflow-visible outline-none"
onDoubleClick={doubleClick}
onKeyDown={keyDown}
- onLostPointerCapture={() => {
- dragging.current = null;
- }}
onPointerDown={start}
onPointerMove={(event) => {
- if (dragging.current !== null) {
- move(dragging.current, position(event));
+ if (
+ selected !== null &&
+ event.currentTarget.hasPointerCapture(event.pointerId)
+ ) {
+ move(selected, position(event));
}
}}
role="application"
diff --git a/src/features/tone-curves/pass.ts b/src/features/tone-curves/pass.ts
new file mode 100644
index 0000000..24a16ca
--- /dev/null
+++ b/src/features/tone-curves/pass.ts
@@ -0,0 +1,28 @@
+import { effect, type Frame, type Gpu, type Target, target } from "vgpu";
+import { type Curve, sampleCurve } from "./curve";
+import shader from "./curves.wgsl";
+
+const curveSize = 1024;
+
+export function createToneCurves(gpu: Gpu, source: Target) {
+ const output = target(gpu, { size: source.size, format: source.format });
+ const curve = gpu.device.createBuffer({
+ size: curveSize * Float32Array.BYTES_PER_ELEMENT,
+ usage: ["storage", "copy_dst"],
+ });
+ const apply = effect(gpu, shader, { set: { source: source.color, curve } });
+ return {
+ render(frame: Frame, points: Curve) {
+ if (points.every((point) => point.x === point.y)) {
+ return source;
+ }
+ curve.write(sampleCurve(points, curveSize));
+ frame.pass(output, apply);
+ return output;
+ },
+ dispose() {
+ output.color.dispose();
+ curve.dispose();
+ },
+ };
+}
diff --git a/src/app/editor/sidebar/curves/index.tsx b/src/features/tone-curves/tone-curves.tsx
similarity index 51%
rename from src/app/editor/sidebar/curves/index.tsx
rename to src/features/tone-curves/tone-curves.tsx
index 9244b97..42464ba 100644
--- a/src/app/editor/sidebar/curves/index.tsx
+++ b/src/features/tone-curves/tone-curves.tsx
@@ -1,19 +1,14 @@
-import { useRenderer } from "@/app/editor/renderer/provider";
-import { useScene } from "@/app/scene";
-import { Histogram } from "@/features/histogram";
-import type { createHistogram } from "@/features/histogram/histogram";
-import Graph from "./graph";
+import type { ReactNode } from "react";
+import { type Curve, defaultCurve } from "./curve";
+import { Graph } from "./graph";
-const histogramColors = ["#a3a3a3"] as const;
-
-type CurvesProps = {
- histogram: ReturnType<typeof createHistogram>;
+type ToneCurvesProps = {
+ points: Curve;
+ onChange: (points: Curve) => void;
+ children?: ReactNode;
};
-export function Curves({ histogram }: CurvesProps) {
- const renderer = useRenderer();
- const points = useScene((scene) => scene.curve);
- const setCurve = useScene((scene) => scene.setCurve);
+export function ToneCurves({ points, onChange, children }: ToneCurvesProps) {
return (
<section aria-label="Curves" className="space-y-2.5 p-4 shadow-ridge">
<div className="flex items-center justify-between">
@@ -21,7 +16,7 @@ export function Curves({ histogram }: CurvesProps) {
<button
aria-label="Reset curve"
className="flex size-5 cursor-pointer items-center justify-center rounded text-neutral-500 transition-colors hover:bg-white/5 hover:text-neutral-300 focus-visible:outline-1 focus-visible:outline-neutral-400"
- onClick={() => setCurve()}
+ onClick={() => onChange(defaultCurve)}
title="Reset curve"
type="button"
>
@@ -41,16 +36,8 @@ export function Curves({ histogram }: CurvesProps) {
</div>
<div className="px-0.5">
<div className="relative aspect-square rounded border border-black bg-neutral-900 shadow-groove">
- <Histogram
- histogram={histogram}
- image={renderer.inputImage}
- colors={histogramColors}
- working
- fillOpacity={0.65}
- aria-label="input histogram"
- className="pointer-events-none absolute inset-0 h-full w-full opacity-25"
- />
- <Graph onChange={setCurve} points={points} />
+ {children}
+ <Graph onChange={onChange} points={points} />
</div>
</div>
</section>
diff --git a/src/lib/curves/index.ts b/src/lib/math.ts
similarity index 81%
rename from src/lib/curves/index.ts
rename to src/lib/math.ts
index 9c8cdd4..6de2c3b 100644
--- a/src/lib/curves/index.ts
+++ b/src/lib/math.ts
@@ -1,5 +1,8 @@
-export type CurvePoint = { readonly x: number; readonly y: number };
-export type Curve = readonly CurvePoint[];
+type Point = { readonly x: number; readonly y: number };
+
+export function clamp(value: number, min = 0, max = 1) {
+ return Math.min(max, Math.max(min, value));
+}
/** One-sided PCHIP endpoint slope, limited to preserve the segment's shape. */
function endpointSlope(
@@ -23,7 +26,7 @@ function endpointSlope(
}
/** Shape-preserving cubic interpolation of at least two points with strictly increasing x. */
-export function interpolateCurve(points: Curve) {
+export function interpolatePchip(points: readonly Point[]) {
const widths = points.slice(1).map((point, i) => point.x - points[i].x);
const slopes = widths.map(
(width, i) => (points[i + 1].y - points[i].y) / width,
@@ -77,11 +80,3 @@ export function interpolateCurve(points: Curve) {
);
};
}
-
-/** Uniform samples over 0..1, including both endpoints; size must be at least two. */
-export function sampleCurve(points: Curve, size = 1024) {
- const evaluate = interpolateCurve(points);
- return Float32Array.from({ length: size }, (_, i) =>
- evaluate(i / (size - 1)),
- );
-}
diff --git a/tests/curves.e2e.ts b/tests/curves.e2e.ts
index 07c9cf2..1c9187e 100644
--- a/tests/curves.e2e.ts
+++ b/tests/curves.e2e.ts
@@ -1,5 +1,5 @@
import { expect, type Page, test } from "@playwright/test";
-import { interpolateCurve } from "@/lib/curves";
+import { interpolatePchip } from "@/lib/math";
async function centerPixel(page: Page) {
const screenshot = await page.locator("canvas").screenshot();
@@ -49,7 +49,7 @@ test("a master curve maps colors beyond its white endpoint to white", async ({
await expect.poll(() => centerPixel(page)).toEqual([255, 255, 255, 255]);
});
-test("curve commands update the scene, reset, and start fresh for another image", async ({
+test("curve commands reject invalid edits, reset, and start fresh for another image", async ({
page,
}) => {
await page.goto("/");
@@ -75,6 +75,47 @@ test("curve commands update the scene, reset, and start fresh for another image"
const snapshot = window.openlight.getState();
snapshot.curve[1].y = 0;
const afterSnapshotChange = window.openlight.getState().curve;
+ const rejected = [
+ [],
+ [{ x: 0, y: 0 }],
+ [
+ { x: 0, y: 0 },
+ { x: 0, y: 1 },
+ ],
+ [
+ { x: 0, y: 0 },
+ { x: 1 / 2048, y: 1 },
+ ],
+ [
+ { x: 0, y: 0 },
+ { x: 0.8, y: 0.5 },
+ { x: 0.5, y: 1 },
+ ],
+ [
+ { x: 0, y: 0 },
+ { x: 1, y: Number.NaN },
+ ],
+ [
+ { x: 0, y: -1 },
+ { x: 1, y: 1 },
+ ],
+ [
+ { x: 0.1, y: 0.1 },
+ { x: 1, y: 1 },
+ ],
+ [
+ { x: 0, y: 0 },
+ { x: 0.9, y: 0.9 },
+ ],
+ ].map((curve) => {
+ try {
+ window.openlight.setCurve(curve);
+ return false;
+ } catch (error) {
+ return error instanceof Error && error.message.length > 0;
+ }
+ });
+ const afterRejected = window.openlight.getState().curve;
window.openlight.setCurve();
const reset = window.openlight.getState().curve;
window.openlight.setCurve(edited);
@@ -91,6 +132,8 @@ test("curve commands update the scene, reset, and start fresh for another image"
initial,
edited,
afterSnapshotChange,
+ rejected,
+ afterRejected,
reset,
reloaded: window.openlight.getState().curve,
file: window.openlight.getState().file,
@@ -107,6 +150,8 @@ test("curve commands update the scene, reset, and start fresh for another image"
{ x: 1, y: 1 },
]);
expect(result.afterSnapshotChange).toEqual(result.edited);
+ expect(result.rejected).toEqual(Array(9).fill(true));
+ expect(result.afterRejected).toEqual(result.edited);
expect(result.reset).toEqual(identity);
expect(result.reloaded).toEqual(identity);
expect(result.file).toBe("another.svg");
@@ -156,7 +201,7 @@ test("curves render after adjustments and resetting restores the preview", async
const adjusted = await centerPixel(page);
const adjustedPreview = await page.locator("canvas").screenshot();
await page.evaluate((curve) => window.openlight.setCurve(curve), points);
- const expected = interpolateCurve(points)(adjusted[0] / 255) * 255;
+ const expected = interpolatePchip(points)(adjusted[0] / 255) * 255;
await expect
.poll(async () => Math.abs((await centerPixel(page))[0] - expected))
.toBeLessThan(2);
diff --git a/tests/curves.test.ts b/tests/curves.test.ts
index c85b2ea..b08cc2b 100644
--- a/tests/curves.test.ts
+++ b/tests/curves.test.ts
@@ -1,5 +1,6 @@
import { expect, test } from "@playwright/test";
-import { interpolateCurve, sampleCurve } from "@/lib/curves";
+import { sampleCurve } from "@/features/tone-curves/curve";
+import { interpolatePchip } from "@/lib/math";
test("the diagonal samples to identity, including black and white", () => {
const points = [
@@ -14,7 +15,7 @@ test("the diagonal samples to identity, including black and white", () => {
});
test("a midtone lift interpolates the handles with a smooth cubic", () => {
- const evaluate = interpolateCurve([
+ const evaluate = interpolatePchip([
{ x: 0, y: 0 },
{ x: 0.5, y: 0.75 },
{ x: 1, y: 1 },
@@ -38,7 +39,7 @@ test("unevenly spaced points, plateaus, and reversals do not overshoot", () => {
{ x: 0.99, y: 0.95 },
{ x: 1, y: 1 },
];
- const evaluate = interpolateCurve(points);
+ const evaluate = interpolatePchip(points);
for (let i = 0; i < points.length - 1; i++) {
const start = points[i];
const end = points[i + 1];