From 12daaf8ab03b033b828b68f413e96809ef65b309 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Fri, 4 Dec 2026 23:57:48 -0800 Subject: [PATCH] Rename the 'Image to Channels' node to 'Into Channels' and defer its channels on any graphic --- Cargo.lock | 2 + .../nodes/src/raster_nodes/renames.rs | 3 + .../messages/portfolio/document_migration.rs | 12 +- .../libraries/graphic-types/src/adjustment.rs | 5 +- .../libraries/graphic-types/src/effects.rs | 17 +- node-graph/libraries/graphic-types/src/lib.rs | 2 +- .../raster-kernels/src/adjustment_steps.rs | 5 +- .../raster-kernels/src/adjustments.rs | 15 ++ .../libraries/rendering/src/renderer.rs | 6 +- .../wgpu-executor/src/vello_adjustments.rs | 1 + .../wgpu-executor/src/vello_adjustments.wgsl | 5 + .../wgpu-executor/src/vello_render/tests.rs | 11 + node-graph/nodes/raster/Cargo.toml | 5 + node-graph/nodes/raster/src/adjustments.rs | 39 +--- node-graph/nodes/raster/src/channels.rs | 198 ++++++++++++++++++ node-graph/nodes/raster/src/lib.rs | 1 + 16 files changed, 279 insertions(+), 48 deletions(-) create mode 100644 node-graph/nodes/raster/src/channels.rs diff --git a/Cargo.lock b/Cargo.lock index 2d18223b06..041e9e6d7a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5772,12 +5772,14 @@ dependencies = [ "node-macro", "raster-kernels", "raster-types", + "rendering", "serde", "thiserror 2.0.21", "tokio", "tsify", "vector-types", "wasm-bindgen", + "wgpu-executor", ] [[package]] diff --git a/document/migrations/nodes/src/raster_nodes/renames.rs b/document/migrations/nodes/src/raster_nodes/renames.rs index 6ee56d2d41..db3c87319e 100644 --- a/document/migrations/nodes/src/raster_nodes/renames.rs +++ b/document/migrations/nodes/src/raster_nodes/renames.rs @@ -4,3 +4,6 @@ use migration_core::rename; // Version 2 is where old Mix nodes join the lineage, and stored Mix Colors nodes already have its layout rename!("raster_nodes::blending_nodes::MixColorsNode"@1 => @2); + +// 'Image to Channels' became 'Into Channels', taking and giving graphics, whose stored input and channel outputs keep their places +rename!("raster_nodes::adjustments::ImageToChannelsNode"@1 => "raster_nodes::channels::IntoChannelsNode"@2); diff --git a/editor/src/messages/portfolio/document_migration.rs b/editor/src/messages/portfolio/document_migration.rs index 521b920338..f20260c3ff 100644 --- a/editor/src/messages/portfolio/document_migration.rs +++ b/editor/src/messages/portfolio/document_migration.rs @@ -544,6 +544,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[ "raster_nodes::blending_nodes::ColorOverlayNode", ], }, + NodeReplacement { + node: graphene_std::raster_nodes::channels::into_channels::IDENTIFIER, + aliases: &["raster_nodes::adjustments::ImageToChannelsNode"], + }, NodeReplacement { node: graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER, aliases: &[ @@ -1564,13 +1568,13 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_ } } - // The "Split Vec2", "Split Vector2", and "Split Channels" wrapper networks became the multi-output `vec2_to_numbers` and `image_to_channels` proto nodes. + // The "Split Vec2", "Split Vector2", and "Split Channels" wrapper networks became the multi-output `vec2_to_numbers` and `into_channels` proto nodes. // A wrapper saved before these gained a hidden primary output had each field one output lower, so its wires shift up by one. // Pre-pass for the same reason as the Brush, Transform, and Image migrations above: replacing the outer network impl orphans its child paths. let split_wrapper_replacements = [ ("Split Vec2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER), ("Split Vector2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER), - ("Split Channels", graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER), + ("Split Channels", graphene_std::raster_nodes::channels::into_channels::IDENTIFIER), ]; for (old_reference, new_identifier) in split_wrapper_replacements { let split_nodes: Vec<(NodeId, Vec)> = document @@ -1616,7 +1620,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_ } } - // The standalone "Extract XY" and "Extract Channel" nodes were removed in favor of the multi-output "Vec2 to Numbers" and "Image to Channels" nodes. + // The standalone "Extract XY" and "Extract Channel" nodes were removed in favor of the multi-output "Vec2 to Numbers" and "Into Channels" nodes. // Convert each to its replacement, moving its downstream wires to the field output for the axis or channel it extracted. const EXTRACT_XY: [&str; 2] = ["graphene_core::extract_xy::ExtractXyNode", "graphene_core::ops::ExtractXyNode"]; const EXTRACT_CHANNEL: [&str; 4] = [ @@ -1635,7 +1639,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_ if EXTRACT_XY.contains(&name) { Some((*node_id, path, graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER, "Extract XY")) } else if EXTRACT_CHANNEL.contains(&name) { - Some((*node_id, path, graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER, "Extract Channel")) + Some((*node_id, path, graphene_std::raster_nodes::channels::into_channels::IDENTIFIER, "Extract Channel")) } else { None } diff --git a/node-graph/libraries/graphic-types/src/adjustment.rs b/node-graph/libraries/graphic-types/src/adjustment.rs index 1c0c21e770..be36e81088 100644 --- a/node-graph/libraries/graphic-types/src/adjustment.rs +++ b/node-graph/libraries/graphic-types/src/adjustment.rs @@ -86,6 +86,8 @@ pub enum Adjustment { opacity: f64, }, Solarize, + /// Shows the alpha as a gray of the same gamma-encoded level, keeping the alpha, so a luminance mask of the gray shows as much as the alpha. + AlphaToGray, } impl Adjustment { @@ -112,6 +114,7 @@ impl Adjustment { Self::ColorLookup { .. } => EffectKind::ColorLookup, Self::ColorOverlay { .. } => EffectKind::PaintOverlay, Self::Solarize => EffectKind::Solarize, + Self::AlphaToGray => EffectKind::AlphaToGray, } } @@ -151,7 +154,7 @@ impl Adjustment { visitor.parameter("inverse", inverse, false); } Self::MakeOpaque { strength } => visitor.parameter("strength", strength, 100.), - Self::Invert | Self::Solarize => {} + Self::Invert | Self::Solarize | Self::AlphaToGray => {} Self::BrightnessContrast { brightness, contrast, diff --git a/node-graph/libraries/graphic-types/src/effects.rs b/node-graph/libraries/graphic-types/src/effects.rs index 51939213f8..c6a5ca2494 100644 --- a/node-graph/libraries/graphic-types/src/effects.rs +++ b/node-graph/libraries/graphic-types/src/effects.rs @@ -15,7 +15,7 @@ use core_types::Color; use core_types::blending::BlendMode; use core_types::color::SRGBA8; use core_types::graphene_hash::CacheHash; -use core_types::list::{ATTR_EFFECTS, ATTR_OPACITY, ATTR_OPACITY_FILL, Item, List}; +use core_types::list::{ATTR_EFFECTS, ATTR_OPACITY, ATTR_OPACITY_FILL, Item, ItemAttributeValues, List}; use core_types::transfer_curve::{TransferCurve, TransferCurveEvaluator}; use dyn_any::DynAny; use glam::{DAffine2, DMat2, DVec2, DVec3}; @@ -117,6 +117,8 @@ pub enum EffectKind { PhotoFilter, ColorLookup, Solarize, + /// Shows the content's alpha as a gray, as 'Into Channels' does for its alpha output. + AlphaToGray, } impl std::fmt::Display for EffectKind { @@ -175,6 +177,7 @@ impl std::fmt::Display for EffectKind { Self::PhotoFilter => "Photo Filter", Self::ColorLookup => "Color Lookup", Self::Solarize => "Solarize", + Self::AlphaToGray => "Alpha to Gray", }) } } @@ -846,8 +849,14 @@ pub fn contour_gradient_position(distance: f32, start: f32, span: f32) -> f32 { /// Appends an effect to the item's list, after those already applied to it, recording the item's transform at that point. /// Like a stroke's transform, it sets the space the effect's lengths and angles are measured in, so transforms applied later carry and scale the effect. pub fn stamp_effect(item: &mut Item, effect: Effect) { - let transform = stamped_transform(item.attribute_cloned_or_default(ATTR_TRANSFORM)); - item.attribute_mut_or_insert_default::(ATTR_EFFECTS) + stamp_effect_on(item.attributes_mut(), effect); +} + +/// Like [`stamp_effect`], given the item's attributes. +pub fn stamp_effect_on(attributes: &mut ItemAttributeValues, effect: Effect) { + let transform = stamped_transform(attributes.get::(ATTR_TRANSFORM).copied().unwrap_or_default()); + attributes + .get_or_insert_default_mut::(ATTR_EFFECTS) .0 .push(Item::new_from_element(effect).with_attribute(ATTR_TRANSFORM, transform)); } @@ -1886,6 +1895,7 @@ impl EffectOperation { }), EffectKind::ColorLookup => Self::Adjustment(Adjustment::ColorLookup { lut_file: Default::default() }), EffectKind::Solarize => Self::Adjustment(Adjustment::Solarize), + EffectKind::AlphaToGray => Self::Adjustment(Adjustment::AlphaToGray), } } @@ -2899,6 +2909,7 @@ mod tests { PhotoFilter, ColorLookup, Solarize, + AlphaToGray, PaintOverlay, ]; for kind in kinds { diff --git a/node-graph/libraries/graphic-types/src/lib.rs b/node-graph/libraries/graphic-types/src/lib.rs index 8067c649f8..f873e04f3c 100644 --- a/node-graph/libraries/graphic-types/src/lib.rs +++ b/node-graph/libraries/graphic-types/src/lib.rs @@ -24,7 +24,7 @@ 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, + stamp_effect, stamp_effect_on, stamped_transform, }; pub use filters::NoiseDistribution; pub use generator::Generator; diff --git a/node-graph/libraries/raster-kernels/src/adjustment_steps.rs b/node-graph/libraries/raster-kernels/src/adjustment_steps.rs index 2f93378429..2aab89f79d 100644 --- a/node-graph/libraries/raster-kernels/src/adjustment_steps.rs +++ b/node-graph/libraries/raster-kernels/src/adjustment_steps.rs @@ -30,11 +30,12 @@ pub enum StepKind { ColorLookup, ColorOverlay, Solarize, + AlphaToGray, } impl StepKind { /// Every kind, in the order of their codes. - pub const ALL: [StepKind; 21] = [ + pub const ALL: [StepKind; 22] = [ StepKind::Desaturate, StepKind::GammaCorrection, StepKind::MakeOpaque, @@ -56,6 +57,7 @@ impl StepKind { StepKind::ColorLookup, StepKind::ColorOverlay, StepKind::Solarize, + StepKind::AlphaToGray, ]; /// The number a step's header holds for its kind, which the shader picks the step's function by. @@ -269,6 +271,7 @@ mod tests { opacity: 50., }, Adjustment::Solarize, + Adjustment::AlphaToGray, ]; let steps = AdjustmentSteps::encode(&run.iter().collect::>()); diff --git a/node-graph/libraries/raster-kernels/src/adjustments.rs b/node-graph/libraries/raster-kernels/src/adjustments.rs index eb94414320..e08313a316 100644 --- a/node-graph/libraries/raster-kernels/src/adjustments.rs +++ b/node-graph/libraries/raster-kernels/src/adjustments.rs @@ -226,6 +226,7 @@ pub fn visit_kernel(adjustment: &Adjustment, visitor: V) - } Adjustment::Invert => visitor.visit(Invert), Adjustment::Solarize => visitor.visit(Solarize), + Adjustment::AlphaToGray => visitor.visit(AlphaToGray), Adjustment::Threshold { min_luminance, max_luminance } => visitor.visit(Threshold { min_luminance: (min_luminance / 100.) as f32, max_luminance: (max_luminance / 100.) as f32, @@ -1121,6 +1122,20 @@ impl MapColor for Solarize { } } +/// Grays each color to the gamma-encoded level of its alpha, keeping the alpha. +struct AlphaToGray; + +impl MapColor for AlphaToGray { + fn map_cpu(&self, color: Color) -> Color { + let gray = srgb_to_linear(color.a()); + color.map_rgb(|_| gray) + } + + fn encode_step(&self, steps: &mut AdjustmentSteps) { + steps.push(StepKind::AlphaToGray, []); + } +} + struct Threshold { min_luminance: f32, max_luminance: f32, diff --git a/node-graph/libraries/rendering/src/renderer.rs b/node-graph/libraries/rendering/src/renderer.rs index 23f44a6f13..0126fc1b6f 100644 --- a/node-graph/libraries/rendering/src/renderer.rs +++ b/node-graph/libraries/rendering/src/renderer.rs @@ -1755,7 +1755,7 @@ fn svg_expresses_adjustment(adjustment: &Adjustment) -> bool { use graphic_types::adjustment::DesaturateMethod; match adjustment { - Adjustment::Threshold { .. } | Adjustment::GradientMap { .. } | Adjustment::ChannelMixer(_) | Adjustment::ColorOverlay { .. } => true, + Adjustment::Threshold { .. } | Adjustment::GradientMap { .. } | Adjustment::ChannelMixer(_) | Adjustment::ColorOverlay { .. } | Adjustment::AlphaToGray => true, Adjustment::Desaturate { method } => matches!( method, DesaturateMethod::LuminanceRec709 | DesaturateMethod::ChannelsAverage | DesaturateMethod::LumaRec709 | DesaturateMethod::LumaRec601 @@ -2095,6 +2095,10 @@ impl SvgFilterPrimitives { }; self.push("feColorMatrix", &format!(r#"in="{image}" color-interpolation-filters="{space}" {}"#, matrix([weights; 3])), "") } + Adjustment::AlphaToGray => { + let values = "0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0"; + self.push("feColorMatrix", &format!(r#"{} type="matrix" values="{values}""#, in_gamma(image)), "") + } // TODO: Express the other cross-channel adjustments, which no SVG primitive covers exactly _ => image.to_string(), } diff --git a/node-graph/libraries/wgpu-executor/src/vello_adjustments.rs b/node-graph/libraries/wgpu-executor/src/vello_adjustments.rs index ba606470cc..227ca9d538 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_adjustments.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_adjustments.rs @@ -109,6 +109,7 @@ fn step_function(kind: StepKind) -> (&'static str, Option<[Encoding; 2]>) { StepKind::ColorLookup => ("color_lookup", Some([Gamma, Gamma])), StepKind::ColorOverlay => ("color_overlay", Some([Gamma, Gamma])), StepKind::Solarize => ("solarize", Some([Gamma, Gamma])), + StepKind::AlphaToGray => ("alpha_to_gray", Some([Gamma, Gamma])), } } diff --git a/node-graph/libraries/wgpu-executor/src/vello_adjustments.wgsl b/node-graph/libraries/wgpu-executor/src/vello_adjustments.wgsl index a7a864330e..f09da5942e 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_adjustments.wgsl +++ b/node-graph/libraries/wgpu-executor/src/vello_adjustments.wgsl @@ -365,6 +365,11 @@ fn solarize(color: vec4, at: u32) -> vec4 { return vec4(min(color.rgb, 1. - color.rgb), color.a); } +// The alpha as a gray of the same gamma-encoded level, keeping the alpha +fn alpha_to_gray(color: vec4, at: u32) -> vec4 { + return vec4(vec3(color.a), color.a); +} + // Matches `apply_levels` with the gamma of 1 that every caller here passes, so its power is left out fn apply_levels(value: f32, input_shadows: f32, input_highlights: f32, output_minimum: f32, output_maximum: f32) -> f32 { let highlights_minus_shadows = clamp(input_highlights - input_shadows, F32_EPSILON, 1.); diff --git a/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs b/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs index 5a5b2623ec..54160a8ae1 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs @@ -5279,9 +5279,20 @@ fn gpu_color_adjustments_match_the_cpu_kernels() { ("Photo Filter", photo_filter(warming, 25., true)), ("Photo Filter at full density", photo_filter(cooling, 100., false)), ("Photo Filter at full density preserving luminosity", photo_filter(cooling, 100., true)), + ("Alpha to Gray", Adjustment::AlphaToGray), ]; let mut runs: Vec<(String, Vec)> = runs.into_iter().map(|(name, adjustment)| (name.to_string(), vec![adjustment])).collect(); + // The opaque grays of one channel each that 'Into Channels' outputs + let opaque = Adjustment::MakeOpaque { strength: 100. }; + let green_gray = Adjustment::ChannelMixer(Box::new(ChannelMixerSettings { + monochrome: true, + monochrome_mix: row(0., 100., 0., 0.), + ..Default::default() + })); + runs.push(("Green as an opaque gray".to_string(), vec![green_gray, opaque.clone()])); + runs.push(("Alpha as an opaque gray".to_string(), vec![Adjustment::AlphaToGray, opaque])); + // Every blend mode, overlaying an opaque color and a translucent one, each with a luma apart from every test color's, which Darker Color and Lighter Color compare, and off Hard Mix's steep ramp over them for blend_mode in BlendMode::list().into_iter().flatten().chain(&[BlendMode::Erase, BlendMode::Restore, BlendMode::MultiplyAlpha]) { for (color, opacity) in [ diff --git a/node-graph/nodes/raster/Cargo.toml b/node-graph/nodes/raster/Cargo.toml index c0ef7cf804..6b39d1e0d4 100644 --- a/node-graph/nodes/raster/Cargo.toml +++ b/node-graph/nodes/raster/Cargo.toml @@ -53,5 +53,10 @@ tsify = { workspace = true, optional = true } wasm-bindgen = { workspace = true, optional = true } [dev-dependencies] +# Local dependencies +rendering = { workspace = true } +wgpu-executor = { workspace = true } + +# Workspace dependencies tokio = { workspace = true } futures = { workspace = true } diff --git a/node-graph/nodes/raster/src/adjustments.rs b/node-graph/nodes/raster/src/adjustments.rs index 48a0c53b78..cd95c077a6 100644 --- a/node-graph/nodes/raster/src/adjustments.rs +++ b/node-graph/nodes/raster/src/adjustments.rs @@ -15,7 +15,7 @@ pub use graphic_types::adjustment::{DesaturateMethod, RelativeAbsolute}; pub use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior, NoiseType}; use graphic_types::{Effect, EffectOperation, Generator, Graphic, Vector, stamp_effect}; use raster_kernels::{evaluate_color_parameter, evaluate_gradient_effects}; -use raster_types::{CPU, GPU, Image, Raster}; +use raster_types::{CPU, GPU, Raster}; use vector_types::Gradient; /// Stamps the adjustment onto the item's effects, to be carried out wherever its content is rendered or read. @@ -50,42 +50,6 @@ fn gamma_correction( ) } -/// The red, green, blue, and alpha channels of an image, split into separate node outputs. -#[derive(Debug, Clone, dyn_any::DynAny, node_macro::Destructure)] -pub struct ImageChannels { - /// The red channel of the image, as a grayscale image. - pub red: Item>, - /// The green channel of the image, as a grayscale image. - pub green: Item>, - /// The blue channel of the image, as a grayscale image. - pub blue: Item>, - /// The alpha channel of the image, as a grayscale image. - pub alpha: Item>, -} - -/// Separates an image into its red, green, blue, and alpha channels, each provided as a grayscale image. -#[node_macro::node(category("Raster"), icon("NodeImageToChannels"), name("Image to Channels"))] -fn image_to_channels(_: impl Ctx, image: Item>) -> ImageChannels { - let (image, attributes) = raster_kernels::evaluate_raster_effects(image).into_parts(); - let (width, height) = (image.width, image.height); - - // O(4 × pixels), since all four channels are written even when only some outputs are connected - let mut channels: [Vec; 4] = core::array::from_fn(|_| Vec::with_capacity(image.data.len())); - for color in &image.data { - for (channel, value) in channels.iter_mut().zip([color.r(), color.g(), color.b(), color.a()]) { - channel.push(Color::from_rgbaf32_unchecked(value, value, value, 1.)); - } - } - - // Each channel image keeps the source image's attributes, such as its transform - let [red, green, blue, alpha] = channels.map(|data| { - let channel_image = Image { width, height, data }; - Item::from_parts(Raster::new_cpu(channel_image), attributes.clone()) - }); - - ImageChannels { red, green, blue, alpha } -} - #[node_macro::node(category("Raster: Adjustment"), icon("NodeMakeOpaque"), version(2))] fn make_opaque( _: impl Ctx, @@ -1461,6 +1425,7 @@ mod _graphene_hash_impls { mod tests { use super::*; use raster_kernels::evaluate_color_effects; + use raster_types::Image; /// Matched to within one 8-bit level. fn assert_close(actual: [f32; 3], expected: [f32; 3]) { diff --git a/node-graph/nodes/raster/src/channels.rs b/node-graph/nodes/raster/src/channels.rs new file mode 100644 index 0000000000..dc27901f26 --- /dev/null +++ b/node-graph/nodes/raster/src/channels.rs @@ -0,0 +1,198 @@ +use core_types::ATTR_OPACITY_FILL; +use core_types::context::Ctx; +use core_types::list::{ATTR_EFFECTS, Item, ItemAttributeValues}; +use graphic_types::adjustment::{Adjustment, ChannelMixerRow, ChannelMixerSettings}; +use graphic_types::{Effect, EffectOperation, Effects, Graphic, stamp_effect_on}; + +/// The red, green, blue, and alpha channels of a graphic, split into separate node outputs. +#[derive(Debug, Clone, dyn_any::DynAny, node_macro::Destructure)] +pub struct Channels { + /// The red channel of the graphic as a grayscale graphic, keeping the graphic's transparency. + pub red: Item, + /// The green channel of the graphic as a grayscale graphic, keeping the graphic's transparency. + pub green: Item, + /// The blue channel of the graphic as a grayscale graphic, keeping the graphic's transparency. + pub blue: Item, + /// The alpha channel of the graphic as an opaque grayscale graphic, from black where the graphic is transparent to white where it's opaque. + pub alpha: Item, +} + +/// Separates the input graphic into its red, green, blue, and alpha channels, each as a grayscale graphic. +/// +/// The color channels keep the graphic's transparency, while the alpha channel is opaque, so it masks by its luminance as the alpha did. +#[node_macro::node(category("Raster"), icon("NodeImageToChannels"), version(2))] +fn into_channels(_: impl Ctx, content: Item) -> Channels { + // Each output is the content with adjustments graying it by one channel, carried out wherever it's rendered or read + let channel = |grays: &[Adjustment]| { + let mut channel = content.clone(); + with_effects_holder(&mut channel, |attributes| grays.iter().for_each(|gray| stamp_adjustment(attributes, gray.clone()))); + channel + }; + + Channels { + red: channel(&[channel_gray([100., 0., 0.])]), + green: channel(&[channel_gray([0., 100., 0.])]), + blue: channel(&[channel_gray([0., 0., 100.])]), + alpha: channel(&[Adjustment::AlphaToGray, Adjustment::MakeOpaque { strength: 100. }]), + } +} + +/// Gives `edit` the attributes of the item a graphic's effects go on. +/// That's the one item the graphic holds, which keeps the handling of its own kind (an image's adjustments reach even its fully transparent pixels) and stays an image for 'Flatten Raster' to take out, +/// unless the graphic's own effects or fill, which act before effects appended to the graphic, would then act after them. +fn with_effects_holder(graphic: &mut Item, edit: impl FnOnce(&mut ItemAttributeValues) -> R) -> R { + let envelope_has_effects = graphic.attribute::(ATTR_EFFECTS).is_some_and(|effects| !effects.is_empty()); + let envelope_acts_first = envelope_has_effects || graphic.attribute_cloned_or::(ATTR_OPACITY_FILL, 1.) != 1.; + + if !envelope_acts_first && let Some(attributes) = lone_item_attributes(graphic.element_mut()) { + return edit(attributes); + } + edit(graphic.attributes_mut()) +} + +/// The attributes of the one item a graphic holds, or `None` if it holds a list. +fn lone_item_attributes(graphic: &mut Graphic) -> Option<&mut ItemAttributeValues> { + Some(match graphic { + Graphic::Graphic(item) => item.attributes_mut(), + Graphic::Vector(item) => item.attributes_mut(), + Graphic::RasterCPU(item) => item.attributes_mut(), + Graphic::RasterGPU(item) => item.attributes_mut(), + Graphic::Color(item) => item.attributes_mut(), + Graphic::Gradient(item) => item.attributes_mut(), + Graphic::Generator(item) => item.attributes_mut(), + Graphic::Text(item) => item.attributes_mut(), + _ => return None, + }) +} + +/// Stamps the adjustment onto the effects in these attributes. +fn stamp_adjustment(attributes: &mut ItemAttributeValues, adjustment: Adjustment) { + stamp_effect_on(attributes, Effect::new(&EffectOperation::Adjustment(adjustment))); +} + +/// A monochrome Channel Mixer graying each color by its red, green, and blue channels weighted by the `weights` in percent. +fn channel_gray(weights: [f64; 3]) -> Adjustment { + let row = |[red, green, blue]: [f64; 3]| ChannelMixerRow { red, green, blue, constant: 0. }; + + // The rows a monochrome mixer ignores keep the node's defaults, so they stamp nothing + Adjustment::ChannelMixer(Box::new(ChannelMixerSettings { + monochrome: true, + monochrome_mix: row(weights), + red: row([100., 0., 0.]), + green: row([0., 100., 0.]), + blue: row([0., 0., 100.]), + })) +} + +#[cfg(test)] +mod tests { + use super::*; + use core_types::ATTR_TRANSFORM; + use core_types::color::Color; + use glam::{DAffine2, DVec2, UVec2}; + use raster_types::{CPU, Image, Raster}; + + /// An image of `pixels` in one row, one pixel per document unit, embedded in a graphic as a wire of images embeds it. + fn image(pixels: &[Color]) -> Item { + let image = Image { + width: pixels.len() as u32, + height: 1, + data: pixels.to_vec(), + }; + let raster = Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(pixels.len() as f64, 1.))); + Item::new_from_element(Graphic::from(raster)) + } + + /// The image a graphic holds alone. + fn lone_image(graphic: &Item) -> &Item> { + let Graphic::RasterCPU(raster) = graphic.element() else { panic!("expected a lone image") }; + raster + } + + /// The graphic's rendered pixels as straight-alpha RGBA8, one pixel per document unit from its origin across a `size` view, or `None` without a GPU. + fn rendered(graphic: &Item, size: UVec2) -> Option> { + use rendering::{Render, RenderParams}; + + let executor = futures::executor::block_on(wgpu_executor::WgpuExecutor::new())?; + let list = core_types::list::List::new_from_item(graphic.clone()); + let draw = &mut |scene: &mut rendering::vello_scene_builder::VelloSceneBuilder| list.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()); + let texture = executor.render_vello(size, DAffine2::IDENTITY, draw).expect("the graphic should render"); + let pixels = executor.read_texture_pixels(&texture).expect("the render should read back"); + Some(pixels.as_chunks::<4>().0.to_vec()) + } + + #[test] + fn into_channels_grays_each_color_keeping_its_alpha_and_makes_the_alpha_opaque() { + use raster_kernels::adjustments::adjust_color; + + // A translucent pixel and a fully transparent one, whose hidden color its channels still gray + let pixels = [Color::from_rgbaf32_unchecked(0.75, 0.1, 0.3, 0.6), Color::from_rgbaf32_unchecked(0.25, 0.5, 1., 0.)]; + let Channels { red, green, blue, alpha } = into_channels((), image(&pixels)); + + // Each output is the image itself, still an image, with adjustments graying each pixel to one channel's gamma-encoded level, or the alpha's + for (channel, output) in [red, green, blue, alpha].into_iter().enumerate() { + assert_eq!(output.attributes().iter_any().count(), 0, "the envelope stays empty"); + let raster = lone_image(&output); + assert_eq!(raster.element().data, pixels, "the pixels are left alone"); + let effects = raster.attribute::(ATTR_EFFECTS).cloned().unwrap_or_default(); + + for pixel in pixels { + let gray = effects.operations().fold(pixel, |color, operation| match operation { + EffectOperation::Adjustment(adjustment) => adjust_color(&adjustment, color), + operation => panic!("{operation:?} isn't an adjustment"), + }); + + // The colors keep the pixel's alpha, and the alpha is opaque + let (level, kept_alpha) = match channel { + 3 => (pixel.a(), 1.), + _ => (pixel.to_gamma_srgb_channels()[channel], pixel.a()), + }; + let [r, g, b, a] = gray.to_gamma_srgb_channels(); + assert!( + [r, g, b].iter().all(|gray| (gray - level).abs() < 1e-5) && (a - kept_alpha).abs() < 1e-6, + "channel {channel} of {pixel:?} grays to {gray:?}" + ); + } + } + } + + #[test] + fn into_channels_color_outputs_keep_the_sources_transparency() { + // Half transparent white, then fully transparent red, then opaque white + let Channels { red, .. } = into_channels((), image(&[Color::WHITE.with_alpha(0.5), Color::from_rgbaf32_unchecked(1., 0., 0., 0.), Color::WHITE])); + + let Some(pixels) = rendered(&red, UVec2::new(3, 1)) else { return }; + assert!(pixels[0][..3] == [255; 3] && pixels[0][3].abs_diff(128) <= 1, "{:?}", pixels[0]); + assert_eq!(pixels[1][3], 0, "the transparent pixel stays transparent"); + assert_eq!(pixels[2], [255; 4]); + } + + #[test] + fn into_channels_adjusts_a_graphic_by_its_envelope_where_its_fill_acts_first() { + use graphic_types::EffectKind::{AlphaToGray, MakeOpaque}; + + let kinds = |effects: Option<&Effects>| effects.map_or(Vec::new(), |effects| effects.effects().map(|effect| effect.kind()).collect::>()); + + // A placement alone leaves the image within to take the effects, so a placement left at its default acts as no placement + let placed = image(&[Color::WHITE]).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::new(3., 0.))); + let Channels { alpha, .. } = into_channels((), placed); + assert_eq!(kinds(lone_image(&alpha).attribute(ATTR_EFFECTS)), [AlphaToGray, MakeOpaque]); + + // The envelope's fill fades the image before the effects appended to the graphic, so they go on the envelope + let faded = image(&[Color::WHITE]).with_attribute(ATTR_OPACITY_FILL, 0.5); + let Channels { alpha, .. } = into_channels((), faded); + assert_eq!(kinds(alpha.attribute(ATTR_EFFECTS)), [AlphaToGray, MakeOpaque]); + assert!(lone_image(&alpha).attribute::(ATTR_EFFECTS).is_none(), "the image within is left alone"); + } + + #[test] + fn into_channels_renders_an_images_alpha_opaque_across_its_rectangle() { + // A half transparent pixel, which shows middle gray, then a fully transparent one, which shows black rather than nothing + let Channels { alpha, .. } = into_channels((), image(&[Color::WHITE.with_alpha(0.5), Color::TRANSPARENT])); + + let Some(pixels) = rendered(&alpha, UVec2::new(3, 1)) else { return }; + assert!(pixels[0][..3].iter().all(|level| level.abs_diff(128) <= 1) && pixels[0][3] == 255, "{:?}", pixels[0]); + assert_eq!(pixels[1], [0, 0, 0, 255]); + assert_eq!(pixels[2][3], 0, "past the image"); + } +} diff --git a/node-graph/nodes/raster/src/lib.rs b/node-graph/nodes/raster/src/lib.rs index 53fe3fa703..5c0757a7e2 100644 --- a/node-graph/nodes/raster/src/lib.rs +++ b/node-graph/nodes/raster/src/lib.rs @@ -1,5 +1,6 @@ pub mod adjustments; pub mod blending_nodes; +pub mod channels; pub use raster_kernels::color_lookup_table; pub mod dehaze; pub mod filter;