PhotoCraft: An open-source, photo editor written by scratch in pure Rust
perf(ui): bound carried selection outlines and stabilize clipping (#5699)
Sir Clangington III.914d51f9bbd0
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 7a9592b69..7e2e66ff4 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -3083,8 +3083,11 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:(px(y1.ceil()).div_euclid(q) + 2) * q,)};+ let bounds_key = if k > 1 { u64::MAX / 2 - doc.id.0 } else { u64::MAX - doc.id.0 };+ let carried_bounds = carried.then(|| app.cached_bounds(bounds_key, sel).intersect(&vis));+ let step = carried_bounds.map_or(step, |b| crate::outline::bounded_step(b, step));let key = crate::surface_fingerprint(sel)- ^ (step as u64) << 56+ ^ u64::from(step).rotate_left(56)^ doc.id.0.rotate_left(17)^ (vis.x0 as u64) << 8^ (vis.y0 as u64) << 24@@ -3094,8 +3097,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:let fresh = matches!(&app.outline_cache, Some((d, k, _)) if *d == doc.id && *k == key);if !fresh {let t0 = crate::gpu_canvas::now_ms();- let bounds_key = if k > 1 { u64::MAX / 2 - doc.id.0 } else { u64::MAX - doc.id.0 };- let b = app.cached_bounds(bounds_key, sel).intersect(&vis);+ let b = carried_bounds.unwrap_or_else(|| app.cached_bounds(bounds_key, sel).intersect(&vis));// Filters can occupy every worker in Rayon's global pool. A parallel scan here would// block the UI thread waiting for those workers, preventing job cancellation (#1554).let mut segs =@@ -4153,9 +4155,12 @@ pub(crate) fn marching_ants_mapped(painter: &egui::Painter, segs: &[crate::outli/// The part of the line `a`–`b` inside `r` (Liang–Barsky), if any.fn clip_line(r: Rect, a: Pos2, b: Pos2) -> Option<(Pos2, Pos2)> {- let d = b - a;- let (mut t0, mut t1) = (0.0f32, 1.0f32);- for (p, q) in [(-d.x, a.x - r.min.x), (d.x, r.max.x - a.x), (-d.y, a.y - r.min.y), (d.y, r.max.y - a.y)] {+ // Perspective can put endpoints billions of pixels away. f32 subtraction/interpolation+ // loses viewport-sized differences there, clipping visible ants to the wrong endpoints.+ let (ax, ay) = (f64::from(a.x), f64::from(a.y));+ let (dx, dy) = (f64::from(b.x) - ax, f64::from(b.y) - ay);+ let (mut t0, mut t1) = (0.0f64, 1.0f64);+ for (p, q) in [(-dx, ax - f64::from(r.min.x)), (dx, f64::from(r.max.x) - ax), (-dy, ay - f64::from(r.min.y)), (dy, f64::from(r.max.y) - ay)] {if p == 0.0 {if q < 0.0 {return None;@@ -4166,7 +4171,27 @@ fn clip_line(r: Rect, a: Pos2, b: Pos2) -> Option<(Pos2, Pos2)> {t1 = t1.min(q / p);}}- (t0 <= t1).then(|| (a + d * t0, a + d * t1))+ let at = |t: f64| pos2((ax + dx * t) as f32, (ay + dy * t) as f32);+ (t0 <= t1).then(|| (at(t0), at(t1)))+}++#[cfg(test)]+mod transform_outline_clip_tests {+ use super::*;++ #[test]+ fn near_horizon_lines_keep_viewport_precision() {+ let r = Rect::from_min_max(pos2(0.0, 0.0), pos2(800.0, 600.0));+ for (a, b, start, end) in [+ (pos2(-1e9, 100.0), pos2(1e9, 100.0), pos2(0.0, 100.0), pos2(800.0, 100.0)),+ (pos2(100.0, -1e9), pos2(100.0, 1e9), pos2(100.0, 0.0), pos2(100.0, 600.0)),+ (pos2(-1e9, -1e9), pos2(1e9, 1e9), pos2(0.0, 0.0), pos2(600.0, 600.0)),+ ] {+ let (x, y) = clip_line(r, a, b).unwrap();+ assert!(x.distance(start) < 0.01 && y.distance(end) < 0.01, "{x:?}–{y:?}, expected {start:?}–{end:?}");+ }+ assert!(clip_line(r, pos2(-1e9, -100.0), pos2(1e9, -100.0)).is_none());+ }}/// Marching ants along lines already placed on screen (a warped outline is a run of short ones).diff --git a/crates/ui-egui/src/outline.rs b/crates/ui-egui/src/outline.rsindex bdb5c4150..9e06a1ae6 100644--- a/crates/ui-egui/src/outline.rs+++ b/crates/ui-egui/src/outline.rs@@ -10,6 +10,21 @@ use photocraft_raster::Surface;/// A boundary segment in document pixel coordinates (axis-aligned).pub type Segment = ([i32; 2], [i32; 2]);+/// Bound a whole-selection trace, including offscreen pixels carried into view by a transform.+/// Include grid alignment and the two padding cells in the budget; ordinary traces keep their step.+pub(crate) fn bounded_step(bounds: Rect, mut step: u32) -> u32 {+ step = step.max(1);+ let cells = |step: u32| {+ let s = i64::from(step);+ let axis = |lo: i32, hi: i32| ((i64::from(hi) + s - 1).div_euclid(s) - i64::from(lo).div_euclid(s) + 2).max(0) as u64;+ axis(bounds.x0, bounds.x1).saturating_mul(axis(bounds.y0, bounds.y1))+ };+ while cells(step) > 1_048_576 {+ step = step.saturating_mul(2);+ }+ step+}+/// Extract the boundary of `mask` (> 0.5 = selected) as merged horizontal and vertical segments.pub fn outline(mask: &Surface, bounds: Rect) -> Vec<Segment> {outline_scaled(mask, bounds, 1)@@ -40,15 +55,22 @@ fn outline_scaled_impl(mask: &Surface, bounds: Rect, step: u32, parallel: bool)let mut grid = vec![false; w * h];let half = step / 2;let sample_row = |gy: usize, row: &mut [bool]| {- let y = (gy0 + gy as i32) * step + half;- if y < bounds.y0 || y >= bounds.y1 {+ let y0 = (gy0 + gy as i32) * step;+ if y0 >= bounds.y1 || y0 + step <= bounds.y0 {return;}+ // A coarse cell can overlap a one-pixel-wide selection even when its centre misses it.+ // Sample the overlapping edge; padding cells still stay outside the mask.+ let y = (y0 + half).clamp(bounds.y0, bounds.y1 - 1);let mut vals = vec![0.0f32; row.len()];mask.sample_row_strided(y, gx0 * step + half, step, 0, &mut vals);for (gx, (cell, v)) in row.iter_mut().zip(vals).enumerate() {let x = (gx0 + gx as i32) * step + half;- *cell = x >= bounds.x0 && x < bounds.x1 && v > 0.5;+ *cell = if x >= bounds.x0 && x < bounds.x1 {+ v > 0.5+ } else {+ x - half < bounds.x1 && x - half + step > bounds.x0 && mask.sample_channel(x.clamp(bounds.x0, bounds.x1 - 1), y, 0) > 0.5+ };}};#[cfg(not(target_arch = "wasm32"))]@@ -108,6 +130,33 @@ mod tests {use super::*;use photocraft_color::PixelFormat;+ #[test]+ fn whole_transform_trace_has_a_bounded_grid() {+ assert_eq!(bounded_step(Rect::new(0, 0, 200, 150), 1), 1);+ assert_eq!(bounded_step(Rect::new(0, 0, 6000, 6000), 1), 8);+ for bounds in [Rect::new(-50_001, -50_003, 50_000, 50_000), Rect::new(-1_000_000, 0, 1_000_000, 1)] {+ let step = i64::from(bounded_step(bounds, 1));+ let w = (i64::from(bounds.x1) + step - 1).div_euclid(step) - i64::from(bounds.x0).div_euclid(step) + 2;+ let h = (i64::from(bounds.y1) + step - 1).div_euclid(step) - i64::from(bounds.y0).div_euclid(step) + 2;+ assert!(w * h <= 1_048_576, "{bounds:?}: {w} × {h}");+ }+ // Both distant pieces survive the coarse trace: it covers the whole selection, not the viewport.+ let mut mask = Surface::new(PixelFormat::GRAY8);+ mask.fill_rect(Rect::new(-50_000, -50_000, -49_488, -49_488), &[1.0]);+ mask.fill_rect(Rect::new(49_488, 49_488, 50_000, 50_000), &[1.0]);+ let bounds = mask.content_bounds();+ let lines = outline_scaled_serial(&mask, bounds, bounded_step(bounds, 1));+ assert!(lines.iter().any(|(a, _)| a[0] < -49_000));+ assert!(lines.iter().any(|(a, _)| a[0] > 49_000));+ let mut thin = Surface::new(PixelFormat::GRAY8);+ thin.fill_rect(Rect::new(-1_000_000, 0, -999_488, 1), &[1.0]);+ thin.fill_rect(Rect::new(999_488, 0, 1_000_000, 1), &[1.0]);+ let bounds = thin.content_bounds();+ let lines = outline_scaled_serial(&thin, bounds, bounded_step(bounds, 1));+ assert!(lines.iter().any(|(a, _)| a[0] < -999_000), "thin left piece remains visible");+ assert!(lines.iter().any(|(a, _)| a[0] > 999_000), "thin right piece remains visible");+ }+#[test]fn rectangle_has_four_edges() {let mut m = Surface::new(PixelFormat::GRAY8);