From d8c06f4597281773f654e347b06562723af3ac9c Mon Sep 17 00:00:00 2001 From: x-labb <154824493+x-labb@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:15:31 +0100 Subject: [PATCH 1/5] fix(engine): a gradient's transparency follows the interpolation method (#12010) paint.gradient baked only the colours with `method` and took the nearest stop's alpha for each dense stop, so the transparency never followed the method. Colour and opacity stops are now baked apart, and Smooth gets its own opacity curve (the Oklab easing of the colours, response y^(1/2.2)), fitted to the measured Foreground to Transparent ramp: alpha 255/179/100/35/0 at x 50/250/400/550/750. Opaque gradients and calls without `method` paint as before. --- crates/engine/src/cmd.rs | 2 + .../src/cmd/gradient_alpha_method_tests.rs | 77 +++++++++++++++++++ crates/engine/src/cmd/paint_cmds.rs | 51 +++++++++--- crates/engine/src/presets/gradients.rs | 15 +++- crates/io/src/gradient_bake.rs | 49 ++++++++++-- crates/io/src/lib.rs | 2 +- 6 files changed, 178 insertions(+), 18 deletions(-) create mode 100644 crates/engine/src/cmd/gradient_alpha_method_tests.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index c727a8850d1..9e16929a308 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -93,6 +93,8 @@ pub mod frame_cmds; pub mod fx_view_cmds; pub mod fx_visibility_cmds; pub mod gallery_cmds; +#[cfg(test)] +mod gradient_alpha_method_tests; pub mod gradient_fill_cmds; pub mod group_view_cmds; pub mod history_cmds; diff --git a/crates/engine/src/cmd/gradient_alpha_method_tests.rs b/crates/engine/src/cmd/gradient_alpha_method_tests.rs new file mode 100644 index 00000000000..2ca1e947631 --- /dev/null +++ b/crates/engine/src/cmd/gradient_alpha_method_tests.rs @@ -0,0 +1,77 @@ +//! #12010: the transparency of a gradient drawn with the Gradient tool follows the interpolation +//! method (Smooth by default) instead of a straight line. Reference: Foreground to Transparent, +//! Smooth, dragged (100, 300) to (700, 300): alpha 255 / 179 / 100 / 35 / 0 at x 50 / 250 / 400 / +//! 550 / 750. + +use serde_json::{Value, json}; + +use crate::Session; + +fn drawn(extra: Value) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 600, "background": "transparent"})).unwrap(); + let mut p = json!({"gradient": "Foreground to Transparent", "from": [100, 300], "to": [700, 300], "dither": false}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + s.execute("paint.gradient", p).unwrap(); + s +} + +fn alpha_at(s: &Session, x: i32) -> f32 { + let d = s.active().unwrap(); + let l = d.doc.layer(d.active_layer.unwrap()).unwrap(); + let photocraft_doc::LayerContent::Raster(surface) = &l.content else { panic!("a pixel layer") }; + surface.pixel(x, 300)[3] * 255.0 +} + +#[test] +fn smooth_transparency_ramp_matches_the_reference() { + let s = drawn(json!({"method": "smooth"})); + for (x, want) in [(50, 255.0), (250, 179.0), (400, 100.0), (550, 35.0), (750, 0.0)] { + let got = alpha_at(&s, x); + assert!((got - want).abs() <= 2.0, "x={x}: alpha {got:.1}, want {want}"); + } +} + +#[test] +fn without_a_method_the_ramp_stays_straight() { + let s = drawn(json!({})); + for (x, want) in [(250, 191.0), (400, 128.0), (550, 64.0)] { + let got = alpha_at(&s, x); + assert!((got - want).abs() <= 2.0, "x={x}: alpha {got:.1}, want {want}"); + } +} + +#[test] +fn opaque_gradients_paint_the_same_with_a_method() { + let paint = |extra: Value| { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 8, "background": "white"})).unwrap(); + let mut p = json!({"colors": ["#000000", "#ffffff"], "from": [0, 4], "to": [64, 4], "dither": false}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + s.execute("paint.gradient", p).unwrap(); + (0..64).map(|x| alpha_and_red(&s, x)).collect::>() + }; + fn alpha_and_red(s: &Session, x: i32) -> Vec { + let d = s.active().unwrap(); + let l = d.doc.layer(d.active_layer.unwrap()).unwrap(); + let photocraft_doc::LayerContent::Raster(surface) = &l.content else { panic!() }; + surface.pixel(x, 4) + } + // The colours still follow the method; the alpha stays opaque. + let smooth = paint(json!({"method": "smooth"})); + assert!(smooth.iter().all(|p| (p[3] - 1.0).abs() < 1e-3)); + assert_ne!(smooth, paint(json!({}))); +} + +#[test] +fn a_transparent_ramp_with_other_methods_still_paints() { + for m in ["classic", "perceptual", "linear"] { + let s = drawn(json!({"method": m})); + let (a, b) = (alpha_at(&s, 250), alpha_at(&s, 550)); + assert!(a > b && (0.0..=255.0).contains(&a), "{m}: {a} {b}"); + } +} diff --git a/crates/engine/src/cmd/paint_cmds.rs b/crates/engine/src/cmd/paint_cmds.rs index 37cac96a23d..e868c3a3334 100644 --- a/crates/engine/src/cmd/paint_cmds.rs +++ b/crates/engine/src/cmd/paint_cmds.rs @@ -144,15 +144,48 @@ fn gradient(s: &mut Session, p: &Value) -> Result { // where straight stops give 0.0625. let stops = match p.get("method").and_then(Value::as_str).and_then(photocraft_io::GradientMethod::from_name) { Some(m) if stops.len() >= 2 => { - let colors = stops.iter().map(|(t, c)| (*t, photocraft_color::Color::rgba(c[0], c[1], c[2], c[3]))).collect(); - let mids = vec![0.5; stops.len() - 1]; - photocraft_io::bake_gradient(colors, &mids, (f(p, "smoothness", 100.0) / 100.0).clamp(0.0, 1.0), m) - .into_iter() - .map(|(t, c)| { - let rgb = c.to_rgb(); - (t, [rgb[0], rgb[1], rgb[2], c.alpha]) - }) - .collect() + let smoothness = (f(p, "smoothness", 100.0) / 100.0).clamp(0.0, 1.0); + // With transparency, the colour and opacity stops are baked apart: the colours by the + // method, the opacity by the method's own transparency curve (#12010). Merged stops + // would ease each of their sub-segments again and take the nearest stop's alpha. + let split = match gradients::tool_fill_stops(s, p)? { + Some((cs, os)) => Some((cs, os)), + None => { + // The legacy `colors` list, evenly spaced. + let os = gradients::transparency_param(p, "paint.gradient")?.unwrap_or_default(); + let colors: Vec<[f32; 4]> = + p.get("colors").and_then(Value::as_array).map(|a| a.iter().map(|v| color(Some(v), fg)).collect()).unwrap_or_default(); + let n = colors.len(); + let cs = colors + .iter() + .enumerate() + .map(|(i, c)| (if n > 1 { i as f32 / (n - 1) as f32 } else { 0.0 }, photocraft_color::Color::rgb(c[0], c[1], c[2]))) + .collect(); + Some((cs, os)) + } + }; + match split { + Some((cs, os)) if os.iter().any(|o| (o.1 - 1.0).abs() > 1e-6) && cs.len() >= 2 => { + let mids = vec![0.5; cs.len() - 1]; + let colours: Vec<(f32, [f32; 4])> = photocraft_io::bake_gradient(cs, &mids, smoothness, m) + .into_iter() + .map(|(t, c)| (t, [c.to_rgb()[0], c.to_rgb()[1], c.to_rgb()[2], 1.0])) + .collect(); + let omids = vec![0.5; os.len().saturating_sub(1)]; + gradients::apply_opacity(colours, &photocraft_io::bake_gradient_opacity(os, &omids, smoothness, m)) + } + _ => { + let colors = stops.iter().map(|(t, c)| (*t, photocraft_color::Color::rgba(c[0], c[1], c[2], c[3]))).collect(); + let mids = vec![0.5; stops.len() - 1]; + photocraft_io::bake_gradient(colors, &mids, smoothness, m) + .into_iter() + .map(|(t, c)| { + let rgb = c.to_rgb(); + (t, [rgb[0], rgb[1], rgb[2], c.alpha]) + }) + .collect() + } + } } _ => stops, }; diff --git a/crates/engine/src/presets/gradients.rs b/crates/engine/src/presets/gradients.rs index 20cb95d95bb..d9f5c6bf25d 100644 --- a/crates/engine/src/presets/gradients.rs +++ b/crates/engine/src/presets/gradients.rs @@ -401,19 +401,28 @@ pub const STOP: &str = "gradient.presets.stop"; /// own. `None` when the caller gave `colors` (the legacy evenly spaced form `paint.gradient` /// handles itself). pub fn tool_stops(s: &Session, p: &Value) -> Result> { + Ok(tool_preset(s, p)?.map(|g| g.resolve(s.tools.foreground, s.tools.background))) +} + +/// The same gradient as [`tool_stops`] with its colour and opacity stops kept apart, for the +/// interpolation `method`, which treats the two differently. +pub fn tool_fill_stops(s: &Session, p: &Value) -> Result> { + Ok(tool_preset(s, p)?.map(|g| g.fill_stops(s.tools.foreground, s.tools.background))) +} + +fn tool_preset(s: &Session, p: &Value) -> Result> { const CMD: &str = "paint.gradient"; if p.get("colors").and_then(Value::as_array).is_some_and(|a| !a.is_empty()) { return Ok(None); } - let g = if let Some(name) = str_param(p, "gradient") { + Ok(Some(if let Some(name) = str_param(p, "gradient") { let (gi, ii) = find(&s.presets.gradients, name, None).ok_or_else(|| bad(CMD, format!("no gradient preset \"{name}\"")))?; s.presets.gradients[gi].items[ii].clone().with_transparency(p, CMD)? } else if p.get("stops").is_some() { GradientPreset::from_params("Custom", p, CMD)? } else { s.presets.gradient.clone().with_transparency(p, CMD)? - }; - Ok(Some(g.resolve(s.tools.foreground, s.tools.background))) + })) } /// The preset named by `"preset"` (else the current gradient), or explicit `"stops"`. diff --git a/crates/io/src/gradient_bake.rs b/crates/io/src/gradient_bake.rs index 6c7aaf32f43..c8d521a3e75 100644 --- a/crates/io/src/gradient_bake.rs +++ b/crates/io/src/gradient_bake.rs @@ -195,10 +195,11 @@ const OPACITY_RESPONSE: f32 = 0.65; /// Dense linear opacity stops reproducing Photoshop's interpolation of a gradient's transparency /// (Smoothness, opacity midpoints and the method, see [`OPACITY_RESPONSE`]). Returns the input -/// unchanged when it already interpolates linearly. Smooth keeps Classic's opacity curve: it was -/// not measured (the Photoshop build it was fitted on has no Smooth method). +/// unchanged when it already interpolates linearly. Smooth follows [`bake_smooth_opacity`]. pub fn bake_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32], smoothness: f32, method: Method) -> Vec<(f32, f32)> { - let method = if method == Method::Smooth { Method::Classic } else { method }; + if method == Method::Smooth { + return bake_smooth_opacity(stops, midpoints); + } let plain_mids = midpoints.iter().all(|m| (m - 0.5).abs() < 1e-3); let smoothness = if smoothness.is_finite() { smoothness.clamp(0.0, 1.0) } else { 0.0 }; if stops.len() < 2 || (smoothness <= 0.0 && method == Method::Classic && plain_mids) { @@ -236,6 +237,43 @@ pub fn bake_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32], smoothness: f32, baked } +/// Gamma of Smooth's opacity response: the opacity of a fully transparent gradient ramp is the +/// Oklab lightness curve's linear value `y` raised to `1 / 2.2`. Photoshop 27.11, "Foreground to +/// Transparent" dragged over 600 px: alpha 255 / 179 / 100 / 35 / 0 at 50 / 250 / 400 / 550 / 750 +/// (#12010). The same ramp as an sRGB grey (`y` encoded with the sRGB curve) gives 30 at the dark +/// end, 5 levels off, where the 2.2 power gives 35. +const SMOOTH_OPACITY_GAMMA: f32 = 2.2; + +/// Smooth's transparency ramp: each opacity stop is a grey whose Oklab lightness is +/// `(opacity^2.2)^(1/3)`, which the colours' measured Smooth easing ([`SMOOTH_EASE`]) crosses +/// segment by segment, and the linear value `y = L^3` comes out as opacity `y^(1/2.2)`. Smoothness +/// doesn't change Smooth; opacity midpoints still move each segment's centre. Constant opacity +/// comes back unchanged. +fn bake_smooth_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32]) -> Vec<(f32, f32)> { + if stops.len() < 2 || stops.windows(2).all(|w| w[0].1 == w[1].1) { + return stops; + } + let mut s = stops; + s.sort_by(|a, b| a.0.total_cmp(&b.0)); + let pts: Vec<(f32, [f32; 3])> = s + .iter() + .map(|(t, o)| { + let o = if o.is_finite() { o.clamp(0.0, 1.0) } else { 1.0 }; + (*t, [o.powf(SMOOTH_OPACITY_GAMMA).cbrt(); 3]) + }) + .collect(); + const N: usize = 96; + let mut baked: Vec<(f32, f32)> = (0..=N) + .map(|k| { + let t = k as f32 / N as f32; + let l = eval(&pts, midpoints, 0.0, t, Method::Smooth)[0]; + (t, if l.is_finite() { l.clamp(0.0, 1.0).powi(3).powf(1.0 / SMOOTH_OPACITY_GAMMA) } else { 1.0 }) + }) + .collect(); + baked.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6); + baked +} + #[cfg(test)] mod tests { use super::*; @@ -280,10 +318,11 @@ mod tests { } #[test] - fn plain_classic_and_smooth_opacity_stay_as_stored() { + fn plain_classic_and_constant_smooth_opacity_stay_as_stored() { let stops = vec![(1.0, 0.0), (0.0, 1.0)]; assert_eq!(bake_opacity(stops.clone(), &[0.5], 0.0, Method::Classic), stops); - assert_eq!(bake_opacity(stops.clone(), &[0.5], 0.0, Method::Smooth), stops); + let flat = vec![(0.0, 0.4), (1.0, 0.4)]; + assert_eq!(bake_opacity(flat.clone(), &[0.5], 0.0, Method::Smooth), flat); assert_eq!(bake_opacity(vec![(0.5, 0.3)], &[], 1.0, Method::Linear), vec![(0.5, 0.3)]); } diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index c796b7cffa1..b7c0b7bf9ac 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -53,7 +53,7 @@ mod flat; mod gradient_bake; pub mod guides_map; mod png_steps; -pub use gradient_bake::{Method as GradientMethod, bake as bake_gradient}; +pub use gradient_bake::{Method as GradientMethod, bake as bake_gradient, bake_opacity as bake_gradient_opacity}; mod duotone_map; mod kra; pub mod linked; From 0f76df26c42b19ae43a67e60437566f4aacf15ee Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 02:16:17 +0100 Subject: [PATCH 2/5] PR #12644: keep the new transparency curve to the measured case Smooth's opacity curve was measured only in the Gradient tool at 100 % Smoothness. The split path also changed Classic, Perceptual and Linear, Smooth below 100 %, and (through bake_opacity) Gradient Overlay and PSD Smooth gradients; #12010 says unmeasured cases keep today's behaviour. - paint.gradient bakes the opacity apart only for Smooth at 100 % Smoothness; everything else keeps the merged stops. - bake_opacity maps Smooth to Classic again; the measured curve is the separate bake_smooth_opacity, used only by the Gradient tool. - A single colour stop with a transparency ramp now follows the curve; legacy `colors` with their own alpha keep the merged stops. - bake_smooth_opacity clamps constant stops. Tests pin today's ramp for the other methods and Smoothness 50, and cover the single-colour, RGBA-colour and constant-stop cases. Co-Authored-By: x-labb Co-Authored-By: Claude Opus 5.5 --- .../src/cmd/gradient_alpha_method_tests.rs | 40 +++++++++-- crates/engine/src/cmd/paint_cmds.rs | 67 ++++++++++++------- crates/io/src/gradient_bake.rs | 39 +++++------ crates/io/src/lib.rs | 2 +- 4 files changed, 99 insertions(+), 49 deletions(-) diff --git a/crates/engine/src/cmd/gradient_alpha_method_tests.rs b/crates/engine/src/cmd/gradient_alpha_method_tests.rs index 2ca1e947631..b8327cb8cba 100644 --- a/crates/engine/src/cmd/gradient_alpha_method_tests.rs +++ b/crates/engine/src/cmd/gradient_alpha_method_tests.rs @@ -67,11 +67,41 @@ fn opaque_gradients_paint_the_same_with_a_method() { assert_ne!(smooth, paint(json!({}))); } +// Not measured in the Gradient tool: the other methods, and Smooth below 100 % Smoothness, keep +// today's merged stops (each dense stop takes the nearest stop's alpha). #[test] -fn a_transparent_ramp_with_other_methods_still_paints() { - for m in ["classic", "perceptual", "linear"] { - let s = drawn(json!({"method": m})); - let (a, b) = (alpha_at(&s, 250), alpha_at(&s, 550)); - assert!(a > b && (0.0..=255.0).contains(&a), "{m}: {a} {b}"); +fn unmeasured_methods_and_smoothness_keep_todays_ramp() { + for extra in [json!({"method": "classic"}), json!({"method": "perceptual"}), json!({"method": "linear"}), json!({"method": "smooth", "smoothness": 50})] { + let s = drawn(extra.clone()); + for (x, want) in [(175, 250.0), (250, 191.0), (400, 128.0), (550, 64.0)] { + let got = alpha_at(&s, x); + assert!((got - want).abs() <= 1.0, "{extra} x={x}: alpha {got:.1}, want {want}"); + } + } +} + +fn drawn_colors(colors: Value) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 600, "background": "transparent"})).unwrap(); + let p = json!({"colors": colors, "transparency": [[0, 100], [1, 0]], "method": "smooth", "from": [100, 300], "to": [700, 300], "dither": false}); + s.execute("paint.gradient", p).unwrap(); + s +} + +#[test] +fn one_colour_with_a_transparency_ramp_follows_smooth() { + let s = drawn_colors(json!(["#ff0000"])); + for (x, want) in [(50, 255.0), (250, 179.0), (400, 100.0), (550, 35.0), (750, 0.0)] { + let got = alpha_at(&s, x); + assert!((got - want).abs() <= 2.0, "x={x}: alpha {got:.1}, want {want}"); + } +} + +#[test] +fn legacy_colours_keep_their_own_alpha() { + let s = drawn_colors(json!(["#ff000080", "#ff000080"])); + for (x, want) in [(50, 128.0), (400, 64.0), (750, 0.0)] { + let got = alpha_at(&s, x); + assert!((got - want).abs() <= 1.0, "x={x}: alpha {got:.1}, want {want}"); } } diff --git a/crates/engine/src/cmd/paint_cmds.rs b/crates/engine/src/cmd/paint_cmds.rs index e868c3a3334..498ec7aa546 100644 --- a/crates/engine/src/cmd/paint_cmds.rs +++ b/crates/engine/src/cmd/paint_cmds.rs @@ -145,36 +145,25 @@ fn gradient(s: &mut Session, p: &Value) -> Result { let stops = match p.get("method").and_then(Value::as_str).and_then(photocraft_io::GradientMethod::from_name) { Some(m) if stops.len() >= 2 => { let smoothness = (f(p, "smoothness", 100.0) / 100.0).clamp(0.0, 1.0); - // With transparency, the colour and opacity stops are baked apart: the colours by the - // method, the opacity by the method's own transparency curve (#12010). Merged stops - // would ease each of their sub-segments again and take the nearest stop's alpha. - let split = match gradients::tool_fill_stops(s, p)? { - Some((cs, os)) => Some((cs, os)), - None => { - // The legacy `colors` list, evenly spaced. - let os = gradients::transparency_param(p, "paint.gradient")?.unwrap_or_default(); - let colors: Vec<[f32; 4]> = - p.get("colors").and_then(Value::as_array).map(|a| a.iter().map(|v| color(Some(v), fg)).collect()).unwrap_or_default(); - let n = colors.len(); - let cs = colors - .iter() - .enumerate() - .map(|(i, c)| (if n > 1 { i as f32 / (n - 1) as f32 } else { 0.0 }, photocraft_color::Color::rgb(c[0], c[1], c[2]))) - .collect(); - Some((cs, os)) - } - }; + // Smooth at 100 % Smoothness bakes the colour and opacity stops apart: the colours by + // the method, the opacity by Smooth's measured transparency curve (#12010). Merged + // stops would take the nearest stop's alpha. The other methods and Smoothness values + // were not measured in the Gradient tool and keep the merged stops. + let split = if m == photocraft_io::GradientMethod::Smooth && smoothness >= 1.0 { split_stops(s, p, fg)? } else { None }; match split { - Some((cs, os)) if os.iter().any(|o| (o.1 - 1.0).abs() > 1e-6) && cs.len() >= 2 => { - let mids = vec![0.5; cs.len() - 1]; + Some((cs, os)) => { + let mids = vec![0.5; cs.len().saturating_sub(1)]; let colours: Vec<(f32, [f32; 4])> = photocraft_io::bake_gradient(cs, &mids, smoothness, m) .into_iter() - .map(|(t, c)| (t, [c.to_rgb()[0], c.to_rgb()[1], c.to_rgb()[2], 1.0])) + .map(|(t, c)| { + let rgb = c.to_rgb(); + (t, [rgb[0], rgb[1], rgb[2], 1.0]) + }) .collect(); let omids = vec![0.5; os.len().saturating_sub(1)]; - gradients::apply_opacity(colours, &photocraft_io::bake_gradient_opacity(os, &omids, smoothness, m)) + gradients::apply_opacity(colours, &photocraft_io::bake_gradient_smooth_opacity(os, &omids)) } - _ => { + None => { let colors = stops.iter().map(|(t, c)| (*t, photocraft_color::Color::rgba(c[0], c[1], c[2], c[3]))).collect(); let mids = vec![0.5; stops.len() - 1]; photocraft_io::bake_gradient(colors, &mids, smoothness, m) @@ -204,6 +193,36 @@ fn gradient(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// The Gradient tool's colour stops (opaque) and opacity stops kept apart, for Smooth's own +/// transparency curve. `None` when the opacity is constant, or when legacy `colors` carry their +/// own alpha (that case keeps the merged stops). A single colour stop spans the whole gradient. +fn split_stops(s: &Session, p: &Value, fg: [f32; 4]) -> Result> { + let (mut cs, os) = match gradients::tool_fill_stops(s, p)? { + Some(split) => split, + None => { + // The legacy `colors` list, evenly spaced. + let colors: Vec<[f32; 4]> = p.get("colors").and_then(Value::as_array).map(|a| a.iter().map(|v| color(Some(v), fg)).collect()).unwrap_or_default(); + if colors.iter().any(|c| c[3] < 1.0) { + return Ok(None); + } + let n = colors.len(); + let cs = colors + .iter() + .enumerate() + .map(|(i, c)| (if n > 1 { i as f32 / (n - 1) as f32 } else { 0.0 }, photocraft_color::Color::rgb(c[0], c[1], c[2]))) + .collect(); + (cs, gradients::transparency_param(p, "paint.gradient")?.unwrap_or_default()) + } + }; + if os.iter().all(|o| (o.1 - 1.0).abs() < 1e-6) { + return Ok(None); + } + if let [(_, c)] = cs.as_slice() { + cs = vec![(0.0, *c), (1.0, *c)]; + } + Ok(if cs.is_empty() { None } else { Some((cs, os)) }) +} + /// Paint helper command specs. pub fn specs() -> Vec { vec![ diff --git a/crates/io/src/gradient_bake.rs b/crates/io/src/gradient_bake.rs index c8d521a3e75..954dfdd48a9 100644 --- a/crates/io/src/gradient_bake.rs +++ b/crates/io/src/gradient_bake.rs @@ -195,11 +195,10 @@ const OPACITY_RESPONSE: f32 = 0.65; /// Dense linear opacity stops reproducing Photoshop's interpolation of a gradient's transparency /// (Smoothness, opacity midpoints and the method, see [`OPACITY_RESPONSE`]). Returns the input -/// unchanged when it already interpolates linearly. Smooth follows [`bake_smooth_opacity`]. +/// unchanged when it already interpolates linearly. Smooth keeps Classic's opacity curve here: it +/// was measured only in the Gradient tool at 100 % Smoothness ([`bake_smooth_opacity`]). pub fn bake_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32], smoothness: f32, method: Method) -> Vec<(f32, f32)> { - if method == Method::Smooth { - return bake_smooth_opacity(stops, midpoints); - } + let method = if method == Method::Smooth { Method::Classic } else { method }; let plain_mids = midpoints.iter().all(|m| (m - 0.5).abs() < 1e-3); let smoothness = if smoothness.is_finite() { smoothness.clamp(0.0, 1.0) } else { 0.0 }; if stops.len() < 2 || (smoothness <= 0.0 && method == Method::Classic && plain_mids) { @@ -246,22 +245,17 @@ const SMOOTH_OPACITY_GAMMA: f32 = 2.2; /// Smooth's transparency ramp: each opacity stop is a grey whose Oklab lightness is /// `(opacity^2.2)^(1/3)`, which the colours' measured Smooth easing ([`SMOOTH_EASE`]) crosses -/// segment by segment, and the linear value `y = L^3` comes out as opacity `y^(1/2.2)`. Smoothness -/// doesn't change Smooth; opacity midpoints still move each segment's centre. Constant opacity -/// comes back unchanged. -fn bake_smooth_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32]) -> Vec<(f32, f32)> { +/// segment by segment, and the linear value `y = L^3` comes out as opacity `y^(1/2.2)`. Measured +/// in the Gradient tool at 100 % Smoothness with 50 % midpoints, the only case that uses it. +/// Constant opacity comes back as it is, clamped to 0..=1. +pub fn bake_smooth_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32]) -> Vec<(f32, f32)> { + let clamp = |o: f32| if o.is_finite() { o.clamp(0.0, 1.0) } else { 1.0 }; if stops.len() < 2 || stops.windows(2).all(|w| w[0].1 == w[1].1) { - return stops; + return stops.into_iter().map(|(t, o)| (t, clamp(o))).collect(); } let mut s = stops; s.sort_by(|a, b| a.0.total_cmp(&b.0)); - let pts: Vec<(f32, [f32; 3])> = s - .iter() - .map(|(t, o)| { - let o = if o.is_finite() { o.clamp(0.0, 1.0) } else { 1.0 }; - (*t, [o.powf(SMOOTH_OPACITY_GAMMA).cbrt(); 3]) - }) - .collect(); + let pts: Vec<(f32, [f32; 3])> = s.iter().map(|(t, o)| (*t, [clamp(*o).powf(SMOOTH_OPACITY_GAMMA).cbrt(); 3])).collect(); const N: usize = 96; let mut baked: Vec<(f32, f32)> = (0..=N) .map(|k| { @@ -318,11 +312,10 @@ mod tests { } #[test] - fn plain_classic_and_constant_smooth_opacity_stay_as_stored() { + fn plain_classic_and_smooth_opacity_stay_as_stored() { let stops = vec![(1.0, 0.0), (0.0, 1.0)]; assert_eq!(bake_opacity(stops.clone(), &[0.5], 0.0, Method::Classic), stops); - let flat = vec![(0.0, 0.4), (1.0, 0.4)]; - assert_eq!(bake_opacity(flat.clone(), &[0.5], 0.0, Method::Smooth), flat); + assert_eq!(bake_opacity(stops.clone(), &[0.5], 0.0, Method::Smooth), stops); assert_eq!(bake_opacity(vec![(0.5, 0.3)], &[], 1.0, Method::Linear), vec![(0.5, 0.3)]); } @@ -431,6 +424,14 @@ mod tests { } /// `eval` guards its own stops instead of relying on `bake`'s two-stop check. + #[test] + fn smooth_opacity_clamps_constant_stops() { + let flat = vec![(0.0, 0.4), (1.0, 0.4)]; + assert_eq!(bake_smooth_opacity(flat.clone(), &[0.5]), flat); + assert_eq!(bake_smooth_opacity(vec![(0.0, 2.0), (1.0, 2.0)], &[0.5]), vec![(0.0, 1.0), (1.0, 1.0)]); + assert_eq!(bake_smooth_opacity(vec![(0.5, f32::NAN)], &[]), vec![(0.5, 1.0)]); + } + #[test] fn eval_with_fewer_than_two_stops_does_not_index_out_of_range() { assert_eq!(eval(&[], &[], 1.0, 0.5, Method::Smooth), [0.0; 3]); diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index b7c0b7bf9ac..6cee2d1c453 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -53,7 +53,7 @@ mod flat; mod gradient_bake; pub mod guides_map; mod png_steps; -pub use gradient_bake::{Method as GradientMethod, bake as bake_gradient, bake_opacity as bake_gradient_opacity}; +pub use gradient_bake::{Method as GradientMethod, bake as bake_gradient, bake_smooth_opacity as bake_gradient_smooth_opacity}; mod duotone_map; mod kra; pub mod linked; From 597b220cf008a6d9034f1f3ff76e259c2da1dfec Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 13:33:34 +0100 Subject: [PATCH 3/5] PR #12644: the eval doc comment back on its own test Co-Authored-By: x-labb Co-Authored-By: Claude Opus 5.5 --- crates/io/src/gradient_bake.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/io/src/gradient_bake.rs b/crates/io/src/gradient_bake.rs index c2666211d3a..6dee3dfd930 100644 --- a/crates/io/src/gradient_bake.rs +++ b/crates/io/src/gradient_bake.rs @@ -458,7 +458,6 @@ mod tests { assert!((at(&s, 0.25)[0] - 0.5).abs() < 0.01); } - /// `eval` guards its own stops instead of relying on `bake`'s two-stop check. #[test] fn smooth_opacity_clamps_constant_stops() { let flat = vec![(0.0, 0.4), (1.0, 0.4)]; @@ -467,6 +466,7 @@ mod tests { assert_eq!(bake_smooth_opacity(vec![(0.5, f32::NAN)], &[]), vec![(0.5, 1.0)]); } + /// `eval` guards its own stops instead of relying on `bake`'s two-stop check. #[test] fn eval_with_fewer_than_two_stops_does_not_index_out_of_range() { assert_eq!(eval(&[], &[], 1.0, 0.5, Method::Smooth), [0.0; 3]); From a65bea764be6d40cb6d83291ed341884bcf1cfbe Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 11 Nov 2026 14:10:18 +0100 Subject: [PATCH 4/5] PR #12644: pin today's ramp only at the reviewed points The x=175 value was a guess; main paints 255 there for the other methods. The 191/128/64 points from the review stay pinned. Co-Authored-By: x-labb Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/gradient_alpha_method_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/gradient_alpha_method_tests.rs b/crates/engine/src/cmd/gradient_alpha_method_tests.rs index b8327cb8cba..5b62b4778c2 100644 --- a/crates/engine/src/cmd/gradient_alpha_method_tests.rs +++ b/crates/engine/src/cmd/gradient_alpha_method_tests.rs @@ -73,7 +73,7 @@ fn opaque_gradients_paint_the_same_with_a_method() { fn unmeasured_methods_and_smoothness_keep_todays_ramp() { for extra in [json!({"method": "classic"}), json!({"method": "perceptual"}), json!({"method": "linear"}), json!({"method": "smooth", "smoothness": 50})] { let s = drawn(extra.clone()); - for (x, want) in [(175, 250.0), (250, 191.0), (400, 128.0), (550, 64.0)] { + for (x, want) in [(250, 191.0), (400, 128.0), (550, 64.0)] { let got = alpha_at(&s, x); assert!((got - want).abs() <= 1.0, "{extra} x={x}: alpha {got:.1}, want {want}"); } From 69ad84d9fbee119bde5d7b3a4dbc0ad9829f3f27 Mon Sep 17 00:00:00 2001 From: David Mann Date: Fri, 13 Nov 2026 02:43:21 +0100 Subject: [PATCH 5/5] PR #12644: keep Smooth's transparency gradient at 97 stops The colour and opacity bakes sample the same 97 positions, but apply_opacity cut every interval into four (385 stops), and paint_gradient scans the stops for every pixel. Multiply the alpha in at each shared position instead; other positions still go through apply_opacity. Raised by CodeRabbit. Co-Authored-By: x-labb Co-Authored-By: Claude Opus 5.5 --- .../src/cmd/gradient_alpha_method_tests.rs | 11 +++++ crates/engine/src/cmd/paint_cmds.rs | 41 +++++++++++++------ 2 files changed, 40 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/gradient_alpha_method_tests.rs b/crates/engine/src/cmd/gradient_alpha_method_tests.rs index 5b62b4778c2..26030610259 100644 --- a/crates/engine/src/cmd/gradient_alpha_method_tests.rs +++ b/crates/engine/src/cmd/gradient_alpha_method_tests.rs @@ -105,3 +105,14 @@ fn legacy_colours_keep_their_own_alpha() { assert!((got - want).abs() <= 1.0, "x={x}: alpha {got:.1}, want {want}"); } } + +// paint_gradient scans the stops for every pixel: Smooth's colour and opacity bakes share their +// 97 positions and must not be cut into four per interval (385 stops). +#[test] +fn smooth_transparency_keeps_one_stop_per_sampled_position() { + use photocraft_color::Color; + let black = Color::rgb(0.0, 0.0, 0.0); + let stops = super::paint_cmds::smooth_split_stops((vec![(0.0, black), (1.0, black)], vec![(0.0, 1.0), (1.0, 0.0)])); + assert_eq!(stops.len(), 97); + assert!((stops[0].1[3] - 1.0).abs() < 1e-6 && stops[96].1[3].abs() < 1e-6); +} diff --git a/crates/engine/src/cmd/paint_cmds.rs b/crates/engine/src/cmd/paint_cmds.rs index 00fdaf4c881..e4e0c2265ad 100644 --- a/crates/engine/src/cmd/paint_cmds.rs +++ b/crates/engine/src/cmd/paint_cmds.rs @@ -168,18 +168,7 @@ fn gradient(s: &mut Session, p: &Value) -> Result { // were not measured in the Gradient tool and keep the merged stops. let split = if m == photocraft_io::GradientMethod::Smooth && smoothness >= 1.0 { split_stops(s, p, fg)? } else { None }; match split { - Some((cs, os)) => { - let mids = vec![0.5; cs.len().saturating_sub(1)]; - let colours: Vec<(f32, [f32; 4])> = photocraft_io::bake_gradient(cs, &mids, smoothness, m) - .into_iter() - .map(|(t, c)| { - let rgb = c.to_rgb(); - (t, [rgb[0], rgb[1], rgb[2], 1.0]) - }) - .collect(); - let omids = vec![0.5; os.len().saturating_sub(1)]; - gradients::apply_opacity(colours, &photocraft_io::bake_gradient_smooth_opacity(os, &omids)) - } + Some(split) => smooth_split_stops(split), None => { let colors = stops.iter().map(|(t, c)| (*t, photocraft_color::Color::rgba(c[0], c[1], c[2], c[3]))).collect(); let mids = vec![0.5; stops.len() - 1]; @@ -210,6 +199,34 @@ fn gradient(s: &mut Session, p: &Value) -> Result { Ok(Value::Null) } +/// Smooth's colour and opacity stops baked apart, then joined. Both bakes sample the same +/// positions, so the alpha is multiplied in at each one: [`gradients::apply_opacity`] would cut +/// every interval into four (385 stops instead of 97), and `paint_gradient` scans the stops for +/// every pixel. Positions that differ still go through `apply_opacity`. +pub(crate) fn smooth_split_stops((cs, os): gradients::FillStops) -> gradients::Stops { + let mids = vec![0.5; cs.len().saturating_sub(1)]; + let colours: gradients::Stops = photocraft_io::bake_gradient(cs, &mids, 1.0, photocraft_io::GradientMethod::Smooth) + .into_iter() + .map(|(t, c)| { + let rgb = c.to_rgb(); + (t, [rgb[0], rgb[1], rgb[2], 1.0]) + }) + .collect(); + let omids = vec![0.5; os.len().saturating_sub(1)]; + let opacity = photocraft_io::bake_gradient_smooth_opacity(os, &omids); + if colours.len() != opacity.len() || colours.iter().zip(&opacity).any(|(c, o)| (c.0 - o.0).abs() > 1e-6) { + return gradients::apply_opacity(colours, &opacity); + } + colours + .into_iter() + .zip(opacity) + .map(|((t, mut c), (_, a))| { + c[3] = if a.is_finite() { a.clamp(0.0, 1.0) } else { 1.0 }; + (t, c) + }) + .collect() +} + /// The Gradient tool's colour stops (opaque) and opacity stops kept apart, for Smooth's own /// transparency curve. `None` when the opacity is constant, or when legacy `colors` carry their /// own alpha (that case keeps the merged stops). A single colour stop spans the whole gradient.