diff --git a/crates/color/src/blend.rs b/crates/color/src/blend.rs index 5cf5fbd691..508c26977e 100644 --- a/crates/color/src/blend.rs +++ b/crates/color/src/blend.rs @@ -1,7 +1,7 @@ //! Photoshop and Paint.NET blend modes (scalar reference implementation). //! //! Formulas follow the public PDF / ISO 32000-2 and W3C Compositing definitions, -//! with Photoshop's variants where they differ (Soft Light, Hard Mix, Darker/Lighter Color, +//! with Photoshop's variants where they differ (Hard Mix, Darker/Lighter Color, //! Linear Burn/Dodge, Vivid/Linear/Pin Light, Subtract, Divide). This is the CPU reference //! that the GPU kernels must match. @@ -323,10 +323,19 @@ fn hard_light(cb: f32, cs: f32) -> f32 { } } -/// Photoshop's Soft Light (differs from the W3C/PDF definition in the upper half). +/// Photoshop's Soft Light: the W3C/PDF curve. In the upper half (`cs > 0.5`) the backdrop moves +/// towards `D(cb)`, which is `sqrt(cb)` above a quarter and the cubic `((16·cb − 12)·cb + 4)·cb` +/// below it; with `sqrt` throughout, dark backdrops came out up to 20 levels too light (#8804, +/// measured on psd-tools `blend-modes/rgb-blend-modes.psd`). #[inline] fn soft_light_ps(cb: f32, cs: f32) -> f32 { - if cs <= 0.5 { 2.0 * cb * cs + cb * cb * (1.0 - 2.0 * cs) } else { 2.0 * cb * (1.0 - cs) + cb.max(0.0).sqrt() * (2.0 * cs - 1.0) } + if cs <= 0.5 { + 2.0 * cb * cs + cb * cb * (1.0 - 2.0 * cs) + } else { + let b = cb.max(0.0); + let d = if b <= 0.25 { ((16.0 * b - 12.0) * b + 4.0) * b } else { b.sqrt() }; + 2.0 * cb * (1.0 - cs) + d * (2.0 * cs - 1.0) + } } // ---- non-separable helpers (W3C Compositing Level 1) ---- @@ -572,6 +581,37 @@ mod tests { assert!(close(blend_channel(BlendMode::HardMix, 0.6, 0.3), 0.0)); } + /// #8804: Photoshop's Soft Light over a dark backdrop (cb ≤ 0.25, cs > 0.5) follows the W3C + /// curve `D(cb) = ((16·cb − 12)·cb + 4)·cb`, not `sqrt(cb)`. Measured on psd-tools + /// `blend-modes/rgb-blend-modes.psd` (Photoshop's merged image), in 8-bit levels: + /// (backdrop, source, Photoshop). + #[test] + fn soft_light_follows_photoshop_over_dark_backdrops() { + for (cb, cs, ps) in [(4u8, 247u8, 11.0f32), (6, 254, 19.0), (9, 252, 25.0), (10, 237, 32.0), (14, 253, 46.0)] { + let got = blend_channel(BlendMode::SoftLight, f32::from(cb) / 255.0, f32::from(cs) / 255.0) * 255.0; + assert!((got - ps).abs() <= 7.0, "cb {cb} cs {cs}: {got} vs Photoshop {ps}"); + } + } + + #[test] + fn soft_light_is_the_w3c_formula() { + let d = |cb: f32| if cb <= 0.25 { ((16.0 * cb - 12.0) * cb + 4.0) * cb } else { cb.sqrt() }; + let w3c = |cb: f32, cs: f32| if cs <= 0.5 { cb - (1.0 - 2.0 * cs) * cb * (1.0 - cb) } else { cb + (2.0 * cs - 1.0) * (d(cb) - cb) }; + for b in (0..=255u8).step_by(3) { + for s in (0..=255u8).step_by(5) { + let (cb, cs) = (f32::from(b) / 255.0, f32::from(s) / 255.0); + let got = blend_channel(BlendMode::SoftLight, cb, cs); + assert!((got - w3c(cb, cs)).abs() < 1e-5, "cb {b} cs {s}: {got} vs {}", w3c(cb, cs)); + } + } + // Continuous where the two halves of D meet (both give 0.5 at cb = 0.25). + let below = blend_channel(BlendMode::SoftLight, 0.25, 1.0); + let above = blend_channel(BlendMode::SoftLight, 0.25 + 1e-6, 1.0); + assert!(close(below, 0.5) && (above - below).abs() < 1e-4, "{below} {above}"); + // A negative backdrop (32-bit documents) counts as black under a light source, as before. + assert!(close(blend_channel(BlendMode::SoftLight, -0.1, 1.0), 0.0)); + } + #[test] fn vivid_light_source_extremes_and_interior_values() { for cb in [0.0, 0.25, 0.5, 0.75, 1.0] { diff --git a/crates/compose/src/advanced_tests.rs b/crates/compose/src/advanced_tests.rs index 22f374af6e..a0fdf52cb0 100644 --- a/crates/compose/src/advanced_tests.rs +++ b/crates/compose/src/advanced_tests.rs @@ -270,10 +270,12 @@ fn interior_effects_blend_over_the_layer_mode_unless_grouped() { fn interior_effects_blend_with_the_backdrop_through_a_see_through_normal_layer() { // #6232: #04170F under a Normal layer at fill 0 with a yellow Soft Light colour overlay. The // overlay soft-lights the dark green it sees through the layer (Photoshop's soft light of - // yellow: sqrt(b) for red and green, b² for blue), not transparency, which would leave plain - // yellow. A half-transparent part of the layer mixes it in at half strength. + // yellow: the W3C D(b) for red and green, which is the cubic ((16b − 12)b + 4)b below a + // quarter (#8804), and b² for blue), not transparency, which would leave plain yellow. A + // half-transparent part of the layer mixes it in at half strength. let bg: [f32; 3] = [4.0 / 255.0, 23.0 / 255.0, 15.0 / 255.0]; - let lit = [bg[0].sqrt(), bg[1].sqrt(), bg[2] * bg[2]]; + let dark = |b: f32| ((16.0 * b - 12.0) * b + 4.0) * b; + let lit = [dark(bg[0]), dark(bg[1]), bg[2] * bg[2]]; let half = |c: usize| (bg[c] + lit[c]) / 2.0; for depth in DEPTHS { let mut d = doc(depth, false); diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgsl index a6c0c63579..c10f27d4f2 100644 --- a/crates/gpu/src/compose.wgsl +++ b/crates/gpu/src/compose.wgsl @@ -139,9 +139,13 @@ fn hard_light(cb: f32, cs: f32) -> f32 { let s = 2.0 * cs - 1.0; return cb + s - cb * s; } +// The W3C curve, as Photoshop: D(cb) is the cubic below a quarter, sqrt above it (#8804). fn soft_light_ps(cb: f32, cs: f32) -> f32 { if (cs <= 0.5) { return 2.0 * cb * cs + cb * cb * (1.0 - 2.0 * cs); } - return 2.0 * cb * (1.0 - cs) + sqrt(max(cb, 0.0)) * (2.0 * cs - 1.0); + let b = max(cb, 0.0); + var d = sqrt(b); + if (b <= 0.25) { d = ((16.0 * b - 12.0) * b + 4.0) * b; } + return 2.0 * cb * (1.0 - cs) + d * (2.0 * cs - 1.0); } fn vivid_light_ps(cb: f32, cs: f32) -> f32 { if (cs <= 0.5) { diff --git a/crates/io/src/ora.rs b/crates/io/src/ora.rs index 6d1bcfd87f..916ac839a2 100644 --- a/crates/io/src/ora.rs +++ b/crates/io/src/ora.rs @@ -77,9 +77,9 @@ pub(crate) fn krita_blend(id: &str) -> Option<(BlendMode, bool)> { "dodge" => (B::ColorDodge, false), "burn" => (B::ColorBurn, false), "hard_light" => (B::HardLight, false), - "soft_light" => (B::SoftLight, false), - // The W3C soft light curve, close to but not Photoshop's. - "soft_light_svg" => (B::SoftLight, true), + // Krita's own Soft Light keeps sqrt(cb) over dark backdrops; Photoshop's is the W3C curve. + "soft_light" => (B::SoftLight, true), + "soft_light_svg" => (B::SoftLight, false), "diff" => (B::Difference, false), "exclusion" => (B::Exclusion, false), "linear_burn" => (B::LinearBurn, false), @@ -124,7 +124,7 @@ pub(crate) fn krita_id(mode: BlendMode) -> Option<&'static str> { B::LinearDodge => "linear_dodge", B::LighterColor => "lighter color", B::Overlay => "overlay", - B::SoftLight => "soft_light", + B::SoftLight => "soft_light_svg", B::HardLight => "hard_light", B::VividLight => "vivid_light", B::LinearLight => "linear light", @@ -167,9 +167,6 @@ const SVG_OPS: [(&str, BlendMode); 15] = [ /// A composite-op attribute as a blend mode; unknown names fall back to Normal with a warning. fn composite_op(op: &str, layer: &str, warnings: &mut Warnings) -> BlendMode { if let Some((_, mode)) = SVG_OPS.iter().find(|(name, _)| *name == op) { - if op == "svg:soft-light" { - warnings.note("svg:soft-light (the W3C curve) opens as Photoshop's Soft Light, which differs slightly"); - } return *mode; } match op { diff --git a/crates/io/src/ora/tests.rs b/crates/io/src/ora/tests.rs index c7c253ef29..922135a42e 100644 --- a/crates/io/src/ora/tests.rs +++ b/crates/io/src/ora/tests.rs @@ -327,9 +327,29 @@ fn reads_other_applications_stacks() { assert_eq!(get("Strange").blend, BlendMode::Normal); assert!(get("Lost").surface().unwrap().content_bounds().is_empty()); let all = r.warnings.join("\n"); - for needle in ["svg:dst-in", "", "missing from the archive", "krita:hard mix", "svg:soft-light"] { + for needle in ["svg:dst-in", "", "missing from the archive", "krita:hard mix"] { assert!(all.contains(needle), "{needle} not in {all}"); } + // svg:soft-light is the W3C curve, which is Photoshop's Soft Light (#8804): no warning. + assert!(!all.contains("soft-light"), "{all}"); +} + +#[test] +fn krita_soft_light_ids_map_to_photoshop_soft_light() { + // Krita's own soft_light keeps sqrt(cb) over dark backdrops, so it is the approximation; + // soft_light_svg is the W3C curve Photoshop uses (#8804). + assert_eq!(super::krita_blend("soft_light"), Some((BlendMode::SoftLight, true))); + assert_eq!(super::krita_blend("soft_light_svg"), Some((BlendMode::SoftLight, false))); + assert_eq!(super::krita_id(BlendMode::SoftLight), Some("soft_light_svg")); + let xml = r#" + + + "#; + let r = crate::import("soft.ora", &archive(xml, &[("a.png", solid_png(2, 2, [40, 40, 40, 255]))])).unwrap(); + assert!(r.document.layers.iter().all(|l| l.blend == BlendMode::SoftLight)); + let all = r.warnings.join("\n"); + assert!(all.contains("krita:soft_light blend mode is approximated"), "{all}"); + assert!(!all.contains("soft_light_svg"), "{all}"); } #[test] diff --git a/crates/io/tests/it/blend_modes_corpus.rs b/crates/io/tests/it/blend_modes_corpus.rs new file mode 100644 index 0000000000..296e2e2a50 --- /dev/null +++ b/crates/io/tests/it/blend_modes_corpus.rs @@ -0,0 +1,67 @@ +//! Blend modes against Photoshop's own merged image of psd-tools `blend-modes/rgb-blend-modes.psd`: +//! one 64 × 64 cell per mode, a duck over a rainbow backdrop. +#![cfg(feature = "corpus")] + +use photocraft_color::BlendMode; +use photocraft_geom::Rect; +use photocraft_io::{import, merged_composite}; +use photocraft_psd::PsdFile; + +const CELL: i32 = 64; + +/// The largest and mean difference in 8-bit levels between our flatten and Photoshop's merged image +/// over the cell of `mode`, on the pixels where that cell's duck is fully opaque (its anti-aliased +/// edge mixes in the backdrop, which says nothing about the mode). +fn cell_error(mode: BlendMode) -> (f32, f32) { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/psd-tools/blend-modes/rgb-blend-modes.psd"); + let bytes = std::fs::read(path).expect("run cargo xtask corpus --psd-tools"); + let doc = import("rgb-blend-modes.psd", &bytes).expect("opens").document; + let file = PsdFile::from_bytes(&bytes).expect("parses"); + let merged = merged_composite(&file).expect("merged image"); + let ours = photocraft_compose::flatten(&doc).px; + let width = doc.size.width as i32; + let duck = doc.walk().into_iter().map(|(_, _, l)| l).find(|l| l.name == "rubber_duck_PNG1" && l.blend == mode).expect("the mode's duck"); + let surface = duck.surface().expect("duck pixels"); + let bounds = surface.content_bounds(); + let (x0, y0) = ((bounds.x0 / CELL) * CELL, (bounds.y0 / CELL) * CELL); + let mut alpha = vec![[0.0f32; 4]; (CELL * CELL) as usize]; + surface.read_rgba_into(Rect::from_xywh(x0, y0, CELL as u32, CELL as u32), &mut alpha); + let (mut max, mut sum, mut n) = (0.0f32, 0.0f32, 0u32); + for y in 1..CELL - 1 { + for x in 1..CELL - 1 { + // Opaque, and so are its four neighbours (one pixel in from the edge). + let opaque = |dx: i32, dy: i32| alpha[((y + dy) * CELL + x + dx) as usize][3] >= 1.0; + if !(opaque(0, 0) && opaque(-1, 0) && opaque(1, 0) && opaque(0, -1) && opaque(0, 1)) { + continue; + } + let i = ((y0 + y) * width + x0 + x) as usize; + for c in 0..3 { + let d = ((ours[i][c] * 255.0).round() - (merged[i][c] * 255.0).round()).abs(); + max = max.max(d); + sum += d; + n += 1; + } + } + } + assert!(n > 3000, "{mode:?}: only {n} opaque samples"); + (max, sum / n as f32) +} + +/// #8804: Soft Light over the dark parts of the rainbow. With `sqrt(cb)` below a quarter the cell +/// was up to 20 levels too light; the W3C curve Photoshop uses is within 7. +#[test] +fn soft_light_matches_photoshop_over_dark_backdrops() { + let (max, mean) = cell_error(BlendMode::SoftLight); + eprintln!("Soft Light: max {max} mean {mean:.3}"); + assert!(max <= 7.0 && mean < 0.6, "max {max} mean {mean}"); +} + +/// The modes #8804 checked next to Soft Light stay where they were. +#[test] +fn separable_light_modes_match_photoshop() { + for mode in [BlendMode::Multiply, BlendMode::Screen, BlendMode::Overlay, BlendMode::HardLight] { + let (max, mean) = cell_error(mode); + eprintln!("{mode:?}: max {max} mean {mean:.3}"); + assert!(max <= 3.0, "{mode:?}: max {max} mean {mean}"); + } +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 662d37c307..5519fc0d6b 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -8,6 +8,7 @@ mod affinity_corpus; mod annotations; mod artboard_guide_order; mod banded; +mod blend_modes_corpus; mod cancel; mod channels; mod cmyk_composite_export; diff --git a/docs/ora.md b/docs/ora.md index 61125f060b..f981a74d8d 100644 --- a/docs/ora.md +++ b/docs/ora.md @@ -43,8 +43,9 @@ everything: the document keeps its file and its unsaved changes. Automation foll OpenRaster elements other than `stack` and `layer` (MyPaint's text, for example), missing layer images and unknown composite operations open with a warning instead of failing the file. -Krita's W3C Soft Light (`svg:soft-light`, `krita:soft_light_svg`) and its own Hard Mix open as -Photoshop's Soft Light and Hard Mix, which differ slightly, also with a warning. +Krita's W3C Soft Light (`svg:soft-light`, `krita:soft_light_svg`) is Photoshop's Soft Light and +opens as it. Krita's own Soft Light (`krita:soft_light`, `sqrt` over dark backdrops) and its own +Hard Mix open as Photoshop's Soft Light and Hard Mix, which differ slightly, with a warning. ## Limits and safety