PhotoCraft: An open-source, photo editor written by scratch in pure Rust
perf: Edit > Clear works tile by tile on large selections (#3463) (#3482)
Fabio Lussi40300964821c
diff --git a/crates/engine/src/fill_cmds.rs b/crates/engine/src/fill_cmds.rsindex 1c2048464..eab1fb165 100644--- a/crates/engine/src/fill_cmds.rs+++ b/crates/engine/src/fill_cmds.rs@@ -291,7 +291,7 @@ fn blend_into(surf: &mut Surface, area: Rect, source: &Source, sel: Option<&Surflet done = std::sync::Mutex::new(done);tiles.into_par_iter().try_for_each(|(tc, tile)| -> Result<()> {let tr = tc.rect().intersect(&area);- let mask = sel.map(|m| Mask { bytes: m.tile(tc).map_or(m.default_bytes(), |t| t.bytes()), fmt: m.format(), origin: tc.rect() });+ let mask = sel.map(|m| Mask::of(m, tc));if let Some(s) = &solid&& tr == tc.rect()&& mask.as_ref().is_none_or(|m| m.full(tr))@@ -315,21 +315,25 @@ fn blend_into(surf: &mut Surface, area: Rect, source: &Source, sel: Option<&Surf}/// The selection's coverage over one tile (its channel 0).-struct Mask<'a> {+pub(crate) struct Mask<'a> {bytes: &'a [u8],fmt: photocraft_color::PixelFormat,origin: Rect,}-impl Mask<'_> {- fn at(&self, x: i32, y: i32) -> f32 {+impl<'a> Mask<'a> {+ /// `sel` over the tile at `tc` (its default pixel where it has no tile there).+ pub(crate) fn of(sel: &'a Surface, tc: photocraft_geom::TileCoord) -> Self {+ Mask { bytes: sel.tile(tc).map_or(sel.default_bytes(), |t| t.bytes()), fmt: sel.format(), origin: tc.rect() }+ }+ pub(crate) fn at(&self, x: i32, y: i32) -> f32 {let bpp = self.fmt.bytes_per_pixel();// A default-pixel mask is one pixel long: every position reads it.let i = if self.bytes.len() == bpp { 0 } else { ((y - self.origin.y0) as usize * TILE_SIZE as usize + (x - self.origin.x0) as usize) * bpp };self.bytes.get(i..i + bpp).map_or(0.0, |px| photocraft_color::read_sample(px, self.fmt.sample, 0))}/// Fully selected over `r`?- fn full(&self, r: Rect) -> bool {+ pub(crate) fn full(&self, r: Rect) -> bool {(r.y0..r.y1).all(|y| (r.x0..r.x1).all(|x| self.at(x, y) >= 1.0))}}diff --git a/crates/engine/src/pixels.rs b/crates/engine/src/pixels.rsindex 76f3c6340..323d6ccda 100644--- a/crates/engine/src/pixels.rs+++ b/crates/engine/src/pixels.rs@@ -2,7 +2,7 @@use photocraft_compose::{Buffer, adjust};use photocraft_doc::{Adjustment, Document, Layer, LayerContent};-use photocraft_geom::Rect;+use photocraft_geom::{Rect, TILE_SIZE};use photocraft_raster::{Surface, to_rgba};/// Composite `layers` inside their visible composite bounds (effects included) and write the result directly into a@@ -130,73 +130,154 @@ fn adjusted(s: &Surface, r: Rect, adj: &Adjustment, selection: Option<&Surface>,}/// Fill (respecting selection coverage) with a straight RGBA colour.+/// Works tile by tile in parallel on the encoded pixels; a fully selected tile of an opaque fill+/// that may set alpha becomes one shared solid tile.pub(crate) fn try_fill_surface(s: &mut Surface, area: Rect, color: [f32; 4], selection: Option<&Surface>, lock_transparency: bool) -> crate::Result<()> {let fmt = s.format();- let n = fmt.channels();- let mut region = crate::allocation::read_region(s, area, "filling pixels")?;- fill_region(&mut region, fmt, n, area, color, selection, lock_transparency);- s.try_write_region(area, ®ion)- .map_err(|e| crate::EngineError::Other(format!("not enough memory while writing filled pixels ({e}); the document was not changed")))-}--fn fill_region(- region: &mut [f32],- fmt: photocraft_color::PixelFormat,- n: usize,- area: Rect,- color: [f32; 4],- selection: Option<&Surface>,- lock_transparency: bool,-) {- let w = area.width() as usize;- for (i, px) in region.chunks_exact_mut(n).enumerate() {- let x = area.x0 + (i % w) as i32;- let y = area.y0 + (i / w) as i32;- let k = selection.map_or(1.0, |sel| sel.sample_channel(x, y, 0));+ // Coverage 1 of an opaque colour replaces the colour (and the alpha, unless it is kept).+ let opaque = color[3] == 1.0 && (!lock_transparency || !fmt.alpha) && selection.is_none_or(|m| m.format().sample != photocraft_color::SampleType::F32);+ let solid = opaque.then(|| {+ let mut enc = [0.0f32; 8];+ let n = photocraft_raster::from_rgba_into(&fmt, [color[0], color[1], color[2], 1.0], &mut enc);+ s.solid_tile(enc.get(..n).unwrap_or(&[]))+ });+ let whole = |full: bool| solid.as_ref().filter(|_| full).map(|t| TileEdit::Put(t.clone()));+ edit_tiles(s, area, selection, "filling pixels", whole, |k, px| {if k <= 0.0 {- continue;+ return false;}- let d = to_rgba(&fmt, px);- let sa = color[3] * k;- let oa = sa + d[3] * (1.0 - sa);- let mut o = [0.0f32; 4];- if oa > 0.0 {- for c in 0..3 {- o[c] = (color[c] * sa + d[c] * d[3] * (1.0 - sa)) / oa;- }+ fill_pixel(&fmt, px, color, k, lock_transparency);+ true+ })+}++/// One pixel of [`try_fill_surface`]: `color` over `px` (encoded) at coverage `k`.+fn fill_pixel(fmt: &photocraft_color::PixelFormat, px: &mut [f32], color: [f32; 4], k: f32, lock_transparency: bool) {+ let d = to_rgba(fmt, px);+ let sa = color[3] * k;+ let oa = sa + d[3] * (1.0 - sa);+ let mut o = [0.0f32; 4];+ if oa > 0.0 {+ for c in 0..3 {+ o[c] = (color[c] * sa + d[c] * d[3] * (1.0 - sa)) / oa;}- o[3] = if lock_transparency { d[3] } else { oa };- let mut enc = [0.0f32; 8];- photocraft_raster::from_rgba_into(&fmt, o, &mut enc);- px.copy_from_slice(&enc[..n]);+ }+ o[3] = if lock_transparency { d[3] } else { oa };+ let mut enc = [0.0f32; 8];+ let m = photocraft_raster::from_rgba_into(fmt, o, &mut enc);+ let n = px.len().min(m);+ if let (Some(dst), Some(src)) = (px.get_mut(..n), enc.get(..n)) {+ dst.copy_from_slice(src);}}/// Clear pixels (make transparent) within the selection.+/// Works tile by tile in parallel on the encoded pixels; a fully selected tile is dropped (it+/// would only hold empty pixels), and tiles the selection leaves alone stay shared with history.pub(crate) fn try_clear_surface(s: &mut Surface, area: Rect, selection: Option<&Surface>) -> crate::Result<()> {let fmt = s.format();let n = fmt.channels();if !fmt.alpha {return Ok(());}- let mut region = crate::allocation::read_region(s, area, "erasing pixels")?;- clear_region(&mut region, n, area, selection);- s.try_write_region(area, ®ion)- .map_err(|e| crate::EngineError::Other(format!("not enough memory while erasing pixels ({e}); the document was not changed")))?;+ // Cleared pixels become all zeros; when that is also the default pixel, a cleared tile is no tile.+ let empty_default = s.default_bytes().iter().all(|&b| b == 0);+ let whole = |full: bool| (full && empty_default).then_some(TileEdit::Drop);+ edit_tiles(s, area, selection, "erasing pixels", whole, |k, px| {+ let Some(a) = px.get_mut(n - 1) else { return false };+ *a *= 1.0 - k;+ // Fully cleared pixels become the empty pixel, so bounds and tile pruning see them as gone.+ if *a <= 0.0 {+ px.fill(0.0);+ }+ true+ })?;s.prune();Ok(())}-fn clear_region(region: &mut [f32], n: usize, area: Rect, selection: Option<&Surface>) {- let w = area.width() as usize;- for (i, px) in region.chunks_exact_mut(n).enumerate() {- let k = selection.map_or(1.0, |sel| sel.sample_channel(area.x0 + (i % w) as i32, area.y0 + (i / w) as i32, 0));- px[n - 1] *= 1.0 - k;- // Fully cleared pixels become the empty pixel, so bounds and tile pruning see them as gone.- if px[n - 1] <= 0.0 {- px.fill(0.0);+/// A whole-tile shortcut of [`edit_tiles`].+enum TileEdit {+ /// Replace the tile with this (shared) one.+ Put(std::sync::Arc<photocraft_raster::Tile>),+ /// Remove the tile (it reads as the default pixel again).+ Drop,+}++/// Edit `s` over `area` tile by tile in parallel. `whole` may handle a tile lying wholly inside+/// `area` and fully selected (`true`) in one go; otherwise `pixel` edits each pixel of the area+/// with its selection coverage (decoded channel values in and out; `false` = left untouched).+/// A tile is copied only when one of its pixels actually changes (tiles are shared with undo+/// states), and pixels are decoded and re-encoded exactly as a whole-region float round trip+/// would, so the result is the same as one pass over `area`.+fn edit_tiles(+ s: &mut Surface,+ area: Rect,+ selection: Option<&Surface>,+ purpose: &str,+ whole: impl Fn(bool) -> Option<TileEdit> + Sync,+ pixel: impl Fn(f32, &mut [f32]) -> bool + Sync,+) -> crate::Result<()> {+ use photocraft_raster::Tile;+ use rayon::prelude::*;+ use std::sync::Arc;+ let fmt = s.format();+ let (n, bpp) = (fmt.channels(), fmt.bytes_per_pixel());+ let oom = |e| crate::EngineError::Other(format!("not enough memory while {purpose} ({e}); the document was not changed"));+ let mut coords = crate::allocation::capacity(area.tiles().count(), purpose)?;+ coords.extend(area.tiles());+ // Untouched pixels read as the default where the surface has no tile.+ let blank = if coords.iter().any(|&tc| s.tile(tc).is_none()) { Some(s.try_default_tile().map_err(oom)?) } else { None };+ let surf = &*s;+ let edits = coords+ .into_par_iter()+ .map(|tc| -> crate::Result<Option<(photocraft_geom::TileCoord, Option<Arc<Tile>>)>> {+ let tr = tc.rect().intersect(&area);+ let mask = selection.map(|m| crate::fill_cmds::Mask::of(m, tc));+ let full = tr == tc.rect() && mask.as_ref().is_none_or(|m| m.full(tr));+ let current = surf.tile(tc);+ match whole(full) {+ Some(TileEdit::Put(t)) => return Ok(Some((tc, Some(t)))),+ Some(TileEdit::Drop) => return Ok(current.map(|_| (tc, None))),+ None => {}+ }+ let Some(src) = current.map(|t| &**t).or(blank.as_ref()) else { return Ok(None) };+ let mut out: Option<Tile> = None;+ let (mut px, mut enc) = ([0.0f32; 8], [0u8; 32]);+ let (Some(px), Some(enc)) = (px.get_mut(..n), enc.get_mut(..bpp)) else { return Ok(None) };+ for y in tr.y0..tr.y1 {+ let row = (y - tc.ty * TILE_SIZE) as usize * TILE_SIZE as usize;+ for x in tr.x0..tr.x1 {+ let i = (row + (x - tc.tx * TILE_SIZE) as usize) * bpp;+ let Some(old) = src.bytes().get(i..i + bpp) else { continue };+ for (c, v) in px.iter_mut().enumerate() {+ *v = photocraft_color::read_sample(old, fmt.sample, c);+ }+ if !pixel(mask.as_ref().map_or(1.0, |m| m.at(x, y)), px) {+ continue;+ }+ photocraft_raster::encode_pixel(&fmt, px, enc);+ if enc == old {+ continue;+ }+ if out.is_none() {+ out = Some(src.try_clone().map_err(oom)?);+ }+ if let Some(dst) = out.as_mut().and_then(|t| t.bytes_mut().get_mut(i..i + bpp)) {+ dst.copy_from_slice(enc);+ }+ }+ }+ Ok(out.map(|t| (tc, Some(Arc::new(t)))))+ })+ .collect::<crate::Result<Vec<_>>>()?;+ for (tc, tile) in edits.into_iter().flatten() {+ match tile {+ Some(t) => s.put_tiles([(tc, t)]),+ None => drop(s.take_tiles(tc.rect())),}}+ Ok(())}/// Remap a surface through a pixel-coordinate mapping (used for flips/rotations).diff --git a/crates/engine/src/pixels_tests.rs b/crates/engine/src/pixels_tests.rsindex c7ee89960..0da488010 100644--- a/crates/engine/src/pixels_tests.rs+++ b/crates/engine/src/pixels_tests.rs@@ -124,3 +124,120 @@ fn an_empty_layer_is_left_alone() {adjust_surface(&mut s, &Adjustment::Invert, None, ColorMode::Rgb);assert_eq!(s.tile_count(), 0);}++/// The whole-region float pass that the tiled Clear and background Fill replaced (#3463).+fn reference_fill_or_clear(s: &Surface, area: Rect, selection: Option<&Surface>, fill: Option<([f32; 4], bool)>) -> Surface {+ let mut s = s.clone();+ let fmt = s.format();+ let n = fmt.channels();+ if fill.is_none() && !fmt.alpha {+ return s;+ }+ let w = area.width() as usize;+ let mut region = s.read_region(area);+ for (i, px) in region.chunks_exact_mut(n).enumerate() {+ let k = selection.map_or(1.0, |sel| sel.sample_channel(area.x0 + (i % w) as i32, area.y0 + (i / w) as i32, 0));+ match fill {+ Some((color, lock)) => {+ if k > 0.0 {+ fill_pixel(&fmt, px, color, k, lock);+ }+ }+ None => {+ px[n - 1] *= 1.0 - k;+ if px[n - 1] <= 0.0 {+ px.fill(0.0);+ }+ }+ }+ }+ s.write_region(area, ®ion);+ s+}++/// [`layer`] plus a fully painted tile and a transparent pixel that still carries a colour.+fn clear_layer(fmt: PixelFormat) -> Surface {+ let mut s = layer(fmt);+ s.fill_rect(Rect::new(0, 0, 256, 256), &from_rgba(&fmt, [0.2, 0.7, 0.4, if fmt.alpha { 0.8 } else { 1.0 }]));+ s.write_pixel(260, 250, &from_rgba(&fmt, [0.9, 0.1, 0.1, 0.0]));+ s+}++fn same_pixels(a: &Surface, b: &Surface) -> bool {+ let r = Rect::new(-10, -10, 800, 800);+ a.read_region(r) == b.read_region(r)+}++#[test]+fn tiled_clear_and_fill_match_one_pass_over_the_area() {+ let mut formats = Vec::new();+ for mode in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab, ColorMode::Grayscale] {+ for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {+ formats.push(PixelFormat { mode, sample, alpha: true });+ }+ }+ formats.push(PixelFormat { mode: ColorMode::Rgb, sample: SampleType::U8, alpha: false });+ formats.push(PixelFormat { mode: ColorMode::Cmyk, sample: SampleType::U16, alpha: false });+ // A soft (feathered) selection: fully selected over the first tile, fading out across the next.+ let mut soft = Surface::new(PixelFormat::GRAY8);+ let sr = Rect::new(0, 0, 600, 400);+ soft.write_region(sr, &(0..sr.height()).flat_map(|_| (0..sr.width()).map(|x| (1.0 - (x as f32 - 256.0).max(0.0) / 300.0).max(0.0))).collect::<Vec<_>>());+ let canvas = Rect::new(0, 0, 700, 600);+ for fmt in formats {+ let s = clear_layer(fmt);+ for sel in [None, Some(&soft)] {+ let area = sel.map_or(canvas, |m| m.content_bounds());+ let what = format!("{fmt:?} selection {}", sel.is_some());+ let mut got = s.clone();+ try_clear_surface(&mut got, area, sel).unwrap();+ assert!(same_pixels(&got, &reference_fill_or_clear(&s, area, sel, None)), "clear {what}");+ if fmt.alpha {+ assert!(!same_pixels(&got, &s), "clear {what} changes the layer");+ }+ for color in [[1.0, 1.0, 1.0, 1.0], [0.3, 0.5, 0.9, 1.0], [0.3, 0.5, 0.9, 0.4]] {+ for lock in [true, false] {+ let mut got = s.clone();+ try_fill_surface(&mut got, area, color, sel, lock).unwrap();+ assert!(same_pixels(&got, &reference_fill_or_clear(&s, area, sel, Some((color, lock)))), "fill {color:?} lock {lock} {what}");+ }+ }+ }+ }+}++#[test]+fn clear_leaves_unselected_tiles_shared_and_drops_cleared_ones() {+ let s = clear_layer(PixelFormat::RGBA8);+ let mut sel = Surface::new(PixelFormat::GRAY8);+ // Fully selects tile (0, 0) and part of (1, 0); the selection's bounds reach tile (2, 1),+ // whose pixels it leaves alone.+ sel.fill_rect(Rect::new(0, 0, 280, 256), &[1.0]);+ sel.write_pixel(600, 300, &[0.0]);+ sel.write_pixel(601, 301, &[0.5]);+ let mut got = s.clone();+ try_clear_surface(&mut got, Rect::new(0, 0, 602, 302), Some(&sel)).unwrap();+ let tile = |s: &Surface, tx, ty| s.tile(photocraft_geom::TileCoord::new(tx, ty)).cloned();+ assert!(tile(&got, 0, 0).is_none(), "a fully cleared tile is no tile");+ let (a, b) = (tile(&s, 2, 1).unwrap(), tile(&got, 2, 1).unwrap());+ assert!(std::sync::Arc::ptr_eq(&a, &b), "a tile the selection leaves alone is not copied");+ assert!(!std::sync::Arc::ptr_eq(&tile(&s, 1, 0).unwrap(), &tile(&got, 1, 0).unwrap()), "a partly cleared tile is copied");+}++/// Release-only timing for Edit › Clear on a 48 MP layer (#3463): about 2 s with the old+/// whole-region float pass, tens of milliseconds tiled.+#[test]+#[ignore = "benchmark; run with --release -- --ignored --nocapture"]+fn benchmark_clear_large_selection() {+ for (background, feather) in [(false, 0), (false, 200), (true, 0), (true, 200)] {+ let mut s = crate::Session::new();+ s.execute("file.new", json!({"width": 8000, "height": 6000, "background": "white"})).unwrap();+ if !background {+ s.execute("layer.new.layer", json!({})).unwrap();+ s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();+ }+ s.execute("select.rect", json!({"x": 10, "y": 10, "width": 7980, "height": 5980, "ellipse": feather > 0, "feather": feather})).unwrap();+ let t = Instant::now();+ s.execute("edit.clear", json!({})).unwrap();+ println!("#3463 clear 8000x6000, background {background}, feather {feather}: {:?}", t.elapsed());+ }+}diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rsindex 3315f0bff..c80dce82c 100644--- a/crates/raster/src/lib.rs+++ b/crates/raster/src/lib.rs@@ -594,6 +594,11 @@ impl Surface {}}+ /// A tile filled with the default pixel (what a missing tile reads as), allocated fallibly.+ pub fn try_default_tile(&self) -> Result<Tile, AllocationError> {+ Tile::try_filled(&self.format, &self.default_pixel)+ }+/// A tile of this surface's format filled with `px` (normalised channel values). Sharing one/// across many coordinates fills them without copying (tiles are copy-on-write).pub fn solid_tile(&self, px: &[f32]) -> Arc<Tile> {