Skip to content

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

CMYK compositing: layer effects and knockouts ink by ink

SBaksa6ded412767d8
diff --git a/crates/compose/src/cmyk.rs b/crates/compose/src/cmyk.rs
index 1f7c9575d..1e0f6c844 100644
--- a/crates/compose/src/cmyk.rs
+++ b/crates/compose/src/cmyk.rs
@@ -26,6 +26,9 @@ use photocraft_geom::Rect;
use super::{Ctx, RENDER_TILE, advanced, empty_in, mask_vals, pattern};
+#[path = "cmyk_split.rs"]
+pub mod split;
+
/// One straight-alpha CMYK pixel: C, M, Y, K (0..1 ink), alpha.
pub type Cmyka = [f32; 5];
@@ -550,30 +553,85 @@ fn render_tile(doc: &Document, rect: Rect, cx: &Ctx) -> CmykBuffer {
b
}
-/// The composite of `doc` over `rect` in CMYK + alpha, mixed on ink values; `None` when
-/// [`supports`] is false. Tiles render in parallel on native targets (one at a time on wasm);
+/// Whether [`render_cmyk`] composites `doc` on ink values: on this module's exact path
+/// ([`supports`]) or, for layer effects and knockouts, ink by ink through the RGB compositor
+/// ([`split::supports`]).
+pub fn renders_inks(doc: &Document) -> bool {
+ supports(doc) || split::supports(doc)
+}
+
+/// The composite of `doc` over `rect` in CMYK + alpha, mixed on ink values; `None` unless
+/// [`renders_inks`]. Tiles render in parallel on native targets (one at a time on wasm);
/// every tile is independent, so the result doesn't depend on the tiling or the thread count.
pub fn render_cmyk(doc: &Document, rect: Rect) -> Option<CmykBuffer> {
render_cmyk_tiled(doc, rect, RENDER_TILE)
}
+/// [`render_cmyk`] as display RGB (straight alpha), each pixel's inks shown through the
+/// document's CMYK profile as the RGB compositor reads CMYK pixels; `None` unless
+/// [`renders_inks`]. What a canvas showing the ink composite would draw.
+pub fn render_display(doc: &Document, rect: Rect) -> Option<super::Buffer> {
+ let inks = render_cmyk(doc, rect)?;
+ let space = super::cmyk_space(doc);
+ let show = |part: &[Cmyka]| -> Vec<[f32; 4]> {
+ photocraft_color::convert::with_cmyk_space(space.as_ref(), || {
+ part.iter()
+ .map(|p| {
+ let [r, g, b] = photocraft_color::convert::cmyk_to_rgb([p[0], p[1], p[2], p[3]]);
+ [r, g, b, p[4]]
+ })
+ .collect()
+ })
+ };
+ // Rows of tiles at a time, on every core (the profile is set per worker thread).
+ let chunk = (rect.width() as usize).max(1) * RENDER_TILE as usize;
+ #[cfg(not(target_arch = "wasm32"))]
+ let px: Vec<[f32; 4]> = {
+ use rayon::prelude::*;
+ inks.px.par_chunks(chunk).flat_map_iter(show).collect()
+ };
+ #[cfg(target_arch = "wasm32")]
+ let px: Vec<[f32; 4]> = inks.px.chunks(chunk).flat_map(show).collect();
+ Some(super::Buffer { rect, px })
+}
+
/// [`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) {
+ if supports(doc) {
+ let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode);
+ let cx = Ctx::for_doc(doc, &patterns);
+ return Some(render_with(rect, tile, |t| render_tile(doc, t, &cx)));
+ }
+ if !split::supports(doc) {
return None;
}
- let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode);
- let cx = Ctx::for_doc(doc, &patterns);
- Some(render_with(doc, rect, tile, &cx))
+ let mut out = CmykBuffer::transparent(rect);
+ let done = split::render_bands(doc, rect, 0, tile, |band| {
+ place(&mut out, &band);
+ Ok::<(), ()>(())
+ });
+ done.ok().map(|()| out)
+}
+
+/// Copies `part` into `out` where their rectangles overlap (`part` lies within `out`).
+fn place(out: &mut CmykBuffer, part: &CmykBuffer) {
+ let (rect, w) = (out.rect, out.rect.width() as usize);
+ let pw = part.rect.width() as usize;
+ for (row, src) in part.px.chunks_exact(pw.max(1)).enumerate() {
+ let o = ((part.rect.y0 - rect.y0) as usize + row) * w + (part.rect.x0 - rect.x0) as usize;
+ if let Some(dst) = out.px.get_mut(o..o + pw) {
+ dst.copy_from_slice(src);
+ }
+ }
}
-fn render_with(doc: &Document, rect: Rect, tile: i32, cx: &Ctx) -> CmykBuffer {
+/// `rect` rendered tile by tile by `render_tile`, tiles in parallel on native targets.
+fn render_with(rect: Rect, tile: i32, render_tile: impl Fn(Rect) -> CmykBuffer + Sync) -> CmykBuffer {
let tile = tile.max(1);
let mut out = CmykBuffer::transparent(rect);
if rect.is_empty() {
return out;
}
- let w = rect.width() as usize;
let mut tiles = Vec::new();
let mut y = rect.y0;
while y < rect.y1 {
@@ -589,28 +647,22 @@ fn render_with(doc: &Document, rect: Rect, tile: i32, cx: &Ctx) -> CmykBuffer {
#[cfg(not(target_arch = "wasm32"))]
let parts: Vec<CmykBuffer> = {
use rayon::prelude::*;
- tiles.par_iter().map(|t| render_tile(doc, *t, cx)).collect()
+ tiles.par_iter().map(|t| render_tile(*t)).collect()
};
#[cfg(target_arch = "wasm32")]
- let parts: Vec<CmykBuffer> = tiles.iter().map(|t| render_tile(doc, *t, cx)).collect();
+ let parts: Vec<CmykBuffer> = tiles.iter().map(|t| render_tile(*t)).collect();
for part in &parts {
- let pw = part.rect.width() as usize;
- for (row, src) in part.px.chunks_exact(pw.max(1)).enumerate() {
- let o = ((part.rect.y0 - rect.y0) as usize + row) * w + (part.rect.x0 - rect.x0) as usize;
- if let Some(dst) = out.px.get_mut(o..o + pw) {
- dst.copy_from_slice(src);
- }
- }
+ place(&mut out, part);
}
out
}
/// [`render_cmyk`] in horizontal bands, top to bottom, handing each band to `sink` (so a huge
-/// document is never held as one full-size float composite); `None` when [`supports`] is false.
+/// document is never held as one full-size float composite); `None` unless [`renders_inks`].
/// `band_rows` as in [`super::render_bands`].
pub fn render_cmyk_bands<E>(doc: &Document, rect: Rect, band_rows: i32, mut sink: impl FnMut(CmykBuffer) -> Result<(), E>) -> Option<Result<(), E>> {
if !supports(doc) {
- return None;
+ 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 cx = Ctx::for_doc(doc, &patterns);
@@ -618,7 +670,7 @@ pub fn render_cmyk_bands<E>(doc: &Document, rect: Rect, band_rows: i32, mut sink
let mut y = rect.y0;
while y < rect.y1 {
let y1 = y.saturating_add(rows).min(rect.y1);
- if let Err(e) = sink(render_with(doc, Rect::new(rect.x0, y, rect.x1, y1), RENDER_TILE, &cx)) {
+ if let Err(e) = sink(render_with(Rect::new(rect.x0, y, rect.x1, y1), RENDER_TILE, |t| render_tile(doc, t, &cx))) {
return Some(Err(e));
}
y = y1;
diff --git a/crates/compose/src/cmyk_split.rs b/crates/compose/src/cmyk_split.rs
new file mode 100644
index 000000000..89153b636
--- /dev/null
+++ b/crates/compose/src/cmyk_split.rs
@@ -0,0 +1,313 @@
+//! CMYK documents with layer effects (and stack structures the ink path leaves alone, such as
+//! knockouts), composited ink by ink through the RGB compositor itself.
+//!
+//! Everything allowed here works channel by channel: per-channel blend modes, effects built from
+//! coverage and painted with colours or colour gradients, the ink-by-ink adjustments, masks,
+//! groups, clipping and knockouts. So the RGB compositor run on a stand-in document whose red,
+//! green and blue hold the brightness (1 − ink) of cyan, magenta and yellow gives exactly those
+//! inks' result, and a second run with black's brightness in all three gives black. Blends stay
+//! clipped to 0..1 (unclipped blending would make negative ink), as on the ink path.
+//!
+//! 32-bit documents stay on the RGB compositor (32-bit CMYK isn't a print mode, and 32-bit Levels
+//! use their own float formula); so do pattern paints, bevel textures, effect blend modes that mix
+//! channels, Blend If and channel restrictions, which don't work channel by channel.
+
+use photocraft_color::blend::BlendMode;
+use photocraft_color::{Color, ColorMode, PixelFormat, SampleType};
+use photocraft_doc::adjust::ToneSpace;
+use photocraft_doc::effects::{Effect, FxPaint};
+use photocraft_doc::{Adjustment, Document, Fill, Layer, LayerContent};
+use photocraft_geom::Rect;
+use photocraft_raster::Surface;
+
+use super::{CmykBuffer, MAX_DEPTH, clean, cmyk_pixels, ink_adjustment, separable};
+use crate::{Buffer, Ctx, advanced, pattern};
+
+/// Which ink (0..=3: C, M, Y, K) a stand-in document carries in its red, green and blue.
+pub(super) type Planes = [usize; 3];
+const CMY: Planes = [0, 1, 2];
+const K: Planes = [3, 3, 3];
+
+/// Whether `doc` composites ink by ink on this path.
+pub fn supports(doc: &Document) -> bool {
+ doc.mode == ColorMode::Cmyk && doc.depth != SampleType::F32 && stack_supported(&doc.layers, 0)
+}
+
+fn stack_supported(layers: &[Layer], depth: u32) -> bool {
+ depth <= MAX_DEPTH && layers.iter().filter(|l| l.visible).all(|l| layer_supported(l, depth))
+}
+
+fn layer_supported(l: &Layer, depth: u32) -> bool {
+ let plain = l.opacity.is_finite() && l.fill_opacity.is_finite() && l.excluded_channels == 0 && l.blend_if.is_default();
+ // Effects on an adjustment layer (which has no pixels of its own to shape them) stay on the RGB
+ // compositor.
+ let effects = !crate::effects::has_effects(l)
+ || (!matches!(l.content, LayerContent::Adjustment(_)) && l.effects.items.iter().filter(|e| e.enabled()).all(effect_supported));
+ let content = match &l.content {
+ LayerContent::Group(g) => g.artboard.is_none() && (separable(l.blend) || l.blend == BlendMode::PassThrough) && stack_supported(&g.children, depth + 1),
+ LayerContent::Adjustment(a) => ink_adjustment(a) && separable(l.blend),
+ // A stroked shape can draw its stroke from the vector, in its own colour.
+ LayerContent::Shape(sh) if sh.stroke.is_some() => false,
+ _ => cmyk_pixels(l) && separable(l.blend),
+ };
+ // Effects and knockouts are laid out over the layer's bounds: they must be the same on the
+ // stand-ins (see [`stand_in_surface`]).
+ let shaped = crate::effects::has_effects(l) || l.advanced.knockout != photocraft_doc::Knockout::None;
+ plain && effects && content && (!shaped || transparent_outside(l))
+}
+
+/// Whether every surface `l` draws from has alpha and a transparent default pixel.
+fn transparent_outside(l: &Layer) -> bool {
+ match &l.content {
+ LayerContent::Group(g) => g.children.iter().all(transparent_outside),
+ _ => l.surface().is_none_or(|s| s.format().alpha && s.default_pixel().last().is_some_and(|a| *a <= 0.0)),
+ }
+}
+
+fn effect_supported(e: &Effect) -> bool {
+ let paint = |p: &FxPaint| !matches!(p, FxPaint::Pattern { .. });
+ match e {
+ Effect::DropShadow(s) | Effect::InnerShadow(s) => separable(s.common.blend),
+ Effect::OuterGlow(g) | Effect::InnerGlow(g) => separable(g.common.blend) && paint(&g.paint),
+ Effect::Stroke(s) => separable(s.common.blend) && paint(&s.paint),
+ Effect::ColorOverlay { common, .. } | Effect::GradientOverlay { common, .. } => separable(common.blend),
+ Effect::Satin(s) => separable(s.common.blend),
+ Effect::BevelEmboss(b) => separable(b.highlight.blend) && separable(b.shadow.blend) && b.texture.is_none(),
+ Effect::PatternOverlay { .. } => false,
+ }
+}
+
+/// The brightness (1 − ink) of ink `i` of a CMYK pixel or colour (0 for a missing or non-finite
+/// value: no ink).
+fn brightness(inks: &[f32], i: usize) -> f32 {
+ 1.0 - inks.get(i).copied().map_or(0.0, clean)
+}
+
+fn stand_in_color(c: &Color, planes: Planes) -> Color {
+ let ink = c.in_mode(ColorMode::Cmyk).c;
+ Color { mode: ColorMode::Rgb, c: [brightness(&ink, planes[0]), brightness(&ink, planes[1]), brightness(&ink, planes[2]), 0.0], alpha: c.alpha }
+}
+
+/// A CMYK surface as an RGB one (same depth and alpha) holding the planes' brightness.
+fn stand_in_surface(s: &Surface, planes: Planes) -> Surface {
+ let from = s.format();
+ if from.mode != ColorMode::Cmyk {
+ return s.clone();
+ }
+ let to = PixelFormat { mode: ColorMode::Rgb, sample: from.sample, alpha: from.alpha };
+ let n = from.channels().max(1);
+ let px = |p: &[f32], dst: &mut Vec<f32>| {
+ dst.extend(planes.iter().map(|&i| brightness(p, i)));
+ if from.alpha {
+ dst.push(p.get(4).copied().unwrap_or(0.0));
+ }
+ };
+ let source_default = s.default_pixel();
+ let mut default = Vec::new();
+ px(&source_default, &mut default);
+ let map = |src: &[f32], dst: &mut Vec<f32>| {
+ for p in src.chunks_exact(n) {
+ let start = dst.len();
+ px(p, dst);
+ // Layer bounds count the pixels that differ from the default, transparent ones too: a
+ // transparent pixel whose other inks differ keeps a colour of its own here (it never
+ // shows), so the stand-in's bounds are the document's.
+ if from.alpha
+ && p.get(4) == Some(&0.0)
+ && *p != *source_default
+ && dst.get(start..) == Some(&default[..])
+ && let Some(v) = dst.get_mut(start)
+ {
+ *v = if *v > 0.5 { 0.0 } else { 1.0 };
+ }
+ }
+ };
+ let mut out = Surface::with_default(to, &default);
+ let rects: Vec<Rect> = s.tiles().map(|(c, _)| c.rect()).collect();
+ let convert = |r: &Rect| {
+ let (mut src, mut dst) = (Vec::new(), Vec::new());
+ s.read_region_into(*r, &mut src);
+ map(&src, &mut dst);
+ (*r, dst)
+ };
+ #[cfg(not(target_arch = "wasm32"))]
+ let tiles: Vec<(Rect, Vec<f32>)> = {
+ use rayon::prelude::*;
+ rects.par_iter().map(convert).collect()
+ };
+ #[cfg(target_arch = "wasm32")]
+ let tiles: Vec<(Rect, Vec<f32>)> = rects.iter().map(convert).collect();
+ for (r, data) in &tiles {
+ out.write_region(*r, data);
+ }
+ out
+}
+
+/// A fill's colours as stand-ins. A solid colour is first stored at the document's depth, as the
+/// compositor renders CMYK solid fills (`gradient_fill::render_cmyk_fill`).
+fn stand_in_fill(f: &mut Fill, planes: Planes, depth: SampleType) {
+ match f {
+ Fill::Solid(c) => {
+ let one = Rect::new(0, 0, 1, 1);
+ let stored = crate::gradient_fill::render_cmyk_fill(&Fill::Solid(*c), one, one, depth).map(|s| s.pixel(0, 0));
+ let ink = stored.as_deref().map_or(c.in_mode(ColorMode::Cmyk).c, |p| std::array::from_fn(|i| p.get(i).copied().unwrap_or(0.0)));
+ let alpha = stored.as_deref().and_then(|p| p.get(4).copied()).unwrap_or(c.alpha);
+ *c = stand_in_color(&Color { mode: ColorMode::Cmyk, c: ink, alpha }, planes);
+ }
+ Fill::Gradient { stops, .. } => stops.iter_mut().for_each(|s| s.1 = stand_in_color(&s.1, planes)),
+ _ => {}
+ }
+}
+
+/// Levels and Curves on the CMYK channels as RGB records of the planes' inks (the composite
+/// record stays the composite).
+fn stand_in_adjustment(a: &mut Adjustment, planes: Planes) {
+ match a {
+ Adjustment::Levels { per_channel, space, black, .. } if *space == ToneSpace::Cmyk => {
+ let ink = |i: usize| if i == 3 { black.clone() } else { per_channel.get(i).cloned().unwrap_or_default() };
+ *per_channel = [ink(planes[0]), ink(planes[1]), ink(planes[2])];
+ *black = Default::default();
+ *space = ToneSpace::Rgb;
+ }
+ Adjustment::Curves { per_channel, space, black, .. } if *space == ToneSpace::Cmyk => {
+ let ink = |i: usize| if i == 3 { black.clone() } else { per_channel.get(i).cloned().unwrap_or_default() };
+ *per_channel = [ink(planes[0]), ink(planes[1]), ink(planes[2])];
+ *black = Vec::new();
+ *space = ToneSpace::Rgb;
+ }
+ _ => {}
+ }
+}
+
+fn stand_in_effect(e: &mut Effect, planes: Planes) {
+ let cc = |c: &mut Color| *c = stand_in_color(c, planes);
+ let paint = |p: &mut FxPaint| match p {
+ FxPaint::Color(c) => cc(c),
+ FxPaint::Gradient(g) => g.stops.iter_mut().for_each(|s| cc(&mut s.1)),
+ FxPaint::Pattern { .. } => {}
+ };
+ match e {
+ Effect::DropShadow(s) | Effect::InnerShadow(s) => cc(&mut s.color),
+ Effect::OuterGlow(g) | Effect::InnerGlow(g) => paint(&mut g.paint),
+ Effect::Stroke(s) => paint(&mut s.paint),
+ Effect::ColorOverlay { color, .. } => cc(color),
+ Effect::GradientOverlay { gradient, .. } => gradient.stops.iter_mut().for_each(|s| cc(&mut s.1)),
+ Effect::Satin(s) => cc(&mut s.color),
+ Effect::BevelEmboss(b) => {
+ cc(&mut b.highlight_color);
+ cc(&mut b.shadow_color);
+ }
+ Effect::PatternOverlay { .. } => {}
+ }
+}
+
+fn stand_in_layer(l: &mut Layer, planes: Planes, depth: SampleType, canvas: Rect) {
+ let cache = |c: &mut Option<Surface>| {
+ if let Some(s) = c {
+ *s = stand_in_surface(s, planes);
+ }
+ };
+ let frame = crate::fill_frame(l, canvas);
+ // A fill covers the canvas and beyond, where effects near its edges reach.
+ let reach = canvas.inflate(crate::effects::margin(l).saturating_add(1));
+ match &mut l.content {
+ LayerContent::Raster(s) => *s = stand_in_surface(s, planes),
+ LayerContent::Text(t) => cache(&mut t.cache),
+ LayerContent::Shape(sh) => cache(&mut sh.cache),
+ LayerContent::Smart(sm) => cache(&mut sm.cache),
+ LayerContent::Fill(f) => {
+ // The cache stays valid: its fill is changed the same way.
+ if let Some(c) = l.fill_cache.as_mut().filter(|c| c.fill == *f) {
+ c.surface = stand_in_surface(&c.surface, planes);
+ stand_in_fill(&mut c.fill, planes, depth);
+ } else if matches!(f, Fill::Gradient { .. })
+ && let Some(s) = crate::gradient_fill::render_cmyk_fill(f, reach, frame, depth)
+ {
+ // A gradient is the compositor's own CMYK ramp (an RGB ramp of the stand-in
+ // colours would interpolate differently), given as the fill's rendered pixels.
+ let mut fill = f.clone();
+ stand_in_fill(&mut fill, planes, depth);
+ l.fill_cache = Some(photocraft_doc::FillCache { fill, surface: stand_in_surface(&s, planes) });
+ }
+ stand_in_fill(f, planes, depth);
+ }
+ LayerContent::Adjustment(a) => stand_in_adjustment(a, planes),
+ LayerContent::Group(g) => g.children.iter_mut().for_each(|c| stand_in_layer(c, planes, depth, canvas)),
+ }
+ l.effects.items.iter_mut().for_each(|e| stand_in_effect(e, planes));
+}
+
+/// `doc` as an RGB document carrying the `planes` inks' brightness.
+pub(super) fn stand_in(doc: &Document, planes: Planes) -> Document {
+ let mut d = doc.clone();
+ d.mode = ColorMode::Rgb;
+ d.icc_profile = None;
+ d.layers.iter_mut().for_each(|l| stand_in_layer(l, planes, doc.depth, doc.bounds()));
+ d
+}
+
+/// A stand-in document rendered over `rect` by the RGB compositor, blends clipped to 0..1.
+struct StandIn<'a> {
+ doc: &'a Document,
+ cx: Ctx<'a>,
+}
+
+impl<'a> StandIn<'a> {
+ /// Ready to render `rect` (effect maps built up front, as the RGB compositor does).
+ fn prepare(&self, rect: Rect) {
+ self.cx.set_fx_clip(rect);
+ crate::prepare_effects(&self.doc.layers, rect, &self.cx, |f| crate::in_blend_space(false, false, f));
+ }
+
+ fn tile(&self, rect: Rect) -> Buffer {
+ crate::in_blend_space(false, false, || {
+ let mut b = Buffer::transparent(rect);
+ crate::composite_stack_at(&self.doc.layers, &mut b, &self.cx, advanced::Scope::ROOT);
+ b
+ })
+ }
+}
+
+/// The CMY and K stand-ins' tiles as one CMYK tile.
+fn combine(cmy: &Buffer, k: &Buffer) -> CmykBuffer {
+ let ink = |v: f32| if v.is_finite() { (1.0 - v).clamp(0.0, 1.0) } else { 0.0 };
+ let px = cmy
+ .px
+ .iter()
+ .zip(&k.px)
+ .map(|(p, q)| {
+ let alpha = clean(p[3]).clamp(0.0, 1.0);
+ if alpha <= 0.0 { [0.0; 5] } else { [ink(p[0]), ink(p[1]), ink(p[2]), ink(q[0]), alpha] }
+ })
+ .collect();
+ CmykBuffer { rect: cmy.rect, px }
+}
+
+/// Renders `doc` (which [`supports`]) band by band through the two stand-ins.
+pub(super) fn render_bands<E>(doc: &Document, rect: Rect, band_rows: i32, tile: i32, mut sink: impl FnMut(CmykBuffer) -> Result<(), E>) -> Result<(), E> {
+ let (cmy, k) = (stand_in(doc, CMY), stand_in(doc, K));
+ let no_patterns = pattern::PreparedPatterns::new(&[], pattern::PREPARED_PATTERN_BYTES);
+ let a = StandIn { doc: &cmy, cx: Ctx::for_doc(&cmy, &no_patterns) };
+ let b = StandIn { doc: &k, cx: Ctx::for_doc(&k, &no_patterns) };
+ let rows = crate::band_rows_for(rect.width(), band_rows);
+ let mut y = rect.y0;
+ while y < rect.y1 {
+ let y1 = y.saturating_add(rows).min(rect.y1);
+ let band = Rect::new(rect.x0, y, rect.x1, y1);
+ a.prepare(band);
+ b.prepare(band);
+ sink(super::render_with(band, tile, |t| combine(&a.tile(t), &b.tile(t))))?;
+ y = y1;
+ }
+ Ok(())
+}
+
+/// `doc`'s `planes` stand-in rendered over `rect` (tests compare plane orders).
+#[cfg(test)]
+pub(super) fn render_planes(doc: &Document, rect: Rect, planes: Planes) -> Buffer {
+ let d = stand_in(doc, planes);
+ let no_patterns = pattern::PreparedPatterns::new(&[], pattern::PREPARED_PATTERN_BYTES);
+ let s = StandIn { doc: &d, cx: Ctx::for_doc(&d, &no_patterns) };
+ s.prepare(rect);
+ s.tile(rect)
+}
diff --git a/crates/compose/src/cmyk_tests.rs b/crates/compose/src/cmyk_tests.rs
index a677e6e1a..0b73c2530 100644
--- a/crates/compose/src/cmyk_tests.rs
+++ b/crates/compose/src/cmyk_tests.rs
@@ -396,7 +396,6 @@ fn unsupported_documents_fall_back() {
check("hue", &|l| l.blend = BlendMode::Hue);
check("luminosity", &|l| l.blend = BlendMode::Luminosity);
check("lighter colour", &|l| l.blend = BlendMode::LighterColor);
- check("knockout", &|l| l.advanced.knockout = Knockout::Shallow);
check("channels", &|l| l.excluded_channels = 1);
check("nan opacity", &|l| l.opacity = f32::NAN);
// Adjustments that weigh the channels together, or whose records name RGB channels.
@@ -418,7 +417,14 @@ fn unsupported_documents_fall_back() {
}
let mut d = simple();
d.layers.push(deep);
- assert!(!supports(&d));
+ assert!(!supports(&d) && !renders_inks(&d));
+ // Knockouts take the ink-by-ink route through the RGB compositor instead.
+ let mut d = simple();
+ let mut l = layer(&[(Rect::new(0, 0, 1, 1), [0.5; 5])]);
+ l.advanced.knockout = Knockout::Shallow;
+ d.layers.push(l);
+ assert!(!supports(&d) && split::supports(&d));
+ assert!(render_cmyk(&d, d.bounds()).is_some());
}
#[test]
@@ -1094,6 +1100,8 @@ fn adjustment_stacks_match_the_reference() {
iso.blend = BlendMode::Normal;
d.layers.extend([inv, onto, base, lv, pass, iso]);
assert_matches_reference(&d);
+ // The black record and the rest go the same way through the stand-ins.
+ assert_routes_agree(&d);
}
/// In a 32-bit document (no rounding to levels), inks an adjustment leaves alone come out
@@ -1120,3 +1128,488 @@ fn untouched_inks_stay_bit_exact() {
assert!((got[3] - want_k).abs() < 1e-6, "{blend:?}: {got:?}");
}
}
+
+// ---- stage 4: layer effects, ink by ink through the RGB compositor -----------------------------
+
+use photocraft_doc::effects::{
+ Bevel, BevelStyle, BevelTechnique, Contour, Effect, FxCommon, FxPaint, Glow, GlowSource, GlowTechnique, Gradient, Satin, Shadow, StrokeFx, StrokePosition,
+};
+
+fn ink_color(c: [f32; 4]) -> photocraft_color::Color {
+ photocraft_color::Color { mode: ColorMode::Cmyk, c, alpha: 1.0 }
+}
+
+/// `d` over its canvas grown by a pixel, through the split route in 3-pixel tiles.
+fn split_render(d: &Document) -> CmykBuffer {
+ let rect = Rect::new(-1, -1, d.size.width as i32 + 1, d.size.height as i32 + 1);
+ let mut out = CmykBuffer::transparent(rect);
+ let r = split::render_bands(d, rect, 0, 3, |b| {
+ super::place(&mut out, &b);
+ Ok::<(), ()>(())
+ });
+ assert!(r.is_ok());
+ out
+}
+
+#[derive(Debug, Clone)]
+enum FxSpec {
+ Shadow { inner: bool, color: [f32; 4], blend: BlendMode, opacity: f32, distance: f32, size: f32, spread: f32, knocks_out: bool },
+ Glow { inner: bool, color: [f32; 4], gradient: Option<[f32; 4]>, blend: BlendMode, opacity: f32, size: f32 },
+ Stroke { color: [f32; 4], gradient: Option<[f32; 4]>, position: u8, size: f32, blend: BlendMode, opacity: f32 },
+ Overlay { color: [f32; 4], blend: BlendMode, opacity: f32 },
+ GradientOverlay { from: [f32; 4], to: [f32; 4], blend: BlendMode, opacity: f32 },
+ Satin { color: [f32; 4], blend: BlendMode, opacity: f32, invert: bool },
+ Bevel { style: u8, size: f32, up: bool, highlight: [f32; 4], shadow: [f32; 4] },
+}
+
+fn inks4() -> impl Strategy<Value = [f32; 4]> {
+ (unit(), unit(), unit(), unit()).prop_map(|(c, m, y, k)| [c, m, y, k])
+}
+
+fn fx_spec() -> impl Strategy<Value = FxSpec> {
+ prop_oneof![
+ (any::<bool>(), inks4(), blend_mode(), unit(), 0.0f32..3.0, 0.0f32..3.0, unit(), any::<bool>()).prop_map(
+ |(inner, color, blend, opacity, distance, size, spread, knocks_out)| FxSpec::Shadow {
+ inner,
+ color,
+ blend,
+ opacity,
+ distance,
+ size,
+ spread,
+ knocks_out
+ }
+ ),
+ (any::<bool>(), inks4(), prop::option::of(inks4()), blend_mode(), unit(), 0.0f32..3.0)
+ .prop_map(|(inner, color, gradient, blend, opacity, size)| FxSpec::Glow { inner, color, gradient, blend, opacity, size }),
+ (inks4(), prop::option::of(inks4()), 0u8..3, 1.0f32..3.0, blend_mode(), unit())
+ .prop_map(|(color, gradient, position, size, blend, opacity)| FxSpec::Stroke { color, gradient, position, size, blend, opacity }),
+ (inks4(), blend_mode(), unit()).prop_map(|(color, blend, opacity)| FxSpec::Overlay { color, blend, opacity }),
+ (inks4(), inks4(), blend_mode(), unit()).prop_map(|(from, to, blend, opacity)| FxSpec::GradientOverlay { from, to, blend, opacity }),
+ (inks4(), blend_mode(), unit(), any::<bool>()).prop_map(|(color, blend, opacity, invert)| FxSpec::Satin { color, blend, opacity, invert }),
+ (0u8..5, 1.0f32..3.0, any::<bool>(), inks4(), inks4()).prop_map(|(style, size, up, highlight, shadow)| FxSpec::Bevel {
+ style,
+ size,
+ up,
+ highlight,
+ shadow
+ }),
+ ]
+}
+
+fn make_effect(f: &FxSpec) -> Effect {
+ let paint = |c: &[f32; 4], g: &Option<[f32; 4]>| match g {
+ Some(to) => FxPaint::Gradient(Gradient { stops: vec![(0.0, ink_color(*c)), (1.0, ink_color(*to))], ..Default::default() }),
+ None => FxPaint::Color(ink_color(*c)),
+ };
+ match f {
+ FxSpec::Shadow { inner, color, blend, opacity, distance, size, spread, knocks_out } => {
+ let s = Shadow {
+ common: FxCommon::new(*blend, *opacity),
+ color: ink_color(*color),
+ angle: 120.0,
+ use_global_light: false,
+ distance: *distance,
+ spread: *spread,
+ size: *size,
+ contour: Contour::Linear,
+ anti_alias: false,
+ noise: 0.0,
+ knocks_out: *knocks_out,
+ };
+ if *inner { Effect::InnerShadow(s) } else { Effect::DropShadow(s) }
+ }
+ FxSpec::Glow { inner, color, gradient, blend, opacity, size } => {
+ let g = Glow {
+ common: FxCommon::new(*blend, *opacity),
+ paint: paint(color, gradient),
+ technique: GlowTechnique::Softer,
+ spread: 0.0,
+ size: *size,
+ contour: Contour::Linear,
+ anti_alias: false,
+ range: 0.5,
+ jitter: 0.0,
+ noise: 0.0,
+ source: GlowSource::Edge,
+ };
+ if *inner { Effect::InnerGlow(g) } else { Effect::OuterGlow(g) }
+ }
+ FxSpec::Stroke { color, gradient, position, size, blend, opacity } => Effect::Stroke(StrokeFx {
+ common: FxCommon::new(*blend, *opacity),
+ size: *size,
+ position: [StrokePosition::Outside, StrokePosition::Inside, StrokePosition::Center][usize::from(*position) % 3],
+ paint: paint(color, gradient),
+ }),
+ FxSpec::Overlay { color, blend, opacity } => Effect::ColorOverlay { common: FxCommon::new(*blend, *opacity), color: ink_color(*color) },
+ FxSpec::GradientOverlay { from, to, blend, opacity } => Effect::GradientOverlay {
+ common: FxCommon::new(*blend, *opacity),
+ gradient: Gradient { stops: vec![(0.0, ink_color(*from)), (1.0, ink_color(*to))], ..Default::default() },
+ dither: false,
+ },
+ FxSpec::Satin { color, blend, opacity, invert } => Effect::Satin(Satin {
+ common: FxCommon::new(*blend, *opacity),
+ color: ink_color(*color),
+ angle: 19.0,
+ distance: 2.0,
+ size: 2.0,
+ contour: Contour::Linear,
+ anti_alias: false,
+ invert: *invert,
+ }),
+ FxSpec::Bevel { style, size, up, highlight, shadow } => Effect::BevelEmboss(Bevel {
+ enabled: true,
+ style: [BevelStyle::OuterBevel, BevelStyle::InnerBevel, BevelStyle::Emboss, BevelStyle::PillowEmboss, BevelStyle::StrokeEmboss]
+ [usize::from(*style) % 5],
+ technique: BevelTechnique::Smooth,
+ depth: 1.0,
+ up: *up,
+ size: *size,
+ soften: 0.0,
+ angle: 120.0,
+ altitude: 30.0,
+ use_global_light: false,
+ gloss_contour: Contour::Linear,
+ highlight: FxCommon::new(BlendMode::Screen, 0.75),
+ highlight_color: ink_color(*highlight),
+ shadow: FxCommon::new(BlendMode::Multiply, 0.75),
+ shadow_color: ink_color(*shadow),
+ contour: None,
+ texture: None,
+ }),
+ }
+}
+
+/// A random document with effects on some of its layers (and a knockout now and then).
+fn with_effects(s: &Spec, fx: &[(usize, FxSpec)], knockout: Option<usize>) -> Document {
+ let mut d = doc(s.w as u32, s.h as u32);
+ d.layers = s.layers.iter().map(build).collect();
+ let n = d.layers.len().max(1);
+ for (i, f) in fx {
+ // Adjustment layers don't carry effects (see `split::supports`).
+ if let Some(l) = d.layers.get_mut(i % n).filter(|l| !matches!(l.content, LayerContent::Adjustment(_))) {
+ l.effects.enabled = true;
+ l.effects.items.push(make_effect(f));
+ }
+ }
+ if let Some(l) = knockout.and_then(|i| d.layers.get_mut(i % n)) {
+ l.advanced.knockout = Knockout::Shallow;
+ }
+ d
+}
+
+proptest! {
+ #![proptest_config(ProptestConfig { cases: 120, ..ProptestConfig::default() })]
+
+ /// On every stack the exact path handles, the split route gives the same inks.
+ #[test]
+ fn the_split_route_agrees_with_the_exact_path(s in spec()) {
+ prop_assume!(!clips_onto_pass_through(&s.layers));
+ let mut d = doc(s.w as u32, s.h as u32);
+ d.layers = s.layers.iter().map(build).collect();
+ prop_assume!(supports(&d) && split::supports(&d));
+ // Both are exact up to float rounding, which a mode that jumps can magnify (see [`jumps`]).
+ prop_assume!(!any_layer(&d.layers, &|l| jumps(l.blend)));
+ let via = split_render(&d);
+ let exact = render_cmyk(&d, via.rect).unwrap_or_else(|| panic!("supported"));
+ for (i, (g, w)) in via.px.iter().zip(&exact.px).enumerate() {
+ prop_assert!((g[4] - w[4]).abs() <= 1e-5, "alpha {i}: {g:?} vs {w:?}");
+ if w[4] > 1e-4 {
+ prop_assert!((0..4).all(|c| (g[c] - w[c]).abs() <= 1e-5), "ink {i}: {g:?} vs {w:?}");
+ }
+ }
+ }
+
+ /// The RGB compositor treats every channel on its own for everything the split route
+ /// allows, effects included: which ink feeds which channel doesn't change any ink's result
+ /// (nor coverage). That is what makes running it on inks' brightness exact.
+ #[test]
+ fn effects_work_channel_by_channel(
+ s in spec(),
+ fx in prop::collection::vec((0usize..8, fx_spec()), 1..4),
+ knockout in prop::option::of(0usize..8),
+ ) {
+ let d = with_effects(&s, &fx, knockout);
+ prop_assume!(split::supports(&d));
+ let rect = Rect::new(-2, -2, s.w + 2, s.h + 2);
+ let cmy = split::render_planes(&d, rect, [0, 1, 2]);
+ let rot = split::render_planes(&d, rect, [1, 2, 0]);
+ let k = split::render_planes(&d, rect, [3, 3, 3]);
+ let mix = split::render_planes(&d, rect, [3, 0, 3]);
+ let same = |a: f32, b: f32| (a - b).abs() <= 1e-6 || (a.is_nan() && b.is_nan());
+ for i in 0..cmy.px.len() {
+ let (p, r, q, m) = (cmy.px[i], rot.px[i], k.px[i], mix.px[i]);
+ prop_assert!(same(p[3], r[3]) && same(p[3], q[3]) && same(p[3], m[3]), "coverage {i}: {p:?} {r:?} {q:?} {m:?}");
+ prop_assert!(same(r[0], p[1]) && same(r[1], p[2]) && same(r[2], p[0]), "rotated {i}: {p:?} vs {r:?}");
+ prop_assert!(same(q[0], q[1]) && same(q[1], q[2]), "black {i}: {q:?}");
+ prop_assert!(same(m[0], q[0]) && same(m[1], p[0]) && same(m[2], q[0]), "mixed {i}: {m:?} vs {p:?} / {q:?}");
+ }
+ }
+
+ /// Effects don't depend on the tiling or banding (beyond the RGB compositor's own float
+ /// rounding, which can differ by an ulp between tilings).
+ #[test]
+ fn split_tiling_is_invisible(s in spec(), fx in prop::collection::vec((0usize..8, fx_spec()), 1..3), tile in 1i32..9) {
+ let d = with_effects(&s, &fx, None);
+ prop_assume!(split::supports(&d));
+ let whole = render_cmyk_tiled(&d, d.bounds(), 1024).unwrap_or_else(|| panic!("supported"));
+ let tiled = render_cmyk_tiled(&d, d.bounds(), tile).unwrap_or_else(|| panic!("supported"));
+ for (p, q) in tiled.px.iter().zip(&whole.px) {
+ prop_assert!(p.iter().zip(q).all(|(a, b)| (a - b).abs() <= 1e-6), "{p:?} vs {q:?}");
+ }
+ }
+}
+
+/// A K-only drop shadow under K-only type on blank paper puts down black ink only.
+#[test]
+fn k_only_shadows_stay_k_only() {
+ let mut d = doc(12, 8);
+ d.layers.push(paper(12, 8, [0.0; 4]));
+ let mut t = layer(&[(Rect::new(2, 2, 6, 5), [0.0, 0.0, 0.0, 1.0, 1.0])]);
+ t.effects.enabled = true;
+ t.effects.items.push(Effect::DropShadow(Shadow {
+ common: FxCommon::new(BlendMode::Multiply, 0.75),
+ color: ink_color([0.0, 0.0, 0.0, 1.0]),
+ angle: 135.0,
+ use_global_light: false,
+ distance: 2.0,
+ spread: 0.0,
+ size: 0.0,
+ contour: Contour::Linear,
+ anti_alias: false,
+ noise: 0.0,
+ knocks_out: true,
+ }));
+ d.layers.push(t);
+ assert!(!supports(&d) && split::supports(&d));
+ let got = render_cmyk(&d, d.bounds()).unwrap_or_else(|| panic!("supported"));
+ assert!(got.px.iter().all(|p| p[..3].iter().all(|v| *v <= 1e-6)), "no C, M or Y anywhere");
+ // Light from the upper left: the shadow falls a pixel down and to the right of the type.
+ let at = |x: i32, y: i32| got.px[(y * 12 + x) as usize];
+ assert!((at(6, 5)[3] - 0.75).abs() < 1e-5, "shadow: {:?}", at(6, 5));
+ assert!((at(3, 3)[3] - 1.0).abs() < 1e-6, "type: {:?}", at(3, 3));
+ assert!(at(10, 1)[3] <= 1e-6, "paper: {:?}", at(10, 1));
+}
+
+/// A colour overlay paints the layer in exactly its inks; an outside stroke in its own.
+#[test]
+fn overlays_and_strokes_paint_exact_inks() {
+ let mut d = doc(10, 8);
+ d.layers.push(paper(10, 8, [0.0; 4]));
+ let mut l = layer(&[(Rect::new(3, 3, 7, 6), [0.0, 0.0, 0.0, 1.0, 1.0])]);
+ l.effects.enabled = true;
+ l.effects.items.push(Effect::ColorOverlay { common: FxCommon::new(BlendMode::Normal, 1.0), color: ink_color([0.2, 0.4, 0.6, 0.1]) });
+ l.effects.items.push(Effect::Stroke(StrokeFx {
+ common: FxCommon::new(BlendMode::Normal, 1.0),
+ size: 1.0,
+ position: StrokePosition::Outside,
+ paint: FxPaint::Color(ink_color([0.0, 1.0, 0.0, 0.0])),
+ }));
+ d.layers.push(l);
+ let got = render_cmyk(&d, d.bounds()).unwrap_or_else(|| panic!("supported"));
+ let at = |x: i32, y: i32| got.px[(y * 10 + x) as usize];
+ let near = |a: Cmyka, b: Cmyka| a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 1e-6);
+ assert!(near(at(4, 4), [0.2, 0.4, 0.6, 0.1, 1.0]), "overlay: {:?}", at(4, 4));
+ assert!(near(at(2, 4), [0.0, 1.0, 0.0, 0.0, 1.0]), "stroke: {:?}", at(2, 4));
+ assert!(near(at(0, 0), [0.0, 0.0, 0.0, 0.0, 1.0]), "paper: {:?}", at(0, 0));
+}
+
+/// Pattern paints and channel-mixing effect modes stay on the RGB compositor.
+#[test]
+fn effects_that_mix_channels_fall_back() {
+ let with = |e: Effect| {
+ let mut d = doc(2, 2);
+ let mut l = layer(&[(Rect::new(0, 0, 1, 1), [0.5; 5])]);
+ l.effects.enabled = true;
+ l.effects.items.push(e);
+ d.layers.push(l);
+ d
+ };
+ let overlay = |blend| Effect::ColorOverlay { common: FxCommon::new(blend, 1.0), color: ink_color([0.5; 4]) };
+ assert!(split::supports(&with(overlay(BlendMode::Multiply))));
+ assert!(!renders_inks(&with(overlay(BlendMode::Color))));
+ let pattern = Effect::PatternOverlay {
+ common: FxCommon::new(BlendMode::Normal, 1.0),
+ name: "p".into(),
+ id: "p".into(),
+ scale: 1.0,
+ angle: 0.0,
+ link: true,
+ phase: (0.0, 0.0),
+ };
+ assert!(!renders_inks(&with(pattern)));
+ // Effects on an adjustment layer (it has no pixels of its own to shape them).
+ let mut adj = adjustment(Adjustment::Invert);
+ adj.effects.enabled = true;
+ adj.effects.items.push(overlay(BlendMode::Multiply));
+ let mut d = doc(2, 2);
+ d.layers.push(adj);
+ assert!(!split::supports(&d));
+ // 32-bit CMYK documents too.
+ let mut d = with(overlay(BlendMode::Multiply));
+ d.depth = SampleType::F32;
+ assert!(!split::supports(&d));
+}
+
+/// Found by a long random run: Normal mixing onto nothing must give the source's ink exactly. A
+/// rounding error (1 → 0.99999994) is magnified by modes that jump at full ink, here Reflect
+/// turning no ink into full K.
+#[test]
+fn normal_onto_nothing_is_exact() {
+ let shape = LayerSpec::Pixels {
+ kind: Kind::Shape,
+ blend: BlendMode::Normal,
+ fills: vec![(Rect::new(0, 0, 1, 1), [0.0, 0.0, 0.0, 1.0, 1.0])],
+ opacity: 1.0,
+ fill: 1.0,
+ clipped: false,
+ visible: true,
+ mask: Some(MaskSpec { rects: vec![], default: 0.4949783, density: 1.0, enabled: true }),
+ };
+ let inv = LayerSpec::Pixels {
+ kind: Kind::Adjust(AdjSpec::Invert),
+ blend: BlendMode::Reflect,
+ fills: vec![(Rect::new(0, 0, 1, 1), [0.0; 5])],
+ opacity: 1.0,
+ fill: 1.0,
+ clipped: false,
+ visible: true,
+ mask: None,
+ };
+ let mut d = doc(4, 6);
+ d.layers =
+ vec![build(&LayerSpec::Group { children: vec![shape, inv], pass_through: false, blend: BlendMode::Normal, opacity: 1.0, fill: 1.0, mask: None })];
+ assert_matches_reference(&d);
+ assert_eq!(render1(&d, 0, 0)[..4], [0.0; 4]);
+}
+
+/// Found by a long random run: a transparent pixel with ink of its own counts towards the
+/// layer's bounds, which lay out a gradient overlay; the stand-ins keep it counted whichever ink
+/// they carry.
+#[test]
+fn transparent_inked_pixels_keep_their_bounds() {
+ let inner = LayerSpec::Pixels {
+ kind: Kind::Raster,
+ blend: BlendMode::Normal,
+ fills: vec![(Rect::new(0, -1, 1, 1), [0.0, 0.0, 0.0, 0.0, 1.0]), (Rect::new(0, 1, 1, 2), [0.0, 0.0, 1.0, 0.0, 0.0])],
+ opacity: 1.0,
+ fill: 1.0,
+ clipped: false,
+ visible: true,
+ mask: None,
+ };
+ let g = |children: Vec<LayerSpec>, pass_through: bool| LayerSpec::Group {
+ children,
+ pass_through,
+ blend: BlendMode::Normal,
+ opacity: 1.0,
+ fill: 1.0,
+ mask: None,
+ };
+ let s = Spec { w: 2, h: 2, layers: vec![g(vec![g(vec![g(vec![inner], false)], false)], true)] };
+ let fx = [(0usize, FxSpec::GradientOverlay { from: [1.0, 0.0, 0.0, 0.0], to: [0.0; 4], blend: BlendMode::Normal, opacity: 1.0 })];
+ let d = with_effects(&s, &fx, None);
+ let rect = Rect::new(-2, -2, 4, 4);
+ let cmy = split::render_planes(&d, rect, [0, 1, 2]);
+ for planes in [[3, 0, 3], [0, 0, 0], [0, 3, 3]] {
+ let other = split::render_planes(&d, rect, planes);
+ let at = planes.iter().position(|p| *p == 0).unwrap_or(0);
+ for (p, o) in cmy.px.iter().zip(&other.px) {
+ assert!((p[0] - o[at]).abs() <= 1e-6 && (p[3] - o[3]).abs() <= 1e-6, "{planes:?}: {p:?} vs {o:?}");
+ }
+ }
+}
+
+/// Blend modes that jump (at no ink or full ink): a rounding difference between two exact
+/// computations can land on either side of the jump.
+fn jumps(mode: BlendMode) -> bool {
+ use BlendMode as B;
+ matches!(mode, B::ColorBurn | B::ColorDodge | B::VividLight | B::HardMix | B::Divide | B::Reflect | B::Glow | B::PaintNetColorBurn | B::PaintNetColorDodge)
+}
+
+fn any_layer(layers: &[Layer], f: &dyn Fn(&Layer) -> bool) -> bool {
+ layers.iter().any(|l| f(l) || matches!(&l.content, LayerContent::Group(g) if any_layer(&g.children, f)))
+}
+
+/// The display form of the ink composite: where a single opaque layer's pixel shows, it is the
+/// colour the RGB compositor shows (both read the inks through the document's profile).
+#[test]
+fn display_shows_the_inks_through_the_profile() {
+ let mut d = doc(8, 4);
+ d.layers.push(paper(8, 4, [0.0; 4]));
+ d.layers.push(layer(&[(Rect::new(0, 0, 4, 4), [0.0, 0.0, 0.0, 1.0, 1.0]), (Rect::new(4, 0, 8, 2), [0.7, 0.1, 0.0, 0.3, 1.0])]));
+ let shown = render_display(&d, d.bounds()).unwrap_or_else(|| panic!("supported"));
+ let rgb = crate::render(&d, d.bounds());
+ for (s, r) in shown.px.iter().zip(&rgb.px) {
+ assert!(s.iter().zip(r).all(|(a, b)| (a - b).abs() <= 1e-4), "{s:?} vs {r:?}");
+ }
+ // Unsupported documents have no ink composite to show.
+ let mut lum = layer(&[(Rect::new(0, 0, 1, 1), [0.5; 5])]);
+ lum.blend = BlendMode::Luminosity;
+ d.layers.push(lum);
+ assert!(render_display(&d, d.bounds()).is_none());
+}
+
+/// The split route gives the exact path's inks on `d` (which both handle).
+fn assert_routes_agree(d: &Document) {
+ assert!(supports(d) && split::supports(d));
+ let via = split_render(d);
+ let exact = render_cmyk(d, via.rect).unwrap_or_else(|| panic!("supported"));
+ for (g, w) in via.px.iter().zip(&exact.px) {
+ assert!((g[4] - w[4]).abs() <= 1e-5 && (w[4] <= 1e-4 || (0..4).all(|c| (g[c] - w[c]).abs() <= 1e-5)), "{g:?} vs {w:?}");
+ }
+}
+
+/// Black-only Levels and Curves through the stand-ins: K changes, nothing else does.
+#[test]
+fn black_records_reach_k_through_the_stand_ins() {
+ use photocraft_doc::adjust::{CurvePoint, LevelsChannel, ToneSpace};
+ let d0 = LevelsChannel::default;
+ for adj in [
+ cmyk_levels(d0(), LevelsChannel { out_white: 0.5, ..d0() }),
+ Adjustment::Curves {
+ master: Vec::new(),
+ per_channel: [Vec::new(), Vec::new(), Vec::new()],
+ space: ToneSpace::Cmyk,
+ black: vec![CurvePoint { input: 0.0, output: 0.0 }, CurvePoint { input: 1.0, output: 0.6 }],
+ },
+ ] {
+ let mut d = doc(3, 1);
+ d.layers.push(paper(3, 1, [0.1, 0.2, 0.3, 0.0]));
+ d.layers.push(adjustment(adj));
+ assert_routes_agree(&d);
+ assert!(split_render(&d).px.iter().filter(|p| p[4] > 0.0).all(|p| p[3] > 0.3), "K added");
+ }
+}
+
+/// Effects are laid out over the layer's bounds, which on a layer without transparency the
+/// stand-ins can't keep (its pixels that differ only in other inks would match the default):
+/// such a layer stays on the RGB compositor.
+#[test]
+fn effects_on_opaque_layers_fall_back() {
+ let mut d = doc(4, 4);
+ let mut bg = paper(4, 4, [0.0; 4]);
+ bg.effects.enabled = true;
+ bg.effects.items.push(Effect::ColorOverlay { common: FxCommon::new(BlendMode::Multiply, 0.5), color: ink_color([0.0, 0.0, 0.0, 1.0]) });
+ d.layers.push(bg);
+ assert!(!split::supports(&d) && !renders_inks(&d));
+}
+
+/// Solid and gradient fills without rendered pixels give the same inks on both routes (both
+/// stored at the document's levels, as the compositor renders CMYK fills).
+#[test]
+fn fills_agree_on_both_routes() {
+ let g = photocraft_doc::Fill::gradient(
+ vec![(0.0, cmyk_color([1.0, 0.2, 0.0, 0.0], 1.0)), (1.0, cmyk_color([0.0, 0.0, 0.7, 1.0], 0.6))],
+ 30.0,
+ 1.0,
+ Default::default(),
+ false,
+ );
+ for fill in [g, photocraft_doc::Fill::Solid(cmyk_color([0.13, 0.0, 0.9375, 0.0], 0.55))] {
+ let mut d = doc(9, 5);
+ d.layers.push(paper(9, 5, [0.0, 0.1, 0.0, 0.0]));
+ d.layers.push(Layer::new("f", LayerContent::Fill(fill)));
+ assert_routes_agree(&d);
+ }
+}
diff --git a/crates/io/tests/cmyk_export.rs b/crates/io/tests/cmyk_export.rs
index 5f192700c..67d5ed77e 100644
--- a/crates/io/tests/cmyk_export.rs
+++ b/crates/io/tests/cmyk_export.rs
@@ -174,3 +174,42 @@ fn channel_weighing_adjustments_go_through_the_profile() {
assert!(r.warnings.iter().any(|w| w.contains("converted back through the document's CMYK profile")), "{:?}", r.warnings);
assert_eq!(decode(&r.bytes).layout(), ChannelLayout::Cmyk);
}
+
+#[test]
+fn layer_effects_export_their_inks() {
+ // K-only type with a K-only drop shadow on blank paper: the TIFF has black ink only.
+ use photocraft_doc::effects::{Contour, Effect, FxCommon, Shadow};
+ let mut d = cmyk_doc(SampleType::U8);
+ d.layers.push(fill(SampleType::U8, false, &[(Rect::new(0, 0, 12, 8), [0.0; 5])]));
+ let mut t = fill(SampleType::U8, true, &[(Rect::new(2, 2, 6, 5), [0.0, 0.0, 0.0, 1.0, 1.0])]);
+ t.effects.enabled = true;
+ t.effects.items.push(Effect::DropShadow(Shadow {
+ common: FxCommon::new(BlendMode::Multiply, 0.75),
+ color: photocraft_color::Color { mode: ColorMode::Cmyk, c: [0.0, 0.0, 0.0, 1.0], alpha: 1.0 },
+ angle: 135.0,
+ use_global_light: false,
+ distance: 2.0,
+ spread: 0.0,
+ size: 1.0,
+ contour: Contour::Linear,
+ anti_alias: false,
+ noise: 0.0,
+ knocks_out: true,
+ }));
+ d.layers.push(t);
+ let r = export(&d, "a.tif", &ExportOptions::default()).unwrap_or_else(|e| panic!("{e}"));
+ assert!(!r.warnings.iter().any(|w| w.contains("converted back")), "{:?}", r.warnings);
+ let img = decode(&r.bytes);
+ assert_eq!(img.layout(), ChannelLayout::Cmyk);
+ let mut shadow = 0;
+ for y in 0..8 {
+ for x in 0..12 {
+ let p = pixel(&img, x, y);
+ assert_eq!(&p[..3], &[0.0; 3], "({x},{y}) {p:?}");
+ shadow += usize::from(p[3] > 0.0 && p[3] < 1.0);
+ }
+ }
+ assert!(shadow > 0, "a soft shadow");
+ assert_eq!(pixel(&img, 3, 3), vec![0.0, 0.0, 0.0, 1.0], "type");
+}
+