New node: 'Blend If' (#5065)

Add Blend If, hiding content by its own tones and those beneath it
This commit is contained in:
Keavon Chambers authored and GitHub committed 2026-12-03 04:03:46 -08:00
1 parent c8e8fbf8d1
commit e30bf2e987
31 files changed
+4121 -233

No files matched your search

@@ -3,7 +3,7 @@
//! Content with an effect no filter can carry out, and a backdrop whose copy in markup would nest, are drawn as images in place of markup.
//! Placeholders stand in for each until it's resolved, leaving an SVG that never is short of those effects.
use crate::renderer::{CanvasImage, Render, RenderOutputType, RenderParams, RenderSvgSegmentList, SvgRender, render_raster_cpu_image_svg};
use crate::renderer::{CanvasImage, Render, RenderOutputType, RenderParams, RenderSvgSegmentList, SvgRender, format_transform_matrix, render_raster_cpu_image_svg};
use crate::vello_scene_builder::{MAX_EFFECTS_AREA_PER_VIEWPORT_AREA, VelloSceneBuilder};
use core_types::Color;
use core_types::blending::BlendMode;
@@ -202,6 +202,8 @@ pub struct DeferredImage {
pub margin: f64,
pub opacity: f32,
pub blend_mode: BlendMode,
/// The reference for the mask fading the image by Blend If's ranges of what lies beneath, if any.
pub mask: Option<String>,
}
/// What the GPU renders an image of for an SVG.
@@ -276,6 +278,7 @@ pub struct DeferredImagePlacement {
pub user_to_document: DAffine2,
pub opacity: f32,
pub blend_mode: BlendMode,
pub mask: Option<String>,
/// Whether the image is drawn to a canvas rather than embedded in the SVG.
pub to_canvas: bool,
/// Screen pixels per document unit, which sizes an image drawn to a canvas.
@@ -289,14 +292,22 @@ pub struct DeferredImageLayout {
pub size: UVec2,
}
/// The starts of the markers around the markup standing in for an item of deferred content, which its ID and `-->` follow.
pub(crate) const DEFERRED_IMAGE_OPENING: &str = "<!--deferred-image-";
pub(crate) const DEFERRED_IMAGE_CLOSING: &str = "<!--/deferred-image-";
/// The starts of the markers around a copy of that markup in a Blend If mask, which can't draw the canvas of its image, followed by its ID, a hyphen and the key color's hex (for the opening), and `-->`.
pub(crate) const DEFERRED_COVER_OPENING: &str = "<!--deferred-cover-";
pub(crate) const DEFERRED_COVER_CLOSING: &str = "<!--/deferred-cover-";
/// The markers that open and close the markup standing in for the item of deferred content `id` names.
pub(crate) fn image_markers(id: u64) -> (String, String) {
(format!("<!--deferred-image-{id}-->"), format!("<!--/deferred-image-{id}-->"))
(format!("{DEFERRED_IMAGE_OPENING}{id}-->"), format!("{DEFERRED_IMAGE_CLOSING}{id}-->"))
}
/// Whether the `markup` holds markers of markup standing in for an item of deferred content.
pub(crate) fn holds_image_markers(markup: &str) -> bool {
markup.contains("<!--deferred-image-")
markup.contains(DEFERRED_IMAGE_OPENING)
}
impl DeferredImage {
@@ -311,6 +322,7 @@ impl DeferredImage {
user_to_document: self.user_to_document,
opacity: self.opacity,
blend_mode: self.blend_mode,
mask: self.mask.clone(),
to_canvas: self.render_params.to_canvas(),
canvas_image_scale: self.render_params.canvas_image_scale,
},
@@ -358,11 +370,41 @@ pub fn substitute_deferred_image(svg: &mut String, image_data: &mut Vec<(u64, Ca
canvas_image_scale: placement.canvas_image_scale,
..Default::default()
};
render_raster_cpu_image_svg(image, placement.transform, placement.opacity, placement.blend_mode, &mut render, &render_params);
let opacity = if placement.opacity < 1. { format!(r#" opacity="{}""#, placement.opacity) } else { String::new() };
let style = if placement.blend_mode != BlendMode::Normal {
format!(r#" style="{}""#, placement.blend_mode.render())
} else {
String::new()
};
let markup = render.svg.to_svg_string();
// A mask goes on a group taking the image's opacity and blend mode, which still blends with what lies beneath
let markup = match &placement.mask {
Some(mask) => {
render_raster_cpu_image_svg(image, placement.transform, 1., BlendMode::Normal, &mut render, &render_params);
format!(r#"<g mask="{mask}"{opacity}{style}>{}</g>"#, render.svg.to_svg_string())
}
None => {
render_raster_cpu_image_svg(image, placement.transform, placement.opacity, placement.blend_mode, &mut render, &render_params);
render.svg.to_svg_string()
}
};
while let Some(span) = marked_span(svg, &opening, &closing) {
svg.replace_range(span, &markup);
}
image_data.extend(render.image_data);
// A Blend If mask can't draw the canvas in its copy of what lies beneath, so a rectangle of the color its ranges show in full covers the image there
if placement.to_canvas {
let (opening, closing) = (format!("{DEFERRED_COVER_OPENING}{}-", placement.id), format!("{DEFERRED_COVER_CLOSING}{}-->", placement.id));
let transform = format_transform_matrix(placement.transform);
while let Some(start) = svg.find(&opening) {
let key_start = start + opening.len();
let Some(key_end) = svg[key_start..].find("-->").map(|offset| key_start + offset) else { break };
let Some(end) = svg[key_end..].find(&closing).map(|offset| key_end + offset + closing.len()) else {
break;
};
let cover = format!(r##"<rect width="1" height="1" transform="{transform}" fill="#{}"{opacity}{style} />"##, &svg[key_start..key_end]);
svg.replace_range(start..end, &cover);
}
}
}
@@ -3,6 +3,7 @@ pub mod deferred_image;
pub mod render_ext;
mod renderer;
mod svg_backdrop;
mod svg_blend_if;
pub mod to_peniko;
pub mod vello_scene_builder;
File diff suppressed because it is too large. Load diff
@@ -134,7 +134,8 @@ 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.
pub(crate) fn backdrop_copy(&mut self, render_params: &RenderParams, region: [DVec2; 2], read_reach: f64) -> Option<String> {
/// The image is embedded `for_mask`, which draws no canvas.
pub(crate) fn backdrop_copy(&mut self, render_params: &RenderParams, region: [DVec2; 2], read_reach: f64, for_mask: bool) -> Option<BackdropCopy> {
if self.drawing_deferred_markup || !self.transform.matrix2.determinant().is_normal() {
return None;
}
@@ -151,8 +152,11 @@ 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));
// An image needs the outline of the root's clip, if it has one, to cut what it holds by
let image_clip = match holds_backdrop && self.images_replace_markup(render_params) {
let image_clip = match images && self.images_replace_markup(render_params) {
true => match &clip {
Some((reference, _)) => self.clip_outline(reference).map(Some),
None => Some(None),
@@ -161,9 +165,16 @@ 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 copies = match (holds_backdrop, image_clip) {
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),
(true, Some(clip)) => self.backdrop_image(root, copies_to_document, clip, region, read_reach, render_params),
(true, Some(clip)) => {
let image_params = RenderParams {
embeds_images: render_params.embeds_images || for_mask,
..render_params.clone()
};
self.backdrop_image(root, copies_to_document, clip, region, read_reach, &image_params)
}
(true, None) => self.backdrop_markup_copies(root, copies_to_document, true, true),
}?;
@@ -172,11 +183,22 @@ impl SvgRender {
group.holds_backdrop = true;
}
let Some((clip_path, root_to_document)) = clip else { return Some(copies) };
let markup = match clip {
Some((clip_path, root_to_document)) => {
let matrix = format_transform_matrix(self.transform.inverse() * root_to_document);
let transform = if matrix.is_empty() { String::new() } else { format!(r#" transform="{matrix}""#) };
format!(r#"<g{transform} clip-path="{clip_path}">{copies}</g>"#)
}
None => copies,
};
Some(BackdropCopy { markup, image })
}
let matrix = format_transform_matrix(self.transform.inverse() * root_to_document);
let transform = if matrix.is_empty() { String::new() } else { format!(r#" transform="{matrix}""#) };
Some(format!(r#"<g{transform} clip-path="{clip_path}">{copies}</g>"#))
/// 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).
fn draws_canvases_since(&self, root: usize, render_params: &RenderParams) -> bool {
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)
}
/// 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.
@@ -240,6 +262,7 @@ impl SvgRender {
margin: self.ancestors_reach + read_reach,
opacity: 1.,
blend_mode: BlendMode::Normal,
mask: None,
});
let (opening, closing) = deferred_image::image_markers(id);
@@ -247,6 +270,13 @@ impl SvgRender {
}
}
/// Markup showing what lies beneath content (see [`SvgRender::backdrop_copy`]).
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.
pub image: bool,
}
/// The outline of the union of the `shapes`, each filled by the nonzero rule, as one path filled by that rule, or `None` if their coordinates aren't finite or a sweep fails.
/// Each shape's winding is resolved alone first, so the final sweep counts one winding rather than one per shape at every edge.
fn united_outline(shapes: &[BezPath]) -> Option<BezPath> {
@@ -336,7 +366,7 @@ pub(crate) fn backdrop_markup(render: &mut SvgRender, effects: &Effects, bounds:
let space_to_user = space.unwrap_or_default();
let read_region = (space_to_user * Quad::from_box([min, max])).bounding_box();
let read_reach = reach * spans_along_axes((render.transform * space_to_user).matrix2).max_element();
let copy = render.backdrop_copy(render_params, read_region, read_reach)?;
let copy = render.backdrop_copy(render_params, read_region, read_reach, false)?.markup;
let copy = match space.map(|space| format_transform_matrix(space.inverse())) {
Some(matrix) if !matrix.is_empty() => format!(r#"<g transform="{matrix}">{copy}</g>"#),
_ => copy,
@@ -0,0 +1,228 @@
//! Blend If in SVG, all native: filter primitives weigh each pixel by its channels' levels through tables of the ranges' weights, fading the content within its effects filter,
//! and a mask holding a copy of what lies beneath, filtered into its weights, fades every layer the content draws.
use crate::deferred_image::{DEFERRED_COVER_CLOSING, DEFERRED_COVER_OPENING, DEFERRED_IMAGE_CLOSING, DEFERRED_IMAGE_OPENING};
use crate::renderer::{RenderParams, SvgRender};
use core_types::uuid::generate_uuid;
use glam::DVec2;
use graphic_types::BlendIfChannel;
use graphic_types::blend_if::{BlendRange, ChannelRanges, GRAY_PERCENTAGES};
use graphic_types::effects::spans_along_axes;
use std::fmt::Write;
/// Pushes the primitives weighing how strongly the `ranges` show each pixel of the `image` result by its straight color, given `push` (a primitive's tag, attributes, and children, returning its result's name).
/// Returns the name of the result holding the weight in its alpha, or `None` if the ranges show everything.
pub(crate) fn weight(push: &mut impl FnMut(&str, &str, &str) -> String, image: &str, ranges: &ChannelRanges) -> Option<String> {
let mut weight: Option<String> = None;
for (channel, range) in ranges.limiting() {
// A gray exactly between two levels gains a sliver of a level, so it rounds up as `gray_level` rounds it
let [red, green, blue] = GRAY_PERCENTAGES.map(|percentage| percentage as f64 / 100.);
let alpha_row = match channel {
BlendIfChannel::Gray => format!("{red} {green} {blue} 0 {}", 0.005 / 255.),
BlendIfChannel::Red => "1 0 0 0 0".to_string(),
BlendIfChannel::Green => "0 1 0 0 0".to_string(),
BlendIfChannel::Blue => "0 0 1 0 0".to_string(),
};
// The channel's level moved into alpha, then looked up in the table of the range's weight at each level, which the browser's 8-bit filters index exactly
let level = push(
"feColorMatrix",
&format!(r#"in="{image}" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 {alpha_row}" color-interpolation-filters="sRGB""#),
"",
);
let table: Vec<String> = range.level_weights().iter().map(|weight| format_table_value(*weight)).collect();
let shown = push(
"feComponentTransfer",
&format!(r#"in="{level}" color-interpolation-filters="sRGB""#),
&format!(r#"<feFuncA type="table" tableValues="{}" />"#, table.join(" ")),
);
weight = Some(match weight {
Some(previous) => push("feComposite", &format!(r#"in="{shown}" in2="{previous}" operator="in""#), ""),
None => shown,
});
}
weight
}
/// 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 {
with_canvases_covered(&with_deferred_images_marked_for_covers(markup, key), key)
}
/// The `markup` with the canvases standing in for images covered with the `key` color, at their own placement, size, opacity, and blend mode, so a translucent image hides less of what lies beneath it.
fn with_canvases_covered(markup: &str, key: &str) -> String {
const OPENING: &str = "<foreignObject";
const CLOSING: &str = "</foreignObject>";
let mut covered = String::with_capacity(markup.len());
let mut rest = markup;
while let Some(start) = rest.find(OPENING) {
let Some(end) = rest[start..].find(CLOSING).map(|offset| start + offset + CLOSING.len()) else {
break;
};
covered.push_str(&rest[..start]);
// A canvas's cover takes its opening tag's attributes
let element = &rest[start..end];
match (element.contains("data-canvas-placeholder"), element.find('>')) {
(true, Some(tag_end)) => write!(covered, r#"<rect{} fill="{key}" />"#, &element[OPENING.len()..tag_end]).unwrap(),
(true, None) => {}
(false, _) => covered.push_str(element),
}
rest = &rest[end..];
}
covered.push_str(rest);
covered
}
/// The `markup` with the markup standing in for each image the GPU renders marked for a rectangle of the `key` color to cover once the image arrives (see [`crate::deferred_image::substitute_deferred_image`]).
/// Without a GPU the markup is what's drawn, which the mask reads as it is.
fn with_deferred_images_marked_for_covers(markup: &str, key: &str) -> String {
let markup = markup.replace(DEFERRED_IMAGE_CLOSING, DEFERRED_COVER_CLOSING);
let mut parts = markup.split(DEFERRED_IMAGE_OPENING);
let mut marked = parts.next().unwrap_or_default().to_string();
for part in parts {
// Each opening marker's ID is followed by the end of the comment, before which the key goes
match part.split_once("-->") {
Some((id, rest)) => write!(marked, "{DEFERRED_COVER_OPENING}{id}-{}-->{rest}", key.trim_start_matches('#')).unwrap(),
None => write!(marked, "{DEFERRED_IMAGE_OPENING}{part}").unwrap(),
}
}
marked
}
/// A color the `underlying` ranges, which multiply, show most strongly (in full if any color is shown in full), as a hex color.
/// Each channel shows its levels in full in one span, and the gray rises with each channel, so the colors from every channel's lowest such level to every one's highest pass through each gray between them.
fn key_color(underlying: &[ChannelRanges]) -> String {
// The span of levels each channel shows most strongly, by itself
let span = |range: fn(&ChannelRanges) -> &BlendRange| {
let shown = |level: usize| underlying.iter().map(|ranges| range(ranges).weight(level as f64 / 255.)).product::<f64>();
let most = (0..256).map(shown).fold(0., f64::max);
let levels: Vec<usize> = (0..256).filter(|&level| shown(level) >= most).collect();
[levels.first().copied().unwrap_or(0), levels.last().copied().unwrap_or(255)].map(|level| level as f64)
};
let spans = [span(|ranges| &ranges.red), span(|ranges| &ranges.green), span(|ranges| &ranges.blue)];
// O(256 × ranges): the colors along the way from the lowest ends to the highest, which the gray's ranges show most strongly somewhere
let weight = |color: [f64; 3]| underlying.iter().map(|ranges| ranges.weight(color)).product::<f64>();
let color_at = |step: usize| spans.map(|[low, high]| (low + (high - low) * step as f64 / 255.).round() / 255.);
let best = (0..256).map(color_at).fold(color_at(0), |best, color| if weight(color) > weight(best) { color } else { best });
let [red, green, blue] = best.map(|channel| (channel * 255.).round() as u8);
format!("#{red:02x}{green:02x}{blue:02x}")
}
/// A weight for a table, with no more digits than it needs.
fn format_table_value(weight: f64) -> String {
let rounded = format!("{weight:.4}");
rounded.trim_end_matches('0').trim_end_matches('.').to_string()
}
/// Writes a mask into the render's defs that fades what's drawn in the current user space by how strongly the `underlying` ranges, which multiply, show what lies beneath, returning its reference, or `None` with nothing beneath to read.
/// `bounds` is the content's extent in this user space and `reach` how far its effects reach past it along each axis there.
pub(crate) fn underlying_mask(render: &mut SvgRender, underlying: &[ChannelRanges], bounds: [DVec2; 2], reach: DVec2, render_params: &RenderParams) -> Option<String> {
let mut markup = String::new();
let mut count = 0;
let mut push = |tag: &str, attributes: &str, children: &str| {
count += 1;
let result = format!("blend-if-{count}");
match children.is_empty() {
true => write!(markup, r#"<{tag} {attributes} result="{result}" />"#),
false => write!(markup, r#"<{tag} {attributes} result="{result}">{children}</{tag}>"#),
}
.unwrap();
result
};
// Each side's channels multiply, and so do the sides
let mut weight: Option<String> = None;
for ranges in underlying {
let Some(shown) = self::weight(&mut push, "SourceGraphic", ranges) else { continue };
weight = Some(match weight {
Some(previous) => push("feComposite", &format!(r#"in="{shown}" in2="{previous}" operator="in""#), ""),
None => shown,
});
}
let weight = weight?;
// Where nothing lies beneath, nothing is hidden: the weight is 1 - alpha × (1 - weight)
let invert = r#"<feFuncA type="linear" slope="-1" intercept="1" />"#;
let hidden = push("feComponentTransfer", &format!(r#"in="{weight}""#), invert);
let hidden_beneath = push("feComposite", &format!(r#"in="{hidden}" in2="SourceAlpha" operator="in""#), "");
push("feComponentTransfer", &format!(r#"in="{hidden_beneath}""#), invert);
// The mask covers how far the effects reach past the content, and a document pixel more for the pixels its edges cut through
let reach = reach + spans_along_axes(render.transform.matrix2.inverse());
let (min, max) = (bounds[0] - reach, bounds[1] + reach);
let region = format!(r#"x="{}" y="{}" width="{}" height="{}""#, min.x, min.y, max.x - min.x, max.y - min.y);
// Each pixel reads only what lies beneath it, so an image of that reads nothing past the view
let copy = render.backdrop_copy(render_params, [min, max], 0., true)?;
// Where canvases and the GPU's images stand in for what lies beneath in a copy of its markup, it can't be read, so nothing there is hidden
let copy = match copy.image {
true => copy.markup,
false => with_unreadable_covered(&copy.markup, &key_color(underlying)),
};
let (filter_id, mask_id) = (format!("blend-if-{}", generate_uuid()), format!("blend-if-mask-{}", generate_uuid()));
write!(
render.svg_defs,
r#"<filter id="{filter_id}" filterUnits="userSpaceOnUse" {region} color-interpolation-filters="sRGB">{markup}</filter><mask id="{mask_id}" mask-type="alpha" maskUnits="userSpaceOnUse" {region}><g filter="url(#{filter_id})">{copy}</g></mask>"#
)
.unwrap();
Some(format!("url(#{mask_id})"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keys_are_colors_the_ranges_show_in_full_where_no_gray_is() {
// Red from 60% up and blue up to 40%, which no gray passes both of
let mut ranges = ChannelRanges::default();
(ranges.red.falloff_start, ranges.red.range_start) = (60., 60.);
(ranges.blue.range_end, ranges.blue.falloff_end) = (40., 40.);
let key = key_color(&[ranges]);
let channel = |index: usize| u8::from_str_radix(&key[1 + 2 * index..3 + 2 * index], 16).unwrap() as f64 / 255.;
assert_eq!(ranges.weight([channel(0), channel(1), channel(2)]), 1., "{key}");
}
#[test]
fn copies_where_no_image_stands_in_cover_canvases_and_the_gpus_images_with_the_key_color() {
use crate::deferred_image::{DeferredImagePlacement, substitute_deferred_image};
use core_types::Color;
use core_types::blending::BlendMode;
use glam::DAffine2;
use graphic_types::raster_types::{Image, Raster};
let canvas = r#"<foreignObject x="1" y="2" width="3" height="4"><div data-canvas-placeholder="image-7"></div></foreignObject>"#;
let stand_in = r#"<!--deferred-image-9--><path d="M0,0" /><!--/deferred-image-9-->"#;
let covered = with_unreadable_covered(&format!("{canvas}{stand_in}"), "#000000");
// A canvas becomes a rectangle of the key color at its own placement, and the stand-in for the GPU's image is marked for one
assert!(covered.starts_with(r##"<rect x="1" y="2" width="3" height="4" fill="#000000" />"##), "{covered}");
assert!(covered.contains(r#"<!--deferred-cover-9-000000--><path d="M0,0" /><!--/deferred-cover-9-->"#), "{covered}");
// Once the GPU's image arrives in a canvas in place of the original stand-in, the rectangle replaces the copy's
let placement = DeferredImagePlacement {
id: 9,
transform: DAffine2::IDENTITY,
user_to_document: DAffine2::IDENTITY,
opacity: 1.,
blend_mode: BlendMode::Normal,
mask: None,
to_canvas: true,
canvas_image_scale: 1.,
};
let mut svg = format!("{covered}{stand_in}");
substitute_deferred_image(&mut svg, &mut Vec::new(), &placement, &Raster::new_cpu(Image::new(1, 1, Color::BLACK)));
assert!(svg.contains(r##"<rect width="1" height="1" transform="" fill="#000000" />"##) && !svg.contains("deferred-"), "{svg}");
}
}
@@ -613,7 +613,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();
if reads_backdrop {
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());
let linear = effect_to_device.matrix2;