Skip to content

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

Pattern Stamp tool in the S-group flyout (#922)

Matt Van Horn619095bfd0b0
diff --git a/crates/engine/examples/bench_pattern_stamp.rs b/crates/engine/examples/bench_pattern_stamp.rs
new file mode 100644
index 000000000..90b529851
--- /dev/null
+++ b/crates/engine/examples/bench_pattern_stamp.rs
@@ -0,0 +1,57 @@
+//! Timing: Pattern Stamp on a 24 MP (6016×4000) RGBA8 document.
+//!
+//! ```sh
+//! cargo run --release -p photocraft-engine --example bench_pattern_stamp
+//! ```
+//!
+//! One aligned, hard 200 px stroke along y=2000 from x=100 to x=5900, impressionist off, then
+//! optionally the same stroke with impressionist on.
+
+use std::time::Instant;
+
+use photocraft_engine::Session;
+use serde_json::json;
+
+fn main() {
+ let mut s = Session::new();
+ if let Err(e) = s.execute("file.new", json!({"width": 6016, "height": 4000, "depth": 8, "mode": "rgb"})) {
+ eprintln!("file.new: {e}");
+ std::process::exit(1);
+ }
+ println!("document 6016x4000, 8-bit RGB (24.06 MP)");
+ let stroke = json!({
+ "points": [[100, 2000], [5900, 2000]],
+ "size": 200,
+ "hardness": 100,
+ "pattern": "Checkerboard",
+ "scale": 100,
+ "aligned": true,
+ "impressionist": false,
+ });
+ let t = Instant::now();
+ match s.execute("paint.patternStamp", stroke.clone()) {
+ Ok(r) => {
+ let ms = t.elapsed().as_secs_f64() * 1000.0;
+ println!("patternStamp aligned hardness 100 size 200, 5800 px stroke: {ms:.1} ms");
+ println!("damage={}", r.get("damage").unwrap_or(&json!(null)));
+ }
+ Err(e) => {
+ eprintln!("paint.patternStamp: {e}");
+ std::process::exit(1);
+ }
+ }
+ let mut impressionist = stroke;
+ impressionist["impressionist"] = json!(true);
+ impressionist["points"] = json!([[100, 2400], [5900, 2400]]);
+ let t = Instant::now();
+ match s.execute("paint.patternStamp", impressionist) {
+ Ok(_) => {
+ let ms = t.elapsed().as_secs_f64() * 1000.0;
+ println!("patternStamp impressionist hardness 100 size 200, 5800 px stroke: {ms:.1} ms");
+ }
+ Err(e) => {
+ eprintln!("paint.patternStamp impressionist: {e}");
+ std::process::exit(1);
+ }
+ }
+}
diff --git a/crates/engine/src/brush_cmds.rs b/crates/engine/src/brush_cmds.rs
index 982f6cd67..665c4b63b 100644
--- a/crates/engine/src/brush_cmds.rs
+++ b/crates/engine/src/brush_cmds.rs
@@ -48,7 +48,7 @@ fn always(_: &Session) -> std::result::Result<(), String> {
}
/// Largest stroke coordinate accepted (a few times the largest document side, 300 000 px).
-const MAX_COORD: f64 = 1_000_000.0;
+pub(crate) const MAX_COORD: f64 = 1_000_000.0;
/// Parse `points`: arrays `[x, y, pressure?, tiltX?, tiltY?, rotation?, timeMs?, wheel?]` or
/// objects `{"x":…, "y":…, "pressure":…, "tiltX":…, …, "time":…}`.
diff --git a/crates/engine/src/channel_cmds.rs b/crates/engine/src/channel_cmds.rs
index 014a78aa9..a9c30e971 100644
--- a/crates/engine/src/channel_cmds.rs
+++ b/crates/engine/src/channel_cmds.rs
@@ -568,6 +568,7 @@ fn routed(id: &str) -> bool {
|| matches!(
id,
"paint.cloneStamp"
+ | "paint.patternStamp"
| "paint.healingBrush"
| "paint.spotHealing"
| "paint.dodge"
diff --git a/crates/engine/src/retouch_cmds.rs b/crates/engine/src/retouch_cmds.rs
index 7d493fa67..e306bce07 100644
--- a/crates/engine/src/retouch_cmds.rs
+++ b/crates/engine/src/retouch_cmds.rs
@@ -1,5 +1,5 @@
-//! Retouching tools as commands: Clone Stamp, Healing Brush, Spot Healing Brush, Patch,
-//! Content-Aware Move, Dodge, Burn, Sponge, Blur, Sharpen, Smudge and History Brush.
+//! Retouching tools as commands: Clone Stamp, Pattern Stamp, Healing Brush, Spot Healing Brush,
+//! Patch, Content-Aware Move, Dodge, Burn, Sponge, Blur, Sharpen, Smudge and History Brush.
//!
//! Every command takes a Photoshop-style brush (`points`, `size`, `hardness`, `opacity`, `flow`,
//! `spacing`, `layer`), respects the active selection as a mask and the layer's transparency lock, and
@@ -25,6 +25,7 @@ use crate::{EngineError, Result, Session};
mod content_aware_move;
mod patch;
+mod pattern_stamp;
pub use patch::preview as patch_preview;
fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
@@ -80,6 +81,10 @@ fn parse_brush(s: &Session, p: &Value, cmd: &str) -> Result<(Stroke, Option<Laye
if pts.is_empty() {
return Err(bad(cmd, "`points` is empty"));
}
+ // A stroke runs dab by dab along its length: an absurd coordinate would mean billions of dabs.
+ if pts.iter().any(|q| !(q.x.abs() <= crate::brush_cmds::MAX_COORD && q.y.abs() <= crate::brush_cmds::MAX_COORD)) {
+ return Err(bad(cmd, format!("point coordinates must be finite and within ±{}", crate::brush_cmds::MAX_COORD)));
+ }
let base = s.tools.brush.clone();
let pct = |k: &str, d: f32, lo: f32, hi: f32| num(p, k, d).clamp(lo, hi) / 100.0;
let brush = BrushSettings {
@@ -709,6 +714,18 @@ pub fn specs() -> Vec<CommandSpec> {
run: clone_stamp,
journal: true,
},
+ CommandSpec {
+ id: "paint.patternStamp",
+ label: "Pattern Stamp",
+ menu: &[],
+ shortcut: None,
+ params: brush_params!(
+ r#","pattern":id|name?=Patterns panel current,"scale":1..1000 %=100,"angle":deg=0,"aligned":bool=true,"impressionist":bool=false,"mode":"normal|multiply|…"="normal","phase":[px,py]? → {"damage","phase","aligned","pattern"}"#
+ ),
+ enabled: pattern_stamp::enabled,
+ run: pattern_stamp::run,
+ journal: true,
+ },
CommandSpec {
id: "paint.healingBrush",
label: "Healing Brush",
diff --git a/crates/engine/src/retouch_cmds/pattern_stamp.rs b/crates/engine/src/retouch_cmds/pattern_stamp.rs
new file mode 100644
index 000000000..cb9e0adfe
--- /dev/null
+++ b/crates/engine/src/retouch_cmds/pattern_stamp.rs
@@ -0,0 +1,311 @@
+//! Pattern Stamp: paint with the current pattern through a brush stroke.
+//!
+//! Aligned strokes lock the tile origin in document space. Unaligned strokes restart the origin at
+//! the first point of that stroke. Impressionist jitters each dab's phase with a seeded RNG so a
+//! replay of the same points is identical.
+
+use photocraft_color::{BlendMode, PixelFormat};
+use photocraft_compose::pattern::{Placement, Tile, render};
+use photocraft_doc::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};
+use photocraft_raster::{Surface, from_rgba_into, to_rgba};
+use serde_json::{Value, json};
+
+use super::{bad, blend_param, damage_json, flag, has_pixel_layer, parse_brush};
+use crate::{Result, Session};
+
+/// A single stroke's accumulated coverage must stay at or under this many pixels (8192², so a
+/// stroke corner to corner across a 24–36 MP canvas fits). Larger footprints return an error
+/// instead of allocating.
+const MAX_STROKE_PIXELS: u64 = 67_108_864;
+
+const STREAM_PHASE_X: u64 = 101;
+const STREAM_PHASE_Y: u64 = 102;
+
+pub(super) fn enabled(s: &Session) -> std::result::Result<(), String> {
+ has_pixel_layer(s)?;
+ 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"));
+ }
+ 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;
+
+ let dmg = s.edit("Pattern Stamp", |doc, _| {
+ crate::pattern_cmds::ensure_in_doc(doc, &pat);
+ let pre = doc.clone();
+ let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?;
+ let sel = pre.selection.as_ref();
+ if impressionist {
+ paint_impressionist(surf, &stroke, sel, lock, &tile, &pat, phase, scale, angle, seed, mode)
+ } else {
+ paint_aligned(surf, &stroke, sel, lock, &tile, phase, scale, angle, mode, CMD)
+ }
+ })?;
+ if let Some(st) = s.active_mut() {
+ st.last_damage = Some(dmg);
+ }
+ Ok(json!({
+ "damage": damage_json(dmg),
+ "phase": [phase.0, phase.1],
+ "aligned": aligned,
+ "pattern": pat.id,
+ }))
+}
+
+fn stamp_scale(p: &Value, cmd: &str) -> Result<f32> {
+ match p.get("scale") {
+ None => Ok(1.0),
+ Some(v) => {
+ let s = v.as_f64().ok_or_else(|| bad(cmd, "`scale` must be a number (1..1000 %)"))?;
+ if !s.is_finite() || !(1.0..=1000.0).contains(&s) {
+ return Err(bad(cmd, "scale must be 1..1000 %"));
+ }
+ Ok((s as f32) / 100.0)
+ }
+ }
+}
+
+fn stamp_angle(p: &Value, cmd: &str) -> Result<f32> {
+ match p.get("angle") {
+ None => Ok(0.0),
+ Some(v) => {
+ let a = v.as_f64().ok_or_else(|| bad(cmd, "`angle` must be a number (degrees)"))?;
+ if !a.is_finite() {
+ return Err(bad(cmd, "`angle` must be finite"));
+ }
+ Ok(a as f32)
+ }
+ }
+}
+
+fn stamp_phase(p: &Value, cmd: &str, aligned: bool, first: &StrokePoint) -> Result<(f32, f32)> {
+ match p.get("phase") {
+ None => {
+ if aligned {
+ Ok((0.0, 0.0))
+ } else {
+ Ok((first.x as f32, first.y as f32))
+ }
+ }
+ Some(v) => {
+ let a = v.as_array().ok_or_else(|| bad(cmd, "`phase` must be [px, py]"))?;
+ let x = a.first().and_then(Value::as_f64).ok_or_else(|| bad(cmd, "`phase` must be [px, py]"))?;
+ let y = a.get(1).and_then(Value::as_f64).ok_or_else(|| bad(cmd, "`phase` must be [px, py]"))?;
+ if !x.is_finite() || !y.is_finite() {
+ return Err(bad(cmd, "`phase` coordinates must be finite"));
+ }
+ Ok((x as f32, y as f32))
+ }
+ }
+}
+
+fn reject_huge_stroke(cmd: &str, stroke: &Stroke) -> Result<()> {
+ let pad = f64::from(stroke.brush.size.max(1.0)).mul_add(0.5, 4.0);
+ let mut min_x = f64::INFINITY;
+ let mut min_y = f64::INFINITY;
+ let mut max_x = f64::NEG_INFINITY;
+ let mut max_y = f64::NEG_INFINITY;
+ for q in &stroke.points {
+ min_x = min_x.min(q.x);
+ min_y = min_y.min(q.y);
+ max_x = max_x.max(q.x);
+ max_y = max_y.max(q.y);
+ }
+ if !min_x.is_finite() || !min_y.is_finite() || !max_x.is_finite() || !max_y.is_finite() {
+ return Err(bad(cmd, "point coordinates must be finite"));
+ }
+ let w = (max_x - min_x + pad * 2.0).ceil().max(1.0);
+ let h = (max_y - min_y + pad * 2.0).ceil().max(1.0);
+ if !w.is_finite() || !h.is_finite() || w > 1.0e9 || h > 1.0e9 {
+ return Err(bad(cmd, format!("stroke too large (at most {MAX_STROKE_PIXELS} px)")));
+ }
+ let area = (w as u64).saturating_mul(h as u64);
+ if area > MAX_STROKE_PIXELS {
+ return Err(bad(cmd, format!("stroke too large ({w:.0}×{h:.0} px, at most {MAX_STROKE_PIXELS})")));
+ }
+ Ok(())
+}
+
+fn reject_bounds(cmd: &str, bounds: Rect) -> Result<()> {
+ if bounds.is_empty() {
+ return Ok(());
+ }
+ let (w, h) = (u64::from(bounds.width()), u64::from(bounds.height()));
+ let area = w.saturating_mul(h);
+ if area > MAX_STROKE_PIXELS {
+ return Err(bad(cmd, format!("stroke too large ({w}×{h} px, at most {MAX_STROKE_PIXELS})")));
+ }
+ Ok(())
+}
+
+fn placement(phase: (f32, f32), scale: f32, angle: f32) -> Placement {
+ Placement::new(Rect::EMPTY, false, phase, scale, angle)
+}
+
+fn rgba_to_region(fmt: &PixelFormat, rect: Rect, rgba: &[[f32; 4]]) -> Region {
+ let n = fmt.channels();
+ let mut paint = Region::new(rect, n);
+ let mut enc = [0.0f32; 8];
+ for (i, px) in rgba.iter().enumerate() {
+ from_rgba_into(fmt, *px, &mut enc);
+ let Some(start) = i.checked_mul(n) else { continue };
+ let Some(end) = start.checked_add(n) else { continue };
+ if let (Some(dst), Some(src)) = (paint.data.get_mut(start..end), enc.get(..n)) {
+ dst.copy_from_slice(src);
+ }
+ }
+ paint
+}
+
+#[allow(clippy::too_many_arguments)]
+fn paint_aligned(
+ surf: &mut Surface,
+ stroke: &Stroke,
+ sel: Option<&Surface>,
+ lock: bool,
+ tile: &Tile,
+ phase: (f32, f32),
+ scale: f32,
+ angle: f32,
+ mode: BlendMode,
+ cmd: &str,
+) -> Result<Rect> {
+ let (bounds, cov) = stroke_coverage(stroke);
+ reject_bounds(cmd, bounds)?;
+ 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);
+ 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;
+ }
+ let dx = x.wrapping_sub(fp.rect.x0) as u32;
+ let dy = y.wrapping_sub(fp.rect.y0) as u32;
+ let w = fp.rect.width();
+ let idx = (dy as usize).saturating_mul(w as usize).saturating_add(dx as usize);
+ fp.cov.get(idx).copied().unwrap_or(0.0)
+}
+
+#[allow(clippy::too_many_arguments)]
+fn stamp_dab(
+ work: &mut Region,
+ fmt: &PixelFormat,
+ tile: &Tile,
+ fp: &Footprint,
+ phase: (f32, f32),
+ scale: f32,
+ angle: f32,
+ seed: u64,
+ tw: f32,
+ th: f32,
+ mode: BlendMode,
+) {
+ let r = fp.rect.intersect(&work.rect);
+ if r.is_empty() {
+ return;
+ }
+ let i = fp.index as u64;
+ let jx = photocraft_paint::rng::rand_signed(seed, i, STREAM_PHASE_X) * tw;
+ let jy = photocraft_paint::rng::rand_signed(seed, i, STREAM_PHASE_Y) * th;
+ let place = placement((phase.0 + jx, phase.1 + jy), scale, angle);
+ let rgba = render(tile, &place, r);
+ let rw = r.width() as usize;
+ let n = work.ch;
+ let mut enc = [0.0f32; 8];
+ for y in r.y0..r.y1 {
+ for x in r.x0..r.x1 {
+ let k = footprint_cov(fp, x, y);
+ if k <= 0.0 {
+ continue;
+ }
+ let ox = (x - r.x0) as usize;
+ let oy = (y - r.y0) as usize;
+ let Some(px) = rgba.get(oy.saturating_mul(rw).saturating_add(ox)) else { continue };
+ from_rgba_into(fmt, *px, &mut enc);
+ let dst = work.px_mut(x, y);
+ if mode == BlendMode::Normal {
+ if let Some(src) = enc.get(..n) {
+ over_native(fmt, dst, src, k, false);
+ }
+ } else {
+ let d = to_rgba(fmt, dst);
+ let o = photocraft_color::blend::composite(mode, d, *px, k);
+ from_rgba_into(fmt, o, &mut enc);
+ if let Some(src) = enc.get(..n) {
+ dst.copy_from_slice(src);
+ }
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn stroke(points: &[(f64, f64)], size: f32) -> Stroke {
+ let brush = photocraft_paint::BrushSettings { size, ..Default::default() };
+ Stroke { brush, points: points.iter().map(|&(x, y)| StrokePoint::new(x, y, 1.0)).collect() }
+ }
+
+ #[test]
+ fn a_diagonal_across_a_24_mp_canvas_is_not_too_large() {
+ assert!(reject_huge_stroke("t", &stroke(&[(0.0, 0.0), (6015.0, 3999.0)], 100.0)).is_ok());
+ assert!(reject_bounds("t", Rect::from_xywh(-60, -60, 6136, 4120)).is_ok());
+ assert!(reject_huge_stroke("t", &stroke(&[(0.0, 0.0), (9000.0, 9000.0)], 100.0)).is_err());
+ assert!(reject_bounds("t", Rect::from_xywh(0, 0, 9000, 9000)).is_err());
+ }
+}
diff --git a/crates/engine/src/retouch_cmds/tests.rs b/crates/engine/src/retouch_cmds/tests.rs
index b4a7f30a5..fd30b0099 100644
--- a/crates/engine/src/retouch_cmds/tests.rs
+++ b/crates/engine/src/retouch_cmds/tests.rs
@@ -316,6 +316,7 @@ fn history_brush_errors_when_layer_is_new() {
fn retouch_commands_are_registered_and_need_a_pixel_layer() {
let ids = [
"paint.cloneStamp",
+ "paint.patternStamp",
"paint.healingBrush",
"paint.spotHealing",
"paint.dodge",
@@ -341,8 +342,9 @@ fn retouch_commands_are_registered_and_need_a_pixel_layer() {
// Paint target (#207): mask, alpha channel, Quick Mask
// ---------------------------------------------------------------------------------------------
-const RETOUCH_IDS: [&str; 10] = [
+const RETOUCH_IDS: [&str; 11] = [
"paint.cloneStamp",
+ "paint.patternStamp",
"paint.healingBrush",
"paint.spotHealing",
"paint.dodge",
@@ -926,3 +928,165 @@ fn clone_and_heal_with_a_far_source_are_plain_errors() {
s.execute(cmd, json!({"points": [[10, 10], [30, 10]], "source": [2147483000, 0]})).unwrap();
}
}
+
+fn stamp(s: &mut Session, extra: Value) -> Result<Value> {
+ let mut p = json!({"points": [[16, 16]], "size": 16, "hardness": 100, "pattern": "Checkerboard", "scale": 100, "aligned": true});
+ if let Some(obj) = extra.as_object() {
+ for (k, v) in obj {
+ p[k] = v.clone();
+ }
+ }
+ s.execute("paint.patternStamp", p)
+}
+
+fn checker_at(x: i32, y: i32) -> f32 {
+ if (x.div_euclid(8) + y.div_euclid(8)).rem_euclid(2) == 0 { 0.8 } else { 1.0 }
+}
+
+#[test]
+fn pattern_stamp_paints_the_tile_at_every_depth_and_undoes() {
+ for depth in DEPTHS {
+ let mut s = session(64, 48, depth, "rgb");
+ let before = rgba(&s, 16, 16);
+ let r = stamp(&mut s, json!({"points": [[16, 16]]})).unwrap();
+ assert_eq!(r["aligned"], json!(true));
+ assert_eq!(r["phase"], json!([0.0, 0.0]));
+ assert!(r["pattern"].as_str().is_some_and(|id| !id.is_empty()), "{r}");
+ let got = rgba(&s, 16, 16);
+ let want = checker_at(16, 16);
+ for c in 0..3 {
+ assert!((got[c] - want).abs() <= tol(depth), "depth {depth} {got:?} want {want}");
+ }
+ assert!(got[3] > 0.99, "{got:?}");
+ assert_ne!(got, before);
+ assert!(s.active().unwrap().doc.patterns.iter().any(|p| p.name == "Checkerboard"));
+ assert!(s.undo());
+ assert!((rgba(&s, 16, 16)[0] - before[0]).abs() <= tol(depth));
+ assert!(s.redo());
+ assert!((rgba(&s, 16, 16)[0] - want).abs() <= tol(depth));
+ }
+ let mut g = session(48, 32, 16, "gray");
+ stamp(&mut g, json!({"points": [[16, 16]]})).unwrap();
+ let p = rgba(&g, 16, 16);
+ assert!((p[0] - checker_at(16, 16)).abs() <= tol(16), "{p:?}");
+}
+
+#[test]
+fn pattern_stamp_integer_scale_reproduces_the_tile_in_the_dab() {
+ let mut s = session(32, 32, 8, "rgb");
+ stamp(&mut s, json!({"points": [[8, 8]], "size": 16, "hardness": 100, "phase": [0, 0]})).unwrap();
+ for (x, y) in [(8, 8), (10, 8), (8, 12)] {
+ let got = rgba(&s, x, y);
+ let want = checker_at(x, y);
+ assert!((got[0] - want).abs() <= tol(8) && (got[1] - want).abs() <= tol(8), "({x},{y}) {got:?} want {want}");
+ }
+}
+
+#[test]
+fn pattern_stamp_scaled_tiles_have_no_gaps() {
+ for scale in [50.0, 200.0] {
+ let mut s = session(64, 48, 8, "rgb");
+ stamp(&mut s, json!({"points": [[24, 24]], "size": 24, "hardness": 100, "scale": scale, "phase": [0, 0]})).unwrap();
+ let mut holes = 0;
+ for y in 20..28 {
+ for x in 20..28 {
+ if rgba(&s, x, y)[3] < 0.5 {
+ holes += 1;
+ }
+ }
+ }
+ assert_eq!(holes, 0, "scale {scale}: transparent holes inside the dab");
+ }
+}
+
+#[test]
+fn pattern_stamp_aligned_keeps_document_phase_across_strokes() {
+ let mut s = session(80, 40, 8, "rgb");
+ stamp(&mut s, json!({"points": [[10, 16]], "size": 8, "hardness": 100, "aligned": true, "phase": [0, 0]})).unwrap();
+ let a = rgba(&s, 10, 16);
+ stamp(&mut s, json!({"points": [[18, 16]], "size": 8, "hardness": 100, "aligned": true, "phase": [0, 0]})).unwrap();
+ let b = rgba(&s, 18, 16);
+ assert!((a[0] - checker_at(10, 16)).abs() <= tol(8), "{a:?}");
+ assert!((b[0] - checker_at(18, 16)).abs() <= tol(8), "{b:?}");
+ assert!((a[0] - b[0]).abs() > 0.05, "aligned wallpaper: (10,16) and (18,16) sit on different cells");
+}
+
+#[test]
+fn pattern_stamp_unaligned_restarts_at_each_stroke() {
+ let mut s = session(80, 40, 8, "rgb");
+ let r1 = stamp(&mut s, json!({"points": [[10, 16]], "size": 8, "hardness": 100, "aligned": false})).unwrap();
+ assert_eq!(r1["phase"], json!([10.0, 16.0]));
+ let a = rgba(&s, 10, 16);
+ let r2 = stamp(&mut s, json!({"points": [[40, 16]], "size": 8, "hardness": 100, "aligned": false})).unwrap();
+ assert_eq!(r2["phase"], json!([40.0, 16.0]));
+ let b = rgba(&s, 40, 16);
+ assert!((a[0] - b[0]).abs() <= tol(8), "each stroke's first point is the tile origin: {a:?} vs {b:?}");
+}
+
+#[test]
+fn pattern_stamp_impressionist_is_seeded_and_replayable() {
+ let pts = json!([[20, 20], [36, 22], [52, 20]]);
+ let params = json!({"points": pts, "size": 12, "hardness": 80, "pattern": "Bricks", "impressionist": true, "aligned": true});
+ let mut a = session(80, 40, 8, "rgb");
+ a.execute("paint.patternStamp", params.clone()).unwrap();
+ let mut samples = [[0.0f32; 4]; 3];
+ for (i, x) in [20, 36, 52].into_iter().enumerate() {
+ samples[i] = rgba(&a, x, 20);
+ }
+ assert!(a.undo());
+ a.execute("paint.patternStamp", params.clone()).unwrap();
+ for (i, x) in [20, 36, 52].into_iter().enumerate() {
+ let got = rgba(&a, x, 20);
+ for c in 0..4 {
+ assert!((got[c] - samples[i][c]).abs() < 1e-6, "replay x={x} {got:?} vs {:?}", samples[i]);
+ }
+ }
+ let mut b = session(80, 40, 8, "rgb");
+ let mut off = params.clone();
+ off["impressionist"] = json!(false);
+ b.execute("paint.patternStamp", off).unwrap();
+ let smooth = rgba(&b, 36, 20);
+ let noisy = samples[1];
+ assert!((noisy[0] - smooth[0]).abs() > 1e-4 || (noisy[1] - smooth[1]).abs() > 1e-4, "impressionist should jitter the phase: {noisy:?} vs {smooth:?}");
+}
+
+#[test]
+fn pattern_stamp_tile_seam_matches_an_untilled_reference() {
+ let mut s = session(96, 96, 8, "rgb");
+ stamp(&mut s, json!({"points": [[64, 48]], "size": 32, "hardness": 100, "phase": [0, 0]})).unwrap();
+ let pat = s.patterns.items.iter().find(|p| p.name == "Checkerboard").cloned().expect("builtin");
+ let tile = photocraft_compose::pattern::Tile::new(&pat).expect("tile");
+ let place = photocraft_compose::pattern::Placement::new(photocraft_geom::Rect::EMPTY, false, (0.0, 0.0), 1.0, 0.0);
+ let col = photocraft_geom::Rect::new(64, 40, 65, 56);
+ let reference = photocraft_compose::pattern::render(&tile, &place, col);
+ for (i, y) in (40..56).enumerate() {
+ let got = rgba(&s, 64, y);
+ let want = reference[i];
+ for c in 0..3 {
+ assert!((got[c] - want[c]).abs() <= tol(8), "y={y} {got:?} vs {want:?}");
+ }
+ }
+}
+
+#[test]
+fn pattern_stamp_rejects_hostile_input() {
+ let mut s = session(64, 48, 8, "rgb");
+ assert!(s.execute("paint.patternStamp", json!({"points": [], "pattern": "Checkerboard"})).is_err());
+ assert!(s.execute("paint.patternStamp", json!({"pattern": "Checkerboard"})).is_err());
+ assert!(s.execute("paint.patternStamp", json!({"points": [[16, 16]], "pattern": "no-such-pattern"})).is_err());
+ assert!(s.execute("paint.patternStamp", json!({"points": [[16, 16]], "pattern": "Checkerboard", "size": 1e30})).is_err());
+ assert!(s.execute("paint.patternStamp", json!({"points": [[1e7, 0]], "pattern": "Checkerboard", "size": 8})).is_err());
+ assert!(s.execute("paint.patternStamp", json!({"points": [[f64::NAN, 0]], "pattern": "Checkerboard", "size": 8})).is_err());
+ assert!(s.execute("paint.patternStamp", json!({"points": [[0, 0], [9000, 9000]], "pattern": "Checkerboard", "size": 5000, "hardness": 100})).is_err());
+ let fmt = photocraft_color::PixelFormat::new(photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8, false);
+ s.patterns.items.push(photocraft_doc::Pattern {
+ id: "empty-pat".into(),
+ name: "EmptyTile".into(),
+ width: 0,
+ height: 0,
+ surface: photocraft_raster::Surface::new(fmt),
+ });
+ assert!(s.execute("paint.patternStamp", json!({"points": [[8, 8]], "pattern": "EmptyTile", "size": 8})).is_err());
+ s.execute("layer.setProps", json!({"locks": {"pixels": true}})).unwrap();
+ assert!(stamp(&mut s, json!({"points": [[16, 16]]})).is_err());
+}
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 2ffa96ea9..bdeae2dd2 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -432,6 +432,7 @@ pub(crate) fn freehand_tool(tool: Tool) -> bool {
| Tool::SpotHealing
| Tool::Healing
| Tool::CloneStamp
+ | Tool::PatternStamp
| Tool::Blur
| Tool::Sharpen
| Tool::Smudge
@@ -3577,6 +3578,7 @@ mod tests {
Tool::Eraser,
Tool::BackgroundEraser,
Tool::CloneStamp,
+ Tool::PatternStamp,
Tool::Smudge,
Tool::Dodge,
Tool::Lasso,
@@ -3596,6 +3598,12 @@ mod tests {
assert!(brush_tip_centre(Tool::Healing, true, false, 20.0));
assert!(!brush_tip_centre(Tool::Healing, false, false, 20.0));
assert!(brush_tip_centre(Tool::CloneStamp, false, true, 20.0));
+ assert!(brush_tip_centre(Tool::PatternStamp, false, false, 20.0));
+ assert!(
+ brush_tip_centre(Tool::PatternStamp, true, false, 20.0),
+ "Pattern Stamp keeps the brush centre; Option does not switch it to a clone-source mark"
+ );
+ assert!(!brush_tip_centre(Tool::PatternStamp, false, false, 2.0));
assert!(brush_tip_centre(Tool::Brush, false, false, 20.0));
assert!(!brush_tip_centre(Tool::QuickSelection, false, false, 20.0));
assert!(brush_tip_centre(Tool::BackgroundEraser, false, false, 2.0));
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index d78237562..b79e56c2f 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -2211,3 +2211,8 @@ fontWeight Bold Tučná
fontWeight ExtraBold Extratučná
fontWeight Black Černá
fontWeight Italic Kurzíva
+
+# Pattern Stamp tool
+ Pattern Stamp Tool Nástroj razítko vzorku
+ Pattern Stamp Razítko vzorku
+ Impressionist Impresionista
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index 7d472a295..62a32495b 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -2251,3 +2251,8 @@ fontWeight Bold Fett
fontWeight ExtraBold Extrafett
fontWeight Black Schwarz
fontWeight Italic Kursiv
+
+# Pattern Stamp tool
+ Pattern Stamp Tool Musterstempel-Werkzeug
+ Pattern Stamp Musterstempel
+ Impressionist Impressionistisch
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index 61c1babdf..178b06ff9 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -2281,3 +2281,8 @@ fontWeight Bold Negrita
fontWeight ExtraBold Extranegra
fontWeight Black Ultraniegra
fontWeight Italic Cursiva
+
+# Pattern Stamp tool
+ Pattern Stamp Tool Herramienta Sello de motivo
+ Pattern Stamp Sello de motivo
+ Impressionist Impresionista
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index c39252bf6..cafccef5d 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -2639,3 +2639,7 @@ fontWeight Bold Gras
fontWeight ExtraBold Extra-gras
fontWeight Black Noir
fontWeight Italic Italique
+
+# Pattern Stamp tool
+ Pattern Stamp Tool Outil Tampon de motif
+ Impressionist Impressionniste
diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv
index 7d9c6a0b0..d83a67a09 100644
--- a/crates/ui-egui/src/i18n/id.tsv
+++ b/crates/ui-egui/src/i18n/id.tsv
@@ -2025,7 +2025,7 @@
Magnetic Lasso Magnetic Lasso
History Brush History Brush
Art History Brush Art History Brush
- Pattern Stamp Pattern Stamp
+ Pattern Stamp Stempel Pola
Spot Healing Spot Healing
Red Eye Red Eye
Patch Patch
@@ -2626,3 +2626,7 @@ fontWeight Bold Tebal
fontWeight ExtraBold Ekstra Tebal
fontWeight Black Sangat Tebal
fontWeight Italic Miring
+
+# Pattern Stamp tool
+ Pattern Stamp Tool Alat Stempel Pola
+ Impressionist Impresionis
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index 7721193b3..e5c245baf 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -2282,3 +2282,9 @@ fontWeight Bold Grassetto
fontWeight ExtraBold Extra-grassetto
fontWeight Black Nero
fontWeight Italic Corsivo
+
+# Pattern Stamp tool
+ Pattern Stamp Tool Strumento Timbro motivo
+ Pattern Stamp Timbro motivo
+ Impressionist Impressionista
+
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index b2eda6df2..9879cd084 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -2194,3 +2194,8 @@ fontWeight Bold 太字
fontWeight ExtraBold 特太
fontWeight Black 極太
fontWeight Italic 斜体
+
+# Pattern Stamp tool
+ Pattern Stamp Tool パターンスタンプツール
+ Pattern Stamp パターンスタンプ
+ Impressionist 印象派
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index f250392d1..64ae82d61 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -2794,3 +2794,8 @@ fontWeight Bold 굵게
fontWeight ExtraBold 더 굵게
fontWeight Black 아주 굵게
fontWeight Italic 기울임
+
+# Pattern Stamp tool
+ Pattern Stamp Tool 패턴 스탬프 도구
+ Pattern Stamp 패턴 스탬프
+ Impressionist 인상파
diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n/mod.rs
index 8036e1a24..a93e41c91 100644
--- a/crates/ui-egui/src/i18n/mod.rs
+++ b/crates/ui-egui/src/i18n/mod.rs
@@ -725,6 +725,21 @@ mod tests {
}
}
+ #[test]
+ fn pattern_stamp_ui_strings_have_translations_in_every_registered_language() {
+ const STRINGS: &[&str] = &["Pattern Stamp Tool", "Pattern Stamp", "Impressionist", "Aligned"];
+ for lang in Lang::all() {
+ for source in STRINGS {
+ let translated = tr(lang, source);
+ if lang == Lang::EN {
+ assert_eq!(translated, *source, "English source string {source}");
+ } else {
+ assert_ne!(translated, *source, "{} is missing {source:?}", lang.code());
+ }
+ }
+ }
+ }
+
/// Camera Raw includes dynamic colour-band labels and contextual labels that the generic
/// tl! scanner cannot see. Cover the partial catalog too, without claiming whole-app coverage.
#[test]
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index 098ec8144..43fe84590 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -3243,3 +3243,6 @@ cameraRaw Roughness Chropowatość
Edits that change the whole document, such as a layer's blend mode, opacity or visibility, redraw all of it. Zmiany obejmujące cały dokument, takie jak tryb mieszania, krycie lub widoczność warstwy, odświeżają go w całości.
Its layers don't fit the GPU memory budget. Raising Memory usage in Preferences › Performance raises the budget, up to a quarter of this computer's memory. Warstwy nie mieszczą się w budżecie pamięci GPU. Zwiększenie wartości Użycie pamięci w Preferencje › Wydajność zwiększa budżet, maksymalnie do jednej czwartej pamięci tego komputera.
The GPU compositor wasn't used: {reason} Kompozytor GPU nie został użyty: {reason}
+# Pattern Stamp tool
+ Pattern Stamp Tool Narzędzie Pieczątka wzoru
+ Impressionist Impresjonistyczny
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index 2b2feffb4..8fd7f7ed6 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -2646,3 +2646,7 @@ fontWeight Bold Negrito
fontWeight ExtraBold Extranegrito
fontWeight Black Ultraniegra
fontWeight Italic Itálico
+
+# Pattern Stamp tool
+ Pattern Stamp Tool Ferramenta Carimbo de padrão
+ Impressionist Impressionista
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index f9b69d3c5..2b56d93ab 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -2486,3 +2486,7 @@ fontWeight Bold Жирный
fontWeight ExtraBold Особо жирный
fontWeight Black Чёрный
fontWeight Italic Курсив
+
+# Pattern Stamp tool
+ Pattern Stamp Tool Инструмент узорный штамп
+ Impressionist Импрессионист
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index ec720c08f..dd0360e1a 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -2219,3 +2219,8 @@ fontWeight Bold 粗体
fontWeight ExtraBold 特粗
fontWeight Black 黑体
fontWeight Italic 斜体
+
+# Pattern Stamp tool
+ Pattern Stamp Tool 图案图章工具
+ Pattern Stamp 图案图章
+ Impressionist 印象派
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index 500468471..fb01a3266 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -2188,3 +2188,8 @@ fontWeight Bold 粗體
fontWeight ExtraBold 特粗
fontWeight Black 黑體
fontWeight Italic 斜體
+
+# Pattern Stamp tool
+ Pattern Stamp Tool 圖案圖章工具
+ Pattern Stamp 圖案圖章
+ Impressionist 印象派
diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs
index 00e501392..d91108771 100644
--- a/crates/ui-egui/src/icons.rs
+++ b/crates/ui-egui/src/icons.rs
@@ -89,6 +89,7 @@ pub fn tool_icon(t: Tool) -> &'static str {
Tool::ContentAwareMove => "arrow-left-right",
Tool::RedEye => "eye",
Tool::CloneStamp => "stamp",
+ Tool::PatternStamp => "grid-3x3",
Tool::HistoryBrush => "clock",
Tool::Blur => "droplet",
Tool::Sharpen => "triangle",
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index d4529cbaa..3a72f74b9 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -26,7 +26,7 @@ const TOOL_SECTIONS: &[&[&[Tool]]] = &[
&[
&[Tool::SpotHealing, Tool::Healing, Tool::Patch, Tool::ContentAwareMove, Tool::RedEye],
&[Tool::Brush, Tool::Pencil, Tool::MixerBrush],
- &[Tool::CloneStamp],
+ &[Tool::CloneStamp, Tool::PatternStamp],
&[Tool::HistoryBrush],
&[Tool::Eraser, Tool::BackgroundEraser, Tool::MagicEraser],
&[Tool::Gradient, Tool::PaintBucket],
@@ -3176,6 +3176,42 @@ mod type_flyout_tests {
assert!(j.contains(&Tool::RedEye), "{j:?}");
assert_eq!(j.last(), Some(&Tool::RedEye));
}
+
+ #[test]
+ fn long_press_clone_stamp_selects_pattern_stamp() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]);
+ frame(&mut app, &ctx, 0.0, vec![]);
+ frame(&mut app, &ctx, 0.1, vec![]);
+ let index = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).position(|slot| slot.contains(&Tool::CloneStamp)).unwrap();
+ let slot = TOOL_SECTIONS.iter().flat_map(|section| section.iter()).nth(index).copied().unwrap();
+ assert_eq!(slot, &[Tool::CloneStamp, Tool::PatternStamp]);
+ let bx = if Tokens::get(&ctx).pro { 30.0 } else { 36.0 };
+ let mut buttons: Vec<Rect> = ctx.viewport(|v| {
+ v.prev_pass
+ .widgets
+ .layers()
+ .flat_map(|(_, w)| w.iter())
+ .filter(|w| w.rect.size() == egui::Vec2::splat(bx) && w.sense.senses_click())
+ .map(|w| w.rect)
+ .collect()
+ });
+ buttons.sort_by(|a, b| a.top().total_cmp(&b.top()));
+ let at = buttons[index].center();
+ let pointer = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
+ frame(&mut app, &ctx, 1.0, vec![egui::Event::PointerMoved(at), pointer(at, true)]);
+ frame(&mut app, &ctx, 1.36, vec![]);
+ assert_eq!(ctx.data(|d| d.get_temp::<(egui::Id, Rect)>(egui::Id::new("tool-flyout"))).map(|(id, _)| id), Some(egui::Id::new(("tool-slot", index))));
+ frame(&mut app, &ctx, 1.4, vec![pointer(at, false)]);
+ frame(&mut app, &ctx, 1.45, vec![]);
+ let key = egui::Id::new(("tool-slot", index));
+ let menu = ctx.memory(|m| m.area_rect(key.with("flyout"))).unwrap();
+ let row = egui::pos2(menu.left() + 65.0, menu.top() + 39.0 + 8.0);
+ frame(&mut app, &ctx, 2.0, vec![egui::Event::PointerMoved(row), pointer(row, true)]);
+ frame(&mut app, &ctx, 2.05, vec![pointer(row, false)]);
+ assert_eq!(app.ui.tool, Tool::PatternStamp);
+ }
}
#[cfg(test)]
diff --git a/crates/ui-egui/src/preset_panels.rs b/crates/ui-egui/src/preset_panels.rs
index 29468bfa4..2dc728295 100644
--- a/crates/ui-egui/src/preset_panels.rs
+++ b/crates/ui-egui/src/preset_panels.rs
@@ -1104,6 +1104,7 @@ mod tests {
assert_eq!(app.ui.tool, Tool::Eraser);
assert_eq!(app.session.tools.brush.size, 60.0);
assert_eq!(tool_id(Tool::CloneStamp), "cloneStamp");
+ assert_eq!(tool_id(Tool::PatternStamp), "patternStamp");
assert_eq!(Tool::from_name(&tool_id(Tool::CustomShape)), Some(Tool::CustomShape));
}
diff --git a/crates/ui-egui/src/retouch_ui.rs b/crates/ui-egui/src/retouch_ui.rs
index 8c9125fc6..7460c3f52 100644
--- a/crates/ui-egui/src/retouch_ui.rs
+++ b/crates/ui-egui/src/retouch_ui.rs
@@ -28,6 +28,23 @@ pub fn finish_stroke(app: &mut PhotocraftApp, tool: Tool, points: &[[f64; 3]], m
let (cmd, mut p): (&str, Value) = match tool {
Tool::SpotHealing => ("paint.spotHealing", json!({"type": o.spot_type, "sampleAllLayers": o.sample_all_layers})),
Tool::MixerBrush => ("paint.mixerBrush", json!({})),
+ 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::Healing | Tool::CloneStamp => {
let mut p = json!({"aligned": o.clone_aligned, "sampleLayer": o.clone_sample});
// The Clone Source panel's active slot (set by ⌥-click) drives the stroke: the engine
@@ -78,6 +95,9 @@ pub fn finish_stroke(app: &mut PhotocraftApp, tool: Tool, points: &[[f64; 3]], m
// Aligned: keep the offset for later strokes; non-aligned: every stroke restarts at the source.
app.ui.clone_offset = r.get("offset").and_then(|v| serde_json::from_value(v.clone()).ok()).filter(|_| o.clone_aligned);
}
+ Ok(r) if tool == Tool::PatternStamp => {
+ app.ui.pattern_stamp_phase = r.get("phase").and_then(|v| serde_json::from_value(v.clone()).ok()).filter(|_| o.pattern_stamp_aligned);
+ }
Ok(_) => {}
Err(e) => {
app.ui.status = e;
@@ -257,6 +277,9 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo
crate::widgets::vline(ui, 22.0);
opt(ui, tl!("Lasso around an area, then drag the selection"));
}
+ Tool::PatternStamp => {
+ pattern_stamp_options(app, ui);
+ }
Tool::Healing | Tool::CloneStamp => {
crate::widgets::checkbox(ui, &mut o.clone_aligned, tl!("Aligned"));
opt(ui, tl!("Sample:"));
@@ -325,6 +348,30 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo
true
}
+fn pattern_stamp_options(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
+ let opts: Vec<(String, String)> = app.session.patterns.items.iter().map(|p| (p.id.clone(), p.display_name().to_string())).collect();
+ let mut pat = photocraft_engine::presets::patterns::current(&app.session).or(app.session.patterns.items.first()).map(|p| p.id.clone()).unwrap_or_default();
+ let o = &mut app.ui.tool_options;
+ crate::widgets::checkbox(ui, &mut o.pattern_stamp_aligned, tl!("Aligned"));
+ crate::widgets::checkbox(ui, &mut o.pattern_stamp_impressionist, tl!("Impressionist"));
+ crate::widgets::vline(ui, 22.0);
+ opt(ui, tl!("Pattern"));
+ let opts_ref: Vec<(String, &str)> = opts.iter().map(|(id, n)| (id.clone(), n.as_str())).collect();
+ let picked = if opts_ref.is_empty() {
+ ui.label(egui::RichText::new(tl!("No patterns")).color(Tokens::get(ui.ctx()).text_faint));
+ false
+ } else {
+ crate::widgets::dropdown(ui, "pattern-stamp-pat", &mut pat, &opts_ref, 140.0)
+ };
+ opt(ui, tl!("Scale"));
+ crate::widgets::value_field(ui, &mut o.pattern_stamp_scale, 1.0..=1000.0, "%", 58.0);
+ opt(ui, tl!("Angle:"));
+ crate::widgets::value_field(ui, &mut o.pattern_stamp_angle, -180.0..=180.0, "°", 58.0);
+ if picked {
+ let _ = app.run("pattern.presets.select", json!({"pattern": pat}));
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -585,4 +632,37 @@ mod tests {
assert!(j.contains(&Tool::RedEye));
assert!(j.iter().all(|t| t.key() == 'J'));
}
+
+ #[test]
+ fn s_group_is_clone_stamp_then_pattern_stamp() {
+ assert_eq!(Tool::CloneStamp.key(), 'S');
+ assert_eq!(Tool::PatternStamp.key(), 'S');
+ let group: Vec<Tool> = Tool::ALL.iter().copied().filter(|t| t.key() == 'S').collect();
+ assert_eq!(group, vec![Tool::CloneStamp, Tool::PatternStamp]);
+ assert_eq!(Tool::from_name("patternStamp"), Some(Tool::PatternStamp));
+ }
+
+ #[test]
+ fn pattern_stamp_stroke_paints_pixels_and_keeps_phase_when_aligned() {
+ let mut app = app();
+ assert!(finish_stroke(&mut app, Tool::PatternStamp, &[[20.0, 30.0, 1.0], [50.0, 30.0, 1.0]], egui::Modifiers::NONE));
+ assert!(!app.ui.status_error, "{}", app.ui.status);
+ assert_eq!(app.session.journal.last().map(|(id, _)| id.as_str()), Some("paint.patternStamp"));
+ assert!(app.ui.pattern_stamp_phase.is_some());
+ let px = active(&app).surface().unwrap().rgba(30, 30);
+ assert!(px[3] > 0.5, "the stamp paints through the brush: {px:?}");
+ app.ui.tool_options.pattern_stamp_aligned = false;
+ app.ui.pattern_stamp_phase = None;
+ assert!(finish_stroke(&mut app, Tool::PatternStamp, &[[70.0, 30.0, 1.0]], egui::Modifiers::NONE));
+ assert!(app.ui.pattern_stamp_phase.is_none(), "unaligned strokes do not keep phase");
+ }
+
+ #[test]
+ fn pattern_stamp_does_not_require_a_clone_source() {
+ let mut app = app();
+ assert!(app.ui.clone_source.is_none());
+ assert!(finish_stroke(&mut app, Tool::PatternStamp, &[[12.0, 30.0, 1.0]], egui::Modifiers::NONE));
+ assert!(!app.ui.status_error, "{}", app.ui.status);
+ assert!(app.ui.clone_source.is_none());
+ }
}
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index b558db217..12706fb75 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -92,6 +92,7 @@ pub enum Tool {
ContentAwareMove,
RedEye,
CloneStamp,
+ PatternStamp,
HistoryBrush,
Blur,
Sharpen,
@@ -115,7 +116,7 @@ pub enum Tool {
}
impl Tool {
- pub const ALL: [Tool; 50] = [
+ pub const ALL: [Tool; 51] = [
Tool::Move,
Tool::RectMarquee,
Tool::EllipseMarquee,
@@ -146,6 +147,7 @@ impl Tool {
Tool::ContentAwareMove,
Tool::RedEye,
Tool::CloneStamp,
+ Tool::PatternStamp,
Tool::HistoryBrush,
Tool::Blur,
Tool::Sharpen,
@@ -202,6 +204,7 @@ impl Tool {
Tool::ContentAwareMove => "Content-Aware Move Tool",
Tool::RedEye => "Red Eye Tool",
Tool::CloneStamp => "Clone Stamp Tool",
+ Tool::PatternStamp => "Pattern Stamp Tool",
Tool::HistoryBrush => "History Brush Tool",
Tool::Blur => "Blur Tool",
Tool::Sharpen => "Sharpen Tool",
@@ -238,6 +241,7 @@ impl Tool {
| Tool::SpotHealing
| Tool::Healing
| Tool::CloneStamp
+ | Tool::PatternStamp
| Tool::HistoryBrush
| Tool::Blur
| Tool::Sharpen
@@ -263,7 +267,7 @@ impl Tool {
Tool::Hand => 'H',
Tool::Zoom => 'Z',
Tool::SpotHealing | Tool::Healing | Tool::Patch | Tool::ContentAwareMove | Tool::RedEye => 'J',
- Tool::CloneStamp => 'S',
+ Tool::CloneStamp | Tool::PatternStamp => 'S',
Tool::HistoryBrush => 'Y',
Tool::Blur | Tool::Sharpen | Tool::Smudge => '\0',
Tool::Dodge | Tool::Burn | Tool::Sponge => 'O',
@@ -423,6 +427,14 @@ pub struct ToolOptions {
pub type_align: String,
/// Clone Stamp / Healing Brush.
pub clone_aligned: bool,
+ /// Pattern Stamp: lock the tile origin in document space across strokes.
+ pub pattern_stamp_aligned: bool,
+ /// Pattern Stamp: jitter each dab's phase (seeded, replayable).
+ pub pattern_stamp_impressionist: bool,
+ /// Pattern Stamp scale %, 1..1000 (100 = the tile's native size).
+ pub pattern_stamp_scale: f32,
+ /// Pattern Stamp rotation in degrees (counter-clockwise).
+ pub pattern_stamp_angle: f32,
/// current | currentAndBelow | all
pub clone_sample: String,
/// Spot Healing: contentAware | createTexture | proximityMatch
@@ -545,6 +557,10 @@ impl Default for ToolOptions {
type_aa: "sharp".into(),
type_align: "left".into(),
clone_aligned: true,
+ pattern_stamp_aligned: true,
+ pattern_stamp_impressionist: false,
+ pattern_stamp_scale: 100.0,
+ pattern_stamp_angle: 0.0,
clone_sample: "current".into(),
spot_type: "contentAware".into(),
patch_mode: "source".into(),
@@ -753,6 +769,9 @@ pub struct UiState {
pub clone_source: Option<[f64; 2]>,
#[serde(default)]
pub clone_offset: Option<[f64; 2]>,
+ /// Pattern Stamp aligned origin in document pixels, kept across strokes.
+ #[serde(default)]
+ pub pattern_stamp_phase: Option<[f32; 2]>,
/// Painting targets the active layer's mask instead of its pixels.
#[serde(default)]
pub mask_target: bool,
@@ -904,6 +923,7 @@ impl Default for UiState {
tool_smoothing: Vec::new(),
clone_source: None,
clone_offset: None,
+ pattern_stamp_phase: None,
extras: Extras::default(),
view: Default::default(),
actions: Default::default(),
@@ -994,7 +1014,9 @@ mod tests {
assert_eq!(Tool::from_name("Red Eye Tool"), Some(Tool::RedEye));
assert_eq!(Tool::RedEye.key(), 'J');
assert!(!Tool::RedEye.is_brushlike());
- assert_eq!(Tool::ALL.len(), 50);
+ assert_eq!(Tool::from_name("patternStamp"), Some(Tool::PatternStamp));
+ assert_eq!(Tool::from_name("Pattern Stamp Tool"), Some(Tool::PatternStamp));
+ assert_eq!(Tool::ALL.len(), 51);
assert_eq!(Tool::from_name("nope"), None);
}
diff --git a/docs/roadmap.md b/docs/roadmap.md
index 8da587f0f..8611cf22e 100644
--- a/docs/roadmap.md
+++ b/docs/roadmap.md
@@ -70,7 +70,7 @@ Confidence: moderate — the next users of 0.2.x will move these numbers either
| Smart filters / text / effect shapes in PSDs | Measured on our Photoshop-authored set (https://github.com/storytold/photocraft-corpus, `corpus/photoshop`, 258 files): see the per-group floors in `crates/io/tests/corpus.rs` and `crates/engine/tests/photoshop_oracles.rs`. Smart objects and smart filters now survive PSD save and open (41 corpus files, 206 smart objects, round trip strict; Photoshop opens our exports with live filters); re-rendering Photoshop's smart filters with ours matches 5/30 (was 1/30) | low–medium | Remaining re-render gaps are filter maths (Gaussian/Motion Blur, Unsharp Mask, Emboss, Add Noise RNG) and bicubic placement. |
| Core editing (layers, masks, selections, adjustments, filters, transforms) | Broad engine coverage; many interaction bugs fixed after 0.2.0 (adjustment dialogs, Curves, crop, Move/Transform modifiers, gesture origin) | medium | Fixes not yet user-validated. |
| UI / UX polish | Shortcut audit 214 → 0 failures; dock, Layers rows and menus reworked; first visual-QA sweep found 14 defects (#147–#157). 2026-10-07: the keyboard-only shortcuts with no menu item (⌥[ ⌥] ⌥, ⌥. layer navigation, ⇧⌥[ ⇧⌥] to extend the selection, 1–0 for opacity and ⇧ for flow or fill, ⇧[ ⇧] hardness, ⌥⌘T to transform a copy and ⌥⇧⌘T to step and repeat), ⌥-click colour sampling with painting tools, double-click a Layers row for Layer Style, File › New from Clipboard, a centred main window and remembered Liquify settings (#352, #417, #350, #368, #419, #418) | low–medium | Needs recurring visual QA with realistic documents. |
-| Tools | 2026-10-08: Pencil, Mixer Brush, Patch, Content-Aware Move and Vertical Type are toolbar tools. Remaining missing tools include Red Eye, Pattern Stamp, Art History Brush, Freeform/Curvature Pen, Add/Delete Anchor Point tools, single row/column marquee, Color Sampler, Perspective Crop, Rotate View, type masks and Frame | low–medium | Patch has a live healing preview. Content-Aware Move is partial: Move/Extend, Structure/Color and Sample All Layers exist; Transform On Drop and a live result preview remain missing (`TOOL-213-4` in the scorecard). Magic/Background Eraser added; live gradients in progress (#180). Magnetic Lasso added 2026-10-08 (live-wire edge tracing, Width/Contrast/Frequency, `select.magneticLasso`). |
+| Tools | 2026-10-08: Pencil, Mixer Brush, Patch, Content-Aware Move and Vertical Type are toolbar tools. Remaining missing tools include Red Eye, Art History Brush, Freeform/Curvature Pen, Add/Delete Anchor Point tools, single row/column marquee, Color Sampler, Perspective Crop, Rotate View, type masks and Frame | low–medium | Patch has a live healing preview. Content-Aware Move is partial: Move/Extend, Structure/Color and Sample All Layers exist; Transform On Drop and a live result preview remain missing (`TOOL-213-4` in the scorecard). Magic/Background Eraser added; live gradients in progress (#180). Magnetic Lasso added 2026-10-08 (live-wire edge tracing, Width/Contrast/Frequency, `select.magneticLasso`). Pattern Stamp added 2026-10-08 (S flyout, `paint.patternStamp`, Aligned / Impressionist). |
| Painting | Brush model and Brush Settings panel near Photoshop; .abr/.grd import; persistent presets; pen pressure/tilt on Windows, web, macOS and X11 | medium | Native Wayland pen input open (#79; a pen opens the window through Xwayland meanwhile); X11 pressure confirmed by a user, macOS not yet verified on tablet hardware. |
| Text / typography | Engine works; caret placement and size editing fixed; OpenType features, text-on-path editing, composer parity partial | medium-low | Measure with the Photoshop-authored set. |
| Colour management | Colour-managed canvas (document → monitor), embedded CMYK profiles, linear EXR/HDR, 16-bit float canvas | medium-high | Monitor profile follows only at launch. |
diff --git a/scorecard/tools.toml b/scorecard/tools.toml
index 4ade01644..2c5f53419 100644
--- a/scorecard/tools.toml
+++ b/scorecard/tools.toml
@@ -103,6 +103,13 @@ status = "partial"
issue = 213
note = "Brush tools set CursorIcon::None (canvas.rs:1259-1275); not verified per OS"
+[[item]]
+id = "TOOL-213-18"
+target = "Pattern Stamp tool: sibling of Clone Stamp in the S flyout"
+status = "done"
+issue = 213
+note = "Tool::PatternStamp in the S group; paint.patternStamp stamps the Patterns-panel tile with Aligned and Impressionist (an approximation: it jitters each dab's tile phase, not Photoshop's smeared impressionist look); engine tests cover depths, seams, hostile input"
+
[[item]]
id = "TOOL-214-1"
target = "Select and Mask workspace: view modes, Refine Edge brush, 6 outputs"