Free open-source image editor for the browser
Add a Grain effect layer that simulates film grain (#60)
Rodrigo Belfioreb1d6f3cdb07c
diff --git a/API.md b/API.mdindex 65303a5..5e8084e 100644--- a/API.md+++ b/API.md@@ -38,7 +38,7 @@ File loads are queued; `loadUrl` starts at once, and when two opens overlap the## Editing-Commands take explicit layer IDs rather than using UI selection. Without an ID, adjustments, the tone curve, and white balance address the base image; color-mixer, Details, and vignette commands use the first matching root effect or create one at the top of the stack; effects nested in other layers stay untouched. Creation and parameter changes are one edit, respecting an open history group.+Commands take explicit layer IDs rather than using UI selection. Without an ID, adjustments, the tone curve, and white balance address the base image; color-mixer, Details, vignette, and grain commands use the first matching root effect or create one at the top of the stack; effects nested in other layers stay untouched. Creation and parameter changes are one edit, respecting an open history group.`setAdjustments(change, id?)` updates only the supplied adjustments on an image or mask. Values must be finite numbers within these inclusive ranges. Unknown names and invalid values throw.@@ -56,6 +56,8 @@ Commands take explicit layer IDs rather than using UI selection. Without an ID,`setVignette({ intensity, softness }, id?)` updates a vignette layer. Values are finite numbers from 0 to 100; defaults are intensity 0 and softness 50. Without an ID, it updates the first vignette or creates one, which starts at intensity 50 unless the change sets it. Intensity 0 bypasses the effect; increasing softness spreads the transition toward the center. The falloff stays centered on the source image before crop and rotation, independently of viewport zoom and pan. Its position among the effect layers determines processing order. It multiplies linear RGB equally and preserves alpha and HDR headroom.+`setGrain({ amount, size, roughness }, id?)` updates a Grain layer, film grain in the style of Lightroom's. Values are finite numbers from 0 to 100; defaults are amount 0, size 25, and roughness 50. Without an ID, it updates the first Grain layer or creates one, which starts at amount 25 unless the change sets it. Amount 0 bypasses the effect. The particles lie at four fixed spacings, one to eight source pixels apart: size fades the finer ones out as the coarser ones come in, rather than stretching them, and roughness mixes in neighboring spacings and varies the particles' size, so 0 is even and 100 is clumped. The grain is fixed to source pixels before crop and rotation: zoom, pan, and crop do not move it, and a full-size export matches the preview; a smaller `longEdge` averages it like any fine detail. It moves luminance only, most in the midtones and fading toward black and white, scaling the channels equally so color holds, and leaves alpha and HDR headroom unchanged.+`setFill({ color, blend }, id?)` updates a Color layer: `color` is `#rrggbb` sRGB and `blend` is `normal`, `multiply`, `screen`, `overlay`, `soft-light`, `color`, or `luminosity`. The layer paints that color over the image below it, blended as Photoshop does on encoded values, so inside a brush or gradient mask it paints the mask's coverage; the layer's opacity sets the strength. Without an ID it updates the first Color layer or creates one, which starts at `#f0763c` in Normal.Create an empty Heal effect with `addLayer("heal")`.@@ -80,7 +82,7 @@ Direct mask children of another mask modify coverage instead of processing image| Method | Behavior || --- | --- |-| `addLayer(kind, placement?)` | Adds `"exposure"`, `"color-mixer"`, `"details"`, `"vignette"`, `"fill"`, `"heal"`, or `"mask"`; selects and returns its ID. `{ inside: id }` appends a child to a processing layer; `{ above: id }` inserts directly above that layer among its siblings; without a placement, the layer goes on top of the root stack. Exposure starts at +1 EV, Vignette at intensity 50; Color Mixer, Details, Healing, and masks start neutral. |+| `addLayer(kind, placement?)` | Adds `"exposure"`, `"color-mixer"`, `"details"`, `"vignette"`, `"grain"`, `"fill"`, `"heal"`, or `"mask"`; selects and returns its ID. `{ inside: id }` appends a child to a processing layer; `{ above: id }` inserts directly above that layer among its siblings; without a placement, the layer goes on top of the root stack. Exposure starts at +1 EV, Vignette at intensity 50, Grain at amount 25; Color Mixer, Details, Healing, and masks start neutral. || `selectLayer(id)` | Selects any layer. || `setLayer(id, change)` | Updates processing-layer `name`, `visible`, or `opacity` (0–1). || `setExposure(id, value)` | Sets an Exposure layer to -5…5 EV. |@@ -158,7 +160,7 @@ The image renders at the document dimensions and downsamples to `longEdge` with`scene` is the `getState()` scene; each image layer's `source` names an entry in `sources`. Opening the file with `loadScene`, `openFile`, a drop, or the file picker decodes the stored source again and restores the frame and every layer as a new document with empty history. Preview settings and history are not saved.-Opening validates every value as the matching command does, and a file that fails leaves the workspace in its error state with a message naming the first invalid field. Fields OpenLight does not know are dropped. A parameter missing from `adjustments`, `details`, `vignette`, `fill`, or `colorMixer` takes its default, so older files still open when a group gains a parameter; a RAW image without a white balance uses its As Shot value. `version` increases only when older files can no longer open as written; a newer version is rejected.+Opening validates every value as the matching command does, and a file that fails leaves the workspace in its error state with a message naming the first invalid field. Fields OpenLight does not know are dropped. A parameter missing from `adjustments`, `details`, `vignette`, `grain`, `fill`, or `colorMixer` takes its default, so older files still open when a group gains a parameter; a RAW image without a white balance uses its As Shot value. `version` increases only when older files can no longer open as written; a newer version is rejected.## Drafts@@ -170,7 +172,7 @@ On a fresh load the start screen shows a notice in the viewport's corner with **## State-`getState()` returns a detached snapshot containing `file`, `failure`, `documentId`, `scene`, `selectedLayerId`, `size`, `frame`, `adjustments`, `whiteBalance`, `details`, `toneCurve`, `colorMixer`, `vignette`, `preview`, and `history`. `scene` contains `frame` and the layer tree. The top-level adjustment, tone-curve, and white-balance values come from `scene.layers[0]`; details, color-mixer, and vignette values describe the first matching root layer from the bottom, or its defaults. `colorMixer` contains eight-value `hue`, `saturation`, and `luminance` arrays in the color order above, defaulting to zero. `whiteBalance` contains absolute temperature/tint for RAW sources and is undefined for other sources. `file` is the open document's filename, or without one the file loading or failed, `failure` is the last file that failed to open and its error until another opens or the notice is dismissed, and `history` contains `undoCount`, `redoCount`, and `editing`, which is true while a group is open.+`getState()` returns a detached snapshot containing `file`, `failure`, `documentId`, `scene`, `selectedLayerId`, `size`, `frame`, `adjustments`, `whiteBalance`, `details`, `toneCurve`, `colorMixer`, `vignette`, `grain`, `preview`, and `history`. `scene` contains `frame` and the layer tree. The top-level adjustment, tone-curve, and white-balance values come from `scene.layers[0]`; details, color-mixer, vignette, and grain values describe the first matching root layer from the bottom, or its defaults. `colorMixer` contains eight-value `hue`, `saturation`, and `luminance` arrays in the color order above, defaulting to zero. `whiteBalance` contains absolute temperature/tint for RAW sources and is undefined for other sources. `file` is the open document's filename, or without one the file loading or failed, `failure` is the last file that failed to open and its error until another opens or the notice is dismissed, and `history` contains `undoCount`, `redoCount`, and `editing`, which is true while a group is open.Without a document, `documentId`, `size`, `frame`, and `preview` are undefined. Adjustments, details, and the tone curve use their defaults, and history counts are zero. Mutating the snapshot does not edit the document.@@ -194,6 +196,7 @@ editor.run({| `set-color-mixer` | `color`, `hue?`, `saturation?`, `luminance?`, `layerId?` | Like `setColorMixer`. || `set-details` | `clarity?`, `sharpening?`, `sharpenRadius?`, `layerId?` | Like `setDetails`. || `set-vignette` | `intensity?`, `softness?`, `layerId?` | Like `setVignette`. |+| `set-grain` | `amount?`, `size?`, `roughness?`, `layerId?` | Like `setGrain`. || `add-mask` | `mask`, `adjustments?` | Adds a mask layer with those adjustments on top of the stack as one edit. || `delete-layer` | `layerId` | Like `deleteLayer`. || `set-crop` | `aspectRatio?`, `straighten?` | Replaces the frame with the largest centered crop of the source at `aspectRatio`, width over height, straightened by −45 to 45 degrees. Without either, it removes the crop. |diff --git a/README.md b/README.mdindex 524c564..17b5284 100644--- a/README.md+++ b/README.md@@ -16,11 +16,11 @@ Image processing runs on your own GPU with WebGPU. Photos never leave your devic- Tone curves with a live input histogram.- Clarity and sharpening.- Color Mixer with eight hue, saturation, and luminance ranges.-- Vignette.+- Vignette and film grain.**Layers and masks**-- Draggable effect layers: Details, Exposure, Color Mixer, Vignette, and Color, which paints one color with Photoshop blend modes.+- Draggable effect layers: Details, Exposure, Color Mixer, Vignette, Grain, and Color, which paints one color with Photoshop blend modes.- Linear and radial masks with their own adjustments and child effects.- Add and Subtract submasks, from a mask's actions menu, to shape its coverage.diff --git a/src/app/commands.ts b/src/app/commands.tsindex bec7318..f30e801 100644--- a/src/app/commands.ts+++ b/src/app/commands.ts@@ -12,6 +12,8 @@ import { applyCrop } from "@/features/crop/edits";import { fitRatio, rotate } from "@/features/crop/geometry";import { setDetails } from "@/features/details/edits";import { detailsSchema } from "@/features/details/model";+import { setGrain } from "@/features/grain/edits";+import { grainSchema } from "@/features/grain/model";import { addLayer, deleteLayer } from "@/features/layers/edits";import { maskSchema } from "@/features/layers/model";import { curveSchema, defaultCurve } from "@/features/tone-curves/curve";@@ -129,6 +131,15 @@ export const commands = {),}),),+ "set-grain": command(+ "Adds film grain: amount from 0 (off) to 100, size from 0 (fine) to 100 (coarse), and roughness from 0 (even) to 100 (clumped), keeping omitted values. Without layerId it edits the first Grain layer, creating one when there is none.",+ z.extend(change(grainSchema), { layerId }),+ (document, { layerId, ...grain }) => ({+ layerId: editEffect(document, "grain", layerId, (id) =>+ setGrain(document, grain, id),+ ),+ }),+ ),"add-mask": command("Adds a mask layer on top of the stack with optional adjustments, as one edit, and returns its layerId. Coordinates are source pixels, unaffected by crop. A linear mask covers fully at start and fades out at end; a radial mask covers an ellipse around center with radius [x, y], angle in degrees, and feather from 0 to 1.",z.strictObject({diff --git a/src/app/controls.ts b/src/app/controls.tsindex 4dfb742..08fca0e 100644--- a/src/app/controls.ts+++ b/src/app/controls.ts@@ -17,6 +17,7 @@ import type {BrushStroke,Details,Fill,+ Grain,Mask,Preview,ProcessingLayer,@@ -38,6 +39,8 @@ import { applyCrop } from "@/features/crop/edits";import { setDetails } from "@/features/details/edits";import { defaultDetails } from "@/features/details/model";import { setFill } from "@/features/fill/edits";+import { setGrain } from "@/features/grain/edits";+import { defaultGrain } from "@/features/grain/model";import { addHealPatch, setHealSource } from "@/features/heal/edits";import {addLayer,@@ -130,6 +133,10 @@ export function createControls(setVignette(document, change, id),);},+ setGrain(change: Partial<Grain>, id?: string) {+ const document = workspace.getDocument();+ editEffect(document, "grain", id, (id) => setGrain(document, change, id));+ },setFill(change: Partial<Fill>, id?: string) {const document = workspace.getDocument();editEffect(document, "fill", id, (id) => setFill(document, change, id));@@ -202,6 +209,7 @@ export function createControls(colorMixer:findEffect(layers, "color-mixer")?.colorMixer ?? defaultMixer,vignette: findEffect(layers, "vignette")?.vignette ?? defaultVignette,+ grain: findEffect(layers, "grain")?.grain ?? defaultGrain,history: document?.history.status.getState() ?? {undoCount: 0,redoCount: 0,diff --git a/src/app/editor/adjust/index.tsx b/src/app/editor/adjust/index.tsxindex 68ef50c..231b96c 100644--- a/src/app/editor/adjust/index.tsx+++ b/src/app/editor/adjust/index.tsx@@ -34,6 +34,7 @@ import {detailsParameters,} from "@/features/details/controls";import { FillControls } from "@/features/fill/controls";+import { GrainControls, grainParameters } from "@/features/grain/controls";import { HealControls } from "@/features/heal/controls";import { Histogram } from "@/features/histogram";import { OverlayToggle } from "@/features/layers/overlay-toggle";@@ -137,6 +138,8 @@ function SelectedControls({ layer }: { layer: Layer }) {return <ColorMixerControls id={layer.id} mixer={layer.colorMixer} />;case "vignette":return <VignetteControls id={layer.id} vignette={layer.vignette} />;+ case "grain":+ return <GrainControls id={layer.id} grain={layer.grain} />;case "fill":return <FillControls id={layer.id} fill={layer.fill} />;case "heal":@@ -338,6 +341,13 @@ function SelectedDials({parameters={vignetteParameters(document, layer.id, layer.vignette)}/>);+ case "grain":+ return (+ <DockControls+ header={<DockTitle layer={layer} />}+ parameters={grainParameters(document, layer.id, layer.grain)}+ />+ );case "exposure":return (<DockControlsdiff --git a/src/app/editor/layers.ts b/src/app/editor/layers.tsindex 38f60a7..7b68075 100644--- a/src/app/editor/layers.ts+++ b/src/app/editor/layers.ts@@ -1,6 +1,7 @@import { ColorMixerIcon } from "@/components/icons/color-mixer";import { DetailsIcon } from "@/components/icons/details";import { ExposureIcon } from "@/components/icons/exposure";+import { GrainIcon } from "@/components/icons/grain";import { HealIcon } from "@/components/icons/heal";import { VignetteIcon } from "@/components/icons/vignette";import type {@@ -17,6 +18,7 @@ import { defaultAdjustments } from "@/features/adjustments/model";import { defaultMixer, isNeutral } from "@/features/color-mixer/model";import { defaultDetails } from "@/features/details/model";import { defaultFill } from "@/features/fill/model";+import { defaultGrain } from "@/features/grain/model";import type { EffectKind } from "@/features/layers/controls";import { defaultCurve } from "@/features/tone-curves/curve";import { defaultVignette } from "@/features/vignette/model";@@ -53,6 +55,7 @@ export const effectKinds = [addable: true,},{ kind: "vignette", label: "Vignette", Icon: VignetteIcon, addable: true },+ { kind: "grain", label: "Grain", Icon: GrainIcon, addable: true },{ kind: "fill", label: "Color", addable: true },{ kind: "heal", label: "Healing", Icon: HealIcon, addable: false },] as const satisfies readonly EffectKind[];@@ -70,6 +73,8 @@ export function createLayer(kind: EffectLayer["kind"]): EffectLayer {return { ...base, kind, exposure: 1 };case "vignette":return { ...base, kind, vignette: { ...defaultVignette, intensity: 50 } };+ case "grain":+ return { ...base, kind, grain: { ...defaultGrain, amount: 25 } };case "color-mixer":return { ...base, kind, colorMixer: defaultMixer };case "fill":@@ -111,6 +116,8 @@ function effectNeutral(layer: ProcessingLayer): boolean {return layer.exposure === 0;case "vignette":return layer.vignette.intensity === 0;+ case "grain":+ return layer.grain.amount === 0;case "color-mixer":return isNeutral(layer.colorMixer);case "fill":diff --git a/src/app/editor/renderer.ts b/src/app/editor/renderer.tsindex 0c96472..cc74d00 100644--- a/src/app/editor/renderer.ts+++ b/src/app/editor/renderer.ts@@ -16,6 +16,7 @@ import { adjustments } from "@/features/adjustments/pass";import { colorMixer } from "@/features/color-mixer/pass";import { unsharpMask } from "@/features/details/unsharp-mask";import { fill } from "@/features/fill/pass";+import { grain } from "@/features/grain/pass";import { heal } from "@/features/heal/pass";import { toneCurves } from "@/features/tone-curves/pass";import { vignette } from "@/features/vignette/pass";@@ -73,6 +74,9 @@ function composeLayer(case "vignette":edited = pipeline(below, [vignette(layer.vignette, `${name}/vignette`)]);break;+ case "grain":+ edited = pipeline(below, [grain(layer.grain, `${name}/grain`)]);+ break;case "color-mixer":edited = pipeline(below, [colorMixer(layer.colorMixer, `${name}/color-mixer`),diff --git a/src/app/scene-file.ts b/src/app/scene-file.tsindex 042c449..a5fc060 100644--- a/src/app/scene-file.ts+++ b/src/app/scene-file.ts@@ -17,6 +17,7 @@ import {import { defaultMixer, mixerSchema } from "@/features/color-mixer/model";import { defaultDetails, detailsSchema } from "@/features/details/model";import { defaultFill, fillSchema } from "@/features/fill/model";+import { defaultGrain, grainSchema } from "@/features/grain/model";import { healPatchSchema } from "@/features/heal/model";import {layerSettings,@@ -77,6 +78,11 @@ function processingLayer(children: z.ZodMiniType<readonly ProcessingLayer[]>) {kind: z.literal("vignette"),vignette: withDefaults(defaultVignette, vignetteSchema),}),+ z.object({+ ...base,+ kind: z.literal("grain"),+ grain: withDefaults(defaultGrain, grainSchema),+ }),z.object({...base,kind: z.literal("color-mixer"),diff --git a/src/components/icons/grain.tsx b/src/components/icons/grain.tsxnew file mode 100644index 0000000..fb02ad1--- /dev/null+++ b/src/components/icons/grain.tsx@@ -0,0 +1,16 @@+import { Icon, type IconProps } from "./icon";++export function GrainIcon(props: IconProps) {+ return (+ <Icon {...props}>+ <g fill="currentColor" stroke="none">+ <circle cx="8" cy="7" r="2" />+ <circle cx="15.5" cy="6" r="1.5" />+ <circle cx="17.5" cy="13" r="2" />+ <circle cx="10.5" cy="13.5" r="1.5" />+ <circle cx="6" cy="17" r="1.5" />+ <circle cx="13" cy="19" r="1.5" />+ </g>+ </Icon>+ );+}diff --git a/src/core/document/index.ts b/src/core/document/index.tsindex 3661380..aa64637 100644--- a/src/core/document/index.ts+++ b/src/core/document/index.ts@@ -16,6 +16,7 @@ export type {EffectLayer,Fill,Gradient,+ Grain,HealPatch,ImageLayer,Layer,diff --git a/src/core/document/scene.ts b/src/core/document/scene.tsindex a3fbd09..521f3f0 100644--- a/src/core/document/scene.ts+++ b/src/core/document/scene.ts@@ -36,6 +36,13 @@ export type Vignette = {readonly softness: number;};+/** Film grain in 0..100 UI units, anchored to source pixels. */+export type Grain = {+ readonly amount: number;+ readonly size: number;+ readonly roughness: number;+};+export type Blend =| "normal"| "multiply"@@ -112,6 +119,7 @@ export type ProcessingLayer = {| { readonly kind: "details"; readonly details: Readonly<Details> }| { readonly kind: "exposure"; readonly exposure: number }| { readonly kind: "vignette"; readonly vignette: Vignette }+ | { readonly kind: "grain"; readonly grain: Grain }| { readonly kind: "color-mixer"; readonly colorMixer: ColorMixer }| { readonly kind: "fill"; readonly fill: Fill }| { readonly kind: "heal"; readonly patches: readonly HealPatch[] }diff --git a/src/features/grain/controls.tsx b/src/features/grain/controls.tsxnew file mode 100644index 0000000..88c5d9e--- /dev/null+++ b/src/features/grain/controls.tsx@@ -0,0 +1,38 @@+import { Slider } from "@roprgm/ui/slider";+import type { Parameter } from "@/components/editor/parameter";+import { useDocument } from "@/components/editor/session";+import type { EditorDocument, Grain } from "@/core/document";+import { setGrain } from "./edits";+import { defaultGrain } from "./model";++export function grainParameters(+ document: EditorDocument,+ id: string,+ grain: Grain,+): Parameter[] {+ const controls = [+ ["amount", "Amount"],+ ["size", "Size"],+ ["roughness", "Roughness"],+ ] as const;+ return controls.map(([name, label]) => ({+ id: name,+ label,+ value: grain[name],+ min: 0,+ max: 100,+ defaultValue: defaultGrain[name],+ onChange: (value) => setGrain(document, { [name]: value }, id),+ }));+}++export function GrainControls({ id, grain }: { id: string; grain: Grain }) {+ const document = useDocument();+ return (+ <section className="flex flex-col gap-1.5 p-3.5">+ {grainParameters(document, id, grain).map(({ id, ...parameter }) => (+ <Slider key={id} {...parameter} />+ ))}+ </section>+ );+}diff --git a/src/features/grain/edits.ts b/src/features/grain/edits.tsnew file mode 100644index 0000000..70780e9--- /dev/null+++ b/src/features/grain/edits.ts@@ -0,0 +1,19 @@+import { type EditorDocument, editLayer, type Grain } from "@/core/document";+import { change, parse } from "@/lib/parse";+import { grainSchema } from "./model";++const grainChange = change(grainSchema);++export function setGrain(+ document: EditorDocument,+ grain: Partial<Grain>,+ id: string,+) {+ const values = parse(grainChange, grain, "Invalid grain adjustment");+ editLayer(document, id, (layer) => {+ if (layer.kind !== "grain") {+ throw Error("Select a grain layer.");+ }+ return { ...layer, grain: { ...layer.grain, ...values } };+ });+}diff --git a/src/features/grain/grain.wgsl b/src/features/grain/grain.wgslnew file mode 100644index 0000000..4216914--- /dev/null+++ b/src/features/grain/grain.wgsl@@ -0,0 +1,83 @@+import { linearToSrgb, srgbToLinear } from "@vgpu/wgsl-std/color";+import { pi } from "@vgpu/wgsl-std/constants";+import { pcg3d } from "@vgpu/wgsl-std/hash";+import { luminance } from "../../core/image/color.wgsl";++// Film grain: soft particles of random tone scattered in source pixels, so every render of the+// photo shows the same grain. Particles lie at four fixed spacings, one to eight pixels apart, that+// never move: size slides a window across them, so finer grain fades as coarser grain comes in, and+// roughness widens it to mix in neighboring spacings and varies the particles' radius. The grain+// moves the encoded luminance, most in the midtones, and scales the channels together so color holds.+struct Params {+ amount: f32,+ size: f32,+ roughness: f32,+ // Source pixels per texel, so a reduced proxy samples the grain at the same document positions.+ scale: vec2f,+}++@group(0) @binding(0) var source: texture_2d<f32>;+@group(0) @binding(1) var<uniform> params: Params;++// Four uniform values in [0, 1) for the particle of a cell.+fn random(cell: vec2i, octave: u32) -> vec4f {+ let hash = pcg3d(vec3u(bitcast<vec2u>(cell), octave)).xy;+ return vec4f(vec4u(hash & vec2u(0xffffu), hash >> vec2u(16u))) / 65536.0;+}++// One particle anywhere in each unit cell, a smooth bump with a radius of at most one cell, so only+// the 3×3 cells around `point` reach it, and a tone from -1 to 1. Unit variance on average.+fn particles(point: vec2f, octave: u32, roughness: f32) -> f32 {+ let base = vec2i(floor(point));+ let spread = 0.5 * roughness;+ var sum = 0.0;+ for (var y = -1; y <= 1; y++) {+ for (var x = -1; x <= 1; x++) {+ let cell = base + vec2i(x, y);+ let particle = random(cell, octave);+ let offset = point - vec2f(cell) - particle.xy;+ let radius = 1.0 - spread * particle.z;+ let bump = max(1.0 - dot(offset, offset) / (radius * radius), 0.0);+ sum += (particle.w * 2.0 - 1.0) * bump * bump * bump;+ }+ }+ // E[tone²] = 1/3 times E[∫bump²], which is πr²/7 for a bump of radius r.+ let radius2 = 1.0 - spread + spread * spread / 3.0;+ return sum / sqrt(pi * radius2 / 21.0);+}++const octaves = 4u;++fn grain(point: vec2f) -> f32 {+ let roughness = params.roughness / 100.0;+ // The window's center and width, in octaves.+ let center = f32(octaves - 1u) * params.size / 100.0;+ let width = 0.35 + 0.65 * roughness;+ var sum = 0.0;+ var power = 0.0;+ for (var octave = 0u; octave < octaves; octave++) {+ let weight = exp(-0.5 * pow((f32(octave) - center) / width, 2.0));+ if (weight < 0.02) {+ continue;+ }+ // Each spacing doubles the last; an offset keeps their cells from sharing edges.+ let cells = point / exp2(f32(octave)) + vec2f(0.37, 0.71) * f32(octave);+ sum += weight * particles(cells, octave, roughness);+ power += weight * weight;+ }+ // Independent octaves of unit variance add up to the square root of their weights' squares.+ return sum / sqrt(power);+}++@fragment fn fs_main(@builtin(position) position: vec4f) -> @location(0) vec4f {+ let input = textureLoad(source, vec2i(position.xy), 0);+ let light = luminance(input.rgb);+ if (light <= 0.0 || light >= 1.0) {+ return input;+ }+ let tone = linearToSrgb(light);+ // Strongest in the midtones and gone at black and white; at 100 it deviates 8% of the range there.+ let strength = params.amount / 100.0 * 0.08 * sqrt(4.0 * tone * (1.0 - tone));+ let grained = max(tone + strength * grain(position.xy * params.scale), 0.0);+ return vec4f(input.rgb * (srgbToLinear(grained) / light), input.a);+}diff --git a/src/features/grain/model.ts b/src/features/grain/model.tsnew file mode 100644index 0000000..1ab1862--- /dev/null+++ b/src/features/grain/model.ts@@ -0,0 +1,15 @@+import { z } from "zod/mini";+import type { Grain } from "@/core/document";+import { range } from "@/lib/parse";++export const defaultGrain: Readonly<Grain> = {+ amount: 0,+ size: 25,+ roughness: 50,+};++export const grainSchema = z.object({+ amount: range(0, 100),+ size: range(0, 100),+ roughness: range(0, 100),+}) satisfies z.ZodMiniType<Grain>;diff --git a/src/features/grain/pass.ts b/src/features/grain/pass.tsnew file mode 100644index 0000000..c882036--- /dev/null+++ b/src/features/grain/pass.ts@@ -0,0 +1,17 @@+import type { Grain } from "@/core/document";+import { merge, node, type RenderImage } from "@/core/renderer";+import shader from "./grain.wgsl";++/** Grain lies in source pixels, so a reduced proxy passes its scale to sample the same grain. */+export function grain(settings: Grain, name = "grain") {+ if (settings.amount === 0) {+ return;+ }+ return (image: RenderImage) =>+ merge(+ { source: image },+ node(name, shader, {+ set: { params: { ...settings, scale: image.scale } },+ }),+ );+}diff --git a/tests/grain.e2e.ts b/tests/grain.e2e.tsnew file mode 100644index 0000000..64aaee7--- /dev/null+++ b/tests/grain.e2e.ts@@ -0,0 +1,91 @@+import type { Page } from "@playwright/test";+import { expect, test } from "./fixtures";++/** The exported image's red channel, row by row; grain keeps a gray image gray. */+async function exportRed(page: Page) {+ return page.evaluate(async () => {+ 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 image pixels.");+ context.drawImage(image, 0, 0);+ const { data } = context.getImageData(0, 0, image.width, image.height);+ return Array.from(data.filter((_, index) => index % 4 === 0));+ });+}++function mean(values: readonly number[]) {+ return values.reduce((sum, value) => sum + value, 0) / values.length;+}++function deviation(values: readonly number[]) {+ const center = mean(values);+ return Math.sqrt(mean(values.map((value) => (value - center) ** 2)));+}++function correlation(a: readonly number[], b: readonly number[]) {+ const [ma, mb] = [mean(a), mean(b)];+ const covariance = mean(+ a.map((value, index) => (value - ma) * (b[index] - mb)),+ );+ return covariance / (deviation(a) * deviation(b));+}++test("grain textures a gray image without shifting its tone, holds through a crop, and undoes", async ({+ page,+}) => {+ await page.goto("/");+ await page.locator('input[type="file"]').setInputFiles({+ name: "gray.svg",+ mimeType: "image/svg+xml",+ buffer: Buffer.from(+ '<svg xmlns="http://www.w3.org/2000/svg" width="256" height="128"><rect width="256" height="128" fill="#808080"/></svg>',+ ),+ });+ await page.getByRole("button", { name: "Add effect", exact: true }).click();+ await page.getByRole("menuitem", { name: "Grain", exact: true }).click();+ const amount = page.getByRole("textbox", { name: "Amount", exact: true });+ await expect(amount).toHaveValue("25");+ await expect(+ page.getByRole("textbox", { name: "Size", exact: true }),+ ).toHaveValue("25");+ await expect(+ page.getByRole("textbox", { name: "Roughness", exact: true }),+ ).toHaveValue("50");++ const light = await exportRed(page);+ expect(deviation(light)).toBeGreaterThan(2);+ expect(Math.abs(mean(light) - 128)).toBeLessThan(1);++ await amount.fill("100");+ await amount.press("Enter");+ const heavy = await exportRed(page);+ expect(deviation(heavy)).toBeGreaterThan(3 * deviation(light));+ expect(Math.abs(mean(heavy) - 128)).toBeLessThan(1);+ expect(await exportRed(page)).toEqual(heavy);++ // A little more size fades coarser grain in over the same particles rather than stretching them.+ const size = page.getByRole("textbox", { name: "Size", exact: true });+ await size.fill("30");+ await size.press("Enter");+ expect(correlation(await exportRed(page), heavy)).toBeGreaterThan(0.9);+ await page.getByRole("button", { name: "Undo", exact: true }).click();+ expect(await exportRed(page)).toEqual(heavy);++ // A centered square crop of the 256 × 128 image keeps source columns 64 to 191.+ await page.evaluate(() =>+ window.openlight.run({ type: "set-crop", aspectRatio: 1 }),+ );+ expect(await exportRed(page)).toEqual(+ heavy.filter((_, index) => index % 256 >= 64 && index % 256 < 192),+ );++ const undo = page.getByRole("button", { name: "Undo", exact: true });+ await undo.click();+ await undo.click();+ expect(await exportRed(page)).toEqual(light);++ await amount.fill("0");+ await amount.press("Enter");+ expect(deviation(await exportRed(page))).toBe(0);+});diff --git a/tests/rendering-benchmark.ts b/tests/rendering-benchmark.tsindex 12059d0..b23b2c3 100644--- a/tests/rendering-benchmark.ts+++ b/tests/rendering-benchmark.ts@@ -19,6 +19,7 @@ export type Workload =| "neutral"| "color-mixer"| "vignette"+ | "grain"| "detail"| "pipeline"| "pipeline-input"@@ -173,6 +174,15 @@ export async function benchmarkRendering(vignette: { intensity: 80, softness: 60 },});}+ if (workload === "grain") {+ effects.push({+ ...common,+ id: "benchmark-grain",+ name: "Grain",+ kind: "grain",+ grain: { amount: 50, size: 25, roughness: 50 },+ });+ }if (workload === "fill") {effects.push({...common,diff --git a/tests/rendering.bench.ts b/tests/rendering.bench.tsindex 74ce8d1..2396310 100644--- a/tests/rendering.bench.ts+++ b/tests/rendering.bench.ts@@ -8,6 +8,7 @@ for (const workload of ["neutral","color-mixer","vignette",+ "grain","detail","pipeline","pipeline-input",