Change the 'Mask' node's Luminance weights to 0.3, 0.59, 0.11, and add a Luminance (SVG) mode (#5062)

This commit is contained in:
Keavon Chambers authored and GitHub committed 2026-12-02 14:50:26 -08:00
1 parent ebc49b40fc
commit e27119b58b
12 files changed
+141 -44

No files matched your search

@@ -300,7 +300,7 @@ impl Adjustment {
pub enum DesaturateMethod {
/// Light level of the color, the Y (luminance) of Rec. 709, which weights the linear-light RGB channels by `0.2126, 0.7152, 0.0722`.
///
/// Accessibility contrast ratios and SVG luminance masks use this.
/// Accessibility contrast ratios use this.
#[default]
#[label("Luminance (Rec. 709)")]
#[cfg_attr(feature = "serde", serde(alias = "SRGB"))]
+49 -12
View File
@@ -7,26 +7,45 @@ use dyn_any::DynAny;
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
#[widget(Radio)]
#[widget(Dropdown)]
pub enum MaskMode {
/// White shows the content and black hides it, with transparent areas also hiding it.
/// White shows the content and black hides it, with transparent areas also hiding it. Brightness is judged by weighting the gamma-encoded RGB channels by `0.3, 0.59, 0.11`.
///
/// This matches the Luminosity family of blend modes.
#[default]
Luminance,
/// Like Luminance, but brightness is judged by weighting the gamma-encoded RGB channels by `0.2125, 0.7154, 0.0721`, so greens show more of the content, and reds and blues less.
///
/// SVG luminance masks use this, so masks brought in from SVG keep their look.
#[label("Luminance (SVG)")]
LuminanceSvg,
/// Opaque areas show the content and transparent areas hide it, whatever their colors.
Alpha,
}
/// The weights of the red, green, and blue channels in a mask's luminance, those of SVG's `luminanceToAlpha`, taken on gamma-encoded channels as an SVG mask does.
pub const MASK_LUMINANCE_WEIGHTS: [f32; 3] = [0.2125, 0.7154, 0.0721];
/// The weights of the red, green, and blue channels in the luminance of a mask in the `Luminance` mode, taken on gamma-encoded channels, those the Luminosity family of blend modes uses.
pub const MASK_LUMINANCE_WEIGHTS: [f32; 3] = [0.3, 0.59, 0.11];
/// The weights of the red, green, and blue channels in SVG's `luminanceToAlpha`, taken on gamma-encoded channels as an SVG mask does.
/// They weigh the luminance of a mask in the `LuminanceSvg` mode and of the maps that vary other effects, which SVG reads by `luminanceToAlpha`.
pub const SVG_LUMINANCE_WEIGHTS: [f32; 3] = [0.2125, 0.7154, 0.0721];
impl MaskMode {
/// The weights of a mask graphic's premultiplied gamma-encoded red, green, blue, and alpha channels that sum to how much it shows the content.
pub fn channel_weights(self) -> [f32; 4] {
let ([red, green, blue], alpha) = match self {
Self::Luminance => (MASK_LUMINANCE_WEIGHTS, 0.),
Self::LuminanceSvg => (SVG_LUMINANCE_WEIGHTS, 0.),
Self::Alpha => ([0.; 3], 1.),
};
[red, green, blue, alpha]
}
}
/// How much a pixel of the mask graphic, given as premultiplied gamma-encoded channels, shows the content, from 0 to 1.
/// The luminance of premultiplied channels is that of the straight color times its alpha, so transparent areas hide the content in either mode.
pub fn mask_coverage([red, green, blue, alpha]: [f32; 4], mode: MaskMode) -> f32 {
let [red_weight, green_weight, blue_weight] = MASK_LUMINANCE_WEIGHTS;
let coverage = match mode {
MaskMode::Luminance => red * red_weight + green * green_weight + blue * blue_weight,
MaskMode::Alpha => alpha,
};
/// The luminance of premultiplied channels is that of the straight color times its alpha, so transparent areas hide the content in every mode.
pub fn mask_coverage(channels: [f32; 4], mode: MaskMode) -> f32 {
let coverage: f32 = channels.into_iter().zip(mode.channel_weights()).map(|(channel, weight)| channel * weight).sum();
coverage.clamp(0., 1.)
}
@@ -89,7 +108,7 @@ pub fn masked_radius_blur_levels(radius: f64, pixels_per_length: f64) -> Vec<f64
/// The 8-bit code of a masked radius blur map's luminance at a pixel, given as premultiplied gamma-encoded channels, which picks the pixel's interpolation between blurs.
pub fn masked_radius_blur_code(channels: [f32; 4]) -> u8 {
(mask_coverage(channels, MaskMode::Luminance) * 255.).round() as u8
(mask_coverage(channels, MaskMode::LuminanceSvg) * 255.).round() as u8
}
/// For a masked radius blur map's luminance as an 8-bit `code`, the level below it among the `levels` (from [`masked_radius_blur_levels`]) and how many of 255 parts of the interpolation the level above takes, the rest going to the level below.
@@ -120,3 +139,21 @@ pub fn masked_radius_blur_weight(level: usize, code: u8, levels: &[f64]) -> u32
_ => 0,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn luminance_modes_weigh_pure_red_green_and_blue_by_their_own_weights() {
let level = |channels: [f32; 4], mode| (mask_coverage(channels, mode) * 255.).round() as u8;
let primaries = [[1., 0., 0., 1.], [0., 1., 0., 1.], [0., 0., 1., 1.]];
assert_eq!(primaries.map(|primary| level(primary, MaskMode::Luminance)), [77, 150, 28]);
assert_eq!(primaries.map(|primary| level(primary, MaskMode::LuminanceSvg)), [54, 182, 18]);
assert_eq!(primaries.map(|primary| level(primary, MaskMode::Alpha)), [255; 3]);
// Premultiplied channels count the color by its alpha
assert_eq!(level([0., 0.5, 0., 0.5], MaskMode::Luminance), 75);
}
}
@@ -1076,10 +1076,10 @@ pub enum DisplaceMode {
/// For PSD interop, the 8-bit level of a displacement map's luminance that moves nothing, which black lies the farthest from.
pub const DISPLACEMENT_NEUTRAL_LEVEL: f64 = 128.;
/// The share of its distance that a displacement map's premultiplied gamma-encoded `color` moves the content, by its luminance as a mask reads it:
/// The share of its distance that a displacement map's premultiplied gamma-encoded `color` moves the content, by its luminance as an SVG luminance mask reads it:
/// -1 at black, none at the neutral level, and 127/128 at white. Where the map is translucent it's seen over the neutral level.
pub fn displacement_amount(color: [f32; 4]) -> f64 {
let luminance = mask_coverage(color, MaskMode::Luminance) as f64;
let luminance = mask_coverage(color, MaskMode::LuminanceSvg) as f64;
let level = luminance * 255. + DISPLACEMENT_NEUTRAL_LEVEL * (1. - color[3] as f64);
(level - DISPLACEMENT_NEUTRAL_LEVEL) / DISPLACEMENT_NEUTRAL_LEVEL
}
@@ -2849,7 +2849,7 @@ mod tests {
assert!((displacement_amount([0., 0., 0., 1.]) + 1.).abs() < 1e-5);
assert_eq!(displacement_amount([0., 0., 0., 0.]), 0.);
// A color moves the content by its luminance, as a mask reads it, and a pixel reads from the opposite way
// A color moves the content by its luminance, as an SVG luminance mask reads it, and a pixel reads from the opposite way
let red = displacement_amount([1., 0., 0., 1.]);
assert!((red - (0.2125 * 255. - DISPLACEMENT_NEUTRAL_LEVEL) / DISPLACEMENT_NEUTRAL_LEVEL).abs() < 1e-5);
assert_eq!(map_displacement([1., 0., 0., 1.], DVec2::new(10., -4.)), DVec2::new(10., -4.) * -red);
@@ -90,7 +90,7 @@ pub(crate) fn masked_radius_blur_codes(colors: &[Color]) -> Vec<u8> {
pub(crate) fn masked_box_blur_luminances(colors: &[Color]) -> Vec<f32> {
let luminance = |color: Color| {
let [red, green, blue, alpha] = color.to_gamma_srgb_channels();
mask_coverage([red * alpha, green * alpha, blue * alpha, alpha], MaskMode::Luminance).clamp(0., 1.)
mask_coverage([red * alpha, green * alpha, blue * alpha, alpha], MaskMode::LuminanceSvg).clamp(0., 1.)
};
colors.iter().map(|&color| half::f16::from_f32(luminance(color)).to_f32()).collect()
}
+37 -2
View File
@@ -1679,7 +1679,7 @@ fn write_svg_effects_filter_on_lattice(
let luminance = match paint_markup {
Some(markup) => {
let image = primitives.paint_image(markup, region);
primitives.mask_coverage(&image, MaskMode::Luminance)
primitives.mask_coverage(&image, MaskMode::LuminanceSvg)
}
None => primitives.map(map_capture(0)),
};
@@ -8497,7 +8497,8 @@ mod tests {
let mut defs = String::new();
write_svg_effects_filter(&mut defs, &effects, &layers, 0, 1., 1., bounds, 0, &paints, leading.end..trailing.start, 1.).unwrap();
assert_eq!(defs.matches("<feImage").count(), 1, "{defs}");
assert!(defs.contains(r#"type="luminanceToAlpha""#) && defs.contains(r#"stdDeviation="2 2""#), "{defs}");
assert!(defs.contains(r#"type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0""#), "{defs}");
assert!(defs.contains(r#"stdDeviation="2 2""#) && !defs.contains("luminanceToAlpha"), "{defs}");
assert!(defs.contains(r#"<feFuncA type="linear" slope="-0.5" intercept="1" />"#), "{defs}");
// The two trailing masks become one, which shows the content the second masks, while the leading one stands alone
@@ -8526,6 +8527,40 @@ mod tests {
assert!(!defs.contains("<feImage") && defs.contains(r##"<feFlood flood-color="#000000" flood-opacity="1""##), "{defs}");
}
#[test]
fn svg_mask_coverage_weighs_luminance_as_the_cpu_and_gpu_do_in_each_mode() {
use graphic_types::MaskMode;
use graphic_types::masks::{SVG_LUMINANCE_WEIGHTS, mask_coverage};
let coverage_markup = |mode| {
let mut primitives = SvgFilterPrimitives::default();
primitives.mask_coverage("image", mode);
primitives.markup
};
let primaries = [[1., 0., 0., 1.], [0., 1., 0., 1.], [0., 0., 1., 1.]];
// The default mode's matrix leaves the color empty and takes the luminance of pure red, green, and blue into alpha as the CPU and GPU do
let markup = coverage_markup(MaskMode::Luminance);
let values = markup.split(r#"type="matrix" values=""#).nth(1).and_then(|rest| rest.split('"').next()).unwrap_or_default();
let values: Vec<f32> = values.split(' ').filter_map(|value| value.parse().ok()).collect();
assert!(values.len() == 20 && values[..15].iter().all(|&value| value == 0.), "{markup}");
let alpha_row = |channels: [f32; 4]| (0..4).map(|channel| values[15 + channel] * channels[channel]).sum::<f32>() + values[19];
let levels = primaries.map(|primary| (alpha_row(primary) * 255.).round() as u8);
assert_eq!(levels, [77, 150, 28], "{markup}");
assert_eq!(levels, primaries.map(|primary| (mask_coverage(primary, MaskMode::Luminance) * 255.).round() as u8));
// The SVG mode is SVG's own `luminanceToAlpha`, whose weights the CPU and GPU take
let markup = coverage_markup(MaskMode::LuminanceSvg);
assert!(markup.contains(r#"type="luminanceToAlpha""#) && !markup.contains(r#"type="matrix""#), "{markup}");
assert_eq!(SVG_LUMINANCE_WEIGHTS, [0.2125, 0.7154, 0.0721]);
// Both take the luminance over black, which counts the color by its alpha, while the alpha mode takes the image as it is
for mode in [MaskMode::Luminance, MaskMode::LuminanceSvg] {
assert!(coverage_markup(mode).contains(r#"in="image" in2="effect-1" operator="over""#), "{mode:?}");
}
assert!(coverage_markup(MaskMode::Alpha).is_empty());
}
#[test]
fn svg_leading_masks_wrap_the_content_every_layer_draws() {
use graphic_types::{EffectOperation, MaskMode};
@@ -8,7 +8,7 @@ use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
use core_types::uuid::generate_uuid;
use glam::{DAffine2, DVec2};
use graphic_types::effects::{EffectOperation, Effects, spans_along_axes};
use graphic_types::masks::{MaskMode, mask_density_line, mask_feather_sigma, masked_radius_blur_weight};
use graphic_types::masks::{MASK_LUMINANCE_WEIGHTS, MaskMode, mask_density_line, mask_feather_sigma, masked_radius_blur_weight};
use graphic_types::{Appearance, Graphic};
use raster_kernels::effect_kernels::NEGLIGIBLE_LENGTH;
use std::fmt::Write;
@@ -308,15 +308,19 @@ impl SvgFilterPrimitives {
/// The `mode`'s coverage of a mask graphic's `image`, in the alpha of the result, matching the GPU's `mask_coverage`.
pub(super) fn mask_coverage(&mut self, image: &str, mode: MaskMode) -> String {
match mode {
// Over black, the luminance of the opaque result is that of the premultiplied channels
let luminance = match mode {
MaskMode::Luminance => {
let black = self.push("feFlood", r#"flood-color="black""#, "");
let opaque = self.push("feComposite", &format!(r#"in="{image}" in2="{black}" operator="over""#), "");
self.push("feColorMatrix", &format!(r#"in="{opaque}" type="luminanceToAlpha""#), "")
let [red, green, blue] = MASK_LUMINANCE_WEIGHTS;
format!(r#"type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 {red} {green} {blue} 0 0""#)
}
MaskMode::Alpha => image.to_string(),
}
MaskMode::LuminanceSvg => r#"type="luminanceToAlpha""#.to_string(),
MaskMode::Alpha => return image.to_string(),
};
// Over black, the luminance of the opaque result is that of the premultiplied channels
let black = self.push("feFlood", r#"flood-color="black""#, "");
let opaque = self.push("feComposite", &format!(r#"in="{image}" in2="{black}" operator="over""#), "");
self.push("feColorMatrix", &format!(r#"in="{opaque}" {luminance}"#), "")
}
/// How much the mask graphic's `image` shows the content, in the alpha of the result, matching the GPU's mask passes.
+2 -1
View File
@@ -2,6 +2,7 @@ use crate::clip::clipped_to;
use crate::{bezpath, graphic_list};
use core_types::Color;
use core_types::list::{ATTR_APPEARANCE, ATTR_PAINT, Item, List};
use graphic_types::masks::{MaskMode, mask_coverage};
use graphic_types::{Appearance, CoverPlacement, Coverage, Graphic, Vector, stamp_coverage};
use usvg::tiny_skia_path::PathBuilder;
@@ -50,5 +51,5 @@ fn luminance_to_alpha(content: &mut List<Graphic>) {
fn luminance_as_alpha(color: Color) -> Color {
let [red, green, blue, alpha] = color.to_gamma_srgb_channels();
Color::BLACK.with_alpha((0.2126 * red + 0.7152 * green + 0.0722 * blue) * alpha)
Color::BLACK.with_alpha(mask_coverage([red * alpha, green * alpha, blue * alpha, alpha], MaskMode::LuminanceSvg))
}
@@ -282,11 +282,19 @@ fn a_stroked_even_odd_path_strokes_its_original_outline_above_the_converted_fill
#[test]
fn a_luminance_mask_masks_by_the_luminance_of_its_paints_as_alpha() -> Result<(), Error> {
let content = converted(r##"<mask id="mask"><rect width="8" height="8" fill="#808080"/></mask><g mask="url(#mask)"><rect width="8" height="8"/></g>"##)?;
// Pure green takes SVG's own weight for it, as the Luminance (SVG) mask mode does
for (fill, alpha) in [("#808080", 128. / 255.), ("#00ff00", 0.7154)] {
let content = converted(&format!(
r##"<mask id="mask"><rect width="8" height="8" fill="{fill}"/></mask><g mask="url(#mask)"><rect width="8" height="8"/></g>"##
))?;
let masker = group(&content, 0).and_then(|masked| group(masked, 0));
let masker_paint = masker.and_then(appearance_of).and_then(|appearance| appearance.first_paint_of(Cover::Fill));
assert!(matches!(masker_paint, Some(Graphic::Color(color)) if color.element().with_alpha(1.) == Color::BLACK && (color.element().a() - 128. / 255.).abs() < 1e-5));
let masker = group(&content, 0).and_then(|masked| group(masked, 0));
let masker_paint = masker.and_then(appearance_of).and_then(|appearance| appearance.first_paint_of(Cover::Fill));
assert!(
matches!(masker_paint, Some(Graphic::Color(color)) if color.element().with_alpha(1.) == Color::BLACK && (color.element().a() - alpha).abs() < 1e-5),
"{fill} masks by {masker_paint:?}"
);
}
Ok(())
}
@@ -9,11 +9,11 @@ impl PassRecorder<'_> {
/// How much the `mask` graphic's texture shows the content at each pixel, from 0 to 1, matching the CPU's `mask_strength`.
/// Its coverage is softened by a Gaussian of standard deviation `sigma` in pixels, then mapped through its `density` percentage, flipped if `invert`.
pub(super) fn mask_strength(&mut self, mask: &wgpu::Texture, mode: MaskMode, density: f64, sigma: f64, invert: bool) -> wgpu::Texture {
let mode = Parameters {
values: [if mode == MaskMode::Alpha { 1. } else { 0. }, 0., 0., 0.],
let weights = Parameters {
values: mode.channel_weights(),
..Default::default()
};
let mut coverage = self.run("mask_coverage", COVERAGE_FORMAT, self.size, mask, None, None, mode);
let mut coverage = self.run("mask_coverage", COVERAGE_FORMAT, self.size, mask, None, None, weights);
if sigma >= NEGLIGIBLE_LENGTH {
coverage = self.blur(coverage, BlurKernel::Gaussian { sigma }, false);
@@ -1,14 +1,13 @@
// The passes that mask, feather, and blur content by a radius mask, appended to `vello_effects.wgsl` and sharing its bindings and parameters
// SVG's `luminanceToAlpha` weights, taken on gamma-encoded channels, matching `MASK_LUMINANCE_WEIGHTS`
const MASK_LUMINANCE_WEIGHTS: vec3<f32> = vec3<f32>(0.2125, 0.7154, 0.0721);
// SVG's `luminanceToAlpha` weights, taken on gamma-encoded channels, by which the maps varying other effects are read, matching `SVG_LUMINANCE_WEIGHTS`
const SVG_LUMINANCE_WEIGHTS: vec3<f32> = vec3<f32>(0.2125, 0.7154, 0.0721);
// How much the mask graphic in `source`, premultiplied, shows the content: its luminance (times its alpha) with `values.x` 0, or its alpha with 1
// How much the mask graphic in `source`, premultiplied, shows the content: its channels weighed by the mask mode's `values`, matching `MaskMode::channel_weights`
@fragment
fn mask_coverage(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
let mask = textureLoad(source, vec2<i32>(position.xy), 0);
let coverage = select(dot(mask.rgb, MASK_LUMINANCE_WEIGHTS), mask.a, parameters.values.x > 0.5);
return vec4<f32>(clamp(coverage, 0., 1.), 0., 0., 0.);
return vec4<f32>(clamp(dot(mask, parameters.values), 0., 1.), 0., 0., 0.);
}
// The mask's feathered coverage in `source` mapped through its density line, of slope `values.x` and intercept `values.y`
@@ -75,7 +74,7 @@ fn feather_erode(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f3
@fragment
fn masked_radius_blur_luminance(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
let map = textureLoad(source, vec2<i32>(position.xy), 0);
let luminance = clamp(dot(map.rgb, MASK_LUMINANCE_WEIGHTS), 0., 1.);
let luminance = clamp(dot(map.rgb, SVG_LUMINANCE_WEIGHTS), 0., 1.);
if parameters.values.x > 0.5 {
return vec4<f32>(luminance);
}
@@ -1168,6 +1168,17 @@ fn masks_show_the_content_where_their_graphic_is_light_or_opaque() {
assert_eq!(pixel(&pixels, size, 40, 55)[3], 0, "transparent hides it");
assert_eq!(pixel(&pixels, size, 70, 55), white, "opaque shows it");
// Each luminance mode shows the content by its own weights of pure red, green, and blue
for (mode, levels) in [(MaskMode::Luminance, [77, 150, 28]), (MaskMode::LuminanceSvg, [54, 182, 18])] {
for (primary, level) in [GraphicColor::RED, GraphicColor::GREEN, GraphicColor::BLUE].into_iter().zip(levels) {
let Some(pixels) = render(vec![mask(halves(primary, primary), mode, 100., 0., false)]) else {
return;
};
let shown = pixel(&pixels, size, 55, 55)[3];
assert!(shown.abs_diff(level) <= 1, "{mode:?} shows {shown} of the content by {primary:?} rather than {level}");
}
}
// A feather softens the mask's edge at the middle of the square by a Gaussian
let Some(pixels) = render(vec![mask(halves(GraphicColor::BLACK, GraphicColor::WHITE), MaskMode::Luminance, 100., 4., false)]) else {
return;
@@ -1671,7 +1682,7 @@ fn gpu_masked_box_blurs_match_the_cpu() {
[gray, gray, gray, 1.].map(f16::from_f32)
})
.collect();
let luminance = |texel: &[f16; 4]| mask_coverage(texel.map(f16::to_f32), MaskMode::Luminance).clamp(0., 1.);
let luminance = |texel: &[f16; 4]| mask_coverage(texel.map(f16::to_f32), MaskMode::LuminanceSvg).clamp(0., 1.);
let luminances: Vec<f32> = map.iter().map(|texel| f16::from_f32(luminance(texel)).to_f32()).collect();
for (radius, gamma) in [(7.3, false), (7.3, true), (16., false), (30.5, true)] {
@@ -2705,6 +2716,8 @@ fn cpu_evaluated_effects_match_the_gpu_passes() {
let make_opaque = |strength| EffectOperation::Adjustment(Adjustment::MakeOpaque { strength });
let mask_cases = [
vec![mask(&mask_image, MaskMode::Luminance, 100., 0., false)],
vec![mask(&mask_image, MaskMode::LuminanceSvg, 100., 0., false)],
vec![mask(&linear, MaskMode::LuminanceSvg, 80., 3., true)],
vec![mask(&mask_image, MaskMode::Alpha, 70., 3., true)],
vec![mask(&linear, MaskMode::Luminance, 100., 6., false)],
vec![mask(&radial, MaskMode::Alpha, 100., 0., false)],
@@ -559,9 +559,9 @@ fn field_displacement(local: vec2<f32>) -> vec2<f32> {
return moved * settings.xy;
}
// How many levels past the neutral one a displacement map's premultiplied texel lies, by the luminance a mask reads, seen over the neutral level where it's translucent, matching the CPU's `displacement_amount`
// How many levels past the neutral one a displacement map's premultiplied texel lies, by the luminance an SVG luminance mask reads, seen over the neutral level where it's translucent, matching the CPU's `displacement_amount`
fn displacement_map_levels(map: vec4<f32>) -> f32 {
let luminance = clamp(dot(map.rgb, MASK_LUMINANCE_WEIGHTS), 0., 1.);
let luminance = clamp(dot(map.rgb, SVG_LUMINANCE_WEIGHTS), 0., 1.);
return luminance * 255. + DISPLACEMENT_NEUTRAL_LEVEL * (1. - map.a) - DISPLACEMENT_NEUTRAL_LEVEL;
}