PhotoCraft: An open-source, photo editor written by scratch in pure Rust
CMYK: adjustment layers composite on the document's own inks (14 oracles pass) (#4945)
Timothy Daly1e6f565a7bcc
diff --git a/crates/compose/src/adjust.rs b/crates/compose/src/adjust.rsindex 4d37aa39a..87f41030a 100644--- a/crates/compose/src/adjust.rs+++ b/crates/compose/src/adjust.rs@@ -392,6 +392,9 @@ pub fn stored_channels(adj: &Adjustment, mode: ColorMode, depth: Option<SampleTy*v = if i > 0 { mirror } else { 1.0 } - v.clamp(0.0, 1.0);}}+ // CMYK posterizes the stored values (1 - ink), which its uneven levels make differ from+ // posterizing the ink: psd-tools posterize_cmyk.psd (3 to 21 levels) is exact so.+ Adjustment::Posterize { levels } if mode == ColorMode::Cmyk => ch.iter_mut().for_each(|v| *v = 1.0 - posterize_in(1.0 - *v, *levels, depth)),Adjustment::Posterize { levels } => ch.iter_mut().for_each(|v| *v = posterize_in(*v, *levels, depth)),Adjustment::Threshold { level } => {// On the 8-bit grid, like the RGB threshold.@@ -2033,6 +2036,17 @@ mod tone_tests {assert!(near(in_cmyk(&t, [0.8; 3]), cmyk_to_rgb([0.0; 4]), 2e-3));}+ /// CMYK posterizes the stored value 1 - ink: with 3 levels an ink of 85 (stored 170) lands on+ /// the middle step, 128 (stored 127), where posterizing the ink would drop it to none (psd-tools+ /// posterize_cmyk.psd, levels 3 to 21, exact so).+ #[test]+ fn cmyk_posterize_works_on_the_stored_values() {+ let mut ink = [85.0 / 255.0; 4];+ stored_channels(&Adjustment::Posterize { levels: 3 }, ColorMode::Cmyk, Some(SampleType::U8), &mut ink);+ assert!(ink.iter().all(|v| (v * 255.0 - 128.0).abs() < 1e-3), "{ink:?}");+ assert_eq!(posterize(85.0 / 255.0, 3), 0.0, "posterizing the ink itself");+ }+#[test]fn cmyk_threshold_compares_the_inks_plain_luma() {assert_eq!(ink_luma([0.0; 4]), 1.0);diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rsindex f05520a58..b742540b9 100644--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@ -129,6 +129,10 @@ fn render_tiled_with(doc: &Document, rect: Rect, tile: i32, cx: &Ctx) -> Bufferif u64::from(rect.width()) * u64::from(rect.height()) > MAX_RENDER_PIXELS {return Buffer::transparent(Rect::EMPTY);}+ // A CMYK stack with adjustment layers the inks carry exactly composites on its inks.+ if let Some(buf) = native::render_cmyk(doc, rect, tile) {+ return buf;+ }// A Lab stack with adjustment layers that work on L, a and b composites on its stored values.if let Some(buf) = native_lab::render_lab(doc, rect, tile) {return buf;diff --git a/crates/compose/src/native.rs b/crates/compose/src/native.rsindex 9eafd18cc..e2bc653d7 100644--- a/crates/compose/src/native.rs+++ b/crates/compose/src/native.rs@@ -1,85 +1,246 @@-//! Mode-native flattening of plain CMYK layer stacks (#3778).+//! Mode-native compositing of plain CMYK layer stacks (#3778).//!//! The compositor works in display RGB, so flattening a CMYK document through it reads every ink//! value through the profile and separates it again: even a lone Background comes back with//! different ink. When every visible layer is a plain raster layer in Normal mode (no masks,//! effects, clipping or advanced blending), the composite needs no colour conversion at all://! Normal mixes ink values linearly, as Photoshop does in CMYK, so it is worked out on the stored-//! values and an opaque layer keeps them exactly.+//! values and an opaque layer keeps them exactly. A layer mask (unfeathered) scales the mix, as+//! it does there.+//!+//! Plain adjustment layers that Photoshop evaluates on the inks (Invert, Posterize, Threshold,+//! Brightness/Contrast, and Levels and Curves on CMYK channels) join such a stack too: on the+//! stored inks their rules are exact, where the RGB compositor can only apply them to a separation+//! of its RGB composite, whose black differs from the file's. Such stacks are also rendered for+//! display this way ([`render_cmyk`]); stacks of raster layers alone keep the RGB compositor there.use photocraft_color::blend::BlendMode;-use photocraft_color::{ColorMode, PixelFormat};-use photocraft_doc::{Document, Layer, LayerContent};+use photocraft_color::{ColorMode, PixelFormat, SampleType};+use photocraft_doc::adjust::ToneSpace;+use photocraft_doc::{Adjustment, Document, Layer, LayerContent, LayerMask};use photocraft_geom::Rect;use photocraft_raster::Surface;+use crate::{Buffer, adjust};+/// Process channels of a CMYK pixel.const INKS: usize = 4;-/// A layer the native path can composite: a visible raster layer the compositor would only blend-/// Normally at its opacity.-fn plain(layer: &Layer) -> Option<&Surface> {- let LayerContent::Raster(s) = &layer.content else { return None };- let simple = layer.blend == BlendMode::Normal+/// Whether the compositor would only blend `layer` Normally at its opacity through its layer mask:+/// no clipping, vector mask, feathered mask, effects, excluded channels, Blend If or advanced+/// blending.+fn simple(layer: &Layer) -> bool {+ layer.blend == BlendMode::Normal&& !layer.clipped- && layer.mask.as_ref().is_none_or(|m| !m.enabled)+ && !crate::masks::has_feather(layer)&& layer.vector_mask.as_ref().is_none_or(|v| !v.enabled)&& !crate::effects::has_effects(layer)&& layer.excluded_channels == 0&& layer.blend_if.is_default()&& layer.advanced.is_default()&& layer.video.is_none()- && s.format().mode == ColorMode::Cmyk;- simple.then_some(s)+}++/// A layer the native path can composite: a visible raster layer the compositor would only blend+/// Normally at its opacity.+fn plain(layer: &Layer) -> Option<&Surface> {+ let LayerContent::Raster(s) = &layer.content else { return None };+ (simple(layer) && s.format().mode == ColorMode::Cmyk).then_some(s)+}++/// An adjustment on straight inks, prepared once per composite.+enum InkOp<'a> {+ /// Each ink's stored value (1 - ink) through its channel's table: C, M, Y, K+ /// (`adjust::ink_through`; Levels, Curves and Brightness/Contrast).+ Tables([Vec<f32>; INKS]),+ /// Invert, Posterize or Threshold (`adjust::stored_channels`).+ Rules(&'a Adjustment),+}++impl InkOp<'_> {+ fn apply(&self, ink: &mut [f32; INKS], depth: SampleType) {+ match self {+ InkOp::Tables(t) => {+ for (v, table) in ink.iter_mut().zip(t) {+ *v = adjust::ink_through(table, *v);+ }+ }+ InkOp::Rules(adj) => adjust::stored_channels(adj, ColorMode::Cmyk, Some(depth), ink),+ }+ }+}++/// The ink evaluation of an adjustment layer the native path can composite.+fn ink_op(layer: &Layer, depth: SampleType) -> Option<InkOp<'_>> {+ let LayerContent::Adjustment(adj) = &layer.content else { return None };+ if !simple(layer) {+ return None;+ }+ match adj {+ Adjustment::Invert | Adjustment::Posterize { .. } | Adjustment::Threshold { .. } => Some(InkOp::Rules(adj)),+ Adjustment::BrightnessContrast { brightness, contrast, legacy } => {+ let t = adjust::ink_brightness_contrast_lut(*brightness, *contrast, *legacy);+ Some(InkOp::Tables([t.clone(), t.clone(), t.clone(), t]))+ }+ Adjustment::Levels { space: ToneSpace::Cmyk, .. } | Adjustment::Curves { space: ToneSpace::Cmyk, .. } => {+ Some(InkOp::Tables(adjust::tone_luts_depth(adj, Some(depth))))+ }+ _ => None,+ }+}++/// One step of a native stack, at the layer's opacity × fill, through its mask.+enum Item<'a> {+ Layer(&'a Surface, f32, Option<&'a LayerMask>),+ Adjust(InkOp<'a>, f32, Option<&'a LayerMask>),+}++/// Groups nested deeper than this keep the RGB compositor.+const MAX_DEPTH: usize = 64;++/// `layers`' visible steps, appended to `items`; `None` when one needs the RGB compositor. A group+/// at full opacity without a mask is inlined: pass-through groups composite their children straight+/// onto the backdrop, and so do isolated (Normal) groups of raster layers alone, since Normal+/// composites associatively; an adjustment inside an isolated group would only see the group's+/// own content, so such a group keeps the RGB compositor (`adjustments` false).+fn collect<'a>(layers: &'a [Layer], depth: SampleType, adjustments: bool, items: &mut Vec<Item<'a>>, level: usize) -> Option<()> {+ if level > MAX_DEPTH {+ return None;+ }+ for layer in layers.iter().filter(|l| l.visible) {+ let alpha = (layer.opacity * layer.fill_opacity).clamp(0.0, 1.0);+ let mask = layer.mask.as_ref().filter(|m| m.enabled);+ if let LayerContent::Group(g) = &layer.content {+ let open = g.artboard.is_none()+ && alpha >= 1.0+ && mask.is_none()+ && !layer.clipped+ && layer.vector_mask.as_ref().is_none_or(|v| !v.enabled)+ && !crate::effects::has_effects(layer)+ && layer.excluded_channels == 0+ && layer.blend_if.is_default()+ && layer.advanced.is_default();+ match layer.blend {+ BlendMode::PassThrough if open => collect(&g.children, depth, adjustments, items, level + 1)?,+ BlendMode::Normal if open => collect(&g.children, depth, false, items, level + 1)?,+ _ => return None,+ }+ continue;+ }+ let item = match plain(layer) {+ Some(s) => Item::Layer(s, alpha, mask),+ None if adjustments => Item::Adjust(ink_op(layer, depth)?, alpha, mask),+ None => return None,+ };+ items.push(item);+ }+ Some(())+}++/// A CMYK document's visible layers, prepared for compositing on their ink values.+pub struct InkStack<'a> {+ items: Vec<Item<'a>>,+ depth: SampleType,+}++impl<'a> InkStack<'a> {+ /// `None` unless `doc` is CMYK and every visible layer is a plain raster layer, a plain+ /// adjustment layer the inks carry exactly, or a group that can be inlined (see the module+ /// docs and [`collect`]).+ pub fn new(doc: &'a Document) -> Option<Self> {+ if doc.mode != ColorMode::Cmyk {+ return None;+ }+ let mut items = Vec::new();+ collect(&doc.layers, doc.depth, true, &mut items, 0)?;+ Some(InkStack { items, depth: doc.depth })+ }++ /// Whether the stack has an adjustment layer (the RGB compositor can't match it exactly).+ pub fn adjusts(&self) -> bool {+ self.items.iter().any(|i| matches!(i, Item::Adjust(..)))+ }++ /// Straight C, M, Y, K and alpha over `rect`, row-major, into `acc` (`src` and `mv` are+ /// scratch).+ fn composite(&self, rect: Rect, acc: &mut Vec<[f32; INKS + 1]>, src: &mut Vec<f32>, mv: &mut Vec<f32>) {+ let n = rect.width() as usize * rect.height() as usize;+ acc.clear();+ acc.resize(n, [0.0f32; INKS + 1]);+ // The mask's value at pixel `i` (1 without one).+ let masked = |mask: Option<&LayerMask>, mv: &mut Vec<f32>| match mask {+ Some(m) => m.values_into(rect, mv),+ None => {+ mv.clear();+ mv.resize(n, 1.0);+ }+ };+ for item in &self.items {+ match item {+ Item::Layer(surf, opacity, mask) => {+ let opacity = *opacity;+ if opacity <= 0.0 || (surf.content_bounds().intersect(&rect).is_empty() && surf.default_pixel().iter().all(|v| *v == 0.0)) {+ continue;+ }+ let sf = surf.format();+ let sn = sf.channels();+ surf.read_region_into(rect, src);+ masked(*mask, mv);+ for ((d, s), k) in acc.iter_mut().zip(src.chunks_exact(sn)).zip(mv.iter()) {+ let sa = if sf.alpha { s.get(INKS).copied().unwrap_or(1.0) } else { 1.0 } * opacity * k.clamp(0.0, 1.0);+ if sa <= 0.0 {+ continue;+ }+ let oa = sa + d[INKS] * (1.0 - sa);+ let keep = d[INKS] * (1.0 - sa);+ for (c, v) in s.iter().take(INKS).enumerate() {+ // An opaque pixel replaces what is below exactly (no rounding through the mix).+ d[c] = if sa >= 1.0 { *v } else { (v * sa + d[c] * keep) / oa };+ }+ d[INKS] = oa;+ }+ }+ Item::Adjust(op, opacity, mask) => {+ if *opacity <= 0.0 {+ continue;+ }+ masked(*mask, mv);+ for (d, k) in acc.iter_mut().zip(mv.iter()) {+ let mix = opacity * k.clamp(0.0, 1.0);+ if d[INKS] <= 0.0 || mix <= 0.0 {+ continue;+ }+ let mut ink = [d[0], d[1], d[2], d[3]];+ op.apply(&mut ink, self.depth);+ for (c, v) in ink.iter().enumerate() {+ d[c] += (v - d[c]) * mix;+ }+ }+ }+ }+ }+ }}/// The composite of `doc` over `rect` in `fmt`, worked out in ink values, or `None` when the/// document isn't CMYK or a visible layer needs the full compositor (see the module docs)./// `paper` flattens onto white paper (no ink) and makes the result opaque.pub fn flatten_cmyk(doc: &Document, rect: Rect, fmt: PixelFormat, paper: bool) -> Option<Surface> {- if doc.mode != ColorMode::Cmyk || fmt.mode != ColorMode::Cmyk || doc.layers.iter().any(|l| l.clipped) {+ if fmt.mode != ColorMode::Cmyk {return None;}- let mut stack = Vec::new();- for layer in doc.layers.iter().filter(|l| l.visible) {- let alpha = (layer.opacity * layer.fill_opacity).clamp(0.0, 1.0);- stack.push((plain(layer)?, alpha));- }+ let stack = InkStack::new(doc)?;let mut out = Surface::new(fmt);if rect.is_empty() {return Some(out);}let n = fmt.channels();- let w = rect.width() as usize;let rows = crate::band_rows_for(rect.width(), 0);- let (mut acc, mut src, mut data) = (Vec::new(), Vec::new(), Vec::new());+ let (mut acc, mut src, mut mv, mut data) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());let mut y = rect.y0;while y < rect.y1 {let band = Rect::new(rect.x0, y, rect.x1, y.saturating_add(rows).min(rect.y1));- // Straight C, M, Y, K, alpha per pixel, starting transparent.- acc.clear();- acc.resize(w * band.height() as usize, [0.0f32; INKS + 1]);- for &(surf, opacity) in &stack {- if opacity <= 0.0 || (surf.content_bounds().intersect(&band).is_empty() && surf.default_pixel().iter().all(|v| *v == 0.0)) {- continue;- }- let sf = surf.format();- let sn = sf.channels();- surf.read_region_into(band, &mut src);- for (d, s) in acc.iter_mut().zip(src.chunks_exact(sn)) {- let sa = if sf.alpha { s[INKS] } else { 1.0 } * opacity;- if sa <= 0.0 {- continue;- }- let oa = sa + d[INKS] * (1.0 - sa);- let keep = d[INKS] * (1.0 - sa);- for c in 0..INKS {- // An opaque pixel replaces what is below exactly (no rounding through the mix).- d[c] = if sa >= 1.0 { s[c] } else { (s[c] * sa + d[c] * keep) / oa };- }- d[INKS] = oa;- }- }+ stack.composite(band, &mut acc, &mut src, &mut mv);data.clear();data.resize(acc.len() * n, 0.0);for (p, o) in acc.iter().zip(data.chunks_exact_mut(n)) {@@ -99,3 +260,41 @@ pub fn flatten_cmyk(doc: &Document, rect: Rect, fmt: PixelFormat, paper: bool) -out.prune();Some(out)}++/// The display composite (straight RGBA, through the document's CMYK profile) of a CMYK document+/// whose stack has adjustment layers the inks carry exactly, worked out on the inks; `None` for+/// any other document, which the RGB compositor renders. Rows of `tile` render in parallel.+pub fn render_cmyk(doc: &Document, rect: Rect, tile: i32) -> Option<Buffer> {+ let stack = InkStack::new(doc).filter(InkStack::adjusts)?;+ let cmyk = crate::cmyk_space(doc);+ let w = rect.width() as usize;+ let mut out = Buffer::transparent(rect);+ if w == 0 || rect.is_empty() {+ return Some(out);+ }+ let rows = tile.max(1) as usize;+ let band = |i: usize, px: &mut [[f32; 4]]| {+ let y0 = rect.y0.saturating_add((i * rows) as i32);+ let r = Rect::new(rect.x0, y0, rect.x1, y0.saturating_add((px.len() / w) as i32));+ let (mut acc, mut src, mut mv) = (Vec::new(), Vec::new(), Vec::new());+ stack.composite(r, &mut acc, &mut src, &mut mv);+ photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || {+ for (o, p) in px.iter_mut().zip(&acc) {+ if p[INKS] > 0.0 {+ let [r, g, b] = photocraft_color::convert::cmyk_to_rgb([p[0], p[1], p[2], p[3]]);+ *o = [r, g, b, p[INKS]];+ }+ }+ });+ };+ #[cfg(not(target_arch = "wasm32"))]+ {+ use rayon::prelude::*;+ out.px.par_chunks_mut(w * rows).enumerate().for_each(|(i, px)| band(i, px));+ }+ #[cfg(target_arch = "wasm32")]+ for (i, px) in out.px.chunks_mut(w * rows).enumerate() {+ band(i, px);+ }+ Some(out)+}diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rsindex 75cbcce06..64c33e6c8 100644--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@ -606,6 +606,111 @@ fn a_16_bit_lab_invert_layer_keeps_greys_neutral() {assert!((lab[0] - 75.0).abs() < 0.1 && lab[1].abs() < 0.05 && lab[2].abs() < 0.05, "{lab:?}");}+/// A CMYK document of one opaque raster layer holding `ink` everywhere, at `depth`.+fn cmyk_doc(ink: [f32; 4], depth: SampleType) -> Document {+ let mut d = Document::new("c", Size::new(4, 4), ColorMode::Cmyk, depth);+ let mut l = Layer::raster("bg", d.pixel_format());+ l.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 4, 4), &[ink[0], ink[1], ink[2], ink[3], 1.0]);+ d.layers.push(l);+ d+}++/// Adjustment layers Photoshop evaluates on the inks composite on the document's own inks, not on+/// a separation of the RGB composite: exact for Invert, Posterize, Threshold, Brightness/Contrast+/// and CMYK Levels / Curves (photoshop corpus cmyk8 and cmyk16 oracles), through opacity and an+/// (unfeathered) mask as linear ink mixes.+#[test]+fn cmyk_ink_adjustments_composite_on_the_documents_inks() {+ use photocraft_color::convert::cmyk_to_rgb;+ let ink = [0.2, 0.4, 0.6, 0.1];+ let rgb = |i: [f32; 4]| {+ let c = cmyk_to_rgb(i);+ [c[0], c[1], c[2], 1.0]+ };+ for depth in [SampleType::U8, SampleType::U16] {+ let mut d = cmyk_doc(ink, depth);+ // Stored inks, as the document's surface rounds them.+ let stored: [f32; 4] = std::array::from_fn(|c| d.layers[0].surface().unwrap().pixel(0, 0)[c]);+ d.layers.push(Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert)));+ assert!(close4(px(&d, 1, 1), rgb(stored.map(|v| 1.0 - v))), "{depth:?} invert");+ // Half opacity and a half mask mix the inks linearly: a quarter of the way.+ d.layers[1].opacity = 0.5;+ let mut m = LayerMask::reveal_all();+ m.surface.fill_rect(Rect::new(0, 0, 4, 4), &[0.5]);+ d.layers[1].mask = Some(m);+ let k = 0.5 * d.layers[1].mask.as_ref().unwrap().value(1, 1);+ assert!(close4(px(&d, 1, 1), rgb(stored.map(|v| v + (1.0 - 2.0 * v) * k))), "{depth:?} mixed");+ // Brightness/Contrast curves each ink's stored value.+ let table = adjust::ink_brightness_contrast_lut(25.0, 30.0, true);+ d.layers[1] = Layer::new("bc", LayerContent::Adjustment(Adjustment::BrightnessContrast { brightness: 25.0, contrast: 30.0, legacy: true }));+ assert!(close4(px(&d, 1, 1), rgb(stored.map(|v| adjust::ink_through(&table, v)))), "{depth:?} brightness/contrast");+ // Flattening keeps the adjusted inks exactly, with no trip through RGB.+ let flat = flatten_to_surface(&d, d.pixel_format(), None);+ let got = flat.pixel(2, 2);+ for c in 0..4 {+ let want = adjust::ink_through(&table, stored[c]);+ let q = if depth == SampleType::U8 { 255.0 } else { 65535.0 };+ assert!((got[c] - want).abs() <= 0.5 / q + 1e-6, "{depth:?} flattened ink {c}: {} vs {want}", got[c]);+ }+ }+}++/// Only stacks with ink adjustments take the ink compositor for display: plain CMYK layers keep+/// the RGB compositor (which the GPU matches), and so does any stack with an adjustment the inks+/// don't carry or a layer they can't composite.+#[test]+fn only_cmyk_stacks_with_ink_adjustments_render_on_their_inks() {+ let r = Rect::new(0, 0, 4, 4);+ let mut d = cmyk_doc([0.2, 0.4, 0.6, 0.1], SampleType::U8);+ assert!(native::render_cmyk(&d, r, 64).is_none(), "plain layers");+ d.layers.push(Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert)));+ assert!(native::render_cmyk(&d, r, 64).is_some());+ let hue = Adjustment::HueSaturation { hue: 30.0, saturation: 0.0, lightness: 0.0, colorize: false, ranges: photocraft_doc::adjust::HueRange::defaults() };+ d.layers.push(Layer::new("hue", LayerContent::Adjustment(hue)));+ assert!(native::render_cmyk(&d, r, 64).is_none(), "an adjustment the inks don't carry");+ d.layers.pop();+ d.layers[1].blend = BlendMode::Multiply;+ assert!(native::render_cmyk(&d, r, 64).is_none(), "a blend mode");+ d.layers[1].blend = BlendMode::Normal;+ let mut rgb = cmyk_doc([0.2, 0.4, 0.6, 0.1], SampleType::U8);+ rgb.mode = ColorMode::Rgb;+ rgb.layers.push(Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert)));+ assert!(native::render_cmyk(&rgb, r, 64).is_none(), "not a CMYK document");+ // Tiles render alike whatever their size.+ let whole = render_tiled(&d, d.bounds(), 64);+ assert_eq!(render_tiled(&d, d.bounds(), 1).px, whole.px);+}++/// Groups at full opacity without a mask are inlined: a pass-through group's adjustment reaches+/// the layers below it, and an isolated group of raster layers composites as its children would.+/// An isolated group's adjustment (which only sees the group) or a translucent group keeps the+/// RGB compositor.+#[test]+fn cmyk_ink_compositing_inlines_open_groups() {+ use photocraft_color::convert::cmyk_to_rgb;+ let r = Rect::new(0, 0, 4, 4);+ let mut d = cmyk_doc([0.2, 0.4, 0.6, 0.1], SampleType::U16);+ let stored: [f32; 4] = std::array::from_fn(|c| d.layers[0].surface().unwrap().pixel(0, 0)[c]);+ let mut g = Layer::group("g", vec![Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert))]);+ g.blend = BlendMode::PassThrough;+ d.layers.push(g);+ let c = cmyk_to_rgb(stored.map(|v| 1.0 - v));+ assert!(close4(px(&d, 1, 1), [c[0], c[1], c[2], 1.0]), "a pass-through group's Invert reaches the inks below");+ d.layers[1].blend = BlendMode::Normal;+ assert!(native::render_cmyk(&d, r, 64).is_none(), "an isolated group's adjustment");+ d.layers[1].blend = BlendMode::PassThrough;+ d.layers[1].opacity = 0.5;+ assert!(native::render_cmyk(&d, r, 64).is_none(), "a translucent group");+ // An isolated group of raster layers, with an adjustment above it, still composites on the inks.+ let mut top = Layer::raster("top", d.pixel_format());+ top.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 2, 4), &[0.9, 0.0, 0.0, 0.0, 1.0]);+ d.layers[1] = Layer::group("raster", vec![top]);+ d.layers.push(Layer::new("inv", LayerContent::Adjustment(Adjustment::Invert)));+ assert!(native::render_cmyk(&d, r, 64).is_some());+ let c = cmyk_to_rgb(stored.map(|v| 1.0 - v));+ assert!(close4(px(&d, 3, 1), [c[0], c[1], c[2], 1.0]), "outside the group's layer");+}+#[test]fn cmyk_document_renders_via_rgb() {let mut d = Document::new("c", Size::new(2, 2), ColorMode::Cmyk, SampleType::U8);@@ -2986,6 +3091,29 @@ fn modern_lut_timing() {println!("modern_lut(-50, 30): {:?} each", t.elapsed() / 100);}+#[test]+#[ignore = "timing: cargo test --release -p photocraft-compose cmyk_ink_render_timing -- --ignored --nocapture"]+fn cmyk_ink_render_timing() {+ // 24 MP CMYK8 photo-sized noise with one adjustment layer: the ink path (Invert) against the+ // RGB compositor (Exposure, which the inks don't carry).+ let (w, h) = (6000, 4000);+ let mut d = Document::new("c", Size::new(w, h), ColorMode::Cmyk, SampleType::U8);+ let mut l = Layer::raster("bg", d.pixel_format());+ let data: Vec<f32> = (0..(w * h) as usize)+ .flat_map(|i| [(i % 251) as f32 / 255.0, (i % 241) as f32 / 255.0, (i % 239) as f32 / 255.0, (i % 97) as f32 / 255.0, 1.0])+ .collect();+ l.surface_mut().unwrap().write_region(Rect::new(0, 0, w as i32, h as i32), &data);+ d.layers.push(l);+ for adj in [Adjustment::Invert, Adjustment::Exposure { exposure: 0.5, offset: 0.0, gamma: 1.0 }] {+ d.layers.truncate(1);+ d.layers.push(Layer::new("adj", LayerContent::Adjustment(adj.clone())));+ let _ = render(&d, Rect::new(0, 0, 512, 512));+ let t = std::time::Instant::now();+ let b = render(&d, d.bounds());+ println!("{}: {:?} ({} px)", adj.label(), t.elapsed(), b.px.len());+ }+}+// A pass-through group with an adjustment layer reaches the layers beneath, unless the group is// the base of a clipping group: then Photoshop renders it isolated, and an adjustment with no// content of its own in the group changes nothing (psd-tools passthrough_clipping_mask_adjustment).diff --git a/crates/io/tests/corpus.rs b/crates/io/tests/corpus.rsindex ffd80797c..e08fbc5ef 100644--- a/crates/io/tests/corpus.rs+++ b/crates/io/tests/corpus.rs@@ -152,11 +152,11 @@ const MIXED: Source = Source { label: "io corpus", dir: "corpus/psd", group_dept/// The full psd-tools test set (309 files at the pinned commit; see `xtask/psd-tools-corpus.sha256`):/// 226 vs the merged image + 10 vs the thumbnail (Advanced Blending knockouts: +7).-const PSD_TOOLS: Source = Source { label: "psd-tools corpus", dir: "corpus/psd-tools", group_depth: 0, pass_floor: 241, roundtrip_floor: 308 };+const PSD_TOOLS: Source = Source { label: "psd-tools corpus", dir: "corpus/psd-tools", group_depth: 0, pass_floor: 242, roundtrip_floor: 308 };/// Our Photoshop-authored oracles (256 files; https://github.com/storytold/photocraft-corpus),/// grouped by feature (`smart-filters`, `effects`, `text`, `adjustments/<mode><bits>`).-const PHOTOSHOP: Source = Source { label: "photoshop oracles", dir: "corpus/photoshop", group_depth: 2, pass_floor: 152, roundtrip_floor: 258 };+const PHOTOSHOP: Source = Source { label: "photoshop oracles", dir: "corpus/photoshop", group_depth: 2, pass_floor: 165, roundtrip_floor: 258 };/// The corpus directory; a missing corpus fails the test.fn locate(src: &Source) -> PathBuf {diff --git a/docs/file-format-parity.md b/docs/file-format-parity.mdindex 69cbba163..c960e2e1b 100644--- a/docs/file-format-parity.md+++ b/docs/file-format-parity.md@@ -1,6 +1,6 @@# File-format parity-> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-13 · **Change:** minor (CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026+> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-10-13 · **Change:** minor (CMYK Posterize on the stored values, psd-tools oracle floor 242/309; CMYK adjustment layers composite on the document's inks; Photoshop-oracle floor 165/258; CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; modern Brightness/Contrast's brightness curve; Photoshop-oracle floor 151/258; Lab documents composite on their stored L, a, b; Photoshop-oracle floor 152/258; Levels on whole levels at every step with Photoshop's shadow toe; Photoshop-oracle floor 146/258, psd-tools 238/309; 32-bit adjustments unclipped; Photoshop-oracle floor 149/258; mask feathers blur with their exact variance; Threshold splits on Photoshop's luminosity; a pass-through clipping base with an adjustment renders isolated; psd-tools oracle floor 240/309; 16-bit Posterize as Photoshop bins it; psd-tools oracle floor 241/309; Gradient Map luminosity; Photoshop-oracle floor 147/258; PSD: `Mt16`/`Mt32` merged transparency read; palette PNGs open in Indexed Color mode, #4804; earlier: CMYK Invert, Posterize and Threshold on the inks; 16-bit Lab Invert; Photoshop-oracle floor 145/258; `.atn` import maps 112 events; DDS textures open, #1327; DPX read and write, #1049; #2465 fixed: CS2 placed layers with only a `PlLd` block open their contents; Photoshop Actions `.atn` read and write; `.shc` contour files read and write; earlier the same day: indexed BMP palette mode; Save keeps a JPEG's quality and a WebP's encoding) · **Target:** Adobe Photoshop 2026Every format Photoshop 2026 (27.11.0) reads or writes, with PhotoCraft's support, fidelity andtests. Photoshop's list comes from its `Info.plist` `CFBundleDocumentTypes`, the PiPL read/write@@ -142,6 +142,8 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings.| Date | Change | Summary ||---|---|---|+| 2026-10-13 | minor | CMYK Posterize works on the stored values (1 − ink), as Photoshop does: psd-tools posterize_cmyk passes (13.8 % → 0 of pixels off on the ink path); psd-tools floor → 242 of 309 |+| 2026-10-13 | minor | CMYK documents whose layers are plain raster layers plus Invert, Posterize, Threshold, Brightness/Contrast, Levels or Curves layers composite on their own inks for display, export and flattening: the cmyk8/16 oracles for those seven adjustments pass; Photoshop-oracle floor 151 → 165 of 258 || 2026-10-13 | minor | CMYK Threshold compares the Rec. 601 luma of the inks' plain complement, as Photoshop does (every pixel of cmyk8/16 threshold-128.psd); oracle bad pixels 1.6% → 0.2% || 2026-10-13 | minor | CMYK Brightness/Contrast (modern and legacy) curves each ink's stored value (1 − ink), exact on destructive edits; cmyk8/16 oracle bad pixels 71% → 48–57% (the RGB composite's separation still differs) || 2026-10-13 | minor | Modern Brightness/Contrast: the brightness curve refit to Photoshop, so the rgb and gray 8/16/32 brightness-contrast oracles pass; Photoshop-oracle floor 145 → 151 of 258 |diff --git a/docs/gaps.md b/docs/gaps.mdindex 0be2319ed..7c6722e60 100644--- a/docs/gaps.md+++ b/docs/gaps.md@@ -1,6 +1,6 @@# Where PhotoCraft falls short of Photoshop-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed) · **Target:** Adobe Photoshop 2026Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impacton the way to beta. This is the work list agents pick from: take the highest-ranked entry that@@ -262,6 +262,8 @@ what an agent can't finish alone.| Date | Change | Summary ||---|---|---|+| 2026-10-13 | minor | G1: CMYK Posterize works on the stored values (1 − ink); psd-tools posterize_cmyk passes; psd-tools floor → 242 of 309 |+| 2026-10-13 | minor | G1: CMYK stacks with Invert, Posterize, Threshold, Brightness/Contrast, Levels or Curves layers composite on the document's own inks (14 CMYK oracles pass); Photoshop-oracle floor 151 → 165 of 258 || 2026-10-13 | minor | CMYK Threshold compares the Rec. 601 luma of the inks' plain complement, as Photoshop does (every pixel of cmyk8/16 threshold-128.psd); oracle bad pixels 1.6% → 0.2% || 2026-10-13 | minor | G1: CMYK Brightness/Contrast (modern and legacy) curves each ink's stored value as Photoshop does; oracle bad pixels 71% → 48–57%, floor unchanged || 2026-10-13 | minor | G1: modern Brightness/Contrast's brightness curve refit to Photoshop (six oracles pass); Photoshop-oracle floor 145 → 151 of 258 |diff --git a/docs/scorecard.md b/docs/scorecard.mdindex 5d3a99304..d88548f30 100644--- a/docs/scorecard.md+++ b/docs/scorecard.md@@ -7,7 +7,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js| Area | Done | Partial | Missing | Key numbers ||---|---:|---:|---:|---|| [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) |-| [File compatibility](#file-compatibility) | 7 | 13 | 7 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 241/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 152/256, round trip ≥ 258/256 |+| [File compatibility](#file-compatibility) | 7 | 13 | 7 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 242/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 165/256, round trip ≥ 258/256 || [Tools](#tools) | 32 | 11 | 0 | || [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 161 (target 0) || [Type](#type) | 4 | 3 | 2 | |@@ -93,8 +93,8 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t| Corpus | Directory | Files | Oracle pass floor | Round-trip floor ||---|---|---:|---:|---:|| io corpus | `corpus/psd` | 170 | 146 | 169 |-| psd-tools corpus | `corpus/psd-tools` | 309 | 241 | 308 |-| photoshop oracles | `corpus/photoshop` | 256 | 152 | 258 |+| psd-tools corpus | `corpus/psd-tools` | 309 | 242 | 308 |+| photoshop oracles | `corpus/photoshop` | 256 | 165 | 258 || Id | Target | Status | Issue | Note ||---|---|---|---|---|