From 7deeaeeba1638353a0fe6abdcd534a198c144cb0 Mon Sep 17 00:00:00 2001 From: Unemars <62496697+Unemars@users.noreply.github.com> Date: Sun, 18 Oct 2026 01:16:29 +0200 Subject: [PATCH 1/5] Brush: large tips rasterize, accumulate and composite in parallel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A 2000 px soft tip is a 12 MP dab, and every dab ran on one thread: the tip's coverage (92 ms), its accumulation into the stroke's tiles (44 ms) and the composite of the dirty tiles into the layer (177 ms), about 300 ms a dab, so a stroke across a 24 MP photo lagged by a quarter second per frame. Photoshop keeps such strokes fluid by spreading them over the cores. Each stage is independent per row (the round tip's coverage) or per tile (the accumulation, the composite), so they now run on the thread pool from 256² pixels of work up, to the same pixels: the per-pixel maths is untouched, the dither and Dissolve hash positions, and a test renders a 700 px soft stroke, a Dissolve stroke and a per-dab-colour stroke (with a selection, 8-bit) both ways and compares every pixel. Below the threshold, and on the web, nothing changes. The composite's writes to the layer stay in order; its tiles are composited in batches so the pending regions stay small. `examples/big_dab_bench.rs` prints the stages of one dab. On a loaded 16-thread machine the 12 MP dab went from about 300 ms to 100–140 ms; the hard 2000 px tip from 75 to 35 ms. Co-Authored-By: Claude Fable 5.1 --- crates/paint/Cargo.toml | 4 + crates/paint/examples/big_dab_bench.rs | 44 ++++ crates/paint/src/brush_tests.rs | 53 +++++ crates/paint/src/render.rs | 307 ++++++++++++++++--------- 4 files changed, 297 insertions(+), 111 deletions(-) create mode 100644 crates/paint/examples/big_dab_bench.rs diff --git a/crates/paint/Cargo.toml b/crates/paint/Cargo.toml index afb9a196d00..4f4ca359e6c 100644 --- a/crates/paint/Cargo.toml +++ b/crates/paint/Cargo.toml @@ -13,5 +13,9 @@ photocraft-color = { workspace = true } photocraft-raster = { workspace = true } serde = { workspace = true } +# Large tips rasterize, accumulate and composite in parallel (the same pixels as serially). +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +rayon = { workspace = true } + [dev-dependencies] serde_json = { workspace = true } diff --git a/crates/paint/examples/big_dab_bench.rs b/crates/paint/examples/big_dab_bench.rs new file mode 100644 index 00000000000..a31265224ca --- /dev/null +++ b/crates/paint/examples/big_dab_bench.rs @@ -0,0 +1,44 @@ +//! Where a large brush's time goes: one dab of a 2000 px tip, by stage. +//! `cargo run --release -p photocraft-paint --example big_dab_bench [size] [hardness]` +use photocraft_color::PixelFormat; +use photocraft_geom::Rect; +use photocraft_paint::{BrushContext, BrushSettings, Dab, StrokePoint, StrokeRenderer}; +use photocraft_raster::Surface; +use std::time::Instant; + +fn main() { + let args: Vec = std::env::args().collect(); + let size: f32 = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(2000.0); + let hardness: f32 = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(0.0); + let brush = BrushSettings { size, hardness, spacing: 0.25, color: [1.0, 0.0, 0.0, 1.0], ..Default::default() }; + let fmt = PixelFormat::RGBA8; + let mut pre = Surface::new(fmt); + pre.fill_rect(Rect::new(0, 0, 4928, 3280), &[0.5, 0.5, 0.5, 1.0]); + let mut target = pre.clone(); + // Stage 1: the tip's coverage alone. + let ctx = BrushContext::new(&brush); + let dab = Dab::round(photocraft_geom::Point::new(2464.0, 1640.0), size / 2.0, 1.0); + let rect = ctx.dab_rect(&dab, false); + let mut cov = Vec::new(); + let t = Instant::now(); + ctx.rasterize(&dab, false, rect, &mut cov); + let raster = t.elapsed(); + println!("tip {size} px, hardness {hardness}: dab rect {}x{} = {:.1} MP", rect.width(), rect.height(), rect.width() as f64 * rect.height() as f64 / 1e6); + println!(" rasterize (coverage): {:>7.1} ms", raster.as_secs_f64() * 1e3); + // Stage 2+3: push through the renderer (rasterize + accumulate), then composite. + let mut r = StrokeRenderer::new(&brush, Some(fmt), 1.0); + let t = Instant::now(); + // Two points a pixel apart: the generator places the first dab at once (a lone point waits). + r.push(&[StrokePoint::new(2464.0, 1640.0, 1.0), StrokePoint::new(2465.0, 1640.0, 1.0)]); + let push = t.elapsed(); + println!(" push (rasterize+accumulate): {:>5.1} ms (accumulate ≈ {:.1} ms)", push.as_secs_f64() * 1e3, push.saturating_sub(raster).as_secs_f64() * 1e3); + let t = Instant::now(); + let dmg = r.composite(&pre, &mut target, None, false, false); + let comp = t.elapsed(); + println!(" composite (dirty tiles): {:>7.1} ms over {}x{}", comp.as_secs_f64() * 1e3, dmg.width(), dmg.height()); + // A second dab half a spacing away, as a stroke does: the same again. + let t = Instant::now(); + r.push(&[StrokePoint::new(2464.0 + f64::from(size) * 0.25, 1640.0, 1.0), StrokePoint::new(2466.0 + f64::from(size) * 0.25, 1640.0, 1.0)]); + let dmg = r.composite(&pre, &mut target, None, false, false); + println!(" next dab push+composite: {:>7.1} ms over {}x{}", t.elapsed().as_secs_f64() * 1e3, dmg.width(), dmg.height()); +} diff --git a/crates/paint/src/brush_tests.rs b/crates/paint/src/brush_tests.rs index d0d7de41109..90e1e64f500 100644 --- a/crates/paint/src/brush_tests.rs +++ b/crates/paint/src/brush_tests.rs @@ -1493,3 +1493,56 @@ fn an_aliased_stroke_at_partial_opacity_is_one_flat_colour() { assert_eq!(s.rgba(x, 5), first, "pixel {x} of the Pencil line"); } } + +/// Large tips rasterize, accumulate and composite in parallel (rows of a dab, tiles of a stroke); +/// the pixels are the ones the serial path gives, with 8-bit dithering, a selection, Dissolve and +/// per-dab colour included. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn large_tips_render_the_same_in_parallel_and_serially() { + let mut sel = Surface::new(PixelFormat::GRAY8); + sel.fill_rect(Rect::new(0, 0, 900, 700), &[1.0]); + sel.fill_rect(Rect::new(300, 0, 400, 700), &[0.0]); + let strokes: Vec<(BrushSettings, Vec)> = vec![ + (BrushSettings { size: 700.0, hardness: 0.0, flow: 0.6, color: [0.9, 0.2, 0.1, 1.0], ..brush() }, line(200.0, 700.0, 350.0)), + ( + BrushSettings { size: 420.0, hardness: 1.0, opacity: 0.5, mode: BlendMode::Dissolve, color: [0.1, 0.5, 0.9, 1.0], ..brush() }, + line(150.0, 750.0, 300.0), + ), + ( + BrushSettings { + size: 500.0, + hardness: 0.3, + color_dynamics: ColorDynamics { enabled: true, hue_jitter: 0.5, per_tip: true, ..Default::default() }, + color: [0.2, 0.8, 0.3, 1.0], + ..brush() + }, + line(100.0, 800.0, 400.0), + ), + ]; + let render = |parallel_from: usize| -> Vec> { + crate::render::set_parallel_min_pixels(parallel_from); + strokes + .iter() + .map(|(b, pts)| { + let mut s = Surface::new(PixelFormat::RGBA8); + s.fill_rect(Rect::new(0, 0, 900, 700), &[0.5, 0.5, 0.5, 1.0]); + let (mut with_sel, mut plain) = (s.clone(), s); + render_stroke(&mut with_sel, b, pts, Some(&sel), false, 1.0); + render_stroke(&mut plain, b, pts, None, false, 1.0); + let mut px = with_sel.read_region(Rect::new(0, 0, 900, 700)); + px.extend(plain.read_region(Rect::new(0, 0, 900, 700))); + px + }) + .collect() + }; + let parallel = render(0); + let serial = render(usize::MAX); + crate::render::set_parallel_min_pixels(256 * 256); + for (i, (p, s)) in parallel.iter().zip(&serial).enumerate() { + assert_eq!(p.len(), s.len()); + let diff = p.iter().zip(s).filter(|(a, b)| a != b).count(); + assert_eq!(diff, 0, "stroke {i}: {diff} pixels differ between the parallel and the serial render"); + assert!(p.iter().any(|v| (*v - 0.5).abs() > 0.1), "stroke {i} painted something"); + } +} diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rs index 5f59aafad18..b0fa7d64eab 100644 --- a/crates/paint/src/render.rs +++ b/crates/paint/src/render.rs @@ -39,6 +39,66 @@ fn dither8(px: &mut [f32], x: i32, y: i32) { /// Edge of a stroke-buffer tile. pub const COV_TILE: i32 = 64; + +/// Work on at least this many pixels runs in parallel (rows of a dab, tiles of a stroke): below +/// it the threads cost more than they save. A large soft tip is tens of megapixels per dab, and +/// every stage of it is independent per row or tile, so the pixels come out the same. +#[cfg(not(target_arch = "wasm32"))] +static PARALLEL_MIN_PIXELS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(256 * 256); + +/// Whether `pixels` of independent work are worth the thread pool (never on the web). +fn parallel(pixels: usize) -> bool { + #[cfg(not(target_arch = "wasm32"))] + { + pixels >= PARALLEL_MIN_PIXELS.load(std::sync::atomic::Ordering::Relaxed) + } + #[cfg(target_arch = "wasm32")] + { + let _ = pixels; + false + } +} + +/// Tests: the pixel count from which work runs in parallel (`usize::MAX` keeps everything serial). +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) fn set_parallel_min_pixels(n: usize) { + PARALLEL_MIN_PIXELS.store(n, std::sync::atomic::Ordering::Relaxed); +} + +/// `f(row index, row)` over the rows of `out` (`w` values each), in parallel when worth it. +fn for_each_row(out: &mut [f32], w: usize, f: impl Fn(usize, &mut [f32]) + Sync) { + if w == 0 { + return; + } + #[cfg(not(target_arch = "wasm32"))] + if parallel(out.len()) { + use rayon::prelude::*; + out.par_chunks_exact_mut(w).enumerate().for_each(|(i, row)| f(i, row)); + return; + } + out.chunks_exact_mut(w).enumerate().for_each(|(i, row)| f(i, row)); +} + +/// `f` over `items`, in parallel when `pixels` are worth it. +fn for_each_item(items: &mut [T], pixels: usize, f: impl Fn(&mut T) + Sync) { + #[cfg(not(target_arch = "wasm32"))] + if parallel(pixels) { + use rayon::prelude::*; + items.par_iter_mut().for_each(&f); + return; + } + items.iter_mut().for_each(&f); +} + +/// `f` over `items`, collecting its results in order, in parallel when `pixels` are worth it. +fn map_items(items: &[T], pixels: usize, f: impl Fn(&T) -> R + Sync) -> Vec { + #[cfg(not(target_arch = "wasm32"))] + if parallel(pixels) { + use rayon::prelude::*; + return items.par_iter().map(&f).collect(); + } + items.iter().map(&f).collect() +} /// Computed tips with a smaller radius (in pixels) are rasterised by area, not at pixel centres. const SMALL_TIP_RADIUS: f32 = 3.0; /// Sub-pixel sample offsets (a 4×4 grid) for the area coverage of small tips. @@ -466,61 +526,71 @@ impl CoverageMap { let (t0x, t0y) = (rect.x0.div_euclid(COV_TILE), rect.y0.div_euclid(COV_TILE)); let (t1x, t1y) = ((rect.x1 - 1).div_euclid(COV_TILE), (rect.y1 - 1).div_euclid(COV_TILE)); let want_col = color.is_some() && nc > 0; + // The tiles this dab touches (a tile with no value in it is skipped), each independent of + // the others: a large dab's tiles accumulate in parallel, to the same values. + let mut keys: Vec<((i32, i32), Rect)> = Vec::new(); for ty in t0y..=t1y { for tx in t0x..=t1x { let tr = Rect::new(tx * COV_TILE, ty * COV_TILE, (tx + 1) * COV_TILE, (ty + 1) * COV_TILE).intersect(&rect); if tr.is_empty() { continue; } - // Skip tiles this dab doesn't touch. - let any = (tr.y0..tr.y1).any(|y| { - let row = (y - rect.y0) as usize * w; - vals[row + (tr.x0 - rect.x0) as usize..row + (tr.x1 - rect.x0) as usize].iter().any(|&v| v > 0.0) - }); - if !any { - continue; - } - let tile = self.tiles.entry((tx, ty)).or_insert_with(|| CovTile { - cov: vec![0.0; (COV_TILE * COV_TILE) as usize], - depth: Vec::new(), - col: if want_col { vec![0.0; (COV_TILE * COV_TILE) as usize * nc] } else { Vec::new() }, - }); - if want_col && tile.col.is_empty() { - tile.col = vec![0.0; (COV_TILE * COV_TILE) as usize * nc]; - } - if depth.is_some() && tile.depth.is_empty() { - tile.depth = vec![0.0; (COV_TILE * COV_TILE) as usize]; - } - self.dirty.insert((tx, ty)); - for y in tr.y0..tr.y1 { - let row = (y - rect.y0) as usize * w; - let trow = ((y - ty * COV_TILE) * COV_TILE) as usize; - for x in tr.x0..tr.x1 { - let v = vals[row + (x - rect.x0) as usize]; - if v <= 0.0 { - continue; - } - let ti = trow + (x - tx * COV_TILE) as usize; - if let (Some(dv), Some(slot)) = (depth.and_then(|dp| dp.get(row + (x - rect.x0) as usize)), tile.depth.get_mut(ti)) { - *slot = slot.max(*dv); - } - let c = tile.cov[ti]; - let nv = if ceil > c { c + v * (ceil - c) } else { c }; - if nv <= c { - continue; - } - if let (true, Some(col)) = (want_col, color) { - let k = if c < 1.0 { (nv - c) / (1.0 - c) } else { 0.0 }; - let p = &mut tile.col[ti * nc..(ti + 1) * nc]; - for i in 0..nc { - p[i] = col[i] * k + p[i] * (1.0 - k); - } - } - tile.cov[ti] = nv; - } - } + keys.push(((tx, ty), tr)); } } + let touched = map_items(&keys, keys.len() * (COV_TILE * COV_TILE) as usize, |(_, tr)| { + (tr.y0..tr.y1).any(|y| { + let row = (y - rect.y0) as usize * w; + vals[row + (tr.x0 - rect.x0) as usize..row + (tr.x1 - rect.x0) as usize].iter().any(|&v| v > 0.0) + }) + }); + let keys: Vec<((i32, i32), Rect)> = keys.into_iter().zip(touched).filter(|(_, t)| *t).map(|(k, _)| k).collect(); + for (key, _) in &keys { + let tile = self.tiles.entry(*key).or_insert_with(|| CovTile { + cov: vec![0.0; (COV_TILE * COV_TILE) as usize], + depth: Vec::new(), + col: if want_col { vec![0.0; (COV_TILE * COV_TILE) as usize * nc] } else { Vec::new() }, + }); + if want_col && tile.col.is_empty() { + tile.col = vec![0.0; (COV_TILE * COV_TILE) as usize * nc]; + } + if depth.is_some() && tile.depth.is_empty() { + tile.depth = vec![0.0; (COV_TILE * COV_TILE) as usize]; + } + self.dirty.insert(*key); + } + let wanted: HashMap<(i32, i32), Rect> = keys.into_iter().collect(); + let mut tiles: Vec<(Rect, (i32, i32), &mut CovTile)> = self.tiles.iter_mut().filter_map(|(k, t)| Some((*wanted.get(k)?, *k, t))).collect(); + for_each_item(&mut tiles, wanted.len() * (COV_TILE * COV_TILE) as usize, |(tr, (tx, ty), tile)| { + let (tx, ty) = (*tx, *ty); + for y in tr.y0..tr.y1 { + let row = (y - rect.y0) as usize * w; + let trow = ((y - ty * COV_TILE) * COV_TILE) as usize; + for x in tr.x0..tr.x1 { + let v = vals[row + (x - rect.x0) as usize]; + if v <= 0.0 { + continue; + } + let ti = trow + (x - tx * COV_TILE) as usize; + if let (Some(dv), Some(slot)) = (depth.and_then(|dp| dp.get(row + (x - rect.x0) as usize)), tile.depth.get_mut(ti)) { + *slot = slot.max(*dv); + } + let c = tile.cov[ti]; + let nv = if ceil > c { c + v * (ceil - c) } else { c }; + if nv <= c { + continue; + } + if let (true, Some(col)) = (want_col, color) { + let k = if c < 1.0 { (nv - c) / (1.0 - c) } else { 0.0 }; + let p = &mut tile.col[ti * nc..(ti + 1) * nc]; + for i in 0..nc { + p[i] = col[i] * k + p[i] * (1.0 - k); + } + } + tile.cov[ti] = nv; + } + } + }); } fn take_dirty(&mut self) -> Vec<(i32, i32)> { @@ -989,75 +1059,88 @@ impl StrokeRenderer { // colour, as in Photoshop, not grain that a tolerance-0 Magic Wand or Paint Bucket trips on. let dither = fmt.sample == SampleType::U8 && !b.aliased; let mut dmg = Rect::EMPTY; - let mut region = Vec::new(); - for (tx, ty) in keys { - let Some(tile) = self.cov.tiles.get(&(tx, ty)) else { continue }; - let tr = Rect::new(tx * COV_TILE, ty * COV_TILE, (tx + 1) * COV_TILE, (ty + 1) * COV_TILE).intersect(&bounds); - if tr.is_empty() { - continue; - } - pre.read_region_into(tr, &mut region); - let sel = selection.map(|s| (s.channels(), s.read_region(tr))); - let w = tr.width() as usize; - for y in tr.y0..tr.y1 { - for x in tr.x0..tr.x1 { - let ti = ((y - ty * COV_TILE) * COV_TILE + (x - tx * COV_TILE)) as usize; - let c = tile.cov[ti]; - if c <= 0.0 { - continue; - } - let i = (y - tr.y0) as usize * w + (x - tr.x0) as usize; - let m = self.ctx.stroke_mask_wet(c, tile.depth.get(ti).copied(), self.dual.as_ref().map(|d| d.get(x, y)), x, y); - let s = sel.as_ref().map_or(1.0, |(sc, v)| v[i * sc]); - let mut k = (m * opacity * s).min(1.0); - if k <= 0.0 { - continue; - } - if b.mode == BlendMode::Dissolve { - k = if hash2(x, y, b.seed) < k { 1.0 } else { 0.0 }; - if k == 0.0 { + // Each tile composites on its own (a large stroke's tiles in parallel, to the same + // pixels); the writes to the target go one by one. Batches keep the pending regions small. + const BATCH: usize = 256; + for batch in keys.chunks(BATCH) { + let regions: Vec<(Rect, Vec)> = map_items(batch, batch.len() * (COV_TILE * COV_TILE) as usize, |&(tx, ty)| { + let Some(tile) = self.cov.tiles.get(&(tx, ty)) else { return (Rect::EMPTY, Vec::new()) }; + let tr = Rect::new(tx * COV_TILE, ty * COV_TILE, (tx + 1) * COV_TILE, (ty + 1) * COV_TILE).intersect(&bounds); + if tr.is_empty() { + return (Rect::EMPTY, Vec::new()); + } + let mut region = Vec::new(); + pre.read_region_into(tr, &mut region); + let sel = selection.map(|s| (s.channels(), s.read_region(tr))); + // Per-dab colour rewrites the source per pixel: a copy per tile. + let mut src = src; + let w = tr.width() as usize; + for y in tr.y0..tr.y1 { + for x in tr.x0..tr.x1 { + let ti = ((y - ty * COV_TILE) * COV_TILE + (x - tx * COV_TILE)) as usize; + let c = tile.cov[ti]; + if c <= 0.0 { continue; } - } - let px = &mut region[i * n..(i + 1) * n]; - if b.erase { - if let (Some(a), false) = (a_idx, lock_transparency) { - px[a] *= 1.0 - k; + let i = (y - tr.y0) as usize * w + (x - tr.x0) as usize; + let m = self.ctx.stroke_mask_wet(c, tile.depth.get(ti).copied(), self.dual.as_ref().map(|d| d.get(x, y)), x, y); + let s = sel.as_ref().map_or(1.0, |(sc, v)| v[i * sc]); + let mut k = (m * opacity * s).min(1.0); + if k <= 0.0 { + continue; + } + if b.mode == BlendMode::Dissolve { + k = if hash2(x, y, b.seed) < k { 1.0 } else { 0.0 }; + if k == 0.0 { + continue; + } + } + let px = &mut region[i * n..(i + 1) * n]; + if b.erase { + if let (Some(a), false) = (a_idx, lock_transparency) { + px[a] *= 1.0 - k; + } + if dither { + dither8(px, x, y); + } + continue; + } + if lock_transparency && a_idx.is_some_and(|a| px[a] <= 0.0) { + continue; + } + if self.per_dab_color && !tile.col.is_empty() { + let p = &tile.col[ti * nc..(ti + 1) * nc]; + for ch in 0..nc { + src[ch] = p[ch] / c; + } + } + if matches!(b.mode, BlendMode::Normal | BlendMode::Dissolve) { + over_native(&fmt, px, &src[..n], k, lock_transparency); + } else { + let d = to_rgba(&fmt, px); + let sr = to_rgba(&fmt, &src[..n]); + let mut o = photocraft_color::blend::composite(b.mode, d, sr, k); + if lock_transparency { + o[3] = d[3]; + } + let mut enc = [0.0f32; 8]; + from_rgba_into(&fmt, o, &mut enc); + px.copy_from_slice(&enc[..n]); } if dither { dither8(px, x, y); } - continue; - } - if lock_transparency && a_idx.is_some_and(|a| px[a] <= 0.0) { - continue; - } - if self.per_dab_color && !tile.col.is_empty() { - let p = &tile.col[ti * nc..(ti + 1) * nc]; - for ch in 0..nc { - src[ch] = p[ch] / c; - } - } - if matches!(b.mode, BlendMode::Normal | BlendMode::Dissolve) { - over_native(&fmt, px, &src[..n], k, lock_transparency); - } else { - let d = to_rgba(&fmt, px); - let sr = to_rgba(&fmt, &src[..n]); - let mut o = photocraft_color::blend::composite(b.mode, d, sr, k); - if lock_transparency { - o[3] = d[3]; - } - let mut enc = [0.0f32; 8]; - from_rgba_into(&fmt, o, &mut enc); - px.copy_from_slice(&enc[..n]); - } - if dither { - dither8(px, x, y); } } + (tr, region) + }); + for (tr, region) in regions { + if tr.is_empty() { + continue; + } + target.write_region(tr, ®ion); + dmg = dmg.union(&tr); } - target.write_region(tr, ®ion); - dmg = dmg.union(&tr); } if all { bounds } else { dmg } } @@ -1091,23 +1174,25 @@ fn rasterize_round(d: &Dab, rect: Rect, out: &mut [f32], hardness: f32, aliased: let w = rect.width() as usize; let reach = if aliased { rm } else { tip_reach(rm, hardness).max(rm) }; let reach2 = (reach + 0.5) * (reach + 0.5); - for (yy, row) in out.chunks_exact_mut(w).enumerate() { + let alpha = d.alpha; + // Rows are independent: a large tip's rows run in parallel, to the same values. + for_each_row(out, w, |yy, row| { let dy = (rect.y0 + yy as i32) as f32 + 0.5 - cy; if aliased { for (xx, dst) in row.iter_mut().enumerate() { let dx = (rect.x0 + xx as i32) as f32 + 0.5 - cx; let d2 = (dx * ro).powi(2) + dy * dy; - *dst = if d2 < reach2 && d2.sqrt() <= rm { d.alpha } else { 0.0 }; + *dst = if d2 < reach2 && d2.sqrt() <= rm { alpha } else { 0.0 }; } } else { for (xx, dst) in row.iter_mut().enumerate() { let dx = (rect.x0 + xx as i32) as f32 + 0.5 - cx; let d2 = (dx * ro).powi(2) + dy * dy; let val = if d2 >= reach2 { 0.0 } else { tip_falloff(d2.sqrt(), rm, hardness) }; - *dst = if val <= 0.0 { 0.0 } else { val * d.alpha }; + *dst = if val <= 0.0 { 0.0 } else { val * alpha }; } } - } + }); } #[cfg(test)] From 2a003d51ea11a2dbe7cbdfb1750aa87ea4087513 Mon Sep 17 00:00:00 2001 From: Unemars <62496697+Unemars@users.noreply.github.com> Date: Sun, 18 Oct 2026 01:24:26 +0200 Subject: [PATCH 2/5] Cargo.lock: rayon for photocraft-paint Co-Authored-By: Claude Fable 5.1 --- Cargo.lock | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.lock b/Cargo.lock index 43a4a44f652..2ed70ab879c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4913,6 +4913,7 @@ dependencies = [ "photocraft-color", "photocraft-geom", "photocraft-raster", + "rayon", "serde", "serde_json", ] From 4b06b0cc5a311ed595aaa3c0405d19ebca945d67 Mon Sep 17 00:00:00 2001 From: Unemars <62496697+Unemars@users.noreply.github.com> Date: Sun, 18 Oct 2026 15:53:07 +0200 Subject: [PATCH 3/5] Brush: small tips keep their speed next to the parallel large ones MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The first version slowed small brushes by about a third (reviewer's measurement: a 20 px soft zigzag 856 → 1736 ms over 6000 dabs), for three reasons, all gone: - `CoverageMap::accumulate` looked the dab's tiles up by walking the whole tile map (`iter_mut().filter_map`) on every dab, so a long stroke's thousands of tiles taxed every small dab. The touched tiles now leave the map (`remove`), accumulate, and go back: one to four lookups for a small tip. - The composite allocated a fresh 64 KB buffer per tile per frame (6872 `brk` calls per 3000 dabs against main's 542): the heap grew and trimmed every frame. The buffers live in a pool on the renderer (`RegionPool`, emptied on clone) and are reused from composite to composite. - The row / tile bodies passed as closures to the helpers cost a 20 px tip's `rasterize` half as much again (7.5 → 11.6 µs). They are `#[inline(always)]` steps on `Copy` structs (`RoundTip::row`, `DabValues::tile`), called from plain loops below the threshold and from rayon above it; `rasterize` is back to main's time. `examples/stroke_bench.rs` times a long zigzag stroke of one tip, push + composite per point (best of four, loaded machine; main → now): 20 px 667 → 706 ms, 50 px 1805 → 1734 ms, 150 px 11 017 → 5163 ms. Comments: the per-tile copy of `src` in the composite is the intended reading (a tile without per-dab colour only occurs in strokes without per-dab colour, where `src` is never rewritten), and `set_parallel_min_pixels` changes a process-wide static harmlessly. `parallel()` and the helpers' `pixels` are `cfg`'d so the wasm build has no unused warnings. Co-Authored-By: Claude Fable 5.1 --- crates/paint/examples/stroke_bench.rs | 64 ++++++ crates/paint/src/render.rs | 280 +++++++++++++++++--------- 2 files changed, 247 insertions(+), 97 deletions(-) create mode 100644 crates/paint/examples/stroke_bench.rs diff --git a/crates/paint/examples/stroke_bench.rs b/crates/paint/examples/stroke_bench.rs new file mode 100644 index 00000000000..2a6b59cfa76 --- /dev/null +++ b/crates/paint/examples/stroke_bench.rs @@ -0,0 +1,64 @@ +//! A long stroke of one tip, timed per dab: a zigzag over a 4928×3280 RGBA8 document that sweeps +//! the whole page, `push` then `composite` after every point, as painting does per frame. Small +//! tips are the everyday case; a long stroke grows the stroke's tile map to thousands of tiles, +//! and the time per dab must not grow with it. +//! `cargo run --release -p photocraft-paint --example stroke_bench -- [size] [hardness] [dabs]` +use photocraft_color::PixelFormat; +use photocraft_geom::Rect; +use photocraft_paint::{BrushSettings, StrokePoint, StrokeRenderer}; +use photocraft_raster::Surface; +use std::time::Instant; + +fn main() { + let args: Vec = std::env::args().collect(); + let size: f32 = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(20.0); + let hardness: f32 = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(0.0); + let dabs: usize = args.get(3).and_then(|s| s.parse().ok()).unwrap_or(6000); + let (w, h) = (4928.0f64, 3280.0f64); + let brush = BrushSettings { size, hardness, spacing: 0.25, color: [1.0, 0.0, 0.0, 1.0], ..Default::default() }; + let fmt = PixelFormat::RGBA8; + let mut pre = Surface::new(fmt); + pre.fill_rect(Rect::new(0, 0, w as i32, h as i32), &[0.5, 0.5, 0.5, 1.0]); + let mut target = pre.clone(); + // Segments from the top margin to the bottom one and back, advancing across the width so that + // `dabs` dabs at the brush's spacing sweep the document once. + let step = f64::from(size) * 0.25; + let margin = f64::from(size); + let span = h - 2.0 * margin; + let segments = ((dabs as f64 * step) / span).ceil().max(1.0) as usize; + let dx = (w - 2.0 * margin) / segments as f64; + let mut r = StrokeRenderer::new(&brush, Some(fmt), 1.0); + let (mut t_push, mut t_comp) = (0.0f64, 0.0f64); + let t_all = Instant::now(); + let mut pos = (margin, margin); + r.push(&[StrokePoint::new(pos.0, pos.1, 1.0)]); + let mut pushes = 0usize; + 'stroke: for seg in 0..segments { + let (x0, y0) = pos; + let (x1, y1) = (margin + (seg + 1) as f64 * dx, if seg % 2 == 0 { h - margin } else { margin }); + let n = (((x1 - x0).powi(2) + (y1 - y0).powi(2)).sqrt() / step).ceil().max(1.0) as usize; + for i in 1..=n { + let f = i as f64 / n as f64; + let t = Instant::now(); + r.push(&[StrokePoint::new(x0 + (x1 - x0) * f, y0 + (y1 - y0) * f, 1.0)]); + let tp = t.elapsed().as_secs_f64(); + r.composite(&pre, &mut target, None, false, false); + t_comp += t.elapsed().as_secs_f64() - tp; + t_push += tp; + pushes += 1; + if r.dab_count() >= dabs { + break 'stroke; + } + } + pos = (x1, y1); + } + let total = t_all.elapsed().as_secs_f64(); + let placed = r.dab_count(); + println!( + "tip {size} px, hardness {hardness}: {placed} dabs in {pushes} pushes over {segments} segments: {:.0} ms (push {:.0}, composite {:.0}), {:.1} µs per dab", + total * 1e3, + t_push * 1e3, + t_comp * 1e3, + total * 1e6 / placed.max(1) as f64 + ); +} diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rs index b0fa7d64eab..f58594c1853 100644 --- a/crates/paint/src/render.rs +++ b/crates/paint/src/render.rs @@ -46,39 +46,22 @@ pub const COV_TILE: i32 = 64; #[cfg(not(target_arch = "wasm32"))] static PARALLEL_MIN_PIXELS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(256 * 256); -/// Whether `pixels` of independent work are worth the thread pool (never on the web). +/// Whether `pixels` of independent work are worth the thread pool (the web has none: there every +/// stage takes its serial path). +#[cfg(not(target_arch = "wasm32"))] fn parallel(pixels: usize) -> bool { - #[cfg(not(target_arch = "wasm32"))] - { - pixels >= PARALLEL_MIN_PIXELS.load(std::sync::atomic::Ordering::Relaxed) - } - #[cfg(target_arch = "wasm32")] - { - let _ = pixels; - false - } + pixels >= PARALLEL_MIN_PIXELS.load(std::sync::atomic::Ordering::Relaxed) } /// Tests: the pixel count from which work runs in parallel (`usize::MAX` keeps everything serial). +/// The static is process-wide, so brush tests on other threads see the change too; that is +/// harmless, because every stage gives the same pixels serially and in parallel (the point of +/// the test that uses this), so no test can tell which way it ran. #[cfg(all(test, not(target_arch = "wasm32")))] pub(crate) fn set_parallel_min_pixels(n: usize) { PARALLEL_MIN_PIXELS.store(n, std::sync::atomic::Ordering::Relaxed); } -/// `f(row index, row)` over the rows of `out` (`w` values each), in parallel when worth it. -fn for_each_row(out: &mut [f32], w: usize, f: impl Fn(usize, &mut [f32]) + Sync) { - if w == 0 { - return; - } - #[cfg(not(target_arch = "wasm32"))] - if parallel(out.len()) { - use rayon::prelude::*; - out.par_chunks_exact_mut(w).enumerate().for_each(|(i, row)| f(i, row)); - return; - } - out.chunks_exact_mut(w).enumerate().for_each(|(i, row)| f(i, row)); -} - /// `f` over `items`, in parallel when `pixels` are worth it. fn for_each_item(items: &mut [T], pixels: usize, f: impl Fn(&mut T) + Sync) { #[cfg(not(target_arch = "wasm32"))] @@ -87,6 +70,8 @@ fn for_each_item(items: &mut [T], pixels: usize, f: impl Fn(&mut T) + S items.par_iter_mut().for_each(&f); return; } + #[cfg(target_arch = "wasm32")] + let _ = pixels; items.iter_mut().for_each(&f); } @@ -97,6 +82,8 @@ fn map_items(items: &[T], pixels: usize, f: impl Fn(&T) -> R + use rayon::prelude::*; return items.par_iter().map(&f).collect(); } + #[cfg(target_arch = "wasm32")] + let _ = pixels; items.iter().map(&f).collect() } /// Computed tips with a smaller radius (in pixels) are rasterised by area, not at pixel centres. @@ -544,53 +531,44 @@ impl CoverageMap { vals[row + (tr.x0 - rect.x0) as usize..row + (tr.x1 - rect.x0) as usize].iter().any(|&v| v > 0.0) }) }); - let keys: Vec<((i32, i32), Rect)> = keys.into_iter().zip(touched).filter(|(_, t)| *t).map(|(k, _)| k).collect(); - for (key, _) in &keys { - let tile = self.tiles.entry(*key).or_insert_with(|| CovTile { - cov: vec![0.0; (COV_TILE * COV_TILE) as usize], - depth: Vec::new(), - col: if want_col { vec![0.0; (COV_TILE * COV_TILE) as usize * nc] } else { Vec::new() }, - }); - if want_col && tile.col.is_empty() { - tile.col = vec![0.0; (COV_TILE * COV_TILE) as usize * nc]; - } - if depth.is_some() && tile.depth.is_empty() { - tile.depth = vec![0.0; (COV_TILE * COV_TILE) as usize]; - } - self.dirty.insert(*key); - } - let wanted: HashMap<(i32, i32), Rect> = keys.into_iter().collect(); - let mut tiles: Vec<(Rect, (i32, i32), &mut CovTile)> = self.tiles.iter_mut().filter_map(|(k, t)| Some((*wanted.get(k)?, *k, t))).collect(); - for_each_item(&mut tiles, wanted.len() * (COV_TILE * COV_TILE) as usize, |(tr, (tx, ty), tile)| { - let (tx, ty) = (*tx, *ty); - for y in tr.y0..tr.y1 { - let row = (y - rect.y0) as usize * w; - let trow = ((y - ty * COV_TILE) * COV_TILE) as usize; - for x in tr.x0..tr.x1 { - let v = vals[row + (x - rect.x0) as usize]; - if v <= 0.0 { - continue; - } - let ti = trow + (x - tx * COV_TILE) as usize; - if let (Some(dv), Some(slot)) = (depth.and_then(|dp| dp.get(row + (x - rect.x0) as usize)), tile.depth.get_mut(ti)) { - *slot = slot.max(*dv); - } - let c = tile.cov[ti]; - let nv = if ceil > c { c + v * (ceil - c) } else { c }; - if nv <= c { - continue; - } - if let (true, Some(col)) = (want_col, color) { - let k = if c < 1.0 { (nv - c) / (1.0 - c) } else { 0.0 }; - let p = &mut tile.col[ti * nc..(ti + 1) * nc]; - for i in 0..nc { - p[i] = col[i] * k + p[i] * (1.0 - k); - } - } - tile.cov[ti] = nv; + // The touched tiles leave the map while they accumulate and go back after: the dab's cost + // follows the tiles under it (one to four for a small tip), not the size of the map, which a + // long stroke grows to thousands of tiles. + let n = (COV_TILE * COV_TILE) as usize; + let mut tiles: Vec<(Rect, (i32, i32), CovTile)> = keys + .into_iter() + .zip(touched) + .filter(|(_, t)| *t) + .map(|((key, tr), _)| { + let mut tile = self.tiles.remove(&key).unwrap_or_else(|| CovTile { cov: vec![0.0; n], depth: Vec::new(), col: Vec::new() }); + if want_col && tile.col.is_empty() { + tile.col = vec![0.0; n * nc]; } + if depth.is_some() && tile.depth.is_empty() { + tile.depth = vec![0.0; n]; + } + self.dirty.insert(key); + (tr, key, tile) + }) + .collect(); + let dab = DabValues { vals, rect, w, ceil, color: if want_col { color } else { None }, depth, nc }; + // The serial path stays a plain loop over an inlined step (see `rasterize_round`). + #[cfg(not(target_arch = "wasm32"))] + if parallel(tiles.len() * n) { + use rayon::prelude::*; + tiles.par_iter_mut().for_each(|(tr, key, tile)| dab.tile(*tr, *key, tile)); + } else { + for (tr, key, tile) in &mut tiles { + dab.tile(*tr, *key, tile); } - }); + } + #[cfg(target_arch = "wasm32")] + for (tr, key, tile) in &mut tiles { + dab.tile(*tr, *key, tile); + } + for (_, key, tile) in tiles { + self.tiles.insert(key, tile); + } } fn take_dirty(&mut self) -> Vec<(i32, i32)> { @@ -657,6 +635,55 @@ impl UnionLive { } } +/// One dab's coverage (`vals` over `rect`, `w` wide) as [`CoverageMap::accumulate`] adds it to +/// a tile: the dab's opacity ceiling, its colour when the stroke has per-dab colour (`nc` channels), +/// its Wet Edges depth. +#[derive(Clone, Copy)] +struct DabValues<'a> { + vals: &'a [f32], + rect: Rect, + w: usize, + ceil: f32, + color: Option<&'a [f32]>, + depth: Option<&'a [f32]>, + nc: usize, +} + +impl DabValues<'_> { + /// Adds the dab over `tr` (within tile `(tx, ty)`) to `tile`. + #[inline(always)] + fn tile(self, tr: Rect, (tx, ty): (i32, i32), tile: &mut CovTile) { + let DabValues { vals, rect, w, ceil, color, depth, nc } = self; + for y in tr.y0..tr.y1 { + let row = (y - rect.y0) as usize * w; + let trow = ((y - ty * COV_TILE) * COV_TILE) as usize; + for x in tr.x0..tr.x1 { + let v = vals[row + (x - rect.x0) as usize]; + if v <= 0.0 { + continue; + } + let ti = trow + (x - tx * COV_TILE) as usize; + if let (Some(dv), Some(slot)) = (depth.and_then(|dp| dp.get(row + (x - rect.x0) as usize)), tile.depth.get_mut(ti)) { + *slot = slot.max(*dv); + } + let c = tile.cov[ti]; + let nv = if ceil > c { c + v * (ceil - c) } else { c }; + if nv <= c { + continue; + } + if let Some(col) = color { + let k = if c < 1.0 { (nv - c) / (1.0 - c) } else { 0.0 }; + let p = &mut tile.col[ti * nc..(ti + 1) * nc]; + for i in 0..nc { + p[i] = col[i] * k + p[i] * (1.0 - k); + } + } + tile.cov[ti] = nv; + } + } + } +} + /// Incremental stroke rendering: feed points, composite dirty tiles from the pre-stroke pixels. #[derive(Clone, Debug)] pub struct StrokeRenderer { @@ -673,6 +700,19 @@ pub struct StrokeRenderer { dab_buf: Vec, dual_buf: Vec, all_dabs: Option>, + regions: RegionPool, +} + +/// The tile buffers [`StrokeRenderer::composite`] works in, kept from one composite to the next: +/// a small stroke's few tiles reuse theirs instead of growing and trimming the heap every frame +/// (that cost a 50 px stroke a third of its time). A clone starts with none. +#[derive(Debug, Default)] +struct RegionPool(Vec>); + +impl Clone for RegionPool { + fn clone(&self) -> Self { + Self::default() + } } impl StrokeRenderer { @@ -765,6 +805,7 @@ impl StrokeRenderer { dab_buf: Vec::new(), dual_buf: Vec::new(), all_dabs: None, + regions: RegionPool::default(), }) } Some(m) => { @@ -816,6 +857,7 @@ impl StrokeRenderer { dab_buf: Vec::new(), dual_buf: Vec::new(), all_dabs: None, + regions: RegionPool::default(), } } @@ -946,6 +988,7 @@ impl StrokeRenderer { dab_buf: dabs, dual_buf: duals, all_dabs: None, + regions: RegionPool::default(), }; t.raster_pending(); // Tiles whose coverage the tail doesn't change still composite the same: redraw them all. @@ -1059,20 +1102,29 @@ impl StrokeRenderer { // colour, as in Photoshop, not grain that a tolerance-0 Magic Wand or Paint Bucket trips on. let dither = fmt.sample == SampleType::U8 && !b.aliased; let mut dmg = Rect::EMPTY; - // Each tile composites on its own (a large stroke's tiles in parallel, to the same - // pixels); the writes to the target go one by one. Batches keep the pending regions small. + // Each tile composites into a buffer of its own (a large stroke's tiles in parallel, to + // the same pixels); the writes to the target go one by one, in order. Batches keep the + // pending buffers few, and the pool keeps them from one composite to the next. const BATCH: usize = 256; + let mut pool = std::mem::take(&mut self.regions.0); for batch in keys.chunks(BATCH) { - let regions: Vec<(Rect, Vec)> = map_items(batch, batch.len() * (COV_TILE * COV_TILE) as usize, |&(tx, ty)| { - let Some(tile) = self.cov.tiles.get(&(tx, ty)) else { return (Rect::EMPTY, Vec::new()) }; + let mut items: Vec<((i32, i32), Rect, Vec)> = batch.iter().map(|&key| (key, Rect::EMPTY, pool.pop().unwrap_or_default())).collect(); + for_each_item(&mut items, batch.len() * (COV_TILE * COV_TILE) as usize, |(key, done, region)| { + let (tx, ty) = *key; + let Some(tile) = self.cov.tiles.get(&(tx, ty)) else { return }; let tr = Rect::new(tx * COV_TILE, ty * COV_TILE, (tx + 1) * COV_TILE, (ty + 1) * COV_TILE).intersect(&bounds); if tr.is_empty() { - return (Rect::EMPTY, Vec::new()); + return; } - let mut region = Vec::new(); - pre.read_region_into(tr, &mut region); + pre.read_region_into(tr, region); let sel = selection.map(|s| (s.channels(), s.read_region(tr))); - // Per-dab colour rewrites the source per pixel: a copy per tile. + // Per-dab colour rewrites the source per pixel, so each tile works on its own copy + // that starts from the brush colour. (Before the tiles ran in parallel, one `src` + // carried over from tile to tile; a tile without per-dab colour then painted with + // whatever colour the previous tile's last pixel had left in it. Such a tile only + // occurs when the stroke has no per-dab colour at all, and then `src` is never + // rewritten, so the pixels are the same either way; the copy per tile is the + // intended reading.) let mut src = src; let w = tr.width() as usize; for y in tr.y0..tr.y1 { @@ -1132,16 +1184,17 @@ impl StrokeRenderer { } } } - (tr, region) + *done = tr; }); - for (tr, region) in regions { - if tr.is_empty() { - continue; + for (_, tr, region) in items { + if !tr.is_empty() { + target.write_region(tr, ®ion); + dmg = dmg.union(&tr); } - target.write_region(tr, ®ion); - dmg = dmg.union(&tr); + pool.push(region); } } + self.regions.0 = pool; if all { bounds } else { dmg } } } @@ -1172,27 +1225,60 @@ fn rasterize_round(d: &Dab, rect: Rect, out: &mut [f32], hardness: f32, aliased: let ro = d.roundness.max(0.5 / d.radius).min(1.0); let rm = (d.radius * ro).max(0.5); let w = rect.width() as usize; + if w == 0 { + return; + } let reach = if aliased { rm } else { tip_reach(rm, hardness).max(rm) }; - let reach2 = (reach + 0.5) * (reach + 0.5); - let alpha = d.alpha; - // Rows are independent: a large tip's rows run in parallel, to the same values. - for_each_row(out, w, |yy, row| { - let dy = (rect.y0 + yy as i32) as f32 + 0.5 - cy; - if aliased { + let tip = RoundTip { cx, cy, ro, rm, reach2: (reach + 0.5) * (reach + 0.5), hardness, alpha: d.alpha, aliased, x0: rect.x0, y0: rect.y0 }; + // Rows are independent: a large tip's rows run in parallel, to the same values. The serial + // path stays a plain loop over an inlined row: the same code as before the threads (a closure + // passed to a helper cost a small tip half its rasterization time). + #[cfg(not(target_arch = "wasm32"))] + if parallel(out.len()) { + use rayon::prelude::*; + out.par_chunks_exact_mut(w).enumerate().for_each(|(yy, row)| tip.row(yy, row)); + return; + } + for (yy, row) in out.chunks_exact_mut(w).enumerate() { + tip.row(yy, row); + } +} + +/// A round tip's coverage, computed row by row (see [`rasterize_round`]). +#[derive(Clone, Copy)] +struct RoundTip { + cx: f32, + cy: f32, + ro: f32, + rm: f32, + reach2: f32, + hardness: f32, + alpha: f32, + aliased: bool, + x0: i32, + y0: i32, +} + +impl RoundTip { + /// Row `yy` of the tip's rectangle into `row`. + #[inline(always)] + fn row(self, yy: usize, row: &mut [f32]) { + let dy = (self.y0 + yy as i32) as f32 + 0.5 - self.cy; + if self.aliased { for (xx, dst) in row.iter_mut().enumerate() { - let dx = (rect.x0 + xx as i32) as f32 + 0.5 - cx; - let d2 = (dx * ro).powi(2) + dy * dy; - *dst = if d2 < reach2 && d2.sqrt() <= rm { alpha } else { 0.0 }; + let dx = (self.x0 + xx as i32) as f32 + 0.5 - self.cx; + let d2 = (dx * self.ro).powi(2) + dy * dy; + *dst = if d2 < self.reach2 && d2.sqrt() <= self.rm { self.alpha } else { 0.0 }; } } else { for (xx, dst) in row.iter_mut().enumerate() { - let dx = (rect.x0 + xx as i32) as f32 + 0.5 - cx; - let d2 = (dx * ro).powi(2) + dy * dy; - let val = if d2 >= reach2 { 0.0 } else { tip_falloff(d2.sqrt(), rm, hardness) }; - *dst = if val <= 0.0 { 0.0 } else { val * alpha }; + let dx = (self.x0 + xx as i32) as f32 + 0.5 - self.cx; + let d2 = (dx * self.ro).powi(2) + dy * dy; + let val = if d2 >= self.reach2 { 0.0 } else { tip_falloff(d2.sqrt(), self.rm, self.hardness) }; + *dst = if val <= 0.0 { 0.0 } else { val * self.alpha }; } } - }); + } } #[cfg(test)] From 8c5ec444dbeea93b5f0a2533c18baba71e2626e2 Mon Sep 17 00:00:00 2001 From: Unemars <62496697+Unemars@users.noreply.github.com> Date: Wed, 21 Oct 2026 19:43:02 +0200 Subject: [PATCH 4/5] Brush test: the parallel threshold goes back to its default however the test ends MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The parallel-vs-serial test moved the process-wide threshold and restored a hard-coded 256² only on success. A drop guard now restores it on every exit path, a panic inside a render included, from the renderer's own `DEFAULT_PARALLEL_MIN_PIXELS` instead of a copy of the literal. Co-Authored-By: Claude Opus 5.5 --- crates/paint/src/brush_tests.rs | 10 +++++++++- crates/paint/src/render.rs | 6 +++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/paint/src/brush_tests.rs b/crates/paint/src/brush_tests.rs index 4c90586b787..8edf99350af 100644 --- a/crates/paint/src/brush_tests.rs +++ b/crates/paint/src/brush_tests.rs @@ -1641,9 +1641,17 @@ fn large_tips_render_the_same_in_parallel_and_serially() { }) .collect() }; + // The threshold is process-wide: put the default back however the test ends, a panic + // inside a render included. + struct Restore; + impl Drop for Restore { + fn drop(&mut self) { + crate::render::set_parallel_min_pixels(crate::render::DEFAULT_PARALLEL_MIN_PIXELS); + } + } + let _restore = Restore; let parallel = render(0); let serial = render(usize::MAX); - crate::render::set_parallel_min_pixels(256 * 256); for (i, (p, s)) in parallel.iter().zip(&serial).enumerate() { assert_eq!(p.len(), s.len()); let diff = p.iter().zip(s).filter(|(a, b)| a != b).count(); diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rs index 9afd83c6d18..ab38249bd9b 100644 --- a/crates/paint/src/render.rs +++ b/crates/paint/src/render.rs @@ -44,7 +44,11 @@ pub const COV_TILE: i32 = 64; /// it the threads cost more than they save. A large soft tip is tens of megapixels per dab, and /// every stage of it is independent per row or tile, so the pixels come out the same. #[cfg(not(target_arch = "wasm32"))] -static PARALLEL_MIN_PIXELS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(256 * 256); +pub(crate) const DEFAULT_PARALLEL_MIN_PIXELS: usize = 256 * 256; + +/// The threshold in use: [`DEFAULT_PARALLEL_MIN_PIXELS`] (tests move it). +#[cfg(not(target_arch = "wasm32"))] +static PARALLEL_MIN_PIXELS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(DEFAULT_PARALLEL_MIN_PIXELS); /// Whether `pixels` of independent work are worth the thread pool (the web has none: there every /// stage takes its serial path). From 360e0920fcbe417c4385f9773529cc964d4e1e0f Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 22 Oct 2026 20:27:43 +0200 Subject: [PATCH 5/5] Integration: parallel brush composite keeps the document's CMYK profile (#7218) The document's CMYK profile is active per thread (with_cmyk_space), and the parallel composite ran its tiles on rayon workers outside that scope. On a CMYK document with its own profile, every blend mode other than Normal and Dissolve then converted those tiles through the built-in coated CMYK: a 40 px Multiply line 1100 px long (17+ tiles, parallel at the default threshold) differed from the serial path in 256384 samples. The workers now enter the caller's CMYK space, as the compositor and gpu crates do. Test: a_parallel_composite_converts_through_the_documents_cmyk_profile fails without the fix. Co-authored-by: Unemars <62496697+Unemars@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/paint/Cargo.toml | 1 + crates/paint/src/brush_tests.rs | 39 +++++++++++++++++++++++++++++++++ crates/paint/src/render.rs | 8 ++++++- 4 files changed, 48 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index dacf8307d54..1fac8f1ea80 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4942,6 +4942,7 @@ dependencies = [ name = "photocraft-paint" version = "0.11.1" dependencies = [ + "photocraft-cms", "photocraft-color", "photocraft-geom", "photocraft-raster", diff --git a/crates/paint/Cargo.toml b/crates/paint/Cargo.toml index 4f4ca359e6c..b72880c40c7 100644 --- a/crates/paint/Cargo.toml +++ b/crates/paint/Cargo.toml @@ -18,4 +18,5 @@ serde = { workspace = true } rayon = { workspace = true } [dev-dependencies] +photocraft-cms = { workspace = true } serde_json = { workspace = true } diff --git a/crates/paint/src/brush_tests.rs b/crates/paint/src/brush_tests.rs index 8edf99350af..8b9cd692192 100644 --- a/crates/paint/src/brush_tests.rs +++ b/crates/paint/src/brush_tests.rs @@ -1660,6 +1660,45 @@ fn large_tips_render_the_same_in_parallel_and_serially() { } } +/// A CMYK document with its own profile: blend modes other than Normal convert each pixel through +/// that profile, which is active per thread, so a stroke composited in parallel gives the pixels the +/// serial path gives (the workers enter the caller's CMYK space too). +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_parallel_composite_converts_through_the_documents_cmyk_profile() { + use photocraft_cms::synth::{CmykParams, cmyk_profile}; + use photocraft_color::convert::{CmykSpace, with_cmyk_space}; + let profile = + cmyk_profile(&CmykParams { description: "Brush Test CMYK".into(), tvi: [0.26, 0.26, 0.26, 0.3], grid_a2b: 5, grid_b2a: 9, ..Default::default() }); + let bytes = profile.to_bytes(); + let Some(space) = CmykSpace::for_profile(Some(&bytes)) else { panic!("the synthetic profile is a CMYK space") }; + let fmt = PixelFormat::new(ColorMode::Cmyk, SampleType::U16, true); + // A 40 px Multiply line over 1100 px dirties more than 16 tiles: the composite's batch is + // worth the threads at the default threshold, and always at threshold 0. + let b = BrushSettings { size: 40.0, hardness: 0.5, mode: BlendMode::Multiply, color: [0.2, 0.4, 0.9, 1.0], ..brush() }; + let pts = line(40.0, 1140.0, 60.0); + let full = Rect::new(0, 0, 1200, 120); + let render = |parallel_from: usize| -> Vec { + crate::render::set_parallel_min_pixels(parallel_from); + let mut s = Surface::new(fmt); + s.fill_rect(full, &[0.1, 0.5, 0.3, 0.05, 1.0]); + with_cmyk_space(Some(&space), || render_stroke(&mut s, &b, &pts, None, false, 1.0)); + s.read_region(full) + }; + struct Restore; + impl Drop for Restore { + fn drop(&mut self) { + crate::render::set_parallel_min_pixels(crate::render::DEFAULT_PARALLEL_MIN_PIXELS); + } + } + let _restore = Restore; + let parallel = render(0); + let serial = render(usize::MAX); + let diff = parallel.iter().zip(&serial).filter(|(a, b)| a != b).count(); + assert_eq!(diff, 0, "{diff} samples differ between the parallel and the serial composite in a profiled CMYK document"); + assert!(serial.chunks(5).any(|p| (p[1] - 0.5).abs() > 0.05), "the stroke painted something"); +} + /// Photoshop (measured): a 100 px brush with a 20 px Dual Brush tip resized to 50 / 2 / 1 px has a /// 10 / 0.4 / 0.2 px dual tip, unrounded and with no floor, and back at 100 px it is 20 px again; past /// 5000 px the dual tip is capped there and the proportion is lost (#4809). diff --git a/crates/paint/src/render.rs b/crates/paint/src/render.rs index ab38249bd9b..d92f83b7ca2 100644 --- a/crates/paint/src/render.rs +++ b/crates/paint/src/render.rs @@ -1111,9 +1111,12 @@ impl StrokeRenderer { // pending buffers few, and the pool keeps them from one composite to the next. const BATCH: usize = 256; let mut pool = std::mem::take(&mut self.regions.0); + // The document's CMYK profile is active per thread: the workers enter the caller's, or a + // blend mode other than Normal would convert their tiles through the built-in coated CMYK. + let cmyk = photocraft_color::convert::active_cmyk_space(); for batch in keys.chunks(BATCH) { let mut items: Vec<((i32, i32), Rect, Vec)> = batch.iter().map(|&key| (key, Rect::EMPTY, pool.pop().unwrap_or_default())).collect(); - for_each_item(&mut items, batch.len() * (COV_TILE * COV_TILE) as usize, |(key, done, region)| { + let composite_tile = |(key, done, region): &mut ((i32, i32), Rect, Vec)| { let (tx, ty) = *key; let Some(tile) = self.cov.tiles.get(&(tx, ty)) else { return }; let tr = Rect::new(tx * COV_TILE, ty * COV_TILE, (tx + 1) * COV_TILE, (ty + 1) * COV_TILE).intersect(&bounds); @@ -1190,6 +1193,9 @@ impl StrokeRenderer { } } *done = tr; + }; + for_each_item(&mut items, batch.len() * (COV_TILE * COV_TILE) as usize, |item| { + photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || composite_tile(item)) }); for (_, tr, region) in items { if !tr.is_empty() {