Skip to content

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

fix(blend): keep 32-bit Hue/Saturation/Color/Luminosity above 1 (#1735)

eric5b051861bcd8
diff --git a/crates/color/src/blend.rs b/crates/color/src/blend.rs
index 05ab00f16..cd8f6eac3 100644
--- a/crates/color/src/blend.rs
+++ b/crates/color/src/blend.rs
@@ -336,7 +336,17 @@ pub fn lum(c: [f32; 3]) -> f32 {
0.3 * c[0] + 0.59 * c[1] + 0.11 * c[2]
}
-fn clip_color(c: [f32; 3]) -> [f32; 3] {
+/// ClipColor: moves `c` towards its grey ([`lum`]) until every channel is within `0..=top`,
+/// keeping the luminosity. `top` is the brightest in-gamut value: 1, or `f32::MAX` in 32-bit
+/// documents (values above 1 are valid light there, so only negatives are pulled in).
+///
+/// The scale factors `l / (l − min)` and `(top − l) / (max − l)` lie in 0..1 only while the
+/// luminosity itself is in range. Outside it no colour of that luminosity is in gamut: the plain
+/// formula turned colours inside out (a grey of 2 as the Luminosity of (0.5, 0.25, 0.125) gave
+/// (1.0, 2.32, 2.99)) and, for greys, divided by the rounding noise of `max − l`, so results were
+/// arbitrary and differed between the CPU and the GPU. Such colours become their grey instead
+/// (the formula's value as the luminosity reaches the bound).
+fn clip_color(c: [f32; 3], top: f32) -> [f32; 3] {
let l = lum(c);
let n = c[0].min(c[1]).min(c[2]);
let x = c[0].max(c[1]).max(c[2]);
@@ -344,13 +354,13 @@ fn clip_color(c: [f32; 3]) -> [f32; 3] {
if n < 0.0 {
let d = l - n;
for v in &mut out {
- *v = if d.abs() < 1e-12 { l } else { l + (*v - l) * l / d };
+ *v = if l > 0.0 && d > 0.0 { l + (*v - l) * l / d } else { l };
}
}
- if x > 1.0 {
+ if x > top {
let d = x - l;
for v in &mut out {
- *v = if d.abs() < 1e-12 { l } else { l + (*v - l) * (1.0 - l) / d };
+ *v = if l < top && d > 0.0 { l + (*v - l) * (top - l) / d } else { l };
}
}
out
@@ -359,8 +369,13 @@ fn clip_color(c: [f32; 3]) -> [f32; 3] {
/// `c` with its luminosity ([`lum`]) moved to `l`, clipped back into gamut towards grey (the
/// Luminosity blend mode's SetLum + ClipColor).
pub fn set_lum(c: [f32; 3], l: f32) -> [f32; 3] {
+ set_lum_within(c, l, 1.0)
+}
+
+/// [`set_lum`] clipping at `top` instead of 1 (see [`blend_rgb_within`]).
+fn set_lum_within(c: [f32; 3], l: f32, top: f32) -> [f32; 3] {
let d = l - lum(c);
- clip_color([c[0] + d, c[1] + d, c[2] + d])
+ clip_color([c[0] + d, c[1] + d, c[2] + d], top)
}
fn sat(c: [f32; 3]) -> f32 {
@@ -382,11 +397,17 @@ fn set_sat(c: [f32; 3], s: f32) -> [f32; 3] {
/// Blend a whole RGB triple: `B(Cb, Cs)` including non-separable modes.
pub fn blend_rgb(mode: BlendMode, cb: [f32; 3], cs: [f32; 3]) -> [f32; 3] {
+ blend_rgb_within(mode, cb, cs, 1.0)
+}
+
+/// [`blend_rgb`] with Hue / Saturation / Color / Luminosity clipped at `top` instead of 1:
+/// `f32::MAX` keeps the values above 1 of 32-bit documents (their gamut has no upper bound).
+pub fn blend_rgb_within(mode: BlendMode, cb: [f32; 3], cs: [f32; 3], top: f32) -> [f32; 3] {
match mode {
- BlendMode::Hue => set_lum(set_sat(cs, sat(cb)), lum(cb)),
- BlendMode::Saturation => set_lum(set_sat(cb, sat(cs)), lum(cb)),
- BlendMode::Color => set_lum(cs, lum(cb)),
- BlendMode::Luminosity => set_lum(cb, lum(cs)),
+ BlendMode::Hue => set_lum_within(set_sat(cs, sat(cb)), lum(cb), top),
+ BlendMode::Saturation => set_lum_within(set_sat(cb, sat(cs)), lum(cb), top),
+ BlendMode::Color => set_lum_within(cs, lum(cb), top),
+ BlendMode::Luminosity => set_lum_within(cb, lum(cs), top),
BlendMode::DarkerColor => {
if lum(cs) < lum(cb) {
cs
@@ -405,9 +426,10 @@ pub fn blend_rgb(mode: BlendMode, cb: [f32; 3], cs: [f32; 3]) -> [f32; 3] {
}
}
-/// [`blend_rgb`] for 32-bit float documents: separable modes use [`blend_channel_hdr`].
+/// [`blend_rgb`] for 32-bit float documents: separable modes use [`blend_channel_hdr`], and the
+/// non-separable ones keep values above 1 ([`blend_rgb_within`] at `f32::MAX`).
pub fn blend_rgb_hdr(mode: BlendMode, cb: [f32; 3], cs: [f32; 3]) -> [f32; 3] {
- if mode.is_separable() { std::array::from_fn(|i| blend_channel_hdr(mode, cb[i], cs[i])) } else { blend_rgb(mode, cb, cs) }
+ if mode.is_separable() { std::array::from_fn(|i| blend_channel_hdr(mode, cb[i], cs[i])) } else { blend_rgb_within(mode, cb, cs, f32::MAX) }
}
/// Composite a straight-alpha source over a straight-alpha backdrop with blend mode and opacity.
@@ -598,8 +620,9 @@ mod tests {
assert_eq!(blend_channel_hdr(BlendMode::Divide, f32::MAX, 1e-30), f32::MAX);
assert_eq!(blend_channel_hdr(BlendMode::LinearDodge, f32::MAX, f32::MAX), f32::MAX);
assert!(blend_channel_hdr(BlendMode::LinearDodge, f32::INFINITY, 1.0).is_finite());
- // Every other mode is unchanged, and the in-range results agree.
- for m in BlendMode::LAYER_MODES.into_iter().filter(|m| !matches!(m, BlendMode::LinearDodge | BlendMode::Divide)) {
+ // Every other separable mode is unchanged (the non-separable ones keep values above 1:
+ // blend_rgb_within), and the in-range results agree.
+ for m in BlendMode::LAYER_MODES.into_iter().filter(|m| m.is_separable() && !matches!(m, BlendMode::LinearDodge | BlendMode::Divide)) {
for (cb, cs) in [(0.2, 0.3), (0.9, 0.05), (2.0, 0.5), (0.4, 1.5)] {
assert_eq!(blend_rgb(m, [cb, cs, 0.5], [cs, cb, 0.25]), blend_rgb_hdr(m, [cb, cs, 0.5], [cs, cb, 0.25]), "{m:?} cb={cb} cs={cs}");
}
@@ -624,6 +647,149 @@ mod tests {
assert!(close(s[0], s[1]) && close(s[1], s[2]));
}
+ /// ClipColor exactly as ISO 32000 / W3C write it (what `clip_color` was before it guarded
+ /// out-of-range luminosities).
+ fn spec_clip_color(c: [f32; 3]) -> [f32; 3] {
+ let l = lum(c);
+ let n = c[0].min(c[1]).min(c[2]);
+ let x = c[0].max(c[1]).max(c[2]);
+ let mut out = c;
+ if n < 0.0 {
+ let d = l - n;
+ for v in &mut out {
+ *v = if d.abs() < 1e-12 { l } else { l + (*v - l) * l / d };
+ }
+ }
+ if x > 1.0 {
+ let d = x - l;
+ for v in &mut out {
+ *v = if d.abs() < 1e-12 { l } else { l + (*v - l) * (1.0 - l) / d };
+ }
+ }
+ out
+ }
+
+ fn spec_blend_rgb(mode: BlendMode, cb: [f32; 3], cs: [f32; 3]) -> [f32; 3] {
+ let set_lum = |c: [f32; 3], l: f32| {
+ let d = l - lum(c);
+ spec_clip_color([c[0] + d, c[1] + d, c[2] + d])
+ };
+ match mode {
+ BlendMode::Hue => set_lum(set_sat(cs, sat(cb)), lum(cb)),
+ BlendMode::Saturation => set_lum(set_sat(cb, sat(cs)), lum(cb)),
+ BlendMode::Color => set_lum(cs, lum(cb)),
+ BlendMode::Luminosity => set_lum(cb, lum(cs)),
+ m => blend_rgb(m, cb, cs),
+ }
+ }
+
+ const NON_SEPARABLE: [BlendMode; 4] = [BlendMode::Hue, BlendMode::Saturation, BlendMode::Color, BlendMode::Luminosity];
+
+ #[test]
+ fn non_separable_modes_unchanged_on_integer_inputs() {
+ // 8/16-bit documents only hold 0..1, where the luminosity stays in range (up to a
+ // rounding step at white) and ClipColor is the plain ISO 32000 formula.
+ let mut edges: Vec<f32> = vec![0.0, 1.0 / 255.0, 0.5, 254.0 / 255.0, 65534.0 / 65535.0, 1.0];
+ edges.extend((0..=8).map(|i| i as f32 / 8.0));
+ let mut colors = Vec::new();
+ for &r in &edges {
+ for &g in &edges {
+ for &b in &edges {
+ colors.push([r, g, b]);
+ }
+ }
+ }
+ let mut seed = 0x1234_5678u32;
+ let mut next = |levels: u32| {
+ seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
+ ((seed >> 8) % (levels + 1)) as f32 / levels as f32
+ };
+ for _ in 0..2000 {
+ let levels = if next(1) > 0.5 { 255 } else { 65535 };
+ colors.push([next(levels), next(levels), next(levels)]);
+ }
+ let mut worst = 0.0f32;
+ for (i, &cb) in colors.iter().enumerate() {
+ for &cs in colors.iter().skip(i % 7).step_by(7) {
+ for m in NON_SEPARABLE {
+ let (got, want) = (blend_rgb(m, cb, cs), spec_blend_rgb(m, cb, cs));
+ for k in 0..3 {
+ worst = worst.max((got[k] - want[k]).abs());
+ }
+ }
+ }
+ }
+ // Only white-ish colours whose luminosity rounds a step above 1 can differ, by a rounding step.
+ assert!(worst <= 1e-6, "{worst}");
+ }
+
+ #[test]
+ fn non_separable_modes_stable_when_luminosity_is_out_of_range() {
+ // The spec formula divided by `max − lum`, which is rounding noise for a grey above 1 and
+ // turns colours inside out when the luminosity is above 1: Luminosity of a grey of 2 over
+ // (0.5, 0.25, 0.125) gave (1.0, 2.32, 2.99).
+ let spec = spec_blend_rgb(BlendMode::Luminosity, [0.5, 0.25, 0.125], [2.0; 3]);
+ assert!(spec[0] < spec[2], "{spec:?}");
+ let colors: [[f32; 3]; 10] = [
+ [1.0, 1.0, 1.0],
+ [1.5, 1.5, 1.5],
+ [2.0, 2.0, 2.0],
+ [4.0, 4.0, 4.0],
+ [1000.0, 1000.0, 1000.0],
+ [2.0, 2.0, 1.999_999],
+ [4.0, 3.999_9, 4.0],
+ [3.0, 0.25, 0.125],
+ [1.25, 0.875, 3.75],
+ [-0.25, 0.5, 1.375],
+ ];
+ for top in [1.0, f32::MAX] {
+ for m in NON_SEPARABLE {
+ for cb in colors {
+ for cs in colors {
+ let r = blend_rgb_within(m, cb, cs, top);
+ assert!(r.iter().all(|v| v.is_finite()), "{m:?} {cb:?} {cs:?} {top}: {r:?}");
+ // The target luminosity is kept, at any depth.
+ let want = if m == BlendMode::Luminosity { lum(cs) } else { lum(cb) };
+ if want >= 0.0 {
+ assert!((lum(r) - want).abs() <= 1e-4 * want.max(1.0), "{m:?} {cb:?} {cs:?} {top}: {r:?}");
+ }
+ let (lo, hi) = (r[0].min(r[1]).min(r[2]), r[0].max(r[1]).max(r[2]));
+ if top == 1.0 {
+ // In gamut, or (a luminosity above 1 has no in-gamut colour) its grey.
+ assert!((lo >= 0.0 && hi <= 1.0 + E) || hi - lo <= 1e-6 * hi, "{m:?} {cb:?} {cs:?}: {r:?}");
+ } else {
+ assert!(lo >= -1e-6 * hi.max(1.0), "{m:?} {cb:?} {cs:?}: {r:?}");
+ }
+ }
+ }
+ }
+ }
+ // 32-bit: a grey backdrop gives a grey of its own luminosity in Hue and Saturation, a
+ // grey source a grey in Color, and bright colours keep their values above 1.
+ for g in [1.5f32, 2.0, 4.0, 1000.0] {
+ let grey = [g; 3];
+ for cs in colors {
+ for m in [BlendMode::Hue, BlendMode::Saturation] {
+ let r = blend_rgb_within(m, grey, cs, f32::MAX);
+ assert!(r.iter().all(|&v| (v - lum(grey)).abs() <= 1e-5 * g), "{m:?} {g} {cs:?}: {r:?}");
+ }
+ }
+ let r = blend_rgb_within(BlendMode::Luminosity, [0.5, 0.25, 0.125], grey, f32::MAX);
+ assert!(r[0] > 1.0 && r[0] > r[1] && r[1] > r[2], "{g}: {r:?}");
+ let r = blend_rgb_within(BlendMode::Color, grey, [3.0, 0.25, 0.125], f32::MAX);
+ assert!(r[0] > 1.0 && r[0] > r[1] && r[1] > r[2], "{g}: {r:?}");
+ // Integer documents: no colour of that luminosity fits in 0..1, so it is its grey.
+ let r = blend_rgb_within(BlendMode::Luminosity, [0.5, 0.25, 0.125], grey, 1.0);
+ assert!(r.iter().all(|&v| (v - lum(grey)).abs() <= 1e-5 * g), "{g}: {r:?}");
+ }
+ // Continuous across near-greys: the result barely moves from the grey's.
+ for m in NON_SEPARABLE {
+ let a = blend_rgb_within(m, [2.0, 2.0, 2.0], [4.0, 4.0, 4.0], f32::MAX);
+ let b = blend_rgb_within(m, [2.0, 2.0, 1.999_999], [4.0, 3.999_999, 4.0], f32::MAX);
+ assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 1e-4), "{m:?}: {a:?} {b:?}");
+ }
+ }
+
#[test]
fn darker_lighter_color_pick_whole_pixel() {
let a = [0.9, 0.1, 0.1];
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index 201306d2e..ebecc60c1 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -97,7 +97,7 @@ pub fn render_tiled(doc: &Document, rect: Rect, tile: i32) -> Buffer {
fn render_tiled_with(doc: &Document, rect: Rect, tile: i32, cx: &Ctx) -> Buffer {
let tile = tile.max(1);
// Lab documents mix Normal blending in CIELAB, as Photoshop does (psblend::LAB_MIX); 32-bit
- // documents don't clip Add / Divide at 1 (psblend::HDR).
+ // documents don't clip Add / Divide or Hue / Saturation / Color / Luminosity at 1 (psblend::HDR).
let lab = doc.mode == photocraft_color::ColorMode::Lab;
let hdr = doc.depth == photocraft_color::SampleType::F32;
// CMYK layers are read through the document's own CMYK profile (thread-local scope).
diff --git a/crates/compose/src/psblend.rs b/crates/compose/src/psblend.rs
index 063e32ef5..84566086e 100644
--- a/crates/compose/src/psblend.rs
+++ b/crates/compose/src/psblend.rs
@@ -76,8 +76,9 @@ thread_local! {
/// (Photoshop composites Lab documents in Lab; an anti-aliased edge between two colours
/// differs by up to 14 / 255 from an sRGB mix: psd-tools stroke-color-descriptors-lab).
pub static LAB_MIX: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
- /// Set while rendering a 32-bit float document: Linear Dodge (Add) and Divide don't clip at 1
- /// ([`generic::blend_rgb_hdr`]), as in Photoshop's 32-bit mode; integer depths clip.
+ /// Set while rendering a 32-bit float document: Linear Dodge (Add) and Divide don't clip at 1,
+ /// and Hue, Saturation, Color and Luminosity keep values above 1 ([`generic::blend_rgb_hdr`]),
+ /// as in Photoshop's 32-bit mode; integer depths clip.
pub static HDR: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
@@ -274,6 +275,20 @@ mod tests {
assert!((color_dodge(0.25, 0.5) - 0.5).abs() < 1e-6);
}
+ #[test]
+ fn hdr_nests_and_restores() {
+ let bright = |m| blend_rgb(m, [0.5, 0.5, 0.5], [1.0, 0.0, 0.0])[0];
+ with_hdr(true, || {
+ // A 32-bit document keeps Color's red above 1.
+ assert!(bright(BlendMode::Color) > 1.1);
+ // Another tile's (or document's) scope run inside this one doesn't reset it.
+ with_hdr(false, || assert!(bright(BlendMode::Color) <= 1.0));
+ assert!(HDR.get());
+ });
+ assert!(!HDR.get());
+ assert!(bright(BlendMode::Color) <= 1.0);
+ }
+
#[test]
fn other_modes_delegate() {
for m in BlendMode::LAYER_MODES {
diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs
index 3aace8056..b2276ab86 100644
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@ -87,6 +87,57 @@ fn every_blend_mode_matches_reference_on_opaque_pixels() {
}
}
+/// One opaque pixel: `top` in `mode` over `bottom`, in a document of `depth`.
+fn blend_px(depth: SampleType, mode: BlendMode, bottom: [f32; 3], top: [f32; 3]) -> [f32; 4] {
+ let mut d = Document::new("b", Size::new(1, 1), ColorMode::Rgb, depth);
+ let fmt = d.pixel_format();
+ let mut b = Layer::raster("b", fmt);
+ b.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 1, 1), &photocraft_raster::from_rgba(&fmt, [bottom[0], bottom[1], bottom[2], 1.0]));
+ let mut t = Layer::raster("t", fmt);
+ t.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 1, 1), &photocraft_raster::from_rgba(&fmt, [top[0], top[1], top[2], 1.0]));
+ t.blend = mode;
+ d.layers = vec![b, t];
+ px(&d, 0, 0)
+}
+
+#[test]
+fn non_separable_modes_keep_values_above_one_in_32_bit() {
+ use photocraft_color::blend::{blend_rgb_within, lum};
+ let modes = [BlendMode::Hue, BlendMode::Saturation, BlendMode::Color, BlendMode::Luminosity];
+ // Hue over a grey of 2: the grey (the backdrop has no saturation), not ClipColor dividing
+ // by the rounding noise of `max − lum` (Hue over (4, 3.9999, 4) gave 27.7 in blue).
+ for bg in [[2.0, 2.0, 2.0], [2.0, 2.0, 1.999_99], [4.0, 3.999_9, 4.0]] {
+ for m in modes {
+ for top in [[3.0, 0.25, 0.125], [2.0, 2.0, 2.0], [4.0, 3.999_9, 4.0]] {
+ let got = blend_px(SampleType::F32, m, bg, top);
+ let want = blend_rgb_within(m, bg, top, f32::MAX);
+ assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1e-4 * w.abs().max(1.0)), "{m:?} {bg:?} {top:?}: {got:?} vs {want:?}");
+ assert!(got.iter().all(|v| v.is_finite() && *v >= -1e-5), "{m:?} {bg:?} {top:?}: {got:?}");
+ }
+ }
+ }
+ // A saturated colour keeps its brightness above 1 in 32-bit, and is clipped into 0..1
+ // (exactly as before) in 8/16-bit.
+ let (bg, top) = ([0.5, 0.5, 0.5], [1.0, 0.0, 0.0]);
+ let hdr = blend_px(SampleType::F32, BlendMode::Color, bg, top);
+ assert!((hdr[0] - 1.2).abs() < 1e-4 && (lum([hdr[0], hdr[1], hdr[2]]) - 0.5).abs() < 1e-4, "{hdr:?}");
+ for depth in [SampleType::U8, SampleType::U16] {
+ for m in modes {
+ let got = blend_px(depth, m, bg, top);
+ let want = photocraft_color::blend::blend_rgb(m, bg, top);
+ assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1.0 / 255.0), "{m:?} {depth:?}: {got:?} vs {want:?}");
+ }
+ let got = blend_px(depth, BlendMode::Color, bg, top);
+ assert!(got[0] <= 1.0 && got[0] > 0.9, "{depth:?}: {got:?}");
+ }
+ // A 32-bit document's in-range colours that stay in range are unchanged.
+ for m in modes {
+ let got = blend_px(SampleType::F32, m, [0.6, 0.3, 0.2], [0.2, 0.7, 0.5]);
+ let want = photocraft_color::blend::blend_rgb(m, [0.6, 0.3, 0.2], [0.2, 0.7, 0.5]);
+ assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1e-5), "{m:?}: {got:?} vs {want:?}");
+ }
+}
+
#[test]
fn layer_mask_hides_pixels() {
let mut d = doc_white(4, 4);
diff --git a/crates/gpu/src/compose.wgsl b/crates/gpu/src/compose.wgsl
index c06b4a865..e0f0ddfad 100644
--- a/crates/gpu/src/compose.wgsl
+++ b/crates/gpu/src/compose.wgsl
@@ -48,7 +48,7 @@ const F_STROKE_OUT: u32 = 1024u; // effect paint: outside stroke band
const F_FIRST: u32 = 2048u; // outside strokes: nothing accumulated yet
const F_CHANNELS: u32 = 4096u; // lerp: per-channel weights in p0 (channel restrictions)
const F_LAB: u32 = 65536u; // Lab document: Normal mixes in CIELAB
-const F_HDR: u32 = 262144u; // 32-bit float document: Add / Divide don't clip at 1
+const F_HDR: u32 = 262144u; // 32-bit float document: Add / Divide and Hue/Saturation/Color/Luminosity don't clip at 1
const F_QUANT: u32 = 32768u; // lerp: A rounded to p0.x steps (adjustment results, integer docs)
const F_ADD_DIFF: u32 = 16384u; // lerp: A + (B - C) premultiplied (clips on pass-through groups)
const F_TEXT_GAMMA: u32 = 8192u; // blend / atop / fx merge: type layer, mix coverage at gamma p4.w
@@ -216,22 +216,24 @@ fn blend_channel(mode: i32, cb: f32, cs: f32) -> f32 {
fn lum(c: vec3<f32>) -> f32 { return 0.3 * c.r + 0.59 * c.g + 0.11 * c.b; }
-fn clip_color(c: vec3<f32>) -> vec3<f32> {
+// photocraft_color::blend::clip_color: towards grey until within 0..top; a luminosity outside
+// that range has no in-gamut colour (and max − lum is rounding noise), so it gives its grey.
+fn clip_color(c: vec3<f32>, top: f32) -> vec3<f32> {
let l = lum(c);
let n = min(min(c.r, c.g), c.b);
let x = max(max(c.r, c.g), c.b);
var out = c;
if (n < 0.0) {
let d = l - n;
- if (abs(d) < 1e-12) { out = vec3(l); } else { out = l + (out - l) * l / d; }
+ if (l > 0.0 && d > 0.0) { out = l + (out - l) * l / d; } else { out = vec3(l); }
}
- if (x > 1.0) {
+ if (x > top) {
let d = x - l;
- if (abs(d) < 1e-12) { out = vec3(l); } else { out = l + (out - l) * (1.0 - l) / d; }
+ if (l < top && d > 0.0) { out = l + (out - l) * (top - l) / d; } else { out = vec3(l); }
}
return out;
}
-fn set_lum(c: vec3<f32>, l: f32) -> vec3<f32> { return clip_color(c + (l - lum(c))); }
+fn set_lum(c: vec3<f32>, l: f32, top: f32) -> vec3<f32> { return clip_color(c + (l - lum(c)), top); }
fn sat(c: vec3<f32>) -> f32 { return max(max(c.r, c.g), c.b) - min(min(c.r, c.g), c.b); }
fn set_sat(c: vec3<f32>, s: f32) -> vec3<f32> {
let mx = max(max(c.r, c.g), c.b);
@@ -241,11 +243,13 @@ fn set_sat(c: vec3<f32>, s: f32) -> vec3<f32> {
}
fn blend_rgb(mode: i32, cb: vec3<f32>, cs: vec3<f32>) -> vec3<f32> {
+ // blend_rgb_within: 32-bit documents keep values above 1 (f32::MAX).
+ let top = select(1.0, F32_MAX, (op.flags & F_HDR) != 0u);
switch mode {
- case 24: { return set_lum(set_sat(cs, sat(cb)), lum(cb)); } // Hue
- case 25: { return set_lum(set_sat(cb, sat(cs)), lum(cb)); } // Saturation
- case 26: { return set_lum(cs, lum(cb)); } // Color
- case 27: { return set_lum(cb, lum(cs)); } // Luminosity
+ case 24: { return set_lum(set_sat(cs, sat(cb)), lum(cb), top); } // Hue
+ case 25: { return set_lum(set_sat(cb, sat(cs)), lum(cb), top); } // Saturation
+ case 26: { return set_lum(cs, lum(cb), top); } // Color
+ case 27: { return set_lum(cb, lum(cs), top); } // Luminosity
case 7: { return select(cb, cs, lum(cs) < lum(cb)); } // DarkerColor
case 12: { return select(cb, cs, lum(cs) > lum(cb)); } // LighterColor
default: {
@@ -608,7 +612,7 @@ fn adjust(c: vec3<f32>) -> vec3<f32> {
let g = p3.y;
let lin = vec3(t_decode(c.r, g), t_decode(c.g, g), t_decode(c.b, g));
var f = vec3(t_encode(dot(p0.xyz, lin), g), t_encode(dot(p1.xyz, lin), g), t_encode(dot(p2.xyz, lin), g));
- if (p3.x > 0.5) { f = set_lum(f, lum(c)); }
+ if (p3.x > 0.5) { f = set_lum(f, lum(c), 1.0); }
return clamp(f, vec3(0.0), vec3(1.0));
}
case 12: { // Black & White
diff --git a/crates/gpu/src/plan.rs b/crates/gpu/src/plan.rs
index d718d807e..0bf1230fb 100644
--- a/crates/gpu/src/plan.rs
+++ b/crates/gpu/src/plan.rs
@@ -362,7 +362,8 @@ pub const F_FIRST: u32 = 2048;
pub const F_CHANNELS: u32 = 4096;
/// Lab document: Normal blending mixes in CIELAB (`psblend::LAB_MIX`).
pub const F_LAB: u32 = 65536;
-/// 32-bit float document: Linear Dodge (Add) and Divide don't clip at 1 (`psblend::HDR`).
+/// 32-bit float document: Linear Dodge (Add) and Divide don't clip at 1, and the non-separable
+/// modes clip only below 0 (`psblend::HDR`).
pub const F_HDR: u32 = 262144;
/// `Lerp`: A rounded to `p0.x` steps per unit (adjustment results on integer documents).
pub const F_QUANT: u32 = 32768;
diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rs
index 85d3b5e21..9dccc008f 100644
--- a/crates/gpu/tests/parity.rs
+++ b/crates/gpu/tests/parity.rs
@@ -1448,6 +1448,72 @@ fn blend_mode_extremes() {
}
}
+/// Colours for the non-separable modes: in gamut, greys and near-greys above 1 (lum ≈ max, where
+/// ClipColor divided by rounding noise), saturated colours above 1, negatives and mixes. All are
+/// exact in half floats (the GPU's layer textures of 16/32-bit documents), so both compositors
+/// see the same inputs.
+const NONSEP_COLORS: [[f32; 3]; 12] = [
+ [0.25, 0.5, 0.75],
+ [1.0, 1.0, 1.0],
+ [0.0, 0.0, 0.0],
+ [1.5, 1.5, 1.5],
+ [2.0, 2.0, 2.0],
+ [4.0, 4.0, 4.0],
+ [2.0, 2.0, 1.996_093_8],
+ [4.0, 3.992_187_5, 4.0],
+ [3.0, 0.25, 0.125],
+ [0.125, 2.5, 0.375],
+ [1.25, 0.875, 3.75],
+ [-0.25, 0.5, 1.375],
+];
+
+/// Every pair of `colors` (backdrop column, source row) as one opaque pixel, in `mode`.
+fn nonsep_doc(mode: BlendMode, depth: SampleType, colors: &[[f32; 3]]) -> Document {
+ let n = colors.len() as u32;
+ let mut d = Document::new("x", Size::new(n, n), ColorMode::Rgb, depth);
+ let fmt = d.pixel_format();
+ let mut bg = Layer::raster("bg", fmt);
+ let mut top = Layer::raster("top", fmt);
+ for (i, b) in colors.iter().enumerate() {
+ for (j, s) in colors.iter().enumerate() {
+ let r = Rect::from_xywh(i as i32, j as i32, 1, 1);
+ bg.surface_mut().unwrap().fill_rect(r, &photocraft_raster::from_rgba(&fmt, [b[0], b[1], b[2], 1.0]));
+ top.surface_mut().unwrap().fill_rect(r, &photocraft_raster::from_rgba(&fmt, [s[0], s[1], s[2], 1.0]));
+ }
+ }
+ top.blend = mode;
+ d.layers.push(bg);
+ d.layers.push(top);
+ d
+}
+
+const NONSEP_MODES: [BlendMode; 6] =
+ [BlendMode::Hue, BlendMode::Saturation, BlendMode::Color, BlendMode::Luminosity, BlendMode::DarkerColor, BlendMode::LighterColor];
+
+#[test]
+fn non_separable_modes_on_hdr_values() {
+ // 32-bit documents hold values above 1 (and below 0): Hue / Saturation / Color / Luminosity
+ // used to divide by the rounding noise of `max − lum` in ClipColor there, which the CPU and
+ // GPU round differently (Hue over a grey of 2: CPU 1.0, GPU 2.82).
+ let Some(mut g) = gpu() else { return };
+ let mut failures = Vec::new();
+ for mode in NONSEP_MODES {
+ if let Err(e) = diff_rect(&mut g, &nonsep_doc(mode, SampleType::F32, &NONSEP_COLORS), Rect::new(0, 0, 12, 12), &format!("hdr {mode:?}")) {
+ failures.push(e);
+ }
+ }
+ // Integer documents store 0..1 only.
+ let in_gamut: Vec<[f32; 3]> = NONSEP_COLORS.iter().map(|c| c.map(|v| v.clamp(0.0, 1.0))).collect();
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ for mode in NONSEP_MODES {
+ if let Err(e) = diff_rect(&mut g, &nonsep_doc(mode, depth, &in_gamut), Rect::new(0, 0, 12, 12), &format!("in gamut {mode:?} {depth:?}")) {
+ failures.push(e);
+ }
+ }
+ }
+ assert!(failures.is_empty(), "{}", failures.join("\n"));
+}
+
#[test]
fn float_documents_blend_past_white() {
// 32-bit documents hold values above 1; Linear Dodge (Add) and Divide don't clip them there