From 06ac6c8931e9dc07025ebc9952d80d92f9b6f53d Mon Sep 17 00:00:00 2001 From: Justin John Date: Mon, 2 Nov 2026 20:30:57 +0530 Subject: [PATCH 1/5] Path cache: skip untouched paths, cover channels and alpha images, cap memory Follow-up to #133's review notes. - The cache key now covers the owner layer's and texture set's channels, and each path's brush alpha image, so changing them repaints instead of reusing stale pixels. - The cache keeps a snapshot after each path and the tiles each path painted. An unchanged path above an edit reuses its tiles when the edit didn't reach them; removing a path reuses the paths above it. - Snapshots stay within 256 MB, oldest dropped first, keeping the one below the path being edited so live edits start there. - Path repaints ignore the quick mask: a path paints only from what it stores. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/painting.rs | 8 + crates/engine/src/path_tool.rs | 304 ++++++++++++++++++++++++++------ crates/engine/src/quick_mask.rs | 4 +- crates/engine/src/session.rs | 5 +- 4 files changed, 265 insertions(+), 56 deletions(-) diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index de132ffd..3c90af84 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -141,6 +141,8 @@ impl Session { let ts = self.ts(); let size = self.caches.get(ts).map(|c| c.size).unwrap_or((1024, 1024)); let pickup = if quick_mask { None } else { self.pickup_mode(first_uv)? }; + // PathCache reuses a path's tiles only if painting one tile reads no other. + debug_assert!(!(self.painting_paths && pickup.is_some()), "path repaints never pick up"); if pickup.is_some() { // Clone and smudge read the composite: bring it up to date first. self.update(); @@ -402,6 +404,9 @@ impl Session { self.doc = st.before; return Ok(()); } + if self.painting_paths { + self.path_tiles.extend(st.canvas.dirty.iter().copied()); + } let gbuf = self.caches.get(st.ts).map(|c| c.gbuf.clone()); let mesh = self.mesh.clone(); let mut staging = std::mem::take(&mut st.staging); @@ -502,6 +507,9 @@ impl Session { pub(crate) fn commit_fill(&mut self, label: &str, ts: usize, canvas: &StrokeCanvas) -> Result<()> { let size = (canvas.alpha.width(), canvas.alpha.height()); let src = |opacity| CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None }; + if self.painting_paths { + self.path_tiles.extend(canvas.dirty.iter().copied()); + } if self.quick_mask.editing { self.commit_quick_mask(ts, size, src(self.tool.brush.opacity)); return Ok(()); diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 0b2903e0..6629c944 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -7,13 +7,16 @@ //! (`path.edit`, live while the points, brush or material change) or removed (`path.remove`). use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; +use texturecraft_compose::ImageRes; use texturecraft_core::{Channel, Effect, EffectKind, LayerId, Mask, MaskBackground, PathShape}; use texturecraft_geom::OrbitCamera; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_paint::{BrushSettings, Lasso, fill_coverage, spline}; +use texturecraft_texel::{TILE_AREA, TileImage}; use crate::commands::{CommandSpec, always, bad, boolp, has_layer, u64p}; use crate::session::{StackTarget, Tool}; @@ -22,6 +25,9 @@ use crate::{EngineError, Result, Session, cmd}; /// Control points kept at most. pub const MAX_PATH_POINTS: usize = 4096; +/// Bytes of tiles the path cache's snapshots may hold (plus the edited path's); the oldest go +/// first. +const CACHE_BYTES: usize = 256 << 20; /// Curve sampling step in viewport pixels (3D view) and texture units (2D view). const STEP_PX: f32 = 2.0; const STEP_UV: f32 = 0.001; @@ -58,17 +64,74 @@ impl PathState { } } -/// A path sublayer's pixels after painting its first paths (`below`), with the mesh and -/// texture size they were painted for. +/// Mesh id, texture size, owner layer channels, texture set channels. +type CacheKey = (u64, Option<(u32, u32)>, Vec, Vec); +/// A path sublayer's images: its mask (`None`) and each channel. +type Snap = BTreeMap, TileImage>; +/// A stored path and the brush alpha image it was painted with. +type Painted = (PathShape, Option>); + +/// A path sublayer as last painted for `key`: its paths, its images after each path +/// (`snaps[k]` after the first k; tiles are shared, so a snapshot costs only the tiles that +/// path changed; None once [`evict`]ed) and the tiles each path painted. #[derive(Clone)] -// shortcut: the key doesn't cover image resources a path's brush alpha reads; replacing one -// leaves cached paths with the old alpha until a path below the edited one changes. pub(crate) struct PathCache { eid: LayerId, - key: (u64, Option<(u32, u32)>), - below: Vec, - mask: Option, - layers: Vec<((LayerId, Channel), texturecraft_texel::TileImage)>, + key: CacheKey, + shapes: Vec, + snaps: Vec>, + tiles: Vec>, +} + +/// Drop the snapshots past `budget` bytes, oldest first, so adding a path and editing recent +/// ones stay cheap, but keep snapshot `edited` (below the path being edited, so its next live +/// repaint starts there). Snapshot k holds at most path k-1's tiles in each image; the first +/// (empty) and the last (the live pixels) cost nothing. +fn evict(snaps: &mut [Option], tiles: &[BTreeSet<(u32, u32)>], budget: usize, edited: usize) { + let mut bytes = 0; + for k in (1..snaps.len().saturating_sub(1)).rev().filter(|&k| k != edited) { + if let Some(snap) = &snaps[k] { + bytes += tiles[k - 1].len() * snap.values().map(|i| TILE_AREA * i.comps() * 2).sum::(); + if bytes > budget { + snaps[k] = None; + } + } + } +} + +fn same_handle(a: Option<&Arc>, b: Option<&Arc>) -> bool { + match (a, b) { + (Some(x), Some(y)) => Arc::ptr_eq(x, y), + (x, y) => x.is_none() && y.is_none(), + } +} + +fn same_path(a: &Painted, b: &Painted) -> bool { + a.0 == b.0 && same_handle(a.1.as_ref(), b.1.as_ref()) +} + +/// Whether `a` and `b` hold the same tiles at `tiles`, by shared handle (painting a tile always +/// gives it a new one); a missing image reads as empty. +fn same_tiles(a: &Snap, b: &Snap, tiles: &BTreeSet<(u32, u32)>) -> bool { + a.keys().chain(b.keys()).all(|k| { + let (x, y) = (a.get(k), b.get(k)); + let dims = |i: &TileImage| (i.width(), i.height(), i.comps()); + x.zip(y).is_none_or(|(x, y)| dims(x) == dims(y)) + && tiles.iter().all(|&(tx, ty)| same_handle(x.and_then(|i| i.tile_handle(tx, ty)), y.and_then(|i| i.tile_handle(tx, ty)))) + }) +} + +/// Copy `from`'s tiles at `tiles` into `to`. +fn copy_tiles(to: &mut Snap, from: &Snap, tiles: &BTreeSet<(u32, u32)>) { + for (k, src) in from { + to.entry(*k).or_insert_with(|| TileImage::new(src.width(), src.height(), src.comps())); + } + for (k, dst) in to.iter_mut() { + let src = from.get(k); + for &(x, y) in tiles { + dst.set_tile(x, y, src.and_then(|i| i.tile_handle(x, y)).cloned()); + } + } } /// What a stored path is painted with ([`PathShape::paint`]). @@ -197,7 +260,7 @@ fn remove_path(s: &mut Session, p: &Value) -> Result { { shapes.remove(index); } - s.render_paths(eid, index) + s.render_paths(eid) })?; if s.tool.path.editing.is_some_and(|(e, _)| e == eid) { s.stop_path_edit(); @@ -359,32 +422,43 @@ impl Session { }, _ => return Err(EngineError::Other(format!("{} is not a path sublayer", eid.0))), }; - let mut out = self.render_paths(eid, index)?.get(index).cloned().unwrap_or_else(|| json!({})); + let mut out = self.render_paths(eid)?.get(index).cloned().unwrap_or_else(|| json!({})); out["effect"] = json!(eid.0); out["index"] = json!(index); Ok(out) } - /// Repaint path sublayer `eid` from its stored paths, bottom to top, where paths before - /// `from` are unchanged: their pixels come from [`PathCache`] when it holds them, and are - /// cached for the next repaint otherwise, so editing a path repaints it and the paths above - /// only. Runs inside the caller's undo step. Returns each painted path's report (null for - /// the cached ones). - fn render_paths(&mut self, eid: LayerId, from: usize) -> Result> { + /// Repaint path sublayer `eid` from its stored paths, bottom to top. From [`PathCache`]: the + /// paths before the first changed one keep their pixels, and an unchanged path above it + /// whose tiles the change didn't reach keeps its painted tiles; the rest repaint. Runs + /// inside the caller's undo step. Returns each painted path's report (null for the cached + /// ones). + fn render_paths(&mut self, eid: LayerId) -> Result> { let shapes = self.paths(eid).ok_or_else(|| EngineError::Other(format!("{} is not a path sublayer", eid.0)))?.to_vec(); - let key = (self.mesh_id, self.caches.get(self.ts()).map(|c| c.size)); - self.doc.pixels.masks.remove(&eid); - self.doc.pixels.layers.retain(|(id, _), _| *id != eid); - let start = match &self.path_cache { - Some(c) if c.eid == eid && c.key == key && c.below.len() <= from && shapes.get(..c.below.len()) == Some(&c.below[..]) => { - if let Some(m) = &c.mask { - self.doc.pixels.masks.insert(eid, m.clone()); - } - self.doc.pixels.layers.extend(c.layers.iter().cloned()); - c.below.len() - } - _ => 0, - }; + let images = &self.images; + let alpha = |sh: &PathShape| read_paint(sh).ok().and_then(|p| p.brush.alpha_image).and_then(|n| images.get(&n).cloned()); + let new: Vec = shapes + .into_iter() + .map(|sh| { + let a = alpha(&sh); + (sh, a) + }) + .collect(); + let project = &self.doc.project; + let owner = project.effect(eid).and_then(|(o, _)| project.layer(o).ok()).map(|l| l.channels.keys().copied().collect()).unwrap_or_default(); + let set = project.texture_set(self.ts()).map(|t| t.channel_list()).unwrap_or_default(); + let key: CacheKey = (self.mesh_id, self.caches.get(self.ts()).map(|c| c.size), owner, set); + let old = self.path_cache.take().filter(|c| c.eid == eid && c.key == key); + let (prefix, suffix) = old.as_ref().map_or((0, 0), |c| { + let p = c.shapes.iter().zip(&new).take_while(|(a, b)| same_path(a, b)).count(); + (p, c.shapes[p..].iter().rev().zip(new[p..].iter().rev()).take_while(|(a, b)| same_path(a, b)).count()) + }); + // Start from the last snapshot kept at or below the first changed path (the first one, + // empty, is always kept). + let start = old.as_ref().map_or(0, |c| (0..=prefix).rev().find(|&k| c.snaps[k].is_some()).unwrap_or(0)); + let mut snaps = old.as_ref().map_or_else(|| vec![Some(Snap::new())], |c| c.snaps[..=start].to_vec()); + let mut tiles = old.as_ref().map_or_else(Vec::new, |c| c.tiles[..start].to_vec()); + let mut state = snaps[start].clone().unwrap_or_default(); // Each path goes through the regular stroke and fill code with its own settings; their // own history entries are dropped (the caller records one step). let saved = (self.tool.clone(), self.camera, self.target, self.quick_mask.editing); @@ -395,13 +469,22 @@ impl Session { self.painting_paths = true; let mut out = vec![Value::Null; start]; let mut result = Ok(()); - for i in start..=shapes.len() { - if i == from.min(shapes.len()) && i > start { - let pixels = &self.doc.pixels; - let layers = pixels.layers.iter().filter(|((id, _), _)| *id == eid).map(|(k, v)| (*k, v.clone())).collect(); - self.path_cache = Some(PathCache { eid, key, below: shapes[..i].to_vec(), mask: pixels.masks.get(&eid).cloned(), layers }); + for (j, (sh, _)) in new.iter().enumerate().skip(start) { + // Painting is per tile: over the same tiles, an unchanged path paints the same. + let o = if j < prefix { Some(j) } else { (j >= new.len() - suffix).then(|| j + old.as_ref().map_or(0, |c| c.shapes.len()) - new.len()) }; + if let (Some(c), Some(o)) = (&old, o) + && let (Some(below), Some(after)) = (&c.snaps[o], &c.snaps[o + 1]) + && same_tiles(&state, below, &c.tiles[o]) + { + copy_tiles(&mut state, after, &c.tiles[o]); + tiles.push(c.tiles[o].clone()); + snaps.push(Some(state.clone())); + evict(&mut snaps, &tiles, CACHE_BYTES, prefix); + out.push(Value::Null); + continue; } - let Some(sh) = shapes.get(i) else { break }; + self.put_snap(eid, &state); + self.path_tiles.clear(); match self.paint_shape(sh) { Ok(v) => out.push(v), Err(e) => { @@ -409,13 +492,39 @@ impl Session { break; } } + state = self.take_snap(eid); + tiles.push(std::mem::take(&mut self.path_tiles)); + snaps.push(Some(state.clone())); + evict(&mut snaps, &tiles, CACHE_BYTES, prefix); } + self.put_snap(eid, &state); self.painting_paths = false; (self.tool, self.camera, self.target, self.quick_mask.editing) = saved; (self.undo, self.redo) = history; + if result.is_ok() { + self.path_cache = Some(PathCache { eid, key, shapes: new, snaps, tiles }); + } result.map(|_| out) } + fn take_snap(&self, eid: LayerId) -> Snap { + let p = &self.doc.pixels; + let mask = p.masks.get(&eid).map(|m| (None, m.clone())); + mask.into_iter().chain(p.layers.iter().filter(|((id, _), _)| *id == eid).map(|((_, c), img)| (Some(*c), img.clone()))).collect() + } + + fn put_snap(&mut self, eid: LayerId, snap: &Snap) { + let p = &mut self.doc.pixels; + p.masks.remove(&eid); + p.layers.retain(|(id, _), _| *id != eid); + for (k, img) in snap { + match k { + None => p.masks.insert(eid, img.clone()), + Some(c) => p.layers.insert((eid, *c), img.clone()), + }; + } + } + fn paint_shape(&mut self, shape: &PathShape) -> Result { let paint = read_paint(shape)?; self.tool.brush = paint.brush; @@ -493,7 +602,7 @@ impl Session { #[cfg(test)] mod tests { - use serde_json::json; + use serde_json::{Value, json}; use crate::{Session, execute}; @@ -504,29 +613,118 @@ mod tests { v } - #[test] - fn cached_repaint_matches_a_full_repaint() { - let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap(); + /// A session with horizontal UV paths at `rows` (one path sublayer) on a 512 texture. + fn with_paths(rows: &[f32]) -> (Session, texturecraft_core::LayerId) { + let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 512).unwrap(); s.update(); execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap(); let mut eid = 0; - for v in [0.2, 0.5, 0.8] { - let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.9, v + 0.05]], "commit": true})).unwrap(); + for v in rows { + let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.9, v]], "commit": true})).unwrap(); eid = r["committed"]["effect"].as_u64().unwrap(); } - let eid = texturecraft_core::LayerId(eid); - // Live edits of the middle path reuse the bottom path's pixels. - execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap(); - for v in [0.4, 0.45] { - execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.5, v], [0.9, v]]})).unwrap(); - } - assert_eq!(s.path_cache.as_ref().map(|c| c.below.len()), Some(1)); - let r = s.render_paths(eid, 1).unwrap(); - assert!(r[0].is_null() && !r[1].is_null(), "the bottom path came from the cache: {r:?}"); - let cached = pixels(&s, eid); + (s, texturecraft_core::LayerId(eid)) + } + + /// Move path `index` to row `v` (a live edit) and check the result against painting every + /// path. Returns which paths were repainted. + fn edit_row(s: &mut Session, eid: texturecraft_core::LayerId, index: usize, v: f32) -> Vec { + execute(s, "path.edit", &json!({"effect": eid.0, "index": index})).unwrap(); + let before = s.path_cache.clone(); + execute(s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.5, v], [0.9, v]]})).unwrap(); + let cached = pixels(s, eid); + s.path_cache = before; + let painted = s.render_paths(eid).unwrap().iter().map(|r| !r.is_null()).collect(); + assert_eq!(cached, pixels(s, eid)); s.path_cache = None; - s.render_paths(eid, 0).unwrap(); - assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path"); + s.render_paths(eid).unwrap(); + assert_eq!(cached, pixels(s, eid), "same pixels as painting every path"); assert!(!cached.is_empty()); + s.stop_path_edit(); + painted + } + + #[test] + fn cached_repaint_matches_a_full_repaint() { + // Rows 0.2, 0.45 and 0.8 of 512 texels are in different 64-texel tile rows. + let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]); + assert_eq!(edit_row(&mut s, eid, 1, 0.47), [false, true, false], "only the edited path repaints"); + assert_eq!(edit_row(&mut s, eid, 0, 0.22), [true, false, false], "paths above keep their tiles"); + assert_eq!(edit_row(&mut s, eid, 0, 0.79), [true, false, true], "a path over the change repaints"); + } + + #[test] + fn removing_a_path_keeps_the_paths_above() { + let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]); + let before = s.path_cache.clone(); + execute(&mut s, "path.remove", &json!({"effect": eid.0, "index": 0})).unwrap(); + let cached = pixels(&s, eid); + s.path_cache = before; + assert!(s.render_paths(eid).unwrap().iter().all(Value::is_null), "both paths above came from the cache"); + s.path_cache = None; + s.render_paths(eid).unwrap(); + assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path"); + } + + #[test] + fn replacing_the_brush_alpha_image_repaints() { + let (mut s, eid) = with_paths(&[0.2]); + let img = |v: f32| std::sync::Arc::new(texturecraft_compose::ImageRes { width: 2, height: 2, rgba: vec![[v; 4]; 4], srgb: false }); + s.images.insert("a".into(), img(1.0)); + execute(&mut s, "tool.brush", &json!({"alpha": {"image": "a"}})).unwrap(); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.8], [0.9, 0.8]], "commit": true})).unwrap(); + s.render_paths(eid).unwrap(); + s.images.insert("a".into(), img(0.5)); + let r = s.render_paths(eid).unwrap(); + assert!(r[0].is_null() && !r[1].is_null(), "only the path using the image repaints: {r:?}"); + } + + #[test] + fn snapshots_stay_within_the_budget() { + let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]); + let c = s.path_cache.as_mut().unwrap(); + super::evict(&mut c.snaps, &c.tiles, usize::MAX, 0); + assert_eq!(c.snaps.iter().flatten().count(), 4); + super::evict(&mut c.snaps, &c.tiles, 0, 0); + assert!(c.snaps[0].is_some() && c.snaps[3].is_some() && c.snaps[1..3].iter().all(Option::is_none), "only the free ones stay"); + // Appending still paints the new path alone. + let shape = s.paths(eid).unwrap()[0].clone(); + if let Some(texturecraft_core::Effect { kind: texturecraft_core::EffectKind::Path(v), .. }) = s.doc.project.effect_mut(eid) { + v.push(shape); + } + let r = s.render_paths(eid).unwrap(); + assert_eq!(r.iter().map(|x| !x.is_null()).collect::>(), [false, false, false, true]); + // Editing above evicted snapshots repaints from the bottom and matches a full repaint. + let c = s.path_cache.as_mut().unwrap(); + super::evict(&mut c.snaps, &c.tiles, 0, 0); + assert_eq!(edit_row(&mut s, eid, 2, 0.81), [true; 4], "the copy of path 1 sits on repainted tiles"); + // That edit kept the snapshot below path 3 within a zero budget: its next frame starts there. + let c = s.path_cache.as_mut().unwrap(); + super::evict(&mut c.snaps, &c.tiles, 0, 2); + assert!(c.snaps[2].is_some() && c.snaps[1].is_none()); + assert_eq!(edit_row(&mut s, eid, 2, 0.83), [false, false, true, true], "path 4 lost its snapshot too"); + } + + #[test] + fn the_quick_mask_does_not_clip_paths() { + let (mut s, eid) = with_paths(&[0.2, 0.8]); + let plain = pixels(&s, eid); + s.quick_mask.enabled = true; + s.path_cache = None; + s.render_paths(eid).unwrap(); + assert_eq!(plain, pixels(&s, eid)); + } + + #[test] + fn owner_channel_change_skips_the_cache() { + let (mut s, eid) = with_paths(&[0.3, 0.7]); + s.render_paths(eid).unwrap(); + let owner = s.doc.project.effect(eid).unwrap().0; + let layer = s.doc.project.layer_mut(owner).unwrap(); + let ch = *layer.channels.keys().next().unwrap(); + layer.channels.remove(&ch); + let r = s.render_paths(eid).unwrap(); + assert!(!r[0].is_null(), "the bottom path was repainted: {r:?}"); + assert!(!s.doc.pixels.layers.contains_key(&(eid, ch)), "no pixels left in the removed channel"); } } diff --git a/crates/engine/src/quick_mask.rs b/crates/engine/src/quick_mask.rs index 304ab3c9..f407a9ef 100644 --- a/crates/engine/src/quick_mask.rs +++ b/crates/engine/src/quick_mask.rs @@ -86,10 +86,10 @@ impl Session { } /// What limits a paint stroke on `ts`: the mask and whether it is inverted (None when the - /// quick mask is off or being edited). + /// quick mask is off or being edited, and for paths, which repaint from what they store). pub(crate) fn stroke_limit(&self, ts: usize, size: (u32, u32)) -> Option<(TileImage, bool)> { let q = &self.quick_mask; - (q.enabled && !q.editing).then(|| (self.quick_mask_image(ts, size), q.inverted)) + (q.enabled && !q.editing && !self.painting_paths).then(|| (self.quick_mask_image(ts, size), q.inverted)) } /// Commit a stroke into the quick mask of `ts`. diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index e9909635..7b49d8e2 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -346,8 +346,10 @@ pub struct Session { pub quick_mask: crate::quick_mask::QuickMask, /// A path sublayer is being repainted from its paths (the only way to paint into one). pub(crate) painting_paths: bool, - /// Pixels of the paths below the one being edited, so live edits skip repainting them. + /// A path sublayer as last painted, so a repaint skips the paths an edit didn't reach. pub(crate) path_cache: Option, + /// Tiles painted since `render_paths` cleared it (the footprint of one path). + pub(crate) path_tiles: std::collections::BTreeSet<(u32, u32)>, pub path: Option, pub modified: bool, /// Bumps on every document change. @@ -402,6 +404,7 @@ impl Session { quick_mask: Default::default(), painting_paths: false, path_cache: None, + path_tiles: Default::default(), path: None, modified: false, revision: 1, From 0ec4775ef63ad89f6eccfc84947c2391eceefbf1 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:30:56 -0500 Subject: [PATCH 2/5] fix(path-cache): charge each snapshot for the tile buffers it alone keeps alive evict charged snapshot k for path k-1's tiles only, but snapshot k holds every pixel after k paths and shares tile handles with the others. After an older snapshot was evicted, a newer one could retain a whole older generation (full fill, one-tile stroke, full fill, one-tile stroke) and the 256 MiB cap was exceeded. Walk newest to oldest and charge only handles not already held by the live pixels, the edited snapshot or a kept newer snapshot. Also drop the debug_assert from non-test code. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/painting.rs | 2 - crates/engine/src/path_tool.rs | 103 +++++++++++++++++++++++++++------ 2 files changed, 84 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index 3c90af84..dd0013b2 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -141,8 +141,6 @@ impl Session { let ts = self.ts(); let size = self.caches.get(ts).map(|c| c.size).unwrap_or((1024, 1024)); let pickup = if quick_mask { None } else { self.pickup_mode(first_uv)? }; - // PathCache reuses a path's tiles only if painting one tile reads no other. - debug_assert!(!(self.painting_paths && pickup.is_some()), "path repaints never pick up"); if pickup.is_some() { // Clone and smudge read the composite: bring it up to date first. self.update(); diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 6629c944..b73dd661 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -16,7 +16,7 @@ use texturecraft_core::{Channel, Effect, EffectKind, LayerId, Mask, MaskBackgrou use texturecraft_geom::OrbitCamera; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_paint::{BrushSettings, Lasso, fill_coverage, spline}; -use texturecraft_texel::{TILE_AREA, TileImage}; +use texturecraft_texel::TileImage; use crate::commands::{CommandSpec, always, bad, boolp, has_layer, u64p}; use crate::session::{StackTarget, Tool}; @@ -83,18 +83,48 @@ pub(crate) struct PathCache { tiles: Vec>, } +/// The identities of the tile buffers `snap` holds, added to `seen`; returns the bytes of those +/// not already there. +fn charge(snap: &Snap, seen: &mut BTreeSet) -> usize { + let mut bytes = 0; + for img in snap.values() { + for ty in 0..img.tiles_y() { + for tx in 0..img.tiles_x() { + if let Some(t) = img.tile_handle(tx, ty) + && seen.insert(Arc::as_ptr(t) as usize) + { + bytes += t.len() * 2; + } + } + } + } + bytes +} + /// Drop the snapshots past `budget` bytes, oldest first, so adding a path and editing recent /// ones stay cheap, but keep snapshot `edited` (below the path being edited, so its next live -/// repaint starts there). Snapshot k holds at most path k-1's tiles in each image; the first -/// (empty) and the last (the live pixels) cost nothing. -fn evict(snaps: &mut [Option], tiles: &[BTreeSet<(u32, u32)>], budget: usize, edited: usize) { +/// repaint starts there). Tiles are shared between snapshots and with the live pixels (the last +/// snapshot) and snapshot k holds every tile as it was after k paths, so each snapshot, newest +/// first, is charged for the tile buffers no live pixels, kept newer snapshot or `edited` already +/// hold: what freeing it would release at most. The first (empty) and the last cost nothing. +fn evict(snaps: &mut [Option], budget: usize, edited: usize) { + let mut seen = BTreeSet::new(); + for k in [snaps.len().saturating_sub(1), edited] { + if let Some(Some(snap)) = snaps.get(k) { + charge(snap, &mut seen); + } + } let mut bytes = 0; for k in (1..snaps.len().saturating_sub(1)).rev().filter(|&k| k != edited) { - if let Some(snap) = &snaps[k] { - bytes += tiles[k - 1].len() * snap.values().map(|i| TILE_AREA * i.comps() * 2).sum::(); - if bytes > budget { - snaps[k] = None; - } + let Some(Some(snap)) = snaps.get(k) else { continue }; + // Count into a copy: an evicted snapshot's tiles are not retained by it any more. + let mut with = seen.clone(); + let cost = charge(snap, &mut with); + if bytes + cost > budget { + snaps[k] = None; + } else { + bytes += cost; + seen = with; } } } @@ -479,7 +509,7 @@ impl Session { copy_tiles(&mut state, after, &c.tiles[o]); tiles.push(c.tiles[o].clone()); snaps.push(Some(state.clone())); - evict(&mut snaps, &tiles, CACHE_BYTES, prefix); + evict(&mut snaps, CACHE_BYTES, prefix); out.push(Value::Null); continue; } @@ -495,7 +525,7 @@ impl Session { state = self.take_snap(eid); tiles.push(std::mem::take(&mut self.path_tiles)); snaps.push(Some(state.clone())); - evict(&mut snaps, &tiles, CACHE_BYTES, prefix); + evict(&mut snaps, CACHE_BYTES, prefix); } self.put_snap(eid, &state); self.painting_paths = false; @@ -683,10 +713,15 @@ mod tests { fn snapshots_stay_within_the_budget() { let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]); let c = s.path_cache.as_mut().unwrap(); - super::evict(&mut c.snaps, &c.tiles, usize::MAX, 0); + super::evict(&mut c.snaps, usize::MAX, 0); assert_eq!(c.snaps.iter().flatten().count(), 4); - super::evict(&mut c.snaps, &c.tiles, 0, 0); - assert!(c.snaps[0].is_some() && c.snaps[3].is_some() && c.snaps[1..3].iter().all(Option::is_none), "only the free ones stay"); + // The paths are on different tiles, so keeping every snapshot costs nothing beyond the live + // pixels: even a zero budget keeps them. + super::evict(&mut c.snaps, 0, 0); + assert_eq!(c.snaps.iter().flatten().count(), 4, "snapshots that share every tile with the live pixels are free"); + // Drop them by hand to test the repaint from the bottom. + c.snaps[1] = None; + c.snaps[2] = None; // Appending still paints the new path alone. let shape = s.paths(eid).unwrap()[0].clone(); if let Some(texturecraft_core::Effect { kind: texturecraft_core::EffectKind::Path(v), .. }) = s.doc.project.effect_mut(eid) { @@ -696,13 +731,43 @@ mod tests { assert_eq!(r.iter().map(|x| !x.is_null()).collect::>(), [false, false, false, true]); // Editing above evicted snapshots repaints from the bottom and matches a full repaint. let c = s.path_cache.as_mut().unwrap(); - super::evict(&mut c.snaps, &c.tiles, 0, 0); + assert!(c.snaps[1].is_none() && c.snaps[2].is_none()); assert_eq!(edit_row(&mut s, eid, 2, 0.81), [true; 4], "the copy of path 1 sits on repainted tiles"); - // That edit kept the snapshot below path 3 within a zero budget: its next frame starts there. + // That edit kept the snapshot below path 3 within a zero budget: its next frame starts + // there, and the snapshots above it that cost nothing keep their paths unrepainted. let c = s.path_cache.as_mut().unwrap(); - super::evict(&mut c.snaps, &c.tiles, 0, 2); - assert!(c.snaps[2].is_some() && c.snaps[1].is_none()); - assert_eq!(edit_row(&mut s, eid, 2, 0.83), [false, false, true, true], "path 4 lost its snapshot too"); + super::evict(&mut c.snaps, 0, 2); + assert!(c.snaps[2].is_some()); + assert_eq!(edit_row(&mut s, eid, 2, 0.83), [false, false, true, false], "only the edited path repaints"); + } + + /// `prev` with the tiles in `at` replaced by new handles (what painting a path does). + fn painted(prev: &super::Snap, at: &[(u32, u32)]) -> super::Snap { + let mut next = prev.clone(); + for img in next.values_mut() { + for &(x, y) in at { + img.set_tile(x, y, Some(std::sync::Arc::new(vec![1u16; texturecraft_texel::TILE_AREA * 4]))); + } + } + next + } + + #[test] + fn the_budget_counts_the_tiles_an_old_snapshot_keeps_alive() { + let all: Vec<(u32, u32)> = (0..4).flat_map(|y| (0..4).map(move |x| (x, y))).collect(); + let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into(); + // A full-texture fill, a one-tile stroke, another full fill, another one-tile stroke. + let s1 = painted(&empty, &all); + let s2 = painted(&s1, &[(0, 0)]); + let s3 = painted(&s2, &all); + let s4 = painted(&s3, &[(0, 0)]); + let mut snaps = vec![Some(empty), Some(s1), Some(s2), Some(s3), Some(s4)]; + // Snapshot 3 is the edited one. Snapshot 2 alone holds 15 tiles of the first fill that + // neither the live image nor snapshot 3 has: that is over a budget of 8 tiles. + let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2; + super::evict(&mut snaps, 8 * tile_bytes, 3); + assert!(snaps[3].is_some(), "the edited snapshot stays"); + assert!(snaps[2].is_none(), "snapshot 2 keeps the first fill alive, over the budget"); } #[test] From 14f02e5fe79d333f9d115ee3dc0c90c0ba633206 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:17:44 -0500 Subject: [PATCH 3/5] test(path-cache): a snapshot is charged only for tiles no kept snapshot shares Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/path_tool.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index b73dd661..bd4c9715 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -770,6 +770,33 @@ mod tests { assert!(snaps[2].is_none(), "snapshot 2 keeps the first fill alive, over the budget"); } + #[test] + fn a_snapshot_is_charged_only_for_what_no_kept_snapshot_shares() { + let all: Vec<(u32, u32)> = (0..4).flat_map(|y| (0..4).map(move |x| (x, y))).collect(); + let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into(); + let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2; + // Two full fills then a one-tile stroke (the live pixels). Snapshot 2 shares 15 tiles with + // the live pixels and owns one; snapshot 1 owns the whole first fill: 16 tiles. + let s1 = painted(&empty, &all); + let s2 = painted(&s1, &all); + let s3 = painted(&s2, &[(0, 0)]); + let fresh = || vec![Some(empty.clone()), Some(s1.clone()), Some(s2.clone()), Some(s3.clone())]; + let kept = |snaps: &[Option]| snaps.iter().map(Option::is_some).collect::>(); + let mut snaps = fresh(); + super::evict(&mut snaps, usize::MAX, 0); + assert_eq!(kept(&snaps), [true; 4]); + let mut snaps = fresh(); + super::evict(&mut snaps, tile_bytes, 0); + assert_eq!(kept(&snaps), [true, false, true, true], "snapshot 2 costs one tile, snapshot 1 sixteen"); + let mut snaps = fresh(); + super::evict(&mut snaps, 0, 0); + assert_eq!(kept(&snaps), [true, false, false, true], "snapshot 2 owns one tile, over a zero budget"); + // Keeping snapshot 1 (edited) makes snapshot 2 free of the tiles they share, not of its own. + let mut snaps = fresh(); + super::evict(&mut snaps, 0, 1); + assert_eq!(kept(&snaps), [true, true, false, true]); + } + #[test] fn the_quick_mask_does_not_clip_paths() { let (mut s, eid) = with_paths(&[0.2, 0.8]); From 589eb4c76432db8b350ec4c8e8c56f0f956833e8 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sat, 28 Nov 2026 10:29:26 -0500 Subject: [PATCH 4/5] test(path-cache): a filled path above an edit keeps its tiles from the cache Covers the footprint recorded by commit_fill; emptying it left every other test green. Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/path_tool.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index bd4c9715..785c779d 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -683,6 +683,15 @@ mod tests { assert_eq!(edit_row(&mut s, eid, 0, 0.79), [true, false, true], "a path over the change repaints"); } + #[test] + fn a_filled_path_above_an_edit_keeps_its_tiles() { + // The stroke at row 0.2 is edited; the closed, filled path above it lies in other tiles. + let (mut s, eid) = with_paths(&[0.2]); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.7], [0.5, 0.7], [0.5, 0.9], [0.1, 0.9]], "closed": true, "fill": true, "commit": true})) + .unwrap(); + assert_eq!(edit_row(&mut s, eid, 0, 0.22), [true, false], "the fill above comes from the cache, with its pixels"); + } + #[test] fn removing_a_path_keeps_the_paths_above() { let (mut s, eid) = with_paths(&[0.2, 0.45, 0.8]); From f28d4d8b6439208fa721536be0023853841ad3d4 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:30:56 -0500 Subject: [PATCH 5/5] fix(paths): count each snapshot's tile table against the path cache budget Co-Authored-By: Claude Sonnet 5.5 --- crates/engine/src/path_tool.rs | 58 ++++++++++++++++++++++++++-------- crates/texel/src/tile.rs | 11 +++++++ 2 files changed, 56 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 5efc1215..15455941 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -173,11 +173,15 @@ pub(crate) struct PathCache { tiles: Vec>, } -/// The identities of the tile buffers `snap` holds, added to `seen`; returns the bytes of those -/// not already there. +/// The identities of the tile buffers and tile tables `snap` holds, added to `seen`; returns the +/// bytes of those not already there. A table (one pointer per tile slot) is shared by clones until +/// one writes, so a snapshot that diverged from the live image holds its own. fn charge(snap: &Snap, seen: &mut BTreeSet) -> usize { let mut bytes = 0; for img in snap.values() { + if seen.insert(img.table_id()) { + bytes += img.table_bytes(); + } for ty in 0..img.tiles_y() { for tx in 0..img.tiles_x() { if let Some(t) = img.tile_handle(tx, ty) @@ -239,7 +243,9 @@ impl EvictPacer { /// A snapshot was appended after a path that painted `tiles` tile positions of `state`'s images. fn appended(&mut self, snaps: &mut [Option], edited: usize, state: &Snap, tiles: usize) { let tile_bytes: usize = state.values().map(|image| texturecraft_texel::TILE_AREA * image.comps() * 2).sum(); - self.held = self.held.saturating_add(tiles.saturating_mul(tile_bytes)); + // The new snapshot may also own a table per image (a write after the clone copies it). + let table_bytes: usize = state.values().map(TileImage::table_bytes).sum(); + self.held = self.held.saturating_add(tiles.saturating_mul(tile_bytes)).saturating_add(table_bytes); if self.held > CACHE_BYTES { self.held = evict(snaps, CACHE_BYTES, edited); } @@ -1475,10 +1481,11 @@ mod tests { let c = s.path_cache.as_mut().unwrap(); super::evict(&mut c.snaps, usize::MAX, 0); assert_eq!(c.snaps.iter().flatten().count(), 4); - // The paths are on different tiles, so keeping every snapshot costs nothing beyond the live - // pixels: even a zero budget keeps them. - super::evict(&mut c.snaps, 0, 0); - assert_eq!(c.snaps.iter().flatten().count(), 4, "snapshots that share every tile with the live pixels are free"); + // The paths are on different tiles, so a snapshot costs nothing beyond its own tile table + // (the tiles are all shared with the live pixels): a budget of two tables keeps them. + let table: usize = c.snaps[1].as_ref().unwrap().values().map(texturecraft_texel::TileImage::table_bytes).sum(); + super::evict(&mut c.snaps, 2 * table, 0); + assert_eq!(c.snaps.iter().flatten().count(), 4, "snapshots that share every tile with the live pixels cost only their tables"); // Drop them by hand to test the repaint from the bottom. c.snaps[1] = None; c.snaps[2] = None; @@ -1493,10 +1500,11 @@ mod tests { let c = s.path_cache.as_mut().unwrap(); assert!(c.snaps[1].is_none() && c.snaps[2].is_none()); assert_eq!(edit_row(&mut s, eid, 2, 0.81), [true; 4], "the copy of path 1 sits on repainted tiles"); - // That edit kept the snapshot below path 3 within a zero budget: its next frame starts - // there, and the snapshots above it that cost nothing keep their paths unrepainted. + // That edit kept the snapshot below path 3 within a one-table budget: its next frame starts + // there, and the snapshots above it that cost only a table keep their paths unrepainted. let c = s.path_cache.as_mut().unwrap(); - super::evict(&mut c.snaps, 0, 2); + let table: usize = c.snaps[2].as_ref().unwrap().values().map(texturecraft_texel::TileImage::table_bytes).sum(); + super::evict(&mut c.snaps, table, 2); assert!(c.snaps[2].is_some()); assert_eq!(edit_row(&mut s, eid, 2, 0.83), [false, false, true, false], "only the edited path repaints"); } @@ -1533,6 +1541,7 @@ mod tests { #[test] fn appending_paths_scans_the_snapshots_only_when_the_budget_may_be_passed() { let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into(); + let table = empty.values().map(texturecraft_texel::TileImage::table_bytes).sum::(); let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2; let mut snaps = vec![Some(empty.clone()), Some(painted(&empty, &[(0, 0)]))]; let mut pacer = super::EvictPacer::start(&mut snaps, 0); @@ -1540,7 +1549,7 @@ mod tests { // A few small paths add up to an estimate without a scan (a scan would reset it to the exact 0). for n in 1..=3 { pacer.appended(&mut snaps, 0, &empty, 1); - assert_eq!(pacer.held, n * tile_bytes, "after {n} paths"); + assert_eq!(pacer.held, n * (tile_bytes + table), "after {n} paths"); } // Past the budget the estimate gives way to an exact scan. pacer.appended(&mut snaps, 0, &empty, super::CACHE_BYTES / tile_bytes + 1); @@ -1552,6 +1561,7 @@ mod tests { let all: Vec<(u32, u32)> = (0..4).flat_map(|y| (0..4).map(move |x| (x, y))).collect(); let empty: super::Snap = [(Some(texturecraft_core::Channel::BaseColor), texturecraft_texel::TileImage::new(256, 256, 4))].into(); let tile_bytes = texturecraft_texel::TILE_AREA * 4 * 2; + let table = empty.values().map(texturecraft_texel::TileImage::table_bytes).sum::(); // Two full fills then a one-tile stroke (the live pixels). Snapshot 2 shares 15 tiles with // the live pixels and owns one; snapshot 1 owns the whole first fill: 16 tiles. let s1 = painted(&empty, &all); @@ -1563,8 +1573,8 @@ mod tests { super::evict(&mut snaps, usize::MAX, 0); assert_eq!(kept(&snaps), [true; 4]); let mut snaps = fresh(); - super::evict(&mut snaps, tile_bytes, 0); - assert_eq!(kept(&snaps), [true, false, true, true], "snapshot 2 costs one tile, snapshot 1 sixteen"); + super::evict(&mut snaps, tile_bytes + table, 0); + assert_eq!(kept(&snaps), [true, false, true, true], "snapshot 2 costs one tile and a table, snapshot 1 sixteen"); let mut snaps = fresh(); super::evict(&mut snaps, 0, 0); assert_eq!(kept(&snaps), [true, false, false, true], "snapshot 2 owns one tile, over a zero budget"); @@ -1574,6 +1584,28 @@ mod tests { assert_eq!(kept(&snaps), [true, true, false, true]); } + #[test] + fn the_tile_table_of_a_diverged_snapshot_counts_once_against_the_budget() { + // Big image: the table (one slot per tile position) outweighs a one-tile stroke. + let empty: super::Snap = [(Some(texturecraft_core::Channel::Roughness), texturecraft_texel::TileImage::new(8192, 8192, 4))].into(); + let table = empty.values().map(texturecraft_texel::TileImage::table_bytes).sum::(); + assert!(table >= 128 * 128 * 8, "table {table}"); + let s1 = painted(&empty, &[(0, 0)]); + let s2 = painted(&s1, &[(1, 0)]); + let s3 = painted(&s2, &[(2, 0)]); + let live = painted(&s3, &[(3, 0)]); + let mut seen = std::collections::BTreeSet::new(); + // Alone, a diverged snapshot holds its own table; charged again with the same table, it is free. + let first = super::charge(&s2, &mut seen); + assert!(first >= table, "charged {first}"); + assert_eq!(super::charge(&s2, &mut seen), 0); + // Tiles alone (8 KiB each) would fit this budget; with tables only one snapshot does. + let tile_only = texturecraft_texel::TILE_AREA * 4 * 2; + let mut snaps = vec![Some(empty.clone()), Some(s1), Some(s2), Some(s3), Some(live)]; + super::evict(&mut snaps, 3 * tile_only, 0); + assert!(snaps.iter().filter(|s| s.is_some()).count() < 5, "tables must evict snapshots"); + } + #[test] fn the_quick_mask_does_not_clip_paths() { let (mut s, eid) = with_paths(&[0.2, 0.8]); diff --git a/crates/texel/src/tile.rs b/crates/texel/src/tile.rs index 31e30349..81c96ac7 100644 --- a/crates/texel/src/tile.rs +++ b/crates/texel/src/tile.rs @@ -62,6 +62,17 @@ impl TileImage { self.tile_index(tx, ty).and_then(|i| self.tiles.get(i)).and_then(Option::as_ref) } + /// Identity of the shared tile table: clones share it until one of them writes, so two images + /// with the same id hold one allocation (for memory accounting). + pub fn table_id(&self) -> usize { + Arc::as_ptr(&self.tiles) as usize + } + + /// Bytes of the tile table itself (one slot per tile position), not counting the tiles. + pub fn table_bytes(&self) -> usize { + self.tiles.len().saturating_mul(std::mem::size_of::>()) + } + /// Replace a tile wholesale (None frees it). pub fn set_tile(&mut self, tx: u32, ty: u32, data: Option) { let len = TILE_AREA * self.comps;