From 4244ec2b9ee743378db63a5b2688e2b57acaf4ff Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Mon, 26 Oct 2026 18:33:35 +0530 Subject: [PATCH] perf: crop selection morphology and bound small-radius distances --- .github/workflows/ci.yml | 30 +++ .../examples/bench_selection_morphology.rs | 64 +++++++ crates/algo/src/selection.rs | 21 +-- crates/algo/src/selection/distance.rs | 58 +++++- crates/algo/src/selection/morphology.rs | 98 ++++++++++ crates/algo/src/selection/morphology/tests.rs | 177 ++++++++++++++++++ docs/gaps.md | 9 +- docs/selection-distance-performance.md | 60 ++++++ docs/target-app-parity.md | 9 +- 9 files changed, 509 insertions(+), 17 deletions(-) create mode 100644 crates/algo/examples/bench_selection_morphology.rs create mode 100644 crates/algo/src/selection/morphology.rs create mode 100644 crates/algo/src/selection/morphology/tests.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cea1326c0c3..0ff80a8468a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,6 +11,10 @@ on: types: [opened, synchronize, reopened, labeled] workflow_dispatch: inputs: + selection_morphology: + description: "Compare selection morphology on 36 MP (Linux, exact outputs)" + type: boolean + default: false fuzz: description: "Run the fuzz job" type: boolean @@ -415,3 +419,29 @@ jobs: with: name: fuzz-${{ matrix.target.crate }}-${{ matrix.target.name }} path: crates/${{ matrix.target.crate }}/fuzz/artifacts + + selection-morphology: + if: inputs.selection_morphology == true + runs-on: ubuntu-latest + timeout-minutes: 45 + env: + RAYON_NUM_THREADS: "4" + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + key: selection-morphology-perf + - name: Compare exact outputs and release timings on 36 MP + run: | + set -o pipefail + cargo run --release -p photocraft-algo --example bench_selection_morphology | tee selection-morphology-perf.txt + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: always() + with: + name: selection-morphology-performance + path: selection-morphology-perf.txt + - name: Quick performance suite + run: cargo xtask perf --quick diff --git a/crates/algo/examples/bench_selection_morphology.rs b/crates/algo/examples/bench_selection_morphology.rs new file mode 100644 index 00000000000..076f3ef544e --- /dev/null +++ b/crates/algo/examples/bench_selection_morphology.rs @@ -0,0 +1,64 @@ +//! Compare the former full-canvas formulas with cropped morphology on 36 MP. +//! Run in release on CI; includes output allocation and checks exact equality. +use photocraft_algo::selection::{border, contract, edt, expand}; +use std::{hint::black_box, time::Instant}; + +type Op = fn(&[f32], usize, usize, f32) -> Vec; + +fn old_expand(m: &[f32], w: usize, h: usize, r: f32) -> Vec { + let seeds: Vec = m.iter().map(|v| *v >= 0.5).collect(); + m.iter().zip(edt(&seeds, w, h)).map(|(v, d)| v.max((r + 1.0 - d).clamp(0.0, 1.0))).collect() +} +fn old_contract(m: &[f32], w: usize, h: usize, r: f32) -> Vec { + let inv: Vec = m.iter().map(|v| 1.0 - v).collect(); + old_expand(&inv, w, h, r).iter().map(|v| 1.0 - v).collect() +} +fn old_border(m: &[f32], w: usize, h: usize, r: f32) -> Vec { + let inside: Vec = m.iter().map(|v| *v >= 0.5).collect(); + let outside: Vec = inside.iter().map(|v| !v).collect(); + let (di, dout) = (edt(&inside, w, h), edt(&outside, w, h)); + inside.iter().zip(di.iter().zip(&dout)).map(|(s, (a, b))| (1.0 - ((if *s { b } else { a }) - 1.0) / r).clamp(0.0, 1.0)).collect() +} +fn main() -> Result<(), Box> { + let (w, h) = (6000, 6000); + println!("36 MP; median of three runs including allocation; RAYON_NUM_THREADS={}", std::env::var("RAYON_NUM_THREADS").unwrap_or_default()); + for (case, size) in [("sparse", 50), ("dense", 4000)] { + let mut m = vec![0.0; w * h]; + let start = (w - size) / 2; + for row in m.chunks_exact_mut(w).skip(start).take(size) { + if let Some(span) = row.get_mut(start..start + size) { + span.fill(1.0) + } + } + for r in [3.0, 50.0] { + for (name, old, new) in + [("expand", old_expand as Op, expand as Op), ("contract", old_contract as Op, contract as Op), ("border", old_border as Op, border as Op)] + { + let mut timings = [0.0; 2]; + let expected = old(&m, w, h, r); + if new(&m, w, h, r) != expected { + return Err(format!("output mismatch: {case} {name} {r}").into()); + } + drop(expected); + for (slot, op) in timings.iter_mut().zip([old, new]) { + let mut runs = [0.0; 3]; + for time in &mut runs { + let now = Instant::now(); + let result = black_box(op(black_box(&m), w, h, r)); + *time = now.elapsed().as_secs_f64() * 1000.0; + drop(result); + } + runs.sort_by(f64::total_cmp); + *slot = runs.get(1).copied().unwrap_or_default(); + } + println!( + "{case} {name} r={r}: old={:.2}ms new={:.2}ms speedup={:.2}x exact=true", + timings.first().copied().unwrap_or_default(), + timings.get(1).copied().unwrap_or_default(), + timings.first().copied().unwrap_or_default() / timings.get(1).copied().unwrap_or(1.0) + ); + } + } + } + Ok(()) +} diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index 1e71a502c79..e714d2196a5 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -763,6 +763,7 @@ pub fn tone_range(px: &[[f32; 4]], lo: f32, hi: f32, falloff: f32) -> Vec { mod distance; mod lasso; mod marquee; +mod morphology; pub use distance::edt; pub(crate) use lasso::clip_segment; @@ -770,18 +771,15 @@ pub use lasso::{MAX_PAINTED_TILES, polygon_edge_tiles, polygon_surface}; pub use marquee::{combine_sparse, combine_surfaces, ellipse_surface}; /// Grows the selection by `r` pixels. +/// Invalid dimensions or nonfinite/negative radii return an empty buffer. pub fn expand(m: &[f32], w: usize, h: usize, r: f32) -> Vec { - let inside: Vec = m.iter().map(|v| *v >= 0.5).collect(); - let d = edt(&inside, w, h); - // A pixel whose centre is `d` away from the nearest selected centre is - // covered when d ≤ r (fractional radii give partial coverage). - m.iter().zip(d).map(|(v, d)| v.max((r + 1.0 - d).clamp(0.0, 1.0))).collect() + morphology::modify(m, w, h, r, morphology::Kind::Expand) } /// Shrinks the selection by `r` pixels. +/// Invalid dimensions or nonfinite/negative radii return an empty buffer. pub fn contract(m: &[f32], w: usize, h: usize, r: f32) -> Vec { - let inv: Vec = m.iter().map(|v| 1.0 - v).collect(); - expand(&inv, w, h, r).into_iter().map(|v| 1.0 - v).collect() + morphology::modify(m, w, h, r, morphology::Kind::Contract) } /// Select › Modify › Border: a soft band `2r` wide centred on the selection edge, as in @@ -790,14 +788,9 @@ pub fn contract(m: &[f32], w: usize, h: usize, r: f32) -> Vec { /// either side (measured on Photoshop 27.11, Border 4: 63, 127, 191, 255 | 255, 191, 127, 63 /// across a straight edge, the same along the inside of a corner). It used to be a hard band /// `r` wide. +/// Invalid dimensions or nonfinite/negative radii return an empty buffer. pub fn border(m: &[f32], w: usize, h: usize, r: f32) -> Vec { - let inside: Vec = m.iter().map(|v| *v >= 0.5).collect(); - let outside: Vec = inside.iter().map(|v| !v).collect(); - let (to_inside, to_outside) = (edt(&inside, w, h), edt(&outside, w, h)); - if r <= 0.0 || to_inside.len() != m.len() || to_outside.len() != m.len() { - return vec![0.0; m.len()]; - } - inside.iter().zip(to_inside.iter().zip(&to_outside)).map(|(&sel, (&di, &dout))| (1.0 - ((if sel { dout } else { di }) - 1.0) / r).clamp(0.0, 1.0)).collect() + morphology::modify(m, w, h, r, morphology::Kind::Border) } /// Smooth: removes specks and rounds corners (box average of radius `round(r)`, edges diff --git a/crates/algo/src/selection/distance.rs b/crates/algo/src/selection/distance.rs index 2dad2d2cbb0..53588904f00 100644 --- a/crates/algo/src/selection/distance.rs +++ b/crates/algo/src/selection/distance.rs @@ -3,9 +3,65 @@ const NO_SEED: u32 = u32::MAX; // Keep the public API's finite result for a mask with no selected pixel. -const EMPTY_DISTANCE: f32 = 1e10; +pub(super) const EMPTY_DISTANCE: f32 = 1e10; const BAND_ROWS: usize = 32; +/// Exact distances within `reach` (at most six pixels), EMPTY_DISTANCE beyond it. +/// Two contiguous vertical sweeps and a short horizontal stencil avoid envelopes, +/// transposes and task-local buffers. One byte per pixel stores capped vertical distances. +pub(super) fn edt_bounded(seeds: &[bool], w: usize, h: usize, reach: f32) -> Vec { + if w == 0 || h == 0 || w.checked_mul(h) != Some(seeds.len()) || !(0.0..=6.0).contains(&reach) { + return Vec::new(); + } + let radius = reach.ceil() as usize; + let cap = radius as u8 + 1; + let mut vertical: Vec = seeds.iter().map(|s| if *s { 0 } else { cap }).collect(); + for y in 1..h { + let (before, after) = vertical.split_at_mut(y * w); + if let (Some(prev), Some(row)) = (before.get((y - 1) * w..), after.get_mut(..w)) { + for (d, p) in row.iter_mut().zip(prev) { + *d = (*d).min(p.saturating_add(1)); + } + } + } + for y in (1..h).rev() { + let (before, after) = vertical.split_at_mut(y * w); + if let (Some(row), Some(next)) = (before.get_mut((y - 1) * w..), after.get(..w)) { + for (d, n) in row.iter_mut().zip(next) { + *d = (*d).min(n.saturating_add(1)); + } + } + } + let mut out = vec![EMPTY_DISTANCE; seeds.len()]; + for_chunks(&mut out, w, |y, dst| { + let Some(row) = vertical.get(y * w..(y + 1) * w) else { return }; + if row.iter().all(|d| *d == cap) { + return; + } + for (x, d) in dst.iter_mut().enumerate() { + if row.get(x) == Some(&0) { + *d = 0.0; + continue; + } + let left = x.saturating_sub(radius); + let right = x.saturating_add(radius).saturating_add(1).min(w); + let Some(span) = row.get(left..right) else { continue }; + let mut best = (radius + 1).pow(2); + for (i, &dy) in span.iter().enumerate() { + best = best.min((left + i).abs_diff(x).pow(2) + usize::from(dy).pow(2)); + if best == 1 { + break; + } + } + let distance = (best as f64).sqrt() as f32; + if distance <= reach { + *d = distance; + } + } + }); + out +} + /// Euclidean distance to the nearest `true` pixel, in row-major order. /// /// Empty or inconsistent dimensions return an empty buffer. A mask with no seeds returns diff --git a/crates/algo/src/selection/morphology.rs b/crates/algo/src/selection/morphology.rs new file mode 100644 index 00000000000..ac159c9e3c7 --- /dev/null +++ b/crates/algo/src/selection/morphology.rs @@ -0,0 +1,98 @@ +//! Radius-limited selection morphology. Only the nonzero bounds plus a halo need distances; +//! the flat public API still requires a canvas-sized output. Canvas edges are not implicit +//! seeds: the engine supplies padding when Apply effect at canvas bounds is requested. + +use super::distance::{EMPTY_DISTANCE, edt, edt_bounded}; + +#[derive(Clone, Copy)] +pub(super) enum Kind { + Expand, + Contract, + Border, +} + +#[derive(Debug, PartialEq)] +struct Window { + x0: usize, + x1: usize, + y0: usize, + y1: usize, +} + +fn window(m: &[f32], w: usize, h: usize, r: f32) -> Option { + let mut b = Window { x0: w, x1: 0, y0: h, y1: 0 }; + for (y, row) in m.chunks_exact(w).enumerate() { + if let Some(x) = row.iter().position(|v| *v != 0.0) { + b.x0 = b.x0.min(x); + b.y0 = b.y0.min(y); + b.y1 = y + 1; + b.x1 = b.x1.max(row.iter().rposition(|v| *v != 0.0).unwrap_or(x) + 1); + } + } + if b.x1 == 0 { + // Preserve the general EDT's finite no-seed sentinel even for library callers + // passing radii far beyond the command's 500 px limit. + return (r >= EMPTY_DISTANCE).then_some(Window { x0: 0, x1: w, y0: 0, y1: h }); + } + // Coverage reaches r + 1 centres; the extra pixel also supplies real outside seeds + // for erosion. Saturating arithmetic handles radii larger than the canvas. + let halo = (r.ceil() as usize).saturating_add(1); + Some(Window { x0: b.x0.saturating_sub(halo), x1: b.x1.saturating_add(halo).min(w), y0: b.y0.saturating_sub(halo), y1: b.y1.saturating_add(halo).min(h) }) +} + +pub(super) fn modify(m: &[f32], w: usize, h: usize, r: f32, kind: Kind) -> Vec { + if w == 0 || h == 0 || w.checked_mul(h) != Some(m.len()) || m.len() > isize::MAX as usize / 4 || !r.is_finite() || r < 0.0 { + return Vec::new(); + } + let mut out = match kind { + Kind::Expand => m.to_vec(), + // Retain the old complement's rounding for fractional input coverage. + Kind::Contract => m.iter().map(|v| 1.0 - (1.0 - v)).collect(), + Kind::Border => vec![0.0; m.len()], + }; + if matches!(kind, Kind::Border) && r == 0.0 { + return out; + } + let Some(b) = window(m, w, h, r) else { return out }; + let (cw, ch) = (b.x1 - b.x0, b.y1 - b.y0); + let mut seeds = Vec::with_capacity(cw * ch); + for row in m.chunks_exact(w).skip(b.y0).take(ch) { + if let Some(span) = row.get(b.x0..b.x1) { + seeds.extend(span.iter().map(|v| match kind { + // Do not replace this with v < 0.5: the old complement includes ties, + // including values that round to 0.5 after subtraction. + Kind::Contract => 1.0 - v >= 0.5, + _ => *v >= 0.5, + })); + } + } + let distance = |seeds: &[bool]| { + if r <= 5.0 { edt_bounded(seeds, cw, ch, r + 1.0) } else { edt(seeds, cw, ch) } + }; + let passes = if matches!(kind, Kind::Border) { 2 } else { 1 }; + for pass in 0..passes { + // Drop each distance plane before the next pass. Border never keeps two float + // distance planes or two seed masks alive together. + let d = distance(&seeds); + for (y, (src, dst)) in m.chunks_exact(w).zip(out.chunks_exact_mut(w)).skip(b.y0).take(ch).enumerate() { + let (Some(src), Some(dst), Some(dist)) = (src.get(b.x0..b.x1), dst.get_mut(b.x0..b.x1), d.get(y * cw..(y + 1) * cw)) else { continue }; + for ((v, out), d) in src.iter().zip(dst).zip(dist) { + *out = match kind { + Kind::Expand => v.max((r + 1.0 - d).clamp(0.0, 1.0)), + Kind::Contract => 1.0 - (1.0 - v).max((r + 1.0 - d).clamp(0.0, 1.0)), + Kind::Border if (*v >= 0.5) == (pass == 1) => (1.0 - (d - 1.0) / r).clamp(0.0, 1.0), + Kind::Border => *out, + }; + } + } + if pass + 1 < passes { + for seed in &mut seeds { + *seed = !*seed; + } + } + } + out +} + +#[cfg(test)] +mod tests; diff --git a/crates/algo/src/selection/morphology/tests.rs b/crates/algo/src/selection/morphology/tests.rs new file mode 100644 index 00000000000..51db628476f --- /dev/null +++ b/crates/algo/src/selection/morphology/tests.rs @@ -0,0 +1,177 @@ +use super::*; +use crate::selection::{border, contract, expand}; + +fn oracle(m: &[f32], w: usize, h: usize, r: f32, kind: Kind) -> Vec { + let inside: Vec = m.iter().map(|v| *v >= 0.5).collect(); + match kind { + Kind::Expand => m.iter().zip(edt(&inside, w, h)).map(|(v, d)| v.max((r + 1.0 - d).clamp(0.0, 1.0))).collect(), + Kind::Contract => { + let inv: Vec = m.iter().map(|v| 1.0 - v).collect(); + oracle(&inv, w, h, r, Kind::Expand).iter().map(|v| 1.0 - v).collect() + } + Kind::Border => { + if r == 0.0 { + return vec![0.0; m.len()]; + } + let outside: Vec = inside.iter().map(|v| !v).collect(); + let di = edt(&inside, w, h); + let dout = edt(&outside, w, h); + inside.iter().zip(di.iter().zip(&dout)).map(|(sel, (di, dout))| (1.0 - ((if *sel { dout } else { di }) - 1.0) / r).clamp(0.0, 1.0)).collect() + } + } +} + +#[test] +fn matches_full_canvas_formulas() { + for (w, h) in [(1usize, 1usize), (1, 31), (37, 1), (39, 27)] { + for case in 0..9 { + let m: Vec = (0..w * h) + .map(|i| { + let (x, y) = (i % w, i / w); + match case { + 0 => 0.0, + 1 => 1.0, + 2 => { + if x == w / 2 && y == h / 2 { + 1.0 + } else { + 0.0 + } + } + 3 => { + if x < w / 2 && y < h / 2 { + 1.0 + } else { + 0.0 + } + } + 4 => { + if x.abs_diff(w / 2) < 3 && y.abs_diff(h / 2) < 3 { + 1.0 + } else { + 0.0 + } + } + 5 => { + if x.abs_diff(w / 2) < 5 && y.abs_diff(h / 2) < 5 && (x.abs_diff(w / 2) > 2 || y.abs_diff(h / 2) > 2) { + 1.0 + } else { + 0.0 + } + } + 6 => [0.0, 0.1, 0.499_999_97, 0.5, 0.6, 1.0][(i * 31 + i / 7) % 6], + 7 => 0.25, + _ => { + if x == 0 || x + 1 == w || y == 0 || y + 1 == h { + 1.0 + } else { + 0.0 + } + } + } + }) + .collect(); + for r in [0.0, 0.25, 1.0, 1.5, 2.0, 4.25, 5.0, 5.01, 12.0, 100.0] { + for kind in [Kind::Expand, Kind::Contract, Kind::Border] { + assert_eq!(modify(&m, w, h, r, kind), oracle(&m, w, h, r, kind), "{w}x{h} case {case} radius {r}"); + } + } + } + } +} + +#[test] +fn tiny_selection_uses_tiny_distance_window() { + let (w, h) = (1024, 768); + let mut m = vec![0.0; w * h]; + for y in 300..350 { + m[y * w + 400..y * w + 450].fill(1.0); + } + let b = window(&m, w, h, 5.0).unwrap(); + assert_eq!(b, Window { x0: 394, x1: 456, y0: 294, y1: 356 }); + assert_eq!((b.x1 - b.x0) * (b.y1 - b.y0), 62 * 62); +} + +#[test] +fn invalid_dimensions_and_radii_are_safe() { + for op in [expand, contract, border] { + for (w, h) in [(0, 1), (1, 0), (2, 2), (usize::MAX, 2)] { + assert!(op(&[1.0], w, h, 2.0).is_empty()); + } + for r in [f32::NAN, f32::INFINITY, -1.0] { + assert!(op(&[1.0], 1, 1, r).is_empty()); + } + } +} + +#[test] +fn bounded_distances_match_edt_within_reach() { + for (w, h) in [(1, 17), (23, 1), (31, 29)] { + for pattern in 0..4 { + let seeds: Vec = (0..w * h) + .map(|i| match pattern { + 0 => false, + 1 => true, + 2 => i == w * h / 2, + _ => (i * 73 + i / w * 11) % 19 == 0, + }) + .collect(); + let exact = edt(&seeds, w, h); + for reach in [1.0, 1.25, 2.0, 4.5, 6.0] { + let got = edt_bounded(&seeds, w, h, reach); + for (g, e) in got.iter().zip(&exact) { + if *e <= reach { assert_eq!(g, e) } else { assert!(*g > reach) } + } + } + } + } +} + +#[test] +fn every_three_by_three_mask_matches_with_a_cropped_halo() { + let (w, h) = (17, 19); + for bits in 0..512 { + let mut m = vec![0.0; w * h]; + for y in 0..3 { + for x in 0..3 { + if bits & (1 << (y * 3 + x)) != 0 { + m[(y + 7) * w + x + 6] = 1.0; + } + } + } + // Retain faint pixels beyond the binary selection's bounds too. + m[3 * w + 2] = 0.125; + for r in [0.0, 0.414_213_54, 0.414_213_66, 1.5, 3.0, 5.0, 5.5] { + for kind in [Kind::Expand, Kind::Contract, Kind::Border] { + assert_eq!(modify(&m, w, h, r, kind), oracle(&m, w, h, r, kind), "mask {bits} radius {r}"); + } + } + } +} + +#[test] +fn enormous_finite_radii_keep_the_no_seed_sentinel_behavior() { + for m in [vec![0.0; 9], vec![1.0; 9], vec![0.25; 9]] { + for r in [1e10, 2e10, f32::MAX] { + for kind in [Kind::Expand, Kind::Contract, Kind::Border] { + assert_eq!(modify(&m, 3, 3, r, kind), oracle(&m, 3, 3, r, kind)); + } + } + } +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn bounded_and_general_paths_are_worker_count_independent() { + let (w, h) = (400, 300); + let m: Vec = (0..w * h).map(|i| if (i * 73 + i / w * 11) % 19 == 0 { 1.0 } else { 0.0 }).collect(); + for r in [3.0, 9.0] { + for kind in [Kind::Expand, Kind::Contract, Kind::Border] { + let expected = oracle(&m, w, h, r, kind); + for workers in [1, 2, 4] { + let pool = rayon::ThreadPoolBuilder::new().num_threads(workers).build().unwrap(); + assert_eq!(pool.install(|| modify(&m, w, h, r, kind)), expected); + } + } + } +} diff --git a/docs/gaps.md b/docs/gaps.md index 9168b453ba1..43c245d9e7f 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where PhotoCraft falls short of Photoshop -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (G9: 12 of 178 preferences do nothing, as the scorecard prefs audit counts them; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed; G10: Amiga IFF write; G10: PSD spot channels in Photoshop's polarity, earlier PhotoCraft PSDs keep their ink, #7415 split; G10: TIFF alpha and spot channels written and read as extra samples, FILE-215-7 done, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-26 · **Change:** minor (cropped selection morphology performance evidence added; G9: 12 of 178 preferences do nothing, as the scorecard prefs audit counts them; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed; G10: Amiga IFF write; G10: PSD spot channels in Photoshop's polarity, earlier PhotoCraft PSDs keep their ink, #7415 split; G10: TIFF alpha and spot channels written and read as extra samples, FILE-215-7 done, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact on the way to beta. This is the work list agents pick from: take the highest-ranked entry that @@ -294,6 +294,12 @@ what an agent can't finish alone. - **Estimate:** 150–250 h. ### G2. Interactive performance +- **Measured progress (2026-10-26):** Expand, Contract and Border restrict distance work to + the nonzero bounds plus a radius halo. Small radii use capped distances; Contract avoids + inverted float masks and Border retains one distance plane. On 36 MP, twelve synthetic + comparisons measure 1.54–37.82× faster with exact output equality. Full-canvas mask + conversion and output remain; no GUI budget or readiness percentage changes. + [Method, measurements and limits](selection-distance-performance.md#cropped-selection-morphology-2026-10-26). - **Measured progress (2026-10-10):** Tilt-Shift's existing per-level halo/copy optimization measures 1.07–1.49× faster across nine local 24 MP cases, with exact finite output bits. The filtered proxy improves for medium/large blur; its @@ -390,6 +396,7 @@ what an agent can't finish alone. | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | Expand/Contract/Border distance work cropped to nonzero bounds; bounded distances for radii ≤5; 36 MP exact-output comparisons improve 1.54–37.82× across twelve cases; percentages, estimates and scorecard budgets unchanged | | 2026-10-25 | minor | G9: the count of preferences that do nothing is the scorecard's again, 12 of 178 (it still said 24 of 171, from 2026-10-15); no estimate changed | | 2026-10-25 | minor | G6: Art History Brush landed as partial (TOOL-213-20, #1610), so no toolbar tool is missing; no percentage or estimate changed | | 2026-10-23 | minor | G4: hard-round built-in presets use 5% spacing (#8842), guarded by large-stroke outline and pressure-opacity pixel regressions at 8/16/32-bit; percentages and estimates unchanged | diff --git a/docs/selection-distance-performance.md b/docs/selection-distance-performance.md index f0db2a70931..d4a19dc719f 100644 --- a/docs/selection-distance-performance.md +++ b/docs/selection-distance-performance.md @@ -73,3 +73,63 @@ EDT_WORKERS=1 cargo test --release -p photocraft-algo distance_transform_release The previous scalar implementation is retained only in the test module as the reference and benchmark baseline. + +## Cropped selection morphology (2026-10-26) + +Expand, Contract and Border now keep distance work inside the nonzero mask bounds, +expanded by `ceil(radius) + 1` and clipped to the supplied canvas. Nonzero bounds include +fractional coverage below the binary 0.5 threshold. Real pixels in the halo provide +outside seeds; cropping does not introduce an artificial selection edge. The engine's +existing canvas-bound padding remains responsible for Apply effect at canvas bounds. + +For radii up to 5 px, two vertical sweeps store capped distances in one byte per pixel. +A short horizontal stencil computes exact Euclidean distances only within `radius + 1`; +farther samples cannot contribute to the existing coverage formulas. Larger radii use +the general EDT above. Contract classifies complement seeds directly and writes the +complement coverage formula without allocating inverted float masks. Border runs its +two cropped transforms sequentially, reusing one seed mask and retaining one distance +plane at a time. + +A 50×50 selection at radius 5 needs a 62×62 distance window (3,844 samples), even on a +36 MP canvas. Seed, vertical and output-distance buffers total about 23 KB on the bounded +path, excluding allocator overhead. The flat API still scans its input for bounds and +returns a full-sized output (144 MB at 36 MP). Engine mask conversion, tiled writeback, +undo and compositing remain outside this optimization; this does not establish a GUI +latency budget or solve sparse document storage. + +Regression tests compare against the previous full-canvas formulas for empty/full masks, +one-row/column canvases, holes, edge-touching shapes, fractional radii, and fractional +coverage including complement rounding at 0.5. Every 3×3 binary mask is also checked +inside a larger canvas with a faint sample outside its binary bounds. The small-radius +distances are compared with the general EDT. Invalid dimensions and nonfinite/negative +radii return empty buffers. + +Reproduce on the fork through the CI workflow's optional `selection_morphology` input. +It runs `cargo run --release -p photocraft-algo --example bench_selection_morphology` +and `cargo xtask perf --quick` remotely. The comparison uses a 6000×6000 mask with either +a centred 50×50 square or a centred 4000×4000 square, radii 3 and 50, and four Rayon +workers. It checks every output sample against the previous formulas before timing; +reported medians include output allocation and exclude output destruction, with three +runs per implementation. These measurements are separate from the historical EDT-only +measurements above and do not change the scorecard baseline. + +Measurements from [scratch CI job 121583341033](https://github.com/wanikhawar/photocraft/actions/runs/40326176434/job/121583341033), +2026-10-26, commit `5afd231138368f9be856e8c21c2946f2e386797c`, GitHub-hosted Ubuntu 26.04, +stable Rust, normal release profile. The benchmark step completed successfully; the +superseded run was cancelled during the later quick performance build. The full validation +run is recorded in the PR. Times below are milliseconds; all twelve outputs match exactly. + +| Selection | Operation | Radius | Before p50 | After p50 | Speedup | +|---|---|---:|---:|---:|---:| +| 50×50 | Expand | 3 | 359.55 | 94.51 | 3.80× | +| 50×50 | Contract | 3 | 614.64 | 81.47 | 7.54× | +| 50×50 | Border | 3 | 738.30 | 19.52 | 37.82× | +| 50×50 | Expand | 50 | 357.84 | 99.76 | 3.59× | +| 50×50 | Contract | 50 | 601.19 | 81.19 | 7.41× | +| 50×50 | Border | 50 | 738.50 | 20.08 | 36.79× | +| 4000×4000 | Expand | 3 | 416.83 | 171.26 | 2.43× | +| 4000×4000 | Contract | 3 | 615.49 | 283.26 | 2.17× | +| 4000×4000 | Border | 3 | 802.48 | 377.78 | 2.12× | +| 4000×4000 | Expand | 50 | 414.50 | 268.96 | 1.54× | +| 4000×4000 | Contract | 50 | 610.98 | 260.77 | 2.34× | +| 4000×4000 | Border | 50 | 784.89 | 467.06 | 1.68× | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5c9fcd4b993..da3f528600d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # PhotoCraft vs Adobe Photoshop: target-app parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-25 · **Change:** minor (12 of 178 preferences do nothing, from the scorecard; the Camera Raw row names per-camera colour for non-DNG cameras as missing, not the Calibration panel, which landed 2026-10-13; Content-Aware Scale measurements added, #5236; Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; area type, TYPE-218-10 partial, Type scorecard 5 / 5 / 0; compound layer properties export as separate Photoshop Set events, #8304; JPEG Options dialog landed, FILE-215-19 partial; Print › Functions › Bleed through `file.print`; Content-Aware Move live preview for every selection size, TOOL-213-4 done, #6680; retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; fill and adjustment layers copy and paste whole, UI-217-23 partial, #2344; shape layers take Density and Feather, TOOL-214-12 done, #5846; on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged; PSD spot plates in Photoshop's polarity, #7415 split; TIFF spot plates, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-26 · **Change:** minor (cropped selection morphology performance evidence added; 12 of 178 preferences do nothing, from the scorecard; the Camera Raw row names per-camera colour for non-DNG cameras as missing, not the Calibration panel, which landed 2026-10-13; Content-Aware Scale measurements added, #5236; Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; area type, TYPE-218-10 partial, Type scorecard 5 / 5 / 0; compound layer properties export as separate Photoshop Set events, #8304; JPEG Options dialog landed, FILE-215-19 partial; Print › Functions › Bleed through `file.print`; Content-Aware Move live preview for every selection size, TOOL-213-4 done, #6680; retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; fill and adjustment layers copy and paste whole, UI-217-23 partial, #2344; shape layers take Density and Feather, TOOL-214-12 done, #5846; on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged; PSD spot plates in Photoshop's polarity, #7415 split; TIFF spot plates, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026 The authoritative answer to "how close is PhotoCraft to Photoshop, and how much work is left". The one-page summary is [`ROADMAP.md`](../ROADMAP.md); the ranked work list is [`gaps.md`](gaps.md); @@ -363,6 +363,12 @@ i7-9750H, 12 workers, 24 MP RGBA8, Good quality, amount 1: Spin 66.10 → 16.43 (4.02×), Zoom 19.19 → 5.35 s (3.59×), one paired run each, exact output equality. These are local measurements at amount 1; see [method and limits](radial-blur-performance.md). +2026-10-26: cropped Expand, Contract and Border measure 1.54–37.82× faster across twelve +36 MP synthetic mask cases on GitHub Actions, with exact output equality. Radii up to 5 px +use capped distances; Contract avoids inverted float masks and Border retains one distance +plane. Full-canvas mask conversion/output remain; no GUI budget or percentage changes. +See [measurements and limits](selection-distance-performance.md#cropped-selection-morphology-2026-10-26). + 2026-10-10: native selection distance transforms measured 7.59–10.57x faster on six 24–36 MP synthetic masks on an AWS c7i.4xlarge (16 workers, three paired release runs). The transform also corrects f32 envelope errors past coordinate 4096, including nonzero @@ -574,6 +580,7 @@ See [method, raw measurements and reproduction](five-algorithm-performance.md). | Date | Change | Summary | |---|---|---| +| 2026-10-26 | minor | Expand/Contract/Border distance work cropped to nonzero bounds; bounded distances for radii ≤5; 36 MP exact-output comparisons improve 1.54–37.82× across twelve cases; percentages, estimates and scorecard budgets unchanged | | 2026-10-25 | minor | UI / UX and Workspace rows: 12 of 178 preferences do nothing, the scorecard's count. Camera Raw row: the Calibration panel landed on 2026-10-13 (#5128); what is missing is per-camera colour for non-DNG cameras ([gaps.md](gaps.md) G14). Percentages and estimates unchanged | | 2026-10-23 | minor | Colour management and modes: PSD spot plates are stored as Photoshop stores them (ink 0 = solid), and PSDs from earlier PhotoCraft versions keep their ink (#7415 split, part 4); estimates unchanged | | 2026-10-23 | minor | Colour management and modes: spot plates now save and open in TIFF (#7415); estimates unchanged |