PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Gradient Overlay: repaint the whole layer when a stroke moves its frame (#4053) (#5340)
David Mann5c1b9425d132
diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rsindex 5acdd7931..20657a253 100644--- a/crates/compose/src/effects.rs+++ b/crates/compose/src/effects.rs@@ -37,6 +37,25 @@ pub fn has_effects(layer: &Layer) -> bool {layer.effects.enabled && layer.effects.items.iter().any(Effect::enabled)}+/// Whether an enabled effect is laid out over the layer's frame ([`crate::effects_frame`]), so+/// growing or shrinking the layer repaints it everywhere, not only where its pixels changed: a+/// Gradient Overlay, a gradient stroke (its frame is the shape's extent), and patterns linked with+/// the layer without an effects reference point (overlays, pattern strokes and glows, and bevel+/// textures tile from the frame's top-left).+pub fn spans_frame(layer: &Layer) -> bool {+ let unanchored = layer.effects.reference.is_none();+ let pattern = |p: &FxPaint| unanchored && matches!(p, FxPaint::Pattern { .. });+ has_effects(layer)+ && layer.effects.items.iter().filter(|e| e.enabled()).any(|e| match e {+ Effect::GradientOverlay { .. } => true,+ Effect::PatternOverlay { link, .. } => *link && unanchored,+ Effect::Stroke(s) => matches!(s.paint, FxPaint::Gradient(_)) || pattern(&s.paint),+ Effect::OuterGlow(g) | Effect::InnerGlow(g) => pattern(&g.paint),+ Effect::BevelEmboss(b) => unanchored && b.texture.as_ref().is_some_and(|t| t.link),+ _ => false,+ })+}+/// Pixels an effect stack can reach beyond the layer's shape.pub fn margin(layer: &Layer) -> i32 {let mut m = 0.0f32;diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rsindex e35d5ad40..7c0ce9098 100644--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@ -890,6 +890,38 @@ pub fn paint_bounds(layer: &Layer) -> Option<Rect> {(!r.is_empty()).then_some(r)}+/// The frame a layer's effects are laid out in: [`paint_bounds`] for a shape, else the layer's+/// bounds ([`layer_bounds`]). A Gradient Overlay spans it, linked patterns tile from its corner.+pub fn effects_frame(layer: &Layer, canvas: Rect) -> Rect {+ paint_bounds(layer).unwrap_or_else(|| layer_bounds(layer, canvas))+}++/// The pixels a change from `a` to `b` repaints beyond those it changed: where a layer whose+/// effects span its frame ([`effects::spans_frame`]) moved that frame, the layer's whole composite+/// before and after. Painting on a layer with a Gradient Overlay lays the one gradient out again+/// over the grown layer, as Photoshop does after each stroke; damage that covers only the stroke+/// leaves the old gradient around earlier strokes (#4053). Empty when no such frame moved.+pub fn relayout_damage(a: &Document, b: &Document) -> Rect {+ let mut out = Rect::EMPTY;+ let mut add = |r: Rect| {+ if !r.is_empty() {+ out = if out.is_empty() { r } else { out.union(&r) };+ }+ };+ for (_, _, y) in b.walk() {+ if !y.visible || !effects::spans_frame(y) {+ continue;+ }+ let Some(x) = a.layer(y.id) else { continue };+ if effects_frame(x, a.bounds()) == effects_frame(y, b.bounds()) {+ continue;+ }+ add(change_bounds(x, a.bounds()).unwrap_or_else(|| a.bounds()));+ add(change_bounds(y, b.bounds()).unwrap_or_else(|| b.bounds()));+ }+ out+}+/// The bounding box of a shape layer's vector content: its path control bounds plus stroke width.pub fn shape_bounds(sh: &photocraft_doc::ShapeLayer) -> Option<Rect> {if sh.fill.is_none() && sh.stroke.as_ref().is_none_or(|s| s.width <= 0.0 || s.opacity <= 0.0) {@@ -1514,15 +1546,7 @@ fn composite_layer_effects(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffadvanced::composite_clipped(clipped, &mut content, cx);let vstroke = vstroke.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() });let maps = effect_maps(layer, rect, cx);- effects::composite_with_effects_prepared(- layer,- &content,- backdrop,- &maps,- paint_bounds(layer).unwrap_or_else(|| layer_bounds(layer, cx.canvas)),- cx.patterns,- vstroke,- );+ effects::composite_with_effects_prepared(layer, &content, backdrop, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke);}/// The coverage-mixing gamma of a layer: the text blending gamma@@ -1780,7 +1804,7 @@ fn cached_effect_maps(layer: &Layer, region: Rect, key: u64, cx: &Ctx) -> std::s}fn texture_ctx<'a>(layer: &Layer, region: Rect, cx: &Ctx<'a>) -> effects::TextureCtx<'a> {- let sb = paint_bounds(layer).unwrap_or_else(|| layer_bounds(layer, cx.canvas));+ let sb = effects_frame(layer, cx.canvas);effects::TextureCtx { rect: region, patterns: cx.patterns.source(), anchor: layer.effects.reference.unwrap_or((f64::from(sb.x0), f64::from(sb.y0))) }}@@ -1835,15 +1859,7 @@ fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) {let vstroke = vstroke.as_ref().map(|(s, m)| effects::VectorStroke { stroke: s, mask: m.as_deref() });let mut opaque = Buffer { rect, px: base.px.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() };let maps = effect_maps(layer, rect, cx);- effects::composite_with_effects_prepared(- layer,- &content,- &mut opaque,- &maps,- paint_bounds(layer).unwrap_or_else(|| layer_bounds(layer, cx.canvas)),- cx.patterns,- vstroke,- );+ effects::composite_with_effects_prepared(layer, &content, &mut opaque, &maps, effects_frame(layer, cx.canvas), cx.patterns, vstroke);if let Some(m) = &hide {let plain = Buffer { rect, px: base.px.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() };advanced::apply_hiding_mask(&mut opaque, &plain, m);diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rsindex ddd487154..bd7d3ceba 100644--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@ -1082,6 +1082,34 @@ fn glow_gradient_follows_the_shape() {assert!(edge[0] > 0.8 && edge[2] < 0.2, "{edge:?}");}+// A Gradient Overlay spans the layer's frame: growing the layer repaints all of it, not just the+// new pixels (#4053). Effects that don't depend on the frame repaint only what changed.+#[test]+fn relayout_damage_covers_a_layer_whose_gradient_frame_moved() {+ let overlay = Effect::GradientOverlay { common: FxCommon::new(photocraft_color::BlendMode::Normal, 1.0), gradient: Gradient::default(), dither: false };+ let grown = |a: &Document, rect: Rect, rgba: [f32; 4]| {+ let mut b = a.clone();+ let old = b.layers.last().unwrap().clone();+ let mut l = solid_layer("sq", rect, rgba);+ (l.id, l.effects) = (old.id, old.effects);+ *b.layers.last_mut().unwrap() = l;+ b+ };+ let a = fx_doc(vec![overlay.clone()]);+ let b = grown(&a, Rect::new(10, 10, 36, 34), [1.0, 0.0, 0.0, 1.0]);+ let d = crate::relayout_damage(&a, &b);+ assert!(d.contains_rect(&Rect::new(10, 10, 36, 34)), "{d:?}");+ // Same bounds, other pixels: the frame stays, the pixels' own damage is enough.+ assert_eq!(crate::relayout_damage(&a, &grown(&a, Rect::new(10, 10, 30, 30), [0.0, 1.0, 0.0, 1.0])), Rect::EMPTY);+ // A Color Overlay doesn't depend on the frame.+ let c = fx_doc(vec![Effect::ColorOverlay { common: FxCommon::new(photocraft_color::BlendMode::Normal, 1.0), color: Color::BLACK }]);+ assert_eq!(crate::relayout_damage(&c, &grown(&c, Rect::new(10, 10, 36, 34), [1.0, 0.0, 0.0, 1.0])), Rect::EMPTY);+ // Nor does a disabled overlay.+ let mut off = a.clone();+ off.layers.last_mut().unwrap().effects.enabled = false;+ assert_eq!(crate::relayout_damage(&off, &grown(&off, Rect::new(10, 10, 36, 34), [1.0, 0.0, 0.0, 1.0])), Rect::EMPTY);+}+#[test]fn gradient_overlay_follows_angle_and_reverse() {let g = Gradient { stops: vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], angle: 0.0, ..Gradient::default() };diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rsindex b30e56da3..5098b958b 100644--- a/crates/engine/src/jobs.rs+++ b/crates/engine/src/jobs.rs@@ -732,6 +732,7 @@ impl Session {// action it plays (a script step) must not flush the steps it ran so far into the action// being recorded, nor move the recording mark past the entries it is about to replace.let recording = if spec.journal && crate::actions_cmds::replayable(id) { self.actions.recording.take() } else { None };+ let before = self.active().map(|st| st.doc.clone());// Last-resort guard (AGENTS.md, Never crash): a command that panics anyway fails with an// error instead of taking the app down. `edit` only commits a document after its closure// returns, so the documents are unchanged.@@ -759,12 +760,28 @@ impl Session {Ok(Started::Job(jid))}(Ok(v), None) => {+ if let Some(before) = before {+ self.add_relayout_damage(&before);+ }self.after_command(id, params, spec.journal, Some(nested_from));Ok(Started::Done(v))}}}+ /// Grows the damage a command reported for the pixels it changed by what effects laid out+ /// over a layer's frame repaint when it moved ([`photocraft_compose::relayout_damage`]): a+ /// stroke on a layer with a Gradient Overlay reports the stroke, but the gradient is laid out+ /// again over the whole grown layer (#4053). `before` is the active document before.+ fn add_relayout_damage(&mut self, before: &Arc<Document>) {+ let Some(st) = self.active_mut().filter(|st| st.doc.id == before.id && !Arc::ptr_eq(&st.doc, before)) else { return };+ let Some(d) = st.last_damage.filter(|d| !d.is_empty()) else { return };+ let extra = photocraft_compose::relayout_damage(before, &st.doc);+ if !extra.is_empty() {+ st.last_damage = Some(d.union(&extra));+ }+ }+/// A command that failed on a layer id the document doesn't have says which ids it does have/// (#5058): ids are not positions (an opened PNG's Background is not layer 1), and an agent/// should not need `document.inspect` to recover.diff --git a/crates/engine/tests/gradient_overlay_strokes.rs b/crates/engine/tests/gradient_overlay_strokes.rsnew file mode 100644index 000000000..e233f8984--- /dev/null+++ b/crates/engine/tests/gradient_overlay_strokes.rs@@ -0,0 +1,89 @@+//! A Gradient Overlay spans one gradient over the layer's current bounds, so a stroke that grows+//! the layer re-lays the gradient out over all of it (#4053). The damage a stroke reports must+//! cover that, or a canvas that redraws only the damage keeps the old gradient around the earlier+//! strokes: one gradient per stroke instead of one over the whole layer.++use photocraft_engine::Session;+use serde_json::json;++/// What a canvas that redraws only each edit's damage shows: the cold render before the edit,+/// with the edit's damage (grown by the effects' reach, as the canvas grows it) rendered again.+fn redraw_damage(shown: &mut photocraft_compose::Buffer, s: &Session) {+ let st = s.active().unwrap();+ let reach = st.doc.layers.iter().filter(|l| photocraft_compose::effects::has_effects(l)).map(photocraft_compose::effects::margin).max().unwrap_or(0);+ let damage = st.last_damage.expect("a stroke reports bounded damage").inflate(reach).intersect(&st.doc.bounds());+ let (w, h) = (st.doc.size.width, st.doc.size.height);+ let patch = photocraft_compose::render_reduced_damage(&st.doc, w, h, damage);+ for y in patch.rect.y0..patch.rect.y1 {+ for x in patch.rect.x0..patch.rect.x1 {+ let i = (y * w as i32 + x) as usize;+ shown.px[i] = patch.get(x, y);+ }+ }+}++fn session(effect: &str, params: serde_json::Value) -> Session {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 160, "height": 80, "background": "white"})).unwrap();+ s.execute("layer.new.layer", json!({})).unwrap();+ s.execute(effect, params).unwrap();+ s+}++const GREY: &str = "#808080";++/// Each stroke redrawn over the last cold render equals a cold render after it.+fn strokes_redraw_like_a_cold_render(mut s: Session, strokes: &[serde_json::Value]) {+ s.execute("paint.stroke", json!({"points": [[20, 20], [40, 30]], "size": 12, "hardness": 1.0, "color": GREY})).unwrap();+ for (i, p) in strokes.iter().enumerate() {+ let st = s.active().unwrap();+ let mut shown = photocraft_compose::render(&st.doc, st.doc.bounds());+ s.execute("paint.stroke", p.clone()).unwrap();+ redraw_damage(&mut shown, &s);+ let st = s.active().unwrap();+ let cold = photocraft_compose::render(&st.doc, st.doc.bounds());+ let worst = shown.px.iter().zip(&cold.px).map(|(a, b)| (0..4).map(|c| (a[c] - b[c]).abs()).fold(0.0f32, f32::max)).fold(0.0f32, f32::max);+ assert!(worst < 1e-6, "after stroke {i} the redrawn canvas differs from a cold render by {worst}");+ }+}++#[test]+fn a_gradient_overlay_is_laid_out_again_after_each_stroke() {+ let s = session("layer.layerStyle.gradientOverlay", json!({"from": "#ff0000", "to": "#0000ff", "angle": 0}));+ strokes_redraw_like_a_cold_render(+ s,+ &[+ // Far from the first: the layer grows to the right and down.+ json!({"points": [[120, 50], [140, 64]], "size": 12, "hardness": 1.0, "color": GREY}),+ // Up and to the left of both.+ json!({"points": [[6, 6], [10, 8]], "size": 6, "hardness": 1.0, "color": GREY}),+ // Erasing the far stroke shrinks the layer again.+ json!({"points": [[110, 40], [150, 74]], "size": 40, "hardness": 1.0, "erase": true}),+ ],+ );+}++#[test]+fn a_stroke_inside_the_layer_keeps_its_own_damage() {+ let mut s = session("layer.layerStyle.gradientOverlay", json!({"from": "#ff0000", "to": "#0000ff", "angle": 0}));+ s.execute("paint.stroke", json!({"points": [[10, 10], [150, 70]], "size": 12, "hardness": 1.0, "color": GREY})).unwrap();+ // Within the layer's bounds: the gradient's frame stays, so only the stroke repaints.+ let r = s.execute("paint.stroke", json!({"points": [[60, 40], [70, 40]], "size": 6, "hardness": 1.0, "color": GREY})).unwrap();+ let d = &r["damage"];+ let reported = photocraft_geom::Rect::new(+ d[0].as_i64().unwrap() as i32,+ d[1].as_i64().unwrap() as i32,+ (d[0].as_i64().unwrap() + d[2].as_i64().unwrap()) as i32,+ (d[1].as_i64().unwrap() + d[3].as_i64().unwrap()) as i32,+ );+ assert_eq!(s.active().unwrap().last_damage, Some(reported));+}++#[test]+fn effects_not_laid_out_over_the_layer_keep_the_stroke_damage() {+ let mut s = session("layer.layerStyle.colorOverlay", json!({"color": "#00ff00"}));+ s.execute("paint.stroke", json!({"points": [[20, 20], [40, 30]], "size": 12, "hardness": 1.0, "color": GREY})).unwrap();+ s.execute("paint.stroke", json!({"points": [[120, 50], [140, 64]], "size": 12, "hardness": 1.0, "color": GREY})).unwrap();+ let d = s.active().unwrap().last_damage.unwrap();+ assert!(d.x0 >= 100, "a Color Overlay repaints only the stroke: {d:?}");+}diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex db11fc730..474864746 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -516,12 +516,22 @@ pub(crate) struct CommittedStroke {pub(crate) revision: u64,key: u64,damage: Vec<DRect>,+ /// What the commit repaints beyond the stroke whatever a cache showed: the layer's whole+ /// composite when effects laid out over its frame moved with it (a Gradient Overlay spans the+ /// grown layer, #4053; `photocraft_compose::relayout_damage`).+ relayout: DRect,}impl CommittedStroke {#[cfg(test)]pub(crate) fn for_test(key: u64, damage: Vec<DRect>) -> Self {- Self { doc: photocraft_doc::DocId(0), revision: 0, key, damage }+ Self { doc: photocraft_doc::DocId(0), revision: 0, key, damage, relayout: DRect::EMPTY }+ }++ /// The raw preview key of the live stroke's last step: what a cache showed at release.+ #[cfg(test)]+ pub(crate) fn last_key(&self) -> u64 {+ self.key + self.damage.len() as u64}/// What a cache that showed raw preview `key` of this stroke at the revision before misses.@@ -1472,6 +1482,13 @@ pub(crate) fn damage_since(app: &PhotocraftApp, idx: usize, seen: (u64, u64), no&& let Some(c) = app.committed_stroke.as_ref().filter(|c| c.doc == st.doc.id && c.revision == now.0)&& let Some(r) = c.since(seen.1 ^ display_key){+ let r = if c.relayout.is_empty() {+ r+ } else if r.is_empty() {+ c.relayout+ } else {+ r.union(&c.relayout)+ };return Some(if r.is_empty() { r } else { r.inflate(effect_reach(&st.doc.layers)) });}if seen.1 == now.1 ^ display_key && seen.0 + 1 == now.0 {@@ -5845,6 +5862,7 @@ fn commit_brush_stroke(app: &mut PhotocraftApp, d: &Drag) {}}let LiveStroke { stroke, doc, key, damage, .. } = l;+ let before = app.session.documents().iter().find(|st| st.doc.id == doc).map(|st| st.doc.clone());if let EngineStroke::Brush(stroke) = stroke&& app.session.offer_live_stroke(*stroke).is_err(){@@ -5855,14 +5873,15 @@ fn commit_brush_stroke(app: &mut PhotocraftApp, d: &Drag) {app.stroke_trace.stroke(crate::gpu_canvas::now_ms() - started);app.session.clear_live_stroke();let Ok(r) = result else { return };- let revision = app.session.documents().iter().find(|st| st.doc.id == doc).map(|st| st.revision);+ let after = app.session.documents().iter().find(|st| st.doc.id == doc).map(|st| (st.revision, st.doc.clone()));if r.get("fromLive").and_then(serde_json::Value::as_bool) == Some(true)- && let Some(revision) = revision+ && let Some((revision, after)) = after{- app.committed_stroke = Some(CommittedStroke { doc, revision, key, damage });+ let relayout = before.map_or(DRect::EMPTY, |b| photocraft_compose::relayout_damage(&b, &after));+ app.committed_stroke = Some(CommittedStroke { doc, revision, key, damage, relayout });} else {// Rendered again from scratch: the commit's damage rect refreshes the stroke.- let shown = CommittedStroke { doc, revision: 0, key, damage };+ let shown = CommittedStroke { doc, revision: 0, key, damage, relayout: DRect::EMPTY };// Raw preview key 0 = the document itself (its colour display folded in).shown_as_document(app, doc, |k| shown.since(k).is_some());}diff --git a/crates/ui-egui/src/stroke_timing_tests.rs b/crates/ui-egui/src/stroke_timing_tests.rsindex a472a4125..88f218c3b 100644--- a/crates/ui-egui/src/stroke_timing_tests.rs+++ b/crates/ui-egui/src/stroke_timing_tests.rs@@ -338,6 +338,38 @@ fn a_committed_stroke_refreshes_only_what_each_cache_had_not_shown() {assert_eq!(c.since(99), None, "not a key of this stroke");}+/// A stroke that grows a layer with a Gradient Overlay lays the one gradient out again over the+/// whole layer (#4053): the canvas, which already showed the live stroke, still repaints where+/// the earlier strokes are, not just the new stroke's own pixels (it repainted nothing, leaving+/// one gradient per stroke).+#[test]+fn a_committed_stroke_repaints_a_gradient_overlay_over_the_whole_layer() {+ let mut h = harness();+ h.state_mut().run("layer.new.layer", json!({})).unwrap();+ h.state_mut().run("layer.layerStyle.gradientOverlay", json!({"from": "#ff0000", "to": "#0000ff", "angle": 0})).unwrap();+ h.state_mut().run("tools.setBrush", json!({"brush": {"size": 10, "hardness": 1.0}})).unwrap();+ let drag = |h: &mut Harness<'static, PhotocraftApp>, pts: &[(f32, f32)]| {+ move_to(h, pts[0].0, pts[0].1);+ button(h, pts[0].0, pts[0].1, true);+ for (x, y) in &pts[1..] {+ move_to(h, *x, *y);+ }+ let (x, y) = pts[pts.len() - 1];+ button(h, x, y, false);+ h.run_steps(2);+ };+ drag(&mut h, &[(20.0, 20.0), (30.0, 25.0), (40.0, 30.0)]);+ drag(&mut h, &[(150.0, 60.0), (160.0, 70.0), (170.0, 80.0)]);+ let app = h.state();+ let idx = app.session.active_index().unwrap();+ let st = app.session.active().unwrap();+ let c = app.committed_stroke.as_ref().expect("the commit took the live stroke's pixels");+ assert_eq!(c.revision, st.revision);+ // A cache that showed the live stroke's last step.+ let missed = crate::canvas::damage_since(app, idx, (st.revision - 1, c.last_key()), (st.revision, 0), 0, st.last_damage).unwrap();+ assert!(missed.contains(25, 25), "the gradient around the first stroke is repainted: {missed:?}");+}+#[test]fn the_stroke_trace_times_each_frame_of_a_stroke_and_ends_on_release() {// The app's hooks around the canvas (`raw_input_hook` starts a frame, `ui` ends it); the