PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Speed up Tilt-Shift with existing per-level halo trimming (#2880)
optimalbytee3360f6e442a0
diff --git a/crates/algo/examples/bench_tilt_shift.rs b/crates/algo/examples/bench_tilt_shift.rsnew file mode 100644index 000000000..7b3f13e92--- /dev/null+++ b/crates/algo/examples/bench_tilt_shift.rs@@ -0,0 +1,54 @@+//! Complete Tilt-Shift filtering, including tiled reads and writes.+//! Run alone in release: `bench_tilt_shift 6000 4000 5 1`.+//! Fourth argument models the existing preview proxy scale (e.g. 1500 1000 7 4).+use photocraft_algo::{FilterParams, apply_in};+use photocraft_color::{ColorMode, PixelFormat, SampleType};+use photocraft_geom::Rect;+use photocraft_raster::Surface;++fn main() {+ let args: Vec<String> = std::env::args().collect();+ let number = |i: usize, fallback| args.get(i).and_then(|s| s.parse::<i32>().ok()).unwrap_or(fallback);+ let (w, h, reps) = (number(1, 6000).clamp(1, 6000), number(2, 4000).clamp(1, 6000), number(3, 5).clamp(1, 20));+ let proxy = number(4, 1).clamp(1, 8) as f32;+ let bounds = Rect::new(0, 0, w, h);+ for (sample, name) in [(SampleType::U8, "U8"), (SampleType::U16, "U16"), (SampleType::F32, "F32")] {+ let mut source = Surface::new(PixelFormat::new(ColorMode::Rgb, sample, true));+ for y in 0..h {+ let row: Vec<f32> = (0..w)+ .flat_map(|x| {+ let a = if (x + y) % 31 == 0 { 0.0 } else { 0.7 + (x % 7) as f32 / 30.0 };+ let hdr = if sample == SampleType::F32 { 3.0 } else { 1.0 };+ [hdr * (x % 256) as f32 / 255.0, ((x * 3 + y) % 251) as f32 / 250.0, ((x ^ y) % 256) as f32 / 255.0, a]+ })+ .collect();+ source.write_region(Rect::new(0, y, w, y + 1), &row);+ }+ let mut cases = vec![("medium", 80.0, 0.5, 0.5, 27.0, 0.1, 0.15)];+ if sample == SampleType::U8 {+ cases.extend([+ ("small", 15.0, 0.5, 0.5, 0.0, 0.1, 0.15),+ ("large", 300.0, 0.5, 0.5, -71.0, 0.03, 0.4),+ ("wide_focus", 80.0, 0.5, 0.5, 0.0, 0.4, 0.05),+ ("sharp_transition", 80.0, 0.2, 0.8, 63.0, 0.05, 0.01),+ ("focused", 80.0, 0.5, 0.5, 0.0, 1.0, 0.15),+ ("blurred", 80.0, -5.0, -5.0, 27.0, 0.1, 0.15),+ ]);+ }+ for (label, blur, center_x, center_y, angle, focus, transition) in cases {+ let params = FilterParams::TiltShift { blur: blur / proxy, center_x, center_y, angle, focus, transition };+ for _ in 0..2 {+ std::hint::black_box(apply_in(&source, ¶ms, bounds, bounds, None, bounds));+ }+ let mut times = Vec::new();+ for _ in 0..reps {+ let start = std::time::Instant::now();+ let output = apply_in(&source, ¶ms, bounds, bounds, None, bounds);+ times.push(start.elapsed().as_secs_f64() * 1000.0);+ std::hint::black_box(&output);+ drop(output);+ }+ println!("{}", serde_json::json!({"width": w, "height": h, "depth": name, "case": label, "proxy": proxy, "ms": times}));+ }+ }+}diff --git a/crates/algo/src/gallery.rs b/crates/algo/src/gallery.rsindex 414faddb1..53ed13d3b 100644--- a/crates/algo/src/gallery.rs+++ b/crates/algo/src/gallery.rs@@ -18,6 +18,10 @@ use crate::{BlurPath, Ctx, FieldPin, IrisPin, SpinPin};#[path = "tests_iris.rs"]mod tests;+#[cfg(test)]+#[path = "tests_tilt_shift.rs"]+mod tilt_shift_tests;+/// Gaussian σ for a gallery blur amount in px.fn sigma_of(blur: f32) -> f32 {blur.clamp(0.0, 500.0) * 0.6@@ -88,7 +92,7 @@ fn variable_blur(src: &Image, out: Rect, ctx: &Ctx, smax: f32, trim_levels: boollet (level, lw): (&[f32], usize) = if k == 0 {(&p, ww)} else {- // Only Iris opts in. Each level needs its own box-cascade reach,+ // Iris and Tilt-Shift opt in. Each level needs its own box-cascade reach,// not the maximum blur's trailing halo. Keep the original top/left:// moving the running sums' start changes floating-point cancellation.let trim = trim_levels && win.intersect(&out) == out;@@ -148,9 +152,10 @@ pub(crate) fn tilt_shift(src: &Image, out: Rect, ctx: &Ctx, blur: f32, centre: (// Band normal (the band runs along `angle`).let (s, c) = angle.to_radians().sin_cos();let (nx, ny) = (s, c);- let smax = sigma_of(blur);+ // A NaN amount must not become the upper bound of f32::clamp below.+ let smax = sigma_of(blur).max(0.0);let (f0, f1) = (focus.max(0.0), focus.max(0.0) + transition.max(1e-3));- variable_blur(src, out, ctx, smax, false, |x, y| {+ variable_blur(src, out, ctx, smax, true, |x, y| {let d = ((x - cx) * nx + (y - cy) * ny).abs() / ss;smax * smoothstep(f0, f1, d)})diff --git a/crates/algo/src/tests_tilt_shift.rs b/crates/algo/src/tests_tilt_shift.rsnew file mode 100644index 000000000..49a6e79bb--- /dev/null+++ b/crates/algo/src/tests_tilt_shift.rs@@ -0,0 +1,215 @@+use super::*;+use photocraft_color::{ColorMode, PixelFormat, SampleType};+use photocraft_raster::{Interrupt, Surface};++#[path = "tests_tilt_shift_reference.rs"]+mod reference;++fn image(rect: Rect, ch: usize) -> Image {+ let data = (rect.y0..rect.y1)+ .flat_map(|y| {+ (rect.x0..rect.x1).flat_map(move |x| {+ (0..ch).map(move |c| match c {+ 0 => (x * 17 + y * 31).rem_euclid(113) as f32 / 37.0 - 0.5,+ 1 => {+ if (x + y).rem_euclid(3) == 0 {+ 1.0+ } else {+ 0.0+ }+ }+ _ => ((x ^ y).unsigned_abs() as usize + c) as f32 % 23.0 / 22.0,+ })+ })+ })+ .collect();+ Image { rect, ch, data }+}++fn params(blur: f32, centre: (f32, f32), angle: f32, focus: f32, transition: f32) -> crate::FilterParams {+ crate::FilterParams::TiltShift { blur, center_x: centre.0, center_y: centre.1, angle, focus, transition }+}++fn check(src: &Image, out: Rect, ctx: &Ctx, p: &crate::FilterParams) {+ let crate::FilterParams::TiltShift { blur, center_x, center_y, angle, focus, transition } = *p else { panic!("Tilt-Shift fixture") };+ let want = reference::tilt_shift(src, out, ctx, blur, (center_x, center_y), angle, focus, transition);+ let got = tilt_shift(src, out, ctx, blur, (center_x, center_y), angle, focus, transition);+ assert_eq!(got.len(), want.len());+ for (i, (&got, &want)) in got.iter().zip(&want).enumerate() {+ assert!(got.to_bits() == want.to_bits() || (got.is_nan() && want.is_nan()), "sample {i}: {got} != {want}, delta {}", (got - want).abs());+ }+}++#[test]+fn tilt_shift_matches_frozen_kernel_at_band_boundaries_and_edges() {+ let bounds = Rect::new(-19, 7, 54, 66);+ let mut cases = Vec::new();+ for blur in [0.0, 0.49, 0.5, 1.0, 15.0, 80.0, 500.0] {+ for angle in [-90.0, -71.0, 0.0, 27.0, 90.0, 180.0] {+ cases.push(params(blur, (0.18, 0.91), angle, 0.03, 0.01));+ cases.push(params(blur, (0.5, 0.5), angle, 0.1, 0.6));+ }+ }+ cases.push(params(80.0, (0.5, 0.5), 0.0, 5.0, 0.1));+ cases.push(params(80.0, (-5.0, -5.0), 27.0, 0.1, 0.15));+ for ch in 1..=6 {+ let src = image(bounds.inflate(12), ch);+ for alpha in [false, true] {+ let ctx = Ctx { bounds, mode: ColorMode::Rgb, alpha };+ for p in &cases {+ check(&src, bounds, &ctx, p);+ check(&src, Rect::new(-7, 17, 15, 39), &ctx, p);+ }+ }+ }+}++#[test]+fn tilt_shift_preserves_degenerate_and_nonfinite_parameter_behavior() {+ for bounds in [Rect::EMPTY, Rect::new(1, -1, 2, 0), Rect::new(-5, 3, 14, 4)] {+ let src = image(bounds, 4);+ let ctx = Ctx { bounds, mode: ColorMode::Rgb, alpha: true };+ for value in [0.0, -1.0, f32::MIN, f32::MAX, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {+ for field in 0..6 {+ // The old NaN blur amount panicked in the sigma clamp. Its+ // corrected identity behavior has a separate regression below.+ if field == 0 && value.is_nan() {+ continue;+ }+ let mut p = params(15.0, (0.5, 0.5), 0.0, 0.1, 0.15);+ if let crate::FilterParams::TiltShift { blur, center_x, center_y, angle, focus, transition } = &mut p {+ match field {+ 0 => *blur = value,+ 1 => *center_x = value,+ 2 => *center_y = value,+ 3 => *angle = value,+ 4 => *focus = value,+ _ => *transition = value,+ }+ }+ check(&src, bounds, &ctx, &p);+ }+ }+ }+ let bounds = Rect::new(0, 0, 3, 5);+ let ctx = Ctx { bounds, mode: ColorMode::Rgb, alpha: true };+ assert!(crate::kernel(¶ms(15.0, (0.5, 0.5), 0.0, 0.1, 0.15), &Image { rect: bounds, ch: 4, data: vec![] }, bounds, &ctx).is_empty());+ assert!(crate::kernel(¶ms(15.0, (0.5, 0.5), 0.0, 0.1, 0.15), &Image { rect: bounds, ch: 0, data: vec![] }, bounds, &ctx).is_empty());+}++#[test]+fn tilt_shift_nan_blur_is_an_identity_instead_of_panicking() {+ let bounds = Rect::new(-2, 3, 9, 14);+ let src = image(bounds, 4);+ let ctx = Ctx { bounds, mode: ColorMode::Rgb, alpha: true };+ let p = params(f32::NAN, (0.5, 0.5), 0.0, 0.1, 0.15);+ assert_eq!(crate::kernel(&p, &src, bounds, &ctx), src.data);+ let mut surface = Surface::new(PixelFormat::RGBA32F);+ surface.write_region(bounds, &src.data);+ assert_eq!(crate::apply_in(&surface, &p, bounds, bounds, None, bounds), surface);+ // Prove this synthetic input panicked in the unchanged starting kernel.+ assert!(std::panic::catch_unwind(|| reference::tilt_shift(&src, bounds, &ctx, f32::NAN, (0.5, 0.5), 0.0, 0.1, 0.15)).is_err());+}++#[test]+fn tilt_shift_keeps_running_sum_order_for_extreme_hdr_and_signed_zero() {+ let bounds = Rect::new(-13, -5, 24, 28);+ let mut src = image(bounds.inflate(15), 4);+ let values = [0.0, -0.0, 1e30, -1e30, 1e-30, -1e-30, 0.8];+ for (i, px) in src.data.as_chunks_mut::<4>().0.iter_mut().enumerate() {+ px[0] = values[i % values.len()];+ px[1] = values[(i + 3) % values.len()];+ px[3] = [0.0, 1e-8, 0.5, 1.0][i % 4];+ }+ let ctx = Ctx { bounds, mode: ColorMode::Rgb, alpha: true };+ for blur in [0.5, 15.0, 80.0, 300.0] {+ for angle in [0.0, 37.0, -90.0] {+ let p = params(blur, (0.5, 0.5), angle, 0.1, 0.15);+ check(&src, bounds, &ctx, &p);+ check(&src, Rect::new(0, 0, 10, 17), &ctx, &p);+ }+ }+ for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {+ let mut invalid = src.clone();+ invalid.data[19] = value;+ invalid.data[47] = value;+ check(&invalid, bounds, &ctx, ¶ms(15.0, (0.5, 0.5), 0.0, 0.1, 0.15));+ }+}++#[test]+fn tilt_shift_depths_models_selection_and_tile_edges_match_reference() {+ let bounds = Rect::new(-17, 11, 96, 84);+ let area = Rect::new(-9, 17, 79, 77);+ let p = params(17.0, (0.3, 0.7), 29.0, 0.07, 0.3);+ let mut selection = Surface::new(PixelFormat::GRAY8);+ selection.fill_rect(bounds, &[0.4]);+ selection.fill_rect(Rect::new(3, 19, 35, 44), &[1.0]);+ selection.fill_rect(Rect::new(10, 20, 20, 30), &[0.0]);+ for mode in [+ ColorMode::Rgb,+ ColorMode::Grayscale,+ ColorMode::Cmyk,+ ColorMode::Lab,+ ColorMode::Bitmap,+ ColorMode::Indexed,+ ColorMode::Duotone,+ ColorMode::Multichannel,+ ] {+ for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {+ for alpha in [false, true] {+ let fmt = PixelFormat::new(mode, sample, alpha);+ let mut surface = Surface::new(fmt);+ surface.write_region(bounds, &image(bounds, fmt.channels()).data);+ let original = surface.clone();+ let ctx = Ctx { bounds, mode, alpha };+ let radius = reach(17.0).ceil() as i32 + 1;+ assert_eq!(p.halo_for(bounds), crate::Halo::Radius(radius));+ for extent in [None, Some(bounds)] {+ for tile in [16, 47, 128] {+ let got = crate::apply_tiled(&surface, &p, area, bounds, Some(&selection), tile, extent);+ let mut want = surface.clone();+ for y in (area.y0..area.y1).step_by(tile as usize) {+ for x in (area.x0..area.x1).step_by(tile as usize) {+ let t = Rect::new(x, y, (x + tile).min(area.x1), (y + tile).min(area.y1));+ let src = match extent {+ Some(e) => Image::read_clamped(&surface, t.inflate(radius), e),+ None => Image::read(&surface, t.inflate(radius)),+ };+ let mut data = reference::tilt_shift(&src, t, &ctx, 17.0, (0.3, 0.7), 29.0, 0.07, 0.3);+ crate::mix_selection(&mut data, t, &selection, &src);+ want.write_region(t, &data);+ }+ }+ assert_eq!(got.read_region(bounds), want.read_region(bounds), "{fmt:?}, tile {tile}, extent {extent:?}");+ }+ }+ assert_eq!(surface, original);+ }+ }+ }+}++#[test]+fn tilt_shift_cancellation_preserves_source() {+ use std::sync::atomic::{AtomicBool, Ordering};+ let bounds = Rect::new(0, 0, 512, 256);+ let mut source = Surface::new(PixelFormat::RGBA8);+ source.write_region(bounds, &image(bounds, 4).data);+ let original = source.clone();+ let p = params(80.0, (0.5, 0.5), 27.0, 0.1, 0.15);+ assert!(crate::apply_in_with(&source, &p, bounds, bounds, None, bounds, &Interrupt::cancel_only(&|| true)).is_none());+ let cancelled = AtomicBool::new(false);+ let cancel = || cancelled.load(Ordering::Relaxed);+ let progress = |p| {+ if p > 0.0 {+ cancelled.store(true, Ordering::Relaxed);+ }+ };+ let ctl = Interrupt::new(&cancel, &progress);+ assert!(crate::apply_in_with(&source, &p, bounds, bounds, None, bounds, &ctl).is_none());+ assert!(cancelled.load(Ordering::Relaxed));+ assert_eq!(source, original);+ let fresh = crate::apply_in_with(&source, &p, bounds, bounds, None, bounds, &Interrupt::NONE);+ assert_eq!(fresh, Some(crate::apply_in(&source, &p, bounds, bounds, None, bounds)));+}diff --git a/crates/algo/src/tests_tilt_shift_reference.rs b/crates/algo/src/tests_tilt_shift_reference.rsnew file mode 100644index 000000000..dca8c6d20--- /dev/null+++ b/crates/algo/src/tests_tilt_shift_reference.rs@@ -0,0 +1,134 @@+//! Frozen Tilt-Shift kernel from base a28d786638ffbb84c5fb7d5d30ea1c3d594cd3bc.+use super::*;+/// Gaussian σ for a gallery blur amount in px.+fn sigma_of(blur: f32) -> f32 {+ blur.clamp(0.0, 500.0) * 0.6+}++const LEVELS: usize = 6;++/// Blurs `src` over `out` with a per-pixel σ (`sigma(x, y)`, ≤ `smax`).+fn variable_blur(src: &Image, out: Rect, ctx: &Ctx, smax: f32, trim_levels: bool, sigma: impl Fn(f32, f32) -> f32) -> Vec<f32> {+ let n = src.ch;+ if n == 0 || out.is_empty() {+ return Vec::new();+ }+ if smax < 0.3 {+ return src.crop(out);+ }+ let win = src.rect;+ let (ww, wh) = (win.width() as usize, win.height() as usize);+ let (ow, oh) = (out.width() as usize, out.height() as usize);+ let Some(row_len) = ww.checked_mul(n).filter(|&len| len > 0) else { return Vec::new() };+ let Some(source_len) = row_len.checked_mul(wh) else { return Vec::new() };+ let Some(pixels) = ow.checked_mul(oh) else { return Vec::new() };+ let Some(samples) = pixels.checked_mul(n) else { return Vec::new() };+ if trim_levels && src.data.len() != source_len {+ return Vec::new();+ }+ // Level σs: 0, then smax / 2^(LEVELS-1) … smax.+ let lv: Vec<f32> = std::iter::once(0.0).chain((0..LEVELS).map(|k| smax / 2f32.powi((LEVELS - 1 - k) as i32))).collect();+ let sig: Vec<f32> = (0..pixels)+ .map(|i| {+ let (x, y) = xy(out, i);+ sigma(x as f32 + 0.5, y as f32 + 0.5).clamp(0.0, smax)+ })+ .collect();+ // Hat-function weight of level k for σ s.+ let weight = |k: usize, s: f32| -> f32 {+ let c = lv[k];+ if k > 0 && s >= lv[k - 1] && s <= c {+ (s - lv[k - 1]) / (c - lv[k - 1]).max(1e-6)+ } else if k + 1 < lv.len() && s >= c && s <= lv[k + 1] {+ (lv[k + 1] - s) / (lv[k + 1] - c).max(1e-6)+ } else if k + 1 == lv.len() && s >= c {+ 1.0+ } else {+ 0.0+ }+ };+ let p = if trim_levels {+ // The window is exactly src.rect: read interleaved channels together,+ // retaining the same multiplication and alpha order as premul_window.+ let mut p = src.data.clone();+ premultiply(&mut p, n, ctx.alpha);+ p+ } else {+ premul_window(src, win, ctx.alpha)+ };+ let mut acc = vec![0.0f32; samples];+ let mut buf = Vec::new();+ for (k, &lvk) in lv.iter().enumerate() {+ if !sig.iter().any(|&s| weight(k, s) > 0.0) {+ continue;+ }+ let (level, lw): (&[f32], usize) = if k == 0 {+ (&p, ww)+ } else {+ // Only Iris opts in. Each level needs its own box-cascade reach,+ // not the maximum blur's trailing halo. Keep the original top/left:+ // moving the running sums' start changes floating-point cancellation.+ let trim = trim_levels && win.intersect(&out) == out;+ let reach = if !trim || lvk < 0.3 { 0 } else { gauss_box_radii(lvk).iter().sum::<usize>() };+ let reach = i32::try_from(reach).unwrap_or(i32::MAX);+ let lw = if trim { (i64::from(out.x1.saturating_add(reach).min(win.x1)) - i64::from(win.x0)) as usize } else { ww };+ let lh = if trim { (i64::from(out.y1.saturating_add(reach).min(win.y1)) - i64::from(win.y0)) as usize } else { wh };+ buf.clear();+ if buf.capacity() == 0 {+ // Match the old single full-window allocation. Row appends must+ // not geometrically grow the capacity beyond that window.+ buf.reserve_exact(p.len());+ }+ if trim {+ for row in p.chunks_exact(row_len).take(lh) {+ if let Some(row) = row.get(..lw * n) {+ buf.extend_from_slice(row);+ }+ }+ } else {+ buf.extend_from_slice(&p);+ }+ gauss_blur_n(&mut buf, lw, lh, n, lvk);+ (&buf, lw)+ };+ for (i, &s) in sig.iter().enumerate() {+ let wk = weight(k, s);+ if wk <= 0.0 {+ continue;+ }+ let (x, y) = xy(out, i);+ let o = (((y - win.y0) as usize) * lw + (x - win.x0) as usize) * n;+ if let (Some(dst), Some(px)) = (acc.get_mut(i * n..(i + 1) * n), level.get(o..o + n)) {+ for (dst, px) in dst.iter_mut().zip(px) {+ *dst += px * wk;+ }+ }+ }+ }+ for px in acc.chunks_exact_mut(n) {+ unpremul_px(px, ctx.alpha);+ }+ acc+}++fn short_side(b: Rect) -> f32 {+ (b.width().min(b.height()) as f32).max(1.0)+}++/// Tilt-Shift: a sharp band through the centre at `angle`, blurring with+/// distance beyond `focus` over `transition` (both fractions of the shorter side).+#[allow(clippy::too_many_arguments)]+pub(crate) fn tilt_shift(src: &Image, out: Rect, ctx: &Ctx, blur: f32, centre: (f32, f32), angle: f32, focus: f32, transition: f32) -> Vec<f32> {+ let b = ctx.bounds;+ let ss = short_side(b);+ let (cx, cy) = (b.x0 as f32 + centre.0 * b.width() as f32, b.y0 as f32 + centre.1 * b.height() as f32);+ // Band normal (the band runs along `angle`).+ let (s, c) = angle.to_radians().sin_cos();+ let (nx, ny) = (s, c);+ let smax = sigma_of(blur);+ let (f0, f1) = (focus.max(0.0), focus.max(0.0) + transition.max(1e-3));+ variable_blur(src, out, ctx, smax, false, |x, y| {+ let d = ((x - cx) * nx + (y - cy) * ny).abs() / ss;+ smax * smoothstep(f0, f1, d)+ })+}diff --git a/docs/gaps.md b/docs/gaps.mdindex 171d38f32..ddffcc15c 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-10 · **Change:** major (first version: every known shortfall ranked, from the 2026-10-10 re-measure) · **Target:** Adobe Photoshop 2026+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-10 · **Change:** minor (Tilt-Shift evidence added to G2; earlier the same day: major, every known shortfall ranked from the re-measure) · **Target:** Adobe Photoshop 2026Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impacton the way to beta. This is the work list agents pick from: take the highest-ranked entry that@@ -158,6 +158,12 @@ what an agent can't finish alone.- **Estimate:** 150–250 h.### G2. Interactive performance+- **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+ default small blur and the 36 MP saturated-field gain are inconclusive.+ [Method and full ranges](tilt-shift-performance.md). Native GUI latency remains+ unmeasured; no scorecard budget or parity percentage is changed by this work.- **Missing:** 22 of 25 budgeted scenarios are over budget (baseline 2026-10-05, a heavilyloaded machine): layer move with styles 321 ms p50 against 25 ms, opacity change 276 msagainst 20 ms, paste 12 MP 1.2 s against 100 ms, layer move on 15000×10000 16-bit 2.7 s,@@ -212,5 +218,6 @@ what an agent can't finish alone.| Date | Change | Summary ||---|---|---|+| 2026-10-10 | minor | G2: recorded Tilt-Shift computation/filtered-proxy measurements and limits; gap and estimate remain open || 2026-10-10 | minor | Checked against the alpha gate (no alpha blockers); #2374 marked closed || 2026-10-10 | major | First version, from the full re-measure against Photoshop 2026 27.11.0 and the open issues |diff --git a/docs/target-app-parity.md b/docs/target-app-parity.mdindex ea014b092..472a0f7cf 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-10 · **Last updated:** 2026-10-10 · **Change:** major (full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment into this file) · **Target:** Adobe Photoshop 2026+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-10 · **Change:** minor (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) · **Target:** Adobe Photoshop 2026The authoritative answer to "how close is PhotoCraft to Photoshop, and how much work is left". Theone-page summary is [`ROADMAP.md`](../ROADMAP.md); the ranked work list is [`gaps.md`](gaps.md);@@ -382,6 +382,17 @@ Confidence: moderate — the next users of 0.2.x will move these numbers either### By dimension+2026-10-10: Tilt-Shift reuses the established contiguous premultiplication and+per-level trailing-halo trimming. Nine local 24 MP RGB U8/U16/F32 cases improve+1.07–1.49× with separated observed ranges (Ryzen 7 9700X, Windows, eight workers):+default blur 15, 609.5 → 451.7 ms; rotated blur 80, 1729.3 → 1241.4 ms. At 36 MP,+rotated blur 80: 2458.7 → 1668.0 ms; the saturated-field gain is inconclusive.+The existing filtered preview proxy at document blur 80/300 improves from+66.9/179.4 → 55.9/132.8 ms; its default blur 15 gain is inconclusive.+Finite pixel bits match the frozen starting kernel exactly. These are computation+timings with two baseline rounds, not GUI frame latency or a Photoshop parity+increase; see [method, upstream SIMD/rustfft investigation and full ranges](tilt-shift-performance.md).+2026-10-10: Iris Blur pin preparation, saturated-distance evaluation and trailingGaussian-level halo trimming measure 1.18–1.76× faster across eight local 24 MPRGB U8/U16/F32 cases (Ryzen 7 9700X, Windows, eight workers). Default blur 15:@@ -549,6 +560,7 @@ See [method, raw measurements and reproduction](five-algorithm-performance.md).| Date | Change | Summary ||---|---|---|+| 2026-10-10 | minor | Added measured Tilt-Shift computation/filtered-proxy gains and inconclusive cases; parity percentages and budgets unchanged || 2026-10-10 | minor | Readiness-by-audience table: percent and hours for full, mainstream and essentials; full number confirmed as the additive weighted sum over dimensions (46%, reported ~45%) || 2026-10-10 | minor | Added mainstream-practitioner (~43%) and essentials-user (~61%) numbers with written weights and discounts; full ready-for-real-work rechecked against its written weights (46%, reported ~45%), unchanged || 2026-10-10 | minor | Stage checked against the core-workflow alpha gate in `roadmap.md`: passes |diff --git a/docs/tilt-shift-performance.md b/docs/tilt-shift-performance.mdnew file mode 100644index 000000000..6b42bc487--- /dev/null+++ b/docs/tilt-shift-performance.md@@ -0,0 +1,255 @@+# Tilt-Shift computation (2026-10-10)++Starting base: `a28d786638ffbb84c5fb7d5d30ea1c3d594cd3bc`, freshly fetched+`origin/main`. Branch: `codex/tilt-shift-performance-20261010`. Worktree:+`C:\Users\Colum\.codex\worktrees\6c32\photocraft`. At investigation time,+`upstream/main` was `5963e5b7f0aefa0d94b5cf67ef3c1c9b6d3399dd`, two commits ahead:+[Recent entries](https://github.com/storytold/photocraft/commit/b773a39efa4a65888fcce4a5d8dffcf4fa45700a)+and [temporary Move](https://github.com/storytold/photocraft/commit/5963e5b7f0aefa0d94b5cf67ef3c1c9b6d3399dd).+Neither changes filtering. The original checkout, local main and other worktrees+were not edited. Cargo uses `target/agent-tilt-shift` throughout.++## Upstream evidence and choice++GitHub open/closed/merged PRs and open/closed issues were searched for blur,+Tilt-Shift, Field Blur, sampling, SIMD, portable, std::simd and rustfft. Relevant+bodies, discussions, final diffs, merge commits, Gallery history and current+source were inspected before the implementation was selected.++| Work | Status and evidence | Consequence for Tilt-Shift |+|---|---|---|+| [#1524: portable Mosaic reads](https://github.com/storytold/photocraft/pull/1524), [merge d651be13](https://github.com/storytold/photocraft/commit/d651be1393b709d638dd9d0e4824a420f795d3ae) | The SIMD-related proposal the human referred to. Its AVX2/pulp portion was experimental and removed before merge: the [review](https://github.com/storytold/photocraft/pull/1524#issuecomment-6072959394) found no complete-filter gain to justify dependencies/features/CI. Portable contiguous row reads and exact-output tests landed. | Reuse contiguous reads. Main has no general portable-SIMD Gallery backend or nightly std::simd path to reuse. |+| [#1471: adaptive rustfft Motion Blur](https://github.com/storytold/photocraft/pull/1471), [merge c7dbb37b](https://github.com/storytold/photocraft/commit/c7dbb37b3c61c18223e56c10d06efc71e48c7677) | Merged. Builds on [#902](https://github.com/storytold/photocraft/pull/902)'s merged bilinear taps/row convolution. Wide uniform streaks benefit from FFT; short/unsupported cases retain rows. Current code bounds FFT allocations and rejects unsuitable coordinates/samples from that path. | Tilt-Shift is spatially varying, not one uniform convolution. A single FFT would change the band; one FFT per existing Gaussian level would preserve spatial blending but replace linear-time box cascades with transforms, padding, complex scratch and numerical differences. No demonstrated crossover warrants that machinery here. |+| [#867: Gaussian running sums and bands](https://github.com/storytold/photocraft/pull/867), [#628: Box Blur](https://github.com/storytold/photocraft/pull/628), [#1602: fixed-channel accumulators](https://github.com/storytold/photocraft/pull/1602) carrying closed [#1511](https://github.com/storytold/photocraft/pull/1511) | Merged, with radius-independent separable passes, traversal/allocation improvements and compiler-friendly accumulators. | Gallery already uses separable boxes, with f64 running sums. Replacing them with the f32 Gaussian accumulators would change HDR cancellation/rounding. Avoid a broad kernel/traversal rewrite. |+| [#1499: Radial sampling](https://github.com/storytold/photocraft/pull/1499) | Merged after [review](https://github.com/storytold/photocraft/pull/1499#issuecomment-6071866387) removed a changed-output polar approximation and a separate preview scheduler. Exact transform preparation and interleaved taps remained. | Preserve the kernel and reuse current services. Tilt-Shift already prepares its band geometry once per tile and has no radial/disk samples to precompute. |+| [#2578: Iris Blur](https://github.com/storytold/photocraft/pull/2578), [merge fa33712d](https://github.com/storytold/photocraft/commit/fa33712dd3bd87c4502c01dbeae3d235383e1b46) | Already merged in the starting base. Prepares Iris geometry and adds exact-output contiguous premultiplication and per-level trailing-halo trimming to the shared helper; only Iris opts in. | Opt Tilt-Shift into that established helper. No new algorithm, dependency, cache or scheduler is needed. Field remains unchanged. |+| [#1899: preview worker/cancellation](https://github.com/storytold/photocraft/pull/1899), [#1825: keep preview during commit](https://github.com/storytold/photocraft/pull/1825), [#2207: preview scale](https://github.com/storytold/photocraft/pull/2207) | Merged. Latest-request worker; cancel stale work after 150 ms without parameter changes, preserving updates during dragging. Pixel parameters scale with the existing proxy. | Leave the UI and worker intact; faster tile computation also shortens the existing worker's filtering work. |+| Active [#2685](https://github.com/storytold/photocraft/pull/2685), [#2580](https://github.com/storytold/photocraft/pull/2580), [#2739](https://github.com/storytold/photocraft/pull/2739) | Respectively Spin/Lens/Extrude/Wind/Trap sampling, general compression/IO/compositing allocation work, and smart-filter stage caching/background jobs. #2685 touches Gallery's Spin path, not Tilt-Shift's Gaussian field. | No existing Tilt-Shift fix or overlapping implementation found. Keep this change confined to Tilt-Shift's opt-in and its tests. |++[Issue #464](https://github.com/storytold/photocraft/issues/464) records Gaussian+preview lag and profiling with copying and waits prominent; [#211](https://github.com/storytold/photocraft/issues/211)+tracks broader slow algorithms. They inform the need for complete-filter and+preview-workload measurements, rather than claiming a microbenchmark fixes GUI latency.++[RustFFT's primary documentation](https://github.com/ejmahler/RustFFT/blob/master/README.md)+describes O(N log N) transforms and automatic native AVX/SSE/NEON selection, with+different wasm SIMD requirements. That is useful existing infrastructure for+uniform expensive kernels, but does not remove the spatially varying blend or+improve the asymptotic cost of Gallery's existing box passes. No FFT or explicit+SIMD candidate is benchmarked here; the comparison above is an algorithmic and+maintenance assessment, not a measured claim that they can never be faster.++## Numerical and memory contract++Tilt-Shift has one band, described by `centerX`, `centerY`, `angle`, `focus`,+`transition` and `blur`; its engine/model has no pins parameter. Six nonzero+Gaussian levels plus the zero level retain their existing geometric spacing,+three-box radii, smoothstep sigma field and hat weights. Sharp/blurred and+transition pixels still blend their original levels. Pixel centres, image+coordinates, transparent premultiplication and edge policy are unchanged.++The optimized helper clones the already interleaved source and premultiplies it+with the same per-pixel operations. For each Gaussian level it keeps the+original top/left, trimming only right/bottom to the output plus that level's+summed box radii. Its artificial trailing edge cannot influence output through+the three finite-support passes. Keeping the leading edge preserves the+running-sum initialization, update order and f64 cancellation, including HDR.+No samples or levels are dropped. Cropped-output containment retains the+helper's existing fallback to a full window.++The existing source, premultiplied buffer, sigma map, accumulator and reusable+level buffer remain. Full-window capacity is still reserved once; populated+length and blur scratch shrink. There is no retained cache, feature dispatch,+threshold or planning cost. Source halo reads, auto tile sizes, worker count,+selection mixing, output writeback, undo/redo and cancellation services remain+the same. No change requires a native CPU feature or unsafe code.++One pre-existing crash found by the synthetic tests is fixed: a NaN low-level+blur amount previously became f32::clamp's invalid upper bound. It now acts as+identity. The regression asserts the frozen starting implementation panics and+the corrected kernel returns the source. Valid finite parameters keep exact bits.++`tests_tilt_shift_reference.rs` freezes the starting scalar Gallery/Tilt-Shift+expressions, using the unchanged Gaussian helpers. Differential tests compare+every finite f32 bit (including signed zero), with matching NaN classifications:+1–6 channels, RGB/Gray/CMYK/Lab and the expanded Bitmap/Indexed/Duotone/Multichannel+storage, U8/U16/F32, alpha/no alpha, narrow and soft band+boundaries, translated/rotated bands, tiny/empty/one-row images, blur thresholds,+full focus/full blur, extreme and nonfinite parameters, HDR/negative/high-contrast+samples, nonfinite pixels, selections, transparent/repeated edges and tile sizes+16/47/128. Cancellation before work and after progress preserves the source.+Malformed internal source lengths and zero channels are also checked.++## Measurement method++Windows x86_64, Ryzen 7 9700X (8 cores/16 logical), 64 GiB installed RAM;+stable Rust 1.99.0 / LLVM 23.1.1. Normal workspace release profile: opt-level 3,+thin LTO, one codegen unit. Eight Rayon workers. Builds/tests are stopped during+measurements, and process inspection checks for concurrent Cargo/rustc/benchmark+work. Ordinary system activity and thermal/allocator variation remain.++`bench_tilt_shift` constructs deterministic textured RGBA surfaces with varying+alpha and HDR F32 values. Two untimed warmups precede each case. Timing covers+complete `apply_in`: source/halo reads, tiled field and level computation, Rayon,+writeback and pruning. Fixture construction and output destruction are excluded.+It uses the unchanged pipeline, not an isolated hot loop. Baseline executables+are built before editing the algorithm and retained in local `plan/`.+The `blurred` case puts the band outside the image through the low-level Rust+API; it is a saturated-field stress case, outside the engine dialog's centre+range. All other cases use the supported dialog parameters. No pin list is+invented for Tilt-Shift. Model performance is measured for RGB; other models are+covered by differential correctness tests.++The preview workload models the existing 24 MP document's 1500×1000 filtered+proxy (factor 4), with blur 15/80/300 becoming 3.75/20/75. Position, angle, focus+and transition are relative and unchanged. This times filtering a proxy after a+parameter update. It excludes proxy construction, Session/history, queue/settle+delay, compositing, GPU upload and presentation; it is not actual GUI input/frame+latency. The implementation does not alter the preview factor or kernel.++```powershell+$env:CARGO_TARGET_DIR = 'target/agent-tilt-shift'+$env:RAYON_NUM_THREADS = '8'+cargo run --release -p photocraft-algo --example bench_tilt_shift -- 6000 4000 5 1+cargo run --release -p photocraft-algo --example bench_tilt_shift -- 6000 6000 5 1+cargo run --release -p photocraft-algo --example bench_tilt_shift -- 1500 1000 7 4+cargo run --release -p photocraft-algo --example bench_tilt_shift -- 128 96 7 1+```++## Results++Order: base A, candidate, base B, with all four sizes completed per implementation+round. Full-size cases have five timed samples per round; proxy and small cases+have seven. Base p50 pools the two unchanged rounds (10/14 samples); candidate+p50 uses 5/7 samples. Ranges include every timed sample, not only best runs.+Local raw logs are `plan/tilt-{baseline,candidate,baseline-repeat}-*.jsonl`.++The parameters are fixed by the example: `small` is blur 15, centred, angle 0,+focus 0.1, transition 0.15; `medium` is blur 80 at angle 27; `large` is blur 300,+angle -71, focus 0.03, transition 0.4. `wide_focus` is blur 80, angle 0, focus 0.4,+transition 0.05; `sharp_transition` is centred at (0.2, 0.8), blur 80, angle 63,+focus 0.05, transition 0.01. `focused` uses focus 1; `blurred` uses the low-level+outside-image centre (-5, -5). The latter two use blur 80. Proxy blur alone is+divided by four. U16/F32 time the rotated medium case.++### 24 MP (6000×4000)++| Depth / case | Base ms (range) | Candidate ms (range) | Speedup |+|---|---:|---:|---:|+| U8 medium | 1729.3 (1530.2–1996.6) | 1241.4 (1227.0–1256.5) | 1.39× |+| U8 small | 609.5 (594.2–616.1) | 451.7 (443.1–479.9) | 1.35× |+| U8 large | 5340.1 (5042.7–5861.9) | 3698.9 (3498.1–3722.3) | 1.44× |+| U8 wide_focus | 1204.9 (1177.8–1273.9) | 828.7 (792.5–874.5) | 1.45× |+| U8 sharp_transition | 1615.6 (1576.2–1636.4) | 1148.4 (1135.1–1153.2) | 1.41× |+| U8 focused | 433.5 (426.1–438.2) | 406.1 (399.6–410.5) | 1.07× |+| U8 blurred | 1105.7 (1051.6–1146.0) | 963.6 (938.0–1045.8) | 1.15× |+| U16 medium | 1935.8 (1877.7–1978.8) | 1306.8 (1268.9–1403.0) | 1.48× |+| F32 medium | 1961.7 (1858.5–2010.5) | 1316.8 (1270.2–1396.5) | 1.49× |++### 36 MP (6000×6000)++| Depth / case | Base ms (range) | Candidate ms (range) | Speedup |+|---|---:|---:|---:|+| U8 medium | 2458.7 (2066.6–2541.9) | 1668.0 (1656.9–1682.4) | 1.47× |+| U8 small | 806.6 (733.7–864.2) | 655.1 (627.0–678.9) | 1.23× |+| U8 large | 8856.0 (6766.5–9301.8) | 6176.2 (5780.6–6622.0) | 1.43× |+| U8 wide_focus | 1612.8 (1562.4–1672.7) | 1066.4 (1057.8–1084.3) | 1.51× |+| U8 sharp_transition | 2529.7 (2448.6–2590.1) | 1714.6 (1705.0–1890.4) | 1.48× |+| U8 focused | 646.3 (627.5–680.0) | 614.1 (613.8–618.5) | 1.05× |+| U8 blurred | 1633.2 (1595.3–1687.9) | 1577.6 (1566.4–1623.2) | 1.04× |+| U16 medium | 2618.4 (2498.4–2687.4) | 2020.7 (1994.9–2027.0) | 1.30× |+| F32 medium | 2669.3 (2561.2–2741.6) | 2020.5 (1734.9–2173.3) | 1.32× |++### 1500×1000 filtered preview proxy, factor 4++| Depth / case | Base ms (range) | Candidate ms (range) | Speedup |+|---|---:|---:|---:|+| U8 medium | 66.9 (63.1–82.0) | 55.9 (54.9–59.0) | 1.20× |+| U8 small | 29.4 (27.2–32.9) | 28.0 (26.4–29.9) | 1.05× |+| U8 large | 179.4 (157.0–205.6) | 132.8 (116.7–149.6) | 1.35× |+| U8 wide_focus | 52.1 (46.7–72.0) | 40.4 (38.9–44.0) | 1.29× |+| U8 sharp_transition | 64.3 (54.6–75.4) | 44.2 (41.2–45.7) | 1.45× |+| U8 focused | 17.9 (16.7–18.7) | 15.0 (14.6–15.1) | 1.20× |+| U8 blurred | 37.4 (36.1–48.0) | 29.5 (28.2–33.0) | 1.27× |+| U16 medium | 89.2 (81.3–95.8) | 58.1 (56.0–59.0) | 1.54× |+| F32 medium | 93.7 (83.1–102.4) | 60.3 (57.9–65.8) | 1.55× |++### 128×96 small-image overhead++| Depth / case | Base ms (range) | Candidate ms (range) | Speedup |+|---|---:|---:|---:|+| U8 medium | 30.25 (30.09–31.83) | 18.14 (17.69–19.34) | 1.67× |+| U8 small | 3.93 (3.85–3.99) | 3.15 (3.13–3.22) | 1.25× |+| U8 large | 278.90 (273.62–313.48) | 145.97 (142.65–148.51) | 1.91× |+| U8 wide_focus | 26.08 (25.29–27.79) | 15.48 (15.38–15.69) | 1.69× |+| U8 sharp_transition | 31.12 (30.48–46.89) | 17.40 (17.35–17.65) | 1.79× |+| U8 focused | 1.56 (1.50–1.64) | 1.07 (1.06–1.09) | 1.46× |+| U8 blurred | 7.57 (6.82–11.06) | 6.19 (6.05–7.02) | 1.22× |+| U16 medium | 30.99 (30.58–32.48) | 17.94 (17.61–18.07) | 1.73× |+| F32 medium | 31.53 (30.28–48.73) | 17.90 (17.82–18.74) | 1.76× |++All nine 24 MP cases have separated observed ranges. Gains are modest for the+focused and saturated stress fields. At 36 MP the saturated field's ranges+overlap; no convincing gain is established there. Default blur 15 on the preview+proxy also has overlapping ranges: its 1.05× pooled median change is inconclusive.+Medium/large proxy cases improve 1.20/1.35×, and U16/F32 medium proxy cases improve+1.54/1.55×. The small-image saturated case is also inconclusive; the remaining+small-image cases improve 1.25–1.91× with separated ranges.++There is meaningful drift, so the pooled p50 must not imply precise repeatability:+24 MP U8 medium base A/B medians are 1909.1/1564.3 ms (candidate 1241.4), giving+1.54/1.26× against the individual rounds. The 36 MP large case's base A/B medians+are 7234.7/9170.0 ms (candidate 6176.2), giving 1.17/1.48×. Process CPU sampling+during the repeat found the benchmark using about 7.6 cores and no other heavy+CPU consumer. The report retains the full variation rather than attributing it+to a proven cause.++For one complete 24 MP suite (fixture construction, warmups and all depths/cases+included), sampled Windows `PeakWorkingSet64` is 2,162,429,952 bytes for the base+and 2,044,227,584 for the candidate, about 5.5% lower (2.01 → 1.90 GiB).+This is an allocator-dependent process high-water measurement, not a per-filter+live-memory bound. Allocation counts are not instrumented; the source-copy,+sigma-map, level-metadata, output and level-buffer allocations remain, and full-window buffer+capacity is retained. Smaller populated levels and scratch account for the+structural reduction in work. Neither SIMD nor FFT crossover performance is+claimed; no adaptive threshold is introduced.++Maximum observed finite pixel error is **zero** in the differential tests. Every+pixel must match, so localized band-edge, seam, opacity or aliasing errors cannot+hide in an average-error metric. NaN classifications match. The NaN blur crash+regression intentionally differs from the starting kernel by returning identity.++## Validation and remaining limits++The full `photocraft-algo` suite passes: 425 tests, 18 ignored, no failures.+All six Tilt-Shift differential/regression tests also pass in release. Strict+all-targets Clippy passes for the algorithm crate. The existing engine filter+integration group passes all 16 tests, including selection, repeat, undo and+16/32-bit filtering. `cargo xtask layers` reports 29 crates with no violations;+`cargo xtask wasm` passes the required workspace packages and the HEIF-enabled+codec check. Regenerating the scorecard produces identical content.++`cargo xtask perf --quick` exits successfully; all five configured quick benches+(`perf_scenarios`, `type_bench`, `layout_bench`, `camera_raw_bench`, `bevel_bench`)+complete. Reports are retained locally in+`target/agent-tilt-shift/perf/{results.json,summary.md}`. The regression comparison+is skipped because the checked-in baseline is from an Apple M4 Pro/macOS machine+class. Quick mode does not enforce full-size budgets. The layout harness still+reports unrelated frame overruns; completing this gate does not establish+broader responsiveness or budget compliance. Formatting and Git whitespace+checks pass.++Algorithm checks also pass for aarch64/x86_64 macOS, aarch64 Windows and+aarch64/x86_64 Linux. These are compilation checks from Windows, not executions+or performance measurements on those platforms. Native timing evidence is+limited to this Windows x86_64 machine. `cargo xtask test-corpus --changed`+correctly skips its suites because no format, IO, compositor, GPU or text crate+changed. Command registrations and UI code are unchanged.++The measurements establish equivalence to the starting PhotoCraft kernel, not a+new Photoshop oracle or broader parity increase. Cold startup, actual GUI+input/frame latency, allocation counts and other platforms' native performance+remain unmeasured. No performance budget, scorecard checklist or parity floor is+raised from these local results. The shared craftrules checkout was unavailable+at the documented paths; the repository's own contributor and validation rules+were followed.