Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Compose: effect maps that don't fit in the effect cache are built over the render rect, not rebuilt whole on every render (#8330)

Ian Swope0edfe05f2c60
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index 2ed1873a9..3bf93c4c9 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -399,6 +399,7 @@ pub fn render_layer(layer: &Layer, rect: Rect) -> Buffer {
vector_masks: RenderVectorMasks::default(),
fx_maps: Default::default(),
fx_clip: Default::default(),
+ fx_over_budget: false,
tone_luts: prepare_tones(std::slice::from_ref(layer), 0),
doc: None,
layer_keys: Default::default(),
@@ -749,6 +750,9 @@ struct Ctx<'a> {
fx_maps: std::sync::Mutex<std::collections::HashMap<u64, (std::sync::Arc<effects::FxMaps>, bool)>>,
/// The rectangle being rendered (a band of [`render_bands`]); see [`effect_region`].
fx_clip: std::sync::Mutex<Option<Rect>>,
+ /// The whole-region effect maps of this render's layers wouldn't fit in the effect cache
+ /// together ([`fx_over_budget`]), so local ones are clipped to the render rect (#8330).
+ fx_over_budget: bool,
/// The document being rendered (deep knockouts reveal its Background); `None` for a lone layer.
doc: Option<&'a Document>,
/// Effect-map identities of this render's document layers (see [`LayerKeys`]).
@@ -820,6 +824,7 @@ impl<'a> Ctx<'a> {
vector_masks: RenderVectorMasks::default(),
fx_maps: Default::default(),
fx_clip: Default::default(),
+ fx_over_budget: fx_over_budget(&doc.layers, doc.bounds()),
layer_keys: Default::default(),
tone_luts: prepare_tones(&doc.layers, 0),
}
@@ -1973,7 +1978,9 @@ fn fx_cache() -> &'static std::sync::Mutex<FxCache> {
/// 1920 × 103675 webtoon page each such layer's maps took about 2.4 GB, and a render held them for
/// every layer at once (60 GB with 25 stroked type layers, #1909). When its effects are local
/// ([`effects::maps_are_local`]), such a layer's maps are built over the render rectangle padded
-/// by twice the effect reach instead, which gives the same pixels there. Only when `rect`, what
+/// by twice the effect reach instead, which gives the same pixels there. So are any layer's local
+/// maps when the render's whole-region maps wouldn't fit in the effect cache ([`fx_over_budget`]).
+/// Only when `rect`, what
/// the caller composites the layer over, lies within the render rectangle: a group's effect shape
/// (or anything else rendering children over a wider area) gets the whole region.
fn effect_region(layer: &Layer, rect: Rect, cx: &Ctx) -> (Rect, bool) {
@@ -1981,7 +1988,7 @@ fn effect_region(layer: &Layer, rect: Rect, cx: &Ctx) -> (Rect, bool) {
let region = effect_source_bounds(layer, cx.canvas).inflate(m).intersect(&cx.canvas.inflate(m));
let clip = *cx.fx_clip.lock().unwrap_or_else(|e| e.into_inner());
match clip {
- Some(c) if c.contains_rect(&rect) && advanced::shapeless(layer) && effects::maps_are_local(layer) => {
+ Some(c) if c.contains_rect(&rect) && (advanced::shapeless(layer) || cx.fx_over_budget) && effects::maps_are_local(layer) => {
let part = region.intersect(&c.inflate(m.saturating_mul(2)));
(part, part != region)
}
@@ -1989,6 +1996,38 @@ fn effect_region(layer: &Layer, rect: Rect, cx: &Ctx) -> (Rect, bool) {
}
}
+/// Whether the effect maps of the visible layers of `layers` (groups included), each over its
+/// whole region, would take more than the effect cache budget together. A render needs all of
+/// them, so when they don't fit, building one evicts the next one needed and every render builds
+/// them all again, seconds even for a small rect (#8330). Counted as [`effects::FxMaps::bytes`]
+/// counts them, with only the shape and one map per enabled effect: a lower bound.
+fn fx_over_budget(layers: &[Layer], canvas: Rect) -> bool {
+ fx_region_bytes(layers, canvas) > effect_cache_budget() as u64
+}
+
+/// The lower bound [`fx_over_budget`] compares with the budget.
+fn fx_region_bytes(layers: &[Layer], canvas: Rect) -> u64 {
+ fn bytes(layers: &[Layer], canvas: Rect, depth: u32) -> u64 {
+ let mut total = 0u64;
+ for l in layers.iter().filter(|l| l.visible) {
+ if effects::has_effects(l) {
+ let m = effects::margin(l);
+ let region = effect_source_bounds(l, canvas).inflate(m).intersect(&canvas.inflate(m));
+ let maps = 1 + l.effects.items.iter().filter(|e| e.enabled()).count() as u64;
+ let px = u64::from(region.width()) * u64::from(region.height());
+ total = total.saturating_add(maps.saturating_mul(px).saturating_mul(4));
+ }
+ if let LayerContent::Group(g) = &l.content
+ && depth < PREPARE_DEPTH
+ {
+ total = total.saturating_add(bytes(&g.children, canvas, depth + 1));
+ }
+ }
+ total
+ }
+ bytes(layers, canvas, 0)
+}
+
/// The layer's effect maps over its region (layer bounds grown by the effect reach, within the
/// canvas grown likewise; see [`effect_region`]), built once per layer state and shared by every
/// tile. `rect` is what the caller composites the layer over (see [`effect_region`]).
diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs
index 99823457f..707ea98c8 100644
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@ -1665,6 +1665,105 @@ fn shapeless_effect_maps_cover_only_the_band_being_rendered() {
);
}
+/// [`shapeless_fx_doc`] with Transparency Shapes Layer back on everywhere: ordinary layers, whose
+/// effect regions are their own bounds grown by the effects' reach.
+fn ordinary_fx_doc(depth: SampleType) -> Document {
+ fn shaped(layers: &mut [Layer]) {
+ for l in layers {
+ l.advanced.transparency_shapes = true;
+ if let LayerContent::Group(g) = &mut l.content {
+ shaped(&mut g.children);
+ }
+ }
+ }
+ let mut d = shapeless_fx_doc(depth);
+ shaped(&mut d.layers);
+ d
+}
+
+#[test]
+fn effect_maps_over_the_cache_budget_are_built_over_the_render_rect() {
+ // #8330: an ordinary layer's maps cover its whole region, so on a large document a render's
+ // layers can need more than the effect cache holds; building one then evicts the next one
+ // needed, and every render, however small, builds them all again. Over the budget, local maps
+ // are built over the render rect (plus twice the reach), as a shapeless layer's are (#1909).
+ let d = ordinary_fx_doc(SampleType::U8);
+ let patterns = pattern::PreparedPatterns::new(&d.patterns, pattern::PREPARED_PATTERN_BYTES);
+ // A row through fx8 (pixels at y 552..570, an outside stroke and an inner glow).
+ let band = Rect::new(0, 561, 48, 562);
+ let mut cx = Ctx::for_doc(&d, &patterns);
+ assert!(!cx.fx_over_budget, "a small document fits");
+ let l = &d.layers[9];
+ let whole = effect_region(l, band, &cx);
+ cx.set_fx_clip(band);
+ assert_eq!(effect_region(l, band, &cx), whole, "under the budget: the whole region");
+ cx.fx_over_budget = true;
+ let (part, clipped) = effect_region(l, band, &cx);
+ assert_eq!(part, whole.0.intersect(&band.inflate(2 * effects::margin(l))));
+ assert!(clipped && part.height() < whole.0.height(), "{part:?} vs {:?}", whole.0);
+ let built = effect_maps(l, band, &cx).bytes();
+ cx.fx_over_budget = false;
+ cx.set_fx_clip(Rect::new(0, 0, 1, 1));
+ cx.set_fx_clip(band);
+ assert!(built < effect_maps(l, band, &cx).bytes());
+ cx.fx_over_budget = true;
+ // Composited over more than the band, and maps that aren't local: the whole region.
+ assert_eq!(effect_region(l, Rect::new(0, 500, 48, 600), &cx), whole);
+ let noisy = &d.layers[2];
+ assert!(!effects::maps_are_local(noisy));
+ cx.set_fx_clip(Rect::new(0, 100, 48, 140));
+ assert!(!effect_region(noisy, Rect::new(0, 100, 48, 140), &cx).1);
+}
+
+#[test]
+fn renders_with_maps_clipped_over_the_budget_match_the_whole_maps() {
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let d = ordinary_fx_doc(depth);
+ let patterns = pattern::PreparedPatterns::new(&d.patterns, pattern::PREPARED_PATTERN_BYTES);
+ purge_effect_cache();
+ let whole = render(&d, d.bounds());
+ let mut cx = Ctx::for_doc(&d, &patterns);
+ cx.fx_over_budget = true;
+ // Bands, edit-sized parts and single tiles, each from maps built over it alone.
+ purge_effect_cache();
+ let bands = (0..10).map(|i| Rect::new(0, i * 64, 48, (i + 1) * 64));
+ let parts = [Rect::new(3, 290, 41, 333), Rect::new(0, 0, 48, 20), Rect::new(20, 600, 48, 640), Rect::new(0, 296, 20, 312), Rect::new(10, 425, 40, 445)];
+ for r in bands.chain(parts) {
+ let p = render_tiled_with(&d, r, RENDER_TILE, &cx);
+ for y in r.y0..r.y1 {
+ for x in r.x0..r.x1 {
+ assert_eq!(p.get(x, y), whole.get(x, y), "{depth:?}: {r:?} differs at ({x},{y})");
+ }
+ }
+ }
+ assert!(render_tiled_with(&d, d.bounds(), 16, &cx).px == whole.px, "{depth:?}: tiled render differs");
+ }
+}
+
+#[test]
+fn the_effect_map_estimate_is_a_lower_bound() {
+ // fx_over_budget compares a lower bound of the maps' bytes with the budget: it must not
+ // exceed what building them takes, or a document that fits would lose its shared maps.
+ let d = ordinary_fx_doc(SampleType::U8);
+ let patterns = pattern::PreparedPatterns::new(&d.patterns, pattern::PREPARED_PATTERN_BYTES);
+ let cx = Ctx::for_doc(&d, &patterns);
+ let mut todo = Vec::new();
+ effect_layers(&d.layers, d.bounds(), 0, &mut todo);
+ let built: usize = todo.iter().map(|l| effect_maps(l, d.bounds(), &cx).bytes()).sum();
+ let estimate = fx_region_bytes(&d.layers, d.bounds());
+ assert!(estimate > 0 && estimate <= built as u64, "estimate {estimate} B, built {built} B");
+ // A 9000 x 6000 document with three full layers, each with a drop shadow (#8330's case):
+ // about 1.3 GB, over the default 768 MB. One such layer fits.
+ let mut big = Document::with_background("big", Size::new(9000, 6000), ColorMode::Rgb, SampleType::U8, Color::WHITE);
+ let mut l = Layer::raster("fill", big.pixel_format());
+ l.surface_mut().unwrap().fill_rect(big.bounds(), &photocraft_raster::from_rgba(&big.pixel_format(), [0.8, 0.5, 0.3, 1.0]));
+ l.effects.items = vec![Effect::DropShadow(Shadow { size: 40.0, ..shadow(20.0, 120.0) })];
+ big.layers.push(l.clone());
+ assert!(fx_region_bytes(&big.layers, big.bounds()) < DEFAULT_FX_CACHE_BUDGET as u64);
+ big.layers.extend([l.clone(), l]);
+ assert!(fx_region_bytes(&big.layers, big.bounds()) > DEFAULT_FX_CACHE_BUDGET as u64);
+}
+
// ---------- PSD-fidelity effect semantics (fitted on Photoshop composites) ----------
#[test]