From 4c586aba1f4464950df116cc8f9e3173bbbd5a6e Mon Sep 17 00:00:00 2001 From: qvest-ssels <214787280+qvest-ssels@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:10:45 +0100 Subject: [PATCH] fix(paint): History Brush restores transparency instead of painting over (#14701) In Normal mode the History Brush composited the source state over the current pixels, so a transparent area in the source could not clear what was painted or moved there since, and a moved subject stayed visible as a second image. It now mixes the source into the pixels at the brush weight (premultiplied, alpha included), in the commit and in the live stroke. Other modes and locked transparency composite as before. --- crates/engine/src/cmd/retouch_cmds.rs | 2 +- crates/engine/src/cmd/retouch_cmds/clone.rs | 6 +- crates/engine/src/cmd/retouch_cmds/heal.rs | 8 +- .../history_brush_transparency_tests.rs | 107 ++++++++++++++++++ crates/paint/src/retouch.rs | 38 ++++++- 5 files changed, 156 insertions(+), 5 deletions(-) create mode 100644 crates/engine/src/cmd/retouch_cmds/history_brush_transparency_tests.rs diff --git a/crates/engine/src/cmd/retouch_cmds.rs b/crates/engine/src/cmd/retouch_cmds.rs index 6c891b84495..3af08d9c98c 100644 --- a/crates/engine/src/cmd/retouch_cmds.rs +++ b/crates/engine/src/cmd/retouch_cmds.rs @@ -16,7 +16,7 @@ use photocraft_algo::retouch::{ToneRange, dodge_burn, local_blur, local_sharpen, use photocraft_color::{BlendMode, PixelFormat, SampleType}; use photocraft_doc::{Document, LayerContent, LayerId}; use photocraft_geom::Rect; -use photocraft_paint::retouch::{Footprint, Region, Smudge, alpha_index, apply_coverage, apply_dab_stroke}; +use photocraft_paint::retouch::{Footprint, Region, Smudge, alpha_index, apply_coverage, apply_dab_stroke, restore_coverage}; use photocraft_paint::{BrushSettings, Stroke, StrokePoint}; use photocraft_raster::{Surface, from_rgba_into, to_rgba}; use rayon::prelude::*; diff --git a/crates/engine/src/cmd/retouch_cmds/clone.rs b/crates/engine/src/cmd/retouch_cmds/clone.rs index ada043ade49..6eb13ef6a9b 100644 --- a/crates/engine/src/cmd/retouch_cmds/clone.rs +++ b/crates/engine/src/cmd/retouch_cmds/clone.rs @@ -4,7 +4,7 @@ use super::sampling::{SampleLayers, sample_layers}; use super::{ BlendMode, BrushSettings, Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, SampleType, Session, Stroke, StrokePoint, Surface, Value, alpha_index, apply_coverage, bad, blend_from_str, coverage, damage_json, flag, has_pixel_layer, json, parse_brush, pattern_stamp, periodic, point, - reject_huge_stroke, run_stroke, to_rgba, + reject_huge_stroke, restore_coverage, run_stroke, to_rgba, }; /// Where a clone stroke samples: `offset` / `source` params, else the active Clone Source slot, @@ -512,10 +512,14 @@ impl LiveRetouch { // The Pattern Stamp's Behind goes beneath the pixels, as its commit lays it. let behind = matches!(self.paint, LivePaint::Pattern { behind: true, .. }); let clone = matches!(self.paint, LivePaint::Clone { .. }); + let history = matches!(self.paint, LivePaint::History(_)); let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?; surf.write_region(r, &self.pre_surf.read_region(r)); let damage = if clone { apply_clone_coverage(surf, r, cov, self.opacity, self.sel.as_ref(), self.lock, &paint, self.mode) + } else if history { + // As the commit paints it (`heal::history_brush`): the source state replaces the pixels. + restore_coverage(surf, r, cov, self.opacity, self.sel.as_ref(), self.lock, &paint, self.mode) } else { pattern_stamp::lay_coverage(surf, r, cov, self.opacity, self.sel.as_ref(), self.lock, &paint, self.mode, behind) }; diff --git a/crates/engine/src/cmd/retouch_cmds/heal.rs b/crates/engine/src/cmd/retouch_cmds/heal.rs index 9388258ef72..97955cac24b 100644 --- a/crates/engine/src/cmd/retouch_cmds/heal.rs +++ b/crates/engine/src/cmd/retouch_cmds/heal.rs @@ -3,7 +3,7 @@ use super::periodic; use super::sampling::{SampleLayers, composite_region, sample_all_layers, sample_layers}; use super::{ BlendMode, CompleteParams, Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, Session, Stroke, Surface, Value, apply_coverage, bad, - coverage, damage_json, flag, inpaint, json, parse_brush, poisson, reject_huge_stroke, run_stroke, string, + coverage, damage_json, flag, inpaint, json, parse_brush, poisson, reject_huge_stroke, restore_coverage, run_stroke, string, }; /// Grow a stroke's coverage map by `m` pixels of zero coverage (a Dirichlet boundary for the solve). @@ -172,7 +172,7 @@ pub(super) fn history_brush(s: &mut Session, p: &Value) -> Result { let src = if src_surface.format() == fmt { src_surface } else { src_surface.convert(fmt) }; let (bounds, cov) = coverage(CMD, &stroke)?; let paint = Region::read(&src, bounds); - Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode)) + Ok(restore_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode)) })?; let mut r = json!({ "damage": damage_json(dmg) }); if from_live { @@ -314,3 +314,7 @@ pub(super) fn spot_healing(s: &mut Session, p: &Value) -> Result { #[cfg(test)] #[path = "heal_indexed_tests.rs"] mod heal_indexed_tests; + +#[cfg(test)] +#[path = "history_brush_transparency_tests.rs"] +mod history_brush_transparency_tests; diff --git a/crates/engine/src/cmd/retouch_cmds/history_brush_transparency_tests.rs b/crates/engine/src/cmd/retouch_cmds/history_brush_transparency_tests.rs new file mode 100644 index 00000000000..7f57a168b20 --- /dev/null +++ b/crates/engine/src/cmd/retouch_cmds/history_brush_transparency_tests.rs @@ -0,0 +1,107 @@ +//! #14701: the History Brush in Normal mode restores the source state's pixels, transparency +//! included, instead of laying them over what is there now. Painting a moved subject's new place +//! from the state before the move clears it again (no "ghost" double image), at the stroke's +//! opacity, and the live stroke shows what the commit paints. Other modes still composite. + +use serde_json::json; + +use super::*; + +const W: i32 = 48; +const H: i32 = 16; +const RED: [f32; 4] = [0.8, 0.1, 0.1, 1.0]; + +/// A `depth` RGB document with a layer over the Background holding a red subject on its left +/// half (History row 2), then the subject moved to the right half (row 3, the current state). +fn moved(depth: u64) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": W, "height": H, "depth": depth, "mode": "rgb"})).unwrap(); + s.execute("layer.new.layer", json!({})).unwrap(); + for left in [true, false] { + s.edit("setup", |doc, active| { + let b = doc.bounds(); + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let fmt = surf.format(); + let data: Vec = (b.y0..b.y1) + .flat_map(|y| (b.x0..b.x1).map(move |x| (x, y))) + .flat_map(|(x, _)| photocraft_raster::from_rgba(&fmt, if (x < W / 2) == left { RED } else { [0.0; 4] })) + .collect(); + surf.write_region(b, &data); + Ok(()) + }) + .unwrap(); + } + s +} + +/// A stroke across the whole layer from History row 2 (the subject still on the left). +fn stroke(extra: Value) -> Value { + let mut p = json!({"points": [[0, 8], [W, 8]], "size": 40, "hardness": 100, "state": 2}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) { + p.extend(extra.clone()); + } + p +} + +fn layer_rgba(doc: &Document, s: &Session, x: i32, y: i32) -> [f32; 4] { + doc.layer(s.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().rgba(x, y) +} + +fn close(a: [f32; 4], b: [f32; 4], tol: f32) -> bool { + a.iter().zip(b).all(|(a, b)| (a - b).abs() <= tol) +} + +#[test] +fn history_brush_restores_transparency_from_the_source_state() { + for depth in [8u64, 16, 32] { + let mut s = moved(depth); + s.execute("paint.historyBrush", stroke(json!({}))).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let (left, right) = (layer_rgba(&doc, &s, 8, 8), layer_rgba(&doc, &s, 40, 8)); + assert!(close(left, RED, 0.01), "depth {depth}: the subject comes back on the left: {left:?}"); + assert!(right[3] < 0.01, "depth {depth}: the moved subject is cleared, no ghost: {right:?}"); + } +} + +#[test] +fn history_brush_restores_transparency_at_the_stroke_opacity() { + for depth in [8u64, 16, 32] { + let mut s = moved(depth); + s.execute("paint.historyBrush", stroke(json!({"opacity": 50}))).unwrap(); + let doc = s.active().unwrap().doc.clone(); + let (left, right) = (layer_rgba(&doc, &s, 8, 8), layer_rgba(&doc, &s, 40, 8)); + assert!((left[3] - 0.5).abs() < 0.01 && close([left[0], left[1], left[2], 1.0], RED, 0.01), "depth {depth}: half the subject back: {left:?}"); + assert!((right[3] - 0.5).abs() < 0.01 && close([right[0], right[1], right[2], 1.0], RED, 0.01), "depth {depth}: half cleared: {right:?}"); + } +} + +#[test] +fn live_history_brush_shows_the_restored_transparency() { + for depth in [8u64, 32] { + let s = moved(depth); + let live = super::super::LiveRetouch::begin(&s, "paint.historyBrush", &stroke(json!({}))).unwrap(); + let (left, right) = (layer_rgba(&live.doc, &s, 8, 8), layer_rgba(&live.doc, &s, 40, 8)); + assert!(close(left, RED, 0.01), "depth {depth}: {left:?}"); + assert!(right[3] < 0.01, "depth {depth}: the live stroke clears the moved subject: {right:?}"); + } +} + +#[test] +fn other_modes_and_locked_transparency_keep_compositing() { + // Multiply of a transparent source changes nothing: the moved subject stays. + let mut s = moved(8); + s.execute("paint.historyBrush", stroke(json!({"mode": "multiply"}))).unwrap(); + let doc = s.active().unwrap().doc.clone(); + assert!(close(layer_rgba(&doc, &s, 40, 8), RED, 0.01)); + // Locked transparency keeps the layer's alpha: nothing to clear, nothing to restore. + let mut s = moved(8); + s.edit("lock", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().locks.transparency = true; + Ok(()) + }) + .unwrap(); + s.execute("paint.historyBrush", stroke(json!({}))).unwrap(); + let doc = s.active().unwrap().doc.clone(); + assert!(close(layer_rgba(&doc, &s, 40, 8), RED, 0.01)); + assert!(layer_rgba(&doc, &s, 8, 8)[3] < 0.01); +} diff --git a/crates/paint/src/retouch.rs b/crates/paint/src/retouch.rs index 9ab36bf2def..2fa370367d8 100644 --- a/crates/paint/src/retouch.rs +++ b/crates/paint/src/retouch.rs @@ -202,6 +202,39 @@ pub fn apply_coverage( lock_transparency: bool, paint: &Region, blend: BlendMode, +) -> Rect { + composite_coverage(target, rect, cov, opacity, selection, lock_transparency, paint, blend, false) +} + +/// [`apply_coverage`] for the History Brush (#14701): in Normal mode the paint image *replaces* +/// the pixels at the per-pixel weight (a premultiplied mix, alpha included), so a transparent +/// source pixel clears what is there instead of leaving it under the restored pixels. Other +/// modes, locked transparency and targets without alpha composite as [`apply_coverage`] does. +#[allow(clippy::too_many_arguments)] +pub fn restore_coverage( + target: &mut Surface, + rect: Rect, + cov: &[f32], + opacity: f32, + selection: Option<&Surface>, + lock_transparency: bool, + paint: &Region, + blend: BlendMode, +) -> Rect { + composite_coverage(target, rect, cov, opacity, selection, lock_transparency, paint, blend, true) +} + +#[allow(clippy::too_many_arguments)] +fn composite_coverage( + target: &mut Surface, + rect: Rect, + cov: &[f32], + opacity: f32, + selection: Option<&Surface>, + lock_transparency: bool, + paint: &Region, + blend: BlendMode, + replace: bool, ) -> Rect { if rect.is_empty() { return Rect::EMPTY; @@ -237,7 +270,10 @@ pub fn apply_coverage( } let src = paint.px(x, y); if blend == BlendMode::Normal { - over_native(&fmt, px, src, k, lock_transparency); + match a { + Some(a) if replace && !lock_transparency => mix_premultiplied(px, src, a, k), + _ => over_native(&fmt, px, src, k, lock_transparency), + } } else { // A transparent source cannot paint. Skip it before an RGB round trip changes // untouched native CMYK/Lab values; Normal handles zero weight in over_native.