Free open-source image editor for the browser
Add curves and soften landing
Rodrigo0c9e28a4c911
diff --git a/playwright.config.ts b/playwright.config.tsindex 0bcace3..3376768 100644--- a/playwright.config.ts+++ b/playwright.config.ts@@ -7,7 +7,7 @@ if (process.platform !== "darwin") {export default defineConfig({testDir: "./tests",- testMatch: "**/*.e2e.ts",+ testMatch: ["**/*.e2e.ts", "**/*.test.ts"],use: {channel: "chromium",baseURL: "http://127.0.0.1:4173",diff --git a/src/app/editor/renderer/renderer.ts b/src/app/editor/renderer/renderer.tsindex 4aa6d0f..f236aec 100644--- a/src/app/editor/renderer/renderer.ts+++ b/src/app/editor/renderer/renderer.ts@@ -8,17 +8,36 @@ import {} from "vgpu";import type { Scene } from "@/app/scene";import { histogram } from "@/features/histogram/bins";-import { histogramChart } from "@/features/histogram/histogram";+import {+ type HistogramMode,+ histogramChart,+} from "@/features/histogram/histogram";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;+export type HistogramOptions = {+ stage?: "input" | "output";+ mode?: HistogramMode;+};+/** Owns scene passes and intermediate textures for one decoded source. */export function createRenderer(gpu: Gpu, source: Target) {- const output = target(gpu, { size: source.size, format: source.format });+ 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 bins = histogram(gpu);const display = effect(gpu, shader, {set: {@@ -27,9 +46,27 @@ export function createRenderer(gpu: Gpu, source: Target) {});const canvases = new Set<{ canvas: Target & { dpr: number }; view: View }>();- const charts = new Set<ReturnType<typeof histogramChart>>();+ const charts = {+ input: new Set<ReturnType<typeof histogramChart>>(),+ output: new Set<ReturnType<typeof histogramChart>>(),+ };let disposed = false;let sampling = false;+ async function drawHistograms(+ image: Target,+ outputs: Set<ReturnType<typeof histogramChart>>,+ space: "display" | "working",+ ) {+ if (disposed || outputs.size === 0) {+ return;+ }+ const counts = await bins.read(image, space);+ if (!disposed) {+ for (const draw of outputs) {+ draw(counts);+ }+ }+ }return {attachCanvas(canvas: Target & { dpr: number }, view: View) {const output = { canvas, view };@@ -38,18 +75,27 @@ export function createRenderer(gpu: Gpu, source: Target) {canvases.delete(output);};},- attachHistogram(svg: SVGSVGElement) {- const draw = histogramChart(svg);- charts.add(draw);+ attachHistogram(+ svg: SVGSVGElement,+ { stage = "output", mode = "rgb" }: HistogramOptions = {},+ ) {+ const draw = histogramChart(svg, mode);+ charts[stage].add(draw);return () => {- charts.delete(draw);+ charts[stage].delete(draw);};},render(frame: Frame, scene: Scene) {frame.pass(- output,+ adjusted,adjust.set({ source: source.color, adjustments: scene.adjustments }),);+ let output = adjusted;+ if (scene.curve.some((point) => point.x !== point.y)) {+ curve.write(sampleCurve(scene.curve, curveSize));+ frame.pass(curved, applyCurve);+ output = curved;+ }for (const { canvas, view } of canvases) {frame.pass(canvas,@@ -64,21 +110,14 @@ export function createRenderer(gpu: Gpu, source: Target) {}),);}- if (sampling || charts.size === 0) {+ if (sampling || charts.input.size + charts.output.size === 0) {return;}sampling = true;frame.done.then(async () => {- if (disposed) {- return;- }- const counts = await bins.read(output);- if (!disposed) {- for (const draw of charts) {- draw(counts);- }- }+ await drawHistograms(adjusted, charts.input, "working");+ await drawHistograms(output, charts.output, "display");}).catch((error: unknown) => {if (!disposed) {@@ -92,8 +131,11 @@ export function createRenderer(gpu: Gpu, source: Target) {dispose() {disposed = true;canvases.clear();- charts.clear();- output.color.dispose();+ charts.input.clear();+ charts.output.clear();+ adjusted.color.dispose();+ curved.color.dispose();+ curve.dispose();},};}diff --git a/src/app/editor/sidebar/curves/graph.tsx b/src/app/editor/sidebar/curves/graph.tsxnew file mode 100644index 0000000..85eef2f--- /dev/null+++ b/src/app/editor/sidebar/curves/graph.tsx@@ -0,0 +1,230 @@+import {+ type KeyboardEvent,+ type MouseEvent,+ type PointerEvent,+ useRef,+ useState,+} from "react";+import {+ type Curve,+ type CurvePoint,+ interpolateCurve,+ sampleCurve,+} from "@/lib/curves";++const gap = 1 / 1024;++function gridLines(spacing: number) {+ return Array.from({ length: 256 / spacing - 1 }, (_, index) => {+ const position = (index + 1) * spacing;+ return `M${position} 0V256 M0 ${position}H256`;+ }).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 {+ x: clamp((event.clientX - bounds.left) / bounds.width),+ y: clamp(1 - (event.clientY - bounds.top) / bounds.height),+ };+}++type GraphProps = { points: Curve; onChange: (points: Curve) => void };++export default 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 }));+ }+ function remove(index: number) {+ if (index > 0 && index < points.length - 1) {+ onChange(points.toSpliced(index, 1));+ select(null);+ }+ }+ function hitTest(event: MouseEvent<SVGSVGElement>) {+ const point = position(event);+ const size = event.currentTarget.getBoundingClientRect().width;+ return points.findIndex(+ (candidate) =>+ Math.hypot(candidate.x - point.x, candidate.y - point.y) * size <= 12,+ );+ }+ function doubleClick(event: MouseEvent<SVGSVGElement>) {+ const index = hitTest(event);+ if (index === 0) {+ move(index, { x: 0, y: 0 });+ } else if (index === points.length - 1) {+ move(index, { x: 1, y: 1 });+ } else {+ 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+ ) {+ return null;+ }+ onChange(points.toSpliced(index, 0, point));+ select(index);+ return index;+ }+ function start(event: PointerEvent<SVGSVGElement>) {+ if (event.button !== 0) {+ return;+ }+ event.preventDefault();+ event.currentTarget.focus();+ const point = position(event);+ let index = hitTest(event);+ if (index < 0) {+ const added = insert(point);+ if (added === null) {+ return;+ }+ 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) });+ return;+ }+ if (selected === null || !points[selected]) {+ return;+ }+ if (event.key === "Delete" || event.key === "Backspace") {+ event.preventDefault();+ remove(selected);+ return;+ }+ const directions: Record<string, CurvePoint> = {+ ArrowLeft: { x: -1, y: 0 },+ ArrowRight: { x: 1, y: 0 },+ ArrowDown: { x: 0, y: -1 },+ ArrowUp: { x: 0, y: 1 },+ };+ const direction = directions[event.key];+ if (direction) {+ event.preventDefault();+ let step = 0.001;+ if (event.shiftKey) {+ step = 0.01;+ }+ move(selected, {+ x: points[selected].x + direction.x * step,+ y: points[selected].y + direction.y * step,+ });+ }+ }+ return (+ <svg+ aria-label="Tone curve"+ aria-description="Click or press Enter to add a point. Drag or use arrow keys to move it. Endpoints follow the edges. Shift moves faster. Double-click resets an endpoint or removes an interior point. Delete removes an interior point."+ 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));+ }+ }}+ role="application"+ tabIndex={-1}+ viewBox="0 0 256 256"+ >+ <path+ d={gridLines(8)}+ fill="none"+ stroke="white"+ strokeOpacity="0.04"+ vectorEffect="non-scaling-stroke"+ />+ <path+ d={gridLines(32)}+ fill="none"+ stroke="white"+ strokeOpacity="0.07"+ vectorEffect="non-scaling-stroke"+ />+ <path+ d="M0 256L256 0"+ fill="none"+ stroke="#a3a3a3"+ strokeDasharray="3 4"+ strokeOpacity="0.2"+ />+ <polyline+ className="drop-shadow-[0_1px_1px_rgb(0_0_0/0.25)]"+ fill="none"+ points={line}+ stroke="#e5e5e5"+ strokeWidth="2"+ />+ {points.map((point, index) => (+ <circle+ className="fill-neutral-800 stroke-neutral-200 data-[selected=true]:fill-neutral-100"+ cx={point.x * 256}+ cy={(1 - point.y) * 256}+ data-selected={selected === index}+ key={point.x}+ r="4"+ strokeWidth="2"+ />+ ))}+ </svg>+ );+}diff --git a/src/app/editor/sidebar/curves/index.tsx b/src/app/editor/sidebar/curves/index.tsxnew file mode 100644index 0000000..1406656--- /dev/null+++ b/src/app/editor/sidebar/curves/index.tsx@@ -0,0 +1,45 @@+import Histogram from "@/app/editor/sidebar/histogram";+import { useScene } from "@/app/scene";+import Graph from "./graph";++export default function Curves() {+ const points = useScene((scene) => scene.curve);+ const setCurve = useScene((scene) => scene.setCurve);+ return (+ <section aria-label="Curves" className="space-y-2.5 p-4 shadow-ridge">+ <div className="flex items-center justify-between">+ <h2 className="text-sm text-neutral-400">Curves</h2>+ <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()}+ title="Reset curve"+ type="button"+ >+ <svg+ aria-hidden="true"+ className="size-3.5"+ fill="none"+ stroke="currentColor"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="1.5"+ viewBox="0 0 24 24"+ >+ <path d="M3 10a9 9 0 1 1 2.6 8.4M3 4v6h6" />+ </svg>+ </button>+ </div>+ <div className="px-0.5">+ <div className="relative aspect-square rounded border border-black bg-neutral-900 shadow-groove">+ <Histogram+ className="pointer-events-none absolute inset-0 h-full w-full opacity-25"+ mode="combined"+ stage="input"+ />+ <Graph onChange={setCurve} points={points} />+ </div>+ </div>+ </section>+ );+}diff --git a/src/app/editor/sidebar/histogram.tsx b/src/app/editor/sidebar/histogram.tsxindex c6efeeb..6e91f3e 100644--- a/src/app/editor/sidebar/histogram.tsx+++ b/src/app/editor/sidebar/histogram.tsx@@ -1,18 +1,26 @@import { useEffect, useRef } from "react";import { useRenderer } from "@/app/editor/renderer/provider";+import type { HistogramOptions } from "@/app/editor/renderer/renderer";-export default function Histogram() {+type HistogramProps = HistogramOptions & { className?: string };++export default function Histogram({+ stage = "output",+ mode = "rgb",+ className = "h-24 w-full",+}: HistogramProps) {const renderer = useRenderer();const ref = useRef<SVGSVGElement>(null);useEffect(() => {if (ref.current) {- return renderer.attachHistogram(ref.current);+ return renderer.attachHistogram(ref.current, { stage, mode });}- }, [renderer]);+ }, [renderer, stage, mode]);return (<svgref={ref}- className="h-24 w-full"+ aria-label={`${stage} histogram`}+ className={className}preserveAspectRatio="none"viewBox="0 0 255 100"/>diff --git a/src/app/editor/sidebar/index.tsx b/src/app/editor/sidebar/index.tsxindex 4a3b2c5..05ed9dd 100644--- a/src/app/editor/sidebar/index.tsx+++ b/src/app/editor/sidebar/index.tsx@@ -1,15 +1,17 @@import ResizablePanel from "@/components/ui/resizable-panel";import AdjustmentControls from "./adjustment-controls";+import Curves from "./curves";import Histogram from "./histogram";export default function Sidebar() {return (<ResizablePanel>- <div className="flex flex-col divide-y divide-black">+ <div className="flex h-full flex-col divide-y divide-black overflow-y-auto"><section className="bg-neutral-900 p-0.5 pb-0"><Histogram /></section><AdjustmentControls />+ <Curves /></div></ResizablePanel>);diff --git a/src/app/landing/backdrop.wgsl b/src/app/landing/backdrop.wgslindex 4f10918..ced4d44 100644--- a/src/app/landing/backdrop.wgsl+++ b/src/app/landing/backdrop.wgsl@@ -12,7 +12,7 @@ struct Params {@group(0) @binding(0) var<uniform> params: Params;const dark = vec3f(0.075);-const light = vec3f(0.21, 0.2, 0.19);+const light = vec3f(0.17, 0.163, 0.156);const mote = vec3f(1.0, 0.94, 0.82);// One drifting, twinkling mote per grid cell; each pixel checks its 3x3 neighborhood.@@ -25,7 +25,7 @@ fn motes(p: vec2f, t: f32, density: f32, rise: f32) -> f32 {for (var x = -1; x <= 1; x++) {let o = vec2f(f32(x), f32(y));let h = hash3(vec3f(cell + o, density));- let sway = vec2f(sin(t * 0.5 + h.z * tau), cos(t * 0.4 + h.x * tau)) * 0.2;+ let sway = vec2f(sin(t * 0.5 + h.z * tau), cos(t * 0.4 + h.x * tau)) * 0.1;let dist = distance(f, o + 0.3 + h.xy * 0.4 + sway);let size = 0.03 + h.z * 0.05;let twinkle = 0.55 + 0.45 * sin(t * (0.8 + h.y * 1.5) + h.x * tau);@@ -63,7 +63,7 @@ fn motes(p: vec2f, t: f32, density: f32, rise: f32) -> f32 {let q = pointer + rotate2d(p - pointer, near * 1.6) * (1.0 + pull * falloff * 1.2);// Dust shows where the light is: inside the beam, and around a dragged file.- let dust = motes(q, t, 7.0, 0.3) + motes(q, t, 12.0, 0.25) * 0.5;+ let dust = motes(q, t, 7.0, 0.15) + motes(q, t, 12.0, 0.125) * 0.5;let lit = 0.15 + 0.6 * beam + near * 0.6;// Static per-pixel dither hides banding in the few gray levels the glow spans.diff --git a/src/app/scene/controls.ts b/src/app/scene/controls.tsindex 8af0ff3..59c0f57 100644--- a/src/app/scene/controls.ts+++ b/src/app/scene/controls.ts@@ -7,6 +7,7 @@ function getState() {return {file: scene.source?.file.name,adjustments: { ...scene.adjustments },+ curve: scene.curve.map((point) => ({ ...point })),};}@@ -22,6 +23,7 @@ export function useControls() {() => ({loadImage: (file: File) => useScene.getState().loadImage(gpu, file),setAdjustments: useScene.getState().setAdjustments,+ setCurve: useScene.getState().setCurve,getState,}),[gpu],diff --git a/src/app/scene/index.ts b/src/app/scene/index.tsindex 269bdf6..705106a 100644--- a/src/app/scene/index.ts+++ b/src/app/scene/index.ts@@ -1,5 +1,6 @@import type { Gpu, Target } from "vgpu";import { create } from "zustand";+import type { Curve } from "@/lib/curves";import decode from "@/lib/decode";/** Non-destructive edits: exposure in stops, the rest -100..100. */@@ -30,22 +31,34 @@ 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 };+export type Scene = { source?: Source; adjustments: Adjustments; curve: Curve };type SceneStore = Scene & {loadImage: (gpu: Gpu, file: File) => Promise<void>;setAdjustments: (change: Partial<Adjustments>) => void;+ /** Ordered points in 0..1; endpoints follow the lower-left and upper-right edges. Omit to reset. */+ setCurve: (curve?: Curve) => void;};export const useScene = create<SceneStore>((set, get) => ({adjustments: { ...defaultAdjustments },+ curve: defaultCurve,loadImage: async (gpu, file) => {if (!(file instanceof File)) {throw new Error("loadImage requires a File.");}const source = { file };get().source?.image?.color.dispose();- set({ source, adjustments: { ...defaultAdjustments } });+ set({+ source,+ adjustments: { ...defaultAdjustments },+ curve: defaultCurve,+ });try {const image = await decode(gpu, file);if (get().source !== source) {@@ -66,4 +79,10 @@ export const useScene = create<SceneStore>((set, get) => ({}set({ adjustments: { ...adjustments, ...change } });},+ setCurve: (curve = defaultCurve) => {+ if (!get().source) {+ throw new Error("Load an image before changing the curve.");+ }+ set({ curve: curve.map((point) => ({ ...point })) });+ },}));diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsxindex 4bcb88c..4db4317 100644--- a/src/components/ui/button.tsx+++ b/src/components/ui/button.tsx@@ -8,7 +8,7 @@ export default function Button({return (<buttonclassName={cn(- "cursor-pointer rounded border border-black bg-neutral-700 px-4 py-2.5 text-neutral-100 shadow-ridge hover:bg-neutral-600 active:bg-neutral-800 active:shadow-groove focus-visible:outline-2 focus-visible:outline-offset-3 focus-visible:outline-neutral-400",+ "cursor-pointer rounded-lg border border-black bg-neutral-700 px-3 py-2 text-neutral-100 shadow-ridge hover:bg-neutral-600 active:bg-neutral-700 active:shadow-groove focus-visible:outline-2 focus-visible:outline-offset-3 focus-visible:outline-neutral-400 transition-colors",className,)}type="button"diff --git a/src/features/histogram/bins.ts b/src/features/histogram/bins.tsindex 89bc193..88d467b 100644--- a/src/features/histogram/bins.ts+++ b/src/features/histogram/bins.ts@@ -7,9 +7,14 @@ export function histogram(gpu: Gpu) {const buffer = storage(gpu, emptyBins.byteLength);const counter = compute(gpu, shader, { set: { bins: buffer } });return {- async read(image: Target) {+ async read(image: Target, space: "display" | "working" = "display") {buffer.write(emptyBins);- counter.set({ source: image.color }).dispatch(32, 20);+ counter+ .set({+ source: image.color,+ params: { working: Number(space === "working") },+ })+ .dispatch(32, 20);return new Uint32Array(await buffer.read());},};diff --git a/src/features/histogram/bins.wgsl b/src/features/histogram/bins.wgslindex a7adcce..e4eea36 100644--- a/src/features/histogram/bins.wgsl+++ b/src/features/histogram/bins.wgsl@@ -1,7 +1,13 @@import { display } from "../../lib/color.wgsl";+import { linearToSrgb3 } from "@vgpu/wgsl-std/color";++struct Params {+ working: u32,+}@group(0) @binding(0) var source: texture_2d<f32>;@group(0) @binding(1) var<storage, read_write> bins: array<atomic<u32>, 768>;+@group(0) @binding(2) var<uniform> params: Params;const samples = vec2u(512, 320);// Soft-binning weight spread across a bin pair; kept as a fixed-point scale so atomics stay integer.@@ -22,8 +28,11 @@ fn softBin(channel: u32, position: f32) {return;}let texel = textureLoad(source, id.xy * textureDimensions(source) / samples, 0).rgb;- let encoded = display(texel) * 255.0;- softBin(0u, encoded.r);- softBin(1u, encoded.g);- softBin(2u, encoded.b);+ var encoded = display(texel);+ if (params.working != 0u) {+ encoded = linearToSrgb3(clamp(texel, vec3f(0.0), vec3f(1.0)));+ }+ softBin(0u, encoded.r * 255.0);+ softBin(1u, encoded.g * 255.0);+ softBin(2u, encoded.b * 255.0);}diff --git a/src/features/histogram/histogram.ts b/src/features/histogram/histogram.tsindex 7352065..6cbf24c 100644--- a/src/features/histogram/histogram.ts+++ b/src/features/histogram/histogram.ts@@ -3,6 +3,8 @@ const binCount = 256;const kernel = [1, 4, 6, 4, 1];const kernelWeight = 16;+export type HistogramMode = "rgb" | "combined";+/** Applies the binomial kernel over one channel's soft-binned counts. */function smooth(bins: Uint32Array, channel: number) {return Array.from({ length: binCount }, (_, bin) => {@@ -18,8 +20,13 @@ function smooth(bins: Uint32Array, channel: number) {}/** RGB polyline points on a 255×100 box: smoothed, then square-root scaled to the shared peak. */-function curves(bins: Uint32Array) {- const counts = channels.map((_, channel) => smooth(bins, channel));+function curves(bins: Uint32Array, mode: HistogramMode) {+ let counts = channels.map((_, channel) => smooth(bins, channel));+ if (mode === "combined") {+ counts = [+ counts[0].map((count, bin) => count + counts[1][bin] + counts[2][bin]),+ ];+ }const peak = Math.max(1, ...counts.flat());return counts.map((channel) =>channel@@ -32,17 +39,26 @@ function curves(bins: Uint32Array) {}/** Binds a histogram output once; subsequent updates write directly to its SVG. */-export function histogramChart(svg: SVGSVGElement) {- svg.innerHTML = `<title>Histogram</title>${channels+export function histogramChart(+ svg: SVGSVGElement,+ mode: HistogramMode = "rgb",+) {+ let colors = channels;+ let opacity = 0.2;+ if (mode === "combined") {+ colors = ["#a3a3a3"];+ opacity = 0.65;+ }+ svg.innerHTML = `<title>Histogram</title>${colors.map((color) =>- `<g><polygon fill="${color}" fill-opacity="0.2"/><polyline fill="none" stroke="${color}" vector-effect="non-scaling-stroke"/></g>`,+ `<g><polygon fill="${color}" fill-opacity="${opacity}"/><polyline fill="none" stroke="${color}" vector-effect="non-scaling-stroke"/></g>`,).join("")}`;const polygons = svg.querySelectorAll("polygon");const lines = svg.querySelectorAll("polyline");return (bins: Uint32Array) => {- curves(bins).forEach((points, channel) => {+ curves(bins, mode).forEach((points, channel) => {polygons[channel].setAttribute("points", `0,100 ${points} 255,100`);lines[channel].setAttribute("points", points);});diff --git a/src/lib/curves/curves.wgsl b/src/lib/curves/curves.wgslnew file mode 100644index 0000000..03c17ed--- /dev/null+++ b/src/lib/curves/curves.wgsl@@ -0,0 +1,29 @@+import { linearToSrgb, srgbToLinear } from "@vgpu/wgsl-std/color";++@group(0) @binding(0) var source: texture_2d<f32>;+@group(0) @binding(1) var<storage, read> curve: array<f32>;++// The graph uses sRGB transfer; input and output remain linear working RGB.+fn lookup(linear: f32) -> f32 {+ let last = arrayLength(&curve) - 1u;+ let position = clamp(linearToSrgb(linear), 0.0, 1.0) * f32(last);+ let lo = u32(position);+ return srgbToLinear(mix(curve[lo], curve[min(lo + 1u, last)], fract(position)));+}++// Film-like tone mapping: interpolate the middle channel between mapped extremes in linear RGB.+fn tone(color: vec3f) -> vec3f {+ let low = min(color.r, min(color.g, color.b));+ let high = max(color.r, max(color.g, color.b));+ let mappedLow = lookup(low);+ if (high == low) {+ return vec3f(mappedLow);+ }+ let mappedHigh = lookup(high);+ return vec3f(mappedLow) + (color - low) * (mappedHigh - mappedLow) / (high - low);+}++@fragment fn fs_main(@builtin(position) position: vec4f) -> @location(0) vec4f {+ let input = textureLoad(source, vec2i(position.xy), 0);+ return vec4f(tone(clamp(input.rgb, vec3f(0.0), vec3f(1.0))), input.a);+}diff --git a/src/lib/curves/index.ts b/src/lib/curves/index.tsnew file mode 100644index 0000000..9c8cdd4--- /dev/null+++ b/src/lib/curves/index.ts@@ -0,0 +1,87 @@+export type CurvePoint = { readonly x: number; readonly y: number };+export type Curve = readonly CurvePoint[];++/** One-sided PCHIP endpoint slope, limited to preserve the segment's shape. */+function endpointSlope(+ width: number,+ nextWidth: number,+ slope: number,+ nextSlope: number,+) {+ const tangent =+ ((2 * width + nextWidth) * slope - width * nextSlope) / (width + nextWidth);+ if (Math.sign(tangent) !== Math.sign(slope)) {+ return 0;+ }+ if (+ Math.sign(slope) !== Math.sign(nextSlope) &&+ Math.abs(tangent) > 3 * Math.abs(slope)+ ) {+ return 3 * slope;+ }+ return tangent;+}++/** Shape-preserving cubic interpolation of at least two points with strictly increasing x. */+export function interpolateCurve(points: Curve) {+ 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,+ );+ const last = slopes.length - 1;+ const tangents = points.map((_, i) => {+ if (last === 0) {+ return slopes[0];+ }+ if (i === 0) {+ return endpointSlope(widths[0], widths[1], slopes[0], slopes[1]);+ }+ if (i === points.length - 1) {+ return endpointSlope(+ widths[last],+ widths[last - 1],+ slopes[last],+ slopes[last - 1],+ );+ }+ const before = slopes[i - 1];+ const after = slopes[i];+ if (before * after <= 0) {+ return 0;+ }+ const leftWeight = 2 * widths[i] + widths[i - 1];+ const rightWeight = widths[i] + 2 * widths[i - 1];+ return (+ (leftWeight + rightWeight) / (leftWeight / before + rightWeight / after)+ );+ });+ return (x: number) => {+ if (x <= points[0].x) {+ return points[0].y;+ }+ if (x >= points[points.length - 1].x) {+ return points[points.length - 1].y;+ }+ let i = 0;+ while (x > points[i + 1].x) {+ i++;+ }+ const t = (x - points[i].x) / widths[i];+ const t2 = t * t;+ const t3 = t2 * t;+ return (+ (2 * t3 - 3 * t2 + 1) * points[i].y ++ (t3 - 2 * t2 + t) * widths[i] * tangents[i] ++ (3 * t2 - 2 * t3) * points[i + 1].y ++ (t3 - t2) * widths[i] * tangents[i + 1]+ );+ };+}++/** 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.tsnew file mode 100644index 0000000..3916179--- /dev/null+++ b/tests/curves.e2e.ts@@ -0,0 +1,402 @@+import { expect, type Page, test } from "@playwright/test";+import { interpolateCurve } from "@/lib/curves";++async function centerPixel(page: Page) {+ const screenshot = await page.locator("canvas").screenshot();+ return page.evaluate(+ async (bytes) => {+ const image = await createImageBitmap(+ new Blob([new Uint8Array(bytes)], { type: "image/png" }),+ );+ const canvas = new OffscreenCanvas(image.width, image.height);+ const context = canvas.getContext("2d");+ if (!context) {+ throw new Error("Cannot read the preview screenshot.");+ }+ context.drawImage(image, 0, 0);+ image.close();+ return [+ ...context.getImageData(canvas.width / 2, canvas.height / 2, 1, 1).data,+ ];+ },+ [...screenshot],+ );+}++test("a master curve maps colors beyond its white endpoint to white", async ({+ page,+}) => {+ await page.goto("/");+ await page.waitForFunction(() => window.openlight);+ await page.evaluate(() =>+ window.openlight.loadImage(+ new File(+ [+ '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#305080"/></svg>',+ ],+ "blue.svg",+ { type: "image/svg+xml" },+ ),+ ),+ );+ await expect.poll(() => centerPixel(page)).toEqual([48, 80, 128, 255]);+ await page.evaluate(() =>+ window.openlight.setCurve([+ { x: 0, y: 0 },+ { x: 0.1, y: 1 },+ ]),+ );+ await expect.poll(() => centerPixel(page)).toEqual([255, 255, 255, 255]);+});++test("curve commands update the scene, reset, and start fresh for another image", async ({+ page,+}) => {+ await page.goto("/");+ await page.waitForFunction(() => window.openlight);+ const result = await page.evaluate(async () => {+ const image = new File(+ [+ '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#808080"/></svg>',+ ],+ "curve.svg",+ { type: "image/svg+xml" },+ );+ await window.openlight.loadImage(image);+ const initial = window.openlight.getState().curve;+ const points = [+ { x: 0, y: 0 },+ { x: 0.5, y: 0.75 },+ { x: 1, y: 1 },+ ];+ window.openlight.setCurve(points);+ points[1].y = 0.25;+ const edited = window.openlight.getState().curve;+ const snapshot = window.openlight.getState();+ snapshot.curve[1].y = 0;+ const afterSnapshotChange = window.openlight.getState().curve;+ window.openlight.setCurve();+ const reset = window.openlight.getState().curve;+ window.openlight.setCurve(edited);+ await window.openlight.loadImage(+ new File(+ [+ '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#305080"/></svg>',+ ],+ "another.svg",+ { type: "image/svg+xml" },+ ),+ );+ return {+ initial,+ edited,+ afterSnapshotChange,+ reset,+ reloaded: window.openlight.getState().curve,+ file: window.openlight.getState().file,+ };+ });+ const identity = [+ { x: 0, y: 0 },+ { x: 1, y: 1 },+ ];+ expect(result.initial).toEqual(identity);+ expect(result.edited).toEqual([+ { x: 0, y: 0 },+ { x: 0.5, y: 0.75 },+ { x: 1, y: 1 },+ ]);+ expect(result.afterSnapshotChange).toEqual(result.edited);+ expect(result.reset).toEqual(identity);+ expect(result.reloaded).toEqual(identity);+ expect(result.file).toBe("another.svg");+ await expect.poll(() => centerPixel(page)).toEqual([48, 80, 128, 255]);+});++test("curves render after adjustments and resetting restores the preview", async ({+ page,+}) => {+ const errors: string[] = [];+ page.on("pageerror", (error) => errors.push(error.message));+ page.on("console", (message) => {+ if (message.type() === "error") {+ errors.push(message.text());+ }+ });+ await page.goto("/");+ await page.waitForFunction(() => window.openlight);+ await page.evaluate(() =>+ window.openlight.loadImage(+ new File(+ [+ '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#808080"/></svg>',+ ],+ "gray.svg",+ { type: "image/svg+xml" },+ ),+ ),+ );+ await expect.poll(() => centerPixel(page)).toEqual([128, 128, 128, 255]);+ const original = await page.locator("canvas").screenshot();+ const points = [+ { x: 0, y: 0 },+ { x: 0.5, y: 0.75 },+ { x: 1, y: 1 },+ ];+ await page.evaluate((curve) => window.openlight.setCurve(curve), points);+ await expect+ .poll(async () => (await centerPixel(page))[0])+ .toBeCloseTo(192, -1);+ await page.evaluate(() => window.openlight.setCurve());+ await expect+ .poll(() => page.locator("canvas").screenshot())+ .toEqual(original);+ await page.evaluate(() => window.openlight.setAdjustments({ exposure: -1 }));+ await expect.poll(async () => (await centerPixel(page))[0]).toBeLessThan(120);+ 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;+ await expect+ .poll(async () => Math.abs((await centerPixel(page))[0] - expected))+ .toBeLessThan(2);+ await page.evaluate(() => window.openlight.setCurve());+ await expect+ .poll(() => page.locator("canvas").screenshot())+ .toEqual(adjustedPreview);+ await page.evaluate(() => window.openlight.setAdjustments({ exposure: 0 }));+ await expect+ .poll(() => page.locator("canvas").screenshot())+ .toEqual(original);+ expect(errors).toEqual([]);+});++test("the curve panel edits points over a combined input histogram", async ({+ page,+}) => {+ const errors: string[] = [];+ page.on("pageerror", (error) => errors.push(error.message));+ page.on("console", (message) => {+ if (message.type() === "error") {+ errors.push(message.text());+ }+ });+ await page.goto("/");+ await page.waitForFunction(() => window.openlight);+ await page.evaluate(() =>+ window.openlight.loadImage(+ new File(+ [+ '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#808080"/></svg>',+ ],+ "gray.svg",+ { type: "image/svg+xml" },+ ),+ ),+ );+ const graph = page.getByRole("application", { name: "Tone curve" });+ await graph.scrollIntoViewIfNeeded();+ const bounds = await graph.boundingBox();+ if (!bounds) {+ throw new Error("Curve graph is not visible.");+ }+ const input = page.locator('svg[aria-label="input histogram"] polyline');+ const output = page+ .locator('svg[aria-label="output histogram"] polyline')+ .first();+ await expect(input).toHaveCount(1);+ await expect(input).toHaveAttribute("points", /,0\.0/);+ await expect(output).toHaveAttribute("points", /,0\.0/);+ const inputBefore = await input.getAttribute("points");+ const outputBefore = await output.getAttribute("points");+ await graph.click({+ position: { x: bounds.width / 2, y: bounds.height / 2 },+ });+ await expect(graph.locator("circle")).toHaveCount(3);+ await page.mouse.move(+ bounds.x + bounds.width / 2,+ bounds.y + bounds.height / 2,+ );+ await page.mouse.down();+ await page.mouse.move(+ bounds.x + bounds.width / 2,+ bounds.y + bounds.height / 4,+ { steps: 5 },+ );+ await page.mouse.up();+ const edited = await page.evaluate(+ () => window.openlight.getState().curve[1],+ );+ expect(edited.x).toBeCloseTo(0.5, 2);+ expect(edited.y).toBeCloseTo(0.75, 2);+ await expect(output).not.toHaveAttribute("points", outputBefore ?? "");+ await expect(input).toHaveAttribute("points", inputBefore ?? "");+ await expect+ .poll(async () => (await centerPixel(page))[0])+ .toBeGreaterThan(185);+ await graph.press("Shift+ArrowDown");+ expect(+ (await page.evaluate(() => window.openlight.getState().curve[1])).y,+ ).toBeCloseTo(edited.y - 0.01, 5);+ await graph.press("Delete");+ await expect(graph.locator("circle")).toHaveCount(2);+ await expect.poll(() => centerPixel(page)).toEqual([128, 128, 128, 255]);+ await graph.press("Enter");+ await expect(graph.locator("circle")).toHaveCount(3);+ await graph.press("ArrowUp");+ expect(+ (await page.evaluate(() => window.openlight.getState().curve[1])).y,+ ).toBeCloseTo(0.501, 5);+ await graph.dblclick({+ position: { x: bounds.width / 2, y: bounds.height * 0.499 },+ });+ await expect(graph.locator("circle")).toHaveCount(2);+ await page.evaluate(() =>+ window.openlight.setCurve([+ { x: 0, y: 0 },+ { x: 0.3, y: 0.4 },+ { x: 0.7, y: 0.6 },+ { x: 1, y: 1 },+ ]),+ );+ await expect(graph.locator("circle")).toHaveCount(4);+ await page.mouse.move(+ bounds.x + bounds.width * 0.3,+ bounds.y + bounds.height * 0.6,+ );+ await page.mouse.down();+ await page.mouse.move(bounds.x + bounds.width + 20, bounds.y - 20, {+ steps: 5,+ });+ await page.mouse.up();+ const constrained = await page.evaluate(+ () => window.openlight.getState().curve,+ );+ expect(constrained[1].x).toBeLessThan(constrained[2].x);+ expect(constrained[1].y).toBe(1);+ await page.mouse.move(+ bounds.x + bounds.width / 2,+ bounds.y + bounds.height / 2,+ );+ expect(await page.evaluate(() => window.openlight.getState().curve)).toEqual(+ constrained,+ );+ await page.getByRole("button", { name: "Reset curve" }).click();+ await expect(graph.locator("circle")).toHaveCount(2);+ expect(await page.evaluate(() => window.openlight.getState().curve)).toEqual([+ { x: 0, y: 0 },+ { x: 1, y: 1 },+ ]);+ await expect.poll(() => centerPixel(page)).toEqual([128, 128, 128, 255]);+ await page.evaluate(() => window.openlight.setAdjustments({ exposure: -1 }));+ await expect(input).not.toHaveAttribute("points", inputBefore ?? "");+ expect(errors).toEqual([]);+});++test("endpoints follow the edges, remap black and white, and reset on double-click", async ({+ page,+}) => {+ await page.goto("/");+ await page.waitForFunction(() => window.openlight);+ for (const example of [+ {+ color: "#000000",+ index: 0,+ start: { x: 0, y: 0 },+ vertical: { x: 0, y: 0.25 },+ horizontal: { x: 0.2, y: 0 },+ expected: 64,+ },+ {+ color: "#ffffff",+ index: 1,+ start: { x: 1, y: 1 },+ vertical: { x: 1, y: 0.75 },+ horizontal: { x: 0.8, y: 1 },+ expected: 191,+ },+ ]) {+ await page.evaluate(+ (color) =>+ window.openlight.loadImage(+ new File(+ [+ `<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="${color}"/></svg>`,+ ],+ "endpoint.svg",+ { type: "image/svg+xml" },+ ),+ ),+ example.color,+ );+ const graph = page.getByRole("application", { name: "Tone curve" });+ await graph.evaluate((element) =>+ element.scrollIntoView({ block: "center" }),+ );+ const bounds = await graph.boundingBox();+ if (!bounds) {+ throw new Error("Curve graph is not visible.");+ }+ const screen = (point: { x: number; y: number }) => ({+ x: bounds.x + point.x * bounds.width,+ y: bounds.y + (1 - point.y) * bounds.height,+ });+ const start = screen(example.start);+ const vertical = screen(example.vertical);+ const horizontal = screen(example.horizontal);+ await page.mouse.move(start.x, start.y);+ await page.mouse.down();+ await page.mouse.move(vertical.x, vertical.y, { steps: 5 });+ await page.mouse.up();+ const moved = await page.evaluate(+ (index) => window.openlight.getState().curve[index],+ example.index,+ );+ expect(moved.x).toBeCloseTo(example.vertical.x, 2);+ expect(moved.y).toBeCloseTo(example.vertical.y, 2);+ await expect+ .poll(async () =>+ Math.max(+ ...(await centerPixel(page))+ .slice(0, 3)+ .map((value) => Math.abs(value - example.expected)),+ ),+ )+ .toBeLessThan(2);+ await graph.dblclick({+ position: {+ x: example.vertical.x * bounds.width,+ y: (1 - example.vertical.y) * bounds.height,+ },+ });+ await expect(graph.locator("circle")).toHaveCount(2);+ expect(+ await page.evaluate(+ (index) => window.openlight.getState().curve[index],+ example.index,+ ),+ ).toEqual(example.start);+ await page.mouse.move(start.x, start.y);+ await page.mouse.down();+ await page.mouse.move(horizontal.x, horizontal.y, { steps: 5 });+ await page.mouse.up();+ const shifted = await page.evaluate(+ (index) => window.openlight.getState().curve[index],+ example.index,+ );+ expect(shifted.x).toBeCloseTo(example.horizontal.x, 2);+ expect(shifted.y).toBeCloseTo(example.horizontal.y, 2);+ await graph.dblclick({+ position: {+ x: example.horizontal.x * bounds.width,+ y: (1 - example.horizontal.y) * bounds.height,+ },+ });+ expect(+ await page.evaluate(() => window.openlight.getState().curve),+ ).toEqual([+ { x: 0, y: 0 },+ { x: 1, y: 1 },+ ]);+ }+});diff --git a/tests/curves.test.ts b/tests/curves.test.tsnew file mode 100644index 0000000..c85b2ea--- /dev/null+++ b/tests/curves.test.ts@@ -0,0 +1,57 @@+import { expect, test } from "@playwright/test";+import { interpolateCurve, sampleCurve } from "@/lib/curves";++test("the diagonal samples to identity, including black and white", () => {+ const points = [+ { x: 0, y: 0 },+ { x: 1, y: 1 },+ ];+ const samples = sampleCurve(points, 257);+ expect(samples).toBeInstanceOf(Float32Array);+ for (let i = 0; i < samples.length; i++) {+ expect(samples[i]).toBeCloseTo(i / 256, 7);+ }+});++test("a midtone lift interpolates the handles with a smooth cubic", () => {+ const evaluate = interpolateCurve([+ { x: 0, y: 0 },+ { x: 0.5, y: 0.75 },+ { x: 1, y: 1 },+ ]);+ expect(evaluate(0.25)).toBeCloseTo(0.453125, 7);+ expect(evaluate(0.5)).toBe(0.75);+ expect(evaluate(0.75)).toBeCloseTo(0.921875, 7);+ expect(evaluate(-1)).toBe(0);+ expect(evaluate(2)).toBe(1);+ const leftSlope = (evaluate(0.5) - evaluate(0.5 - 0.00001)) / 0.00001;+ const rightSlope = (evaluate(0.5 + 0.00001) - evaluate(0.5)) / 0.00001;+ expect(leftSlope).toBeCloseTo(rightSlope, 3);+});++test("unevenly spaced points, plateaus, and reversals do not overshoot", () => {+ const points = [+ { x: 0, y: 0 },+ { x: 0.02, y: 0.4 },+ { x: 0.3, y: 0.4 },+ { x: 0.7, y: 0.2 },+ { x: 0.99, y: 0.95 },+ { x: 1, y: 1 },+ ];+ const evaluate = interpolateCurve(points);+ for (let i = 0; i < points.length - 1; i++) {+ const start = points[i];+ const end = points[i + 1];+ expect(evaluate(start.x)).toBeCloseTo(start.y, 10);+ let previous = start.y;+ for (let step = 1; step <= 100; step++) {+ const value = evaluate(start.x + ((end.x - start.x) * step) / 100);+ expect(value).toBeGreaterThanOrEqual(Math.min(start.y, end.y) - 1e-12);+ expect(value).toBeLessThanOrEqual(Math.max(start.y, end.y) + 1e-12);+ expect(+ (value - previous) * Math.sign(end.y - start.y),+ ).toBeGreaterThanOrEqual(-1e-12);+ previous = value;+ }+ }+});