From c81368470bd1b876b14ec5c8d29728d14deabfab Mon Sep 17 00:00:00 2001 From: Jeremy Hooke Date: Mon, 2 Nov 2026 23:30:16 +1100 Subject: [PATCH 01/14] LR-EDIT-EFFECTS-GRAIN: film grain from crystal layers (process V3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Grain under the new process V3 is drawn from a simulated emulsion of crystal layers, after Aurélien Pierre's crystallographic grain model (implemented from the article's description). It fades out towards black and white as on a print, is applied symmetrically in the display-encoded domain (no shadow darkening, no grey specks in blown highlights), and matches Lightroom Classic's strength and grain width at mid grey. The emulsion is drawn once per Size / Roughness / seed on two periodic tiles in frame coordinates and kept as summed-area tables, so each output pixel takes the exact mean of the emulsion under its footprint: a preview is the export's grain box-downscaled. CPU and GPU read the same tables (the GPU from the finish kernel's aux buffer). V1 and V2 keep their value-noise grain exactly. Co-Authored-By: Claude Opus 5.5 --- crates/develop/src/settings.rs | 8 +- crates/gpu/src/ctx.rs | 5 + crates/gpu/src/params.rs | 42 +- crates/gpu/src/wgsl/finish.wgsl | 79 ++- crates/pipeline/src/crystal.rs | 747 +++++++++++++++++++++++++++ crates/pipeline/src/finish.rs | 85 ++- crates/pipeline/src/lib.rs | 3 + crates/pipeline/src/local.rs | 4 +- crates/pipeline/src/tests_crystal.rs | 261 ++++++++++ crates/pipeline/src/tests_grain.rs | 82 +++ docs/gpu-pipeline.md | 2 +- docs/grain.md | 106 ++++ docs/parity-checklist.md | 2 +- docs/process-versions.md | 3 +- docs/whats-new.md | 9 + 15 files changed, 1397 insertions(+), 41 deletions(-) create mode 100644 crates/pipeline/src/crystal.rs create mode 100644 crates/pipeline/src/tests_crystal.rs create mode 100644 crates/pipeline/src/tests_grain.rs create mode 100644 docs/grain.md diff --git a/crates/develop/src/settings.rs b/crates/develop/src/settings.rs index 739171abd9..8cb33a6a4e 100644 --- a/crates/develop/src/settings.rs +++ b/crates/develop/src/settings.rs @@ -84,17 +84,21 @@ pub enum Process { /// Highlights and Shadows keep the local contrast of the tones they move: their edge-aware base /// is taken of a fine median of log luminance (issue #632). V2, + /// Film grain from a stack of crystal layers (after Aurélien Pierre's model): resolution + /// independent, fading out at black and white; V1 and V2 keep their value noise. + V3, } impl Process { /// Every process, oldest first. - pub const ALL: [Process; 2] = [Process::V1, Process::V2]; - pub const LATEST: Process = Process::V2; + pub const ALL: [Process; 3] = [Process::V1, Process::V2, Process::V3]; + pub const LATEST: Process = Process::V3; pub const fn version(self) -> ProcessVersion { match self { Process::V1 => ProcessVersion(1), Process::V2 => ProcessVersion(2), + Process::V3 => ProcessVersion(3), } } } diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index ea93008fed..24048e7f22 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -367,6 +367,11 @@ fn constants() -> String { for (i, h) in GRAIN_HASH.iter().enumerate() { s += &format!("const GRAIN_H{i}: u32 = {h}u;\n"); } + use lightcraft_pipeline::crystal::{TILE_PER_LONG, TORI}; + s += &format!( + "const CRYSTAL_T0: u32 = {}u;\nconst CRYSTAL_T1: u32 = {}u;\nconst CRYSTAL_TPL: f32 = {:?};\n", + TORI[0], TORI[1], TILE_PER_LONG as f32 + ); for (name, idx) in crate::params::finish_fields() { s += &format!("const F_{name}: u32 = {idx}u;\n"); } diff --git a/crates/gpu/src/params.rs b/crates/gpu/src/params.rs index b46b7cc1ac..4ab667731e 100644 --- a/crates/gpu/src/params.rs +++ b/crates/gpu/src/params.rs @@ -3,7 +3,7 @@ use lightcraft_develop::VignetteStyle; use lightcraft_pipeline::colorops::POINT_WORDS; -use lightcraft_pipeline::finish::{FinishParams, MASK_TERMS, srgb_lut}; +use lightcraft_pipeline::finish::{FinishParams, GrainModel, MASK_TERMS, srgb_lut}; /// Entries per tone-curve table (`lightcraft_pipeline::finish` builds them at this size). pub const CURVE_N: u32 = 1024; @@ -60,6 +60,12 @@ const FIELDS: &[(&str, usize)] = &[ // the window's offset in the whole output and the whole output's size (pixels) ("VIG_VIEW", 4), ("GRAIN", 1), + // 0 = value noise (processes V1, V2: GRAIN_AMT, GRAIN_SC, GRAIN_ROUGH), 1 = crystal layers (V3) + ("GRAIN_MODEL", 1), + // crystal grain: amplitude, footprint (tile px per output px), the tori's tables in `aux` + ("GRAIN_K", 1), + ("GRAIN_FOOT", 1), + ("GRAIN_SAT", 2), ("GRAIN_AMT", 1), ("GRAIN_SC", 1), ("GRAIN_ROUGH", 1), @@ -146,7 +152,7 @@ pub struct Present { } /// The `finish` kernel's parameter block and auxiliary table (tone LUT | chroma curve | sRGB LUT | curve LUTs | -/// mask terms) for `fp` with `masks` (their local adjustments' terms). +/// mask terms | crystal grain tables) for `fp` with `masks` (their local adjustments' terms). pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Present) -> (Vec, Vec) { let mut aux: Vec = fp.tone.lut().to_vec(); aux.extend_from_slice(fp.tone.chroma_lut()); @@ -163,6 +169,13 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr for m in masks { aux.extend_from_slice(m); } + let mut sat_off = [0u32; 2]; + if let Some(GrainModel::Crystal(g)) = &fp.grain { + for (off, sat) in sat_off.iter_mut().zip(&g.tile.sats) { + *off = aux.len() as u32; + aux.extend_from_slice(sat); + } + } let mut p = Block::new(); p.u("W", fp.w as u32); @@ -248,12 +261,27 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr p.b("PROOF_DEST_WARN", pp.dest_warning); p.b("PROOF_DISP_WARN", pp.display_warning); } - if let Some((amt, cell, rough, seed)) = fp.grain { + if let Some(model) = &fp.grain { p.b("GRAIN", true); - p.f("GRAIN_AMT", amt); - p.f("GRAIN_SC", fp.px_per_long as f32 / cell); - p.f("GRAIN_ROUGH", rough); - p.u("GRAIN_SEED", seed); + match model { + GrainModel::Value(g) => { + p.u("GRAIN_MODEL", 0); + p.f("GRAIN_AMT", g.amt); + p.f("GRAIN_SC", fp.px_per_long as f32 / g.cell); + p.f("GRAIN_ROUGH", g.rough); + p.u("GRAIN_SEED", g.seed); + } + GrainModel::Crystal(g) => { + p.u("GRAIN_MODEL", 1); + p.f("GRAIN_K", g.k); + p.f("GRAIN_FOOT", g.foot); + if let Some(i) = index("GRAIN_SAT") { + for (slot, off) in p.0.iter_mut().skip(i).zip(sat_off) { + *slot = off; + } + } + } + } let long = fp.ow.max(fp.oh); let [a, b, c, d, e, f] = fp.out_to_norm.0; let (kx, ky) = (fp.ow / long, fp.oh / long); diff --git a/crates/gpu/src/wgsl/finish.wgsl b/crates/gpu/src/wgsl/finish.wgsl index 767ff44c99..863b34d540 100644 --- a/crates/gpu/src/wgsl/finish.wgsl +++ b/crates/gpu/src/wgsl/finish.wgsl @@ -216,6 +216,65 @@ fn ghash(i: i32, j: i32, seed: u32) -> f32 { return f32(v & 0xffffu) / 32768.0 - 1.0; } +// Crystal grain (process V3): `lightcraft_pipeline::crystal` (keep in step with it). The tori's +// summed-area tables follow the other tables in `aux` (offsets F_GRAIN_SAT). +fn cg_bilinear(o: u32, t: u32, x: f32, y: f32) -> f32 { + let s = t + 1u; + let i = min(u32(max(x, 0.0)), t - 1u); + let j = min(u32(max(y, 0.0)), t - 1u); + let fx = x - f32(i); + let fy = y - f32(j); + let b = o + j * s + i; + let a = aux[b] + (aux[b + 1u] - aux[b]) * fx; + let c = aux[b + s] + (aux[b + s + 1u] - aux[b + s]) * fx; + return a + (c - a) * fy; +} + +fn cg_integral(o: u32, t: u32, x: f32, y: f32) -> f32 { + let tf = f32(t); + let wx = x >= tf; + let wy = y >= tf; + let rx = select(x, x - tf, wx); + let ry = select(y, y - tf, wy); + var v = cg_bilinear(o, t, rx, ry); + if (wx) { + v += cg_bilinear(o, t, tf, ry); + } + if (wy) { + v += cg_bilinear(o, t, rx, tf); + } + if (wx && wy) { + v += cg_bilinear(o, t, tf, tf); + } + return v; +} + +fn cg_box(o: u32, t: u32, x0_: f32, y0_: f32, w: f32) -> f32 { + let tf = f32(t); + let x0 = x0_ - floor(x0_ / tf) * tf; + let y0 = y0_ - floor(y0_ / tf) * tf; + return cg_integral(o, t, x0 + w, y0 + w) - cg_integral(o, t, x0, y0 + w) - cg_integral(o, t, x0 + w, y0) + cg_integral(o, t, x0, y0); +} + +fn cg_lift(v: f32) -> f32 { + let c = clamp(v, 0.0, 1.0); + return select((c + 0.055) / 2.4, c, c <= 0.04045); +} + +fn cg_srgb_to_linear(v: f32) -> f32 { + return select(pow((v + 0.055) / 1.055, 2.4), v / 12.92, v <= 0.04045); +} + +fn crystal_grain(e: vec3, gx: f32, gy: f32) -> vec3 { + let w = pf(F_GRAIN_FOOT); + let x0 = gx * CRYSTAL_TPL - 0.5 * w; + let y0 = gy * CRYSTAL_TPL - 0.5 * w; + let g = (cg_box(pu(F_GRAIN_SAT), CRYSTAL_T0, x0, y0, w) + cg_box(pu(F_GRAIN_SAT + 1u), CRYSTAL_T1, x0, y0, w)) / (w * w); + let lum = clamp(0.2126 * e.x + 0.7152 * e.y + 0.0722 * e.z, 0.0, 1.0); + let k = pf(F_GRAIN_K) * g * (1.0 - cg_srgb_to_linear(lum)); + return e + k * vec3(cg_lift(e.x), cg_lift(e.y), cg_lift(e.z)); +} + fn grain_noise(x: f32, y: f32, seed: u32) -> f32 { let x0 = floor(x); let y0 = floor(y); @@ -549,14 +608,18 @@ fn main(@builtin(global_invocation_id) gid: vec3) { let py = f32(y) + 0.5; let gx = pf(F_GRAIN_AFF) * px + pf(F_GRAIN_AFF + 2u) * py + pf(F_GRAIN_AFF + 4u); let gy = pf(F_GRAIN_AFF + 1u) * px + pf(F_GRAIN_AFF + 3u) * py + pf(F_GRAIN_AFF + 5u); - let sc = pf(F_GRAIN_SC); - let rough = pf(F_GRAIN_ROUGH); - let seed = pu(F_GRAIN_SEED); - var g = grain_noise(gx * sc, gy * sc, seed); - g = g * (1.0 - rough * 0.5) + grain_noise(gx * sc * 2.3, gy * sc * 2.3, seed ^ 0x55u) * rough * 0.7; - let lum = 0.2126 * e.x + 0.7152 * e.y + 0.0722 * e.z; - let k = pf(F_GRAIN_AMT) * g * (0.35 + 2.6 * lum * (1.0 - lum)); - e = e + k; + if (pu(F_GRAIN_MODEL) == 1u) { + e = crystal_grain(e, gx, gy); + } else { + let sc = pf(F_GRAIN_SC); + let rough = pf(F_GRAIN_ROUGH); + let seed = pu(F_GRAIN_SEED); + var g = grain_noise(gx * sc, gy * sc, seed); + g = g * (1.0 - rough * 0.5) + grain_noise(gx * sc * 2.3, gy * sc * 2.3, seed ^ 0x55u) * rough * 0.7; + let lum = 0.2126 * e.x + 0.7152 * e.y + 0.0722 * e.z; + let k = pf(F_GRAIN_AMT) * g * (0.35 + 2.6 * lum * (1.0 - lum)); + e = e + k; + } } if (warn == 1u) { e = vec3(1.0, 0.0, 0.0); diff --git a/crates/pipeline/src/crystal.rs b/crates/pipeline/src/crystal.rs new file mode 100644 index 0000000000..ba2f2f7b9c --- /dev/null +++ b/crates/pipeline/src/crystal.rs @@ -0,0 +1,747 @@ +//! Crystal-layer film grain, the grain of process V3 and later ([`crate::finish::GrainModel`]). +//! +//! After the model of Aurélien Pierre, *Stochastic photographic grain synthesis from +//! crystallographic structure simulation* (2023), implemented from the article's description of +//! the method; no code was taken from it or from any implementation. `docs/grain.md` has the +//! method, the calibration and the measurements. +//! +//! - **Emulsion.** A stack of layers. Each layer has one crystal shape (a regular polygon of 3–8 +//! vertices, a random rotation, a log-normal width) and is a Boolean model: Poisson seeds grown +//! into crystals, at the density that leaves half the layer covered ([`FILLING`]). +//! - **Capture.** A point's grain is the number of layers covering it, less its mean: many +//! independent layers of different crystal sizes give dense, soft, cloudy grain. +//! - **Print.** The light a point captures is proportional to the light falling on it, and the +//! print shows less grain towards paper white: the grain is `Y·(1 − Y)` in linear light, so +//! it fades out at black and at white. It is added in the display-encoded domain (first order), +//! where it is symmetric: it neither darkens shadows nor greys blown highlights. +//! +//! **Resolution independence.** The emulsion is drawn once per setting on two periodic tiles +//! (tori) in frame coordinates, at twice the resolution of a 6000 px export ([`PITCH`]). Each +//! output pixel takes the exact mean of the emulsion under its footprint from the tiles' summed +//! area tables, so a preview shows exactly the export's grain box-downscaled to its size, and an +//! export larger than 6000 px still has crystals rather than enlarged pixels. The layers are +//! split between two tori of different sizes ([`TORI`]); their pattern only repeats as a whole +//! after tens of thousands of pixels. +//! +//! **Cost.** Drawing the tiles takes a few milliseconds and is cached per setting +//! ([`CrystalGrain::new`]); a pixel then costs two box sums (16 table reads), on the CPU and in the +//! GPU kernel (`finish.wgsl`, which reads the same tables). + +use std::f64::consts::TAU; +use std::sync::{Arc, Mutex, PoisonError}; + +use lightcraft_color::transfer::srgb_to_linear; +use lightcraft_develop::Grain; +use lightcraft_raster::par_rows; + +/// Long edge (output pixels) at which grain sizes and strengths are specified: a 24 MP export. +pub const REF_LONG: f64 = 6000.0; +/// Size of a tile pixel in reference pixels: tiles are drawn at twice the reference resolution. +pub const PITCH: f64 = 0.5; +/// Tile pixels per long edge of the frame. +pub const TILE_PER_LONG: f64 = REF_LONG / PITCH; +/// Sides of the two tori (tile pixels: 640 and 567 reference pixels). Layers alternate between +/// them; the sizes share no small factor, so the sum repeats only after 362,880 reference pixels. +pub const TORI: [usize; 2] = [1280, 1134]; +/// Fraction of each layer covered by its crystals. +pub const FILLING: f64 = 0.5; +/// Rows per band when drawing a tile (each band is drawn in parallel). +const BAND: usize = 64; +/// Encoded luminance at which the strength is specified (mid grey, 128 of 255). +const MID_GREY: f32 = 128.0 / 255.0; +/// A footprint this large (tile pixels: a render under 24 px long) gets no grain. +const MAX_FOOTPRINT: f32 = 500.0; +/// Settings whose tiles are kept (a preview and an export, a few thumbnails). +const CACHE: usize = 4; + +/// The look of a grain setting: what the tiles are drawn from. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct CrystalLook { + /// Median crystal width (circumscribed diameter, reference pixels). + pub width: f64, + /// Log standard deviation of the layers' crystal widths. + pub spread: f64, + /// Number of layers. + pub layers: usize, +} + +/// Piecewise-linear interpolation through `(x, y)` knots sorted by `x`, constant outside them. +fn interp(knots: &[(f64, f64)], x: f64) -> f64 { + let (Some(first), Some(last)) = (knots.first(), knots.last()) else { return 0.0 }; + if x <= first.0 { + return first.1; + } + for w in knots.windows(2) { + if let [(x0, y0), (x1, y1)] = *w + && x <= x1 + { + return y0 + (y1 - y0) * (x - x0) / (x1 - x0).max(1e-9); + } + } + last.1 +} + +/// Median crystal width at Roughness 50 by Size (reference pixels), fitted so the grain's width +/// matches Lightroom Classic's (`fit_widths`, `docs/grain.md`). Size 0 is as fine as the model +/// gets: crystals narrower than a pixel, uncorrelated pixels. +const WIDTH_BY_SIZE: [(f64, f64); 6] = [(0.0, 0.55), (10.0, 1.39), (25.0, 2.95), (50.0, 5.17), (75.0, 8.78), (100.0, 12.38)]; +/// Width factor by Roughness. +const WIDTH_BY_ROUGHNESS: [(f64, f64); 3] = [(0.0, 0.734), (50.0, 1.0), (100.0, 1.422)]; +/// Layers by Size: coarser grain averages more layers, so it stays a soft clump texture. +const LAYERS_BY_SIZE: [(f64, f64); 4] = [(0.0, 16.0), (25.0, 31.0), (50.0, 54.0), (100.0, 70.0)]; + +/// Log-width spread every look has on top of Roughness's. The look the tables were chosen from (a +/// prototype on whole-pixel crystals, `docs/grain.md`) rounded crystal widths to whole pixels, +/// which spreads their sizes by about this much; with it, the anti-aliased crystals here have the +/// prototype's texture at every scale, not just its width. +const SPREAD_FLOOR: f64 = 0.45; + +/// A slider value as a number in `0..=100`; `fallback` for NaN. +fn slider(v: f64, fallback: f64) -> f64 { + if v.is_nan() { fallback } else { v.clamp(0.0, 100.0) } +} + +impl CrystalLook { + pub fn new(size: f64, roughness: f64) -> CrystalLook { + let (s, r) = (slider(size, 25.0), slider(roughness, 50.0)); + CrystalLook { + width: interp(&WIDTH_BY_SIZE, s) * interp(&WIDTH_BY_ROUGHNESS, r), + spread: (0.1 + 0.6 * r / 100.0).hypot(SPREAD_FLOOR), + layers: interp(&LAYERS_BY_SIZE, s).round().clamp(2.0, 120.0) as usize, + } + } +} + +/// Grain strength (8-bit levels at mid grey on a 6000 px export) for Amount, Size and Roughness, +/// measured on Lightroom Classic exports (the fit of open PR #1060's `docs/grain.md`). +pub fn strength_levels(amount: f64, size: f64, roughness: f64) -> f64 { + let (s, d) = (slider(size, 25.0), slider(roughness, 50.0) / 100.0 - 0.5); + slider(amount, 0.0) / 100.0 * (2.447 + 1.386 * (-s / 19.88).exp()).exp() * (1.0 - 0.084 * d + 1.6384 * d * d) +} + +// ---- hashing + +#[inline] +fn mix(mut x: u32) -> u32 { + x ^= x >> 16; + x = x.wrapping_mul(0x7feb_352d); + x ^= x >> 15; + x = x.wrapping_mul(0x846c_a68b); + x ^ (x >> 16) +} + +#[inline] +fn hash(a: u32, b: u32, c: u32, d: u32) -> u32 { + mix(mix(mix(mix(a ^ 0x9e37_79b9) ^ b) ^ c.wrapping_mul(0x85eb_ca6b)) ^ d.wrapping_mul(0xc2b2_ae35)) +} + +/// A hash as a number in (0, 1]. +#[inline] +fn unit(h: u32) -> f64 { + (h as f64 + 0.5) / 4_294_967_296.0 +} + +/// The standard normal quantile of `p` in (0, 1) (Acklam's rational approximation, ~1e-9). +fn normal_quantile(p: f64) -> f64 { + const A: [f64; 6] = + [-39.696_830_286_653_76, 220.946_098_424_520_5, -275.928_510_446_968_7, 138.357_751_867_269, -30.664_798_066_147_16, 2.506_628_277_459_239]; + const B: [f64; 5] = [-54.476_098_798_224_06, 161.585_836_858_040_9, -155.698_979_859_886_6, 66.801_311_887_719_72, -13.280_681_552_885_72]; + const C: [f64; 6] = [ + -0.007_784_894_002_430_293, + -0.322_396_458_041_136_5, + -2.400_758_277_161_838, + -2.549_732_539_343_734, + 4.374_664_141_464_968, + 2.938_163_982_698_783, + ]; + const D: [f64; 4] = [0.007_784_695_709_041_462, 0.322_467_129_070_039_8, 2.445_134_137_142_996, 3.754_408_661_907_416]; + let p = p.clamp(1e-12, 1.0 - 1e-12); + let tail = + |q: f64| (((((C[0] * q + C[1]) * q + C[2]) * q + C[3]) * q + C[4]) * q + C[5]) / ((((D[0] * q + D[1]) * q + D[2]) * q + D[3]) * q + 1.0); + if p < 0.024_25 { + tail((-2.0 * p.ln()).sqrt()) + } else if p > 1.0 - 0.024_25 { + -tail((-2.0 * (1.0 - p).ln()).sqrt()) + } else { + let q = p - 0.5; + let r = q * q; + (((((A[0] * r + A[1]) * r + A[2]) * r + A[3]) * r + A[4]) * r + A[5]) * q + / (((((B[0] * r + B[1]) * r + B[2]) * r + B[3]) * r + B[4]) * r + 1.0) + } +} + +/// The emulsion's layers. Their crystal widths are the `layers` quantiles of the log-normal +/// width distribution, dealt to the layers in an order the seed shuffles: every seed has the same +/// mix of sizes (so the same grain width and strength), in a different arrangement. +fn emulsion(seed: u32, look: &CrystalLook) -> Vec { + let n = look.layers.max(1); + let mut order: Vec<(u32, usize)> = (0..n).map(|l| (hash(seed, l as u32, 0x5047, 0), l)).collect(); + order.sort_unstable(); + let mut rank = vec![0usize; n]; + for (r, &(_, l)) in order.iter().enumerate() { + if let Some(slot) = rank.get_mut(l) { + *slot = r; + } + } + (0..n).map(|l| Layer::new(seed, l as u32, look, normal_quantile((rank.get(l).copied().unwrap_or(0) as f64 + 0.5) / n as f64))).collect() +} + +fn normal(h1: u32, h2: u32) -> f64 { + (-2.0 * unit(h1).ln()).sqrt() * (TAU * unit(h2)).cos() +} + +/// The cumulative distribution of a Poisson count of mean `mu`, up to where it reaches 1 (at +/// most 512 entries; `mu` stays below ~150 here). +fn poisson_cdf(mu: f64) -> Vec { + let mut cdf = Vec::new(); + let mut p = (-mu).exp(); + let mut cum = p; + for k in 1..512u32 { + cdf.push(cum); + if cum >= 1.0 - 1e-12 { + break; + } + p *= mu / k as f64; + cum += p; + } + cdf +} + +/// A Poisson count drawn from its `cdf` by hash `h`. +#[inline] +fn poisson(cdf: &[f64], h: u32) -> usize { + let u = unit(h); + cdf.partition_point(|&c| c < u) +} + +// ---- one layer + +/// A stream of hashes: a Weyl sequence through [`mix`]. +struct Stream(u32); + +impl Stream { + #[inline] + fn next(&mut self) -> u32 { + self.0 = self.0.wrapping_add(0x9e37_79b9); + mix(self.0) + } +} + +/// Sub-pixel positions a crystal centre is rounded to, per axis, when drawn from its [`Stamp`]. +const PHASES: usize = 16; +/// Crystals up to this circumradius (tile pixels) are drawn from a stamp. +const STAMP_R: f64 = 16.0; + +/// A layer's crystal rasterised at every sub-pixel phase of its centre: for a centre at +/// `(X + qx/PHASES, Y + qy/PHASES)` (`X`, `Y` integers) it covers rows `Y + rows[qy].0 ..= Y + +/// rows[qy].1`, and in row `Y + rows[qy].0 + k` the pixels `X + o.0 ..= X + o.1`, with +/// `o = spans[(qy·PHASES + qx)·height + k]`. +#[derive(Clone, Debug)] +struct Stamp { + rows: [(i32, i32); PHASES], + height: usize, + spans: Vec<(i32, i32)>, +} + +/// One emulsion layer: its crystal (a regular polygon) and seed density, in tile pixels. +#[derive(Clone, Debug)] +struct Layer { + /// The crystal as half-planes, relative to its centre: `x ≥ a + s·y` for each `(a, s)` of + /// `left` (`nl` used), `x ≤ a + s·y` for `right` (`nr` used), `y0 ≤ y ≤ y1`. + left: [(f64, f64); 8], + right: [(f64, f64); 8], + nl: usize, + nr: usize, + y0: f64, + y1: f64, + /// Circumradius. + r: f64, + /// Seeds per tile pixel. + lambda: f64, + seed: u32, + index: u32, + stamp: Option, +} + +/// Crystals narrower than this (tile pixels) cover at most two neighbouring pixel centres: their +/// layer is drawn as independent pixels. +const FINE: f64 = 1.5; + +impl Layer { + /// Layer `index` of the emulsion of `seed`, its crystal width `z` log standard deviations + /// from the median. + fn new(seed: u32, index: u32, look: &CrystalLook, z: f64) -> Layer { + let h = |k: u32| hash(seed, index, k, 0x51ed); + let n = (4.5 + normal(h(1), h(2))).round().clamp(3.0, 8.0) as usize; + let rot = TAU * unit(h(3)); + let width = look.width.max(0.05) * (look.spread * z.clamp(-2.5, 2.5)).exp(); + let r = width / 2.0 / PITCH; + let vert = |k: usize| { + let a = rot + TAU * k as f64 / n as f64; + (r * a.cos(), r * a.sin()) + }; + let mut layer = Layer { + left: [(0.0, 0.0); 8], + right: [(0.0, 0.0); 8], + nl: 0, + nr: 0, + y0: f64::INFINITY, + y1: f64::NEG_INFINITY, + r, + lambda: -(1.0 - FILLING).ln() / (0.5 * n as f64 * r * r * (TAU / n as f64).sin()).max(1e-9), + seed, + index, + stamp: None, + }; + for k in 0..n { + let ((x0, y0), (x1, y1)) = (vert(k), vert(k + 1)); + layer.y0 = layer.y0.min(y0); + layer.y1 = layer.y1.max(y0); + let dy = y1 - y0; + if dy.abs() < 1e-12 { + continue; + } + // counter-clockwise: the inside is left of each edge + let sl = (x1 - x0) / dy; + let line = (x0 - sl * y0, sl); + if dy > 0.0 { + if let Some(slot) = layer.right.get_mut(layer.nr) { + *slot = line; + layer.nr += 1; + } + } else if let Some(slot) = layer.left.get_mut(layer.nl) { + *slot = line; + layer.nl += 1; + } + } + if r <= STAMP_R && 2.0 * r >= FINE { + layer.stamp = Some(layer.stamp()); + } + layer + } + + fn stamp(&self) -> Stamp { + let q = PHASES as f64; + let mut rows = [(0, -1); PHASES]; + for (qy, r) in rows.iter_mut().enumerate() { + let g = qy as f64 / q; + *r = ((g + self.y0 - 0.5).ceil() as i32, (g + self.y1 - 0.5).floor() as i32); + } + let height = rows.iter().map(|(a, b)| (b - a + 1).max(0) as usize).max().unwrap_or(0); + let mut spans = vec![(0, -1); PHASES * PHASES * height]; + for (qy, &(a, b)) in rows.iter().enumerate() { + for k in 0..(b - a + 1).max(0) { + let (xl, xr) = self.span((a + k) as f64 + 0.5 - qy as f64 / q); + for qx in 0..PHASES { + let f = qx as f64 / q; + if let Some(o) = spans.get_mut((qy * PHASES + qx) * height + k as usize) { + *o = ((f + xl - 0.5).ceil() as i32, (f + xr - 0.5).floor() as i32); + } + } + } + } + Stamp { rows, height, spans } + } + + /// The crystal's horizontal extent at height `y` above its centre (convex: one interval). + #[inline] + fn span(&self, y: f64) -> (f64, f64) { + let lo = self.left.iter().take(self.nl).fold(f64::NEG_INFINITY, |m, &(a, s)| m.max(a + s * y)); + let hi = self.right.iter().take(self.nr).fold(f64::INFINITY, |m, &(a, s)| m.min(a + s * y)); + (lo, hi) + } + + /// Sets the bits of the pixels the layer covers in rows `y0..` of a torus of side `t`: + /// `cover` holds whole rows of `w` words (bit `i % 64` of word `i / 64` is pixel `i`). + fn draw(&self, t: usize, y0: usize, w: usize, cover: &mut [u64]) { + let rows = cover.len() / w.max(1); + if 2.0 * self.r < FINE { + // each pixel covered with probability FILLING (one half: one random bit) + for (j, row) in cover.chunks_mut(w.max(1)).enumerate() { + let mut bits = Stream(hash(self.seed, self.index, (y0 + j) as u32, 0xb175)); + for v in row.iter_mut() { + *v = bits.next() as u64 | (bits.next() as u64) << 32; + } + if let (Some(last), r @ 1..=63) = (row.last_mut(), t % 64) { + *last &= (1u64 << r) - 1; + } + } + return; + } + let tf = t as f64; + let m = (tf / (4.0 * self.r).max(16.0)).floor().clamp(1.0, tf) as i64; + let c = tf / m as f64; + let cdf = poisson_cdf(self.lambda * c * c); + let (lo, hi) = (y0 as f64 - self.r - 1.0, (y0 + rows) as f64 + self.r + 1.0); + for cy in (lo / c).floor() as i64..=(hi / c).floor() as i64 { + let wy = cy.rem_euclid(m) as u32; + for cx in 0..m { + let mut h = Stream(hash(self.seed ^ (self.index << 20), cx as u32, wy, 0xce11)); + for _ in 0..poisson(&cdf, h.next()) { + let (u, v) = (unit(h.next()), unit(h.next())); + self.splat((cx as f64 + u) * c, (cy as f64 + v) * c, t, y0, w, cover); + } + } + } + } + + /// Marks the pixels whose centres the crystal at (`px`, `py`) covers (see [`Self::draw`]). + #[inline] + fn splat(&self, px: f64, py: f64, t: usize, y0: usize, w: usize, cover: &mut [u64]) { + let rows = cover.len() / w.max(1); + if let Some(st) = &self.stamp { + let (bx, by) = (px.floor(), py.floor()); + let (qx, qy) = ((((px - bx) * PHASES as f64) as usize).min(PHASES - 1), (((py - by) * PHASES as f64) as usize).min(PHASES - 1)); + let (bx, by) = (bx as i64, by as i64); + let Some(&(a, b)) = st.rows.get(qy) else { return }; + let (lo, hi) = ((by + a as i64).max(y0 as i64), (by + b as i64).min((y0 + rows) as i64 - 1)); + let base = (qy * PHASES + qx) * st.height; + let Some(spans) = st.spans.get(base + (lo - by - a as i64).max(0) as usize..) else { return }; + for (j, &(o0, o1)) in (lo..=hi).zip(spans) { + if o0 <= o1 { + let off = (j as usize - y0) * w; + if let Some(row) = cover.get_mut(off..off + w) { + set_wrapped(row, t, bx + o0 as i64, bx + o1 as i64); + } + } + } + return; + } + let first = (py + self.y0 - 0.5).ceil().max(y0 as f64); + let last = (py + self.y1 - 0.5).floor().min((y0 + rows) as f64 - 1.0); + if last < first { + return; + } + for j in first as usize..=last as usize { + let (xl, xr) = self.span(j as f64 + 0.5 - py); + let (i0, i1) = ((px + xl - 0.5).ceil() as i64, (px + xr - 0.5).floor() as i64); + if i1 < i0 { + continue; + } + let Some(row) = cover.get_mut((j - y0) * w..(j - y0 + 1) * w) else { continue }; + set_wrapped(row, t, i0, i1); + } + } +} + +/// Sets bits `a..=b` (`a ≤ b`) of a row of words. +#[inline] +fn set_bits(row: &mut [u64], a: usize, b: usize) { + let (wa, wb) = (a >> 6, b >> 6); + let (lo, hi) = (!0u64 << (a & 63), !0u64 >> (63 - (b & 63))); + if wa == wb { + if let Some(v) = row.get_mut(wa) { + *v |= lo & hi; + } + return; + } + if let Some(v) = row.get_mut(wa) { + *v |= lo; + } + for v in row.iter_mut().take(wb).skip(wa + 1) { + *v = !0; + } + if let Some(v) = row.get_mut(wb) { + *v |= hi; + } +} + +/// Sets pixels `i0..=i1` of a periodic row of `t` pixels (`i0 ≤ i1`, within one period of +/// `0..t`: the crystal centres are in `0..t`). +#[inline] +fn set_wrapped(row: &mut [u64], t: usize, i0: i64, i1: i64) { + let ti = t as i64; + if i0 >= 0 && i1 < ti { + set_bits(row, i0 as usize, i1 as usize); + return; + } + if t == 0 { + return; + } + if i1 - i0 + 1 >= ti { + set_bits(row, 0, t - 1); + return; + } + let (a, b) = if i0 < 0 { + (i0 + ti, i1 + ti) + } else if i0 >= ti { + (i0 - ti, i1 - ti) + } else { + (i0, i1) + }; + let (a, b) = (a.clamp(0, ti - 1) as usize, b.max(0) as usize); + if b < t { + set_bits(row, a, b); + } else { + set_bits(row, a, t - 1); + set_bits(row, 0, (b - t).min(t - 1)); + } +} + +/// Bit planes of the layer counts (enough for 127 layers per torus). +const PLANES: usize = 7; + +/// Adds one layer's `cover` bits to the bit-sliced counters `planes` (`PLANES × cover.len()`). +#[inline] +fn add_layer(planes: &mut [u64], cover: &[u64]) { + let n = cover.len(); + for (i, &c) in cover.iter().enumerate() { + let mut carry = c; + for p in 0..PLANES { + if carry == 0 { + break; + } + let Some(slot) = planes.get_mut(p * n + i) else { break }; + let s = *slot; + *slot = s ^ carry; + carry &= s; + } + } +} + +// ---- tiles + +/// The emulsion drawn on the two tori: each as a summed-area table of its grain (layer count less +/// its mean), scaled so that the sum of both, averaged over a reference pixel, has unit variance. +pub struct CrystalTile { + pub look: CrystalLook, + /// `(side + 1)²` entries each: `sat[t][y·(side + 1) + x]` = sum over `[0, x) × [0, y)`. + pub sats: [Vec; 2], +} + +impl std::fmt::Debug for CrystalTile { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CrystalTile").field("look", &self.look).finish_non_exhaustive() + } +} + +/// Layer counts of torus `which` (side `t`): `t × t`, row-major. +fn draw_torus(which: usize, t: usize, seed: u32, look: &CrystalLook) -> Vec { + let layers: Vec = emulsion(seed, look).into_iter().filter(|l| l.index as usize % 2 == which).collect(); + let w = t.div_ceil(64); + let mut count = vec![0u8; t * t]; + par_rows(&mut count, t * BAND, |band, out| { + let rows = out.len() / t.max(1); + let n = rows * w; + let (mut cover, mut planes) = (vec![0u64; n], vec![0u64; PLANES * n]); + for layer in &layers { + cover.fill(0); + layer.draw(t, band * BAND, w, &mut cover); + add_layer(&mut planes, &cover); + } + for (j, row) in out.chunks_mut(t.max(1)).enumerate() { + for (i, o) in row.iter_mut().enumerate() { + let (word, bit) = (j * w + i / 64, i % 64); + *o = (0..PLANES).fold(0u8, |c, p| c | ((planes.get(p * n + word).map_or(0, |v| (v >> bit) & 1) as u8) << p)); + } + } + }); + count +} + +/// Integer summed-area table of `count` (`t × t`): `(t + 1)²` entries. +fn summed_area(count: &[u8], t: usize) -> Vec { + let s = t + 1; + let mut sat = vec![0u32; s * s]; + // row prefix sums in parallel, then each row adds the one above + par_rows(&mut sat, s, |y, row| { + let Some(src) = y.checked_sub(1).and_then(|y| count.get(y * t..(y + 1) * t)) else { return }; + let mut acc = 0u32; + for (o, &c) in row.iter_mut().skip(1).zip(src) { + acc += c as u32; + *o = acc; + } + }); + for y in 1..s { + let (above, below) = sat.split_at_mut(y * s); + let (Some(prev), Some(row)) = (above.get((y - 1) * s..), below.get_mut(..s)) else { continue }; + for (o, &p) in row.iter_mut().zip(prev) { + *o = o.wrapping_add(p); + } + } + sat +} + +/// Sum over the reference pixels (2 × 2 tile pixels) of torus `count` (`t × t`, `t` even) of +/// their squared deviation from `mean` (per tile pixel), and the number of reference pixels. +fn reference_square_sum(count: &[u8], t: usize, mean: f64) -> (f64, usize) { + let h = t / 2; + let mut rows = vec![0.0f64; h]; + par_rows(&mut rows, 1, |y, out| { + let (Some(a), Some(b)) = (count.get(2 * y * t..(2 * y + 1) * t), count.get((2 * y + 1) * t..(2 * y + 2) * t)) else { return }; + let mut s = 0.0; + for (&[a0, a1], &[b0, b1]) in a.as_chunks::<2>().0.iter().zip(b.as_chunks::<2>().0) { + let q = (a0 as u32 + a1 as u32 + b0 as u32 + b1 as u32) as f64 / 4.0 - mean; + s += q * q; + } + if let Some(o) = out.first_mut() { + *o = s; + } + }); + (rows.iter().sum(), h * h) +} + +impl CrystalTile { + /// Draws the emulsion of `look` with `seed`, or `None` if it has no grain (no variance). + pub fn new(look: CrystalLook, seed: u32) -> Option { + let [t0, t1] = TORI; + let (c0, c1) = lightcraft_raster::par_join(|| draw_torus(0, t0, seed, &look), || draw_torus(1, t1, seed, &look)); + let mut var = 0.0; + let mut tori = Vec::with_capacity(2); + for (count, t) in [(c0, t0), (c1, t1)] { + let mean = count.iter().map(|&c| c as u64).sum::() as f64 / (t * t).max(1) as f64; + let (sq, n) = reference_square_sum(&count, t, mean); + var += sq / n.max(1) as f64; + tori.push((summed_area(&count, t), t, mean)); + } + if !(var > 1e-12 && var.is_finite()) { + return None; + } + let k = 1.0 / var.sqrt(); + let mut sats = tori.into_iter().map(|(sat, t, mean)| { + let s = t + 1; + let mut out = vec![0.0f32; s * s]; + par_rows(&mut out, s, |y, row| { + for (x, (o, &v)) in row.iter_mut().zip(sat.get(y * s..).unwrap_or_default()).enumerate() { + *o = ((v as f64 - mean * (x * y) as f64) * k) as f32; + } + }); + out + }); + Some(CrystalTile { look, sats: [sats.next()?, sats.next()?] }) + } + + /// Sum of torus `which`'s grain over the box `[x0, x0 + w] × [y0, y0 + w]` (tile pixels, + /// `0 ≤ w < side`), the table bilinearly interpolated: the exact integral of the pixels. + #[inline] + fn box_sum(&self, which: usize, x0: f32, y0: f32, w: f32) -> f32 { + let (Some(sat), Some(&t)) = (self.sats.get(which), TORI.get(which)) else { return 0.0 }; + let tf = t as f32; + let (x0, y0) = (x0 - (x0 / tf).floor() * tf, y0 - (y0 / tf).floor() * tf); + let at = |x: f32, y: f32| integral(sat, t, x, y); + at(x0 + w, y0 + w) - at(x0, y0 + w) - at(x0 + w, y0) + at(x0, y0) + } + + /// Mean grain over the square of side `w` centred on (`x`, `y`) (tile pixels): unit variance + /// at `w` = 2 (a 6000 px render). + #[inline] + pub fn field(&self, x: f32, y: f32, w: f32) -> f32 { + let (x0, y0) = (x - 0.5 * w, y - 0.5 * w); + (self.box_sum(0, x0, y0, w) + self.box_sum(1, x0, y0, w)) / (w * w) + } +} + +/// The table `sat` (side `t + 1`) bilinearly interpolated at (`x`, `y`) in `0..=t`. +#[inline] +fn bilinear(sat: &[f32], t: usize, x: f32, y: f32) -> f32 { + let s = t + 1; + let (i, j) = ((x.max(0.0) as usize).min(t - 1), (y.max(0.0) as usize).min(t - 1)); + let (fx, fy) = (x - i as f32, y - j as f32); + let g = |i: usize, j: usize| sat.get(j * s + i).copied().unwrap_or(0.0); + let a = g(i, j) + (g(i + 1, j) - g(i, j)) * fx; + let b = g(i, j + 1) + (g(i + 1, j + 1) - g(i, j + 1)) * fx; + a + (b - a) * fy +} + +/// The periodic grain's integral over `[0, x) × [0, y)` for `x`, `y` in `0..2t`. +#[inline] +fn integral(sat: &[f32], t: usize, x: f32, y: f32) -> f32 { + let tf = t as f32; + let (wx, wy) = (x >= tf, y >= tf); + let (rx, ry) = (if wx { x - tf } else { x }, if wy { y - tf } else { y }); + let mut v = bilinear(sat, t, rx, ry); + if wx { + v += bilinear(sat, t, tf, ry); + } + if wy { + v += bilinear(sat, t, rx, tf); + } + if wx && wy { + v += bilinear(sat, t, tf, tf); + } + v +} + +// ---- the render's grain + +/// The crystal grain of one render. +#[derive(Clone, Debug)] +pub struct CrystalGrain { + pub tile: Arc, + /// Encoded-luminance amplitude at unit field and unit tone weight. + pub k: f32, + /// An output pixel's side in tile pixels. + pub foot: f32, +} + +type Key = (u64, u64, u32); +static TILES: Mutex)>> = Mutex::new(Vec::new()); + +/// The tile of `look` and `seed`, drawn or from the cache. +fn tile(look: CrystalLook, seed: u32) -> Option> { + let key = (look.width.to_bits(), look.spread.to_bits() ^ (look.layers as u64).rotate_left(40), seed); + { + let cache = TILES.lock().unwrap_or_else(PoisonError::into_inner); + if let Some((_, t)) = cache.iter().find(|(k, _)| *k == key) { + return Some(t.clone()); + } + } + let t = Arc::new(CrystalTile::new(look, seed)?); + let mut cache = TILES.lock().unwrap_or_else(PoisonError::into_inner); + cache.retain(|(k, _)| *k != key); + if cache.len() >= CACHE { + cache.remove(0); + } + cache.push((key, t.clone())); + Some(t) +} + +/// The tone weight of an encoded channel value `v` (0..1): `Y·dV/dY` of the sRGB curve, i.e. how +/// much `v` moves when the channel's linear light is scaled. +#[inline] +pub fn lift(v: f32) -> f32 { + let v = v.clamp(0.0, 1.0); + if v <= 0.040_45 { v } else { (v + 0.055) / 2.4 } +} + +/// The tone weight at mid grey (what [`CrystalGrain::k`] is calibrated at). +fn mid_weight() -> f32 { + lift(MID_GREY) * (1.0 - srgb_to_linear(MID_GREY)) +} + +impl CrystalGrain { + /// The grain of `g` at `px_per_long` output pixels per long edge (`None`: no grain). + pub fn new(g: &Grain, px_per_long: f64) -> Option { + let levels = strength_levels(g.amount, g.size, g.roughness); + if !(levels > 0.0 && px_per_long.is_finite() && px_per_long > 0.0) { + return None; + } + let foot = (TILE_PER_LONG / px_per_long) as f32; + if !(foot.is_finite() && foot > 0.0 && foot < MAX_FOOTPRINT) { + return None; + } + let tile = tile(CrystalLook::new(g.size, g.roughness), g.seed)?; + Some(CrystalGrain { tile, k: (levels / 255.0) as f32 / mid_weight(), foot }) + } + + /// Display-encoded colour `e` with grain, at frame position (`gx`, `gy`) (fractions of the + /// frame's long edge). + #[inline] + pub fn apply(&self, e: [f32; 3], gx: f32, gy: f32) -> [f32; 3] { + if !(gx.is_finite() && gy.is_finite()) { + return e; + } + let tpl = TILE_PER_LONG as f32; + let g = self.tile.field(gx * tpl, gy * tpl, self.foot); + let lum = (0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2]).clamp(0.0, 1.0); + let k = self.k * g * (1.0 - srgb_to_linear(lum)); + if !k.is_finite() { + return e; + } + e.map(|v| v + k * lift(v)) + } +} + +#[cfg(test)] +#[path = "tests_crystal.rs"] +mod tests; diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index aa194252e9..b6a9b334fa 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -85,6 +85,48 @@ fn vignette(s: &DevelopSettings) -> Option { /// Hash constants of [`grain_noise`] (shared with the GPU kernel). pub const GRAIN_HASH: [u32; 4] = [0x8da6_b343, 0xd816_3841, 0xcb1a_b31f, 0x5bd1_e995]; +/// The grain of processes V1 and V2: two octaves of value noise. Frozen: photos on those +/// processes keep rendering with it (`docs/process-versions.md`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ValueGrain { + /// Amplitude (display-encoded). + pub amt: f32, + /// Noise cell size (output pixels). + pub cell: f32, + /// Roughness 0..1: weight of the finer octave. + pub rough: f32, + pub seed: u32, +} + +/// A render's film grain. The model follows the photo's process: changing it would change how +/// existing photos look, so the crystal grain came with process V3. +#[derive(Clone, Debug)] +pub enum GrainModel { + /// V1 and V2: value noise. + Value(ValueGrain), + /// V3 and later: crystal layers ([`crate::crystal`]). + Crystal(crate::crystal::CrystalGrain), +} + +impl GrainModel { + /// The grain `s` renders with at `px_per_long` output pixels per long edge (`None`: none). + pub fn new(s: &DevelopSettings, px_per_long: f64) -> Option { + let g = &s.grain; + match s.process.process() { + Process::V1 | Process::V2 => (g.amount > 0.0).then(|| { + let cell = (0.0006 + (g.size / 100.0) as f32 * 0.0024) * px_per_long as f32; + GrainModel::Value(ValueGrain { + amt: (g.amount / 100.0) as f32 * 0.13, + cell: cell.max(0.6), + rough: (g.roughness / 100.0) as f32, + seed: g.seed, + }) + }), + Process::V3 => crate::crystal::CrystalGrain::new(g, px_per_long).map(GrainModel::Crystal), + } + } +} + #[inline] fn grain_noise(x: f32, y: f32, seed: u32) -> f32 { // A degenerate frame (zero-width crop) maps pixels to NaN/inf coordinates: no grain there. @@ -183,8 +225,8 @@ pub struct FinishParams { pub air_pre: f32, pub gain: f32, pub ev: f32, - /// Grain: amount, cell size (px), roughness, seed. - pub grain: Option<(f32, f32, f32, u32)>, + /// Film grain: the model of the photo's process ([`GrainModel`]). + pub grain: Option, /// Output px → normalized oriented coordinates. pub out_to_norm: lightcraft_geom::Affine, pub ow: f64, @@ -229,10 +271,7 @@ impl FinishParams { && frame.oh.is_finite() && frame.ow.max(frame.oh) > 0.0 && out_to_norm.0.iter().all(|v| v.is_finite()); - let grain = (s.grain.amount > 0.0 && effects && finite_frame).then(|| { - let cell = (0.0006 + (s.grain.size / 100.0) as f32 * 0.0024) * px_per_long as f32; - ((s.grain.amount / 100.0) as f32 * 0.13, cell.max(0.6), (s.grain.roughness / 100.0) as f32, s.grain.seed) - }); + let grain = if effects && finite_frame { GrainModel::new(s, px_per_long) } else { None }; let calibration = s.section_enabled("calibration"); let peak = s.hdr.peak(); FinishParams { @@ -292,7 +331,7 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap { let l = &s.light; match s.process.process() { // V2 changes the Highlights/Shadows base (`local::tone_base`), not the tone map - Process::V1 | Process::V2 => match info.camera_tone.as_ref().filter(|_| info.raw) { + Process::V1 | Process::V2 | Process::V3 => match info.camera_tone.as_ref().filter(|_| info.raw) { Some(curve) => ToneMap::camera_hdr(curve, l.contrast, l.whites, l.blacks, peak), None if info.raw => ToneMap::hdr(l.contrast, l.whites, l.blacks, peak), None => ToneMap::display_hdr(l.contrast, l.whites, l.blacks, peak), @@ -521,20 +560,28 @@ pub(crate) fn finish_with( e = refine_saturation(e0, e, fp.refine_sat); } } - if let Some((amt, cell, rough, seed)) = *grain { - let n = out_to_norm.apply(Point::new(x as f64 + 0.5, y as f64 + 0.5)); - let (gx, gy) = ((n.x * fp.ow) as f32 / long as f32, (n.y * fp.oh) as f32 / long as f32); - let sc = fp.px_per_long as f32 / cell; - let mut g = grain_noise(gx * sc, gy * sc, seed); - g = g * (1.0 - rough * 0.5) + grain_noise(gx * sc * 2.3, gy * sc * 2.3, seed ^ 0x55) * rough * 0.7; - let mut lum = 0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2]; - if hdr { - lum = lum.clamp(0.0, 1.0); + match grain { + Some(GrainModel::Value(g)) => { + // V1/V2 (frozen): exactly the arithmetic those processes always had + let n = out_to_norm.apply(Point::new(x as f64 + 0.5, y as f64 + 0.5)); + let (gx, gy) = ((n.x * fp.ow) as f32 / long as f32, (n.y * fp.oh) as f32 / long as f32); + let sc = fp.px_per_long as f32 / g.cell; + let mut v = grain_noise(gx * sc, gy * sc, g.seed); + v = v * (1.0 - g.rough * 0.5) + grain_noise(gx * sc * 2.3, gy * sc * 2.3, g.seed ^ 0x55) * g.rough * 0.7; + let mut lum = 0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2]; + if hdr { + lum = lum.clamp(0.0, 1.0); + } + let k = g.amt * v * (0.35 + 2.6 * lum * (1.0 - lum)); + if k.is_finite() { + e = e.map(|v| v + k); + } } - let k = amt * g * (0.35 + 2.6 * lum * (1.0 - lum)); - if k.is_finite() { - e = e.map(|v| v + k); + Some(GrainModel::Crystal(g)) => { + let n = out_to_norm.apply(Point::new(x as f64 + 0.5, y as f64 + 0.5)); + e = g.apply(e, (n.x * fp.ow / long) as f32, (n.y * fp.oh / long) as f32); } + None => {} } let e = match &p_lut { Some((l, k)) if hdr => { diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs index d56e8fe82d..4eca5bea90 100644 --- a/crates/pipeline/src/lib.rs +++ b/crates/pipeline/src/lib.rs @@ -26,6 +26,7 @@ pub mod auto; pub mod blemish; pub mod colorops; +pub mod crystal; pub mod cull; pub mod curve; pub mod dust; @@ -750,6 +751,8 @@ mod tests; #[cfg(test)] mod tests_geometry; #[cfg(test)] +mod tests_grain; +#[cfg(test)] mod tests_hdr; #[cfg(test)] mod tests_local; diff --git a/crates/pipeline/src/local.rs b/crates/pipeline/src/local.rs index 6d09cf7557..3121bc9311 100644 --- a/crates/pipeline/src/local.rs +++ b/crates/pipeline/src/local.rs @@ -371,11 +371,11 @@ pub fn base_detail_radius(px_per_long: f64) -> usize { } /// Median radius (px) of the highlights/shadows base of `s`'s rendering process at `px_per_long`: -/// 0 (no median) under V1, [`base_detail_radius`] from V2. +/// 0 (no median) under V1, [`base_detail_radius`] from V2 (V3 changes only the grain). pub fn tone_base_detail(s: &DevelopSettings, px_per_long: f64) -> usize { match s.process.process() { Process::V1 => 0, - Process::V2 => base_detail_radius(px_per_long), + Process::V2 | Process::V3 => base_detail_radius(px_per_long), } } diff --git a/crates/pipeline/src/tests_crystal.rs b/crates/pipeline/src/tests_crystal.rs new file mode 100644 index 0000000000..c446c874f7 --- /dev/null +++ b/crates/pipeline/src/tests_crystal.rs @@ -0,0 +1,261 @@ +use super::*; + +/// The field rendered at `long` px per long edge on an `n × n` patch starting at pixel `origin`. +fn patch(tile: &CrystalTile, long: f64, n: usize, origin: usize) -> Vec { + let w = (TILE_PER_LONG / long) as f32; + (0..n * n).map(|k| tile.field(((origin + k % n) as f32 + 0.5) * w, ((origin + k / n) as f32 + 0.5) * w, w)).collect() +} + +fn std(v: &[f32]) -> f64 { + let m = v.iter().map(|&x| x as f64).sum::() / v.len() as f64; + (v.iter().map(|&x| (x as f64 - m).powi(2)).sum::() / v.len() as f64).sqrt() +} + +/// Lag (px) at which the autocorrelation (mean of horizontal and vertical) falls to ½. +fn half_width(v: &[f32], n: usize) -> f64 { + let m = v.iter().map(|&x| x as f64).sum::() / v.len() as f64; + let d: Vec = v.iter().map(|&x| x as f64 - m).collect(); + let var = d.iter().map(|x| x * x).sum::() / d.len() as f64; + let corr = |k: usize, horizontal: bool| { + let mut s = 0.0; + let mut c = 0usize; + for y in 0..n - if horizontal { 0 } else { k } { + for x in 0..n - if horizontal { k } else { 0 } { + let b = if horizontal { y * n + x + k } else { (y + k) * n + x }; + s += d[y * n + x] * d[b]; + c += 1; + } + } + s / c as f64 / var + }; + let mut out = 0.0; + for horizontal in [true, false] { + let mut prev = 1.0; + let mut w = 16.0; + for k in 1..16 { + let c = corr(k, horizontal); + if c <= 0.5 { + w = k as f64 - 1.0 + (prev - 0.5) / (prev - c).max(1e-9); + break; + } + prev = c; + } + out += w / 2.0; + } + out +} + +fn tile_of(size: f64, roughness: f64) -> Arc { + tile(CrystalLook::new(size, roughness), 7).expect("a tile") +} + +#[test] +fn reference_render_has_unit_variance_and_no_mean() { + let t = tile_of(25.0, 50.0); + let v = patch(&t, REF_LONG, 600, 37); + let m = v.iter().map(|&x| x as f64).sum::() / v.len() as f64; + assert!((std(&v) - 1.0).abs() < 0.05, "std {}", std(&v)); + assert!(m.abs() < 0.03, "mean {m}"); +} + +#[test] +fn small_render_is_the_downscaled_reference() { + for (size, rough) in [(0.0, 50.0), (25.0, 50.0), (100.0, 50.0), (25.0, 0.0), (25.0, 100.0)] { + let t = tile_of(size, rough); + for k in [2usize, 4, 8] { + let full = patch(&t, REF_LONG, 120 * k, 0); + let n = 120; + let down: Vec = (0..n * n) + .map(|q| { + let (x, y) = (q % n, q / n); + let mut s = 0.0; + for dy in 0..k { + for dx in 0..k { + s += full[(y * k + dy) * n * k + x * k + dx]; + } + } + s / (k * k) as f32 + }) + .collect(); + let small = patch(&t, REF_LONG / k as f64, n, 0); + let worst = down.iter().zip(&small).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max); + assert!(worst < 2e-3, "size {size} roughness {rough} 1/{k}: differs by {worst}"); + } + } +} + +#[test] +fn strength_matches_the_target_at_mid_grey() { + for (a, s, r) in [(50.0, 25.0, 50.0), (25.0, 25.0, 50.0), (50.0, 0.0, 50.0), (50.0, 100.0, 50.0), (50.0, 25.0, 0.0)] { + let g = CrystalGrain::new(&Grain { amount: a, size: s, roughness: r, seed: 3 }, REF_LONG).expect("grain"); + let n = 500; + let lum: Vec = (0..n * n) + .map(|k| { + let (x, y) = ((k % n) as f32 + 0.5, (k / n) as f32 + 0.5); + let e = g.apply([MID_GREY; 3], x / REF_LONG as f32, y / REF_LONG as f32); + (0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2]) * 255.0 + }) + .collect(); + let want = strength_levels(a, s, r); + assert!((std(&lum) / want - 1.0).abs() < 0.06, "{a}/{s}/{r}: {} levels, want {want}", std(&lum)); + } +} + +#[test] +fn tones_keep_their_mean() { + // the strongest settings in the shadows; near white, strong grain clips at 255 like any grain + let cases = [ + (100.0, 0.0, &[5.0f32, 20.0, 40.0, 60.0, 128.0, 255.0][..]), + (50.0, 0.0, &[200.0, 245.0][..]), + (50.0, 25.0, &[20.0, 128.0, 245.0, 255.0][..]), + ]; + for (amount, size, levels) in cases { + let g = CrystalGrain::new(&Grain { amount, size, roughness: 50.0, seed: 3 }, REF_LONG).expect("grain"); + for &level in levels { + let n = 400; + let mut sum = 0.0f64; + for k in 0..n * n { + let (x, y) = ((k % n) as f32 + 0.5, (k / n) as f32 + 0.5); + let e = g.apply([level / 255.0; 3], x / REF_LONG as f32, y / REF_LONG as f32); + sum += (e[1].clamp(0.0, 1.0) * 255.0) as f64; + } + let shift = sum / (n * n) as f64 - level as f64; + assert!(shift.abs() < 0.5, "{amount}/{size}: level {level} moved {shift:+.2}"); + } + } +} + +#[test] +fn hostile_settings_render_finite_or_no_grain() { + let bad = [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1e9, 1e9, 0.0]; + for &a in &bad { + for &s in &bad { + for &ppl in &[f64::NAN, 0.0, -5.0, 1.0, 24.0, 1e12, 6000.0] { + let g = Grain { amount: if a == 0.0 { 50.0 } else { a }, size: s, roughness: s, seed: u32::MAX }; + if let Some(c) = CrystalGrain::new(&g, ppl) { + for (x, y) in [(0.0, 0.0), (-3.5, 1e7), (f32::NAN, 0.2), (0.5, f32::INFINITY), (1.0, 0.6667)] { + let e = c.apply([0.5, 0.2, 0.9], x, y); + assert!(e.iter().all(|v| v.is_finite()), "{g:?} at {ppl}: {e:?}"); + } + } + } + } + } +} + +#[test] +fn seed_picks_the_pattern() { + let look = CrystalLook::new(25.0, 50.0); + let (a, b, c) = (tile(look, 1), tile(look, 1), tile(look, 2)); + let (Some(a), Some(b), Some(c)) = (a, b, c) else { panic!("tiles") }; + let (pa, pb, pc) = (patch(&a, REF_LONG, 64, 0), patch(&b, REF_LONG, 64, 0), patch(&c, REF_LONG, 64, 0)); + assert_eq!(pa, pb); + assert_ne!(pa, pc); +} + +/// Grain width (autocorrelation half-width at mid grey, 6000 px) at Lightroom Classic's +/// measured settings (open PR #1060's table); Size 0 is as fine as uncorrelated pixels get (0.5). +#[test] +fn width_matches_lightroom_classic() { + let lrc = [(0.0, 50.0, 0.5), (25.0, 50.0, 1.13), (100.0, 50.0, 3.38), (25.0, 0.0, 0.86), (25.0, 100.0, 1.54)]; + for (s, r, want) in lrc { + let got = half_width(&patch(&tile_of(s, r), REF_LONG, 360, 0), 360); + assert!((got / want - 1.0).abs() < 0.1, "size {s} roughness {r}: width {got:.3}, want {want}"); + } +} + +/// Prints how long drawing a tile takes per setting (`--ignored --nocapture`, alone). +#[test] +#[ignore] +fn tile_timing_report() { + for (s, r) in [(0.0, 50.0), (10.0, 50.0), (25.0, 50.0), (50.0, 50.0), (100.0, 50.0), (25.0, 0.0), (25.0, 100.0), (100.0, 100.0)] { + let look = CrystalLook::new(s, r); + let mut best = f64::INFINITY; + for seed in 0..5 { + let start = std::time::Instant::now(); + let t = CrystalTile::new(look, 100 + seed); + best = best.min(start.elapsed().as_secs_f64() * 1e3); + assert!(t.is_some()); + } + eprintln!("size {s:>5} roughness {r:>5}: {best:.1} ms ({:?})", look); + } +} + +/// Fits the median crystal width per Size (Roughness 50) and the Roughness factors at Size 25 to +/// Lightroom Classic's grain widths (`--ignored --nocapture`; paste into the look tables). +#[test] +#[ignore] +fn fit_widths() { + let width_of = |look: CrystalLook| { + let mut w = 0.0; + for seed in [11, 12] { + let t = CrystalTile::new(look, seed).expect("tile"); + w += half_width(&patch(&t, REF_LONG, 360, 0), 360) / 2.0; + } + w + }; + let fit = |s: f64, r: f64, want: f64| { + let base = CrystalLook::new(s, r); + let (mut lo, mut hi) = (0.05f64, 40.0f64); + for _ in 0..18 { + let mid = (lo * hi).sqrt(); + if width_of(CrystalLook { width: mid, ..base }) < want { lo = mid } else { hi = mid } + } + let d = (lo * hi).sqrt(); + (d, width_of(CrystalLook { width: d, ..base })) + }; + for (s, want) in [(0.0, 0.43), (10.0, 0.71), (25.0, 1.13), (50.0, 1.70), (75.0, 2.54), (100.0, 3.38)] { + let (d, got) = fit(s, 50.0, want); + eprintln!("size {s}: width {d:.3} gives {got:.3} (want {want})"); + } + let (d50, _) = fit(25.0, 50.0, 1.13); + for (r, want) in [(0.0, 0.86), (100.0, 1.54)] { + let (d, got) = fit(25.0, r, want); + eprintln!("roughness {r}: factor {:.3} gives {got:.3} (want {want})", d / d50); + } +} + +/// Autocorrelation at lags 1–4 and the strength kept by box downscales of 2–16 (relative), of +/// candidate looks (`--ignored --nocapture`): compares a look's texture with a reference's. +#[test] +#[ignore] +fn texture_report() { + let profile = |look: CrystalLook| { + let n = 512; + let (mut acf, mut down) = ([0.0; 4], [0.0; 4]); + for seed in [21, 22] { + let t = CrystalTile::new(look, seed).expect("tile"); + let v = patch(&t, REF_LONG, n, 0); + let s0 = std(&v); + for (k, a) in acf.iter_mut().enumerate() { + let lag = k + 1; + let mut s = 0.0f64; + for y in 0..n { + for x in 0..n - lag { + s += (v[y * n + x] * v[y * n + x + lag] + v[x * n + y] * v[(x + lag) * n + y]) as f64; + } + } + *a += s / (2 * n * (n - lag)) as f64 / (s0 * s0) / 2.0; + } + for (k, d) in down.iter_mut().enumerate() { + let f = 2usize << k; + let m = n / f; + let b: Vec = (0..m * m) + .map(|q| { + let (x, y) = (q % m * f, q / m * f); + (0..f * f).map(|i| v[(y + i / f) * n + x + i % f]).sum::() / (f * f) as f32 + }) + .collect(); + *d += std(&b) / s0 / 2.0; + } + } + (acf, down) + }; + for (s, r) in [(25.0, 50.0), (50.0, 50.0), (100.0, 50.0), (25.0, 0.0), (25.0, 100.0)] { + let (a, d) = profile(CrystalLook::new(s, r)); + eprintln!( + "size {s} roughness {r}: acf {:.2} {:.2} {:.2} {:.2} down {:.2} {:.2} {:.2} {:.3}", + a[0], a[1], a[2], a[3], d[0], d[1], d[2], d[3] + ); + } +} diff --git a/crates/pipeline/src/tests_grain.rs b/crates/pipeline/src/tests_grain.rs new file mode 100644 index 0000000000..4c8dd554bd --- /dev/null +++ b/crates/pipeline/src/tests_grain.rs @@ -0,0 +1,82 @@ +//! Film grain through the whole pipeline: which model each process renders with, and the crystal +//! grain's resolution independence (`crate::crystal`). + +use lightcraft_develop::{DevelopSettings, Process}; +use lightcraft_raster::Rgb32f; + +use crate::finish::GrainModel; +use crate::{OutputDepth, RenderRequest, SourceInfo, render}; + +fn on(process: Process, amount: f64) -> DevelopSettings { + let mut s = DevelopSettings { process: process.version(), ..Default::default() }; + s.grain.amount = amount; + s +} + +/// Display-encoded luminance (0..255, 16-bit precision) of a render of `src` at `w × h`. +fn luma(src: &Rgb32f, s: &DevelopSettings, w: usize, h: usize) -> Vec { + let mut req = RenderRequest::fit(w, h); + req.depth = OutputDepth::U16; + let r = render(src, &SourceInfo::default(), s, &req); + let Some(crate::DeepSamples::U16(v)) = r.deep.map(|d| d.samples) else { panic!("no 16-bit render") }; + v.chunks(3).map(|p| (0.2126 * p[0] as f64 + 0.7152 * p[1] as f64 + 0.0722 * p[2] as f64) / 257.0).collect() +} + +fn std(v: &[f64]) -> f64 { + let m = v.iter().sum::() / v.len() as f64; + (v.iter().map(|x| (x - m).powi(2)).sum::() / v.len() as f64).sqrt() +} + +#[test] +fn processes_before_v3_keep_the_value_noise() { + for p in Process::ALL { + let model = GrainModel::new(&on(p, 40.0), 2000.0); + match p { + Process::V1 | Process::V2 => assert!(matches!(model, Some(GrainModel::Value(_))), "{p:?}"), + Process::V3 => assert!(matches!(model, Some(GrainModel::Crystal(_))), "{p:?}"), + } + assert!(GrainModel::new(&on(p, 0.0), 2000.0).is_none(), "{p:?}: no grain at Amount 0"); + } + let src = Rgb32f::filled(160, 120, [0.18; 3]); + let (v2, v3) = (luma(&src, &on(Process::V2, 50.0), 160, 120), luma(&src, &on(Process::V3, 50.0), 160, 120)); + assert_ne!(v2, v3, "V3 renders the crystal grain"); +} + +/// A preview shows what the export shows, box-downscaled to its size (whole pipeline). +#[test] +fn small_render_matches_the_downscaled_large_render() { + let src = Rgb32f::filled(300, 200, [0.18; 3]); + let (w, h, k) = (1200, 800, 4); + for size in [0.0, 25.0, 100.0] { + let mut s = on(Process::V3, 60.0); + s.grain.size = size; + let base = luma(&src, &on(Process::V3, 0.0), w, h); + let big: Vec = luma(&src, &s, w, h).iter().zip(&base).map(|(a, b)| a - b).collect(); + let down: Vec = (0..(w / k) * (h / k)) + .map(|q| { + let (x, y) = (q % (w / k) * k, q / (w / k) * k); + (0..k * k).map(|i| big[(y + i / k) * w + x + i % k]).sum::() / (k * k) as f64 + }) + .collect(); + let small = luma(&src, &s, w / k, h / k); + let ratio = std(&small) / std(&down); + assert!((0.95..1.05).contains(&ratio), "size {size}: preview / export grain {ratio:.3}"); + } +} + +/// Degenerate and hostile grain settings render finite pixels under V3. +#[test] +fn hostile_grain_settings_render() { + let src = Rgb32f::filled(40, 30, [0.5, 0.2, 0.05]); + for (amount, size, rough) in + [(f64::NAN, 25.0, 50.0), (1e9, -1e9, f64::INFINITY), (50.0, f64::NAN, f64::NAN), (100.0, 100.0, 100.0), (-5.0, 0.0, 0.0)] + { + let mut s = on(Process::V3, amount); + s.grain.size = size; + s.grain.roughness = rough; + s.grain.seed = u32::MAX; + for (w, h) in [(40, 30), (1, 1), (3, 400)] { + assert!(luma(&src, &s, w, h).iter().all(|v| v.is_finite()), "{amount}/{size}/{rough} at {w}×{h}"); + } + } +} diff --git a/docs/gpu-pipeline.md b/docs/gpu-pipeline.md index a35218c46d..bbabfea9c3 100644 --- a/docs/gpu-pipeline.md +++ b/docs/gpu-pipeline.md @@ -259,7 +259,7 @@ real failure still stops the whole process. Such a test asserts on its own rende `crates/gpu/tests/it/equivalence.rs` renders the same settings on both and compares 8-bit sRGB: bounds **mean |Δ| < 0.5 LSB and max |Δ| ≤ 3 LSB** per channel. Measured (Apple M4 Pro, Metal): **max 1 LSB, mean ≤ 0.0003 LSB** for every case — 26 settings cases (all tone/colour/effects tools, -3 vignette styles, grain, curves, grading, B&W, WB, NR, crop/straighten/flip, lens + perspective, +3 vignette styles, grain (value noise and crystal layers), curves, grading, B&W, WB, NR, crop/straighten/flip, lens + perspective, three mask sets incl. CPU-evaluated shapes, spots + defringe), all 8 orientations ± crop, embedded DNG lens data, display-referred sources, draft quality, full-size renders; the 24 MP export in `render_bench` also differs by max 1 LSB. Cached (slider-drag) GPU renders are bit-identical to diff --git a/docs/grain.md b/docs/grain.md new file mode 100644 index 0000000000..e1e9a351f8 --- /dev/null +++ b/docs/grain.md @@ -0,0 +1,106 @@ +# Film grain + +The Effects panel's Grain (`ctl:grain.amount`, `ctl:grain.size`, `ctl:grain.roughness`; XMP +`crs:GrainAmount`, `crs:GrainSize`, `crs:GrainFrequency`) draws grain from a simulated emulsion of +crystal layers: `crates/pipeline/src/crystal.rs` on the CPU, the same tables read by the GPU +kernel (`crates/gpu/src/wgsl/finish.wgsl`). + +This is the grain of **process V3** and later ([process-versions.md](process-versions.md)). Photos on +V1 or V2 keep the two-octave value noise they were edited with (`finish::ValueGrain`), so opening an +older catalog never changes a photo's grain; Update to Current Process moves a photo to the crystal +grain. The sliders, their ranges and their XMP names are unchanged. + +## Model + +After Aurélien Pierre, [*Stochastic photographic grain synthesis from crystallographic structure +simulation*](https://eng.aurelienpierre.com/2023/07/stochastic-photographic-grain-synthesis-from-crystallographic-structure-simulation/) +(2023). Implemented from the article's description of the method; no code was taken from it or from +any other implementation. + +- **Emulsion.** A stack of layers. Each layer has one crystal shape: a regular polygon of + `round(4.5 + z)` vertices (3–8), a random rotation, and a width (circumscribed diameter) drawn from a + log-normal distribution. The layers' widths are the quantiles of that distribution, dealt out in an + order the seed shuffles, so every seed has the same mix of sizes (the same grain strength and + width) in a different arrangement. +- **Crystals.** Each layer is a Boolean model: Poisson seeds grown into crystals, at the density + `λ = −ln(1 − F)/A` (crystal area `A`) that leaves a fraction `F = ½` of the layer covered. +- **Capture.** A point's grain is the number of layers covering it less the mean: many independent + layers of different crystal sizes add up to dense, soft, cloudy grain with no hard particle edges. +- **Print.** The light a crystal captures is proportional to the light falling on it, and a print + shows less grain towards paper white: the grain is `Y·(1 − Y)·g` in linear light (`Y` the pixel's + luminance), zero at black and at white. It is applied in the display-encoded domain, to first + order: each channel `v` moves by `k·lift(v)·(1 − Y)·g`, where `lift(v) = Y·dv/dY` of the sRGB curve. + In that domain the grain is symmetric, so it neither darkens shadows (the article's model in + linear light does, through the concave encoding) nor greys blown highlights, and it keeps hue. +- **Colour:** monochrome, as in Lightroom Classic. + +## Resolution independence + +The emulsion is drawn in frame coordinates at twice the resolution of a 6000 px export (a tile pixel +is half a reference pixel), on two periodic tiles (tori) of 640 and 567 reference pixels; layers +alternate between them. The tiles are stored as summed-area tables, so each output pixel takes the +**exact mean of the emulsion under its footprint** (16 table reads): a fit-to-window preview shows +the export's grain box-downscaled to its size, and an export larger than 6000 px (a 45 MP camera) +still shows crystals rather than enlarged pixels. The tori share no small factor: the two patterns +only line up again after 362,880 reference pixels, so the grain has no visible period. + +Measured on the comparison renders (four photos, six regions each, 1500 px preview against the +6000 px export box-downscaled to 1500 px): preview / export grain strength **1.00–1.04** at the +default, finest and coarsest settings. `crystal::tests::small_render_is_the_downscaled_reference` +checks it exactly at 1/2, 1/4 and 1/8 size; `tests_grain::small_render_matches_the_downscaled_large_render` +through the whole pipeline. + +## Mapping and calibration + +Amount, Size and Roughness keep Lightroom Classic's meaning: strength and width at mid grey match its +exports (the measurements of open PR #1060, `docs/grain.md` on that branch). + +| Quantity | Value | +|---|---| +| strength (levels of 255 at mid grey, 6000 px) | `Amount/100 · exp(2.447 + 1.386·exp(−Size/19.88)) · (1 − 0.084d + 1.6384d²)`, `d = Roughness/100 − ½`: 8.55 at 50 / 25 / 50 | +| median crystal width (reference px) | by Size: 0.55, 1.39, 2.95, 5.17, 8.78, 12.38 at 0, 10, 25, 50, 75, 100; × 0.734 / 1 / 1.422 at Roughness 0 / 50 / 100 (`fit_widths`) | +| width spread (log std) | `hypot(0.1 + 0.6·Roughness/100, 0.45)` | +| layers | by Size: 16, 31, 54, 70 at 0, 25, 50, 100 | + +- **Amount only scales the strength**: the amplitude is measured from the drawn emulsion itself (its + variance at the reference resolution), so every setting and seed has exactly its target strength, + and dragging Amount draws nothing new. In the article the layer count sets the strength; here it + sets only how dense the texture is (coarser grain averages more layers, so it stays a soft clump + texture). +- **Texture.** The width spread was chosen so the anti-aliased crystals have the texture of the + first, whole-pixel prototype at every scale, not just its width: autocorrelation at 1–5 px and the + strength kept by box downscales of 2–16 match it within a few hundredths + (`texture_report`). +- **Size 0** is as fine as the model gets: crystals narrower than a pixel, uncorrelated pixels + (width 0.51 px; Lightroom Classic's 0.43 needs anti-correlated grain). + +Measured (chart, 6000 px, 8-bit, against the same build without grain): + +| Amount / Size / Roughness | Strength at grey 20 · 128 · 245 | Width | Lightroom Classic at 128 | +|---|---|---|---| +| 25 / 25 / 50 | 1.66 · 4.29 · 1.67 | 1.11 | 4.29, 1.13 | +| 50 / 25 / 50 | 3.27 · 8.57 · 3.30 | 1.12 | 8.55, 1.13 | +| 100 / 25 / 50 | 6.53 · 17.14 · 6.36 | 1.12 | 17.01, 1.14 | +| 50 / 0 / 50 | 8.80 · 23.10 · 8.55 | 0.53 | 23.08, 0.43 | +| 50 / 50 / 50 | 2.46 · 6.42 · 2.43 | 1.70 | — | +| 50 / 100 / 50 | 2.24 · 5.83 · 2.19 | 3.39 | 5.83, 3.38 | +| 50 / 25 / 0 | 4.73 · 12.44 · 4.67 | 0.85 | 12.42, 0.86 | +| 50 / 25 / 100 | 4.46 · 11.75 · 4.37 | 1.53 | 11.68, 1.54 | + +Unlike Lightroom Classic's, the grain fades towards black and white (the print model). Mean +brightness change on 24 photo regions: within ±0.1 level on every dark and mid-tone region at every +setting (#1060: up to +3.8 on dark fabric at 50 / 0 / 50); up to −0.55 on sunlit skin at the +strongest settings, where grain clips at white; blown highlights stay clean (−0.01 on a blown +curtain; #1060: −9.3). Fine detail under the grain is kept (detail gain +0.96–1.00). + +## Performance + +- **Drawing the emulsion** (per Size, Roughness and seed; cached, so Amount drags and re-renders + draw nothing): every crystal is stamped as bit spans from a per-layer table of its rasterisation at + 16 × 16 sub-pixel phases, layers are counted in bit-sliced counters, and the tiles are drawn in + parallel bands. 5–17 ms on an M2 Max (12 threads) at any setting (`tile_timing_report`). +- **Per pixel:** two box sums, on the CPU and on the GPU; the tables (12 MB) follow the finish + kernel's other tables in its `aux` buffer. +- **24 MP NEF → PNG** (`lightcraft-cli render`, M2 Max, median of three): no grain 1.09 s, grain + 50 / 25 / 50 1.09 s on the GPU; 1.33 s and 1.49 s CPU-only (the finish stage 0.26 → 0.42 s). diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 46aabad737..9fb4c88fb4 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -203,7 +203,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-EDIT-EFFECTS-CLARITY | Clarity | P0 | ✅ | `ctl:effects.clarity` | | | LR-EDIT-EFFECTS-DEHAZE | Dehaze | P0 | ✅ | `ctl:effects.dehaze` | | | LR-EDIT-EFFECTS-VIGNETTE | Post-crop vignette | P0 | ✅ | `ctl:vignette.*`, `crates/pipeline/src/finish.rs`, `crates/ui-egui/src/panels/edit.rs` | style picker (Highlight / Color / Paint) in the Effects section | -| LR-EDIT-EFFECTS-GRAIN | Grain | P1 | ✅ | `ctl:grain.*` | | +| LR-EDIT-EFFECTS-GRAIN | Grain | P1 | ✅ | `ctl:grain.*`, `crates/pipeline/src/crystal.rs` | Process V3: crystal-layer grain ([grain.md](grain.md)), Lightroom Classic's strength and width at mid grey, fades out at black and white, preview = export box-downscaled; CPU + GPU. V1/V2 keep value noise | | LR-EDIT-DETAIL-SHARPEN | Sharpening | P0 | 🟡 | `ctl:detail.sharpenAmount`, `ctl:detail.sharpenRadius`, `ctl:detail.sharpenDetail`, `ctl:detail.sharpenMasking`, `crates/pipeline/src/visualize.rs` | Amount and Masking work; Radius and Detail are stored (XMP round trip) but do not change the render yet (the band is a fixed 0.18 % of the long edge). Alt/Option-drag previews: Amount greyscale, Radius / Detail the detail band sharpening amplifies, Masking the mask (white = sharpened) | | LR-EDIT-DETAIL-NR | Luminance noise reduction | P0 | ✅ | `ctl:detail.nrLuminance`, `ctl:detail.nrDetail`, `ctl:detail.nrContrast` | radii in the original's pixels, so grid, loupe and smaller exports look like the full-size render scaled down (`local::nr_params`, `Plan::detail_scale`, #960). Alt/Option-drag on Luminance, Detail and Contrast shows the photo in greyscale | | LR-EDIT-DETAIL-CNR | Colour noise reduction | P0 | ✅ | `ctl:detail.nrColor`, `ctl:detail.nrColorDetail`, `ctl:detail.nrColorSmoothness` | preview-size independent like luminance NR (#960) | diff --git a/docs/process-versions.md b/docs/process-versions.md index 7e6788f11e..ecac100b75 100644 --- a/docs/process-versions.md +++ b/docs/process-versions.md @@ -8,7 +8,8 @@ stronger Light sliders, issue #196) without changing a single photo someone has | Process | What it changes | |---|---| | **V1** | LightCraft's rendering from before process versions existed. Frozen. | -| **V2** (the latest) | Highlights and Shadows keep fine detail (issue #632): their base layer (`local::tone_base`) is the edge-aware filter of a separable median of log luminance (radius 0.15 % of the long edge, at most 24 px, `local::BASE_DETAIL`) instead of log luminance itself, so twigs, lines and texture take their surroundings' shift and keep their contrast; region edges stay sharp. CPU (`local::prepare`) and GPU prepare branch on `local::tone_base_detail` (0 = no median under V1); the base plane is cached per process (`local::BaseKey`). Renders without Highlights or Shadows (global or local) are the same as V1's. Tone map unchanged. | +| **V2** | Highlights and Shadows keep fine detail (issue #632): their base layer (`local::tone_base`) is the edge-aware filter of a separable median of log luminance (radius 0.15 % of the long edge, at most 24 px, `local::BASE_DETAIL`) instead of log luminance itself, so twigs, lines and texture take their surroundings' shift and keep their contrast; region edges stay sharp. CPU (`local::prepare`) and GPU prepare branch on `local::tone_base_detail` (0 = no median under V1); the base plane is cached per process (`local::BaseKey`). Renders without Highlights or Shadows (global or local) are the same as V1's. Tone map unchanged. | +| **V3** (the latest) | Film grain from crystal layers ([grain.md](grain.md), `crates/pipeline/src/crystal.rs`), after Aurélien Pierre's model: resolution independent (a preview is the export's grain box-downscaled), fading out at black and white, calibrated to Lightroom Classic's strength and width at mid grey. V1 and V2 keep their two-octave value noise exactly (`finish::ValueGrain`; on the GPU `F_GRAIN_MODEL` 0); `finish::GrainModel::new` picks the model per process. Renders without grain are the same as V2's. Other open PRs also propose a V3: whichever lands second renumbers and keeps the other's change. | ## The rule diff --git a/docs/whats-new.md b/docs/whats-new.md index 98a0ac7157..d3eb0f198f 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,14 @@ # What's new in LightCraft +## 2026-11-02 + +### Film grain that looks like film +- Grain now comes from a simulated emulsion of crystal layers (after Aurélien Pierre's model): dense, soft and cloudy + rather than dots on top of the photo. It fades out towards black and white as on a print, so shadows keep their depth + and blown highlights stay clean, and the fit-to-window preview shows the grain you will export. Amount, Size and + Roughness keep their meaning and Lightroom Classic's strength and grain size. It is part of a new process version + (V3): photos you have already edited keep their grain until you update them to the current process. + ## 2026-10-30 ### The Flatpak may talk to the accessibility bus From 0c6cd98215c54d848aa3ab1b6b4e2f0e3815f938 Mon Sep 17 00:00:00 2001 From: Jeremy Hooke Date: Mon, 2 Nov 2026 23:34:16 +1100 Subject: [PATCH 02/14] LR-EDIT-EFFECTS-GRAIN: crystal grain a row at a time on the CPU An unrotated row's pixels share box edges: the summed-area tables are cut once along the row's two box edges and each pixel takes one interpolation per torus (9-10 ns per pixel against 27, either orientation). Rotated frames keep the per-pixel boxes; row_field_matches_per_pixel_field checks both agree. Co-Authored-By: Claude Opus 5.5 --- crates/pipeline/src/crystal.rs | 97 +++++++++++++++++++++++++++- crates/pipeline/src/finish.rs | 28 ++++++-- crates/pipeline/src/tests_crystal.rs | 61 +++++++++++++++++ 3 files changed, 181 insertions(+), 5 deletions(-) diff --git a/crates/pipeline/src/crystal.rs b/crates/pipeline/src/crystal.rs index ba2f2f7b9c..df5c3edebb 100644 --- a/crates/pipeline/src/crystal.rs +++ b/crates/pipeline/src/crystal.rs @@ -662,6 +662,75 @@ fn integral(sat: &[f32], t: usize, x: f32, y: f32) -> f32 { v } +/// The integral of torus `sat` (side `t`) over `[0, i) × [0, across)` (`along_x`) or +/// `[0, across) × [0, i)`, for `i` in `0..=t`: the table cut along a line, with the periodic part +/// of `across` folded in (`across` in `0..2t`). +fn line(sat: &[f32], t: usize, along_x: bool, across: f32, out: &mut Vec) { + let (tf, n) = (t as f32, t + 1); + let wrap = across >= tf; + let a = (if wrap { across - tf } else { across }).clamp(0.0, tf); + let j = (a as usize).min(t.saturating_sub(1)); + let f = (a - j as f32) as f64; + out.clear(); + out.resize(n, 0.0); + // entry `i` of table line `k` (a row when cutting along x, a column when along y) + let at = |k: usize, i: usize| if along_x { sat.get(k * n + i) } else { sat.get(i * n + k) }.copied().unwrap_or(0.0) as f64; + for (i, o) in out.iter_mut().enumerate() { + let (p, q) = (at(j, i), at(j + 1, i)); + *o = p + (q - p) * f + if wrap { at(t, i) } else { 0.0 }; + } +} + +/// [`line`] interpolated at `x ≥ 0` (any number of periods along). +#[inline] +fn along(line: &[f64], t: usize, inv_t: f64, x: f64) -> f64 { + let tf = t as f64; + let q = (x * inv_t).floor().max(0.0); + let r = (x - q * tf).clamp(0.0, tf); + let i = (r as usize).min(t.saturating_sub(1)); + let f = r - i as f64; + let (Some(&a), Some(&b), Some(&end)) = (line.get(i), line.get(i + 1), line.get(t)) else { return 0.0 }; + a + (b - a) * f + q * end +} + +impl CrystalTile { + /// The grain of a line of `out.len()` output pixels side by side, each a square of side `w` + /// (tile pixels), the first centred on (`x`, `y`), the next `step` (`±w`) along x (`along_x`) + /// or y. The table is cut once along the line's two box edges; each pixel then costs one + /// interpolation per torus instead of [`Self::field`]'s eight table lookups. + pub fn row_field(&self, x: f32, y: f32, w: f32, step: f32, along_x: bool, out: &mut [f32]) { + out.fill(0.0); + let n = out.len(); + let (pos, across) = if along_x { (x, y) } else { (y, x) }; + let sign = if step < 0.0 { -1.0 } else { 1.0 }; + let first = pos as f64 - 0.5 * step as f64; + let lowest = first.min(first + n as f64 * step as f64); + let (mut near, mut far) = (Vec::new(), Vec::new()); + for (which, &t) in TORI.iter().enumerate() { + let Some(sat) = self.sats.get(which) else { continue }; + let tf = t as f32; + let lo = across - 0.5 * w; + let lo = lo - (lo / tf).floor() * tf; + line(sat, t, along_x, lo, &mut near); + line(sat, t, along_x, lo + w, &mut far); + let shift = (lowest / t as f64).floor() * t as f64; + let inv_t = 1.0 / t as f64; + let edge = |k: usize| { + let e = first + k as f64 * step as f64 - shift; + along(&far, t, inv_t, e) - along(&near, t, inv_t, e) + }; + let mut prev = edge(0); + for (k, o) in out.iter_mut().enumerate() { + let next = edge(k + 1); + *o += (sign * (next - prev)) as f32; + prev = next; + } + } + let area = w * w; + out.iter_mut().for_each(|v| *v /= area); + } +} + // ---- the render's grain /// The crystal grain of one render. @@ -732,7 +801,33 @@ impl CrystalGrain { return e; } let tpl = TILE_PER_LONG as f32; - let g = self.tile.field(gx * tpl, gy * tpl, self.foot); + self.apply_field(e, self.tile.field(gx * tpl, gy * tpl, self.foot)) + } + + /// The grain field of a row of `out.len()` pixels whose first centre is at (`gx`, `gy`) and + /// which step (`dx`, `dy`) (fractions of the long edge), when the step is along x or y (an + /// unrotated frame in any orientation) and the pixels are squares of the render's size + /// (`false` otherwise: use [`Self::apply`] per pixel). + pub fn row(&self, gx: f64, gy: f64, dx: f64, dy: f64, out: &mut [f32]) -> bool { + let tpl = TILE_PER_LONG; + let ((sx, sy), w) = ((dx * tpl, dy * tpl), self.foot as f64); + let (step, along_x) = if sy.abs() <= 1e-6 { + (sx, true) + } else if sx.abs() <= 1e-6 { + (sy, false) + } else { + return false; + }; + if !(gx.is_finite() && gy.is_finite() && step.is_finite()) || (step.abs() - w).abs() > 1e-4 * w { + return false; + } + self.tile.row_field((gx * tpl) as f32, (gy * tpl) as f32, self.foot, step as f32, along_x, out); + true + } + + /// Display-encoded colour `e` with grain field value `g` (see [`CrystalTile::field`]). + #[inline] + pub fn apply_field(&self, e: [f32; 3], g: f32) -> [f32; 3] { let lum = (0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2]).clamp(0.0, 1.0); let k = self.k * g * (1.0 - srgb_to_linear(lum)); if !k.is_finite() { diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index b6a9b334fa..059c124609 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -149,6 +149,21 @@ fn grain_noise(x: f32, y: f32, seed: u32) -> f32 { a + (b - a) * v } +/// The crystal grain of output row `y` (`w` pixels) when its pixels are axis-aligned; empty +/// otherwise (and without crystal grain): the pixels then take it one by one. +fn crystal_row(fp: &FinishParams, y: usize, w: usize) -> Vec { + let Some(GrainModel::Crystal(g)) = &fp.grain else { return Vec::new() }; + let long = fp.ow.max(fp.oh); + let (a, b) = (fp.out_to_norm.apply(Point::new(0.5, y as f64 + 0.5)), fp.out_to_norm.apply(Point::new(1.5, y as f64 + 0.5))); + let (gx, gy) = (a.x * fp.ow / long, a.y * fp.oh / long); + let (dx, dy) = ((b.x - a.x) * fp.ow / long, (b.y - a.y) * fp.oh / long); + let mut out = vec![0.0; w]; + if !g.row(gx, gy, dx, dy, &mut out) { + out.clear(); + } + out +} + /// Number of per-mask terms in [`mask_terms`]. pub const MASK_TERMS: usize = 21; @@ -429,6 +444,8 @@ pub(crate) fn finish_with( let hdr = peak > 1.0; let mut out = vec![T::default(); w * h]; for_rows(&mut out, w, |y, row| { + // the crystal grain of the whole row at once when its pixels are axis-aligned + let crystal_row = crystal_row(fp, y, row.len()); for (x, px) in row.iter_mut().enumerate() { let i = y * w + x; let raw = p.img.data[i]; @@ -577,10 +594,13 @@ pub(crate) fn finish_with( e = e.map(|v| v + k); } } - Some(GrainModel::Crystal(g)) => { - let n = out_to_norm.apply(Point::new(x as f64 + 0.5, y as f64 + 0.5)); - e = g.apply(e, (n.x * fp.ow / long) as f32, (n.y * fp.oh / long) as f32); - } + Some(GrainModel::Crystal(g)) => match crystal_row.get(x) { + Some(&f) => e = g.apply_field(e, f), + None => { + let n = out_to_norm.apply(Point::new(x as f64 + 0.5, y as f64 + 0.5)); + e = g.apply(e, (n.x * fp.ow / long) as f32, (n.y * fp.oh / long) as f32); + } + }, None => {} } let e = match &p_lut { diff --git a/crates/pipeline/src/tests_crystal.rs b/crates/pipeline/src/tests_crystal.rs index c446c874f7..bd0ddbf7e8 100644 --- a/crates/pipeline/src/tests_crystal.rs +++ b/crates/pipeline/src/tests_crystal.rs @@ -259,3 +259,64 @@ fn texture_report() { ); } } + +/// A row computed with shared box edges equals the per-pixel boxes: any size, mirrored rows, rows +/// across the tori's seams and far from the origin. +#[test] +fn row_field_matches_per_pixel_field() { + let t = tile_of(25.0, 50.0); + for (w, sign, x, y) in [ + (2.0f32, 1.0f32, 3.3f32, 7.9f32), + (2.0, -1.0, 9000.2, 1275.0), + (8.0, 1.0, 11990.0, 2260.5), + (0.7, 1.0, 1279.6, 0.1), + (31.0, -1.0, 400.0, 1133.9), + ] { + for along_x in [true, false] { + let mut row = vec![0.0f32; 700]; + t.row_field(x, y, w, sign * w, along_x, &mut row); + for (k, &v) in row.iter().enumerate() { + let d = sign * w * k as f32; + let want = if along_x { t.field(x + d, y, w) } else { t.field(x, y + d, w) }; + assert!((v - want).abs() < 2e-3, "w {w} sign {sign} x {along_x} from ({x}, {y}), pixel {k}: {v} vs {want}"); + } + } + } +} + +/// Per-pixel cost of the grain on one thread (`--ignored --nocapture`). +#[test] +#[ignore] +fn pixel_cost_report() { + let g = CrystalGrain::new(&Grain { amount: 50.0, size: 25.0, roughness: 50.0, seed: 1 }, REF_LONG).expect("grain"); + let (w, h) = (4000usize, 600usize); + let mut sink = 0.0f32; + let t0 = std::time::Instant::now(); + for y in 0..h { + for x in 0..w { + sink += g.tile.field((x as f32 + 0.5) * 2.0, (y as f32 + 0.5) * 2.0, 2.0); + } + } + let per_pixel = t0.elapsed().as_secs_f64() / (w * h) as f64 * 1e9; + let mut row = vec![0.0; w]; + let t1 = std::time::Instant::now(); + for y in 0..h { + g.tile.row_field(1.0, (y as f32 + 0.5) * 2.0, 2.0, 2.0, true, &mut row); + sink += row[7]; + } + let per_row = t1.elapsed().as_secs_f64() / (w * h) as f64 * 1e9; + let t3 = std::time::Instant::now(); + for y in 0..h { + g.tile.row_field((y as f32 + 0.5) * 2.0, 1.0, 2.0, 2.0, false, &mut row); + sink += row[7]; + } + eprintln!("column {:.1} ns/px", t3.elapsed().as_secs_f64() / (w * h) as f64 * 1e9); + let t2 = std::time::Instant::now(); + for y in 0..h { + for x in 0..w { + sink += g.apply_field([0.4, 0.5, 0.6], (x + y) as f32 * 1e-4)[1]; + } + } + let tone = t2.elapsed().as_secs_f64() / (w * h) as f64 * 1e9; + eprintln!("field {per_pixel:.1} ns/px, row {per_row:.1} ns/px, tone {tone:.1} ns/px ({sink})"); +} From fe6e064975a0275f98faeb7e503cfb54889491d8 Mon Sep 17 00:00:00 2001 From: Jeremy Hooke Date: Tue, 3 Nov 2026 08:59:46 +1100 Subject: [PATCH 03/14] LR-EDIT-EFFECTS-GRAIN: crystal grain keeps slider drags in budget on slower machines Measured on a Ryzen 5 7545U with a Radeon 740M (RADV), where grain cost what the M2 Max hid: - The tables stay on the GPU between renders (Gpu::grain_tables) and are copied into the finish kernel's aux buffer on the device, instead of being appended to aux and uploaded (12 MB) on every render. Amount drag, 2.5 MP preview: 16.9 -> 11-15 ms a frame (no grain: 8 ms). - A draft render (a drag) doesn't wait for a tile it hasn't got: the last tile of the seed stands in while the new one is drawn in the background, on a pool of half the cores; the full render when the drag ends waits for the exact tile. Size drag: 62-66 -> 13-14 ms a frame. wasm drafts still wait. - Stamps draw each row as a 64-bit mask, a fixed number of rows per layer, rows outside the band landing in scratch rows around it: no branch per row. Tiles 10-20 % faster at every setting, bit-identical. Tests: GPU grain patterns in turn (same, new size, new roughness, new seed, back) match the CPU; a drag takes the last tile while the next is drawn, then the exact one. Co-Authored-By: Claude Opus 5.5 --- crates/gpu/src/ctx.rs | 40 +++++- crates/gpu/src/params.rs | 12 +- crates/gpu/src/render.rs | 17 ++- crates/gpu/tests/it/equivalence.rs | 27 ++++ crates/pipeline/src/crystal.rs | 177 +++++++++++++++++++++++---- crates/pipeline/src/finish.rs | 60 +++++---- crates/pipeline/src/lib.rs | 4 +- crates/pipeline/src/tests_crystal.rs | 33 ++++- crates/pipeline/src/tests_grain.rs | 4 +- docs/grain.md | 23 +++- 10 files changed, 330 insertions(+), 67 deletions(-) diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index 24048e7f22..068d866f33 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -337,6 +337,9 @@ pub struct Gpu { free: std::sync::Mutex>, /// Largest storage buffer the device accepts (bytes). pub max_buffer: u64, + /// The crystal grain tables of the last grain pattern, resident: a render (each Amount step + /// of a drag) copies them on the GPU instead of uploading their 12 MB again ([`Gpu::grain_tables`]). + grain: std::sync::Mutex, Buf)>>, } /// WGSL constants shared by every module (generated from the CPU pipeline's values). @@ -459,7 +462,7 @@ impl Gpu { }); let max_buffer = limits.max_storage_buffer_binding_size.min(limits.max_buffer_size); log::info!("gpu: {} ({:?}), {} kernels in {build_ms} ms, buffers ≤ {} MiB", info.name, info.backend, kernels.len(), max_buffer >> 20); - Ok(Gpu { device, queue, info, kernels, dummy, free: Default::default(), max_buffer }) + Ok(Gpu { device, queue, info, kernels, dummy, free: Default::default(), max_buffer, grain: Default::default() }) } /// A buffer of `len` 32-bit values with undefined contents (a recycled one when possible). @@ -641,6 +644,41 @@ impl Gpu { ); } + /// Record into `enc` a copy of `tile`'s summed-area tables (both tori, back to back) into + /// `dst` at value offset `at`, uploading them first unless they are the resident ones. False + /// when `dst` can't hold them (an over-limit placeholder: the render has failed already). + pub fn grain_tables( + &self, + enc: &mut wgpu::CommandEncoder, + tile: &std::sync::Arc, + dst: &Buf, + at: usize, + ) -> bool { + let len: usize = tile.sats.iter().map(Vec::len).sum(); + let (start, bytes) = ((at as u64) * 4, (len as u64) * 4); + if len == 0 || dst.raw().size() < start.saturating_add(bytes) { + return false; + } + let mut resident = self.grain.lock().unwrap_or_else(|e| e.into_inner()); + if !resident.as_ref().is_some_and(|(t, b)| std::sync::Arc::ptr_eq(t, tile) && b.raw().size() >= bytes) { + // the old tables go back to the pool first: one pattern's tables are resident at a time + *resident = None; + let buf = self.buffer(len); + if buf.raw().size() < bytes { + return false; + } + let mut off = 0u64; + for sat in &tile.sats { + self.queue.write_buffer(buf.raw(), off, bytemuck::cast_slice(sat)); + off += (sat.len() as u64) * 4; + } + *resident = Some((tile.clone(), buf)); + } + let Some((_, src)) = resident.as_ref() else { return false }; + enc.copy_buffer_to_buffer(src.raw(), 0, dst.raw(), start, bytes); + true + } + /// Stands in for a buffer that could not be created (the render has failed already). fn placeholder(&self) -> wgpu::Buffer { self.device.create_buffer(&wgpu::BufferDescriptor { diff --git a/crates/gpu/src/params.rs b/crates/gpu/src/params.rs index 4ab667731e..72c1e108ef 100644 --- a/crates/gpu/src/params.rs +++ b/crates/gpu/src/params.rs @@ -152,7 +152,8 @@ pub struct Present { } /// The `finish` kernel's parameter block and auxiliary table (tone LUT | chroma curve | sRGB LUT | curve LUTs | -/// mask terms | crystal grain tables) for `fp` with `masks` (their local adjustments' terms). +/// mask terms) for `fp` with `masks` (their local adjustments' terms). The crystal grain's tables go +/// after `aux` in the kernel's buffer ([`crate::render`] copies them there). pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Present) -> (Vec, Vec) { let mut aux: Vec = fp.tone.lut().to_vec(); aux.extend_from_slice(fp.tone.chroma_lut()); @@ -169,11 +170,14 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr for m in masks { aux.extend_from_slice(m); } + // the crystal grain's tables follow `aux` on the GPU without being part of it: they stay + // resident between renders ([`crate::Gpu::grain_tables`]) and the render copies them in let mut sat_off = [0u32; 2]; if let Some(GrainModel::Crystal(g)) = &fp.grain { - for (off, sat) in sat_off.iter_mut().zip(&g.tile.sats) { - *off = aux.len() as u32; - aux.extend_from_slice(sat); + let mut off = aux.len(); + for (slot, sat) in sat_off.iter_mut().zip(&g.tile.sats) { + *slot = off as u32; + off += sat.len(); } } diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index 9d6172d9c3..9b5f235a05 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -156,6 +156,20 @@ impl<'a> Cx<'a> { } } + /// The finish kernel's `aux` buffer: `aux`, then the crystal grain's tables when it has them + /// (copied on the GPU from the resident ones, see [`Gpu::grain_tables`]). + pub fn finish_aux(&mut self, aux: &[f32], grain: Option<&lightcraft_pipeline::finish::GrainModel>) -> Buf { + let Some(lightcraft_pipeline::finish::GrainModel::Crystal(g)) = grain else { return self.gpu.upload(aux) }; + let tables: usize = g.tile.sats.iter().map(Vec::len).sum(); + let out = self.gpu.buffer(aux.len().saturating_add(tables)); + if !aux.is_empty() && out.raw().size() >= (aux.len() as u64) * 4 { + self.gpu.queue.write_buffer(out.raw(), 0, bytemuck::cast_slice(aux)); + } + let enc = self.enc.get_or_insert_with(|| self.gpu.encoder()); + self.gpu.grain_tables(enc, &g.tile, &out, aux.len()); + out + } + /// Submit what is recorded and read back `len` values of `b`. pub fn read(&mut self, b: &Buf, len: usize) -> Vec { self.pending = 0; @@ -683,6 +697,7 @@ pub fn render( px_per_long: plan.px_per_long, air_pre: prep.air, space: req.space, + draft: req.quality == lightcraft_pipeline::Quality::Draft, }); // soft proofing as the CPU's `finish` sets it up (an output-device table never gets here: see `render`) fp.proof = req.proof.map(|pr| pr.params(req.space)); @@ -696,7 +711,7 @@ pub fn render( chroma: masks.is_some() && prep.chroma.is_some(), }; let (p, aux) = finish_block(&fp, &terms, &present); - let aux = gpu.upload(&aux); + let aux = cx.finish_aux(&aux, fp.grain.as_ref()); // cleared, so that work which never ran cannot pass for an image (see the check below) let out = cx.zeroed(n); if fault == Some(crate::Fault::Validation) { diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index 6a1a8464c4..1f0cf89a45 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -153,6 +153,33 @@ fn banded_full_size_render_matches() { check("banded 3000×2000", &src, &SourceInfo { raw: true, ..Default::default() }, &s, &RenderRequest::fit(w, h)); } +/// The crystal grain's tables stay on the GPU between renders: an Amount change reuses them, +/// another pattern (Size, Roughness, seed) replaces them, and going back draws the first again. +#[test] +fn grain_patterns_in_turn_match() { + if !gpu() { + return; + } + let src = scene(1, 480, 320); + let info = SourceInfo { raw: true, ..Default::default() }; + let steps: [(&str, f64, f64, f64, u32); 6] = [ + ("grain 50/25/50", 50.0, 25.0, 50.0, 1), + ("grain 90/25/50 (same pattern)", 90.0, 25.0, 50.0, 1), + ("grain 50/70/50 (new size)", 50.0, 70.0, 50.0, 1), + ("grain 50/70/0 (new roughness)", 50.0, 70.0, 0.0, 1), + ("grain 50/70/0 seed 7", 50.0, 70.0, 0.0, 7), + ("grain 50/25/50 again", 50.0, 25.0, 50.0, 1), + ]; + for (name, amount, size, roughness, seed) in steps { + let mut s = DevelopSettings::default(); + s.grain.amount = amount; + s.grain.size = size; + s.grain.roughness = roughness; + s.grain.seed = seed; + check(name, &src, &info, &s, &RenderRequest::fit(480, 320)); + } +} + fn cases() -> Vec<(&'static str, Edit)> { vec![ ("default", |_| {}), diff --git a/crates/pipeline/src/crystal.rs b/crates/pipeline/src/crystal.rs index df5c3edebb..6098e7e570 100644 --- a/crates/pipeline/src/crystal.rs +++ b/crates/pipeline/src/crystal.rs @@ -236,11 +236,29 @@ const STAMP_R: f64 = 16.0; /// `(X + qx/PHASES, Y + qy/PHASES)` (`X`, `Y` integers) it covers rows `Y + rows[qy].0 ..= Y + /// rows[qy].1`, and in row `Y + rows[qy].0 + k` the pixels `X + o.0 ..= X + o.1`, with /// `o = spans[(qy·PHASES + qx)·height + k]`. +/// +/// The same rows as bit masks, for drawing a crystal without a branch per row: phase +/// `p = qy·PHASES + qx` spans pixels `X + extent[p].0 ..= X + extent[p].1`, and its row `k` is +/// `masks[p·height + k]` shifted to `X + extent[p].0` (rows past the phase's own are empty). +/// `masks` is empty when a phase is wider than 64 pixels. #[derive(Clone, Debug)] struct Stamp { rows: [(i32, i32); PHASES], height: usize, spans: Vec<(i32, i32)>, + extent: Vec<(i32, i32)>, + masks: Vec, +} + +/// Where [`Layer::draw`] draws: rows `y0..y0 + rows` of a torus of side `t`, `w` words per row, +/// after `margin` scratch rows. +#[derive(Clone, Copy)] +struct Band { + t: usize, + y0: usize, + rows: usize, + w: usize, + margin: usize, } /// One emulsion layer: its crystal (a regular polygon) and seed density, in tile pixels. @@ -340,7 +358,25 @@ impl Layer { } } } - Stamp { rows, height, spans } + let mut extent = vec![(0, -1); PHASES * PHASES]; + let mut masks = vec![0u64; PHASES * PHASES * height]; + let mut fits = true; + for (p, e) in extent.iter_mut().enumerate() { + let Some(rows) = spans.get(p * height..(p + 1) * height) else { continue }; + let used = || rows.iter().filter(|(o0, o1)| o0 <= o1); + let (Some(lo), Some(hi)) = (used().map(|o| o.0).min(), used().map(|o| o.1).max()) else { continue }; + *e = (lo, hi); + fits &= hi - lo < 64; + for (m, &(o0, o1)) in masks.iter_mut().skip(p * height).zip(rows) { + if o0 <= o1 && o1 - lo < 64 { + *m = (!0u64 >> (63 - (o1 - o0))) << (o0 - lo); + } + } + } + if !fits { + masks.clear(); + } + Stamp { rows, height, spans, extent, masks } } /// The crystal's horizontal extent at height `y` above its centre (convex: one interval). @@ -352,12 +388,14 @@ impl Layer { } /// Sets the bits of the pixels the layer covers in rows `y0..` of a torus of side `t`: - /// `cover` holds whole rows of `w` words (bit `i % 64` of word `i / 64` is pixel `i`). - fn draw(&self, t: usize, y0: usize, w: usize, cover: &mut [u64]) { - let rows = cover.len() / w.max(1); + /// `cover` holds whole rows of `w` words (bit `i % 64` of word `i / 64` is pixel `i`), the + /// band's rows between `margin` rows above and below it (scratch: what lands there is not part + /// of the band; `margin` is at least the stamp's height). + fn draw(&self, t: usize, y0: usize, w: usize, margin: usize, cover: &mut [u64]) { + let rows = (cover.len() / w.max(1)).saturating_sub(2 * margin); if 2.0 * self.r < FINE { // each pixel covered with probability FILLING (one half: one random bit) - for (j, row) in cover.chunks_mut(w.max(1)).enumerate() { + for (j, row) in cover.chunks_mut(w.max(1)).skip(margin).take(rows).enumerate() { let mut bits = Stream(hash(self.seed, self.index, (y0 + j) as u32, 0xb175)); for v in row.iter_mut() { *v = bits.next() as u64 | (bits.next() as u64) << 32; @@ -379,7 +417,7 @@ impl Layer { let mut h = Stream(hash(self.seed ^ (self.index << 20), cx as u32, wy, 0xce11)); for _ in 0..poisson(&cdf, h.next()) { let (u, v) = (unit(h.next()), unit(h.next())); - self.splat((cx as f64 + u) * c, (cy as f64 + v) * c, t, y0, w, cover); + self.splat((cx as f64 + u) * c, (cy as f64 + v) * c, Band { t, y0, rows, w, margin }, cover); } } } @@ -387,22 +425,47 @@ impl Layer { /// Marks the pixels whose centres the crystal at (`px`, `py`) covers (see [`Self::draw`]). #[inline] - fn splat(&self, px: f64, py: f64, t: usize, y0: usize, w: usize, cover: &mut [u64]) { - let rows = cover.len() / w.max(1); + fn splat(&self, px: f64, py: f64, band: Band, cover: &mut [u64]) { + let Band { t, y0, rows, w, margin } = band; if let Some(st) = &self.stamp { let (bx, by) = (px.floor(), py.floor()); let (qx, qy) = ((((px - bx) * PHASES as f64) as usize).min(PHASES - 1), (((py - by) * PHASES as f64) as usize).min(PHASES - 1)); let (bx, by) = (bx as i64, by as i64); let Some(&(a, b)) = st.rows.get(qy) else { return }; let (lo, hi) = ((by + a as i64).max(y0 as i64), (by + b as i64).min((y0 + rows) as i64 - 1)); - let base = (qy * PHASES + qx) * st.height; - let Some(spans) = st.spans.get(base + (lo - by - a as i64).max(0) as usize..) else { return }; - for (j, &(o0, o1)) in (lo..=hi).zip(spans) { - if o0 <= o1 { - let off = (j as usize - y0) * w; - if let Some(row) = cover.get_mut(off..off + w) { - set_wrapped(row, t, bx + o0 as i64, bx + o1 as i64); + if hi < lo { + return; + } + // within the torus across: the whole stamp, a fixed number of rows of masks (those + // above or below the band land in the margins) + let p = qy * PHASES + qx; + if let (Some(&(e0, e1)), Some(masks)) = (st.extent.get(p), st.masks.get(p * st.height..(p + 1) * st.height)) { + let (xs, top) = (bx + e0 as i64, by + a as i64 - y0 as i64 + margin as i64); + if xs >= 0 && bx + (e1 as i64) < t as i64 && top >= 0 { + let (word, shift) = ((xs >> 6) as usize, (xs & 63) as u32); + // a bit past the row's last word would be a pixel ≥ t: the high word is then 0 + let start = top as usize * w + word; + for (k, &m) in masks.iter().enumerate() { + let v = (m as u128) << shift; + let i = start + k * w; + if let Some(c) = cover.get_mut(i) { + *c |= v as u64; + } + if let Some(c) = cover.get_mut(i + 1) { + *c |= (v >> 64) as u64; + } } + return; + } + } + // rows `lo..=hi` of the band, spans `k0..` of the stamp's rows (`hi ≤ by + b`: within its height) + let (k0, n) = ((lo - by - a as i64) as usize, (hi - lo + 1) as usize); + let base = (qy * PHASES + qx) * st.height + k0; + let (r0, r1) = (lo as usize - y0 + margin, hi as usize + 1 - y0 + margin); + let (Some(spans), Some(band)) = (st.spans.get(base..base + n), cover.get_mut(r0 * w..r1 * w)) else { return }; + for (row, &(o0, o1)) in band.chunks_exact_mut(w.max(1)).zip(spans) { + if o0 <= o1 { + set_wrapped(row, t, bx + o0 as i64, bx + o1 as i64); } } return; @@ -418,7 +481,7 @@ impl Layer { if i1 < i0 { continue; } - let Some(row) = cover.get_mut((j - y0) * w..(j - y0 + 1) * w) else { continue }; + let Some(row) = cover.get_mut((j - y0 + margin) * w..(j - y0 + margin + 1) * w) else { continue }; set_wrapped(row, t, i0, i1); } } @@ -519,15 +582,17 @@ impl std::fmt::Debug for CrystalTile { fn draw_torus(which: usize, t: usize, seed: u32, look: &CrystalLook) -> Vec { let layers: Vec = emulsion(seed, look).into_iter().filter(|l| l.index as usize % 2 == which).collect(); let w = t.div_ceil(64); + // scratch rows above and below a band, for the stamps' rows outside it (`Layer::splat`) + let margin = layers.iter().filter_map(|l| l.stamp.as_ref().map(|s| s.height)).max().unwrap_or(0); let mut count = vec![0u8; t * t]; par_rows(&mut count, t * BAND, |band, out| { let rows = out.len() / t.max(1); let n = rows * w; - let (mut cover, mut planes) = (vec![0u64; n], vec![0u64; PLANES * n]); + let (mut cover, mut planes) = (vec![0u64; n + 2 * margin * w], vec![0u64; PLANES * n]); for layer in &layers { cover.fill(0); - layer.draw(t, band * BAND, w, &mut cover); - add_layer(&mut planes, &cover); + layer.draw(t, band * BAND, w, margin, &mut cover); + add_layer(&mut planes, cover.get(margin * w..margin * w + n).unwrap_or_default()); } for (j, row) in out.chunks_mut(t.max(1)).enumerate() { for (i, o) in row.iter_mut().enumerate() { @@ -746,23 +811,77 @@ pub struct CrystalGrain { type Key = (u64, u64, u32); static TILES: Mutex)>> = Mutex::new(Vec::new()); -/// The tile of `look` and `seed`, drawn or from the cache. -fn tile(look: CrystalLook, seed: u32) -> Option> { +/// The tile being drawn in the background for a drag ([`tile`]): one at a time. +static DRAWING: Mutex> = Mutex::new(None); + +/// The tile of `look` and `seed`, drawn or from the cache. Unless `wait`, a tile not drawn yet +/// is drawn in the background and the last one drawn for `seed` stands in for it meanwhile: a +/// Size or Roughness drag doesn't wait for every step's tile (tens of milliseconds on a slow +/// CPU), and the full-quality render when it ends waits for the exact one. +fn tile(look: CrystalLook, seed: u32, wait: bool) -> Option> { let key = (look.width.to_bits(), look.spread.to_bits() ^ (look.layers as u64).rotate_left(40), seed); { let cache = TILES.lock().unwrap_or_else(PoisonError::into_inner); if let Some((_, t)) = cache.iter().find(|(k, _)| *k == key) { return Some(t.clone()); } + // (wasm has no threads to draw on) + if !wait + && !cfg!(target_arch = "wasm32") + && let Some((_, stand_in)) = cache.iter().rev().find(|(k, _)| k.2 == seed) + { + let stand_in = stand_in.clone(); + drop(cache); + draw_in_background(key, look, seed); + return Some(stand_in); + } } let t = Arc::new(CrystalTile::new(look, seed)?); + keep(key, t.clone()); + Some(t) +} + +/// Adds `t` to the cache (the most recent last). +fn keep(key: Key, t: Arc) { let mut cache = TILES.lock().unwrap_or_else(PoisonError::into_inner); cache.retain(|(k, _)| *k != key); if cache.len() >= CACHE { cache.remove(0); } - cache.push((key, t.clone())); - Some(t) + cache.push((key, t)); +} + +/// Draws the tile of `key` on the thread pool unless another is being drawn (the next render +/// asks again for what it needs then). +fn draw_in_background(key: Key, look: CrystalLook, seed: u32) { + { + let mut drawing = DRAWING.lock().unwrap_or_else(PoisonError::into_inner); + if drawing.is_some() { + return; + } + *drawing = Some(key); + } + let draw = move || { + if let Some(t) = CrystalTile::new(look, seed) { + keep(key, Arc::new(t)); + } + *DRAWING.lock().unwrap_or_else(PoisonError::into_inner) = None; + }; + // on a pool of its own: the renders of the drag don't queue behind its parallel bands + match background_pool() { + Some(pool) => pool.spawn(draw), + None => rayon::spawn(draw), + } +} + +/// Half the cores, for tiles drawn in the background (`None`: the pool couldn't be made). +fn background_pool() -> Option<&'static rayon::ThreadPool> { + static POOL: std::sync::OnceLock> = std::sync::OnceLock::new(); + POOL.get_or_init(|| { + let n = std::thread::available_parallelism().map_or(2, |n| n.get()).div_ceil(2); + rayon::ThreadPoolBuilder::new().num_threads(n).thread_name(|i| format!("grain-tile-{i}")).build().ok() + }) + .as_ref() } /// The tone weight of an encoded channel value `v` (0..1): `Y·dV/dY` of the sRGB curve, i.e. how @@ -781,6 +900,16 @@ fn mid_weight() -> f32 { impl CrystalGrain { /// The grain of `g` at `px_per_long` output pixels per long edge (`None`: no grain). pub fn new(g: &Grain, px_per_long: f64) -> Option { + Self::with(g, px_per_long, true) + } + + /// [`Self::new`] for a draft render (a drag): while its tile is drawn, the last tile drawn for + /// the same seed stands in for it (see [`tile`]). + pub fn draft(g: &Grain, px_per_long: f64) -> Option { + Self::with(g, px_per_long, false) + } + + fn with(g: &Grain, px_per_long: f64, wait: bool) -> Option { let levels = strength_levels(g.amount, g.size, g.roughness); if !(levels > 0.0 && px_per_long.is_finite() && px_per_long > 0.0) { return None; @@ -789,7 +918,7 @@ impl CrystalGrain { if !(foot.is_finite() && foot > 0.0 && foot < MAX_FOOTPRINT) { return None; } - let tile = tile(CrystalLook::new(g.size, g.roughness), g.seed)?; + let tile = tile(CrystalLook::new(g.size, g.roughness), g.seed, wait)?; Some(CrystalGrain { tile, k: (levels / 255.0) as f32 / mid_weight(), foot }) } diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index 059c124609..bf97e02d4a 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -109,8 +109,9 @@ pub enum GrainModel { } impl GrainModel { - /// The grain `s` renders with at `px_per_long` output pixels per long edge (`None`: none). - pub fn new(s: &DevelopSettings, px_per_long: f64) -> Option { + /// The grain `s` renders with at `px_per_long` output pixels per long edge (`None`: none); + /// `draft`: for a drag ([`crate::crystal::CrystalGrain::draft`]). + pub fn new(s: &DevelopSettings, px_per_long: f64, draft: bool) -> Option { let g = &s.grain; match s.process.process() { Process::V1 | Process::V2 => (g.amount > 0.0).then(|| { @@ -122,6 +123,7 @@ impl GrainModel { seed: g.seed, }) }), + Process::V3 if draft => crate::crystal::CrystalGrain::draft(g, px_per_long).map(GrainModel::Crystal), Process::V3 => crate::crystal::CrystalGrain::new(g, px_per_long).map(GrainModel::Crystal), } } @@ -264,12 +266,14 @@ pub struct FinishParamsInput<'a> { pub px_per_long: f64, pub air_pre: f32, pub space: OutputSpace, + /// A draft render (a drag, [`crate::Quality::Draft`]): see [`GrainModel::new`]. + pub draft: bool, } impl FinishParams { /// Parameters for a `w × h` render into `space`; `ev`/`air_pre` as in [`crate::Prepared`]. pub fn new(input: FinishParamsInput<'_>) -> FinishParams { - let FinishParamsInput { settings: s, frame, info, image_size: (w, h), px_per_long, air_pre, space } = input; + let FinishParamsInput { settings: s, frame, info, image_size: (w, h), px_per_long, air_pre, space, draft } = input; let effects = s.section_enabled("effects"); let (clar, tex, dehaze) = if effects { ((s.effects.clarity / 100.0) as f32, (s.effects.texture / 100.0) as f32, (s.effects.dehaze / 100.0) as f32) @@ -286,7 +290,7 @@ impl FinishParams { && frame.oh.is_finite() && frame.ow.max(frame.oh) > 0.0 && out_to_norm.0.iter().all(|v| v.is_finite()); - let grain = if effects && finite_frame { GrainModel::new(s, px_per_long) } else { None }; + let grain = if effects && finite_frame { GrainModel::new(s, px_per_long, draft) } else { None }; let calibration = s.section_enabled("calibration"); let peak = s.hdr.peak(); FinishParams { @@ -354,18 +358,20 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap { } } -pub(crate) fn finish( - p: &Prepared, - s: &DevelopSettings, - frame: &Frame, - info: &SourceInfo, - space: OutputSpace, - display: Option<&crate::DisplaySpace>, - proof: Option, -) -> Rgba8 { +pub(crate) fn finish(p: &Prepared, s: &DevelopSettings, frame: &Frame, info: &SourceInfo, req: &crate::RenderRequest) -> Rgba8 { + let (space, display, proof) = (req.space, req.display.as_ref(), req.proof); let (w, h) = (p.img.width, p.img.height); - let mut fp = - FinishParams::new(FinishParamsInput { settings: s, frame, info, image_size: (w, h), px_per_long: p.px_per_long, air_pre: p.air, space }); + let draft = req.quality == crate::Quality::Draft; + let mut fp = FinishParams::new(FinishParamsInput { + settings: s, + frame, + info, + image_size: (w, h), + px_per_long: p.px_per_long, + air_pre: p.air, + space, + draft, + }); fp.proof = proof.map(|pr| pr.params(space)); if let Some(d) = display { fp.for_display(d, proof); @@ -382,19 +388,21 @@ pub(crate) fn finish( } /// [`finish`] into 16-bit display-encoded or 32-bit float linear samples (output primaries). -pub(crate) fn finish_deep( - p: &Prepared, - s: &DevelopSettings, - frame: &Frame, - info: &SourceInfo, - space: OutputSpace, - depth: OutputDepth, - proof: Option, -) -> DeepImage { +pub(crate) fn finish_deep(p: &Prepared, s: &DevelopSettings, frame: &Frame, info: &SourceInfo, req: &crate::RenderRequest) -> DeepImage { use lightcraft_color::transfer::srgb_to_linear; + let (space, depth, proof) = (req.space, req.depth, req.proof); let (w, h) = (p.img.width, p.img.height); - let mut fp = - FinishParams::new(FinishParamsInput { settings: s, frame, info, image_size: (w, h), px_per_long: p.px_per_long, air_pre: p.air, space }); + let draft = req.quality == crate::Quality::Draft; + let mut fp = FinishParams::new(FinishParamsInput { + settings: s, + frame, + info, + image_size: (w, h), + px_per_long: p.px_per_long, + air_pre: p.air, + space, + draft, + }); fp.proof = proof.map(|pr| pr.params(space)); let trc = fp.out_trc; let samples = match depth { diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs index 4eca5bea90..c81653eab7 100644 --- a/crates/pipeline/src/lib.rs +++ b/crates/pipeline/src/lib.rs @@ -616,13 +616,13 @@ fn render_impl(src: Src<'_>, info: &SourceInfo, s: &DevelopSettings, req: &Rende c.put(CacheEntry { src: a.clone(), geo, sampled, lin: Some((lin_key, lin)), planes }); } if req.depth != OutputDepth::U8 { - let deep = finish::finish_deep(&prep, s, frame, info, req.space, req.depth, req.proof); + let deep = finish::finish_deep(&prep, s, frame, info, req); let image = deep.to_rgba8(); let histogram = Histogram::of_srgb8(&image); lap("finish (deep)", &mut t); return Rendered { image, histogram, deep: Some(deep) }; } - let image = finish::finish(&prep, s, frame, info, req.space, req.display.as_ref(), req.proof); + let image = finish::finish(&prep, s, frame, info, req); lap("finish", &mut t); let cut = |i: &Rgba8| match plan.keep { Some(k) => i.crop(k.x, k.y, k.w, k.h), diff --git a/crates/pipeline/src/tests_crystal.rs b/crates/pipeline/src/tests_crystal.rs index bd0ddbf7e8..13c7433c69 100644 --- a/crates/pipeline/src/tests_crystal.rs +++ b/crates/pipeline/src/tests_crystal.rs @@ -46,7 +46,7 @@ fn half_width(v: &[f32], n: usize) -> f64 { } fn tile_of(size: f64, roughness: f64) -> Arc { - tile(CrystalLook::new(size, roughness), 7).expect("a tile") + tile(CrystalLook::new(size, roughness), 7, true).expect("a tile") } #[test] @@ -146,13 +146,42 @@ fn hostile_settings_render_finite_or_no_grain() { #[test] fn seed_picks_the_pattern() { let look = CrystalLook::new(25.0, 50.0); - let (a, b, c) = (tile(look, 1), tile(look, 1), tile(look, 2)); + let (a, b, c) = (tile(look, 1, true), tile(look, 1, true), tile(look, 2, true)); let (Some(a), Some(b), Some(c)) = (a, b, c) else { panic!("tiles") }; let (pa, pb, pc) = (patch(&a, REF_LONG, 64, 0), patch(&b, REF_LONG, 64, 0), patch(&c, REF_LONG, 64, 0)); assert_eq!(pa, pb); assert_ne!(pa, pc); } +/// A draft (a Size or Roughness drag) doesn't wait for a new tile: the last tile of the seed stands +/// in while the new one is drawn in the background, and then the drag gets it. A render that +/// waits always gets the exact tile, as does a draft for a seed with no tile yet. +#[test] +fn a_drag_takes_the_last_tile_while_the_next_is_drawn() { + // seeds of their own: other tests share the cache (which they may also evict from) + let (seed, fresh) = (0x0d4a_0001, 0x0d4a_0002); + let (a, b) = (CrystalLook::new(30.0, 50.0), CrystalLook::new(31.0, 50.0)); + let exact = |look: CrystalLook, seed: u32| patch(&CrystalTile::new(look, seed).expect("tile"), REF_LONG, 32, 0); + let first = tile(a, seed, true).expect("tile"); + assert_eq!(first.look, a); + let stand_in = tile(b, seed, false).expect("tile"); + assert_eq!(stand_in.look, a, "the draft waited for its tile"); + // the drag's next renders get the new tile once it is drawn + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + let drawn = loop { + let t = tile(b, seed, false).expect("tile"); + if t.look == b { + break t; + } + assert!(std::time::Instant::now() < deadline, "the background tile never arrived"); + std::thread::sleep(std::time::Duration::from_millis(5)); + }; + assert_eq!(patch(&drawn, REF_LONG, 32, 0), exact(b, seed)); + assert_eq!(patch(&tile(b, seed, true).expect("tile"), REF_LONG, 32, 0), exact(b, seed)); + // nothing drawn for this seed: nothing to stand in, the draft draws it + assert_eq!(patch(&tile(a, fresh, false).expect("tile"), REF_LONG, 32, 0), exact(a, fresh)); +} + /// Grain width (autocorrelation half-width at mid grey, 6000 px) at Lightroom Classic's /// measured settings (open PR #1060's table); Size 0 is as fine as uncorrelated pixels get (0.5). #[test] diff --git a/crates/pipeline/src/tests_grain.rs b/crates/pipeline/src/tests_grain.rs index 4c8dd554bd..7ec8aadbbd 100644 --- a/crates/pipeline/src/tests_grain.rs +++ b/crates/pipeline/src/tests_grain.rs @@ -30,12 +30,12 @@ fn std(v: &[f64]) -> f64 { #[test] fn processes_before_v3_keep_the_value_noise() { for p in Process::ALL { - let model = GrainModel::new(&on(p, 40.0), 2000.0); + let model = GrainModel::new(&on(p, 40.0), 2000.0, false); match p { Process::V1 | Process::V2 => assert!(matches!(model, Some(GrainModel::Value(_))), "{p:?}"), Process::V3 => assert!(matches!(model, Some(GrainModel::Crystal(_))), "{p:?}"), } - assert!(GrainModel::new(&on(p, 0.0), 2000.0).is_none(), "{p:?}: no grain at Amount 0"); + assert!(GrainModel::new(&on(p, 0.0), 2000.0, false).is_none(), "{p:?}: no grain at Amount 0"); } let src = Rgb32f::filled(160, 120, [0.18; 3]); let (v2, v3) = (luma(&src, &on(Process::V2, 50.0), 160, 120), luma(&src, &on(Process::V3, 50.0), 160, 120)); diff --git a/docs/grain.md b/docs/grain.md index e1e9a351f8..9fe62c62ee 100644 --- a/docs/grain.md +++ b/docs/grain.md @@ -97,10 +97,23 @@ curtain; #1060: −9.3). Fine detail under the grain is kept (detail gain ## Performance - **Drawing the emulsion** (per Size, Roughness and seed; cached, so Amount drags and re-renders - draw nothing): every crystal is stamped as bit spans from a per-layer table of its rasterisation at - 16 × 16 sub-pixel phases, layers are counted in bit-sliced counters, and the tiles are drawn in - parallel bands. 5–17 ms on an M2 Max (12 threads) at any setting (`tile_timing_report`). -- **Per pixel:** two box sums, on the CPU and on the GPU; the tables (12 MB) follow the finish - kernel's other tables in its `aux` buffer. + draw nothing): every crystal is stamped from a per-layer table of its rasterisation at 16 × 16 + sub-pixel phases, as one 64-bit mask per row (a fixed number of rows per layer, those outside a + band landing in scratch rows around it, so a crystal costs no branch per row), layers are counted + in bit-sliced counters, and the tiles are drawn in parallel bands. 5–17 ms on an M2 Max (12 + threads; measured before the row masks), 15–33 ms on a Ryzen 5 7545U (6 cores, 12 threads; 10–20 % + less than before them) at any setting (`tile_timing_report`). +- **Drags.** A draft render (a slider drag) doesn't wait for a tile it hasn't got: the last tile + drawn for the photo's seed stands in while the new one is drawn in the background, on a pool of + half the cores so the drag's renders don't queue behind it, and the next render takes it. The + full-quality render when the drag ends waits for the exact tile. A Size drag on the Ryzen with its + Radeon 740M (GPU, 2.5 MP preview): 13–14 ms a frame instead of 62–66 ms. (On wasm, without + threads, drafts wait.) +- **Per pixel:** two box sums, on the CPU and on the GPU. The tables (12 MB) stay on the GPU + between renders, for the last tile used (`Gpu::grain_tables`), and are copied after the finish + kernel's other tables in its `aux` buffer on the GPU: an Amount drag uploads nothing. On the + Radeon 740M an Amount drag frame (2.5 MP) went from 16.9 to 11–15 ms (no grain: 8 ms). - **24 MP NEF → PNG** (`lightcraft-cli render`, M2 Max, median of three): no grain 1.09 s, grain 50 / 25 / 50 1.09 s on the GPU; 1.33 s and 1.49 s CPU-only (the finish stage 0.26 → 0.42 s). +- **24 MP NEF → PNG on the Ryzen 5 7545U / Radeon 740M** (median of three): no grain 2.07 s, grain + 50 / 25 / 50 2.09 s on the GPU; 2.69 s and 2.87 s CPU-only. From 4ea6a811b4ec45f3538963e0c4c6c0ed3a47cc3d Mon Sep 17 00:00:00 2001 From: Jeremy Hooke Date: Tue, 3 Nov 2026 09:27:38 +1100 Subject: [PATCH 04/14] LR-EDIT-EFFECTS-GRAIN: grain pattern and export timings re-measured on the M2 Max Co-Authored-By: Claude Opus 5.5 --- docs/grain.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/grain.md b/docs/grain.md index 9fe62c62ee..e400953934 100644 --- a/docs/grain.md +++ b/docs/grain.md @@ -100,9 +100,9 @@ curtain; #1060: −9.3). Fine detail under the grain is kept (detail gain draw nothing): every crystal is stamped from a per-layer table of its rasterisation at 16 × 16 sub-pixel phases, as one 64-bit mask per row (a fixed number of rows per layer, those outside a band landing in scratch rows around it, so a crystal costs no branch per row), layers are counted - in bit-sliced counters, and the tiles are drawn in parallel bands. 5–17 ms on an M2 Max (12 - threads; measured before the row masks), 15–33 ms on a Ryzen 5 7545U (6 cores, 12 threads; 10–20 % - less than before them) at any setting (`tile_timing_report`). + in bit-sliced counters, and the tiles are drawn in parallel bands. 7–15 ms on an M2 Max (12 + threads), 15–33 ms on a Ryzen 5 7545U (6 cores, 12 threads; 10–20 % less than before the row + masks) at any setting (`tile_timing_report`). - **Drags.** A draft render (a slider drag) doesn't wait for a tile it hasn't got: the last tile drawn for the photo's seed stands in while the new one is drawn in the background, on a pool of half the cores so the drag's renders don't queue behind it, and the next render takes it. The @@ -113,7 +113,7 @@ curtain; #1060: −9.3). Fine detail under the grain is kept (detail gain between renders, for the last tile used (`Gpu::grain_tables`), and are copied after the finish kernel's other tables in its `aux` buffer on the GPU: an Amount drag uploads nothing. On the Radeon 740M an Amount drag frame (2.5 MP) went from 16.9 to 11–15 ms (no grain: 8 ms). -- **24 MP NEF → PNG** (`lightcraft-cli render`, M2 Max, median of three): no grain 1.09 s, grain - 50 / 25 / 50 1.09 s on the GPU; 1.33 s and 1.49 s CPU-only (the finish stage 0.26 → 0.42 s). +- **24 MP NEF → PNG** (`lightcraft-cli render`, M2 Max, median of three): no grain 1.10 s, grain + 50 / 25 / 50 1.10 s on the GPU; 1.33 s and 1.47 s CPU-only (the finish stage 0.26 → 0.42 s). - **24 MP NEF → PNG on the Ryzen 5 7545U / Radeon 740M** (median of three): no grain 2.07 s, grain 50 / 25 / 50 2.09 s on the GPU; 2.69 s and 2.87 s CPU-only. From 50e6422a7266eee795eb0012459722f61b8b5845 Mon Sep 17 00:00:00 2001 From: Jeremy Hooke Date: Tue, 3 Nov 2026 11:11:43 +1100 Subject: [PATCH 05/14] LR-EDIT-EFFECTS-GRAIN: grain drag benchmark; Ryzen numbers for main and #1060 `grain_drag_bench` (lightcraft-gpu example): GPU draft renders of a 2.5 MP preview while Amount or Size is dragged, ms per frame. It doesn't depend on the grain model, so it runs unchanged on other branches. docs/grain.md gets its results on the Ryzen 5 7545U / Radeon 740M for main, #1060 and this model, and the whole-render grain cost of main and #1060 there. Co-Authored-By: Claude Opus 5.5 --- crates/gpu/examples/grain_drag_bench.rs | 56 +++++++++++++++++++++++++ docs/grain.md | 13 +++++- 2 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 crates/gpu/examples/grain_drag_bench.rs diff --git a/crates/gpu/examples/grain_drag_bench.rs b/crates/gpu/examples/grain_drag_bench.rs new file mode 100644 index 0000000000..5a47cb6740 --- /dev/null +++ b/crates/gpu/examples/grain_drag_bench.rs @@ -0,0 +1,56 @@ +//! Grain slider drags on the GPU: the time per frame of the draft renders the loupe makes while +//! Amount or Size is dragged, on a ~2.5 MP preview (1936 × 1290, the procedural demo photo). +//! `cargo run --release -p lightcraft-gpu --example grain_drag_bench` (`FRAMES=n`, default 40). +//! +//! The same source, settings and request on every build, so it can be copied unchanged into +//! another branch to compare grain models (see `docs/grain.md` → Performance). Each drag first +//! renders four frames that aren't counted (stage cache, GPU pipelines), then moves the slider one +//! step a frame; prints the median, fastest and slowest frame. +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use std::sync::Arc; +use std::time::Instant; + +use lightcraft_develop::DevelopSettings; +use lightcraft_pipeline::{Quality, RenderRequest, SourceInfo, StageCache}; + +fn main() { + let frames: usize = std::env::var("FRAMES").ok().and_then(|v| v.parse().ok()).unwrap_or(40).max(1); + let (w, h) = (1936, 1290); + let src = Arc::new(lightcraft_scenes::demo_library()[3].render(w, h)); + let info = SourceInfo { raw: true, ..Default::default() }; + let draft = RenderRequest { quality: Quality::Draft, ..RenderRequest::fit(w, h) }; + let Some(adapter) = lightcraft_gpu::adapter_name() else { + eprintln!("no GPU adapter: nothing to measure"); + return; + }; + println!("gpu: {adapter}; {w}×{h} draft renders, {frames} frames per drag"); + let mut s = DevelopSettings::default(); + s.light.exposure = 0.3; + let mut drag = |label: &str, step: &dyn Fn(&mut DevelopSettings, usize)| { + let cache = StageCache::default(); + let mut ms = Vec::with_capacity(frames); + for i in 0..frames + 4 { + step(&mut s, i); + let t = Instant::now(); + assert!(lightcraft_gpu::render(&src, &info, &s, &draft, Some(&cache)).is_some(), "GPU render failed"); + if i >= 4 { + ms.push(t.elapsed().as_secs_f64() * 1e3); + } + } + ms.sort_by(f64::total_cmp); + println!("{label:<30} median {:5.1} ms min {:5.1} max {:5.1}", ms[ms.len() / 2], ms[0], ms[ms.len() - 1]); + }; + drag("exposure drag, no grain", &|s, i| { + s.grain.amount = 0.0; + s.light.exposure = 0.3 + i as f64 * 0.01; + }); + drag("Amount drag (20 → 100)", &|s, i| { + s.grain.size = 25.0; + s.grain.amount = 20.0 + (i * 2 % 80) as f64; + }); + drag("Size drag (amount 50, 0 → 100)", &|s, i| { + s.grain.amount = 50.0; + s.grain.size = (i * 2 % 100) as f64; + }); +} diff --git a/docs/grain.md b/docs/grain.md index e400953934..e6e844cbf9 100644 --- a/docs/grain.md +++ b/docs/grain.md @@ -109,6 +109,16 @@ curtain; #1060: −9.3). Fine detail under the grain is kept (detail gain full-quality render when the drag ends waits for the exact tile. A Size drag on the Ryzen with its Radeon 740M (GPU, 2.5 MP preview): 13–14 ms a frame instead of 62–66 ms. (On wasm, without threads, drafts wait.) +- **Drag benchmark** (`cargo run --release -p lightcraft-gpu --example grain_drag_bench`: GPU + draft renders of the 1936 × 1290 demo photo, median ms per frame of 100; the example has no + dependency on this model, so it can be copied unchanged into another branch). Ryzen 5 7545U / + Radeon 740M: + + | Build | No grain (Exposure drag) | Amount drag | Size drag | + |---|---|---|---| + | main (value noise) | 8–12 | 10–13 | 10–13 | + | #1060 (particles) | 8 | 11–14 | 151–179 (17–312) | + | this model | 8–11 | 14–15 | 13 | - **Per pixel:** two box sums, on the CPU and on the GPU. The tables (12 MB) stay on the GPU between renders, for the last tile used (`Gpu::grain_tables`), and are copied after the finish kernel's other tables in its `aux` buffer on the GPU: an Amount drag uploads nothing. On the @@ -116,4 +126,5 @@ curtain; #1060: −9.3). Fine detail under the grain is kept (detail gain - **24 MP NEF → PNG** (`lightcraft-cli render`, M2 Max, median of three): no grain 1.10 s, grain 50 / 25 / 50 1.10 s on the GPU; 1.33 s and 1.47 s CPU-only (the finish stage 0.26 → 0.42 s). - **24 MP NEF → PNG on the Ryzen 5 7545U / Radeon 740M** (median of three): no grain 2.07 s, grain - 50 / 25 / 50 2.09 s on the GPU; 2.69 s and 2.87 s CPU-only. + 50 / 25 / 50 2.10 s on the GPU; 2.72 s and 2.88 s CPU-only. Grain costs main +0.03 s on the GPU + and +0.10 s CPU-only, #1060 +1.81 s and +3.54 s. From e909f7f78ef166d7dcad622b1eeb32de65043e93 Mon Sep 17 00:00:00 2001 From: Jeremy Hooke Date: Tue, 3 Nov 2026 11:19:34 +1100 Subject: [PATCH 06/14] LR-EDIT-EFFECTS-GRAIN: grain drag benchmark on the M2 Max for main, #1060 and this model Co-Authored-By: Claude Opus 5.5 --- docs/grain.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs/grain.md b/docs/grain.md index e6e844cbf9..22b249e649 100644 --- a/docs/grain.md +++ b/docs/grain.md @@ -119,6 +119,14 @@ curtain; #1060: −9.3). Fine detail under the grain is kept (detail gain | main (value noise) | 8–12 | 10–13 | 10–13 | | #1060 (particles) | 8 | 11–14 | 151–179 (17–312) | | this model | 8–11 | 14–15 | 13 | + + M2 Max (Metal), same benchmark, the medians of three runs: + + | Build | No grain (Exposure drag) | Amount drag | Size drag | + |---|---|---|---| + | main (value noise) | 3.2–3.4 | 2.9–3.0 | 2.9 | + | #1060 (particles) | 3.3 | 3.0–3.1 | 35.6–36.0 | + | this model | 3.2–3.3 | 3.4–3.5 | 5.9–6.0 | - **Per pixel:** two box sums, on the CPU and on the GPU. The tables (12 MB) stay on the GPU between renders, for the last tile used (`Gpu::grain_tables`), and are copied after the finish kernel's other tables in its `aux` buffer on the GPU: an Amount drag uploads nothing. On the From 1acedc81ee13950d286c7c8cd6c9dd680d5a0a21 Mon Sep 17 00:00:00 2001 From: Jeremy Hooke Date: Tue, 3 Nov 2026 11:31:19 +1100 Subject: [PATCH 07/14] LR-EDIT-EFFECTS-GRAIN: M2 Max export timings for main, #1060 and this model from clean builds Co-Authored-By: Claude Opus 5.5 --- docs/grain.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/grain.md b/docs/grain.md index 22b249e649..85efca8e00 100644 --- a/docs/grain.md +++ b/docs/grain.md @@ -131,8 +131,9 @@ curtain; #1060: −9.3). Fine detail under the grain is kept (detail gain between renders, for the last tile used (`Gpu::grain_tables`), and are copied after the finish kernel's other tables in its `aux` buffer on the GPU: an Amount drag uploads nothing. On the Radeon 740M an Amount drag frame (2.5 MP) went from 16.9 to 11–15 ms (no grain: 8 ms). -- **24 MP NEF → PNG** (`lightcraft-cli render`, M2 Max, median of three): no grain 1.10 s, grain - 50 / 25 / 50 1.10 s on the GPU; 1.33 s and 1.47 s CPU-only (the finish stage 0.26 → 0.42 s). +- **24 MP NEF → PNG** (`lightcraft-cli render`, M2 Max, median of three): no grain 1.06 s, grain + 50 / 25 / 50 1.05 s on the GPU; 1.28 s and 1.43 s CPU-only (the finish stage 0.26 → 0.42 s). + Grain costs main ≈ 0 on the GPU and +0.08 s CPU-only, #1060 +0.29 s and +1.71 s. - **24 MP NEF → PNG on the Ryzen 5 7545U / Radeon 740M** (median of three): no grain 2.07 s, grain 50 / 25 / 50 2.10 s on the GPU; 2.72 s and 2.88 s CPU-only. Grain costs main +0.03 s on the GPU and +0.10 s CPU-only, #1060 +1.81 s and +3.54 s. From b908538a16637e851de0abc85e431058bd2c6714 Mon Sep 17 00:00:00 2001 From: Jeremy Hooke Date: Tue, 3 Nov 2026 12:08:45 +1100 Subject: [PATCH 08/14] LR-EDIT-EFFECTS-GRAIN: review fixes (shared grain tables, own test cache, per-pixel preview check) - Gpu::grain_tables returns the resident buffer it copied from as an Arc that the render keeps until it submits: replacing the tables on another thread no longer hands the buffer back to the pool while a recorded copy from it is unsubmitted (regression test). - The drag test uses a tile cache of its own, so other V3 tests can't evict its stand-in. - small_render_matches_the_downscaled_large_render compares the grain pixel by pixel (measured 0.003 of 255 levels apart), not only its strength. - GPU equivalence covers V1 and V2 grain again. - docs/grain.md: the drag benchmark command sets FRAMES=100; the rotated-frame footprint is an axis-aligned square (documented, also in crystal.rs). Co-Authored-By: Claude Opus 5.5 --- crates/gpu/src/ctx.rs | 50 ++++++++++++++++++++++------ crates/gpu/src/render.rs | 14 ++++++-- crates/gpu/tests/it/equivalence.rs | 13 ++++++++ crates/pipeline/src/crystal.rs | 45 +++++++++++++++---------- crates/pipeline/src/tests_crystal.rs | 4 ++- crates/pipeline/src/tests_grain.rs | 8 +++++ docs/grain.md | 7 +++- 7 files changed, 108 insertions(+), 33 deletions(-) diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index 068d866f33..563a450c58 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -339,7 +339,9 @@ pub struct Gpu { pub max_buffer: u64, /// The crystal grain tables of the last grain pattern, resident: a render (each Amount step /// of a drag) copies them on the GPU instead of uploading their 12 MB again ([`Gpu::grain_tables`]). - grain: std::sync::Mutex, Buf)>>, + /// Shared with each render that recorded a copy from them until it submits: replacing them + /// while another thread's copy is unsubmitted must not hand the buffer back to the pool. + grain: std::sync::Mutex, std::sync::Arc)>>, } /// WGSL constants shared by every module (generated from the CPU pipeline's values). @@ -645,38 +647,41 @@ impl Gpu { } /// Record into `enc` a copy of `tile`'s summed-area tables (both tori, back to back) into - /// `dst` at value offset `at`, uploading them first unless they are the resident ones. False - /// when `dst` can't hold them (an over-limit placeholder: the render has failed already). + /// `dst` at value offset `at`, uploading them first unless they are the resident ones. + /// Returns the buffer copied from, which the caller keeps until it has submitted `enc` (another + /// render may replace the resident tables meanwhile). None when `dst` can't hold them (an + /// over-limit placeholder: the render has failed already). pub fn grain_tables( &self, enc: &mut wgpu::CommandEncoder, tile: &std::sync::Arc, dst: &Buf, at: usize, - ) -> bool { + ) -> Option> { let len: usize = tile.sats.iter().map(Vec::len).sum(); let (start, bytes) = ((at as u64) * 4, (len as u64) * 4); if len == 0 || dst.raw().size() < start.saturating_add(bytes) { - return false; + return None; } let mut resident = self.grain.lock().unwrap_or_else(|e| e.into_inner()); if !resident.as_ref().is_some_and(|(t, b)| std::sync::Arc::ptr_eq(t, tile) && b.raw().size() >= bytes) { - // the old tables go back to the pool first: one pattern's tables are resident at a time + // the old tables go back to the pool first (once no unsubmitted copy holds them): one + // pattern's tables are resident at a time *resident = None; let buf = self.buffer(len); if buf.raw().size() < bytes { - return false; + return None; } let mut off = 0u64; for sat in &tile.sats { self.queue.write_buffer(buf.raw(), off, bytemuck::cast_slice(sat)); off += (sat.len() as u64) * 4; } - *resident = Some((tile.clone(), buf)); + *resident = Some((tile.clone(), std::sync::Arc::new(buf))); } - let Some((_, src)) = resident.as_ref() else { return false }; + let (_, src) = resident.as_ref()?; enc.copy_buffer_to_buffer(src.raw(), 0, dst.raw(), start, bytes); - true + Some(src.clone()) } /// Stands in for a buffer that could not be created (the render has failed already). @@ -1060,6 +1065,31 @@ mod tests { } } + /// Resident grain tables replaced by another pattern stay out of the pool while a render + /// that recorded a copy from them hasn't submitted it: reusing them then would hand that + /// render another tile's tables. + #[test] + fn replaced_grain_tables_stay_alive_until_their_copy_is_submitted() { + use lightcraft_pipeline::crystal::{CrystalLook, CrystalTile}; + let Some(g) = crate::device() else { + lightcraft_testkit::skip!(Gpu, "no GPU device"); + return; + }; + let look = CrystalLook::new(25.0, 50.0); + let (Some(a), Some(b)) = (CrystalTile::new(look, 0x7ab1_0001), CrystalTile::new(look, 0x7ab1_0002)) else { panic!("tiles") }; + let (a, b) = (std::sync::Arc::new(a), std::sync::Arc::new(b)); + let len: usize = a.sats.iter().map(Vec::len).sum(); + let dst = g.buffer(len); + let mut first = g.encoder(); + let held = g.grain_tables(&mut first, &a, &dst, 0).expect("tables copied"); + // another render replaces the resident tables before `first` is submitted + let mut second = g.encoder(); + assert!(g.grain_tables(&mut second, &b, &dst, 0).is_some()); + let next = g.buffer(len); + assert!(next.raw() != held.raw(), "the replaced tables went back to the pool before their copy was submitted"); + g.submit([first.finish(), second.finish()]); + } + /// A GPU retired by another failure (a validation error) keeps a live device: its buffers are /// still released, which takes a poll. #[test] diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index 9b5f235a05..8db731bc48 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -131,6 +131,10 @@ pub(crate) struct Cx<'a> { enc: Option, /// Kernel invocations recorded since the last submit. pending: u64, + /// Buffers shared with other renders that recorded commands read from (the resident grain + /// tables): kept until those commands are submitted. Declared after `enc`, so an unsubmitted + /// encoder is dropped before them. + held: Vec>, } /// Kernel invocations recorded before a render submits them (under one full-size pass over a @@ -142,7 +146,7 @@ const BAND_PIXELS: usize = 4 << 20; impl<'a> Cx<'a> { pub fn new(gpu: &'a Gpu) -> Cx<'a> { - Cx { gpu, enc: Some(gpu.encoder()), pending: 0 } + Cx { gpu, enc: Some(gpu.encoder()), pending: 0, held: Vec::new() } } /// Record kernel `name` (see [`Gpu::run`]). @@ -166,7 +170,7 @@ impl<'a> Cx<'a> { self.gpu.queue.write_buffer(out.raw(), 0, bytemuck::cast_slice(aux)); } let enc = self.enc.get_or_insert_with(|| self.gpu.encoder()); - self.gpu.grain_tables(enc, &g.tile, &out, aux.len()); + self.held.extend(self.gpu.grain_tables(enc, &g.tile, &out, aux.len())); out } @@ -174,7 +178,9 @@ impl<'a> Cx<'a> { pub fn read(&mut self, b: &Buf, len: usize) -> Vec { self.pending = 0; let enc = self.enc.take().unwrap_or_else(|| self.gpu.encoder()); - self.gpu.finish_and_read(enc, b, len) + let out = self.gpu.finish_and_read(enc, b, len); + self.held.clear(); + out } /// Submit what is recorded so far without waiting. Renders submit stage by stage and every @@ -186,6 +192,7 @@ impl<'a> Cx<'a> { if let Some(enc) = self.enc.take() { self.gpu.submit([enc.finish()]); } + self.held.clear(); } /// Submit what is recorded and wait for it (profiling only: stage timings). @@ -194,6 +201,7 @@ impl<'a> Cx<'a> { if let Some(enc) = self.enc.take() { self.gpu.submit([enc.finish()]); } + self.held.clear(); let _ = self.gpu.poll(wgpu::PollType::wait_indefinitely()); } diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index 1f0cf89a45..c30e75fef4 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -257,6 +257,19 @@ fn cases() -> Vec<(&'static str, Edit)> { s.grain.size = 40.0; s.grain.roughness = 60.0; }), + // the frozen value-noise grain of the earlier processes (the default is V3's crystals) + ("grain, process V1", |s| { + s.process = Process::V1.version(); + s.grain.amount = 50.0; + s.grain.size = 40.0; + s.grain.roughness = 60.0; + }), + ("grain, process V2", |s| { + s.process = Process::V2.version(); + s.grain.amount = 50.0; + s.grain.size = 40.0; + s.grain.roughness = 60.0; + }), ("dehaze -", |s| s.effects.dehaze = -50.0), ("dehaze +", |s| s.effects.dehaze = 60.0), ("clarity/texture -", |s| { diff --git a/crates/pipeline/src/crystal.rs b/crates/pipeline/src/crystal.rs index 6098e7e570..fbac487aef 100644 --- a/crates/pipeline/src/crystal.rs +++ b/crates/pipeline/src/crystal.rs @@ -18,7 +18,8 @@ //! **Resolution independence.** The emulsion is drawn once per setting on two periodic tiles //! (tori) in frame coordinates, at twice the resolution of a 6000 px export ([`PITCH`]). Each //! output pixel takes the exact mean of the emulsion under its footprint from the tiles' summed -//! area tables, so a preview shows exactly the export's grain box-downscaled to its size, and an +//! area tables (a rotated frame's pixel: of an axis-aligned square of its size), so a preview +//! shows exactly the export's grain box-downscaled to its size, and an //! export larger than 6000 px still has crystals rather than enlarged pixels. The layers are //! split between two tori of different sizes ([`TORI`]); their pattern only repeats as a whole //! after tens of thousands of pixels. @@ -809,7 +810,9 @@ pub struct CrystalGrain { } type Key = (u64, u64, u32); -static TILES: Mutex)>> = Mutex::new(Vec::new()); +/// Recently drawn tiles (the most recent last). +type Cache = Mutex)>>; +static TILES: Cache = Mutex::new(Vec::new()); /// The tile being drawn in the background for a drag ([`tile`]): one at a time. static DRAWING: Mutex> = Mutex::new(None); @@ -819,41 +822,46 @@ static DRAWING: Mutex> = Mutex::new(None); /// Size or Roughness drag doesn't wait for every step's tile (tens of milliseconds on a slow /// CPU), and the full-quality render when it ends waits for the exact one. fn tile(look: CrystalLook, seed: u32, wait: bool) -> Option> { + tile_in(&TILES, look, seed, wait) +} + +/// [`tile`] with the tiles cached in `cache` (a test's own, which other tests can't evict from). +fn tile_in(cache: &'static Cache, look: CrystalLook, seed: u32, wait: bool) -> Option> { let key = (look.width.to_bits(), look.spread.to_bits() ^ (look.layers as u64).rotate_left(40), seed); { - let cache = TILES.lock().unwrap_or_else(PoisonError::into_inner); - if let Some((_, t)) = cache.iter().find(|(k, _)| *k == key) { + let tiles = cache.lock().unwrap_or_else(PoisonError::into_inner); + if let Some((_, t)) = tiles.iter().find(|(k, _)| *k == key) { return Some(t.clone()); } // (wasm has no threads to draw on) if !wait && !cfg!(target_arch = "wasm32") - && let Some((_, stand_in)) = cache.iter().rev().find(|(k, _)| k.2 == seed) + && let Some((_, stand_in)) = tiles.iter().rev().find(|(k, _)| k.2 == seed) { let stand_in = stand_in.clone(); - drop(cache); - draw_in_background(key, look, seed); + drop(tiles); + draw_in_background(cache, key, look, seed); return Some(stand_in); } } let t = Arc::new(CrystalTile::new(look, seed)?); - keep(key, t.clone()); + keep(cache, key, t.clone()); Some(t) } -/// Adds `t` to the cache (the most recent last). -fn keep(key: Key, t: Arc) { - let mut cache = TILES.lock().unwrap_or_else(PoisonError::into_inner); - cache.retain(|(k, _)| *k != key); - if cache.len() >= CACHE { - cache.remove(0); +/// Adds `t` to `cache` (the most recent last). +fn keep(cache: &Cache, key: Key, t: Arc) { + let mut tiles = cache.lock().unwrap_or_else(PoisonError::into_inner); + tiles.retain(|(k, _)| *k != key); + if tiles.len() >= CACHE { + tiles.remove(0); } - cache.push((key, t)); + tiles.push((key, t)); } /// Draws the tile of `key` on the thread pool unless another is being drawn (the next render /// asks again for what it needs then). -fn draw_in_background(key: Key, look: CrystalLook, seed: u32) { +fn draw_in_background(cache: &'static Cache, key: Key, look: CrystalLook, seed: u32) { { let mut drawing = DRAWING.lock().unwrap_or_else(PoisonError::into_inner); if drawing.is_some() { @@ -863,7 +871,7 @@ fn draw_in_background(key: Key, look: CrystalLook, seed: u32) { } let draw = move || { if let Some(t) = CrystalTile::new(look, seed) { - keep(key, Arc::new(t)); + keep(cache, key, Arc::new(t)); } *DRAWING.lock().unwrap_or_else(PoisonError::into_inner) = None; }; @@ -923,7 +931,8 @@ impl CrystalGrain { } /// Display-encoded colour `e` with grain, at frame position (`gx`, `gy`) (fractions of the - /// frame's long edge). + /// frame's long edge): the mean over an axis-aligned square footprint centred there, which + /// for a rotated frame's pixel stands in for its rotated footprint (`docs/grain.md`). #[inline] pub fn apply(&self, e: [f32; 3], gx: f32, gy: f32) -> [f32; 3] { if !(gx.is_finite() && gy.is_finite()) { diff --git a/crates/pipeline/src/tests_crystal.rs b/crates/pipeline/src/tests_crystal.rs index 13c7433c69..9f57a8c35f 100644 --- a/crates/pipeline/src/tests_crystal.rs +++ b/crates/pipeline/src/tests_crystal.rs @@ -158,7 +158,9 @@ fn seed_picks_the_pattern() { /// waits always gets the exact tile, as does a draft for a seed with no tile yet. #[test] fn a_drag_takes_the_last_tile_while_the_next_is_drawn() { - // seeds of their own: other tests share the cache (which they may also evict from) + // a cache of its own: other tests' tiles (through any V3 render) would evict from the shared one + static OWN: Cache = Mutex::new(Vec::new()); + let tile = |look, seed, wait| tile_in(&OWN, look, seed, wait); let (seed, fresh) = (0x0d4a_0001, 0x0d4a_0002); let (a, b) = (CrystalLook::new(30.0, 50.0), CrystalLook::new(31.0, 50.0)); let exact = |look: CrystalLook, seed: u32| patch(&CrystalTile::new(look, seed).expect("tile"), REF_LONG, 32, 0); diff --git a/crates/pipeline/src/tests_grain.rs b/crates/pipeline/src/tests_grain.rs index 7ec8aadbbd..6cc3ab73bf 100644 --- a/crates/pipeline/src/tests_grain.rs +++ b/crates/pipeline/src/tests_grain.rs @@ -61,6 +61,14 @@ fn small_render_matches_the_downscaled_large_render() { let small = luma(&src, &s, w / k, h / k); let ratio = std(&small) / std(&down); assert!((0.95..1.05).contains(&ratio), "size {size}: preview / export grain {ratio:.3}"); + // and the same grain pixel by pixel, not just as strong: the preview's grain (less its + // no-grain render) against the downscaled export's + let small_base = luma(&src, &on(Process::V3, 0.0), w / k, h / k); + let delta: Vec = small.iter().zip(&small_base).map(|(a, b)| a - b).collect(); + // (measured: at most 0.003 of 255 levels apart, the 16-bit output's rounding; the grain's + // standard deviation is 1.4–2.9 levels, so a shifted or reseeded pattern is far outside) + let worst = delta.iter().zip(&down).map(|(a, b)| (a - b).abs()).fold(0.0, f64::max); + assert!(worst < 0.01, "size {size}: preview grain {worst:.4} levels from the downscaled export's"); } } diff --git a/docs/grain.md b/docs/grain.md index 85efca8e00..e27e53866c 100644 --- a/docs/grain.md +++ b/docs/grain.md @@ -44,6 +44,11 @@ the export's grain box-downscaled to its size, and an export larger than 6000 px still shows crystals rather than enlarged pixels. The tori share no small factor: the two patterns only line up again after 362,880 reference pixels, so the grain has no visible period. +In a rotated frame (a straightened or rotated crop) the footprint is approximated: each pixel takes +the mean over an axis-aligned square of its size centred on it, not over the rotated pixel (summed +area tables only give axis-aligned boxes). The grain strength is the same; the exact match with a +box-downscaled export holds for unrotated frames in any orientation. + Measured on the comparison renders (four photos, six regions each, 1500 px preview against the 6000 px export box-downscaled to 1500 px): preview / export grain strength **1.00–1.04** at the default, finest and coarsest settings. `crystal::tests::small_render_is_the_downscaled_reference` @@ -109,7 +114,7 @@ curtain; #1060: −9.3). Fine detail under the grain is kept (detail gain full-quality render when the drag ends waits for the exact tile. A Size drag on the Ryzen with its Radeon 740M (GPU, 2.5 MP preview): 13–14 ms a frame instead of 62–66 ms. (On wasm, without threads, drafts wait.) -- **Drag benchmark** (`cargo run --release -p lightcraft-gpu --example grain_drag_bench`: GPU +- **Drag benchmark** (`FRAMES=100 cargo run --release -p lightcraft-gpu --example grain_drag_bench`: GPU draft renders of the 1936 × 1290 demo photo, median ms per frame of 100; the example has no dependency on this model, so it can be copied unchanged into another branch). Ryzen 5 7545U / Radeon 740M: From 2038ebc7600857ba14ddbc11cb402f59ee116ede Mon Sep 17 00:00:00 2001 From: Jeremy Hooke Date: Tue, 3 Nov 2026 13:37:43 +1100 Subject: [PATCH 09/14] LR-EDIT-EFFECTS-GRAIN: review fixes (one draw per missed tile, table copies read back) - A render that misses a crystal tile another thread is drawing (another render, or the background draw of a drag) waits for it instead of drawing it again; the marker is cleared and waiters woken on success and failure. Pool workers still draw for themselves: blocked, one could hold up part of the very drawing it waits for. Regression test. - The grain-table replacement test copies into a destination per render and reads both back against their tile's tables. Co-Authored-By: Claude Opus 5.5 --- crates/gpu/src/ctx.rs | 12 +++-- crates/pipeline/src/crystal.rs | 70 +++++++++++++++++++++++++--- crates/pipeline/src/tests_crystal.rs | 17 +++++++ 3 files changed, 89 insertions(+), 10 deletions(-) diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index 563a450c58..6ff058e3e6 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -1079,15 +1079,19 @@ mod tests { let (Some(a), Some(b)) = (CrystalTile::new(look, 0x7ab1_0001), CrystalTile::new(look, 0x7ab1_0002)) else { panic!("tiles") }; let (a, b) = (std::sync::Arc::new(a), std::sync::Arc::new(b)); let len: usize = a.sats.iter().map(Vec::len).sum(); - let dst = g.buffer(len); + let (dst_a, dst_b) = (g.buffer(len), g.buffer(len)); let mut first = g.encoder(); - let held = g.grain_tables(&mut first, &a, &dst, 0).expect("tables copied"); + let held = g.grain_tables(&mut first, &a, &dst_a, 0).expect("tables copied"); // another render replaces the resident tables before `first` is submitted let mut second = g.encoder(); - assert!(g.grain_tables(&mut second, &b, &dst, 0).is_some()); + assert!(g.grain_tables(&mut second, &b, &dst_b, 0).is_some()); let next = g.buffer(len); assert!(next.raw() != held.raw(), "the replaced tables went back to the pool before their copy was submitted"); - g.submit([first.finish(), second.finish()]); + g.submit([first.finish()]); + // each render read its own tile's tables + let tables = |t: &lightcraft_pipeline::crystal::CrystalTile| t.sats.concat(); + assert!(g.finish_and_read::(second, &dst_a, len) == tables(&a), "the first render copied other tables"); + assert!(g.finish_and_read::(g.encoder(), &dst_b, len) == tables(&b), "the second render copied other tables"); } /// A GPU retired by another failure (a validation error) keeps a live device: its buffers are diff --git a/crates/pipeline/src/crystal.rs b/crates/pipeline/src/crystal.rs index fbac487aef..fe33711c3e 100644 --- a/crates/pipeline/src/crystal.rs +++ b/crates/pipeline/src/crystal.rs @@ -29,7 +29,7 @@ //! GPU kernel (`finish.wgsl`, which reads the same tables). use std::f64::consts::TAU; -use std::sync::{Arc, Mutex, PoisonError}; +use std::sync::{Arc, Condvar, Mutex, PoisonError}; use lightcraft_color::transfer::srgb_to_linear; use lightcraft_develop::Grain; @@ -810,6 +810,11 @@ pub struct CrystalGrain { } type Key = (u64, u64, u32); + +/// The cache key of the tile of `look` and `seed`. +fn key_of(look: CrystalLook, seed: u32) -> Key { + (look.width.to_bits(), look.spread.to_bits() ^ (look.layers as u64).rotate_left(40), seed) +} /// Recently drawn tiles (the most recent last). type Cache = Mutex)>>; static TILES: Cache = Mutex::new(Vec::new()); @@ -817,6 +822,37 @@ static TILES: Cache = Mutex::new(Vec::new()); /// The tile being drawn in the background for a drag ([`tile`]): one at a time. static DRAWING: Mutex> = Mutex::new(None); +/// The tiles being drawn, by cache and key, and the condition their drawers signal when done: a +/// render that misses a tile another is drawing waits for it rather than drawing it again. +static IN_FLIGHT: Mutex> = Mutex::new(Vec::new()); +static DRAWN: Condvar = Condvar::new(); + +/// Marks a tile drawn (or failed) when dropped and wakes the renders waiting for it. +struct Drawing((usize, Key)); + +impl Drop for Drawing { + fn drop(&mut self) { + IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner).retain(|d| *d != self.0); + DRAWN.notify_all(); + } +} + +/// Registers the tile of `id` as being drawn, or `None` if another thread is drawing it. +fn start_drawing(id: (usize, Key)) -> Option { + let mut busy = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner); + if busy.contains(&id) { + return None; + } + busy.push(id); + Some(Drawing(id)) +} + +/// The tile of `key` in `cache`. +fn cached(cache: &Cache, key: Key) -> Option> { + let tiles = cache.lock().unwrap_or_else(PoisonError::into_inner); + tiles.iter().find(|(k, _)| *k == key).map(|(_, t)| t.clone()) +} + /// The tile of `look` and `seed`, drawn or from the cache. Unless `wait`, a tile not drawn yet /// is drawn in the background and the last one drawn for `seed` stands in for it meanwhile: a /// Size or Roughness drag doesn't wait for every step's tile (tens of milliseconds on a slow @@ -827,7 +863,7 @@ fn tile(look: CrystalLook, seed: u32, wait: bool) -> Option> { /// [`tile`] with the tiles cached in `cache` (a test's own, which other tests can't evict from). fn tile_in(cache: &'static Cache, look: CrystalLook, seed: u32, wait: bool) -> Option> { - let key = (look.width.to_bits(), look.spread.to_bits() ^ (look.layers as u64).rotate_left(40), seed); + let key = key_of(look, seed); { let tiles = cache.lock().unwrap_or_else(PoisonError::into_inner); if let Some((_, t)) = tiles.iter().find(|(k, _)| *k == key) { @@ -844,6 +880,20 @@ fn tile_in(cache: &'static Cache, look: CrystalLook, seed: u32, wait: bool) -> O return Some(stand_in); } } + let id = (std::ptr::from_ref(cache) as usize, key); + // a pool worker draws the tile itself: blocked, it could hold up the drawing it waits for + // (its stack may carry a part of that drawing's parallel work); wasm has no other threads + if !cfg!(target_arch = "wasm32") && rayon::current_thread_index().is_none() { + let mut busy = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner); + while busy.contains(&id) { + busy = DRAWN.wait(busy).unwrap_or_else(PoisonError::into_inner); + } + drop(busy); + if let Some(t) = cached(cache, key) { + return Some(t); + } + } + let _drawing = start_drawing(id); let t = Arc::new(CrystalTile::new(look, seed)?); keep(cache, key, t.clone()); Some(t) @@ -862,19 +912,27 @@ fn keep(cache: &Cache, key: Key, t: Arc) { /// Draws the tile of `key` on the thread pool unless another is being drawn (the next render /// asks again for what it needs then). fn draw_in_background(cache: &'static Cache, key: Key, look: CrystalLook, seed: u32) { - { + let marker = { let mut drawing = DRAWING.lock().unwrap_or_else(PoisonError::into_inner); if drawing.is_some() { return; } + // (`None`: a render is drawing it already) + let Some(marker) = start_drawing((std::ptr::from_ref(cache) as usize, key)) else { return }; *drawing = Some(key); - } - let draw = move || { + marker + }; + spawn_in_background(move || { if let Some(t) = CrystalTile::new(look, seed) { keep(cache, key, Arc::new(t)); } + drop(marker); *DRAWING.lock().unwrap_or_else(PoisonError::into_inner) = None; - }; + }); +} + +/// Runs `draw` on the background pool. +fn spawn_in_background(draw: impl FnOnce() + Send + 'static) { // on a pool of its own: the renders of the drag don't queue behind its parallel bands match background_pool() { Some(pool) => pool.spawn(draw), diff --git a/crates/pipeline/src/tests_crystal.rs b/crates/pipeline/src/tests_crystal.rs index 9f57a8c35f..1101de4eed 100644 --- a/crates/pipeline/src/tests_crystal.rs +++ b/crates/pipeline/src/tests_crystal.rs @@ -184,6 +184,23 @@ fn a_drag_takes_the_last_tile_while_the_next_is_drawn() { assert_eq!(patch(&tile(a, fresh, false).expect("tile"), REF_LONG, 32, 0), exact(a, fresh)); } +/// A render that misses a tile another thread is drawing waits for that tile rather than drawing +/// it a second time. +#[test] +fn a_render_waits_for_a_tile_being_drawn() { + static OWN: Cache = Mutex::new(Vec::new()); + let (look, seed) = (CrystalLook::new(40.0, 50.0), 0x0d4a_0003); + let key = key_of(look, seed); + let marker = start_drawing((std::ptr::from_ref(&OWN) as usize, key)).expect("not drawn yet"); + let render = std::thread::spawn(move || tile_in(&OWN, look, seed, true)); + std::thread::sleep(std::time::Duration::from_millis(200)); + let drawn = Arc::new(CrystalTile::new(look, seed).expect("tile")); + keep(&OWN, key, drawn.clone()); + drop(marker); + let got = render.join().expect("render thread").expect("tile"); + assert!(Arc::ptr_eq(&got, &drawn), "the render drew the tile again"); +} + /// Grain width (autocorrelation half-width at mid grey, 6000 px) at Lightroom Classic's /// measured settings (open PR #1060's table); Size 0 is as fine as uncorrelated pixels get (0.5). #[test] From 7f637bef4700b3ef446a6ba07ec4a575e679d18b Mon Sep 17 00:00:00 2001 From: Jeremy Hooke Date: Tue, 3 Nov 2026 14:42:20 +1100 Subject: [PATCH 10/14] LR-EDIT-EFFECTS-GRAIN: review fix (renders that miss a tile together draw it once) A render off the thread pool checked for a tile being drawn, let go of the lock, then registered its own draw without looking at the result: two renders that missed the same tile together both drew it. The check, the wait and the registration now happen under one lock. The new test races eight renders per seed and failed on the old code every run. Co-Authored-By: Claude Opus 5.5 --- crates/pipeline/src/crystal.rs | 24 ++++++++++++++++-------- crates/pipeline/src/tests_crystal.rs | 23 +++++++++++++++++++++++ 2 files changed, 39 insertions(+), 8 deletions(-) diff --git a/crates/pipeline/src/crystal.rs b/crates/pipeline/src/crystal.rs index fe33711c3e..e3caa6ae2c 100644 --- a/crates/pipeline/src/crystal.rs +++ b/crates/pipeline/src/crystal.rs @@ -883,17 +883,25 @@ fn tile_in(cache: &'static Cache, look: CrystalLook, seed: u32, wait: bool) -> O let id = (std::ptr::from_ref(cache) as usize, key); // a pool worker draws the tile itself: blocked, it could hold up the drawing it waits for // (its stack may carry a part of that drawing's parallel work); wasm has no other threads - if !cfg!(target_arch = "wasm32") && rayon::current_thread_index().is_none() { + let _drawing = if !cfg!(target_arch = "wasm32") && rayon::current_thread_index().is_none() { + // checked, waited for and registered under one lock: two renders that miss the tile + // together can't both find it neither cached nor being drawn (`cached` takes the cache's + // lock under this one; nothing takes them the other way round) let mut busy = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner); - while busy.contains(&id) { + loop { + if let Some(t) = cached(cache, key) { + return Some(t); + } + if !busy.contains(&id) { + break; + } busy = DRAWN.wait(busy).unwrap_or_else(PoisonError::into_inner); } - drop(busy); - if let Some(t) = cached(cache, key) { - return Some(t); - } - } - let _drawing = start_drawing(id); + busy.push(id); + Some(Drawing(id)) + } else { + start_drawing(id) + }; let t = Arc::new(CrystalTile::new(look, seed)?); keep(cache, key, t.clone()); Some(t) diff --git a/crates/pipeline/src/tests_crystal.rs b/crates/pipeline/src/tests_crystal.rs index 1101de4eed..6f2f5c27fe 100644 --- a/crates/pipeline/src/tests_crystal.rs +++ b/crates/pipeline/src/tests_crystal.rs @@ -201,6 +201,29 @@ fn a_render_waits_for_a_tile_being_drawn() { assert!(Arc::ptr_eq(&got, &drawn), "the render drew the tile again"); } +/// Renders that miss the same tile together draw it once: the first registers the draw and the +/// others wait for it, as no gap lets a second render find it neither cached nor being drawn. +#[test] +fn renders_that_miss_a_tile_together_draw_it_once() { + static OWN: Cache = Mutex::new(Vec::new()); + const N: usize = 8; + let look = CrystalLook::new(0.0, 50.0); + for seed in 0x0d4a_1000..0x0d4a_1000 + 40 { + let start = Arc::new(std::sync::Barrier::new(N)); + let renders: Vec<_> = (0..N) + .map(|_| { + let start = start.clone(); + std::thread::spawn(move || { + start.wait(); + tile_in(&OWN, look, seed, true) + }) + }) + .collect(); + let got: Vec<_> = renders.into_iter().map(|r| r.join().expect("render thread").expect("tile")).collect(); + assert!(got.iter().all(|t| Arc::ptr_eq(t, &got[0])), "seed {seed:#x}: a render drew the tile again"); + } +} + /// Grain width (autocorrelation half-width at mid grey, 6000 px) at Lightroom Classic's /// measured settings (open PR #1060's table); Size 0 is as fine as uncorrelated pixels get (0.5). #[test] From 6b59774ca7784363f92111e7e618ccf5ddff655d Mon Sep 17 00:00:00 2001 From: Jeremy Hooke Date: Tue, 3 Nov 2026 15:35:34 +1100 Subject: [PATCH 11/14] LR-EDIT-EFFECTS-GRAIN: review fix (a drawer hands its tile to the renders waiting for it) A render waiting for a tile read it back from the cache after waking; if other tiles evicted it meanwhile, the render drew it again. The in-flight entry now carries a slot the drawer fills before it wakes the waiters. The tests wait for the renders to reach the wait (by the slot's holders) instead of sleeping, and the simultaneous-miss test holds the first draw until the other seven renders wait, so the misses always overlap. Co-Authored-By: Claude Opus 5.5 --- crates/pipeline/src/crystal.rs | 64 ++++++++++++++++++++-------- crates/pipeline/src/tests_crystal.rs | 52 +++++++++++++++++++++- 2 files changed, 98 insertions(+), 18 deletions(-) diff --git a/crates/pipeline/src/crystal.rs b/crates/pipeline/src/crystal.rs index e3caa6ae2c..586aed4d98 100644 --- a/crates/pipeline/src/crystal.rs +++ b/crates/pipeline/src/crystal.rs @@ -29,7 +29,7 @@ //! GPU kernel (`finish.wgsl`, which reads the same tables). use std::f64::consts::TAU; -use std::sync::{Arc, Condvar, Mutex, PoisonError}; +use std::sync::{Arc, Condvar, Mutex, OnceLock, PoisonError}; use lightcraft_color::transfer::srgb_to_linear; use lightcraft_develop::Grain; @@ -822,17 +822,40 @@ static TILES: Cache = Mutex::new(Vec::new()); /// The tile being drawn in the background for a drag ([`tile`]): one at a time. static DRAWING: Mutex> = Mutex::new(None); +/// The tile a drawing hands to the renders waiting for it, set when it is drawn. +type Slot = Arc>>; + /// The tiles being drawn, by cache and key, and the condition their drawers signal when done: a -/// render that misses a tile another is drawing waits for it rather than drawing it again. -static IN_FLIGHT: Mutex> = Mutex::new(Vec::new()); +/// render that misses a tile another is drawing waits for it rather than drawing it again. The +/// drawer hands the tile over in its slot, so the waiters get it even if the cache has evicted it +/// by the time they wake. +static IN_FLIGHT: Mutex> = Mutex::new(Vec::new()); static DRAWN: Condvar = Condvar::new(); /// Marks a tile drawn (or failed) when dropped and wakes the renders waiting for it. -struct Drawing((usize, Key)); +struct Drawing { + id: (usize, Key), + done: Slot, +} + +impl Drawing { + /// Registers the draw of `id` in `busy` (the locked [`IN_FLIGHT`]). + fn register(busy: &mut Vec<((usize, Key), Slot)>, id: (usize, Key)) -> Drawing { + let done = Slot::default(); + busy.push((id, done.clone())); + Drawing { id, done } + } + + /// Hands `t` to the renders waiting for it (they wake when this is dropped). + fn finish(&self, t: &Arc) { + // (already set: only the first tile counts, and every drawing draws the same one) + let _ = self.done.set(t.clone()); + } +} impl Drop for Drawing { fn drop(&mut self) { - IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner).retain(|d| *d != self.0); + IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner).retain(|(d, _)| *d != self.id); DRAWN.notify_all(); } } @@ -840,11 +863,10 @@ impl Drop for Drawing { /// Registers the tile of `id` as being drawn, or `None` if another thread is drawing it. fn start_drawing(id: (usize, Key)) -> Option { let mut busy = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner); - if busy.contains(&id) { + if busy.iter().any(|(d, _)| *d == id) { return None; } - busy.push(id); - Some(Drawing(id)) + Some(Drawing::register(&mut busy, id)) } /// The tile of `key` in `cache`. @@ -883,26 +905,32 @@ fn tile_in(cache: &'static Cache, look: CrystalLook, seed: u32, wait: bool) -> O let id = (std::ptr::from_ref(cache) as usize, key); // a pool worker draws the tile itself: blocked, it could hold up the drawing it waits for // (its stack may carry a part of that drawing's parallel work); wasm has no other threads - let _drawing = if !cfg!(target_arch = "wasm32") && rayon::current_thread_index().is_none() { + let drawing = if !cfg!(target_arch = "wasm32") && rayon::current_thread_index().is_none() { // checked, waited for and registered under one lock: two renders that miss the tile // together can't both find it neither cached nor being drawn (`cached` takes the cache's // lock under this one; nothing takes them the other way round) let mut busy = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner); + let mut waited_for: Option = None; loop { - if let Some(t) = cached(cache, key) { + if let Some(t) = waited_for.as_ref().and_then(|done| done.get().cloned()).or_else(|| cached(cache, key)) { return Some(t); } - if !busy.contains(&id) { - break; - } + let Some((_, done)) = busy.iter().find(|(d, _)| *d == id) else { break }; + waited_for = Some(done.clone()); busy = DRAWN.wait(busy).unwrap_or_else(PoisonError::into_inner); } - busy.push(id); - Some(Drawing(id)) + Some(Drawing::register(&mut busy, id)) } else { start_drawing(id) }; + #[cfg(test)] + if let Some(d) = &drawing { + tests::hold_for_waiters(d); + } let t = Arc::new(CrystalTile::new(look, seed)?); + if let Some(d) = &drawing { + d.finish(&t); + } keep(cache, key, t.clone()); Some(t) } @@ -932,7 +960,9 @@ fn draw_in_background(cache: &'static Cache, key: Key, look: CrystalLook, seed: }; spawn_in_background(move || { if let Some(t) = CrystalTile::new(look, seed) { - keep(cache, key, Arc::new(t)); + let t = Arc::new(t); + marker.finish(&t); + keep(cache, key, t); } drop(marker); *DRAWING.lock().unwrap_or_else(PoisonError::into_inner) = None; @@ -950,7 +980,7 @@ fn spawn_in_background(draw: impl FnOnce() + Send + 'static) { /// Half the cores, for tiles drawn in the background (`None`: the pool couldn't be made). fn background_pool() -> Option<&'static rayon::ThreadPool> { - static POOL: std::sync::OnceLock> = std::sync::OnceLock::new(); + static POOL: OnceLock> = OnceLock::new(); POOL.get_or_init(|| { let n = std::thread::available_parallelism().map_or(2, |n| n.get()).div_ceil(2); rayon::ThreadPoolBuilder::new().num_threads(n).thread_name(|i| format!("grain-tile-{i}")).build().ok() diff --git a/crates/pipeline/src/tests_crystal.rs b/crates/pipeline/src/tests_crystal.rs index 6f2f5c27fe..b0b44c1596 100644 --- a/crates/pipeline/src/tests_crystal.rs +++ b/crates/pipeline/src/tests_crystal.rs @@ -1,5 +1,29 @@ use super::*; +/// The draws [`hold_for_waiters`] holds, by cache, and how many renders wait for each. +static HOLDS: Mutex> = Mutex::new(Vec::new()); + +/// Holds the draw of `d` until the renders [`HOLDS`] names for its cache are waiting for it (each +/// holds a clone of its slot, as do the drawing and its in-flight entry), so a test can make +/// renders miss a tile together. +pub(super) fn hold_for_waiters(d: &Drawing) { + let held = HOLDS.lock().unwrap_or_else(PoisonError::into_inner).iter().find(|(c, _)| *c == d.id.0).map(|h| h.1); + let Some(waiters) = held else { return }; + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + while Arc::strong_count(&d.done) < 2 + waiters && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(1)); + } +} + +/// Waits until `n` renders wait for the draw of `d`. +fn until_waiting(d: &Drawing, n: usize) { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + while Arc::strong_count(&d.done) < 2 + n { + assert!(std::time::Instant::now() < deadline, "the renders never waited"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } +} + /// The field rendered at `long` px per long edge on an `n × n` patch starting at pixel `origin`. fn patch(tile: &CrystalTile, long: f64, n: usize, origin: usize) -> Vec { let w = (TILE_PER_LONG / long) as f32; @@ -193,7 +217,7 @@ fn a_render_waits_for_a_tile_being_drawn() { let key = key_of(look, seed); let marker = start_drawing((std::ptr::from_ref(&OWN) as usize, key)).expect("not drawn yet"); let render = std::thread::spawn(move || tile_in(&OWN, look, seed, true)); - std::thread::sleep(std::time::Duration::from_millis(200)); + until_waiting(&marker, 1); let drawn = Arc::new(CrystalTile::new(look, seed).expect("tile")); keep(&OWN, key, drawn.clone()); drop(marker); @@ -201,12 +225,38 @@ fn a_render_waits_for_a_tile_being_drawn() { assert!(Arc::ptr_eq(&got, &drawn), "the render drew the tile again"); } +/// A render waiting for a tile gets it from its drawer even when the cache evicted it before the +/// render woke. +#[test] +fn a_waiting_render_gets_the_tile_the_cache_evicted() { + static OWN: Cache = Mutex::new(Vec::new()); + let (look, seed) = (CrystalLook::new(40.0, 50.0), 0x0d4a_0004); + let key = key_of(look, seed); + let marker = start_drawing((std::ptr::from_ref(&OWN) as usize, key)).expect("not drawn yet"); + let render = std::thread::spawn(move || tile_in(&OWN, look, seed, true)); + until_waiting(&marker, 1); + let drawn = Arc::new(CrystalTile::new(look, seed).expect("tile")); + marker.finish(&drawn); + keep(&OWN, key, drawn.clone()); + // other renders' tiles push it out of the cache before the waiter wakes + for other in 1..=CACHE as u32 { + keep(&OWN, key_of(look, seed + other), drawn.clone()); + } + assert!(cached(&OWN, key).is_none(), "the tile is still cached"); + drop(marker); + let got = render.join().expect("render thread").expect("tile"); + assert!(Arc::ptr_eq(&got, &drawn), "the render drew the tile again"); +} + /// Renders that miss the same tile together draw it once: the first registers the draw and the /// others wait for it, as no gap lets a second render find it neither cached nor being drawn. +/// The first draw is held until the other renders all wait for it, so the misses overlap. #[test] fn renders_that_miss_a_tile_together_draw_it_once() { static OWN: Cache = Mutex::new(Vec::new()); const N: usize = 8; + // the first render's draw waits for the other seven to miss the tile too + HOLDS.lock().unwrap_or_else(PoisonError::into_inner).push((std::ptr::from_ref(&OWN) as usize, N - 1)); let look = CrystalLook::new(0.0, 50.0); for seed in 0x0d4a_1000..0x0d4a_1000 + 40 { let start = Arc::new(std::sync::Barrier::new(N)); From 21a235f6241b761defea5e9e5469ce0ecaa77400 Mon Sep 17 00:00:00 2001 From: Jeremy Hooke Date: Tue, 3 Nov 2026 16:52:23 +1100 Subject: [PATCH 12/14] LR-EDIT-EFFECTS-GRAIN: review fixes (crystal tile waiter tests) - hold_for_waiters fails at its deadline instead of returning, so a setup that never makes renders overlap can't pass. - A test drives the real tile_in drawer, with its cache emptied before the waiter wakes, and asserts the waiter gets the drawer's tile. It fails if tile_in's finish call is removed. A hold now applies to a set number of draws, so a redraw isn't held too. - The eviction test gives each replacement entry its own tile. Co-Authored-By: Claude Opus 5.5 --- crates/pipeline/src/crystal.rs | 4 +++ crates/pipeline/src/tests_crystal.rs | 52 +++++++++++++++++++++++----- 2 files changed, 48 insertions(+), 8 deletions(-) diff --git a/crates/pipeline/src/crystal.rs b/crates/pipeline/src/crystal.rs index 586aed4d98..3e6f644bb7 100644 --- a/crates/pipeline/src/crystal.rs +++ b/crates/pipeline/src/crystal.rs @@ -932,6 +932,10 @@ fn tile_in(cache: &'static Cache, look: CrystalLook, seed: u32, wait: bool) -> O d.finish(&t); } keep(cache, key, t.clone()); + #[cfg(test)] + if let Some(d) = &drawing { + tests::evict_before_waking(cache, d); + } Some(t) } diff --git a/crates/pipeline/src/tests_crystal.rs b/crates/pipeline/src/tests_crystal.rs index b0b44c1596..f57802a1ff 100644 --- a/crates/pipeline/src/tests_crystal.rs +++ b/crates/pipeline/src/tests_crystal.rs @@ -1,20 +1,37 @@ use super::*; -/// The draws [`hold_for_waiters`] holds, by cache, and how many renders wait for each. -static HOLDS: Mutex> = Mutex::new(Vec::new()); +/// The draws [`hold_for_waiters`] holds, by cache: how many renders wait for each, and how many +/// draws are left to hold. +static HOLDS: Mutex> = Mutex::new(Vec::new()); /// Holds the draw of `d` until the renders [`HOLDS`] names for its cache are waiting for it (each /// holds a clone of its slot, as do the drawing and its in-flight entry), so a test can make /// renders miss a tile together. pub(super) fn hold_for_waiters(d: &Drawing) { - let held = HOLDS.lock().unwrap_or_else(PoisonError::into_inner).iter().find(|(c, _)| *c == d.id.0).map(|h| h.1); - let Some(waiters) = held else { return }; + let waiters = { + let mut holds = HOLDS.lock().unwrap_or_else(PoisonError::into_inner); + let Some(h) = holds.iter_mut().find(|h| h.0 == d.id.0 && h.2 > 0) else { return }; + h.2 -= 1; + h.1 + }; let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); - while Arc::strong_count(&d.done) < 2 + waiters && std::time::Instant::now() < deadline { + while Arc::strong_count(&d.done) < 2 + waiters { + assert!(std::time::Instant::now() < deadline, "the renders never waited"); std::thread::sleep(std::time::Duration::from_millis(1)); } } +/// The caches [`evict_before_waking`] empties. +static EVICTS: Mutex> = Mutex::new(Vec::new()); + +/// Empties `cache` if [`EVICTS`] names it, after its drawer `d` has cached its tile and before it +/// wakes the renders waiting for it, as other renders' tiles can push it out in that gap. +pub(super) fn evict_before_waking(cache: &Cache, d: &Drawing) { + if EVICTS.lock().unwrap_or_else(PoisonError::into_inner).contains(&d.id.0) { + cache.lock().unwrap_or_else(PoisonError::into_inner).clear(); + } +} + /// Waits until `n` renders wait for the draw of `d`. fn until_waiting(d: &Drawing, n: usize) { let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); @@ -239,8 +256,9 @@ fn a_waiting_render_gets_the_tile_the_cache_evicted() { marker.finish(&drawn); keep(&OWN, key, drawn.clone()); // other renders' tiles push it out of the cache before the waiter wakes + // (each its own tile: a waiter that took another key's would fail the check below) for other in 1..=CACHE as u32 { - keep(&OWN, key_of(look, seed + other), drawn.clone()); + keep(&OWN, key_of(look, seed + other), Arc::new(CrystalTile::new(look, seed + other).expect("tile"))); } assert!(cached(&OWN, key).is_none(), "the tile is still cached"); drop(marker); @@ -248,6 +266,23 @@ fn a_waiting_render_gets_the_tile_the_cache_evicted() { assert!(Arc::ptr_eq(&got, &drawn), "the render drew the tile again"); } +/// A render waiting for a tile another render is drawing gets the drawer's tile even when the +/// cache drops it before the waiter wakes. +#[test] +fn a_render_drawing_a_tile_hands_it_to_its_waiter() { + static OWN: Cache = Mutex::new(Vec::new()); + let id = std::ptr::from_ref(&OWN) as usize; + // the first render's draw (only: a second would be the waiter drawing it again) waits for the + // second render to wait for it, and the cache empties before the second wakes + HOLDS.lock().unwrap_or_else(PoisonError::into_inner).push((id, 1, 1)); + EVICTS.lock().unwrap_or_else(PoisonError::into_inner).push(id); + let (look, seed) = (CrystalLook::new(0.0, 50.0), 0x0d4a_0005); + let renders: Vec<_> = (0..2).map(|_| std::thread::spawn(move || tile_in(&OWN, look, seed, true))).collect(); + let got: Vec<_> = renders.into_iter().map(|r| r.join().expect("render thread").expect("tile")).collect(); + assert!(cached(&OWN, key_of(look, seed)).is_none(), "the cache kept the tile"); + assert!(Arc::ptr_eq(&got[0], &got[1]), "the waiter drew the tile again"); +} + /// Renders that miss the same tile together draw it once: the first registers the draw and the /// others wait for it, as no gap lets a second render find it neither cached nor being drawn. /// The first draw is held until the other renders all wait for it, so the misses overlap. @@ -256,9 +291,10 @@ fn renders_that_miss_a_tile_together_draw_it_once() { static OWN: Cache = Mutex::new(Vec::new()); const N: usize = 8; // the first render's draw waits for the other seven to miss the tile too - HOLDS.lock().unwrap_or_else(PoisonError::into_inner).push((std::ptr::from_ref(&OWN) as usize, N - 1)); + const SEEDS: u32 = 40; + HOLDS.lock().unwrap_or_else(PoisonError::into_inner).push((std::ptr::from_ref(&OWN) as usize, N - 1, SEEDS as usize)); let look = CrystalLook::new(0.0, 50.0); - for seed in 0x0d4a_1000..0x0d4a_1000 + 40 { + for seed in 0x0d4a_1000..0x0d4a_1000 + SEEDS { let start = Arc::new(std::sync::Barrier::new(N)); let renders: Vec<_> = (0..N) .map(|_| { From a850d05fe40b2dcd1ad9ca51b1caaf28c86c7f12 Mon Sep 17 00:00:00 2001 From: Jeremy Hooke Date: Sat, 7 Nov 2026 10:31:14 +1100 Subject: [PATCH 13/14] LR-EDIT-EFFECTS-GRAIN: review fixes (crystal grain unit tests) Direct tests for what was only covered through whole renders, or not at all: slider clamping and NaN fallbacks, interp, normal_quantile, the Poisson draws, the emulsion's mix of sizes per seed, the summed-area table and box sums against brute force (seams, negative coordinates, other periods) and the footprint limit. A tile redrawn is now compared with the first one directly: seed_picks_the_pattern compared a cached tile with itself. Co-Authored-By: Claude Opus 5.5 --- crates/pipeline/src/crystal.rs | 2 +- crates/pipeline/src/tests_crystal.rs | 192 ++++++++++++++++++++++++++- docs/grain.md | 1 + 3 files changed, 189 insertions(+), 6 deletions(-) diff --git a/crates/pipeline/src/crystal.rs b/crates/pipeline/src/crystal.rs index 9f47542657..241fd8c7ae 100644 --- a/crates/pipeline/src/crystal.rs +++ b/crates/pipeline/src/crystal.rs @@ -50,7 +50,7 @@ pub const FILLING: f64 = 0.5; const BAND: usize = 64; /// Encoded luminance at which the strength is specified (mid grey, 128 of 255). const MID_GREY: f32 = 128.0 / 255.0; -/// A footprint this large (tile pixels: a render under 24 px long) gets no grain. +/// A footprint this large (tile pixels: a render 24 px long or less) gets no grain. const MAX_FOOTPRINT: f32 = 500.0; /// Settings whose tiles are kept (a preview and an export, a few thumbnails). const CACHE: usize = 4; diff --git a/crates/pipeline/src/tests_crystal.rs b/crates/pipeline/src/tests_crystal.rs index 33c88b0e5e..59428491b0 100644 --- a/crates/pipeline/src/tests_crystal.rs +++ b/crates/pipeline/src/tests_crystal.rs @@ -187,11 +187,193 @@ fn hostile_settings_render_finite_or_no_grain() { #[test] fn seed_picks_the_pattern() { let look = CrystalLook::new(25.0, 50.0); - let (a, b, c) = (tile(look, 1, true), tile(look, 1, true), tile(look, 2, true)); - let (Some(a), Some(b), Some(c)) = (a, b, c) else { panic!("tiles") }; - let (pa, pb, pc) = (patch(&a, REF_LONG, 64, 0), patch(&b, REF_LONG, 64, 0), patch(&c, REF_LONG, 64, 0)); - assert_eq!(pa, pb); - assert_ne!(pa, pc); + let (Some(a), Some(c)) = (tile(look, 1, true), tile(look, 2, true)) else { panic!("tiles") }; + assert_ne!(patch(&a, REF_LONG, 64, 0), patch(&c, REF_LONG, 64, 0)); +} + +/// A tile drawn again (its cache entry evicted, another process, an export after a preview) is the +/// same to the bit, however many threads draw it. These draw directly: through [`tile`], the second +/// would be the first one out of the cache. +#[test] +fn a_tile_draws_the_same_every_time() { + let look = CrystalLook::new(25.0, 50.0); + let one_thread = rayon::ThreadPoolBuilder::new().num_threads(1).build().expect("a pool"); + let (Some(a), Some(b)) = (CrystalTile::new(look, 1), one_thread.install(|| CrystalTile::new(look, 1))) else { panic!("tiles") }; + assert!(a.sats == b.sats, "the same seed drew different tiles"); +} + +/// Every seed has the same mix of crystal sizes, dealt to the layers in its own order. +#[test] +fn seeds_share_the_mix_of_crystal_sizes() { + let look = CrystalLook::new(50.0, 80.0); + let radii = |seed| emulsion(seed, &look).iter().map(|l| l.r).collect::>(); + let sorted = |mut v: Vec| { + v.sort_by(f64::total_cmp); + v + }; + let (a, b) = (radii(1), radii(2)); + assert_eq!(a.len(), look.layers); + assert_eq!(a, radii(1), "the same seed deals the same order"); + assert_ne!(a, b, "another seed deals another order"); + assert_eq!(sorted(a), sorted(b)); + assert_eq!(emulsion(1, &CrystalLook { layers: 0, ..look }).len(), 1, "an emulsion has a layer"); +} + +#[test] +fn sliders_clamp_and_fall_back() { + let look = CrystalLook::new; + assert_eq!(look(f64::NAN, f64::NAN), look(25.0, 50.0), "NaN is the default"); + assert_eq!(look(-1e9, f64::NEG_INFINITY), look(0.0, 0.0)); + assert_eq!(look(1e9, f64::INFINITY), look(100.0, 100.0)); + // the ends of the tables + assert_eq!((look(0.0, 50.0).width, look(0.0, 50.0).layers), (0.55, 16)); + assert_eq!((look(100.0, 50.0).width, look(100.0, 50.0).layers), (12.38, 70)); + assert_eq!(look(100.0, 0.0).width, 12.38 * 0.734); + assert_eq!(look(100.0, 100.0).width, 12.38 * 1.422); + assert!(look(25.0, 100.0).spread > look(25.0, 0.0).spread); + + let default = strength_levels(50.0, 25.0, 50.0); + assert_eq!(strength_levels(f64::NAN, 25.0, 50.0), 0.0, "a NaN Amount is no grain"); + assert_eq!(strength_levels(-5.0, 25.0, 50.0), 0.0); + assert_eq!(strength_levels(50.0, f64::NAN, f64::NAN), default); + assert_eq!(strength_levels(1e9, 25.0, 50.0), 2.0 * default); + assert_eq!(strength_levels(50.0, -1e9, 50.0), strength_levels(50.0, 0.0, 50.0)); + assert_eq!(strength_levels(50.0, 25.0, f64::INFINITY), strength_levels(50.0, 25.0, 100.0)); + // Lightroom Classic's at the ends of each slider (`docs/grain.md`) + for (want, (a, s, r)) in [(23.08, (50.0, 0.0, 50.0)), (5.83, (50.0, 100.0, 50.0)), (12.42, (50.0, 25.0, 0.0)), (11.68, (50.0, 25.0, 100.0))] { + let got = strength_levels(a, s, r); + assert!((got / want - 1.0).abs() < 0.01, "{a}/{s}/{r}: {got}, want {want}"); + } +} + +#[test] +fn interp_is_linear_between_knots_and_constant_outside() { + let knots = [(0.0, 1.0), (10.0, 3.0), (20.0, 2.0)]; + for (x, want) in [(-5.0, 1.0), (0.0, 1.0), (5.0, 2.0), (10.0, 3.0), (15.0, 2.5), (20.0, 2.0), (99.0, 2.0)] { + assert_eq!(interp(&knots, x), want, "at {x}"); + } + assert_eq!(interp(&[], 5.0), 0.0); + assert_eq!(interp(&[(3.0, 7.0)], 5.0), 7.0); +} + +#[test] +fn normal_quantile_matches_the_table() { + for (p, z) in [(0.5, 0.0), (0.975, 1.959_963_985), (0.841_344_746, 1.0), (0.001, -3.090_232_306), (1e-6, -4.753_424_309)] { + assert!((normal_quantile(p) - z).abs() < 1e-7, "at {p}: {}, want {z}", normal_quantile(p)); + assert!((normal_quantile(1.0 - p) + z).abs() < 1e-7, "at 1 - {p}"); + } + // increasing across the approximation's joins (0.02425 and its mirror), finite at the ends + let sweep: Vec = (0..=1000).map(|k| normal_quantile(k as f64 / 1000.0)).collect(); + assert!(sweep.iter().all(|z| z.is_finite())); + assert!(sweep.windows(2).all(|w| w[0] < w[1])); +} + +#[test] +fn poisson_counts_have_the_mean_and_variance_of_mu() { + let n = 40_000u32; + for mu in [0.5, 4.0, 40.0, 150.0] { + let cdf = poisson_cdf(mu); + assert!(cdf.windows(2).all(|w| w[0] <= w[1]), "mu {mu}: the distribution must not fall"); + assert!(cdf.last().is_some_and(|&c| c >= 1.0 - 1e-12), "mu {mu}: the distribution must reach 1"); + let draws: Vec = (0..n).map(|i| poisson(&cdf, mix(i)) as f64).collect(); + let mean = draws.iter().sum::() / n as f64; + let var = draws.iter().map(|d| (d - mean).powi(2)).sum::() / n as f64; + assert!((mean - mu).abs() < 4.0 * (mu / n as f64).sqrt(), "mu {mu}: mean {mean}"); + assert!((var / mu - 1.0).abs() < 0.05, "mu {mu}: variance {var}"); + } +} + +#[test] +fn poisson_stays_in_range_at_the_ends() { + for h in [0, u32::MAX] { + assert_eq!(poisson(&poisson_cdf(0.0), h), 0, "mean 0 is never a crystal"); + // past what the model uses, e^-mu underflows: a capped count, not a panic + assert!(poisson(&poisson_cdf(1e6), h) <= 512); + assert_eq!(poisson(&[], h), 0); + } +} + +#[test] +fn summed_area_matches_brute_force() { + let t = 7; + let count: Vec = (0..t * t).map(|i| (mix(i as u32) % 71) as u8).collect(); + let sat = summed_area(&count, t); + assert_eq!(sat.len(), (t + 1) * (t + 1)); + for y in 0..=t { + for x in 0..=t { + let want: u32 = (0..y).flat_map(|j| (0..x).map(move |i| (i, j))).map(|(i, j)| count[j * t + i] as u32).sum(); + assert_eq!(sat[y * (t + 1) + x], want, "[0, {x}) × [0, {y})"); + } + } +} + +/// Boxes against the emulsion's own pixels (each table's counts, less their mean, scaled to unit +/// variance as [`CrystalTile::new`] does), integrated by hand. Whole and fractional boxes, across +/// the torus's seams, at negative coordinates and periods away. +#[test] +fn box_sum_is_the_integral_of_the_emulsion() { + let (look, seed) = (CrystalLook::new(25.0, 50.0), 7); + let tile = CrystalTile::new(look, seed).expect("a tile"); + let counts = [0, 1].map(|which| draw_torus(which, TORI[which], seed, &look)); + let means: [f64; 2] = [0, 1].map(|w| counts[w].iter().map(|&c| c as f64).sum::() / (TORI[w] * TORI[w]) as f64); + let var: f64 = [0, 1] + .map(|w| { + let (sq, n) = reference_square_sum(&counts[w], TORI[w], means[w]); + sq / n as f64 + }) + .iter() + .sum(); + let k = 1.0 / var.sqrt(); + // The overlap of the cell at `i` with `[a, a + w]`. + let overlap = |i: i64, a: f64, w: f64| ((i + 1) as f64).min(a + w) - (i as f64).max(a); + let integral_by_hand = |which: usize, x0: f32, y0: f32, w: f32| { + let (x0, y0, w, t) = (x0 as f64, y0 as f64, w as f64, TORI[which] as i64); + let mut sum = 0.0; + for j in y0.floor() as i64..(y0 + w).ceil() as i64 { + for i in x0.floor() as i64..(x0 + w).ceil() as i64 { + let c = counts[which][(j.rem_euclid(t) * t + i.rem_euclid(t)) as usize] as f64; + sum += (c - means[which]) * k * overlap(i, x0, w) * overlap(j, y0, w); + } + } + sum + }; + for which in [0, 1] { + let t = TORI[which] as f32; + for (x0, y0, w) in [ + (0.0, 0.0, 2.0), + (100.0, 200.0, 37.0), + (3.25, 7.5, 2.0), + (10.6, 11.3, 0.7), + (50.5, 60.25, 400.0), + (t - 1.5, 20.0, 4.0), + (20.0, t - 1.5, 4.0), + (t - 0.5, t - 0.25, 31.0), + (-1.5, -2.25, 8.0), + (3.0 * t + 12.5, -2.0 * t + 40.5, 8.0), + ] { + let (got, want) = (tile.box_sum(which, x0, y0, w) as f64, integral_by_hand(which, x0, y0, w)); + let area = (w * w) as f64; + assert!((got - want).abs() / area < 2e-3, "torus {which}, ({x0}, {y0}) side {w}: {got} vs {want}"); + } + } + // the field is the two tori's mean, centred on its position + let (x, y, w) = (640.25, 1133.5, 3.0); + let want = (integral_by_hand(0, x - 0.5 * w, y - 0.5 * w, w) + integral_by_hand(1, x - 0.5 * w, y - 0.5 * w, w)) / (w * w) as f64; + assert!((tile.field(x, y, w) as f64 - want).abs() < 2e-3, "field {} vs {want}", tile.field(x, y, w)); +} + +/// A render under the footprint limit gets grain, one at or past it none, whatever else it asks. +#[test] +fn only_a_render_past_the_footprint_limit_loses_its_grain() { + let g = Grain { amount: 50.0, size: 25.0, roughness: 50.0, seed: 3 }; + let limit = TILE_PER_LONG / MAX_FOOTPRINT as f64; + assert_eq!(limit, 24.0); + for none in [limit, limit - 1.0, 1.0, 0.0, -5.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert!(CrystalGrain::new(&g, none).is_none(), "{none} px per long edge"); + } + assert_eq!(CrystalGrain::new(&g, limit + 1.0).expect("grain").foot, 480.0); + assert_eq!(CrystalGrain::new(&g, REF_LONG).expect("grain").foot, 2.0); + assert!(CrystalGrain::new(&Grain { amount: 0.0, ..g }, REF_LONG).is_none(), "no grain at Amount 0"); } /// A draft (a Size or Roughness drag) doesn't wait for a new tile: the last tile of the seed stands diff --git a/docs/grain.md b/docs/grain.md index fe271e8131..37890df317 100644 --- a/docs/grain.md +++ b/docs/grain.md @@ -132,6 +132,7 @@ curtain; #1060: −9.3). Fine detail under the grain is kept (detail gain | main (value noise) | 3.2–3.4 | 2.9–3.0 | 2.9 | | #1060 (particles) | 3.3 | 3.0–3.1 | 35.6–36.0 | | this model | 3.2–3.3 | 3.4–3.5 | 5.9–6.0 | + - **Per pixel:** two box sums, on the CPU and on the GPU. The tables (12 MB) stay on the GPU between renders, for the last tile used (`Gpu::grain_tables`), and are copied after the finish kernel's other tables in its `aux` buffer on the GPU: an Amount drag uploads nothing. On the From 622c288621d404b3d40a5ebccce1ce8d203746de Mon Sep 17 00:00:00 2001 From: Jeremy Hooke Date: Sat, 7 Nov 2026 11:06:06 +1100 Subject: [PATCH 14/14] LR-EDIT-EFFECTS-GRAIN: review fix (a draft waits when nothing can stand in) Co-Authored-By: Claude Opus 5.5 --- crates/pipeline/src/crystal.rs | 4 +++- docs/grain.md | 10 ++++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/crates/pipeline/src/crystal.rs b/crates/pipeline/src/crystal.rs index 15f5fac6ec..325329d3ff 100644 --- a/crates/pipeline/src/crystal.rs +++ b/crates/pipeline/src/crystal.rs @@ -878,7 +878,9 @@ fn cached(cache: &Cache, key: Key) -> Option> { /// The tile of `look` and `seed`, drawn or from the cache. Unless `wait`, a tile not drawn yet /// is drawn in the background and the last one drawn for `seed` stands in for it meanwhile: a /// Size or Roughness drag doesn't wait for every step's tile (tens of milliseconds on a slow -/// CPU), and the full-quality render when it ends waits for the exact one. +/// CPU), and the full-quality render when it ends waits for the exact one. With no tile cached +/// for `seed` nothing can stand in, so even without `wait` this waits for a draw already running +/// or draws the tile. fn tile(look: CrystalLook, seed: u32, wait: bool) -> Option> { tile_in(&TILES, look, seed, wait) } diff --git a/docs/grain.md b/docs/grain.md index 5302c012f1..5e66405c6f 100644 --- a/docs/grain.md +++ b/docs/grain.md @@ -108,10 +108,12 @@ curtain; #1060: −9.3). Fine detail under the grain is kept (detail gain in bit-sliced counters, and the tiles are drawn in parallel bands. 7–15 ms on an M2 Max (12 threads), 15–33 ms on a Ryzen 5 7545U (6 cores, 12 threads; 10–20 % less than before the row masks) at any setting (`tile_timing_report`). -- **Drags.** A draft render (a slider drag) doesn't wait for a tile it hasn't got: the last tile - drawn for the photo's seed stands in while the new one is drawn in the background, on a pool of - half the cores so the drag's renders don't queue behind it, and the next render takes it. The - full-quality render when the drag ends waits for the exact tile. A Size drag on the Ryzen with its +- **Drags.** A draft render (a slider drag) doesn't wait for a tile it hasn't got if one for the + photo's seed is cached: the last one drawn stands in while the new one is drawn in the background, + on a pool of half the cores so the drag's renders don't queue behind it, and the next render takes + it. With none cached for the seed there is nothing to stand in, so the draft waits for a draw + already running or draws the tile itself. The full-quality render when the drag ends waits for the + exact tile. A Size drag on the Ryzen with its Radeon 740M (GPU, 2.5 MP preview): 13–14 ms a frame instead of 62–66 ms. (On wasm, without threads, drafts wait.) - **Drag benchmark** (`FRAMES=100 cargo run --release -p lightcraft-gpu --example grain_drag_bench`: GPU