diff --git a/crates/algo/src/gradient_cmyk_ink_blend_tests.rs b/crates/algo/src/gradient_cmyk_ink_blend_tests.rs new file mode 100644 index 0000000000..7a9f51b60b --- /dev/null +++ b/crates/algo/src/gradient_cmyk_ink_blend_tests.rs @@ -0,0 +1,175 @@ +//! #18662: in CMYK the Gradient tool blends on the inks (`v = 1 − ink`, all four channels), not +//! through RGB and a new separation. + +use photocraft_color::blend::{blend_channel, blend_rgb}; +use photocraft_color::{ColorMode, PixelFormat, SampleType}; +use photocraft_raster::Surface; + +use super::{BlendMode, FillMode, GradientShape, Rect, paint_gradient}; + +const W: i32 = 48; + +/// Base inks, one row each: red, grey, a warm colour, a green, rich black, white paper. +const BASES: [[f32; 4]; 6] = [[0.0, 1.0, 1.0, 0.0], [0.4, 0.3, 0.3, 0.1], [0.1, 0.55, 0.8, 0.05], [0.75, 0.1, 0.65, 0.2], [0.7, 0.6, 0.5, 0.9], [0.0; 4]]; + +fn format(sample: SampleType) -> PixelFormat { + PixelFormat { mode: ColorMode::Cmyk, sample, alpha: true } +} + +fn gradient(s: &mut Surface, mode: BlendMode, locked: bool) { + let a = [30.0 / 255.0, 120.0 / 255.0, 220.0 / 255.0, 1.0]; + let b = [240.0 / 255.0, 200.0 / 255.0, 40.0 / 255.0, 1.0]; + let rows = BASES.len() as i32; + paint_gradient( + s, + Rect::new(0, 0, W, rows), + (0.0, 0.0), + (W as f32, 0.0), + GradientShape::Linear, + &[(0.0, a), (1.0, b)], + false, + 1.0, + FillMode::Blend(mode), + false, + None, + locked, + ); +} + +fn base(sample: SampleType, alpha: f32) -> Surface { + let mut s = Surface::new(format(sample)); + for (y, inks) in BASES.iter().enumerate() { + s.fill_rect(Rect::new(0, y as i32, W, y as i32 + 1), &[inks[0], inks[1], inks[2], inks[3], alpha]); + } + s +} + +/// The gradient's own inks: the same gradient laid in Normal on transparency. +fn source(sample: SampleType) -> Surface { + let mut s = Surface::new(format(sample)); + gradient(&mut s, BlendMode::Normal, false); + s +} + +fn inks(s: &Surface, x: i32, y: i32) -> [f32; 4] { + let p = s.pixel(x, y); + [p[0], p[1], p[2], p[3]] +} + +fn v(inks: [f32; 4]) -> [f32; 4] { + inks.map(|i| 1.0 - i) +} + +fn tolerance(sample: SampleType) -> f32 { + if sample == SampleType::U8 { 0.01 } else { 1e-4 } +} + +/// Runs `mode` over every base row in 8 and 16 bit and checks each pixel's inks against +/// `expected(base v, source v)` (in `v`). +fn check(mode: BlendMode, expected: impl Fn([f32; 4], [f32; 4]) -> [f32; 4]) { + for sample in [SampleType::U8, SampleType::U16] { + let src = source(sample); + let before = base(sample, 1.0); + let mut out = before.clone(); + gradient(&mut out, mode, false); + for y in 0..BASES.len() as i32 { + for x in 0..W { + let want = expected(v(inks(&before, x, y)), v(inks(&src, x, y))).map(|c| 1.0 - c.clamp(0.0, 1.0)); + let got = inks(&out, x, y); + for c in 0..4 { + assert!((got[c] - want[c]).abs() <= tolerance(sample), "{mode:?} {sample:?} at ({x}, {y}) channel {c}: {got:?}, want {want:?}"); + } + assert_eq!(out.pixel(x, y)[4], 1.0); + } + } + } +} + +#[test] +fn separable_modes_use_the_rgb_formula_on_each_ink() { + use BlendMode::*; + for mode in [ + Darken, + Multiply, + ColorBurn, + LinearBurn, + Lighten, + Screen, + ColorDodge, + LinearDodge, + Overlay, + SoftLight, + HardLight, + VividLight, + LinearLight, + PinLight, + Difference, + Exclusion, + Subtract, + Divide, + ] { + check(mode, |b, s| std::array::from_fn(|i| blend_channel(mode, b[i], s[i]))); + } + check(HardMix, |b, s| std::array::from_fn(|i| if b[i] + s[i] > 1.0 + 1e-6 { 1.0 } else { 0.0 })); +} + +#[test] +fn hue_saturation_and_color_keep_the_base_k_and_luminosity_takes_the_source_k() { + let cmy = |c: [f32; 4]| [c[0], c[1], c[2]]; + for mode in [BlendMode::Hue, BlendMode::Saturation, BlendMode::Color, BlendMode::Luminosity] { + check(mode, |b, s| { + let out = blend_rgb(mode, cmy(b), cmy(s)); + let k = if mode == BlendMode::Luminosity { s[3] } else { b[3] }; + [out[0], out[1], out[2], k] + }); + } +} + +#[test] +fn darker_and_lighter_color_pick_the_whole_pixel_by_ink_luminosity() { + let lum = |c: [f32; 4]| (0.30 * c[0] + 0.59 * c[1] + 0.11 * c[2]) * c[3]; + check(BlendMode::DarkerColor, |b, s| if lum(s) < lum(b) { s } else { b }); + check(BlendMode::LighterColor, |b, s| if lum(s) > lum(b) { s } else { b }); +} + +#[test] +fn hard_mix_tie_gives_full_ink_in_16_bit() { + let sample = SampleType::U16; + let src = source(sample); + // Each base pixel is the exact complement of the gradient's inks there: b + s is full in v. + let mut out = Surface::new(format(sample)); + for x in 0..W { + let s = inks(&src, x, 0); + out.write_pixel(x, 0, &[1.0 - s[0], 1.0 - s[1], 1.0 - s[2], 1.0 - s[3], 1.0]); + } + gradient(&mut out, BlendMode::HardMix, false); + for x in 0..W { + assert_eq!(inks(&out, x, 0), [1.0; 4], "at x {x}"); + } +} + +/// Source-over: `(1 − αb) · s + αb · B(b, s)` in v and an opaque result; with Lock Transparent +/// Pixels the colour is `B(b, s)` and the alpha stays. +#[test] +fn half_transparent_base_mixes_the_source_and_the_blend_in_v() { + let sample = SampleType::U16; + let ab = 0.5; + let src = source(sample); + for locked in [false, true] { + let before = base(sample, ab); + let mut out = before.clone(); + gradient(&mut out, BlendMode::Multiply, locked); + let weight = if locked { 1.0 } else { ab }; + for y in 0..BASES.len() as i32 { + for x in 0..W { + let (b, s) = (v(inks(&before, x, y)), v(inks(&src, x, y))); + let want: [f32; 4] = std::array::from_fn(|i| 1.0 - ((1.0 - weight) * s[i] + weight * b[i] * s[i])); + let got = inks(&out, x, y); + for c in 0..4 { + assert!((got[c] - want[c]).abs() <= 1e-4, "locked {locked} at ({x}, {y}) channel {c}: {got:?}, want {want:?}"); + } + assert_eq!(out.pixel(x, y)[4], if locked { before.pixel(x, y)[4] } else { 1.0 }); + } + } + } +} diff --git a/crates/algo/src/paint.rs b/crates/algo/src/paint.rs index d603fe594a..1891c0b08b 100644 --- a/crates/algo/src/paint.rs +++ b/crates/algo/src/paint.rs @@ -71,6 +71,8 @@ pub fn sample_stops(stops: &[(f32, [f32; 4])], t: f32) -> [f32; 4] { /// zero, `rim(x, y)` (when given) is the strength of a bucket's transparent-seed fringe there: the /// pixel takes the fill at coverage `rim × (1 − α)`, its own transparency (#11354 review; see /// [`bucket_fill_inks`]). Lock Transparent Pixels and Clear ignore it. +/// With `on_inks`, a CMYK target blends the modes [`blend::blends_inks`] lists on its inks +/// ([`blend::composite_inks`]) instead of through RGB (the Gradient tool, #18662). #[allow(clippy::too_many_arguments)] fn composite_area( s: &mut Surface, @@ -82,11 +84,17 @@ fn composite_area( lock_transparency: bool, inks: Option<[f32; 4]>, rim: Option<&(dyn Fn(i32, i32) -> f32 + Sync)>, + on_inks: bool, ) { // Composite tile by tile (in parallel on native); tiles with zero coverage are left untouched, // so their copy-on-write storage (and GPU residency) survives. let fmt = s.format(); let n = fmt.channels(); + let levels = match fmt.sample { + photocraft_color::SampleType::U8 => Some(255.0), + photocraft_color::SampleType::U16 => Some(65535.0), + _ => None, + }; let tiles: Vec = area.tiles().map(|tc| tc.rect().intersect(&area)).filter(|r| !r.is_empty()).collect(); let src: &Surface = s; let work = |r: &Rect| -> Option<(Rect, Vec)> { @@ -123,6 +131,23 @@ fn composite_area( if mode == FillMode::Behind && (lock_transparency || d[3] >= 1.0) { continue; } + // 32-bit CMYK is not measured, so it keeps the RGB path; on 8 and 16 bit the + // source is blended as stored samples, so Hard Mix ties are exact. + if let FillMode::Blend(m) = mode + && on_inks + && let Some(l) = levels + && blend::blends_inks(m) + { + let src = color(x, y); + from_rgba_into(&fmt, src, &mut enc); + let source = [enc[0], enc[1], enc[2], enc[3]].map(|v| (v.clamp(0.0, 1.0) * l).round() / l); + let (out, alpha) = blend::composite_inks(m, [px[0], px[1], px[2], px[3]], d[3], source, src[3] * k, lock_transparency); + px[..4].copy_from_slice(&out); + if fmt.alpha { + px[4] = alpha; + } + continue; + } let o = match mode { FillMode::Blend(m) => blend_pixel(m, d, color(x, y), k, lock_transparency), // Locked transparency keeps the alpha, so Clear leaves the pixel as it is. @@ -230,6 +255,7 @@ pub fn paint_gradient( lock_transparency, None, None, + fmt.mode == photocraft_color::ColorMode::Cmyk, ); } @@ -391,7 +417,7 @@ fn fill_region( if hit == Some(&true) { strength(x, y) } else { 0.0 } }; let rim: Option<&(dyn Fn(i32, i32) -> f32 + Sync)> = if use_rim { Some(&on_ring) } else { None }; - composite_area(s, b, mode, |x, y| region.at(x, y) * strength(x, y), src, composite_blend, lock_transparency, inks, rim); + composite_area(s, b, mode, |x, y| region.at(x, y) * strength(x, y), src, composite_blend, lock_transparency, inks, rim, false); } /// Over `region.bbox` (row-major): the pixels the region leaves uncovered that touch one of its @@ -425,6 +451,10 @@ mod gradient_hard_mix_tie_tests; #[path = "gradient_hard_mix_rounded_source_tests.rs"] mod gradient_hard_mix_rounded_source_tests; +#[cfg(test)] +#[path = "gradient_cmyk_ink_blend_tests.rs"] +mod gradient_cmyk_ink_blend_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/color/src/blend.rs b/crates/color/src/blend.rs index 43861a5c21..ac3ff28323 100644 --- a/crates/color/src/blend.rs +++ b/crates/color/src/blend.rs @@ -684,6 +684,84 @@ pub fn composite_atop(mode: BlendMode, backdrop: [f32; 4], source: [f32; 4], opa out } +/// Whether CMYK paint blends `mode` on the inks themselves ([`blend_inks`]): the modes measured +/// there (#18662). Normal, Dissolve and the rest keep the RGB path. +pub fn blends_inks(mode: BlendMode) -> bool { + use BlendMode::*; + matches!( + mode, + Darken + | Multiply + | ColorBurn + | LinearBurn + | Lighten + | Screen + | ColorDodge + | LinearDodge + | Overlay + | SoftLight + | HardLight + | VividLight + | LinearLight + | PinLight + | HardMix + | Difference + | Exclusion + | Subtract + | Divide + | Hue + | Saturation + | Color + | Luminosity + | DarkerColor + | LighterColor + ) +} + +/// `B(Cb, Cs)` on CMYK inks, each given as `v = 1 − ink` (C, M, Y, K): the separable modes apply +/// their RGB formula to all four channels; Hue, Saturation and Color work on C, M, Y and keep the +/// backdrop's K, Luminosity keeps the source's K; Darker and Lighter Color pick the whole pixel by +/// `lum(C, M, Y) × K`. Hard Mix gives full ink (0) where `cb + cs` is exactly 1, measured, also +/// at the ends (paper under full ink), where the RGB formula gives white. +pub fn blend_inks(mode: BlendMode, cb: [f32; 4], cs: [f32; 4]) -> [f32; 4] { + let cmy = |c: [f32; 4]| [c[0], c[1], c[2]]; + let with_k = |c: [f32; 3], k: f32| [c[0], c[1], c[2], k]; + let out = match mode { + BlendMode::Hue | BlendMode::Saturation | BlendMode::Color => with_k(blend_rgb(mode, cmy(cb), cmy(cs)), cb[3]), + BlendMode::Luminosity => with_k(blend_rgb(mode, cmy(cb), cmy(cs)), cs[3]), + BlendMode::DarkerColor | BlendMode::LighterColor => { + let (b, s) = (lum(cmy(cb)) * cb[3], lum(cmy(cs)) * cs[3]); + let source = if mode == BlendMode::DarkerColor { s < b } else { s > b }; + if source { cs } else { cb } + } + // Callers pass 8- or 16-bit whole levels only, so a tie is exact up to f32 rounding. + BlendMode::HardMix => std::array::from_fn(|i| if cb[i] + cs[i] > 1.0 + 1e-6 { 1.0 } else { 0.0 }), + m => std::array::from_fn(|i| blend_channel(m, cb[i], cs[i])), + }; + out.map(|v| v.clamp(0.0, 1.0)) +} + +/// [`composite`] (or [`composite_atop`] when `atop`) on CMYK inks (0 = none, 1 = full), blended +/// with [`blend_inks`] in `v = 1 − ink`. `ab` is the backdrop's alpha and `as_` the source's +/// alpha times its coverage. Returns the inks and the alpha. +pub fn composite_inks(mode: BlendMode, backdrop: [f32; 4], ab: f32, source: [f32; 4], as_: f32, atop: bool) -> ([f32; 4], f32) { + if as_ <= 0.0 { + return (backdrop, ab); + } + let (cb, cs) = (backdrop.map(|v| 1.0 - v), source.map(|v| 1.0 - v)); + let b = blend_inks(mode, cb, cs); + let (v, alpha): ([f32; 4], f32) = if atop { + (std::array::from_fn(|i| (1.0 - as_) * cb[i] + as_ * b[i]), ab) + } else { + let ao = as_ + ab * (1.0 - as_); + if ao <= 0.0 { + return ([0.0; 4], 0.0); + } + (std::array::from_fn(|i| ((1.0 - as_) * ab * cb[i] + (1.0 - ab) * as_ * cs[i] + as_ * ab * b[i]) / ao), ao) + }; + (v.map(|v| (1.0 - v).clamp(0.0, 1.0)), alpha) +} + #[cfg(test)] mod tests;