LR-EDIT-EFFECTS-GRAIN: review fixes (one draw per missed tile, table copies read back)

- A render that misses a crystal tile another thread is drawing (another render, or the
  background draw of a drag) waits for it instead of drawing it again; the marker is cleared and
  waiters woken on success and failure. Pool workers still draw for themselves: blocked, one
  could hold up part of the very drawing it waits for. Regression test.
- The grain-table replacement test copies into a destination per render and reads both back
  against their tile's tables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Jeremy Hooke
2026-11-03 13:37:43 +11:00
co-authored by Claude Opus 5.5
parent b908538a16
commit 2038ebc760
3 changed files with 89 additions and 10 deletions
+8 -4
View File
@@ -1079,15 +1079,19 @@ mod tests {
let (Some(a), Some(b)) = (CrystalTile::new(look, 0x7ab1_0001), CrystalTile::new(look, 0x7ab1_0002)) else { panic!("tiles") };
let (a, b) = (std::sync::Arc::new(a), std::sync::Arc::new(b));
let len: usize = a.sats.iter().map(Vec::len).sum();
let dst = g.buffer(len);
let (dst_a, dst_b) = (g.buffer(len), g.buffer(len));
let mut first = g.encoder();
let held = g.grain_tables(&mut first, &a, &dst, 0).expect("tables copied");
let held = g.grain_tables(&mut first, &a, &dst_a, 0).expect("tables copied");
// another render replaces the resident tables before `first` is submitted
let mut second = g.encoder();
assert!(g.grain_tables(&mut second, &b, &dst, 0).is_some());
assert!(g.grain_tables(&mut second, &b, &dst_b, 0).is_some());
let next = g.buffer(len);
assert!(next.raw() != held.raw(), "the replaced tables went back to the pool before their copy was submitted");
g.submit([first.finish(), second.finish()]);
g.submit([first.finish()]);
// each render read its own tile's tables
let tables = |t: &lightcraft_pipeline::crystal::CrystalTile| t.sats.concat();
assert!(g.finish_and_read::<f32>(second, &dst_a, len) == tables(&a), "the first render copied other tables");
assert!(g.finish_and_read::<f32>(g.encoder(), &dst_b, len) == tables(&b), "the second render copied other tables");
}
/// A GPU retired by another failure (a validation error) keeps a live device: its buffers are
+64 -6
View File
@@ -29,7 +29,7 @@
//! GPU kernel (`finish.wgsl`, which reads the same tables).
use std::f64::consts::TAU;
use std::sync::{Arc, Mutex, PoisonError};
use std::sync::{Arc, Condvar, Mutex, PoisonError};
use lightcraft_color::transfer::srgb_to_linear;
use lightcraft_develop::Grain;
@@ -810,6 +810,11 @@ pub struct CrystalGrain {
}
type Key = (u64, u64, u32);
/// The cache key of the tile of `look` and `seed`.
fn key_of(look: CrystalLook, seed: u32) -> Key {
(look.width.to_bits(), look.spread.to_bits() ^ (look.layers as u64).rotate_left(40), seed)
}
/// Recently drawn tiles (the most recent last).
type Cache = Mutex<Vec<(Key, Arc<CrystalTile>)>>;
static TILES: Cache = Mutex::new(Vec::new());
@@ -817,6 +822,37 @@ static TILES: Cache = Mutex::new(Vec::new());
/// The tile being drawn in the background for a drag ([`tile`]): one at a time.
static DRAWING: Mutex<Option<Key>> = Mutex::new(None);
/// The tiles being drawn, by cache and key, and the condition their drawers signal when done: a
/// render that misses a tile another is drawing waits for it rather than drawing it again.
static IN_FLIGHT: Mutex<Vec<(usize, Key)>> = Mutex::new(Vec::new());
static DRAWN: Condvar = Condvar::new();
/// Marks a tile drawn (or failed) when dropped and wakes the renders waiting for it.
struct Drawing((usize, Key));
impl Drop for Drawing {
fn drop(&mut self) {
IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner).retain(|d| *d != self.0);
DRAWN.notify_all();
}
}
/// Registers the tile of `id` as being drawn, or `None` if another thread is drawing it.
fn start_drawing(id: (usize, Key)) -> Option<Drawing> {
let mut busy = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner);
if busy.contains(&id) {
return None;
}
busy.push(id);
Some(Drawing(id))
}
/// The tile of `key` in `cache`.
fn cached(cache: &Cache, key: Key) -> Option<Arc<CrystalTile>> {
let tiles = cache.lock().unwrap_or_else(PoisonError::into_inner);
tiles.iter().find(|(k, _)| *k == key).map(|(_, t)| t.clone())
}
/// The tile of `look` and `seed`, drawn or from the cache. Unless `wait`, a tile not drawn yet
/// is drawn in the background and the last one drawn for `seed` stands in for it meanwhile: a
/// Size or Roughness drag doesn't wait for every step's tile (tens of milliseconds on a slow
@@ -827,7 +863,7 @@ fn tile(look: CrystalLook, seed: u32, wait: bool) -> Option<Arc<CrystalTile>> {
/// [`tile`] with the tiles cached in `cache` (a test's own, which other tests can't evict from).
fn tile_in(cache: &'static Cache, look: CrystalLook, seed: u32, wait: bool) -> Option<Arc<CrystalTile>> {
let key = (look.width.to_bits(), look.spread.to_bits() ^ (look.layers as u64).rotate_left(40), seed);
let key = key_of(look, seed);
{
let tiles = cache.lock().unwrap_or_else(PoisonError::into_inner);
if let Some((_, t)) = tiles.iter().find(|(k, _)| *k == key) {
@@ -844,6 +880,20 @@ fn tile_in(cache: &'static Cache, look: CrystalLook, seed: u32, wait: bool) -> O
return Some(stand_in);
}
}
let id = (std::ptr::from_ref(cache) as usize, key);
// a pool worker draws the tile itself: blocked, it could hold up the drawing it waits for
// (its stack may carry a part of that drawing's parallel work); wasm has no other threads
if !cfg!(target_arch = "wasm32") && rayon::current_thread_index().is_none() {
let mut busy = IN_FLIGHT.lock().unwrap_or_else(PoisonError::into_inner);
while busy.contains(&id) {
busy = DRAWN.wait(busy).unwrap_or_else(PoisonError::into_inner);
}
drop(busy);
if let Some(t) = cached(cache, key) {
return Some(t);
}
}
let _drawing = start_drawing(id);
let t = Arc::new(CrystalTile::new(look, seed)?);
keep(cache, key, t.clone());
Some(t)
@@ -862,19 +912,27 @@ fn keep(cache: &Cache, key: Key, t: Arc<CrystalTile>) {
/// Draws the tile of `key` on the thread pool unless another is being drawn (the next render
/// asks again for what it needs then).
fn draw_in_background(cache: &'static Cache, key: Key, look: CrystalLook, seed: u32) {
{
let marker = {
let mut drawing = DRAWING.lock().unwrap_or_else(PoisonError::into_inner);
if drawing.is_some() {
return;
}
// (`None`: a render is drawing it already)
let Some(marker) = start_drawing((std::ptr::from_ref(cache) as usize, key)) else { return };
*drawing = Some(key);
}
let draw = move || {
marker
};
spawn_in_background(move || {
if let Some(t) = CrystalTile::new(look, seed) {
keep(cache, key, Arc::new(t));
}
drop(marker);
*DRAWING.lock().unwrap_or_else(PoisonError::into_inner) = None;
};
});
}
/// Runs `draw` on the background pool.
fn spawn_in_background(draw: impl FnOnce() + Send + 'static) {
// on a pool of its own: the renders of the drag don't queue behind its parallel bands
match background_pool() {
Some(pool) => pool.spawn(draw),
+17
View File
@@ -184,6 +184,23 @@ fn a_drag_takes_the_last_tile_while_the_next_is_drawn() {
assert_eq!(patch(&tile(a, fresh, false).expect("tile"), REF_LONG, 32, 0), exact(a, fresh));
}
/// A render that misses a tile another thread is drawing waits for that tile rather than drawing
/// it a second time.
#[test]
fn a_render_waits_for_a_tile_being_drawn() {
static OWN: Cache = Mutex::new(Vec::new());
let (look, seed) = (CrystalLook::new(40.0, 50.0), 0x0d4a_0003);
let key = key_of(look, seed);
let marker = start_drawing((std::ptr::from_ref(&OWN) as usize, key)).expect("not drawn yet");
let render = std::thread::spawn(move || tile_in(&OWN, look, seed, true));
std::thread::sleep(std::time::Duration::from_millis(200));
let drawn = Arc::new(CrystalTile::new(look, seed).expect("tile"));
keep(&OWN, key, drawn.clone());
drop(marker);
let got = render.join().expect("render thread").expect("tile");
assert!(Arc::ptr_eq(&got, &drawn), "the render drew the tile again");
}
/// Grain width (autocorrelation half-width at mid grey, 6000 px) at Lightroom Classic's
/// measured settings (open PR #1060's table); Size 0 is as fine as uncorrelated pixels get (0.5).
#[test]