Skip to content

LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust

M5.2a: lightcraft-gpu crate (wgpu compute) with the per-pixel stage on the GPU

Brandon Thomasc7a1e3e2f636
diff --git a/Cargo.lock b/Cargo.lock
index c5fa711c7..4fa0b12e3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2105,6 +2105,22 @@ dependencies = [
"serde",
]
+[[package]]
+name = "lightcraft-gpu"
+version = "0.1.0"
+dependencies = [
+ "bytemuck",
+ "lightcraft-color",
+ "lightcraft-develop",
+ "lightcraft-geom",
+ "lightcraft-pipeline",
+ "lightcraft-raster",
+ "lightcraft-scenes",
+ "log",
+ "pollster 1.0.1",
+ "wgpu",
+]
+
[[package]]
name = "lightcraft-mcp"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index f52003e69..78206499a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -21,6 +21,7 @@ lightcraft-meta = { path = "crates/meta" }
lightcraft-develop = { path = "crates/develop" }
lightcraft-scenes = { path = "crates/scenes" }
lightcraft-pipeline = { path = "crates/pipeline" }
+lightcraft-gpu = { path = "crates/gpu" }
lightcraft-catalog = { path = "crates/catalog" }
lightcraft-preview = { path = "crates/preview" }
lightcraft-engine = { path = "crates/engine" }
@@ -57,6 +58,10 @@ moxcms = { version = "0.9", default-features = false, features = ["lut"] }
jxl-oxide = { version = "0.12", default-features = false }
ravif = { version = "0.13", default-features = false, features = ["threading"] } # no "asm": it needs nasm (non-Rust)
+# gpu (crates/gpu; native backends only, no GL: everything stays pure Rust)
+wgpu = { version = "30", default-features = false, features = ["std", "parking_lot", "metal", "vulkan", "dx12", "wgsl"] }
+pollster = "1"
+
# ui
egui = "0.36"
egui_extras = { version = "0.36", default-features = false }
diff --git a/crates/color/src/perceptual.rs b/crates/color/src/perceptual.rs
index 40743f80a..aa3ffbfa3 100644
--- a/crates/color/src/perceptual.rs
+++ b/crates/color/src/perceptual.rs
@@ -44,6 +44,13 @@ fn mul(m: &[[f32; 3]; 3], v: [f32; 3]) -> [f32; 3] {
]
}
+/// The f32 matrices [`oklab_from_2020`] and [`oklab_to_2020`] use (row-major): Rec.2020 → LMS,
+/// LMS → Rec.2020, cube-rooted LMS → Lab, Lab → cube-rooted LMS. GPU kernels embed these.
+pub fn oklab_matrices() -> [[[f32; 3]; 3]; 4] {
+ let m = mats();
+ [m.to_lms, m.from_lms, m.to_lab, m.from_lab]
+}
+
/// Linear Rec.2020 → OkLab `[L, a, b]`.
#[inline]
pub fn oklab_from_2020(rgb: [f32; 3]) -> [f32; 3] {
diff --git a/crates/gpu/Cargo.toml b/crates/gpu/Cargo.toml
new file mode 100644
index 000000000..765e4c6d7
--- /dev/null
+++ b/crates/gpu/Cargo.toml
@@ -0,0 +1,27 @@
+[package]
+name = "lightcraft-gpu"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+description = "LightCraft GPU develop pipeline: wgpu compute (WGSL) twin of the CPU pipeline, which stays the reference (L3)"
+
+[lints]
+workspace = true
+
+[dependencies]
+lightcraft-geom = { workspace = true }
+lightcraft-color = { workspace = true }
+lightcraft-raster = { workspace = true }
+lightcraft-develop = { workspace = true }
+lightcraft-pipeline = { workspace = true }
+log = { workspace = true }
+
+# Native only: Metal / Vulkan / DX12 through wgpu (pure Rust; the drivers are the system's).
+# The browser build keeps the CPU pipeline (WebGPU needs async device creation: see docs/gpu-pipeline.md).
+[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
+wgpu = { workspace = true }
+pollster = { workspace = true }
+bytemuck = { workspace = true }
+
+[dev-dependencies]
+lightcraft-scenes = { workspace = true }
diff --git a/crates/gpu/src/ctx.rs b/crates/gpu/src/ctx.rs
new file mode 100644
index 000000000..3fb922142
--- /dev/null
+++ b/crates/gpu/src/ctx.rs
@@ -0,0 +1,281 @@
+//! The wgpu device, the compiled kernels, buffers, dispatch and readback.
+
+use std::collections::HashMap;
+
+use wgpu::util::DeviceExt;
+
+/// A kernel module: WGSL source, its storage bindings (name, writable, element type) after the
+/// parameter block `P` (binding 0), and its entry points.
+struct Module {
+ src: &'static str,
+ bindings: &'static [(&'static str, bool, &'static str)],
+ entries: &'static [&'static str],
+}
+
+const MODULES: &[Module] = &[
+ Module {
+ src: include_str!("wgsl/finish.wgsl"),
+ bindings: &[
+ ("img", false, "f32"),
+ ("log_l", false, "f32"),
+ ("base_p", false, "f32"),
+ ("clar", false, "f32"),
+ ("tex", false, "f32"),
+ ("dark", false, "f32"),
+ ("masks", false, "f32"),
+ ("aux", false, "f32"),
+ ("out", true, "u32"),
+ ],
+ entries: &["main"],
+ },
+ Module { src: include_str!("wgsl/blur.wgsl"), bindings: &[("src", false, "f32"), ("dst", true, "f32")], entries: &["box_h", "box_v"] },
+ Module {
+ src: include_str!("wgsl/resize.wgsl"),
+ bindings: &[("src", false, "f32"), ("table", false, "u32"), ("dst", true, "f32")],
+ entries: &["resize_h", "resize_v"],
+ },
+ Module {
+ src: include_str!("wgsl/map.wgsl"),
+ bindings: &[("a", false, "f32"), ("b", false, "f32"), ("c", false, "f32"), ("dst", true, "f32")],
+ entries: &["log_lum_k", "dark_k", "guided_pre", "guided_ab", "guided_apply", "wb_k", "nr_lum", "chroma_k", "nr_col", "subsample"],
+ },
+];
+
+struct Kernel {
+ pipeline: wgpu::ComputePipeline,
+ layout: wgpu::BindGroupLayout,
+ nbuf: usize,
+}
+
+/// A device buffer of `len` 32-bit values.
+pub struct Buf {
+ pub buf: wgpu::Buffer,
+ pub len: usize,
+}
+
+pub struct Gpu {
+ pub device: wgpu::Device,
+ pub queue: wgpu::Queue,
+ pub info: wgpu::AdapterInfo,
+ kernels: HashMap<&'static str, Kernel>,
+ dummy: wgpu::Buffer,
+ /// Largest storage buffer the device accepts (bytes).
+ pub max_buffer: u64,
+}
+
+/// WGSL constants shared by every module (generated from the CPU pipeline's values).
+fn constants() -> String {
+ use lightcraft_pipeline::finish::{GRAIN_HASH, MASK_TERMS, SRGB_LUT_N};
+ use lightcraft_pipeline::tone::{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();
+ let to_srgb = lightcraft_color::REC2020.to_space(&lightcraft_color::SRGB).to_f32();
+ for (name, m) in [("OK_TO_LMS", to_lms), ("OK_FROM_LMS", from_lms), ("OK_TO_LAB", to_lab), ("OK_FROM_LAB", from_lab), ("TO_SRGB", to_srgb)] {
+ let rows: Vec<String> = m.iter().map(|r| format!("vec3<f32>({:?}, {:?}, {:?})", r[0], r[1], r[2])).collect();
+ s += &format!("const {name} = array<vec3<f32>, 3>({});\n", rows.join(", "));
+ }
+ s += &format!("const TONE_MIN_EV: f32 = {LUT_MIN_EV:?};\nconst TONE_MAX_EV: f32 = {LUT_MAX_EV:?};\nconst TONE_N: u32 = {LUT_N}u;\n");
+ s += &format!("const TONE_MIN_GAIN: f32 = {:?};\n", 2f32.powf(LUT_MIN_EV));
+ s += &format!("const SRGB_N: u32 = {SRGB_LUT_N}u;\nconst CURVE_N: u32 = {}u;\nconst MASK_TERMS: u32 = {MASK_TERMS}u;\n", crate::params::CURVE_N);
+ for (i, h) in GRAIN_HASH.iter().enumerate() {
+ s += &format!("const GRAIN_H{i}: u32 = {h}u;\n");
+ }
+ for (name, idx) in crate::params::finish_fields() {
+ s += &format!("const F_{name}: u32 = {idx}u;\n");
+ }
+ s
+}
+
+fn module_source(m: &Module, consts: &str) -> String {
+ let mut s = String::from(consts);
+ s += "@group(0) @binding(0) var<storage, read> P: array<u32>;\n";
+ for (i, (name, write, ty)) in m.bindings.iter().enumerate() {
+ let access = if *write { "read_write" } else { "read" };
+ s += &format!("@group(0) @binding({}) var<storage, {access}> {name}: array<{ty}>;\n", i + 1);
+ }
+ s += include_str!("wgsl/common.wgsl");
+ s += m.src;
+ s
+}
+
+impl Gpu {
+ /// Create a device on the best available adapter (no software fallback), or `None`.
+ pub fn new() -> Option<Gpu> {
+ let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
+ desc.backends = wgpu::Backends::PRIMARY;
+ let instance = wgpu::Instance::new(desc);
+ let adapter = pollster::block_on(
+ instance.request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::HighPerformance, ..Default::default() }),
+ )
+ .ok()?;
+ let info = adapter.get_info();
+ if info.device_type == wgpu::DeviceType::Cpu {
+ log::info!("gpu: only a software adapter ({}), using the CPU pipeline", info.name);
+ return None;
+ }
+ let limits = adapter.limits();
+ if limits.max_storage_buffers_per_shader_stage < 10 {
+ log::info!("gpu: {} has too few storage buffers per stage", info.name);
+ return None;
+ }
+ let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
+ label: Some("lightcraft"),
+ required_limits: limits.clone(),
+ ..Default::default()
+ }))
+ .ok()?;
+ // Errors outside an error scope (e.g. out of memory during a render): log, and stop using
+ // the GPU (the render in flight is redone on the CPU).
+ device.on_uncaptured_error(std::sync::Arc::new(|e| {
+ log::error!("gpu: {e}");
+ crate::mark_broken();
+ }));
+ let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
+ let consts = constants();
+ let mut kernels = HashMap::new();
+ for m in MODULES {
+ let src = module_source(m, &consts);
+ let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl(src.into()) });
+ let mut entries = vec![storage_entry(0, true)];
+ entries.extend(m.bindings.iter().enumerate().map(|(i, (_, w, _))| storage_entry(i as u32 + 1, !w)));
+ let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, entries: &entries });
+ let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: None,
+ bind_group_layouts: &[Some(&layout)],
+ immediate_size: 0,
+ });
+ for e in m.entries {
+ let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
+ label: Some(e),
+ layout: Some(&pl),
+ module: &module,
+ entry_point: Some(e),
+ compilation_options: Default::default(),
+ cache: None,
+ });
+ kernels.insert(*e, Kernel { pipeline, layout: layout.clone(), nbuf: m.bindings.len() });
+ }
+ }
+ if let Some(e) = pollster::block_on(scope.pop()) {
+ log::error!("gpu: kernels failed to build on {}: {e}", info.name);
+ return None;
+ }
+ let dummy = device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("dummy"),
+ size: 16,
+ usage: wgpu::BufferUsages::STORAGE,
+ mapped_at_creation: false,
+ });
+ let max_buffer = limits.max_storage_buffer_binding_size.min(limits.max_buffer_size);
+ log::info!("gpu: {} ({:?})", info.name, info.backend);
+ Some(Gpu { device, queue, info, kernels, dummy, max_buffer })
+ }
+
+ /// A zero-initialized buffer of `len` 32-bit values.
+ pub fn buffer(&self, len: usize) -> Buf {
+ let size = (len.max(1) * 4) as u64;
+ let buf = self.device.create_buffer(&wgpu::BufferDescriptor {
+ label: None,
+ size,
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ Buf { buf, len }
+ }
+
+ /// Upload 32-bit values.
+ pub fn upload<T: bytemuck::Pod>(&self, data: &[T]) -> Buf {
+ let bytes: &[u8] = bytemuck::cast_slice(data);
+ let len = bytes.len() / 4;
+ if bytes.is_empty() {
+ return self.buffer(1);
+ }
+ let buf = self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: None,
+ contents: bytes,
+ usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST,
+ });
+ Buf { buf, len }
+ }
+
+ /// Whether a buffer of `len` 32-bit values fits the device limits.
+ pub fn fits(&self, len: usize) -> bool {
+ (len as u64) * 4 <= self.max_buffer
+ }
+
+ pub fn encoder(&self) -> wgpu::CommandEncoder {
+ self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: None })
+ }
+
+ /// Record kernel `name` with parameters `p` over buffers `bufs` (None = unused binding).
+ pub fn run(&self, enc: &mut wgpu::CommandEncoder, name: &str, p: &[u32], bufs: &[Option<&Buf>], groups: [u32; 3]) {
+ let k = self.kernels.get(name).unwrap_or_else(|| panic!("unknown kernel {name}"));
+ assert_eq!(bufs.len(), k.nbuf, "{name}: binding count");
+ let params = self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
+ label: None,
+ contents: bytemuck::cast_slice(if p.is_empty() { &[0u32] } else { p }),
+ usage: wgpu::BufferUsages::STORAGE,
+ });
+ let mut entries = vec![wgpu::BindGroupEntry { binding: 0, resource: params.as_entire_binding() }];
+ for (i, b) in bufs.iter().enumerate() {
+ let buf = b.map(|b| &b.buf).unwrap_or(&self.dummy);
+ entries.push(wgpu::BindGroupEntry { binding: i as u32 + 1, resource: buf.as_entire_binding() });
+ }
+ let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &k.layout, entries: &entries });
+ let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some(name), timestamp_writes: None });
+ pass.set_pipeline(&k.pipeline);
+ pass.set_bind_group(0, &bg, &[]);
+ pass.dispatch_workgroups(groups[0], groups[1], groups[2]);
+ }
+
+ /// Submit `enc`, then read back the first `len` 32-bit values of `src`.
+ pub fn finish_and_read<T: bytemuck::Pod>(&self, mut enc: wgpu::CommandEncoder, src: &Buf, len: usize) -> Vec<T> {
+ assert!(len <= src.len, "readback of {len} values from a buffer of {}", src.len);
+ let size = (len * 4) as u64;
+ let staging = self.device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("readback"),
+ size: size.max(4),
+ usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+ enc.copy_buffer_to_buffer(&src.buf, 0, &staging, 0, size);
+ self.queue.submit([enc.finish()]);
+ let slice = staging.slice(..size);
+ let (tx, rx) = std::sync::mpsc::channel();
+ slice.map_async(wgpu::MapMode::Read, move |r| {
+ let _ = tx.send(r);
+ });
+ let _ = self.device.poll(wgpu::PollType::wait_indefinitely());
+ match rx.recv() {
+ Ok(Ok(())) => {}
+ other => panic!("gpu readback failed: {other:?}"),
+ }
+ let data = slice.get_mapped_range().expect("mapped");
+ let out: Vec<T> = bytemuck::cast_slice(&data).to_vec();
+ drop(data);
+ staging.unmap();
+ out
+ }
+}
+
+fn storage_entry(binding: u32, read_only: bool) -> wgpu::BindGroupLayoutEntry {
+ wgpu::BindGroupLayoutEntry {
+ binding,
+ visibility: wgpu::ShaderStages::COMPUTE,
+ ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only }, has_dynamic_offset: false, min_binding_size: None },
+ count: None,
+ }
+}
+
+/// Workgroups covering a `w × h` grid with `wg`-sized groups.
+pub fn groups2(w: usize, h: usize, wg: [usize; 2]) -> [u32; 3] {
+ [w.div_ceil(wg[0]).max(1) as u32, h.div_ceil(wg[1]).max(1) as u32, 1]
+}
+
+#[allow(dead_code)] // used by the plane kernels
+/// Workgroups for a 1-D kernel of `n` threads (256 per group) on a 2-D grid (see `lin_index`).
+pub fn groups1(n: usize) -> [u32; 3] {
+ let g = n.div_ceil(256).max(1);
+ let x = g.min(32768);
+ [x as u32, g.div_ceil(x) as u32, 1]
+}
diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs
new file mode 100644
index 000000000..fd84d71da
--- /dev/null
+++ b/crates/gpu/src/lib.rs
@@ -0,0 +1,119 @@
+//! The LightCraft develop pipeline on the GPU (wgpu compute, WGSL kernels).
+//!
+//! The CPU pipeline (`lightcraft-pipeline`) is the reference: every kernel here is a port of a CPU
+//! stage, both read the same resolved parameters ([`lightcraft_pipeline::Plan`],
+//! [`lightcraft_pipeline::finish::FinishParams`]), and the equivalence tests (`tests/`) render the
+//! same settings on both and bound the difference in 8-bit sRGB. Stages without a kernel run on the
+//! CPU inside the same render (per-stage hybrid); see `docs/gpu-pipeline.md`.
+//!
+//! Use [`render`]: it returns `None` when the GPU is unavailable, disabled (`LIGHTCRAFT_GPU=0` or
+//! [`set_enabled`]), or the render does not fit the device — callers then render on the CPU.
+//! The browser build has no GPU path yet (WebGPU device creation is asynchronous): everything here
+//! compiles to the CPU fallback on wasm32.
+#![forbid(unsafe_code)]
+
+use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, Ordering};
+
+use lightcraft_develop::DevelopSettings;
+use lightcraft_pipeline::{RenderRequest, Rendered, SourceInfo, StageCache};
+use lightcraft_raster::Rgb32f;
+
+#[cfg(not(target_arch = "wasm32"))]
+mod ctx;
+#[cfg(not(target_arch = "wasm32"))]
+mod params;
+#[cfg(not(target_arch = "wasm32"))]
+mod render;
+
+#[cfg(not(target_arch = "wasm32"))]
+pub use render::GpuStages;
+
+static ENABLED: AtomicBool = AtomicBool::new(true);
+/// Set when a GPU render failed: the process stays on the CPU from then on.
+static BROKEN: AtomicBool = AtomicBool::new(false);
+
+/// Stop using the GPU for the rest of the process (after a device error).
+#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
+fn mark_broken() {
+ BROKEN.store(true, Ordering::Relaxed);
+}
+
+/// Allow or forbid GPU rendering at runtime (a preference). `LIGHTCRAFT_GPU=0` forbids it for the
+/// whole process regardless.
+pub fn set_enabled(on: bool) {
+ ENABLED.store(on, Ordering::Relaxed);
+}
+
+/// Whether GPU rendering is allowed (environment, preference, no earlier failure).
+pub fn enabled() -> bool {
+ ENABLED.load(Ordering::Relaxed) && !BROKEN.load(Ordering::Relaxed) && !env_disabled()
+}
+
+fn env_disabled() -> bool {
+ static OFF: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ *OFF.get_or_init(|| std::env::var("LIGHTCRAFT_GPU").is_ok_and(|v| matches!(v.trim(), "0" | "off" | "false" | "no")))
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+fn device() -> Option<&'static ctx::Gpu> {
+ static GPU: std::sync::OnceLock<Option<ctx::Gpu>> = std::sync::OnceLock::new();
+ if env_disabled() {
+ return None;
+ }
+ GPU.get_or_init(|| std::panic::catch_unwind(ctx::Gpu::new).ok().flatten()).as_ref()
+}
+
+/// Whether a usable GPU adapter exists and GPU rendering is enabled (creates the device on first
+/// use).
+pub fn available() -> bool {
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ enabled() && device().is_some()
+ }
+ #[cfg(target_arch = "wasm32")]
+ {
+ false
+ }
+}
+
+/// The adapter's name and backend, e.g. "Apple M4 Pro (Metal)".
+pub fn adapter_name() -> Option<String> {
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ device().map(|g| format!("{} ({:?})", g.info.name, g.info.backend))
+ }
+ #[cfg(target_arch = "wasm32")]
+ {
+ None
+ }
+}
+
+/// Render `src` with `s` on the GPU, reusing the device-resident stages kept with `stages` (the
+/// view's CPU stage cache). `None`: render on the CPU instead.
+pub fn render(src: &Arc<Rgb32f>, info: &SourceInfo, s: &DevelopSettings, req: &RenderRequest, stages: Option<&StageCache>) -> Option<Rendered> {
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ if !enabled() {
+ return None;
+ }
+ let gpu = device()?;
+ let ext = stages.map(|c| c.extension::<GpuStages>());
+ let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| render::render(gpu, src, info, s, req, ext.as_deref())));
+ match r {
+ // a device error during the render: its result is not trustworthy
+ Ok(_) if BROKEN.load(Ordering::Relaxed) => None,
+ Ok(r) => r,
+ Err(_) => {
+ log::error!("gpu: render failed; using the CPU pipeline from now on");
+ BROKEN.store(true, Ordering::Relaxed);
+ None
+ }
+ }
+ }
+ #[cfg(target_arch = "wasm32")]
+ {
+ let _ = (src, info, s, req, stages);
+ None
+ }
+}
diff --git a/crates/gpu/src/params.rs b/crates/gpu/src/params.rs
new file mode 100644
index 000000000..64d722d7e
--- /dev/null
+++ b/crates/gpu/src/params.rs
@@ -0,0 +1,211 @@
+//! Parameter blocks: the per-pixel stage's [`FinishParams`] packed into the 32-bit words the
+//! `finish` kernel reads (`F_*` constants, generated from [`FIELDS`]), plus its auxiliary tables.
+
+use lightcraft_develop::VignetteStyle;
+use lightcraft_pipeline::finish::{FinishParams, MASK_TERMS, srgb_lut};
+
+/// Entries per tone-curve table (`lightcraft_pipeline::finish` builds them at this size).
+pub const CURVE_N: u32 = 1024;
+
+/// Field name and number of 32-bit words.
+const FIELDS: &[(&str, usize)] = &[
+ ("W", 1),
+ ("H", 1),
+ ("NMASK", 1),
+ ("MASK_OFF", 1),
+ ("SRGB_OFF", 1),
+ ("CURVE_OFF", 1),
+ ("CURVES", 1),
+ ("GAIN", 1),
+ ("EV", 1),
+ ("AIR", 1),
+ ("AIR_PRE", 1),
+ ("HL", 1),
+ ("SH", 1),
+ ("CLAR", 1),
+ ("TEX", 1),
+ ("DEHAZE", 1),
+ ("SHARPEN", 1),
+ ("SHARPEN_MASK", 1),
+ ("HAS_CLAR", 1),
+ ("HAS_TEX", 1),
+ ("HAS_DARK", 1),
+ ("OPS_IDENTITY", 1),
+ ("VIBRANCE", 1),
+ ("SATURATION", 1),
+ ("MIXER", 1),
+ ("MIX_HUE", 8),
+ ("MIX_SAT", 8),
+ ("MIX_LUM", 8),
+ ("BW", 1),
+ ("BW_MIX", 8),
+ ("GRADING", 1),
+ ("WHEELS", 12),
+ ("BLENDING", 1),
+ ("BALANCE", 1),
+ ("SKIN", 1),
+ ("BANDH", 8),
+ ("VIG", 1),
+ ("VIG_AMOUNT", 1),
+ ("VIG_START", 1),
+ ("VIG_WIDTH", 1),
+ ("VIG_ASPECT_MIX", 1),
+ ("VIG_POWER", 1),
+ ("VIG_HL", 1),
+ ("VIG_STYLE", 1),
+ ("GRAIN", 1),
+ ("GRAIN_AMT", 1),
+ ("GRAIN_SC", 1),
+ ("GRAIN_ROUGH", 1),
+ ("GRAIN_SEED", 1),
+ ("GRAIN_AFF", 6),
+];
+
+/// `(name, index)` of every field (for the WGSL constants).
+pub fn finish_fields() -> Vec<(&'static str, usize)> {
+ let mut i = 0;
+ FIELDS
+ .iter()
+ .map(|(n, len)| {
+ let r = (*n, i);
+ i += len;
+ r
+ })
+ .collect()
+}
+
+fn index(name: &str) -> usize {
+ let mut i = 0;
+ for (n, len) in FIELDS {
+ if *n == name {
+ return i;
+ }
+ i += len;
+ }
+ panic!("unknown finish field {name}")
+}
+
+/// A parameter block being filled by name.
+pub struct Block(pub Vec<u32>);
+
+impl Block {
+ fn new() -> Block {
+ Block(vec![0; FIELDS.iter().map(|f| f.1).sum()])
+ }
+ fn f(&mut self, name: &str, v: f32) {
+ let i = index(name);
+ self.0[i] = v.to_bits();
+ }
+ fn u(&mut self, name: &str, v: u32) {
+ let i = index(name);
+ self.0[i] = v;
+ }
+ fn b(&mut self, name: &str, v: bool) {
+ self.u(name, v as u32);
+ }
+ fn fs(&mut self, name: &str, v: &[f32]) {
+ let i = index(name);
+ for (k, x) in v.iter().enumerate() {
+ self.0[i + k] = x.to_bits();
+ }
+ }
+}
+
+/// Which optional planes are bound.
+pub struct Present {
+ pub clarity: bool,
+ pub texture: bool,
+ pub dark: bool,
+}
+
+/// The `finish` kernel's parameter block and auxiliary table (tone LUT | sRGB LUT | curve LUTs |
+/// mask terms) for `fp` with `masks` (their local adjustments' terms).
+pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Present) -> (Vec<u32>, Vec<f32>) {
+ let mut aux: Vec<f32> = fp.tone.lut().to_vec();
+ let srgb_off = aux.len();
+ aux.extend_from_slice(&srgb_lut()[..]);
+ let curve_off = aux.len();
+ if let Some(c) = &fp.curves {
+ for l in c {
+ assert_eq!(l.v.len(), CURVE_N as usize);
+ aux.extend_from_slice(&l.v);
+ }
+ }
+ let mask_off = aux.len();
+ for m in masks {
+ aux.extend_from_slice(m);
+ }
+
+ let mut p = Block::new();
+ p.u("W", fp.w as u32);
+ p.u("H", fp.h as u32);
+ p.u("NMASK", masks.len() as u32);
+ p.u("MASK_OFF", mask_off as u32);
+ p.u("SRGB_OFF", srgb_off as u32);
+ p.u("CURVE_OFF", curve_off as u32);
+ p.b("CURVES", fp.curves.is_some());
+ p.f("GAIN", fp.gain);
+ p.f("EV", fp.ev);
+ p.f("AIR", fp.air);
+ p.f("AIR_PRE", fp.air_pre);
+ p.f("HL", fp.hl);
+ p.f("SH", fp.sh);
+ p.f("CLAR", fp.clar);
+ p.f("TEX", fp.tex);
+ p.f("DEHAZE", fp.dehaze);
+ p.f("SHARPEN", fp.sharpen);
+ p.f("SHARPEN_MASK", fp.sharpen_mask);
+ p.b("HAS_CLAR", present.clarity);
+ p.b("HAS_TEX", present.texture);
+ p.b("HAS_DARK", present.dark);
+
+ let ops = &fp.ops;
+ p.b("OPS_IDENTITY", ops.is_identity());
+ p.f("VIBRANCE", ops.vibrance);
+ p.f("SATURATION", ops.saturation);
+ p.b("MIXER", ops.mixer);
+ p.fs("MIX_HUE", &ops.hue);
+ p.fs("MIX_SAT", &ops.sat);
+ p.fs("MIX_LUM", &ops.lum);
+ p.b("BW", ops.bw.is_some());
+ p.fs("BW_MIX", &ops.bw.unwrap_or([0.0; 8]));
+ if let Some((wheels, blending, balance)) = &ops.grading {
+ p.b("GRADING", true);
+ let w: Vec<f32> = wheels.iter().flat_map(|k| [k.a, k.b, k.lum]).collect();
+ p.fs("WHEELS", &w);
+ p.f("BLENDING", *blending);
+ p.f("BALANCE", *balance);
+ }
+ p.f("SKIN", ops.skin);
+ p.fs("BANDH", lightcraft_pipeline::colorops::band_hues());
+
+ if let Some(v) = &fp.vig {
+ p.b("VIG", true);
+ p.f("VIG_AMOUNT", v.amount);
+ p.f("VIG_START", v.start);
+ p.f("VIG_WIDTH", v.width);
+ p.f("VIG_ASPECT_MIX", v.aspect_mix);
+ p.f("VIG_POWER", v.power);
+ p.f("VIG_HL", v.highlights);
+ p.u(
+ "VIG_STYLE",
+ match v.style {
+ VignetteStyle::HighlightPriority => 1,
+ VignetteStyle::PaintOverlay => 2,
+ VignetteStyle::ColorPriority => 0,
+ },
+ );
+ }
+ if let Some((amt, cell, rough, seed)) = 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);
+ 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);
+ p.fs("GRAIN_AFF", &[(a * kx) as f32, (b * ky) as f32, (c * kx) as f32, (d * ky) as f32, (e * kx) as f32, (f * ky) as f32]);
+ }
+ (p.0, aux)
+}
diff --git a/crates/gpu/src/render.rs b/crates/gpu/src/render.rs
new file mode 100644
index 000000000..fd118b4fb
--- /dev/null
+++ b/crates/gpu/src/render.rs
@@ -0,0 +1,288 @@
+//! The GPU renderer: the CPU pipeline's stages, evaluated on the device where a kernel exists and
+//! on the CPU otherwise (per-stage hybrid). Stage results stay on the device and are cached per
+//! view exactly like [`lightcraft_pipeline::StageCache`] (same keys, see [`lightcraft_pipeline::Plan`]).
+
+use std::sync::{Arc, Mutex};
+
+use lightcraft_develop::DevelopSettings;
+use lightcraft_pipeline::finish::{FinishParams, mask_terms};
+use lightcraft_pipeline::{Plan, RenderRequest, Rendered, SourceInfo, local};
+use lightcraft_raster::{Histogram, Plane, Rgb32f, Rgba8};
+
+use crate::ctx::{Buf, Gpu, groups2};
+use crate::params::{Present, finish_block};
+
+/// Device-resident stages of one view, kept next to the CPU [`lightcraft_pipeline::StageCache`]
+/// (as its extension). Holds the last two output sizes, like the CPU cache.
+#[derive(Default)]
+pub struct GpuStages {
+ entries: Mutex<Vec<Entry>>,
+}
+
+const CAPACITY: usize = 2;
+
+#[derive(Clone)]
+struct Entry {
+ src: Arc<Rgb32f>,
+ geo: u64,
+ sampled: Arc<Buf>,
+ lin: Option<(u64, Arc<Buf>)>,
+ planes: Planes,
+}
+
+/// Spatial planes of one linear image (`key` = its `lin_key`), each tagged with its radius.
+#[derive(Clone, Default)]
+struct Planes {
+ key: u64,
+ log_l: Option<Arc<Buf>>,
+ base: Option<(u32, Arc<Buf>)>,
+ clarity: Option<(u32, Arc<Buf>)>,
+ texture: Option<(u32, Arc<Buf>)>,
+ dark: Option<(u32, Arc<Buf>, f32)>,
+}
+
+impl GpuStages {
+ fn get(&self, src: &Arc<Rgb32f>, geo: u64) -> Option<Entry> {
+ self.lock().iter().find(|e| e.geo == geo && Arc::ptr_eq(&e.src, src)).cloned()
+ }
+
+ fn put(&self, e: Entry) {
+ let mut v = self.lock();
+ v.retain(|o| !(o.geo == e.geo && Arc::ptr_eq(&o.src, &e.src)));
+ v.push(e);
+ while v.len() > CAPACITY {
+ v.remove(0);
+ }
+ }
+
+ fn lock(&self) -> std::sync::MutexGuard<'_, Vec<Entry>> {
+ self.entries.lock().unwrap_or_else(|e| e.into_inner())
+ }
+
+ /// Number of cached output sizes.
+ pub fn len(&self) -> usize {
+ self.lock().len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.len() == 0
+ }
+}
+
+/// CPU copies made along the way (for stages that still run on the CPU).
+#[derive(Default)]
+struct Host {
+ lin: Option<Arc<Rgb32f>>,
+ log_l: Option<Arc<Plane>>,
+}
+
+fn rgb_words(img: &Rgb32f) -> &[f32] {
+ bytemuck::cast_slice(&img.data)
+}
+
+pub(crate) fn download_rgb(gpu: &Gpu, b: &Buf, w: usize, h: usize) -> Rgb32f {
+ let v: Vec<[f32; 3]> = gpu.finish_and_read(gpu.encoder(), b, w * h * 3);
+ Rgb32f { width: w, height: h, data: v }
+}
+
+pub(crate) fn download_plane(gpu: &Gpu, b: &Buf, w: usize, h: usize) -> Plane {
+ let v: Vec<f32> = gpu.finish_and_read(gpu.encoder(), b, w * h);
+ Plane { width: w, height: h, data: v }
+}
+
+/// Render on `gpu`, reusing `stages` (if given). `None` when the render does not fit the device.
+pub fn render(
+ gpu: &Gpu,
+ src: &Arc<Rgb32f>,
+ info: &SourceInfo,
+ s: &DevelopSettings,
+ req: &RenderRequest,
+ stages: Option<&GpuStages>,
+) -> Option<Rendered> {
+ let prof = lightcraft_pipeline_profiling();
+ let mut t = prof.then(std::time::Instant::now);
+ let lap = |what: &str, t: &mut Option<std::time::Instant>| {
+ if let Some(t) = t {
+ eprintln!(" gpu {what}: {:.1} ms", t.elapsed().as_secs_f64() * 1e3);
+ *t = std::time::Instant::now();
+ }
+ };
+ let plan = lightcraft_pipeline::plan(src, info, s, req);
+ let (w, h) = (plan.w, plan.h);
+ let n = w * h;
+ if !gpu.fits(n * 3) || !gpu.fits(src.data.len() * 3) {
+ return None;
+ }
+ let s = &*plan.settings;
+ let cached = stages.and_then(|c| c.get(src, plan.geo));
+ let mut host = Host::default();
+
+ // 1. geometry
+ let sampled = match &cached {
+ Some(e) => e.sampled.clone(),
+ None => Arc::new(sample(gpu, src, &plan)),
+ };
+ lap("sample", &mut t);
+
+ // 2. white balance, defringe, spots, noise reduction
+ let lin = match cached.as_ref().and_then(|e| e.lin.clone()).filter(|(k, _)| *k == plan.lin_key) {
+ Some((_, b)) => b,
+ None => Arc::new(linear(gpu, &sampled, info, &plan, &mut host)),
+ };
+ lap("wb/nr", &mut t);
+
+ // 3. spatial planes
+ let mut planes = match cached.map(|e| e.planes) {
+ Some(p) if p.key == plan.lin_key => p,
+ _ => Planes { key: plan.lin_key, ..Default::default() },
+ };
+ let prep = prepare(gpu, &lin, &plan, req, &mut planes, &mut host);
+ lap("planes", &mut t);
+ if let Some(c) = stages {
+ c.put(Entry { src: src.clone(), geo: plan.geo, sampled, lin: Some((plan.lin_key, lin.clone())), planes });
+ }
+
+ // 4. masks
+ let (masks, terms) = masks(gpu, &lin, &prep, &plan, &mut host);
+ lap("masks", &mut t);
+
+ // 5. per-pixel stage
+ let fp = FinishParams::new(s, &plan.frame, info, w, h, plan.px_per_long, prep.air);
+ let present = Present { clarity: prep.clarity.is_some(), texture: prep.texture.is_some(), dark: prep.dark.is_some() };
+ let (p, aux) = finish_block(&fp, &terms, &present);
+ let aux = gpu.upload(&aux);
+ let out = gpu.buffer(n);
+ let mut enc = gpu.encoder();
+ gpu.run(
+ &mut enc,
+ "main",
+ &p,
+ &[
+ Some(&lin),
+ Some(&prep.log_l),
+ Some(&prep.base),
+ prep.clarity.as_deref(),
+ prep.texture.as_deref(),
+ prep.dark.as_deref(),
+ masks.as_ref(),
+ Some(&aux),
+ Some(&out),
+ ],
+ groups2(w, h, [16, 16]),
+ );
+ let data: Vec<[u8; 4]> = gpu.finish_and_read(enc, &out, n);
+ let image = Rgba8 { width: w, height: h, data };
+ lap("finish", &mut t);
+ let histogram = Histogram::of_srgb8(&image);
+ Some(Rendered { image, histogram })
+}
+
+fn lightcraft_pipeline_profiling() -> bool {
+ static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ *ON.get_or_init(|| std::env::var_os("LIGHTCRAFT_PROFILE").is_some())
+}
+
+/// Resample the source into the output frame.
+fn sample(gpu: &Gpu, src: &Arc<Rgb32f>, plan: &Plan<'_>) -> Buf {
+ let img = plan.frame.sample(src, plan.w, plan.h);
+ gpu.upload(rgb_words(&img))
+}
+
+/// The white-balanced, retouched, denoised image.
+fn linear(gpu: &Gpu, sampled: &Buf, info: &SourceInfo, plan: &Plan<'_>, host: &mut Host) -> Buf {
+ let mut img = download_rgb(gpu, sampled, plan.w, plan.h);
+ lightcraft_pipeline::lin_cpu(&mut img, info, plan);
+ local::denoise(&mut img, &plan.settings, plan.src_long, plan.w.max(plan.h));
+ let b = gpu.upload(rgb_words(&img));
+ host.lin = Some(Arc::new(img));
+ b
+}
+
+/// The planes the per-pixel stage reads.
+struct Prep {
+ log_l: Arc<Buf>,
+ base: Arc<Buf>,
+ clarity: Option<Arc<Buf>>,
+ texture: Option<Arc<Buf>>,
+ dark: Option<Arc<Buf>>,
+ air: f32,
+}
+
+fn host_lin(gpu: &Gpu, lin: &Buf, plan: &Plan<'_>, host: &mut Host) -> Arc<Rgb32f> {
+ host.lin.get_or_insert_with(|| Arc::new(download_rgb(gpu, lin, plan.w, plan.h))).clone()
+}
+
+fn host_log_l(gpu: &Gpu, prep_log_l: &Buf, plan: &Plan<'_>, host: &mut Host) -> Arc<Plane> {
+ host.log_l.get_or_insert_with(|| Arc::new(download_plane(gpu, prep_log_l, plan.w, plan.h))).clone()
+}
+
+fn plane_at(slot: &mut Option<(u32, Arc<Buf>)>, sigma: f32, f: impl FnOnce() -> Buf) -> Arc<Buf> {
+ match slot {
+ Some((k, p)) if *k == sigma.to_bits() => p.clone(),
+ _ => {
+ let p = Arc::new(f());
+ *slot = Some((sigma.to_bits(), p.clone()));
+ p
+ }
+ }
+}
+
+fn prepare(gpu: &Gpu, lin: &Buf, plan: &Plan<'_>, req: &RenderRequest, planes: &mut Planes, host: &mut Host) -> Prep {
+ let s = &*plan.settings;
+ let sig = local::plane_sigmas(s, plan.px_per_long, req.quality);
+ let log_l = match &planes.log_l {
+ Some(b) => b.clone(),
+ None => {
+ let img = host_lin(gpu, lin, plan, host);
+ let l = img.map(local::log_lum);
+ let b = Arc::new(gpu.upload(&l.data));
+ host.log_l = Some(Arc::new(l));
+ planes.log_l = Some(b.clone());
+ b
+ }
+ };
+ let mut cpu_plane = |f: &dyn Fn(&Plane, &Rgb32f) -> Plane| {
+ let l = host_log_l(gpu, &log_l, plan, host);
+ let img = host_lin(gpu, lin, plan, host);
+ gpu.upload(&f(&l, &img).data)
+ };
+ let base = match sig.base {
+ Some(sg) => plane_at(&mut planes.base, sg, || cpu_plane(&|l, _| local::guided_fast(l, sg, local::BASE_EPS))),
+ None => log_l.clone(),
+ };
+ let clarity = sig.clarity.map(|sg| plane_at(&mut planes.clarity, sg, || cpu_plane(&|l, _| local::guided_fast(l, sg, local::CLARITY_EPS))));
+ let texture = sig.texture.map(|sg| plane_at(&mut planes.texture, sg, || cpu_plane(&|l, _| lightcraft_raster::blur::gaussian(l, sg))));
+ let (dark, air) = match sig.dark {
+ None => (None, 1.0),
+ Some(sg) => match &planes.dark {
+ Some((k, d, air)) if *k == sg.to_bits() => (Some(d.clone()), *air),
+ _ => {
+ let img = host_lin(gpu, lin, plan, host);
+ let d = lightcraft_raster::blur::gaussian(&img.map(local::dark_of), sg);
+ let air = local::airlight(&d);
+ let b = Arc::new(gpu.upload(&d.data));
+ planes.dark = Some((sg.to_bits(), b.clone(), air));
+ (Some(b), air)
+ }
+ },
+ };
+ Prep { log_l, base, clarity, texture, dark, air }
+}
+
+/// Evaluate the masks: their alpha planes (concatenated) and their adjustment terms.
+fn masks(gpu: &Gpu, lin: &Buf, prep: &Prep, plan: &Plan<'_>, host: &mut Host) -> (Option<Buf>, Vec<[f32; lightcraft_pipeline::finish::MASK_TERMS]>) {
+ let s = &*plan.settings;
+ if !s.masks.iter().any(|m| m.visible && !m.components.is_empty()) {
+ return (None, Vec::new());
+ }
+ let img = host_lin(gpu, lin, plan, host);
+ let l = host_log_l(gpu, &prep.log_l, plan, host);
+ let ev = s.light.exposure as f32;
+ let ev = lightcraft_pipeline::masks::evaluate(&s.masks, &plan.frame, plan.w, plan.h, &img, &l, ev);
+ let terms = ev.iter().map(|m| mask_terms(&m.adjust)).collect();
+ let mut all = Vec::with_capacity(ev.len() * plan.w * plan.h);
+ for m in &ev {
+ all.extend_from_slice(&m.alpha.data);
+ }
+ (Some(gpu.upload(&all)), terms)
+}
diff --git a/crates/gpu/src/wgsl/blur.wgsl b/crates/gpu/src/wgsl/blur.wgsl
new file mode 100644
index 000000000..6312864e4
--- /dev/null
+++ b/crates/gpu/src/wgsl/blur.wgsl
@@ -0,0 +1,61 @@
+// Box passes (clamped edges) over an image of NC interleaved channels; three of each approximate a
+// Gaussian (`lightcraft_raster::blur::gaussian`). Each thread slides a running sum over CH pixels.
+// P: w, h, nc, r, ch. Bindings: src, dst.
+
+// Horizontal: one thread per CH consecutive pixels of a row.
+@compute @workgroup_size(64, 4)
+fn box_h(@builtin(global_invocation_id) g: vec3<u32>) {
+ let w = pu(0u);
+ let h = pu(1u);
+ let nc = pu(2u);
+ let r = i32(pu(3u));
+ let ch = pu(4u);
+ let y = g.y;
+ let x0 = g.x * ch;
+ if (y >= h || x0 >= w) {
+ return;
+ }
+ let last = i32(w) - 1;
+ let inv = 1.0 / f32(2 * r + 1);
+ let row = y * w;
+ let x1 = min(x0 + ch, w);
+ for (var c = 0u; c < nc; c++) {
+ var acc = 0.0;
+ for (var k = -r; k <= r; k++) {
+ acc += src[(row + u32(clamp(i32(x0) + k, 0, last))) * nc + c];
+ }
+ for (var x = x0; x < x1; x++) {
+ dst[(row + x) * nc + c] = acc * inv;
+ acc = acc + src[(row + u32(min(i32(x) + r + 1, last))) * nc + c] - src[(row + u32(max(i32(x) - r, 0))) * nc + c];
+ }
+ }
+}
+
+// Vertical: one thread per CH consecutive rows of a column (the CPU re-primes every BAND rows the
+// same way).
+@compute @workgroup_size(64, 4)
+fn box_v(@builtin(global_invocation_id) g: vec3<u32>) {
+ let w = pu(0u);
+ let h = pu(1u);
+ let nc = pu(2u);
+ let r = i32(pu(3u));
+ let ch = pu(4u);
+ let x = g.x;
+ let y0 = g.y * ch;
+ if (x >= w || y0 >= h) {
+ return;
+ }
+ let last = i32(h) - 1;
+ let inv = 1.0 / f32(2 * r + 1);
+ let y1 = min(y0 + ch, h);
+ for (var c = 0u; c < nc; c++) {
+ var acc = 0.0;
+ for (var k = -r; k <= r; k++) {
+ acc += src[(u32(clamp(i32(y0) + k, 0, last)) * w + x) * nc + c];
+ }
+ for (var y = y0; y < y1; y++) {
+ dst[(y * w + x) * nc + c] = acc * inv;
+ acc = acc + src[(u32(min(i32(y) + r + 1, last)) * w + x) * nc + c] - src[(u32(max(i32(y) - r, 0)) * w + x) * nc + c];
+ }
+ }
+}
diff --git a/crates/gpu/src/wgsl/common.wgsl b/crates/gpu/src/wgsl/common.wgsl
new file mode 100644
index 000000000..409972e4f
--- /dev/null
+++ b/crates/gpu/src/wgsl/common.wgsl
@@ -0,0 +1,67 @@
+// Shared helpers, prepended to every kernel (after the generated constants and bindings).
+// Each function mirrors its CPU twin in `lightcraft-pipeline` / `lightcraft-color`; keep them in step.
+
+fn pu(i: u32) -> u32 {
+ return P[i];
+}
+
+fn pf(i: u32) -> f32 {
+ return bitcast<f32>(P[i]);
+}
+
+// Linear index of a 1-D kernel dispatched on a 2-D grid of 256-wide workgroups.
+fn lin_index(g: vec3<u32>, n: vec3<u32>) -> u32 {
+ return g.x + g.y * n.x * 256u;
+}
+
+fn sstep(e0: f32, e1: f32, x: f32) -> f32 {
+ let t = clamp((x - e0) / (e1 - e0), 0.0, 1.0);
+ return t * t * (3.0 - 2.0 * t);
+}
+
+fn rem_euclid(a: f32, b: f32) -> f32 {
+ let r = a % b;
+ return select(r, r + b, r < 0.0);
+}
+
+const PI: f32 = 3.14159265358979323846;
+const TAU: f32 = 6.28318530717958647692;
+const GREY: f32 = 0.18;
+
+fn wrap_angle(a: f32) -> f32 {
+ return rem_euclid(a + PI, TAU) - PI;
+}
+
+// Rec.2020 luminance (`lightcraft_color::luminance_2020`).
+fn lum2020(c: vec3<f32>) -> f32 {
+ return c.x * 0.2627 + c.y * 0.6780 + c.z * 0.0593;
+}
+
+// `lightcraft_pipeline::local::log_lum`.
+fn log_lum(c: vec3<f32>) -> f32 {
+ return log2(max(lum2020(c), 1e-7) / GREY);
+}
+
+fn mul3(m: array<vec3<f32>, 3>, v: vec3<f32>) -> vec3<f32> {
+ return vec3<f32>(
+ m[0].x * v.x + m[0].y * v.y + m[0].z * v.z,
+ m[1].x * v.x + m[1].y * v.y + m[1].z * v.z,
+ m[2].x * v.x + m[2].y * v.y + m[2].z * v.z,
+ );
+}
+
+fn cbrt(x: f32) -> f32 {
+ return sign(x) * pow(abs(x), 1.0 / 3.0);
+}
+
+// Linear Rec.2020 → OkLab.
+fn oklab(c: vec3<f32>) -> vec3<f32> {
+ let lms = mul3(OK_TO_LMS, c);
+ return mul3(OK_TO_LAB, vec3<f32>(cbrt(lms.x), cbrt(lms.y), cbrt(lms.z)));
+}
+
+// OkLab → linear Rec.2020.
+fn oklab_inv(lab: vec3<f32>) -> vec3<f32> {
+ let l = mul3(OK_FROM_LAB, lab);
+ return mul3(OK_FROM_LMS, l * l * l);
+}
diff --git a/crates/gpu/src/wgsl/finish.wgsl b/crates/gpu/src/wgsl/finish.wgsl
new file mode 100644
index 000000000..0548ab5db
--- /dev/null
+++ b/crates/gpu/src/wgsl/finish.wgsl
@@ -0,0 +1,358 @@
+// The per-pixel stage: a straight port of `lightcraft_pipeline::finish` (keep in step with it).
+// Bindings: img (rgb, pre-exposure), log_l, base, clar, tex, dark, masks (NMASK planes), aux
+// (tone LUT | sRGB LUT | curve LUTs | mask terms), out (packed RGBA8).
+
+fn tone_apply(y: f32) -> f32 {
+ if (y <= 0.0) {
+ return 0.0;
+ }
+ let ev = log2(y / GREY);
+ let f = clamp((ev - TONE_MIN_EV) / (TONE_MAX_EV - TONE_MIN_EV), 0.0, 1.0) * f32(TONE_N - 1u);
+ let i = min(u32(f), TONE_N - 2u);
+ let t = f - f32(i);
+ let v = aux[i] + (aux[i + 1u] - aux[i]) * t;
+ if (ev < TONE_MIN_EV) {
+ return v * (y / (GREY * TONE_MIN_GAIN));
+ }
+ return v;
+}
+
+fn encode_srgb(v: f32) -> f32 {
+ let o = pu(F_SRGB_OFF);
+ let f = clamp(v, 0.0, 1.0) * f32(SRGB_N);
+ let i = min(u32(f), SRGB_N - 1u);
+ let t = f - f32(i);
+ return aux[o + i] + (aux[o + i + 1u] - aux[o + i]) * t;
+}
+
+fn curve(ch: u32, x: f32) -> f32 {
+ let o = pu(F_CURVE_OFF) + ch * CURVE_N;
+ let f = clamp(x, 0.0, 1.0) * f32(CURVE_N - 1u);
+ let i = min(u32(f), CURVE_N - 2u);
+ let t = f - f32(i);
+ return aux[o + i] + (aux[o + i + 1u] - aux[o + i]) * t;
+}
+
+fn band_weights(h: f32) -> array<f32, 8> {
+ var w: array<f32, 8>;
+ for (var i = 0u; i < 8u; i++) {
+ let a = pf(F_BANDH + i);
+ let b = pf(F_BANDH + (i + 1u) % 8u);
+ let span = rem_euclid(wrap_angle(b - a), TAU);
+ let d = rem_euclid(wrap_angle(h - a), TAU);
+ if (d <= span) {
+ let t = d / span;
+ let s = 0.5 - 0.5 * cos(t * PI);
+ w[i] += 1.0 - s;
+ w[(i + 1u) % 8u] += s;
+ break;
+ }
+ }
+ return w;
+}
+
+// `ColorOps::apply`.
+fn color_ops(rgb: vec3<f32>, local_sat: f32, local_hue: f32) -> vec3<f32> {
+ if (pu(F_OPS_IDENTITY) != 0u && local_sat == 0.0 && local_hue == 0.0) {
+ return rgb;
+ }
+ let lab0 = oklab(rgb);
+ var l = lab0.x;
+ var c = sqrt(lab0.y * lab0.y + lab0.z * lab0.z);
+ var h = atan2(lab0.z, lab0.y);
+ if (pu(F_MIXER) != 0u) {
+ let w = band_weights(h);
+ var dh = 0.0;
+ var ds = 0.0;
+ var dl = 0.0;
+ for (var i = 0u; i < 8u; i++) {
+ dh += w[i] * pf(F_MIX_HUE + i);
+ ds += w[i] * pf(F_MIX_SAT + i);
+ dl += w[i] * pf(F_MIX_LUM + i);
+ }
+ let chroma_w = min(c / 0.12, 1.0);
+ h += dh * chroma_w;
+ c *= max(1.0 + ds, 0.0);
+ l += dl * chroma_w * sqrt(max(l, 0.05));
+ }
+ let vib = pf(F_VIBRANCE);
+ if (vib != 0.0) {
+ let low = 1.0 - clamp(c / 0.22, 0.0, 1.0);
+ var skin = 1.0;
+ if (vib > 0.0) {
+ let q = wrap_angle(h - pf(F_SKIN)) / 0.35;
+ skin = 1.0 - 0.6 * exp(-(q * q));
+ }
+ c *= max(1.0 + vib * low * low * skin * 1.2, 0.0);
+ }
+ let sat = pf(F_SATURATION);
+ if (sat != 0.0 || local_sat != 0.0) {
+ c *= max(1.0 + sat + local_sat, 0.0);
+ }
+ h += local_hue;
+ if (pu(F_BW) != 0u) {
+ let w = band_weights(h);
+ var mix = 0.0;
+ for (var i = 0u; i < 8u; i++) {
+ mix += w[i] * pf(F_BW_MIX + i);
+ }
+ l = max(l + mix * min(c / 0.2, 1.0) * 0.25, 0.0);
+ c = 0.0;
+ }
+ var lab = vec3<f32>(l, c * cos(h), c * sin(h));
+ if (pu(F_GRADING) != 0u) {
+ let m = 0.5 - pf(F_BALANCE) * 0.25;
+ let width = 0.15 + pf(F_BLENDING) * 0.5;
+ let ws = 1.0 - sstep(m - width, m + width * 0.25, lab.x);
+ let wh = sstep(m - width * 0.25, m + width, lab.x);
+ let wm = max(1.0 - ws - wh, 0.0);
+ let wts = array<f32, 4>(ws, wm, wh, 1.0);
+ for (var k = 0u; k < 4u; k++) {
+ let wt = wts[k];
+ lab.y += pf(F_WHEELS + 3u * k) * wt;
+ lab.z += pf(F_WHEELS + 3u * k + 1u) * wt;
+ lab.x += pf(F_WHEELS + 3u * k + 2u) * wt;
+ }
+ }
+ return oklab_inv(lab);
+}
+
+fn ghash(i: i32, j: i32, seed: u32) -> f32 {
+ var v = (bitcast<u32>(i) * GRAIN_H0) ^ (bitcast<u32>(j) * GRAIN_H1) ^ (seed * GRAIN_H2);
+ v ^= v >> 13u;
+ v = v * GRAIN_H3;
+ v ^= v >> 15u;
+ return f32(v & 0xffffu) / 32768.0 - 1.0;
+}
+
+fn grain_noise(x: f32, y: f32, seed: u32) -> f32 {
+ let x0 = floor(x);
+ let y0 = floor(y);
+ let fx = x - x0;
+ let fy = y - y0;
+ let i = i32(x0);
+ 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;
+ return a + (b - a) * v;
+}
+
+fn enc8(v: f32) -> u32 {
+ return u32(clamp(v, 0.0, 1.0) * 255.0 + 0.5);
+}
+
+@compute @workgroup_size(16, 16)
+fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
+ let w = pu(F_W);
+ let h = pu(F_H);
+ if (gid.x >= w || gid.y >= h) {
+ return;
+ }
+ let x = gid.x;
+ let y = gid.y;
+ let i = y * w + x;
+ let n = w * h;
+ let gain = pf(F_GAIN);
+ let ev = pf(F_EV);
+ var c = vec3<f32>(img[3u * i], img[3u * i + 1u], img[3u * i + 2u]);
+ if (gain != 1.0) {
+ c = c * gain;
+ }
+ let l_pre = log_l[i];
+ let l0 = l_pre + ev;
+
+ // --- local (mask) contributions
+ var lt: array<f32, 14>;
+ var tint_on = false;
+ var tint_dir = vec2<f32>(0.0, 0.0);
+ var tint_amt = 0.0;
+ let nm = pu(F_NMASK);
+ for (var m = 0u; m < nm; m++) {
+ let a = masks[m * n + i];
+ if (a <= 0.0) {
+ continue;
+ }
+ let t = pu(F_MASK_OFF) + m * MASK_TERMS;
+ for (var k = 0u; k < 14u; k++) {
+ lt[k] += a * aux[t + k];
+ }
+ if (aux[t + 14u] > 0.0) {
+ tint_on = true;
+ tint_dir = vec2<f32>(aux[t + 15u], aux[t + 16u]);
+ tint_amt = a * aux[t + 17u];
+ }
+ }
+ let l_exp = lt[0];
+ let l_temp = lt[1];
+ let l_tint = lt[2];
+
+ // --- dehaze (scene linear)
+ let dz = pf(F_DEHAZE) + lt[10];
+ if (dz != 0.0 && pu(F_HAS_DARK) != 0u) {
+ let d = clamp(dark[i] / pf(F_AIR_PRE), 0.0, 1.0);
+ let air = pf(F_AIR);
+ if (dz > 0.0) {
+ let t = max(1.0 - 0.95 * min(dz, 1.0) * d, 0.12);
+ c = max((c - air * (1.0 - t)) / t, vec3<f32>(0.0));
+ } else {
+ let k = min(-dz, 1.0) * 0.7 * (0.35 + 0.65 * d);
+ c = c + (air * 0.9 - c) * k;
+ }
+ }
+
+ // --- local exposure / temp / tint
+ if (l_exp != 0.0) {
+ c = c * exp2(l_exp);
+ }
+ if (l_temp != 0.0 || l_tint != 0.0) {
+ let y0 = lum2020(c);
+ c = vec3<f32>(c.x * (1.0 + 0.3 * l_temp), c.y * (1.0 - 0.22 * l_tint), c.z * max(1.0 - 0.3 * l_temp, 0.0));
+ let y1 = max(lum2020(c), 1e-9);
+ c = c * y0 / y1;
+ }
+
+ // --- local tone in log luminance
+ var l1 = l0;
+ if (dz != 0.0 || l_exp != 0.0) {
+ l1 = log_lum(c);
+ }
+ let shift = l1 - l0;
+ let base = base_p[i] + ev + shift;
+ var delta = 0.0;
+ let hh = pf(F_HL) + lt[4];
+ let ss = pf(F_SH) + lt[5];
+ if (hh != 0.0 || ss != 0.0) {
+ let ws = 1.0 - sstep(-4.8, 0.3, base);
+ let wh = sstep(-1.0, 2.8, base);
+ delta += ss * 1.7 * ws * sqrt(ws) + hh * 1.7 * wh;
+ }
+ if (lt[6] != 0.0) {
+ delta += lt[6] * 0.8 * sstep(0.5, 3.0, l1);
+ }
+ if (lt[7] != 0.0) {
+ delta += lt[7] * 0.8 * (1.0 - sstep(-6.0, -1.5, l1));
+ }
+ if (lt[3] != 0.0) {
+ delta += lt[3] * 0.14 * clamp(l1, -6.0, 4.0);
+ }
+ let cl = pf(F_CLAR) + lt[9];
+ if (cl != 0.0 && pu(F_HAS_CLAR) != 0u) {
+ let det = clamp(l_pre - clar[i], -2.5, 2.5);
+ let q = base / 3.2;
+ let mid = exp(-(q * q));
+ delta += cl * 0.85 * det * (0.35 + 0.65 * mid);
+ }
+ let tx = pf(F_TEX) + lt[8];
+ let sp = lt[13] * 0.6 + pf(F_SHARPEN);
+ if ((tx != 0.0 || sp != 0.0) && pu(F_HAS_TEX) != 0u) {
+ let det = l_pre - tex[i];
+ let tame = 1.0 - 0.6 * sstep(0.4, 1.6, abs(det));
+ delta += tx * 1.1 * clamp(det, -1.0, 1.0) * tame;
+ if (sp != 0.0) {
+ let sm = pf(F_SHARPEN_MASK);
+ var mk = 1.0;
+ if (sm > 0.0) {
+ mk = sstep(sm * 0.25, sm * 0.25 + 0.15, abs(det));
+ }
+ delta += sp * 1.3 * clamp(det, -0.8, 0.8) * mk;
+ }
+ }
+ if (delta != 0.0) {
+ c = c * exp2(delta);
+ }
+
+ // --- tone map on luminance, highlight desaturation
+ let yl = lum2020(c);
+ let o = tone_apply(yl);
+ var d = vec3<f32>(0.0);
+ if (yl > 1e-9) {
+ d = c * o / yl;
+ }
+ let mx = max(d.x, max(d.y, d.z));
+ if (mx > 1.0) {
+ let t = clamp((mx - 1.0) / max(mx - o, 1e-6), 0.0, 1.0);
+ d = d + (o - d) * t;
+ }
+
+ // --- colour
+ d = color_ops(d, lt[11], lt[12]);
+ if (tint_on) {
+ let lab = oklab(d);
+ d = oklab_inv(vec3<f32>(lab.x, lab.y + tint_dir.x * 0.08 * tint_amt, lab.z + tint_dir.y * 0.08 * tint_amt));
+ }
+
+ // --- vignette (display linear, post-crop)
+ if (pu(F_VIG) != 0u) {
+ let fw = f32(w);
+ let fh = f32(h);
+ let aspect = fw / fh;
+ let amount = pf(F_VIG_AMOUNT);
+ let mixa = pf(F_VIG_ASPECT_MIX);
+ let power = pf(F_VIG_POWER);
+ let u = (f32(x) + 0.5) / fw * 2.0 - 1.0;
+ let vv = (f32(y) + 0.5) / fh * 2.0 - 1.0;
+ let sx = 1.0 + (aspect - 1.0) * mixa;
+ let sy = 1.0 + (1.0 / aspect - 1.0) * mixa;
+ let ax = abs(u * max(sx, 1.0) / max(sx, sy));
+ let ay = abs(vv * max(sy, 1.0) / max(sx, sy));
+ let dist = pow(pow(ax, power) + pow(ay, power), 1.0 / power);
+ let start = pf(F_VIG_START);
+ let t = sstep(start, start + pf(F_VIG_WIDTH), dist);
+ if (t > 0.0) {
+ let lum = clamp(lum2020(d), 0.0, 1.0);
+ if (amount < 0.0) {
+ var f = 1.0 + amount * t;
+ let style = pu(F_VIG_STYLE);
+ if (style == 1u) {
+ f += (1.0 - f) * pf(F_VIG_HL) * sstep(0.4, 1.0, lum);
+ }
+ if (style == 2u) {
+ d = d * (1.0 - (-amount) * t) + 0.0;
+ } else {
+ d = d * f;
+ }
+ } else {
+ d = d + (1.0 - d) * amount * t * 0.85;
+ }
+ }
+ }
+
+ // --- gamut map to sRGB (desaturate towards luminance until in range)
+ var r = mul3(TO_SRGB, d);
+ let yy = clamp(0.2126 * r.x + 0.7152 * r.y + 0.0722 * r.z, 0.0, 1.0);
+ var tg = 1.0;
+ for (var k = 0u; k < 3u; k++) {
+ let cc = r[k];
+ if (cc < 0.0) {
+ tg = min(tg, yy / max(yy - cc, 1e-9));
+ } else if (cc > 1.0) {
+ tg = min(tg, (1.0 - yy) / max(cc - yy, 1e-9));
+ }
+ }
+ if (tg < 1.0) {
+ r = yy + (r - yy) * tg;
+ }
+
+ // --- encode, curves, grain
+ var e = vec3<f32>(encode_srgb(r.x), encode_srgb(r.y), encode_srgb(r.z));
+ if (pu(F_CURVES) != 0u) {
+ e = vec3<f32>(curve(0u, e.x), curve(1u, e.y), curve(2u, e.z));
+ }
+ if (pu(F_GRAIN) != 0u) {
+ let px = f32(x) + 0.5;
+ 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;
+ }
+ out[i] = enc8(e.x) | (enc8(e.y) << 8u) | (enc8(e.z) << 16u) | (255u << 24u);
+}
diff --git a/crates/gpu/src/wgsl/map.wgsl b/crates/gpu/src/wgsl/map.wgsl
new file mode 100644
index 000000000..c0a4419a9
--- /dev/null
+++ b/crates/gpu/src/wgsl/map.wgsl
@@ -0,0 +1,137 @@
+// Element-wise kernels (one thread per pixel, 1-D on a 2-D grid). Bindings: a, b, c (inputs), dst.
+// P[0] = pixel count; further parameters per kernel. Each mirrors a CPU expression in
+// `lightcraft_pipeline::local` (named in the comment).
+
+fn rgb_a(i: u32) -> vec3<f32> {
+ return vec3<f32>(a[3u * i], a[3u * i + 1u], a[3u * i + 2u]);
+}
+
+fn put_rgb(i: u32, v: vec3<f32>) {
+ dst[3u * i] = v.x;
+ dst[3u * i + 1u] = v.y;
+ dst[3u * i + 2u] = v.z;
+}
+
+// `log_lum` of an RGB image.
+@compute @workgroup_size(256)
+fn log_lum_k(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
+ let i = lin_index(g, nw);
+ if (i >= pu(0u)) {
+ return;
+ }
+ dst[i] = log_lum(rgb_a(i));
+}
+
+// `dark_of`: the dark channel (dehaze).
+@compute @workgroup_size(256)
+fn dark_k(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
+ let i = lin_index(g, nw);
+ if (i >= pu(0u)) {
+ return;
+ }
+ let c = rgb_a(i);
+ dst[i] = min(min(c.x, c.y), c.z);
+}
+
+// Guided filter input pair (p, p²).
+@compute @workgroup_size(256)
+fn guided_pre(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
+ let i = lin_index(g, nw);
+ if (i >= pu(0u)) {
+ return;
+ }
+ let p = a[i];
+ dst[2u * i] = p;
+ dst[2u * i + 1u] = p * p;
+}
+
+// Guided filter coefficients (a, b) from blurred (mean, corr). P[1] = eps.
+@compute @workgroup_size(256)
+fn guided_ab(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
+ let i = lin_index(g, nw);
+ if (i >= pu(0u)) {
+ return;
+ }
+ let m = a[2u * i];
+ let c = a[2u * i + 1u];
+ let v = max(c - m * m, 0.0);
+ let k = v / (v + pf(1u));
+ dst[2u * i] = k;
+ dst[2u * i + 1u] = m - k * m;
+}
+
+// `q = a·p + b` (a: p, b: interleaved blurred coefficients).
+@compute @workgroup_size(256)
+fn guided_apply(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
+ let i = lin_index(g, nw);
+ if (i >= pu(0u)) {
+ return;
+ }
+ dst[i] = b[2u * i] * a[i] + b[2u * i + 1u];
+}
+
+// White balance: 3×3 matrix (P[1] = has matrix, P[2..11] row-major), clamped at 0.
+@compute @workgroup_size(256)
+fn wb_k(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
+ let i = lin_index(g, nw);
+ if (i >= pu(0u)) {
+ return;
+ }
+ var c = rgb_a(i);
+ if (pu(1u) != 0u) {
+ c = vec3<f32>(
+ pf(2u) * c.x + pf(3u) * c.y + pf(4u) * c.z,
+ pf(5u) * c.x + pf(6u) * c.y + pf(7u) * c.z,
+ pf(8u) * c.x + pf(9u) * c.y + pf(10u) * c.z,
+ );
+ }
+ put_rgb(i, max(c * 1.0, vec3<f32>(0.0)));
+}
+
+// Luminance NR: scale by 2^((f − l)·k) (a: image, b: log luminance l, c: filtered f). P[1] = k.
+@compute @workgroup_size(256)
+fn nr_lum(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
+ let i = lin_index(g, nw);
+ if (i >= pu(0u)) {
+ return;
+ }
+ let d = (c[i] - b[i]) * pf(1u);
+ put_rgb(i, rgb_a(i) * exp2(d));
+}
+
+// Chromaticity rgb / Y.
+@compute @workgroup_size(256)
+fn chroma_k(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
+ let i = lin_index(g, nw);
+ if (i >= pu(0u)) {
+ return;
+ }
+ let c0 = rgb_a(i);
+ let y = max(lum2020(c0), 1e-6);
+ put_rgb(i, vec3<f32>(c0.x / y, c0.y / y, c0.z / y));
+}
+
+// Colour NR: blend chromaticity towards its blur and re-apply luminance (a: image, b: chroma,
+// c: blurred chroma). P[1] = t.
+@compute @workgroup_size(256)
+fn nr_col(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
+ let i = lin_index(g, nw);
+ if (i >= pu(0u)) {
+ return;
+ }
+ let yl = lum2020(rgb_a(i));
+ let t = pf(1u);
+ let c0 = vec3<f32>(b[3u * i], b[3u * i + 1u], b[3u * i + 2u]);
+ let cb = vec3<f32>(c[3u * i], c[3u * i + 1u], c[3u * i + 2u]);
+ put_rgb(i, max((c0 + (cb - c0) * t) * yl, vec3<f32>(0.0)));
+}
+
+// Every P[1]-th value of `a` (airlight sampling). P[0] = output count.
+@compute @workgroup_size(256)
+fn subsample(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgroups) nw: vec3<u32>) {
+ let i = lin_index(g, nw);
+ if (i >= pu(0u)) {
+ return;
+ }
+ dst[i] = a[i * pu(1u)];
+}
diff --git a/crates/gpu/src/wgsl/resize.wgsl b/crates/gpu/src/wgsl/resize.wgsl
new file mode 100644
index 000000000..a766e53ab
--- /dev/null
+++ b/crates/gpu/src/wgsl/resize.wgsl
@@ -0,0 +1,51 @@
+// Separable resample with precomputed taps (`lightcraft_raster::resample::weights`, uploaded):
+// table[3i..3i+3] = (first source index, tap count, weight offset), weights stored as f32 bits.
+// Bindings: src, table (u32), dst.
+
+// Horizontal. P: sw, h, dw, nc.
+@compute @workgroup_size(16, 16)
+fn resize_h(@builtin(global_invocation_id) g: vec3<u32>) {
+ let sw = pu(0u);
+ let h = pu(1u);
+ let dw = pu(2u);
+ let nc = pu(3u);
+ let x = g.x;
+ let y = g.y;
+ if (x >= dw || y >= h) {
+ return;
+ }
+ let lo = table[3u * x];
+ let cnt = table[3u * x + 1u];
+ let off = table[3u * x + 2u];
+ for (var c = 0u; c < nc; c++) {
+ var acc = 0.0;
+ for (var k = 0u; k < cnt; k++) {
+ acc = acc + src[(y * sw + lo + k) * nc + c] * bitcast<f32>(table[off + k]);
+ }
+ dst[(y * dw + x) * nc + c] = acc;
+ }
+}
+
+// Vertical. P: w, sh, dh, nc.
+@compute @workgroup_size(16, 16)
+fn resize_v(@builtin(global_invocation_id) g: vec3<u32>) {
+ let w = pu(0u);
+ let sh = pu(1u);
+ let dh = pu(2u);
+ let nc = pu(3u);
+ let x = g.x;
+ let y = g.y;
+ if (x >= w || y >= dh) {
+ return;
+ }
+ let lo = table[3u * y];
+ let cnt = table[3u * y + 1u];
+ let off = table[3u * y + 2u];
+ for (var c = 0u; c < nc; c++) {
+ var acc = 0.0;
+ for (var k = 0u; k < cnt; k++) {
+ acc = acc + src[((lo + k) * w + x) * nc + c] * bitcast<f32>(table[off + k]);
+ }
+ dst[(y * w + x) * nc + c] = acc;
+ }
+}
diff --git a/crates/gpu/tests/equivalence.rs b/crates/gpu/tests/equivalence.rs
new file mode 100644
index 000000000..151574fec
--- /dev/null
+++ b/crates/gpu/tests/equivalence.rs
@@ -0,0 +1,293 @@
+//! CPU ↔ GPU equivalence: the same settings rendered by the CPU pipeline (the reference) and by
+//! `lightcraft_gpu::render`, compared in 8-bit sRGB.
+//!
+//! Bounds (documented in `docs/gpu-pipeline.md`): mean |Δ| < 0.5 LSB and max |Δ| ≤ 3 LSB per
+//! channel for every case. Skips (passes with a note) when no GPU adapter exists, e.g. on CI.
+
+use std::sync::Arc;
+
+use lightcraft_develop::{BrushStroke, DevelopSettings, Mask, MaskComponent, MaskOp, MaskShape, Spot, Treatment, VignetteStyle, WbMode, Wheel};
+use lightcraft_geom::{Orientation, Point, Rect};
+use lightcraft_pipeline::{Quality, RenderRequest, SourceInfo, StageCache, render};
+use lightcraft_raster::{Rgb32f, Rgba8};
+
+const MEAN_LSB: f64 = 0.5;
+const MAX_LSB: u8 = 3;
+
+fn gpu() -> bool {
+ let ok = lightcraft_gpu::available();
+ if !ok {
+ eprintln!("skipped: no GPU adapter");
+ }
+ ok
+}
+
+fn scene(i: usize, w: usize, h: usize) -> Arc<Rgb32f> {
+ Arc::new(lightcraft_scenes::demo_library()[i].render(w, h))
+}
+
+/// (mean |Δ|, max |Δ|, share of channels with |Δ| > 1).
+fn diff(a: &Rgba8, b: &Rgba8) -> (f64, u8, f64) {
+ assert_eq!((a.width, a.height), (b.width, b.height));
+ let (mut sum, mut max, mut over) = (0u64, 0u8, 0u64);
+ for (p, q) in a.data.iter().zip(&b.data) {
+ for c in 0..3 {
+ let d = p[c].abs_diff(q[c]);
+ sum += d as u64;
+ max = max.max(d);
+ over += (d > 1) as u64;
+ }
+ }
+ let n = (a.data.len() * 3) as f64;
+ (sum as f64 / n, max, over as f64 / n)
+}
+
+fn check(name: &str, src: &Arc<Rgb32f>, info: &SourceInfo, s: &DevelopSettings, req: &RenderRequest) -> (f64, u8) {
+ let cpu = render(src, info, s, req).image;
+ let gpu = lightcraft_gpu::render(src, info, s, req, None).expect("gpu render");
+ let (mean, max, over) = diff(&cpu, &gpu.image);
+ eprintln!("{name:<28} {}x{} mean {mean:.4} max {max} >1: {:.4}%", cpu.width, cpu.height, over * 100.0);
+ assert!(mean < MEAN_LSB && max <= MAX_LSB, "{name}: mean {mean:.4} LSB, max {max} LSB");
+ (mean, max)
+}
+
+type Edit = fn(&mut DevelopSettings);
+
+fn typical(s: &mut DevelopSettings) {
+ s.light.exposure = 0.3;
+ s.light.highlights = -40.0;
+ s.light.shadows = 30.0;
+ s.effects.clarity = 15.0;
+ s.effects.texture = 10.0;
+ s.effects.dehaze = 10.0;
+ s.detail.nr_luminance = 30.0;
+ s.detail.nr_color = 25.0;
+ s.detail.sharpen_amount = 40.0;
+}
+
+fn cases() -> Vec<(&'static str, Edit)> {
+ vec![
+ ("default", |_| {}),
+ ("typical", typical),
+ ("exposure/contrast/whites", |s| {
+ s.light.exposure = -0.7;
+ s.light.contrast = 45.0;
+ s.light.whites = 30.0;
+ s.light.blacks = -25.0;
+ }),
+ ("vibrance/saturation", |s| {
+ s.color.vibrance = 40.0;
+ s.color.saturation = -20.0;
+ }),
+ ("colour mixer", |s| {
+ s.mixer.blue.sat = -60.0;
+ s.mixer.orange.hue = 30.0;
+ s.mixer.green.lum = 40.0;
+ }),
+ ("b&w mix", |s| {
+ s.treatment = Treatment::Bw;
+ s.bw_mix.blue = 60.0;
+ s.bw_mix.red = -30.0;
+ }),
+ ("colour grading", |s| {
+ s.grading.shadows = Wheel { hue: 220.0, sat: 40.0, lum: -10.0 };
+ s.grading.highlights = Wheel { hue: 40.0, sat: 30.0, lum: 10.0 };
+ s.grading.global = Wheel { hue: 300.0, sat: 10.0, lum: 0.0 };
+ s.grading.blending = 70.0;
+ s.grading.balance = 20.0;
+ }),
+ ("tone curves", |s| {
+ s.curve.highlights = -30.0;
+ s.curve.shadows = 25.0;
+ s.curve.master = vec![Point::new(0.0, 0.05), Point::new(0.5, 0.55), Point::new(1.0, 0.95)];
+ s.curve.blue = vec![Point::new(0.0, 0.0), Point::new(0.5, 0.45), Point::new(1.0, 1.0)];
+ }),
+ ("vignette (highlight)", |s| {
+ s.vignette.amount = -60.0;
+ s.vignette.highlights = 50.0;
+ s.vignette.roundness = -40.0;
+ }),
+ ("vignette (paint, +)", |s| {
+ s.vignette.amount = 40.0;
+ s.vignette.style = VignetteStyle::PaintOverlay;
+ }),
+ ("vignette (paint, -)", |s| {
+ s.vignette.amount = -40.0;
+ s.vignette.style = VignetteStyle::PaintOverlay;
+ }),
+ ("grain", |s| {
+ s.grain.amount = 50.0;
+ s.grain.size = 40.0;
+ s.grain.roughness = 60.0;
+ }),
+ ("dehaze -", |s| s.effects.dehaze = -50.0),
+ ("dehaze +", |s| s.effects.dehaze = 60.0),
+ ("clarity/texture -", |s| {
+ s.effects.clarity = -60.0;
+ s.effects.texture = -40.0;
+ }),
+ ("sharpen masking", |s| {
+ s.detail.sharpen_amount = 90.0;
+ s.detail.sharpen_masking = 60.0;
+ }),
+ ("white balance", |s| {
+ s.wb.mode = WbMode::Custom;
+ s.wb.temp = 8200.0;
+ s.wb.tint = 15.0;
+ }),
+ ("noise reduction", |s| {
+ s.detail.nr_luminance = 70.0;
+ s.detail.nr_detail = 30.0;
+ s.detail.nr_color = 60.0;
+ s.detail.nr_color_smoothness = 50.0;
+ }),
+ ("crop + straighten + flip", |s| {
+ s.crop.geometry.rect = Rect::new(0.1, 0.05, 0.85, 0.9);
+ s.crop.geometry.angle = 7.5;
+ s.crop.flip_h = true;
+ }),
+ ("orientation", |s| s.orientation = Orientation::Rotate90),
+ ("lens + perspective", |s| {
+ s.optics.distortion = 30.0;
+ s.optics.vignetting = 40.0;
+ s.optics.ca_red = 50.0;
+ s.optics.ca_blue = -40.0;
+ s.geometry.vertical = 20.0;
+ }),
+ ("masks (gradients)", |s| {
+ s.masks = vec![
+ Mask {
+ components: vec![MaskComponent {
+ op: MaskOp::Add,
+ invert: false,
+ shape: MaskShape::Linear { start: Point::new(0.5, 0.0), end: Point::new(0.5, 0.6) },
+ }],
+ adjust: lightcraft_develop::LocalAdjustments { exposure: -0.8, temp: -30.0, saturation: 20.0, ..Default::default() },
+ ..Default::default()
+ },
+ Mask {
+ components: vec![
+ MaskComponent {
+ op: MaskOp::Add,
+ invert: false,
+ shape: MaskShape::Radial { center: Point::new(0.4, 0.6), rx: 0.25, ry: 0.15, angle: 20.0, feather: 60.0, invert: false },
+ },
+ MaskComponent {
+ op: MaskOp::Intersect,
+ invert: true,
+ shape: MaskShape::Linear { start: Point::new(0.0, 0.0), end: Point::new(1.0, 1.0) },
+ },
+ ],
+ adjust: lightcraft_develop::LocalAdjustments {
+ shadows: 40.0,
+ clarity: 30.0,
+ contrast: 20.0,
+ color_hue: 30.0,
+ color_sat: 50.0,
+ hue: 10.0,
+ ..Default::default()
+ },
+ ..Default::default()
+ },
+ ];
+ }),
+ ("masks (brush + ranges)", |s| {
+ let stroke = BrushStroke {
+ points: vec![Point::new(0.1, 0.3), Point::new(0.5, 0.4), Point::new(0.8, 0.35)],
+ size: 0.04,
+ flow: 60.0,
+ ..Default::default()
+ };
+ let erase = BrushStroke { points: vec![Point::new(0.5, 0.4)], size: 0.03, erase: true, ..Default::default() };
+ s.masks = vec![
+ Mask {
+ components: vec![MaskComponent { op: MaskOp::Add, invert: false, shape: MaskShape::Brush { strokes: vec![stroke, erase] } }],
+ adjust: lightcraft_develop::LocalAdjustments { exposure: 0.7, whites: 20.0, blacks: -20.0, dehaze: 30.0, ..Default::default() },
+ ..Default::default()
+ },
+ Mask {
+ components: vec![MaskComponent {
+ op: MaskOp::Add,
+ invert: false,
+ shape: MaskShape::LuminanceRange { lo: 0.5, hi: 0.8, lo_feather: 0.1, hi_feather: 0.1 },
+ }],
+ adjust: lightcraft_develop::LocalAdjustments { highlights: -50.0, texture: 30.0, sharpness: 40.0, ..Default::default() },
+ ..Default::default()
+ },
+ Mask {
+ components: vec![MaskComponent {
+ op: MaskOp::Add,
+ invert: false,
+ shape: MaskShape::ColorRange { samples: vec![[0.6, -0.05, -0.08]], refine: 50.0 },
+ }],
+ adjust: lightcraft_develop::LocalAdjustments { saturation: 40.0, tint: 20.0, ..Default::default() },
+ invert: true,
+ ..Default::default()
+ },
+ ];
+ }),
+ ("spots + defringe (cpu stage)", |s| {
+ s.spots = vec![Spot { points: vec![Point::new(0.3, 0.3)], size: 0.03, source_offset: Some(Point::new(0.1, 0.0)), ..Default::default() }];
+ s.optics.defringe_purple_amount = 5.0;
+ }),
+ ]
+}
+
+#[test]
+fn gpu_matches_cpu() {
+ if !gpu() {
+ return;
+ }
+ let src = scene(0, 960, 640);
+ let raw = SourceInfo { raw: true, ..Default::default() };
+ let req = RenderRequest::fit(720, 720);
+ let mut worst = (0.0f64, 0u8);
+ for (name, edit) in cases() {
+ let mut s = DevelopSettings::default();
+ edit(&mut s);
+ let (m, x) = check(name, &src, &raw, &s, &req);
+ worst = (worst.0.max(m), worst.1.max(x));
+ }
+ eprintln!("worst: mean {:.4} LSB, max {} LSB", worst.0, worst.1);
+}
+
+#[test]
+fn rendered_sources_and_other_scenes() {
+ if !gpu() {
+ return;
+ }
+ // A display-referred source (JPEG-like: display tone map) and other scenes / sizes / draft.
+ let jpeg = SourceInfo::default();
+ for (i, (w, h)) in [(3usize, (800usize, 533usize)), (5, (640, 960)), (7, (1200, 800))] {
+ let src = scene(i, w, h);
+ let mut s = DevelopSettings::default();
+ typical(&mut s);
+ s.color.vibrance = 25.0;
+ check(&format!("scene {i} display-referred"), &src, &jpeg, &s, &RenderRequest::fit(700, 700));
+ let draft = RenderRequest { quality: Quality::Draft, ..RenderRequest::fit(500, 500) };
+ check(&format!("scene {i} draft"), &src, &SourceInfo { raw: true, ..Default::default() }, &s, &draft);
+ check(&format!("scene {i} full size"), &src, &SourceInfo { raw: true, ..Default::default() }, &s, &RenderRequest::fit(w, h));
+ }
+}
+
+#[test]
+fn cached_renders_match_uncached() {
+ if !gpu() {
+ return;
+ }
+ // Slider drags reuse device-resident stages: the result must equal a fresh render.
+ let src = scene(1, 900, 600);
+ let info = SourceInfo { raw: true, ..Default::default() };
+ let cache = StageCache::default();
+ let req = RenderRequest::fit(640, 640);
+ let mut s = DevelopSettings::default();
+ typical(&mut s);
+ for k in 0..4 {
+ s.light.exposure = 0.1 * k as f64;
+ s.effects.clarity = 10.0 + 5.0 * (k / 2) as f64;
+ s.detail.nr_luminance = 20.0 + 10.0 * (k % 2) as f64;
+ let warm = lightcraft_gpu::render(&src, &info, &s, &req, Some(&cache)).expect("gpu");
+ let fresh = lightcraft_gpu::render(&src, &info, &s, &req, None).expect("gpu");
+ assert_eq!(warm.image, fresh.image, "step {k}");
+ }
+}
diff --git a/crates/pipeline/src/colorops.rs b/crates/pipeline/src/colorops.rs
index b271e5609..5d378d19a 100644
--- a/crates/pipeline/src/colorops.rs
+++ b/crates/pipeline/src/colorops.rs
@@ -16,7 +16,8 @@ pub fn oklch_hue_of_srgb_hue(deg: f64) -> f32 {
lab_to_lch(oklab_from_2020(m))[2]
}
-fn band_hues() -> &'static [f32; 8] {
+/// OkLCh hue (radians) of each colour-mixer band centre.
+pub fn band_hues() -> &'static [f32; 8] {
static H: OnceLock<[f32; 8]> = OnceLock::new();
H.get_or_init(|| MIXER_HUES.map(oklch_hue_of_srgb_hue))
}
@@ -47,23 +48,28 @@ pub fn band_weights(h: f32) -> [f32; 8] {
w
}
-#[derive(Clone, Copy)]
-struct WheelK {
- a: f32,
- b: f32,
- lum: f32,
+/// A colour-grading wheel as an OkLab offset (a, b) and a lightness shift.
+#[derive(Clone, Copy, Debug)]
+pub struct WheelK {
+ pub a: f32,
+ pub b: f32,
+ pub lum: f32,
}
+/// The colour tools' parameters, resolved once per render (fields are read by the GPU kernel).
+#[derive(Clone, Debug)]
pub struct ColorOps {
- vibrance: f32,
- saturation: f32,
- hue: [f32; 8],
- sat: [f32; 8],
- lum: [f32; 8],
- mixer: bool,
- bw: Option<[f32; 8]>,
- grading: Option<([WheelK; 4], f32, f32)>,
- skin: f32,
+ pub vibrance: f32,
+ pub saturation: f32,
+ pub hue: [f32; 8],
+ pub sat: [f32; 8],
+ pub lum: [f32; 8],
+ pub mixer: bool,
+ pub bw: Option<[f32; 8]>,
+ /// Wheels (shadows, midtones, highlights, global), blending, balance.
+ pub grading: Option<([WheelK; 4], f32, f32)>,
+ /// OkLCh hue of skin tones (protected by vibrance).
+ pub skin: f32,
}
fn wheel(w: &lightcraft_develop::Wheel) -> WheelK {
diff --git a/crates/pipeline/src/finish.rs b/crates/pipeline/src/finish.rs
index 196a75b2c..5a79a2ded 100644
--- a/crates/pipeline/src/finish.rs
+++ b/crates/pipeline/src/finish.rs
@@ -3,7 +3,7 @@
use lightcraft_color::spline::{Lut1, MonotoneCurve};
use lightcraft_color::transfer::linear_to_srgb;
use lightcraft_color::{REC2020, SRGB, luminance_2020};
-use lightcraft_develop::{DevelopSettings, ToneCurve, VignetteStyle};
+use lightcraft_develop::{DevelopSettings, LocalAdjustments, ToneCurve, VignetteStyle};
use lightcraft_geom::Point;
use lightcraft_raster::Rgba8;
@@ -55,14 +55,16 @@ fn curve_luts(c: &ToneCurve) -> Option<[Lut1; 3]> {
Some(std::array::from_fn(|i| if chans[i] { MonotoneCurve::new(&to_pts(per[i])).to_lut(N).compose(&base) } else { base.clone() }))
}
-struct Vig {
- amount: f32,
- start: f32,
- width: f32,
- aspect_mix: f32,
- power: f32,
- highlights: f32,
- style: VignetteStyle,
+/// Vignette (post-crop) parameters.
+#[derive(Clone, Copy, Debug)]
+pub struct Vig {
+ pub amount: f32,
+ pub start: f32,
+ pub width: f32,
+ pub aspect_mix: f32,
+ pub power: f32,
+ pub highlights: f32,
+ pub style: VignetteStyle,
}
fn vignette(s: &DevelopSettings) -> Option<Vig> {
@@ -81,14 +83,17 @@ fn vignette(s: &DevelopSettings) -> Option<Vig> {
})
}
+/// Hash constants of [`grain_noise`] (shared with the GPU kernel).
+pub const GRAIN_HASH: [u32; 4] = [0x8da6_b343, 0xd816_3841, 0xcb1a_b31f, 0x5bd1_e995];
+
#[inline]
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(0x8da6_b343) ^ (j as u32).wrapping_mul(0xd816_3841) ^ seed.wrapping_mul(0xcb1a_b31f);
+ 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]);
v ^= v >> 13;
- v = v.wrapping_mul(0x5bd1_e995);
+ v = v.wrapping_mul(GRAIN_HASH[3]);
v ^= v >> 15;
(v & 0xffff) as f32 / 32768.0 - 1.0
};
@@ -99,33 +104,130 @@ fn grain_noise(x: f32, y: f32, seed: u32) -> f32 {
a + (b - a) * v
}
-pub fn finish(p: &Prepared, s: &DevelopSettings, frame: &Frame, info: &SourceInfo) -> Rgba8 {
- let (w, h) = (p.img.width, p.img.height);
- let tone = if info.raw {
- ToneMap::new(s.light.contrast, s.light.whites, s.light.blacks)
- } else {
- ToneMap::display(s.light.contrast, s.light.whites, s.light.blacks)
- };
- let ops = ColorOps::new(s);
- let curves = curve_luts(&s.curve);
- let vig = if s.section_enabled("effects") { vignette(s) } else { None };
- let to_srgb: [[f32; 3]; 3] = REC2020.to_space(&SRGB).to_f32();
- let hl = (s.light.highlights / 100.0) as f32;
- let sh = (s.light.shadows / 100.0) as f32;
- let (clar, tex, dehaze) = if s.section_enabled("effects") {
- ((s.effects.clarity / 100.0) as f32, (s.effects.texture / 100.0) as f32, (s.effects.dehaze / 100.0) as f32)
+/// Number of per-mask terms in [`mask_terms`].
+pub const MASK_TERMS: usize = 18;
+
+/// A mask's local adjustments as the per-pixel stage uses them (alpha-weighted sums), in order:
+/// exposure, temp, tint, contrast, highlights, shadows, whites, blacks, texture, clarity, dehaze,
+/// saturation, hue, sharpness, then the colour overlay: on (0/1), cos and sin of its OkLCh hue, and
+/// its strength.
+pub fn mask_terms(j: &LocalAdjustments) -> [f32; MASK_TERMS] {
+ let (on, cos, sin, amt) = if j.color_sat > 0.0 {
+ let hue = crate::colorops::oklch_hue_of_srgb_hue(j.color_hue);
+ (1.0, hue.cos(), hue.sin(), (j.color_sat / 100.0) as f32)
} else {
- (0.0, 0.0, 0.0)
+ (0.0, 0.0, 0.0, 0.0)
};
- let sharpen = (s.detail.sharpen_amount / 150.0) as f32;
- let sharpen_mask = (s.detail.sharpen_masking / 100.0) as f32;
- // Planes are pre-exposure: scale the airlight, shift log luminance (see `Prepared`).
- let (air, air_pre, gain, ev) = (p.air * p.gain, p.air, p.gain, p.ev);
- let grain = (s.grain.amount > 0.0 && s.section_enabled("effects")).then(|| {
- let cell = (0.0006 + (s.grain.size / 100.0) as f32 * 0.0024) * p.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 out_to_norm = frame.out_to_norm(w, h);
+ [
+ j.exposure as f32,
+ (j.temp / 100.0) as f32,
+ (j.tint / 100.0) as f32,
+ (j.contrast / 100.0) as f32,
+ (j.highlights / 100.0) as f32,
+ (j.shadows / 100.0) as f32,
+ (j.whites / 100.0) as f32,
+ (j.blacks / 100.0) as f32,
+ (j.texture / 100.0) as f32,
+ (j.clarity / 100.0) as f32,
+ (j.dehaze / 100.0) as f32,
+ (j.saturation / 100.0) as f32,
+ (j.hue / 100.0) as f32 * 0.6,
+ (j.sharpness / 100.0) as f32,
+ on,
+ cos,
+ sin,
+ amt,
+ ]
+}
+
+/// Everything the per-pixel stage computes once per render: the CPU loop below and the GPU kernel
+/// (`lightcraft-gpu`) both read their parameters from here, so the two cannot drift apart.
+pub struct FinishParams {
+ pub tone: ToneMap,
+ pub ops: ColorOps,
+ /// Tone curves (parametric ∘ point, per channel) on encoded values, 1024 entries each.
+ pub curves: Option<[Lut1; 3]>,
+ pub vig: Option<Vig>,
+ pub to_srgb: [[f32; 3]; 3],
+ pub hl: f32,
+ pub sh: f32,
+ pub clar: f32,
+ pub tex: f32,
+ pub dehaze: f32,
+ pub sharpen: f32,
+ pub sharpen_mask: f32,
+ /// Airlight after and before exposure, exposure gain and EV (see [`crate::Prepared`]).
+ pub air: f32,
+ pub air_pre: f32,
+ pub gain: f32,
+ pub ev: f32,
+ /// Grain: amount, cell size (px), roughness, seed.
+ pub grain: Option<(f32, f32, f32, u32)>,
+ /// Output px → normalized oriented coordinates.
+ pub out_to_norm: lightcraft_geom::Affine,
+ pub ow: f64,
+ pub oh: f64,
+ pub w: usize,
+ pub h: usize,
+ pub px_per_long: f64,
+}
+
+impl FinishParams {
+ /// Parameters for a `w × h` render; `ev`/`air_pre` as in [`crate::Prepared`].
+ pub fn new(s: &DevelopSettings, frame: &Frame, info: &SourceInfo, w: usize, h: usize, px_per_long: f64, air_pre: f32) -> FinishParams {
+ let effects = s.section_enabled("effects");
+ let (clar, tex, dehaze) = if effects {
+ ((s.effects.clarity / 100.0) as f32, (s.effects.texture / 100.0) as f32, (s.effects.dehaze / 100.0) as f32)
+ } else {
+ (0.0, 0.0, 0.0)
+ };
+ let ev = s.light.exposure as f32;
+ let gain = 2f32.powf(ev);
+ let grain = (s.grain.amount > 0.0 && effects).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)
+ });
+ FinishParams {
+ tone: if info.raw {
+ ToneMap::new(s.light.contrast, s.light.whites, s.light.blacks)
+ } else {
+ ToneMap::display(s.light.contrast, s.light.whites, s.light.blacks)
+ },
+ ops: ColorOps::new(s),
+ curves: curve_luts(&s.curve),
+ vig: if effects { vignette(s) } else { None },
+ to_srgb: REC2020.to_space(&SRGB).to_f32(),
+ hl: (s.light.highlights / 100.0) as f32,
+ sh: (s.light.shadows / 100.0) as f32,
+ clar,
+ tex,
+ dehaze,
+ sharpen: (s.detail.sharpen_amount / 150.0) as f32,
+ sharpen_mask: (s.detail.sharpen_masking / 100.0) as f32,
+ air: air_pre * gain,
+ air_pre,
+ gain,
+ ev,
+ grain,
+ out_to_norm: frame.out_to_norm(w, h),
+ ow: frame.ow,
+ oh: frame.oh,
+ w,
+ h,
+ px_per_long,
+ }
+ }
+}
+
+pub(crate) fn finish(p: &Prepared, s: &DevelopSettings, frame: &Frame, info: &SourceInfo) -> Rgba8 {
+ let (w, h) = (p.img.width, p.img.height);
+ let fp = FinishParams::new(s, frame, info, w, h, p.px_per_long, p.air);
+ let FinishParams { tone, ops, curves, vig, to_srgb, hl, sh, clar, tex, dehaze, sharpen, sharpen_mask, air, air_pre, gain, ev, grain, .. } = &fp;
+ let (hl, sh, clar, tex, dehaze, sharpen, sharpen_mask, air, air_pre, gain, ev) =
+ (*hl, *sh, *clar, *tex, *dehaze, *sharpen, *sharpen_mask, *air, *air_pre, *gain, *ev);
+ let terms: Vec<[f32; MASK_TERMS]> = p.masks.iter().map(|m| mask_terms(&m.adjust)).collect();
+ let out_to_norm = fp.out_to_norm;
+ let long = fp.ow.max(fp.oh);
let aspect = w as f32 / h as f32;
let srgb = srgb_lut();
@@ -138,35 +240,22 @@ pub fn finish(p: &Prepared, s: &DevelopSettings, frame: &Frame, info: &SourceInf
let l_pre = p.log_l.data[i];
let l0 = l_pre + ev;
- // --- local (mask) contributions
- let (mut l_exp, mut l_temp, mut l_tint, mut l_con, mut l_hl, mut l_sh, mut l_wh, mut l_bl) = (0.0f32, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
- let (mut l_tex, mut l_clar, mut l_dehaze, mut l_sat, mut l_hue, mut l_sharp) = (0.0f32, 0.0, 0.0, 0.0, 0.0, 0.0);
+ // --- local (mask) contributions: alpha-weighted sums of the masks' terms
+ let mut l = [0.0f32; 14];
let mut tint_col: Option<([f32; 3], f32)> = None;
- for m in &p.masks {
+ for (m, t) in p.masks.iter().zip(&terms) {
let a = m.alpha.data[i];
if a <= 0.0 {
continue;
}
- let j = &m.adjust;
- l_exp += a * j.exposure as f32;
- l_temp += a * (j.temp / 100.0) as f32;
- l_tint += a * (j.tint / 100.0) as f32;
- l_con += a * (j.contrast / 100.0) as f32;
- l_hl += a * (j.highlights / 100.0) as f32;
- l_sh += a * (j.shadows / 100.0) as f32;
- l_wh += a * (j.whites / 100.0) as f32;
- l_bl += a * (j.blacks / 100.0) as f32;
- l_tex += a * (j.texture / 100.0) as f32;
- l_clar += a * (j.clarity / 100.0) as f32;
- l_dehaze += a * (j.dehaze / 100.0) as f32;
- l_sat += a * (j.saturation / 100.0) as f32;
- l_hue += a * (j.hue / 100.0) as f32 * 0.6;
- l_sharp += a * (j.sharpness / 100.0) as f32;
- if j.color_sat > 0.0 {
- let hue = crate::colorops::oklch_hue_of_srgb_hue(j.color_hue);
- tint_col = Some(([hue.cos(), hue.sin(), 0.0], a * (j.color_sat / 100.0) as f32));
+ for k in 0..14 {
+ l[k] += a * t[k];
+ }
+ if t[14] > 0.0 {
+ tint_col = Some(([t[15], t[16], 0.0], a * t[17]));
}
}
+ let [l_exp, l_temp, l_tint, l_con, l_hl, l_sh, l_wh, l_bl, l_tex, l_clar, l_dehaze, l_sat, l_hue, l_sharp] = l;
// --- dehaze (scene linear)
let dz = dehaze + l_dehaze;
@@ -259,7 +348,7 @@ pub fn finish(p: &Prepared, s: &DevelopSettings, frame: &Frame, info: &SourceInf
}
// --- vignette (display linear, post-crop)
- if let Some(v) = &vig {
+ if let Some(v) = vig {
let u = (x as f32 + 0.5) / w as f32 * 2.0 - 1.0;
let vv = (y as f32 + 0.5) / h as f32 * 2.0 - 1.0;
let sx = 1.0 + (aspect - 1.0) * v.aspect_mix;
@@ -286,7 +375,7 @@ pub fn finish(p: &Prepared, s: &DevelopSettings, frame: &Frame, info: &SourceInf
}
// --- gamut map to sRGB (desaturate towards luminance until in range)
- let m = &to_srgb;
+ let m = to_srgb;
let mut r = [
m[0][0] * d[0] + m[0][1] * d[1] + m[0][2] * d[2],
m[1][0] * d[0] + m[1][1] * d[1] + m[1][2] * d[2],
@@ -307,13 +396,13 @@ pub fn finish(p: &Prepared, s: &DevelopSettings, frame: &Frame, info: &SourceInf
// --- encode, curves, grain
let mut e = r.map(|v| encode_srgb(srgb, v));
- if let Some(l) = &curves {
+ if let Some(l) = curves {
e = [l[0].eval(e[0]), l[1].eval(e[1]), l[2].eval(e[2])];
}
- if let Some((amt, cell, rough, seed)) = grain {
+ if let Some((amt, cell, rough, seed)) = *grain {
let n = out_to_norm.apply(Point::new(x as f64 + 0.5, y as f64 + 0.5));
- let (gx, gy) = ((n.x * frame.ow) as f32 / frame.ow.max(frame.oh) as f32, (n.y * frame.oh) as f32 / frame.ow.max(frame.oh) as f32);
- let sc = p.px_per_long as f32 / cell;
+ 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 lum = 0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2];
@@ -326,9 +415,10 @@ pub fn finish(p: &Prepared, s: &DevelopSettings, frame: &Frame, info: &SourceInf
out
}
-const SRGB_LUT_N: usize = 4096;
+pub const SRGB_LUT_N: usize = 4096;
-fn srgb_lut() -> &'static [f32; SRGB_LUT_N + 1] {
+/// Linear → sRGB-encoded table (`SRGB_LUT_N + 1` entries over 0..1), interpolated linearly.
+pub fn srgb_lut() -> &'static [f32; SRGB_LUT_N + 1] {
static LUT: std::sync::OnceLock<Box<[f32; SRGB_LUT_N + 1]>> = std::sync::OnceLock::new();
LUT.get_or_init(|| {
let mut t = Box::new([0.0f32; SRGB_LUT_N + 1]);
diff --git a/crates/pipeline/src/lib.rs b/crates/pipeline/src/lib.rs
index ac62a327a..3ccee51ba 100644
--- a/crates/pipeline/src/lib.rs
+++ b/crates/pipeline/src/lib.rs
@@ -23,19 +23,21 @@
#![forbid(unsafe_code)]
pub mod auto;
-mod colorops;
-mod finish;
+pub mod colorops;
+pub mod finish;
pub mod geometry;
-mod local;
+pub mod local;
pub mod masks;
pub mod optics;
pub mod profiles;
pub mod spots;
-mod tone;
+pub mod tone;
pub mod transform;
pub mod upright;
use lightcraft_develop::{DevelopSettings, Treatment};
+use std::any::Any;
+use std::borrow::Cow;
use std::sync::{Arc, Mutex};
use lightcraft_raster::{Histogram, Plane, Rgb32f, Rgba8, par_rows};
@@ -105,9 +107,6 @@ pub(crate) struct Prepared {
/// Airlight of `dark` (before exposure).
pub air: f32,
pub masks: Vec<masks::Evaluated>,
- /// Exposure in EV and as a linear gain.
- pub ev: f32,
- pub gain: f32,
/// Output pixels per unit of the source long edge.
pub px_per_long: f64,
}
@@ -137,11 +136,13 @@ pub fn frame_for(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings, apply_cro
pub struct StageCache {
entries: Mutex<Vec<CacheEntry>>,
capacity: usize,
+ /// Another renderer's per-view state (the GPU renderer keeps its device-resident stages here).
+ ext: Mutex<Option<Arc<dyn Any + Send + Sync>>>,
}
impl Default for StageCache {
fn default() -> Self {
- StageCache { entries: Mutex::new(Vec::new()), capacity: 2 }
+ StageCache { entries: Mutex::new(Vec::new()), capacity: 2, ext: Mutex::new(None) }
}
}
@@ -149,6 +150,21 @@ impl StageCache {
/// Drop everything (e.g. when memory is needed).
pub fn clear(&self) {
self.lock().clear();
+ *self.ext.lock().unwrap_or_else(|e| e.into_inner()) = None;
+ }
+
+ /// Per-view state of type `T` kept alongside this cache (created on first use). Lets another
+ /// renderer of the same view (e.g. `lightcraft-gpu`) keep its own stage cache with this one.
+ pub fn extension<T: Any + Send + Sync + Default>(&self) -> Arc<T> {
+ let mut g = self.ext.lock().unwrap_or_else(|e| e.into_inner());
+ if let Some(e) = g.as_ref()
+ && let Ok(t) = e.clone().downcast::<T>()
+ {
+ return t;
+ }
+ let t = Arc::new(T::default());
+ *g = Some(t.clone());
+ t
}
/// Number of cached output sizes.
@@ -192,6 +208,66 @@ fn hash_of(parts: impl std::hash::Hash) -> u64 {
BuildHasherDefault::<DefaultHasher>::default().hash_one(parts)
}
+/// What a render resolves to before any pixel work: the effective settings (profile and Upright
+/// applied), the geometric frame, the output size and the stage-cache keys. Shared by the CPU
+/// renderer and the GPU renderer (`lightcraft-gpu`), so both key their caches identically.
+pub struct Plan<'a> {
+ pub settings: Cow<'a, DevelopSettings>,
+ pub frame: geometry::Frame,
+ pub w: usize,
+ pub h: usize,
+ /// Output pixels per unit of the oriented source's long edge.
+ pub px_per_long: f64,
+ /// Long edge of the source buffer (px).
+ pub src_long: usize,
+ /// Key of the resampled source (together with the source buffer's identity).
+ pub geo: u64,
+ /// Key of the white-balanced, retouched, denoised image (and of the planes computed from it).
+ pub lin_key: u64,
+}
+
+/// Resolve `s` against `src` for `req` (see [`Plan`]).
+pub fn plan<'a>(src: &Rgb32f, info: &SourceInfo, s: &'a DevelopSettings, req: &RenderRequest) -> Plan<'a> {
+ let settings: Cow<'a, DevelopSettings> = match profiles::effective(s) {
+ Cow::Borrowed(b) => upright::resolve(src, info, b),
+ Cow::Owned(o) => Cow::Owned(upright::resolve(src, info, &o).into_owned()),
+ };
+ let s = &*settings;
+ let frame = frame_for(src, info, s, req.apply_crop);
+ let (w, h) = frame.fit(req.max_w, req.max_h);
+ let px_per_long = frame.px_per_long(w);
+ let src_long = src.width.max(src.height);
+ let geo = hash_of((format!("{frame:?}"), w, h));
+ let (wb_t, wb_tint) = local::effective_wb(info, s);
+ let d = &s.detail;
+ let lin_key = hash_of((
+ geo,
+ [wb_t, wb_tint, info.as_shot_temp, info.as_shot_tint].map(f64::to_bits),
+ format!("{:?}", s.spots),
+ // defringe runs in this stage
+ format!("{:?}", s.optics),
+ [d.nr_luminance, d.nr_detail, d.nr_color, d.nr_color_detail, d.nr_color_smoothness].map(f64::to_bits),
+ src_long,
+ ));
+ Plan { settings, frame, w, h, px_per_long, src_long, geo, lin_key }
+}
+
+/// Whether the scene-linear stage needs work only the CPU does (defringe, spot removal).
+pub fn lin_needs_cpu(s: &DevelopSettings) -> bool {
+ let o = &s.optics;
+ let defringe = s.section_enabled("optics") && (o.defringe_purple_amount > 0.0 || o.defringe_green_amount > 0.0);
+ defringe || !s.spots.is_empty()
+}
+
+/// The white-balanced, defringed, retouched image (before noise reduction): the CPU part of the
+/// scene-linear stage, in place.
+pub fn lin_cpu(img: &mut Rgb32f, info: &SourceInfo, p: &Plan<'_>) {
+ let s = &*p.settings;
+ local::white_balance(img, info, s);
+ optics::defringe(img, s, p.px_per_long / optics::DEFRINGE_REF_LONG);
+ spots::apply(img, &s.spots, &p.frame, p.px_per_long);
+}
+
/// Render `src` with settings `s`.
pub fn render(src: &Rgb32f, info: &SourceInfo, s: &DevelopSettings, req: &RenderRequest) -> Rendered {
render_impl(Src::Borrowed(src), info, s, req, None)
@@ -217,22 +293,18 @@ fn render_impl(src: Src<'_>, info: &SourceInfo, s: &DevelopSettings, req: &Rende
}
};
let mut t = profiling().then(std::time::Instant::now);
- let s = &*profiles::effective(s);
let src_img: &Rgb32f = match &src {
Src::Borrowed(r) => r,
Src::Shared(a) => a,
};
- let s = &*upright::resolve(src_img, info, s);
- let frame = frame_for(src_img, info, s, req.apply_crop);
- let (w, h) = frame.fit(req.max_w, req.max_h);
- let px_per_long = frame.px_per_long(w);
- let src_long = src_img.width.max(src_img.height);
+ let plan = plan(src_img, info, s, req);
+ let Plan { ref frame, w, h, px_per_long, src_long, geo, lin_key, .. } = plan;
+ let s = &*plan.settings;
let shared = match (&src, cache) {
(Src::Shared(a), Some(c)) => Some((*a, c)),
_ => None,
};
- let geo = hash_of((format!("{frame:?}"), w, h));
let cached = shared.and_then(|(a, c)| c.get(a, geo));
let sampled = match &cached {
Some(e) => e.sampled.clone(),
@@ -240,25 +312,12 @@ fn render_impl(src: Src<'_>, info: &SourceInfo, s: &DevelopSettings, req: &Rende
};
lap("sample", &mut t);
- let (wb_t, wb_tint) = local::effective_wb(info, s);
- let d = &s.detail;
- let lin_key = hash_of((
- geo,
- [wb_t, wb_tint, info.as_shot_temp, info.as_shot_tint].map(f64::to_bits),
- format!("{:?}", s.spots),
- // defringe runs in this stage
- format!("{:?}", s.optics),
- [d.nr_luminance, d.nr_detail, d.nr_color, d.nr_color_detail, d.nr_color_smoothness].map(f64::to_bits),
- src_long,
- ));
let lin = match cached.as_ref().and_then(|e| e.lin.clone()).filter(|(k, _)| *k == lin_key) {
Some((_, img)) => img,
None => {
// Without a cache the resampled buffer is ours: work on it in place.
let mut img = if shared.is_some() { (*sampled).clone() } else { Arc::unwrap_or_clone(sampled.clone()) };
- local::white_balance(&mut img, info, s);
- optics::defringe(&mut img, s, px_per_long / optics::DEFRINGE_REF_LONG);
- spots::apply(&mut img, &s.spots, &frame, px_per_long);
+ lin_cpu(&mut img, info, &plan);
local::denoise(&mut img, s, src_long, w.max(h));
Arc::new(img)
}
@@ -268,12 +327,12 @@ fn render_impl(src: Src<'_>, info: &SourceInfo, s: &DevelopSettings, req: &Rende
Some(p) if p.key == lin_key => p,
_ => local::Planes { key: lin_key, ..Default::default() },
};
- let prep = local::prepare(lin.clone(), s, &frame, px_per_long, req.quality, &mut planes);
+ let prep = local::prepare(lin.clone(), s, frame, px_per_long, req.quality, &mut planes);
lap("prepare", &mut t);
if let Some((a, c)) = shared {
c.put(CacheEntry { src: a.clone(), geo, sampled, lin: Some((lin_key, lin)), planes });
}
- let image = finish::finish(&prep, s, &frame, info);
+ let image = finish::finish(&prep, s, frame, info);
lap("finish", &mut t);
let histogram = Histogram::of_srgb8(&image);
lap("histogram", &mut t);
diff --git a/crates/pipeline/src/local.rs b/crates/pipeline/src/local.rs
index 27bb1d0df..590ea5ff4 100644
--- a/crates/pipeline/src/local.rs
+++ b/crates/pipeline/src/local.rs
@@ -22,19 +22,24 @@ pub fn white_balance(img: &mut Rgb32f, info: &SourceInfo, s: &DevelopSettings) {
wb_gain(img, info, s, 1.0);
}
-fn wb_gain(img: &mut Rgb32f, info: &SourceInfo, s: &DevelopSettings, gain: f32) {
+/// The white-balance matrix (linear Rec.2020, luminance-preserving) for the settings, or `None`
+/// when the as-shot white is kept.
+pub fn wb_matrix_for(info: &SourceInfo, s: &DevelopSettings) -> Option<[[f32; 3]; 3]> {
let (t, tint) = effective_wb(info, s);
- let m = if (t - info.as_shot_temp).abs() < 1e-6 && (tint - info.as_shot_tint).abs() < 1e-6 {
- None
- } else {
- let set = wb_matrix(&REC2020, temp_tint_to_xy(t, tint));
- let shot = wb_matrix(&REC2020, temp_tint_to_xy(info.as_shot_temp, info.as_shot_tint));
- let m = set.mul(&shot.inverse().unwrap_or(lightcraft_color::Mat3::IDENTITY));
- // Normalize so neutral luminance is preserved (WB shouldn't change exposure).
- let g = m.apply([1.0, 1.0, 1.0]);
- let y = g[0] * 0.2627 + g[1] * 0.6780 + g[2] * 0.0593;
- Some(m.mul(&lightcraft_color::Mat3::diag(1.0 / y, 1.0 / y, 1.0 / y)).to_f32())
- };
+ if (t - info.as_shot_temp).abs() < 1e-6 && (tint - info.as_shot_tint).abs() < 1e-6 {
+ return None;
+ }
+ let set = wb_matrix(&REC2020, temp_tint_to_xy(t, tint));
+ let shot = wb_matrix(&REC2020, temp_tint_to_xy(info.as_shot_temp, info.as_shot_tint));
+ let m = set.mul(&shot.inverse().unwrap_or(lightcraft_color::Mat3::IDENTITY));
+ // Normalize so neutral luminance is preserved (WB shouldn't change exposure).
+ let g = m.apply([1.0, 1.0, 1.0]);
+ let y = g[0] * 0.2627 + g[1] * 0.6780 + g[2] * 0.0593;
+ Some(m.mul(&lightcraft_color::Mat3::diag(1.0 / y, 1.0 / y, 1.0 / y)).to_f32())
+}
+
+fn wb_gain(img: &mut Rgb32f, info: &SourceInfo, s: &DevelopSettings, gain: f32) {
+ let m = wb_matrix_for(info, s);
let w = img.width;
for_rows(&mut img.data, w, |_, row| {
for p in row.iter_mut() {
@@ -96,7 +101,7 @@ fn guided_apply(p: &Plane, a: &Plane, b: &Plane) -> Plane {
/// large windows at a fraction of the cost.
pub fn guided_fast(p: &Plane, sigma: f32, eps: f32) -> Plane {
use lightcraft_raster::resample::{Filter, resize};
- let s = (sigma / 3.0).floor().clamp(1.0, 16.0) as usize;
+ let s = guided_fast_step(sigma);
if s <= 1 {
return guided(p, sigma, eps);
}
@@ -107,28 +112,57 @@ pub fn guided_fast(p: &Plane, sigma: f32, eps: f32) -> Plane {
guided_apply(p, &up(&ma), &up(&mb))
}
+/// Subsampling step of [`guided_fast`] for `sigma` (1 = no subsampling: the plain guided filter).
+pub fn guided_fast_step(sigma: f32) -> usize {
+ (sigma / 3.0).floor().clamp(1.0, 16.0) as usize
+}
+
+/// Luminance noise reduction: guided filter of log luminance (`sigma` px, `eps`), blended by `k`.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct NrLum {
+ pub sigma: f32,
+ pub eps: f32,
+ pub k: f32,
+}
+
+/// Colour noise reduction: chromaticity blurred by `sigma` px, mixed in by `t`.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct NrColor {
+ pub sigma: f32,
+ pub t: f32,
+}
+
+/// Noise-reduction parameters at an output long edge of `out_long` px (see [`denoise`]).
+pub fn nr_params(s: &DevelopSettings, src_long: usize, out_long: usize) -> (Option<NrLum>, Option<NrColor>) {
+ let lum = (s.detail.nr_luminance / 100.0) as f32;
+ let col = (s.detail.nr_color / 100.0) as f32;
+ let scale = (out_long as f32 / src_long.max(1) as f32).clamp(0.05, 1.0);
+ let l = (lum > 0.0).then(|| {
+ let detail = (s.detail.nr_detail / 100.0) as f32;
+ NrLum { sigma: (1.0 + 2.5 * lum) * scale.max(0.4), eps: 0.002 + lum * lum * 0.25 * (1.0 - 0.7 * detail), k: lum.sqrt() }
+ });
+ let c = (col > 0.0).then(|| {
+ let sigma = (1.5 + 6.0 * col) * scale.max(0.35) * (1.0 + (s.detail.nr_color_smoothness / 100.0) as f32);
+ let keep = (s.detail.nr_color_detail / 100.0) as f32 * 0.5;
+ NrColor { sigma, t: col * (1.0 - keep) }
+ });
+ (l, c)
+}
+
/// Noise reduction at output resolution: luminance via an edge-aware self-guided filter on
/// log-luminance, colour by blurring chromaticity (rgb / Y) and re-applying the original luminance.
/// Radii scale with how much the source was downsampled (preview noise is already averaged out).
pub fn denoise(img: &mut Rgb32f, s: &DevelopSettings, src_long: usize, out_long: usize) {
- let lum = (s.detail.nr_luminance / 100.0) as f32;
- let col = (s.detail.nr_color / 100.0) as f32;
- if lum <= 0.0 && col <= 0.0 {
- return;
- }
- let scale = (out_long as f32 / src_long.max(1) as f32).clamp(0.05, 1.0);
+ let (lum, col) = nr_params(s, src_long, out_long);
let w = img.width;
- if lum > 0.0 {
+ if let Some(nr) = lum {
let _t = crate::profiling().then(std::time::Instant::now);
let l = img.map(log_lum);
- let detail = (s.detail.nr_detail / 100.0) as f32;
- let eps = 0.002 + lum * lum * 0.25 * (1.0 - 0.7 * detail);
- let f = guided(&l, (1.0 + 2.5 * lum) * scale.max(0.4), eps);
- let k = lum.sqrt();
+ let f = guided(&l, nr.sigma, nr.eps);
for_rows(&mut img.data, w, |y, row| {
for (x, p) in row.iter_mut().enumerate() {
let i = y * w + x;
- let d = (f.data[i] - l.data[i]) * k;
+ let d = (f.data[i] - l.data[i]) * nr.k;
let g = d.exp2();
*p = p.map(|v| v * g);
}
@@ -137,23 +171,20 @@ pub fn denoise(img: &mut Rgb32f, s: &DevelopSettings, src_long: usize, out_long:
eprintln!(" nr luminance: {:.1} ms", t.elapsed().as_secs_f64() * 1e3);
}
}
- if col > 0.0 {
+ if let Some(nr) = col {
let _t = crate::profiling().then(std::time::Instant::now);
let chroma = img.map(|c| {
let y = luminance_2020(c).max(1e-6);
[c[0] / y, c[1] / y, c[2] / y]
});
- let sigma = (1.5 + 6.0 * col) * scale.max(0.35) * (1.0 + (s.detail.nr_color_smoothness / 100.0) as f32);
- let b = gaussian(&chroma, sigma);
- let keep = (s.detail.nr_color_detail / 100.0) as f32 * 0.5;
+ let b = gaussian(&chroma, nr.sigma);
for_rows(&mut img.data, w, |y, row| {
for (x, p) in row.iter_mut().enumerate() {
let i = y * w + x;
let yl = luminance_2020(*p);
let c0 = chroma.data[i];
let cb = b.data[i];
- let t = col * (1.0 - keep);
- *p = [0, 1, 2].map(|k| ((c0[k] + (cb[k] - c0[k]) * t) * yl).max(0.0));
+ *p = [0, 1, 2].map(|k| ((c0[k] + (cb[k] - c0[k]) * nr.t) * yl).max(0.0));
}
});
if let Some(t) = _t {
@@ -191,32 +222,60 @@ fn plane_at(slot: &mut Option<(u32, Arc<Plane>)>, sigma: f32, f: impl FnOnce() -
}
}
-/// The spatial planes the per-pixel stage needs for `img` (white-balanced, before exposure),
-/// reusing whatever `planes` already holds for it. Missing planes are computed side by side (each
-/// one alone scales poorly: the guided filters work on small subsampled grids).
-pub(crate) fn prepare(img: Arc<Rgb32f>, s: &DevelopSettings, frame: &Frame, px_per_long: f64, q: Quality, planes: &mut Planes) -> Prepared {
- let log_l = planes.log_l.get_or_insert_with(|| Arc::new(timed("log_l", || img.map(log_lum)))).clone();
+/// Guided-filter epsilons (EV²) of the highlights/shadows base and the clarity band.
+pub const BASE_EPS: f32 = 0.35;
+pub const CLARITY_EPS: f32 = 0.8;
+
+/// Dark channel of a pixel (dehaze).
+#[inline]
+pub fn dark_of(c: [f32; 3]) -> f32 {
+ c[0].min(c[1]).min(c[2])
+}
+
+/// Radii (px) of the spatial planes the settings need (`None` = not needed).
+#[derive(Clone, Copy, Debug, Default, PartialEq)]
+pub struct PlaneSigmas {
+ /// Edge-aware base for highlights/shadows (fast guided filter, [`BASE_EPS`]).
+ pub base: Option<f32>,
+ /// Clarity band (fast guided filter, [`CLARITY_EPS`]).
+ pub clarity: Option<f32>,
+ /// Texture / sharpening band (Gaussian).
+ pub texture: Option<f32>,
+ /// Dehaze dark channel (Gaussian).
+ pub dark: Option<f32>,
+}
+
+pub fn plane_sigmas(s: &DevelopSettings, px_per_long: f64, q: Quality) -> PlaneSigmas {
let ppl = px_per_long as f32;
let local_any = |f: fn(&lightcraft_develop::LocalAdjustments) -> f64| s.masks.iter().any(|m| f(&m.adjust) != 0.0);
let tone_active =
s.light.highlights != 0.0 || s.light.shadows != 0.0 || s.masks.iter().any(|m| m.adjust.highlights != 0.0 || m.adjust.shadows != 0.0);
// Edge-aware base at ~1.5% of the long edge (EV² epsilon: edges of > ~0.6 EV are preserved).
- let base_sigma = tone_active.then(|| {
+ let base = tone_active.then(|| {
let sigma = (0.015 * ppl).max(1.0);
if q == Quality::Draft { sigma.min(24.0) } else { sigma }
});
- let clarity_sigma = (s.effects.clarity != 0.0 || local_any(|a| a.clarity)).then(|| (0.012 * ppl).max(1.0));
- let texture_sigma = (s.effects.texture != 0.0 || s.detail.sharpen_amount != 0.0 || local_any(|a| a.texture) || local_any(|a| a.sharpness))
+ let clarity = (s.effects.clarity != 0.0 || local_any(|a| a.clarity)).then(|| (0.012 * ppl).max(1.0));
+ let texture = (s.effects.texture != 0.0 || s.detail.sharpen_amount != 0.0 || local_any(|a| a.texture) || local_any(|a| a.sharpness))
.then(|| (0.0018 * ppl).max(0.6));
- let dark_sigma = (s.effects.dehaze != 0.0 || local_any(|a| a.dehaze)).then(|| (0.02 * ppl).max(1.0));
+ let dark = (s.effects.dehaze != 0.0 || local_any(|a| a.dehaze)).then(|| (0.02 * ppl).max(1.0));
+ PlaneSigmas { base, clarity, texture, dark }
+}
+
+/// The spatial planes the per-pixel stage needs for `img` (white-balanced, before exposure),
+/// reusing whatever `planes` already holds for it. Missing planes are computed side by side (each
+/// one alone scales poorly: the guided filters work on small subsampled grids).
+pub(crate) fn prepare(img: Arc<Rgb32f>, s: &DevelopSettings, frame: &Frame, px_per_long: f64, q: Quality, planes: &mut Planes) -> Prepared {
+ let log_l = planes.log_l.get_or_insert_with(|| Arc::new(timed("log_l", || img.map(log_lum)))).clone();
+ let PlaneSigmas { base: base_sigma, clarity: clarity_sigma, texture: texture_sigma, dark: dark_sigma } = plane_sigmas(s, px_per_long, q);
let Planes { base: sb, clarity: sc, texture: st, dark: sd, .. } = planes;
let l = &log_l;
let (base, (clarity_blur, (texture_blur, dark))) = par_join(
- || base_sigma.map(|sg| plane_at(sb, sg, || timed("base", || guided_fast(l, sg, 0.35)))),
+ || base_sigma.map(|sg| plane_at(sb, sg, || timed("base", || guided_fast(l, sg, BASE_EPS)))),
|| {
par_join(
- || clarity_sigma.map(|sg| plane_at(sc, sg, || timed("clarity", || guided_fast(l, sg, 0.8)))),
+ || clarity_sigma.map(|sg| plane_at(sc, sg, || timed("clarity", || guided_fast(l, sg, CLARITY_EPS)))),
|| {
par_join(
|| texture_sigma.map(|sg| plane_at(st, sg, || timed("texture", || gaussian(l, sg)))),
@@ -224,7 +283,7 @@ pub(crate) fn prepare(img: Arc<Rgb32f>, s: &DevelopSettings, frame: &Frame, px_p
dark_sigma.map(|sg| match sd {
Some((k, d, air)) if *k == sg.to_bits() => (d.clone(), *air),
_ => {
- let d = timed("dehaze", || Arc::new(gaussian(&img.map(|c| c[0].min(c[1]).min(c[2])), sg)));
+ let d = timed("dehaze", || Arc::new(gaussian(&img.map(dark_of), sg)));
let air = airlight(&d);
*sd = Some((sg.to_bits(), d.clone(), air));
(d, air)
@@ -242,9 +301,8 @@ pub(crate) fn prepare(img: Arc<Rgb32f>, s: &DevelopSettings, frame: &Frame, px_p
None => (None, 1.0),
};
let ev = s.light.exposure as f32;
- let gain = 2f32.powf(ev);
let masks = timed("masks", || masks::evaluate(&s.masks, frame, img.width, img.height, &img, &log_l, ev));
- Prepared { img, log_l, base, clarity_blur, texture_blur, dark, air, masks, ev, gain, px_per_long }
+ Prepared { img, log_l, base, clarity_blur, texture_blur, dark, air, masks, px_per_long }
}
/// Airlight estimate: bright end of the dark channel.
diff --git a/crates/pipeline/src/tone.rs b/crates/pipeline/src/tone.rs
index 2419cf19c..63d23abc1 100644
--- a/crates/pipeline/src/tone.rs
+++ b/crates/pipeline/src/tone.rs
@@ -9,9 +9,10 @@
//! S-curve adjustments in a gamma-2.2 perceptual domain and a short shoulder above 0.95.
pub const GREY: f32 = 0.18;
-const LUT_MIN_EV: f32 = -14.0;
-const LUT_MAX_EV: f32 = 10.0;
-const LUT_N: usize = 4096;
+/// The tone LUT spans `LUT_MIN_EV..LUT_MAX_EV` around grey in `LUT_N` steps.
+pub const LUT_MIN_EV: f32 = -14.0;
+pub const LUT_MAX_EV: f32 = 10.0;
+pub const LUT_N: usize = 4096;
#[derive(Clone, Debug)]
pub struct ToneMap {
@@ -86,6 +87,11 @@ impl ToneMap {
ToneMap { lut }
}
+ /// The table (`LUT_N` entries, see [`ToneMap::apply`]).
+ pub fn lut(&self) -> &[f32] {
+ &self.lut
+ }
+
/// Scene luminance → display-linear luminance.
#[inline]
pub fn apply(&self, y: f32) -> f32 {
diff --git a/crates/raster/src/blur.rs b/crates/raster/src/blur.rs
index ac8eeda6c..8deba2d13 100644
--- a/crates/raster/src/blur.rs
+++ b/crates/raster/src/blur.rs
@@ -4,7 +4,7 @@ use crate::resample::Pixel;
use crate::{Image, par_rows};
/// Box radii approximating a Gaussian of `sigma` with 3 passes (Kovesi / Wells).
-fn box_radii(sigma: f32) -> [usize; 3] {
+pub fn box_radii(sigma: f32) -> [usize; 3] {
let n = 3.0f32;
let w_ideal = (12.0 * sigma * sigma / n + 1.0).sqrt();
let mut wl = w_ideal.floor() as i32;
@@ -40,7 +40,7 @@ fn box_row<T: Pixel>(row: &mut [T], tmp: &mut Vec<T>, r: usize) {
}
/// Rows per parallel band in the vertical pass (each band re-primes its running sums).
-const BAND: usize = 32;
+pub const BAND: usize = 32;
/// One vertical box pass `src → dst` (clamped edges): a running sum per column, vectorized across
/// the row, parallel over horizontal bands. Cache-friendly — no transposes.
diff --git a/crates/raster/src/resample.rs b/crates/raster/src/resample.rs
index b6c37b792..a57595838 100644
--- a/crates/raster/src/resample.rs
+++ b/crates/raster/src/resample.rs
@@ -54,8 +54,9 @@ impl Filter {
}
}
-/// Contributions for each output coordinate: (first source index, weights).
-fn weights(src: usize, dst: usize, filter: Filter) -> Vec<(usize, Vec<f32>)> {
+/// Contributions for each output coordinate: (first source index, weights) — the exact taps
+/// [`resize`] uses (GPU kernels upload these tables).
+pub fn weights(src: usize, dst: usize, filter: Filter) -> Vec<(usize, Vec<f32>)> {
let scale = src as f32 / dst as f32;
let fscale = scale.max(1.0);
let support = filter.support() * fscale;