Use the measured Smooth transparency curve on layer masks

This commit is contained in:
yoriswind committed 2026-12-01 03:00:58 -08:00
1 parent 2e32ed7bb5
commit 0cafa5d862
3 files changed
+101 -4

No files matched your search

@@ -0,0 +1,63 @@
use serde_json::{Value, json};
const MASK_ROW: [f32; 21] =
[0.0, 15.0, 34.0, 53.0, 73.0, 93.0, 113.0, 131.0, 148.0, 164.0, 178.0, 191.0, 204.0, 215.0, 226.0, 235.0, 242.0, 248.0, 253.0, 255.0, 255.0];
fn row(mode: &str, depth: u8, target: &str, method: &str, stops: Value, opacity: Option<Value>) -> Vec<f32> {
let mut s = crate::session();
s.execute("file.new", json!({"width": 800, "height": 16, "mode": mode, "depth": depth, "background": "transparent"})).unwrap();
if target == "mask" {
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
}
let mut params = json!({"from": [100, 10], "to": [700, 10], "stops": stops, "method": method, "dither": false, "target": target});
if let Some(opacity) = opacity {
params["transparency"] = opacity;
}
s.execute("paint.gradient", params.clone()).unwrap();
let st = s.active().unwrap();
let surface = crate::channel_cmds::read_target_surface(&st.doc, st.active_layer, &params).unwrap();
(0..800).map(|x| if target == "mask" { surface.pixel(x, 10)[0] } else { surface.rgba(x, 10)[3] }).map(|value| value * 255.0).collect()
}
fn fade(mode: &str, depth: u8, target: &str, method: &str) -> Vec<f32> {
row(mode, depth, target, method, json!([[0, "#000000"], [1, "#000000"]]), Some(json!([[0, 100], [1, 0]])))
}
#[test]
fn smooth_transparency_follows_the_measured_layer_mask_fade() {
for mode in ["rgb", "gray", "cmyk", "lab"] {
for depth in [8, 16] {
let output = fade(mode, depth, "mask", "smooth");
for (i, expected) in MASK_ROW.into_iter().enumerate() {
let x = 100 + 30 * i;
assert!((output[x] - expected).abs() <= 2.0, "{mode} {depth}-bit, x={x}: {}, expected {expected}", output[x]);
}
assert!(output.windows(2).all(|w| w[0] <= w[1]));
assert_eq!(output[50], 0.0);
assert_eq!(output[750], 255.0);
}
}
}
#[test]
fn smooth_mask_fade_keeps_existing_pixel_deep_mask_and_other_method_curves() {
let pixels = fade("rgb", 8, "pixels", "smooth");
let deep_mask = fade("rgb", 32, "mask", "smooth");
for (x, alpha) in [(50, 255.0), (250, 179.0), (400, 100.0), (550, 35.0), (750, 0.0)] {
assert!((pixels[x] - alpha).abs() <= 2.0, "pixel alpha at {x}: {}", pixels[x]);
assert!((deep_mask[x] - (255.0 - alpha)).abs() <= 2.0, "float mask at {x}: {}", deep_mask[x]);
}
for method in ["classic", "perceptual", "linear"] {
let pixels = fade("rgb", 8, "pixels", method);
let mask = fade("rgb", 8, "mask", method);
for x in [50, 250, 400, 550, 750] {
assert!((pixels[x] + mask[x] - 255.0).abs() <= 1.0, "{method} at {x}: pixel {}, mask {}", pixels[x], mask[x]);
}
}
let colors = json!([[0, "#000000"], [1, "#ffffff"]]);
let opaque = row("rgb", 16, "mask", "smooth", colors.clone(), None);
assert_eq!(opaque, row("rgb", 16, "mask", "smooth", colors, Some(json!([[0, 100], [1, 100]]))));
assert_eq!((opaque[50], opaque[750]), (0.0, 255.0));
}
+20 -2
View File
@@ -181,6 +181,16 @@ fn gradient(s: &mut Session, p: &Value) -> Result<Value> {
// 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(split)
if crate::channel_cmds::target_of(p) == crate::channel_cmds::Target::Mask
&& s.active().is_some_and(|st| {
use photocraft_color::{ColorMode, SampleType};
matches!(st.doc.mode, ColorMode::Rgb | ColorMode::Grayscale | ColorMode::Cmyk | ColorMode::Lab)
&& matches!(st.doc.depth, SampleType::U8 | SampleType::U16)
}) =>
{
smooth_split_stops_with(split, photocraft_io::gradient_bake::bake_smooth_mask_opacity)
}
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();
@@ -234,7 +244,11 @@ pub(crate) const GRADIENT_MASK_STEP: &str = "Draw gradient on mask";
/// 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 {
pub(crate) fn smooth_split_stops(stops: gradients::FillStops) -> gradients::Stops {
smooth_split_stops_with(stops, photocraft_io::bake_gradient_smooth_opacity)
}
fn smooth_split_stops_with((cs, os): gradients::FillStops, bake_opacity: impl FnOnce(Vec<(f32, f32)>, &[f32]) -> Vec<(f32, f32)>) -> 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()
@@ -244,7 +258,7 @@ pub(crate) fn smooth_split_stops((cs, os): gradients::FillStops) -> gradients::S
})
.collect();
let omids = vec![0.5; os.len().saturating_sub(1)];
let opacity = photocraft_io::bake_gradient_smooth_opacity(os, &omids);
let opacity = bake_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);
}
@@ -323,5 +337,9 @@ mod bucket_no_op_history_tests;
#[cfg(test)]
mod bucket_bitmap_tests;
#[cfg(test)]
#[path = "gradient_mask_smooth_transparency_tests.rs"]
mod gradient_mask_smooth_transparency_tests;
#[cfg(test)]
mod bucket_behind_tests;
+18 -2
View File
@@ -366,19 +366,35 @@ const SMOOTH_OPACITY_GAMMA: f32 = 2.2;
/// 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)> {
bake_smooth_opacity_with(stops, midpoints, |o| o.powf(SMOOTH_OPACITY_GAMMA).cbrt(), |l| l.powi(3).powf(1.0 / SMOOTH_OPACITY_GAMMA))
}
/// Smooth's opacity response for the Gradient tool on an 8- or 16-bit layer mask. The same
/// Smooth easing with a lightness response of `L^1.75` fits the measured mask fade (#18670).
pub fn bake_smooth_mask_opacity(stops: Vec<(f32, f32)>, midpoints: &[f32]) -> Vec<(f32, f32)> {
const MASK_POWER: f32 = 1.75;
bake_smooth_opacity_with(stops, midpoints, |o| o.powf(1.0 / MASK_POWER), |l| l.powf(MASK_POWER))
}
fn bake_smooth_opacity_with(
stops: Vec<(f32, f32)>,
midpoints: &[f32],
to_lightness: impl Fn(f32) -> f32,
from_lightness: impl Fn(f32) -> 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.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)| (*t, [clamp(*o).powf(SMOOTH_OPACITY_GAMMA).cbrt(); 3])).collect();
let pts: Vec<(f32, [f32; 3])> = s.iter().map(|(t, o)| (*t, [to_lightness(clamp(*o)); 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 })
(t, if l.is_finite() { from_lightness(l.clamp(0.0, 1.0)) } else { 1.0 })
})
.collect();
baked.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6);