PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Performance: the lower-stack cache follows an edit up the stack (P9 / P11, #5286) (#5288)
David Mannd9eb46b48517
diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rsindex 45e07500b..de6ca3e56 100644--- a/crates/gpu/src/lib.rs+++ b/crates/gpu/src/lib.rs@@ -24,7 +24,9 @@//! staged uploads and evicted pages stay bounded.//! - **Stack reuse.** A complete root stack unit can checkpoint its backdrop into bounded chunk//! textures. Exact COW snapshots invalidate the lower prefix; edits above it restore those-//! pixels and execute only the remaining passes. Groups and clipping units stay indivisible.+//! pixels and execute only the remaining passes, capturing on the way the highest checkpoint+//! below the edit, so repeating it (a duplicate or paste and its undo) skips that much more.+//! Groups and clipping units stay indivisible.//!//! Vector masks (rasterised once per mask state into a combined mask texture), layers clipped to//! pass-through groups, stroked shapes with clipped layers (fill and stroke split once per shape@@ -1302,7 +1304,10 @@ impl Compositor {if chunks.is_empty() {return;}- let first_pass = checkpoint.filter(|_| chunks.iter().all(|c| self.prefix.contains(*c))).map_or(0, |c| c.pass_end);+ // Chunks may hold different checkpoints: bind from the lowest one any of them resumes at.+ let first_pass = checkpoint+ .and_then(|_| chunks.iter().map(|c| self.prefix.restore_point(*c).map(|r| r.pass_end)).try_fold(usize::MAX, |m, p| Some(m.min(p?))))+ .unwrap_or(0);let bound = self.bind_cell(device, queue, encoder, doc, plan, paged, cell, fr, first_pass, stats);// Chunk pool.@@ -1372,7 +1377,7 @@ impl Compositor {for (ci, c) in chunks.iter().enumerate() {let mut resume = 0;- if let Some(cp) = checkpoint+ if let Some(cp) = checkpoint.and_then(|_| self.prefix.restore_point(*c))&& let Some((dst, _)) = self.pool.get(cp.slot as usize)&& self.prefix.copy_out(encoder, *c, dst){@@ -1397,11 +1402,12 @@ impl Compositor {return;}}- if resume == 0+ // Also after resuming from a lower checkpoint: the chunk moves up to this one.+ if resume < i&& let Some(cp) = checkpoint.filter(|cp| cp.pass_end == i)&& let Some((src, _)) = self.pool.get(cp.slot as usize){- self.prefix.capture(device, encoder, *c, src);+ self.prefix.capture(device, encoder, *c, src, cp);}let scissor = match p.clip {Some(clip) => {@@ -1467,11 +1473,11 @@ impl Compositor {pass.set_bind_group(1, bg1[i].as_ref(), &[]);pass.draw(0..3, 0..1);}- if resume == 0+ if resume < plan.passes.len()&& let Some(cp) = checkpoint.filter(|cp| cp.pass_end == plan.passes.len())&& let Some((src, _)) = self.pool.get(cp.slot as usize){- self.prefix.capture(device, encoder, *c, src);+ self.prefix.capture(device, encoder, *c, src, cp);}let (t, v) = &self.pool[plan.root as usize];sink(encoder, ChunkOut { rect: *c, texture: t, view: v });diff --git a/crates/gpu/src/prefix.rs b/crates/gpu/src/prefix.rsindex 0312a25fa..34c70916e 100644--- a/crates/gpu/src/prefix.rs+++ b/crates/gpu/src/prefix.rs@@ -6,6 +6,13 @@//! every frame, and caching those would fill the budget with entries that never hit again.//! A partial rectangle is served as a sub-rect copy of the whole chunk it falls into, and a//! capture merges into the chunk it overlaps, so every hit lands on the same stable entry.+//!+//! Each chunk remembers the checkpoint it holds. A render captures at the highest checkpoint+//! below its edit, also where it resumed from a lower cached one, so the cache follows the edit+//! up the stack chunk by chunk: repeating an edit high in the stack (a duplicate or paste and its+//! undo) then skips everything below it, and chunks a refresh doesn't reach keep serving their+//! own, lower prefix meanwhile (#5286). A chunk moved by a partial capture holds only that+//! rectangle afterwards: the rest of it misses once, like any fresh entry.use std::collections::HashMap;use photocraft_doc::{Document, Layer};@@ -21,11 +28,17 @@ pub(crate) const MAX_BYTES: u64 = 512 << 20;pub(crate) struct Chunk {tex: Tex,covered: Vec<Rect>,+ /// The checkpoint the covered pixels hold.+ checkpoint: Checkpoint,+ bytes: u64,}pub(crate) struct Prefix {context: Option<Document>,+ /// The root layers of the last prepared render, all of them: a chunk stays valid while every+ /// render since its capture left the layers below its checkpoint as they were.layers: Vec<Layer>,+ /// Where renders capture: the highest useful checkpoint below the latest edit.checkpoint: Option<Checkpoint>,chunks: HashMap<Rect, Chunk>,bytes: u64,@@ -90,6 +103,7 @@ impl Prefix {self.context.as_ref().map(|d| d.id)}+ /// Drops the chunks `doc` invalidated and returns the checkpoint this render captures at.pub(crate) fn prepare(&mut self, doc: &Document, plan: &Plan<'_>) -> Option<Checkpoint> {if self.budget == 0 {return None;@@ -97,39 +111,51 @@ impl Prefix {// Keeping every non-layer field makes new document inputs invalidate automatically.// Tile data is Arc-shared; shared Tile equality does not scan its pixel bytes.let mut context = doc.clone();- let mut layers = std::mem::take(&mut context.layers);+ let layers = std::mem::take(&mut context.layers);let same_context = self.context.as_ref() == Some(&context);- let changed = self.layers.iter().zip(&layers).position(|(a, b)| a != b).or_else(|| (layers.len() < self.layers.len()).then_some(layers.len()));- let old = self.checkpoint.filter(|c| same_context && changed.is_none() && plan.checkpoints.contains(c));- let checkpoint = old.or_else(|| {- if same_context && let Some(changed) = changed {- plan.checkpoints.iter().rev().find(|c| c.layer_end <= changed && c.pass_end > 1).copied()- } else {+ // The lowest root layer this render changes since the last one (a layer added or removed+ // at the top changes from there on).+ let changed = self+ .layers+ .iter()+ .zip(&layers)+ .position(|(a, b)| a != b)+ .or_else(|| (layers.len() != self.layers.len()).then_some(layers.len().min(self.layers.len())));+ if same_context {+ let mut freed = 0u64;+ self.chunks.retain(|_, c| {+ let keep = changed.is_none_or(|ch| c.checkpoint.layer_end <= ch) && plan.checkpoints.contains(&c.checkpoint);+ if !keep {+ freed = freed.saturating_add(c.bytes);+ }+ keep+ });+ self.bytes = self.bytes.saturating_sub(freed);+ } else {+ self.clear();+ }+ let kept = self.checkpoint.filter(|c| same_context && changed.is_none() && plan.checkpoints.contains(c));+ let checkpoint = kept.or_else(|| match changed {+ // Just below the edit; nothing when it is at the bottom.+ Some(changed) if same_context => plan.checkpoints.iter().rev().find(|c| c.layer_end <= changed && c.pass_end > 1).copied(),+ _ => {let mut useful = plan.checkpoints.iter().rev().filter(|c| c.pass_end > 1);let last = useful.next().copied();useful.next().copied().or(last)}});- if old.is_none() {- self.clear();- }- let Some(checkpoint) = checkpoint else {- // Remember bottom-layer edits even when no useful prefix survives: otherwise- // every other edit would populate and immediately discard the default checkpoint.- self.context = Some(context);- self.layers = layers;- return None;- };- layers.truncate(checkpoint.layer_end);+ // Remember bottom-layer edits even when no useful prefix survives: otherwise every other+ // edit would populate and immediately discard the default checkpoint.self.context = Some(context);self.layers = layers;- self.checkpoint = Some(checkpoint);- Some(checkpoint)+ self.checkpoint = checkpoint;+ checkpoint}- /// Whether every pixel of `rect` is already cached in its whole grid chunk.- pub(crate) fn contains(&self, rect: Rect) -> bool {- self.covered_by(rect).is_some()+ /// The checkpoint the cached pixels of `rect` hold, when every one of them is cached in its+ /// whole grid chunk.+ pub(crate) fn restore_point(&self, rect: Rect) -> Option<Checkpoint> {+ self.covered_by(rect).map(|(chunk, _)| chunk.checkpoint)}/// The whole chunk and the source offset that serve `rect`, when it is fully covered.@@ -160,7 +186,8 @@ impl Prefix {/// Merges the rendered `rect` (document coordinates) into its whole grid chunk, admitting/// the chunk while space remains. Replacing entries on every miss would make a full/// refresh larger than the cache evict its own next hits.- pub(crate) fn capture(&mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, rect: Rect, src: &wgpu::Texture) {+ /// A chunk holding another (lower) checkpoint starts over with this capture.+ pub(crate) fn capture(&mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, rect: Rect, src: &wgpu::Texture, checkpoint: Checkpoint) {if rect.is_empty() {return;}@@ -174,9 +201,15 @@ impl Prefix {let tex =Tex::new(device, "pc_compose_prefix", cell.width(), cell.height(), src.format(), wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST);self.bytes = self.bytes.saturating_add(cell_bytes);- self.chunks.insert(cell, Chunk { tex, covered: Vec::new() });+ self.chunks.insert(cell, Chunk { tex, covered: Vec::new(), checkpoint, bytes: cell_bytes });}let Some(chunk) = self.chunks.get_mut(&cell) else { return };+ if chunk.checkpoint != checkpoint {+ // The render restored this chunk's old pixels earlier in the same encoder, so+ // overwriting them in place is ordered after that copy.+ chunk.covered.clear();+ chunk.checkpoint = checkpoint;+ }// A whole-chunk render replaces the coverage; a partial rectangle lands at its offset// inside the cell, beside whatever earlier strokes put there.if rect == cell {diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rsindex 44836c233..de2a97200 100644--- a/crates/gpu/tests/parity.rs+++ b/crates/gpu/tests/parity.rs@@ -259,6 +259,93 @@ fn stack_prefix_reuse_matches_uncached_gpu_and_cpu_at_every_depth() {}}+/// Duplicating a layer high in the stack, undoing and redoing it (#5286): the render resumes+/// from the lower cached prefix and moves the cache up to just below the copy, so the undo and+/// the redo skip more passes. Every render matches an uncached compositor bit for bit, at every+/// depth.+#[test]+fn prefix_follows_an_edit_up_the_stack_and_stays_exact() {+ let Some(mut g) = gpu() else { return };+ let mut uncached = Compositor::new(&g.device);+ uncached.set_composite_cache_budget(0);+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {+ let mut doc = Document::new("follow", Size::new(300, 70), ColorMode::Rgb, depth);+ for seed in 1..=6 {+ doc.layers.push(noise_layer("layer", doc.pixel_format(), doc.bounds(), seed, 0.2));+ }+ let mut exact = |g: &mut Gpu, doc: &Document, what: &str| -> photocraft_gpu::Stats {+ let stats = diff_rect(g, doc, doc.bounds(), what).unwrap_or_else(|e| panic!("{e}"));+ let cached = render_to_vec(&mut g.comp, &g.device, &g.queue, doc, doc.bounds()).unwrap();+ let cold = render_to_vec(&mut uncached, &g.device, &g.queue, doc, doc.bounds()).unwrap();+ assert_eq!(cached, cold, "{depth:?} {what}: reuse preserves the GPU accumulator exactly");+ stats+ };+ exact(&mut g, &doc, "populate");+ // An edit low in the stack puts the cache there.+ doc.layers[1].opacity = 0.6;+ assert_eq!(exact(&mut g, &doc, "low edit").prefix_hits, 0);+ let low = doc.clone();+ let copy = doc.layers[4].duplicate();+ doc.layers.insert(5, copy);+ let first = exact(&mut g, &doc, "duplicate");+ assert!(first.prefix_hits > 0, "{depth:?} the duplicate resumes from the low prefix");+ let undo = exact(&mut g, &low, "undo");+ assert!(undo.prefix_hits > 0, "{depth:?}");+ assert!(undo.prefix_passes_skipped > first.prefix_passes_skipped, "{depth:?} the cache moved up: {first:?} {undo:?}");+ let redo = exact(&mut g, &doc, "redo");+ assert_eq!(redo.prefix_passes_skipped, undo.prefix_passes_skipped, "{depth:?}");+ // An edit below the moved cache still invalidates it.+ doc.layers[2].opacity = 0.4;+ assert_eq!(exact(&mut g, &doc, "lower edit").prefix_hits, 0, "{depth:?}");+ }+}++/// A small refresh above the cache moves only the chunk it renders, which then holds just that+/// rectangle; the other chunks keep serving their lower checkpoint, and a full render afterwards+/// resumes each chunk from its own (#5286). Every render matches an uncached compositor exactly.+#[test]+fn chunks_keep_their_own_checkpoint_after_a_partial_refresh() {+ let Some(mut g) = gpu() else { return };+ let mut uncached = Compositor::try_new_with_format(&g.device, wgpu::TextureFormat::Rgba32Float).unwrap();+ uncached.set_texture_limit(PAGED_LIMIT);+ uncached.set_composite_cache_budget(0);+ let mut doc = base_doc(600, 300);+ for seed in 2..=5 {+ doc.layers.push(noise_layer("layer", PixelFormat::RGBA8, doc.bounds(), seed, 0.2));+ }+ let mut render = |g: &mut Gpu, doc: &Document, rect: Rect, what: &str| -> photocraft_gpu::Stats {+ let (cached, stats) = photocraft_gpu::render_to_vec_stats(&mut g.paged, &g.device, &g.queue, doc, rect).unwrap();+ let cold = render_to_vec(&mut uncached, &g.device, &g.queue, doc, rect).unwrap();+ assert_eq!(cached, cold, "{what}: reuse preserves the GPU accumulator exactly");+ let cpu = photocraft_compose::render(doc, rect);+ assert!(worst_diff(&cpu.px, &cached).0 <= TOL, "{what}: GPU and CPU differ");+ stats+ };+ render(&mut g, &doc, doc.bounds(), "populate");+ doc.layers[1].opacity = 0.5;+ let low = render(&mut g, &doc, doc.bounds(), "low edit");+ assert_eq!(low.prefix_hits, 0);+ // A copy near the top, refreshed in one chunk only.+ let copy = doc.layers[3].duplicate();+ doc.layers.insert(4, copy);+ let small = render(&mut g, &doc, Rect::new(10, 10, 60, 60), "partial duplicate refresh");+ assert_eq!(small.prefix_hits, 1, "{small:?}");+ let full = render(&mut g, &doc, doc.bounds(), "full refresh after the partial one");+ assert_eq!(full.prefix_hits, full.chunks - 1, "only the partly moved chunk misses: {full:?}");+ let again = render(&mut g, &doc, doc.bounds(), "full refresh, all moved");+ assert_eq!(again.prefix_hits, again.chunks);+ assert!(again.prefix_passes_skipped > full.prefix_passes_skipped, "{full:?} {again:?}");+ // Mixed checkpoints: a bottom-half refresh moves the chunks it covers whole further up+ // (an edit at the top), the top half keeps the previous checkpoint and still hits.+ doc.layers.last_mut().unwrap().opacity = 0.7;+ let bottom = render(&mut g, &doc, Rect::new(0, 256, 600, 300), "bottom strip");+ assert_eq!(bottom.prefix_hits, bottom.chunks);+ let moved = render(&mut g, &doc, Rect::new(0, 0, 512, 256), "whole top chunks");+ assert_eq!(moved.prefix_hits, moved.chunks);+ let mixed = render(&mut g, &doc, doc.bounds(), "full refresh, mixed checkpoints");+ assert_eq!(mixed.prefix_hits, mixed.chunks, "{mixed:?}");+}+#[test]fn root_checkpoints_keep_clipping_groups_and_adjustments_whole() {let Some(mut g) = gpu() else { return };