From a9c26551f10ff71d3ff9d9275f9f337ab3e11447 Mon Sep 17 00:00:00 2001 From: Brennan Stehling <277419+brennanMKE@users.noreply.github.com> Date: Tue, 27 Oct 2026 02:08:57 -0700 Subject: [PATCH 1/4] perf: add P81/P82 redraw-area rows on full-canvas layers (#9329) Track-only rows that check they hit the whole-document-redraw path and print the refreshed pixel count: undo of a brush dab on a 16-bit 15000x10000 full-canvas layer (reps capped at 5) and a fill of a 2 % selection on a 24 MP full-canvas layer. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/ui-egui/examples/perf_scenarios.rs | 114 +++++++++++++++++++++- docs/scorecard.md | 4 +- perf/budgets.toml | 21 ++++ 3 files changed, 136 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/examples/perf_scenarios.rs b/crates/ui-egui/examples/perf_scenarios.rs index 4ea1c1e87b..49ce5af218 100644 --- a/crates/ui-egui/examples/perf_scenarios.rs +++ b/crates/ui-egui/examples/perf_scenarios.rs @@ -102,6 +102,10 @@ struct Bench { errors: Vec<(String, String)>, /// The row being timed, so a panic inside it is reported against that row. current: Option, + /// Pixels the last `refresh` redrew (`Refresh.px`; the rect's area on the CPU). + last_px: std::cell::Cell, + /// Refreshed pixels per sample, for rows that report them (#9329); `record` prints the p50. + px: std::cell::RefCell>, } impl Bench { @@ -138,11 +142,12 @@ impl Bench { let t = Instant::now(); match &self.gpu { Some((g, rs)) => { - g.refresh(doc.id.0, doc, damage, None); + self.last_px.set(g.refresh(doc.id.0, doc, damage, None).px); let _ = rs.device.poll(eframe::wgpu::PollType::Wait { submission_index: None, timeout: None }); } None => { let r = damage.unwrap_or(doc.bounds()).intersect(&doc.bounds()); + self.last_px.set(if r.is_empty() { 0 } else { r.size().area() }); if !r.is_empty() { std::hint::black_box(photocraft_compose::render(doc, r)); } @@ -190,6 +195,7 @@ impl Bench { } self.current = Some(name.to_string()); self.sampler.reset(); + self.px.borrow_mut().clear(); let mut samples = Vec::new(); let mut run = || -> Res<()> { if warm { @@ -216,6 +222,11 @@ impl Bench { samples.len(), r["peak_rss_bytes"].as_u64().unwrap_or(0) >> 20, ); + let mut px = std::mem::take(&mut *self.px.borrow_mut()); + if !px.is_empty() { + px.sort_unstable(); + println!("{name:<52} refresh px {}", px[px.len() / 2]); + } self.rows.push(r); } Err(e) => { @@ -368,6 +379,8 @@ fn main() { rows: Vec::new(), errors: Vec::new(), current: None, + last_px: std::cell::Cell::new(0), + px: std::cell::RefCell::new(Vec::new()), }; println!("perf_scenarios: {} mode, {} reps, {}", if quick { "quick" } else { "full" }, reps, adapter.as_deref().unwrap_or("CPU canvas")); let t_all = Instant::now(); @@ -375,7 +388,7 @@ fn main() { // A panic in one group (a crash the scenario found) is reported against the row that was // running, and the other groups still run. type Group = fn(&mut Bench, &Sizes); - let groups: [(&str, Group); 7] = [ + let groups: [(&str, Group); 8] = [ ("layered", layered_scenarios), ("many layers", many_layer_scenarios), ("full-canvas layers", full_canvas_layer_scenarios), @@ -383,6 +396,7 @@ fn main() { ("long operations", job_scenarios), ("algorithms", algorithm_scenarios), ("huge document", huge_document_scenarios), + ("redraw area", redraw_area_scenarios), ]; let use_gpu = b.gpu.is_some(); if let Some(wanted) = arg(&args, "--group") @@ -1199,3 +1213,99 @@ fn liquify_preview_scenario(b: &mut Bench) { } b.record(name, &Session::new(), &samples, Ok(())); } + +/// The share of the canvas `r` covers. +fn coverage(doc: &photocraft_doc::Document, r: Rect) -> f64 { + r.intersect(&doc.bounds()).size().area() as f64 / doc.bounds().size().area().max(1) as f64 +} + +/// The content bounds of `layer`'s pixels. +fn layer_bounds(s: &Session, layer: u64) -> Res { + let doc = &s.active().ok_or("no document")?.doc; + doc.layer(photocraft_doc::LayerId(layer)).and_then(|l| l.surface()).map(|p| p.content_bounds()).ok_or_else(|| "layer has no pixels".to_string()) +} + +/// A document with one painted layer covering the whole canvas; returns it and the layer. +fn full_layer_doc(w: u32, h: u32, depth: u32) -> Res<(Session, u64)> { + let mut s = Session::new(); + exec(&mut s, "file.new", json!({"width": w, "height": h, "depth": depth, "background": "white"}))?; + exec(&mut s, "layer.new.layer", json!({"name": "full"}))?; + exec(&mut s, "edit.fill", json!({"color": "#6080a0"}))?; + let layer = active_layer(&s)?; + let doc = s.active().ok_or("no document")?.doc.clone(); + let cover = coverage(&doc, layer_bounds(&s, layer)?); + if cover < 0.95 { + return Err(format!("path check: the painted layer covers {:.1} % of the canvas, not >= 95 %", cover * 100.0)); + } + Ok((s, layer)) +} + +/// #9329 PR A: the redraw area of edits on a full-canvas layer, where redrawing the whole +/// document is the expensive cliff. Each row checks it hits that path and prints `refresh px`. +fn redraw_area_scenarios(b: &mut Bench, sz: &Sizes) { + let undo = "undo a brush dab on a full-canvas 16-bit 15000x10000 layer + refresh"; + if b.wanted(undo) { + b.current = Some(undo.to_string()); + let (w, h) = sz.huge16; + match full_layer_doc(w, h, 16) { + Err(e) => b.errors.push((undo.to_string(), e)), + Ok((mut s, _)) => { + let _ = b.refresh(&s, true); + // Two 1.2 GB layers and, before the fix, a 150 MP refresh per sample. + let reps = b.reps.min(5); + b.time(undo, &mut s, reps, true, |b, s, i| { + let (x, y) = (200 + (i as u32 * 97) % (w - 400), 200 + (i as u32 * 61) % (h - 400)); + exec(s, "paint.stroke", json!({"points": [[x, y]], "size": 60, "hardness": 0.8, "color": "#c03020"}))?; + b.refresh(s, false)?; + let before = s.active().ok_or("no document")?.doc.clone(); + let t = Instant::now(); + exec(s, "edit.undo", json!({}))?; + let took = ms(t) + b.refresh(s, false)?; + b.px.borrow_mut().push(b.last_px.get()); + let after = s.active().ok_or("no document")?.doc.clone(); + if photocraft_engine::layer_multi_cmds::step_damage(&before, &after).is_some_and(|r| r.is_empty()) { + return Err("path check: the undo changed no pixels".into()); + } + Ok(took) + }); + } + } + } + + let fill = "fill a 2 % selection on a full-canvas 24 MP layer + refresh"; + if b.wanted(fill) { + b.current = Some(fill.to_string()); + let (w, h) = sz.big_photo; + let built = full_layer_doc(w, h, 8).and_then(|(mut s, layer)| { + exec(&mut s, "select.rect", json!({"x": w / 3, "y": h / 3, "width": w / 8, "height": h / 8}))?; + let doc = s.active().ok_or("no document")?.doc.clone(); + let sel = doc.selection.as_ref().map(|m| m.content_bounds()).ok_or("no selection")?; + let share = coverage(&doc, sel); + if share > 0.02 { + return Err(format!("path check: the selection covers {:.2} % of the canvas, not <= 2 %", share * 100.0)); + } + Ok((s, layer)) + }); + match built { + Err(e) => b.errors.push((fill.to_string(), e)), + Ok((mut s, _)) => { + let _ = b.refresh(&s, true); + let reps = b.reps; + b.time(fill, &mut s, reps, true, |b, s, i| { + // The colour alternates, so every sample changes pixels. + let color = if i % 2 == 0 { "#20c040" } else { "#c02040" }; + let before = s.active().ok_or("no document")?.doc.clone(); + let t = Instant::now(); + exec(s, "edit.fill", json!({"color": color}))?; + let took = ms(t) + b.refresh(s, false)?; + b.px.borrow_mut().push(b.last_px.get()); + let after = s.active().ok_or("no document")?.doc.clone(); + if photocraft_engine::layer_multi_cmds::step_damage(&before, &after).is_some_and(|r| r.is_empty()) { + return Err("path check: the fill changed no pixels".into()); + } + Ok(took) + }); + } + } + } +} diff --git a/docs/scorecard.md b/docs/scorecard.md index b9f9bb0a1e..934aa3a425 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -6,7 +6,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | Area | Done | Partial | Missing | Key numbers | |---|---:|---:|---:|---| -| [Performance](#performance) | 3 | 22 | 42 | 76 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 38 not run, 4 not measurable yet (baseline 2026-10-05) | +| [Performance](#performance) | 3 | 22 | 44 | 78 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 40 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 | | [Tools](#tools) | 36 | 9 | 0 | | | [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 12 of 181 (target 0) | @@ -98,6 +98,8 @@ Baseline: 2026-10-05, 1 run, commit `f5d2bcb54a`, Apple M4 Pro (48 GB), GPU Appl | P77 | Toggle an adjustment layer's visibility | ≤ 10 ms p95 | – | – | – | – | – | not run | [#6535](https://github.com/storytold/photocraft/issues/6535) | | P78 | Hide the top adjustment layer among 150 full-canvas layers, 6 MP, GPU budget forced to 512 MB (CPU fallback) | ≤ 30 ms p95 | – | – | – | – | – | not run | [#6533](https://github.com/storytold/photocraft/issues/6533) | | P79 | Zoomed-out reduced composite of a 30000x30000 document with one painted layer (#9330 target: 60000x60000) | track only | – | – | – | – | – | not run | [#1015](https://github.com/storytold/photocraft/issues/1015) | +| P81 | Undo a brush dab on a full-canvas 16-bit 15000 x 10000 layer + refresh | track only | – | – | – | – | – | not run | [#9329](https://github.com/storytold/photocraft/issues/9329) | +| P82 | Fill a 2 % selection on a full-canvas 24 MP layer + refresh | track only | – | – | – | – | – | not run | [#9329](https://github.com/storytold/photocraft/issues/9329) | **Not measurable yet** (the code can't do it yet; no number is recorded): diff --git a/perf/budgets.toml b/perf/budgets.toml index b538808553..bfb64dad60 100644 --- a/perf/budgets.toml +++ b/perf/budgets.toml @@ -751,3 +751,24 @@ issue = 1015 bench = "perf_scenarios" row = "zoomed-out reduced composite of the huge document with one painted layer" enforce = false # tracked only + +# ---- #9329: redraw area of edits on full-canvas layers (track only) --------------------------- +# +# Each row checks it hits the path it claims (a full-canvas layer; a non-empty edit; a small +# selection) and prints `refresh px ` after its timing line. + +[[scenario]] +id = "P81" +title = "Undo a brush dab on a full-canvas 16-bit 15000 x 10000 layer + refresh" +issue = 9329 +bench = "perf_scenarios" +row = "undo a brush dab on a full-canvas 16-bit 15000x10000 layer + refresh" +enforce = false # new; no baseline yet + +[[scenario]] +id = "P82" +title = "Fill a 2 % selection on a full-canvas 24 MP layer + refresh" +issue = 9329 +bench = "perf_scenarios" +row = "fill a 2 % selection on a full-canvas 24 MP layer + refresh" +enforce = false # new; no baseline yet From 2119158a5efa5a88eb7c174c313c3a837d5c4940 Mon Sep 17 00:00:00 2001 From: Brennan Stehling <277419+brennanMKE@users.noreply.github.com> Date: Sun, 25 Oct 2026 04:50:09 -0700 Subject: [PATCH 2/4] perf: a pixel change damages only the tiles that changed; command rects become checked hints (#9329) step_damage narrows a layer whose only change is in its surfaces (pixels, mask, type, smart-object and fill caches) to the bounding box of the tiles that differ: a merge walk of the two tile maps, pointer compares only. A mask's tiles grow by its feather, all of them by the layer's effects and the effects of the groups around it, never past the layer's whole extents. A frame-spanning effect whose frame moved keeps the whole extents (#4053). Undo, redo and History jumps get it for free: undoing a 60 px dab on a full-canvas layer redraws its tiles, not the canvas, and so does a fill or filter on a small selection. The painting commands' own damage rects go through one door, Session::hint_damage, which intersects them with the edit's damage. Debug and test builds count a hint that misses a changed tile in Session::damage_misses and log it; nothing panics. refresh_type_layers reports step_damage instead of None. Deleted: note_damage and layers_damage (identical to step_damage after layer.setProps and layer.translate), note_inert_insert (step_damage already steps over inert layers, #1771), and the engine's siblings_of they used. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/engine/src/cmd.rs | 7 - crates/engine/src/cmd/brush_cmds.rs | 4 +- crates/engine/src/cmd/eraser_cmds.rs | 6 +- crates/engine/src/cmd/layer_multi_cmds.rs | 9 +- .../engine/src/cmd/layer_multi_cmds/damage.rs | 226 +++++++++----- .../engine/src/cmd/layer_multi_cmds/moves.rs | 4 +- .../engine/src/cmd/layer_multi_cmds/tests.rs | 3 - .../cmd/layer_multi_cmds/tile_damage_tests.rs | 282 ++++++++++++++++++ crates/engine/src/cmd/redeye_cmds.rs | 4 +- crates/engine/src/cmd/retouch_cmds.rs | 4 +- .../cmd/retouch_cmds/content_aware_move.rs | 4 +- crates/engine/src/cmd/retouch_cmds/patch.rs | 4 +- .../src/cmd/retouch_cmds/pattern_stamp.rs | 4 +- crates/engine/src/cmd/retouch_cmds/remove.rs | 8 +- crates/engine/src/cmd/type_cmds.rs | 8 +- crates/engine/src/jobs.rs | 4 + crates/engine/src/lib.rs | 9 + crates/engine/src/new_layer.rs | 1 - crates/engine/src/session/execute.rs | 28 ++ crates/engine/src/session/layers.rs | 5 +- crates/engine/tests/it/type_format_targets.rs | 4 +- .../src/canvas/background_redraw/tests.rs | 5 +- crates/ui-egui/src/canvas/tests.rs | 12 +- 23 files changed, 513 insertions(+), 132 deletions(-) create mode 100644 crates/engine/src/cmd/layer_multi_cmds/tile_damage_tests.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index fc8442d67a..1598870479 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -464,7 +464,6 @@ fn build() -> Vec { *active = Some(id); Ok(id) })?; - crate::layer_multi_cmds::note_inert_insert(s, id); Ok(json!({ "layer": id.0 })) } ), @@ -606,9 +605,6 @@ fn build() -> Vec { ["name"] => "Rename Layer", _ => "Layer Properties", }; - let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); - // Clipping and channel changes reach the layers around it: recomposite everything. - let local = p.get("clipped").is_none() && p.get("channels").is_none(); // The eye: a history state only with History Options › Make Layer Visibility // Changes Undoable. let only_visibility = changed.as_slice() == ["visible"]; @@ -664,9 +660,6 @@ fn build() -> Vec { } Ok(()) })?; - if local { - crate::layer_multi_cmds::note_damage(s, &before, &ids); - } Ok(Value::Null) } ), diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 05af865ddc..f501b27c40 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -243,9 +243,7 @@ fn layer_id(s: &Session, p: &Value) -> Result { } fn damage_json(s: &mut Session, dmg: Rect) -> Value { - if let Some(st) = s.active_mut() { - st.last_damage = Some(dmg); - } + s.hint_damage(dmg); json!({ "damage": [dmg.x0, dmg.y0, dmg.width(), dmg.height()] }) } diff --git a/crates/engine/src/cmd/eraser_cmds.rs b/crates/engine/src/cmd/eraser_cmds.rs index 129753ea86..a506ecd403 100644 --- a/crates/engine/src/cmd/eraser_cmds.rs +++ b/crates/engine/src/cmd/eraser_cmds.rs @@ -67,10 +67,8 @@ fn pixels_locked(doc: &Document, l: &Layer) -> Option { } fn damage(s: &mut Session, dmg: Rect, erased: bool) -> Value { - if let Some(st) = s.active_mut() - && !dmg.is_empty() - { - st.last_damage = Some(dmg); + if !dmg.is_empty() { + s.hint_damage(dmg); } json!({ "erased": erased, "damage": [dmg.x0, dmg.y0, dmg.width(), dmg.height()] }) } diff --git a/crates/engine/src/cmd/layer_multi_cmds.rs b/crates/engine/src/cmd/layer_multi_cmds.rs index 52f36b9ffa..79abb250a3 100644 --- a/crates/engine/src/cmd/layer_multi_cmds.rs +++ b/crates/engine/src/cmd/layer_multi_cmds.rs @@ -20,8 +20,10 @@ mod selection; mod structure; use align::{align, distribute}; -pub use damage::{layer_bounds, layers_damage, same_pixels, selection_only_change, step_damage}; -pub(crate) use damage::{note_damage, note_inert_insert, note_insert}; +#[cfg(any(test, debug_assertions))] +pub(crate) use damage::hint_misses; +pub(crate) use damage::note_insert; +pub use damage::{layer_bounds, same_pixels, selection_only_change, step_damage}; use moves::link_groups; pub(crate) use moves::shift_surface; #[cfg(test)] @@ -164,3 +166,6 @@ mod tests; #[cfg(test)] mod layers_panel_parity_tests; + +#[cfg(test)] +mod tile_damage_tests; diff --git a/crates/engine/src/cmd/layer_multi_cmds/damage.rs b/crates/engine/src/cmd/layer_multi_cmds/damage.rs index 129dea0556..bad2821d5e 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/damage.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/damage.rs @@ -1,55 +1,58 @@ -use super::{Document, Layer, LayerContent, LayerId, Rect, Session, VideoData}; +use super::{Document, Layer, LayerContent, Rect, Session, VideoData}; -/// The document pixels an edit of the layers `ids` (moved, shown, hidden or restyled; contents -/// otherwise as they were) can have changed from `before` to `after`, or `None` for anywhere. -pub fn layers_damage(before: &Document, after: &Document, ids: &[LayerId]) -> Option { - let mut out = Rect::EMPTY; - for d in [before, after] { - let canvas = d.bounds(); - for id in ids { - // A layer gone from one side (never for a move) changes who knows what. - let (siblings, k, outer) = siblings_of(d, *id)?; - let b = photocraft_compose::change_bounds_in(siblings, k, outer, canvas)?; - if !b.is_empty() { - out = if out.is_empty() { b } else { out.union(&b) }; +/// Calls `f` with the rect of every tile that differs between two surfaces of the same format and +/// default pixel: a tile only one side has, or a different copy-on-write tile pointer at the same +/// coordinate. A merge walk of the two sorted tile maps: pointer compares, no pixel reads. Both +/// documents stay alive during the comparison, so tile addresses cannot be reused under it. +/// `false` (and no calls) when the format or default pixel differs: every pixel may have changed. +fn each_changed_tile(a: &photocraft_raster::Surface, b: &photocraft_raster::Surface, mut f: impl FnMut(Rect)) -> bool { + if a.format() != b.format() || a.default_bytes() != b.default_bytes() { + return false; + } + let (mut xs, mut ys) = (a.tiles().peekable(), b.tiles().peekable()); + loop { + match (xs.peek(), ys.peek()) { + (None, None) => return true, + (Some((ca, ta)), Some((cb, tb))) if ca == cb => { + if !std::sync::Arc::ptr_eq(ta, tb) { + f(ca.rect()); + } + xs.next(); + ys.next(); + } + (Some((ca, _)), Some((cb, _))) if ca < cb => { + f(ca.rect()); + xs.next(); + } + (Some((ca, _)), None) => { + f(ca.rect()); + xs.next(); + } + (_, Some((cb, _))) => { + f(cb.rect()); + ys.next(); } } } - Some(out) } -/// The sibling list holding layer `id` in `doc` (bottom→top), its index there, and the list -/// holding its parent group with the group's index (`None` at the top level). -type Siblings<'d> = (&'d [Layer], usize, Option<(&'d [Layer], usize)>); - -fn siblings_of(doc: &Document, id: LayerId) -> Option> { - let path = doc.path_of(id)?; - let (&k, parent) = path.split_last()?; - let Some((&g, grand)) = parent.split_last() else { return Some((doc.layers.as_slice(), k, None)) }; - let outer = if grand.is_empty() { doc.layers.as_slice() } else { doc.layer_at(grand)?.children()? }; - Some((outer.get(g)?.children()?, k, Some((outer, g)))) +/// The pixels that differ between two surfaces, to tile precision: the bounding box of the tiles +/// [`each_changed_tile`] finds (empty when the pixels are identical), or `None` when the format +/// or default pixel differs. +fn surface_damage(a: &photocraft_raster::Surface, b: &photocraft_raster::Surface) -> Option { + let mut out = Rect::EMPTY; + each_changed_tile(a, b, |r| out = out.union(&r)).then_some(out) } -/// Report [`layers_damage`] as the active document's last change, so the canvas recomposites -/// only that (grown by the effect reach around it) instead of everything. -pub(crate) fn note_damage(s: &mut Session, before: &Document, ids: &[LayerId]) { - let Some(st) = s.active_mut() else { return }; - if before.size != st.doc.size { - return; - } - st.last_damage = layers_damage(before, &st.doc, ids); -} - -/// Whether two surfaces hold identical pixels: same format and default pixel, and the same -/// copy-on-write tile pointers at the same coordinates. Both documents stay alive during the -/// comparison, so tile addresses cannot be reused under it. +/// Whether two surfaces hold identical pixels (see [`surface_damage`]). fn surfaces_equal(a: &photocraft_raster::Surface, b: &photocraft_raster::Surface) -> bool { - a.format() == b.format() - && a.default_pixel() == b.default_pixel() - && a.tile_count() == b.tile_count() - && a.tiles().zip(b.tiles()).all(|((ca, ta), (cb, tb))| ca == cb && std::sync::Arc::ptr_eq(ta, tb)) + surface_damage(a, b) == Some(Rect::EMPTY) } +/// How [`layer_pixels_cmp`] compares a pair of surfaces a layer draws from, given the feather (in +/// pixels) the compositor blurs it by: `true` when the pair counts as equal for the caller. +type SurfaceCmp<'f> = &'f mut dyn FnMut(&photocraft_raster::Surface, &photocraft_raster::Surface, f32) -> bool; + /// Byte blobs kept in `Arc`s (PSD raw blocks, embedded smart-object sources): pointer-identical /// or content-equal (they are small compared to pixels, and undo steps rarely re-parse them). fn blob_equal(x: &std::sync::Arc>, y: &std::sync::Arc>) -> bool { @@ -64,18 +67,18 @@ fn blobs_equal(a: &Option>>, b: &Option, b: &Option) -> bool { +/// Layer masks (also the smart-filter mask): scalars plus the surface, compared by `surf`. +fn masks_cmp(a: &Option, b: &Option, surf: SurfaceCmp) -> bool { match (a, b) { (None, None) => true, (Some(x), Some(y)) => { - x.enabled == y.enabled && x.linked == y.linked && x.density == y.density && x.feather == y.feather && surfaces_equal(&x.surface, &y.surface) + x.enabled == y.enabled && x.linked == y.linked && x.density == y.density && x.feather == y.feather && surf(&x.surface, &y.surface, x.feather) } _ => false, } } -fn texts_equal(a: &photocraft_doc::TextLayer, b: &photocraft_doc::TextLayer) -> bool { +fn texts_cmp(a: &photocraft_doc::TextLayer, b: &photocraft_doc::TextLayer, surf: SurfaceCmp) -> bool { a.text == b.text && a.font_family == b.font_family && a.size_pt == b.size_pt @@ -87,15 +90,15 @@ fn texts_equal(a: &photocraft_doc::TextLayer, b: &photocraft_doc::TextLayer) -> && a.orientation == b.orientation && a.antialias == b.antialias && a.warp == b.warp + && blobs_equal(&a.psd_raw, &b.psd_raw) && match (&a.cache, &b.cache) { (None, None) => true, - (Some(x), Some(y)) => surfaces_equal(x, y), + (Some(x), Some(y)) => surf(x, y, 0.0), _ => false, } - && blobs_equal(&a.psd_raw, &b.psd_raw) } -fn smarts_equal(a: &photocraft_doc::SmartObject, b: &photocraft_doc::SmartObject) -> bool { +fn smarts_cmp(a: &photocraft_doc::SmartObject, b: &photocraft_doc::SmartObject, surf: SurfaceCmp) -> bool { a.filters_enabled == b.filters_enabled && a.transform == b.transform && a.smart_filters == b.smart_filters @@ -109,13 +112,14 @@ fn smarts_equal(a: &photocraft_doc::SmartObject, b: &photocraft_doc::SmartObject (photocraft_doc::SmartSource::Linked { path: x }, photocraft_doc::SmartSource::Linked { path: y }) => x == y, _ => false, } + && blobs_equal(&a.psd_raw, &b.psd_raw) + // The filter mask shapes the filtered result the cache holds: compared exactly. + && masks_cmp(&a.filter_mask, &b.filter_mask, &mut |x, y, _| surfaces_equal(x, y)) && match (&a.cache, &b.cache) { (None, None) => true, - (Some(x), Some(y)) => surfaces_equal(x, y), + (Some(x), Some(y)) => surf(x, y, 0.0), _ => false, } - && blobs_equal(&a.psd_raw, &b.psd_raw) - && masks_equal(&a.filter_mask, &b.filter_mask) } /// Extra alpha/spot channels (the image itself in Multichannel mode). @@ -132,6 +136,13 @@ fn alpha_channels_equal(a: &photocraft_doc::AlphaChannel, b: &photocraft_doc::Al /// (name, locks, label, `psd_blocks`, `psd_id`, link group, XMP — none of them composite; video /// bails out earlier in the walk). fn layer_pixels_equal(a: &Layer, b: &Layer) -> bool { + layer_pixels_cmp(a, b, &mut |x, y, _| surfaces_equal(x, y)) +} + +/// [`layer_pixels_equal`] with the surfaces the layer draws from (its pixels, mask, type and +/// smart-object caches, fill cache) compared by `surf`; everything else compares exactly, before +/// any surface, so `surf` sees a pair only when every scalar the compositor reads is equal. +fn layer_pixels_cmp(a: &Layer, b: &Layer, surf: SurfaceCmp) -> bool { let Layer { id, name: _, @@ -162,27 +173,38 @@ fn layer_pixels_equal(a: &Layer, b: &Layer) -> bool { && *opacity == b.opacity && *fill_opacity == b.fill_opacity && *clipped == b.clipped - && masks_equal(mask, &b.mask) && *vector_mask == b.vector_mask && *effects == b.effects && *excluded_channels == b.excluded_channels && *blend_if == b.blend_if && *advanced == b.advanced + && match (fill_cache, &b.fill_cache) { + (None, None) => true, + (Some(x), Some(y)) => x.fill == y.fill, + _ => false, + } && match (content, &b.content) { - (LayerContent::Raster(x), LayerContent::Raster(y)) => surfaces_equal(x, y), + (LayerContent::Raster(_), LayerContent::Raster(_)) => true, // Children are walked separately; only the group's own clipping frame counts. (LayerContent::Group(x), LayerContent::Group(y)) => x.artboard == y.artboard, (LayerContent::Fill(x), LayerContent::Fill(y)) => x == y, (LayerContent::Adjustment(x), LayerContent::Adjustment(y)) => x == y, - (LayerContent::Text(x), LayerContent::Text(y)) => texts_equal(x, y), + (LayerContent::Text(x), LayerContent::Text(y)) => texts_cmp(x, y, &mut |_, _, _| true), (LayerContent::Shape(x), LayerContent::Shape(y)) => x == y, - (LayerContent::Smart(x), LayerContent::Smart(y)) => smarts_equal(x, y), + (LayerContent::Smart(x), LayerContent::Smart(y)) => smarts_cmp(x, y, &mut |_, _, _| true), _ => false, } + // Every scalar is equal: now the surfaces. + && masks_cmp(mask, &b.mask, surf) + && match (content, &b.content) { + (LayerContent::Raster(x), LayerContent::Raster(y)) => surf(x, y, 0.0), + (LayerContent::Text(x), LayerContent::Text(y)) => texts_cmp(x, y, surf), + (LayerContent::Smart(x), LayerContent::Smart(y)) => smarts_cmp(x, y, surf), + _ => true, + } && match (fill_cache, &b.fill_cache) { - (None, None) => true, - (Some(x), Some(y)) => x.fill == y.fill && surfaces_equal(&x.surface, &y.surface), - _ => false, + (Some(x), Some(y)) => surf(&x.surface, &y.surface, 0.0), + _ => true, } } @@ -363,13 +385,24 @@ pub fn selection_only_change(a: &Document, b: &Document) -> bool { /// what `layer.setProps` already reports as unbounded), and video layers. Inserting a copy of a /// 12 MP layer used to recomposite every layer of the document (#2883, P8/P9 in /// `perf/budgets.toml`). +/// +/// A layer whose only change is in the pixels of its surfaces (raster content, mask, type or +/// smart-object cache, fill cache) damages only the tiles that changed ([`tile_damage`]), so +/// undoing a brush dab on a full-canvas layer redraws the dab's tiles, not the canvas (#9329). pub fn step_damage(a: &Document, b: &Document) -> Option { if !doc_pixels_equal(a, b) { return None; } /// The list holding a sibling list's parent group, and the group's index there. type Outer<'d> = Option<(&'d [Layer], usize)>; - fn walk(xs: &[Layer], ys: &[Layer], (ox, oy): (Outer, Outer), a: &Document, b: &Document, out: &mut Rect) -> bool { + /// What the groups around a sibling list add to a change inside it: the summed reach of + /// their effects, and whether any lays effects out over its frame. + #[derive(Clone, Copy)] + struct Around { + reach: i32, + spans_frame: bool, + } + fn walk(xs: &[Layer], ys: &[Layer], (ox, oy): (Outer, Outer), around: Around, a: &Document, b: &Document, out: &mut Rect) -> bool { // Pair the layers by id, stepping over layers only one side has: one that draws nothing // changes no pixels (a new empty layer or group, #1771), any other only where it draws. let one_sided = |layers: &[Layer], k: usize, outer: Outer, canvas: Rect, out: &mut Rect| { @@ -420,7 +453,8 @@ pub fn step_damage(a: &Document, b: &Document) -> Option { if x.clipped != y.clipped || x.excluded_channels != y.excluded_channels { return false; } - if !layer_pixels_equal(x, y) { + let tiles = tile_damage(x, y); + if tiles != Some(Rect::EMPTY) { // Both sides' extents: a move changes pixels where it left and where it landed. // A clipped adjustment reaches as far as its base (#6535). let (Some(bx), Some(by)) = @@ -428,11 +462,27 @@ pub fn step_damage(a: &Document, b: &Document) -> Option { else { return false; }; - *out = if out.is_empty() { bx.union(&by) } else { out.union(&bx).union(&by) }; + let whole = bx.union(&by); + // Only pixels changed: the changed tiles, grown by what the groups around reach, + // never more than the whole extents. Effects laid out over a frame repaint it + // everywhere when it moves (#4053), so then the whole extents. + let frame_moved = around.spans_frame + || (photocraft_compose::effects::spans_frame(y) + && photocraft_compose::effects_frame(x, a.bounds()) != photocraft_compose::effects_frame(y, b.bounds())); + let d = match tiles { + Some(t) if !frame_moved => t.inflate(around.reach).intersect(&whole.inflate(around.reach)).intersect(&b.bounds()), + _ => whole, + }; + *out = out.union(&d); } match (x.children(), y.children()) { (Some(xc), Some(yc)) => { - if !walk(xc, yc, (Some((xs, xk)), Some((ys, yk))), a, b, out) { + let reach = |l: &Layer| if photocraft_compose::effects::has_effects(l) { photocraft_compose::effects::margin(l) } else { 0 }; + let inner = Around { + reach: around.reach.saturating_add(reach(x).max(reach(y))), + spans_frame: around.spans_frame || photocraft_compose::effects::spans_frame(x) || photocraft_compose::effects::spans_frame(y), + }; + if !walk(xc, yc, (Some((xs, xk)), Some((ys, yk))), inner, a, b, out) { return false; } } @@ -442,7 +492,44 @@ pub fn step_damage(a: &Document, b: &Document) -> Option { } } let mut out = Rect::EMPTY; - if walk(&a.layers, &b.layers, (None, None), a, b, &mut out) { Some(out) } else { None } + if walk(&a.layers, &b.layers, (None, None), Around { reach: 0, spans_frame: false }, a, b, &mut out) { Some(out) } else { None } +} + +/// How many tiles that differ between `before` and `after` (in the surfaces of layers both have) +/// `hint` misses: a command's own damage rect that misses a changed tile is too narrow (#4053). +#[cfg(any(test, debug_assertions))] +pub(crate) fn hint_misses(before: &Document, after: &Document, hint: Rect) -> usize { + let mut misses = 0; + for (_, _, y) in after.walk() { + let Some(x) = before.layer(y.id) else { continue }; + layer_pixels_cmp(x, y, &mut |p, q, _| { + each_changed_tile(p, q, |t| misses += usize::from(t.intersect(&hint).is_empty())); + true + }); + } + misses +} + +/// The pixels a change from layer `a` to layer `b` (the same layer on either side of a step) can +/// have changed when only the pixels of its surfaces changed: the tiles that differ +/// ([`surface_damage`]), a mask's grown by its feather, all grown by the layer's own effects. +/// Empty when the layers render identically. `None` when anything else changed (a property, the +/// content kind, a surface's format or default pixel): the caller then takes the layer's whole +/// extents. Children of groups are not compared (the caller walks them). +fn tile_damage(a: &Layer, b: &Layer) -> Option { + let mut tiles = Rect::EMPTY; + let only_pixels = layer_pixels_cmp(a, b, &mut |x, y, feather| { + let Some(r) = surface_damage(x, y) else { return false }; + let r = if feather > 0.0 { photocraft_vector::feather::grow(r, photocraft_vector::feather::feather_sigma(feather)) } else { r }; + tiles = tiles.union(&r); + true + }); + if !only_pixels { + return None; + } + // Effects are equal on both sides here (they are compared before any surface). + let margin = if photocraft_compose::effects::has_effects(b) { photocraft_compose::effects::margin(b) } else { 0 }; + Some(if tiles.is_empty() || margin == 0 { tiles } else { tiles.inflate(margin) }) } /// The pixels adding or removing `layers[k]` can change, when that is bounded: its change bounds @@ -485,19 +572,6 @@ fn inert_at(layers: &[Layer], k: usize) -> bool { && (l.clipped || layers.get(k + 1).is_none_or(|above| !above.clipped)) } -/// Report that adding layer `id` to the active document changed no pixels when it draws -/// nothing ([`inert_at`]), so the canvas doesn't recomposite every layer for it (#1771). Looks -/// only at the new layer and its neighbour, never at other layers' tiles. -pub(crate) fn note_inert_insert(s: &mut Session, id: LayerId) { - let Some(st) = s.active_mut() else { return }; - let Some(path) = st.doc.path_of(id) else { return }; - let Some((&k, parent)) = path.split_last() else { return }; - let siblings = if parent.is_empty() { Some(st.doc.layers.as_slice()) } else { st.doc.layer_at(parent).and_then(Layer::children) }; - if siblings.is_some_and(|sib| inert_at(sib, k)) { - st.last_damage = Some(Rect::EMPTY); - } -} - /// Report the pixels a command made of more than one edit changed since `before` ([`step_damage`]), /// so the canvas recomposites only where its new layers draw instead of the whole document. /// A single [`Session::edit`] already reports its own damage: don't call this after one (#5695). diff --git a/crates/engine/src/cmd/layer_multi_cmds/moves.rs b/crates/engine/src/cmd/layer_multi_cmds/moves.rs index 822e0f6ad1..9be731e0c8 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/moves.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/moves.rs @@ -1,4 +1,3 @@ -use super::damage::note_damage; use super::selection::{reselect, same_named_targets, selected, top_level}; use super::structure::check_group_depth; use super::{Document, EngineError, Layer, LayerContent, LayerId, Result, Session, Value, bad, int_i32, json}; @@ -151,7 +150,7 @@ pub fn translate(s: &mut Session, p: &Value) -> Result { } let mask_target = p.get("target").and_then(Value::as_str) == Some("mask"); let before = s.active().ok_or(EngineError::NoDocument)?.doc.clone(); - let ids = s.edit("Move", |doc, _| { + s.edit("Move", |doc, _| { let (alone, rest): (Vec, Vec) = roots.iter().partition(|id| mask_target && doc.layer(**id).is_some_and(moves_mask_alone)); let mut ids = move_targets(doc, &rest); if ids.is_empty() && alone.is_empty() { @@ -181,7 +180,6 @@ pub fn translate(s: &mut Session, p: &Value) -> Result { } Ok(ids) })?; - note_damage(s, &before, &ids); Ok(Value::Null) } diff --git a/crates/engine/src/cmd/layer_multi_cmds/tests.rs b/crates/engine/src/cmd/layer_multi_cmds/tests.rs index e03081a598..a983837cc6 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/tests.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/tests.rs @@ -386,9 +386,6 @@ fn clipped_adjustment_in_pass_through_clip_base_damages_its_group() { let LayerContent::Group(g) = &mut deleted.layers[2].content else { panic!("group") }; g.children.remove(1); assert_eq!(step_damage(&before, &deleted), group); - let LayerContent::Group(g) = &before.layers[2].content else { panic!("group") }; - let ids = [g.children[1].id]; - assert_eq!(layers_damage(&before, &after, &ids), group); // Without the layer clipped to the group it stays pass-through: just A's base. before.layers.truncate(3); after.layers.truncate(3); diff --git a/crates/engine/src/cmd/layer_multi_cmds/tile_damage_tests.rs b/crates/engine/src/cmd/layer_multi_cmds/tile_damage_tests.rs new file mode 100644 index 0000000000..9d3d466d67 --- /dev/null +++ b/crates/engine/src/cmd/layer_multi_cmds/tile_damage_tests.rs @@ -0,0 +1,282 @@ +//! #9329 PR A: a pixel change damages only the tiles that changed, and command rects are hints +//! checked against them. + +use super::*; +use photocraft_geom::TILE_SIZE; + +fn session(w: u32, h: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": w, "height": h})).unwrap(); + s +} + +fn doc(s: &Session) -> std::sync::Arc { + s.active().unwrap().doc.clone() +} + +fn damage(s: &Session) -> Option { + s.active().unwrap().last_damage +} + +/// The composite of `after` equals `before`'s outside `damage`. +fn unchanged_outside(before: &Document, after: &Document, damage: Rect) -> bool { + let (x, y) = (photocraft_compose::render(before, before.bounds()), photocraft_compose::render(after, after.bounds())); + let w = before.bounds().width() as i32; + x.px.iter().zip(&y.px).enumerate().all(|(i, (p, q))| p == q || damage.contains(i as i32 % w, i as i32 / w)) +} + +/// The tiles `r` overlaps, as one rect. +fn tiles_of(r: Rect) -> Rect { + let down = |v: i32| v.div_euclid(TILE_SIZE) * TILE_SIZE; + Rect::new(down(r.x0), down(r.y0), down(r.x1 - 1) + TILE_SIZE, down(r.y1 - 1) + TILE_SIZE) +} + +/// A new pixel layer with `rects` filled opaque, through one plain edit. +fn layer_with(s: &mut Session, rects: &[(Rect, [f32; 4])]) -> LayerId { + let id = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.edit("paint", |doc, _| { + let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap(); + for (r, px) in rects { + surf.fill_rect(*r, px); + } + Ok(()) + }) + .unwrap(); + id +} + +fn full_layer(s: &mut Session) -> LayerId { + let canvas = doc(s).bounds(); + layer_with(s, &[(canvas, [0.4, 0.5, 0.6, 1.0])]) +} + +/// One plain edit of layer `id`'s pixels, returning the documents on either side. +fn paint(s: &mut Session, id: LayerId, r: Rect, px: [f32; 4]) -> (std::sync::Arc, std::sync::Arc) { + let before = doc(s); + s.edit("paint", |doc, _| { + doc.layer_mut(id).unwrap().surface_mut().unwrap().fill_rect(r, &px); + Ok(()) + }) + .unwrap(); + (before, doc(s)) +} + +#[test] +fn a_fill_on_a_selection_damages_only_its_tiles() { + let mut s = session(1024, 768); + full_layer(&mut s); + let sel = Rect::new(300, 300, 440, 410); + s.execute("select.rect", json!({"x": sel.x0, "y": sel.y0, "width": sel.width(), "height": sel.height()})).unwrap(); + let before = doc(&s); + s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap(); + let d = damage(&s).expect("a bounded fill"); + assert!(!d.is_empty() && tiles_of(sel).contains_rect(&d), "{d:?}"); + assert!(d.size().area() < doc(&s).bounds().size().area() / 4, "{d:?}"); + assert!(unchanged_outside(&before, &doc(&s), d)); +} + +#[test] +fn undo_of_a_brush_dab_on_a_full_layer_redraws_only_its_tiles() { + let mut s = session(1024, 768); + full_layer(&mut s); + let four_tiles = 4 * (TILE_SIZE as u64).pow(2); + let before = doc(&s); + s.execute("paint.stroke", json!({"points": [[500, 400]], "size": 60, "color": "#ff0000"})).unwrap(); + let painted = doc(&s); + let d = damage(&s).expect("the dab"); + assert!(!d.is_empty() && d.size().area() <= four_tiles, "dab {d:?}"); + assert!(unchanged_outside(&before, &painted, d)); + assert!(s.undo()); + let d = damage(&s).expect("undo is bounded"); + assert!(!d.is_empty() && d.size().area() <= four_tiles, "undo {d:?}"); + assert!(unchanged_outside(&painted, &doc(&s), d)); + assert!(s.redo()); + let d = damage(&s).expect("redo is bounded"); + assert!(!d.is_empty() && d.size().area() <= four_tiles, "redo {d:?}"); + assert!(unchanged_outside(&before, &doc(&s), d)); +} + +/// The damage `note_damage` used to report after a move: both extents of the moved layer. +#[test] +fn a_move_still_damages_both_extents() { + let mut s = session(1024, 768); + let r = Rect::new(100, 100, 200, 200); + let id = layer_with(&mut s, &[(r, [1.0, 0.0, 0.0, 1.0])]); + let before = doc(&s); + s.execute("layer.translate", json!({"layer": id.0, "dx": 300, "dy": 50})).unwrap(); + let after = doc(&s); + let canvas = after.bounds(); + let extents = |d: &Document| photocraft_compose::change_bounds(d.layer(id).unwrap(), canvas).unwrap(); + let both = extents(&before).union(&extents(&after)); + assert_eq!(both, r.union(&r.translate(300, 50))); + assert_eq!(damage(&s), Some(both)); + assert!(unchanged_outside(&before, &after, both)); +} + +#[test] +fn set_props_damage_is_unchanged_without_note_damage() { + let r = Rect::new(100, 100, 200, 200); + for props in [json!({"opacity": 0.5}), json!({"fill": 0.5}), json!({"blend": "multiply"}), json!({"visible": false})] { + let mut s = session(1024, 768); + let id = layer_with(&mut s, &[(r, [1.0, 0.0, 0.0, 0.8])]); + let before = doc(&s); + let mut p = props.clone(); + p["layer"] = json!(id.0); + s.execute("layer.setProps", p).unwrap(); + assert_eq!(damage(&s), Some(r), "{props}"); + assert!(unchanged_outside(&before, &doc(&s), r), "{props}"); + } +} + +#[test] +fn a_mask_edit_damages_its_tiles_grown_by_the_feather() { + let mut s = session(1024, 768); + let id = full_layer(&mut s); + let feather = 10.0; + s.edit("mask", |doc, _| { + doc.layer_mut(id).unwrap().mask = Some(photocraft_doc::LayerMask { feather, ..photocraft_doc::LayerMask::reveal_all() }); + Ok(()) + }) + .unwrap(); + let before = doc(&s); + let hole = Rect::new(600, 400, 610, 410); + s.edit("mask paint", |doc, _| { + doc.layer_mut(id).unwrap().mask.as_mut().unwrap().surface.fill_rect(hole, &[0.0]); + Ok(()) + }) + .unwrap(); + let after = doc(&s); + let d = step_damage(&before, &after).unwrap(); + let grown = photocraft_vector::feather::grow(tiles_of(hole), photocraft_vector::feather::feather_sigma(feather)); + assert_eq!(d, grown.intersect(&after.bounds())); + assert!(d.contains_rect(&tiles_of(hole)) && d != after.bounds(), "{d:?}"); + assert!(unchanged_outside(&before, &after, d)); +} + +#[test] +fn tile_damage_grows_by_the_layer_effect_margin() { + let mut s = session(1024, 768); + let (a, b) = (Rect::new(50, 50, 150, 150), Rect::new(600, 400, 700, 500)); + let id = layer_with(&mut s, &[(a, [1.0, 0.0, 0.0, 1.0]), (b, [1.0, 0.0, 0.0, 1.0])]); + s.edit("fx", |doc, _| { + doc.layer_mut(id).unwrap().effects.items.push(photocraft_doc::Effect::default_drop_shadow()); + Ok(()) + }) + .unwrap(); + let m = photocraft_compose::effects::margin(doc(&s).layer(id).unwrap()); + assert!(m > 0); + let (before, after) = paint(&mut s, id, Rect::new(640, 440, 660, 460), [0.0, 0.0, 0.0, 0.0]); + let d = step_damage(&before, &after).unwrap(); + let whole = photocraft_compose::change_bounds(after.layer(id).unwrap(), after.bounds()).unwrap(); + assert_eq!(d, tiles_of(b).inflate(m).intersect(&whole)); + assert!(d.x0 < tiles_of(b).x0 && d.y0 < tiles_of(b).y0, "the shadow reaches past the tile: {d:?}"); + assert!(unchanged_outside(&before, &after, d)); +} + +/// #4053: effects laid out over the layer's frame repaint it everywhere when it grows. +#[test] +fn a_frame_spanning_effect_still_redraws_its_whole_frame() { + use photocraft_doc::{Effect, FxCommon, Gradient}; + let mut s = session(1024, 768); + let id = layer_with(&mut s, &[(Rect::new(100, 100, 700, 200), [1.0, 0.0, 0.0, 1.0])]); + s.edit("fx", |doc, _| { + doc.layer_mut(id).unwrap().effects.items.push(Effect::GradientOverlay { + common: FxCommon::new(photocraft_doc::BlendMode::Normal, 1.0), + gradient: Gradient::default(), + dither: false, + interpolation: None, + }); + Ok(()) + }) + .unwrap(); + let (before, after) = paint(&mut s, id, Rect::new(700, 100, 800, 200), [0.0, 1.0, 0.0, 1.0]); + let d = step_damage(&before, &after).unwrap(); + let extents = |d: &Document| photocraft_compose::change_bounds(d.layer(id).unwrap(), d.bounds()).unwrap(); + let whole = extents(&before).union(&extents(&after)); + assert!(whole.contains_rect(&Rect::new(100, 100, 800, 200)), "{whole:?}"); + assert_eq!(d, whole); + assert!(unchanged_outside(&before, &after, d)); +} + +#[test] +fn refreshing_type_layers_damages_only_those_layers() { + let mut s = session(1500, 1000); + let one = LayerId(s.execute("type.create", json!({"x": 100, "y": 100, "text": "One", "size": 20})).unwrap()["layer"].as_u64().unwrap()); + let two = LayerId(s.execute("type.create", json!({"x": 1000, "y": 800, "text": "Two", "size": 20})).unwrap()["layer"].as_u64().unwrap()); + let before = doc(&s); + let busy = s.refresh_type_layers(&[(before.id, one)]); + assert!(busy.is_empty()); + let after = doc(&s); + let d = damage(&s).expect("a bounded refresh"); + let bounds = |d: &Document, id: LayerId| photocraft_compose::change_bounds(d.layer(id).unwrap(), d.bounds()).unwrap(); + assert!(bounds(&before, one).union(&bounds(&after, one)).contains_rect(&d), "{d:?}"); + assert!(d.intersect(&bounds(&after, two)).is_empty(), "{d:?}"); + assert!(unchanged_outside(&before, &after, d)); +} + +#[test] +fn a_hint_that_misses_a_changed_tile_is_counted() { + let mut s = session(1024, 768); + let id = full_layer(&mut s); + paint(&mut s, id, Rect::new(600, 400, 620, 420), [1.0, 0.0, 0.0, 1.0]); + assert_eq!(s.damage_misses, 0); + s.hint_damage(Rect::new(0, 0, 10, 10)); + assert_eq!(s.damage_misses, 1); + assert_eq!(damage(&s), Some(Rect::EMPTY)); + // A hint covering the change is not a miss. + paint(&mut s, id, Rect::new(600, 400, 620, 420), [0.0, 1.0, 0.0, 1.0]); + s.hint_damage(Rect::new(600, 400, 620, 420)); + assert_eq!(s.damage_misses, 1); + assert_eq!(damage(&s), Some(Rect::new(600, 400, 620, 420))); +} + +#[test] +fn painting_command_hints_cover_their_changed_tiles() { + let mut s = session(600, 400); + let mut rects = Vec::new(); + for by in 0..20 { + for bx in 0..30 { + let v = ((bx * 7 + by * 13) % 17) as f32 / 17.0; + rects.push((Rect::from_xywh(bx * 20, by * 20, 20, 20), [v, 1.0 - v, 0.5 * v + 0.2, 1.0])); + } + } + rects.push((Rect::new(430, 280, 470, 320), [0.1, 0.1, 0.1, 1.0])); + for y in 292..309 { + for x in 442..459 { + if (x - 450) * (x - 450) + (y - 300) * (y - 300) <= 64 { + rects.push((Rect::from_xywh(x, y, 1, 1), [0.9, 0.05, 0.05, 1.0])); + } + } + } + layer_with(&mut s, &rects); + let ty = s.execute("type.create", json!({"x": 40, "y": 380, "text": "Hi", "size": 20})).unwrap()["layer"].as_u64().unwrap(); + let mut steps: Vec<(&str, serde_json::Value, Option)> = vec![ + ("paint.stroke", json!({"points": [[100, 100], [300, 120]], "size": 20, "color": "#2040ff"}), None), + ("paint.backgroundEraser", json!({"points": [[120, 300], [200, 320]], "size": 20}), None), + ("paint.cloneStamp", json!({"points": [[400, 100]], "offset": [-100, 0], "size": 30, "hardness": 100}), None), + ("paint.healingBrush", json!({"points": [[420, 200]], "source": [300, 200], "size": 30, "hardness": 100}), None), + ("paint.redEye", json!({"x": 450, "y": 300}), None), + ("paint.patch", json!({"offset": [60, 0]}), Some(Rect::new(60, 250, 100, 290))), + ("paint.remove", json!({"points": [[500, 100], [540, 140]], "size": 24}), None), + ("paint.contentAwareMove", json!({"offset": [100, -50], "structure": 3, "color": 4}), Some(Rect::new(300, 300, 340, 340))), + ("paint.patternStamp", json!({"points": [[200, 200]], "size": 16, "hardness": 100, "pattern": "Checkerboard", "scale": 100, "aligned": true}), None), + ]; + steps.push(("type.setStyle", json!({"layer": ty, "size": 40}), None)); + for (cmd, p, sel) in steps { + if let Some(r) = sel { + s.execute("select.rect", json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height()})).unwrap(); + } else if doc(&s).selection.is_some() { + s.execute("select.deselect", json!({})).unwrap(); + } + if cmd != "type.setStyle" { + let layer = doc(&s).layers.iter().find(|l| l.surface().is_some() && !doc(&s).is_background(l.id)).unwrap().id; + s.select_layer(layer).unwrap(); + } + let before = doc(&s); + s.execute(cmd, p).unwrap_or_else(|e| panic!("{cmd}: {e}")); + assert_eq!(s.damage_misses, 0, "{cmd}: its hint missed a changed tile"); + assert!(!same_pixels(&before, &doc(&s)), "{cmd} changed nothing"); + let d = damage(&s).unwrap_or_else(|| doc(&s).bounds()); + assert!(unchanged_outside(&before, &doc(&s), d), "{cmd}: pixels changed outside {d:?}"); + } +} diff --git a/crates/engine/src/cmd/redeye_cmds.rs b/crates/engine/src/cmd/redeye_cmds.rs index eefd1a37ba..02067d130b 100644 --- a/crates/engine/src/cmd/redeye_cmds.rs +++ b/crates/engine/src/cmd/redeye_cmds.rs @@ -243,9 +243,7 @@ fn red_eye(s: &mut Session, p: &Value) -> Result { } Ok((damage, total)) })?; - if let Some(st) = s.active_mut() { - st.last_damage = Some(damage); - } + s.hint_damage(damage); Ok(json!({ "damage": [damage.x0, damage.y0, damage.width(), damage.height()], "pixels": total })) } diff --git a/crates/engine/src/cmd/retouch_cmds.rs b/crates/engine/src/cmd/retouch_cmds.rs index da9183169f..bb754e13a0 100644 --- a/crates/engine/src/cmd/retouch_cmds.rs +++ b/crates/engine/src/cmd/retouch_cmds.rs @@ -193,9 +193,7 @@ fn run_stroke( // large layer would dominate the cost of a dab. f(&pre, surf, pre.selection.as_ref(), lock) })?; - if let Some(st) = s.active_mut() { - st.last_damage = Some(dmg); - } + s.hint_damage(dmg); Ok(dmg) } diff --git a/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs b/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs index 6e01926e3f..dbc73d9388 100644 --- a/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs +++ b/crates/engine/src/cmd/retouch_cmds/content_aware_move.rs @@ -529,9 +529,7 @@ pub(super) fn content_aware_move(s: &mut Session, p: &Value) -> Result { } Ok(()) })?; - if let Some(st) = s.active_mut() { - st.last_damage = Some(damage); - } + s.hint_damage(damage); let mode = if plan.mode == Mode::Move { "move" } else { "extend" }; let mut out = json!({ "damage": damage_json(damage), "offset": [dx, dy], "mode": mode }); if plan.map.is_some() { diff --git a/crates/engine/src/cmd/retouch_cmds/patch.rs b/crates/engine/src/cmd/retouch_cmds/patch.rs index 557c173b4b..b84de04052 100644 --- a/crates/engine/src/cmd/retouch_cmds/patch.rs +++ b/crates/engine/src/cmd/retouch_cmds/patch.rs @@ -296,9 +296,7 @@ fn patch_content_aware(s: &mut Session, p: &Value) -> Result { *crate::channel_cmds::target_surface(doc, target.id, &p)?.0 = surf; Ok(()) })?; - if let Some(st) = s.active_mut() { - st.last_damage = Some(damage); - } + s.hint_damage(damage); Ok(json!({ "damage": damage_json(damage), "offset": [dx, dy], "contentAware": true })) }, ) diff --git a/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs b/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs index f13afc112e..4499715307 100644 --- a/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs +++ b/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs @@ -96,9 +96,7 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result { paint_aligned(surf, &st.stroke, sel, lock, &st.tile, st.placement(), st.mode, CMD) } })?; - if let Some(state) = s.active_mut() { - state.last_damage = Some(dmg); - } + s.hint_damage(dmg); Ok(json!({ "damage": damage_json(dmg), "phase": [st.phase.0, st.phase.1], diff --git a/crates/engine/src/cmd/retouch_cmds/remove.rs b/crates/engine/src/cmd/retouch_cmds/remove.rs index a7283d390b..777b1131f9 100644 --- a/crates/engine/src/cmd/retouch_cmds/remove.rs +++ b/crates/engine/src/cmd/retouch_cmds/remove.rs @@ -252,15 +252,11 @@ pub(super) fn remove(s: &mut Session, p: &Value) -> Result { *active = Some(r.1); Ok(r) })?; - if let Some(st) = s.active_mut() { - st.last_damage = Some(damage); - } + s.hint_damage(damage); return Ok(json!({ "damage": damage_json(damage), "layer": nid.0 })); } let damage = s.edit(label, |doc, _| replace(doc, Target { id, all_layers: false }, &p, &out, &hole))?; - if let Some(st) = s.active_mut() { - st.last_damage = Some(damage); - } + s.hint_damage(damage); Ok(json!({ "damage": damage_json(damage) })) }, ) diff --git a/crates/engine/src/cmd/type_cmds.rs b/crates/engine/src/cmd/type_cmds.rs index 1e103cf89f..58a2145409 100644 --- a/crates/engine/src/cmd/type_cmds.rs +++ b/crates/engine/src/cmd/type_cmds.rs @@ -694,8 +694,8 @@ fn with_text_layer(s: &mut Session, p: &Value, label: &str, f: impl FnOnce(&m } Ok((r, damage)) })?; - if let Some(st) = s.active_mut() { - st.last_damage = damage; + if let Some(d) = damage { + s.hint_damage(d); } Ok(r) } @@ -764,8 +764,8 @@ pub(crate) fn with_text_targets( } Ok(damage) })?; - if let Some(st) = s.active_mut() { - st.last_damage = damage; + if let Some(d) = damage { + s.hint_damage(d); } Ok(ids) } diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index bf3560eb9f..7a01d6786d 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -860,6 +860,10 @@ impl Session { self.coalesce_request = None; self.color_restrict = None; self.filter_mask_layer = None; + #[cfg(any(test, debug_assertions))] + { + self.hint_before = None; + } let pending = self.jobs.pending.take(); match (r, pending) { (Err(e), Some(job)) => { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index c88ae3bfaf..17dbed3e43 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -277,6 +277,15 @@ pub struct Session { /// document, source read-only)`. The shell takes them with [`Session::take_held_open`]. held_opens: Vec<(u64, Document, bool)>, next_held_open: u64, + /// The document before the latest [`Session::edit`] of the running command, which + /// [`Session::hint_damage`] checks a hint against. Set by `edit`, taken by `hint_damage`, + /// dropped when the command ends. Debug and test builds only. + #[cfg(any(test, debug_assertions))] + hint_before: Option>, + /// Damage hints that missed a tile their edit changed ([`Session::hint_damage`]): each one a + /// command reporting too narrow a redraw area (#4053). Counted in debug and test builds only; + /// tests read it. + pub damage_misses: usize, } #[cfg(test)] diff --git a/crates/engine/src/new_layer.rs b/crates/engine/src/new_layer.rs index 4cba7f0c52..b102907ccc 100644 --- a/crates/engine/src/new_layer.rs +++ b/crates/engine/src/new_layer.rs @@ -58,7 +58,6 @@ pub fn run(s: &mut Session, p: &Value) -> Result { *active = Some(id); Ok(id) })?; - crate::layer_multi_cmds::note_inert_insert(s, id); Ok(json!({ "layer": id.0 })) } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 69c389f0c6..bc70ed2739 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -248,6 +248,8 @@ impl Session { // report its own, tighter damage after this. let damage = layer_multi_cmds::step_damage(&before, &st.doc); let keep_clean = st.keeps_clean(&before); + #[cfg(any(test, debug_assertions))] + let hint_before = before.clone(); let key = self.coalesce_request.clone(); let st = self.active_mut().ok_or(EngineError::NoDocument)?; let layers = st.layer_target(); @@ -268,6 +270,10 @@ impl Session { st.bump_revision(keep_clean); st.last_damage = damage; self.samplers_removed += samplers_removed; + #[cfg(any(test, debug_assertions))] + { + self.hint_before = Some(hint_before); + } if damage.is_none_or(|d| !d.is_empty()) { // Free the mask early; a stale entry would only miss (it is keyed by pixels). self.subject_cache = Default::default(); @@ -275,4 +281,26 @@ impl Session { } Ok(r) } + + /// A command's own rect for the pixels its latest [`Session::edit`] changed: sub-tile precise + /// for a brush dab, where the edit's own damage ([`layer_multi_cmds::step_damage`]) has tile + /// precision. The redraw area becomes the intersection of the two, so a hint can only narrow + /// it (or bound a change `step_damage` can't). In debug and test builds, a hint that misses a + /// tile the edit changed is counted in [`Session::damage_misses`] and logged; it never panics. + pub fn hint_damage(&mut self, rect: photocraft_geom::Rect) { + #[cfg(any(test, debug_assertions))] + if let Some(before) = self.hint_before.take() + && let Some(st) = self.active() + && st.doc.id == before.id + { + let misses = layer_multi_cmds::hint_misses(&before, &st.doc, rect); + if misses > 0 { + let step = st.history.undo_label().unwrap_or("?"); + eprintln!("warning: `{step}` hinted damage {rect:?} that misses {misses} changed tile(s); the canvas may not redraw them"); + self.damage_misses += misses; + } + } + let Some(st) = self.active_mut() else { return }; + st.last_damage = Some(st.last_damage.map_or(rect, |d| d.intersect(&rect))); + } } diff --git a/crates/engine/src/session/layers.rs b/crates/engine/src/session/layers.rs index b8ea5ea89d..2e6009d16f 100644 --- a/crates/engine/src/session/layers.rs +++ b/crates/engine/src/session/layers.rs @@ -1,5 +1,5 @@ use super::history::fix_selection; -use super::{Arc, EngineError, LayerId, Result, Session, channel_cmds, type_cmds}; +use super::{Arc, EngineError, LayerId, Result, Session, channel_cmds, layer_multi_cmds, type_cmds}; impl Session { /// Replace the active document's active layer without creating a history step. @@ -83,7 +83,8 @@ impl Session { if clean { st.saved_revision = st.revision; } - st.last_damage = None; + // Only the refreshed layers' caches changed: their changed tiles. + st.last_damage = layer_multi_cmds::step_damage(&snapshot, &st.doc); } } busy diff --git a/crates/engine/tests/it/type_format_targets.rs b/crates/engine/tests/it/type_format_targets.rs index 54e7d3f8af..e5f13ffd48 100644 --- a/crates/engine/tests/it/type_format_targets.rs +++ b/crates/engine/tests/it/type_format_targets.rs @@ -87,8 +87,10 @@ fn selected_type_properties_preserve_each_layers_other_attributes_and_one_histor if indices.contains(&i) { assert_ne!(actual.psd_raw, before[i].psd_raw, "editable PSD data refreshed"); let damage = s.active().unwrap().last_damage.unwrap(); + // The pixels the layer draws, before and after (the cache's tiles, narrowed to the + // layer's extents by the edit's own damage, #9329). for t in [&before[i], &actual] { - let bounds = t.cache.as_ref().unwrap().tile_bounds(); + let bounds = t.cache.as_ref().unwrap().content_bounds(); assert_eq!(damage.intersect(&bounds), bounds); } } diff --git a/crates/ui-egui/src/canvas/background_redraw/tests.rs b/crates/ui-egui/src/canvas/background_redraw/tests.rs index 55afe9ac6b..b13692d83c 100644 --- a/crates/ui-egui/src/canvas/background_redraw/tests.rs +++ b/crates/ui-egui/src/canvas/background_redraw/tests.rs @@ -249,8 +249,9 @@ fn an_edit_damaging_most_of_a_large_document_is_drawn_in_the_background_too() { let Some(mut g) = gpu_app() else { return }; let doc = cpu_only_document(g.harness.state_mut(), 2600, 1700); settle(&mut g); - // Filling part of the Blend If layer can change the composite anywhere: the whole canvas. - g.harness.state_mut().run("select.rect", json!({"x": 100, "y": 100, "width": 300, "height": 300})).expect("select"); + // Filling most of the Blend If layer touches tiles all over it: the whole canvas (a fill of a + // small part damages only its own tiles, #9329). + g.harness.state_mut().run("select.rect", json!({"x": 100, "y": 100, "width": 2500, "height": 1500})).expect("select"); g.harness.step(); g.harness.state_mut().run("edit.fill", json!({"color": "#22ee22"})).expect("fill"); assert_eq!(g.harness.state().session.active().expect("document").last_damage, Some(Rect::new(0, 0, 2600, 1700))); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index f213a67d9d..cbb0c8c5be 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1679,12 +1679,18 @@ fn mask_view_uploads_each_live_stroke_before_release() { assert_eq!(app.session.documents()[0].doc.layer(layer).unwrap(), &original); crate::channel_view::ensure(&mut app, &ctx, 0); let mut delta = ctx.tex_manager().write().take_delta(); - let egui::ImageData::Color(image) = &delta.set.get(&tex).unwrap()[0].image; + let upload = &delta.set.get(&tex).unwrap()[0]; + let egui::ImageData::Color(image) = &upload.image; let st = &app.session.documents()[0]; + // Undo redraws only the tiles the stroke changed (#9329): a partial upload of them. + let f = factor as i32; + let r = upload.pos.map_or(st.doc.bounds(), |pos| { + DRect::new(pos[0] as i32 * f, pos[1] as i32 * f, (pos[0] + image.size[0]) as i32 * f, (pos[1] + image.size[1]) as i32 * f) + .intersect(&st.doc.bounds()) + }); assert_eq!( image.pixels, - crate::channel_view::render(&st.doc, &st.channel_view, st.doc.bounds(), factor, crate::channel_view::Look::default(), st.active_layer) - .unwrap(), + crate::channel_view::render(&st.doc, &st.channel_view, r, factor, crate::channel_view::Look::default(), st.active_layer).unwrap(), "undo restores the shown mask" ); delta.clear(); From c855685c7f16963afcdc3530705308f21ed37774 Mon Sep 17 00:00:00 2001 From: Brennan Stehling <277419+brennanMKE@users.noreply.github.com> Date: Sun, 25 Oct 2026 05:08:47 -0700 Subject: [PATCH 3/4] test: cover group and clip-base effect damage, and mask undo coverage (#9329) Co-Authored-By: Claude Opus 5.5 (1M context) --- .../cmd/layer_multi_cmds/tile_damage_tests.rs | 39 +++++++++++++++++++ crates/ui-egui/src/canvas/tests.rs | 3 ++ 2 files changed, 42 insertions(+) diff --git a/crates/engine/src/cmd/layer_multi_cmds/tile_damage_tests.rs b/crates/engine/src/cmd/layer_multi_cmds/tile_damage_tests.rs index 9d3d466d67..c7acbff4a0 100644 --- a/crates/engine/src/cmd/layer_multi_cmds/tile_damage_tests.rs +++ b/crates/engine/src/cmd/layer_multi_cmds/tile_damage_tests.rs @@ -173,6 +173,45 @@ fn tile_damage_grows_by_the_layer_effect_margin() { assert!(unchanged_outside(&before, &after, d)); } +#[test] +fn a_dab_inside_a_group_with_a_drop_shadow_damages_the_shadow() { + let mut s = session(1024, 768); + let child = layer_with(&mut s, &[(Rect::new(600, 400, 700, 500), [1.0, 0.0, 0.0, 1.0])]); + s.execute("layer.select", json!({"layer": child.0})).unwrap(); + let g = LayerId(s.execute("layer.groupLayers", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.edit("fx", |doc, _| { + doc.layer_mut(g).unwrap().effects.items.push(photocraft_doc::Effect::default_drop_shadow()); + Ok(()) + }) + .unwrap(); + assert!(photocraft_compose::effects::margin(doc(&s).layer(g).unwrap()) > 0); + let dab = Rect::new(640, 440, 660, 460); + let (before, after) = paint(&mut s, child, dab, [0.0, 0.0, 1.0, 1.0]); + let d = damage(&s).expect("a bounded dab"); + assert!(d.contains_rect(&dab), "{d:?}"); + assert!(unchanged_outside(&before, &after, d), "the group's shadow changed outside {d:?}"); +} + +#[test] +fn painting_a_clip_base_under_a_styled_clipped_layer_is_covered() { + let mut s = session(1024, 768); + let base = layer_with(&mut s, &[(Rect::new(500, 300, 800, 600), [0.0, 1.0, 0.0, 1.0])]); + let top = full_layer(&mut s); + s.edit("clip", |doc, _| { + let l = doc.layer_mut(top).unwrap(); + l.clipped = true; + l.effects.items.push(photocraft_doc::Effect::default_drop_shadow()); + Ok(()) + }) + .unwrap(); + let (before, after) = paint(&mut s, base, Rect::new(300, 200, 340, 240), [0.0, 0.0, 1.0, 1.0]); + let d = damage(&s).expect("a bounded base edit"); + assert!(unchanged_outside(&before, &after, d), "the clipped layer changed outside {d:?}"); + let (before, after) = paint(&mut s, base, Rect::new(640, 440, 660, 460), [0.0, 0.0, 0.0, 0.0]); + let d = damage(&s).expect("a bounded base edit"); + assert!(unchanged_outside(&before, &after, d), "the clipped layer changed outside {d:?}"); +} + /// #4053: effects laid out over the layer's frame repaint it everywhere when it grows. #[test] fn a_frame_spanning_effect_still_redraws_its_whole_frame() { diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index cbb0c8c5be..e4dfe59b93 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1688,6 +1688,9 @@ fn mask_view_uploads_each_live_stroke_before_release() { DRect::new(pos[0] as i32 * f, pos[1] as i32 * f, (pos[0] + image.size[0]) as i32 * f, (pos[1] + image.size[1]) as i32 * f) .intersect(&st.doc.bounds()) }); + // It covers the stroke's span (x 10..70 along y 30, size 12), so it + // proves coverage and not only values. + assert!(r.contains_rect(&DRect::new(10, 26, 70, 34)), "undo covers the stroke: {r:?}"); assert_eq!( image.pixels, crate::channel_view::render(&st.doc, &st.channel_view, r, factor, crate::channel_view::Look::default(), st.active_layer).unwrap(), From e2855fddd74225a286dad15365c6d9f0ca849714 Mon Sep 17 00:00:00 2001 From: Brennan Stehling <277419+brennanMKE@users.noreply.github.com> Date: Wed, 28 Oct 2026 02:04:54 -0700 Subject: [PATCH 4/4] test: P81/P82 count only timed refreshes; mask undo must upload a partial rect (#9329) Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/ui-egui/examples/perf_scenarios.rs | 2 ++ crates/ui-egui/src/canvas/tests.rs | 7 +++---- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/examples/perf_scenarios.rs b/crates/ui-egui/examples/perf_scenarios.rs index 49ce5af218..68d3055318 100644 --- a/crates/ui-egui/examples/perf_scenarios.rs +++ b/crates/ui-egui/examples/perf_scenarios.rs @@ -200,6 +200,8 @@ impl Bench { let mut run = || -> Res<()> { if warm { f(self, s, 0)?; + // `refresh px` describes only the timed runs. + self.px.borrow_mut().clear(); } for i in 0..reps.max(1) { samples.push(f(self, s, i + 1)?); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index e4dfe59b93..61971f13d9 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1684,10 +1684,9 @@ fn mask_view_uploads_each_live_stroke_before_release() { let st = &app.session.documents()[0]; // Undo redraws only the tiles the stroke changed (#9329): a partial upload of them. let f = factor as i32; - let r = upload.pos.map_or(st.doc.bounds(), |pos| { - DRect::new(pos[0] as i32 * f, pos[1] as i32 * f, (pos[0] + image.size[0]) as i32 * f, (pos[1] + image.size[1]) as i32 * f) - .intersect(&st.doc.bounds()) - }); + let pos = upload.pos.expect("undo uploads only the changed tiles, not the whole mask"); + let r = DRect::new(pos[0] as i32 * f, pos[1] as i32 * f, (pos[0] + image.size[0]) as i32 * f, (pos[1] + image.size[1]) as i32 * f) + .intersect(&st.doc.bounds()); // It covers the stroke's span (x 10..70 along y 30, size 12), so it // proves coverage and not only values. assert!(r.contains_rect(&DRect::new(10, 26, 70, 34)), "undo covers the stroke: {r:?}");