Skip to content

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

Effects: Gradient Overlay transparency follows Smoothness, midpoints and method (#1954)

David Mann1ce9a87b6b10
diff --git a/crates/io/src/blocks.rs b/crates/io/src/blocks.rs
index 87fda102f..dbd4cfe84 100644
--- a/crates/io/src/blocks.rs
+++ b/crates/io/src/blocks.rs
@@ -252,7 +252,8 @@ pub(crate) fn gradient_style_value(s: GradientStyle) -> Value {
pub(crate) type Stops = (Vec<(f32, Color)>, Vec<(f32, f32)>);
/// Stops of a `Grdn` descriptor, baked to Photoshop's interpolation (smoothness `Intr`, stop
-/// midpoints, and the parent's interpolation method when given, see [`gradient_method`]).
+/// midpoints, and the parent's interpolation method when given, see [`gradient_method`]); the
+/// opacity stops as [`baked_opacity_stops`].
pub(crate) fn gradient_stops_with(grad: &Descriptor, method: Option<&[u8]>) -> Stops {
let raw = gradient_stops_raw(grad);
let stops = if raw.stops.len() >= 2 {
@@ -260,7 +261,7 @@ pub(crate) fn gradient_stops_with(grad: &Descriptor, method: Option<&[u8]>) -> S
} else {
raw.stops
};
- (stops, raw.opacity)
+ (stops, baked_opacity_stops(grad, method))
}
/// A `Grdn` descriptor's stops as stored: colour stops (sorted), the midpoint of each segment
@@ -376,26 +377,27 @@ pub(crate) fn gradient_desc_with(stops: &[(f32, Color)], opacity: &[(f32, f32)],
.with("Trns", Value::List(trns))
}
-/// Opacity stops of a `Grdn` descriptor with Photoshop's smoothness and midpoints applied (the
-/// same curve as the colour stops, Classic interpolation), densely sampled.
-fn smoothed_opacity_stops(grad: &Descriptor) -> Vec<(f32, f32)> {
+/// Opacity stops of a `Grdn` descriptor with Photoshop's smoothness, opacity midpoints and
+/// interpolation method applied (densely sampled; as stored when the interpolation is plain).
+/// Gradient fill layers and the gradient layer effects share it: Photoshop renders their
+/// transparency identically.
+fn baked_opacity_stops(grad: &Descriptor, method: Option<&[u8]>) -> Vec<(f32, f32)> {
let mut stops = Vec::new();
let mut mids = Vec::new();
if let Some(Value::List(items)) = grad.get("Trns") {
for it in items {
if let Value::Descriptor(s) = it {
- let a = num(s.get("Opct")).unwrap_or(100.0) as f32 / 100.0;
- stops.push((num(s.get("Lctn")).unwrap_or(0.0) as f32 / 4096.0, Color::rgba(a, a, a, 1.0)));
+ stops.push((num(s.get("Lctn")).unwrap_or(0.0) as f32 / 4096.0, num(s.get("Opct")).unwrap_or(100.0) as f32 / 100.0));
mids.push(num(s.get("Mdpn")).unwrap_or(50.0) as f32 / 100.0);
}
}
}
+ // Midpoint k applies to the segment after stop k (stored on the stop that ends it).
let mut order: Vec<usize> = (0..stops.len()).collect();
order.sort_by(|a, b| stops[*a].0.total_cmp(&stops[*b].0));
let mids: Vec<f32> = order.iter().skip(1).filter_map(|i| mids.get(*i).copied()).collect();
let smooth = num(grad.get("Intr")).map_or(0.0, |v| (v / 4096.0) as f32);
- let baked = if stops.len() >= 2 { crate::gradient_bake::bake(stops, &mids, smooth, crate::gradient_bake::Method::Classic) } else { stops };
- baked.into_iter().map(|(t, c)| (t, c.to_rgb()[0])).collect()
+ crate::gradient_bake::bake_opacity(stops, &mids, smooth, crate::gradient_bake::Method::from_code(method))
}
/// Parses a fill block (`SoCo`, `GdFl`, `PtFl`).
@@ -415,9 +417,9 @@ pub fn fill_from_desc(key: &[u8; 4], d: &Descriptor) -> Option<Fill> {
let scale = num(d.get("Scl ")).map_or(1.0, |v| v as f32 / 100.0);
let raw = get_desc(d, "Grad").map(|g| gradient_stops_editable(g, gradient_method(d)));
let (mut stops, midpoints) = raw.map(|r| (r.stops, r.mids)).unwrap_or_default();
- // Opacity stops with Photoshop's smoothness and opacity midpoints applied (raw when
- // the interpolation is plain); none when fully opaque.
- let mut opacity_stops = get_desc(d, "Grad").map(smoothed_opacity_stops).unwrap_or_default();
+ // Opacity stops with Photoshop's smoothness, opacity midpoints and method applied
+ // (raw when the interpolation is plain); none when fully opaque.
+ let mut opacity_stops = get_desc(d, "Grad").map(|g| baked_opacity_stops(g, gradient_method(d))).unwrap_or_default();
if opacity_stops.iter().all(|o| o.1 >= 1.0 - 1e-4) {
opacity_stops.clear();
}
diff --git a/crates/io/src/effects_map.rs b/crates/io/src/effects_map.rs
index 00815e2c8..38d22e372 100644
--- a/crates/io/src/effects_map.rs
+++ b/crates/io/src/effects_map.rs
@@ -811,6 +811,84 @@ mod tests {
}
}
+ /// A Gradient Overlay `lfx2` laid out as Photoshop writes it: one black colour, opacity
+ /// 100 → 0 % with the opacity midpoint `mid` (%), Smoothness `intr` (0..4096) and the method
+ /// enum `gs99` (Photoshop 25.1's key in layer effects; codes `Gcls`, `Lnr `, `Perc`).
+ fn overlay_lfx2(mid: i32, intr: f64, method: &str) -> Vec<u8> {
+ let black = || Descriptor::new("RGBC").with("Rd ", Value::Double(0.0)).with("Grn ", Value::Double(0.0)).with("Bl ", Value::Double(0.0));
+ let clr = |loc: i32| {
+ Value::Descriptor(
+ Descriptor::new("Clrt")
+ .with("Clr ", Value::Descriptor(black()))
+ .with("Type", Value::Enumerated { type_id: Id::new("Clry"), value: Id::new("UsrS") })
+ .with("Lctn", Value::Integer(loc))
+ .with("Mdpn", Value::Integer(50)),
+ )
+ };
+ let trn = |loc: i32, op: f32, mid: i32| {
+ Value::Descriptor(Descriptor::new("TrnS").with("Opct", unit(b"#Prc", op)).with("Lctn", Value::Integer(loc)).with("Mdpn", Value::Integer(mid)))
+ };
+ let grad = Descriptor::new("Grdn")
+ .with("GrdF", Value::Enumerated { type_id: Id::new("GrdF"), value: Id::new("CstS") })
+ .with("Intr", Value::Double(intr))
+ .with("Clrs", Value::List(vec![clr(0), clr(4096)]))
+ .with("Trns", Value::List(vec![trn(0, 100.0, 50), trn(4096, 0.0, mid)]));
+ let fx = Descriptor::new("GrFl")
+ .with("enab", Value::Boolean(true))
+ .with("Grad", Value::Descriptor(grad))
+ .with("Angl", unit(b"#Ang", 0.0))
+ .with("gs99", Value::Enumerated { type_id: Id::new("gradientInterpolationMethodType"), value: Id::new(method) });
+ let d = Descriptor::new("null").with("masterFXSwitch", Value::Boolean(true)).with("GrFl", Value::Descriptor(fx));
+ let mut data = 0u32.to_be_bytes().to_vec();
+ data.extend(VersionedDescriptor { version: 16, descriptor: d }.to_bytes());
+ data
+ }
+
+ fn overlay_opacity(data: &[u8]) -> Vec<(f32, f32)> {
+ let (_, fx) = parse_lfx2(data).unwrap();
+ let Some(Effect::GradientOverlay { gradient, .. }) = fx.first() else { panic!("overlay: {fx:?}") };
+ gradient.opacity_stops.clone()
+ }
+
+ fn opacity_at(o: &[(f32, f32)], t: f32) -> f32 {
+ let i = o.windows(2).position(|w| t >= w[0].0 && t <= w[1].0).unwrap();
+ o[i].1 + (o[i + 1].1 - o[i].1) * (t - o[i].0) / (o[i + 1].0 - o[i].0)
+ }
+
+ /// #1954: the overlay's transparency follows Smoothness, the opacity midpoints and the method
+ /// like a gradient fill layer's (Photoshop 25.1 renders both identically; the values are its
+ /// composites at t = 0.25 and 0.5).
+ #[test]
+ fn gradient_overlay_opacity_follows_smoothness_midpoint_and_method() {
+ let at = |mid, intr, method: &str, t| opacity_at(&overlay_opacity(&overlay_lfx2(mid, intr, method)), t);
+ // Plain Classic stays the linear fade it is stored as.
+ assert_eq!(overlay_opacity(&overlay_lfx2(50, 0.0, "Gcls")), vec![(0.0, 1.0), (1.0, 0.0)]);
+ // Midpoint 25 %: half transparent a quarter of the way.
+ assert!((at(25, 0.0, "Gcls", 0.25) - 0.5).abs() < 0.01);
+ // Smoothness 100 % eases the ends (Photoshop: 0.796 at a quarter).
+ assert!((at(50, 4096.0, "Gcls", 0.25) - 0.796).abs() < 0.015);
+ // The method bends the transparency ramp too, not only the colours (Photoshop at the
+ // middle: 0.631 Linear, 0.255 Perceptual).
+ assert!((at(50, 0.0, "Lnr ", 0.5) - 0.631).abs() < 0.015);
+ assert!((at(50, 0.0, "Perc", 0.5) - 0.255).abs() < 0.015);
+ assert!((at(25, 4096.0, "Perc", 0.25) - 0.255).abs() < 0.015);
+ }
+
+ /// A regenerated `lfx2` carries the baked ramp as plain (Classic, Smoothness 0) stops, so it
+ /// reads back unchanged.
+ #[test]
+ fn baked_overlay_opacity_round_trips() {
+ let data = overlay_lfx2(25, 4096.0, "Perc");
+ let (master, fx) = parse_lfx2(&data).unwrap();
+ let a = overlay_opacity(&data);
+ let b = overlay_opacity(&write_lfx2(master, &fx));
+ assert!(a.len() > 2);
+ assert_eq!(a.len(), b.len());
+ for (x, y) in a.iter().zip(&b) {
+ assert!((x.0 - y.0).abs() < 1e-3 && (x.1 - y.1).abs() < 1e-4, "{x:?} vs {y:?}");
+ }
+ }
+
#[test]
fn garbage_is_none() {
assert!(parse_lfx2(&[0, 0]).is_none());
diff --git a/crates/io/src/gradient_bake.rs b/crates/io/src/gradient_bake.rs
index 0d34816a7..ca4c82e9f 100644
--- a/crates/io/src/gradient_bake.rs
+++ b/crates/io/src/gradient_bake.rs
@@ -185,10 +185,116 @@ pub fn bake(stops: Vec<(f32, Color)>, midpoints: &[f32], smoothness: f32, method
out
}
+/// Exponent of Photoshop's opacity response for Perceptual and Linear gradients: the opacity
+/// stops enter the method's space as if they were sRGB grey levels (Linear: linear light;
+/// Perceptual: Oklab L), and the interpolated linear-light value `y` comes out as opacity
+/// `y^0.65`. Fitted on Photoshop 25.1 (scripted Gradient Overlays and gradient fill layers, which
+/// render identical pixels: 100 → 0 % and 100 → 20 → 90 % ramps with Smoothness 0 and 100 and
+/// midpoints 25 and 50 %, within 0.015 of every 8-bit sample; a flat 60 % renders as 47 %).
+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 (Photoshop 25.1 has no Smooth method).
+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 };
+ 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) {
+ return stops;
+ }
+ let into = |o: f32| -> f32 {
+ let o = if o.is_finite() { o.clamp(0.0, 1.0) } else { 1.0 };
+ match method {
+ Method::Linear => lin(o),
+ Method::Perceptual => lin(o).cbrt(),
+ Method::Classic | Method::Smooth => o,
+ }
+ };
+ let out = |v: f32| -> f32 {
+ let v = if v.is_finite() { v } else { 1.0 };
+ let y = match method {
+ Method::Linear => v,
+ Method::Perceptual => v.max(0.0).powi(3),
+ Method::Classic | Method::Smooth => return v.clamp(0.0, 1.0),
+ };
+ y.clamp(0.0, 1.0).powf(OPACITY_RESPONSE)
+ };
+ 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, [into(*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;
+ // Smoothness and midpoints shape the curve as for Classic colours, in the method's space.
+ (t, out(eval(&pts, midpoints, smoothness, t, Method::Classic)[0]))
+ })
+ .collect();
+ baked.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-6);
+ baked
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ fn opacity_at(stops: &[(f32, f32)], t: f32) -> f32 {
+ let i = stops.windows(2).position(|w| t >= w[0].0 && t <= w[1].0).unwrap();
+ let (a, b) = (stops[i], stops[i + 1]);
+ a.1 + (b.1 - a.1) * (t - a.0) / (b.0 - a.0)
+ }
+
+ /// Photoshop 25.1 Gradient Overlay samples (black, Normal, over white; a 256 px wide linear
+ /// gradient, pixel `x` at t = (x + 0.5) / 256): opacity stops, midpoints, Smoothness, method,
+ /// and (x, opacity) pairs read from the composite.
+ #[test]
+ fn opacity_matches_photoshop_samples() {
+ type Case = (&'static [(f32, f32)], &'static [f32], f32, Method, &'static [(f32, f32)]);
+ let ramp: &[(f32, f32)] = &[(0.0, 1.0), (1.0, 0.0)];
+ let three: &[(f32, f32)] = &[(0.0, 1.0), (0.25, 0.2), (1.0, 0.9)];
+ let cases: [Case; 9] = [
+ (ramp, &[0.5], 0.0, Method::Linear, &[(64.0, 0.827), (128.0, 0.631), (192.0, 0.400)]),
+ (ramp, &[0.5], 0.0, Method::Perceptual, &[(64.0, 0.565), (128.0, 0.255), (192.0, 0.063)]),
+ (ramp, &[0.25], 1.0, Method::Classic, &[(32.0, 0.796), (64.0, 0.502), (128.0, 0.298), (192.0, 0.122)]),
+ (ramp, &[0.25], 1.0, Method::Linear, &[(32.0, 0.859), (64.0, 0.631), (128.0, 0.447), (192.0, 0.247)]),
+ (ramp, &[0.25], 1.0, Method::Perceptual, &[(32.0, 0.639), (64.0, 0.255), (128.0, 0.090), (192.0, 0.016)]),
+ (ramp, &[0.5], 1.0, Method::Classic, &[(64.0, 0.796), (128.0, 0.502), (192.0, 0.204)]),
+ (three, &[0.5, 0.5], 1.0, Method::Classic, &[(32.0, 0.557), (64.0, 0.200), (160.0, 0.502)]),
+ (three, &[0.5, 0.5], 1.0, Method::Perceptual, &[(32.0, 0.392), (64.0, 0.106), (160.0, 0.341)]),
+ (three, &[0.5, 0.5], 0.0, Method::Linear, &[(32.0, 0.647), (64.0, 0.106), (160.0, 0.557)]),
+ ];
+ for (stops, mids, smooth, m, samples) in cases {
+ let baked = bake_opacity(stops.to_vec(), mids, smooth, m);
+ for (x, want) in samples {
+ let got = opacity_at(&baked, (x + 0.5) / 256.0);
+ assert!((got - want).abs() < 0.015, "{m:?} smooth {smooth} mids {mids:?} x {x}: {got} vs Photoshop {want}");
+ }
+ }
+ // A flat 60 % renders as 47 % in Linear and Perceptual, 60 % in Classic.
+ for (m, want) in [(Method::Linear, 0.471), (Method::Perceptual, 0.471)] {
+ let baked = bake_opacity(vec![(0.0, 0.6), (1.0, 0.6)], &[0.5], 0.0, m);
+ assert!(baked.iter().all(|o| (o.1 - want).abs() < 0.01), "{m:?}: {baked:?}");
+ }
+ }
+
+ #[test]
+ 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);
+ 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)]);
+ }
+
+ #[test]
+ fn opacity_bake_survives_hostile_values() {
+ for m in [Method::Classic, Method::Perceptual, Method::Linear, Method::Smooth] {
+ let baked = bake_opacity(vec![(f32::NAN, f32::INFINITY), (1.0, f32::NAN), (0.5, -3.0)], &[f32::NAN, 2.0], f32::NAN, m);
+ assert!(baked.iter().all(|o| (0.0..=1.0).contains(&o.1)), "{m:?}: {baked:?}");
+ }
+ }
+
fn at(stops: &[(f32, Color)], t: f32) -> [f32; 3] {
let i = stops.windows(2).position(|w| t >= w[0].0 && t <= w[1].0).unwrap();
let (a, b) = (&stops[i], &stops[i + 1]);