diff --git a/editor/src/messages/layout/utility_types/widgets/input_widgets.rs b/editor/src/messages/layout/utility_types/widgets/input_widgets.rs index ac8d2e64b7..f22051429c 100644 --- a/editor/src/messages/layout/utility_types/widgets/input_widgets.rs +++ b/editor/src/messages/layout/utility_types/widgets/input_widgets.rs @@ -878,6 +878,22 @@ pub struct SliderMarker { /// Whether this marker follows its neighbors instead of bounding them, so they may drag past its drawn position. #[serde(rename = "betweenNeighbors")] between_neighbors: bool, + /// How this marker and the next may pass each other. + #[serde(rename = "overlapNext")] + overlap_next: MarkerOverlap, +} + +/// How a slider marker and the next may pass each other, as split handles whose ranges may overlap. +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub enum MarkerOverlap { + /// Neither may pass the other. + #[default] + Never, + /// Each may pass the other but not the marker beyond it, so split handles' inner halves can overlap while the handles can't pass each other. + NextOnly, + /// The markers up to this one and those after it don't bound each other, so split handles can pass each other entirely. + Freely, } impl SliderMarker { @@ -890,6 +906,7 @@ impl SliderMarker { paired_with_next: false, dashed_to_next: false, between_neighbors: false, + overlap_next: MarkerOverlap::Never, } } @@ -907,6 +924,11 @@ impl SliderMarker { self.dashed_to_next = true; self } + + pub fn overlap_next(mut self, overlap: MarkerOverlap) -> Self { + self.overlap_next = overlap; + self + } } #[cfg_attr(feature = "wasm", derive(tsify::Tsify))] diff --git a/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs b/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs index 4b2bbc9f2c..863f8fa3e1 100644 --- a/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs +++ b/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs @@ -35,8 +35,8 @@ use graphene_std::vector::style::{ }; use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector}; use graphene_std::{ - Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, GlowTechnique, Graphic, - MaskMode, MinimumMaximumMode, NoiseDistribution, + Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, + GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, }; use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType}; use kurbo::BezPath; @@ -1277,6 +1277,7 @@ impl_table_item_layout_for_choice_enum!( WarpStyle, WaveType, DisplaceMode, + BlendIfChannel, EffectKind, Generator, GlowSource, @@ -1472,6 +1473,7 @@ macro_rules! known_item_types { WarpStyle, WaveType, DisplaceMode, + BlendIfChannel, DashPattern, BoxCorners, TransferCurve, diff --git a/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs b/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs index 1e6105eaa4..814d6f76d1 100644 --- a/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs +++ b/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs @@ -676,6 +676,7 @@ fn static_node_inspector() -> NodeInspector { map.insert("hue_saturation_inspector".to_string(), Box::new(node_inspector::hue_saturation_inspector)); map.insert("black_and_white_inspector".to_string(), Box::new(node_inspector::black_and_white_inspector)); map.insert("threshold_inspector".to_string(), Box::new(node_inspector::threshold_inspector)); + map.insert("blend_if_inspector".to_string(), Box::new(node_inspector::blend_if_inspector)); map.insert("vibrance_inspector".to_string(), Box::new(node_inspector::vibrance_inspector)); map.insert("color_balance_inspector".to_string(), Box::new(node_inspector::color_balance_inspector)); map.insert("fill_inspector".to_string(), Box::new(node_inspector::fill_inspector)); diff --git a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs index e566f4afc7..f2f42571c5 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs @@ -41,7 +41,7 @@ use graphene_std::vector::style::{ build_transform_with_y_preservation, }; use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification}; -use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector}; +use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector}; use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType}; use graphene_std::{NodeParameter, ParameterRef}; use math_parser::parser::{MessagePart, ParseError}; @@ -464,6 +464,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type, Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), + Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), @@ -1916,6 +1917,8 @@ pub(crate) fn levels_inspector(node_id: NodeId, context: &mut NodeInspectorConte enum MarkerScale { /// A 0..100 percentage, placed linearly. Percent, + /// A 0..100 percentage of a channel's 256 levels, placed linearly and shown to a tenth, which tells neighboring levels apart. + LevelPercent, /// A gamma of 0.01..9.99 running from 9.99 at the left to 0.01 at the right, logarithmic on each side of the 1 at its center. Gamma, /// A hue of 0..360 degrees, placed linearly on a track that wraps around. @@ -1925,7 +1928,7 @@ enum MarkerScale { impl MarkerScale { fn position(self, value: f64) -> f64 { match self { - Self::Percent => value / 100., + Self::Percent | Self::LevelPercent => value / 100., Self::Gamma if value >= 1. => 0.5 - 0.5 * value.log10() / 9.99_f64.log10(), Self::Gamma => 0.5 + 0.5 * value.log10() / 0.01_f64.log10(), Self::Degrees => { @@ -1939,7 +1942,7 @@ impl MarkerScale { fn value(self, position: f64) -> f64 { match self { - Self::Percent => (position * 100.).clamp(0., 100.), + Self::Percent | Self::LevelPercent => (position * 100.).clamp(0., 100.), Self::Gamma if position <= 0.5 => 9.99_f64.powf(1. - 2. * position).clamp(1., 9.99), Self::Gamma => 0.01_f64.powf(2. * position - 1.).clamp(0.01, 1.), Self::Degrees => (position * 360.).clamp(0., 360.), @@ -1949,6 +1952,7 @@ impl MarkerScale { fn number_input(self) -> NumberInput { match self { Self::Percent => NumberInput::default().mode_increment().unit("%").min(0.).max(100.).display_decimal_places(0), + Self::LevelPercent => NumberInput::default().mode_increment().unit("%").min(0.).max(100.).display_decimal_places(1), Self::Gamma => NumberInput::default().mode_increment().min(0.01).max(9.99).display_decimal_places(2), Self::Degrees => NumberInput::default().mode_increment().unit("°").min(0.).max(360.).display_decimal_places(0), } @@ -1973,6 +1977,8 @@ struct SliderSectionParam { dash_to_next: bool, /// Whether the marker takes its scale position within the span between its neighbors rather than the whole track, following them as they move. between_neighbors: bool, + /// How the marker and the next parameter's marker may pass each other (see [`overlap_bounds`]). + overlap_next: MarkerOverlap, } impl SliderSectionParam { @@ -1985,6 +1991,7 @@ impl SliderSectionParam { pair_with_next: false, dash_to_next: false, between_neighbors: false, + overlap_next: MarkerOverlap::Never, } } @@ -2002,11 +2009,52 @@ impl SliderSectionParam { self.dash_to_next = true; self } + + fn overlap_next(mut self, overlap: MarkerOverlap) -> Self { + self.overlap_next = overlap; + self + } +} + +/// The span the marker at `index` may move within where markers may overlap their next (see [`MarkerOverlap`]). +fn overlap_bounds(positions: &[f64], overlaps_next: &[MarkerOverlap], index: usize) -> (f64, f64) { + let overlap = |i: Option| i.and_then(|i| overlaps_next.get(i)).copied().unwrap_or_default(); + let position = |i: Option| i.and_then(|i| positions.get(i)).copied(); + let (previous, before_previous, next, after_next) = (index.checked_sub(1), index.checked_sub(2), Some(index + 1), Some(index + 2)); + let mut lower = 0_f64; + let mut upper = 1_f64; + + // A neighbor bounds the marker unless they overlap + if overlap(previous) == MarkerOverlap::Never + && let Some(previous) = position(previous) + { + lower = lower.max(previous); + } + if overlap(Some(index)) == MarkerOverlap::Never + && let Some(next) = position(next) + { + upper = upper.min(next); + } + + // Past a neighbor overlapping only its next, the marker beyond bounds it too, unless either overlaps freely + let bounds_beyond = |near: MarkerOverlap, far: MarkerOverlap| (near == MarkerOverlap::NextOnly || far == MarkerOverlap::NextOnly) && near != MarkerOverlap::Freely && far != MarkerOverlap::Freely; + if bounds_beyond(overlap(previous), overlap(before_previous)) + && let Some(before_previous) = position(before_previous) + { + lower = lower.max(before_previous); + } + if bounds_beyond(overlap(Some(index)), overlap(next)) + && let Some(after_next) = position(after_next) + { + upper = upper.min(after_next); + } + + (lower, upper) } /// Append a section of related parameters as rows: a shared slider over `track` (with one marker per non-exposed parameter) sits on the first non-exposed row /// alongside its 60px number input, and the remaining non-exposed rows show only their 60px number input. Exposed parameters render as the standard exposed-row display. -/// Marker positions are clamped to non-decreasing display order so they never visually cross even if the underlying values do. +/// Marker positions are clamped to non-decreasing display order so they never visually cross even if the underlying values do, except where they may overlap. fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorContext, track: &Gradient, params: &[SliderSectionParam], layout: &mut Vec) { // Snapshot exposure and values before the mutable-borrow loop let exposure_and_value: Vec<(bool, f64)> = match get_document_node(node_id, context) { @@ -2034,6 +2082,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte let mut marker_scales = Vec::new(); let mut marker_positions = Vec::new(); let mut marker_between = Vec::new(); + let mut marker_overlaps = Vec::new(); let mut marker_colors_and_links = Vec::new(); for (i, param) in params.iter().enumerate() { let (exposed, value) = exposure_and_value[i]; @@ -2046,13 +2095,21 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte marker_default_positions.push(param.scale.position(param.default_value)); marker_scales.push(param.scale); marker_between.push(param.between_neighbors); + marker_overlaps.push(if next_has_marker { param.overlap_next } else { MarkerOverlap::Never }); marker_colors_and_links.push((param.handle_color, param.pair_with_next && next_has_marker, param.dash_to_next && next_has_marker)); } // Enforce non-decreasing order so markers never visually cross, matching the node's algorithm where shadows takes precedence. // A marker placed between its neighbors bounds nothing here and instead takes its scale position within their settled span. let cyclic = params.iter().any(|param| param.scale.cyclic()); - if !cyclic { + let overlapping = marker_overlaps.iter().any(|&overlap| overlap != MarkerOverlap::Never); + if overlapping { + // Markers allowed to overlap are held only past those they can't pass, each bounded by markers earlier in the list + for i in 0..marker_positions.len() { + let (lower, _) = overlap_bounds(&marker_positions, &marker_overlaps, i); + marker_positions[i] = marker_positions[i].max(lower); + } + } else if !cyclic { let mut floor = 0.; for (position, &between) in marker_positions.iter_mut().zip(&marker_between) { if between { @@ -2073,8 +2130,8 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte let slider_markers: Vec = marker_positions .iter() .zip(&marker_colors_and_links) - .zip(&marker_between) - .map(|((&position, &(handle_color, paired, dashed)), &between)| { + .zip(marker_between.iter().zip(&marker_overlaps)) + .map(|((&position, &(handle_color, paired, dashed)), (&between, &overlap))| { let mut marker = SliderMarker::new(position, 0.5, handle_color); if paired { marker = marker.pair_with_next(); @@ -2085,6 +2142,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte if between { marker = marker.between_neighbors(); } + marker = marker.overlap_next(overlap); marker }) .collect(); @@ -2106,6 +2164,7 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte let marker_scales = marker_scales.clone(); let marker_positions = marker_positions.clone(); let marker_between = marker_between.clone(); + let marker_overlaps = marker_overlaps.clone(); move |update: &SliderInputUpdate| { let i = match update { SliderInputUpdate::MoveMarker { index, .. } | SliderInputUpdate::ResetMarker { index } => *index as usize, @@ -2120,8 +2179,13 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte // The span the marker's scale maps onto: its neighbors' positions when placed between them, otherwise the track between the // nearest markers that bound it, which a marker placed between its neighbors never does let bounding = |j: usize| between || !marker_between[j]; - let left = (0..i).rev().find(|&j| bounding(j)).map_or(0., |j| marker_positions[j]); - let right = (i + 1..marker_positions.len()).find(|&j| bounding(j)).map_or(1., |j| marker_positions[j]); + let (left, right) = if overlapping { + overlap_bounds(&marker_positions, &marker_overlaps, i) + } else { + let left = (0..i).rev().find(|&j| bounding(j)).map_or(0., |j| marker_positions[j]); + let right = (i + 1..marker_positions.len()).find(|&j| bounding(j)).map_or(1., |j| marker_positions[j]); + (left, right) + }; let scale_position = match update { SliderInputUpdate::MoveMarker { position, .. } if between => { @@ -2546,6 +2610,105 @@ pub(crate) fn threshold_inspector(node_id: NodeId, context: &mut NodeInspectorCo layout } +pub(crate) fn blend_if_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec { + use graphene_std::blending_nodes::blend_if::blend_if::*; + + let channel = enum_choice::() + .for_socket(ParameterWidgetsInfo::new(node_id, ChannelInput, true, context)) + .inspector_row(); + + let channel_value = match get_document_node(node_id, context).ok().and_then(|document_node| document_node.input_value(ChannelInput).cloned()) { + Some(TaggedValue::BlendIfChannel(channel)) => channel, + _ => BlendIfChannel::Gray, + }; + let ([content, underlying], track_color): ([[ParameterRef; 4]; 2], Color) = match channel_value { + BlendIfChannel::Gray => ( + [ + [ + ContentFalloffStartInput.into(), + ContentRangeStartInput.into(), + ContentRangeEndInput.into(), + ContentFalloffEndInput.into(), + ], + [ + UnderlyingFalloffStartInput.into(), + UnderlyingRangeStartInput.into(), + UnderlyingRangeEndInput.into(), + UnderlyingFalloffEndInput.into(), + ], + ], + Color::WHITE, + ), + BlendIfChannel::Red => ( + [ + [ + RedContentFalloffStartInput.into(), + RedContentRangeStartInput.into(), + RedContentRangeEndInput.into(), + RedContentFalloffEndInput.into(), + ], + [ + RedUnderlyingFalloffStartInput.into(), + RedUnderlyingRangeStartInput.into(), + RedUnderlyingRangeEndInput.into(), + RedUnderlyingFalloffEndInput.into(), + ], + ], + Color::RED, + ), + BlendIfChannel::Green => ( + [ + [ + GreenContentFalloffStartInput.into(), + GreenContentRangeStartInput.into(), + GreenContentRangeEndInput.into(), + GreenContentFalloffEndInput.into(), + ], + [ + GreenUnderlyingFalloffStartInput.into(), + GreenUnderlyingRangeStartInput.into(), + GreenUnderlyingRangeEndInput.into(), + GreenUnderlyingFalloffEndInput.into(), + ], + ], + Color::GREEN, + ), + BlendIfChannel::Blue => ( + [ + [ + BlueContentFalloffStartInput.into(), + BlueContentRangeStartInput.into(), + BlueContentRangeEndInput.into(), + BlueContentFalloffEndInput.into(), + ], + [ + BlueUnderlyingFalloffStartInput.into(), + BlueUnderlyingRangeStartInput.into(), + BlueUnderlyingRangeEndInput.into(), + BlueUnderlyingFalloffEndInput.into(), + ], + ], + Color::BLUE, + ), + }; + + // Each side's range runs along its channel's levels as a black split handle joined to a white one, with the fully shown range dashed between them + let track = Gradient::from(vec![Color::BLACK, track_color]); + let mut layout = vec![channel]; + for [falloff_start, range_start, range_end, falloff_end] in [content, underlying] { + let params = [ + SliderSectionParam::new(falloff_start, Color::BLACK, 0., MarkerScale::LevelPercent).pair_with_next(), + SliderSectionParam::new(range_start, Color::BLACK, 0., MarkerScale::LevelPercent) + .dash_to_next() + .overlap_next(MarkerOverlap::Freely), + SliderSectionParam::new(range_end, Color::WHITE, 100., MarkerScale::LevelPercent).pair_with_next(), + SliderSectionParam::new(falloff_end, Color::WHITE, 100., MarkerScale::LevelPercent), + ]; + build_shared_slider_section(node_id, context, &track, ¶ms, &mut layout); + } + layout +} + pub(crate) fn vibrance_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec { use graphene_std::raster::vibrance::*; diff --git a/frontend/src/components/widgets/inputs/SliderInput.svelte b/frontend/src/components/widgets/inputs/SliderInput.svelte index c8809ad383..a6e8d181dd 100644 --- a/frontend/src/components/widgets/inputs/SliderInput.svelte +++ b/frontend/src/components/widgets/inputs/SliderInput.svelte @@ -140,7 +140,9 @@ const reorder = allowReorder && allowSelect; let held = position; - if (!reorder && !allowWrap) { + if (!reorder && !allowWrap && markers.some((marker) => marker.overlapNext !== "Never")) { + held = holdWithOverlaps(first, last, position); + } else if (!reorder && !allowWrap) { const lower = neighborBound(first, -1) ?? 0; const upper = (neighborBound(last, 1) ?? 1) - spacing; held = Math.max(lower, Math.min(upper, position)); @@ -156,6 +158,33 @@ return wrap ? held - Math.floor(held) : Math.max(0, Math.min(1 - spacing, held)); } + // Holds markers `first..=last` moving to `position` within the track and each member's bounds from the markers outside the run, as the backend's `overlap_bounds` gives them + function holdWithOverlaps(first: number, last: number, position: number): number { + const outsideRun = (i: number) => i >= 0 && i < markers.length && (i < first || i > last); + const overlap = (i: number) => (i >= 0 && i < markers.length ? markers[i].overlapNext : "Never"); + const boundsBeyond = (near: number, far: number) => (overlap(near) === "NextOnly" || overlap(far) === "NextOnly") && overlap(near) !== "Freely" && overlap(far) !== "Freely"; + + let lower = 0; + let upper = 1; + for (let k = first; k <= last; k += 1) { + const offset = markers[k].position - markers[first].position; + lower = Math.max(lower, -offset); + upper = Math.min(upper, 1 - offset); + + // A neighbor bounds the marker unless they overlap, and past a neighbor overlapping only its next, so does the marker beyond it + const lowerBounds = [overlap(k - 1) === "Never" ? k - 1 : -1, boundsBeyond(k - 1, k - 2) ? k - 2 : -1]; + const upperBounds = [overlap(k) === "Never" ? k + 1 : -1, boundsBeyond(k, k + 1) ? k + 2 : -1]; + lowerBounds.filter(outsideRun).forEach((i) => { + lower = Math.max(lower, markers[i].position - offset); + }); + upperBounds.filter(outsideRun).forEach((i) => { + upper = Math.min(upper, markers[i].position - offset); + }); + } + + return Math.max(lower, Math.min(upper, position)); + } + // The position of the nearest marker past `index` in the direction of `step` that bounds others, skipping any placed between its neighbors since those follow them instead function neighborBound(index: number, step: -1 | 1): number | undefined { for (let i = index + step; i >= 0 && i < markers.length; i += step) { @@ -657,7 +686,10 @@ } $: midpointPositions = diamondPositions(markers, showMidpoints, trackCyclic, trackInterpolation); $: strips = markerSpans(markers, allowWrap, (marker) => marker.pairedWithNext); - $: dashes = markerSpans(markers, allowWrap, (marker) => marker.dashedToNext); + // A dashed link vanishes while the markers it joins have overlapped past each other, leaving no span between them + $: dashes = markerSpans(markers, allowWrap, (marker) => marker.dashedToNext).filter( + ({ index }) => markers[index].overlapNext === "Never" || markers[index + 1].position >= markers[index].position, + ); onMount(() => { document.addEventListener("keydown", deleteShortcut); diff --git a/node-graph/graph-craft/src/document/value.rs b/node-graph/graph-craft/src/document/value.rs index fbc887bc01..9fd5b5e27f 100644 --- a/node-graph/graph-craft/src/document/value.rs +++ b/node-graph/graph-craft/src/document/value.rs @@ -551,6 +551,7 @@ tagged_value! { WarpStyle(graphic_types::WarpStyle), WaveType(graphic_types::WaveType), DisplaceMode(graphic_types::DisplaceMode), + BlendIfChannel(graphic_types::BlendIfChannel), GridType(vector::misc::GridType), GridTopology(vector::misc::GridTopology), ArcType(vector::misc::ArcType), diff --git a/node-graph/interpreted-executor/src/node_registry.rs b/node-graph/interpreted-executor/src/node_registry.rs index c970915cab..c33668f962 100644 --- a/node-graph/interpreted-executor/src/node_registry.rs +++ b/node-graph/interpreted-executor/src/node_registry.rs @@ -29,7 +29,7 @@ use graphene_std::vector::misc::{ use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin}; use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification}; use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type}; -use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution}; +use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution}; use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType}; use node_registry_macros::async_node; use std::collections::HashMap; @@ -303,6 +303,7 @@ fn node_registry() -> HashMap Self { + Self { + falloff_start: 0., + range_start: 0., + range_end: 100., + falloff_end: 100., + } + } +} + +impl BlendRange { + /// How strongly the content shows where the channel is `value`, from 0 to 1. + pub fn weight(&self, value: f64) -> f64 { + let value = value * 100.; + let tolerance = CUTOFF_TOLERANCE * 100.; + + // Each side rises (or falls) across its falloff, with its ends taken in either order + let side = |falloff: f64, range: f64, rising: bool| { + let (low, high) = (falloff.min(range), falloff.max(range)); + match (high - low > tolerance, rising) { + (true, true) => ((value - low) / (high - low)).clamp(0., 1.), + (true, false) => ((high - value) / (high - low)).clamp(0., 1.), + (false, true) => f64::from(value >= low - tolerance), + (false, false) => f64::from(value <= high + tolerance), + } + }; + + side(self.falloff_start, self.range_start, true) * side(self.falloff_end, self.range_end, false) + } + + /// Whether the range shows every level fully, so it changes nothing. + pub fn shows_everything(&self) -> bool { + // Rising then falling, it's full everywhere once it's full at both ends + self.weight(0.) >= 1. && self.weight(1.) >= 1. + } + + /// The weight at each of the [`CHANNEL_LEVELS`] levels, from black to white. + pub fn level_weights(&self) -> Vec { + (0..CHANNEL_LEVELS).map(|level| self.weight(level as f64 / (CHANNEL_LEVELS - 1) as f64)).collect() + } + + fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) { + let key = |parameter: &str| format!("{group}_{parameter}"); + visitor.parameter(&key("falloff_start"), &mut self.falloff_start, 0.); + visitor.parameter(&key("range_start"), &mut self.range_start, 0.); + visitor.parameter(&key("range_end"), &mut self.range_end, 100.); + visitor.parameter(&key("falloff_end"), &mut self.falloff_end, 100.); + } +} + +/// The ranges each channel's levels must fall within for the content to show, which multiply. +#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)] +pub struct ChannelRanges { + pub gray: BlendRange, + pub red: BlendRange, + pub green: BlendRange, + pub blue: BlendRange, +} + +impl ChannelRanges { + /// Each channel with its range, in the order the GPU takes them. + pub fn channels(&self) -> [(BlendIfChannel, &BlendRange); 4] { + [ + (BlendIfChannel::Gray, &self.gray), + (BlendIfChannel::Red, &self.red), + (BlendIfChannel::Green, &self.green), + (BlendIfChannel::Blue, &self.blue), + ] + } + + /// The channels with ranges that hide some levels. + pub fn limiting(&self) -> impl Iterator { + self.channels().into_iter().filter(|(_, range)| !range.shows_everything()) + } + + /// Whether every channel's range shows every level fully, so they change nothing. + pub fn show_everything(&self) -> bool { + self.limiting().next().is_none() + } + + /// How strongly the content shows for a straight gamma-encoded `color`, each channel (and the gray from them) read at its nearest level. + pub fn weight(&self, color: [f64; 3]) -> f64 { + self.channel_weights(color).into_iter().product() + } + + /// The weight each channel's range gives a straight gamma-encoded `color`, in the order of [`Self::channels`], which multiply to its [`Self::weight`]. + pub fn channel_weights(&self, color: [f64; 3]) -> [f64; 4] { + let levels = color.map(channel_level); + let value = |level: usize| level as f64 / (CHANNEL_LEVELS - 1) as f64; + let [red, green, blue] = levels.map(value); + + [self.gray.weight(value(gray_level(levels))), self.red.weight(red), self.green.weight(green), self.blue.weight(blue)] + } + + fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, side: &str) { + self.gray.visit_parameters(visitor, side); + self.red.visit_parameters(visitor, &format!("red_{side}")); + self.green.visit_parameters(visitor, &format!("green_{side}")); + self.blue.visit_parameters(visitor, &format!("blue_{side}")); + } +} + +/// The level from 0 to 255 nearest a channel's `value` from 0 to 1, with halves rounding up as the browsers' 8-bit filters round them. +pub fn channel_level(value: f64) -> usize { + ((value.clamp(0., 1.) * (CHANNEL_LEVELS - 1) as f64 + 0.5).floor() as usize).min(CHANNEL_LEVELS - 1) +} + +/// The gray level of red, green, and blue levels, worked out in whole numbers so a gray exactly between two levels rounds up in every renderer. +pub fn gray_level(levels: [usize; 3]) -> usize { + let weighed: usize = levels.iter().zip(GRAY_PERCENTAGES).map(|(level, percentage)| level * percentage).sum(); + (weighed + 50) / 100 +} + +/// The ranges of Blend If's two sides: those of the content's own colors, which fade the content like its fill, and those of what lies beneath it, which fade all it draws like its opacity. +#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)] +pub struct BlendIfRanges { + pub content: ChannelRanges, + pub underlying: ChannelRanges, +} + +impl BlendIfRanges { + pub(crate) fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) { + self.content.visit_parameters(visitor, "content"); + self.underlying.visit_parameters(visitor, "underlying"); + } +} + +/// How strongly all the content draws shows over a backdrop pixel with the straight gamma-encoded `color` and `alpha`, by the `underlying` ranges. +/// Where nothing lies beneath, nothing is hidden, so the weight eases to full as the backdrop turns transparent. +pub fn underlying_weight(underlying: &ChannelRanges, color: [f64; 3], alpha: f64) -> f64 { + 1. - alpha.clamp(0., 1.) * (1. - underlying.weight(color)) +} + +/// The Blend If rows that act just before the row at `index` among `rows`: once `index` is the first row (or follows a pixel filter, like a blur or adjustment), those from it up to the next pixel filter. +/// So each Blend If reads and fades the content as the pixel filters before it leave it, ahead of the shadows and glows around it, which are knocked out by the content as it then shows. +pub fn blend_ifs_acting_before(rows: &[EffectOperation], index: usize) -> Vec<&BlendIfRanges> { + let follows_pixel_filter = index.checked_sub(1).is_none_or(|previous| processes_pixels(&rows[previous])); + if !follows_pixel_filter { + return Vec::new(); + } + + (rows[index..].iter()) + .take_while(|operation| !processes_pixels(operation)) + .filter_map(|operation| match operation { + EffectOperation::BlendIf(ranges) => Some(ranges.as_ref()), + _ => None, + }) + .collect() +} + +/// Whether a solid paint overlay at `index` among `rows` may mix into the content's own colors ahead of the other effects. +/// Not where a Blend If reading those colors acts in the same stretch between pixel filters, since it reads them before the overlay paints. +pub fn paint_overlay_folds(rows: &[EffectOperation], index: usize) -> bool { + let start = rows[..index].iter().rposition(processes_pixels).map_or(0, |previous| previous + 1); + let end = rows[index..].iter().position(processes_pixels).map_or(rows.len(), |next| index + next); + !fades_content(&rows[start..end]) +} + +/// Whether a Blend If among the `operations` fades the content by its own colors, as a fill varying across it does. +pub fn fades_content(operations: &[EffectOperation]) -> bool { + operations + .iter() + .any(|operation| matches!(operation, EffectOperation::BlendIf(ranges) if !ranges.content.show_everything())) +} + +/// Whether a row processes the pixels of everything before it, as a pixel filter (like a blur or adjustment) that changes something does, which ends a stretch of rows that Blend Ifs act at the start of. +fn processes_pixels(operation: &EffectOperation) -> bool { + is_pixel_filter(operation) && !operation.changes_nothing() +} + +/// The ranges beneath of each Blend If row among the `operations` that hides anything by what lies beneath, which multiply. +pub fn underlying_ranges<'a>(operations: impl IntoIterator) -> Vec { + (operations.into_iter()) + .filter_map(|operation| match operation { + EffectOperation::BlendIf(ranges) if !ranges.underlying.show_everything() => Some(ranges.underlying), + _ => None, + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn range(falloff_start: f64, range_start: f64, range_end: f64, falloff_end: f64) -> BlendRange { + BlendRange { + falloff_start, + range_start, + range_end, + falloff_end, + } + } + + /// A level from 0 to 255 as a channel value. + fn level(level: f64) -> f64 { + level / 255. + } + + #[test] + fn ranges_fade_linearly_across_their_falloffs() { + let percent = |level: f64| level / 255. * 100.; + let soft = range(percent(64.), percent(128.), percent(192.), percent(224.)); + + assert_eq!(soft.weight(level(32.)), 0.); + assert!((soft.weight(level(96.)) - 0.5).abs() < 1e-12); + assert_eq!(soft.weight(level(160.)), 1.); + assert!((soft.weight(level(208.)) - 0.5).abs() < 1e-12); + assert_eq!(soft.weight(level(240.)), 0.); + } + + #[test] + fn unsplit_cutoffs_keep_the_level_they_lie_on() { + // For PSD interop, black at 64 keeps 64 and white at 192 keeps 192, given in percent as they'd be imported + let percent = |level: f64| level / 255. * 100.; + let hard = range(percent(64.), percent(64.), percent(192.), percent(192.)); + + assert_eq!(hard.weight(level(63.)), 0.); + assert_eq!(hard.weight(level(64.)), 1.); + assert_eq!(hard.weight(level(192.)), 1.); + assert_eq!(hard.weight(level(193.)), 0.); + } + + #[test] + fn the_default_range_shows_everything() { + assert!(BlendRange::default().shows_everything()); + assert!(ChannelRanges::default().show_everything()); + assert!(!range(0., 10., 100., 100.).shows_everything()); + assert!(!range(0., 0., 100., 99.).shows_everything()); + } + + #[test] + fn channels_multiply_with_gray_weighing_the_color() { + let ranges = ChannelRanges { + gray: range(0., 50., 100., 100.), + red: range(0., 0., 50., 100.), + ..Default::default() + }; + + // The gray of a light pink shows fully, but its red at full strength fades it to nothing + assert_eq!(ranges.weight([1., 0.5, 0.5]), 0.); + // A dark red's gray, read at its own level, lies partway up its falloff, while its red lies within its range + let red = level(77.); + let gray = gray_level([77, 0, 0]) as f64 / 255.; + let expected = (gray * 100. / 50.) * ((100. - red * 100.) / 50.).min(1.); + assert!((ranges.weight([red, 0., 0.]) - expected).abs() < 1e-12); + } + + #[test] + fn nothing_beneath_hides_nothing() { + let underlying = ChannelRanges { + gray: range(50., 50., 100., 100.), + ..Default::default() + }; + + assert_eq!(underlying_weight(&underlying, [0.; 3], 0.), 1.); + assert_eq!(underlying_weight(&underlying, [0.; 3], 1.), 0.); + assert!((underlying_weight(&underlying, [0.; 3], 0.25) - 0.75).abs() < 1e-12); + } + + #[test] + fn blend_ifs_act_after_the_blurs_and_adjustments_before_them() { + let blend_if = EffectOperation::BlendIf(Box::default()); + let blur = EffectOperation::Blur { + radius_mask: Default::default(), + radius: 2., + box_blur: false, + gamma: false, + }; + let shadow = EffectOperation::default_for(crate::EffectKind::DropShadow); + let rows = [shadow.clone(), blend_if.clone(), blur, shadow, blend_if]; + + // The first acts ahead of the shadow before it, and the second just after the blur, ahead of the shadow between them + let acting: Vec = (0..rows.len()).map(|index| blend_ifs_acting_before(&rows, index).len()).collect(); + assert_eq!(acting, [1, 0, 0, 1, 0]); + + // A blur of no radius changes nothing, so it starts no stretch of its own + let no_blur = EffectOperation::Blur { + radius_mask: Default::default(), + radius: 0., + box_blur: false, + gamma: false, + }; + let rows = [EffectOperation::default_for(crate::EffectKind::DropShadow), no_blur, EffectOperation::BlendIf(Box::default())]; + assert_eq!(blend_ifs_acting_before(&rows, 0).len(), 1); + } + + #[test] + fn grays_between_two_levels_round_up() { + // Blue at 250 weighs 27.5 levels of gray, and 249 weighs 27.39 + assert_eq!(gray_level([0, 0, 250]), 28); + assert_eq!(gray_level([0, 0, 249]), 27); + assert_eq!(gray_level([5, 0, 0]), 2); + assert_eq!(gray_level([255, 255, 255]), 255); + } + + #[test] + fn paint_overlays_keep_their_strength_where_a_blend_if_reads_the_content_beside_them() { + let overlay = EffectOperation::Adjustment(crate::Adjustment::ColorOverlay { + color: core_types::Color::RED, + blend_mode: core_types::blending::BlendMode::Normal, + opacity: 100., + }); + let mut ranges = BlendIfRanges::default(); + ranges.content.gray.range_start = 40.; + let blend_if = EffectOperation::BlendIf(Box::new(ranges)); + let blur = EffectOperation::Blur { + radius_mask: Default::default(), + radius: 2., + box_blur: false, + gamma: false, + }; + + assert!(!paint_overlay_folds(&[overlay.clone(), blend_if.clone(), blur.clone()], 0)); + assert!(paint_overlay_folds(&[overlay.clone(), blur.clone(), blend_if.clone()], 0)); + assert!(paint_overlay_folds(&[blend_if, blur, overlay.clone()], 2)); + assert!(paint_overlay_folds(&[overlay, EffectOperation::BlendIf(Box::default())], 0)); + } +} diff --git a/node-graph/libraries/graphic-types/src/effect_layers.rs b/node-graph/libraries/graphic-types/src/effect_layers.rs index 3ef6bf00ea..6dc32ddc43 100644 --- a/node-graph/libraries/graphic-types/src/effect_layers.rs +++ b/node-graph/libraries/graphic-types/src/effect_layers.rs @@ -65,8 +65,11 @@ pub struct EffectLayers { /// How many of the effects, from the first, are carried out within the content's image. pub flattened: usize, pub layers: Vec, - /// The rows from the first mask after every other effect to the end, which fade each finished layer at each pixel like the item's opacity. Empty where those masks flatten what's before them instead. + /// The rows from the first mask after every other effect to the end: masks, and Blend Ifs reading only what lies beneath, which fade each finished layer at each pixel like the item's opacity. + /// Empty where those masks flatten what's before them instead. pub trailing_masks: Range, + /// Whether a Blend If fades every layer by the colors of what lies beneath. + pub fades_by_underlying: bool, } impl EffectLayers { @@ -76,9 +79,10 @@ impl EffectLayers { let operations: Vec = effects.operations().collect(); let blend_mode = if blend_mode.to_svg_style_name().is_some() { blend_mode } else { BlendMode::Normal }; - // Normal content at full fill hides what lies beneath its share, so its interior pieces blend with it alone, in any mode, within its own layer + // Normal content at full fill hides what lies beneath its share, so its interior pieces blend with it alone, in any mode, within its own layer. + // A Blend If fading the content by its colors acts as a fill below full wherever it hides any. let shares_content = blend_mode == BlendMode::Normal; - let blends_into_content = shares_content && fill >= 1.; + let blends_into_content = shares_content && fill >= 1. && !crate::blend_if::fades_content(&operations); // The masks after every other effect fade the layers rather than the content's image, so they flatten nothing before them let no_rows = operations.len()..operations.len(); @@ -174,8 +178,10 @@ 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, 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 fades_by_underlying = !crate::blend_if::underlying_ranges(&operations).is_empty(); + + // 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 reads what lies beneath + if blends_into_content && backdrop.is_empty() && !fades_by_underlying && matches!(layers.as_slice(), [layer] if layer.blend_mode == BlendMode::Normal) { let content = EffectLayer { blend_mode: BlendMode::Normal, parts: vec![LayerPart::Content], @@ -184,6 +190,7 @@ impl EffectLayers { flattened: operations.len(), layers: vec![content], trailing_masks: no_rows, + fades_by_underlying, }; } @@ -192,7 +199,12 @@ impl EffectLayers { content_layer.parts.splice(0..0, backdrop); } - Self { flattened, layers, trailing_masks } + Self { + flattened, + layers, + trailing_masks, + fades_by_underlying, + } } /// Like [`Self::plan`], for effects stamped in more than one space (see [`Effects::runs`]), as renderers draw them. @@ -214,8 +226,13 @@ impl EffectLayers { planned } - /// Whether a layered piece reads what lies beneath the content. + /// Whether a layered piece, or a Blend If fading the layers, reads what lies beneath the content. pub fn reads_backdrop(&self) -> bool { + self.fades_by_underlying || self.reads_around_backdrop() + } + + /// Whether a layered piece reads what lies around each pixel beneath the content, as a background blur does, where a Blend If reads only the pixel itself. + pub fn reads_around_backdrop(&self) -> bool { (self.layers.iter().flat_map(|layer| &layer.parts)).any(|part| matches!(part, LayerPart::Piece(piece) if piece.place == PiecePlace::Backdrop)) } @@ -283,9 +300,11 @@ 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()) + effects.operations().any(|operation| match &operation { + EffectOperation::BackgroundBlur { .. } => !operation.changes_nothing(), + EffectOperation::BlendIf(ranges) => !ranges.underlying.show_everything(), + _ => false, + }) } /// Whether an effect row can draw as layered pieces, rather than being carried out within the content's image. @@ -335,31 +354,39 @@ fn merged_into_content(operations: &[EffectOperation]) -> usize { .map_or(0, |index| index + 1) } -/// The effects carried out in the content's own image, which make a clipping base's shape: every row through the last pixel filter, which merges the pieces before it into that image, then the trailing masks fading it. +/// The effects carried out in the content's own image, which make a clipping base's shape: every row through the last pixel filter, which merges the pieces before it into that image, then the trailing masks fading it, leaving out each Blend If that reads only what lies beneath. /// The other pieces are cast from or laid over the content, so for PSD interop they don't shape a clip. Borrowed if nothing is left out. pub fn content_image_effects(effects: &Effects) -> Cow<'_, Effects> { let operations: Vec = effects.operations().collect(); let trailing_masks = trailing_masks(&operations); let merged = merged_into_content(&operations[..trailing_masks.start]); - if merged == trailing_masks.start { + + // A Blend If reading only what lies beneath fades the finished layers wherever it sits, so it shapes no clip (and it's the only kind the trailing masks can hold) + let kept: Vec = (0..merged).chain(trailing_masks).filter(|&index| !reads_only_beneath(&operations[index])).collect(); + if kept.len() == operations.len() { return Cow::Borrowed(effects); } - Cow::Owned(Effects((0..merged).chain(trailing_masks).filter_map(|index| effects.0.clone_item(index)).collect())) + Cow::Owned(Effects(kept.into_iter().filter_map(|index| effects.0.clone_item(index)).collect())) } /// The rows from the first mask after every other effect that changes something to the end, or none without such a mask or an effect before it. +/// A Blend If reading only what lies beneath is passed over, since it fades the finished layers as the masks do, but one reading the content's colors counts as another effect. fn trailing_masks(operations: &[EffectOperation]) -> Range { let no_rows = operations.len()..operations.len(); let is_mask = |operation: &EffectOperation| matches!(operation, EffectOperation::Mask { .. }); + let is_other = |operation: &EffectOperation| !operation.changes_nothing() && !is_mask(operation) && !reads_only_beneath(operation); - let Some(last_other) = operations.iter().rposition(|operation| !operation.changes_nothing() && !is_mask(operation)) else { - return no_rows; - }; - let first_mask = operations[last_other + 1..].iter().position(|operation| !operation.changes_nothing()); + let Some(last_other) = operations.iter().rposition(is_other) else { return no_rows }; + let first_mask = operations[last_other + 1..].iter().position(|operation| !operation.changes_nothing() && is_mask(operation)); first_mask.map_or(no_rows, |offset| last_other + 1 + offset..operations.len()) } +/// Whether the effect is a Blend If without ranges of the content's own colors, so it reads only what lies beneath (or changes nothing). +fn reads_only_beneath(operation: &EffectOperation) -> bool { + matches!(operation, EffectOperation::BlendIf(ranges) if ranges.content.show_everything()) +} + /// The pieces the effect at `index` draws, each with the mode it blends by, leaving out those painting no color. fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendMode)> { // Only a drop shadow can show through the content @@ -442,6 +469,7 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM | EffectOperation::HighPass { .. } | EffectOperation::AddNoise { .. } | EffectOperation::Dissolve { .. } + | EffectOperation::BlendIf(_) | EffectOperation::Adjustment(_) => Vec::new(), }; pieces.into_iter().flatten().collect() @@ -815,6 +843,71 @@ mod tests { assert_eq!(parts(&layers)[content_layer], [Some((1, 0, PiecePlace::Backdrop)), None]); } + #[test] + fn blend_ifs_draw_no_pieces_and_read_the_backdrop_only_by_their_ranges_beneath() { + let mut ranges = crate::blend_if::BlendIfRanges::default(); + ranges.content.gray.range_start = 50.; + let content_only = Effects::from_operations([EffectOperation::BlendIf(Box::new(ranges))]); + let layers = EffectLayers::plan(&content_only, BlendMode::Normal, 1., true); + assert_eq!(layers.layers.len(), 1); + assert!(!layers.reads_backdrop() && !effects_read_backdrop(&content_only)); + + ranges.underlying.blue.falloff_end = 50.; + let beneath = Effects::from_operations([EffectOperation::BlendIf(Box::new(ranges))]); + let layers = EffectLayers::plan(&beneath, BlendMode::Normal, 1., true); + assert_eq!(layers.layers[0].parts, [LayerPart::Content]); + assert!(layers.reads_backdrop() && effects_read_backdrop(&beneath)); + + // Fading the content by its colors, it splits a blended interior piece as a partial fill does, even at a full fill + let screen = Effects::from_operations([inner_shadow(RED.with_alpha(0.75), BlendMode::Screen), EffectOperation::BlendIf(Box::new(ranges))]); + let layers = EffectLayers::plan(&screen, BlendMode::Normal, 1., true); + assert_eq!(modes(&layers), [BlendMode::Screen, BlendMode::Normal]); + assert!(layers.reads_through_share()); + } + + #[test] + fn blend_ifs_after_trailing_masks_leave_them_trailing() { + let mut ranges = crate::blend_if::BlendIfRanges::default(); + ranges.underlying.gray.range_start = 50.; + let blend_if = EffectOperation::BlendIf(Box::new(ranges)); + let kinds = |effects: &Effects| -> Vec { content_image_effects(effects).operations().map(|operation| operation.kind()).collect() }; + + // After the mask as before it, the shadow keeps its layer and mode while the mask fades each layer, and a clipping base takes the mask alone + for operations in [ + [drop_shadow(RED, BlendMode::Multiply), mask(), blend_if.clone()], + [drop_shadow(RED, BlendMode::Multiply), blend_if.clone(), mask()], + ] { + let effects = Effects::from_operations(operations); + let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true); + assert_eq!(layers.flattened, 0, "{:?}", effects.operations().map(|operation| operation.kind()).collect::>()); + assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]); + assert!(layers.fades_layers()); + assert_eq!(kinds(&effects), [EffectKind::Mask]); + } + + // With nothing else to trail, a clipping base still takes the mask alone in either order + assert_eq!(kinds(&Effects::from_operations([blend_if.clone(), mask()])), [EffectKind::Mask]); + assert_eq!(kinds(&Effects::from_operations([mask(), blend_if])), [EffectKind::Mask]); + } + + #[test] + fn blend_ifs_reading_the_content_after_masks_keep_them_from_trailing() { + let mut ranges = crate::blend_if::BlendIfRanges::default(); + ranges.content.gray.range_start = 50.; + let blend_if = EffectOperation::BlendIf(Box::new(ranges)); + let kinds = |operations: Vec| -> Vec { content_image_effects(&Effects::from_operations(operations)).operations().map(|operation| operation.kind()).collect() }; + + // The mask merges the shadow flattened before it into the content's image, which the Blend If then reads + let effects = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), mask(), blend_if.clone()]); + let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true); + assert_eq!(layers.flattened, 2); + assert!(!layers.fades_layers()); + + // A clipping base takes the mask alone, with the Blend If before it or after it + assert_eq!(kinds(vec![blend_if.clone(), mask()]), [EffectKind::Mask]); + assert_eq!(kinds(vec![mask(), blend_if]), [EffectKind::Mask]); + } + #[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); diff --git a/node-graph/libraries/graphic-types/src/effects.rs b/node-graph/libraries/graphic-types/src/effects.rs index 4c90eabf7a..1c41d3eeee 100644 --- a/node-graph/libraries/graphic-types/src/effects.rs +++ b/node-graph/libraries/graphic-types/src/effects.rs @@ -4,6 +4,7 @@ use crate::Graphic; use crate::adjustment::Adjustment; +use crate::blend_if::BlendIfRanges; use crate::filters::{Convolution, NoiseDistribution}; use crate::masks::{MaskMode, mask_feather_sigma}; use crate::parameters::{ParameterVisitor, ReadParameters, WriteParameters}; @@ -93,6 +94,8 @@ pub enum EffectKind { ColorHalftone, /// Blurs what lies beneath the content within its silhouette, as if seen through frosted glass. BackgroundBlur, + /// Shows the content only where its own colors, and those of what lies beneath it, fall within ranges of their channels. + BlendIf, // The adjustments, which change each color of the content on its own, as their nodes of the same names do Desaturate, GammaCorrection, @@ -151,6 +154,7 @@ impl std::fmt::Display for EffectKind { Self::Pixelate => "Pixelate", Self::ColorHalftone => "Color Halftone", Self::BackgroundBlur => "Background Blur", + Self::BlendIf => "Blend If", Self::Desaturate => "Desaturate", Self::GammaCorrection => "Gamma Correction", Self::MakeOpaque => "Make Opaque", @@ -1240,6 +1244,8 @@ pub enum EffectOperation { /// Whether to blend the colors with their gamma encoding rather than in linear light. gamma: bool, }, + /// Fades the content by how its own colors fall within ranges, as its fill does, and everything it draws by how the colors beneath fall within others, as its opacity does. + BlendIf(Box), Adjustment(Adjustment), } @@ -1298,6 +1304,7 @@ impl EffectOperation { Self::Pixelate { .. } => EffectKind::Pixelate, Self::ColorHalftone { .. } => EffectKind::ColorHalftone, Self::BackgroundBlur { .. } => EffectKind::BackgroundBlur, + Self::BlendIf(_) => EffectKind::BlendIf, Self::Adjustment(adjustment) => adjustment.kind(), } } @@ -1380,6 +1387,7 @@ impl EffectOperation { // The four neighbors lie a fixed distance away, so only the blur needs a radius Self::Sharpen { amount, radius, edges_only, .. } => *amount <= 0. || (!*edges_only && *radius <= 0.), Self::MinimumMaximum { radius, .. } => *radius <= 0., + Self::BlendIf(ranges) => ranges.content.show_everything() && ranges.underlying.show_everything(), } } @@ -1415,7 +1423,7 @@ impl EffectOperation { | Self::Outline { .. } | Self::BevelAndEmboss { .. } | Self::Feather { .. } => false, - Self::PaintOverlay { .. } | Self::Mask { .. } | Self::BackgroundBlur { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => false, + Self::PaintOverlay { .. } | Self::Mask { .. } | Self::BackgroundBlur { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::BlendIf(_) | Self::Adjustment(_) => false, } } @@ -1483,7 +1491,7 @@ impl EffectOperation { Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } => self.displacement_reach() + 1., // Within the frame they paint the content's own cells or dots, reading a cell's or a dot's area around each point there, which `Effects::source_region` finds Self::Pixelate { .. } | Self::ColorHalftone { .. } => 0., - Self::PaintOverlay { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => 0., + Self::PaintOverlay { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::BlendIf(_) | Self::Adjustment(_) => 0., } } @@ -1618,7 +1626,7 @@ impl EffectOperation { offset, phase, } => [radius, red_angle, green_angle, blue_angle, &mut offset.x, &mut offset.y, phase].into_iter().for_each(finite), - Self::PaintOverlay { .. } | Self::ConvolutionKernel { .. } | Self::FindEdges | Self::Adjustment(_) => {} + Self::PaintOverlay { .. } | Self::ConvolutionKernel { .. } | Self::FindEdges | Self::BlendIf(_) | Self::Adjustment(_) => {} } self } @@ -1830,6 +1838,7 @@ impl EffectOperation { box_blur: false, gamma: false, }, + EffectKind::BlendIf => Self::BlendIf(Box::default()), 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. }), @@ -2217,6 +2226,7 @@ impl EffectOperation { visitor.parameter("offset", offset, DVec2::ZERO); visitor.parameter("phase", phase, 0.); } + Self::BlendIf(ranges) => ranges.visit_parameters(visitor), Self::Adjustment(adjustment) => adjustment.visit_parameters(visitor), } } @@ -2487,10 +2497,16 @@ mod tests { offset: DVec2::new(-4., 6.), phase: 25., }, + EffectOperation::BlendIf(Box::new({ + let mut ranges = BlendIfRanges::default(); + ranges.content.gray.range_start = 25.; + ranges.underlying.red.falloff_end = 80.; + ranges + })), ]; - for operation in operations { - assert_eq!(Effect::new(&operation).operation(), operation); + 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 @@ -2512,6 +2528,13 @@ mod tests { 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"); + + // Blend If's ranges ride attributes named like its node's inputs + let blend_if = operations.iter().find(|operation| operation.kind() == EffectKind::BlendIf).unwrap(); + let row = Effect::new(blend_if); + assert_eq!(row.0.attribute::("content_range_start"), Some(&25.)); + assert_eq!(row.0.attribute::("red_underlying_falloff_end"), Some(&80.)); + assert_eq!(row.0.attributes().iter_any().count(), 2); } #[test] diff --git a/node-graph/libraries/graphic-types/src/lib.rs b/node-graph/libraries/graphic-types/src/lib.rs index f2313bc9a6..8067c649f8 100644 --- a/node-graph/libraries/graphic-types/src/lib.rs +++ b/node-graph/libraries/graphic-types/src/lib.rs @@ -1,6 +1,7 @@ pub mod adjustment; pub mod appearance; pub mod artboard; +pub mod blend_if; pub mod effect_layers; pub mod effects; pub mod filters; @@ -20,6 +21,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 blend_if::BlendIfChannel; pub use effects::{ BevelDirection, BevelStyle, BevelTechnique, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique, MinimumMaximumMode, linked_to_content, paint_with_envelope_effects, stamp_effect, stamped_transform, diff --git a/node-graph/libraries/graphic-types/src/resampling.rs b/node-graph/libraries/graphic-types/src/resampling.rs index 128cc1bdd0..1329e32feb 100644 --- a/node-graph/libraries/graphic-types/src/resampling.rs +++ b/node-graph/libraries/graphic-types/src/resampling.rs @@ -1746,6 +1746,7 @@ impl EffectOperation { | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::BackgroundBlur { .. } + | Self::BlendIf(_) | Self::Adjustment(_) => false, } } diff --git a/node-graph/libraries/raster-kernels/src/raster_effects.rs b/node-graph/libraries/raster-kernels/src/raster_effects.rs index 643474d971..844e2abb8e 100644 --- a/node-graph/libraries/raster-kernels/src/raster_effects.rs +++ b/node-graph/libraries/raster-kernels/src/raster_effects.rs @@ -8,7 +8,7 @@ use crate::generators::pattern_sampler; use crate::layer_blending::blend_layer; use crate::masks::{feather_strength, mask_strength, masked, masked_box_blur_luminances, masked_radius_blur, masked_radius_blur_codes, variable_box_blur}; use crate::resample_kernels::{MotionBlurShear, displaced, frame_warped, halftoned, motion_blurred, pixelated, radial_blurred}; -use crate::value_effects::{adjusted_gradient, adjustments, evaluate_gradient_effects, filled_color}; +use crate::value_effects::{adjusted_gradient_with_blend_ifs, adjustments, content_blend_ifs, evaluate_gradient_effects, filled_color_with_blend_ifs}; use crate::warp_kernels::WarpRasterizer; use core_types::FallibleVec2Operations; use core_types::blending::BlendMode; @@ -19,6 +19,7 @@ use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFOR use glam::{DAffine2, DMat2, DVec2}; use graphic_types::Graphic; use graphic_types::adjustment::Adjustment; +use graphic_types::blend_if::{ChannelRanges, blend_ifs_acting_before, paint_overlay_folds}; use graphic_types::effect_layers::{EffectLayers, LayerPart, PiecePlace}; use graphic_types::effects::{ BevelDirection, BevelStyle, BevelTechnique, EffectCapture, EffectOperation, Effects, GlowFill, GlowSource, GlowTechnique, OutlineFill, bevel_light, contour_gradient_span, effect_space, @@ -31,6 +32,7 @@ use graphic_types::resampling::{DisplacementField, EffectFrame, FrameWarp, Halft use raster_types::parallel_rows::fill_rows; use raster_types::{CPU, Image, Raster}; use std::collections::HashMap; +use std::ops::Range; use vector_types::gradient::{Gradient, GradientForm, GradientSettings, GradientSpread}; mod styles; @@ -118,9 +120,22 @@ fn evaluate(raster: &Raster, transform: DAffine2, effects: &Effects, fill: }) .collect(); + // Each row's run and its place in it, which Blend Ifs act within as the renderers' runs do + let operations: Vec = rows.iter().map(|(operation, ..)| operation.clone()).collect(); + let runs: Vec> = effects.runs().into_iter().map(|(_, rows)| rows).collect(); + let in_run = |index: usize| match runs.iter().find(|rows| rows.contains(&index)) { + Some(rows) => (&operations[rows.clone()], index - rows.start), + None => (&operations[..], index), + }; + // Unless a fill fades them first, leading adjustments flattened into the image change its own colors, keeping even transparent pixels' colors let layers = EffectLayers::plan_runs(effects, BlendMode::Normal, fill, true); - let leading_adjustments = rows.iter().take(layers.flattened).take_while(|_| fill == 1.).map_while(|(operation, ..)| match operation { + let overlay_folds = |index: usize| { + let (run, row) = in_run(index); + paint_overlay_folds(run, row) + }; + let leading_adjustments = (rows.iter().enumerate().take(layers.flattened).take_while(|_| fill == 1.)).map_while(|(index, (operation, ..))| match operation { + EffectOperation::Adjustment(Adjustment::ColorOverlay { .. }) if !overlay_folds(index) => None, EffectOperation::Adjustment(adjustment) => Some(adjustment), _ => None, }); @@ -181,9 +196,13 @@ fn evaluate(raster: &Raster, transform: DAffine2, effects: &Effects, fill: let mut pieces: HashMap> = HashMap::new(); // How much the trailing masks together show of each finished layer let mut layer_fade: Option> = None; + // How strongly the Blend Ifs so far show the content, which fades it like a fill varying across it + let mut blend_if_weight: Option> = None; // Each run after the first takes the result of those before it as its content at full strength, like the renderers' nested runs let mut run_fill = fill; + // The leading adjustments carried out on the image's colors still start stretches that Blend Ifs act at the start of + let mut rows_reached = 0; for (index, &(ref operation, effect_to_pixels, starts_later_run)) in rows.iter().enumerate().skip(leading) { if starts_later_run { full = match (filled.take(), beneath.take()) { @@ -192,7 +211,23 @@ fn evaluate(raster: &Raster, transform: DAffine2, effects: &Effects, fill: (None, None) => full, }; run_fill = 1.; + blend_if_weight = None; } + + let acting_blend_ifs = (rows_reached..=index).flat_map(|row| { + let (run, row) = in_run(row); + blend_ifs_acting_before(run, row) + }); + for ranges in acting_blend_ifs.filter(|ranges| !ranges.content.show_everything()) { + let weight = blend_if_weights(&full, &ranges.content); + filled = Some(filled.as_ref().unwrap_or(&full).zip(&weight, |pixel, weight| pixel.map(|channel| channel * weight))); + blend_if_weight = Some(match blend_if_weight { + Some(previous) => previous.zip(&weight, |previous, weight| previous * weight), + None => weight, + }); + } + rows_reached = index + 1; + if operation.changes_nothing() { continue; } @@ -210,6 +245,7 @@ fn evaluate(raster: &Raster, transform: DAffine2, effects: &Effects, fill: let layered = index >= layers.flattened; let piece = |plane: usize| layered.then_some(EffectCapture { index, plane }); let knockout_fill = if layered { 1. } else { run_fill }; + let knockout_weight = blend_if_weight.as_ref().filter(|_| !layered); match *operation { EffectOperation::Blur { radius, box_blur, gamma, .. } if !operation.varies_blur_radius() => { @@ -273,7 +309,7 @@ fn evaluate(raster: &Raster, transform: DAffine2, effects: &Effects, fill: let silhouette = full.map(|[_, _, _, alpha]| alpha).shifted(offset.x, offset.y); let strength = cast(silhouette, size, spread, GlowTechnique::Softer, 100., contour, pixels_per_length); let shadow = tinted(&strength, color); - let shadow = if knockout { knocked_out(shadow, &full, knockout_fill) } else { shadow }; + let shadow = if knockout { knocked_out(shadow, &full, knockout_fill, knockout_weight) } else { shadow }; place_beneath(&mut pieces, piece(0), &mut beneath, shadow); } EffectOperation::OuterGlow { @@ -293,7 +329,7 @@ fn evaluate(raster: &Raster, transform: DAffine2, effects: &Effects, fill: let strength = shaped(raw.clone(), range, contour); let grain = styles::GlowGrain::new(&paint, noise, jitter, seed, pixels_to_effect); let fades = matches!(paint, GlowFill::Gradient { .. }) || noise > 0.; - let glow = knocked_out(glow_tint(&paint, &strength, &raw, fades, grain.as_ref()), &full, knockout_fill); + let glow = knocked_out(glow_tint(&paint, &strength, &raw, fades, grain.as_ref()), &full, knockout_fill, knockout_weight); place_beneath(&mut pieces, piece(0), &mut beneath, glow); } EffectOperation::InnerShadow { @@ -411,7 +447,7 @@ fn evaluate(raster: &Raster, transform: DAffine2, effects: &Effects, fill: // The band outside lies beneath the content like a shadow, and the band inside over it like an inner shadow if let Some(band) = &bands.outside { - let band = knocked_out(painted(band), &full, knockout_fill); + let band = knocked_out(painted(band), &full, knockout_fill, knockout_weight); place_beneath(&mut pieces, piece(0), &mut beneath, band); } if let Some(band) = &bands.inside { @@ -492,7 +528,7 @@ fn evaluate(raster: &Raster, transform: DAffine2, effects: &Effects, fill: place_within(&mut pieces, piece(plane), &mut full, &mut filled, tinted(&amount, color), blend_mode); } for (plane, (amount, (color, _))) in outside.into_iter().flatten().zip(colors).enumerate() { - let slope = knocked_out(tinted(&amount, color), &full, knockout_fill); + let slope = knocked_out(tinted(&amount, color), &full, knockout_fill, knockout_weight); place_beneath(&mut pieces, piece(plane + 2), &mut beneath, slope); } } @@ -511,8 +547,8 @@ fn evaluate(raster: &Raster, 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 { .. } => {} + // An image of its own has nothing beneath it to blur, or for Blend If to read, which fades the content where it acts + EffectOperation::BackgroundBlur { .. } | EffectOperation::BlendIf(_) => {} // 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)); @@ -672,7 +708,7 @@ fn evaluate(raster: &Raster, transform: DAffine2, effects: &Effects, fill: let Some(frame) = &frame else { continue }; let Some(screens) = HalftoneScreen::of(operation, frame) else { continue }; - // Each pixel's share of the content that the fill left fades the printed dots, rather than printing the faded content's fainter dots + // Each pixel's share of the content that the fill and the Blend Ifs left fades the printed dots, rather than printing the faded content's fainter dots merge_beneath(&mut full, &mut filled, &mut beneath); let shares = filled.as_ref().map(|filled| crate::filter_kernels::fill_shares(&full, filled)); let unfaded = filled.map(|filled| crate::filter_kernels::at_full_coverage(&filled, &full)); @@ -881,19 +917,31 @@ fn tinted(coverage: &Plane, color: Color) -> Plane<[f32; 4]> { coverage.map(|coverage| color.map(|channel| channel * coverage)) } -/// A tinted image of what lies beneath, hidden behind the full-strength content where the content covers it as strongly as `fill`. -fn knocked_out(tinted: Plane<[f32; 4]>, full_content: &Plane<[f32; 4]>, fill: f32) -> Plane<[f32; 4]> { - if fill >= 1. { +/// A tinted image of what lies beneath, hidden behind the full-strength content where the content covers it as strongly as `fill`, times the Blend If weight if any fades it. +fn knocked_out(tinted: Plane<[f32; 4]>, full_content: &Plane<[f32; 4]>, fill: f32, blend_if_weight: Option<&Plane>) -> Plane<[f32; 4]> { + if fill >= 1. && blend_if_weight.is_none() { return tinted; } // The faded content shows what's beneath through 1 - fill × alpha of it, of which only 1 - alpha may show this - tinted.zip(full_content, |tinted, content| { - let shown = (1. - content[3]) / (1. - fill * content[3]).max(f32::EPSILON); + let covering = match blend_if_weight { + Some(weight) => full_content.zip(weight, |content, weight| [content[3], weight * fill, 0., 0.]), + None => full_content.map(|content| [content[3], fill, 0., 0.]), + }; + tinted.zip(&covering, |tinted, [alpha, fill, ..]| { + let shown = (1. - alpha) / (1. - fill * alpha).max(f32::EPSILON); tinted.map(|channel| channel * shown) }) } +/// How strongly Blend If's `ranges` show each pixel of a premultiplied gamma-encoded `image`, by its straight color. +fn blend_if_weights(image: &Plane<[f32; 4]>, ranges: &ChannelRanges) -> Plane { + image.map(|[red, green, blue, alpha]| { + let straight = if alpha > 0. { [red, green, blue].map(|channel| (channel / alpha) as f64) } else { [0.; 3] }; + ranges.weight(straight) as f32 + }) +} + /// Places a tinted image beneath the content: as the layered `piece` if it names one, or else stacked over what lies `beneath` the content so far. fn place_beneath(pieces: &mut HashMap>, piece: Option, beneath: &mut Option>, tinted: Plane<[f32; 4]>) { match piece { @@ -1192,8 +1240,9 @@ fn paint_sampler(paint: &Graphic) -> Option Color + Sync + // The fill fades the color beneath its paint overlays, which paint over it at full strength, as the renderers fill an endless color let opacity = item.attribute_cloned_or::(ATTR_OPACITY, 1.) as f32; let fill = item.attribute_cloned_or::(ATTR_OPACITY_FILL, 1.) as f32; - let adjustments = item.attribute::(ATTR_EFFECTS).map(adjustments).unwrap_or_default(); - let color = filled_color(*item.element(), &adjustments, fill); + let effects = item.attribute::(ATTR_EFFECTS); + let (adjustments, blend_ifs) = (effects.map(adjustments).unwrap_or_default(), effects.map(content_blend_ifs).unwrap_or_default()); + let color = filled_color_with_blend_ifs(*item.element(), &adjustments, &blend_ifs, fill); Some(Box::new(move |_| faded(color, opacity))) } Graphic::RasterCPU(item) => { @@ -1344,12 +1393,13 @@ fn displacement_map_sampler(map: &Graphic) -> Option [f32; Some(Box::new(move |point| sample_gamma(&image, to_pixels.transform_point2(point)).map(|channel| channel * opacity))) } Graphic::Gradient(item) => { - // The GPU fades a gradient by its fill in the layer of its opacity, unless adjustments act on the ramp the fill fades - let adjustments = item.attribute::(ATTR_EFFECTS).filter(|effects| !effects.change_nothing()).map(adjustments).unwrap_or_default(); + // The GPU fades a gradient by its fill in the layer of its opacity, unless effects act on the ramp the fill fades + let effects = item.attribute::(ATTR_EFFECTS).filter(|effects| !effects.change_nothing()); + let (adjustments, blend_ifs) = (effects.map(adjustments).unwrap_or_default(), effects.map(content_blend_ifs).unwrap_or_default()); let opacity = item.attribute_cloned_or::(ATTR_OPACITY, 1.) as f32; let fill = item.attribute_cloned_or::(ATTR_OPACITY_FILL, 1.) as f32; let settings = GradientSettings::from_item_attributes(item); - let (gradient, settings, opacity) = match adjusted_gradient(item.element(), settings, &adjustments, fill) { + let (gradient, settings, opacity) = match adjusted_gradient_with_blend_ifs(item.element(), settings, &adjustments, &blend_ifs, fill) { Some((adjusted, adjusted_settings)) => (std::borrow::Cow::Owned(adjusted), adjusted_settings, opacity), None => (std::borrow::Cow::Borrowed(item.element()), settings, opacity * fill), }; @@ -1363,12 +1413,16 @@ fn displacement_map_sampler(map: &Graphic) -> Option [f32; })) } Graphic::Color(item) => { - // The GPU fills a solid color from 8-bit channels in a layer of its opacity, which the fill fades too unless adjustments act on the faded color - let adjustments = item.attribute::(ATTR_EFFECTS).filter(|effects| !effects.change_nothing()).map(adjustments).unwrap_or_default(); + // The GPU fills a solid color from 8-bit channels in a layer of its opacity, which the fill fades too unless effects act on the faded color + let effects = item.attribute::(ATTR_EFFECTS).filter(|effects| !effects.change_nothing()); + let (adjustments, blend_ifs) = (effects.map(adjustments).unwrap_or_default(), effects.map(content_blend_ifs).unwrap_or_default()); let fill = item.attribute_cloned_or::(ATTR_OPACITY_FILL, 1.) as f32; - let (color, opacity) = match adjustments.is_empty() { + let (color, opacity) = match adjustments.is_empty() && blend_ifs.is_empty() { true => (*item.element(), paint_opacity(item)), - false => (filled_color(*item.element(), &adjustments, fill), item.attribute_cloned_or::(ATTR_OPACITY, 1.) as f32), + false => ( + filled_color_with_blend_ifs(*item.element(), &adjustments, &blend_ifs, fill), + item.attribute_cloned_or::(ATTR_OPACITY, 1.) as f32, + ), }; let (color, opacity) = (core_types::color::SRGBA8::from(color), layer_opacity(opacity)); @@ -2449,6 +2503,60 @@ mod tests { } } + #[test] + fn halftones_keep_the_fade_of_blend_ifs_before_them() { + use graphic_types::blend_if::{BlendIfRanges, BlendRange}; + + // A Blend If hiding the white content stays hiding it once a halftone prints it, which white leaves as white + let mut ranges = BlendIfRanges::default(); + ranges.content.gray = BlendRange { + falloff_start: 0., + range_start: 0., + range_end: 50., + falloff_end: 50., + }; + let halftone = EffectOperation::ColorHalftone { + radius: 4., + red_angle: 45., + green_angle: 45., + blue_angle: 45., + offset: DVec2::ZERO, + phase: 0., + }; + let mut item = Item::new_from_element(Raster::new_cpu(Image::new(24, 24, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(24.))); + [EffectOperation::BlendIf(Box::new(ranges)), halftone] + .iter() + .for_each(|operation| graphic_types::stamp_effect(&mut item, graphic_types::Effect::new(operation))); + + let evaluated = evaluate_raster_effects(item); + assert!(evaluated.element().data.iter().all(|color| color.a() < 1e-5)); + } + + #[test] + fn blend_ifs_still_act_after_leading_adjustments_that_change_nothing() { + use graphic_types::blend_if::{BlendIfRanges, BlendRange}; + + // A Blend If hiding the white content hides it before the invert, though the image's own colors take the Make Opaque of no strength ahead of it + let mut ranges = BlendIfRanges::default(); + ranges.content.gray = BlendRange { + falloff_start: 0., + range_start: 0., + range_end: 50., + falloff_end: 50., + }; + let mut item = Item::new_from_element(Raster::new_cpu(Image::new(8, 8, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(8.))); + [ + EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 0. }), + EffectOperation::BlendIf(Box::new(ranges)), + EffectOperation::Adjustment(Adjustment::Invert), + ] + .iter() + .for_each(|operation| graphic_types::stamp_effect(&mut item, graphic_types::Effect::new(operation))); + + let evaluated = evaluate_raster_effects(item); + assert!(evaluated.element().data.iter().all(|color| color.a() < 1e-5)); + } + #[test] fn halftones_too_fine_to_print_show_their_tone() { // Dots a fraction of a pixel apart print the tone they average to, which for opaque content is the content diff --git a/node-graph/libraries/raster-kernels/src/value_effects.rs b/node-graph/libraries/raster-kernels/src/value_effects.rs index 2764d5c231..6689b7bde6 100644 --- a/node-graph/libraries/raster-kernels/src/value_effects.rs +++ b/node-graph/libraries/raster-kernels/src/value_effects.rs @@ -7,6 +7,7 @@ use core_types::Color; use core_types::graphene_hash::CacheHash; use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, Item}; use graphic_types::adjustment::Adjustment; +use graphic_types::blend_if::{ChannelRanges, blend_ifs_acting_before, fades_content}; use graphic_types::effects::{EffectOperation, Effects}; use std::hash::{DefaultHasher, Hasher}; use std::sync::{Mutex, PoisonError}; @@ -29,6 +30,47 @@ pub fn adjustments(effects: &Effects) -> Vec { .collect() } +/// A step a value's Blend Ifs take among its adjustments (see [`content_blend_ifs`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum BlendIfStep { + /// A Blend If reads the value's colors and fades the value by these content ranges, as a fill does. + Fade(ChannelRanges), + /// An effect run after the first starts (see [`Effects::runs`]), taking the value as the runs before it leave it as its content at full strength. + NextRun, +} + +/// Where each Blend If among the effects that fades a value by its own colors reads it, after how many of the [`adjustments`], with where each effect run after the first starts. +/// Empty if no Blend If fades the value. +pub fn content_blend_ifs(effects: &Effects) -> Vec<(usize, BlendIfStep)> { + let operations: Vec = effects.operations().collect(); + if !fades_content(&operations) { + return Vec::new(); + } + + // Each run's Blend Ifs act from its own start, as the renderers draw each run's effects on the result of those before it + let mut adjustments_before = 0; + let mut steps = Vec::new(); + for (run_index, (_, rows)) in effects.runs().into_iter().enumerate() { + if run_index > 0 { + steps.push((adjustments_before, BlendIfStep::NextRun)); + } + + let run = &operations[rows]; + for (row, operation) in run.iter().enumerate() { + let acting = blend_ifs_acting_before(run, row).into_iter().filter(|ranges| !ranges.content.show_everything()); + steps.extend(acting.map(|ranges| (adjustments_before, BlendIfStep::Fade(ranges.content)))); + + adjustments_before += usize::from(matches!(operation, EffectOperation::Adjustment(_))); + } + } + steps +} + +/// Whether a Blend If fades a value with effects in more than one run, so later runs read and paint within the result of those before them. +pub fn blend_ifs_span_runs(effects: &Effects) -> bool { + content_blend_ifs(effects).iter().any(|(_, step)| *step == BlendIfStep::NextRun) +} + /// The color with `adjustments` carried out on it in order. pub fn adjusted_color(color: Color, adjustments: &[Adjustment]) -> Color { adjustments.iter().fold(color, |color, adjustment| adjust_color(adjustment, color)) @@ -37,19 +79,60 @@ pub fn adjusted_color(color: Color, adjustments: &[Adjustment]) -> Color { /// The color an endless paint of `color` shows with `adjustments` carried out over it and its `fill` fading it, though not the paint overlays painted over it. /// Without edges, each paint overlay blends with the paint itself, which is exact where the paint is opaque. pub fn filled_color(color: Color, adjustments: &[Adjustment], fill: f32) -> Color { - if fill >= 1. { - return adjusted_color(color, adjustments); - } - fill_through(color, adjustments, fill, |index, color| adjust_color(&adjustments[index], color)) + filled_color_with_blend_ifs(color, adjustments, &[], fill) } -/// Carries out `adjustments` over a paint faded by `fill` as [`filled_color`] does, with `adjust` carrying out each one besides a paint overlay, given its index. -fn fill_through(color: Color, adjustments: &[Adjustment], fill: f32, adjust: impl Fn(usize, Color) -> Color) -> Color { +/// Like [`filled_color`], with the steps of the `blend_ifs` (see [`content_blend_ifs`]) also fading the paint by each one's content ranges where it reads the paint's colors. +pub fn filled_color_with_blend_ifs(color: Color, adjustments: &[Adjustment], blend_ifs: &[(usize, BlendIfStep)], fill: f32) -> Color { + if fill >= 1. && blend_ifs.is_empty() { + return adjusted_color(color, adjustments); + } + fill_through(color, adjustments, blend_ifs, fill, |index, color| adjust_color(&adjustments[index], color), ChannelRanges::weight) +} + +/// Carries out `adjustments` over a paint faded by `fill` and the `blend_ifs` as [`filled_color_with_blend_ifs`] does, with `adjust` carrying out each one besides a paint overlay, given its index. +/// `weigh` gives how strongly a Blend If's ranges show the gamma-encoded channels it reads. +fn fill_through( + color: Color, + adjustments: &[Adjustment], + blend_ifs: &[(usize, BlendIfStep)], + fill: f32, + adjust: impl Fn(usize, Color) -> Color, + mut weigh: impl FnMut(&ChannelRanges, [f64; 3]) -> f64, +) -> Color { + // Each Blend If fades the faded color by how strongly it shows the full-strength one, which each later run resets to the faded color + let mut steps = blend_ifs.iter().peekable(); + let mut take_steps = |full: &mut Color, filled: &mut Color, adjusted_count: usize| { + let mut weight = 1.; + let mut faded = false; + while let Some((_, step)) = steps.next_if(|(before, _)| *before <= adjusted_count) { + match step { + BlendIfStep::Fade(ranges) => { + let [red, green, blue, _] = full.to_gamma_srgb_channels(); + weight *= weigh(ranges, [red, green, blue].map(f64::from)); + faded = true; + } + BlendIfStep::NextRun => { + *filled = filled.with_alpha(filled.a() * std::mem::replace(&mut weight, 1.) as f32); + *full = *filled; + } + } + } + *filled = filled.with_alpha(filled.a() * weight as f32); + faded + }; + // The color at full strength, which each paint overlay blends with, and the color the fill fades, which it paints over at full strength let (mut full, mut filled) = (color, color.with_alpha(color.a() * fill)); + + // Once a Blend If fades them, adjustments keep the colors empty where they're empty, as the renderers keep empty pixels + let mut faded = false; for (index, adjustment) in adjustments.iter().enumerate() { + faded |= take_steps(&mut full, &mut filled, index); + let Adjustment::ColorOverlay { color: paint, blend_mode, opacity } = *adjustment else { - (full, filled) = (adjust(index, full), adjust(index, filled)); + let adjusted = |color: Color| if !faded || color.a() > 0. { adjust(index, color) } else { color }; + (full, filled) = (adjusted(full), adjusted(filled)); continue; }; @@ -64,18 +147,39 @@ fn fill_through(color: Color, adjustments: &[Adjustment], fill: f32, adjust: imp filled = Color::from_gamma_srgb_channels(mix(red, under_red), mix(green, under_green), mix(blue, under_blue), alpha); full = overlay_paint(full, paint, blend_mode, (opacity / 100.) as f32); } + take_steps(&mut full, &mut filled, adjustments.len()); filled } -/// Carries out `adjustments` in order on any number of colors with the `fill` fading them, with each one's kernel prepared once. -fn prepared(adjustments: &[Adjustment], fill: f32) -> Box Color> { +/// Carries out `adjustments` in order on any number of colors with the `fill` and the `blend_ifs` fading them, with each one's kernel prepared once. +fn prepared(adjustments: &[Adjustment], blend_ifs: &[(usize, BlendIfStep)], fill: f32) -> Box Color> { let kernels: Vec = adjustments.iter().map(PreparedAdjustment::new).collect(); - if fill >= 1. { + if fill >= 1. && blend_ifs.is_empty() { return Box::new(move |color| kernels.iter().fold(color, |color, kernel| kernel.adjust(color))); } - let adjustments = adjustments.to_vec(); - Box::new(move |color| fill_through(color, &adjustments, fill, |index, color| kernels[index].adjust(color))) + let (adjustments, blend_ifs) = (adjustments.to_vec(), blend_ifs.to_vec()); + Box::new(move |color| fill_through(color, &adjustments, &blend_ifs, fill, |index, color| kernels[index].adjust(color), ChannelRanges::weight)) +} + +/// Tells apart the colors each channel's range of each of the `blend_ifs` shows fully, partly, or not at all, as it reads them where [`fill_through`] fades by it. +fn blend_if_regions(adjustments: &[Adjustment], blend_ifs: &[(usize, BlendIfStep)], fill: f32) -> impl Fn(Color) -> u64 { + let kernels: Vec = adjustments.iter().map(PreparedAdjustment::new).collect(); + let (adjustments, blend_ifs) = (adjustments.to_vec(), blend_ifs.to_vec()); + + // Each channel's state (hidden, partly shown, or shown) is a digit in base 3, so up to ten Blend Ifs stay apart exactly + move |color| { + let mut region = 0_u64; + let weigh = |ranges: &ChannelRanges, channels: [f64; 3]| { + for weight in ranges.channel_weights(channels) { + let state = u64::from(weight > 0.) + u64::from(weight >= 1.); + region = region.wrapping_mul(3).wrapping_add(state); + } + ranges.weight(channels) + }; + fill_through(color, &adjustments, &blend_ifs, fill, |index, color| kernels[index].adjust(color), weigh); + region + } } /// The gradient with `adjustments` carried out along its ramp, with the settings to read the result with, or `None` if there are no adjustments. @@ -83,17 +187,28 @@ fn prepared(adjustments: &[Adjustment], fill: f32) -> Box Color /// A stepped ramp holds each stop's color, so adjusting the stops is exact. Elsewhere an adjustment can bend the ramp between stops, /// so the adjusted ramp is resampled into stops that interpolate linearly in gamma. pub fn adjusted_gradient(gradient: &Gradient, settings: GradientSettings, adjustments: &[Adjustment], fill: f32) -> Option<(Gradient, GradientSettings)> { - if adjustments.is_empty() { + adjusted_gradient_with_blend_ifs(gradient, settings, adjustments, &[], fill) +} + +/// Like [`adjusted_gradient`], with the `blend_ifs` also fading the ramp as [`filled_color_with_blend_ifs`] fades a color, or `None` if there are neither adjustments nor Blend Ifs. +pub fn adjusted_gradient_with_blend_ifs( + gradient: &Gradient, + settings: GradientSettings, + adjustments: &[Adjustment], + blend_ifs: &[(usize, BlendIfStep)], + fill: f32, +) -> Option<(Gradient, GradientSettings)> { + if adjustments.is_empty() && blend_ifs.is_empty() { return None; } // A gradient without stops reads as black, so its adjusted ramp is one stop of the adjusted black if gradient.is_empty() { - return Some((Gradient::from(vec![prepared(adjustments, fill)(Color::BLACK)]), settings)); + return Some((Gradient::from(vec![prepared(adjustments, blend_ifs, fill)(Color::BLACK)]), settings)); } if settings.interpolation == GradientInterpolation::Stepped { - let adjust = prepared(adjustments, fill); + let adjust = prepared(adjustments, blend_ifs, fill); return Some((gradient.map_colors(|color| adjust(*color)), settings)); } @@ -102,6 +217,16 @@ pub fn adjusted_gradient(gradient: &Gradient, settings: GradientSettings, adjust gradient.cache_hash(&mut hasher); settings.cache_hash(&mut hasher); adjustments.iter().for_each(|adjustment| adjustment.cache_hash(&mut hasher)); + for (before, step) in blend_ifs { + hasher.write_usize(*before); + match step { + BlendIfStep::Fade(ranges) => { + hasher.write_u8(0); + ranges.cache_hash(&mut hasher); + } + BlendIfStep::NextRun => hasher.write_u8(1), + } + } hasher.write_u32(fill.to_bits()); let key = hasher.finish(); @@ -114,7 +239,11 @@ pub fn adjusted_gradient(gradient: &Gradient, settings: GradientSettings, adjust return Some(result); } - let resampled = gradient.map_ramp(settings, prepared(adjustments, fill)); + // A Blend If cuts the ramp off wherever the colors it reads cross its ranges, which may lie between the resampling's probes + let resampled = match blend_ifs.is_empty() { + true => gradient.map_ramp(settings, prepared(adjustments, blend_ifs, fill)), + false => gradient.map_ramp_by_regions(settings, prepared(adjustments, blend_ifs, fill), blend_if_regions(adjustments, blend_ifs, fill)), + }; let resampled_settings = GradientSettings { space: GradientSpace::RgbGamma, interpolation: GradientInterpolation::Linear, @@ -129,29 +258,43 @@ pub fn adjusted_gradient(gradient: &Gradient, settings: GradientSettings, adjust Some((resampled, resampled_settings)) } -/// The color with the adjustments among its effects carried out and the effects consumed, for nodes that read the color. +/// The color with the adjustments among the effects carried out on it, faded by each Blend If where it reads the color, for the paints and nodes that read the value. +pub fn color_after_effects(color: Color, effects: &Effects) -> Color { + filled_color_with_blend_ifs(color, &adjustments(effects), &content_blend_ifs(effects), 1.) +} + +/// Carries out the effects on any number of colors as [`color_after_effects`] does on one, with each adjustment's kernel prepared once. +pub fn prepared_color_after_effects(effects: &Effects) -> Box Color> { + prepared(&adjustments(effects), &content_blend_ifs(effects), 1.) +} + +/// The gradient with the effects carried out along its ramp as [`color_after_effects`] carries them out on a color, with the settings to read the result with, or `None` with nothing to carry out. +pub fn gradient_after_effects(gradient: &Gradient, settings: GradientSettings, effects: &Effects) -> Option<(Gradient, GradientSettings)> { + adjusted_gradient_with_blend_ifs(gradient, settings, &adjustments(effects), &content_blend_ifs(effects), 1.) +} + +/// The color with its effects carried out as [`color_after_effects`] does and consumed, for nodes that read the color. /// A color without the effects attribute is returned as it is. pub fn evaluate_color_effects(item: Item) -> Item { - let Some(adjustments) = item.attribute::(ATTR_EFFECTS).map(adjustments) else { + let Some(color) = item.attribute::(ATTR_EFFECTS).map(|effects| color_after_effects(*item.element(), effects)) else { return item; }; let mut item = item; - *item.element_mut() = adjusted_color(*item.element(), &adjustments); + *item.element_mut() = color; item.remove_attribute::(ATTR_EFFECTS); item } -/// The gradient with the adjustments among its effects carried out along its ramp and the effects consumed, for nodes that read its colors. +/// The gradient with its effects carried out along its ramp as [`gradient_after_effects`] does and consumed, for nodes that read its colors. /// A gradient without the effects attribute is returned as it is. pub fn evaluate_gradient_effects(item: Item) -> Item { - let Some(adjustments) = item.attribute::(ATTR_EFFECTS).map(adjustments) else { - return item; - }; + let Some(effects) = item.attribute::(ATTR_EFFECTS) else { return item }; let settings = GradientSettings::from_item_attributes(&item); + let adjusted = gradient_after_effects(item.element(), settings, effects); let mut item = item; - let settings = match adjusted_gradient(item.element(), settings, &adjustments, 1.) { + let settings = match adjusted { Some((gradient, adjusted_settings)) => { *item.element_mut() = gradient; adjusted_settings @@ -180,6 +323,16 @@ mod tests { actual.iter().zip(expected).all(|(actual, expected)| (actual - expected).abs() < 1e-4) } + /// The `element` with each row stamped on it while it's placed by the row's scale, so a row stamped at a new scale starts a run of its own. + fn stamped(element: T, rows: &[(EffectOperation, f64)]) -> Item { + let mut item = Item::new_from_element(element); + for (operation, scale) in rows { + item.set_attribute(core_types::ATTR_TRANSFORM, glam::DAffine2::from_scale(glam::DVec2::splat(*scale))); + graphic_types::stamp_effect(&mut item, graphic_types::Effect::new(operation)); + } + item + } + #[test] fn paint_overlays_mix_in_gamma_unfaded_by_the_fill() { let half_white = [Adjustment::ColorOverlay { @@ -198,6 +351,162 @@ mod tests { assert!(close(gamma(filled_color(Color::BLACK, &half_white, 0.5)), [2. / 3., 2. / 3., 2. / 3., 0.75])); } + #[test] + fn consumed_effects_fade_values_by_their_blend_ifs_where_they_read_the_colors() { + use graphic_types::blend_if::BlendIfRanges; + + // Shown only where the gray is at least half + let mut hides_darks = BlendIfRanges::default(); + hides_darks.content.gray.falloff_start = 50.; + hides_darks.content.gray.range_start = 50.; + let blend_if = EffectOperation::BlendIf(Box::new(hides_darks)); + let invert = EffectOperation::Adjustment(Adjustment::Invert); + let red = EffectOperation::Adjustment(Adjustment::ColorOverlay { + color: Color::RED, + blend_mode: BlendMode::Normal, + opacity: 100., + }); + let black_through = |operations: Vec| evaluate_color_effects(Item::new_from_element(Color::BLACK).with_attribute(ATTR_EFFECTS, Effects::from_operations(operations))); + + // Black is hidden, whether inverted after the Blend If reads it or not, but shows once inverted before + assert_eq!(black_through(vec![blend_if.clone()]).element().a(), 0.); + assert_eq!(black_through(vec![blend_if.clone(), invert.clone()]).element().a(), 0.); + assert!(close(gamma(*black_through(vec![invert, blend_if.clone()]).element()), [1.; 4])); + + // An overlay after it paints over the hidden color at full strength, as over a fill of none, and the effects are consumed + let overlaid = black_through(vec![blend_if.clone(), red]); + assert!(close(gamma(*overlaid.element()), [1., 0., 0., 1.])); + assert!(overlaid.attribute::(ATTR_EFFECTS).is_none()); + + // A gradient's dark start is hidden and its light end shown + let gradient = Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE])).with_attribute(ATTR_EFFECTS, Effects::from_operations([blend_if])); + let evaluated = evaluate_gradient_effects(gradient); + let settings = GradientSettings::from_item_attributes(&evaluated); + assert!(evaluated.element().evaluate(0., settings).a() < 1e-6); + assert!(close(gamma(evaluated.element().evaluate(1., settings)), [1.; 4])); + } + + #[test] + fn consumed_values_fade_by_blend_ifs_reading_each_effect_run_as_the_runs_before_it_leave_it() { + use graphic_types::blend_if::BlendIfRanges; + + // Shown only where the gray is at least half + let mut hides_darks = BlendIfRanges::default(); + hides_darks.content.gray.falloff_start = 50.; + hides_darks.content.gray.range_start = 50.; + let blend_if = EffectOperation::BlendIf(Box::new(hides_darks)); + let overlay = |color: Color| { + EffectOperation::Adjustment(Adjustment::ColorOverlay { + color, + blend_mode: BlendMode::Normal, + opacity: 100., + }) + }; + + // White painted blue is read as blue by a Blend If after a scale, which hides it, but in the same run the Blend If reads the white beneath the overlay + let color_through = |color: Color, rows: &[(EffectOperation, f64)]| *evaluate_color_effects(stamped(color, rows)).element(); + assert_eq!(color_through(Color::WHITE, &[(overlay(Color::BLUE), 1.), (blend_if.clone(), 2.)]).a(), 0.); + assert!(close(gamma(color_through(Color::WHITE, &[(overlay(Color::BLUE), 1.), (blend_if.clone(), 1.)])), [0., 0., 1., 1.])); + + // Black hidden before a scale leaves nothing for an overlay after it to paint within + assert_eq!(color_through(Color::BLACK, &[(blend_if.clone(), 1.), (overlay(Color::RED), 2.)]).a(), 0.); + assert!(close(gamma(color_through(Color::BLACK, &[(blend_if.clone(), 1.), (overlay(Color::RED), 1.)])), [1., 0., 0., 1.])); + + // A ramp painted blue is hidden all along by a Blend If after a scale + let ramp = stamped(Gradient::from(vec![Color::BLACK, Color::WHITE]), &[(overlay(Color::BLUE), 1.), (blend_if, 2.)]); + let evaluated = evaluate_gradient_effects(ramp); + let settings = GradientSettings::from_item_attributes(&evaluated); + for t in [0., 0.25, 0.75, 1.] { + let shown = evaluated.element().evaluate(t, settings); + assert!(shown.a() < 1e-6, "hidden at {t}: {:?}", gamma(shown)); + } + } + + #[test] + fn values_a_blend_if_hides_stay_hidden_through_adjustments_raising_alpha_as_rasters_do() { + use crate::raster_effects::{evaluate_raster_effects, premultiplied_gamma_channels}; + use graphic_types::EffectKind; + use graphic_types::blend_if::BlendIfRanges; + use raster_types::{Image, Raster}; + + // Shown only where the gray is at least half + let mut hides_darks = BlendIfRanges::default(); + hides_darks.content.gray.falloff_start = 50.; + hides_darks.content.gray.range_start = 50.; + let blend_if = EffectOperation::BlendIf(Box::new(hides_darks)); + let make_opaque = EffectOperation::default_for(EffectKind::MakeOpaque); + let red = EffectOperation::Adjustment(Adjustment::ColorOverlay { + color: Color::RED, + blend_mode: BlendMode::Normal, + opacity: 100., + }); + + // Black consumed as a color, which agrees with a raster's pixel of it + let black_through = |name: &str, rows: &[(EffectOperation, f64)]| { + let color = *evaluate_color_effects(stamped(Color::BLACK, rows)).element(); + let raster = evaluate_raster_effects(stamped(Raster::new_cpu(Image::new(1, 1, Color::BLACK)), rows)); + let pixel = raster.element().data.first().copied().unwrap_or(Color::TRANSPARENT); + let (color_channels, pixel_channels) = (premultiplied_gamma_channels(color), premultiplied_gamma_channels(pixel)); + assert!(close(color_channels, pixel_channels), "black {name}: {color_channels:?} vs the raster's {pixel_channels:?}"); + color + }; + + // Hidden black stays hidden when made opaque, in its run or the next, where an overlay finds nothing to paint within either + let hidden = [ + ("made opaque", vec![(blend_if.clone(), 1.), (make_opaque.clone(), 1.)]), + ("made opaque in the next run", vec![(blend_if.clone(), 1.), (make_opaque.clone(), 2.)]), + ("made opaque and painted in the next run", vec![(blend_if.clone(), 1.), (make_opaque.clone(), 2.), (red.clone(), 2.)]), + ]; + for (name, rows) in hidden { + assert_eq!(black_through(name, &rows).a(), 0., "black {name}"); + } + + // In its own run, an overlay still paints within the full-strength black + let painted = black_through("made opaque and painted", &[(blend_if.clone(), 1.), (make_opaque.clone(), 1.), (red, 1.)]); + assert!(close(gamma(painted), [1., 0., 0., 1.]), "{:?}", gamma(painted)); + + // A ramp made opaque stays hidden where it's dark, in the Blend If's run or the next + for scale in [1., 2.] { + let ramp = stamped(Gradient::from(vec![Color::BLACK, Color::WHITE]), &[(blend_if.clone(), 1.), (make_opaque.clone(), scale)]); + let evaluated = evaluate_gradient_effects(ramp); + let settings = GradientSettings::from_item_attributes(&evaluated); + for (t, alpha) in [(0., 0.), (0.25, 0.), (0.75, 1.), (1., 1.)] { + let shown = evaluated.element().evaluate(t, settings).a(); + assert!((shown - alpha).abs() < 1e-6, "the alpha at {t} with the scale {scale} is {shown}"); + } + } + } + + #[test] + fn a_ramp_keeps_the_band_a_blend_if_shows_between_where_resampling_probes_it() { + use graphic_types::blend_if::{BlendIfRanges, BlendRange}; + + // Shown only where the gray lies from 30% to 40%, which neither end of the ramp nor any of its quarter points lands within + let mut band = BlendIfRanges::default(); + band.content.gray = BlendRange { + falloff_start: 30., + range_start: 30., + range_end: 40., + falloff_end: 40., + }; + let effects = Effects::from_operations([EffectOperation::BlendIf(Box::new(band))]); + let gamma_settings = GradientSettings { + space: GradientSpace::RgbGamma, + interpolation: GradientInterpolation::Linear, + ..Default::default() + }; + let (resampled, settings) = gradient_after_effects(&Gradient::from(vec![Color::BLACK, Color::WHITE]), gamma_settings, &effects).expect("the Blend If fades the ramp"); + + // The band shows its own grays from level 77 to 102, which lie from 30% to just past 40% along the ramp, with sharp edges + for t in [0.301, 0.35, 0.4] { + let shown = resampled.evaluate(t, settings); + assert!(close(gamma(shown), [t as f32, t as f32, t as f32, 1.]), "the band shows at {t}: {:?}", gamma(shown)); + } + for t in [0., 0.25, 0.299, 0.403, 0.5, 0.75, 1.] { + assert!(resampled.evaluate(t, settings).a() < 1e-6, "hidden at {t}"); + } + } + #[test] fn a_gradient_without_stops_adjusts_the_black_it_reads_as() { let empty = Gradient::from(Vec::::new()); diff --git a/node-graph/libraries/rendering/src/deferred_image.rs b/node-graph/libraries/rendering/src/deferred_image.rs index 011584caf5..0905e4ce57 100644 --- a/node-graph/libraries/rendering/src/deferred_image.rs +++ b/node-graph/libraries/rendering/src/deferred_image.rs @@ -3,7 +3,7 @@ //! Content with an effect no filter can carry out, and a backdrop whose copy in markup would nest, are drawn as images in place of markup. //! Placeholders stand in for each until it's resolved, leaving an SVG that never is short of those effects. -use crate::renderer::{CanvasImage, Render, RenderOutputType, RenderParams, RenderSvgSegmentList, SvgRender, render_raster_cpu_image_svg}; +use crate::renderer::{CanvasImage, Render, RenderOutputType, RenderParams, RenderSvgSegmentList, SvgRender, format_transform_matrix, render_raster_cpu_image_svg}; use crate::vello_scene_builder::{MAX_EFFECTS_AREA_PER_VIEWPORT_AREA, VelloSceneBuilder}; use core_types::Color; use core_types::blending::BlendMode; @@ -202,6 +202,8 @@ pub struct DeferredImage { pub margin: f64, pub opacity: f32, pub blend_mode: BlendMode, + /// The reference for the mask fading the image by Blend If's ranges of what lies beneath, if any. + pub mask: Option, } /// What the GPU renders an image of for an SVG. @@ -276,6 +278,7 @@ pub struct DeferredImagePlacement { pub user_to_document: DAffine2, pub opacity: f32, pub blend_mode: BlendMode, + pub mask: Option, /// Whether the image is drawn to a canvas rather than embedded in the SVG. pub to_canvas: bool, /// Screen pixels per document unit, which sizes an image drawn to a canvas. @@ -289,14 +292,22 @@ pub struct DeferredImageLayout { pub size: UVec2, } +/// The starts of the markers around the markup standing in for an item of deferred content, which its ID and `-->` follow. +pub(crate) const DEFERRED_IMAGE_OPENING: &str = "`. +pub(crate) const DEFERRED_COVER_OPENING: &str = ""), format!("")) + (format!("{DEFERRED_IMAGE_OPENING}{id}-->"), format!("{DEFERRED_IMAGE_CLOSING}{id}-->")) } /// Whether the `markup` holds markers of markup standing in for an item of deferred content. pub(crate) fn holds_image_markers(markup: &str) -> bool { - markup.contains("", placement.id)); + let transform = format_transform_matrix(placement.transform); + while let Some(start) = svg.find(&opening) { + let key_start = start + opening.len(); + let Some(key_end) = svg[key_start..].find("-->").map(|offset| key_start + offset) else { break }; + let Some(end) = svg[key_end..].find(&closing).map(|offset| key_end + offset + closing.len()) else { + break; + }; + let cover = format!(r##""##, &svg[key_start..key_end]); + svg.replace_range(start..end, &cover); + } + } } diff --git a/node-graph/libraries/rendering/src/lib.rs b/node-graph/libraries/rendering/src/lib.rs index 4ac3149a08..b9e67ea262 100644 --- a/node-graph/libraries/rendering/src/lib.rs +++ b/node-graph/libraries/rendering/src/lib.rs @@ -3,6 +3,7 @@ pub mod deferred_image; pub mod render_ext; mod renderer; mod svg_backdrop; +mod svg_blend_if; pub mod to_peniko; pub mod vello_scene_builder; diff --git a/node-graph/libraries/rendering/src/renderer.rs b/node-graph/libraries/rendering/src/renderer.rs index 252935591b..d013c93d6a 100644 --- a/node-graph/libraries/rendering/src/renderer.rs +++ b/node-graph/libraries/rendering/src/renderer.rs @@ -1,6 +1,7 @@ use crate::deferred_image::{self, DeferredContent, DeferredImage, EffectMap}; use crate::render_ext::{PaintTarget, RenderExt}; use crate::svg_backdrop::{self, OpenGroup, OpenGroups}; +use crate::svg_blend_if; use crate::to_peniko::{BlendModeExt, ToPenikoColor}; use crate::vello_scene_builder::VelloSceneBuilder; use core_types::CacheHash; @@ -25,6 +26,7 @@ use core_types::{ use dyn_any::DynAny; use glam::{DAffine2, DMat2, DVec2}; use graphene_resource::Resource; +use graphic_types::blend_if::{BlendIfRanges, ChannelRanges, blend_ifs_acting_before, fades_content, paint_overlay_folds, underlying_ranges}; use graphic_types::effect_layers::{EffectLayers, LayerPart, PiecePlace, content_image_effects, effects_read_backdrop, is_pixel_filter, piece_blend_mode}; use graphic_types::effects::{EffectCapture, GlowFill, effect_space, spans_along_axes}; use graphic_types::filters::is_random_field_filter; @@ -44,7 +46,9 @@ use kurbo::{Affine, BezPath, Cap, Join, PathEl, Shape}; use num_traits::Zero; use raster_kernels::effect_kernels::NEGLIGIBLE_LENGTH; use raster_kernels::raster_effects::adjusted_raster; -use raster_kernels::value_effects::{adjusted_color, adjusted_gradient, adjustments, filled_color}; +use raster_kernels::value_effects::{ + BlendIfStep, adjusted_color, adjusted_gradient, adjusted_gradient_with_blend_ifs, blend_ifs_span_runs, color_after_effects, filled_color_with_blend_ifs, gradient_after_effects, +}; use skrifa::instance::{LocationRef, NormalizedCoord, Size}; use skrifa::outline::{DrawSettings, OutlinePen}; use skrifa::raw::FontRef as SkrifaFontRef; @@ -260,6 +264,14 @@ impl ItemCompositing<'_> { } } + /// Blend If's ranges of what lies beneath, which fade all the item draws if it's `bounded`. As on the GPU, content without bounds reads nothing beneath it, which hides nothing. + fn underlying_ranges_read(&self, bounded: bool) -> Vec { + match self.effects.filter(|_| bounded) { + Some((effects, _)) => underlying_ranges(&effects.operations().collect::>()), + None => Vec::new(), + } + } + /// Whether the effects group draws the item's opacity and blend mode itself, as its layers blend onto what lies beneath, so the item pushes no layer of its own. fn effects_draw_compositing(&self) -> bool { self.effects.is_some() && self.layered @@ -279,13 +291,14 @@ impl ItemCompositing<'_> { return Vec::new(); }; - (effects.operations().enumerate()) + let operations: Vec = effects.operations().collect(); + (operations.iter().cloned().enumerate()) .map_while(|(index, operation)| { let flattened = index < layers.flattened; match operation { EffectOperation::Adjustment(adjustment @ Adjustment::ColorOverlay { .. }) => { let with_content = flattened || layers.layer_of(EffectCapture { index, plane: 0 }) == layers.content_layer(); - (fill == 1. && with_content).then_some(adjustment) + (fill == 1. && with_content && paint_overlay_folds(&operations, index)).then_some(adjustment) } EffectOperation::Adjustment(adjustment) if flattened && (fill == 1. || raster_kernels::adjustments::preserves_alpha(&adjustment)) => Some(adjustment), _ => None, @@ -413,11 +426,24 @@ impl ItemCompositing<'_> { self.opacity * self.effects.map_or(1., |(_, fill)| fill) } - /// How an endless item (a color or gradient filling everything) draws, alike in SVG and Vello, from the layers its effects plan. + /// How an endless item (a color or gradient filling everything) draws, alike in SVG and Vello, from the layers its effects plan as one run (see [`carried_out_in_view`]). /// Its other effects, mostly casting from edges it lacks, are left undone. fn endless_paint(&self) -> EndlessPaint { + let blend_ifs_fade = self.effects.is_some_and(|(effects, _)| fades_content(&effects.operations().collect::>())); + self.endless_paint_where(blend_ifs_fade) + } + + /// [`Self::endless_paint`] for an endless `color`, which the Blend Ifs fade only if its one weight is partial, unlike a gradient's weight varying along its ramp. + fn endless_color_paint(&self, color: Color) -> EndlessPaint { + let unfaded = self.endless_paint_where(false); + if unfaded.blend_if_weight(color) < 1. { self.endless_paint_where(true) } else { unfaded } + } + + /// [`Self::endless_paint`] where the Blend Ifs fade the content if `blend_ifs_fade`, as a fill does. + fn endless_paint_where(&self, blend_ifs_fade: bool) -> EndlessPaint { let mut paint = EndlessPaint { adjustments: Vec::new(), + blend_ifs: Vec::new(), fill: 1., opacity: self.opacity, blend_mode: self.blend_mode, @@ -428,14 +454,21 @@ impl ItemCompositing<'_> { paint.fill = fill; paint.blend_mode = content_layer.map_or(self.blend_mode, |layer| layers.layers[layer].blend_mode); - // Below a full fill, a blended overlay in the content's layer and every one after it paint over everything, which is exact for a paint covering everything + // Where a fill or a Blend If fades the content, a blended overlay in its layer and every one after paint over everything, exact for a paint covering everything let mut over_everything = false; - for (index, operation) in effects.operations().enumerate() { + let operations: Vec = effects.operations().collect(); + let faded = fill < 1. || blend_ifs_fade; + for (index, operation) in operations.iter().cloned().enumerate() { + // A solid color has one weight, and a gradient one along its ramp, of the paint as the adjustments before the Blend If leave it + for ranges in blend_ifs_acting_before(&operations, index).into_iter().filter(|ranges| !ranges.content.show_everything()) { + paint.blend_ifs.push((paint.adjustments.len(), BlendIfStep::Fade(ranges.content))); + } + let EffectOperation::Adjustment(adjustment) = operation else { continue }; let capture = EffectCapture { index, plane: 0 }; let in_content_layer = content_layer.is_some_and(|layer| layers.layers[layer].parts.iter().any(|part| matches!(part, LayerPart::Piece(piece) if piece.capture == capture))); let piece = layers.piece(capture).map(|(_, piece)| piece); - over_everything |= fill < 1. && in_content_layer && piece.is_some_and(|piece| piece.blend_mode != BlendMode::Normal); + over_everything |= faded && in_content_layer && piece.is_some_and(|piece| piece.blend_mode != BlendMode::Normal); match (adjustment, piece) { // A solid paint overlay in a layer of its own paints over everything beneath it @@ -519,6 +552,15 @@ impl ItemCompositing<'_> { // Masks leading or trailing the other effects become SVG's own masks around the filters, which carry out those between. // SVG's own masks measure in the user space, so effects measuring in a space of their own leave every mask to the filters. let (leading_masks, trailing_masks) = if transformed { (0..0, effects.len()..effects.len()) } else { masks::native_masks(effects) }; + + // Blend If's ranges of what lies beneath fade every layer by a mask copying it before any of the item is drawn + let underlying = self.underlying_ranges_read(bounded); + let blend_if_mask = (!underlying.is_empty()) + .then(|| svg_blend_if::underlying_mask(render, &underlying, bounds, self.reach_around(bounds, 0.), render_params)) + .flatten(); + + // Each layer takes one mask, so beside Blend If's the masks trailing the effects are carried out in the filters instead + let trailing_masks = if blend_if_mask.is_some() { effects.len()..effects.len() } else { trailing_masks }; let filtered = leading_masks.end..trailing_masks.start; // The effects' drawn paints as markup in a run's effect space, where the content's placement places those following it. @@ -620,7 +662,12 @@ impl ItemCompositing<'_> { // The filters carry out the effects between the native masks, other than those reading what lies beneath, so with only those at a full fill there are none let run_filtered = filtered.start.clamp(rows.start, rows.end) - rows.start..filtered.end.clamp(rows.start, rows.end) - rows.start; - let filters_content = (run.operations_in(run_filtered.clone())).any(|operation| !operation.changes_nothing() && !matches!(operation, EffectOperation::BackgroundBlur { .. })); + let reads_only_beneath = |operation: &EffectOperation| match operation { + EffectOperation::BackgroundBlur { .. } => true, + EffectOperation::BlendIf(ranges) => ranges.content.show_everything(), + _ => false, + }; + let filters_content = (run.operations_in(run_filtered.clone())).any(|operation| !operation.changes_nothing() && !reads_only_beneath(&operation)); let needs_filter = filters_content || run_fill < 1.; let pixel_exact = full_size_export && space_to_document.matrix2 == DMat2::IDENTITY; @@ -734,6 +781,7 @@ impl ItemCompositing<'_> { backdrop, backdrop_cut_depth: reading_split, backdrop_masks, + blend_if_mask, }) } } @@ -764,6 +812,8 @@ struct SvgEffects { backdrop_cut_depth: usize, /// The references for the masks cutting what lies beneath that the content cutting it isn't drawn through, in the last run's effect space. backdrop_masks: Vec, + /// The reference for the mask fading every layer by Blend If's ranges of what lies beneath, if any. + blend_if_mask: Option, } /// One layer of an item's effects in SVG: a group filtering the content into the layer, blending by its mode. @@ -816,9 +866,25 @@ fn draw_effect_runs( // The runs before this one paint past the content, which this run then reaches from let content_bounds = bounds.map_or([DVec2::ZERO; 2], |bounds| [DVec2::new(bounds.x0, bounds.y0), DVec2::new(bounds.x1, bounds.y1)]); - let earlier_reach = effects.run(0..rows.start).reach_around(content_transform, content_bounds, frame.map_or(0., |(_, overhang)| overhang)); + let earlier_effects = effects.run(0..rows.start); + let earlier_reach = earlier_effects.reach_around(content_transform, content_bounds, frame.map_or(0., |(_, overhang)| overhang)); let earlier_bounds = bounds.map(|bounds| bounds.inflate(earlier_reach.x, earlier_reach.y)); let earlier_frame = frame.map(|(frame, overhang)| (frame, overhang + earlier_reach.max_element())); + + // Blend If's ranges of what lies beneath fade every layer the item draws, as in SVG, so those stamped in the runs within join this run, which reads what lies beneath + let mut run = run.into_owned(); + for operation in earlier_effects.operations() { + if let EffectOperation::BlendIf(ranges) = operation + && !ranges.underlying.show_everything() + { + let underlying = EffectOperation::BlendIf(Box::new(BlendIfRanges { + content: Default::default(), + ..*ranges + })); + let row = Item::new_from_element(graphic_types::Effect::new(&underlying)).with_attribute(ATTR_TRANSFORM, *stamped_transform); + run.0.push(row); + } + } scene.draw_effects(&run, 1., opacity, blend_mode, layered, earlier_bounds, space, earlier_frame, &mut draw_run_paint, &mut |scene| { let flattened = (1., BlendMode::Normal, false); @@ -841,6 +907,8 @@ fn without_opacity_and_blend_mode(item: ItemRef<'_, T>, element: T) -> Item, + /// The content ranges of each Blend If, after how many of the adjustments it reads the paint's colors. + blend_ifs: Vec<(usize, BlendIfStep)>, fill: f32, opacity: f32, blend_mode: BlendMode, @@ -851,11 +919,34 @@ struct EndlessPaint { impl EndlessPaint { /// The fill to carry out along a gradient's ramp and the opacity of its layer. With nothing to carry out, the fill fades the layer instead, sparing a resampled ramp. fn ramp_fill_and_opacity(&self) -> (f32, f32) { - match self.adjustments.is_empty() { + match self.adjustments.is_empty() && self.blend_ifs.is_empty() { true => (1., self.opacity * self.fill), false => (self.fill, self.opacity), } } + + /// How strongly the Blend Ifs show the paint where it's `color`, each reading the color as the adjustments before it leave it. + fn blend_if_weight(&self, color: Color) -> f32 { + (self.blend_ifs.iter()) + .filter_map(|(before, step)| match step { + BlendIfStep::Fade(ranges) => { + let [red, green, blue, _] = adjusted_color(color, &self.adjustments[..*before]).to_gamma_srgb_channels(); + Some(ranges.weight([red, green, blue].map(f64::from)) as f32) + } + BlendIfStep::NextRun => None, + }) + .product() + } + + /// The color the paint shows where it's `color`, with the adjustments carried out over it and faded by the `fill`, and by each Blend If where it reads the paint. + fn shown_color(&self, color: Color, fill: f32) -> Color { + filled_color_with_blend_ifs(color, &self.adjustments, &self.blend_ifs, fill) + } + + /// The gradient with the adjustments carried out along its ramp and faded as [`Self::shown_color`] fades a color, with the settings to read it with, or `None` with nothing to carry out. + fn adjusted_gradient(&self, gradient: &Gradient, settings: GradientSettings, fill: f32) -> Option<(Gradient, GradientSettings)> { + adjusted_gradient_with_blend_ifs(gradient, settings, &self.adjustments, &self.blend_ifs, fill) + } } /// A vector's solid paints with adjustments carried out on their colors, and the effects left after those adjustments. @@ -958,7 +1049,7 @@ pub fn graphic_list_painted_bounds(list: &List, maps_resolved: bool) -> } } -/// The effects' runs (see [`Effects::runs`]), split before each Gaussian blur varying its radius with other effects before it in its run, which it flattens anyway. +/// The effects' runs (see [`Effects::runs`]), split before each Gaussian blur varying its radius with other effects before it in its run, which it flattens anyway, unless it takes its results as maps. /// One reads its input once per level, and browsers redo a filter's input for each read, so a fresh source keeps chained ones from multiplying the work. fn svg_runs(effects: &Effects) -> Vec<(DAffine2, Range)> { let operations: Vec = effects.operations().collect(); @@ -969,7 +1060,8 @@ fn svg_runs(effects: &Effects) -> Vec<(DAffine2, Range)> { for index in rows.start + 1..rows.end { let gaussian = matches!(operations[index], EffectOperation::Blur { box_blur: false, .. }); let masked_radius_blur = gaussian && operations[index].varies_blur_radius() && !operations[index].changes_nothing(); - if masked_radius_blur && operations[start..index].iter().any(|operation| !operation.changes_nothing()) { + let reads_input = !masked_radius_blur_takes_maps(&operations[start..index]); + if masked_radius_blur && reads_input && operations[start..index].iter().any(|operation| !operation.changes_nothing()) { runs.push((stamped_transform, start..index)); start = index; } @@ -979,6 +1071,12 @@ fn svg_runs(effects: &Effects) -> Vec<(DAffine2, Range)> { runs } +/// Whether SVG takes the results of a Gaussian blur varying its radius after the `rows_before` it in its run as the GPU's maps, as it takes a box's. +/// After a Blend If fading the content by its own colors, the blur has the full-strength content and the faded one to blur, and a filter starting afresh before it takes only one. +fn masked_radius_blur_takes_maps(rows_before: &[EffectOperation]) -> bool { + fades_content(rows_before) +} + /// The `layers` the GPU plans for its last run of effects, narrowed to the last split of that run (see [`svg_runs`]) starting `split_start` rows in, numbering the pieces within it. /// The splits before it are flattened, so their rows draw no pieces but what lies beneath, which the last split copies for them. fn layers_of_last_split(mut layers: EffectLayers, split_start: usize) -> EffectLayers { @@ -1057,6 +1155,7 @@ fn render_svg_through_filters(render: &mut SvgRender, effects: Option render.parent_tag( - "g", - |attributes| { - if opacity < 1. { - attributes.push("opacity", opacity.to_string()); - } - if layer.blend_mode != BlendMode::default() { - attributes.push("style", layer.blend_mode.render()); - } - }, - |render| { - // Its markup lies in the last run's effect space, like the layer's content + // What lies beneath, filtered, goes beneath the content's filtered group in a group taking the layer's opacity and blend mode. + // So does a transformed layer beside Blend If's mask, which measures in the user space of the group taking it. + let backdrop = backdrop.as_ref().filter(|_| layer.holds_content); + if backdrop.is_none() && (blend_if_mask.is_none() || matrix.is_empty()) { + draw_layer(render, layer, true); + continue; + } + + render.parent_tag( + "g", + |attributes| { + if opacity < 1. { + attributes.push("opacity", opacity.to_string()); + } + if layer.blend_mode != BlendMode::default() { + attributes.push("style", layer.blend_mode.render()); + } + if let Some(mask) = &blend_if_mask { + attributes.push_backdrop("mask", mask); + } + }, + |render| { + // Its markup lies in the last run's effect space, like the layer's content + if let Some(backdrop) = backdrop { let masked = (backdrop_masks.iter()).fold(backdrop.markup.clone(), |markup, mask| format!(r#"{markup}"#)); - match &layer_fade_mask { - Some(mask) => render.parent_tag( + if let Some(mask) = &layer_fade_mask { + return render.parent_tag( "g", |attributes| { if !matrix.is_empty() { @@ -1179,17 +1291,14 @@ fn render_svg_through_filters(render: &mut SvgRender, effects: Option { - let markup = if matrix.is_empty() { masked } else { format!(r#"{masked}"#) }; - render.leaf_node(SvgSegment::Backdrop(markup)); - draw_layer(render, layer, false); - } + ); } - }, - ), - None => draw_layer(render, layer, true), - } + let markup = if matrix.is_empty() { masked } else { format!(r#"{masked}"#) }; + render.leaf_node(SvgSegment::Backdrop(markup)); + } + draw_layer(render, layer, false); + }, + ); } let Some(markup) = content_markup else { return }; @@ -1323,6 +1432,8 @@ struct DeferredMarkup { id: u64, /// The content's extent with how far its effects reach past it, in the user space the markup is drawn in. bounds: [DVec2; 2], + /// The reference for the mask fading the image by Blend If's ranges of what lies beneath, if any. + mask: Option, } impl SvgRender { @@ -1334,7 +1445,15 @@ impl SvgRender { /// Opens markup standing in for an image the GPU renders of an item, if SVG filters can't carry out all its effects, which [`finish_deferred_markup`] then closes. /// `bounds` gives the content's extent in the current user space, and `overhang` how far it already paints past its frame there, as a group's nested effects do. -fn start_deferred_markup(render: &mut SvgRender, render_params: &RenderParams, compositing: &ItemCompositing, bounds: impl FnOnce() -> RenderBoundingBox, overhang: f64) -> Option { +/// Endless content, like a color or gradient filling everything, is given its extent but isn't `bounded`. +fn start_deferred_markup( + render: &mut SvgRender, + render_params: &RenderParams, + compositing: &ItemCompositing, + bounds: impl FnOnce() -> RenderBoundingBox, + bounded: bool, + overhang: f64, +) -> Option { // TODO: Paints (patterns) whose effects need the GPU's maps then draw wrongly or not at all, unlike Vello. Embed a GPU render of such a paint, // filled in by `svg_readback.rs` like its images, maps, and planned generators (see the values and renders plan's boundary work). if !render.images_replace_markup(render_params) || compositing.svg_expresses_effects() || !render.transform.matrix2.determinant().is_normal() { @@ -1344,15 +1463,19 @@ fn start_deferred_markup(render: &mut SvgRender, render_params: &RenderParams, c // The image covers how far the effects reach past the content, measured in this user space, where effects relative to its extent take its size let reach = compositing.reach_around([min, max], overhang); + let reached = [min - reach, max + reach]; + + // The image, rendered on its own, reads nothing beneath it, so a mask applies Blend If's ranges of what lies beneath to it, copied before the image's markup begins + let underlying = compositing.underlying_ranges_read(bounded); + let mask = (!underlying.is_empty()) + .then(|| svg_blend_if::underlying_mask(render, &underlying, reached, DVec2::ZERO, render_params)) + .flatten(); let id = generate_uuid(); render.leaf_node(deferred_image::image_markers(id).0); render.drawing_deferred_markup = true; - Some(DeferredMarkup { - id, - bounds: [min - reach, max + reach], - }) + Some(DeferredMarkup { id, bounds: reached, mask }) } /// Closes the markup [`start_deferred_markup`] opened, if it did, recording the item `content` makes without its opacity and blend mode for the GPU to render. @@ -1364,7 +1487,7 @@ fn finish_deferred_markup( blend_mode: BlendMode, content: impl FnOnce() -> Graphic, ) { - let Some(DeferredMarkup { id, bounds }) = markup else { return }; + let Some(DeferredMarkup { id, bounds, mask }) = markup else { return }; render.drawing_deferred_markup = false; render.leaf_node(deferred_image::image_markers(id).1); @@ -1378,6 +1501,7 @@ fn finish_deferred_markup( margin: render.ancestors_reach, opacity: compositing.opacity, blend_mode, + mask, }); } @@ -1884,8 +2008,22 @@ fn write_svg_effects_filter_on_lattice( let last_operation = operations.iter().rposition(|operation| !operation.changes_nothing()); // Shadows beneath the content reach its alpha only through a later pixel filter (see `is_pixel_filter`) let flattened_shown = |index: usize, within: bool| shows_content || (cuts_within && !within && last_pixel_filter.is_some_and(|last| index < last)); + let blend_ifs: Vec> = (0..operations.len()).map(|index| blend_ifs_acting_before(&operations, index).into_iter().copied().collect()).collect(); + let takes_maps: Vec = (0..operations.len()).map(|index| masked_radius_blur_takes_maps(&operations[..index])).collect(); - for (index, operation) in operations.into_iter().enumerate().filter(|(_, operation)| !operation.changes_nothing()) { + for (index, operation) in operations.into_iter().enumerate() { + // Blend If fades the content by its own colors like a fill varying across it, which only the content's own layer shows + for ranges in blend_ifs[index].iter().filter(|_| shows_content) { + let mut push = |tag: &str, attributes: &str, children: &str| primitives.push(tag, attributes, children); + if let Some(weight) = svg_blend_if::weight(&mut push, &full, &ranges.content) { + let image = filled.take().unwrap_or_else(|| full.clone()); + filled = Some(primitives.push("feComposite", &format!(r#"in="{image}" in2="{weight}" operator="in""#), "")); + } + } + + if operation.changes_nothing() { + continue; + } let paint_markup = svg_drawn_paint(&operation).and_then(|_| paints.next()); // A trailing mask that SVG's own mask carries out still fades the opacity here let (carried_out, fades_layers) = (filtered.contains(&index), layers.trailing_masks.contains(&index)); @@ -1929,13 +2067,17 @@ fn write_svg_effects_filter_on_lattice( } primitives.merge_beneath(&mut full, &mut filled, beneath.take()); - // No SVG primitive sizes a box by each pixel, so the results come from the GPU as maps, leaving the content unblurred until they resolve - if box_blur { + // No SVG primitive sizes a box by each pixel, and a Gaussian after a Blend If can't start a fresh filter (see `masked_radius_blur_takes_maps`), + // so the results come from the GPU as maps, leaving the content unblurred until they resolve + if box_blur || takes_maps[index] { + // A box's results are its planes 0 and 1, and a Gaussian's 1 and 2, past its radius mask's luminance + let (full_plane, filled_plane) = if box_blur { (0, 1) } else { (1, 2) }; + // The full-strength content takes a map only where it shows unfaded or a later effect reads it let full_is_read = filled.is_none() || last_operation.is_some_and(|last| index < last); - filled = filled.map(|filled| primitives.map_standing_in(map_capture(1), "feOffset", &format!(r#"in="{filled}""#))); + filled = filled.map(|filled| primitives.map_standing_in(map_capture(filled_plane), "feOffset", &format!(r#"in="{filled}""#))); if full_is_read { - full = primitives.map_standing_in(map_capture(0), "feOffset", &format!(r#"in="{full}""#)); + full = primitives.map_standing_in(map_capture(full_plane), "feOffset", &format!(r#"in="{full}""#)); } continue; } @@ -2094,8 +2236,8 @@ fn write_svg_effects_filter_on_lattice( full = faded(&full); continue; } - // What lies beneath is copied outside the filter, which can't read it - EffectOperation::BackgroundBlur { .. } => continue, + // What lies beneath is copied outside the filter, which can't read it, and Blend If fades the content where it acts + EffectOperation::BackgroundBlur { .. } | EffectOperation::BlendIf(_) => continue, EffectOperation::Adjustment(ref adjustment) => { if !(shows_content || cuts_within) { continue; @@ -2269,24 +2411,22 @@ fn rect_bounds(rect: kurbo::Rect) -> RenderBoundingBox { RenderBoundingBox::Rectangle([DVec2::new(rect.x0, rect.y0), DVec2::new(rect.x1, rect.y1)]) } -/// The color one paint item contributes, with the adjustments among its effects carried out and faded by its opacity attributes. +/// The color one paint item contributes, with its effects carried out (see [`color_after_effects`]) and faded by its opacity attributes. pub(crate) fn faded_paint_color(item: ItemRef<'_, Color>, for_mask: bool) -> Option { let mut color = *item.element()?; if let Some(effects) = item.attribute::(ATTR_EFFECTS) { - color = adjusted_color(color, &adjustments(effects)); + color = color_after_effects(color, effects); } Some(color.with_alpha(color.a() * item.paint_opacity(for_mask))) } -/// The ramp one gradient paint item contributes, with the adjustments among its effects carried out along it, and the settings to read it with. +/// The ramp one gradient paint item contributes, with its effects carried out along it (see [`gradient_after_effects`]), and the settings to read it with. pub(crate) fn painted_gradient(item: ItemRef<'_, Gradient>) -> Option<(Cow<'_, Gradient>, GradientSettings)> { let gradient = item.element()?; let settings = gradient_settings_from_item(item); - let adjusted = item - .attribute::(ATTR_EFFECTS) - .and_then(|effects| adjusted_gradient(gradient, settings, &adjustments(effects), 1.)); + let adjusted = item.attribute::(ATTR_EFFECTS).and_then(|effects| gradient_after_effects(gradient, settings, effects)); Some(match adjusted { Some((gradient, settings)) => (Cow::Owned(gradient), settings), None => (Cow::Borrowed(gradient), settings), @@ -2346,7 +2486,7 @@ impl MaskType { } } -/// Mutable state used whilst rendering to an SVG +/// Mutable state used while rendering to an SVG pub struct SvgRender { pub svg: Vec, pub svg_defs: String, @@ -2523,7 +2663,7 @@ pub enum RenderOutputType { Vello, } -/// Static state used whilst rendering +/// Static state used while rendering #[derive(Default, Clone, CacheHash)] pub struct RenderParams { pub render_mode: RenderMode, @@ -3220,6 +3360,7 @@ fn render_graphic_item_svg(item: ItemRef<'_, Graphic>, next_clips: bool, mask_st render_params, &compositing, || compositing.bounds_with_frame(effects_bounds(), frame), + endless_area.is_none(), nested_reach.max_element(), ); let filters = compositing.svg_filters(render, render_params, effects_bounds, |keeps| Graphic::Graphic(Box::new(effects_content(item, element.clone(), keeps)))); @@ -4305,7 +4446,7 @@ fn render_vector_item_svg(item: ItemRef<'_, Vector>, next_clips: bool, clip_mask let bounds = vector.stroke_inclusive_bounding_box_with_transform(paths, DAffine2::IDENTITY, stroke.as_ref())?; Some(frame_of_bounds(bounds, item.attribute_cloned_or_default(ATTR_TRANSFORM))) }; - let deferred = start_deferred_markup(render, render_params, &compositing, || compositing.bounds_with_frame(bounds(), frame), 0.); + let deferred = start_deferred_markup(render, render_params, &compositing, || compositing.bounds_with_frame(bounds(), frame), true, 0.); // The filter's maps are of the effects that remain after those folded into the paints, which it numbers them by, and the folded ones keep alpha let filters = compositing.svg_filters(render, render_params, bounds, |keeps| { let mut content = effects_content(item, vector.clone(), keeps); @@ -5072,7 +5213,7 @@ fn render_raster_cpu_item_svg(item: ItemRef<'_, Raster>, render: &mut SvgRe }; let bounds = || RenderBoundingBox::Rectangle((transform * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box()); - let deferred = start_deferred_markup(render, render_params, &compositing, bounds, 0.); + let deferred = start_deferred_markup(render, render_params, &compositing, bounds, true, 0.); // The filter's maps are of the adjusted image with the effects that remain, which the filter numbers them by let filters = compositing.svg_filters(render, render_params, bounds, |keeps| { let mut content = effects_content(item, image.clone(), keeps); @@ -5268,7 +5409,7 @@ fn render_generator_item_svg(item: ItemRef<'_, Generator>, render: &mut SvgRende let image_transform = transform * DAffine2::from_translation(area[0]) * DAffine2::from_scale(area[1] - area[0]); let bounds = (image_transform * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box(); - let deferred = start_deferred_markup(render, render_params, &compositing, || RenderBoundingBox::Rectangle(bounds), 0.); + let deferred = start_deferred_markup(render, render_params, &compositing, || RenderBoundingBox::Rectangle(bounds), false, 0.); let filters = compositing.svg_filters_within(render, render_params, bounds, false, |keeps| { let mut content = effects_content(item, generator, keeps); content.set_attribute(ATTR_EFFECTS, compositing.effects.map(|(effects, _)| effects.clone()).unwrap_or_default()); @@ -5548,14 +5689,14 @@ fn render_color_item_svg(item: ItemRef<'_, Color>, render: &mut SvgRender, rende let Some(&color) = item.element() else { return }; let compositing = item.compositing(render_params, item.attribute_cloned_or_default(ATTR_TRANSFORM)); - // Leading masks that give the color edges let its effects be carried out within them like any other content's, and filters and warps, which change even a flat color, carry them out over the area in view + // Leading masks that give the color edges let its effects be carried out within them like any other content's, and filters, warps, or Blend Ifs spanning runs carry them out over the area in view let extent = compositing .effects .and_then(|(effects, _)| masks::masked_extent(effects, compositing.placement).or_else(|| filtered_endless_area(effects, &compositing, render, render_params))); if let Some(extent) = extent { let blend_mode: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); let bounds = || RenderBoundingBox::Rectangle(extent); - let deferred = start_deferred_markup(render, render_params, &compositing, bounds, 0.); + let deferred = start_deferred_markup(render, render_params, &compositing, bounds, false, 0.); let filters = compositing.svg_filters_within(render, render_params, extent, false, |keeps| Graphic::Color(effects_content(item, color, keeps))); // Without filters, as in an effect space that collapses, the color takes its opacity and blend mode as if its masks left it without edges @@ -5573,9 +5714,10 @@ fn render_color_item_svg(item: ItemRef<'_, Color>, render: &mut SvgRender, rende render_edgeless_color_svg(item, render, &compositing, color, render_params); } -/// Whether the effects change endless content (like a color or gradient filling everything) over the area in view, as filters reading its details do, and warps within their frames. -fn changes_endless_content_in_view(effects: &Effects) -> bool { - graphic_types::filters::has_filters(effects) || warps_change_endless_content(effects) +/// Whether endless content carries out its `effects` over the area in view rather than on its paint: for filters and warps, which change even a flat color, +/// and for Blend Ifs spanning effect runs, which the paint's layers can't carry from one run to the next. +fn carried_out_in_view(effects: &Effects) -> bool { + graphic_types::filters::has_filters(effects) || warps_change_endless_content(effects) || blend_ifs_span_runs(effects) } /// Whether any of the effects is a warp that changes something, which it does within its frame even to endless content. @@ -5583,9 +5725,9 @@ fn warps_change_endless_content(effects: &Effects) -> bool { effects.operations().any(|operation| operation.is_warp() && !operation.changes_nothing()) } -/// The area in view in the current user space, grown past it by how far the `effects` and the groups around them read, for endless content that its filters or warps change there, if it has any. +/// The area in view in the current user space, grown past it by how far the `effects` and the groups around them read, for endless content carrying them out there (see [`carried_out_in_view`]). fn filtered_endless_area(effects: &Effects, compositing: &ItemCompositing, render: &SvgRender, render_params: &RenderParams) -> Option<[DVec2; 2]> { - if !changes_endless_content_in_view(effects) { + if !carried_out_in_view(effects) { return None; } let own_reach = effects @@ -5608,8 +5750,8 @@ fn render_edgeless_color_svg(item: ItemRef<'_, Color>, render: &mut SvgRender, c } // SVG filters change nothing else visible about an endless color, so its adjustments are carried out on the color itself - let paint = compositing.endless_paint(); - let shown = filled_color(color, &paint.adjustments, paint.fill); + let paint = compositing.endless_color_paint(color); + let shown = paint.shown_color(color, paint.fill); let full_alpha = adjusted_color(color, &paint.adjustments).a(); // The masks among its effects wrap it in a group, which takes its blend mode so it blends with what lies beneath the group @@ -5660,13 +5802,26 @@ fn emit_endless_shape(attributes: &mut SvgRenderAttrs, rect: Option<(DVec2, DVec } /// For endless content (a color or gradient filling everything) with random field filters (like Add Noise), the adjustments before the first of them, which its paint takes instead, -/// and the effects from there that change it: the random field filters with the adjustments, blurs, and masks after them. Its other effects have no edges to cast from. `None` without a random field filter. +/// and the effects from there that change it: the random field filters with the adjustments, blurs, masks, and Blend Ifs' content ranges after them. Its other effects have no edges to cast from. `None` without a random field filter. fn endless_field_effects(compositing: &ItemCompositing) -> Option<(Vec, Effects)> { let (effects, fill) = compositing.effects?; - let shown_effects = effects.keeping(|operation| { - let changes_endless_content = matches!(operation, EffectOperation::Adjustment(_) | EffectOperation::Blur { .. } | EffectOperation::Mask { .. }); - !operation.changes_nothing() && (changes_endless_content || is_random_field_filter(operation)) + let mut shown_effects = effects.keeping(|operation| match operation { + EffectOperation::BlendIf(ranges) => !ranges.content.show_everything(), + operation => { + let changes_endless_content = matches!(operation, EffectOperation::Adjustment(_) | EffectOperation::Blur { .. } | EffectOperation::Mask { .. }); + !operation.changes_nothing() && (changes_endless_content || is_random_field_filter(operation)) + } }); + + // Content without bounds reads nothing beneath it, so a Blend If acts by its content's ranges alone + for index in 0..shown_effects.len() { + if let Some(effect) = shown_effects.0.element_mut(index) + && let EffectOperation::BlendIf(ranges) = effect.operation() + { + let underlying = Default::default(); + *effect = graphic_types::Effect::new(&EffectOperation::BlendIf(Box::new(BlendIfRanges { underlying, ..*ranges }))); + } + } let shown: Vec = shown_effects.operations().collect(); if !shown.iter().any(is_random_field_filter) { return None; @@ -5678,7 +5833,7 @@ fn endless_field_effects(compositing: &ItemCompositing) -> Option<(Vec { let with_content = *index < layers.flattened || layers.layer_of(EffectCapture { index: *index, plane: 0 }) == layers.content_layer(); - fill == 1. && with_content + fill == 1. && with_content && paint_overlay_folds(&shown, *index) } EffectOperation::Adjustment(adjustment) => fill == 1. || raster_kernels::adjustments::preserves_alpha(adjustment), _ => false, @@ -5796,8 +5951,8 @@ fn render_color_item_to_vello(item: ItemRef<'_, Color>, scene: &mut VelloSceneBu let blend_mode: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); - // Leading masks that give the color edges let its effects be carried out within them like any other content's, and filters and warps, which change even a flat color, carry them out over the area in view, as in SVG - let carried_out = |effects: &Effects| masks::masked_extent(effects, compositing.placement).is_some() || changes_endless_content_in_view(effects); + // Leading masks that give the color edges let its effects be carried out within them like any other content's, and filters, warps, or Blend Ifs spanning runs carry them out over the area in view, as in SVG + let carried_out = |effects: &Effects| masks::masked_extent(effects, compositing.placement).is_some() || carried_out_in_view(effects); if compositing.effects.is_some_and(|(effects, _)| carried_out(effects)) { let vello_color = SRGBA8::from(color).to_peniko_color(); return draw_endless_item_with_effects(scene, &compositing, blend_mode, parent_transform, render_params, |scene| scene.fill_viewport(vello_color, None)); @@ -5810,8 +5965,8 @@ fn render_color_item_to_vello(item: ItemRef<'_, Color>, scene: &mut VelloSceneBu return draw_endless_item_with_effects(scene, &compositing, blend_mode, parent_transform, render_params, |scene| scene.fill_viewport(vello_color, None)); } - let paint = compositing.endless_paint(); - let shown = SRGBA8::from(filled_color(color, &paint.adjustments, paint.fill)).to_peniko_color(); + let paint = compositing.endless_color_paint(color); + let shown = SRGBA8::from(paint.shown_color(color, paint.fill)).to_peniko_color(); let full_alpha = adjusted_color(color, &paint.adjustments).a(); let masks = endless_masks(&compositing); @@ -5910,14 +6065,14 @@ fn render_gradient_item_svg_with_thumbnail_rect(item: ItemRef<'_, Gradient>, thu let compositing = item.compositing(render_params, item.attribute_cloned_or_default(ATTR_TRANSFORM)); let settings = gradient_settings_from_item(item); - // Leading masks that give the gradient edges let its effects be carried out within them like any other content's, and filters reading its details and warps carry them out over the area in view + // Leading masks that give the gradient edges let its effects be carried out within them like any other content's, and filters reading its details, warps, or Blend Ifs spanning runs carry them out over the area in view let extent = compositing .effects .and_then(|(effects, _)| masks::masked_extent(effects, compositing.placement).or_else(|| filtered_endless_area(effects, &compositing, render, render_params))); if let Some(extent) = extent.filter(|_| thumbnail_rect.is_none()) { let blend_mode: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); let bounds = || RenderBoundingBox::Rectangle(extent); - let deferred = start_deferred_markup(render, render_params, &compositing, bounds, 0.); + let deferred = start_deferred_markup(render, render_params, &compositing, bounds, false, 0.); let filters = compositing.svg_filters_within(render, render_params, extent, false, |keeps| Graphic::Gradient(effects_content(item, source_gradient.clone(), keeps))); // Without filters, as in an effect space that collapses, the gradient takes its opacity and blend mode as if its masks left it without edges @@ -5974,7 +6129,7 @@ fn render_edgeless_gradient_svg( // SVG filters change nothing else visible about an endless gradient, so its adjustments are carried out along its ramp let paint = compositing.endless_paint(); let (fill, opacity) = paint.ramp_fill_and_opacity(); - let (gradient, settings) = match adjusted_gradient(source_gradient, settings, &paint.adjustments, fill) { + let (gradient, settings) = match paint.adjusted_gradient(source_gradient, settings, fill) { Some((adjusted, settings)) => (Cow::Owned(adjusted), settings), None => (Cow::Borrowed(source_gradient), settings), }; @@ -6078,8 +6233,8 @@ fn render_gradient_item_to_vello(item: ItemRef<'_, Gradient>, scene: &mut VelloS let blend_mode: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE); - // Leading masks that give the gradient edges let its effects be carried out within them like any other content's, and filters reading its details and warps carry them out over the area in view, as in SVG - let carried_out = |effects: &Effects| masks::masked_extent(effects, compositing.placement).is_some() || changes_endless_content_in_view(effects); + // Leading masks that give the gradient edges let its effects be carried out within them like any other content's, and filters reading its details, warps, or Blend Ifs spanning runs carry them out over the area in view, as in SVG + let carried_out = |effects: &Effects| masks::masked_extent(effects, compositing.placement).is_some() || carried_out_in_view(effects); if compositing.effects.is_some_and(|(effects, _)| carried_out(effects)) { let (brush, brush_transform) = gradient_brush(item, source_gradient, settings, parent_transform); return draw_endless_item_with_effects(scene, &compositing, blend_mode, parent_transform, render_params, |scene| { @@ -6103,7 +6258,7 @@ fn render_gradient_item_to_vello(item: ItemRef<'_, Gradient>, scene: &mut VelloS // Its adjustments are carried out along the ramp, as in SVG let paint = compositing.endless_paint(); let (fill, opacity) = paint.ramp_fill_and_opacity(); - let (gradient, settings) = match adjusted_gradient(source_gradient, settings, &paint.adjustments, fill) { + let (gradient, settings) = match paint.adjusted_gradient(source_gradient, settings, fill) { Some((adjusted, settings)) => (Cow::Owned(adjusted), settings), None => (Cow::Borrowed(source_gradient), settings), }; @@ -6589,7 +6744,7 @@ fn render_text_item_svg(item: ItemRef<'_, String>, render: &mut SvgRender, rende return; } - let deferred = start_deferred_markup(render, render_params, &compositing, || layout_bounds, 0.); + let deferred = start_deferred_markup(render, render_params, &compositing, || layout_bounds, true, 0.); let filters = compositing.svg_filters(render, render_params, || layout_bounds, |keeps| Graphic::Text(effects_content(item, text.clone(), keeps))); let filtered = filters.is_some(); @@ -6789,7 +6944,7 @@ impl Render for List { pub enum SvgSegment { Slice(&'static str), String(String), - /// Markup showing what lies beneath content reading it, which copies of what lies beneath can leave out. + /// Markup showing what lies beneath content reading it, or referencing a mask that does, which copies of what lies beneath can leave out. Backdrop(String), } @@ -6848,6 +7003,13 @@ impl SvgRenderAttrs<'_> { } self.push_complex(name, move |renderer| renderer.svg.push(value)); } + /// Pushes an attribute holding a copy of what lies beneath, as one segment that copies of what lies beneath can leave out (see [`SvgSegment::Backdrop`]). + pub fn push_backdrop(&mut self, name: &str, value: &str) { + if svg_backdrop::isolates(name, value) { + self.0.open_groups.opening_isolates = true; + } + self.0.svg.push(SvgSegment::Backdrop(format!(r#" {name}="{value}""#))); + } pub fn push_val(&mut self, value: impl Into) { self.0.svg.push(value.into()); } @@ -8496,6 +8658,155 @@ mod tests { assert_eq!(taken(&alpha_curve, 0.5), Some(0)); } + #[test] + fn endless_random_fields_keep_the_blend_ifs_among_the_effects_they_change() { + use graphic_types::blend_if::BlendIfRanges; + use graphic_types::{Effect, EffectOperation, NoiseDistribution, stamp_effect}; + + // A Blend If hiding the darker half of the color as the paint's adjustment leaves it, which the noise's effects then carry out + let mut ranges = BlendIfRanges::default(); + ranges.content.gray.range_start = 50.; + let noise = EffectOperation::AddNoise { + amount: 20., + distribution: NoiseDistribution::Uniform, + monochromatic: false, + seed: 0, + }; + let mut item = Item::new_from_element(Color::BLACK); + for operation in [EffectOperation::Adjustment(Adjustment::Invert), EffectOperation::BlendIf(Box::new(ranges)), noise] { + stamp_effect(&mut item, Effect::new(&operation)); + } + + let compositing = ItemRef::Item(&item).compositing(&RenderParams::default(), DAffine2::IDENTITY); + let (adjustments, remaining) = endless_field_effects(&compositing).expect("the noise changes the color"); + assert_eq!(adjustments.len(), 1); + assert!(matches!(remaining.operations().next(), Some(EffectOperation::BlendIf(_))), "{remaining:?}"); + } + + #[test] + fn svg_endless_random_fields_fade_by_the_blend_ifs_content_ranges_alone() { + use graphic_types::blend_if::BlendIfRanges; + use graphic_types::raster_types::Image; + use graphic_types::{Effect, EffectOperation, NoiseDistribution, stamp_effect}; + + // A noisy color over an image, with a Blend If reading its own tones and what lies beneath + let mut ranges = BlendIfRanges::default(); + ranges.content.gray.range_start = 50.; + ranges.underlying.gray.range_start = 50.; + let noise = EffectOperation::AddNoise { + amount: 20., + distribution: NoiseDistribution::Uniform, + monochromatic: false, + seed: 0, + }; + let mut color = Item::new_from_element(Color::WHITE); + for operation in [EffectOperation::BlendIf(Box::new(ranges)), noise] { + stamp_effect(&mut color, Effect::new(&operation)); + } + let image = Item::new_from_element(Raster::new_cpu(Image::new(2, 2, Color::BLACK))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(20.))); + + let mut render = SvgRender::new(); + let render_params = RenderParams { + for_export: true, + view: Some(Footprint { + resolution: glam::UVec2::splat(20), + ..Default::default() + }), + ..Default::default() + }; + List::new_from_item(image).render_svg(&mut render, &render_params); + List::new_from_item(color).render_svg(&mut render, &render_params); + + // Only its own tones fade it, as on the GPU + assert!(render.svg_defs.contains(r#"