Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions crates/develop/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,12 +99,15 @@ pub enum Process {
/// V6, with film grain from a stack of crystal layers (after Aurélien Pierre's model): resolution
/// independent, fading out at black and white; V1 to V6 keep their value noise.
V7,
/// V7, with the Highlights/Shadows base taken of log luminance without its fine detail (clamped
/// between a fine and a 3× wider median), so gaps in dark lettering aren't lifted into bright blocks.
V8,
}

impl Process {
/// Every process, oldest first.
pub const ALL: [Process; 7] = [Process::V1, Process::V2, Process::V3, Process::V4, Process::V5, Process::V6, Process::V7];
pub const LATEST: Process = Process::V7;
pub const ALL: [Process; 8] = [Process::V1, Process::V2, Process::V3, Process::V4, Process::V5, Process::V6, Process::V7, Process::V8];
pub const LATEST: Process = Process::V8;

pub const fn version(self) -> ProcessVersion {
match self {
Expand All @@ -115,6 +118,7 @@ impl Process {
Process::V5 => ProcessVersion(5),
Process::V6 => ProcessVersion(6),
Process::V7 => ProcessVersion(7),
Process::V8 => ProcessVersion(8),
}
}
}
Expand Down
9 changes: 4 additions & 5 deletions crates/develop/src/tests_process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,14 +89,13 @@ fn v1_is_left_out_when_saving_and_other_processes_are_kept() {
#[test]
fn unknown_process_numbers_load_and_render_with_the_newest_known() {
// written by a newer LightCraft: kept as it is, rendered with the latest process this build has
let newer = Process::LATEST.version().0 + 1;
let s = DevelopSettings::from_json(&json!({"process": newer, "light": {"exposure": 0.5}})).unwrap();
assert_eq!(s.process, ProcessVersion(newer));
let s = DevelopSettings::from_json(&json!({"process": LATEST_PLUS_ONE, "light": {"exposure": 0.5}})).unwrap();
assert_eq!(s.process, ProcessVersion(LATEST_PLUS_ONE));
assert_eq!(s.process.process(), Process::LATEST);
assert!(!s.process.is_known());
assert!(!s.process.is_outdated(), "never downgraded by Update to Current Process");
assert_eq!(s.to_json()["process"], json!(newer));
assert_eq!(s.merged(&json!({"light": {"exposure": 1.0}})).unwrap().process, ProcessVersion(newer));
assert_eq!(s.to_json()["process"], json!(LATEST_PLUS_ONE));
assert_eq!(s.merged(&json!({"light": {"exposure": 1.0}})).unwrap().process, ProcessVersion(LATEST_PLUS_ONE));
// below V1 (no LightCraft writes it): rendered as V1, and updatable
let zero = DevelopSettings::from_json(&json!({"process": 0})).unwrap().process;
assert_eq!((zero.process(), zero.is_known(), zero.is_outdated()), (Process::V1, false, true));
Expand Down
7 changes: 6 additions & 1 deletion crates/gpu/src/ctx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ const MODULES: &[Module] = &[
"guided_pre",
"guided_ab",
"guided_apply",
"clamp_between_k",
"wb_k",
"nr_lum",
"chroma_k",
Expand Down Expand Up @@ -197,7 +198,11 @@ fn build_jobs(
layout: Some(&p.pipeline_layout),
module: &p.module,
entry_point: Some(entry),
compilation_options: Default::default(),
// Only the median kernels (`blur.wgsl`, `med_tile`) use workgroup memory, and they
// load every element they read before the barrier, so wgpu's default zeroing is not
// needed. On DX12 it is written out as one assignment per element, which made FXC take
// about 87 s over these kernels at every start of a release build.
compilation_options: wgpu::PipelineCompilationOptions { zero_initialize_workgroup_memory: false, ..Default::default() },
cache: None,
});
let kernel = Kernel { pipeline, layout: p.layout.clone(), nbuf: p.nbuf };
Expand Down
102 changes: 96 additions & 6 deletions crates/gpu/src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -371,28 +371,48 @@ fn guided_coeffs(cx: &mut Cx<'_>, p: &Buf, w: usize, h: usize, sigma: f32, eps:
gaussian(cx, &ab, w, h, 2, sigma)
}

/// Pixels per thread along the pass of `median_h` / `median_v` (`MED_K` in `blur.wgsl`).
const MEDIAN_K: usize = 4;

/// Separable median of a plane (`local::median_hv`).
fn median_hv(cx: &mut Cx<'_>, p: &Buf, w: usize, h: usize, r: usize) -> Buf {
if r == 0 || w * h == 0 {
return cx.copy(p);
}
let pr = [w as u32, h as u32, 1, r.min(local::BASE_DETAIL_MAX) as u32];
let tmp = cx.gpu.buffer(w * h);
cx.run("median_h", &pr, &[Some(p), Some(&tmp)], groups2(w, h, [16, 16]));
cx.run("median_h", &pr, &[Some(p), Some(&tmp)], groups2(w.div_ceil(MEDIAN_K), h, [16, 16]));
let out = cx.gpu.buffer(w * h);
cx.run("median_v", &pr, &[Some(&tmp), Some(&out)], groups2(w, h, [16, 16]));
cx.run("median_v", &pr, &[Some(&tmp), Some(&out)], groups2(w, h.div_ceil(MEDIAN_K), [16, 16]));
out
}

/// The highlights/shadows base (`local::tone_base`; `detail` 0: V1, no median).
fn tone_base(cx: &mut Cx<'_>, l: &Buf, w: usize, h: usize, sigma: f32, detail: usize) -> Buf {
/// The highlights/shadows base (`local::tone_base`; `detail` 0: V1, no detail removal).
fn tone_base(cx: &mut Cx<'_>, l: &Buf, w: usize, h: usize, sigma: f32, detail: usize, keeps_gaps: bool) -> Buf {
if detail == 0 {
return guided_fast(cx, l, w, h, sigma, local::BASE_EPS);
}
let m = median_hv(cx, l, w, h, detail);
let m = if keeps_gaps { detail_free(cx, l, w, h, detail) } else { median_hv(cx, l, w, h, detail) };
guided_fast(cx, &m, w, h, sigma, local::BASE_EPS)
}

/// Log luminance without detail finer than `r` px (`local::detail_free`): clamped between its
/// median at `r` and the median of a `local::BASE_COARSE_STEP`× downscaled copy, enlarged.
fn detail_free(cx: &mut Cx<'_>, l: &Buf, w: usize, h: usize, r: usize) -> Buf {
if r == 0 || w * h == 0 {
return cx.copy(l);
}
let fine = median_hv(cx, l, w, h, r);
let s = local::BASE_COARSE_STEP;
let (lw, lh) = (w.div_ceil(s).max(1), h.div_ceil(s).max(1));
let lo = resize(cx, l, (w, h), (lw, lh), 1, Filter::Box);
let lo_median = median_hv(cx, &lo, lw, lh, r);
let coarse = resize(cx, &lo_median, (lw, lh), (w, h), 1, Filter::Bilinear);
let out = cx.gpu.buffer(w * h);
map(cx, "clamp_between_k", w * h, &[], [Some(l), Some(&fine), Some(&coarse)], &out);
out
}

/// Fast guided filter (`local::guided_fast`): coefficients on a subsampled grid.
fn guided_fast(cx: &mut Cx<'_>, p: &Buf, w: usize, h: usize, sigma: f32, eps: f32) -> Buf {
let s = local::guided_fast_step(sigma);
Expand Down Expand Up @@ -1418,7 +1438,7 @@ fn prepare(cx: &mut Cx<'_>, lin: &Buf, plan: &Plan<'_>, req: &RenderRequest, pla
let base = match sig.base {
Some(sg) => {
let key = local::base_key(&plan.settings, sg, sig.base_detail);
plane_at(&mut planes.base, key, || tone_base(cx, &log_l, w, h, sg, sig.base_detail))
plane_at(&mut planes.base, key, || tone_base(cx, &log_l, w, h, sg, sig.base_detail, local::base_keeps_gaps(&plan.settings)))
}
None => log_l.clone(),
};
Expand Down Expand Up @@ -1841,6 +1861,76 @@ mod tests {
time("guided sigma=1.75", &mut |cx| drop(guided(cx, &src, w, h, 1.75, 0.01)));
}

/// The tiled median kernels select exactly what the CPU's sorted window does: edge tiles,
/// planes smaller than a tile or a window, every radius and many ties.
#[test]
fn median_matches_cpu_bit_for_bit() {
// (creating the device writes the crash sentinel another test swaps out)
let _serial = crate::DEVICE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
let Some(gpu) = crate::device() else { return lightcraft_testkit::skip!(Gpu, "no GPU adapter") };
let _scope = crate::ctx::RenderScope::new(gpu);
let mut seed = 0x9e37_79b9_u32;
let mut next = move || {
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
seed
};
for (w, h) in [(1, 1), (2, 3), (5, 70), (70, 5), (63, 65), (130, 67), (200, 129)] {
// a coarse level set gives ties; a smooth ramp and fine noise give distinct values
let mut p = Plane::new(w, h);
for (i, o) in p.data.iter_mut().enumerate() {
let (x, y) = (i % w, i / w);
*o = match (next() % 3, next()) {
(0, v) => (v % 7) as f32 * 0.5 - 2.0,
(1, v) => (x + 2 * y) as f32 * 0.01 + (v % 100) as f32 * 1e-4,
(_, v) => (v % 10_000) as f32 * 1e-3 - 5.0,
};
}
let src = gpu.upload(&p.data);
for r in 1..=local::BASE_DETAIL_MAX {
let mut cx = Cx::new(gpu);
let out = median_hv(&mut cx, &src, w, h, r);
let got: Vec<f32> = cx.read(&out, w * h);
let want = local::median_hv(&p, r);
let bad = got.iter().zip(&want.data).position(|(g, c)| g.to_bits() != c.to_bits());
assert!(bad.is_none(), "{w}×{h} r={r}: pixel {bad:?}");
}
}
}

/// Highlights/shadows base timings on the #3460 frame size:
/// `cargo test --release -p lightcraft-gpu bench_tone_base -- --ignored --nocapture`.
#[test]
#[ignore]
fn bench_tone_base() {
let Some(gpu) = crate::device() else { return eprintln!("no gpu: {:?}", crate::unavailable_reason()) };
let _scope = crate::ctx::RenderScope::new(gpu);
let (w, h) = (6960, 4640);
let r = local::base_detail_radius(w as f64);
eprintln!("{} ({:?}) r={r}", gpu.info.name, gpu.info.backend);
let l: Vec<f32> = (0..w * h).map(|i: usize| ((i.wrapping_mul(2_654_435_761)) % 1000) as f32 / 250.0 - 6.0).collect();
let src = gpu.upload(&l);
let time = |name: &str, f: &mut dyn FnMut(&mut Cx<'_>)| {
let mut ts = Vec::new();
for _ in 0..9 {
let mut cx = Cx::new(gpu);
cx.sync();
let t = std::time::Instant::now();
f(&mut cx);
cx.sync();
ts.push(t.elapsed().as_secs_f64() * 1e3);
}
ts.sort_by(f64::total_cmp);
eprintln!("{name:<40} min {:.1} ms median {:.1} ms", ts[0], ts[4]);
};
let sigma = 0.015 * w as f32;
time("median_hv", &mut |cx| drop(median_hv(cx, &src, w, h, r)));
time("detail_free", &mut |cx| drop(detail_free(cx, &src, w, h, r)));
time("guided_fast", &mut |cx| drop(guided_fast(cx, &src, w, h, sigma, local::BASE_EPS)));
time("tone_base", &mut |cx| drop(tone_base(cx, &src, w, h, sigma, r, true)));
}

/// The device scores Remove's candidate sources like the CPU and picks the same one.
#[test]
fn auto_source_picks_the_cpu_candidate() {
Expand Down
120 changes: 89 additions & 31 deletions crates/gpu/src/wgsl/blur.wgsl
Original file line number Diff line number Diff line change
Expand Up @@ -113,56 +113,114 @@ fn minmax(@builtin(global_invocation_id) g: vec3<u32>) {
}

// Separable median of a single-channel plane (`lightcraft_pipeline::local::median_hv`): 2r+1
// taps (r ≤ 24, clamped edges) along a row (median_h) or a column (median_v), one thread per
// pixel. The median is a selection, so the result matches the CPU's bit for bit.
// taps (1 ≤ r ≤ 24, clamped edges) along a row (median_h) or a column (median_v). The median is a
// selection, so the result matches the CPU's bit for bit.
// P: w, h, nc (unused), r.
fn median_of(n: u32, r: u32, v: ptr<function, array<f32, 49>>) -> f32 {
// partial selection sort up to the middle
for (var i = 0u; i <= r; i++) {
var m = i;
for (var j = i + 1u; j < n; j++) {
if ((*v)[j] < (*v)[m]) {
m = j;
}
//
// Each thread finds the medians of 4 neighbouring pixels along the pass by rank: a tap is the
// median of a window when fewer than r+1 of its taps are smaller and at least r+1 are smaller or
// equal. The 4 windows share all but their first and last 3 taps, so one count over the shared
// taps serves all four. A 16×16 workgroup (64 pixels along the pass, 16 lines across) first loads
// its taps into `med_tile`. On a 6960×4640 plane at r = 10 this takes 47 ms on an M2 Max, against
// 191 ms for a partial selection sort per pixel over a private array of taps, which drivers keep in
// scratch memory because it is indexed dynamically.
const MED_K: u32 = 4u;
const MED_LINE: u32 = 113u; // 16·MED_K + 2·24, odd
// Not zero-initialised (`build_jobs` in ctx.rs turns that off): write every element read.
var<workgroup> med_tile: array<f32, 1808>; // 16 lines

// The medians of the 2r+1-tap windows starting at `med_tile[base + k]`, k < 4 (r ≥ 1). Taps 3 to
// n-1 are in all four windows; the three at each end are in some.
fn median4(base: u32, r: u32) -> vec4<f32> {
let n = 2u * r + 1u;
let e0 = vec3<f32>(med_tile[base], med_tile[base + 1u], med_tile[base + 2u]);
let e1 = vec3<f32>(med_tile[base + n], med_tile[base + n + 1u], med_tile[base + n + 2u]);
var out = vec4<f32>(0.0);
var found = vec4<bool>(false);
for (var i = 0u; i < n + 3u; i++) {
let c = med_tile[base + i];
var less = 0u;
var le = 0u;
for (var j = 3u; j < n; j++) {
let v = med_tile[base + j];
less += select(0u, 1u, v < c);
le += select(0u, 1u, v <= c);
}
let l0 = select(vec3<u32>(0u), vec3<u32>(1u), e0 < vec3<f32>(c));
let l1 = select(vec3<u32>(0u), vec3<u32>(1u), e1 < vec3<f32>(c));
let q0 = select(vec3<u32>(0u), vec3<u32>(1u), e0 <= vec3<f32>(c));
let q1 = select(vec3<u32>(0u), vec3<u32>(1u), e1 <= vec3<f32>(c));
// window k: taps k..k+n-1 = taps k..2 of the start, the middle, taps n..n+k-1 of the end
let lw = vec4<u32>(l0.x + l0.y + l0.z, l0.y + l0.z + l1.x, l0.z + l1.x + l1.y, l1.x + l1.y + l1.z) + vec4<u32>(less);
let qw = vec4<u32>(q0.x + q0.y + q0.z, q0.y + q0.z + q1.x, q0.z + q1.x + q1.y, q1.x + q1.y + q1.z) + vec4<u32>(le);
let has = vec4<bool>((i < n), (i >= 1u) && (i < n + 1u), (i >= 2u) && (i < n + 2u), (i >= 3u));
let hit = has & !found & (lw <= vec4<u32>(r)) & (qw > vec4<u32>(r));
out = select(out, vec4<f32>(c), hit);
found = found | hit;
if (all(found)) {
break;
}
let t = (*v)[i];
(*v)[i] = (*v)[m];
(*v)[m] = t;
}
return (*v)[r];
return out;
}

// Thread (l.x, l.y) of a workgroup takes line l.x and pixels 4·l.y to 4·l.y + 3 along it, so the
// threads of a SIMD group read 16 different lines at once; with an odd line length those fall in
// different banks of workgroup memory.
@compute @workgroup_size(16, 16)
fn median_h(@builtin(global_invocation_id) g: vec3<u32>) {
fn median_h(@builtin(local_invocation_id) l: vec3<u32>, @builtin(workgroup_id) wg: vec3<u32>) {
let w = pu(0u);
let h = pu(1u);
let r = min(pu(3u), 24u);
if (g.x >= w || g.y >= h) {
let span = 16u * MED_K + 2u * r;
let x0 = i32(wg.x * 16u * MED_K) - i32(r);
// load: consecutive threads read consecutive pixels of a row
for (var e = l.y * 16u + l.x; e < 16u * span; e += 256u) {
let line = e / span;
let k = e % span;
let y = min(wg.y * 16u + line, h - 1u);
let x = clamp(x0 + i32(k), 0, i32(w) - 1);
med_tile[line * MED_LINE + k] = src[y * w + u32(x)];
}
workgroupBarrier();
let y = wg.y * 16u + l.x;
let x = (wg.x * 16u + l.y) * MED_K;
if (x >= w || y >= h) {
return;
}
let n = 2u * r + 1u;
var v: array<f32, 49>;
let row = g.y * w;
for (var k = 0u; k < n; k++) {
let x = clamp(i32(g.x + k) - i32(r), 0, i32(w) - 1);
v[k] = src[row + u32(x)];
let m = median4(l.x * MED_LINE + l.y * MED_K, r);
for (var k = 0u; k < MED_K; k++) {
if (x + k < w) {
dst[y * w + x + k] = m[k];
}
}
dst[row + g.x] = median_of(n, r, &v);
}

@compute @workgroup_size(16, 16)
fn median_v(@builtin(global_invocation_id) g: vec3<u32>) {
fn median_v(@builtin(local_invocation_id) l: vec3<u32>, @builtin(workgroup_id) wg: vec3<u32>) {
let w = pu(0u);
let h = pu(1u);
let r = min(pu(3u), 24u);
if (g.x >= w || g.y >= h) {
let span = 16u * MED_K + 2u * r;
let y0 = i32(wg.y * 16u * MED_K) - i32(r);
// load: consecutive threads read consecutive pixels of a row (16 columns)
for (var e = l.y * 16u + l.x; e < 16u * span; e += 256u) {
let line = e % 16u;
let k = e / 16u;
let x = min(wg.x * 16u + line, w - 1u);
let y = clamp(y0 + i32(k), 0, i32(h) - 1);
med_tile[line * MED_LINE + k] = src[u32(y) * w + x];
}
workgroupBarrier();
let x = wg.x * 16u + l.x;
let y = (wg.y * 16u + l.y) * MED_K;
if (x >= w || y >= h) {
return;
}
let n = 2u * r + 1u;
var v: array<f32, 49>;
for (var k = 0u; k < n; k++) {
let y = clamp(i32(g.y + k) - i32(r), 0, i32(h) - 1);
v[k] = src[u32(y) * w + g.x];
let m = median4(l.x * MED_LINE + l.y * MED_K, r);
for (var k = 0u; k < MED_K; k++) {
if (y + k < h) {
dst[(y + k) * w + x] = m[k];
}
}
dst[g.y * w + g.x] = median_of(n, r, &v);
}
19 changes: 19 additions & 0 deletions crates/gpu/src/wgsl/map.wgsl
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,25 @@ fn guided_apply(@builtin(global_invocation_id) g: vec3<u32>, @builtin(num_workgr
dst[i] = b[2u * i] * a[i] + b[2u * i + 1u];
}

// `clamp_between` (`local::detail_free`): a clamped between b and c, in either order.
@compute @workgroup_size(256)
fn clamp_between_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 lo = min(b[i], c[i]);
let hi = max(b[i], c[i]);
let v = a[i];
if (v < lo) {
dst[i] = lo;
} else if (v > hi) {
dst[i] = hi;
} else {
dst[i] = v;
}
}

// Cross guided filter (`masks::guided_cross`), a: guide, b: input. P[1] = 0: (guide, input);
// 1: (guide·input, guide²).
@compute @workgroup_size(256)
Expand Down
4 changes: 2 additions & 2 deletions crates/gpu/tests/it/equivalence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -807,7 +807,7 @@ fn light_v3_operators_match() {
}

/// Issue #632: the Highlights / Shadows base of each process (V1: the edge-aware filter of log
/// luminance; V2: of its fine median, a radius that grows with the render) matches the CPU's, and
/// luminance; V2 to V7: of its fine median, V8 on: of its detail-free plane, a radius that grows with the render) matches the CPU's, and
/// a warm cache never hands one process the other's base.
#[test]
fn highlights_shadows_base_matches_on_every_process() {
Expand Down Expand Up @@ -838,7 +838,7 @@ fn highlights_shadows_base_matches_on_every_process() {
}];
check(&format!("{p:?} local highlights {w}"), &src, &raw, &s, &req);
}
for p in [Process::V1, Process::V2, Process::V4, Process::V1, Process::V2, Process::V4] {
for p in [Process::V1, Process::V2, Process::V4, Process::V8, Process::V1, Process::V2, Process::V4, Process::V8] {
let mut s = DevelopSettings { process: p.version(), ..DevelopSettings::default() };
s.light.highlights = -100.0;
let warm = lightcraft_gpu::render(&src, &raw, &s, &req, Some(&cache)).expect("gpu");
Expand Down
Loading
Loading