From a58a8a9ae837d55a2ec1aa68870e5d56795db907 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Wed, 14 Oct 2026 10:07:04 -0700 Subject: [PATCH 1/2] Move the adjustment and generator kernels into a raster-kernels crate --- Cargo.lock | 22 +- Cargo.toml | 1 + node-graph/libraries/graphic-types/Cargo.toml | 3 + .../libraries/graphic-types/src/adjustment.rs | 296 ++++ .../libraries/graphic-types/src/generator.rs | 113 ++ node-graph/libraries/graphic-types/src/lib.rs | 3 + .../libraries/raster-kernels/Cargo.toml | 28 + .../raster-kernels/src/adjustments.rs | 1432 ++++++++++++++++ .../libraries/raster-kernels/src/blending.rs | 20 + .../raster-kernels}/src/color_lookup_table.rs | 85 +- .../src/color_lookup_table/format_3dl.rs | 0 .../src/color_lookup_table/format_csp.rs | 0 .../src/color_lookup_table/format_cube.rs | 0 .../src/color_lookup_table/format_icc.rs | 0 .../src/color_lookup_table/format_look.rs | 0 .../raster-kernels/src/generators.rs | 239 +++ .../libraries/raster-kernels/src/kernel.rs | 6 + .../libraries/raster-kernels/src/lib.rs | 9 + node-graph/libraries/raster-types/src/lib.rs | 1 + .../raster-types}/src/parallel_rows.rs | 0 node-graph/libraries/resources/src/lib.rs | 18 +- .../libraries/vector-types/src/gradient.rs | 2 +- node-graph/nodes/raster/Cargo.toml | 9 +- node-graph/nodes/raster/src/adjust.rs | 27 +- node-graph/nodes/raster/src/adjustments.rs | 1521 +++-------------- node-graph/nodes/raster/src/blending_nodes.rs | 19 +- node-graph/nodes/raster/src/filter.rs | 2 +- node-graph/nodes/raster/src/lib.rs | 3 +- node-graph/nodes/raster/src/std_nodes.rs | 153 +- 29 files changed, 2526 insertions(+), 1486 deletions(-) create mode 100644 node-graph/libraries/graphic-types/src/adjustment.rs create mode 100644 node-graph/libraries/graphic-types/src/generator.rs create mode 100644 node-graph/libraries/raster-kernels/Cargo.toml create mode 100644 node-graph/libraries/raster-kernels/src/adjustments.rs create mode 100644 node-graph/libraries/raster-kernels/src/blending.rs rename node-graph/{nodes/raster => libraries/raster-kernels}/src/color_lookup_table.rs (86%) rename node-graph/{nodes/raster => libraries/raster-kernels}/src/color_lookup_table/format_3dl.rs (100%) rename node-graph/{nodes/raster => libraries/raster-kernels}/src/color_lookup_table/format_csp.rs (100%) rename node-graph/{nodes/raster => libraries/raster-kernels}/src/color_lookup_table/format_cube.rs (100%) rename node-graph/{nodes/raster => libraries/raster-kernels}/src/color_lookup_table/format_icc.rs (100%) rename node-graph/{nodes/raster => libraries/raster-kernels}/src/color_lookup_table/format_look.rs (100%) create mode 100644 node-graph/libraries/raster-kernels/src/generators.rs create mode 100644 node-graph/libraries/raster-kernels/src/kernel.rs create mode 100644 node-graph/libraries/raster-kernels/src/lib.rs rename node-graph/{nodes/raster => libraries/raster-types}/src/parallel_rows.rs (100%) diff --git a/Cargo.lock b/Cargo.lock index 430e4e93cd9..bdc86698072 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2710,10 +2710,12 @@ dependencies = [ "dyn-any", "glam", "graphene-hash", + "graphene-resource", "node-macro", "raster-types", "serde", "serde_json", + "tsify", "vector-types", "wasm-bindgen", ] @@ -5719,6 +5721,20 @@ dependencies = [ "rustversion", ] +[[package]] +name = "raster-kernels" +version = "0.0.0" +dependencies = [ + "core-types", + "fastnoise-lite", + "glam", + "graphene-resource", + "graphic-types", + "raster-types", + "thiserror 2.0.21", + "vector-types", +] + [[package]] name = "raster-nodes" version = "0.0.0" @@ -5727,18 +5743,16 @@ dependencies = [ "color", "core-types", "dyn-any", - "fastnoise-lite", "futures", "glam", "graphene-core", "graphene-hash", "graphene-resource", + "graphic-types", "image", "ndarray", "node-macro", - "num_enum", - "rand", - "rand_chacha", + "raster-kernels", "raster-types", "serde", "thiserror 2.0.21", diff --git a/Cargo.toml b/Cargo.toml index 5709d28134c..407261a5f45 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -95,6 +95,7 @@ core-types = { path = "node-graph/libraries/core-types" } raster-types = { path = "node-graph/libraries/raster-types" } vector-types = { path = "node-graph/libraries/vector-types" } graphic-types = { path = "node-graph/libraries/graphic-types" } +raster-kernels = { path = "node-graph/libraries/raster-kernels" } brush-types = { path = "node-graph/libraries/brush-types" } rendering = { path = "node-graph/libraries/rendering" } brush-nodes = { path = "node-graph/nodes/brush" } diff --git a/node-graph/libraries/graphic-types/Cargo.toml b/node-graph/libraries/graphic-types/Cargo.toml index 2b9274be11d..a0af59d7487 100644 --- a/node-graph/libraries/graphic-types/Cargo.toml +++ b/node-graph/libraries/graphic-types/Cargo.toml @@ -21,6 +21,7 @@ wasm = [ "core-types/wasm", "vector-types/wasm", "raster-types/wasm", + "tsify", "wasm-bindgen", ] @@ -28,6 +29,7 @@ wasm = [ # Local dependencies core-types = { workspace = true } graphene-hash = { workspace = true } +graphene-resource = { workspace = true } brush-types = { workspace = true } raster-types = { workspace = true, features = ["wgpu"] } vector-types = { workspace = true } @@ -40,4 +42,5 @@ serde_json = { workspace = true } # Optional workspace dependencies serde = { workspace = true, optional = true } +tsify = { workspace = true, optional = true } wasm-bindgen = { workspace = true, optional = true } diff --git a/node-graph/libraries/graphic-types/src/adjustment.rs b/node-graph/libraries/graphic-types/src/adjustment.rs new file mode 100644 index 00000000000..ab2cccc7fde --- /dev/null +++ b/node-graph/libraries/graphic-types/src/adjustment.rs @@ -0,0 +1,296 @@ +//! Color adjustments as plain data, each holding its node's settings in the node's own units, carried out by the kernels of the `raster-kernels` crate. + +use core_types::Color; +use core_types::blending::BlendMode; +use core_types::graphene_hash::CacheHash; +use core_types::list::Item; +use core_types::transfer_curve::TransferCurve; +use dyn_any::DynAny; +use graphene_resource::Resource; +use vector_types::Gradient; + +/// A color adjustment applied to each color on its own, with no regard for its neighbors. +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub enum Adjustment { + Desaturate { + method: DesaturateMethod, + }, + GammaCorrection { + gamma: f64, + inverse: bool, + }, + MakeOpaque, + BrightnessContrast { + /// Percent. + brightness: f64, + /// Percent. + contrast: f64, + use_classic: bool, + /// On a scale of 0 to 255. + classic_pivot: f64, + }, + Levels(Box), + Curves(Box), + BlackAndWhite(BlackAndWhiteSettings), + HueSaturation(Box), + Invert, + Threshold { + /// Percent. + min_luminance: f64, + /// Percent. + max_luminance: f64, + }, + GradientMap { + /// The gradient, with its whole-ramp settings as its attributes. + gradient: Item, + reverse: bool, + }, + Vibrance { + /// Percent. + vibrance: f64, + /// Percent. + saturation: f64, + }, + ChannelMixer(Box), + SelectiveColor(Box), + Posterize { + levels: i64, + }, + Exposure { + exposure: f64, + offset: f64, + gamma_correction: f64, + }, + ColorBalance(ColorBalanceSettings), + PhotoFilter { + color: Color, + /// Percent. + density: f64, + preserve_luminosity: bool, + }, + ColorLookup { + /// The file the lookup table is read from. + lut_file: Resource, + }, + ColorOverlay { + color: Color, + blend_mode: BlendMode, + /// Percent. + opacity: f64, + }, +} + +impl std::fmt::Display for Adjustment { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::Desaturate { .. } => "Desaturate", + Self::GammaCorrection { .. } => "Gamma Correction", + Self::MakeOpaque => "Make Opaque", + Self::BrightnessContrast { .. } => "Brightness/Contrast", + Self::Levels(_) => "Levels", + Self::Curves(_) => "Curves", + Self::BlackAndWhite(_) => "Black & White", + Self::HueSaturation(_) => "Hue/Saturation", + Self::Invert => "Invert", + Self::Threshold { .. } => "Threshold", + Self::GradientMap { .. } => "Gradient Map", + Self::Vibrance { .. } => "Vibrance", + Self::ChannelMixer(_) => "Channel Mixer", + Self::SelectiveColor(_) => "Selective Color", + Self::Posterize { .. } => "Posterize", + Self::Exposure { .. } => "Exposure", + Self::ColorBalance(_) => "Color Balance", + Self::PhotoFilter { .. } => "Photo Filter", + Self::ColorLookup { .. } => "Color Lookup", + Self::ColorOverlay { .. } => "Color Overlay", + }) + } +} + +/// Conversion from a color to grayscale. +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)] +#[widget(Dropdown)] +pub enum DesaturateMethod { + /// Light level of the color, the Y (luminance) of Rec. 709, which weights the linear-light RGB channels by `0.2126, 0.7152, 0.0722`. + /// + /// Accessibility contrast ratios and SVG luminance masks use this. + #[default] + #[label("Luminance (Rec. 709)")] + #[cfg_attr(feature = "serde", serde(alias = "SRGB"))] + LuminanceRec709, + /// Light level approximation for the color, the Y′ (luma) of Rec. 709, which weights the gamma-encoded RGB channels by `0.2126, 0.7152, 0.0722`. + /// + /// CSS filter functions such as `grayscale()` use this. + #[label("Luma (Rec. 709)")] + LumaRec709, + /// Light level approximation for the color, the Y′ (luma) of Rec. 601, which weights the gamma-encoded RGB channels by `0.299, 0.587, 0.114`. + /// + /// The Luminosity family of blend modes uses this, rounded to `0.3, 0.59, 0.11`. + #[label("Luma (Rec. 601)")] + LumaRec601, + /// Perceptually uniform scale from black to white, the L (lightness) of OkLab. + #[label("Lightness (OkLab)")] + #[cfg_attr(feature = "serde", serde(alias = "Perceptual"))] + LightnessOkLab, + /// Mean of the three linear-light RGB channels. + #[menu_separator] + #[cfg_attr(feature = "serde", serde(alias = "AverageChannels"))] + ChannelsAverage, + /// Smallest of the three linear-light RGB channels. + #[cfg_attr(feature = "serde", serde(alias = "MinimumChannels"))] + ChannelsMinimum, + /// Largest of the three linear-light RGB channels, the V (value) of HSV. + #[cfg_attr(feature = "serde", serde(alias = "MaximumChannels"))] + ChannelsMaximum, + /// Midpoint of the largest and smallest gamma-encoded RGB channels, the L (lightness) of HSL. + /// + /// The classic "Desaturate" command of many image editors uses this. + #[label("Lightness (HSL)")] + LightnessHsl, +} + +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)] +#[widget(Radio)] +pub enum RelativeAbsolute { + #[default] + Relative, + Absolute, +} + +/// One channel's Levels record: percentage input and output points and the midtones gamma. +#[derive(Clone, Copy, Debug, PartialEq, CacheHash)] +pub struct LevelsRecord { + pub shadows: f64, + pub midtones: f64, + pub highlights: f64, + pub output_minimums: f64, + pub output_maximums: f64, +} + +/// The composite record that the three color channels pass through after their own, and the alpha record that stands apart. +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub struct LevelsSettings { + pub composite: LevelsRecord, + pub red: LevelsRecord, + pub green: LevelsRecord, + pub blue: LevelsRecord, + pub alpha: LevelsRecord, +} + +/// The composite curve that the three color channels pass through after their own, and the alpha curve that stands apart. +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub struct CurvesSettings { + pub composite: TransferCurve, + pub red: TransferCurve, + pub green: TransferCurve, + pub blue: TransferCurve, + pub alpha: TransferCurve, +} + +/// The percentage each hue contributes to the gray, and the color tinting it when `use_tint` is set. +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub struct BlackAndWhiteSettings { + pub use_tint: bool, + pub tint: Color, + pub reds: f64, + pub yellows: f64, + pub greens: f64, + pub cyans: f64, + pub blues: f64, + pub magentas: f64, +} + +/// One set of Hue/Saturation sliders: a hue in degrees and saturation and lightness percentages. +#[derive(Clone, Copy, Debug, PartialEq, CacheHash)] +pub struct HueSaturationSliders { + pub hue: f64, + pub saturation: f64, + pub lightness: f64, +} + +/// The sliders for one range of hues, which apply fully from the range start to its end, fading out at the falloff ends. Edges are in degrees. +#[derive(Clone, Copy, Debug, PartialEq, CacheHash)] +pub struct HueRangeSettings { + pub sliders: HueSaturationSliders, + pub falloff_start: f64, + pub range_start: f64, + pub range_end: f64, + pub falloff_end: f64, +} + +/// The master sliders shift every color, each hue range adds its own, and colorizing replaces them all with an absolute hue and saturation. +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub struct HueSaturationSettings { + pub master: HueSaturationSliders, + pub colorize: bool, + pub colorize_sliders: HueSaturationSliders, + pub reds: HueRangeSettings, + pub yellows: HueRangeSettings, + pub greens: HueRangeSettings, + pub cyans: HueRangeSettings, + pub blues: HueRangeSettings, + pub magentas: HueRangeSettings, +} + +/// The percentages of each source channel, plus a constant, that sum to one output channel. +#[derive(Clone, Copy, Debug, PartialEq, CacheHash)] +pub struct ChannelMixerRow { + pub red: f64, + pub green: f64, + pub blue: f64, + pub constant: f64, +} + +/// A row for each output channel, or for the single gray channel when monochrome. +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub struct ChannelMixerSettings { + pub monochrome: bool, + pub monochrome_mix: ChannelMixerRow, + pub red: ChannelMixerRow, + pub green: ChannelMixerRow, + pub blue: ChannelMixerRow, +} + +/// Percentage offsets to the cyan, magenta, yellow, and black inks of one group of colors. +#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)] +pub struct SelectiveColorInks { + pub cyan: f64, + pub magenta: f64, + pub yellow: f64, + pub black: f64, +} + +/// The ink offsets of each group of colors, and whether they are relative to the inks already present. +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub struct SelectiveColorSettings { + pub mode: RelativeAbsolute, + pub reds: SelectiveColorInks, + pub yellows: SelectiveColorInks, + pub greens: SelectiveColorInks, + pub cyans: SelectiveColorInks, + pub blues: SelectiveColorInks, + pub magentas: SelectiveColorInks, + pub whites: SelectiveColorInks, + pub neutrals: SelectiveColorInks, + pub blacks: SelectiveColorInks, +} + +/// Percentage shifts along the three opponent color axes for one tonal range. +#[derive(Clone, Copy, Debug, PartialEq, CacheHash)] +pub struct ColorBalanceShifts { + pub cyan_red: f64, + pub magenta_green: f64, + pub yellow_blue: f64, +} + +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub struct ColorBalanceSettings { + pub shadows: ColorBalanceShifts, + pub midtones: ColorBalanceShifts, + pub highlights: ColorBalanceShifts, + pub preserve_luminosity: bool, +} diff --git a/node-graph/libraries/graphic-types/src/generator.rs b/node-graph/libraries/graphic-types/src/generator.rs new file mode 100644 index 00000000000..87581787469 --- /dev/null +++ b/node-graph/libraries/graphic-types/src/generator.rs @@ -0,0 +1,113 @@ +//! Procedural patterns described by their settings, rendered at whatever resolution is needed of whatever part is seen by the kernels of the `raster-kernels` crate. + +use core_types::graphene_hash::CacheHash; +use dyn_any::DynAny; + +/// Style of noise pattern. +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)] +#[widget(Dropdown)] +pub enum NoiseType { + #[default] + Perlin, + #[label("OpenSimplex2")] + OpenSimplex2, + #[label("OpenSimplex2S")] + OpenSimplex2S, + Cellular, + ValueCubic, + Value, + WhiteNoise, +} + +/// Style of layered levels of the noise pattern. +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)] +pub enum FractalType { + #[default] + None, + #[label("Fractional Brownian Motion")] + FBm, + Ridged, + PingPong, + #[label("Progressive (Domain Warp Only)")] + DomainWarpProgressive, + #[label("Independent (Domain Warp Only)")] + DomainWarpIndependent, +} + +/// Distance function used by the cellular noise. +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)] +pub enum CellularDistanceFunction { + #[default] + Euclidean, + #[label("Euclidean Squared (Faster)")] + EuclideanSq, + Manhattan, + Hybrid, +} + +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)] +pub enum CellularReturnType { + CellValue, + #[default] + #[label("Nearest (F1)")] + Nearest, + #[label("Next Nearest (F2)")] + NextNearest, + #[label("Average (F1 / 2 + F2 / 2)")] + Average, + #[label("Difference (F2 - F1)")] + Difference, + #[label("Product (F2 * F1 / 2)")] + Product, + #[label("Division (F1 / F2)")] + Division, +} + +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)] +#[widget(Dropdown)] +pub enum DomainWarpType { + #[default] + None, + #[label("OpenSimplex2")] + OpenSimplex2, + #[label("OpenSimplex2 Reduced")] + OpenSimplex2Reduced, + BasicGrid, +} + +/// The settings of a noise pattern, with lengths measured in the document units of the space it's sampled in. +#[derive(Debug, Clone, PartialEq, CacheHash)] +pub struct NoiseSettings { + pub seed: i64, + pub scale: f64, + pub noise_type: NoiseType, + pub domain_warp_type: DomainWarpType, + pub domain_warp_amplitude: f64, + pub fractal_type: FractalType, + pub fractal_octaves: i64, + pub fractal_lacunarity: f64, + pub fractal_gain: f64, + pub fractal_weighted_strength: f64, + pub fractal_ping_pong_strength: f64, + pub cellular_distance_function: CellularDistanceFunction, + pub cellular_return_type: CellularReturnType, + pub cellular_jitter: f64, +} + +/// A procedural pattern, a function of position in its own space that renders across any area at any resolution. +#[derive(Debug, Clone, PartialEq, CacheHash)] +pub enum GeneratorPattern { + Noise(NoiseSettings), + /// The Mandelbrot set, with the unit square spanning -2 to 1 along the real axis and -1.5 to 1.5 along the imaginary axis. + Mandelbrot, +} diff --git a/node-graph/libraries/graphic-types/src/lib.rs b/node-graph/libraries/graphic-types/src/lib.rs index 82a375bdbdb..78534f8f430 100644 --- a/node-graph/libraries/graphic-types/src/lib.rs +++ b/node-graph/libraries/graphic-types/src/lib.rs @@ -1,5 +1,7 @@ +pub mod adjustment; pub mod appearance; pub mod artboard; +pub mod generator; pub mod graphic; // Re-export all transitive dependencies so downstream crates only need to depend on graphic-types @@ -8,6 +10,7 @@ pub use raster_types; pub use vector_types; // Re-export commonly used types at the crate root +pub use adjustment::Adjustment; pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage}; pub use artboard::Artboard; pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector}; diff --git a/node-graph/libraries/raster-kernels/Cargo.toml b/node-graph/libraries/raster-kernels/Cargo.toml new file mode 100644 index 00000000000..e2d07fb2664 --- /dev/null +++ b/node-graph/libraries/raster-kernels/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "raster-kernels" +description = "The kernels carrying out Graphene's raster operations, such as each color adjustment" +version.workspace = true +license.workspace = true +authors.workspace = true +edition.workspace = true +repository.workspace = true +readme.workspace = true +homepage.workspace = true +rust-version.workspace = true +publish.workspace = true + +[lints] +workspace = true + +[dependencies] +# Local dependencies +core-types = { workspace = true } +graphene-resource = { workspace = true } +graphic-types = { workspace = true } +raster-types = { workspace = true } +vector-types = { workspace = true } + +# Workspace dependencies +fastnoise-lite = { workspace = true } +glam = { workspace = true } +thiserror = { workspace = true } diff --git a/node-graph/libraries/raster-kernels/src/adjustments.rs b/node-graph/libraries/raster-kernels/src/adjustments.rs new file mode 100644 index 00000000000..efb035cf114 --- /dev/null +++ b/node-graph/libraries/raster-kernels/src/adjustments.rs @@ -0,0 +1,1432 @@ +//! The kernels carrying out each [`Adjustment`], with its settings turned into what its kernel reads by [`visit_kernel`]. + +use crate::MapColor; +use crate::blending::ColorOverlay; +use crate::color_lookup_table::{Lut, parse_cached}; +use core_types::Color; +use core_types::color::{linear_to_srgb, set_luminosity, srgb_to_linear}; +use core_types::transfer_curve::TransferCurveEvaluator; +use glam::Vec3; +use graphic_types::adjustment::{self as settings, Adjustment, DesaturateMethod, RelativeAbsolute}; +use raster_types::parallel_rows::fill_rows; +use std::sync::Arc; +use vector_types::GradientSettings; +use vector_types::gradient::GradientEvaluator; + +/// How many colors each thread band handles at a time when a long slice is split across threads. +const COLORS_PER_ROW: usize = 4096; + +/// Adjusts each color in place, on threads for long slices on native platforms. O(n). +pub fn adjust_colors(adjustment: &Adjustment, colors: &mut [Color]) { + struct AdjustColors<'a>(&'a mut [Color]); + + impl AdjustmentVisitor for AdjustColors<'_> { + type Output = (); + + fn visit(self, kernel: K) { + fill_rows(self.0, COLORS_PER_ROW, |_, row| row.iter_mut().for_each(|color| *color = kernel.map_cpu(*color))); + } + + fn unchanged(self) {} + } + + visit_kernel(adjustment, AdjustColors(colors)); +} + +/// The color with `adjustment` carried out on it. To adjust many colors one at a time, prepare a [`PreparedAdjustment`] once instead. +pub fn adjust_color(adjustment: &Adjustment, color: Color) -> Color { + struct AdjustColor(Color); + + impl AdjustmentVisitor for AdjustColor { + type Output = Color; + + fn visit(self, kernel: K) -> Color { + kernel.map_cpu(self.0) + } + + fn unchanged(self) -> Color { + self.0 + } + } + + visit_kernel(adjustment, AdjustColor(color)) +} + +/// An adjustment with its kernel prepared from its settings, which carries it out on any number of colors without preparing it again. +pub struct PreparedAdjustment(Option>); + +impl PreparedAdjustment { + pub fn new(adjustment: &Adjustment) -> Self { + struct Prepare; + + impl AdjustmentVisitor for Prepare { + type Output = Option>; + + fn visit(self, kernel: K) -> Self::Output { + Some(Box::new(kernel)) + } + + fn unchanged(self) -> Self::Output { + None + } + } + + Self(visit_kernel(adjustment, Prepare)) + } + + /// The color with the adjustment carried out on it. + pub fn adjust(&self, color: Color) -> Color { + self.0.as_ref().map_or(color, |kernel| kernel.map_cpu(color)) + } +} + +/// Receives the kernel carrying out an [`Adjustment`], which has its own type for each adjustment. +pub trait AdjustmentVisitor { + type Output; + fn visit(self, kernel: K) -> Self::Output; + /// Stands in for the kernel of an adjustment that leaves every color as it is, such as a lookup table with a file that can't be read. + fn unchanged(self) -> Self::Output; +} + +/// Hands `visitor` the kernel carrying out `adjustment`, with what the kernel reads worked out once from the adjustment's settings. +/// Settings past their nodes' bounds that would divide by zero are clamped to those bounds, so a description from anywhere stays finite. +pub fn visit_kernel(adjustment: &Adjustment, visitor: V) -> V::Output { + match adjustment { + Adjustment::Desaturate { method } => visitor.visit(Desaturate { method: *method }), + Adjustment::GammaCorrection { gamma, inverse } => { + let gamma = gamma.max(0.0001); + let exponent = if *inverse { 1. / gamma } else { gamma }; + visitor.visit(GammaCorrection { exponent: exponent as f32 }) + } + Adjustment::MakeOpaque => visitor.visit(MakeOpaque), + Adjustment::BrightnessContrast { + brightness, + contrast, + use_classic, + classic_pivot, + } => { + let classic_pivot = (classic_pivot / 255.) as f32; + + // Each algorithm has its own slider range, matched here and in the Inspector + let (brightness_extent, contrast_minimum) = if *use_classic { (100., -100.) } else { (150., -50.) }; + let brightness = (*brightness as f32).clamp(-brightness_extent, brightness_extent); + let contrast = (*contrast as f32).clamp(contrast_minimum, 100.) / 100.; + + // Beyond a magnitude of 100, the curve for 100 is applied first and the curve for the remainder after it + let magnitude = brightness.abs(); + let first_curve = BrightnessCurve::new(magnitude.min(100.)); + let second_curve = BrightnessCurve::new((magnitude - 100.).max(0.)); + + visitor.visit(BrightnessContrast { + use_classic: *use_classic, + brightness, + contrast, + classic_pivot, + first_curve, + second_curve, + }) + } + Adjustment::Levels(levels) => { + let record = |record: &settings::LevelsRecord| { + LevelsRecord::new( + record.shadows as f32, + record.midtones as f32, + record.highlights as f32, + record.output_minimums as f32, + record.output_maximums as f32, + ) + }; + let composite = record(&levels.composite); + + // Alpha stands apart from the composite record that the three color channels pass through + let alpha = record(&levels.alpha); + + visitor.visit(Levels { + red: LevelsChain::new(record(&levels.red), composite), + green: LevelsChain::new(record(&levels.green), composite), + blue: LevelsChain::new(record(&levels.blue), composite), + alpha: alpha.stage(alpha.midtones), + }) + } + Adjustment::Curves(curves) => visitor.visit(Curves { + composite: curves.composite.evaluator(), + red: curves.red.evaluator(), + green: curves.green.evaluator(), + blue: curves.blue.evaluator(), + alpha: curves.alpha.evaluator(), + }), + Adjustment::BlackAndWhite(black_and_white) => visitor.visit(BlackAndWhite { + use_tint: black_and_white.use_tint, + tint: black_and_white.tint, + reds: (black_and_white.reds / 100.) as f32, + yellows: (black_and_white.yellows / 100.) as f32, + greens: (black_and_white.greens / 100.) as f32, + cyans: (black_and_white.cyans / 100.) as f32, + blues: (black_and_white.blues / 100.) as f32, + magentas: (black_and_white.magentas / 100.) as f32, + }), + Adjustment::HueSaturation(hue_saturation) => { + let sliders = |sliders: &settings::HueSaturationSliders| PreparedHueSaturationSliders::new(sliders.hue as f32, sliders.saturation as f32, sliders.lightness as f32); + let range = |range: &settings::HueRangeSettings| { + HueSaturationRangeSettings::new( + range.falloff_start as f32, + range.range_start as f32, + range.range_end as f32, + range.falloff_end as f32, + sliders(&range.sliders), + ) + }; + + visitor.visit(HueSaturation { + master: sliders(&hue_saturation.master), + colorize: hue_saturation.colorize, + colorize_settings: sliders(&hue_saturation.colorize_sliders), + reds: range(&hue_saturation.reds), + yellows: range(&hue_saturation.yellows), + greens: range(&hue_saturation.greens), + cyans: range(&hue_saturation.cyans), + blues: range(&hue_saturation.blues), + magentas: range(&hue_saturation.magentas), + }) + } + Adjustment::Invert => visitor.visit(Invert), + Adjustment::Threshold { min_luminance, max_luminance } => visitor.visit(Threshold { + min_luminance: (min_luminance / 100.) as f32, + max_luminance: (max_luminance / 100.) as f32, + }), + Adjustment::GradientMap { gradient, reverse } => visitor.visit(GradientMap { + evaluator: gradient.element().evaluator(GradientSettings::from_item_attributes(gradient)), + reverse: *reverse, + }), + Adjustment::Vibrance { vibrance, saturation } => visitor.visit(Vibrance { + vibrance: (vibrance / 100.) as f32, + saturation_scale: (1. + saturation / 100.) as f32, + }), + Adjustment::ChannelMixer(channel_mixer) => { + // Weights and constants are 10-bit fixed point truncated toward zero, which PSD interop depends on + let weight = |percent: f64| (percent as f32 * 1024. / 100.).trunc() / 1024.; + let settings::ChannelMixerSettings { + monochrome, + monochrome_mix, + red, + green, + blue, + } = &**channel_mixer; + + visitor.visit(ChannelMixer { + monochrome: *monochrome, + monochrome_r: weight(monochrome_mix.red), + monochrome_g: weight(monochrome_mix.green), + monochrome_b: weight(monochrome_mix.blue), + monochrome_c: weight(monochrome_mix.constant), + red_r: weight(red.red), + red_g: weight(red.green), + red_b: weight(red.blue), + red_c: weight(red.constant), + green_r: weight(green.red), + green_g: weight(green.green), + green_b: weight(green.blue), + green_c: weight(green.constant), + blue_r: weight(blue.red), + blue_g: weight(blue.green), + blue_b: weight(blue.blue), + blue_c: weight(blue.constant), + }) + } + Adjustment::SelectiveColor(selective_color) => { + let mode = selective_color.mode; + + // For PSD interop, the combined percent (c + k + c k / 100) rounds half up to an integer + let ink = |color: f32, k: f32| { + let percent = ((2. * (100. * (color + k) + color * k) + 100.) / 200.).floor(); + match mode { + // The multiplier is stored as one byte, 255 / b above 1 and b / 255 below, so 99% and 100% both act as 127/128 + RelativeAbsolute::Relative => { + let multiplier = 1. + percent / 100.; + if multiplier >= 1. { + 255. / (255. / multiplier).round() - 1. + } else { + (255. * multiplier).round() / 255. - 1. + } + } + RelativeAbsolute::Absolute => percent / 100., + } + }; + + let groups = [ + (SelectiveColorGroup::Reds, &selective_color.reds), + (SelectiveColorGroup::Yellows, &selective_color.yellows), + (SelectiveColorGroup::Greens, &selective_color.greens), + (SelectiveColorGroup::Cyans, &selective_color.cyans), + (SelectiveColorGroup::Blues, &selective_color.blues), + (SelectiveColorGroup::Magentas, &selective_color.magentas), + (SelectiveColorGroup::Whites, &selective_color.whites), + (SelectiveColorGroup::Neutrals, &selective_color.neutrals), + (SelectiveColorGroup::Blacks, &selective_color.blacks), + ] + .map(|(group, inks)| { + let [c, m, y, k] = [inks.cyan, inks.magenta, inks.yellow, inks.black].map(|percent| percent as f32); + SelectiveColorGroupInks { + group, + cmyk: [c, m, y, k], + inks: [ink(c, k), ink(m, k), ink(y, k)], + } + }); + + visitor.visit(SelectiveColor { mode, groups }) + } + Adjustment::Posterize { levels } => visitor.visit(Posterize { levels: (*levels).max(2) as f32 }), + Adjustment::Exposure { exposure, offset, gamma_correction } => visitor.visit(Exposure { + exposure: *exposure as f32, + offset: *offset as f32, + gamma_correction: gamma_correction.max(0.0001) as f32, + }), + Adjustment::ColorBalance(color_balance) => { + let preserve_luminosity = color_balance.preserve_luminosity; + + // The derivation below is integer arithmetic, so the sliders round to whole percentages first + let shifts = |shifts: &settings::ColorBalanceShifts| [shifts.cyan_red, shifts.magenta_green, shifts.yellow_blue].map(|value| (value as f32).round() as i32); + let [s_r, s_g, s_b] = shifts(&color_balance.shadows); + let [m_r, m_g, m_b] = shifts(&color_balance.midtones); + let [h_r, h_g, h_b] = shifts(&color_balance.highlights); + + let s_max = s_r.max(s_g).max(s_b); + let m_max = m_r.max(m_g).max(m_b); + let m_min = m_r.min(m_g).min(m_b); + let h_min = h_r.min(h_g).min(h_b); + let red = color_balance_curve(s_r, m_r, h_r, s_max, m_max, m_min, h_min, preserve_luminosity); + let green = color_balance_curve(s_g, m_g, h_g, s_max, m_max, m_min, h_min, preserve_luminosity); + let blue = color_balance_curve(s_b, m_b, h_b, s_max, m_max, m_min, h_min, preserve_luminosity); + + visitor.visit(ColorBalance { red, green, blue }) + } + Adjustment::PhotoFilter { color, density, preserve_luminosity } => { + let density = (density / 100.) as f32; + + // The image is multiplied in XYZ by the filter color normalized to the white point, with density easing that multiplier toward 1 + let filter_xyz = multiply_matrix(&SRGB_TO_XYZ_D50, [color.r(), color.g(), color.b()]); + let factor = [ + 1. + density * (filter_xyz[0] / WHITE_XYZ_D50[0] - 1.), + 1. + density * (filter_xyz[1] / WHITE_XYZ_D50[1] - 1.), + 1. + density * (filter_xyz[2] / WHITE_XYZ_D50[2] - 1.), + ]; + + visitor.visit(PhotoFilter { + factor, + preserve_luminosity: *preserve_luminosity, + }) + } + Adjustment::ColorLookup { lut_file } => match parse_cached(lut_file) { + Ok(lut) => visitor.visit(ColorLookup { lut }), + Err(_) => visitor.unchanged(), + }, + Adjustment::ColorOverlay { color, blend_mode, opacity } => visitor.visit(ColorOverlay { + color: *color, + blend_mode: *blend_mode, + opacity: (opacity / 100.) as f32, + }), + } +} + +struct Desaturate { + method: DesaturateMethod, +} + +impl MapColor for Desaturate { + fn map_cpu(&self, color: Color) -> Color { + // Gamma-encoded formulas are decoded as if they were a gray + let gamma = || color.to_gamma_srgb_channels(); + let luminance = match self.method { + DesaturateMethod::LuminanceRec709 => color.luminance_rec_709(), + DesaturateMethod::LumaRec709 => { + let [r, g, b, _] = gamma(); + srgb_to_linear(0.2126 * r + 0.7152 * g + 0.0722 * b) + } + DesaturateMethod::LumaRec601 => { + let [r, g, b, _] = gamma(); + srgb_to_linear(0.299 * r + 0.587 * g + 0.114 * b) + } + DesaturateMethod::LightnessOkLab => { + // A gray's OkLab lightness is the cube root of its linear value, so cubing gives the gray of equal lightness + let lightness = color.lightness_oklab(); + lightness * lightness * lightness + } + DesaturateMethod::ChannelsAverage => color.average_rgb_channels(), + DesaturateMethod::ChannelsMinimum => color.minimum_rgb_channels(), + DesaturateMethod::ChannelsMaximum => color.maximum_rgb_channels(), + DesaturateMethod::LightnessHsl => { + // The transfer curve is monotonic, so the extremes are found first and only they are encoded + let max = linear_to_srgb(color.maximum_rgb_channels()); + let min = linear_to_srgb(color.minimum_rgb_channels()); + srgb_to_linear((max + min) / 2.) + } + }; + color.map_rgb(|_| luminance) + } +} + +struct GammaCorrection { + exponent: f32, +} + +impl MapColor for GammaCorrection { + fn map_cpu(&self, color: Color) -> Color { + color.apply_gamma_exponent(self.exponent) + } +} + +struct MakeOpaque; + +impl MapColor for MakeOpaque { + fn map_cpu(&self, color: Color) -> Color { + color.with_alpha(1.) + } +} + +/// Remaps a gamma-space channel through the stages of a Levels adjustment: the input range, the midtones gamma, and the output range. +fn apply_levels(value: f32, input_shadows: f32, input_highlights: f32, inverse_gamma: f32, output_minimum: f32, output_maximum: f32) -> f32 { + let highlights_minus_shadows = (input_highlights - input_shadows).clamp(f32::EPSILON, 1.); + let value = ((value - input_shadows).max(0.) / highlights_minus_shadows).min(1.); + let value = value.powf(inverse_gamma); + + value * (output_maximum - output_minimum) + output_minimum +} + +/// The classic Brightness/Contrast algorithm: a Levels remap around the pivot, adding the brightness before a positive +/// contrast stretch and after a negative contrast squeeze. +fn brightness_contrast_classic(value: f32, brightness: f32, contrast: f32, pivot: f32) -> f32 { + // Full contrast is a hard step, sending values at the pivot or above to white (with half a 16-bit step of slack for float ties) + if contrast >= 1. { + return if value + brightness >= pivot - 1. / 65536. { 1. } else { 0. }; + } + + let result = if contrast > 0. { + let input_shadows = pivot * contrast - brightness; + apply_levels(value, input_shadows, input_shadows + 1. - contrast, 1., 0., 1.) + } else { + let output_minimum = brightness - pivot * contrast; + apply_levels(value, 0., 1., 1., output_minimum, output_minimum + 1. + contrast) + }; + + result.clamp(0., 1.) +} + +/// One brightness curve of the current algorithm, for a magnitude in 0..100: a line of slope 2^(b/110) up to an output of 0.5, +/// continued by a cubic Hermite segment that eases into (1, 1). +#[derive(Clone, Copy)] +struct BrightnessCurve { + slope: f32, + knee: f32, + end_slope: f32, +} + +impl BrightnessCurve { + fn new(brightness: f32) -> Self { + let slope = 2_f32.powf(brightness / 110.); + let knee = 0.5 / slope; + let end_slope = (1. / (1. + 12. * (slope - 1.))).max(0.1); + + Self { slope, knee, end_slope } + } + + /// Evaluates the Hermite segment at its parameter t in 0..1, returning the value and its derivative with respect to x. + fn hermite(&self, t: f32) -> (f32, f32) { + let length = 1. - self.knee; + let start_tangent = length * self.slope; + let end_tangent = length * self.end_slope; + let t2 = t * t; + let t3 = t2 * t; + + let value = (2. * t3 - 3. * t2 + 1.) * 0.5 + (t3 - 2. * t2 + t) * start_tangent + (-2. * t3 + 3. * t2) + (t3 - t2) * end_tangent; + let derivative = ((6. * t2 - 6. * t) * 0.5 + (3. * t2 - 4. * t + 1.) * start_tangent + (-6. * t2 + 6. * t) + (3. * t2 - 2. * t) * end_tangent) / length; + + (value, derivative) + } + + fn forward(&self, x: f32) -> f32 { + if x < self.knee { + return self.slope * x; + } + + let t = ((x - self.knee) / (1. - self.knee)).min(1.); + self.hermite(t).0.min(1.) + } + + /// Inverts the curve, solving the monotone Hermite segment with a bracketed Newton iteration. + fn inverse(&self, y: f32) -> f32 { + if y <= 0.5 { + return y / self.slope; + } + + let mut low = 0.; + let mut high = 1.; + let mut t = (y - 0.5) * 2.; + for _ in 0..8 { + let (value, derivative) = self.hermite(t); + let error = value - y; + if error > 0. { + high = t; + } else { + low = t; + } + + let step = t - error / (derivative * (1. - self.knee)); + t = if step >= low && step <= high { step } else { (low + high) * 0.5 }; + } + + self.knee + t * (1. - self.knee) + } +} + +struct BrightnessContrast { + use_classic: bool, + brightness: f32, + contrast: f32, + classic_pivot: f32, + first_curve: BrightnessCurve, + second_curve: BrightnessCurve, +} + +impl MapColor for BrightnessContrast { + fn map_cpu(&self, color: Color) -> Color { + color.map_gamma_rgb(|c| { + if self.use_classic { + return brightness_contrast_classic(c, self.brightness / 255., self.contrast, self.classic_pivot); + } + + // Negative brightness runs the same curves in reverse + let brightened = if self.brightness >= 0. { + self.second_curve.forward(self.first_curve.forward(c)) + } else { + self.first_curve.inverse(self.second_curve.inverse(c)) + }; + + // Contrast pushes away from (or pulls toward) the midpoint, most strongly at the quarter tones + let contrasted = brightened + 0.76 * self.contrast * (2. * brightened - 1.) * brightened.min(1. - brightened); + contrasted.clamp(0., 1.) + }) + } +} + +/// One Levels record in the node's units: percentage input and output points and the gamma value. +#[derive(Clone, Copy)] +struct LevelsRecord { + shadows: f32, + midtones: f32, + highlights: f32, + output_minimums: f32, + output_maximums: f32, +} + +/// A record's input curve followed by its output range. +#[derive(Clone, Copy)] +struct LevelsStage { + curve: LevelsCurve, + output_minimum: f32, + output_maximum: f32, +} + +impl LevelsRecord { + fn new(shadows: f32, midtones: f32, highlights: f32, output_minimums: f32, output_maximums: f32) -> Self { + Self { + shadows, + midtones, + highlights, + output_minimums, + output_maximums, + } + } + + fn stage(&self, gamma: f32) -> LevelsStage { + LevelsStage { + curve: LevelsCurve::from_points(self.shadows * 2.55, self.highlights * 2.55, gamma), + output_minimum: self.output_minimums / 100., + output_maximum: self.output_maximums / 100., + } + } +} + +impl LevelsStage { + fn apply(&self, value: f32) -> f32 { + self.curve.apply(value) * (self.output_maximum - self.output_minimum) + self.output_minimum + } +} + +/// A channel's record followed by the composite record. +#[derive(Clone, Copy)] +struct LevelsChain { + first: LevelsStage, + second: LevelsStage, + two_stages: bool, +} + +impl LevelsChain { + fn new(channel: LevelsRecord, composite: LevelsRecord) -> Self { + // For PSD interop, two power functions with nothing between them (the composite's input points and the + // channel's output range at their defaults) merge into one curve with the product of the gammas, toe included + let nothing_between = composite.shadows == 0. && composite.highlights == 100. && channel.output_minimums == 0. && channel.output_maximums == 100.; + if nothing_between { + let merged = LevelsRecord { + output_minimums: composite.output_minimums, + output_maximums: composite.output_maximums, + ..channel + }; + let stage = merged.stage(channel.midtones * composite.midtones); + Self { + first: stage, + second: stage, + two_stages: false, + } + } else { + Self { + first: channel.stage(channel.midtones), + second: composite.stage(composite.midtones), + two_stages: true, + } + } + } + + fn apply(&self, value: f32) -> f32 { + let value = self.first.apply(value); + if self.two_stages { self.second.apply(value) } else { value } + } +} + +struct Levels { + red: LevelsChain, + green: LevelsChain, + blue: LevelsChain, + alpha: LevelsStage, +} + +impl MapColor for Levels { + fn map_cpu(&self, color: Color) -> Color { + // Levels math operates in gamma space + let [r, g, b, a] = color.to_gamma_srgb_channels(); + + Color::from_gamma_srgb_channels(self.red.apply(r), self.green.apply(g), self.blue.apply(b), self.alpha.apply(a)) + } +} + +struct Curves { + composite: TransferCurveEvaluator, + red: TransferCurveEvaluator, + green: TransferCurveEvaluator, + blue: TransferCurveEvaluator, + alpha: TransferCurveEvaluator, +} + +impl Curves { + fn apply(&self, [r, g, b, a]: [f32; 4]) -> [f32; 4] { + let map = |channel: &TransferCurveEvaluator, value: f32| self.composite.evaluate(channel.evaluate(value as f64).clamp(0., 1.)).clamp(0., 1.) as f32; + + // Alpha stands apart from the composite curve that the three color channels pass through + let a = self.alpha.evaluate(a as f64).clamp(0., 1.) as f32; + + [map(&self.red, r), map(&self.green, g), map(&self.blue, b), a] + } +} + +impl MapColor for Curves { + fn map_cpu(&self, color: Color) -> Color { + // Curves math operates in gamma space + let [r, g, b, a] = self.apply(color.to_gamma_srgb_channels()); + Color::from_gamma_srgb_channels(r, g, b, a) + } +} + +struct BlackAndWhite { + use_tint: bool, + tint: Color, + reds: f32, + yellows: f32, + greens: f32, + cyans: f32, + blues: f32, + magentas: f32, +} + +impl MapColor for BlackAndWhite { + fn map_cpu(&self, color: Color) -> Color { + let BlackAndWhite { + use_tint, + tint, + reds, + yellows, + greens, + cyans, + blues, + magentas, + } = *self; + + // Black & White channel weights are tuned for gamma-space values + let [r, g, b, alpha_part] = color.to_gamma_srgb_channels(); + + let gray_base = r.min(g).min(b); + + let red_part = r - gray_base; + let green_part = g - gray_base; + let blue_part = b - gray_base; + + let additional = if red_part == 0. { + let cyan_part = green_part.min(blue_part); + cyan_part * cyans + (green_part - cyan_part) * greens + (blue_part - cyan_part) * blues + } else if green_part == 0. { + let magenta_part = red_part.min(blue_part); + magenta_part * magentas + (red_part - magenta_part) * reds + (blue_part - magenta_part) * blues + } else { + let yellow_part = red_part.min(green_part); + yellow_part * yellows + (red_part - yellow_part) * reds + (green_part - yellow_part) * greens + }; + + let luminance = (gray_base + additional).clamp(0., 1.); + if !use_tint { + return Color::from_gamma_srgb_channels(luminance, luminance, luminance, alpha_part); + } + + // The tint takes on the gray's luminosity the way the Luminosity blend mode would + let [tint_r, tint_g, tint_b, _] = tint.to_gamma_srgb_channels(); + let tint_luma = luma_rec_601_fixed_point(tint_r, tint_g, tint_b); + let [tinted_r, tinted_g, tinted_b] = set_luminosity(tint_r, tint_g, tint_b, tint_luma, luminance); + + Color::from_gamma_srgb_channels(tinted_r, tinted_g, tinted_b, alpha_part) + } +} + +/// HSL of gamma-encoded channels: hue in degrees, saturation and lightness in 0..1. +fn gamma_rgb_to_hsl(r: f32, g: f32, b: f32) -> [f32; 3] { + let maximum = r.max(g).max(b); + let minimum = r.min(g).min(b); + let chroma = maximum - minimum; + let lightness = (maximum + minimum) / 2.; + if chroma <= 0. { + return [0., 0., lightness]; + } + + let saturation = chroma / (1. - (2. * lightness - 1.).abs()).max(1e-6); + [hexagon_hue_degrees(r, g, b), saturation.min(1.), lightness] +} + +/// Hexagon hue in degrees of three channels in any encoding, 0 for gray. +fn hexagon_hue_degrees(r: f32, g: f32, b: f32) -> f32 { + let maximum = r.max(g).max(b); + let chroma = maximum - r.min(g).min(b); + if chroma <= 0. { + return 0.; + } + + let sector = if maximum == r { + wrap_positive((g - b) / chroma, 6.) + } else if maximum == g { + (b - r) / chroma + 2. + } else { + (r - g) / chroma + 4. + }; + sector * 60. +} + +/// `value` wrapped into the range from 0 to `modulus`. +fn wrap_positive(value: f32, modulus: f32) -> f32 { + value - (value / modulus).floor() * modulus +} + +/// Gamma-encoded channels from a hue in degrees and saturation and lightness in 0..1. +fn hsl_to_gamma_rgb(hue: f32, saturation: f32, lightness: f32) -> [f32; 3] { + let chroma = (1. - (2. * lightness - 1.).abs()) * saturation; + let sector = wrap_positive(hue, 360.) / 60.; + let x = chroma * (1. - (wrap_positive(sector, 2.) - 1.).abs()); + let (r, g, b) = if sector < 1. { + (chroma, x, 0.) + } else if sector < 2. { + (x, chroma, 0.) + } else if sector < 3. { + (0., chroma, x) + } else if sector < 4. { + (0., x, chroma) + } else if sector < 5. { + (x, 0., chroma) + } else { + (chroma, 0., x) + }; + let m = lightness - chroma / 2.; + + [(r + m).clamp(0., 1.), (g + m).clamp(0., 1.), (b + m).clamp(0., 1.)] +} + +/// One set of Hue/Saturation sliders: a hue shift in degrees and saturation and lightness amounts in -1..1. +#[derive(Clone, Copy)] +struct PreparedHueSaturationSliders { + hue: f32, + saturation: f32, + saturation_gain: f32, + lightness: f32, +} + +impl PreparedHueSaturationSliders { + fn new(hue: f32, saturation_percent: f32, lightness_percent: f32) -> Self { + let saturation = saturation_percent / 100.; + Self { + hue, + saturation, + saturation_gain: saturation_gain(saturation), + lightness: lightness_percent / 100., + } + } +} + +/// A hue range with its falloff: full weight from `range_start` to `range_end`, fading linearly to zero at the falloff ends. +#[derive(Clone, Copy)] +struct HueSaturationRangeSettings { + falloff_start: f32, + range_start: f32, + range_end: f32, + falloff_end: f32, + settings: PreparedHueSaturationSliders, +} + +impl HueSaturationRangeSettings { + fn new(falloff_start: f32, range_start: f32, range_end: f32, falloff_end: f32, settings: PreparedHueSaturationSliders) -> Self { + // For PSD interop, each edge rounds to 1536 hue units per turn over 359 rather than 360 degrees, landing up to a degree late + let edge = |degrees: f32| (degrees * 1536. / 359.).round() * 360. / 1536.; + + Self { + falloff_start: edge(falloff_start), + range_start: edge(range_start), + range_end: edge(range_end), + falloff_end: edge(falloff_end), + settings, + } + } + + fn weight(&self, hue: f32) -> f32 { + let distance = |from: f32, to: f32| wrap_positive(to - from, 360.); + if distance(self.range_start, hue) <= distance(self.range_start, self.range_end) { + return 1.; + } + let start_falloff = distance(self.falloff_start, self.range_start); + let end_falloff = distance(self.range_end, self.falloff_end); + if distance(self.falloff_start, hue) < start_falloff { + return distance(self.falloff_start, hue) / start_falloff; + } + if distance(self.range_end, hue) < end_falloff { + return 1. - distance(self.range_end, hue) / end_falloff; + } + 0. + } +} + +/// The six ranges' combined effect on one pixel, gathered before the master sliders apply. +struct HueSaturationRangeEffect { + hue_shift: f32, + saturation_factor: f32, + fully_saturate: bool, + rgb: [f32; 3], +} + +impl HueSaturationRangeEffect { + fn apply(&mut self, range: &HueSaturationRangeSettings, original_hue: f32, original_saturation: f32) { + // Range weights come from the original hue, and grays belong to no range + let weight = if original_saturation > 0. { range.weight(original_hue) } else { 0. }; + if weight <= 0. { + return; + } + + self.hue_shift += range.settings.hue * weight; + // For PSD interop, +100 saturates fully from the very edge of the falloff rather than scaling with the weight + if range.settings.saturation >= 1. { + self.fully_saturate = true; + } else { + self.saturation_factor *= 1. + (range.settings.saturation_gain - 1.) * weight; + } + self.rgb = lightness_toward_max_or_min(self.rgb, range.settings.lightness * weight); + } +} + +/// The factor a saturation amount in -1..1 applies to HSL saturation, quantized for PSD interop: 1 - trunc(256 a) / 256 below zero and floor(65280 / (255 - trunc(254 a))) / 256 above. +fn saturation_gain(amount: f32) -> f32 { + if amount < 0. { + 1. - (-amount * 256.).trunc() / 256. + } else { + (65280. / (255. - (amount * 254.).trunc())).floor() / 256. + } +} + +/// Blends toward white for a positive amount and toward black for a negative one, as the master lightness slider does. +fn lightness_toward_white_or_black(value: f32, amount: f32) -> f32 { + if amount >= 0. { value + (1. - value) * amount } else { value * (1. + amount) } +} + +/// A range's lightness moves the channels toward the color's own maximum (positive) or minimum (negative) instead. +fn lightness_toward_max_or_min(rgb: [f32; 3], amount: f32) -> [f32; 3] { + let maximum = rgb[0].max(rgb[1]).max(rgb[2]); + let minimum = rgb[0].min(rgb[1]).min(rgb[2]); + let toward = if amount >= 0. { maximum } else { minimum }; + let blend = |value: f32| value + (toward - value) * amount.abs(); + [blend(rgb[0]), blend(rgb[1]), blend(rgb[2])] +} + +struct HueSaturation { + master: PreparedHueSaturationSliders, + colorize: bool, + colorize_settings: PreparedHueSaturationSliders, + reds: HueSaturationRangeSettings, + yellows: HueSaturationRangeSettings, + greens: HueSaturationRangeSettings, + cyans: HueSaturationRangeSettings, + blues: HueSaturationRangeSettings, + magentas: HueSaturationRangeSettings, +} + +impl MapColor for HueSaturation { + fn map_cpu(&self, color: Color) -> Color { + let Self { + master, + colorize, + colorize_settings, + reds, + yellows, + greens, + cyans, + blues, + magentas, + } = *self; + let [r, g, b, alpha] = color.to_gamma_srgb_channels(); + + if colorize { + let [_, _, lightness] = gamma_rgb_to_hsl(r, g, b); + let lightness = lightness_toward_white_or_black(lightness, colorize_settings.lightness); + let [r, g, b] = hsl_to_gamma_rgb(colorize_settings.hue, colorize_settings.saturation, lightness); + return Color::from_gamma_srgb_channels(r, g, b, alpha); + } + + // Each range weights its sliders by its falloff around the original hue: hue shifts add and saturation gains multiply + let [original_hue, original_saturation, _] = gamma_rgb_to_hsl(r, g, b); + let mut effect = HueSaturationRangeEffect { + hue_shift: master.hue, + saturation_factor: 1., + fully_saturate: false, + rgb: [r, g, b], + }; + effect.apply(&reds, original_hue, original_saturation); + effect.apply(&yellows, original_hue, original_saturation); + effect.apply(&greens, original_hue, original_saturation); + effect.apply(&cyans, original_hue, original_saturation); + effect.apply(&blues, original_hue, original_saturation); + effect.apply(&magentas, original_hue, original_saturation); + let HueSaturationRangeEffect { + hue_shift, + mut saturation_factor, + mut fully_saturate, + rgb, + } = effect; + if master.saturation >= 1. { + fully_saturate = true; + } else { + saturation_factor *= master.saturation_gain; + } + + // The master lightness blends toward white or black before the hue and saturation, which work in HSL of the gamma channels + let rgb = [ + lightness_toward_white_or_black(rgb[0], master.lightness), + lightness_toward_white_or_black(rgb[1], master.lightness), + lightness_toward_white_or_black(rgb[2], master.lightness), + ]; + let [hue, saturation, lightness] = gamma_rgb_to_hsl(rgb[0], rgb[1], rgb[2]); + let saturation = if saturation <= 0. { + 0. + } else if fully_saturate { + 1. + } else { + (saturation * saturation_factor).min(1.) + }; + let [r, g, b] = hsl_to_gamma_rgb(hue + hue_shift, saturation, lightness); + + Color::from_gamma_srgb_channels(r, g, b, alpha) + } +} + +struct Invert; + +impl MapColor for Invert { + fn map_cpu(&self, color: Color) -> Color { + color.map_gamma_rgb(|channel| 1. - channel) + } +} + +struct Threshold { + min_luminance: f32, + max_luminance: f32, +} + +impl MapColor for Threshold { + fn map_cpu(&self, color: Color) -> Color { + // For PSD interop, we compare this 14-bit fixed-point Rec. 601 luma against the level unrounded + let [r, g, b, _] = color.to_gamma_srgb_channels(); + let luminance = (4915. * r + 9667. * g + 1802. * b) / 16384.; + + let output = if luminance >= self.min_luminance && luminance <= self.max_luminance { + Color::WHITE + } else { + Color::BLACK + }; + output.with_alpha(color.a()) + } +} + +struct GradientMap { + evaluator: GradientEvaluator, + reverse: bool, +} + +impl MapColor for GradientMap { + fn map_cpu(&self, color: Color) -> Color { + // The classic 0.3/0.59/0.11 luma of the gamma-encoded channels picks the position along the gradient + let [r, g, b, alpha] = color.to_gamma_srgb_channels(); + let intensity = 0.3 * r + 0.59 * g + 0.11 * b; + let intensity = if self.reverse { 1. - intensity } else { intensity }; + + // The source alpha is kept and the gradient's own alpha stops are ignored + self.evaluator.evaluate(intensity as f64).with_alpha(alpha) + } +} + +struct Vibrance { + vibrance: f32, + saturation_scale: f32, +} + +impl MapColor for Vibrance { + fn map_cpu(&self, color: Color) -> Color { + // Vibrance then saturation, both in linear light, which equals applying each alone in turn + let (r, g, b) = (color.r(), color.g(), color.b()); + let maximum = r.max(g).max(b); + let [chroma_factor, brightness_factor] = vibrance_factors(r, g, b, self.vibrance); + let after_vibrance = Color::from_rgbaf32_unchecked( + scale_about_maximum(r, maximum, chroma_factor, brightness_factor), + scale_about_maximum(g, maximum, chroma_factor, brightness_factor), + scale_about_maximum(b, maximum, chroma_factor, brightness_factor), + color.a(), + ); + + // For PSD interop, saturation scales each channel's distance from a gray weighted by ProPhoto's luminance coefficients + let gray = 0.288040 * after_vibrance.r() + 0.711874 * after_vibrance.g() + 0.000086 * after_vibrance.b(); + after_vibrance.map_rgb(|c| (gray + (c - gray) * self.saturation_scale).clamp(0., 1.)) + } +} + +fn scale_about_maximum(channel: f32, maximum: f32, chroma_factor: f32, brightness_factor: f32) -> f32 { + (brightness_factor * (maximum + chroma_factor * (channel - maximum))).clamp(0., 1.) +} + +/// Share of the vibrance boost the skin-tone protection removes at full weight, a fitted constant. +const VIBRANCE_PROTECTION_LOSS: f32 = 0.4857; + +/// Vibrance on linear SDR channels as `[chroma factor about the max, brightness multiply]` for an amount in -1..1, both fading out toward black. +/// Negative desaturates and darkens low-chroma colors most. Positive boosts them, brightens a little, and spares reds. +fn vibrance_factors(r: f32, g: f32, b: f32, amount: f32) -> [f32; 2] { + let maximum = r.max(g).max(b); + let minimum = r.min(g).min(b); + if maximum <= 0. { + return [1., 1.]; + } + let ratio = minimum / maximum; + let saturation = 1. - ratio; + let q = ratio * saturation; + let toe = 1. - (16. * maximum).min(1.); + let rolloff = 1. - toe * toe; + let brightness = (2. * q - q * q) * (1. - maximum) * rolloff; + + if amount < 0. { + let amount = -amount; + let chroma_factor = (1. - amount / 4.) * (1. - amount * (1. - rolloff * saturation * (1. + saturation) / 2.)); + return [chroma_factor, 1. - amount * brightness]; + } + + let protection = skin_tone_window(hexagon_hue_degrees(r, g, b)) * (1. - saturation * saturation); + let amount = amount * (1. - protection * (1. - amount)); + let boost = (5. / 6.) * (1. - VIBRANCE_PROTECTION_LOSS * protection) * amount * ratio * (1. - minimum) * rolloff; + [1. / (1. - boost), 1. + amount * brightness / 4.] +} + +/// How fully a hue falls under the skin-tone protection: all of it from red to 30 degrees, fading out by 45, and back in from 300. +fn skin_tone_window(hue: f32) -> f32 { + if hue < 45. { + ((45. - hue) / 15.).min(1.) + } else if hue >= 300. { + (hue - 300.) / 60. + } else { + 0. + } +} + +struct ChannelMixer { + monochrome: bool, + monochrome_r: f32, + monochrome_g: f32, + monochrome_b: f32, + monochrome_c: f32, + red_r: f32, + red_g: f32, + red_b: f32, + red_c: f32, + green_r: f32, + green_g: f32, + green_b: f32, + green_c: f32, + blue_r: f32, + blue_g: f32, + blue_b: f32, + blue_c: f32, +} + +impl MapColor for ChannelMixer { + fn map_cpu(&self, color: Color) -> Color { + let [r, g, b, a] = color.to_gamma_srgb_channels(); + + let (out_r, out_g, out_b) = if self.monochrome { + let gray = (r * self.monochrome_r + g * self.monochrome_g + b * self.monochrome_b + self.monochrome_c).clamp(0., 1.); + + (gray, gray, gray) + } else { + let red = (r * self.red_r + g * self.red_g + b * self.red_b + self.red_c).clamp(0., 1.); + let green = (r * self.green_r + g * self.green_g + b * self.green_b + self.green_c).clamp(0., 1.); + let blue = (r * self.blue_r + g * self.blue_g + b * self.blue_b + self.blue_c).clamp(0., 1.); + + (red, green, blue) + }; + + Color::from_gamma_srgb_channels(out_r, out_g, out_b, a) + } +} + +/// The groups of colors that Selective Color adjusts, in the order of its settings. +#[derive(Clone, Copy)] +enum SelectiveColorGroup { + Reds, + Yellows, + Greens, + Cyans, + Blues, + Magentas, + Whites, + Neutrals, + Blacks, +} + +/// A group's cyan, magenta, yellow, and black percentages, with the inks they combine into for each of red, green, and blue. +#[derive(Clone, Copy)] +struct SelectiveColorGroupInks { + group: SelectiveColorGroup, + cmyk: [f32; 4], + inks: [f32; 3], +} + +struct SelectiveColor { + mode: RelativeAbsolute, + groups: [SelectiveColorGroupInks; 9], +} + +impl MapColor for SelectiveColor { + fn map_cpu(&self, color: Color) -> Color { + let [r, g, b, a] = color.to_gamma_srgb_channels(); + + let min = |a: f32, b: f32, c: f32| a.min(b).min(c); + let max = |a: f32, b: f32, c: f32| a.max(b).max(c); + let med = |a: f32, b: f32, c: f32| a + b + c - min(a, b, c) - max(a, b, c); + + let max_channel = max(r, g, b); + let min_channel = min(r, g, b); + + let pixel_color_range = |group| match group { + SelectiveColorGroup::Reds => max_channel == r, + SelectiveColorGroup::Yellows => min_channel == b, + SelectiveColorGroup::Greens => max_channel == g, + SelectiveColorGroup::Cyans => min_channel == r, + SelectiveColorGroup::Blues => max_channel == b, + SelectiveColorGroup::Magentas => min_channel == g, + SelectiveColorGroup::Whites => r > 0.5 && g > 0.5 && b > 0.5, + // Every pixel, since the neutrals scale factor already vanishes at black, white, and fully saturated colors + SelectiveColorGroup::Neutrals => true, + SelectiveColorGroup::Blacks => r < 0.5 && g < 0.5 && b < 0.5, + }; + + let color_parameter_group_scale_factor_rgb = max(r, g, b) - med(r, g, b); + let color_parameter_group_scale_factor_cmy = med(r, g, b) - min(r, g, b); + + // Used to apply the r, g, or b channel slope (by multiplying it by 1) in relative mode, or no slope (by multiplying it by 0) in absolute mode + let (slope_r, slope_g, slope_b) = match self.mode { + RelativeAbsolute::Relative => (r - 1., g - 1., b - 1.), + RelativeAbsolute::Absolute => (-1., -1., -1.), + }; + + let mut sum = Vec3::ZERO; + for SelectiveColorGroupInks { + group, + cmyk: [c, m, y, k], + inks: [ink_c, ink_m, ink_y], + } in self.groups + { + // Skip this group if it's left at zero or this pixel's color isn't in the range it affects + if (c == 0. && m == 0. && y == 0. && k == 0.) || !pixel_color_range(group) { + continue; + } + + let color_parameter_group_scale_factor = match group { + SelectiveColorGroup::Reds | SelectiveColorGroup::Greens | SelectiveColorGroup::Blues => color_parameter_group_scale_factor_rgb, + SelectiveColorGroup::Cyans | SelectiveColorGroup::Magentas | SelectiveColorGroup::Yellows => color_parameter_group_scale_factor_cmy, + SelectiveColorGroup::Whites => min(r, g, b) * 2. - 1., + SelectiveColorGroup::Neutrals => 1. - ((max(r, g, b) - 0.5).abs() + (min(r, g, b) - 0.5).abs()), + SelectiveColorGroup::Blacks => 1. - max(r, g, b) * 2., + }; + + let offset_r = (ink_c * slope_r).max(-r).min(-r + 1.) * color_parameter_group_scale_factor; + let offset_g = (ink_m * slope_g).max(-g).min(-g + 1.) * color_parameter_group_scale_factor; + let offset_b = (ink_y * slope_b).max(-b).min(-b + 1.) * color_parameter_group_scale_factor; + + // An 8-bit PSD document sums the groups' 8-bit offsets, which this float node does not currently attempt to reproduce + sum += Vec3::new(offset_r, offset_g, offset_b); + } + + let rgb = Vec3::new(r, g, b); + let out = (sum + rgb).clamp(Vec3::ZERO, Vec3::ONE); + + Color::from_gamma_srgb_channels(out.x, out.y, out.z, a) + } +} + +struct Posterize { + levels: f32, +} + +impl MapColor for Posterize { + fn map_cpu(&self, color: Color) -> Color { + let levels = self.levels; + + color.map_gamma_rgb(|c| { + // Bins as floor(c * levels) with the outputs spread evenly to white. + // The sliver of slack keeps an input exactly on an edge in the upper bin despite float ties. + let bin = ((c + 2e-7) * levels).floor().min(levels - 1.); + bin / (levels - 1.) + }) + } +} + +struct Exposure { + exposure: f32, + offset: f32, + gamma_correction: f32, +} + +impl MapColor for Exposure { + fn map_cpu(&self, color: Color) -> Color { + // Linearizes with a 2.2 power above a straight toe of slope 1/32, the two meeting at this constant + const TOE_END: f32 = 0.05568117; // 32^(-1. / 1.2) + + let decode = |value: f32| if value < TOE_END { value / 32. } else { value.powf(2.2) }; + let encode = |linear: f32| if linear < TOE_END / 32. { linear * 32. } else { linear.powf(1. / 2.2) }; + let adjust = |c: f32| { + let linear = decode(c) * 2_f32.powf(self.exposure) + self.offset; + encode(linear.max(0.).powf(1. / self.gamma_correction).min(1.)) + }; + + let [r, g, b, a] = color.to_gamma_srgb_channels(); + Color::from_gamma_srgb_channels(adjust(r), adjust(g), adjust(b), a) + } +} + +/// A Levels-style tone curve: input black and white points on a 0..255 scale and a gamma exponent. For gamma above 1 the +/// power curve's slope is unbounded at black, so a cubic toe holds it to 2^gamma until past where that line meets the curve. +#[derive(Debug, Clone, Copy)] +struct LevelsCurve { + black: f32, + white: f32, + exponent: f32, + toe_end: f32, + toe_value: f32, + toe_slope_start: f32, + toe_slope_end: f32, +} + +impl LevelsCurve { + fn new(black: i32, white: i32, gamma: f32) -> Self { + Self::from_points(black as f32, white as f32, gamma) + } + + /// `gamma` is the Levels dialog value (pixel exponent 1/gamma). + fn from_points(black: f32, white: f32, gamma: f32) -> Self { + let gamma = gamma.max(0.01); + let black = black.min(white - 1.); + let exponent = 1. / gamma; + + let mut curve = Self { + black, + white, + exponent, + toe_end: 0., + toe_value: 0., + toe_slope_start: 0., + toe_slope_end: 0., + }; + if gamma > 1. { + let slope = 2_f32.powf(gamma); + let intersection = 255. * slope.powf(-1. / (1. - exponent)); + // The cubic toe joins the power curve at twice the intersection + if intersection > 1e-3 { + let toe_end = 2. * intersection; + curve.toe_end = toe_end; + curve.toe_value = 255. * (toe_end / 255.).powf(exponent); + curve.toe_slope_start = slope; + curve.toe_slope_end = exponent * (toe_end / 255.).powf(exponent - 1.); + } + } + curve + } + + /// Maps one gamma-space channel value in 0..1. + fn apply(&self, value: f32) -> f32 { + let t = ((value * 255. - self.black) * 255. / (self.white - self.black)).clamp(0., 255.); + let y = if t < self.toe_end { + let u = t / self.toe_end; + let hermite_start = u * u * u - 2. * u * u + u; + let hermite_end_value = 3. * u * u - 2. * u * u * u; + let hermite_end_slope = u * u * u - u * u; + hermite_start * self.toe_end * self.toe_slope_start + hermite_end_value * self.toe_value + hermite_end_slope * self.toe_end * self.toe_slope_end + } else { + 255. * (t / 255.).powf(self.exponent) + }; + y / 255. + } +} + +/// One channel's Levels parameters from its own slider values, and (with preserve_luminosity) the slider +/// extremes across all three channels. The halvings truncate toward zero, as PSD interop requires. +#[allow(clippy::too_many_arguments)] +fn color_balance_curve(s: i32, m: i32, h: i32, s_max: i32, m_max: i32, m_min: i32, h_min: i32, preserve_luminosity: bool) -> LevelsCurve { + let (black, white, tone) = if preserve_luminosity { + (s_max - s, 255 - (h - h_min), m - (m_max + m_min) / 2) + } else { + (0.max(-s), 255 - 0.max(h), (s + h) / 2 + m) + }; + + // Rounding the derived gamma to hundredths, the precision of a PSD Levels record, is needed for compatible results + let gamma = (2_f32.powf(tone as f32 / 100.) * 100.).round() / 100.; + LevelsCurve::new(black, white, gamma) +} + +struct ColorBalance { + red: LevelsCurve, + green: LevelsCurve, + blue: LevelsCurve, +} + +impl MapColor for ColorBalance { + fn map_cpu(&self, color: Color) -> Color { + // The curves operate on gamma-space channel values + let [r, g, b, a] = color.to_gamma_srgb_channels(); + Color::from_gamma_srgb_channels(self.red.apply(r), self.green.apply(g), self.blue.apply(b), a) + } +} + +struct PhotoFilter { + factor: [f32; 3], + preserve_luminosity: bool, +} + +impl MapColor for PhotoFilter { + fn map_cpu(&self, pixel: Color) -> Color { + let PhotoFilter { factor, preserve_luminosity } = *self; + + let [r_in, g_in, b_in, alpha] = pixel.to_gamma_srgb_channels(); + let xyz = multiply_matrix(&SRGB_TO_XYZ_D50, [srgb_to_linear(r_in), srgb_to_linear(g_in), srgb_to_linear(b_in)]); + let filtered = multiply_matrix(&XYZ_D50_TO_SRGB, [xyz[0] * factor[0], xyz[1] * factor[1], xyz[2] * factor[2]]); + let mut r = linear_to_srgb(filtered[0].clamp(0., 1.)); + let mut g = linear_to_srgb(filtered[1].clamp(0., 1.)); + let mut b = linear_to_srgb(filtered[2].clamp(0., 1.)); + + if preserve_luminosity { + let luma_in = luma_rec_601_fixed_point(r_in.clamp(0., 1.), g_in.clamp(0., 1.), b_in.clamp(0., 1.)); + [r, g, b] = set_luminosity(r, g, b, luma_rec_601_fixed_point(r, g, b), luma_in); + } + + Color::from_gamma_srgb_channels(r, g, b, alpha) + } +} + +// sRGB colorants adapted to D50 as in the sRGB IEC61966-2.1 ICC profile, row major, and their inverse +pub(crate) const SRGB_TO_XYZ_D50: [[f32; 3]; 3] = [[0.43607, 0.38515, 0.14307], [0.22249, 0.71687, 0.06061], [0.01392, 0.09708, 0.71410]]; +pub(crate) const XYZ_D50_TO_SRGB: [[f32; 3]; 3] = [[3.134096, -1.6174, -0.490638], [-0.978793, 1.916295, 0.033454], [0.071971, -0.228987, 1.40538]]; +pub(crate) const WHITE_XYZ_D50: [f32; 3] = [0.96420, 1., 0.82491]; + +pub(crate) fn multiply_matrix(matrix: &[[f32; 3]; 3], vector: [f32; 3]) -> [f32; 3] { + [ + matrix[0][0] * vector[0] + matrix[0][1] * vector[1] + matrix[0][2] * vector[2], + matrix[1][0] * vector[0] + matrix[1][1] * vector[1] + matrix[1][2] * vector[2], + matrix[2][0] * vector[0] + matrix[2][1] * vector[1] + matrix[2][2] * vector[2], + ] +} + +/// The Rec. 601 luma in the 14-bit fixed point that PSD interop depends on. +fn luma_rec_601_fixed_point(r: f32, g: f32, b: f32) -> f32 { + (4915. * r + 9667. * g + 1802. * b) / 16384. +} + +struct ColorLookup { + lut: Arc, +} + +impl MapColor for ColorLookup { + fn map_cpu(&self, color: Color) -> Color { + // Lookup tables address the gamma-encoded channels + let [r, g, b, a] = color.to_gamma_srgb_channels(); + let [r, g, b] = self.lut.apply([r, g, b]); + + Color::from_gamma_srgb_channels(r, g, b, a) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const COLORS: [Color; 2] = [Color::from_rgbaf32_unchecked(0.2, 0.5, 0.9, 1.), Color::from_rgbaf32_unchecked(1., 0., 0.3, 0.5)]; + + #[test] + fn a_prepared_adjustment_matches_preparing_it_for_each_color() { + let adjustments = [ + Adjustment::Invert, + Adjustment::Posterize { levels: 3 }, + Adjustment::Exposure { + exposure: 1., + offset: 0.1, + gamma_correction: 1.2, + }, + ]; + + for adjustment in &adjustments { + let prepared = PreparedAdjustment::new(adjustment); + for color in COLORS { + assert_eq!(prepared.adjust(color), adjust_color(adjustment, color), "{adjustment:?}"); + } + } + } + + #[test] + fn settings_past_their_bounds_stay_finite() { + let adjustments = [ + Adjustment::Posterize { levels: 1 }, + Adjustment::GammaCorrection { gamma: 0., inverse: true }, + Adjustment::Exposure { + exposure: 0., + offset: 0., + gamma_correction: 0., + }, + ]; + + for adjustment in &adjustments { + for color in COLORS { + let adjusted = adjust_color(adjustment, color); + assert!([adjusted.r(), adjusted.g(), adjusted.b(), adjusted.a()].iter().all(|channel| channel.is_finite()), "{adjustment:?}"); + } + } + } +} diff --git a/node-graph/libraries/raster-kernels/src/blending.rs b/node-graph/libraries/raster-kernels/src/blending.rs new file mode 100644 index 00000000000..db8ec6920ef --- /dev/null +++ b/node-graph/libraries/raster-kernels/src/blending.rs @@ -0,0 +1,20 @@ +//! The kernels blending one color with another. + +use crate::MapColor; +use core_types::Color; +use core_types::blending::{BlendMode, apply_blend_mode}; + +pub(crate) struct ColorOverlay { + pub(crate) color: Color, + pub(crate) blend_mode: BlendMode, + pub(crate) opacity: f32, +} + +impl MapColor for ColorOverlay { + fn map_cpu(&self, pixel: Color) -> Color { + let overlay = apply_blend_mode(self.color, pixel, self.blend_mode); + let mix = |image: f32, overlay: f32| image + (overlay - image) * self.opacity; + + Color::from_rgbaf32_unchecked(mix(pixel.r(), overlay.r()), mix(pixel.g(), overlay.g()), mix(pixel.b(), overlay.b()), pixel.a()) + } +} diff --git a/node-graph/nodes/raster/src/color_lookup_table.rs b/node-graph/libraries/raster-kernels/src/color_lookup_table.rs similarity index 86% rename from node-graph/nodes/raster/src/color_lookup_table.rs rename to node-graph/libraries/raster-kernels/src/color_lookup_table.rs index 06362d32d70..d3ce156192d 100644 --- a/node-graph/nodes/raster/src/color_lookup_table.rs +++ b/node-graph/libraries/raster-kernels/src/color_lookup_table.rs @@ -8,35 +8,52 @@ mod format_look; use crate::adjustments::{SRGB_TO_XYZ_D50, WHITE_XYZ_D50, XYZ_D50_TO_SRGB, multiply_matrix}; use core_types::color::{linear_to_srgb, srgb_to_linear}; -use graphene_resource::{Resource, ResourceHash}; -use std::sync::{Arc, Mutex, PoisonError}; +use graphene_resource::{Resource, ResourceHash, WeakResource}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; pub const LUT_FILE_EXTENSIONS: &[&str] = &["cube", "3dl", "look", "csp", "icc", "icm"]; /// A file's parse result, in the form the cache shares out. type ParsedLut = Result, LutParseError>; -/// The last file a node parsed, kept as the node's own data so the file is not parsed anew each time the node runs again. -#[derive(Debug, Clone, Default)] -pub struct LutCache(Arc>>); - -impl LutCache { - /// [`Lut::parse`] for a resource, reusing the last result while the file's content hash stays the same. - pub fn parse(&self, resource: &Resource) -> ParsedLut { - // A lock poisoned by a panic elsewhere still guards a usable cache - let mut cached = self.0.lock().unwrap_or_else(PoisonError::into_inner); - - let hash = resource.hash(); - if let Some((cached_hash, result)) = cached.as_ref() - && *cached_hash == hash - { - return result.clone(); - } +/// A parse result, kept while the file it came from is still loaded somewhere. +struct ParsedFile { + hash: ResourceHash, + file: WeakResource, + parsed: ParsedLut, +} + +/// The parse results of the files that are still loaded, shared by every adjustment that reads a lookup table. +static PARSED_FILES: Mutex> = Mutex::new(Vec::new()); + +fn parsed_files() -> MutexGuard<'static, Vec> { + // A lock poisoned by a panic elsewhere still guards a usable cache + PARSED_FILES.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// [`Lut::parse`] for a resource, reusing the result for as long as a file with the same content hash stays loaded. O(n) in the loaded files. +pub fn parse_cached(resource: &Resource) -> ParsedLut { + let hash = resource.hash(); + + // Follows the copy in hand, in case another copy of the same content is the one that goes away + if let Some(entry) = parsed_files().iter_mut().find(|entry| entry.hash == hash) { + entry.file = resource.downgrade(); + return entry.parsed.clone(); + } - let result = Lut::parse(resource).map(Arc::new); - *cached = Some((hash, result.clone())); - result + // Parsed outside the lock, so a large file doesn't hold up the adjustments reading other files + let parsed = Lut::parse(resource).map(Arc::new); + + let mut parsed_files = parsed_files(); + parsed_files.retain(|entry| entry.file.is_alive()); + if !parsed_files.iter().any(|entry| entry.hash == hash) { + parsed_files.push(ParsedFile { + hash, + file: resource.downgrade(), + parsed: parsed.clone(), + }); } + parsed } /// Why a file could not be read as a lookup table. @@ -423,18 +440,20 @@ mod tests { } #[test] - fn a_cache_parses_a_file_once_until_the_file_changes() { - let file = Resource::new(b"LUT_1D_SIZE 2\n0 0 0\n1 1 1\n".to_vec()); - let cache = LutCache::default(); - let first = cache.parse(&file).unwrap(); - assert!(Arc::ptr_eq(&first, &cache.parse(&file).unwrap())); - - // A cloned node shares its cache - assert!(Arc::ptr_eq(&first, &cache.clone().parse(&file).unwrap())); - - // Another file takes its place, a failed one included - assert!(cache.parse(&Resource::new(b"hello world".to_vec())).is_err()); - assert!(!Arc::ptr_eq(&first, &cache.parse(&file).unwrap())); + fn the_cache_parses_a_file_once_while_it_stays_loaded() { + let file = Resource::new(b"LUT_1D_SIZE 2\n0 0 0\n0.5 1 1\n".to_vec()); + let first = parse_cached(&file).unwrap(); + + // Any number of other files, failed ones included, leave it in place + let others: Vec = (0..20).map(|index| Resource::new(format!("not a table {index}").into_bytes())).collect(); + others.iter().for_each(|other| assert!(parse_cached(other).is_err())); + assert!(Arc::ptr_eq(&first, &parse_cached(&file).unwrap())); + + // Once no copy of it is loaded, parsing another file clears it out + let content = file.to_vec(); + drop(file); + assert!(parse_cached(&Resource::new(b"not a table either".to_vec())).is_err()); + assert!(!Arc::ptr_eq(&first, &parse_cached(&Resource::new(content)).unwrap())); } #[test] diff --git a/node-graph/nodes/raster/src/color_lookup_table/format_3dl.rs b/node-graph/libraries/raster-kernels/src/color_lookup_table/format_3dl.rs similarity index 100% rename from node-graph/nodes/raster/src/color_lookup_table/format_3dl.rs rename to node-graph/libraries/raster-kernels/src/color_lookup_table/format_3dl.rs diff --git a/node-graph/nodes/raster/src/color_lookup_table/format_csp.rs b/node-graph/libraries/raster-kernels/src/color_lookup_table/format_csp.rs similarity index 100% rename from node-graph/nodes/raster/src/color_lookup_table/format_csp.rs rename to node-graph/libraries/raster-kernels/src/color_lookup_table/format_csp.rs diff --git a/node-graph/nodes/raster/src/color_lookup_table/format_cube.rs b/node-graph/libraries/raster-kernels/src/color_lookup_table/format_cube.rs similarity index 100% rename from node-graph/nodes/raster/src/color_lookup_table/format_cube.rs rename to node-graph/libraries/raster-kernels/src/color_lookup_table/format_cube.rs diff --git a/node-graph/nodes/raster/src/color_lookup_table/format_icc.rs b/node-graph/libraries/raster-kernels/src/color_lookup_table/format_icc.rs similarity index 100% rename from node-graph/nodes/raster/src/color_lookup_table/format_icc.rs rename to node-graph/libraries/raster-kernels/src/color_lookup_table/format_icc.rs diff --git a/node-graph/nodes/raster/src/color_lookup_table/format_look.rs b/node-graph/libraries/raster-kernels/src/color_lookup_table/format_look.rs similarity index 100% rename from node-graph/nodes/raster/src/color_lookup_table/format_look.rs rename to node-graph/libraries/raster-kernels/src/color_lookup_table/format_look.rs diff --git a/node-graph/libraries/raster-kernels/src/generators.rs b/node-graph/libraries/raster-kernels/src/generators.rs new file mode 100644 index 00000000000..ea8412f5da7 --- /dev/null +++ b/node-graph/libraries/raster-kernels/src/generators.rs @@ -0,0 +1,239 @@ +//! The kernels rendering each [`GeneratorPattern`] across any area of its space at any resolution. + +use core_types::Color; +use glam::{DVec2, IVec2, Vec2}; +use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, NoiseSettings, NoiseType}; +use raster_types::parallel_rows::fill_rows; +use raster_types::{Image, ImageError}; + +/// The most iterations a point is tested for escaping the Mandelbrot set, beyond which it counts as inside. +const MANDELBROT_ITERATIONS: u32 = 255; + +/// The pattern across `area` of its own space, from its minimum to its maximum corner, sampled at the centers of a `width` by `height` grid of pixels. +/// Fails where an image of that size can't be allocated. +/// The rows are rendered in parallel on native targets. +pub fn render_pattern(pattern: &GeneratorPattern, area: [DVec2; 2], width: u32, height: u32) -> Result, ImageError> { + let mut image = Image::try_new(width, height, Color::TRANSPARENT)?; + let pixel_size = (area[1] - area[0]) / DVec2::new(width as f64, height as f64); + let pixel_center = |x: usize, y: usize| area[0] + (DVec2::new(x as f64, y as f64) + 0.5) * pixel_size; + + match pattern { + GeneratorPattern::Noise(settings) => { + let noise = NoiseSampler::new(settings); + fill_rows(&mut image.data, width as usize, |y, row| { + row.iter_mut().enumerate().for_each(|(x, pixel)| *pixel = Color::from_luminance(noise.sample(pixel_center(x, y)))); + }); + } + GeneratorPattern::Mandelbrot => { + fill_rows(&mut image.data, width as usize, |y, row| { + row.iter_mut().enumerate().for_each(|(x, pixel)| { + let c = pixel_center(x, y) * 3. - DVec2::new(2., 1.5); + let value = mandelbrot_escape_iterations(c) as f32 / MANDELBROT_ITERATIONS as f32; + *pixel = Color::from_rgbaf32_unchecked(value, value, value, 1.); + }); + }); + } + } + + Ok(image) +} + +/// Samples a noise pattern's luminance, from 0 to 1, at positions in its space. +struct NoiseSampler { + noise: fastnoise_lite::FastNoiseLite, + white_noise_seed: Option, + domain_warp: bool, +} + +impl NoiseSampler { + fn new(settings: &NoiseSettings) -> Self { + let mut noise = fastnoise_lite::FastNoiseLite::with_seed(settings.seed as i32); + noise.set_frequency(Some(1. / (settings.scale as f32).max(f32::EPSILON))); + + // Domain warp + let domain_warp_type = match settings.domain_warp_type { + DomainWarpType::None => None, + DomainWarpType::OpenSimplex2 => Some(fastnoise_lite::DomainWarpType::OpenSimplex2), + DomainWarpType::OpenSimplex2Reduced => Some(fastnoise_lite::DomainWarpType::OpenSimplex2Reduced), + DomainWarpType::BasicGrid => Some(fastnoise_lite::DomainWarpType::BasicGrid), + }; + let domain_warp = domain_warp_type.is_some() && settings.domain_warp_amplitude > 0.; + noise.set_domain_warp_type(domain_warp_type); + noise.set_domain_warp_amp(Some(settings.domain_warp_amplitude as f32)); + + // Noise and fractal + let noise_type = match settings.noise_type { + NoiseType::Perlin => fastnoise_lite::NoiseType::Perlin, + NoiseType::OpenSimplex2 => fastnoise_lite::NoiseType::OpenSimplex2, + NoiseType::OpenSimplex2S => fastnoise_lite::NoiseType::OpenSimplex2S, + NoiseType::Cellular => fastnoise_lite::NoiseType::Cellular, + NoiseType::ValueCubic => fastnoise_lite::NoiseType::ValueCubic, + NoiseType::Value => fastnoise_lite::NoiseType::Value, + NoiseType::WhiteNoise => { + return Self { + noise, + white_noise_seed: Some(settings.seed as i32), + domain_warp: false, + }; + } + }; + noise.set_noise_type(Some(noise_type)); + let fractal_type = match settings.fractal_type { + FractalType::None => fastnoise_lite::FractalType::None, + FractalType::FBm => fastnoise_lite::FractalType::FBm, + FractalType::Ridged => fastnoise_lite::FractalType::Ridged, + FractalType::PingPong => fastnoise_lite::FractalType::PingPong, + FractalType::DomainWarpProgressive => fastnoise_lite::FractalType::DomainWarpProgressive, + FractalType::DomainWarpIndependent => fastnoise_lite::FractalType::DomainWarpIndependent, + }; + noise.set_fractal_type(Some(fractal_type)); + noise.set_fractal_octaves(Some(settings.fractal_octaves as i32)); + noise.set_fractal_lacunarity(Some(settings.fractal_lacunarity as f32)); + noise.set_fractal_gain(Some(settings.fractal_gain as f32)); + noise.set_fractal_weighted_strength(Some(settings.fractal_weighted_strength as f32)); + noise.set_fractal_ping_pong_strength(Some(settings.fractal_ping_pong_strength as f32)); + + // Cellular + let cellular_distance_function = match settings.cellular_distance_function { + CellularDistanceFunction::Euclidean => fastnoise_lite::CellularDistanceFunction::Euclidean, + CellularDistanceFunction::EuclideanSq => fastnoise_lite::CellularDistanceFunction::EuclideanSq, + CellularDistanceFunction::Manhattan => fastnoise_lite::CellularDistanceFunction::Manhattan, + CellularDistanceFunction::Hybrid => fastnoise_lite::CellularDistanceFunction::Hybrid, + }; + let cellular_return_type = match settings.cellular_return_type { + CellularReturnType::CellValue => fastnoise_lite::CellularReturnType::CellValue, + CellularReturnType::Nearest => fastnoise_lite::CellularReturnType::Distance, + CellularReturnType::NextNearest => fastnoise_lite::CellularReturnType::Distance2, + CellularReturnType::Average => fastnoise_lite::CellularReturnType::Distance2Add, + CellularReturnType::Difference => fastnoise_lite::CellularReturnType::Distance2Sub, + CellularReturnType::Product => fastnoise_lite::CellularReturnType::Distance2Mul, + CellularReturnType::Division => fastnoise_lite::CellularReturnType::Distance2Div, + }; + noise.set_cellular_distance_function(Some(cellular_distance_function)); + noise.set_cellular_return_type(Some(cellular_return_type)); + noise.set_cellular_jitter(Some(settings.cellular_jitter as f32)); + + Self { + noise, + white_noise_seed: None, + domain_warp, + } + } + + fn sample(&self, position: DVec2) -> f32 { + // White noise gives each square of one document unit its own random value + if let Some(seed) = self.white_noise_seed { + return white_noise(seed, position.floor().as_ivec2()); + } + + let (mut x, mut y) = (position.x as f32, position.y as f32); + if self.domain_warp { + (x, y) = self.noise.domain_warp_2d(x, y); + } + (self.noise.get_noise_2d(x, y) + 1.) * 0.5 + } +} + +/// A random value from 0 to 1 for each cell of a grid, the same for the same seed and cell. In 32-bit math, which a GPU can match. +fn white_noise(seed: i32, cell: IVec2) -> f32 { + let [hash, _, _] = pcg3d([cell.x as u32, cell.y as u32, seed as u32]); + + // The top 24 bits, which an f32 holds exactly + (hash >> 8) as f32 / (1_u32 << 24) as f32 +} + +/// PCG3D from Jarzynski and Olano's "Hash Functions for GPU Rendering", which spreads every input bit across the result. +fn pcg3d(input: [u32; 3]) -> [u32; 3] { + let mix = |[x, y, z]: [u32; 3]| { + let x = x.wrapping_add(y.wrapping_mul(z)); + let y = y.wrapping_add(z.wrapping_mul(x)); + let z = z.wrapping_add(x.wrapping_mul(y)); + [x, y, z] + }; + + let v = mix(input.map(|value| value.wrapping_mul(1_664_525).wrapping_add(1_013_904_223))); + mix(v.map(|value| value ^ (value >> 16))) +} + +/// How many iterations `c` takes to escape the Mandelbrot set, or the iteration limit if it doesn't. In f32, which a GPU can match near the boundary. +fn mandelbrot_escape_iterations(c: DVec2) -> u32 { + let c = c.as_vec2(); + let mut z = Vec2::ZERO; + for iteration in 0..MANDELBROT_ITERATIONS { + z = Vec2::new(z.x * z.x - z.y * z.y, 2. * z.x * z.y) + c; + if z.length_squared() > 4. { + return iteration; + } + } + MANDELBROT_ITERATIONS +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn renders_of_overlapping_areas_agree_where_they_overlap() { + let noise = GeneratorPattern::Noise(NoiseSettings { + seed: 7, + scale: 10., + noise_type: NoiseType::OpenSimplex2, + domain_warp_type: DomainWarpType::None, + domain_warp_amplitude: 0., + fractal_type: FractalType::FBm, + fractal_octaves: 3, + fractal_lacunarity: 2., + fractal_gain: 0.5, + fractal_weighted_strength: 0., + fractal_ping_pong_strength: 2., + cellular_distance_function: CellularDistanceFunction::Euclidean, + cellular_return_type: CellularReturnType::Nearest, + cellular_jitter: 1., + }); + + // One pixel per unit across 0 to 32, and again across 16 to 48, as two neighboring tiles of a render would sample it + let whole = render_pattern(&noise, [DVec2::ZERO, DVec2::splat(32.)], 32, 32).unwrap(); + let shifted = render_pattern(&noise, [DVec2::splat(16.), DVec2::splat(48.)], 32, 32).unwrap(); + for y in 0..16 { + for x in 0..16 { + assert_eq!(whole.data[(y + 16) * 32 + x + 16], shifted.data[y * 32 + x]); + } + } + } + + #[test] + fn white_noise_is_the_same_wherever_and_however_finely_it_is_sampled() { + let white_noise = |seed| { + GeneratorPattern::Noise(NoiseSettings { + seed, + scale: 10., + noise_type: NoiseType::WhiteNoise, + domain_warp_type: DomainWarpType::None, + domain_warp_amplitude: 0., + fractal_type: FractalType::None, + fractal_octaves: 1, + fractal_lacunarity: 2., + fractal_gain: 0.5, + fractal_weighted_strength: 0., + fractal_ping_pong_strength: 2., + cellular_distance_function: CellularDistanceFunction::Euclidean, + cellular_return_type: CellularReturnType::Nearest, + cellular_jitter: 1., + }) + }; + + // Each unit cell keeps its value when sampled four times as finely + let coarse = render_pattern(&white_noise(3), [DVec2::ZERO, DVec2::splat(4.)], 4, 4).unwrap(); + let fine = render_pattern(&white_noise(3), [DVec2::ZERO, DVec2::splat(4.)], 16, 16).unwrap(); + for y in 0..16 { + for x in 0..16 { + assert_eq!(fine.data[y * 16 + x], coarse.data[(y / 4) * 4 + x / 4]); + } + } + + // The values spread across the whole range, and another seed gives others + let luminances: Vec = coarse.data.iter().map(|color| color.r()).collect(); + assert!(luminances.iter().any(|&value| value < 0.5) && luminances.iter().any(|&value| value > 0.5)); + assert_ne!(render_pattern(&white_noise(4), [DVec2::ZERO, DVec2::splat(4.)], 4, 4).unwrap().data, coarse.data); + } +} diff --git a/node-graph/libraries/raster-kernels/src/kernel.rs b/node-graph/libraries/raster-kernels/src/kernel.rs new file mode 100644 index 00000000000..a76f121165c --- /dev/null +++ b/node-graph/libraries/raster-kernels/src/kernel.rs @@ -0,0 +1,6 @@ +use core_types::Color; + +/// A per-pixel color mapping, run by `map_cpu` on the CPU. +pub trait MapColor: Sync + 'static { + fn map_cpu(&self, color: Color) -> Color; +} diff --git a/node-graph/libraries/raster-kernels/src/lib.rs b/node-graph/libraries/raster-kernels/src/lib.rs new file mode 100644 index 00000000000..650b0b09e63 --- /dev/null +++ b/node-graph/libraries/raster-kernels/src/lib.rs @@ -0,0 +1,9 @@ +//! The kernels carrying out raster operations, such as color adjustments and procedural patterns, each worked out once from its settings. + +pub mod adjustments; +mod blending; +pub mod color_lookup_table; +pub mod generators; +mod kernel; + +pub use kernel::*; diff --git a/node-graph/libraries/raster-types/src/lib.rs b/node-graph/libraries/raster-types/src/lib.rs index 02413ecf220..eac0d10c46d 100644 --- a/node-graph/libraries/raster-types/src/lib.rs +++ b/node-graph/libraries/raster-types/src/lib.rs @@ -1,4 +1,5 @@ pub mod image; +pub mod parallel_rows; pub mod raster_types; // Re-exports for convenience diff --git a/node-graph/nodes/raster/src/parallel_rows.rs b/node-graph/libraries/raster-types/src/parallel_rows.rs similarity index 100% rename from node-graph/nodes/raster/src/parallel_rows.rs rename to node-graph/libraries/raster-types/src/parallel_rows.rs diff --git a/node-graph/libraries/resources/src/lib.rs b/node-graph/libraries/resources/src/lib.rs index a989d4d3f1b..aa10fc4da59 100644 --- a/node-graph/libraries/resources/src/lib.rs +++ b/node-graph/libraries/resources/src/lib.rs @@ -5,7 +5,7 @@ use std::future::Future; use std::hash::Hash; use std::ops::Deref; use std::pin::Pin; -use std::sync::Arc; +use std::sync::{Arc, Weak}; #[derive(Clone, DynAny)] pub struct Resource { @@ -30,6 +30,22 @@ impl Resource { pub fn empty() -> Self { Self::new([]) } + + /// A reference to this resource's data that doesn't keep it alive. + pub fn downgrade(&self) -> WeakResource { + WeakResource(Arc::downgrade(&self.inner)) + } +} + +/// A reference to a [`Resource`]'s data that doesn't keep it alive, for caches of what's derived from the data. +#[derive(Clone)] +pub struct WeakResource(Weak + Send + Sync>); + +impl WeakResource { + /// Whether anything still holds the resource's data. + pub fn is_alive(&self) -> bool { + self.0.strong_count() > 0 + } } impl Default for Resource { diff --git a/node-graph/libraries/vector-types/src/gradient.rs b/node-graph/libraries/vector-types/src/gradient.rs index 8b2aa7849a6..b155be13abb 100644 --- a/node-graph/libraries/vector-types/src/gradient.rs +++ b/node-graph/libraries/vector-types/src/gradient.rs @@ -1763,7 +1763,7 @@ impl GradientInterpolation { /// The whole-ramp attributes governing how a gradient plays back, read together off a gradient item so the /// sampling entry points take one argument instead of a widening list of same-typed positional ones. -#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, Hash)] +#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, Hash, graphene_hash::CacheHash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct GradientSettings { pub spread: GradientSpread, diff --git a/node-graph/nodes/raster/Cargo.toml b/node-graph/nodes/raster/Cargo.toml index 3f9e6d56d91..c0ef7cf8047 100644 --- a/node-graph/nodes/raster/Cargo.toml +++ b/node-graph/nodes/raster/Cargo.toml @@ -16,9 +16,10 @@ workspace = true [features] default = ["serde"] -serde = ["dep:serde", "core-types/serde", "raster-types/serde", "vector-types/serde"] +serde = ["dep:serde", "core-types/serde", "graphic-types/serde", "raster-types/serde", "vector-types/serde"] wasm = [ "core-types/wasm", + "graphic-types/wasm", "raster-types/wasm", "vector-types/wasm", "tsify", @@ -33,18 +34,16 @@ core-types = { workspace = true } graphene-core = { workspace = true } graphene-resource = { workspace = true } graphene-hash = { workspace = true } +graphic-types = { workspace = true } +raster-kernels = { workspace = true } raster-types = { workspace = true } vector-types = { workspace = true } # Workspace dependencies bytemuck = { workspace = true } glam = { workspace = true } -num_enum = { workspace = true } image = { workspace = true } ndarray = { workspace = true } -rand = { workspace = true } -rand_chacha = { workspace = true } -fastnoise-lite = { workspace = true } serde = { workspace = true, optional = true } color = { workspace = true } thiserror = { workspace = true } diff --git a/node-graph/nodes/raster/src/adjust.rs b/node-graph/nodes/raster/src/adjust.rs index d0625fee9a1..e6748810672 100644 --- a/node-graph/nodes/raster/src/adjust.rs +++ b/node-graph/nodes/raster/src/adjust.rs @@ -1,27 +1,28 @@ use core_types::color::Color; +use graphic_types::Adjustment; +use raster_kernels::adjustments::{PreparedAdjustment, adjust_color, adjust_colors}; use raster_types::{CPU, Raster}; use vector_types::Gradient; -pub trait Adjust

{ - fn adjust(&mut self, map_fn: impl Fn(&P) -> P); +pub trait Adjust { + fn adjust(&mut self, adjustment: &Adjustment); } -impl Adjust for Color { - fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) { - *self = map_fn(self); +impl Adjust for Color { + fn adjust(&mut self, adjustment: &Adjustment) { + *self = adjust_color(adjustment, *self); } } -impl Adjust for Raster { - fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) { - for color in self.data_mut().data.iter_mut() { - *color = map_fn(color); - } +impl Adjust for Raster { + fn adjust(&mut self, adjustment: &Adjustment) { + adjust_colors(adjustment, &mut self.data_mut().data); } } -impl Adjust for Gradient { - fn adjust(&mut self, map_fn: impl Fn(&Color) -> Color) { - *self = self.map_colors(map_fn); +impl Adjust for Gradient { + fn adjust(&mut self, adjustment: &Adjustment) { + let adjustment = PreparedAdjustment::new(adjustment); + *self = self.map_colors(|color| adjustment.adjust(*color)); } } diff --git a/node-graph/nodes/raster/src/adjustments.rs b/node-graph/nodes/raster/src/adjustments.rs index c7e7b6508be..1f674ae3d09 100644 --- a/node-graph/nodes/raster/src/adjustments.rs +++ b/node-graph/nodes/raster/src/adjustments.rs @@ -1,105 +1,36 @@ #![allow(clippy::too_many_arguments)] use crate::adjust::Adjust; -use crate::color_lookup_table::{LutCache, LutParseError}; -use core::fmt::Debug; +use crate::color_lookup_table::{LutParseError, parse_cached}; use core_types::color::Color; -use core_types::color::{linear_to_srgb, set_luminosity, srgb_to_linear}; use core_types::context::Ctx; use core_types::list::{Item, List}; -use core_types::transfer_curve::{TransferCurve, TransferCurveEvaluator}; +use core_types::transfer_curve::TransferCurve; use glam::DVec2; -use glam::Vec3; use graphene_resource::Resource; -use num_enum::{FromPrimitive, IntoPrimitive}; +use graphic_types::adjustment::{ + Adjustment, BlackAndWhiteSettings, ChannelMixerRow, ChannelMixerSettings, ColorBalanceSettings, ColorBalanceShifts, CurvesSettings, HueRangeSettings, HueSaturationSettings, HueSaturationSliders, + LevelsRecord, LevelsSettings, SelectiveColorInks, SelectiveColorSettings, +}; +pub use graphic_types::adjustment::{DesaturateMethod, RelativeAbsolute}; +pub use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType}; use raster_types::{CPU, Image, Raster}; use vector_types::Gradient; -/// Conversion from a color to grayscale. -#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, dyn_any::DynAny, node_macro::ChoiceType, bytemuck::NoUninit, FromPrimitive, IntoPrimitive)] -#[widget(Dropdown)] -#[repr(u32)] -pub enum DesaturateMethod { - /// Light level of the color, the Y (luminance) of Rec. 709, which weights the linear-light RGB channels by `0.2126, 0.7152, 0.0722`. - /// - /// Accessibility contrast ratios and SVG luminance masks use this. - #[default] - #[label("Luminance (Rec. 709)")] - #[cfg_attr(feature = "serde", serde(alias = "SRGB"))] - LuminanceRec709, - /// Light level approximation for the color, the Y′ (luma) of Rec. 709, which weights the gamma-encoded RGB channels by `0.2126, 0.7152, 0.0722`. - /// - /// CSS filter functions such as `grayscale()` use this. - #[label("Luma (Rec. 709)")] - LumaRec709, - /// Light level approximation for the color, the Y′ (luma) of Rec. 601, which weights the gamma-encoded RGB channels by `0.299, 0.587, 0.114`. - /// - /// The Luminosity family of blend modes uses this, rounded to `0.3, 0.59, 0.11`. - #[label("Luma (Rec. 601)")] - LumaRec601, - /// Perceptually uniform scale from black to white, the L (lightness) of OkLab. - #[label("Lightness (OkLab)")] - #[cfg_attr(feature = "serde", serde(alias = "Perceptual"))] - LightnessOkLab, - /// Mean of the three linear-light RGB channels. - #[menu_separator] - #[cfg_attr(feature = "serde", serde(alias = "AverageChannels"))] - ChannelsAverage, - /// Smallest of the three linear-light RGB channels. - #[cfg_attr(feature = "serde", serde(alias = "MinimumChannels"))] - ChannelsMinimum, - /// Largest of the three linear-light RGB channels, the V (value) of HSV. - #[cfg_attr(feature = "serde", serde(alias = "MaximumChannels"))] - ChannelsMaximum, - /// Midpoint of the largest and smallest gamma-encoded RGB channels, the L (lightness) of HSL. - /// - /// The classic "Desaturate" command of many image editors uses this. - #[label("Lightness (HSL)")] - LightnessHsl, +/// Applies the adjustment to the item's element. +fn adjust(item: Item, adjustment: Adjustment) -> Item { + let mut item = item; + item.element_mut().adjust(&adjustment); + item } #[node_macro::node(category("Raster: Adjustment"), icon("NodeDesaturate"))] -fn desaturate>(_: impl Ctx, #[implementations(Raster, Color, Gradient)] input: Item, method: Item) -> Item { - let mut input = input; - let method = method.into_element(); - - input.element_mut().adjust(|color| { - // Gamma-encoded formulas are decoded as if they were a gray - let gamma = || color.to_gamma_srgb_channels(); - let luminance = match method { - DesaturateMethod::LuminanceRec709 => color.luminance_rec_709(), - DesaturateMethod::LumaRec709 => { - let [r, g, b, _] = gamma(); - srgb_to_linear(0.2126 * r + 0.7152 * g + 0.0722 * b) - } - DesaturateMethod::LumaRec601 => { - let [r, g, b, _] = gamma(); - srgb_to_linear(0.299 * r + 0.587 * g + 0.114 * b) - } - DesaturateMethod::LightnessOkLab => { - // A gray's OkLab lightness is the cube root of its linear value, so cubing gives the gray of equal lightness - let lightness = color.lightness_oklab(); - lightness * lightness * lightness - } - DesaturateMethod::ChannelsAverage => color.average_rgb_channels(), - DesaturateMethod::ChannelsMinimum => color.minimum_rgb_channels(), - DesaturateMethod::ChannelsMaximum => color.maximum_rgb_channels(), - DesaturateMethod::LightnessHsl => { - // The transfer curve is monotonic, so the extremes are found first and only they are encoded - let max = linear_to_srgb(color.maximum_rgb_channels()); - let min = linear_to_srgb(color.minimum_rgb_channels()); - srgb_to_linear((max + min) / 2.) - } - }; - color.map_rgb(|_| luminance) - }); - input +fn desaturate(_: impl Ctx, #[implementations(Raster, Color, Gradient)] input: Item, method: Item) -> Item { + adjust(input, Adjustment::Desaturate { method: method.into_element() }) } #[node_macro::node(category("Raster: Adjustment"), icon("NodeGammaCorrection"))] -fn gamma_correction>( +fn gamma_correction( _: impl Ctx, #[implementations(Raster, Color, Gradient)] input: Item, #[default(2.2)] @@ -109,13 +40,13 @@ fn gamma_correction>( gamma: Item, inverse: Item, ) -> Item { - let mut input = input; - let gamma = gamma.into_element(); - let inverse = inverse.into_element(); - - let exponent = if inverse { 1. / gamma } else { gamma }; - input.element_mut().adjust(|color| color.apply_gamma_exponent(exponent as f32)); - input + adjust( + input, + Adjustment::GammaCorrection { + gamma: gamma.into_element(), + inverse: inverse.into_element(), + }, + ) } /// The red, green, blue, and alpha channels of an image, split into separate node outputs. @@ -155,104 +86,8 @@ fn image_to_channels(_: impl Ctx, image: Item>) -> ImageChannels { } #[node_macro::node(category("Raster: Adjustment"), icon("NodeMakeOpaque"))] -fn make_opaque>(_: impl Ctx, #[implementations(Raster, Color, Gradient)] input: Item) -> Item { - let mut input = input; - input.element_mut().adjust(|color| color.with_alpha(1.)); - input -} - -/// Remaps a gamma-space channel through the stages of a Levels adjustment: the input range, the midtones gamma, and the output range. -fn apply_levels(value: f32, input_shadows: f32, input_highlights: f32, inverse_gamma: f32, output_minimum: f32, output_maximum: f32) -> f32 { - let highlights_minus_shadows = (input_highlights - input_shadows).clamp(f32::EPSILON, 1.); - let value = ((value - input_shadows).max(0.) / highlights_minus_shadows).min(1.); - let value = value.powf(inverse_gamma); - - value * (output_maximum - output_minimum) + output_minimum -} - -/// The classic Brightness/Contrast algorithm: a Levels remap around the pivot, adding the brightness before a positive -/// contrast stretch and after a negative contrast squeeze. -fn brightness_contrast_classic(value: f32, brightness: f32, contrast: f32, pivot: f32) -> f32 { - // Full contrast is a hard step, sending values at the pivot or above to white (with half a 16-bit step of slack for float ties) - if contrast >= 1. { - return if value + brightness >= pivot - 1. / 65536. { 1. } else { 0. }; - } - - let result = if contrast > 0. { - let input_shadows = pivot * contrast - brightness; - apply_levels(value, input_shadows, input_shadows + 1. - contrast, 1., 0., 1.) - } else { - let output_minimum = brightness - pivot * contrast; - apply_levels(value, 0., 1., 1., output_minimum, output_minimum + 1. + contrast) - }; - - result.clamp(0., 1.) -} - -/// One brightness curve of the current algorithm, for a magnitude in 0..100: a line of slope 2^(b/110) up to an output of 0.5, -/// continued by a cubic Hermite segment that eases into (1, 1). -struct BrightnessCurve { - slope: f32, - knee: f32, - end_slope: f32, -} - -impl BrightnessCurve { - fn new(brightness: f32) -> Self { - let slope = 2_f32.powf(brightness / 110.); - let knee = 0.5 / slope; - let end_slope = (1. / (1. + 12. * (slope - 1.))).max(0.1); - - Self { slope, knee, end_slope } - } - - /// Evaluates the Hermite segment at its parameter t in 0..1, returning the value and its derivative with respect to x. - fn hermite(&self, t: f32) -> (f32, f32) { - let length = 1. - self.knee; - let start_tangent = length * self.slope; - let end_tangent = length * self.end_slope; - let t2 = t * t; - let t3 = t2 * t; - - let value = (2. * t3 - 3. * t2 + 1.) * 0.5 + (t3 - 2. * t2 + t) * start_tangent + (-2. * t3 + 3. * t2) + (t3 - t2) * end_tangent; - let derivative = ((6. * t2 - 6. * t) * 0.5 + (3. * t2 - 4. * t + 1.) * start_tangent + (-6. * t2 + 6. * t) + (3. * t2 - 2. * t) * end_tangent) / length; - - (value, derivative) - } - - fn forward(&self, x: f32) -> f32 { - if x < self.knee { - return self.slope * x; - } - - let t = ((x - self.knee) / (1. - self.knee)).min(1.); - self.hermite(t).0.min(1.) - } - - /// Inverts the curve, solving the monotone Hermite segment with a bracketed Newton iteration. - fn inverse(&self, y: f32) -> f32 { - if y <= 0.5 { - return y / self.slope; - } - - let mut low = 0.; - let mut high = 1.; - let mut t = (y - 0.5) * 2.; - for _ in 0..8 { - let (value, derivative) = self.hermite(t); - let error = value - y; - if error > 0. { - high = t; - } else { - low = t; - } - - let step = t - error / (derivative * (1. - self.knee)); - t = if step >= low && step <= high { step } else { (low + high) * 0.5 }; - } - - self.knee + t * (1. - self.knee) - } +fn make_opaque(_: impl Ctx, #[implementations(Raster, Color, Gradient)] input: Item) -> Item { + adjust(input, Adjustment::MakeOpaque) } // Aims for interoperable compatibility with: @@ -264,7 +99,7 @@ impl BrightnessCurve { // // TODO: A Lab-only mode once Graphite supports the CIE Lab color space. #[node_macro::node(name("Brightness/Contrast"), category("Raster: Adjustment"), icon("NodeBrightnessContrast"), inspector("brightness_contrast_inspector"))] -fn brightness_contrast>( +fn brightness_contrast( _: impl Ctx, #[implementations(Raster, Color, Gradient)] input: Item, #[unit("%")] @@ -281,46 +116,20 @@ fn brightness_contrast>( #[default(127.)] classic_pivot: Item, ) -> Item { - let mut input = input; - let use_classic = use_classic.into_element(); - let classic_pivot = (classic_pivot.into_element() / 255.) as f32; - - // Each algorithm has its own slider range, matched here and in the Inspector - let (brightness_extent, contrast_minimum) = if use_classic { (100., -100.) } else { (150., -50.) }; - let brightness = (brightness.into_element() as f32).clamp(-brightness_extent, brightness_extent); - let contrast = (contrast.into_element() as f32).clamp(contrast_minimum, 100.) / 100.; - - // Beyond a magnitude of 100, the curve for 100 is applied first and the curve for the remainder after it - let magnitude = brightness.abs(); - let first_curve = BrightnessCurve::new(magnitude.min(100.)); - let second_curve = BrightnessCurve::new((magnitude - 100.).max(0.)); - - input.element_mut().adjust(|color| { - color.map_gamma_rgb(|c| { - if use_classic { - return brightness_contrast_classic(c, brightness / 255., contrast, classic_pivot); - } - - // Negative brightness runs the same curves in reverse - let brightened = if brightness >= 0. { - second_curve.forward(first_curve.forward(c)) - } else { - first_curve.inverse(second_curve.inverse(c)) - }; - - // Contrast pushes away from (or pulls toward) the midpoint, most strongly at the quarter tones - let contrasted = brightened + 0.76 * contrast * (2. * brightened - 1.) * brightened.min(1. - brightened); - contrasted.clamp(0., 1.) - }) - }); - - input + adjust( + input, + Adjustment::BrightnessContrast { + brightness: brightness.into_element(), + contrast: contrast.into_element(), + use_classic: use_classic.into_element(), + classic_pivot: classic_pivot.into_element(), + }, + ) } -#[repr(u32)] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType)] #[widget(Dropdown)] /// The channel whose settings are shown, with RGB adjusting all three color channels together. pub enum AdjustmentChannel { @@ -333,97 +142,13 @@ pub enum AdjustmentChannel { Alpha, } -/// One Levels record in the node's units: percentage input and output points and the gamma value. -#[derive(Clone, Copy)] -struct LevelsRecord { - shadows: f32, - midtones: f32, - highlights: f32, - output_minimums: f32, - output_maximums: f32, -} - -/// A record's input curve followed by its output range. -#[derive(Clone, Copy)] -struct LevelsStage { - curve: LevelsCurve, - output_minimum: f32, - output_maximum: f32, -} - -impl LevelsRecord { - fn new(shadows: f32, midtones: f32, highlights: f32, output_minimums: f32, output_maximums: f32) -> Self { - Self { - shadows, - midtones, - highlights, - output_minimums, - output_maximums, - } - } - - fn stage(&self, gamma: f32) -> LevelsStage { - LevelsStage { - curve: LevelsCurve::from_points(self.shadows * 2.55, self.highlights * 2.55, gamma), - output_minimum: self.output_minimums / 100., - output_maximum: self.output_maximums / 100., - } - } -} - -impl LevelsStage { - fn apply(&self, value: f32) -> f32 { - self.curve.apply(value) * (self.output_maximum - self.output_minimum) + self.output_minimum - } -} - -/// A channel's record followed by the composite record. -#[derive(Clone, Copy)] -struct LevelsChain { - first: LevelsStage, - second: LevelsStage, - two_stages: bool, -} - -impl LevelsChain { - fn new(channel: LevelsRecord, composite: LevelsRecord) -> Self { - // For PSD interop, two power functions with nothing between them (the composite's input points and the - // channel's output range at their defaults) merge into one curve with the product of the gammas, toe included - let nothing_between = composite.shadows == 0. && composite.highlights == 100. && channel.output_minimums == 0. && channel.output_maximums == 100.; - if nothing_between { - let merged = LevelsRecord { - output_minimums: composite.output_minimums, - output_maximums: composite.output_maximums, - ..channel - }; - let stage = merged.stage(channel.midtones * composite.midtones); - Self { - first: stage, - second: stage, - two_stages: false, - } - } else { - Self { - first: channel.stage(channel.midtones), - second: composite.stage(composite.midtones), - two_stages: true, - } - } - } - - fn apply(&self, value: f32) -> f32 { - let value = self.first.apply(value); - if self.two_stages { self.second.apply(value) } else { value } - } -} - // Aims for interoperable compatibility with: // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=levl%27%20%3D%20Levels // // Some further analysis available at: // https://geraldbakker.nl/psnumbers/levels.html #[node_macro::node(category("Raster: Adjustment"), icon("NodeLevels"), inspector("levels_inspector"))] -fn levels>( +fn levels( _: impl Ctx, #[implementations(Raster, Color, Gradient)] image: Item, #[unit("%")] @@ -568,62 +293,22 @@ fn levels>( alpha_output_maximums: Item, _channel: Item, ) -> Item { - let mut image = image; - let composite = LevelsRecord::new( - shadows.into_element() as f32, - midtones.into_element() as f32, - highlights.into_element() as f32, - output_minimums.into_element() as f32, - output_maximums.into_element() as f32, - ); - let red = LevelsChain::new( - LevelsRecord::new( - red_shadows.into_element() as f32, - red_midtones.into_element() as f32, - red_highlights.into_element() as f32, - red_output_minimums.into_element() as f32, - red_output_maximums.into_element() as f32, - ), - composite, - ); - let green = LevelsChain::new( - LevelsRecord::new( - green_shadows.into_element() as f32, - green_midtones.into_element() as f32, - green_highlights.into_element() as f32, - green_output_minimums.into_element() as f32, - green_output_maximums.into_element() as f32, - ), - composite, - ); - let blue = LevelsChain::new( - LevelsRecord::new( - blue_shadows.into_element() as f32, - blue_midtones.into_element() as f32, - blue_highlights.into_element() as f32, - blue_output_minimums.into_element() as f32, - blue_output_maximums.into_element() as f32, - ), - composite, - ); - - // Alpha stands apart from the composite record that the three color channels pass through - let alpha = LevelsRecord::new( - alpha_shadows.into_element() as f32, - alpha_midtones.into_element() as f32, - alpha_highlights.into_element() as f32, - alpha_output_minimums.into_element() as f32, - alpha_output_maximums.into_element() as f32, - ); - let alpha = alpha.stage(alpha.midtones); - - image.element_mut().adjust(|color| { - // Levels math operates in gamma space - let [r, g, b, a] = color.to_gamma_srgb_channels(); - - Color::from_gamma_srgb_channels(red.apply(r), green.apply(g), blue.apply(b), alpha.apply(a)) - }); - image + let record = |shadows: Item, midtones: Item, highlights: Item, output_minimums: Item, output_maximums: Item| LevelsRecord { + shadows: shadows.into_element(), + midtones: midtones.into_element(), + highlights: highlights.into_element(), + output_minimums: output_minimums.into_element(), + output_maximums: output_maximums.into_element(), + }; + let settings = LevelsSettings { + composite: record(shadows, midtones, highlights, output_minimums, output_maximums), + red: record(red_shadows, red_midtones, red_highlights, red_output_minimums, red_output_maximums), + green: record(green_shadows, green_midtones, green_highlights, green_output_minimums, green_output_maximums), + blue: record(blue_shadows, blue_midtones, blue_highlights, blue_output_minimums, blue_output_maximums), + alpha: record(alpha_shadows, alpha_midtones, alpha_highlights, alpha_output_minimums, alpha_output_maximums), + }; + + adjust(image, Adjustment::Levels(Box::new(settings))) } // Aims for interoperable compatibility with: @@ -634,7 +319,7 @@ fn levels>( // points, and the per-channel curves apply before the composite one, like Levels. The value between those two stages // stays exact rather than rounding through an 8-bit table, which can leave results a level away from 8-bit pipelines. #[node_macro::node(category("Raster: Adjustment"), icon("NodeCurves"), inspector("transfer_curves_inspector"))] -fn curves + Send>( +fn curves( _: impl Ctx, #[implementations(Raster, Color, Gradient)] image: Item, curve: Item, @@ -644,25 +329,15 @@ fn curves + Send>( #[name("(Alpha) Curve")] alpha_curve: Item, _channel: Item, ) -> Item { - let mut image = image; - let composite = curve.into_element().evaluator(); - let red = red_curve.into_element().evaluator(); - let green = green_curve.into_element().evaluator(); - let blue = blue_curve.into_element().evaluator(); - let alpha = alpha_curve.into_element().evaluator(); - let map = |channel: &TransferCurveEvaluator, value: f32| composite.evaluate(channel.evaluate(value as f64).clamp(0., 1.)).clamp(0., 1.) as f32; - - image.element_mut().adjust(|color| { - // Curves math operates in gamma space - let [r, g, b, a] = color.to_gamma_srgb_channels(); - - // Alpha stands apart from the composite curve that the three color channels pass through - let a = alpha.evaluate(a as f64).clamp(0., 1.) as f32; - - Color::from_gamma_srgb_channels(map(&red, r), map(&green, g), map(&blue, b), a) - }); + let settings = CurvesSettings { + composite: curve.into_element(), + red: red_curve.into_element(), + green: green_curve.into_element(), + blue: blue_curve.into_element(), + alpha: alpha_curve.into_element(), + }; - image + adjust(image, Adjustment::Curves(Box::new(settings))) } #[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] @@ -691,7 +366,7 @@ fn points_to_transfer_curve( // https://stackoverflow.com/a/55233732/775283 // Works the same for gamma and linear color #[node_macro::node(name("Black & White"), category("Raster: Adjustment"), icon("NodeBlackAndWhite"), inspector("black_and_white_inspector"))] -fn black_and_white>( +fn black_and_white( _: impl Ctx, #[implementations(Raster, Color, Gradient)] image: Item, use_tint: Item, @@ -727,63 +402,23 @@ fn black_and_white>( #[soft(-200..300)] magentas: Item, ) -> Item { - let mut image = image; - let tint = tint.into_element(); - let use_tint = use_tint.into_element(); - let reds = reds.into_element(); - let yellows = yellows.into_element(); - let greens = greens.into_element(); - let cyans = cyans.into_element(); - let blues = blues.into_element(); - let magentas = magentas.into_element(); - - image.element_mut().adjust(|color| { - // Black & White channel weights are tuned for gamma-space values - let [r, g, b, alpha_part] = color.to_gamma_srgb_channels(); - - let reds = (reds / 100.) as f32; - let yellows = (yellows / 100.) as f32; - let greens = (greens / 100.) as f32; - let cyans = (cyans / 100.) as f32; - let blues = (blues / 100.) as f32; - let magentas = (magentas / 100.) as f32; - - let gray_base = r.min(g).min(b); - - let red_part = r - gray_base; - let green_part = g - gray_base; - let blue_part = b - gray_base; - - let additional = if red_part == 0. { - let cyan_part = green_part.min(blue_part); - cyan_part * cyans + (green_part - cyan_part) * greens + (blue_part - cyan_part) * blues - } else if green_part == 0. { - let magenta_part = red_part.min(blue_part); - magenta_part * magentas + (red_part - magenta_part) * reds + (blue_part - magenta_part) * blues - } else { - let yellow_part = red_part.min(green_part); - yellow_part * yellows + (red_part - yellow_part) * reds + (green_part - yellow_part) * greens - }; - - let luminance = (gray_base + additional).clamp(0., 1.); - if !use_tint { - return Color::from_gamma_srgb_channels(luminance, luminance, luminance, alpha_part); - } - - // The tint takes on the gray's luminosity the way the Luminosity blend mode would - let [tint_r, tint_g, tint_b, _] = tint.to_gamma_srgb_channels(); - let tint_luma = luma_rec_601_fixed_point(tint_r, tint_g, tint_b); - let [tinted_r, tinted_g, tinted_b] = set_luminosity(tint_r, tint_g, tint_b, tint_luma, luminance); + let settings = BlackAndWhiteSettings { + use_tint: use_tint.into_element(), + tint: tint.into_element(), + reds: reds.into_element(), + yellows: yellows.into_element(), + greens: greens.into_element(), + cyans: cyans.into_element(), + blues: blues.into_element(), + magentas: magentas.into_element(), + }; - Color::from_gamma_srgb_channels(tinted_r, tinted_g, tinted_b, alpha_part) - }); - image + adjust(image, Adjustment::BlackAndWhite(settings)) } -#[repr(u32)] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType)] #[widget(Dropdown)] pub enum HueSaturationRange { #[default] @@ -796,182 +431,13 @@ pub enum HueSaturationRange { Magentas, } -/// HSL of gamma-encoded channels: hue in degrees, saturation and lightness in 0..1. -fn gamma_rgb_to_hsl(r: f32, g: f32, b: f32) -> [f32; 3] { - let maximum = r.max(g).max(b); - let minimum = r.min(g).min(b); - let chroma = maximum - minimum; - let lightness = (maximum + minimum) / 2.; - if chroma <= 0. { - return [0., 0., lightness]; - } - - let saturation = chroma / (1. - (2. * lightness - 1.).abs()).max(1e-6); - [hexagon_hue_degrees(r, g, b), saturation.min(1.), lightness] -} - -/// Hexagon hue in degrees of three channels in any encoding, 0 for gray. -fn hexagon_hue_degrees(r: f32, g: f32, b: f32) -> f32 { - let maximum = r.max(g).max(b); - let chroma = maximum - r.min(g).min(b); - if chroma <= 0. { - return 0.; - } - - let sector = if maximum == r { - wrap_positive((g - b) / chroma, 6.) - } else if maximum == g { - (b - r) / chroma + 2. - } else { - (r - g) / chroma + 4. - }; - sector * 60. -} - -/// `value` wrapped into the range from 0 to `modulus`. -fn wrap_positive(value: f32, modulus: f32) -> f32 { - value - (value / modulus).floor() * modulus -} - -/// Gamma-encoded channels from a hue in degrees and saturation and lightness in 0..1. -fn hsl_to_gamma_rgb(hue: f32, saturation: f32, lightness: f32) -> [f32; 3] { - let chroma = (1. - (2. * lightness - 1.).abs()) * saturation; - let sector = wrap_positive(hue, 360.) / 60.; - let x = chroma * (1. - (wrap_positive(sector, 2.) - 1.).abs()); - let (r, g, b) = if sector < 1. { - (chroma, x, 0.) - } else if sector < 2. { - (x, chroma, 0.) - } else if sector < 3. { - (0., chroma, x) - } else if sector < 4. { - (0., x, chroma) - } else if sector < 5. { - (x, 0., chroma) - } else { - (chroma, 0., x) - }; - let m = lightness - chroma / 2.; - - [(r + m).clamp(0., 1.), (g + m).clamp(0., 1.), (b + m).clamp(0., 1.)] -} - -/// One set of Hue/Saturation sliders: a hue shift in degrees and saturation and lightness amounts in -1..1. -#[derive(Clone, Copy)] -struct HueSaturationSettings { - hue: f32, - saturation: f32, - lightness: f32, -} - -impl HueSaturationSettings { - fn new(hue: f32, saturation_percent: f32, lightness_percent: f32) -> Self { - Self { - hue, - saturation: saturation_percent / 100., - lightness: lightness_percent / 100., - } - } -} - -/// A hue range with its falloff: full weight from `range_start` to `range_end`, fading linearly to zero at the falloff ends. -#[derive(Clone, Copy)] -struct HueSaturationRangeSettings { - falloff_start: f32, - range_start: f32, - range_end: f32, - falloff_end: f32, - settings: HueSaturationSettings, -} - -impl HueSaturationRangeSettings { - fn new(falloff_start: f32, range_start: f32, range_end: f32, falloff_end: f32, settings: HueSaturationSettings) -> Self { - // For PSD interop, each edge rounds to 1536 hue units per turn over 359 rather than 360 degrees, landing up to a degree late - let edge = |degrees: f32| (degrees * 1536. / 359.).round() * 360. / 1536.; - - Self { - falloff_start: edge(falloff_start), - range_start: edge(range_start), - range_end: edge(range_end), - falloff_end: edge(falloff_end), - settings, - } - } - - fn weight(&self, hue: f32) -> f32 { - let distance = |from: f32, to: f32| wrap_positive(to - from, 360.); - if distance(self.range_start, hue) <= distance(self.range_start, self.range_end) { - return 1.; - } - let start_falloff = distance(self.falloff_start, self.range_start); - let end_falloff = distance(self.range_end, self.falloff_end); - if distance(self.falloff_start, hue) < start_falloff { - return distance(self.falloff_start, hue) / start_falloff; - } - if distance(self.range_end, hue) < end_falloff { - return 1. - distance(self.range_end, hue) / end_falloff; - } - 0. - } -} - -/// The six ranges' combined effect on one pixel, gathered before the master sliders apply. -struct HueSaturationRangeEffect { - hue_shift: f32, - saturation_factor: f32, - fully_saturate: bool, - rgb: [f32; 3], -} - -impl HueSaturationRangeEffect { - fn apply(&mut self, range: &HueSaturationRangeSettings, original_hue: f32, original_saturation: f32) { - // Range weights come from the original hue, and grays belong to no range - let weight = if original_saturation > 0. { range.weight(original_hue) } else { 0. }; - if weight <= 0. { - return; - } - - self.hue_shift += range.settings.hue * weight; - // For PSD interop, +100 saturates fully from the very edge of the falloff rather than scaling with the weight - if range.settings.saturation >= 1. { - self.fully_saturate = true; - } else { - self.saturation_factor *= 1. + (saturation_gain(range.settings.saturation) - 1.) * weight; - } - self.rgb = lightness_toward_max_or_min(self.rgb, range.settings.lightness * weight); - } -} - -/// The factor a saturation amount in -1..1 applies to HSL saturation, quantized for PSD interop: 1 - trunc(256 a) / 256 below zero and floor(65280 / (255 - trunc(254 a))) / 256 above. -fn saturation_gain(amount: f32) -> f32 { - if amount < 0. { - 1. - (-amount * 256.).trunc() / 256. - } else { - (65280. / (255. - (amount * 254.).trunc())).floor() / 256. - } -} - -/// Blends toward white for a positive amount and toward black for a negative one, as the master lightness slider does. -fn lightness_toward_white_or_black(value: f32, amount: f32) -> f32 { - if amount >= 0. { value + (1. - value) * amount } else { value * (1. + amount) } -} - -/// A range's lightness moves the channels toward the color's own maximum (positive) or minimum (negative) instead. -fn lightness_toward_max_or_min(rgb: [f32; 3], amount: f32) -> [f32; 3] { - let maximum = rgb[0].max(rgb[1]).max(rgb[2]); - let minimum = rgb[0].min(rgb[1]).min(rgb[2]); - let toward = if amount >= 0. { maximum } else { minimum }; - let blend = |value: f32| value + (toward - value) * amount.abs(); - [blend(rgb[0]), blend(rgb[1]), blend(rgb[2])] -} - // Aims for interoperable compatibility with: // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27hue%20%27%20%3D%20Old,saturation%2C%20Photoshop%205.0 // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=0%20%3D%20Use%20other.-,Hue/Saturation,-Hue/Saturation%20settings // // TODO: Residuals in 8-bit PSD interop: the byte-hue colorize table, the colorize lightness slider (up to 2.5 levels), and the range edges (a few tenths of a degree) #[node_macro::node(name("Hue/Saturation"), category("Raster: Adjustment"), icon("NodeHueSaturation"), inspector("hue_saturation_inspector"))] -fn hue_saturation>( +fn hue_saturation( _: impl Ctx, #[implementations(Raster, Color, Gradient)] input: Item, #[unit("°")] @@ -1241,125 +707,80 @@ fn hue_saturation>( magentas_falloff_end: Item, _range: Item, ) -> Item { - let mut input = input; - let master = HueSaturationSettings::new(hue.into_element() as f32, saturation.into_element() as f32, lightness.into_element() as f32); - let colorize = colorize.into_element(); - let colorize_settings = HueSaturationSettings::new(colorize_hue.into_element() as f32, colorize_saturation.into_element() as f32, colorize_lightness.into_element() as f32); - let (reds, yellows, greens, cyans, blues, magentas) = ( - HueSaturationRangeSettings::new( - reds_falloff_start.into_element() as f32, - reds_range_start.into_element() as f32, - reds_range_end.into_element() as f32, - reds_falloff_end.into_element() as f32, - HueSaturationSettings::new(reds_hue.into_element() as f32, reds_saturation.into_element() as f32, reds_lightness.into_element() as f32), + let sliders = |hue: Item, saturation: Item, lightness: Item| HueSaturationSliders { + hue: hue.into_element(), + saturation: saturation.into_element(), + lightness: lightness.into_element(), + }; + let range = |sliders: HueSaturationSliders, falloff_start: Item, range_start: Item, range_end: Item, falloff_end: Item| HueRangeSettings { + sliders, + falloff_start: falloff_start.into_element(), + range_start: range_start.into_element(), + range_end: range_end.into_element(), + falloff_end: falloff_end.into_element(), + }; + let settings = HueSaturationSettings { + master: sliders(hue, saturation, lightness), + colorize: colorize.into_element(), + colorize_sliders: sliders(colorize_hue, colorize_saturation, colorize_lightness), + reds: range( + sliders(reds_hue, reds_saturation, reds_lightness), + reds_falloff_start, + reds_range_start, + reds_range_end, + reds_falloff_end, ), - HueSaturationRangeSettings::new( - yellows_falloff_start.into_element() as f32, - yellows_range_start.into_element() as f32, - yellows_range_end.into_element() as f32, - yellows_falloff_end.into_element() as f32, - HueSaturationSettings::new(yellows_hue.into_element() as f32, yellows_saturation.into_element() as f32, yellows_lightness.into_element() as f32), + yellows: range( + sliders(yellows_hue, yellows_saturation, yellows_lightness), + yellows_falloff_start, + yellows_range_start, + yellows_range_end, + yellows_falloff_end, ), - HueSaturationRangeSettings::new( - greens_falloff_start.into_element() as f32, - greens_range_start.into_element() as f32, - greens_range_end.into_element() as f32, - greens_falloff_end.into_element() as f32, - HueSaturationSettings::new(greens_hue.into_element() as f32, greens_saturation.into_element() as f32, greens_lightness.into_element() as f32), + greens: range( + sliders(greens_hue, greens_saturation, greens_lightness), + greens_falloff_start, + greens_range_start, + greens_range_end, + greens_falloff_end, ), - HueSaturationRangeSettings::new( - cyans_falloff_start.into_element() as f32, - cyans_range_start.into_element() as f32, - cyans_range_end.into_element() as f32, - cyans_falloff_end.into_element() as f32, - HueSaturationSettings::new(cyans_hue.into_element() as f32, cyans_saturation.into_element() as f32, cyans_lightness.into_element() as f32), + cyans: range( + sliders(cyans_hue, cyans_saturation, cyans_lightness), + cyans_falloff_start, + cyans_range_start, + cyans_range_end, + cyans_falloff_end, ), - HueSaturationRangeSettings::new( - blues_falloff_start.into_element() as f32, - blues_range_start.into_element() as f32, - blues_range_end.into_element() as f32, - blues_falloff_end.into_element() as f32, - HueSaturationSettings::new(blues_hue.into_element() as f32, blues_saturation.into_element() as f32, blues_lightness.into_element() as f32), + blues: range( + sliders(blues_hue, blues_saturation, blues_lightness), + blues_falloff_start, + blues_range_start, + blues_range_end, + blues_falloff_end, ), - HueSaturationRangeSettings::new( - magentas_falloff_start.into_element() as f32, - magentas_range_start.into_element() as f32, - magentas_range_end.into_element() as f32, - magentas_falloff_end.into_element() as f32, - HueSaturationSettings::new(magentas_hue.into_element() as f32, magentas_saturation.into_element() as f32, magentas_lightness.into_element() as f32), + magentas: range( + sliders(magentas_hue, magentas_saturation, magentas_lightness), + magentas_falloff_start, + magentas_range_start, + magentas_range_end, + magentas_falloff_end, ), - ); - - input.element_mut().adjust(|color| { - let [r, g, b, alpha] = color.to_gamma_srgb_channels(); - - if colorize { - let [_, _, lightness] = gamma_rgb_to_hsl(r, g, b); - let lightness = lightness_toward_white_or_black(lightness, colorize_settings.lightness); - let [r, g, b] = hsl_to_gamma_rgb(colorize_settings.hue, colorize_settings.saturation, lightness); - return Color::from_gamma_srgb_channels(r, g, b, alpha); - } - - // Each range weights its sliders by its falloff around the original hue: hue shifts add and saturation gains multiply - let [original_hue, original_saturation, _] = gamma_rgb_to_hsl(r, g, b); - let mut effect = HueSaturationRangeEffect { - hue_shift: master.hue, - saturation_factor: 1., - fully_saturate: false, - rgb: [r, g, b], - }; - effect.apply(&reds, original_hue, original_saturation); - effect.apply(&yellows, original_hue, original_saturation); - effect.apply(&greens, original_hue, original_saturation); - effect.apply(&cyans, original_hue, original_saturation); - effect.apply(&blues, original_hue, original_saturation); - effect.apply(&magentas, original_hue, original_saturation); - let HueSaturationRangeEffect { - hue_shift, - mut saturation_factor, - mut fully_saturate, - rgb, - } = effect; - if master.saturation >= 1. { - fully_saturate = true; - } else { - saturation_factor *= saturation_gain(master.saturation); - } - - // The master lightness blends toward white or black before the hue and saturation, which work in HSL of the gamma channels - let rgb = [ - lightness_toward_white_or_black(rgb[0], master.lightness), - lightness_toward_white_or_black(rgb[1], master.lightness), - lightness_toward_white_or_black(rgb[2], master.lightness), - ]; - let [hue, saturation, lightness] = gamma_rgb_to_hsl(rgb[0], rgb[1], rgb[2]); - let saturation = if saturation <= 0. { - 0. - } else if fully_saturate { - 1. - } else { - (saturation * saturation_factor).min(1.) - }; - let [r, g, b] = hsl_to_gamma_rgb(hue + hue_shift, saturation, lightness); + }; - Color::from_gamma_srgb_channels(r, g, b, alpha) - }); - input + adjust(input, Adjustment::HueSaturation(Box::new(settings))) } // Aims for interoperable compatibility with: // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27%20%3D%20Color%20Lookup-,%27nvrt%27%20%3D%20Invert,-%27post%27%20%3D%20Posterize #[node_macro::node(category("Raster: Adjustment"), icon("NodeInvert"))] -fn invert>(_: impl Ctx, #[implementations(Raster, Color, Gradient)] input: Item) -> Item { - let mut input = input; - input.element_mut().adjust(|color| color.map_gamma_rgb(|channel| 1. - channel)); - input +fn invert(_: impl Ctx, #[implementations(Raster, Color, Gradient)] input: Item) -> Item { + adjust(input, Adjustment::Invert) } // Aims for interoperable compatibility with: // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=post%27%20%3D%20Posterize-,%27thrs%27%20%3D%20Threshold,-%27grdm%27%20%3D%20Gradient #[node_macro::node(category("Raster: Adjustment"), icon("NodeThreshold"), inspector("threshold_inspector"))] -fn threshold>( +fn threshold( _: impl Ctx, #[implementations(Raster, Color, Gradient)] image: Item, #[unit("%")] @@ -1373,19 +794,13 @@ fn threshold>( #[default(100.)] max_luminance: Item, ) -> Item { - let mut image = image; - let min_luminance = (min_luminance.into_element() / 100.) as f32; - let max_luminance = (max_luminance.into_element() / 100.) as f32; - - image.element_mut().adjust(|color| { - // For PSD interop, we compare this 14-bit fixed-point Rec. 601 luma against the level unrounded - let [r, g, b, _] = color.to_gamma_srgb_channels(); - let luminance = (4915. * r + 9667. * g + 1802. * b) / 16384.; - - let output = if luminance >= min_luminance && luminance <= max_luminance { Color::WHITE } else { Color::BLACK }; - output.with_alpha(color.a()) - }); - image + adjust( + image, + Adjustment::Threshold { + min_luminance: min_luminance.into_element(), + max_luminance: max_luminance.into_element(), + }, + ) } // Aims for interoperable compatibility with: @@ -1402,35 +817,26 @@ fn threshold>( // TODO: `(c[i + 1] - c[i - 1]) / 2`, the end stops repeated past the ends, so two stops give `0.5 p + 1.5 p^2 - p^3`. // TODO: - The ramp is `(1 - s) * linear + s * smooth` for smoothness s, clamped per interval to its two stop colors. #[node_macro::node(category("Raster: Adjustment"), icon("NodeGradientMap"))] -fn gradient_map + Send>( +fn gradient_map( _: impl Ctx, #[implementations(Raster, Color, Gradient)] image: Item, #[default(Color::BLACK, Color::WHITE)] gradient: Item, reverse: Item, ) -> Item { - let mut image = image; - let settings = vector_types::GradientSettings::from(&gradient); - let evaluator = gradient.into_element().evaluator(settings); - let reverse = reverse.into_element(); - - image.element_mut().adjust(|color| { - // The classic 0.3/0.59/0.11 luma of the gamma-encoded channels picks the position along the gradient - let [r, g, b, alpha] = color.to_gamma_srgb_channels(); - let intensity = 0.3 * r + 0.59 * g + 0.11 * b; - let intensity = if reverse { 1. - intensity } else { intensity }; - - // The source alpha is kept and the gradient's own alpha stops are ignored - evaluator.evaluate(intensity as f64).with_alpha(alpha) - }); - - image + adjust( + image, + Adjustment::GradientMap { + gradient, + reverse: reverse.into_element(), + }, + ) } // Aims for interoperable compatibility with: // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27-,vibA%27%20%3D%20Vibrance,-%27hue%20%27%20%3D%20Old // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=Vibrance%20(Photoshop%20CS3) #[node_macro::node(category("Raster: Adjustment"), icon("NodeVibrance"), inspector("vibrance_inspector"))] -fn vibrance>( +fn vibrance( _: impl Ctx, #[implementations(Raster, Color, Gradient)] image: Item, #[unit("%")] @@ -1442,78 +848,18 @@ fn vibrance>( #[hard(-100..100)] saturation: Item, ) -> Item { - let mut image = image; - let vibrance = (vibrance.into_element() / 100.) as f32; - let saturation_scale = (1. + saturation.into_element() / 100.) as f32; - - // Vibrance then saturation, both in linear light, which equals applying each alone in turn - image.element_mut().adjust(|color| { - let (r, g, b) = (color.r(), color.g(), color.b()); - let maximum = r.max(g).max(b); - let [chroma_factor, brightness_factor] = vibrance_factors(r, g, b, vibrance); - let after_vibrance = Color::from_rgbaf32_unchecked( - scale_about_maximum(r, maximum, chroma_factor, brightness_factor), - scale_about_maximum(g, maximum, chroma_factor, brightness_factor), - scale_about_maximum(b, maximum, chroma_factor, brightness_factor), - color.a(), - ); - - // For PSD interop, saturation scales each channel's distance from a gray weighted by ProPhoto's luminance coefficients - let gray = 0.288040 * after_vibrance.r() + 0.711874 * after_vibrance.g() + 0.000086 * after_vibrance.b(); - after_vibrance.map_rgb(|c| (gray + (c - gray) * saturation_scale).clamp(0., 1.)) - }); - image -} - -fn scale_about_maximum(channel: f32, maximum: f32, chroma_factor: f32, brightness_factor: f32) -> f32 { - (brightness_factor * (maximum + chroma_factor * (channel - maximum))).clamp(0., 1.) + adjust( + image, + Adjustment::Vibrance { + vibrance: vibrance.into_element(), + saturation: saturation.into_element(), + }, + ) } -/// Share of the vibrance boost the skin-tone protection removes at full weight, a fitted constant. -const VIBRANCE_PROTECTION_LOSS: f32 = 0.4857; - -/// Vibrance on linear SDR channels as `[chroma factor about the max, brightness multiply]` for an amount in -1..1, both fading out toward black. -/// Negative desaturates and darkens low-chroma colors most. Positive boosts them, brightens a little, and spares reds. -fn vibrance_factors(r: f32, g: f32, b: f32, amount: f32) -> [f32; 2] { - let maximum = r.max(g).max(b); - let minimum = r.min(g).min(b); - if maximum <= 0. { - return [1., 1.]; - } - let ratio = minimum / maximum; - let saturation = 1. - ratio; - let q = ratio * saturation; - let toe = 1. - (16. * maximum).min(1.); - let rolloff = 1. - toe * toe; - let brightness = (2. * q - q * q) * (1. - maximum) * rolloff; - - if amount < 0. { - let amount = -amount; - let chroma_factor = (1. - amount / 4.) * (1. - amount * (1. - rolloff * saturation * (1. + saturation) / 2.)); - return [chroma_factor, 1. - amount * brightness]; - } - - let protection = skin_tone_window(hexagon_hue_degrees(r, g, b)) * (1. - saturation * saturation); - let amount = amount * (1. - protection * (1. - amount)); - let boost = (5. / 6.) * (1. - VIBRANCE_PROTECTION_LOSS * protection) * amount * ratio * (1. - minimum) * rolloff; - [1. / (1. - boost), 1. + amount * brightness / 4.] -} - -/// How fully a hue falls under the skin-tone protection: all of it from red to 30 degrees, fading out by 45, and back in from 300. -fn skin_tone_window(hue: f32) -> f32 { - if hue < 45. { - ((45. - hue) / 15.).min(1.) - } else if hue >= 300. { - (hue - 300.) / 60. - } else { - 0. - } -} - -#[repr(u32)] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType)] #[widget(Radio)] pub enum RedGreenBlue { #[default] @@ -1533,95 +879,13 @@ pub enum RedGreenBlueAlpha { Alpha, } -/// Style of noise pattern. -#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType)] -#[widget(Dropdown)] -pub enum NoiseType { - #[default] - Perlin, - #[label("OpenSimplex2")] - OpenSimplex2, - #[label("OpenSimplex2S")] - OpenSimplex2S, - Cellular, - ValueCubic, - Value, - WhiteNoise, -} - -/// Style of layered levels of the noise pattern. -#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType)] -pub enum FractalType { - #[default] - None, - #[label("Fractional Brownian Motion")] - FBm, - Ridged, - PingPong, - #[label("Progressive (Domain Warp Only)")] - DomainWarpProgressive, - #[label("Independent (Domain Warp Only)")] - DomainWarpIndependent, -} - -/// Distance function used by the cellular noise. -#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType)] -pub enum CellularDistanceFunction { - #[default] - Euclidean, - #[label("Euclidean Squared (Faster)")] - EuclideanSq, - Manhattan, - Hybrid, -} - -#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType)] -pub enum CellularReturnType { - CellValue, - #[default] - #[label("Nearest (F1)")] - Nearest, - #[label("Next Nearest (F2)")] - NextNearest, - #[label("Average (F1 / 2 + F2 / 2)")] - Average, - #[label("Difference (F2 - F1)")] - Difference, - #[label("Product (F2 * F1 / 2)")] - Product, - #[label("Division (F1 / F2)")] - Division, -} - -#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType)] -#[widget(Dropdown)] -pub enum DomainWarpType { - #[default] - None, - #[label("OpenSimplex2")] - OpenSimplex2, - #[label("OpenSimplex2 Reduced")] - OpenSimplex2Reduced, - BasicGrid, -} - // Aims for interoperable compatibility with: // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27mixr%27%20%3D%20Channel%20Mixer // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=Lab%20color%20only-,Channel%20Mixer,-Key%20is%20%27mixr // // TODO: CMYK source channels once Graphite supports the CMYK color space. #[node_macro::node(category("Raster: Adjustment"), icon("NodeChannelMixer"), inspector("channel_mixer_inspector"))] -fn channel_mixer>( +fn channel_mixer( _: impl Ctx, #[implementations(Raster, Color, Gradient)] image: Item, @@ -1730,67 +994,26 @@ fn channel_mixer>( // Display-only parameters (not used within the node) _output_channel: Item, ) -> Item { - let mut image = image; - let monochrome = monochrome.into_element(); - let (monochrome_r, monochrome_g, monochrome_b, monochrome_c) = ( - monochrome_r.into_element() as f32, - monochrome_g.into_element() as f32, - monochrome_b.into_element() as f32, - monochrome_c.into_element() as f32, - ); - let (red_r, red_g, red_b, red_c) = (red_r.into_element() as f32, red_g.into_element() as f32, red_b.into_element() as f32, red_c.into_element() as f32); - let (green_r, green_g, green_b, green_c) = ( - green_r.into_element() as f32, - green_g.into_element() as f32, - green_b.into_element() as f32, - green_c.into_element() as f32, - ); - let (blue_r, blue_g, blue_b, blue_c) = (blue_r.into_element() as f32, blue_g.into_element() as f32, blue_b.into_element() as f32, blue_c.into_element() as f32); - - image.element_mut().adjust(|color| { - let [r, g, b, a] = color.to_gamma_srgb_channels(); - - // Weights and constants are 10-bit fixed point truncated toward zero, which PSD interop depends on - let weight = |percent: f32| (percent * 1024. / 100.).trunc() / 1024.; - - let (out_r, out_g, out_b) = if monochrome { - let (monochrome_r, monochrome_g, monochrome_b, monochrome_c) = (weight(monochrome_r), weight(monochrome_g), weight(monochrome_b), weight(monochrome_c)); - - let gray = (r * monochrome_r + g * monochrome_g + b * monochrome_b + monochrome_c).clamp(0., 1.); - - (gray, gray, gray) - } else { - let (red_r, red_g, red_b, red_c) = (weight(red_r), weight(red_g), weight(red_b), weight(red_c)); - let (green_r, green_g, green_b, green_c) = (weight(green_r), weight(green_g), weight(green_b), weight(green_c)); - let (blue_r, blue_g, blue_b, blue_c) = (weight(blue_r), weight(blue_g), weight(blue_b), weight(blue_c)); - - let red = (r * red_r + g * red_g + b * red_b + red_c).clamp(0., 1.); - let green = (r * green_r + g * green_g + b * green_b + green_c).clamp(0., 1.); - let blue = (r * blue_r + g * blue_g + b * blue_b + blue_c).clamp(0., 1.); - - (red, green, blue) - }; - - Color::from_gamma_srgb_channels(out_r, out_g, out_b, a) - }); - image -} + let row = |red: Item, green: Item, blue: Item, constant: Item| ChannelMixerRow { + red: red.into_element(), + green: green.into_element(), + blue: blue.into_element(), + constant: constant.into_element(), + }; + let settings = ChannelMixerSettings { + monochrome: monochrome.into_element(), + monochrome_mix: row(monochrome_r, monochrome_g, monochrome_b, monochrome_c), + red: row(red_r, red_g, red_b, red_c), + green: row(green_r, green_g, green_b, green_c), + blue: row(blue_r, blue_g, blue_b, blue_c), + }; -#[repr(u32)] -#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)] -#[widget(Radio)] -pub enum RelativeAbsolute { - #[default] - Relative, - Absolute, + adjust(image, Adjustment::ChannelMixer(Box::new(settings))) } -#[repr(u32)] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType)] pub enum SelectiveColorChoice { #[default] Reds, @@ -1813,7 +1036,7 @@ pub enum SelectiveColorChoice { // Algorithm based on: // https://blog.pkh.me/p/22-understanding-selective-coloring-in-adobe-photoshop.html #[node_macro::node(category("Raster: Adjustment"), icon("NodeSelectiveColor"), inspector("selective_color_inspector"))] -fn selective_color>( +fn selective_color( _: impl Ctx, #[implementations(Raster, Color, Gradient)] image: Item, @@ -2010,133 +1233,39 @@ fn selective_color>( _colors: Item, ) -> Item { - let mut image = image; - let mode = mode.into_element(); - let (r_c, r_m, r_y, r_k) = (r_c.into_element() as f32, r_m.into_element() as f32, r_y.into_element() as f32, r_k.into_element() as f32); - let (y_c, y_m, y_y, y_k) = (y_c.into_element() as f32, y_m.into_element() as f32, y_y.into_element() as f32, y_k.into_element() as f32); - let (g_c, g_m, g_y, g_k) = (g_c.into_element() as f32, g_m.into_element() as f32, g_y.into_element() as f32, g_k.into_element() as f32); - let (c_c, c_m, c_y, c_k) = (c_c.into_element() as f32, c_m.into_element() as f32, c_y.into_element() as f32, c_k.into_element() as f32); - let (b_c, b_m, b_y, b_k) = (b_c.into_element() as f32, b_m.into_element() as f32, b_y.into_element() as f32, b_k.into_element() as f32); - let (m_c, m_m, m_y, m_k) = (m_c.into_element() as f32, m_m.into_element() as f32, m_y.into_element() as f32, m_k.into_element() as f32); - let (w_c, w_m, w_y, w_k) = (w_c.into_element() as f32, w_m.into_element() as f32, w_y.into_element() as f32, w_k.into_element() as f32); - let (n_c, n_m, n_y, n_k) = (n_c.into_element() as f32, n_m.into_element() as f32, n_y.into_element() as f32, n_k.into_element() as f32); - let (k_c, k_m, k_y, k_k) = (k_c.into_element() as f32, k_m.into_element() as f32, k_y.into_element() as f32, k_k.into_element() as f32); - - image.element_mut().adjust(|color| { - let [r, g, b, a] = color.to_gamma_srgb_channels(); - - let min = |a: f32, b: f32, c: f32| a.min(b).min(c); - let max = |a: f32, b: f32, c: f32| a.max(b).max(c); - let med = |a: f32, b: f32, c: f32| a + b + c - min(a, b, c) - max(a, b, c); - - let max_channel = max(r, g, b); - let min_channel = min(r, g, b); - - let pixel_color_range = |choice| match choice { - SelectiveColorChoice::Reds => max_channel == r, - SelectiveColorChoice::Yellows => min_channel == b, - SelectiveColorChoice::Greens => max_channel == g, - SelectiveColorChoice::Cyans => min_channel == r, - SelectiveColorChoice::Blues => max_channel == b, - SelectiveColorChoice::Magentas => min_channel == g, - SelectiveColorChoice::Whites => r > 0.5 && g > 0.5 && b > 0.5, - // Every pixel, since the neutrals scale factor already vanishes at black, white, and fully saturated colors - SelectiveColorChoice::Neutrals => true, - SelectiveColorChoice::Blacks => r < 0.5 && g < 0.5 && b < 0.5, - }; - - let color_parameter_group_scale_factor_rgb = max(r, g, b) - med(r, g, b); - let color_parameter_group_scale_factor_cmy = med(r, g, b) - min(r, g, b); - - // Used to apply the r, g, or b channel slope (by multiplying it by 1) in relative mode, or no slope (by multiplying it by 0) in absolute mode - let (slope_r, slope_g, slope_b) = match mode { - RelativeAbsolute::Relative => (r - 1., g - 1., b - 1.), - RelativeAbsolute::Absolute => (-1., -1., -1.), - }; - - let array = [ - (SelectiveColorChoice::Reds, (r_c, r_m, r_y, r_k)), - (SelectiveColorChoice::Yellows, (y_c, y_m, y_y, y_k)), - (SelectiveColorChoice::Greens, (g_c, g_m, g_y, g_k)), - (SelectiveColorChoice::Cyans, (c_c, c_m, c_y, c_k)), - (SelectiveColorChoice::Blues, (b_c, b_m, b_y, b_k)), - (SelectiveColorChoice::Magentas, (m_c, m_m, m_y, m_k)), - (SelectiveColorChoice::Whites, (w_c, w_m, w_y, w_k)), - (SelectiveColorChoice::Neutrals, (n_c, n_m, n_y, n_k)), - (SelectiveColorChoice::Blacks, (k_c, k_m, k_y, k_k)), - ]; - let mut sum = Vec3::ZERO; - for &(color_parameter_group, (c, m, y, k)) in &array { - // Skip this color parameter group... - // ...if it's unchanged from the default of zero offset on all CMYK parameters, or... - // ...if this pixel's color isn't in the range affected by this color parameter group - if (c == 0. && m == 0. && y == 0. && k == 0.) || !pixel_color_range(color_parameter_group) { - continue; - } - - let color_parameter_group_scale_factor = match color_parameter_group { - SelectiveColorChoice::Reds | SelectiveColorChoice::Greens | SelectiveColorChoice::Blues => color_parameter_group_scale_factor_rgb, - SelectiveColorChoice::Cyans | SelectiveColorChoice::Magentas | SelectiveColorChoice::Yellows => color_parameter_group_scale_factor_cmy, - SelectiveColorChoice::Whites => min(r, g, b) * 2. - 1., - SelectiveColorChoice::Neutrals => 1. - ((max(r, g, b) - 0.5).abs() + (min(r, g, b) - 0.5).abs()), - SelectiveColorChoice::Blacks => 1. - max(r, g, b) * 2., - }; - - // For PSD interop, the combined percent (c + k + c k / 100) rounds half up to an integer - let ink = |color: f32| { - let percent = ((2. * (100. * (color + k) + color * k) + 100.) / 200.).floor(); - match mode { - // The multiplier is stored as one byte, 255 / b above 1 and b / 255 below, so 99% and 100% both act as 127/128 - RelativeAbsolute::Relative => { - let multiplier = 1. + percent / 100.; - if multiplier >= 1. { - 255. / (255. / multiplier).round() - 1. - } else { - (255. * multiplier).round() / 255. - 1. - } - } - RelativeAbsolute::Absolute => percent / 100., - } - }; - - let offset_r = (ink(c) * slope_r).max(-r).min(-r + 1.) * color_parameter_group_scale_factor; - let offset_g = (ink(m) * slope_g).max(-g).min(-g + 1.) * color_parameter_group_scale_factor; - let offset_b = (ink(y) * slope_b).max(-b).min(-b + 1.) * color_parameter_group_scale_factor; - - // An 8-bit PSD document sums the groups' 8-bit offsets, which this float node does not currently attempt to reproduce - sum += Vec3::new(offset_r, offset_g, offset_b); - } - - let rgb = Vec3::new(r, g, b); - let out = (sum + rgb).clamp(Vec3::ZERO, Vec3::ONE); + let inks = |cyan: Item, magenta: Item, yellow: Item, black: Item| SelectiveColorInks { + cyan: cyan.into_element(), + magenta: magenta.into_element(), + yellow: yellow.into_element(), + black: black.into_element(), + }; + let settings = SelectiveColorSettings { + mode: mode.into_element(), + reds: inks(r_c, r_m, r_y, r_k), + yellows: inks(y_c, y_m, y_y, y_k), + greens: inks(g_c, g_m, g_y, g_k), + cyans: inks(c_c, c_m, c_y, c_k), + blues: inks(b_c, b_m, b_y, b_k), + magentas: inks(m_c, m_m, m_y, m_k), + whites: inks(w_c, w_m, w_y, w_k), + neutrals: inks(n_c, n_m, n_y, n_k), + blacks: inks(k_c, k_m, k_y, k_k), + }; - Color::from_gamma_srgb_channels(out.x, out.y, out.z, a) - }); - image + adjust(image, Adjustment::SelectiveColor(Box::new(settings))) } // Aims for interoperable compatibility with: // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=nvrt%27%20%3D%20Invert-,%27post%27%20%3D%20Posterize,-%27thrs%27%20%3D%20Threshold #[node_macro::node(category("Raster: Adjustment"), icon("NodePosterize"))] -fn posterize>( +fn posterize( _: impl Ctx, #[implementations(Raster, Color, Gradient)] input: Item, #[default(4)] #[hard(2..)] levels: Item, ) -> Item { - let mut input = input; - let levels = levels.into_element() as f32; - - input.element_mut().adjust(|color| { - color.map_gamma_rgb(|c| { - // Bins as floor(c * levels) with the outputs spread evenly to white. - // The sliver of slack keeps an input exactly on an edge in the upper bin despite float ties. - let bin = ((c + 2e-7) * levels).floor().min(levels - 1.); - bin / (levels - 1.) - }) - }); - input + adjust(input, Adjustment::Posterize { levels: levels.into_element() }) } // Aims for interoperable compatibility with: @@ -2146,7 +1275,7 @@ fn posterize>( // The exposure, offset, and gamma operations follow: // https://geraldbakker.nl/psnumbers/exposure.html #[node_macro::node(category("Raster: Adjustment"), icon("NodeExposure"), inspector("exposure_inspector"))] -fn exposure>( +fn exposure( _: impl Ctx, #[implementations(Raster, Color, Gradient)] input: Item, #[range] @@ -2161,32 +1290,19 @@ fn exposure>( #[soft(0.01..10)] gamma_correction: Item, ) -> Item { - let mut input = input; - let exposure = exposure.into_element() as f32; - let offset = offset.into_element() as f32; - let gamma_correction = gamma_correction.into_element() as f32; - - // Linearizes with a 2.2 power above a straight toe of slope 1/32, the two meeting at this constant - const TOE_END: f32 = 0.05568117; // 32^(-1. / 1.2) - - let decode = |value: f32| if value < TOE_END { value / 32. } else { value.powf(2.2) }; - let encode = |linear: f32| if linear < TOE_END / 32. { linear * 32. } else { linear.powf(1. / 2.2) }; - let adjust = |c: f32| { - let linear = decode(c) * 2_f32.powf(exposure) + offset; - encode(linear.max(0.).powf(1. / gamma_correction).min(1.)) - }; - - input.element_mut().adjust(|color| { - let [r, g, b, a] = color.to_gamma_srgb_channels(); - Color::from_gamma_srgb_channels(adjust(r), adjust(g), adjust(b), a) - }); - input + adjust( + input, + Adjustment::Exposure { + exposure: exposure.into_element(), + offset: offset.into_element(), + gamma_correction: gamma_correction.into_element(), + }, + ) } -#[repr(u32)] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, dyn_any::DynAny, node_macro::ChoiceType)] #[widget(Dropdown)] pub enum TonalRange { Shadows, @@ -2195,91 +1311,13 @@ pub enum TonalRange { Highlights, } -/// A Levels-style tone curve: input black and white points on a 0..255 scale and a gamma exponent. For gamma above 1 the -/// power curve's slope is unbounded at black, so a cubic toe holds it to 2^gamma until past where that line meets the curve. -#[derive(Debug, Clone, Copy)] -struct LevelsCurve { - black: f32, - white: f32, - exponent: f32, - toe_end: f32, - toe_value: f32, - toe_slope_start: f32, - toe_slope_end: f32, -} - -impl LevelsCurve { - fn new(black: i32, white: i32, gamma: f32) -> Self { - Self::from_points(black as f32, white as f32, gamma) - } - - /// `gamma` is the Levels dialog value (pixel exponent 1/gamma). - fn from_points(black: f32, white: f32, gamma: f32) -> Self { - let gamma = gamma.max(0.01); - let black = black.min(white - 1.); - let exponent = 1. / gamma; - - let mut curve = Self { - black, - white, - exponent, - toe_end: 0., - toe_value: 0., - toe_slope_start: 0., - toe_slope_end: 0., - }; - if gamma > 1. { - let slope = 2_f32.powf(gamma); - let intersection = 255. * slope.powf(-1. / (1. - exponent)); - // The cubic toe joins the power curve at twice the intersection - if intersection > 1e-3 { - let toe_end = 2. * intersection; - curve.toe_end = toe_end; - curve.toe_value = 255. * (toe_end / 255.).powf(exponent); - curve.toe_slope_start = slope; - curve.toe_slope_end = exponent * (toe_end / 255.).powf(exponent - 1.); - } - } - curve - } - - /// Maps one gamma-space channel value in 0..1. - fn apply(&self, value: f32) -> f32 { - let t = ((value * 255. - self.black) * 255. / (self.white - self.black)).clamp(0., 255.); - let y = if t < self.toe_end { - let u = t / self.toe_end; - let hermite_start = u * u * u - 2. * u * u + u; - let hermite_end_value = 3. * u * u - 2. * u * u * u; - let hermite_end_slope = u * u * u - u * u; - hermite_start * self.toe_end * self.toe_slope_start + hermite_end_value * self.toe_value + hermite_end_slope * self.toe_end * self.toe_slope_end - } else { - 255. * (t / 255.).powf(self.exponent) - }; - y / 255. - } -} - -/// One channel's Levels parameters from its own slider values, and (with preserve_luminosity) the slider -/// extremes across all three channels. The halvings truncate toward zero, as PSD interop requires. -fn color_balance_curve(s: i32, m: i32, h: i32, s_max: i32, m_max: i32, m_min: i32, h_min: i32, preserve_luminosity: bool) -> LevelsCurve { - let (black, white, tone) = if preserve_luminosity { - (s_max - s, 255 - (h - h_min), m - (m_max + m_min) / 2) - } else { - (0.max(-s), 255 - 0.max(h), (s + h) / 2 + m) - }; - - // Rounding the derived gamma to hundredths, the precision of a PSD Levels record, is needed for compatible results - let gamma = (2_f32.powf(tone as f32 / 100.) * 100.).round() / 100.; - LevelsCurve::new(black, white, gamma) -} - // Aims for interoperable compatibility with: // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27blnc%27%20%3D%20Color%20Balance // // Every channel is a Levels curve whose black point, white point, and two-decimal gamma are derived from -// the nine sliders, see `color_balance_curve`. +// the nine sliders, see `color_balance_curve` in the adjustment kernels. #[node_macro::node(category("Raster: Adjustment"), icon("NodeColorBalance"), inspector("color_balance_inspector"))] -fn color_balance>( +fn color_balance( _: impl Ctx, #[implementations(Raster, Color, Gradient)] image: Item, @@ -2336,48 +1374,26 @@ fn color_balance>( // Display-only parameter (not used within the node) _tone: Item, ) -> Item { - let mut image = image; - let preserve_luminosity = preserve_luminosity.into_element(); - - // The derivation below is integer arithmetic, so the sliders round to whole percentages first - let slider = |value: f32| value.round() as i32; - let (s_r, s_g, s_b) = ( - slider(shadows_cyan_red.into_element() as f32), - slider(shadows_magenta_green.into_element() as f32), - slider(shadows_yellow_blue.into_element() as f32), - ); - let (m_r, m_g, m_b) = ( - slider(midtones_cyan_red.into_element() as f32), - slider(midtones_magenta_green.into_element() as f32), - slider(midtones_yellow_blue.into_element() as f32), - ); - let (h_r, h_g, h_b) = ( - slider(highlights_cyan_red.into_element() as f32), - slider(highlights_magenta_green.into_element() as f32), - slider(highlights_yellow_blue.into_element() as f32), - ); - - let s_max = s_r.max(s_g).max(s_b); - let m_max = m_r.max(m_g).max(m_b); - let m_min = m_r.min(m_g).min(m_b); - let h_min = h_r.min(h_g).min(h_b); - let red = color_balance_curve(s_r, m_r, h_r, s_max, m_max, m_min, h_min, preserve_luminosity); - let green = color_balance_curve(s_g, m_g, h_g, s_max, m_max, m_min, h_min, preserve_luminosity); - let blue = color_balance_curve(s_b, m_b, h_b, s_max, m_max, m_min, h_min, preserve_luminosity); - - image.element_mut().adjust(|color| { - // The curves operate on gamma-space channel values - let [r, g, b, a] = color.to_gamma_srgb_channels(); - Color::from_gamma_srgb_channels(red.apply(r), green.apply(g), blue.apply(b), a) - }); - image + let shifts = |cyan_red: Item, magenta_green: Item, yellow_blue: Item| ColorBalanceShifts { + cyan_red: cyan_red.into_element(), + magenta_green: magenta_green.into_element(), + yellow_blue: yellow_blue.into_element(), + }; + let settings = ColorBalanceSettings { + shadows: shifts(shadows_cyan_red, shadows_magenta_green, shadows_yellow_blue), + midtones: shifts(midtones_cyan_red, midtones_magenta_green, midtones_yellow_blue), + highlights: shifts(highlights_cyan_red, highlights_magenta_green, highlights_yellow_blue), + preserve_luminosity: preserve_luminosity.into_element(), + }; + + adjust(image, Adjustment::ColorBalance(settings)) } // Aims for interoperable compatibility with: // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=%27phfl%27%20%3D%20Photo%20Filter // https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/#:~:text=of%20the%20file.-,Photo%20Filter,-Key%20is%20%27phfl #[node_macro::node(category("Raster: Adjustment"), icon("NodePhotoFilter"))] -fn photo_filter>( +fn photo_filter( _: impl Ctx, #[implementations(Raster, Color, Gradient)] image: Item, #[default("#ec8a00")] color: Item, @@ -2388,53 +1404,14 @@ fn photo_filter>( density: Item, #[default(true)] preserve_luminosity: Item, ) -> Item { - let mut image = image; - let color = color.into_element(); - let density = (density.into_element() / 100.) as f32; - let preserve_luminosity = preserve_luminosity.into_element(); - - // The image is multiplied in XYZ by the filter color normalized to the white point, with density easing that multiplier toward 1 - let filter_xyz = multiply_matrix(&SRGB_TO_XYZ_D50, [color.r(), color.g(), color.b()]); - let factor = [ - 1. + density * (filter_xyz[0] / WHITE_XYZ_D50[0] - 1.), - 1. + density * (filter_xyz[1] / WHITE_XYZ_D50[1] - 1.), - 1. + density * (filter_xyz[2] / WHITE_XYZ_D50[2] - 1.), - ]; - - image.element_mut().adjust(|pixel| { - let [r_in, g_in, b_in, alpha] = pixel.to_gamma_srgb_channels(); - let xyz = multiply_matrix(&SRGB_TO_XYZ_D50, [srgb_to_linear(r_in), srgb_to_linear(g_in), srgb_to_linear(b_in)]); - let filtered = multiply_matrix(&XYZ_D50_TO_SRGB, [xyz[0] * factor[0], xyz[1] * factor[1], xyz[2] * factor[2]]); - let mut r = linear_to_srgb(filtered[0].clamp(0., 1.)); - let mut g = linear_to_srgb(filtered[1].clamp(0., 1.)); - let mut b = linear_to_srgb(filtered[2].clamp(0., 1.)); - - if preserve_luminosity { - let luma_in = luma_rec_601_fixed_point(r_in.clamp(0., 1.), g_in.clamp(0., 1.), b_in.clamp(0., 1.)); - [r, g, b] = set_luminosity(r, g, b, luma_rec_601_fixed_point(r, g, b), luma_in); - } - - Color::from_gamma_srgb_channels(r, g, b, alpha) - }); - image -} - -// sRGB colorants adapted to D50 as in the sRGB IEC61966-2.1 ICC profile, row major, and their inverse -pub(crate) const SRGB_TO_XYZ_D50: [[f32; 3]; 3] = [[0.43607, 0.38515, 0.14307], [0.22249, 0.71687, 0.06061], [0.01392, 0.09708, 0.71410]]; -pub(crate) const XYZ_D50_TO_SRGB: [[f32; 3]; 3] = [[3.134096, -1.6174, -0.490638], [-0.978793, 1.916295, 0.033454], [0.071971, -0.228987, 1.40538]]; -pub(crate) const WHITE_XYZ_D50: [f32; 3] = [0.96420, 1., 0.82491]; - -pub(crate) fn multiply_matrix(matrix: &[[f32; 3]; 3], vector: [f32; 3]) -> [f32; 3] { - [ - matrix[0][0] * vector[0] + matrix[0][1] * vector[1] + matrix[0][2] * vector[2], - matrix[1][0] * vector[0] + matrix[1][1] * vector[1] + matrix[1][2] * vector[2], - matrix[2][0] * vector[0] + matrix[2][1] * vector[1] + matrix[2][2] * vector[2], - ] -} - -/// The Rec. 601 luma in the 14-bit fixed point that PSD interop depends on. -fn luma_rec_601_fixed_point(r: f32, g: f32, b: f32) -> f32 { - (4915. * r + 9667. * g + 1802. * b) / 16384. + adjust( + image, + Adjustment::PhotoFilter { + color: color.into_element(), + density: density.into_element(), + preserve_luminosity: preserve_luminosity.into_element(), + }, + ) } // Aims for interoperable compatibility with: @@ -2444,7 +1421,7 @@ fn luma_rec_601_fixed_point(r: f32, g: f32, b: f32) -> f32 { // TODO: Support dither, which needs the pixel position that a per-color adjustment never sees. // TODO: Verify the tetrahedral interpolation, which is unconfirmed against other implementations. #[node_macro::node(category("Raster: Adjustment"), icon("NodeColorLookup"))] -fn color_lookup + Send>( +fn color_lookup( _: impl Ctx, /// The image whose colors are remapped by the LUT (lookup table). #[implementations(Raster, Color, Gradient)] @@ -2453,45 +1430,21 @@ fn color_lookup + Send>( #[name("LUT File")] #[widget(ParsedWidgetOverride::Custom = "lut_file")] lut_file: Item, - #[data] lut_cache: LutCache, ) -> Result, LutParseError> { - let mut image = image; - if lut_file.element().is_empty() { + let lut_file = lut_file.into_element(); + if lut_file.is_empty() { return Ok(image); } - let lut = lut_cache.parse(lut_file.element())?; - - image.element_mut().adjust(|color| { - // Lookup tables address the gamma-encoded channels - let [r, g, b, a] = color.to_gamma_srgb_channels(); - let [r, g, b] = lut.apply([r, g, b]); - Color::from_gamma_srgb_channels(r, g, b, a) - }); + // Parsed here to report a file that isn't a lookup table, then the kernel reuses the cached result + parse_cached(&lut_file)?; - Ok(image) + Ok(adjust(image, Adjustment::ColorLookup { lut_file })) } mod _graphene_hash_impls { - use super::{ - AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RedGreenBlueAlpha, - RelativeAbsolute, SelectiveColorChoice, TonalRange, - }; - graphene_hash::impl_via_hash!( - DesaturateMethod, - RedGreenBlue, - RedGreenBlueAlpha, - NoiseType, - FractalType, - CellularDistanceFunction, - CellularReturnType, - DomainWarpType, - RelativeAbsolute, - SelectiveColorChoice, - AdjustmentChannel, - TonalRange, - HueSaturationRange - ); + use super::{AdjustmentChannel, HueSaturationRange, RedGreenBlue, RedGreenBlueAlpha, SelectiveColorChoice, TonalRange}; + graphene_hash::impl_via_hash!(RedGreenBlue, RedGreenBlueAlpha, SelectiveColorChoice, AdjustmentChannel, TonalRange, HueSaturationRange); } #[cfg(test)] diff --git a/node-graph/nodes/raster/src/blending_nodes.rs b/node-graph/nodes/raster/src/blending_nodes.rs index 1be51ba6433..6e46550b524 100644 --- a/node-graph/nodes/raster/src/blending_nodes.rs +++ b/node-graph/nodes/raster/src/blending_nodes.rs @@ -3,6 +3,7 @@ use core_types::Ctx; use core_types::blending::BlendMode; use core_types::color::Color; use core_types::list::Item; +use graphic_types::Adjustment; use raster_types::{CPU, Raster}; use vector_types::Gradient; @@ -31,7 +32,7 @@ fn mix_colors( // TODO: Rename to "Paint Overlay" and take a `Graphic` paint like the `Fill` node, enabling this to serve the cases of Color Overlay, Gradient Overlay, and Pattern Overlay. #[node_macro::node(category("Raster: Effect"), icon("NodeColorOverlay"))] -fn color_overlay>( +fn color_overlay( _: impl Ctx, #[implementations( Raster, @@ -48,16 +49,12 @@ fn color_overlay>( opacity: Item, ) -> Item { let mut image = image; - let color = color.into_element(); - let blend_mode = blend_mode.into_element(); - let opacity = (opacity.into_element() / 100.) as f32; - - image.element_mut().adjust(|pixel| { - let overlay = apply_blend_mode(color, *pixel, blend_mode); - let mix = |image: f32, overlay: f32| image + (overlay - image) * opacity; - - Color::from_rgbaf32_unchecked(mix(pixel.r(), overlay.r()), mix(pixel.g(), overlay.g()), mix(pixel.b(), overlay.b()), pixel.a()) - }); + let adjustment = Adjustment::ColorOverlay { + color: color.into_element(), + blend_mode: blend_mode.into_element(), + opacity: opacity.into_element(), + }; + image.element_mut().adjust(&adjustment); image } diff --git a/node-graph/nodes/raster/src/filter.rs b/node-graph/nodes/raster/src/filter.rs index 3d6492ab2d8..691ab3a5952 100644 --- a/node-graph/nodes/raster/src/filter.rs +++ b/node-graph/nodes/raster/src/filter.rs @@ -1,9 +1,9 @@ -use crate::parallel_rows::fill_rows; use bytemuck::{Pod, Zeroable}; use core_types::color::{Alpha, Color, Pixel, RGB}; use core_types::context::Ctx; use core_types::list::Item; use raster_types::Image; +use raster_types::parallel_rows::fill_rows; use raster_types::{Bitmap, BitmapMut}; use raster_types::{CPU, Raster}; diff --git a/node-graph/nodes/raster/src/lib.rs b/node-graph/nodes/raster/src/lib.rs index c6eadef89d4..4a815c712ea 100644 --- a/node-graph/nodes/raster/src/lib.rs +++ b/node-graph/nodes/raster/src/lib.rs @@ -1,9 +1,8 @@ pub mod adjust; pub mod adjustments; pub mod blending_nodes; -pub mod color_lookup_table; +pub use raster_kernels::color_lookup_table; pub mod dehaze; pub mod filter; pub mod image_color_palette; -pub mod parallel_rows; pub mod std_nodes; diff --git a/node-graph/nodes/raster/src/std_nodes.rs b/node-graph/nodes/raster/src/std_nodes.rs index d0dca74b6a7..7504ee1ea4b 100644 --- a/node-graph/nodes/raster/src/std_nodes.rs +++ b/node-graph/nodes/raster/src/std_nodes.rs @@ -1,5 +1,4 @@ use crate::adjustments::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType}; -use crate::parallel_rows::fill_rows; use core_types::ATTR_TRANSFORM; use core_types::color::Color; use core_types::color::{Alpha, AlphaMut, Channel, LinearChannel, Luminance, RGBMut}; @@ -8,11 +7,11 @@ use core_types::list::Item; use core_types::math::bbox::Bbox; use core_types::transform::Transform; use dyn_any::DynAny; -use fastnoise_lite; -use glam::{DAffine2, DVec2, UVec2, Vec2}; +use glam::{DAffine2, DVec2, UVec2}; use graphene_resource::Resource; -use rand::prelude::*; -use rand_chacha::ChaCha8Rng; +use graphic_types::generator::{GeneratorPattern, NoiseSettings}; +use raster_kernels::generators::render_pattern; +use raster_types::parallel_rows::fill_rows; use raster_types::{Bitmap, BitmapMut}; use raster_types::{CPU, Raster}; use raster_types::{Image, ImageError}; @@ -298,100 +297,23 @@ fn noise_pattern( let width = (size.x * footprint_scale.x) as u32; let height = (size.y * footprint_scale.y) as u32; - // All - let mut image = Image::try_new(width, height, Color::from_luminance(0.5))?; - let mut noise = fastnoise_lite::FastNoiseLite::with_seed(seed as i32); - noise.set_frequency(Some(1. / (scale as f32).max(f32::EPSILON))); - - // Domain Warp - let domain_warp_type = match domain_warp_type { - DomainWarpType::None => None, - DomainWarpType::OpenSimplex2 => Some(fastnoise_lite::DomainWarpType::OpenSimplex2), - DomainWarpType::OpenSimplex2Reduced => Some(fastnoise_lite::DomainWarpType::OpenSimplex2Reduced), - DomainWarpType::BasicGrid => Some(fastnoise_lite::DomainWarpType::BasicGrid), - }; - let domain_warp_active = domain_warp_type.is_some(); - noise.set_domain_warp_type(domain_warp_type); - noise.set_domain_warp_amp(Some(domain_warp_amplitude as f32)); - - // Fractal - let noise_type = match noise_type { - NoiseType::Perlin => fastnoise_lite::NoiseType::Perlin, - NoiseType::OpenSimplex2 => fastnoise_lite::NoiseType::OpenSimplex2, - NoiseType::OpenSimplex2S => fastnoise_lite::NoiseType::OpenSimplex2S, - NoiseType::Cellular => fastnoise_lite::NoiseType::Cellular, - NoiseType::ValueCubic => fastnoise_lite::NoiseType::ValueCubic, - NoiseType::Value => fastnoise_lite::NoiseType::Value, - NoiseType::WhiteNoise => { - // TODO: Generate in layer space, not viewport space - - let mut rng = ChaCha8Rng::seed_from_u64(seed as u64); - - for y in 0..height { - for x in 0..width { - let pixel = image.get_pixel_mut(x, y).unwrap(); - let luminance = rng.random_range(0.0..1.) as f32; - *pixel = Color::from_luminance(luminance); - } - } - - return Ok(Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform)); - } - }; - noise.set_noise_type(Some(noise_type)); - let fractal_type = match fractal_type { - FractalType::None => fastnoise_lite::FractalType::None, - FractalType::FBm => fastnoise_lite::FractalType::FBm, - FractalType::Ridged => fastnoise_lite::FractalType::Ridged, - FractalType::PingPong => fastnoise_lite::FractalType::PingPong, - FractalType::DomainWarpProgressive => fastnoise_lite::FractalType::DomainWarpProgressive, - FractalType::DomainWarpIndependent => fastnoise_lite::FractalType::DomainWarpIndependent, - }; - noise.set_fractal_type(Some(fractal_type)); - noise.set_fractal_octaves(Some(fractal_octaves as i32)); - noise.set_fractal_lacunarity(Some(fractal_lacunarity as f32)); - noise.set_fractal_gain(Some(fractal_gain as f32)); - noise.set_fractal_weighted_strength(Some(fractal_weighted_strength as f32)); - noise.set_fractal_ping_pong_strength(Some(fractal_ping_pong_strength as f32)); - - // Cellular - let cellular_distance_function = match cellular_distance_function { - CellularDistanceFunction::Euclidean => fastnoise_lite::CellularDistanceFunction::Euclidean, - CellularDistanceFunction::EuclideanSq => fastnoise_lite::CellularDistanceFunction::EuclideanSq, - CellularDistanceFunction::Manhattan => fastnoise_lite::CellularDistanceFunction::Manhattan, - CellularDistanceFunction::Hybrid => fastnoise_lite::CellularDistanceFunction::Hybrid, - }; - let cellular_return_type = match cellular_return_type { - CellularReturnType::CellValue => fastnoise_lite::CellularReturnType::CellValue, - CellularReturnType::Nearest => fastnoise_lite::CellularReturnType::Distance, - CellularReturnType::NextNearest => fastnoise_lite::CellularReturnType::Distance2, - CellularReturnType::Average => fastnoise_lite::CellularReturnType::Distance2Add, - CellularReturnType::Difference => fastnoise_lite::CellularReturnType::Distance2Sub, - CellularReturnType::Product => fastnoise_lite::CellularReturnType::Distance2Mul, - CellularReturnType::Division => fastnoise_lite::CellularReturnType::Distance2Div, - }; - noise.set_cellular_distance_function(Some(cellular_distance_function)); - noise.set_cellular_return_type(Some(cellular_return_type)); - noise.set_cellular_jitter(Some(cellular_jitter as f32)); - - let coordinate_offset = offset.as_vec2(); - let scale = size.as_vec2() / Vec2::new(width as f32, height as f32); - // Calculate the noise for every pixel - for y in 0..height { - for x in 0..width { - let pixel = image.get_pixel_mut(x, y).unwrap(); - let pos = Vec2::new(x as f32, y as f32); - let vec = pos * scale + coordinate_offset; - - let (mut x, mut y) = (vec.x, vec.y); - if domain_warp_active && domain_warp_amplitude > 0. { - (x, y) = noise.domain_warp_2d(x, y); - } - - let luminance = (noise.get_noise_2d(x, y) + 1.) * 0.5; - *pixel = Color::from_luminance(luminance); - } - } + let noise = GeneratorPattern::Noise(NoiseSettings { + seed, + scale, + noise_type, + domain_warp_type, + domain_warp_amplitude, + fractal_type, + fractal_octaves, + fractal_lacunarity, + fractal_gain, + fractal_weighted_strength, + fractal_ping_pong_strength, + cellular_distance_function, + cellular_return_type, + cellular_jitter, + }); + let image = render_pattern(&noise, [offset, offset + size], width, height)?; Ok(Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, transform)) } @@ -415,38 +337,7 @@ fn mandelbrot(ctx: impl ExtractFootprint + Send) -> Result>, Im let scale = footprint.scale(); let width = (size.x * scale.x) as u32; let height = (size.y * scale.y) as u32; - - let mut image = Image::try_new(width, height, Color::TRANSPARENT)?; - let max_iter = 255; - - let scale = 3. * size.as_vec2() / Vec2::new(width as f32, height as f32); - let coordinate_offset = offset.as_vec2() * 3. - Vec2::new(2., 1.5); - for y in 0..height { - for x in 0..width { - let pos = Vec2::new(x as f32, y as f32); - let c = pos * scale + coordinate_offset; - - let iter = mandelbrot_impl(c, max_iter); - *image.get_mut(x as usize, y as usize) = map_color(iter, max_iter); - } - } + let image = render_pattern(&GeneratorPattern::Mandelbrot, [offset, offset + size], width, height)?; Ok(Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(offset) * DAffine2::from_scale(size))) } - -#[inline(always)] -fn mandelbrot_impl(c: Vec2, max_iter: usize) -> usize { - let mut z = Vec2::new(0., 0.); - for i in 0..max_iter { - z = Vec2::new(z.x * z.x - z.y * z.y, 2. * z.x * z.y) + c; - if z.length_squared() > 4. { - return i; - } - } - max_iter -} - -fn map_color(iter: usize, max_iter: usize) -> Color { - let v = iter as f32 / max_iter as f32; - Color::from_rgbaf32_unchecked(v, v, v, 1.) -} From 01a7831a929a9c1d2dd1edd4b94ba464fc8d9046 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Tue, 17 Nov 2026 22:26:33 -0800 Subject: [PATCH 2/2] Address review findings on the LUT parse cache --- .../raster-kernels/src/color_lookup_table.rs | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/node-graph/libraries/raster-kernels/src/color_lookup_table.rs b/node-graph/libraries/raster-kernels/src/color_lookup_table.rs index d3ce156192d..0efa48b9fe7 100644 --- a/node-graph/libraries/raster-kernels/src/color_lookup_table.rs +++ b/node-graph/libraries/raster-kernels/src/color_lookup_table.rs @@ -35,17 +35,25 @@ fn parsed_files() -> MutexGuard<'static, Vec> { pub fn parse_cached(resource: &Resource) -> ParsedLut { let hash = resource.hash(); - // Follows the copy in hand, in case another copy of the same content is the one that goes away - if let Some(entry) = parsed_files().iter_mut().find(|entry| entry.hash == hash) { - entry.file = resource.downgrade(); - return entry.parsed.clone(); + { + let mut parsed_files = parsed_files(); + + // Follows the copy in hand before pruning, in case another copy of the same content is the one that went away + let cached = parsed_files.iter_mut().find(|entry| entry.hash == hash).map(|entry| { + entry.file = resource.downgrade(); + entry.parsed.clone() + }); + parsed_files.retain(|entry| entry.file.is_alive()); + + if let Some(parsed) = cached { + return parsed; + } } // Parsed outside the lock, so a large file doesn't hold up the adjustments reading other files let parsed = Lut::parse(resource).map(Arc::new); let mut parsed_files = parsed_files(); - parsed_files.retain(|entry| entry.file.is_alive()); if !parsed_files.iter().any(|entry| entry.hash == hash) { parsed_files.push(ParsedFile { hash,