Skip to content

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

Pattern Stamp and Background Eraser draw live; Spot Healing shows its heal area (TOOL-213-7, #3754)

David Mann086a82d547b1
diff --git a/crates/engine/src/eraser_cmds.rs b/crates/engine/src/eraser_cmds.rs
index 98169aff7..0d6af8770 100644
--- a/crates/engine/src/eraser_cmds.rs
+++ b/crates/engine/src/eraser_cmds.rs
@@ -11,7 +11,7 @@ use photocraft_algo::selection as sel;
use photocraft_doc::{Document, Layer, LayerContent, LayerId};
use photocraft_geom::Rect;
use photocraft_paint::Stroke;
-use photocraft_paint::bg_erase::{BgEraseSettings, apply_background_eraser};
+use photocraft_paint::bg_erase::{BgEraseSettings, apply_background_eraser, background_eraser_effect, background_eraser_stroke};
use photocraft_paint::replace::{Limits, Sampling};
use serde_json::{Value, json};
@@ -126,8 +126,9 @@ fn magic_eraser(s: &mut Session, p: &Value) -> Result<Value> {
Ok(damage(s, dmg, true))
}
-/// `paint.backgroundEraser`: a stroke erasing colours similar to the sampled one.
-fn background_eraser(s: &mut Session, p: &Value) -> Result<Value> {
+/// The stroke, settings and layer of a `paint.backgroundEraser` (shared by the command and its
+/// live preview), after the same checks.
+fn background_eraser_setup(s: &Session, p: &Value) -> Result<(Stroke, BgEraseSettings, LayerId)> {
const CMD: &str = "paint.backgroundEraser";
let pts = crate::brush_cmds::parse_points(p, CMD)?;
if pts.iter().any(|q| !q.x.is_finite() || !q.y.is_finite() || q.x.abs() > 1e7 || q.y.abs() > 1e7) {
@@ -143,17 +144,21 @@ fn background_eraser(s: &mut Session, p: &Value) -> Result<Value> {
background: s.tools.background,
};
let id = active_pixel_layer(s, CMD)?;
- {
- let d = s.active().ok_or(EngineError::NoDocument)?;
- let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?;
- if let Some(e) = pixels_locked(&d.doc, l) {
- return Err(e);
- }
- if d.doc.effective_locks(id).transparency && !is_background(l) {
- return Err(EngineError::Other(format!("Could not use the Background Eraser because the transparency of layer \"{}\" is locked", l.name)));
- }
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let l = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?;
+ if let Some(e) = pixels_locked(&d.doc, l) {
+ return Err(e);
+ }
+ if d.doc.effective_locks(id).transparency && !is_background(l) {
+ return Err(EngineError::Other(format!("Could not use the Background Eraser because the transparency of layer \"{}\" is locked", l.name)));
}
- let stroke = Stroke { brush, points: pts };
+ Ok((Stroke { brush, points: pts }, bs, id))
+}
+
+/// `paint.backgroundEraser`: a stroke erasing colours similar to the sampled one.
+fn background_eraser(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "paint.backgroundEraser";
+ let (stroke, bs, id) = background_eraser_setup(s, p)?;
let dmg = s.edit("Background Eraser", |doc, _| {
let selection = doc.selection.clone();
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
@@ -164,6 +169,23 @@ fn background_eraser(s: &mut Session, p: &Value) -> Result<Value> {
Ok(damage(s, dmg, true))
}
+/// A `paint.backgroundEraser` stroke shown while it is drawn: the same params, checks and
+/// erasing per dab as the commit (on a Background already turned into a normal layer), so the
+/// preview at the last point is the committed result.
+pub fn live_background_eraser(s: &Session, p: &Value) -> Result<crate::retouch_cmds::LiveDab> {
+ const CMD: &str = "paint.backgroundEraser";
+ let (stroke, bs, id) = background_eraser_setup(s, p)?;
+ let mut doc = (*s.active().ok_or(EngineError::NoDocument)?.doc).clone();
+ unlock_background(doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?);
+ let stroke = background_eraser_stroke(&stroke);
+ crate::retouch_cmds::LiveDab::with_effect_on(doc, CMD, &json!({}), stroke, Some(id), 0, true, |pre| match background_eraser_effect(pre.format(), &bs) {
+ Some(effect) => Box::new(effect),
+ // No alpha: the commit erases nothing either.
+ None => Box::new(|_: &mut photocraft_paint::retouch::Region, _: &photocraft_paint::retouch::Footprint| {}),
+ })?
+ .with_tail_preview()
+}
+
/// Eraser-group command specs.
pub fn specs() -> Vec<CommandSpec> {
vec![
diff --git a/crates/engine/src/eraser_cmds/tests.rs b/crates/engine/src/eraser_cmds/tests.rs
index 1946f346f..07866aa72 100644
--- a/crates/engine/src/eraser_cmds/tests.rs
+++ b/crates/engine/src/eraser_cmds/tests.rs
@@ -275,3 +275,58 @@ fn bench_magic_eraser_24mp() {
let t3 = t0.elapsed().as_secs_f64() * 1000.0;
println!("phases: sample {t1:.1} ms, wand {:.1} ms, erase {:.1} ms", t2 - t1, t3 - t2);
}
+
+/// The live Background Eraser shows exactly what the commit erases, fed point by point: on the
+/// Background (which the commit turns into a normal layer first), with every sampling mode, at
+/// 8 and 16 bits (the live working pixels are floats between dabs, as the commit's are).
+#[test]
+fn live_background_eraser_matches_the_commit() {
+ let all = [[6.0, 20.0], [18.0, 22.0], [30.0, 18.0], [44.0, 24.0], [56.0, 20.0]];
+ for depth in [8, 16] {
+ for sampling in ["continuous", "once", "backgroundSwatch"] {
+ let mut s = session("rgb", depth);
+ s.execute("tools.setColors", json!({"background": "#000000"})).unwrap();
+ let opts = |pts: &[[f64; 2]]| json!({"points": pts, "size": 14, "hardness": 0.6, "sampling": sampling, "limits": "discontiguous", "tolerance": 30, "seed": 7});
+ let (doc, h) = (s.active().unwrap().doc.clone(), history_len(&s));
+ let mut live = live_background_eraser(&s, &opts(&all[..1])).unwrap();
+ for q in &all[1..] {
+ live.push(&[photocraft_paint::StrokePoint::new(q[0], q[1], 1.0)]).unwrap();
+ }
+ let st = s.active().unwrap();
+ assert!(std::sync::Arc::ptr_eq(&doc, &st.doc) && history_len(&s) == h, "the preview leaves the document alone");
+ let id = st.active_layer.unwrap();
+ let shown = live.doc.layer(id).unwrap().surface().unwrap().clone();
+ s.execute("paint.backgroundEraser", opts(&all)).unwrap();
+ assert_eq!(history_len(&s), h + 1, "one History step");
+ let mut erased = false;
+ for y in 0..48 {
+ for x in 0..64 {
+ let (got, want) = (shown.rgba(x, y), surface(&s).rgba(x, y));
+ erased |= want[3] < 0.5;
+ // The colour under a fully erased pixel doesn't show.
+ if got[3] == 0.0 && want[3] == 0.0 {
+ continue;
+ }
+ assert_eq!(got, want, "{sampling} {depth}-bit ({x}, {y})");
+ }
+ }
+ assert!(erased, "{sampling} {depth}: the stroke erased something");
+ }
+ }
+}
+
+#[test]
+fn live_background_eraser_refuses_what_the_command_refuses() {
+ let mut s = session("rgb", 8);
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("layer.setProps", json!({"locks": {"transparency": true}})).unwrap();
+ let p = json!({"points": [[20, 20]]});
+ assert!(live_background_eraser(&s, &p).is_err());
+ assert!(s.execute("paint.backgroundEraser", p).is_err());
+ let s = session("rgb", 8);
+ for p in [json!({}), json!({"points": []}), json!({"points": [[f64::NAN, 0]]}), json!({"points": [[1e300, 0]]}), json!({"points": [[0, 0]], "sampling": 3})]
+ {
+ assert!(live_background_eraser(&s, &p).is_err(), "{p}");
+ }
+ assert!(live_background_eraser(&Session::new(), &json!({"points": [[0, 0]]})).is_err());
+}
diff --git a/crates/engine/src/retouch_cmds.rs b/crates/engine/src/retouch_cmds.rs
index 0da474c22..b96ddea8c 100644
--- a/crates/engine/src/retouch_cmds.rs
+++ b/crates/engine/src/retouch_cmds.rs
@@ -26,6 +26,7 @@ use crate::{EngineError, Result, Session};
mod content_aware_move;
mod patch;
mod pattern_stamp;
+pub use pattern_stamp::live_impressionist as live_pattern_impressionist;
mod remove;
pub use patch::preview as patch_preview;
@@ -315,6 +316,9 @@ enum LivePaint {
Clone { which: SampleLayers, map: crate::presets::clone_source::Mapping, cmd: &'static str },
/// The History Brush's history state.
History(Surface),
+ /// The Pattern Stamp's pattern, tiled from its aligned placement (Impressionist strokes are
+ /// laid dab by dab: `pattern_stamp::live_impressionist`).
+ Pattern { tile: std::sync::Arc<photocraft_compose::pattern::Tile>, place: photocraft_compose::pattern::Placement },
}
/// A retouching stroke shown while it is drawn: the dabs so far composited onto a copy of the
@@ -340,10 +344,19 @@ pub struct LiveRetouch {
}
impl LiveRetouch {
- /// Start a live stroke of `cmd` (`paint.cloneStamp`, `paint.healingBrush` or
- /// `paint.historyBrush`) from its params; their `points` are rendered.
+ /// Start a live stroke of `cmd` (`paint.cloneStamp`, `paint.healingBrush`,
+ /// `paint.historyBrush` or an aligned, non-Impressionist `paint.patternStamp`) from its
+ /// params; their `points` are rendered.
pub fn begin(s: &Session, cmd: &str, p: &Value) -> Result<Self> {
has_pixel_layer(s).map_err(EngineError::Other)?;
+ if cmd == "paint.patternStamp" {
+ let st = pattern_stamp::Setup::parse(s, p)?;
+ if st.impressionist {
+ return Err(bad(cmd, "Impressionist strokes are laid dab by dab (pattern_stamp::live_impressionist)"));
+ }
+ let paint = LivePaint::Pattern { place: st.placement(), tile: st.tile };
+ return Self::with_paint(s, cmd, p, st.stroke, st.id, paint, st.mode);
+ }
let (stroke, id) = parse_brush(s, p, cmd)?;
let mode = blend_param(p, cmd)?;
let paint = match cmd {
@@ -356,8 +369,13 @@ impl LiveRetouch {
}
}
"paint.historyBrush" => LivePaint::History(history_source(s, id, p, cmd)?),
- other => return Err(bad(other, "live retouching strokes are the Clone Stamp, Healing Brush and History Brush")),
+ other => return Err(bad(other, "live retouching strokes are the Clone Stamp, Healing Brush, History Brush and Pattern Stamp")),
};
+ Self::with_paint(s, cmd, p, stroke, id, paint, mode)
+ }
+
+ /// Start a live stroke of `cmd` painting `paint` through `stroke`'s coverage.
+ fn with_paint(s: &Session, cmd: &str, p: &Value, stroke: Stroke, id: Option<LayerId>, paint: LivePaint, mode: BlendMode) -> Result<Self> {
let pre = s.active().ok_or(EngineError::NoDocument)?.doc.clone();
let mut doc = (*pre).clone();
let sel = doc.selection.clone();
@@ -432,6 +450,7 @@ impl LiveRetouch {
let paint = match &self.paint {
LivePaint::Clone { which, map, cmd } => clone_sample(&self.pre, self.id, &self.pre_surf, *which, r, map, cmd)?,
LivePaint::History(src) => Region::read(src, r),
+ LivePaint::Pattern { tile, place } => pattern_stamp::paint_region(tile, place, &self.pre_surf.format(), r),
};
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));
@@ -899,6 +918,52 @@ fn dab_cmd(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
Ok(json!({ "damage": damage_json(dmg) }))
}
+/// The working pixels of a [`LiveDab`]: a copy of the target in its own depth, or (`precise`)
+/// float pixels copied from it a tile at a time as dabs first reach them, so only the stroke's
+/// area is ever copied.
+struct WorkPixels {
+ surf: Surface,
+ /// Tiles (`TILE` px) copied from the target so far; `None` when `surf` is a full copy.
+ filled: Option<std::collections::HashSet<(i32, i32)>>,
+}
+
+impl WorkPixels {
+ const TILE: i32 = 64;
+
+ fn new(pre: &Surface, precise: bool) -> Self {
+ if precise {
+ let f = pre.format();
+ let fmt = PixelFormat::new(f.mode, SampleType::F32, f.alpha);
+ Self { surf: Surface::new(fmt), filled: Some(std::collections::HashSet::new()) }
+ } else {
+ Self { surf: pre.clone(), filled: None }
+ }
+ }
+
+ /// The working pixels of `r` (`pre` = the target before the stroke).
+ fn read(&mut self, pre: &Surface, r: Rect) -> Region {
+ if let Some(filled) = &mut self.filled
+ && !r.is_empty()
+ {
+ let t = Self::TILE;
+ for ty in r.y0.div_euclid(t)..=(r.y1 - 1).div_euclid(t) {
+ for tx in r.x0.div_euclid(t)..=(r.x1 - 1).div_euclid(t) {
+ if filled.insert((tx, ty)) {
+ let cell = Rect::new(tx * t, ty * t, tx * t + t, ty * t + t);
+ // Normalised samples, stored unrounded as floats.
+ self.surf.write_region(cell, &pre.read_region(cell));
+ }
+ }
+ }
+ }
+ Region::read(&self.surf, r)
+ }
+
+ fn write(&mut self, region: &Region) {
+ region.write(&mut self.surf);
+ }
+}
+
/// A Dodge, Burn, Sponge, Blur, Sharpen or Smudge stroke shown while it is drawn: each new dab
/// runs the tool's effect on a working copy of the target, in order, and the changed area is
/// mixed back over the original at the brush opacity, as `apply_dab_stroke` does on release.
@@ -912,7 +977,7 @@ pub struct LiveDab {
effect: DabEffect,
halo: i32,
pre_surf: Surface,
- work: Surface,
+ work: WorkPixels,
id: Option<LayerId>,
params: Value,
opacity: f32,
@@ -952,7 +1017,25 @@ impl LiveDab {
halo: i32,
effect: impl FnOnce(&Surface) -> DabEffect,
) -> Result<Self> {
- let mut doc = (*s.active().ok_or(EngineError::NoDocument)?.doc).clone();
+ let doc = (*s.active().ok_or(EngineError::NoDocument)?.doc).clone();
+ Self::with_effect_on(doc, cmd, p, stroke, id, halo, false, effect)
+ }
+
+ /// [`Self::with_effect`] on `doc`, a copy of the active document with what the commit's own
+ /// edit does first (the Background Eraser's Background turned into a normal layer, say). With
+ /// `precise` the working pixels between dabs are kept as floats, as the commit keeps them, so
+ /// the preview is the commit at any depth (else they are stored in the target's depth).
+ #[allow(clippy::too_many_arguments)]
+ pub(crate) fn with_effect_on(
+ mut doc: Document,
+ cmd: &str,
+ p: &Value,
+ stroke: Stroke,
+ id: Option<LayerId>,
+ halo: i32,
+ precise: bool,
+ effect: impl FnOnce(&Surface) -> DabEffect,
+ ) -> Result<Self> {
let sel = doc.selection.clone();
let (surf, lock) = crate::channel_cmds::target_surface(&mut doc, id, p)?;
let pre_surf = surf.clone();
@@ -966,7 +1049,7 @@ impl LiveDab {
done: 0,
effect,
halo,
- work: pre_surf.clone(),
+ work: WorkPixels::new(&pre_surf, precise),
pre_surf,
id,
params: p.clone(),
@@ -1006,9 +1089,9 @@ impl LiveDab {
if r.is_empty() {
continue;
}
- let mut region = Region::read(&self.work, r.inflate(self.halo));
+ let mut region = self.work.read(&self.pre_surf, r.inflate(self.halo));
(self.effect)(&mut region, &ctx.footprint(d, self.done + k));
- region.crop(r).write(&mut self.work);
+ self.work.write(&region.crop(r));
dmg = dmg.union(&r);
}
self.done += new.len();
@@ -1018,7 +1101,7 @@ impl LiveDab {
let ds = self.renderer.tail_dabs();
let r = ds.iter().fold(Rect::EMPTY, |a, d| a.union(&ctx.dab_rect(d, false)));
if !r.is_empty() {
- let mut region = Region::read(&self.work, r.inflate(self.halo));
+ let mut region = self.work.read(&self.pre_surf, r.inflate(self.halo));
for (k, d) in ds.iter().enumerate() {
(self.effect)(&mut region, &ctx.footprint(d, self.done + k));
}
@@ -1035,7 +1118,7 @@ impl LiveDab {
self.bounds = self.bounds.union(&dmg).union(&tail_rect);
let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?;
if !shown.is_empty() {
- let (orig, work) = (Region::read(&self.pre_surf, shown), Region::read(&self.work, shown));
+ let (orig, work) = (Region::read(&self.pre_surf, shown), self.work.read(&self.pre_surf, shown));
photocraft_paint::retouch::mix_back(surf, &orig, &work, shown, self.opacity, self.sel.as_ref(), self.lock);
}
if let Some((r, work)) = tail {
diff --git a/crates/engine/src/retouch_cmds/pattern_stamp.rs b/crates/engine/src/retouch_cmds/pattern_stamp.rs
index cb9e0adfe..3c0772baf 100644
--- a/crates/engine/src/retouch_cmds/pattern_stamp.rs
+++ b/crates/engine/src/retouch_cmds/pattern_stamp.rs
@@ -6,7 +6,7 @@
use photocraft_color::{BlendMode, PixelFormat};
use photocraft_compose::pattern::{Placement, Tile, render};
-use photocraft_doc::Pattern;
+use photocraft_doc::{LayerId, Pattern};
use photocraft_geom::Rect;
use photocraft_paint::retouch::{Footprint, Region, apply_coverage, apply_dab_stroke, over_native, stroke_coverage};
use photocraft_paint::{Stroke, StrokePoint};
@@ -29,53 +29,110 @@ pub(super) fn enabled(s: &Session) -> std::result::Result<(), String> {
if crate::pattern_cmds::resolve(s, "").is_none() { Err("no pattern selected".into()) } else { Ok(()) }
}
-pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
- const CMD: &str = "paint.patternStamp";
- let (mut stroke, id) = parse_brush(s, p, CMD)?;
- let mode = blend_param(p, CMD)?;
- let aligned = flag(p, "aligned", true);
- let impressionist = flag(p, "impressionist", false);
- let pat = crate::pattern_cmds::resolve_param(s, CMD, p)?;
- if pat.is_empty() {
- return Err(bad(CMD, "the pattern is empty"));
+/// A parsed `paint.patternStamp`: shared by the command and its live preview, so both paint the
+/// same stroke (seeded the same way) with the same tile and placement.
+pub(super) struct Setup {
+ pub(super) stroke: Stroke,
+ pub(super) id: Option<LayerId>,
+ pub(super) mode: BlendMode,
+ aligned: bool,
+ pub(super) impressionist: bool,
+ pat: Pattern,
+ pub(super) tile: std::sync::Arc<Tile>,
+ phase: (f32, f32),
+ scale: f32,
+ angle: f32,
+ seed: u64,
+}
+
+impl Setup {
+ pub(super) fn parse(s: &Session, p: &Value) -> Result<Self> {
+ const CMD: &str = "paint.patternStamp";
+ let (mut stroke, id) = parse_brush(s, p, CMD)?;
+ let mode = blend_param(p, CMD)?;
+ let aligned = flag(p, "aligned", true);
+ let impressionist = flag(p, "impressionist", false);
+ let pat = crate::pattern_cmds::resolve_param(s, CMD, p)?;
+ if pat.is_empty() {
+ return Err(bad(CMD, "the pattern is empty"));
+ }
+ let scale = stamp_scale(p, CMD)?;
+ let angle = stamp_angle(p, CMD)?;
+ let Some(first) = stroke.points.first() else {
+ return Err(bad(CMD, "`points` is empty"));
+ };
+ let phase = stamp_phase(p, CMD, aligned, first)?;
+ let tile = std::sync::Arc::new(Tile::new(&pat).ok_or_else(|| bad(CMD, "the pattern is empty"))?);
+ reject_huge_stroke(CMD, &stroke)?;
+ let seed = p.get("seed").and_then(Value::as_u64).unwrap_or_else(|| {
+ let bytes = p.get("points").map(std::string::ToString::to_string).unwrap_or_default();
+ photocraft_paint::rng::seed_from_bytes(bytes.as_bytes())
+ });
+ stroke.brush.seed = seed;
+ Ok(Self { stroke, id, mode, aligned, impressionist, pat, tile, phase, scale, angle, seed })
+ }
+
+ /// Where the pattern sits (aligned strokes; Impressionist jitters it per dab).
+ pub(super) fn placement(&self) -> Placement {
+ placement(self.phase, self.scale, self.angle)
}
- let scale = stamp_scale(p, CMD)?;
- let angle = stamp_angle(p, CMD)?;
- let Some(first) = stroke.points.first() else {
- return Err(bad(CMD, "`points` is empty"));
- };
- let phase = stamp_phase(p, CMD, aligned, first)?;
- let tile = Tile::new(&pat).ok_or_else(|| bad(CMD, "the pattern is empty"))?;
- reject_huge_stroke(CMD, &stroke)?;
- let seed = p.get("seed").and_then(Value::as_u64).unwrap_or_else(|| {
- let bytes = p.get("points").map(std::string::ToString::to_string).unwrap_or_default();
- photocraft_paint::rng::seed_from_bytes(bytes.as_bytes())
- });
- stroke.brush.seed = seed;
+ /// One Impressionist dab's edit of a working copy in `fmt`.
+ fn impressionist_effect(&self, fmt: PixelFormat) -> super::DabEffect {
+ let (tile, phase, scale, angle, seed, mode) = (self.tile.clone(), self.phase, self.scale, self.angle, self.seed, self.mode);
+ let (tw, th) = (self.pat.width as f32 * scale, self.pat.height as f32 * scale);
+ Box::new(move |work, fp| stamp_dab(work, &fmt, &tile, fp, phase, scale, angle, seed, tw, th, mode))
+ }
+}
+pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "paint.patternStamp";
+ let st = Setup::parse(s, p)?;
let dmg = s.edit("Pattern Stamp", |doc, _| {
- crate::pattern_cmds::ensure_in_doc(doc, &pat);
+ crate::pattern_cmds::ensure_in_doc(doc, &st.pat);
let pre = doc.clone();
- let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?;
+ let (surf, lock) = crate::channel_cmds::target_surface(doc, st.id, p)?;
let sel = pre.selection.as_ref();
- if impressionist {
- paint_impressionist(surf, &stroke, sel, lock, &tile, &pat, phase, scale, angle, seed, mode)
+ if st.impressionist {
+ // Halo is the dab footprint only: Impressionist jitters phase, it does not blur.
+ let effect = st.impressionist_effect(surf.format());
+ Ok(apply_dab_stroke(surf, &st.stroke, sel, lock, 0, effect))
} else {
- paint_aligned(surf, &stroke, sel, lock, &tile, phase, scale, angle, mode, CMD)
+ paint_aligned(surf, &st.stroke, sel, lock, &st.tile, st.placement(), st.mode, CMD)
}
})?;
- if let Some(st) = s.active_mut() {
- st.last_damage = Some(dmg);
+ if let Some(state) = s.active_mut() {
+ state.last_damage = Some(dmg);
}
Ok(json!({
"damage": damage_json(dmg),
- "phase": [phase.0, phase.1],
- "aligned": aligned,
- "pattern": pat.id,
+ "phase": [st.phase.0, st.phase.1],
+ "aligned": st.aligned,
+ "pattern": st.pat.id,
}))
}
+/// A Pattern Stamp stroke with Impressionist on, shown while it is drawn: the same jittered dabs,
+/// laid one by one as the commit lays them (`apply_dab_stroke`), so the preview at the last point
+/// is the committed result. Aligned strokes are live through [`super::LiveRetouch`].
+pub fn live_impressionist(s: &Session, p: &Value) -> Result<super::LiveDab> {
+ const CMD: &str = "paint.patternStamp";
+ has_pixel_layer(s).map_err(crate::EngineError::Other)?;
+ let st = Setup::parse(s, p)?;
+ if !st.impressionist {
+ return Err(bad(CMD, "only Impressionist strokes are laid dab by dab; aligned strokes preview through LiveRetouch"));
+ }
+ let (stroke, id) = (st.stroke.clone(), st.id);
+ let doc = (*s.active().ok_or(crate::EngineError::NoDocument)?.doc).clone();
+ super::LiveDab::with_effect_on(doc, CMD, p, stroke, id, 0, true, |pre| st.impressionist_effect(pre.format()))?.with_tail_preview()
+}
+
+/// The pattern under destination `rect` in `fmt` (native channels): what an aligned stroke paints
+/// through its coverage.
+pub(super) fn paint_region(tile: &Tile, place: &Placement, fmt: &PixelFormat, rect: Rect) -> Region {
+ rgba_to_region(fmt, rect, &render(tile, place, rect))
+}
+
fn stamp_scale(p: &Value, cmd: &str) -> Result<f32> {
match p.get("scale") {
None => Ok(1.0),
@@ -188,9 +245,7 @@ fn paint_aligned(
sel: Option<&Surface>,
lock: bool,
tile: &Tile,
- phase: (f32, f32),
- scale: f32,
- angle: f32,
+ place: Placement,
mode: BlendMode,
cmd: &str,
) -> Result<Rect> {
@@ -199,35 +254,10 @@ fn paint_aligned(
if bounds.is_empty() {
return Ok(Rect::EMPTY);
}
- let place = placement(phase, scale, angle);
- let rgba = render(tile, &place, bounds);
- let paint = rgba_to_region(&surf.format(), bounds, &rgba);
+ let paint = paint_region(tile, &place, &surf.format(), bounds);
Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode))
}
-#[allow(clippy::too_many_arguments)]
-fn paint_impressionist(
- surf: &mut Surface,
- stroke: &Stroke,
- sel: Option<&Surface>,
- lock: bool,
- tile: &Tile,
- pat: &Pattern,
- phase: (f32, f32),
- scale: f32,
- angle: f32,
- seed: u64,
- mode: BlendMode,
-) -> Result<Rect> {
- let fmt = surf.format();
- let tw = pat.width as f32 * scale;
- let th = pat.height as f32 * scale;
- // Halo is the dab footprint only: Impressionist jitters phase, it does not blur.
- Ok(apply_dab_stroke(surf, stroke, sel, lock, 0, |work, fp| {
- stamp_dab(work, &fmt, tile, fp, phase, scale, angle, seed, tw, th, mode);
- }))
-}
-
fn footprint_cov(fp: &Footprint, x: i32, y: i32) -> f32 {
if x < fp.rect.x0 || y < fp.rect.y0 {
return 0.0;
diff --git a/crates/engine/src/retouch_cmds/tests.rs b/crates/engine/src/retouch_cmds/tests.rs
index 6ceb14c10..4a28fa9b8 100644
--- a/crates/engine/src/retouch_cmds/tests.rs
+++ b/crates/engine/src/retouch_cmds/tests.rs
@@ -1296,7 +1296,7 @@ macro_rules! live_coordinate_regression {
live_coordinate_regression!(
live_retouch_rejects_invalid_batches_without_changing_the_preview,
LiveRetouch,
- ["paint.cloneStamp", "paint.healingBrush", "paint.historyBrush"]
+ ["paint.cloneStamp", "paint.healingBrush", "paint.historyBrush", "paint.patternStamp"]
);
live_coordinate_regression!(
live_dab_rejects_invalid_batches_without_changing_the_preview,
@@ -1509,3 +1509,72 @@ fn spot_healing_keeps_film_grain_through_overlapping_strokes() {
}
}
}
+
+/// The live Pattern Stamp shows exactly what the commit paints, fed point by point, at 8 and 16
+/// bits: aligned strokes through their coverage (`LiveRetouch`), Impressionist ones dab by dab
+/// (`LiveDab` with float working pixels, as the commit's).
+#[test]
+fn live_pattern_stamp_matches_the_commit() {
+ let all = [[20.0, 30.0], [34.0, 36.0], [50.0, 28.0], [70.0, 34.0]];
+ for depth in [8, 16] {
+ for (impressionist, aligned) in [(false, true), (false, false), (true, true)] {
+ let mut s = session(96, 64, depth, "rgb");
+ paint_layer(&mut s, texture);
+ let opts = |pts: &[[f64; 2]]| {
+ json!({"points": pts, "size": 14, "hardness": 40, "opacity": 70, "pattern": "Checkerboard", "scale": 150, "angle": 20,
+ "aligned": aligned, "impressionist": impressionist, "mode": "multiply", "seed": 11})
+ };
+ let (doc, h) = (s.active().unwrap().doc.clone(), s.active().unwrap().history.past_len());
+ let pts = |v: &[[f64; 2]]| v.iter().map(|q| StrokePoint::new(q[0], q[1], 1.0)).collect::<Vec<_>>();
+ let shown = if impressionist {
+ assert!(LiveRetouch::begin(&s, "paint.patternStamp", &opts(&all[..1])).is_err(), "Impressionist is laid dab by dab");
+ let mut live = live_pattern_impressionist(&s, &opts(&all[..1])).unwrap();
+ live.push(&pts(&all[1..3])).unwrap();
+ live.push(&pts(&all[3..])).unwrap();
+ live.doc.clone()
+ } else {
+ assert!(live_pattern_impressionist(&s, &opts(&all[..1])).is_err());
+ let mut live = LiveRetouch::begin(&s, "paint.patternStamp", &opts(&all[..1])).unwrap();
+ live.push(&pts(&all[1..3])).unwrap();
+ live.push(&pts(&all[3..])).unwrap();
+ live.doc.clone()
+ };
+ assert!(std::sync::Arc::ptr_eq(&doc, &s.active().unwrap().doc), "the preview leaves the document alone");
+ s.execute("paint.patternStamp", opts(&all)).unwrap();
+ assert_eq!(s.active().unwrap().history.past_len(), h + 1, "one History step");
+ let id = s.active().unwrap().active_layer.unwrap();
+ let (a, b) = (shown.layer(id).unwrap().surface().unwrap(), s.active().unwrap().doc.layer(id).unwrap().surface().unwrap());
+ let mut changed = false;
+ for y in 0..64 {
+ for x in 0..96 {
+ let (got, want) = (a.rgba(x, y), b.rgba(x, y));
+ changed |= (0..3).any(|c| (want[c] - texture(x, y)[c]).abs() > 0.02);
+ assert_eq!(got, want, "impressionist {impressionist} aligned {aligned} {depth}-bit ({x}, {y})");
+ }
+ }
+ assert!(changed, "the stroke painted");
+ }
+ }
+}
+
+/// A live Pattern Stamp on the layer mask paints the mask, as the commit does, and leaves the
+/// layer's pixels alone.
+#[test]
+fn live_pattern_stamp_paints_the_targeted_mask() {
+ let mut s = session(64, 48, 8, "rgb");
+ paint_layer(&mut s, texture);
+ s.execute("layer.layerMask.revealAll", json!({})).unwrap();
+ let all = [[16.0, 20.0], [40.0, 24.0]];
+ let opts = |pts: &[[f64; 2]]| json!({"points": pts, "size": 12, "pattern": "Checkerboard", "target": "mask", "seed": 3});
+ let mut live = LiveRetouch::begin(&s, "paint.patternStamp", &opts(&all[..1])).unwrap();
+ live.push(&[StrokePoint::new(40.0, 24.0, 1.0)]).unwrap();
+ let shown = live.doc.clone();
+ s.execute("paint.patternStamp", opts(&all)).unwrap();
+ let id = s.active().unwrap().active_layer.unwrap();
+ let (lv, cm) = (shown.layer(id).unwrap(), s.active().unwrap().doc.layer(id).unwrap());
+ let (lm, cmask) = (&lv.mask.as_ref().unwrap().surface, &cm.mask.as_ref().unwrap().surface);
+ let b = Rect::new(0, 0, 64, 48);
+ assert_eq!(lm.read_region(b), cmask.read_region(b), "the live mask is the committed mask");
+ assert!((0..64).any(|x| cmask.rgba(x, 22)[0] < 0.99), "the mask was painted");
+ assert_eq!(lv.surface().unwrap().read_region(b), cm.surface().unwrap().read_region(b), "pixels untouched");
+}
diff --git a/crates/paint/src/bg_erase.rs b/crates/paint/src/bg_erase.rs
index 14b3df396..c6689fd7b 100644
--- a/crates/paint/src/bg_erase.rs
+++ b/crates/paint/src/bg_erase.rs
@@ -4,13 +4,14 @@
//! Colours are compared in the surface's own colour channels (RGB, CMYK, Gray, Lab… at any depth),
//! so nothing is converted through RGB; only alpha changes.
+use photocraft_color::PixelFormat;
use photocraft_geom::Rect;
use photocraft_raster::{Surface, from_rgba};
use serde::{Deserialize, Serialize};
use crate::Stroke;
use crate::replace::{Limits, Sampling};
-use crate::retouch::{Region, alpha_index, apply_dab_stroke};
+use crate::retouch::{Footprint, Region, alpha_index, apply_dab_stroke};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
@@ -49,16 +50,33 @@ fn dist(a: &[f32], b: &[f32]) -> f32 {
/// the selection limits the effect. Returns the damaged rectangle; empty when the surface has no
/// alpha channel.
pub fn apply_background_eraser(target: &mut Surface, stroke: &Stroke, bs: &BgEraseSettings, selection: Option<&Surface>) -> Rect {
- let fmt = target.format();
- let Some(a) = alpha_index(&fmt) else { return Rect::EMPTY };
+ let Some(effect) = background_eraser_effect(target.format(), bs) else { return Rect::EMPTY };
+ apply_dab_stroke(target, &background_eraser_stroke(stroke), selection, false, 0, effect)
+}
+
+/// The stroke [`apply_background_eraser`] runs its dabs along: full opacity (the tool has none),
+/// never the brush's erase flag. Live previews run the same dabs.
+pub fn background_eraser_stroke(stroke: &Stroke) -> Stroke {
+ let mut stroke = stroke.clone();
+ stroke.brush.opacity = 1.0;
+ stroke.brush.erase = false;
+ stroke
+}
+
+/// One Background Eraser dab's edit of a working copy in format `fmt`: shared by
+/// [`apply_background_eraser`] and live previews that run the dabs as they come, so both erase
+/// the same pixels. `None` when `fmt` has no alpha channel (nothing can be erased).
+pub fn background_eraser_effect(fmt: PixelFormat, bs: &BgEraseSettings) -> Option<impl FnMut(&mut Region, &Footprint) + use<>> {
+ let a = alpha_index(&fmt)?;
let nc = a;
let tol = if bs.tolerance.is_finite() { bs.tolerance.clamp(0.0, 1.0) } else { 0.0 };
let soft = bs.limits != Limits::FindEdges;
let native = |c: [f32; 4]| -> Vec<f32> { from_rgba(&fmt, [c[0], c[1], c[2], 1.0])[..nc].to_vec() };
let swatch = native(bs.background);
let fg = native(bs.foreground);
+ let (sampling, limits, protect_foreground) = (bs.sampling, bs.limits, bs.protect_foreground);
let mut once: Option<Option<Vec<f32>>> = None;
- let match_w = |d: f32| -> f32 {
+ let match_w = move |d: f32| -> f32 {
if d > tol {
0.0
} else if soft && tol > 0.0 {
@@ -68,10 +86,7 @@ pub fn apply_background_eraser(target: &mut Surface, stroke: &Stroke, bs: &BgEra
1.0
}
};
- let mut stroke = stroke.clone();
- stroke.brush.opacity = 1.0;
- stroke.brush.erase = false;
- apply_dab_stroke(target, &stroke, selection, false, 0, |work: &mut Region, fp| {
+ Some(move |work: &mut Region, fp: &Footprint| {
let r = fp.rect.intersect(&work.rect);
if r.is_empty() {
return;
@@ -85,7 +100,7 @@ pub fn apply_background_eraser(target: &mut Surface, stroke: &Stroke, bs: &BgEra
let p = work.px(cx, cy);
(p[a] > 0.0).then(|| p[..nc].to_vec())
};
- let sampled = match bs.sampling {
+ let sampled = match sampling {
Sampling::Continuous => hotspot(work),
Sampling::Once => once.get_or_insert_with(|| hotspot(work)).clone(),
Sampling::BackgroundSwatch => Some(swatch.clone()),
@@ -105,13 +120,13 @@ pub fn apply_background_eraser(target: &mut Surface, stroke: &Stroke, bs: &BgEra
continue;
}
let c = &p[..nc];
- if bs.protect_foreground && dist(c, &fg) <= tol {
+ if protect_foreground && dist(c, &fg) <= tol {
continue;
}
weight[(y - r.y0) as usize * w + (x - r.x0) as usize] = match_w(dist(c, &sampled));
}
}
- if bs.limits != Limits::Discontiguous {
+ if limits != Limits::Discontiguous {
keep_connected(&mut weight, w, h, (cx.clamp(r.x0, r.x1 - 1) - r.x0) as usize, (cy.clamp(r.y0, r.y1 - 1) - r.y0) as usize);
}
for y in r.y0..r.y1 {
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 1f5310388..ea74d435c 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -491,13 +491,20 @@ pub(crate) fn strokes_live(tool: Tool) -> bool {
) || live_retouch_command(tool).is_some()
}
-/// The retouching tools drawn live (`LiveRetouch`), by the command their live stroke previews.
-/// The Healing Brush shows its texture while drawing; the blend comes on release.
+/// The Spot Healing Brush's stroke while dragging: Photoshop shows the area it will heal as a
+/// semi-opaque dark overlay (an image overlay, the same in every UI theme) and heals on release.
+pub(crate) const SPOT_HEALING_TRAIL: Color32 = Color32::from_black_alpha(128);
+
+/// The retouching tools drawn live (`LiveRetouch`; the Background Eraser's and an Impressionist
+/// Pattern Stamp's dabs are laid one by one, `LiveDab`), by the command their live stroke
+/// previews. The Healing Brush shows its texture while drawing; the blend comes on release.
fn live_retouch_command(tool: Tool) -> Option<&'static str> {
match tool {
Tool::CloneStamp => Some("paint.cloneStamp"),
Tool::Healing => Some("paint.healingBrush"),
Tool::HistoryBrush => Some("paint.historyBrush"),
+ Tool::PatternStamp => Some("paint.patternStamp"),
+ Tool::BackgroundEraser => Some("paint.backgroundEraser"),
_ => None,
}
}
@@ -615,6 +622,20 @@ fn begin_live_stroke(app: &PhotocraftApp) -> Option<LiveStroke> {
p["points"] = json!(d.points);
p["target"] = paint_target(app);
EngineStroke::Dab(photocraft_engine::retouch_cmds::LiveDab::begin(&app.session, cmd, &p).ok()?)
+ } else if d.tool == Tool::PatternStamp {
+ // The params `retouch_ui::finish_stroke` commits.
+ let mut p = crate::retouch_ui::pattern_stamp_params(app, &d.points);
+ p["points"] = json!(d.points);
+ p["target"] = paint_target(app);
+ if app.ui.tool_options.pattern_stamp_impressionist {
+ EngineStroke::Dab(photocraft_engine::retouch_cmds::live_pattern_impressionist(&app.session, &p).ok()?)
+ } else {
+ EngineStroke::Retouch(photocraft_engine::retouch_cmds::LiveRetouch::begin(&app.session, "paint.patternStamp", &p).ok()?)
+ }
+ } else if d.tool == Tool::BackgroundEraser {
+ // The params `eraser_ui::finish_stroke` commits (layer pixels only).
+ let p = crate::eraser_ui::background_eraser_params(app, &d.points);
+ EngineStroke::Dab(photocraft_engine::eraser_cmds::live_background_eraser(&app.session, &p).ok()?)
} else if let Some(cmd) = live_retouch_command(d.tool) {
// The params `retouch_ui::finish_stroke` commits.
let mut p = if d.tool == Tool::HistoryBrush { json!({}) } else { crate::retouch_ui::clone_params(app)? };
@@ -4041,6 +4062,9 @@ fn draw_drag_preview(app: &mut PhotocraftApp, painter: &egui::Painter, xf: &View
Tool::QuickSelection => Color32::from_white_alpha(40),
// The Remove Tool tints what it will remove, like Photoshop's.
Tool::Remove => crate::theme::Tokens::get(painter.ctx()).danger.gamma_multiply(0.45),
+ // The Spot Healing Brush darkens the area it will heal, as Photoshop's does while
+ // dragging; the heal itself is computed on release.
+ Tool::SpotHealing => SPOT_HEALING_TRAIL,
_ => Color32::from_white_alpha(60),
};
let Some(st) = app.session.active() else { return };
diff --git a/crates/ui-egui/src/eraser_ui.rs b/crates/ui-egui/src/eraser_ui.rs
index 59fc4d492..a6cd686d8 100644
--- a/crates/ui-egui/src/eraser_ui.rs
+++ b/crates/ui-egui/src/eraser_ui.rs
@@ -40,17 +40,23 @@ pub fn finish_stroke(app: &mut PhotocraftApp, tool: Tool, points: &[[f64; 3]]) -
if tool != Tool::BackgroundEraser {
return false;
}
+ let r = app.run("paint.backgroundEraser", background_eraser_params(app, points));
+ report(app, r);
+ true
+}
+
+/// `paint.backgroundEraser` params for a stroke along `points`: shared by the live preview and
+/// the commit, with the jitter seed from the first point (`retouch_ui::stroke_seed`).
+pub(crate) fn background_eraser_params(app: &PhotocraftApp, points: &[[f64; 3]]) -> Value {
let o = &app.ui.tool_options;
- let p = json!({
+ json!({
"points": points,
"sampling": o.bg_sampling,
"limits": o.bg_limits,
"tolerance": o.bg_tolerance,
"protectForegroundColor": o.bg_protect_fg,
- });
- let r = app.run("paint.backgroundEraser", p);
- report(app, r);
- true
+ "seed": crate::retouch_ui::stroke_seed(points),
+ })
}
/// Whether `tool` is the Eraser in Pencil mode: it erases hard, aliased pixels through
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 8e662d866..255b82b22 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -2179,6 +2179,8 @@ mod pen_variants_tests;
#[cfg(test)]
mod color_replacement_tests;
#[cfg(test)]
+mod live_retouch_tests;
+#[cfg(test)]
mod pencil_tests;
#[cfg(test)]
diff --git a/crates/ui-egui/src/live_retouch_tests.rs b/crates/ui-egui/src/live_retouch_tests.rs
new file mode 100644
index 000000000..dff475cde
--- /dev/null
+++ b/crates/ui-egui/src/live_retouch_tests.rs
@@ -0,0 +1,145 @@
+//! Pattern Stamp and Background Eraser strokes draw live (TOOL-213-7, #3754): the canvas shows
+//! the engine's real result while dragging, the release commits exactly those pixels as one
+//! History step, and the commit is what the one-shot command paints for the same stroke. The Spot
+//! Healing Brush shows the area it will heal and heals on release, as Photoshop does.
+
+use egui::Modifiers;
+use serde_json::{Value, json};
+
+use crate::PhotocraftApp;
+use crate::canvas::{ToolEvent, display_doc, strokes_live, tool_event};
+use crate::state::Tool;
+
+const STROKE: [(f64, f64); 4] = [(12.0, 20.0), (30.0, 24.0), (48.0, 18.0), (66.0, 22.0)];
+
+/// An 80×40 document at `depth` bits: a white Background with a black block on its left half,
+/// with `tool` picked (14 px, soft, no smoothing).
+fn app(depth: u32, tool: Tool) -> PhotocraftApp {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ app.run("file.new", json!({"width": 80, "height": 40, "depth": depth})).unwrap();
+ app.run("select.rect", json!({"x": 0, "y": 0, "width": 40, "height": 40})).unwrap();
+ app.run("edit.fill", json!({"color": "#000000"})).unwrap();
+ app.run("select.deselect", json!({})).unwrap();
+ app.ui.tool = tool;
+ crate::paint_mouse::sync_tool_brush(&mut app);
+ app.run("tools.setBrush", json!({"brush": {"size": 14, "hardness": 0.5, "pressureSize": false, "smoothing": {"amount": 0.0}}})).unwrap();
+ app
+}
+
+/// The active layer's pixels (or its mask) in `doc`.
+fn surface(doc: &photocraft_doc::Document, app: &PhotocraftApp, mask: bool) -> Vec<f32> {
+ let l = doc.layer(app.session.active().unwrap().active_layer.unwrap()).unwrap();
+ let s = if mask { &l.mask.as_ref().unwrap().surface } else { l.surface().unwrap() };
+ s.read_region(photocraft_geom::Rect::new(0, 0, 80, 40))
+}
+
+/// Drag `STROKE` with the picked tool. Returns what the canvas showed at the last move (the
+/// targeted surface) and the params the release committed.
+fn live_drag(app: &mut PhotocraftApp, cmd: &str, mask: bool) -> (Vec<f32>, Value) {
+ let (before, steps) = (app.session.active().unwrap().doc.clone(), app.session.active().unwrap().history.past_len());
+ let m = Modifiers::NONE;
+ tool_event(app, ToolEvent::Down { x: STROKE[0].0, y: STROKE[0].1, pressure: 1.0 }, m);
+ for &(x, y) in &STROKE[1..] {
+ tool_event(app, ToolEvent::Move { x, y, pressure: 1.0 }, m);
+ }
+ assert!(app.live_stroke.is_some(), "{cmd}: the canvas shows the stroke while dragging");
+ let shown = display_doc(app, 0).0;
+ let shown = surface(&shown, app, mask);
+ assert!(shown != surface(&before, app, mask), "{cmd}: the preview paints as it goes");
+ let st = app.session.active().unwrap();
+ assert!(std::sync::Arc::ptr_eq(&before, &st.doc) && st.history.past_len() == steps, "{cmd}: nothing committed while dragging");
+ let (x, y) = STROKE[3];
+ tool_event(app, ToolEvent::Up { x, y }, m);
+ assert!(!app.ui.status_error, "{}", app.ui.status);
+ assert!(app.live_stroke.is_none());
+ assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1, "{cmd}: one History step");
+ let params = app.session.journal.iter().rev().find(|(name, _)| name == cmd).unwrap().1.clone();
+ (shown, params)
+}
+
+/// The release committed what the drag showed, and the one-shot command gives the same pixels
+/// again; without the live stroke's seed too where nothing is jittered (`keep_seed` false: a
+/// brush without jitter paints the same whatever the seed; Impressionist jitters every dab).
+fn check_commit(app: &mut PhotocraftApp, cmd: &str, shown: &[f32], mut params: Value, mask: bool, keep_seed: bool) {
+ let committed = app.session.active().unwrap().doc.clone();
+ assert!(surface(&committed, app, mask) == shown, "{cmd}: the release commits the pixels the drag showed");
+ app.run("edit.undo", json!({})).unwrap();
+ if !keep_seed {
+ params.as_object_mut().unwrap().remove("seed");
+ }
+ app.run(cmd, params).unwrap();
+ assert!(surface(&app.session.active().unwrap().doc, app, mask) == shown, "{cmd}: the one-shot command paints the same");
+}
+
+#[test]
+fn pattern_stamp_draws_live_and_commits_what_it_showed() {
+ for depth in [8, 16] {
+ for impressionist in [false, true] {
+ let mut app = app(depth, Tool::PatternStamp);
+ assert!(strokes_live(Tool::PatternStamp));
+ app.ui.tool_options.pattern_stamp_impressionist = impressionist;
+ app.ui.tool_options.pattern_stamp_scale = 150.0;
+ let (shown, params) = live_drag(&mut app, "paint.patternStamp", false);
+ assert_eq!(params["impressionist"], json!(impressionist));
+ check_commit(&mut app, "paint.patternStamp", &shown, params, false, impressionist);
+ }
+ }
+}
+
+#[test]
+fn a_live_pattern_stamp_on_the_layer_mask_paints_the_mask() {
+ let mut app = app(8, Tool::PatternStamp);
+ app.run("layer.new.layer", json!({})).unwrap();
+ app.run("layer.layerMask.revealAll", json!({})).unwrap();
+ app.ui.mask_target = true;
+ let pixels = surface(&app.session.active().unwrap().doc, &app, false);
+ let (shown, params) = live_drag(&mut app, "paint.patternStamp", true);
+ assert_eq!(params["target"], json!("mask"));
+ assert!(surface(&app.session.active().unwrap().doc, &app, false) == pixels, "the layer's pixels are untouched");
+ check_commit(&mut app, "paint.patternStamp", &shown, params, true, false);
+}
+
+#[test]
+fn background_eraser_draws_live_and_commits_what_it_showed() {
+ for depth in [8, 16] {
+ for sampling in ["continuous", "once"] {
+ let mut app = app(depth, Tool::BackgroundEraser);
+ assert!(strokes_live(Tool::BackgroundEraser));
+ app.ui.tool_options.bg_sampling = sampling.into();
+ let (shown, params) = live_drag(&mut app, "paint.backgroundEraser", false);
+ // The release turned the Background into a normal layer, as the command does.
+ let st = app.session.active().unwrap();
+ assert_eq!(st.doc.layer(st.active_layer.unwrap()).unwrap().name, "Layer 0");
+ check_commit(&mut app, "paint.backgroundEraser", &shown, params, false, false);
+ }
+ }
+}
+
+#[test]
+fn a_refused_background_eraser_stroke_shows_nothing_and_reports_on_release() {
+ let mut app = app(8, Tool::BackgroundEraser);
+ app.run("layer.new.layer", json!({})).unwrap();
+ app.run("layer.setProps", json!({"locks": {"transparency": true}})).unwrap();
+ let steps = app.session.active().unwrap().history.past_len();
+ let m = Modifiers::NONE;
+ tool_event(&mut app, ToolEvent::Down { x: 20.0, y: 20.0, pressure: 1.0 }, m);
+ tool_event(&mut app, ToolEvent::Move { x: 40.0, y: 20.0, pressure: 1.0 }, m);
+ assert!(app.live_stroke.is_none(), "the engine refuses the stroke, so nothing is drawn live");
+ tool_event(&mut app, ToolEvent::Up { x: 40.0, y: 20.0 }, m);
+ assert!(app.ui.status_error && app.ui.status.contains("transparency"), "{}", app.ui.status);
+ assert_eq!(app.session.active().unwrap().history.past_len(), steps);
+}
+
+#[test]
+fn spot_healing_shows_the_area_it_heals_and_heals_on_release() {
+ let mut app = app(8, Tool::SpotHealing);
+ assert!(!strokes_live(Tool::SpotHealing), "the heal needs the whole stroke");
+ assert_eq!(crate::canvas::SPOT_HEALING_TRAIL.r(), 0, "a dark overlay, as Photoshop's");
+ let steps = app.session.active().unwrap().history.past_len();
+ let m = Modifiers::NONE;
+ tool_event(&mut app, ToolEvent::Down { x: 30.0, y: 20.0, pressure: 1.0 }, m);
+ tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 20.0, pressure: 1.0 }, m);
+ assert_eq!(app.session.active().unwrap().history.past_len(), steps);
+ tool_event(&mut app, ToolEvent::Up { x: 50.0, y: 20.0 }, m);
+ assert_eq!(app.session.active().unwrap().history.past_len(), steps + 1);
+}
diff --git a/crates/ui-egui/src/retouch_ui.rs b/crates/ui-egui/src/retouch_ui.rs
index 8e78a5dd9..11f576f0b 100644
--- a/crates/ui-egui/src/retouch_ui.rs
+++ b/crates/ui-egui/src/retouch_ui.rs
@@ -78,6 +78,38 @@ pub(crate) fn color_replacement_params(app: &PhotocraftApp) -> Value {
})
}
+/// `paint.patternStamp` params from the options bar and the Patterns panel (without `points` and
+/// `target`): shared by the live preview and the commit. The jitter `seed` comes from the stroke's
+/// first point, so the live stroke (which starts with only that point) and the commit agree.
+pub(crate) fn pattern_stamp_params(app: &PhotocraftApp, points: &[[f64; 3]]) -> Value {
+ let o = &app.ui.tool_options;
+ let mut p = json!({
+ "aligned": o.pattern_stamp_aligned,
+ "impressionist": o.pattern_stamp_impressionist,
+ "scale": o.pattern_stamp_scale,
+ "angle": o.pattern_stamp_angle,
+ "seed": stroke_seed(points),
+ });
+ if o.pattern_stamp_aligned
+ && let Some(ph) = app.ui.pattern_stamp_phase
+ {
+ p["phase"] = json!(ph);
+ }
+ if let Some(id) = photocraft_engine::presets::patterns::current(&app.session).or(app.session.patterns.items.first()).map(|x| x.id.clone()) {
+ p["pattern"] = json!(id);
+ }
+ p
+}
+
+/// The jitter seed of a stroke drawn live and committed on release: from its first position, which
+/// the live stroke and the commit share (the engine's default hashes every point, which the live
+/// stroke doesn't have yet).
+pub(crate) fn stroke_seed(points: &[[f64; 3]]) -> u64 {
+ // Position only: a pen tap raises the first point's pressure on release (#1798).
+ let first = points.first().map(|p| json!([p[0], p[1]]).to_string()).unwrap_or_default();
+ photocraft_engine::paint::rng::seed_from_bytes(first.as_bytes())
+}
+
/// Finish a stroke with a retouching tool. Returns false if `tool` isn't one.
pub fn finish_stroke(app: &mut PhotocraftApp, tool: Tool, points: &[[f64; 3]], mods: egui::Modifiers) -> bool {
let o = app.ui.tool_options.clone();
@@ -87,23 +119,7 @@ pub fn finish_stroke(app: &mut PhotocraftApp, tool: Tool, points: &[[f64; 3]], m
Tool::Remove => ("paint.remove", json!({"sampleAllLayers": o.sample_all_layers})),
Tool::MixerBrush => ("paint.mixerBrush", json!({})),
Tool::ColorReplacement => ("paint.colorReplacement", color_replacement_params(app)),
- Tool::PatternStamp => {
- let mut p = json!({
- "aligned": o.pattern_stamp_aligned,
- "impressionist": o.pattern_stamp_impressionist,
- "scale": o.pattern_stamp_scale,
- "angle": o.pattern_stamp_angle,
- });
- if o.pattern_stamp_aligned
- && let Some(ph) = app.ui.pattern_stamp_phase
- {
- p["phase"] = json!(ph);
- }
- if let Some(id) = photocraft_engine::presets::patterns::current(&app.session).or(app.session.patterns.items.first()).map(|x| x.id.clone()) {
- p["pattern"] = json!(id);
- }
- ("paint.patternStamp", p)
- }
+ Tool::PatternStamp => ("paint.patternStamp", pattern_stamp_params(app, points)),
Tool::Healing | Tool::CloneStamp => {
let Some(p) = clone_params(app) else {
// Option-click on the Mac, Alt-click on Windows.
diff --git a/docs/brush-parity.md b/docs/brush-parity.md
index 75575abd7..dbe1fd719 100644
--- a/docs/brush-parity.md
+++ b/docs/brush-parity.md
@@ -1,6 +1,6 @@
# Brush and painting parity
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-10 · **Change:** major (first version: brush engine, dynamics, pressure, smoothing, cursors, retouch tools and feel audited from source and open issues) · **Target:** Adobe Photoshop 2026
+> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-11 · **Change:** minor (Pattern Stamp and Background Eraser draw live, TOOL-213-7; 2026-10-10: major, first version: brush engine, dynamics, pressure, smoothing, cursors, retouch tools and feel audited from source and open issues) · **Target:** Adobe Photoshop 2026
Painting is where Photoshop users notice differences first, so it gets its own checklist: the
brush engine (`crates/paint/src/brush.rs`), the Brush Settings UI
@@ -58,7 +58,7 @@ tablets against Photoshop side by side.
| Latency: dab to screen within a frame | partial | budgets P13/P16/P33 over (scorecard); big-brush lag #2619, #1994; cursor lag #2566, #1343 |
| No hitch at mouse-up on a long stroke | not measurable | P32 needs a frame harness |
| Live stroke for Brush and Eraser | done | |
-| Live stroke for every brush-based retouch tool | missing | TOOL-213-7 |
+| Live stroke for every brush-based retouch tool | partial | TOOL-213-7: all live but the Mixer Brush (PR #3627); Spot Healing shows the area it heals and heals on release, as Photoshop does |
| No OS arrow cursor over the canvas with a pen | partial | TOOL-213-14 |
## Gestures and cursors
@@ -110,4 +110,5 @@ tablets against Photoshop side by side.
| Date | Change | Summary |
|---|---|---|
+| 2026-10-11 | minor | Pattern Stamp and Background Eraser draw live (#3754); live retouch row now partial (Mixer Brush left) |
| 2026-10-10 | major | First version, from a source audit and the open issues |
diff --git a/docs/gaps.md b/docs/gaps.md
index 8a2b90cbe..0aa1d6d61 100644
--- a/docs/gaps.md
+++ b/docs/gaps.md
@@ -1,6 +1,6 @@
# Where PhotoCraft falls short of Photoshop
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-10 · **Change:** minor (Tilt-Shift evidence added to G2; earlier the same day: major, every known shortfall ranked from the re-measure) · **Target:** Adobe Photoshop 2026
+> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-11 · **Change:** minor (G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; 2026-10-10: Tilt-Shift evidence added to G2, and major, every known shortfall ranked from the re-measure) · **Target:** Adobe Photoshop 2026
Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact
on the way to beta. This is the work list agents pick from: take the highest-ranked entry that
@@ -128,8 +128,9 @@ what an agent can't finish alone.
- **Missing:** lag with big brushes (#2619, #1994) and under the cursor (#2566, #1343); jumpy
pressure on Windows (#2046) and tap sensitivity (#1933); stair-stepped line weights (#1776),
interpolation and smoothing problems (#2138), edge falloff (#2149), pixelated cursor vs
- Photoshop (#1433), brush rotation not driven by pen rotation (#1301); live preview only for
- Brush and Eraser (TOOL-213-7); no image file as a brush tip (TOOL-213-12); per-control pressure
+ Photoshop (#1433), brush rotation not driven by pen rotation (#1301); no live preview for the
+ Mixer Brush yet (TOOL-213-7, in PR #3627; the other brush tools draw live, Spot Healing and Remove
+ compute on release as in Photoshop); no image file as a brush tip (TOOL-213-12); per-control pressure
curves (TOOL-213-11); 4 of Photoshop's symmetry modes.
- **Detail:** [`brush-parity.md`](brush-parity.md).
- **Estimate:** 100–180 h. **Human:** checking feel on real tablets.
@@ -218,6 +219,7 @@ what an agent can't finish alone.
| Date | Change | Summary |
|---|---|---|
+| 2026-10-11 | minor | G4: Pattern Stamp and Background Eraser draw live, Spot Healing shows a dark overlay while dragging (#3754); only the Mixer Brush is left of TOOL-213-7 |
| 2026-10-10 | minor | G2: recorded Tilt-Shift computation/filtered-proxy measurements and limits; gap and estimate remain open |
| 2026-10-10 | minor | Checked against the alpha gate (no alpha blockers); #2374 marked closed |
| 2026-10-10 | major | First version, from the full re-measure against Photoshop 2026 27.11.0 and the open issues |
diff --git a/docs/scorecard.md b/docs/scorecard.md
index fdba39bd4..91a53e48a 100644
--- a/docs/scorecard.md
+++ b/docs/scorecard.md
@@ -136,7 +136,7 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t
| TOOL-213-4 | Content-Aware Move tool reusing inpaint completion | partial | [#213](https://github.com/storytold/photocraft/issues/213) | paint.contentAwareMove (retouch_cmds/content_aware_move.rs: move/extend, Structure 1-7, Color 0-10, Sample All Layers; background job) + Tool::ContentAwareMove (J group: lasso, then drag). Missing: Transform On Drop, a live preview of the result (the drag shows the outline only) |
| TOOL-213-5 | Painting a type/shape/smart/fill layer offers to rasterize, then continues the stroke | done | [#213](https://github.com/storytold/photocraft/issues/213) | rasterize_prompt.rs: OK rasterizes then paints (two history states), Cancel does nothing; drivable via ui.dialog.confirm |
| TOOL-213-6 | Fill dialog: contents, blend, opacity, preserve transparency; remembered; Shift+Backspace | done | [#213](https://github.com/storytold/photocraft/issues/213) | fill_ui.rs dialog over edit.fill (fill_cmds.rs): all contents, mode, opacity, preserve; remembered in prefs; Shift+F5 / Shift+Backspace |
-| TOOL-213-7 | Live stroke preview for every brush-based retouch tool | partial | [#213](https://github.com/storytold/photocraft/issues/213) | Live (canvas.rs strokes_live): Brush, Pencil, Eraser, Blur, Sharpen, Smudge, Dodge, Burn, Sponge, Clone Stamp, Healing Brush, History Brush (#1026, #1040); the release commits the live stroke's pixels (P32). Not yet live: Spot Healing Brush, Mixer Brush, Background Eraser, Pattern Stamp |
+| TOOL-213-7 | Live stroke preview for every brush-based retouch tool | partial | [#213](https://github.com/storytold/photocraft/issues/213) | Live (canvas.rs strokes_live): Brush, Pencil, Eraser, Color Replacement, Blur, Sharpen, Smudge, Dodge, Burn, Sponge, Clone Stamp, Healing Brush, History Brush (#1026, #1040), Pattern Stamp (aligned and Impressionist) and Background Eraser (#3754); the release commits the live stroke's pixels (P32) or, for the retouch tools, the same pixels the live stroke showed (tested equal at 8 and 16 bits). Spot Healing Brush shows the area it heals as a dark overlay and heals on release, as Photoshop does. Not yet live: Mixer Brush (in PR #3627) |
| TOOL-213-8 | Clone Source: W/H link, drawn overlay (opacity/blend/clip/auto-hide), Alt target cursor | partial | [#213](https://github.com/storytold/photocraft/issues/213) | Clone Source overlay drawn with opacity, inversion, circular clipping and auto-hide; W/H link, custom-tip clipping and overlay blend modes remain missing |
| TOOL-213-9 | Eyedropper comparison ring (new colour above, current below) while sampling | done | [#213](https://github.com/storytold/photocraft/issues/213) | eyedropper_ring (canvas.rs): the sampled colour on the upper arc, the foreground below, drawn for the Eyedropper and Alt-sampling while the button is held; the Precise-cursor preference keeps the crosshair |
| TOOL-213-10 | Ctrl+Alt drag resizes brush size/hardness with an on-canvas readout | done | [#213](https://github.com/storytold/photocraft/issues/213) | brush_resize.rs (#297, #370): Alt+right-drag, or Control+Option-drag on macOS (Control+Alt everywhere), sets diameter horizontally and hardness vertically, circle plus Diameter/Hardness readout, one coalesced tools.setBrush, no paint or history; 9 tests there |
diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md
index 472a0f7cf..8ac3e1628 100644
--- a/docs/target-app-parity.md
+++ b/docs/target-app-parity.md
@@ -1,6 +1,6 @@
# PhotoCraft vs Adobe Photoshop: target-app parity
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-10 · **Change:** minor (Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment) · **Target:** Adobe Photoshop 2026
+> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-11 · **Change:** minor (retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment) · **Target:** Adobe Photoshop 2026
The authoritative answer to "how close is PhotoCraft to Photoshop, and how much work is left". The
one-page summary is [`ROADMAP.md`](../ROADMAP.md); the ranked work list is [`gaps.md`](gaps.md);
@@ -170,7 +170,7 @@ parity for the area and are already contained in the dimension rows above.
| Layers, groups, masks, blend modes, smart objects, layer styles | 65% | 150–250 | Broad and GPU-accelerated. Open: multi-layer Smart Object conversion (#2604, #2648), layer clipboard between documents (UI-217-23), Stamp Visible, contour editor, smart-object perspective (FILE-215-6), mask targeting by command (#2458) |
| Selections, Select and Mask, channels | 55% | 120–200 | All selection tools, single row/column marquee included (#2837). Select and Mask is a generic dialog (TOOL-214-1), no Refine Hair (#2671); Select Subject/Sky classical, 559 ms p50 on 24 MP vs a 100 ms budget |
| Painting and brush engine | 55% | 150–250 | Every Brush Settings section exists; feel is the gap: lag on big brushes, pressure jumps, smoothing and edge quality reports ([brush-parity.md](brush-parity.md)) |
-| Retouching (healing, clone, patch, remove, content-aware) | 50% | 100–180 | Remove tool non-generative; Content-Aware Fill has no workspace (TOOL-214-15); live stroke preview only for Brush/Eraser (TOOL-213-7) |
+| Retouching (healing, clone, patch, remove, content-aware) | 50% | 100–180 | Remove tool non-generative; Content-Aware Fill has no workspace (TOOL-214-15); no live stroke preview for the Mixer Brush yet (TOOL-213-7) |
| Transform, warp, puppet, perspective, liquify | 55% | 100–180 | Free Transform modifiers right; no transform context menu (TOOL-214-5), no skew fields, puppet mesh is a block grid (TOOL-214-6), Liquify called "useless" by a user (#2606) |
| Adjustments and filters | 70% | 120–200 | All present; smart-filter re-render matches Photoshop on 5 of 30 files; Filter Gallery looks approximate; no Neural Filters |
| Type | 40% | 120–200 | Engine works; no type on a path, manual kerning, RTL paragraphs, OpenType panel UI, live Warp Text preview; Type tool freeze on macOS (#2518) |
@@ -560,6 +560,7 @@ See [method, raw measurements and reproduction](five-algorithm-performance.md).
| Date | Change | Summary |
|---|---|---|
+| 2026-10-11 | minor | Retouching evidence: Pattern Stamp and Background Eraser draw live (#3754), only the Mixer Brush is left of TOOL-213-7; percentages unchanged |
| 2026-10-10 | minor | Added measured Tilt-Shift computation/filtered-proxy gains and inconclusive cases; parity percentages and budgets unchanged |
| 2026-10-10 | minor | Readiness-by-audience table: percent and hours for full, mainstream and essentials; full number confirmed as the additive weighted sum over dimensions (46%, reported ~45%) |
| 2026-10-10 | minor | Added mainstream-practitioner (~43%) and essentials-user (~61%) numbers with written weights and discounts; full ready-for-real-work rechecked against its written weights (46%, reported ~45%), unchanged |
diff --git a/scorecard/tools.toml b/scorecard/tools.toml
index 51e377192..4dd814419 100644
--- a/scorecard/tools.toml
+++ b/scorecard/tools.toml
@@ -52,7 +52,7 @@ id = "TOOL-213-7"
target = "Live stroke preview for every brush-based retouch tool"
status = "partial"
issue = 213
-note = "Live (canvas.rs strokes_live): Brush, Pencil, Eraser, Blur, Sharpen, Smudge, Dodge, Burn, Sponge, Clone Stamp, Healing Brush, History Brush (#1026, #1040); the release commits the live stroke's pixels (P32). Not yet live: Spot Healing Brush, Mixer Brush, Background Eraser, Pattern Stamp"
+note = "Live (canvas.rs strokes_live): Brush, Pencil, Eraser, Color Replacement, Blur, Sharpen, Smudge, Dodge, Burn, Sponge, Clone Stamp, Healing Brush, History Brush (#1026, #1040), Pattern Stamp (aligned and Impressionist) and Background Eraser (#3754); the release commits the live stroke's pixels (P32) or, for the retouch tools, the same pixels the live stroke showed (tested equal at 8 and 16 bits). Spot Healing Brush shows the area it heals as a dark overlay and heals on release, as Photoshop does. Not yet live: Mixer Brush (in PR #3627)"
[[item]]
id = "TOOL-213-8"