From 91e18fa45a5d70f7760ffe9287448e3071b50682 Mon Sep 17 00:00:00 2001 From: VoiceLessQ Date: Sun, 25 Oct 2026 02:19:26 -0200 Subject: [PATCH 1/6] paint: 13 more painting tools wrap across the canvas edges in Pattern Preview Clone Stamp already wraps in Pattern Preview (#4997). Blur, Sharpen, Smudge, Dodge, Burn, Sponge, Mixer Brush, Color Replacement, Background Eraser, Pattern Stamp, History Brush, Healing Brush and Spot Healing now take "wrap": true as well, and the canvas sends it while Pattern Preview is on (#8883). The sequential-dab tools run their dabs on WorkTiles, moved into photocraft_paint::retouch and given a wrap tile: each canvas pixel is kept once and read and written wherever it repeats, so a live stroke and its commit still give the same pixels. The composite tools go through #4997's periodic::Composite via one periodic::stroke helper. Spot Healing centres its sampling window on the stroke, at most one canvas across. With wrap off, every command takes the path it took before. --- crates/engine/src/brush_cmds.rs | 20 +- crates/engine/src/eraser_cmds.rs | 12 +- crates/engine/src/retouch_cmds.rs | 364 ++++++++++-------- .../engine/src/retouch_cmds/pattern_stamp.rs | 14 +- crates/engine/src/retouch_cmds/periodic.rs | 25 ++ crates/engine/src/retouch_cmds/tests.rs | 289 ++++++++++++++ crates/paint/src/bg_erase.rs | 19 +- crates/paint/src/lib.rs | 4 +- crates/paint/src/mixer.rs | 31 +- crates/paint/src/replace.rs | 42 +- crates/paint/src/retouch.rs | 264 +++++++++++++ crates/paint/src/wrap.rs | 166 ++++++++ crates/ui-egui/src/canvas.rs | 8 + crates/ui-egui/src/eraser_ui.rs | 6 +- crates/ui-egui/src/retouch_ui.rs | 56 ++- crates/ui-egui/src/stroke_timing_tests.rs | 54 +++ 16 files changed, 1179 insertions(+), 195 deletions(-) create mode 100644 crates/paint/src/wrap.rs diff --git a/crates/engine/src/brush_cmds.rs b/crates/engine/src/brush_cmds.rs index feb238cf40..bd82e4f808 100644 --- a/crates/engine/src/brush_cmds.rs +++ b/crates/engine/src/brush_cmds.rs @@ -9,7 +9,7 @@ use photocraft_doc::LayerContent; use photocraft_geom::Rect; use photocraft_paint::mixer::{MixerSettings, apply_mixer_stroke}; -use photocraft_paint::replace::{Limits, ReplaceMode, ReplaceSettings, Sampling, apply_color_replacement, color_replacement_effect}; +use photocraft_paint::replace::{Limits, ReplaceMode, ReplaceSettings, Sampling, apply_color_replacement_wrapped, color_replacement_effect}; use photocraft_paint::tile::PREVIEW_SIDE; use photocraft_paint::{ BrushPreset, BrushSettings, GrayTile, Pattern, PresetCaptures, StoredTile, Stroke, StrokePoint, StrokeRenderer, TipShape, render_stroke, @@ -667,10 +667,13 @@ fn mixer_brush(s: &mut Session, p: &Value) -> Result { let stroke = Stroke { brush, points: pts }; let dmg = s.edit("Mixer Brush", |doc, _| { let sel = doc.selection.clone(); + // View › Pattern Preview: the stroke paints and picks up where it lies on the canvas. + let wrap = flag(p, "wrap", false).then(|| doc.bounds()).filter(|t| !t.is_empty()); let sample = if sample_all { let ds = photocraft_paint::dabs(&stroke); let ctx = photocraft_paint::BrushContext::new(&stroke.brush); let area = ds.iter().fold(Rect::EMPTY, |r, d| r.union(&ctx.dab_rect(d, false))); + let area = wrap.map_or(area, |t| photocraft_paint::wrap::fold_area(area, t)); let buf = photocraft_compose::render(doc, area); let mut surf = Surface::new(photocraft_color::PixelFormat::RGBA32F); let flat: Vec = buf.px.iter().flatten().copied().collect(); @@ -682,7 +685,7 @@ fn mixer_brush(s: &mut Session, p: &Value) -> Result { None }; let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?; - Ok(apply_mixer_stroke(surf, sample.as_ref(), &stroke, &m, &mut state, sel.as_ref(), lock)) + Ok(apply_mixer_stroke(surf, sample.as_ref(), &stroke, &m, &mut state, sel.as_ref(), lock, wrap)) })?; state.end_stroke(paint, m.clean_after_stroke, m.load_after_stroke); s.tools.mixer = state; @@ -752,8 +755,9 @@ fn color_replacement(s: &mut Session, p: &Value) -> Result { let dmg = s.edit("Color Replacement", |doc, _| { let sel = doc.selection.clone(); let lock = doc.effective_locks(id).transparency; + let wrap = flag(p, "wrap", false).then(|| doc.bounds()); let surf = paint_surface(doc, id, &json!({}))?; - Ok(apply_color_replacement(surf, &stroke, &rs, sel.as_ref(), lock)) + Ok(apply_color_replacement_wrapped(surf, &stroke, &rs, sel.as_ref(), lock, wrap)) })?; Ok(damage_json(s, dmg)) } @@ -762,8 +766,10 @@ fn color_replacement(s: &mut Session, p: &Value) -> Result { /// recolouring per dab as the commit, so the preview at the last point is the committed result. pub fn live_color_replacement(s: &Session, p: &Value) -> Result { let (stroke, rs, id) = color_replacement_setup(s, p)?; - crate::retouch_cmds::LiveDab::with_effect(s, "paint.colorReplacement", &json!({}), stroke, Some(id), 0, |pre| { - Box::new(color_replacement_effect(pre.clone(), rs)) + // Layer pixels, as the commit paints, wrapped as it is. + let params = json!({"wrap": flag(p, "wrap", false)}); + crate::retouch_cmds::LiveDab::with_effect(s, "paint.colorReplacement", ¶ms, stroke, Some(id), 0, |pre, wrap| { + Box::new(color_replacement_effect(pre.clone(), rs, wrap)) })? .with_tail_preview() } @@ -1203,7 +1209,7 @@ pub fn specs() -> Vec { spec!( "paint.mixerBrush", "Mixer Brush", - r##"{"points":[…],"brush":{…}?,"preset":name?,"size":0.5..5000 px?,"wet":0..100=brush.mixer.wet,"load":0..100=brush.mixer.load,"mix":0..100=brush.mixer.mix,"flow":0..100=brush.mixer.flow,"color":"#rrggbb"?=foreground (a color other than the one recorded by the last stroke, load or clean loads it first; a load or clean records the foreground),"sampleAllLayers":bool=brush.mixer.sampleAllLayers,"cleanAfterStroke":bool=brush.mixer.cleanAfterStroke (empty the brush after the stroke),"loadAfterStroke":bool=brush.mixer.loadAfterStroke (load the brush with `color` after the stroke),"seed":u64?}"##, + r##"{"points":[…],"brush":{…}?,"preset":name?,"size":0.5..5000 px?,"wet":0..100=brush.mixer.wet,"load":0..100=brush.mixer.load,"mix":0..100=brush.mixer.mix,"flow":0..100=brush.mixer.flow,"color":"#rrggbb"?=foreground (a color other than the one recorded by the last stroke, load or clean loads it first; a load or clean records the foreground),"sampleAllLayers":bool=brush.mixer.sampleAllLayers,"cleanAfterStroke":bool=brush.mixer.cleanAfterStroke (empty the brush after the stroke),"loadAfterStroke":bool=brush.mixer.loadAfterStroke (load the brush with `color` after the stroke),"seed":u64?,"wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges)}"##, has_paintable, mixer_brush, true @@ -1213,7 +1219,7 @@ pub fn specs() -> Vec { spec!( "paint.colorReplacement", "Color Replacement", - r##"{"points":[…],"brush":{…}?,"size":px?,"mode":"hue|saturation|color|luminosity"="color","sampling":"continuous|once|backgroundSwatch"="continuous","limits":"contiguous|discontiguous|findEdges"="contiguous","tolerance":0..100=30,"antiAlias":bool=true,"color":"#rrggbb"?=foreground,"target":"pixels"="pixels","seed":u64?}"##, + r##"{"points":[…],"brush":{…}?,"size":px?,"mode":"hue|saturation|color|luminosity"="color","sampling":"continuous|once|backgroundSwatch"="continuous","limits":"contiguous|discontiguous|findEdges"="contiguous","tolerance":0..100=30,"antiAlias":bool=true,"color":"#rrggbb"?=foreground,"target":"pixels"="pixels","seed":u64?,"wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges)}"##, crate::commands::has_paintable, color_replacement, true diff --git a/crates/engine/src/eraser_cmds.rs b/crates/engine/src/eraser_cmds.rs index 129753ea86..653cd79993 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, background_eraser_effect, background_eraser_stroke}; +use photocraft_paint::bg_erase::{BgEraseSettings, apply_background_eraser_wrapped, background_eraser_effect, background_eraser_stroke}; use photocraft_paint::replace::{Limits, Sampling}; use serde_json::{Value, json}; @@ -152,10 +152,12 @@ fn background_eraser(s: &mut Session, p: &Value) -> Result { let (stroke, bs, id) = background_eraser_setup(s, p)?; let dmg = s.edit("Background Eraser", |doc, _| { let selection = doc.selection.clone(); + // View › Pattern Preview: the stroke carries on across the canvas edges. + let wrap = flag(p, "wrap", false).then(|| doc.bounds()); crate::extra_cmds::background_to_layer(doc, id); let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; let surf = l.surface_mut().ok_or_else(|| bad(CMD, "not a pixel layer"))?; - Ok(apply_background_eraser(surf, &stroke, &bs, selection.as_ref())) + Ok(apply_background_eraser_wrapped(surf, &stroke, &bs, selection.as_ref(), wrap)) })?; Ok(damage(s, dmg, true)) } @@ -170,7 +172,9 @@ pub fn live_background_eraser(s: &Session, p: &Value) -> Result Box::new(effect), // No alpha: the commit erases nothing either. None => Box::new(|_: &mut photocraft_paint::retouch::Region, _: &photocraft_paint::retouch::Footprint| {}), @@ -196,7 +200,7 @@ pub fn specs() -> Vec { label: "Background Eraser", menu: &[], shortcut: None, - params: r##"{"points":[[x,y,pressure?],…],"size":px?,"hardness":0..1?,"brush":{…}?,"preset":name?,"sampling":"continuous|once|backgroundSwatch"="continuous","limits":"discontiguous|contiguous|findEdges"="contiguous","tolerance":0..100=50,"protectForegroundColor":bool=false,"seed":u64?}"##, + params: r##"{"points":[[x,y,pressure?],…],"size":px?,"hardness":0..1?,"brush":{…}?,"preset":name?,"sampling":"continuous|once|backgroundSwatch"="continuous","limits":"discontiguous|contiguous|findEdges"="contiguous","tolerance":0..100=50,"protectForegroundColor":bool=false,"seed":u64?,"wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges)}"##, enabled: has_pixel_layer, run: background_eraser, journal: true, diff --git a/crates/engine/src/retouch_cmds.rs b/crates/engine/src/retouch_cmds.rs index eae429f8c0..4480f9b8b8 100644 --- a/crates/engine/src/retouch_cmds.rs +++ b/crates/engine/src/retouch_cmds.rs @@ -15,7 +15,8 @@ use photocraft_algo::retouch::{ToneRange, dodge_burn, local_blur, local_sharpen, use photocraft_color::{BlendMode, PixelFormat, SampleType}; use photocraft_doc::{Document, LayerContent, LayerId}; use photocraft_geom::Rect; -use photocraft_paint::retouch::{Footprint, Region, Smudge, alpha_index, apply_coverage, apply_dab_stroke}; +use photocraft_paint::retouch::{Footprint, Region, Smudge, WorkTiles, alpha_index, apply_coverage, apply_dab_stroke_wrapped}; +use photocraft_paint::wrap::wrap_coord; use photocraft_paint::{BrushSettings, Stroke, StrokePoint}; use photocraft_raster::{Surface, from_rgba_into, to_rgba}; use rayon::prelude::*; @@ -120,6 +121,10 @@ fn num(p: &Value, k: &str, d: f32) -> f32 { fn flag(p: &Value, k: &str, d: bool) -> bool { p.get(k).and_then(Value::as_bool).unwrap_or(d) } +/// The canvas a stroke with `"wrap": true` repeats across (View › Pattern Preview). +fn wrap_tile(pre: &Document, p: &Value) -> Option { + flag(p, "wrap", false).then(|| pre.bounds()).filter(|t| !t.is_empty()) +} fn string<'a>(p: &'a Value, k: &str, d: &'a str) -> &'a str { p.get(k).and_then(Value::as_str).unwrap_or(d) } @@ -382,26 +387,19 @@ fn clone_stamp(s: &mut Session, p: &Value) -> Result { let from_live = live.is_some(); let map = clone_mapping(s, p, &stroke, CMD)?; let off = map.offset(); - let dmg = - run_stroke(s, "Clone Stamp", id, p, |pre, surf, sel, lock| { - if let Some(l) = live { - *surf = l.surface; - return Ok(l.bounds); - } - if flag(p, "wrap", false) { - let mut renderer = photocraft_paint::StrokeRenderer::new(&stroke.brush, None, 1.0); - renderer.push(&stroke.points); - renderer.finish(); - let before = surf.clone(); - let bounds = renderer.bounds(); - return periodic::Composite { target: surf, before: &before, tile: pre.bounds(), opacity: stroke.brush.opacity, selection: sel, lock, mode } - .draw(bounds, &stroke.brush, &stroke.points, |r| clone_sample(pre, id, &before, which, r, &map, true, CMD)); - } - let (bounds, cov) = coverage(CMD, &stroke)?; - // Samples come from the pre-stroke state, so pixels painted earlier in the stroke are never re-cloned. - let paint = clone_sample(pre, id, surf, which, bounds, &map, flag(p, "wrap", false), CMD)?; - Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode)) - })?; + let dmg = run_stroke(s, "Clone Stamp", id, p, |pre, surf, sel, lock| { + if let Some(l) = live { + *surf = l.surface; + return Ok(l.bounds); + } + if flag(p, "wrap", false) { + return periodic::stroke(pre, surf, &stroke, sel, lock, mode, |before, r| clone_sample(pre, id, before, which, r, &map, true, CMD)); + } + let (bounds, cov) = coverage(CMD, &stroke)?; + // Samples come from the pre-stroke state, so pixels painted earlier in the stroke are never re-cloned. + let paint = clone_sample(pre, id, surf, which, bounds, &map, flag(p, "wrap", false), CMD)?; + Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode)) + })?; let mut r = clone_result(dmg, off, aligned, p, &stroke); if from_live { r["fromLive"] = json!(true); @@ -520,11 +518,7 @@ impl LiveRetouch { /// Everything the stroke has touched so far. pub fn bounds(&self) -> Rect { let bounds = self.renderer.bounds().union(&self.tail); - if self.cmd == "paint.cloneStamp" && flag(&self.params, "wrap", false) { - periodic::project(bounds, self.pre.bounds()).into_iter().fold(Rect::EMPTY, |a, b| a.union(&b)) - } else { - bounds - } + if flag(&self.params, "wrap", false) { periodic::project(bounds, self.pre.bounds()).into_iter().fold(Rect::EMPTY, |a, b| a.union(&b)) } else { bounds } } /// Every point rendered so far, in order. @@ -567,7 +561,7 @@ impl LiveRetouch { let pts: Vec<_> = pts.iter().map(|q| StrokePoint::new(q.x, q.y, q.pressure)).collect(); self.points.extend_from_slice(&pts); self.renderer.push(&pts); - if self.cmd == "paint.cloneStamp" && flag(&self.params, "wrap", false) { + if flag(&self.params, "wrap", false) { return self.push_periodic(); } let old = std::mem::replace(&mut self.tail, Rect::EMPTY); @@ -596,8 +590,12 @@ impl LiveRetouch { let mut tail = self.renderer.tail_preview(); self.tail = tail.as_mut().map_or(Rect::EMPTY, |t| t.take_dirty_rect()); dirty = dirty.union(&self.tail); - let LivePaint::Clone { which, map, cmd } = &self.paint else { - return Err(bad(&self.cmd, "periodic painting requires a clone source")); + let (pre, id, pre_surf, live_paint, live_cmd) = (&self.pre, self.id, &self.pre_surf, &self.paint, self.cmd.as_str()); + let fmt = pre_surf.format(); + let paint = |r| match live_paint { + LivePaint::Clone { which, map, cmd } => clone_sample(pre, id, pre_surf, *which, r, map, true, cmd), + LivePaint::History(src) => periodic::sample(pre, id, src, SampleLayers::Current, r, live_cmd), + LivePaint::Pattern { tile, place } => Ok(pattern_stamp::paint_region(tile, place, &fmt, r)), }; let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?; periodic::Composite { @@ -609,7 +607,7 @@ impl LiveRetouch { lock: self.lock, mode: self.mode, } - .draw(dirty, &self.brush, &self.points, |r| clone_sample(&self.pre, self.id, &self.pre_surf, *which, r, map, true, cmd)) + .draw(dirty, &self.brush, &self.points, paint) } /// Redraw `r` from the pre-stroke pixels with the clone source through coverage `cov`. @@ -678,15 +676,30 @@ fn healing_brush(s: &mut Session, p: &Value) -> Result { let map = clone_mapping(s, p, &stroke, CMD)?; let off = map.offset(); let dmg = run_stroke(s, "Healing Brush", id, p, |pre, surf, sel, lock| { + // Pattern Preview: source and destination repeat across the canvas edges, so a stroke over + // a seam heals as one patch and goes on wherever it repeats. + let wrap = flag(p, "wrap", false); let (bounds, cov) = coverage(CMD, &stroke)?; let (g, cov) = pad_coverage(bounds, &cov, 2); let fmt = surf.format(); - let src = clone_sample(pre, id, surf, which, g, &map, false, CMD)?; + let src = clone_sample(pre, id, surf, which, g, &map, wrap, CMD)?; // The destination the texture is fitted to: the layer itself, or what the user sees when // sampling several layers (so healing onto an empty layer matches the composite). - let dst = if which == SampleLayers::Current { Region::read(surf, g) } else { composite_region(pre, id, which, g, fmt) }; + let dst = if wrap { + periodic::sample(pre, id, surf, which, g, CMD)? + } else if which == SampleLayers::Current { + Region::read(surf, g) + } else { + composite_region(pre, id, which, g, fmt) + }; let mask: Vec = cov.iter().map(|c| *c > 0.0).collect(); let healed = heal_region(&fmt, &src, &dst, &mask); + if wrap { + return periodic::stroke(pre, surf, &stroke, sel, lock, mode, |_, r| { + let part = healed.crop(r); + if part.rect == r { Ok(part) } else { Err(bad(CMD, "the healed patch does not cover the stroke")) } + }); + } Ok(apply_coverage(surf, g, &cov, stroke.brush.opacity, sel, lock, &healed, mode)) })?; Ok(clone_result(dmg, off, aligned, p, &stroke)) @@ -714,13 +727,17 @@ fn history_brush(s: &mut Session, p: &Value) -> Result { let live = s.live_commit.take().filter(|l| l.matches(s, CMD, p, &stroke.points)); let from_live = live.is_some(); let src_surface = history_source(s, id, p, CMD)?; - let dmg = run_stroke(s, "History Brush", id, p, |_, surf, sel, lock| { + let dmg = run_stroke(s, "History Brush", id, p, |pre, surf, sel, lock| { if let Some(l) = live { *surf = l.surface; return Ok(l.bounds); } let fmt = surf.format(); let src = if src_surface.format() == fmt { src_surface } else { src_surface.convert(fmt) }; + if flag(p, "wrap", false) { + // Pattern Preview: the history state repeats with the canvas, as the stroke does. + return periodic::stroke(pre, surf, &stroke, sel, lock, mode, |_, r| periodic::sample(pre, id, &src, SampleLayers::Current, r, CMD)); + } let (bounds, cov) = coverage(CMD, &stroke)?; let paint = Region::read(&src, bounds); Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode)) @@ -798,24 +815,63 @@ enum SpotType { /// Photoshop 25.4 (measured): a dab changes exactly the brush's footprint, and Content-Aware takes /// its texture from around it, as Edit › Fill does from its window /// ([`crate::fill_cmds::sampling_window`] of the stroke's bounds), which is what this samples. -fn spot_heal_surface(surf: &mut Surface, pre: &Document, stroke: &Stroke, kind: SpotType, all: bool, sel: Option<&Surface>, lock: bool) -> Result { - let (bounds, cov) = coverage("paint.spotHealing", stroke)?; +/// +/// Wrapped around the canvas `wrap` (View › Pattern Preview), the window is centred on the stroke +/// whatever the canvas edges and at most one canvas across, so it holds no second copy of the +/// stroke; its pixels repeat across the edges, and the healed pixels go where they lie on the +/// canvas. +#[allow(clippy::too_many_arguments)] +fn spot_heal_surface( + surf: &mut Surface, + pre: &Document, + stroke: &Stroke, + kind: SpotType, + all: bool, + sel: Option<&Surface>, + lock: bool, + wrap: Option, +) -> Result { + const CMD: &str = "paint.spotHealing"; + let (bounds, cov) = coverage(CMD, stroke)?; let size = stroke.brush.size; - let region_rect = crate::fill_cmds::sampling_window(bounds, pre.bounds()); + let region_rect = match wrap { + Some(tile) => { + let (tw, th) = (i64::from(tile.width()), i64::from(tile.height())); + let x0 = (i64::from(bounds.x0) + i64::from(bounds.x1) - tw) / 2; + let y0 = (i64::from(bounds.y0) + i64::from(bounds.y1) - th) / 2; + let around = Rect::new(x0 as i32, y0 as i32, (x0 + tw) as i32, (y0 + th) as i32); + crate::fill_cmds::sampling_window(bounds, around) + } + None => crate::fill_cmds::sampling_window(bounds, pre.bounds()), + }; if region_rect.is_empty() { return Ok(Rect::EMPTY); } // Proximity Match looks for its source anywhere in that window. let margin = (region_rect.width().max(region_rect.height()) / 2) as i32; let fmt = surf.format(); - let img = if all { composite_region(pre, None, SampleLayers::All, region_rect, fmt) } else { Region::read(surf, region_rect) }; + let img = match wrap { + Some(_) => periodic::sample(pre, None, surf, if all { SampleLayers::All } else { SampleLayers::Current }, region_rect, CMD)?, + None if all => composite_region(pre, None, SampleLayers::All, region_rect, fmt), + None => Region::read(surf, region_rect), + }; let (w, h, ch) = (img.width(), img.height(), img.ch); let bw = bounds.width() as usize; let mut stroke_cov = vec![0.0f32; w * h]; for (i, c) in cov.iter().enumerate() { let (x, y) = (bounds.x0 + (i % bw) as i32, bounds.y0 + (i / bw) as i32); + // A wrapped stroke longer than the window (one canvas) folds onto it: the strongest + // coverage of each pixel heals it once. + let (x, y) = match wrap { + Some(t) => { + let wrap_into = |v: i32, lo: i32, period: u32| wrap_coord(v, lo, lo.saturating_add(period as i32)); + (wrap_into(x, region_rect.x0, t.width()), wrap_into(y, region_rect.y0, t.height())) + } + None => (x, y), + }; if region_rect.contains(x, y) { - stroke_cov[img.index(x, y)] = *c; + let px = &mut stroke_cov[img.index(x, y)]; + *px = px.max(*c); } } let hole: Vec = stroke_cov.iter().map(|c| *c > 0.0).collect(); @@ -843,8 +899,19 @@ fn spot_heal_surface(surf: &mut Surface, pre: &Document, stroke: &Stroke, kind: let src = Region { rect: region_rect, ch, data: filled }; let healed = heal_region(&fmt, &src, &img, &heal_mask); let dmg = bounds.intersect(®ion_rect); - let dmg_cov: Vec = (dmg.y0..dmg.y1).flat_map(|y| (dmg.x0..dmg.x1).map(move |x| (x, y))).map(|(x, y)| stroke_cov[img.index(x, y)]).collect(); - Ok(apply_coverage(surf, dmg, &dmg_cov, stroke.brush.opacity, sel, lock, &healed, BlendMode::Normal)) + let cov_of = |r: Rect, (dx, dy): (i32, i32)| -> Vec { + (r.y0..r.y1).flat_map(|y| (r.x0..r.x1).map(move |x| (x, y))).map(|(x, y)| stroke_cov[img.index(x + dx, y + dy)]).collect() + }; + let Some(tile) = wrap else { + return Ok(apply_coverage(surf, dmg, &cov_of(dmg, (0, 0)), stroke.brush.opacity, sel, lock, &healed, BlendMode::Normal)); + }; + let mut done = Rect::EMPTY; + for (part, off) in photocraft_paint::wrap::pieces(dmg, tile) { + let mut paint = healed.crop(part.translate(off.0, off.1)); + paint.rect = part; + done = done.union(&apply_coverage(surf, part, &cov_of(part, off), stroke.brush.opacity, sel, lock, &paint, BlendMode::Normal)); + } + Ok(done) } fn spot_healing(s: &mut Session, p: &Value) -> Result { @@ -858,7 +925,8 @@ fn spot_healing(s: &mut Session, p: &Value) -> Result { o => return Err(bad(CMD, format!("unknown type `{o}` (contentAware|createTexture|proximityMatch)"))), }; let all = sample_all_layers(p); - let dmg = run_stroke(s, "Spot Healing Brush", id, p, |pre, surf, sel, lock| spot_heal_surface(surf, pre, &stroke, kind, all, sel, lock))?; + let dmg = + run_stroke(s, "Spot Healing Brush", id, p, |pre, surf, sel, lock| spot_heal_surface(surf, pre, &stroke, kind, all, sel, lock, wrap_tile(pre, p)))?; Ok(json!({ "damage": damage_json(dmg) })) } @@ -1139,8 +1207,9 @@ fn dab_cmd(s: &mut Session, p: &Value, cmd: &str) -> Result { } let fmt = surf.format(); let mut effect = tool.effect(fmt, stroke.brush.spacing); - let mut sampler = all.then(|| AllLayers::new(pre, fmt)); - Ok(apply_dab_stroke(surf, &stroke, sel, lock, tool.neighborhood().halo(), |work, fp| match &mut sampler { + let (halo, wrap) = (tool.neighborhood().halo(), wrap_tile(pre, p)); + let mut sampler = all.then(|| AllLayers::new(pre, fmt).wrapped(wrap, &stroke, halo)); + Ok(apply_dab_stroke_wrapped(surf, &stroke, sel, lock, halo, wrap, |work, fp| match &mut sampler { Some(all) => all.dab(work, fp, |w, f| effect(w, f)), None => effect(work, fp), })) @@ -1152,81 +1221,6 @@ fn dab_cmd(s: &mut Session, p: &Value, cmd: &str) -> Result { Ok(r) } -/// Side of the tiles a live sequential-dab stroke keeps its working pixels in ([`WorkTiles`]). -const WORK_TILE: i32 = 128; - -/// The working copy of a live sequential-dab stroke: the target's native channels as `f32`, in -/// tiles copied from the pre-stroke surface the first time a dab writes to them. Unlike a -/// `Surface`, it isn't rounded to the document's depth between dabs, so each dab sees what the -/// commit's working copy (`apply_dab_stroke`) holds and the preview is the commit's pixels. -struct WorkTiles { - ch: usize, - tiles: std::collections::HashMap<(i32, i32), Vec>, -} - -impl WorkTiles { - fn new(ch: usize) -> Self { - Self { ch, tiles: std::collections::HashMap::new() } - } - - fn tile_rect((tx, ty): (i32, i32)) -> Rect { - Rect::new(tx * WORK_TILE, ty * WORK_TILE, tx * WORK_TILE + WORK_TILE, ty * WORK_TILE + WORK_TILE) - } - - /// The tiles `r` overlaps. - fn coords(r: Rect) -> impl Iterator { - let (x0, x1) = (r.x0.div_euclid(WORK_TILE), (r.x1 - 1).div_euclid(WORK_TILE)); - let (y0, y1) = (r.y0.div_euclid(WORK_TILE), (r.y1 - 1).div_euclid(WORK_TILE)); - let empty = r.is_empty(); - (y0..=y1).filter(move |_| !empty).flat_map(move |ty| (x0..=x1).map(move |tx| (tx, ty))) - } - - /// The working pixels of `r`: the pre-stroke pixels `pre` where no dab has written yet. - fn read(&self, pre: &Surface, r: Rect) -> Region { - let mut out = Region::new(r, self.ch); - let n = self.ch; - let mut buf = Vec::new(); - for c in Self::coords(r) { - let tr = Self::tile_rect(c); - let part = r.intersect(&tr); - let w = part.width() as usize * n; - let tile = self.tiles.get(&c); - if tile.is_none() { - pre.read_region_into(part, &mut buf); - } - for y in part.y0..part.y1 { - let src = match tile { - Some(t) => t.get(((y - tr.y0) * WORK_TILE + (part.x0 - tr.x0)) as usize * n..).and_then(|s| s.get(..w)), - None => buf.get((y - part.y0) as usize * w..).and_then(|s| s.get(..w)), - }; - let dst = out.index(part.x0, y) * n; - if let (Some(s), Some(d)) = (src, out.data.get_mut(dst..dst + w)) { - d.copy_from_slice(s); - } - } - } - out - } - - /// Store `region` as the working pixels of its rectangle. - fn write(&mut self, pre: &Surface, region: &Region) { - let (r, n) = (region.rect, self.ch); - for c in Self::coords(r) { - let tr = Self::tile_rect(c); - let tile = self.tiles.entry(c).or_insert_with(|| pre.read_region(tr)); - let part = r.intersect(&tr); - let w = part.width() as usize * n; - for y in part.y0..part.y1 { - let dst = ((y - tr.y0) * WORK_TILE + (part.x0 - tr.x0)) as usize * n; - let src = region.index(part.x0, y) * n; - if let (Some(s), Some(d)) = (region.data.get(src..src + w), tile.get_mut(dst..dst + w)) { - d.copy_from_slice(s); - } - } - } - } -} - /// 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. @@ -1249,6 +1243,8 @@ pub struct LiveDab { sel: Option, lock: bool, bounds: Rect, + /// The canvas a wrapped stroke repeats across (View › Pattern Preview, `"wrap": true`). + wrap: Option, /// Show the dabs finishing the stroke would add, so the preview at the last point is the /// commit. Only for effects that a repeated dab doesn't change (Color Replacement): the /// tail runs on a scratch copy at every push, so an effect that carries paint from dab to @@ -1278,13 +1274,14 @@ impl LiveDab { let (tool, _) = DabTool::parse(s, cmd, p, &stroke)?; let (neighborhood, spacing, brush) = (tool.neighborhood(), stroke.brush.spacing, Box::new(stroke.brush.clone())); let effect = tool.clone(); - let mut live = Self::with_neighborhood(s, cmd, p, stroke, id, neighborhood, |pre| effect.effect(pre.format(), spacing))?; + let mut live = Self::with_neighborhood(s, cmd, p, stroke, id, neighborhood, |pre, _| effect.effect(pre.format(), spacing))?; live.tool = Some((tool, brush)); Ok(live) } - /// Start a live stroke of `cmd` that runs `effect` (made from the target before the stroke) - /// at each dab of `stroke`, reading `halo` pixels around it. `p` gives the target. + /// Start a live stroke of `cmd` that runs `effect` (made from the target before the stroke + /// and the canvas a wrapped stroke repeats across) at each dab of `stroke`, reading `halo` + /// pixels around it. `p` gives the target and `wrap`. pub(crate) fn with_effect( s: &Session, cmd: &str, @@ -1292,7 +1289,7 @@ impl LiveDab { stroke: Stroke, id: Option, halo: i32, - effect: impl FnOnce(&Surface) -> DabEffect, + effect: impl FnOnce(&Surface, Option) -> DabEffect, ) -> Result { Self::with_neighborhood(s, cmd, p, stroke, id, DabNeighborhood::Halo(halo), effect) } @@ -1304,7 +1301,7 @@ impl LiveDab { stroke: Stroke, id: Option, neighborhood: DabNeighborhood, - effect: impl FnOnce(&Surface) -> DabEffect, + effect: impl FnOnce(&Surface, Option) -> DabEffect, ) -> Result { let st = s.active().ok_or(EngineError::NoDocument)?; let base = (st.doc.id, st.revision); @@ -1323,7 +1320,7 @@ impl LiveDab { stroke: Stroke, id: Option, halo: i32, - effect: impl FnOnce(&Surface) -> DabEffect, + effect: impl FnOnce(&Surface, Option) -> DabEffect, ) -> Result { Self::with_neighborhood_on(doc, cmd, p, stroke, id, DabNeighborhood::Halo(halo), effect) } @@ -1335,12 +1332,13 @@ impl LiveDab { stroke: Stroke, id: Option, neighborhood: DabNeighborhood, - effect: impl FnOnce(&Surface) -> DabEffect, + effect: impl FnOnce(&Surface, Option) -> DabEffect, ) -> Result { + let wrap = wrap_tile(&doc, p); let sel = doc.selection.clone(); let (surf, lock) = crate::channel_cmds::target_surface(&mut doc, id, p)?; let pre_surf = surf.clone(); - let effect = effect(&pre_surf); + let effect = effect(&pre_surf, wrap); // `apply_dab_stroke` generates the same dabs (`dabs`: zoom 1, no smoothing scale). let renderer = photocraft_paint::StrokeRenderer::new(&stroke.brush, None, 1.0).record_dabs(); let mut live = Self { @@ -1350,7 +1348,7 @@ impl LiveDab { done: 0, effect, neighborhood, - work: WorkTiles::new(pre_surf.channels()), + work: WorkTiles::new(pre_surf.channels()).wrapped(wrap), pre_surf, id, params: p.clone(), @@ -1358,6 +1356,7 @@ impl LiveDab { sel, lock, bounds: Rect::EMPTY, + wrap, preview_tail: false, tail: Rect::EMPTY, tool: None, @@ -1391,15 +1390,34 @@ impl LiveDab { if r.is_empty() { continue; } + let fp = ctx.footprint(d, self.done + k); let mut region = self.work.read(&self.pre_surf, self.neighborhood.read_rect(r, d)); - (self.effect)(&mut region, &ctx.footprint(d, self.done + k)); - self.work.write(&self.pre_surf, ®ion.crop(r)); - dmg = dmg.union(&r); + (self.effect)(&mut region, &fp); + self.work.write_dab(&self.pre_surf, ®ion, &fp); + dmg = dmg.union(&self.on_canvas(r)); } self.done += new.len(); dmg } + /// Where the stroke's rectangle `r` lands on the document: `r`, or in a wrapped stroke the + /// part of the canvas it covers. + fn on_canvas(&self, r: Rect) -> Rect { + self.wrap.map_or(r, |t| photocraft_paint::wrap::fold_area(r, t)) + } + + /// [`Self::show`] working pixels laid out in the stroke's own coordinates: a wrapped stroke + /// shows each part where it lies on the canvas. + fn show_unwrapped(&mut self, work: &Region) -> Result<()> { + let Some(tile) = self.wrap else { return self.show(work.rect, work) }; + for (part, (dx, dy)) in photocraft_paint::wrap::pieces(work.rect, tile) { + let mut piece = work.crop(part.translate(dx, dy)); + piece.rect = part; + self.show(part, &piece)?; + } + Ok(()) + } + /// Mix the working pixels of `r` back over the original into the shown document. fn show(&mut self, r: Rect, work: &Region) -> Result<()> { let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?; @@ -1433,7 +1451,7 @@ impl LiveDab { // Back to the stroke without the previous tail. let old = std::mem::replace(&mut self.tail, Rect::EMPTY); let shown = dmg.union(&old); - let tail_rect = tail.as_ref().map_or(Rect::EMPTY, |(r, _)| *r); + let tail_rect = tail.as_ref().map_or(Rect::EMPTY, |(r, _)| self.on_canvas(*r)); if shown.is_empty() && tail_rect.is_empty() { return Ok(Rect::EMPTY); } @@ -1442,9 +1460,9 @@ impl LiveDab { let work = self.work.read(&self.pre_surf, shown); self.show(shown, &work)?; } - if let Some((r, work)) = tail { - self.show(r, &work)?; - self.tail = r; + if let Some((_, work)) = tail { + self.show_unwrapped(&work)?; + self.tail = tail_rect; } Ok(shown.union(&tail_rect)) } @@ -1490,26 +1508,56 @@ struct AllLayers<'a> { pre: &'a Document, fmt: PixelFormat, visible: Option, + /// A stroke wrapped around the canvas (View › Pattern Preview): the composite at full + /// precision under everything the stroke reads, and the dabs' edits of it, kept once per + /// pixel of the canvas as the layer's working pixels are. + wrapped: Option<(Surface, WorkTiles)>, } impl<'a> AllLayers<'a> { fn new(pre: &'a Document, fmt: PixelFormat) -> Self { - Self { pre, fmt, visible: None } + Self { pre, fmt, visible: None, wrapped: None } + } + + /// Sample for `stroke` wrapped around `wrap`, whose dabs read `halo` pixels around them. + fn wrapped(mut self, wrap: Option, stroke: &Stroke, halo: i32) -> Self { + let Some(tile) = wrap else { return self }; + let ctx = photocraft_paint::BrushContext::new(&stroke.brush); + let reach = photocraft_paint::dabs(stroke).iter().fold(Rect::EMPTY, |r, d| r.union(&ctx.dab_rect(d, false))).inflate(halo); + let area = photocraft_paint::wrap::fold_area(reach, tile); + let mut visible = Surface::new(PixelFormat { sample: SampleType::F32, ..self.fmt }); + if !area.is_empty() { + visible.write_region(area, &composite_region(self.pre, None, SampleLayers::All, area, self.fmt).data); + } + self.wrapped = Some((visible, WorkTiles::new(self.fmt.channels()).wrapped(Some(tile)))); + self } fn dab(&mut self, work: &mut Region, fp: &Footprint, effect: impl FnOnce(&mut Region, &Footprint)) { + if let Some((visible, edits)) = self.wrapped.as_mut() { + let mut shown = edits.read(visible, work.rect); + effect(&mut shown, fp); + lay(work, &shown, fp); + edits.write_dab(visible, &shown, fp); + return; + } let (pre, fmt) = (self.pre, self.fmt); let visible = self.visible.get_or_insert_with(|| composite_region(pre, None, SampleLayers::All, work.rect, fmt)); if visible.rect != work.rect || visible.ch != work.ch { return effect(work, fp); } effect(visible, fp); - let r = fp.rect.intersect(&work.rect); - for y in r.y0..r.y1 { - for x in r.x0..r.x1 { - if fp.at(x, y) > 0.0 { - work.px_mut(x, y).copy_from_slice(visible.px(x, y)); - } + lay(work, visible, fp); + } +} + +/// Lay what a dab did to the visible pixels onto the layer's working pixels under it. +fn lay(work: &mut Region, visible: &Region, fp: &Footprint) { + let r = fp.rect.intersect(&work.rect); + for y in r.y0..r.y1 { + for x in r.x0..r.x1 { + if fp.at(x, y) > 0.0 { + work.px_mut(x, y).copy_from_slice(visible.px(x, y)); } } } @@ -1547,7 +1595,7 @@ pub fn specs() -> Vec { 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"}"# + 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]?,"wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges) → {"damage","phase","aligned","pattern"}"# ), enabled: pattern_stamp::enabled, run: pattern_stamp::run, @@ -1559,7 +1607,7 @@ pub fn specs() -> Vec { menu: &[], shortcut: None, params: brush_params!( - r#","source":[sx,sy] | "offset":[dx,dy],"aligned":bool=true,"sampleLayer":"current|currentAndBelow|all"="current","mode":"normal|…"="normal" → {"damage","offset","aligned","nextSource"}"# + r#","source":[sx,sy] | "offset":[dx,dy],"aligned":bool=true,"sampleLayer":"current|currentAndBelow|all"="current","mode":"normal|…"="normal","wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges) → {"damage","offset","aligned","nextSource"}"# ), enabled: has_pixel_layer, run: healing_brush, @@ -1570,7 +1618,9 @@ pub fn specs() -> Vec { label: "Spot Healing Brush", menu: &[], shortcut: None, - params: brush_params!(r#","type":"contentAware|createTexture|proximityMatch"="contentAware","sampleAllLayers":bool=false"#), + params: brush_params!( + r#","type":"contentAware|createTexture|proximityMatch"="contentAware","sampleAllLayers":bool=false,"wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges)"# + ), enabled: has_pixel_layer, run: spot_healing, journal: true, @@ -1612,7 +1662,9 @@ pub fn specs() -> Vec { label: "Dodge", menu: &[], shortcut: None, - params: brush_params!(r#","range":"shadows|midtones|highlights"="midtones","exposure":1..100=50,"protectTones":bool=true"#), + params: brush_params!( + r#","range":"shadows|midtones|highlights"="midtones","exposure":1..100=50,"protectTones":bool=true,"wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges)"# + ), enabled: has_pixel_layer, run: |s, p| dab_cmd(s, p, "paint.dodge"), journal: true, @@ -1622,7 +1674,9 @@ pub fn specs() -> Vec { label: "Burn", menu: &[], shortcut: None, - params: brush_params!(r#","range":"shadows|midtones|highlights"="midtones","exposure":1..100=50,"protectTones":bool=true"#), + params: brush_params!( + r#","range":"shadows|midtones|highlights"="midtones","exposure":1..100=50,"protectTones":bool=true,"wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges)"# + ), enabled: has_pixel_layer, run: |s, p| dab_cmd(s, p, "paint.burn"), journal: true, @@ -1632,7 +1686,9 @@ pub fn specs() -> Vec { label: "Sponge", menu: &[], shortcut: None, - params: brush_params!(r#","mode":"desaturate|saturate"="desaturate","vibrance":bool=true (flow = sponge strength)"#), + params: brush_params!( + r#","mode":"desaturate|saturate"="desaturate","vibrance":bool=true (flow = sponge strength),"wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges)"# + ), enabled: has_pixel_layer, run: |s, p| dab_cmd(s, p, "paint.sponge"), journal: true, @@ -1642,7 +1698,9 @@ pub fn specs() -> Vec { label: "Blur", menu: &[], shortcut: None, - params: brush_params!(r#","strength":1..100=50,"sampleAllLayers":bool=false"#), + params: brush_params!( + r#","strength":1..100=50,"sampleAllLayers":bool=false,"wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges)"# + ), enabled: has_pixel_layer, run: |s, p| dab_cmd(s, p, "paint.blur"), journal: true, @@ -1652,7 +1710,9 @@ pub fn specs() -> Vec { label: "Sharpen", menu: &[], shortcut: None, - params: brush_params!(r#","strength":1..100=50,"protectDetail":bool=true,"sampleAllLayers":bool=false"#), + params: brush_params!( + r#","strength":1..100=50,"protectDetail":bool=true,"sampleAllLayers":bool=false,"wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges)"# + ), enabled: has_pixel_layer, run: |s, p| dab_cmd(s, p, "paint.sharpen"), journal: true, @@ -1662,7 +1722,9 @@ pub fn specs() -> Vec { label: "Smudge", menu: &[], shortcut: None, - params: brush_params!(r#","strength":1..100=50,"fingerPainting":bool=false (starts with the foreground colour),"sampleAllLayers":bool=false"#), + params: brush_params!( + r#","strength":1..100=50,"fingerPainting":bool=false (starts with the foreground colour),"sampleAllLayers":bool=false,"wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges)"# + ), enabled: has_pixel_layer, run: |s, p| dab_cmd(s, p, "paint.smudge"), journal: true, @@ -1673,7 +1735,7 @@ pub fn specs() -> Vec { menu: &[], shortcut: None, params: brush_params!( - r#","state":row (a History panel row, as history.setSource: 0 = oldest state, then the current one, then the greyed redo states),"snapshot":id (a history.newSnapshot id; default: the History panel's source, else the oldest held state; a source of another canvas size is an error)"# + r#","state":row (a History panel row, as history.setSource: 0 = oldest state, then the current one, then the greyed redo states),"snapshot":id (a history.newSnapshot id; default: the History panel's source, else the oldest held state; a source of another canvas size is an error),"wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges)"# ), enabled: has_pixel_layer, run: history_brush, diff --git a/crates/engine/src/retouch_cmds/pattern_stamp.rs b/crates/engine/src/retouch_cmds/pattern_stamp.rs index f13afc112e..7ccb293d4f 100644 --- a/crates/engine/src/retouch_cmds/pattern_stamp.rs +++ b/crates/engine/src/retouch_cmds/pattern_stamp.rs @@ -8,12 +8,12 @@ use photocraft_color::{BlendMode, PixelFormat}; use photocraft_compose::pattern::{Placement, Tile, render}; use photocraft_doc::{LayerId, Pattern}; use photocraft_geom::Rect; -use photocraft_paint::retouch::{Footprint, Region, apply_coverage, apply_dab_stroke, over_native}; +use photocraft_paint::retouch::{Footprint, Region, apply_coverage, apply_dab_stroke_wrapped, over_native}; 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, reject_huge_stroke}; +use super::{bad, blend_param, damage_json, flag, has_pixel_layer, parse_brush, periodic, reject_huge_stroke, wrap_tile}; use crate::{Result, Session}; const STREAM_PHASE_X: u64 = 101; @@ -88,10 +88,16 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result { let pre = doc.clone(); let (surf, lock) = crate::channel_cmds::target_surface(doc, st.id, p)?; let sel = pre.selection.as_ref(); + // View › Pattern Preview: the stroke carries on across the canvas edges, the pattern + // following it as it goes. + let wrap = wrap_tile(&pre, p); 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)) + Ok(apply_dab_stroke_wrapped(surf, &st.stroke, sel, lock, 0, wrap, effect)) + } else if wrap.is_some() { + let (place, fmt) = (st.placement(), surf.format()); + periodic::stroke(&pre, surf, &st.stroke, sel, lock, st.mode, |_, r| Ok(paint_region(&st.tile, &place, &fmt, r))) } else { paint_aligned(surf, &st.stroke, sel, lock, &st.tile, st.placement(), st.mode, CMD) } @@ -119,7 +125,7 @@ pub fn live_impressionist(s: &Session, p: &Value) -> Result { } 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, |pre| st.impressionist_effect(pre.format()))?.with_tail_preview() + super::LiveDab::with_effect_on(doc, CMD, p, stroke, id, 0, |pre, _| st.impressionist_effect(pre.format()))?.with_tail_preview() } /// The pattern under destination `rect` in `fmt` (native channels): what an aligned stroke paints diff --git a/crates/engine/src/retouch_cmds/periodic.rs b/crates/engine/src/retouch_cmds/periodic.rs index f31542fb5a..27f4c9c86c 100644 --- a/crates/engine/src/retouch_cmds/periodic.rs +++ b/crates/engine/src/retouch_cmds/periodic.rs @@ -23,6 +23,31 @@ pub(super) fn project(rect: Rect, tile: Rect) -> Vec { ys.into_iter().flat_map(|(y0, y1)| xs.iter().map(move |&(x0, x1)| Rect::new(x0, y0, x1, y1))).collect() } +/// A composite tool's stroke wrapped around the document: `paint` gives the pixels for a +/// rectangle in the stroke's own coordinates, from the target as it was before the stroke, and +/// they go on through the stroke's coverage wherever it repeats on the document. +pub(super) fn stroke( + pre: &Document, + target: &mut Surface, + stroke: &Stroke, + selection: Option<&Surface>, + lock: bool, + mode: BlendMode, + mut paint: impl FnMut(&Surface, Rect) -> Result, +) -> Result { + let mut renderer = photocraft_paint::StrokeRenderer::new(&stroke.brush, None, 1.0); + renderer.push(&stroke.points); + renderer.finish(); + let before = target.clone(); + let bounds = renderer.bounds(); + Composite { target, before: &before, tile: pre.bounds(), opacity: stroke.brush.opacity, selection, lock, mode }.draw( + bounds, + &stroke.brush, + &stroke.points, + |r| paint(&before, r), + ) +} + /// Composite periodic copies of one stroke, restoring each dirty patch from pre-stroke pixels. /// Each dab wraps once, then builds flow towards its opacity ceiling. Stroke opacity and /// selection are applied once after all dabs, including repeated visits through other tiles. diff --git a/crates/engine/src/retouch_cmds/tests.rs b/crates/engine/src/retouch_cmds/tests.rs index 524e12f080..e88129cb67 100644 --- a/crates/engine/src/retouch_cmds/tests.rs +++ b/crates/engine/src/retouch_cmds/tests.rs @@ -2407,3 +2407,292 @@ fn periodic_clone_interior_matches_ordinary_brush_masks_and_transparency() { } } } + +// --------------------------------------------------------------------------------------------- +// View › Pattern Preview: every retouching stroke wraps across the canvas edges (#8883) +// --------------------------------------------------------------------------------------------- + +/// The canvas the Pattern Preview tests wrap around. +const WRAP: (u32, u32) = (48, 36); + +/// `texture` repeated every canvas, so each copy of a pixel holds the same colour. +fn tiled_texture(x: i32, y: i32) -> [f32; 4] { + texture(x.rem_euclid(WRAP.0 as i32), y.rem_euclid(WRAP.1 as i32)) +} + +/// A stroke from just inside the corner where the middle copy of a three-by-three tiling meets +/// the next copies, out across both of its edges. +fn corner_stroke(extra: &Value) -> Value { + let mut p = json!({"points": [[84, 64], [106, 79]], "size": 12, "hardness": 100}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + p +} + +/// The texture on the layer. +fn textured(s: &mut Session) { + paint_layer(s, tiled_texture); +} + +/// The texture under an empty layer, which is the target (Sample All Layers). +fn textured_below(s: &mut Session) { + paint_layer(s, tiled_texture); + s.execute("layer.new.layer", json!({})).unwrap(); +} + +/// The texture in history state 1, painted over since. +fn textured_in_history(s: &mut Session) { + paint_layer(s, tiled_texture); + paint_layer(s, |_, _| [0.15, 0.2, 0.7, 1.0]); +} + +type Setup = fn(&mut Session); + +/// Every stroke tool that wraps, with options and a document for it. `true` marks the tools +/// that composite a paint image through the stroke's coverage (`periodic::Composite`), which +/// matches the ordinary composite only within rounding. +fn wrap_cases() -> Vec<(&'static str, Value, Setup, bool)> { + vec![ + ("paint.dodge", json!({"exposure": 60}), textured, false), + ("paint.burn", json!({"exposure": 40, "range": "shadows", "protectTones": false}), textured, false), + ("paint.sponge", json!({"mode": "saturate"}), textured, false), + ("paint.blur", json!({"strength": 80}), textured, false), + ("paint.sharpen", json!({"strength": 60}), textured, false), + ("paint.smudge", json!({"strength": 70}), textured, false), + ("paint.blur", json!({"strength": 80, "sampleAllLayers": true}), textured_below, false), + ("paint.smudge", json!({"strength": 70, "sampleAllLayers": true}), textured_below, false), + ("paint.mixerBrush", json!({"wet": 100, "mix": 80, "load": 50}), textured, false), + ("paint.mixerBrush", json!({"wet": 100, "mix": 80, "sampleAllLayers": true}), textured_below, false), + ("paint.colorReplacement", json!({"color": "#ff8000", "tolerance": 60}), textured, false), + ("paint.backgroundEraser", json!({"tolerance": 40}), textured, false), + ("paint.patternStamp", json!({"pattern": "Bricks", "impressionist": true}), textured, false), + ("paint.patternStamp", json!({"pattern": "Checkerboard"}), textured, true), + ("paint.historyBrush", json!({"state": 1}), textured_in_history, true), + ("paint.healingBrush", json!({"offset": [-20, -14]}), textured, true), + ("paint.cloneStamp", json!({"offset": [-20, -14]}), textured, true), + ] +} + +/// The native-channel difference `periodic::Composite` may leave against the ordinary composite. +fn composite_tolerance(depth: u64) -> f32 { + match depth { + 8 => 1.1 / 255.0, + 16 => 1.1 / 65535.0, + _ => 0.00001, + } +} + +#[test] +fn every_wrapping_stroke_paints_the_canvas_as_on_the_canvas_tiled_three_by_three() { + // A stroke with `"wrap": true` gives each pixel of the canvas what the same stroke gives the + // copy of that pixel it goes over, on a document holding the canvas tiled three by three. + let (w, h) = (WRAP.0 as usize, WRAP.1 as usize); + for depth in DEPTHS { + for (cmd, extra, setup, composite) in wrap_cases() { + let mut canvas = session(WRAP.0, WRAP.1, depth, "rgb"); + setup(&mut canvas); + let mut tiled = session(3 * WRAP.0, 3 * WRAP.1, depth, "rgb"); + setup(&mut tiled); + let (mut wrapped, plain) = (corner_stroke(&extra), corner_stroke(&extra)); + wrapped["wrap"] = json!(true); + canvas.execute(cmd, wrapped).unwrap_or_else(|e| panic!("{cmd} at {depth}: {e}")); + let before = layer_pixels(&tiled); + tiled.execute(cmd, plain).unwrap(); + let (got, want) = (layer_pixels(&canvas), layer_pixels(&tiled)); + let n = got.len() / (w * h); + let at = |x: usize, y: usize| (y * 3 * w + x) * n..(y * 3 * w + x + 1) * n; + let tolerance = if composite { composite_tolerance(depth) } else { 0.0 }; + let (mut moved, mut edges) = (0, [false; 4]); + for y in 0..h { + for x in 0..w { + let copies = (0..3).flat_map(|j| (0..3).map(move |i| (x + i * w, y + j * h))); + let changed: Vec<_> = copies.filter(|&(u, v)| want[at(u, v)] != before[at(u, v)]).collect(); + let (pixel, expected) = match changed.as_slice() { + [] => (&got[(y * w + x) * n..][..n], &before[at(x, y)]), + [(u, v)] => (&got[(y * w + x) * n..][..n], &want[at(*u, *v)]), + _ => panic!("{cmd}: ({x}, {y}) has two copies under the stroke"), + }; + let error = pixel.iter().zip(expected).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(error <= tolerance, "{cmd} {extra} at {depth}-bit: ({x}, {y}) is off by {error}"); + if !changed.is_empty() { + moved += 1; + edges[0] |= x < 8; + edges[1] |= x >= w - 8; + edges[2] |= y < 8; + edges[3] |= y >= h - 8; + } + } + } + assert!(moved > 150 && edges.iter().all(|&e| e), "{cmd} {extra} at {depth}-bit: the stroke crossed both edges ({moved} px, {edges:?})"); + } + } +} + +#[test] +fn a_wrapped_stroke_inside_the_canvas_paints_as_an_ordinary_one() { + let p = json!({"points": [[130, 110], [150, 118], [168, 112]], "size": 14, "hardness": 60}); + let mut cases: Vec<(&str, Value, Setup, bool)> = wrap_cases(); + cases.push(("paint.spotHealing", json!({"type": "contentAware"}), textured, false)); + cases.push(("paint.spotHealing", json!({"type": "proximityMatch"}), textured, false)); + for depth in [8, 32] { + for (cmd, extra, setup, composite) in &cases { + let run = |wrap: bool| { + // Big enough that Spot Healing's window stays clear of the edges either way. + let mut s = session(300, 230, depth, "rgb"); + setup(&mut s); + let mut q = p.clone(); + for (k, v) in extra.as_object().unwrap() { + q[k] = v.clone(); + } + q["wrap"] = json!(wrap); + let r = s.execute(cmd, q).unwrap(); + (layer_pixels(&s), r["damage"].clone()) + }; + let ((plain, d0), (wrapped, d1)) = (run(false), run(true)); + let tolerance = if *composite { composite_tolerance(depth) } else { 0.0 }; + let error = plain.iter().zip(&wrapped).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(error <= tolerance, "{cmd} {extra} at {depth}-bit: off by {error}"); + if !*composite { + assert_eq!(d0, d1, "{cmd} {extra} at {depth}-bit: the same damage"); + } + } + } +} + +#[test] +fn spot_healing_across_the_canvas_corner_heals_every_copy_of_the_stroke_and_nothing_else() { + // The window is centred on the stroke whatever the edges and one canvas across, so the + // corner heals from what surrounds it in the copies, the same as when the stroke stays inside. + for kind in ["contentAware", "createTexture", "proximityMatch"] { + let mut s = session(WRAP.0, WRAP.1, 8, "rgb"); + paint_layer(&mut s, |x, y| if (x - 2).abs() < 3 && (y - 2).abs() < 3 { [0.0, 0.0, 0.0, 1.0] } else { tiled_texture(x, y) }); + let before = layer_pixels(&s); + // The dark blemish straddles the corner (0, 0); the stroke is drawn on the copy to its + // lower right, around (48, 36). + s.execute("paint.spotHealing", json!({"points": [[48, 36], [50, 38]], "size": 14, "hardness": 100, "type": kind, "wrap": true})).unwrap(); + let after = layer_pixels(&s); + let n = after.len() / (WRAP.0 * WRAP.1) as usize; + let px = |v: &[f32], x: usize, y: usize| v[(y * WRAP.0 as usize + x) * n..][..n].to_vec(); + for (x, y) in [(1, 1), (46, 1), (1, 34), (46, 34)] { + assert!(px(&after, x, y)[0] > 0.1, "{kind}: ({x}, {y}) healed: {:?}", px(&after, x, y)); + } + for (x, y) in [(24, 18), (10, 18), (24, 4), (38, 28)] { + assert_eq!(px(&after, x, y), px(&before, x, y), "{kind}: ({x}, {y}) is far from the stroke"); + } + } +} + +#[test] +fn a_wrapped_dab_bigger_than_the_canvas_stays_on_it() { + let mut cases = wrap_cases(); + cases.push(("paint.spotHealing", json!({"type": "contentAware"}), textured, false)); + for (cmd, extra, setup, _) in cases { + let mut s = session(16, 12, 8, "rgb"); + setup(&mut s); + let mut p = json!({"points": [[8, 6], [30, 20]], "size": 60, "hardness": 0, "wrap": true}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + let r = s.execute(cmd, p).unwrap_or_else(|e| panic!("{cmd}: {e}")); + let d = r["damage"].as_array().map(|d| d.iter().filter_map(Value::as_i64).collect::>()).unwrap_or_default(); + assert!(matches!(d.as_slice(), [x, y, w, h] if *x >= 0 && *y >= 0 && x + w <= 16 && y + h <= 12), "{cmd}: damage {d:?} is on the canvas"); + let st = s.active().unwrap(); + let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); + assert!([(-1, 5), (16, 5), (5, -1), (5, 12), (40, 30)].iter().all(|&(x, y)| surf.rgba(x, y)[3] == 0.0), "{cmd}: nothing lands off the canvas"); + } +} + +#[test] +fn wrapped_live_strokes_show_what_their_commits_paint() { + // Across the left and bottom edges, as the canvas draws them: Dodge … Smudge commit the + // pixels they drew; the strokes that preview their finishing dabs show their commit's. + let points = [[30.0, 20.0], [10.0, 30.0], [-6.0, 40.0], [-12.0, 34.0]]; + for depth in DEPTHS { + for (cmd, extra) in dab_cases() { + let mut s = session(WRAP.0, WRAP.1, depth, "rgb"); + paint_layer(&mut s, tiled_texture); + let mut extra = extra.clone(); + extra["wrap"] = json!(true); + let rendered = s.execute(cmd, dab_opts(&points, 50, &extra)).unwrap(); + let want = layer_pixels(&s); + s.execute("edit.undo", json!({})).unwrap(); + offer_live(&mut s, cmd, &points, 50, &extra); + let taken = s.execute(cmd, dab_opts(&points, 50, &extra)).unwrap(); + assert_eq!(taken["fromLive"], json!(true), "{cmd} at {depth}-bit"); + assert_eq!(taken["damage"], rendered["damage"], "{cmd} at {depth}-bit"); + assert!(layer_pixels(&s) == want, "{cmd} at {depth}-bit: the live pixels are the command's"); + } + let pts: Vec<_> = points.iter().map(|q| StrokePoint::new(q[0], q[1], 1.0)).collect(); + type Begin = fn(&Session, &Value) -> Result; + let shown: [(&str, Value, Begin); 3] = [ + ("paint.colorReplacement", json!({"color": "#ff8000", "tolerance": 60}), crate::brush_cmds::live_color_replacement), + ("paint.backgroundEraser", json!({"tolerance": 40}), crate::eraser_cmds::live_background_eraser), + // A seed, as the canvas sends: without one the jitter hashes all the points. + ("paint.patternStamp", json!({"pattern": "Bricks", "impressionist": true, "seed": 7}), live_pattern_impressionist), + ]; + for (cmd, extra, begin) in shown { + let mut s = session(WRAP.0, WRAP.1, depth, "rgb"); + paint_layer(&mut s, tiled_texture); + let mut p = dab_opts(&points[..1], 50, &extra); + p["wrap"] = json!(true); + let mut live = begin(&s, &p).unwrap(); + live.push(&pts[1..]).unwrap(); + let shown = live.doc.clone(); + let pre = s.active().unwrap().doc.clone(); + p["points"] = json!(points); + s.execute(cmd, p).unwrap(); + let st = s.active().unwrap(); + let id = st.active_layer.unwrap(); + let (a, b) = (shown.layer(id).unwrap().surface().unwrap(), st.doc.layer(id).unwrap().surface().unwrap()); + let before = pre.layer(id).unwrap().surface().unwrap(); + let worst = (0..WRAP.1 as i32) + .flat_map(|y| (0..WRAP.0 as i32).map(move |x| (x, y))) + .map(|(x, y)| (0..4).map(|c| (a.rgba(x, y)[c] - b.rgba(x, y)[c]).abs()).fold(0.0f32, f32::max)) + .fold(0.0f32, f32::max); + assert!(worst <= 2.0 / 255.0 + 1e-6, "{cmd} at {depth}-bit: live and commit differ by {worst}"); + let right = WRAP.0 as i32 - 3; + assert!((0..WRAP.1 as i32).any(|y| b.rgba(right, y) != before.rgba(right, y)), "{cmd} at {depth}-bit: the stroke came back at the right edge"); + } + } +} + +#[test] +fn wrapped_live_retouch_strokes_show_what_their_commits_paint() { + // History Brush commits the pixels its live stroke drew across the edges; the aligned Pattern + // Stamp's preview is its commit. + let points = [[30.0, 20.0], [10.0, 30.0], [-6.0, 40.0], [-12.0, 34.0]]; + let pts: Vec<_> = points.iter().map(|q| StrokePoint::new(q[0], q[1], 1.0)).collect(); + for depth in DEPTHS { + for (cmd, extra, setup) in [ + ("paint.historyBrush", json!({"state": 1}), textured_in_history as Setup), + ("paint.patternStamp", json!({"pattern": "Checkerboard"}), textured as Setup), + ] { + let mut s = session(WRAP.0, WRAP.1, depth, "rgb"); + setup(&mut s); + let mut p = dab_opts(&points[..1], 50, &extra); + p["wrap"] = json!(true); + let mut live = LiveRetouch::begin(&s, cmd, &p).unwrap(); + live.push(&pts[1..]).unwrap(); + p["points"] = json!(points); + let shown = live.doc.layer(s.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().read_region(Rect::new(0, 0, 48, 36)); + let plain = s.execute(cmd, p.clone()).unwrap(); + let want = layer_pixels(&s); + let error = shown.iter().zip(&want).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(error <= composite_tolerance(depth), "{cmd} at {depth}-bit: the preview is off by {error}"); + if cmd == "paint.historyBrush" { + // A stroke drawn on the document as it is after the undo. + s.execute("edit.undo", json!({})).unwrap(); + let mut first = p.clone(); + first["points"] = json!(points[..1]); + let mut live = LiveRetouch::begin(&s, cmd, &first).unwrap(); + live.push(&pts[1..]).unwrap(); + s.offer_live_retouch(live).unwrap(); + let taken = s.execute(cmd, p).unwrap(); + assert_eq!(taken["fromLive"], json!(true), "{depth}-bit"); + assert_eq!(taken["damage"], plain["damage"], "{depth}-bit"); + assert!(layer_pixels(&s) == want, "{depth}-bit: the committed live pixels are the command's"); + } + } + } +} diff --git a/crates/paint/src/bg_erase.rs b/crates/paint/src/bg_erase.rs index 323a90036a..e41308e76a 100644 --- a/crates/paint/src/bg_erase.rs +++ b/crates/paint/src/bg_erase.rs @@ -10,7 +10,7 @@ use serde::{Deserialize, Serialize}; use crate::Stroke; use crate::replace::{Limits, Sampling}; -use crate::retouch::{Footprint, Region, alpha_index, apply_dab_stroke}; +use crate::retouch::{Footprint, Region, alpha_index, apply_dab_stroke_wrapped}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] @@ -49,8 +49,14 @@ 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 Some(effect) = background_eraser_effect(target, bs) else { return Rect::EMPTY }; - apply_dab_stroke(target, &background_eraser_stroke(stroke), selection, false, 0, effect) + apply_background_eraser_wrapped(target, stroke, bs, selection, None) +} + +/// [`apply_background_eraser`] wrapped around `wrap` (View › Pattern Preview): the stroke samples +/// and erases where its pixels lie on that canvas, so it carries on across the edges. +pub fn apply_background_eraser_wrapped(target: &mut Surface, stroke: &Stroke, bs: &BgEraseSettings, selection: Option<&Surface>, wrap: Option) -> Rect { + let Some(effect) = background_eraser_effect(target, bs, wrap) else { return Rect::EMPTY }; + apply_dab_stroke_wrapped(target, &background_eraser_stroke(stroke), selection, false, 0, wrap, effect) } /// The stroke [`apply_background_eraser`] runs its dabs along: full opacity (the tool has none), @@ -64,8 +70,9 @@ pub fn background_eraser_stroke(stroke: &Stroke) -> Stroke { /// One Background Eraser dab's edit of a working copy of `pre` (the target before the stroke): /// shared by [`apply_background_eraser`] and live previews that run the dabs as they come, so both -/// erase the same pixels. `None` when `pre` has no alpha channel (nothing can be erased). -pub fn background_eraser_effect(pre: &Surface, bs: &BgEraseSettings) -> Option> { +/// erase the same pixels. `None` when `pre` has no alpha channel (nothing can be erased). In a +/// stroke wrapped around `wrap`, `pre` is read where the working pixels lie on that canvas. +pub fn background_eraser_effect(pre: &Surface, bs: &BgEraseSettings, wrap: Option) -> Option> { let fmt = pre.format(); let a = alpha_index(&fmt)?; let nc = a; @@ -97,7 +104,7 @@ pub fn background_eraser_effect(pre: &Surface, bs: &BgEraseSettings) -> Option, @@ -101,7 +105,9 @@ pub fn apply_mixer_stroke( state: &mut MixerState, selection: Option<&Surface>, lock_transparency: bool, + wrap: Option, ) -> Rect { + let wrap = wrap.filter(|t| !t.is_empty()); let fmt = target.format(); let n = fmt.channels(); let a = alpha_index(&fmt); @@ -121,7 +127,7 @@ pub fn apply_mixer_stroke( st.brush.opacity = 1.0; let mut acc = vec![0.0f32; n]; let mut paint = vec![0.0f32; n]; - let dmg = apply_dab_stroke(target, &st, selection, lock_transparency, 0, |work, fp| { + let dmg = apply_dab_stroke_wrapped(target, &st, selection, lock_transparency, 0, wrap, |work, fp| { // Transfer › Wetness / Mix Jitter scale the settings per dab. let (wet, mix) = (wet * fp.dab.wet.clamp(0.0, 1.0), mix * fp.dab.mix.clamp(0.0, 1.0)); // Sample the canvas under the dab. @@ -136,6 +142,7 @@ pub fn apply_mixer_stroke( } let px: Vec = match sample { Some(s) => { + let (x, y) = wrap.map_or((x, y), |t| (wrap_coord(x, t.x0, t.x1), wrap_coord(y, t.y0, t.y1))); let v = s.pixel(x, y); if s.format() == fmt { v } else { from_rgba(&fmt, s.rgba(x, y)) } } @@ -202,7 +209,16 @@ mod tests { let mut s = Surface::new(PixelFormat::RGBA8); let mut st = MixerState::default(); st.load([1.0, 0.0, 0.0, 1.0]); - apply_mixer_stroke(&mut s, None, &stroke(10.0), &MixerSettings { wet: 0.0, load, mix: 0.0, flow: 1.0, ..Default::default() }, &mut st, None, false); + apply_mixer_stroke( + &mut s, + None, + &stroke(10.0), + &MixerSettings { wet: 0.0, load, mix: 0.0, flow: 1.0, ..Default::default() }, + &mut st, + None, + false, + None, + ); let (start, end) = (s.rgba(10, 10)[3], s.rgba(190, 10)[3]); assert!(start > 0.95, "{start}"); if expect_dry { @@ -231,6 +247,7 @@ mod tests { &mut st, None, false, + None, ); // Blue is dragged into the white half. let c = s.rgba(115, 10); @@ -252,7 +269,7 @@ mod tests { // On red, the clean wet brush smears red and lays down none of the blue it was loaded with. let mut s = Surface::new(PixelFormat::RGBA8); s.fill_rect(Rect::new(0, 0, 200, 20), &[1.0, 0.0, 0.0, 1.0]); - apply_mixer_stroke(&mut s, None, &stroke(10.0), &MixerSettings::default(), &mut st, None, false); + apply_mixer_stroke(&mut s, None, &stroke(10.0), &MixerSettings::default(), &mut st, None, false, None); let c = s.rgba(100, 10); assert!(c[0] > 0.99 && c[1] < 0.01 && c[2] < 0.01, "{c:?}"); } @@ -288,7 +305,7 @@ mod tests { fn dry_empty_brush_paints_nothing() { let mut s = Surface::new(PixelFormat::RGBA8); let mut st = MixerState::default(); - let dmg = apply_mixer_stroke(&mut s, None, &stroke(10.0), &MixerSettings { wet: 0.0, ..Default::default() }, &mut st, None, false); + let dmg = apply_mixer_stroke(&mut s, None, &stroke(10.0), &MixerSettings { wet: 0.0, ..Default::default() }, &mut st, None, false, None); assert!(!dmg.is_empty()); assert_eq!(s.rgba(50, 10)[3], 0.0); } @@ -306,7 +323,7 @@ mod tests { for p in &mut k.points { p.pressure = pressure; } - apply_mixer_stroke(&mut s, None, &k, &MixerSettings { wet: 1.0, load: 1.0, mix: 1.0, flow: 1.0, ..Default::default() }, &mut st, None, false); + apply_mixer_stroke(&mut s, None, &k, &MixerSettings { wet: 1.0, load: 1.0, mix: 1.0, flow: 1.0, ..Default::default() }, &mut st, None, false, None); st.pickup }; assert!(run(0.0).is_none()); diff --git a/crates/paint/src/replace.rs b/crates/paint/src/replace.rs index 20619cd48a..957037a0bd 100644 --- a/crates/paint/src/replace.rs +++ b/crates/paint/src/replace.rs @@ -8,7 +8,8 @@ use photocraft_raster::{Surface, from_rgba_into, to_rgba}; use serde::{Deserialize, Serialize}; use crate::Stroke; -use crate::retouch::{Footprint, Region, apply_dab_stroke}; +use crate::retouch::{Footprint, Region, apply_dab_stroke_wrapped}; +use crate::wrap::wrap_coord; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -79,14 +80,29 @@ fn dist(a: &[f32; 4], b: [f32; 3]) -> f32 { /// Replace colours along a stroke. Returns the damaged rectangle. pub fn apply_color_replacement(target: &mut Surface, stroke: &Stroke, rs: &ReplaceSettings, selection: Option<&Surface>, lock_transparency: bool) -> Rect { - let effect = color_replacement_effect(target.clone(), rs.clone()); - apply_dab_stroke(target, stroke, selection, lock_transparency, 0, effect) + apply_color_replacement_wrapped(target, stroke, rs, selection, lock_transparency, None) +} + +/// [`apply_color_replacement`] wrapped around `wrap` (View › Pattern Preview): the stroke samples +/// and recolours where its pixels lie on that canvas, so it carries on across the edges. +pub fn apply_color_replacement_wrapped( + target: &mut Surface, + stroke: &Stroke, + rs: &ReplaceSettings, + selection: Option<&Surface>, + lock_transparency: bool, + wrap: Option, +) -> Rect { + let effect = color_replacement_effect(target.clone(), rs.clone(), wrap); + apply_dab_stroke_wrapped(target, stroke, selection, lock_transparency, 0, wrap, effect) } /// One Color Replacement dab's edit of a working copy, matching against `pre` (the target before /// the stroke). Shared by [`apply_color_replacement`] and live previews that run the dabs as they -/// come, so both recolour the same pixels. -pub fn color_replacement_effect(pre: Surface, rs: ReplaceSettings) -> impl FnMut(&mut Region, &Footprint) { +/// come, so both recolour the same pixels. In a stroke wrapped around `wrap` (View › Pattern +/// Preview), `pre` is read where the dab's pixels lie on that canvas. +pub fn color_replacement_effect(pre: Surface, rs: ReplaceSettings, wrap: Option) -> impl FnMut(&mut Region, &Footprint) { + let wrap = wrap.filter(|t| !t.is_empty()); let fmt = pre.format(); let n = fmt.channels(); let mode = match rs.mode { @@ -111,13 +127,14 @@ pub fn color_replacement_effect(pre: Surface, rs: ReplaceSettings) -> impl FnMut }; move |work: &mut Region, fp: &Footprint| { let (cx, cy) = (fp.dab.center.x.floor() as i32, fp.dab.center.y.floor() as i32); + let (sx, sy) = wrap.map_or((cx, cy), |t| (wrap_coord(cx, t.x0, t.x1), wrap_coord(cy, t.y0, t.y1))); let sampled = match rs.sampling { Sampling::Continuous => { - let c = pre.rgba(cx, cy); + let c = pre.rgba(sx, sy); [c[0], c[1], c[2]] } Sampling::Once => *once.get_or_insert_with(|| { - let c = pre.rgba(cx, cy); + let c = pre.rgba(sx, sy); [c[0], c[1], c[2]] }), Sampling::BackgroundSwatch => [rs.background[0], rs.background[1], rs.background[2]], @@ -127,8 +144,15 @@ pub fn color_replacement_effect(pre: Surface, rs: ReplaceSettings) -> impl FnMut return; } let (w, h) = (r.width() as usize, r.height() as usize); - let mut pre_px = vec![[0.0f32; 4]; w * h]; - pre.read_rgba_into(r, &mut pre_px); + let read = |q: Rect| { + let mut px = vec![[0.0f32; 4]; q.width() as usize * q.height() as usize]; + pre.read_rgba_into(q, &mut px); + px + }; + let pre_px = match wrap { + Some(t) => crate::wrap::read(r, t, 1, read), + None => read(r), + }; // Per-pixel match weight. let mut weight = vec![0.0f32; w * h]; for y in r.y0..r.y1 { diff --git a/crates/paint/src/retouch.rs b/crates/paint/src/retouch.rs index 06bafe6cfb..09c38fc78a 100644 --- a/crates/paint/src/retouch.rs +++ b/crates/paint/src/retouch.rs @@ -14,10 +14,13 @@ //! All pixel data here is the surface's *native* channels as normalised `f32` (any depth, any colour //! model); colour-space-specific work happens in the callbacks. +use std::collections::HashMap; + use photocraft_color::{BlendMode, PixelFormat}; use photocraft_geom::Rect; use photocraft_raster::{Surface, from_rgba_into, to_rgba}; +use crate::wrap::{fits, fold_area, wrap_coord}; use crate::{Dab, Stroke, dab_coverage, dabs}; /// A rectangle of native-channel pixels (`rect.width() × rect.height() × ch` floats, row-major). @@ -75,6 +78,14 @@ impl Region { pub fn write(&self, s: &mut Surface) { s.write_region(self.rect, &self.data); } + /// Read `rect` from a surface that repeats `wrap` apart (View › Pattern Preview): `rect` may + /// cross its edges. `None` (or an empty tile) is [`Region::read`]. + pub fn read_wrapped(s: &Surface, rect: Rect, wrap: Option) -> Self { + match wrap.filter(|t| !t.is_empty()) { + Some(tile) => Self { rect, ch: s.channels(), data: crate::wrap::read(rect, tile, s.channels(), |r| s.read_region(r)) }, + None => Self::read(s, rect), + } + } } /// One dab's footprint: coverage (hardness falloff × dab alpha) over its bounding rectangle. @@ -266,6 +277,174 @@ pub fn apply_dab_stroke( bounds } +/// [`apply_dab_stroke`] wrapped around `wrap` (View › Pattern Preview): each dab reads and edits +/// the pixels where it repeats on that tile, so a stroke crossing an edge carries on at the +/// opposite one. The dabs run one by one on a [`WorkTiles`] working copy, as live previews run +/// them. `None` (or an empty tile) is [`apply_dab_stroke`]. Returns the damaged rectangle. +pub fn apply_dab_stroke_wrapped( + target: &mut Surface, + stroke: &Stroke, + selection: Option<&Surface>, + lock_transparency: bool, + halo: i32, + wrap: Option, + mut effect: impl FnMut(&mut Region, &Footprint), +) -> Rect { + let Some(tile) = wrap.filter(|t| !t.is_empty()) else { + return apply_dab_stroke(target, stroke, selection, lock_transparency, halo, effect); + }; + let ctx = crate::BrushContext::new(&stroke.brush); + let mut work = WorkTiles::new(target.channels()).wrapped(Some(tile)); + let mut damage = Rect::EMPTY; + for (i, d) in dabs(stroke).iter().enumerate() { + let fp = ctx.footprint(d, i); + if fp.rect.is_empty() { + continue; + } + let mut region = work.read(target, fp.rect.inflate(halo)); + effect(&mut region, &fp); + work.write_dab(target, ®ion, &fp); + damage = damage.union(&fold_area(fp.rect, tile)); + } + let written: Vec = work.areas().map(|r| r.intersect(&tile)).filter(|r| !r.is_empty()).collect(); + for r in written { + let edited = work.read(target, r); + mix_back(target, &Region::read(target, r), &edited, r, stroke.brush.opacity, selection, lock_transparency); + } + damage +} + +/// Side of the tiles a [`WorkTiles`] working copy keeps its pixels in. +const WORK_TILE: i32 = 128; + +/// The working copy of a sequential-dab stroke run dab by dab (live previews, +/// [`apply_dab_stroke_wrapped`]): the target's native channels as `f32`, in tiles copied from the +/// pre-stroke surface the first time a dab writes to them. Unlike a `Surface`, it isn't rounded to +/// the document's depth between dabs, so each dab sees what [`apply_dab_stroke`]'s working copy +/// holds. Wrapped around a tile ([`Self::wrapped`]), it keeps each pixel once, where it lies on +/// the tile, and reads and writes it wherever it repeats. +pub struct WorkTiles { + ch: usize, + tiles: HashMap<(i32, i32), Vec>, + wrap: Option, +} + +impl WorkTiles { + pub fn new(ch: usize) -> Self { + Self { ch, tiles: HashMap::new(), wrap: None } + } + + /// Keep the pixels of a stroke wrapped around `tile` (View › Pattern Preview). `None` or an + /// empty tile doesn't wrap. + pub fn wrapped(mut self, tile: Option) -> Self { + self.wrap = tile.filter(|t| !t.is_empty()); + self + } + + fn tile_rect((tx, ty): (i32, i32)) -> Rect { + Rect::new(tx * WORK_TILE, ty * WORK_TILE, tx * WORK_TILE + WORK_TILE, ty * WORK_TILE + WORK_TILE) + } + + /// The tiles `r` overlaps. + fn coords(r: Rect) -> impl Iterator { + let (x0, x1) = (r.x0.div_euclid(WORK_TILE), (r.x1 - 1).div_euclid(WORK_TILE)); + let (y0, y1) = (r.y0.div_euclid(WORK_TILE), (r.y1 - 1).div_euclid(WORK_TILE)); + let empty = r.is_empty(); + (y0..=y1).filter(move |_| !empty).flat_map(move |ty| (x0..=x1).map(move |tx| (tx, ty))) + } + + /// The working pixels of `r`: the pre-stroke pixels `pre` where no dab has written yet. + /// Wrapped, `r` may cross the tile's edges or be bigger than it. + pub fn read(&self, pre: &Surface, r: Rect) -> Region { + match self.wrap { + Some(tile) => Region { rect: r, ch: self.ch, data: crate::wrap::read(r, tile, self.ch, |part| self.read_at(pre, part).data) }, + None => self.read_at(pre, r), + } + } + + fn read_at(&self, pre: &Surface, r: Rect) -> Region { + let mut out = Region::new(r, self.ch); + let n = self.ch; + let mut buf = Vec::new(); + for c in Self::coords(r) { + let tr = Self::tile_rect(c); + let part = r.intersect(&tr); + let w = part.width() as usize * n; + let tile = self.tiles.get(&c); + if tile.is_none() { + pre.read_region_into(part, &mut buf); + } + for y in part.y0..part.y1 { + let src = match tile { + Some(t) => t.get(((y - tr.y0) * WORK_TILE + (part.x0 - tr.x0)) as usize * n..).and_then(|s| s.get(..w)), + None => buf.get((y - part.y0) as usize * w..).and_then(|s| s.get(..w)), + }; + let dst = out.index(part.x0, y) * n; + if let (Some(s), Some(d)) = (src, out.data.get_mut(dst..dst + w)) { + d.copy_from_slice(s); + } + } + } + out + } + + /// Store a dab's edit: the pixels of `region` (which covers the dab) over the dab's rectangle + /// `fp.rect`. Wrapped, they land where they lie on the tile; a dab bigger than the tile covers + /// some pixels more than once, and each keeps the copy the dab covers most. + pub fn write_dab(&mut self, pre: &Surface, region: &Region, fp: &Footprint) { + let r = fp.rect.intersect(®ion.rect); + let Some(tile) = self.wrap else { + return self.write_at(pre, ®ion.crop(r)); + }; + if fits(r, tile) { + for (part, (dx, dy)) in crate::wrap::pieces(r, tile) { + let mut piece = region.crop(part.translate(dx, dy)); + piece.rect = part; + self.write_at(pre, &piece); + } + return; + } + let area = fold_area(r, tile); + let mut folded = self.read_at(pre, area); + let mut most = vec![0.0f32; area.width() as usize * area.height() as usize]; + for y in r.y0..r.y1 { + for x in r.x0..r.x1 { + let (c, tx, ty) = (fp.at(x, y), wrap_coord(x, tile.x0, tile.x1), wrap_coord(y, tile.y0, tile.y1)); + if let Some(m) = most.get_mut(folded.index(tx, ty)) + && c > *m + { + *m = c; + folded.px_mut(tx, ty).copy_from_slice(region.px(x, y)); + } + } + } + self.write_at(pre, &folded); + } + + /// Store `region` as the working pixels of its rectangle. + fn write_at(&mut self, pre: &Surface, region: &Region) { + let (r, n) = (region.rect, self.ch); + for c in Self::coords(r) { + let tr = Self::tile_rect(c); + let tile = self.tiles.entry(c).or_insert_with(|| pre.read_region(tr)); + let part = r.intersect(&tr); + let w = part.width() as usize * n; + for y in part.y0..part.y1 { + let dst = ((y - tr.y0) * WORK_TILE + (part.x0 - tr.x0)) as usize * n; + let src = region.index(part.x0, y) * n; + if let (Some(s), Some(d)) = (region.data.get(src..src + w), tile.get_mut(dst..dst + w)) { + d.copy_from_slice(s); + } + } + } + } + + /// The rectangles of the tiles dabs have written to. + pub fn areas(&self) -> impl Iterator + '_ { + self.tiles.keys().map(|&c| Self::tile_rect(c)) + } +} + /// Mix a sequential-dab stroke's working pixels `work` back over the original `orig` at /// `opacity × selection` inside `rect`, and write that area to `target`: the last step of /// [`apply_dab_stroke`], shared with live previews that run the dabs as they come. @@ -637,4 +816,89 @@ mod tests { } } } + + /// The canvas the Pattern Preview strokes below wrap around. + const TILE: Rect = Rect::new(0, 0, 40, 30); + + /// `area` of a surface showing the canvas repeated: every pixel of the canvas has its own colour. + fn tiled(fmt: PixelFormat, area: Rect) -> Surface { + let mut s = Surface::new(fmt); + let px = (area.y0..area.y1).flat_map(|y| (area.x0..area.x1).map(move |x| (wrap_coord(x, 0, 40), wrap_coord(y, 0, 30)))); + let data: Vec = px.flat_map(|(x, y)| [x as f32 / 40.0, y as f32 / 30.0, ((x * 7 + y * 3) % 13) as f32 / 13.0, 1.0]).collect(); + s.write_region(area, &data); + s + } + + fn smudge(size: f32) -> impl FnMut(&mut Region, &Footprint) { + let mut sm = Smudge::new(0.8, None, size).with_alpha(Some(3)); + move |work, fp| sm.dab(work, fp) + } + + #[test] + fn a_wrapped_sequential_stroke_paints_the_canvas_as_its_tiled_copies_would() { + // View › Pattern Preview: a smudge across a corner of the canvas copy it is drawn on gives + // the canvas exactly what it gives the canvas tiled three by three, where it runs into the + // next copies and carries their colours along. (The same points both times: moved points + // would place the dabs a rounding apart.) + let fmt = PixelFormat::RGBA32F; + let far = stroke(&[(68.0, 48.0), (92.0, 70.0)], 12.0, 0.5); + let halo = Smudge::sampling_radius(12.0); + let mut canvas = tiled(fmt, TILE); + let dmg = apply_dab_stroke_wrapped(&mut canvas, &far, None, false, halo, Some(TILE), smudge(12.0)); + let three = Rect::new(0, 0, 120, 90); + let (before, mut big) = (tiled(fmt, three), tiled(fmt, three)); + apply_dab_stroke(&mut big, &far, None, false, halo, smudge(12.0)); + let mut changed = 0; + for y in 0..30 { + for x in 0..40 { + let copies = [(40, 30), (80, 30), (40, 60), (80, 60)].map(|(dx, dy)| (x + dx, y + dy)); + let moved: Vec<_> = copies.into_iter().filter(|&(u, v)| big.pixel(u, v) != before.pixel(u, v)).collect(); + let want = match moved.as_slice() { + [] => before.pixel(x, y), + [(u, v)] => big.pixel(*u, *v), + _ => panic!("({x}, {y}): two copies under the stroke"), + }; + assert_eq!(canvas.pixel(x, y), want, "({x}, {y})"); + changed += usize::from(!moved.is_empty()); + } + } + assert!(changed > 300, "the smudge crossed both edges ({changed} px)"); + assert!(dmg.x0 >= 0 && dmg.y0 >= 0 && dmg.x1 <= 40 && dmg.y1 <= 30, "{dmg:?}"); + assert!((-12..0).all(|x| canvas.pixel(x, 20)[3] == 0.0) && (40..52).all(|x| canvas.pixel(x, 20)[3] == 0.0), "nothing off the canvas"); + } + + #[test] + fn a_wrapped_sequential_stroke_inside_the_canvas_paints_as_before() { + for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA32F] { + let st = stroke(&[(16.0, 12.0), (24.0, 18.0)], 6.0, 0.8); + let run = |wrap| { + let mut s = tiled(fmt, TILE); + let dmg = apply_dab_stroke_wrapped(&mut s, &st, None, false, Smudge::sampling_radius(6.0), wrap, smudge(6.0)); + (s, dmg) + }; + let ((plain, d0), (wrapped, d1)) = (run(None), run(Some(TILE))); + assert_eq!(d0, d1, "{fmt:?}"); + assert!((0..30).all(|y| (0..40).all(|x| plain.pixel(x, y) == wrapped.pixel(x, y))), "{fmt:?}"); + assert!(plain.pixel(20, 15) != tiled(fmt, TILE).pixel(20, 15), "{fmt:?}: the stroke smudged"); + } + } + + #[test] + fn a_wrapped_dab_bigger_than_the_canvas_edits_all_of_it_and_nothing_else() { + let small = Rect::new(0, 0, 10, 8); + let mut s = Surface::new(PixelFormat::RGBA32F); + s.fill_rect(small, &[1.0, 0.0, 0.0, 1.0]); + let darken = |work: &mut Region, fp: &Footprint| { + let r = fp.rect.intersect(&work.rect); + for y in r.y0..r.y1 { + for x in r.x0..r.x1 { + work.px_mut(x, y)[0] *= 1.0 - 0.5 * fp.at(x, y); + } + } + }; + let dmg = apply_dab_stroke_wrapped(&mut s, &stroke(&[(5.0, 4.0), (9.0, 6.0)], 30.0, 0.0), None, false, 0, Some(small), darken); + assert_eq!(dmg, small); + assert!((0..8).all(|y| (0..10).all(|x| s.pixel(x, y)[0] < 1.0)), "every pixel under the dab's copies darkens"); + assert!((-5..15).all(|x| s.pixel(x, -1)[3] == 0.0 && s.pixel(x, 8)[3] == 0.0), "nothing off the canvas"); + } } diff --git a/crates/paint/src/wrap.rs b/crates/paint/src/wrap.rs new file mode 100644 index 0000000000..efad49d3ca --- /dev/null +++ b/crates/paint/src/wrap.rs @@ -0,0 +1,166 @@ +//! View › Pattern Preview geometry: the document repeats its canvas (the *tile*) in every +//! direction, so a stroke past one edge carries on at the opposite one. Coordinates outside the +//! tile name the pixel a whole number of tile sizes away that lies on it. + +use photocraft_geom::Rect; + +/// `v` moved a whole number of periods into `lo..hi` (`v` itself when that is empty). +#[inline] +pub fn wrap_coord(v: i32, lo: i32, hi: i32) -> i32 { + let period = i64::from(hi) - i64::from(lo); + if period <= 0 { + return v; + } + (i64::from(lo) + (i64::from(v) - i64::from(lo)).rem_euclid(period)) as i32 +} + +/// Whether `rect` fits in `tile`, so it covers no pixel of the tile twice. +pub fn fits(rect: Rect, tile: Rect) -> bool { + rect.width() <= tile.width() && rect.height() <= tile.height() +} + +/// The part of `tile` that `rect` covers once moved onto it: per axis, the rectangle's span moved +/// a whole number of periods, or the whole tile where the span is longer or crosses an edge. +pub fn fold_area(rect: Rect, tile: Rect) -> Rect { + if rect.is_empty() || tile.is_empty() { + return Rect::EMPTY; + } + let span = |a0: i32, a1: i32, lo: i32, hi: i32| { + let start = wrap_coord(a0, lo, hi); + let len = i64::from(a1) - i64::from(a0); + if i64::from(start) + len > i64::from(hi) { (lo, hi) } else { (start, start + len as i32) } + }; + let (x0, x1) = span(rect.x0, rect.x1, tile.x0, tile.x1); + let (y0, y1) = span(rect.y0, rect.y1, tile.y0, tile.y1); + Rect::new(x0, y0, x1, y1) +} + +/// One axis of `a0..a1` cut where it crosses the edges of `lo..hi`: each run's start on the tile, +/// its start in `a0..a1`, and its length. +fn runs(a0: i32, a1: i32, lo: i32, hi: i32) -> Vec<(i32, i32, i32)> { + let period = i64::from(hi) - i64::from(lo); + let mut out = Vec::new(); + let mut a = i64::from(a0); + while a < i64::from(a1) { + let k = (a - i64::from(lo)).div_euclid(period) * period; + let end = (i64::from(a1) - k).min(i64::from(hi)); + let start = a - k; + out.push((start as i32, a as i32, (end - start) as i32)); + a = end + k; + } + out +} + +/// `r` cut where it crosses the edges of `tile`: each part moved onto the tile, with the offset +/// that moves it back (`part.translate(dx, dy)` is that part of `r`). A rectangle bigger than the +/// tile gives parts that overlap on it. +pub fn pieces(r: Rect, tile: Rect) -> Vec<(Rect, (i32, i32))> { + if r.is_empty() || tile.is_empty() { + return Vec::new(); + } + let xs = runs(r.x0, r.x1, tile.x0, tile.x1); + runs(r.y0, r.y1, tile.y0, tile.y1) + .into_iter() + .flat_map(|(ty, uy, h)| xs.iter().map(move |&(tx, ux, w)| (Rect::new(tx, ty, tx + w, ty + h), (ux - tx, uy - ty)))) + .collect() +} + +/// The values over `r` of an image repeating `tile` apart, given `read`, which returns a +/// rectangle of the tile (`n` values per pixel, row-major). A rectangle crossing at most one edge +/// per axis is read in its parts; a bigger one reads the tile area it covers once. +pub fn read(r: Rect, tile: Rect, n: usize, mut read: impl FnMut(Rect) -> Vec) -> Vec { + let w = r.width() as usize; + let mut out = vec![T::default(); w * r.height() as usize * n]; + if r.is_empty() || tile.is_empty() { + return out; + } + let (xs, ys) = (runs(r.x0, r.x1, tile.x0, tile.x1), runs(r.y0, r.y1, tile.y0, tile.y1)); + let mut copy = |src: &[T], at: usize, x: i32, y: i32, len: i32| { + let o = ((y - r.y0) as usize * w + (x - r.x0) as usize) * n; + let len = len as usize * n; + if let (Some(d), Some(s)) = (out.get_mut(o..o + len), src.get(at..at + len)) { + d.copy_from_slice(s); + } + }; + if xs.len() * ys.len() <= 4 { + for &(ty, uy, h) in &ys { + for &(tx, ux, len) in &xs { + let part = read(Rect::new(tx, ty, tx + len, ty + h)); + for row in 0..h { + copy(&part, row as usize * len as usize * n, ux, uy + row, len); + } + } + } + return out; + } + let area = fold_area(r, tile); + let src = read(area); + let aw = area.width() as usize; + for &(ty, uy, h) in &ys { + for row in 0..h { + for &(tx, ux, len) in &xs { + copy(&src, ((ty + row - area.y0) as usize * aw + (tx - area.x0) as usize) * n, ux, uy + row, len); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn coordinates_wrap_onto_the_tile_from_any_distance() { + assert_eq!([-17, -1, 0, 15, 16, 33, 1_000_000].map(|v| wrap_coord(v, 0, 16)), [15, 15, 0, 15, 0, 1, 0]); + assert_eq!(wrap_coord(-3, 10, 20), 17); + } + + #[test] + fn pieces_cover_the_rectangle_once_and_land_on_the_tile() { + let tile = Rect::new(0, 0, 10, 8); + for r in [Rect::new(7, 6, 13, 11), Rect::new(-25, 3, 4, 5), Rect::new(2, 2, 5, 5), Rect::new(-3, -3, 30, 20)] { + let mut seen = std::collections::HashMap::new(); + for (part, (dx, dy)) in pieces(r, tile) { + assert!(tile.contains(part.x0, part.y0) && part.x1 <= tile.x1 && part.y1 <= tile.y1, "{part:?} on the tile"); + for y in part.y0..part.y1 { + for x in part.x0..part.x1 { + *seen.entry((x + dx, y + dy)).or_insert(0) += 1; + assert_eq!((wrap_coord(x + dx, 0, 10), wrap_coord(y + dy, 0, 8)), (x, y)); + } + } + } + assert_eq!(seen.len(), (r.width() * r.height()) as usize, "{r:?}"); + assert!(seen.values().all(|&c| c == 1) && seen.keys().all(|&(x, y)| r.contains(x, y)), "{r:?}"); + } + } + + #[test] + fn a_read_repeats_the_tile_whatever_the_rectangle() { + let tile = Rect::new(4, 2, 14, 10); + let value = |x: i32, y: i32| (wrap_coord(x, 4, 14) * 100 + wrap_coord(y, 2, 10)) as f32; + let mut reads = 0; + // Two values per pixel; `read` only ever asks for rectangles of the tile. + let mut from_tile = |q: Rect| { + reads += 1; + assert!(q.x0 >= tile.x0 && q.y0 >= tile.y0 && q.x1 <= tile.x1 && q.y1 <= tile.y1, "{q:?}"); + (q.y0..q.y1).flat_map(|y| (q.x0..q.x1).flat_map(move |x| [value(x, y), -value(x, y)])).collect::>() + }; + for r in [Rect::new(10, 7, 17, 12), Rect::new(5, 3, 9, 6), Rect::new(-31, -5, 40, 30), Rect::new(0, 0, 0, 5)] { + let got = read(r, tile, 2, &mut from_tile); + let want: Vec = (r.y0..r.y1).flat_map(|y| (r.x0..r.x1).flat_map(move |x| [value(x, y), -value(x, y)])).collect(); + assert_eq!(got, want, "{r:?}"); + } + assert!(reads <= 4 + 1 + 1, "small rectangles read in parts, big ones once ({reads})"); + } + + #[test] + fn the_fold_area_is_where_a_rectangle_lands() { + let tile = Rect::new(0, 0, 10, 8); + assert_eq!(fold_area(Rect::new(12, 9, 15, 12), tile), Rect::new(2, 1, 5, 4)); + assert_eq!(fold_area(Rect::new(8, 2, 12, 4), tile), Rect::new(0, 2, 10, 4)); + assert_eq!(fold_area(Rect::new(-50, -50, 50, 50), tile), tile); + assert_eq!(fold_area(Rect::EMPTY, tile), Rect::EMPTY); + assert!(fits(Rect::new(3, 3, 13, 11), tile) && !fits(Rect::new(0, 0, 11, 2), tile)); + } +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index ab3e6939a7..83614c9244 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -700,6 +700,13 @@ fn stroke_params(app: &PhotocraftApp, d: &Drag, points: &[Vec]) -> serde_js p } +/// View › Pattern Preview: a painting stroke goes on across the canvas edges (#8883). +pub(crate) fn pattern_wrap(app: &PhotocraftApp, p: &mut serde_json::Value) { + if app.ui.view.pattern_preview { + p["wrap"] = json!(true); + } +} + /// Tools whose strokes the engine renders while they are drawn (`LiveStroke`). pub(crate) fn strokes_live(tool: Tool) -> bool { matches!( @@ -881,6 +888,7 @@ fn begin_live_stroke(app: &PhotocraftApp) -> Option { } 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)? }; + pattern_wrap(app, &mut p); p["points"] = json!(d.points); p["target"] = paint_target(app); EngineStroke::Retouch(photocraft_engine::retouch_cmds::LiveRetouch::begin(&app.session, cmd, &p).ok()?) diff --git a/crates/ui-egui/src/eraser_ui.rs b/crates/ui-egui/src/eraser_ui.rs index f92c3427e9..c13dca17f6 100644 --- a/crates/ui-egui/src/eraser_ui.rs +++ b/crates/ui-egui/src/eraser_ui.rs @@ -49,14 +49,16 @@ pub fn finish_stroke(app: &mut PhotocraftApp, tool: Tool, points: &[[f64; 3]]) - /// 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; - json!({ + let mut p = json!({ "points": points, "sampling": o.bg_sampling, "limits": o.bg_limits, "tolerance": o.bg_tolerance, "protectForegroundColor": o.bg_protect_fg, "seed": crate::retouch_ui::stroke_seed(points), - }) + }); + crate::canvas::pattern_wrap(app, &mut p); + p } /// Whether `tool` is the Eraser in Pencil mode: it erases hard, aliased pixels through diff --git a/crates/ui-egui/src/retouch_ui.rs b/crates/ui-egui/src/retouch_ui.rs index 5ed59869de..e62371bef5 100644 --- a/crates/ui-egui/src/retouch_ui.rs +++ b/crates/ui-egui/src/retouch_ui.rs @@ -32,6 +32,8 @@ pub(crate) fn clone_params(app: &PhotocraftApp) -> Option { p["wrap"] = json!(app.ui.view.pattern_preview); p["opacity"] = json!(app.session.tools.brush.opacity * 100.0); p["flow"] = json!(app.session.tools.brush.flow * 100.0); + } else { + crate::canvas::pattern_wrap(app, &mut p); } // The Clone Source panel's active slot (set by ⌥-click) drives the stroke: the engine keeps // the aligned pairing and applies the slot's scale/rotation/flip. @@ -49,7 +51,7 @@ pub(crate) fn clone_params(app: &PhotocraftApp) -> Option { /// Blur, Sharpen, Smudge, Dodge, Burn, Sponge. Shared by the live preview and the commit. pub(crate) fn dab_params(app: &PhotocraftApp, tool: Tool) -> Option<(&'static str, Value)> { let o = &app.ui.tool_options; - Some(match tool { + let (cmd, mut p) = match tool { Tool::Blur => ("paint.blur", json!({"strength": o.strength, "sampleAllLayers": o.sample_all.blur})), Tool::Sharpen => ("paint.sharpen", json!({"strength": o.strength, "protectDetail": o.protect_detail, "sampleAllLayers": o.sample_all.sharpen})), Tool::Smudge => ("paint.smudge", json!({"strength": o.strength, "fingerPainting": o.finger_painting, "sampleAllLayers": o.sample_all.smudge})), @@ -59,7 +61,9 @@ pub(crate) fn dab_params(app: &PhotocraftApp, tool: Tool) -> Option<(&'static st ), Tool::Sponge => ("paint.sponge", json!({"mode": o.sponge_mode, "vibrance": o.vibrance})), _ => return None, - }) + }; + crate::canvas::pattern_wrap(app, &mut p); + Some((cmd, p)) } /// `paint.colorReplacement` params from the options bar (without `points`): shared by the live @@ -67,7 +71,7 @@ pub(crate) fn dab_params(app: &PhotocraftApp, tool: Tool) -> Option<(&'static st /// stroke paints the same colour; Background Swatch sampling matches the background colour. pub(crate) fn color_replacement_params(app: &PhotocraftApp) -> Value { let o = &app.ui.tool_options; - json!({ + let mut p = json!({ "color": app.session.tools.foreground, "mode": o.cr_mode, "sampling": o.cr_sampling, @@ -76,7 +80,9 @@ pub(crate) fn color_replacement_params(app: &PhotocraftApp) -> Value { "antiAlias": o.cr_anti_alias, // A mask or channel target is refused: the tool recolours layer pixels only. "target": crate::canvas::paint_target(app), - }) + }); + crate::canvas::pattern_wrap(app, &mut p); + p } /// `paint.patternStamp` params from the options bar and the Patterns panel (without `points` and @@ -99,6 +105,7 @@ pub(crate) fn pattern_stamp_params(app: &PhotocraftApp, points: &[[f64; 3]]) -> 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); } + crate::canvas::pattern_wrap(app, &mut p); p } @@ -158,6 +165,10 @@ pub fn finish_stroke(app: &mut PhotocraftApp, tool: Tool, points: &[[f64; 3]], m _ => return false, }; p["points"] = pts; + // Spot Healing, Mixer Brush and History Brush; the others' params have it already. + if tool != Tool::Remove { + crate::canvas::pattern_wrap(app, &mut p); + } // The layer mask, an alpha channel or the Quick Mask when targeted, as the Brush paints. p["target"] = crate::canvas::paint_target(app); let result = app.run(cmd, p); @@ -730,6 +741,43 @@ mod tests { } } + #[test] + fn every_retouching_stroke_wraps_in_pattern_preview() { + // View › Pattern Preview (#8883): a stroke across the right edge asks its command to go + // on at the opposite one, and only then. + let tools = [ + (Tool::Blur, "paint.blur"), + (Tool::Sharpen, "paint.sharpen"), + (Tool::Smudge, "paint.smudge"), + (Tool::Dodge, "paint.dodge"), + (Tool::Burn, "paint.burn"), + (Tool::Sponge, "paint.sponge"), + (Tool::MixerBrush, "paint.mixerBrush"), + (Tool::ColorReplacement, "paint.colorReplacement"), + (Tool::PatternStamp, "paint.patternStamp"), + (Tool::Healing, "paint.healingBrush"), + (Tool::HistoryBrush, "paint.historyBrush"), + (Tool::SpotHealing, "paint.spotHealing"), + (Tool::BackgroundEraser, "paint.backgroundEraser"), + ]; + for (tool, cmd) in tools { + for pattern_preview in [false, true] { + let mut app = app(); + stripes(&mut app, 8, "pixels"); + app.ui.view.pattern_preview = pattern_preview; + app.ui.clone_source = Some([20.0, 30.0]); + app.ui.tool = tool; + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 86.0, y: 30.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Move { x: 112.0, y: 30.0, pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 112.0, y: 30.0 }, m); + assert!(!app.ui.status_error, "{tool:?}: {}", app.ui.status); + let (_, p) = app.session.journal.iter().rev().find(|(id, _)| id == cmd).cloned().unwrap_or_else(|| panic!("{tool:?}: no {cmd}")); + assert_eq!(p.get("wrap").and_then(Value::as_bool).unwrap_or(false), pattern_preview, "{tool:?}: {p}"); + } + } + } + #[test] fn clone_stamp_in_pattern_preview_wraps_a_dab_across_the_right_edge() { for pattern_preview in [false, true] { diff --git a/crates/ui-egui/src/stroke_timing_tests.rs b/crates/ui-egui/src/stroke_timing_tests.rs index ac88a6c899..cd50206d7d 100644 --- a/crates/ui-egui/src/stroke_timing_tests.rs +++ b/crates/ui-egui/src/stroke_timing_tests.rs @@ -500,6 +500,60 @@ fn releasing_a_sequential_dab_stroke_commits_what_a_replay_paints() { } } +/// View › Pattern Preview (#8883): a Blur, Smudge or Dodge stroke dragged past the right edge +/// carries on at the left one, and the release still commits the pixels its live stroke drew. +#[test] +fn a_sequential_dab_stroke_past_the_edge_in_pattern_preview_commits_its_live_pixels() { + for (tool, cmd) in [(Tool::Blur, "paint.blur"), (Tool::Smudge, "paint.smudge"), (Tool::Dodge, "paint.dodge")] { + let setup = |run: &mut dyn FnMut(&str, Value)| { + run("tools.setBrush", json!({"brush": {"size": 24, "hardness": 0.2}})); + run("paint.stroke", json!({"points": [[0, 50], [200, 50]], "size": 30, "hardness": 0.5, "color": "#c04020"})); + run("paint.stroke", json!({"points": [[0, 35], [200, 65]], "size": 8, "hardness": 1.0, "color": "#2060c0"})); + }; + let mut h = harness(); + setup(&mut |id, p| { + h.state_mut().run(id, p).unwrap(); + }); + let before = h.state().session.active().unwrap().doc.clone(); + { + let app = h.state_mut(); + app.ui.tool = tool; + app.ui.view.pattern_preview = true; + app.ui.views[0].zoom = 2.0; + app.ui.views[0].center = [100.0, 50.0]; + } + h.run_steps(1); + move_to(&mut h, 150.0, 50.0); + button(&mut h, 150.0, 50.0, true); + for (x, y) in [(175.0, 52.0), (200.0, 50.0), (225.0, 47.0), (245.0, 50.0)] { + move_to(&mut h, x, y); + } + assert!(h.state().live_stroke.is_some(), "{cmd}: a live stroke"); + h.state_mut().retouch_from_live = false; + button(&mut h, 245.0, 50.0, false); + h.run_steps(2); + let app = h.state(); + assert!(app.retouch_from_live, "{cmd}: the release took the live pixels instead of rendering the stroke again"); + let (_, p) = app.session.journal.iter().rev().find(|(id, _)| id == cmd).cloned().expect("a committed stroke"); + assert_eq!(p["wrap"], json!(true), "{cmd}: {p}"); + let mut fresh = photocraft_engine::Session::new(); + fresh.execute("file.new", json!({"width": 200, "height": 100, "background": "white"})).unwrap(); + setup(&mut |id, p| { + fresh.execute(id, p).unwrap(); + }); + fresh.execute(cmd, p).unwrap(); + let st = app.session.active().unwrap(); + let (a, b, pre) = ( + photocraft_compose::render(&st.doc, st.doc.bounds()), + photocraft_compose::render(&fresh.active().unwrap().doc, st.doc.bounds()), + photocraft_compose::render(&before, st.doc.bounds()), + ); + assert!(a.px.iter().zip(&b.px).all(|(x, y)| x == y), "{cmd}: live commit and replay differ"); + let left = |buf: &photocraft_compose::Buffer| (30..70).flat_map(|y| (0..30).map(move |x| (x, y))).map(|(x, y)| buf.px[y * 200 + x]).collect::>(); + assert_ne!(left(&a), left(&pre), "{cmd}: the stroke came back at the left edge"); + } +} + /// Pressure changes Smudge's painted footprint, but not the square of colour it carries. /// Exercise the actual pen → live preview → release handoff → journal replay, then undo/redo. #[test] From 26c218f722746e174b8fabe8e0eea4dfce6a64f0 Mon Sep 17 00:00:00 2001 From: VoiceLessQ Date: Sun, 25 Oct 2026 11:36:15 -0200 Subject: [PATCH 2/6] retouch: wrapped Dodge and Burn tone each pixel once; Spot Healing skips a window with nothing to heal from Dodge and Burn remember each pixel's coverage so one stroke tones it once. With wrap on, that memory was keyed by the unwrapped position. A stroke longer than the canvas came back to a pixel under a new key and toned it again from its toned value: mid grey went to 0.816 instead of 0.651 under Dodge at 60%. Coverage is now kept per canvas pixel. A dab bigger than the canvas is folded first, and each pixel takes the most coverage any of its copies gets (the copy WorkTiles keeps). Spot Healing returns early when the stroke covers its whole sampling window, as a wrapped dab bigger than the canvas does. The fill had nothing to sample from. It left the pixels alone but reported the whole canvas as damage. Wrap off, Dodge in bench_live_dab_release (6000x4000, 8-bit, medians of 4 interleaved runs) stays within 0.8% of before at every brush size. --- crates/engine/src/retouch_cmds.rs | 75 +++++++++++++++++++------ crates/engine/src/retouch_cmds/tests.rs | 45 +++++++++++++++ 2 files changed, 102 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/retouch_cmds.rs b/crates/engine/src/retouch_cmds.rs index 4480f9b8b8..b2eb58059f 100644 --- a/crates/engine/src/retouch_cmds.rs +++ b/crates/engine/src/retouch_cmds.rs @@ -16,7 +16,7 @@ use photocraft_color::{BlendMode, PixelFormat, SampleType}; use photocraft_doc::{Document, LayerContent, LayerId}; use photocraft_geom::Rect; use photocraft_paint::retouch::{Footprint, Region, Smudge, WorkTiles, alpha_index, apply_coverage, apply_dab_stroke_wrapped}; -use photocraft_paint::wrap::wrap_coord; +use photocraft_paint::wrap::{fits, fold_area, pieces, wrap_coord}; use photocraft_paint::{BrushSettings, Stroke, StrokePoint}; use photocraft_raster::{Surface, from_rgba_into, to_rgba}; use rayon::prelude::*; @@ -875,7 +875,8 @@ fn spot_heal_surface( } } let hole: Vec = stroke_cov.iter().map(|c| *c > 0.0).collect(); - if !hole.iter().any(|h| *h) { + // Nothing to heal, or (a wrapped dab covering its whole window) nothing to heal from. + if !hole.iter().any(|h| *h) || hole.iter().all(|h| *h) { return Ok(Rect::EMPTY); } // Synthesise over a slightly larger domain than the Poisson region, so the solve's boundary pixels @@ -971,8 +972,9 @@ fn color_dab(fmt: &PixelFormat, work: &mut Region, fp: &Footprint, strength: f32 /// stroke's coverage there (`toned` is the full-exposure colour). Dabs build up coverage as in a /// brush stroke, capped at full coverage, so Exposure caps a stroke the way Opacity caps a paint /// stroke: overlapping dabs and passes within one stroke don't compound the tone curve, and a -/// new stroke builds on the last. -fn tone_stroke(fmt: PixelFormat, toned: impl Fn([f32; 3]) -> [f32; 3] + 'static) -> DabEffect { +/// new stroke builds on the last. Wrapped around `wrap` (View › Pattern Preview), the coverage is +/// kept per canvas pixel, so a stroke coming back to a pixel one canvas away tones it once. +fn tone_stroke(fmt: PixelFormat, wrap: Option, toned: impl Fn([f32; 3]) -> [f32; 3] + 'static) -> DabEffect { /// Side of the cells that remember, per touched pixel, the coverage applied so far and the /// original pixel (copied from the working pixels the first time a dab reaches it). Dense /// cells rather than a map per pixel: a map lookup per covered pixel made long strokes with @@ -985,11 +987,8 @@ fn tone_stroke(fmt: PixelFormat, toned: impl Fn([f32; 3]) -> [f32; 3] + 'static) let mut cells: std::collections::HashMap<(i32, i32), Cell> = std::collections::HashMap::new(); let a = alpha_index(&fmt); let n = fmt.channels(); - Box::new(move |work, fp| { - let r = fp.rect.intersect(&work.rect); - if r.is_empty() { - return; - } + // Tone the pixels of `px` at `r` moved by `(dx, dy)`, remembered at `r`. + let mut tone = move |px: &mut Region, fp: &Footprint, r: Rect, (dx, dy): (i32, i32)| { let mut enc = [0.0f32; 8]; for cy in r.y0.div_euclid(CELL)..=(r.y1 - 1).div_euclid(CELL) { for cx in r.x0.div_euclid(CELL)..=(r.x1 - 1).div_euclid(CELL) { @@ -1003,7 +1002,7 @@ fn tone_stroke(fmt: PixelFormat, toned: impl Fn([f32; 3]) -> [f32; 3] + 'static) let cell = cells.entry((cx, cy)).or_insert_with(|| Cell { cov: vec![-1.0; len], orig: vec![0.0; len * n] }); for y in part.y0..part.y1 { for x in part.x0..part.x1 { - let k = fp.at(x, y).clamp(0.0, 1.0); + let k = fp.at(x + dx, y + dy).clamp(0.0, 1.0); if k <= 0.0 { continue; } @@ -1011,7 +1010,7 @@ fn tone_stroke(fmt: PixelFormat, toned: impl Fn([f32; 3]) -> [f32; 3] + 'static) let (Some(prev), Some(src)) = (cell.cov.get_mut(i), cell.orig.get_mut(i * n..i * n + n)) else { continue }; if *prev < 0.0 { // First touch: the working pixel is still the original. - src.copy_from_slice(work.px(x, y)); + src.copy_from_slice(px.px(x + dx, y + dy)); *prev = 0.0; } // Dabs build up the stroke's coverage as a brush stroke's do (flow), up @@ -1025,16 +1024,55 @@ fn tone_stroke(fmt: PixelFormat, toned: impl Fn([f32; 3]) -> [f32; 3] + 'static) let t = toned([o[0], o[1], o[2]]); let m = [o[0] + (t[0] - o[0]) * k, o[1] + (t[1] - o[1]) * k, o[2] + (t[2] - o[2]) * k]; from_rgba_into(&fmt, [m[0], m[1], m[2], o[3]], &mut enc); - let px = work.px_mut(x, y); + let out = px.px_mut(x + dx, y + dy); for c in 0..n { if Some(c) != a { - px[c] = enc[c]; + out[c] = enc[c]; } } } } } } + }; + Box::new(move |work, fp| { + let r = fp.rect.intersect(&work.rect); + if r.is_empty() { + return; + } + match wrap { + None => tone(work, fp, r, (0, 0)), + Some(tile) if fits(r, tile) => { + for (part, off) in pieces(r, tile) { + tone(work, fp, part, off); + } + } + // A dab bigger than the canvas covers its pixels more than once: tone each at the + // most coverage any copy gets (the copy `WorkTiles` keeps), and give every copy that. + Some(tile) => { + let area = fold_area(r, tile); + let mut on = Region::new(area, work.ch); + let mut most = Footprint { dab: fp.dab, index: fp.index, rect: area, cov: vec![0.0; area.width() as usize * area.height() as usize] }; + let at = |x, y| (wrap_coord(x, tile.x0, tile.x1), wrap_coord(y, tile.y0, tile.y1)); + for y in r.y0..r.y1 { + for x in r.x0..r.x1 { + let (tx, ty) = at(x, y); + let i = on.index(tx, ty); + on.px_mut(tx, ty).copy_from_slice(work.px(x, y)); + if let Some(m) = most.cov.get_mut(i) { + *m = m.max(fp.at(x, y)); + } + } + } + tone(&mut on, &most, area, (0, 0)); + for y in r.y0..r.y1 { + for x in r.x0..r.x1 { + let (tx, ty) = at(x, y); + work.px_mut(x, y).copy_from_slice(on.px(tx, ty)); + } + } + } + } }) } @@ -1140,11 +1178,12 @@ impl DabTool { } } - /// The per-dab effect on a working copy in `fmt`, for a brush of `spacing`. - fn effect(&self, fmt: PixelFormat, spacing: f32) -> DabEffect { + /// The per-dab effect on a working copy in `fmt`, for a brush of `spacing`, on a stroke + /// wrapped around `wrap`. + fn effect(&self, fmt: PixelFormat, spacing: f32, wrap: Option) -> DabEffect { let sp = spacing; match self.clone() { - Self::Tone { burn, range, exposure, protect } => tone_stroke(fmt, move |c| dodge_burn(c, exposure, range, burn, protect)), + Self::Tone { burn, range, exposure, protect } => tone_stroke(fmt, wrap, move |c| dodge_burn(c, exposure, range, burn, protect)), // Flow is already in each dab's coverage; a full-flow pass moves colours half-way. Self::Sponge { saturate, vibrance } => Box::new(move |work, fp| color_dab(&fmt, work, fp, 0.5, sp, |c, k| sponge(c, k, saturate, vibrance))), Self::Focus { sharpen, strength, protect, sigma } => { @@ -1206,8 +1245,8 @@ fn dab_cmd(s: &mut Session, p: &Value, cmd: &str) -> Result { return Ok(l.bounds); } let fmt = surf.format(); - let mut effect = tool.effect(fmt, stroke.brush.spacing); let (halo, wrap) = (tool.neighborhood().halo(), wrap_tile(pre, p)); + let mut effect = tool.effect(fmt, stroke.brush.spacing, wrap); let mut sampler = all.then(|| AllLayers::new(pre, fmt).wrapped(wrap, &stroke, halo)); Ok(apply_dab_stroke_wrapped(surf, &stroke, sel, lock, halo, wrap, |work, fp| match &mut sampler { Some(all) => all.dab(work, fp, |w, f| effect(w, f)), @@ -1274,7 +1313,7 @@ impl LiveDab { let (tool, _) = DabTool::parse(s, cmd, p, &stroke)?; let (neighborhood, spacing, brush) = (tool.neighborhood(), stroke.brush.spacing, Box::new(stroke.brush.clone())); let effect = tool.clone(); - let mut live = Self::with_neighborhood(s, cmd, p, stroke, id, neighborhood, |pre, _| effect.effect(pre.format(), spacing))?; + let mut live = Self::with_neighborhood(s, cmd, p, stroke, id, neighborhood, |pre, wrap| effect.effect(pre.format(), spacing, wrap))?; live.tool = Some((tool, brush)); Ok(live) } diff --git a/crates/engine/src/retouch_cmds/tests.rs b/crates/engine/src/retouch_cmds/tests.rs index e88129cb67..cbe535097b 100644 --- a/crates/engine/src/retouch_cmds/tests.rs +++ b/crates/engine/src/retouch_cmds/tests.rs @@ -2603,6 +2603,51 @@ fn a_wrapped_dab_bigger_than_the_canvas_stays_on_it() { } } +#[test] +fn spot_healing_with_nothing_left_to_sample_leaves_the_layer_alone() { + // Wrapped, the dab covers all of a canvas smaller than it, so its window has no pixel left + // to heal from. + for depth in DEPTHS { + for kind in ["contentAware", "createTexture", "proximityMatch"] { + let mut s = session(48, 36, depth, "rgb"); + textured(&mut s); + let before = layer_pixels(&s); + let r = s.execute("paint.spotHealing", json!({"points": [[48, 36]], "size": 64, "hardness": 100, "type": kind, "wrap": true})).unwrap(); + assert_eq!(layer_pixels(&s), before, "{kind} at {depth}-bit"); + assert_eq!(r["damage"][2].as_i64().unwrap() * r["damage"][3].as_i64().unwrap(), 0, "{kind} at {depth}-bit: no damage, got {}", r["damage"]); + } + } +} + +#[test] +fn a_wrapped_dodge_or_burn_stroke_tones_each_pixel_once() { + // A stroke round the canvas, or a dab bigger than it, comes back to pixels one canvas away; + // the stroke still tones each of them once, as a single dab does. + for depth in DEPTHS { + for cmd in ["paint.dodge", "paint.burn"] { + let run = |w: u32, h: u32, mut p: Value| { + let mut s = session(w, h, depth, "rgb"); + paint_layer(&mut s, |_, _| [0.5, 0.5, 0.5, 1.0]); + p["exposure"] = json!(60); + s.execute(cmd, p).unwrap(); + layer_pixels(&s) + }; + let once = run(WRAP.0, WRAP.1, json!({"points": [[24, 18]], "size": 10, "hardness": 100})); + let n = once.len() / (WRAP.0 * WRAP.1) as usize; + let toned = &once[(18 * WRAP.0 as usize + 24) * n..][..n]; + assert_ne!(toned, &once[..n], "{cmd} at {depth}-bit: the dab tones"); + let round = run(WRAP.0, WRAP.1, json!({"points": [[2, 18], [122, 18]], "size": 10, "hardness": 100, "wrap": true})); + for x in 0..WRAP.0 as usize { + assert_eq!(&round[(18 * WRAP.0 as usize + x) * n..][..n], toned, "{cmd} at {depth}-bit: ({x}, 18)"); + } + let big = run(16, 12, json!({"points": [[8, 6], [30, 20]], "size": 60, "hardness": 100, "wrap": true})); + for (i, px) in big.chunks(n).enumerate() { + assert_eq!(px, toned, "{cmd} at {depth}-bit: pixel {i} under the big dab"); + } + } + } +} + #[test] fn wrapped_live_strokes_show_what_their_commits_paint() { // Across the left and bottom edges, as the canvas draws them: Dodge … Smudge commit the From ea4ec7b80e7a0627b66ba824d75d29e5d65b5beb Mon Sep 17 00:00:00 2001 From: VoiceLessQ Date: Wed, 28 Oct 2026 18:04:57 -0200 Subject: [PATCH 3/6] retouch: a wrapped stroke over its work budget names its own command periodic::Composite said paint.cloneStamp for every tool; Healing Brush, History Brush and Pattern Stamp now go through it too. The command is passed in, and the live stroke passes its own. --- crates/engine/src/cmd/retouch_cmds/clone.rs | 3 ++- crates/engine/src/cmd/retouch_cmds/heal.rs | 4 ++-- .../src/cmd/retouch_cmds/pattern_stamp.rs | 2 +- crates/engine/src/cmd/retouch_cmds/periodic.rs | 8 ++++++-- crates/engine/src/cmd/retouch_cmds/tests.rs | 18 ++++++++++++++++++ 5 files changed, 29 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/retouch_cmds/clone.rs b/crates/engine/src/cmd/retouch_cmds/clone.rs index e0643d9fec..41f168244f 100644 --- a/crates/engine/src/cmd/retouch_cmds/clone.rs +++ b/crates/engine/src/cmd/retouch_cmds/clone.rs @@ -136,7 +136,7 @@ pub(super) fn clone_stamp(s: &mut Session, p: &Value) -> Result { return Ok(l.bounds); } if flag(p, "wrap", false) { - return periodic::stroke(pre, surf, &stroke, sel, lock, mode, |before, r| clone_sample(pre, id, before, which, r, &map, true, CMD)); + return periodic::stroke(pre, surf, &stroke, sel, lock, mode, CMD, |before, r| clone_sample(pre, id, before, which, r, &map, true, CMD)); } let (bounds, cov) = coverage(CMD, &stroke)?; // Samples come from the pre-stroke state, so pixels painted earlier in the stroke are never re-cloned. @@ -349,6 +349,7 @@ impl LiveRetouch { selection: self.sel.as_ref(), lock: self.lock, mode: self.mode, + cmd: live_cmd, } .draw(dirty, &self.brush, &self.points, paint) } diff --git a/crates/engine/src/cmd/retouch_cmds/heal.rs b/crates/engine/src/cmd/retouch_cmds/heal.rs index 791f65fc62..c68789e2c3 100644 --- a/crates/engine/src/cmd/retouch_cmds/heal.rs +++ b/crates/engine/src/cmd/retouch_cmds/heal.rs @@ -73,7 +73,7 @@ pub(super) fn healing_brush(s: &mut Session, p: &Value) -> Result { let mask: Vec = cov.iter().map(|c| *c > 0.0).collect(); let healed = heal_region(&fmt, &src, &dst, &mask); if wrap { - return periodic::stroke(pre, surf, &stroke, sel, lock, mode, |_, r| { + return periodic::stroke(pre, surf, &stroke, sel, lock, mode, CMD, |_, r| { let part = healed.crop(r); if part.rect == r { Ok(part) } else { Err(bad(CMD, "the healed patch does not cover the stroke")) } }); @@ -114,7 +114,7 @@ pub(super) fn history_brush(s: &mut Session, p: &Value) -> Result { let src = if src_surface.format() == fmt { src_surface } else { src_surface.convert(fmt) }; if flag(p, "wrap", false) { // Pattern Preview: the history state repeats with the canvas, as the stroke does. - return periodic::stroke(pre, surf, &stroke, sel, lock, mode, |_, r| periodic::sample(pre, id, &src, SampleLayers::Current, r, CMD)); + return periodic::stroke(pre, surf, &stroke, sel, lock, mode, CMD, |_, r| periodic::sample(pre, id, &src, SampleLayers::Current, r, CMD)); } let (bounds, cov) = coverage(CMD, &stroke)?; let paint = Region::read(&src, bounds); diff --git a/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs b/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs index 7ccb293d4f..021e02a08a 100644 --- a/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs +++ b/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs @@ -97,7 +97,7 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result { Ok(apply_dab_stroke_wrapped(surf, &st.stroke, sel, lock, 0, wrap, effect)) } else if wrap.is_some() { let (place, fmt) = (st.placement(), surf.format()); - periodic::stroke(&pre, surf, &st.stroke, sel, lock, st.mode, |_, r| Ok(paint_region(&st.tile, &place, &fmt, r))) + periodic::stroke(&pre, surf, &st.stroke, sel, lock, st.mode, CMD, |_, r| Ok(paint_region(&st.tile, &place, &fmt, r))) } else { paint_aligned(surf, &st.stroke, sel, lock, &st.tile, st.placement(), st.mode, CMD) } diff --git a/crates/engine/src/cmd/retouch_cmds/periodic.rs b/crates/engine/src/cmd/retouch_cmds/periodic.rs index 57527e1629..63c3b40f07 100644 --- a/crates/engine/src/cmd/retouch_cmds/periodic.rs +++ b/crates/engine/src/cmd/retouch_cmds/periodic.rs @@ -26,6 +26,7 @@ pub(super) fn project(rect: Rect, tile: Rect) -> Vec { /// A composite tool's stroke wrapped around the document: `paint` gives the pixels for a /// rectangle in the stroke's own coordinates, from the target as it was before the stroke, and /// they go on through the stroke's coverage wherever it repeats on the document. +#[allow(clippy::too_many_arguments)] pub(super) fn stroke( pre: &Document, target: &mut Surface, @@ -33,6 +34,7 @@ pub(super) fn stroke( selection: Option<&Surface>, lock: bool, mode: BlendMode, + cmd: &str, mut paint: impl FnMut(&Surface, Rect) -> Result, ) -> Result { let mut renderer = photocraft_paint::StrokeRenderer::new(&stroke.brush, None, 1.0); @@ -40,7 +42,7 @@ pub(super) fn stroke( renderer.finish(); let before = target.clone(); let bounds = renderer.bounds(); - Composite { target, before: &before, tile: pre.bounds(), opacity: stroke.brush.opacity, selection, lock, mode }.draw( + Composite { target, before: &before, tile: pre.bounds(), opacity: stroke.brush.opacity, selection, lock, mode, cmd }.draw( bounds, &stroke.brush, &stroke.points, @@ -59,6 +61,8 @@ pub(super) struct Composite<'a> { pub selection: Option<&'a Surface>, pub lock: bool, pub mode: BlendMode, + /// The command an over-budget stroke's error names. + pub cmd: &'a str, } impl Composite<'_> { @@ -163,7 +167,7 @@ impl Composite<'_> { ); *work = work.saturating_add(r.width() as u64 * r.height() as u64); if *work > 64 * 1024 * 1024 { - return Err(bad("paint.cloneStamp", "wrapped stroke exceeds its coverage budget")); + return Err(bad(self.cmd, "wrapped stroke exceeds its coverage budget")); } ctx.rasterize_into(dab, dual, r, &mut values, wet.then_some(&mut depths)); let mut sampled = None; diff --git a/crates/engine/src/cmd/retouch_cmds/tests.rs b/crates/engine/src/cmd/retouch_cmds/tests.rs index fe2ea3beab..eb031a1a1f 100644 --- a/crates/engine/src/cmd/retouch_cmds/tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/tests.rs @@ -2766,3 +2766,21 @@ fn wrapped_live_retouch_strokes_show_what_their_commits_paint() { } } } + +#[test] +fn a_wrapped_composite_stroke_over_its_work_budget_names_its_own_command() { + // Big, tightly spaced dabs pass the stroke footprint check but not the wrapped-work budget. + for (cmd, extra, setup) in [ + ("paint.historyBrush", json!({"state": 1}), textured_in_history as Setup), + ("paint.patternStamp", json!({"pattern": "Checkerboard"}), textured as Setup), + ] { + let mut s = session(WRAP.0, WRAP.1, 8, "rgb"); + setup(&mut s); + let mut p = json!({"points": [[0, 0], [700, 0]], "size": 1000, "hardness": 100, "spacing": 1, "wrap": true}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + let err = s.execute(cmd, p).unwrap_err().to_string(); + assert!(err.contains(cmd) && err.contains("coverage budget"), "{cmd}: {err}"); + } +} From 854f6ec9009317dcfd61ddcb9c82e9bcc0464e13 Mon Sep 17 00:00:00 2001 From: VoiceLessQ Date: Mon, 2 Nov 2026 00:40:54 -0200 Subject: [PATCH 4/6] retouch tests: a wrapped stroke has to change the pixels it covers The corner check passed on the pre-stroke texture, and the oversized-dab check passed on a no-op. Spot Healing stays excepted in the second one: it has nothing left to sample there. --- crates/engine/src/cmd/retouch_cmds/tests.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/retouch_cmds/tests.rs b/crates/engine/src/cmd/retouch_cmds/tests.rs index 38fb98fdf3..6946df3ff3 100644 --- a/crates/engine/src/cmd/retouch_cmds/tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/tests.rs @@ -2699,8 +2699,9 @@ fn spot_healing_across_the_canvas_corner_heals_every_copy_of_the_stroke_and_noth let after = layer_pixels(&s); let n = after.len() / (WRAP.0 * WRAP.1) as usize; let px = |v: &[f32], x: usize, y: usize| v[(y * WRAP.0 as usize + x) * n..][..n].to_vec(); - for (x, y) in [(1, 1), (46, 1), (1, 34), (46, 34)] { - assert!(px(&after, x, y)[0] > 0.1, "{kind}: ({x}, {y}) healed: {:?}", px(&after, x, y)); + assert!(px(&after, 1, 1)[0] > 0.1, "{kind}: the blemish healed: {:?}", px(&after, 1, 1)); + for (x, y) in [(46, 1), (1, 34), (46, 34)] { + assert_ne!(px(&after, x, y), px(&before, x, y), "{kind}: ({x}, {y}) is under the stroke"); } for (x, y) in [(24, 18), (10, 18), (24, 4), (38, 28)] { assert_eq!(px(&after, x, y), px(&before, x, y), "{kind}: ({x}, {y}) is far from the stroke"); @@ -2715,6 +2716,7 @@ fn a_wrapped_dab_bigger_than_the_canvas_stays_on_it() { for (cmd, extra, setup, _) in cases { let mut s = session(16, 12, 8, "rgb"); setup(&mut s); + let before = layer_pixels(&s); let mut p = json!({"points": [[8, 6], [30, 20]], "size": 60, "hardness": 0, "wrap": true}); for (k, v) in extra.as_object().unwrap() { p[k] = v.clone(); @@ -2725,6 +2727,10 @@ fn a_wrapped_dab_bigger_than_the_canvas_stays_on_it() { let st = s.active().unwrap(); let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); assert!([(-1, 5), (16, 5), (5, -1), (5, 12), (40, 30)].iter().all(|&(x, y)| surf.rgba(x, y)[3] == 0.0), "{cmd}: nothing lands off the canvas"); + // Spot Healing has nothing left to sample here (the next test). + if cmd != "paint.spotHealing" { + assert!(layer_pixels(&s) != before, "{cmd} {extra}: the stroke changed the canvas"); + } } } From a7568b70b747786e027f3133b17434c18e01beed Mon Sep 17 00:00:00 2001 From: VoiceLessQ Date: Mon, 2 Nov 2026 01:27:12 -0200 Subject: [PATCH 5/6] retouch tests: a wrapped corner has to heal as well as change --- crates/engine/src/cmd/retouch_cmds/tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/engine/src/cmd/retouch_cmds/tests.rs b/crates/engine/src/cmd/retouch_cmds/tests.rs index 6946df3ff3..ede2cb9348 100644 --- a/crates/engine/src/cmd/retouch_cmds/tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/tests.rs @@ -2701,6 +2701,7 @@ fn spot_healing_across_the_canvas_corner_heals_every_copy_of_the_stroke_and_noth let px = |v: &[f32], x: usize, y: usize| v[(y * WRAP.0 as usize + x) * n..][..n].to_vec(); assert!(px(&after, 1, 1)[0] > 0.1, "{kind}: the blemish healed: {:?}", px(&after, 1, 1)); for (x, y) in [(46, 1), (1, 34), (46, 34)] { + assert!(px(&after, x, y)[0] > 0.1, "{kind}: ({x}, {y}) healed: {:?}", px(&after, x, y)); assert_ne!(px(&after, x, y), px(&before, x, y), "{kind}: ({x}, {y}) is under the stroke"); } for (x, y) in [(24, 18), (10, 18), (24, 4), (38, 28)] { From d4f27c60fa449688be2ae59744f01c01058c2b54 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 7 Nov 2026 20:40:29 +0100 Subject: [PATCH 6/6] #9348: only Clone Stamp and Healing Brush wrap in Pattern Preview Measured in the reference application: in View > Pattern Preview the Clone Stamp and Healing Brush carry a stroke on across the canvas edges. Blur, Sharpen, Smudge, Dodge, Burn, Sponge, Color Replacement, Background Eraser, Pattern Stamp and History Brush show "Symmetry and Pattern Preview are not supported with this tool ... does not perform wrap-around" and stop at the edge; Spot Healing stops at the edge too. Keep the Healing Brush wrap (commit and live preview, through periodic::stroke) and drop the wrap from the other tools: their commands, WorkTiles' wrap tile, photocraft_paint::wrap and the canvas params go back to main's code. Tests: the tiling checks stay for Clone Stamp and Healing Brush; new tests check that the other tools' strokes, live and committed, stop at the edge and that the canvas sends `wrap` only for the two tools that wrap. Co-Authored-By: VoiceLessQ <44067308+VoiceLessQ@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/brush_cmds.rs | 13 +- crates/engine/src/cmd/eraser_cmds.rs | 31 +- crates/engine/src/cmd/retouch_cmds.rs | 39 +-- crates/engine/src/cmd/retouch_cmds/clone.rs | 21 +- crates/engine/src/cmd/retouch_cmds/dab.rs | 209 ++++++------ crates/engine/src/cmd/retouch_cmds/heal.rs | 78 +---- .../src/cmd/retouch_cmds/pattern_stamp.rs | 14 +- .../engine/src/cmd/retouch_cmds/sampling.rs | 49 +-- crates/engine/src/cmd/retouch_cmds/tests.rs | 312 ++++-------------- crates/paint/src/bg_erase.rs | 19 +- crates/paint/src/lib.rs | 4 +- crates/paint/src/replace.rs | 42 +-- crates/paint/src/retouch.rs | 264 --------------- crates/paint/src/wrap.rs | 166 ---------- crates/ui-egui/src/canvas.rs | 4 +- crates/ui-egui/src/canvas/strokes.rs | 8 - crates/ui-egui/src/stroke_timing_tests.rs | 54 --- crates/ui-egui/src/tools/eraser_ui.rs | 6 +- crates/ui-egui/src/tools/retouch_ui.rs | 23 +- crates/ui-egui/src/tools/retouch_ui/tests.rs | 36 +- 20 files changed, 287 insertions(+), 1105 deletions(-) delete mode 100644 crates/paint/src/wrap.rs diff --git a/crates/engine/src/cmd/brush_cmds.rs b/crates/engine/src/cmd/brush_cmds.rs index 9142cbf6ff..e09ff2098c 100644 --- a/crates/engine/src/cmd/brush_cmds.rs +++ b/crates/engine/src/cmd/brush_cmds.rs @@ -9,7 +9,7 @@ use photocraft_doc::LayerContent; use photocraft_geom::Rect; use photocraft_paint::mixer::{MixerSettings, MixerState}; -use photocraft_paint::replace::{Limits, ReplaceMode, ReplaceSettings, Sampling, apply_color_replacement_wrapped, color_replacement_effect}; +use photocraft_paint::replace::{Limits, ReplaceMode, ReplaceSettings, Sampling, apply_color_replacement, color_replacement_effect}; use photocraft_paint::tile::PREVIEW_SIDE; use photocraft_paint::{ BrushPreset, BrushSettings, GrayTile, Pattern, PresetCaptures, StoredTile, Stroke, StrokePoint, StrokeRenderer, TipShape, render_stroke, @@ -860,9 +860,8 @@ fn color_replacement(s: &mut Session, p: &Value) -> Result { let dmg = s.edit("Color Replacement", |doc, _| { let sel = doc.selection.clone(); let lock = doc.effective_locks(id).transparency; - let wrap = flag(p, "wrap", false).then(|| doc.bounds()); let surf = paint_surface(doc, id, &json!({}))?; - Ok(apply_color_replacement_wrapped(surf, &stroke, &rs, sel.as_ref(), lock, wrap)) + Ok(apply_color_replacement(surf, &stroke, &rs, sel.as_ref(), lock)) })?; Ok(damage_json(s, dmg)) } @@ -871,10 +870,8 @@ fn color_replacement(s: &mut Session, p: &Value) -> Result { /// recolouring per dab as the commit, so the preview at the last point is the committed result. pub fn live_color_replacement(s: &Session, p: &Value) -> Result { let (stroke, rs, id) = color_replacement_setup(s, p)?; - crate::retouch_cmds::LiveDab::with_effect(s, "paint.colorReplacement", p, stroke, Some(id), 0, |pre, wrap| { - Box::new(color_replacement_effect(pre.clone(), rs, wrap)) - })? - .with_tail_preview() + crate::retouch_cmds::LiveDab::with_effect(s, "paint.colorReplacement", p, stroke, Some(id), 0, |pre| Box::new(color_replacement_effect(pre.clone(), rs)))? + .with_tail_preview() } fn brush_json(b: &BrushSettings) -> Value { @@ -1339,7 +1336,7 @@ pub fn specs() -> Vec { spec!( "paint.colorReplacement", "Color Replacement", - r##"{"points":[…],"brush":{…}?,"size":px?,"mode":"hue|saturation|color|luminosity"="color","sampling":"continuous|once|backgroundSwatch"="continuous","limits":"contiguous|discontiguous|findEdges"="contiguous","tolerance":0..100=30,"antiAlias":bool=true,"color":"#rrggbb"?=foreground,"target":"pixels"="pixels","seed":u64?,"wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges)}"##, + r##"{"points":[…],"brush":{…}?,"size":px?,"mode":"hue|saturation|color|luminosity"="color","sampling":"continuous|once|backgroundSwatch"="continuous","limits":"contiguous|discontiguous|findEdges"="contiguous","tolerance":0..100=30,"antiAlias":bool=true,"color":"#rrggbb"?=foreground,"target":"pixels"="pixels","seed":u64?}"##, crate::commands::has_paintable, color_replacement, true diff --git a/crates/engine/src/cmd/eraser_cmds.rs b/crates/engine/src/cmd/eraser_cmds.rs index d33f1afae0..1433498078 100644 --- a/crates/engine/src/cmd/eraser_cmds.rs +++ b/crates/engine/src/cmd/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_wrapped, background_eraser_effect, background_eraser_stroke}; +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}; @@ -165,18 +165,16 @@ fn background_eraser(s: &mut Session, p: &Value) -> Result { let bg = s.tools.background; let dmg = s.edit("Background Eraser", |doc, _| { let selection = doc.selection.clone(); - // View › Pattern Preview: the stroke carries on across the canvas edges. - let wrap = flag(p, "wrap", false).then(|| doc.bounds()); if colors.is_none() { crate::extra_cmds::background_to_layer(doc, id); } let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; let surf = l.surface_mut().ok_or_else(|| bad(CMD, "not a pixel layer"))?; if let Some(colors) = colors { - let effect = selected_background_effect(surf, &bs, colors, bg, wrap); - Ok(photocraft_paint::retouch::apply_dab_stroke_wrapped(surf, &background_eraser_stroke(&stroke), selection.as_ref(), false, 0, wrap, effect)) + let effect = selected_background_effect(surf, &bs, colors, bg); + Ok(photocraft_paint::retouch::apply_dab_stroke(surf, &background_eraser_stroke(&stroke), selection.as_ref(), false, 0, effect)) } else { - Ok(apply_background_eraser_wrapped(surf, &stroke, &bs, selection.as_ref(), wrap)) + Ok(apply_background_eraser(surf, &stroke, &bs, selection.as_ref())) } })?; Ok(damage(s, dmg, true)) @@ -187,7 +185,6 @@ fn selected_background_effect( bs: &BgEraseSettings, colors: crate::color_channels::ColorChannels, bg: [f32; 4], - wrap: Option, ) -> crate::retouch_cmds::DabEffect { let fmt = pre.format(); let alpha = fmt.mode.color_channels(); @@ -195,7 +192,7 @@ fn selected_background_effect( // Opaque Backgrounds have no alpha sample. The matching algorithm uses a temporary opaque // alpha to calculate erased coverage; the real layer keeps its original format and identity. let opaque = pre.convert(photocraft_color::PixelFormat::new(fmt.mode, fmt.sample, true)); - let Some(mut effect) = background_eraser_effect(&opaque, bs, wrap) else { + let Some(mut effect) = background_eraser_effect(&opaque, bs) else { return Box::new(|_, _| {}); }; Box::new(move |region, footprint| { @@ -238,20 +235,16 @@ pub fn live_background_eraser(s: &Session, p: &Value) -> Result Box::new(effect), - // No alpha: the commit erases nothing either. - None => Box::new(|_: &mut photocraft_paint::retouch::Region, _: &photocraft_paint::retouch::Footprint| {}), - } + crate::retouch_cmds::LiveDab::with_effect_on(doc, CMD, &json!({}), stroke, Some(id), 0, |pre| match background_eraser_effect(pre, &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() } @@ -274,7 +267,7 @@ pub fn specs() -> Vec { label: "Background Eraser", menu: &[], shortcut: None, - params: r##"{"points":[[x,y,pressure?],…],"size":px?,"hardness":0..1?,"brush":{…}?,"preset":name?,"sampling":"continuous|once|backgroundSwatch"="continuous","limits":"discontiguous|contiguous|findEdges"="contiguous","tolerance":0..100=50,"protectForegroundColor":bool=false,"seed":u64?,"wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges)}"##, + params: r##"{"points":[[x,y,pressure?],…],"size":px?,"hardness":0..1?,"brush":{…}?,"preset":name?,"sampling":"continuous|once|backgroundSwatch"="continuous","limits":"discontiguous|contiguous|findEdges"="contiguous","tolerance":0..100=50,"protectForegroundColor":bool=false,"seed":u64?}"##, enabled: has_pixel_layer, run: background_eraser, journal: true, diff --git a/crates/engine/src/cmd/retouch_cmds.rs b/crates/engine/src/cmd/retouch_cmds.rs index e6cc4eb3d4..bf05a7e879 100644 --- a/crates/engine/src/cmd/retouch_cmds.rs +++ b/crates/engine/src/cmd/retouch_cmds.rs @@ -16,8 +16,7 @@ use photocraft_algo::retouch::{ToneRange, dodge_burn, local_blur, local_sharpen, use photocraft_color::{BlendMode, PixelFormat, SampleType}; use photocraft_doc::{Document, LayerContent, LayerId}; use photocraft_geom::Rect; -use photocraft_paint::retouch::{Footprint, Region, Smudge, WorkTiles, alpha_index, apply_coverage, apply_dab_stroke_wrapped}; -use photocraft_paint::wrap::wrap_coord; +use photocraft_paint::retouch::{Footprint, Region, Smudge, alpha_index, apply_coverage, apply_dab_stroke}; use photocraft_paint::{BrushSettings, Stroke, StrokePoint}; use photocraft_raster::{Surface, from_rgba_into, to_rgba}; use rayon::prelude::*; @@ -123,10 +122,6 @@ fn num(p: &Value, k: &str, d: f32) -> f32 { fn flag(p: &Value, k: &str, d: bool) -> bool { p.get(k).and_then(Value::as_bool).unwrap_or(d) } -/// The canvas a stroke with `"wrap": true` repeats across (View › Pattern Preview). -fn wrap_tile(pre: &Document, p: &Value) -> Option { - flag(p, "wrap", false).then(|| pre.bounds()).filter(|t| !t.is_empty()) -} fn string<'a>(p: &'a Value, k: &str, d: &'a str) -> &'a str { p.get(k).and_then(Value::as_str).unwrap_or(d) } @@ -253,7 +248,7 @@ pub fn specs() -> Vec { 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]?,"wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges) → {"damage","phase","aligned","pattern"}"# + 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, @@ -276,9 +271,7 @@ pub fn specs() -> Vec { label: "Spot Healing Brush", menu: &[], shortcut: None, - params: brush_params!( - r#","type":"contentAware|createTexture|proximityMatch"="contentAware","sampleAllLayers":bool=false,"wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges)"# - ), + params: brush_params!(r#","type":"contentAware|createTexture|proximityMatch"="contentAware","sampleAllLayers":bool=false"#), enabled: has_pixel_layer, run: spot_healing, journal: true, @@ -320,9 +313,7 @@ pub fn specs() -> Vec { label: "Dodge", menu: &[], shortcut: None, - params: brush_params!( - r#","range":"shadows|midtones|highlights"="midtones","exposure":1..100=50,"protectTones":bool=true,"wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges)"# - ), + params: brush_params!(r#","range":"shadows|midtones|highlights"="midtones","exposure":1..100=50,"protectTones":bool=true"#), enabled: has_pixel_layer, run: |s, p| dab_cmd(s, p, "paint.dodge"), journal: true, @@ -332,9 +323,7 @@ pub fn specs() -> Vec { label: "Burn", menu: &[], shortcut: None, - params: brush_params!( - r#","range":"shadows|midtones|highlights"="midtones","exposure":1..100=50,"protectTones":bool=true,"wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges)"# - ), + params: brush_params!(r#","range":"shadows|midtones|highlights"="midtones","exposure":1..100=50,"protectTones":bool=true"#), enabled: has_pixel_layer, run: |s, p| dab_cmd(s, p, "paint.burn"), journal: true, @@ -344,9 +333,7 @@ pub fn specs() -> Vec { label: "Sponge", menu: &[], shortcut: None, - params: brush_params!( - r#","mode":"desaturate|saturate"="desaturate","vibrance":bool=true (flow = sponge strength),"wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges)"# - ), + params: brush_params!(r#","mode":"desaturate|saturate"="desaturate","vibrance":bool=true (flow = sponge strength)"#), enabled: has_pixel_layer, run: |s, p| dab_cmd(s, p, "paint.sponge"), journal: true, @@ -356,9 +343,7 @@ pub fn specs() -> Vec { label: "Blur", menu: &[], shortcut: None, - params: brush_params!( - r#","strength":1..100=50,"sampleAllLayers":bool=false,"wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges)"# - ), + params: brush_params!(r#","strength":1..100=50,"sampleAllLayers":bool=false"#), enabled: has_pixel_layer, run: |s, p| dab_cmd(s, p, "paint.blur"), journal: true, @@ -368,9 +353,7 @@ pub fn specs() -> Vec { label: "Sharpen", menu: &[], shortcut: None, - params: brush_params!( - r#","strength":1..100=50,"protectDetail":bool=true,"sampleAllLayers":bool=false,"wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges)"# - ), + params: brush_params!(r#","strength":1..100=50,"protectDetail":bool=true,"sampleAllLayers":bool=false"#), enabled: has_pixel_layer, run: |s, p| dab_cmd(s, p, "paint.sharpen"), journal: true, @@ -380,9 +363,7 @@ pub fn specs() -> Vec { label: "Smudge", menu: &[], shortcut: None, - params: brush_params!( - r#","strength":1..100=50,"fingerPainting":bool=false (starts with the foreground colour),"sampleAllLayers":bool=false,"wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges)"# - ), + params: brush_params!(r#","strength":1..100=50,"fingerPainting":bool=false (starts with the foreground colour),"sampleAllLayers":bool=false"#), enabled: has_pixel_layer, run: |s, p| dab_cmd(s, p, "paint.smudge"), journal: true, @@ -393,7 +374,7 @@ pub fn specs() -> Vec { menu: &[], shortcut: None, params: brush_params!( - r#","state":row (a History panel row, as history.setSource: 0 = oldest state, then the current one, then the greyed redo states),"snapshot":id (a history.newSnapshot id; default: the History panel's source, else the oldest held state; a source of another canvas size is an error),"wrap":bool=false (View › Pattern Preview: the stroke goes on across the canvas edges)"# + r#","state":row (a History panel row, as history.setSource: 0 = oldest state, then the current one, then the greyed redo states),"snapshot":id (a history.newSnapshot id; default: the History panel's source, else the oldest held state; a source of another canvas size is an error)"# ), enabled: has_pixel_layer, run: history_brush, diff --git a/crates/engine/src/cmd/retouch_cmds/clone.rs b/crates/engine/src/cmd/retouch_cmds/clone.rs index 9e79894a44..66cf276332 100644 --- a/crates/engine/src/cmd/retouch_cmds/clone.rs +++ b/crates/engine/src/cmd/retouch_cmds/clone.rs @@ -265,7 +265,14 @@ impl LiveRetouch { /// Everything the stroke has touched so far. pub fn bounds(&self) -> Rect { let bounds = self.renderer.bounds().union(&self.tail); - if flag(&self.params, "wrap", false) { periodic::project(bounds, self.pre.bounds()).into_iter().fold(Rect::EMPTY, |a, b| a.union(&b)) } else { bounds } + if self.wraps() { periodic::project(bounds, self.pre.bounds()).into_iter().fold(Rect::EMPTY, |a, b| a.union(&b)) } else { bounds } + } + + /// Whether the stroke repeats across the canvas edges (View › Pattern Preview). Only the Clone + /// Stamp and the Healing Brush do: the reference application's other retouching tools stop + /// at the edge. + fn wraps(&self) -> bool { + matches!(self.cmd.as_str(), "paint.cloneStamp" | "paint.healingBrush") && flag(&self.params, "wrap", false) } /// Every point rendered so far, in order. @@ -317,7 +324,7 @@ impl LiveRetouch { let pts: Vec<_> = pts.iter().map(|q| StrokePoint::new(q.x, q.y, q.pressure)).collect(); self.points.extend_from_slice(&pts); self.renderer.push(&pts); - if flag(&self.params, "wrap", false) { + if self.wraps() { return self.push_periodic(); } let old = std::mem::replace(&mut self.tail, Rect::EMPTY); @@ -346,13 +353,11 @@ impl LiveRetouch { let mut tail = self.renderer.tail_preview(); self.tail = tail.as_mut().map_or(Rect::EMPTY, |t| t.take_dirty_rect()); dirty = dirty.union(&self.tail); - let (pre, id, pre_surf, live_paint, live_cmd) = (&self.pre, self.id, &self.pre_surf, &self.paint, self.cmd.as_str()); - let fmt = pre_surf.format(); - let paint = |r| match live_paint { - LivePaint::Clone { which, map, cmd } => clone_sample(pre, id, pre_surf, *which, r, map, true, cmd), - LivePaint::History(src) => periodic::sample(pre, id, src, SampleLayers::Current, r, live_cmd), - LivePaint::Pattern { tile, place } => Ok(pattern_stamp::paint_region(tile, place, &fmt, r)), + let LivePaint::Clone { which, map, cmd } = &self.paint else { + return Err(bad(&self.cmd, "periodic painting requires a clone source")); }; + let (pre, id, pre_surf, live_cmd) = (&self.pre, self.id, &self.pre_surf, self.cmd.as_str()); + let paint = |r| clone_sample(pre, id, pre_surf, *which, r, map, true, cmd); let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?; periodic::Composite { target: surf, diff --git a/crates/engine/src/cmd/retouch_cmds/dab.rs b/crates/engine/src/cmd/retouch_cmds/dab.rs index 597a1a5d74..e51ac10021 100644 --- a/crates/engine/src/cmd/retouch_cmds/dab.rs +++ b/crates/engine/src/cmd/retouch_cmds/dab.rs @@ -1,10 +1,9 @@ use super::sampling::{AllLayers, sample_all_layers}; use super::{ BrushSettings, Document, EngineError, Footprint, IndexedParallelIterator, LayerId, ParallelIterator, ParallelSliceMut, PixelFormat, Rect, Region, Result, - Session, Smudge, Stroke, StrokePoint, Surface, ToneRange, Value, WorkTiles, alpha_index, apply_dab_stroke_wrapped, bad, damage_json, dodge_burn, flag, - from_rgba_into, has_pixel_layer, json, local_blur, local_sharpen, num, parse_brush, run_stroke, sponge, string, to_rgba, wrap_tile, + Session, Smudge, Stroke, StrokePoint, Surface, ToneRange, Value, alpha_index, apply_dab_stroke, bad, damage_json, dodge_burn, flag, from_rgba_into, + has_pixel_layer, json, local_blur, local_sharpen, num, parse_brush, run_stroke, sponge, string, to_rgba, }; -use photocraft_paint::wrap::{fits, fold_area, pieces, wrap_coord}; // --------------------------------------------------------------------------------------------- // Toning (Dodge / Burn / Sponge) and focus (Blur / Sharpen), Smudge @@ -47,9 +46,8 @@ fn color_dab(fmt: &PixelFormat, work: &mut Region, fp: &Footprint, strength: f32 /// stroke's coverage there (`toned` is the full-exposure colour). Dabs build up coverage as in a /// brush stroke, capped at full coverage, so Exposure caps a stroke the way Opacity caps a paint /// stroke: overlapping dabs and passes within one stroke don't compound the tone curve, and a -/// new stroke builds on the last. Wrapped around `wrap` (View › Pattern Preview), the coverage is -/// kept per canvas pixel, so a stroke coming back to a pixel one canvas away tones it once. -fn tone_stroke(fmt: PixelFormat, wrap: Option, toned: impl Fn([f32; 3]) -> [f32; 3] + 'static) -> DabEffect { +/// new stroke builds on the last. +fn tone_stroke(fmt: PixelFormat, toned: impl Fn([f32; 3]) -> [f32; 3] + 'static) -> DabEffect { /// Side of the cells that remember, per touched pixel, the coverage applied so far and the /// original pixel (copied from the working pixels the first time a dab reaches it). Dense /// cells rather than a map per pixel: a map lookup per covered pixel made long strokes with @@ -62,8 +60,11 @@ fn tone_stroke(fmt: PixelFormat, wrap: Option, toned: impl Fn([f32; 3]) -> let mut cells: std::collections::HashMap<(i32, i32), Cell> = std::collections::HashMap::new(); let a = alpha_index(&fmt); let n = fmt.channels(); - // Tone the pixels of `px` at `r` moved by `(dx, dy)`, remembered at `r`. - let mut tone = move |px: &mut Region, fp: &Footprint, r: Rect, (dx, dy): (i32, i32)| { + Box::new(move |work, fp| { + let r = fp.rect.intersect(&work.rect); + if r.is_empty() { + return; + } let mut enc = [0.0f32; 8]; for cy in r.y0.div_euclid(CELL)..=(r.y1 - 1).div_euclid(CELL) { for cx in r.x0.div_euclid(CELL)..=(r.x1 - 1).div_euclid(CELL) { @@ -77,7 +78,7 @@ fn tone_stroke(fmt: PixelFormat, wrap: Option, toned: impl Fn([f32; 3]) -> let cell = cells.entry((cx, cy)).or_insert_with(|| Cell { cov: vec![-1.0; len], orig: vec![0.0; len * n] }); for y in part.y0..part.y1 { for x in part.x0..part.x1 { - let k = fp.at(x + dx, y + dy).clamp(0.0, 1.0); + let k = fp.at(x, y).clamp(0.0, 1.0); if k <= 0.0 { continue; } @@ -85,7 +86,7 @@ fn tone_stroke(fmt: PixelFormat, wrap: Option, toned: impl Fn([f32; 3]) -> let (Some(prev), Some(src)) = (cell.cov.get_mut(i), cell.orig.get_mut(i * n..i * n + n)) else { continue }; if *prev < 0.0 { // First touch: the working pixel is still the original. - src.copy_from_slice(px.px(x + dx, y + dy)); + src.copy_from_slice(work.px(x, y)); *prev = 0.0; } // Dabs build up the stroke's coverage as a brush stroke's do (flow), up @@ -99,55 +100,16 @@ fn tone_stroke(fmt: PixelFormat, wrap: Option, toned: impl Fn([f32; 3]) -> let t = toned([o[0], o[1], o[2]]); let m = [o[0] + (t[0] - o[0]) * k, o[1] + (t[1] - o[1]) * k, o[2] + (t[2] - o[2]) * k]; from_rgba_into(&fmt, [m[0], m[1], m[2], o[3]], &mut enc); - let out = px.px_mut(x + dx, y + dy); + let px = work.px_mut(x, y); for c in 0..n { if Some(c) != a { - out[c] = enc[c]; + px[c] = enc[c]; } } } } } } - }; - Box::new(move |work, fp| { - let r = fp.rect.intersect(&work.rect); - if r.is_empty() { - return; - } - match wrap { - None => tone(work, fp, r, (0, 0)), - Some(tile) if fits(r, tile) => { - for (part, off) in pieces(r, tile) { - tone(work, fp, part, off); - } - } - // A dab bigger than the canvas covers its pixels more than once: tone each at the - // most coverage any copy gets (the copy `WorkTiles` keeps), and give every copy that. - Some(tile) => { - let area = fold_area(r, tile); - let mut on = Region::new(area, work.ch); - let mut most = Footprint { dab: fp.dab, index: fp.index, rect: area, cov: vec![0.0; area.width() as usize * area.height() as usize] }; - let at = |x, y| (wrap_coord(x, tile.x0, tile.x1), wrap_coord(y, tile.y0, tile.y1)); - for y in r.y0..r.y1 { - for x in r.x0..r.x1 { - let (tx, ty) = at(x, y); - let i = on.index(tx, ty); - on.px_mut(tx, ty).copy_from_slice(work.px(x, y)); - if let Some(m) = most.cov.get_mut(i) { - *m = m.max(fp.at(x, y)); - } - } - } - tone(&mut on, &most, area, (0, 0)); - for y in r.y0..r.y1 { - for x in r.x0..r.x1 { - let (tx, ty) = at(x, y); - work.px_mut(x, y).copy_from_slice(on.px(tx, ty)); - } - } - } - } }) } @@ -253,12 +215,11 @@ impl DabTool { } } - /// The per-dab effect on a working copy in `fmt`, for a brush of `spacing`, on a stroke - /// wrapped around `wrap`. - pub(super) fn effect(&self, fmt: PixelFormat, spacing: f32, wrap: Option) -> DabEffect { + /// The per-dab effect on a working copy in `fmt`, for a brush of `spacing`. + pub(super) fn effect(&self, fmt: PixelFormat, spacing: f32) -> DabEffect { let sp = spacing; match self.clone() { - Self::Tone { burn, range, exposure, protect } => tone_stroke(fmt, wrap, move |c| dodge_burn(c, exposure, range, burn, protect)), + Self::Tone { burn, range, exposure, protect } => tone_stroke(fmt, move |c| dodge_burn(c, exposure, range, burn, protect)), // Flow is already in each dab's coverage; a full-flow pass moves colours half-way. Self::Sponge { saturate, vibrance } => Box::new(move |work, fp| color_dab(&fmt, work, fp, 0.5, sp, |c, k| sponge(c, k, saturate, vibrance))), Self::Focus { sharpen, strength, protect, sigma } => { @@ -320,10 +281,9 @@ pub(super) fn dab_cmd(s: &mut Session, p: &Value, cmd: &str) -> Result { return Ok(l.bounds); } let fmt = surf.format(); - let (halo, wrap) = (tool.neighborhood().halo(), wrap_tile(pre, p)); - let mut effect = tool.effect(fmt, stroke.brush.spacing, wrap); - let mut sampler = all.then(|| AllLayers::new(pre, fmt).wrapped(wrap, &stroke, halo)); - Ok(apply_dab_stroke_wrapped(surf, &stroke, sel, lock, halo, wrap, |work, fp| match &mut sampler { + let mut effect = tool.effect(fmt, stroke.brush.spacing); + let mut sampler = all.then(|| AllLayers::new(pre, fmt)); + Ok(apply_dab_stroke(surf, &stroke, sel, lock, tool.neighborhood().halo(), |work, fp| match &mut sampler { Some(all) => all.dab(work, fp, |w, f| effect(w, f)), None => effect(work, fp), })) @@ -335,6 +295,81 @@ pub(super) fn dab_cmd(s: &mut Session, p: &Value, cmd: &str) -> Result { Ok(r) } +/// Side of the tiles a live sequential-dab stroke keeps its working pixels in ([`WorkTiles`]). +const WORK_TILE: i32 = 128; + +/// The working copy of a live sequential-dab stroke: the target's native channels as `f32`, in +/// tiles copied from the pre-stroke surface the first time a dab writes to them. Unlike a +/// `Surface`, it isn't rounded to the document's depth between dabs, so each dab sees what the +/// commit's working copy (`apply_dab_stroke`) holds and the preview is the commit's pixels. +struct WorkTiles { + ch: usize, + tiles: std::collections::HashMap<(i32, i32), Vec>, +} + +impl WorkTiles { + fn new(ch: usize) -> Self { + Self { ch, tiles: std::collections::HashMap::new() } + } + + fn tile_rect((tx, ty): (i32, i32)) -> Rect { + Rect::new(tx * WORK_TILE, ty * WORK_TILE, tx * WORK_TILE + WORK_TILE, ty * WORK_TILE + WORK_TILE) + } + + /// The tiles `r` overlaps. + fn coords(r: Rect) -> impl Iterator { + let (x0, x1) = (r.x0.div_euclid(WORK_TILE), (r.x1 - 1).div_euclid(WORK_TILE)); + let (y0, y1) = (r.y0.div_euclid(WORK_TILE), (r.y1 - 1).div_euclid(WORK_TILE)); + let empty = r.is_empty(); + (y0..=y1).filter(move |_| !empty).flat_map(move |ty| (x0..=x1).map(move |tx| (tx, ty))) + } + + /// The working pixels of `r`: the pre-stroke pixels `pre` where no dab has written yet. + fn read(&self, pre: &Surface, r: Rect) -> Region { + let mut out = Region::new(r, self.ch); + let n = self.ch; + let mut buf = Vec::new(); + for c in Self::coords(r) { + let tr = Self::tile_rect(c); + let part = r.intersect(&tr); + let w = part.width() as usize * n; + let tile = self.tiles.get(&c); + if tile.is_none() { + pre.read_region_into(part, &mut buf); + } + for y in part.y0..part.y1 { + let src = match tile { + Some(t) => t.get(((y - tr.y0) * WORK_TILE + (part.x0 - tr.x0)) as usize * n..).and_then(|s| s.get(..w)), + None => buf.get((y - part.y0) as usize * w..).and_then(|s| s.get(..w)), + }; + let dst = out.index(part.x0, y) * n; + if let (Some(s), Some(d)) = (src, out.data.get_mut(dst..dst + w)) { + d.copy_from_slice(s); + } + } + } + out + } + + /// Store `region` as the working pixels of its rectangle. + fn write(&mut self, pre: &Surface, region: &Region) { + let (r, n) = (region.rect, self.ch); + for c in Self::coords(r) { + let tr = Self::tile_rect(c); + let tile = self.tiles.entry(c).or_insert_with(|| pre.read_region(tr)); + let part = r.intersect(&tr); + let w = part.width() as usize * n; + for y in part.y0..part.y1 { + let dst = ((y - tr.y0) * WORK_TILE + (part.x0 - tr.x0)) as usize * n; + let src = region.index(part.x0, y) * n; + if let (Some(s), Some(d)) = (region.data.get(src..src + w), tile.get_mut(dst..dst + w)) { + d.copy_from_slice(s); + } + } + } + } +} + /// 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. @@ -362,8 +397,6 @@ pub struct LiveDab { sel: Option, lock: bool, bounds: Rect, - /// The canvas a wrapped stroke repeats across (View › Pattern Preview, `"wrap": true`). - wrap: Option, /// Show the dabs finishing the stroke would add, so the preview at the last point is the /// commit. Only for effects that a repeated dab doesn't change (Color Replacement): the /// tail runs on a scratch copy at every push, so an effect that carries paint from dab to @@ -393,14 +426,13 @@ impl LiveDab { let (tool, _) = DabTool::parse(s, cmd, p, &stroke)?; let (neighborhood, spacing, brush) = (tool.neighborhood(), stroke.brush.spacing, Box::new(stroke.brush.clone())); let effect = tool.clone(); - let mut live = Self::with_neighborhood(s, cmd, p, stroke, id, neighborhood, |pre, wrap| effect.effect(pre.format(), spacing, wrap))?; + let mut live = Self::with_neighborhood(s, cmd, p, stroke, id, neighborhood, |pre| effect.effect(pre.format(), spacing))?; live.tool = Some((tool, brush)); Ok(live) } - /// Start a live stroke of `cmd` that runs `effect` (made from the target before the stroke - /// and the canvas a wrapped stroke repeats across) at each dab of `stroke`, reading `halo` - /// pixels around it. `p` gives the target and `wrap`. + /// Start a live stroke of `cmd` that runs `effect` (made from the target before the stroke) + /// at each dab of `stroke`, reading `halo` pixels around it. `p` gives the target. pub(crate) fn with_effect( s: &Session, cmd: &str, @@ -408,7 +440,7 @@ impl LiveDab { stroke: Stroke, id: Option, halo: i32, - effect: impl FnOnce(&Surface, Option) -> DabEffect, + effect: impl FnOnce(&Surface) -> DabEffect, ) -> Result { Self::with_neighborhood(s, cmd, p, stroke, id, DabNeighborhood::Halo(halo), effect) } @@ -420,7 +452,7 @@ impl LiveDab { stroke: Stroke, id: Option, neighborhood: DabNeighborhood, - effect: impl FnOnce(&Surface, Option) -> DabEffect, + effect: impl FnOnce(&Surface) -> DabEffect, ) -> Result { let captured = crate::channel_cmds::inject_target(s, cmd, p.clone()); let p = &captured; @@ -446,7 +478,7 @@ impl LiveDab { stroke: Stroke, id: Option, halo: i32, - effect: impl FnOnce(&Surface, Option) -> DabEffect, + effect: impl FnOnce(&Surface) -> DabEffect, ) -> Result { Self::with_neighborhood_on(doc, cmd, p, stroke, id, DabNeighborhood::Halo(halo), effect) } @@ -458,14 +490,13 @@ impl LiveDab { stroke: Stroke, id: Option, neighborhood: DabNeighborhood, - effect: impl FnOnce(&Surface, Option) -> DabEffect, + effect: impl FnOnce(&Surface) -> DabEffect, ) -> Result { - let wrap = wrap_tile(&doc, p); let colors = crate::color_channels::explicit(p, crate::channel_cmds::color_count(&doc))?; let sel = doc.selection.clone(); let (surf, lock) = crate::channel_cmds::target_surface(&mut doc, id, p)?; let pre_surf = surf.clone(); - let effect = effect(&pre_surf, wrap); + let effect = effect(&pre_surf); // Generate the same dabs as `apply_dab_stroke` (zoom 1), without a StrokeRenderer: // its accumulated coverage isn't used here, and each effect rasterizes its own footprint. let ctx = photocraft_paint::BrushContext::new(&stroke.brush); @@ -480,7 +511,7 @@ impl LiveDab { done: 0, effect, neighborhood, - work: WorkTiles::new(pre_surf.channels()).wrapped(wrap), + work: WorkTiles::new(pre_surf.channels()), pre_surf, colors, id, @@ -489,7 +520,6 @@ impl LiveDab { sel, lock, bounds: Rect::EMPTY, - wrap, preview_tail: false, tail: Rect::EMPTY, tool: None, @@ -525,11 +555,10 @@ impl LiveDab { if r.is_empty() { continue; } - let fp = ctx.footprint(d, self.done.saturating_add(k)); let mut region = self.work.read(&self.pre_surf, self.neighborhood.read_rect(r, d)); - (self.effect)(&mut region, &fp); - self.work.write_dab(&self.pre_surf, ®ion, &fp); - dmg = dmg.union(&self.on_canvas(r)); + (self.effect)(&mut region, &ctx.footprint(d, self.done.saturating_add(k))); + self.work.write(&self.pre_surf, ®ion.crop(r)); + dmg = dmg.union(&r); } self.done = self.done.saturating_add(new.len()); new.clear(); @@ -537,24 +566,6 @@ impl LiveDab { dmg } - /// Where the stroke's rectangle `r` lands on the document: `r`, or in a wrapped stroke the - /// part of the canvas it covers. - fn on_canvas(&self, r: Rect) -> Rect { - self.wrap.map_or(r, |t| photocraft_paint::wrap::fold_area(r, t)) - } - - /// [`Self::show`] working pixels laid out in the stroke's own coordinates: a wrapped stroke - /// shows each part where it lies on the canvas. - fn show_unwrapped(&mut self, work: &Region) -> Result<()> { - let Some(tile) = self.wrap else { return self.show(work.rect, work) }; - for (part, (dx, dy)) in photocraft_paint::wrap::pieces(work.rect, tile) { - let mut piece = work.crop(part.translate(dx, dy)); - piece.rect = part; - self.show(part, &piece)?; - } - Ok(()) - } - /// Mix the working pixels of `r` back over the original into the shown document. fn show(&mut self, r: Rect, work: &Region) -> Result<()> { let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.id, &self.params)?; @@ -599,7 +610,7 @@ impl LiveDab { // Back to the stroke without the previous tail. let old = std::mem::replace(&mut self.tail, Rect::EMPTY); let shown = dmg.union(&old); - let tail_rect = tail.as_ref().map_or(Rect::EMPTY, |(r, _)| self.on_canvas(*r)); + let tail_rect = tail.as_ref().map_or(Rect::EMPTY, |(r, _)| *r); if shown.is_empty() && tail_rect.is_empty() { return Ok(Rect::EMPTY); } @@ -608,9 +619,9 @@ impl LiveDab { let work = self.work.read(&self.pre_surf, shown); self.show(shown, &work)?; } - if let Some((_, work)) = tail { - self.show_unwrapped(&work)?; - self.tail = tail_rect; + if let Some((r, work)) = tail { + self.show(r, &work)?; + self.tail = r; } Ok(shown.union(&tail_rect)) } diff --git a/crates/engine/src/cmd/retouch_cmds/heal.rs b/crates/engine/src/cmd/retouch_cmds/heal.rs index c68789e2c3..b26decfd69 100644 --- a/crates/engine/src/cmd/retouch_cmds/heal.rs +++ b/crates/engine/src/cmd/retouch_cmds/heal.rs @@ -3,7 +3,7 @@ use super::periodic; use super::sampling::{SampleLayers, composite_region, sample_all_layers, sample_layers}; use super::{ BlendMode, CompleteParams, Document, EngineError, LayerId, PixelFormat, Rect, Region, Result, Session, Stroke, Surface, Value, apply_coverage, bad, - coverage, damage_json, flag, inpaint, json, parse_brush, poisson, reject_huge_stroke, run_stroke, string, wrap_coord, wrap_tile, + coverage, damage_json, flag, inpaint, json, parse_brush, poisson, reject_huge_stroke, run_stroke, string, }; /// Grow a stroke's coverage map by `m` pixels of zero coverage (a Dirichlet boundary for the solve). @@ -105,17 +105,13 @@ pub(super) fn history_brush(s: &mut Session, p: &Value) -> Result { let live = s.live_commit.take().filter(|l| l.matches(s, CMD, p, &stroke.points)); let from_live = live.is_some(); let src_surface = history_source(s, id, p, CMD)?; - let dmg = run_stroke(s, "History Brush", id, p, |pre, surf, sel, lock| { + let dmg = run_stroke(s, "History Brush", id, p, |_, surf, sel, lock| { if let Some(l) = live { *surf = l.surface; return Ok(l.bounds); } let fmt = surf.format(); let src = if src_surface.format() == fmt { src_surface } else { src_surface.convert(fmt) }; - if flag(p, "wrap", false) { - // Pattern Preview: the history state repeats with the canvas, as the stroke does. - return periodic::stroke(pre, surf, &stroke, sel, lock, mode, CMD, |_, r| periodic::sample(pre, id, &src, SampleLayers::Current, r, CMD)); - } let (bounds, cov) = coverage(CMD, &stroke)?; let paint = Region::read(&src, bounds); Ok(apply_coverage(surf, bounds, &cov, stroke.brush.opacity, sel, lock, &paint, mode)) @@ -193,68 +189,28 @@ enum SpotType { /// Photoshop 25.4 (measured): a dab changes exactly the brush's footprint, and Content-Aware takes /// its texture from around it, as Edit › Fill does from its window /// ([`crate::fill_cmds::sampling_window`] of the stroke's bounds), which is what this samples. -/// -/// Wrapped around the canvas `wrap` (View › Pattern Preview), the window is centred on the stroke -/// whatever the canvas edges and at most one canvas across, so it holds no second copy of the -/// stroke; its pixels repeat across the edges, and the healed pixels go where they lie on the -/// canvas. -#[allow(clippy::too_many_arguments)] -fn spot_heal_surface( - surf: &mut Surface, - pre: &Document, - stroke: &Stroke, - kind: SpotType, - all: bool, - sel: Option<&Surface>, - lock: bool, - wrap: Option, -) -> Result { - const CMD: &str = "paint.spotHealing"; - let (bounds, cov) = coverage(CMD, stroke)?; +fn spot_heal_surface(surf: &mut Surface, pre: &Document, stroke: &Stroke, kind: SpotType, all: bool, sel: Option<&Surface>, lock: bool) -> Result { + let (bounds, cov) = coverage("paint.spotHealing", stroke)?; let size = stroke.brush.size; - let region_rect = match wrap { - Some(tile) => { - let (tw, th) = (i64::from(tile.width()), i64::from(tile.height())); - let x0 = (i64::from(bounds.x0) + i64::from(bounds.x1) - tw) / 2; - let y0 = (i64::from(bounds.y0) + i64::from(bounds.y1) - th) / 2; - let around = Rect::new(x0 as i32, y0 as i32, (x0 + tw) as i32, (y0 + th) as i32); - crate::fill_cmds::sampling_window(bounds, around) - } - None => crate::fill_cmds::sampling_window(bounds, pre.bounds()), - }; + let region_rect = crate::fill_cmds::sampling_window(bounds, pre.bounds()); if region_rect.is_empty() { return Ok(Rect::EMPTY); } // Proximity Match looks for its source anywhere in that window. let margin = (region_rect.width().max(region_rect.height()) / 2) as i32; let fmt = surf.format(); - let img = match wrap { - Some(_) => periodic::sample(pre, None, surf, if all { SampleLayers::All } else { SampleLayers::Current }, region_rect, CMD)?, - None if all => composite_region(pre, None, SampleLayers::All, region_rect, fmt), - None => Region::read(surf, region_rect), - }; + let img = if all { composite_region(pre, None, SampleLayers::All, region_rect, fmt) } else { Region::read(surf, region_rect) }; let (w, h, ch) = (img.width(), img.height(), img.ch); let bw = bounds.width() as usize; let mut stroke_cov = vec![0.0f32; w * h]; for (i, c) in cov.iter().enumerate() { let (x, y) = (bounds.x0 + (i % bw) as i32, bounds.y0 + (i / bw) as i32); - // A wrapped stroke longer than the window (one canvas) folds onto it: the strongest - // coverage of each pixel heals it once. - let (x, y) = match wrap { - Some(t) => { - let wrap_into = |v: i32, lo: i32, period: u32| wrap_coord(v, lo, lo.saturating_add(period as i32)); - (wrap_into(x, region_rect.x0, t.width()), wrap_into(y, region_rect.y0, t.height())) - } - None => (x, y), - }; if region_rect.contains(x, y) { - let px = &mut stroke_cov[img.index(x, y)]; - *px = px.max(*c); + stroke_cov[img.index(x, y)] = *c; } } let hole: Vec = stroke_cov.iter().map(|c| *c > 0.0).collect(); - // Nothing to heal, or (a wrapped dab covering its whole window) nothing to heal from. - if !hole.iter().any(|h| *h) || hole.iter().all(|h| *h) { + if !hole.iter().any(|h| *h) { return Ok(Rect::EMPTY); } // Synthesise over a slightly larger domain than the Poisson region, so the solve's boundary pixels @@ -278,19 +234,8 @@ fn spot_heal_surface( let src = Region { rect: region_rect, ch, data: filled }; let healed = heal_region(&fmt, &src, &img, &heal_mask); let dmg = bounds.intersect(®ion_rect); - let cov_of = |r: Rect, (dx, dy): (i32, i32)| -> Vec { - (r.y0..r.y1).flat_map(|y| (r.x0..r.x1).map(move |x| (x, y))).map(|(x, y)| stroke_cov[img.index(x + dx, y + dy)]).collect() - }; - let Some(tile) = wrap else { - return Ok(apply_coverage(surf, dmg, &cov_of(dmg, (0, 0)), stroke.brush.opacity, sel, lock, &healed, BlendMode::Normal)); - }; - let mut done = Rect::EMPTY; - for (part, off) in photocraft_paint::wrap::pieces(dmg, tile) { - let mut paint = healed.crop(part.translate(off.0, off.1)); - paint.rect = part; - done = done.union(&apply_coverage(surf, part, &cov_of(part, off), stroke.brush.opacity, sel, lock, &paint, BlendMode::Normal)); - } - Ok(done) + let dmg_cov: Vec = (dmg.y0..dmg.y1).flat_map(|y| (dmg.x0..dmg.x1).map(move |x| (x, y))).map(|(x, y)| stroke_cov[img.index(x, y)]).collect(); + Ok(apply_coverage(surf, dmg, &dmg_cov, stroke.brush.opacity, sel, lock, &healed, BlendMode::Normal)) } pub(super) fn spot_healing(s: &mut Session, p: &Value) -> Result { @@ -304,7 +249,6 @@ pub(super) fn spot_healing(s: &mut Session, p: &Value) -> Result { o => return Err(bad(CMD, format!("unknown type `{o}` (contentAware|createTexture|proximityMatch)"))), }; let all = sample_all_layers(p); - let dmg = - run_stroke(s, "Spot Healing Brush", id, p, |pre, surf, sel, lock| spot_heal_surface(surf, pre, &stroke, kind, all, sel, lock, wrap_tile(pre, p)))?; + let dmg = run_stroke(s, "Spot Healing Brush", id, p, |pre, surf, sel, lock| spot_heal_surface(surf, pre, &stroke, kind, all, sel, lock))?; Ok(json!({ "damage": damage_json(dmg) })) } diff --git a/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs b/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs index 6b5dae73b5..06b5bd17e7 100644 --- a/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs +++ b/crates/engine/src/cmd/retouch_cmds/pattern_stamp.rs @@ -8,12 +8,12 @@ use photocraft_color::{BlendMode, PixelFormat}; use photocraft_compose::pattern::{Placement, Tile, render}; use photocraft_doc::{LayerId, Pattern}; use photocraft_geom::Rect; -use photocraft_paint::retouch::{Footprint, Region, apply_coverage, apply_dab_stroke_wrapped, over_native}; +use photocraft_paint::retouch::{Footprint, Region, apply_coverage, apply_dab_stroke, over_native}; 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, periodic, reject_huge_stroke, wrap_tile}; +use super::{bad, blend_param, damage_json, flag, has_pixel_layer, parse_brush, reject_huge_stroke}; use crate::{Result, Session}; const STREAM_PHASE_X: u64 = 101; @@ -88,16 +88,10 @@ pub(super) fn run(s: &mut Session, p: &Value) -> Result { let pre = doc.clone(); let (surf, lock) = crate::channel_cmds::target_surface(doc, st.id, p)?; let sel = pre.selection.as_ref(); - // View › Pattern Preview: the stroke carries on across the canvas edges, the pattern - // following it as it goes. - let wrap = wrap_tile(&pre, p); 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_wrapped(surf, &st.stroke, sel, lock, 0, wrap, effect)) - } else if wrap.is_some() { - let (place, fmt) = (st.placement(), surf.format()); - periodic::stroke(&pre, surf, &st.stroke, sel, lock, st.mode, CMD, |_, r| Ok(paint_region(&st.tile, &place, &fmt, r))) + Ok(apply_dab_stroke(surf, &st.stroke, sel, lock, 0, effect)) } else { paint_aligned(surf, &st.stroke, sel, lock, &st.tile, st.placement(), st.mode, CMD) } @@ -123,7 +117,7 @@ pub fn live_impressionist(s: &Session, p: &Value) -> Result { } 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, |pre, _| st.impressionist_effect(pre.format()))?.with_tail_preview() + super::LiveDab::with_effect_on(doc, CMD, p, stroke, id, 0, |pre| st.impressionist_effect(pre.format()))?.with_tail_preview() } /// The pattern under destination `rect` in `fmt` (native channels): what an aligned stroke paints diff --git a/crates/engine/src/cmd/retouch_cmds/sampling.rs b/crates/engine/src/cmd/retouch_cmds/sampling.rs index 8719e931bc..253f6648ad 100644 --- a/crates/engine/src/cmd/retouch_cmds/sampling.rs +++ b/crates/engine/src/cmd/retouch_cmds/sampling.rs @@ -1,7 +1,4 @@ -use super::{ - Document, Footprint, LayerId, PixelFormat, Rect, Region, Result, SampleType, Stroke, Surface, Value, WorkTiles, bad, flag, from_rgba_into, string, - targets_pixels, -}; +use super::{Document, Footprint, LayerId, PixelFormat, Rect, Region, Result, Surface, Value, bad, flag, from_rgba_into, string, targets_pixels}; // --------------------------------------------------------------------------------------------- // Sampling sources @@ -74,56 +71,26 @@ pub(super) struct AllLayers<'a> { pre: &'a Document, fmt: PixelFormat, visible: Option, - /// A stroke wrapped around the canvas (View › Pattern Preview): the composite at full - /// precision under everything the stroke reads, and the dabs' edits of it, kept once per - /// pixel of the canvas as the layer's working pixels are. - wrapped: Option<(Surface, WorkTiles)>, } impl<'a> AllLayers<'a> { pub(super) fn new(pre: &'a Document, fmt: PixelFormat) -> Self { - Self { pre, fmt, visible: None, wrapped: None } - } - - /// Sample for `stroke` wrapped around `wrap`, whose dabs read `halo` pixels around them. - pub(super) fn wrapped(mut self, wrap: Option, stroke: &Stroke, halo: i32) -> Self { - let Some(tile) = wrap else { return self }; - let ctx = photocraft_paint::BrushContext::new(&stroke.brush); - let reach = photocraft_paint::dabs(stroke).iter().fold(Rect::EMPTY, |r, d| r.union(&ctx.dab_rect(d, false))).inflate(halo); - let area = photocraft_paint::wrap::fold_area(reach, tile); - let mut visible = Surface::new(PixelFormat { sample: SampleType::F32, ..self.fmt }); - if !area.is_empty() { - visible.write_region(area, &composite_region(self.pre, None, SampleLayers::All, area, self.fmt).data); - } - self.wrapped = Some((visible, WorkTiles::new(self.fmt.channels()).wrapped(Some(tile)))); - self + Self { pre, fmt, visible: None } } pub(super) fn dab(&mut self, work: &mut Region, fp: &Footprint, effect: impl FnOnce(&mut Region, &Footprint)) { - if let Some((visible, edits)) = self.wrapped.as_mut() { - let mut shown = edits.read(visible, work.rect); - effect(&mut shown, fp); - lay(work, &shown, fp); - edits.write_dab(visible, &shown, fp); - return; - } let (pre, fmt) = (self.pre, self.fmt); let visible = self.visible.get_or_insert_with(|| composite_region(pre, None, SampleLayers::All, work.rect, fmt)); if visible.rect != work.rect || visible.ch != work.ch { return effect(work, fp); } effect(visible, fp); - lay(work, visible, fp); - } -} - -/// Lay what a dab did to the visible pixels onto the layer's working pixels under it. -fn lay(work: &mut Region, visible: &Region, fp: &Footprint) { - let r = fp.rect.intersect(&work.rect); - for y in r.y0..r.y1 { - for x in r.x0..r.x1 { - if fp.at(x, y) > 0.0 { - work.px_mut(x, y).copy_from_slice(visible.px(x, y)); + let r = fp.rect.intersect(&work.rect); + for y in r.y0..r.y1 { + for x in r.x0..r.x1 { + if fp.at(x, y) > 0.0 { + work.px_mut(x, y).copy_from_slice(visible.px(x, y)); + } } } } diff --git a/crates/engine/src/cmd/retouch_cmds/tests.rs b/crates/engine/src/cmd/retouch_cmds/tests.rs index ede2cb9348..b5730f5e34 100644 --- a/crates/engine/src/cmd/retouch_cmds/tests.rs +++ b/crates/engine/src/cmd/retouch_cmds/tests.rs @@ -1912,7 +1912,7 @@ fn live_dab_batches_match_the_accumulating_renderer() { p["flow"] = json!(63); let (stroke, _) = parse_brush(&s, &p, cmd).unwrap(); let (tool, _) = DabTool::parse(&s, cmd, &p, &stroke).unwrap(); - let mut effect = tool.effect(pre.format(), stroke.brush.spacing, None); + let mut effect = tool.effect(pre.format(), stroke.brush.spacing); let mut reference = StrokeRenderer::new(&stroke.brush, None, 1.0).record_dabs(); // A fixed region containing all dabs plus their read neighbourhoods. let orig = Region::read(&pre, Rect::new(-128, -128, 384, 256)); @@ -2534,7 +2534,7 @@ fn periodic_clone_interior_matches_ordinary_brush_masks_and_transparency() { } // --------------------------------------------------------------------------------------------- -// View › Pattern Preview: every retouching stroke wraps across the canvas edges (#8883) +// View › Pattern Preview: Clone Stamp and Healing Brush wrap across the canvas edges (#8883) // --------------------------------------------------------------------------------------------- /// The canvas the Pattern Preview tests wrap around. @@ -2555,48 +2555,11 @@ fn corner_stroke(extra: &Value) -> Value { p } -/// The texture on the layer. -fn textured(s: &mut Session) { - paint_layer(s, tiled_texture); -} - -/// The texture under an empty layer, which is the target (Sample All Layers). -fn textured_below(s: &mut Session) { - paint_layer(s, tiled_texture); - s.execute("layer.new.layer", json!({})).unwrap(); -} - -/// The texture in history state 1, painted over since. -fn textured_in_history(s: &mut Session) { - paint_layer(s, tiled_texture); - paint_layer(s, |_, _| [0.15, 0.2, 0.7, 1.0]); -} - -type Setup = fn(&mut Session); - -/// Every stroke tool that wraps, with options and a document for it. `true` marks the tools -/// that composite a paint image through the stroke's coverage (`periodic::Composite`), which -/// matches the ordinary composite only within rounding. -fn wrap_cases() -> Vec<(&'static str, Value, Setup, bool)> { - vec![ - ("paint.dodge", json!({"exposure": 60}), textured, false), - ("paint.burn", json!({"exposure": 40, "range": "shadows", "protectTones": false}), textured, false), - ("paint.sponge", json!({"mode": "saturate"}), textured, false), - ("paint.blur", json!({"strength": 80}), textured, false), - ("paint.sharpen", json!({"strength": 60}), textured, false), - ("paint.smudge", json!({"strength": 70}), textured, false), - ("paint.blur", json!({"strength": 80, "sampleAllLayers": true}), textured_below, false), - ("paint.smudge", json!({"strength": 70, "sampleAllLayers": true}), textured_below, false), - ("paint.colorReplacement", json!({"color": "#ff8000", "tolerance": 60}), textured, false), - ("paint.backgroundEraser", json!({"tolerance": 40}), textured, false), - ("paint.colorReplacement", json!({"color": "#ff8000", "tolerance": 60, "target": {"colors": [0, 2]}}), textured, false), - ("paint.backgroundEraser", json!({"tolerance": 40, "target": {"colors": [0, 2]}}), textured, false), - ("paint.patternStamp", json!({"pattern": "Bricks", "impressionist": true}), textured, false), - ("paint.patternStamp", json!({"pattern": "Checkerboard"}), textured, true), - ("paint.historyBrush", json!({"state": 1}), textured_in_history, true), - ("paint.healingBrush", json!({"offset": [-20, -14]}), textured, true), - ("paint.cloneStamp", json!({"offset": [-20, -14]}), textured, true), - ] +/// The stroke tools that wrap, with their options. Both composite a paint image through the +/// stroke's coverage (`periodic::Composite`), which matches the ordinary composite only within +/// rounding. +fn wrap_cases() -> [(&'static str, Value); 2] { + [("paint.healingBrush", json!({"offset": [-20, -14]})), ("paint.cloneStamp", json!({"offset": [-20, -14]}))] } /// The native-channel difference `periodic::Composite` may leave against the ordinary composite. @@ -2614,11 +2577,11 @@ fn every_wrapping_stroke_paints_the_canvas_as_on_the_canvas_tiled_three_by_three // copy of that pixel it goes over, on a document holding the canvas tiled three by three. let (w, h) = (WRAP.0 as usize, WRAP.1 as usize); for depth in DEPTHS { - for (cmd, extra, setup, composite) in wrap_cases() { + for (cmd, extra) in wrap_cases() { let mut canvas = session(WRAP.0, WRAP.1, depth, "rgb"); - setup(&mut canvas); + paint_layer(&mut canvas, tiled_texture); let mut tiled = session(3 * WRAP.0, 3 * WRAP.1, depth, "rgb"); - setup(&mut tiled); + paint_layer(&mut tiled, tiled_texture); let (mut wrapped, plain) = (corner_stroke(&extra), corner_stroke(&extra)); wrapped["wrap"] = json!(true); canvas.execute(cmd, wrapped).unwrap_or_else(|e| panic!("{cmd} at {depth}: {e}")); @@ -2627,7 +2590,7 @@ fn every_wrapping_stroke_paints_the_canvas_as_on_the_canvas_tiled_three_by_three let (got, want) = (layer_pixels(&canvas), layer_pixels(&tiled)); let n = got.len() / (w * h); let at = |x: usize, y: usize| (y * 3 * w + x) * n..(y * 3 * w + x + 1) * n; - let tolerance = if composite { composite_tolerance(depth) } else { 0.0 }; + let tolerance = composite_tolerance(depth); let (mut moved, mut edges) = (0, [false; 4]); for y in 0..h { for x in 0..w { @@ -2657,66 +2620,31 @@ fn every_wrapping_stroke_paints_the_canvas_as_on_the_canvas_tiled_three_by_three #[test] fn a_wrapped_stroke_inside_the_canvas_paints_as_an_ordinary_one() { let p = json!({"points": [[130, 110], [150, 118], [168, 112]], "size": 14, "hardness": 60}); - let mut cases: Vec<(&str, Value, Setup, bool)> = wrap_cases(); - cases.push(("paint.spotHealing", json!({"type": "contentAware"}), textured, false)); - cases.push(("paint.spotHealing", json!({"type": "proximityMatch"}), textured, false)); for depth in [8, 32] { - for (cmd, extra, setup, composite) in &cases { + for (cmd, extra) in wrap_cases() { let run = |wrap: bool| { - // Big enough that Spot Healing's window stays clear of the edges either way. let mut s = session(300, 230, depth, "rgb"); - setup(&mut s); + paint_layer(&mut s, tiled_texture); let mut q = p.clone(); for (k, v) in extra.as_object().unwrap() { q[k] = v.clone(); } q["wrap"] = json!(wrap); - let r = s.execute(cmd, q).unwrap(); - (layer_pixels(&s), r["damage"].clone()) + s.execute(cmd, q).unwrap(); + layer_pixels(&s) }; - let ((plain, d0), (wrapped, d1)) = (run(false), run(true)); - let tolerance = if *composite { composite_tolerance(depth) } else { 0.0 }; + let (plain, wrapped) = (run(false), run(true)); let error = plain.iter().zip(&wrapped).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - assert!(error <= tolerance, "{cmd} {extra} at {depth}-bit: off by {error}"); - if !*composite { - assert_eq!(d0, d1, "{cmd} {extra} at {depth}-bit: the same damage"); - } - } - } -} - -#[test] -fn spot_healing_across_the_canvas_corner_heals_every_copy_of_the_stroke_and_nothing_else() { - // The window is centred on the stroke whatever the edges and one canvas across, so the - // corner heals from what surrounds it in the copies, the same as when the stroke stays inside. - for kind in ["contentAware", "createTexture", "proximityMatch"] { - let mut s = session(WRAP.0, WRAP.1, 8, "rgb"); - paint_layer(&mut s, |x, y| if (x - 2).abs() < 3 && (y - 2).abs() < 3 { [0.0, 0.0, 0.0, 1.0] } else { tiled_texture(x, y) }); - let before = layer_pixels(&s); - // The dark blemish straddles the corner (0, 0); the stroke is drawn on the copy to its - // lower right, around (48, 36). - s.execute("paint.spotHealing", json!({"points": [[48, 36], [50, 38]], "size": 14, "hardness": 100, "type": kind, "wrap": true})).unwrap(); - let after = layer_pixels(&s); - let n = after.len() / (WRAP.0 * WRAP.1) as usize; - let px = |v: &[f32], x: usize, y: usize| v[(y * WRAP.0 as usize + x) * n..][..n].to_vec(); - assert!(px(&after, 1, 1)[0] > 0.1, "{kind}: the blemish healed: {:?}", px(&after, 1, 1)); - for (x, y) in [(46, 1), (1, 34), (46, 34)] { - assert!(px(&after, x, y)[0] > 0.1, "{kind}: ({x}, {y}) healed: {:?}", px(&after, x, y)); - assert_ne!(px(&after, x, y), px(&before, x, y), "{kind}: ({x}, {y}) is under the stroke"); - } - for (x, y) in [(24, 18), (10, 18), (24, 4), (38, 28)] { - assert_eq!(px(&after, x, y), px(&before, x, y), "{kind}: ({x}, {y}) is far from the stroke"); + assert!(error <= composite_tolerance(depth), "{cmd} {extra} at {depth}-bit: off by {error}"); } } } #[test] fn a_wrapped_dab_bigger_than_the_canvas_stays_on_it() { - let mut cases = wrap_cases(); - cases.push(("paint.spotHealing", json!({"type": "contentAware"}), textured, false)); - for (cmd, extra, setup, _) in cases { + for (cmd, extra) in wrap_cases() { let mut s = session(16, 12, 8, "rgb"); - setup(&mut s); + paint_layer(&mut s, tiled_texture); let before = layer_pixels(&s); let mut p = json!({"points": [[8, 6], [30, 20]], "size": 60, "hardness": 0, "wrap": true}); for (k, v) in extra.as_object().unwrap() { @@ -2728,168 +2656,68 @@ fn a_wrapped_dab_bigger_than_the_canvas_stays_on_it() { let st = s.active().unwrap(); let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap(); assert!([(-1, 5), (16, 5), (5, -1), (5, 12), (40, 30)].iter().all(|&(x, y)| surf.rgba(x, y)[3] == 0.0), "{cmd}: nothing lands off the canvas"); - // Spot Healing has nothing left to sample here (the next test). - if cmd != "paint.spotHealing" { - assert!(layer_pixels(&s) != before, "{cmd} {extra}: the stroke changed the canvas"); - } + assert!(layer_pixels(&s) != before, "{cmd} {extra}: the stroke changed the canvas"); } } #[test] -fn spot_healing_with_nothing_left_to_sample_leaves_the_layer_alone() { - // Wrapped, the dab covers all of a canvas smaller than it, so its window has no pixel left - // to heal from. - for depth in DEPTHS { - for kind in ["contentAware", "createTexture", "proximityMatch"] { - let mut s = session(48, 36, depth, "rgb"); - textured(&mut s); +fn the_tools_the_reference_application_does_not_wrap_stop_at_the_canvas_edge() { + // Measured in the reference application: in Pattern Preview the Clone Stamp and Healing + // Brush carry a stroke on across the canvas edges, but Blur … Sponge, Color Replacement, + // Background Eraser, Pattern Stamp and History Brush warn that they don't wrap, and Spot + // Healing stops at the edge too. Their `wrap` stroke over the corner paints as the same + // stroke without it. + let points = [[36.0, 24.0], [58.0, 39.0]]; + let cases = [ + ("paint.blur", json!({"strength": 80})), + ("paint.sharpen", json!({"strength": 60})), + ("paint.smudge", json!({"strength": 70})), + ("paint.dodge", json!({"exposure": 60})), + ("paint.burn", json!({"exposure": 40})), + ("paint.sponge", json!({"mode": "saturate"})), + ("paint.colorReplacement", json!({"color": "#ff8000", "tolerance": 60})), + ("paint.backgroundEraser", json!({"tolerance": 40})), + ("paint.patternStamp", json!({"pattern": "Checkerboard"})), + ("paint.patternStamp", json!({"pattern": "Bricks", "impressionist": true, "seed": 7})), + ("paint.historyBrush", json!({"state": 1})), + ("paint.spotHealing", json!({"type": "contentAware"})), + ]; + for (cmd, extra) in cases { + let run = |wrap: bool| { + let mut s = session(WRAP.0, WRAP.1, 8, "rgb"); + paint_layer(&mut s, tiled_texture); + // Painted over since history state 1, so the History Brush has something to bring back. + paint_layer(&mut s, |x, y| tiled_texture(x + 7, y + 5)); + let mut p = dab_opts(&points, 100, &extra); + p["size"] = json!(12); + p["wrap"] = json!(wrap); let before = layer_pixels(&s); - let r = s.execute("paint.spotHealing", json!({"points": [[48, 36]], "size": 64, "hardness": 100, "type": kind, "wrap": true})).unwrap(); - assert_eq!(layer_pixels(&s), before, "{kind} at {depth}-bit"); - assert_eq!(r["damage"][2].as_i64().unwrap() * r["damage"][3].as_i64().unwrap(), 0, "{kind} at {depth}-bit: no damage, got {}", r["damage"]); - } + s.execute(cmd, p).unwrap_or_else(|e| panic!("{cmd}: {e}")); + (before, layer_pixels(&s)) + }; + let ((before, plain), (_, wrapped)) = (run(false), run(true)); + assert!(plain != before, "{cmd} {extra}: the stroke paints inside the canvas"); + assert!(wrapped == plain, "{cmd} {extra}: nothing comes back at the opposite edges"); } } #[test] -fn a_wrapped_dodge_or_burn_stroke_tones_each_pixel_once() { - // A stroke round the canvas, or a dab bigger than it, comes back to pixels one canvas away; - // the stroke still tones each of them once, as a single dab does. - for depth in DEPTHS { - for cmd in ["paint.dodge", "paint.burn"] { - let run = |w: u32, h: u32, mut p: Value| { - let mut s = session(w, h, depth, "rgb"); - paint_layer(&mut s, |_, _| [0.5, 0.5, 0.5, 1.0]); - p["exposure"] = json!(60); - s.execute(cmd, p).unwrap(); - layer_pixels(&s) - }; - let once = run(WRAP.0, WRAP.1, json!({"points": [[24, 18]], "size": 10, "hardness": 100})); - let n = once.len() / (WRAP.0 * WRAP.1) as usize; - let toned = &once[(18 * WRAP.0 as usize + 24) * n..][..n]; - assert_ne!(toned, &once[..n], "{cmd} at {depth}-bit: the dab tones"); - let round = run(WRAP.0, WRAP.1, json!({"points": [[2, 18], [122, 18]], "size": 10, "hardness": 100, "wrap": true})); - for x in 0..WRAP.0 as usize { - assert_eq!(&round[(18 * WRAP.0 as usize + x) * n..][..n], toned, "{cmd} at {depth}-bit: ({x}, 18)"); - } - let big = run(16, 12, json!({"points": [[8, 6], [30, 20]], "size": 60, "hardness": 100, "wrap": true})); - for (i, px) in big.chunks(n).enumerate() { - assert_eq!(px, toned, "{cmd} at {depth}-bit: pixel {i} under the big dab"); - } - } - } -} - -#[test] -fn wrapped_live_strokes_show_what_their_commits_paint() { - // Across the left and bottom edges, as the canvas draws them: Dodge … Smudge commit the - // pixels they drew; the strokes that preview their finishing dabs show their commit's. - let points = [[30.0, 20.0], [10.0, 30.0], [-6.0, 40.0], [-12.0, 34.0]]; - for depth in DEPTHS { - for (cmd, extra) in dab_cases() { - let mut s = session(WRAP.0, WRAP.1, depth, "rgb"); - paint_layer(&mut s, tiled_texture); - let mut extra = extra.clone(); - extra["wrap"] = json!(true); - let rendered = s.execute(cmd, dab_opts(&points, 50, &extra)).unwrap(); - let want = layer_pixels(&s); - s.execute("edit.undo", json!({})).unwrap(); - offer_live(&mut s, cmd, &points, 50, &extra); - let taken = s.execute(cmd, dab_opts(&points, 50, &extra)).unwrap(); - assert_eq!(taken["fromLive"], json!(true), "{cmd} at {depth}-bit"); - assert_eq!(taken["damage"], rendered["damage"], "{cmd} at {depth}-bit"); - assert!(layer_pixels(&s) == want, "{cmd} at {depth}-bit: the live pixels are the command's"); - } - let pts: Vec<_> = points.iter().map(|q| StrokePoint::new(q[0], q[1], 1.0)).collect(); - type Begin = fn(&Session, &Value) -> Result; - let shown: [(&str, Value, Begin); 5] = [ - ("paint.colorReplacement", json!({"color": "#ff8000", "tolerance": 60}), crate::brush_cmds::live_color_replacement), - ("paint.colorReplacement", json!({"color": "#ff8000", "tolerance": 60, "target": {"colors": [0, 2]}}), crate::brush_cmds::live_color_replacement), - ("paint.backgroundEraser", json!({"tolerance": 40}), crate::eraser_cmds::live_background_eraser), - ("paint.backgroundEraser", json!({"tolerance": 40, "target": {"colors": [0, 2]}}), crate::eraser_cmds::live_background_eraser), - // A seed, as the canvas sends: without one the jitter hashes all the points. - ("paint.patternStamp", json!({"pattern": "Bricks", "impressionist": true, "seed": 7}), live_pattern_impressionist), - ]; - for (cmd, extra, begin) in shown { - let mut s = session(WRAP.0, WRAP.1, depth, "rgb"); - paint_layer(&mut s, tiled_texture); - let mut p = dab_opts(&points[..1], 50, &extra); - p["wrap"] = json!(true); - let mut live = begin(&s, &p).unwrap(); - live.push(&pts[1..]).unwrap(); - let shown = live.doc.clone(); - let pre = s.active().unwrap().doc.clone(); - p["points"] = json!(points); - s.execute(cmd, p).unwrap(); - let st = s.active().unwrap(); - let id = st.active_layer.unwrap(); - let (a, b) = (shown.layer(id).unwrap().surface().unwrap(), st.doc.layer(id).unwrap().surface().unwrap()); - let before = pre.layer(id).unwrap().surface().unwrap(); - let worst = (0..WRAP.1 as i32) - .flat_map(|y| (0..WRAP.0 as i32).map(move |x| (x, y))) - .map(|(x, y)| (0..4).map(|c| (a.rgba(x, y)[c] - b.rgba(x, y)[c]).abs()).fold(0.0f32, f32::max)) - .fold(0.0f32, f32::max); - assert!(worst <= 2.0 / 255.0 + 1e-6, "{cmd} at {depth}-bit: live and commit differ by {worst}"); - let right = WRAP.0 as i32 - 3; - assert!((0..WRAP.1 as i32).any(|y| b.rgba(right, y) != before.rgba(right, y)), "{cmd} at {depth}-bit: the stroke came back at the right edge"); - } - } -} - -#[test] -fn wrapped_live_retouch_strokes_show_what_their_commits_paint() { - // History Brush commits the pixels its live stroke drew across the edges; the aligned Pattern - // Stamp's preview is its commit. - let points = [[30.0, 20.0], [10.0, 30.0], [-6.0, 40.0], [-12.0, 34.0]]; +fn live_history_and_pattern_strokes_stop_at_the_canvas_edge() { + // The History Brush and aligned Pattern Stamp previews stop at the edge as their commits do. + let points = [[36.0, 24.0], [58.0, 39.0]]; let pts: Vec<_> = points.iter().map(|q| StrokePoint::new(q[0], q[1], 1.0)).collect(); - for depth in DEPTHS { - for (cmd, extra, setup) in [ - ("paint.historyBrush", json!({"state": 1}), textured_in_history as Setup), - ("paint.patternStamp", json!({"pattern": "Checkerboard"}), textured as Setup), - ] { - let mut s = session(WRAP.0, WRAP.1, depth, "rgb"); - setup(&mut s); - let mut p = dab_opts(&points[..1], 50, &extra); - p["wrap"] = json!(true); + for (cmd, extra) in [("paint.historyBrush", json!({"state": 1})), ("paint.patternStamp", json!({"pattern": "Checkerboard"}))] { + let bounds = |wrap: bool| { + let mut s = session(WRAP.0, WRAP.1, 8, "rgb"); + paint_layer(&mut s, tiled_texture); + paint_layer(&mut s, |_, _| [0.15, 0.2, 0.7, 1.0]); + let mut p = dab_opts(&points[..1], 100, &extra); + p["size"] = json!(12); + p["wrap"] = json!(wrap); let mut live = LiveRetouch::begin(&s, cmd, &p).unwrap(); live.push(&pts[1..]).unwrap(); - p["points"] = json!(points); - let shown = live.doc.layer(s.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap().read_region(Rect::new(0, 0, 48, 36)); - let plain = s.execute(cmd, p.clone()).unwrap(); - let want = layer_pixels(&s); - let error = shown.iter().zip(&want).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); - assert!(error <= composite_tolerance(depth), "{cmd} at {depth}-bit: the preview is off by {error}"); - if cmd == "paint.historyBrush" { - // A stroke drawn on the document as it is after the undo. - s.execute("edit.undo", json!({})).unwrap(); - let mut first = p.clone(); - first["points"] = json!(points[..1]); - let mut live = LiveRetouch::begin(&s, cmd, &first).unwrap(); - live.push(&pts[1..]).unwrap(); - s.offer_live_retouch(live).unwrap(); - let taken = s.execute(cmd, p).unwrap(); - assert_eq!(taken["fromLive"], json!(true), "{depth}-bit"); - assert_eq!(taken["damage"], plain["damage"], "{depth}-bit"); - assert!(layer_pixels(&s) == want, "{depth}-bit: the committed live pixels are the command's"); - } - } - } -} - -#[test] -fn a_wrapped_composite_stroke_over_its_work_budget_names_its_own_command() { - // Big, tightly spaced dabs pass the stroke footprint check but not the wrapped-work budget. - for (cmd, extra, setup) in [ - ("paint.historyBrush", json!({"state": 1}), textured_in_history as Setup), - ("paint.patternStamp", json!({"pattern": "Checkerboard"}), textured as Setup), - ] { - let mut s = session(WRAP.0, WRAP.1, 8, "rgb"); - setup(&mut s); - let mut p = json!({"points": [[0, 0], [700, 0]], "size": 1000, "hardness": 100, "spacing": 1, "wrap": true}); - for (k, v) in extra.as_object().unwrap() { - p[k] = v.clone(); - } - let err = s.execute(cmd, p).unwrap_err().to_string(); - assert!(err.contains(cmd) && err.contains("coverage budget"), "{cmd}: {err}"); + live.bounds() + }; + assert_eq!(bounds(true), bounds(false), "{cmd}: the live stroke stays where it was drawn"); } } diff --git a/crates/paint/src/bg_erase.rs b/crates/paint/src/bg_erase.rs index e41308e76a..323a90036a 100644 --- a/crates/paint/src/bg_erase.rs +++ b/crates/paint/src/bg_erase.rs @@ -10,7 +10,7 @@ use serde::{Deserialize, Serialize}; use crate::Stroke; use crate::replace::{Limits, Sampling}; -use crate::retouch::{Footprint, Region, alpha_index, apply_dab_stroke_wrapped}; +use crate::retouch::{Footprint, Region, alpha_index, apply_dab_stroke}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] @@ -49,14 +49,8 @@ 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 { - apply_background_eraser_wrapped(target, stroke, bs, selection, None) -} - -/// [`apply_background_eraser`] wrapped around `wrap` (View › Pattern Preview): the stroke samples -/// and erases where its pixels lie on that canvas, so it carries on across the edges. -pub fn apply_background_eraser_wrapped(target: &mut Surface, stroke: &Stroke, bs: &BgEraseSettings, selection: Option<&Surface>, wrap: Option) -> Rect { - let Some(effect) = background_eraser_effect(target, bs, wrap) else { return Rect::EMPTY }; - apply_dab_stroke_wrapped(target, &background_eraser_stroke(stroke), selection, false, 0, wrap, effect) + let Some(effect) = background_eraser_effect(target, 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), @@ -70,9 +64,8 @@ pub fn background_eraser_stroke(stroke: &Stroke) -> Stroke { /// One Background Eraser dab's edit of a working copy of `pre` (the target before the stroke): /// shared by [`apply_background_eraser`] and live previews that run the dabs as they come, so both -/// erase the same pixels. `None` when `pre` has no alpha channel (nothing can be erased). In a -/// stroke wrapped around `wrap`, `pre` is read where the working pixels lie on that canvas. -pub fn background_eraser_effect(pre: &Surface, bs: &BgEraseSettings, wrap: Option) -> Option> { +/// erase the same pixels. `None` when `pre` has no alpha channel (nothing can be erased). +pub fn background_eraser_effect(pre: &Surface, bs: &BgEraseSettings) -> Option> { let fmt = pre.format(); let a = alpha_index(&fmt)?; let nc = a; @@ -104,7 +97,7 @@ pub fn background_eraser_effect(pre: &Surface, bs: &BgEraseSettings, wrap: Optio return; } if orig.as_ref().is_none_or(|o| o.rect != work.rect) { - orig = Some(Region::read_wrapped(&pre, work.rect, wrap)); + orig = Some(Region::read(&pre, work.rect)); } let Some(orig) = orig.as_ref() else { return }; let (cx, cy) = (fp.dab.center.x.floor() as i32, fp.dab.center.y.floor() as i32); diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index fc356ff5cb..7054e11492 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -10,8 +10,7 @@ //! //! Module map: [`brush`] (the serde model), [`dynamics`] (points → dabs), [`render`] (dabs → //! stroke buffer → pixels), [`presets`] (built-ins), [`mixer`] (Mixer Brush), [`replace`] (Color -//! Replacement), [`retouch`] (sequential/accumulating helpers for the retouch tools), [`wrap`] -//! (View › Pattern Preview: strokes repeating across the canvas edges). +//! Replacement), [`retouch`] (sequential/accumulating helpers for the retouch tools). #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] @@ -35,7 +34,6 @@ pub mod retouch; pub mod rng; pub mod symmetry; pub mod tile; -pub mod wrap; pub use brush::{ BrushPreset, BrushSettings, ColorDynamics, Control, DualBrush, Dynamic, MAX_BRUSH_SIZE, MAX_SCATTER, MaskMode, Pattern, PatternStyle, Pose, PresetCaptures, diff --git a/crates/paint/src/replace.rs b/crates/paint/src/replace.rs index 957037a0bd..20619cd48a 100644 --- a/crates/paint/src/replace.rs +++ b/crates/paint/src/replace.rs @@ -8,8 +8,7 @@ use photocraft_raster::{Surface, from_rgba_into, to_rgba}; use serde::{Deserialize, Serialize}; use crate::Stroke; -use crate::retouch::{Footprint, Region, apply_dab_stroke_wrapped}; -use crate::wrap::wrap_coord; +use crate::retouch::{Footprint, Region, apply_dab_stroke}; #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -80,29 +79,14 @@ fn dist(a: &[f32; 4], b: [f32; 3]) -> f32 { /// Replace colours along a stroke. Returns the damaged rectangle. pub fn apply_color_replacement(target: &mut Surface, stroke: &Stroke, rs: &ReplaceSettings, selection: Option<&Surface>, lock_transparency: bool) -> Rect { - apply_color_replacement_wrapped(target, stroke, rs, selection, lock_transparency, None) -} - -/// [`apply_color_replacement`] wrapped around `wrap` (View › Pattern Preview): the stroke samples -/// and recolours where its pixels lie on that canvas, so it carries on across the edges. -pub fn apply_color_replacement_wrapped( - target: &mut Surface, - stroke: &Stroke, - rs: &ReplaceSettings, - selection: Option<&Surface>, - lock_transparency: bool, - wrap: Option, -) -> Rect { - let effect = color_replacement_effect(target.clone(), rs.clone(), wrap); - apply_dab_stroke_wrapped(target, stroke, selection, lock_transparency, 0, wrap, effect) + let effect = color_replacement_effect(target.clone(), rs.clone()); + apply_dab_stroke(target, stroke, selection, lock_transparency, 0, effect) } /// One Color Replacement dab's edit of a working copy, matching against `pre` (the target before /// the stroke). Shared by [`apply_color_replacement`] and live previews that run the dabs as they -/// come, so both recolour the same pixels. In a stroke wrapped around `wrap` (View › Pattern -/// Preview), `pre` is read where the dab's pixels lie on that canvas. -pub fn color_replacement_effect(pre: Surface, rs: ReplaceSettings, wrap: Option) -> impl FnMut(&mut Region, &Footprint) { - let wrap = wrap.filter(|t| !t.is_empty()); +/// come, so both recolour the same pixels. +pub fn color_replacement_effect(pre: Surface, rs: ReplaceSettings) -> impl FnMut(&mut Region, &Footprint) { let fmt = pre.format(); let n = fmt.channels(); let mode = match rs.mode { @@ -127,14 +111,13 @@ pub fn color_replacement_effect(pre: Surface, rs: ReplaceSettings, wrap: Option< }; move |work: &mut Region, fp: &Footprint| { let (cx, cy) = (fp.dab.center.x.floor() as i32, fp.dab.center.y.floor() as i32); - let (sx, sy) = wrap.map_or((cx, cy), |t| (wrap_coord(cx, t.x0, t.x1), wrap_coord(cy, t.y0, t.y1))); let sampled = match rs.sampling { Sampling::Continuous => { - let c = pre.rgba(sx, sy); + let c = pre.rgba(cx, cy); [c[0], c[1], c[2]] } Sampling::Once => *once.get_or_insert_with(|| { - let c = pre.rgba(sx, sy); + let c = pre.rgba(cx, cy); [c[0], c[1], c[2]] }), Sampling::BackgroundSwatch => [rs.background[0], rs.background[1], rs.background[2]], @@ -144,15 +127,8 @@ pub fn color_replacement_effect(pre: Surface, rs: ReplaceSettings, wrap: Option< return; } let (w, h) = (r.width() as usize, r.height() as usize); - let read = |q: Rect| { - let mut px = vec![[0.0f32; 4]; q.width() as usize * q.height() as usize]; - pre.read_rgba_into(q, &mut px); - px - }; - let pre_px = match wrap { - Some(t) => crate::wrap::read(r, t, 1, read), - None => read(r), - }; + let mut pre_px = vec![[0.0f32; 4]; w * h]; + pre.read_rgba_into(r, &mut pre_px); // Per-pixel match weight. let mut weight = vec![0.0f32; w * h]; for y in r.y0..r.y1 { diff --git a/crates/paint/src/retouch.rs b/crates/paint/src/retouch.rs index 53ef5b9a01..ec66e32f84 100644 --- a/crates/paint/src/retouch.rs +++ b/crates/paint/src/retouch.rs @@ -14,13 +14,10 @@ //! All pixel data here is the surface's *native* channels as normalised `f32` (any depth, any colour //! model); colour-space-specific work happens in the callbacks. -use std::collections::HashMap; - use photocraft_color::{BlendMode, PixelFormat}; use photocraft_geom::Rect; use photocraft_raster::{Surface, from_rgba_into, to_rgba}; -use crate::wrap::{fits, fold_area, wrap_coord}; use crate::{Dab, Stroke, dab_coverage, dabs}; /// A rectangle of native-channel pixels (`rect.width() × rect.height() × ch` floats, row-major). @@ -78,14 +75,6 @@ impl Region { pub fn write(&self, s: &mut Surface) { s.write_region(self.rect, &self.data); } - /// Read `rect` from a surface that repeats `wrap` apart (View › Pattern Preview): `rect` may - /// cross its edges. `None` (or an empty tile) is [`Region::read`]. - pub fn read_wrapped(s: &Surface, rect: Rect, wrap: Option) -> Self { - match wrap.filter(|t| !t.is_empty()) { - Some(tile) => Self { rect, ch: s.channels(), data: crate::wrap::read(rect, tile, s.channels(), |r| s.read_region(r)) }, - None => Self::read(s, rect), - } - } } /// One dab's footprint: coverage (hardness falloff × dab alpha) over its bounding rectangle. @@ -289,174 +278,6 @@ pub fn apply_dab_stroke( bounds } -/// [`apply_dab_stroke`] wrapped around `wrap` (View › Pattern Preview): each dab reads and edits -/// the pixels where it repeats on that tile, so a stroke crossing an edge carries on at the -/// opposite one. The dabs run one by one on a [`WorkTiles`] working copy, as live previews run -/// them. `None` (or an empty tile) is [`apply_dab_stroke`]. Returns the damaged rectangle. -pub fn apply_dab_stroke_wrapped( - target: &mut Surface, - stroke: &Stroke, - selection: Option<&Surface>, - lock_transparency: bool, - halo: i32, - wrap: Option, - mut effect: impl FnMut(&mut Region, &Footprint), -) -> Rect { - let Some(tile) = wrap.filter(|t| !t.is_empty()) else { - return apply_dab_stroke(target, stroke, selection, lock_transparency, halo, effect); - }; - let ctx = crate::BrushContext::new(&stroke.brush); - let mut work = WorkTiles::new(target.channels()).wrapped(Some(tile)); - let mut damage = Rect::EMPTY; - for (i, d) in dabs(stroke).iter().enumerate() { - let fp = ctx.footprint(d, i); - if fp.rect.is_empty() { - continue; - } - let mut region = work.read(target, fp.rect.inflate(halo)); - effect(&mut region, &fp); - work.write_dab(target, ®ion, &fp); - damage = damage.union(&fold_area(fp.rect, tile)); - } - let written: Vec = work.areas().map(|r| r.intersect(&tile)).filter(|r| !r.is_empty()).collect(); - for r in written { - let edited = work.read(target, r); - mix_back(target, &Region::read(target, r), &edited, r, stroke.brush.opacity, selection, lock_transparency); - } - damage -} - -/// Side of the tiles a [`WorkTiles`] working copy keeps its pixels in. -const WORK_TILE: i32 = 128; - -/// The working copy of a sequential-dab stroke run dab by dab (live previews, -/// [`apply_dab_stroke_wrapped`]): the target's native channels as `f32`, in tiles copied from the -/// pre-stroke surface the first time a dab writes to them. Unlike a `Surface`, it isn't rounded to -/// the document's depth between dabs, so each dab sees what [`apply_dab_stroke`]'s working copy -/// holds. Wrapped around a tile ([`Self::wrapped`]), it keeps each pixel once, where it lies on -/// the tile, and reads and writes it wherever it repeats. -pub struct WorkTiles { - ch: usize, - tiles: HashMap<(i32, i32), Vec>, - wrap: Option, -} - -impl WorkTiles { - pub fn new(ch: usize) -> Self { - Self { ch, tiles: HashMap::new(), wrap: None } - } - - /// Keep the pixels of a stroke wrapped around `tile` (View › Pattern Preview). `None` or an - /// empty tile doesn't wrap. - pub fn wrapped(mut self, tile: Option) -> Self { - self.wrap = tile.filter(|t| !t.is_empty()); - self - } - - fn tile_rect((tx, ty): (i32, i32)) -> Rect { - Rect::new(tx * WORK_TILE, ty * WORK_TILE, tx * WORK_TILE + WORK_TILE, ty * WORK_TILE + WORK_TILE) - } - - /// The tiles `r` overlaps. - fn coords(r: Rect) -> impl Iterator { - let (x0, x1) = (r.x0.div_euclid(WORK_TILE), (r.x1 - 1).div_euclid(WORK_TILE)); - let (y0, y1) = (r.y0.div_euclid(WORK_TILE), (r.y1 - 1).div_euclid(WORK_TILE)); - let empty = r.is_empty(); - (y0..=y1).filter(move |_| !empty).flat_map(move |ty| (x0..=x1).map(move |tx| (tx, ty))) - } - - /// The working pixels of `r`: the pre-stroke pixels `pre` where no dab has written yet. - /// Wrapped, `r` may cross the tile's edges or be bigger than it. - pub fn read(&self, pre: &Surface, r: Rect) -> Region { - match self.wrap { - Some(tile) => Region { rect: r, ch: self.ch, data: crate::wrap::read(r, tile, self.ch, |part| self.read_at(pre, part).data) }, - None => self.read_at(pre, r), - } - } - - fn read_at(&self, pre: &Surface, r: Rect) -> Region { - let mut out = Region::new(r, self.ch); - let n = self.ch; - let mut buf = Vec::new(); - for c in Self::coords(r) { - let tr = Self::tile_rect(c); - let part = r.intersect(&tr); - let w = part.width() as usize * n; - let tile = self.tiles.get(&c); - if tile.is_none() { - pre.read_region_into(part, &mut buf); - } - for y in part.y0..part.y1 { - let src = match tile { - Some(t) => t.get(((y - tr.y0) * WORK_TILE + (part.x0 - tr.x0)) as usize * n..).and_then(|s| s.get(..w)), - None => buf.get((y - part.y0) as usize * w..).and_then(|s| s.get(..w)), - }; - let dst = out.index(part.x0, y) * n; - if let (Some(s), Some(d)) = (src, out.data.get_mut(dst..dst + w)) { - d.copy_from_slice(s); - } - } - } - out - } - - /// Store a dab's edit: the pixels of `region` (which covers the dab) over the dab's rectangle - /// `fp.rect`. Wrapped, they land where they lie on the tile; a dab bigger than the tile covers - /// some pixels more than once, and each keeps the copy the dab covers most. - pub fn write_dab(&mut self, pre: &Surface, region: &Region, fp: &Footprint) { - let r = fp.rect.intersect(®ion.rect); - let Some(tile) = self.wrap else { - return self.write_at(pre, ®ion.crop(r)); - }; - if fits(r, tile) { - for (part, (dx, dy)) in crate::wrap::pieces(r, tile) { - let mut piece = region.crop(part.translate(dx, dy)); - piece.rect = part; - self.write_at(pre, &piece); - } - return; - } - let area = fold_area(r, tile); - let mut folded = self.read_at(pre, area); - let mut most = vec![0.0f32; area.width() as usize * area.height() as usize]; - for y in r.y0..r.y1 { - for x in r.x0..r.x1 { - let (c, tx, ty) = (fp.at(x, y), wrap_coord(x, tile.x0, tile.x1), wrap_coord(y, tile.y0, tile.y1)); - if let Some(m) = most.get_mut(folded.index(tx, ty)) - && c > *m - { - *m = c; - folded.px_mut(tx, ty).copy_from_slice(region.px(x, y)); - } - } - } - self.write_at(pre, &folded); - } - - /// Store `region` as the working pixels of its rectangle. - fn write_at(&mut self, pre: &Surface, region: &Region) { - let (r, n) = (region.rect, self.ch); - for c in Self::coords(r) { - let tr = Self::tile_rect(c); - let tile = self.tiles.entry(c).or_insert_with(|| pre.read_region(tr)); - let part = r.intersect(&tr); - let w = part.width() as usize * n; - for y in part.y0..part.y1 { - let dst = ((y - tr.y0) * WORK_TILE + (part.x0 - tr.x0)) as usize * n; - let src = region.index(part.x0, y) * n; - if let (Some(s), Some(d)) = (region.data.get(src..src + w), tile.get_mut(dst..dst + w)) { - d.copy_from_slice(s); - } - } - } - } - - /// The rectangles of the tiles dabs have written to. - pub fn areas(&self) -> impl Iterator + '_ { - self.tiles.keys().map(|&c| Self::tile_rect(c)) - } -} - /// Mix a sequential-dab stroke's working pixels `work` back over the original `orig` at /// `opacity × selection` inside `rect`, and write that area to `target`: the last step of /// [`apply_dab_stroke`], shared with live previews that run the dabs as they come. @@ -1066,89 +887,4 @@ mod tests { } } } - - /// The canvas the Pattern Preview strokes below wrap around. - const TILE: Rect = Rect::new(0, 0, 40, 30); - - /// `area` of a surface showing the canvas repeated: every pixel of the canvas has its own colour. - fn tiled(fmt: PixelFormat, area: Rect) -> Surface { - let mut s = Surface::new(fmt); - let px = (area.y0..area.y1).flat_map(|y| (area.x0..area.x1).map(move |x| (wrap_coord(x, 0, 40), wrap_coord(y, 0, 30)))); - let data: Vec = px.flat_map(|(x, y)| [x as f32 / 40.0, y as f32 / 30.0, ((x * 7 + y * 3) % 13) as f32 / 13.0, 1.0]).collect(); - s.write_region(area, &data); - s - } - - fn smudge(size: f32) -> impl FnMut(&mut Region, &Footprint) { - let mut sm = Smudge::new(0.8, None, size).with_alpha(Some(3)); - move |work, fp| sm.dab(work, fp) - } - - #[test] - fn a_wrapped_sequential_stroke_paints_the_canvas_as_its_tiled_copies_would() { - // View › Pattern Preview: a smudge across a corner of the canvas copy it is drawn on gives - // the canvas exactly what it gives the canvas tiled three by three, where it runs into the - // next copies and carries their colours along. (The same points both times: moved points - // would place the dabs a rounding apart.) - let fmt = PixelFormat::RGBA32F; - let far = stroke(&[(68.0, 48.0), (92.0, 70.0)], 12.0, 0.5); - let halo = Smudge::sampling_radius(12.0); - let mut canvas = tiled(fmt, TILE); - let dmg = apply_dab_stroke_wrapped(&mut canvas, &far, None, false, halo, Some(TILE), smudge(12.0)); - let three = Rect::new(0, 0, 120, 90); - let (before, mut big) = (tiled(fmt, three), tiled(fmt, three)); - apply_dab_stroke(&mut big, &far, None, false, halo, smudge(12.0)); - let mut changed = 0; - for y in 0..30 { - for x in 0..40 { - let copies = [(40, 30), (80, 30), (40, 60), (80, 60)].map(|(dx, dy)| (x + dx, y + dy)); - let moved: Vec<_> = copies.into_iter().filter(|&(u, v)| big.pixel(u, v) != before.pixel(u, v)).collect(); - let want = match moved.as_slice() { - [] => before.pixel(x, y), - [(u, v)] => big.pixel(*u, *v), - _ => panic!("({x}, {y}): two copies under the stroke"), - }; - assert_eq!(canvas.pixel(x, y), want, "({x}, {y})"); - changed += usize::from(!moved.is_empty()); - } - } - assert!(changed > 300, "the smudge crossed both edges ({changed} px)"); - assert!(dmg.x0 >= 0 && dmg.y0 >= 0 && dmg.x1 <= 40 && dmg.y1 <= 30, "{dmg:?}"); - assert!((-12..0).all(|x| canvas.pixel(x, 20)[3] == 0.0) && (40..52).all(|x| canvas.pixel(x, 20)[3] == 0.0), "nothing off the canvas"); - } - - #[test] - fn a_wrapped_sequential_stroke_inside_the_canvas_paints_as_before() { - for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA32F] { - let st = stroke(&[(16.0, 12.0), (24.0, 18.0)], 6.0, 0.8); - let run = |wrap| { - let mut s = tiled(fmt, TILE); - let dmg = apply_dab_stroke_wrapped(&mut s, &st, None, false, Smudge::sampling_radius(6.0), wrap, smudge(6.0)); - (s, dmg) - }; - let ((plain, d0), (wrapped, d1)) = (run(None), run(Some(TILE))); - assert_eq!(d0, d1, "{fmt:?}"); - assert!((0..30).all(|y| (0..40).all(|x| plain.pixel(x, y) == wrapped.pixel(x, y))), "{fmt:?}"); - assert!(plain.pixel(20, 15) != tiled(fmt, TILE).pixel(20, 15), "{fmt:?}: the stroke smudged"); - } - } - - #[test] - fn a_wrapped_dab_bigger_than_the_canvas_edits_all_of_it_and_nothing_else() { - let small = Rect::new(0, 0, 10, 8); - let mut s = Surface::new(PixelFormat::RGBA32F); - s.fill_rect(small, &[1.0, 0.0, 0.0, 1.0]); - let darken = |work: &mut Region, fp: &Footprint| { - let r = fp.rect.intersect(&work.rect); - for y in r.y0..r.y1 { - for x in r.x0..r.x1 { - work.px_mut(x, y)[0] *= 1.0 - 0.5 * fp.at(x, y); - } - } - }; - let dmg = apply_dab_stroke_wrapped(&mut s, &stroke(&[(5.0, 4.0), (9.0, 6.0)], 30.0, 0.0), None, false, 0, Some(small), darken); - assert_eq!(dmg, small); - assert!((0..8).all(|y| (0..10).all(|x| s.pixel(x, y)[0] < 1.0)), "every pixel under the dab's copies darkens"); - assert!((-5..15).all(|x| s.pixel(x, -1)[3] == 0.0 && s.pixel(x, 8)[3] == 0.0), "nothing off the canvas"); - } } diff --git a/crates/paint/src/wrap.rs b/crates/paint/src/wrap.rs deleted file mode 100644 index efad49d3ca..0000000000 --- a/crates/paint/src/wrap.rs +++ /dev/null @@ -1,166 +0,0 @@ -//! View › Pattern Preview geometry: the document repeats its canvas (the *tile*) in every -//! direction, so a stroke past one edge carries on at the opposite one. Coordinates outside the -//! tile name the pixel a whole number of tile sizes away that lies on it. - -use photocraft_geom::Rect; - -/// `v` moved a whole number of periods into `lo..hi` (`v` itself when that is empty). -#[inline] -pub fn wrap_coord(v: i32, lo: i32, hi: i32) -> i32 { - let period = i64::from(hi) - i64::from(lo); - if period <= 0 { - return v; - } - (i64::from(lo) + (i64::from(v) - i64::from(lo)).rem_euclid(period)) as i32 -} - -/// Whether `rect` fits in `tile`, so it covers no pixel of the tile twice. -pub fn fits(rect: Rect, tile: Rect) -> bool { - rect.width() <= tile.width() && rect.height() <= tile.height() -} - -/// The part of `tile` that `rect` covers once moved onto it: per axis, the rectangle's span moved -/// a whole number of periods, or the whole tile where the span is longer or crosses an edge. -pub fn fold_area(rect: Rect, tile: Rect) -> Rect { - if rect.is_empty() || tile.is_empty() { - return Rect::EMPTY; - } - let span = |a0: i32, a1: i32, lo: i32, hi: i32| { - let start = wrap_coord(a0, lo, hi); - let len = i64::from(a1) - i64::from(a0); - if i64::from(start) + len > i64::from(hi) { (lo, hi) } else { (start, start + len as i32) } - }; - let (x0, x1) = span(rect.x0, rect.x1, tile.x0, tile.x1); - let (y0, y1) = span(rect.y0, rect.y1, tile.y0, tile.y1); - Rect::new(x0, y0, x1, y1) -} - -/// One axis of `a0..a1` cut where it crosses the edges of `lo..hi`: each run's start on the tile, -/// its start in `a0..a1`, and its length. -fn runs(a0: i32, a1: i32, lo: i32, hi: i32) -> Vec<(i32, i32, i32)> { - let period = i64::from(hi) - i64::from(lo); - let mut out = Vec::new(); - let mut a = i64::from(a0); - while a < i64::from(a1) { - let k = (a - i64::from(lo)).div_euclid(period) * period; - let end = (i64::from(a1) - k).min(i64::from(hi)); - let start = a - k; - out.push((start as i32, a as i32, (end - start) as i32)); - a = end + k; - } - out -} - -/// `r` cut where it crosses the edges of `tile`: each part moved onto the tile, with the offset -/// that moves it back (`part.translate(dx, dy)` is that part of `r`). A rectangle bigger than the -/// tile gives parts that overlap on it. -pub fn pieces(r: Rect, tile: Rect) -> Vec<(Rect, (i32, i32))> { - if r.is_empty() || tile.is_empty() { - return Vec::new(); - } - let xs = runs(r.x0, r.x1, tile.x0, tile.x1); - runs(r.y0, r.y1, tile.y0, tile.y1) - .into_iter() - .flat_map(|(ty, uy, h)| xs.iter().map(move |&(tx, ux, w)| (Rect::new(tx, ty, tx + w, ty + h), (ux - tx, uy - ty)))) - .collect() -} - -/// The values over `r` of an image repeating `tile` apart, given `read`, which returns a -/// rectangle of the tile (`n` values per pixel, row-major). A rectangle crossing at most one edge -/// per axis is read in its parts; a bigger one reads the tile area it covers once. -pub fn read(r: Rect, tile: Rect, n: usize, mut read: impl FnMut(Rect) -> Vec) -> Vec { - let w = r.width() as usize; - let mut out = vec![T::default(); w * r.height() as usize * n]; - if r.is_empty() || tile.is_empty() { - return out; - } - let (xs, ys) = (runs(r.x0, r.x1, tile.x0, tile.x1), runs(r.y0, r.y1, tile.y0, tile.y1)); - let mut copy = |src: &[T], at: usize, x: i32, y: i32, len: i32| { - let o = ((y - r.y0) as usize * w + (x - r.x0) as usize) * n; - let len = len as usize * n; - if let (Some(d), Some(s)) = (out.get_mut(o..o + len), src.get(at..at + len)) { - d.copy_from_slice(s); - } - }; - if xs.len() * ys.len() <= 4 { - for &(ty, uy, h) in &ys { - for &(tx, ux, len) in &xs { - let part = read(Rect::new(tx, ty, tx + len, ty + h)); - for row in 0..h { - copy(&part, row as usize * len as usize * n, ux, uy + row, len); - } - } - } - return out; - } - let area = fold_area(r, tile); - let src = read(area); - let aw = area.width() as usize; - for &(ty, uy, h) in &ys { - for row in 0..h { - for &(tx, ux, len) in &xs { - copy(&src, ((ty + row - area.y0) as usize * aw + (tx - area.x0) as usize) * n, ux, uy + row, len); - } - } - } - out -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn coordinates_wrap_onto_the_tile_from_any_distance() { - assert_eq!([-17, -1, 0, 15, 16, 33, 1_000_000].map(|v| wrap_coord(v, 0, 16)), [15, 15, 0, 15, 0, 1, 0]); - assert_eq!(wrap_coord(-3, 10, 20), 17); - } - - #[test] - fn pieces_cover_the_rectangle_once_and_land_on_the_tile() { - let tile = Rect::new(0, 0, 10, 8); - for r in [Rect::new(7, 6, 13, 11), Rect::new(-25, 3, 4, 5), Rect::new(2, 2, 5, 5), Rect::new(-3, -3, 30, 20)] { - let mut seen = std::collections::HashMap::new(); - for (part, (dx, dy)) in pieces(r, tile) { - assert!(tile.contains(part.x0, part.y0) && part.x1 <= tile.x1 && part.y1 <= tile.y1, "{part:?} on the tile"); - for y in part.y0..part.y1 { - for x in part.x0..part.x1 { - *seen.entry((x + dx, y + dy)).or_insert(0) += 1; - assert_eq!((wrap_coord(x + dx, 0, 10), wrap_coord(y + dy, 0, 8)), (x, y)); - } - } - } - assert_eq!(seen.len(), (r.width() * r.height()) as usize, "{r:?}"); - assert!(seen.values().all(|&c| c == 1) && seen.keys().all(|&(x, y)| r.contains(x, y)), "{r:?}"); - } - } - - #[test] - fn a_read_repeats_the_tile_whatever_the_rectangle() { - let tile = Rect::new(4, 2, 14, 10); - let value = |x: i32, y: i32| (wrap_coord(x, 4, 14) * 100 + wrap_coord(y, 2, 10)) as f32; - let mut reads = 0; - // Two values per pixel; `read` only ever asks for rectangles of the tile. - let mut from_tile = |q: Rect| { - reads += 1; - assert!(q.x0 >= tile.x0 && q.y0 >= tile.y0 && q.x1 <= tile.x1 && q.y1 <= tile.y1, "{q:?}"); - (q.y0..q.y1).flat_map(|y| (q.x0..q.x1).flat_map(move |x| [value(x, y), -value(x, y)])).collect::>() - }; - for r in [Rect::new(10, 7, 17, 12), Rect::new(5, 3, 9, 6), Rect::new(-31, -5, 40, 30), Rect::new(0, 0, 0, 5)] { - let got = read(r, tile, 2, &mut from_tile); - let want: Vec = (r.y0..r.y1).flat_map(|y| (r.x0..r.x1).flat_map(move |x| [value(x, y), -value(x, y)])).collect(); - assert_eq!(got, want, "{r:?}"); - } - assert!(reads <= 4 + 1 + 1, "small rectangles read in parts, big ones once ({reads})"); - } - - #[test] - fn the_fold_area_is_where_a_rectangle_lands() { - let tile = Rect::new(0, 0, 10, 8); - assert_eq!(fold_area(Rect::new(12, 9, 15, 12), tile), Rect::new(2, 1, 5, 4)); - assert_eq!(fold_area(Rect::new(8, 2, 12, 4), tile), Rect::new(0, 2, 10, 4)); - assert_eq!(fold_area(Rect::new(-50, -50, 50, 50), tile), tile); - assert_eq!(fold_area(Rect::EMPTY, tile), Rect::EMPTY); - assert!(fits(Rect::new(3, 3, 13, 11), tile) && !fits(Rect::new(0, 0, 11, 2), tile)); - } -} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index c0efd7ae37..ac471a9269 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -97,9 +97,7 @@ pub(crate) use selection::{floating_outline, selection_drag_delta}; pub(crate) use start_screen::start_screen_drop_hint; pub(crate) use strokes::multiple_color_target; pub use strokes::paint_target; -pub(crate) use strokes::{ - ClonePreviewCache, CommittedStroke, LiveStroke, cancel_mixer_on_context_change, freehand_tool, pattern_wrap, spread_ms, strokes_live, -}; +pub(crate) use strokes::{ClonePreviewCache, CommittedStroke, LiveStroke, cancel_mixer_on_context_change, freehand_tool, spread_ms, strokes_live}; use strokes::{HOLD_REPEAT_MS, draw_clone_preview, feed_live_stroke, pointer_button_modifiers, pointer_moves, stroke_wants_time, tap_at_peak_pressure}; #[cfg(test)] pub(crate) use strokes::{SPOT_HEALING_TRAIL, live_retouch_points}; diff --git a/crates/ui-egui/src/canvas/strokes.rs b/crates/ui-egui/src/canvas/strokes.rs index 404a46b9fa..c7c6d4b643 100644 --- a/crates/ui-egui/src/canvas/strokes.rs +++ b/crates/ui-egui/src/canvas/strokes.rs @@ -310,13 +310,6 @@ pub(super) fn stroke_params(app: &PhotocraftApp, d: &Drag, points: &[Vec]) p } -/// View › Pattern Preview: a painting stroke goes on across the canvas edges (#8883). -pub(crate) fn pattern_wrap(app: &PhotocraftApp, p: &mut serde_json::Value) { - if app.ui.view.pattern_preview { - p["wrap"] = json!(true); - } -} - /// Tools whose strokes the engine renders while they are drawn (`LiveStroke`). pub(crate) fn strokes_live(tool: Tool) -> bool { matches!( @@ -394,7 +387,6 @@ pub(super) fn begin_live_stroke(app: &PhotocraftApp) -> Option { } 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 { crate::retouch_ui::history_brush_params(app) } else { crate::retouch_ui::clone_params(app)? }; - pattern_wrap(app, &mut p); p["points"] = json!(d.points); p["target"] = paint_target(app); EngineStroke::Retouch(Box::new(photocraft_engine::retouch_cmds::LiveRetouch::begin(&app.session, cmd, &p).ok()?)) diff --git a/crates/ui-egui/src/stroke_timing_tests.rs b/crates/ui-egui/src/stroke_timing_tests.rs index 5e44707c28..ed59943fae 100644 --- a/crates/ui-egui/src/stroke_timing_tests.rs +++ b/crates/ui-egui/src/stroke_timing_tests.rs @@ -499,60 +499,6 @@ fn releasing_a_sequential_dab_stroke_commits_what_a_replay_paints() { } } -/// View › Pattern Preview (#8883): a Blur, Smudge or Dodge stroke dragged past the right edge -/// carries on at the left one, and the release still commits the pixels its live stroke drew. -#[test] -fn a_sequential_dab_stroke_past_the_edge_in_pattern_preview_commits_its_live_pixels() { - for (tool, cmd) in [(Tool::Blur, "paint.blur"), (Tool::Smudge, "paint.smudge"), (Tool::Dodge, "paint.dodge")] { - let setup = |run: &mut dyn FnMut(&str, Value)| { - run("tools.setBrush", json!({"brush": {"size": 24, "hardness": 0.2}})); - run("paint.stroke", json!({"points": [[0, 50], [200, 50]], "size": 30, "hardness": 0.5, "color": "#c04020"})); - run("paint.stroke", json!({"points": [[0, 35], [200, 65]], "size": 8, "hardness": 1.0, "color": "#2060c0"})); - }; - let mut h = harness(); - setup(&mut |id, p| { - h.state_mut().run(id, p).unwrap(); - }); - let before = h.state().session.active().unwrap().doc.clone(); - { - let app = h.state_mut(); - app.ui.tool = tool; - app.ui.view.pattern_preview = true; - app.ui.views[0].zoom = 2.0; - app.ui.views[0].center = [100.0, 50.0]; - } - h.run_steps(1); - move_to(&mut h, 150.0, 50.0); - button(&mut h, 150.0, 50.0, true); - for (x, y) in [(175.0, 52.0), (200.0, 50.0), (225.0, 47.0), (245.0, 50.0)] { - move_to(&mut h, x, y); - } - assert!(h.state().live_stroke.is_some(), "{cmd}: a live stroke"); - h.state_mut().retouch_from_live = false; - button(&mut h, 245.0, 50.0, false); - h.run_steps(2); - let app = h.state(); - assert!(app.retouch_from_live, "{cmd}: the release took the live pixels instead of rendering the stroke again"); - let (_, p) = app.session.journal.iter().rev().find(|(id, _)| id == cmd).cloned().expect("a committed stroke"); - assert_eq!(p["wrap"], json!(true), "{cmd}: {p}"); - let mut fresh = photocraft_engine::Session::new(); - fresh.execute("file.new", json!({"width": 200, "height": 100, "background": "white"})).unwrap(); - setup(&mut |id, p| { - fresh.execute(id, p).unwrap(); - }); - fresh.execute(cmd, p).unwrap(); - let st = app.session.active().unwrap(); - let (a, b, pre) = ( - photocraft_compose::render(&st.doc, st.doc.bounds()), - photocraft_compose::render(&fresh.active().unwrap().doc, st.doc.bounds()), - photocraft_compose::render(&before, st.doc.bounds()), - ); - assert!(a.px.iter().zip(&b.px).all(|(x, y)| x == y), "{cmd}: live commit and replay differ"); - let left = |buf: &photocraft_compose::Buffer| (30..70).flat_map(|y| (0..30).map(move |x| (x, y))).map(|(x, y)| buf.px[y * 200 + x]).collect::>(); - assert_ne!(left(&a), left(&pre), "{cmd}: the stroke came back at the left edge"); - } -} - /// Pressure changes Smudge's painted footprint, but not the square of colour it carries. /// Exercise the actual pen → live preview → release handoff → journal replay, then undo/redo. #[test] diff --git a/crates/ui-egui/src/tools/eraser_ui.rs b/crates/ui-egui/src/tools/eraser_ui.rs index 8782c29863..ac896eeb0b 100644 --- a/crates/ui-egui/src/tools/eraser_ui.rs +++ b/crates/ui-egui/src/tools/eraser_ui.rs @@ -49,16 +49,14 @@ pub fn finish_stroke(app: &mut PhotocraftApp, tool: Tool, points: &[[f64; 3]]) - /// 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 mut p = json!({ + json!({ "points": points, "sampling": o.bg_sampling, "limits": o.bg_limits, "tolerance": o.bg_tolerance, "protectForegroundColor": o.bg_protect_fg, "seed": crate::retouch_ui::stroke_seed(points), - }); - crate::canvas::pattern_wrap(app, &mut p); - p + }) } /// Whether `tool` is the Eraser in Pencil mode: it erases hard, aliased pixels through diff --git a/crates/ui-egui/src/tools/retouch_ui.rs b/crates/ui-egui/src/tools/retouch_ui.rs index c694679202..6b6d0f07e2 100644 --- a/crates/ui-egui/src/tools/retouch_ui.rs +++ b/crates/ui-egui/src/tools/retouch_ui.rs @@ -29,13 +29,11 @@ pub(crate) fn clone_params(app: &PhotocraftApp) -> Option { let o = &app.ui.tool_options; // The options bar's Mode is the tool's own brush's. let mode = crate::blend_keys::brush_tool_mode(app.ui.tool, app.session.tools.brush.mode); - let mut p = json!({"aligned": o.clone_aligned, "sampleLayer": o.clone_sample, "mode": mode.label()}); + // View › Pattern Preview: both tools carry a stroke on across the canvas edges (#8883). + let mut p = json!({"aligned": o.clone_aligned, "sampleLayer": o.clone_sample, "mode": mode.label(), "wrap": app.ui.view.pattern_preview}); if app.ui.tool == Tool::CloneStamp { - p["wrap"] = json!(app.ui.view.pattern_preview); p["opacity"] = json!(app.session.tools.brush.opacity * 100.0); p["flow"] = json!(app.session.tools.brush.flow * 100.0); - } else { - crate::canvas::pattern_wrap(app, &mut p); } // The Clone Source panel's active slot (set by ⌥-click) drives the stroke: the engine keeps // the aligned pairing and applies the slot's scale/rotation/flip. @@ -63,7 +61,7 @@ pub(crate) fn history_brush_params(app: &PhotocraftApp) -> Value { /// Blur, Sharpen, Smudge, Dodge, Burn, Sponge. Shared by the live preview and the commit. pub(crate) fn dab_params(app: &PhotocraftApp, tool: Tool) -> Option<(&'static str, Value)> { let o = &app.ui.tool_options; - let (cmd, mut p) = match tool { + Some(match tool { Tool::Blur => ("paint.blur", json!({"strength": o.strength, "sampleAllLayers": o.sample_all.blur})), Tool::Sharpen => ("paint.sharpen", json!({"strength": o.strength, "protectDetail": o.protect_detail, "sampleAllLayers": o.sample_all.sharpen})), Tool::Smudge => ("paint.smudge", json!({"strength": o.strength, "fingerPainting": o.finger_painting, "sampleAllLayers": o.sample_all.smudge})), @@ -73,9 +71,7 @@ pub(crate) fn dab_params(app: &PhotocraftApp, tool: Tool) -> Option<(&'static st ), Tool::Sponge => ("paint.sponge", json!({"mode": o.sponge_mode, "vibrance": o.vibrance})), _ => return None, - }; - crate::canvas::pattern_wrap(app, &mut p); - Some((cmd, p)) + }) } /// `paint.colorReplacement` params from the options bar (without `points`): shared by the live @@ -83,7 +79,7 @@ pub(crate) fn dab_params(app: &PhotocraftApp, tool: Tool) -> Option<(&'static st /// stroke paints the same colour; Background Swatch sampling matches the background colour. pub(crate) fn color_replacement_params(app: &PhotocraftApp) -> Value { let o = &app.ui.tool_options; - let mut p = json!({ + json!({ "color": app.session.tools.foreground, "mode": o.cr_mode, "sampling": o.cr_sampling, @@ -92,9 +88,7 @@ pub(crate) fn color_replacement_params(app: &PhotocraftApp) -> Value { "antiAlias": o.cr_anti_alias, // A mask or channel target is refused: the tool recolours layer pixels only. "target": crate::canvas::paint_target(app), - }); - crate::canvas::pattern_wrap(app, &mut p); - p + }) } /// `paint.patternStamp` params from the options bar and the Patterns panel (without `points` and @@ -119,7 +113,6 @@ pub(crate) fn pattern_stamp_params(app: &PhotocraftApp, points: &[[f64; 3]]) -> 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); } - crate::canvas::pattern_wrap(app, &mut p); p } @@ -188,10 +181,6 @@ pub fn finish_stroke(app: &mut PhotocraftApp, tool: Tool, points: &[[f64; 3]], m _ => return false, }; p["points"] = pts; - // Spot Healing and History Brush; the others' params have it already. - if !matches!(tool, Tool::Remove | Tool::MixerBrush) { - crate::canvas::pattern_wrap(app, &mut p); - } // The layer mask, an alpha channel or the Quick Mask when targeted, as the Brush paints. p["target"] = crate::canvas::paint_target(app); let result = app.run(cmd, p); diff --git a/crates/ui-egui/src/tools/retouch_ui/tests.rs b/crates/ui-egui/src/tools/retouch_ui/tests.rs index bfe9672331..816c9ca12e 100644 --- a/crates/ui-egui/src/tools/retouch_ui/tests.rs +++ b/crates/ui-egui/src/tools/retouch_ui/tests.rs @@ -29,24 +29,26 @@ fn stripes(app: &mut PhotocraftApp, step: usize, target: &str) { } #[test] -fn every_retouching_stroke_wraps_in_pattern_preview() { - // View › Pattern Preview (#8883): a stroke across the right edge asks its command to go - // on at the opposite one, and only then. +fn only_clone_stamp_and_healing_brush_wrap_in_pattern_preview() { + // View › Pattern Preview (#8883): a Clone Stamp or Healing Brush stroke across the right edge + // asks its command to go on at the opposite one, and only then. The reference application's + // other retouching tools stop at the edge. let tools = [ - (Tool::Blur, "paint.blur"), - (Tool::Sharpen, "paint.sharpen"), - (Tool::Smudge, "paint.smudge"), - (Tool::Dodge, "paint.dodge"), - (Tool::Burn, "paint.burn"), - (Tool::Sponge, "paint.sponge"), - (Tool::ColorReplacement, "paint.colorReplacement"), - (Tool::PatternStamp, "paint.patternStamp"), - (Tool::Healing, "paint.healingBrush"), - (Tool::HistoryBrush, "paint.historyBrush"), - (Tool::SpotHealing, "paint.spotHealing"), - (Tool::BackgroundEraser, "paint.backgroundEraser"), + (Tool::CloneStamp, "paint.cloneStamp", true), + (Tool::Healing, "paint.healingBrush", true), + (Tool::Blur, "paint.blur", false), + (Tool::Sharpen, "paint.sharpen", false), + (Tool::Smudge, "paint.smudge", false), + (Tool::Dodge, "paint.dodge", false), + (Tool::Burn, "paint.burn", false), + (Tool::Sponge, "paint.sponge", false), + (Tool::ColorReplacement, "paint.colorReplacement", false), + (Tool::PatternStamp, "paint.patternStamp", false), + (Tool::HistoryBrush, "paint.historyBrush", false), + (Tool::SpotHealing, "paint.spotHealing", false), + (Tool::BackgroundEraser, "paint.backgroundEraser", false), ]; - for (tool, cmd) in tools { + for (tool, cmd, wraps) in tools { for pattern_preview in [false, true] { let mut app = app(); stripes(&mut app, 8, "pixels"); @@ -59,7 +61,7 @@ fn every_retouching_stroke_wraps_in_pattern_preview() { tool_event(&mut app, ToolEvent::Up { x: 112.0, y: 30.0 }, m); assert!(!app.ui.status_error, "{tool:?}: {}", app.ui.status); let (_, p) = app.session.journal.iter().rev().find(|(id, _)| id == cmd).cloned().unwrap_or_else(|| panic!("{tool:?}: no {cmd}")); - assert_eq!(p.get("wrap").and_then(Value::as_bool).unwrap_or(false), pattern_preview, "{tool:?}: {p}"); + assert_eq!(p.get("wrap").and_then(Value::as_bool).unwrap_or(false), wraps && pattern_preview, "{tool:?}: {p}"); } } }