Replace Color Overlay with a Paint Overlay effect that paints with any graphic

This commit is contained in:
Keavon Chambers committed 2026-10-30 20:22:17 -07:00
1 parent e6cb938ff9
commit 9bf8f2469d
14 files changed
+582 -141

No files matched your search

@@ -388,6 +388,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<Graphic>(x) => color_widget(default_info, ColorInput::default()),
// ============
// STRUCT TYPES
// ============
@@ -533,8 +533,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_core::raster::ChannelMixerNode",
],
},
// Color Overlay became Paint Overlay, whose paint input takes the old color input's value as a solid paint
NodeReplacement {
node: graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
node: graphene_std::raster_nodes::effects::paint_overlay::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::ColorOverlayNode",
"graphene_raster_nodes::generate_curves::ColorOverlayNode",
@@ -542,6 +543,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_core::raster::adjustments::ColorOverlayNode",
"raster_nodes::generate_curves::ColorOverlayNode",
"graphene_raster_nodes::blending_nodes::ColorOverlayNode",
"raster_nodes::blending_nodes::ColorOverlayNode",
],
},
NodeReplacement {
@@ -1272,6 +1274,10 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), under.clone(), &network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), over.clone(), &network_path);
}
if *new == graphene_std::raster_nodes::effects::paint_overlay::IDENTIFIER {
reset_default_display_name(document, node_id, &network_path, "Color Overlay");
}
}
}
}
@@ -2395,7 +2401,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
(graphene_std::artboard::create_artboard::BackgroundInput.into(), Color::WHITE),
(graphene_std::math_nodes::color_value::ColorInput.into(), Color::TRANSPARENT),
(graphene_std::raster_nodes::adjustments::black_and_white::TintInput.into(), Color::BLACK),
(graphene_std::raster_nodes::blending_nodes::color_overlay::ColorInput.into(), Color::BLACK),
];
for (parameter, fallback) in conversions {
if reference != DefinitionIdentifier::ProtoNode(parameter.node_identifier.clone()) {
@@ -3535,7 +3540,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
photo_filter::IDENTIFIER,
color_lookup::IDENTIFIER,
image_to_channels::IDENTIFIER,
graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
graphene_std::raster_nodes::effects::paint_overlay::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::mask::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::extend_image_to_bounds::IDENTIFIER,
@@ -1,5 +1,6 @@
//! Color adjustments as plain data holding their nodes' settings in the nodes' own units, decoded from effect rows, carried out by the kernels of the `raster-kernels` crate.
use crate::Graphic;
use crate::effects::{EffectKind, ParameterVisitor};
use core_types::Color;
use core_types::blending::BlendMode;
@@ -120,7 +121,7 @@ impl Adjustment {
Self::ColorBalance(_) => EffectKind::ColorBalance,
Self::PhotoFilter { .. } => EffectKind::PhotoFilter,
Self::ColorLookup { .. } => EffectKind::ColorLookup,
Self::ColorOverlay { .. } => EffectKind::ColorOverlay,
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
}
}
@@ -270,7 +271,12 @@ impl Adjustment {
}
Self::ColorLookup { lut_file } => visitor.parameter("lut_file", lut_file, Resource::default()),
Self::ColorOverlay { color, blend_mode, opacity } => {
visitor.parameter("color", color, Color::BLACK);
// Rides the row as the paint of the Paint Overlay node, which stamps it
let mut paint = Graphic::from(*color);
visitor.parameter("paint", &mut paint, Graphic::from(Color::BLACK));
if let Graphic::Color(paint) = paint {
*color = *paint.element();
}
visitor.parameter("blend_mode", blend_mode, BlendMode::default());
visitor.parameter("opacity", opacity, 100.);
}
@@ -2,13 +2,16 @@
//! Each row is an [`EffectKind`] whose parameters ride its item as attributes, read as their defaults when absent.
//! Each renderer decodes the rows into [`EffectOperation`]s and carries them out its own way, at the resolution of each render.
use crate::Graphic;
use crate::adjustment::Adjustment;
use core_types::ATTR_TRANSFORM;
use core_types::Color;
use core_types::blending::BlendMode;
use core_types::color::SRGBA8;
use core_types::graphene_hash::CacheHash;
use core_types::list::{ATTR_EFFECTS, Item, List};
use dyn_any::DynAny;
use glam::{DMat2, DVec2, DVec3};
use glam::{DAffine2, DMat2, DVec2, DVec3};
use std::fmt::Debug;
use vector_types::vector::style::StrokeAlign;
@@ -32,6 +35,8 @@ pub enum EffectKind {
Outline,
/// Lights the content as if raised from the surface or pressed into it, with highlights and shadows along its edges.
BevelAndEmboss,
/// Paints over the content within its silhouette, mixing with its colors by a blend mode. A solid color paint is the color overlay adjustment.
PaintOverlay,
// The adjustments, which change each color of the content on its own, as their nodes of the same names do
Desaturate,
GammaCorrection,
@@ -52,7 +57,6 @@ pub enum EffectKind {
ColorBalance,
PhotoFilter,
ColorLookup,
ColorOverlay,
}
impl std::fmt::Display for EffectKind {
@@ -66,6 +70,7 @@ impl std::fmt::Display for EffectKind {
Self::Satin => "Satin",
Self::Outline => "Outline",
Self::BevelAndEmboss => "Bevel & Emboss",
Self::PaintOverlay => "Paint Overlay",
Self::Desaturate => "Desaturate",
Self::GammaCorrection => "Gamma Correction",
Self::MakeOpaque => "Make Opaque",
@@ -85,7 +90,6 @@ impl std::fmt::Display for EffectKind {
Self::ColorBalance => "Color Balance",
Self::PhotoFilter => "Photo Filter",
Self::ColorLookup => "Color Lookup",
Self::ColorOverlay => "Color Overlay",
})
}
}
@@ -145,6 +149,29 @@ pub fn bevel_light(angle: f64, altitude: f64, lengths_to_target: DMat2) -> DVec3
(across * altitude.cos()).extend(altitude.sin())
}
/// An overlay's paint with its unit square fitted to `content_bounds`, the content's extent in the space it's drawn in, if it's a gradient or image without its own placement.
pub fn fitted_paint(paint: &Graphic, content_bounds: [DVec2; 2]) -> Option<Graphic> {
let unplaced = match paint {
Graphic::Gradient(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
Graphic::RasterCPU(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
Graphic::RasterGPU(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
_ => false,
};
if !unplaced {
return None;
}
let fit = DAffine2::from_translation(content_bounds[0]) * DAffine2::from_scale(content_bounds[1] - content_bounds[0]);
let mut paint = paint.clone();
match &mut paint {
Graphic::Gradient(item) => item.set_attribute(ATTR_TRANSFORM, fit),
Graphic::RasterCPU(item) => item.set_attribute(ATTR_TRANSFORM, fit),
Graphic::RasterGPU(item) => item.set_attribute(ATTR_TRANSFORM, fit),
_ => {}
}
Some(paint)
}
/// One image operation of an [`Effects`] list: an [`EffectKind`] plus its parameters, carried as attributes on the inner item.
/// Each parameter's attribute is named after the input of the node that stamps the kind. Attributes the kind doesn't take are ignored.
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
@@ -167,7 +194,20 @@ impl Effect {
pub fn operation(&self) -> EffectOperation {
let mut operation = EffectOperation::placeholder(self.kind());
operation.visit_parameters(&mut ReadParameters(&self.0));
operation
// A solid paint mixes the same into every pixel, so the renderers carry it out with the other adjustments
match operation {
EffectOperation::PaintOverlay {
paint: Graphic::Color(color),
blend_mode,
opacity,
} => EffectOperation::Adjustment(Adjustment::ColorOverlay {
color: *color.element(),
blend_mode,
opacity,
}),
operation => operation,
}
}
}
@@ -295,6 +335,14 @@ pub enum EffectOperation {
highlight_color: Color,
shadow_color: Color,
},
/// Paints over the content with a paint other than a solid color, since a solid one decodes into the color overlay adjustment instead.
PaintOverlay {
/// Placed in the space the content's item is, or fitted to the content's bounds if it's a gradient or image without its own placement.
paint: Graphic,
blend_mode: BlendMode,
/// Percent.
opacity: f64,
},
Adjustment(Adjustment),
}
@@ -314,6 +362,7 @@ impl EffectOperation {
Self::Satin { .. } => EffectKind::Satin,
Self::Outline { .. } => EffectKind::Outline,
Self::BevelAndEmboss { .. } => EffectKind::BevelAndEmboss,
Self::PaintOverlay { .. } => EffectKind::PaintOverlay,
Self::Adjustment(adjustment) => adjustment.kind(),
}
}
@@ -330,7 +379,7 @@ impl EffectOperation {
Self::Satin { offset, blur, .. } => offset.length() + 3. * blur.max(0.),
Self::Outline { weight, .. } => weight.max(0.),
Self::BevelAndEmboss { size, soften, .. } => size.max(0.) + 3. * (soften.max(0.) + bevel_smoothing(*size)),
Self::Adjustment(_) => 0.,
Self::PaintOverlay { .. } | Self::Adjustment(_) => 0.,
}
}
@@ -387,6 +436,11 @@ impl EffectOperation {
highlight_color: Color::TRANSPARENT,
shadow_color: Color::TRANSPARENT,
},
EffectKind::PaintOverlay => Self::PaintOverlay {
paint: Graphic::default(),
blend_mode: BlendMode::default(),
opacity: 0.,
},
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),
@@ -422,11 +476,6 @@ impl EffectOperation {
preserve_luminosity: false,
}),
EffectKind::ColorLookup => Self::Adjustment(Adjustment::ColorLookup { lut_file: Default::default() }),
EffectKind::ColorOverlay => Self::Adjustment(Adjustment::ColorOverlay {
color: Color::TRANSPARENT,
blend_mode: Default::default(),
opacity: 0.,
}),
}
}
@@ -487,6 +536,11 @@ impl EffectOperation {
visitor.parameter("highlight_color", highlight_color, Color::from(SRGBA8::new(0xff, 0xff, 0xff, 0xbf)));
visitor.parameter("shadow_color", shadow_color, Color::from(SRGBA8::new(0, 0, 0, 0xbf)));
}
Self::PaintOverlay { paint, blend_mode, opacity } => {
visitor.parameter("paint", paint, Graphic::from(Color::BLACK));
visitor.parameter("blend_mode", blend_mode, BlendMode::default());
visitor.parameter("opacity", opacity, 100.);
}
Self::Adjustment(adjustment) => adjustment.visit_parameters(visitor),
}
}
@@ -524,6 +578,7 @@ impl ParameterVisitor for ReadParameters<'_> {
#[cfg(test)]
mod tests {
use super::*;
use vector_types::{Gradient, GradientStop};
#[test]
fn rows_round_trip_their_operations_eliding_defaults() {
@@ -573,12 +628,43 @@ mod tests {
highlight_color: Color::YELLOW,
shadow_color: Color::BLUE,
},
EffectOperation::PaintOverlay {
paint: Graphic::from(Gradient::new([0., 1.].map(|position| GradientStop {
position,
midpoint: 0.5,
color: Color::from_rgbaf32_unchecked(position as f32, 0., 1., 1.),
}))),
blend_mode: BlendMode::Multiply,
opacity: 60.,
},
EffectOperation::Adjustment(Adjustment::ColorOverlay {
color: Color::GREEN,
blend_mode: BlendMode::Screen,
opacity: 100.,
}),
];
for operation in operations {
assert_eq!(Effect::new(&operation).operation(), operation);
}
// A solid paint decodes into the color overlay adjustment, which the Paint Overlay row also carries
let solid = EffectOperation::PaintOverlay {
paint: Graphic::from(Color::RED),
blend_mode: BlendMode::Normal,
opacity: 50.,
};
let solid_row = Effect::new(&solid);
assert_eq!(solid_row.kind(), EffectKind::PaintOverlay);
assert_eq!(
solid_row.operation(),
EffectOperation::Adjustment(Adjustment::ColorOverlay {
color: Color::RED,
blend_mode: BlendMode::Normal,
opacity: 50.,
})
);
let default_row = Effect::new(&EffectOperation::default_for(EffectKind::DropShadow));
assert_eq!(default_row.0.attributes().iter_any().count(), 0, "a default operation stamps no parameters");
}
@@ -606,7 +692,7 @@ mod tests {
ColorBalance,
PhotoFilter,
ColorLookup,
ColorOverlay,
PaintOverlay,
];
for kind in kinds {
let operation = EffectOperation::default_for(kind);
@@ -14,7 +14,7 @@ pub use vector_types;
pub use adjustment::Adjustment;
pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage};
pub use artboard::Artboard;
pub use effects::{BevelDirection, BevelStyle, Effect, EffectKind, EffectOperation, Effects, GlowSource, stamp_effect};
pub use effects::{BevelDirection, BevelStyle, Effect, EffectKind, EffectOperation, Effects, GlowSource, fitted_paint, stamp_effect};
pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector};
pub mod migrations {
@@ -3,6 +3,7 @@
use crate::{RasterKernel, Wgsl, gpu_params};
use core_types::Color;
use core_types::blending::BlendMode;
/// A color as the premultiplied, gamma-encoded channels the passes work with, carried in a [`Color`] to be passed to them.
pub fn premultiplied_gamma_channels(color: Color) -> Color {
@@ -244,3 +245,19 @@ impl RasterKernel for KeepEmpty {
Wgsl::function(include_str!("wgsl/effect_keep_empty.wgsl"))
}
}
gpu_params! {
/// The image (input 0) with a straight-alpha linear-light paint (input 1) mixed over its colors by a blend mode, as much as the paint covers and `opacity` lets it, keeping the image's alpha.
#[derive(Clone)]
pub struct PaintOverlay {
pub blend_mode: BlendMode,
pub opacity: f32,
}
}
impl RasterKernel for PaintOverlay {
const INPUTS: usize = 2;
fn wgsl() -> Wgsl {
Wgsl::function(format!("{}\n{}", include_str!("wgsl/blending.wgsl"), include_str!("wgsl/effect_paint_overlay.wgsl")))
}
}
@@ -0,0 +1,18 @@
// The blend modes work on straight linear colors, as they do for a solid color overlay
fn kernel(coord: vec2<i32>) -> vec4<f32> {
let parameters = params();
let image = input_0_load(coord);
let paint = input_1_load(coord);
if image.a <= 0. {
return vec4<f32>(0.);
}
if paint.a <= 0. {
return image;
}
let backdrop = vec4<f32>(srgb_to_linear(image.rgb / image.a), 1.);
let blended = apply_blend_mode(vec4<f32>(paint.rgb, 1.), backdrop, parameters.blend_mode);
let mixed = mix(backdrop.rgb, blended.rgb, parameters.opacity * paint.a);
return vec4<f32>(linear_to_srgb(mixed) * image.a, image.a);
}
+164 -34
View File
@@ -31,7 +31,7 @@ use graphic_types::vector_types::vector::style::{RenderMode, StrokeAlign, Stroke
use graphic_types::vector_types::vector::{
GeometryCache, Path, PlacedContours, contour_bezpaths, contours_bounding_box, contours_stroke_inclusive_bounding_box, edit_item_geometry, edit_list_row_geometry, no_paths,
};
use graphic_types::{Adjustment, Appearance, Artboard, BevelStyle, Cover, Coverage, Effects, FillAndStroke, Graphic, Vector};
use graphic_types::{Adjustment, Appearance, Artboard, BevelStyle, Cover, Coverage, EffectOperation, Effects, FillAndStroke, Graphic, Vector, fitted_paint};
use kurbo::{Affine, BezPath, Cap, Join, PathEl, Shape};
use num_traits::Zero;
use raster_kernels::adjustments::{adjust_color, adjusted_raster, leading_adjustments, preserves_alpha};
@@ -247,17 +247,45 @@ impl ItemCompositing<'_> {
}
}
/// Draws the content `draw` draws through the effects group, given the content's bounds in the scene's space.
/// Rendering a split scene calls `draw` again for each part.
fn draw_with_effects(&self, scene: &mut VelloSceneBuilder, bounds: impl FnOnce() -> RenderBoundingBox, mut draw: impl FnMut(&mut VelloSceneBuilder)) {
/// Draws the content `draw` draws through the effects group, given the content's bounds in the scene's space. Rendering a split scene calls `draw` again for each part.
/// `transform` maps the space the content's item is placed in, where the paint overlays' paints are placed too, into the scene's space.
fn draw_with_effects(
&self,
scene: &mut VelloSceneBuilder,
transform: DAffine2,
render_params: &RenderParams,
bounds: impl FnOnce() -> RenderBoundingBox,
mut draw: impl FnMut(&mut VelloSceneBuilder),
) {
let Some((effects, fill)) = self.effects else { return draw(scene) };
let bounds = match bounds() {
RenderBoundingBox::Rectangle([min, max]) => Some(kurbo::Rect::new(min.x, min.y, max.x, max.y)),
RenderBoundingBox::Rectangle(bounds) => Some(bounds),
RenderBoundingBox::Infinite => None,
RenderBoundingBox::None => return draw(scene),
};
scene.draw_effects(effects, fill, bounds, &mut draw);
// A paint fitted to the content's bounds is placed in the scene's space they're measured in
let paint_params = render_params.for_pattern();
let paints: Vec<(Graphic, DAffine2)> = effects
.operations()
.filter_map(|operation| match operation {
EffectOperation::PaintOverlay { paint, .. } => Some(paint),
_ => None,
})
.map(|paint| match bounds.and_then(|bounds| fitted_paint(&paint, bounds)) {
Some(fitted) => (fitted, DAffine2::IDENTITY),
None => (paint, transform),
})
.collect();
let mut draw_paint = |index: usize, scene: &mut VelloSceneBuilder| {
if let Some((paint, transform)) = paints.get(index) {
paint.render_to_vello(scene, *transform, &paint_params);
}
};
let bounds = bounds.map(|[min, max]| kurbo::Rect::new(min.x, min.y, max.x, max.y));
scene.draw_effects(effects, fill, bounds, &mut draw_paint, &mut draw);
}
/// The opacity for content drawn without the effects group, as SVG draws content its filter can't apply to.
@@ -303,13 +331,30 @@ impl ItemCompositing<'_> {
/// Writes the SVG filter carrying out the effects, if there are any to apply, given the content's bounds in the current user space.
/// Returns the reference for the `filter` attribute of a group wrapping the content, which also takes the item's opacity and blend mode.
fn svg_filter(&self, render: &mut SvgRender, bounds: impl FnOnce() -> RenderBoundingBox) -> Option<String> {
fn svg_filter(&self, render: &mut SvgRender, render_params: &RenderParams, bounds: impl FnOnce() -> RenderBoundingBox) -> Option<String> {
let (effects, fill) = self.effects?;
// Effects change nothing visible about content without edges, like a color or gradient layer filling everything
let RenderBoundingBox::Rectangle(bounds) = bounds() else { return None };
let id = write_svg_effects_filter(&mut render.svg_defs, effects, fill, bounds, render.transform, self.pixel_scale)?;
// The paint overlays' paints that aren't solid colors, drawn as markup in the user space, where the content's bounds fit those without a placement
let paint_params = render_params.for_pattern();
let paints: Vec<String> = effects
.operations()
.filter_map(|operation| match operation {
EffectOperation::PaintOverlay { paint, .. } => Some(paint),
_ => None,
})
.map(|paint| {
let paint = fitted_paint(&paint, bounds).unwrap_or(paint);
let mut paint_render = SvgRender::new();
paint_render.transform = render.transform;
paint.render_svg(&mut paint_render, &paint_params);
format!("<defs>{}</defs>{}", paint_render.svg_defs, paint_render.svg.to_svg_string())
})
.collect();
let id = write_svg_effects_filter(&mut render.svg_defs, effects, fill, bounds, render.transform, self.pixel_scale, &paints)?;
Some(format!("url(#{id})"))
}
}
@@ -487,6 +532,30 @@ impl SvgFilterPrimitives {
)
}
/// A paint's markup, drawn in the user space, as an image filling the `region` of it from its minimum to its maximum corner.
/// Filters take outside graphics only as images, which an embedded SVG document keeps portable to viewers that can't reference elements.
fn paint_image(&mut self, markup: &str, [min, max]: [DVec2; 2]) -> String {
use base64::Engine;
let size = max - min;
let document = format!(
r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:graphite="https://graphite.art" viewBox="{} {} {} {}" width="{}" height="{}" preserveAspectRatio="none">{markup}</svg>"#,
min.x, min.y, size.x, size.y, size.x, size.y
);
let href = format!("data:image/svg+xml;base64,{}", base64::engine::general_purpose::STANDARD.encode(document));
let placement = format!(r#"x="{}" y="{}" width="{}" height="{}" preserveAspectRatio="none""#, min.x, min.y, size.x, size.y);
self.push("feImage", &format!(r#"href="{href}" {placement}"#), "")
}
/// The image with the paint mixed over its colors by the blend mode, keeping its alpha.
fn overlay(&mut self, image: &str, paint: &str, blend_mode: BlendMode) -> String {
// SVG has no counterpart for some blend modes, which paint normally instead
let mode = blend_mode.to_svg_style_name().unwrap_or("normal");
let blended = self.push("feBlend", &format!(r#"in="{paint}" in2="{image}" mode="{mode}""#), "");
self.push("feComposite", &format!(r#"in="{blended}" in2="{image}" operator="atop""#), "")
}
/// The coverage tinted `color`.
fn tint(&mut self, coverage: &str, color: Color) -> String {
let flood = self.push(
@@ -604,8 +673,8 @@ impl SvgFilterPrimitives {
/// Writes an SVG filter into `svg_defs` that carries out `effects` like the GPU passes do, returning its ID, or `None` if the user space is degenerate.
/// `bounds` is the content's extent in the filtered group's user space, which `user_to_document` maps into the document space the effects' lengths are measured in.
/// `pixel_scale` is how many output pixels span a document unit.
fn write_svg_effects_filter(svg_defs: &mut String, effects: &Effects, fill: f32, bounds: [DVec2; 2], user_to_document: DAffine2, pixel_scale: f64) -> Option<String> {
/// `pixel_scale` is how many output pixels span a document unit, and `paints` holds the markup of the paint overlays' paints that aren't solid colors, in order.
fn write_svg_effects_filter(svg_defs: &mut String, effects: &Effects, fill: f32, bounds: [DVec2; 2], user_to_document: DAffine2, pixel_scale: f64, paints: &[String]) -> Option<String> {
use graphic_types::effects::{bevel_light, outline_extents};
use graphic_types::{BevelDirection, EffectOperation, GlowSource};
@@ -616,7 +685,12 @@ fn write_svg_effects_filter(svg_defs: &mut String, effects: &Effects, fill: f32,
let document_to_user = user_to_document.matrix2.inverse();
let length_scale = determinant.abs().sqrt().recip();
// The filter covers how far the effects reach past the content
let reach = effects.reach() * length_scale;
let region = [bounds[0] - reach, bounds[1] + reach];
let mut primitives = SvgFilterPrimitives::default();
let mut paints = paints.iter();
// The content at full strength, which casts every silhouette, and the content faded by the fill, which shows in the result
let mut full = "SourceGraphic".to_string();
@@ -721,6 +795,18 @@ fn write_svg_effects_filter(svg_defs: &mut String, effects: &Effects, fill: f32,
primitives.shade_within(&mut full, &mut filled, &coverage, color);
}
}
EffectOperation::PaintOverlay { blend_mode, opacity, .. } => {
let Some(markup) = paints.next() else { continue };
let mut paint = primitives.paint_image(markup, region);
if opacity < 100. {
let slope = opacity / 100.;
paint = primitives.push("feComponentTransfer", &format!(r#"in="{paint}""#), &format!(r#"<feFuncA type="linear" slope="{slope}" />"#));
}
filled = filled.map(|filled| primitives.overlay(&filled, &paint, blend_mode));
full = primitives.overlay(&full, &paint, blend_mode);
}
EffectOperation::Adjustment(ref adjustment) => {
filled = filled.map(|filled| primitives.adjust(&filled, adjustment));
full = primitives.adjust(&full, adjustment);
@@ -739,9 +825,7 @@ fn write_svg_effects_filter(svg_defs: &mut String, effects: &Effects, fill: f32,
}
}
// The filter covers how far the effects reach past the content
let reach = effects.reach() * length_scale;
let (min, max) = (bounds[0] - reach, bounds[1] + reach);
let [min, max] = region;
let id = format!("effects-{}", generate_uuid());
write!(
svg_defs,
@@ -1443,7 +1527,7 @@ fn render_graphic_item_svg(item: ItemRef<'_, Graphic>, next_clips: bool, mask_st
let render_item = |render: &mut SvgRender| {
// The filter also covers how far the effects nested inside reach past the content, measured in this user space
let document_scale = render.transform.matrix2.determinant().abs().sqrt();
let filter = compositing.svg_filter(render, || match element.bounding_box(transform, true) {
let filter = compositing.svg_filter(render, render_params, || match element.bounding_box(transform, true) {
RenderBoundingBox::Rectangle([min, max]) => {
let nested_reach = nested_effects_reach(element) / document_scale;
RenderBoundingBox::Rectangle([min - nested_reach, max + nested_reach])
@@ -1499,12 +1583,12 @@ fn render_graphic_item_to_vello<'a>(
next_clips: bool,
mask_element_and_transform: &mut Option<(&'a Graphic, DAffine2)>,
scene: &mut VelloSceneBuilder,
transform: DAffine2,
parent_transform: DAffine2,
render_params: &RenderParams,
) {
let Some(element) = item.element() else { return };
let item_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let transform = transform * item_transform;
let transform = parent_transform * item_transform;
let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE);
// This item's declared appearance (if any) cascades to descendants lacking their own
let child_render_params = item
@@ -1550,7 +1634,7 @@ fn render_graphic_item_to_vello<'a>(
bounds => bounds,
};
let draw_content = |scene: &mut VelloSceneBuilder| {
compositing.draw_with_effects(scene, effects_bounds, |scene| element.render_to_vello(scene, transform, render_params));
compositing.draw_with_effects(scene, parent_transform, render_params, effects_bounds, |scene| element.render_to_vello(scene, transform, render_params));
};
if next_clips && mask_element_and_transform.is_none() {
@@ -1740,7 +1824,7 @@ impl Render for Graphic {
}
Graphic::RasterCPU(item) => render_raster_cpu_item_to_vello(ItemRef::Item(item), scene, transform, render_params),
Graphic::RasterGPU(item) => render_raster_gpu_item_to_vello(ItemRef::Item(item), scene, transform, render_params),
Graphic::Color(item) => render_color_item_to_vello(ItemRef::Item(item), scene, render_params),
Graphic::Color(item) => render_color_item_to_vello(ItemRef::Item(item), scene, transform, render_params),
Graphic::Gradient(item) => render_gradient_item_to_vello(ItemRef::Item(item), scene, transform, render_params),
Graphic::Text(item) => render_text_item_to_vello(ItemRef::Item(item), scene, transform, render_params),
Graphic::GraphicList(list) => list.render_to_vello(scene, transform, render_params),
@@ -2403,7 +2487,7 @@ fn render_vector_item_svg(item: ItemRef<'_, Vector>, next_clips: bool, clip_mask
};
let render_shape = |render: &mut SvgRender| {
let filter = compositing.svg_filter(render, || {
let filter = compositing.svg_filter(render, render_params, || {
let item_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let stroke = appearance().and_then(|appearance| appearance.fill_and_stroke().stroke);
let paths = item.attribute::<List<Path>>(ATTR_PATHS).unwrap_or_else(|| no_paths());
@@ -2744,7 +2828,7 @@ fn render_vector_item_to_vello(
}
_ => {
let effects_bounds = || layer_geometry.map_or(RenderBoundingBox::None, |(layer_affine, layer_rect)| rect_bounds(layer_affine.transform_rect_bbox(layer_rect)));
compositing.draw_with_effects(scene, effects_bounds, |scene| {
compositing.draw_with_effects(scene, parent_transform, render_params, effects_bounds, |scene| {
if use_layer {
let cloned_element = element.clone();
@@ -3163,7 +3247,9 @@ fn render_raster_image_svg<T>(item: ItemRef<'_, T>, image: &Raster<CPU>, coverag
}
};
let filter = compositing.svg_filter(render, || RenderBoundingBox::Rectangle((transform * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box()));
let filter = compositing.svg_filter(render, render_params, || {
RenderBoundingBox::Rectangle((transform * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box())
});
// A filter's wrapping group takes the opacity and blend mode instead
let (opacity, blend_mode) = match filter {
@@ -3300,7 +3386,7 @@ fn render_raster_cpu_item_to_vello(item: ItemRef<'_, Raster<CPU>>, scene: &mut V
let sampler = peniko::ImageSampler::new().with_extend(peniko::Extend::Pad);
let item_bounds = || RenderBoundingBox::Rectangle((transform * transform_attribute * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box());
compositing.draw_with_effects(scene, item_bounds, |scene| {
compositing.draw_with_effects(scene, transform, render_params, item_bounds, |scene| {
let image_transform = kurbo::Affine::new(image_transform.to_cols_array());
match &adjusted_texture {
Some(texture) => scene.draw_texture(texture.clone(), sampler, image_transform),
@@ -3463,7 +3549,7 @@ fn render_raster_gpu_item_to_vello(item: ItemRef<'_, Raster<GPU>>, scene: &mut V
let image_transform = transform * transform_attribute * coverage * DAffine2::from_scale(1. / DVec2::new(width as f64, height as f64));
let item_bounds = || RenderBoundingBox::Rectangle((transform * transform_attribute * coverage * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box());
compositing.draw_with_effects(scene, item_bounds, |scene| {
compositing.draw_with_effects(scene, transform, render_params, item_bounds, |scene| {
scene.draw_texture(texture.clone(), sampler, kurbo::Affine::new(image_transform.to_cols_array()))
});
@@ -3490,9 +3576,9 @@ impl Render for List<Color> {
}
}
fn render_to_vello(&self, scene: &mut VelloSceneBuilder, _parent_transform: DAffine2, render_params: &RenderParams) {
fn render_to_vello(&self, scene: &mut VelloSceneBuilder, parent_transform: DAffine2, render_params: &RenderParams) {
for index in 0..self.len() {
render_color_item_to_vello(ItemRef::ListItem(self, index), scene, render_params);
render_color_item_to_vello(ItemRef::ListItem(self, index), scene, parent_transform, render_params);
}
}
}
@@ -3527,7 +3613,7 @@ fn render_color_item_svg(item: ItemRef<'_, Color>, render: &mut SvgRender, rende
}
/// Draws one item of color content into the Vello scene, covering the whole render area.
fn render_color_item_to_vello(item: ItemRef<'_, Color>, scene: &mut VelloSceneBuilder, render_params: &RenderParams) {
fn render_color_item_to_vello(item: ItemRef<'_, Color>, scene: &mut VelloSceneBuilder, parent_transform: DAffine2, render_params: &RenderParams) {
let Some(color) = item.element() else { return };
let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE);
let compositing = item.compositing(render_params);
@@ -3542,7 +3628,7 @@ fn render_color_item_to_vello(item: ItemRef<'_, Color>, scene: &mut VelloSceneBu
layer = true;
}
compositing.draw_with_effects(scene, || RenderBoundingBox::Infinite, |scene| scene.fill_viewport(vello_color, None));
compositing.draw_with_effects(scene, parent_transform, render_params, || RenderBoundingBox::Infinite, |scene| scene.fill_viewport(vello_color, None));
if layer {
scene.pop_layer();
@@ -3752,7 +3838,13 @@ fn render_gradient_item_to_vello(item: ItemRef<'_, Gradient>, scene: &mut VelloS
layer = true;
}
compositing.draw_with_effects(scene, || RenderBoundingBox::Infinite, |scene| scene.fill_viewport(&fill, Some(brush_transform)));
compositing.draw_with_effects(
scene,
parent_transform,
render_params,
|| RenderBoundingBox::Infinite,
|scene| scene.fill_viewport(&fill, Some(brush_transform)),
);
if layer {
scene.pop_layer();
@@ -4059,7 +4151,7 @@ fn render_text_item_svg(item: ItemRef<'_, String>, render: &mut SvgRender, rende
return;
}
let filter = compositing.svg_filter(render, || layout_bounds);
let filter = compositing.svg_filter(render, render_params, || layout_bounds);
let filtered = filter.is_some();
// Wrap all glyph <path> elements in a <g> with the item's transform/opacity/blend-mode, which a filter's wrapping group takes instead
@@ -4158,6 +4250,8 @@ fn render_text_item_to_vello(item: ItemRef<'_, String>, scene: &mut VelloSceneBu
compositing.draw_with_effects(
scene,
transform,
render_params,
|| rect_bounds(transformed_bounds()),
|scene| {
text_nodes::for_each_styled_glyph_run(&layout, text, typesetting, |glyph_run, x_offset, space_extra| {
@@ -4431,6 +4525,7 @@ mod tests {
[DVec2::ZERO, DVec2::splat(10.)],
DAffine2::from_scale(DVec2::splat(2.)),
1.,
&[],
)
.unwrap();
@@ -4449,7 +4544,7 @@ mod tests {
gamma: false,
};
let mut defs = String::new();
write_svg_effects_filter(&mut defs, &Effects::from_operations([blur]), 0.5, [DVec2::ZERO, DVec2::ONE], DAffine2::IDENTITY, 1.).unwrap();
write_svg_effects_filter(&mut defs, &Effects::from_operations([blur]), 0.5, [DVec2::ZERO, DVec2::ONE], DAffine2::IDENTITY, 1., &[]).unwrap();
// The fill fades a copy of the content, which is blurred in linear light and passed through as the filter's last result
assert!(defs.contains(r#"<feFuncA type="linear" slope="0.5" />"#), "{defs}");
@@ -4458,13 +4553,13 @@ mod tests {
}
#[test]
fn svg_effects_filters_carry_out_inner_glows_satins_outlines_and_bevels() {
fn svg_effects_filters_carry_out_inner_glows_satins_outlines_bevels_and_paint_overlays() {
use graphic_types::vector_types::vector::style::StrokeAlign;
use graphic_types::{BevelDirection, EffectOperation, GlowSource};
let filter = |operation| {
let mut defs = String::new();
write_svg_effects_filter(&mut defs, &Effects::from_operations([operation]), 1., [DVec2::ZERO, DVec2::splat(10.)], DAffine2::IDENTITY, 1.).unwrap();
write_svg_effects_filter(&mut defs, &Effects::from_operations([operation]), 1., [DVec2::ZERO, DVec2::splat(10.)], DAffine2::IDENTITY, 1., &[]).unwrap();
defs
};
let invert = r#"<feFuncA type="linear" slope="-1" intercept="1" />"#;
@@ -4513,9 +4608,34 @@ mod tests {
shadow_color: Color::BLACK,
};
let mut bevel_defs = String::new();
write_svg_effects_filter(&mut bevel_defs, &Effects::from_operations([bevel]), 1., [DVec2::ZERO, DVec2::splat(10.)], DAffine2::IDENTITY, 2.).unwrap();
write_svg_effects_filter(&mut bevel_defs, &Effects::from_operations([bevel]), 1., [DVec2::ZERO, DVec2::splat(10.)], DAffine2::IDENTITY, 2., &[]).unwrap();
assert!(bevel_defs.contains(r#"operator="erode" radius="2""#) && bevel_defs.contains(r#"stdDeviation="1""#), "{bevel_defs}");
assert_eq!(bevel_defs.matches(r#"surfaceScale="4""#).count(), 2, "{bevel_defs}");
// A paint overlay embeds its paint's markup as an image of the filter region, then blends it over the content within the content's alpha
let overlay = EffectOperation::PaintOverlay {
paint: Graphic::from(Gradient::default()),
blend_mode: BlendMode::Multiply,
opacity: 50.,
};
let mut overlay_defs = String::new();
let paints = [r#"<rect width="10" height="10" fill="red" />"#.to_string()];
write_svg_effects_filter(
&mut overlay_defs,
&Effects::from_operations([overlay]),
1.,
[DVec2::ZERO, DVec2::splat(10.)],
DAffine2::IDENTITY,
1.,
&paints,
)
.unwrap();
assert!(
overlay_defs.contains(r#"<feImage href="data:image/svg+xml;base64,"#) && overlay_defs.contains(r#"x="0" y="0" width="10" height="10""#),
"{overlay_defs}"
);
assert!(overlay_defs.contains(r#"<feFuncA type="linear" slope="0.5" />"#), "{overlay_defs}");
assert!(overlay_defs.contains(r#"mode="multiply""#) && overlay_defs.contains(r#"operator="atop""#), "{overlay_defs}");
}
#[test]
@@ -4532,6 +4652,7 @@ mod tests {
[DVec2::ZERO, DVec2::ONE],
DAffine2::IDENTITY,
1.,
&[],
)
.unwrap();
defs
@@ -4589,7 +4710,16 @@ mod tests {
true
}
fn render_effects(&mut self, _: glam::UVec2, _: kurbo::Affine, _: &Effects, _: f32, _: DMat2, _: &mut dyn FnMut(&mut VelloSceneBuilder)) -> graphic_types::raster_types::Texture {
fn render_effects(
&mut self,
_: glam::UVec2,
_: kurbo::Affine,
_: &Effects,
_: f32,
_: DMat2,
_: &mut dyn FnMut(usize, &mut VelloSceneBuilder),
_: &mut dyn FnMut(&mut VelloSceneBuilder),
) -> graphic_types::raster_types::Texture {
panic!("the vector is drawn through an effects group");
}
@@ -33,9 +33,19 @@ pub trait EffectsRenderer: Send {
/// Whether the GPU can carry out effects, without which effects groups draw their content faded by their fill.
fn renders_effects(&self) -> bool;
/// Renders the content `draw` draws, placed by `view`, into a texture of `size`, returning a straight-alpha texture of the same size with `effects` carried out on it.
/// Renders the content `draw` draws, and each paint overlay's paint `draw_paint` draws by index, placed by `view` in textures of `size`, returning a straight-alpha texture of the same size with `effects` carried out on it.
/// `lengths_to_pixels` maps the effects' lengths onto the texture's pixels, and `fill` fades the content but not the shadows and glows cast from it.
fn render_effects(&mut self, size: UVec2, view: Affine, effects: &Effects, fill: f32, lengths_to_pixels: DMat2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Texture;
#[expect(clippy::too_many_arguments)]
fn render_effects(
&mut self,
size: UVec2,
view: Affine,
effects: &Effects,
fill: f32,
lengths_to_pixels: DMat2,
draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder),
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
) -> Texture;
/// A straight-alpha texture of the size of the CPU `raster`, with `adjustments` carried out on its pixels, kept for as long as they're drawn that way.
/// `None` if they can't be carried out.
@@ -241,9 +251,9 @@ impl<'a> VelloSceneBuilder<'a> {
self.effects_renderer.as_deref_mut().filter(|renderer| renderer.renders_effects())?.adjust_raster(raster, adjustments)
}
/// Draws the content `draw` draws with `effects` carried out on it, given the area it covers in the space of the drawn content, or `None` if unbounded.
/// `fill` fades the content but not the shadows and glows cast from it. Rendering a split scene calls `draw` again for each part.
pub fn draw_effects(&mut self, effects: &Effects, fill: f32, bounds: Option<Rect>, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) {
/// Draws the content `draw` draws with `effects` carried out on it, within `bounds` in the space of the drawn content (or everywhere for `None`), drawing again for each part of a split render.
/// `draw_paint` draws each paint overlay's paint by its index among them, and `fill` fades the content but not the shadows and glows cast from it.
pub fn draw_effects(&mut self, effects: &Effects, fill: f32, bounds: Option<Rect>, draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder), draw: &mut dyn FnMut(&mut VelloSceneBuilder)) {
if !self.effects_renderer.as_ref().is_some_and(|renderer| renderer.renders_effects()) {
self.push_viewport_layer(peniko::Mix::Normal, fill);
draw(self);
@@ -273,7 +283,7 @@ impl<'a> VelloSceneBuilder<'a> {
let content_view = Affine::scale(resolution) * Affine::translate(-origin) * self.view;
let Some(renderer) = self.effects_renderer.as_deref_mut() else { return };
let result = renderer.render_effects(size, content_view, effects, fill, lengths_to_device * resolution, draw);
let result = renderer.render_effects(size, content_view, effects, fill, lengths_to_device * resolution, draw_paint, draw);
// Draw the result where the content was
self.images.push(SceneImage::Texture { texture: result, minified: false });
@@ -5,17 +5,20 @@ use crate::WgpuPipelineCache;
use crate::raster_kernel::{MAX_FRAME_SIDE, adjust_raster, blur_raster, run_raster_kernel};
use crate::shader_runtime::raster_kernel_runtime::RasterKernelInput;
use core_types::list::{ATTR_EFFECTS, Item};
use core_types::math::quad::Quad;
use core_types::ops::Convert;
use core_types::transform::Footprint;
use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color, NodeError};
use glam::{DAffine2, DMat2, DVec2, UVec2};
use graphic_types::effects::{bevel_light, bevel_smoothing, outline_extents};
use graphic_types::{Adjustment, BevelDirection, EffectOperation, Effects, GlowSource};
use graphic_types::effects::{bevel_light, bevel_smoothing, fitted_paint, outline_extents};
use graphic_types::{Adjustment, BevelDirection, EffectOperation, Effects, GlowSource, Graphic};
use raster_kernels::RasterKernel;
use raster_kernels::adjustments::{leading_adjustments, preserves_alpha};
use raster_kernels::blur::BlurSpace;
use raster_kernels::effects::*;
use raster_types::{CPU, GPU, Raster, Storage};
use rendering::vello_scene_builder::VelloSceneBuilder;
use rendering::{Render, RenderParams};
/// Blurs and spreads shorter than this, in pixels, leave no visible trace.
pub const NEGLIGIBLE_LENGTH: f64 = 0.01;
@@ -90,9 +93,24 @@ fn evaluate(raster: &Raster<GPU>, transform: DAffine2, operations: &[EffectOpera
margin = margin.min(((DVec2::splat(MAX_FRAME_SIDE as f64) - size.as_dvec2()) / 2.).max(DVec2::ZERO).floor());
let grown_size = grown(margin).as_uvec2();
// A paint is placed in the space the raster's item is placed in, or fitted to the raster's extent there, and rendered over the grown raster's pixels
let parent_to_pixels = DAffine2::from_translation(margin) * DAffine2::from_scale(size.as_dvec2()) * placement.inverse();
let bounds = (placement * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box();
let mut render_paint = |_: usize, paint: &Graphic| {
let executor = pipeline.executor().ok_or_else(|| NodeError::new("A GPU is required to render a paint"))?;
let fitted = fitted_paint(paint, bounds);
let paint = fitted.as_ref().unwrap_or(paint);
let render_params = RenderParams::default().for_pattern();
let mut draw = |scene: &mut VelloSceneBuilder| paint.render_to_vello(scene, DAffine2::IDENTITY, &render_params);
let texture = executor
.render_vello_raster(grown_size, parent_to_pixels, &mut draw)
.map_err(|error| NodeError::new(error.to_string()))?;
Ok(Raster::<GPU>::new_gpu(texture))
};
let mut pass = EffectsPass::new(raster, grown_size, DAffine2::from_translation(-margin), fill, lengths_to_pixels, pipeline)?;
for operation in operations {
pass.apply(operation)?;
pass.apply(operation, &mut render_paint)?;
}
let result = pass.finish()?;
@@ -101,17 +119,18 @@ fn evaluate(raster: &Raster<GPU>, transform: DAffine2, operations: &[EffectOpera
}
/// Carries out `operations` in order on `content`, a straight-alpha raster in the pixels `lengths_to_pixels` maps the effects' lengths onto, into a raster of its size.
/// `fill` fades the content but not the shadows and glows cast from it.
/// `fill` fades the content but not the shadows and glows cast from it, and `render_paint` renders each paint overlay's paint, by its index among them, over the same pixels.
pub fn apply_effects(
content: &Raster<GPU>,
operations: impl IntoIterator<Item = EffectOperation>,
fill: f32,
lengths_to_pixels: DMat2,
render_paint: &mut dyn FnMut(usize, &Graphic) -> Result<Raster<GPU>, NodeError>,
pipeline: &WgpuPipelineCache,
) -> Result<Raster<GPU>, NodeError> {
let mut pass = EffectsPass::new(content, content.size(), DAffine2::IDENTITY, fill, lengths_to_pixels, pipeline)?;
for operation in operations {
pass.apply(&operation)?;
pass.apply(&operation, render_paint)?;
}
Ok(pass.finish()?.with_coverage(content.coverage()))
}
@@ -127,6 +146,8 @@ pub struct EffectsPass<'a> {
filled: Option<Raster<GPU>>,
/// The shadows and glows stacked beneath the content.
beneath: Option<Raster<GPU>>,
/// How many paint overlays have been carried out.
paint_overlays: usize,
}
impl<'a> EffectsPass<'a> {
@@ -143,11 +164,12 @@ impl<'a> EffectsPass<'a> {
full,
filled,
beneath: None,
paint_overlays: 0,
})
}
/// Carries out the next effect.
pub fn apply(&mut self, operation: &EffectOperation) -> Result<(), NodeError> {
/// Carries out the next effect, with `render_paint` rendering a paint overlay's paint, by its index among them, into a straight-alpha raster over the images' pixels.
pub fn apply(&mut self, operation: &EffectOperation, render_paint: &mut dyn FnMut(usize, &Graphic) -> Result<Raster<GPU>, NodeError>) -> Result<(), NodeError> {
let lengths_to_pixels = self.lengths_to_pixels;
let length_scale = lengths_to_pixels.determinant().abs().sqrt();
@@ -256,6 +278,19 @@ impl<'a> EffectsPass<'a> {
self.shade_within(&coverage, color)?;
}
}
EffectOperation::PaintOverlay { ref paint, blend_mode, opacity } => {
let paint = render_paint(self.paint_overlays, paint)?;
self.paint_overlays += 1;
let overlay = PaintOverlay {
blend_mode,
opacity: (opacity / 100.) as f32,
};
self.full = self.run(&overlay, &[&self.full, &paint])?;
if let Some(filled) = &self.filled {
self.filled = Some(self.run(&overlay, &[filled, &paint])?);
}
}
EffectOperation::Adjustment(ref adjustment) => {
self.full = self.adjust_image(&self.full, adjustment)?;
if let Some(filled) = &self.filled {
@@ -6,7 +6,7 @@ use core_types::graphene_hash::CacheHash;
use core_types::ops::Convert;
use core_types::transform::Footprint;
use glam::{DMat2, UVec2};
use graphic_types::{Adjustment, Effects};
use graphic_types::{Adjustment, Effects, Graphic};
use raster_types::{CPU, GPU, Raster, Texture, WeakCPU};
use rendering::vello_scene_builder::{EffectsRenderer, SceneImage, VelloSceneBuilder, image_downscale_factor, image_texture_size};
use std::collections::HashMap;
@@ -305,14 +305,31 @@ impl EffectsRenderer for RenderContext<'_> {
self.kernels.executor().is_some()
}
fn render_effects(&mut self, size: UVec2, view: Affine, effects: &Effects, fill: f32, lengths_to_pixels: DMat2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Texture {
fn render_effects(
&mut self,
size: UVec2,
view: Affine,
effects: &Effects,
fill: f32,
lengths_to_pixels: DMat2,
draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder),
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
) -> Texture {
// Rendered into a raster of the content, which the effects are carried out on with the same kernels as a raster's own effects
let executor = self.kernels.executor().expect("effects are only rendered with a GPU");
let kernels = self.kernels;
let executor = kernels.executor().expect("effects are only rendered with a GPU");
let content = executor.request_texture_with_format(size, executor.raster_format());
self.render_area(draw, view, size, &content);
let content = Raster::<GPU>::new_gpu(content);
match apply_effects(&content, effects.operations(), fill, lengths_to_pixels, self.kernels) {
// The paint overlays' paints, each rendered over the same pixels as the content
let mut render_paint = |index: usize, _: &Graphic| {
let paint = executor.request_texture_with_format(size, executor.raster_format());
self.render_area(&mut |scene| draw_paint(index, scene), view, size, &paint);
Ok(Raster::<GPU>::new_gpu(paint))
};
match apply_effects(&content, effects.operations(), fill, lengths_to_pixels, &mut render_paint, kernels) {
Ok(result) => result
.texture()
.cloned()
@@ -276,11 +276,29 @@ fn degenerate_strokes_render() {
/// Renders an opaque white square from (`min`, `min`) to (`max`, `max`) through `effects` with `fill`.
fn render_square_with_effects(effects: Vec<graphic_types::EffectOperation>, fill: f32, min: f64, max: f64, size: UVec2) -> Option<Vec<[u8; 4]>> {
let square = Rect::new(min, min, max, max);
let effects = graphic_types::Effects::from_operations(effects);
use rendering::{Render, RenderParams};
let square = Rect::new(min, min, max, max);
// The paint overlays' paints, drawn as the renderer does for content placed in the scene's space
let paints: Vec<graphic_types::Graphic> = (effects.iter())
.filter_map(|operation| match operation {
graphic_types::EffectOperation::PaintOverlay { paint, .. } => Some(paint),
_ => None,
})
.map(|paint| graphic_types::fitted_paint(paint, [glam::DVec2::splat(min), glam::DVec2::splat(max)]).unwrap_or_else(|| paint.clone()))
.collect();
let mut draw_paint = |index: usize, scene: &mut VelloSceneBuilder| {
if let Some(paint) = paints.get(index) {
paint.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default().for_pattern());
}
};
let effects = graphic_types::Effects::from_operations(effects);
render(size, |scene| {
scene.draw_effects(&effects, fill, Some(square), &mut |scene| scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square));
scene.draw_effects(&effects, fill, Some(square), &mut draw_paint, &mut |scene| {
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square)
});
})
}
@@ -461,6 +479,46 @@ fn inner_glows_satins_outlines_and_bevels_fall_where_they_should() {
assert_eq!(pixel(&pixels, size, 55, 40), white, "the content inside is unlit");
}
#[test]
fn paint_overlays_stretch_unplaced_paints_across_the_content() {
use core_types::Color as GraphicColor;
use core_types::blending::BlendMode;
use core_types::list::Item;
use graphic_types::raster_types::{Image, Raster};
use graphic_types::vector_types::gradient::{Gradient, GradientStop};
use graphic_types::{EffectOperation, Graphic};
let size = UVec2::new(128, 128);
let overlay = |paint: Graphic| EffectOperation::PaintOverlay {
paint,
blend_mode: BlendMode::Normal,
opacity: 100.,
};
let reddish = |[red, green, blue, alpha]: [u8; 4]| red > 200 && green < 64 && blue < 64 && alpha == 255;
let bluish = |[red, green, blue, alpha]: [u8; 4]| blue > 200 && red < 64 && green < 64 && alpha == 255;
// A gradient from red to blue runs from the square's left edge to its right edge
let stops = [(0., GraphicColor::RED), (1., GraphicColor::BLUE)].map(|(position, color)| GradientStop { position, midpoint: 0.5, color });
let Some(pixels) = render_square_with_effects(vec![overlay(Graphic::from(Gradient::new(stops)))], 1., 30., 80., size) else {
return;
};
assert!(reddish(pixel(&pixels, size, 31, 55)), "the start at the left edge: {:?}", pixel(&pixels, size, 31, 55));
assert!(bluish(pixel(&pixels, size, 78, 55)), "the end at the right edge: {:?}", pixel(&pixels, size, 78, 55));
assert_eq!(pixel(&pixels, size, 25, 55)[3], 0, "nothing outside the content");
// An image of a red pixel beside a blue one covers the square, each pixel half of it
let image = Image {
width: 2,
height: 1,
data: vec![GraphicColor::RED, GraphicColor::BLUE],
};
let Some(pixels) = render_square_with_effects(vec![overlay(Graphic::from(Item::new_from_element(Raster::new_cpu(image))))], 1., 30., 80., size) else {
return;
};
assert!(reddish(pixel(&pixels, size, 35, 40)), "the left half: {:?}", pixel(&pixels, size, 35, 40));
assert!(bluish(pixel(&pixels, size, 75, 70)), "the right half: {:?}", pixel(&pixels, size, 75, 70));
}
#[test]
fn later_shadows_stack_over_earlier_ones_beneath_the_content() {
use core_types::Color as GraphicColor;
@@ -505,8 +563,10 @@ fn nested_effects_groups_render_inside_out() {
gamma: false,
}]);
let draw = |scene: &mut VelloSceneBuilder| {
scene.draw_effects(&shadow, 1., Some(square.inflate(12., 12.)), &mut |scene| {
scene.draw_effects(&blur, 1., Some(square), &mut |scene| scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square));
scene.draw_effects(&shadow, 1., Some(square.inflate(12., 12.)), &mut |_, _| {}, &mut |scene| {
scene.draw_effects(&blur, 1., Some(square), &mut |_, _| {}, &mut |scene| {
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square)
});
});
};
@@ -617,6 +677,8 @@ fn a_rasters_evaluated_effects_match_the_rendered_effects_group() {
use crate::raster_effects::evaluate_raster_effects;
use crate::shader_runtime::raster_kernel_runtime::RasterKernelRuntime;
use core_types::Color as GraphicColor;
use core_types::blending::BlendMode;
use core_types::list::ATTR_GRADIENT_FORM;
use core_types::list::{ATTR_EFFECTS, Item};
use core_types::ops::{Convert, ConvertAsync};
use core_types::transform::Footprint;
@@ -624,8 +686,9 @@ fn a_rasters_evaluated_effects_match_the_rendered_effects_group() {
use glam::DVec2;
use graphic_types::adjustment::{Adjustment, LevelsRecord, LevelsSettings};
use graphic_types::raster_types::{CPU, GPU, Image, Raster, Storage};
use graphic_types::vector_types::gradient::{Gradient, GradientForm, GradientStop};
use graphic_types::vector_types::vector::style::StrokeAlign;
use graphic_types::{BevelDirection, BevelStyle, EffectOperation, Effects, GlowSource};
use graphic_types::{BevelDirection, BevelStyle, EffectOperation, Effects, GlowSource, Graphic};
let size = UVec2::new(160, 160);
let (min, max) = (50, 100);
@@ -747,7 +810,62 @@ fn a_rasters_evaluated_effects_match_the_rendered_effects_group() {
let pipeline = WgpuPipelineCache::default();
executor.pipeline_init::<RasterKernelRuntime>(&pipeline);
for effects in cases {
// Paint overlays over a colored backdrop, their paints placed on their own since the raster and the square fit unplaced paints to different bounds
let backdrop = EffectOperation::Adjustment(Adjustment::ColorOverlay {
color: GraphicColor::from_rgbaf32_unchecked(0.3, 0.6, 0.2, 1.),
blend_mode: BlendMode::Normal,
opacity: 100.,
});
let gradient = |form: GradientForm, transform: DAffine2| {
let stops = [(0., [0.9, 0.1, 0.4, 1.]), (0.5, [0.2, 0.3, 0.9, 0.5]), (1., [1., 0.9, 0.7, 1.])].map(|(position, [red, green, blue, alpha])| GradientStop {
position,
midpoint: 0.5,
color: GraphicColor::from_rgbaf32_unchecked(red, green, blue, alpha),
});
let item = Item::new_from_element(Gradient::new(stops)).with_attribute(ATTR_TRANSFORM, transform);
Graphic::from(item.with_attribute(ATTR_GRADIENT_FORM, form))
};
let linear = gradient(GradientForm::Linear, DAffine2::from_translation(DVec2::new(45., 60.)) * DAffine2::from_scale(DVec2::splat(60.)));
let radial = gradient(GradientForm::Radial, DAffine2::from_translation(DVec2::splat(75.)) * DAffine2::from_scale(DVec2::splat(30.)));
// A checkerboard with a pixel for each of the square's, so sampling it needs no interpolation
let checker = Image {
width: 50,
height: 50,
data: (0..2500)
.map(|index| match (index % 50 / 5 + index / 50 / 5) % 2 {
0 => GraphicColor::RED,
_ => GraphicColor::from_rgbaf32_unchecked(0., 0., 1., 0.5),
})
.collect(),
};
let checker_placement = DAffine2::from_translation(DVec2::splat(50.)) * DAffine2::from_scale(DVec2::splat(50.));
let checker = Graphic::from(Item::new_from_element(Raster::new_cpu(checker)).with_attribute(ATTR_TRANSFORM, checker_placement));
let overlay = |paint: &Graphic, blend_mode, opacity| {
vec![
backdrop.clone(),
EffectOperation::PaintOverlay {
paint: paint.clone(),
blend_mode,
opacity,
},
]
};
// Hard Mix's threshold and the hue of the gradient's grays turn the slightest rounding into large differences, so they take the checkerboard's exact colors instead
let ill_conditioned = [BlendMode::HardMix, BlendMode::Hue];
let mut paint_cases: Vec<_> = (BlendMode::list().into_iter().flatten())
.filter(|blend_mode| !ill_conditioned.contains(blend_mode))
.map(|&blend_mode| overlay(&linear, blend_mode, 100.))
.collect();
paint_cases.extend(ill_conditioned.map(|blend_mode| overlay(&checker, blend_mode, 100.)));
paint_cases.extend([
overlay(&linear, BlendMode::Normal, 40.),
overlay(&radial, BlendMode::Multiply, 100.),
overlay(&checker, BlendMode::Screen, 100.),
]);
for effects in cases.into_iter().chain(paint_cases) {
for fill in [1., 0.5] {
let Some(rendered) = render_square_with_effects(effects.clone(), fill, min as f64, max as f64, size) else {
return;
@@ -792,7 +910,16 @@ fn a_rasters_evaluated_effects_match_the_rendered_effects_group() {
}
}
}
assert!(worst <= 2, "{effects:?} at fill {fill} differs from the render by up to {worst} levels");
// Modes that divide, or land near black where the gamma encoding is steepest, amplify the rounding of the rendered paint's eight bits
use BlendMode::*;
let tolerance = match effects.last() {
Some(EffectOperation::PaintOverlay {
blend_mode: ColorBurn | LinearBurn | ColorDodge | HardLight | VividLight | LinearLight | PinLight,
..
}) => 8,
_ => 2,
};
assert!(worst <= tolerance, "{effects:?} at fill {fill} differs from the render by up to {worst} levels");
}
}
}
@@ -885,7 +1012,7 @@ fn effects_groups_carry_out_adjustments_like_their_kernels_map_colors() {
let effects = Effects::from_operations(run.iter().cloned().map(EffectOperation::Adjustment));
let draw = |scene: &mut VelloSceneBuilder| {
let bounds = Rect::new(0., 0., size.x as f64, size.y as f64);
scene.draw_effects(&effects, 1., Some(bounds), &mut |scene| {
scene.draw_effects(&effects, 1., Some(bounds), &mut |_, _| {}, &mut |scene| {
scene.draw_raster(raster.clone(), peniko::ImageSampler::new(), Affine::IDENTITY)
});
};
@@ -914,7 +1041,7 @@ fn effects_groups_keep_the_empty_space_empty_when_an_adjustment_changes_alpha()
let square = Rect::new(4., 4., 12., 12.);
let effects = Effects::from_operations([EffectOperation::Adjustment(Adjustment::MakeOpaque)]);
let draw = |scene: &mut VelloSceneBuilder| {
scene.draw_effects(&effects, 1., Some(Rect::new(0., 0., 16., 16.)), &mut |scene| {
scene.draw_effects(&effects, 1., Some(Rect::new(0., 0., 16., 16.)), &mut |_, _| {}, &mut |scene| {
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::new([1., 1., 1., 0.5]), None, &square)
});
};
@@ -1,14 +1,7 @@
use crate::effects::ApplyEffect;
use crate::raster_kernel::raster_kernel_pipeline;
use core_types::Ctx;
use core_types::Interrupt;
use core_types::blending::BlendMode;
use core_types::color::Color;
use core_types::list::Item;
use graphic_types::{Adjustment, Graphic, Vector};
use raster_types::{CPU, GPU, Raster};
use vector_types::Gradient;
use wgpu_executor::WgpuPipelineCache;
pub use core_types::blending::{apply_blend_mode, blend_colors};
@@ -33,66 +26,10 @@ fn mix_colors(
under
}
// TODO: Rename to "Paint Overlay" and take a `Graphic` paint like the `Fill` node, enabling this to serve the cases of Color Overlay, Gradient Overlay, and Pattern Overlay.
#[node_macro::node(category("Raster: Effect"), icon("NodeColorOverlay"))]
fn color_overlay<T: ApplyEffect>(
_: impl Ctx,
#[implementations(
Raster<CPU>,
Color,
Gradient,
Graphic,
Vector,
Raster<GPU>,
String,
)]
image: Item<T>,
#[default(Color::BLACK)] color: Item<Color>,
blend_mode: Item<BlendMode>,
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(100.)]
opacity: Item<f64>,
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
) -> Result<Item<T>, Interrupt> {
let adjustment = Adjustment::ColorOverlay {
color: color.into_element(),
blend_mode: blend_mode.into_element(),
opacity: opacity.into_element(),
};
Ok(T::apply_adjustment(image, adjustment, pipeline.element())?)
}
#[cfg(test)]
mod test {
use core_types::blending::BlendMode;
use core_types::color::Color;
use core_types::list::Item;
#[test]
fn color_overlay_multiply() {
let image_color = Color::from_rgbaf32_unchecked(0.7, 0.6, 0.5, 0.4);
// Color { red: 0., green: 1., blue: 0., alpha: 1. }
let overlay_color = Color::GREEN;
// 100% of the output should come from the multiplied value
let opacity = 100.;
let result = super::color_overlay(
(),
Item::new_from_element(image_color),
overlay_color.into(),
BlendMode::Multiply.into(),
opacity.into(),
Item::default(),
);
let result = result.unwrap().into_element();
// The output should just be the original green and alpha channels (as we multiply them by 1 and other channels by 0)
assert_eq!(result, Color::from_rgbaf32_unchecked(0., image_color.g(), 0., image_color.a()));
}
#[test]
fn mix_colors_paints_over_at_its_opacity() {
+52
View File
@@ -1,4 +1,5 @@
use crate::raster_kernel::raster_kernel_pipeline;
use core_types::blending::BlendMode;
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, Item, List};
use core_types::{ATTR_OPACITY_FILL, CacheHash, Color, Ctx, Interrupt, NodeError};
use glam::DVec2;
@@ -397,6 +398,40 @@ fn bevel_and_emboss<T: ApplyEffect>(
)
}
/// Paints over the input graphics within their shape, mixing the paint with their colors by a blend mode.
#[node_macro::node(category("Raster: Effect"), icon("NodeColorOverlay"))]
fn paint_overlay<T: ApplyEffect>(
_: impl Ctx,
/// The content to paint over.
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
content: Item<T>,
/// The color, gradient, image, or other graphic to paint with. A gradient or image without its own placement stretches across the content.
#[default(Color::BLACK)]
paint: Item<Graphic>,
/// How the paint mixes with the content's colors.
blend_mode: Item<BlendMode>,
/// How strongly the paint shows.
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(100.)]
opacity: Item<f64>,
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
) -> Result<Item<T>, Interrupt> {
let (blend_mode, opacity) = (blend_mode.into_element(), opacity.into_element());
// The paint is the element alone, since the wire envelope's attributes would nest it as a group
Ok(match paint.into_element() {
Graphic::None(_) | Graphic::NoneList(_) => content,
// A solid paint mixes the same into every pixel, as an adjustment
Graphic::Color(color) => {
let color = *color.element();
T::apply_adjustment(content, Adjustment::ColorOverlay { color, blend_mode, opacity }, pipeline.element())?
}
paint => T::apply_effect(content, EffectOperation::PaintOverlay { paint, blend_mode, opacity }, pipeline.element())?,
})
}
/// Uploads an image to the GPU and carries out its effects into the pixels, at the image's own resolution, for what comes next to run on the GPU right away.
#[node_macro::node(category("Raster"), icon("NodeUploadTexture"))]
fn eager(
@@ -620,6 +655,23 @@ mod tests {
});
}
#[test]
fn paint_overlay_multiplies_a_color_into_the_content() {
let image_color = Color::from_rgbaf32_unchecked(0.7, 0.6, 0.5, 0.4);
let result = super::paint_overlay(
(),
Item::new_from_element(image_color),
Item::new_from_element(Graphic::from(Color::GREEN)),
BlendMode::Multiply.into(),
100_f64.into(),
Item::default(),
);
// Multiplying by green keeps only the green channel, and the content keeps its own alpha
assert_eq!(result.unwrap().into_element(), Color::from_rgbaf32_unchecked(0., image_color.g(), 0., image_color.a()));
}
#[test]
fn the_input_adapter_uploads_a_raster_once_until_its_pixels_or_effects_change() {
futures::executor::block_on(async {