Skip to content

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

Content-Aware tools: Photoshop's behaviour, measured (#2202)

Unemars401abc48a919
diff --git a/crates/algo/src/content_aware.rs b/crates/algo/src/content_aware.rs
index 95e03b65f..a33d5059a 100644
--- a/crates/algo/src/content_aware.rs
+++ b/crates/algo/src/content_aware.rs
@@ -1,30 +1,43 @@
-//! Edit › Content-Aware Fill: patch-based completion ([`crate::inpaint::complete`]) with a
-//! restricted sampling area, geometric adaptation and colour adaptation.
+//! Edit › Content-Aware Fill: patch-based completion ([`crate::inpaint::complete_masked`]) with
+//! Photoshop's sampling area, colour adaptation and geometric adaptation.
//!
-//! * **Sampling area**: pixels outside the allowed `source` mask may not be copied from. The
-//! completion only copies fully-known patches, so excluded pixels are handed to it as
-//! unknown and restored afterwards; only the real hole keeps the synthesised values.
+//! Photoshop 25.4 was measured as a black box (synthetic and public-domain images, results read
+//! back exactly; none of its code or assets were used):
+//!
+//! * **Sampling window** ([`sampling_window`]): the fill copies only from a square centred on the
+//! selection's bounding box, of side `4·√(max(w, 50)·max(h, 50))`: four times a square
+//! selection's side, 200 px at least, and for a long thin selection four times the geometric
+//! mean of its sides. At the canvas edge the square slides inwards rather than being cut. Pixels
+//! outside it never change the result (Edit › Fill and the workspace's Rectangular area alike).
+//! * **Auto sampling area** ([`auto_sampling`]): the workspace's default keeps, within that
+//! square, only what looks like the selection's surroundings: a region of another brightness or
+//! another texture is left out along its edges, wherever it lies (a bright band through the
+//! window is excluded, the matching area beyond it is not).
+//! * **The fill** copies pieces of the sampling area pixel for pixel (15–40 px across), joined by
+//! seams a few pixels wide: see [`crate::inpaint`].
+//! * **Colour adaptation** None / Default / High / Very High: with None the copies are exact; the
+//! others let each copied patch take a gain and a bias towards its surroundings, more at each
+//! level ([`color_level`]). The patch transform is that of S. Darabi et al., *Image Melding*,
+//! SIGGRAPH 2012.
//! * **Rotation / scale / mirror adaptation**: the sampling window is extended with rotated,
-//! rescaled and mirrored copies of itself, laid out side by side (separated by unknown gaps
-//! wider than a patch), so the patch search can pick transformed source patches, as in
-//! the generalised PatchMatch of C. Barnes, E. Shechtman, D. B. Goldman, A. Finkelstein,
-//! *The Generalized PatchMatch Correspondence Algorithm*, ECCV 2010 (which searches over
-//! rotations and scales; we enumerate a small set instead).
-//! * **Colour adaptation**: the low frequencies of the fill are pulled towards the smooth
-//! membrane interpolation of the hole boundary (P. Pérez, M. Gangnet, A. Blake, *Poisson
-//! Image Editing*, SIGGRAPH 2003 uses the same membrane for seamless cloning), which corrects
-//! gradual brightness and colour changes across the hole while keeping the copied texture.
+//! rescaled and mirrored copies of itself, laid out side by side (separated by gaps that are no
+//! image at all), so the patch search can pick transformed source patches, as in the
+//! generalised PatchMatch of C. Barnes, E. Shechtman, D. B. Goldman, A. Finkelstein, *The
+//! Generalized PatchMatch Correspondence Algorithm*, ECCV 2010 (which searches over rotations
+//! and scales; we enumerate a small set instead).
//!
//! Buffers are interleaved `w × h × ch` normalised floats (any model/depth); deterministic.
-use crate::inpaint::{CompleteParams, complete_with};
+use photocraft_geom::Rect;
+
+use crate::inpaint::{Adapt, CompleteParams, Px, complete_masked};
use crate::poisson::membrane_fill_with;
/// Options for [`fill`].
#[derive(Clone, Debug, PartialEq)]
pub struct FillOptions {
- /// Colour adaptation strength `0..=1` (Photoshop: none 0, default ≈0.35, high, very high).
- pub color_adaptation: f32,
+ /// Colour adaptation of the copies ([`color_level`]).
+ pub color_adaptation: Adapt,
/// Extra source rotations in degrees (Photoshop's rotation adaptation levels).
pub rotations: Vec<f32>,
/// Add downscaled and upscaled source copies.
@@ -36,7 +49,7 @@ pub struct FillOptions {
impl Default for FillOptions {
fn default() -> Self {
- Self { color_adaptation: 0.35, rotations: Vec::new(), scale: false, mirror: false, seed: 1 }
+ Self { color_adaptation: color_level("default"), rotations: Vec::new(), scale: false, mirror: false, seed: 1 }
}
}
@@ -51,16 +64,43 @@ pub fn rotation_level(level: &str) -> Vec<f32> {
}
}
-/// Colour adaptation strength for Photoshop's levels: none, default, high, veryHigh.
-pub fn color_level(level: &str) -> f32 {
+/// Colour adaptation for Photoshop's levels: none, default, high, veryHigh. Measured on a texture
+/// under a brightness ramp: with None the copies are exact; Default shifts them by up to about
+/// 10/255, High about 20, Very High about 35, scaling their contrast a little more at each level.
+pub fn color_level(level: &str) -> Adapt {
match level {
- "none" => 0.0,
- "high" => 0.65,
- "veryHigh" => 0.9,
- _ => 0.35,
+ "none" => Adapt::NONE,
+ "high" => Adapt { gain: (0.8, 1.25), bias: 0.08 },
+ "veryHigh" => Adapt { gain: (0.67, 1.5), bias: 0.14 },
+ _ => Adapt { gain: (0.9, 1.1), bias: 0.04 },
}
}
+/// Photoshop's sampling window for a selection with bounding box `hole`: the square of side
+/// `4·√(max(w, 50)·max(h, 50))` centred on it, slid inside `canvas` (and clipped to it only where
+/// the canvas is smaller than the square). A selection longer than that square (more than 16
+/// times as long as it is wide, which was not measured) keeps its whole length.
+pub fn sampling_window(hole: Rect, canvas: Rect) -> Rect {
+ if hole.is_empty() || canvas.is_empty() {
+ return Rect::EMPTY;
+ }
+ let (w, h) = (f64::from(hole.width().max(50)), f64::from(hole.height().max(50)));
+ let side = (4.0 * (w * h).sqrt()).round().min(i32::MAX as f64) as i64;
+ // Twice the centre, so that odd sizes stay exact.
+ let span = |c2: i64, extent: u32, lo: i32, hi: i32| -> (i32, i32) {
+ let (lo, hi) = (i64::from(lo), i64::from(hi));
+ let side = side.max(i64::from(extent));
+ if side >= hi - lo {
+ return (lo as i32, hi as i32);
+ }
+ let a = ((c2 - side) / 2).clamp(lo, hi - side);
+ (a as i32, (a + side) as i32)
+ };
+ let (x0, x1) = span(i64::from(hole.x0) + i64::from(hole.x1), hole.width(), canvas.x0, canvas.x1);
+ let (y0, y1) = span(i64::from(hole.y0) + i64::from(hole.y1), hole.height(), canvas.y0, canvas.y1);
+ Rect::new(x0, y0, x1, y1)
+}
+
/// One source variant: pixels and which of them are usable.
struct Variant {
w: usize,
@@ -132,31 +172,6 @@ fn variant(src: Src, deg: f32, scale: f32, mirror: bool) -> Variant {
out
}
-/// Separable box blur of radius `r` (edge-clamped).
-fn box_blur(w: usize, h: usize, ch: usize, v: &[f32], r: usize) -> Vec<f32> {
- if r == 0 {
- return v.to_vec();
- }
- let pass = |src: &[f32], horizontal: bool| -> Vec<f32> {
- let mut dst = vec![0.0f32; src.len()];
- let (n, m) = if horizontal { (h, w) } else { (w, h) };
- let idx = |line: usize, k: usize| if horizontal { line * w + k } else { k * w + line };
- let norm = 1.0 / (2 * r + 1) as f32;
- for line in 0..n {
- for c in 0..ch {
- let at = |k: i64| src[idx(line, k.clamp(0, m as i64 - 1) as usize) * ch + c];
- let mut acc: f32 = (-(r as i64)..=r as i64).map(at).sum();
- for k in 0..m {
- dst[idx(line, k) * ch + c] = acc * norm;
- acc += at(k as i64 + r as i64 + 1) - at(k as i64 - r as i64);
- }
- }
- }
- dst
- };
- pass(&pass(v, true), false)
-}
-
/// Fill `hole` in `img`, copying only from pixels where `source` is true (and not in the hole).
/// Returns the full buffer (unchanged outside the hole). Falls back to the membrane fill when
/// nothing can be sampled.
@@ -183,7 +198,7 @@ pub fn fill_with(
if !hole.iter().any(|h| *h) {
return Ok(img.to_vec());
}
- let params = CompleteParams { seed: opts.seed, ..Default::default() };
+ let params = CompleteParams { seed: opts.seed, adapt: opts.color_adaptation, ..Default::default() };
let gap = 2 * params.patch_radius + 2;
let ok: Vec<bool> = hole.iter().zip(source).map(|(h, s)| !h && *s).collect();
let src = Src { w, h, ch, img, ok: &ok };
@@ -199,18 +214,24 @@ pub fn fill_with(
extra.push(variant(src, 0.0, 0.8, false));
extra.push(variant(src, 0.0, 1.25, false));
}
- // Mosaic: identity at the left, variants in a column to its right.
+ // Mosaic: identity at the left, variants in a column to its right, gaps that are no image.
let col_w = extra.iter().map(|v| v.w).max().unwrap_or(0);
let col_h: usize = extra.iter().map(|v| v.h + gap).sum();
let mw = if extra.is_empty() { w } else { w + gap + col_w };
let mh = h.max(col_h);
let mut mimg = vec![0.0f32; mw * mh * ch];
- let mut unknown = vec![true; mw * mh];
+ let mut roles = vec![Px::Void; mw * mh];
for y in 0..h {
for x in 0..w {
let (s, d) = (y * w + x, y * mw + x);
mimg[d * ch..(d + 1) * ch].copy_from_slice(&img[s * ch..(s + 1) * ch]);
- unknown[d] = !ok[s];
+ roles[d] = if hole[s] {
+ Px::Hole
+ } else if ok[s] {
+ Px::Source
+ } else {
+ Px::Known
+ };
}
}
let mut oy = 0;
@@ -219,16 +240,18 @@ pub fn fill_with(
for x in 0..v.w {
let (s, d) = (y * v.w + x, (oy + y) * mw + w + gap + x);
mimg[d * ch..(d + 1) * ch].copy_from_slice(&v.img[s * ch..(s + 1) * ch]);
- unknown[d] = !v.ok[s];
+ if v.ok[s] {
+ roles[d] = Px::Source;
+ }
}
}
oy += v.h + gap;
}
ctl.check()?;
- // The completion is nearly all the work: it reports 0–90 %.
+ // The completion is nearly all the work.
let cancel = || ctl.cancelled();
- let progress = |f: f32| ctl.progress(f * 0.9);
- let filled = complete_with(mw, mh, ch, &mimg, &unknown, &params, &photocraft_raster::Interrupt::new(&cancel, &progress))?;
+ let progress = |f: f32| ctl.progress(f * 0.99);
+ let filled = complete_masked(mw, mh, ch, &mimg, &roles, &params, &photocraft_raster::Interrupt::new(&cancel, &progress))?;
let mut out = img.to_vec();
match filled {
Some(f) => {
@@ -244,47 +267,203 @@ pub fn fill_with(
None => out = membrane_fill_with(w, h, ch, img, hole, ctl)?,
}
ctl.check()?;
- if opts.color_adaptation > 0.0 {
- adapt_colors(w, h, ch, img, hole, &mut out, opts.color_adaptation, ctl)?;
- }
ctl.progress(1.0);
Ok(out)
}
-/// Pull the fill's low frequencies towards the membrane interpolation of the hole boundary.
-#[allow(clippy::too_many_arguments)]
-fn adapt_colors(
- w: usize,
- h: usize,
- ch: usize,
- img: &[f32],
- hole: &[bool],
- out: &mut [f32],
- k: f32,
- ctl: &photocraft_raster::Interrupt,
-) -> Result<(), photocraft_raster::Cancelled> {
- let (mut x0, mut y0, mut x1, mut y1) = (w, h, 0, 0);
+/// Box mean of radius `r` over a `w × h` plane (edge-clamped), by summed areas.
+fn box_mean(w: usize, h: usize, v: &[f32], r: usize) -> Vec<f32> {
+ let w1 = w + 1;
+ let mut s = vec![0.0f64; w1 * (h + 1)];
+ for y in 0..h {
+ let mut row = 0.0f64;
+ for x in 0..w {
+ row += f64::from(v[y * w + x]);
+ s[(y + 1) * w1 + x + 1] = s[y * w1 + x + 1] + row;
+ }
+ }
+ let mut out = vec![0.0f32; w * h];
+ for y in 0..h {
+ let (y0, y1) = (y.saturating_sub(r), (y + r + 1).min(h));
+ for x in 0..w {
+ let (x0, x1) = (x.saturating_sub(r), (x + r + 1).min(w));
+ let sum = s[y1 * w1 + x1] + s[y0 * w1 + x0] - s[y0 * w1 + x1] - s[y1 * w1 + x0];
+ out[y * w + x] = (sum / ((x1 - x0) * (y1 - y0)) as f64) as f32;
+ }
+ }
+ out
+}
+
+/// Largest side [`auto_sampling`] works at: bigger windows are segmented at a reduced scale.
+const AUTO_SIDE: usize = 384;
+
+/// Content-Aware Fill's Auto sampling area within a window (the whole `w × h` buffer): the pixels
+/// that look like the hole's surroundings. Each pixel is described by its local mean colour and
+/// local contrast (7 × 7); the ring around the hole is summarised by a few clusters of those; a
+/// pixel near a cluster prefers to be sampled, one far from all of them not, and one min cut
+/// (contrast-sensitive, so the boundary follows edges) settles the area. Returns the mask of
+/// pixels that may be copied from (never the hole). Falls back to everything outside the hole
+/// when the area would be too small to copy from.
+pub fn auto_sampling(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool]) -> Vec<bool> {
+ use crate::segment::{FREE, HARD_FG, RgbImage, grid_cut_with};
+ assert_eq!(img.len(), w * h * ch);
+ assert_eq!(hole.len(), w * h);
+ let everything: Vec<bool> = hole.iter().map(|h| !h).collect();
+ if w == 0 || h == 0 || ch == 0 || !hole.iter().any(|h| *h) {
+ return everything;
+ }
+ // Work at a reduced scale for big windows (the area is smooth at this scale).
+ let k = w.max(h).div_ceil(AUTO_SIDE).max(1);
+ let (sw, sh) = (w.div_ceil(k), h.div_ceil(k));
+ let nc = ch.min(3);
+ let mut planes = vec![vec![0.0f32; sw * sh]; nc];
+ let mut shole = vec![false; sw * sh];
+ let mut cnt = vec![0.0f32; sw * sh];
for y in 0..h {
for x in 0..w {
- if hole[y * w + x] {
- (x0, y0, x1, y1) = (x0.min(x), y0.min(y), x1.max(x + 1), y1.max(y + 1));
+ let i = (y / k) * sw + x / k;
+ let p = y * w + x;
+ if hole[p] {
+ shole[i] = true;
+ }
+ for (c, pl) in planes.iter_mut().enumerate() {
+ pl[i] += img[p * ch + c];
}
+ cnt[i] += 1.0;
}
}
- let r = ((x1 - x0).max(y1 - y0) / 6).clamp(1, 32);
- let membrane = membrane_fill_with(w, h, ch, img, hole, ctl)?;
- ctl.progress(0.97);
- ctl.check()?;
- let low = box_blur(w, h, ch, out, r);
- for (i, &hl) in hole.iter().enumerate() {
- if hl {
- for c in 0..ch {
- let j = i * ch + c;
- out[j] = (out[j] + k * (membrane[j] - low[j])).clamp(0.0, 1.0);
+ for pl in &mut planes {
+ pl.iter_mut().zip(&cnt).for_each(|(v, n)| *v /= n.max(1.0));
+ }
+ // Features: local means and local contrast (of the luma-ish average of the colour planes).
+ let r = 3;
+ let means: Vec<Vec<f32>> = planes.iter().map(|p| box_mean(sw, sh, p, r)).collect();
+ let luma: Vec<f32> = (0..sw * sh).map(|i| planes.iter().map(|p| p[i]).sum::<f32>() / nc as f32).collect();
+ let luma2: Vec<f32> = luma.iter().map(|v| v * v).collect();
+ let (lm, lm2) = (box_mean(sw, sh, &luma, r), box_mean(sw, sh, &luma2, r));
+ let contrast: Vec<f32> = lm.iter().zip(&lm2).map(|(m, m2)| (m2 - m * m).max(0.0).sqrt()).collect();
+ let nf = nc + 1;
+ let feat = |i: usize, out: &mut [f32]| {
+ for (c, m) in means.iter().enumerate() {
+ out[c] = m[i];
+ }
+ out[nc] = 2.0 * contrast[i];
+ };
+ // The ring: outside the hole, within a few pixels of it.
+ let dist = crate::selection::edt(&shole, sw, sh);
+ let ring_w = 6.0f32 / k as f32 + 1.0;
+ let ring: Vec<usize> = (0..sw * sh).filter(|&i| !shole[i] && dist[i] <= ring_w).collect();
+ if ring.is_empty() {
+ return everything;
+ }
+ // A few cluster centres of the ring's features (k-means, deterministic start).
+ let kc = 6.min(ring.len());
+ let mut f = vec![0.0f32; nf];
+ let mut centres: Vec<Vec<f32>> = (0..kc)
+ .map(|j| {
+ feat(ring[j * ring.len() / kc], &mut f);
+ f.clone()
+ })
+ .collect();
+ let d2 = |a: &[f32], b: &[f32]| a.iter().zip(b).map(|(x, y)| (x - y) * (x - y)).sum::<f32>();
+ for _ in 0..8 {
+ let mut acc = vec![vec![0.0f32; nf]; kc];
+ let mut n = vec![0usize; kc];
+ for &i in &ring {
+ feat(i, &mut f);
+ let j = (0..kc).min_by(|&a, &b| d2(&f, &centres[a]).total_cmp(&d2(&f, &centres[b]))).unwrap_or(0);
+ acc[j].iter_mut().zip(&f).for_each(|(a, v)| *a += v);
+ n[j] += 1;
+ }
+ for j in 0..kc {
+ if n[j] > 0 {
+ centres[j] = acc[j].iter().map(|v| v / n[j] as f32).collect();
}
}
}
- Ok(())
+ let nearest = |i: usize, f: &mut [f32]| -> f32 {
+ feat(i, f);
+ centres.iter().map(|c| d2(f, c)).fold(f32::INFINITY, f32::min).sqrt()
+ };
+ // How much the ring itself varies around its clusters sets the scale of "similar".
+ let mut spread: Vec<f32> = ring.iter().map(|&i| nearest(i, &mut f)).collect();
+ let q = (spread.len() * 9 / 10).min(spread.len() - 1);
+ let (_, s90, _) = spread.select_nth_unstable_by(q, |a, b| a.total_cmp(b));
+ let tau = (*s90 * 1.6).max(0.03);
+ let mut cost_fg = vec![0.0f32; sw * sh];
+ let mut cost_bg = vec![0.0f32; sw * sh];
+ let mut fixed = vec![FREE; sw * sh];
+ for i in 0..sw * sh {
+ if shole[i] || dist[i] <= 1.5 {
+ fixed[i] = HARD_FG;
+ continue;
+ }
+ let d = nearest(i, &mut f) / tau;
+ cost_fg[i] = d * d;
+ cost_bg[i] = 1.0;
+ }
+ let rgb = RgbImage::from_fn(sw, sh, |x, y| {
+ let i = y * sw + x;
+ let c = |j: usize| means[j.min(nc - 1)][i];
+ [c(0), c(1), c(2)]
+ });
+ // Contrast-sensitive smoothness (the weight of a squared colour difference). The scale of
+ // "similar" and this weight were fitted to Photoshop's Auto overlays (mean IoU 0.92 on ten
+ // synthetic and public-domain cases).
+ let area = grid_cut_with(&rgb, &cost_fg, &cost_bg, &fixed, |d2| 8.0 * (-d2 / (2.0 * 0.05 * 0.05)).exp() + 0.05);
+ let mut out = vec![false; w * h];
+ for y in 0..h {
+ for x in 0..w {
+ let i = y * w + x;
+ out[i] = !hole[i] && area[(y / k) * sw + x / k];
+ }
+ }
+ // Too little to copy from (fewer source pixels than twice the hole): sample everything.
+ let n_hole = hole.iter().filter(|h| **h).count();
+ if out.iter().filter(|o| **o).count() < 2 * n_hole.max(64) {
+ return everything;
+ }
+ out
+}
+
+/// The Patch Tool's and the Content-Aware Move Tool's Color option (0–10) as the colour adaptation
+/// of the copied content. Measured on Photoshop 25.4 with content brighter than its new place: 0
+/// keeps it as it is; 3 moves it about 0.12 (32 of 42 levels, and 31 of 102: a limit, not a
+/// fraction), 6 about 80 % of 42 levels, 10 most of the way (35 of 42, 95 of 102). So the shift is
+/// limited to about `0.04 · color`, the contrast change likewise widening.
+pub fn color_amount(color: u8) -> Adapt {
+ if color == 0 {
+ return Adapt::NONE;
+ }
+ let c = f32::from(color.min(10));
+ Adapt { gain: (1.0 - 0.033 * c, 1.0 + 0.05 * c), bias: 0.04 * c }
+}
+
+/// Gain and bias per channel taking the samples `from` to the level and contrast of the samples
+/// `to` (both interleaved, `ch` per sample), within `a`: how copied content is fitted to its new
+/// surroundings.
+pub fn level_transform(ch: usize, from: &[f32], to: &[f32], a: Adapt) -> Vec<(f32, f32)> {
+ let moments = |v: &[f32], c: usize| {
+ let (mut s, mut s2, mut n) = (0.0f64, 0.0f64, 0.0f64);
+ for x in v.chunks_exact(ch.max(1)) {
+ s += f64::from(x[c]);
+ s2 += f64::from(x[c]) * f64::from(x[c]);
+ n += 1.0;
+ }
+ (s, s2, n)
+ };
+ (0..ch)
+ .map(|c| {
+ let (fs, fs2, fnn) = moments(from, c);
+ let (ts, ts2, tn) = moments(to, c);
+ if a.is_none() || fnn == 0.0 || tn == 0.0 {
+ return (1.0, 0.0);
+ }
+ // Both sets scaled to the same count for the fit.
+ let k = fnn / tn;
+ crate::inpaint::fit(a, fnn as f32, (ts * k) as f32, (ts2 * k) as f32, fs as f32, fs2 as f32)
+ })
+ .collect()
}
#[cfg(test)]
@@ -323,7 +502,7 @@ mod tests {
let (w, h) = (48, 32);
let (img, hole) = stripes(w, h);
let src = vec![true; w * h];
- let out = fill(w, h, 1, &img, &hole, &src, &FillOptions { color_adaptation: 0.0, ..Default::default() });
+ let out = fill(w, h, 1, &img, &hole, &src, &FillOptions { color_adaptation: Adapt::NONE, ..Default::default() });
for i in 0..w * h {
if !hole[i] {
assert_eq!(out[i], img[i]);
@@ -341,7 +520,7 @@ mod tests {
let img: Vec<f32> = (0..w * h).map(|i| if i % w < 20 { 0.1 } else { 0.9 }).collect();
let hole: Vec<bool> = (0..w * h).map(|i| (16..24).contains(&(i % w)) && (6..14).contains(&(i / w))).collect();
let right: Vec<bool> = (0..w * h).map(|i| i % w >= 24).collect();
- let out = fill(w, h, 1, &img, &hole, &right, &FillOptions { color_adaptation: 0.0, ..Default::default() });
+ let out = fill(w, h, 1, &img, &hole, &right, &FillOptions { color_adaptation: Adapt::NONE, ..Default::default() });
let mean: f32 = (0..w * h).filter(|i| hole[*i]).map(|i| out[i]).sum::<f32>() / 64.0;
assert!(mean > 0.8, "mean {mean}");
}
@@ -352,7 +531,7 @@ mod tests {
let (img, hole) = stripes(w, h);
let rgb: Vec<f32> = img.iter().flat_map(|v| [*v, *v * 0.5, 1.0 - *v]).collect();
let src = vec![true; w * h];
- let opts = FillOptions { color_adaptation: 0.65, rotations: rotation_level("low"), scale: true, mirror: true, seed: 7 };
+ let opts = FillOptions { color_adaptation: color_level("high"), rotations: rotation_level("low"), scale: true, mirror: true, seed: 7 };
let a = fill(w, h, 3, &rgb, &hole, &src, &opts);
let b = fill(w, h, 3, &rgb, &hole, &src, &opts);
assert_eq!(a, b);
@@ -366,11 +545,127 @@ mod tests {
let img: Vec<f32> = (0..w * h).map(|i| (i % w) as f32 / w as f32).collect();
let hole: Vec<bool> = (0..w * h).map(|i| (14..26).contains(&(i % w)) && (5..15).contains(&(i / w))).collect();
let src = vec![true; w * h];
- let out = fill(w, h, 1, &img, &hole, &src, &FillOptions { color_adaptation: 0.9, ..Default::default() });
+ let out = fill(w, h, 1, &img, &hole, &src, &FillOptions { color_adaptation: color_level("veryHigh"), ..Default::default() });
let err: f32 = (0..w * h).filter(|i| hole[*i]).map(|i| (out[i] - img[i]).abs()).sum::<f32>() / 120.0;
assert!(err < 0.12, "mean error {err}");
}
+ /// I.i.d. noise: every value occurs once, so a filled pixel equal to an image pixel was copied.
+ fn noise(w: usize, h: usize, seed: u64) -> Vec<f32> {
+ let mut z = seed;
+ (0..w * h * 3)
+ .map(|_| {
+ z = z.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
+ 0.2 + 0.6 * ((z >> 40) as f32 / (1u64 << 24) as f32)
+ })
+ .collect()
+ }
+
+ #[test]
+ fn sampling_window_is_photoshops() {
+ let canvas = Rect::new(0, 0, 800, 800);
+ let sq = |x0: i32, y0: i32, w: i32, h: i32| Rect::new(x0, y0, x0 + w, y0 + h);
+ // Photoshop 25.4's sampling overlay: a square of side 4·√(max(w,50)·max(h,50)) centred on
+ // the selection's bounds.
+ assert_eq!(sampling_window(sq(375, 375, 50, 50), canvas), sq(300, 300, 200, 200));
+ assert_eq!(sampling_window(sq(350, 350, 100, 100), canvas), sq(200, 200, 400, 400));
+ assert_eq!(sampling_window(sq(395, 395, 10, 10), canvas), sq(300, 300, 200, 200));
+ assert_eq!(sampling_window(sq(370, 370, 60, 60), canvas), sq(280, 280, 240, 240));
+ // Long selections (Photoshop's overlay, read off the screen to a pixel: 281, 399, 691).
+ assert_eq!(sampling_window(sq(350, 385, 100, 30), canvas), sq(258, 258, 283, 283));
+ assert_eq!(sampling_window(sq(300, 375, 200, 50), canvas), sq(200, 200, 400, 400));
+ assert_eq!(sampling_window(sq(250, 350, 300, 100), canvas), sq(53, 53, 693, 693));
+ // At the canvas edge the square slides inwards rather than being cut.
+ assert_eq!(sampling_window(sq(10, 375, 50, 50), canvas), sq(0, 300, 200, 200));
+ assert_eq!(sampling_window(sq(5, 5, 60, 60), canvas), sq(0, 0, 240, 240));
+ // A canvas smaller than the square clips it; a very long selection keeps its length.
+ assert_eq!(sampling_window(sq(40, 40, 50, 50), Rect::new(0, 0, 150, 120)), Rect::new(0, 0, 150, 120));
+ assert_eq!(sampling_window(sq(100, 995, 1800, 10), Rect::new(0, 0, 2000, 2000)), sq(100, 400, 1800, 1200));
+ assert_eq!(sampling_window(Rect::EMPTY, canvas), Rect::EMPTY);
+ }
+
+ #[test]
+ fn auto_sampling_keeps_what_looks_like_the_surroundings() {
+ // Grey texture, dark on the left, 50 levels brighter on the right; the hole is in the dark
+ // part near the boundary (Photoshop's Auto leaves the bright part out).
+ let (w, h) = (200, 200);
+ let tex = noise(w, h, 3);
+ let shade = |x: usize, band: bool| {
+ if band {
+ if (130..150).contains(&x) { 0.55 } else { 0.35 }
+ } else if x < 135 {
+ 0.35
+ } else {
+ 0.55
+ }
+ };
+ for band in [false, true] {
+ let img: Vec<f32> = (0..w * h * 3).map(|i| shade((i / 3) % w, band) + (tex[i] - 0.5) * 0.1).collect();
+ let hole: Vec<bool> = (0..w * h).map(|i| (75..125).contains(&(i % w)) && (75..125).contains(&(i / w))).collect();
+ let area = auto_sampling(w, h, 3, &img, &hole);
+ let frac = |x0: usize, x1: usize| {
+ let n = (0..w * h).filter(|i| (x0..x1).contains(&(i % w)) && !hole[*i]).count();
+ (0..w * h).filter(|i| (x0..x1).contains(&(i % w)) && area[*i]).count() as f32 / n as f32
+ };
+ assert!(hole.iter().zip(&area).all(|(hl, a)| !(*hl && *a)), "never the hole");
+ assert!(frac(0, 125) > 0.95, "the dark side is sampled ({})", frac(0, 125));
+ if band {
+ // A bright band through the window is left out; the dark area beyond it is not.
+ assert!(frac(133, 147) < 0.05, "the band is excluded ({})", frac(133, 147));
+ assert!(frac(155, 200) > 0.9, "beyond the band is sampled ({})", frac(155, 200));
+ } else {
+ assert!(frac(140, 200) < 0.05, "the bright side is excluded ({})", frac(140, 200));
+ }
+ }
+ }
+
+ #[test]
+ fn without_colour_adaptation_the_fill_copies_pixels_exactly() {
+ // A smooth texture with fine noise, so that every value is unique: a filled pixel equal to
+ // an image pixel was copied from it. Photoshop's fill (colour adaptation None) is such
+ // copies, joined by narrow seams.
+ let (w, h) = (120, 120);
+ let fine = noise(w, h, 9);
+ let img: Vec<f32> = (0..w * h * 3)
+ .map(|i| {
+ let (x, y, c) = (((i / 3) % w) as f32, ((i / 3) / w) as f32, i % 3);
+ 0.5 + 0.2 * (x * 0.21 + c as f32).sin() * (y * 0.17).cos() + 0.1 * (x * 0.05 - y * 0.08).sin() + (fine[i] - 0.5) * 0.08
+ })
+ .collect();
+ let hole: Vec<bool> = (0..w * h).map(|i| (40..80).contains(&(i % w)) && (40..80).contains(&(i / w))).collect();
+ // Votes of identical copies average to the copy up to float rounding.
+ let key = |v: &[f32], i: usize| [0, 1, 2].map(|c| (v[i * 3 + c] * 1e5).round() as i64);
+ let known: std::collections::HashSet<[i64; 3]> = (0..w * h).filter(|i| !hole[*i]).map(|i| key(&img, i)).collect();
+ let out = fill(w, h, 3, &img, &hole, &vec![true; w * h], &FillOptions { color_adaptation: Adapt::NONE, ..Default::default() });
+ let exact = (0..w * h).filter(|i| hole[*i] && known.contains(&key(&out, *i))).count();
+ assert!(exact as f32 > 0.2 * 1600.0, "{exact} of 1600 filled pixels are exact copies");
+ // And the fill is as busy as the noise around it, not a blur of it.
+ let lap = |v: &[f32], x: usize, y: usize| {
+ let p = |x: usize, y: usize| v[(y * w + x) * 3];
+ (4.0 * p(x, y) - p(x - 1, y) - p(x + 1, y) - p(x, y - 1) - p(x, y + 1)).abs()
+ };
+ let mean = |inside: bool| {
+ let pts: Vec<(usize, usize)> = (1..h - 1).flat_map(|y| (1..w - 1).map(move |x| (x, y))).filter(|&(x, y)| hole[y * w + x] == inside).collect();
+ pts.iter().map(|&(x, y)| lap(&out, x, y)).sum::<f32>() / pts.len() as f32
+ };
+ assert!(mean(true) > 0.6 * mean(false), "fill detail {} against {}", mean(true), mean(false));
+ }
+
+ #[test]
+ fn patch_color_shifts_up_to_about_four_hundredths_per_step() {
+ // Content 0.4 brighter than where it lands (Photoshop's Patch, Color 3 and 10).
+ let from: Vec<f32> = (0..300).map(|i| 0.7 + 0.05 * ((i % 7) as f32 / 7.0)).collect();
+ let to: Vec<f32> = from.iter().map(|v| v - 0.4).collect();
+ let level = from.iter().sum::<f32>() / 300.0;
+ let shift = |c: u8| {
+ let gb = level_transform(1, &from, &to, color_amount(c));
+ level - from.iter().map(|v| gb[0].0 * v + gb[0].1).sum::<f32>() / 300.0
+ };
+ assert_eq!(shift(0), 0.0);
+ assert!((shift(3) - 0.12).abs() < 0.01, "{}", shift(3));
+ assert!((shift(10) - 0.4).abs() < 0.01, "{}", shift(10));
+ }
+
#[test]
fn variant_geometry() {
let img = vec![0.5f32; 10 * 6];
diff --git a/crates/algo/src/inpaint.rs b/crates/algo/src/inpaint.rs
index 6708c9429..4f485ad46 100644
--- a/crates/algo/src/inpaint.rs
+++ b/crates/algo/src/inpaint.rs
@@ -1,13 +1,28 @@
-//! Hole filling for Spot Healing: patch-based completion, proximity match and texture synthesis.
+//! Hole filling for Content-Aware Fill and Spot Healing: patch-based completion, proximity match
+//! and texture synthesis.
//!
//! * [`complete`], content-aware fill: the multi-scale "space-time completion" EM scheme of
//! Y. Wexler, E. Shechtman, M. Irani, *Space-Time Completion of Video*, IEEE TPAMI 2007, with the
//! nearest-neighbour field computed by C. Barnes, E. Shechtman, A. Finkelstein, D. B. Goldman,
//! *PatchMatch: A Randomized Correspondence Algorithm for Structural Image Editing*, SIGGRAPH 2009
//! (random init, propagation, exponentially shrinking random search). Each EM iteration finds, for
-//! every patch overlapping the hole, its most similar fully-known patch, then re-estimates hole
-//! pixels by a similarity-weighted vote of the overlapping matches. Coarse-to-fine over an image
-//! pyramid (the coarsest level is initialised by membrane interpolation), so large holes stay cheap.
+//! every patch overlapping the hole, its most similar source patch, then re-estimates hole pixels
+//! by a similarity-weighted vote of the overlapping matches. Coarse to fine over an image pyramid
+//! (down to where the hole is about four patches across): the coarsest level starts by filling
+//! the hole from its edge inwards, ring by ring, each pixel from the patch that best matches what
+//! is known around it (rather than from a smooth membrane, which draws the fill towards flat
+//! areas); every finer level starts from the coarser level's matches scaled up and voted with the
+//! finer level's own pixels, so the texture stays sharp. Where neighbouring patches agree on their
+//! source (the usual case), the vote copies the source pixels exactly; only along the seams
+//! between copied pieces does it blend.
+//!
+//! This is what Photoshop's Content-Aware Fill does, measured as a black box on Photoshop 25.4
+//! (see `content_aware`): with colour adaptation off its fill is pieces of the image copied pixel
+//! for pixel, typically 15–40 px across, joined by seams a few pixels wide; with colour
+//! adaptation the copies come with a gain and bias. That is the patch transform of S. Darabi,
+//! E. Shechtman, C. Barnes, D. B. Goldman, P. Sen, *Image Melding: Combining Inconsistent Images
+//! using Patch-based Synthesis*, SIGGRAPH 2012: each source patch may be scaled and offset per
+//! channel to match its target, within limits ([`Adapt`]), and is voted in adjusted.
//! * [`best_offset`], proximity match: the single displacement whose surrounding ring best matches the
//! ring around the hole (sum of squared differences), i.e. an automatic Healing Brush source.
//! * [`synthesize`], create texture: patch-based texture synthesis in the style of A. Efros,
@@ -50,6 +65,30 @@ impl Rng {
}
}
+/// How far a copied patch may be adjusted to its target, per channel: `gain · source + bias`, the
+/// gain within `gain` and the bias within `±bias` (Image Melding's photometric transform). The
+/// gain is the ratio of the patches' standard deviations, the bias what then matches their means.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Adapt {
+ pub gain: (f32, f32),
+ pub bias: f32,
+}
+
+impl Adapt {
+ /// Copies are taken as they are.
+ pub const NONE: Adapt = Adapt { gain: (1.0, 1.0), bias: 0.0 };
+
+ pub fn is_none(&self) -> bool {
+ self.gain == (1.0, 1.0) && self.bias == 0.0
+ }
+}
+
+impl Default for Adapt {
+ fn default() -> Self {
+ Self::NONE
+ }
+}
+
/// Parameters for [`complete`].
#[derive(Clone, Debug, PartialEq)]
pub struct CompleteParams {
@@ -60,49 +99,71 @@ pub struct CompleteParams {
pub min_em_iters: usize,
/// PatchMatch passes per EM iteration.
pub pm_iters: usize,
- /// Levels where the hole is wider than this (in that level's pixels) only *refine* the upsampled
- /// match field (one local PatchMatch pass and one vote), which keeps big holes tractable: the
- /// structure is decided at coarse scale, fine levels just add detail.
+ /// Levels where the hole is wider than this (in that level's pixels) only *refine* the
+ /// scaled-up match field (one local PatchMatch pass and one vote), which keeps big holes
+ /// tractable: the structure is decided at coarse scale, fine levels just add detail.
pub refine_extent: usize,
+ /// Colour adaptation of the copies.
+ pub adapt: Adapt,
pub seed: u64,
}
impl Default for CompleteParams {
fn default() -> Self {
- Self { patch_radius: 3, em_iters: 8, min_em_iters: 2, pm_iters: 2, refine_extent: 96, seed: 1 }
+ Self { patch_radius: 3, em_iters: 10, min_em_iters: 3, pm_iters: 2, refine_extent: 192, adapt: Adapt::NONE, seed: 1 }
}
}
+/// What a pixel is to [`complete_masked`].
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Px {
+ /// Not part of the image (a gap, or outside a transformed copy): ignored.
+ Void,
+ /// Known, part of the context the fill must agree with, but not copied from.
+ Known,
+ /// Known and may be copied from.
+ Source,
+ /// To be filled.
+ Hole,
+}
+
/// One pyramid level.
#[derive(Clone)]
struct Level {
w: usize,
h: usize,
img: Vec<f32>,
- hole: Vec<bool>,
+ px: Vec<Px>,
}
+/// Half-size level: a cell is a hole if any of its pixels is; else it averages its non-void
+/// pixels, and may be copied from only if all of them may.
fn downsample(l: &Level, ch: usize) -> Level {
let (w, h) = (l.w.div_ceil(2), l.h.div_ceil(2));
let mut img = vec![0.0f32; w * h * ch];
- let mut hole = vec![false; w * h];
+ let mut px = vec![Px::Void; w * h];
for y in 0..h {
for x in 0..w {
let mut n = 0.0f32;
let o = (y * w + x) * ch;
+ let (mut hole, mut all_source, mut any) = (false, true, false);
for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
let (sx, sy) = (x * 2 + dx, y * 2 + dy);
if sx >= l.w || sy >= l.h {
continue;
}
let si = sy * l.w + sx;
- if l.hole[si] {
- hole[y * w + x] = true;
- } else {
- for c in 0..ch {
- img[o + c] += l.img[si * ch + c];
+ match l.px[si] {
+ Px::Hole => hole = true,
+ Px::Void => all_source = false,
+ k => {
+ any = true;
+ all_source &= k == Px::Source;
+ for c in 0..ch {
+ img[o + c] += l.img[si * ch + c];
+ }
+ n += 1.0;
}
- n += 1.0;
}
}
if n > 0.0 {
@@ -110,9 +171,18 @@ fn downsample(l: &Level, ch: usize) -> Level {
img[o + c] /= n;
}
}
+ px[y * w + x] = if hole {
+ Px::Hole
+ } else if !any {
+ Px::Void
+ } else if all_source {
+ Px::Source
+ } else {
+ Px::Known
+ };
}
}
- Level { w, h, img, hole }
+ Level { w, h, img, px }
}
/// Summed-area table of a boolean grid (`(w+1) × (h+1)`).
@@ -154,6 +224,10 @@ fn hole_bbox(w: usize, h: usize, hole: &[bool]) -> Option<(usize, usize, usize,
b
}
+/// A finished coarser level: width, height, pixels and match field (source centre per target,
+/// `i32::MIN` where there is none).
+type Coarser = (usize, usize, Vec<f32>, Vec<(i32, i32)>);
+
/// Per-level PatchMatch/EM state.
struct Solver<'a> {
w: usize,
@@ -161,24 +235,42 @@ struct Solver<'a> {
ch: usize,
r: i32,
img: &'a mut Vec<f32>,
- hole: &'a [bool],
- /// Valid source centres: the whole patch is inside the grid and contains no hole pixel.
+ px: &'a [Px],
+ /// Valid source centres: the whole patch is inside the grid and may be copied from.
valid: Vec<bool>,
valid_list: Vec<(i32, i32)>,
/// Target centres (patch overlaps the hole), row-major.
targets: Vec<bool>,
+ adapt: Adapt,
/// Cancellation: checked per row band; a cancelled solve's output is discarded.
ctl: photocraft_raster::Interrupt<'a>,
}
+/// Gain and bias of one channel for target moments `(Σt, Σt²)` and source moments `(Σs, Σs²)`
+/// over `n` samples, within the limits.
+#[inline]
+pub(crate) fn fit(a: Adapt, n: f32, st: f32, stt: f32, ss: f32, sss: f32) -> (f32, f32) {
+ let (mt, ms) = (st / n, ss / n);
+ let vt = (stt / n - mt * mt).max(0.0);
+ let vs = (sss / n - ms * ms).max(0.0);
+ let g = if vs > 1e-10 { (vt / vs).sqrt() } else { 1.0 };
+ let g = g.clamp(a.gain.0, a.gain.1);
+ let b = (mt - g * ms).clamp(-a.bias, a.bias);
+ (g, b)
+}
+
impl Solver<'_> {
#[inline]
fn is_valid(&self, x: i32, y: i32) -> bool {
x >= 0 && y >= 0 && (x as usize) < self.w && (y as usize) < self.h && self.valid[y as usize * self.w + x as usize]
}
- /// SSD between the (clipped) target patch at `t` and the source patch at `s`, per sample.
+ /// Distance between the target patch at `t` (its pixels inside the grid and not void) and the
+ /// source patch at `s`, per sample; with colour adaptation the source is fitted first.
fn dist(&self, t: (i32, i32), s: (i32, i32), cutoff: f32) -> f32 {
+ if !self.adapt.is_none() {
+ return self.dist_adapted(t, s);
+ }
let (w, h, ch, r) = (self.w as i32, self.h as i32, self.ch, self.r);
let full = ((2 * r + 1) * (2 * r + 1)) as f32 * ch as f32;
let mut sum = 0.0f32;
@@ -191,7 +283,7 @@ impl Solver<'_> {
let sy = s.1 + dy;
for dx in -r..=r {
let tx = t.0 + dx;
- if tx < 0 || tx >= w {
+ if tx < 0 || tx >= w || self.px[ty as usize * self.w + tx as usize] == Px::Void {
continue;
}
let ti = (ty as usize * self.w + tx as usize) * ch;
@@ -210,6 +302,70 @@ impl Solver<'_> {
if n == 0 { f32::INFINITY } else { sum / n as f32 }
}
+ /// Moments of the target patch at `t` and the source patch at `s` per channel:
+ /// `[Σt, Σt², Σs, Σs², Σts]`, and the sample count.
+ fn moments(&self, t: (i32, i32), s: (i32, i32), m: &mut [[f32; 5]]) -> usize {
+ let (w, h, ch, r) = (self.w as i32, self.h as i32, self.ch, self.r);
+ m.iter_mut().for_each(|v| *v = [0.0; 5]);
+ let mut n = 0usize;
+ for dy in -r..=r {
+ let ty = t.1 + dy;
+ if ty < 0 || ty >= h {
+ continue;
+ }
+ let sy = s.1 + dy;
+ for dx in -r..=r {
+ let tx = t.0 + dx;
+ if tx < 0 || tx >= w || self.px[ty as usize * self.w + tx as usize] == Px::Void {
+ continue;
+ }
+ let ti = (ty as usize * self.w + tx as usize) * ch;
+ let si = (sy as usize * self.w + (s.0 + dx) as usize) * ch;
+ for (c, mc) in m.iter_mut().enumerate().take(ch) {
+ let (a, b) = (self.img[ti + c], self.img[si + c]);
+ mc[0] += a;
+ mc[1] += a * a;
+ mc[2] += b;
+ mc[3] += b * b;
+ mc[4] += a * b;
+ }
+ n += 1;
+ }
+ }
+ n
+ }
+
+ fn dist_adapted(&self, t: (i32, i32), s: (i32, i32)) -> f32 {
+ let mut m = [[0.0f32; 5]; 8];
+ let ch = self.ch.min(8);
+ let n = self.moments(t, s, &mut m[..ch]);
+ if n == 0 {
+ return f32::INFINITY;
+ }
+ let nf = n as f32;
+ let mut sum = 0.0f32;
+ for mc in &m[..ch] {
+ let (g, b) = fit(self.adapt, nf, mc[0], mc[1], mc[2], mc[3]);
+ // Σ (t − g s − b)², expanded.
+ sum += mc[1] + g * g * mc[3] + nf * b * b - 2.0 * g * mc[4] - 2.0 * b * mc[0] + 2.0 * g * b * mc[2];
+ }
+ sum.max(0.0) / (nf * ch as f32)
+ }
+
+ /// Gain and bias per channel for the match `t → s` (identity without adaptation).
+ fn transform(&self, t: (i32, i32), s: (i32, i32), out: &mut [(f32, f32)]) {
+ if self.adapt.is_none() {
+ out.iter_mut().for_each(|v| *v = (1.0, 0.0));
+ return;
+ }
+ let mut m = [[0.0f32; 5]; 8];
+ let ch = self.ch.min(8);
+ let n = self.moments(t, s, &mut m[..ch]);
+ for (c, o) in out.iter_mut().enumerate() {
+ *o = if n == 0 || c >= ch { (1.0, 0.0) } else { fit(self.adapt, n as f32, m[c][0], m[c][1], m[c][2], m[c][3]) };
+ }
+ }
+
/// One PatchMatch pass over all target rows, in parallel bands (each band propagates within itself).
fn patchmatch(&self, nnf: &mut [(i32, i32)], cost: &mut [f32], pass: usize, seed: u64, search_radius: i32) {
const BAND: usize = 16;
@@ -285,7 +441,32 @@ impl Solver<'_> {
}
}
- /// Re-estimate hole pixels by a similarity-weighted vote of all overlapping patch matches.
+ /// Recompute every target's match cost (hole pixels change between iterations).
+ fn costs(&self, nnf: &[(i32, i32)], cost: &mut [f32]) -> Result<(), photocraft_raster::Cancelled> {
+ let w = self.w;
+ let row = |(y, co): (usize, &mut [f32])| {
+ if self.ctl.cancelled() {
+ return;
+ }
+ for (x, c) in co.iter_mut().enumerate() {
+ let i = y * w + x;
+ if self.targets[i] {
+ *c = self.dist((x as i32, y as i32), nnf[i], f32::INFINITY);
+ }
+ }
+ };
+ #[cfg(not(target_arch = "wasm32"))]
+ if w * self.h >= PAR_MIN {
+ use rayon::prelude::*;
+ cost.par_chunks_mut(w).enumerate().for_each(row);
+ return self.ctl.check();
+ }
+ cost.chunks_mut(w).enumerate().for_each(row);
+ self.ctl.check()
+ }
+
+ /// Re-estimate hole pixels by a similarity-weighted vote of all overlapping patch matches
+ /// (each copy adjusted by its gain and bias).
fn vote(&mut self, nnf: &[(i32, i32)], cost: &[f32]) {
let (w, h, ch, r) = (self.w, self.h, self.ch, self.r);
// σ² from the 75th percentile of match costs (Wexler et al. use a robust scale like this).
@@ -297,6 +478,32 @@ impl Solver<'_> {
let (_, v, _) = cs.select_nth_unstable_by(k, |a, b| a.total_cmp(b));
v.max(1e-6)
};
+ // Each target's photometric transform (computed once, used by every pixel it covers).
+ let adapted = !self.adapt.is_none();
+ let gb: Vec<(f32, f32)> = if adapted {
+ let mut gb = vec![(1.0f32, 0.0f32); w * h * ch];
+ let this = &*self;
+ let row = |(y, out): (usize, &mut [(f32, f32)])| {
+ for x in 0..w {
+ let i = y * w + x;
+ if this.targets[i] && cost[i].is_finite() {
+ this.transform((x as i32, y as i32), nnf[i], &mut out[x * ch..(x + 1) * ch]);
+ }
+ }
+ };
+ #[cfg(not(target_arch = "wasm32"))]
+ if w * h >= PAR_MIN {
+ use rayon::prelude::*;
+ gb.par_chunks_mut(w * ch).enumerate().for_each(row);
+ } else {
+ gb.chunks_mut(w * ch).enumerate().for_each(row);
+ }
+ #[cfg(target_arch = "wasm32")]
+ gb.chunks_mut(w * ch).enumerate().for_each(row);
+ gb
+ } else {
+ Vec::new()
+ };
let img = &*self.img;
let row = |y: usize| -> Vec<(usize, Vec<f32>)> {
let mut out = Vec::new();
@@ -304,7 +511,7 @@ impl Solver<'_> {
return out;
}
for x in 0..w {
- if !self.hole[y * w + x] {
+ if self.px[y * w + x] != Px::Hole {
continue;
}
let mut acc = vec![0.0f32; ch];
@@ -328,7 +535,13 @@ impl Solver<'_> {
let wt = (-cost[ti] / (2.0 * sigma2)).exp().max(1e-8);
let si = (sy as usize * w + sx as usize) * ch;
for c in 0..ch {
- acc[c] += img[si + c] * wt;
+ let v = if adapted {
+ let (g, b) = gb[ti * ch + c];
+ g * img[si + c] + b
+ } else {
+ img[si + c]
+ };
+ acc[c] += v * wt;
}
wsum += wt;
}
@@ -357,8 +570,71 @@ impl Solver<'_> {
}
}
-/// Content-aware completion of `hole` (see module docs). Returns `None` when there is no fully-known
-/// patch to copy from (the caller can fall back to [`membrane_fill`]).
+/// Fill the hole from its edge inwards, one ring at a time: each pixel takes the centre of the
+/// source patch that best matches what is already known around it.
+fn onion_peel(w: usize, h: usize, ch: usize, r: i32, img: &mut [f32], px: &[Px], sources: &[(i32, i32)]) {
+ let mut known: Vec<bool> = px.iter().map(|k| matches!(k, Px::Known | Px::Source)).collect();
+ loop {
+ let front: Vec<usize> = (0..w * h)
+ .filter(|&i| {
+ if known[i] || px[i] != Px::Hole {
+ return false;
+ }
+ let (x, y) = ((i % w) as i32, (i / w) as i32);
+ (-1..=1).any(|dy: i32| {
+ (-1..=1).any(|dx: i32| {
+ let (nx, ny) = (x + dx, y + dy);
+ nx >= 0 && ny >= 0 && (nx as usize) < w && (ny as usize) < h && known[ny as usize * w + nx as usize]
+ })
+ })
+ })
+ .collect();
+ if front.is_empty() {
+ break;
+ }
+ let best = |&i: &usize| -> Vec<f32> {
+ let (x, y) = ((i % w) as i32, (i / w) as i32);
+ let mut best = (f32::INFINITY, (0i32, 0i32));
+ for &(sx, sy) in sources {
+ let (mut e, mut n) = (0.0f32, 0usize);
+ for dy in -r..=r {
+ for dx in -r..=r {
+ let (tx, ty) = (x + dx, y + dy);
+ if tx < 0 || ty < 0 || tx as usize >= w || ty as usize >= h || !known[ty as usize * w + tx as usize] {
+ continue;
+ }
+ let (ti, si) = ((ty as usize * w + tx as usize) * ch, ((sy + dy) as usize * w + (sx + dx) as usize) * ch);
+ for c in 0..ch {
+ let d = img[ti + c] - img[si + c];
+ e += d * d;
+ }
+ n += 1;
+ }
+ }
+ if n > 0 && e / (n as f32) < best.0 {
+ best = (e / n as f32, (sx, sy));
+ }
+ }
+ let si = (best.1.1 as usize * w + best.1.0 as usize) * ch;
+ img[si..si + ch].to_vec()
+ };
+ #[cfg(not(target_arch = "wasm32"))]
+ let vals: Vec<Vec<f32>> = {
+ use rayon::prelude::*;
+ front.par_iter().map(best).collect()
+ };
+ #[cfg(target_arch = "wasm32")]
+ let vals: Vec<Vec<f32>> = front.iter().map(best).collect();
+ for (&i, v) in front.iter().zip(vals) {
+ img[i * ch..(i + 1) * ch].copy_from_slice(&v);
+ known[i] = true;
+ }
+ }
+}
+
+/// Content-aware completion of `hole` (see module docs), copying from any pixel outside it. Returns
+/// `None` when there is no fully-known patch to copy from (the caller can fall back to
+/// [`membrane_fill`]).
pub fn complete(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], p: &CompleteParams) -> Option<Vec<f32>> {
// Never cancelled, so never `Err`.
complete_with(w, h, ch, img, hole, p, &photocraft_raster::Interrupt::NONE).unwrap_or(None)
@@ -375,18 +651,37 @@ pub fn complete_with(
p: &CompleteParams,
ctl: &photocraft_raster::Interrupt,
) -> Result<Option<Vec<f32>>, photocraft_raster::Cancelled> {
- assert_eq!(img.len(), w * h * ch);
assert_eq!(hole.len(), w * h);
- let Some((bx0, by0, bx1, by1)) = hole_bbox(w, h, hole) else { return Ok(Some(img.to_vec())) };
+ let px: Vec<Px> = hole.iter().map(|h| if *h { Px::Hole } else { Px::Source }).collect();
+ complete_masked(w, h, ch, img, &px, p, ctl)
+}
+
+/// [`complete_with`] with every pixel's role given ([`Px`]): the hole, the context, what may be
+/// copied, and what isn't image at all.
+pub fn complete_masked(
+ w: usize,
+ h: usize,
+ ch: usize,
+ img: &[f32],
+ px: &[Px],
+ p: &CompleteParams,
+ ctl: &photocraft_raster::Interrupt,
+) -> Result<Option<Vec<f32>>, photocraft_raster::Cancelled> {
+ assert_eq!(img.len(), w * h * ch);
+ assert_eq!(px.len(), w * h);
+ let hole: Vec<bool> = px.iter().map(|k| *k == Px::Hole).collect();
+ let Some((bx0, by0, bx1, by1)) = hole_bbox(w, h, &hole) else { return Ok(Some(img.to_vec())) };
+ drop(hole);
let r = p.patch_radius.max(1);
let psz = 2 * r + 1;
- // Pyramid: shrink until the hole is a few patches across.
- let mut levels = vec![Level { w, h, img: img.to_vec(), hole: hole.to_vec() }];
+ // Pyramid: shrink until the hole is about four patches across (a deeper pyramid decides the
+ // structure where the texture has averaged out, and fills flat).
+ let mut levels = vec![Level { w, h, img: img.to_vec(), px: px.to_vec() }];
let mut ext = (bx1 - bx0).max(by1 - by0);
let mut exts = vec![ext];
while let Some(l) = levels.last() {
ctl.check()?;
- if ext <= 2 * psz || l.w / 2 < 3 * psz || l.h / 2 < 3 * psz {
+ if ext <= 4 * psz || l.w / 2 < 3 * psz || l.h / 2 < 3 * psz {
break;
}
let d = downsample(l, ch);
@@ -395,30 +690,20 @@ pub fn complete_with(
exts.push(ext);
}
let nlev = levels.len();
- let mut nnf: Vec<(i32, i32)> = Vec::new();
- let mut prev: Option<(usize, usize, Vec<f32>)> = None;
+ // The coarser level's result: its size, pixels and match field (empty when it had nothing to
+ // copy).
+ let mut prev: Option<Coarser> = None;
let total_px: usize = levels.iter().map(|l| l.w * l.h).sum();
let mut done_px = 0usize;
+ let ri = r as i32;
for li in (0..nlev).rev() {
ctl.check()?;
- let Level { w: lw, h: lh, img: mut limg, hole: lhole } = levels[li].clone();
- // Initialise the hole: membrane at the coarsest level, upsampled result elsewhere.
- match &prev {
- None => limg = membrane_fill(lw, lh, ch, &limg, &lhole),
- Some((pw, ph, pimg)) => {
- for y in 0..lh {
- for x in 0..lw {
- if lhole[y * lw + x] {
- let (sx, sy) = ((x / 2).min(pw - 1), (y / 2).min(ph - 1));
- let (d, s) = ((y * lw + x) * ch, (sy * pw + sx) * ch);
- limg[d..d + ch].copy_from_slice(&pimg[s..s + ch]);
- }
- }
- }
- }
- }
- let ri = r as i32;
+ let Level { w: lw, h: lh, img: mut limg, px: lpx } = std::mem::replace(&mut levels[li], Level { w: 0, h: 0, img: Vec::new(), px: Vec::new() });
+ let lhole: Vec<bool> = lpx.iter().map(|k| *k == Px::Hole).collect();
+ let source: Vec<bool> = lpx.iter().map(|k| *k == Px::Source).collect();
let hs = integral(lw, lh, &lhole);
+ let ss = integral(lw, lh, &source);
+ let full = (psz * psz) as u32;
let mut valid = vec![false; lw * lh];
let mut valid_list = Vec::new();
let mut targets = vec![false; lw * lh];
@@ -427,30 +712,54 @@ pub fn complete_with(
ctl.check()?;
}
for x in 0..lw as i32 {
- let cnt = window_count(&hs, lw, lh, x - ri, y - ri, x + ri + 1, y + ri + 1);
- let inside = x >= ri && y >= ri && x + ri < lw as i32 && y + ri < lh as i32;
let i = y as usize * lw + x as usize;
- if inside && cnt == 0 {
+ let inside = x >= ri && y >= ri && x + ri < lw as i32 && y + ri < lh as i32;
+ if inside && window_count(&ss, lw, lh, x - ri, y - ri, x + ri + 1, y + ri + 1) == full {
valid[i] = true;
valid_list.push((x, y));
}
- targets[i] = cnt > 0;
+ targets[i] = window_count(&hs, lw, lh, x - ri, y - ri, x + ri + 1, y + ri + 1) > 0;
+ }
+ }
+ // Initialise the hole: at the coarsest level peeled from its edge inwards (or a membrane
+ // where nothing can be copied), else the coarser level's pixels, refined below by a vote of
+ // its scaled-up matches.
+ match &prev {
+ Some((pw, ph, pimg, _)) => {
+ for y in 0..lh {
+ for x in 0..lw {
+ if lhole[y * lw + x] {
+ let (sx, sy) = ((x / 2).min(pw - 1), (y / 2).min(ph - 1));
+ let (d, s) = ((y * lw + x) * ch, (sy * pw + sx) * ch);
+ limg[d..d + ch].copy_from_slice(&pimg[s..s + ch]);
+ }
+ }
+ }
+ }
+ None if !valid_list.is_empty() => onion_peel(lw, lh, ch, ri, &mut limg, &lpx, &valid_list),
+ None => {
+ let unknown: Vec<bool> = lpx.iter().map(|k| matches!(k, Px::Hole | Px::Void)).collect();
+ let m = membrane_fill(lw, lh, ch, &limg, &unknown);
+ for (i, hl) in lhole.iter().enumerate() {
+ if *hl {
+ limg[i * ch..(i + 1) * ch].copy_from_slice(&m[i * ch..(i + 1) * ch]);
+ }
+ }
}
}
if valid_list.is_empty() {
if li == 0 {
return Ok(None);
}
- prev = Some((lw, lh, limg));
- nnf.clear();
+ prev = Some((lw, lh, limg, Vec::new()));
continue;
}
- let mut solver = Solver { w: lw, h: lh, ch, r: ri, img: &mut limg, hole: &lhole, valid, valid_list, targets, ctl: *ctl };
- // NNF init: upsampled from the coarser level where possible, random otherwise.
+ let mut solver = Solver { w: lw, h: lh, ch, r: ri, img: &mut limg, px: &lpx, valid, valid_list, targets, adapt: p.adapt, ctl: *ctl };
+ // NNF init: the coarser level's matches scaled up where they land on a valid source,
+ // random otherwise.
let mut rng = Rng::new(p.seed ^ (li as u64) << 20);
- let pw_prev = prev.as_ref().map_or(0, |p| p.0);
- let old = std::mem::take(&mut nnf);
- let mut new_nnf = vec![(0i32, 0i32); lw * lh];
+ let mut nnf = vec![(0i32, 0i32); lw * lh];
+ let mut upsampled = false;
for y in 0..lh {
if y % 32 == 0 {
ctl.check()?;
@@ -460,19 +769,29 @@ pub fn complete_with(
continue;
}
let mut cand = None;
- if !old.is_empty() && pw_prev > 0 {
- let pi = (y / 2) * pw_prev + (x / 2);
- if let Some(&(sx, sy)) = old.get(pi) {
- let c = (sx * 2 + (x % 2) as i32, sy * 2 + (y % 2) as i32);
+ if let Some((pw, ph, _, old)) = &prev
+ && !old.is_empty()
+ {
+ let (cx, cy) = ((x / 2).min(pw - 1), (y / 2).min(ph - 1));
+ let (sx, sy) = old[cy * pw + cx];
+ if sx != i32::MIN {
+ // The same displacement, twice as long.
+ let c = (x as i32 + 2 * (sx - cx as i32), y as i32 + 2 * (sy - cy as i32));
if solver.is_valid(c.0, c.1) {
cand = Some(c);
}
}
}
- new_nnf[y * lw + x] = cand.unwrap_or_else(|| solver.valid_list[(rng.next() % solver.valid_list.len() as u64) as usize]);
+ upsampled |= cand.is_some();
+ nnf[y * lw + x] = cand.unwrap_or_else(|| solver.valid_list[(rng.next() % solver.valid_list.len() as u64) as usize]);
}
}
- nnf = new_nnf;
+ let mut cost = vec![f32::INFINITY; lw * lh];
+ // A finer level starts from the coarse matches voted with its own (sharp) pixels.
+ if upsampled {
+ solver.costs(&nnf, &mut cost)?;
+ solver.vote(&nnf, &cost);
+ }
let refine_only = li + 1 < nlev && exts[li] > p.refine_extent;
let em = if li + 1 == nlev {
p.em_iters
@@ -483,18 +802,11 @@ pub fn complete_with(
};
let pm_iters = if refine_only { 1 } else { p.pm_iters };
let full_search = (lw.max(lh)) as i32;
- let mut cost = vec![f32::INFINITY; lw * lh];
for it in 0..em {
// Costs change as hole pixels are re-estimated: refresh before each PatchMatch.
- for (i, c) in cost.iter_mut().enumerate() {
- if i % (lw * 32).max(1) == 0 {
- ctl.check()?;
- }
- if solver.targets[i] {
- *c = solver.dist(((i % lw) as i32, (i / lw) as i32), nnf[i], f32::INFINITY);
- }
- }
- // Wide random search on coarse levels / first iteration, local refinement afterwards.
+ solver.costs(&nnf, &mut cost)?;
+ // Wide random search on the coarsest level and on each level's first iteration,
+ // local refinement afterwards.
let radius = if refine_only {
2
} else if li + 1 == nlev || it == 0 {
@@ -510,12 +822,14 @@ pub fn complete_with(
solver.vote(&nnf, &cost);
ctl.check()?;
}
+ // Keep the match field (unmatched cells marked) for the next level.
+ let field: Vec<(i32, i32)> = nnf.iter().zip(&solver.targets).map(|(n, t)| if *t { *n } else { (i32::MIN, i32::MIN) }).collect();
// Finer levels cost ~4× the previous one: weight progress by pixel count.
done_px += lw * lh;
ctl.progress(done_px as f32 / total_px.max(1) as f32);
- prev = Some((lw, lh, limg));
+ prev = Some((lw, lh, limg, field));
}
- Ok(prev.map(|(_, _, img)| img))
+ Ok(prev.map(|(_, _, img, _)| img))
}
/// Proximity match: the displacement `(dx, dy)` (within `max_radius`) whose surroundings best match the
diff --git a/crates/engine/src/edit_menu_cmds.rs b/crates/engine/src/edit_menu_cmds.rs
index a2dece028..46f924511 100644
--- a/crates/engine/src/edit_menu_cmds.rs
+++ b/crates/engine/src/edit_menu_cmds.rs
@@ -331,13 +331,14 @@ fn content_aware_fill(s: &mut Session, p: &Value) -> Result<Value> {
}
/// Delete and Fill Selection (#1286): Photoshop's one-click removal from the selection-tool
-/// context menu. Content-Aware Fill with its default settings into the layer, no dialog.
+/// context menu. Content-Aware Fill into the layer, no dialog, sampling as Edit › Fill does (the
+/// whole window, measured on Photoshop 25.4) with the default colour adaptation.
fn delete_and_fill(s: &mut Session, _: &Value) -> Result<Value> {
- content_aware_fill_as(s, &json!({}), "edit.deleteAndFillSelection", "Delete and Fill Selection")
+ content_aware_fill_as(s, &json!({"sampling": "rectangular"}), "edit.deleteAndFillSelection", "Delete and Fill Selection")
}
fn content_aware_fill_as(s: &mut Session, p: &Value, cmd: &'static str, label: &'static str) -> Result<Value> {
- use photocraft_algo::content_aware::{FillOptions, color_level, fill_with, rotation_level};
+ use photocraft_algo::content_aware::{FillOptions, auto_sampling, color_level, fill_with, rotation_level};
let id = pixel_layer(s).map_err(EngineError::Other)?;
let st = s.active().ok_or(EngineError::NoDocument)?;
let doc = st.doc.clone();
@@ -346,14 +347,17 @@ fn content_aware_fill_as(s: &mut Session, p: &Value, cmd: &'static str, label: &
if hb.is_empty() {
return Err(bad(cmd, "the selection is outside the canvas"));
}
- // The canvas is at most i32 wide, so the extent fits; saturate anyway rather than wrap (#963).
- let ext = i32::try_from(hb.width().max(hb.height())).unwrap_or(i32::MAX);
let sampling = str_or(p, "sampling", "auto").to_string();
let custom_mask: Option<Surface> = p.get("channel").and_then(|v| channel_mask(&doc, v)).cloned();
let custom_rect = if p.get("area").is_some() { Some(rect_param(p, "area", cmd)?) } else { None };
+ // Photoshop's window (`content_aware::sampling_window`) for Auto and Rectangular; `margin`
+ // asks for a rectangle that far around the selection instead.
let window = match sampling.as_str() {
- "auto" => hb.inflate(crate::fill_cmds::sampling_margin(hb)),
- "rectangular" => hb.inflate(int(p, "margin").map_or(ext.max(16), |m| m.clamp(0, 100_000) as i32)),
+ "auto" => crate::fill_cmds::sampling_window(hb, doc.bounds()),
+ "rectangular" => match int(p, "margin") {
+ Some(m) => hb.inflate(m.clamp(0, 100_000) as i32),
+ None => crate::fill_cmds::sampling_window(hb, doc.bounds()),
+ },
"custom" => {
let r = match (custom_rect, custom_mask.as_ref()) {
(Some(r), _) => r,
@@ -413,6 +417,11 @@ fn content_aware_fill_as(s: &mut Session, p: &Value, cmd: &'static str, label: &
}
}
ctx.check()?;
+ // Auto: only what looks like the selection's surroundings.
+ if sampling == "auto" {
+ source = auto_sampling(w, h, n, &img, &hole);
+ }
+ ctx.check()?;
let filled = ctx.stage(0.05, 1.0, label, |ctl| fill_with(w, h, n, &img, &hole, &source, &opts, ctl)).map_err(|_| EngineError::Cancelled)?;
Ok((img, cover, hole, filled))
},
diff --git a/crates/engine/src/edit_menu_cmds/tests.rs b/crates/engine/src/edit_menu_cmds/tests.rs
index c17f47533..a94a05410 100644
--- a/crates/engine/src/edit_menu_cmds/tests.rs
+++ b/crates/engine/src/edit_menu_cmds/tests.rs
@@ -218,6 +218,22 @@ fn delete_and_fill_selection_removes_the_object_in_one_step() {
assert!(s.execute("edit.deleteAndFillSelection", json!({})).is_err());
}
+#[test]
+fn content_aware_fill_samples_photoshops_window() {
+ // A 50 px selection samples the 200 px square centred on it (Photoshop 25.4's overlay);
+ // at the canvas edge the square slides inwards. Edit › Fill uses the same window.
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 600, "height": 400, "background": "white"})).unwrap();
+ for (x, y, want) in [(275, 175, [200, 100, 200, 200]), (10, 10, [0, 0, 200, 200])] {
+ s.execute("select.rect", json!({"x": x, "y": y, "width": 50, "height": 50})).unwrap();
+ for sampling in ["auto", "rectangular"] {
+ let r = s.execute("edit.contentAwareFill", json!({"sampling": sampling})).unwrap();
+ assert_eq!(r["window"], json!(want), "{sampling} at {x},{y}");
+ s.undo();
+ }
+ }
+}
+
#[test]
fn content_aware_fill_outputs_and_sampling() {
let mut s = blob_session(8);
diff --git a/crates/engine/src/fill_cmds.rs b/crates/engine/src/fill_cmds.rs
index 827bef866..9453652e7 100644
--- a/crates/engine/src/fill_cmds.rs
+++ b/crates/engine/src/fill_cmds.rs
@@ -191,7 +191,7 @@ fn content_aware(surf: &Surface, sel: &Surface, canvas: Rect, color_adaptation:
if hole_bounds.is_empty() {
return Err(EngineError::Other("the selection is outside the canvas".into()));
}
- let window = hole_bounds.inflate(sampling_margin(hole_bounds)).intersect(&canvas);
+ let window = sampling_window(hole_bounds, canvas);
let fmt = surf.format();
let n = fmt.channels();
let (w, h) = window_size(window)?;
@@ -219,12 +219,12 @@ fn content_aware(surf: &Surface, sel: &Surface, canvas: Rect, color_adaptation:
Ok(Source::Pixels(window, px))
}
-/// The automatic Content-Aware sampling margin around `hole`: three quarters of its larger side,
-/// at least 32 pixels. Worked out in u64 because a loaded document can declare a selection whose
-/// extent times three overflows u32 (#963); a margin beyond i32 saturates, as `Rect::inflate` does.
-pub(crate) fn sampling_margin(hole: Rect) -> i32 {
- let ext = u64::from(hole.width().max(hole.height()));
- i32::try_from(ext * 3 / 4).unwrap_or(i32::MAX).max(32)
+/// Photoshop's Content-Aware sampling window around the selection bounds `hole`
+/// ([`photocraft_algo::content_aware::sampling_window`]): Edit › Fill, the workspace's Rectangular
+/// and Auto areas and the retouching tools all copy from within it. Worked out in i64, so a loaded
+/// document declaring an absurd selection can't overflow it (#963).
+pub(crate) fn sampling_window(hole: Rect, canvas: Rect) -> Rect {
+ photocraft_algo::content_aware::sampling_window(hole.intersect(&canvas), canvas)
}
/// The size of a Content-Aware sampling window, or an error for a window too large to read and
diff --git a/crates/engine/src/retouch_cmds.rs b/crates/engine/src/retouch_cmds.rs
index 8ef1988eb..d7e58306a 100644
--- a/crates/engine/src/retouch_cmds.rs
+++ b/crates/engine/src/retouch_cmds.rs
@@ -587,14 +587,19 @@ enum SpotType {
/// Fill the stroke area with no source, then gradient-domain blend it into its surroundings. With
/// `all` (Sample All Layers) it heals what is visible, so it works on an empty layer above the image.
+///
+/// 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) -> Rect {
let (bounds, cov) = stroke_coverage(stroke);
let size = stroke.brush.size;
- let margin = (size.max(8.0) * 1.0).ceil() as i32 + 8;
- let region_rect = bounds.inflate(margin).intersect(&pre.bounds());
+ let region_rect = crate::fill_cmds::sampling_window(bounds, pre.bounds());
if region_rect.is_empty() {
return 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 (w, h, ch) = (img.width(), img.height(), img.ch);
@@ -1085,7 +1090,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Patch",
menu: &[],
shortcut: None,
- params: r#"{"offset":[dx,dy] (how far the selection was dragged),"mode":"source|destination"="source","layer":id?=active,"target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target} → {"damage","offset"}"#,
+ params: r#"{"offset":[dx,dy] (how far the selection was dragged),"mode":"source|destination"="source","contentAware":bool=false (fill the selection content-aware from the dragged-to place; a background job),"structure":1..7=4 (content-aware: 3..7 copy the middle exactly, 1..2 re-synthesise more of it),"color":0..10=0 (content-aware: how far the copy's level adapts to the selection's surroundings),"sampleAllLayers":bool=false (content-aware),"layer":id?=active,"target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target} → {"damage","offset"}"#,
enabled: patch::enabled,
run: patch::patch,
journal: true,
@@ -1095,7 +1100,7 @@ pub fn specs() -> Vec<CommandSpec> {
label: "Content-Aware Move",
menu: &[],
shortcut: None,
- params: r#"{"offset":[dx,dy] (how far the selection was dragged),"mode":"move|extend"="move","structure":1..7=4 (7 keeps the content up to its edge, lower blends a wider edge band),"color":0..10=0 (how far the content's colour adapts to its new place),"sampleAllLayers":bool=false,"layer":id?=active,"target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target} → {"damage","offset","mode"} (a background job; the selection moves with the content)"#,
+ params: r#"{"offset":[dx,dy] (how far the selection was dragged),"mode":"move|extend"="move","structure":1..7=4 (3..7 copy the content exactly but for a band about a patch wide along its edge; 2 widens the band, 1 re-synthesises the content too),"color":0..10=0 (0 keeps the content's level; higher values bring it towards its new place, by up to about 0.04 × color),"sampleAllLayers":bool=false,"layer":id?=active,"target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target} → {"damage","offset","mode"} (a background job; the selection moves with the content)"#,
enabled: content_aware_move::enabled,
run: content_aware_move::content_aware_move,
journal: true,
diff --git a/crates/engine/src/retouch_cmds/content_aware_move.rs b/crates/engine/src/retouch_cmds/content_aware_move.rs
index 0f1e40362..aa320413f 100644
--- a/crates/engine/src/retouch_cmds/content_aware_move.rs
+++ b/crates/engine/src/retouch_cmds/content_aware_move.rs
@@ -2,22 +2,28 @@
//! content-aware fill close the gaps.
//!
//! The selection is the content, `offset` how far the user dragged it. At the new place the content
-//! is pasted, its colour fitted to the new surroundings by `color` (0 keeps it, 10 is a full
-//! seamless clone as the Patch Tool's), and a band along its edge, inside the selection, is
-//! re-synthesised from the surroundings so that it merges in. `structure` sets that band: 7 keeps
-//! the content up to the selection's edge, lower values hand a wider band to the surroundings. In
-//! `move` mode the place the content left is then filled content-aware (`extend` keeps it). That
-//! fill never samples the moved content, so the object doesn't come back as a ghost; the edge band
-//! may sample it (it is the context the band blends towards), but not the content's old place.
-//! (`content_aware::fill` treats excluded pixels as unknown, so excluding the content there would
-//! turn the whole moved area into one hole and smear the band further.)
+//! is pasted, fitted to its new surroundings by `color`, and a band along its edge, inside the
+//! selection, is re-synthesised from the surroundings so that it merges in. In `move` mode the place
+//! the content left is then filled content-aware (`extend` keeps it). That fill never samples the
+//! moved content, so the object doesn't come back as a ghost; the edge band may sample it (it is the
+//! context the band blends towards), but not the content's old place.
+//!
+//! Measured on Photoshop 25.4 (a 60 px selection holding a ring-shaped object, dragged 150 px):
+//! * **Structure** 3 to 7 give the same result, bit for bit: the content is copied exactly up to
+//! about 8 px from the selection's edge, and that band blends into the surroundings. 2 widens the
+//! band; 1 re-synthesises the content too, so even its middle is no longer an exact copy.
+//! * **Color** 0 pastes the content as it is; higher values bring its level towards the new
+//! surroundings by up to about `0.04 · color` (Patch Tool, content 42 and 102 levels brighter:
+//! 3 shifts it 32 and 31 levels, 10 shifts it 35 and 95), a limited gain and bias
+//! ([`photocraft_algo::content_aware::color_amount`]).
//!
//! The selection moves with the content, as in Photoshop. A soft selection counts wherever it is
//! above zero (as the Patch Tool's); the band does the blending. The fills are PatchMatch
//! completions and can take seconds on large selections, so the command runs as a background job
-//! (#210): with progress, cancellable, and the document unchanged until it applies.
+//! (#210): with progress, cancellable, and the document unchanged until it applies. The Patch
+//! Tool's Content-Aware mode lands its content the same way ([`land`]).
-use photocraft_algo::content_aware::{FillOptions, fill_with};
+use photocraft_algo::content_aware::{FillOptions, color_amount, color_level, fill_with, level_transform};
use super::patch::{coverage, offset, selection_area, target_layer};
use super::*;
@@ -58,10 +64,18 @@ fn level(p: &Value, k: &str, default: u8, lo: u8, hi: u8) -> Result<u8> {
}
}
+/// The pixels a step reads and writes: a layer (or, with `None`, the channel `p` targets), and
+/// whether reading samples the visible composite (Sample All Layers).
+#[derive(Clone, Copy, Debug)]
+pub(super) struct Target {
+ pub id: Option<LayerId>,
+ pub all_layers: bool,
+}
+
/// What a move does, checked before any work starts.
#[derive(Clone, Copy, Debug)]
struct Plan {
- id: Option<LayerId>,
+ target: Target,
canvas: Rect,
/// The selected area (where the content comes from).
area: Rect,
@@ -69,7 +83,6 @@ struct Plan {
mode: Mode,
structure: u8,
color: u8,
- all_layers: bool,
}
fn plan(s: &Session, p: &Value) -> Result<Plan> {
@@ -101,19 +114,21 @@ fn plan(s: &Session, p: &Value) -> Result<Plan> {
return Err(bad(CMD, "the moved selection must stay inside the canvas"));
}
let all_layers = flag(p, "sampleAllLayers", false) && targets_pixels(p);
- Ok(Plan { id, canvas, area, offset: (dx, dy), mode, structure, color, all_layers })
+ Ok(Plan { target: Target { id, all_layers }, canvas, area, offset: (dx, dy), mode, structure, color })
}
/// Width in pixels of the edge band re-synthesised at the new place, for Structure 1..7 and content
-/// `min_side` pixels across. 7 keeps everything; the fractions grow the band roughly geometrically
-/// towards 1, so the default 4 blends about a tenth of the content into its surroundings.
-fn band_width(structure: u8, min_side: u32) -> usize {
- const FRACTION: [f32; 7] = [0.30, 0.22, 0.15, 0.10, 0.06, 0.03, 0.0];
- let f = FRACTION.get(usize::from(structure.saturating_sub(1))).copied().unwrap_or(0.0);
- if f == 0.0 {
- return 0;
- }
- ((min_side as f32 * f).round() as usize).clamp(2, 128)
+/// `min_side` pixels across. Photoshop gives the same result for 3 to 7: the band is about a patch
+/// wide whatever the content's size; 2 and 1 widen it (1 so far that the content itself is
+/// re-synthesised).
+pub(super) fn band_width(structure: u8, min_side: u32) -> usize {
+ let side = min_side as f32;
+ let w = match structure {
+ 0 | 1 => (side * 0.3).max(12.0),
+ 2 => (side * 0.18).max(9.0),
+ _ => 6.0,
+ };
+ (w.round() as usize).min(128)
}
/// The cells of a `w × h` mask whose whole `(2r+1)²` neighbourhood, as far as it lies on the grid,
@@ -147,17 +162,17 @@ fn erode(w: usize, h: usize, m: &[bool], r: usize) -> Vec<bool> {
out
}
-/// Where a fill samples from around `r`: as Edit › Content-Aware Fill's automatic sampling area,
-/// three quarters of the extent around it (at least 32, at most [`MAX_MARGIN`] pixels).
-fn window(r: Rect, canvas: Rect) -> Rect {
- r.inflate(crate::fill_cmds::sampling_margin(r).min(MAX_MARGIN)).intersect(&canvas)
+/// Where a fill samples from around `r`: Photoshop's Content-Aware window
+/// ([`crate::fill_cmds::sampling_window`]), at most [`MAX_MARGIN`] pixels around `r`.
+pub(super) fn window(r: Rect, canvas: Rect) -> Rect {
+ crate::fill_cmds::sampling_window(r, canvas).intersect(&r.inflate(MAX_MARGIN))
}
/// The pixels a step works on: the targeted surface, or with Sample All Layers the visible
/// composite (encoded in the target's format).
-fn read(doc: &mut Document, plan: &Plan, p: &Value, rect: Rect) -> Result<Region> {
- let (surf, _) = crate::channel_cmds::target_surface(doc, plan.id, p)?;
- if plan.all_layers {
+pub(super) fn read(doc: &mut Document, t: Target, p: &Value, rect: Rect) -> Result<Region> {
+ let (surf, _) = crate::channel_cmds::target_surface(doc, t.id, p)?;
+ if t.all_layers {
let fmt = surf.format();
return Ok(composite_region(doc, None, SampleLayers::All, rect, fmt));
}
@@ -167,8 +182,8 @@ fn read(doc: &mut Document, plan: &Plan, p: &Value, rect: Rect) -> Result<Region
/// Write `out` over `mask` into the target, replacing the pixels (the result already holds what
/// should show there). With the transparency lock, alpha is kept and transparent pixels stay as
/// they are. Returns the written rectangle. Shared with the Remove Tool.
-pub(super) fn replace(doc: &mut Document, id: Option<LayerId>, p: &Value, out: &Region, mask: &[bool]) -> Result<Rect> {
- let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?;
+pub(super) fn replace(doc: &mut Document, t: Target, p: &Value, out: &Region, mask: &[bool]) -> Result<Rect> {
+ let (surf, lock) = crate::channel_cmds::target_surface(doc, t.id, p)?;
let fmt = surf.format();
let a = alpha_index(&fmt);
let rect = out.rect;
@@ -199,80 +214,112 @@ pub(super) fn replace(doc: &mut Document, id: Option<LayerId>, p: &Value, out: &
}
/// Selection coverage over `rect` as a mask (set wherever it is above zero).
-fn mask(sel: &Surface, rect: Rect) -> Vec<bool> {
+pub(super) fn mask(sel: &Surface, rect: Rect) -> Vec<bool> {
coverage(sel, rect).into_iter().map(|c| c > 0.0).collect()
}
/// Fill options: the fill's own colour adaptation (Edit › Content-Aware Fill's default), seeded so
/// the result is reproducible.
-fn fill_options() -> FillOptions {
+pub(super) fn fill_options() -> FillOptions {
FillOptions { seed: 0x00ca_4e00, ..FillOptions::default() }
}
-/// The new target surface and the rectangle it changed: the content pasted at the offset, then
-/// (`move`) its old place filled. Works on `doc`, a copy of the document.
-fn run_move(doc: &mut Document, sel: &Surface, plan: &Plan, p: &Value, ctx: &crate::jobs::JobCtx, label: &str) -> Result<(Surface, Rect)> {
- let (dx, dy) = plan.offset;
- let opts = fill_options();
- let split = if plan.mode == Mode::Move { 0.4 } else { 1.0 };
- let cancelled = |_| EngineError::Cancelled;
+/// A ring of `w` pixels just outside `m` (within the grid).
+fn outer_ring(gw: usize, gh: usize, m: &[bool], w: usize) -> Vec<bool> {
+ let inside: Vec<bool> = m.iter().map(|v| !*v).collect();
+ erode(gw, gh, &inside, w).iter().zip(m).map(|(keep, sel)| !*keep && !*sel).collect()
+}
- // 1. The content at its new place.
- let dst_area = plan.area.translate(dx, dy);
- let win = window(dst_area, plan.canvas);
+/// Content landing at `dst_area`: the pixels of the window around it, with `selected` (the
+/// selection's shape there) to be replaced by the content found `shift` away (`content` = that
+/// window, so `content` pixel = window pixel + `shift`). The content's middle is copied, its level
+/// fitted to the new surroundings by `color`; a `band_width(structure)` band inside the selection's
+/// edge is re-synthesised from the surroundings and that middle, never sampling `avoid`. Writes the
+/// result into the target and returns the rectangle it changed.
+#[allow(clippy::too_many_arguments)]
+pub(super) fn land(
+ doc: &mut Document,
+ t: Target,
+ p: &Value,
+ win: Rect,
+ selected: &[bool],
+ content: &Region,
+ avoid: &[bool],
+ structure: u8,
+ color: u8,
+ stage: (f32, f32),
+ ctx: &crate::jobs::JobCtx,
+ label: &str,
+) -> Result<Rect> {
let (w, h) = (win.width() as usize, win.height() as usize);
- let here = read(doc, plan, p, win)?;
- let fmt = crate::channel_cmds::target_surface(doc, plan.id, p)?.0.format();
+ let here = read(doc, t, p, win)?;
let n = here.ch;
- // The content with its original surroundings, laid over this window.
- let mut src = read(doc, plan, p, win.translate(-dx, -dy))?;
- src.rect = win;
- let moved = mask(sel, win.translate(-dx, -dy));
- let old_place = mask(sel, win);
- let side = plan.area.width().min(plan.area.height());
- let core = erode(w, h, &moved, band_width(plan.structure, side));
+ let (sx0, sy0, sx1, sy1) = selected.iter().enumerate().filter(|(_, s)| **s).fold((w, h, 0, 0), |b, (i, _)| {
+ let (x, y) = (i % w, i / w);
+ (b.0.min(x), b.1.min(y), b.2.max(x + 1), b.3.max(y + 1))
+ });
+ let side = (sx1.saturating_sub(sx0)).min(sy1.saturating_sub(sy0)) as u32;
+ let core = erode(w, h, selected, band_width(structure, side));
ctx.check()?;
- // Colour: fit the kept content to the new surroundings (seamless clone), mixed in by `color`.
- let fitted = if plan.color > 0 && core.iter().any(|c| *c) {
- let healed = heal_region(&fmt, &src, &here, &core);
- let k = f32::from(plan.color) / 10.0;
- let mut f = src.clone();
- f.data.iter_mut().zip(&healed.data).for_each(|(s, h)| *s += (h - *s) * k);
- f
- } else {
- src
- };
+ // Colour: the content's surroundings (where it came from) against the new ones, both just
+ // outside the selection's shape.
+ let ring = outer_ring(w, h, selected, 6);
+ let pick = |r: &Region| -> Vec<f32> { ring.iter().enumerate().filter(|(_, k)| **k).flat_map(|(i, _)| r.data[i * n..(i + 1) * n].to_vec()).collect() };
+ let gb = level_transform(n, &pick(content), &pick(&here), color_amount(color));
+ let fmt = crate::channel_cmds::target_surface(doc, t.id, p)?.0.format();
+ let alpha = alpha_index(&fmt);
let mut buf = here;
for (i, _) in core.iter().enumerate().filter(|(_, c)| **c) {
- let r = i * n..(i + 1) * n;
- if let (Some(d), Some(s)) = (buf.data.get_mut(r.clone()), fitted.data.get(r)) {
- d.copy_from_slice(s);
+ for (c, &(g, b)) in gb.iter().enumerate() {
+ let v = content.data[i * n + c];
+ // Colour channels are fitted; alpha is copied.
+ buf.data[i * n + c] = if Some(c) == alpha { v } else { g * v + b };
}
}
- // Structure: the band between the kept core and the selection's edge comes from the surroundings
- // and the kept core (see the module docs), never from the content's old place.
- let band: Vec<bool> = moved.iter().zip(&core).map(|(m, c)| *m && !*c).collect();
+ clamp_samples(&fmt, &mut buf.data);
+ // Structure: the band between the kept core and the selection's edge comes from the
+ // surroundings and the kept core, never from what `avoid` marks.
+ let band: Vec<bool> = selected.iter().zip(&core).map(|(m, c)| *m && !*c).collect();
if band.iter().any(|b| *b) {
- let allowed: Vec<bool> = old_place.iter().map(|o| !*o).collect();
- buf.data = ctx.stage(0.0, split, label, |ctl| fill_with(w, h, n, &buf.data, &band, &allowed, &opts, ctl)).map_err(cancelled)?;
+ let allowed: Vec<bool> = avoid.iter().map(|o| !*o).collect();
+ let opts = FillOptions { color_adaptation: if color == 0 { color_level("default") } else { color_amount(color) }, ..fill_options() };
+ buf.data = ctx.stage(stage.0, stage.1, label, |ctl| fill_with(w, h, n, &buf.data, &band, &allowed, &opts, ctl)).map_err(|_| EngineError::Cancelled)?;
}
- let mut damage = replace(doc, plan.id, p, &buf, &moved)?;
+ replace(doc, t, p, &buf, selected)
+}
+
+/// The new target surface and the rectangle it changed: the content pasted at the offset, then
+/// (`move`) its old place filled. Works on `doc`, a copy of the document.
+fn run_move(doc: &mut Document, sel: &Surface, plan: &Plan, p: &Value, ctx: &crate::jobs::JobCtx, label: &str) -> Result<(Surface, Rect)> {
+ let (dx, dy) = plan.offset;
+ let opts = fill_options();
+ let split = if plan.mode == Mode::Move { 0.4 } else { 1.0 };
+ let cancelled = |_| EngineError::Cancelled;
+
+ // 1. The content at its new place: the content with its original surroundings laid over the
+ // window there; never sampling the content's old place.
+ let win = window(plan.area.translate(dx, dy), plan.canvas);
+ let mut content = read(doc, plan.target, p, win.translate(-dx, -dy))?;
+ content.rect = win;
+ let moved = mask(sel, win.translate(-dx, -dy));
+ let old_place = mask(sel, win);
+ let mut damage = land(doc, plan.target, p, win, &moved, &content, &old_place, plan.structure, plan.color, (0.0, split), ctx, label)?;
// 2. Move: fill the place the content left (where the content didn't land on it).
if plan.mode == Mode::Move {
ctx.check()?;
let win = window(plan.area, plan.canvas);
let (w, h) = (win.width() as usize, win.height() as usize);
- let img = read(doc, plan, p, win)?;
+ let img = read(doc, plan.target, p, win)?;
let landed = mask(sel, win.translate(-dx, -dy));
let hole: Vec<bool> = mask(sel, win).iter().zip(&landed).map(|(s, l)| *s && !*l).collect();
if hole.iter().any(|h| *h) {
let allowed: Vec<bool> = landed.iter().map(|l| !*l).collect();
let data = ctx.stage(split, 1.0, label, |ctl| fill_with(w, h, img.ch, &img.data, &hole, &allowed, &opts, ctl)).map_err(cancelled)?;
- damage = damage.union(&replace(doc, plan.id, p, &Region { rect: win, ch: img.ch, data }, &hole)?);
+ damage = damage.union(&replace(doc, plan.target, p, &Region { rect: win, ch: img.ch, data }, &hole)?);
}
}
- let surf = crate::channel_cmds::target_surface(doc, plan.id, p)?.0.clone();
+ let surf = crate::channel_cmds::target_surface(doc, plan.target.id, p)?.0.clone();
Ok((surf, damage))
}
@@ -298,7 +345,7 @@ pub(super) fn content_aware_move(s: &mut Session, p: &Value) -> Result<Value> {
move |s, (surf, damage)| {
let (dx, dy) = plan.offset;
s.edit(label, |doc, _| {
- *crate::channel_cmds::target_surface(doc, plan.id, &p)?.0 = surf;
+ *crate::channel_cmds::target_surface(doc, plan.target.id, &p)?.0 = surf;
// The selection follows the content, ready for another drag.
if let Some(sel) = doc.selection.as_ref() {
doc.selection = Some(crate::layer_multi_cmds::shift_surface(sel, dx, dy));
diff --git a/crates/engine/src/retouch_cmds/patch.rs b/crates/engine/src/retouch_cmds/patch.rs
index dc0f5e362..f3cb4765a 100644
--- a/crates/engine/src/retouch_cmds/patch.rs
+++ b/crates/engine/src/retouch_cmds/patch.rs
@@ -6,6 +6,16 @@
//! takes the colour and lighting around the repaired area. A feathered selection blends the result
//! in by its coverage. Only the targeted surface is read and written: in Normal mode the patch
//! samples the current layer.
+//!
+//! With `contentAware` (Photoshop's Patch: Content-Aware) the selected area is filled from the
+//! dragged-to place content-aware, as the Content-Aware Move Tool lands its content
+//! ([`super::content_aware_move::land`]): the middle is copied, fitted to the selection's
+//! surroundings by `color` (0–10), and a band along the edge, set by `structure` (1–7), is
+//! re-synthesised. Measured on Photoshop 25.4 (a 60 px selection dragged 150 px onto a ring-shaped
+//! object): only the selection changes; Structure 3 to 7 give the same result; Color 0 keeps the
+//! copied level, higher values shift it towards the surroundings by up to about `0.04 · color`
+//! (3: 32 of 42 levels, 31 of 102; 10: 35 of 42, 95 of 102). It runs as a background job, like
+//! the move.
use super::*;
@@ -202,6 +212,9 @@ fn patch_surface(surf: &mut Surface, sel: &Surface, plan: &Plan, lock: bool, ste
}
pub(super) fn patch(s: &mut Session, p: &Value) -> Result<Value> {
+ if flag(p, "contentAware", false) {
+ return patch_content_aware(s, p);
+ }
let plan = plan(s, p)?;
let label = if plan.destination { "Patch (Destination)" } else { "Patch" };
let dmg = run_stroke(s, label, plan.id, p, |pre, surf, _, lock| {
@@ -229,3 +242,61 @@ pub fn preview(s: &Session, p: &Value, max_cells: u64, min_step: u32) -> Result<
let dmg = patch_surface(surf, sel, &plan, lock, step);
Ok((doc, dmg))
}
+
+/// Optional whole-number param in `lo..=hi`; absent or null gives `default`.
+fn level(p: &Value, k: &str, default: u8, lo: u8, hi: u8) -> Result<u8> {
+ match p.get(k) {
+ None | Some(Value::Null) => Ok(default),
+ Some(v) => match v.as_f64() {
+ Some(x) if x.is_finite() && (f64::from(lo)..=f64::from(hi)).contains(&x) => Ok(x.round() as u8),
+ _ => Err(bad(CMD, format!("`{k}` must be a number {lo}..{hi}"))),
+ },
+ }
+}
+
+/// Patch: Content-Aware. The selection is filled from the place it was dragged to (see the module
+/// docs), as a background job.
+fn patch_content_aware(s: &mut Session, p: &Value) -> Result<Value> {
+ use super::content_aware_move::{Target, land, mask, read, window};
+ const LABEL: &str = "Patch (Content-Aware)";
+ let plan = plan(s, p)?;
+ let structure = level(p, "structure", 4, 1, 7)?;
+ let color = level(p, "color", 0, 0, 10)?;
+ let target = Target { id: plan.id, all_layers: flag(p, "sampleAllLayers", false) && targets_pixels(p) };
+ let d = s.active().ok_or(EngineError::NoDocument)?;
+ let doc = d.doc.clone();
+ let p = p.clone();
+ let (dx, dy) = plan.offset;
+ let (area, canvas) = (plan.area, plan.canvas);
+ crate::jobs::run(
+ s,
+ LABEL,
+ true,
+ {
+ let p = p.clone();
+ move |ctx| {
+ ctx.progress(0.0, LABEL);
+ let mut work = (*doc).clone();
+ let sel = doc.selection.as_ref().ok_or_else(|| bad(CMD, "select the area to patch first"))?;
+ let win = window(area, canvas);
+ let mut content = read(&mut work, target, &p, win.translate(dx, dy))?;
+ content.rect = win;
+ let selected = mask(sel, win);
+ let avoid = vec![false; selected.len()];
+ let damage = land(&mut work, target, &p, win, &selected, &content, &avoid, structure, color, (0.0, 1.0), ctx, LABEL)?;
+ let surf = crate::channel_cmds::target_surface(&mut work, target.id, &p)?.0.clone();
+ Ok((surf, damage))
+ }
+ },
+ move |s, (surf, damage)| {
+ s.edit(LABEL, |doc, _| {
+ *crate::channel_cmds::target_surface(doc, target.id, &p)?.0 = surf;
+ Ok(())
+ })?;
+ if let Some(st) = s.active_mut() {
+ st.last_damage = Some(damage);
+ }
+ Ok(json!({ "damage": damage_json(damage), "offset": [dx, dy], "contentAware": true }))
+ },
+ )
+}
diff --git a/crates/engine/src/retouch_cmds/remove.rs b/crates/engine/src/retouch_cmds/remove.rs
index 57847e7fc..56c110b65 100644
--- a/crates/engine/src/retouch_cmds/remove.rs
+++ b/crates/engine/src/retouch_cmds/remove.rs
@@ -8,7 +8,7 @@
//! runs as a background job (#210): with progress, cancellable, and the document unchanged until
//! it applies, in one undo step.
-use super::content_aware_move::replace;
+use super::content_aware_move::{Target, replace};
use super::patch::coverage;
use super::*;
@@ -28,6 +28,13 @@ const GROW: usize = 2;
/// Seed of the completion, so a removal is reproducible.
const SEED: u64 = 0x0052_e30e;
+/// The sampling margin around the stroke: three quarters of its larger side, at least 32 pixels
+/// (in u64, so a huge extent can't overflow; a margin beyond i32 saturates).
+fn sampling_margin(area: Rect) -> i32 {
+ let ext = u64::from(area.width().max(area.height()));
+ i32::try_from(ext * 3 / 4).unwrap_or(i32::MAX).max(32)
+}
+
/// What a removal does, checked before any work starts.
struct Plan {
id: Option<LayerId>,
@@ -62,7 +69,7 @@ fn plan(s: &Session, p: &Value) -> Result<Plan> {
if area.is_empty() {
return Err(bad(CMD, "the stroke is outside the canvas"));
}
- let window = area.inflate(crate::fill_cmds::sampling_margin(area).min(MAX_MARGIN)).intersect(&canvas);
+ let window = area.inflate(sampling_margin(area).min(MAX_MARGIN)).intersect(&canvas);
let close_loops = flag(p, "closeLoops", true);
let all_layers = flag(p, "sampleAllLayers", false) && targets_pixels(p);
Ok(Plan { id, stroke, window, close_loops, all_layers })
@@ -143,7 +150,7 @@ pub(super) fn remove(s: &mut Session, p: &Value) -> Result<Value> {
}
},
move |s, (out, hole)| {
- let damage = s.edit(label, |doc, _| replace(doc, id, &p, &out, &hole))?;
+ let damage = s.edit(label, |doc, _| replace(doc, Target { id, all_layers: false }, &p, &out, &hole))?;
if let Some(st) = s.active_mut() {
st.last_damage = Some(damage);
}
diff --git a/crates/engine/src/retouch_cmds/tests.rs b/crates/engine/src/retouch_cmds/tests.rs
index a41f5445b..6be113770 100644
--- a/crates/engine/src/retouch_cmds/tests.rs
+++ b/crates/engine/src/retouch_cmds/tests.rs
@@ -707,6 +707,39 @@ fn patch_source_repairs_the_selection_with_texture_from_the_drag_target() {
}
}
+#[test]
+fn patch_content_aware_copies_the_dragged_to_content_into_the_selection() {
+ // Photoshop's Patch: Content-Aware (measured on 25.4): only the selection changes; its middle
+ // is the dragged-to content (Color 0 keeps its level), the edge band blends.
+ for depth in [8, 16] {
+ let mut s = session(128, 64, depth, "rgb");
+ paint_layer(&mut s, blemished(40));
+ s.execute("select.rect", json!({"x": 32, "y": 12, "width": 24, "height": 24})).unwrap();
+ let r = s.execute("paint.patch", json!({"offset": [-30, 2], "contentAware": true, "structure": 7, "color": 0})).unwrap();
+ assert_eq!(r["contentAware"], json!(true));
+ for (x, y) in [(42, 22), (44, 24), (46, 26)] {
+ let (got, want) = (rgba(&s, x, y), texture(x - 30, y + 2));
+ for c in 0..4 {
+ assert!((got[c] - want[c]).abs() <= tol(depth), "depth {depth}: middle copied at {x},{y}: {got:?} vs {want:?}");
+ }
+ }
+ for (x, y) in [(31, 20), (56, 25), (12, 20), (44, 40)] {
+ let (got, want) = (rgba(&s, x, y), texture(x, y));
+ assert!((got[0] - want[0]).abs() <= tol(depth), "depth {depth}: untouched {x},{y}: {got:?}");
+ }
+ assert_eq!(s.active().unwrap().history.undo_label(), Some("Patch (Content-Aware)"));
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(rgba(&s, 44, 24)[1], 0.0, "depth {depth}: undo brings the blemish back");
+ }
+ // Bad options are refused before any work.
+ let mut s = session(96, 48, 8, "rgb");
+ paint_layer(&mut s, blemished(40));
+ s.execute("select.rect", json!({"x": 36, "y": 16, "width": 16, "height": 16})).unwrap();
+ for p in [json!({"offset": [-30, 0], "contentAware": true, "structure": 9}), json!({"offset": [-30, 0], "contentAware": true, "color": -1})] {
+ assert!(s.execute("paint.patch", p.clone()).is_err(), "{p}");
+ }
+}
+
#[test]
fn patch_destination_repairs_the_drag_target_from_the_selection() {
let mut s = session(96, 48, 16, "rgb");
@@ -864,40 +897,55 @@ fn content_aware_extend_keeps_the_original() {
#[test]
fn content_aware_move_structure_and_color_shape_the_result() {
- // Structure 7, Color 0: the content is copied exactly, edge to edge.
- let mut s = session(128, 64, 16, "rgb");
- paint_layer(&mut s, texture);
- s.execute("select.rect", json!({"x": 10, "y": 10, "width": 24, "height": 24})).unwrap();
- s.execute("paint.contentAwareMove", json!({"offset": [70, 20], "structure": 7, "mode": "extend"})).unwrap();
- for (x, y) in [(10, 10), (22, 22), (33, 33)] {
+ // Structure 7, Color 0: the content is copied exactly but for a band about a patch wide along
+ // its edge, which blends into the new surroundings; Structure 3 gives the same, bit for bit
+ // (as in Photoshop).
+ let moved = |structure: u64| {
+ let mut s = session(128, 64, 16, "rgb");
+ paint_layer(&mut s, texture);
+ s.execute("select.rect", json!({"x": 10, "y": 10, "width": 24, "height": 24})).unwrap();
+ s.execute("paint.contentAwareMove", json!({"offset": [70, 20], "structure": structure, "mode": "extend"})).unwrap();
+ s
+ };
+ let s = moved(7);
+ for (x, y) in [(16, 16), (22, 22), (27, 27)] {
let (got, want) = (rgba(&s, x + 70, y + 20), texture(x, y));
for c in 0..4 {
assert!((got[c] - want[c]).abs() <= tol(16), "strict copy at {x},{y}: {got:?} vs {want:?}");
}
}
- // A lower Structure re-synthesises an edge band: the edge differs from a plain copy, the
- // centre doesn't.
- let mut s = session(128, 64, 16, "rgb");
- paint_layer(&mut s, texture);
+ let s3 = moved(3);
+ for y in 30..54 {
+ for x in 80..104 {
+ assert_eq!(rgba(&s, x, y), rgba(&s3, x, y), "structure 3 and 7 agree at {x},{y}");
+ }
+ }
+ // Structure 2 widens the re-synthesised band: the edge differs from a plain copy, the centre
+ // doesn't. Structure 1 re-synthesises the content too, its centre included.
let copy = |s: &Session, x: i32, y: i32| (rgba(s, x + 70, y + 20), rgba(s, x, y));
- s.execute("select.rect", json!({"x": 10, "y": 10, "width": 24, "height": 24})).unwrap();
- s.execute("paint.contentAwareMove", json!({"offset": [70, 20], "structure": 1, "mode": "extend"})).unwrap();
+ let s = moved(2);
let (centre, orig) = copy(&s, 22, 22);
assert_eq!(centre, orig, "the centre is kept");
let edge = (0..24).filter(|i| copy(&s, 10 + i, 10).0 != copy(&s, 10 + i, 10).1).count();
assert!(edge > 12, "the top edge row is blended in ({edge} of 24 pixels differ)");
+ let s = moved(1);
+ let (centre, orig) = copy(&s, 22, 22);
+ assert_ne!(centre, orig, "structure 1 re-synthesises the centre too");
// Color 10 fits a bright patch to a dark place; Color 0 keeps it bright.
let mean = |color: u64| {
let mut s = session(128, 64, 32, "rgb");
paint_layer(&mut s, |x, _| if x < 64 { [0.8, 0.8, 0.8, 1.0] } else { [0.2, 0.2, 0.2, 1.0] });
- s.execute("select.rect", json!({"x": 20, "y": 20, "width": 16, "height": 16})).unwrap();
+ s.execute("select.rect", json!({"x": 20, "y": 20, "width": 24, "height": 24})).unwrap();
s.execute("paint.contentAwareMove", json!({"offset": [70, 0], "structure": 7, "color": color, "mode": "extend"})).unwrap();
- (94..102).map(|x| rgba(&s, x, 28)[0]).sum::<f32>() / 8.0
+ // The copied middle (the edge band is re-synthesised from the dark surroundings).
+ (98..106).map(|x| rgba(&s, x, 32)[0]).sum::<f32>() / 8.0
};
- let (kept, fitted) = (mean(0), mean(10));
+ let (kept, some, fitted) = (mean(0), mean(3), mean(10));
assert!((kept - 0.8).abs() < 1e-3, "color 0 keeps the colour: {kept}");
- assert!(fitted < 0.3, "color 10 adapts to the dark surroundings: {fitted}");
+ // Photoshop shifts by up to about 0.04 per step of Color.
+ assert!((some - 0.68).abs() < 0.03, "color 3 adapts part of the way: {some}");
+ assert!((fitted - 0.4).abs() < 0.03, "color 10 adapts most of the way: {fitted}");
}
#[test]
diff --git a/crates/ui-egui/src/patch_preview.rs b/crates/ui-egui/src/patch_preview.rs
index 3876343ce..b669a60ed 100644
--- a/crates/ui-egui/src/patch_preview.rs
+++ b/crates/ui-egui/src/patch_preview.rs
@@ -31,6 +31,10 @@ pub(crate) struct PatchPreview {
/// The offset of the current Patch drag, if one is dragging the patch (not drawing a lasso).
fn drag_offset(app: &mut PhotocraftApp) -> Option<[i32; 2]> {
+ // Content-Aware patches are background jobs: the canvas shows the result when it is done.
+ if app.ui.tool_options.patch_content_aware {
+ return None;
+ }
let d = app.drag.as_ref().filter(|d| d.tool == Tool::Patch)?;
let (start, mods) = (d.start, d.modifiers);
let end = d.points.last().map_or(start, |p| [p[0], p[1]]);
diff --git a/crates/ui-egui/src/retouch_ui.rs b/crates/ui-egui/src/retouch_ui.rs
index b17fc654a..74d8490e2 100644
--- a/crates/ui-egui/src/retouch_ui.rs
+++ b/crates/ui-egui/src/retouch_ui.rs
@@ -176,6 +176,23 @@ pub fn finish_patch(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2]) {
return;
}
let preview = crate::patch_preview::take(app);
+ let o = &app.ui.tool_options;
+ if o.patch_content_aware {
+ // A background job (progress dialog, Esc cancels), like the Content-Aware Move.
+ let p = json!({
+ "offset": off,
+ "contentAware": true,
+ "structure": o.patch_structure.round().clamp(1.0, 7.0),
+ "color": o.patch_color.round().clamp(0.0, 10.0),
+ "sampleAllLayers": o.sample_all_layers,
+ "target": crate::canvas::paint_target(app),
+ });
+ if let Err(e) = app.run("paint.patch", p) {
+ app.ui.status = e;
+ app.ui.status_error = true;
+ }
+ return;
+ }
let p = json!({"offset": off, "mode": app.ui.tool_options.patch_mode, "target": crate::canvas::paint_target(app)});
match app.run("paint.patch", p) {
Ok(_) => crate::patch_preview::committed(app, preview, off),
@@ -313,11 +330,25 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo
crate::widgets::checkbox(ui, &mut o.sample_all_layers, tl!("Sample All Layers"));
}
Tool::Patch => {
+ // Photoshop's options bar: Patch: Normal (Source / Destination) or Content-Aware
+ // (Structure, Color, Sample All Layers).
opt(ui, tl!("Patch:"));
- for (k, l) in [("source", tl!("Source")), ("destination", tl!("Destination"))] {
- let mut on = o.patch_mode == k;
- if crate::widgets::checkbox(ui, &mut on, l).clicked() {
- o.patch_mode = k.into();
+ let kinds = [("normal".to_string(), tl!("Normal")), ("contentAware".to_string(), tl!("Content-Aware"))];
+ let mut kind = if o.patch_content_aware { "contentAware" } else { "normal" }.to_string();
+ crate::widgets::dropdown(ui, "patch-kind", &mut kind, &kinds, 120.0);
+ o.patch_content_aware = kind == "contentAware";
+ if o.patch_content_aware {
+ opt(ui, tl!("Structure:"));
+ crate::widgets::value_field(ui, &mut o.patch_structure, 1.0..=7.0, "", 40.0);
+ opt(ui, tl!("Color:"));
+ crate::widgets::value_field(ui, &mut o.patch_color, 0.0..=10.0, "", 40.0);
+ crate::widgets::checkbox(ui, &mut o.sample_all_layers, tl!("Sample All Layers"));
+ } else {
+ for (k, l) in [("source", tl!("Source")), ("destination", tl!("Destination"))] {
+ let mut on = o.patch_mode == k;
+ if crate::widgets::checkbox(ui, &mut on, l).clicked() {
+ o.patch_mode = k.into();
+ }
}
}
crate::widgets::vline(ui, 22.0);
@@ -669,6 +700,27 @@ mod tests {
assert!(px[0] > 0.95 && px[1] > 0.95 && px[2] > 0.95, "blemish patched with the white background: {px:?}");
}
+ #[test]
+ fn patch_tool_content_aware_fills_from_where_it_is_dropped() {
+ let mut app = app();
+ app.run("paint.pencil", json!({"points": [[68, 30], [74, 30]], "size": 6, "color": "#ff0000"})).unwrap();
+ app.run("select.rect", json!({"x": 60, "y": 20, "width": 24, "height": 20})).unwrap();
+ app.ui.tool = Tool::Patch;
+ app.ui.tool_options.patch_content_aware = true;
+ app.ui.tool_options.patch_structure = 5.0;
+ app.ui.tool_options.patch_color = 3.0;
+ let m = egui::Modifiers::NONE;
+ tool_event(&mut app, ToolEvent::Down { x: 70.0, y: 30.0, pressure: 1.0 }, m);
+ tool_event(&mut app, ToolEvent::Move { x: 50.0, y: 31.0, pressure: 1.0 }, m);
+ tool_event(&mut app, ToolEvent::Up { x: 30.0, y: 30.0 }, m);
+ assert!(!app.ui.status_error, "{}", app.ui.status);
+ let (id, p) = app.session.journal.last().cloned().unwrap();
+ assert_eq!(id, "paint.patch");
+ assert_eq!((p["contentAware"].as_bool(), p["structure"].as_f64(), p["color"].as_f64()), (Some(true), Some(5.0), Some(3.0)));
+ let px = active(&app).surface().unwrap().rgba(71, 30);
+ assert!(px[0] > 0.95 && px[1] > 0.95 && px[2] > 0.95, "blemish filled from the white background: {px:?}");
+ }
+
#[test]
fn content_aware_move_tool_lassoes_then_moves_or_extends() {
for (mode, keeps) in [("move", false), ("extend", true)] {
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index 4e75923b8..8b8028690 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -478,6 +478,10 @@ pub struct ToolOptions {
pub spot_type: String,
/// Patch: source (repair the selection) | destination (repair where it is dragged).
pub patch_mode: String,
+ /// Patch: Content-Aware instead of Normal, with its Structure 1..7 and Color 0..10.
+ pub patch_content_aware: bool,
+ pub patch_structure: f32,
+ pub patch_color: f32,
/// Content-Aware Move: move | extend, Structure 1..7, Color 0..10.
pub cam_mode: String,
pub cam_structure: f32,
@@ -637,6 +641,9 @@ impl Default for ToolOptions {
clone_sample: "current".into(),
spot_type: "contentAware".into(),
patch_mode: "source".into(),
+ patch_content_aware: false,
+ patch_structure: 4.0,
+ patch_color: 0.0,
cam_mode: "move".into(),
cam_structure: 4.0,
cam_color: 0.0,