diff --git a/crates/compose/src/curvature_sizes.rs b/crates/compose/src/curvature_sizes.rs index c2dfe755..7b6014e0 100644 --- a/crates/compose/src/curvature_sizes.rs +++ b/crates/compose/src/curvature_sizes.rs @@ -1,5 +1,6 @@ //! The baked curvature map at the detail sizes of curvature generators, built once per map and layout. +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, Weak}; use rayon::prelude::*; @@ -11,52 +12,55 @@ use crate::eval::{Inputs, blur}; /// The curvature map padded past its UV islands and blurred at each size of [`CurvatureDetail::SIZES`] after the first. pub struct CurvatureSizes { - pub levels: Vec, + /// One per blurred size, built once a generator gives that size a weight above 0. + pub levels: Vec>>, } -/// Built sizes by the curvature data they come from, the working texture size, the UV tile block and the tiles' scales. -type CacheEntry = (Weak>, (u32, u32), (u32, u32), BlockScales, Arc); +/// The bake map size, its UV tile block and the working texture size a cache entry was built for. +type CacheKey = ((u32, u32), (u32, u32), (u32, u32)); + +/// Built sizes by the curvature data they come from, their layout and the tiles' scales. +type CacheEntry = (Weak>, CacheKey, BlockScales, Arc); static CACHE: Mutex> = Mutex::new(Vec::new()); impl CurvatureSizes { - /// The sizes of the texture set `inp` composites (None without a baked curvature map). - pub fn of(inp: &Inputs) -> Option> { + /// The sizes of the texture set `inp` composites, holding at least those `needed` marks (one flag per blurred size); None without a baked curvature map or a needed size. + pub fn of(inp: &Inputs, needed: &[bool]) -> Option> { let curvature = inp.baked.maps.get(&BakedMap::Curvature)?; let (width, height) = (inp.baked.resolution, inp.baked.height(BakedMap::Curvature)); + if !needed.contains(&true) || width == 0 || height == 0 { + return None; + } + let grid = inp.project.texture_set(inp.ts).ok().and_then(|set| set.tile_grid()); let block = grid.map_or((width, height), |grid| (width / grid.cols.max(1), height / grid.rows.max(1))); - let working_size = (inp.gbuf.width, inp.gbuf.height); - - let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - cache.retain(|(source, ..)| source.strong_count() > 0); - let same_source = |source: &Weak>| source.upgrade().is_some_and(|data| Arc::ptr_eq(&data, curvature)); - let cached = cache.iter().find(|(source, cached_size, cached_block, cached_scales, _)| { - same_source(source) && *cached_size == working_size && *cached_block == block && *cached_scales == inp.block_scales - }); - if let Some((.., sizes)) = cached { + let key = ((width, height), block, (inp.gbuf.width, inp.gbuf.height)); + let built = cached(curvature, key, &inp.block_scales); + if let Some(sizes) = built.as_ref().filter(|sizes| sizes.holds(needed)) { return Some(sizes.clone()); } - // Covered working texels mark where they land in the bake atlas - let mut covered = vec![false; (width * height) as usize]; - for texel in (0..working_size.0 * working_size.1).filter(|texel| inp.gbuf.covered(*texel as usize)) { - let uv = [((texel % working_size.0) as f32 + 0.5) / working_size.0 as f32, ((texel / working_size.0) as f32 + 0.5) / working_size.1 as f32]; - if let Some(baked_uv) = inp.block_scales.bake_uv(uv, working_size) { - let (baked_x, baked_y) = ((baked_uv[0] * width as f32) as u32, (baked_uv[1] * height as f32) as u32); - if let Some(slot) = covered.get_mut((baked_y.min(height - 1) * width + baked_x.min(width - 1)) as usize) { - *slot = true; - } - } - } - - let sizes = Arc::new(CurvatureSizes::build(curvature, (width, height), &covered, block)); - cache.push((Arc::downgrade(curvature), working_size, block, inp.block_scales.clone(), sizes.clone())); - Some(sizes) + // Built without the cache locked: the build runs parallel work, and a thread waiting on it may composite a tile that asks the cache again + let covered = covered_texels(inp, (width, height)); + let sizes = CurvatureSizes::build(curvature, (width, height), &covered, block, needed, built.as_deref()); + Some(store(curvature, key, &inp.block_scales, sizes)) } - /// Pad `curvature` from its `covered` texels within each UV tile `block`, then blur each block at every size. - fn build(curvature: &[f32], (width, height): (u32, u32), covered: &[bool], block: (u32, u32)) -> CurvatureSizes { + /// Whether every size `needed` marks is built. + fn holds(&self, needed: &[bool]) -> bool { + needed.iter().zip(&self.levels).all(|(needs, level)| !needs || level.is_some()) + } + + /// Pad `curvature` from its `covered` texels within each UV tile `block`, then blur each block at the sizes `needed` marks; sizes already in `built` are kept as they are. + fn build( + curvature: &[f32], + (width, height): (u32, u32), + covered: &[bool], + block: (u32, u32), + needed: &[bool], + built: Option<&CurvatureSizes>, + ) -> CurvatureSizes { let padding = DilationMap::in_rectangular_blocks(covered, width, height, None, block); let deviation: Vec = padding.src.par_iter().map(|&source| if source == NONE { 0.0 } else { curvature.get(source as usize).copied().unwrap_or(0.5) - 0.5 }).collect(); @@ -65,7 +69,15 @@ impl CurvatureSizes { let levels = CurvatureDetail::SIZES .iter() .skip(1) - .map(|size| { + .enumerate() + .map(|(level, size)| { + if let Some(existing) = built.and_then(|sizes| sizes.levels.get(level)).and_then(Option::clone) { + return Some(existing); + } + if !needed.get(level).copied().unwrap_or(false) { + return None; + } + // Sizes are texels at 2K; a blur this wide holds nothing finer than half its radius, so it is stored that much coarser let radius = (size * block_width as f32 / 2048.0).round().max(1.0) as u32; let step = (radius / 2).max(1).next_power_of_two(); @@ -77,13 +89,55 @@ impl CurvatureSizes { blur_block(&mut blurred, width, region, radius); } } - coarsen(&blurred, (width, height), step) + Some(Arc::new(coarsen(&blurred, (width, height), step))) }) .collect(); CurvatureSizes { levels } } } +/// The cached sizes of `curvature` for layout `key` and tile `scales`, if any. +fn cached(curvature: &Arc>, key: CacheKey, scales: &BlockScales) -> Option> { + let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + cache.retain(|(source, ..)| source.strong_count() > 0); + cache.iter().find(|entry| is_entry_for(entry, curvature, key, scales)).map(|(.., sizes)| sizes.clone()) +} + +/// Cache `sizes`, keeping the sizes another thread cached meanwhile, and return what the cache holds now. +fn store(curvature: &Arc>, key: CacheKey, scales: &BlockScales, sizes: CurvatureSizes) -> Arc { + let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let Some((.., cached_sizes)) = cache.iter_mut().find(|entry| is_entry_for(entry, curvature, key, scales)) else { + let sizes = Arc::new(sizes); + cache.push((Arc::downgrade(curvature), key, scales.clone(), sizes.clone())); + return sizes; + }; + + let levels = cached_sizes.levels.iter().zip(sizes.levels).map(|(cached, built)| cached.clone().or(built)).collect(); + *cached_sizes = Arc::new(CurvatureSizes { levels }); + cached_sizes.clone() +} + +/// Whether cache `entry` holds the sizes of `curvature` for layout `key` and tile `scales`. +fn is_entry_for((source, cached_key, cached_scales, _): &CacheEntry, curvature: &Arc>, key: CacheKey, scales: &BlockScales) -> bool { + source.upgrade().is_some_and(|data| Arc::ptr_eq(&data, curvature)) && *cached_key == key && cached_scales == scales +} + +/// The bake atlas texels (`width × height`) that the covered working texels of `inp` land on. +fn covered_texels(inp: &Inputs, (width, height): (u32, u32)) -> Vec { + let working_size = (inp.gbuf.width, inp.gbuf.height); + let covered: Vec = (0..width * height).map(|_| AtomicBool::new(false)).collect(); + (0..working_size.0 * working_size.1).into_par_iter().filter(|texel| inp.gbuf.covered(*texel as usize)).for_each(|texel| { + let uv = [((texel % working_size.0) as f32 + 0.5) / working_size.0 as f32, ((texel / working_size.0) as f32 + 0.5) / working_size.1 as f32]; + if let Some(baked_uv) = inp.block_scales.bake_uv(uv, working_size) { + let (baked_x, baked_y) = ((baked_uv[0] * width as f32) as u32, (baked_uv[1] * height as f32) as u32); + if let Some(slot) = covered.get((baked_y.min(height - 1) * width + baked_x.min(width - 1)) as usize) { + slot.store(true, Ordering::Relaxed); + } + } + }); + covered.into_iter().map(AtomicBool::into_inner).collect() +} + /// Blur the `(x0, y0, w, h)` block of `data` (`width` texels per row) in place, reading nothing outside it. fn blur_block(data: &mut [f32], width: u32, (x0, y0, w, h): (u32, u32, u32, u32), radius: u32) { let mut block: Vec = @@ -122,12 +176,40 @@ mod tests { #[test] fn padding_keeps_an_island_border_from_reading_flat() { - let left_half = |texel: u32| texel % 64 < 32; - let curvature: Vec = (0..64 * 64).map(|texel| if left_half(texel) { 1.0 } else { 0.0 }).collect(); - let covered: Vec = (0..64 * 64).map(left_half).collect(); - let sizes = CurvatureSizes::build(&curvature, (64, 64), &covered, (64, 64)); - for level in &sizes.levels { - assert!((level.sample(31, 32) - 0.5).abs() < 0.01, "the border keeps the island's curvature, not the empty texels beside it"); + let map_size: u32 = 64; + let left_half = |texel: u32| texel % map_size < map_size / 2; + let curvature: Vec = (0..map_size * map_size).map(|texel| if left_half(texel) { 1.0 } else { 0.0 }).collect(); + let covered: Vec = (0..map_size * map_size).map(left_half).collect(); + let shape = (map_size, map_size); + let sizes = CurvatureSizes::build(&curvature, shape, &covered, shape, &[true; CurvatureDetail::BLURRED_SIZES], None); + + // The last covered column, halfway down + let (border_x, border_y) = (map_size / 2 - 1, map_size / 2); + for level in sizes.levels.iter().flatten() { + assert!((level.sample(border_x, border_y) - 0.5).abs() < 0.01, "the border keeps the island's curvature, not the empty texels beside it"); + } + } + + #[test] + fn sizes_built_on_demand_match_a_full_build() { + let map_size: u32 = 64; + let curvature: Vec = + (0..map_size * map_size).map(|texel| 0.5 + 0.4 * ((texel % map_size) as f32 * 0.3).sin() * ((texel / map_size) as f32 * 0.2).cos()).collect(); + let covered = vec![true; (map_size * map_size) as usize]; + let shape = (map_size, map_size); + let all = vec![true; CurvatureDetail::BLURRED_SIZES]; + let full = CurvatureSizes::build(&curvature, shape, &covered, shape, &all, None); + + let even: Vec = (0..all.len()).map(|level| level % 2 == 0).collect(); + let partial = CurvatureSizes::build(&curvature, shape, &covered, shape, &even, None); + assert!(partial.levels.iter().zip(&even).all(|(level, needed)| level.is_some() == *needed), "only the needed sizes are built"); + + let completed = CurvatureSizes::build(&curvature, shape, &covered, shape, &all, Some(&partial)); + for ((built, expected), earlier) in completed.levels.iter().zip(&full.levels).zip(&partial.levels) { + assert_eq!(built.as_ref().map(|level| &level.deviation), expected.as_ref().map(|level| &level.deviation), "the same values either way"); + if let (Some(built), Some(earlier)) = (built, earlier) { + assert!(Arc::ptr_eq(built, earlier), "sizes already built are kept, not rebuilt"); + } } } } diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 1eb29882..e8fd391b 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -771,28 +771,48 @@ fn fields_of(inp: &Inputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32 if tiles.is_empty() || inp.gbuf.width == 0 { return out; } - let res = inp.gbuf.width; + + let working_width = inp.gbuf.width; let mut order = Vec::new(); draw_order(inp.project, list, 0, &mut order); + prepare_curvature_sizes(inp, &order); + for id in order { let Some(layer) = inp.project.content_layer(id) else { continue }; - if let Some(m) = layer_mask(inp.project, id).filter(|m| m.enabled && neighbourhood(&m.effects, res).is_some()) - && let Some(f) = field(inp, channels, &out, id, Job::Mask(m), tiles) + + if let Some(mask) = layer_mask(inp.project, id).filter(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some()) + && let Some(filtered) = field(inp, channels, &out, id, Job::Mask(mask), tiles) { - out.insert(FieldKey::Mask(id), f); + out.insert(FieldKey::Mask(id), filtered); } - if layer.is_group() || neighbourhood(&layer.content_effects, res).is_none() { + + if layer.is_group() || neighbourhood(&layer.content_effects, working_width).is_none() { continue; } - for ch in channels.iter().filter(|c| layer.channels.contains_key(c)) { - if let Some(f) = field(inp, channels, &out, id, Job::Content(*ch), tiles) { - out.insert(FieldKey::Content(id, *ch), f); + for channel in channels.iter().filter(|channel| layer.channels.contains_key(channel)) { + if let Some(filtered) = field(inp, channels, &out, id, Job::Content(*channel), tiles) { + out.insert(FieldKey::Content(id, *channel), filtered); } } } out } +/// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel. +fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { + let mut needed = [false; CurvatureDetail::BLURRED_SIZES]; + let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible)); + let masks = visible.filter_map(|id| layer_mask(inp.project, *id)).filter(|mask| mask.enabled); + for effect in masks.flat_map(|mask| &mask.effects).filter(|effect| effect.visible) { + if let EffectKind::Generator(Generator { detail: Some(detail), .. }) = &effect.kind { + for (slot, in_use) in needed.iter_mut().zip(detail.blurred_sizes_in_use()) { + *slot |= in_use; + } + } + } + CurvatureSizes::of(inp, &needed); +} + struct Node<'a> { id: LayerId, content: Content<'a>, @@ -810,7 +830,7 @@ struct Node<'a> { /// Plans of the visible effects of a stack: mask effects (`channel` None) or the content /// effects of one channel (paint effects then read that channel's pixels). -fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tx: u32, ty: u32, channel: Option) -> Vec> { +fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y: u32, channel: Option) -> Vec> { effects .iter() .filter(|effect| effect.visible) @@ -819,14 +839,17 @@ fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tx: u32, ty: u32, c Some(channel) => (inp.pixels.layer(effect.id, channel), PaintTarget::Layer(effect.id)), None => (inp.pixels.masks.get(&effect.id), PaintTarget::Mask(effect.id)), }; - let reads_detail = matches!(&effect.kind, EffectKind::Generator(generator) if generator.detail.is_some()); + let curvature_sizes = match &effect.kind { + EffectKind::Generator(Generator { detail: Some(detail), .. }) => CurvatureSizes::of(inp, &detail.blurred_sizes_in_use()), + _ => None, + }; EffectPlan { kind: &effect.kind, blend: effect.blend, opacity: effect.opacity, - data: if effect.kind.painted() { tile_of(inp, image, tx, ty, channel) } else { None }, + data: if effect.kind.painted() { tile_of(inp, image, tile_x, tile_y, channel) } else { None }, preview: previews(inp, target), - curvature_sizes: if reads_detail { CurvatureSizes::of(inp) } else { None }, + curvature_sizes, } }) .collect() @@ -1215,7 +1238,9 @@ impl<'a, 'b> Texel<'a, 'b> { let baked_size = (self.inp.baked.resolution, self.inp.baked.height(BakedMap::Curvature)); let (baked_x, baked_y) = ((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32); - let blurred = |index: usize| curvature_sizes.and_then(|sizes| sizes.levels.get(index)).map_or(0.0, |level| level.sample(baked_x, baked_y)); + let blurred = |index: usize| { + curvature_sizes.and_then(|sizes| sizes.levels.get(index)).and_then(Option::as_deref).map_or(0.0, |level| level.sample(baked_x, baked_y)) + }; let (mut edges, mut cavities) = (0.0f32, 0.0f32); for (index, (size, weight)) in CurvatureDetail::SIZES.iter().zip(detail.weights).enumerate() { let deviation = if index == 0 { curvature - 0.5 } else { blurred(index - 1) }; diff --git a/crates/core/src/layer/curvature_detail.rs b/crates/core/src/layer/curvature_detail.rs index 826b9823..75c9d36a 100644 --- a/crates/core/src/layer/curvature_detail.rs +++ b/crates/core/src/layer/curvature_detail.rs @@ -19,6 +19,14 @@ impl CurvatureDetail { /// Mostly the finer sizes, tuned the same way: worn edges are thin lines. pub const EDGE_WEIGHTS: [f32; 7] = [1.0, 0.8, 0.5, 0.25, 0.1, 0.0, 0.0]; + + /// How many sizes are blurred copies of the map (all but the first). + pub const BLURRED_SIZES: usize = CurvatureDetail::SIZES.len() - 1; + + /// Which blurred sizes this detail reads: those with a weight above 0. + pub fn blurred_sizes_in_use(&self) -> [bool; CurvatureDetail::BLURRED_SIZES] { + std::array::from_fn(|blurred| self.weights.get(blurred + 1).is_some_and(|weight| *weight > 0.0)) + } } impl Default for CurvatureDetail {