PhotoCraft: An open-source, photo editor written by scratch in pure Rust
perf(compose): blend pixel layers row by row, Normal in 8-pixel vector blocks
Akos Arinton5418399ddaa3
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rsindex 3cf2f1dc1..5d5a733e2 100644--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@ -193,14 +193,15 @@ fn render_tiled_with(doc: &Document, rect: Rect, tile: i32, cx: &Ctx) -> Buffer}});} else {- // Few, wide bands: the tiles of each band in parallel.- for (i, band) in out.px.chunks_mut(band_len).enumerate() {+ // Few, wide bands: the tiles of each band in parallel, and the bands too, so a band's+ // slowest tile doesn't leave the other cores idle until the next band starts.+ out.px.par_chunks_mut(band_len).enumerate().for_each(|(i, band)| {let y0 = rect.y0 + i as i32 * tile;let parts: Vec<Buffer> = band_tiles(y0).into_par_iter().map(run).collect();for part in &parts {put(band, y0, part);}- }+ });}}#[cfg(target_arch = "wasm32")]@@ -1350,6 +1351,38 @@ fn composite_artboard(layer: &Layer, ab: &photocraft_doc::Artboard, clipped: &[L}}+/// The surface `render_content` reads `layer`'s pixels from, when that is all it draws.+fn pixel_surface(layer: &Layer) -> Option<&Surface> {+ if matches!(layer.content, LayerContent::Group(_) | LayerContent::Fill(_) | LayerContent::Adjustment(_)) {+ return None;+ }+ layer.surface()+}++/// A pixel layer (nothing clipped to it) onto `backdrop`, read from its tiles a row at a time:+/// the same arithmetic as `render_content` + `blend_into_fill`, without a tile-sized copy of the+/// layer (a megabyte per 256² render tile).+fn composite_pixel_layer(layer: &Layer, surf: &Surface, backdrop: &mut Buffer, cx: &Ctx) {+ let rect = backdrop.rect;+ let w = rect.width() as usize;+ if w == 0 {+ return;+ }+ let mv = mask_vals(layer, rect, cx);+ let gamma = text_gamma(layer);+ let mut row = vec![[0.0f32; 4]; w];+ for (ry, dst) in backdrop.px.chunks_exact_mut(w).enumerate() {+ let y = rect.y0 + ry as i32;+ surf.read_rgba_into(Rect::new(rect.x0, y, rect.x1, y + 1), &mut row);+ if let Some(m) = mv.as_ref().and_then(|m| m.get(ry * w..(ry + 1) * w)) {+ for (p, k) in row.iter_mut().zip(m) {+ p[3] *= k;+ }+ }+ blend_span_fill(dst, &row, rect.x0, y, layer.blend, layer.opacity, layer.fill_opacity, gamma);+ }+}+fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer, cx: &Ctx, scope: advanced::Scope) {let rect = backdrop.rect;// A TSL-off stroke base that is transparent here can still have visible clipped siblings;@@ -1468,6 +1501,11 @@ fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Bufferblend_into_fill(backdrop, &content, layer.blend, layer.opacity, layer.fill_opacity, 1.0);return;}+ if clipped.is_empty()+ && let Some(surf) = pixel_surface(layer)+ {+ return composite_pixel_layer(layer, surf, backdrop, cx);+ }let Some(mut content) = render_content(layer, rect, cx) else { return };advanced::composite_clipped(clipped, &mut content, cx);blend_into_fill(backdrop, &content, layer.blend, layer.opacity, layer.fill_opacity, text_gamma(layer));@@ -1853,44 +1891,51 @@ fn blend_into(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32/// [`blend_into_g`] for a layer's own `opacity` and `fill`: Fill is part of the blend for/// Photoshop's special eight ([`psblend::composite_fill`]), plain coverage otherwise.fn blend_into_fill(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32, fill: f32, gamma: f32) {+ for_rows(backdrop, src, |dst, s, x0, y| blend_span_fill(dst, s, x0, y, mode, opacity, fill, gamma));+}++/// [`blend_into`] mixing coverage in a `gamma` space (type layers).+fn blend_into_g(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32, gamma: f32) {+ for_rows(backdrop, src, |dst, s, x0, y| blend_span_g(dst, s, x0, y, mode, opacity, gamma));+}++/// Runs `f(backdrop row, src row, x0, y)` over the rows of two buffers covering the same rect.+fn for_rows(backdrop: &mut Buffer, src: &Buffer, mut f: impl FnMut(&mut [[f32; 4]], &[[f32; 4]], i32, i32)) {+ let rect = backdrop.rect;+ let w = (rect.width() as usize).max(1);+ for (ry, (dst, s)) in backdrop.px.chunks_mut(w).zip(src.px.chunks(w)).enumerate() {+ f(dst, s, rect.x0, rect.y0 + ry as i32);+ }+}++/// [`blend_into_fill`] of one row: `dst` and `src` start at pixel (`x0`, `y`).+#[allow(clippy::too_many_arguments)]+fn blend_span_fill(dst: &mut [[f32; 4]], src: &[[f32; 4]], x0: i32, y: i32, mode: BlendMode, opacity: f32, fill: f32, gamma: f32) {if fill >= 1.0 || !psblend::fill_is_special(mode) {- return blend_into_g(backdrop, src, mode, opacity * fill, gamma);+ return blend_span_g(dst, src, x0, y, mode, opacity * fill, gamma);}- for (b, s) in backdrop.px.iter_mut().zip(&src.px) {+ for (b, s) in dst.iter_mut().zip(src) {if s[3] > 0.0 {*b = psblend::composite_fill(mode, *b, *s, opacity, fill, gamma);}}}-/// [`blend_into`] mixing coverage in a `gamma` space (type layers).-fn blend_into_g(backdrop: &mut Buffer, src: &Buffer, mode: BlendMode, opacity: f32, gamma: f32) {+/// [`blend_into_g`] of one row: `dst` and `src` start at pixel (`x0`, `y`).+fn blend_span_g(dst: &mut [[f32; 4]], src: &[[f32; 4]], x0: i32, y: i32, mode: BlendMode, opacity: f32, gamma: f32) {// The blend space is constant in this loop. Some TLS implementations synchronise even a// boolean read, so select the common Normal kernel once instead of once per pixel.if mode == BlendMode::Normal && gamma == 1.0 && !psblend::LAB_MIX.with(|l| l.get()) {- for (i, b) in backdrop.px.iter_mut().enumerate() {- let s = src.px[i];- if s[3] <= 0.0 {- continue;- }- *b = psblend::composite_normal_rgb(*b, s, opacity);- }- return;+ return psblend::composite_normal_rgb_span(dst, src, opacity);}- let rect = backdrop.rect;- let w = rect.width() as i32;- for (i, b) in backdrop.px.iter_mut().enumerate() {- let mut s = src.px[i];+ for (x, (b, s)) in (x0..).zip(dst.iter_mut().zip(src)) {+ let mut s = *s;if s[3] <= 0.0 {continue;}- let mut mode = mode;if mode == BlendMode::Dissolve {- let x = rect.x0 + (i as i32 % w);- let y = rect.y0 + (i as i32 / w);s[3] = if dissolve_noise(x, y) < s[3] * opacity { 1.0 } else { 0.0 };- mode = BlendMode::Normal;- *b = blend::composite(mode, *b, s, 1.0);+ *b = blend::composite(BlendMode::Normal, *b, s, 1.0);continue;}*b = blend::composite_gamma(mode, *b, s, opacity, gamma);diff --git a/crates/compose/src/psblend.rs b/crates/compose/src/psblend.rsindex 4cff6f308..b5eeaa79d 100644--- a/crates/compose/src/psblend.rs+++ b/crates/compose/src/psblend.rs@@ -238,6 +238,63 @@ pub(crate) fn composite_normal_rgb(backdrop: [f32; 4], source: [f32; 4], opacitynormal_rgb(backdrop, source, as_, ao)}+/// [`composite_normal_rgb`] over a row, bit for bit, in blocks the compiler vectorizes (see+/// [`normal_lanes`]); the tail that doesn't fill a block goes through the scalar kernel.+pub(crate) fn composite_normal_rgb_span(dst: &mut [[f32; 4]], src: &[[f32; 4]], opacity: f32) {+ let n = dst.len().min(src.len());+ let (dc, dt) = dst[..n].as_chunks_mut::<LANES>();+ let (sc, st) = src[..n].as_chunks::<LANES>();+ for (b, s) in dc.iter_mut().zip(sc) {+ normal_lanes(b, s, opacity);+ }+ for (b, s) in dt.iter_mut().zip(st) {+ // Not `s[3] > 0`: a NaN alpha is blended (into NaN), as the scalar loop does.+ if s[3] <= 0.0 {+ continue;+ }+ *b = composite_normal_rgb(*b, *s, opacity);+ }+}++/// Pixels per block of [`normal_lanes`]: two 128-bit vectors (or one 256-bit) per channel.+const LANES: usize = 8;++/// [`composite_normal_rgb`] (after the caller's `source alpha > 0` test) on one block of pixels,+/// without branches: one array per channel, fixed-length loops the compiler vectorizes, and a+/// select per pixel between the backdrop, zero and the mix. Same operations in the same order+/// (Rust never fuses them into multiply-adds) and the same tests, NaN included: bit-identical.+#[inline]+#[allow(clippy::needless_range_loop)] // lanes index several arrays in lockstep+fn normal_lanes(b: &mut [[f32; 4]; LANES], s: &[[f32; 4]; LANES], opacity: f32) {+ let lane = |p: &[[f32; 4]; LANES], c: usize| -> [f32; LANES] { std::array::from_fn(|i| p[i][c]) };+ let (b0, b1, b2, ab) = (lane(b, 0), lane(b, 1), lane(b, 2), lane(b, 3));+ let (s0, s1, s2, s3) = (lane(s, 0), lane(s, 1), lane(s, 2), lane(s, 3));+ let mut as_ = [0.0f32; LANES];+ let mut ao = [0.0f32; LANES];+ let mut kb = [0.0f32; LANES];+ let mut inv = [0.0f32; LANES];+ for i in 0..LANES {+ as_[i] = s3[i] * opacity;+ ao[i] = as_[i] + ab[i] * (1.0 - as_[i]);+ kb[i] = ab[i] * (1.0 - as_[i]);+ inv[i] = 1.0 / ao[i];+ }+ for i in 0..LANES {+ let mix = [(kb[i] * b0[i] + as_[i] * s0[i]) * inv[i], (kb[i] * b1[i] + as_[i] * s1[i]) * inv[i], (kb[i] * b2[i] + as_[i] * s2[i]) * inv[i], ao[i]];+ // The scalar path's tests: skipped where the source is empty (`s[3] <= 0`) or adds+ // nothing (`as_ <= 0`), zero where nothing is left (`ao <= 0`).+ let keep = (s3[i] <= 0.0) | (as_[i] <= 0.0);+ let gone = ao[i] <= 0.0;+ b[i] = if keep {+ b[i]+ } else if gone {+ [0.0; 4]+ } else {+ mix+ };+ }+}+#[inline]fn normal_rgb(backdrop: [f32; 4], source: [f32; 4], as_: f32, ao: f32) -> [f32; 4] {// B(Cb, Cs) = Cs. Keep the scalar composite's operation order and straight alpha.diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rsindex ddd487154..4cc6e7925 100644--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@ -80,6 +80,105 @@ fn normal_rgb_kernel_preserves_scalar_bits() {}}+/// The vectorized row kernel against the scalar loop it replaced, over row lengths that cover+/// whole blocks, tails and both, with samples full of NaN, signed zeros, infinities, subnormals+/// and values outside 0..1.+#[test]+fn normal_rgb_span_preserves_scalar_bits() {+ let specials = [0.0, -0.0, 1.0, 0.5, 0.03, -0.5, 2.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::from_bits(1), f32::MIN_POSITIVE, 1e-30];+ let mut seed = 0x9e37_79b9u32;+ let mut next = move || {+ seed ^= seed << 13;+ seed ^= seed >> 17;+ seed ^= seed << 5;+ seed+ };+ let mut value = || {+ let r = next();+ if r % 3 == 0 { specials[(r / 3) as usize % specials.len()] } else { (r % 1000) as f32 / 999.0 }+ };+ for len in 0..41 {+ for _ in 0..40 {+ let backdrop: Vec<[f32; 4]> = (0..len).map(|_| [value(), value(), value(), value()]).collect();+ let source: Vec<[f32; 4]> = (0..len).map(|_| [value(), value(), value(), value()]).collect();+ let opacity = value();+ let mut want = backdrop.clone();+ for (b, s) in want.iter_mut().zip(&source) {+ if s[3] <= 0.0 {+ continue;+ }+ *b = original_normal_rgb(*b, *s, opacity);+ }+ let mut got = backdrop;+ psblend::composite_normal_rgb_span(&mut got, &source, opacity);+ for (i, (g, w)) in got.iter().zip(&want).enumerate() {+ assert_eq!(g.map(f32::to_bits), w.map(f32::to_bits), "len {len}, pixel {i}, opacity {opacity}: {g:?} vs {w:?}");+ }+ }+ }+}++/// A pixel layer read and blended a row at a time gives exactly what blending a tile-sized copy+/// of it gave, across depths, modes (Dissolve's per-pixel noise and the fill-special modes+/// included), fill, masks (feathered too) and a rect that is not tile-aligned and runs off the+/// layer's pixels.+#[test]+fn pixel_layer_rows_match_tile_copy() {+ let rect = Rect::new(-3, 2, 37, 21);+ let modes = [+ BlendMode::Normal,+ BlendMode::Multiply,+ BlendMode::Dissolve,+ BlendMode::Overlay,+ BlendMode::ColorBurn,+ BlendMode::LinearBurn,+ BlendMode::VividLight,+ BlendMode::Difference,+ BlendMode::Hue,+ ];+ for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F] {+ let mut l = Layer::raster("p", fmt);+ for y in 0..20 {+ for x in 0..30 {+ let t = (x * 7 + y * 13) as f32 / 400.0;+ let a = [0.0, 0.03, 0.5, 1.0][(x + y) as usize % 4];+ l.surface_mut().unwrap().write_pixel(x, y, &photocraft_raster::from_rgba(&fmt, [t.fract(), 1.0 - t.fract(), 0.3, a]));+ }+ }+ let mut sharp = LayerMask::reveal_all();+ sharp.surface.fill_rect(Rect::new(5, 0, 12, 30), &[0.25]);+ let mut feathered = sharp.clone();+ feathered.feather = 2.5;+ for mask in [None, Some(sharp), Some(feathered)] {+ l.mask = mask;+ for mode in modes {+ for fill in [1.0, 0.4] {+ l.blend = mode;+ l.opacity = 0.8;+ l.fill_opacity = fill;+ let mut doc = doc_white(40, 30);+ doc.layers.push(l.clone());+ let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode);+ let cx = Ctx::for_doc(&doc, &patterns);+ let layer = &doc.layers[1];+ let backdrop = Buffer {+ rect,+ px: (0..rect.width() * rect.height())+ .map(|i| [(i % 11) as f32 / 10.0, (i % 5) as f32 / 4.0, 0.6, [1.0, 0.5, 0.0][i as usize % 3]])+ .collect(),+ };+ let mut want = backdrop.clone();+ let content = render_content(layer, rect, &cx).unwrap();+ blend_into_fill(&mut want, &content, layer.blend, layer.opacity, layer.fill_opacity, text_gamma(layer));+ let mut got = backdrop;+ composite_pixel_layer(layer, pixel_surface(layer).unwrap(), &mut got, &cx);+ assert_buffer_bits(&got, &want);+ }+ }+ }+ }+}+fn normal_rgb_test_buffers(fmt: PixelFormat) -> (Buffer, Buffer) {let rect = Rect::new(-3, -2, 5, 0);let mut bottom = Surface::new(fmt);