Free open-source image editor for the browser
Add light adjustments
Rodrigob308a9cdd268
diff --git a/README.md b/README.mdindex be7411f..6fe64a6 100644--- a/README.md+++ b/README.md@@ -37,6 +37,7 @@ await openlight.openFiles([new File([xmpText], "photo.xmp"),]);openlight.setAdjustments({ exposure: 1, saturation: -25 });+openlight.setAdjustments({ highlights: -50, shadows: 50, whites: 10, blacks: -10 });const state = // Or read immediately: openlight.getState()```@@ -56,5 +57,11 @@ scene store owns document state and generic editing actions, without file loader`setAdjustments` merges a partial update. Exposure accepts -5 to 5; otheradjustments accept -100 to 100. Loading another image resets adjustments.+The four tone controls follow Camera Raw XMP's units and direction. Each effect+is owned by its matching WGSL file in `src/lib/adjustments/`.+Whites and blacks move their endpoints along monotone cubic curves in perceptual+space, leaving middle gray fixed. At full strength the endpoint moves by 0.1.+Highlights and shadows use pointwise curves fitted against Lightroom exports;+they do not yet model Lightroom's spatial processing.State includes the file name and adjustments. Loading commands resolve when theirbatch finishes; image decoding failures appear in the editor. The renderer runs every frame.diff --git a/src/app/editor/renderer/renderer.ts b/src/app/editor/renderer/renderer.tsindex 22390f0..35dd0ee 100644--- a/src/app/editor/renderer/renderer.ts+++ b/src/app/editor/renderer/renderer.ts@@ -5,20 +5,17 @@ import {type Gpu,sampler,type Target,- 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 { createAdjustments } from "@/lib/adjustments";import shader from "./renderer.wgsl";/** 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 adjust = effect(gpu, adjustmentsShader, {- set: { sourceSampler: sampler(gpu) },- });+ const adjust = createAdjustments(gpu, source);+ const adjusted = adjust.output;const toneCurves = createToneCurves(gpu, adjusted);const display = effect(gpu, shader, {set: {@@ -43,10 +40,7 @@ export function createRenderer(gpu: Gpu, source: Target) {},update(scene: Scene) {frame(gpu, (frame) => {- frame.pass(- adjusted,- adjust.set({ source: source.color, adjustments: scene.adjustments }),- );+ adjust.render(frame, scene.adjustments);output = toneCurves.render(frame, scene.toneCurve);});rendered = true;@@ -73,7 +67,7 @@ export function createRenderer(gpu: Gpu, source: Target) {},dispose() {listeners.clear();- adjusted.color.dispose();+ adjust.dispose();toneCurves.dispose();},};diff --git a/src/app/editor/sidebar/adjustment-controls.tsx b/src/app/editor/sidebar/adjustment-controls.tsxindex c826eab..b453477 100644--- a/src/app/editor/sidebar/adjustment-controls.tsx+++ b/src/app/editor/sidebar/adjustment-controls.tsx@@ -43,7 +43,7 @@ function AdjustmentSlider({ name, ...props }: AdjustmentSliderProps) {export default function AdjustmentControls() {return (- <section className="flex flex-col gap-3 p-4 shadow-ridge">+ <section className="flex flex-col gap-2 p-4 shadow-ridge"><AdjustmentSlider name="exposure" label="Exposure" step={0.01} /><AdjustmentSlidername="incrementalTemperature"@@ -56,6 +56,10 @@ export default function AdjustmentControls() {stops={stops.incrementalTint}/><AdjustmentSlider name="contrast" label="Contrast" />+ <AdjustmentSlider name="highlights" label="Highlights" />+ <AdjustmentSlider name="shadows" label="Shadows" />+ <AdjustmentSlider name="whites" label="Whites" />+ <AdjustmentSlider name="blacks" label="Blacks" /><AdjustmentSlidername="vibrance"label="Vibrance"diff --git a/src/app/loaders/camera-raw-xmp.ts b/src/app/loaders/camera-raw-xmp.tsindex ee0f626..af93898 100644--- a/src/app/loaders/camera-raw-xmp.ts+++ b/src/app/loaders/camera-raw-xmp.ts@@ -7,12 +7,19 @@ import {import type { FileLoader } from "./registry";function toAdjustments(xmp: CameraRawXmp): Partial<Adjustments> {- return {- ...(xmp.exposure2012 === undefined ? {} : { exposure: xmp.exposure2012 }),- ...(xmp.contrast2012 === undefined ? {} : { contrast: xmp.contrast2012 }),- ...(xmp.vibrance === undefined ? {} : { vibrance: xmp.vibrance }),- ...(xmp.saturation === undefined ? {} : { saturation: xmp.saturation }),+ const adjustments: Partial<Adjustments> = {+ exposure: xmp.exposure2012,+ contrast: xmp.contrast2012,+ highlights: xmp.highlights2012,+ shadows: xmp.shadows2012,+ whites: xmp.whites2012,+ blacks: xmp.blacks2012,+ vibrance: xmp.vibrance,+ saturation: xmp.saturation,};+ return Object.fromEntries(+ Object.entries(adjustments).filter(([, value]) => value !== undefined),+ );}async function importCameraRawXmp(file: File) {diff --git a/src/app/scene/index.ts b/src/app/scene/index.tsindex de371c5..2dd56a8 100644--- a/src/app/scene/index.ts+++ b/src/app/scene/index.ts@@ -6,21 +6,19 @@ import {validateCurve,} from "@/features/tone-curves/curve";-/** Non-destructive edits: exposure in stops, the rest -100..100. */-export type Adjustments = {- exposure: number;- incrementalTemperature: number;- incrementalTint: number;- contrast: number;- vibrance: number;- saturation: number;-};+import type { Adjustments } from "@/lib/adjustments";++export type { Adjustments } from "@/lib/adjustments";export const defaultAdjustments: Adjustments = {exposure: 0,incrementalTemperature: 0,incrementalTint: 0,contrast: 0,+ highlights: 0,+ shadows: 0,+ whites: 0,+ blacks: 0,vibrance: 0,saturation: 0,};@@ -30,6 +28,10 @@ export const adjustmentLimits: Adjustments = {incrementalTemperature: 100,incrementalTint: 100,contrast: 100,+ highlights: 100,+ shadows: 100,+ whites: 100,+ blacks: 100,vibrance: 100,saturation: 100,};diff --git a/src/features/camera-raw-xmp/xmp.ts b/src/features/camera-raw-xmp/xmp.tsindex f063a24..815d4c7 100644--- a/src/features/camera-raw-xmp/xmp.ts+++ b/src/features/camera-raw-xmp/xmp.ts@@ -4,6 +4,10 @@ const rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";export type CameraRawXmp = {exposure2012?: number;contrast2012?: number;+ highlights2012?: number;+ shadows2012?: number;+ whites2012?: number;+ blacks2012?: number;vibrance?: number;saturation?: number;};@@ -11,6 +15,10 @@ export type CameraRawXmp = {const attributes = {Exposure2012: "exposure2012",Contrast2012: "contrast2012",+ Highlights2012: "highlights2012",+ Shadows2012: "shadows2012",+ Whites2012: "whites2012",+ Blacks2012: "blacks2012",Vibrance: "vibrance",Saturation: "saturation",} as const satisfies Record<string, keyof CameraRawXmp>;diff --git a/src/lib/adjustments/adjustments.wgsl b/src/lib/adjustments/adjustments.wgslindex dc60f77..f370c37 100644--- a/src/lib/adjustments/adjustments.wgsl+++ b/src/lib/adjustments/adjustments.wgsl@@ -1,40 +1,19 @@-struct Adjustments {- exposure: f32,- incrementalTemperature: f32,- incrementalTint: f32,- contrast: f32,- vibrance: f32,- saturation: f32,-}+import { luminance } from "../color.wgsl";+import { adjustBlacks } from "./blacks.wgsl";+import { adjustHighlights } from "./highlights.wgsl";+import { adjustShadows } from "./shadows.wgsl";+import { adjustWhites } from "./whites.wgsl";+import { Adjustments, prepareColor } from "./prepare.wgsl";@group(0) @binding(0) var source: texture_2d<f32>;@group(0) @binding(1) var sourceSampler: sampler;@group(0) @binding(2) var<uniform> adjustments: Adjustments;-// All adjustment functions accept and return linear Rec.2020.-fn adjustExposure(color: vec3f, stops: f32) -> vec3f {- let bounded = clamp(color, vec3f(0.0), vec3f(1.0));- if stops < 0.0 {- return exp2(stops * 1.09) * pow(bounded, vec3f(exp2(-stops * 0.14)));- }- let gain = mix(vec2f(1.11, -0.11) * min(stops, 1.0), vec2f(4.05, -0.63), max(stops - 1.0, 0.0) / 4.0);- return 1.0 - pow(1.0 - pow(bounded, vec3f(exp2(gain.y))), vec3f(exp2(gain.x)));-}-fn interpolateGain(amount: f32, half: vec3f, full: vec3f) -> vec3f {let strength = 2.0 * abs(amount);return mix(half * min(strength, 1.0), full, max(strength - 1.0, 0.0));}-fn adjustWhiteBalance(color: vec3f, temperature: f32, tint: f32) -> vec3f {- let warmth = vec3f(2.50, 1.19, -1.89) * temperature- + (vec3f(1.55, 1.89, 2.93) + vec3f(-1.47, -1.05, -0.69) * temperature) * abs(temperature);- let tintGain = (vec3f(0.53, -0.59, 1.02) + vec3f(0.64, 0.94, 1.35) * tint) * tint;- let gain = warmth + tintGain;- let bounded = min(color, vec3f(1.0));- return bounded / (bounded + (1.0 - bounded) * exp2(-gain)) + (color - bounded);-}-fn adjustContrast(color: vec3f, amount: f32) -> vec3f {let positive = interpolateGain(amount - 1.0, vec3f(0.32, 1.48, 0.0), vec3f(0.59, 2.77, 0.0)).xy;let gain = select(positive, vec2f(-0.43, -2.51) * (1.0 - amount), amount < 1.0);@@ -43,8 +22,8 @@ fn adjustContrast(color: vec3f, amount: f32) -> vec3f {}fn adjustSaturation(color: vec3f, amount: f32) -> vec3f {- let luminance = dot(color, vec3f(0.2627, 0.6780, 0.0593));- return vec3f(luminance) + (color - vec3f(luminance)) * amount;+ let gray = vec3f(luminance(color));+ return gray + (color - gray) * amount;}fn adjustVibrance(color: vec3f, amount: f32) -> vec3f {@@ -58,9 +37,11 @@ fn adjustVibrance(color: vec3f, amount: f32) -> vec3f {@fragmentfn fs_main(@location(0) uv: vec2f) -> @location(0) vec4f {let input = textureSample(source, sourceSampler, uv);- var color = input.rgb;- color = adjustExposure(color, adjustments.exposure);- color = adjustWhiteBalance(color, adjustments.incrementalTemperature / 100.0, adjustments.incrementalTint / 100.0);+ let prepared = prepareColor(input.rgb, adjustments);+ var color = adjustHighlights(prepared, adjustments.highlights);+ color = adjustShadows(color, adjustments.shadows);+ color = adjustWhites(color, adjustments.whites);+ color = adjustBlacks(color, adjustments.blacks);color = adjustContrast(color, 1.0 + adjustments.contrast / 100.0);color = adjustVibrance(color, adjustments.vibrance / 100.0);color = adjustSaturation(color, 1.0 + adjustments.saturation / 100.0);diff --git a/src/lib/adjustments/blacks.wgsl b/src/lib/adjustments/blacks.wgslnew file mode 100644index 0000000..391d1d1--- /dev/null+++ b/src/lib/adjustments/blacks.wgsl@@ -0,0 +1,16 @@+import { linearToSrgb, srgbToLinear } from "@vgpu/wgsl-std/color";+import { luminance } from "../color.wgsl";+import { endpointCurve, remapLuminance } from "./endpoint.wgsl";++// Shift the endpoint by up to 0.1 in perceptual space; amount is -100..100.+export fn adjustBlacks(color: vec3f, amount: f32) -> vec3f {+ if amount == 0.0 {+ return color;+ }+ let light = linearToSrgb(luminance(color));+ if light >= 0.5 {+ return color;+ }+ let mapped = endpointCurve(light, amount / 100.0 * 0.1);+ return remapLuminance(color, srgbToLinear(mapped));+}diff --git a/src/lib/adjustments/endpoint.wgsl b/src/lib/adjustments/endpoint.wgslnew file mode 100644index 0000000..3d2d304--- /dev/null+++ b/src/lib/adjustments/endpoint.wgsl@@ -0,0 +1,22 @@+import { luminance } from "../color.wgsl";++// In perceptual 0..1: move the black endpoint horizontally or vertically,+// joining the identity at 0.5 with slope 1. Whites use the mirrored curve.+export fn endpointCurve(value: f32, offset: f32) -> f32 {+ let start = max(-offset, 0.0);+ let t = clamp((value - start) / (0.5 - start), 0.0, 1.0);+ return max(value, start) + offset * (1.0 - t) * (1.0 - t) * (1.0 + 2.0 * t);+}++// Move towards neutral white when brightening and neutral black when darkening.+// This also handles a lifted pure black or a clipped colored highlight.+export fn remapLuminance(color: vec3f, mapped: f32) -> vec3f {+ let light = luminance(color);+ if mapped > light {+ return mix(color, vec3f(1.0), (mapped - light) / (1.0 - light));+ }+ if mapped < light {+ return color * (mapped / light);+ }+ return color;+}diff --git a/src/lib/adjustments/highlights.wgsl b/src/lib/adjustments/highlights.wgslnew file mode 100644index 0000000..5788790--- /dev/null+++ b/src/lib/adjustments/highlights.wgsl@@ -0,0 +1,33 @@+import { linearToSrgb } from "@vgpu/wgsl-std/color";+import { luminance } from "../color.wgsl";++fn highlightCompression(tone: f32) -> f32 {+ let mask = smoothstep(0.0, 0.25, tone);+ let curve = 0.5 + tone * (1.0 - tone) *+ (-0.89 + tone * (-1.1 + tone * 6.44));+ let tail = smoothstep(0.95, 1.0, tone);+ return mask * curve - 0.2 * tail * tail * tail;+}++export fn adjustHighlights(color: vec3f, amount: f32) -> vec3f {+ if amount == 0.0 { return color; }+ let light = clamp(luminance(color), 0.0, 1.0);+ let strength = abs(amount) / 100.0;+ if amount < 0.0 {+ let tone = linearToSrgb(light);+ let gain = exp2(-highlightCompression(tone));+ // Preserve more chroma in bright colors, without clipping to a display gamut.+ let chroma = pow(gain, 1.0 - 0.76 * smoothstep(0.5, 1.0, tone));+ let gray = vec3f(luminance(color));+ let endpoint = gray * gain + (color - gray) * chroma;+ return mix(color, endpoint, strength);+ }+ // Positive endpoint still fitted only to fixture ramps.+ let mask = smoothstep(0.0, 0.175, linearToSrgb(light));+ let curve = 0.38 + 2.42 * light * light;+ let stops = mask * curve;+ // Limit of the shoulder near black avoids subtraction cancellation.+ if light < 0.0001 { return color * mix(1.0, exp2(stops), strength); }+ let mapped = 1.0 - pow(1.0 - light, exp2(stops));+ return color * mix(1.0, mapped / light, strength);+}diff --git a/src/lib/adjustments/index.ts b/src/lib/adjustments/index.tsnew file mode 100644index 0000000..bce8658--- /dev/null+++ b/src/lib/adjustments/index.ts@@ -0,0 +1,46 @@+import {+ effect,+ type Frame,+ type Gpu,+ sampler,+ type Target,+ target,+} from "vgpu";+import shader from "./adjustments.wgsl";++/** UI units: exposure in stops, every other adjustment in -100..100. */+export type Adjustments = {+ exposure: number;+ incrementalTemperature: number;+ incrementalTint: number;+ contrast: number;+ highlights: number;+ shadows: number;+ whites: number;+ blacks: number;+ vibrance: number;+ saturation: number;+};++/** Owns the adjustment pass and output for one source. */+export function createAdjustments(gpu: Gpu, source: Target) {+ const output = target(gpu, { size: source.size, format: source.format });+ const apply = effect(gpu, shader, {+ set: {+ source: source.color,+ sourceSampler: sampler(gpu, {+ minFilter: "linear",+ magFilter: "linear",+ }),+ },+ });+ return {+ output,+ render(frame: Frame, adjustments: Adjustments) {+ frame.pass(output, apply.set({ adjustments }));+ },+ dispose() {+ output.color.dispose();+ },+ };+}diff --git a/src/lib/adjustments/prepare.wgsl b/src/lib/adjustments/prepare.wgslnew file mode 100644index 0000000..4465c9f--- /dev/null+++ b/src/lib/adjustments/prepare.wgsl@@ -0,0 +1,36 @@+export struct Adjustments {+ exposure: f32,+ incrementalTemperature: f32,+ incrementalTint: f32,+ contrast: f32,+ highlights: f32,+ shadows: f32,+ whites: f32,+ blacks: f32,+ vibrance: f32,+ saturation: f32,+}++// Source preparation in linear Rec.2020; retain the calibrated constants.+fn adjustExposure(color: vec3f, stops: f32) -> vec3f {+ let bounded = clamp(color, vec3f(0.0), vec3f(1.0));+ if stops < 0.0 {+ return exp2(stops * 1.09) * pow(bounded, vec3f(exp2(-stops * 0.14)));+ }+ let gain = mix(vec2f(1.11, -0.11) * min(stops, 1.0), vec2f(4.05, -0.63), max(stops - 1.0, 0.0) / 4.0);+ return 1.0 - pow(1.0 - pow(bounded, vec3f(exp2(gain.y))), vec3f(exp2(gain.x)));+}++fn adjustWhiteBalance(color: vec3f, temperature: f32, tint: f32) -> vec3f {+ let warmth = vec3f(2.50, 1.19, -1.89) * temperature+ + (vec3f(1.55, 1.89, 2.93) + vec3f(-1.47, -1.05, -0.69) * temperature) * abs(temperature);+ let tintGain = (vec3f(0.53, -0.59, 1.02) + vec3f(0.64, 0.94, 1.35) * tint) * tint;+ let gain = warmth + tintGain;+ let bounded = min(color, vec3f(1.0));+ return bounded / (bounded + (1.0 - bounded) * exp2(-gain)) + (color - bounded);+}++export fn prepareColor(color: vec3f, adjustments: Adjustments) -> vec3f {+ return adjustWhiteBalance(adjustExposure(color, adjustments.exposure),+ adjustments.incrementalTemperature / 100.0, adjustments.incrementalTint / 100.0);+}diff --git a/src/lib/adjustments/shadows.wgsl b/src/lib/adjustments/shadows.wgslnew file mode 100644index 0000000..33f16ce--- /dev/null+++ b/src/lib/adjustments/shadows.wgsl@@ -0,0 +1,25 @@+import { linearToSrgb, srgbToLinear } from "@vgpu/wgsl-std/color";+import { luminance } from "../color.wgsl";++fn liftedShadow(tone: f32) -> f32 {+ let inverse = 1.0 - tone;+ let shape = 0.95 + tone * (-3.0 + 3.28 * tone);+ return tone + sqrt(tone) * inverse * inverse * shape;+}++fn crushedShadow(tone: f32) -> f32 {+ let shape = -2.21 + tone * (6.91 - 7.12 * tone);+ return tone + pow(tone, 1.25) * pow(1.0 - tone, 2.25) * shape;+}++export fn adjustShadows(color: vec3f, amount: f32) -> vec3f {+ if amount == 0.0 { return color; }+ let light = clamp(luminance(color), 0.0, 1.0);+ if light == 0.0 { return color; }+ let tone = linearToSrgb(light);+ let endpointStrength = select(1.0, 0.25, amount > 0.0);+ let strength = abs(amount) / 100.0 * endpointStrength;+ let mappedTone = select(crushedShadow(tone), liftedShadow(tone), amount > 0.0);+ let gain = srgbToLinear(mappedTone) / light;+ return color * mix(1.0, gain, strength);+}diff --git a/src/lib/adjustments/whites.wgsl b/src/lib/adjustments/whites.wgslnew file mode 100644index 0000000..7fde08d--- /dev/null+++ b/src/lib/adjustments/whites.wgsl@@ -0,0 +1,16 @@+import { linearToSrgb, srgbToLinear } from "@vgpu/wgsl-std/color";+import { luminance } from "../color.wgsl";+import { endpointCurve, remapLuminance } from "./endpoint.wgsl";++// Shift the endpoint by up to 0.1 in perceptual space; amount is -100..100.+export fn adjustWhites(color: vec3f, amount: f32) -> vec3f {+ if amount == 0.0 {+ return color;+ }+ let light = linearToSrgb(luminance(color));+ if light <= 0.5 {+ return color;+ }+ let mapped = 1.0 - endpointCurve(1.0 - light, -amount / 100.0 * 0.1);+ return remapLuminance(color, srgbToLinear(mapped));+}diff --git a/src/lib/color.wgsl b/src/lib/color.wgslindex e8fd090..e64d957 100644--- a/src/lib/color.wgsl+++ b/src/lib/color.wgsl@@ -1,5 +1,9 @@import { linearToSrgb3 } from "@vgpu/wgsl-std/color";+export fn luminance(color: vec3f) -> f32 {+ return dot(color, vec3f(0.2627, 0.6780, 0.0593));+}+// The working space is linear Rec.2020; these convert its primaries to and from linear sRGB and Display P3 (column-major).export const srgbToRec2020 = mat3x3f(0.6274, 0.0691, 0.0164,diff --git a/tests/endpoints.e2e.ts b/tests/endpoints.e2e.tsnew file mode 100644index 0000000..b1e3c1c--- /dev/null+++ b/tests/endpoints.e2e.ts@@ -0,0 +1,104 @@+import { expect, test } from "@playwright/test";++test("black and white points preserve midgray, clip or lift endpoints, and reset", 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);+ const outputs = await page.evaluate(async () => {+ const canvas = new OffscreenCanvas(256, 2);+ const context = canvas.getContext("2d");+ if (!context) throw new Error("Cannot create tone ramp.");+ const pixels = context.createImageData(256, 2);+ for (let x = 0; x < 256; x++) {+ pixels.data.set([x, x, x, 255], x * 4);+ pixels.data.set(+ [x, Math.max(0, x - 10), Math.max(0, x - 20), 255],+ (256 + x) * 4,+ );+ }+ context.putImageData(pixels, 0, 0);+ await window.openlight.loadImage(+ new File([await canvas.convertToBlob()], "ramp.png", {+ type: "image/png",+ }),+ );+ const outputs = [];+ for (const [whites, blacks] of [+ [0, 0],+ [100, 0],+ [-100, 0],+ [0, -100],+ [0, 100],+ [100, -100],+ [-100, 100],+ [0, 0],+ ]) {+ window.openlight.setAdjustments({ whites, blacks });+ const image = await createImageBitmap(+ await window.openlight.exportImage(),+ );+ context.drawImage(image, 0, 0);+ image.close();+ outputs.push([...context.getImageData(0, 0, 256, 2).data]);+ }+ return outputs;+ });+ const [+ original,+ whiteClip,+ whiteLower,+ blackClip,+ blackLift,+ clipped,+ compressed,+ reset,+ ] = outputs;+ for (const output of outputs) {+ for (let x = 0; x < 256; x++) {+ const [red, green, blue, alpha] = output.slice(x * 4, x * 4 + 4);+ expect(+ Math.max(red, green, blue) - Math.min(red, green, blue),+ ).toBeLessThanOrEqual(1);+ expect(alpha).toBe(255);+ if (x > 0) {+ const step = red - output[(x - 1) * 4];+ expect(step).toBeGreaterThanOrEqual(0);+ expect(step).toBeLessThanOrEqual(3);+ }+ }+ expect(output.slice(128 * 4, 128 * 4 + 4)).toEqual([128, 128, 128, 255]);+ }+ for (let x = 0; x < 256; x++) {+ expect(original[x * 4]).toBe(x);+ if (x <= 127) expect(whiteClip[x * 4]).toBe(x);+ if (x <= 127) expect(whiteLower[x * 4]).toBe(x);+ if (x >= 128) expect(blackClip[x * 4]).toBe(x);+ if (x >= 128) expect(blackLift[x * 4]).toBe(x);+ }+ for (const output of [whiteClip, clipped]) {+ expect(output[230 * 4]).toBe(255);+ expect(output.slice((256 + 255) * 4)).toEqual([255, 255, 255, 255]);+ }+ for (const output of [blackClip, clipped]) {+ expect(output[25 * 4]).toBe(0);+ expect(output.slice((256 + 25) * 4, (256 + 26) * 4)).toEqual([+ 0, 0, 0, 255,+ ]);+ }+ for (const output of [blackLift, compressed]) {+ expect(output[0]).toBeGreaterThanOrEqual(25);+ expect(output[0]).toBeLessThanOrEqual(26);+ }+ for (const output of [whiteLower, compressed]) {+ expect(output[255 * 4]).toBeGreaterThanOrEqual(229);+ expect(output[255 * 4]).toBeLessThanOrEqual(230);+ }+ expect(reset).toEqual(original);+ expect(errors).toEqual([]);+});diff --git a/tests/export.e2e.ts b/tests/export.e2e.tsindex e64b527..14146ae 100644--- a/tests/export.e2e.ts+++ b/tests/export.e2e.ts@@ -36,7 +36,13 @@ test("exports full-resolution PNGs with current edits through the API and button});expect(original).toEqual([128, 128, 128, 255]);await page.evaluate(() => {- window.openlight.setAdjustments({ exposure: 1 });+ window.openlight.setAdjustments({+ exposure: 1,+ highlights: -20,+ shadows: 30,+ whites: 10,+ blacks: -5,+ });window.openlight.setToneCurve([{ x: 0, y: 0 },{ x: 0.5, y: 0.75 },diff --git a/tests/highlights-shadows.e2e.ts b/tests/highlights-shadows.e2e.tsnew file mode 100644index 0000000..e13a23a--- /dev/null+++ b/tests/highlights-shadows.e2e.ts@@ -0,0 +1,167 @@+import { expect, test } from "@playwright/test";++function linear(value: number) {+ const encoded = value / 255;+ return encoded <= 0.04045+ ? encoded / 12.92+ : ((encoded + 0.055) / 1.055) ** 2.4;+}++test("highlights preserve ramps, compose with preparation, and reset", 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);+ const result = await page.evaluate(async () => {+ // The same bright patch appears on two backgrounds, above a translucent row.+ const width = 1025;+ const height = 513;+ const canvas = new OffscreenCanvas(width, height);+ const context = canvas.getContext("2d");+ if (!context) throw new Error("Cannot create highlights fixture.");+ const pixels = context.createImageData(width, height);+ for (let y = 0; y < height; y++) {+ for (let x = 0; x < width; x++) {+ const patch = Math.abs(x - 256) < 32 || Math.abs(x - 768) < 32;+ const background = x < 512 ? 64 : 248;+ let value = patch && Math.abs(y - 256) < 32 ? 240 : background;+ if (y < 64) value = Math.round((x * 255) / (width - 1));+ pixels.data.set(+ [value, value, value, y === height - 1 ? 128 : 255],+ (y * width + x) * 4,+ );+ }+ }+ context.putImageData(pixels, 0, 0);+ context.fillStyle = "rgb(200, 230, 200)";+ context.fillRect(0, height - 2, width, 1);+ const file = new File([await canvas.convertToBlob()], "contexts.png", {+ type: "image/png",+ });+ const read = async () => {+ const bitmap = await createImageBitmap(+ await window.openlight.exportImage(),+ );+ context.clearRect(0, 0, width, height);+ context.drawImage(bitmap, 0, 0);+ bitmap.close();+ return [...context.getImageData(0, 0, width, height).data];+ };+ await window.openlight.loadImage(file);+ const neutral = await read();+ window.openlight.setAdjustments({ highlights: -100 });+ const negative = await read();+ window.openlight.setAdjustments({ highlights: -50 });+ const half = await read();+ window.openlight.setAdjustments({ highlights: 100 });+ const positive = await read();+ window.openlight.setAdjustments({ highlights: 0, shadows: 100 });+ const liftedShadows = await read();+ window.openlight.setAdjustments({ shadows: 50 });+ const halfShadows = await read();+ const prepared = {+ highlights: -75,+ shadows: 0,+ exposure: 0.4,+ incrementalTemperature: 20,+ incrementalTint: -12,+ };+ window.openlight.setAdjustments(prepared);+ const changed = await read();+ await window.openlight.loadImage(file);+ window.openlight.setAdjustments(prepared);+ const fresh = await read();+ window.openlight.setAdjustments({+ highlights: 0,+ exposure: 0,+ incrementalTemperature: 0,+ incrementalTint: 0,+ });+ const reset = await read();+ const patchIndices = [226, 738].map((x) => (256 * width + x) * 4);+ return {+ neutral: patchIndices.map((i) => neutral[i]),+ negative: patchIndices.map((i) => negative[i]),+ positive: patchIndices.map((i) => positive[i]),+ shadowRamps: [halfShadows, liftedShadows].map((output) =>+ Array.from({ length: width }, (_, x) => output[(32 * width + x) * 4]),+ ),+ reloadMatches: changed.every((value, i) => value === fresh[i]),+ ramps: [neutral, negative, half, positive].map((output) =>+ Array.from({ length: width }, (_, x) => output[(32 * width + x) * 4]),+ ),+ resetMatches: reset.every((value, i) => value === neutral[i]),+ alphaMatches: [negative, positive, changed, fresh].every((output) =>+ output.every((value, i) => i % 4 !== 3 || value === neutral[i]),+ ),+ neutralColors: [negative, positive].every((output) =>+ output+ .slice(32 * width * 4, 33 * width * 4)+ .every(+ (value, i) =>+ i % 4 === 3 || Math.abs(value - output[i - (i % 4)]) <= 1,+ ),+ ),+ pastel: [neutral, negative, half].map((output) =>+ output.slice((height - 2) * width * 4, (height - 2) * width * 4 + 3),+ ),+ };+ });+ expect(result.neutral).toEqual([240, 240]);+ expect(result.positive[0]).toBe(result.positive[1]);+ for (const value of result.negative) expect(value).toBeLessThan(240);+ for (const value of result.positive) expect(value).toBeGreaterThan(240);+ const [neutral, negative, half, positive] = result.ramps;+ const [halfShadows, liftedShadows] = result.shadowRamps;+ for (const ramp of result.ramps) {+ expect(ramp[0]).toBe(0);+ for (let x = 1; x < ramp.length; x++) {+ expect(ramp[x] - ramp[x - 1]).toBeGreaterThanOrEqual(-1);+ expect(ramp[x] - ramp[x - 1]).toBeLessThanOrEqual(6);+ }+ }+ for (let x = 0; x < neutral.length; x++) {+ expect(liftedShadows[x]).toBeGreaterThanOrEqual(neutral[x]);+ expect(halfShadows[x]).toBeGreaterThanOrEqual(neutral[x]);+ expect(halfShadows[x]).toBeLessThanOrEqual(liftedShadows[x]);+ expect(+ Math.abs(+ linear(halfShadows[x]) -+ (linear(neutral[x]) + linear(liftedShadows[x])) / 2,+ ),+ ).toBeLessThan(0.01);+ }+ expect(liftedShadows[0]).toBe(0);+ expect(liftedShadows.at(-1)).toBe(255);+ for (let x = 0; x < neutral.length; x++) {+ expect(negative[x]).toBeLessThanOrEqual(half[x]);+ expect(half[x]).toBeLessThanOrEqual(neutral[x]);+ expect(positive[x]).toBeGreaterThanOrEqual(neutral[x]);+ expect(+ Math.abs(+ linear(half[x]) - (linear(neutral[x]) + linear(negative[x])) / 2,+ ),+ ).toBeLessThan(0.01);+ }+ expect(result.reloadMatches).toBe(true);+ expect(result.resetMatches).toBe(true);+ expect(result.alphaMatches).toBe(true);+ expect(result.neutralColors).toBe(true);+ const [pastel, darkened, halfway] = result.pastel;+ expect(Math.abs(darkened[0] - darkened[2])).toBeLessThanOrEqual(1);+ for (let channel = 0; channel < 3; channel++) {+ expect(darkened[channel]).toBeLessThan(pastel[channel]);+ expect(+ Math.abs(+ linear(halfway[channel]) -+ (linear(pastel[channel]) + linear(darkened[channel])) / 2,+ ),+ ).toBeLessThan(0.01);+ }+ expect(errors).toEqual([]);+});diff --git a/tests/loaders.e2e.ts b/tests/loaders.e2e.tsindex 218cf64..799bb2f 100644--- a/tests/loaders.e2e.ts+++ b/tests/loaders.e2e.ts@@ -44,7 +44,7 @@ test("file batches load one image before its settings, regardless of file order"for (const settingsFirst of [true, false]) {const parameters = settings(- 'crs:Exposure2012="1.25" crs:Contrast2012="-20" crs:Vibrance="30" crs:Saturation="-10"',+ 'crs:Exposure2012="1.25" crs:Contrast2012="-20" crs:Highlights2012="-50" crs:Shadows2012="50" crs:Whites2012="25" crs:Blacks2012="-25" crs:Vibrance="30" crs:Saturation="-10"',settingsFirst ? "photo.xml" : "photo.xmp",);const ignored = { name: "second.png", content: "invalid image" };@@ -57,6 +57,10 @@ test("file batches load one image before its settings, regardless of file order"adjustments: {exposure: 1.25,contrast: -20,+ highlights: -50,+ shadows: 50,+ whites: 25,+ blacks: -25,vibrance: 30,saturation: -10,},@@ -72,12 +76,27 @@ test("file batches load one image before its settings, regardless of file order"expect(partial.adjustments).toMatchObject({exposure: -1,contrast: -20,+ highlights: -50,+ shadows: 50,+ whites: 25,+ blacks: -25,vibrance: 30,saturation: -10,});await expect.poll(() => page.locator("canvas").screenshot()).not.toEqual(before);+ const reset = await openFiles(page, [+ settings(+ 'crs:Highlights2012="0" crs:Shadows2012="0" crs:Whites2012="0" crs:Blacks2012="0"',+ ),+ ]);+ expect(reset.adjustments).toMatchObject({+ highlights: 0,+ shadows: 0,+ whites: 0,+ blacks: 0,+ });}});diff --git a/tests/smoke.e2e.ts b/tests/smoke.e2e.tsindex fe546c8..d2e68d7 100644--- a/tests/smoke.e2e.ts+++ b/tests/smoke.e2e.ts@@ -35,7 +35,7 @@ test("browser actions load, adjust, reset, and report failures", async ({await page.evaluate(() => {const image = new File([- '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#808080"/></svg>',+ '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#808080"/><rect width="8" height="32" fill="#202020"/><rect x="24" width="8" height="32" fill="#e0e0e0"/></svg>',],"gray.svg",{ type: "image/svg+xml" },@@ -49,6 +49,46 @@ test("browser actions load, adjust, reset, and report failures", async ({);const canvas = page.locator("canvas");const before = await canvas.screenshot();+ const toneControls = [+ { name: "highlights", label: "Highlights", x: 16, level: 128 },+ { name: "shadows", label: "Shadows", x: 16, level: 128 },+ { name: "whites", label: "Whites", x: 28, level: 224 },+ { name: "blacks", label: "Blacks", x: 4, level: 32 },+ ];+ for (const { name, label, x, level } of toneControls) {+ const slider = page.getByRole("slider", { name: label, exact: true });+ const field = page.getByRole("textbox", { name: label, exact: true });+ await expect(slider).toHaveAttribute("min", "-100");+ await expect(slider).toHaveAttribute("max", "100");+ await expect(slider).toHaveValue("0");+ const pixels: number[] = [];+ for (const value of [-100, 100]) {+ await field.fill(String(value));+ await field.press("Enter");+ await expect(slider).toHaveValue(String(value));+ const state = await page.evaluate(() => window.openlight.getState());+ expect(state.adjustments).toMatchObject({ [name]: value });+ pixels.push(+ await page.evaluate(async (x) => {+ const image = await createImageBitmap(+ await window.openlight.exportImage(),+ );+ const canvas = new OffscreenCanvas(image.width, image.height);+ const context = canvas.getContext("2d");+ if (!context) throw new Error("Cannot read exported image.");+ context.drawImage(image, 0, 0);+ image.close();+ return context.getImageData(x, 16, 1, 1).data[0];+ }, x),+ );+ }+ expect(pixels[0]).toBeLessThan(level);+ expect(pixels[1]).toBeGreaterThan(level);+ await expect.poll(() => canvas.screenshot()).not.toEqual(before);+ await slider.dblclick();+ await expect(field).toHaveValue("0");+ await expect.poll(() => canvas.screenshot()).toEqual(before);+ }const histogram = await page.locator("polyline").first()@@ -75,6 +115,12 @@ test("browser actions load, adjust, reset, and report failures", async ({});await expect.poll(() => canvas.screenshot()).toEqual(before);await page.evaluate(async () => {+ window.openlight.setAdjustments({+ highlights: -50,+ shadows: 50,+ whites: 25,+ blacks: -25,+ });const superseded = window.openlight.openFile(new File(['<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"/>'],@@ -94,7 +140,7 @@ test("browser actions load, adjust, reset, and report failures", async ({await window.openlight.openFile(new File([- '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#808080"/></svg>',+ '<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#808080"/><rect width="8" height="32" fill="#202020"/><rect x="24" width="8" height="32" fill="#e0e0e0"/></svg>',],"replacement.svg",{ type: "image/svg+xml" },@@ -103,6 +149,12 @@ test("browser actions load, adjust, reset, and report failures", async ({return window.openlight.getState();});expect(recovered.file).toBe("replacement.svg");+ expect(recovered.adjustments).toMatchObject({+ highlights: 0,+ shadows: 0,+ whites: 0,+ blacks: 0,+ });await expect.poll(() => canvas.screenshot()).toEqual(before);expect(errors).toEqual([]);});