PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Content-Aware tools: faster, cancellable at once, same pixels (P21, P22, P49) (#3395)
Unemars6ecad201329a
diff --git a/crates/algo/src/content_aware.rs b/crates/algo/src/content_aware.rsindex a33d5059a..5000ad2e7 100644--- a/crates/algo/src/content_aware.rs+++ b/crates/algo/src/content_aware.rs@@ -30,7 +30,12 @@use photocraft_geom::Rect;-use crate::inpaint::{Adapt, CompleteParams, Px, complete_masked};+use std::borrow::Cow;++use photocraft_raster::{Cancelled, Interrupt};++use crate::inpaint::{Adapt, CompleteParams, Px, complete_masked, complete_masked_owned};+use crate::par;use crate::poisson::membrane_fill_with;/// Options for [`fill`].@@ -143,7 +148,8 @@ fn sample(src: Src, x: f32, y: f32, out: &mut [f32]) -> bool {}/// Transformed copy of the source: rotation (degrees) and scale about the centre, optional mirror.-fn variant(src: Src, deg: f32, scale: f32, mirror: bool) -> Variant {+/// `Err` when cancelled.+fn variant(src: Src, deg: f32, scale: f32, mirror: bool, ctl: &Interrupt) -> Result<Variant, Cancelled> {let Src { w, h, ch, .. } = src;let (s, c) = (-deg.to_radians()).sin_cos();// Output size: the rotated, scaled bounding box.@@ -153,8 +159,12 @@ fn variant(src: Src, deg: f32, scale: f32, mirror: bool) -> Variant {let (icx, icy) = ((w as f32 - 1.0) / 2.0, (h as f32 - 1.0) / 2.0);let (ocx, ocy) = ((ow as f32 - 1.0) / 2.0, (oh as f32 - 1.0) / 2.0);let mut out = Variant { w: ow, h: oh, img: vec![0.0; ow * oh * ch], ok: vec![false; ow * oh] };- let mut px = vec![0.0f32; ch];- for y in 0..oh {+ // Every pixel is sampled on its own, so the rows can be done in any order.+ let row = |y: usize, irow: &mut [f32], orow: &mut [bool]| {+ if ctl.cancelled() {+ return;+ }+ let mut px = vec![0.0f32; ch];for x in 0..ow {let (dx, dy) = ((x as f32 - ocx) / scale, (y as f32 - ocy) / scale);let mut sx = icx + dx * c - dy * s;@@ -163,13 +173,14 @@ fn variant(src: Src, deg: f32, scale: f32, mirror: bool) -> Variant {sx = (w as f32 - 1.0) - sx;}if sample(src, sx, sy, &mut px) {- let i = y * ow + x;- out.ok[i] = true;- out.img[i * ch..(i + 1) * ch].copy_from_slice(&px);+ orow[x] = true;+ irow[x * ch..(x + 1) * ch].copy_from_slice(&px);}}- }- out+ };+ par::chunks2_mut(&mut out.img, ow * ch, &mut out.ok, ow, true, row);+ ctl.check()?;+ Ok(out)}/// Fill `hole` in `img`, copying only from pixels where `source` is true (and not in the hole).@@ -191,81 +202,136 @@ pub fn fill_with(source: &[bool],opts: &FillOptions,ctl: &photocraft_raster::Interrupt,+) -> Result<Vec<f32>, photocraft_raster::Cancelled> {+ fill_cow(w, h, ch, Cow::Borrowed(img), hole, source, opts, ctl)+}++/// [`fill_with`] that fills `img` itself rather than a copy of it (a big window need not be held+/// twice). The result differs from `img` only in the hole.+#[allow(clippy::too_many_arguments)]+pub fn fill_owned(+ w: usize,+ h: usize,+ ch: usize,+ img: Vec<f32>,+ hole: &[bool],+ source: &[bool],+ opts: &FillOptions,+ ctl: &photocraft_raster::Interrupt,+) -> Result<Vec<f32>, photocraft_raster::Cancelled> {+ fill_cow(w, h, ch, Cow::Owned(img), hole, source, opts, ctl)+}++#[allow(clippy::too_many_arguments)]+fn fill_cow(+ w: usize,+ h: usize,+ ch: usize,+ img: Cow<[f32]>,+ hole: &[bool],+ source: &[bool],+ opts: &FillOptions,+ ctl: &photocraft_raster::Interrupt,) -> Result<Vec<f32>, photocraft_raster::Cancelled> {assert_eq!(img.len(), w * h * ch);assert_eq!(hole.len(), w * h);assert_eq!(source.len(), w * h);if !hole.iter().any(|h| *h) {- return Ok(img.to_vec());+ return Ok(img.into_owned());}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 };+ let ok: Vec<bool> = par::map(w * h, true, |i| !hole[i] && source[i]);+ let src = Src { w, h, ch, img: &img, ok: &ok };// Variants: the identity (which holds the hole) first, then the adaptations.let mut extra: Vec<Variant> = Vec::new();if opts.mirror {- extra.push(variant(src, 0.0, 1.0, true));+ extra.push(variant(src, 0.0, 1.0, true, ctl)?);}for ° in &opts.rotations {- extra.push(variant(src, deg, 1.0, false));+ extra.push(variant(src, deg, 1.0, false, ctl)?);}if opts.scale {- extra.push(variant(src, 0.0, 0.8, false));- extra.push(variant(src, 0.0, 1.25, false));- }+ extra.push(variant(src, 0.0, 0.8, false, ctl)?);+ extra.push(variant(src, 0.0, 1.25, false, ctl)?);+ }+ let role = |s: usize| {+ if hole[s] {+ Px::Hole+ } else if ok[s] {+ Px::Source+ } else {+ Px::Known+ }+ };// 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 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]);- roles[d] = if hole[s] {- Px::Hole- } else if ok[s] {- Px::Source- } else {- Px::Known- };+ // Without variants it is the image itself.+ let (mw, mh, mosaic, roles): (usize, usize, Option<Vec<f32>>, Vec<Px>) = if extra.is_empty() {+ (w, h, None, par::map(w * h, true, role))+ } else {+ 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 = w + gap + col_w;+ let mh = h.max(col_h);+ let mut mimg = vec![0.0f32; mw * mh * ch];+ 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]);+ roles[d] = role(s);+ }}- }- let mut oy = 0;- for v in &extra {- for y in 0..v.h {- 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]);- if v.ok[s] {- roles[d] = Px::Source;+ let mut oy = 0;+ for v in &extra {+ ctl.check()?;+ for y in 0..v.h {+ 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]);+ if v.ok[s] {+ roles[d] = Px::Source;+ }}}+ oy += v.h + gap;}- oy += v.h + gap;- }+ (mw, mh, Some(mimg), roles)+ };+ drop((extra, ok));ctl.check()?;// The completion is nearly all the work.let cancel = || ctl.cancelled();let progress = |f: f32| ctl.progress(f * 0.99);- let filled = complete_masked(mw, mh, ch, &mimg, &roles, ¶ms, &photocraft_raster::Interrupt::new(&cancel, &progress))?;- let mut out = img.to_vec();- match filled {- Some(f) => {- for y in 0..h {- for x in 0..w {- if hole[y * w + x] {- let (s, d) = ((y * mw + x) * ch, (y * w + x) * ch);- out[d..d + ch].copy_from_slice(&f[s..s + ch]);+ let inner = photocraft_raster::Interrupt::new(&cancel, &progress);+ let out = match mosaic {+ // Without variants the image itself is completed (it changes only in the hole).+ None => {+ let filled: Result<Vec<f32>, Cow<[f32]>> = match img {+ Cow::Owned(v) => complete_masked_owned(w, h, ch, v, &roles, ¶ms, &inner)?.map_err(Cow::Owned),+ Cow::Borrowed(b) => complete_masked(w, h, ch, b, &roles, ¶ms, &inner)?.ok_or(Cow::Borrowed(b)),+ };+ match filled {+ Ok(f) => f,+ Err(img) => membrane_fill_with(w, h, ch, &img, hole, ctl)?,+ }+ }+ Some(mimg) => match complete_masked(mw, mh, ch, &mimg, &roles, ¶ms, &inner)? {+ Some(f) => {+ let mut out = img.into_owned();+ for y in 0..h {+ for x in 0..w {+ if hole[y * w + x] {+ let (s, d) = ((y * mw + x) * ch, (y * w + x) * ch);+ out[d..d + ch].copy_from_slice(&f[s..s + ch]);+ }}}+ out}- }- None => out = membrane_fill_with(w, h, ch, img, hole, ctl)?,- }+ None => membrane_fill_with(w, h, ch, &img, hole, ctl)?,+ },+ };ctl.check()?;ctl.progress(1.0);Ok(out)@@ -305,36 +371,50 @@ const AUTO_SIDE: usize = 384;/// 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};+ // Never cancelled; the fallback (everything outside the hole) is unreachable.+ auto_sampling_with(w, h, ch, img, hole, &Interrupt::NONE).unwrap_or_else(|_| hole.iter().map(|h| !h).collect())+}++/// [`auto_sampling`] that can be cancelled. `Err(Cancelled)` when `ctl` was cancelled.+pub fn auto_sampling_with(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool], ctl: &Interrupt) -> Result<Vec<bool>, Cancelled> {+ use crate::segment::{FREE, HARD_FG, RgbImage, grid_cut_cancellable};assert_eq!(img.len(), w * h * ch);assert_eq!(hole.len(), w * h);- let everything: Vec<bool> = hole.iter().map(|h| !h).collect();+ let everything = || -> Vec<bool> { par::map(hole.len(), true, |i| !hole[i]) };if w == 0 || h == 0 || ch == 0 || !hole.iter().any(|h| *h) {- return everything;+ return Ok(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 {- 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];+ // Each cell sums its k × k pixels, a row of cells at a time (in the same order as one pass+ // over the image would).+ // Per cell: the sums of its colour planes, its pixel count and whether it holds the hole.+ let mut sums = vec![0.0f32; sw * sh * (nc + 2)];+ par::chunks_mut(&mut sums, sw * (nc + 2), true, |sy, row| {+ if ctl.cancelled() {+ return;+ }+ for y in sy * k..((sy + 1) * k).min(h) {+ for x in 0..w {+ let cell = &mut row[(x / k) * (nc + 2)..(x / k + 1) * (nc + 2)];+ let p = y * w + x;+ if hole[p] {+ cell[nc + 1] = 1.0;+ }+ for c in 0..nc {+ cell[c] += img[p * ch + c];+ }+ cell[nc] += 1.0;}- cnt[i] += 1.0;}- }- for pl in &mut planes {- pl.iter_mut().zip(&cnt).for_each(|(v, n)| *v /= n.max(1.0));- }+ });+ ctl.check()?;+ let cell = |i: usize| &sums[i * (nc + 2)..(i + 1) * (nc + 2)];+ let planes: Vec<Vec<f32>> = (0..nc).map(|c| (0..sw * sh).map(|i| cell(i)[c] / cell(i)[nc].max(1.0)).collect()).collect();+ let shole: Vec<bool> = (0..sw * sh).map(|i| cell(i)[nc + 1] > 0.0).collect();+ drop(sums);// 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();@@ -354,8 +434,9 @@ pub fn auto_sampling(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool])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;+ return Ok(everything());}+ ctl.check()?;// 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];@@ -410,20 +491,21 @@ pub fn auto_sampling(w: usize, h: usize, ch: usize, img: &[f32], hole: &[bool])// 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);+ ctl.check()?;+ let area =+ grid_cut_cancellable(&rgb, &cost_fg, &cost_bg, &fixed, |d2| 8.0 * (-d2 / (2.0 * 0.05 * 0.05)).exp() + 0.05, &|| ctl.cancelled()).ok_or(Cancelled)?;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];+ par::chunks_mut(&mut out, w, true, |y, row| {+ for (x, o) in row.iter_mut().enumerate() {+ *o = !hole[y * w + x] && 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;+ let n_hole = par::count(hole.len(), |i| hole[i]);+ if par::count(out.len(), |i| out[i]) < 2 * n_hole.max(64) {+ return Ok(everything());}- out+ Ok(out)}/// The Patch Tool's and the Content-Aware Move Tool's Color option (0–10) as the colour adaptation@@ -497,6 +579,36 @@ mod tests {assert_eq!(out, fill(w, h, 1, &img, &hole, &source, &FillOptions::default()), "same result as the plain fill");}+ #[test]+ fn filling_in_place_is_filling_a_copy() {+ let (w, h) = (90, 70);+ let rgb: Vec<f32> = noise(w, h, 4).iter().enumerate().map(|(i, v)| v * 0.5 + 0.3 * ((i / 3 % w) % 11 < 5) as u8 as f32).collect();+ let hole: Vec<bool> = (0..w * h).map(|i| (30..52).contains(&(i % w)) && (25..44).contains(&(i / w))).collect();+ let source: Vec<bool> = (0..w * h).map(|i| i % w < 75).collect();+ let none = Interrupt::NONE;+ for opts in [FillOptions::default(), FillOptions { color_adaptation: Adapt::NONE, mirror: true, ..Default::default() }] {+ let copy = fill_with(w, h, 3, &rgb, &hole, &source, &opts, &none).unwrap();+ let owned = fill_owned(w, h, 3, rgb.clone(), &hole, &source, &opts, &none).unwrap();+ assert_eq!(copy.iter().map(|v| v.to_bits()).collect::<Vec<_>>(), owned.iter().map(|v| v.to_bits()).collect::<Vec<_>>());+ // Only the hole changes.+ assert!((0..w * h).all(|i| hole[i] || (0..3).all(|c| owned[i * 3 + c].to_bits() == rgb[i * 3 + c].to_bits())));+ }+ // Nothing to copy from: the membrane, either way.+ let nowhere = vec![false; w * h];+ let copy = fill_with(w, h, 3, &rgb, &hole, &nowhere, &FillOptions::default(), &none).unwrap();+ assert_eq!(copy, fill_owned(w, h, 3, rgb.clone(), &hole, &nowhere, &FillOptions::default(), &none).unwrap());+ }++ #[test]+ fn auto_sampling_can_be_cancelled() {+ let (w, h) = (200, 160);+ let img: Vec<f32> = noise(w, h, 5).iter().enumerate().map(|(i, v)| v * 0.1 + if (i / 3) % w < 120 { 0.3 } else { 0.6 }).collect();+ let hole: Vec<bool> = (0..w * h).map(|i| (80..110).contains(&(i % w)) && (60..90).contains(&(i / w))).collect();+ let yes = || true;+ assert!(auto_sampling_with(w, h, 3, &img, &hole, &Interrupt::cancel_only(&yes)).is_err());+ assert_eq!(auto_sampling_with(w, h, 3, &img, &hole, &Interrupt::NONE).unwrap(), auto_sampling(w, h, 3, &img, &hole));+ }+#[test]fn fills_only_the_hole_with_known_texture() {let (w, h) = (48, 32);@@ -671,9 +783,9 @@ mod tests {let img = vec![0.5f32; 10 * 6];let ok = vec![true; 60];let src = Src { w: 10, h: 6, ch: 1, img: &img, ok: &ok };- let v = variant(src, 90.0, 1.0, false);+ let v = variant(src, 90.0, 1.0, false, &Interrupt::NONE).unwrap();assert_eq!((v.w, v.h), (6, 10));- let v = variant(src, 0.0, 0.8, true);+ let v = variant(src, 0.0, 0.8, true, &Interrupt::NONE).unwrap();assert_eq!((v.w, v.h), (8, 5));assert!(v.ok.iter().filter(|o| **o).count() > 20);}diff --git a/crates/algo/src/inpaint.rs b/crates/algo/src/inpaint.rsindex f72d2d5c2..37e91da49 100644--- a/crates/algo/src/inpaint.rs+++ b/crates/algo/src/inpaint.rs@@ -34,14 +34,23 @@//! `w × h` hole mask, and return a full buffer equal to the input outside the hole. They are//! deterministic (fixed-seed hash RNG, results independent of thread count).+use std::borrow::Cow;++use crate::par;use crate::poisson::membrane_fill;mod proximity_integral;use proximity_integral::HoleIntegral;-/// Below this many grid cells a level runs single-threaded (thread hand-off costs more than it saves).-#[cfg(not(target_arch = "wasm32"))]-const PAR_MIN: usize = 128 * 128;+/// Below this many cells a pass runs on the calling thread (thread hand-off costs more than it+/// saves). Every pass gives the same result either way.+const PAR_MIN: usize = 64 * 64;++/// [`PAR_MIN`] for the passes that match or vote a patch per cell.+const PAR_MIN_PATCHES: usize = 16 * 16;++/// Largest level (in cells) whose source patches' moments [`Solver::prepare`] keeps.+const SOURCE_MOMENTS_MAX: usize = 1 << 20;/// SplitMix64: tiny deterministic RNG.#[derive(Clone)]@@ -57,6 +66,10 @@ impl Rng {z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);z ^ (z >> 31)}+ /// Skip `n` numbers (the same state as after `n` calls of [`Rng::next`]).+ pub(crate) fn skip(&mut self, n: u64) {+ self.0 = self.0.wrapping_add(n.wrapping_mul(0x9E37_79B9_7F4A_7C15));+ }/// Uniform integer in `lo..=hi`.pub(crate) fn range(&mut self, lo: i32, hi: i32) -> i32 {if hi <= lo {@@ -128,40 +141,77 @@ pub enum Px {Hole,}-/// One pyramid level.-#[derive(Clone)]-struct Level {+/// One pyramid level. Level 0 borrows the caller's buffers until it is solved.+struct Level<'a> {w: usize,h: usize,- img: Vec<f32>,- px: Vec<Px>,+ img: Cow<'a, [f32]>,+ px: Cow<'a, [Px]>,+}++impl Level<'_> {+ const EMPTY: Level<'static> = Level { w: 0, h: 0, img: Cow::Borrowed(&[]), px: Cow::Borrowed(&[]) };+}++/// The half-open box `[x0, x1) × [y0, y1)` of a level's grid.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+struct Bounds {+ x0: usize,+ y0: usize,+ x1: usize,+ y1: usize,+}++impl Bounds {+ /// Grown by `r` on every side, within a `w × h` grid.+ fn grow(self, r: usize, w: usize, h: usize) -> Bounds {+ Bounds { x0: self.x0.saturating_sub(r), y0: self.y0.saturating_sub(r), x1: self.x1.saturating_add(r).min(w), y1: self.y1.saturating_add(r).min(h) }+ }++ /// The same box on the next coarser level (whose cells are 2 × 2 of these).+ fn half(self) -> Bounds {+ Bounds { x0: self.x0 / 2, y0: self.y0 / 2, x1: self.x1.div_ceil(2), y1: self.y1.div_ceil(2) }+ }++ fn width(&self) -> usize {+ self.x1.saturating_sub(self.x0)+ }++ fn height(&self) -> usize {+ self.y1.saturating_sub(self.y0)+ }++ fn area(&self) -> usize {+ self.width() * self.height()+ }}/// 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 {+fn downsample(l: &Level, ch: usize) -> Level<'static> {let (w, h) = (l.w.div_ceil(2), l.h.div_ceil(2));let mut img = vec![0.0f32; w * h * ch];let mut px = vec![Px::Void; w * h];- for y in 0..h {- for x in 0..w {+ let (lw, lh, limg, lpx) = (l.w, l.h, &*l.img, &*l.px);+ let row = |y: usize, irow: &mut [f32], prow: &mut [Px]| {+ for (x, p) in prow.iter_mut().enumerate() {let mut n = 0.0f32;- let o = (y * w + x) * ch;+ let o = 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 {+ if sx >= lw || sy >= lh {continue;}- let si = sy * l.w + sx;- match l.px[si] {+ let si = sy * lw + sx;+ match lpx[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];+ irow[o + c] += limg[si * ch + c];}n += 1.0;}@@ -169,10 +219,10 @@ fn downsample(l: &Level, ch: usize) -> Level {}if n > 0.0 {for c in 0..ch {- img[o + c] /= n;+ irow[o + c] /= n;}}- px[y * w + x] = if hole {+ *p = if hole {Px::Hole} else if !any {Px::Void@@ -182,11 +232,14 @@ fn downsample(l: &Level, ch: usize) -> Level {Px::Known};}- }- Level { w, h, img, px }+ };+ par::chunks2_mut(&mut img, w * ch, &mut px, w, w * h >= PAR_MIN, row);+ Level { w, h, img: Cow::Owned(img), px: Cow::Owned(px) }}-/// Summed-area table of a boolean grid (`(w+1) × (h+1)`).+/// Summed-area table of a boolean grid (`(w+1) × (h+1)`). Not inlined: in [`synthesize`] it made+/// Create Texture's candidate loop slower (measured).+#[inline(never)]fn integral(w: usize, h: usize, m: &[bool]) -> Vec<u32> {let mut s = vec![0u32; (w + 1) * (h + 1)];for y in 0..h {@@ -225,9 +278,204 @@ 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)>);+/// Bounds of the hole pixels of a role grid.+fn hole_bounds(w: usize, h: usize, px: &[Px]) -> Option<Bounds> {+ // Per row the first and last hole column; the union of the rows' spans.+ let rows: Vec<Option<(usize, usize)>> = par::map(h, w * h >= PAR_MIN, |y| {+ let row = px.get(y * w..(y + 1) * w)?;+ let x0 = row.iter().position(|k| *k == Px::Hole)?;+ let x1 = row.iter().rposition(|k| *k == Px::Hole).unwrap_or(x0) + 1;+ Some((x0, x1))+ });+ let mut b: Option<Bounds> = None;+ for (y, span) in rows.into_iter().enumerate() {+ if let Some((x0, x1)) = span {+ b = Some(match b {+ None => Bounds { x0, y0: y, x1, y1: y + 1 },+ Some(b) => Bounds { x0: b.x0.min(x0), y0: b.y0, x1: b.x1.max(x1), y1: y + 1 },+ });+ }+ }+ b+}++/// Valid source centres: the whole `2r+1` patch inside the grid and copyable. Found per row+/// (each pixel's horizontal run), then per column of runs. `None` when cancelled.+fn valid_sources(w: usize, h: usize, r: usize, px: &[Px], ctl: &photocraft_raster::Interrupt) -> Option<Vec<bool>> {+ const BAND: usize = 64;+ let side = 2 * r + 1;+ let par = w * h >= PAR_MIN;+ let mut run = vec![false; w * h];+ if w < side || h < side {+ return Some(run);+ }+ // Per row: is the run of `side` pixels centred on each one all copyable (a sliding count)?+ par::chunks_mut(&mut run, w, par, |y, out| {+ if y % BAND == 0 && ctl.cancelled() {+ return;+ }+ let row = &px[y * w..(y + 1) * w];+ let copyable = |x: usize| usize::from(row[x] == Px::Source);+ let mut count: usize = (0..side).map(copyable).sum();+ out[r] = count == side;+ for (x, o) in out.iter_mut().enumerate().take(w - r).skip(r + 1) {+ count = count + copyable(x + r) - copyable(x - r - 1);+ *o = count == side;+ }+ });+ if ctl.cancelled() {+ return None;+ }+ // Per column, in bands of rows: how many such runs end each row in a row; a centre is valid+ // where `side` of them stack up to `r` rows below it.+ let mut valid = vec![false; w * h];+ par::chunks_mut(&mut valid, BAND * w, par, |band, out| {+ if ctl.cancelled() {+ return;+ }+ let (y0, rows) = (band * BAND, out.len() / w);+ let mut stack = vec![0usize; w];+ for yy in y0.saturating_sub(r)..(y0 + rows + r).min(h) {+ for (x, n) in stack.iter_mut().enumerate() {+ *n = if run[yy * w + x] { *n + 1 } else { 0 };+ }+ // `yy` is the bottom row of centre `y`'s patch.+ if yy < y0 + r || yy < 2 * r {+ continue;+ }+ let y = yy - r;+ for (v, n) in out[(y - y0) * w..(y - y0 + 1) * w].iter_mut().zip(&stack).take(w - r).skip(r) {+ *v = *n >= side;+ }+ }+ });+ if ctl.cancelled() {+ return None;+ }+ Some(valid)+}++/// Columns per block of [`Sources`]' index.+const SOURCE_BLOCK: usize = 64;++/// The valid source centres in row-major order, indexed by counts per row and per block of+/// [`SOURCE_BLOCK`] columns (so the `k`-th is found without listing them all).+struct Sources {+ /// Valid centres before each row (`h + 1` entries).+ row_start: Vec<usize>,+ /// Per row, the valid centres in it before each block.+ block_start: Vec<u32>,+ blocks: usize,+}++impl Sources {+ fn new(valid: &[bool], w: usize) -> Sources {+ let h = valid.len().checked_div(w).unwrap_or(0);+ let blocks = w.div_ceil(SOURCE_BLOCK);+ let mut block_start = vec![0u32; h * blocks];+ // Per row: the block prefix, and the row's count.+ let counts: Vec<usize> = par::map(h, valid.len() >= PAR_MIN, |y| valid[y * w..(y + 1) * w].iter().filter(|v| **v).count());+ par::chunks_mut(&mut block_start, blocks, valid.len() >= PAR_MIN, |y, out| {+ let mut n = 0u32;+ for (b, o) in out.iter_mut().enumerate() {+ *o = n;+ n += valid[y * w + b * SOURCE_BLOCK..y * w + ((b + 1) * SOURCE_BLOCK).min(w)].iter().filter(|v| **v).count() as u32;+ }+ });+ let mut row_start = Vec::with_capacity(counts.len() + 1);+ let mut total = 0usize;+ row_start.push(0);+ for c in counts {+ total += c;+ row_start.push(total);+ }+ Sources { row_start, block_start, blocks }+ }++ fn len(&self) -> usize {+ self.row_start.last().copied().unwrap_or(0)+ }++ /// The `k`-th valid centre in row-major order (`k < len`).+ fn nth(&self, k: usize, valid: &[bool], w: usize) -> (i32, i32) {+ let y = self.row_start.partition_point(|&s| s <= k).saturating_sub(1);+ let left = k.saturating_sub(self.row_start.get(y).copied().unwrap_or(0));+ let row_blocks = self.block_start.get(y * self.blocks..(y + 1) * self.blocks).unwrap_or(&[]);+ let b = row_blocks.partition_point(|&s| s as usize <= left).saturating_sub(1);+ let mut left = left.saturating_sub(row_blocks.get(b).copied().unwrap_or(0) as usize);+ let x0 = b * SOURCE_BLOCK;+ for (x, v) in valid.iter().skip(y * w + x0).take(w.saturating_sub(x0)).enumerate() {+ if *v {+ if left == 0 {+ return ((x0 + x) as i32, y as i32);+ }+ left -= 1;+ }+ }+ (0, 0)+ }++ /// All of them, in row-major order.+ fn all(&self, valid: &[bool], w: usize) -> Vec<(i32, i32)> {+ let mut out = Vec::with_capacity(self.len());+ for (i, v) in valid.iter().enumerate() {+ if *v {+ out.push(((i % w) as i32, (i / w) as i32));+ }+ }+ out+ }+}++/// Per cell of `tb` (the hole's bounds `hb` grown by the patch radius, where all of them lie): is+/// it a target centre (its patch overlaps the hole)?+fn targets_around(w: usize, r: usize, px: &[Px], hb: Bounds, tb: Bounds) -> Vec<bool> {+ // Hole counts summed over the hole's bounds: every hole pixel lies inside them.+ let (bw, bh) = (hb.width(), hb.height());+ let mut s = vec![0u32; (bw + 1) * (bh + 1)];+ for y in 0..bh {+ let mut row = 0u32;+ for x in 0..bw {+ row += u32::from(px[(hb.y0 + y) * w + hb.x0 + x] == Px::Hole);+ s[(y + 1) * (bw + 1) + x + 1] = s[y * (bw + 1) + x + 1] + row;+ }+ }+ let mut targets = vec![false; tb.area()];+ let ri = r as i32;+ let (ox, oy) = (hb.x0 as i32, hb.y0 as i32);+ for y in tb.y0..tb.y1 {+ for x in tb.x0..tb.x1 {+ let k = (y - tb.y0) * tb.width() + (x - tb.x0);+ let (x, y) = (x as i32, y as i32);+ targets[k] = window_count(&s, bw, bh, x - ri - ox, y - ri - oy, x + ri + 1 - ox, y + ri + 1 - oy) > 0;+ }+ }+ targets+}++/// A finished coarser level: its size, pixels and match field (the source centre per cell of+/// its target box, `i32::MIN` where there is none; empty when it had nothing to copy).+struct Coarser {+ w: usize,+ h: usize,+ img: Vec<f32>,+ field: Vec<(i32, i32)>,+ tbox: Bounds,+}++impl Coarser {+ /// The match of cell `(x, y)` (`i32::MIN` outside the target box).+ fn field_at(&self, x: usize, y: usize) -> (i32, i32) {+ let t = self.tbox;+ if x < t.x0 || x >= t.x1 || y < t.y0 || y >= t.y1 {+ return (i32::MIN, i32::MIN);+ }+ self.field.get((y - t.y0) * t.width() + (x - t.x0)).copied().unwrap_or((i32::MIN, i32::MIN))+ }+}++/// Most channels whose moments the colour adaptation fits (the rest are copied as they are).+const MOM_CH: usize = 8;/// Per-level PatchMatch/EM state.struct Solver<'a> {@@ -239,11 +487,22 @@ struct Solver<'a> {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.+ /// The hole's bounds and the targets' (the hole's grown by the patch radius): nothing outside+ /// them changes or is matched. The match field, its costs and these per-target tables are+ /// kept over `tbox`, row-major.+ hole_box: Bounds,+ tbox: Bounds,+ /// Target centres (the patch overlaps the hole).targets: Vec<bool>,- /// No pixel of the level is [`Px::Void`] (patches inside the grid need no per-pixel check).- no_void: bool,+ /// Per cell of `tbox`: the whole patch is inside the grid and not void (so its distances+ /// need no bounds checks and its own moments can be kept).+ full: Vec<bool>,+ /// With colour adaptation, per cell of `tbox` and channel (at most [`MOM_CH`]): `Σt, Σt²` of+ /// the patch, for full patches, as of the last [`Solver::costs`].+ tmom: Vec<[f32; 2]>,+ /// With colour adaptation where it pays: per source centre and channel, `Σs, Σs²` of its+ /// patch (source pixels never change within a level). Empty otherwise.+ smom: Vec<[f32; 2]>,adapt: Adapt,/// Cancellation: checked per row band; a cancelled solve's output is discarded.ctl: photocraft_raster::Interrupt<'a>,@@ -268,32 +527,66 @@ impl Solver<'_> {x >= 0 && y >= 0 && (x as usize) < self.w && (y as usize) < self.h && self.valid[y as usize * self.w + x as usize]}- /// 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 {+ /// Mark the full target patches (`full`), and keep the source moments where they pay off.+ fn prepare(&mut self, keep_source_moments: bool) {+ let (w, h, r, tb) = (self.w, self.h, self.r as usize, self.tbox);+ let side = 2 * r + 1;+ let mut full = vec![false; tb.area()];+ let px = self.px;+ par::chunks_mut(&mut full, tb.width(), tb.area() >= PAR_MIN_PATCHES, |ty, out| {+ let y = tb.y0 + ty;+ if y < r || y + r >= h {+ return;+ }+ for (tx, f) in out.iter_mut().enumerate() {+ let x = tb.x0 + tx;+ if x < r || x + r >= w {+ continue;+ }+ *f = (y - r..=y + r).all(|yy| px[yy * w + x - r..yy * w + x - r + side].iter().all(|k| *k != Px::Void));+ }+ });+ self.full = full;+ if self.adapt.is_none() {+ return;+ }+ let c8 = self.ch.min(MOM_CH);+ self.tmom = vec![[0.0; 2]; tb.area() * c8];+ if !keep_source_moments {+ return;+ }+ let (ch, img, valid, ctl) = (self.ch, &*self.img, &self.valid, &self.ctl);+ let mut smom = vec![[0.0f32; 2]; w * h * c8];+ par::chunks_mut(&mut smom, w * c8, w * h >= PAR_MIN_PATCHES, |y, out| {+ if ctl.cancelled() {+ return;+ }+ for x in 0..w {+ if valid[y * w + x] {+ patch_moments(img, w, ch, c8, side, x - r, y - r, &mut out[x * c8..(x + 1) * c8]);+ }+ }+ });+ self.smom = smom;+ }++ /// Distance between the target patch at `t` (its pixels inside the grid and not void; `k` its+ /// index in the `tbox` tables) and the source patch at `s`, per sample; with colour adaptation+ /// the source is fitted first.+ #[inline]+ fn dist(&self, t: (i32, i32), k: usize, s: (i32, i32), cutoff: f32) -> f32 {+ let full = self.full[k];if !self.adapt.is_none() {- return self.dist_adapted(t, s);+ return if full { self.dist_adapted_full(k, t, s) } else { self.dist_adapted(t, s) };}+ if full { self.dist_full(t, s, cutoff) } else { self.dist_clipped(t, s, cutoff) }+ }++ /// [`Solver::dist`] without adaptation, of a patch that may be clipped.+ fn dist_clipped(&self, t: (i32, i32), s: (i32, i32), cutoff: f32) -> f32 {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;- // The usual case: the whole target patch is image. The same sums in the same order as- // below, a row at a time.- if self.no_void && t.0 >= r && t.1 >= r && t.0 + r < w && t.1 + r < h {- let len = (2 * r + 1) as usize * ch;- for dy in -r..=r {- let ti = ((t.1 + dy) as usize * self.w + (t.0 - r) as usize) * ch;- let si = ((s.1 + dy) as usize * self.w + (s.0 - r) as usize) * ch;- for (a, b) in self.img[ti..ti + len].iter().zip(&self.img[si..si + len]) {- let d = a - b;- sum += d * d;- }- if sum > cutoff * full {- return f32::INFINITY;- }- }- return sum / full;- }let mut n = 0usize;for dy in -r..=r {let ty = t.1 + dy;@@ -322,6 +615,31 @@ impl Solver<'_> {if n == 0 { f32::INFINITY } else { sum / n as f32 }}+ /// [`Solver::dist_clipped`] of a full patch: the same sums, in the same order. It gives up+ /// (infinity) as soon as the sum shows the patch is worse than `cutoff`, which the sum, only+ /// growing, can show after any pixel: the caller only asks whether it is better.+ fn dist_full(&self, t: (i32, i32), s: (i32, i32), cutoff: f32) -> f32 {+ let (w, ch, r) = (self.w, self.ch, self.r);+ let side = (2 * r + 1) as usize;+ let full = ((2 * r + 1) * (2 * r + 1)) as f32 * ch as f32;+ let (span, limit) = (side * ch, cutoff * full);+ let mut sum = 0.0f32;+ for dy in -r..=r {+ let ti = ((t.1 + dy) as usize * w + (t.0 - r) as usize) * ch;+ let si = ((s.1 + dy) as usize * w + (s.0 - r) as usize) * ch;+ for (tp, sp) in self.img[ti..ti + span].chunks_exact(ch).zip(self.img[si..si + span].chunks_exact(ch)) {+ for (a, b) in tp.iter().zip(sp) {+ let d = a - b;+ sum += d * d;+ }+ if sum > limit {+ return f32::INFINITY;+ }+ }+ }+ sum / (side * side * ch) 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 {@@ -355,133 +673,345 @@ impl Solver<'_> {n}+ /// [`Solver::moments`] of a full target patch (`k` in the `tbox` tables): the target's own+ /// sums kept from [`Solver::costs`], the source's from [`Solver::prepare`] when kept, each+ /// summed in the same order as there.+ fn moments_full(&self, k: usize, t: (i32, i32), s: (i32, i32), m: &mut [[f32; 5]]) {+ let (w, ch, r) = (self.w, self.ch, self.r);+ let c8 = m.len();+ let side = (2 * r + 1) as usize;+ let tm = &self.tmom[k * c8..(k + 1) * c8];+ let sm = self.smom.get((s.1 as usize * w + s.0 as usize) * c8..(s.1 as usize * w + s.0 as usize + 1) * c8);+ let mut acc = [[0.0f32; 3]; MOM_CH];+ for dy in -r..=r {+ let ti = ((t.1 + dy) as usize * w + (t.0 - r) as usize) * ch;+ let si = ((s.1 + dy) as usize * w + (s.0 - r) as usize) * ch;+ let (trow, srow) = (&self.img[ti..ti + side * ch], &self.img[si..si + side * ch]);+ if sm.is_some() {+ for (tp, sp) in trow.chunks_exact(ch).zip(srow.chunks_exact(ch)) {+ for c in 0..c8 {+ acc[c][2] += tp[c] * sp[c];+ }+ }+ } else {+ for (tp, sp) in trow.chunks_exact(ch).zip(srow.chunks_exact(ch)) {+ for c in 0..c8 {+ let (a, b) = (tp[c], sp[c]);+ acc[c][0] += b;+ acc[c][1] += b * b;+ acc[c][2] += a * b;+ }+ }+ }+ }+ for (c, mc) in m.iter_mut().enumerate() {+ let [ss, sss] = match sm {+ Some(sm) => sm[c],+ None => [acc[c][0], acc[c][1]],+ };+ *mc = [tm[c][0], tm[c][1], ss, sss, acc[c][2]];+ }+ }+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 mut m = [[0.0f32; 5]; MOM_CH];+ let ch = self.ch.min(MOM_CH);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)+ adapted_cost(self.adapt, n as f32, &m[..ch])+ }++ fn dist_adapted_full(&self, k: usize, t: (i32, i32), s: (i32, i32)) -> f32 {+ let mut m = [[0.0f32; 5]; MOM_CH];+ let ch = self.ch.min(MOM_CH);+ self.moments_full(k, t, s, &mut m[..ch]);+ let side = (2 * self.r + 1) as usize;+ adapted_cost(self.adapt, (side * side) as f32, &m[..ch])}/// 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)]) {+ fn transform(&self, t: (i32, i32), k: usize, 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]);+ let mut m = [[0.0f32; 5]; MOM_CH];+ let ch = self.ch.min(MOM_CH);+ let n = if self.full[k] {+ self.moments_full(k, t, s, &mut m[..ch]);+ let side = (2 * self.r + 1) as usize;+ side * side+ } else {+ 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).+ /// One PatchMatch step at target `t` (`k` in the target box) whose match is `cur`: propagation+ /// from the matches of the neighbours visited just before it (`left` in its row, `up` in its+ /// column, in this pass's direction `step`), then random search in exponentially shrinking+ /// windows around the best (two numbers from `rng` per window).+ #[allow(clippy::too_many_arguments)]+ #[inline]+ fn pm_step(+ &self,+ t: (i32, i32),+ k: usize,+ cur: ((i32, i32), f32),+ left: Option<(i32, i32)>,+ up: Option<(i32, i32)>,+ step: i32,+ rng: &mut Rng,+ search_radius: i32,+ ) -> ((i32, i32), f32) {+ let (mut best, mut bc) = cur;+ if let Some(c) = left {+ let cand = (c.0 + step, c.1);+ if self.is_valid(cand.0, cand.1) && cand != best {+ let d = self.dist(t, k, cand, bc);+ if d < bc {+ (best, bc) = (cand, d);+ }+ }+ }+ if let Some(c) = up {+ let cand = (c.0, c.1 + step);+ if self.is_valid(cand.0, cand.1) && cand != best {+ let d = self.dist(t, k, cand, bc);+ if d < bc {+ (best, bc) = (cand, d);+ }+ }+ }+ let mut rad = search_radius;+ while rad >= 1 {+ let cand = (best.0 + rng.range(-rad, rad), best.1 + rng.range(-rad, rad));+ if self.is_valid(cand.0, cand.1) && cand != best {+ let d = self.dist(t, k, cand, bc);+ if d < bc {+ (best, bc) = (cand, d);+ }+ }+ rad /= 2;+ }+ (best, bc)+ }++ /// One PatchMatch pass over all target rows, in bands of the grid's rows: each band is+ /// visited in raster order (backwards on odd passes), propagating within itself, its random+ /// numbers seeded by its index. `nnf` and `cost` are over the target box. The bands run in+ /// parallel; when there are fewer of them than threads, each is also swept in wavefronts of+ /// blocks (a cell depends only on its neighbours before it in its row and its column), which+ /// visits every cell with the same neighbours and random numbers as the raster order.fn patchmatch(&self, nnf: &mut [(i32, i32)], cost: &mut [f32], pass: usize, seed: u64, search_radius: i32) {const BAND: usize = 16;- let w = self.w;+ let tb = self.tbox;+ let tw = tb.width();+ if tw == 0 || tb.height() == 0 || nnf.len() < tb.area() || cost.len() < tb.area() {+ return;+ }let reverse = pass % 2 == 1;- let band_fn = |bi: usize, nn: &mut [(i32, i32)], co: &mut [f32]| {+ let step: i32 = if reverse { -1 } else { 1 };+ let band_seed = |bi: usize| seed ^ (bi as u64).wrapping_mul(0x2545_F491_4F6C_DD1D) ^ ((pass as u64) << 40);+ // The bands crossing the target box: index, first row, rows in the box.+ let mut bands = Vec::new();+ let mut y = tb.y0;+ while y < tb.y1 {+ let bi = y / BAND;+ let end = ((bi + 1) * BAND).min(tb.y1);+ bands.push((bi, y, end - y));+ y = end;+ }+ let threads = par::threads();+ if tb.area() >= PAR_MIN_PATCHES * 8 && !bands.is_empty() && bands.len() < threads {+ self.patchmatch_wavefront(nnf, cost, &bands, reverse, &band_seed, search_radius);+ return;+ }+ let band_fn = |bi: usize, ys: usize, nn: &mut [(i32, i32)], co: &mut [f32]| {if self.ctl.cancelled() {return;}- let mut rng = Rng::new(seed ^ (bi as u64).wrapping_mul(0x2545_F491_4F6C_DD1D) ^ ((pass as u64) << 40));- let y0 = bi * BAND;- let rows = nn.len() / w;- let step: i32 = if reverse { -1 } else { 1 };+ let rows = nn.len() / tw;+ let mut rng = Rng::new(band_seed(bi));for ry in 0..rows {+ if self.ctl.cancelled() {+ return;+ }let ly = if reverse { rows - 1 - ry } else { ry };- let y = y0 + ly;- for rx in 0..w {- let x = if reverse { w - 1 - rx } else { rx };- let li = ly * w + x;- if !self.targets[y * w + x] {+ let y = ys + ly;+ for rx in 0..tw {+ let lx = if reverse { tw - 1 - rx } else { rx };+ let li = ly * tw + lx;+ let k = (y - tb.y0) * tw + lx;+ if !self.targets[k] {continue;}- let t = (x as i32, y as i32);- let (mut best, mut bc) = (nn[li], co[li]);- // Propagation from the already-visited neighbours (within this band).- let nx = x as i32 - step;- if nx >= 0 && (nx as usize) < w {- let c = nn[ly * w + nx as usize];- let cand = (c.0 + step, c.1);- if self.is_valid(cand.0, cand.1) && cand != best {- let d = self.dist(t, cand, bc);- if d < bc {- (best, bc) = (cand, d);- }- }- }+ // Neighbours outside the target box hold no match: nothing to try.+ let nx = lx as i32 - step;+ let left = (nx >= 0 && (nx as usize) < tw).then(|| nn[ly * tw + nx as usize]);let nly = ly as i32 - step;- if nly >= 0 && (nly as usize) < rows {- let c = nn[nly as usize * w + x];- let cand = (c.0, c.1 + step);- if self.is_valid(cand.0, cand.1) && cand != best {- let d = self.dist(t, cand, bc);- if d < bc {- (best, bc) = (cand, d);- }- }- }- // Random search in exponentially shrinking windows.- let mut rad = search_radius;- while rad >= 1 {- let cand = (best.0 + rng.range(-rad, rad), best.1 + rng.range(-rad, rad));- if self.is_valid(cand.0, cand.1) && cand != best {- let d = self.dist(t, cand, bc);- if d < bc {- (best, bc) = (cand, d);- }- }- rad /= 2;- }- nn[li] = best;- co[li] = bc;+ let up = (nly >= 0 && (nly as usize) < rows).then(|| nn[nly as usize * tw + lx]);+ let t = ((tb.x0 + lx) as i32, y as i32);+ (nn[li], co[li]) = self.pm_step(t, k, (nn[li], co[li]), left, up, step, &mut rng, search_radius);}}};- #[cfg(not(target_arch = "wasm32"))]- if w * self.h >= PAR_MIN {- use rayon::prelude::*;- nnf.par_chunks_mut(BAND * w).zip(cost.par_chunks_mut(BAND * w)).enumerate().for_each(|(bi, (nn, co))| band_fn(bi, nn, co));- return;- }- for (bi, (nn, co)) in nnf.chunks_mut(BAND * w).zip(cost.chunks_mut(BAND * w)).enumerate() {- band_fn(bi, nn, co);+ // The target box's rows, band by band.+ let mut parts = Vec::with_capacity(bands.len());+ let (mut nn_rest, mut co_rest) = (&mut nnf[..tb.area()], &mut cost[..tb.area()]);+ for &(bi, ys, rows) in &bands {+ let (nn, nr) = std::mem::take(&mut nn_rest).split_at_mut(rows * tw);+ let (co, cr) = std::mem::take(&mut co_rest).split_at_mut(rows * tw);+ parts.push((bi, ys, nn, co));+ (nn_rest, co_rest) = (nr, cr);}+ let par = tb.area() >= PAR_MIN_PATCHES && parts.len() > 1;+ par::each(parts, par, |(bi, ys, nn, co)| band_fn(bi, ys, nn, co));}- /// 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;+ /// [`Solver::patchmatch`] swept in wavefronts: the cells of each band in blocks of a row, a+ /// block once the block before it in its row and the one above it (in the pass's direction)+ /// are done. A target's random numbers are those it would draw in raster order (each target+ /// draws the same count).+ fn patchmatch_wavefront(+ &self,+ nnf: &mut [(i32, i32)],+ cost: &mut [f32],+ bands: &[(usize, usize, usize)],+ reverse: bool,+ band_seed: &(dyn Fn(usize) -> u64 + Sync),+ search_radius: i32,+ ) {+ use std::sync::atomic::{AtomicU32, AtomicU64, Ordering::Relaxed};++ let tb = self.tbox;+ let tw = tb.width();+ let step: i32 = if reverse { -1 } else { 1 };+ let pack = |(x, y): (i32, i32)| (u64::from(x as u32) << 32) | u64::from(y as u32);+ let unpack = |v: u64| ((v >> 32) as u32 as i32, v as u32 as i32);+ // Random numbers each target draws.+ let mut draws = 0u64;+ let mut rad = search_radius;+ while rad >= 1 {+ draws += 2;+ rad /= 2;+ }+ // Targets before each column of each row of the box.+ let mut before = vec![0u32; tb.height() * (tw + 1)];+ for (ry, row) in before.chunks_mut(tw + 1).enumerate() {+ for lx in 0..tw {+ row[lx + 1] = row[lx] + u32::from(self.targets[ry * tw + lx]);}- 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);+ }+ // Targets visited before each of a band's rows (in the pass's order).+ let row_base: Vec<Vec<u64>> = bands+ .iter()+ .map(|&(_, ys, rows)| {+ let mut base = Vec::with_capacity(rows);+ let mut n = 0u64;+ for pr in 0..rows {+ base.push(n);+ let ly = if reverse { rows - 1 - pr } else { pr };+ n += u64::from(before[(ys + ly - tb.y0) * (tw + 1) + tw]);}+ base+ })+ .collect();+ let block = (tw / 8).clamp(4, 32);+ let blocks = tw.div_ceil(block);+ let nn: Vec<AtomicU64> = nnf[..tb.area()].iter().map(|m| AtomicU64::new(pack(*m))).collect();+ let co: Vec<AtomicU32> = cost[..tb.area()].iter().map(|c| AtomicU32::new(c.to_bits())).collect();+ let sweep = |(j, pr, b): (usize, usize, usize)| {+ let (bi, ys, rows) = bands[j];+ let ly = if reverse { rows - 1 - pr } else { pr };+ let y = ys + ly;+ let ry = y - tb.y0;+ let (pc0, pc1) = (b * block, ((b + 1) * block).min(tw));+ // The targets visited before this block, in raster order.+ let first = if reverse { tw - 1 - pc0 } else { pc0 };+ let row = &before[ry * (tw + 1)..(ry + 1) * (tw + 1)];+ let in_row = if reverse { row[tw] - row[first + 1] } else { row[first] };+ let mut rng = Rng::new(band_seed(bi));+ rng.skip((row_base[j][pr] + u64::from(in_row)) * draws);+ for pc in pc0..pc1 {+ let lx = if reverse { tw - 1 - pc } else { pc };+ let k = ry * tw + lx;+ if !self.targets[k] {+ continue;+ }+ let nx = lx as i32 - step;+ let left = (nx >= 0 && (nx as usize) < tw).then(|| unpack(nn[ry * tw + nx as usize].load(Relaxed)));+ let nly = ly as i32 - step;+ let up = (nly >= 0 && (nly as usize) < rows).then(|| unpack(nn[(ys + nly as usize - tb.y0) * tw + lx].load(Relaxed)));+ let cur = (unpack(nn[k].load(Relaxed)), f32::from_bits(co[k].load(Relaxed)));+ let t = ((tb.x0 + lx) as i32, y as i32);+ let (m, c) = self.pm_step(t, k, cur, left, up, step, &mut rng, search_radius);+ nn[k].store(pack(m), Relaxed);+ co[k].store(c.to_bits(), Relaxed);}};- #[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();+ // Wavefront `d`: block `b` of (visited) row `pr` with `pr + b = d`, in every band. Each+ // wave ends before the next starts.+ let longest = bands.iter().map(|b| b.2).max().unwrap_or(0);+ for d in 0..longest + blocks - 1 {+ if self.ctl.cancelled() {+ return;+ }+ let wave: Vec<(usize, usize, usize)> = bands+ .iter()+ .enumerate()+ .flat_map(|(j, &(_, _, rows))| (0..rows).filter(move |&pr| pr <= d && d - pr < blocks).map(move |pr| (j, pr, d - pr)))+ .collect();+ par::each(wave, true, sweep);+ }+ for (m, a) in nnf.iter_mut().zip(&nn) {+ *m = unpack(a.load(Relaxed));}- cost.chunks_mut(w).enumerate().for_each(row);+ for (c, a) in cost.iter_mut().zip(&co) {+ *c = f32::from_bits(a.load(Relaxed));+ }+ }++ /// Recompute every target's match cost (hole pixels change between iterations), and with+ /// colour adaptation the full target patches' own moments.+ fn costs(&mut self, nnf: &[(i32, i32)], cost: &mut [f32]) -> Result<(), photocraft_raster::Cancelled> {+ let (w, ch, r, tb) = (self.w, self.ch, self.r as usize, self.tbox);+ let par = tb.area() >= PAR_MIN_PATCHES;+ self.ctl.check()?;+ if !self.adapt.is_none() {+ let c8 = ch.min(MOM_CH);+ let side = 2 * r + 1;+ let mut tmom = std::mem::take(&mut self.tmom);+ let (img, full, ctl) = (&*self.img, &self.full, &self.ctl);+ par::chunks_mut(&mut tmom, tb.width() * c8, par, |ty, out| {+ if ctl.cancelled() {+ return;+ }+ for tx in 0..tb.width() {+ if full[ty * tb.width() + tx] {+ patch_moments(img, w, ch, c8, side, tb.x0 + tx - r, tb.y0 + ty - r, &mut out[tx * c8..(tx + 1) * c8]);+ }+ }+ });+ self.tmom = tmom;+ }+ let this = &*self;+ par::chunks_mut(cost, tb.width(), par, |ty, co| {+ if this.ctl.cancelled() {+ return;+ }+ let y = tb.y0 + ty;+ for (tx, c) in co.iter_mut().enumerate() {+ let k = ty * tb.width() + tx;+ if this.targets[k] {+ *c = this.dist(((tb.x0 + tx) as i32, y as i32), k, nnf[k], f32::INFINITY);+ }+ }+ });self.ctl.check()}@@ -489,8 +1019,15 @@ impl Solver<'_> {/// (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);+ let (tb, hb) = (self.tbox, self.hole_box);+ // A cancelled solve is thrown away.+ if self.ctl.cancelled() {+ return;+ }+ let used = |k: usize| self.targets[k] && cost[k].is_finite();// σ² from the 75th percentile of match costs (Wexler et al. use a robust scale like this).- let mut cs: Vec<f32> = cost.iter().zip(&self.targets).filter(|(c, t)| **t && c.is_finite()).map(|(c, _)| *c).collect();+ let cs: Vec<f32> = (0..tb.area()).filter(|&k| used(k)).map(|k| cost[k]).collect();+ let mut cs = cs;let sigma2 = if cs.is_empty() {1.0} else {@@ -498,249 +1035,456 @@ 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).+ drop(cs);+ // Each target's weight and 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 par = tb.area() >= PAR_MIN_PATCHES;+ // A weight (zero for a target that doesn't vote) and its match's centre (as a pixel+ // index) per target.+ let mut wt = vec![0.0f32; tb.area()];+ let mut src = vec![0isize; tb.area()];+ par::chunks2_mut(&mut wt, tb.width(), &mut src, tb.width(), par, |ty, wrow, srow| {+ for (tx, (o, sc)) in wrow.iter_mut().zip(srow.iter_mut()).enumerate() {+ let k = ty * tb.width() + tx;+ if used(k) {+ *o = (-cost[k] / (2.0 * sigma2)).exp().max(1e-8);+ *sc = nnf[k].1 as isize * w as isize + nnf[k].0 as isize;+ }+ }+ });+ let mut gb: Vec<(f32, f32)> = Vec::new();+ if adapted {+ gb = vec![(1.0f32, 0.0f32); tb.area() * 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]);+ par::chunks_mut(&mut gb, tb.width() * ch, par, |ty, out| {+ if this.ctl.cancelled() {+ return;+ }+ let y = tb.y0 + ty;+ for tx in 0..tb.width() {+ let k = ty * tb.width() + tx;+ if used(k) {+ this.transform(((tb.x0 + tx) as i32, y as i32), k, nnf[k], &mut out[tx * ch..(tx + 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);+ });+ }+ // The vote, into a buffer over the hole's bounds (every pixel reads the old pixels).+ let votes = Votes { w, h, ch, r: r as usize, tbox: tb, img: &*self.img, wt: &wt, src: &src, gb: &gb };+ let (px, ctl) = (self.px, &self.ctl);+ let mut out = vec![0.0f32; hb.area() * ch];+ let mut got = vec![false; hb.area()];+ let row = |yy: usize, orow: &mut [f32], grow: &mut [bool]| {+ if ctl.cancelled() {+ return;+ }+ let y = hb.y0 + yy;+ for x in hb.x0..hb.x1 {+ if px[y * w + x] != Px::Hole {+ continue;+ }+ let o = (x - hb.x0) * ch;+ let dst = &mut orow[o..o + ch];+ grow[x - hb.x0] = match (ch, adapted) {+ (1, false) => votes.pixel::<1, false>(x, y, dst),+ (3, false) => votes.pixel::<3, false>(x, y, dst),+ (4, false) => votes.pixel::<4, false>(x, y, dst),+ (1, true) => votes.pixel::<1, true>(x, y, dst),+ (3, true) => votes.pixel::<3, true>(x, y, dst),+ (4, true) => votes.pixel::<4, true>(x, y, dst),+ _ => votes.pixel_any(x, y, adapted, dst),+ };}- #[cfg(target_arch = "wasm32")]- gb.chunks_mut(w * ch).enumerate().for_each(row);- gb- } else {- Vec::new()};- // Each target's vote weight, computed once rather than for every pixel it covers.- let weight: Vec<f32> =- cost.iter().zip(&self.targets).map(|(c, t)| if *t && c.is_finite() { (-*c / (2.0 * sigma2)).exp().max(1e-8) } else { 0.0 }).collect();- let img = &*self.img;- let row = |y: usize| -> Vec<(usize, Vec<f32>)> {- let mut out = Vec::new();- if self.ctl.cancelled() {- return out;+ par::chunks2_mut(&mut out, hb.width() * ch, &mut got, hb.width(), hb.area() >= PAR_MIN_PATCHES, row);+ for yy in 0..hb.height() {+ for xx in 0..hb.width() {+ if got[yy * hb.width() + xx] {+ let (d, s) = (((hb.y0 + yy) * w + hb.x0 + xx) * ch, (yy * hb.width() + xx) * ch);+ self.img[d..d + ch].copy_from_slice(&out[s..s + ch]);+ }}- for x in 0..w {- if self.px[y * w + x] != Px::Hole {+ }+ }+}++/// What [`Solver::vote`] votes with: per target (over the target box) its weight (zero when it+/// doesn't vote), its match's centre as a pixel index, and with colour adaptation its gain and+/// bias per channel.+struct Votes<'a> {+ w: usize,+ h: usize,+ ch: usize,+ r: usize,+ tbox: Bounds,+ img: &'a [f32],+ wt: &'a [f32],+ src: &'a [isize],+ gb: &'a [(f32, f32)],+}++impl Votes<'_> {+ /// Hole pixel `(x, y)`'s vote into `out` (`CH` channels): the weighted mean of what the+ /// matches of the patches covering it put there, summed patch by patch in raster order of+ /// their centres. False when no patch votes.+ #[inline(always)]+ fn pixel<const CH: usize, const ADAPT: bool>(&self, x: usize, y: usize, out: &mut [f32]) -> bool {+ let (w, r, tb) = (self.w, self.r, self.tbox);+ let mut acc = [0.0f32; CH];+ let mut wsum = 0.0f32;+ for ty in y.saturating_sub(r)..=(y + r).min(self.h - 1) {+ let dy = ty as isize - y as isize;+ let krow = (ty - tb.y0) * tb.width();+ for tx in x.saturating_sub(r)..=(x + r).min(w - 1) {+ let k = krow + tx - tb.x0;+ let wt = self.wt[k];+ if wt == 0.0 {continue;}- let mut acc = vec![0.0f32; ch];- let mut wsum = 0.0f32;- for dy in -r..=r {- let ty = y as i32 + dy;- if ty < 0 || ty as usize >= h {- continue;- }- for dx in -r..=r {- let tx = x as i32 + dx;- if tx < 0 || tx as usize >= w {- continue;- }- let ti = ty as usize * w + tx as usize;- if !self.targets[ti] || !cost[ti].is_finite() {- continue;- }- let s = nnf[ti];- let (sx, sy) = (s.0 - dx, s.1 - dy);- let wt = weight[ti];- let si = (sy as usize * w + sx as usize) * ch;- for c in 0..ch {- 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;- }+ // The pixel of the match's patch that lands here.+ let si = (self.src[k] - dy * w as isize - (tx as isize - x as isize)) as usize * CH;+ let s = &self.img[si..si + CH];+ for c in 0..CH {+ let v = if ADAPT {+ let (g, b) = self.gb[k * CH + c];+ g * s[c] + b+ } else {+ s[c]+ };+ acc[c] += v * wt;}- if wsum > 0.0 {- acc.iter_mut().for_each(|v| *v /= wsum);- out.push((x, acc));+ wsum += wt;+ }+ }+ if wsum > 0.0 {+ for (d, a) in out.iter_mut().zip(&acc) {+ *d = a / wsum;+ }+ return true;+ }+ false+ }++ /// [`Votes::pixel`] for any number of channels.+ fn pixel_any(&self, x: usize, y: usize, adapted: bool, out: &mut [f32]) -> bool {+ let (w, r, tb, ch) = (self.w, self.r, self.tbox, self.ch);+ let mut acc = vec![0.0f32; ch];+ let mut wsum = 0.0f32;+ for ty in y.saturating_sub(r)..=(y + r).min(self.h - 1) {+ let dy = ty as isize - y as isize;+ let krow = (ty - tb.y0) * tb.width();+ for tx in x.saturating_sub(r)..=(x + r).min(w - 1) {+ let k = krow + tx - tb.x0;+ let wt = self.wt[k];+ if wt == 0.0 {+ continue;}+ let si = (self.src[k] - dy * w as isize - (tx as isize - x as isize)) as usize * ch;+ for (c, a) in acc.iter_mut().enumerate() {+ let v = if adapted {+ let (g, b) = self.gb[k * ch + c];+ g * self.img[si + c] + b+ } else {+ self.img[si + c]+ };+ *a += v * wt;+ }+ wsum += wt;}- out- };- #[cfg(not(target_arch = "wasm32"))]- let rows: Vec<Vec<(usize, Vec<f32>)>> = if w * h >= PAR_MIN {- use rayon::prelude::*;- (0..h).into_par_iter().map(row).collect()- } else {- (0..h).map(row).collect()- };- #[cfg(target_arch = "wasm32")]- let rows: Vec<Vec<(usize, Vec<f32>)>> = (0..h).map(row).collect();- for (y, r) in rows.into_iter().enumerate() {- for (x, v) in r {- self.img[(y * w + x) * ch..(y * w + x + 1) * ch].copy_from_slice(&v);+ }+ if wsum > 0.0 {+ for (d, a) in out.iter_mut().zip(&acc) {+ *d = a / wsum;+ }+ return true;+ }+ false+ }+}++/// `Σv, Σv²` per channel (the first `out.len()`) of the `side × side` patch with top-left+/// `(x0, y0)`, summed row by row, pixel by pixel, as [`Solver::moments`] does.+#[allow(clippy::too_many_arguments)]+fn patch_moments(img: &[f32], w: usize, ch: usize, c8: usize, side: usize, x0: usize, y0: usize, out: &mut [[f32; 2]]) {+ out.iter_mut().for_each(|v| *v = [0.0; 2]);+ for y in y0..y0 + side {+ let row = &img[(y * w + x0) * ch..(y * w + x0 + side) * ch];+ for p in row.chunks_exact(ch) {+ for (c, o) in out.iter_mut().enumerate().take(c8) {+ let a = p[c];+ o[0] += a;+ o[1] += a * a;}}}}+/// The adapted distance from the moments `[Σt, Σt², Σs, Σs², Σts]` of each channel over `n`+/// samples: what is left of the target after the source is fitted to it, per sample.+#[inline]+fn adapted_cost(a: Adapt, nf: f32, m: &[[f32; 5]]) -> f32 {+ let mut sum = 0.0f32;+ for mc in m {+ let (g, b) = fit(a, 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 * m.len() as f32)+}++/// `Σ (t − s)²` over a target patch's known pixels (offsets `offs` from its centre, samples+/// `tv`, `CH` per pixel) against the source patch centred at pixel `base`, summed in that order;+/// `None` once the sum reaches `limit` (it only grows).+#[inline(always)]+fn known_sse<const CH: usize>(image: &[f32], offs: &[isize], tv: &[f32], base: isize, limit: f32) -> Option<f32> {+ let mut e = 0.0f32;+ for (o, t) in offs.iter().zip(tv.as_chunks::<CH>().0) {+ let si = (base + o) as usize * CH;+ let s = &image[si..si + CH];+ for c in 0..CH {+ let d = t[c] - s[c];+ e += d * d;+ }+ if e >= limit {+ return None;+ }+ }+ Some(e)+}++/// [`known_sse`] of [`LANES`] sources at once, each against its own limit (summed in step: the+/// sums are independent, so the processor overlaps them).+#[inline(always)]+fn known_sse_lanes<const CH: usize>(image: &[f32], offs: &[isize], tv: &[f32], bases: [isize; LANES], limits: [f32; LANES]) -> [Option<f32>; LANES] {+ let mut e = [0.0f32; LANES];+ for (o, t) in offs.iter().zip(tv.as_chunks::<CH>().0) {+ for l in 0..LANES {+ let si = (bases[l] + o) as usize * CH;+ let s = &image[si..si + CH];+ for c in 0..CH {+ let d = t[c] - s[c];+ e[l] += d * d;+ }+ }+ // Sums only grow: once all of them reached their limits, none can win.+ if (0..LANES).all(|l| e[l] >= limits[l]) {+ break;+ }+ }+ std::array::from_fn(|l| (e[l] < limits[l]).then_some(e[l]))+}++/// Sources [`known_sse_lanes`] sums at once.+const LANES: usize = 4;++/// [`known_sse`] for any number of channels.+fn known_sse_any(image: &[f32], ch: usize, offs: &[isize], tv: &[f32], base: isize, limit: f32) -> Option<f32> {+ let mut e = 0.0f32;+ for (o, t) in offs.iter().zip(tv.chunks_exact(ch.max(1))) {+ let si = (base + o) as usize * ch;+ for (tc, sc) in t.iter().zip(&image[si..si + ch]) {+ let d = tc - sc;+ e += d * d;+ }+ if e >= limit {+ return None;+ }+ }+ Some(e)+}++/// The best source so far of [`onion_peel`]'s search.+#[derive(Clone, Copy)]+struct Best {+ /// Error per sample, and the place in the sources.+ v: f32,+ j: usize,+ /// Sums of squared errors from which `sum / n` is above `v`, and at least `v`.+ worse: f32,+ equal: f32,+}++/// The least sum `e ≥ 0` with `e / n > v` (`strict`) or `e / n ≥ v` in float arithmetic (the+/// quotient only grows with `e`); infinity for an infinite `v`.+fn least_sum(v: f32, n: f32, strict: bool) -> f32 {+ let holds = |e: f32| if strict { e / n > v } else { e / n >= v };+ if !v.is_finite() || !n.is_finite() || n <= 0.0 {+ return f32::INFINITY;+ }+ let mut e = (v * n).max(0.0);+ while e > 0.0 && holds(e.next_down()) {+ e = e.next_down();+ }+ while !holds(e) && e < f32::INFINITY {+ e = e.next_up();+ }+ e+}+/// 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 (the first such patch in-/// `sources` order on ties).+/// source patch that best matches what is already known around it (the first in `sources` of+/// those that match best). `hb` bounds the hole.///-/// The search is exhaustive, but most candidates are rejected early (#2771): the patch's known-/// offsets and pixels are gathered once per front pixel, the filled neighbours' sources (shifted-/// the same way, as in PatchMatch propagation; every 16th source where no neighbour is filled yet)-/// give an upper bound on the best error before the scan, and a candidate's sum of squares is-/// abandoned as soon as it can no longer win. The sum is accumulated in the same order as the-/// full one and only grows, so the chosen source, and the fill, are exactly those of the plain-/// scan.-fn onion_peel(w: usize, h: usize, ch: usize, r: i32, img: &mut [f32], px: &[Px], sources: &[(i32, i32)]) {- if ch == 0 {- return;- }- let mut known: Vec<bool> = px.iter().map(|k| matches!(k, Px::Known | Px::Source)).collect();- // Which source each filled pixel copied (`NONE` until it has been filled), and each valid- // source's index by position, to seed a pixel's search from its filled neighbours.+/// The search is exhaustive, but most sources are given up early (#2771, #2805): the target's+/// known pixels are gathered once, the search starts from where the pixel's filled neighbours+/// took their sources (or every 16th source at the hole's edge), and a source's error stops being+/// added up once it can only lose (it only grows). So it finds the same source as a plain scan in+/// order, sooner.+#[allow(clippy::too_many_arguments)]+fn onion_peel(+ w: usize,+ h: usize,+ ch: usize,+ r: i32,+ img: &mut [f32],+ px: &[Px],+ hb: Bounds,+ sources: &[(i32, i32)],+ ctl: &photocraft_raster::Interrupt,+) -> Result<(), photocraft_raster::Cancelled> {const NONE: u32 = u32::MAX;- let mut picked = vec![NONE; w * h];- let mut source_at = vec![NONE; w * h];- for (k, &(sx, sy)) in sources.iter().enumerate() {- if let Some(slot) = source_at.get_mut(sy as usize * w + sx as usize) {- *slot = u32::try_from(k).unwrap_or(NONE);- }+ let mut known: Vec<bool> = px.iter().map(|k| matches!(k, Px::Known | Px::Source)).collect();+ // Each source centre's place in `sources`, and the source each filled pixel took.+ let mut index = vec![NONE; w * h];+ for (j, &(x, y)) in sources.iter().enumerate() {+ index[y as usize * w + x as usize] = j as u32;}- let side = (2 * r + 1) as usize;+ let mut took = vec![NONE; w * h];+ let neighbours = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)];loop {- let front: Vec<usize> = (0..w * h)- .filter(|&i| {+ ctl.check()?;+ let mut front: Vec<usize> = Vec::new();+ for y in hb.y0..hb.y1 {+ for x in hb.x0..hb.x1 {+ let i = y * w + x;if known[i] || px[i] != Px::Hole {- return false;+ continue;}- let (x, y) = ((i % w) as i32, (i / w) as i32);- (-1..=1).any(|dy: i32| {+ let (x, y) = (x as i32, y as i32);+ let edge = (-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 edge {+ front.push(i);+ }+ }+ }if front.is_empty() {break;}- let (img_ro, known_ro, picked_ro) = (&*img, &known, &picked);- // The index of the best source for front pixel `i`, or `None` when no pixel around it is- // known (then pixel 0 is copied, as the plain scan did).- let best = |&i: &usize| -> Option<usize> {+ let (known_now, took_now) = (&known, &took);+ let image = &*img;+ let best = |&i: &usize| -> (Vec<f32>, u32) {let (x, y) = ((i % w) as i32, (i / w) as i32);- // The known pixels of the target patch: their offset (in pixels) and their samples, in- // the plain scan's order.+ // The known pixels of the target patch, in the plain scan's order: each one's offset+ // from the patch centre (in pixels) and its samples (gathered once, #2805).+ let side = (2 * r + 1) as usize;let mut offs: Vec<isize> = Vec::with_capacity(side * side);let mut tv: Vec<f32> = Vec::with_capacity(side * side * ch);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_ro[ty as usize * w + tx as usize] {- continue;+ if tx >= 0 && ty >= 0 && (tx as usize) < w && (ty as usize) < h && known_now[ty as usize * w + tx as usize] {+ let ti = (ty as usize * w + tx as usize) * ch;+ offs.push(dy as isize * w as isize + dx as isize);+ tv.extend_from_slice(&image[ti..ti + ch]);}- let ti = (ty as usize * w + tx as usize) * ch;- offs.push(dy as isize * w as isize + dx as isize);- tv.extend_from_slice(&img_ro[ti..ti + ch]);}}- if offs.is_empty() {- return None;- }- let n = offs.len() as f32;- // Mean square difference against the source patch centred at `base`, abandoned- // (`None`) as soon as the mean so far exceeds `bound` or reaches `best` (the final- // mean can only be larger).- let ssd = |base: isize, bound: f32, best: f32| -> Option<f32> {- let mut e = 0.0f32;- for (j, (o, t)) in offs.iter().zip(tv.chunks_exact(ch)).enumerate() {- let si = (base + o) as usize * ch;- for (tc, sc) in t.iter().zip(&img_ro[si..si + ch]) {- let d = tc - sc;- e += d * d;+ // The best so far: its error per sample, its place in `sources` (the first of equals+ // wins, as in a scan in order), and the sums of squares at which a source surely loses+ // to it (`e / n` above the best) or ties it (at least the best).+ let mut best = Best { v: f32::INFINITY, j: usize::MAX, worse: f32::INFINITY, equal: f32::INFINITY };+ if !offs.is_empty() {+ let nf = offs.len() as f32;+ let base_of = |j: usize| sources.get(j).map_or(0, |&(sx, sy)| sy as isize * w as isize + sx as isize);+ // The sum at which source `j` can't win: a tie loses to an earlier source.+ let limit_of = |j: usize, best: &Best| if j > best.j { best.equal } else { best.worse };+ // Source `j`'s whole sum `e` (it did not reach its limit): does it win?+ let adopt = |j: usize, e: f32, best: &mut Best| {+ let v = e / nf;+ if v < f32::INFINITY && (v < best.v || (v == best.v && j < best.j)) {+ *best = Best { v, j, worse: least_sum(v, nf, true), equal: least_sum(v, nf, false) };}- if j % 4 == 3 {- let m = e / n;- if m > bound || m >= best {- return None;- }+ };+ let consider = |j: usize, best: &mut Best| {+ if j >= sources.len() {+ return;}- }- Some(e / n)- };- // An upper bound on the best mean (any candidate's mean is one): the best of the filled- // neighbours' sources, each shifted with its neighbour, or, at the hole's edge where no- // neighbour is filled yet, of every 16th source.- let mut bound = f32::INFINITY;- for dy in -1..=1i32 {- for dx in -1..=1i32 {- let (nx, ny) = (x + dx, y + dy);- if nx < 0 || ny < 0 || nx as usize >= w || ny as usize >= h {+ let (base, limit) = (base_of(j), limit_of(j, best));+ let e = match ch {+ 1 => known_sse::<1>(image, &offs, &tv, base, limit),+ 3 => known_sse::<3>(image, &offs, &tv, base, limit),+ 4 => known_sse::<4>(image, &offs, &tv, base, limit),+ _ => known_sse_any(image, ch, &offs, &tv, base, limit),+ };+ if let Some(e) = e {+ adopt(j, e, best);+ }+ };+ // A close bound early: where the filled neighbours' sources point (shifted as in+ // PatchMatch's propagation), or at the hole's edge, where none is filled yet,+ // every 16th source.+ for (dx, dy) in neighbours {+ let (qx, qy) = (x + dx, y + dy);+ if qx < 0 || qy < 0 || qx as usize >= w || qy as usize >= h {continue;}- let Some(&(sx, sy)) = sources.get(picked_ro[ny as usize * w + nx as usize] as usize) else { continue };+ let Some(&(sx, sy)) = sources.get(took_now[qy as usize * w + qx as usize] as usize) else { continue };let (cx, cy) = (sx - dx, sy - dy);- if cx < 0 || cy < 0 || cx as usize >= w || cy as usize >= h || source_at[cy as usize * w + cx as usize] == NONE {- continue;+ if cx >= 0 && cy >= 0 && (cx as usize) < w && (cy as usize) < h && index[cy as usize * w + cx as usize] != NONE {+ consider(index[cy as usize * w + cx as usize] as usize, &mut best);}- if let Some(e) = ssd(cy as isize * w as isize + cx as isize, f32::INFINITY, bound) {- bound = e;+ }+ if best.j == usize::MAX {+ for j in (0..sources.len()).step_by(16) {+ consider(j, &mut best);}}- }- if bound == f32::INFINITY {- for &(sx, sy) in sources.iter().step_by(16) {- if let Some(e) = ssd(sy as isize * w as isize + sx as isize, f32::INFINITY, bound) {- bound = e;+ // The scan in order, `LANES` sources at a time (their sums are independent, so they+ // overlap), each against its limit from the best before them: the best only gets+ // better, so a source given up would have lost to it anyway.+ let mut j = 0;+ while j + LANES <= sources.len() {+ if j.is_multiple_of(4096) && j > 0 && ctl.cancelled() {+ break;}+ let bases: [isize; LANES] = std::array::from_fn(|l| base_of(j + l));+ let limits: [f32; LANES] = std::array::from_fn(|l| limit_of(j + l, &best));+ let sums = match ch {+ 1 => known_sse_lanes::<1>(image, &offs, &tv, bases, limits),+ 3 => known_sse_lanes::<3>(image, &offs, &tv, bases, limits),+ 4 => known_sse_lanes::<4>(image, &offs, &tv, bases, limits),+ _ => std::array::from_fn(|l| known_sse_any(image, ch, &offs, &tv, bases[l], limits[l])),+ };+ for (l, e) in sums.into_iter().enumerate() {+ if let Some(e) = e {+ adopt(j + l, e, &mut best);+ }+ }+ j += LANES;}- }- // The plain scan, in order, keeping the first strictly smaller mean: a candidate is- // abandoned once its mean exceeds the bound (the best is at most the bound) or reaches- // the best so far (a tie would not replace it).- let mut best = (f32::INFINITY, None);- for (k, &(sx, sy)) in sources.iter().enumerate() {- if let Some(e) = ssd(sy as isize * w as isize + sx as isize, bound, best.0)- && e < best.0- {- best = (e, Some(k));+ for j in j..sources.len() {+ consider(j, &mut best);}}- best.1- };- #[cfg(not(target_arch = "wasm32"))]- let found: Vec<Option<usize>> = {- use rayon::prelude::*;- front.par_iter().map(best).collect()+ let (sx, sy) = sources.get(best.j).copied().unwrap_or((0, 0));+ let si = (sy as usize * w + sx as usize) * ch;+ (image[si..si + ch].to_vec(), if best.j == usize::MAX { NONE } else { best.j as u32 })};- #[cfg(target_arch = "wasm32")]- let found: Vec<Option<usize>> = front.iter().map(best).collect();- // Pixel 0 as it was before this ring (what a pixel with nothing known around it copies).- let first = img[..ch].to_vec();- for (&i, k) in front.iter().zip(found) {- match k.and_then(|k| sources.get(k)) {- // Sources are never hole pixels, so none of them changes during the ring.- Some(&(sx, sy)) => img.copy_within((sy as usize * w + sx as usize) * ch..(sy as usize * w + sx as usize + 1) * ch, i * ch),- None => img[i * ch..(i + 1) * ch].copy_from_slice(&first),- }+ let vals: Vec<(Vec<f32>, u32)> = par::map(front.len(), front.len() * sources.len() >= 4096, |k| best(&front[k]));+ ctl.check()?;+ for (&i, (v, j)) in front.iter().zip(vals) {+ img[i * ch..(i + 1) * ch].copy_from_slice(&v);known[i] = true;- picked[i] = k.and_then(|k| u32::try_from(k).ok()).unwrap_or(NONE);+ took[i] = j;}}+ Ok(())}/// Content-aware completion of `hole` (see module docs), copying from any pixel outside it. Returns@@ -778,17 +1522,47 @@ pub fn complete_masked(p: &CompleteParams,ctl: &photocraft_raster::Interrupt,) -> Result<Option<Vec<f32>>, photocraft_raster::Cancelled> {+ Ok(complete_cow(w, h, ch, Cow::Borrowed(img), px, p, ctl)?.ok())+}++/// [`complete_masked`] that fills `img` itself instead of a copy of it (only the hole changes):+/// `Err(img)`, untouched, when there is nothing to copy from.+pub fn complete_masked_owned(+ w: usize,+ h: usize,+ ch: usize,+ img: Vec<f32>,+ px: &[Px],+ p: &CompleteParams,+ ctl: &photocraft_raster::Interrupt,+) -> Result<Result<Vec<f32>, Vec<f32>>, photocraft_raster::Cancelled> {+ Ok(complete_cow(w, h, ch, Cow::Owned(img), px, p, ctl)?.map_err(Cow::into_owned))+}++/// The completion, on the caller's pixels or a copy of them: `Err` gives them back when there is+/// nothing to copy from.+fn complete_cow<'a>(+ w: usize,+ h: usize,+ ch: usize,+ img: Cow<'a, [f32]>,+ px: &'a [Px],+ p: &CompleteParams,+ ctl: &photocraft_raster::Interrupt,+) -> Result<Result<Vec<f32>, Cow<'a, [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 Some(hb0) = hole_bounds(w, h, px) else { return Ok(Ok(img.into_owned())) };+ if ch == 0 {+ return Ok(Ok(Vec::new()));+ }let r = p.patch_radius.max(1);let psz = 2 * r + 1;// 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 levels = vec![Level { w, h, img, px: Cow::Borrowed(px) }];+ let mut boxes = vec![hb0];+ let mut ext = hb0.width().max(hb0.height());let mut exts = vec![ext];while let Some(l) = levels.last() {ctl.check()?;@@ -797,95 +1571,116 @@ pub fn complete_masked(}let d = downsample(l, ch);levels.push(d);+ boxes.push(boxes[boxes.len() - 1].half());ext = ext.div_ceil(2);exts.push(ext);}let nlev = levels.len();- // The coarser level's result: its size, pixels and match field (empty when it had nothing to- // copy).+ // The coarser level's result.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, 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];- for y in 0..lh as i32 {- if y % 32 == 0 {- ctl.check()?;- }- for x in 0..lw as i32 {- let i = y as usize * lw + x as usize;- 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] = window_count(&hs, lw, lh, x - ri, y - ri, x + ri + 1, y + ri + 1) > 0;- }+ let Level { w: lw, h: lh, img: limg, px: lpx } = std::mem::replace(&mut levels[li], Level::EMPTY);+ let hb = boxes[li];+ let tb = hb.grow(r, lw, lh);+ let valid = valid_sources(lw, lh, r, &lpx, ctl).ok_or(photocraft_raster::Cancelled)?;+ let sources = Sources::new(&valid, lw);+ // Nothing to copy from at the finest level: the caller falls back (and gets its pixels+ // back as they were).+ if li == 0 && sources.len() == 0 {+ return Ok(Err(limg));}+ // The level's own pixels to fill (at level 0 the caller's, or a copy made in parallel).+ let mut limg = match limg {+ Cow::Owned(v) => v,+ Cow::Borrowed(b) => {+ const CHUNK: usize = 1 << 16;+ let mut v = vec![0.0f32; b.len()];+ par::chunks_mut(&mut v, CHUNK, true, |i, d| d.copy_from_slice(&b[i * CHUNK..i * CHUNK + d.len()]));+ v+ }+ };+ let targets = targets_around(lw, r, &lpx, hb, tb);+ ctl.check()?;// 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 coarser = prev.take();+ match &coarser {+ Some(c) => {+ let (pw, ph) = (c.w, c.h);+ for y in hb.y0..hb.y1 {+ for x in hb.x0..hb.x1 {+ if lpx[y * lw + x] == Px::Hole {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]);+ limg[d..d + ch].copy_from_slice(&c.img[s..s + ch]);}}}}- None if !valid_list.is_empty() => onion_peel(lw, lh, ch, ri, &mut limg, &lpx, &valid_list),+ None if sources.len() > 0 => onion_peel(lw, lh, ch, ri, &mut limg, &lpx, hb, &sources.all(&valid, lw), ctl)?,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 {+ for (i, k) in lpx.iter().enumerate() {+ if *k == Px::Hole {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, Vec::new()));+ if sources.len() == 0 {+ prev = Some(Coarser { w: lw, h: lh, img: limg, field: Vec::new(), tbox: tb });continue;}- let no_void = !lpx.contains(&Px::Void);- let mut solver = Solver { w: lw, h: lh, ch, r: ri, img: &mut limg, px: &lpx, valid, valid_list, targets, no_void, adapt: p.adapt, ctl: *ctl };+ let refine_only = li + 1 < nlev && exts[li] > p.refine_extent;+ let n_targets = targets.iter().filter(|t| **t).count();+ // Source moments are worth keeping when there are few sources for the matches tried.+ let keep_source_moments = lw * lh <= SOURCE_MOMENTS_MAX && sources.len() <= n_targets.saturating_mul(if refine_only { 4 } else { 64 });+ let mut solver = Solver {+ w: lw,+ h: lh,+ ch,+ r: ri,+ img: &mut limg,+ px: &lpx,+ valid,+ targets,+ hole_box: hb,+ tbox: tb,+ full: Vec::new(),+ tmom: Vec::new(),+ smom: Vec::new(),+ adapt: p.adapt,+ ctl: *ctl,+ };+ solver.prepare(keep_source_moments);+ ctl.check()?;// 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 mut nnf = vec![(0i32, 0i32); lw * lh];+ let tw = tb.width();+ let mut nnf = vec![(0i32, 0i32); tb.area()];let mut upsampled = false;- for y in 0..lh {+ for y in tb.y0..tb.y1 {if y % 32 == 0 {ctl.check()?;}- for x in 0..lw {- if !solver.targets[y * lw + x] {+ for x in tb.x0..tb.x1 {+ let k = (y - tb.y0) * tw + (x - tb.x0);+ if !solver.targets[k] {continue;}let mut cand = None;- if let Some((pw, ph, _, old)) = &prev- && !old.is_empty()+ if let Some(c) = &coarser+ && !c.field.is_empty(){- let (cx, cy) = ((x / 2).min(pw - 1), (y / 2).min(ph - 1));- let (sx, sy) = old[cy * pw + cx];+ let (cx, cy) = ((x / 2).min(c.w - 1), (y / 2).min(c.h - 1));+ let (sx, sy) = c.field_at(cx, cy);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));@@ -895,16 +1690,17 @@ pub fn complete_masked(}}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[k] = cand.unwrap_or_else(|| sources.nth((rng.next() % sources.len() as u64) as usize, &solver.valid, lw));}}- let mut cost = vec![f32::INFINITY; lw * lh];+ // The coarser level has given all it had.+ drop(coarser);+ let mut cost = vec![f32::INFINITY; tb.area()];// 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} else if refine_only {@@ -934,14 +1730,17 @@ pub fn complete_masked(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();+ // A vote that saw the cancellation stopped part-way: never hand its pixels on.+ ctl.check()?;+ // Keep the match field (unmatched cells marked) for the next level (none after the last).+ let field: Vec<(i32, i32)> =+ if li == 0 { Vec::new() } else { 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, field));+ prev = Some(Coarser { w: lw, h: lh, img: limg, field, tbox: tb });}- Ok(prev.map(|(_, _, img, _)| img))+ Ok(prev.map(|c| c.img).ok_or(Cow::Owned(Vec::new())))}/// Proximity match: the displacement `(dx, dy)` (within `max_radius`) whose surroundings best match the@@ -1248,7 +2047,64 @@ mod tests {assert_eq!(best_offset(w, h, ch, &img, &hole, 2, 0), None);}- /// The exhaustive onion peel, as it was before the early-exit search (#2771).+ /// Structure, fine noise and flat patches (so that some matches tie exactly), `ch` channels.+ fn busy(w: usize, h: usize, ch: usize, seed: u64) -> Vec<f32> {+ let mut rng = Rng::new(seed);+ (0..w * h)+ .flat_map(|i| {+ let (x, y) = (i % w, i / w);+ let flat = (x / 9 + y / 7) % 5 == 0;+ let n = (rng.next() % 1000) as f32 / 1000.0;+ (0..ch)+ .map(move |c| if flat { 0.25 + 0.1 * c as f32 } else { (0.2 + 0.004 * x as f32 + 0.1 * ((x + 2 * y + c) % 6) as f32 + 0.05 * n).min(1.0) })+ })+ .collect()+ }++ fn bits(v: &[f32]) -> Vec<u32> {+ v.iter().map(|x| x.to_bits()).collect()+ }++ /// Roles: a hole, a band that is context only, a corner that is no image.+ fn roles(w: usize, h: usize, hole: &[bool]) -> Vec<Px> {+ (0..w * h)+ .map(|i| {+ let (x, y) = (i % w, i / w);+ if hole[i] {+ Px::Hole+ } else if x < 4 && y < 6 {+ Px::Void+ } else if (w * 3 / 4..w * 3 / 4 + 3).contains(&x) {+ Px::Known+ } else {+ Px::Source+ }+ })+ .collect()+ }++ #[test]+ #[cfg(not(target_arch = "wasm32"))]+ fn results_do_not_depend_on_the_thread_count() {+ // Big enough for the parallel passes, and for PatchMatch to sweep in wavefronts where+ // there are fewer bands than threads (never with one thread).+ let (w, h) = (300, 260);+ for (ch, adapt) in [(3, Adapt::NONE), (4, Adapt { gain: (0.9, 1.1), bias: 0.04 })] {+ let img = busy(w, h, ch, 3);+ let hole = disc(w, h, 140.0, 130.0, 40.0);+ let px = roles(w, h, &hole);+ let p = CompleteParams { adapt, ..Default::default() };+ let run = |threads: usize| {+ let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).build().unwrap();+ bits(&pool.install(|| complete_masked(w, h, ch, &img, &px, &p, &photocraft_raster::Interrupt::NONE)).unwrap().unwrap())+ };+ let one = run(1);+ assert_eq!(one, run(3), "{ch} channels, 3 threads");+ assert_eq!(one, run(16), "{ch} channels, 16 threads");+ }+ }++ /// The onion peel as first written: every source in order, every known pixel summed.fn onion_peel_plain(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 {@@ -1266,7 +2122,7 @@ mod tests {}).collect();if front.is_empty() {- return;+ break;}let vals: Vec<Vec<f32>> = front.iter()@@ -1304,10 +2160,11 @@ mod tests {}}+ /// #2805's case (upstream's own speed-up of the onion peel, superseded here): repeating+ /// texture with many exact ties, two holes; the result must be the plain scan's to the bit.#[test]fn onion_peel_picks_exactly_what_the_plain_scan_picks() {let (w, h, ch, r) = (48, 40, 3, 3);- // Noise over a gradient, with the left half repeating every 6 columns: many exact ties.let mut img = texture(w, h);for y in 0..h {for x in 6..w / 2 {@@ -1316,6 +2173,7 @@ mod tests {}}}+ let none = photocraft_raster::Interrupt::NONE;for hole in [disc(w, h, 20.0, 18.0, 7.5), disc(w, h, 34.0, 22.0, 5.0)] {let px: Vec<Px> = hole.iter().map(|h| if *h { Px::Hole } else { Px::Source }).collect();let near = integral(w, h, &hole);@@ -1324,13 +2182,178 @@ mod tests {.filter(|&(x, y)| window_count(&near, w, h, x - r, y - r, x + r + 1, y + r + 1) == 0).collect();let (mut fast, mut plain) = (img.clone(), img.clone());- onion_peel(w, h, ch, r, &mut fast, &px, &sources);+ onion_peel(w, h, ch, r, &mut fast, &px, hole_bounds(w, h, &px).unwrap(), &sources, &none).unwrap();onion_peel_plain(w, h, ch, r, &mut plain, &px, &sources);assert!(fast.iter().zip(&plain).all(|(a, b)| a.to_bits() == b.to_bits()));assert_ne!(fast, img);}}+ #[test]+ fn onion_peel_takes_the_plain_scans_sources() {+ let none = photocraft_raster::Interrupt::NONE;+ for (w, h, ch, seed) in [(44, 36, 1, 1), (50, 40, 3, 2), (40, 40, 4, 3)] {+ let mut img = busy(w, h, ch, seed);+ // Also an image of a few exact values, where many sources tie.+ if seed == 3 {+ img.iter_mut().for_each(|v| *v = (*v * 3.0).round() / 3.0);+ }+ let hole = disc(w, h, w as f32 * 0.45, h as f32 * 0.5, 7.5);+ let px = roles(w, h, &hole);+ let valid = valid_sources(w, h, 3, &px, &none).unwrap();+ let sources = Sources::new(&valid, w).all(&valid, w);+ let (mut a, mut b) = (img.clone(), img.clone());+ onion_peel(w, h, ch, 3, &mut a, &px, hole_bounds(w, h, &px).unwrap(), &sources, &none).unwrap();+ onion_peel_plain(w, h, ch, 3, &mut b, &px, &sources);+ assert_eq!(bits(&a), bits(&b), "{w}×{h}×{ch}");+ }+ }++ #[test]+ fn least_sum_is_where_the_quotient_crosses() {+ let mut rng = Rng::new(5);+ for i in 0..4000 {+ let n = (1 + rng.next() % 49) as f32;+ let v = match i % 4 {+ 0 => 0.0,+ 1 => (rng.next() % 1000) as f32 * 1e-9,+ _ => (rng.next() % 1_000_000) as f32 / 1_000_000.0,+ };+ for strict in [true, false] {+ let holds = |e: f32| if strict { e / n > v } else { e / n >= v };+ let e = least_sum(v, n, strict);+ assert!(holds(e), "{v} {n} {strict}: {e}");+ assert!(e == 0.0 || !holds(e.next_down()), "{v} {n} {strict}: {e} is not the least");+ }+ }+ assert_eq!(least_sum(f32::INFINITY, 4.0, true), f32::INFINITY);+ }++ #[test]+ fn valid_sources_are_the_wholly_copyable_patches() {+ let (w, h, r) = (37, 29, 2);+ let mut rng = Rng::new(9);+ let px: Vec<Px> = (0..w * h)+ .map(|_| match rng.next() % 23 {+ 0 => Px::Hole,+ 1 => Px::Void,+ 2 => Px::Known,+ _ => Px::Source,+ })+ .collect();+ let valid = valid_sources(w, h, r, &px, &photocraft_raster::Interrupt::NONE).unwrap();+ let source: Vec<bool> = px.iter().map(|k| *k == Px::Source).collect();+ let ss = integral(w, h, &source);+ let (ri, full) = (r as i32, ((2 * r + 1) * (2 * r + 1)) as u32);+ for y in 0..h as i32 {+ for x in 0..w as i32 {+ let inside = x >= ri && y >= ri && x + ri < w as i32 && y + ri < h as i32;+ let want = inside && window_count(&ss, w, h, x - ri, y - ri, x + ri + 1, y + ri + 1) == full;+ assert_eq!(valid[y as usize * w + x as usize], want, "({x}, {y})");+ }+ }+ // Counting per row and block finds the centres in order.+ let sources = Sources::new(&valid, w);+ let list = sources.all(&valid, w);+ assert!(list.len() > 10 && list.len() == sources.len());+ for (k, p) in list.iter().enumerate() {+ assert_eq!(sources.nth(k, &valid, w), *p);+ }+ // And on a grid wider than a block, with empty blocks and rows.+ let (w, h) = (300, 9);+ let wide: Vec<bool> = (0..w * h).map(|i| (i % w) % 7 == 3 && (i % w) / 64 != 2 && i / w != 4).collect();+ let sources = Sources::new(&wide, w);+ let list = sources.all(&wide, w);+ for (k, p) in list.iter().enumerate() {+ assert_eq!(sources.nth(k, &wide, w), *p);+ }+ }++ #[test]+ fn full_patches_measure_as_clipped_ones() {+ let (w, h, ch, r) = (46, 38, 4, 3);+ let mut img = busy(w, h, ch, 4);+ let hole = disc(w, h, 20.0, 18.0, 6.0);+ let px = roles(w, h, &hole);+ let none = photocraft_raster::Interrupt::NONE;+ let hb = hole_bounds(w, h, &px).unwrap();+ let tb = hb.grow(r, w, h);+ let valid = valid_sources(w, h, r, &px, &none).unwrap();+ let picks: Vec<(i32, i32)> = Sources::new(&valid, w).all(&valid, w).iter().step_by(37).copied().collect();+ assert!(picks.len() > 5);+ for adapt in [Adapt::NONE, Adapt { gain: (0.8, 1.25), bias: 0.08 }] {+ for keep in [false, true] {+ let targets = targets_around(w, r, &px, hb, tb);+ let mut s = Solver {+ w,+ h,+ ch,+ r: r as i32,+ img: &mut img,+ px: &px,+ valid: valid.clone(),+ targets,+ hole_box: hb,+ tbox: tb,+ full: Vec::new(),+ tmom: Vec::new(),+ smom: Vec::new(),+ adapt,+ ctl: none,+ };+ s.prepare(keep);+ let nnf = vec![picks[0]; tb.area()];+ let mut cost = vec![f32::INFINITY; tb.area()];+ s.costs(&nnf, &mut cost).unwrap();+ let mut checked = 0;+ for k in 0..tb.area() {+ if !s.targets[k] || !s.full[k] {+ continue;+ }+ let t = ((tb.x0 + k % tb.width()) as i32, (tb.y0 + k / tb.width()) as i32);+ for &src in &picks {+ if adapt.is_none() {+ let exact = s.dist_clipped(t, src, f32::INFINITY);+ assert_eq!(s.dist_full(t, src, f32::INFINITY).to_bits(), exact.to_bits());+ for cutoff in [exact * 0.5, exact, exact * 2.0] {+ let (a, b) = (s.dist_full(t, src, cutoff), s.dist_clipped(t, src, cutoff));+ assert_eq!(a < cutoff, b < cutoff);+ }+ } else {+ let (mut m1, mut m2) = ([[0.0f32; 5]; 4], [[0.0f32; 5]; 4]);+ s.moments_full(k, t, src, &mut m1);+ assert_eq!(s.moments(t, src, &mut m2), (2 * r + 1) * (2 * r + 1));+ assert_eq!(m1.map(|c| c.map(f32::to_bits)), m2.map(|c| c.map(f32::to_bits)));+ assert_eq!(s.dist_adapted_full(k, t, src).to_bits(), s.dist_adapted(t, src).to_bits());+ }+ checked += 1;+ }+ }+ assert!(checked > 100, "{checked}");+ }+ }+ }++ #[test]+ fn owned_completion_fills_in_place_or_gives_the_pixels_back() {+ let (w, h, ch) = (64, 52, 3);+ let img = busy(w, h, ch, 6);+ let hole = disc(w, h, 30.0, 26.0, 8.0);+ let px = roles(w, h, &hole);+ let (p, none) = (CompleteParams::default(), photocraft_raster::Interrupt::NONE);+ let borrowed = complete_masked(w, h, ch, &img, &px, &p, &none).unwrap().unwrap();+ let owned = complete_masked_owned(w, h, ch, img.clone(), &px, &p, &none).unwrap().unwrap();+ assert_eq!(bits(&owned), bits(&borrowed));+ // Nothing may be copied: no completion, and the pixels come back as they were.+ let known: Vec<Px> = px.iter().map(|k| if *k == Px::Source { Px::Known } else { *k }).collect();+ assert!(complete_masked(w, h, ch, &img, &known, &p, &none).unwrap().is_none());+ let back = complete_masked_owned(w, h, ch, img.clone(), &known, &p, &none).unwrap().unwrap_err();+ assert_eq!(bits(&back), bits(&img));+ // Cancelled, it stops.+ let yes = || true;+ assert!(complete_masked_owned(w, h, ch, img, &px, &p, &photocraft_raster::Interrupt::cancel_only(&yes)).is_err());+ }+#[test]fn synthesis_fills_hole_with_plausible_values() {let (w, h, ch) = (64, 64, 3);diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rsindex c68d2e555..ded4ad31a 100644--- a/crates/algo/src/lib.rs+++ b/crates/algo/src/lib.rs@@ -49,6 +49,7 @@ mod other;mod other2;pub mod paint;pub mod panorama;+mod par;pub mod perspective;mod photo_util;mod pixelate;diff --git a/crates/algo/src/par.rs b/crates/algo/src/par.rsnew file mode 100644index 000000000..90a848181--- /dev/null+++ b/crates/algo/src/par.rs@@ -0,0 +1,77 @@+//! Data-parallel helpers: rayon on native targets, sequential on wasm (where this crate has no+//! threads). Each gives the same result either way, and whatever `par` says.++/// `f(index, chunk)` for each `len`-item chunk of `buf`, in parallel when `par`.+pub(crate) fn chunks_mut<T: Send>(buf: &mut [T], len: usize, par: bool, f: impl Fn(usize, &mut [T]) + Sync + Send) {+ if len == 0 {+ return;+ }+ #[cfg(not(target_arch = "wasm32"))]+ if par {+ use rayon::prelude::*;+ buf.par_chunks_mut(len).enumerate().for_each(|(i, c)| f(i, c));+ return;+ }+ let _ = par;+ buf.chunks_mut(len).enumerate().for_each(|(i, c)| f(i, c));+}++/// [`chunks_mut`] over two buffers in step: the `i`-th `la`-item chunk of `a` with the `i`-th+/// `lb`-item chunk of `b`.+pub(crate) fn chunks2_mut<A: Send, B: Send>(a: &mut [A], la: usize, b: &mut [B], lb: usize, par: bool, f: impl Fn(usize, &mut [A], &mut [B]) + Sync + Send) {+ if la == 0 || lb == 0 {+ return;+ }+ #[cfg(not(target_arch = "wasm32"))]+ if par {+ use rayon::prelude::*;+ a.par_chunks_mut(la).zip(b.par_chunks_mut(lb)).enumerate().for_each(|(i, (ca, cb))| f(i, ca, cb));+ return;+ }+ let _ = par;+ a.chunks_mut(la).zip(b.chunks_mut(lb)).enumerate().for_each(|(i, (ca, cb))| f(i, ca, cb));+}++/// `[f(0), f(1), …, f(n - 1)]`, in parallel when `par`.+pub(crate) fn map<T: Send>(n: usize, par: bool, f: impl Fn(usize) -> T + Sync + Send) -> Vec<T> {+ #[cfg(not(target_arch = "wasm32"))]+ if par {+ use rayon::prelude::*;+ return (0..n).into_par_iter().map(f).collect();+ }+ let _ = par;+ (0..n).map(f).collect()+}++/// How many of `0..n` satisfy `f`.+pub(crate) fn count(n: usize, f: impl Fn(usize) -> bool + Sync + Send) -> usize {+ #[cfg(not(target_arch = "wasm32"))]+ {+ use rayon::prelude::*;+ (0..n).into_par_iter().filter(|&i| f(i)).count()+ }+ #[cfg(target_arch = "wasm32")]+ (0..n).filter(|&i| f(i)).count()+}++/// `f(item)` for each of `items`, in parallel when `par`.+pub(crate) fn each<T: Send>(items: Vec<T>, par: bool, f: impl Fn(T) + Sync + Send) {+ #[cfg(not(target_arch = "wasm32"))]+ if par {+ use rayon::prelude::*;+ items.into_par_iter().for_each(f);+ return;+ }+ let _ = par;+ items.into_iter().for_each(f);+}++/// Threads the parallel helpers can use (1 on wasm).+pub(crate) fn threads() -> usize {+ #[cfg(not(target_arch = "wasm32"))]+ {+ rayon::current_num_threads()+ }+ #[cfg(target_arch = "wasm32")]+ 1+}diff --git a/crates/algo/src/segment/maxflow.rs b/crates/algo/src/segment/maxflow.rsindex 868347ae7..dcde4ebdf 100644--- a/crates/algo/src/segment/maxflow.rs+++ b/crates/algo/src/segment/maxflow.rs@@ -23,6 +23,12 @@ const INF_DIST: u32 = u32::MAX;/// Residual capacities at or below this count as saturated (guards against float round-off/// leaving tiny positive residuals that would cause long chains of negligible augmentations).const EPS: f32 = 1e-5;+/// How many steps the max-flow loops take between asks whether to stop.+const CANCEL_EVERY: u32 = 1024;++fn never() -> bool {+ false+}/// A directed graph with source/sink terminal capacities.#[derive(Clone, Debug, Default)]@@ -110,24 +116,35 @@ impl Graph {/// Computes the maximum flow (= minimum cut capacity).pub fn maxflow(&mut self) -> f64 {+ self.maxflow_with(&never).unwrap_or(self.flow)+ }++ /// [`Graph::maxflow`] that stops when `cancel` returns true (asked every few thousand steps):+ /// `None` then, and the cut is meaningless. Not cancelled, it does exactly what+ /// [`Graph::maxflow`] does.+ pub fn maxflow_with(&mut self, cancel: &dyn Fn() -> bool) -> Option<f64> {if self.node_count() >= 4096 {let mut source = false;let mut sink = false;for &capacity in &self.tr_cap {if !capacity.is_finite() {- return self.maxflow_bk();+ return self.bk(cancel);}source |= capacity > EPS;sink |= capacity < -EPS;}if source && sink && self.r_cap.iter().all(|v| v.is_finite() && *v >= 0.0) {- return self.maxflow_push_relabel();+ return self.push_relabel(cancel);}}- self.maxflow_bk()+ self.bk(cancel)}pub(super) fn maxflow_bk(&mut self) -> f64 {+ self.bk(&never).unwrap_or(self.flow)+ }++ fn bk(&mut self, cancel: &dyn Fn() -> bool) -> Option<f64> {let n = self.node_count();let mut queue: VecDeque<u32> = VecDeque::new();let mut orphans: VecDeque<u32> = VecDeque::new();@@ -145,7 +162,12 @@ impl Graph {}}let mut time = 0u32;+ let mut steps = 0u32;while let Some(i) = queue.pop_front() {+ steps = steps.wrapping_add(1);+ if steps.is_multiple_of(CANCEL_EVERY) && cancel() {+ return None;+ }let i = i as usize;self.active[i] = false;if self.parent[i] == NONE {@@ -197,7 +219,7 @@ impl Graph {self.adopt(o as usize, time, &mut queue, &mut orphans);}}- self.flow+ Some(self.flow)}fn augment(&mut self, m: usize, orphans: &mut VecDeque<u32>) {diff --git a/crates/algo/src/segment/maxflow/push_relabel.rs b/crates/algo/src/segment/maxflow/push_relabel.rsindex 8ae7632c3..914645d4c 100644--- a/crates/algo/src/segment/maxflow/push_relabel.rs+++ b/crates/algo/src/segment/maxflow/push_relabel.rs@@ -5,14 +5,20 @@//! The existing SoA residual graph is reused. Terminal source arcs are saturated//! into a preflow; `back` keeps their reverse capacity, `excess` uses f64 so local//! f32 capacity updates do not accumulate excess-rounding drift.-use super::{EPS, Graph, NONE, TERMINAL};+use super::{CANCEL_EVERY, EPS, Graph, NONE, TERMINAL};use std::collections::VecDeque;impl Graph {+ #[cfg(test)]pub(super) fn maxflow_push_relabel(&mut self) -> f64 {+ self.push_relabel(&super::never).unwrap_or(self.flow)+ }++ /// Push/relabel; `None` when `cancel` stopped it.+ pub(super) fn push_relabel(&mut self, cancel: &dyn Fn() -> bool) -> Option<f64> {let n = self.node_count();let Some(source_height) = u32::try_from(n).ok().filter(|&n| n < u32::MAX / 2).map(|n| n + 2) else {- return self.maxflow_bk();+ return self.bk(cancel);};let mut back = vec![0.0f32; n];let mut excess = vec![0.0f64; n];@@ -34,7 +40,12 @@ impl Graph {}let mut work = 0usize;let frequency = self.r_cap.len().saturating_mul(2).saturating_add(n);+ let mut steps = 0u32;while let Some(i) = queue.pop_front() {+ steps = steps.wrapping_add(1);+ if steps.is_multiple_of(CANCEL_EVERY) && cancel() {+ return None;+ }self.active[i] = false;while excess[i] > f64::from(EPS) {if self.dist[i] == 1 && self.tr_cap[i] < -EPS {@@ -127,7 +138,7 @@ impl Graph {a = self.next[ai];}}- self.flow+ Some(self.flow)}fn global_relabel(&mut self, source_height: u32, back: &[f32]) {diff --git a/crates/algo/src/segment/mod.rs b/crates/algo/src/segment/mod.rsindex f14a22d1e..dba4ebfce 100644--- a/crates/algo/src/segment/mod.rs+++ b/crates/algo/src/segment/mod.rs@@ -242,14 +242,38 @@ pub fn grid_cut_with(img: &RgbImage, cost_fg: &[f32], cost_bg: &[f32], fixed: &[grid_cut_weighted::<true>(img, cost_fg, cost_bg, fixed, weight)}+/// [`grid_cut_with`] that stops when `cancel` returns true (asked every few thousand max-flow+/// steps): `None` then. Not cancelled, the same cut.+pub fn grid_cut_cancellable(+ img: &RgbImage,+ cost_fg: &[f32],+ cost_bg: &[f32],+ fixed: &[u8],+ weight: impl Fn(f32) -> f32,+ cancel: &dyn Fn() -> bool,+) -> Option<Vec<bool>> {+ grid_cut_impl::<true>(img, cost_fg, cost_bg, fixed, weight, cancel)+}+mod edge_starts;// The const parameter also runs the previous full scan in before/after workflow tests.fn grid_cut_weighted<const OPTIMIZED: bool>(img: &RgbImage, cost_fg: &[f32], cost_bg: &[f32], fixed: &[u8], weight: impl Fn(f32) -> f32) -> Vec<bool> {+ grid_cut_impl::<OPTIMIZED>(img, cost_fg, cost_bg, fixed, weight, &|| false).unwrap_or_default()+}++fn grid_cut_impl<const OPTIMIZED: bool>(+ img: &RgbImage,+ cost_fg: &[f32],+ cost_bg: &[f32],+ fixed: &[u8],+ weight: impl Fn(f32) -> f32,+ cancel: &dyn Fn() -> bool,+) -> Option<Vec<bool>> {let (w, h) = (img.w as i32, img.h as i32);- let Some(n) = img.w.checked_mul(img.h).filter(|&n| n < u32::MAX as usize - 2) else { return Vec::new() };+ let Some(n) = img.w.checked_mul(img.h).filter(|&n| n < u32::MAX as usize - 2) else { return Some(Vec::new()) };if img.w > i32::MAX as usize || img.h > i32::MAX as usize || [img.px.len(), cost_fg.len(), cost_bg.len(), fixed.len()].iter().any(|&len| len < n) {- return Vec::new();+ return Some(Vec::new());}let mut free = Vec::new();let mut idx = vec![u32::MAX; n];@@ -262,7 +286,7 @@ fn grid_cut_weighted<const OPTIMIZED: bool>(img: &RgbImage, cost_fg: &[f32], cos}let mut out: Vec<bool> = fixed.iter().map(|f| *f == HARD_FG).collect();if count == 0 {- return out;+ return Some(out);}let mut g = Graph::with_capacity(count as usize, count as usize * 4);for i in 0..n {@@ -307,7 +331,7 @@ fn grid_cut_weighted<const OPTIMIZED: bool>(img: &RgbImage, cost_fg: &[f32], cos}}if OPTIMIZED {- g.maxflow();+ g.maxflow_with(cancel)?;} else {g.maxflow_bk();}@@ -316,7 +340,7 @@ fn grid_cut_weighted<const OPTIMIZED: bool>(img: &RgbImage, cost_fg: &[f32], cosout[i] = g.in_source(idx[i] as usize);}}- out+ Some(out)}fn add_fixed_link(g: &mut Graph, node: usize, fixed: u8, wt: f32) {diff --git a/crates/algo/src/segment/tests.rs b/crates/algo/src/segment/tests.rsindex 68ce38348..c3a37dc6d 100644--- a/crates/algo/src/segment/tests.rs+++ b/crates/algo/src/segment/tests.rs@@ -35,6 +35,35 @@ fn maxflow_clrs_network() {assert_eq!(g.residual_out_of_source_side(), 0.0);}+#[test]+fn maxflow_can_be_cancelled_and_otherwise_cuts_the_same() {+ // A 120 × 100 grid with terminal links both ways (push/relabel) and a small one (BK).+ for (w, h) in [(120usize, 100usize), (20, 15)] {+ let mut g = Graph::with_capacity(w * h, w * h * 2);+ let mut z = 7u64;+ let mut next = || {+ z = z.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);+ (z >> 40) as f32 / (1u64 << 24) as f32+ };+ for i in 0..w * h {+ g.add_tweights(i, next() * 2.0, next() * 2.0);+ if i % w + 1 < w {+ g.add_edge(i, i + 1, next(), next());+ }+ if i + w < w * h {+ g.add_edge(i, i + w, next(), next());+ }+ }+ let (mut plain, mut asked) = (g.clone(), g.clone());+ let flow = plain.maxflow();+ assert_eq!(asked.maxflow_with(&|| false), Some(flow));+ assert!((0..w * h).all(|i| plain.in_source(i) == asked.in_source(i)));+ if w * h > 4096 {+ assert_eq!(g.maxflow_with(&|| true), None);+ }+ }+}+/// Reference max flow (Edmonds–Karp on a dense matrix; node 0 = s, n−1 = t).fn edmonds_karp(cap: &mut [Vec<f64>]) -> f64 {let n = cap.len();diff --git a/crates/engine/examples/content_aware_bench.rs b/crates/engine/examples/content_aware_bench.rsnew file mode 100644index 000000000..0fbf30ccb--- /dev/null+++ b/crates/engine/examples/content_aware_bench.rs@@ -0,0 +1,462 @@+//! Content-Aware family: timings of the perf scenarios P21, P22 and P49 (the same documents and+//! steps as `photocraft-ui-egui`'s `perf_scenarios`, without the canvas refresh), and a hash of+//! every tool's output, to check that a speed-up leaves the result bit for bit as it was.+//!+//! ```text+//! cargo run --release -p photocraft-engine --example content_aware_bench -- bench caf|heal|spot|cancel|cancelscan|full24 [reps]+//! cargo run --release -p photocraft-engine --example content_aware_bench -- hash|hash-big+//! ```+//!+//! `bench` prints one line per sample (`<scenario> <ms>`), so runs of two builds can be+//! interleaved and pooled. `hash-big` hashes the benchmarks' own fills (10 and 24 MP). `hash` prints `<case> <blake3 of the output>` for Content-Aware Fill+//! (every sampling and adaptation option), Edit › Fill Content-Aware, Delete and Fill, Spot+//! Healing, Patch and Content-Aware Move at 8, 16 and 32 bits, and for the algorithms called+//! directly on synthetic buffers (1, 3 and 4 channels).+use std::time::{Duration, Instant};++use photocraft_algo::content_aware::{self, FillOptions};+use photocraft_algo::inpaint::{self, Adapt, CompleteParams};+use photocraft_engine::Session;+use photocraft_engine::jobs::{JobId, Started};+use photocraft_geom::Rect;+use serde_json::{Value, json};++type Res<T> = Result<T, String>;++fn exec(s: &mut Session, id: &str, p: Value) -> Res<Value> {+ s.execute(id, p).map_err(|e| format!("{id}: {e}"))+}++/// Wall-clock milliseconds (mod 100 s), to line samples up with a trace.+fn epoch_ms() -> f64 {+ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0.0, |d| d.as_secs_f64() * 1000.0) % 100000.0+}++fn ms(t: Instant) -> f64 {+ t.elapsed().as_secs_f64() * 1000.0+}++/// `perf_scenarios`' photo: gradients, a soft blob, fine noise and a high-contrast disc, through+/// JPEG so it opens like a real photo.+fn open_photo(w: u32, h: u32) -> Res<Session> {+ use rayon::prelude::*;+ let mut px = vec![0u8; w as usize * h as usize * 3];+ let (cx, cy, r) = (w as f32 * 0.55, h as f32 * 0.5, w.min(h) as f32 / 3.0);+ px.par_chunks_mut(w as usize * 3).enumerate().for_each(|(y, row)| {+ for x in 0..w as usize {+ let (fx, fy) = (x as f32 / w as f32, y as f32 / h as f32);+ let n = ((x.wrapping_mul(73_856_093) ^ y.wrapping_mul(19_349_663)) % 997) as f32 / 997.0 - 0.5;+ let blob = (-(((fx - 0.4) * 3.0).powi(2) + ((fy - 0.55) * 4.0).powi(2))).exp();+ let inside = ((x as f32 - cx).powi(2) + (y as f32 - cy).powi(2)).sqrt() < r;+ let (r0, g0, b0) = if inside { (0.85, 0.3 + 0.2 * (fx * 40.0).sin(), 0.15) } else { (0.35, 0.45, 0.55) };+ let rgb = [r0 + 0.1 * blob + n * 0.08, g0 + 0.1 * blob + n * 0.08, b0 + 0.2 * fy + n * 0.08];+ for (c, v) in rgb.into_iter().enumerate() {+ row[x * 3 + c] = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;+ }+ }+ });+ let img =+ photocraft_codecs::Image::from_raw(w, h, photocraft_codecs::ChannelLayout::Rgb, photocraft_codecs::SampleType::U8, px).map_err(|e| e.to_string())?;+ let jpeg = photocraft_codecs::encode(&img, photocraft_codecs::Format::Jpeg, &Default::default()).map_err(|e| e.to_string())?;+ let doc = photocraft_io::import("photo.jpg", &jpeg).map_err(|e| e.to_string())?.document;+ let mut s = Session::new();+ s.open_document(doc, Some("photo.jpg".into()));+ Ok(s)+}++/// Minor page faults of this process so far (Linux; 0 elsewhere).+fn minor_faults() -> u64 {+ std::fs::read_to_string("/proc/self/stat")+ .ok()+ .and_then(|st| st.rsplit(')').next().and_then(|rest| rest.split_whitespace().nth(7)?.parse().ok()))+ .unwrap_or(0)+}++fn start_job(s: &mut Session, id: &str, p: Value) -> Res<JobId> {+ match s.start(id, p).map_err(|e| format!("{id}: {e}"))? {+ Started::Job(j) => Ok(j),+ Started::Done(_) => Err(format!("{id} did not run as a background job")),+ }+}++fn wait_job(s: &mut Session, id: JobId) -> Res<()> {+ let t = Instant::now();+ loop {+ if s.poll_jobs().iter().any(|e| e.id == id) {+ return Ok(());+ }+ if t.elapsed().as_secs() > 120 {+ return Err("job did not finish in 120 s".into());+ }+ std::thread::sleep(Duration::from_millis(1));+ }+}++fn bench(which: &str, reps: usize) -> Res<()> {+ match which {+ // P21: Content-Aware Fill 10 MP (200 px hole).+ "caf" => {+ let (w, h) = (3872u32, 2592u32);+ let mut s = open_photo(w, h)?;+ for i in 1..=reps {+ exec(&mut s, "select.rect", json!({"x": w / 3 + i as u32 * 40, "y": h / 3, "width": 200, "height": 200, "ellipse": true}))?;+ let t = Instant::now();+ exec(&mut s, "edit.contentAwareFill", json!({"seed": i}))?;+ println!("caf {:.3}", ms(t));+ exec(&mut s, "edit.undo", json!({}))?;+ exec(&mut s, "select.deselect", json!({}))?;+ }+ }+ // P22: Spot Healing stroke 10 MP.+ "heal" => {+ let (w, h) = (3872u32, 2592u32);+ let mut s = open_photo(w, h)?;+ for i in 1..=reps {+ let (x, y) = (w / 4 + i as u32 * 60, h / 4);+ let pts: Vec<Value> = (0..10).map(|k| json!([x + k * 12, y + k * 4])).collect();+ let t = Instant::now();+ exec(&mut s, "paint.spotHealing", json!({"points": pts, "size": 60}))?;+ println!("heal {:.3}", ms(t));+ }+ }+ // P49: cancel a Content-Aware Fill job on 24 MP, early, midway and late.+ "cancel" => {+ let (w, h) = (6000u32, 4000u32);+ let mut s = open_photo(w, h)?;+ exec(&mut s, "select.rect", json!({"x": w / 3, "y": h / 3, "width": w / 5, "height": h / 4}))?;+ for i in 1..=reps {+ let job = start_job(&mut s, "edit.contentAwareFill", json!({}))?;+ let after = 20 + (i as u64 * 97) % 700;+ std::thread::sleep(Duration::from_millis(after));+ let t = Instant::now();+ s.cancel_job(job);+ s.join_cancelled_jobs();+ println!("cancel {:.3} (after {after} ms)", ms(t));+ wait_job(&mut s, job)?;+ }+ }+ // P49's job cancelled every `reps` ms through its run: where cancelling waits longest.+ "cancelscan" => {+ let (w, h) = (6000u32, 4000u32);+ let mut s = open_photo(w, h)?;+ exec(&mut s, "select.rect", json!({"x": w / 3, "y": h / 3, "width": w / 5, "height": h / 4}))?;+ let env = |k: &str, d: u64| std::env::var(k).ok().and_then(|v| v.parse().ok()).unwrap_or(d);+ let (mut after, until) = (env("CAF_SCAN_FROM", 10), env("CAF_SCAN_TO", 2500));+ while after < until {+ let job = start_job(&mut s, "edit.contentAwareFill", json!({}))?;+ std::thread::sleep(Duration::from_millis(after));+ let t = Instant::now();+ if std::env::var_os("CAF_TRACE").is_some() {+ eprintln!("CANCEL @{:.1}", epoch_ms());+ }+ s.cancel_job(job);+ s.join_cancelled_jobs();+ println!("cancelscan {:.3} (after {after} ms)", ms(t));+ if std::env::var_os("CAF_TRACE").is_some() {+ eprintln!("JOINED @{:.1}", epoch_ms());+ }+ wait_job(&mut s, job)?;+ after += reps.max(1) as u64;+ }+ }+ // `retouch_bench`'s Spot Healing dabs (sizes 50, 100, 200, 300; Content-Aware, or the type+ // in `CAF_SPOT_TYPE`) on its 6016² document, `reps` rounds.+ "spot" => {+ let side = 6016u32;+ let mut s = Session::new();+ exec(&mut s, "file.new", json!({"width": side, "height": side, "depth": 8}))?;+ let area = Rect::new(2000, 2000, 4048, 4048);+ s.edit("texture", |doc, active| {+ let Some(surf) = active.and_then(|id| doc.layer_mut(id)).and_then(|l| l.surface_mut()) else { return Ok(()) };+ let fmt = surf.format();+ let mut data = Vec::with_capacity(area.width() as usize * area.height() as usize * 4);+ for y in area.y0..area.y1 {+ for x in area.x0..area.x1 {+ let n = ((x.wrapping_mul(73_856_093) ^ y.wrapping_mul(19_349_663)) as u32 % 1000) as f32 / 1000.0 * 0.08 - 0.04;+ let blemish = (x % 400 - 200).abs() < 8 && (y % 400 - 200).abs() < 8;+ let v = if blemish {+ [0.05, 0.05, 0.05, 1.0]+ } else {+ [0.3 + 0.0002 * x as f32 + n, 0.4 + ((x + y) as f32 * 0.01).sin() * 0.1 + n, 0.5 + n, 1.0]+ };+ data.extend(photocraft_raster::from_rgba(&fmt, v));+ }+ }+ surf.write_region(area, &data);+ Ok(())+ })+ .map_err(|e| e.to_string())?;+ // Comma-separated types, run in turn (`CAF_SPOT_TYPE`, default Content-Aware).+ let kinds = std::env::var("CAF_SPOT_TYPE").unwrap_or_else(|_| "contentAware".into());+ let mut k = 4u32;+ for _ in 0..reps {+ for kind in kinds.split(',') {+ for size in [50.0, 100.0, 200.0, 300.0] {+ k += 1;+ let (x, y) = (2200 + (k % 4) * 400, 2200 + (k / 4 % 4) * 400);+ let (t, f) = (Instant::now(), minor_faults());+ exec(&mut s, "paint.spotHealing", json!({"points": [[x, y]], "size": size, "hardness": 50, "type": kind}))?;+ println!("{}{size} {:.3} faults {}", &kind[..4], ms(t), minor_faults().saturating_sub(f));+ }+ }+ }+ }+ // The whole 24 MP fill, uncancelled (how long P49's job runs).+ "full24" => {+ let (w, h) = (6000u32, 4000u32);+ let mut s = open_photo(w, h)?;+ exec(&mut s, "select.rect", json!({"x": w / 3, "y": h / 3, "width": w / 5, "height": h / 4}))?;+ for _ in 1..=reps {+ let t = Instant::now();+ exec(&mut s, "edit.contentAwareFill", json!({}))?;+ println!("full24 {:.3}", ms(t));+ exec(&mut s, "edit.undo", json!({}))?;+ }+ }+ o => return Err(format!("unknown scenario `{o}` (caf|heal|spot|cancel|cancelscan|full24)")),+ }+ Ok(())+}++fn hash_f32(v: &[f32]) -> String {+ let mut hs = blake3::Hasher::new();+ for x in v {+ hs.update(&x.to_bits().to_le_bytes());+ }+ hs.finalize().to_hex()[..16].to_string()+}++/// The active layer's pixels over the canvas.+fn layer_hash(s: &Session) -> Res<String> {+ let d = s.active().ok_or("no document")?;+ let id = d.active_layer.ok_or("no active layer")?;+ let surf = d.doc.layer(id).and_then(|l| l.surface()).ok_or("no surface")?;+ Ok(hash_f32(&surf.read_region(d.doc.bounds())))+}++/// A textured document: gradients, stripes, a bright band, blobs and fine noise.+fn textured(w: u32, h: u32, depth: u64) -> Res<Session> {+ let mut s = Session::new();+ exec(&mut s, "file.new", json!({"width": w, "height": h, "depth": depth}))?;+ s.edit("texture", |doc, active| {+ let Some(surf) = active.and_then(|id| doc.layer_mut(id)).and_then(|l| l.surface_mut()) else { return Ok(()) };+ let fmt = surf.format();+ let area = Rect::new(0, 0, w as i32, h as i32);+ let mut data = Vec::with_capacity(w as usize * h as usize * 4);+ for y in 0..h as i32 {+ for x in 0..w as i32 {+ let n = ((x.wrapping_mul(73_856_093) ^ y.wrapping_mul(19_349_663)) as u32 % 1000) as f32 / 1000.0 * 0.08 - 0.04;+ let stripe = if (x / 9) % 2 == 0 { 0.1 } else { 0.0 };+ let band = if (x - y / 2).rem_euclid(400) < 40 { 0.25 } else { 0.0 };+ let blob = (-(((x as f32 / w as f32 - 0.6) * 4.0).powi(2) + ((y as f32 / h as f32 - 0.4) * 5.0).powi(2))).exp() * 0.2;+ let v = [0.25 + 0.0002 * x as f32 + stripe + band + n, 0.4 + ((x + y) as f32 * 0.02).sin() * 0.1 + blob + n, 0.5 + band * 0.5 - blob + n, 1.0];+ data.extend(photocraft_raster::from_rgba(&fmt, v.map(|c| c.clamp(0.0, 1.0))));+ }+ }+ surf.write_region(area, &data);+ Ok(())+ })+ .map_err(|e| e.to_string())?;+ Ok(s)+}++/// The tools on an 8-bit document converted to another colour mode.+fn mode_cases(mode: &str, out: &mut Vec<(String, String)>) -> Res<()> {+ let mut s = textured(600, 450, 8)?;+ exec(&mut s, &format!("image.mode.{mode}"), json!({}))?;+ let mut step = |s: &mut Session, name: &str, cmds: &[(&str, Value)]| -> Res<()> {+ for (id, p) in cmds {+ exec(s, id, p.clone())?;+ }+ out.push((format!("{mode}/{name}"), layer_hash(s)?));+ Ok(())+ };+ let ellipse = |x: u32, y: u32, sw: u32, sh: u32| ("select.rect", json!({"x": x, "y": y, "width": sw, "height": sh, "ellipse": true}));+ step(&mut s, "caf-auto", &[ellipse(250, 200, 70, 60), ("edit.contentAwareFill", json!({}))])?;+ step(&mut s, "caf-none", &[ellipse(400, 120, 50, 50), ("edit.contentAwareFill", json!({"colorAdaptation": "none", "sampling": "rectangular"}))])?;+ step(&mut s, "patch-ca", &[ellipse(120, 300, 50, 40), ("paint.patch", json!({"offset": [150, -80], "contentAware": true, "color": 4}))])?;+ step(&mut s, "move", &[ellipse(450, 320, 60, 50), ("paint.contentAwareMove", json!({"offset": [-90, -60]}))])?;+ exec(&mut s, "select.deselect", json!({}))?;+ step(&mut s, "spot", &[("paint.spotHealing", json!({"points": [[100, 100], [130, 110], [160, 125]], "size": 30}))])?;+ Ok(())+}++fn doc_cases(depth: u64, out: &mut Vec<(String, String)>) -> Res<()> {+ let (w, h) = (900u32, 700u32);+ let mut s = textured(w, h, depth)?;+ let mut step = |s: &mut Session, name: &str, cmds: &[(&str, Value)]| -> Res<()> {+ for (id, p) in cmds {+ exec(s, id, p.clone())?;+ }+ let hash = layer_hash(s)?;+ // A case that changes nothing checks nothing.+ let same = out.last().is_some_and(|(_, prev): &(String, String)| *prev == hash);+ out.push((format!("doc{depth}/{name}"), if same { format!("{hash} UNCHANGED") } else { hash }));+ Ok(())+ };+ let ellipse = |x: u32, y: u32, sw: u32, sh: u32| ("select.rect", json!({"x": x, "y": y, "width": sw, "height": sh, "ellipse": true}));+ step(&mut s, "caf-auto", &[ellipse(400, 300, 90, 70), ("edit.contentAwareFill", json!({}))])?;+ step(+ &mut s,+ "caf-rect-none",+ &[ellipse(150, 120, 60, 80), ("edit.contentAwareFill", json!({"sampling": "rectangular", "colorAdaptation": "none", "seed": 3}))],+ )?;+ step(&mut s, "caf-high-rot", &[ellipse(600, 450, 40, 40), ("edit.contentAwareFill", json!({"colorAdaptation": "high", "rotationAdaptation": "low"}))])?;+ step(+ &mut s,+ "caf-veryhigh-mirror-scale",+ &[+ ellipse(700, 150, 36, 30),+ ("edit.contentAwareFill", json!({"colorAdaptation": "veryHigh", "mirror": true, "scale": true, "rotationAdaptation": "full"})),+ ],+ )?;+ step(&mut s, "caf-custom", &[ellipse(300, 500, 50, 50), ("edit.contentAwareFill", json!({"sampling": "custom", "area": [100, 400, 200, 250]}))])?;+ // A wide hole: the finest levels only refine (the hole is wider than `refine_extent`).+ step(&mut s, "caf-big", &[("select.rect", json!({"x": 300, "y": 200, "width": 330, "height": 250})), ("edit.contentAwareFill", json!({"seed": 9}))])?;+ step(&mut s, "fill-ca", &[ellipse(200, 300, 50, 60), ("edit.fill", json!({"contents": "contentAware"}))])?;+ step(&mut s, "fill-ca-noadapt", &[ellipse(650, 550, 50, 40), ("edit.fill", json!({"contents": "contentAware", "colorAdaptation": false}))])?;+ step(&mut s, "delete-and-fill", &[ellipse(100, 600, 45, 45), ("edit.deleteAndFillSelection", json!({}))])?;+ exec(&mut s, "select.deselect", json!({}))?;+ for (k, kind) in ["contentAware", "proximityMatch", "createTexture"].into_iter().enumerate() {+ let (x, y) = (150 + 220 * k as u32, 250);+ let pts: Vec<Value> = (0..8).map(|j| json!([x + j * 10, y + j * 5])).collect();+ step(&mut s, &format!("spot-{kind}"), &[("paint.spotHealing", json!({"points": pts, "size": 40, "type": kind}))])?;+ }+ step(&mut s, "spot-dab", &[("paint.spotHealing", json!({"points": [[820, 640]], "size": 25}))])?;+ step(&mut s, "patch-normal", &[ellipse(350, 100, 60, 50), ("paint.patch", json!({"offset": [120, 60]}))])?;+ step(&mut s, "patch-ca", &[ellipse(500, 450, 70, 60), ("paint.patch", json!({"offset": [-150, -40], "contentAware": true, "color": 3}))])?;+ step(&mut s, "patch-ca-s1", &[ellipse(200, 150, 50, 50), ("paint.patch", json!({"offset": [100, 90], "contentAware": true, "structure": 1}))])?;+ step(&mut s, "move", &[ellipse(420, 380, 80, 60), ("paint.contentAwareMove", json!({"offset": [-120, 80]}))])?;+ step(&mut s, "move-color", &[ellipse(600, 200, 60, 60), ("paint.contentAwareMove", json!({"offset": [90, 110], "color": 5, "structure": 2}))])?;+ step(+ &mut s,+ "extend",+ &[ellipse(150, 450, 70, 50), ("paint.contentAwareMove", json!({"offset": [80, -60], "mode": "extend", "color": 10, "structure": 7}))],+ )?;+ // A feathered selection (partial coverage) and the fill onto a duplicate.+ step(&mut s, "caf-feather", &[ellipse(640, 330, 70, 50), ("select.modify.feather", json!({"radius": 6})), ("edit.contentAwareFill", json!({"seed": 4}))])?;+ step(&mut s, "caf-duplicate", &[ellipse(260, 380, 50, 40), ("edit.contentAwareFill", json!({"output": "duplicate"}))])?;+ // Last: the fill lands on a new layer, which becomes the active one.+ step(&mut s, "caf-margin-new", &[ellipse(500, 200, 70, 40), ("edit.contentAwareFill", json!({"sampling": "rectangular", "margin": 60, "output": "new"}))])?;+ Ok(())+}++/// Smooth gradient, stripes and deterministic noise, `ch` channels.+fn synth(w: usize, h: usize, ch: usize, seed: u64) -> Vec<f32> {+ let mut rng = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;+ (0..w * h)+ .flat_map(|i| {+ let (x, y) = ((i % w) as f32, (i / w) as f32);+ rng ^= rng << 13;+ rng ^= rng >> 7;+ rng ^= rng << 17;+ let n = (rng % 1000) as f32 / 1000.0 * 0.06 - 0.03;+ let stripe = if (i % w / 5).is_multiple_of(2) { 0.15 } else { 0.0 };+ (0..ch).map(move |c| (0.2 + 0.003 * x * (c as f32 + 1.0) / ch as f32 + 0.002 * y + stripe * (c % 2) as f32 + n).clamp(0.0, 1.0))+ })+ .collect()+}++fn algo_cases(out: &mut Vec<(String, String)>) {+ let disc = |w: usize, h: usize, cx: f32, cy: f32, rx: f32, ry: f32| -> Vec<bool> {+ (0..w * h).map(|i| (((i % w) as f32 - cx) / rx).hypot(((i / w) as f32 - cy) / ry) < 1.0).collect()+ };+ for &(w, h, ch) in &[(96usize, 80usize, 1usize), (160, 140, 3), (300, 260, 4), (520, 400, 3)] {+ let img = synth(w, h, ch, (w * h) as u64);+ let hole = disc(w, h, w as f32 * 0.45, h as f32 * 0.55, w as f32 * 0.12, h as f32 * 0.1);+ for (name, adapt) in [("none", Adapt::NONE), ("default", content_aware::color_level("default")), ("veryHigh", content_aware::color_level("veryHigh"))] {+ let p = CompleteParams { adapt, seed: 5, ..Default::default() };+ let r = inpaint::complete(w, h, ch, &img, &hole, &p);+ out.push((format!("complete/{w}x{h}x{ch}/{name}"), r.map_or("none".into(), |v| hash_f32(&v))));+ }+ let src: Vec<bool> = (0..w * h).map(|i| (i % w) < w * 3 / 4).collect();+ let opts = FillOptions { rotations: content_aware::rotation_level("medium"), mirror: true, scale: ch == 3, seed: 2, ..Default::default() };+ out.push((format!("fill/{w}x{h}x{ch}/variants"), hash_f32(&content_aware::fill(w, h, ch, &img, &hole, &src, &opts))));+ let auto = content_aware::auto_sampling(w, h, ch, &img, &hole);+ out.push((format!("auto/{w}x{h}x{ch}"), hash_f32(&auto.iter().map(|b| f32::from(u8::from(*b))).collect::<Vec<_>>())));+ out.push((format!("offset/{w}x{h}x{ch}"), format!("{:?}", inpaint::best_offset(w, h, ch, &img, &hole, 4, (w / 3) as i32))));+ out.push((format!("synth/{w}x{h}x{ch}"), hash_f32(&inpaint::synthesize(w, h, ch, &img, &hole, 12, 0x5eed))));+ }+ // A hole wider than `refine_extent` (refine-only levels) and a long thin one.+ let (w, h, ch) = (900usize, 640usize, 3usize);+ let img = synth(w, h, ch, 77);+ let big = disc(w, h, 450.0, 320.0, 160.0, 120.0);+ let p = CompleteParams { adapt: content_aware::color_level("default"), ..Default::default() };+ out.push(("complete/big/default".into(), inpaint::complete(w, h, ch, &img, &big, &p).map_or("none".into(), |v| hash_f32(&v))));+ let thin: Vec<bool> = (0..w * h).map(|i| (100..800).contains(&(i % w)) && (300..312).contains(&(i / w))).collect();+ out.push(("complete/thin/none".into(), inpaint::complete(w, h, ch, &img, &thin, &CompleteParams::default()).map_or("none".into(), |v| hash_f32(&v))));+ // Roles: a void gap and a known-but-not-source area.+ let (w, h, ch) = (200usize, 160usize, 3usize);+ let img = synth(w, h, ch, 3);+ let px: Vec<inpaint::Px> = (0..w * h)+ .map(|i| {+ let (x, y) = (i % w, i / w);+ if (80..120).contains(&x) && (60..100).contains(&y) {+ inpaint::Px::Hole+ } else if x < 12 || y > 150 {+ inpaint::Px::Void+ } else if x > 170 {+ inpaint::Px::Known+ } else {+ inpaint::Px::Source+ }+ })+ .collect();+ let p = CompleteParams { adapt: content_aware::color_level("high"), seed: 11, ..Default::default() };+ let r = inpaint::complete_masked(w, h, ch, &img, &px, &p, &photocraft_raster::Interrupt::NONE);+ out.push((+ "masked/roles/high".into(),+ match r {+ Ok(Some(v)) => hash_f32(&v),+ Ok(None) => "none".into(),+ Err(_) => "cancelled".into(),+ },+ ));+}++fn main() -> Res<()> {+ let args: Vec<String> = std::env::args().skip(1).collect();+ match args.first().map(String::as_str) {+ Some("bench") => {+ let which = args.get(1).map_or("caf", String::as_str);+ let reps = args.get(2).and_then(|v| v.parse().ok()).unwrap_or(8);+ bench(which, reps)+ }+ // The benchmarks' own documents (10 and 24 MP): the fills P21, P22 and P49 time.+ Some("hash-big") => {+ let (w, h) = (3872u32, 2592u32);+ let mut s = open_photo(w, h)?;+ for i in 1..=2u32 {+ exec(&mut s, "select.rect", json!({"x": w / 3 + i * 40, "y": h / 3, "width": 200, "height": 200, "ellipse": true}))?;+ exec(&mut s, "edit.contentAwareFill", json!({"seed": i}))?;+ println!("P21/{i} {}", layer_hash(&s)?);+ exec(&mut s, "select.deselect", json!({}))?;+ let (x, y) = (w / 4 + i * 60, h / 4);+ let pts: Vec<Value> = (0..10).map(|k| json!([x + k * 12, y + k * 4])).collect();+ exec(&mut s, "paint.spotHealing", json!({"points": pts, "size": 60}))?;+ println!("P22/{i} {}", layer_hash(&s)?);+ }+ let (w, h) = (6000u32, 4000u32);+ let mut s = open_photo(w, h)?;+ exec(&mut s, "select.rect", json!({"x": w / 3, "y": h / 3, "width": w / 5, "height": h / 4}))?;+ exec(&mut s, "edit.contentAwareFill", json!({}))?;+ println!("P49 {}", layer_hash(&s)?);+ Ok(())+ }+ Some("hash") => {+ let mut out = Vec::new();+ algo_cases(&mut out);+ for depth in [8, 16, 32] {+ doc_cases(depth, &mut out)?;+ }+ for mode in ["grayscale", "cmyk", "lab"] {+ mode_cases(mode, &mut out)?;+ }+ for (k, v) in out {+ println!("{k} {v}");+ }+ Ok(())+ }+ _ => Err("usage: content_aware_bench bench caf|heal|spot|cancel|cancelscan|full24 [reps] | hash | hash-big".into()),+ }+}diff --git a/crates/engine/src/edit_menu_cmds.rs b/crates/engine/src/edit_menu_cmds.rsindex e289e43d6..103a5edc6 100644--- a/crates/engine/src/edit_menu_cmds.rs+++ b/crates/engine/src/edit_menu_cmds.rs@@ -347,7 +347,7 @@ fn delete_and_fill(s: &mut Session, _: &Value) -> Result<Value> {}fn content_aware_fill_as(s: &mut Session, p: &Value, cmd: &'static str, label: &'static str) -> Result<Value> {- use photocraft_algo::content_aware::{FillOptions, auto_sampling, color_level, fill_with, rotation_level};+ use photocraft_algo::content_aware::{FillOptions, auto_sampling_with, color_level, fill_owned, rotation_level};let id = pixel_layer(s).map_err(EngineError::Other)?;let st = s.active().ok_or(EngineError::NoDocument)?;let doc = st.doc.clone();@@ -401,61 +401,90 @@ fn content_aware_fill_as(s: &mut Session, p: &Value, cmd: &'static str, label: &label,true,move |ctx| {+ use rayon::prelude::*;++ use crate::fill_cmds::{read_window, read_window_cover, read_window_mask};ctx.progress(0.0, label);+ let cancel = || ctx.cancelled();let surf = doc.layer(id).and_then(|l| l.surface()).ok_or(EngineError::NoLayer(id))?;- let img = surf.read_region(window);- let mut cover = vec![0.0f32; w * h];- let mut hole = vec![false; w * h];- let mut source = vec![true; w * h];- for y in 0..h {- if y % 64 == 0 {- ctx.check()?;- }- for x in 0..w {- let (dx, dy) = (window.x0 + x as i32, window.y0 + y as i32);- let i = y * w + x;- cover[i] = sel.sample_channel(dx, dy, 0);- hole[i] = cover[i] > 0.0;- if sampling == "custom" {- source[i] = match (custom_rect, custom_mask.as_ref()) {- (Some(r), _) => r.contains(dx, dy),- (None, Some(m)) => m.sample_channel(dx, dy, 0) > 0.5,- _ => true,- };- }- }- }+ let img = read_window(surf, window, &cancel).ok_or(EngineError::Cancelled)?;+ let hole = read_window_cover(&sel, window, &cancel).ok_or(EngineError::Cancelled)?;+ let mut source = match (sampling.as_str(), custom_rect, custom_mask.as_ref()) {+ ("custom", Some(r), _) => (0..w * h).into_par_iter().map(|i| r.contains(window.x0 + (i % w) as i32, window.y0 + (i / w) as i32)).collect(),+ ("custom", None, Some(m)) => read_window_mask(m, window, &cancel).ok_or(EngineError::Cancelled)?.par_iter().map(|v| *v > 0.5).collect(),+ _ => vec![true; w * h],+ };ctx.check()?;// Auto: only what looks like the selection's surroundings.if sampling == "auto" {- source = auto_sampling(w, h, n, &img, &hole);+ source = auto_sampling_with(w, h, n, &img, &hole, &photocraft_raster::Interrupt::cancel_only(&cancel)).map_err(|_| EngineError::Cancelled)?;}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))+ // The fill changes only the selected pixels: keep the original and the coverage over+ // their bounds for the apply step, and fill the window's pixels themselves.+ let (bx0, by0, bx1, by1) = mask_bounds(w, h, &hole);+ let original: Vec<f32> = (by0..by1).flat_map(|y| img[(y * w + bx0) * n..(y * w + bx1) * n].iter().copied()).collect();+ let at = |x: usize, y: usize| (window.x0 + x as i32, window.y0 + y as i32);+ let ((x0, y0), (x1, y1)) = (at(bx0, by0), at(bx1, by1));+ let cover = read_window_mask(&sel, Rect::new(x0, y0, x1, y1), &cancel).ok_or(EngineError::Cancelled)?;+ let n_hole = cover.iter().filter(|c| **c > 0.0).count();+ let filled = ctx.stage(0.05, 1.0, label, |ctl| fill_owned(w, h, n, img, &hole, &source, &opts, ctl)).map_err(|_| EngineError::Cancelled)?;+ Ok(FilledWindow { filled, bounds: (bx0, by0, bx1, by1), original, cover, n_hole })},- move |s, (img, cover, hole, filled)| apply_content_aware_fill(s, label, id, &output, fmt, window, &img, &cover, &hole, &filled),+ move |s, done| apply_content_aware_fill(s, label, id, &output, fmt, window, done),)}+/// A Content-Aware Fill's result for its apply step: the filled window (the same as the+/// original outside the selected pixels) and, over the bounds of the selected pixels (in window+/// coordinates), the original pixels and the selection's coverage.+struct FilledWindow {+ filled: Vec<f32>,+ bounds: (usize, usize, usize, usize),+ original: Vec<f32>,+ cover: Vec<f32>,+ n_hole: usize,+}++/// `f(window index, index over the bounds, coverage)` for each selected pixel of a+/// [`FilledWindow`] (`w` wide).+fn each_selected(w: usize, (bx0, by0, bx1, by1): (usize, usize, usize, usize), cover: &[f32], mut f: impl FnMut(usize, usize, f32)) {+ let bw = bx1.saturating_sub(bx0);+ for y in by0..by1 {+ for x in bx0..bx1 {+ let k = (y - by0) * bw + (x - bx0);+ if let Some(&c) = cover.get(k)+ && c > 0.0+ {+ f(y * w + x, k, c);+ }+ }+ }+}++/// Bounds `(x0, y0, x1, y1)` of the set cells of a `w × h` mask (all zero when there are none).+fn mask_bounds(w: usize, h: usize, m: &[bool]) -> (usize, usize, usize, usize) {+ use rayon::prelude::*;+ if w == 0 {+ return (0, 0, 0, 0);+ }+ let rows: Vec<Option<(usize, usize)>> =+ m.par_chunks(w).take(h).map(|row| Some((row.iter().position(|v| *v)?, row.iter().rposition(|v| *v)? + 1))).collect();+ let mut b: Option<(usize, usize, usize, usize)> = None;+ for (y, span) in rows.into_iter().enumerate() {+ if let Some((x0, x1)) = span {+ b = Some(b.map_or((x0, y, x1, y + 1), |(bx0, by0, bx1, _)| (bx0.min(x0), by0, bx1.max(x1), y + 1)));+ }+ }+ b.unwrap_or((0, 0, 0, 0))+}+/// Write a Content-Aware Fill result (the job's apply step): into the layer, a new layer or a/// duplicate, as one undo step.-#[allow(clippy::too_many_arguments)]-fn apply_content_aware_fill(- s: &mut Session,- label: &str,- id: LayerId,- output: &str,- fmt: PixelFormat,- window: Rect,- img: &[f32],- cover: &[f32],- hole: &[bool],- filled: &[f32],-) -> Result<Value> {+fn apply_content_aware_fill(s: &mut Session, label: &str, id: LayerId, output: &str, fmt: PixelFormat, window: Rect, done: FilledWindow) -> Result<Value> {let n = fmt.channels();let (w, h) = (window.width() as usize, window.height() as usize);- let n_hole = hole.iter().filter(|h| **h).count();+ let FilledWindow { mut filled, bounds, original, cover, n_hole } = done;let layer = s.edit(label, |doc, active| {let target = match output {"new" => {@@ -464,14 +493,12 @@ fn apply_content_aware_fill(let lf = l.surface().map(|s| s.format()).unwrap_or(fmt);let ln = lf.channels();px.resize(w * h * ln, 0.0);- for i in 0..w * h {- if hole[i] {- let rgba = to_rgba(&fmt, &filled[i * n..(i + 1) * n]);- let mut enc = [0.0f32; 8];- from_rgba_into(&lf, [rgba[0], rgba[1], rgba[2], rgba[3] * cover[i]], &mut enc);- px[i * ln..(i + 1) * ln].copy_from_slice(&enc[..ln]);- }- }+ each_selected(w, bounds, &cover, |i, _, c| {+ let rgba = to_rgba(&fmt, &filled[i * n..(i + 1) * n]);+ let mut enc = [0.0f32; 8];+ from_rgba_into(&lf, [rgba[0], rgba[1], rgba[2], rgba[3] * c], &mut enc);+ px[i * ln..(i + 1) * ln].copy_from_slice(&enc[..ln]);+ });if let Some(s) = l.surface_mut() {s.write_region(window, &px);s.prune();@@ -490,16 +517,14 @@ fn apply_content_aware_fill(_ => id,};let surf = writable_surface(doc, target)?;- let mut out = img.to_vec();- for (i, &k) in cover.iter().enumerate() {- if k > 0.0 {- for c in 0..n {- let j = i * n + c;- out[j] = img[j] + (filled[j] - img[j]) * k;- }+ // The fill blended in by the coverage (elsewhere it is the original).+ each_selected(w, bounds, &cover, |i, k, c| {+ for ch in 0..n {+ let (j, o) = (i * n + ch, k * n + ch);+ filled[j] = original[o] + (filled[j] - original[o]) * c;}- }- surf.write_region(window, &out);+ });+ surf.write_region(window, &filled);Ok(target)})?;Ok(json!({"layer": layer.0, "filled": n_hole, "window": [window.x0, window.y0, window.width(), window.height()]}))diff --git a/crates/engine/src/fill_cmds.rs b/crates/engine/src/fill_cmds.rsindex eab1fb165..193a1aea8 100644--- a/crates/engine/src/fill_cmds.rs+++ b/crates/engine/src/fill_cmds.rs@@ -246,6 +246,67 @@ pub(crate) fn window_size(window: Rect) -> Result<(usize, usize)> {Ok((w as usize, h as usize))}+/// [`Surface::read_region`] of `r`, read in parallel bands and asking `cancelled` before each+/// (`None` once it says so): a Content-Aware window can be tens of megapixels.+pub(crate) fn read_window(surf: &Surface, r: Rect, cancelled: &(dyn Fn() -> bool + Sync)) -> Option<Vec<f32>> {+ use rayon::prelude::*;+ const BAND: usize = 64;+ let n = surf.channels();+ let (w, h) = (r.width() as usize, r.height() as usize);+ let mut out = vec![0.0f32; w * h * n];+ if out.is_empty() {+ return Some(out);+ }+ // Each worker reads its bands through one buffer of its own.+ out.par_chunks_mut(BAND * w * n).enumerate().for_each_init(Vec::new, |buf, (i, chunk)| {+ if cancelled() {+ return;+ }+ let y0 = r.y0 + (i * BAND) as i32;+ let band = Rect::new(r.x0, y0, r.x1, y0 + (chunk.len() / (w * n)) as i32);+ surf.read_region_into(band, buf);+ if buf.len() == chunk.len() {+ chunk.copy_from_slice(buf);+ }+ });+ if cancelled() { None } else { Some(out) }+}++/// Which pixels of `r` a selection (or mask) covers at all: channel 0 above zero, read in+/// parallel bands as [`read_window`] does, without holding the coverage itself.+pub(crate) fn read_window_cover(surf: &Surface, r: Rect, cancelled: &(dyn Fn() -> bool + Sync)) -> Option<Vec<bool>> {+ use rayon::prelude::*;+ const BAND: usize = 64;+ let n = surf.channels().max(1);+ let (w, h) = (r.width() as usize, r.height() as usize);+ let mut out = vec![false; w * h];+ if out.is_empty() {+ return Some(out);+ }+ out.par_chunks_mut(BAND * w).enumerate().for_each_init(Vec::new, |buf, (i, chunk)| {+ if cancelled() {+ return;+ }+ let y0 = r.y0 + (i * BAND) as i32;+ surf.read_region_into(Rect::new(r.x0, y0, r.x1, y0 + (chunk.len() / w) as i32), buf);+ for (o, px) in chunk.iter_mut().zip(buf.chunks_exact(n)) {+ *o = px[0] > 0.0;+ }+ });+ if cancelled() { None } else { Some(out) }+}++/// Channel 0 of [`read_window`] (a selection's or an alpha channel's coverage).+pub(crate) fn read_window_mask(surf: &Surface, r: Rect, cancelled: &(dyn Fn() -> bool + Sync)) -> Option<Vec<f32>> {+ use rayon::prelude::*;+ let n = surf.channels().max(1);+ let all = read_window(surf, r, cancelled)?;+ if n == 1 {+ return Some(all);+ }+ Some(all.par_chunks_exact(n).map(|px| px[0]).collect())+}+/// How the source goes onto the target.#[derive(Clone, Copy)]struct Blend {diff --git a/docs/development.md b/docs/development.mdindex 5baf62bc1..1236dd65c 100644--- a/docs/development.md+++ b/docs/development.md@@ -283,6 +283,7 @@ translations do not affect the denominator. Unregistered locale TSV files are ig- **Numbers** (7360 × 4912, 8 text layers + one painted layer with drop shadow + stroke + bevel, Hue/Saturation on top; M4 Pro; `cargo run --release -p photocraft-ui-egui --example fx_bench`), CPU fallback → GPU: full refresh with warm effect maps 5.7 s → 47 ms; Hue/Saturation tweak above the effects 4.7 s → 31 ms; brush dab on a plain layer 32 → 1.7 ms; brush dab on the effect layer (its maps rebuilt around the dab) 659 → 3.7 ms; first refresh (all maps built) 6.4 s → 0.39 s. With the CPU ~14× oversubscribed by parallel builds (min of 7 runs): 8.1 s → 0.33 s, 9.9 s → 0.28 s, 28 → 2.2 ms, 1.7 s → 89 ms; moving a text layer 7 px 336 → 13 ms. `fx_bench --compare corpus/psd/…/*.psd` reports the GPU vs CPU difference on real files (30 of the 31 corpus files with effects render on the GPU, worst 0.12/255).- On the CPU path `compose::effect_maps` caches shadow, glow, bevel and satin maps per layer state (LRU, 768 MB budget).- Live adjustment previews on large documents use a downsampled proxy (`ui-egui/src/proxy.rs`).+- **Content-Aware tools** (`algo::inpaint`, `algo::content_aware`: Fill, Spot Healing, Patch, Content-Aware Move). `cargo run --release -p photocraft-engine --example content_aware_bench -- bench caf|heal|cancel` times the P21, P22 and P49 rows without the UI, one sample per line, so two builds can be run in turn and pooled. `-- hash` prints a hash of every tool's output at 8, 16 and 32 bits and in Gray, CMYK and Lab: the fill is fitted to Photoshop, so a speed-up must leave both builds' lists equal. The solver works only over the hole's bounds grown by a patch radius (nothing else changes or is matched). PatchMatch sweeps its bands in wavefronts when there are fewer bands than threads; each cell sees the same neighbours and random numbers as in raster order, so the result does not depend on the thread count. Cancellation is checked per row: a 24 MP fill stops within tens of milliseconds, most of it spent freeing its buffers.- `ui.inspect` returns `perf` timings (UI ms per frame, composite ms, upload ms).- Never scan full surfaces per frame. Cache per document revision (`PhotocraftApp::cached_bounds`). An uncached `content_bounds()` on a 36 MP layer once cost 77 ms per frame.