diff --git a/editor/src/messages/portfolio/document/document_message_handler.rs b/editor/src/messages/portfolio/document/document_message_handler.rs index ffa7236dcf5..68b13500b15 100644 --- a/editor/src/messages/portfolio/document/document_message_handler.rs +++ b/editor/src/messages/portfolio/document/document_message_handler.rs @@ -4138,7 +4138,7 @@ impl DocumentMessageHandler { }) .unwrap_or((None, None, None)); - let blend_mode_menu_entries = BlendMode::list_svg_subset() + let blend_mode_menu_entries = BlendMode::list() .iter() .map(|modes| { modes @@ -4155,7 +4155,7 @@ impl DocumentMessageHandler { let widgets = vec![ DropdownInput::new(blend_mode_menu_entries) - .selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list_svg_subset()).map(|index| index as u32)) + .selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list()).map(|index| index as u32)) .disabled(disabled) .draw_icon(false) .sizing(WidgetSizing::default().grow(false)) diff --git a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs index f2f42571c5c..eb0261400de 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs @@ -1337,7 +1337,7 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout return LayoutGroup::row(vec![]); }; if let Some(&TaggedValue::BlendMode(blend_mode)) = input.as_non_exposed_value() { - let entries = BlendMode::list_svg_subset() + let entries = BlendMode::list() .iter() .map(|category| { category @@ -1354,9 +1354,7 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout widgets.extend_from_slice(&[ Separator::new(SeparatorStyle::Unrelated).widget_instance(), - DropdownInput::new(entries) - .selected_index(blend_mode.index_in_list_svg_subset().map(|index| index as u32)) - .widget_instance(), + DropdownInput::new(entries).selected_index(blend_mode.index_in_list().map(|index| index as u32)).widget_instance(), ]); } LayoutGroup::row(widgets).with_tooltip_description("Formula used for blending.") diff --git a/node-graph/libraries/core-types/src/blending.rs b/node-graph/libraries/core-types/src/blending.rs index 3aaf7217536..a2ac3fc05b6 100644 --- a/node-graph/libraries/core-types/src/blending.rs +++ b/node-graph/libraries/core-types/src/blending.rs @@ -72,31 +72,32 @@ impl BlendMode { ] } - /// The subset of [`BlendMode::list()`] that is supported by SVG. - pub fn list_svg_subset() -> [&'static [BlendMode]; 6] { + pub fn index_in_list(&self) -> Option { + Self::list().iter().flat_map(|x| x.iter()).position(|&blend_mode| blend_mode == *self) + } + + /// Whether a layer in this mode reads what lies beneath it to blend, since neither SVG's `mix-blend-mode` nor Vello's layers have the mode. + /// The alpha-only utility modes, hidden from the list, draw layers normally. + pub fn reads_backdrop(&self) -> bool { + self.to_svg_style_name().is_none() && !matches!(self, BlendMode::Erase | BlendMode::Restore | BlendMode::MultiplyAlpha) + } + + /// Whether a paint's strength (an effect's opacity, or a layer's fill) moves its color toward the mode's neutral color, which then blends at full strength, rather than fading the blend, for PSD interop. + pub fn strength_moves_toward_neutral(&self) -> bool { use BlendMode::*; - [ - // Normal group - &[Normal], - // Darken group - &[Darken, Multiply, ColorBurn], - // Lighten group - &[Lighten, Screen, ColorDodge], - // Contrast group - &[Overlay, SoftLight, HardLight], - // Inversion group - &[Difference, Exclusion], - // Component group - &[Hue, Saturation, Color, Luminosity], - ] + matches!(self, ColorDodge | LinearDodge | ColorBurn | LinearBurn | VividLight | LinearLight | HardMix) } - pub fn index_in_list(&self) -> Option { - Self::list().iter().flat_map(|x| x.iter()).position(|&blend_mode| blend_mode == *self) + /// Whether a layer's fill moves its content toward the mode's neutral color (see [`Self::strength_moves_toward_neutral`]) rather than fading it, for PSD interop. + /// The layer then reads what lies beneath it to blend (see [`Self::layer_reads_backdrop`]). + pub fn fill_moves_layer_toward_neutral(&self) -> bool { + self.strength_moves_toward_neutral() } - pub fn index_in_list_svg_subset(&self) -> Option { - Self::list_svg_subset().iter().flat_map(|x| x.iter()).position(|&blend_mode| blend_mode == *self) + /// Whether a layer in this mode at this `fill` reads what lies beneath it to blend: in a mode neither SVG's `mix-blend-mode` nor Vello's layers have, + /// or below a full fill moving it toward the mode's neutral color, which Color Dodge and Color Burn layers otherwise blend natively without. + pub fn layer_reads_backdrop(&self, fill: f32) -> bool { + self.reads_backdrop() || (fill < 1. && self.fill_moves_layer_toward_neutral()) } /// Convert the enum to the CSS string for the blend mode. @@ -130,11 +131,14 @@ impl BlendMode { } /// Renders the blend mode CSS style declaration. + /// A mode CSS lacks, which layers read what lies beneath to blend by, draws normally where nothing beneath can be read, as for content without bounds. pub fn render(&self) -> String { format!( r#" mix-blend-mode: {};"#, self.to_svg_style_name().unwrap_or_else(|| { - log::warn!("Unsupported blend mode {self:?}"); + if !self.reads_backdrop() { + log::warn!("Unsupported blend mode {self:?}"); + } "normal" }) ) @@ -156,7 +160,7 @@ impl Display for BlendMode { BlendMode::Lighten => write!(f, "Lighten"), BlendMode::Screen => write!(f, "Screen"), BlendMode::ColorDodge => write!(f, "Color Dodge"), - BlendMode::LinearDodge => write!(f, "Linear Dodge"), + BlendMode::LinearDodge => write!(f, "Linear Dodge (Add)"), BlendMode::LighterColor => write!(f, "Lighter Color"), // Contrast group BlendMode::Overlay => write!(f, "Overlay"), @@ -247,6 +251,30 @@ pub fn apply_blend_mode(foreground: Color, background: Color, blend_mode: BlendM } } +/// How strongly a layer whose fill moves it toward neutral (see [`BlendMode::fill_moves_layer_toward_neutral`]) shows over a backdrop of `backdrop_alpha`: fully over an opaque one, +/// by its `fill` over nothing, and between, the harmonic mean of the two weighted by that alpha, which shows nothing at no fill. +pub fn layer_fill_shown(backdrop_alpha: f32, fill: f32) -> f32 { + let weighted = (1. - backdrop_alpha) + backdrop_alpha * fill; + if weighted <= 0. { 0. } else { (fill / weighted).min(1.) } +} + +/// Like [`apply_blend_mode`], with the foreground at `strength` (from 0 to 1) moved toward the mode's neutral color where it does that (see [`BlendMode::strength_moves_toward_neutral`]), +/// for the caller to composite at full strength. Other modes take the foreground as it is, for the caller to fade the blend by the strength. +pub fn apply_blend_mode_at_strength(foreground: Color, background: Color, blend_mode: BlendMode, strength: f32) -> Color { + let toward = |neutral: f32| { + let moved = |channel: f32| neutral + strength * (channel - neutral); + Color::from_rgbaf32_unchecked(moved(foreground.r()), moved(foreground.g()), moved(foreground.b()), foreground.a()) + }; + + match blend_mode { + BlendMode::ColorDodge | BlendMode::LinearDodge => apply_blend_mode(toward(0.), background, blend_mode), + BlendMode::ColorBurn | BlendMode::LinearBurn => apply_blend_mode(toward(1.), background, blend_mode), + BlendMode::VividLight | BlendMode::LinearLight => apply_blend_mode(toward(0.5), background, blend_mode), + BlendMode::HardMix => background.blend_rgb(foreground, |backdrop, source| Color::blend_hard_mix_at_strength(backdrop, source, strength)), + _ => apply_blend_mode(foreground, background, blend_mode), + } +} + #[cfg(test)] mod tests { use super::*; @@ -375,6 +403,33 @@ mod tests { } } + #[test] + fn strength_moves_a_paint_toward_the_modes_neutral_color() { + let backdrop = Color::from_rgbaf32_unchecked(0.4, 0.4, 0.4, 1.); + let paint = Color::from_rgbaf32_unchecked(0.8, 0.8, 0.8, 1.); + let at_half = |blend_mode: BlendMode| apply_blend_mode_at_strength(paint, backdrop, blend_mode, 0.5).r(); + + // Half the paint added, the paint halfway to white burned in, and the paint halfway to middle gray lighting + assert!((at_half(BlendMode::LinearDodge) - 0.8).abs() < 1e-6, "{}", at_half(BlendMode::LinearDodge)); + assert!((at_half(BlendMode::LinearBurn) - 0.3).abs() < 1e-6, "{}", at_half(BlendMode::LinearBurn)); + assert!((at_half(BlendMode::LinearLight) - 0.7).abs() < 1e-6, "{}", at_half(BlendMode::LinearLight)); + + // The modes whose strength fades their blend take the paint as it is + assert_eq!(at_half(BlendMode::Subtract), apply_blend_mode(paint, backdrop, BlendMode::Subtract).r()); + + // Layers read what lies beneath for the ten modes CSS lacks, of which five move their content toward neutral by their fill + let reading: Vec = BlendMode::list().into_iter().flatten().copied().filter(BlendMode::reads_backdrop).collect(); + assert_eq!(reading.len(), 10); + assert_eq!(reading.iter().filter(|blend_mode| blend_mode.fill_moves_layer_toward_neutral()).count(), 5); + assert!(!BlendMode::Erase.reads_backdrop()); + + // Color Dodge and Color Burn do too below a full fill, which they otherwise blend natively at + for blend_mode in [BlendMode::ColorDodge, BlendMode::ColorBurn] { + assert!(!blend_mode.reads_backdrop() && !blend_mode.layer_reads_backdrop(1.) && blend_mode.layer_reads_backdrop(0.5) && blend_mode.layer_reads_backdrop(0.)); + } + assert!(!BlendMode::Multiply.layer_reads_backdrop(0.5) && BlendMode::LinearBurn.layer_reads_backdrop(1.)); + } + #[test] fn source_over_weights_straight_colors_by_alpha() { let over = Color::from_rgbaf32_unchecked(1., 0., 0., 0.5); diff --git a/node-graph/libraries/graphic-types/src/effect_layers.rs b/node-graph/libraries/graphic-types/src/effect_layers.rs index 6dc32ddc432..46a91ff197d 100644 --- a/node-graph/libraries/graphic-types/src/effect_layers.rs +++ b/node-graph/libraries/graphic-types/src/effect_layers.rs @@ -74,10 +74,14 @@ pub struct EffectLayers { impl EffectLayers { /// The layers of content drawn with `blend_mode` and faded by `fill` through `effects`, or with every effect flattened if not `layered`, as for content clipped by a mask. - /// Content in a mode CSS lacks is drawn normally, so it's planned that way. + /// Content in a mode CSS lacks reads what lies beneath to blend by it (see [`BlendMode::reads_backdrop`]), but the alpha-only utility modes are planned as normal. pub fn plan(effects: &Effects, blend_mode: BlendMode, fill: f32, layered: bool) -> Self { let operations: Vec = effects.operations().collect(); - let blend_mode = if blend_mode.to_svg_style_name().is_some() { blend_mode } else { BlendMode::Normal }; + let blend_mode = if blend_mode.to_svg_style_name().is_some() || blend_mode.reads_backdrop() { + blend_mode + } else { + BlendMode::Normal + }; // Normal content at full fill hides what lies beneath its share, so its interior pieces blend with it alone, in any mode, within its own layer. // A Blend If fading the content by its colors acts as a fill below full wherever it hides any. @@ -226,9 +230,20 @@ impl EffectLayers { planned } - /// Whether a layered piece, or a Blend If fading the layers, reads what lies beneath the content. + /// Whether a layered piece, a Blend If fading the layers, or a layer's blend mode reads what lies beneath the content. pub fn reads_backdrop(&self) -> bool { - self.fades_by_underlying || self.reads_around_backdrop() + self.fades_by_underlying || self.reads_around_backdrop() || self.layers.iter().any(|layer| layer.blend_mode.reads_backdrop()) + } + + /// Whether the content's layer reads what lies beneath it to blend at the content's `fill` (see [`BlendMode::layer_reads_backdrop`]). + /// Color Dodge and Color Burn blend natively instead over a piece beneath the content it doesn't knock out, which what lies beneath the item leaves out. + pub fn content_reads_backdrop(&self, fill: f32) -> bool { + let Some(content_layer) = self.content_layer() else { return false }; + let blend_mode = self.layers[content_layer].blend_mode; + + let shown_beneath = |part: &LayerPart| matches!(part, LayerPart::Piece(piece) if piece.place == PiecePlace::Beneath && !piece.knocks_out); + let pieces_show_beneath = self.layers[..content_layer].iter().flat_map(|layer| &layer.parts).any(shown_beneath); + blend_mode.reads_backdrop() || (blend_mode.layer_reads_backdrop(fill) && !pieces_show_beneath) } /// Whether a layered piece reads what lies around each pixel beneath the content, as a background blur does, where a Blend If reads only the pixel itself. @@ -298,20 +313,30 @@ impl EffectLayers { } } -/// Whether any of the effects reads what lies beneath the content, like a background blur. +/// Whether any of the effects reads what lies beneath the content, like a background blur, or may, like a shadow in a mode CSS lacks. pub fn effects_read_backdrop(effects: &Effects) -> bool { effects.operations().any(|operation| match &operation { EffectOperation::BackgroundBlur { .. } => !operation.changes_nothing(), EffectOperation::BlendIf(ranges) => !ranges.underlying.show_everything(), - _ => false, + _ => { + !operation.changes_nothing() + && pieces(0, &operation) + .iter() + .any(|(piece, blend_mode)| piece.place == PiecePlace::Beneath && blend_mode.reads_backdrop()) + } }) } /// Whether an effect row can draw as layered pieces, rather than being carried out within the content's image. -/// Blurs, adjustments, masks, and feathers process the pixels of everything before them, and blend modes CSS lacks can't blend against the backdrop in SVG or a GPU layer, -/// though interior pieces that `blend_into_content` blend with the content alone, which the renderers do themselves. +/// Blurs, adjustments, masks, and feathers process the pixels of everything before them. A piece in a mode CSS lacks reads what lies beneath the item to blend, so only one beneath the content +/// can, though interior pieces that `blend_into_content` blend with the content alone, which the renderers do themselves. fn can_be_layered(operation: &EffectOperation, blend_into_content: bool) -> bool { - let layers_in = |(piece, blend_mode): (EffectPiece, BlendMode)| blend_mode.to_svg_style_name().is_some() || (blend_into_content && piece.place == PiecePlace::Within); + let layers_in = |(piece, blend_mode): (EffectPiece, BlendMode)| match piece.place { + _ if blend_mode.to_svg_style_name().is_some() => true, + PiecePlace::Beneath => blend_mode.reads_backdrop(), + PiecePlace::Within => blend_into_content, + _ => false, + }; !is_pixel_filter(operation) && pieces(0, operation).into_iter().all(layers_in) } @@ -562,9 +587,11 @@ mod tests { let layers = EffectLayers::plan(&effects, BlendMode::Overlay, 1., true); assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Overlay, BlendMode::Screen, BlendMode::Normal]); - // A mode CSS lacks is drawn normally, so it's planned that way, and an interior piece blending within the content's layer may take one too + // Content in a mode CSS lacks reads what lies beneath to blend by it, and an interior piece blending within the content's layer may take one too let layers = EffectLayers::plan(&effects, BlendMode::LinearBurn, 1., true); - assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]); + assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::LinearBurn, BlendMode::Screen, BlendMode::Normal]); + assert!(layers.reads_backdrop() && !layers.reads_around_backdrop()); + assert!(!EffectLayers::plan(&effects, BlendMode::Overlay, 1., true).reads_backdrop()); let linear_burn = Effects::from_operations([drop_shadow(red, BlendMode::Multiply), inner_shadow(red, BlendMode::LinearBurn)]); assert_eq!(EffectLayers::plan(&linear_burn, BlendMode::Normal, 1., true).flattened, 0); assert_eq!(EffectLayers::plan(&linear_burn, BlendMode::Normal, 0.5, true).flattened, 2); @@ -647,14 +674,11 @@ mod tests { let layers = EffectLayers::plan(&Effects::from_operations([with_knockout(true), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true); assert_eq!(parts(&layers)[0], [Some((1, 0, PiecePlace::Through { over: false }))]); - // One flattened for a mode CSS lacks covers it too - let mut flattened_shadow = with_knockout(false); - if let EffectOperation::DropShadow { blend_mode, .. } = &mut flattened_shadow { - *blend_mode = BlendMode::LinearBurn; - } - let layers = EffectLayers::plan(&Effects::from_operations([flattened_shadow, inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true); - assert_eq!(layers.flattened, 1); - assert_eq!(parts(&layers)[1], [Some((1, 0, through_over))]); + // One flattened before an interior piece in a mode CSS lacks covers it too + let flattening = [with_knockout(false), inner_shadow(red, BlendMode::LinearBurn), inner_shadow(red, BlendMode::Screen)]; + let layers = EffectLayers::plan(&Effects::from_operations(flattening), BlendMode::Normal, 0.5, true); + assert_eq!(layers.flattened, 2); + assert_eq!(parts(&layers)[1], [Some((2, 0, through_over))]); } #[test] @@ -761,9 +785,14 @@ mod tests { assert_eq!((layers.flattened, layers.trailing_masks.clone()), (2, 2..2)); let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false); assert_eq!((layers.flattened, layers.trailing_masks.clone()), (5, 5..5)); - let unmerged = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply), mask()]); - let layers = EffectLayers::plan(&unmerged, BlendMode::Normal, 1., true); - assert_eq!((layers.flattened, layers.trailing_masks.clone()), (3, 3..3)); + let unmerged = Effects::from_operations([ + drop_shadow(RED, BlendMode::Multiply), + inner_shadow(RED, BlendMode::LinearBurn), + drop_shadow(RED, BlendMode::Multiply), + mask(), + ]); + let layers = EffectLayers::plan(&unmerged, BlendMode::Normal, 0.5, true); + assert_eq!((layers.flattened, layers.trailing_masks.clone()), (4, 4..4)); } #[test] @@ -780,19 +809,23 @@ mod tests { assert_eq!(layers.flattened, 2); assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]); - let effects = Effects::from_operations([inner_shadow(RED, BlendMode::Screen), drop_shadow(RED, BlendMode::LinearBurn), inner_shadow(RED, BlendMode::Multiply)]); + // An interior piece in a mode CSS lacks, which would read the content beneath it, flattens what's before it, where one beneath the content takes a layer of its own + let effects = Effects::from_operations([inner_shadow(RED, BlendMode::Screen), inner_shadow(RED, BlendMode::LinearBurn), inner_shadow(RED, BlendMode::Multiply)]); let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true); assert_eq!(layers.flattened, 2); + let layers = EffectLayers::plan(&Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn)]), BlendMode::Normal, 0.5, true); + assert_eq!((layers.flattened, modes(&layers)), (0, vec![BlendMode::LinearBurn, BlendMode::Normal])); + assert!(layers.reads_backdrop()); // A flattened shadow left unmerged by a blur would cover the layered shadow after it, so everything flattens - let effects = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply)]); - let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true); - assert_eq!(layers.flattened, 2); + let effects = Effects::from_operations([drop_shadow(RED, BlendMode::Multiply), inner_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply)]); + let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true); + assert_eq!(layers.flattened, 3); assert_eq!(modes(&layers), [BlendMode::Normal]); // Clipped content flattens everything - let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false); - assert_eq!(layers.flattened, 2); + let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, false); + assert_eq!(layers.flattened, 3); assert_eq!(parts(&layers), [[None]]); } diff --git a/node-graph/libraries/raster-kernels/src/layer_blending.rs b/node-graph/libraries/raster-kernels/src/layer_blending.rs index 0b879a4524b..6d07613d386 100644 --- a/node-graph/libraries/raster-kernels/src/layer_blending.rs +++ b/node-graph/libraries/raster-kernels/src/layer_blending.rs @@ -1,8 +1,9 @@ //! Blends a layer onto those beneath it by a blend mode, with the W3C Compositing and Blending formulas on gamma-encoded colors, as SVG and the GPU's layers blend. -//! The modes CSS lacks blend normally, since layers only ever take the others. +//! The modes CSS lacks, which layers read what lies beneath to blend by, take the formulas the effects share (see [`crate::blending::blend_gamma`]). use crate::effect_kernels::Plane; -use core_types::blending::BlendMode; +use core_types::Color; +use core_types::blending::{BlendMode, apply_blend_mode_at_strength, layer_fill_shown}; use core_types::color::BLEND_EDGE_TOLERANCE; /// The premultiplied gamma-encoded `layer` blended by the mode onto the layers `below` it. O(width × height). @@ -12,6 +13,20 @@ pub fn blend_layer(layer: &Plane<[f32; 4]>, below: &Plane<[f32; 4]>, blend_mode: /// One premultiplied pixel blended onto another: its color mixes toward the blend of both as far as the backdrop covers it, and it then composites over the backdrop. pub fn blend_pixel(source: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode) -> [f32; 4] { + blend_pixel_at_strength(source, backdrop, blend_mode, 1.) +} + +/// One premultiplied pixel of a layer's full-strength content blended onto another by the mode, faded by the layer's `fill`, or over the backdrop +/// in a mode whose fill moves the content toward its neutral color (see [`BlendMode::fill_moves_layer_toward_neutral`]), moved there by it. +pub fn blend_layer_pixel(content: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode, fill: f32) -> [f32; 4] { + match blend_mode.fill_moves_layer_toward_neutral() { + true => blend_pixel_at_strength(content, backdrop, blend_mode, fill), + false => blend_pixel(content.map(|channel| channel * fill), backdrop, blend_mode), + } +} + +/// [`blend_pixel`] with the source at `strength`, which moves it toward the mode's neutral color where it blends, and shows it as strongly as [`layer_fill_shown`] gives. +fn blend_pixel_at_strength(source: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode, strength: f32) -> [f32; 4] { let (source_alpha, backdrop_alpha) = (source[3], backdrop[3]); if source_alpha <= 0. { return backdrop; @@ -22,14 +37,18 @@ pub fn blend_pixel(source: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode) false => [0.; 3], }; let (source_color, backdrop_color) = (straight(source), straight(backdrop)); - let blended = blend(backdrop_color, source_color, blend_mode); + let blended = match strength < 1. { + true => blend_at_strength(backdrop_color, source_color, blend_mode, strength), + false => blend(backdrop_color, source_color, blend_mode), + }; + let shown = source_alpha * layer_fill_shown(backdrop_alpha, strength); let mut result = [0.; 4]; for channel in 0..3 { let mixed = (1. - backdrop_alpha) * source_color[channel] + backdrop_alpha * blended[channel]; - result[channel] = source_alpha * mixed + (1. - source_alpha) * backdrop[channel]; + result[channel] = shown * mixed + (1. - shown) * backdrop[channel]; } - result[3] = source_alpha + backdrop_alpha * (1. - source_alpha); + result[3] = shown + backdrop_alpha * (1. - shown); result } @@ -40,10 +59,22 @@ fn blend(backdrop: [f32; 3], source: [f32; 3], blend_mode: BlendMode) -> [f32; 3 BlendMode::Saturation => set_luminosity(set_saturation(backdrop, saturation(source)), luminosity(backdrop)), BlendMode::Color => set_luminosity(source, luminosity(backdrop)), BlendMode::Luminosity => set_luminosity(backdrop, luminosity(source)), + blend_mode if blend_mode.reads_backdrop() => crate::blending::blend_gamma(backdrop, source, blend_mode), _ => [0, 1, 2].map(|channel| blend_channel(backdrop[channel], source[channel], blend_mode)), } } +/// The blend of straight `backdrop` and `source` colors with the source at `strength`, moved toward the mode's neutral color (see [`apply_blend_mode_at_strength`]). +fn blend_at_strength(backdrop: [f32; 3], source: [f32; 3], blend_mode: BlendMode, strength: f32) -> [f32; 3] { + if !blend_mode.strength_moves_toward_neutral() { + return blend(backdrop, source, blend_mode); + } + + let color = |[red, green, blue]: [f32; 3]| Color::from_rgbaf32_unchecked(red, green, blue, 1.); + let blended = apply_blend_mode_at_strength(color(source), color(backdrop), blend_mode, strength); + [blended.r(), blended.g(), blended.b()] +} + /// The mode's blend of one channel of the backdrop and source, for the modes that blend each channel on its own. fn blend_channel(backdrop: f32, source: f32, blend_mode: BlendMode) -> f32 { let hard_light = |backdrop: f32, source: f32| match source <= 0.5 { @@ -143,6 +174,195 @@ mod tests { assert!((screened[0] - (0.5 * 0.75 + 0.5 * 0.5)).abs() < 1e-6); } + /// The reference formulas, for PSD interop, for the modes CSS lacks and for Color Burn and Color Dodge, at full strength, on a channel of straight gamma-encoded `backdrop` and `source` colors. + fn reference_formula(blend_mode: BlendMode, backdrop: [f32; 3], source: [f32; 3]) -> [f32; 3] { + let luma = |color: [f32; 3]| 0.3 * color[0] + 0.59 * color[1] + 0.11 * color[2]; + let color_burn = |b: f32, s: f32| { + if b >= 1. { + 1. + } else if s <= 0. { + 0. + } else { + 1. - ((1. - b) / s).min(1.) + } + }; + let color_dodge = |b: f32, s: f32| { + if b <= 0. { + 0. + } else if s >= 1. { + 1. + } else { + (b / (1. - s)).min(1.) + } + }; + let channels = |formula: &dyn Fn(f32, f32) -> f32| [0, 1, 2].map(|channel| formula(backdrop[channel], source[channel]).clamp(0., 1.)); + + match blend_mode { + BlendMode::ColorBurn => channels(&color_burn), + BlendMode::ColorDodge => channels(&color_dodge), + BlendMode::LinearBurn => channels(&|b, s| b + s - 1.), + BlendMode::LinearDodge => channels(&|b, s| b + s), + BlendMode::VividLight => channels(&|b, s| if s <= 0.5 { color_burn(b, 2. * s) } else { color_dodge(b, 2. * s - 1.) }), + BlendMode::LinearLight => channels(&|b, s| b + 2. * s - 1.), + BlendMode::PinLight => channels(&|b, s| if s <= 0.5 { b.min(2. * s) } else { b.max(2. * s - 1.) }), + BlendMode::HardMix => channels(&|b, s| 256. * b - 255. * (1. - s)), + BlendMode::Subtract => channels(&|b, s| b - s), + BlendMode::Divide => channels(&|b, s| { + if b <= 0. { + 0. + } else if s <= 0. { + 1. + } else { + b / s + } + }), + BlendMode::DarkerColor => { + if luma(source) < luma(backdrop) { + source + } else { + backdrop + } + } + BlendMode::LighterColor => { + if luma(source) > luma(backdrop) { + source + } else { + backdrop + } + } + _ => panic!("{blend_mode} blends natively"), + } + } + + /// Pairs of a backdrop and a source color, away from Hard Mix's ramp and the lumas' ties. + const PAIRS: [([f32; 3], [f32; 3]); 4] = [ + ([0.2, 0.6, 0.45], [0.85, 0.3, 0.6]), + ([0.9, 0.1, 0.5], [0.3, 0.7, 0.2]), + ([0.55, 0.55, 0.55], [0.05, 0.95, 0.35]), + ([0., 1., 0.3], [0.6, 0.15, 0.8]), + ]; + + #[test] + fn modes_css_lacks_take_the_reference_formulas_over_any_backdrop() { + for blend_mode in BlendMode::list().into_iter().flatten().copied().filter(BlendMode::reads_backdrop) { + for (backdrop, source) in PAIRS { + let expected = reference_formula(blend_mode, backdrop, source); + let opaque = |[red, green, blue]: [f32; 3]| [red, green, blue, 1.]; + + // Over an opaque backdrop, the source takes the formula + let blended = blend_pixel(opaque(source), opaque(backdrop), blend_mode); + assert!( + (0..3).all(|channel| (blended[channel] - expected[channel]).abs() < 1e-5), + "{blend_mode}: {blended:?} rather than {expected:?}" + ); + + // Over one of half alpha, its color mixes halfway from its own to the formula's, as the 16 native modes do + let half = [backdrop[0] * 0.5, backdrop[1] * 0.5, backdrop[2] * 0.5, 0.5]; + let blended = blend_pixel(opaque(source), half, blend_mode); + for channel in 0..3 { + let mixed = 0.5 * source[channel] + 0.5 * expected[channel]; + assert!((blended[channel] - mixed).abs() < 1e-5, "{blend_mode} over half alpha: {blended:?}"); + } + } + } + } + + #[test] + fn fills_move_the_content_toward_neutral_in_seven_modes_and_fade_it_in_the_others() { + let fill = 0.5; + let reading = BlendMode::list().into_iter().flatten().copied().filter(BlendMode::reads_backdrop); + for blend_mode in reading.chain([BlendMode::ColorDodge, BlendMode::ColorBurn]) { + for (backdrop, source) in PAIRS { + let blended = blend_layer_pixel([source[0], source[1], source[2], 1.], [backdrop[0], backdrop[1], backdrop[2], 1.], blend_mode, fill); + + let expected = match blend_mode { + // The paint at full strength once moved halfway toward black, white, or middle gray + BlendMode::ColorDodge | BlendMode::LinearDodge => reference_formula(blend_mode, backdrop, source.map(|channel| fill * channel)), + BlendMode::ColorBurn | BlendMode::LinearBurn => reference_formula(blend_mode, backdrop, source.map(|channel| 1. - fill * (1. - channel))), + BlendMode::VividLight | BlendMode::LinearLight => reference_formula(blend_mode, backdrop, source.map(|channel| 0.5 + fill * (channel - 0.5))), + // A ramp a fill of half makes `clamp(2b - 1 + s)` + BlendMode::HardMix => [0, 1, 2].map(|channel| Color::blend_hard_mix_at_strength(backdrop[channel], source[channel], fill).clamp(0., 1.)), + // Halfway from the backdrop to the blend + _ => { + let full = reference_formula(blend_mode, backdrop, source); + [0, 1, 2].map(|channel| backdrop[channel] + (full[channel] - backdrop[channel]) * fill) + } + }; + assert!( + (0..3).all(|channel| (blended[channel] - expected[channel]).abs() < 1e-5), + "{blend_mode}: {blended:?} rather than {expected:?}" + ); + assert!((blended[3] - 1.).abs() < 1e-6, "{blend_mode} covers the opaque backdrop"); + } + } + + // Where nothing lies beneath, the fill fades the content as it is, as a fill fades content in the other modes + let faded = blend_layer_pixel([0.8, 0.4, 0.2, 1.], [0.; 4], BlendMode::LinearDodge, fill); + assert!(faded.iter().zip([0.4, 0.2, 0.1, 0.5]).all(|(channel, expected)| (channel - expected).abs() < 1e-6), "{faded:?}"); + } + + #[test] + fn fills_moving_layers_toward_neutral_blend_their_share_at_full_strength_over_opaque_backdrops_and_change_nothing_at_no_fill() { + let close = |ours: [f32; 4], expected: [f32; 4]| ours.iter().zip(expected).all(|(ours, expected)| (ours - expected).abs() < 1e-5); + let premultiplied = |[red, green, blue]: [f32; 3], alpha: f32| [red * alpha, green * alpha, blue * alpha, alpha]; + let pushed = |blend_mode: BlendMode, source: [f32; 3], fill: f32| { + source.map(|channel| match blend_mode { + BlendMode::ColorDodge | BlendMode::LinearDodge => fill * channel, + BlendMode::ColorBurn | BlendMode::LinearBurn => 1. - fill * (1. - channel), + _ => 0.5 + fill * (channel - 0.5), + }) + }; + + let modes = [ + BlendMode::ColorDodge, + BlendMode::ColorBurn, + BlendMode::LinearDodge, + BlendMode::LinearBurn, + BlendMode::VividLight, + BlendMode::LinearLight, + ]; + for blend_mode in modes { + for (backdrop, source) in PAIRS { + for alpha in [1., 0.5] { + for fill in [0., 0.3, 1.] { + // Over an opaque backdrop, the content's share blends the paint moved toward neutral at full strength, the rest showing the backdrop, for PSD interop + let full = reference_formula(blend_mode, backdrop, pushed(blend_mode, source, fill)); + let expected = [0, 1, 2].map(|channel| alpha * full[channel] + (1. - alpha) * backdrop[channel]); + let blended = blend_layer_pixel(premultiplied(source, alpha), premultiplied(backdrop, 1.), blend_mode, fill); + assert!(close(blended, premultiplied(expected, 1.)), "{blend_mode} at fill {fill}, alpha {alpha}: {blended:?}"); + + // Over nothing, the fill fades the content as it is + let blended = blend_layer_pixel(premultiplied(source, alpha), [0.; 4], blend_mode, fill); + assert!(close(blended, premultiplied(source, alpha * fill)), "{blend_mode} at fill {fill} over nothing: {blended:?}"); + } + + for backdrop_alpha in [0.25, 0.5, 0.75] { + let beneath = premultiplied(backdrop, backdrop_alpha); + + // No fill leaves a partly covering backdrop as it is, alpha included + let unfilled = blend_layer_pixel(premultiplied(source, alpha), beneath, blend_mode, 0.); + assert!(close(unfilled, beneath), "{blend_mode} at no fill over alpha {backdrop_alpha}: {unfilled:?}"); + + // A full fill blends by the W3C's general formula, mixing toward the blend as far as the backdrop covers + let blend = reference_formula(blend_mode, backdrop, source); + let mixed = [0, 1, 2].map(|channel| (1. - backdrop_alpha) * source[channel] + backdrop_alpha * blend[channel]); + let expected = [0, 1, 2] + .map(|channel| alpha * mixed[channel] + (1. - alpha) * beneath[channel]) + .into_iter() + .chain([alpha + (1. - alpha) * backdrop_alpha]) + .collect::>(); + let filled = blend_layer_pixel(premultiplied(source, alpha), beneath, blend_mode, 1.); + assert!(close(filled, expected.try_into().unwrap()), "{blend_mode} at full fill over alpha {backdrop_alpha}: {filled:?}"); + } + } + } + } + + // An opaque layer at no fill over half alpha leaves that alpha + let unfilled = blend_layer_pixel([0.8, 0.4, 0.2, 1.], [0.25, 0.25, 0.25, 0.5], BlendMode::LinearDodge, 0.); + assert!((unfilled[3] - 0.5).abs() < 1e-6, "{unfilled:?}"); + } + #[test] fn the_luminosity_of_black_over_any_gray_is_black() { for level in 0..=255 { diff --git a/node-graph/libraries/rendering/src/lib.rs b/node-graph/libraries/rendering/src/lib.rs index b9e67ea2621..6909a3b2e78 100644 --- a/node-graph/libraries/rendering/src/lib.rs +++ b/node-graph/libraries/rendering/src/lib.rs @@ -4,6 +4,7 @@ pub mod render_ext; mod renderer; mod svg_backdrop; mod svg_blend_if; +mod svg_layer_blend; pub mod to_peniko; pub mod vello_scene_builder; diff --git a/node-graph/libraries/rendering/src/renderer.rs b/node-graph/libraries/rendering/src/renderer.rs index a9252957b4f..fe410c55365 100644 --- a/node-graph/libraries/rendering/src/renderer.rs +++ b/node-graph/libraries/rendering/src/renderer.rs @@ -2,6 +2,7 @@ use crate::deferred_image::{self, DeferredContent, DeferredImage, EffectMap}; use crate::render_ext::{PaintTarget, RenderExt}; use crate::svg_backdrop::{self, OpenGroup, OpenGroups}; use crate::svg_blend_if; +use crate::svg_layer_blend::{self, SvgLayerBlend}; use crate::to_peniko::{BlendModeExt, ToPenikoColor}; use crate::vello_scene_builder::VelloSceneBuilder; use core_types::CacheHash; @@ -135,10 +136,13 @@ impl<'a, T> ItemRef<'a, T> { }; // Outline mode shows only geometry - let effects = self - .attribute::(ATTR_EFFECTS) - .filter(|effects| !effects.change_nothing() && render_params.render_mode != RenderMode::Outline); - let blend_mode = self.attribute_cloned_or_default(ATTR_BLEND_MODE); + let outline = render_params.render_mode == RenderMode::Outline; + let stamped_effects = self.attribute::(ATTR_EFFECTS); + let effects = stamped_effects.filter(|effects| !effects.change_nothing() && !outline); + let blend_mode: BlendMode = self.attribute_cloned_or_default(ATTR_BLEND_MODE); + + // A layer reading what lies beneath to blend by its mode at its fill draws through an effects group, even of no effects + let effects = effects.or_else(|| (blend_mode.layer_reads_backdrop(fill) && !outline).then(|| stamped_effects.unwrap_or(no_effects()))); match effects { Some(effects) => ItemCompositing { @@ -230,7 +234,14 @@ impl<'a> ItemRef<'a, Vector> { } } +/// No effects, for content whose blend mode draws it through an effects group anyway. +fn no_effects() -> &'static Effects { + static NO_EFFECTS: std::sync::LazyLock = std::sync::LazyLock::new(Effects::default); + &NO_EFFECTS +} + /// How an item composites: the alpha and blend mode of the layer it draws through, and the effects its content renders through. +#[derive(Clone, Copy)] struct ItemCompositing<'a> { opacity: f32, blend_mode: BlendMode, @@ -257,7 +268,17 @@ impl ItemCompositing<'_> { } /// This compositing for content clipped by the content beneath it, if `clipped`, which flattens every effect into the content's image so the clip cuts the whole result. + /// Inside the clip's layer, a mode that reads what lies beneath finds nothing there, so content with no effects but that mode draws normally. fn clipped(self, clipped: bool) -> Self { + if clipped && let Some((_, fill)) = self.effects.filter(|(effects, fill)| self.blend_mode.layer_reads_backdrop(*fill) && effects.change_nothing()) { + return Self { + opacity: self.opacity * fill, + effects: None, + layered: false, + ..self + }; + } + Self { layered: self.layered && !clipped, ..self @@ -272,6 +293,18 @@ impl ItemCompositing<'_> { } } + /// Whether the item's layer reads what lies beneath it to blend by its mode at its fill (see [`EffectLayers::content_reads_backdrop`]). + fn layer_reads_backdrop(&self) -> bool { + let fill = self.effects.map_or(1., |(_, fill)| fill); + self.layers().is_some_and(|layers| layers.content_reads_backdrop(fill)) + } + + /// Whether a layer of the effects' pieces, beneath the content, reads what lies beneath it to blend by its mode. + fn pieces_read_backdrop(&self) -> bool { + self.layers() + .is_some_and(|layers| layers.layers.iter().any(|layer| !layer.holds_content() && layer.blend_mode.reads_backdrop())) + } + /// Whether the effects group draws the item's opacity and blend mode itself, as its layers blend onto what lies beneath, so the item pushes no layer of its own. fn effects_draw_compositing(&self) -> bool { self.effects.is_some() && self.layered @@ -325,7 +358,8 @@ impl ItemCompositing<'_> { fn with_remaining_effects<'b>(&self, remaining: &'b Effects) -> ItemCompositing<'b> { let fill = self.effects.map_or(1., |(_, fill)| fill); - match remaining.change_nothing() { + // A mode that reads what lies beneath keeps the effects group to blend through + match remaining.change_nothing() && !(self.blend_mode.layer_reads_backdrop(fill) && self.layered) { true => ItemCompositing { opacity: self.opacity * fill, effects: None, @@ -536,8 +570,19 @@ impl ItemCompositing<'_> { fn svg_filters_within(&self, render: &mut SvgRender, render_params: &RenderParams, bounds: [DVec2; 2], bounded: bool, content: impl FnOnce(bool) -> Graphic) -> Option { let (effects, fill) = self.effects?; - // Each run's filter measures in its effect space, which a group's transform sets up unless the content is only moved since the effects were stamped - let runs = svg_runs(effects); + // A mode `mix-blend-mode` lacks blends the content's layer onto what lies beneath, and a fill moving it toward the mode's neutral color leaves it at full strength for the blend + let blends_onto_backdrop = self.layered && bounded && self.layer_reads_backdrop(); + let (fill, blend_fill) = match blends_onto_backdrop && self.blend_mode.fill_moves_layer_toward_neutral() { + true => (1., fill), + false => (fill, 1.), + }; + + // Each run's filter measures in its effect space, which a group's transform sets up unless the content is only moved since the effects were stamped. + // Content without effects, drawn through them for its blend mode, takes one run of none in its own space. + let mut runs = svg_runs(effects); + if runs.is_empty() { + runs.push((self.content_transform, 0..0)); + } let spaces: Vec = runs.iter().map(|(stamped_transform, _)| effect_space(self.content_transform, *stamped_transform)).collect(); if spaces.iter().any(|space| !space.matrix2.determinant().is_normal()) { return None; @@ -563,6 +608,12 @@ impl ItemCompositing<'_> { let trailing_masks = if blend_if_mask.is_some() { effects.len()..effects.len() } else { trailing_masks }; let filtered = leading_masks.end..trailing_masks.start; + // That blend, and those of pieces in modes `mix-blend-mode` lacks, read one copy of what lies beneath, taken before any of the item is drawn, over its reach and a document pixel more + let layer_blend = (blends_onto_backdrop || (self.layered && bounded && self.pieces_read_backdrop())).then(|| { + let reach = self.reach_around(bounds, 0.) + spans_along_axes(render.transform.matrix2.inverse()); + SvgLayerBlend::new(render, render_params, self.blend_mode, [bounds[0] - reach, bounds[1] + reach], blend_fill as f64) + }); + // The effects' drawn paints as markup in a run's effect space, where the content's placement places those following it. // The markup of SVG's own masks lies in the document, where the maps and images of its own effects reach it, unlike markup a filter embeds as an image. let paint_params = render_params.for_pattern(); @@ -638,7 +689,7 @@ impl ItemCompositing<'_> { let (run_layers, opacity) = match last { true => { let reading_layers = EffectLayers::plan(&reading_run, self.blend_mode, run_fill, self.layered); - reads_backdrop = reading_layers.reads_backdrop(); + reads_backdrop = reading_layers.reads_backdrop() || blends_onto_backdrop; (layers_of_last_split(reading_layers, rows.start - reading_rows.start), self.opacity) } false => (EffectLayers::plan(&run, BlendMode::Normal, run_fill, false), 1.), @@ -782,6 +833,8 @@ impl ItemCompositing<'_> { backdrop_cut_depth: reading_split, backdrop_masks, blend_if_mask, + layer_blend, + content_blends: blends_onto_backdrop, }) } } @@ -814,6 +867,10 @@ struct SvgEffects { backdrop_masks: Vec, /// The reference for the mask fading every layer by Blend If's ranges of what lies beneath, if any. blend_if_mask: Option, + /// What the layers blending by modes `mix-blend-mode` lacks blend onto, in the content's mode, if any do. + layer_blend: Option, + /// Whether the content's layer is one of them. + content_blends: bool, } /// One layer of an item's effects in SVG: a group filtering the content into the layer, blending by its mode. @@ -852,7 +909,15 @@ fn draw_effect_runs( draw_paint: &dyn Fn(usize, &mut VelloSceneBuilder), draw: &mut dyn FnMut(&mut VelloSceneBuilder), ) { - let Some(((stamped_transform, rows), earlier)) = runs.split_last() else { return draw(scene) }; + // Content without effects draws through a group of its own for a blend mode reading what lies beneath, though without bounds it reads nothing, as in SVG, so it draws natively faded by its fill + let Some(((stamped_transform, rows), earlier)) = runs.split_last() else { + if bounds.is_none() { + scene.push_viewport_layer(blend_mode.to_peniko(), opacity * fill); + draw(scene); + return scene.pop_layer(); + } + return scene.draw_effects(effects, fill, opacity, blend_mode, layered, bounds, DAffine2::IDENTITY, frame, &mut |_, _| {}, draw); + }; let space = effect_space(content_transform, *stamped_transform); let run = effects.run(rows.clone()); @@ -864,6 +929,13 @@ fn draw_effect_runs( return scene.draw_effects(&run, fill, opacity, blend_mode, layered, bounds, space, frame, &mut draw_run_paint, draw); } + // Blending onto what lies beneath, a fill moving the content toward neutral leaves the runs within at full strength + let blends_onto_backdrop = layered && bounds.is_some() && EffectLayers::plan(&run, blend_mode, fill, layered).content_reads_backdrop(fill); + let (inner_fill, outer_fill) = match blends_onto_backdrop && blend_mode.fill_moves_layer_toward_neutral() { + true => (1., fill), + false => (fill, 1.), + }; + // The runs before this one paint past the content, which this run then reaches from let content_bounds = bounds.map_or([DVec2::ZERO; 2], |bounds| [DVec2::new(bounds.x0, bounds.y0), DVec2::new(bounds.x1, bounds.y1)]); let earlier_effects = effects.run(0..rows.start); @@ -885,14 +957,25 @@ fn draw_effect_runs( run.0.push(row); } } - scene.draw_effects(&run, 1., opacity, blend_mode, layered, earlier_bounds, space, earlier_frame, &mut draw_run_paint, &mut |scene| { - let flattened = (1., BlendMode::Normal, false); - - // The runs within are drawn into this run's content, over nothing of their own, so they read nothing beneath them, as in SVG - scene.draw_placed(kurbo::Affine::IDENTITY, |scene| { - draw_effect_runs(scene, effects, earlier, fill, flattened, content_transform, bounds, frame, draw_paint, draw) - }); - }); + scene.draw_effects( + &run, + outer_fill, + opacity, + blend_mode, + layered, + earlier_bounds, + space, + earlier_frame, + &mut draw_run_paint, + &mut |scene| { + let flattened = (1., BlendMode::Normal, false); + + // The runs within are drawn into this run's content, over nothing of their own, so they read nothing beneath them, as in SVG + scene.draw_placed(kurbo::Affine::IDENTITY, |scene| { + draw_effect_runs(scene, effects, earlier, inner_fill, flattened, content_transform, bounds, frame, draw_paint, draw) + }); + }, + ); } /// The item as content of its own, without the opacity and blend mode that act on its effects' result as a whole, which an image of it takes instead. @@ -1106,13 +1189,19 @@ fn svg_draws_past_content(operation: &EffectOperation) -> bool { ) } -/// Whether the effects of any item nested anywhere inside `graphic` read what lies beneath them, like a background blur. O(items inside). +/// Whether any item nested anywhere inside `graphic` reads what lies beneath it, by its effects (like a background blur) or by its blend mode. O(items inside). fn nested_effects_read_backdrop(graphic: &Graphic) -> bool { fn item_reads(item: &Item) -> bool { - item.attribute::(ATTR_EFFECTS).is_some_and(effects_read_backdrop) + let fill = item.attribute_cloned_or::(ATTR_OPACITY_FILL, 1.) as f32; + item.attribute::(ATTR_EFFECTS).is_some_and(effects_read_backdrop) || item.attribute_cloned_or_default::(ATTR_BLEND_MODE).layer_reads_backdrop(fill) } fn list_reads(list: &List, nested: impl Fn(&T) -> bool) -> bool { - (0..list.len()).any(|index| list.attribute::(ATTR_EFFECTS, index).is_some_and(effects_read_backdrop) || list.element(index).is_some_and(&nested)) + (0..list.len()).any(|index| { + let fill = list.attribute_cloned_or::(ATTR_OPACITY_FILL, index, 1.) as f32; + let blend_mode = list.attribute_cloned_or_default::(ATTR_BLEND_MODE, index); + let reads = list.attribute::(ATTR_EFFECTS, index).is_some_and(effects_read_backdrop) || blend_mode.layer_reads_backdrop(fill); + reads || list.element(index).is_some_and(&nested) + }) } match graphic { @@ -1156,6 +1245,8 @@ fn render_svg_through_filters(render: &mut SvgRender, effects: Option layer_blend.as_ref().filter(|_| content_blends), + false => piece_blend.as_ref(), + }; + if backdrop.is_none() && layer_blend.is_none() && (blend_if_mask.is_none() || matrix.is_empty()) { draw_layer(render, layer, true); continue; } - render.parent_tag( - "g", - |attributes| { - if opacity < 1. { - attributes.push("opacity", opacity.to_string()); - } - if layer.blend_mode != BlendMode::default() { - attributes.push("style", layer.blend_mode.render()); - } - if let Some(mask) = &blend_if_mask { - attributes.push_backdrop("mask", mask); + let draw_contents = |render: &mut SvgRender| { + // Its markup lies in the last run's effect space, like the layer's content + if let Some(backdrop) = backdrop { + let masked = (backdrop_masks.iter()).fold(backdrop.markup.clone(), |markup, mask| format!(r#"{markup}"#)); + if let Some(mask) = &layer_fade_mask { + return render.parent_tag( + "g", + |attributes| { + if !matrix.is_empty() { + attributes.push(ATTR_TRANSFORM, matrix.clone()); + } + attributes.push("mask", mask.clone()); + }, + |render| { + let outside_transform = render.transform; + render.transform = outside_transform * transform; + render.leaf_node(SvgSegment::Backdrop(masked)); + draw_layer(render, layer, false); + render.transform = outside_transform; + }, + ); } - }, - |render| { - // Its markup lies in the last run's effect space, like the layer's content - if let Some(backdrop) = backdrop { - let masked = (backdrop_masks.iter()).fold(backdrop.markup.clone(), |markup, mask| format!(r#"{markup}"#)); - if let Some(mask) = &layer_fade_mask { - return render.parent_tag( - "g", - |attributes| { - if !matrix.is_empty() { - attributes.push(ATTR_TRANSFORM, matrix.clone()); - } - attributes.push("mask", mask.clone()); - }, - |render| { - let outside_transform = render.transform; - render.transform = outside_transform * transform; - render.leaf_node(SvgSegment::Backdrop(masked)); - draw_layer(render, layer, false); - render.transform = outside_transform; - }, - ); + let markup = if matrix.is_empty() { masked } else { format!(r#"{masked}"#) }; + render.leaf_node(SvgSegment::Backdrop(markup)); + } + draw_layer(render, layer, false); + }; + + // Blend If's mask fades the layer once it's blended + match (layer_blend, &blend_if_mask) { + (Some(layer_blend), None) => svg_layer_blend::draw_blended_layer(render, layer_blend, opacity, draw_contents), + (Some(layer_blend), Some(mask)) => render.parent_tag( + "g", + |attributes| attributes.push_backdrop("mask", mask), + |render| svg_layer_blend::draw_blended_layer(render, layer_blend, opacity, draw_contents), + ), + (None, _) => render.parent_tag( + "g", + |attributes| { + if opacity < 1. { + attributes.push("opacity", opacity.to_string()); } - let markup = if matrix.is_empty() { masked } else { format!(r#"{masked}"#) }; - render.leaf_node(SvgSegment::Backdrop(markup)); - } - draw_layer(render, layer, false); - }, - ); + if layer.blend_mode != BlendMode::default() && !layer.blend_mode.reads_backdrop() { + attributes.push("style", layer.blend_mode.render()); + } + if let Some(mask) = &blend_if_mask { + attributes.push_backdrop("mask", mask); + } + }, + draw_contents, + ), + } } let Some(markup) = content_markup else { return }; @@ -1434,6 +1548,10 @@ struct DeferredMarkup { bounds: [DVec2; 2], /// The reference for the mask fading the image by Blend If's ranges of what lies beneath, if any. mask: Option, + /// What the image blends onto by a mode `mix-blend-mode` lacks, if anything lies beneath it, with where its markup starts among the render's segments. + layer_blend: Option<(SvgLayerBlend, usize)>, + /// The item's opacity, which the image takes, or else the blend. + opacity: f32, } impl SvgRender { @@ -1443,23 +1561,37 @@ impl SvgRender { } } +/// The render parameters for content blending onto what's drawn beneath it by a mode CSS lacks, which in the viewport embed its images rather than draw them through canvases, +/// since the masks blending it read their pixels. +fn embedding_images_to_blend<'a>(render: &SvgRender, render_params: &'a RenderParams, compositing: &ItemCompositing) -> Cow<'a, RenderParams> { + let blends = || compositing.layered && compositing.effects.is_some() && (compositing.layer_reads_backdrop() || compositing.pieces_read_backdrop()); + match render_params.to_canvas() && blends() && render.draws_beneath() { + true => Cow::Owned(RenderParams { + embeds_images: true, + ..render_params.clone() + }), + false => Cow::Borrowed(render_params), + } +} + /// Opens markup standing in for an image the GPU renders of an item, if SVG filters can't carry out all its effects, which [`finish_deferred_markup`] then closes. /// `bounds` gives the content's extent in the current user space, and `overhang` how far it already paints past its frame there, as a group's nested effects do. /// Endless content, like a color or gradient filling everything, is given its extent but isn't `bounded`. -fn start_deferred_markup( +/// Returns the compositing the markup then draws in, which leaves out what a blend around it carries out. +fn start_deferred_markup<'a>( render: &mut SvgRender, render_params: &RenderParams, - compositing: &ItemCompositing, + compositing: &ItemCompositing<'a>, bounds: impl FnOnce() -> RenderBoundingBox, bounded: bool, overhang: f64, -) -> Option { +) -> (Option, ItemCompositing<'a>) { // TODO: Paints (patterns) whose effects need the GPU's maps then draw wrongly or not at all, unlike Vello. Embed a GPU render of such a paint, // filled in by `svg_readback.rs` like its images, maps, and planned generators (see the values and renders plan's boundary work). if !render.images_replace_markup(render_params) || compositing.svg_expresses_effects() || !render.transform.matrix2.determinant().is_normal() { - return None; + return (None, *compositing); } - let RenderBoundingBox::Rectangle([min, max]) = bounds() else { return None }; + let RenderBoundingBox::Rectangle([min, max]) = bounds() else { return (None, *compositing) }; // The image covers how far the effects reach past the content, measured in this user space, where effects relative to its extent take its size let reach = compositing.reach_around([min, max], overhang); @@ -1471,40 +1603,113 @@ fn start_deferred_markup( .then(|| svg_blend_if::underlying_mask(render, &underlying, reached, DVec2::ZERO, render_params)) .flatten(); + // A mode `mix-blend-mode` lacks blends the image as it blends markup, onto a copy of what lies beneath taken before the image's markup begins. + // Pieces of effects in layers of their own keep their modes only within the image, which then blends whole at full strength, its content faded by the fill. + let (blend_mode, fill) = (compositing.blend_mode, compositing.effects.map_or(1., |(_, fill)| fill)); + let moves_by_fill = blend_mode.fill_moves_layer_toward_neutral() && !compositing.layers().is_some_and(|layers| layers.layers.len() > 1); + let layer_blend = (compositing.layered && bounded && compositing.layer_reads_backdrop()) + .then(|| { + let pixel = spans_along_axes(render.transform.matrix2.inverse()); + let blend_fill = if moves_by_fill { fill } else { 1. }; + let blend = SvgLayerBlend::new(render, render_params, blend_mode, [reached[0] - pixel, reached[1] + pixel], blend_fill as f64); + (blend, render.svg.len()) + }) + .filter(|(blend, _)| blend.blends()); + + // The blend fades the markup standing in for the image, and moves it by the fill if it does that + let within = match &layer_blend { + Some((blend, _)) => ItemCompositing { + opacity: 1., + effects: compositing.effects.map(|(effects, fill)| (effects, if blend.moves_by_fill() { 1. } else { fill })), + ..*compositing + }, + None => *compositing, + }; + let id = generate_uuid(); render.leaf_node(deferred_image::image_markers(id).0); render.drawing_deferred_markup = true; - Some(DeferredMarkup { id, bounds: reached, mask }) + let markup = DeferredMarkup { + id, + bounds: reached, + mask, + layer_blend, + opacity: compositing.opacity, + }; + (Some(markup), within) } /// Closes the markup [`start_deferred_markup`] opened, if it did, recording the item `content` makes without its opacity and blend mode for the GPU to render. -fn finish_deferred_markup( - render: &mut SvgRender, - markup: Option, - render_params: &RenderParams, - compositing: &ItemCompositing, - blend_mode: BlendMode, - content: impl FnOnce() -> Graphic, -) { - let Some(DeferredMarkup { id, bounds, mask }) = markup else { return }; +fn finish_deferred_markup(render: &mut SvgRender, markup: Option, render_params: &RenderParams, blend_mode: BlendMode, content: impl FnOnce() -> Graphic) { + let Some(DeferredMarkup { + id, + bounds, + mask, + layer_blend, + opacity, + }) = markup + else { + return; + }; render.drawing_deferred_markup = false; render.leaf_node(deferred_image::image_markers(id).1); + // The image blending onto what lies beneath takes the blend's groups around it, and Blend If's mask around those, embedded so the masks within read its pixels + let mut content = content(); + let (opacity, blend_mode, mask, render_params) = match layer_blend { + Some((blend, start)) if svg_layer_blend::wrap_blended_layer(render, &blend, opacity, start) => { + if let Some(mask) = &mask { + render.svg.insert(start, SvgSegment::Slice(">")); + render.svg.insert(start, SvgSegment::Backdrop(format!(r#" mask="{mask}""#))); + render.svg.insert(start, SvgSegment::Slice("")); + } + + // A fill moving the content toward neutral leaves the image at full strength, for the blend to move it + if blend.moves_by_fill() { + without_fill(&mut content); + } + + let render_params = RenderParams { + embeds_images: true, + ..render_params.clone() + }; + (1., BlendMode::Normal, None, render_params) + } + _ if blend_mode.reads_backdrop() => (opacity, BlendMode::Normal, mask, render_params.clone()), + _ => (opacity, blend_mode, mask, render_params.clone()), + }; + render.deferred_images.push(DeferredImage { id, - content: DeferredContent::Item(content()), - render_params: render_params.clone(), + content: DeferredContent::Item(content), + render_params, user_to_document: render.transform, bounds, margin: render.ancestors_reach, - opacity: compositing.opacity, + opacity, blend_mode, mask, }); } +/// Removes the fill from the item `graphic` holds, if it's one item. +fn without_fill(graphic: &mut Graphic) { + match graphic { + Graphic::Graphic(item) => _ = item.remove_attribute::(ATTR_OPACITY_FILL), + Graphic::Vector(item) => _ = item.remove_attribute::(ATTR_OPACITY_FILL), + Graphic::RasterCPU(item) => _ = item.remove_attribute::(ATTR_OPACITY_FILL), + Graphic::RasterGPU(item) => _ = item.remove_attribute::(ATTR_OPACITY_FILL), + Graphic::Color(item) => _ = item.remove_attribute::(ATTR_OPACITY_FILL), + Graphic::Gradient(item) => _ = item.remove_attribute::(ATTR_OPACITY_FILL), + Graphic::Generator(item) => _ = item.remove_attribute::(ATTR_OPACITY_FILL), + Graphic::Text(item) => _ = item.remove_attribute::(ATTR_OPACITY_FILL), + _ => {} + } +} + /// Whether SVG filter primitives can carry out the effect operation, rather than leaving it undone. fn svg_expresses(operation: &EffectOperation) -> bool { match operation { @@ -3268,6 +3473,7 @@ fn render_graphic_item_svg(item: ItemRef<'_, Graphic>, next_clips: bool, mask_st .map(|appearance| render_params.for_child_item(appearance)); let render_params = child_render_params.as_ref().unwrap_or(render_params); let compositing = item.compositing(render_params, transform).clipped(mask_state.is_some()); + let render_params = &embedding_images_to_blend(render, render_params, &compositing); let matrix = format_transform_matrix(transform); let mut masked_by = None; @@ -3352,7 +3558,7 @@ fn render_graphic_item_svg(item: ItemRef<'_, Graphic>, next_clips: bool, mask_st _ => DVec2::ZERO, }; - let deferred = start_deferred_markup( + let (deferred, compositing) = start_deferred_markup( render, render_params, &compositing, @@ -3403,7 +3609,7 @@ fn render_graphic_item_svg(item: ItemRef<'_, Graphic>, next_clips: bool, mask_st ); }); - finish_deferred_markup(render, deferred, render_params, &compositing, blend_mode, || { + finish_deferred_markup(render, deferred, render_params, blend_mode, || { Graphic::Graphic(Box::new(without_opacity_and_blend_mode(item, element.clone()))) }); }); @@ -4131,17 +4337,10 @@ impl Render for List { } } -/// Emits one vector shape as SVG, with no wrapping group of its own. -/// When `filtered`, the group applying the item's effects takes its opacity and blend mode instead. -fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, filtered: bool, folded: Option<&FoldedPaints>, render: &mut SvgRender, render_params: &RenderParams) { +/// Emits one vector shape as SVG, with no wrapping group of its own, at the `opacity` and `blend_mode` it draws in. +fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, opacity: f32, blend_mode: BlendMode, folded: Option<&FoldedPaints>, render: &mut SvgRender, render_params: &RenderParams) { let paths = item.attribute::>(ATTR_PATHS).unwrap_or_else(|| no_paths()); let item_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); - let blend_mode_attr: BlendMode = if filtered { BlendMode::default() } else { item.attribute_cloned_or_default(ATTR_BLEND_MODE) }; - let opacity = if filtered { - 1. - } else { - item.compositing(render_params, item_transform).opacity_without_effects() - }; // The item's own declared appearance wins over one cascading down from an ancestor let own_appearance = item.attribute::(ATTR_APPEARANCE).and_then(Appearance::declared); @@ -4356,8 +4555,8 @@ fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, filtered: attributes.push("opacity", opacity.to_string()); } - if blend_mode_attr != BlendMode::default() { - attributes.push("style", blend_mode_attr.render()); + if blend_mode != BlendMode::default() { + attributes.push("style", blend_mode.render()); } }); @@ -4443,7 +4642,7 @@ fn render_vector_item_svg(item: ItemRef<'_, Vector>, next_clips: bool, clip_mask let bounds = vector.stroke_inclusive_bounding_box_with_transform(paths, DAffine2::IDENTITY, stroke.as_ref())?; Some(frame_of_bounds(bounds, item.attribute_cloned_or_default(ATTR_TRANSFORM))) }; - let deferred = start_deferred_markup(render, render_params, &compositing, || compositing.bounds_with_frame(bounds(), frame), true, 0.); + let (deferred, compositing) = start_deferred_markup(render, render_params, &compositing, || compositing.bounds_with_frame(bounds(), frame), true, 0.); // The filter's maps are of the effects that remain after those folded into the paints, which it numbers them by, and the folded ones keep alpha let filters = compositing.svg_filters(render, render_params, bounds, |keeps| { let mut content = effects_content(item, vector.clone(), keeps); @@ -4453,6 +4652,12 @@ fn render_vector_item_svg(item: ItemRef<'_, Vector>, next_clips: bool, clip_mask let filtered = filters.is_some(); let blend_mode: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); + // A filter's wrapping group takes the opacity and blend mode instead + let (opacity, shape_blend_mode) = match filtered { + true => (1., BlendMode::default()), + false => (compositing.opacity_without_effects(), blend_mode), + }; + render_svg_through_filters(render, filters, compositing.opacity, |render| { // The item's own filters read its paints around each pixel, so a pattern paint's images and maps cover past the view as far as they read let own_reach = if filtered { @@ -4461,11 +4666,11 @@ fn render_vector_item_svg(item: ItemRef<'_, Vector>, next_clips: bool, clip_mask 0. }; render.ancestors_reach += own_reach; - render_vector_shape_svg(item, vector, filtered, folded.as_ref(), render, render_params); + render_vector_shape_svg(item, vector, opacity, shape_blend_mode, folded.as_ref(), render, render_params); render.ancestors_reach -= own_reach; }); - finish_deferred_markup(render, deferred, render_params, &compositing, blend_mode, || { + finish_deferred_markup(render, deferred, render_params, blend_mode, || { Graphic::Vector(Box::new(without_opacity_and_blend_mode(item, vector.clone()))) }); }; @@ -5191,6 +5396,7 @@ fn render_raster_cpu_item_svg(item: ItemRef<'_, Raster>, render: &mut SvgRe let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); let compositing = item.compositing(render_params, transform); + let render_params = &embedding_images_to_blend(render, render_params, &compositing); if image.data.is_empty() { return; @@ -5210,7 +5416,7 @@ fn render_raster_cpu_item_svg(item: ItemRef<'_, Raster>, render: &mut SvgRe }; let bounds = || RenderBoundingBox::Rectangle((transform * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box()); - let deferred = start_deferred_markup(render, render_params, &compositing, bounds, true, 0.); + let (deferred, compositing) = start_deferred_markup(render, render_params, &compositing, bounds, true, 0.); // The filter's maps are of the adjusted image with the effects that remain, which the filter numbers them by let filters = compositing.svg_filters(render, render_params, bounds, |keeps| { let mut content = effects_content(item, image.clone(), keeps); @@ -5229,7 +5435,7 @@ fn render_raster_cpu_item_svg(item: ItemRef<'_, Raster>, render: &mut SvgRe }); // The GPU carries out the leading adjustments too, on the image as it was - finish_deferred_markup(render, deferred, render_params, &compositing, blend_mode_attr, || { + finish_deferred_markup(render, deferred, render_params, blend_mode_attr, || { Graphic::RasterCPU(Box::new(without_opacity_and_blend_mode(item, source_image.clone()))) }); } @@ -5406,7 +5612,7 @@ fn render_generator_item_svg(item: ItemRef<'_, Generator>, render: &mut SvgRende let image_transform = transform * DAffine2::from_translation(area[0]) * DAffine2::from_scale(area[1] - area[0]); let bounds = (image_transform * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box(); - let deferred = start_deferred_markup(render, render_params, &compositing, || RenderBoundingBox::Rectangle(bounds), false, 0.); + let (deferred, compositing) = start_deferred_markup(render, render_params, &compositing, || RenderBoundingBox::Rectangle(bounds), false, 0.); let filters = compositing.svg_filters_within(render, render_params, bounds, false, |keeps| { let mut content = effects_content(item, generator, keeps); content.set_attribute(ATTR_EFFECTS, compositing.effects.map(|(effects, _)| effects.clone()).unwrap_or_default()); @@ -5422,9 +5628,7 @@ fn render_generator_item_svg(item: ItemRef<'_, Generator>, render: &mut SvgRende render_raster_cpu_image_svg(&image, image_transform, opacity, blend_mode, render, render_params) }); - finish_deferred_markup(render, deferred, render_params, &compositing, blend_mode_attr, || { - Graphic::Generator(without_opacity_and_blend_mode(item, generator)) - }); + finish_deferred_markup(render, deferred, render_params, blend_mode_attr, || Graphic::Generator(without_opacity_and_blend_mode(item, generator))); } /// The part of an item's own space in view, which `transform` places, grown past the view by `reach` in document pixels, with the pixels across and down it covers in the view. @@ -5693,7 +5897,7 @@ fn render_color_item_svg(item: ItemRef<'_, Color>, render: &mut SvgRender, rende if let Some(extent) = extent { let blend_mode: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); let bounds = || RenderBoundingBox::Rectangle(extent); - let deferred = start_deferred_markup(render, render_params, &compositing, bounds, false, 0.); + let (deferred, compositing) = start_deferred_markup(render, render_params, &compositing, bounds, false, 0.); let filters = compositing.svg_filters_within(render, render_params, extent, false, |keeps| Graphic::Color(effects_content(item, color, keeps))); // Without filters, as in an effect space that collapses, the color takes its opacity and blend mode as if its masks left it without edges @@ -5702,9 +5906,7 @@ fn render_color_item_svg(item: ItemRef<'_, Color>, render: &mut SvgRender, rende true => emit_endless_color(render, color, 1., BlendMode::Normal, None), false => render_edgeless_color_svg(item, render, &compositing, color, render_params), }); - finish_deferred_markup(render, deferred, render_params, &compositing, blend_mode, || { - Graphic::Color(without_opacity_and_blend_mode(item, color)) - }); + finish_deferred_markup(render, deferred, render_params, blend_mode, || Graphic::Color(without_opacity_and_blend_mode(item, color))); return; } @@ -6069,7 +6271,7 @@ fn render_gradient_item_svg_with_thumbnail_rect(item: ItemRef<'_, Gradient>, thu if let Some(extent) = extent.filter(|_| thumbnail_rect.is_none()) { let blend_mode: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); let bounds = || RenderBoundingBox::Rectangle(extent); - let deferred = start_deferred_markup(render, render_params, &compositing, bounds, false, 0.); + let (deferred, compositing) = start_deferred_markup(render, render_params, &compositing, bounds, false, 0.); let filters = compositing.svg_filters_within(render, render_params, extent, false, |keeps| Graphic::Gradient(effects_content(item, source_gradient.clone(), keeps))); // Without filters, as in an effect space that collapses, the gradient takes its opacity and blend mode as if its masks left it without edges @@ -6078,7 +6280,7 @@ fn render_gradient_item_svg_with_thumbnail_rect(item: ItemRef<'_, Gradient>, thu true => render_gradient_shape_svg(item, source_gradient, settings, None, 1., BlendMode::Normal, render, render_params), false => render_edgeless_gradient_svg(item, source_gradient, settings, None, &compositing, render, render_params), }); - finish_deferred_markup(render, deferred, render_params, &compositing, blend_mode, || { + finish_deferred_markup(render, deferred, render_params, blend_mode, || { Graphic::Gradient(without_opacity_and_blend_mode(item, source_gradient.clone())) }); return; @@ -6741,7 +6943,7 @@ fn render_text_item_svg(item: ItemRef<'_, String>, render: &mut SvgRender, rende return; } - let deferred = start_deferred_markup(render, render_params, &compositing, || layout_bounds, true, 0.); + let (deferred, compositing) = start_deferred_markup(render, render_params, &compositing, || layout_bounds, true, 0.); let filters = compositing.svg_filters(render, render_params, || layout_bounds, |keeps| Graphic::Text(effects_content(item, text.clone(), keeps))); let filtered = filters.is_some(); @@ -6784,9 +6986,7 @@ fn render_text_item_svg(item: ItemRef<'_, String>, render: &mut SvgRender, rende ); }); - finish_deferred_markup(render, deferred, render_params, &compositing, blend_mode_attr, || { - Graphic::Text(without_opacity_and_blend_mode(item, text.clone())) - }); + finish_deferred_markup(render, deferred, render_params, blend_mode_attr, || Graphic::Text(without_opacity_and_blend_mode(item, text.clone()))); } /// Draws one item of text content into the Vello scene, laying out its glyphs under the item's styling. @@ -11264,4 +11464,518 @@ mod tests { "the bounds {min} to {max} cut off the square's corners" ); } + + /// A 2 by 2 raster of a dark orange placed by `transform`, blending by `blend_mode`. + fn blended_image(transform: DAffine2, blend_mode: BlendMode) -> Item> { + use graphic_types::raster_types::Image; + + let color = Color::from_gamma_srgb_channels(0.6, 0.3, 0.1, 1.); + Item::new_from_element(Raster::new_cpu(Image::new(2, 2, color))) + .with_attribute(ATTR_TRANSFORM, transform) + .with_attribute(ATTR_BLEND_MODE, blend_mode) + } + + /// A unit square of a solid `color` placed by `transform`, blending by `blend_mode`. + fn colored_square(color: Color, transform: DAffine2, blend_mode: BlendMode) -> Item { + use kurbo::Shape; + + let mut item = Vector::item_from_bezpath(&kurbo::Rect::new(0., 0., 1., 1.).to_path(0.1)); + item.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(color)))); + item.set_attribute(ATTR_TRANSFORM, transform); + item.set_attribute(ATTR_BLEND_MODE, blend_mode); + item + } + + /// The markup inside each mask showing what lies beneath a layer blending by a mode CSS lacks, in the order they're written to the `defs`. + fn layer_blend_masks(defs: &str) -> Vec<&str> { + defs.split(r#"").next()).collect() + } + + #[test] + fn svg_layers_in_modes_css_lacks_blend_onto_a_copy_of_what_lies_beneath() { + let placement = DAffine2::from_translation(DVec2::splat(5.)) * DAffine2::from_scale(DVec2::splat(10.)); + + for blend_mode in BlendMode::list().into_iter().flatten().copied() { + let mut images = List::new_from_item(white_image(DAffine2::from_scale(DVec2::splat(20.)), false)); + images.push(blended_image(placement, blend_mode)); + let render = exported(&images); + let svg = render.svg.to_svg_string(); + + // The modes CSS has blend natively + if !blend_mode.reads_backdrop() { + let native = blend_mode == BlendMode::Normal || svg.contains(&blend_mode.render().trim().to_string()); + assert!(native && layer_blend_masks(&render.svg_defs).is_empty(), "{blend_mode}: {svg}"); + continue; + } + + // The layer's alpha shows the blend, built on a copy of the image beneath, which also shows it by its alpha, and on copies of the layer + assert!(svg.contains(r#"mask="url(#layer-blend-shown-"#) && !svg.contains("mix-blend-mode: normal"), "{blend_mode}: {svg}"); + let masks = layer_blend_masks(&render.svg_defs); + assert!(matches!(masks[..], [mask] if mask.contains(r##"= 1. { + assert!(compositing.effects.is_none() && svg.contains(blend_mode.render().trim()), "{case}: {svg}"); + assert!(layer_blend_masks(&render.svg_defs).is_empty() && !render.svg_defs.contains("backdrop-"), "{case}: {}", render.svg_defs); + continue; + } + + // Below it, the layer moved toward neutral by its fill blends onto a copy of what lies beneath, as in the modes CSS lacks + assert!(compositing.effects.is_some(), "{case}"); + assert!( + matches!(layer_blend_masks(&render.svg_defs)[..], [mask] if mask.contains(r##" *blend_mode, + _ => unreachable!(), + }; + let mut squares = List::new_from_item(colored_square(Color::WHITE, DAffine2::from_scale(DVec2::splat(30.)), BlendMode::Normal)); + squares.push(orange_square_item(&[piece], fill, 1.).with_attribute(ATTR_BLEND_MODE, content_mode)); + let render = exported(&squares); + let svg = render.svg.to_svg_string(); + + // The content's layer blends onto the copy of what lies beneath where its mode reads it at its fill, and a piece's where its own mode does, at full strength + let content_blends = content_mode.layer_reads_backdrop(fill as f32); + let blended_layers: Vec<&str> = svg + .match_indices(r#" = render.svg_defs.split("").next()).collect(); + let faded: Vec<&&str> = filters.iter().filter(|filter| filter.contains(r#" List> { + let mut images = List::new_from_item(white_image(DAffine2::from_scale(DVec2::splat(20.)), false)); + for index in 0..count { + images.push(blended_image( + DAffine2::from_translation(DVec2::splat(index as f64)) * DAffine2::from_scale(DVec2::splat(10.)), + BlendMode::LinearDodge, + )); + } + images + } + + #[test] + fn exported_svg_layer_blends_over_others_blend_onto_an_embedded_image_of_what_lies_beneath_rather_than_nested_copies() { + for count in [2, 3, 5] { + let render = exported(&stacked_layer_blends(count)); + + // Only the lowest copies what lies beneath in markup, and each above takes an image of the white image and the blends beneath it + let masks = layer_blend_masks(&render.svg_defs); + assert_eq!(masks.len(), count, "{count}: {}", render.svg_defs); + assert!( + masks[0].contains(r##">(); + let [image] = items[..] else { panic!("{case}: one image of the item, not {}", items.len()) }; + assert!( + image.blend_mode == BlendMode::Normal && image.opacity == 1. && image.mask.is_none() && !image.render_params.to_canvas(), + "{case}" + ); + let DeferredContent::Item(Graphic::RasterCPU(content)) = &image.content else { + panic!("{case}: the raster's image") + }; + assert!(content.attribute::(ATTR_OPACITY_FILL).is_none(), "{case}: the blend moves the image by its fill"); + + let faded = element_markup(&svg, r#">(); + let [image] = items[..] else { panic!("one image of the item, not {}", items.len()) }; + let DeferredContent::Item(Graphic::RasterCPU(content)) = &image.content else { + panic!("the raster's image") + }; + assert!(content.attribute::(ATTR_OPACITY_FILL).is_some_and(|fill| *fill == 0.)); + assert!(svg.contains(r#"mask="url(#layer-blend-shown-"#) && !render.svg_defs.contains("layer-blend-fill-shown-"), "{svg}"); + } + + #[test] + fn svg_layer_blends_of_images_the_gpu_renders_of_shapes_no_filter_draws_fade_the_markup_standing_in_once() { + use graphic_types::{Effect, EffectOperation, stamp_effect}; + + // A square in Linear Burn at half opacity with a Motion Blur stamped before its height collapsed, leaving no space for a filter to measure in + let mut square = colored_square(Color::from_gamma_srgb_channels(1., 0.5, 0., 1.), DAffine2::from_scale(DVec2::splat(10.)), BlendMode::LinearBurn); + stamp_effect( + &mut square, + Effect::new(&EffectOperation::MotionBlur { + angle: 0., + distance: 4., + gamma: false, + }), + ); + square.set_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(5.)) * DAffine2::from_scale(DVec2::new(10., 0.))); + square.set_attribute(ATTR_OPACITY, 0.5); + let mut squares = List::new_from_item(colored_square(Color::WHITE, DAffine2::from_scale(DVec2::splat(20.)), BlendMode::Normal)); + squares.push(square); + + for (case, render_params) in [("exported", exported_params()), ("in the viewport", RenderParams::default())] { + let mut render = SvgRender::new(); + squares.render_svg(&mut render, &render_params); + let svg = render.svg.to_svg_string(); + + // The markup between the markers, shown while the GPU renders the image or if it can't, takes the opacity only from the blend around it + let [image] = &render.deferred_images[..] else { + panic!("{case}: one image of the square, not {}", render.deferred_images.len()) + }; + let layer = element_markup(&svg, r#" RenderParams { + RenderParams { + for_export: true, + ..Default::default() + } + } } diff --git a/node-graph/libraries/rendering/src/svg_backdrop.rs b/node-graph/libraries/rendering/src/svg_backdrop.rs index 8adadd809d3..ed349ab2734 100644 --- a/node-graph/libraries/rendering/src/svg_backdrop.rs +++ b/node-graph/libraries/rendering/src/svg_backdrop.rs @@ -134,17 +134,9 @@ impl SvgRender { /// Markup showing what lies beneath the content drawn next, within the `region` of the current user space it reads, or `None` if nothing does. /// It copies the markup drawn since the backdrop root, or where that holds a copy already, stands for an image the GPU renders of it or else leaves held copies out. - /// The image is embedded `for_mask`, which draws no canvas. + /// The image is embedded `for_mask`, since a mask can't render canvases. pub(crate) fn backdrop_copy(&mut self, render_params: &RenderParams, region: [DVec2; 2], read_reach: f64, for_mask: bool) -> Option { - if self.drawing_deferred_markup || !self.transform.matrix2.determinant().is_normal() { - return None; - } - let root = self.open_groups.groups.iter().rposition(|group| group.isolates)?; - - // A clip's own stack lies over nothing, as in the GPU's layer for it, though a group isolated within it still reads what it drew - if root == 0 && self.open_groups.clip { - return None; - } + let root = self.backdrop_root()?; // The backdrop root's own clip cuts every level's copy as it cuts the originals, from a group around them in the space of its content let root_group = &self.open_groups.groups[root]; @@ -152,8 +144,9 @@ impl SvgRender { let clip = root_group.clip_path.clone().zip(root_group.user_to_document); let copies_to_document = clip.as_ref().map_or(self.transform, |(_, root_to_document)| *root_to_document); - // A mask draws no canvas, so where one stands in for what lies beneath, the GPU's image of it shows what's displayed, as it does for later readers - let images = holds_backdrop || (for_mask && self.draws_canvases_since(root, render_params)); + // In the viewport, images draw to canvases in `` elements, which a mask can't render, so a mask reads the GPU's image of what lies beneath instead, as later readers do + let draws_canvases = self.draws_canvases_since(root, render_params); + let images = holds_backdrop || (for_mask && draws_canvases); // An image needs the outline of the root's clip, if it has one, to cut what it holds by let image_clip = match images && self.images_replace_markup(render_params) { @@ -167,7 +160,7 @@ impl SvgRender { // Elsewhere, copies leave out the blurred copies earlier content holds, so they never nest, losing only the blur of a blur where it overlaps let image = images && image_clip.is_some(); let copies = match (images, image_clip) { - (false, _) => self.backdrop_markup_copies(root, copies_to_document, render_params.to_canvas(), false), + (false, _) => self.backdrop_markup_copies(root, copies_to_document, render_params.to_canvas() || draws_canvases, false), (true, Some(clip)) => { let image_params = RenderParams { embeds_images: render_params.embeds_images || for_mask, @@ -194,11 +187,42 @@ impl SvgRender { Some(BackdropCopy { markup, image }) } - /// Whether the markup drawn since the backdrop `root` draws through canvases, as images and the GPU's images of content do in the viewport. O(segments drawn since the root). + /// The group isolating the content drawn next from what lies beneath it, its backdrop root, as an index of the open groups, or `None` if it reads nothing beneath. + fn backdrop_root(&self) -> Option { + if self.drawing_deferred_markup || !self.transform.matrix2.determinant().is_normal() { + return None; + } + let root = self.open_groups.groups.iter().rposition(|group| group.isolates)?; + + // A clip's own stack lies over nothing, as in the GPU's layer for it, though a group isolated within it still reads what it drew + (root > 0 || !self.open_groups.clip).then_some(root) + } + + /// Whether anything is drawn beneath the content drawn next for [`Self::backdrop_copy`] to show, as markup it copies or content it has the GPU draw again. + /// O(segments drawn since the backdrop root). + pub(crate) fn draws_beneath(&self) -> bool { + let Some(root) = self.backdrop_root() else { return false }; + + (root..self.open_groups.groups.len()).any(|level| { + let group = &self.open_groups.groups[level]; + let markup = &self.svg[group.content_start..self.level_content_end(level)]; + let copied = group.user_to_document.is_some() && markup.iter().any(|segment| segment.as_str().contains('<')); + copied || group.drawn.iter().any(|drawn| drawn.count > 0) + }) + } + + /// Where the markup drawn directly inside the open group at `level` ends among the render's segments, at the tag of the group open inside it, if any. + fn level_content_end(&self, level: usize) -> usize { + self.open_groups.groups.get(level + 1).map_or(self.svg.len(), |inner| inner.tag_start) + } + + /// Whether the markup drawn since the backdrop `root` draws through canvases, as images and the GPU's images of content do in the viewport the `render_params` draw in, + /// even where the content reading it embeds its own images. O(segments drawn since the root). fn draws_canvases_since(&self, root: usize, render_params: &RenderParams) -> bool { + let in_viewport = !(render_params.for_export || render_params.thumbnail || render_params.for_mask || render_params.inside_pattern); let start = self.open_groups.groups[root].content_start; let draws_canvas = |segment: &SvgSegment| segment.as_str().contains("data-canvas-placeholder") || deferred_image::holds_image_markers(segment.as_str()); - render_params.to_canvas() && self.svg[start..].iter().any(draws_canvas) + in_viewport && self.svg[start..].iter().any(draws_canvas) } /// Copies of the content drawn at each level of the groups open since the backdrop `root`, in the space `copies_to_document` maps into the document, or `None` if there's none. @@ -212,8 +236,7 @@ impl SvgRender { let mut copies = Vec::new(); for level in (root..=current).rev() { let group = &self.open_groups.groups[level]; - let start = group.content_start; - let end = self.open_groups.groups.get(level + 1).map_or(self.svg.len(), |inner| inner.tag_start); + let (start, end) = (group.content_start, self.level_content_end(level)); let drawn = self.svg[start..end].iter().filter(kept).any(|segment| segment.as_str().contains('<')); let Some(user_to_document) = group.user_to_document.filter(|_| drawn) else { continue }; @@ -271,6 +294,7 @@ impl SvgRender { } /// Markup showing what lies beneath content (see [`SvgRender::backdrop_copy`]). +#[derive(Clone)] pub(crate) struct BackdropCopy { pub markup: String, /// Whether the markup stands for an image the GPU renders of what lies beneath, rather than copying what's drawn. diff --git a/node-graph/libraries/rendering/src/svg_blend_if.rs b/node-graph/libraries/rendering/src/svg_blend_if.rs index 3fac1b37b25..f36f143b0a2 100644 --- a/node-graph/libraries/rendering/src/svg_blend_if.rs +++ b/node-graph/libraries/rendering/src/svg_blend_if.rs @@ -49,7 +49,7 @@ pub(crate) fn weight(push: &mut impl FnMut(&str, &str, &str) -> String, image: & /// The viewport's copy of what lies beneath as `markup`, with what a mask can't draw, so SVG can't read, covered by rectangles of the `key` color the ranges show in full. /// What's drawn over a cover still hides it, as it hides the image the cover stands in for. -fn with_unreadable_covered(markup: &str, key: &str) -> String { +pub(crate) fn with_unreadable_covered(markup: &str, key: &str) -> String { with_canvases_covered(&with_deferred_images_marked_for_covers(markup, key), key) } diff --git a/node-graph/libraries/rendering/src/svg_layer_blend.rs b/node-graph/libraries/rendering/src/svg_layer_blend.rs new file mode 100644 index 00000000000..04ad6880722 --- /dev/null +++ b/node-graph/libraries/rendering/src/svg_layer_blend.rs @@ -0,0 +1,571 @@ +//! Layers in the blend modes `mix-blend-mode` lacks, or below a full fill moving them toward neutral in Color Dodge and Color Burn, built all natively from what SVG composites, +//! over a copy of what lies beneath (see [`SvgRender::backdrop_copy`]). +//! The layer's alpha, times [`layer_fill_shown`] where its fill moves it toward neutral, shows an opaque result: the layer made opaque, and over it the blend, shown by the alpha of what lies beneath, +//! as the W3C's general formula mixes them. The blend draws the layer, recolored and made opaque, over an opaque copy of what lies beneath, where `s` is the layer moved toward neutral by its fill: +//! - Linear Burn, Subtract: Lighten by `x`, then Difference by `x`, which leaves `max(0, b - x)` exactly, for `x` of `1 - s` or `s`. +//! - Linear Dodge: that over the inverted copy, inverted back. Linear Light: Linear Burn by `2s`, then Linear Dodge by `2s - 1`. +//! - Hard Mix: at full strength, the copy where it and the layer sum to white exactly, and white where they sum past it, each where Color Dodge reaches white. +//! Below it, Linear Burn by `q (1 - s)`, stretched by `1 / (1 - q)`. +//! - Divide: Color Dodge by the inverted layer. Pin Light: Darken by `2s`, then Lighten by `2s - 1`. Vivid Light: Color Burn by `2s`, then Color Dodge by `2s - 1`. +//! - Darker Color, Lighter Color: the layer over the copy, masked to where Luminosity moves the copy's color down (or up) by a level or more. +//! - Color Dodge, Color Burn: themselves by `s`. + +use crate::renderer::{RenderParams, SvgRender, SvgSegment}; +use crate::svg_backdrop::BackdropCopy; +use crate::svg_blend_if::with_unreadable_covered; +use core_types::blending::{BlendMode, layer_fill_shown}; +use core_types::uuid::generate_uuid; +use glam::DVec2; +use std::fmt::Write; + +/// A layer blending by a mode `mix-blend-mode` lacks, with what it reads to blend onto what lies beneath. +pub(crate) struct SvgLayerBlend { + blend_mode: BlendMode, + /// The copy of what lies beneath, taken before any of the item is drawn, or `None` with nothing beneath. + copy: Option, + /// The region of the current user space the layer covers, which the blend's filters and masks cover too. + region: [DVec2; 2], + /// The fill moving the layer toward the mode's neutral color (see [`BlendMode::fill_moves_layer_toward_neutral`]), or 1 where the layer is faded by its fill already. + fill: f64, +} + +impl SvgLayerBlend { + /// Copies what lies beneath the `region` of the current user space, before any of the layer is drawn, for it to blend onto by the mode. + pub(crate) fn new(render: &mut SvgRender, render_params: &RenderParams, blend_mode: BlendMode, region: [DVec2; 2], fill: f64) -> Self { + Self { + blend_mode, + copy: render.backdrop_copy(render_params, region, 0., true), + region, + fill, + } + } + + /// The blend of another layer of the same item by its own `blend_mode` at full strength, onto the same copy of what lies beneath. + pub(crate) fn with_mode(&self, blend_mode: BlendMode) -> Self { + Self { + blend_mode, + copy: self.copy.clone(), + region: self.region, + fill: 1., + } + } + + /// Whether the layer blends onto what lies beneath, rather than over nothing. + pub(crate) fn blends(&self) -> bool { + self.copy.is_some() && recipe(self.blend_mode, self.fill).is_some() + } + + /// Whether the blend moves the layer toward the mode's neutral color by a fill below full, which the layer itself then leaves out. + pub(crate) fn moves_by_fill(&self) -> bool { + self.fill < 1. + } +} + +/// A map of each straight color channel, `scale × channel + offset`, clamped to 0 to 1. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Recolor { + scale: f64, + offset: f64, +} + +impl Recolor { + const IDENTITY: Self = Self { scale: 1., offset: 0. }; + const INVERT: Self = Self { scale: -1., offset: 1. }; +} + +/// One step building a mode SVG lacks: the layer recolored and made opaque, then drawn by a native mode. +#[derive(Clone, Copy, Debug)] +struct BlendStep { + recolor: Recolor, + blend_mode: BlendMode, +} + +/// A stage of steps over its base (the copy of what lies beneath, or the stage before), recolored, whose result it then recolors by `stretch`. +#[derive(Clone, Debug)] +struct BlendStage { + base: Recolor, + steps: Vec, + stretch: Recolor, +} + +/// How SVG builds a mode it lacks over an opaque copy of what lies beneath. +#[derive(Clone, Debug)] +enum BlendRecipe { + Stages(Vec), + /// Hard Mix at full strength: the copy where it and the layer sum to white exactly, and white where they sum past it. + HardMixThreshold, + /// The layer's whole color where its luma is lower than that of what lies beneath, or higher if `lighter`. + Pick { + lighter: bool, + }, +} + +/// The recipe for a mode SVG lacks at the `fill` moving the layer's color toward neutral where the mode does that, or `None` for a mode SVG has at it. +fn recipe(blend_mode: BlendMode, fill: f64) -> Option { + use BlendMode::*; + + let step = |scale: f64, offset: f64, blend_mode: BlendMode| BlendStep { + recolor: Recolor { scale, offset }, + blend_mode, + }; + // Lightening by `x`, then the difference from it, leaves `max(0, b - x)` in whole levels + let burn_by = |scale: f64, offset: f64| vec![step(scale, offset, Lighten), step(scale, offset, Difference)]; + let stage = |base: Recolor, steps: Vec, stretch: Recolor| BlendStage { base, steps, stretch }; + let (identity, invert) = (Recolor::IDENTITY, Recolor::INVERT); + let steepness = 255. * fill / 256.; + + let stages = match blend_mode { + LinearBurn => vec![stage(identity, burn_by(-fill, fill), identity)], + Subtract => vec![stage(identity, burn_by(1., 0.), identity)], + LinearDodge => vec![stage(invert, burn_by(fill, 0.), invert)], + LinearLight => vec![stage(identity, burn_by(-2. * fill, fill), identity), stage(invert, burn_by(2. * fill, -fill), invert)], + HardMix if fill >= 1. => return Some(BlendRecipe::HardMixThreshold), + HardMix => vec![stage( + identity, + burn_by(-steepness, steepness), + Recolor { + scale: 1. / (1. - steepness), + offset: 0., + }, + )], + Divide => vec![stage(identity, vec![step(-1., 1., ColorDodge)], identity)], + ColorDodge if fill < 1. => vec![stage(identity, vec![step(fill, 0., ColorDodge)], identity)], + ColorBurn if fill < 1. => vec![stage(identity, vec![step(fill, 1. - fill, ColorBurn)], identity)], + PinLight => vec![stage(identity, vec![step(2., 0., Darken), step(2., -1., Lighten)], identity)], + VividLight => vec![stage(identity, vec![step(2. * fill, 1. - fill, ColorBurn), step(2. * fill, -fill, ColorDodge)], identity)], + DarkerColor => return Some(BlendRecipe::Pick { lighter: false }), + LighterColor => return Some(BlendRecipe::Pick { lighter: true }), + _ => return None, + }; + Some(BlendRecipe::Stages(stages)) +} + +/// The filters and masks one blended layer writes into the render's defs, each within the layer's region. +struct BlendDefs<'a> { + defs: &'a mut String, + region: String, + uuid: u64, + recolors: Vec<(Recolor, String)>, +} + +impl BlendDefs<'_> { + /// Writes a def named `name` with the `tag`, the `attributes` past its ID, and the `children`, returning a reference to it. + fn write(&mut self, name: &str, tag: &str, attributes: &str, children: &str) -> String { + let id = format!("layer-blend-{name}-{}", self.uuid); + write!(self.defs, r#"<{tag} id="{id}" {attributes} {}>{children}"#, self.region).unwrap(); + format!("url(#{id})") + } + + /// A filter named `name` of the `primitives` on gamma-encoded colors. + fn filter(&mut self, name: &str, primitives: &str) -> String { + self.write(name, "filter", r#"filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB""#, primitives) + } + + /// A mask named `name` showing what the `markup` covers, by its alpha. + fn mask(&mut self, name: &str, markup: &str) -> String { + self.write(name, "mask", r#"mask-type="alpha" maskUnits="userSpaceOnUse""#, markup) + } + + /// A filter making what it draws opaque in its straight color, recolored, written once for each recoloring. + fn recolor(&mut self, recolor: Recolor) -> String { + if let Some((_, reference)) = self.recolors.iter().find(|(written, _)| *written == recolor) { + return reference.clone(); + } + + let Recolor { scale, offset } = recolor; + let name = format!("recolor-{}", self.recolors.len()); + let reference = self.filter( + &name, + &format!(r#""#), + ); + self.recolors.push((recolor, reference.clone())); + reference + } +} + +/// What a blended layer draws around it, with its defs written. +struct BlendGroups { + /// The attributes of each group around the layer made opaque and the blend over it, outermost first. + around: Vec>, + /// The filter making the layer opaque, beneath the blend. + opaque: String, + /// The ID the layer's own group takes, for copies of it to reference. + layer_id: String, + /// The blend's markup, drawn over the layer made opaque, which copies of what lies beneath leave out so they never nest. + blended: String, +} + +/// Writes the defs of the `blend` of a layer at `opacity` and returns what it draws around the layer, or `None` with nothing beneath to blend onto. +fn blend_groups(render: &mut SvgRender, blend: &SvgLayerBlend, opacity: f32) -> Option { + let (Some(copy), Some(recipe)) = (&blend.copy, recipe(blend.blend_mode, blend.fill)) else { + return None; + }; + + let uuid = generate_uuid(); + let layer_id = format!("layer-blend-layer-{uuid}"); + let [min, max] = blend.region; + let mut defs = BlendDefs { + defs: &mut render.svg_defs, + region: format!(r#"x="{}" y="{}" width="{}" height="{}""#, min.x, min.y, max.x - min.x, max.y - min.y), + uuid, + recolors: Vec::new(), + }; + + // Copies of the layer reference it, and masks read what lies beneath from an image or a copy covering what they can't draw + let layer = format!(r##""##); + let beneath_in_mask = if copy.image { copy.markup.clone() } else { with_unreadable_covered(©.markup, "#000000") }; + let opaque = defs.recolor(Recolor::IDENTITY); + let drawn = |filter: &str, blend_mode: BlendMode, markup: &str| format!(r#"{markup}"#, blend_mode.render().trim()); + + let blend_markup = match recipe { + // Each stage's steps blend over its base alone, within a group recoloring what they leave + BlendRecipe::Stages(stages) => { + let mut result = copy.markup.clone(); + for stage in stages { + let base = format!(r#"{result}"#, defs.recolor(stage.base)); + let steps: String = stage.steps.iter().map(|step| drawn(&defs.recolor(step.recolor), step.blend_mode, &layer)).collect(); + result = format!(r#"{base}{steps}"#, defs.recolor(stage.stretch)); + } + result + } + // Color Dodge reaches white exactly where the layer and the copy sum to white or past it, or past it alone for the layer a level darker + BlendRecipe::HardMixThreshold => { + let white = defs.filter("white", r#""#); + let mut reaches_white = |offset: f64| { + format!( + r#"{}{}"#, + copy.markup, + drawn(&defs.recolor(Recolor { scale: 1., offset }), BlendMode::ColorDodge, &layer) + ) + }; + let (sums_to_white, sums_past_white) = (reaches_white(0.), reaches_white(-1. / 255.)); + format!( + r#"{}{sums_to_white}{sums_past_white}"#, + copy.markup + ) + } + // Luminosity moves the copy's color by the layer's luma less its own, which the change in any channel shows the direction of + BlendRecipe::Pick { lighter } => { + let any_channel = defs.filter("any-channel", r#""#); + let toward = if lighter { BlendMode::Lighten } else { BlendMode::Darken }; + let moved = format!( + r#"{beneath_in_mask}{}{}{}"#, + drawn(&opaque, BlendMode::Luminosity, &layer), + drawn(&opaque, toward, &beneath_in_mask), + drawn(&opaque, BlendMode::Difference, &beneath_in_mask) + ); + let picked = defs.mask("picked", &moved); + format!(r#"{}{layer}"#, copy.markup) + } + }; + + // The blend shows by the alpha of what lies beneath, and the whole by the layer's own alpha, at its opacity + let beneath = defs.mask("beneath", &beneath_in_mask); + let blended = format!(r#"{blend_markup}"#); + let mut outer = vec![("mask", defs.mask("shown", &layer))]; + if opacity < 1. { + outer.push(("opacity", opacity.to_string())); + } + let mut around = vec![outer]; + + // A fill moving the layer toward neutral shows it by how much lies beneath, by a table of each level of alpha there + if blend.fill < 1. { + let table: Vec = (0..=255).map(|level| format!("{:.5}", layer_fill_shown(level as f32 / 255., blend.fill as f32))).collect(); + let weight = defs.filter( + "fill-weight", + &format!(r#""#, table.join(" ")), + ); + around.push(vec![("mask", defs.mask("fill-shown", &format!(r#"{beneath_in_mask}"#)))]); + } + + Some(BlendGroups { around, opaque, layer_id, blended }) +} + +/// Draws the layer `draw_layer` draws, blended by the mode onto what lies beneath it and faded by `opacity`. +pub(crate) fn draw_blended_layer(render: &mut SvgRender, blend: &SvgLayerBlend, opacity: f32, draw_layer: impl FnOnce(&mut SvgRender)) { + let Some(BlendGroups { around, opaque, layer_id, blended }) = blend_groups(render, blend, opacity) else { + // Over nothing, the layer shows as it is, faded by a fill it would otherwise move toward neutral + let opacity = opacity as f64 * blend.fill; + return render.parent_tag( + "g", + |attributes| { + if opacity < 1. { + attributes.push("opacity", opacity.to_string()); + } + }, + draw_layer, + ); + }; + + nest_groups(render, &around, |render| { + render.parent_tag( + "g", + |attributes| attributes.push("filter", opaque), + |render| render.parent_tag("g", |attributes| attributes.push("id", layer_id), draw_layer), + ); + render.leaf_node(SvgSegment::Backdrop(blended)); + }); +} + +/// Wraps the markup drawn since the segment at `start`, an image of the layer the GPU renders, in what [`draw_blended_layer`] draws around a layer. Returns whether it blends. +pub(crate) fn wrap_blended_layer(render: &mut SvgRender, blend: &SvgLayerBlend, opacity: f32, start: usize) -> bool { + let Some(BlendGroups { around, opaque, layer_id, blended }) = blend_groups(render, blend, opacity) else { + return false; + }; + + let opening = |attributes: &Vec<(&'static str, String)>| format!("", attributes.iter().map(|(name, value)| format!(r#" {name}="{value}""#)).collect::()); + let mut opened: String = around.iter().map(opening).collect(); + write!(opened, r#""#).unwrap(); + render.svg.insert(start, opened.into()); + render.svg.push("".into()); + render.svg.push(SvgSegment::Backdrop(blended)); + render.svg.push("".repeat(around.len()).into()); + true +} + +/// Opens a group of each of the `groups`' attributes, outermost first, around what `inner` draws. +fn nest_groups(render: &mut SvgRender, groups: &[Vec<(&'static str, String)>], inner: impl FnOnce(&mut SvgRender)) { + let Some((attributes, nested)) = groups.split_first() else { return inner(render) }; + render.parent_tag( + "g", + |tag| attributes.iter().for_each(|(name, value)| tag.push(*name, value.clone())), + |render| nest_groups(render, nested, inner), + ); +} + +#[cfg(test)] +mod tests { + use super::*; + use raster_kernels::layer_blending::{blend_layer_pixel, blend_pixel}; + + /// The modes SVG builds from native compositing. + const MODES: [BlendMode; 10] = [ + BlendMode::LinearBurn, + BlendMode::DarkerColor, + BlendMode::LinearDodge, + BlendMode::LighterColor, + BlendMode::VividLight, + BlendMode::LinearLight, + BlendMode::PinLight, + BlendMode::HardMix, + BlendMode::Subtract, + BlendMode::Divide, + ]; + + /// The modes SVG has, which it builds from native compositing too below a full fill moving the layer toward neutral. + const BELOW_FULL_FILL: [BlendMode; 2] = [BlendMode::ColorDodge, BlendMode::ColorBurn]; + + /// A value as the 8-bit buffers browsers hold the results of filters and groups in keep it. + fn quantized(value: f64) -> f64 { + (value.clamp(0., 1.) * 255.).round() / 255. + } + + /// The opaque color an opaque `source` composites natively by the mode onto an opaque `backdrop`, by the W3C's formula, held in 8 bits. + fn native(blend_mode: BlendMode, backdrop: [f64; 3], source: [f64; 3]) -> [f64; 3] { + let opaque = |[red, green, blue]: [f64; 3]| [red as f32, green as f32, blue as f32, 1.]; + let blended = blend_pixel(opaque(source), opaque(backdrop), blend_mode); + [0, 1, 2].map(|channel| quantized(blended[channel] as f64)) + } + + /// A color recolored, held in 8 bits. + fn recolored(recolor: Recolor, color: [f64; 3]) -> [f64; 3] { + color.map(|channel| quantized(recolor.scale * channel + recolor.offset)) + } + + /// The opaque color the `recipe` builds from an opaque `layer` over an opaque `backdrop`, compositing natively by the W3C's formulas, each result held in 8 bits. + fn emulated(recipe: &BlendRecipe, backdrop: [f64; 3], layer: [f64; 3]) -> [f64; 3] { + match recipe { + BlendRecipe::Stages(stages) => { + let mut result = backdrop; + for stage in stages { + result = recolored(stage.base, result); + for step in &stage.steps { + result = native(step.blend_mode, result, recolored(step.recolor, layer)); + } + result = recolored(stage.stretch, result); + } + result + } + BlendRecipe::HardMixThreshold => { + let reaches_white = |offset: f64| native(BlendMode::ColorDodge, backdrop, recolored(Recolor { scale: 1., offset }, layer)).map(|channel| quantized(255. * channel - 254.)); + let at_white = native(BlendMode::Multiply, backdrop, reaches_white(0.)); + native(BlendMode::Lighten, at_white, reaches_white(-1. / 255.)) + } + BlendRecipe::Pick { lighter } => { + let moved = native(BlendMode::Luminosity, backdrop, layer); + let toward = native(if *lighter { BlendMode::Lighten } else { BlendMode::Darken }, moved, backdrop); + let change = native(BlendMode::Difference, toward, backdrop); + let layer_wins = change.iter().sum::() * 255. >= 1.; + if layer_wins { layer } else { backdrop } + } + } + } + + /// Colors on the 8-bit grid, which a render's inputs lie on. + fn levels(colors: &[[u8; 3]]) -> Vec<[f64; 3]> { + colors.iter().map(|color| color.map(|level| level as f64 / 255.)).collect() + } + + /// How many levels the recipe's result may stray from the CPU's at a `fill` below full, where the layer's recolored channels round to whole levels: + /// none at full strength, which leaves them whole, a level otherwise, and on Hard Mix's ramp half a level stretched by `1 / (1 - steepness)`, more past a level. + fn tolerance(blend_mode: BlendMode, fill: f64) -> f64 { + match (fill < 1., blend_mode) { + (false, _) => 0.5, + (true, BlendMode::HardMix) => 1. + 0.5 / (1. - 255. * fill / 256.), + // Burning and dodging by a nearly black or white layer stretch its rounding most, by up to a fifth across these colors + (true, BlendMode::VividLight | BlendMode::ColorDodge | BlendMode::ColorBurn) => 3., + (true, _) => 1., + } + } + + #[test] + fn recipes_build_each_mode_from_native_compositing_at_full_strength_exactly() { + // Every level of a gray backdrop under every level of a gray layer, and a spread of colors + let grays: Vec<[f64; 3]> = (0..=255).map(|level| [level as f64 / 255.; 3]).collect(); + let colors = levels(&[ + [0, 0, 0], + [255, 255, 255], + [204, 51, 128], + [30, 200, 90], + [128, 128, 128], + [250, 180, 20], + [64, 96, 230], + [127, 129, 140], + ]); + let opaque = |[red, green, blue]: [f64; 3]| [red as f32, green as f32, blue as f32, 1.]; + + for blend_mode in MODES.into_iter().filter(|blend_mode| !matches!(blend_mode, BlendMode::DarkerColor | BlendMode::LighterColor)) { + let recipe = recipe(blend_mode, 1.).expect("SVG lacks the mode"); + for (backdrops, layers) in [(&grays, &grays), (&colors, &colors)] { + for &backdrop in backdrops { + for &layer in layers { + let svg = emulated(&recipe, backdrop, layer); + let cpu = blend_layer_pixel(opaque(layer), opaque(backdrop), blend_mode, 1.); + for channel in 0..3 { + assert!( + (svg[channel] - cpu[channel] as f64).abs() * 255. <= 0.5 + 1e-4, + "{blend_mode} of {layer:?} over {backdrop:?} gives {svg:?} in SVG and {cpu:?} on the CPU" + ); + } + } + } + } + } + } + + #[test] + fn recipes_build_each_mode_from_native_compositing_below_full_strength_within_their_rounding() { + let colors = levels(&[ + [0, 0, 0], + [255, 255, 255], + [204, 51, 128], + [30, 200, 90], + [128, 128, 128], + [250, 180, 20], + [64, 96, 230], + [127, 129, 140], + ]); + let opaque = |[red, green, blue]: [f64; 3]| [red as f32, green as f32, blue as f32, 1.]; + + for blend_mode in MODES.into_iter().filter(BlendMode::fill_moves_layer_toward_neutral).chain(BELOW_FULL_FILL) { + for fill in [0.8, 0.6, 0.25, 0.] { + let recipe = recipe(blend_mode, fill).expect("SVG lacks the mode"); + for &backdrop in &colors { + for &layer in &colors { + let svg = emulated(&recipe, backdrop, layer); + let cpu = blend_layer_pixel(opaque(layer), opaque(backdrop), blend_mode, fill as f32); + for channel in 0..3 { + let difference = (svg[channel] - cpu[channel] as f64).abs() * 255.; + assert!( + difference <= tolerance(blend_mode, fill), + "{blend_mode} at fill {fill} of {layer:?} over {backdrop:?} gives {svg:?} in SVG and {cpu:?} on the CPU" + ); + } + } + } + } + } + } + + #[test] + fn darker_and_lighter_color_pick_as_on_the_cpu_but_may_keep_the_backdrop_within_half_a_level_of_luma() { + let opaque = |[red, green, blue]: [f64; 3]| [red as f32, green as f32, blue as f32, 1.]; + let luma = |color: [f64; 3]| 255. * (0.3 * color[0] + 0.59 * color[1] + 0.11 * color[2]); + + // Pairs of colors around ties of luma, by a fraction of a level or a level or more, with channels at black and white where Luminosity clips + let colors = levels(&[ + [0, 0, 255], + [0, 48, 0], + [0, 47, 0], + [0, 49, 0], + [255, 0, 0], + [0, 130, 0], + [10, 120, 40], + [128, 128, 128], + [100, 140, 140], + [255, 255, 255], + [0, 0, 0], + [255, 254, 255], + ]); + for lighter in [false, true] { + let blend_mode = if lighter { BlendMode::LighterColor } else { BlendMode::DarkerColor }; + for &backdrop in &colors { + for &layer in &colors { + let svg = emulated(&BlendRecipe::Pick { lighter }, backdrop, layer); + let difference = luma(layer) - luma(backdrop); + let cpu = blend_layer_pixel(opaque(layer), opaque(backdrop), blend_mode, 1.); + let cpu = [cpu[0] as f64, cpu[1] as f64, cpu[2] as f64]; + // It picks what the CPU picks, or within half a level of a tie, where Luminosity may move no channel a level, it may keep the backdrop, as at a tie + let near_tie = difference.abs() < 0.5; + assert!(svg == cpu.map(quantized) || (near_tie && svg == backdrop), "{blend_mode} of {layer:?} over {backdrop:?} picks {svg:?}"); + } + } + } + + // Blue's luma lies just under green's, so Darker Color keeps the blue backdrop + let (blue, green) = ([0., 0., 1.], [0., 48. / 255., 0.]); + assert_eq!(emulated(&BlendRecipe::Pick { lighter: false }, blue, green), blue); + } + + #[test] + fn layers_blend_by_the_alpha_beneath_and_their_own_as_on_the_cpu() { + let (backdrop, layer) = ([0.2, 0.6, 0.45], [0.85, 0.3, 0.6]); + + // Color Dodge and Color Burn blend so only below a full fill + let cases = [(1., 0.5, 1., 1.), (0.5, 1., 0.6, 1.), (0.75, 0.25, 0.4, 0.7), (1., 0., 0.5, 1.), (1., 0.5, 0., 1.)]; + let modes_and_cases = MODES.into_iter().chain(BELOW_FULL_FILL).flat_map(|blend_mode| cases.map(|case| (blend_mode, case))); + for (blend_mode, (layer_alpha, backdrop_alpha, fill, opacity)) in modes_and_cases.filter(|(blend_mode, (_, _, fill, _))| *fill < 1. || blend_mode.reads_backdrop()) { + // Only a fill moving the layer toward neutral reaches the blend, which shows it by the alpha beneath, and the layer is otherwise already faded by it + let moves = blend_mode.fill_moves_layer_toward_neutral(); + let blend_fill = if moves { fill } else { 1. }; + let drawn_alpha = if moves { layer_alpha } else { layer_alpha * fill }; + let blend = emulated(&recipe(blend_mode, blend_fill).unwrap(), backdrop, layer); + + // The layer made opaque, the blend over it by the alpha beneath, all shown by the layer's alpha, its fill's weight, and its opacity over what lies beneath + let shown = opacity * drawn_alpha * layer_fill_shown(backdrop_alpha as f32, blend_fill as f32) as f64; + let svg: Vec = (0..3) + .map(|channel| shown * (backdrop_alpha * blend[channel] + (1. - backdrop_alpha) * layer[channel]) + (1. - shown) * backdrop_alpha * backdrop[channel]) + .chain([shown + (1. - shown) * backdrop_alpha]) + .collect(); + + // The CPU blends the full-strength content by the fill, then the opacity mixes from what lies beneath to that + let premultiplied = |color: [f64; 3], alpha: f64| [color[0] * alpha, color[1] * alpha, color[2] * alpha, alpha].map(|channel| channel as f32); + let beneath = premultiplied(backdrop, backdrop_alpha); + let blended = blend_layer_pixel(premultiplied(layer, layer_alpha), beneath, blend_mode, fill as f32); + for channel in 0..4 { + let cpu = beneath[channel] as f64 + (blended[channel] - beneath[channel]) as f64 * opacity; + assert!( + (svg[channel] - cpu).abs() * 255. <= 2., + "{blend_mode} at layer alpha {layer_alpha}, alpha beneath {backdrop_alpha}, fill {fill}, and opacity {opacity}: {svg:?} in SVG against {cpu} in channel {channel} on the CPU" + ); + } + } + } + + #[test] + fn modes_svg_has_take_no_recipe() { + for blend_mode in BlendMode::list().into_iter().flatten() { + assert_eq!(recipe(*blend_mode, 1.).is_some(), blend_mode.reads_backdrop(), "{blend_mode}"); + } + } +} diff --git a/node-graph/libraries/rendering/src/to_peniko.rs b/node-graph/libraries/rendering/src/to_peniko.rs index 42624ef3eeb..61f2a214183 100644 --- a/node-graph/libraries/rendering/src/to_peniko.rs +++ b/node-graph/libraries/rendering/src/to_peniko.rs @@ -42,7 +42,7 @@ impl BlendModeExt for BlendMode { BlendMode::Saturation => peniko::Mix::Saturation, BlendMode::Color => peniko::Mix::Color, BlendMode::Luminosity => peniko::Mix::Luminosity, - // Like SVG, the modes that layers can't blend by fall back to normal + // Vello lacks the rest, so they draw normally, and layers in those reading what lies beneath blend in an effects group (see `BlendMode::reads_backdrop`) _ => peniko::Mix::Normal, } } diff --git a/node-graph/libraries/rendering/src/vello_scene_builder.rs b/node-graph/libraries/rendering/src/vello_scene_builder.rs index 9fc765d8d7a..4a8d9e20e0d 100644 --- a/node-graph/libraries/rendering/src/vello_scene_builder.rs +++ b/node-graph/libraries/rendering/src/vello_scene_builder.rs @@ -612,7 +612,7 @@ impl<'a> VelloSceneBuilder<'a> { // What lies beneath, for the effects that read it, where each of the effects texture's pixels lands in it. // Content without bounds reads nothing, as in SVG, and content reading past the scene's edges asks for the scene to be rendered grown by as much. - let reads_backdrop = layers.reads_backdrop() && capture.is_none() && bounds.is_some() && self.backdrop_readable(); + let reads_backdrop = (layers.reads_backdrop() || layers.content_reads_backdrop(fill)) && capture.is_none() && bounds.is_some() && self.backdrop_readable(); if reads_backdrop && layers.reads_around_backdrop() { // A box reaches as far along each axis of the view as its square turned into it does, and a Gaussian as far every way as its widest stretch let readers = (effects.operations()).filter(|operation| matches!(operation, graphic_types::EffectOperation::BackgroundBlur { .. }) && !operation.changes_nothing()); diff --git a/node-graph/libraries/wgpu-executor/src/vello_effects.rs b/node-graph/libraries/wgpu-executor/src/vello_effects.rs index ec5954661b1..2e7e57c4d25 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_effects.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_effects.rs @@ -21,6 +21,7 @@ use wgpu::util::DeviceExt; mod blend_if; mod filters; +mod layer_blend; mod masks; mod resample; mod styles; @@ -167,7 +168,7 @@ impl EffectPasses { log::warn!("This GPU can't render into the formats layer effects need, so content draws without its effects"); } - // The filters', resampling, styles', masks', and Blend If's passes live in files of their own, sharing this one's bindings and helpers + // The filters', resampling, styles', masks', Blend If's, and layer blending's passes live in files of their own, sharing this one's bindings and helpers let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("vello_effects.wgsl"), source: wgpu::ShaderSource::Wgsl( @@ -179,7 +180,8 @@ impl EffectPasses { include_str!("vello_warp.wgsl"), include_str!("vello_styles.wgsl"), include_str!("vello_masks.wgsl"), - include_str!("vello_blend_if.wgsl") + include_str!("vello_blend_if.wgsl"), + include_str!("vello_layer_blend.wgsl") ) .into(), ), @@ -263,7 +265,8 @@ impl EffectPasses { .clone() } - /// Carries out `effects` on `content`, a texture of premultiplied pixels, returning each of the `layers` they draw in a pooled texture of [`WORKING_FORMAT`] the same size, with the mode it blends by. + /// Carries out `effects` on `content`, a texture of premultiplied pixels, returning each of the `layers` they draw in a pooled texture of [`WORKING_FORMAT`] the same size, with the mode it blends by + /// (normal for one in a mode Vello's layers lack, which comes back blended onto the `backdrop` already). /// `effect_to_pixels` places the effects' space on the texture's pixels, `fill` fades the content but not the shadows and glows cast from it, and `opacity` fades the layers. /// The `frame`, in the texture's pixels, is the content's extent, which displacements take as their own. /// `paints` holds the effects' drawn paints in order, each rendered over the same pixels as the content. @@ -297,6 +300,16 @@ impl EffectPasses { let lengths_to_pixels = effect_to_pixels.matrix2; let length_scale = lengths_to_pixels.determinant().abs().sqrt(); + // A fill moving the content toward its layer mode's neutral color leaves the content at full strength, for its layer to blend by that fill. + // Color Dodge and Color Burn layers blend so only where they read what lies beneath (see `EffectLayers::content_reads_backdrop`), and with nothing to read, natively. + let content_mode = layers.content_layer().map(|layer| layers.layers[layer].blend_mode); + let natively_otherwise = content_mode.is_some_and(|blend_mode| !blend_mode.reads_backdrop()); + let content_blends_onto_backdrop = layers.content_reads_backdrop(fill) && !(natively_otherwise && backdrop.is_none()); + let (fill, blend_fill) = match content_blends_onto_backdrop && content_mode.is_some_and(|blend_mode| blend_mode.fill_moves_layer_toward_neutral()) { + true => (1., fill), + false => (fill, 1.), + }; + // The content at full strength, which casts every silhouette, read from the content itself (whatever its format) until a pass replaces it let mut full: Option = None; // The content faded by the fill, which shows in the result @@ -1130,7 +1143,7 @@ impl EffectPasses { // Each layer stacks its parts in order: what lies beneath the content, then the content with what lies within it let mut content_image = Some(content_image); - let mut results = Vec::new(); + let (mut results, mut content_result) = (Vec::new(), None); for (index, layer) in layers.layers.iter().enumerate() { let holds_content = Some(index) == content_layer; let mut stack = if holds_content { beneath.take() } else { None }; @@ -1199,9 +1212,16 @@ impl EffectPasses { let faded = recorder.run("apply_mask", WORKING_FORMAT, recorder.size, &result, Some(fade), None, Parameters::default()); recorder.replace(&mut result, faded); } + if holds_content { + content_result = Some(results.len()); + } results.push((result, layer.blend_mode)); } + // A layer in a mode Vello's layers lack blends onto what lies beneath here, before the Blend Ifs fade the blended layer + let content_result = content_result.filter(|_| content_blends_onto_backdrop); + recorder.blend_onto_backdrop(backdrop, blend_fill, content_result, &mut results); + // Blend If's ranges of what lies beneath fade every layer, like the opacity varying across them let underlying = underlying_ranges(&every_operation); if let Some(backdrop) = backdrop.filter(|_| !underlying.is_empty()) { diff --git a/node-graph/libraries/wgpu-executor/src/vello_effects/layer_blend.rs b/node-graph/libraries/wgpu-executor/src/vello_effects/layer_blend.rs new file mode 100644 index 00000000000..3779ed82cce --- /dev/null +++ b/node-graph/libraries/wgpu-executor/src/vello_effects/layer_blend.rs @@ -0,0 +1,40 @@ +//! The GPU pass blending a layer by a mode Vello's layers lack, onto what lies beneath it, matching the CPU's `blend_layer_pixel` and SVG's layers built from native compositing. + +use super::{Parameters, PassRecorder, WORKING_FORMAT}; +use core_types::blending::BlendMode; +use vello_gpu::kurbo::Affine; + +impl PassRecorder<'_> { + /// Blends onto the scene's `backdrop` each layer's image in `results` whose mode reads what lies beneath (see [`BlendMode::reads_backdrop`]), and the `content` one if it reads it at its fill, + /// leaving what it then draws normally. The `fill` moves only the content toward its mode's neutral color (see [`BlendMode::fill_moves_layer_toward_neutral`]). Without a backdrop, nothing lies beneath. + pub(super) fn blend_onto_backdrop(&mut self, backdrop: Option<(&wgpu::Texture, Affine)>, fill: f32, content: Option, results: &mut [(wgpu::Texture, BlendMode)]) { + for (index, (image, blend_mode)) in results.iter_mut().enumerate() { + let holds_content = Some(index) == content; + if !holds_content && !blend_mode.reads_backdrop() { + continue; + } + let strength = if holds_content && blend_mode.fill_moves_layer_toward_neutral() { fill } else { 1. }; + + match backdrop { + Some((backdrop, placement)) => { + let placed = Parameters::placed_in_backdrop(placement); + let [x, y, ..] = placed.values; + let parameters = Parameters { + values: [x, y, *blend_mode as u32 as f32, strength], + ..placed + }; + let blended = self.run("blend_onto_backdrop", WORKING_FORMAT, self.size, backdrop, Some(image), None, parameters); + self.replace(image, blended); + } + // Over nothing, the layer shows as it is, faded by a fill it would otherwise move toward neutral + None if strength < 1. => { + let faded = self.scale(image, strength); + self.replace(image, faded); + } + None => {} + } + + *blend_mode = BlendMode::Normal; + } + } +} diff --git a/node-graph/libraries/wgpu-executor/src/vello_layer_blend.wgsl b/node-graph/libraries/wgpu-executor/src/vello_layer_blend.wgsl new file mode 100644 index 00000000000..7ce4eda5e55 --- /dev/null +++ b/node-graph/libraries/wgpu-executor/src/vello_layer_blend.wgsl @@ -0,0 +1,48 @@ +// The pass blending a layer by a mode that reads what lies beneath, appended to the effect passes, matching the CPU's `blend_layer_pixel` + +// A paint at `strength` blended by the mode, moved toward the mode's neutral color where its strength does that, matching `apply_blend_mode_at_strength` +fn blend_gamma_at_strength(backdrop: vec3, paint: vec3, mode: u32, strength: f32) -> vec3 { + // Hard Mix steepens its ramp with the strength instead + if mode == 17u { + let mixed = vec3(hard_mix(backdrop.r, paint.r, strength), hard_mix(backdrop.g, paint.g, strength), hard_mix(backdrop.b, paint.b, strength)); + return clamp(mixed, vec3(0.), vec3(1.)); + } + + // Color Dodge and Linear Dodge move toward black, Color Burn and Linear Burn toward white, and Vivid Light and Linear Light toward middle gray + var moved = paint; + if mode == 8u || mode == 9u { + moved = strength * paint; + } else if mode == 3u || mode == 4u { + moved = 1. - strength * (1. - paint); + } else if mode == 14u || mode == 15u { + moved = 0.5 + strength * (paint - 0.5); + } + return blend_gamma(backdrop, moved, mode); +} + +// How strongly a layer whose fill `strength` moves it toward neutral shows over a backdrop of `backdrop_alpha`, matching the CPU's `layer_fill_shown` +fn layer_fill_shown(backdrop_alpha: f32, strength: f32) -> f32 { + return min(strength / max((1. - backdrop_alpha) + backdrop_alpha * strength, 1e-6), 1.); +} + +// A layer's image (`secondary`) blended by the mode in `values.z` onto what lies beneath it, sampled from the scene's backdrop (`source`) where each pixel lands as `sample_backdrop` places it. +// It's what the layer then draws normally: its color mixed toward the blend as far as the backdrop covers it, shown as strongly as a fill `values.w` moving it toward neutral leaves it. +@fragment +fn blend_onto_backdrop(@builtin(position) position: vec4) -> @location(0) vec4 { + let layer = textureLoad(secondary, vec2(position.xy), 0); + let backdrop = textureSampleLevel(source, linear_sampler, backdrop_point(position.xy) / vec2(textureDimensions(source)), 0.); + if layer.a <= 0. { + return vec4(0.); + } + + let paint = clamp(layer.rgb / layer.a, vec3(0.), vec3(1.)); + var beneath = vec3(0.); + if backdrop.a > 0. { + beneath = clamp(backdrop.rgb / backdrop.a, vec3(0.), vec3(1.)); + } + let strength = parameters.values.w; + let blended = blend_gamma_at_strength(beneath, paint, u32(parameters.values.z), strength); + + let shown = layer.a * layer_fill_shown(backdrop.a, strength); + return vec4(shown * ((1. - backdrop.a) * paint + backdrop.a * blended), shown); +} diff --git a/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs b/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs index 0ab961d5e4f..a371bfc545e 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs @@ -11509,3 +11509,474 @@ fn endless_layers_fade_by_blend_ifs_reading_each_effect_run_as_the_runs_before_i }; assert!(worst <= 3, "the half-filled color mask differs between the CPU and GPU by up to {worst} levels"); } + +/// A raster of `size` texels placed a texel to each of the render's pixels from `corner`, each of the straight 8-bit color `level` gives at its column and row. +fn leveled_image(corner: UVec2, size: UVec2, level: impl Fn(u32, u32) -> [u8; 4]) -> core_types::list::Item> { + use core_types::color::SRGBA8; + use graphic_types::raster_types::{Image, Raster}; + + let data = (0..size.x * size.y) + .map(|index| { + let [red, green, blue, alpha] = level(index % size.x, index / size.x); + core_types::Color::from(SRGBA8::new(red, green, blue, alpha)) + }) + .collect(); + let placement = DAffine2::from_translation(corner.as_dvec2()) * DAffine2::from_scale(size.as_dvec2()); + core_types::list::Item::new_from_element(Raster::new_cpu(Image { width: size.x, height: size.y, data })).with_attribute(core_types::ATTR_TRANSFORM, placement) +} + +/// The premultiplied gamma-encoded channels of a straight 8-bit color, from 0 to 1. +fn premultiplied_gamma([red, green, blue, alpha]: [u8; 4]) -> [f32; 4] { + let alpha = alpha as f32 / 255.; + [red, green, blue] + .map(|channel| channel as f32 / 255. * alpha) + .into_iter() + .chain([alpha]) + .collect::>() + .try_into() + .unwrap() +} + +/// What lies beneath layers blending by the modes Vello's layers lack: red rising across and green rising down over a constant blue, opaque in the top half and fading across the bottom half to a quarter. +fn blend_backdrop_level(x: u32, y: u32) -> [u8; 4] { + let alpha = if y < 48 { 255 } else { 255 - x * 191 / 95 }; + [(x * 255 / 95) as u8, (y * 255 / 95) as u8, 140, alpha as u8] +} + +/// The layer blending onto it, 80 texels across from the corner at 8: red falling down, green rising across, and blue rising across both, with a band of half alpha. +fn blend_content_level(x: u32, y: u32) -> [u8; 4] { + let alpha = if (50..62).contains(&y) { 128 } else { 255 }; + [(230 - 2 * y) as u8, (20 + 2 * x) as u8, ((x + 2 * y) * 255 / 237) as u8, alpha] +} + +/// Whether a blend is ill-conditioned for the colors, where it stretches the rounding of what lies beneath far: on or near Hard Mix's steep ramp, +/// where a burn or dodge (Vivid Light's too) is by a paint dark or light enough to stretch each level more than fourfold, and near a tie of luma for Darker or Lighter Color. +fn blend_ill_conditioned(blend_mode: BlendMode, content: [f32; 4], backdrop: [f32; 4], fill: f32) -> bool { + let straight = |pixel: [f32; 4]| [0, 1, 2].map(|channel| if pixel[3] > 0. { pixel[channel] / pixel[3] } else { 0. }); + let (source, beneath) = (straight(content), straight(backdrop)); + let luma = |color: [f32; 3]| 0.3 * color[0] + 0.59 * color[1] + 0.11 * color[2]; + let strength = if blend_mode.fill_moves_layer_toward_neutral() { fill } else { 1. }; + let steepness = 255. * strength / 256.; + + match blend_mode { + BlendMode::HardMix => (0..3).any(|channel| (-0.01..1. - steepness + 0.01).contains(&(beneath[channel] - steepness * (1. - source[channel])))), + BlendMode::VividLight => source.iter().any(|&channel| (2. * (0.5 + strength * (channel - 0.5)) - 1.).abs() > 0.75), + BlendMode::ColorDodge => source.iter().any(|&channel| strength * channel > 0.75), + BlendMode::ColorBurn => source.iter().any(|&channel| 1. - strength * (1. - channel) < 0.25), + BlendMode::DarkerColor | BlendMode::LighterColor => (luma(source) - luma(beneath)).abs() < 2. / 255., + _ => false, + } +} + +/// The reference formula, for PSD interop, for one opaque channel of a layer in a mode Vello's layers lack, or in Color Dodge or Color Burn, with its fill, over an opaque backdrop channel. +fn reference_blend(blend_mode: BlendMode, backdrop: f32, source: f32, fill: f32) -> f32 { + let color_burn = |backdrop: f32, source: f32| { + if backdrop >= 1. { + 1. + } else if source <= 0. { + 0. + } else { + 1. - ((1. - backdrop) / source).min(1.) + } + }; + let color_dodge = |backdrop: f32, source: f32| { + if backdrop <= 0. { + 0. + } else if source >= 1. { + 1. + } else { + (backdrop / (1. - source)).min(1.) + } + }; + let mix = |blended: f32| backdrop + (blended.clamp(0., 1.) - backdrop) * fill; + + match blend_mode { + BlendMode::ColorDodge => color_dodge(backdrop, fill * source), + BlendMode::ColorBurn => color_burn(backdrop, 1. - fill * (1. - source)), + BlendMode::LinearBurn => (backdrop + (1. - fill * (1. - source)) - 1.).clamp(0., 1.), + BlendMode::LinearDodge => (backdrop + fill * source).clamp(0., 1.), + BlendMode::VividLight => { + let source = 0.5 + fill * (source - 0.5); + if source <= 0.5 { + color_burn(backdrop, 2. * source) + } else { + color_dodge(backdrop, 2. * source - 1.) + } + } + BlendMode::LinearLight => (backdrop + 2. * (0.5 + fill * (source - 0.5)) - 1.).clamp(0., 1.), + BlendMode::HardMix => { + let steepness = 255. * fill / 256.; + ((backdrop - steepness * (1. - source)) / (1. - steepness)).clamp(0., 1.) + } + BlendMode::PinLight => mix(if source <= 0.5 { backdrop.min(2. * source) } else { backdrop.max(2. * source - 1.) }), + BlendMode::Subtract => mix(backdrop - source), + BlendMode::Divide => mix(if backdrop <= 0. { + 0. + } else if source <= 0. { + 1. + } else { + backdrop / source + }), + _ => panic!("{blend_mode} picks whole colors or blends natively"), + } +} + +#[test] +fn layers_in_modes_vello_lacks_blend_onto_partly_covering_backdrops_as_on_the_cpu_and_by_the_reference_formulas() { + use core_types::list::List; + use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL}; + use graphic_types::Graphic; + use raster_kernels::layer_blending::blend_layer_pixel; + use rendering::{Render, RenderParams}; + + let size = UVec2::splat(96); + let (corner, content_size) = (UVec2::splat(8), UVec2::splat(80)); + let modes = BlendMode::list().into_iter().flatten().copied().filter(BlendMode::reads_backdrop); + + for blend_mode in modes.chain([BlendMode::ColorDodge, BlendMode::ColorBurn]) { + for (fill, opacity) in [(1., 1.), (0.5, 1.), (0.7, 0.6)] { + let content = leveled_image(corner, content_size, blend_content_level) + .with_attribute(ATTR_BLEND_MODE, blend_mode) + .with_attribute(ATTR_OPACITY_FILL, fill as f64) + .with_attribute(ATTR_OPACITY, opacity as f64); + let mut list = List::new_from_item(leveled_image(UVec2::ZERO, size, blend_backdrop_level)); + list.push(content); + let graphic = Graphic::RasterCPUList(list); + let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + + let (mut worst, mut worst_at) = (0., UVec2::ZERO); + for y in 0..size.y { + for x in 0..size.x { + let backdrop = premultiplied_gamma(blend_backdrop_level(x, y)); + let inside = (corner.x..corner.x + content_size.x).contains(&x) && (corner.y..corner.y + content_size.y).contains(&y); + let content = if inside { premultiplied_gamma(blend_content_level(x - corner.x, y - corner.y)) } else { [0.; 4] }; + if blend_ill_conditioned(blend_mode, content, backdrop, fill) { + continue; + } + + // The CPU blends the content by its fill, then its opacity mixes from what lies beneath to that + let blended = blend_layer_pixel(content, backdrop, blend_mode, fill); + let gpu = premultiplied_gamma(pixel(&gpu, size, x, y)); + for channel in 0..4 { + let cpu = backdrop[channel] + (blended[channel] - backdrop[channel]) * opacity; + let difference = (cpu - gpu[channel]).abs() * 255.; + if difference > worst { + (worst, worst_at) = (difference, UVec2::new(x, y)); + } + } + } + } + assert!( + worst <= 3., + "{blend_mode} at fill {fill} and opacity {opacity} differs from the CPU by up to {worst} levels at {worst_at}" + ); + + // Over the opaque top half, the opaque layer takes the reference formula + if opacity < 1. || matches!(blend_mode, BlendMode::DarkerColor | BlendMode::LighterColor) { + continue; + } + for (x, y) in [(20, 12), (50, 30), (80, 44), (14, 40)] { + let backdrop = premultiplied_gamma(blend_backdrop_level(x, y)); + let content = premultiplied_gamma(blend_content_level(x - corner.x, y - corner.y)); + if blend_ill_conditioned(blend_mode, content, backdrop, fill) { + continue; + } + let gpu = premultiplied_gamma(pixel(&gpu, size, x, y)); + for channel in 0..3 { + let expected = reference_blend(blend_mode, backdrop[channel], content[channel], fill); + assert!( + (expected - gpu[channel]).abs() * 255. <= 3., + "{blend_mode} at fill {fill} gives {gpu:?} at ({x}, {y}) rather than {expected} in channel {channel}" + ); + } + } + } + } +} + +#[test] +fn darker_and_lighter_color_layers_pick_whole_colors_by_luma_on_the_gpu() { + use core_types::ATTR_BLEND_MODE; + use core_types::list::List; + use graphic_types::Graphic; + use rendering::{Render, RenderParams}; + + // Blue's luma (0.11) is below the gray's (0.3), though its mean channel (a third) is above it + let size = UVec2::splat(32); + let gray = |_: u32, _: u32| [77, 77, 77, 255]; + let blue = |_: u32, _: u32| [0, 0, 255, 255]; + for (blend_mode, expected) in [(BlendMode::DarkerColor, [0, 0, 255, 255]), (BlendMode::LighterColor, [77, 77, 77, 255])] { + let mut list = List::new_from_item(leveled_image(UVec2::ZERO, size, blue)); + list.push(leveled_image(UVec2::splat(8), UVec2::splat(16), gray).with_attribute(ATTR_BLEND_MODE, blend_mode)); + let graphic = Graphic::RasterCPUList(list); + let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + let picked = pixel(&gpu, size, 16, 16); + assert!(picked.iter().zip(expected).all(|(gpu, expected)| gpu.abs_diff(expected) <= 1), "{blend_mode} picks {picked:?}"); + } +} + +#[test] +fn effect_pieces_beneath_the_content_blend_by_their_own_modes_unmoved_by_its_fill() { + use core_types::Color as GraphicColor; + use glam::DVec2; + use graphic_types::EffectOperation; + use raster_kernels::layer_blending::blend_layer_pixel; + + let size = UVec2::new(128, 128); + let (backdrop, content, shadow, glow) = ([153, 128, 102], [204, 153, 77], [179, 77, 230], [102, 51, 128]); + let levels = |color: [u8; 3]| color.map(|level| level as f32 / 255.); + let piece_color = |color: [u8; 3]| GraphicColor::from_gamma_srgb_channels(levels(color)[0], levels(color)[1], levels(color)[2], 1.); + let shadow_in = |mode: BlendMode| { + let mut operation = drop_shadow(piece_color(shadow), DVec2::splat(10.), 0., 0.); + if let EffectOperation::DropShadow { blend_mode, .. } = &mut operation { + *blend_mode = mode; + } + operation + }; + let dodging_glow = EffectOperation::OuterGlow { + color: piece_color(glow).into(), + blend_mode: BlendMode::ColorDodge, + technique: Default::default(), + spread: 100., + size: 5., + range: 50., + contour: Default::default(), + noise: 0., + jitter: 0., + seed: 0, + }; + + // Each piece, outside the content, and the content, over a piece it knocks out, at a fill moving only the content toward neutral + let cases = [ + ("a Linear Burn shadow under normal content", shadow_in(BlendMode::LinearBurn), shadow, (85, 85), BlendMode::Normal, 1.), + ( + "a normal shadow under Linear Burn content at half fill", + shadow_in(BlendMode::Normal), + shadow, + (85, 85), + BlendMode::LinearBurn, + 0.5, + ), + ("a Color Dodge glow under Color Dodge content at half fill", dodging_glow, glow, (82, 55), BlendMode::ColorDodge, 0.5), + ( + "a Linear Burn shadow under Linear Burn content at half fill", + shadow_in(BlendMode::LinearBurn), + shadow, + (85, 85), + BlendMode::LinearBurn, + 0.5, + ), + ]; + for (case, piece, piece_level, piece_at, content_mode, fill) in cases { + let piece_mode = match &piece { + EffectOperation::DropShadow { blend_mode, .. } | EffectOperation::OuterGlow { blend_mode, .. } => *blend_mode, + _ => unreachable!(), + }; + let [red, green, blue] = backdrop; + let backdrop_color = Color::from_rgb8(red, green, blue); + let [red, green, blue] = content; + let Some(gpu) = render_square_over_backdrop(vec![piece], fill, 1., content_mode, Some(backdrop_color), Color::from_rgb8(red, green, blue), 30., 80., size) else { + return; + }; + + // The reference formula, which the CPU blends by, for an opaque layer at a fill over the opaque backdrop + let opaque = |color: [f32; 3]| [color[0], color[1], color[2], 1.]; + for (blend_mode, source, fill, (x, y)) in [(piece_mode, levels(piece_level), 1., piece_at), (content_mode, levels(content), fill, (50, 50))] { + let expected = match blend_mode { + BlendMode::Normal => source, + _ => [0, 1, 2].map(|channel| reference_blend(blend_mode, levels(backdrop)[channel], source[channel], fill)), + }; + let cpu = blend_layer_pixel(opaque(source), opaque(levels(backdrop)), blend_mode, fill); + let gpu = premultiplied_gamma(pixel(&gpu, size, x, y)); + for channel in 0..3 { + assert!( + (cpu[channel] - expected[channel]).abs() * 255. <= 0.5, + "{case}: the CPU gives {cpu:?} at ({x}, {y}) rather than {expected:?}" + ); + assert!( + (gpu[channel] - expected[channel]).abs() * 255. <= 3., + "{case}: the GPU gives {gpu:?} at ({x}, {y}) rather than {expected:?}" + ); + } + } + } +} + +#[test] +fn color_dodge_and_burn_layers_blend_natively_over_a_shadow_beneath_them_not_knocked_out() { + use core_types::Color as GraphicColor; + use glam::DVec2; + use graphic_types::EffectOperation; + use graphic_types::effect_layers::EffectLayers; + use graphic_types::effects::{EffectCapture, Effects}; + use raster_kernels::layer_blending::blend_pixel; + + let size = UVec2::new(128, 128); + let (backdrop, content, shadow, fill) = ([153, 128, 102], [102, 179, 77], [51, 77, 128], 0.5); + let levels = |color: [u8; 3]| color.map(|level| level as f32 / 255.); + let mut shadow_not_knocked_out = drop_shadow( + GraphicColor::from_gamma_srgb_channels(levels(shadow)[0], levels(shadow)[1], levels(shadow)[2], 1.), + DVec2::splat(10.), + 0., + 0., + ); + if let EffectOperation::DropShadow { knockout, .. } = &mut shadow_not_knocked_out { + *knockout = false; + } + + for blend_mode in [BlendMode::ColorDodge, BlendMode::ColorBurn] { + // What lies beneath the item leaves out the shadow the content blends onto, so the layer blends natively, faded by its fill + let layers = EffectLayers::plan(&Effects::from_operations([shadow_not_knocked_out.clone()]), blend_mode, fill, true); + assert!(!layers.content_reads_backdrop(fill) && layers.layer_of(EffectCapture { index: 0, plane: 0 }).is_some(), "{blend_mode}"); + + let [red, green, blue] = backdrop; + let backdrop_color = Color::from_rgb8(red, green, blue); + let [red, green, blue] = content; + let Some(gpu) = render_square_over_backdrop( + vec![shadow_not_knocked_out.clone()], + fill, + 1., + blend_mode, + Some(backdrop_color), + Color::from_rgb8(red, green, blue), + 30., + 80., + size, + ) else { + return; + }; + + // Over the shadow, and past it over what lies beneath the item, the content faded by its fill blends natively, as the CPU blends it + let opaque = |color: [f32; 3]| [color[0], color[1], color[2], 1.]; + let faded = [levels(content)[0] * fill, levels(content)[1] * fill, levels(content)[2] * fill, fill]; + for (beneath, (x, y)) in [(levels(shadow), (60, 60)), (levels(backdrop), (35, 35))] { + let expected = blend_pixel(faded, opaque(beneath), blend_mode); + let gpu = premultiplied_gamma(pixel(&gpu, size, x, y)); + for channel in 0..3 { + assert!( + (gpu[channel] - expected[channel]).abs() * 255. <= 3., + "{blend_mode} gives {gpu:?} at ({x}, {y}) rather than {expected:?}" + ); + } + } + } +} + +#[test] +fn color_dodge_layers_blending_natively_fade_by_their_fill_in_their_first_effect_run() { + use core_types::list::List; + use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY_FILL, ATTR_TRANSFORM}; + use glam::DVec2; + use graphic_types::adjustment::Adjustment; + use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect}; + use rendering::{Render, RenderParams}; + + // Opaque 0.4 gray in Color Dodge at half fill, made opaque, then scaled, then casting a normal shadow it doesn't knock out, over opaque 0.3 gray + let size = UVec2::splat(128); + let mut content = leveled_image(UVec2::splat(20), UVec2::splat(40), |_, _| [102, 102, 102, 255]) + .with_attribute(ATTR_BLEND_MODE, BlendMode::ColorDodge) + .with_attribute(ATTR_OPACITY_FILL, 0.5); + stamp_effect(&mut content, Effect::new(&EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. }))); + content.set_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(20.)) * DAffine2::from_scale(DVec2::splat(60.))); + let mut shadow = drop_shadow(core_types::Color::from_gamma_srgb_channels(0.2, 0.2, 0.2, 1.), DVec2::splat(10.), 0., 0.); + if let EffectOperation::DropShadow { knockout, .. } = &mut shadow { + *knockout = false; + } + stamp_effect(&mut content, Effect::new(&shadow)); + let mut list = List::new_from_item(leveled_image(UVec2::ZERO, size, |_, _| [77, 77, 77, 255])); + list.push(content); + let graphic = Graphic::RasterCPUList(list); + let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + + // As in SVG, the fill fades the content before Make Opaque restores its alpha, so past the shadow it dodges at full strength: 0.3 / (1 - 0.4) + let dodged = pixel(&gpu, size, 25, 25); + assert!(dodged[..3].iter().all(|&channel| channel.abs_diff(128) <= 3), "{dodged:?}"); +} + +#[test] +fn layers_in_modes_vello_lacks_blend_only_onto_what_their_faded_group_drew() { + use core_types::list::{Item, List}; + use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY}; + use graphic_types::Graphic; + use raster_kernels::layer_blending::blend_layer_pixel; + use rendering::{Render, RenderParams}; + + // White beneath a faded group of dark blue and a layer adding a gray over it, which over the white would add up to white + let size = UVec2::splat(48); + let white = |_: u32, _: u32| [255, 255, 255, 255]; + let dark_blue = |_: u32, _: u32| [20, 30, 120, 255]; + let gray = |_: u32, _: u32| [100, 100, 100, 255]; + let mut inner = List::new_from_item(leveled_image(UVec2::splat(4), UVec2::splat(40), dark_blue)); + inner.push(leveled_image(UVec2::splat(12), UVec2::splat(24), gray).with_attribute(ATTR_BLEND_MODE, BlendMode::LinearDodge)); + let group = Item::new_from_element(Graphic::RasterCPUList(inner)).with_attribute(ATTR_OPACITY, 0.5_f64); + let mut list = List::new_from_item(Item::new_from_element(Graphic::RasterCPUList(List::new_from_item(leveled_image(UVec2::ZERO, size, white))))); + list.push(group); + let graphic = Graphic::GraphicList(list); + let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + + // The layer adds onto the dark blue alone, and the group then fades over the white + let added = blend_layer_pixel(premultiplied_gamma(gray(0, 0)), premultiplied_gamma(dark_blue(0, 0)), BlendMode::LinearDodge, 1.); + let expected: Vec = (0..3).map(|channel| 1. + (added[channel] - 1.) * 0.5).collect(); + let shown = premultiplied_gamma(pixel(&gpu, size, 24, 24)); + for channel in 0..3 { + assert!((shown[channel] - expected[channel]).abs() * 255. <= 2., "{shown:?} rather than {expected:?}"); + } + + // A group in the mode adds all it draws onto what lies beneath it + let mut list = List::new_from_item(Item::new_from_element(Graphic::RasterCPUList(List::new_from_item(leveled_image(UVec2::ZERO, size, dark_blue))))); + list.push(Item::new_from_element(Graphic::RasterCPUList(List::new_from_item(leveled_image(UVec2::splat(12), UVec2::splat(24), gray)))).with_attribute(ATTR_BLEND_MODE, BlendMode::LinearDodge)); + let graphic = Graphic::GraphicList(list); + let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + let shown = premultiplied_gamma(pixel(&gpu, size, 24, 24)); + assert!((0..3).all(|channel| (shown[channel] - added[channel]).abs() * 255. <= 2.), "{shown:?} rather than {added:?}"); +} + +#[test] +fn blend_ifs_fade_a_layer_once_it_blends_by_a_mode_vello_lacks() { + use core_types::ATTR_BLEND_MODE; + use core_types::list::List; + use graphic_types::blend_if::BlendIfRanges; + use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect}; + use raster_kernels::layer_blending::blend_layer_pixel; + use rendering::{Render, RenderParams}; + + // Shown over grays from a quarter up, fully from a half, with columns of gray beneath from dark to light + let mut ranges = BlendIfRanges::default(); + ranges.underlying.gray = blend_range([64., 128., 255., 255.]); + let size = UVec2::new(64, 16); + let columns = |x: u32, _: u32| { + let level = (x * 4) as u8; + [level, level, level, 255] + }; + let orange = |_: u32, _: u32| [230, 140, 60, 255]; + let mut content = leveled_image(UVec2::ZERO, size, orange).with_attribute(ATTR_BLEND_MODE, BlendMode::LinearBurn); + stamp_effect(&mut content, Effect::new(&EffectOperation::BlendIf(Box::new(ranges)))); + let mut list = List::new_from_item(leveled_image(UVec2::ZERO, size, columns)); + list.push(content); + let graphic = Graphic::RasterCPUList(list); + let Some(gpu) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else { + return; + }; + + // Each column shows the blend as strongly as Blend If shows the gray beneath it + for x in 0..size.x { + let beneath = premultiplied_gamma(columns(x, 0)); + let blended = blend_layer_pixel(premultiplied_gamma(orange(0, 0)), beneath, BlendMode::LinearBurn, 1.); + let weight = ranges.underlying.weight([beneath[0], beneath[1], beneath[2]].map(f64::from)) as f32; + let shown = premultiplied_gamma(pixel(&gpu, size, x, 8)); + for channel in 0..3 { + let expected = beneath[channel] + (blended[channel] - beneath[channel]) * weight; + assert!((shown[channel] - expected).abs() * 255. <= 3., "column {x} shows {shown:?} rather than {expected} in channel {channel}"); + } + } +} diff --git a/website/content/features.md b/website/content/features.md index 9503e9d5b7d..3ce52b449a4 100644 --- a/website/content/features.md +++ b/website/content/features.md @@ -68,9 +68,9 @@ Marrying vector and raster under one roof enables both art forms to complement e
- +
-

— Formulation —

+

— Inception —