diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index 2600d794a45..36e040584cd 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -52,6 +52,7 @@ //! | 7 | Kelvin white balance for raws whose camera has matrices (#730) | `Op::SetAsShotWb`, `WhiteBalance.scale` | //! | 8 | History cursor: Go to History Step adds no step | `Op::SetHistoryCursor`, `Photo.history_cursor` | //! | 9 | preview-only recheck | `Photo.preview_checked`, `Op::SetContent.preview_checked` | +//! | 11 | film grain as particles, process V3 (#1060; 10 is claimed by open PRs: whichever lands later renumbers) | `Grain.color`, `Grain.response`, `Grain.size_variation`, `Grain.clumping`, `DevelopSettings.process` 3 | //! //! Rules: //! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a @@ -76,7 +77,7 @@ pub const LOG: &str = "catalog.log"; const FORMAT: &str = "lightcraft-catalog"; /// The catalog format this build writes (and the newest it reads). See the module docs → /// *Format versions*; bump it whenever an [`Op`] variant or a serialized field is added. -pub const VERSION: u32 = 9; +pub const VERSION: u32 = 11; /// When [`Journal::wants_snapshot`] says it's time to compact the log. #[derive(Clone, Copy, Debug)] diff --git a/crates/catalog/src/tests_format_version.rs b/crates/catalog/src/tests_format_version.rs index e31d7fe0c49..9eb8fd4f567 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -97,6 +97,33 @@ fn v6_preview_only_photo_loads_unstamped_and_is_upgraded() { assert_eq!(snapshot_version(&m), u64::from(VERSION)); } +/// A v9 library (before the particle grain and process V3, #1060) opens with its photos' grain and +/// process as they were: the new grain fields take their defaults, the process stays V2 (so the +/// photo keeps its value-noise grain), and the library is rewritten in the current format, which a +/// v9 build then refuses instead of dropping the new fields. +#[test] +fn v9_grain_loads_as_it_was_and_is_upgraded() { + let mut c = Catalog::new(); + let id = c.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: "/p/a.jpg".into() }, "a.jpg", "JPEG", 4, 3, "2026-01-01"); + let mut d = (*p.develop).clone(); + d.process = lightcraft_develop::Process::V2.version(); + d.grain.amount = 30.0; + let grain = d.grain; + p.develop = std::sync::Arc::new(d); + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + let snap = c.to_snapshot(); + assert!(!snap.contains("size_variation") && !snap.contains("clumping"), "a v9 build wrote none of them"); + let m = MemStore::new(); + m.set(SNAPSHOT, format!("{{\"format\":\"lightcraft-catalog\",\"version\":9,\"seq\":1,\"catalog\":{snap}}}\n").into_bytes()); + let (_, loaded, r) = Journal::open(Box::new(m.clone())).unwrap(); + let d = &loaded.photo(id).unwrap().develop; + assert_eq!(d.process, lightcraft_develop::Process::V2.version()); + assert_eq!(d.grain, grain, "the new grain fields take their defaults"); + assert_eq!(r.upgraded_from, Some(9)); + assert_eq!(snapshot_version(&m), u64::from(VERSION)); +} + #[test] fn versionless_log_only_library_is_upgraded() { let mut c = Catalog::new(); @@ -238,8 +265,9 @@ fn op_variants_are_versioned() { Op::SetHistoryCursor { .. } => 8, } } - /// v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`. - const NEWEST_FIELDS: u32 = 9; + /// v11: the particle grain's fields (`Grain.color`, `.response`, `.size_variation`, `.clumping`) + /// and process V3. + const NEWEST_FIELDS: u32 = 11; let newest = since(&Op::SetHistoryCursor { id: PhotoId(1), cursor: None }); assert_eq!(newest.max(NEWEST_FIELDS), VERSION, "the newest op's or fields' version must be the current format version"); } diff --git a/crates/develop/src/controls.rs b/crates/develop/src/controls.rs index 9d384f57c4f..e9be8428eb9 100644 --- a/crates/develop/src/controls.rs +++ b/crates/develop/src/controls.rs @@ -254,7 +254,12 @@ controls! { "vignette.highlights" => vignette.highlights, "Highlights", Vignette, 0, 100, 0, 1, 0, Plain; "grain.amount" => grain.amount, "Grain", Grain, 0, 100, 0, 1, 0, Plain; "grain.size" => grain.size, "Size", Grain, 0, 100, 25, 1, 0, Plain; - "grain.roughness" => grain.roughness, "Roughness", Grain, 0, 100, 50, 1, 0, Plain; + "grain.sizeVariation" => grain.size_variation, "Size Variation", Grain, 0, 100, 40, 1, 0, Plain; + "grain.roughness" => grain.roughness, "Shape", Grain, 0, 100, 50, 1, 0, Plain; + "grain.clumping" => grain.clumping, "Clumping", Grain, 0, 100, 30, 1, 0, Plain; + "grain.color" => grain.color, "Color", Grain, 0, 100, 0, 1, 0, Gradient { from: "#7a7a7a", to: "#c05ad0" }; + "grain.response" => grain.response, "Response", Grain, -100, 100, 0, 1, 0, Centered; + "grain.seed" => grain.seed, "Seed", Grain, 0, 99999, 0, 1, 0, Plain; "enhance.denoise" => enhance.denoise, "Amount", Detail, 0, 100, 0, 1, 0, Plain; "detail.sharpenAmount" => detail.sharpen_amount, "Sharpening", Detail, 0, 150, 0, 1, 0, Plain; "detail.sharpenRadius" => detail.sharpen_radius, "Radius", Detail, 0.5, 3, 1, 0.1, 1, Plain; diff --git a/crates/develop/src/settings.rs b/crates/develop/src/settings.rs index 739171abd93..12b276de655 100644 --- a/crates/develop/src/settings.rs +++ b/crates/develop/src/settings.rs @@ -84,17 +84,22 @@ 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 as clumps of irregular particles (a filtered Boolean model, resolution + /// independent) with Size Variation, Clumping, Color and Response; 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), } } } @@ -599,15 +604,44 @@ impl Default for Vignette { #[serde(default)] pub struct Grain { pub amount: f64, + /// Grain size, relative to the frame (0..100): mean radius 0.3–3 px on a 6000 px export + /// (≈ 1.8–18 µm on a 35 mm frame); finer grain is also stronger, as in Lightroom Classic. pub size: f64, + /// Camera Raw's Roughness: 0 = fine, round, regular grain; 100 = coarse, elongated, irregular + /// grains. Both ends are stronger than 50, as in Lightroom Classic. pub roughness: f64, /// Seed for the procedural grain (stable per photo). pub seed: u32, + /// Colour (chroma) grain, 0..100: independent dye-layer grain on top of the luminance grain. + /// This and the next three fields aren't written at their defaults, so settings saved before + /// they existed keep their JSON and `hash64` (and every cached preview stays valid). + #[serde(skip_serializing_if = "is_zero")] + pub color: f64, + /// Where grain is strongest: −100 shadows (4× the highlights) … 0 equal at every tone … + /// +100 highlights. + #[serde(skip_serializing_if = "is_zero")] + pub response: f64, + /// Spread of grain sizes, 0..100: 0 = all grains the mean size. + #[serde(skip_serializing_if = "Grain::is_default_size_variation")] + pub size_variation: f64, + /// Clumping, 0..100: 0 = single grains; 100 = clusters of several grains. + #[serde(skip_serializing_if = "Grain::is_default_clumping")] + pub clumping: f64, +} + +impl Grain { + fn is_default_size_variation(v: &f64) -> bool { + *v == Grain::default().size_variation + } + + fn is_default_clumping(v: &f64) -> bool { + *v == Grain::default().clumping + } } impl Default for Grain { fn default() -> Self { - Self { amount: 0.0, size: 25.0, roughness: 50.0, seed: 0 } + Self { amount: 0.0, size: 25.0, roughness: 50.0, seed: 0, color: 0.0, response: 0.0, size_variation: 40.0, clumping: 30.0 } } } diff --git a/crates/develop/src/tests_process.rs b/crates/develop/src/tests_process.rs index f89ebfa1154..3dc41975e58 100644 --- a/crates/develop/src/tests_process.rs +++ b/crates/develop/src/tests_process.rs @@ -160,3 +160,20 @@ fn the_process_is_not_an_edit_nor_part_of_copied_settings() { /// A process other than the latest: a newer LightCraft's number (no older one than V1 exists). const LATEST_PLUS_ONE: u32 = ProcessVersion::LATEST.0 + 1; + +#[test] +fn grain_saved_without_the_new_fields_loads_with_their_defaults() { + let s = DevelopSettings::from_json(&legacy()).unwrap(); + let d = Grain::default(); + assert_eq!((s.grain.amount, s.grain.size, s.grain.roughness, s.grain.seed), (20.0, 25.0, 50.0, 0)); + assert_eq!((s.grain.color, s.grain.response, s.grain.size_variation, s.grain.clumping), (d.color, d.response, d.size_variation, d.clumping)); + // saved again, the grain gains no field (the JSON and `hash64` stay as they were) … + assert_eq!(s.to_json()["grain"], legacy()["grain"]); + // … and the new fields are written once they leave their defaults, and read back + let mut g = s.clone(); + (g.grain.color, g.grain.response, g.grain.size_variation, g.grain.clumping) = (10.0, -20.0, 0.0, 70.0); + let v = g.to_json(); + assert_eq!(v["grain"]["size_variation"], json!(0.0)); + assert_eq!(DevelopSettings::from_json(&v).unwrap().grain, g.grain); + assert_ne!(g.hash64(), s.hash64()); +} diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs index d3e56f74914..e42cb925c0a 100644 --- a/crates/gpu/src/ctx.rs +++ b/crates/gpu/src/ctx.rs @@ -7,13 +7,26 @@ use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; /// parameter block `P` (binding 0), and its entry points. struct Module { src: &'static str, + /// Appended to `src` for the kernels built with the device (finish: film grain left out, see + /// [`FILM_GRAIN`]). + tail: &'static str, bindings: &'static [(&'static str, bool, &'static str)], entries: &'static [&'static str], } +/// The finish kernel built with the device draws no film grain (the particle model): FXC (DX12) +/// takes over a second to compile the grain, which every run, and every CLI call, paid at start-up. +/// The kernel with it, [`FILM_GRAIN`], is built on the first render that draws film grain, and a +/// render with film grain never runs the one without it (`render::finish_kernel`). +const FILM_GRAIN_OFF: &str = "\nfn film_grain(gx: f32, gy: f32, lum: f32) -> vec3 {\n return vec3(0.0, 0.0, 0.0);\n}\n"; +const FILM_GRAIN_ON: &str = "\nfn film_grain(gx: f32, gy: f32, lum: f32) -> vec3 {\n return grain_apply(gx, gy, lum);\n}\n"; +/// The finish kernel with film grain (entry `main` of the finish module, built on first use). +pub(crate) const FILM_GRAIN: &str = "main_grain"; + const MODULES: &[Module] = &[ Module { src: include_str!("wgsl/finish.wgsl"), + tail: FILM_GRAIN_OFF, bindings: &[ ("img", false, "f32"), ("log_l", false, "f32"), @@ -29,16 +42,19 @@ const MODULES: &[Module] = &[ }, Module { src: include_str!("wgsl/blur.wgsl"), + tail: "", bindings: &[("src", false, "f32"), ("dst", true, "f32")], entries: &["box_h", "box_v", "median_h", "median_v"], }, Module { src: include_str!("wgsl/resize.wgsl"), + tail: "", bindings: &[("src", false, "f32"), ("table", false, "u32"), ("dst", true, "f32")], entries: &["resize_h", "resize_v"], }, Module { src: include_str!("wgsl/map.wgsl"), + tail: "", bindings: &[("a", false, "f32"), ("b", false, "f32"), ("c", false, "f32"), ("dst", true, "f32")], entries: &[ "log_lum_k", @@ -59,16 +75,19 @@ const MODULES: &[Module] = &[ }, Module { src: include_str!("wgsl/mask.wgsl"), + tail: "", bindings: &[("img", false, "f32"), ("log_l", false, "f32"), ("aux", false, "f32"), ("c", true, "f32"), ("alpha", true, "f32")], entries: &["shape", "combine", "finalize"], }, Module { src: include_str!("wgsl/geom.wgsl"), + tail: "", bindings: &[("src", false, "f32"), ("dst", true, "f32"), ("coverage", false, "u32")], entries: &["orient", "sample_affine", "sample_warp"], }, ]; +#[derive(Clone)] struct Kernel { pipeline: wgpu::ComputePipeline, layout: wgpu::BindGroupLayout, @@ -332,6 +351,10 @@ pub struct Gpu { pub queue: wgpu::Queue, pub info: wgpu::AdapterInfo, kernels: HashMap<&'static str, Kernel>, + /// Kernels built on first use ([`FILM_GRAIN`]), or why one couldn't be (not tried again). + lazy: std::sync::Mutex>>, + /// The WGSL constants the kernels were built with (for the ones built later). + consts: String, dummy: wgpu::Buffer, /// Recycled buffers (see [`Buf`]). free: std::sync::Mutex>, @@ -341,7 +364,7 @@ pub struct Gpu { /// WGSL constants shared by every module (generated from the CPU pipeline's values). fn constants() -> String { - use lightcraft_pipeline::finish::{GRAIN_HASH, MASK_SUMS, MASK_TERMS, SRGB_LUT_N}; + use lightcraft_pipeline::finish::{GRAIN_HASH, MASK_SUMS, MASK_TERMS, SRGB_LUT_N, VALUE_GRAIN_HASH}; use lightcraft_pipeline::tone::{CHROMA_N, LUT_MAX_EV, LUT_MIN_EV, LUT_N}; let mut s = String::new(); let [to_lms, from_lms, to_lab, from_lab] = lightcraft_color::perceptual::oklab_matrices(); @@ -367,6 +390,21 @@ fn constants() -> String { for (i, h) in GRAIN_HASH.iter().enumerate() { s += &format!("const GRAIN_H{i}: u32 = {h}u;\n"); } + for (i, h) in VALUE_GRAIN_HASH.iter().enumerate() { + s += &format!("const GRAIN_VH{i}: u32 = {h}u;\n"); + } + { + use lightcraft_pipeline::grain::{CHANNEL_SALT, MAX_PER_CELL, MAX_REACH, MAX_SUB, P_MAX, P_MIN}; + s += &format!( + "const GRAIN_P_MIN: f32 = {P_MIN:?};\nconst GRAIN_P_MAX: f32 = {P_MAX:?};\nconst GRAIN_MAX_PER_CELL: u32 = {MAX_PER_CELL}u;\nconst GRAIN_MAX_SUB: u32 = {MAX_SUB}u;\nconst GRAIN_MAX_REACH: i32 = {MAX_REACH};\n" + ); + let phases: Vec = lightcraft_pipeline::grain::PHASES.iter().map(|p| format!("vec2({:?}, {:?})", p[0], p[1])).collect(); + // a private array: indexed at run time (a const array may not be, on every backend) + s += &format!("var GRAIN_PHASES: array, 16> = array, 16>({});\n", phases.join(", ")); + for (name, salt) in ["R", "G", "B"].iter().zip(CHANNEL_SALT) { + s += &format!("const GRAIN_SALT_{name}: u32 = {salt}u;\n"); + } + } for (name, idx) in crate::params::finish_fields() { s += &format!("const F_{name}: u32 = {idx}u;\n"); } @@ -374,6 +412,11 @@ fn constants() -> String { } fn module_source(m: &Module, consts: &str) -> String { + module_source_with(m, consts, m.tail) +} + +/// [`module_source`] with another `tail` (the film grain kernel's). +fn module_source_with(m: &Module, consts: &str, tail: &str) -> String { let mut s = String::from(consts); s += "@group(0) @binding(0) var P: array;\n"; for (i, (name, write, ty)) in m.bindings.iter().enumerate() { @@ -382,6 +425,7 @@ fn module_source(m: &Module, consts: &str) -> String { } s += include_str!("wgsl/common.wgsl"); s += m.src; + s += tail; s } @@ -450,7 +494,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, lazy: Default::default(), consts: constants(), dummy, free: Default::default(), max_buffer }) } /// A buffer of `len` 32-bit values with undefined contents (a recycled one when possible). @@ -662,10 +706,26 @@ impl Gpu { if failed() { return; // the render is redone on the CPU: don't spend the GPU on it } - let Some(k) = self.kernels.get(name) else { - // a kernel name typo: fail this render over to the CPU instead of crashing - fail(FailKind::Fatal, format!("unknown kernel {name}")); - return; + let built; + let k = match self.kernels.get(name) { + Some(k) => k, + None if name == FILM_GRAIN => match self.film_grain_kernel() { + Ok(k) => { + built = k; + &built + } + Err(e) => { + // the render is redone on the CPU, with its grain; the device and its other + // kernels stay in use + fail(FailKind::Kernel, e); + return; + } + }, + None => { + // a kernel name typo: fail this render over to the CPU instead of crashing + fail(FailKind::Fatal, format!("unknown kernel {name}")); + return; + } }; assert_eq!(bufs.len(), k.nbuf, "{name}: binding count"); let params = self.init_buffer(bytemuck::cast_slice(if p.is_empty() { &[0u32] } else { p }), wgpu::BufferUsages::STORAGE); @@ -681,6 +741,52 @@ impl Gpu { pass.dispatch_workgroups(groups[0], groups[1], groups[2]); } + /// The finish kernel with film grain ([`FILM_GRAIN`]), built on its first use (renders that + /// need it meanwhile wait for it; the others don't). A build that fails isn't tried again: film + /// grain renders on the CPU. + fn film_grain_kernel(&self) -> Result { + let mut lazy = self.lazy.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(k) = lazy.get(FILM_GRAIN) { + return k.clone(); + } + let built = self.build_film_grain(); + if let Err(e) = &built { + log::error!("gpu: {e}"); + } + lazy.insert(FILM_GRAIN, built.clone()); + built + } + + fn build_film_grain(&self) -> Result { + let (Some(m), Some(base)) = (MODULES.first(), self.kernels.get("main")) else { + return Err("film grain kernel: no finish kernel".into()); + }; + let t0 = std::time::Instant::now(); + let scopes = [self.device.push_error_scope(wgpu::ErrorFilter::Validation), self.device.push_error_scope(wgpu::ErrorFilter::Internal)]; + let src = module_source_with(m, &self.consts, FILM_GRAIN_ON); + let module = self.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(src.into()) }); + let pl = self.device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + bind_group_layouts: &[Some(&base.layout)], + immediate_size: 0, + }); + let pipeline = self.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some(FILM_GRAIN), + layout: Some(&pl), + module: &module, + entry_point: Some("main"), + compilation_options: Default::default(), + cache: None, + }); + let [validation, internal] = scopes; + let (internal, validation) = (pollster::block_on(internal.pop()), pollster::block_on(validation.pop())); + if let Some(e) = internal.or(validation) { + return Err(format!("{}: the film grain kernel failed to build ({e})", self.info.name)); + } + log::info!("gpu: film grain kernel built in {:.0} ms", t0.elapsed().as_secs_f64() * 1000.0); + Ok(Kernel { pipeline, layout: base.layout.clone(), nbuf: base.nbuf }) + } + /// Submit `enc`, then read back the first `len` 32-bit values of `src`. /// /// A failed readback (device lost, map error, timeout) fails the render ([`FailKind::Fatal`]) @@ -779,6 +885,9 @@ pub(crate) enum FailKind { OutOfMemory, /// The image came back entirely black: redone on the CPU in case the GPU dropped work. Blank, + /// A kernel built on first use ([`FILM_GRAIN`]) failed to build: the renders that need it are + /// drawn on the CPU, the others stay on the GPU. + Kernel, /// Device error or loss, readback failure, incomplete image: the GPU is not used again. Fatal, } @@ -887,6 +996,37 @@ pub fn groups1(n: usize) -> [u32; 3] { #[cfg(test)] mod tests { + /// Every WGSL module, with its constants filled in, parses and validates (no adapter needed, + /// so it runs where the GPU tests skip). + #[test] + fn shaders_parse_and_validate() { + let consts = super::constants(); + // every module as built with the device, and the finish kernel with film grain + let with_grain = super::MODULES.first().map(|m| super::module_source_with(m, &consts, super::FILM_GRAIN_ON)); + for src in super::MODULES.iter().map(|m| super::module_source(m, &consts)).chain(with_grain) { + let module = wgpu::naga::front::wgsl::parse_str(&src).unwrap_or_else(|e| panic!("{}", e.emit_to_string(&src))); + wgpu::naga::valid::Validator::new(wgpu::naga::valid::ValidationFlags::all(), wgpu::naga::valid::Capabilities::all()) + .validate(&module) + .unwrap_or_else(|e| panic!("{e:?}")); + } + } + + /// The finish kernel with film grain isn't built with the device (FXC on DX12 spent over a + /// second on it at every start-up, #1060): it is built on its first use, and kept. + #[test] + fn the_film_grain_kernel_is_built_on_first_use() { + let Some(shared) = crate::device() else { + lightcraft_testkit::skip!(Gpu, "no GPU device"); + return; + }; + let g = super::Gpu::new(wgpu::Backends::from(shared.info.backend)).expect("a second device on the same adapter"); + assert!(!g.kernels.contains_key(super::FILM_GRAIN), "not built with the device"); + assert!(g.lazy.lock().unwrap().is_empty()); + assert!(g.film_grain_kernel().is_ok(), "built on first use"); + assert_eq!(g.lazy.lock().unwrap().len(), 1); + assert!(g.film_grain_kernel().is_ok(), "and kept"); + } + /// Every kernel module, as it is handed to the device (the generated constants, the bindings, `common.wgsl`, the /// module), parses and validates without a GPU. #[test] @@ -1007,6 +1147,44 @@ mod tests { } } + /// A film grain kernel the adapter won't build (it is built on the first grain render) sends + /// the grain renders to the CPU and keeps the GPU for everything else: renders without grain, + /// and process V1's value-noise grain, which the kernel built with the device draws. + #[test] + fn a_film_grain_kernel_that_fails_to_build_keeps_the_gpu() { + if run_child("failed_film_grain_child").is_none() { + lightcraft_testkit::skip!(Gpu, "no GPU device"); + } + } + + #[test] + #[ignore = "run in its own process by a_film_grain_kernel_that_fails_to_build_keeps_the_gpu"] + fn failed_film_grain_child() { + use lightcraft_develop::{DevelopSettings, ProcessVersion}; + use lightcraft_pipeline::{RenderRequest, SourceInfo}; + let Some(g) = crate::device() else { + println!("CHILD: no GPU"); + return; + }; + g.lazy.lock().unwrap().insert(super::FILM_GRAIN, Err("simulated: the film grain kernel failed to build".into())); + let (w, h) = (256, 192); + let src = std::sync::Arc::new(lightcraft_raster::Rgb32f::from_fn(w, h, |x, y| [x as f32 / w as f32, y as f32 / h as f32, 0.4])); + let (info, req) = (SourceInfo::default(), RenderRequest::fit(w, h)); + let mut grain = DevelopSettings::default(); + grain.grain.amount = 50.0; + match crate::try_render(&src, &info, &grain, &req, None) { + Err(crate::Fallback::Failed(why)) => assert!(why.contains("film grain"), "{why}"), + other => panic!("a film grain render falls back to the CPU: {:?}", other.map(|_| ())), + } + assert!(crate::available(), "the GPU stays in use: {:?}", crate::unavailable_reason()); + assert!(crate::try_render(&src, &info, &DevelopSettings::default(), &req, None).is_ok(), "a render without grain"); + let v1 = DevelopSettings { process: ProcessVersion::V1, ..grain.clone() }; + assert!(crate::try_render(&src, &info, &v1, &req, None).is_ok(), "V1 grain (value noise)"); + assert!(matches!(crate::try_render(&src, &info, &grain, &req, None), Err(crate::Fallback::Failed(_))), "film grain again"); + assert!(crate::available()); + println!("CHILD: survived"); + } + #[test] #[ignore = "run in its own process by a_retired_but_live_device_is_still_polled"] fn retired_child() { diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 51a8aa45bc7..322441465a4 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -548,7 +548,7 @@ pub fn try_render( gpu.trim(0); format!("{what}: {}", f.reason) } - ctx::FailKind::Limit | ctx::FailKind::Blank => format!("{what}: {}", f.reason), + ctx::FailKind::Limit | ctx::FailKind::Blank | ctx::FailKind::Kernel => format!("{what}: {}", f.reason), }; log::warn!("gpu: rendering on the CPU instead: {reason}"); if render::profiling() { diff --git a/crates/gpu/src/params.rs b/crates/gpu/src/params.rs index b46b7cc1acc..53a29b666f0 100644 --- a/crates/gpu/src/params.rs +++ b/crates/gpu/src/params.rs @@ -3,7 +3,8 @@ 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}; +use lightcraft_pipeline::grain::GrainParams; /// Entries per tone-curve table (`lightcraft_pipeline::finish` builds them at this size). pub const CURVE_N: u32 = 1024; @@ -60,10 +61,44 @@ 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 = particles (V3) + ("GRAIN_MODEL", 1), ("GRAIN_AMT", 1), ("GRAIN_SC", 1), ("GRAIN_ROUGH", 1), + ("GRAIN_AMP", 1), + ("GRAIN_INV_R", 1), + ("GRAIN_S", 1), + ("GRAIN_INV_S", 1), + ("GRAIN_SPREAD", 1), + ("GRAIN_ASPECT", 1), + ("GRAIN_LUMP", 1), + ("GRAIN_CLUMP_E", 1), + ("GRAIN_CLUMP_D", 1), + ("GRAIN_AREA", 1), + ("GRAIN_SUPPORT", 1), + ("GRAIN_SUB_REACH", 1), + ("GRAIN_CELL", 1), + ("GRAIN_KAPPA", 1), + ("GRAIN_K_HH", 1), + ("GRAIN_K_AH", 1), + ("GRAIN_AREA_REF", 1), + ("GRAIN_KAPPA_REF", 1), + ("GRAIN_K_HH_REF", 1), + ("GRAIN_K_AH_REF", 1), + ("GRAIN_HALO", 1), + ("GRAIN_HALO_IN", 1), + ("GRAIN_HALO_OUT", 1), + ("GRAIN_HALO_MEAN", 1), + ("GRAIN_TILT", 1), + ("GRAIN_WF", 1), + ("GRAIN_WN", 1), + ("GRAIN_NOISE_E", 1), + ("GRAIN_NOISE_N", 1), + ("GRAIN_COLOR", 1), + ("GRAIN_GAMMA", 1), ("GRAIN_SEED", 1), + ("GRAIN_PPL", 1), ("GRAIN_AFF", 6), ("REFINE_SAT", 1), ("CALIB", 1), @@ -248,12 +283,21 @@ 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::Particles(g) => { + p.u("GRAIN_MODEL", 1); + particle_grain(&mut p, &g); + } + } 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); @@ -261,3 +305,40 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr } (p.0, aux) } + +/// The particle grain's fields (process V3 and later). +fn particle_grain(p: &mut Block, g: &GrainParams) { + p.f("GRAIN_AMP", g.amp); + p.f("GRAIN_INV_R", g.inv_r); + p.f("GRAIN_S", g.s); + p.f("GRAIN_INV_S", g.inv_s); + p.f("GRAIN_SPREAD", g.spread); + p.f("GRAIN_ASPECT", g.aspect); + p.f("GRAIN_LUMP", g.lump); + p.f("GRAIN_CLUMP_E", g.clump_extra); + p.f("GRAIN_CLUMP_D", g.clump_d); + p.f("GRAIN_AREA", g.area); + p.f("GRAIN_SUPPORT", g.support); + p.f("GRAIN_SUB_REACH", g.sub_reach); + p.f("GRAIN_CELL", g.cell); + p.f("GRAIN_KAPPA", g.kappa); + p.f("GRAIN_K_HH", g.k_hh); + p.f("GRAIN_K_AH", g.k_ah); + p.f("GRAIN_AREA_REF", g.area_ref); + p.f("GRAIN_KAPPA_REF", g.kappa_ref); + p.f("GRAIN_K_HH_REF", g.k_hh_ref); + p.f("GRAIN_K_AH_REF", g.k_ah_ref); + p.f("GRAIN_HALO", g.halo); + p.f("GRAIN_HALO_IN", g.halo_in); + p.f("GRAIN_HALO_OUT", g.halo_out); + p.f("GRAIN_HALO_MEAN", g.halo_mean); + p.f("GRAIN_TILT", g.tilt); + p.f("GRAIN_WF", g.w_field); + p.f("GRAIN_WN", g.w_noise); + p.f("GRAIN_NOISE_E", g.noise_e); + p.f("GRAIN_NOISE_N", g.noise_n); + p.f("GRAIN_COLOR", g.color); + p.f("GRAIN_GAMMA", g.gamma); + p.u("GRAIN_SEED", g.seed); + p.f("GRAIN_PPL", g.px_per_long); +} diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs index 9d6172d9c36..27efb476d0c 100644 --- a/crates/gpu/src/render.rs +++ b/crates/gpu/src/render.rs @@ -707,10 +707,11 @@ pub fn render( let rows = (BAND_PIXELS / w.max(1) / 16 * 16).max(16); // whole workgroups: bands never overlap let y0_at = crate::params::index("Y0").unwrap_or(0); let mut p = p; + let kernel = finish_kernel(&fp); for y0 in (0..h).step_by(rows).filter(|_| fault != Some(crate::Fault::DropWork)) { p[y0_at] = y0 as u32; cx.run( - "main", + kernel, &p, &[ Some(&lin), @@ -1126,6 +1127,12 @@ fn masks(cx: &mut Cx<'_>, lin: &Buf, prep: &Prep, plan: &Plan<'_>, host: &mut Ho (Some(alpha), terms) } +/// The finish kernel for `fp`: the one with film grain ([`crate::ctx::FILM_GRAIN`], built on its +/// first use) when the particle grain is drawn, else the one built with the device. +pub(crate) fn finish_kernel(fp: &lightcraft_pipeline::finish::FinishParams) -> &'static str { + if matches!(fp.grain, Some(lightcraft_pipeline::finish::GrainModel::Particles(_))) { crate::ctx::FILM_GRAIN } else { "main" } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/gpu/src/wgsl/finish.wgsl b/crates/gpu/src/wgsl/finish.wgsl index 767ff44c99e..e184634c336 100644 --- a/crates/gpu/src/wgsl/finish.wgsl +++ b/crates/gpu/src/wgsl/finish.wgsl @@ -208,15 +208,17 @@ fn refine_saturation(before: vec3, after: vec3, refine: f32) -> vec3 f32 { - var v = (bitcast(i) * GRAIN_H0) ^ (bitcast(j) * GRAIN_H1) ^ (seed * GRAIN_H2); +// --- value-noise grain of processes V1 and V2 (frozen): `value_grain_noise` in +// `lightcraft_pipeline::finish` +fn vghash(i: i32, j: i32, seed: u32) -> f32 { + var v = (bitcast(i) * GRAIN_VH0) ^ (bitcast(j) * GRAIN_VH1) ^ (seed * GRAIN_VH2); v ^= v >> 13u; - v = v * GRAIN_H3; + v = v * GRAIN_VH3; v ^= v >> 15u; return f32(v & 0xffffu) / 32768.0 - 1.0; } -fn grain_noise(x: f32, y: f32, seed: u32) -> f32 { +fn value_grain_noise(x: f32, y: f32, seed: u32) -> f32 { let x0 = floor(x); let y0 = floor(y); let fx = x - x0; @@ -225,11 +227,321 @@ fn grain_noise(x: f32, y: f32, seed: u32) -> f32 { let j = i32(y0); let u = fx * fx * (3.0 - 2.0 * fx); let v = fy * fy * (3.0 - 2.0 * fy); - let a = ghash(i, j, seed) + (ghash(i + 1, j, seed) - ghash(i, j, seed)) * u; - let b = ghash(i, j + 1, seed) + (ghash(i + 1, j + 1, seed) - ghash(i, j + 1, seed)) * u; + let a = vghash(i, j, seed) + (vghash(i + 1, j, seed) - vghash(i, j, seed)) * u; + let b = vghash(i, j + 1, seed) + (vghash(i + 1, j + 1, seed) - vghash(i, j + 1, seed)) * u; return a + (b - a) * v; } +fn value_grain(gx: f32, gy: f32, lum: f32) -> f32 { + let sc = pf(F_GRAIN_SC); + let rough = pf(F_GRAIN_ROUGH); + let seed = pu(F_GRAIN_SEED); + var g = value_grain_noise(gx * sc, gy * sc, seed); + g = g * (1.0 - rough * 0.5) + value_grain_noise(gx * sc * 2.3, gy * sc * 2.3, seed ^ 0x55u) * rough * 0.7; + return pf(F_GRAIN_AMT) * g * (0.35 + 2.6 * lum * (1.0 - lum)); +} + +// --- film grain: a port of `lightcraft_pipeline::grain` (keep in step with it) +fn gpcg(v: u32) -> u32 { + let s = v * 747796405u + 2891336453u; + let w = ((s >> ((s >> 28u) + 4u)) ^ s) * 277803737u; + return (w >> 22u) ^ w; +} + +fn gcell(i: i32, j: i32, salt: u32) -> u32 { + return gpcg((bitcast(i) * GRAIN_H0) ^ (bitcast(j) * GRAIN_H1) ^ salt); +} + +fn gsub_hash(h: u32, j: u32) -> u32 { + return gpcg(h ^ ((j + 1u) * 0x9e3779b9u)); +} + +fn gunit(v: u32) -> f32 { + return (f32(v >> 8u) + 0.5) * (1.0 / 16777216.0); +} + +fn gunit16(v: u32) -> f32 { + return (f32(v & 0xffffu) + 0.5) * (1.0 / 65536.0); +} + +fn gunit8(v: u32) -> f32 { + return (f32(v & 0xffu) + 0.5) * (1.0 / 256.0); +} + +fn gunit4(v: u32) -> f32 { + return (f32(v & 15u) + 0.5) * (1.0 / 16.0); +} + +// `coverage_std_at`: the standard deviation of the field (coverage less halo) at coverage `p` +fn grain_std_at(p: f32, area: f32, kappa: f32, k_hh: f32, k_ah: f32) -> f32 { + let c = pf(F_GRAIN_CELL); + let q = 1.0 - p; + let t = -log(q) / area * c * c; + let fw = min(t, 1.0); + let mu = -log(q) * (1.0 - fw / (6.0 * max(t, 1e-12))); + return sqrt(max(q * q * (exp(kappa * mu) - 1.0 + mu * (k_hh - 2.0 * k_ah)), 0.0)); +} + +fn grain_per_cell(p: f32) -> f32 { + let c = pf(F_GRAIN_CELL); + return -log(1.0 - p) / pf(F_GRAIN_AREA) * c * c; +} + +fn grain_std(p: f32) -> f32 { + return grain_std_at(p, pf(F_GRAIN_AREA), pf(F_GRAIN_KAPPA), pf(F_GRAIN_K_HH), pf(F_GRAIN_K_AH)); +} + +fn grain_sub_count(h: u32) -> u32 { + let e = pf(F_GRAIN_CLUMP_E); + if (e <= 0.0) { + return 1u; + } + let extra = floor(gunit(gpcg(h ^ GRAIN_H3)) * (2.0 * e + 1.0)); + return 1u + min(u32(max(extra, 0.0)), GRAIN_MAX_SUB - 1u); +} + +fn grain_sub_offset(hj: u32) -> vec2 { + let o = gpcg(hj ^ GRAIN_H0); + let d = pf(F_GRAIN_CLUMP_D); + return vec2(d * (gunit8(o) + gunit8(o >> 8u) - 1.0), d * (gunit8(o >> 16u) + gunit8(o >> 24u) - 1.0)); +} + +// radius and density of grain `hj` +fn grain_sub_size(hj: u32) -> vec2 { + let rad = gpcg(hj ^ GRAIN_H3); + let z = 2.0 * (gunit8(rad) + gunit8(rad >> 8u) + gunit8(rad >> 16u)) - 3.0; + return vec2(exp(pf(F_GRAIN_SPREAD) * z), 0.25 + 0.75 * gunit8(rad >> 24u)); +} + +// the halo of a clump of weight `w` at squared distance `d2` from its centre (`clump_halo`) +fn grain_clump_halo(w: f32, d2: f32) -> f32 { + let u = d2 * pf(F_GRAIN_HALO_OUT); + if (u >= 1.0 || w == 0.0) { + return 0.0; + } + let v = d2 * pf(F_GRAIN_HALO_IN); + var inner = 0.0; + if (v < 1.0) { + inner = (1.0 - v) * (1.0 - v); + } + return pf(F_GRAIN_HALO) * w * ((1.0 - u) * (1.0 - u) - inner); +} + +// coverage of grain `hj` at offset (dx, dy) from its centre: radius, density, elongation, +// orientation, lobed outline, soft edge (0 beyond its reach) +fn grain_sub_cover(hj: u32, dx: f32, dy: f32, d2: f32) -> f32 { + let s = pf(F_GRAIN_S); + let lump = pf(F_GRAIN_LUMP); + let ro = grain_sub_size(hj); + let r0 = ro.x; + let o = ro.y; + let shp = gpcg(hj ^ GRAIN_H1); + let a = 2.0 * gunit8(shp) - 1.0; + let b = 2.0 * gunit8(shp >> 8u) - 1.0; + let n = sqrt(a * a + b * b); + var ux = 1.0; + var uy = 0.0; + if (n > 1e-3) { + ux = a / n; + uy = b / n; + } + let asp = 1.0 + pf(F_GRAIN_ASPECT) * gunit4(shp >> 16u); + let rr = r0 * sqrt(asp) * (1.0 + lump); + let reach = sqrt(rr * rr + s * s) + s; + if (d2 >= reach * reach) { + return 0.0; + } + let d = sqrt(d2); + var r = r0; + if (d > 1e-6) { + let inv_d = 1.0 / d; + let c = dx * inv_d; + let sn = dy * inv_d; + if (asp > 1.0) { + let cu = c * ux + sn * uy; + let cw = sn * ux - c * uy; + r = r / sqrt(cu * cu * (1.0 / asp) + cw * cw * asp); + } + if (lump > 0.0) { + let m = 0.5 + f32((shp >> 28u) & 15u) * (1.0 / 30.0); + let p2 = GRAIN_PHASES[(shp >> 20u) & 15u]; + let p3 = GRAIN_PHASES[(shp >> 24u) & 15u]; + let c2 = c * c - sn * sn; + let s2 = 2.0 * c * sn; + let c3 = c * (4.0 * c * c - 3.0); + let s3 = sn * (3.0 - 4.0 * sn * sn); + r = r * (1.0 + lump * (0.6 * m * (p2.x * c2 + p2.y * s2) + 0.4 * m * (p3.x * c3 + p3.y * s3))); + } + } + return o * grain_profile(d, r, s, pf(F_GRAIN_INV_S)); +} + +// a disc of radius `r` softened by the edge width `s`, at distance `d` from its centre +fn grain_profile(d: f32, r: f32, s: f32, inv_s: f32) -> f32 { + let rho2 = r * r + s * s; + let tau = (d - sqrt(rho2)) * inv_s; + if (tau >= 1.0) { + return 0.0; + } + var prof = 1.0; + if (tau > -1.0) { + prof = (1.0 - tau) * (1.0 - tau) * (2.0 + tau) * 0.25; + } + return r * r / (rho2 + s * s * 0.2) * prof; +} + +// coverage (the union of its grains) and halo (a ring around its centre) of clump `h` at offset +// (dx, dy) from its centre +fn grain_clump_cover(h: u32, dx: f32, dy: f32) -> vec2 { + let sr = pf(F_GRAIN_SUB_REACH); + let count = grain_sub_count(h); + var t = 1.0; + var w = 0.0; + let has_halo = pf(F_GRAIN_HALO) > 0.0; + for (var j = 0u; j < count; j++) { + let hj = gsub_hash(h, j); + if (has_halo) { + let ro = grain_sub_size(hj); + w += ro.y * ro.x * ro.x; + } + let off = grain_sub_offset(hj); + let ex = dx - off.x; + let ey = dy - off.y; + let d2 = ex * ex + ey * ey; + if (d2 >= sr * sr) { + continue; + } + t *= 1.0 - grain_sub_cover(hj, ex, ey, d2); + } + return vec2(1.0 - t, grain_clump_halo(w, dx * dx + dy * dy)); +} + +fn grain_field(x: f32, y: f32, p: f32, seed: u32) -> f32 { + let t = grain_per_cell(p); + let fw = max(min(t, 1.0), 1e-6); + let end = t + 0.5 * fw; + let r = pf(F_GRAIN_SUPPORT); + let c = pf(F_GRAIN_CELL); + // the cells within reach, as a start and a bounded count (never a loop up to i32::MAX) + let fi0 = floor((x - r) / c); + let fj0 = floor((y - r) / c); + let i0 = i32(clamp(fi0, -2.0e9, 2.0e9)); + let j0 = i32(clamp(fj0, -2.0e9, 2.0e9)); + let ni = min(u32(max(floor((x + r) / c) - fi0, 0.0)), u32(GRAIN_MAX_REACH)); + let nj = min(u32(max(floor((y + r) / c) - fj0, 0.0)), u32(GRAIN_MAX_REACH)); + let e_end = exp(-end); + let e_full = exp(fw - end); + let salt = gpcg(seed); + var keep = 1.0; + var hs = 0.0; + for (var dj = 0u; dj <= nj; dj++) { + let j = j0 + i32(dj); + let dy = y - clamp(y, f32(j) * c, (f32(j) + 1.0) * c); + for (var di = 0u; di <= ni; di++) { + let i = i0 + i32(di); + let dx = x - clamp(x, f32(i) * c, (f32(i) + 1.0) * c); + if (dx * dx + dy * dy >= r * r) { + continue; + } + let base = gcell(i, j, salt); + var prod = 1.0; + for (var k = 0u; k < GRAIN_MAX_PER_CELL; k++) { + let h = gpcg(base + k); + prod *= gunit(h); + if (prod <= e_end) { + break; + } + let pos = gpcg(h ^ GRAIN_H2); + let cx = (f32(i) + gunit16(pos)) * c; + let cy = (f32(j) + gunit16(pos >> 16u)) * c; + let ex = x - cx; + let ey = y - cy; + if (ex * ex + ey * ey >= r * r) { + continue; + } + let ah = grain_clump_cover(h, ex, ey); + if (ah.x == 0.0 && ah.y == 0.0) { + continue; + } + var f = 1.0; + if (prod < e_full) { + f = clamp((end + log(prod)) / fw, 0.0, 1.0); + } + keep *= 1.0 - f * ah.x; + hs += f * ah.y; + } + } + } + // less the halo's deviation from its mean, on the light the grains let through + var halo_mean = 0.0; + if (pf(F_GRAIN_HALO) > 0.0) { + halo_mean = -log(1.0 - p) * pf(F_GRAIN_HALO_MEAN); + } + return 1.0 - keep - (1.0 - p) * (hs - halo_mean); +} + +fn grain_gauss(ix: i32, iy: i32, seed: u32) -> f32 { + let h = gcell(ix, iy, gpcg(seed ^ 0x5bd1e995u)); + let sum = (h & 0xffu) + ((h >> 8u) & 0xffu) + ((h >> 16u) & 0xffu) + (h >> 24u); + return ((f32(sum) + 2.0) * (1.0 / 256.0) - 2.0) * 1.7320508; +} + +fn grain_layer(gx: f32, gy: f32, p: f32, seed: u32) -> f32 { + var d = 0.0; + let wf = pf(F_GRAIN_WF); + let wn = pf(F_GRAIN_WN); + if (wf > 0.0) { + let ir = pf(F_GRAIN_INV_R); + d += wf * (p - grain_field(gx * ir, gy * ir, p, seed)); + } + if (wn > 0.0) { + let ppl = pf(F_GRAIN_PPL); + let ix = i32(floor(gx * ppl)); + let iy = i32(floor(gy * ppl)); + var n = grain_gauss(ix, iy, seed); + let e = pf(F_GRAIN_NOISE_E); + if (e != 0.0) { + // correlated with its four neighbours (`GrainParams::noise`) + let around = grain_gauss(ix - 1, iy, seed) + grain_gauss(ix + 1, iy, seed) + grain_gauss(ix, iy - 1, seed) + grain_gauss(ix, iy + 1, seed); + n = (n - e * around) * pf(F_GRAIN_NOISE_N); + } + d -= wn * grain_std(p) * n; + } + return d; +} + +fn grain_apply(gx: f32, gy: f32, lum: f32) -> vec3 { + let l = clamp(lum, 0.0, 1.0); + let gamma = pf(F_GRAIN_GAMMA); + var shade = max(1.0 - l, 1e-7); + if (gamma != 1.0) { + shade = pow(shade, gamma); + } + let p = GRAIN_P_MIN + (GRAIN_P_MAX - GRAIN_P_MIN) * shade; + let seed = pu(F_GRAIN_SEED); + // equally strong at every tone (at the reference resolution), tilted by the response + let tilt = pf(F_GRAIN_TILT); + var tw = 1.0; + if (tilt != 0.0) { + tw = exp(tilt * (l - 0.5)); + } + let sd_ref = grain_std_at(p, pf(F_GRAIN_AREA_REF), pf(F_GRAIN_KAPPA_REF), pf(F_GRAIN_K_HH_REF), pf(F_GRAIN_K_AH_REF)); + let amp = pf(F_GRAIN_AMP) * tw / max(sd_ref, 1e-4); + let color = pf(F_GRAIN_COLOR); + if (color <= 0.0) { + let lv = amp * grain_layer(gx, gy, p, seed); + return vec3(lv, lv, lv); + } + // one shared layer and a dye layer per channel: √(1 − c)·mono + √c·dye + let wm = sqrt(max(1.0 - color, 0.0)); + let wc = sqrt(color); + let m = wm * amp * grain_layer(gx, gy, p, seed); + let rr = wc * amp * grain_layer(gx, gy, p, seed ^ GRAIN_SALT_R); + let gg = wc * amp * grain_layer(gx, gy, p, seed ^ GRAIN_SALT_G); + let bb = wc * amp * grain_layer(gx, gy, p, seed ^ GRAIN_SALT_B); + return vec3(m + rr, m + gg, m + bb); +} + fn enc8(v: f32) -> u32 { return u32(clamp(v, 0.0, 1.0) * 255.0 + 0.5); } @@ -549,14 +861,13 @@ 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) == 0u) { + e = e + value_grain(gx, gy, lum); + } else { + // `grain_apply` in the kernel built with film grain (`ctx::FILM_GRAIN`) + e = e + film_grain(gx, gy, lum); + } } if (warn == 1u) { e = vec3(1.0, 0.0, 0.0); diff --git a/crates/gpu/tests/it/equivalence.rs b/crates/gpu/tests/it/equivalence.rs index 7432ebb7c8a..8d84691f032 100644 --- a/crates/gpu/tests/it/equivalence.rs +++ b/crates/gpu/tests/it/equivalence.rs @@ -229,6 +229,23 @@ fn cases() -> Vec<(&'static str, Edit)> { s.grain.size = 40.0; s.grain.roughness = 60.0; }), + // processes V1 and V2 keep their value-noise grain + ("grain (V1 value noise)", |s| { + s.process = lightcraft_develop::ProcessVersion::V1; + s.grain.amount = 50.0; + s.grain.size = 40.0; + s.grain.roughness = 60.0; + s.grain.seed = 7; + }), + // coarse grain: explicit Boolean-model grains even at this size, colour layers, response + ("grain (coarse, colour)", |s| { + s.grain.amount = 80.0; + s.grain.size = 90.0; + s.grain.roughness = 100.0; + s.grain.color = 60.0; + s.grain.response = -40.0; + s.grain.seed = 77; + }), ("dehaze -", |s| s.effects.dehaze = -50.0), ("dehaze +", |s| s.effects.dehaze = 60.0), ("clarity/texture -", |s| { @@ -646,7 +663,7 @@ fn highlights_shadows_base_matches_on_every_process() { }]; check(&format!("{p:?} local highlights {w}"), &src, &raw, &s, &req); } - for p in [Process::V1, Process::V2, Process::V1, Process::V2] { + for p in [Process::V1, Process::V2, Process::V3, Process::V1, Process::V2, Process::V3] { let mut s = DevelopSettings { process: p.version(), ..DevelopSettings::default() }; s.light.highlights = -100.0; let warm = lightcraft_gpu::render(&src, &raw, &s, &req, Some(&cache)).expect("gpu"); diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs index aa194252e97..0eb27a96db4 100644 --- a/crates/pipeline/src/finish.rs +++ b/crates/pipeline/src/finish.rs @@ -82,11 +82,41 @@ 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 vignette on display-linear colour `d` at frame position (`u`, `v`) in −1..1 of the whole +/// output frame (`aspect` = its width / height). +fn vignette_pixel(v: &Vig, d: [f32; 3], u: f32, vv: f32, aspect: f32, hdr: bool) -> [f32; 3] { + let sx = 1.0 + (aspect - 1.0) * v.aspect_mix; + let sy = 1.0 + (1.0 / aspect - 1.0) * v.aspect_mix; + let (ax, ay) = ((u * sx.max(1.0) / sx.max(sy)).abs(), (vv * sy.max(1.0) / sx.max(sy)).abs()); + let dist = (ax.powf(v.power) + ay.powf(v.power)).powf(1.0 / v.power); + let t = smooth(v.start, v.start + v.width, dist); + if t <= 0.0 { + return d; + } + if v.amount >= 0.0 { + // lighten towards SDR white; in HDR never pull highlights down to it + return if hdr { d.map(|c| c + (1.0 - c).max(0.0) * v.amount * t * 0.85) } else { d.map(|c| c + (1.0 - c) * v.amount * t * 0.85) }; + } + if v.style == VignetteStyle::PaintOverlay { + return d.map(|c| c * (1.0 - (-v.amount) * t) + 0.0); + } + let mut f = 1.0 + v.amount * t; + if v.style == VignetteStyle::HighlightPriority { + let lum = luminance_2020(d).clamp(0.0, 1.0); + f += (1.0 - f) * v.highlights * smooth(0.4, 1.0, lum); + } + d.map(|c| c * f) +} + +pub use crate::grain::GRAIN_HASH; + +/// Hash constants of [`value_grain_noise`], the grain of processes V1 and V2 (shared with the GPU +/// kernel). +pub const VALUE_GRAIN_HASH: [u32; 4] = [0x8da6_b343, 0xd816_3841, 0xcb1a_b31f, 0x5bd1_e995]; +/// Value noise of the V1/V2 grain. Frozen: photos on those processes render with it. #[inline] -fn grain_noise(x: f32, y: f32, seed: u32) -> f32 { +fn value_grain_noise(x: f32, y: f32, seed: u32) -> f32 { // A degenerate frame (zero-width crop) maps pixels to NaN/inf coordinates: no grain there. if !x.is_finite() || !y.is_finite() { return 0.0; @@ -94,9 +124,10 @@ fn grain_noise(x: f32, y: f32, seed: u32) -> f32 { let (x0, y0) = (x.floor(), y.floor()); let (fx, fy) = (x - x0, y - y0); let h = |i: i32, j: i32| { - let mut v = (i as u32).wrapping_mul(GRAIN_HASH[0]) ^ (j as u32).wrapping_mul(GRAIN_HASH[1]) ^ seed.wrapping_mul(GRAIN_HASH[2]); + let mut v = + (i as u32).wrapping_mul(VALUE_GRAIN_HASH[0]) ^ (j as u32).wrapping_mul(VALUE_GRAIN_HASH[1]) ^ seed.wrapping_mul(VALUE_GRAIN_HASH[2]); v ^= v >> 13; - v = v.wrapping_mul(GRAIN_HASH[3]); + v = v.wrapping_mul(VALUE_GRAIN_HASH[3]); v ^= v >> 15; (v & 0xffff) as f32 / 32768.0 - 1.0 }; @@ -107,6 +138,48 @@ fn grain_noise(x: f32, y: f32, seed: u32) -> f32 { a + (b - a) * v } +/// The grain of processes V1 and V2: two octaves of value noise (frozen, see +/// `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, +} + +impl ValueGrain { + fn new(g: &lightcraft_develop::Grain, px_per_long: f64) -> Option { + (g.amount > 0.0).then(|| { + let cell = (0.0006 + (g.size / 100.0) as f32 * 0.0024) * px_per_long as f32; + 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 } + }) + } +} + +/// A render's film grain. Which model it is follows the photo's process: changing it would change +/// how existing photos look, so the particle model came with a new process. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum GrainModel { + /// V1 and V2: value noise. + Value(ValueGrain), + /// V3 and later: clumps of particles ([`crate::grain`]). + Particles(crate::grain::GrainParams), +} + +impl GrainModel { + /// The grain `s` renders with at `px_per_long` output pixels per long edge (`None`: no grain). + pub fn new(s: &DevelopSettings, px_per_long: f64) -> Option { + match s.process.process() { + Process::V1 | Process::V2 => ValueGrain::new(&s.grain, px_per_long).map(GrainModel::Value), + Process::V3 => crate::grain::GrainParams::new(&s.grain, px_per_long).map(GrainModel::Particles), + } + } +} + /// Number of per-mask terms in [`mask_terms`]. pub const MASK_TERMS: usize = 21; @@ -183,8 +256,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 +302,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 +362,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), @@ -389,8 +459,13 @@ pub(crate) fn finish_with( let peak = fp.peak; let hdr = peak > 1.0; let mut out = vec![T::default(); w * h]; - for_rows(&mut out, w, |y, row| { - for (x, px) in row.iter_mut().enumerate() { + // bands of rows: grain splats each grain once per band (see `GrainParams::apply_band`) + const BAND: usize = 8; + for_rows(&mut out, w * BAND, |band, rows| { + // display-encoded colour and gamut-warning overlay per pixel, before grain and LUT + let mut enc: Vec<([f32; 3], Option<[f32; 3]>)> = Vec::with_capacity(rows.len()); + for q in 0..rows.len() { + let (x, y) = (q % w, band * BAND + q / w); let i = y * w + x; let raw = p.img.data[i]; let local = pixel_local_terms(p, &terms, i); @@ -439,30 +514,7 @@ pub(crate) fn finish_with( if let Some(v) = vig { let u = (vx + x as f32 + 0.5) / vw * 2.0 - 1.0; let vv = (vy + y as f32 + 0.5) / vh * 2.0 - 1.0; - let sx = 1.0 + (aspect - 1.0) * v.aspect_mix; - let sy = 1.0 + (1.0 / aspect - 1.0) * v.aspect_mix; - let (ax, ay) = ((u * sx.max(1.0) / sx.max(sy)).abs(), (vv * sy.max(1.0) / sx.max(sy)).abs()); - let dist = (ax.powf(v.power) + ay.powf(v.power)).powf(1.0 / v.power); - let t = smooth(v.start, v.start + v.width, dist); - if t > 0.0 { - let lum = luminance_2020(d).clamp(0.0, 1.0); - if v.amount < 0.0 { - let mut f = 1.0 + v.amount * t; - if v.style == VignetteStyle::HighlightPriority { - f += (1.0 - f) * v.highlights * smooth(0.4, 1.0, lum); - } - if v.style == VignetteStyle::PaintOverlay { - d = d.map(|c| c * (1.0 - (-v.amount) * t) + 0.0); - } else { - d = d.map(|c| c * f); - } - } else if hdr { - // lighten towards SDR white; never pull HDR highlights down to it - d = d.map(|c| c + (1.0 - c).max(0.0) * v.amount * t * 0.85); - } else { - d = d.map(|c| c + (1.0 - c) * v.amount * t * 0.85); - } - } + d = vignette_pixel(v, d, u, vv, aspect, hdr); } // --- gamut map to the output space (desaturate towards luminance until in range); @@ -521,21 +573,39 @@ pub(crate) fn finish_with( e = refine_saturation(e0, e, fp.refine_sat); } } - if let Some((amt, cell, rough, seed)) = *grain { + if let Some(GrainModel::Value(g)) = *grain { + // 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 / 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 sc = fp.px_per_long as f32 / g.cell; + let mut v = value_grain_noise(gx * sc, gy * sc, g.seed); + v = v * (1.0 - g.rough * 0.5) + value_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 = amt * g * (0.35 + 2.6 * lum * (1.0 - lum)); + let k = g.amt * v * (0.35 + 2.6 * lum * (1.0 - lum)); if k.is_finite() { e = e.map(|v| v + k); } } + enc.push((e, warn)); + } + if let Some(GrainModel::Particles(gp)) = grain { + let (mut gx, mut gy) = (Vec::with_capacity(enc.len()), Vec::with_capacity(enc.len())); + for q in 0..enc.len() { + let (x, y) = (q % w, band * BAND + q / w); + let n = out_to_norm.apply(Point::new(x as f64 + 0.5, y as f64 + 0.5)); + gx.push((n.x * fp.ow / long) as f32); + gy.push((n.y * fp.oh / long) as f32); + } + let mut es: Vec<[f32; 3]> = enc.iter().map(|q| q.0).collect(); + gp.apply_band(&gx, &gy, w, &mut es); + for (q, e) in enc.iter_mut().zip(es) { + q.0 = e; + } + } + for (px, (e, warn)) in rows.iter_mut().zip(enc) { let e = match &p_lut { Some((l, k)) if hdr => { // the LUT sees SDR values; the part above SDR white is carried over @@ -790,7 +860,7 @@ mod tests { #[test] fn grain_noise_is_finite_for_degenerate_coordinates() { for (x, y) in [(f32::NAN, 1.0), (1.0, f32::INFINITY), (f32::NEG_INFINITY, f32::NAN)] { - assert_eq!(grain_noise(x, y, 7), 0.0); + assert_eq!(value_grain_noise(x, y, 7), 0.0); } } diff --git a/crates/pipeline/src/grain.rs b/crates/pipeline/src/grain.rs new file mode 100644 index 00000000000..39546eb95e1 --- /dev/null +++ b/crates/pipeline/src/grain.rs @@ -0,0 +1,1804 @@ +//! Film grain: particles rendered on the spot, a stochastic Boolean model filtered by the output +//! pixel. +//! +//! Implemented from the published model of Newson, Delon & Galerne, "Realistic Film Grain +//! Rendering" (IPOL 2017), extended to clumps of irregular grains: +//! +//! - **Particles.** A *clump* is one to eleven grains around a centre; the clump centres form a +//! Poisson process. Each grain has its own size (log-normal spread: Size Variation), shape (an +//! ellipse of random orientation and elongation with an irregular, lobed outline: Shape), +//! optical density and position in the clump (Clumping). Every value comes from hashes of the +//! seed and the grain's cell, so a seed is a pattern and the same grains are drawn whatever the +//! render size or region. +//! - **Density follows tone.** The clump density is set so that a point is covered with the +//! expected coverage `p` of its tone: `λ·E[∫a_clump] = −ln(1 − p)`. +//! - **Exact statistics.** Each grain is softened by the output pixel's footprint, and the union +//! is evaluated exactly as `1 − Π(1 − aᵢ)`. The Poisson generating functional then gives the +//! mean (`p` at any scale) and the variance `(1 − p)²·(exp(λ·E[∫a_clump²]) − 1)` in closed form. +//! The two clump integrals are measured once per setting by rasterising sample clumps +//! ([`clump_moments`], cached). +//! +//! Resolution independence: grain geometry lives in normalized frame coordinates (a fraction of the +//! uncropped frame's long edge, like a grain on a 35 mm negative) and only the softening — one +//! output pixel — depends on the render size. A small render therefore shows what the export +//! shows downscaled: the same mean, the same (lower) variance. Once clumps are much smaller than a +//! pixel (grid thumbnails, fit-to-window previews of fine grain) the field is replaced by per-pixel +//! Gaussian noise with that exact variance, cross-faded over a band so the switch never shows. +//! +//! Shared with the GPU kernel (`crates/gpu/src/wgsl/finish.wgsl`): keep both in step. + +use std::f32::consts::FRAC_1_SQRT_2; +use std::sync::{Mutex, PoisonError}; + +use lightcraft_develop::Grain; + +/// Hash constants (shared with the GPU kernel). +pub const GRAIN_HASH: [u32; 4] = [0x2c9277b5, 0xac564b05, 0x9e37_79b9, 0x85eb_ca6b]; + +/// Seed salts of the red, green and blue dye layers (colour grain). +pub const CHANNEL_SALT: [u32; 3] = [0x68e3_1da4, 0xb529_7a4d, 0x1b56_c4e9]; + +/// Coverage range: grains always overlap into irregular clumps and pores (a sparse field would +/// read as isolated dots, a saturated one as pores in black): light tones are covered less. +pub const P_MIN: f32 = 0.2; +pub const P_MAX: f32 = 0.8; + +/// Clumps a cell may hold (a bound for the loop, far above any reachable mean). +pub const MAX_PER_CELL: u32 = 48; + +/// Grains a clump may hold. +pub const MAX_SUB: u32 = 11; + +/// Side of a Poisson cell (grain units). Fixed, so that no slider and no render size moves the +/// cell grid: the controls reshape, rescale and regroup the same particles. +pub const CELL: f32 = 2.5; + +/// Cells a pixel looks at along each axis beyond its own (the support is at most `CELL·MAX_REACH/2`). +pub const MAX_REACH: i32 = 12; + +/// Edge softness of the film itself (grain units), on top of the pixel's footprint. +const FILM_SOFT: f64 = 0.4; + +/// The development halo at most (its ring's integral as a fraction of the clump's grains'), and +/// its outer radius at most (clump sizes). +const HALO_MAX: f64 = 3.0; +const HALO_R_MAX: f64 = 6.0; + +/// Response ±100: the amplitude at black relative to white is `exp(∓RESPONSE_TILT)`. +const RESPONSE_TILT: f64 = 1.386_294_4; + +/// Size Variation 100: the log-radius spread (radii from 0.35× to 2.9× the mean). +const SPREAD_MAX: f64 = 0.35; + +/// Shape 100: grains up to 4:1 ellipses, outlines varying by up to 30 % with angle. +const ASPECT_MAX: f64 = 3.0; +const LUMP_MAX: f64 = 0.3; + +/// Clumping 100: on average five more grains per clump, spread over ±2 radii. +const CLUMP_EXTRA_MAX: f64 = 5.0; +const CLUMP_SPREAD_MIN: f64 = 0.8; +const CLUMP_SPREAD_MAX: f64 = 2.0; + +/// Phases (cos, sin of k·π/8) for the grains' outline harmonics (shared with the GPU kernel). +pub const PHASES: [[f32; 2]; 16] = [ + [1.0, 0.0], + [0.923_879_5, 0.382_683_43], + [FRAC_1_SQRT_2, FRAC_1_SQRT_2], + [0.382_683_43, 0.923_879_5], + [0.0, 1.0], + [-0.382_683_43, 0.923_879_5], + [-FRAC_1_SQRT_2, FRAC_1_SQRT_2], + [-0.923_879_5, 0.382_683_43], + [-1.0, 0.0], + [-0.923_879_5, -0.382_683_43], + [-FRAC_1_SQRT_2, -FRAC_1_SQRT_2], + [-0.382_683_43, -0.923_879_5], + [0.0, -1.0], + [0.382_683_43, -0.923_879_5], + [FRAC_1_SQRT_2, -FRAC_1_SQRT_2], + [0.923_879_5, -0.382_683_43], +]; + +/// The softening one output pixel applies, as the edge width of a grain (pixels), without clumps +/// and with the most: the width at which a small render has the grain variance of an export +/// box-downscaled to its size (measured: `small_render_matches_a_downscaled_full_size_render`). +/// Overlapping grains lose more variance to a box than to the soft footprint, so clumps need a +/// wider one. +pub const PIXEL_SOFTNESS: [f64; 2] = [0.44, 0.5]; + +/// The softening one output pixel applies to the halo (pixels). Below the reference resolution +/// the amplitude is set from the reference render's covariance (`ref_covariance`), so this only +/// shapes the halo of a small render, not its strength. +const HALO_PIXEL_SOFTNESS: f64 = 0.44; + +/// Grain units are mean grain radii; the reference resolution for the Amount calibration is a +/// 6000 px long edge (a 24 MP export). +const REF_PX_PER_LONG: f64 = 6000.0; + +/// Explicit particles while one output pixel's softening (the softness less the film's) is below +/// this many clump radii, Gaussian noise above the second bound, cross-faded between. Fine grain +/// on a 24 MP export (Size below about 10) is noise: particles a third of a pixel wide cost many +/// times the grain they add, and the noise is correlated as the particles are. +const EXPLICIT_UPTO: f64 = 0.35; +const GAUSSIAN_FROM: f64 = 0.8; + +/// One grain of a clump: offset from the clump's centre, radius, density, elongation and +/// orientation, outline harmonics (amplitude × phase), and how far it reaches. +#[derive(Clone, Copy, Debug, Default)] +struct Sub { + x: f32, + y: f32, + r: f32, + o: f32, + asp: f32, + inv_asp: f32, + ux: f32, + uy: f32, + h: [f32; 4], + reach: f32, +} + +/// One render's grain parameters (see the module docs). Lengths are in grain units (mean radius 1). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GrainParams { + /// Output scale: brightness change per unit of coverage deviation. + pub amp: f32, + /// Normalized long-edge units → grain units (`1 / mean radius`). + pub inv_r: f32, + /// Edge softness (grain units): film softness and the output pixel's footprint. + pub s: f32, + /// `1 / s`. + pub inv_s: f32, + /// The halo's inner and outer radius around a clump's centre (grain units, softened by the + /// halo's pixel footprint), as `1 / R²` (0 without a halo). + pub halo_in: f32, + pub halo_out: f32, + /// Log-radius spread of the grains (Size Variation). + pub spread: f32, + /// Extra elongation at most (a grain's aspect ratio is `1 + aspect·u`; Shape). + pub aspect: f32, + /// Outline irregularity (Shape). + pub lump: f32, + /// Mean number of extra grains per clump (Clumping). + pub clump_extra: f32, + /// How far a clump's grains lie from its centre at most, per axis (Clumping). + pub clump_d: f32, + /// `E[∫a_clump]`: a clump's expected coverage integral. + pub area: f32, + /// Largest distance at which a clump still covers a point. + pub support: f32, + /// Largest distance at which a grain still covers a point. + pub sub_reach: f32, + /// Side of a Poisson cell ([`CELL`]). + pub cell: f32, + /// `E[∫a_clump²] / E[∫a_clump]` for this softness (the variance formula's exponent). + pub kappa: f32, + /// The halo's moments relative to `E[∫a_clump]`: `E[∫h]`, `E[∫h²]` and `E[∫a·h]`. + pub halo_mean: f32, + pub k_hh: f32, + pub k_ah: f32, + /// `area`, `kappa`, `k_hh` and `k_ah` at the reference resolution: the per-tone amplitude + /// makes the grain's standard deviation there the same at every tone + /// ([`GrainParams::tone_weight`]). + pub area_ref: f32, + pub kappa_ref: f32, + pub k_hh_ref: f32, + pub k_ah_ref: f32, + /// Development halo `k`: a clump whose grains have densities `oᵢ` and radii `rᵢ` lightens its + /// surroundings by `k·W·(P(d²/R_out²) − P(d²/R_in²))`, `W = Σ oᵢ·rᵢ²`, `P(u) = (1 − u)²` + /// below 1: a ring of lower density around the clump whose integral is the look's `halo` + /// times `π·W` ([`GrainParams::clump_halo`]); 0 = none. + pub halo: f32, + /// The halo's outer radius relative to the clump's (1 without a halo). + pub halo_r: f32, + /// Response: the amplitude is multiplied by `exp(tilt·(l − ½))` at luminance `l`. + pub tilt: f32, + /// Cross-fade weights of the explicit field and of the Gaussian noise (`cos² + sin² = 1`). + pub w_field: f32, + pub w_noise: f32, + /// The noise's neighbour weight and normalisation: each pixel's noise is + /// `(n(x) − e·Σ n(4 neighbours))·norm`, so that its correlation with the next pixel is that + /// of the reference render box-averaged to this render's pixels ([`GrainParams::noise`]). + pub noise_e: f32, + pub noise_n: f32, + /// Colour grain, 0..1: from one grain layer for all channels to independent dye layers. + pub color: f32, + /// Tone response exponent: > 1 moves grain into the shadows, < 1 into the highlights. + pub gamma: f32, + pub seed: u32, + /// Output pixels per normalized long edge (for the per-pixel noise). + pub px_per_long: f32, +} + +fn finite(v: f64, lo: f64, hi: f64, default: f64) -> f64 { + if v.is_finite() { v.clamp(lo, hi) } else { default } +} + +/// What Size and Roughness map to (calibrated against Lightroom Classic exports: see +/// [`GrainLook::new`] and `docs/grain.md`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct GrainLook { + /// Mean grain radius, as a fraction of the frame's long edge. + pub radius: f64, + /// Grain shape, 0..1: round, even beads (0) to elongated, lobed grains (1). + pub shape: f64, + /// Development halo: the ring's integral as a fraction of its clump's grains' (0 = none). + pub halo: f64, + /// The halo's outer radius, in clump sizes. + pub halo_r: f64, + /// Standard deviation of the grain at Amount 100 at the reference resolution (display-encoded + /// units: 1 = 255 levels), the same at every tone. + pub level: f64, +} + +impl GrainLook { + /// The look of Size `size` and Roughness `roughness` (both 0..100), fitted to Lightroom + /// Classic exports at a 6000 px long edge (`docs/grain.md`, checked by + /// `grain_matches_lightroom_classic_exports`): the grain's strength and its autocorrelation + /// at Size 0, 25 and 100 (Roughness 50) and at Roughness 0 and 100 (Size 25). Between those + /// points the curves are smooth guesses. + pub fn new(size: f64, roughness: f64) -> GrainLook { + let size = finite(size, 0.0, 100.0, 25.0); + let rough = finite(roughness, 0.0, 100.0, 50.0) / 100.0; + // mean radius at 6000 px: 0.3 px at Size 0 (grain finer than a pixel), 0.83 at 25, 3 at + // 100; Roughness 0 is finer, 100 coarser + let r_px = (0.3 + 2.7 * (size / 100.0).powf(1.17)) * (0.96 - 0.33 * rough + 0.82 * rough * rough); + // a development halo makes the grain regular (negative autocorrelation one to three + // pixels out): below Roughness 50, and for grain finer than Size 25 + let smooth = (1.0 - 2.0 * rough).max(0.0); + let fine = (1.0 - size / 25.0).max(0.0); + let halo = smooth + 1.1 * fine * fine; + // strength at Amount 100 (8-bit levels at every tone): Size 0 46.2, 25 17.1, 100 11.7; + // Roughness 0 and 100 are 1.45× and 1.37× Roughness 50 + let levels = (2.447 + 1.386 * (-size / 19.88).exp()).exp(); + let d = rough - 0.5; + let rough_gain = 1.0 - 0.084 * d + 1.6384 * d * d; + GrainLook { radius: r_px / REF_PX_PER_LONG, shape: rough, halo, halo_r: 3.2, level: levels * rough_gain / 255.0 } + } +} + +/// Standard deviation of the explicit field at `p` (coverage less halo), for a clump coverage +/// integral `area`, the moment ratios `kappa`, `k_hh`, `k_ah` and Poisson cell side `cell`: +/// `(1 − p)²·(exp(κ·μ') − 1 + μ'·(k_hh − 2·k_ah))`, where `μ' = −ln(1 − p)` counts +/// fading-in clumps by `f²` (shared with the GPU kernel). +#[inline] +pub fn coverage_std_at(p: f32, area: f32, kappa: f32, k_hh: f32, k_ah: f32, cell: f32) -> f32 { + let q = 1.0 - p; + let t = -q.ln() / area * cell * cell; + let fw = t.min(1.0); + let mu = -q.ln() * (1.0 - fw / (6.0 * t.max(1e-12))); + let var = q * q * ((kappa * mu).exp() - 1.0 + mu * (k_hh - 2.0 * k_ah)); + var.max(0.0).sqrt() +} + +/// A clump's moments ([`clump_moments`]): `E[∫a]`, `E[∫a²]` of its coverage `a`, and `E[∫h]`, +/// `E[∫h²]`, `E[∫a·h]` with its halo `h`. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +struct Moments { + a1: f64, + a2: f64, + h1: f64, + h2: f64, + ah: f64, +} + +/// The parameters a clump's statistics depend on: shape, halo and softness. +fn moment_key(gp: &GrainParams) -> MomentKey { + [ + gp.spread.to_bits(), + gp.aspect.to_bits(), + gp.lump.to_bits(), + gp.clump_extra.to_bits(), + gp.clump_d.to_bits(), + gp.s.to_bits(), + gp.halo.to_bits(), + gp.halo_r.to_bits(), + gp.halo_in.to_bits(), + ] +} + +/// Cached [`clump_moments`]: keyed by the shape parameters, the halo and the softness. +type MomentKey = [u32; 9]; +static MOMENTS: Mutex> = Mutex::new(Vec::new()); + +/// The clump moments for `gp`'s shape parameters, halo and softness, measured by rasterising a +/// fixed set of sample clumps drawn by the renderer's own generator (cached: a slider drag that +/// changes only Amount, Color or Response, or a render at the same size, measures nothing). +fn clump_moments(gp: &GrainParams) -> Moments { + let key = moment_key(gp); + if let Some(m) = MOMENTS.lock().unwrap_or_else(PoisonError::into_inner).iter().find(|e| e.0 == key).map(|e| e.1) { + return m; + } + const SAMPLES: u32 = 512; + // finer with a halo: the box holds the halo, the grain is a smaller part of it + let grid: usize = if gp.halo > 0.0 { 44 } else { 28 }; + // one entry per sample clump, in parallel, summed in order (the same result every time) + let mut per = vec![Moments::default(); SAMPLES as usize]; + lightcraft_raster::par_rows(&mut per, 1, |k, out| { + let mut subs = [Sub::default(); MAX_SUB as usize]; + let h = pcg(0x51ed_270b ^ (k as u32).wrapping_mul(0x2545_f491)); + let n = gp.sub_count(h); + let mut rb = 0.0f32; + for (j, g) in subs.iter_mut().enumerate().take(n as usize) { + let hj = sub_hash(h, j as u32); + let (ox, oy) = gp.sub_offset(hj); + *g = gp.sub_shape(hj, ox, oy); + rb = rb.max((ox * ox + oy * oy).sqrt() + g.reach); + } + let w = gp.clump_weight(h); + if w > 0.0 && gp.halo_out > 0.0 { + rb = rb.max(1.0 / gp.halo_out.sqrt()); + } + let Some(out) = out.first_mut() else { return }; + if !(rb > 0.0 && rb.is_finite()) { + return; + } + let step = 2.0 * rb / grid as f32; + let mut acc = Moments::default(); + for gy in 0..grid { + for gx in 0..grid { + let (px, py) = (-rb + (gx as f32 + 0.5) * step, -rb + (gy as f32 + 0.5) * step); + let mut t = 1.0f32; + for g in subs.iter().take(n as usize) { + let (dx, dy) = (px - g.x, py - g.y); + let d2 = dx * dx + dy * dy; + if d2 < g.reach * g.reach { + t *= 1.0 - gp.sub_cover(g, dx, dy, d2); + } + } + let hs = gp.clump_halo(w, px * px + py * py); + let (a, h) = ((1.0 - t) as f64, hs as f64); + acc.a1 += a; + acc.a2 += a * a; + acc.h1 += h; + acc.h2 += h * h; + acc.ah += a * h; + } + } + let cell = (step * step) as f64; + *out = Moments { a1: acc.a1 * cell, a2: acc.a2 * cell, h1: acc.h1 * cell, h2: acc.h2 * cell, ah: acc.ah * cell }; + }); + let m = + per.iter().fold(Moments::default(), |m, e| Moments { a1: m.a1 + e.a1, a2: m.a2 + e.a2, h1: m.h1 + e.h1, h2: m.h2 + e.h2, ah: m.ah + e.ah }); + let n = SAMPLES as f64; + let m = Moments { a1: m.a1 / n, a2: m.a2 / n, h1: m.h1 / n, h2: m.h2 / n, ah: m.ah / n }; + let mut cache = MOMENTS.lock().unwrap_or_else(PoisonError::into_inner); + if cache.len() >= 64 { + cache.remove(0); + } + cache.push((key, m)); + m +} + +/// Lags of the reference render's covariance at most, per axis ([`ref_covariance`]). +const LAG_MAX: usize = 16; + +/// The covariance of the grain at the reference resolution between points `(lx, ly)·pitch` apart +/// (`lx` in `0..=lags`, `ly` in `−lags..=lags`), at coverage ½ ([`ref_covariance`]). +#[derive(Clone, Debug, PartialEq)] +struct RefCovariance { + /// Lattice pitch, in reference pixels (1, or more for coarse grain). + pitch: f64, + lags: usize, + c: Vec, +} + +impl RefCovariance { + fn at(&self, lx: i64, ly: i64) -> f64 { + let (lx, ly) = if lx < 0 { (-lx, -ly) } else { (lx, ly) }; + let l = self.lags as i64; + if lx > l || ly.abs() > l { + return 0.0; + } + self.c.get((lx * (2 * l + 1) + ly + l) as usize).copied().unwrap_or(0.0) + } + + /// The variance of the reference render box-averaged over blocks of `k × k` pixels, relative + /// to its variance per pixel (`None` below one lattice pitch). + fn block_variance(&self, k: f64) -> Option { + let kp = k / self.pitch; + if !(kp >= 1.0 && kp.is_finite()) { + return None; + } + let l = self.lags as i64; + let tri = |v: i64| (1.0 - v.unsigned_abs() as f64 / kp).max(0.0); + let mut v = 0.0; + for lx in -l..=l { + let wx = tri(lx); + if wx <= 0.0 { + continue; + } + for ly in -l..=l { + v += self.at(lx, ly) * wx * tri(ly); + } + } + let c0 = self.at(0, 0); + (c0 > 0.0).then(|| (v / (kp * kp) / c0).max(0.0)) + } + + /// The correlation of neighbouring pixels (horizontal and vertical alike) of the reference + /// render box-averaged over blocks of `k × k` pixels (`None` below one lattice pitch). + fn block_correlation(&self, k: f64) -> Option { + let kp = k / self.pitch; + if !(kp >= 1.0 && kp.is_finite()) { + return None; + } + let l = self.lags as i64; + let tri = |v: f64| (1.0 - v.abs() / kp).max(0.0); + let (mut c0, mut c1) = (0.0, 0.0); + for lx in -l..=l { + for ly in -l..=l { + let c = self.at(lx, ly); + let wy = tri(ly as f64); + c0 += c * tri(lx as f64) * wy; + c1 += c * tri(lx as f64 - kp) * wy; + } + } + (c0 > 0.0).then(|| c1 / c0) + } +} + +/// Cached [`ref_covariance`]. +static REF_COVARIANCE: Mutex> = Mutex::new(Vec::new()); + +/// The covariance between the pixels of the reference render (`gp` set up at the reference +/// resolution, `px` its pixel in grain units, `m` its clump moments), from the same exact +/// statistics as the variance: the clump integrals `E[∫a(u)·a(u + l)]`, `E[∫h(u)·h(u + l)]` and +/// `E[∫a(u)·h(u + l) + h(u)·a(u + l)]`, measured on sample clumps rasterised at random phases. +fn ref_covariance(gp: &GrainParams, px: f64, m: &Moments) -> RefCovariance { + let key = moment_key(gp); + if let Some(c) = REF_COVARIANCE.lock().unwrap_or_else(PoisonError::into_inner).iter().find(|e| e.0 == key).map(|e| e.1.clone()) { + return c; + } + let reach = 2.0 * gp.support as f64; + let pitch = px.max(reach / LAG_MAX as f64).max(1e-6); + let lags = ((reach / pitch).ceil() as usize).clamp(1, LAG_MAX); + let width = 2 * lags + 1; + const SAMPLES: u32 = 128; + let p = pitch as f32; + // one table per sample clump, in parallel, summed in order (the same result every time) + let mut per = vec![Vec::new(); SAMPLES as usize]; + lightcraft_raster::par_rows(&mut per, 1, |k, out| { + let Some(out) = out.first_mut() else { return }; + let mut acc = vec![[0.0f64; 3]; (lags + 1) * width]; + let mut subs = [Sub::default(); MAX_SUB as usize]; + let h = pcg(0x51ed_270b ^ (k as u32).wrapping_mul(0x2545_f491)); + let n = gp.sub_count(h); + let mut rb = 0.0f32; + for (j, g) in subs.iter_mut().enumerate().take(n as usize) { + let hj = sub_hash(h, j as u32); + let (ox, oy) = gp.sub_offset(hj); + *g = gp.sub_shape(hj, ox, oy); + rb = rb.max((ox * ox + oy * oy).sqrt() + g.reach); + } + let w = gp.clump_weight(h); + if w > 0.0 && gp.halo_out > 0.0 { + rb = rb.max(1.0 / gp.halo_out.sqrt()); + } + if !(rb > 0.0 && rb.is_finite()) { + return; + } + // the lattice at a random phase: an unbiased estimate of the integrals + let ph = pcg(h ^ 0x7f4a_7c15); + let (fx, fy) = (unit16(ph) * p, unit16(ph >> 16) * p); + let i0 = ((-rb - fx) / p).floor() as i64; + let g_n = ((2.0 * rb / p).ceil() as usize + 2).min(2 * LAG_MAX + 4); + let mut a = vec![0.0f64; g_n * g_n]; + let mut hv = vec![0.0f64; g_n * g_n]; + for gy in 0..g_n { + for gx in 0..g_n { + let (ux, uy) = (fx + (i0 + gx as i64) as f32 * p, fy + (i0 + gy as i64) as f32 * p); + let mut t = 1.0f32; + for g in subs.iter().take(n as usize) { + let (dx, dy) = (ux - g.x, uy - g.y); + let d2 = dx * dx + dy * dy; + if d2 < g.reach * g.reach { + t *= 1.0 - gp.sub_cover(g, dx, dy, d2); + } + } + let hs = gp.clump_halo(w, ux * ux + uy * uy); + if let (Some(av), Some(hh)) = (a.get_mut(gy * g_n + gx), hv.get_mut(gy * g_n + gx)) { + (*av, *hh) = ((1.0 - t) as f64, hs as f64); + } + } + } + let reach_l = lags.min(g_n - 1); + for lx in 0..=reach_l { + for ly in -(reach_l as i64)..=reach_l as i64 { + let mut s3 = [0.0f64; 3]; + for y in 0..g_n { + let y2 = y as i64 + ly; + if y2 < 0 || y2 >= g_n as i64 { + continue; + } + for x in 0..g_n - lx { + let (i, j) = (y * g_n + x, y2 as usize * g_n + x + lx); + let (Some(&a1), Some(&a2), Some(&h1), Some(&h2)) = (a.get(i), a.get(j), hv.get(i), hv.get(j)) else { continue }; + s3[0] += a1 * a2; + s3[1] += h1 * h2; + s3[2] += a1 * h2 + h1 * a2; + } + } + if let Some(e) = acc.get_mut(lx * width + (ly + lags as i64) as usize) { + *e = s3; + } + } + } + *out = acc; + }); + let mut acc = vec![[0.0f64; 3]; (lags + 1) * width]; + for table in &per { + for (e, v) in acc.iter_mut().zip(table) { + for (e, v) in e.iter_mut().zip(v) { + *e += v; + } + } + } + // the covariance at coverage ½ from the integrals (as `coverage_std_at`) + let cell = (pitch * pitch) / SAMPLES as f64; + let (q, a1) = (0.5f64, m.a1.max(1e-9)); + let t = -q.ln() / a1 * (gp.cell as f64).powi(2); + let mu = -q.ln() * (1.0 - t.min(1.0) / (6.0 * t.max(1e-12))); + let c = acc.iter().map(|[aa, hh, ah]| q * q * ((mu * aa * cell / a1).exp() - 1.0 + mu * (hh - ah) * cell / a1)).collect(); + let cov = RefCovariance { pitch: pitch / px, lags, c }; + let mut cache = REF_COVARIANCE.lock().unwrap_or_else(PoisonError::into_inner); + if cache.len() >= 64 { + cache.remove(0); + } + cache.push((key, cov.clone())); + cov +} + +impl GrainParams { + /// Parameters for a render with `px_per_long` output pixels per long edge of the uncropped + /// frame; `None` when there is no grain. Out-of-range or non-finite settings are clamped. + pub fn new(g: &Grain, px_per_long: f64) -> Option { + let look = GrainLook::new(finite(g.size, 0.0, 100.0, 25.0), finite(g.roughness, 0.0, 100.0, 50.0)); + GrainParams::with_look(g, px_per_long, &look) + } + + /// [`GrainParams::new`] with the Size and Roughness mapping given explicitly (calibration). + pub fn with_look(g: &Grain, px_per_long: f64, look: &GrainLook) -> Option { + let amount = finite(g.amount, 0.0, 100.0, 0.0) / 100.0; + let ppl = finite(px_per_long, 1.0, 1e7, 1.0); + if amount <= 0.0 { + return None; + } + let variation = finite(g.size_variation, 0.0, 100.0, 40.0) / 100.0; + let shape = finite(look.shape, 0.0, 1.0, 0.5); + let clumping = finite(g.clumping, 0.0, 100.0, 30.0) / 100.0; + let r_norm = finite(look.radius, 1e-6, 0.01, 0.000_14); + let halo = finite(look.halo, 0.0, HALO_MAX, 0.0); + let halo_r = if halo > 0.0 { finite(look.halo_r, 1.05, HALO_R_MAX, 2.0) } else { 1.0 }; + // the softness, quantized so that nearby render sizes share their cached moments + let pixel_soft = PIXEL_SOFTNESS[0] + (PIXEL_SOFTNESS[1] - PIXEL_SOFTNESS[0]) * clumping; + let soft_at = |ppl: f64, pixel_soft: f64| { + let s = (FILM_SOFT * FILM_SOFT + (pixel_soft / (r_norm * ppl)).powi(2)).sqrt(); + (s * 256.0).round().max(1.0) / 256.0 + }; + let (spread, aspect, lump) = (SPREAD_MAX * variation, ASPECT_MAX * shape, LUMP_MAX * shape); + let clump_extra = CLUMP_EXTRA_MAX * clumping; + let clump_d = CLUMP_SPREAD_MIN + (CLUMP_SPREAD_MAX - CLUMP_SPREAD_MIN) * clumping; + // a clump's scale (grain radii): one grain, or a cluster + let clump_size = 1.0 + 0.7 * clump_d * clump_extra.min(1.0); + let mut gp = GrainParams { + amp: 0.0, + inv_r: (1.0 / r_norm) as f32, + s: 0.0, + inv_s: 0.0, + halo_in: 0.0, + halo_out: 0.0, + spread: spread as f32, + aspect: aspect as f32, + lump: lump as f32, + clump_extra: clump_extra as f32, + clump_d: clump_d as f32, + area: 1.0, + support: 0.0, + sub_reach: 0.0, + cell: CELL, + kappa: 1.0, + halo_mean: 0.0, + k_hh: 0.0, + k_ah: 0.0, + area_ref: 1.0, + kappa_ref: 1.0, + k_hh_ref: 0.0, + k_ah_ref: 0.0, + halo: 0.0, + halo_r: halo_r as f32, + tilt: (finite(g.response, -100.0, 100.0, 0.0) / 100.0 * RESPONSE_TILT) as f32, + w_field: 1.0, + w_noise: 0.0, + noise_e: 0.0, + noise_n: 1.0, + color: (finite(g.color, 0.0, 100.0, 0.0) / 100.0) as f32, + gamma: 2f64.powf(-finite(g.response, -100.0, 100.0, 0.0) / 50.0) as f32, + seed: g.seed, + px_per_long: ppl as f32, + }; + let set_soft = |gp: &mut GrainParams, ppl: f64| { + let s = soft_at(ppl, pixel_soft); + let sh = soft_at(ppl, HALO_PIXEL_SOFTNESS); + (gp.s, gp.inv_s) = (s as f32, (1.0 / s) as f32); + let r_max = (3.0 * spread).exp() * (1.0 + aspect).sqrt() * (1.0 + lump); + gp.sub_reach = ((r_max * r_max + s * s).sqrt() + s) as f32; + let mut support = clump_d * std::f64::consts::SQRT_2 + gp.sub_reach as f64; + if halo > 0.0 { + // the ring around the clump, from its own size out to `halo_r` times it, scaled so + // that its integral is `halo` times the grains' (`P` integrates to `πR²/3`) + let ri2 = clump_size * clump_size + sh * sh; + let ro2 = (halo_r * clump_size).powi(2) + sh * sh; + (gp.halo_in, gp.halo_out) = ((1.0 / ri2) as f32, (1.0 / ro2) as f32); + gp.halo = (3.0 * halo / (ro2 - ri2)) as f32; + support = support.max(ro2.sqrt()); + } + gp.support = support.min(CELL as f64 * MAX_REACH as f64 * 0.5 - 0.01) as f32; + }; + // the grain's standard deviation at the reference resolution is `look.level` per unit of + // Amount at every tone (`tone_weight` divides by the coverage's own deviation there) + set_soft(&mut gp, REF_PX_PER_LONG); + let ratios = |m: &Moments| { + if m.a1 > 0.0 { + let r = |v: f64| (v / m.a1).clamp(0.0, 1e3) as f32; + (m.a1.max(1e-3) as f32, (m.a2 / m.a1).clamp(1e-6, 1.0) as f32, r(m.h1), r(m.h2), r(m.ah)) + } else { + (1.0, 1.0, 0.0, 0.0, 0.0) + } + }; + let m_ref = clump_moments(&gp); + (gp.area_ref, gp.kappa_ref, _, gp.k_hh_ref, gp.k_ah_ref) = ratios(&m_ref); + let ref_px = 1.0 / (r_norm * REF_PX_PER_LONG); + let ref_gp = gp; + // below the reference resolution, the grain is the reference render box-averaged + let ref_block = if ppl < REF_PX_PER_LONG { ref_covariance(&ref_gp, ref_px, &m_ref).block_variance(REF_PX_PER_LONG / ppl) } else { None }; + set_soft(&mut gp, ppl); + let s = gp.s as f64; + (gp.area, gp.kappa, gp.halo_mean, gp.k_hh, gp.k_ah) = ratios(&clump_moments(&gp)); + gp.amp = (amount * finite(look.level, 0.0, 1.0, 0.0)) as f32; + if let Some(v) = ref_block { + // what this render's own statistics give, scaled to the box-averaged reference render + let own = coverage_std_at(0.5, gp.area, gp.kappa, gp.k_hh, gp.k_ah, gp.cell) as f64; + let at_ref = coverage_std_at(0.5, gp.area_ref, gp.kappa_ref, gp.k_hh_ref, gp.k_ah_ref, gp.cell) as f64; + if own > 0.0 && v > 0.0 { + gp.amp *= (v.sqrt() * at_ref / own).clamp(0.25, 4.0) as f32; + } + } + // the pixel's footprint (the softness less the film's) relative to a clump + let px_soft = (s * s - FILM_SOFT * FILM_SOFT).max(0.0).sqrt(); + let t = ((px_soft / clump_size - EXPLICIT_UPTO) / (GAUSSIAN_FROM - EXPLICIT_UPTO)).clamp(0.0, 1.0); + (gp.w_field, gp.w_noise) = if t <= 0.0 { + (1.0, 0.0) + } else if t >= 1.0 { + (0.0, 1.0) + } else { + let a = t * std::f64::consts::FRAC_PI_2; + (a.cos() as f32, a.sin() as f32) + }; + if gp.w_noise > 0.0 { + // the noise correlated with its neighbours as the reference render's pixels are, box- + // averaged to this render's: `−2e / (1 + 4e²)` is the correlation of the next pixel + let k = (REF_PX_PER_LONG / ppl).max(1.0); + let rho = ref_covariance(&ref_gp, ref_px, &m_ref).block_correlation(k).unwrap_or(0.0).clamp(-0.45, 0.45); + let e = if rho.abs() > 1e-6 { (-1.0 + (1.0 - 4.0 * rho * rho).sqrt()) / (4.0 * rho) } else { 0.0 }; + (gp.noise_e, gp.noise_n) = (e as f32, (1.0 / (1.0 + 4.0 * e * e).sqrt()) as f32); + } + Some(gp) + } + + /// Expected coverage for display-encoded luminance `lum` (grain is density: dark tones are + /// covered more). + #[inline] + pub fn coverage(&self, lum: f32) -> f32 { + let l = if lum.is_finite() { lum.clamp(0.0, 1.0) } else { 0.5 }; + P_MIN + (P_MAX - P_MIN) * self.shade(l) + } + + /// `(1 − l)^γ` for luminance `l` in 0..1 (no `powf` at the default response). + #[inline] + fn shade(&self, l: f32) -> f32 { + let d = (1.0 - l).max(1e-7); + if self.gamma == 1.0 { d } else { d.powf(self.gamma) } + } + + /// Amplitude weight for display-encoded luminance `lum`: the inverse of the coverage's standard + /// deviation at the reference resolution, so that the grain is equally strong at every tone, + /// times the Response's tilt towards the shadows or the highlights. + #[inline] + pub fn tone_weight(&self, lum: f32) -> f32 { + let l = if lum.is_finite() { lum.clamp(0.0, 1.0) } else { 0.5 }; + let p = P_MIN + (P_MAX - P_MIN) * self.shade(l); + let sd = coverage_std_at(p, self.area_ref, self.kappa_ref, self.k_hh_ref, self.k_ah_ref, self.cell); + let tilt = if self.tilt == 0.0 { 1.0 } else { (self.tilt * (l - 0.5)).exp() }; + tilt / sd.max(1e-4) + } + + /// Expected clumps per Poisson cell at coverage `p`. + #[inline] + fn per_cell(&self, p: f32) -> f32 { + -(1.0 - p).ln() / self.area * self.cell * self.cell + } + + /// Standard deviation of the explicit field at `p` at this render's resolution (the Gaussian + /// noise's amplitude; see [`coverage_std_at`]). + #[inline] + pub fn coverage_std(&self, p: f32) -> f32 { + coverage_std_at(p, self.area, self.kappa, self.k_hh, self.k_ah, self.cell) + } + + /// Number of grains in the clump with hash `h`. + #[inline] + fn sub_count(&self, h: u32) -> u32 { + if self.clump_extra <= 0.0 { + return 1; + } + let extra = (unit(pcg(h ^ GRAIN_HASH[3])) * (2.0 * self.clump_extra + 1.0)).floor(); + 1 + (extra.max(0.0) as u32).min(MAX_SUB - 1) + } + + /// Offset of the grain with hash `hj` from its clump's centre. + #[inline] + fn sub_offset(&self, hj: u32) -> (f32, f32) { + let o = pcg(hj ^ GRAIN_HASH[0]); + let d = self.clump_d; + (d * (unit8(o) + unit8(o >> 8) - 1.0), d * (unit8(o >> 16) + unit8(o >> 24) - 1.0)) + } + + /// The grain with hash `hj` at offset (ox, oy): radius, density, elongation, orientation and + /// outline. + #[inline] + fn sub_shape(&self, hj: u32, ox: f32, oy: f32) -> Sub { + let (r, o) = self.sub_size(hj); + let shp = pcg(hj ^ GRAIN_HASH[1]); + let (a, b) = (2.0 * unit8(shp) - 1.0, 2.0 * unit8(shp >> 8) - 1.0); + let n = (a * a + b * b).sqrt(); + let (ux, uy) = if n > 1e-3 { (a / n, b / n) } else { (1.0, 0.0) }; + let asp = 1.0 + self.aspect * unit4(shp >> 16); + let m = 0.5 + ((shp >> 28) & 15) as f32 * (1.0 / 30.0); + let p2 = PHASES.get(((shp >> 20) & 15) as usize).copied().unwrap_or([1.0, 0.0]); + let p3 = PHASES.get(((shp >> 24) & 15) as usize).copied().unwrap_or([1.0, 0.0]); + let rr = r * asp.sqrt() * (1.0 + self.lump); + Sub { + x: ox, + y: oy, + r, + o, + asp, + inv_asp: 1.0 / asp, + ux, + uy, + h: [0.6 * m * p2[0], 0.6 * m * p2[1], 0.4 * m * p3[0], 0.4 * m * p3[1]], + reach: (rr * rr + self.s * self.s).sqrt() + self.s, + } + } + + /// Radius and density of the grain with hash `hj`. + #[inline] + fn sub_size(&self, hj: u32) -> (f32, f32) { + let rad = pcg(hj ^ GRAIN_HASH[3]); + let z = 2.0 * (unit8(rad) + unit8(rad >> 8) + unit8(rad >> 16)) - 3.0; + ((self.spread * z).exp(), 0.25 + 0.75 * unit8(rad >> 24)) + } + + /// The halo weight of the clump with hash `h`: `Σ oᵢ·rᵢ²` over its grains (0 without a halo). + #[inline] + fn clump_weight(&self, h: u32) -> f32 { + if self.halo <= 0.0 { + return 0.0; + } + (0..self.sub_count(h)) + .map(|j| { + let (r, o) = self.sub_size(sub_hash(h, j)); + o * r * r + }) + .sum() + } + + /// The halo of a clump of weight `w` at squared distance `d2` from its centre: a ring from the + /// clump's own size out to `halo_r` times it (no square root: a polynomial in `d2`). + #[inline] + fn clump_halo(&self, w: f32, d2: f32) -> f32 { + let u = d2 * self.halo_out; + if u >= 1.0 || w == 0.0 { + return 0.0; + } + let v = d2 * self.halo_in; + let inner = if v < 1.0 { (1.0 - v) * (1.0 - v) } else { 0.0 }; + self.halo * w * ((1.0 - u) * (1.0 - u) - inner) + } + + /// Coverage (density × softened profile) of grain `g` at offset (dx, dy) from its centre, + /// `d2 = dx² + dy²`. + #[inline] + fn sub_cover(&self, g: &Sub, dx: f32, dy: f32, d2: f32) -> f32 { + let d = d2.sqrt(); + let mut r = g.r; + if d > 1e-6 { + let inv_d = 1.0 / d; + let (c, sn) = (dx * inv_d, dy * inv_d); + if g.asp > 1.0 { + // the ellipse's radius in this direction (area πr² whatever the elongation) + let (cu, cw) = (c * g.ux + sn * g.uy, sn * g.ux - c * g.uy); + r /= (cu * cu * g.inv_asp + cw * cw * g.asp).sqrt(); + } + if self.lump > 0.0 { + // cos/sin of 2θ and 3θ from the direction (no trigonometry) + let (c2, s2) = (c * c - sn * sn, 2.0 * c * sn); + let (c3, s3) = (c * (4.0 * c * c - 3.0), sn * (3.0 - 4.0 * sn * sn)); + r *= 1.0 + self.lump * (g.h[0] * c2 + g.h[1] * s2 + g.h[2] * c3 + g.h[3] * s3); + } + } + g.o * Self::profile(d, r, self.s, self.inv_s) + } + + /// A disc of radius `r` softened by the edge width: its value at distance `d` from the centre + /// (integral ≈ πr²). + #[inline] + fn profile(d: f32, r: f32, s: f32, inv_s: f32) -> f32 { + let rho2 = r * r + s * s; + let tau = (d - rho2.sqrt()) * inv_s; + if tau >= 1.0 { + return 0.0; + } + let prof = if tau <= -1.0 { 1.0 } else { (1.0 - tau) * (1.0 - tau) * (2.0 + tau) * 0.25 }; + r * r / (rho2 + s * s * 0.2) * prof + } + + /// Coverage (the union of its grains) and halo (their sum) of the clump with hash `h` at + /// offset (dx, dy) from its centre. + fn clump_cover(&self, h: u32, dx: f32, dy: f32) -> (f32, f32) { + let mut t = 1.0f32; + let rr = self.sub_reach * self.sub_reach; + let hs = self.clump_halo(self.clump_weight(h), dx * dx + dy * dy); + for j in 0..self.sub_count(h) { + let hj = sub_hash(h, j); + let (ox, oy) = self.sub_offset(hj); + let (ex, ey) = (dx - ox, dy - oy); + let d2 = ex * ex + ey * ey; + if d2 >= rr { + continue; + } + let g = self.sub_shape(hj, ox, oy); + if d2 >= g.reach * g.reach { + continue; + } + t *= 1.0 - self.sub_cover(&g, ex, ey, d2); + } + (1.0 - t, hs) + } + + /// The halo's expected value at coverage `p` (its sum over the clumps). + #[inline] + fn halo_at(&self, p: f32) -> f32 { + if self.halo > 0.0 { -(1.0 - p).ln() * self.halo_mean } else { 0.0 } + } + + /// Grain coverage at grain-unit position (x, y) for expected coverage `p` and layer seed, less + /// the halo's deviation from its mean on the light the grains let through (`1 − p`), so that + /// the mean is `p` and the halo is as strong relative to the grains at every tone. + pub fn field(&self, x: f32, y: f32, p: f32, seed: u32) -> f32 { + let t = self.per_cell(p); + // clumps fade in over the last `fw` of the cell's mark range, so the field changes + // continuously with tone (no particle pops in or out); the shift keeps the mean count at t + let fw = t.clamp(1e-6, 1.0); + let end = t + 0.5 * fw; + let (r, c) = (self.support, self.cell); + // the cells within reach, as a start and a bounded count + let (fi0, fj0) = (((x - r) / c).floor(), ((y - r) / c).floor()); + let (ni, nj) = (cells_to((x + r) / c, fi0), cells_to((y + r) / c, fj0)); + let (i0, j0) = (fi0.clamp(-2.0e9, 2.0e9) as i32, fj0.clamp(-2.0e9, 2.0e9) as i32); + // a cell holds clumps while the running product of their uniforms stays above + // exp(−end) (Poisson arrivals in mark order, `mₖ = −ln Π uᵢ`); full weight above exp(fw − end) + let (e_end, e_full) = ((-end).exp(), (fw - end).exp()); + let salt = pcg(seed); + let (mut keep, mut hs) = (1.0f32, 0.0f32); + for dj in 0..=nj { + let j = j0.saturating_add(dj); + let (cy0, cy1) = (j as f32 * c, (j as f32 + 1.0) * c); + let dy = y - y.clamp(cy0, cy1); + for di in 0..=ni { + let i = i0.saturating_add(di); + let (cx0, cx1) = (i as f32 * c, (i as f32 + 1.0) * c); + let dx = x - x.clamp(cx0, cx1); + if dx * dx + dy * dy >= r * r { + continue; + } + let base = cell_hash(i, j, salt); + let mut prod = 1.0f32; + for k in 0..MAX_PER_CELL { + let h = pcg(base.wrapping_add(k)); + prod *= unit(h); + if prod <= e_end { + break; + } + let pos = pcg(h ^ GRAIN_HASH[2]); + let (cx, cy) = ((i as f32 + unit16(pos)) * c, (j as f32 + unit16(pos >> 16)) * c); + let (ex, ey) = (x - cx, y - cy); + if ex * ex + ey * ey >= r * r { + continue; + } + let (a, ha) = self.clump_cover(h, ex, ey); + if a == 0.0 && ha == 0.0 { + continue; + } + let f = if prod >= e_full { 1.0 } else { ((end + prod.ln()) / fw).clamp(0.0, 1.0) }; + keep *= 1.0 - f * a; + hs += f * ha; + } + } + } + 1.0 - keep - (1.0 - p) * (hs - self.halo_at(p)) + } + + /// Per-pixel thresholds as in [`GrainParams::field`], for expected coverages `ps`: `(end, fade + /// width, e^−end, e^(fw − end))` each, and the smallest `e^−end`. + fn pixel_ends(&self, ps: &[f32]) -> (Vec<(f32, f32, f32, f32)>, f32) { + let mut ends = Vec::with_capacity(ps.len()); + let mut e_min = 1.0f32; + for &p in ps { + let t = self.per_cell(p); + let fw = t.clamp(1e-6, 1.0); + let end = t + 0.5 * fw; + let e_end = (-end).exp(); + e_min = e_min.min(e_end); + ends.push((end, fw, e_end, (fw - end).exp())); + } + (ends, e_min) + } + + /// [`GrainParams::field`] for a band of output rows: `xs`, `ys` are the grain-unit positions of + /// `rows × cols` pixels, row-major, on an affine grid (as an output window is), `ps` their + /// expected coverages; the coverage goes to `out`. Visits every cell near the band once and + /// splats each clump's grains onto the pixels they reach, testing each grain against each + /// pixel exactly as `field` does (same particles, same weights; only the product order differs). + pub fn field_band(&self, xs: &[f32], ys: &[f32], cols: usize, ps: &[f32], seed: u32, out: &mut [f32]) { + let len = xs.len().min(ys.len()).min(ps.len()).min(out.len()); + let rows = len.checked_div(cols).unwrap_or(0); + let n = rows * cols; + let (r, c, s) = (self.support, self.cell, self.s); + let corner = |row: usize, k: usize| (xs.get(row * cols + k).copied(), ys.get(row * cols + k).copied()); + let ((Some(x00), Some(y00)), (Some(x01), Some(y01)), (Some(x10), Some(y10))) = + (corner(0, 0), corner(0, cols.wrapping_sub(1)), corner(rows.wrapping_sub(1), 0)) + else { + return; + }; + let finite = [x00, y00, x01, y01, x10, y10, r, c, s].iter().all(|v| v.is_finite()) && c > 0.0 && s > 0.0; + let span = ((x01 - x00).abs().max((y01 - y00).abs()).max((x10 - x00).abs()).max((y10 - y00).abs()) / c.max(1e-6)) as usize; + if !finite || span > 16 * (cols + rows) + 64 { + // not a well-formed window (never for a render): pixel by pixel + for (k, o) in out.iter_mut().enumerate().take(n) { + *o = self.field(xs[k], ys[k], ps[k], seed); + } + return; + } + // along a row (bx, by) per pixel; from row to row (dx, dy) + let (bx, by) = ((x01 - x00) / (cols - 1).max(1) as f32, (y01 - y00) / (cols - 1).max(1) as f32); + let (dx, dy) = ((x10 - x00) / (rows - 1).max(1) as f32, (y10 - y00) / (rows - 1).max(1) as f32); + let bb = bx * bx + by * by; + let inv_b = if bb > 1e-24 { 1.0 / bb.sqrt() } else { 0.0 }; + let (ends, e_min) = self.pixel_ends(&ps[..n]); + let keep = &mut out[..n]; + keep.fill(1.0); + // per pixel, the clump being splatted: Π(1 − aⱼ) over its grains, and the pixels it touched + let mut clump_t = vec![1.0f32; n]; + // and Σ hⱼ (the halo), and the halo summed over the clumps + let mut clump_h = vec![0.0f32; n]; + let mut halo = vec![0.0f32; n]; + let mut touched: Vec = Vec::new(); + let salt = pcg(seed); + let last = (cols - 1) as f32; + let halo_reach = if self.halo > 0.0 && self.halo_out > 0.0 { 1.0 / self.halo_out.sqrt() } else { 0.0 }; + // the pixels whose centres lie in a parameter interval along a row (a hair's margin for + // rounding: each pixel is tested exactly below) + let chord = |a: f32, b: f32| -> Option<(usize, usize)> { + let (lo, hi) = ((a - 0.05).ceil(), (b + 0.05).floor()); + if hi.is_nan() || lo.is_nan() || hi < lo || hi < 0.0 || lo > last { + return None; + } + Some((lo.max(0.0) as usize, (hi.min(last) as usize).min(cols - 1))) + }; + // distance of a point from row `row`'s line, and the pixels of that row within `reach` of it + let row_reach = |row: usize, px: f32, py: f32, reach: f32| -> Option<(usize, usize)> { + let (ddx, ddy) = (px - (x00 + row as f32 * dx), py - (y00 + row as f32 * dy)); + // the cross product: no cancellation far along the row + let perp = if inv_b > 0.0 { (ddx * by - ddy * bx) * inv_b } else { (ddx * ddx + ddy * ddy).sqrt() }; + if perp.abs() >= reach { + return None; + } + if inv_b > 0.0 { + let kc = (ddx * bx + ddy * by) / bb; + let half = (reach * reach - perp * perp).max(0.0).sqrt() * inv_b; + chord(kc - half, kc + half) + } else { + Some((0, cols - 1)) + } + }; + // the band is the parallelogram of its pixel centres; cells within the support of it + let quad = [(x00, y00), (x01, y01), (x10 + (x01 - x00), y10 + (y01 - y00)), (x10, y10)]; + let (qx0, qx1) = quad.iter().fold((f32::INFINITY, f32::NEG_INFINITY), |(a, b), q| (a.min(q.0), b.max(q.0))); + let (i0, i1) = (((qx0 - r) / c).floor() as i32, ((qx1 + r) / c).floor() as i32); + let mut subs: [Option; MAX_SUB as usize]; + let mut offs = [(0.0f32, 0.0f32); MAX_SUB as usize]; + for i in i0..=i1 { + // the parallelogram's Y extent within this column of cells (grown by the support): + // the extremes lie on its edges clipped to the column + let (cx0, cx1) = (i as f32 * c - r, (i as f32 + 1.0) * c + r); + let Some((y_lo, y_hi)) = column_y_extent(&quad, cx0, cx1) else { + continue; + }; + let (j0, j1) = (((y_lo - r) / c).floor() as i32, ((y_hi + r) / c).floor() as i32); + for j in j0..=j1 { + let base = cell_hash(i, j, salt); + let mut prod = 1.0f32; + for k in 0..MAX_PER_CELL { + let h = pcg(base.wrapping_add(k)); + prod *= unit(h); + if prod <= e_min { + break; + } + let pos = pcg(h ^ GRAIN_HASH[2]); + let (cx, cy) = ((i as f32 + unit16(pos)) * c, (j as f32 + unit16(pos >> 16)) * c); + let count = self.sub_count(h) as usize; + subs = [None; MAX_SUB as usize]; + let mut offsets_known = false; + let mut weight = None; + touched.clear(); + for row in 0..rows { + if row_reach(row, cx, cy, r).is_none() { + continue; + } + if !offsets_known { + for (jj, o) in offs.iter_mut().enumerate().take(count) { + *o = self.sub_offset(sub_hash(h, jj as u32)); + } + offsets_known = true; + } + for jj in 0..count { + let Some(&(ox, oy)) = offs.get(jj) else { continue }; + let (sx, sy) = (cx + ox, cy + oy); + if row_reach(row, sx, sy, self.sub_reach).is_none() { + continue; + } + let Some(slot) = subs.get_mut(jj) else { continue }; + let g = *slot.get_or_insert_with(|| self.sub_shape(sub_hash(h, jj as u32), ox, oy)); + let Some((pa, pb)) = row_reach(row, sx, sy, g.reach) else { continue }; + for q in row * cols + pa..=row * cols + pb { + let (Some(&(_, _, e_end, _)), Some(&x), Some(&y)) = (ends.get(q), xs.get(q), ys.get(q)) else { continue }; + if prod <= e_end { + continue; + } + // as `field` rounds it: from the clump's centre, then the grain's offset + let (ex, ey) = ((x - cx) - ox, (y - cy) - oy); + let d2 = ex * ex + ey * ey; + if d2 >= g.reach * g.reach { + continue; + } + let a = self.sub_cover(&g, ex, ey, d2); + if a == 0.0 { + continue; + } + if let (Some(t), Some(hq)) = (clump_t.get_mut(q), clump_h.get_mut(q)) { + if *t == 1.0 && *hq == 0.0 { + touched.push(q); + } + *t *= 1.0 - a; + } + } + } + // the clump's halo, from its centre + if halo_reach > 0.0 { + let w = *weight.get_or_insert_with(|| self.clump_weight(h)); + let Some((pa, pb)) = row_reach(row, cx, cy, halo_reach) else { continue }; + for q in row * cols + pa..=row * cols + pb { + let (Some(&(_, _, e_end, _)), Some(&x), Some(&y)) = (ends.get(q), xs.get(q), ys.get(q)) else { continue }; + if prod <= e_end { + continue; + } + let (ex, ey) = (x - cx, y - cy); + let ha = self.clump_halo(w, ex * ex + ey * ey); + if ha == 0.0 { + continue; + } + if let (Some(t), Some(hq)) = (clump_t.get_mut(q), clump_h.get_mut(q)) { + if *t == 1.0 && *hq == 0.0 { + touched.push(q); + } + *hq += ha; + } + } + } + } + let mut ln_prod = None; + for &q in &touched { + let (Some(&(end, fw, _, e_full)), Some(t), Some(hq)) = (ends.get(q), clump_t.get_mut(q), clump_h.get_mut(q)) else { + continue; + }; + let (a, ha) = (1.0 - *t, *hq); + (*t, *hq) = (1.0, 0.0); + let f = if prod >= e_full { 1.0 } else { ((end + *ln_prod.get_or_insert_with(|| prod.ln())) / fw).clamp(0.0, 1.0) }; + if let (Some(kq), Some(hs)) = (keep.get_mut(q), halo.get_mut(q)) { + *kq *= 1.0 - f * a; + *hs += f * ha; + } + } + } + } + } + for ((v, hs), p) in keep.iter_mut().zip(&halo).zip(ps) { + *v = 1.0 - *v - (1.0 - p) * (hs - self.halo_at(*p)); + } + } + + /// The grain layers (seeds) and how much each adds to every channel: one layer for all + /// channels, or with colour grain that layer plus a dye layer per channel + /// (`√(1 − c)·mono + √c·dye`, so the strength stays the same). + fn layers(&self) -> Vec<(u32, [f32; 3])> { + if self.color <= 0.0 { + return vec![(self.seed, [1.0; 3])]; + } + let (wm, wc) = ((1.0 - self.color).max(0.0).sqrt(), self.color.sqrt()); + let mut v = vec![(self.seed, [wm; 3])]; + for (ch, salt) in CHANNEL_SALT.iter().enumerate() { + let mut w = [0.0; 3]; + if let Some(slot) = w.get_mut(ch) { + *slot = wc; + } + v.push((self.seed ^ salt, w)); + } + v + } + + /// Brightness deviation of one grain layer at normalized position (gx, gy). + #[inline] + fn layer(&self, gx: f32, gy: f32, p: f32, seed: u32) -> f32 { + let mut d = 0.0; + if self.w_field > 0.0 { + d += self.w_field * (p - self.field(gx * self.inv_r, gy * self.inv_r, p, seed)); + } + if self.w_noise > 0.0 { + let (ix, iy) = ((gx * self.px_per_long).floor() as i32, (gy * self.px_per_long).floor() as i32); + d -= self.w_noise * self.coverage_std(p) * self.noise(ix, iy, seed); + } + d + } + + /// Unit-variance noise for pixel (ix, iy), correlated with its four neighbours by `noise_e`. + #[inline] + fn noise(&self, ix: i32, iy: i32, seed: u32) -> f32 { + let n = gauss(ix, iy, seed); + if self.noise_e == 0.0 { + return n; + } + let around = gauss(ix.wrapping_sub(1), iy, seed) + + gauss(ix.wrapping_add(1), iy, seed) + + gauss(ix, iy.wrapping_sub(1), seed) + + gauss(ix, iy.wrapping_add(1), seed); + (n - self.noise_e * around) * self.noise_n + } + + /// What grain adds to each display-encoded channel at normalized position (gx, gy) (fractions + /// of the uncropped frame's long edge) for a pixel of display-encoded luminance `lum`. + pub fn apply(&self, gx: f32, gy: f32, lum: f32) -> [f32; 3] { + if !(gx.is_finite() && gy.is_finite()) { + return [0.0; 3]; + } + let p = self.coverage(lum); + let amp = self.amp * self.tone_weight(lum); + let mut out = [0.0f32; 3]; + for (seed, w) in self.layers() { + let d = amp * self.layer(gx, gy, p, seed); + for (o, w) in out.iter_mut().zip(w) { + *o += w * d; + } + } + out + } + + /// [`GrainParams::apply`] for a band of output rows: adds grain to the display-encoded colours + /// `e` of `rows × cols` pixels (row-major) at normalized positions `gx`, `gy` (an affine grid). + pub fn apply_band(&self, gx: &[f32], gy: &[f32], cols: usize, e: &mut [[f32; 3]]) { + let n = gx.len().min(gy.len()).min(e.len()); + let lums: Vec = e[..n].iter().map(|c| 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]).collect(); + let ps: Vec = lums.iter().map(|l| self.coverage(*l)).collect(); + let amps: Vec = lums.iter().map(|l| self.amp * self.tone_weight(*l)).collect(); + let (xs, ys): (Vec, Vec) = gx[..n].iter().zip(&gy[..n]).map(|(x, y)| (x * self.inv_r, y * self.inv_r)).unzip(); + let mut v = vec![0.0f32; n]; + for (seed, w) in self.layers() { + if self.w_field > 0.0 { + self.field_band(&xs, &ys, cols, &ps, seed, &mut v); + } + for k in 0..n { + let (x, y, p) = (gx[k], gy[k], ps[k]); + if !(x.is_finite() && y.is_finite()) { + continue; + } + let mut d = 0.0; + if self.w_field > 0.0 { + d += self.w_field * (p - v[k]); + } + if self.w_noise > 0.0 { + let (ix, iy) = ((x * self.px_per_long).floor() as i32, (y * self.px_per_long).floor() as i32); + d -= self.w_noise * self.coverage_std(p) * self.noise(ix, iy, seed); + } + let d = amps[k] * d; + let c = &mut e[k]; + *c = [c[0] + w[0] * d, c[1] + w[1] * d, c[2] + w[2] * d]; + } + } + } +} + +/// The Y extent of the parallelogram `quad` within the column `cx0..=cx1`: its extremes lie on the +/// edges clipped to the column. `None` when no edge crosses the column. +fn column_y_extent(quad: &[(f32, f32); 4], cx0: f32, cx1: f32) -> Option<(f32, f32)> { + let (mut y_lo, mut y_hi) = (f32::INFINITY, f32::NEG_INFINITY); + for e in 0..4 { + let ((ax, ay), (bx, by)) = (quad[e], quad[(e + 1) % 4]); + let ex = bx - ax; + let (t0, t1) = if ex.abs() > 1e-12 { + let (u, v) = ((cx0 - ax) / ex, (cx1 - ax) / ex); + (u.min(v).max(0.0), u.max(v).min(1.0)) + } else if ax >= cx0 && ax <= cx1 { + (0.0, 1.0) + } else { + continue; + }; + if t0 > t1 { + continue; + } + for t in [t0, t1] { + let yt = ay + t * (by - ay); + y_lo = y_lo.min(yt); + y_hi = y_hi.max(yt); + } + } + (!(y_lo.is_nan() || y_hi.is_nan() || y_lo > y_hi)).then_some((y_lo, y_hi)) +} + +/// How many cells after `start` (floor of the low edge) reach up to `hi` (in cells): at most +/// [`MAX_REACH`], never negative or non-finite. +#[inline] +fn cells_to(hi: f32, start: f32) -> i32 { + let n = hi.floor() - start; + if n.is_finite() { n.clamp(0.0, MAX_REACH as f32) as i32 } else { 0 } +} + +/// PCG output permutation (RXS-M-XS) of an LCG step. +#[inline] +pub fn pcg(v: u32) -> u32 { + let s = v.wrapping_mul(747_796_405).wrapping_add(2_891_336_453); + let w = ((s >> ((s >> 28) + 4)) ^ s).wrapping_mul(277_803_737); + (w >> 22) ^ w +} + +/// Hash of cell (i, j) for a layer `salt` (`pcg(seed)`). +#[inline] +fn cell_hash(i: i32, j: i32, salt: u32) -> u32 { + pcg((i as u32).wrapping_mul(GRAIN_HASH[0]) ^ (j as u32).wrapping_mul(GRAIN_HASH[1]) ^ salt) +} + +/// Hash of grain `j` of the clump with hash `h`. +#[inline] +fn sub_hash(h: u32, j: u32) -> u32 { + pcg(h ^ (j + 1).wrapping_mul(0x9e37_79b9)) +} + +/// A uniform in (0, 1) from the top 24 bits. +#[inline] +fn unit(v: u32) -> f32 { + ((v >> 8) as f32 + 0.5) * (1.0 / 16_777_216.0) +} + +/// A uniform in (0, 1) from the low 16 bits. +#[inline] +fn unit16(v: u32) -> f32 { + ((v & 0xffff) as f32 + 0.5) * (1.0 / 65_536.0) +} + +/// A uniform in (0, 1) from the low 8 bits. +#[inline] +fn unit8(v: u32) -> f32 { + ((v & 0xff) as f32 + 0.5) * (1.0 / 256.0) +} + +/// A uniform in (0, 1) from the low 4 bits. +#[inline] +fn unit4(v: u32) -> f32 { + ((v & 15) as f32 + 0.5) * (1.0 / 16.0) +} + +/// Unit-variance, near-Gaussian noise for pixel (ix, iy): the sum of four uniforms. +#[inline] +fn gauss(ix: i32, iy: i32, seed: u32) -> f32 { + // four 8-bit uniforms from one hash (their sum is smooth enough at a pixel's scale) + let h = cell_hash(ix, iy, pcg(seed ^ 0x5bd1_e995)); + let sum = (h & 0xff) + ((h >> 8) & 0xff) + ((h >> 16) & 0xff) + (h >> 24); + ((sum as f32 + 2.0) * (1.0 / 256.0) - 2.0) * 1.732_050_8 +} + +#[cfg(test)] +mod tests { + use super::*; + + fn grain(amount: f64, size: f64, roughness: f64) -> Grain { + Grain { amount, size, roughness, ..Default::default() } + } + + /// Brightness deviations of the first channel over a `n × n` pixel patch for a render with + /// `ppl` px per long edge, at constant luminance `lum`. + fn patch(gp: &GrainParams, n: usize, lum: f32) -> Vec { + let ppl = gp.px_per_long; + (0..n * n).map(|i| gp.apply(((i % n) as f32 + 0.5) / ppl + 0.1003, ((i / n) as f32 + 0.5) / ppl + 0.1007, lum)[0]).collect() + } + + /// Autocorrelation of an `n × n` patch at lags 0..8, averaged over the horizontal and + /// vertical directions. + fn acf(v: &[f32], n: usize) -> [f64; 8] { + let (m, var) = stats(v); + let mut out = [0.0; 8]; + for (k, o) in out.iter_mut().enumerate() { + let mut c = 0.0; + for y in 0..n - k { + for x in 0..n - k { + let a = v[y * n + x] as f64 - m; + c += a * (v[y * n + x + k] as f64 - m) + a * (v[(y + k) * n + x] as f64 - m); + } + } + *o = c / (2 * (n - k) * (n - k)) as f64 / var.max(1e-30); + } + out + } + + /// The lag at which an autocorrelation first drops to `level` (linear between lags). + fn width_at(ac: &[f64; 8], level: f64) -> f64 { + for k in 1..8 { + if ac[k] < level { + return (k - 1) as f64 + (ac[k - 1] - level) / (ac[k - 1] - ac[k]); + } + } + 8.0 + } + + /// Calibration report (not a check): std (8-bit levels) and autocorrelation of the seven + /// Lightroom Classic settings at 6000 px, for the mapping or for looks given in `GRAIN_LOOK` + /// ("size rough radius_px shape halo halo_r level_scale;…"). + #[test] + #[ignore] + fn lrc_fit_report() { + let report = |name: &str, g: Grain, look: GrainLook| { + let gp = GrainParams::with_look(&g, 6000.0, &look).unwrap(); + let n = 256; + let tones: Vec = + [39.0f32, 63.0, 118.0, 179.0, 231.0].iter().map(|t| format!("{:5.2}", stats(&patch(&gp, n, t / 255.0)).1.sqrt() * 255.0)).collect(); + let v = patch(&gp, n, 118.0 / 255.0); + let ac = acf(&v, n); + if std::env::var("GRAIN_DOWN").is_ok() { + let big = patch(&gp, 640, 118.0 / 255.0); + let downs: Vec = [2usize, 4, 8, 16] + .iter() + .map(|k| { + let d = box_down(&big, 640, *k); + let sm = GrainParams::with_look(&g, 6000.0 / *k as f64, &look).unwrap(); + let small = patch(&sm, 640 / k, 118.0 / 255.0); + format!("{:.2}/{:.2}", stats(&d).1.sqrt() * 255.0, stats(&small).1.sqrt() * 255.0) + }) + .collect(); + println!("{name:<22} downscaled k2 k4 k8 k16 (export/small render): {}", downs.join(" ")); + } + println!( + "{name:<22} std {} mean {:+.2} | hm {:.2} 1/e {:.2} | ac {:.3} {:.3} {:.3} {:.3} | r {:.2}px wf {:.2}", + tones.join(" "), + stats(&v).0 * 255.0, + width_at(&ac, 0.5), + width_at(&ac, (-1f64).exp()), + ac[1], + ac[2], + ac[3], + ac[4], + look.radius * 6000.0, + gp.w_field + ); + }; + for (a, sz, r) in [ + (25.0, 25.0, 50.0), + (50.0, 25.0, 50.0), + (100.0, 25.0, 50.0), + (50.0, 0.0, 50.0), + (50.0, 100.0, 50.0), + (50.0, 25.0, 0.0), + (50.0, 25.0, 100.0), + ] { + report(&format!("A{a} S{sz} R{r}"), grain(a, sz, r), GrainLook::new(sz, r)); + } + if let Ok(spec) = std::env::var("GRAIN_LOOK") { + for item in spec.split(';').filter(|s| !s.trim().is_empty()) { + let v: Vec = item.split_whitespace().map(|x| x.parse().unwrap()).collect(); + let base = GrainLook::new(v[0], v[1]); + let look = GrainLook { radius: v[2] / 6000.0, shape: v[3], halo: v[4], halo_r: v[5], level: base.level * v[6] }; + report(&format!("S{} R{} {:?}", v[0], v[1], &v[2..]), grain(50.0, v[0], v[1]), look); + } + } + } + + /// Downscale report (not a check): grain sd and lag-1 correlation of a render at 6000/k vs the + /// 6000 px render box-downscaled by k. + #[test] + #[ignore] + fn downscale_report() { + for (size, rough, clumping) in + [(0.0, 50.0, 30.0), (0.0, 50.0, 80.0), (10.0, 50.0, 30.0), (25.0, 0.0, 30.0), (25.0, 50.0, 30.0), (60.0, 0.0, 30.0)] + { + let g = Grain { clumping, ..grain(60.0, size, rough) }; + let full = GrainParams::new(&g, 6000.0).unwrap(); + let mut line = format!("S{size} R{rough} C{clumping}:"); + for k in [2usize, 3, 4, 8] { + let small = GrainParams::new(&g, 6000.0 / k as f64).unwrap(); + let n = 96; + let big = patch(&full, n * k, 0.5); + let down = box_down(&big, n * k, k); + let sm = patch(&small, n, 0.5); + let ratio = (stats(&sm).1 / stats(&down).1).sqrt(); + line += &format!(" k{k} sd {ratio:.2} lag1 {:.2}/{:.2} wf {:.2}", lag1(&down, n), lag1(&sm, n), small.w_field); + } + println!("{line}"); + } + } + + fn stats(v: &[f32]) -> (f64, f64) { + let n = v.len() as f64; + let mean = v.iter().map(|x| *x as f64).sum::() / n; + let var = v.iter().map(|x| (*x as f64 - mean).powi(2)).sum::() / n; + (mean, var) + } + + fn corr(a: &[f32], b: &[f32]) -> f64 { + let ((ma, va), (mb, vb)) = (stats(a), stats(b)); + let c: f64 = a.iter().zip(b).map(|(x, y)| (*x as f64 - ma) * (*y as f64 - mb)).sum::() / a.len() as f64; + c / (va * vb).sqrt().max(1e-30) + } + + /// Correlation of horizontally adjacent pixels. + fn lag1(v: &[f32], n: usize) -> f64 { + let (m, var) = stats(v); + let mut c = 0.0; + for y in 0..n { + for x in 0..n - 1 { + c += (v[y * n + x] as f64 - m) * (v[y * n + x + 1] as f64 - m); + } + } + c / (n * (n - 1)) as f64 / var.max(1e-30) + } + + fn box_down(v: &[f32], n: usize, k: usize) -> Vec { + let m = n / k; + (0..m * m) + .map(|i| { + let (x, y) = (i % m, i / m); + let mut s = 0.0; + for dy in 0..k { + for dx in 0..k { + s += v[(y * k + dy) * n + x * k + dx]; + } + } + s / (k * k) as f32 + }) + .collect() + } + + /// The coverage field on a `n × n` grid with spacing `step` (grain units). + fn field(gp: &GrainParams, n: usize, step: f32, p: f32, seed: u32) -> Vec { + (0..n * n).map(|i| gp.field((i % n) as f32 * step + 3.1, (i / n) as f32 * step + 2.7, p, seed)).collect() + } + + #[test] + fn field_mean_is_the_expected_coverage_and_variance_matches_theory() { + for (size, variation, shape, clumping) in + [(25.0, 40.0, 50.0, 30.0), (80.0, 0.0, 0.0, 0.0), (60.0, 100.0, 100.0, 100.0), (25.0, 20.0, 80.0, 70.0)] + { + let g = Grain { size_variation: variation, clumping, ..grain(50.0, size, shape) }; + let gp = GrainParams::new(&g, 6000.0).unwrap(); + assert_eq!((gp.w_field, gp.w_noise), (1.0, 0.0), "explicit at full size"); + for p in [0.2f32, 0.5, 0.8] { + let v = field(&gp, 240, 0.9, p, 7); + let (mean, var) = stats(&v); + let sd = gp.coverage_std(p) as f64; + assert!((mean - p as f64).abs() < 0.03 + 0.15 * sd, "{g:?} p {p}: mean {mean}"); + assert!((var.sqrt() / sd - 1.0).abs() < 0.2, "{g:?} p {p}: sd {} vs theory {sd}", var.sqrt()); + } + } + } + + /// A small render shows the grain a full-size export would show downscaled to that size: the + /// same mean, a variance and a pixel-to-pixel correlation within tolerance, for both the + /// explicit field and the Gaussian stand-in (fine grain on a small render). + #[test] + fn small_render_matches_a_downscaled_full_size_render() { + for (size, clumping, k) in [(100.0, 30.0, 4usize), (60.0, 0.0, 3), (25.0, 30.0, 4), (0.0, 80.0, 3), (25.0, 30.0, 8)] { + let g = Grain { clumping, ..grain(60.0, size, 50.0) }; + let full = GrainParams::new(&g, 3000.0).unwrap(); + let small = GrainParams::new(&g, 3000.0 / k as f64).unwrap(); + let n = 120; + for lum in [0.25f32, 0.5, 0.8] { + let big = patch(&full, n * k, lum); + let down = box_down(&big, n * k, k); + let sm = patch(&small, n, lum); + let ((m0, v0), (m1, v1)) = (stats(&down), stats(&sm)); + let sd = v0.sqrt().max(v1.sqrt()); + assert!((m0 - m1).abs() < 0.3 * sd + 3e-4, "size {size} ÷{k} lum {lum}: mean {m0} vs {m1}"); + let ratio = (v1 / v0.max(1e-30)).sqrt(); + assert!((0.72..1.38).contains(&ratio), "size {size} ÷{k} lum {lum}: sd ratio {ratio} ({} vs {})", v1.sqrt(), v0.sqrt()); + let (c0, c1) = (lag1(&down, n), lag1(&sm, n)); + assert!((c0 - c1).abs() < 0.25, "size {size} ÷{k} lum {lum}: lag-1 correlation {c0} vs {c1}"); + } + } + } + + /// Grain on a flat grey chart rendered as the CPU renderer does ([`GrainParams::apply_band`]), + /// at a 6000 px long edge: `n × n` pixels of 8-bit tone `tone`. Returns the grain's standard + /// deviation in 8-bit levels and its autocorrelation. + fn chart(g: &Grain, tone: f32, n: usize) -> (f64, [f64; 8]) { + let gp = GrainParams::new(g, 6000.0).unwrap(); + let (mut gx, mut gy) = (Vec::with_capacity(n * n), Vec::with_capacity(n * n)); + for y in 0..n { + for x in 0..n { + gx.push((x as f32 + 0.5) / 6000.0 + 0.2); + gy.push((y as f32 + 0.5) / 6000.0 + 0.3); + } + } + let e = tone / 255.0; + let mut px = vec![[e; 3]; n * n]; + gp.apply_band(&gx, &gy, n, &mut px); + let v: Vec = px.iter().map(|c| (c[1] - e) * 255.0).collect(); + (stats(&v).1.sqrt(), acf(&v, n)) + } + + /// Measured from Lightroom Classic exports (Lightroom Classic 15.1.1, process version 15.4: + /// full-size 6000 × 4000 JPEGs of a chart of flat grey steps; `docs/grain.md`): Amount, Size, + /// Roughness; the grain's standard deviation in 8-bit levels in mid grey (118), the same from + /// 63 to 179 within 1 %; and the lag (pixels) at which its autocorrelation falls to ½. + const LRC_GRAIN: [(f64, f64, f64, f64, f64); 7] = [ + (25.0, 25.0, 50.0, 4.29, 1.13), + (50.0, 25.0, 50.0, 8.55, 1.13), + (100.0, 25.0, 50.0, 17.01, 1.14), + (50.0, 0.0, 50.0, 23.08, 0.43), + (50.0, 100.0, 50.0, 5.83, 3.38), + (50.0, 25.0, 0.0, 12.42, 0.86), + (50.0, 25.0, 100.0, 11.68, 1.54), + ]; + + /// The seven Lightroom Classic settings: the same strength (within 10 %) at every tone from 63 + /// to 179 (within 6 % of each other), and the same correlation width (within 10 %). + #[test] + fn grain_matches_lightroom_classic_exports() { + for (amount, size, rough, lrc_sd, lrc_width) in LRC_GRAIN { + let g = grain(amount, size, rough); + let (sd, ac) = chart(&g, 118.0, 160); + let width = width_at(&ac, 0.5); + assert!((sd / lrc_sd - 1.0).abs() < 0.1, "A{amount} S{size} R{rough}: sd {sd:.2} levels, Lightroom Classic {lrc_sd}"); + assert!((width / lrc_width - 1.0).abs() < 0.1, "A{amount} S{size} R{rough}: width {width:.2} px, Lightroom Classic {lrc_width}"); + let tones: Vec = [63.0, 179.0].iter().map(|t| chart(&g, *t, 120).0).collect(); + for (t, v) in [63, 179].iter().zip(&tones) { + assert!((v / sd - 1.0).abs() < 0.06, "A{amount} S{size} R{rough}: sd {v:.2} at {t} vs {sd:.2} at 118"); + } + } + // Roughness 0 is regular: negative autocorrelation two pixels out, as in Lightroom Classic + // (−0.15); Size 0 is finer than a pixel, with negative correlation at one (−0.17) + assert!(chart(&grain(50.0, 25.0, 0.0), 118.0, 160).1[2] < -0.08); + assert!(chart(&grain(50.0, 0.0, 50.0), 118.0, 160).1[1] < -0.08); + } + + #[test] + fn grain_is_equally_strong_at_every_tone_and_response_tilts_it() { + let sd = |gp: &GrainParams, lum: f32| stats(&patch(gp, 160, lum)).1.sqrt(); + let gp = GrainParams::new(&grain(50.0, 30.0, 50.0), 6000.0).unwrap(); + let (dark, mid, light) = (sd(&gp, 0.05), sd(&gp, 0.5), sd(&gp, 0.95)); + assert!((dark / mid - 1.0).abs() < 0.08 && (light / mid - 1.0).abs() < 0.08, "{dark} {mid} {light}"); + let shadows = GrainParams::new(&Grain { response: -100.0, ..grain(50.0, 30.0, 50.0) }, 6000.0).unwrap(); + let highlights = GrainParams::new(&Grain { response: 100.0, ..grain(50.0, 30.0, 50.0) }, 6000.0).unwrap(); + assert!(sd(&shadows, 0.15) > 1.5 * sd(&shadows, 0.85), "negative response favours the shadows"); + assert!(sd(&highlights, 0.85) > 1.5 * sd(&highlights, 0.15), "positive response favours the highlights"); + // Amount 50 at Size 30 at the reference resolution: about 0.03 (8 levels of 255) + assert!((0.025..0.035).contains(&mid), "mid-grey sd {mid}"); + } + + /// Colour 0: one grain layer, the same in every channel. Colour 100: an independent dye layer + /// per channel (channels uncorrelated). In between, partly shared. + #[test] + fn colour_grain_goes_from_one_layer_to_independent_dye_layers() { + let at = |color: f64| { + let gp = GrainParams::new(&Grain { color, ..grain(60.0, 60.0, 50.0) }, 3000.0).unwrap(); + let n = 90; + let mut ch = [Vec::new(), Vec::new(), Vec::new()]; + for i in 0..n * n { + let o = gp.apply(((i % n) as f32 + 0.5) / 3000.0, ((i / n) as f32 + 0.5) / 3000.0, 0.5); + for k in 0..3 { + ch[k].push(o[k]); + } + } + ch + }; + let mono = at(0.0); + assert!(mono[0] == mono[1] && mono[1] == mono[2], "mono grain is the same in every channel"); + let full = at(100.0); + assert!(corr(&full[0], &full[1]).abs() < 0.15 && corr(&full[1], &full[2]).abs() < 0.15, "dye layers are independent"); + let half = at(50.0); + let c = corr(&half[0], &half[2]); + assert!((0.3..0.7).contains(&c), "half colour: channels share half their grain ({c})"); + // the same strength per channel whatever the colour + let (s0, s1) = (stats(&mono[1]).1.sqrt(), stats(&full[1]).1.sqrt()); + assert!((s1 / s0 - 1.0).abs() < 0.2, "{s0} vs {s1}"); + } + + #[test] + fn the_field_changes_continuously_with_tone() { + let gp = GrainParams::new(&grain(50.0, 40.0, 50.0), 6000.0).unwrap(); + let mut worst = 0.0f32; + for i in 0..1500 { + let (x, y) = (i as f32 * 0.37, i as f32 * 0.11); + for k in 0..60 { + let p = 0.2 + k as f32 * 0.01; + let jump = (gp.field(x, y, p + 1e-4, 3) - gp.field(x, y, p, 3)).abs(); + worst = worst.max(jump); + } + } + assert!(worst < 0.02, "largest change for Δp = 1e-4: {worst}"); + } + + /// The band evaluation (CPU renders) gives what the per-pixel one (the GPU kernel's) gives, + /// for straight, rotated, flipped and transposed bands, with and without colour grain and + /// clumps. + #[test] + fn band_matches_per_pixel() { + for (size, ppl, color, clumping) in + [(25.0, 6000.0, 0.0, 30.0), (90.0, 2000.0, 70.0, 100.0), (0.0, 6000.0, 0.0, 0.0), (25.0, 900.0, 30.0, 60.0)] + { + let g = Grain { response: 30.0, color, clumping, size_variation: 70.0, ..grain(70.0, size, 80.0) }; + let gp = GrainParams::new(&g, ppl).unwrap(); + // (along a row, from row to row) per pixel, in output pixels + for ((ax, ay), (rx, ry)) in + [((1.0f32, 0.0f32), (0.0f32, 1.0f32)), ((0.97, 0.26), (-0.26, 0.97)), ((0.0, 1.0), (1.0, 0.0)), ((-0.6, 0.8), (0.8, 0.6))] + { + let (cols, rows) = (300, 7); + let mut gx = Vec::new(); + let mut gy = Vec::new(); + for row in 0..rows { + for k in 0..cols { + let (u, v) = (k as f32 + 0.5, row as f32 + 0.5); + gx.push(0.2 + (u * ax + v * rx) / ppl as f32); + gy.push(0.3 + (u * ay + v * ry) / ppl as f32); + } + } + let mut px: Vec<[f32; 3]> = (0..cols * rows).map(|k| [0.1 + 0.8 * (k % 97) as f32 / 97.0; 3]).collect(); + let want: Vec<[f32; 3]> = px + .iter() + .enumerate() + .map(|(k, c)| { + let g = gp.apply(gx[k], gy[k], 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]); + [c[0] + g[0], c[1] + g[1], c[2] + g[2]] + }) + .collect(); + gp.apply_band(&gx, &gy, cols, &mut px); + for k in 0..cols * rows { + for ch in 0..3 { + assert!((px[k][ch] - want[k][ch]).abs() < 1e-4, "size {size} dir ({ax}, {ay}) px {k}: {:?} vs {:?}", px[k], want[k]); + } + } + } + } + } + + /// Settings saved before the newer grain controls existed (catalog, XMP, presets) load with + /// their defaults and render the same grain as settings that name them at those defaults. + #[test] + fn settings_without_the_new_fields_are_back_compatible() { + let old: lightcraft_develop::DevelopSettings = + serde_json::from_value(serde_json::json!({"grain": {"amount": 20.0, "size": 30.0, "roughness": 60.0, "seed": 9}})).unwrap(); + let explicit = Grain { amount: 20.0, size: 30.0, roughness: 60.0, seed: 9, ..Grain::default() }; + assert_eq!(old.grain, explicit); + assert_eq!((old.grain.color, old.grain.response, old.grain.size_variation, old.grain.clumping), (0.0, 0.0, 40.0, 30.0)); + let (a, b) = (GrainParams::new(&old.grain, 3000.0).unwrap(), GrainParams::new(&explicit, 3000.0).unwrap()); + assert_eq!(a, b); + assert_eq!((a.color, a.gamma), (0.0, 1.0), "no colour grain, midtone response"); + } + + /// Through the whole pipeline: a 1/4-size render of a flat grey photo shows the grain of the + /// full-size render box-downscaled to that size (same strength within 15 %), for grain that + /// stays explicit and for grain that turns into per-pixel noise at the small size. + #[test] + fn small_pipeline_render_matches_downscaled_full_render() { + use crate::{RenderRequest, SourceInfo, render}; + use lightcraft_raster::Rgb32f; + // big enough that the small render's grain stands well above 8-bit rounding + let (w, h) = (2400, 1800); + let src = Rgb32f::filled(w, h, [0.18, 0.18, 0.18]); + let info = SourceInfo::default(); + for size in [50.0, 100.0] { + let s = lightcraft_develop::DevelopSettings { grain: grain(100.0, size, 50.0), ..Default::default() }; + let full = render(&src, &info, &s, &RenderRequest::fit(w, h)).image; + let small = render(&src, &info, &s, &RenderRequest::fit(w / 4, h / 4)).image; + assert_eq!((small.width, small.height), (w / 4, h / 4)); + let lum = |p: &[u8; 4]| (p[0] as f32 + p[1] as f32 + p[2] as f32) / 3.0; + let down: Vec = (0..(w / 4) * (h / 4)) + .map(|i| { + let (x, y) = (i % (w / 4), i / (w / 4)); + let mut acc = 0.0; + for dy in 0..4 { + for dx in 0..4 { + acc += lum(&full.data[(y * 4 + dy) * w + x * 4 + dx]); + } + } + acc / 16.0 + }) + .collect(); + let sm: Vec = small.data.iter().map(lum).collect(); + let ((m0, v0), (m1, v1)) = (stats(&down), stats(&sm)); + let ratio = (v1 / v0).sqrt(); + assert!((m0 - m1).abs() < 0.5, "size {size}: mean {m0} vs {m1}"); + assert!((0.85..1.15).contains(&ratio), "size {size}: grain sd {} (small) vs {} (downscaled)", v1.sqrt(), v0.sqrt()); + assert!(v0.sqrt() > 0.3, "size {size}: visible grain ({})", v0.sqrt()); + } + } + + /// Every control visibly changes the particles, and the seed is the pattern: another seed is + /// an unrelated pattern, the same seed at another render size is the same particles, and + /// Size Variation, Shape and Clumping change the particles without moving where they are. + #[test] + fn each_control_changes_the_particles() { + let at = |g: Grain, ppl: f64| field(&GrainParams::new(&g, ppl).unwrap(), 150, 0.45, 0.5, g.seed); + let base = Grain { size_variation: 40.0, clumping: 30.0, seed: 3, ..grain(50.0, 100.0, 50.0) }; + let reference = at(base, 6000.0); + assert!(corr(&reference, &at(Grain { seed: 4, ..base }, 6000.0)).abs() < 0.1, "seed 4 is another pattern"); + assert!(corr(&reference, &at(base, 9000.0)) > 0.75, "a bigger render keeps the particles"); + for (what, lo, hi) in [ + ("size variation", Grain { size_variation: 0.0, ..base }, Grain { size_variation: 100.0, ..base }), + ("shape", Grain { roughness: 0.0, ..base }, Grain { roughness: 100.0, ..base }), + ("clumping", Grain { clumping: 0.0, ..base }, Grain { clumping: 100.0, ..base }), + ] { + let c = corr(&at(lo, 6000.0), &at(hi, 6000.0)); + assert!(c < 0.9, "{what} changes the particles ({c})"); + } + // Shape: irregular, elongated particles have more edge for the same coverage + let edges = |v: &[f32]| { + let n = 150; + let mut e = 0; + for i in 0..n * n - 1 { + if i % n != n - 1 && (v[i] > 0.5) != (v[i + 1] > 0.5) { + e += 1; + } + } + e + }; + // (the shape alone: Roughness also scales the grains and adds a halo) + let shaped = |shape: f64| { + let look = GrainLook { shape, halo: 0.0, ..GrainLook::new(base.size, 50.0) }; + field(&GrainParams::with_look(&base, 6000.0, &look).unwrap(), 150, 0.45, 0.5, base.seed) + }; + let (round, rough) = (edges(&shaped(0.0)), edges(&shaped(1.0))); + assert!(rough as f64 > round as f64 * 1.05, "shape 100 has more edge than shape 0 ({rough} vs {round})"); + // Clumping: particles gather, so coverage varies more between neighbourhoods + let blocks = |v: &[f32]| stats(&box_down(v, 150, 10)).1; + let (loose, clumped) = (blocks(&at(Grain { clumping: 0.0, ..base }, 6000.0)), blocks(&at(Grain { clumping: 100.0, ..base }, 6000.0))); + assert!(clumped > loose * 1.2, "clumps make coverage patchier ({clumped} vs {loose})"); + } + + /// Hostile settings (NaN, infinities, far out of range) and positions never panic and give + /// finite output. + #[test] + fn extreme_values_never_panic() { + let vals = [f64::NAN, f64::INFINITY, -1e300, 0.0, 100.0]; + for &a in &[f64::NAN, 1e300, 100.0] { + for &v in &vals { + for ppl in [f64::NAN, 0.0, 1.0, 1e12, 6000.0] { + let g = Grain { amount: a, size: v, roughness: v, seed: u32::MAX, color: v, response: v, size_variation: v, clumping: v }; + let Some(gp) = GrainParams::new(&g, ppl) else { continue }; + for (x, y, l) in [(0.0, 0.0, 0.5), (f32::NAN, 1.0, f32::NAN), (f32::INFINITY, -1e30, 2.0), (1e9, -1e9, -1.0)] { + let o = gp.apply(x, y, l); + assert!(o.iter().all(|c| c.is_finite()), "{g:?} {ppl} {x} {y} {l} → {o:?}"); + } + } + } + } + assert!(GrainParams::new(&grain(f64::NAN, 25.0, 50.0), 1000.0).is_none()); + assert!(GrainParams::new(&grain(-5.0, 25.0, 50.0), 1000.0).is_none()); + } +} diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs index d56e8fe82de..e7acce613b9 100644 --- a/crates/pipeline/src/lib.rs +++ b/crates/pipeline/src/lib.rs @@ -31,6 +31,7 @@ pub mod curve; pub mod dust; pub mod finish; pub mod geometry; +pub mod grain; pub mod local; pub mod local_tone; pub mod lut; diff --git a/crates/pipeline/src/local.rs b/crates/pipeline/src/local.rs index 6d09cf7557b..ea121d60bee 100644 --- a/crates/pipeline/src/local.rs +++ b/crates/pipeline/src/local.rs @@ -375,7 +375,7 @@ pub fn base_detail_radius(px_per_long: f64) -> usize { 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/tests/it/grain_process.rs b/crates/pipeline/tests/it/grain_process.rs new file mode 100644 index 00000000000..88586b9225a --- /dev/null +++ b/crates/pipeline/tests/it/grain_process.rs @@ -0,0 +1,117 @@ +//! The grain model follows the photo's process (`docs/process-versions.md`): V1 and V2 keep the +//! value-noise grain they always rendered with; the particle grain comes with V3. +//! +//! The legacy check is AlexChambers' reproduction from the review of PR #1060: it renders a gray +//! frame through the public CPU API and compares it with the value-noise formula as it stood before +//! the particle grain landed. + +use lightcraft_color::transfer::{linear_to_srgb, srgb_to_linear}; +use lightcraft_develop::{DevelopSettings, Process, ProcessVersion}; +use lightcraft_pipeline::finish::GrainModel; +use lightcraft_pipeline::{DeepSamples, OutputDepth, RenderRequest, SourceInfo, render}; +use lightcraft_raster::Rgb32f; + +/// The value-noise grain formula of processes V1 and V2, written out independently of the +/// renderer. +fn old_noise(x: f32, y: f32, seed: u32) -> f32 { + let (x0, y0) = (x.floor(), y.floor()); + let (fx, fy) = (x - x0, y - y0); + let h = |i: i32, j: i32| { + let mut v = (i as u32).wrapping_mul(0x8da6_b343) ^ (j as u32).wrapping_mul(0xd816_3841) ^ seed.wrapping_mul(0xcb1a_b31f); + v ^= v >> 13; + v = v.wrapping_mul(0x5bd1_e995); + v ^= v >> 15; + (v & 0xffff) as f32 / 32768.0 - 1.0 + }; + let (i, j) = (x0 as i32, y0 as i32); + let (u, v) = (fx * fx * (3.0 - 2.0 * fx), fy * fy * (3.0 - 2.0 * fy)); + let a = h(i, j) + (h(i + 1, j) - h(i, j)) * u; + let b = h(i, j + 1) + (h(i + 1, j + 1) - h(i, j + 1)) * u; + a + (b - a) * v +} + +/// Largest difference (linear, and display-encoded levels of 255) between rendering `s` on a +/// 128 × 96 gray frame and the value-noise grain formula applied to the grain-free render. +fn difference_from_value_noise(s: &DevelopSettings) -> (f32, f32) { + let (w, h) = (128usize, 96usize); + let src = Rgb32f::filled(w, h, [0.18; 3]); + let info = SourceInfo::default(); + let req = RenderRequest { depth: OutputDepth::F32Linear, ..RenderRequest::fit(w, h) }; + let got = render(&src, &info, s, &req).deep.unwrap(); + let mut plain = s.clone(); + plain.grain.amount = 0.0; + let before = render(&src, &info, &plain, &req).deep.unwrap(); + let (DeepSamples::F32(got), DeepSamples::F32(before)) = (got.samples, before.samples) else { + panic!("float output"); + }; + let cell = ((0.0006 + (s.grain.size / 100.0) as f32 * 0.0024) * w as f32).max(0.6); + let sc = w as f32 / cell; + let rough = (s.grain.roughness / 100.0) as f32; + let amount = (s.grain.amount / 100.0) as f32 * 0.13; + let (mut max, mut byte_max) = (0.0f32, 0.0f32); + for y in 0..h { + for x in 0..w { + let i = (y * w + x) * 3; + let e = [linear_to_srgb(before[i]), linear_to_srgb(before[i + 1]), linear_to_srgb(before[i + 2])]; + let gx = (x as f32 + 0.5) / w as f32; + let gy = (y as f32 + 0.5) / w as f32; + let g = old_noise(gx * sc, gy * sc, s.grain.seed) * (1.0 - rough * 0.5) + + old_noise(gx * sc * 2.3, gy * sc * 2.3, s.grain.seed ^ 0x55) * rough * 0.7; + let lum = 0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2]; + let k = amount * g * (0.35 + 2.6 * lum * (1.0 - lum)); + for c in 0..3 { + let want = srgb_to_linear((e[c] + k).clamp(0.0, 1.0)); + max = max.max((want - got[i + c]).abs()); + byte_max = byte_max.max((linear_to_srgb(want) - linear_to_srgb(got[i + c])).abs() * 255.0); + } + } + } + (max, byte_max) +} + +fn grain_json(process: Option) -> DevelopSettings { + let mut j = serde_json::json!({ "grain": { "amount": 50.0, "size": 25.0, "roughness": 50.0, "seed": 7 } }); + if let Some(p) = process { + j["process"] = p.into(); + } + DevelopSettings::from_json(&j).unwrap() +} + +/// Review of PR #1060: settings saved before process versions (V1) render with exactly the grain +/// they always had. Failed with the particle grain on every process (16.5 levels of 255 apart). +#[test] +fn legacy_process_keeps_its_grain() { + let s = grain_json(None); + assert_eq!(s.process, ProcessVersion::V1); + let (max, levels) = difference_from_value_noise(&s); + eprintln!("V1: max linear difference {max}, max encoded difference {levels} levels"); + assert!(max < 1e-5, "V1 grain changed from the established renderer: {max}"); +} + +#[test] +fn process_v2_keeps_the_value_noise_grain() { + let s = grain_json(Some(2)); + assert_eq!(s.process.process(), Process::V2); + let (max, _) = difference_from_value_noise(&s); + assert!(max < 1e-5, "V2 grain changed from the established renderer: {max}"); +} + +/// V3 (and new photos, which get the latest process) render the particle grain. +#[test] +fn process_v3_renders_particle_grain() { + let s = grain_json(Some(3)); + assert_eq!(s.process.process(), Process::V3); + assert!(matches!(GrainModel::new(&s, 3000.0), Some(GrainModel::Particles(_)))); + let (_, levels) = difference_from_value_noise(&s); + assert!(levels > 2.0, "V3 should not render the value-noise grain ({levels} levels apart)"); + + for p in [None, Some(2)] { + assert!(matches!(GrainModel::new(&grain_json(p), 3000.0), Some(GrainModel::Value(_))), "{p:?}"); + } + let new = DevelopSettings { grain: grain_json(None).grain, ..DevelopSettings::default() }; + assert_eq!(new.process, ProcessVersion::LATEST); + assert!(matches!(GrainModel::new(&new, 3000.0), Some(GrainModel::Particles(_)))); + // no grain on any process when Amount is 0 + let none = DevelopSettings::default(); + assert_eq!(GrainModel::new(&none, 3000.0), None); +} diff --git a/crates/pipeline/tests/it/main.rs b/crates/pipeline/tests/it/main.rs index 95fc179bfaa..56a0861a986 100644 --- a/crates/pipeline/tests/it/main.rs +++ b/crates/pipeline/tests/it/main.rs @@ -1,3 +1,4 @@ //! The integration tests, one module per file, linked into one test binary. +mod grain_process; mod preview_save; diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bba91d2f717..56c11bdc110 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -76,6 +76,7 @@ impl LightcraftApp { missing: Default::default(), synthetic_mods: egui::Modifiers::NONE, synthetic_mods_release: false, + pointer_repair: crate::pointer_repair::PointerRepair::default(), host_mods: egui::Modifiers::NONE, styled: false, font_language: i18n::Locale::En, diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index 8234b78fd48..718df090bee 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -125,7 +125,15 @@ impl LightcraftApp { /// The hook also runs before a hidden logic-only tick, so it injects at most one batch and /// keeps that batch in flight until a completed UI pass consumed it. It never injects while /// the fonts are not installed (the pass would draw nothing and the events would be lost). + /// First, mouse-button releases the window integration dropped are put back (`pointer_repair`), + /// over the host's own events: before a prompt's filter drops them, so a release under a prompt + /// still counts as one and the next press after it gets no extra release. pub fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { + self.pointer_repair.repair(raw); + self.inject_synthetic(ctx, raw); + } + + fn inject_synthetic(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { let file = |p: &String| (!p.is_empty()).then(|| std::path::PathBuf::from(p)); if !self.drop_pending.is_empty() { raw.dropped_files = std::mem::take(&mut self.drop_pending) @@ -186,8 +194,9 @@ impl LightcraftApp { if self.synthetic.is_empty() { return; } - let pointer = - |e: &egui::Event| matches!(e, egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } | egui::Event::MouseWheel { .. }); + let pointer = |e: &egui::Event| { + matches!(e, egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } | egui::Event::MouseWheel { .. } | egui::Event::PointerGone) + }; let n = if pointer(&self.synthetic[0]) { 1 } else { diff --git a/crates/ui-egui/src/headless/tests.rs b/crates/ui-egui/src/headless/tests.rs index 7ba584faf02..ec500e75a2f 100644 --- a/crates/ui-egui/src/headless/tests.rs +++ b/crates/ui-egui/src/headless/tests.rs @@ -3096,6 +3096,82 @@ fn slider_nudge_and_pick_advance() { assert_ne!(h.app.session.active(), Some(first), "advanced"); } +/// A slider drag that ends just past the window's edge (the integration drops that release) +/// doesn't keep the slider captured: back over the photo the slider stays put, and a click +/// on the photo zooms as usual (the Grain sliders at the bottom of the panel made it easy). +#[test] +fn a_slider_released_outside_the_window_lets_go() { + let mut h = demo([1300.0, 1600.0]); + let t = Duration::from_secs(10); + h.request("ui.set", json!({"view": "detail", "right": "edit"}), t); + let r = h.request("engine.execute", json!({"command": "develop.set", "params": {"values": {"grain.amount": 40.0}}}), t); + assert_eq!(r["ok"], true, "{r}"); + h.app.ui.open_sections = vec!["effects".to_string()]; + h.settle(SETTLE); + let amount = |h: &Headless| h.app.session.develop_of(h.app.session.active().unwrap()).unwrap().grain.amount; + let slider = h.app.widgets.iter().find(|(id, _)| id == "slider:grain.amount").map(|(_, r)| *r).expect("the Grain slider"); + let canvas = h.app.canvas_rect.expect("the photo").center(); + assert!(matches!(h.app.ui.zoom, crate::state::Zoom::Fit)); + // drag the slider, then off the bottom of the window, where the button goes up unseen + let (a, b) = (slider.center(), slider.center() + egui::vec2(40.0, 0.0)); + let edge = egui::pos2(b.x, 1599.0); + let m = egui::Modifiers::NONE; + // (the window system's own events, one frame each: the repair works on those, before anything is injected) + let host = |h: &mut Headless, e: egui::Event| { + h.events.push(e); + h.step(); + }; + host(&mut h, egui::Event::PointerMoved(a)); + host(&mut h, egui::Event::PointerButton { pos: a, button: egui::PointerButton::Primary, pressed: true, modifiers: m }); + host(&mut h, egui::Event::PointerMoved(b)); + host(&mut h, egui::Event::PointerMoved(edge)); + host(&mut h, egui::Event::PointerGone); + h.settle(SETTLE); + let dragged = amount(&h); + assert!(dragged > 40.0, "the drag moved the slider ({dragged})"); + // back over the photo, and click it + host(&mut h, egui::Event::PointerMoved(canvas + egui::vec2(5.0, 0.0))); + h.settle(SETTLE); + // (without the repair egui still drags the slider here: the ↔ cursor sticks and the + // drag's undo step stays open) + assert_eq!(h.view.ctx.dragged_id(), None, "nothing is dragged once the pointer is back"); + assert!(h.app.session.interaction.is_none(), "the drag's undo step is closed"); + assert_ne!(h.last_cursor, egui::CursorIcon::ResizeHorizontal, "the slider's cursor is gone"); + h.app.synthetic.extend([ + egui::Event::PointerMoved(canvas), + egui::Event::PointerButton { pos: canvas, button: egui::PointerButton::Primary, pressed: true, modifiers: m }, + egui::Event::PointerButton { pos: canvas, button: egui::PointerButton::Primary, pressed: false, modifiers: m }, + ]); + h.settle(SETTLE); + assert_eq!(amount(&h), dragged, "the slider let go"); + assert!(!matches!(h.app.ui.zoom, crate::state::Zoom::Fit), "the click on the photo zoomed in"); +} + +/// The Effects panel's grain sliders include colour grain, the tone response, size variation, +/// clumping and the seed, which drive the photo's settings like any develop control. +#[test] +fn grain_colour_and_response_sliders() { + // tall enough for the Effects panel's last slider without scrolling + let mut h = demo([1300.0, 1600.0]); + let t = Duration::from_secs(10); + h.request("ui.set", json!({"view": "detail", "right": "edit"}), t); + let r = h.request("engine.execute", json!({"command": "develop.set", "params": {"values": {"grain.amount": 40.0}}}), t); + assert_eq!(r["ok"], true, "{r}"); + // only the Effects section open, so its sliders are on screen + h.app.ui.open_sections = vec!["effects".to_string()]; + h.settle(SETTLE); + let grain = |h: &Headless| h.app.session.develop_of(h.app.session.active().unwrap()).unwrap().grain; + for (id, text) in [("grain.response", "-30"), ("grain.color", "25"), ("grain.sizeVariation", "70"), ("grain.clumping", "80"), ("grain.seed", "7")] + { + assert_eq!(h.request("ui.clickWidget", json!({"id": format!("sliderValue:{id}")}), t)["ok"], true, "{id} is in the panel"); + h.request("ui.text", json!({"text": text}), t); + h.request("ui.key", json!({"key": "Enter"}), t); + h.step(); + } + let g = grain(&h); + assert_eq!((g.amount, g.color, g.response, g.size_variation, g.clumping, g.seed), (40.0, 25.0, -30.0, 70.0, 80.0, 7)); +} + /// Click a slider's value and type one (issue #322): Return sets it as one undo step, Esc /// keeps the old value, and the keys typed don't reach the shortcuts (1 = one star). #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7a67d87109f..1bfdb7cc7c7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -36,6 +36,7 @@ mod missing_sweep; mod model_setup; pub mod panels; pub mod pick; +mod pointer_repair; pub mod recheck; pub mod region; pub mod reload; @@ -252,6 +253,8 @@ pub struct LightcraftApp { synthetic_mods: egui::Modifiers, /// Clear `synthetic_mods` on the next frame. synthetic_mods_release: bool, + /// Puts back mouse-button releases the window integration dropped (see `pointer_repair`). + pointer_repair: pointer_repair::PointerRepair, /// The host's last reported physical modifier state (`ModifiersChanged`), restored after a /// synthetic gesture releases instead of unconditionally announcing `NONE`. host_mods: egui::Modifiers, diff --git a/crates/ui-egui/src/panels/edit.rs b/crates/ui-egui/src/panels/edit.rs index 31b1303bf5d..8dfce7cb3ed 100644 --- a/crates/ui-egui/src/panels/edit.rs +++ b/crates/ui-egui/src/panels/edit.rs @@ -285,8 +285,10 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { control(app, ui, d, c, enabled); } sub_title(ui, crate::i18n::tr("Grain")); - for c in ["grain.amount", "grain.size", "grain.roughness"] { - control(app, ui, d, c, c == "grain.amount" || d.grain.amount != 0.0); + for c in + ["grain.amount", "grain.size", "grain.sizeVariation", "grain.roughness", "grain.clumping", "grain.color", "grain.response", "grain.seed"] + { + control(app, ui, d, c, grain_control_enabled(d, c)); } ui.add_space(8.0); }); @@ -373,3 +375,41 @@ pub fn show(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let _ = app.run("develop.reset", json!({})); } } + +/// Whether a Grain slider can be moved: Amount always; the rest once there is grain. Size +/// Variation, Clumping, Color and Response shape the particle grain of process V3; a photo on V1 +/// or V2 keeps its value-noise grain, which they don't act on, so they stay disabled there. +fn grain_control_enabled(d: &DevelopSettings, id: &str) -> bool { + if id == "grain.amount" { + return true; + } + let particle_only = matches!(id, "grain.sizeVariation" | "grain.clumping" | "grain.color" | "grain.response"); + d.grain.amount != 0.0 && (!particle_only || d.process.process() >= lightcraft_develop::Process::V3) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn particle_only_grain_sliders_are_disabled_before_process_v3() { + use lightcraft_develop::{Process, ProcessVersion}; + let all = ["grain.size", "grain.sizeVariation", "grain.roughness", "grain.clumping", "grain.color", "grain.response", "grain.seed"]; + let particle_only = ["grain.sizeVariation", "grain.clumping", "grain.color", "grain.response"]; + let mut d = DevelopSettings::default(); + assert!(grain_control_enabled(&d, "grain.amount")); + assert!(all.iter().all(|c| !grain_control_enabled(&d, c)), "no grain: only Amount moves"); + d.grain.amount = 30.0; + assert_eq!(d.process.process(), Process::LATEST); + assert!(all.iter().all(|c| grain_control_enabled(&d, c)), "V3: every grain slider moves"); + for p in [Process::V1, Process::V2] { + d.process = p.version(); + for c in all { + assert_eq!(grain_control_enabled(&d, c), !particle_only.contains(&c), "{p:?} {c}"); + } + assert!(grain_control_enabled(&d, "grain.amount")); + } + d.process = ProcessVersion::legacy(); + assert!(!grain_control_enabled(&d, "grain.clumping"), "settings saved without a process are V1"); + } +} diff --git a/crates/ui-egui/src/pointer_repair.rs b/crates/ui-egui/src/pointer_repair.rs new file mode 100644 index 00000000000..12d250c4989 --- /dev/null +++ b/crates/ui-egui/src/pointer_repair.rs @@ -0,0 +1,240 @@ +//! Restores mouse-button releases that egui-winit drops. +//! +//! egui-winit forwards a button event only while it knows where the pointer is, and it forgets +//! that when the cursor leaves the window (`CursorLeft` → `PointerGone`). A release that comes +//! after the cursor left, with no move in between, is dropped. Ending a slider drag just past the +//! window's edge is enough. egui then believes the button is still down: the slider stays +//! captured, follows the cursor when it comes back, and takes every later press, so clicks on the +//! photo stop working. +//! +//! [`PointerRepair::repair`] runs over each frame's raw events before egui sees them and puts the +//! release back: +//! - **Back inside:** a pointer that left during a press and comes back inside the window without +//! having moved outside was released out there (while the button is held the window keeps +//! receiving moves outside it), so it is released where it left. +//! - **Press while down:** a press of a button egui still believes is down gets its missing +//! release first. + +/// The pointer buttons egui knows (`egui::PointerButton` as an index). +const BUTTONS: usize = egui::NUM_POINTER_BUTTONS; + +/// What [`PointerRepair::repair`] remembers between frames. +#[derive(Debug, Default)] +pub struct PointerRepair { + /// Buttons down as far as egui knows (pressed, no release seen). + down: [bool; BUTTONS], + /// Where the pointer was last seen. + last: Option, + /// Where the pointer left the window while a button was down (`PointerGone`). + left_at: Option, + /// The window's area in points (the last one the integration announced). + screen: Option, +} + +fn index(b: egui::PointerButton) -> usize { + match b { + egui::PointerButton::Primary => 0, + egui::PointerButton::Secondary => 1, + egui::PointerButton::Middle => 2, + egui::PointerButton::Extra1 => 3, + egui::PointerButton::Extra2 => 4, + } +} + +fn button(i: usize) -> Option { + [ + egui::PointerButton::Primary, + egui::PointerButton::Secondary, + egui::PointerButton::Middle, + egui::PointerButton::Extra1, + egui::PointerButton::Extra2, + ] + .get(i) + .copied() +} + +impl PointerRepair { + /// Puts back the releases egui-winit dropped in `raw` (see the module docs). + pub fn repair(&mut self, raw: &mut egui::RawInput) { + if let Some(r) = raw.screen_rect { + self.screen = Some(r); + } + if !raw.events.iter().any(|e| matches!(e, egui::Event::PointerMoved(_) | egui::Event::PointerButton { .. } | egui::Event::PointerGone)) { + return; + } + let modifiers = egui::Modifiers::NONE; + let events = std::mem::take(&mut raw.events); + // for each event, the buttons released by a real event later in this batch + let mut released_later = vec![[false; BUTTONS]; events.len()]; + let mut seen = [false; BUTTONS]; + for (e, later) in events.iter().zip(released_later.iter_mut()).rev() { + *later = seen; + if let egui::Event::PointerButton { button: b, pressed: false, .. } = e + && let Some(s) = seen.get_mut(index(*b)) + { + *s = true; + } + } + let mut out = Vec::with_capacity(events.len() + 1); + for (e, later) in events.into_iter().zip(released_later) { + match e { + egui::Event::PointerMoved(p) => { + if let Some(at) = self.left_at.take() { + let inside = self.screen.is_none_or(|r| r.contains(p)); + if inside { + // back without a move outside: the button went up out there, unless its own + // release is still to come in this batch + self.release_all(at, modifiers, &later, &mut out); + } + } + self.last = Some(p); + out.push(e); + } + egui::Event::PointerGone => { + if self.down.iter().any(|d| *d) { + self.left_at = self.last; + } + out.push(e); + } + egui::Event::PointerButton { pos, button: b, pressed, modifiers: m } => { + let i = index(b); + if pressed { + if self.down.get(i).copied().unwrap_or(false) { + out.push(egui::Event::PointerButton { pos, button: b, pressed: false, modifiers: m }); + } + self.left_at = None; + } + if let Some(d) = self.down.get_mut(i) { + *d = pressed; + } + self.last = Some(pos); + out.push(e); + } + other => out.push(other), + } + } + raw.events = out; + } + + /// Whether a button is down as far as the host's events said (tests). + #[cfg(test)] + pub(crate) fn any_down(&self) -> bool { + self.down.iter().any(|d| *d) + } + + /// Releases, where the pointer left (`at`), every button still down but those released later in the batch + /// (`released_later`): those keep their real release. The pointer is moved there first only when a release + /// is missing. + fn release_all(&mut self, at: egui::Pos2, modifiers: egui::Modifiers, released_later: &[bool; BUTTONS], out: &mut Vec) { + let missing = |(d, later): (&bool, &bool)| *d && !*later; + if !self.down.iter().zip(released_later).any(missing) { + return; + } + out.push(egui::Event::PointerMoved(at)); + for (i, (d, later)) in self.down.iter_mut().zip(released_later).enumerate() { + if *d + && !*later + && let Some(b) = button(i) + { + *d = false; + out.push(egui::Event::PointerButton { pos: at, button: b, pressed: false, modifiers }); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use egui::{Event, PointerButton, Pos2, Rect, pos2}; + + fn press(p: Pos2, pressed: bool) -> Event { + Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE } + } + + fn frame(r: &mut PointerRepair, events: Vec) -> Vec { + let mut raw = egui::RawInput { screen_rect: Some(Rect::from_min_max(pos2(0.0, 0.0), pos2(800.0, 600.0))), events, ..Default::default() }; + r.repair(&mut raw); + raw.events + } + + fn releases(events: &[Event]) -> usize { + events.iter().filter(|e| matches!(e, Event::PointerButton { pressed: false, .. })).count() + } + + /// A batch that comes back inside and then carries the button's real release: that release is kept, and no + /// release (nor move to where the pointer left) is made up before it. Another button still down with no + /// release to come is still released (CodeRabbit on #1060). + #[test] + fn a_real_release_later_in_the_batch_is_not_made_up_before_it() { + let mut r = PointerRepair::default(); + frame(&mut r, vec![Event::PointerMoved(pos2(700.0, 590.0)), press(pos2(700.0, 590.0), true)]); + let back = frame(&mut r, vec![Event::PointerGone, Event::PointerMoved(pos2(300.0, 300.0)), press(pos2(300.0, 300.0), false)]); + assert_eq!(back, vec![Event::PointerGone, Event::PointerMoved(pos2(300.0, 300.0)), press(pos2(300.0, 300.0), false)]); + assert!(!r.any_down()); + // two buttons down, only the secondary's release to come: the primary is released where it left + let secondary = + |pressed| Event::PointerButton { pos: pos2(700.0, 590.0), button: PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }; + frame(&mut r, vec![Event::PointerMoved(pos2(700.0, 590.0)), press(pos2(700.0, 590.0), true), secondary(true)]); + let back = frame(&mut r, vec![Event::PointerGone, Event::PointerMoved(pos2(300.0, 300.0)), secondary(false)]); + assert_eq!( + back, + vec![ + Event::PointerGone, + Event::PointerMoved(pos2(700.0, 590.0)), + press(pos2(700.0, 590.0), false), + Event::PointerMoved(pos2(300.0, 300.0)), + secondary(false), + ] + ); + assert!(!r.any_down()); + } + + /// The case egui-winit gets wrong: a drag that ends just past the window's edge. + #[test] + fn a_release_lost_outside_the_window_is_restored_when_the_pointer_comes_back() { + let mut r = PointerRepair::default(); + frame(&mut r, vec![Event::PointerMoved(pos2(700.0, 590.0)), press(pos2(700.0, 590.0), true)]); + frame(&mut r, vec![Event::PointerMoved(pos2(720.0, 599.0)), Event::PointerGone]); + // (the release happened outside and was dropped) … the cursor comes back over the photo + let back = frame(&mut r, vec![Event::PointerMoved(pos2(300.0, 300.0))]); + assert_eq!(releases(&back), 1, "released: {back:?}"); + assert!( + matches!(back.get(1), Some(Event::PointerButton { pos, pressed: false, .. }) if *pos == pos2(720.0, 599.0)), + "where it left, before the move inside: {back:?}" + ); + // a click on the photo now is a click + let click = frame(&mut r, vec![press(pos2(300.0, 300.0), true), press(pos2(300.0, 300.0), false)]); + assert_eq!(click.len(), 2, "{click:?}"); + } + + /// A drag that leaves the window and comes back while the button is held keeps going. + #[test] + fn a_drag_held_outside_the_window_is_not_ended() { + let mut r = PointerRepair::default(); + frame(&mut r, vec![Event::PointerMoved(pos2(700.0, 590.0)), press(pos2(700.0, 590.0), true)]); + frame(&mut r, vec![Event::PointerGone]); + // the window keeps getting moves outside it while the button is held (mouse capture) + let outside = frame(&mut r, vec![Event::PointerMoved(pos2(760.0, 640.0)), Event::PointerMoved(pos2(500.0, 580.0))]); + assert_eq!(releases(&outside), 0, "{outside:?}"); + let up = frame(&mut r, vec![press(pos2(500.0, 580.0), false)]); + assert_eq!(releases(&up), 1); + } + + /// Whatever went missing, a new press first ends the stale one. + #[test] + fn a_press_while_egui_thinks_the_button_is_down_is_preceded_by_a_release() { + let mut r = PointerRepair::default(); + frame(&mut r, vec![press(pos2(10.0, 10.0), true)]); + let again = frame(&mut r, vec![press(pos2(50.0, 50.0), true)]); + assert_eq!(again.len(), 2); + assert!(matches!(again.first(), Some(Event::PointerButton { pressed: false, .. }))); + // an ordinary click passes through untouched + let mut r = PointerRepair::default(); + let click = frame(&mut r, vec![Event::PointerMoved(pos2(5.0, 5.0)), press(pos2(5.0, 5.0), true), press(pos2(5.0, 5.0), false)]); + assert_eq!(click.len(), 3); + // leaving and coming back with no button down changes nothing + frame(&mut r, vec![Event::PointerGone]); + assert_eq!(frame(&mut r, vec![Event::PointerMoved(pos2(9.0, 9.0))]).len(), 1); + } +} diff --git a/crates/ui-egui/src/tests/lifecycle_037.rs b/crates/ui-egui/src/tests/lifecycle_037.rs index d994b930016..29d5d27ae30 100644 --- a/crates/ui-egui/src/tests/lifecycle_037.rs +++ b/crates/ui-egui/src/tests/lifecycle_037.rs @@ -1494,6 +1494,24 @@ fn a_new_prompt_shields_raw_pointer_and_cancels_a_held_press() { assert_eq!(h.app.ui.settings.confirm_delete, before, "the press-before-prompt became a click in Settings"); } +/// A release as a prompt appears is dropped by the prompt's filter, but the pointer repair still sees it (it runs over +/// the host's events first), so after the prompt the next press gets no extra release (CodeRabbit on #1060). +#[test] +fn a_release_under_a_prompt_still_reaches_the_pointer_repair() { + let mut h = Headless::new(app(), [1200.0, 900.0], 1.0); + h.step(); + let at = egui::pos2(600.0, 450.0); + h.events.extend([egui::Event::PointerMoved(at), pointer_event(at, true)]); + h.step(); + assert!(h.app.pointer_repair.any_down(), "the press was seen"); + // released in the frame the prompt appears, before it is laid out: its filter drops the release + h.events.push(pointer_event(at, false)); + h.app.quit_prompt = Some(crate::QuitPrompt::Tasks("1 task is still running: Import. Quitting stops it.".into())); + h.step(); + assert!(h.app.quit_prompt.is_some(), "the prompt is up"); + assert!(!h.app.pointer_repair.any_down(), "the release under the prompt was seen"); +} + /// A prompt can be created after `raw_input_hook`, when eframe's `logic` runs. The prompt barrier /// must then drop wheel/new-touch/pointer input that egui already accepted for the pass, before /// any panel reads it, while a touch End still clears egui's private touch state. diff --git a/docs/gpu-pipeline.md b/docs/gpu-pipeline.md index 8dceb96ca90..d1fc7102c31 100644 --- a/docs/gpu-pipeline.md +++ b/docs/gpu-pipeline.md @@ -255,8 +255,8 @@ real failure still stops the whole process. Such a test asserts on its own rende ## Correctness: CPU oracle and equivalence tests `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, +**max 1 LSB, mean ≤ 0.0003 LSB** for every case — 27 settings cases (all tone/colour/effects tools, +3 vignette styles, grain (fine, and coarse with colour grain), 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 00000000000..b8968a926cf --- /dev/null +++ b/docs/grain.md @@ -0,0 +1,197 @@ +# Film grain + +The Effects panel's Grain (`ctl:grain.*`, `crates/pipeline/src/grain.rs`, GPU port in +`crates/gpu/src/wgsl/finish.wgsl`) renders grain particles on the spot, per output pixel, rather +than overlaying a noise texture. + +This is the grain of **process V3** and later ([process-versions.md](process-versions.md)). Photos +on V1 or V2 keep the value-noise grain they were edited with (`finish::ValueGrain`), so opening an +older catalog never changes a photo's grain; Update to Current Process (`develop.updateProcess`) +moves a photo to the particle grain, as one undo step. Size Variation, Clumping, Color and Response +only act on V3, so the Effects panel disables them on a V1 or V2 photo; Size, Roughness (Shape) +and Seed act on both models. + +## Model + +Implemented from the published Boolean model of Newson, Delon & Galerne, *Realistic Film Grain +Rendering* (IPOL 2017), extended to clumps of irregular grains. No code was taken from any +implementation. + +- **Particles.** A *clump* is one to eleven grains around a centre. Clump centres form a Poisson + process on a fixed grid of cells (2.5 mean grain radii), so no slider and no render size + reshuffles them. Each grain has its own: + - **size:** radius `exp(spread·z)`, z ≈ unit normal bounded to ±3 (Size Variation); + - **shape:** an ellipse of random orientation and elongation up to 4:1 (area preserved), with a + lobed outline: the radius varies with angle by `L·m·(0.6 cos(2θ − φ₂) + 0.4 cos(3θ − φ₃))` + (Shape); + - **position in the clump:** within ±0.8 to ±2 radii of its centre (Clumping); + - **optical density:** 0.25–1, so overlapping grains give continuous tones. + + Every value comes from hashes of the seed and the grain's cell: a seed is a pattern. +- **Density follows tone.** A pixel of display-encoded luminance `l` has expected grain coverage + `p = 0.2 + 0.6·(1 − l)^γ`, where darker means denser. The clump density is set so that + `λ·E[∫a_clump] = −ln(1 − p)`. +- **Each pixel shows the coverage averaged over its footprint.** Every grain is softened by an edge + width `s` that combines a constant film softness (0.4 radii) with one output pixel. The union is + evaluated exactly as `1 − Π(1 − aᵢ)`. +- **Development halo.** Fine or smooth grain (below Roughness 50, or finer than Size 25) gets a + ring of lower density around each clump, from the clump's size `c` (`1 + 0.7·spread` grain + radii) out to `H = 3.2` times it, whose integral is `η` times its grains' (as if the developer + were exhausted around a clump). It makes the grain regular: its autocorrelation dips below zero + one to three pixels out, as measured in Lightroom Classic. The ring is + `k·W·(P(d²/R_out²) − P(d²/R_in²))` with `W = Σ oᵢ·rᵢ²` over the clump's grains and + `P(u) = (1 − u)²` below 1: a polynomial in the squared distance, evaluated once per clump + rather than per grain (`clump_halo`). The halo is additive: the field is + `1 − T − (1 − p)·(Hs − E[Hs])`, where `T = Π(1 − aᵢ)` and `Hs` sums the clumps' rings. +- **Exact statistics.** The Poisson generating functional gives the mean (`p` at any scale) and + the variance `(1 − p)²·(exp(λ·E[∫a²]) − 1 + λ·(E[∫h²] − 2·E[∫a·h]))`. The clump integrals are + measured for each setting by rasterising 512 sample clumps drawn by the renderer's own generator, + in parallel and summed in a fixed order (`clump_moments`; cached, so a drag of Amount, Color or + Response measures nothing). +- **Particles fade in with tone.** Within a cell, clumps arrive in mark order and fade in over the + last clump's worth of the mark range. The field therefore changes continuously as the tone + changes: no particle pops in or out between neighbouring pixels or slider steps. +- **Output:** each channel gets `amp · w(l) · (p − field)` in display-encoded space, before the + profile LUT. `w(l)` divides by the field's standard deviation at the reference resolution, so + the grain is **equally strong at every tone**, as in Lightroom Classic (measured flat within 1 % + from 63 to 179 of 255). Response tilts it: `w` is multiplied by `exp(t·(l − ½))` with + `t = ln 4 · Response/100`, so at ±100 the grain is 4× stronger at one end than the other (and + the particle density shifts with tone, as before). +- **Colour:** with Color `c`, each channel gets `√(1 − c)·shared + √c·dye`, where `shared` is the + one grain layer and `dye` the channel's own independent layer. Colour 0 is monochrome grain, + 100 independent dye clouds, and the strength stays the same in between. + +## Resolution independence + +Grain geometry is defined in normalized frame coordinates (fractions of the uncropped frame's long +edge, like grain on a negative). Only the softening (one output pixel) depends on the render size, so +a small render shows what the export shows downscaled: + +- **Explicit particles** are used while one output pixel's softening (the softness less the + film's) is up to 0.35 clump radii. +- **Per-pixel Gaussian noise** with the exact variance above is used from 0.8 clump radii, i.e. + clumps smaller than a pixel: grid thumbnails, fit previews, and fine grain even on a 24 MP + export (Size below about 10, whose particles are a third of a pixel wide). The noise is + correlated with its four neighbours (`noise_e`) so that the next pixel's correlation is the one + the reference render has once box-averaged to this render's pixels (`block_correlation`): Size 0 + keeps its negative correlation (−0.2 at one pixel) as noise. +- **Between the two**, the explicit and Gaussian parts cross-fade with variance-preserving weights. +- **Calibration:** the pixel softness, 0.44 px without clumps rising to 0.5 px at Clumping 100, gives + a small render the grain strength of the export box-downscaled to its size for grain without a + halo. With a halo (band-pass grain, whose strength a box removes very differently from a soft + footprint), below 6000 px the amplitude is set from the reference render's own covariance: + `ref_covariance` measures it at lags up to 16 (pitch ≥ 1 reference pixel) from 128 sample clumps, + and its box-averaged variance gives the strength a render 6000/k px wide must have. +- **Tests:** `small_render_matches_a_downscaled_full_size_render` (grain level) and + `small_pipeline_render_matches_downscaled_full_render` (whole pipeline). +- **Measured:** renders at 1/2 to 1/8 size are within about 10 % of the downscaled export's grain + strength across sizes, roughness and clumping (`downscale_report`, ignored: run it with + `--ignored --nocapture`). + +Amount is calibrated at a 6000 px long edge (a 24 MP export); grain strength is linear in Amount. +Amount 100 gives 17 levels of 255 at the defaults there (Size 25, Roughness 50), 46 at Size 0 and +12 at Size 100: finer grain is stronger, as in Lightroom Classic. + +## Mapping (`GrainLook::new`) + +Size `S` and Roughness `ρ = Roughness/100` set the look. The curves were fitted to the seven +Lightroom Classic exports below; between those points they are smooth guesses. + +| Quantity | Formula | Size 0 / 25 / 100 (Roughness 50) | +|---|---|---| +| mean radius (px at 6000) | `(0.3 + 2.7·(S/100)^1.17) · (0.96 − 0.33ρ + 0.82ρ²)` | 0.30 / 0.83 / 3.0 | +| shape (elongation, lobes) | `ρ` | | +| halo integral `η` | `(1 − 2ρ)⁺ + 1.1·((1 − S/25)⁺)²` | 1.1 / 0 / 0 | +| halo radius `H` (clump sizes) | `3.2` | 3.2 | +| levels at Amount 100 | `exp(2.447 + 1.386·exp(−S/19.88)) · (1 − 0.084d + 1.6384d²)`, `d = ρ − ½` | 46.2 / 17.1 / 11.7 | + +Roughness 0 is finer (0.96× the radius), regular (halo 1) and 1.45× stronger than Roughness 50; +Roughness 100 is coarser (1.45× the radius), irregular and 1.37× stronger. + +## Calibration against Lightroom Classic + +Seven settings exported from Lightroom Classic 15.1.1 (process version 15.4) as full-size JPEGs of +a 6000 × 4000 chart of flat grey steps (39, 63, 118, 179, 231 of 255), measured on the luminance of +each step (900 × 3400 px): the standard deviation in 8-bit levels, and the lag (px) at which the +autocorrelation (mean of horizontal and vertical) falls to ½. "Ours" is `lightcraft-cli render` of +the same chart (CPU), measured the same way; "before" is the grain before this calibration. + +| Amount / Size / Roughness | Lightroom Classic: sd at 39 · 63 · 118 · 179 · 231; width | Ours | Before | +|---|---|---|---| +| 25 / 25 / 50 | 4.29 · 4.29 · 4.29 · 4.29 · 4.29; 1.13 | 4.24 · 4.22 · 4.24 · 4.14 · 4.23; 1.24 | 1.78 · 2.24 · 2.83 · 2.52 · 1.43; 1.14 | +| 50 / 25 / 50 | 8.55 · 8.56 · 8.55 · 8.55 · 8.52; 1.13 | 8.65 · 8.65 · 8.60 · 8.59 · 8.58; 1.17 | 3.43 · 4.39 · 5.61 · 4.97 · 3.05; 1.16 | +| 100 / 25 / 50 | 16.81 · 17.03 · 17.01 · 17.01 · 15.71; 1.14 | 17.39 · 17.37 · 17.31 · 17.28 · 17.25; 1.13 | 6.79 · 8.81 · 11.19 · 10.06 · 6.02; 1.16 | +| 50 / 0 / 50 | 22.12 · 23.01 · 23.08 · 23.06 · 20.00; 0.43 | 22.41 · 23.29 · 23.30 · 23.32 · 20.21; 0.41 | 3.01 · 3.91 · 4.98 · 4.50 · 2.74; 1.02 | +| 50 / 100 / 50 | 5.82 · 5.84 · 5.83 · 5.85 · 5.83; 3.38 | 5.87 · 5.81 · 5.80 · 5.89 · 5.84; 3.45 | 4.61 · 5.91 · 7.52 · 6.73 · 3.82; 3.47 | +| 50 / 25 / 0 | 12.41 · 12.42 · 12.42 · 12.41 · 12.05; 0.86 | 12.60 · 12.58 · 12.53 · 12.51 · 12.44; 0.87 | 3.42 · 4.39 · 5.62 · 4.96 · 3.04; 1.20 | +| 50 / 25 / 100 | 11.68 · 11.68 · 11.68 · 11.68 · 11.42; 1.54 | 11.87 · 11.87 · 11.84 · 11.75 · 11.66; 1.48 | 3.43 · 4.40 · 5.60 · 4.97 · 3.04; 1.09 | + +Autocorrelation at lags 1, 2, 3 px in mid grey: Size 0 is −0.17, 0.02, 0.00 in Lightroom Classic +(ours −0.22, 0.01, 0.00); Roughness 0 is 0.42, −0.15, −0.12 (ours 0.43, −0.12, −0.12). + +Box-downscaled by 2, 4, 8 and 16, the mid-grey step keeps (levels): + +| Amount / Size / Roughness | Lightroom Classic | Ours | +|---|---|---| +| 50 / 25 / 50 | 6.65 · 3.94 · 2.14 · 1.13 | 6.78 · 4.36 · 2.42 · 1.28 | +| 50 / 0 / 50 | 9.00 · 3.90 · 1.80 · 0.87 | 8.97 · 3.84 · 1.75 · 0.83 | +| 50 / 100 / 50 | 5.67 · 5.09 · 3.74 · 2.27 | 5.60 · 5.02 · 3.85 · 2.39 | +| 50 / 25 / 0 | 8.63 · 3.39 · 1.15 · 0.41 | 8.82 · 3.79 · 1.60 · 0.79 | +| 50 / 25 / 100 | 10.12 · 7.10 · 4.10 · 2.21 | 9.97 · 7.25 · 4.35 · 2.37 | + +The grain's large-scale content is within about 15 %, except at Roughness 0: its regular grain +keeps 1.1–1.9× as much as Lightroom Classic's at 4–16 px. Lightroom Classic's strong grain (Amount +100, or Size 0) is weaker at 231 of 255; ours stays flat there. Not measured: Size between 25 and +100, Size and Roughness together away from these points, export sizes other than 6000 px, and +anything about Lightroom Classic's own grain model (Size Variation, Clumping, Color and Response +have no Lightroom Classic counterpart to compare). + +`grain_matches_lightroom_classic_exports` renders the seven settings on a procedural flat-grey +chart at 6000 px and asserts these numbers (strength and width within 10 %, flat from 63 to 179 +within 6 %, the negative lobes of Size 0 and Roughness 0). `lrc_fit_report` (ignored) prints the +full table for a candidate mapping. + +## Controls + +| Control | Range | Meaning | +|---|---|---| +| `grain.amount` | 0–100 | strength (XMP `crs:GrainAmount`) | +| `grain.size` | 0–100 | mean grain radius on a 6000 px export at Roughness 50: 0.3 px (0), 0.83 (25), 1.5 (50), 2.2 (75), 3 px (100); 1.8–18 µm on a 35 mm frame. Finer grain is stronger (XMP `crs:GrainSize`) | +| `grain.sizeVariation` | 0–100 | spread of grain sizes: 0 = all the mean size; 100 = from 0.35× to 2.9× | +| `grain.roughness` (Shape) | 0–100 | 0 = fine, round, regular grain (with a development halo); 100 = coarser, elongated (up to 4:1), lobed, irregular grains; both ends are stronger than 50 (XMP `crs:GrainFrequency`) | +| `grain.clumping` | 0–100 | 0 = single grains; 100 = clusters of six grains on average (up to eleven) | +| `grain.color` | 0–100 | monochrome grain (0) to independent dye clouds per channel (100) | +| `grain.response` | −100–100 | where grain is strongest: equally strong at every tone (0); up to 4× stronger in the shadows (−100) or the highlights (+100) than at the other end | +| `grain.seed` | 0–99,999 | the particle pattern: every value is a different one (drag to try patterns, or type one) | + +Settings saved before Size Variation and Clumping existed load with their defaults (40 and 30); +those without Colour and Response load with both at 0. LightCraft keeps all four and the seed in its +own settings; Camera Raw has no equivalents. + +## Performance + +- **GPU:** the per-pixel kernel evaluates the clumps within reach of each pixel. On the 24 MP test + export the finish pass takes ≈ 200 ms with default grain (≈ 80–270 ms without; ≈ 650 ms with + Color: four layers). A 1500 px preview takes ≈ 15 ms. These were measured before the Lightroom + Classic calibration and not since (no GPU on the calibration machine). +- **CPU:** works on bands of 8 output rows. Each clump is generated once per band and its grains + are splatted onto the pixels they reach (`band_matches_per_pixel` checks the result equals the + per-pixel evaluation). The finish stage (`LIGHTCRAFT_PROFILE=1`) of a `lightcraft-cli render` + of the 24 MP chart on 32 threads, fastest of three, the same build settings, before the + Lightroom Classic calibration (`765142bac`) and after: + + | Amount / Size / Roughness | 0 (no grain) | 50 / 25 / 50 | 50 / 0 / 50 | 50 / 25 / 0 | 50 / 100 / 50 | + |---|---|---|---|---|---| + | before | 0.12 s | 1.09 s | 1.25 s | 0.78 s | 0.59 s | + | calibrated, halo per grain (first version) | 0.13 s | 1.25 s | 7.72 s | 2.39 s | 0.70 s | + | calibrated, halo per clump, fine grain as noise | 0.13 s | 1.15 s | 0.31 s | 1.49 s | 0.66 s | + + The machine was also running another build, so the times vary by about 10 %. Size 0 is now + cheaper than before (noise instead of particles); Roughness 0 costs about twice as much: its ring + around each clump reaches 4–5 px. +- **Parameters:** a new Size, Roughness, Size Variation or Clumping measures the clump moments + (512 sample clumps) and, below 6000 px or for noise, the reference covariance: a few ms on 32 + threads, cached per setting. + +CPU-only exports with grain are over the 1 s budget: real particles cost more than a noise +texture. Interactive renders and exports use the GPU path when an adapter exists. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 5e851e721d2..831f5e2e1d3 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (LR-BEHAV-ACCESS: the Flatpak may talk to the accessibility bus; LR-LIB-ALBUM: album commands leave out photos the library no longer has and record nothing when they add nothing; LR-BEHAV-DRAGDROP: a right-click on a text field while photos are carried from the grid opens no Cut / Copy / Paste menu; LR-BEHAV-DRAGDROP: a right-click while photos are carried from the grid opens no context menu; LR-LIB-VIRTUALCOPY: default numbering is preflighted across the requested batch and explicit names bypass suffix allocation; LR-BEHAV-DRAGDROP: only the primary button drags photos out of the grid and drops them; KEYC-RATING: deleting a keyword while Enable Filters has the filter put aside no longer leaves an empty one there; LR-BEHAV-DRAGDROP: a drop's destination is named with its parent when another folder or album has the same name; LR-VIEW-FILMSTRIP: photos drag from the filmstrip to the same sidebar targets as from the grid; LRC-LIB-LIBFOLDERS: a deep row's count follows its name in a narrow panel; LR-FILT-FLAG / LRC-LIB-FILTERBAR: the flag toggles combine, Picked + Unflagged, #2588; LR-VIEW-PHOTOGRID, LR-VIEW-FILMSTRIP, LR-VIEW-COMPARE, LR-VIEW-SURVEY, LRC-LIB-REFVIEW, LRC-LIB-PEOPLE: the active photo's selection ring shows on light themes and in Compare, Survey and the face tiles, and needs a loaded thumbnail; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-LOCATION: Info GPS text is fully validated before metadata changes; LR-MAP-TRACKLOG decodes GPX character references in point fields; malformed references error; CDATA stays literal; LR-BEHAV-ACCESS: the Thumbnail size control is a slider to screen readers; LR-BEHAV-ACCESS: the Detail photo is named with its file name; LR-VIEW-PHOTOGRID: the grid's empty-view message names its shortcut as this platform writes it and as it is bound; LR-BEHAV-ACCESS: the grid's date headers are named as they read; LR-BEHAV-ACCESS: the sidebar's disclosure triangles name their row; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌘⌥⇧K Set Keyword Shortcut and ⇧K; KEYC-METADATA: ⌘⇧K / Ctrl+Shift+K Edit Keywords; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-FOLDERS: Local's built-in places (Pictures, Desktop, Downloads, Home) offer no Rename Folder… or Move Folder To…, and `folder.rename` / `folder.move` refuse the home folder and its Pictures, Desktop and Downloads; LRC-LIB-CATALOG-SWITCH: a library's catalog.snap or folder given at launch opens that library; LR-IMP-ADD-DIALOG / LR-IMP-MOVE: checked rename-sequence exhaustion; LR-IMP-ADD-DIALOG: an import asks the disk about the probes a scan left, and for each photo's sidecar, up to 16 files at a time; LRC-LIB-LIBFOLDERS: Don't ask again in the Move Photos question is kept only when the move started; a refused move leaves the question on; LR-IMP-ADD-DIALOG: remembered import thumbnail size, density-aware bounded previews and one job per candidate/size bucket (#2237, part of #2056); import loupe remains open; counts unchanged; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MERGE-HDR / LR-MERGE-PANO / LR-MERGE-HDRPANO: the dialog makes a new preview each time it opens, also after a failed one, #2708; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-MISSING: `library.missing` from the control channel checks the files on a worker thread instead of the UI thread; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-CROP-AUTO: Auto straighten reads the vertical vanishing point and the horizon; LR-META-EXIF-FULL: reject extra EXIF clock components so invalid capture-time candidates fall through to valid metadata; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-XMP / LRC-MAP-TRACKLOG: malformed ISO times are not projected or matched; LR-IMP-FORMATS: JPEG ICC APP2 chunk validation; LR-BEHAV-TITLEBAR: a dialog leaves the title bar undimmed, as a macOS sheet does; LR-BEHAV-ACCESS: the bars are toolbars and the panels landmarks for screen readers; LR-BEHAV-ACCESS: every dialog and prompt is exposed as a dialog (a modal one, an alert dialog for the prompts); LR-BEHAV-ACCESS: icon-only buttons are named by their label, with the shortcut as the description; MENU-HELP-HELP: on macOS the Help menu is registered with the application only once the menu bar is installed (muda ignores the call before), so AppKit knows which menu is Help; LR-BEHAV-ACCESS: a slider's value field is named ` value`, with how to use it as its description; MENU-BAR: every shortcut the app shows on macOS lists its modifiers ⌃⌥⇧⌘, as the menu bar does; MENU-BAR: on macOS two menu rows that run the same command each get their own native row and label (File ▸ Export… and File ▸ Export with Preset ▸ Custom…; File ▸ New Album… and Photo ▸ Add to Album ▸ New Album…); LR-BEHAV-DIALOGS: a one-line prompt that is refused stays open and says why, and a New Folder on Disk says it was made; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-VIEW-HISTOGRAM: the shadow and highlight clipping buttons take their tile and chevron from the theme, so the chevron reads in every theme; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MASK-BRUSH: extreme brush segments skip the intermediate dabs; LR-MASK-BRUSH: with the mask overlay hidden, the stroke being painted no longer tints the photo) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** minor (LR-EDIT-EFFECTS-GRAIN: grain calibrated against Lightroom Classic exports: strength per Amount, Size and Roughness, equally strong at every tone, grain width, a development halo for fine and smooth grain; LR-BEHAV-ACCESS: the Flatpak may talk to the accessibility bus; LR-LIB-ALBUM: album commands leave out photos the library no longer has and record nothing when they add nothing; LR-BEHAV-DRAGDROP: a right-click on a text field while photos are carried from the grid opens no Cut / Copy / Paste menu; LR-BEHAV-DRAGDROP: a right-click while photos are carried from the grid opens no context menu; LR-LIB-VIRTUALCOPY: default numbering is preflighted across the requested batch and explicit names bypass suffix allocation; LR-BEHAV-DRAGDROP: only the primary button drags photos out of the grid and drops them; KEYC-RATING: deleting a keyword while Enable Filters has the filter put aside no longer leaves an empty one there; LR-BEHAV-DRAGDROP: a drop's destination is named with its parent when another folder or album has the same name; LR-VIEW-FILMSTRIP: photos drag from the filmstrip to the same sidebar targets as from the grid; LRC-LIB-LIBFOLDERS: a deep row's count follows its name in a narrow panel; LR-FILT-FLAG / LRC-LIB-FILTERBAR: the flag toggles combine, Picked + Unflagged, #2588; LR-VIEW-PHOTOGRID, LR-VIEW-FILMSTRIP, LR-VIEW-COMPARE, LR-VIEW-SURVEY, LRC-LIB-REFVIEW, LRC-LIB-PEOPLE: the active photo's selection ring shows on light themes and in Compare, Survey and the face tiles, and needs a loaded thumbnail; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-LOCATION: Info GPS text is fully validated before metadata changes; LR-MAP-TRACKLOG decodes GPX character references in point fields; malformed references error; CDATA stays literal; LR-BEHAV-ACCESS: the Thumbnail size control is a slider to screen readers; LR-BEHAV-ACCESS: the Detail photo is named with its file name; LR-VIEW-PHOTOGRID: the grid's empty-view message names its shortcut as this platform writes it and as it is bound; LR-BEHAV-ACCESS: the grid's date headers are named as they read; LR-BEHAV-ACCESS: the sidebar's disclosure triangles name their row; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌘⌥⇧K Set Keyword Shortcut and ⇧K; KEYC-METADATA: ⌘⇧K / Ctrl+Shift+K Edit Keywords; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-FOLDERS: Local's built-in places (Pictures, Desktop, Downloads, Home) offer no Rename Folder… or Move Folder To…, and `folder.rename` / `folder.move` refuse the home folder and its Pictures, Desktop and Downloads; LRC-LIB-CATALOG-SWITCH: a library's catalog.snap or folder given at launch opens that library; LR-IMP-ADD-DIALOG / LR-IMP-MOVE: checked rename-sequence exhaustion; LR-IMP-ADD-DIALOG: an import asks the disk about the probes a scan left, and for each photo's sidecar, up to 16 files at a time; LRC-LIB-LIBFOLDERS: Don't ask again in the Move Photos question is kept only when the move started; a refused move leaves the question on; LR-IMP-ADD-DIALOG: remembered import thumbnail size, density-aware bounded previews and one job per candidate/size bucket (#2237, part of #2056); import loupe remains open; counts unchanged; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MERGE-HDR / LR-MERGE-PANO / LR-MERGE-HDRPANO: the dialog makes a new preview each time it opens, also after a failed one, #2708; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LRC-LIB-MISSING: `library.missing` from the control channel checks the files on a worker thread instead of the UI thread; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-CROP-AUTO: Auto straighten reads the vertical vanishing point and the horizon; LR-META-EXIF-FULL: reject extra EXIF clock components so invalid capture-time candidates fall through to valid metadata; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-META-XMP / LRC-MAP-TRACKLOG: malformed ISO times are not projected or matched; LR-IMP-FORMATS: JPEG ICC APP2 chunk validation; LR-BEHAV-TITLEBAR: a dialog leaves the title bar undimmed, as a macOS sheet does; LR-BEHAV-ACCESS: the bars are toolbars and the panels landmarks for screen readers; LR-BEHAV-ACCESS: every dialog and prompt is exposed as a dialog (a modal one, an alert dialog for the prompts); LR-BEHAV-ACCESS: icon-only buttons are named by their label, with the shortcut as the description; MENU-HELP-HELP: on macOS the Help menu is registered with the application only once the menu bar is installed (muda ignores the call before), so AppKit knows which menu is Help; LR-BEHAV-ACCESS: a slider's value field is named ` value`, with how to use it as its description; MENU-BAR: every shortcut the app shows on macOS lists its modifiers ⌃⌥⇧⌘, as the menu bar does; MENU-BAR: on macOS two menu rows that run the same command each get their own native row and label (File ▸ Export… and File ▸ Export with Preset ▸ Custom…; File ▸ New Album… and Photo ▸ Add to Album ▸ New Album…); LR-BEHAV-DIALOGS: a one-line prompt that is refused stays open and says why, and a New Folder on Disk says it was made; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-VIEW-HISTOGRAM: the shadow and highlight clipping buttons take their tile and chevron from the theme, so the chevron reads in every theme; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-FILT-SEARCH-META: `>=` / `<=` in fielded search tokens; MENU-FILE-CLOSE, KEY-CLOSEWINDOW: the notes say Close Window quits the app, after the same check as Quit; MENU-EDIT-SELECTNONE, MENU-EDIT-PASTESELECTED: Edit lists Select Only Active Photo after Deselect All and Paste Settings from Previous after Paste Selected Settings…; on macOS no doubled separators are left where Settings… moved to the app menu; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; LR-MASK-BRUSH: extreme brush segments skip the intermediate dabs; LR-MASK-BRUSH: with the mask overlay hidden, the stroke being painted no longer tints the photo) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -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/grain.rs`, `docs/grain.md` | process V3 (V1/V2 photos keep their value-noise grain until Update to Current Process, `crates/pipeline/tests/it/grain_process.rs`): particles rendered per pixel (own implementation of the Boolean model of Newson et al. 2017, extended to clumps of irregular grains); resolution independent (a small render ≈ the export downscaled, tested). Beyond Lightroom: Size Variation, Shape (Roughness), Clumping, Color (dye layers), Response and Seed sliders. Calibrated against Lightroom Classic exports at 6000 px (seven Amount / Size / Roughness settings: strength within 3 % from 39 to 179 of 255, flat across tones, autocorrelation width within about 10 %; `grain_matches_lightroom_classic_exports`, table in `docs/grain.md`); Size between 25 and 100 and other export sizes not compared; CPU finish stage of a 24 MP export ≈ 1.2 s at the defaults (as before the calibration), 0.3 s at Size 0 (fine grain is correlated noise), 1.5 s at Roughness 0 (GPU not re-measured) | | 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) | @@ -799,6 +799,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-29 | minor | LR-EDIT-EFFECTS-GRAIN: the V3 grain is calibrated against seven Lightroom Classic exports (strength per Amount, Size and Roughness; equally strong at every tone; autocorrelation width; a development halo around each clump makes Roughness 0 and Size 0 regular; Size 0 on a 24 MP export is correlated noise, 4× cheaper than before); Response tilts the strength instead of moving a midtone peak; status unchanged (✅) | | 2026-10-30 | patch | LR-BEHAV-ACCESS: the Flatpak manifests grant `--talk-name=org.a11y.Bus`, so AccessKit can find out whether a screen reader is running and publish the window inside the sandbox; packaging lint requires it in both manifests; status unchanged (🟡), not tried with Orca | | 2026-10-27 | patch | LR-LIB-LABEL, MENU-PHOTO-LABEL, KEY-LABELS: Clear Color Label (`photo.clearLabel`) is a command of its own, so Help → Keyboard Shortcuts can give it a key (#2980); the Photo ▸ Set Color Label ▸ None row runs it; status unchanged | | 2026-10-25 | minor | KEYC-METADATA, LRC-LIB-KEYWORDS: ⌘⌥⇧K / Ctrl+Alt+Shift+K (`dialog.keywordShortcut`, Set Keyword Shortcut) and ⇧K (`keyword.toggleShortcut`) add and remove the keyword shortcut's keywords; Keyword Shortcut leaves LRC-LIB-KEYWORDS' Not yet list; status counts unchanged (KEYC-METADATA stays 🟡) | @@ -835,6 +836,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-22 | minor | LRC-PRINT-LAYOUT: the Japanese photo and postcard paper sizes (L判, 2L判, KG判, はがき, 往復はがき, 六切, 四切, 名刺) are selectable in the page setup and Print dialog and print to PDF at their metric sizes | | 2026-10-22 | minor | #2052 (partial): shared export text adds only Thai faces after Inter and the existing CJK chain. Thai horizontal mark positioning remains incomplete; Arabic fallback is deferred until joining and bidi reordering exist. LR-EXP-WATERMARK reassessed as partial for these layout and font limits; UI fallback unchanged | | 2026-10-24 | patch | LR-LIB-SMARTALBUM: relative-date view and source-count caches expire on the session-clock minute, including nested smart albums; held views retain expired photos until refresh and admit new matches; status and feature counts unchanged | +| 2026-10-22 | minor | LR-EDIT-EFFECTS-GRAIN: the particle grain is process V3; photos on V1 and V2 keep their value-noise grain exactly (CPU and GPU) until Update to Current Process, and their Size Variation, Clumping, Color and Response sliders (V3 only) are disabled; the new grain fields aren't written at their defaults; status unchanged (✅) | | 2026-10-24 | patch | LR-LIB-VIRTUALCOPY: copy names are resolved before batch mutation, numeric exhaustion returns BadParams, and explicit names bypass the counter; status and feature counts unchanged | | 2026-10-22 | patch | LR-META-XMP: namespace URI determines ownership; foreign namespaces using recognized prefixes survive saves and cannot supply native settings or ratings; status and counts unchanged | | 2026-10-22 | patch | LR-EXP-PSD, LR-META-EXIF-FULL: PSD/PSB imports and image resources 1058/1060 now supply EXIF and XMP to metadata readers and All Metadata; Original with Remove Location Info refuses detected PSD/PSB GPS; statuses and feature counts unchanged | @@ -869,6 +871,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-15 | minor | LRC-PRINT-PAGE: Page Options (Page Numbers, Page Info, Crop Marks) on Single Image and Contact Sheet pages, in the Print dialog, `print.set` and templates; still 🟡 (no identity plate, watermark, photo info or Cut Guides) | | 2026-10-15 | minor | LR-IMP-FORMATS: Hasselblad 3FR and FFF show their uncompressed RGB preview (no JPEG in these files) in the grid and loupe until developed, and as the stand-in when a file fails to decode; status unchanged (🟡) | | 2026-10-15 | minor | LR-IMP-FORMATS: a Hasselblad FFF develops with the camera's colour matrix from the original 3FR header it embeds (tag `0xC51B`) instead of the neutral matrix; status unchanged (🟡) | +| 2026-10-11 | minor | LR-EDIT-EFFECTS-GRAIN: grain redrawn as clumps of irregular particles with Size Variation, Shape, Clumping and Seed controls. Earlier: Size range narrowed (old 0–20), Roughness reshapes grains instead of reshuffling them. Earlier the same day: stays ✅ with a note: the value-noise grain was replaced by a Boolean-model film grain (resolution independent, Color and Response sliders), see `docs/grain.md` | | 2026-10-13 | minor | LRC-LIB-KEYWORDS: the Keyword List marks a keyword that has an applied keyword inside it (a dot in its box); status unchanged | | 2026-10-12 | minor | LR-IMP-FORMATS: folder discovery includes SR2/SRF; MCP and CLI reuse the engine extension list. DSC-F828 remains preview-only; decoder support and row status unchanged | | 2026-10-15 | patch | KEYC-RATING: `\` shows / hides the Filter Bar in Photo Grid and Square Grid (Show Original in Detail); status unchanged (🟡) | diff --git a/docs/process-versions.md b/docs/process-versions.md index 7e6788f11e6..f6daa2bbe48 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 as clumps of irregular particles (`crates/pipeline/src/grain.rs`, [grain.md](grain.md)): a filtered Boolean model, resolution independent, calibrated against Lightroom Classic exports, with Size Variation, Shape, Clumping, Color and Response. 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. Composes with open PR #762 (pixel-scale sharpening, also proposed as V3): whichever lands second takes V4 and keeps the other's change. | ## The rule diff --git a/docs/xmp-interop.md b/docs/xmp-interop.md index 254574d91bf..e02627d3d07 100644 --- a/docs/xmp-interop.md +++ b/docs/xmp-interop.md @@ -172,7 +172,7 @@ application's renderer and is ignored: the photo keeps LightCraft's own process, | `ColorNoiseReduction`, `ColorNoiseReductionDetail`, `ColorNoiseReductionSmoothness` | `detail.nr_color/nr_color_detail/nr_color_smoothness` | | | `PostCropVignetteAmount/Midpoint/Roundness/Feather/HighlightContrast` | `vignette.amount/midpoint/roundness/feather/highlights` | | | `PostCropVignetteStyle` | `vignette.style` | 1 highlight priority, 2 colour priority, 3 paint overlay | -| `GrainAmount`, `GrainSize`, `GrainFrequency` | `grain.amount`, `grain.size`, `grain.roughness` | | +| `GrainAmount`, `GrainSize`, `GrainFrequency` | `grain.amount`, `grain.size`, `grain.roughness` | Roughness is LightCraft's grain Shape; `grain.color`, `grain.response`, `grain.sizeVariation`, `grain.clumping` and `grain.seed` have no Camera Raw equivalent (not written) | | `LensProfileEnable`, `AutoLateralCA` | `optics.lens_profile`, `optics.remove_ca` | lens profiles are the file's own (DNG-embedded) corrections, which Lightroom applies whatever its profile switch says (our inference): only `LensProfileEnable=1` carries over, `0` leaves the switch as it is | | `LensManualDistortionAmount`, `VignetteAmount`, `VignetteMidpoint` | `optics.distortion`, `optics.vignetting`, `optics.vignetting_midpoint` | | | `DefringePurple/GreenAmount/HueLo/HueHi` | `optics.defringe_*` | |