diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index 70e815b2b2..c4fc913785 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -818,13 +818,23 @@ pub fn feather(m: &[f32], w: usize, h: usize, radius: f32) -> Vec { /// rows are filled in parallel, and each sub-row tests only the edges that /// cross it (an active edge list over the edges sorted by their top). pub fn polygon(points: &[(f32, f32)], area: Rect, anti_alias: bool) -> Vec { + polygon_window(points, area, area, anti_alias) +} + +/// Rasterizes only `window` intersected with `canvas`, retaining the coordinate arithmetic of +/// [`polygon`] over the whole canvas. Keeping that origin avoids rounding changes in fractional +/// edge coverage when a feathered lasso uses a smaller working mask. +pub fn polygon_window(points: &[(f32, f32)], canvas: Rect, window: Rect, anti_alias: bool) -> Vec { + let area = window.intersect(&canvas); let (w, h) = (area.width() as usize, area.height() as usize); let mut m = vec![0.0f32; w * h]; if points.len() < 3 || w == 0 { return m; } let sub = if anti_alias { 4 } else { 1 }; - let sample_y = |py: usize, s: usize| area.y0 as f32 + py as f32 + (s as f32 + 0.5) / sub as f32; + let dx = (i64::from(area.x0) - i64::from(canvas.x0)) as usize; + let dy = (i64::from(area.y0) - i64::from(canvas.y0)) as usize; + let sample_y = |py: usize, s: usize| canvas.y0 as f32 + (dy + py) as f32 + (s as f32 + 0.5) / sub as f32; // A sub-row at y crosses the edge a→b iff top <= y < bottom; horizontal and NaN edges // never cross one. struct Edge { @@ -871,12 +881,13 @@ pub fn polygon(points: &[(f32, f32)], area: Rect, anti_alias: bool) -> Vec xs.extend(active.iter().map(|&&Edge { a, b, .. }| a.0 + (y - a.1) / (b.1 - a.1) * (b.0 - a.0))); xs.sort_by(|a, b| a.total_cmp(b)); for span in xs.as_chunks::<2>().0 { - let (x0, x1) = ((span[0] - area.x0 as f32).max(0.0), (span[1] - area.x0 as f32).min(w as f32)); + let (x0, x1) = ((span[0] - canvas.x0 as f32).max(0.0), (span[1] - canvas.x0 as f32).min(canvas.width() as f32)); if x1 <= x0 { continue; } - let (c0, c1) = (x0.floor() as usize, (x1.ceil() as usize).min(w)); + let (c0, c1) = ((x0.floor() as usize).saturating_sub(dx), (x1.ceil() as usize).saturating_sub(dx).min(w)); for (cx, v) in row.iter_mut().enumerate().take(c1).skip(c0) { + let cx = cx + dx; let cov = if anti_alias { ((cx + 1) as f32).min(x1) - (cx as f32).max(x0) } else { diff --git a/crates/algo/src/selection/tests.rs b/crates/algo/src/selection/tests.rs index 368633f03a..30ae9b23a2 100644 --- a/crates/algo/src/selection/tests.rs +++ b/crates/algo/src/selection/tests.rs @@ -654,3 +654,23 @@ fn combine_region_matches_combine() { } assert!(combine_region(None, None, SelectionMode::Subtract).is_none()); } + +#[test] +fn polygon_window_keeps_full_canvas_fractional_coverage() { + for canvas in [Rect::new(0, 0, 110_000, 12), Rect::new(-123, -7, 109_877, 5)] { + let points = [(100_003.12, -2.3), (100_043.71, 2.19), (100_032.39, 9.2), (100_001.52, 4.17)]; + for aa in [false, true] { + let full = polygon(&points, canvas, aa); + for requested in [Rect::new(99_998, -10, 100_048, 15), Rect::new(100_010, -3, 100_030, 6), Rect::EMPTY] { + let area = requested.intersect(&canvas); + let local = polygon_window(&points, canvas, requested, aa); + let mut crop = Vec::new(); + for y in area.y0..area.y1 { + let start = (y - canvas.y0) as usize * canvas.width() as usize + (area.x0 - canvas.x0) as usize; + crop.extend_from_slice(&full[start..start + area.width() as usize]); + } + assert_eq!(local, crop, "canvas={canvas:?}, requested={requested:?}, aa={aa}"); + } + } + } +} diff --git a/crates/engine/examples/bench_tool_feather.rs b/crates/engine/examples/bench_tool_feather.rs new file mode 100644 index 0000000000..d7eabf0e53 --- /dev/null +++ b/crates/engine/examples/bench_tool_feather.rs @@ -0,0 +1,150 @@ +//! Feathered marquee / lasso on a 6000×4000 (24 MP) canvas: the pre-windowing reference +//! (shape → dense full-canvas mask → `sel::feather` → `sel::combine(None, …, Replace)`) +//! against the current `select.rect` / `select.lasso` commands, whose dense feather mask +//! stays a (50 + 2·(⌈3·4⌉+1))² = 76² = 5776-pixel window around the 50×50 shape. +//! `cargo run --release -p photocraft-engine --example bench_tool_feather [reps]` +use std::time::{Duration, Instant}; + +use photocraft_algo::selection as sel; +use photocraft_color::{ColorMode, PixelFormat, SampleType}; +use photocraft_doc::{Document, Layer, Size}; +use photocraft_engine::Session; +use photocraft_geom::Rect; +use photocraft_raster::Surface; +use serde_json::{Value, json}; + +type Res = Result>; + +const W: i32 = 6000; +const H: i32 = 4000; +/// A 50×50 shape centred on the canvas, feathered by 4 px. +const X: i32 = W / 2 - 25; +const Y: i32 = H / 2 - 25; +const SHAPE: i32 = 50; +const FEATHER: f32 = 4.0; +const DEFAULT_REPS: usize = 7; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Kind { + Rect, + Ellipse, + Lasso, +} + +impl Kind { + fn label(self) -> &'static str { + match self { + Kind::Rect => "rect", + Kind::Ellipse => "ellipse", + Kind::Lasso => "lasso", + } + } + + fn command(self) -> &'static str { + match self { + Kind::Lasso => "select.lasso", + Kind::Rect | Kind::Ellipse => "select.rect", + } + } + + fn params(self) -> Value { + let r = json!({"x": X, "y": Y, "width": SHAPE, "height": SHAPE, "feather": FEATHER}); + match self { + Kind::Rect => r, + Kind::Ellipse => json!({"x": X, "y": Y, "width": SHAPE, "height": SHAPE, "ellipse": true, "feather": FEATHER}), + Kind::Lasso => json!({"points": [[X, Y], [X + SHAPE, Y], [X + SHAPE, Y + SHAPE], [X, Y + SHAPE]], "feather": FEATHER}), + } + } + + /// The path the windowed commands replaced: shape construction, a dense full-canvas f32 + /// mask, the full-canvas blur, and a full-canvas `Replace` combine against no old selection. + fn reference(self, area: Rect) -> Option { + let mask = match self { + Kind::Rect | Kind::Ellipse => { + let r = Rect::from_xywh(X, Y, SHAPE as u32, SHAPE as u32); + let shape = if self == Kind::Ellipse { + sel::ellipse_surface(r, area, true) + } else { + let mut s = Surface::new(PixelFormat::GRAY8); + s.fill_rect(r.intersect(&area), &[1.0]); + s + }; + sel::mask_from_surface(Some(&shape), area) + } + // Raw floating-point coverage: never quantise before the blur. + Kind::Lasso => { + let e = (X + SHAPE) as f32; + let (x, y, ey) = (X as f32, Y as f32, (Y + SHAPE) as f32); + sel::polygon(&[(x, y), (e, y), (e, ey), (x, ey)], area, true) + } + }; + let (w, h) = (area.width() as usize, area.height() as usize); + let mask = sel::feather(&mask, w, h, FEATHER); + sel::combine(None, &mask, area, sel::SelectionMode::Replace) + } +} + +fn median(times: &[Duration]) -> Duration { + let mut sorted = times.to_vec(); + sorted.sort_unstable(); + let n = sorted.len(); + let Some(mid) = sorted.get(n / 2).copied() else { return Duration::ZERO }; + if n % 2 == 1 { mid } else { sorted.get(n / 2 - 1).copied().map_or(mid, |prev| (prev + mid) / 2) } +} + +fn main() -> Res<()> { + let reps = match std::env::args().nth(1) { + None => DEFAULT_REPS, + Some(v) => { + let n: usize = v.parse().map_err(|e| format!("reps `{v}` must be a whole number ({e})"))?; + if !(1..=1000).contains(&n) { + return Err("reps must be in 1..=1000".into()); + } + n + } + }; + // Sparse 24 MP document: `Document::new` plus an empty raster layer allocates no pixels. + let mut doc = Document::new("bench-24mp", Size::new(W as u32, H as u32), ColorMode::Grayscale, SampleType::U8); + let format = doc.pixel_format(); + doc.layers.push(Layer::raster("Layer 1", format)); + let mut s = Session::new(); + s.add_document(doc, None); + let area = s.active().map(|st| st.doc.bounds()).ok_or("no document")?; + + let full_px = W as u64 * H as u64; + let side = SHAPE as u64 + 2 * ((FEATHER * 3.0).ceil() as u64 + 1); + println!("tool feather, 6000×4000 = {full_px} px canvas, {SHAPE}×{SHAPE} shape, feather {FEATHER} px, median of {reps}"); + println!( + "dense f32 mask: full canvas {full_px} px / {} B vs windowed {side}×{side} = {} px / {} B ({}× fewer)\n", + full_px * 4, + side * side, + side * side * 4, + full_px / (side * side), + ); + for kind in [Kind::Rect, Kind::Ellipse, Kind::Lasso] { + // One untimed pass each: allocator and first-call setup stay out of the medians. + drop(std::hint::black_box(kind.reference(area))); + let _ = s.execute("select.deselect", json!({})); + s.execute(kind.command(), kind.params())?; + let mut reference = Vec::with_capacity(reps); + for _ in 0..reps { + let t = Instant::now(); + let out = kind.reference(area); + reference.push(t.elapsed()); + std::hint::black_box(&out); + drop(out); + } + let mut current = Vec::with_capacity(reps); + for _ in 0..reps { + let _ = s.execute("select.deselect", json!({})); + let t = Instant::now(); + s.execute(kind.command(), kind.params())?; + current.push(t.elapsed()); + } + let (r, c) = (median(&reference), median(¤t)); + let (ms, cm) = (r.as_secs_f64() * 1000.0, c.as_secs_f64() * 1000.0); + let speedup = if cm > 0.0 { ms / cm } else { f64::INFINITY }; + println!("{:<6} reference {ms:>9.2} ms current {cm:>9.2} ms speedup {speedup:>7.1}x", kind.label()); + } + Ok(()) +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 38ede534b1..5b5f37b4d6 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -410,8 +410,9 @@ fn build() -> Vec { s }; if feather > 0.0 { - let m = sel::feather(&sel::mask_from_surface(Some(&shape), area), area.width() as usize, area.height() as usize, feather); - doc.selection = sel::combine(doc.selection.as_ref(), &m, area, sel::SelectionMode::parse(&mode)); + let window = selection_cmds::feather_window(r, area, feather); + let m = sel::feather(&sel::mask_from_surface(Some(&shape), window), window.width() as usize, window.height() as usize, feather); + doc.selection = selection_cmds::combine_band(doc.selection.as_ref(), &m, window, sel::SelectionMode::parse(&mode)); return Ok(()); } let old = doc.selection.take(); diff --git a/crates/engine/src/cmd/selection_cmds.rs b/crates/engine/src/cmd/selection_cmds.rs index 4b8da7e796..0c3881ca10 100644 --- a/crates/engine/src/cmd/selection_cmds.rs +++ b/crates/engine/src/cmd/selection_cmds.rs @@ -600,10 +600,26 @@ pub(crate) fn polygon_selection(s: &mut Session, cmd: &str, label: &str, pts: &[ } let area = s.active().ok_or(EngineError::NoDocument)?.doc.bounds(); if feather > 0.0 { - // The blur spreads past the polygon and isn't bit-identical over a smaller window. - let mut mask = sel::polygon(pts, area, b(p, "antiAlias", true)); - mask = sel::feather(&mask, area.width() as usize, area.height() as usize, feather); - return set_selection(s, label, area, mask, mode(p)); + let (mut lo, mut hi) = ((f32::INFINITY, f32::INFINITY), (f32::NEG_INFINITY, f32::NEG_INFINITY)); + for &(x, y) in pts { + if x.is_finite() && y.is_finite() { + lo = (lo.0.min(x), lo.1.min(y)); + hi = (hi.0.max(x), hi.1.max(y)); + } + } + let bounds = if lo.0 <= hi.0 && lo.1 <= hi.1 { + Rect::new(lo.0.floor() as i32, lo.1.floor() as i32, hi.0.ceil() as i32, hi.1.ceil() as i32) + } else { + Rect::EMPTY + }; + let window = feather_window(bounds, area, feather); + let mask = sel::polygon_window(pts, area, window, b(p, "antiAlias", true)); + let mask = sel::feather(&mask, window.width() as usize, window.height() as usize, feather); + let selected = s.edit(label, |doc, _| { + doc.selection = combine_band(doc.selection.as_ref(), &mask, window, mode(p)); + Ok(doc.selection.is_some()) + })?; + return Ok(json!({ "selected": selected })); } // Only the rows the polygon spans (#4532): rows outside it are empty, and full-width rows // keep `polygon`'s coverage bit-identical (its x arithmetic is relative to the area's left @@ -633,7 +649,7 @@ fn polygon_rows(pts: &[(f32, f32)], area: Rect) -> Rect { /// [`sel::combine`] of a mask covering only `band` (zero elsewhere), giving exactly what the /// whole-canvas combine gives: Replace and Intersect are empty outside the band, and Add and /// Subtract keep the old selection there. -fn combine_band(old: Option<&Surface>, mask: &[f32], band: Rect, m: SelectionMode) -> Option { +pub(crate) fn combine_band(old: Option<&Surface>, mask: &[f32], band: Rect, m: SelectionMode) -> Option { let inside = sel::combine(old, mask, band, m); let Some(old) = old.filter(|_| matches!(m, SelectionMode::Add | SelectionMode::Subtract)) else { return inside }; if band.is_empty() { @@ -646,6 +662,16 @@ fn combine_band(old: Option<&Surface>, mask: &[f32], band: Rect, m: SelectionMod (s.tile_count() > 0).then_some(s) } +/// Keep dense feather masks local to the drawn shape. Clip before inflating: pixels outside +/// the canvas never contribute to the original full-canvas blur, even near a canvas edge. +pub(crate) fn feather_window(bounds: Rect, canvas: Rect, feather: f32) -> Rect { + let bounds = bounds.intersect(&canvas); + if bounds.is_empty() { + return Rect::EMPTY; + } + bounds.inflate(((feather * 3.0).ceil() as i32).saturating_add(1)).intersect(&canvas) +} + macro_rules! spec { ($id:literal, $label:literal, [$($m:literal),*], $params:literal, $en:expr, $run:expr) => { CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: None, params: $params, enabled: $en, run: $run, journal: true } diff --git a/crates/engine/src/cmd/selection_cmds/tests.rs b/crates/engine/src/cmd/selection_cmds/tests.rs index 602262dc7f..0b28681172 100644 --- a/crates/engine/src/cmd/selection_cmds/tests.rs +++ b/crates/engine/src/cmd/selection_cmds/tests.rs @@ -725,3 +725,113 @@ fn lasso_over_its_rows_matches_the_whole_canvas() { assert_eq!(read(&got), read(&want), "case {case}: {m}, anti-alias {aa}, {pts:?}"); } } + +#[test] +fn feather_window_is_bounded_and_clipped_before_growing() { + let canvas = Rect::new(0, 0, 6000, 4000); + let window = feather_window(Rect::from_xywh(3000, 2000, 50, 50), canvas, 4.0); + assert_eq!(window, Rect::new(2987, 1987, 3063, 2063)); + assert_eq!(window.size().area(), 5776); + assert_eq!(feather_window(Rect::from_xywh(3000, 2000, 50, 50), canvas, 1000.0), canvas); + assert_eq!(feather_window(Rect::new(-5, -5, 10, 10), canvas, 2.5), Rect::new(0, 0, 19, 19)); + assert_eq!(feather_window(Rect::new(-20, -20, -1, -1), canvas, 20.0), Rect::EMPTY); + assert_eq!(feather_window(Rect::EMPTY, canvas, 1000.0), Rect::EMPTY); +} + +/// The stored coverage and history must match the previous full-canvas paths, including soft +/// old selections outside the working window and shapes clipped at every canvas edge. +#[test] +fn windowed_tool_feather_matches_full_canvas() { + let area = Rect::new(0, 0, 192, 160); + let shapes = [ + Rect::new(72, 61, 97, 89), + Rect::new(-12, -7, 24, 25), + Rect::new(177, 143, 210, 180), + Rect::new(-15, 65, -2, 80), + Rect::new(75, 65, 75, 80), + Rect::new(-5, -5, 200, 170), + ]; + for (case, r) in shapes.into_iter().enumerate() { + for tool in ["rect", "ellipse", "lasso"] { + for aa in [false, true] { + for radius in [0.05, 2.5, 7.0] { + let pts = [ + (r.x0 as f32 + 0.125, r.y0 as f32 + 0.375), + (r.x1 as f32, r.y0 as f32), + (r.x1 as f32 - 0.25, r.y1 as f32 + 0.125), + (r.x0 as f32, r.y1 as f32), + ]; + let input = if tool == "lasso" { + sel::polygon(&pts, area, aa) + } else { + let mut shape = Surface::new(photocraft_color::PixelFormat::GRAY8); + if tool == "ellipse" { + shape = sel::ellipse_surface(r, area, aa); + } else { + shape.fill_rect(r.intersect(&area), &[1.0]); + } + sel::mask_from_surface(Some(&shape), area) + }; + let mask = sel::feather(&input, area.width() as usize, area.height() as usize, radius); + for m in ["replace", "add", "subtract", "intersect"] { + for has_old in [false, true] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": area.width(), "height": area.height()})).unwrap(); + if has_old { + s.edit("soft selection", |doc, _| { + let mut old = Surface::new(photocraft_color::PixelFormat::GRAY8); + old.fill_rect(Rect::new(3, 4, 180, 150), &[0.6]); + old.fill_rect(Rect::new(70, 60, 90, 80), &[1.0]); + doc.selection = Some(old); + Ok(()) + }) + .unwrap(); + } + let before = s.active().unwrap().doc.selection.clone(); + let want = sel::combine(before.as_ref(), &mask, area, SelectionMode::parse(m)); + let steps = s.active().unwrap().history.past_len(); + let result = if tool == "lasso" { + s.execute("select.lasso", json!({"points": pts, "antiAlias": aa, "feather": radius, "mode": m})).unwrap() + } else { + s.execute("select.rect", json!({"x": r.x0, "y": r.y0, "width": r.width(), "height": r.height(), "ellipse": tool == "ellipse", "antiAlias": aa, "feather": radius, "mode": m})).unwrap() + }; + let got = s.active().unwrap().doc.selection.clone(); + let read = |v: &Option| sel::mask_from_surface(v.as_ref(), area); + assert_eq!(read(&got), read(&want), "case {case}, {tool}, aa={aa}, radius={radius}, mode={m}, old={has_old}"); + assert_eq!(got.is_some(), want.is_some()); + if tool == "lasso" { + assert_eq!(result["selected"], want.is_some()); + } + assert_eq!(s.active().unwrap().history.past_len(), steps + 1); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(read(&s.active().unwrap().doc.selection), read(&before)); + s.execute("edit.redo", json!({})).unwrap(); + assert_eq!(read(&s.active().unwrap().doc.selection), read(&want)); + } + } + } + } + } + } +} + +#[test] +fn small_feathered_tools_work_on_large_sparse_documents_at_every_depth() { + for depth in [8, 16, 32] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 6000, "height": 4000, "depth": depth, "background": "transparent"})).unwrap(); + for ellipse in [false, true] { + s.execute("select.rect", json!({"x": 3000, "y": 2000, "width": 50, "height": 50, "ellipse": ellipse, "feather": 4})).unwrap(); + let selection = s.active().unwrap().doc.selection.as_ref().unwrap(); + assert!(selection.tile_count() <= 4); + assert!(Rect::new(2987, 1987, 3063, 2063).contains_rect(&selection.content_bounds())); + assert!(coverage(&s, 3025, 2025) > 0.95); + assert!(coverage(&s, 3000, 2025) > 0.1 && coverage(&s, 3000, 2025) < 0.8); + } + s.execute("select.lasso", json!({"points": [[3000, 2000], [3050, 2000], [3050, 2050], [3000, 2050]], "feather": 4})).unwrap(); + let selection = s.active().unwrap().doc.selection.as_ref().unwrap(); + assert!(selection.tile_count() <= 4); + assert!(Rect::new(2987, 1987, 3063, 2063).contains_rect(&selection.content_bounds())); + assert!(coverage(&s, 3025, 2025) > 0.95); + } +}