mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge #16479 into the merge queue batch
Patterns paint the grey profile's greys in Grayscale documents (#14975)
This commit is contained in:
commit
44c2a2937d
17 files changed
+556
-61
No files matched your search
@@ -654,7 +654,7 @@ pub fn render_display(doc: &Document, rect: Rect) -> Option<super::Buffer> {
|
||||
/// [`render_cmyk`] with an explicit tile size (tests check tile independence).
|
||||
pub fn render_cmyk_tiled(doc: &Document, rect: Rect, tile: i32) -> Option<CmykBuffer> {
|
||||
if supports(doc) {
|
||||
let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode);
|
||||
let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_doc(doc);
|
||||
let cx = Ctx::for_doc(doc, &patterns);
|
||||
let space = super::cmyk_space(doc);
|
||||
return Some(render_with(rect, tile, |t| render_tile(doc, t, &cx, space.as_ref())));
|
||||
@@ -721,7 +721,7 @@ pub fn render_cmyk_bands<E>(doc: &Document, rect: Rect, band_rows: i32, mut sink
|
||||
if !supports(doc) {
|
||||
return split::supports(doc).then(|| split::render_bands(doc, rect, band_rows, RENDER_TILE, sink));
|
||||
}
|
||||
let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode);
|
||||
let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_doc(doc);
|
||||
let cx = Ctx::for_doc(doc, &patterns);
|
||||
let space = super::cmyk_space(doc);
|
||||
let rows = super::band_rows_for(rect.width(), band_rows);
|
||||
|
||||
@@ -85,7 +85,7 @@ pub(crate) fn render_content_with<A: BufferAlloc>(layer: &Layer, rect: Rect, cx:
|
||||
///
|
||||
/// 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).in_mode(doc.pixel_format().mode);
|
||||
let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_doc(doc);
|
||||
let cx = Ctx::for_doc(doc, &patterns);
|
||||
effect_shape(layer, rect, &cx)
|
||||
}
|
||||
@@ -97,7 +97,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).in_mode(doc.pixel_format().mode);
|
||||
let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_doc(doc);
|
||||
let cx = Ctx::for_doc(doc, &patterns);
|
||||
effect_maps(layer, doc.bounds(), &cx).stroke_frame(st)
|
||||
}
|
||||
@@ -187,9 +187,17 @@ 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.
|
||||
/// compositor does) but without applying the masks: the pixels a PSD fill layer stores. A pattern
|
||||
/// keeps its own colours; [`render_fill_content_in`] paints it as a document does.
|
||||
pub fn render_fill_content(layer: &Layer, f: &Fill, canvas: Rect, patterns: &[Pattern]) -> Buffer {
|
||||
let prepared = pattern::PreparedPatterns::new(patterns, pattern::PREPARED_PATTERN_BYTES);
|
||||
render_fill_content_in(layer, f, canvas, patterns, pattern::PatternSpace::Mode(photocraft_color::ColorMode::Rgb))
|
||||
}
|
||||
|
||||
/// [`render_fill_content`] with a pattern painted in `space`. A file stores the pixels of a
|
||||
/// document's fill layers in [`pattern::PatternSpace::of_pixels`] of the document, so they are
|
||||
/// what the compositor shows for the layer.
|
||||
pub fn render_fill_content_in(layer: &Layer, f: &Fill, canvas: Rect, patterns: &[Pattern], space: pattern::PatternSpace) -> Buffer {
|
||||
let prepared = pattern::PreparedPatterns::new(patterns, pattern::PREPARED_PATTERN_BYTES).in_space(space);
|
||||
render_fill(f, canvas, fill_frame(layer, canvas), &prepared, None)
|
||||
}
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ use content::empty_in;
|
||||
use content::render_content;
|
||||
#[cfg(test)]
|
||||
use content::render_fill;
|
||||
pub use content::{RENDER_TILE, channel_weights, fill_frame, layer_shape, render_fill_content, stroke_frame, surface_to_buffer};
|
||||
pub use content::{RENDER_TILE, channel_weights, fill_frame, layer_shape, render_fill_content, render_fill_content_in, stroke_frame, surface_to_buffer};
|
||||
use ctx::{Ctx, prepare_effects};
|
||||
#[cfg(test)]
|
||||
use ctx::{LayerKeys, PREPARE_DEPTH, effect_layers, prepare_tones};
|
||||
|
||||
+157
-32
@@ -11,7 +11,7 @@ use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, OnceLock, Weak};
|
||||
|
||||
use photocraft_doc::{ColorMode, Pattern, PixelFormat, Rect, SampleType};
|
||||
use photocraft_doc::{ColorMode, Document, Pattern, PixelFormat, Rect, SampleType};
|
||||
|
||||
/// What one rendering call may keep of its patterns' working copies: every pattern it paints with
|
||||
/// stays converted for the call (four of the largest 8-bit ones on desktop), so none is converted
|
||||
@@ -49,8 +49,8 @@ struct OverBudget {
|
||||
pub(crate) struct PreparedPatterns<'a> {
|
||||
patterns: &'a [Pattern],
|
||||
budget: usize,
|
||||
/// The colour mode the patterns are painted into (see [`pattern_rgba`]).
|
||||
mode: ColorMode,
|
||||
/// How the document the patterns are painted into takes their colours (see [`pattern_rgba`]).
|
||||
space: PatternSpace,
|
||||
state: Mutex<PreparedState>,
|
||||
over_budget: OverBudget,
|
||||
}
|
||||
@@ -60,15 +60,20 @@ impl<'a> PreparedPatterns<'a> {
|
||||
Self {
|
||||
patterns,
|
||||
budget,
|
||||
mode: ColorMode::Rgb,
|
||||
space: PatternSpace::Mode(ColorMode::Rgb),
|
||||
state: Mutex::new(PreparedState { slots: HashMap::new(), reserved_bytes: 0 }),
|
||||
over_budget: OverBudget::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Patterns painted into a document of colour mode `mode`.
|
||||
pub(crate) fn in_mode(mut self, mode: ColorMode) -> Self {
|
||||
self.mode = mode;
|
||||
/// Patterns painted into `doc` ([`PatternSpace::of`]).
|
||||
pub(crate) fn in_doc(self, doc: &Document) -> Self {
|
||||
self.in_space(PatternSpace::of(doc))
|
||||
}
|
||||
|
||||
/// Patterns painted in `space`.
|
||||
pub(crate) fn in_space(mut self, space: PatternSpace) -> Self {
|
||||
self.space = space;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -106,7 +111,7 @@ 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_in(p, self.mode).map(Arc::new)).clone()
|
||||
slot.get_or_init(|| Tile::new_in(p, self.space).map(Arc::new)).clone()
|
||||
}
|
||||
// Uncached path: a pattern whose working copy would exceed an absolute cap is not
|
||||
// materialized at all. One past the call's budget is converted under one lock, and
|
||||
@@ -137,7 +142,7 @@ impl<'a> PreparedPatterns<'a> {
|
||||
);
|
||||
}
|
||||
}
|
||||
let tile = Tile::new_in(p, self.mode).map(Arc::new)?;
|
||||
let tile = Tile::new_in(p, self.space).map(Arc::new)?;
|
||||
live.retain(|_, w| w.strong_count() > 0);
|
||||
live.insert(key, Arc::downgrade(&tile));
|
||||
Some(tile)
|
||||
@@ -146,16 +151,103 @@ impl<'a> PreparedPatterns<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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). Empty for a pattern that isn't
|
||||
/// How a document takes the colours of the patterns painted into it. A [`ColorMode`] converts to
|
||||
/// [`PatternSpace::Mode`], so a caller that names a colour mode gets that mode's pixel-format
|
||||
/// conversion; a document's own space is [`PatternSpace::of`] it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum PatternSpace {
|
||||
/// As the pixel format of this colour mode converts them: the pattern's own colours in RGB
|
||||
/// and Lab, the inks in CMYK, and in Grayscale the luma formula's grey.
|
||||
Mode(ColorMode),
|
||||
/// Grey through the grey profile (#14975): sRGB to sGray, relative colorimetric with black
|
||||
/// point compensation, as the swatch colours convert (`swatch_in_doc` in the engine).
|
||||
/// Measured in the reference application, an RGB pattern's blue, green and red paint grey
|
||||
/// 69, 221 and 129 of 255 in an 8-bit Grayscale document.
|
||||
ProfileGray,
|
||||
}
|
||||
|
||||
impl From<ColorMode> for PatternSpace {
|
||||
fn from(mode: ColorMode) -> Self {
|
||||
PatternSpace::Mode(mode)
|
||||
}
|
||||
}
|
||||
|
||||
impl PatternSpace {
|
||||
/// How `doc` takes the patterns the compositor paints into it (Pattern Overlay, pattern fill
|
||||
/// layers, pattern strokes). An 8- or 16-bit Grayscale document in the default grey working
|
||||
/// space takes them through the grey profile. What #14975 did not measure keeps the
|
||||
/// pixel-format conversion of the document's colour mode: 32-bit Grayscale, Duotone and
|
||||
/// Bitmap documents, and a Grayscale document tagged with another grey profile.
|
||||
pub fn of(doc: &Document) -> Self {
|
||||
if doc.mode == ColorMode::Grayscale && doc.depth != SampleType::F32 && in_default_gray_space(doc.icc_profile.as_ref()) {
|
||||
PatternSpace::ProfileGray
|
||||
} else {
|
||||
PatternSpace::Mode(doc.pixel_format().mode)
|
||||
}
|
||||
}
|
||||
|
||||
/// The space of a tile whose pixels are written into `doc` in its pixel format (Edit › Fill,
|
||||
/// the Paint Bucket, the pixels a file stores for a pattern fill layer): the grey profile's
|
||||
/// greys where the compositor paints them ([`Self::of`]), so the written pixels are what a
|
||||
/// pattern fill layer shows; everywhere else the pattern's own colours, which the pixel
|
||||
/// format converts.
|
||||
pub fn of_pixels(doc: &Document) -> Self {
|
||||
match Self::of(doc) {
|
||||
PatternSpace::ProfileGray => PatternSpace::ProfileGray,
|
||||
PatternSpace::Mode(_) => PatternSpace::Mode(ColorMode::Rgb),
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour mode of the painted pattern.
|
||||
fn mode(self) -> ColorMode {
|
||||
match self {
|
||||
PatternSpace::Mode(mode) => mode,
|
||||
PatternSpace::ProfileGray => ColorMode::Grayscale,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a Grayscale document with the embedded profile `icc` is in the default grey working
|
||||
/// space (the engine's `swatch_in_doc` asks the same of the document): untagged, tagged with
|
||||
/// bytes that are no grey profile (the document's profile is then the default one), or tagged
|
||||
/// with the default grey profile itself. Cached by allocation, like
|
||||
/// `photocraft_color::convert::CmykSpace::for_profile`, so asking per render is cheap.
|
||||
fn in_default_gray_space(icc: Option<&Arc<Vec<u8>>>) -> bool {
|
||||
type Cache = Mutex<Vec<(Weak<Vec<u8>>, bool)>>;
|
||||
static CACHE: OnceLock<Cache> = OnceLock::new();
|
||||
let Some(bytes) = icc else { return true };
|
||||
let cached = |c: &[(Weak<Vec<u8>>, bool)]| c.iter().find(|(w, _)| w.as_ptr() == Arc::as_ptr(bytes)).map(|(_, default)| *default);
|
||||
let cache = CACHE.get_or_init(Default::default);
|
||||
{
|
||||
let mut c = cache.lock().unwrap_or_else(|e| e.into_inner());
|
||||
c.retain(|(w, _)| w.strong_count() > 0);
|
||||
if let Some(default) = cached(&c) {
|
||||
return default;
|
||||
}
|
||||
}
|
||||
let default = match craft_cms::Profile::parse(bytes) {
|
||||
Ok(p) if p.color_space == craft_cms::ColorSpace::Gray => {
|
||||
craft_cms::builtin::default_for(craft_cms::ColorSpace::Gray).is_some_and(|d| p.content_hash() == d.content_hash())
|
||||
}
|
||||
_ => true,
|
||||
};
|
||||
let mut c = cache.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if cached(&c).is_none() {
|
||||
c.push((Arc::downgrade(bytes), default));
|
||||
}
|
||||
default
|
||||
}
|
||||
|
||||
/// A pattern's pixels (straight-alpha RGBA, row-major) as they look painted in `space` (a colour
|
||||
/// mode, or a document's [`PatternSpace`]). 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). Empty for a pattern that isn't
|
||||
/// [paintable](Pattern::is_paintable), or whose full RGBA32F copy exceeds the working
|
||||
/// budget. Compact paintable patterns can instead be consumed with [`pattern_rgba_bands`].
|
||||
pub fn pattern_rgba(p: &Pattern, mode: ColorMode) -> Vec<[f32; 4]> {
|
||||
pub fn pattern_rgba(p: &Pattern, space: impl Into<PatternSpace>) -> Vec<[f32; 4]> {
|
||||
let mut px = Vec::new();
|
||||
if p.is_paintable() && pattern_rgba_rows(p, mode, 0, p.height, &mut px).is_none() {
|
||||
if p.is_paintable() && pattern_rgba_rows(p, space, 0, p.height, &mut px).is_none() {
|
||||
px = Vec::new();
|
||||
}
|
||||
px
|
||||
@@ -165,18 +257,24 @@ pub fn pattern_rgba(p: &Pattern, mode: ColorMode) -> Vec<[f32; 4]> {
|
||||
/// pattern is read a band at a time instead of as one copy at 16 bytes per pixel. `None` when the
|
||||
/// memory for the rows cannot be had (on the web a failed allocation aborts the tab, so it is
|
||||
/// asked for, not assumed).
|
||||
pub fn pattern_rgba_rows(p: &Pattern, mode: ColorMode, top: u32, bottom: u32, out: &mut Vec<[f32; 4]>) -> Option<()> {
|
||||
pattern_rgba_rows_in(p, mode, top, bottom, out, photocraft_doc::pattern::MAX_WORKING_BYTES)
|
||||
pub fn pattern_rgba_rows(p: &Pattern, space: impl Into<PatternSpace>, top: u32, bottom: u32, out: &mut Vec<[f32; 4]>) -> Option<()> {
|
||||
pattern_rgba_rows_in(p, space, top, bottom, out, photocraft_doc::pattern::MAX_WORKING_BYTES)
|
||||
}
|
||||
|
||||
/// Stream straight-alpha RGBA rows using at most `max_band_bytes` of pixel scratch.
|
||||
/// Paintability and a complete row fitting the budget are checked before the callback runs.
|
||||
/// A callback refusal or allocation failure stops consumption; callers must not publish
|
||||
/// partially prepared resources as complete.
|
||||
pub fn pattern_rgba_bands(p: &Pattern, mode: ColorMode, max_band_bytes: u64, mut consume: impl FnMut(u32, &[[f32; 4]]) -> Option<()>) -> Option<()> {
|
||||
pub fn pattern_rgba_bands(
|
||||
p: &Pattern,
|
||||
space: impl Into<PatternSpace>,
|
||||
max_band_bytes: u64,
|
||||
mut consume: impl FnMut(u32, &[[f32; 4]]) -> Option<()>,
|
||||
) -> Option<()> {
|
||||
if !p.is_paintable() {
|
||||
return None;
|
||||
}
|
||||
let space = space.into();
|
||||
let budget = max_band_bytes.min(photocraft_doc::pattern::MAX_WORKING_BYTES);
|
||||
let row_bytes = u64::from(p.width).checked_mul(std::mem::size_of::<[f32; 4]>() as u64)?;
|
||||
let rows = u32::try_from((budget / row_bytes).min(u64::from(photocraft_doc::pattern::BAND_ROWS))).ok()?;
|
||||
@@ -185,13 +283,13 @@ pub fn pattern_rgba_bands(p: &Pattern, mode: ColorMode, max_band_bytes: u64, mut
|
||||
}
|
||||
let mut band = Vec::new();
|
||||
for top in (0..p.height).step_by(rows as usize) {
|
||||
pattern_rgba_rows_in(p, mode, top, top.saturating_add(rows), &mut band, budget)?;
|
||||
pattern_rgba_rows_in(p, space, top, top.saturating_add(rows), &mut band, budget)?;
|
||||
consume(top, &band)?;
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
fn pattern_rgba_rows_in(p: &Pattern, mode: ColorMode, top: u32, bottom: u32, out: &mut Vec<[f32; 4]>, max_bytes: u64) -> Option<()> {
|
||||
fn pattern_rgba_rows_in(p: &Pattern, space: impl Into<PatternSpace>, top: u32, bottom: u32, out: &mut Vec<[f32; 4]>, max_bytes: u64) -> Option<()> {
|
||||
let bottom = bottom.min(p.height);
|
||||
let top = top.min(bottom);
|
||||
out.clear();
|
||||
@@ -205,8 +303,22 @@ fn pattern_rgba_rows_in(p: &Pattern, mode: ColorMode, top: u32, bottom: u32, out
|
||||
out.try_reserve_exact(pixels).ok()?;
|
||||
out.resize(pixels, [0.0f32; 4]);
|
||||
p.surface.read_rgba_into(Rect::new(0, top as i32, p.width as i32, bottom as i32), out);
|
||||
let space = space.into();
|
||||
let mode = space.mode();
|
||||
let paints_in = matches!(mode, ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone | ColorMode::Cmyk);
|
||||
if paints_in && p.surface.format().mode != mode {
|
||||
if space == PatternSpace::ProfileGray
|
||||
&& let Some(t) = rgb_to_profile_gray()
|
||||
{
|
||||
for q in out.iter_mut() {
|
||||
let mut g = [0.0f32; 16];
|
||||
if t.eval(&[q[0], q[1], q[2]], &mut g).is_ok() && g[0].is_finite() {
|
||||
let g = g[0].clamp(0.0, 1.0);
|
||||
*q = [g, g, g, q[3]];
|
||||
}
|
||||
}
|
||||
return Some(());
|
||||
}
|
||||
let fmt = PixelFormat::new(mode, SampleType::F32, true);
|
||||
let mut v = [0.0f32; 5];
|
||||
for q in out.iter_mut() {
|
||||
@@ -217,17 +329,25 @@ fn pattern_rgba_rows_in(p: &Pattern, mode: ColorMode, top: u32, bottom: u32, out
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// The pixels of a paintable pattern as they paint in a document of colour mode `mode`, rounded
|
||||
/// The pattern colour (sRGB) to grey transform of [`PatternSpace::ProfileGray`]. `None` when the
|
||||
/// transform cannot be built, which keeps the luma conversion.
|
||||
fn rgb_to_profile_gray() -> Option<Arc<craft_cms::Transform>> {
|
||||
let opts = craft_cms::TransformOptions { intent: craft_cms::Intent::RelativeColorimetric, bpc: true, ..Default::default() };
|
||||
craft_cms::transform::cached(craft_cms::Builtin::Srgb.profile(), craft_cms::Builtin::SGray.profile(), opts).ok()
|
||||
}
|
||||
|
||||
/// The pixels of a paintable pattern as they paint in `space` ([`pattern_rgba`]), rounded
|
||||
/// to the pattern's own sample grid by `quantize`, read a band of rows at a time: no full-size
|
||||
/// `f32` copy. A pattern with its own colours comes through exactly (its samples are on that
|
||||
/// grid); one converted to a grey or CMYK document is rounded to the grid it was drawn on. `None`
|
||||
/// when the memory cannot be had.
|
||||
fn quantized_rgba<T>(p: &Pattern, mode: ColorMode, quantize: impl Fn(f32) -> T) -> Option<Vec<[T; 4]>> {
|
||||
fn quantized_rgba<T>(p: &Pattern, space: impl Into<PatternSpace>, quantize: impl Fn(f32) -> T) -> Option<Vec<[T; 4]>> {
|
||||
let space = space.into();
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact((p.width as usize).checked_mul(p.height as usize)?).ok()?;
|
||||
let mut band = Vec::new();
|
||||
for top in (0..p.height).step_by(photocraft_doc::pattern::BAND_ROWS as usize) {
|
||||
pattern_rgba_rows(p, mode, top, top + photocraft_doc::pattern::BAND_ROWS, &mut band)?;
|
||||
pattern_rgba_rows(p, space, top, top + photocraft_doc::pattern::BAND_ROWS, &mut band)?;
|
||||
out.extend(band.iter().map(|c| [quantize(c[0]), quantize(c[1]), quantize(c[2]), quantize(c[3])]));
|
||||
}
|
||||
Some(out)
|
||||
@@ -267,24 +387,25 @@ impl Tile {
|
||||
Tile::new_in(p, ColorMode::Rgb)
|
||||
}
|
||||
|
||||
/// The tile of `p` painted into a document of colour mode `mode` (see [`pattern_rgba`]).
|
||||
/// `None` when the pattern isn't [paintable](Pattern::is_paintable).
|
||||
pub fn new_in(p: &Pattern, mode: ColorMode) -> Option<Tile> {
|
||||
/// The tile of `p` painted in `space`: a colour mode, or a document's [`PatternSpace`] (see
|
||||
/// [`pattern_rgba`]). `None` when the pattern isn't [paintable](Pattern::is_paintable).
|
||||
pub fn new_in(p: &Pattern, space: impl Into<PatternSpace>) -> Option<Tile> {
|
||||
if !p.is_paintable() {
|
||||
return None;
|
||||
}
|
||||
Tile::build(p, mode, p.pixel_count().saturating_mul(16) > photocraft_doc::pattern::MAX_WORKING_BYTES)
|
||||
Tile::build(p, space, p.pixel_count().saturating_mul(16) > photocraft_doc::pattern::MAX_WORKING_BYTES)
|
||||
}
|
||||
|
||||
/// [`Tile::new_in`], held at the pattern's own depth when `compact` and it has a smaller form.
|
||||
fn build(p: &Pattern, mode: ColorMode, compact: bool) -> Option<Tile> {
|
||||
fn build(p: &Pattern, space: impl Into<PatternSpace>, compact: bool) -> Option<Tile> {
|
||||
let space = space.into();
|
||||
let (w, h) = (p.width as usize, p.height as usize);
|
||||
let texels = match p.surface.format().sample {
|
||||
// A large pattern is held at its own depth (`Pattern::working_bytes`).
|
||||
SampleType::U8 if compact => Texels::Rgba8(quantized_rgba(p, mode, |v| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8)?),
|
||||
SampleType::U16 if compact => Texels::Rgba16(quantized_rgba(p, mode, |v| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16)?),
|
||||
SampleType::U8 if compact => Texels::Rgba8(quantized_rgba(p, space, |v| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8)?),
|
||||
SampleType::U16 if compact => Texels::Rgba16(quantized_rgba(p, space, |v| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16)?),
|
||||
_ => {
|
||||
let mut px = pattern_rgba(p, mode);
|
||||
let mut px = pattern_rgba(p, space);
|
||||
if px.len() as u64 != p.pixel_count() {
|
||||
return None;
|
||||
}
|
||||
@@ -469,6 +590,10 @@ pub(crate) fn render_into(tile: &Tile, place: &Placement, rect: Rect, out: &mut
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "pattern_grayscale_tests.rs"]
|
||||
mod grayscale_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
//! #14975: in a Grayscale document a colour pattern paints the greys of the document's grey
|
||||
//! profile, as measured in the reference application (blue 69, green 221, red 129 of 255), not the
|
||||
//! darker luma-formula greys (29 / 150 / 76). RGB, Lab, 16-bit and 32-bit documents keep the
|
||||
//! pattern's own colours. What the issue did not measure keeps the luma greys: 32-bit Grayscale,
|
||||
//! Duotone and Bitmap documents, and a Grayscale document in another grey working space.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use photocraft_color::{Color, ColorMode, PixelFormat, SampleType};
|
||||
use photocraft_doc::{Document, Effect, FxCommon, Layer, Pattern};
|
||||
use photocraft_geom::{Rect, Size};
|
||||
|
||||
use super::{PatternSpace, pattern_rgba};
|
||||
use crate::render;
|
||||
|
||||
/// The issue's test pattern: 20 x 20 px, quadrants red (top left), green (top right), blue
|
||||
/// (bottom left) and black (bottom right).
|
||||
fn quadrants() -> Pattern {
|
||||
let mut s = photocraft_raster::Surface::new(PixelFormat::RGBA8);
|
||||
s.fill_rect(Rect::new(0, 0, 10, 10), &[1.0, 0.0, 0.0, 1.0]);
|
||||
s.fill_rect(Rect::new(10, 0, 20, 10), &[0.0, 1.0, 0.0, 1.0]);
|
||||
s.fill_rect(Rect::new(0, 10, 10, 20), &[0.0, 0.0, 1.0, 1.0]);
|
||||
s.fill_rect(Rect::new(10, 10, 20, 20), &[0.0, 0.0, 0.0, 1.0]);
|
||||
Pattern::new("quadrants", s, 20, 20)
|
||||
}
|
||||
|
||||
/// The quadrants as a 16-bit grey pattern holding the luma formula's greys (0.299 R + 0.587 G +
|
||||
/// 0.114 B): no document converts a grey pattern, so it paints what the quadrants painted in a
|
||||
/// Grayscale document before #14975.
|
||||
fn luma_quadrants() -> Pattern {
|
||||
let mut s = photocraft_raster::Surface::new(PixelFormat::new(ColorMode::Grayscale, SampleType::U16, true));
|
||||
s.fill_rect(Rect::new(0, 0, 10, 10), &[0.299, 1.0]);
|
||||
s.fill_rect(Rect::new(10, 0, 20, 10), &[0.587, 1.0]);
|
||||
s.fill_rect(Rect::new(0, 10, 10, 20), &[0.114, 1.0]);
|
||||
s.fill_rect(Rect::new(10, 10, 20, 20), &[0.0, 1.0]);
|
||||
Pattern::new("quadrants", s, 20, 20)
|
||||
}
|
||||
|
||||
/// The measured greys (of 255) of the red, green and blue cells.
|
||||
const MEASURED: [(&str, (i32, i32), f32); 3] = [("red", (5, 5), 129.0), ("green", (15, 5), 221.0), ("blue", (5, 15), 69.0)];
|
||||
|
||||
/// The luma formula's greys (of 255) of the same cells: what they painted before #14975.
|
||||
const LUMA: [(&str, (i32, i32), f32); 3] = [("red", (5, 5), 76.245), ("green", (15, 5), 149.685), ("blue", (5, 15), 29.07)];
|
||||
|
||||
/// A 20 x 20 document of `mode` and `depth` with a white Background and a layer covering it that
|
||||
/// carries `pat` as a Normal 100 % Pattern Overlay.
|
||||
fn overlay_doc_of(pat: Pattern, mode: ColorMode, depth: SampleType) -> Document {
|
||||
let mut d = Document::with_background("t", Size::new(20, 20), mode, depth, Color::WHITE);
|
||||
let fmt = d.pixel_format();
|
||||
let mut l = Layer::raster("overlay", fmt);
|
||||
// An opaque mid grey, encoded in the document's own channels.
|
||||
l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 20, 20), &photocraft_raster::from_rgba(&fmt, [0.5, 0.5, 0.5, 1.0]));
|
||||
l.effects.enabled = true;
|
||||
l.effects.items.push(Effect::PatternOverlay {
|
||||
common: FxCommon::new(photocraft_color::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.patterns.push(pat);
|
||||
d.layers.push(l);
|
||||
d
|
||||
}
|
||||
|
||||
/// [`overlay_doc_of`] the issue's quadrants.
|
||||
fn overlay_doc(mode: ColorMode, depth: SampleType) -> Document {
|
||||
overlay_doc_of(quadrants(), mode, depth)
|
||||
}
|
||||
|
||||
fn at(d: &Document, (x, y): (i32, i32)) -> [f32; 4] {
|
||||
render(d, Rect::from_xywh(x, y, 1, 1)).px[0]
|
||||
}
|
||||
|
||||
/// The ICC bytes of a built-in profile, as a document embeds them.
|
||||
fn icc(profile: craft_cms::Builtin) -> Option<Arc<Vec<u8>>> {
|
||||
Some(profile.profile().to_bytes())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_colour_pattern_converts_to_the_grey_profiles_greys() {
|
||||
let px = pattern_rgba(&quadrants(), PatternSpace::ProfileGray);
|
||||
let mut wrong = Vec::new();
|
||||
for (cell, (x, y), want) in MEASURED {
|
||||
let got = px[(y * 20 + x) as usize];
|
||||
if (got[0] * 255.0 - want).abs() > 2.0 || got[0] != got[1] || got[1] != got[2] || got[3] != 1.0 {
|
||||
wrong.push(format!("{cell}: {:?} (grey {:.1}), want {want}", got, got[0] * 255.0));
|
||||
}
|
||||
}
|
||||
// Black stays black.
|
||||
let black = px[15 * 20 + 15];
|
||||
if black[0] * 255.0 > 0.5 {
|
||||
wrong.push(format!("black: {black:?}"));
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
/// A caller that names the Grayscale colour mode, not a document, keeps the pixel format's grey:
|
||||
/// Image › Mode › Bitmap ranks a Custom Pattern's thresholds by it.
|
||||
#[test]
|
||||
fn a_named_colour_mode_keeps_its_pixel_format_conversion() {
|
||||
let px = pattern_rgba(&quadrants(), ColorMode::Grayscale);
|
||||
for (cell, (x, y), want) in LUMA {
|
||||
let got = px[(y * 20 + x) as usize];
|
||||
assert!((got[0] * 255.0 - want).abs() < 0.01 && got[0] == got[1] && got[1] == got[2], "{cell}: {got:?} (grey {:.2}), want {want}", got[0] * 255.0);
|
||||
}
|
||||
assert_eq!(PatternSpace::from(ColorMode::Grayscale), PatternSpace::Mode(ColorMode::Grayscale));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pattern_overlay_in_a_grayscale_document_paints_the_measured_greys() {
|
||||
// A document created in Grayscale, and one whose mode was set to Grayscale (the state Image ›
|
||||
// Mode › Grayscale leaves): the overlay is drawn from the same conversion. Untagged, and
|
||||
// tagged with the default grey profile, as Assign Profile leaves it.
|
||||
let mut wrong = Vec::new();
|
||||
for depth in [SampleType::U8, SampleType::U16] {
|
||||
for tagged in [false, true] {
|
||||
let mut d = overlay_doc(ColorMode::Grayscale, depth);
|
||||
if tagged {
|
||||
d.icc_profile = icc(craft_cms::Builtin::DotGain20Compat);
|
||||
}
|
||||
assert_eq!(PatternSpace::of(&d), PatternSpace::ProfileGray, "{depth:?} tagged {tagged}");
|
||||
for (cell, xy, want) in MEASURED {
|
||||
let got = at(&d, xy);
|
||||
if (got[0] * 255.0 - want).abs() > 2.0 {
|
||||
wrong.push(format!("{depth:?} tagged {tagged} {cell}: grey {:.1}, want {want}", got[0] * 255.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
/// The cases #14975 lists as not measured paint what they painted before: the luma formula's
|
||||
/// greys, which a grey pattern holding them paints in the same document.
|
||||
#[test]
|
||||
fn unmeasured_grayscale_documents_keep_the_luma_greys() {
|
||||
let gamma22 = |depth| {
|
||||
let mut d = overlay_doc(ColorMode::Grayscale, depth);
|
||||
d.icc_profile = icc(craft_cms::Builtin::GrayGamma22);
|
||||
d
|
||||
};
|
||||
let cases = [
|
||||
("32-bit Grayscale", overlay_doc(ColorMode::Grayscale, SampleType::F32)),
|
||||
("Duotone", overlay_doc(ColorMode::Duotone, SampleType::U8)),
|
||||
("Bitmap", overlay_doc(ColorMode::Bitmap, SampleType::U8)),
|
||||
("Grayscale tagged Gray Gamma 2.2", gamma22(SampleType::U8)),
|
||||
("16-bit Grayscale tagged Gray Gamma 2.2", gamma22(SampleType::U16)),
|
||||
];
|
||||
let mut wrong = Vec::new();
|
||||
for (what, d) in cases {
|
||||
// The compositor's conversion, and the one Edit › Fill builds its tile in.
|
||||
let spaces = (PatternSpace::of(&d), PatternSpace::of_pixels(&d));
|
||||
if spaces != (PatternSpace::Mode(ColorMode::Grayscale), PatternSpace::Mode(ColorMode::Rgb)) {
|
||||
wrong.push(format!("{what}: {spaces:?}"));
|
||||
}
|
||||
let mut luma = overlay_doc_of(luma_quadrants(), d.mode, d.depth);
|
||||
luma.icc_profile = d.icc_profile.clone();
|
||||
for (cell, xy, level) in LUMA {
|
||||
let (got, want) = (at(&d, xy), at(&luma, xy));
|
||||
if got.iter().zip(want).any(|(g, w)| (g - w).abs() > 1e-4) {
|
||||
wrong.push(format!("{what} {cell}: {got:?}, the luma grey paints {want:?}"));
|
||||
}
|
||||
// In the 8- and 16-bit Grayscale documents that is the luma level itself.
|
||||
if d.mode == ColorMode::Grayscale && d.depth != SampleType::F32 && (got[0] * 255.0 - level).abs() > 1.0 {
|
||||
wrong.push(format!("{what} {cell}: grey {:.1}, want {level:.1}", got[0] * 255.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
/// The default grey working space is the document's own profile: untagged, or tagged with bytes
|
||||
/// that are no grey profile (the document's profile is then the default grey one).
|
||||
#[test]
|
||||
fn the_grey_working_space_is_read_from_the_documents_profile() {
|
||||
let gray = |profile: Option<Arc<Vec<u8>>>| {
|
||||
let mut d = Document::new("t", Size::new(4, 4), ColorMode::Grayscale, SampleType::U8);
|
||||
d.icc_profile = profile;
|
||||
PatternSpace::of(&d)
|
||||
};
|
||||
assert_eq!(gray(None), PatternSpace::ProfileGray);
|
||||
assert_eq!(gray(icc(craft_cms::Builtin::DotGain20Compat)), PatternSpace::ProfileGray);
|
||||
assert_eq!(gray(icc(craft_cms::Builtin::Srgb)), PatternSpace::ProfileGray, "an RGB profile is not the document's");
|
||||
assert_eq!(gray(Some(Arc::new(b"not a profile".to_vec()))), PatternSpace::ProfileGray, "unreadable bytes are not the document's profile");
|
||||
for other in [craft_cms::Builtin::GrayGamma22, craft_cms::Builtin::SGray] {
|
||||
assert_eq!(gray(icc(other)), PatternSpace::Mode(ColorMode::Grayscale), "{other:?}");
|
||||
}
|
||||
// The same allocation asked twice (the answer is cached by allocation).
|
||||
let tagged = icc(craft_cms::Builtin::GrayGamma22);
|
||||
assert_eq!((gray(tagged.clone()), gray(tagged)), (PatternSpace::Mode(ColorMode::Grayscale), PatternSpace::Mode(ColorMode::Grayscale)));
|
||||
// Other colour modes are themselves, and written pixels keep the pattern's own colours.
|
||||
for mode in [ColorMode::Rgb, ColorMode::Cmyk, ColorMode::Lab] {
|
||||
let d = Document::new("t", Size::new(4, 4), mode, SampleType::U8);
|
||||
assert_eq!((PatternSpace::of(&d), PatternSpace::of_pixels(&d)), (PatternSpace::Mode(mode), PatternSpace::Mode(ColorMode::Rgb)), "{mode:?}");
|
||||
}
|
||||
let d = Document::new("t", Size::new(4, 4), ColorMode::Grayscale, SampleType::U16);
|
||||
assert_eq!(PatternSpace::of_pixels(&d), PatternSpace::ProfileGray);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rgb_lab_16_and_32_bit_documents_keep_the_patterns_colours() {
|
||||
let cells = [((5, 5), [1.0, 0.0, 0.0]), ((15, 5), [0.0, 1.0, 0.0]), ((5, 15), [0.0, 0.0, 1.0]), ((15, 15), [0.0, 0.0, 0.0])];
|
||||
for mode in [ColorMode::Rgb, ColorMode::Lab] {
|
||||
assert_eq!(pattern_rgba(&quadrants(), mode), pattern_rgba(&quadrants(), ColorMode::Rgb), "{mode:?}: the pattern's own colours");
|
||||
}
|
||||
for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
|
||||
let d = overlay_doc(ColorMode::Rgb, depth);
|
||||
for (xy, rgb) in cells {
|
||||
let got = at(&d, xy);
|
||||
assert!(got.iter().zip(rgb).all(|(g, w)| (g - w).abs() < 0.01), "RGB {depth:?} at {xy:?}: {got:?}, want {rgb:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -238,7 +238,7 @@ pub(crate) fn render_reduced_cells(
|
||||
// composited once per colour and summed per run of source columns, not per pixel
|
||||
// (#4017). Tiles lie on the document's tile grid whatever `damage` is, so a damage
|
||||
// render sums exactly what the whole reduction does.
|
||||
let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode);
|
||||
let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_doc(doc);
|
||||
let cx = Ctx::for_doc(doc, &patterns);
|
||||
let t = RENDER_TILE as usize;
|
||||
// The document tile grid (the surfaces' own), in `b`-relative coordinates: the start of
|
||||
|
||||
@@ -35,7 +35,7 @@ pub const MAX_RENDER_PIXELS: u64 = 1 << 30;
|
||||
|
||||
/// [`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).in_mode(doc.pixel_format().mode);
|
||||
let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_doc(doc);
|
||||
let cx = Ctx::for_doc(doc, &patterns);
|
||||
render_tiled_with(doc, rect, tile, &cx)
|
||||
}
|
||||
@@ -221,7 +221,7 @@ fn render_bands_with_alloc<A: BufferAlloc + Sync, E>(
|
||||
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).in_mode(doc.pixel_format().mode);
|
||||
let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_doc(doc);
|
||||
let cx = Ctx::for_doc(doc, &patterns);
|
||||
let rows = band_rows_for(rect.width(), band_rows);
|
||||
let mut y = rect.y0;
|
||||
@@ -399,7 +399,7 @@ pub fn render_layer_in(doc: &Document, layer: &Layer, rect: Rect) -> Buffer {
|
||||
if u64::from(rect.width()) * u64::from(rect.height()) > MAX_RENDER_PIXELS {
|
||||
return Buffer::transparent(Rect::EMPTY);
|
||||
}
|
||||
let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode);
|
||||
let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_doc(doc);
|
||||
// A lone layer: a deep knockout reveals transparency, not the document's Background.
|
||||
let cx = Ctx { doc: None, ..Ctx::for_doc(doc, &patterns) };
|
||||
let lab = doc.mode == photocraft_color::ColorMode::Lab;
|
||||
@@ -506,7 +506,7 @@ mod fallible_bands_tests {
|
||||
fn fail_nth_buffer_constructor_propagates_through_nested_rendering() {
|
||||
let doc = nested_document();
|
||||
let rect = doc.bounds();
|
||||
let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode);
|
||||
let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_doc(&doc);
|
||||
let ctx = Ctx::for_doc(&doc, &patterns);
|
||||
let count = {
|
||||
let mut backdrop = Buffer::filled(rect, [0.0; 4]);
|
||||
@@ -556,7 +556,7 @@ mod fallible_bands_tests {
|
||||
let mut layer = Layer::group("styled group", vec![fill]);
|
||||
layer.effects.items.push(photocraft_doc::Effect::default_drop_shadow());
|
||||
doc.layers.push(layer);
|
||||
let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode);
|
||||
let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_doc(&doc);
|
||||
let cx = Ctx::for_doc(&doc, &patterns);
|
||||
|
||||
for _ in 0..2 {
|
||||
|
||||
@@ -248,7 +248,7 @@ fn pixel_layer_rows_match_tile_copy() {
|
||||
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 patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_doc(&doc);
|
||||
let cx = Ctx::for_doc(&doc, &patterns);
|
||||
let layer = &doc.layers[1];
|
||||
let backdrop = Buffer {
|
||||
|
||||
@@ -104,7 +104,11 @@ pub fn fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
"pattern" => {
|
||||
let pat = crate::pattern_cmds::resolve_param(s, CMD, p)?;
|
||||
let (scale, angle, _, phase) = crate::pattern_cmds::placement(CMD, p)?;
|
||||
let tile = photocraft_compose::pattern::Tile::new(&pat).ok_or_else(|| bad("the pattern is empty or too large to paint"))?;
|
||||
// Where a pattern fill layer and a Pattern Overlay paint the pattern through the grey
|
||||
// profile (an 8- or 16-bit Grayscale document in the default grey space), so does
|
||||
// Edit › Fill (#14975).
|
||||
let space = photocraft_compose::pattern::PatternSpace::of_pixels(&st.doc);
|
||||
let tile = photocraft_compose::pattern::Tile::new_in(&pat, space).ok_or_else(|| bad("the pattern is empty or too large to paint"))?;
|
||||
// Photoshop's Fill uses the canvas origin.
|
||||
let place = photocraft_compose::pattern::Placement::new(Rect::EMPTY, false, phase, scale, angle);
|
||||
out["pattern"] = json!(pat.id);
|
||||
|
||||
@@ -83,7 +83,10 @@ fn bucket(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let source = p.get("contents").or_else(|| p.get("source")).and_then(Value::as_str).unwrap_or("foreground");
|
||||
let pattern = if source == "pattern" {
|
||||
let pat = crate::pattern_cmds::resolve_param(s, "paint.bucket", p)?;
|
||||
let tile = photocraft_compose::pattern::Tile::new(&pat)
|
||||
// Through the grey profile where Edit › Fill and a pattern fill layer paint so (#14975).
|
||||
use photocraft_compose::pattern::PatternSpace;
|
||||
let space = s.active().map_or(PatternSpace::Mode(photocraft_color::ColorMode::Rgb), |d| PatternSpace::of_pixels(&d.doc));
|
||||
let tile = photocraft_compose::pattern::Tile::new_in(&pat, space)
|
||||
.ok_or_else(|| EngineError::BadParams { cmd: "paint.bucket".into(), msg: "the pattern is empty or too large to paint".into() })?;
|
||||
let (scale, angle, _, phase) = crate::pattern_cmds::placement("paint.bucket", p)?;
|
||||
Some((tile, scale, angle, phase))
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Tests that run paint commands, moved from the engine-core `pattern_mode` tests: 2 test(s).
|
||||
//! Tests that run paint commands, moved from the engine-core `pattern_mode` tests: 2 test(s). The
|
||||
//! tests of a pattern's greys in Grayscale documents (#14975) follow them.
|
||||
|
||||
use photocraft_engine::Session;
|
||||
|
||||
@@ -91,3 +92,137 @@ fn a_grayscale_round_trip_keeps_the_pattern_colours() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #14975: the issue's 20 x 20 test pattern (red, green, blue and black quadrants), defined from an
|
||||
/// RGB document; returns its id.
|
||||
fn quadrant_pattern(s: &mut Session) -> String {
|
||||
s.execute("file.new", json!({"width": 20, "height": 20, "mode": "rgb", "depth": 8, "background": "white"})).unwrap();
|
||||
for (x, y, c) in [(0, 0, "#ff0000"), (10, 0, "#00ff00"), (0, 10, "#0000ff"), (10, 10, "#000000")] {
|
||||
s.execute("select.rect", json!({"x": x, "y": y, "width": 10, "height": 10})).unwrap();
|
||||
s.execute("edit.fill", json!({"contents": "color", "color": c})).unwrap();
|
||||
}
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
let r = s.execute("edit.definePattern", json!({"name": "Quadrants"})).unwrap();
|
||||
r["pattern"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
/// The greys (of 255) the reference application paints for the red, green and blue cells in a
|
||||
/// Grayscale document (#14975), where each cell sits on a 20 x 20 canvas-origin tiling.
|
||||
const QUADRANT_GREYS: [(&str, (i32, i32), f32); 3] = [("red", (5, 5), 129.0), ("green", (15, 5), 221.0), ("blue", (5, 15), 69.0)];
|
||||
|
||||
/// The cells that are off by more than 2 levels, or not neutral.
|
||||
fn wrong_greys(s: &mut Session, what: &str) -> Vec<String> {
|
||||
let mut wrong = Vec::new();
|
||||
for (cell, (x, y), want) in QUADRANT_GREYS {
|
||||
let p = pixel(s, x, y);
|
||||
if !neutral(p) || (p[0] * 255.0 - want).abs() > 2.0 {
|
||||
wrong.push(format!("{what} {cell}: {p:?} (grey {:.1}), want {want}", p[0] * 255.0));
|
||||
}
|
||||
}
|
||||
wrong
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_fill_and_the_paint_bucket_paint_a_pattern_through_the_grey_profile() {
|
||||
let mut wrong = Vec::new();
|
||||
for depth in [8, 16] {
|
||||
let mut s = Session::new();
|
||||
let pat = quadrant_pattern(&mut s);
|
||||
// Edit › Fill with the pattern on a new layer.
|
||||
s.execute("file.new", json!({"width": 40, "height": 40, "mode": "gray", "depth": depth, "background": "white"})).unwrap();
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
s.execute("edit.fill", json!({"contents": "pattern", "pattern": pat})).unwrap();
|
||||
wrong.extend(wrong_greys(&mut s, &format!("Edit › Fill {depth}-bit")));
|
||||
// The Paint Bucket in pattern mode on the white Background.
|
||||
s.execute("file.new", json!({"width": 40, "height": 40, "mode": "gray", "depth": depth, "background": "white"})).unwrap();
|
||||
s.execute("paint.bucket", json!({"x": 30, "y": 30, "contents": "pattern", "pattern": pat, "tolerance": 0, "antiAlias": false})).unwrap();
|
||||
wrong.extend(wrong_greys(&mut s, &format!("Paint Bucket {depth}-bit")));
|
||||
// A pattern fill layer paints the same greys.
|
||||
s.execute("file.new", json!({"width": 40, "height": 40, "mode": "gray", "depth": depth, "background": "white"})).unwrap();
|
||||
s.execute("layer.newFillLayer.pattern", json!({"pattern": pat})).unwrap();
|
||||
wrong.extend(wrong_greys(&mut s, &format!("pattern fill layer {depth}-bit")));
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_fill_with_a_pattern_keeps_its_colours_outside_grayscale() {
|
||||
// RGB keeps the pattern's colours exactly; CMYK and Lab keep today's conversion (checked
|
||||
// against a pattern fill layer by `pattern_fills_paint_like_edit_fill_in_every_mode`).
|
||||
let mut s = Session::new();
|
||||
let pat = quadrant_pattern(&mut s);
|
||||
s.execute("file.new", json!({"width": 40, "height": 40, "mode": "rgb", "depth": 8, "background": "white"})).unwrap();
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
s.execute("edit.fill", json!({"contents": "pattern", "pattern": pat})).unwrap();
|
||||
for ((x, y), want) in [((5, 5), [1.0, 0.0, 0.0, 1.0]), ((15, 5), [0.0, 1.0, 0.0, 1.0]), ((5, 15), [0.0, 0.0, 1.0, 1.0])] {
|
||||
assert!(close(pixel(&mut s, x, y), want, 0.004), "RGB at {x},{y}: {:?}", pixel(&mut s, x, y));
|
||||
}
|
||||
}
|
||||
|
||||
/// The issue's quadrants as a grey pattern holding the luma formula's greys (76, 150 and 29 of
|
||||
/// 255), defined from a Grayscale document: no document converts a grey pattern, so it paints
|
||||
/// what the colour quadrants painted in a Grayscale document before #14975. Returns its id.
|
||||
fn luma_quadrant_pattern(s: &mut Session) -> String {
|
||||
s.execute("file.new", json!({"width": 20, "height": 20, "mode": "gray", "depth": 8, "background": "white"})).unwrap();
|
||||
for (x, y, c) in [(0, 0, "#4c4c4c"), (10, 0, "#969696"), (0, 10, "#1d1d1d"), (10, 10, "#000000")] {
|
||||
s.execute("select.rect", json!({"x": x, "y": y, "width": 10, "height": 10})).unwrap();
|
||||
s.execute("edit.fill", json!({"contents": "color", "color": c})).unwrap();
|
||||
}
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
let r = s.execute("edit.definePattern", json!({"name": "Luma Quadrants"})).unwrap();
|
||||
r["pattern"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
/// What #14975 lists as not measured keeps the luma greys in every pattern fill: a 32-bit
|
||||
/// Grayscale document, and a Grayscale document in another grey working space. Edit › Fill, the
|
||||
/// Paint Bucket and a pattern fill layer paint the colour quadrants as they paint the grey pattern
|
||||
/// that holds the luma greys.
|
||||
#[test]
|
||||
fn unmeasured_grayscale_documents_keep_the_luma_greys_in_every_pattern_fill() {
|
||||
let mut wrong = Vec::new();
|
||||
for (what, depth, profile) in
|
||||
[("32-bit", 32, None), ("Gray Gamma 2.2, 8-bit", 8, Some("gray-gamma-2.2")), ("Gray Gamma 2.2, 16-bit", 16, Some("gray-gamma-2.2"))]
|
||||
{
|
||||
let mut s = Session::new();
|
||||
let colour = quadrant_pattern(&mut s);
|
||||
let luma = luma_quadrant_pattern(&mut s);
|
||||
let new_doc = |s: &mut Session| {
|
||||
s.execute("file.new", json!({"width": 40, "height": 40, "mode": "gray", "depth": depth, "background": "white"})).unwrap();
|
||||
if let Some(profile) = profile {
|
||||
s.execute("edit.assignProfile", json!({"profile": profile})).unwrap();
|
||||
}
|
||||
};
|
||||
let cells = |s: &mut Session| QUADRANT_GREYS.map(|(_, (x, y), _)| pixel(s, x, y));
|
||||
let fill = |s: &mut Session, pat: &str| {
|
||||
new_doc(s);
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
s.execute("edit.fill", json!({"contents": "pattern", "pattern": pat})).unwrap();
|
||||
cells(s)
|
||||
};
|
||||
let bucket = |s: &mut Session, pat: &str| {
|
||||
new_doc(s);
|
||||
s.execute("paint.bucket", json!({"x": 30, "y": 30, "contents": "pattern", "pattern": pat, "tolerance": 0, "antiAlias": false})).unwrap();
|
||||
cells(s)
|
||||
};
|
||||
let fill_layer = |s: &mut Session, pat: &str, mode: ColorMode| {
|
||||
new_doc(s);
|
||||
s.execute("layer.newFillLayer.pattern", json!({"pattern": pat})).unwrap();
|
||||
assert_eq!(pattern_mode(s), mode, "{what}: the pattern's own colour mode");
|
||||
cells(s)
|
||||
};
|
||||
let painted = [
|
||||
("Edit › Fill", fill(&mut s, &colour), fill(&mut s, &luma)),
|
||||
("Paint Bucket", bucket(&mut s, &colour), bucket(&mut s, &luma)),
|
||||
("pattern fill layer", fill_layer(&mut s, &colour, ColorMode::Rgb), fill_layer(&mut s, &luma, ColorMode::Grayscale)),
|
||||
];
|
||||
for (by, got, want) in painted {
|
||||
for (((cell, _, _), got), want) in QUADRANT_GREYS.iter().zip(got).zip(want) {
|
||||
// Half a level: the grey pattern holds the luma greys rounded to 8 bits.
|
||||
if !neutral(got) || !close(got, want, 0.5 / 255.0) {
|
||||
wrong.push(format!("{what} {by} {cell}: {got:?}, the luma grey paints {want:?}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
@@ -12,12 +12,12 @@ const PATTERN_UPLOAD_BAND_BYTES: u64 = 4 << 20;
|
||||
|
||||
fn pattern_upload_bands(
|
||||
pat: &Pattern,
|
||||
mode: photocraft_color::ColorMode,
|
||||
space: impl Into<photocraft_compose::pattern::PatternSpace>,
|
||||
max_band_bytes: u64,
|
||||
mut upload: impl FnMut(u32, u32, &[u8]),
|
||||
) -> Result<(), Unsupported> {
|
||||
let mut bytes = Vec::new();
|
||||
photocraft_compose::pattern::pattern_rgba_bands(pat, mode, max_band_bytes, |top, pixels| {
|
||||
photocraft_compose::pattern::pattern_rgba_bands(pat, space, max_band_bytes, |top, pixels| {
|
||||
let len = pixels.len().checked_mul(16)?;
|
||||
bytes.clear();
|
||||
bytes.try_reserve_exact(len).ok()?;
|
||||
@@ -492,14 +492,14 @@ impl Compositor {
|
||||
Some((key, [region.x0, region.y0, region.width() as i32, region.height() as i32]))
|
||||
}
|
||||
|
||||
/// Premultiplied RGBA32F texture of a pattern as it paints in the document's mode (cached by
|
||||
/// pixel identity and mode).
|
||||
/// Premultiplied RGBA32F texture of a pattern as it paints in the document (cached by
|
||||
/// pixel identity and the document's pattern space).
|
||||
pub(crate) fn pattern_view(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, pat: &Pattern) -> Result<wgpu::TextureView, Unsupported> {
|
||||
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 mode = self.pattern_mode;
|
||||
let key = format!("{}\u{0}{}\u{0}{mode:?}", pat.id, pat.name);
|
||||
let space = self.pattern_space;
|
||||
let key = format!("{}\u{0}{}\u{0}{space:?}", pat.id, pat.name);
|
||||
let format = pat.surface.format();
|
||||
// Unstored tiles read the default pixel, interpreted in the source format.
|
||||
let default_bits: Vec<u32> = pat.surface.default_pixel().iter().map(|v| v.to_bits()).collect();
|
||||
@@ -515,7 +515,7 @@ impl Compositor {
|
||||
}
|
||||
let (w, h) = (pat.width, pat.height);
|
||||
let t = Tex::new(device, "pc_pattern", w, h, wgpu::TextureFormat::Rgba32Float, wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST);
|
||||
pattern_upload_bands(pat, mode, PATTERN_UPLOAD_BAND_BYTES, |top, rows, bytes| {
|
||||
pattern_upload_bands(pat, space, PATTERN_UPLOAD_BAND_BYTES, |top, rows, bytes| {
|
||||
write_pattern_band(queue, &t.texture, w, top, rows, bytes);
|
||||
})?;
|
||||
let v = t.view.clone();
|
||||
|
||||
@@ -134,7 +134,7 @@ impl Compositor {
|
||||
let region = region.intersect(&canvas);
|
||||
let plan = plan(doc)?;
|
||||
self.check_fx(doc, &plan)?;
|
||||
self.pattern_mode = doc.pixel_format().mode;
|
||||
self.pattern_space = photocraft_compose::pattern::PatternSpace::of(doc);
|
||||
self.pattern_doc = doc.id;
|
||||
let mut stats = Stats { passes: plan.passes.len(), slots: plan.slots, ..Default::default() };
|
||||
if region.is_empty() {
|
||||
|
||||
@@ -76,9 +76,9 @@ pub struct Compositor {
|
||||
/// Effect temporaries (R32F, region sized) and the frame they were last used.
|
||||
temps: Vec<(Tex, u64)>,
|
||||
patterns: HashMap<String, CachedPattern>,
|
||||
/// The colour mode of the document being encoded: patterns paint in it
|
||||
/// How the document being encoded takes its patterns' colours: they paint in it
|
||||
/// (`photocraft_compose::pattern::pattern_rgba`).
|
||||
pattern_mode: photocraft_color::ColorMode,
|
||||
pattern_space: photocraft_compose::pattern::PatternSpace,
|
||||
/// The document being encoded, which owns the patterns it paints with.
|
||||
pattern_doc: DocId,
|
||||
/// GPU memory pattern textures may hold ([`PATTERN_BUDGET`] by default).
|
||||
|
||||
@@ -148,7 +148,7 @@ impl Compositor {
|
||||
prefix: prefix::Prefix::default(),
|
||||
temps: Vec::new(),
|
||||
patterns: HashMap::new(),
|
||||
pattern_mode: photocraft_color::ColorMode::Rgb,
|
||||
pattern_space: photocraft_compose::pattern::PatternSpace::Mode(photocraft_color::ColorMode::Rgb),
|
||||
pattern_doc: DocId(0),
|
||||
pattern_budget: PATTERN_BUDGET,
|
||||
max_dim: 0,
|
||||
|
||||
@@ -134,6 +134,9 @@ struct Ex<'c> {
|
||||
smart: SmartOut,
|
||||
/// The document's patterns, which Pattern Fill layers are rendered from.
|
||||
patterns: Vec<photocraft_doc::Pattern>,
|
||||
/// How the stored pixels of a Pattern Fill layer take the pattern's colours: as the document
|
||||
/// paints them (the grey profile's greys in a Grayscale document, #14975).
|
||||
pattern_space: photocraft_compose::pattern::PatternSpace,
|
||||
/// The layer written as Photoshop's Background (see [`psd_background`]).
|
||||
background: Option<photocraft_doc::LayerId>,
|
||||
/// Where encoded channels go instead of memory ([`PsdExportOptions::stage_on_scratch_from`]).
|
||||
@@ -1048,7 +1051,7 @@ impl Ex<'_> {
|
||||
// In the frame the layer's masks give it, like the compositor (masks are stored apart).
|
||||
// Readers composite these pixels (ours keeps them as the fill's rendering), so a pattern
|
||||
// fill must be rendered from the document's patterns, not left transparent (#1907).
|
||||
let buf = photocraft_compose::render_fill_content(l, f, self.canvas, &self.patterns);
|
||||
let buf = photocraft_compose::render_fill_content_in(l, f, self.canvas, &self.patterns, self.pattern_space);
|
||||
let mut s = Surface::new(self.fmt);
|
||||
let vals: Vec<f32> = buf.px.iter().flat_map(|p| photocraft_raster::from_rgba(&self.fmt, *p)).collect();
|
||||
s.write_region(self.canvas, &vals);
|
||||
|
||||
@@ -116,6 +116,7 @@ fn export_supported_document(
|
||||
comps: (!crate::comps_map::comps_unchanged(doc)).then(|| (doc.layer_comps.clone(), doc.last_document_state.clone())),
|
||||
smart: SmartOut::new(doc, depth),
|
||||
patterns: doc.patterns.clone(),
|
||||
pattern_space: photocraft_compose::pattern::PatternSpace::of_pixels(doc),
|
||||
background: psd_background(doc),
|
||||
stage: {
|
||||
let raw = doc.size.area().saturating_mul(fmt.bytes_per_pixel() as u64).saturating_mul(doc.walk().len() as u64 + 1);
|
||||
|
||||
Reference in new issue
Block a user