// SPDX-License-Identifier: MIT OR Apache-2.0 //! Node graph: text format, validation, subgraphs, packages and evaluation. use crate::accelerator::{ ColorInput, GreyInput, GreyTransformInput, HalfTransform, PixelImageInput, ResidentColor16, ResidentColorOutput, ResidentColorPass, ResidentGrey16, ResidentGreyFloat, ResidentGreyPass, }; pub use crate::context::Logging; use crate::context::{EvalContext, LiveBytes}; use crate::expr; use crate::grunge; use crate::math; use crate::noise; use crate::ops; use crate::png; use crate::scatter; use crate::tex::{Grey, Tex, Val, lum}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::fmt; use std::sync::Arc as Rc; use std::sync::{Arc, Mutex, OnceLock}; #[derive(Debug)] pub enum Error { Parse(usize, String), UnknownNode(u32, String), UnknownSlot(u32, String), MissingInput(u32, String), MissingNode(u32, u32), Cycle(u32), BadParam(u32, String), GpuReadback(u32, String), NoOutputs, BadSize(usize), Io(String), /// the editor started a newer evaluation; this one stopped early Cancelled, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::Parse(l, m) => write!(f, "line {l}: {m}"), Error::UnknownNode(id, k) => write!(f, "node {id}: unknown node type '{k}'"), Error::UnknownSlot(id, s) => write!(f, "node {id}: unknown input slot '{s}'"), Error::MissingInput(id, s) => write!(f, "node {id}: required input '{s}' is not connected"), Error::MissingNode(id, r) => write!(f, "node {id}: refers to missing node {r}"), Error::Cycle(id) => write!(f, "cycle detected at node {id}"), Error::BadParam(id, m) => write!(f, "node {id}: {m}"), Error::GpuReadback(id, m) => write!(f, "node {id}: GPU readback failed: {m}"), Error::NoOutputs => write!(f, "graph has no outputs"), Error::BadSize(s) => write!(f, "invalid resolution {s} (use 1..=8192)"), Error::Io(m) => write!(f, "io error: {m}"), Error::Cancelled => write!(f, "evaluation cancelled"), } } } impl std::error::Error for Error {} pub struct Spec { pub kind: &'static str, pub req: &'static [&'static str], pub opt: &'static [&'static str], pub doc: &'static str, } /// Slot names of a node's image inputs by position, on the nodes that take many (decompiled pixel processors and fx-maps). pub const IMAGE_SLOTS: &[&str] = &[ "in", "in2", "in3", "in4", "in5", "in6", "in7", "in8", "in9", "in10", "in11", "in12", "in13", "in14", "in15", "in16", "in17", "in18", "in19", "in20", "in21", "in22", "in23", "in24", "in25", "in26", "in27", "in28", "in29", "in30", "in31", "in32", ]; macro_rules! s { ($k:expr_2021, [$($r:expr_2021),*], [$($o:expr_2021),*], $d:expr_2021) => { Spec { kind: $k, req: &[$($r),*], opt: &[$($o),*], doc: $d } }; } pub const SPECS: &[Spec] = &[ s!("color", [], [], "constant colour: r g b a"), s!("white_noise", [], [], "per-pixel random: seed distribution(0 uniform,1 gaussian,2 triangle)"), s!( "gaussian_noise", [], [], "gaussian-distributed per-pixel noise: seed scale contrast invert disorder disorder_speed anisotropy anisotropy_angle tile_x tile_y" ), s!("perlin", [], [], "perlin noise: scale scale_x scale_y seed disorder disorder_speed tile_x tile_y"), s!( "fbm", [], [], "fractal noise/clouds: scale octaves gain seed mode(0 fbm,1 ridged,2 turbulence) disorder disorder_speed anisotropy anisotropy_angle tile_x tile_y" ), s!( "voronoi", [], [], "cellular: scale jitter seed mode(0 f1,1 cell id,2 edge,3 f2,4 f2-f1,5 f1*f2,6 f1/f2) aspect offset_x offset_y distortion distortion_scale distance_mode(0 euclid,1 manhattan,2 chebyshev,3 minkowski) minkowski edge_thickness rounded distance_scale color_seed_mode color_seed invert" ), s!( "voronoi_fractal", [], [], "layered voronoi: scale jitter seed mode aspect offset_x offset_y distortion distortion_scale distance_mode minkowski edge_thickness rounded distance_scale min_level max_level roughness lacunarity opacity blend(0 add,1 max,2 min) color_seed_mode color_seed invert" ), s!("gradient", [], [], "gradient: mode(0 linear,1 radial) angle"), s!("circle", [], [], "radius softness"), s!("rect", [], [], "width height softness"), s!("polygon", [], [], "sides radius softness rotation"), s!("checker", [], [], "tiles"), s!("bricks", [], [], "rows cols mortar bevel offset lum_var seed"), s!( "fx_map", [], ["in", "in2", "in3", "in4"], "run a pattern program: program=\"name\" depth seed blend (0 max 1 add 2 over 3 min 4 multiply) color bg bg_r bg_g bg_b" ), s!("curve", ["in"], [], "tone curves: points (master), points_r points_g points_b points_a as \"x:y,x:y\" lists"), s!("svg", [], [], "vector image: file=\"art.svg\" fit (0 contain 1 stretch 2 cover) scale x y"), s!( "text", [], [], "text: text=\"...\" font=\"face.ttf\" (optional) size x y (y_up=1: y counts up) align (0 left 1 centre 2 right) spacing line_spacing rotation value" ), s!( "channel_shuffle", ["in"], ["in2"], "rebuild channels: src_r src_g src_b src_a (0-3 channels of in, 4-7 channels of in2, 8 zero, 9 one), inv_r inv_g inv_b inv_a" ), s!( "input_value", [], [], "graph parameter read by functions: name, type (0 float, 1 int, 2 bool, 3 float2, 4 float3, 5 float4, 6 int2, 7 int3, 8 int4, 9 string), v / x y z w, min max, label" ), Spec { kind: "pixel_processor", req: &[], opt: IMAGE_SLOTS, doc: "per-pixel expr / expr_g / expr_b / expr_a (string params), or fn=\"function\" to run a function graph per pixel", }, s!( "value_processor", [], ["in", "in2", "in3", "in4"], "run fn=\"function\" once; the result (float, float3 or float4) fills the image. The function can read image statistics" ), s!("sdf_shape", [], [], "2D signed distance shape: shape(0 circle,1 box,2 polygon,3 ring) size aspect sides rotation round x y range"), s!("sdf_op", ["a", "b"], [], "combine SDFs: op(0 union,1 subtract,2 intersect) smooth range"), s!("sdf_mask", ["in"], [], "SDF -> mask: offset softness"), s!("sdf_form", [], [], "procedural 3D SDF form as height: shape(0 sphere,1 box,2 torus,3 cylinder) size repeat round scatter seed height"), s!("bitmap", [], [], "flip_x flip_y gray; imported PNG bitmap: file=\"path.png\""), s!("input", [], [], "subgraph input: idx"), s!("subgraph", [], ["in0", "in1", "in2", "in3"], "instance of a reusable subgraph: graph=\"name\""), s!("shape", [], [], "procedural shape: square, disc, paraboloid, gaussian, diamond, pyramid, half sphere, cone"), s!( "tile_sampler", [], [ "pattern", "pattern2", "pattern3", "pattern4", "pattern5", "pattern6", "mask", "scale_map", "rotation_map", "displacement_map", "color_map", "distribution_map", "background" ], "grid of pattern instances: x_amount y_amount size aspect size_mode scale scale_random size_random rotation rotation_random pattern_rotation symmetry_random position_random offset offset_mode offset_random global_offset_x global_offset_y color color_random lum_by_number lum_by_scale mask_threshold mask_invert mask_random mask_checker invert_mask blending opacity background reverse_order pattern_type pattern_specific pattern_distribution" ), s!( "tile_generator", [], [ "pattern", "pattern2", "pattern3", "pattern4", "pattern5", "pattern6", "mask", "scale_map", "rotation_map", "displacement_map", "color_map", "distribution_map", "background" ], "brick-style tiles: x_amount y_amount size aspect size_mode scale scale_random size_random rotation rotation_random pattern_rotation symmetry_random position_random offset offset_mode offset_random global_offset_x global_offset_y color color_random lum_by_number lum_by_scale mask_checker mask_horizontal mask_vertical mask_random invert_mask blending opacity background reverse_order pattern_type pattern_specific pattern_distribution" ), s!( "splatter", [], ["pattern", "pattern2", "pattern3", "pattern4", "pattern5", "pattern6"], "random scatter of a pattern: count grid_number scale scale_var aspect rotation rot_var pattern_rotation lum_var disorder pan_x pan_y symmetry_random gain output_min output_max background blending opacity pattern_type pattern_specific pattern_distribution" ), s!( "splatter_circular", [], ["pattern", "pattern2", "pattern3", "pattern4", "pattern5", "pattern6"], "instances on one or more circles: number amount_random rings radius radius_random ring_radius_multiplier angle_random spiral_factor spread size size_random scale_by_number scale_by_ring rotation rotation_random center_orientation ring_rotation ring_rotation_random position_random color luminance_random lum_by_number lum_by_ring mask_random background blending opacity pattern_type pattern_specific pattern_distribution" ), s!("clouds", [], [], "soft cloud noise: scale seed contrast invert disorder disorder_speed anisotropy anisotropy_angle tile_x tile_y"), s!( "bnw_spots", [], [], "black and white spots: scale seed contrast invert variant disorder disorder_speed anisotropy anisotropy_angle tile_x tile_y" ), s!("crystal", [], [], "faceted crystal cells: scale disorder seed contrast invert variant"), s!( "directional_noise", [], [], "streak noise, seamless at any angle: scale stretch angle seed contrast invert disorder disorder_speed anisotropy anisotropy_angle tile_x tile_y" ), s!( "grunge", [], [], "grunge masks: variant(0 concrete,1 scratches,2 spots,3 smudges) balance large_variation base_noisiness dirt_specks_opacity invert_dirt scratches_opacity sharpen quantity scratch_width scratch_length details coverage coverage_contrast disorder disorder_speed seed contrast invert" ), s!("plasma", [], [], "smooth plasma waves"), s!("stripes", [], [], "stripes: count angle softness width tile(1 = snap to seamless angle, 0 = exact)"), s!("weave", [], [], "woven threads: count width"), s!("star", [], [], "star shape: points inner size softness rotation"), s!("gradient_axial", [], [], "symmetric gradient: angle"), s!("gradient_circular", [], [], "angular gradient: offset"), s!("switch", [], ["a", "b", "c", "d"], "pass one of up to four inputs: index"), s!("flood_fill", ["in"], [], "label connected regions of a mask"), s!("flood_fill_random", ["in"], [], "random grayscale per flood-fill region"), s!("flood_fill_color", ["in"], [], "random color per flood-fill region"), s!("flood_fill_to_index", ["in"], [], "region number of each flood-fill region as a gray level"), s!("flood_fill_to_position", ["in"], [], "centre of each flood-fill region (outputs: position, x, y)"), s!("flood_fill_to_bbox_size", ["in"], [], "bounding-box size of each flood-fill region (outputs: size, width, height)"), s!("flood_fill_gradient", ["in"], [], "gradient across each flood-fill region"), s!("vector_warp", ["in", "vector"], [], "displace by a vector map: intensity directx"), s!("slope_blur", ["in", "slope"], [], "blur along a slope map: samples intensity mode"), s!("blur_hq", ["in"], [], "high quality blur: intensity quality"), s!("histogram_range", ["in"], [], "select a range of values: position range contrast invert"), s!("bevel", ["in"], [], "bevel a shape: distance smoothing threshold use_as_normal normal_intensity corner(0 round,1 angular) directx"), s!("distance", ["in"], [], "distance field of a mask: distance mode"), s!( "color_match", ["in"], ["reference", "src_color", "target_color"], "recolour: method(0 statistics transfer from reference,1 colour swap) strength source_mode(0 average,1 colour,2 input) src_r src_g src_b target_mode(0 colour,1 input) target_r target_g target_b custom_variation variation_hue variation_chroma variation_luma use_mask mask_hue_range mask_chroma_range mask_luma_range mask_smoothness" ), s!("curvature_smooth", ["in"], [], "smooth curvature from a normal map"), s!("height_blend", ["bg", "fg"], ["mask"], "blend two height maps: opacity contrast output"), s!("make_it_tile_photo", ["in"], [], "make a photo tile: width width_v"), s!("make_it_tile_patch", ["in"], [], "make an image tile with random patches"), s!("clamp", ["in"], [], "clamp values: low high apply_alpha"), s!("highpass", ["in"], [], "high-pass filter: radius"), s!("swirl", ["in"], [], "swirl distortion: amount radius"), s!("edge_wear", ["in"], ["noise"], "edge wear mask from a height map: amount width contrast"), s!("dirt", ["in"], ["noise"], "dirt mask from an ambient occlusion map: amount contrast"), s!("dust", ["in"], ["noise"], "dust mask from a normal map: amount contrast"), s!("output", [], ["in"], "graph output: usage identifier"), s!("dot", ["in"], [], "re-route a link"), s!("blur", ["in"], [], "gaussian blur: radius"), s!("directional_blur", ["in"], [], "angle length"), s!("sharpen", ["in"], [], "radius amount"), s!("levels", ["in"], [], "low high gamma out_low out_high"), s!("adjust", ["in"], [], "brightness contrast"), s!("invert", ["in"], [], "invert colours: invert"), s!("threshold", ["in"], [], "binary threshold: threshold softness mode(0 greater,1 greater or equal,2 lower,3 lower or equal)"), s!("histogram_scan", ["in"], [], "position width"), s!("quantize", ["in"], [], "steps"), s!("to_gray", ["in"], [], "luminance"), s!("channel", ["in"], [], "ch(0 r,1 g,2 b,3 a)"), s!("merge", [], ["r", "g", "b", "a"], "combine channels"), s!("tint", ["in"], [], "multiply by colour: r g b"), s!( "colorize", ["in"], [], "gradient map: interp(0 linear,1 smooth,2 step,3 smoother) smoothness addressing(0 clamp,1 repeat) use_alpha stops p0 r0 g0 b0 a0 ... p15 r15 g15 b15 a15" ), s!("hsl", ["in"], [], "hue sat val"), s!("transform", ["in"], [], "offset_x offset_y scale_x scale_y rotation(turns)"), s!( "mirror", ["in"], [], "mirror an image: axis(0 x,1 y,2 both,3 corner) offset_x offset_y invert_x invert_y corner(0 top left,1 top right,2 bottom left,3 bottom right)" ), s!("warp", ["in", "warp"], [], "slope warp: intensity filtering(0 bilinear,1 nearest,2 bicubic)"), s!("directional_warp", ["in", "warp"], [], "warp in one direction: angle intensity offset filtering(0 bilinear,1 nearest,2 bicubic)"), s!( "blend", ["fg", "bg"], ["mask"], "blend two images: mode (copy, add, subtract, multiply, screen, overlay, max, min, difference, soft_light, color_dodge, color_burn, linear_burn, hard_light, exclusion, divide, linear_light, color, luminosity, dissolve, add_sub, switch, and as compiled graphs blend: add_compiled, subtract_compiled, add_sub_compiled, divide_compiled, soft_light_compiled) opacity alpha_mode(0 source alpha,1 ignore alpha,2 straight,3 premultiplied) crop_x0 crop_y0 crop_x1 crop_y1" ), s!("normal", ["in"], [], "height->normal (OpenGL +Y): strength directx alpha_from_input"), s!("normal_blend", ["a", "b"], ["mask"], "blend normal maps (a = background, b = foreground): opacity"), s!( "ao", ["in"], [], "ambient occlusion: mode(0 blur,1 horizon) radius intensity hbao_radius hbao_intensity quality(0 4,1 8,2 16 samples) use_world_units height_depth surface_size height_depth_cm" ), s!( "quantize_color", ["in"], [], "reduce to few colours (k-means): color_amount contour_smoothing dithering dithering_pattern(0 noise,1 bayer) ignore_alpha distance_color_space(0 lab,1 rgb)" ), s!("curvature", ["in"], [], "curvature of a normal map: mode(0 normal map,1 height map) intensity directx radius"), s!("edge_detect", ["in"], [], "edge lines: mode(0 lines,1 sobel) edge_width edge_roundness invert tolerance intensity"), s!("emboss", ["in"], [], "angle intensity"), s!("non_uniform_blur", ["in", "mask"], [], "blur by a mask: intensity"), s!("radial_blur", ["in"], [], "spin blur around a centre: mode(0 spin,1 zoom) samples angle x y amount radius"), s!("anisotropic_blur", ["in"], [], "blur stretched in one direction: intensity anisotropy angle"), s!( "symmetry", ["in"], [], "mirror the image around a line: axis(0 x,1 y,2 both,3 diagonal,4 anti-diagonal,5 eight-fold) offset flip transfer(0 copy,1 add,2 sub,3 mul,4 add sub,5 max,6 min)" ), s!("skew", ["in"], [], "shear that keeps tiling: skew_x skew_y (whole numbers) align(0 centre,1 top left,2 bottom right)"), s!("auto_levels", ["in"], [], "stretch values to the full range: per_channel"), s!("channel_mixer", ["in"], [], "mix colour channels: rr rg rb gr gg gb br bg bb mono"), s!("alpha_merge", ["rgb"], ["alpha"], "put a grayscale image into the alpha channel"), s!("color_to_mask", ["in"], [], "mask of pixels close to a colour: r g b range softness"), s!("replace_color", ["in"], [], "replace one colour with another: src_r src_g src_b dst_r dst_g dst_b range softness"), s!("pow", ["in"], [], "raise values to a power: exponent"), s!("histogram_shift", ["in"], [], "shift all values: position"), s!("grayscale_conversion", ["in"], [], "weighted grayscale: r g b"), s!( "cells", [], ["color"], "cellular noise: scale jitter seed variant(0 cells1,1 cells2,2 cells3,3 cells4) luminance_random color_source(0 random,1 pseudorandom,2 image) pseudorandom_seed edge_width hardness contrast invert disorder disorder_speed anisotropy anisotropy_angle tile_x tile_y" ), s!( "fractal_sum", [], [], "sum of noise octaves: scale min_level max_level roughness seed mode(0 base,1 turbulence,2 creased) contrast invert disorder disorder_speed" ), s!( "waveform", [], [], "tileable wave pattern: count angle warp warp_scale seed shape(0 sine,1 triangle,2 saw,3 square) contrast invert disorder disorder_speed" ), s!( "gaussian_spots", [], [], "soft gaussian spots: scale size size_variation seed contrast invert disorder disorder_speed anisotropy anisotropy_angle tile_x tile_y" ), s!("normal_invert", ["in"], [], "flip normal map channels: invert_x invert_y invert_z invert_a"), s!("normal_normalize", ["in"], [], "renormalise a normal map"), s!("normal_vector_rotation", ["in"], ["rotation"], "rotate normal vectors: angle directx"), s!("normal_to_height", ["in"], [], "integrate a normal map into a height map: directx relief_balance opacity"), s!("sobel", ["in"], [], "sobel edge magnitude: intensity"), s!("glow", ["in"], [], "glow around bright areas: width intensity clear glow_r glow_g glow_b"), s!("mosaic", ["in"], ["mosaic_map"], "mosaic of the map regions (or a pixel grid without a map): count intensity"), s!("non_uniform_directional_warp", ["in", "intensity"], ["angle"], "warp along a direction chosen per pixel: intensity angle"), s!( "multi_directional_warp", ["in", "warp"], [], "warp in several directions at once: intensity directions(0 one,1 two,2 four) angle mode(0 average,1 max,2 min,3 chain)" ), s!("normal_combine", ["base", "detail"], [], "combine two normal maps: technique(0 whiteout,1 channel mixer,2 detail oriented)"), s!( "triangle_grid", [], [], "grid of triangles: style(0 squares,1 jittered mesh) count border variation x_amount y_amount random_position_multiplier quincunx_offset_x quincunx_offset_y triangulation(0 fixed,1 alternate,2 random) output(0 smooth,1 flat,2 edge distance) height_random thin_lines distance_to_edge_thickness thin_line_color thin_line_background seed contrast invert" ), s!("grunge_map", [], [], "grunge map 1-15: map balance contrast brush_pattern cracks disorder coverage seed invert"), s!("rgba_split", ["in"], [], "split into R, G, B and A grayscale outputs"), s!("alpha_split", ["in"], [], "split into an RGB output and an alpha output"), s!("weave_generator", [], [], "woven threads with gaps: tile_x tile_y weave shape gap_x gap_y contrast invert"), s!("starburst", [], [], "star-like rays: count rays sharpness size rotation rotation_random seed contrast invert"), s!("gradient_reflected", [], [], "gradient that goes 0-1-0: count angle contrast invert"), s!("shape_stroke", ["in"], [], "outline of a shape: width offset softness threshold opacity color_r color_g color_b"), s!("shape_glow", ["in"], [], "glow around a shape: width softness intensity threshold opacity spread color_r color_g color_b"), s!("chrominance_extract", ["in"], [], "colour without brightness"), s!("shape_drop_shadow", ["in"], [], "drop shadow of a mask: angle distance blur opacity spread"), ]; pub fn spec(kind: &str) -> Option<&'static Spec> { SPECS .iter() .chain(crate::func::FUNC_SPECS.iter()) .chain(crate::fxmap::FXM_SPECS.iter()) .chain(crate::atomic::SPECS.iter()) .chain(crate::compiled_ops::SPECS.iter()) .chain(crate::patterns::SPECS.iter()) .find(|s| s.kind == kind) } pub fn category(kind: &str) -> &'static str { match kind { "color" | "white_noise" | "gaussian_noise" | "perlin" | "fbm" | "clouds" | "voronoi" | "voronoi_fractal" | "bnw_spots" | "crystal" | "directional_noise" | "grunge" | "plasma" | "gradient" | "gradient_axial" | "gradient_circular" | "circle" | "rect" | "polygon" | "shape" | "star" | "checker" | "bricks" | "stripes" | "weave" | "tile_sampler" | "tile_generator" | "splatter" | "splatter_circular" | "pixel_processor" | "value_processor" | "fx_map" | "text" | "svg" | "cells" | "fractal_sum" | "waveform" | "gaussian_spots" | "triangle_grid" | "starburst" | "gradient_reflected" | "weave_generator" | "grunge_map" => "Generators", "sdf_shape" | "sdf_op" | "sdf_mask" | "sdf_form" => "SDF", "bitmap" | "input" | "input_value" | "subgraph" | "output" | "dot" => "Utility", k if k.starts_with("f_") => "Function", k if k.starts_with("fxm_") => "Pattern Program", "normal" | "normal_blend" | "normal_combine" | "normal_invert" | "normal_normalize" | "normal_vector_rotation" | "normal_to_height" | "ao" | "curvature" | "curvature_smooth" | "height_blend" | "edge_wear" | "dirt" | "dust" => "Material", _ => "Filters", } } /// Friendly display name for a node kind. pub fn label(kind: &str) -> String { let named = match kind { "fbm" => "Fractal Noise", "clouds" => "Clouds", "bnw_spots" => "BnW Spots", "merge" => "RGBA Merge", "colorize" => "Gradient Map", "voronoi_fractal" => "Voronoi Fractal", "color" => "Uniform Color", "hsl" => "HSL", "ao" => "Ambient Occlusion", "transform" => "Transform 2D", "blur_hq" => "Blur HQ", "make_it_tile_photo" => "Make It Tile Photo", "make_it_tile_patch" => "Make It Tile Patch", "sdf_shape" => "SDF Shape", "sdf_op" => "SDF Combine", "sdf_mask" => "SDF Mask", "sdf_form" => "SDF 3D Form", "pixel_processor" => "Pixel Processor", "value_processor" => "Value Processor", "svg" => "SVG", "text" => "Text", "fx_map" => "Pattern Program Map", "input_value" => "Input Value", "normal" => "Normal From Height", "normal_blend" => "Normal Blend", "rgba_split" => "RGBA Split", "pow" => "Pow", "sobel" => "Sobel", _ => "", }; if !named.is_empty() { return named.to_string(); } let fnamed = match kind { "f_vec2" => "Float2", "f_vec3" => "Float3", "f_vec4" => "Float4", "f_ivec2" => "Integer2", "f_ivec3" => "Integer3", "f_ivec4" => "Integer4", "f_int" => "Integer", "f_bool" => "Boolean", "f_graph_input" => "Graph Input", "f_sample_gray" => "Sample Grayscale", "f_sample_color" => "Sample Color", "f_lerp" => "Lerp", "f_atan2" | "f_atan2_approx" => "Atan2", "f_eq" => "Equal", "f_ne" => "Not Equal", "f_lt" => "Less Than", "f_le" => "Less Or Equal", "f_gt" => "Greater Than", "f_ge" => "Greater Or Equal", "f_pos" => "Position", "f_out" => "Function Output", "fxm_out" => "Program Output", _ => "", }; if !fnamed.is_empty() { return fnamed.to_string(); } let kind = kind.strip_prefix("fxm_").or_else(|| kind.strip_prefix("f_")).unwrap_or(kind); kind.split('_') .map(|w| { let mut c = w.chars(); c.next().map(|f| f.to_uppercase().collect::() + c.as_str()).unwrap_or_default() }) .collect::>() .join(" ") } /// Output usages in the order they are listed on a graph node. pub const OUTPUT_USAGES: [&str; 12] = [ "basecolor", "normal", "roughness", "metallic", "height", "ambient_occlusion", "opacity", "emissive", "diffuse", "specular", "glossiness", "out", ]; pub fn usage_label(usage: &str) -> String { match usage { "basecolor" => "Base Color", "normal" => "Normal", "roughness" => "Roughness", "metallic" => "Metallic", "height" => "Height", "ambient_occlusion" => "Ambient Occlusion", "opacity" => "Opacity", "emissive" => "Emissive", "diffuse" => "Diffuse", "specular" => "Specular", "glossiness" => "Glossiness", "out" => "Output", other => return label(other), } .to_string() } /// Value an unconnected Output node produces. pub fn output_default(usage: &str) -> [f32; 4] { match usage { "normal" => [0.5, 0.5, 1.0, 1.0], "metallic" | "emissive" => [0.0, 0.0, 0.0, 1.0], "ambient_occlusion" | "opacity" => [1.0; 4], "specular" => [0.04, 0.04, 0.04, 1.0], _ => [0.5, 0.5, 0.5, 1.0], } } /// Small graph used for library thumbnails and the node smoke test. None = no preview graph. pub fn demo_graph_for(kind: &str) -> Option { if matches!(kind, "input" | "subgraph" | "bitmap" | "output" | "dot") { return None; } let sp = spec(kind)?; match kind { "fx_map" => return Some("size 64\nsubgraph dots\nmeta kind \"fxmap\"\nnode 1 fxm_marker\nnode 2 fxm_iterate body=@1 grid_x=4 grid_y=4\nnode 3 fxm_out in=@2\nend\nnode 1 fx_map program=\"dots\"\noutput o 1\n".into()), "value_processor" => return Some("size 64\nsubgraph avg\nmeta kind \"function\"\nnode 1 f_image_avg\nnode 2 f_out in=@1\nend\nnode 100 fbm scale=4 seed=2\nnode 1 value_processor fn=\"avg\" in=@100\noutput o 1\n".into()), "svg" => return Some("size 64\nresource art.svg PHN2ZyB2aWV3Qm94PSIwIDAgMTAgMTAiPjxjaXJjbGUgY3g9IjUiIGN5PSI1IiByPSI0IiBmaWxsPSIjZmZmIi8+PC9zdmc+\nnode 1 svg file=\"art.svg\"\noutput o 1\n".into()), _ => {} } let mut t = String::from( "size 64\nnode 100 fbm scale=4 octaves=4 seed=2\nnode 101 gradient angle=0.1\nnode 102 sdf_shape shape=0 size=0.3\nnode 103 sdf_shape shape=1 size=0.25 x=0.15\nnode 104 voronoi scale=5 mode=2 seed=3\nnode 105 threshold in=@104 threshold=0.2\nnode 106 flood_fill in=@105\nnode 107 normal in=@100 strength=3\nnode 108 colorize in=@100 p0=0 r0=1 g0=0.2 b0=0.1 p1=1 r1=0.1 g1=0.4 b1=1\n", ) .replace("\\n", "\n"); let (a, b) = match kind { "sdf_op" | "sdf_mask" => (102, 103), "flood_fill" => (105, 105), k if k.starts_with("flood_fill_") => (106, 106), "dust" | "curvature_smooth" | "normal_combine" | "normal_invert" | "normal_normalize" | "normal_vector_rotation" | "normal_to_height" => { (107, 107) } "vector_warp" => (100, 107), "chrominance_extract" => (108, 108), _ => (100, 101), }; let mut line = format!("node 1 {kind}"); match kind { "pixel_processor" => line += " expr=\"sin(u*18.849556)*0.5+0.5\"", "text" => line += " text=\"Ab\" size=0.5", "input_value" => line += " name=\"level\" type=0 v=0.5", "colorize" => line += " p0=0 r0=0.1 g0=0.1 b0=0.35 p1=1 r1=1 g1=0.8 b1=0.3", "merge" => line += " r=@100 g=@101 b=@100", "alpha_merge" => line += " alpha=@101", "color_to_mask" => line += " r=0.5 g=0.5 b=0.5 range=0.12 softness=0.2", "replace_color" => line += " src_r=0.5 src_g=0.5 src_b=0.5 range=0.2", "switch" => line += " a=@100 b=@101 index=1", _ => {} } for (i, slot) in sp.req.iter().enumerate() { line += &format!(" {slot}=@{}", if i % 2 == 0 { a } else { b }); } t += &line; t += "\noutput o 1\n"; Some(t) } /// Suffix of the text key that keeps the exact digits of an integer setting too large for `Node::nums`. pub const EXACT_SUFFIX: &str = ".exact"; #[derive(Debug, Clone, Default)] pub struct Node { pub kind: String, pub nums: BTreeMap, pub strs: BTreeMap, pub ins: BTreeMap, /// For links coming from a graph (subgraph) node: which of its outputs the slot reads. Absent = default output. pub in_out: BTreeMap, pub pos: [f32; 2], } #[derive(Debug, Clone)] pub struct Comment { pub text: String, pub pos: [f32; 2], pub size: [f32; 2], pub color: u8, } #[derive(Debug, Clone)] pub struct Exposed { pub label: String, pub node: u32, pub param: String, pub min: f32, pub max: f32, } /// Version of the graph text format this build writes. Files without a `format` line are version 1 (they load /// unchanged); a file with a newer version is refused with a clear message instead of being half-understood. /// Format 3 writes names where 1 and 2 wrote numbers (Output Format, blend mode, pattern shape, `f_random`'s generator) /// and renames seven function ops; the older spellings still read the same (see [`crate::names`]). pub const FORMAT_VERSION: u32 = 3; /// What resolving a live link found (kept in memory only). #[derive(Debug, Clone, Default, PartialEq)] pub struct LinkInfo { /// the file that was actually read (the stored path, or a match found in the search folders) pub found: Option, pub issue: Option, /// subgraph names this link brought into the package pub members: Vec, } /// A live link to a graph in another package file (`link "" [""]`). The linked graph is /// not stored in this file: it is read from disk each time the file is opened or the links are refreshed, and used /// through a subgraph node whose `graph` is ``. Every node that uses the same name is an instance of it. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Link { pub name: String, pub path: String, /// which graph of that package; `None` = its main graph pub graph: Option, } #[derive(Debug, Clone)] pub struct Graph { /// format version the file was written with (1 when it had no `format` line) pub format: u32, pub links: Vec, /// subgraph names that came from resolving `links` (read-only copies, never written to the file) pub managed: BTreeSet, /// what the last `resolve_links` found for every link (not saved): the file used and the problem, if any pub link_info: BTreeMap, pub size: usize, /// pixel height at the nominal size; 0 means square (same as `size`) pub height: usize, pub nodes: BTreeMap, pub outputs: Vec<(String, u32)>, /// `output name id.pin` in a file: which named output of the node feeds the graph output (legacy output lines) pub output_pins: BTreeMap, pub subgraphs: BTreeMap, pub resources: BTreeMap>, pub exposed: Vec, pub comments: Vec, pub seed_offset: u32, pub meta: BTreeMap, } impl Default for Graph { fn default() -> Self { Graph { format: FORMAT_VERSION, links: Vec::new(), managed: BTreeSet::new(), link_info: BTreeMap::new(), size: 512, height: 0, nodes: BTreeMap::new(), outputs: Vec::new(), output_pins: BTreeMap::new(), subgraphs: BTreeMap::new(), resources: BTreeMap::new(), exposed: Vec::new(), comments: Vec::new(), seed_offset: 0, meta: BTreeMap::new(), } } } fn split_tokens(line: &str) -> Result, String> { let mut out = Vec::new(); let mut cur = String::new(); let mut in_q = false; let mut had_q = false; for c in line.chars() { match c { '"' => { in_q = !in_q; had_q = true; } c if c.is_whitespace() && !in_q => { if !cur.is_empty() || had_q { out.push(std::mem::take(&mut cur)); had_q = false; } } c => cur.push(c), } } if in_q { return Err("unterminated quote".into()); } if !cur.is_empty() || had_q { out.push(cur); } Ok(out) } // ---------- base64 (for embedded resources) ---------- const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; pub fn b64_encode(d: &[u8]) -> String { let mut s = String::with_capacity(d.len() * 4 / 3 + 4); // (a 6-bit index is always in the table) let digit = |v: u32| B64.get(v as usize & 63).copied().unwrap_or(b'=') as char; for c in d.chunks(3) { let byte = |k: usize| u32::from(c.get(k).copied().unwrap_or(0)); let n = byte(0) << 16 | byte(1) << 8 | byte(2); s.push(digit(n >> 18)); s.push(digit(n >> 12)); s.push(if c.len() > 1 { digit(n >> 6) } else { '=' }); s.push(if c.len() > 2 { digit(n) } else { '=' }); } s } pub fn b64_decode(s: &str) -> Result, String> { let mut out = Vec::with_capacity(s.len() * 3 / 4); let (mut acc, mut bits) = (0u32, 0); for ch in s.bytes() { if ch == b'=' { break; } let v = B64.iter().position(|&b| b == ch).ok_or_else(|| "invalid base64".to_string())? as u32; acc = (acc << 6) | v; bits += 6; if bits >= 8 { bits -= 8; out.push((acc >> bits) as u8); acc &= (1 << bits) - 1; } } Ok(out) } pub const THUMB: usize = 96; pub struct EvalAll { pub thumbs: HashMap>, pub errors: HashMap, pub kept: HashMap>, /// output size of every evaluated node (differs from the graph size when a node has its own Output Size) pub sizes: HashMap, } /// A validated, immutable graph and the compiled functions shared by its instances. pub struct PreparedGraph { graph: Graph, programs: Mutex, String>>>, dependencies: OnceLock>>, } impl PreparedGraph { pub fn parse(text: &str) -> Result { Ok(Self { graph: Graph::parse(text)?, programs: Mutex::default(), dependencies: OnceLock::new() }) } pub fn instance(&self, seed: u32) -> GraphInstance<'_> { GraphInstance { plan: self, nodes: BTreeMap::new(), seed } } /// Values that can affect this output via a reachable node, function, or pattern. pub fn output_parameters(&self, output: &str) -> Option<&BTreeSet> { self.dependencies .get_or_init(|| self.graph.output_nodes().into_iter().map(|(_, name, root)| (name, output_parameters(&self.graph, root))).collect()) .get(output) } fn program(&self, name: &str) -> Result, String> { if let Some(program) = self.programs.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(name) { return program.clone(); } let program = crate::func::compile_named(&self.graph.subgraphs, name).map(Arc::new); self.programs.lock().unwrap_or_else(std::sync::PoisonError::into_inner).insert(name.to_owned(), program.clone()); program } } fn output_parameters(graph: &Graph, root: u32) -> BTreeSet { let reachable = reached(graph, &[root]); let mut parameters: BTreeSet<_> = graph.exposed.iter().filter(|p| reachable.contains(&p.node)).map(|p| p.label.clone()).collect(); let mut pending: Vec<&Node> = reachable.iter().filter_map(|id| graph.nodes.get(id)).collect(); let mut visited = HashSet::new(); while let Some(node) = pending.pop() { if matches!(node.kind.as_str(), "input_value" | "f_graph_input") && let Some(name) = node.strs.get("name") { parameters.insert(name.clone()); } for (_, name) in node.strs.iter().filter(|(slot, _)| matches!(slot.as_str(), "fn" | "program" | "graph") || slot.starts_with("fn.")) { if visited.insert(name) && let Some(inner) = graph.subgraphs.get(name) { pending.extend(inner.nodes.values()); } } } parameters } impl std::ops::Deref for PreparedGraph { type Target = Graph; fn deref(&self) -> &Graph { &self.graph } } /// The runtime parameter bindings of a single material instance. pub struct GraphInstance<'a> { plan: &'a PreparedGraph, nodes: BTreeMap, seed: u32, } impl GraphInstance<'_> { pub fn nodes(&self) -> impl Iterator { self.plan.nodes.iter().map(|(id, node)| self.nodes.get(id).unwrap_or(node)) } pub fn work_nodes(&self, outputs: &[&str]) -> usize { self.reachable_nodes(outputs).len() } /// External images the selected outputs can read. A computed input index can read any slot. pub fn image_inputs(&self, outputs: &[&str]) -> Option> { self.reachable_nodes(outputs) .into_iter() .filter_map(|id| self.nodes.get(&id).or_else(|| self.plan.nodes.get(&id))) .filter(|node| node.kind == "input") .map(|node| (!node.strs.contains_key("fn.idx")).then(|| node.nums.get("idx").copied().unwrap_or(0.0).max(0.0) as u32)) .collect() } fn reachable_nodes(&self, outputs: &[&str]) -> HashSet { let roots: Vec<_> = self.plan.output_nodes().into_iter().filter(|(_, name, _)| outputs.contains(&name.as_str())).map(|(_, _, id)| id).collect(); reached(self.plan, &roots) } pub fn bind_number(&mut self, id: u32, slot: &str, value: f32) { if let Some(node) = self.plan.nodes.get(&id) { self.nodes.entry(id).or_insert_with(|| node.clone()).nums.insert(slot.to_owned(), value); } } pub fn bind_text(&mut self, id: u32, value: &str) { if let Some(node) = self.plan.nodes.get(&id).filter(|node| node.kind == "input_value") { self.nodes.entry(id).or_insert_with(|| node.clone()).strs.insert("v".into(), value.to_owned()); } } pub fn evaluate_owned(&self, ec: &EvalContext, size: usize, images: Vec>, outputs: &[&str]) -> Result, Error> { crate::context::scoped(ec, || { let ext = images.into_iter().map(|t| t.map(Val::of)).collect(); self.plan.evaluate_vals(ec, Some(size), ext, Some((self, outputs))) }) } } struct Ctx<'a> { resident: bool, size: usize, /// pixel height (equals `size` for a square graph) height: usize, /// the graph's own (nominal) size: absolute node sizes are scaled by size / nominal so quick previews stay proportional nominal: usize, /// in a compiled graph, on a node whose size isn't the graph's: the graph's size, which `$outputsize` reads everywhere in the node graph: Option<[usize; 2]>, lib: &'a BTreeMap, res: &'a BTreeMap>, so: u32, depth: usize, /// values of the Input Value nodes of the graph being evaluated (read by function graphs) gin: &'a BTreeMap, instance: Option<&'a GraphInstance<'a>>, plan: Option<&'a PreparedGraph>, /// what the host gave this evaluation: its cancel flag, logging, profiler and memory counter ec: &'a EvalContext, } impl Ctx<'_> { fn program(&self, name: &str) -> Result, String> { match self.plan { Some(plan) => plan.program(name), None => crate::func::compile_named(self.lib, name).map(Arc::new), } } } /// Node id used for the helper nodes of [`Graph::preview_host`] (far above any id an author would reach). pub const PREVIEW_ID: u32 = 4_000_000_001; impl Graph { /// "texture", "function" or "fxmap". pub fn graph_kind(&self) -> &str { match self.meta.get("kind").map(String::as_str) { Some("function") => "function", Some("fxmap") => "fxmap", _ => "texture", } } /// Function graphs and pattern programs are not textures. To look at one, wrap it in a texture graph that /// runs it: a pixel processor for a function, a pattern map for a program. Returns the wrapper and the id of the /// node that shows the result (`None` for ordinary graphs). pub fn preview_host(&self) -> Option<(Graph, u32)> { let kind = self.graph_kind(); if kind == "texture" { return None; } let mut host = Graph { size: self.size, height: self.height, seed_offset: self.seed_offset, resources: self.resources.clone(), subgraphs: self.subgraphs.clone(), ..Graph::default() }; let mut me = self.clone(); me.subgraphs.clear(); me.resources.clear(); host.subgraphs.insert("__self".into(), me); let mut n = Node::default(); if kind == "function" { n.kind = "pixel_processor".into(); n.strs.insert("fn".into(), "__self".into()); } else { n.kind = "fx_map".into(); n.strs.insert("program".into(), "__self".into()); n.nums.insert("color".into(), 0.0); } host.nodes.insert(PREVIEW_ID, n); let mut o = Node { kind: "output".into(), ..Node::default() }; o.strs.insert("usage".into(), "basecolor".into()); o.ins.insert("in".into(), PREVIEW_ID); host.nodes.insert(PREVIEW_ID + 1, o); Some((host, PREVIEW_ID)) } pub fn parse(text: &str) -> Result { let g = Graph::parse_unchecked(text)?; g.validate()?; Ok(g) } /// Parse without validating connections (used by the editor for work-in-progress graphs). pub fn parse_unchecked(text: &str) -> Result { let mut g = Graph { format: 1, ..Graph::default() }; let lines: Vec<&str> = text.lines().collect(); let mut i = 0; while let Some(raw) = lines.get(i).copied() { let ln = i + 1; i += 1; let line = raw.split('#').next().unwrap_or("").trim(); if line.is_empty() { continue; } if let Some(name) = line.strip_prefix("subgraph ") { let mut body = String::new(); let mut closed = false; while let Some(l) = lines.get(i).copied() { i += 1; if l.trim() == "end" { closed = true; break; } body.push_str(l); body.push('\n'); } if !closed { return Err(Error::Parse(ln, "subgraph without matching 'end'".into())); } let sub = Graph::parse_unchecked(&body).map_err(|e| Error::Parse(ln, format!("in subgraph '{}': {e}", name.trim())))?; g.subgraphs.insert(name.trim().to_string(), sub); continue; } if let Some(rest) = line.strip_prefix("comment ") { let t: Vec<&str> = rest.split_whitespace().collect(); let [x, y, w, h, color, text @ ..] = t.as_slice() else { return Err(Error::Parse(ln, "usage: comment x y w h color text...".into())); }; let f = |v: &str| v.parse::().map_err(|_| Error::Parse(ln, "bad comment number".into())); g.comments.push(Comment { text: text.join(" "), pos: [f(x)?, f(y)?], size: [f(w)?.max(40.0), f(h)?.max(30.0)], color: color.parse().unwrap_or(0), }); continue; } let t = split_tokens(line).map_err(|m| Error::Parse(ln, m))?; // (a line that isn't empty has a first token) let word = |k: usize| t.get(k).map_or("", String::as_str); match word(0) { "format" => { let v = t.get(1).and_then(|s| s.parse::().ok()).ok_or_else(|| Error::Parse(ln, "format needs an integer".into()))?; if v > FORMAT_VERSION { return Err(Error::Parse( ln, format!("this file uses format {v}, but this version reads up to format {FORMAT_VERSION}; please update"), )); } g.format = v; } "link" => { if t.len() < 3 || t.len() > 4 { return Err(Error::Parse(ln, "usage: link \"\" [\"\"]".into())); } g.links.push(Link { name: word(1).to_string(), path: word(2).to_string(), graph: t.get(3).cloned().filter(|s| !s.is_empty()) }); } "size" => { g.size = t.get(1).and_then(|s| s.parse::().ok()).ok_or_else(|| Error::Parse(ln, "size needs an integer".into()))?; g.height = match t.get(2) { Some(h) => h.parse::().map_err(|_| Error::Parse(ln, "size height needs an integer".into()))?, None => 0, }; } "seed_offset" => { g.seed_offset = t.get(1).and_then(|s| s.parse::().ok()).ok_or_else(|| Error::Parse(ln, "seed_offset needs an integer".into()))?; } "meta" => { if t.len() != 3 { return Err(Error::Parse(ln, "usage: meta \"value\"".into())); } g.meta.insert(word(1).to_string(), word(2).to_string()); } "resource" => { if t.len() != 3 { return Err(Error::Parse(ln, "usage: resource ".into())); } g.resources.insert(word(1).to_string(), b64_decode(word(2)).map_err(|m| Error::Parse(ln, m))?); } "expose" => { if t.len() != 6 { return Err(Error::Parse(ln, "usage: expose