mirror of
https://github.com/storytold/lightcraft.git
synced 2026-11-28 09:19:25 +01:00
LR-EDIT-EFFECTS-GRAIN: crystal grain keeps slider drags in budget on slower machines
Measured on a Ryzen 5 7545U with a Radeon 740M (RADV), where grain cost what the M2 Max hid: - The tables stay on the GPU between renders (Gpu::grain_tables) and are copied into the finish kernel's aux buffer on the device, instead of being appended to aux and uploaded (12 MB) on every render. Amount drag, 2.5 MP preview: 16.9 -> 11-15 ms a frame (no grain: 8 ms). - A draft render (a drag) doesn't wait for a tile it hasn't got: the last tile of the seed stands in while the new one is drawn in the background, on a pool of half the cores; the full render when the drag ends waits for the exact tile. Size drag: 62-66 -> 13-14 ms a frame. wasm drafts still wait. - Stamps draw each row as a 64-bit mask, a fixed number of rows per layer, rows outside the band landing in scratch rows around it: no branch per row. Tiles 10-20 % faster at every setting, bit-identical. Tests: GPU grain patterns in turn (same, new size, new roughness, new seed, back) match the CPU; a drag takes the last tile while the next is drawn, then the exact one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0c6cd98215
commit
fe6e064975
10 files changed
+330
-67
No files matched your search
+39
-1
@@ -337,6 +337,9 @@ pub struct Gpu {
|
||||
free: std::sync::Mutex<Vec<Tracked>>,
|
||||
/// Largest storage buffer the device accepts (bytes).
|
||||
pub max_buffer: u64,
|
||||
/// The crystal grain tables of the last grain pattern, resident: a render (each Amount step
|
||||
/// of a drag) copies them on the GPU instead of uploading their 12 MB again ([`Gpu::grain_tables`]).
|
||||
grain: std::sync::Mutex<Option<(std::sync::Arc<lightcraft_pipeline::crystal::CrystalTile>, Buf)>>,
|
||||
}
|
||||
|
||||
/// WGSL constants shared by every module (generated from the CPU pipeline's values).
|
||||
@@ -459,7 +462,7 @@ impl Gpu {
|
||||
});
|
||||
let max_buffer = limits.max_storage_buffer_binding_size.min(limits.max_buffer_size);
|
||||
log::info!("gpu: {} ({:?}), {} kernels in {build_ms} ms, buffers ≤ {} MiB", info.name, info.backend, kernels.len(), max_buffer >> 20);
|
||||
Ok(Gpu { device, queue, info, kernels, dummy, free: Default::default(), max_buffer })
|
||||
Ok(Gpu { device, queue, info, kernels, dummy, free: Default::default(), max_buffer, grain: Default::default() })
|
||||
}
|
||||
|
||||
/// A buffer of `len` 32-bit values with undefined contents (a recycled one when possible).
|
||||
@@ -641,6 +644,41 @@ impl Gpu {
|
||||
);
|
||||
}
|
||||
|
||||
/// Record into `enc` a copy of `tile`'s summed-area tables (both tori, back to back) into
|
||||
/// `dst` at value offset `at`, uploading them first unless they are the resident ones. False
|
||||
/// when `dst` can't hold them (an over-limit placeholder: the render has failed already).
|
||||
pub fn grain_tables(
|
||||
&self,
|
||||
enc: &mut wgpu::CommandEncoder,
|
||||
tile: &std::sync::Arc<lightcraft_pipeline::crystal::CrystalTile>,
|
||||
dst: &Buf,
|
||||
at: usize,
|
||||
) -> bool {
|
||||
let len: usize = tile.sats.iter().map(Vec::len).sum();
|
||||
let (start, bytes) = ((at as u64) * 4, (len as u64) * 4);
|
||||
if len == 0 || dst.raw().size() < start.saturating_add(bytes) {
|
||||
return false;
|
||||
}
|
||||
let mut resident = self.grain.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if !resident.as_ref().is_some_and(|(t, b)| std::sync::Arc::ptr_eq(t, tile) && b.raw().size() >= bytes) {
|
||||
// the old tables go back to the pool first: one pattern's tables are resident at a time
|
||||
*resident = None;
|
||||
let buf = self.buffer(len);
|
||||
if buf.raw().size() < bytes {
|
||||
return false;
|
||||
}
|
||||
let mut off = 0u64;
|
||||
for sat in &tile.sats {
|
||||
self.queue.write_buffer(buf.raw(), off, bytemuck::cast_slice(sat));
|
||||
off += (sat.len() as u64) * 4;
|
||||
}
|
||||
*resident = Some((tile.clone(), buf));
|
||||
}
|
||||
let Some((_, src)) = resident.as_ref() else { return false };
|
||||
enc.copy_buffer_to_buffer(src.raw(), 0, dst.raw(), start, bytes);
|
||||
true
|
||||
}
|
||||
|
||||
/// Stands in for a buffer that could not be created (the render has failed already).
|
||||
fn placeholder(&self) -> wgpu::Buffer {
|
||||
self.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
|
||||
@@ -152,7 +152,8 @@ pub struct Present {
|
||||
}
|
||||
|
||||
/// The `finish` kernel's parameter block and auxiliary table (tone LUT | chroma curve | sRGB LUT | curve LUTs |
|
||||
/// mask terms | crystal grain tables) for `fp` with `masks` (their local adjustments' terms).
|
||||
/// mask terms) for `fp` with `masks` (their local adjustments' terms). The crystal grain's tables go
|
||||
/// after `aux` in the kernel's buffer ([`crate::render`] copies them there).
|
||||
pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Present) -> (Vec<u32>, Vec<f32>) {
|
||||
let mut aux: Vec<f32> = fp.tone.lut().to_vec();
|
||||
aux.extend_from_slice(fp.tone.chroma_lut());
|
||||
@@ -169,11 +170,14 @@ pub fn finish_block(fp: &FinishParams, masks: &[[f32; MASK_TERMS]], present: &Pr
|
||||
for m in masks {
|
||||
aux.extend_from_slice(m);
|
||||
}
|
||||
// the crystal grain's tables follow `aux` on the GPU without being part of it: they stay
|
||||
// resident between renders ([`crate::Gpu::grain_tables`]) and the render copies them in
|
||||
let mut sat_off = [0u32; 2];
|
||||
if let Some(GrainModel::Crystal(g)) = &fp.grain {
|
||||
for (off, sat) in sat_off.iter_mut().zip(&g.tile.sats) {
|
||||
*off = aux.len() as u32;
|
||||
aux.extend_from_slice(sat);
|
||||
let mut off = aux.len();
|
||||
for (slot, sat) in sat_off.iter_mut().zip(&g.tile.sats) {
|
||||
*slot = off as u32;
|
||||
off += sat.len();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -156,6 +156,20 @@ impl<'a> Cx<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The finish kernel's `aux` buffer: `aux`, then the crystal grain's tables when it has them
|
||||
/// (copied on the GPU from the resident ones, see [`Gpu::grain_tables`]).
|
||||
pub fn finish_aux(&mut self, aux: &[f32], grain: Option<&lightcraft_pipeline::finish::GrainModel>) -> Buf {
|
||||
let Some(lightcraft_pipeline::finish::GrainModel::Crystal(g)) = grain else { return self.gpu.upload(aux) };
|
||||
let tables: usize = g.tile.sats.iter().map(Vec::len).sum();
|
||||
let out = self.gpu.buffer(aux.len().saturating_add(tables));
|
||||
if !aux.is_empty() && out.raw().size() >= (aux.len() as u64) * 4 {
|
||||
self.gpu.queue.write_buffer(out.raw(), 0, bytemuck::cast_slice(aux));
|
||||
}
|
||||
let enc = self.enc.get_or_insert_with(|| self.gpu.encoder());
|
||||
self.gpu.grain_tables(enc, &g.tile, &out, aux.len());
|
||||
out
|
||||
}
|
||||
|
||||
/// Submit what is recorded and read back `len` values of `b`.
|
||||
pub fn read<T: bytemuck::Pod>(&mut self, b: &Buf, len: usize) -> Vec<T> {
|
||||
self.pending = 0;
|
||||
@@ -683,6 +697,7 @@ pub fn render(
|
||||
px_per_long: plan.px_per_long,
|
||||
air_pre: prep.air,
|
||||
space: req.space,
|
||||
draft: req.quality == lightcraft_pipeline::Quality::Draft,
|
||||
});
|
||||
// soft proofing as the CPU's `finish` sets it up (an output-device table never gets here: see `render`)
|
||||
fp.proof = req.proof.map(|pr| pr.params(req.space));
|
||||
@@ -696,7 +711,7 @@ pub fn render(
|
||||
chroma: masks.is_some() && prep.chroma.is_some(),
|
||||
};
|
||||
let (p, aux) = finish_block(&fp, &terms, &present);
|
||||
let aux = gpu.upload(&aux);
|
||||
let aux = cx.finish_aux(&aux, fp.grain.as_ref());
|
||||
// cleared, so that work which never ran cannot pass for an image (see the check below)
|
||||
let out = cx.zeroed(n);
|
||||
if fault == Some(crate::Fault::Validation) {
|
||||
|
||||
@@ -153,6 +153,33 @@ fn banded_full_size_render_matches() {
|
||||
check("banded 3000×2000", &src, &SourceInfo { raw: true, ..Default::default() }, &s, &RenderRequest::fit(w, h));
|
||||
}
|
||||
|
||||
/// The crystal grain's tables stay on the GPU between renders: an Amount change reuses them,
|
||||
/// another pattern (Size, Roughness, seed) replaces them, and going back draws the first again.
|
||||
#[test]
|
||||
fn grain_patterns_in_turn_match() {
|
||||
if !gpu() {
|
||||
return;
|
||||
}
|
||||
let src = scene(1, 480, 320);
|
||||
let info = SourceInfo { raw: true, ..Default::default() };
|
||||
let steps: [(&str, f64, f64, f64, u32); 6] = [
|
||||
("grain 50/25/50", 50.0, 25.0, 50.0, 1),
|
||||
("grain 90/25/50 (same pattern)", 90.0, 25.0, 50.0, 1),
|
||||
("grain 50/70/50 (new size)", 50.0, 70.0, 50.0, 1),
|
||||
("grain 50/70/0 (new roughness)", 50.0, 70.0, 0.0, 1),
|
||||
("grain 50/70/0 seed 7", 50.0, 70.0, 0.0, 7),
|
||||
("grain 50/25/50 again", 50.0, 25.0, 50.0, 1),
|
||||
];
|
||||
for (name, amount, size, roughness, seed) in steps {
|
||||
let mut s = DevelopSettings::default();
|
||||
s.grain.amount = amount;
|
||||
s.grain.size = size;
|
||||
s.grain.roughness = roughness;
|
||||
s.grain.seed = seed;
|
||||
check(name, &src, &info, &s, &RenderRequest::fit(480, 320));
|
||||
}
|
||||
}
|
||||
|
||||
fn cases() -> Vec<(&'static str, Edit)> {
|
||||
vec![
|
||||
("default", |_| {}),
|
||||
|
||||
+153
-24
@@ -236,11 +236,29 @@ const STAMP_R: f64 = 16.0;
|
||||
/// `(X + qx/PHASES, Y + qy/PHASES)` (`X`, `Y` integers) it covers rows `Y + rows[qy].0 ..= Y +
|
||||
/// rows[qy].1`, and in row `Y + rows[qy].0 + k` the pixels `X + o.0 ..= X + o.1`, with
|
||||
/// `o = spans[(qy·PHASES + qx)·height + k]`.
|
||||
///
|
||||
/// The same rows as bit masks, for drawing a crystal without a branch per row: phase
|
||||
/// `p = qy·PHASES + qx` spans pixels `X + extent[p].0 ..= X + extent[p].1`, and its row `k` is
|
||||
/// `masks[p·height + k]` shifted to `X + extent[p].0` (rows past the phase's own are empty).
|
||||
/// `masks` is empty when a phase is wider than 64 pixels.
|
||||
#[derive(Clone, Debug)]
|
||||
struct Stamp {
|
||||
rows: [(i32, i32); PHASES],
|
||||
height: usize,
|
||||
spans: Vec<(i32, i32)>,
|
||||
extent: Vec<(i32, i32)>,
|
||||
masks: Vec<u64>,
|
||||
}
|
||||
|
||||
/// Where [`Layer::draw`] draws: rows `y0..y0 + rows` of a torus of side `t`, `w` words per row,
|
||||
/// after `margin` scratch rows.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Band {
|
||||
t: usize,
|
||||
y0: usize,
|
||||
rows: usize,
|
||||
w: usize,
|
||||
margin: usize,
|
||||
}
|
||||
|
||||
/// One emulsion layer: its crystal (a regular polygon) and seed density, in tile pixels.
|
||||
@@ -340,7 +358,25 @@ impl Layer {
|
||||
}
|
||||
}
|
||||
}
|
||||
Stamp { rows, height, spans }
|
||||
let mut extent = vec![(0, -1); PHASES * PHASES];
|
||||
let mut masks = vec![0u64; PHASES * PHASES * height];
|
||||
let mut fits = true;
|
||||
for (p, e) in extent.iter_mut().enumerate() {
|
||||
let Some(rows) = spans.get(p * height..(p + 1) * height) else { continue };
|
||||
let used = || rows.iter().filter(|(o0, o1)| o0 <= o1);
|
||||
let (Some(lo), Some(hi)) = (used().map(|o| o.0).min(), used().map(|o| o.1).max()) else { continue };
|
||||
*e = (lo, hi);
|
||||
fits &= hi - lo < 64;
|
||||
for (m, &(o0, o1)) in masks.iter_mut().skip(p * height).zip(rows) {
|
||||
if o0 <= o1 && o1 - lo < 64 {
|
||||
*m = (!0u64 >> (63 - (o1 - o0))) << (o0 - lo);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !fits {
|
||||
masks.clear();
|
||||
}
|
||||
Stamp { rows, height, spans, extent, masks }
|
||||
}
|
||||
|
||||
/// The crystal's horizontal extent at height `y` above its centre (convex: one interval).
|
||||
@@ -352,12 +388,14 @@ impl Layer {
|
||||
}
|
||||
|
||||
/// Sets the bits of the pixels the layer covers in rows `y0..` of a torus of side `t`:
|
||||
/// `cover` holds whole rows of `w` words (bit `i % 64` of word `i / 64` is pixel `i`).
|
||||
fn draw(&self, t: usize, y0: usize, w: usize, cover: &mut [u64]) {
|
||||
let rows = cover.len() / w.max(1);
|
||||
/// `cover` holds whole rows of `w` words (bit `i % 64` of word `i / 64` is pixel `i`), the
|
||||
/// band's rows between `margin` rows above and below it (scratch: what lands there is not part
|
||||
/// of the band; `margin` is at least the stamp's height).
|
||||
fn draw(&self, t: usize, y0: usize, w: usize, margin: usize, cover: &mut [u64]) {
|
||||
let rows = (cover.len() / w.max(1)).saturating_sub(2 * margin);
|
||||
if 2.0 * self.r < FINE {
|
||||
// each pixel covered with probability FILLING (one half: one random bit)
|
||||
for (j, row) in cover.chunks_mut(w.max(1)).enumerate() {
|
||||
for (j, row) in cover.chunks_mut(w.max(1)).skip(margin).take(rows).enumerate() {
|
||||
let mut bits = Stream(hash(self.seed, self.index, (y0 + j) as u32, 0xb175));
|
||||
for v in row.iter_mut() {
|
||||
*v = bits.next() as u64 | (bits.next() as u64) << 32;
|
||||
@@ -379,7 +417,7 @@ impl Layer {
|
||||
let mut h = Stream(hash(self.seed ^ (self.index << 20), cx as u32, wy, 0xce11));
|
||||
for _ in 0..poisson(&cdf, h.next()) {
|
||||
let (u, v) = (unit(h.next()), unit(h.next()));
|
||||
self.splat((cx as f64 + u) * c, (cy as f64 + v) * c, t, y0, w, cover);
|
||||
self.splat((cx as f64 + u) * c, (cy as f64 + v) * c, Band { t, y0, rows, w, margin }, cover);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -387,22 +425,47 @@ impl Layer {
|
||||
|
||||
/// Marks the pixels whose centres the crystal at (`px`, `py`) covers (see [`Self::draw`]).
|
||||
#[inline]
|
||||
fn splat(&self, px: f64, py: f64, t: usize, y0: usize, w: usize, cover: &mut [u64]) {
|
||||
let rows = cover.len() / w.max(1);
|
||||
fn splat(&self, px: f64, py: f64, band: Band, cover: &mut [u64]) {
|
||||
let Band { t, y0, rows, w, margin } = band;
|
||||
if let Some(st) = &self.stamp {
|
||||
let (bx, by) = (px.floor(), py.floor());
|
||||
let (qx, qy) = ((((px - bx) * PHASES as f64) as usize).min(PHASES - 1), (((py - by) * PHASES as f64) as usize).min(PHASES - 1));
|
||||
let (bx, by) = (bx as i64, by as i64);
|
||||
let Some(&(a, b)) = st.rows.get(qy) else { return };
|
||||
let (lo, hi) = ((by + a as i64).max(y0 as i64), (by + b as i64).min((y0 + rows) as i64 - 1));
|
||||
let base = (qy * PHASES + qx) * st.height;
|
||||
let Some(spans) = st.spans.get(base + (lo - by - a as i64).max(0) as usize..) else { return };
|
||||
for (j, &(o0, o1)) in (lo..=hi).zip(spans) {
|
||||
if o0 <= o1 {
|
||||
let off = (j as usize - y0) * w;
|
||||
if let Some(row) = cover.get_mut(off..off + w) {
|
||||
set_wrapped(row, t, bx + o0 as i64, bx + o1 as i64);
|
||||
if hi < lo {
|
||||
return;
|
||||
}
|
||||
// within the torus across: the whole stamp, a fixed number of rows of masks (those
|
||||
// above or below the band land in the margins)
|
||||
let p = qy * PHASES + qx;
|
||||
if let (Some(&(e0, e1)), Some(masks)) = (st.extent.get(p), st.masks.get(p * st.height..(p + 1) * st.height)) {
|
||||
let (xs, top) = (bx + e0 as i64, by + a as i64 - y0 as i64 + margin as i64);
|
||||
if xs >= 0 && bx + (e1 as i64) < t as i64 && top >= 0 {
|
||||
let (word, shift) = ((xs >> 6) as usize, (xs & 63) as u32);
|
||||
// a bit past the row's last word would be a pixel ≥ t: the high word is then 0
|
||||
let start = top as usize * w + word;
|
||||
for (k, &m) in masks.iter().enumerate() {
|
||||
let v = (m as u128) << shift;
|
||||
let i = start + k * w;
|
||||
if let Some(c) = cover.get_mut(i) {
|
||||
*c |= v as u64;
|
||||
}
|
||||
if let Some(c) = cover.get_mut(i + 1) {
|
||||
*c |= (v >> 64) as u64;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
// rows `lo..=hi` of the band, spans `k0..` of the stamp's rows (`hi ≤ by + b`: within its height)
|
||||
let (k0, n) = ((lo - by - a as i64) as usize, (hi - lo + 1) as usize);
|
||||
let base = (qy * PHASES + qx) * st.height + k0;
|
||||
let (r0, r1) = (lo as usize - y0 + margin, hi as usize + 1 - y0 + margin);
|
||||
let (Some(spans), Some(band)) = (st.spans.get(base..base + n), cover.get_mut(r0 * w..r1 * w)) else { return };
|
||||
for (row, &(o0, o1)) in band.chunks_exact_mut(w.max(1)).zip(spans) {
|
||||
if o0 <= o1 {
|
||||
set_wrapped(row, t, bx + o0 as i64, bx + o1 as i64);
|
||||
}
|
||||
}
|
||||
return;
|
||||
@@ -418,7 +481,7 @@ impl Layer {
|
||||
if i1 < i0 {
|
||||
continue;
|
||||
}
|
||||
let Some(row) = cover.get_mut((j - y0) * w..(j - y0 + 1) * w) else { continue };
|
||||
let Some(row) = cover.get_mut((j - y0 + margin) * w..(j - y0 + margin + 1) * w) else { continue };
|
||||
set_wrapped(row, t, i0, i1);
|
||||
}
|
||||
}
|
||||
@@ -519,15 +582,17 @@ impl std::fmt::Debug for CrystalTile {
|
||||
fn draw_torus(which: usize, t: usize, seed: u32, look: &CrystalLook) -> Vec<u8> {
|
||||
let layers: Vec<Layer> = emulsion(seed, look).into_iter().filter(|l| l.index as usize % 2 == which).collect();
|
||||
let w = t.div_ceil(64);
|
||||
// scratch rows above and below a band, for the stamps' rows outside it (`Layer::splat`)
|
||||
let margin = layers.iter().filter_map(|l| l.stamp.as_ref().map(|s| s.height)).max().unwrap_or(0);
|
||||
let mut count = vec![0u8; t * t];
|
||||
par_rows(&mut count, t * BAND, |band, out| {
|
||||
let rows = out.len() / t.max(1);
|
||||
let n = rows * w;
|
||||
let (mut cover, mut planes) = (vec![0u64; n], vec![0u64; PLANES * n]);
|
||||
let (mut cover, mut planes) = (vec![0u64; n + 2 * margin * w], vec![0u64; PLANES * n]);
|
||||
for layer in &layers {
|
||||
cover.fill(0);
|
||||
layer.draw(t, band * BAND, w, &mut cover);
|
||||
add_layer(&mut planes, &cover);
|
||||
layer.draw(t, band * BAND, w, margin, &mut cover);
|
||||
add_layer(&mut planes, cover.get(margin * w..margin * w + n).unwrap_or_default());
|
||||
}
|
||||
for (j, row) in out.chunks_mut(t.max(1)).enumerate() {
|
||||
for (i, o) in row.iter_mut().enumerate() {
|
||||
@@ -746,23 +811,77 @@ pub struct CrystalGrain {
|
||||
type Key = (u64, u64, u32);
|
||||
static TILES: Mutex<Vec<(Key, Arc<CrystalTile>)>> = Mutex::new(Vec::new());
|
||||
|
||||
/// The tile of `look` and `seed`, drawn or from the cache.
|
||||
fn tile(look: CrystalLook, seed: u32) -> Option<Arc<CrystalTile>> {
|
||||
/// The tile being drawn in the background for a drag ([`tile`]): one at a time.
|
||||
static DRAWING: Mutex<Option<Key>> = Mutex::new(None);
|
||||
|
||||
/// The tile of `look` and `seed`, drawn or from the cache. Unless `wait`, a tile not drawn yet
|
||||
/// is drawn in the background and the last one drawn for `seed` stands in for it meanwhile: a
|
||||
/// Size or Roughness drag doesn't wait for every step's tile (tens of milliseconds on a slow
|
||||
/// CPU), and the full-quality render when it ends waits for the exact one.
|
||||
fn tile(look: CrystalLook, seed: u32, wait: bool) -> Option<Arc<CrystalTile>> {
|
||||
let key = (look.width.to_bits(), look.spread.to_bits() ^ (look.layers as u64).rotate_left(40), seed);
|
||||
{
|
||||
let cache = TILES.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some((_, t)) = cache.iter().find(|(k, _)| *k == key) {
|
||||
return Some(t.clone());
|
||||
}
|
||||
// (wasm has no threads to draw on)
|
||||
if !wait
|
||||
&& !cfg!(target_arch = "wasm32")
|
||||
&& let Some((_, stand_in)) = cache.iter().rev().find(|(k, _)| k.2 == seed)
|
||||
{
|
||||
let stand_in = stand_in.clone();
|
||||
drop(cache);
|
||||
draw_in_background(key, look, seed);
|
||||
return Some(stand_in);
|
||||
}
|
||||
}
|
||||
let t = Arc::new(CrystalTile::new(look, seed)?);
|
||||
keep(key, t.clone());
|
||||
Some(t)
|
||||
}
|
||||
|
||||
/// Adds `t` to the cache (the most recent last).
|
||||
fn keep(key: Key, t: Arc<CrystalTile>) {
|
||||
let mut cache = TILES.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
cache.retain(|(k, _)| *k != key);
|
||||
if cache.len() >= CACHE {
|
||||
cache.remove(0);
|
||||
}
|
||||
cache.push((key, t.clone()));
|
||||
Some(t)
|
||||
cache.push((key, t));
|
||||
}
|
||||
|
||||
/// Draws the tile of `key` on the thread pool unless another is being drawn (the next render
|
||||
/// asks again for what it needs then).
|
||||
fn draw_in_background(key: Key, look: CrystalLook, seed: u32) {
|
||||
{
|
||||
let mut drawing = DRAWING.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if drawing.is_some() {
|
||||
return;
|
||||
}
|
||||
*drawing = Some(key);
|
||||
}
|
||||
let draw = move || {
|
||||
if let Some(t) = CrystalTile::new(look, seed) {
|
||||
keep(key, Arc::new(t));
|
||||
}
|
||||
*DRAWING.lock().unwrap_or_else(PoisonError::into_inner) = None;
|
||||
};
|
||||
// on a pool of its own: the renders of the drag don't queue behind its parallel bands
|
||||
match background_pool() {
|
||||
Some(pool) => pool.spawn(draw),
|
||||
None => rayon::spawn(draw),
|
||||
}
|
||||
}
|
||||
|
||||
/// Half the cores, for tiles drawn in the background (`None`: the pool couldn't be made).
|
||||
fn background_pool() -> Option<&'static rayon::ThreadPool> {
|
||||
static POOL: std::sync::OnceLock<Option<rayon::ThreadPool>> = std::sync::OnceLock::new();
|
||||
POOL.get_or_init(|| {
|
||||
let n = std::thread::available_parallelism().map_or(2, |n| n.get()).div_ceil(2);
|
||||
rayon::ThreadPoolBuilder::new().num_threads(n).thread_name(|i| format!("grain-tile-{i}")).build().ok()
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
/// The tone weight of an encoded channel value `v` (0..1): `Y·dV/dY` of the sRGB curve, i.e. how
|
||||
@@ -781,6 +900,16 @@ fn mid_weight() -> f32 {
|
||||
impl CrystalGrain {
|
||||
/// The grain of `g` at `px_per_long` output pixels per long edge (`None`: no grain).
|
||||
pub fn new(g: &Grain, px_per_long: f64) -> Option<CrystalGrain> {
|
||||
Self::with(g, px_per_long, true)
|
||||
}
|
||||
|
||||
/// [`Self::new`] for a draft render (a drag): while its tile is drawn, the last tile drawn for
|
||||
/// the same seed stands in for it (see [`tile`]).
|
||||
pub fn draft(g: &Grain, px_per_long: f64) -> Option<CrystalGrain> {
|
||||
Self::with(g, px_per_long, false)
|
||||
}
|
||||
|
||||
fn with(g: &Grain, px_per_long: f64, wait: bool) -> Option<CrystalGrain> {
|
||||
let levels = strength_levels(g.amount, g.size, g.roughness);
|
||||
if !(levels > 0.0 && px_per_long.is_finite() && px_per_long > 0.0) {
|
||||
return None;
|
||||
@@ -789,7 +918,7 @@ impl CrystalGrain {
|
||||
if !(foot.is_finite() && foot > 0.0 && foot < MAX_FOOTPRINT) {
|
||||
return None;
|
||||
}
|
||||
let tile = tile(CrystalLook::new(g.size, g.roughness), g.seed)?;
|
||||
let tile = tile(CrystalLook::new(g.size, g.roughness), g.seed, wait)?;
|
||||
Some(CrystalGrain { tile, k: (levels / 255.0) as f32 / mid_weight(), foot })
|
||||
}
|
||||
|
||||
|
||||
@@ -109,8 +109,9 @@ pub enum GrainModel {
|
||||
}
|
||||
|
||||
impl GrainModel {
|
||||
/// The grain `s` renders with at `px_per_long` output pixels per long edge (`None`: none).
|
||||
pub fn new(s: &DevelopSettings, px_per_long: f64) -> Option<GrainModel> {
|
||||
/// The grain `s` renders with at `px_per_long` output pixels per long edge (`None`: none);
|
||||
/// `draft`: for a drag ([`crate::crystal::CrystalGrain::draft`]).
|
||||
pub fn new(s: &DevelopSettings, px_per_long: f64, draft: bool) -> Option<GrainModel> {
|
||||
let g = &s.grain;
|
||||
match s.process.process() {
|
||||
Process::V1 | Process::V2 => (g.amount > 0.0).then(|| {
|
||||
@@ -122,6 +123,7 @@ impl GrainModel {
|
||||
seed: g.seed,
|
||||
})
|
||||
}),
|
||||
Process::V3 if draft => crate::crystal::CrystalGrain::draft(g, px_per_long).map(GrainModel::Crystal),
|
||||
Process::V3 => crate::crystal::CrystalGrain::new(g, px_per_long).map(GrainModel::Crystal),
|
||||
}
|
||||
}
|
||||
@@ -264,12 +266,14 @@ pub struct FinishParamsInput<'a> {
|
||||
pub px_per_long: f64,
|
||||
pub air_pre: f32,
|
||||
pub space: OutputSpace,
|
||||
/// A draft render (a drag, [`crate::Quality::Draft`]): see [`GrainModel::new`].
|
||||
pub draft: bool,
|
||||
}
|
||||
|
||||
impl FinishParams {
|
||||
/// Parameters for a `w × h` render into `space`; `ev`/`air_pre` as in [`crate::Prepared`].
|
||||
pub fn new(input: FinishParamsInput<'_>) -> FinishParams {
|
||||
let FinishParamsInput { settings: s, frame, info, image_size: (w, h), px_per_long, air_pre, space } = input;
|
||||
let FinishParamsInput { settings: s, frame, info, image_size: (w, h), px_per_long, air_pre, space, draft } = input;
|
||||
let effects = s.section_enabled("effects");
|
||||
let (clar, tex, dehaze) = if effects {
|
||||
((s.effects.clarity / 100.0) as f32, (s.effects.texture / 100.0) as f32, (s.effects.dehaze / 100.0) as f32)
|
||||
@@ -286,7 +290,7 @@ impl FinishParams {
|
||||
&& frame.oh.is_finite()
|
||||
&& frame.ow.max(frame.oh) > 0.0
|
||||
&& out_to_norm.0.iter().all(|v| v.is_finite());
|
||||
let grain = if effects && finite_frame { GrainModel::new(s, px_per_long) } else { None };
|
||||
let grain = if effects && finite_frame { GrainModel::new(s, px_per_long, draft) } else { None };
|
||||
let calibration = s.section_enabled("calibration");
|
||||
let peak = s.hdr.peak();
|
||||
FinishParams {
|
||||
@@ -354,18 +358,20 @@ pub fn base_tone(s: &DevelopSettings, info: &SourceInfo, peak: f32) -> ToneMap {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn finish(
|
||||
p: &Prepared,
|
||||
s: &DevelopSettings,
|
||||
frame: &Frame,
|
||||
info: &SourceInfo,
|
||||
space: OutputSpace,
|
||||
display: Option<&crate::DisplaySpace>,
|
||||
proof: Option<crate::Proof>,
|
||||
) -> Rgba8 {
|
||||
pub(crate) fn finish(p: &Prepared, s: &DevelopSettings, frame: &Frame, info: &SourceInfo, req: &crate::RenderRequest) -> Rgba8 {
|
||||
let (space, display, proof) = (req.space, req.display.as_ref(), req.proof);
|
||||
let (w, h) = (p.img.width, p.img.height);
|
||||
let mut fp =
|
||||
FinishParams::new(FinishParamsInput { settings: s, frame, info, image_size: (w, h), px_per_long: p.px_per_long, air_pre: p.air, space });
|
||||
let draft = req.quality == crate::Quality::Draft;
|
||||
let mut fp = FinishParams::new(FinishParamsInput {
|
||||
settings: s,
|
||||
frame,
|
||||
info,
|
||||
image_size: (w, h),
|
||||
px_per_long: p.px_per_long,
|
||||
air_pre: p.air,
|
||||
space,
|
||||
draft,
|
||||
});
|
||||
fp.proof = proof.map(|pr| pr.params(space));
|
||||
if let Some(d) = display {
|
||||
fp.for_display(d, proof);
|
||||
@@ -382,19 +388,21 @@ pub(crate) fn finish(
|
||||
}
|
||||
|
||||
/// [`finish`] into 16-bit display-encoded or 32-bit float linear samples (output primaries).
|
||||
pub(crate) fn finish_deep(
|
||||
p: &Prepared,
|
||||
s: &DevelopSettings,
|
||||
frame: &Frame,
|
||||
info: &SourceInfo,
|
||||
space: OutputSpace,
|
||||
depth: OutputDepth,
|
||||
proof: Option<crate::Proof>,
|
||||
) -> DeepImage {
|
||||
pub(crate) fn finish_deep(p: &Prepared, s: &DevelopSettings, frame: &Frame, info: &SourceInfo, req: &crate::RenderRequest) -> DeepImage {
|
||||
use lightcraft_color::transfer::srgb_to_linear;
|
||||
let (space, depth, proof) = (req.space, req.depth, req.proof);
|
||||
let (w, h) = (p.img.width, p.img.height);
|
||||
let mut fp =
|
||||
FinishParams::new(FinishParamsInput { settings: s, frame, info, image_size: (w, h), px_per_long: p.px_per_long, air_pre: p.air, space });
|
||||
let draft = req.quality == crate::Quality::Draft;
|
||||
let mut fp = FinishParams::new(FinishParamsInput {
|
||||
settings: s,
|
||||
frame,
|
||||
info,
|
||||
image_size: (w, h),
|
||||
px_per_long: p.px_per_long,
|
||||
air_pre: p.air,
|
||||
space,
|
||||
draft,
|
||||
});
|
||||
fp.proof = proof.map(|pr| pr.params(space));
|
||||
let trc = fp.out_trc;
|
||||
let samples = match depth {
|
||||
|
||||
@@ -616,13 +616,13 @@ fn render_impl(src: Src<'_>, info: &SourceInfo, s: &DevelopSettings, req: &Rende
|
||||
c.put(CacheEntry { src: a.clone(), geo, sampled, lin: Some((lin_key, lin)), planes });
|
||||
}
|
||||
if req.depth != OutputDepth::U8 {
|
||||
let deep = finish::finish_deep(&prep, s, frame, info, req.space, req.depth, req.proof);
|
||||
let deep = finish::finish_deep(&prep, s, frame, info, req);
|
||||
let image = deep.to_rgba8();
|
||||
let histogram = Histogram::of_srgb8(&image);
|
||||
lap("finish (deep)", &mut t);
|
||||
return Rendered { image, histogram, deep: Some(deep) };
|
||||
}
|
||||
let image = finish::finish(&prep, s, frame, info, req.space, req.display.as_ref(), req.proof);
|
||||
let image = finish::finish(&prep, s, frame, info, req);
|
||||
lap("finish", &mut t);
|
||||
let cut = |i: &Rgba8| match plan.keep {
|
||||
Some(k) => i.crop(k.x, k.y, k.w, k.h),
|
||||
|
||||
@@ -46,7 +46,7 @@ fn half_width(v: &[f32], n: usize) -> f64 {
|
||||
}
|
||||
|
||||
fn tile_of(size: f64, roughness: f64) -> Arc<CrystalTile> {
|
||||
tile(CrystalLook::new(size, roughness), 7).expect("a tile")
|
||||
tile(CrystalLook::new(size, roughness), 7, true).expect("a tile")
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -146,13 +146,42 @@ fn hostile_settings_render_finite_or_no_grain() {
|
||||
#[test]
|
||||
fn seed_picks_the_pattern() {
|
||||
let look = CrystalLook::new(25.0, 50.0);
|
||||
let (a, b, c) = (tile(look, 1), tile(look, 1), tile(look, 2));
|
||||
let (a, b, c) = (tile(look, 1, true), tile(look, 1, true), tile(look, 2, true));
|
||||
let (Some(a), Some(b), Some(c)) = (a, b, c) else { panic!("tiles") };
|
||||
let (pa, pb, pc) = (patch(&a, REF_LONG, 64, 0), patch(&b, REF_LONG, 64, 0), patch(&c, REF_LONG, 64, 0));
|
||||
assert_eq!(pa, pb);
|
||||
assert_ne!(pa, pc);
|
||||
}
|
||||
|
||||
/// A draft (a Size or Roughness drag) doesn't wait for a new tile: the last tile of the seed stands
|
||||
/// in while the new one is drawn in the background, and then the drag gets it. A render that
|
||||
/// waits always gets the exact tile, as does a draft for a seed with no tile yet.
|
||||
#[test]
|
||||
fn a_drag_takes_the_last_tile_while_the_next_is_drawn() {
|
||||
// seeds of their own: other tests share the cache (which they may also evict from)
|
||||
let (seed, fresh) = (0x0d4a_0001, 0x0d4a_0002);
|
||||
let (a, b) = (CrystalLook::new(30.0, 50.0), CrystalLook::new(31.0, 50.0));
|
||||
let exact = |look: CrystalLook, seed: u32| patch(&CrystalTile::new(look, seed).expect("tile"), REF_LONG, 32, 0);
|
||||
let first = tile(a, seed, true).expect("tile");
|
||||
assert_eq!(first.look, a);
|
||||
let stand_in = tile(b, seed, false).expect("tile");
|
||||
assert_eq!(stand_in.look, a, "the draft waited for its tile");
|
||||
// the drag's next renders get the new tile once it is drawn
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
|
||||
let drawn = loop {
|
||||
let t = tile(b, seed, false).expect("tile");
|
||||
if t.look == b {
|
||||
break t;
|
||||
}
|
||||
assert!(std::time::Instant::now() < deadline, "the background tile never arrived");
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
};
|
||||
assert_eq!(patch(&drawn, REF_LONG, 32, 0), exact(b, seed));
|
||||
assert_eq!(patch(&tile(b, seed, true).expect("tile"), REF_LONG, 32, 0), exact(b, seed));
|
||||
// nothing drawn for this seed: nothing to stand in, the draft draws it
|
||||
assert_eq!(patch(&tile(a, fresh, false).expect("tile"), REF_LONG, 32, 0), exact(a, fresh));
|
||||
}
|
||||
|
||||
/// Grain width (autocorrelation half-width at mid grey, 6000 px) at Lightroom Classic's
|
||||
/// measured settings (open PR #1060's table); Size 0 is as fine as uncorrelated pixels get (0.5).
|
||||
#[test]
|
||||
|
||||
@@ -30,12 +30,12 @@ fn std(v: &[f64]) -> f64 {
|
||||
#[test]
|
||||
fn processes_before_v3_keep_the_value_noise() {
|
||||
for p in Process::ALL {
|
||||
let model = GrainModel::new(&on(p, 40.0), 2000.0);
|
||||
let model = GrainModel::new(&on(p, 40.0), 2000.0, false);
|
||||
match p {
|
||||
Process::V1 | Process::V2 => assert!(matches!(model, Some(GrainModel::Value(_))), "{p:?}"),
|
||||
Process::V3 => assert!(matches!(model, Some(GrainModel::Crystal(_))), "{p:?}"),
|
||||
}
|
||||
assert!(GrainModel::new(&on(p, 0.0), 2000.0).is_none(), "{p:?}: no grain at Amount 0");
|
||||
assert!(GrainModel::new(&on(p, 0.0), 2000.0, false).is_none(), "{p:?}: no grain at Amount 0");
|
||||
}
|
||||
let src = Rgb32f::filled(160, 120, [0.18; 3]);
|
||||
let (v2, v3) = (luma(&src, &on(Process::V2, 50.0), 160, 120), luma(&src, &on(Process::V3, 50.0), 160, 120));
|
||||
|
||||
+18
-5
@@ -97,10 +97,23 @@ curtain; #1060: −9.3). Fine detail under the grain is kept (detail gain
|
||||
## Performance
|
||||
|
||||
- **Drawing the emulsion** (per Size, Roughness and seed; cached, so Amount drags and re-renders
|
||||
draw nothing): every crystal is stamped as bit spans from a per-layer table of its rasterisation at
|
||||
16 × 16 sub-pixel phases, layers are counted in bit-sliced counters, and the tiles are drawn in
|
||||
parallel bands. 5–17 ms on an M2 Max (12 threads) at any setting (`tile_timing_report`).
|
||||
- **Per pixel:** two box sums, on the CPU and on the GPU; the tables (12 MB) follow the finish
|
||||
kernel's other tables in its `aux` buffer.
|
||||
draw nothing): every crystal is stamped from a per-layer table of its rasterisation at 16 × 16
|
||||
sub-pixel phases, as one 64-bit mask per row (a fixed number of rows per layer, those outside a
|
||||
band landing in scratch rows around it, so a crystal costs no branch per row), layers are counted
|
||||
in bit-sliced counters, and the tiles are drawn in parallel bands. 5–17 ms on an M2 Max (12
|
||||
threads; measured before the row masks), 15–33 ms on a Ryzen 5 7545U (6 cores, 12 threads; 10–20 %
|
||||
less than before them) at any setting (`tile_timing_report`).
|
||||
- **Drags.** A draft render (a slider drag) doesn't wait for a tile it hasn't got: the last tile
|
||||
drawn for the photo's seed stands in while the new one is drawn in the background, on a pool of
|
||||
half the cores so the drag's renders don't queue behind it, and the next render takes it. The
|
||||
full-quality render when the drag ends waits for the exact tile. A Size drag on the Ryzen with its
|
||||
Radeon 740M (GPU, 2.5 MP preview): 13–14 ms a frame instead of 62–66 ms. (On wasm, without
|
||||
threads, drafts wait.)
|
||||
- **Per pixel:** two box sums, on the CPU and on the GPU. The tables (12 MB) stay on the GPU
|
||||
between renders, for the last tile used (`Gpu::grain_tables`), and are copied after the finish
|
||||
kernel's other tables in its `aux` buffer on the GPU: an Amount drag uploads nothing. On the
|
||||
Radeon 740M an Amount drag frame (2.5 MP) went from 16.9 to 11–15 ms (no grain: 8 ms).
|
||||
- **24 MP NEF → PNG** (`lightcraft-cli render`, M2 Max, median of three): no grain 1.09 s, grain
|
||||
50 / 25 / 50 1.09 s on the GPU; 1.33 s and 1.49 s CPU-only (the finish stage 0.26 → 0.42 s).
|
||||
- **24 MP NEF → PNG on the Ryzen 5 7545U / Radeon 740M** (median of three): no grain 2.07 s, grain
|
||||
50 / 25 / 50 2.09 s on the GPU; 2.69 s and 2.87 s CPU-only.
|
||||
Reference in new issue
Block a user