Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

perf(compose): share bounded pattern preparation across tiles (#104)

MikeeI7c53a3c1ad93
diff --git a/crates/compose/src/effects.rs b/crates/compose/src/effects.rs
index e483d53b1..8248c0777 100644
--- a/crates/compose/src/effects.rs
+++ b/crates/compose/src/effects.rs
@@ -25,7 +25,7 @@ use photocraft_doc::{
};
use photocraft_geom::Rect;
-use crate::pattern::{Placement, Tile};
+use crate::pattern::{PREPARED_PATTERN_BYTES, Placement, PreparedPatterns};
use crate::{Buffer, psblend};
/// `true` if the layer has at least one enabled effect and the master switch is on.
@@ -573,8 +573,18 @@ fn glow_map(shape: &Map, g: &Glow, inner: bool) -> Map {
/// Paints a pattern (looked up in `patterns`) through coverage `m`; missing patterns paint nothing.
#[allow(clippy::too_many_arguments)]
-fn paint_pattern(dst: &mut Buffer, m: &Map, patterns: &[Pattern], name: &str, id: &str, place: Placement, big: Rect, blend: BlendMode, opacity: f32) {
- let Some(tile) = photocraft_doc::pattern::find(patterns, id, name).and_then(Tile::new) else { return };
+fn paint_pattern(
+ dst: &mut Buffer,
+ m: &Map,
+ patterns: &PreparedPatterns<'_>,
+ name: &str,
+ id: &str,
+ place: Placement,
+ big: Rect,
+ blend: BlendMode,
+ opacity: f32,
+) {
+ let Some(tile) = patterns.get(id, name) else { return };
let w = big.width() as usize;
paint(
dst,
@@ -590,7 +600,17 @@ fn paint_pattern(dst: &mut Buffer, m: &Map, patterns: &[Pattern], name: &str, id
}
#[allow(clippy::too_many_arguments)]
-fn paint_fx(dst: &mut Buffer, m: &Map, p: &FxPaint, shape_bounds: Rect, anchor: (f64, f64), big: Rect, blend: BlendMode, opacity: f32, patterns: &[Pattern]) {
+fn paint_fx(
+ dst: &mut Buffer,
+ m: &Map,
+ p: &FxPaint,
+ shape_bounds: Rect,
+ anchor: (f64, f64),
+ big: Rect,
+ blend: BlendMode,
+ opacity: f32,
+ patterns: &PreparedPatterns<'_>,
+) {
match p {
FxPaint::Color(c) => paint_color(dst, m, rgb(c), blend, opacity),
FxPaint::Gradient(g) => {
@@ -825,7 +845,7 @@ pub fn bevel_geom(b: &Bevel) -> BevelGeom {
/// Bevel height map in `0..=1`. Smooth: the shape blurred by two box passes of the bevel
/// width. Chisel: linear ramps of the exact distance to the edge (size wide; emboss styles
/// straddle the edge), slightly blurred for Chisel Soft. Soften blurs the result.
-fn bevel_height(shape: &Map, b: &Bevel, g: &BevelGeom, tex: &TextureCtx) -> Map {
+fn bevel_height(shape: &Map, b: &Bevel, g: &BevelGeom, tex: &TextureCtx, patterns: &PreparedPatterns<'_>) -> Map {
let size = b.size.max(1.0);
let mut h = if b.technique == BevelTechnique::Smooth {
let mut h = shape.clone();
@@ -849,7 +869,7 @@ fn bevel_height(shape: &Map, b: &Bevel, g: &BevelGeom, tex: &TextureCtx) -> Map
// Texture element: the pattern's luminance as extra height, scaled so a full-contrast step
// at 100 % depth slopes like the bevel at its depth.
if let Some(t) = &b.texture
- && let Some(tile) = photocraft_doc::pattern::find(tex.patterns, &t.id, &t.name).and_then(Tile::new)
+ && let Some(tile) = patterns.get(&t.id, &t.name)
{
let unit = if b.depth.abs() > 1e-6 { (g.depth / b.depth).abs().max(1e-3) } else { g.width.max(1.0) };
let place = Placement::anchored(tex.anchor, t.link, t.phase, t.scale, 0.0);
@@ -895,9 +915,9 @@ pub fn bevel_chisel_h(paint: BevelPaint, size: f32, din: f32, dout: f32) -> f32
/// Bevel highlight and shadow maps: `[hi, sh]` (inner or outer) or `[hi, sh, hi_out, sh_out]`
/// (emboss styles).
-fn bevel_maps(shape: &Map, b: &Bevel, light: &GlobalLight, tex: &TextureCtx) -> (Vec<Map>, BevelPaint) {
+fn bevel_maps(shape: &Map, b: &Bevel, light: &GlobalLight, tex: &TextureCtx, patterns: &PreparedPatterns<'_>) -> (Vec<Map>, BevelPaint) {
let g = bevel_geom(b);
- let hmap = bevel_height(shape, b, &g, tex);
+ let hmap = bevel_height(shape, b, &g, tex, patterns);
let (angle, altitude) = if b.use_global_light { (light.angle, light.altitude) } else { (b.angle, b.altitude) };
let (sa, ca) = angle.to_radians().sin_cos();
let (se, ce) = altitude.to_radians().sin_cos();
@@ -1003,6 +1023,18 @@ fn satin_map(shape: &Map, s: &photocraft_doc::effects::Satin) -> Map {
/// Build every effect map for `layer` from its alpha `shape` over `rect`.
pub fn build_maps(layer: &Layer, shape: Vec<f32>, rect: Rect, light: &GlobalLight, tex: &TextureCtx) -> FxMaps {
+ let prepared = PreparedPatterns::new(tex.patterns, PREPARED_PATTERN_BYTES);
+ build_maps_prepared(layer, shape, rect, light, tex, &prepared)
+}
+
+pub(crate) fn build_maps_prepared(
+ layer: &Layer,
+ shape: Vec<f32>,
+ rect: Rect,
+ light: &GlobalLight,
+ tex: &TextureCtx,
+ patterns: &PreparedPatterns<'_>,
+) -> FxMaps {
let (w, h) = (rect.width() as usize, rect.height() as usize);
let shape = Map { w, h, v: shape };
let items: Vec<&Effect> = layer.effects.items.iter().filter(|e| e.enabled()).collect();
@@ -1017,7 +1049,7 @@ pub fn build_maps(layer: &Layer, shape: Vec<f32>, rect: Rect, light: &GlobalLigh
Effect::InnerGlow(g) => vec![glow_map(&shape, g, true)],
Effect::Satin(s) => vec![satin_map(&shape, s)],
Effect::BevelEmboss(b) => {
- let (maps, paint) = bevel_maps(&shape, b, light, tex);
+ let (maps, paint) = bevel_maps(&shape, b, light, tex, patterns);
bevel_paint[i] = paint;
maps
}
@@ -1037,6 +1069,18 @@ const FAR: f32 = 1.0e9;
/// Composites `content` (the layer's own pixels over `big`, alpha already
/// masked, clipped layers applied) plus its effects into `backdrop`.
pub fn composite_with_effects(layer: &Layer, content: &Buffer, backdrop: &mut Buffer, maps: &FxMaps, layer_bounds: Rect, patterns: &[Pattern]) {
+ let prepared = PreparedPatterns::new(patterns, PREPARED_PATTERN_BYTES);
+ composite_with_effects_prepared(layer, content, backdrop, maps, layer_bounds, &prepared);
+}
+
+pub(crate) fn composite_with_effects_prepared(
+ layer: &Layer,
+ content: &Buffer,
+ backdrop: &mut Buffer,
+ maps: &FxMaps,
+ layer_bounds: Rect,
+ patterns: &PreparedPatterns<'_>,
+) {
let big = content.rect;
let (w, h) = (big.width() as usize, big.height() as usize);
let shape = Map { w, h, v: content.px.iter().map(|p| p[3]).collect() };
@@ -1426,7 +1470,13 @@ mod tests {
#[test]
fn smooth_inner_bevel_lights_the_top_edge_inside_only() {
let shape = square(40, 10, 30);
- let (maps, paint) = bevel_maps(&shape, &bevel_of(BevelStyle::InnerBevel, BevelTechnique::Smooth), &GlobalLight::default(), &no_tex());
+ let (maps, paint) = bevel_maps(
+ &shape,
+ &bevel_of(BevelStyle::InnerBevel, BevelTechnique::Smooth),
+ &GlobalLight::default(),
+ &no_tex(),
+ &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES),
+ );
assert_eq!(paint, BevelPaint::Inner);
let at = |m: &Map, x: usize, y: usize| m.v[y * 40 + x];
// Light from the top: highlight along the top edge, shadow along the bottom, flat middle.
@@ -1442,19 +1492,27 @@ mod tests {
fn emboss_paints_both_sides_and_pillow_flips_the_outside() {
let shape = square(40, 10, 30);
let l = GlobalLight::default();
- let (e, paint) = bevel_maps(&shape, &bevel_of(BevelStyle::Emboss, BevelTechnique::Smooth), &l, &no_tex());
+ let (e, paint) =
+ bevel_maps(&shape, &bevel_of(BevelStyle::Emboss, BevelTechnique::Smooth), &l, &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES));
assert_eq!((paint, e.len()), (BevelPaint::Both, 4));
let at = |m: &Map, x: usize, y: usize| m.v[y * 40 + x];
// Emboss: the slope across the top edge faces the light on both sides.
assert!(at(&e[0], 20, 10) > 0.3 && at(&e[2], 20, 9) > 0.3);
- let (p, _) = bevel_maps(&shape, &bevel_of(BevelStyle::PillowEmboss, BevelTechnique::Smooth), &l, &no_tex());
+ let (p, _) =
+ bevel_maps(&shape, &bevel_of(BevelStyle::PillowEmboss, BevelTechnique::Smooth), &l, &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES));
assert!(at(&p[0], 20, 10) > 0.3 && at(&p[3], 20, 9) > 0.3, "pillow: outside top edge in shadow");
}
#[test]
fn chisel_hard_has_flat_facets() {
let shape = square(48, 10, 38);
- let (m, _) = bevel_maps(&shape, &bevel_of(BevelStyle::InnerBevel, BevelTechnique::ChiselHard), &GlobalLight::default(), &no_tex());
+ let (m, _) = bevel_maps(
+ &shape,
+ &bevel_of(BevelStyle::InnerBevel, BevelTechnique::ChiselHard),
+ &GlobalLight::default(),
+ &no_tex(),
+ &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES),
+ );
let at = |x: usize, y: usize| m[0].v[y * 48 + x];
// A constant slope: equal highlight along the top facet.
assert!(at(24, 12) > 0.1 && (at(24, 12) - at(24, 13)).abs() < 1e-3);
@@ -1465,7 +1523,7 @@ mod tests {
let shape = square(40, 6, 34);
let l = GlobalLight::default();
let plain = bevel_of(BevelStyle::InnerBevel, BevelTechnique::Smooth);
- let (a, _) = bevel_maps(&shape, &plain, &l, &no_tex());
+ let (a, _) = bevel_maps(&shape, &plain, &l, &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES));
// A contour reshapes the profile (here a ramp folded at its middle).
let mut c = plain.clone();
let fold = vec![
@@ -1474,7 +1532,7 @@ mod tests {
photocraft_doc::adjust::CurvePoint { input: 1.0, output: 0.0 },
];
c.contour = Some(photocraft_doc::BevelContour { contour: Contour::Custom { name: "fold".into(), points: fold }, range: 1.0, anti_alias: false });
- let (b, _) = bevel_maps(&shape, &c, &l, &no_tex());
+ let (b, _) = bevel_maps(&shape, &c, &l, &no_tex(), &PreparedPatterns::new(&[], PREPARED_PATTERN_BYTES));
let diff: f32 = a[1].v.iter().zip(&b[1].v).map(|(x, y)| (x - y).abs()).sum();
assert!(diff > 5.0, "{diff}");
// A striped texture lights the flat middle.
@@ -1493,7 +1551,7 @@ mod tests {
phase: (0.0, 0.0),
});
let tex = TextureCtx { rect: Rect::new(0, 0, 40, 40), patterns: &pats, anchor: (0.0, 0.0) };
- let (m, _) = bevel_maps(&shape, &t, &l, &tex);
+ let (m, _) = bevel_maps(&shape, &t, &l, &tex, &PreparedPatterns::new(&pats, PREPARED_PATTERN_BYTES));
let mid: f32 = (16..24).map(|y| m[0].v[y * 40 + 20] + m[1].v[y * 40 + 20]).sum();
let flat: f32 = (16..24).map(|y| a[0].v[y * 40 + 20] + a[1].v[y * 40 + 20]).sum();
assert!(mid > flat + 0.5, "{mid} vs {flat}");
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index d8efe20fc..b8c124a38 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -84,7 +84,8 @@ pub fn render(doc: &Document, rect: Rect) -> Buffer {
/// [`render`] with an explicit tile size (tests check tile independence).
pub fn render_tiled(doc: &Document, rect: Rect, tile: i32) -> Buffer {
- let cx = Ctx::for_doc(doc);
+ let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES);
+ let cx = Ctx::for_doc(doc, &patterns);
render_tiled_with(doc, rect, tile, &cx)
}
@@ -193,7 +194,9 @@ pub fn render_bands<E>(doc: &Document, rect: Rect, band_rows: i32, mut sink: imp
if rect.is_empty() {
return Ok(());
}
- let cx = Ctx::for_doc(doc);
+ // Keep prepared pixels and compiled vector masks across bands without retaining any rendered band.
+ let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES);
+ let cx = Ctx::for_doc(doc, &patterns);
let rows = band_rows_for(rect.width(), band_rows);
let mut y = rect.y0;
while y < rect.y1 {
@@ -243,6 +246,7 @@ pub fn flatten(doc: &Document) -> Buffer {
/// Render an arbitrary subset: a single layer (e.g. for thumbnails), isolated.
pub fn render_layer(layer: &Layer, rect: Rect) -> Buffer {
let mut buf = Buffer::transparent(rect);
+ let patterns = pattern::PreparedPatterns::new(&[], pattern::PREPARED_PATTERN_BYTES);
composite_stack(
std::slice::from_ref(layer),
&mut buf,
@@ -250,7 +254,7 @@ pub fn render_layer(layer: &Layer, rect: Rect) -> Buffer {
canvas: rect,
transfer: adjust::Transfer::Srgb,
light: photocraft_doc::GlobalLight::default(),
- patterns: &[],
+ patterns: &patterns,
mode: photocraft_color::ColorMode::Rgb,
depth: photocraft_color::SampleType::F32,
vector_masks: RenderVectorMasks::default(),
@@ -415,8 +419,8 @@ struct Ctx<'a> {
transfer: adjust::Transfer,
/// Global light for layer effects.
light: photocraft_doc::GlobalLight,
- /// The document's patterns (pattern fills and overlays).
- patterns: &'a [Pattern],
+ /// Prepared document patterns, shared across all tiles and bands of this render call.
+ patterns: &'a pattern::PreparedPatterns<'a>,
/// The document's colour mode (channel restrictions name its channels).
mode: photocraft_color::ColorMode,
depth: photocraft_color::SampleType,
@@ -424,12 +428,12 @@ struct Ctx<'a> {
}
impl<'a> Ctx<'a> {
- fn for_doc(doc: &'a Document) -> Self {
+ fn for_doc(doc: &Document, patterns: &'a pattern::PreparedPatterns<'a>) -> Self {
Self {
canvas: doc.bounds(),
transfer: adjust::Transfer::for_mode(doc.mode),
light: doc.global_light,
- patterns: &doc.patterns,
+ patterns,
mode: doc.mode,
depth: doc.depth,
vector_masks: RenderVectorMasks::default(),
@@ -572,7 +576,8 @@ fn render_content(layer: &Layer, rect: Rect, cx: &Ctx) -> Option<Buffer> {
/// The alpha of `layer`'s own content over `rect` (masks applied, row-major): the shape its
/// effect maps are built from (for the GPU compositor). Zero for adjustment layers.
pub fn layer_shape(doc: &Document, layer: &Layer, rect: Rect) -> Vec<f32> {
- let cx = Ctx::for_doc(doc);
+ let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES);
+ let cx = Ctx::for_doc(doc, &patterns);
render_content(layer, rect, &cx).map(|b| b.px.iter().map(|p| p[3]).collect()).unwrap_or_else(|| vec![0.0; rect.width() as usize * rect.height() as usize])
}
@@ -612,10 +617,11 @@ pub fn fill_frame(layer: &Layer, canvas: Rect) -> Rect {
/// A fill layer's content over `canvas`, laid out in the frame its masks give it (as the
/// compositor does) but without applying the masks: the pixels a PSD fill layer stores.
pub fn render_fill_content(layer: &Layer, f: &Fill, canvas: Rect, patterns: &[Pattern]) -> Buffer {
- render_fill(f, canvas, fill_frame(layer, canvas), patterns)
+ let prepared = pattern::PreparedPatterns::new(patterns, pattern::PREPARED_PATTERN_BYTES);
+ render_fill(f, canvas, fill_frame(layer, canvas), &prepared)
}
-fn render_fill(f: &Fill, rect: Rect, canvas: Rect, patterns: &[Pattern]) -> Buffer {
+fn render_fill(f: &Fill, rect: Rect, canvas: Rect, patterns: &pattern::PreparedPatterns<'_>) -> Buffer {
match f {
Fill::Solid(c) => {
let rgb = c.to_rgb();
@@ -642,7 +648,7 @@ fn render_fill(f: &Fill, rect: Rect, canvas: Rect, patterns: &[Pattern]) -> Buff
b
}
// Laid out from the layer's frame when linked; transparent if the pattern is missing.
- Fill::Pattern { name, scale, id, angle, link, phase } => match photocraft_doc::pattern::find(patterns, id, name).and_then(pattern::Tile::new) {
+ Fill::Pattern { name, scale, id, angle, link, phase } => match patterns.get(id, name) {
Some(tile) => Buffer { rect, px: pattern::render(&tile, &pattern::Placement::new(canvas, *link, *phase, *scale, *angle), rect) },
None => Buffer::transparent(rect),
},
@@ -949,7 +955,14 @@ fn composite_layer_plain(layer: &Layer, clipped: &[Layer], backdrop: &mut Buffer
composite_atop(c, &mut content, cx);
}
let maps = effect_maps(layer, cx);
- effects::composite_with_effects(layer, &content, backdrop, &maps, paint_bounds(layer).unwrap_or_else(|| layer_bounds(layer, cx.canvas)), cx.patterns);
+ effects::composite_with_effects_prepared(
+ layer,
+ &content,
+ backdrop,
+ &maps,
+ paint_bounds(layer).unwrap_or_else(|| layer_bounds(layer, cx.canvas)),
+ cx.patterns,
+ );
return;
}
if let Some((mut content, stroke)) = shape_parts(layer, clipped, rect, cx) {
@@ -1101,7 +1114,7 @@ fn effect_maps(layer: &Layer, cx: &Ctx) -> std::sync::Arc<effects::FxMaps> {
let region = layer_bounds(layer, cx.canvas).inflate(m).intersect(&cx.canvas.inflate(m));
if std::env::var_os("PHOTOCRAFT_FX_NOCACHE").is_some() {
let shape = render_content(layer, region, cx).map(|b| b.px.iter().map(|p| p[3]).collect()).unwrap_or_default();
- return std::sync::Arc::new(effects::build_maps(layer, shape, region, &cx.light, &texture_ctx(layer, region, cx)));
+ return std::sync::Arc::new(effects::build_maps_prepared(layer, shape, region, &cx.light, &texture_ctx(layer, region, cx), cx.patterns));
}
let mut h = std::collections::hash_map::DefaultHasher::new();
layer_identity(layer, &mut h);
@@ -1127,7 +1140,7 @@ fn effect_maps(layer: &Layer, cx: &Ctx) -> std::sync::Arc<effects::FxMaps> {
.map(|b| b.px.iter().map(|p| p[3]).collect())
.unwrap_or_else(|| vec![0.0; region.width() as usize * region.height() as usize])
};
- let maps = effects::build_maps(layer, shape, region, &cx.light, &texture_ctx(layer, region, cx));
+ let maps = effects::build_maps_prepared(layer, shape, region, &cx.light, &texture_ctx(layer, region, cx), cx.patterns);
let bytes = maps.bytes();
// Counted exactly once, when the entry is built.
fx_cache().lock().unwrap_or_else(|e| e.into_inner()).bytes += bytes;
@@ -1152,7 +1165,7 @@ fn effect_maps(layer: &Layer, cx: &Ctx) -> std::sync::Arc<effects::FxMaps> {
fn texture_ctx<'a>(layer: &Layer, region: Rect, cx: &Ctx<'a>) -> effects::TextureCtx<'a> {
let sb = paint_bounds(layer).unwrap_or_else(|| layer_bounds(layer, cx.canvas));
- effects::TextureCtx { rect: region, patterns: cx.patterns, anchor: layer.effects.reference.unwrap_or((f64::from(sb.x0), f64::from(sb.y0))) }
+ effects::TextureCtx { rect: region, patterns: cx.patterns.source(), anchor: layer.effects.reference.unwrap_or((f64::from(sb.x0), f64::from(sb.y0))) }
}
/// Composite `layer` onto `base` restricted to the base's alpha (clipping mask semantics),
@@ -1195,7 +1208,7 @@ fn composite_atop_any(layer: &Layer, base: &mut Buffer, cx: &Ctx) {
let Some(content) = render_content(layer, rect, cx) else { return };
let mut opaque = Buffer { rect, px: base.px.iter().map(|p| [p[0], p[1], p[2], 1.0]).collect() };
let maps = effect_maps(layer, cx);
- effects::composite_with_effects(
+ effects::composite_with_effects_prepared(
layer,
&content,
&mut opaque,
diff --git a/crates/compose/src/pattern.rs b/crates/compose/src/pattern.rs
index f352985c7..7adc84fa7 100644
--- a/crates/compose/src/pattern.rs
+++ b/crates/compose/src/pattern.rs
@@ -5,8 +5,76 @@
//! wrap-around on premultiplied colour, so integer placements at 100 % reproduce the tile
//! exactly and scaled ones stay seamless.
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex, OnceLock};
+
use photocraft_doc::{Pattern, Rect};
+pub(crate) const PREPARED_PATTERN_BYTES: usize = 64 << 20;
+const MAX_PREPARED_PATTERNS: usize = 64;
+type PreparedSlot = Arc<OnceLock<Option<Arc<Tile>>>>;
+
+struct PreparedState {
+ slots: HashMap<usize, PreparedSlot>,
+ reserved_bytes: usize,
+}
+
+/// Demand-prepared pixels owned by one rendering call, never by the document.
+pub(crate) struct PreparedPatterns<'a> {
+ patterns: &'a [Pattern],
+ budget: usize,
+ state: Mutex<PreparedState>,
+}
+
+impl<'a> PreparedPatterns<'a> {
+ pub(crate) fn new(patterns: &'a [Pattern], budget: usize) -> Self {
+ Self { patterns, budget, state: Mutex::new(PreparedState { slots: HashMap::new(), reserved_bytes: 0 }) }
+ }
+
+ pub(crate) fn source(&self) -> &'a [Pattern] {
+ self.patterns
+ }
+
+ pub(crate) fn get(&self, id: &str, name: &str) -> Option<Arc<Tile>> {
+ let p = photocraft_doc::pattern::find(self.patterns, id, name)?;
+ if p.is_empty() {
+ return None;
+ }
+ let bytes = usize::try_from(p.width)
+ .ok()
+ .and_then(|w| usize::try_from(p.height).ok().and_then(|h| w.checked_mul(h)))
+ .and_then(|pixels| pixels.checked_mul(std::mem::size_of::<[f32; 4]>()));
+ // The borrowed immutable slice pins these addresses for the complete call.
+ let key = std::ptr::from_ref(p) as usize;
+ let slot = {
+ let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
+ if let Some(slot) = state.slots.get(&key) {
+ Some(Arc::clone(slot))
+ } else if let Some(bytes) = bytes
+ && bytes <= self.budget.saturating_sub(state.reserved_bytes)
+ && state.slots.len() < MAX_PREPARED_PATTERNS
+ {
+ let slot: PreparedSlot = Arc::new(OnceLock::new());
+ // Reserve before initialization: concurrent pending buffers consume the budget too.
+ state.reserved_bytes += bytes;
+ state.slots.insert(key, Arc::clone(&slot));
+ Some(slot)
+ } else {
+ None
+ }
+ };
+ match slot {
+ Some(slot) => {
+ // Conversion must stay serial: Rayon work stealing can re-enter this slot
+ // while its initializer is running inside an effect-map OnceLock.
+ // Run on the requesting worker to preserve its active CMYK profile.
+ slot.get_or_init(|| Tile::new(p).map(Arc::new)).clone()
+ }
+ None => Tile::new(p).map(Arc::new),
+ }
+ }
+}
+
/// A pattern converted once to straight-alpha RGBA for sampling.
pub struct Tile {
w: usize,
@@ -140,9 +208,16 @@ mod tests {
#[test]
fn identity_placement_tiles_exactly() {
- let t = Tile::new(&checker()).unwrap();
+ let patterns = [checker()];
+ let prepared = PreparedPatterns::new(&patterns, PREPARED_PATTERN_BYTES);
+ let t = prepared.get(&patterns[0].id, "").unwrap();
+ let again = prepared.get(&patterns[0].id, "").unwrap();
+ assert!(Arc::ptr_eq(&t, &again));
+ let uncached = PreparedPatterns::new(&patterns, 0);
+ let fallback = uncached.get(&patterns[0].id, "").unwrap();
let p = Placement::new(Rect::new(0, 0, 10, 10), false, (0.0, 0.0), 1.0, 0.0);
let px = render(&t, &p, Rect::new(-4, 0, 8, 1));
+ assert_eq!(px, render(&fallback, &p, Rect::new(-4, 0, 8, 1)));
assert_eq!(px[0], [0.0, 0.0, 1.0, 1.0]); // x = -4 wraps to 0
assert_eq!(px[6], [1.0, 0.0, 0.0, 1.0]); // x = 2
assert_eq!(px[8], [0.0, 0.0, 1.0, 1.0]); // x = 4
diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs
index 4021ab537..6120184ef 100644
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@ -283,9 +283,10 @@ fn solid_and_gradient_fill_layers() {
style: photocraft_doc::GradientStyle::Linear,
reverse: false,
};
- let buf = render_fill(&g, Rect::new(0, 0, 10, 1), Rect::new(0, 0, 10, 1), &[]);
+ let patterns = pattern::PreparedPatterns::new(&[], pattern::PREPARED_PATTERN_BYTES);
+ let buf = render_fill(&g, Rect::new(0, 0, 10, 1), Rect::new(0, 0, 10, 1), &patterns);
// tile independence: a 1px render of the right edge equals the full render
- let one = render_fill(&g, Rect::new(9, 0, 10, 1), Rect::new(0, 0, 10, 1), &[]);
+ let one = render_fill(&g, Rect::new(9, 0, 10, 1), Rect::new(0, 0, 10, 1), &patterns);
assert_eq!(one.px[0], buf.px[9]);
assert!(buf.px[0][0] < buf.px[9][0], "left dark, right light");
}
@@ -685,14 +686,16 @@ fn effect_maps_are_cached_and_invalidated_by_pixel_changes() {
let mut l = solid_layer("fx", Rect::new(16, 16, 48, 48), [1.0, 0.0, 0.0, 1.0]);
l.effects.items.push(photocraft_doc::Effect::default_drop_shadow());
doc.layers.push(l);
- let cx = Ctx::for_doc(&doc);
+ let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES);
+ let cx = Ctx::for_doc(&doc, &patterns);
let a = effect_maps(&doc.layers[1], &cx);
let b = effect_maps(&doc.layers[1], &cx);
assert!(std::sync::Arc::ptr_eq(&a, &b), "second request hits the cache");
let first = flatten(&doc);
// Editing the layer's pixels changes its tiles, so the maps are rebuilt.
doc.layers[1].surface_mut().unwrap().fill_rect(Rect::new(8, 8, 20, 20), &[0.0, 0.0, 1.0, 1.0]);
- let cx = Ctx::for_doc(&doc);
+ let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES);
+ let cx = Ctx::for_doc(&doc, &patterns);
let c = effect_maps(&doc.layers[1], &cx);
assert!(!std::sync::Arc::ptr_eq(&a, &c), "pixel edit invalidates");
// Cached rendering equals a fresh build (tiled and full renders agree too).