Merge PR #7218: Brush: large tips rasterize, accumulate and composite in parallel

This commit is contained in:
David Mann committed 2026-10-25 10:14:11 +01:00
commit d5e56b03e1
6 files changed
+510 -114

No files matched your search

Generated
+2
View File
@@ -5065,9 +5065,11 @@ dependencies = [
name = "photocraft-paint"
version = "0.15.1"
dependencies = [
"photocraft-cms",
"photocraft-color",
"photocraft-geom",
"photocraft-raster",
"rayon",
"serde",
"serde_json",
]
+5
View File
@@ -13,5 +13,10 @@ 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]
photocraft-cms = { workspace = true }
serde_json = { workspace = true }
+44
View File
@@ -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<String> = 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());
}
+64
View File
@@ -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<String> = 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
);
}
+100
View File
@@ -1688,6 +1688,106 @@ fn an_aliased_stroke_at_partial_opacity_is_one_flat_colour() {
}
}
/// 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<StrokePoint>)> = 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<Vec<f32>> {
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()
};
// 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);
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");
}
}
/// 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<f32> {
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).
+295 -114
View File
@@ -39,6 +39,57 @@ 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"))]
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).
#[cfg(not(target_arch = "wasm32"))]
fn parallel(pixels: usize) -> bool {
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` over `items`, in parallel when `pixels` are worth it.
fn for_each_item<T: Send>(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;
}
#[cfg(target_arch = "wasm32")]
let _ = pixels;
items.iter_mut().for_each(&f);
}
/// `f` over `items`, collecting its results in order, in parallel when `pixels` are worth it.
fn map_items<T: Sync, R: Send>(items: &[T], pixels: usize, f: impl Fn(&T) -> R + Sync) -> Vec<R> {
#[cfg(not(target_arch = "wasm32"))]
if parallel(pixels) {
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.
const SMALL_TIP_RADIUS: f32 = 3.0;
/// Sub-pixel sample offsets (a 4×4 grid) for the area coverage of small tips.
@@ -466,61 +517,62 @@ 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() },
});
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)
})
});
// 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; (COV_TILE * COV_TILE) as usize * nc];
tile.col = vec![0.0; n * 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;
}
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)> {
@@ -587,6 +639,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 {
@@ -603,6 +704,19 @@ pub struct StrokeRenderer {
dab_buf: Vec<Dab>,
dual_buf: Vec<Dab>,
all_dabs: Option<Vec<Dab>>,
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<Vec<f32>>);
impl Clone for RegionPool {
fn clone(&self) -> Self {
Self::default()
}
}
impl StrokeRenderer {
@@ -695,6 +809,7 @@ impl StrokeRenderer {
dab_buf: Vec::new(),
dual_buf: Vec::new(),
all_dabs: None,
regions: RegionPool::default(),
})
}
Some(m) => {
@@ -746,6 +861,7 @@ impl StrokeRenderer {
dab_buf: Vec::new(),
dual_buf: Vec::new(),
all_dabs: None,
regions: RegionPool::default(),
}
}
@@ -876,6 +992,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.
@@ -989,77 +1106,106 @@ 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 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);
// 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<f32>)> = batch.iter().map(|&key| (key, Rect::EMPTY, pool.pop().unwrap_or_default())).collect();
let composite_tile = |(key, done, region): &mut ((i32, i32), Rect, Vec<f32>)| {
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;
}
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, 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 {
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 o = if lock_transparency {
photocraft_color::blend::composite_atop(b.mode, d, sr, k)
} else {
photocraft_color::blend::composite(b.mode, d, sr, k)
};
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 o = if lock_transparency {
photocraft_color::blend::composite_atop(b.mode, d, sr, k)
} else {
photocraft_color::blend::composite(b.mode, d, sr, k)
};
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);
}
}
*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() {
target.write_region(tr, &region);
dmg = dmg.union(&tr);
}
pool.push(region);
}
target.write_region(tr, &region);
dmg = dmg.union(&tr);
}
self.regions.0 = pool;
if all { bounds } else { dmg }
}
}
@@ -1090,22 +1236,57 @@ 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 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() {
let dy = (rect.y0 + yy as i32) as f32 + 0.5 - cy;
if aliased {
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 { d.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 * d.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 };
}
}
}