PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Brush: symmetric live strokes update only what changed (#3593) (#3605)
xsvm6d21a69968aa
diff --git a/crates/engine/src/brush_cmds.rs b/crates/engine/src/brush_cmds.rsindex 2167cb1a0..dd5c46608 100644--- a/crates/engine/src/brush_cmds.rs+++ b/crates/engine/src/brush_cmds.rs@@ -415,8 +415,9 @@ pub struct LiveStroke {symmetry: Option<crate::symmetry_cmds::PaintingSymmetry>,mirrors: Vec<StrokeRenderer>,mirror_distinct: Vec<bool>,- /// Restore passes separately; their union may span an otherwise untouched document.- symmetry_regions: Vec<Rect>,+ /// What the symmetric preview drew last, once a mirror differs from the stroke, and how many+ /// passes it merged (a mirror joining redraws every tile).+ union_live: Option<(photocraft_paint::UnionLive, usize)>,pre: Surface,sel: Option<Surface>,lock: bool,@@ -508,7 +509,7 @@ impl LiveStroke {symmetry,mirrors,mirror_distinct,- symmetry_regions: Vec::new(),+ union_live: None,pre,sel,lock,@@ -567,33 +568,27 @@ impl LiveStroke {}let (surf, _) = crate::channel_cmds::target_surface(std::sync::Arc::make_mut(&mut self.doc), self.layer, &self.params)?;if self.mirror_distinct.iter().any(|d| *d) {- // Merge every finished pass once, both here and on commit, including shared axes.+ // The stroke and its distinct mirrors composite as one stroke, as the commit+ // merges them; only the tiles that changed are redrawn.let old = self.tail;- let mut original_preview = self.renderer.clone();- original_preview.finish();- let copies: Vec<_> = self- .mirrors- .iter()- .zip(&self.mirror_distinct)- .filter(|(_, d)| **d)- .map(|(r, _)| {- let mut r = r.clone();- r.finish();- r- })+ let passes = 1 + self.mirror_distinct.iter().filter(|d| **d).count();+ let (mut live, full, mut dmg) = match self.union_live.take() {+ Some((live, merged)) => (live, merged != passes, Rect::EMPTY),+ None => {+ // Leaving the single-pass preview: take its smoothing tail back first.+ if !old.is_empty() {+ surf.write_region(old, &self.pre.read_region(old));+ }+ (photocraft_paint::UnionLive::default(), true, old)+ }+ };+ let mut renderers: Vec<&mut StrokeRenderer> = std::iter::once(&mut self.renderer)+ .chain(self.mirrors.iter_mut().zip(&self.mirror_distinct).filter(|(_, d)| **d).map(|(r, _)| r)).collect();- let bounds = copies.iter().fold(original_preview.bounds().union(&old), |b, r| b.union(&r.bounds()));- if self.symmetry_regions.is_empty() && !old.is_empty() {- surf.write_region(old, &self.pre.read_region(old));- }- for region in &self.symmetry_regions {- surf.write_region(*region, &self.pre.read_region(*region));- }- self.symmetry_regions =- std::iter::once(original_preview.bounds()).chain(copies.iter().map(StrokeRenderer::bounds)).filter(|r| !r.is_empty()).collect();- let damage = original_preview.composite_union_many(&copies, &self.pre, surf, self.sel.as_ref(), self.lock);- self.tail = bounds;- return Ok(damage.union(&bounds));+ dmg = dmg.union(&StrokeRenderer::composite_union_live(&mut renderers, &mut live, full, &self.pre, surf, self.sel.as_ref(), self.lock));+ self.tail = old.union(&live.bounds());+ self.union_live = Some((live, passes));+ return Ok(dmg);}let mut dmg = Rect::EMPTY;let old = std::mem::replace(&mut self.tail, Rect::EMPTY);diff --git a/crates/paint/src/brush_tests.rs b/crates/paint/src/brush_tests.rsindex 61772e4ea..a68f84f1f 100644--- a/crates/paint/src/brush_tests.rs+++ b/crates/paint/src/brush_tests.rs@@ -857,6 +857,91 @@ fn tail_preview_shows_the_stroke_as_finishing_it_would() {assert!(r.tail_preview().is_none());}+#[test]+fn live_union_of_passes_matches_merging_the_finished_passes_after_every_chunk() {+ // Symmetric painting previews the stroke and its mirrors with `composite_union_live`, which+ // redraws only changed tiles; after every chunk the target must be exactly what finishing+ // every pass and merging them with `composite_union_many` gives (the commit takes these pixels).+ let base = BrushSettings { size: 14.0, hardness: 0.6, opacity: 0.6, ..brush() };+ let mut brushes = vec![base.clone()];+ brushes.push(BrushSettings { smoothing: Smoothing { amount: 0.7, ..Default::default() }, ..base.clone() });+ let mut b = base.clone();+ b.dual_brush.enabled = true;+ b.dual_brush.size = 6.0;+ b.dual_brush.scatter = 1.5;+ brushes.push(b);+ let mut b = base.clone();+ b.color_dynamics.enabled = true;+ b.color_dynamics.hue_jitter = 0.5;+ brushes.push(b);+ brushes.push(BrushSettings { wet_edges: true, ..base.clone() });+ brushes.push(BrushSettings { mode: BlendMode::Dissolve, ..base.clone() });+ brushes.push(BrushSettings { erase: true, ..base.clone() });+ let mut b = base.clone();+ b.texture.enabled = true;+ b.texture.each_tip = false;+ brushes.push(b);+ let stroke: Vec<StrokePoint> = (0..40).map(|i| StrokePoint::new(30.0 + i as f64 * 3.7, 40.0 + 25.0 * (i as f64 / 5.0).sin(), 1.0)).collect();+ // Mirrors about x = 100 and y = 75; the first point sits near the vertical axis so passes overlap.+ let mirror = |fx: bool, fy: bool| -> Vec<StrokePoint> {+ stroke.iter().map(|p| StrokePoint::new(if fx { 200.0 - p.x } else { p.x }, if fy { 150.0 - p.y } else { p.y }, p.pressure)).collect()+ };+ let paths = [stroke.clone(), mirror(true, false), mirror(false, true), mirror(true, true)];+ let area = Rect::new(-20, -20, 240, 190);+ let mut sel = Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false));+ let sel_rect = Rect::new(0, 0, 160, 120);+ sel.write_region(sel_rect, &(0..160 * 120).map(|i| ((i % 160) as f32 / 120.0).min(1.0)).collect::<Vec<_>>());+ for sample in [SampleType::U8, SampleType::U16, SampleType::F32] {+ let fmt = PixelFormat::new(ColorMode::Rgb, sample, true);+ let mut pre = Surface::new(fmt);+ let fill = Rect::new(10, 10, 190, 140);+ let n = fmt.channels();+ let px: Vec<f32> =+ (0..fill.width() * fill.height()).flat_map(|i| [(i % 7) as f32 / 7.0, 0.5, (i % 13) as f32 / 13.0, 0.8].into_iter().take(n)).collect();+ pre.write_region(fill, &px);+ for (bi, b) in brushes.iter().enumerate() {+ // (passes included at each chunk, selection): two passes from the start; four, of+ // which two join part-way.+ for (four, selection) in [(false, None), (true, None), (true, Some(&sel))] {+ let mut renderers: Vec<StrokeRenderer> = (0..4).map(|_| StrokeRenderer::new(b, Some(fmt), 1.0)).collect();+ let mut live = crate::render::UnionLive::default();+ let mut target = pre.clone();+ let (mut at, mut chunk, mut merged) = (0, 1, 0);+ while at < stroke.len() {+ let end = (at + chunk).min(stroke.len());+ for (r, path) in renderers.iter_mut().zip(&paths) {+ r.push(&path[at..end]);+ }+ let count = if four && at >= 12 { 4 } else { 2 };+ let full = merged != count;+ merged = count;+ let mut passes: Vec<&mut StrokeRenderer> = renderers.iter_mut().take(count).collect();+ StrokeRenderer::composite_union_live(&mut passes, &mut live, full, &pre, &mut target, selection, false);+ let finished: Vec<StrokeRenderer> = renderers+ .iter()+ .take(count)+ .map(|r| {+ let mut r = r.clone();+ r.finish();+ r+ })+ .collect();+ let mut expected = pre.clone();+ finished[0].composite_union_many(&finished[1..], &pre, &mut expected, selection, false);+ assert!(+ target.read_region(area) == expected.read_region(area),+ "{sample:?}, brush {bi}, four {four}, selection {}, points ..{end}",+ selection.is_some()+ );+ assert_eq!(live.bounds(), finished.iter().fold(Rect::EMPTY, |r, f| r.union(&f.bounds())));+ at = end;+ chunk = chunk % 3 + 1;+ }+ }+ }+ }+}+// ---------- Tilt Scale, Brush Projection, speed spacing, locks, mixer transfer ----------/// Coverage extent (pixels above half coverage) of a rasterised dab along x and y through its centre.diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rsindex 74e4389f1..c5d065249 100644--- a/crates/paint/src/lib.rs+++ b/crates/paint/src/lib.rs@@ -37,7 +37,7 @@ pub use brush::{SectionLocks, ShapeDynamics, Smoothing, Texture, TipShape, Transfer,};pub use mixer::MixerSettings;-pub use render::{BrushContext, StrokeRenderer, grid_center, grid_square, render_stroke};+pub use render::{BrushContext, StrokeRenderer, UnionLive, grid_center, grid_square, render_stroke};pub use tile::{GrayTile, StoredTile};/// One input sample. Missing stylus data defaults to "mouse": full pressure, no tilt/rotation.diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rsindex aa6bd0b96..a92b75fbd 100644--- a/crates/paint/src/render.rs+++ b/crates/paint/src/render.rs@@ -491,6 +491,13 @@ impl CoverageMap {v}+ /// The finished coverage over the tiles `keys`: `tail`'s copy of a tile where finishing the+ /// stroke changes it (see [`StrokeRenderer::tail_preview`]), else this map's own.+ fn finished_subset(&self, tail: Option<&Self>, keys: &HashSet<(i32, i32)>) -> Self {+ let tile = |k: &(i32, i32)| tail.and_then(|t| t.tiles.get(k)).or_else(|| self.tiles.get(k)).map(|t| (*k, t.clone()));+ Self { tiles: keys.iter().filter_map(tile).collect(), nc: self.nc, bounds: tail.map_or(self.bounds, |t| t.bounds), dirty: HashSet::new() }+ }+/// Union two passes of the same brush stroke without applying opacity twice where they/// overlap. The stronger coverage wins, including its per-dab colour when present.fn union_max(&mut self, other: &Self) {@@ -527,6 +534,21 @@ impl CoverageMap {// Stroke renderer// ---------------------------------------------------------------------------+/// What [`StrokeRenderer::composite_union_live`] drew last: the coverage tiles of the passes'+/// smoothing tails (redrawn without them next time) and the merged bounds.+#[derive(Clone, Debug, Default)]+pub struct UnionLive {+ tail_keys: HashSet<(i32, i32)>,+ bounds: Rect,+}++impl UnionLive {+ /// The merged bounds of the finished passes, as last drawn.+ pub fn bounds(&self) -> Rect {+ self.bounds+ }+}+/// Incremental stroke rendering: feed points, composite dirty tiles from the pre-stroke pixels.#[derive(Clone, Debug)]pub struct StrokeRenderer {@@ -570,6 +592,105 @@ impl StrokeRenderer {}merged.composite(pre, target, selection, lock_transparency, true)}++ /// Coverage tiles (stroke and Dual Brush) changed since the last call or composite, into+ /// `keys`; forgets them.+ fn drain_dirty_into(&mut self, keys: &mut HashSet<(i32, i32)>) {+ keys.extend(self.cov.dirty.drain());+ if let Some(d) = self.dual.as_mut() {+ keys.extend(d.dirty.drain());+ }+ }++ /// Every coverage tile (stroke and Dual Brush), into `keys`.+ fn keys_into(&self, keys: &mut HashSet<(i32, i32)>) {+ keys.extend(self.cov.tiles.keys());+ if let Some(d) = &self.dual {+ keys.extend(d.tiles.keys());+ }+ }++ /// Live preview of a stroke painted as several passes (the stroke, then its symmetry+ /// mirrors): leaves `target` as finishing every pass now and compositing them with+ /// [`composite_union_many`](Self::composite_union_many) over `pre` would, but redraws only the+ /// coverage tiles that changed since the previous call (new dabs, and the smoothing tail now+ /// and before). `full` redraws every tile: on the first call, or when a pass joins. Returns+ /// the damaged rectangle.+ pub fn composite_union_live(+ passes: &mut [&mut Self],+ live: &mut UnionLive,+ full: bool,+ pre: &Surface,+ target: &mut Surface,+ selection: Option<&Surface>,+ lock_transparency: bool,+ ) -> Rect {+ let mut keys = std::mem::take(&mut live.tail_keys);+ for p in passes.iter_mut() {+ p.drain_dirty_into(&mut keys);+ if full {+ p.keys_into(&mut keys);+ }+ }+ let tails: Vec<_> = passes.iter().map(|p| p.tail_preview()).collect();+ let mut tail_keys = HashSet::new();+ for t in tails.iter().flatten() {+ t.keys_into(&mut tail_keys);+ }+ keys.extend(&tail_keys);+ let mut merged: Option<Self> = None;+ for (p, t) in passes.iter().zip(&tails) {+ let cov = p.cov.finished_subset(t.as_ref().map(|t| &t.cov), &keys);+ let dual = p.dual.as_ref().map(|d| d.finished_subset(t.as_ref().and_then(|t| t.dual.as_ref()), &keys));+ match merged.as_mut() {+ None => {+ merged = Some(Self {+ ctx: p.ctx.clone(),+ generator: p.generator.clone(),+ cov,+ dual,+ fmt: p.fmt,+ per_dab_color: p.per_dab_color,+ dabs_done: p.dabs_done,+ scratch: Vec::new(),+ depth_scratch: Vec::new(),+ dab_buf: Vec::new(),+ dual_buf: Vec::new(),+ all_dabs: None,+ })+ }+ Some(m) => {+ m.cov.union_max(&cov);+ if let (Some(to), Some(from)) = (&mut m.dual, &dual) {+ to.union_max(from);+ }+ }+ }+ }+ let Some(mut merged) = merged else { return Rect::EMPTY };+ let (before, after) = (live.bounds, merged.bounds());+ // Back to the pre-stroke pixels where the previous call drew and nothing covers now.+ let mut keys: Vec<_> = keys.into_iter().collect();+ keys.sort_unstable();+ let mut dmg = Rect::EMPTY;+ let mut region = Vec::new();+ for &(tx, ty) in &keys {+ let tile = Rect::new(tx * COV_TILE, ty * COV_TILE, (tx + 1) * COV_TILE, (ty + 1) * COV_TILE);+ let old = tile.intersect(&before);+ if !old.is_empty() {+ pre.read_region_into(old, &mut region);+ target.write_region(old, ®ion);+ dmg = dmg.union(&old);+ }+ if merged.cov.tiles.contains_key(&(tx, ty)) {+ dmg = dmg.union(&tile.intersect(&after));+ }+ }+ merged.composite(pre, target, selection, lock_transparency, true);+ live.tail_keys = tail_keys;+ live.bounds = after;+ dmg+ }/// `fmt` = target pixel format (needed for per-dab colour); `zoom` for smoothing.pub fn new(brush: &BrushSettings, fmt: Option<PixelFormat>, zoom: f32) -> Self {let per_dab_color = brush.color_dynamics.enabled && !brush.erase && fmt.is_some();