New node: 'Background Blur' (#5063)

Add a Background Blur effect that blurs what lies beneath the content
This commit is contained in:
Keavon Chambers authored and GitHub committed 2026-12-03 02:35:26 -08:00
1 parent cfb45f2d54
commit 9517b006fa
18 files changed
+3702 -187

No files matched your search

Generated
+1
View File
@@ -6021,6 +6021,7 @@ dependencies = [
"graphene-resource",
"graphic-types",
"kurbo",
"linesweeper",
"log",
"num-traits",
"parley",
@@ -22,6 +22,8 @@ pub enum PiecePlace {
IntoContent { over: bool },
/// The part of an interior piece blending with what shows through the content's fill, in a layer of its mode beneath the content's, or with `over`, over it.
Through { over: bool },
/// What lies beneath the content, filtered and cut to its silhouette, at the bottom of the content's own layer.
Backdrop,
}
/// One coverage of an effect that draws as a piece of its own, named like the map of it.
@@ -115,10 +117,16 @@ impl EffectLayers {
.chain([(LayerPart::Content, blend_mode)])
.collect();
// A shadow not knocked out in the content's layer, flattened or layered, would hide a part placed beneath that layer
// A blurred backdrop, or a shadow not knocked out (flattened or layered), in the content's layer would hide a part placed beneath that layer
let backdrop: Vec<LayerPart> = pieces_from(0, operations.len())
.into_iter()
.filter(|(piece, _)| piece.place == PiecePlace::Backdrop)
.map(|(piece, _)| LayerPart::Piece(piece))
.collect();
let shows_through = |piece: &EffectPiece| piece.place == PiecePlace::Beneath && !piece.knocks_out;
let mut content_run = parts.iter().rev().skip(1).take_while(|(_, mode)| *mode == BlendMode::Normal);
let covered_beneath = content_run.any(|(part, _)| matches!(part, LayerPart::Piece(piece) if shows_through(piece))) || unmerged.iter().any(|(piece, _)| shows_through(piece));
let covered_beneath =
!backdrop.is_empty() || content_run.any(|(part, _)| matches!(part, LayerPart::Piece(piece) if shows_through(piece))) || unmerged.iter().any(|(piece, _)| shows_through(piece));
// Interior pieces of normal content blend within its share, in its layer. Below a full fill, a blended one splits off its part through the fill into a layer beneath
// the content's, or over it when its mode isn't straight along what lies beneath or a shadow covers that, as every later piece then does to keep their order.
@@ -166,8 +174,8 @@ impl EffectLayers {
layers.splice(content_layer..content_layer, through);
}
// One normal layer at a full fill draws the same with all its effects flattened into the content's image, which takes fewer passes
if blends_into_content && matches!(layers.as_slice(), [layer] if layer.blend_mode == BlendMode::Normal) {
// One normal layer at a full fill draws the same with all its effects flattened into the content's image, which takes fewer passes, unless it blurs what lies beneath
if blends_into_content && backdrop.is_empty() && matches!(layers.as_slice(), [layer] if layer.blend_mode == BlendMode::Normal) {
let content = EffectLayer {
blend_mode: BlendMode::Normal,
parts: vec![LayerPart::Content],
@@ -179,6 +187,11 @@ impl EffectLayers {
};
}
// What lies beneath, filtered, goes at the bottom of the content's own layer, which fades and blends it with the content, even from a row flattened into the content
if let Some(content_layer) = layers.iter_mut().find(|layer| layer.holds_content()) {
content_layer.parts.splice(0..0, backdrop);
}
Self { flattened, layers, trailing_masks }
}
@@ -201,6 +214,11 @@ impl EffectLayers {
planned
}
/// Whether a layered piece reads what lies beneath the content.
pub fn reads_backdrop(&self) -> bool {
(self.layers.iter().flat_map(|layer| &layer.parts)).any(|part| matches!(part, LayerPart::Piece(piece) if piece.place == PiecePlace::Backdrop))
}
/// The index of the layer holding the content.
pub fn content_layer(&self) -> Option<usize> {
self.layers.iter().position(EffectLayer::holds_content)
@@ -263,6 +281,13 @@ impl EffectLayers {
}
}
/// Whether any of the effects reads what lies beneath the content, like a background blur.
pub fn effects_read_backdrop(effects: &Effects) -> bool {
effects
.operations()
.any(|operation| matches!(operation, EffectOperation::BackgroundBlur { .. }) && !operation.changes_nothing())
}
/// 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.
@@ -392,6 +417,7 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM
inside.into_iter().chain(outside).flatten().collect()
}
EffectOperation::PaintOverlay { blend_mode, .. } => vec![piece(0, Within, None, *blend_mode)],
EffectOperation::BackgroundBlur { .. } => vec![piece(0, Backdrop, None, BlendMode::Normal)],
EffectOperation::Adjustment(Adjustment::ColorOverlay { color, blend_mode, .. }) => vec![piece(0, Within, Some(*color), *blend_mode)],
EffectOperation::Blur { .. }
| EffectOperation::MotionBlur { .. }
@@ -568,6 +594,11 @@ mod tests {
fn interior_pieces_go_over_the_content_where_its_layer_covers_what_lies_beneath_it() {
let red = RED.with_alpha(0.75);
let through_over = PiecePlace::Through { over: true };
let background_blur = EffectOperation::BackgroundBlur {
radius: 4.,
box_blur: false,
gamma: false,
};
let with_knockout = |knocks_out: bool| {
let mut shadow = drop_shadow(Color::BLACK.with_alpha(0.75), BlendMode::Multiply);
@@ -577,10 +608,12 @@ mod tests {
shadow
};
// A shadow not knocked out beneath the content in its layer would hide even a straight piece's part beneath that layer
let layers = EffectLayers::plan(&Effects::from_operations([with_knockout(false), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
assert_eq!(modes(&layers), [BlendMode::Normal, BlendMode::Screen]);
assert_eq!(parts(&layers)[1], [Some((1, 0, through_over))]);
// A blurred backdrop, or a shadow not knocked out, beneath the content in its layer would hide even a straight piece's part beneath that layer
for beneath in [background_blur, with_knockout(false)] {
let layers = EffectLayers::plan(&Effects::from_operations([beneath.clone(), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
assert_eq!(modes(&layers), [BlendMode::Normal, BlendMode::Screen], "{beneath:?}");
assert_eq!(parts(&layers)[1], [Some((1, 0, through_over))], "{beneath:?}");
}
// A knocked-out shadow doesn't cover it there
let layers = EffectLayers::plan(&Effects::from_operations([with_knockout(true), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
@@ -758,6 +791,30 @@ mod tests {
assert_eq!(kinds(filtered), [EffectKind::Mask, EffectKind::InnerShadow, EffectKind::Blur, EffectKind::Mask]);
}
#[test]
fn a_background_blur_lies_at_the_bottom_of_the_contents_layer() {
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
let background_blur = EffectOperation::BackgroundBlur {
radius: 4.,
box_blur: false,
gamma: false,
};
let blur = EffectOperation::Blur {
radius_mask: Default::default(),
radius: 2.,
box_blur: false,
gamma: false,
};
// Even beside a blended shadow, and flattened by a later blur, it fades and blends with the content
let effects = Effects::from_operations([drop_shadow(blue, BlendMode::Multiply), background_blur, blur]);
let layers = EffectLayers::plan(&effects, BlendMode::Screen, 1., true);
assert!(layers.reads_backdrop());
let content_layer = layers.content_layer().unwrap();
assert_eq!(layers.layers[content_layer].blend_mode, BlendMode::Screen);
assert_eq!(parts(&layers)[content_layer], [Some((1, 0, PiecePlace::Backdrop)), None]);
}
#[test]
fn knocked_out_pieces_hide_behind_however_the_content_covers_them() {
let same_layer = EffectLayers::plan(&Effects::from_operations([drop_shadow(RED, BlendMode::Normal)]), BlendMode::Normal, 0.5, true);
@@ -91,6 +91,8 @@ pub enum EffectKind {
Pixelate,
/// Prints each color channel of the content as dots on its own turned screen, as a press prints ink.
ColorHalftone,
/// Blurs what lies beneath the content within its silhouette, as if seen through frosted glass.
BackgroundBlur,
// The adjustments, which change each color of the content on its own, as their nodes of the same names do
Desaturate,
GammaCorrection,
@@ -148,6 +150,7 @@ impl std::fmt::Display for EffectKind {
Self::Displace => "Displace",
Self::Pixelate => "Pixelate",
Self::ColorHalftone => "Color Halftone",
Self::BackgroundBlur => "Background Blur",
Self::Desaturate => "Desaturate",
Self::GammaCorrection => "Gamma Correction",
Self::MakeOpaque => "Make Opaque",
@@ -452,7 +455,7 @@ impl Effects {
self.effects().skip(rows.start).take(rows.len()).map(Effect::operation)
}
/// How far past the content the effects together can paint, in the effect space of a run of them.
/// How far past the content the effects together can paint, or a background blur among them reads what lies beneath, in the effect space of a run of them.
/// It leaves out what [`Effects::reach_around`] adds from the content's bounds and what it paints past its frame, for the effects relative to its extent.
pub fn reach(&self) -> f64 {
self.operations().map(|operation| operation.painted_reach()).sum()
@@ -1228,6 +1231,15 @@ pub enum EffectOperation {
/// Percent of the spacing between dots that each screen's dots lie past the `offset` along both of its axes.
phase: f64,
},
/// Blurs the backdrop beneath the content within the content's silhouette, beneath the content and its effects.
BackgroundBlur {
/// The standard deviation of the Gaussian, or the half width of the box.
radius: f64,
/// Whether to average a box of pixels rather than weighting them by a Gaussian.
box_blur: bool,
/// Whether to blend the colors with their gamma encoding rather than in linear light.
gamma: bool,
},
Adjustment(Adjustment),
}
@@ -1285,6 +1297,7 @@ impl EffectOperation {
Self::Displace { .. } => EffectKind::Displace,
Self::Pixelate { .. } => EffectKind::Pixelate,
Self::ColorHalftone { .. } => EffectKind::ColorHalftone,
Self::BackgroundBlur { .. } => EffectKind::BackgroundBlur,
Self::Adjustment(adjustment) => adjustment.kind(),
}
}
@@ -1315,7 +1328,7 @@ impl EffectOperation {
/// Whether this operation leaves the content as it is, like a blur of no radius or a shadow of no opacity.
pub fn changes_nothing(&self) -> bool {
match self {
Self::Blur { radius, .. } => *radius <= 0.,
Self::Blur { radius, .. } | Self::BackgroundBlur { radius, .. } => *radius <= 0.,
Self::DropShadow { color, .. } | Self::InnerShadow { color, .. } | Self::Satin { color, .. } => color.a() <= 0.,
Self::OuterGlow { color, noise, .. } | Self::InnerGlow { color, noise, .. } => GlowFill::of(color).is_none_or(|fill| fill.is_invisible(*noise)),
Self::Outline { paint, weight, contour_gradient, .. } => *weight <= 0. || OutlineFill::of(paint, *contour_gradient).is_none_or(|fill| fill.is_invisible()),
@@ -1375,6 +1388,16 @@ impl EffectOperation {
matches!(self, Self::Blur { radius_mask, .. } if !radius_mask.draws_nothing())
}
/// Whether this operation paints nothing past the content, whatever it reads there, like an inner shadow finding the edges it casts from.
pub fn paints_only_within_content(&self) -> bool {
match self {
Self::InnerShadow { .. } | Self::InnerGlow { .. } | Self::Satin { .. } | Self::Mask { .. } | Self::Feather { .. } | Self::BackgroundBlur { .. } => true,
Self::Outline { align, .. } => *align == StrokeAlign::Inside,
Self::BevelAndEmboss { style, .. } => *style == BevelStyle::InnerBevel,
_ => false,
}
}
/// Whether this operation reads the pixels around each one of the image the effects before it leave, like a blur or a warp, rather than casting from the content's shape or changing each pixel alone.
pub fn reads_pixels_around(&self) -> bool {
match self {
@@ -1383,7 +1406,7 @@ impl EffectOperation {
true
}
Self::ConvolutionKernel { .. } | Self::Emboss { .. } | Self::FindEdges | Self::MinimumMaximum { .. } | Self::Sharpen { .. } | Self::HighPass { .. } => true,
// Cast from the content's shape, reading a mask's own image or a feather's map, or changing each pixel alone
// Cast from the content's shape, reading a mask's or the backdrop's own image or a feather's map, or changing each pixel alone
Self::DropShadow { .. }
| Self::InnerShadow { .. }
| Self::OuterGlow { .. }
@@ -1392,7 +1415,7 @@ impl EffectOperation {
| Self::Outline { .. }
| Self::BevelAndEmboss { .. }
| Self::Feather { .. } => false,
Self::PaintOverlay { .. } | Self::Mask { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => false,
Self::PaintOverlay { .. } | Self::Mask { .. } | Self::BackgroundBlur { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => false,
}
}
@@ -1429,8 +1452,9 @@ impl EffectOperation {
pub fn reach(&self) -> f64 {
match self {
// A box reaches its half width, and the pixel past it for a fractional one, while a Gaussian fades out over three standard deviations
Self::Blur { radius, box_blur: true, .. } => radius.max(0.) + 1.,
Self::Blur { radius, .. } => 3. * radius.max(0.),
Self::Blur { radius, box_blur: true, .. } | Self::BackgroundBlur { radius, box_blur: true, .. } => radius.max(0.) + 1.,
// A background blur reads as far past the content as its Gaussian reaches
Self::Blur { radius, .. } | Self::BackgroundBlur { radius, .. } => 3. * radius.max(0.),
// An inner shadow paints within the content but reads this far out to find the edges it casts from.
// Shadows and glows end within their size, past which a precise glow fades over one more unit.
Self::DropShadow { distance, size, .. } | Self::InnerShadow { distance, size, .. } => distance.abs() + size.max(0.) + 1.,
@@ -1516,7 +1540,7 @@ impl EffectOperation {
};
match &mut self {
Self::Blur { radius, .. } => finite(radius),
Self::Blur { radius, .. } | Self::BackgroundBlur { radius, .. } => finite(radius),
Self::DropShadow { angle, distance, spread, size, .. }
| Self::InnerShadow {
angle, distance, choke: spread, size, ..
@@ -1801,6 +1825,11 @@ impl EffectOperation {
offset: DVec2::ZERO,
phase: 0.,
},
EffectKind::BackgroundBlur => Self::BackgroundBlur {
radius: 0.,
box_blur: false,
gamma: false,
},
EffectKind::Desaturate => Self::Adjustment(Adjustment::Desaturate { method: Default::default() }),
EffectKind::GammaCorrection => Self::Adjustment(Adjustment::GammaCorrection { gamma: 0., inverse: false }),
EffectKind::MakeOpaque => Self::Adjustment(Adjustment::MakeOpaque { strength: 0. }),
@@ -1853,6 +1882,11 @@ impl EffectOperation {
visitor.parameter("box_blur", box_blur, false);
visitor.parameter("gamma", gamma, false);
}
Self::BackgroundBlur { radius, box_blur, gamma } => {
visitor.parameter("radius", radius, 10.);
visitor.parameter("box_blur", box_blur, false);
visitor.parameter("gamma", gamma, false);
}
Self::DropShadow {
color,
blend_mode,
@@ -2193,6 +2227,23 @@ mod tests {
use super::*;
use vector_types::{Gradient, GradientStop};
#[test]
fn box_blurs_reach_their_half_width_and_a_pixel_while_gaussians_reach_three_radii() {
let blur = |box_blur| EffectOperation::Blur {
radius_mask: Graphic::default(),
radius: 6.,
box_blur,
gamma: false,
};
let background_blur = |box_blur| EffectOperation::BackgroundBlur { radius: 6., box_blur, gamma: false };
// Whether it blurs the content or what lies beneath it, a blur reaches as far as its kernel reads
for (box_blur, reach) in [(true, 7.), (false, 18.)] {
assert_eq!(blur(box_blur).reach(), reach, "box: {box_blur}");
assert_eq!(background_blur(box_blur).reach(), reach, "box: {box_blur}");
}
}
#[test]
fn rows_round_trip_their_operations_eliding_defaults() {
let operations = [
@@ -2780,6 +2831,16 @@ mod tests {
assert_eq!(runs, vec![0..3, 3..4]);
}
#[test]
fn effects_painting_only_within_the_content_paint_nothing_past_it() {
// An inner shadow reads past the content to find the edges it casts from, but paints only within it
let (inner_shadow, drop_shadow) = (EffectOperation::default_for(EffectKind::InnerShadow), EffectOperation::default_for(EffectKind::DropShadow));
let painted = |effects: Effects| effects.reach_around_by(DAffine2::IDENTITY, [DVec2::ZERO; 2], 0., |operation| !operation.paints_only_within_content());
assert!(Effects::from_operations([inner_shadow.clone()]).reach() > 0.);
assert_eq!(painted(Effects::from_operations([inner_shadow.clone()])), DVec2::ZERO);
assert_eq!(painted(Effects::from_operations([inner_shadow, drop_shadow.clone()])), DVec2::splat(drop_shadow.reach()));
}
#[test]
fn adjustment_rows_elide_their_defaults_and_name_grouped_parameters() {
use EffectKind::*;
@@ -1745,6 +1745,7 @@ impl EffectOperation {
| Self::HighPass { .. }
| Self::AddNoise { .. }
| Self::Dissolve { .. }
| Self::BackgroundBlur { .. }
| Self::Adjustment(_) => false,
}
}
@@ -511,6 +511,8 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
};
place_within(&mut pieces, piece(0), &mut full, &mut filled, painted, blend_mode);
}
// An image of its own has nothing beneath it to blur
EffectOperation::BackgroundBlur { .. } => {}
// A solid paint overlay paints within the content alone, like any other paint overlay
EffectOperation::Adjustment(Adjustment::ColorOverlay { color, blend_mode, opacity }) => {
let painted = premultiplied_gamma_channels(color.with_alpha(color.a() * (opacity / 100.) as f32));
@@ -955,7 +957,7 @@ fn composite_layers(
PiecePlace::Within => SharePart::Whole,
PiecePlace::IntoContent { over: false } => SharePart::IntoContent,
PiecePlace::IntoContent { over: true } => SharePart::IntoContentBeneathPartOver { opacity: OPACITY, fade },
PiecePlace::Beneath | PiecePlace::Through { .. } => continue,
PiecePlace::Beneath | PiecePlace::Through { .. } | PiecePlace::Backdrop => continue,
};
content = composite_in_share(&content, tinted, full_content, piece.blend_mode, part);
}
@@ -977,7 +979,8 @@ fn composite_layers(
PiecePlace::Beneath => tinted.clone(),
PiecePlace::Within if !holds_content => tinted.zip(full_content, |tinted, content| tinted.map(|channel| channel * content[3])),
PiecePlace::Through { .. } => tinted.zip(&through_shares(full_content, &content, OPACITY, fade), |tinted, share| tinted.map(|channel| channel * share)),
PiecePlace::Within | PiecePlace::IntoContent { .. } => continue,
// What lies beneath, for a backdrop the image doesn't have
PiecePlace::Within | PiecePlace::IntoContent { .. } | PiecePlace::Backdrop => continue,
};
stack = Some(stack_over(stack, upper));
}
@@ -34,6 +34,7 @@ log = { workspace = true }
num-traits = { workspace = true }
usvg = { workspace = true }
kurbo = { workspace = true }
linesweeper = { workspace = true }
vector-types = { workspace = true }
graphic-types = { workspace = true }
raster-kernels = { workspace = true }
@@ -1,6 +1,6 @@
//! What SVG can't express, which the GPU renders as images for an SVG to take, once the SVG is drawn.
//! An effect whose coverage SVG filters can't work out, like the shadows and glows shaped for PSD interop, goes in its filter as a map of that coverage, while the content keeps its own markup.
//! Content with an effect no filter can carry out at all is drawn as an image of it in place of its markup.
//! 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};
@@ -8,12 +8,16 @@ use crate::vello_scene_builder::{MAX_EFFECTS_AREA_PER_VIEWPORT_AREA, VelloSceneB
use core_types::Color;
use core_types::blending::BlendMode;
use core_types::color::SRGBA8;
use core_types::list::List;
use core_types::math::quad::Quad;
use core_types::transform::Footprint;
use glam::{DAffine2, DVec2, UVec2};
use graphic_types::Graphic;
use graphic_types::effects::EffectCapture;
use graphic_types::raster_types::{CPU, Raster};
use kurbo::{Affine, BezPath};
use std::sync::Arc;
use vello_gpu::peniko::Fill;
/// The most pixels across or down a map or image may have.
pub const MAX_DEFERRED_IMAGE_PIXELS: u32 = 8192;
@@ -183,13 +187,12 @@ pub fn substitute_effect_map(svg: &mut String, placement: &EffectMapPlacement, m
svg.replace_range(span, &image);
}
/// One item of content an SVG draws as an image the GPU renders of it, since its effects hold one SVG filters can't carry out.
/// Content an SVG draws as an image the GPU renders of it, since SVG can't carry it out as markup.
#[derive(Clone)]
pub struct DeferredImage {
/// Names the markers around the content's own markup in the SVG, which the image replaces.
pub id: u64,
/// The item with its effects, but without its opacity and blend mode, which the image takes instead.
pub content: Graphic,
pub content: DeferredContent,
pub render_params: RenderParams,
/// Maps the user space the markers sit in into the document.
pub user_to_document: DAffine2,
@@ -201,6 +204,67 @@ pub struct DeferredImage {
pub blend_mode: BlendMode,
}
/// What the GPU renders an image of for an SVG.
#[derive(Clone)]
pub enum DeferredContent {
/// An item with effects SVG filters can't carry out, but without its opacity and blend mode, which the image takes instead.
Item(Graphic),
/// What lies beneath content reading its backdrop, drawn in order, for which the markers stand around no markup.
/// The outline of the backdrop root's `clip`, a path in the document filled by the nonzero rule, cuts it as it's drawn, as it cuts what a copy of it would hold.
Beneath { clip: Option<BezPath>, drawn: Vec<DrawnContent> },
}
/// Content an SVG draws, which the GPU draws again into images of what lies beneath content drawn after it.
#[derive(Clone)]
pub struct DrawnContent {
items: Arc<dyn DrawnItems>,
/// How many of the items are drawn, since content drawn among them lies over only those before it.
pub(crate) count: usize,
/// Maps the user space the items are drawn in into the document.
user_to_document: DAffine2,
render_params: RenderParams,
}
impl DrawnContent {
/// The `items` drawn in a user space that `user_to_document` maps into the document, none of them drawn yet.
pub(crate) fn new(items: Arc<dyn DrawnItems>, user_to_document: DAffine2, render_params: &RenderParams) -> Self {
Self {
items,
count: 0,
user_to_document,
render_params: render_params.clone(),
}
}
}
/// A list of graphical content, or one item of it, whose first items the GPU can draw.
pub(crate) trait DrawnItems: Send + Sync {
/// Draws the first `count` items into a scene of the document, from the user space that `transform` maps into it.
fn draw_first(&self, count: usize, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams);
}
impl<T: Clone + Send + Sync + 'static> DrawnItems for List<T>
where
List<T>: Render,
{
fn draw_first(&self, count: usize, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) {
if count >= self.len() {
return self.render_to_vello(scene, transform, render_params);
}
let first: List<T> = (0..count).filter_map(|index| self.clone_item(index)).collect();
first.render_to_vello(scene, transform, render_params);
}
}
impl DrawnItems for Graphic {
fn draw_first(&self, count: usize, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) {
if count > 0 {
self.render_to_vello(scene, transform, render_params);
}
}
}
/// How an SVG draws the image the GPU rendered of an item of deferred content.
#[derive(Clone, Debug, PartialEq)]
pub struct DeferredImagePlacement {
@@ -230,6 +294,11 @@ pub(crate) fn image_markers(id: u64) -> (String, String) {
(format!("<!--deferred-image-{id}-->"), format!("<!--/deferred-image-{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-")
}
impl DeferredImage {
/// The image covering the part of the content's reach in a view that `document_to_view` maps the document into, spanning `view_size` pixels, with at most `max_pixels` across or down.
/// `None` if none of it lies in view.
@@ -252,8 +321,25 @@ impl DeferredImage {
/// Draws the content with its effects into a scene of the document, which the `layout` places in the image's pixels.
pub fn draw(&self, scene: &mut VelloSceneBuilder, layout: &DeferredImageLayout) {
self.content
.render_to_vello(scene, self.user_to_document, &image_render_params(&self.render_params, layout.document_to_pixels, layout.size));
let image_params = |render_params: &RenderParams| image_render_params(render_params, layout.document_to_pixels, layout.size);
match &self.content {
DeferredContent::Item(content) => content.render_to_vello(scene, self.user_to_document, &image_params(&self.render_params)),
DeferredContent::Beneath { clip, drawn } => {
// A clip rather than a layer, within which content reading what lies beneath it would find nothing
if let Some(clip) = clip {
scene.push_clip_layer(Fill::NonZero, Affine::IDENTITY, clip);
}
for drawn in drawn {
drawn.items.draw_first(drawn.count, scene, drawn.user_to_document, &image_params(&drawn.render_params));
}
if clip.is_some() {
scene.pop_layer();
}
}
}
}
}
@@ -2,6 +2,7 @@ pub mod convert_usvg_path;
pub mod deferred_image;
pub mod render_ext;
mod renderer;
mod svg_backdrop;
pub mod to_peniko;
pub mod vello_scene_builder;
File diff suppressed because it is too large. Load diff
@@ -98,7 +98,7 @@ pub(super) fn placed(mask: &Graphic, placement: DAffine2) -> Graphic {
/// Writes into `svg_defs` the masks for the effects in each of the `ranges`, given the markup of the graphics the effects draw with in order, and the content's `bounds` in the user space, which is the effects' own.
/// Returns the reference to each range's mask, which shows the content as much as all its masks together do.
pub(super) fn write_native_masks(svg_defs: &mut String, effects: &Effects, ranges: [Range<usize>; 2], paints: &[String], bounds: [DVec2; 2]) -> [Option<String>; 2] {
pub(super) fn write_native_masks<const N: usize>(svg_defs: &mut String, effects: &Effects, ranges: [Range<usize>; N], paints: &[String], bounds: [DVec2; 2]) -> [Option<String>; N] {
let length_scale = DVec2::ONE;
let region = svg_effects_region(effects, bounds, length_scale);
@@ -0,0 +1,406 @@
//! What lies beneath content in an SVG, which filters can't read, copied for content that reads it, like a background blur.
//! Per the W3C's Backdrop Root, the backdrop is everything drawn before the content since the innermost group that isolates it, or since the start of the render.
use crate::deferred_image::{self, DeferredContent, DeferredImage, DrawnContent, DrawnItems};
use crate::renderer::{RenderParams, SvgRender, SvgSegment, format_transform_matrix};
use core_types::blending::BlendMode;
use core_types::math::quad::Quad;
use core_types::uuid::generate_uuid;
use glam::{DAffine2, DVec2};
use graphic_types::effects::spans_along_axes;
use graphic_types::{EffectOperation, Effects};
use kurbo::{BezPath, PathEl, Shape};
use linesweeper::topology::Topology;
use raster_kernels::effect_kernels::NEGLIGIBLE_LENGTH;
use std::collections::HashMap;
use std::fmt::Write;
use std::sync::Arc;
/// A group an SVG render has open, where the content drawn so far lies beneath what's drawn next inside it.
#[derive(Clone)]
pub(crate) struct OpenGroup {
/// Where the group's opening tag starts among the render's segments.
pub tag_start: usize,
/// Where the group's content starts among the render's segments.
pub content_start: usize,
/// Whether the group isolates what's drawn inside it from what lies beneath it, as opacity, a filter, a mask, a clip path, or a blend mode does.
pub isolates: bool,
/// The group's `clip-path` attribute, which a copy of its content takes too.
pub clip_path: Option<String>,
/// Maps the user space of the group's content into the document, once its content begins.
pub user_to_document: Option<DAffine2>,
/// Whether a copy of what lies beneath, or an image of it, is drawn inside the group so far.
pub holds_backdrop: bool,
/// The content drawn directly inside the group so far, for the GPU to draw again in an image of what lies beneath content drawn after it.
pub drawn: Vec<DrawnContent>,
}
impl OpenGroup {
pub fn new(tag_start: usize, content_start: usize, isolates: bool, clip_path: Option<String>) -> Self {
Self {
tag_start,
content_start,
isolates,
clip_path,
user_to_document: None,
holds_backdrop: false,
drawn: Vec::new(),
}
}
}
/// The groups an SVG render has open, from the render's own start inward to the innermost.
#[derive(Clone)]
pub(crate) struct OpenGroups {
pub groups: Vec<OpenGroup>,
/// Whether the attributes of the tag being opened isolate its content.
pub opening_isolates: bool,
/// The `clip-path` attribute of the tag being opened.
pub opening_clip_path: Option<String>,
/// Whether the render draws a clipping base's clip.
pub clip: bool,
/// The shapes of the clip paths in the render's defs, paths in the document each filled by the nonzero rule, by the `clip-path` attribute referencing each.
/// Images of what lies beneath inside one are cut to the union of its shapes.
pub clip_shapes: HashMap<String, Vec<BezPath>>,
}
impl Default for OpenGroups {
fn default() -> Self {
Self {
groups: vec![OpenGroup::new(0, 0, true, None)],
opening_isolates: false,
opening_clip_path: None,
clip: false,
clip_shapes: HashMap::new(),
}
}
}
/// Whether an attribute makes the element carrying it an isolated group, which the content inside it blends within.
pub(crate) fn isolates(name: &str, value: &str) -> bool {
match name {
"opacity" | "filter" | "mask" | "clip-path" => true,
"style" => value.contains("mix-blend-mode") || value.contains("isolation"),
_ => false,
}
}
impl SvgRender {
/// Records the `items` drawn next, from the user space `user_to_document` maps into the document, in the innermost open group, returning where for [`Self::drew_items`].
/// Nothing is recorded where no image can replace markup, since no image of what lies beneath could.
pub(crate) fn record_drawn<T: DrawnItems + 'static>(&mut self, items: impl FnOnce() -> T, user_to_document: DAffine2, render_params: &RenderParams) -> Option<usize> {
if !self.images_replace_markup(render_params) {
return None;
}
let group = self.open_groups.groups.last_mut()?;
group.drawn.push(DrawnContent::new(Arc::new(items()), user_to_document, render_params));
Some(group.drawn.len() - 1)
}
/// Notes that the first `count` of the items recorded at `record` are drawn, in place of anything recorded after them while they were drawn.
pub(crate) fn drew_items(&mut self, record: Option<usize>, count: usize) {
let (Some(record), Some(group)) = (record, self.open_groups.groups.last_mut()) else { return };
group.drawn.truncate(record + 1);
if let Some(drawn) = group.drawn.get_mut(record) {
drawn.count = count;
}
}
/// Records the `shapes` of the clip path a `clip-path` attribute of the `reference` cuts by (see [`OpenGroups::clip_shapes`]), for images of what lies beneath inside it.
pub(crate) fn record_clip_shapes(&mut self, reference: &str, shapes: impl FnOnce() -> Vec<BezPath>, render_params: &RenderParams) {
if self.images_replace_markup(render_params) {
self.open_groups.clip_shapes.insert(reference.to_string(), shapes());
}
}
/// The outline of the clip path a `clip-path` attribute of the `reference` cuts by, its shapes united into one path filled by the nonzero rule,
/// or `None` if its shapes aren't recorded or can't be united.
fn clip_outline(&mut self, reference: &str) -> Option<BezPath> {
let shapes = self.open_groups.clip_shapes.get(reference)?;
if let [shape] = shapes.as_slice() {
return Some(shape.clone());
}
// United once, the outline is kept in place of the shapes, which are forgotten if they can't be
let outline = united_outline(shapes);
match &outline {
Some(outline) => _ = self.open_groups.clip_shapes.insert(reference.to_string(), vec![outline.clone()]),
None => _ = self.open_groups.clip_shapes.remove(reference),
}
outline
}
/// 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> {
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;
}
// 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];
let holds_backdrop = root_group.holds_backdrop;
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);
// 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) {
true => match &clip {
Some((reference, _)) => self.clip_outline(reference).map(Some),
None => Some(None),
},
false => None,
};
// 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) {
(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, None) => self.backdrop_markup_copies(root, copies_to_document, true, true),
}?;
// Every open group now holds it
for group in &mut self.open_groups.groups {
group.holds_backdrop = true;
}
let Some((clip_path, root_to_document)) = clip else { return Some(copies) };
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>"#))
}
/// 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.
/// Each is wrapped in a group with an ID for `<use>` copies, or with `repeats_markup`, copied as markup, keeping the viewport's canvases,
/// and without the markup showing what lies beneath earlier content if `leaves_out_backdrops`. O(segments drawn since the root).
fn backdrop_markup_copies(&mut self, root: usize, copies_to_document: DAffine2, repeats_markup: bool, leaves_out_backdrops: bool) -> Option<String> {
let current = self.open_groups.groups.len() - 1;
let kept = |segment: &&SvgSegment| !(leaves_out_backdrops && matches!(segment, SvgSegment::Backdrop(_)));
// From the innermost level out, so wrapping one level's content leaves the outer levels' positions as they are
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 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 };
let matrix = format_transform_matrix(copies_to_document.inverse() * user_to_document);
let attributes = if matrix.is_empty() { String::new() } else { format!(r#" transform="{matrix}""#) };
if repeats_markup {
let markup: String = self.svg[start..end].iter().filter(kept).map(SvgSegment::as_str).collect();
copies.push(format!("<g{attributes}>{markup}</g>"));
continue;
}
let id = format!("backdrop-{}", generate_uuid());
self.svg.insert(end, "</g>".into());
self.svg.insert(start, format!(r#"<g id="{id}">"#).into());
for inner in &mut self.open_groups.groups[level + 1..] {
inner.tag_start += 2;
inner.content_start += 2;
}
copies.push(format!(r##"<use href="#{id}"{attributes} />"##));
}
if copies.is_empty() {
return None;
}
copies.reverse();
Some(copies.concat())
}
/// The markers standing for an image the GPU renders of the content drawn since the backdrop `root`, cut by the outline of its `clip`, placed in the space `copies_to_document` maps into the document,
/// or `None` if there's none. It covers the `region` of the current user space and how far past the view the reading reaches, `read_reach` in the document.
fn backdrop_image(&mut self, root: usize, copies_to_document: DAffine2, clip: Option<BezPath>, region: [DVec2; 2], read_reach: f64, render_params: &RenderParams) -> Option<String> {
let drawn: Vec<DrawnContent> = self.open_groups.groups[root..].iter().flat_map(|group| &group.drawn).filter(|drawn| drawn.count > 0).cloned().collect();
if drawn.is_empty() {
return None;
}
let id = generate_uuid();
let bounds = (copies_to_document.inverse() * self.transform * Quad::from_box(region)).bounding_box();
self.deferred_images.push(DeferredImage {
id,
content: DeferredContent::Beneath { clip, drawn },
render_params: render_params.clone(),
user_to_document: copies_to_document,
bounds,
margin: self.ancestors_reach + read_reach,
opacity: 1.,
blend_mode: BlendMode::Normal,
});
let (opening, closing) = deferred_image::image_markers(id);
Some(format!("{opening}{closing}"))
}
}
/// 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> {
const EPSILON: f64 = 1e-5;
// A fill closes each subpath, which the sweep takes only explicitly
let closed: Vec<BezPath> = shapes.iter().map(closed_subpaths).collect();
if !closed.iter().all(BezPath::is_finite) {
return None;
}
let Some(bounds) = closed.iter().map(Shape::bounding_box).reduce(|first, second| first.union(second)) else {
return Some(BezPath::new());
};
// Far from the origin, the tolerance grows with the coordinates' magnitude, since the sweep can't resolve less
let magnitude = bounds.min_x().min(bounds.min_y()).abs().max(bounds.max_x().max(bounds.max_y()).abs());
let epsilon = EPSILON.max(magnitude * f64::EPSILON * 64.);
// Each shape alone is outlined first by what it fills, wound once around, so no shape's winding can cancel another's where they then unite
let mut outlines = BezPath::new();
for shape in &closed {
outlines.extend(swept_outline(shape, epsilon, |&winding| winding != 0)?);
}
swept_outline(&outlines, epsilon, |&winding| winding > 0)
}
/// The outline of where the `inside` test accepts the winding number of the closed `path`, wound once around what it holds, or `None` if the sweep fails.
fn swept_outline(path: &BezPath, epsilon: f64, inside: impl Fn(&i32) -> bool) -> Option<BezPath> {
let topology = Topology::<i32>::from_path(path, epsilon).ok()?;
Some(topology.contours(inside).contours().flat_map(|contour| contour.path.elements().iter().copied()).collect())
}
/// The `shape` with each of its subpaths closed, as a fill closes them.
pub(crate) fn closed_subpaths(shape: &BezPath) -> BezPath {
let mut closed = BezPath::new();
for &element in shape.elements() {
if matches!(element, PathEl::MoveTo(_)) && !matches!(closed.elements().last(), None | Some(PathEl::ClosePath)) {
closed.close_path();
}
closed.push(element);
}
if !matches!(closed.elements().last(), None | Some(PathEl::ClosePath)) {
closed.close_path();
}
closed
}
/// What lies beneath content with background blurs, in SVG.
pub(crate) struct SvgBackdrop {
/// Each copy of what lies beneath, blurred by one background blur, stacked in order within a group the mask cuts to the content.
pub markup: String,
/// The opening tag of the mask cutting it to the content's silhouette, which the content's own markup goes in once it's drawn.
pub mask_tag: String,
/// The content's extent, which cuts it instead where the content draws through canvases, since a mask draws no `<foreignObject>`.
pub content_bounds: [DVec2; 2],
}
/// What lies beneath content with background blurs, or `None` with nothing beneath it, given the content's `bounds` in the effects' `space`.
/// That space is placed in the current user space, or is the user space itself for `None`, and the markup lies in it.
/// The filters go in the render's defs (see [`SvgRender::backdrop_copy`] for what they blur).
/// A length in that space spans `pixels_per_length` screen pixels, across which a blur too slight to show is left out.
pub(crate) fn backdrop_markup(render: &mut SvgRender, effects: &Effects, bounds: [DVec2; 2], space: Option<DAffine2>, pixels_per_length: f64, render_params: &RenderParams) -> Option<SvgBackdrop> {
let blurs: Vec<(f64, bool, bool)> = (effects.operations())
.filter(|operation| !operation.changes_nothing())
.filter_map(|operation| match operation {
EffectOperation::BackgroundBlur { radius, box_blur, gamma } => Some((radius, box_blur, gamma)),
_ => None,
})
.collect();
if blurs.is_empty() {
return None;
}
// SVG has no box blur, so a box becomes the Gaussian of the same variance, which reads past the box's own reach
let sigma = |radius: f64, box_blur: bool| if box_blur { (radius * (radius + 1.) / 3.).sqrt() } else { radius };
let box_overreach: f64 = blurs
.iter()
.filter(|(_, box_blur, _)| *box_blur)
.map(|&(radius, ..)| (3. * sigma(radius, true) - radius - 1.).max(0.))
.sum();
// The blurs read as far past the content as the effects reach
let reach = effects.reach() + box_overreach;
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);
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 = match space.map(|space| format_transform_matrix(space.inverse())) {
Some(matrix) if !matrix.is_empty() => format!(r#"<g transform="{matrix}">{copy}</g>"#),
_ => copy,
};
let mut blurred = String::new();
for (radius, box_blur, gamma) in blurs {
if radius * pixels_per_length.max(1.) < NEGLIGIBLE_LENGTH {
blurred.push_str(&copy);
continue;
}
let sigma = sigma(radius, box_blur);
let space = if gamma { "sRGB" } else { "linearRGB" };
let filter_id = format!("background-blur-{}", generate_uuid());
write!(
render.svg_defs,
r#"<filter id="{filter_id}" filterUnits="userSpaceOnUse" {region}><feGaussianBlur stdDeviation="{sigma}" color-interpolation-filters="{space}" /></filter>"#
)
.unwrap();
write!(blurred, r#"<g filter="url(#{filter_id})">{copy}</g>"#).unwrap();
}
let mask_id = format!("backdrop-mask-{}", generate_uuid());
Some(SvgBackdrop {
markup: format!(r#"<g mask="url(#{mask_id})">{blurred}</g>"#),
mask_tag: format!(r#"<mask id="{mask_id}" mask-type="alpha" maskUnits="userSpaceOnUse" {region}>"#),
content_bounds: bounds,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn clip_shapes_with_coordinates_past_finite_ones_unite_into_no_outline() {
let square = kurbo::Rect::new(0., 0., 10., 10.).to_path(0.1);
let mut broken = BezPath::new();
broken.move_to((0., 0.));
broken.line_to((f64::NAN, 5.));
broken.line_to((5., f64::INFINITY));
// Images inside such a clip path give way to copies leaving held ones out, rather than drawing an outline that's wrong
assert!(united_outline(&[square.clone(), broken]).is_none());
assert!(united_outline(&[square.clone(), square]).is_some_and(|outline| (outline.area().abs() - 100.).abs() < 1e-6));
}
#[test]
fn thousands_of_overlapping_clip_shapes_wound_either_way_unite_quickly_into_what_they_cover() {
// A 100 by 50 grid of squares a unit and a half wide, a unit apart so neighbors overlap, every other one wound the other way
let squares: Vec<BezPath> = (0..5_000)
.map(|index| {
let corner = kurbo::Point::new((index % 100) as f64, (index / 100) as f64);
let square = kurbo::Rect::from_origin_size(corner, (1.5, 1.5)).to_path(0.1);
if index % 2 == 0 { square } else { square.reverse_subpaths() }
})
.collect();
// They unite into the rectangle they cover, none cancelling a neighbor wound against it
let start = std::time::Instant::now();
let outline = united_outline(&squares).expect("the squares unite");
let elapsed = start.elapsed();
assert!((outline.area().abs() - 100.5 * 50.5).abs() < 1e-6, "the union spans {}", outline.area().abs());
assert!(elapsed < std::time::Duration::from_secs(10), "uniting took {elapsed:?}");
}
}
@@ -47,6 +47,16 @@ pub struct VelloSceneBuilder<'a> {
effects_renderer: Option<&'a mut dyn EffectsRenderer>,
/// The coverage the next effects group drawn outputs in place of its result, for an SVG map of it.
effect_capture: Option<EffectCapture>,
/// How many placed drawings are open, each a backdrop root of its own, like a thumbnail of an atlas.
placed_depth: u32,
/// How many pixels past the scene's edges the content reading what lies beneath it reads, which a render of the scene grown by as much holds.
backdrop_apron: u32,
/// Each content drawn so far reading what lies beneath it, as its bounds in the scene and how many pixels past them it reads along each axis, for later content reading through it.
backdrop_readers: Vec<(Rect, DVec2)>,
/// The widest apron a render of the scene grown for content reading past its edges can have, up to which such content stops the drawing, or 0 to draw everything.
largest_apron: u32,
/// Whether the scene still draws, rather than only measuring the apron after content reading past its edges stopped it.
drawing: bool,
}
/// Renders the content of a scene's effects groups offscreen and carries out their effects, while the scene is drawn.
@@ -58,6 +68,7 @@ pub trait EffectsRenderer: Send {
/// returning one for each of the `layers` that `effects` carried out on it draw, with the mode it blends by.
/// `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 what effects relative to the content's extent take as their own.
/// `backdrop` is what lies beneath, for the effects that read it, with the placement of the textures' pixels in it.
/// With a `capture`, the only texture instead holds that effect's coverage, as black with it in alpha.
#[expect(clippy::too_many_arguments)]
fn render_effects(
@@ -70,10 +81,17 @@ pub trait EffectsRenderer: Send {
opacity: f32,
effect_to_pixels: DAffine2,
frame: Option<EffectFrame>,
backdrop: Option<(&wgpu::Texture, Affine)>,
capture: Option<EffectCapture>,
draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder),
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
) -> Vec<(wgpu::Texture, core_types::blending::BlendMode)>;
/// Renders a `scene` drawn so far, with the `images` it draws, into a premultiplied texture of its size, as the backdrop of what's drawn next.
/// `None` if it fails to render.
fn render_backdrop(&mut self, _scene: &vello_gpu::Scene, _images: &[SceneImage], _max_texture_size: u32) -> Option<wgpu::Texture> {
None
}
}
/// The pixels behind an image the scene draws.
@@ -127,7 +145,12 @@ impl GeneratorTile {
#[derive(Debug)]
enum Pushed {
Layer,
Clip,
/// With the path it clips to, given in the scene's space, so it can be pushed again in a scene continuing this one.
Clip {
path: BezPath,
transform: Affine,
fill_rule: Fill,
},
}
impl std::fmt::Debug for VelloSceneBuilder<'_> {
@@ -157,6 +180,11 @@ impl<'a> VelloSceneBuilder<'a> {
pushed: Vec::new(),
effects_renderer: None,
effect_capture: None,
placed_depth: 0,
backdrop_apron: 0,
backdrop_readers: Vec::new(),
largest_apron: 0,
drawing: true,
}
}
@@ -166,6 +194,18 @@ impl<'a> VelloSceneBuilder<'a> {
self
}
/// Stops drawing at the first content reading what lies beneath it past the scene's edges by at most `largest_apron` pixels, which a render grown by as much draws instead.
/// The scene then only measures how far past its edges the rest reads, for that render's apron.
pub fn stopping_for_an_apron_up_to(mut self, largest_apron: u32) -> Self {
self.largest_apron = largest_apron;
self
}
/// Whether the scene drew all its content, rather than stopping at content reading past its edges.
pub fn drew_everything(&self) -> bool {
self.drawing
}
/// Has the next effects group drawn output the coverage `capture` names in place of its result, leaving the groups drawn within it as they are.
pub fn capture_next_effects(&mut self, capture: EffectCapture) {
self.effect_capture = Some(capture);
@@ -188,6 +228,11 @@ impl<'a> VelloSceneBuilder<'a> {
self.max_texture_size
}
/// How many pixels past the scene's edges the content drawn so far that reads what lies beneath it reads, which the scene doesn't hold.
pub fn backdrop_apron(&self) -> u32 {
self.backdrop_apron
}
/// The finished Vello GPU scene and the images its external textures stand for, closing whatever layers and clips were left open.
pub fn finish(mut self) -> (vello_gpu::Scene, Vec<SceneImage>) {
if !self.pushed.is_empty() {
@@ -206,10 +251,13 @@ impl<'a> VelloSceneBuilder<'a> {
}
/// Draws what `draw` draws placed by `placement` within the view, as content with its own document space for its effects' lengths, like each thumbnail of an atlas.
/// It's a backdrop root of its own with nothing beneath it to read, as a run of effects drawn into another run's content is.
pub fn draw_placed(&mut self, placement: Affine, draw: impl FnOnce(&mut Self)) {
let outer_view = self.view;
self.view = outer_view * placement;
self.placed_depth += 1;
draw(self);
self.placed_depth -= 1;
self.view = outer_view;
}
@@ -228,6 +276,9 @@ impl<'a> VelloSceneBuilder<'a> {
/// Like [`Self::fill`] for a path, which it draws without copying.
pub fn fill_path<'b>(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, path: &BezPath) {
if !self.drawing {
return;
}
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
self.scene.set_transform(self.view * transform);
self.scene.set_fill_rule(fill_rule);
@@ -238,6 +289,9 @@ impl<'a> VelloSceneBuilder<'a> {
/// Strokes a shape given in the space of `transform`, with the brush placed by `transform * brush_transform`.
pub fn stroke<'b>(&mut self, stroke: &Stroke, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
if !self.drawing {
return;
}
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
self.scene.set_transform(self.view * transform);
self.scene.set_stroke(stroke.clone());
@@ -248,6 +302,9 @@ impl<'a> VelloSceneBuilder<'a> {
/// Fills the whole scene, which is how content without bounds (like a color or gradient layer) paints, with the brush placed by `brush_transform` in the space of the drawn content.
pub fn fill_viewport<'b>(&mut self, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>) {
if !self.drawing {
return;
}
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
self.scene.set_transform(Affine::IDENTITY);
self.scene.set_paint(paint);
@@ -257,38 +314,99 @@ impl<'a> VelloSceneBuilder<'a> {
/// Begins an isolated layer clipped to `clip`, given in the space of `transform`. Must be balanced by [`Self::pop_layer`].
pub fn push_layer(&mut self, fill_rule: Fill, blend_mode: impl Into<BlendMode>, alpha: f32, transform: Affine, clip: &impl Shape) {
self.scene.set_transform(self.view * transform);
self.scene.set_fill_rule(fill_rule);
self.scene
.push_layer(Some(&finite_path(&clip.to_path(SHAPE_TOLERANCE))), Some(blend_mode.into()), Some(alpha), None, None);
if self.drawing {
self.scene.set_transform(self.view * transform);
self.scene.set_fill_rule(fill_rule);
self.scene
.push_layer(Some(&finite_path(&clip.to_path(SHAPE_TOLERANCE))), Some(blend_mode.into()), Some(alpha), None, None);
}
self.pushed.push(Pushed::Layer);
}
/// Begins an isolated layer covering the whole scene, for content without bounds. Must be balanced by [`Self::pop_layer`].
pub fn push_viewport_layer(&mut self, blend_mode: impl Into<BlendMode>, alpha: f32) {
self.scene.push_layer(None, Some(blend_mode.into()), Some(alpha), None, None);
if self.drawing {
self.scene.push_layer(None, Some(blend_mode.into()), Some(alpha), None, None);
}
self.pushed.push(Pushed::Layer);
}
/// Clips the content that follows to `clip`, given in the space of `transform`, without isolating it. Must be balanced by [`Self::pop_layer`].
pub fn push_clip_layer(&mut self, fill_rule: Fill, transform: Affine, clip: &impl Shape) {
self.scene.set_transform(self.view * transform);
self.scene.set_fill_rule(fill_rule);
self.scene.push_clip_path(&finite_path(&clip.to_path(SHAPE_TOLERANCE)));
self.pushed.push(Pushed::Clip);
// The path is kept to begin the clip again after a render of the scene so far, copied only if it had to be made finite
let path = clip.to_path(SHAPE_TOLERANCE);
let finite = match finite_path(&path) {
Cow::Owned(finite) => Some(finite),
Cow::Borrowed(_) => None,
};
let (path, transform) = (finite.unwrap_or(path), self.view * transform);
if self.drawing {
self.scene.set_transform(transform);
self.scene.set_fill_rule(fill_rule);
self.scene.push_clip_path(&path);
}
self.pushed.push(Pushed::Clip { path, transform, fill_rule });
}
/// Ends the most recent layer or clip.
pub fn pop_layer(&mut self) {
match self.pushed.pop() {
Some(Pushed::Layer) => self.scene.pop_layer(),
Some(Pushed::Clip) => self.scene.pop_clip(),
Some(Pushed::Layer) if self.drawing => self.scene.pop_layer(),
Some(Pushed::Clip { .. }) if self.drawing => self.scene.pop_clip(),
Some(_) => {}
None => log::error!("A scene ends a layer or clip it never began"),
}
}
/// What's drawn so far, which lies beneath what's drawn next, in a premultiplied texture the size of the scene.
/// The scene is rendered so far and continues from an image of that render. `None` where content has nothing beneath it to read, or once the scene stopped drawing.
pub fn backdrop(&mut self) -> Option<wgpu::Texture> {
if !self.drawing || !self.backdrop_readable() {
return None;
}
let renderer = self.effects_renderer.as_deref_mut()?;
// The clips end for the render, then begin again in the scene continuing it
self.pushed.iter().for_each(|_| self.scene.pop_clip());
let rendered = renderer.render_backdrop(&self.scene, &self.images, self.max_texture_size);
if rendered.is_some() {
self.scene.reset();
self.images.clear();
self.image_ids.clear();
}
let backdrop = rendered.inspect(|backdrop| {
self.images.push(SceneImage::Rendered(backdrop.clone()));
let area = Rect::new(0., 0., backdrop.width() as f64, backdrop.height() as f64);
self.scene.set_transform(Affine::IDENTITY);
self.scene.set_paint(PaintType::Image(Image {
image: ImageSource::external_texture(TextureId(0), TextureRegion::Full, true),
sampler: peniko::ImageSampler::new(),
}));
self.scene.set_paint_transform(Affine::IDENTITY);
self.scene.fill_rect(&area);
});
for pushed in &self.pushed {
if let Pushed::Clip { path, transform, fill_rule } = pushed {
self.scene.set_transform(*transform);
self.scene.set_fill_rule(*fill_rule);
self.scene.push_clip_path(path);
}
}
backdrop
}
/// Whether content drawn now has what lies beneath it to read, which it hasn't within an isolated layer, where what lies beneath is only the part inside the layer,
/// within a placed drawing, where the content lies over nothing of its own, or without a renderer.
fn backdrop_readable(&self) -> bool {
self.placed_depth == 0 && !self.pushed.iter().any(|pushed| matches!(pushed, Pushed::Layer)) && self.effects_renderer.is_some()
}
/// Draws an image's rectangle of pixels, from the origin to its width and height, placed by `transform`.
pub fn draw_image(&mut self, image: &peniko::ImageBrush, transform: Affine) {
if !self.drawing {
return;
}
let Some((source, texture_to_image, texture_size)) = self.image_source(SceneImage::Pixels(image.image.clone())) else {
return;
};
@@ -297,6 +415,9 @@ impl<'a> VelloSceneBuilder<'a> {
/// Draws a CPU raster's rectangle of pixels with `adjustments` carried out on them, from the origin to its width and height, placed by `transform`.
pub fn draw_raster(&mut self, raster: Raster<CPU>, adjustments: Vec<Adjustment>, sampler: peniko::ImageSampler, transform: Affine) {
if !self.drawing {
return;
}
let Some((source, texture_to_image, texture_size)) = self.image_source(SceneImage::Raster { raster, adjustments }) else {
return;
};
@@ -305,6 +426,9 @@ impl<'a> VelloSceneBuilder<'a> {
/// Draws a GPU texture's rectangle of pixels, from the origin to its width and height, placed by `transform`.
pub fn draw_texture(&mut self, texture: Texture, sampler: peniko::ImageSampler, transform: Affine) {
if !self.drawing {
return;
}
let Some((source, texture_to_image, texture_size)) = self.image_source(SceneImage::Texture(texture)) else {
return;
};
@@ -317,7 +441,7 @@ impl<'a> VelloSceneBuilder<'a> {
let local_to_device = self.view * transform;
let [a, b, c, d, _, _] = local_to_device.as_coeffs();
let determinant = a * d - b * c;
if !determinant.is_normal() {
if !self.drawing || !determinant.is_normal() {
return;
}
@@ -409,9 +533,12 @@ impl<'a> VelloSceneBuilder<'a> {
let layers = EffectLayers::plan(effects, blend_mode, fill, layered);
// The texture follows the viewport's axes if the effect space only turns and evenly scales, or else its own axes, scaled evenly to keep every direction's detail.
// A box blur or a minimum or maximum, whose square neighborhoods aren't round, turns with its space only along that space's axes.
// A box blur (of the content or what lies beneath it) or a minimum or maximum, whose square neighborhoods aren't round, turns with its space only along that space's axes.
let has_square_kernel = effects.operations().any(|operation| {
let square = matches!(operation, EffectOperation::Blur { box_blur: true, .. } | EffectOperation::MinimumMaximum { .. });
let square = matches!(
operation,
EffectOperation::Blur { box_blur: true, .. } | EffectOperation::BackgroundBlur { box_blur: true, .. } | EffectOperation::MinimumMaximum { .. }
);
square && !operation.changes_nothing()
});
let follows_viewport = is_similarity(effect_to_device.matrix2) && (!has_square_kernel || is_axis_aligned(effect_to_device.matrix2));
@@ -483,16 +610,61 @@ impl<'a> VelloSceneBuilder<'a> {
let size = UVec2::new(size_along(region.width()), size_along(region.height()));
let origin = region.origin().to_vec2();
// 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 {
// 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;
let backdrop_reach: DVec2 = readers
.map(|operation| match operation {
graphic_types::EffectOperation::BackgroundBlur { box_blur: true, .. } => operation.reach() * (linear.abs() * DVec2::ONE),
_ => DVec2::splat(operation.reach() * largest_stretch(linear)),
})
.sum();
// The content in view reads what lies beneath only within its backdrop readers' reach, however far past the view the region extends
let region_in_device = Affine::new(frame_to_device.to_cols_array()).transform_rect_bbox(region);
let mut read_region = region_in_device.intersect(viewport.inflate(backdrop_reach.x, backdrop_reach.y));
// Content farther from the view than its backdrop reach needs no apron of its own, though later content reading through it may
if read_region.width() > 0. && read_region.height() > 0. {
// Where it reads earlier content reading what lies beneath, it reads what that content read too, from the latest back. O(readers drawn so far).
for &(earlier_bounds, earlier_reach) in self.backdrop_readers.iter().rev() {
let overlap = earlier_bounds.intersect(read_region);
if overlap.width() > 0. && overlap.height() > 0. {
read_region = read_region.union(overlap.inflate(earlier_reach.x, earlier_reach.y));
}
}
let past_edges = (-read_region.x0).max(-read_region.y0).max(read_region.x1 - viewport.x1).max(read_region.y1 - viewport.y1);
self.backdrop_apron = self.backdrop_apron.max(past_edges.max(0.).ceil() as u32);
}
self.backdrop_readers.extend(bounds.map(|bounds| (self.view.transform_rect_bbox(bounds), backdrop_reach)));
}
// Content reading past the edges by no more than a grown render holds stops the drawing, leaving all of it to that render
if (1..=self.largest_apron).contains(&self.backdrop_apron) {
self.drawing = false;
}
if !self.drawing {
return;
}
let backdrop = reads_backdrop.then(|| self.backdrop()).flatten();
let texture_to_device = Affine::new(frame_to_device.to_cols_array()) * Affine::translate(origin) * Affine::scale(1. / resolution);
let frame_to_pixels = Affine::scale(resolution) * Affine::translate(-origin);
let content_view = frame_to_pixels * document_to_frame;
let effect_to_pixels = DAffine2::from_cols_array(&content_view.as_coeffs()) * effect_space;
let effect_frame = effect_frame.map(|frame| frame.placed(DAffine2::from_cols_array(&frame_to_pixels.as_coeffs())));
let Some(renderer) = self.effects_renderer.as_deref_mut() else { return };
let results = renderer.render_effects(size, content_view, effects, &layers, fill, opacity, effect_to_pixels, effect_frame, capture, draw_paint, draw);
let backdrop = backdrop.as_ref().map(|backdrop| (backdrop, texture_to_device));
let results = renderer.render_effects(size, content_view, effects, &layers, fill, opacity, effect_to_pixels, effect_frame, backdrop, capture, draw_paint, draw);
// Draw each layer where the content was, blended onto what lies beneath, except a captured coverage, which is drawn as it is
let area = Rect::new(0., 0., size.x as f64, size.y as f64);
let texture_to_device = Affine::new(frame_to_device.to_cols_array()) * Affine::translate(origin) * Affine::scale(1. / resolution);
for (texture, blend_mode) in results {
let isolated = capture.is_none() && (opacity < 1. || blend_mode != core_types::blending::BlendMode::Normal);
if isolated {
@@ -15,6 +15,7 @@ use raster_kernels::effect_kernels::{BlurKernel, MAX_DIRECT_BOX_RADIUS, NEGLIGIB
use raster_kernels::resample_kernels::MotionBlurShear;
use std::collections::HashMap;
use std::sync::{Mutex, PoisonError};
use vello_gpu::kurbo::Affine;
use wgpu::util::DeviceExt;
mod filters;
@@ -69,6 +70,20 @@ impl Default for Parameters {
}
}
impl Parameters {
/// The parameters placing a pass's pixels in the scene's backdrop by `placement`, laid out as the shader's `backdrop_point` reads them.
fn placed_in_backdrop(placement: Affine) -> Self {
let [a, b, c, d, x, y] = placement.as_coeffs().map(|coefficient| coefficient as f32);
Self {
step: [a, b],
offset: [c, d],
values: [x, y, 0., 0.],
..Default::default()
}
}
}
/// The kernel's taps for a texture halved `levels` times, each the distance and weight of a symmetric pair of taps that sample between two texels.
fn kernel_taps(kernel: BlurKernel, levels: u32) -> Vec<[f32; 4]> {
let weights = kernel.weights(levels);
@@ -249,6 +264,7 @@ impl EffectPasses {
/// `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.
/// `backdrop` is what lies beneath, for the effects that read it, with the placement of the content texture's pixels in it.
/// With a `capture`, the only result is instead that effect's coverage, as black with it in alpha, or the share [`EffectCapture::THROUGH_MASK`] names.
#[expect(clippy::too_many_arguments)]
pub(crate) fn apply(
@@ -264,6 +280,7 @@ impl EffectPasses {
effect_to_pixels: DAffine2,
frame: Option<EffectFrame>,
paints: &[wgpu::Texture],
backdrop: Option<(&wgpu::Texture, Affine)>,
capture: Option<EffectCapture>,
) -> Vec<(wgpu::Texture, BlendMode)> {
let mut recorder = PassRecorder {
@@ -287,6 +304,8 @@ impl EffectPasses {
let mut pieces: HashMap<EffectCapture, wgpu::Texture> = HashMap::new();
// How much the trailing masks together show of each finished layer
let mut layer_fade: Option<wgpu::Texture> = None;
// How strongly all the masks together show the content, which they show what lies beneath it by too
let mut masks_strength: Option<wgpu::Texture> = None;
// A captured coverage ends the passes in place of the effects' result, once the content's layer is finished if its knockout or share depends on that
let mut captured: Option<wgpu::Texture> = None;
@@ -715,6 +734,29 @@ impl EffectPasses {
}
recorder.textures.release(height);
}
// What lies beneath, blurred, is always a piece at the bottom of the content's own layer
EffectOperation::BackgroundBlur { radius, box_blur, gamma } => {
let Some((backdrop, placement)) = backdrop else { continue };
let parameters = Parameters::placed_in_backdrop(placement);
let mut seen = recorder.run("sample_backdrop", WORKING_FORMAT, recorder.size, backdrop, None, None, parameters);
let radius = radius * length_scale;
if box_blur && radius > MAX_DIRECT_BOX_RADIUS {
// Past the widest box blurred directly, a box sums running sums at the full radius everywhere, exact as the content's box blur is
let every_pixel = Parameters { color: [1.; 4], ..Default::default() };
let full_radius = recorder.run("flood", COVERAGE_FORMAT, recorder.size, &seen, None, None, every_pixel);
let mut blurred = None;
recorder.masked_box_blur(&seen, &mut blurred, &mut None, &full_radius, DVec2::splat(radius), !gamma, true);
recorder.textures.release(full_radius);
if let Some(blurred) = blurred {
recorder.textures.release(std::mem::replace(&mut seen, blurred));
}
} else if radius >= NEGLIGIBLE_LENGTH {
let kernel = if box_blur { BlurKernel::Box { radius } } else { BlurKernel::Gaussian { sigma: radius } };
seen = recorder.blur(seen, kernel, !gamma);
}
pieces.insert(piece(0), seen);
}
EffectOperation::PaintOverlay { blend_mode, opacity, .. } => {
let Some(paint) = paints.next() else { continue };
let painted = recorder.scale(paint, (opacity / 100.) as f32);
@@ -736,12 +778,24 @@ impl EffectPasses {
let strength = recorder.mask_strength(mask, mode, density, mask_feather_sigma(feather) * length_scale, invert);
capture_plane(&mut recorder, 0, &strength, false);
// Trailing masks fade every finished layer, what lies beneath in the content's own layer included, so only the others fade it here
if layers.trailing_masks.contains(&index) {
layer_fade = Some(recorder.faded_together(layer_fade.take(), strength));
} else {
recorder.merge_beneath(content, &mut full, &mut filled, beneath.take());
recorder.fade_by(content, &mut full, &mut filled, &strength);
recorder.textures.release(strength);
masks_strength = match (backdrop.is_some(), masks_strength.take()) {
(false, _) => {
recorder.textures.release(strength);
None
}
(true, None) => Some(strength),
(true, Some(previous)) => {
let combined = recorder.run("apply_mask", COVERAGE_FORMAT, recorder.size, &previous, Some(&strength), None, Parameters::default());
[previous, strength].into_iter().for_each(|texture| recorder.textures.release(texture));
Some(combined)
}
};
}
}
EffectOperation::Feather { distance } => {
@@ -953,7 +1007,7 @@ impl EffectPasses {
}
}
if let Some(captured) = captured.take_if(|_| !capture_needs_content_layer) {
let textures = [full, filled, beneath, layer_fade].into_iter().flatten().chain(pieces.into_values());
let textures = [full, filled, beneath, layer_fade, masks_strength].into_iter().flatten().chain(pieces.into_values());
textures.for_each(|texture| recorder.textures.release(texture));
queue.submit([recorder.encoder.finish()]);
return vec![(captured, BlendMode::Normal)];
@@ -962,7 +1016,7 @@ impl EffectPasses {
// A coverage the passes never reached, like that of a band too thin to draw at this resolution, covers nothing
if capture.is_some_and(|capture| capture != EffectCapture::THROUGH_MASK) && captured.is_none() {
let empty = recorder.scale(full.as_ref().unwrap_or(content), 0.);
let textures = [full, filled, beneath, layer_fade].into_iter().flatten().chain(pieces.into_values());
let textures = [full, filled, beneath, layer_fade, masks_strength].into_iter().flatten().chain(pieces.into_values());
textures.for_each(|texture| recorder.textures.release(texture));
queue.submit([recorder.encoder.finish()]);
return vec![(empty, BlendMode::Normal)];
@@ -995,7 +1049,7 @@ impl EffectPasses {
PiecePlace::Within => 0.,
PiecePlace::IntoContent { over: false } => 1.,
PiecePlace::IntoContent { over: true } => 2.,
PiecePlace::Beneath | PiecePlace::Through { .. } => continue,
PiecePlace::Beneath | PiecePlace::Through { .. } | PiecePlace::Backdrop => continue,
};
let Some(tinted) = pieces.get(&piece.capture) else { continue };
let parameters = Parameters {
@@ -1031,7 +1085,10 @@ impl EffectPasses {
// A coverage too small to draw, like an outline's band at a far zoom, covers nothing
_ => recorder.run("flood", WORKING_FORMAT, recorder.size, full_content, None, None, Parameters::default()),
};
let textures = [full, Some(content_image), beneath, content_with_fade, layer_fade].into_iter().flatten().chain(pieces.into_values());
let textures = [full, Some(content_image), beneath, content_with_fade, layer_fade, masks_strength]
.into_iter()
.flatten()
.chain(pieces.into_values());
textures.for_each(|texture| recorder.textures.release(texture));
queue.submit([recorder.encoder.finish()]);
return vec![(output, BlendMode::Normal)];
@@ -1057,6 +1114,7 @@ impl EffectPasses {
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 };
let mut backdrop_stack: Option<wgpu::Texture> = None;
for part in &layer.parts {
let LayerPart::Piece(part_piece) = part else { continue };
@@ -1083,6 +1141,12 @@ impl EffectPasses {
};
recorder.run("through_mask", WORKING_FORMAT, recorder.size, tinted, Some(content_image), Some(fading_content), parameters)
}),
PiecePlace::Backdrop => {
if let Some(tinted) = pieces.remove(&part_piece.capture) {
backdrop_stack = Some(recorder.stack_over(backdrop_stack, tinted));
}
continue;
}
PiecePlace::Within | PiecePlace::IntoContent { .. } => continue,
};
if let Some(upper) = upper {
@@ -1090,13 +1154,26 @@ impl EffectPasses {
}
}
// What lies beneath, filtered and cut to the content's own silhouette before its effects and by its masks, goes beneath everything else in the layer
let backdrop_stack = backdrop_stack.map(|backdrop_stack| {
let cut = recorder.run("mask_within", WORKING_FORMAT, recorder.size, &backdrop_stack, None, Some(content), Parameters::default());
recorder.textures.release(backdrop_stack);
let Some(strength) = &masks_strength else { return cut };
let masked = recorder.run("apply_mask", WORKING_FORMAT, recorder.size, &cut, Some(strength), None, Parameters::default());
recorder.textures.release(cut);
masked
});
let image = match (holds_content, read_after) {
(true, true) => content_image.as_ref().map(|image| recorder.scale(image, 1.)),
(true, false) => content_image.take(),
(false, _) => None,
};
let Some(mut result) = image.map(|image| recorder.stack_over(stack.take(), image)).or(stack) else {
continue;
let result = image.map(|image| recorder.stack_over(stack.take(), image)).or(stack);
let mut result = match (result, backdrop_stack) {
(Some(result), backdrop_stack) => recorder.stack_over(backdrop_stack, result),
(None, Some(backdrop_stack)) => backdrop_stack,
(None, None) => continue,
};
if let Some(fade) = &layer_fade {
let faded = recorder.run("apply_mask", WORKING_FORMAT, recorder.size, &result, Some(fade), None, Parameters::default());
@@ -1105,7 +1182,10 @@ impl EffectPasses {
results.push((result, layer.blend_mode));
}
let textures = [full, content_image, beneath, content_with_fade, layer_fade].into_iter().flatten().chain(pieces.into_values());
let textures = [full, content_image, beneath, content_with_fade, layer_fade, masks_strength]
.into_iter()
.flatten()
.chain(pieces.into_values());
textures.for_each(|texture| recorder.textures.release(texture));
queue.submit([recorder.encoder.finish()]);
results
@@ -2021,7 +2101,7 @@ mod tests {
let apply = |textures: &mut EffectTextures, effects: &Effects| {
textures.drawn_passes.clear();
let layers = EffectLayers::plan(effects, BlendMode::Normal, 1., false);
let results = passes.apply(&context.device, &queue, textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None);
let results = passes.apply(&context.device, &queue, textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
results.into_iter().for_each(|(result, _)| textures.release(result));
};
let draw = |textures: &mut EffectTextures| {
@@ -2043,7 +2123,7 @@ mod tests {
textures.drawn_passes.clear();
let effects = Effects::from_operations(operations);
let layers = EffectLayers::plan(&effects, BlendMode::Normal, fill, false);
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None);
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None, None);
results.into_iter().for_each(|(result, _)| textures.release(result));
textures.drawn_passes.clone()
};
@@ -2087,7 +2167,7 @@ mod tests {
let mut drawn = |layered: bool| {
textures.drawn_passes.clear();
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., layered);
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None);
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
results.into_iter().for_each(|(result, _)| textures.release(result));
textures.drawn_passes.clone()
};
@@ -2109,7 +2189,7 @@ mod tests {
let content = textures.acquire(&context.device, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
let queue = context.queue.lock();
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false);
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None);
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
results.into_iter().for_each(|(result, _)| textures.release(result));
let drawn = |label: &str| textures.drawn_passes.iter().filter(|&&drawn| drawn == label).count();
@@ -3,9 +3,9 @@
struct Parameters {
// Converts a target pixel's position into the normalized coordinates the inputs are sampled at
target_to_uv: vec2<f32>,
// One step along the axis a kernel runs, in normalized coordinates
// One step along the axis a kernel runs, in normalized coordinates, or values described where a pass reads them
step: vec2<f32>,
// How far a silhouette is cast, in normalized coordinates
// How far a silhouette is cast, in normalized coordinates, or values described where a pass reads them
offset: vec2<f32>,
// A pass's scalar setting, like a scale factor, fill, opacity, or knockout cover, described where it reads it
amount: f32,
@@ -680,6 +680,17 @@ fn flood(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
return parameters.color;
}
// Where a pixel at `position` lands in the scene's backdrop, in its pixels, placed by the linear map with the columns `step` and `offset`, then moved by `values.xy`
fn backdrop_point(position: vec2<f32>) -> vec2<f32> {
return parameters.values.xy + mat2x2<f32>(parameters.step, parameters.offset) * position;
}
// What lies beneath the content, sampled from the scene's backdrop (`source`) where each pixel lands
@fragment
fn sample_backdrop(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
return textureSampleLevel(source, linear_sampler, backdrop_point(position.xy) / vec2<f32>(textureDimensions(source)), 0.);
}
// A tinted image cut to the full-strength `content`, for a piece within the content drawn in a layer of its own
@fragment
fn mask_within(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
@@ -162,7 +162,7 @@ impl VelloRenderer {
queue,
};
let (scene, images) = scene.finish();
if let Err(error) = context.submit(&scene, images, max_texture_size, target, TargetAlpha::Straight) {
if let Err(error) = context.submit(&scene, images, max_texture_size, target, TargetAlpha::Straight, true) {
log::error!("Vello GPU failed to render: {error}");
clear(device, queue, target);
}
@@ -254,24 +254,86 @@ impl RenderContext<'_> {
/// Renders the scene `draw` draws into `target`, a texture of `size`, in a single Vello GPU render.
fn render_once(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, target: &wgpu::Texture, target_alpha: TargetAlpha) -> Result<(), RenderError> {
let (width, height) = (size.x as u16, size.y as u16);
let max_texture_size = self.device.limits().max_texture_dimension_2d;
let max_size = max_texture_size.min(u16::MAX as u32);
let (mut scene, mut images, apron) = self.draw_scene(draw, view, size, max_texture_size, largest_apron(size, max_size));
// Draw the scene for this render's size and placement, which renders its effects groups as they're drawn
let mut scene = self.canvas.spare_scenes.pop().unwrap_or_else(|| vello_gpu::Scene::new(width, height));
scene.reset_and_resize(width, height);
let mut builder = VelloSceneBuilder::from_vello(scene, view, max_texture_size).with_effects_renderer(self);
draw(&mut builder);
let (scene, images) = builder.finish();
// Content reading what lies beneath it past the scene's edges stops its drawing for one grown by as much, of which the target takes the middle
if let Some(apron) = apron
&& let Some(grown_size) = grown_render_size(size, apron, max_size)
{
self.discard_scene(scene, images);
let grown_view = Affine::translate((apron as f64, apron as f64)) * view;
let (scene, images, _) = self.draw_scene(draw, grown_view, grown_size, max_texture_size, 0);
let rendered = self.submit(&scene, images, max_texture_size, target, target_alpha);
let grown_target = create_texture(
self.device,
"vello_gpu_grown_target",
grown_size,
target.format(),
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC,
);
let rendered = self.submit(&scene, images, max_texture_size, &grown_target, target_alpha, true);
self.canvas.spare_scenes.push(scene);
let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_gpu_grown_copy") });
encoder.copy_texture_to_texture(
wgpu::TexelCopyTextureInfo {
origin: wgpu::Origin3d { x: apron, y: apron, z: 0 },
..grown_target.as_image_copy()
},
target.as_image_copy(),
wgpu::Extent3d {
width: size.x,
height: size.y,
depth_or_array_layers: 1,
},
);
self.queue.submit([encoder.finish()]);
return rendered;
}
// Later content reading farther past the edges than a grown render holds leaves the scene to draw again, reading only what it holds
if apron.is_some() {
self.discard_scene(scene, images);
(scene, images, _) = self.draw_scene(draw, view, size, max_texture_size, 0);
}
let rendered = self.submit(&scene, images, max_texture_size, target, target_alpha, true);
// Once the render that draws it is submitted, the scene is free to reuse
self.canvas.spare_scenes.push(scene);
rendered
}
/// Draws the scene `draw` draws for a render of `size` placed by `view`, which renders its effects groups as they're drawn.
/// It stops at the first content reading what lies beneath it past its edges by at most `largest_apron` pixels, then returns how far past them all of it reads.
fn draw_scene(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, max_texture_size: u32, largest_apron: u32) -> (vello_gpu::Scene, Vec<SceneImage>, Option<u32>) {
let (width, height) = (size.x as u16, size.y as u16);
let mut scene = self.canvas.spare_scenes.pop().unwrap_or_else(|| vello_gpu::Scene::new(width, height));
scene.reset_and_resize(width, height);
let mut builder = VelloSceneBuilder::from_vello(scene, view, max_texture_size)
.with_effects_renderer(self)
.stopping_for_an_apron_up_to(largest_apron);
draw(&mut builder);
let apron = (!builder.drew_everything()).then(|| builder.backdrop_apron());
let (scene, images) = builder.finish();
(scene, images, apron)
}
/// Sets aside a drawn scene without rendering it, freeing the effects results it draws for reuse.
fn discard_scene(&mut self, scene: vello_gpu::Scene, images: Vec<SceneImage>) {
for image in images {
if let SceneImage::Rendered(texture) = image {
self.canvas.effect_textures.release(texture);
}
}
self.canvas.spare_scenes.push(scene);
}
/// Renders a drawn scene, with the images it draws, into `target`, a texture of the scene's size, in a single Vello GPU render.
fn submit(&mut self, scene: &vello_gpu::Scene, images: Vec<SceneImage>, max_texture_size: u32, target: &wgpu::Texture, target_alpha: TargetAlpha) -> Result<(), RenderError> {
/// The effects results it draws are freed for reuse after it, even if it fails when `release_failed`.
fn submit(&mut self, scene: &vello_gpu::Scene, images: Vec<SceneImage>, max_texture_size: u32, target: &wgpu::Texture, target_alpha: TargetAlpha, release_failed: bool) -> Result<(), RenderError> {
let device = self.device;
let (width, height) = (scene.width(), scene.height());
let size = UVec2::new(width as u32, height as u32);
@@ -350,10 +412,12 @@ impl RenderContext<'_> {
queue.submit([encoder.finish()]);
drop((gpu, queue));
// Once the render that draws them is submitted, its effects results are free to reuse
for image in images {
if let SceneImage::Rendered(texture) = image {
self.canvas.effect_textures.release(texture);
// Once the render that draws them is submitted, its effects results are free to reuse, unless a failed render leaves them still to draw
if rendered.is_ok() || release_failed {
for image in images {
if let SceneImage::Rendered(texture) = image {
self.canvas.effect_textures.release(texture);
}
}
}
@@ -376,6 +440,7 @@ impl EffectsRenderer for RenderContext<'_> {
opacity: f32,
effect_to_pixels: DAffine2,
frame: Option<graphic_types::resampling::EffectFrame>,
backdrop: Option<(&wgpu::Texture, Affine)>,
capture: Option<EffectCapture>,
draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder),
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
@@ -408,6 +473,7 @@ impl EffectsRenderer for RenderContext<'_> {
effect_to_pixels,
frame,
&paint_textures,
backdrop,
capture,
);
effect_textures.release(content_texture);
@@ -415,6 +481,31 @@ impl EffectsRenderer for RenderContext<'_> {
results
}
fn render_backdrop(&mut self, scene: &vello_gpu::Scene, images: &[SceneImage], max_texture_size: u32) -> Option<wgpu::Texture> {
let size = UVec2::new(scene.width() as u32, scene.height() as u32);
let backdrop = self.canvas.effect_textures.acquire(self.device, size, self.renderer.precise_format);
// A failed render leaves the scene to go on drawing what it drew, so the results it draws stay in use
match self.submit(scene, images.to_vec(), max_texture_size, &backdrop, TargetAlpha::Premultiplied, false) {
Ok(()) => Some(backdrop),
Err(error) => {
log::error!("Vello GPU failed to render what lies beneath content reading it: {error}");
self.canvas.effect_textures.release(backdrop);
None
}
}
}
}
/// The widest apron of pixels past each edge that a render of `size` can grow by and still fit a texture of `max_size`.
fn largest_apron(size: UVec2, max_size: u32) -> u32 {
max_size.saturating_sub(size.max_element()) / 2
}
/// The size of a render of `size` grown by an `apron` of pixels past each edge, or `None` without one or if it's too large for a texture of `max_size`.
fn grown_render_size(size: UVec2, apron: u32, max_size: u32) -> Option<UVec2> {
(apron > 0 && apron <= largest_apron(size, max_size)).then(|| size + UVec2::splat(2 * apron))
}
/// Leaves `target` transparent.
File diff suppressed because it is too large. Load diff
+38
View File
@@ -0,0 +1,38 @@
use core_types::list::Item;
use core_types::{Color, Ctx};
use graphic_types::raster_types::{CPU, GPU, Raster};
use graphic_types::{Effect, EffectOperation, Generator, Graphic, Vector, stamp_effect};
use vector_types::Gradient;
/// Blurs what lies beneath the input graphics within their shape, like frosted glass seen through them.
///
/// The content draws over the blur, hiding it where opaque. Lowering the content's fill reveals the blur at full strength, while a translucent paint shows it only as strongly as the paint covers.
#[node_macro::node(category("Raster: Effect"))]
fn background_blur<T>(
_: impl Ctx,
/// The content to see the blurred backdrop through.
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Generator)]
content: Item<T>,
/// How far the blur spreads each point of what lies beneath.
#[unit(" px")]
#[range]
#[hard(0..)]
#[soft(..100)]
#[default(10.)]
radius: Item<f64>,
/// Use a box kernel instead of a circular Gaussian kernel, which averages evenly and leaves boxy artifacts.
box_blur: Item<bool>,
/// Opt to incorrectly blend the colors in gamma space for compatibility with the results from other software.
gamma: Item<bool>,
) -> Item<T> {
let mut content = content;
stamp_effect(
&mut content,
Effect::new(&EffectOperation::BackgroundBlur {
radius: radius.into_element(),
box_blur: box_blur.into_element(),
gamma: gamma.into_element(),
}),
);
content
}
+1
View File
@@ -1,3 +1,4 @@
pub mod backdrop;
pub mod distortions;
pub mod effects;
pub mod filters;