Skip to content

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

Patterns paint in the document's colour mode (Gray, CMYK) (#1950)

kayrockscreenprinting72d78f306741
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index 028c07a33..14585bff0 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -89,7 +89,7 @@ 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 patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES);
+ let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode);
let cx = Ctx::for_doc(doc, &patterns);
render_tiled_with(doc, rect, tile, &cx)
}
@@ -210,7 +210,7 @@ pub fn render_bands<E>(doc: &Document, rect: Rect, band_rows: i32, mut sink: imp
return Ok(());
}
// 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 patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode);
let cx = Ctx::for_doc(doc, &patterns);
let rows = band_rows_for(rect.width(), band_rows);
let mut y = rect.y0;
@@ -756,7 +756,7 @@ fn render_content(layer: &Layer, rect: Rect, cx: &Ctx) -> Option<Buffer> {
///
/// See also [`stroke_frame`].
pub fn layer_shape(doc: &Document, layer: &Layer, rect: Rect) -> Vec<f32> {
- let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES);
+ let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode);
let cx = Ctx::for_doc(doc, &patterns);
effect_shape(layer, rect, &cx)
}
@@ -768,7 +768,7 @@ pub fn stroke_frame(doc: &Document, layer: &Layer, st: &photocraft_doc::StrokeFx
if !matches!(st.paint, photocraft_doc::FxPaint::Gradient(_)) || !effects::has_effects(layer) {
return None;
}
- let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES);
+ let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode);
let cx = Ctx::for_doc(doc, &patterns);
effect_maps(layer, doc.bounds(), &cx).stroke_frame(st)
}
diff --git a/crates/compose/src/pattern.rs b/crates/compose/src/pattern.rs
index 7adc84fa7..a55c2c8ab 100644
--- a/crates/compose/src/pattern.rs
+++ b/crates/compose/src/pattern.rs
@@ -8,7 +8,7 @@
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};
-use photocraft_doc::{Pattern, Rect};
+use photocraft_doc::{ColorMode, Pattern, PixelFormat, Rect, SampleType};
pub(crate) const PREPARED_PATTERN_BYTES: usize = 64 << 20;
const MAX_PREPARED_PATTERNS: usize = 64;
@@ -23,12 +23,20 @@ struct PreparedState {
pub(crate) struct PreparedPatterns<'a> {
patterns: &'a [Pattern],
budget: usize,
+ /// The colour mode the patterns are painted into (see [`pattern_rgba`]).
+ mode: ColorMode,
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 }) }
+ Self { patterns, budget, mode: ColorMode::Rgb, state: Mutex::new(PreparedState { slots: HashMap::new(), reserved_bytes: 0 }) }
+ }
+
+ /// Patterns painted into a document of colour mode `mode`.
+ pub(crate) fn in_mode(mut self, mode: ColorMode) -> Self {
+ self.mode = mode;
+ self
}
pub(crate) fn source(&self) -> &'a [Pattern] {
@@ -68,13 +76,33 @@ impl<'a> PreparedPatterns<'a> {
// 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()
+ slot.get_or_init(|| Tile::new_in(p, self.mode).map(Arc::new)).clone()
}
- None => Tile::new(p).map(Arc::new),
+ None => Tile::new_in(p, self.mode).map(Arc::new),
}
}
}
+/// A pattern's pixels (straight-alpha RGBA, row-major) as they look painted into a document of
+/// colour mode `mode`. A pattern keeps its own colours (an RGB pattern stays RGB, in the
+/// library and in the document), but in a Grayscale or CMYK document it paints that mode's
+/// colours: what Edit › Fill writes into the document's pixels, and what Photoshop shows (the
+/// pattern in colour in its picker, filled in grey).
+pub fn pattern_rgba(p: &Pattern, mode: ColorMode) -> Vec<[f32; 4]> {
+ let mut px = vec![[0.0f32; 4]; (p.width as usize).saturating_mul(p.height as usize)];
+ p.surface.read_rgba_into(p.rect(), &mut px);
+ let paints_in = matches!(mode, ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone | ColorMode::Cmyk);
+ if paints_in && p.surface.format().mode != mode {
+ let fmt = PixelFormat::new(mode, SampleType::F32, true);
+ let mut v = [0.0f32; 5];
+ for q in &mut px {
+ let n = photocraft_raster::from_rgba_into(&fmt, *q, &mut v);
+ *q = photocraft_raster::to_rgba(&fmt, v.get(..n).unwrap_or_default());
+ }
+ }
+ px
+}
+
/// A pattern converted once to straight-alpha RGBA for sampling.
pub struct Tile {
w: usize,
@@ -85,12 +113,16 @@ pub struct Tile {
impl Tile {
pub fn new(p: &Pattern) -> Option<Tile> {
+ Tile::new_in(p, ColorMode::Rgb)
+ }
+
+ /// The tile of `p` painted into a document of colour mode `mode` (see [`pattern_rgba`]).
+ pub fn new_in(p: &Pattern, mode: ColorMode) -> Option<Tile> {
if p.is_empty() {
return None;
}
let (w, h) = (p.width as usize, p.height as usize);
- let mut px = vec![[0.0f32; 4]; w * h];
- p.surface.read_rgba_into(p.rect(), &mut px);
+ let mut px = pattern_rgba(p, mode);
for q in &mut px {
for c in 0..3 {
q[c] *= q[3];
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index ed1c84a89..1c4bec9ed 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -644,4 +644,6 @@ pub(crate) fn fix_selection(st: &mut DocState) {
#[cfg(test)]
mod fill_layer_mode_tests;
#[cfg(test)]
+mod pattern_mode_tests;
+#[cfg(test)]
mod tests;
diff --git a/crates/engine/src/pattern_mode_tests.rs b/crates/engine/src/pattern_mode_tests.rs
new file mode 100644
index 000000000..e917cd9cc
--- /dev/null
+++ b/crates/engine/src/pattern_mode_tests.rs
@@ -0,0 +1,95 @@
+//! Patterns paint in the document's colour mode, as in Photoshop: a pattern keeps its own colours
+//! (an RGB pattern stays RGB, in the library and in the document), but a pattern fill in a
+//! Grayscale or CMYK document shows what Edit › Fill with that pattern paints, and converting
+//! back to RGB brings the colours back (the follow-up to #1907; #1905 is about solid and
+//! gradient fills).
+
+use crate::Session;
+use photocraft_doc::ColorMode;
+use serde_json::json;
+
+/// Defines a blue-and-yellow RGB pattern from a scratch document and returns its id.
+fn colour_pattern(s: &mut Session) -> String {
+ s.execute("file.new", json!({"width": 8, "height": 8, "mode": "rgb", "depth": 8, "background": "white"})).unwrap();
+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": 4, "height": 8})).unwrap();
+ s.execute("edit.fill", json!({"contents": "color", "color": "#2040e0"})).unwrap();
+ s.execute("select.inverse", json!({})).unwrap();
+ s.execute("edit.fill", json!({"contents": "color", "color": "#e0d020"})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ let r = s.execute("edit.definePattern", json!({"name": "Blue Yellow"})).unwrap();
+ r["pattern"].as_str().unwrap().to_string()
+}
+
+fn pixel(s: &mut Session, x: i32, y: i32) -> [f32; 4] {
+ let v = s.execute("document.pixel", json!({"x": x, "y": y})).unwrap();
+ let a: Vec<f32> = v.as_array().unwrap().iter().map(|c| c.as_f64().unwrap() as f32).collect();
+ [a[0], a[1], a[2], a[3]]
+}
+
+fn close(a: [f32; 4], b: [f32; 4], tol: f32) -> bool {
+ a.iter().zip(&b).all(|(x, y)| (x - y).abs() <= tol)
+}
+
+fn neutral(p: [f32; 4]) -> bool {
+ p[0] == p[1] && p[1] == p[2]
+}
+
+const XS: [i32; 4] = [1, 5, 9, 14];
+
+/// The composite where `pat` is painted with Edit › Fill on a pixel layer of a new document.
+fn painted(s: &mut Session, mode: &str, depth: u32, pat: &str) -> Vec<[f32; 4]> {
+ s.execute("file.new", json!({"width": 32, "height": 16, "mode": mode, "depth": depth, "background": "white"})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("edit.fill", json!({"contents": "pattern", "pattern": pat})).unwrap();
+ XS.iter().map(|x| pixel(s, *x, 3)).collect()
+}
+
+fn pattern_mode(s: &Session) -> ColorMode {
+ s.active().unwrap().doc.patterns[0].surface.format().mode
+}
+
+#[test]
+fn pattern_fills_paint_like_edit_fill_in_every_mode() {
+ for (mode, cm) in [("gray", ColorMode::Grayscale), ("cmyk", ColorMode::Cmyk), ("lab", ColorMode::Lab), ("rgb", ColorMode::Rgb)] {
+ for depth in [8, 16, 32] {
+ let mut s = Session::new();
+ let pat = colour_pattern(&mut s);
+ let want = painted(&mut s, mode, depth, &pat);
+ s.execute("file.new", json!({"width": 32, "height": 16, "mode": mode, "depth": depth, "background": "white"})).unwrap();
+ s.execute("layer.newFillLayer.pattern", json!({"pattern": pat})).unwrap();
+ assert_eq!(pattern_mode(&s), ColorMode::Rgb, "{mode}/{depth}: the pattern keeps its own colours");
+ for (x, w) in XS.iter().zip(&want) {
+ let got = pixel(&mut s, *x, 3);
+ // Lab: Edit › Fill quantizes Lab at 8/16 bits; the fill layer draws the RGB pattern.
+ let tol = if cm == ColorMode::Lab { 0.02 } else { 0.01 };
+ assert!(close(got, *w, tol), "{mode}/{depth} x {x}: pattern fill {got:?}, Edit › Fill {w:?}");
+ if cm == ColorMode::Grayscale {
+ assert!(neutral(got), "{mode}/{depth} x {x}: {got:?}");
+ }
+ }
+ }
+ }
+}
+
+#[test]
+fn a_grayscale_round_trip_keeps_the_pattern_colours() {
+ for depth in [8, 16] {
+ let mut s = Session::new();
+ let pat = colour_pattern(&mut s);
+ s.execute("file.new", json!({"width": 32, "height": 16, "mode": "rgb", "depth": depth, "background": "white"})).unwrap();
+ s.execute("layer.newFillLayer.pattern", json!({"pattern": pat})).unwrap();
+ let rgb: Vec<[f32; 4]> = XS.iter().map(|x| pixel(&mut s, *x, 3)).collect();
+ assert!(rgb[0][2] > 0.8 && rgb[0][0] < 0.2, "blue in RGB: {:?}", rgb[0]);
+ s.execute("image.mode.grayscale", json!({})).unwrap();
+ for x in XS {
+ let p = pixel(&mut s, x, 3);
+ assert!(neutral(p), "depth {depth} x {x}: grey in Grayscale, {p:?}");
+ }
+ assert_eq!(pattern_mode(&s), ColorMode::Rgb, "the document's pattern keeps its colours");
+ s.execute("image.mode.rgb", json!({})).unwrap();
+ for (x, want) in XS.iter().zip(&rgb) {
+ let p = pixel(&mut s, *x, 3);
+ assert!(close(p, *want, 1e-6), "depth {depth} x {x}: colour back in RGB, {p:?} vs {want:?}");
+ }
+ }
+}
diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs
index 25d9c778d..5551924f0 100644
--- a/crates/gpu/src/lib.rs
+++ b/crates/gpu/src/lib.rs
@@ -388,6 +388,9 @@ pub struct Compositor {
/// Effect temporaries (R32F, region sized) and the frame they were last used.
temps: Vec<(Tex, u64)>,
patterns: HashMap<String, (u64, Tex)>,
+ /// The colour mode of the document being encoded: patterns paint in it
+ /// (`photocraft_compose::pattern::pattern_rgba`).
+ pattern_mode: photocraft_color::ColorMode,
/// Texture side limit the paging is planned for (the device's, or smaller in tests).
max_dim: u32,
/// The device's real texture side limit.
@@ -590,6 +593,7 @@ impl Compositor {
fx: HashMap::new(),
temps: Vec::new(),
patterns: HashMap::new(),
+ pattern_mode: photocraft_color::ColorMode::Rgb,
max_dim: 0,
device_max: device.limits().max_texture_dimension_2d,
page: PAGE,
@@ -853,6 +857,7 @@ impl Compositor {
let region = region.intersect(&canvas);
let plan = plan(doc)?;
self.check_fx(doc, &plan)?;
+ self.pattern_mode = doc.pixel_format().mode;
let mut stats = Stats { passes: plan.passes.len(), slots: plan.slots, ..Default::default() };
if region.is_empty() {
return Ok(stats);
@@ -1322,20 +1327,21 @@ impl Compositor {
Some((key, [region.x0, region.y0, region.width() as i32, region.height() as i32]))
}
- /// Premultiplied RGBA32F texture of a pattern (cached by pixel identity).
+ /// Premultiplied RGBA32F texture of a pattern as it paints in the document's mode (cached by
+ /// pixel identity and mode).
fn pattern_view(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, pat: &Pattern) -> wgpu::TextureView {
let fp = pat.surface.tiles().fold((pat.width as u64) << 32 | pat.height as u64, |acc, (c, t)| {
acc.wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ (Arc::as_ptr(t) as usize as u64) ^ ((c.tx as u64) << 20) ^ c.ty as u64
});
- let key = format!("{}\u{0}{}", pat.id, pat.name);
+ let mode = self.pattern_mode;
+ let key = format!("{}\u{0}{}\u{0}{mode:?}", pat.id, pat.name);
if let Some((f, t)) = self.patterns.get(&key)
&& *f == fp
{
return t.view.clone();
}
let (w, h) = (pat.width, pat.height);
- let mut px = vec![[0.0f32; 4]; w as usize * h as usize];
- pat.surface.read_rgba_into(pat.rect(), &mut px);
+ let px = photocraft_compose::pattern::pattern_rgba(pat, mode);
let bytes: Vec<u8> = px.iter().flat_map(|q| [q[0] * q[3], q[1] * q[3], q[2] * q[3], q[3]]).flat_map(f32::to_le_bytes).collect();
let t = Tex::new(device, "pc_pattern", w, h, wgpu::TextureFormat::Rgba32Float, wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST);
queue.write_texture(
diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rs
index 0b700d5f1..aab24bef5 100644
--- a/crates/gpu/tests/parity.rs
+++ b/crates/gpu/tests/parity.rs
@@ -1539,6 +1539,39 @@ fn pattern_fill_layers() {
}
}
+/// An RGB pattern paints in the document's mode: grey in a Grayscale document, CMYK colours in
+/// a CMYK one (fills and Pattern Overlay), on the GPU as on the CPU.
+#[test]
+fn rgb_patterns_paint_in_the_document_mode() {
+ let Some(mut g) = gpu() else { return };
+ let pat = checker_pattern();
+ for (mode, fmt) in [(ColorMode::Grayscale, PixelFormat::GRAYA8), (ColorMode::Cmyk, PixelFormat::CMYKA8)] {
+ let mut d = Document::new("m", Size::new(60, 40), mode, SampleType::U8);
+ d.layers.push(noise_layer("bg", fmt, Rect::new(0, 0, 60, 40), 63, 0.0));
+ d.patterns.push(pat.clone());
+ let fill = Fill::Pattern { name: pat.name.clone(), id: pat.id.clone(), scale: 1.0, angle: 0.0, link: true, phase: (0.0, 0.0) };
+ let mut l = Layer::new("pat", LayerContent::Fill(fill));
+ l.mask = Some(mask(Rect::new(0, 0, 30, 40), 64, 0.0));
+ d.layers.push(l);
+ let mut o = blob("overlay", d.pixel_format(), 45.0, 20.0, 12.0, [0.9, 0.4, 0.2]);
+ o.effects.items = vec![Effect::PatternOverlay {
+ common: FxCommon::new(BlendMode::Normal, 1.0),
+ name: pat.name.clone(),
+ id: pat.id.clone(),
+ scale: 1.0,
+ angle: 0.0,
+ link: true,
+ phase: (0.0, 0.0),
+ }];
+ d.layers.push(o);
+ if mode == ColorMode::Grayscale {
+ let cpu = photocraft_compose::flatten(&d);
+ assert!(cpu.px.iter().all(|p| (p[0] - p[1]).abs() < 1e-6 && (p[1] - p[2]).abs() < 1e-6), "a Grayscale composite is neutral");
+ }
+ fx_check(&mut g, &d, &format!("RGB pattern in {mode:?}"));
+ }
+}
+
#[test]
fn lab_documents_mix_in_lab() {
let Some(mut g) = gpu() else { return };