From 13bb1687b990827cf50783f4711c1d021cf608ac Mon Sep 17 00:00:00 2001 From: Timon Date: Thu, 3 Dec 2026 20:40:54 +0000 Subject: [PATCH] Add the graph-ui crate, which draws the node graph with Graphene --- Cargo.lock | 39 ++ Cargo.toml | 6 + node-graph/graph-craft/Cargo.toml | 1 + node-graph/graph-craft/src/document/value.rs | 7 + node-graph/graph-ui/Cargo.toml | 36 + node-graph/graph-ui/icons/Cargo.toml | 14 + node-graph/graph-ui/icons/build.rs | 39 ++ node-graph/graph-ui/icons/src/lib.rs | 8 + node-graph/graph-ui/src/dashes.rs | 266 ++++++++ node-graph/graph-ui/src/icons.rs | 90 +++ node-graph/graph-ui/src/lib.rs | 12 + node-graph/graph-ui/src/look.rs | 155 +++++ node-graph/graph-ui/src/network.rs | 155 +++++ node-graph/graph-ui/src/nodes.rs | 627 ++++++++++++++++++ node-graph/graph-ui/src/router.rs | 521 +++++++++++++++ node-graph/graph-ui/src/text.rs | 86 +++ node-graph/graph-ui/types/Cargo.toml | 33 + node-graph/graph-ui/types/src/card.rs | 56 ++ node-graph/graph-ui/types/src/dot.rs | 23 + node-graph/graph-ui/types/src/error_badge.rs | 40 ++ node-graph/graph-ui/types/src/geometry.rs | 493 ++++++++++++++ node-graph/graph-ui/types/src/highlights.rs | 94 +++ node-graph/graph-ui/types/src/inputs.rs | 71 ++ node-graph/graph-ui/types/src/layer.rs | 39 ++ node-graph/graph-ui/types/src/lib.rs | 31 + node-graph/graph-ui/types/src/metrics.rs | 80 +++ .../graph-ui/types/src/network_connector.rs | 111 ++++ node-graph/graph-ui/types/src/placed.rs | 17 + .../graph-ui/types/src/replicated_map.rs | 185 ++++++ node-graph/graph-ui/types/src/scene.rs | 161 +++++ node-graph/graph-ui/types/src/wire.rs | 57 ++ 31 files changed, 3553 insertions(+) create mode 100644 node-graph/graph-ui/Cargo.toml create mode 100644 node-graph/graph-ui/icons/Cargo.toml create mode 100644 node-graph/graph-ui/icons/build.rs create mode 100644 node-graph/graph-ui/icons/src/lib.rs create mode 100644 node-graph/graph-ui/src/dashes.rs create mode 100644 node-graph/graph-ui/src/icons.rs create mode 100644 node-graph/graph-ui/src/lib.rs create mode 100644 node-graph/graph-ui/src/look.rs create mode 100644 node-graph/graph-ui/src/network.rs create mode 100644 node-graph/graph-ui/src/nodes.rs create mode 100644 node-graph/graph-ui/src/router.rs create mode 100644 node-graph/graph-ui/src/text.rs create mode 100644 node-graph/graph-ui/types/Cargo.toml create mode 100644 node-graph/graph-ui/types/src/card.rs create mode 100644 node-graph/graph-ui/types/src/dot.rs create mode 100644 node-graph/graph-ui/types/src/error_badge.rs create mode 100644 node-graph/graph-ui/types/src/geometry.rs create mode 100644 node-graph/graph-ui/types/src/highlights.rs create mode 100644 node-graph/graph-ui/types/src/inputs.rs create mode 100644 node-graph/graph-ui/types/src/layer.rs create mode 100644 node-graph/graph-ui/types/src/lib.rs create mode 100644 node-graph/graph-ui/types/src/metrics.rs create mode 100644 node-graph/graph-ui/types/src/network_connector.rs create mode 100644 node-graph/graph-ui/types/src/placed.rs create mode 100644 node-graph/graph-ui/types/src/replicated_map.rs create mode 100644 node-graph/graph-ui/types/src/scene.rs create mode 100644 node-graph/graph-ui/types/src/wire.rs diff --git a/Cargo.lock b/Cargo.lock index a558d87206..53d40c8184 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2498,6 +2498,7 @@ dependencies = [ "futures", "glam", "graph-craft", + "graph-ui-types", "graphene-animation", "graphene-application-io", "graphene-canvas-utils", @@ -2535,6 +2536,44 @@ dependencies = [ "smallvec", ] +[[package]] +name = "graph-ui" +version = "0.0.0" +dependencies = [ + "core-types", + "glam", + "graph-craft", + "graph-ui-icons", + "graph-ui-types", + "graphene-std", + "graphic-types", + "node-macro", + "rendering", + "svg-convert", + "text-nodes", + "vector-types", + "vello_gpu", +] + +[[package]] +name = "graph-ui-icons" +version = "0.0.0" + +[[package]] +name = "graph-ui-types" +version = "0.0.0" +dependencies = [ + "core-types", + "dyn-any", + "glam", + "graph-layout", + "graphene-hash", + "graphic-types", + "serde", + "tsify", + "wasm-bindgen", +] + [[package]] name = "graphene-animation" version = "0.0.0" diff --git a/Cargo.toml b/Cargo.toml index 2bfb070c9e..5d0fbd8436 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,6 +34,9 @@ members = [ "node-graph/libraries/*", "node-graph/nodes/*", "node-graph/graph-craft", + "node-graph/graph-ui", + "node-graph/graph-ui/icons", + "node-graph/graph-ui/types", "node-graph/graphene-cli", "node-graph/nodes/gstd", "node-graph/interpreted-executor", @@ -112,6 +115,9 @@ vectorize-nodes = { path = "node-graph/nodes/vectorize" } math-nodes = { path = "node-graph/nodes/math" } path-bool-nodes = { path = "node-graph/nodes/path-bool" } graph-craft = { path = "node-graph/graph-craft" } +graph-ui = { path = "node-graph/graph-ui" } +graph-ui-icons = { path = "node-graph/graph-ui/icons" } +graph-ui-types = { path = "node-graph/graph-ui/types" } document-format = { path = "document/format" } document-graph-storage = { path = "document/graph-storage", default-features = false } document-container = { path = "document/container" } diff --git a/node-graph/graph-craft/Cargo.toml b/node-graph/graph-craft/Cargo.toml index 9bdde0b809..bcec359fac 100644 --- a/node-graph/graph-craft/Cargo.toml +++ b/node-graph/graph-craft/Cargo.toml @@ -41,6 +41,7 @@ raster-nodes = { workspace = true, features = ["serde"] } vector-nodes = { workspace = true, features = ["serde"] } graphic-types = { workspace = true, features = ["serde"] } text-nodes = { workspace = true, features = ["serde"] } +graph-ui-types = { workspace = true } # Workspace dependencies log = { workspace = true } diff --git a/node-graph/graph-craft/src/document/value.rs b/node-graph/graph-craft/src/document/value.rs index 9fd5b5e27f..6eea372f68 100644 --- a/node-graph/graph-craft/src/document/value.rs +++ b/node-graph/graph-craft/src/document/value.rs @@ -110,6 +110,8 @@ macro_rules! tagged_value { Runtime(RuntimeHandle), #[serde(skip)] EditorApi(Arc), + #[serde(skip)] + GraphUi(graph_ui_types::TaggedGraphUiValue), /// Only used by the `resource` node, should never be serialized #[serde(skip)] ResourceHash(ResourceHash), @@ -144,6 +146,7 @@ macro_rules! tagged_value { Self::Runtime(runtime) => runtime.cache_hash(state), Self::RenderOutput(x) => x.cache_hash(state), Self::EditorApi(x) => x.cache_hash(state), + Self::GraphUi(x) => x.cache_hash(state), Self::ResourceHash(x) => x.cache_hash(state), } } @@ -208,6 +211,7 @@ macro_rules! tagged_value { Self::SourceId(source) => Box::new(Item::new_from_element(source)), Self::Runtime(runtime) => Box::new(Item::new_from_element(runtime)), Self::EditorApi(x) => Box::new(Item::new_from_element(x)), + Self::GraphUi(x) => x.to_dynany(), Self::ResourceHash(x) => Box::new(Item::new_from_element(x)), } } @@ -268,6 +272,7 @@ macro_rules! tagged_value { Self::SourceId(source) => Arc::new(Item::new_from_element(source)), Self::Runtime(runtime) => Arc::new(Item::new_from_element(runtime)), Self::EditorApi(x) => Arc::new(Item::new_from_element(x)), + Self::GraphUi(x) => x.to_any(), Self::ResourceHash(x) => Arc::new(Item::new_from_element(x)), } } @@ -300,6 +305,7 @@ macro_rules! tagged_value { Self::SourceId(_) => item!(SourceId), Self::Runtime(_) => item!(RuntimeHandle), Self::EditorApi(_) => item!(Arc), + Self::GraphUi(x) => x.ty(), Self::ResourceHash(_) => item!(ResourceHash), }; @@ -458,6 +464,7 @@ macro_rules! tagged_value { Self::SourceId(source) => format!("SourceId({source:?})"), Self::Runtime(_) => "Runtime".to_string(), Self::EditorApi(_) => "PlatformEditorApi".to_string(), + Self::GraphUi(_) => "GraphUi".to_string(), Self::ResourceHash(hash) => format!("ResourceHash({hash:?})"), } } diff --git a/node-graph/graph-ui/Cargo.toml b/node-graph/graph-ui/Cargo.toml new file mode 100644 index 0000000000..86bdf4d103 --- /dev/null +++ b/node-graph/graph-ui/Cargo.toml @@ -0,0 +1,36 @@ +[package] +name = "graph-ui" +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 + +[features] +serde = ["graph-ui-types/serde"] +wasm = ["graph-ui-types/wasm"] + +[dependencies] +# Local dependencies +core-types = { workspace = true } +graph-craft = { workspace = true } +graph-ui-icons = { workspace = true } +graph-ui-types = { workspace = true } +graphene-std = { workspace = true } +graphic-types = { workspace = true } +node-macro = { workspace = true } +rendering = { workspace = true } +svg-convert = { workspace = true } +text-nodes = { workspace = true } +vector-types = { workspace = true } + +# Workspace dependencies +glam = { workspace = true } +vello_gpu = { workspace = true } diff --git a/node-graph/graph-ui/icons/Cargo.toml b/node-graph/graph-ui/icons/Cargo.toml new file mode 100644 index 0000000000..7b71caa4cc --- /dev/null +++ b/node-graph/graph-ui/icons/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "graph-ui-icons" +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 diff --git a/node-graph/graph-ui/icons/build.rs b/node-graph/graph-ui/icons/build.rs new file mode 100644 index 0000000000..4030ec5ea7 --- /dev/null +++ b/node-graph/graph-ui/icons/build.rs @@ -0,0 +1,39 @@ +// TODO(Timon): Replace with generalized icon crate + +use std::fmt::Write; +use std::path::PathBuf; + +const FOLDERS: [&str; 2] = ["16x16-nodes", "16x16-ui-general"]; + +fn main() { + let root = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("../../.."); + let assets = root.join("branding/assets"); + + let mut sources = Vec::new(); + println!("cargo:rerun-if-changed={}", assets.display()); + if assets.is_dir() { + for folder in FOLDERS { + for entry in std::fs::read_dir(assets.join(folder)).unwrap() { + let path = entry.unwrap().path(); + if path.extension().is_some_and(|extension| extension == "svg") { + sources.push((icon_name(&path.file_stem().unwrap().to_string_lossy()), path)); + } + } + } + } else { + println!("cargo:warning=No branding folder, icons will be missing"); + } + sources.sort(); + + let mut table = String::from("static SOURCES: &[(&str, &str)] = &[\n"); + for (name, path) in &sources { + writeln!(table, "\t({name:?}, include_str!({:?})),", path.display().to_string()).unwrap(); + } + table.push_str("];\n"); + std::fs::write(PathBuf::from(std::env::var("OUT_DIR").unwrap()).join("icons.rs"), table).unwrap(); +} + +fn icon_name(file_stem: &str) -> String { + let capitalized = |word: &str| word[..1].to_uppercase() + &word[1..]; + file_stem.split('-').filter(|word| !word.is_empty()).map(capitalized).collect() +} diff --git a/node-graph/graph-ui/icons/src/lib.rs b/node-graph/graph-ui/icons/src/lib.rs new file mode 100644 index 0000000000..7100647f10 --- /dev/null +++ b/node-graph/graph-ui/icons/src/lib.rs @@ -0,0 +1,8 @@ +// TODO(Timon): Replace with generalized icon crate + +include!(concat!(env!("OUT_DIR"), "/icons.rs")); + +pub fn svg(name: &str) -> Option<&'static str> { + let index = SOURCES.binary_search_by_key(&name, |&(name, _)| name).ok()?; + Some(SOURCES[index].1) +} diff --git a/node-graph/graph-ui/src/dashes.rs b/node-graph/graph-ui/src/dashes.rs new file mode 100644 index 0000000000..17744d4cfe --- /dev/null +++ b/node-graph/graph-ui/src/dashes.rs @@ -0,0 +1,266 @@ +use crate::metrics::{BORDER_DASHES, BORDER_WIDTH}; +use glam::DVec2; +use std::f64::consts::{FRAC_PI_2, PI}; +use std::ops::Range; +use vello_gpu::kurbo::{Arc, BezPath, CubicBez, Line, ParamCurve, PathEl, PathSeg, Point, QuadBez}; + +const MEASURE_TOLERANCE: f64 = 0.5; +const MEASURE_DEPTH: u32 = 20; +const ARC_TOLERANCE: f64 = 0.1; + +struct Measured { + distance: f64, + segment: usize, + t: f64, +} + +pub(crate) fn dashed(path: &BezPath, [dash, gap]: [f64; 2]) -> BezPath { + let mut dashes = BezPath::new(); + for contour in contours(path) { + let measured = measure(&contour); + let Some(length) = measured.last().map(|last| last.distance) else { continue }; + let mut distance = 0.; + for (index, interval) in [dash, gap].into_iter().cycle().enumerate() { + if distance >= length { + break; + } + if index % 2 == 0 { + piece(&contour, &measured, distance..(distance + interval).min(length), &mut dashes); + } + distance += interval; + } + } + dashes +} + +fn contours(path: &BezPath) -> Vec> { + let mut contours: Vec> = Vec::new(); + let (mut start, mut last) = (Point::ZERO, Point::ZERO); + for element in path.elements() { + let segment = match *element { + PathEl::MoveTo(point) => { + contours.push(Vec::new()); + (start, last) = (point, point); + continue; + } + PathEl::LineTo(point) => PathSeg::Line(Line::new(last, point)), + PathEl::QuadTo(control, point) => PathSeg::Cubic(QuadBez::new(last, control, point).raise()), + PathEl::CurveTo(first, second, point) => PathSeg::Cubic(CubicBez::new(last, first, second, point)), + PathEl::ClosePath => PathSeg::Line(Line::new(last, start)), + }; + last = segment.end(); + if let Some(contour) = contours.last_mut() { + contour.push(segment); + } + } + contours +} + +fn measure(contour: &[PathSeg]) -> Vec { + let mut measured = Vec::new(); + let mut distance = 0.; + for (segment, piece) in contour.iter().enumerate() { + distance = match piece { + PathSeg::Cubic(cubic) => measure_cubic(*cubic, distance, 0_f64..1., MEASURE_DEPTH, segment, &mut measured), + _ => chord(piece.start(), piece.end(), distance, segment, 1., &mut measured), + }; + } + measured +} + +fn measure_cubic(cubic: CubicBez, distance: f64, range: Range, depth: u32, segment: usize, measured: &mut Vec) -> f64 { + let strays = |control: Point, fraction: f64| { + let on_chord = cubic.p0.lerp(cubic.p3, fraction); + (control.x - on_chord.x).abs().max((control.y - on_chord.y).abs()) > MEASURE_TOLERANCE + }; + if depth == 0 || !(strays(cubic.p1, 1. / 3.) || strays(cubic.p2, 2. / 3.)) { + return chord(cubic.p0, cubic.p3, distance, segment, range.end, measured); + } + let (first, second) = cubic.subdivide(); + let middle = (range.start + range.end) / 2.; + let distance = measure_cubic(first, distance, range.start..middle, depth - 1, segment, measured); + measure_cubic(second, distance, middle..range.end, depth - 1, segment, measured) +} + +fn chord(from: Point, to: Point, distance: f64, segment: usize, t: f64, measured: &mut Vec) -> f64 { + let next = distance + from.distance(to); + if next > distance { + measured.push(Measured { distance: next, segment, t }); + } + next +} + +fn at(measured: &[Measured], distance: f64) -> (usize, f64) { + let index = measured.partition_point(|entry| entry.distance < distance).min(measured.len() - 1); + let entry = &measured[index]; + let (start_distance, start_t) = match index.checked_sub(1).map(|previous| &measured[previous]) { + Some(previous) if previous.segment == entry.segment => (previous.distance, previous.t), + Some(previous) => (previous.distance, 0.), + None => (0., 0.), + }; + (entry.segment, start_t + (entry.t - start_t) * (distance - start_distance) / (entry.distance - start_distance)) +} + +fn piece(contour: &[PathSeg], measured: &[Measured], range: Range, dashes: &mut BezPath) { + let (start_segment, start_t) = at(measured, range.start); + let (end_segment, end_t) = at(measured, range.end); + dashes.move_to(contour[start_segment].eval(start_t)); + let mut push = |segment: usize, range: Range| match contour[segment].subsegment(range) { + PathSeg::Line(line) => dashes.line_to(line.p1), + PathSeg::Quad(quad) => dashes.quad_to(quad.p1, quad.p2), + PathSeg::Cubic(cubic) => dashes.curve_to(cubic.p1, cubic.p2, cubic.p3), + }; + if start_segment == end_segment { + push(start_segment, start_t..end_t); + return; + } + push(start_segment, start_t..1.); + for segment in start_segment + 1..end_segment { + push(segment, 0. ..1.); + } + push(end_segment, 0. ..end_t); +} + +enum BorderPart { + Line(DVec2, DVec2), + Corner(DVec2, f64), +} + +pub(crate) fn border(min: DVec2, max: DVec2, radius: f64, gaps: &[[DVec2; 2]], dashed: bool) -> BezPath { + let inset = BORDER_WIDTH / 2.; + let arc_radius = radius - inset; + let corner_length = flattened_arc_length(radius, [0., FRAC_PI_2]); + let [left, top] = (min + inset).to_array(); + let [right, bottom] = (max - inset).to_array(); + let parts = [ + BorderPart::Line(DVec2::new(left + arc_radius, top), DVec2::new(right - arc_radius, top)), + BorderPart::Corner(DVec2::new(right - arc_radius, top + arc_radius), -FRAC_PI_2), + BorderPart::Line(DVec2::new(right, top + arc_radius), DVec2::new(right, bottom - arc_radius)), + BorderPart::Corner(DVec2::new(right - arc_radius, bottom - arc_radius), 0.), + BorderPart::Line(DVec2::new(right - arc_radius, bottom), DVec2::new(left + arc_radius, bottom)), + BorderPart::Corner(DVec2::new(left + arc_radius, bottom - arc_radius), FRAC_PI_2), + BorderPart::Line(DVec2::new(left, bottom - arc_radius), DVec2::new(left, top + arc_radius)), + BorderPart::Corner(DVec2::new(left + arc_radius, top + arc_radius), PI), + ]; + let length = |part: &BorderPart| match part { + BorderPart::Line(from, to) => from.distance(*to), + BorderPart::Corner(..) => corner_length, + }; + let point = |part: &BorderPart, fraction: f64| match *part { + BorderPart::Line(from, to) => from.lerp(to, fraction), + BorderPart::Corner(center, start_angle) => center + arc_radius * DVec2::from_angle(start_angle + fraction * FRAC_PI_2), + }; + let starts: Vec = parts.iter().scan(0., |start, part| Some(std::mem::replace(start, *start + length(part)))).collect(); + let perimeter: f64 = parts.iter().map(length).sum(); + + let mut left_out: Vec<[f64; 2]> = parts + .iter() + .zip(&starts) + .flat_map(|(part, &start)| { + let straight = matches!(part, BorderPart::Line(..)); + let inside = gaps.iter().filter_map(move |&gap| fractions_inside(|fraction| point(part, fraction), straight, gap)); + inside.map(move |[from, to]| [start + from * length(part), start + to * length(part)]) + }) + .collect(); + left_out.sort_by(|a, b| a[0].total_cmp(&b[0])); + + let shown = if dashed { + let [dash, gap] = BORDER_DASHES; + let length = perimeter.floor(); + let fewer = (length / (dash + gap)).floor(); + let gaps = [fewer, fewer + 1.].map(|count| (length - count * dash) / count); + let (count, gap) = if gaps[1] > 0. && (gaps[1] - gap).abs() <= (gaps[0] - gap).abs() { + (fewer + 1., gaps[1]) + } else { + (fewer, gaps[0]) + }; + (0..count as usize).map(|index| [index as f64 * (dash + gap), index as f64 * (dash + gap) + dash]).collect() + } else { + vec![[0., perimeter]] + }; + let visible = shown.into_iter().flat_map(|[mut from, to]| { + let mut pieces = Vec::new(); + for &[gap_from, gap_to] in &left_out { + if gap_from < to && gap_to > from { + pieces.extend((gap_from > from).then_some([from, gap_from])); + from = from.max(gap_to); + } + } + pieces.extend((from < to).then_some([from, to])); + pieces + }); + + let mut border = BezPath::new(); + for [from, to] in visible { + let mut started = false; + for (part, start) in parts.iter().zip(&starts) { + if length(part) == 0. { + continue; + } + let [a, b] = [from, to].map(|at| ((at - start) / length(part)).clamp(0., 1.)); + if b <= a { + continue; + } + if !started { + border.move_to(<(f64, f64)>::from(point(part, a))); + started = true; + } + match *part { + BorderPart::Line(..) => border.line_to(<(f64, f64)>::from(point(part, b))), + BorderPart::Corner(center, start_angle) => { + border.extend(Arc::new(<(f64, f64)>::from(center), (arc_radius, arc_radius), start_angle + a * FRAC_PI_2, (b - a) * FRAC_PI_2, 0.).append_iter(ARC_TOLERANCE)) + } + } + } + } + border +} + +fn flattened_arc_length(radius: f64, [from, to]: [f64; 2]) -> f64 { + let point = |angle: f64| radius * DVec2::from_angle(angle); + let middle = (from + to) / 2.; + let bulge = point(middle) - (point(from) + point(to)) / 2.; + if bulge.abs().max_element() > MEASURE_TOLERANCE { + flattened_arc_length(radius, [from, middle]) + flattened_arc_length(radius, [middle, to]) + } else { + point(from).distance(point(to)) + } +} + +fn fractions_inside(point: impl Fn(f64) -> DVec2, straight: bool, [low, high]: [DVec2; 2]) -> Option<[f64; 2]> { + let mut range = [0_f64, 1_f64]; + for axis in 0..2 { + let value = |fraction: f64| point(fraction)[axis]; + let [start, end] = [value(0.), value(1.)]; + if start.min(end) > high[axis] || start.max(end) < low[axis] { + return None; + } + if start == end { + continue; + } + let fraction_at = |bound: f64| { + if (bound - start) * (end - start) <= 0. { + return 0.; + } + if (bound - end) * (end - start) >= 0. { + return 1.; + } + if straight { + return (bound - start) / (end - start); + } + let [mut before, mut after] = [0_f64, 1_f64]; + for _ in 0..f64::MANTISSA_DIGITS { + let middle = (before + after) / 2.; + if (value(middle) - bound) * (end - start) < 0. { + before = middle; + } else { + after = middle; + } + } + after + }; + let [a, b] = [fraction_at(low[axis]), fraction_at(high[axis])]; + range = [range[0].max(a.min(b)), range[1].min(a.max(b))]; + } + (range[0] < range[1]).then_some(range) +} diff --git a/node-graph/graph-ui/src/icons.rs b/node-graph/graph-ui/src/icons.rs new file mode 100644 index 0000000000..8df329a5df --- /dev/null +++ b/node-graph/graph-ui/src/icons.rs @@ -0,0 +1,90 @@ +// TODO(Timon): Replace with generalized icon crate + +use crate::card::DataType; +use crate::look::data_type_colors; +use crate::metrics::ICON_SIZE; +use core_types::bounds::{BoundingBox, RenderBoundingBox}; +use core_types::color::SRGBA8; +use core_types::list::List; +use glam::DAffine2; +use graphic_types::{IntoGraphicList, Vector}; +use std::collections::HashMap; +use std::fmt::Write; +use std::sync::{LazyLock, Mutex}; +use svg_convert::Options; + +#[derive(Clone)] +pub struct Icon { + pub(crate) shapes: List, + pub(crate) overflows: bool, +} + +type Converted = HashMap>>; + +static CONVERTED: LazyLock> = LazyLock::new(Mutex::default); + +pub fn icon(name: &str, current: SRGBA8) -> Option { + let mut converted = CONVERTED.lock().unwrap(); + let converted = converted.entry(current).or_default(); + if let Some(icon) = converted.get(name) { + return icon.clone(); + } + let icon = graph_ui_icons::svg(name).and_then(|svg| convert(svg, current)); + converted.insert(name.to_string(), icon.clone()); + icon +} + +fn convert(svg: &str, current: SRGBA8) -> Option { + let mut style_sheet = format!("svg {{ fill: {}; }}", hex_color(current)); + for (class, _) in svg.split("class=\"").skip(1).filter_map(|rest| rest.split_once('"')) { + write!(style_sheet, " .{class} {{ fill: {}; }}", hex_color(class_color(class)?)).unwrap(); + } + let options = Options { + style_sheet: Some(style_sheet), + ..Options::default() + }; + let shapes: List = svg_convert::convert(svg, &options).ok()?.into_flattened_list(); + + let overflows = match shapes.bounding_box(DAffine2::IDENTITY, false) { + RenderBoundingBox::Rectangle([min, max]) => min.min_element() < 0. || max.max_element() > ICON_SIZE, + RenderBoundingBox::Infinite => true, + RenderBoundingBox::None => false, + }; + Some(Icon { shapes, overflows }) +} + +fn hex_color(color: SRGBA8) -> String { + format!("#{:02x}{:02x}{:02x}", color.red, color.green, color.blue) +} + +fn class_color(class: &str) -> Option { + let token = class.strip_prefix("color-")?; + let Some(mix) = token.strip_prefix("mix-") else { return token_color(token) }; + let (pair, percent) = mix.rsplit_once('-')?; + let percent: u16 = percent.parse().ok().filter(|&percent| percent <= 100)?; + let (a, b) = pair.match_indices('-').find_map(|(index, _)| Some((token_color(&pair[..index])?, token_color(&pair[index + 1..])?)))?; + let mix = |a: u8, b: u8| ((u16::from(a) * (100 - percent) + u16::from(b) * percent + 50) / 100) as u8; + Some(SRGBA8::new_opaque(mix(a.red, b.red), mix(a.green, b.green), mix(a.blue, b.blue))) +} + +fn token_color(token: &str) -> Option { + if let Some((digit, _)) = token.split_once('-').filter(|(digit, _)| digit.len() == 1) { + let value = u8::from_str_radix(digit, 16).ok()? * 0x11; + return Some(SRGBA8::new_opaque(value, value, value)); + } + let (name, dim) = token.strip_suffix("-dim").map_or((token, false), |name| (name, true)); + let data_type = match name { + "general" => DataType::General, + "number" => DataType::Number, + "artboard" => DataType::Artboard, + "graphic" => DataType::Graphic, + "raster" => DataType::Raster, + "vector" => DataType::Vector, + "color" => DataType::Color, + "gradient" => DataType::Gradient, + "typography" => DataType::Typography, + _ => return None, + }; + let [bright, dimmed] = data_type_colors(data_type); + Some(if dim { dimmed } else { bright }) +} diff --git a/node-graph/graph-ui/src/lib.rs b/node-graph/graph-ui/src/lib.rs new file mode 100644 index 0000000000..e96fe0699b --- /dev/null +++ b/node-graph/graph-ui/src/lib.rs @@ -0,0 +1,12 @@ +use graph_ui_types::inputs; +pub use graph_ui_types::{GraphUiConfig, card, dot, error_badge, geometry, highlights, layer, metrics, network_connector, placed, replicated_map, scene, wire}; +pub use network::{network, render_config}; +pub use text::{error_text_size, label_width}; + +mod dashes; +pub mod icons; +mod look; +mod network; +pub mod nodes; +pub mod router; +mod text; diff --git a/node-graph/graph-ui/src/look.rs b/node-graph/graph-ui/src/look.rs new file mode 100644 index 0000000000..21d9e46d6b --- /dev/null +++ b/node-graph/graph-ui/src/look.rs @@ -0,0 +1,155 @@ +use crate::card::{Connector, DataType}; +use crate::highlights::Highlight; +use crate::icons; +use crate::metrics::{CHECKER_CELL, HOVERED_CONNECTOR_RING, HOVERED_CONNECTOR_SCALE, ICON_SIZE}; +use core_types::Color; +use core_types::color::SRGBA8; +use core_types::list::{Item, List}; +use core_types::transform::ApplyTransform; +use glam::{DAffine2, DVec2}; +use graphic_types::{CoverPlacement, Coverage, Graphic, Vector, stamp_coverage}; +use std::sync::LazyLock; +use vector_types::vector::algorithms::shapes::rounded_rectangle_bezpath; +use vector_types::vector::style::{Stroke, StrokeJoin}; +use vello_gpu::kurbo::{Affine, BezPath, Rect, Shape}; + +pub(crate) const CARD_OPACITY: f32 = 0.33; +pub(crate) const GRID_DOT_OPACITY: f32 = 0.2; +pub(crate) const BACKDROP: SRGBA8 = SRGBA8::new_opaque(0x22, 0x22, 0x22); +pub(crate) const SELECTED_DOT_RING_OPACITY: f32 = 0.5; +pub(crate) const BORDER: SRGBA8 = SRGBA8::new_opaque(0x55, 0x55, 0x55); +pub(crate) const PREVIEWED_BORDER: SRGBA8 = SRGBA8::new_opaque(0xee, 0xee, 0xee); +pub(crate) const TEXT: SRGBA8 = SRGBA8::new_opaque(0xee, 0xee, 0xee); +pub(crate) const LAYER_IN_INACTIVE_SELECTION: SRGBA8 = SRGBA8::new_opaque(0x55, 0x55, 0x55); +pub(crate) const LAYER_IN_ACTIVE_SELECTION: SRGBA8 = SRGBA8::new_opaque(0x66, 0x66, 0x66); +pub(crate) const HIDDEN_CARD: SRGBA8 = SRGBA8::new_opaque(0x44, 0x44, 0x44); +pub(crate) const HIDDEN_TEXT: SRGBA8 = SRGBA8::new_opaque(0xaa, 0xaa, 0xaa); +pub(crate) const SEPARATOR: SRGBA8 = SRGBA8::new_opaque(0x88, 0x88, 0x88); +pub(crate) const HOVERED_BUTTON: SRGBA8 = SRGBA8::new_opaque(0x55, 0x55, 0x55); +pub(crate) const DISABLED_ICON: SRGBA8 = SRGBA8::new_opaque(0x88, 0x88, 0x88); +pub(crate) const BOX_SELECTION: SRGBA8 = SRGBA8::new_opaque(0x00, 0xa8, 0xff); +pub(crate) const BOX_SELECTION_FILL_OPACITY: f32 = 0.05; +pub(crate) const ERROR_RED: SRGBA8 = SRGBA8::new_opaque(0xd6, 0x53, 0x6e); +pub(crate) const ERROR_TEXT: SRGBA8 = SRGBA8::new_opaque(0x22, 0x22, 0x22); +pub(crate) const ERROR_OPACITY: f64 = 0.5; +pub(crate) const WIRE_SPLIT: SRGBA8 = SRGBA8::new_opaque(0x44, 0x44, 0x44); +pub(crate) const THUMBNAIL_BACKGROUND: SRGBA8 = SRGBA8::new_opaque(0x22, 0x22, 0x22); +const CHECKER_LIGHT: SRGBA8 = SRGBA8::new_opaque(0xff, 0xff, 0xff); +const CHECKER_DARK: SRGBA8 = SRGBA8::new_opaque(0xcc, 0xcc, 0xcc); +pub(crate) const CIRCLE_TOLERANCE: f64 = 1e-3; + +pub(crate) static CONNECTOR_OUTLINE: LazyLock = LazyLock::new(|| parsed("M0,6.306A1.474,1.474,0,0,0,2.356,7.724L7.028,5.248c1.3-.687,1.3-1.809,0-2.5L2.356.276A1.474,1.474,0,0,0,0,1.694Z")); +pub(crate) static STACK_OUTPUT_OUTLINE: LazyLock = LazyLock::new(|| parsed("M0,6.953l2.521,-1.694a2.649,2.649,0,0,1,2.959,0l2.52,1.694v5.047h-8z")); +pub(crate) static STACK_INPUT_OUTLINE: LazyLock = LazyLock::new(|| parsed("M0,0H8V8L5.479,6.319a2.666,2.666,0,0,0-2.959,0L0,8Z")); +pub(crate) static STACK_OUTPUT_WIRE_END: LazyLock = LazyLock::new(|| { + parsed( + "M0,4.5 C0,4.5 0,-3.5 0,-3.5 C0,-3.5 3,-3.5 3,-3.5 C3,-3.5 3,2.565 3,2.565 C2.834,2.632 2.673,2.717 2.52,2.819 C2.52,2.819 0,4.5 0,4.5 Z\ + M5,2.566 C5,2.566 5,-3.5 5,-3.5 C5,-3.5 8,-3.5 8,-3.5 C8,-3.5 8,4.5 8,4.5 C8,4.5 5.479,2.819 5.479,2.819 C5.326,2.717 5.166,2.633 5,2.566 Z", + ) +}); +pub(crate) static STACK_INPUT_WIRE_END: LazyLock = LazyLock::new(|| { + parsed( + "M2.512,9.26 C2.673,9.157 2.834,9.072 3,9 C3,9 3,16 3,16 C3,16 0,16 0,16 C0,16 0,10.95 0,10.95 C0,10.95 2.512,9.26 2.512,9.26 Z\ + M5,16 C5,16 5,9 5,9 C5.166,9.073 5.327,9.158 5.48,9.26 C5.48,9.26 8,10.95 8,10.95 C8,10.95 8,16 8,16 C8,16 5,16 5,16 Z", + ) +}); + +fn parsed(path_data: &str) -> BezPath { + BezPath::from_svg(path_data).expect("A connector outline is valid path data") +} + +pub(crate) fn data_type_colors(data_type: DataType) -> [SRGBA8; 2] { + let colors = match data_type { + DataType::General => [0xcfcfcf, 0x8a8a8a], + DataType::Number => [0xc9a699, 0x886b60], + DataType::Artboard => [0xfbf9eb, 0xb9b9a9], + DataType::Graphic => [0x68c587, 0x37754c], + DataType::Raster => [0xe4bb72, 0x9a7b43], + DataType::Vector => [0x65bbe5, 0x417892], + DataType::Color => [0xce6ea7, 0x924071], + DataType::Gradient => [0xaf81eb, 0x6c489b], + DataType::Typography => [0xeea7a7, 0x955252], + DataType::Invalid => [0xd6536e, 0xa7324a], + }; + colors.map(|color| { + let [_, red, green, blue] = u32::to_be_bytes(color); + SRGBA8::new_opaque(red, green, blue) + }) +} + +pub(crate) fn connector(outline: &BezPath, top_left: DVec2, connector: &Connector, highlight: Highlight) -> List { + drawn_connector(outline, top_left, connector.data_type, connector.connected, highlight) +} + +pub(crate) fn drawn_connector(outline: &BezPath, top_left: DVec2, data_type: DataType, connected: bool, highlight: Highlight) -> List { + let [bright, dim] = data_type_colors(data_type); + match highlight { + Highlight::None => List::new_from_item(outlined(outline, top_left, if connected { bright } else { dim })), + Highlight::WireSource => List::new_from_item(outlined(outline, top_left, bright)), + Highlight::Hovered | Highlight::WireTarget => { + let grown = Affine::translate((top_left.x, top_left.y)) * Affine::scale_about(HOVERED_CONNECTOR_SCALE, outline.bounding_box().center()) * outline.clone(); + let grown = Vector::item_from_bezpath(&grown); + let ring = Stroke { + join: StrokeJoin::Round, + ..Stroke::new(HOVERED_CONNECTOR_RING * HOVERED_CONNECTOR_SCALE) + }; + List::from_iter([painted(grown.clone(), Coverage::new_stroke(&ring), dim.into()), painted(grown, Coverage::new_fill(), bright.into())]) + } + } +} + +pub(crate) fn outlined(outline: &BezPath, top_left: DVec2, color: SRGBA8) -> Item { + let mut outline = Vector::item_from_bezpath(outline); + outline.left_apply_transform(&DAffine2::from_translation(top_left)); + painted(outline, Coverage::new_fill(), color.into()) +} + +pub(crate) fn rounded_rect(min: DVec2, max: DVec2, radii: [f64; 4]) -> Item { + Vector::item_from_bezpath(&rounded_rectangle_bezpath(min, max, radii)) +} + +pub(crate) fn icon(name: &str, top_left: DVec2, current: SRGBA8) -> List { + let Some(icon) = icons::icon(name, current) else { return List::new() }; + let mut graphic = icon.shapes; + if icon.overflows { + let mut clip = rounded_rect(DVec2::ZERO, DVec2::splat(ICON_SIZE), [0.; 4]); + stamp_coverage(&mut clip, Coverage::new_fill(), Graphic::VectorList(graphic), CoverPlacement::Above); + graphic = List::new_from_item(clip); + } + graphic.left_apply_transform(&DAffine2::from_translation(top_left)); + graphic +} + +pub(crate) fn text(outline: &List, top_left: DVec2, color: SRGBA8) -> List { + let glyphs = outline.clone().into_iter(); + let mut glyphs: List = glyphs.map(|glyph| painted(glyph, Coverage::new_fill(), color.into())).collect(); + glyphs.left_apply_transform(&DAffine2::from_translation(top_left)); + glyphs +} + +pub(crate) fn checkerboard(min: DVec2, max: DVec2) -> List { + let mut dark = BezPath::new(); + let cells = ((max - min) / CHECKER_CELL).ceil().as_uvec2(); + for (column, row) in (0..cells.y) + .flat_map(|row| (0..cells.x).map(move |column| (column, row))) + .filter(|(column, row)| (column + row) % 2 == 1) + { + let cell_min = min + DVec2::new(column as f64, row as f64) * CHECKER_CELL; + let cell_max = (cell_min + CHECKER_CELL).min(max); + dark.extend(Rect::new(cell_min.x, cell_min.y, cell_max.x, cell_max.y).path_elements(0.)); + } + let light = painted(rounded_rect(min, max, [0.; 4]), Coverage::new_fill(), CHECKER_LIGHT.into()); + List::from_iter([light, painted(Vector::item_from_bezpath(&dark), Coverage::new_fill(), CHECKER_DARK.into())]) +} + +pub(crate) fn painted(mut item: Item, coverage: Coverage, color: Color) -> Item { + stamp_coverage(&mut item, coverage, Graphic::from(color), CoverPlacement::Above); + item +} + +pub(crate) fn image(content: Graphic, unit_square_to_place: DAffine2) -> Item { + let mut image = rounded_rect(DVec2::ZERO, DVec2::ONE, [0.; 4]); + image.left_apply_transform(&unit_square_to_place); + stamp_coverage(&mut image, Coverage::new_fill(), content, CoverPlacement::Above); + image +} diff --git a/node-graph/graph-ui/src/network.rs b/node-graph/graph-ui/src/network.rs new file mode 100644 index 0000000000..45e5939bee --- /dev/null +++ b/node-graph/graph-ui/src/network.rs @@ -0,0 +1,155 @@ +use crate::GraphUiConfig; +use crate::inputs::{self, TaggedGraphUiValue, Thumbnails}; +use crate::nodes::{ + draw_backdrop, draw_box_selection, draw_cards, draw_dots, draw_errors, draw_grid, draw_highlights, draw_layers, draw_loose_wires, draw_moving, draw_network_connectors, draw_raised, + draw_reorder_bar, draw_thick_wires, draw_thumbnails, draw_wires, texture_layer, +}; +use crate::scene::GraphUiScene; +use core_types::registry::{FieldMetadata, NODE_METADATA, RegistryValueSource}; +use core_types::transform::Footprint; +use core_types::{ContextFeatures, NodeCompileMetadata, ProtoNodeIdentifier}; +use glam::DAffine2; +use graph_craft::document::value::TaggedValue; +use graph_craft::document::{DocumentNode, DocumentNodeImplementation, DocumentNodeMetadata, NodeId, NodeInput, NodeNetwork}; +use graphene_std::application_io::{ExportFormat, RenderConfig}; +use graphene_std::graphic::extend; +use graphene_std::ops::passthrough; +use graphene_std::platform_application_io::wgpu_executor; +use graphene_std::render_cache::render_output_cache; +use graphene_std::render_node::{create_context, render, render_intermediate}; +use std::sync::Arc; + +pub fn network(scene: &GraphUiScene, config: &GraphUiConfig, thumbnails: &Thumbnails) -> NodeNetwork { + let layers = scene.settled().layers.iter().chain(&scene.moving().layers); + let layer_thumbnails = layers.filter_map(|layer| Some((layer.look.key, thumbnails.get(&layer.look.key)?.clone()))); + let values = [ + (inputs::SETTLED, TaggedGraphUiValue::Rows(scene.settled().clone())), + (inputs::MOVING, TaggedGraphUiValue::Rows(scene.moving().clone())), + (inputs::NETWORK_CONNECTORS, TaggedGraphUiValue::NetworkConnectors(scene.network_connectors().clone())), + (inputs::ERRORS, TaggedGraphUiValue::Errors(scene.errors().clone())), + (inputs::THUMBNAILS, TaggedGraphUiValue::Thumbnails(Arc::new(layer_thumbnails.collect()))), + (inputs::WIRE_IN_PROGRESS, TaggedGraphUiValue::WireInProgress(config.wire_in_progress)), + (inputs::REORDER_BAR, TaggedGraphUiValue::ReorderBar(config.reorder_bar)), + (inputs::BOX_SELECTION, TaggedGraphUiValue::BoxSelection(config.box_selection)), + (inputs::FADE_ARTWORK, TaggedGraphUiValue::FadeArtwork(config.fade_artwork)), + (inputs::WIRE_STYLE, TaggedGraphUiValue::WireStyle(config.wire_style)), + (inputs::HIGHLIGHTS, TaggedGraphUiValue::Highlights(config.highlights)), + ]; + + let mut network = NodeNetwork::default(); + for (scope, value) in values { + let ty = value.ty(); + let id = add(&mut network, node(passthrough::IDENTIFIER, vec![NodeInput::value(TaggedValue::GraphUi(value), false)])); + network.scope_injections.insert(scope.as_str().to_string(), (id, ty)); + } + + let [backdrop, above @ ..] = [ + drawn(&mut network, draw_backdrop::IDENTIFIER), + drawn(&mut network, draw_grid::IDENTIFIER), + tiled(&mut network, draw_thick_wires::IDENTIFIER, [draw_layers::IDENTIFIER]), + drawn(&mut network, draw_thumbnails::IDENTIFIER), + drawn(&mut network, draw_loose_wires::IDENTIFIER), + tiled(&mut network, draw_wires::IDENTIFIER, [draw_cards::IDENTIFIER, draw_dots::IDENTIFIER, draw_raised::IDENTIFIER]), + drawn(&mut network, draw_moving::IDENTIFIER), + drawn(&mut network, draw_errors::IDENTIFIER), + drawn(&mut network, draw_network_connectors::IDENTIFIER), + drawn(&mut network, draw_highlights::IDENTIFIER), + drawn(&mut network, draw_reorder_bar::IDENTIFIER), + drawn(&mut network, draw_box_selection::IDENTIFIER), + ]; + let stack = stacked(&mut network, backdrop, above); + let frame = rendered(&mut network, stack); + // INDEX is never read; it forces a nullification and cache pair onto the render's wire, so its memo keys on the footprint and the render params only + let compile_metadata = Some(NodeCompileMetadata { + extract: ContextFeatures::VARARGS | ContextFeatures::INDEX, + inject: ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, + ..Default::default() + }); + let create_context = DocumentNode { + compile_metadata, + ..node(create_context::IDENTIFIER, vec![NodeInput::node(frame, 0)]) + }; + let output = add(&mut network, create_context); + network.exports.push(NodeInput::node(output, 0)); + network +} + +pub fn render_config(view: DAffine2, request: RenderConfig) -> RenderConfig { + let translation = (view.translation * request.scale).round() / request.scale; + let viewport = Footprint { + transform: DAffine2 { translation, ..view }, + resolution: request.viewport.resolution, + ..Default::default() + }; + RenderConfig { + viewport, + scale: request.scale, + time: request.time, + export_format: ExportFormat::Raster, + ..Default::default() + } +} + +fn node(identifier: ProtoNodeIdentifier, inputs: Vec) -> DocumentNode { + DocumentNode { + implementation: DocumentNodeImplementation::ProtoNode(identifier), + inputs, + ..Default::default() + } +} + +fn add(network: &mut NodeNetwork, node: DocumentNode) -> NodeId { + let id = NodeId(u64::MAX - network.nodes.len() as u64); + network.nodes.insert(id, node); + id +} + +fn drawn(network: &mut NodeNetwork, identifier: ProtoNodeIdentifier) -> NodeId { + let scope = |field: &FieldMetadata| match &field.value_source { + RegistryValueSource::Scope(scope) => Ok(NodeInput::scope(*scope)), + source => Err(format!("The parameter {} of the drawing node {identifier} of the node graph reads {source:?}, not a scope", field.name)), + }; + let scopes = NODE_METADATA + .lock() + .unwrap() + .get(&identifier) + .map(|metadata| metadata.fields.iter().map(scope).collect::, _>>()); + let scopes = scopes.unwrap_or_else(|| panic!("The drawing node {identifier} of the node graph is not registered")); + let scopes = scopes.unwrap_or_else(|not_a_scope| panic!("{not_a_scope}")); + add(network, node(identifier, scopes)) +} + +fn stacked(network: &mut NodeNetwork, bottom: NodeId, above: impl IntoIterator) -> NodeId { + let over = |below, layer| add(network, node(extend::IDENTIFIER, vec![NodeInput::node(below, 0), NodeInput::node(layer, 0)])); + above.into_iter().fold(bottom, over) +} + +fn rendered(network: &mut NodeNetwork, content: NodeId) -> NodeId { + let intermediate = add(network, node(render_intermediate::IDENTIFIER, vec![NodeInput::node(content, 0)])); + let inputs = vec![ + NodeInput::node(intermediate, 0), + NodeInput::scope(wgpu_executor::IDENTIFIER), + NodeInput::scope("runtime"), + NodeInput::Reflection(DocumentNodeMetadata::SourceId), + ]; + add(network, node(render::IDENTIFIER, inputs)) +} + +fn tiled(network: &mut NodeNetwork, first: ProtoNodeIdentifier, rest: impl IntoIterator) -> NodeId { + let bottom = drawn(network, first); + let above: Vec = rest.into_iter().map(|identifier| drawn(network, identifier)).collect(); + let bands = stacked(network, bottom, above); + let region = rendered(network, bands); + // The cache's signature names the time and the pointer, which would put both into its key; it reads only the footprint and the render params + let compile_metadata = Some(NodeCompileMetadata { + extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, + inject: ContextFeatures::VARARGS, + ..Default::default() + }); + let cache = DocumentNode { + compile_metadata, + ..node(render_output_cache::IDENTIFIER, vec![NodeInput::node(region, 0), NodeInput::scope(wgpu_executor::IDENTIFIER)]) + }; + let cached = add(network, cache); + add(network, node(texture_layer::IDENTIFIER, vec![NodeInput::node(cached, 0)])) +} diff --git a/node-graph/graph-ui/src/nodes.rs b/node-graph/graph-ui/src/nodes.rs new file mode 100644 index 0000000000..b1dd8f5c45 --- /dev/null +++ b/node-graph/graph-ui/src/nodes.rs @@ -0,0 +1,627 @@ +use crate::card::{Card, Connector, DataType, Selection}; +use crate::dashes::{border, dashed}; +use crate::dot::Dot; +use crate::error_badge::{self, ErrorBadge}; +use crate::geometry::{WireEnd, is_thick_wire, node_geometry, wire_ends}; +use crate::highlights::{ConnectorKey, Highlight, Highlights}; +use crate::inputs::{self, Thumbnails}; +use crate::layer::{Layer, LayerButton}; +use crate::look::{ + BACKDROP, BORDER, BOX_SELECTION, BOX_SELECTION_FILL_OPACITY, CARD_OPACITY, CIRCLE_TOLERANCE, CONNECTOR_OUTLINE, DISABLED_ICON, ERROR_OPACITY, ERROR_RED, ERROR_TEXT, GRID_DOT_OPACITY, HIDDEN_CARD, + HIDDEN_TEXT, HOVERED_BUTTON, LAYER_IN_ACTIVE_SELECTION, LAYER_IN_INACTIVE_SELECTION, PREVIEWED_BORDER, SELECTED_DOT_RING_OPACITY, SEPARATOR, STACK_INPUT_OUTLINE, STACK_INPUT_WIRE_END, + STACK_OUTPUT_OUTLINE, STACK_OUTPUT_WIRE_END, TEXT, THUMBNAIL_BACKGROUND, WIRE_SPLIT, checkerboard, connector, data_type_colors, drawn_connector, icon, image, outlined, painted, rounded_rect, + text, +}; +use crate::metrics::{ + BORDER_WIDTH, CARD_ICON_LEFT, CARD_NAME_LEFT, CARD_NAME_MAX_WIDTH, CARD_RADIUS, CARD_ROW_PADDING, CONNECTOR_GAP, CONNECTOR_SIZE, DOT_HOVERED_RING, DOT_OUTPUT_ARROW, DOT_PREVIEWED_RING_OFFSET, + DOT_RADIUS, DOT_SELECTED_RING, ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH, ERROR_RADIUS, GRID_COLLAPSE_SPACING, GRID_SIZE, HOVERED_CONNECTOR_SCALE, ICON_SIZE, LAYER_BUTTON_RADIUS, LAYER_BUTTON_SIZE, + LAYER_GRIP_DOT_COUNT, LAYER_GRIP_DOT_RADIUS, LAYER_GRIP_DOT_SPACING, LAYER_GRIP_DOTS, LAYER_RADIUS, LAYER_THUMBNAIL_GAP, LAYER_THUMBNAIL_RADIUS, LIST_WIRE_WIDTH, THICK_WIRE_WIDTH, WIRE_DASHES, + WIRE_WIDTH, +}; +use crate::network_connector::{self, NetworkConnector, NetworkConnectorKey, NetworkConnectorKind}; +use crate::placed::Placed; +use crate::replicated_map::ReplicatedMap; +use crate::router::{build_thick_wire_center_line, route}; +use crate::scene::Rows; +use crate::text::{Labels, error_text_size, paragraph_outline}; +use crate::wire::{InputKey, OutputKey, Wire, WireInProgress, WireKey, WireStyle}; +use core_types::color::SRGBA8; +use core_types::list::{ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPREAD, ATTR_OPACITY, Item, List}; +use core_types::transform::ApplyTransform; +use core_types::{Color, Ctx, ExtractFootprint, ExtractVarArgs, Poll}; +use glam::{DAffine2, DVec2}; +use graph_craft::document::value::{RenderOutput, RenderOutputType}; +use graphic_types::raster_types::Raster; +use graphic_types::{CoverPlacement, Coverage, Graphic, Vector, stamp_coverage}; +use rendering::RenderParams; +use std::collections::{BTreeMap, BTreeSet}; +use text_nodes::TextToVectorError; +use vector_types::vector::style::Stroke; +use vector_types::{Gradient, GradientInterpolation, GradientSpread, GradientStop}; +use vello_gpu::kurbo::{BezPath, Circle, Rect, Shape, flatten}; + +const GRID_DOT_ROUNDING_BIAS: f64 = 1. / 64.; +const WIRE_FLATTENING_TOLERANCE: f64 = 0.02; + +#[node_macro::node(transient)] +fn draw_backdrop(ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, #[scope(inputs::FADE_ARTWORK)] fade_artwork: Item) -> List { + let (view, scale) = view_and_device_scale(&ctx); + let viewport_size = ctx.footprint().resolution.as_dvec2() / scale; + let opacity = fade_artwork.into_element() as f32; + let mut backdrop = painted(rounded_rect(DVec2::ZERO, viewport_size, [0.; 4]), Coverage::new_fill(), Color::from(BACKDROP).with_alpha(opacity)); + backdrop.left_apply_transform(&view.inverse()); + List::new_from_item(backdrop) +} + +fn view_and_device_scale(ctx: &(impl ExtractFootprint + ExtractVarArgs)) -> (DAffine2, f64) { + let render_params: Option<&RenderParams> = ctx.vararg(0).ok().and_then(|render_params| render_params.downcast_ref()); + let scale = render_params.expect("The render params are the first vararg").scale; + (DAffine2::from_scale(DVec2::splat(1. / scale)) * ctx.footprint().transform, scale) +} + +#[node_macro::node(transient)] +fn draw_grid(ctx: impl Ctx + ExtractFootprint + ExtractVarArgs) -> List { + let (view, scale) = view_and_device_scale(&ctx); + let viewport_size = ctx.footprint().resolution.as_dvec2() / scale; + let mut dots = grid_dots(view, viewport_size, scale); + dots.left_apply_transform(&view.inverse()); + dots +} + +fn grid_dots(view: DAffine2, viewport_size: DVec2, scale: f64) -> List { + let zoom = view.matrix2.x_axis.length(); + let mut spacing = zoom * GRID_SIZE; + if !spacing.is_finite() || spacing <= 0. { + return List::new(); + } + while spacing < GRID_COLLAPSE_SPACING { + spacing *= 2.; + } + let radius = ((1. + (zoom - 0.5 + 0.001).floor() / 2.) * scale).ceil() as u32; + let period = spacing * scale; + let origin = (view.translation * scale - radius as f64).rem_euclid(DVec2::splat(period)) - period - GRID_DOT_ROUNDING_BIAS; + + let dot_color = Color::WHITE.with_alpha(GRID_DOT_OPACITY); + let stop = |column: u32, color| GradientStop { + position: column as f64 / period, + midpoint: 0.5, + color, + }; + let mut dots = List::new(); + for ([top, bottom], runs) in disc_columns(radius) { + let mut bands = BezPath::new(); + for row in 0..=((viewport_size.y * scale - origin.y) / period).ceil() as u32 { + let y = (origin.y + row as f64 * period).round(); + bands.extend(Rect::new(0., (y + top as f64) / scale, viewport_size.x, (y + bottom as f64) / scale).path_elements(0.)); + } + + let start = runs[0][0]; + let stops = runs.iter().flat_map(|&[left, right]| [stop(left - start, dot_color), stop(right - start, Color::TRANSPARENT)]); + let mut columns = Item::new_from_element(Gradient::new(stops)); + columns.set_attribute(ATTR_GRADIENT_SPREAD, GradientSpread::Repeat); + columns.set_attribute(ATTR_GRADIENT_INTERPOLATION, GradientInterpolation::Stepped); + columns.left_apply_transform(&DAffine2::from_scale_angle_translation(DVec2::splat(spacing), 0., DVec2::new((origin.x + start as f64) / scale, 0.))); + + let mut group = Vector::item_from_bezpath(&bands); + stamp_coverage(&mut group, Coverage::new_fill(), Graphic::Gradient(columns), CoverPlacement::Above); + dots.push(group); + } + dots +} + +fn disc_columns(radius: u32) -> BTreeMap<[u32; 2], Vec<[u32; 2]>> { + let lit = |column: u32, row: u32| (DVec2::new(column as f64, row as f64) + 0.5 - radius as f64).length() < radius as f64; + let mut runs_by_rows = BTreeMap::<[u32; 2], Vec<[u32; 2]>>::new(); + for column in 0..2 * radius { + let top = (0..radius).take_while(|&row| !lit(column, row)).count() as u32; + let runs = runs_by_rows.entry([top, 2 * radius - top]).or_default(); + match runs.last_mut() { + Some(run) if run[1] == column => run[1] += 1, + _ => runs.push([column, column + 1]), + } + } + runs_by_rows +} + +#[node_macro::node(transient, memoize)] +fn draw_layers(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item) -> Result, TextToVectorError> { + layers(rows.element()) +} + +fn layers(rows: &Rows) -> Result, TextToVectorError> { + let mut labels = Labels::default(); + let mut graphic = List::new(); + for layer in &rows.layers { + graphic.extend(draw_layer(layer, &mut labels)?); + } + Ok(graphic) +} + +fn draw_layer(layer: &Placed, labels: &mut Labels) -> Result, TextToVectorError> { + let mut graphic = List::new(); + let [min, max] = layer.body(); + let fill = match (layer.look.selection, layer.look.visible) { + (Selection::Active, _) => LAYER_IN_ACTIVE_SELECTION.into(), + (Selection::Inactive, _) => LAYER_IN_INACTIVE_SELECTION.into(), + (Selection::None, true) => Color::BLACK, + (Selection::None, false) => HIDDEN_CARD.into(), + }; + graphic.push(painted(rounded_rect(min, max, [LAYER_RADIUS; 4]), Coverage::new_fill(), fill.with_alpha(CARD_OPACITY))); + + if !layer.look.renaming { + let [name, name_end] = layer.name_box(); + let text_color = if layer.look.visible { TEXT } else { HIDDEN_TEXT }; + graphic.extend(text(&labels.label(&layer.look.name, name_end.x - name.x)?.outline, name, text_color)); + } + + let [thumbnail_min, thumbnail_max] = layer.thumbnail(); + let thumbnail = rounded_rect(thumbnail_min, thumbnail_max, [LAYER_THUMBNAIL_RADIUS; 4]); + graphic.push(painted(thumbnail, Coverage::new_fill(), THUMBNAIL_BACKGROUND.into())); + let thumbnail_border = Vector::item_from_bezpath(&border(thumbnail_min, thumbnail_max, LAYER_THUMBNAIL_RADIUS, &[], false)); + graphic.push(painted(thumbnail_border, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), BORDER.into())); + let [image_min, image_max] = layer.thumbnail_image(); + graphic.extend(checkerboard(image_min, image_max)); + + if let Some(output) = &layer.look.primary_output { + graphic.extend(stack_output(layer, output, Highlight::None)); + } + match &layer.look.primary_input { + Some(input) => graphic.extend(stack_input(layer, input, Highlight::None)), + None => graphic.push(outlined(&STACK_INPUT_OUTLINE, layer.stack_input(), data_type_colors(DataType::General)[1])), + } + + let [block_min, block_max] = layer.thumbnail_block(); + let mut gaps = vec![[block_min - LAYER_THUMBNAIL_GAP, block_max + LAYER_THUMBNAIL_GAP], layer.visibility()]; + gaps.extend(layer.left_input_wire().map(|wire| [wire - CONNECTOR_GAP / 2., wire + CONNECTOR_GAP / 2.])); + let border = Vector::item_from_bezpath(&border(min, max, LAYER_RADIUS, &gaps, layer.look.previewed)); + let border_color = if layer.look.previewed { PREVIEWED_BORDER } else { BORDER }; + graphic.push(painted(border, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), border_color.into())); + Ok(graphic) +} + +fn stack_output(layer: &Placed, output: &Connector, highlight: Highlight) -> List { + let mut graphic = connector(&STACK_OUTPUT_OUTLINE, layer.stack_output(), output, highlight); + if output.connected && layer.look.primary_output_connected_to_layer && highlight != Highlight::WireSource { + graphic.push(outlined(&STACK_OUTPUT_WIRE_END, layer.stack_output(), data_type_colors(output.data_type)[1])); + } + graphic +} + +fn stack_input(layer: &Placed, input: &Connector, highlight: Highlight) -> List { + let mut graphic = connector(&STACK_INPUT_OUTLINE, layer.stack_input(), input, highlight); + if input.connected && layer.look.primary_input_connected_to_layer && highlight != Highlight::WireSource { + graphic.push(outlined(&STACK_INPUT_WIRE_END, layer.stack_input(), data_type_colors(input.data_type)[1])); + } + graphic +} + +#[node_macro::node(transient)] +fn draw_thumbnails(_: impl Ctx, #[scope(inputs::THUMBNAILS)] thumbnails: Item, #[scope(inputs::SETTLED)] rows: Item) -> List { + layer_thumbnails(thumbnails.element(), rows.element()) +} + +fn layer_thumbnails(thumbnails: &Thumbnails, rows: &Rows) -> List { + let thumbnails = thumbnails.iter().filter_map(|(key, thumbnail)| Some((rows.layers.get(key)?, thumbnail))); + thumbnails + .map(|(layer, thumbnail)| { + let [min, max] = layer.thumbnail_image(); + image(thumbnail.clone(), DAffine2::from_scale_angle_translation(max - min, 0., min)) + }) + .collect() +} + +#[node_macro::node(transient)] +fn texture_layer(ctx: impl Ctx + ExtractFootprint, rendered: Item) -> Poll> { + let RenderOutputType::Texture(texture) = rendered.into_element().data else { + return Poll::error("A layer of the node graph was not rendered into a texture"); + }; + let footprint = ctx.footprint(); + let viewport = footprint.transform.inverse() * DAffine2::from_scale(footprint.resolution.as_dvec2()); + let texture = Graphic::RasterGPU(Item::new_from_element(Raster::new_gpu(texture))); + Poll::Final(List::new_from_item(image(texture, viewport))) +} + +#[node_macro::node(transient, memoize)] +fn draw_raised(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item) -> List { + raised(rows.element()) +} + +fn raised(rows: &Rows) -> List { + let raised_parts_of_layers = rows.layers.iter().flat_map(draw_raised_parts_of_layer); + raised_parts_of_layers.chain(rows.cards.iter().flat_map(draw_connectors_of_card)).collect() +} + +fn draw_raised_parts_of_layer(layer: &Placed) -> List { + let mut graphic = List::new(); + if let Some(input) = &layer.look.secondary_input { + graphic.extend(connector(&CONNECTOR_OUTLINE, layer.secondary_input_connector(), input, Highlight::None)); + } + graphic.extend(grip(layer, false)); + for (_, place, icons) in layer_buttons(layer) { + graphic.extend(layer_button(layer, place, icons, false, false)); + } + graphic +} + +fn grip(layer: &Placed, hovered: bool) -> List { + let grip_color = match (hovered, layer.look.selection != Selection::None) { + (true, _) => Some(Color::WHITE), + (false, true) => Some(TEXT.into()), + (false, false) => None, + }; + let Some(grip_color) = grip_color else { return List::new() }; + let [grip, _] = layer.grip(); + let mut dots = BezPath::new(); + let [columns, rows] = LAYER_GRIP_DOT_COUNT; + for (column, row) in (0..rows).flat_map(|row| (0..columns).map(move |column| (column, row))) { + let center = grip + LAYER_GRIP_DOTS + DVec2::new(column as f64, row as f64) * LAYER_GRIP_DOT_SPACING; + dots.extend(Circle::new((center.x, center.y), LAYER_GRIP_DOT_RADIUS).path_elements(CIRCLE_TOLERANCE)); + } + List::new_from_item(painted(Vector::item_from_bezpath(&dots), Coverage::new_fill(), grip_color)) +} + +fn layer_buttons(layer: &Placed) -> impl Iterator { + let lock = layer.lock().map(|lock| (LayerButton::Lock, lock, ["PadlockLocked", "PadlockUnlocked"])); + let eye = if layer.look.visible { ["EyeVisible", "EyeHide"] } else { ["EyeHidden", "EyeShow"] }; + lock.into_iter().chain([(LayerButton::Visibility, layer.visibility(), eye)]) +} + +fn layer_button(layer: &Placed, [min, max]: [DVec2; 2], [resting, hover]: [&str; 2], hovered: bool, clicked: bool) -> List { + let mut graphic = List::new(); + if hovered { + graphic.push(painted(rounded_rect(min, max, [LAYER_BUTTON_RADIUS; 4]), Coverage::new_fill(), HOVERED_BUTTON.into())); + } + let name = if hovered && !clicked { hover } else { resting }; + graphic.extend(icon(name, min + (LAYER_BUTTON_SIZE - ICON_SIZE) / 2., if layer.look.read_only { DISABLED_ICON } else { TEXT })); + graphic +} + +fn draw_connectors_of_card(card: &Placed) -> List { + card.inputs() + .chain(card.outputs()) + .flat_map(|(top_left, input_or_output)| connector(&CONNECTOR_OUTLINE, top_left, input_or_output, Highlight::None)) + .collect() +} + +#[node_macro::node(transient, memoize)] +fn draw_thick_wires(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item, #[scope(inputs::WIRE_STYLE)] wire_style: Item) -> List { + settled_wires(rows.element(), wire_style.into_element(), true) +} + +#[node_macro::node(transient, memoize)] +fn draw_wires(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item, #[scope(inputs::WIRE_STYLE)] wire_style: Item) -> List { + settled_wires(rows.element(), wire_style.into_element(), false) +} + +fn settled_wires(rows: &Rows, wire_style: WireStyle, thick: bool) -> List { + let settled = [rows]; + let no_imports_or_exports = ReplicatedMap::default(); + let wires = wires_with_ends(&rows.wires, &settled, &no_imports_or_exports).filter(|(_, ends)| is_thick_wire(*ends) == thick); + wires.flat_map(|(wire, ends)| draw_wire(wire, ends, wire_style)).collect() +} + +#[node_macro::node(transient, memoize)] +fn draw_loose_wires( + _: impl Ctx, + #[scope(inputs::MOVING)] moving: Item, + #[scope(inputs::SETTLED)] settled: Item, + #[scope(inputs::NETWORK_CONNECTORS)] network_connectors: Item>, + #[scope(inputs::WIRE_IN_PROGRESS)] wire_in_progress: Item>, + #[scope(inputs::WIRE_STYLE)] wire_style: Item, +) -> List { + let wire_style = wire_style.into_element(); + let rows = [moving.element(), settled.element()]; + let loose = wires_with_ends(&moving.element().wires, &rows, network_connectors.element()); + let mut graphic = wire_in_progress.into_element().map_or_else(List::new, draw_wire_in_progress); + graphic.extend(loose.flat_map(|(wire, ends)| draw_wire(wire, ends, wire_style)).collect()); + graphic +} + +fn wires_with_ends<'a>(wires: &'a ReplicatedMap, rows: &'a [&'a Rows], network_connectors: &'a ReplicatedMap) -> impl Iterator { + wires.iter().filter_map(move |wire| Some((wire, wire_ends(wire, rows, network_connectors)?))) +} + +fn draw_wire(wire: &Wire, ends: [WireEnd; 2], wire_style: WireStyle) -> List { + let [bright, dim] = data_type_colors(wire.data_type); + let previewed = wire.key == WireKey::Preview; + let color = if previewed || wire.insertion_target { bright } else { dim }; + let stroke = |path: &BezPath, width: f64, color: SRGBA8| painted(Vector::item_from_bezpath(path), Coverage::new_stroke(&Stroke::new(width)), color.into()); + let drawn = |path: &BezPath| if previewed { flattened(&dashed(path, WIRE_DASHES)) } else { flattened(path) }; + let path = drawn(&route(ends, wire_style)); + if is_thick_wire(ends) { + let center_line = build_thick_wire_center_line(ends, wire_style); + List::from_iter([stroke(&path, THICK_WIRE_WIDTH, color), stroke(&drawn(¢er_line), WIRE_WIDTH, WIRE_SPLIT)]) + } else if wire.list { + List::from_iter([stroke(&path, LIST_WIRE_WIDTH, color), stroke(&path, WIRE_WIDTH, WIRE_SPLIT)]) + } else { + List::new_from_item(stroke(&path, WIRE_WIDTH, color)) + } +} + +fn draw_wire_in_progress(wire: WireInProgress) -> List { + let path = route(wire.ends, WireStyle::Direct); + if path.elements().len() != 4 { + return List::new(); + } + let [_, dim] = data_type_colors(wire.data_type); + let path = flattened(&path); + List::new_from_item(painted(Vector::item_from_bezpath(&path), Coverage::new_stroke(&Stroke::new(WIRE_WIDTH)), dim.into())) +} + +fn flattened(path: &BezPath) -> BezPath { + let mut lines = BezPath::new(); + flatten(path, WIRE_FLATTENING_TOLERANCE, |element| lines.push(element)); + lines +} + +#[node_macro::node(transient, memoize)] +fn draw_cards(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item) -> Result, TextToVectorError> { + cards(rows.element()) +} + +fn cards(rows: &Rows) -> Result, TextToVectorError> { + let mut labels = Labels::default(); + let mut graphic = List::new(); + for card in &rows.cards { + graphic.extend(draw_card(card, &mut labels)?); + } + Ok(graphic) +} + +fn draw_card(card: &Placed, labels: &mut Labels) -> Result, TextToVectorError> { + let mut graphic = List::new(); + let [min, max] = card.body(); + + let (card_color, text_color) = if card.look.visible { (Color::BLACK, TEXT) } else { (HIDDEN_CARD.into(), HIDDEN_TEXT) }; + let body = rounded_rect(min, max, [CARD_RADIUS; 4]); + graphic.push(painted(body, Coverage::new_fill(), card_color.with_alpha(CARD_OPACITY))); + + let (header_tint, rows_tint) = match card.look.selection { + Selection::None => (0.05, 0.), + Selection::Inactive => (0.15, 0.1), + Selection::Active => (0.2, 0.15), + }; + let header_bottom = if card.rows() == 1 { CARD_RADIUS } else { 0. }; + let header = rounded_rect(min, DVec2::new(max.x, min.y + GRID_SIZE), [CARD_RADIUS, CARD_RADIUS, header_bottom, header_bottom]); + graphic.push(painted(header, Coverage::new_fill(), Color::WHITE.with_alpha(header_tint))); + if card.look.selection != Selection::None && card.rows() > 1 { + let rows = rounded_rect(DVec2::new(min.x, min.y + GRID_SIZE), max, [0., 0., CARD_RADIUS, CARD_RADIUS]); + graphic.push(painted(rows, Coverage::new_fill(), Color::WHITE.with_alpha(rows_tint))); + } + graphic.extend(icon(card.look.icon, min + DVec2::new(CARD_ICON_LEFT, (GRID_SIZE - ICON_SIZE) / 2.), text_color)); + let name = labels.label(&card.look.name, CARD_NAME_MAX_WIDTH)?; + graphic.extend(text(&name.outline, min + DVec2::new(CARD_NAME_LEFT, 0.), text_color)); + + let width = max.x - min.x; + for row in 1..card.rows() as usize { + let (input, output) = (card.look.secondary_inputs.get(row - 1), card.look.secondary_outputs.get(row - 1)); + let Some(connector) = input.or(output) else { continue }; + let name = labels.label(&connector.name, width - 2. * CARD_ROW_PADDING)?; + let left = if input.is_some() { CARD_ROW_PADDING } else { width - CARD_ROW_PADDING - name.width }; + graphic.extend(text(&name.outline, min + DVec2::new(left, row as f64 * GRID_SIZE), text_color)); + } + + let border_color = if card.look.previewed { PREVIEWED_BORDER } else { BORDER }; + let gap = |edge: f64, (top_left, _): (DVec2, &Connector)| { + let center = DVec2::new(edge, top_left.y + CONNECTOR_SIZE / 2.); + [center - CONNECTOR_GAP / 2., center + CONNECTOR_GAP / 2.] + }; + let gaps: Vec<[DVec2; 2]> = card.inputs().map(|input| gap(min.x, input)).chain(card.outputs().map(|output| gap(max.x, output))).collect(); + let border = Vector::item_from_bezpath(&border(min, max, CARD_RADIUS, &gaps, card.look.previewed)); + graphic.push(painted(border, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), border_color.into())); + Ok(graphic) +} + +#[node_macro::node(transient, memoize)] +fn draw_dots(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item) -> List { + dots(rows.element()) +} + +fn dots(rows: &Rows) -> List { + rows.dots.iter().flat_map(|dot| draw_dot(dot, [Highlight::None; 2])).collect() +} + +#[node_macro::node(transient, memoize)] +fn draw_moving(_: impl Ctx, #[scope(inputs::MOVING)] moving: Item, #[scope(inputs::THUMBNAILS)] thumbnails: Item) -> Result, TextToVectorError> { + let moving = moving.element(); + let mut graphic = layers(moving)?; + graphic.extend(layer_thumbnails(thumbnails.element(), moving)); + graphic.extend(cards(moving)?); + graphic.extend(dots(moving)); + graphic.extend(raised(moving)); + Ok(graphic) +} + +fn draw_dot(dot: &Placed, [highlight, output_highlight]: [Highlight; 2]) -> List { + let [wired, unwired] = data_type_colors(dot.look.data_type); + let center = dot.center(); + let grown = matches!(highlight, Highlight::Hovered | Highlight::WireTarget); + let scale = if grown { HOVERED_CONNECTOR_SCALE } else { 1. }; + let circle = |radius: f64| Vector::item_from_bezpath(&Circle::new((center.x, center.y), radius * scale).to_path(CIRCLE_TOLERANCE)); + let output_shown = output_highlight != Highlight::None; + let fill = if dot.look.wired && !output_shown { wired } else { unwired }; + let mut graphic = List::new_from_item(painted(circle(DOT_RADIUS), Coverage::new_fill(), fill.into())); + let resting = [highlight, output_highlight] == [Highlight::None; 2]; + + if grown { + let offset = if dot.look.previewed { DOT_PREVIEWED_RING_OFFSET } else { 0. }; + let ring = circle(DOT_RADIUS + offset + DOT_HOVERED_RING / 2.); + graphic.push(painted(ring, Coverage::new_stroke(&Stroke::new(DOT_HOVERED_RING * scale)), unwired.into())); + } else if resting && dot.look.previewed { + let radius = DOT_RADIUS + DOT_PREVIEWED_RING_OFFSET + BORDER_WIDTH; + let ring = Vector::item_from_bezpath(&border(center - radius, center + radius, radius, &[], true)); + graphic.push(painted(ring, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), wired.into())); + } else if resting && dot.look.selected { + let ring = circle(DOT_RADIUS + DOT_SELECTED_RING / 2.); + graphic.push(painted(ring, Coverage::new_stroke(&Stroke::new(DOT_SELECTED_RING)), Color::WHITE.with_alpha(SELECTED_DOT_RING_OPACITY))); + } + + if output_shown { + graphic.extend(drawn_connector(&CONNECTOR_OUTLINE, center + DOT_OUTPUT_ARROW, dot.look.data_type, true, output_highlight)); + } + graphic +} + +#[node_macro::node(transient, memoize)] +fn draw_errors( + _: impl Ctx, + #[scope(inputs::ERRORS)] errors: Item>, + #[scope(inputs::MOVING)] moving: Item, + #[scope(inputs::SETTLED)] settled: Item, +) -> Result, TextToVectorError> { + let rows = [moving.element(), settled.element()]; + badges_with_anchors(errors.element().iter(), rows).map(|(error, anchor)| draw_error(error, anchor, false)).collect() +} + +fn badges_with_anchors<'a>(errors: impl Iterator, rows: [&'a Rows; 2]) -> impl Iterator { + errors.filter_map(move |error| Some((error, node_geometry(&rows, &error.key)?.error_badge_anchor()))) +} + +fn draw_error(error: &ErrorBadge, anchor: DVec2, hovered: bool) -> Result, TextToVectorError> { + let text_size = error_text_size(&error.text); + let [min, max] = error_badge::body(anchor, text_size); + let mut badge = List::new_from_item(painted(rounded_rect(min, max, [ERROR_RADIUS; 4]), Coverage::new_fill(), ERROR_RED.into())); + let corners = error_badge::tail(anchor); + let mut tail = BezPath::new(); + tail.move_to((corners[0].x, corners[0].y)); + for corner in &corners[1..] { + tail.line_to((corner.x, corner.y)); + } + tail.close_path(); + badge.push(painted(Vector::item_from_bezpath(&tail), Coverage::new_fill(), ERROR_RED.into())); + + let outline = paragraph_outline(&error.text, ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH)?; + badge.extend(text(&outline, error_badge::text_top_left(anchor, text_size), ERROR_TEXT)); + + let mut grouped = rounded_rect(min, corners.into_iter().fold(max, DVec2::max), [0.; 4]); + stamp_coverage(&mut grouped, Coverage::new_fill(), Graphic::VectorList(badge), CoverPlacement::Above); + if !hovered { + grouped.set_attribute(ATTR_OPACITY, ERROR_OPACITY); + } + Ok(grouped) +} + +#[node_macro::node(transient, memoize)] +fn draw_network_connectors(_: impl Ctx, #[scope(inputs::NETWORK_CONNECTORS)] network_connectors: Item>) -> Result, TextToVectorError> { + let mut labels = Labels::default(); + let mut graphic = List::new(); + for row in network_connectors.element() { + graphic.extend(draw_network_connector(row, &mut labels)?); + } + Ok(graphic) +} + +fn draw_network_connector(row: &NetworkConnector, labels: &mut Labels) -> Result, TextToVectorError> { + let mut graphic = row_connector(row, Highlight::None); + let Some(entry) = &row.connector else { return Ok(graphic) }; + let name = labels.label(&entry.name, f64::INFINITY)?; + if !row.renaming { + let [top_left, _] = row.name_box(name.width); + graphic.extend(text(&name.outline, top_left, TEXT)); + } + if row.editable && row.key.index() < 2 { + let [min, max] = row.separator(name.width); + graphic.push(painted(rounded_rect(min, max, [0.; 4]), Coverage::new_fill(), SEPARATOR.into())); + } + Ok(graphic) +} + +fn row_connector(row: &NetworkConnector, highlight: Highlight) -> List { + match &row.connector { + Some(entry) => connector(&CONNECTOR_OUTLINE, row.connector_top_left(), entry, highlight), + None => drawn_connector(&CONNECTOR_OUTLINE, row.connector_top_left(), DataType::General, false, highlight), + } +} + +#[node_macro::node(transient, memoize)] +fn draw_highlights( + _: impl Ctx, + #[scope(inputs::HIGHLIGHTS)] highlights: Item, + #[scope(inputs::MOVING)] moving: Item, + #[scope(inputs::SETTLED)] settled: Item, + #[scope(inputs::NETWORK_CONNECTORS)] network_connectors: Item>, + #[scope(inputs::ERRORS)] errors: Item>, +) -> Result, TextToVectorError> { + let highlights = highlights.into_element(); + let rows = [moving.element(), settled.element()]; + let mut graphic = List::new(); + for dot in rows.iter().flat_map(|rows| &rows.dots) { + let looks = highlights.dot(dot.look.key); + if looks != [Highlight::None; 2] { + graphic.extend(draw_dot(dot, looks)); + } + } + let connectors: BTreeSet = highlights.connectors().collect(); + for key in connectors { + if let Some(drawn) = highlighted_connector(key, highlights.connector(key), rows, network_connectors.element()) { + graphic.extend(drawn); + } + } + for layer in rows.iter().flat_map(|rows| &rows.layers) { + match highlights.layer_button(layer.look.key) { + Some(LayerButton::Grip) => graphic.extend(grip(layer, true)), + Some(hovered) if !layer.look.read_only => { + for (_, place, icons) in layer_buttons(layer).filter(|(button, ..)| *button == hovered) { + graphic.extend(layer_button(layer, place, icons, true, highlights.clicked)); + } + } + _ => {} + } + } + let hovered = errors.element().iter().filter(|error| highlights.badge_hovered(error.key)); + for (error, anchor) in badges_with_anchors(hovered, rows) { + graphic.push(draw_error(error, anchor, true)?); + } + Ok(graphic) +} + +fn highlighted_connector(key: ConnectorKey, highlight: Highlight, rows: [&Rows; 2], network_connectors: &ReplicatedMap) -> Option> { + let card = |node| rows.into_iter().find_map(|rows| rows.cards.get(&node)); + let layer = |node| rows.into_iter().find_map(|rows| rows.layers.get(&node)); + let indexed = |index: usize| move |found: &&Connector| found.index as usize == index; + let on_card = |(top_left, found): (DVec2, &Connector)| connector(&CONNECTOR_OUTLINE, top_left, found, highlight); + match key { + ConnectorKey::Input(InputKey::Node { node, index }) => { + if let Some(card) = card(node) { + return card.inputs().find(|(_, input)| indexed(index)(input)).map(on_card); + } + let layer = layer(node)?; + if let Some(input) = layer.look.primary_input.as_ref().filter(indexed(index)) { + return Some(stack_input(layer, input, highlight)); + } + let input = layer.look.secondary_input.as_ref().filter(indexed(index))?; + Some(connector(&CONNECTOR_OUTLINE, layer.secondary_input_connector(), input, highlight)) + } + ConnectorKey::Output(OutputKey::Node { node, index }) => { + if let Some(card) = card(node) { + return card.outputs().find(|(_, output)| indexed(index)(output)).map(on_card); + } + let layer = layer(node)?; + layer.look.primary_output.as_ref().filter(indexed(index)).map(|output| stack_output(layer, output, highlight)) + } + ConnectorKey::Input(InputKey::Export(index)) => Some(row_connector(network_connectors.get(&NetworkConnectorKey::Export(index))?, highlight)), + ConnectorKey::Output(OutputKey::Import(index)) => Some(row_connector(network_connectors.get(&NetworkConnectorKey::Import(index))?, highlight)), + } +} + +#[node_macro::node(transient)] +fn draw_reorder_bar(_: impl Ctx, #[scope(inputs::REORDER_BAR)] reorder_bar: Item>) -> List { + let Some((kind, anchor)) = reorder_bar.into_element() else { return List::new() }; + let [min, max] = network_connector::reorder_bar(kind, anchor); + List::new_from_item(painted(rounded_rect(min, max, [0.; 4]), Coverage::new_fill(), Color::WHITE)) +} + +#[node_macro::node(transient)] +fn draw_box_selection(ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, #[scope(inputs::BOX_SELECTION)] box_selection: Item>) -> List { + let Some([start, end]) = box_selection.into_element() else { return List::new() }; + let min = start.min(end); + let max = min + (end - start).abs() + 2. * BORDER_WIDTH; + let fill = painted(rounded_rect(min, max, [0.; 4]), Coverage::new_fill(), Color::from(BOX_SELECTION).with_alpha(BOX_SELECTION_FILL_OPACITY)); + let [inner_min, inner_max] = [min + BORDER_WIDTH / 2., max - BORDER_WIDTH / 2.]; + let outline = Rect::new(inner_min.x, inner_min.y, inner_max.x, inner_max.y).to_path(0.); + let border = painted(Vector::item_from_bezpath(&outline), Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), BOX_SELECTION.into()); + let (view, _) = view_and_device_scale(&ctx); + let mut selection = List::from_iter([fill, border]); + selection.left_apply_transform(&view.inverse()); + selection +} diff --git a/node-graph/graph-ui/src/router.rs b/node-graph/graph-ui/src/router.rs new file mode 100644 index 0000000000..51a23ae4c4 --- /dev/null +++ b/node-graph/graph-ui/src/router.rs @@ -0,0 +1,521 @@ +use crate::geometry::{WireEnd, is_thick_wire}; +use crate::metrics::GRID_SIZE; +use crate::wire::WireStyle; +use glam::{DVec2, IVec2}; +use graphene_std::vector::misc::dvec2_to_point; +use vello_gpu::kurbo::{BezPath, DEFAULT_ACCURACY, Line, ParamCurve, Point, Shape, Vec2}; + +pub fn route(ends: [WireEnd; 2], wire_style: WireStyle) -> BezPath { + let [output_position, input_position] = ends.map(|end| end.position); + let [vertical_out, vertical_in] = ends.map(|end| end.vertical); + + let (output_position, input_position) = if is_thick_wire(ends) { + if thick_wire_spans_single_cell(output_position, input_position) { + return BezPath::new(); + } + let trim = 3. * (input_position.y - output_position.y).signum(); + (output_position + DVec2::new(0., trim), input_position - DVec2::new(0., trim)) + } else { + (output_position, input_position) + }; + + match wire_style { + WireStyle::Direct => { + let horizontal_gap = (output_position.x - input_position.x).abs(); + let vertical_gap = (output_position.y - input_position.y).abs(); + + let curve_length = GRID_SIZE; + let curve_falloff_rate = curve_length * std::f64::consts::TAU; + + let horizontal_curve_amount = -(2_f64.powf((-10. * horizontal_gap) / curve_falloff_rate)) + 1.; + let vertical_curve_amount = -(2_f64.powf((-10. * vertical_gap) / curve_falloff_rate)) + 1.; + let horizontal_curve = horizontal_curve_amount * curve_length; + let vertical_curve = vertical_curve_amount * curve_length; + + let locations = [ + output_position, + DVec2::new( + if vertical_out { output_position.x } else { output_position.x + horizontal_curve }, + if vertical_out { output_position.y - vertical_curve } else { output_position.y }, + ), + DVec2::new( + if vertical_in { input_position.x } else { input_position.x - horizontal_curve }, + if vertical_in { input_position.y + vertical_curve } else { input_position.y }, + ), + DVec2::new(input_position.x, input_position.y), + ]; + + let smoothing = 0.5; + let delta01 = DVec2::new((locations[1].x - locations[0].x) * smoothing, (locations[1].y - locations[0].y) * smoothing); + let delta23 = DVec2::new((locations[3].x - locations[2].x) * smoothing, (locations[3].y - locations[2].y) * smoothing); + + let mut wire = BezPath::new(); + wire.move_to(dvec2_to_point(locations[0])); + wire.line_to(dvec2_to_point(locations[1])); + wire.curve_to(dvec2_to_point(locations[1] + delta01), dvec2_to_point(locations[2] - delta23), dvec2_to_point(locations[2])); + wire.line_to(dvec2_to_point(locations[3])); + wire + } + WireStyle::GridAligned => { + let locations = straight_wire_path(output_position, input_position, vertical_out, vertical_in); + straight_wire_to_bezpath(locations) + } + } +} + +fn thick_wire_spans_single_cell(output_position: DVec2, input_position: DVec2) -> bool { + (output_position.x - input_position.x).abs() < 1. && (output_position.y - input_position.y).abs() <= GRID_SIZE +} + +/// The center line that cleaves a thick layer-stack wire, following its path. Its ends reach past the wire (1.5px toward the +/// output connector and 2px toward the input) so the color runs through the full cleaved connector slots. +pub(crate) fn build_thick_wire_center_line(ends: [WireEnd; 2], wire_style: WireStyle) -> BezPath { + let [output_position, input_position] = ends.map(|end| end.position); + if thick_wire_spans_single_cell(output_position, input_position) { + return BezPath::new(); + } + + let wire = route(ends, wire_style); + let (Some(start), Some(end)) = (wire.segments().next().map(|segment| segment.start()), wire.segments().last().map(|segment| segment.end())) else { + return BezPath::new(); + }; + + // The 8px wire trims 3px at each end, so the center line reaches further out to trim 1.5px and 1px instead + let sign = (input_position.y - output_position.y).signum(); + let mut center_line = BezPath::new(); + center_line.move_to(start - Vec2::new(0., 1.5 * sign)); + center_line.line_to(start); + for element in wire.elements().iter().skip(1) { + center_line.push(*element); + } + center_line.line_to(end + Vec2::new(0., 2. * sign)); + center_line +} + +fn straight_wire_path(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool) -> Vec { + let grid_spacing = GRID_SIZE as i32; + let line_width = 2; + + let in_x = input_position.x.floor() as i32; + let in_y = input_position.y.floor() as i32; + let out_x = output_position.x.floor() as i32; + let out_y = output_position.y.floor() as i32; + + let mid_x = (in_x + out_x).div_euclid(2) + (in_x + out_x).div_euclid(2).rem_euclid(grid_spacing); + let mid_y = (in_y + out_y).div_euclid(2) + (in_y + out_y).div_euclid(2).rem_euclid(grid_spacing); + let mid_y_alternate = in_y - in_y.rem_euclid(grid_spacing); + + let x1 = out_x; + let x2 = out_x + grid_spacing; + let x3 = in_x - 2 * grid_spacing; + let x4 = in_x; + let x5 = in_x - 2 * grid_spacing + line_width; + let x6 = out_x + grid_spacing + line_width; + let x7 = out_x + 2 * grid_spacing + line_width; + let x8 = in_x + line_width; + let x9 = out_x + 2 * grid_spacing; + let x10 = mid_x + line_width; + let x11 = out_x - grid_spacing; + let x12 = out_x - 4 * grid_spacing; + let x13 = mid_x; + let x14 = in_x + grid_spacing; + let x15 = in_x - 4 * grid_spacing; + let x16 = in_x + 8 * grid_spacing; + let x17 = mid_x - 2 * line_width; + let x18 = out_x + grid_spacing - 2 * line_width; + let x19 = out_x - 2 * line_width; + let x20 = mid_x - line_width; + + let y1 = out_y; + let y2 = out_y - grid_spacing; + let y3 = in_y; + let y4 = out_y - grid_spacing + 5 * line_width + 1; + let y5 = in_y - 2 * grid_spacing; + let y6 = out_y + 4 * line_width; + let y7 = out_y + 5 * line_width; + let y8 = out_y - 2 * grid_spacing + 5 * line_width + 1; + let y9 = out_y + 6 * line_width; + let y10 = in_y + 2 * grid_spacing; + let y111 = in_y + grid_spacing + 6 * line_width + 1; + let y12 = in_y + grid_spacing - 5 * line_width + 1; + let y13 = in_y - grid_spacing; + let y14 = in_y + grid_spacing; + let y15 = mid_y; + let y16 = mid_y_alternate; + + let wire1 = vec![IVec2::new(x1, y1), IVec2::new(x1, y4), IVec2::new(x5, y4), IVec2::new(x5, y3), IVec2::new(x4, y3)]; + + let wire2 = vec![IVec2::new(x1, y1), IVec2::new(x1, y16), IVec2::new(x3, y16), IVec2::new(x3, y3), IVec2::new(x4, y3)]; + + let wire3 = vec![ + IVec2::new(x1, y1), + IVec2::new(x1, y4), + IVec2::new(x12, y4), + IVec2::new(x12, y10), + IVec2::new(x3, y10), + IVec2::new(x3, y3), + IVec2::new(x4, y3), + ]; + + let wire4 = vec![ + IVec2::new(x1, y1), + IVec2::new(x1, y4), + IVec2::new(x13, y4), + IVec2::new(x13, y10), + IVec2::new(x3, y10), + IVec2::new(x3, y3), + IVec2::new(x4, y3), + ]; + + // `outConnector` point and `inConnector` point lying on the same horizontal grid line and `outConnector` point lies to the right of `inConnector` point + if out_y == in_y && out_x > in_x && (vertical_out || !vertical_in) { + return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y2), IVec2::new(x3, y2), IVec2::new(x3, y3), IVec2::new(x4, y3)]; + }; + + // Handle straight lines + if out_y == in_y || (out_x == in_x && vertical_out) { + return vec![IVec2::new(x1, y1), IVec2::new(x4, y3)]; + }; + + // Handle standard right-angle paths + // Start vertical, then horizontal + + // `outConnector` point lies to the left of `inConnector` point + if vertical_out && in_x > out_x { + // `outConnector` point lies above `inConnector` point + if out_y < in_y { + // `outConnector` point lies on the vertical grid line 4 units to the left of `inConnector` point point + if -4 * grid_spacing <= out_x - in_x && out_x - in_x < -3 * grid_spacing { + return wire1; + }; + + // `outConnector` point lying on vertical grid lines 3 and 2 units to the left of `inConnector` point + if -3 * grid_spacing <= out_x - in_x && out_x - in_x <= -grid_spacing { + if -2 * grid_spacing <= out_y - in_y && out_y - in_y <= -grid_spacing { + return vec![IVec2::new(x1, y1), IVec2::new(x1, y2), IVec2::new(x2, y2), IVec2::new(x2, y3), IVec2::new(x4, y3)]; + }; + + if -grid_spacing <= out_y - in_y && out_y - in_y <= 0 { + return vec![IVec2::new(x1, y1), IVec2::new(x1, y4), IVec2::new(x6, y4), IVec2::new(x6, y3), IVec2::new(x4, y3)]; + }; + + return vec![ + IVec2::new(x1, y1), + IVec2::new(x1, y4), + IVec2::new(x7, y4), + IVec2::new(x7, y5), + IVec2::new(x3, y5), + IVec2::new(x3, y3), + IVec2::new(x4, y3), + ]; + } + + // `outConnector` point lying on vertical grid line 1 units to the left of `inConnector` point + if -grid_spacing < out_x - in_x && out_x - in_x <= 0 { + // `outConnector` point lying on horizontal grid line 1 unit above `inConnector` point + if -2 * grid_spacing <= out_y - in_y && out_y - in_y <= -grid_spacing { + return vec![IVec2::new(x1, y6), IVec2::new(x2, y6), IVec2::new(x8, y3)]; + }; + + // `outConnector` point lying on the same horizontal grid line as `inConnector` point + if -grid_spacing <= out_y - in_y && out_y - in_y <= 0 { + return vec![IVec2::new(x1, y7), IVec2::new(x4, y3)]; + }; + + return vec![ + IVec2::new(x1, y1), + IVec2::new(x1, y2), + IVec2::new(x9, y2), + IVec2::new(x9, y5), + IVec2::new(x3, y5), + IVec2::new(x3, y3), + IVec2::new(x4, y3), + ]; + } + + return vec![IVec2::new(x1, y1), IVec2::new(x1, y4), IVec2::new(x10, y4), IVec2::new(x10, y3), IVec2::new(x4, y3)]; + } + + // `outConnector` point lies below `inConnector` point + // `outConnector` point lying on vertical grid line 1 unit to the left of `inConnector` point + if -grid_spacing <= out_x - in_x && out_x - in_x <= 0 { + // `outConnector` point lying on the horizontal grid lines 1 and 2 units below the `inConnector` point + if 0 <= out_y - in_y && out_y - in_y <= 2 * grid_spacing { + return vec![IVec2::new(x1, y6), IVec2::new(x11, y6), IVec2::new(x11, y3), IVec2::new(x4, y3)]; + }; + + return wire2; + } + + return vec![IVec2::new(x1, y1), IVec2::new(x1, y3), IVec2::new(x4, y3)]; + } + + // `outConnector` point lies to the right of `inConnector` point + if vertical_out && in_x <= out_x { + // `outConnector` point lying on any horizontal grid line above `inConnector` point + if out_y < in_y { + // `outConnector` point lying on horizontal grid line 1 unit above `inConnector` point + if -2 * grid_spacing < out_y - in_y && out_y - in_y <= -grid_spacing { + return wire1; + }; + + // `outConnector` point lying on the same horizontal grid line as `inConnector` point + if -grid_spacing < out_y - in_y && out_y - in_y <= 0 { + return vec![IVec2::new(x1, y1), IVec2::new(x1, y8), IVec2::new(x5, y8), IVec2::new(x5, y3), IVec2::new(x4, y3)]; + }; + + // `outConnector` point lying on vertical grid lines 1 and 2 units to the right of `inConnector` point + if grid_spacing <= out_x - in_x && out_x - in_x <= 3 * grid_spacing { + return vec![ + IVec2::new(x1, y1), + IVec2::new(x1, y4), + IVec2::new(x9, y4), + IVec2::new(x9, y5), + IVec2::new(x3, y5), + IVec2::new(x3, y3), + IVec2::new(x4, y3), + ]; + } + + return vec![ + IVec2::new(x1, y1), + IVec2::new(x1, y4), + IVec2::new(x10, y4), + IVec2::new(x10, y5), + IVec2::new(x5, y5), + IVec2::new(x5, y3), + IVec2::new(x4, y3), + ]; + } + + // `outConnector` point lies below `inConnector` point + if out_y - in_y <= grid_spacing { + // `outConnector` point lies on the horizontal grid line 1 unit below the `inConnector` Point + if 0 <= out_x - in_x && out_x - in_x <= 13 * grid_spacing { + return vec![IVec2::new(x1, y9), IVec2::new(x3, y9), IVec2::new(x3, y3), IVec2::new(x4, y3)]; + }; + + if 13 < out_x - in_x && out_x - in_x <= 18 * grid_spacing { + return wire3; + }; + + return wire4; + } + + // `outConnector` point lies on the horizontal grid line 2 units below `outConnector` point + if grid_spacing <= out_y - in_y && out_y - in_y <= 2 * grid_spacing { + if 0 <= out_x - in_x && out_x - in_x <= 13 * grid_spacing { + return vec![IVec2::new(x1, y7), IVec2::new(x5, y7), IVec2::new(x5, y3), IVec2::new(x4, y3)]; + }; + + if 13 < out_x - in_x && out_x - in_x <= 18 * grid_spacing { + return wire3; + }; + + return wire4; + } + + // 0 to 4 units below the `outConnector` Point + if out_y - in_y <= 4 * grid_spacing { + return wire1; + }; + + return wire2; + } + + // Start horizontal, then vertical + if vertical_in { + // when `outConnector` lies below `inConnector` + if out_y > in_y { + // `out_x` lies to the left of `in_x` + if out_x < in_x { + return vec![IVec2::new(x1, y1), IVec2::new(x4, y1), IVec2::new(x4, y3)]; + }; + + // `out_x` lies to the right of `in_x` + if out_y - in_y <= grid_spacing { + // `outConnector` point directly below `inConnector` point + if 0 <= out_x - in_x && out_x - in_x <= grid_spacing { + return vec![IVec2::new(x1, y1), IVec2::new(x14, y1), IVec2::new(x14, y2), IVec2::new(x4, y2), IVec2::new(x4, y3)]; + }; + + // `outConnector` point lies below `inConnector` point and strictly to the right of `inConnector` point + return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y111), IVec2::new(x4, y111), IVec2::new(x4, y3)]; + } + + return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y2), IVec2::new(x4, y2), IVec2::new(x4, y3)]; + } + + // `out_y` lies on or above the `in_y` point + if -6 * grid_spacing < in_x - out_x && in_x - out_x < 4 * grid_spacing { + // edge case: `outConnector` point lying on vertical grid lines ranging from 4 units to left to 5 units to right of `inConnector` point + if -grid_spacing < in_x - out_x && in_x - out_x < 4 * grid_spacing { + return vec![ + IVec2::new(x1, y1), + IVec2::new(x2, y1), + IVec2::new(x2, y2), + IVec2::new(x15, y2), + IVec2::new(x15, y12), + IVec2::new(x4, y12), + IVec2::new(x4, y3), + ]; + } + + return vec![IVec2::new(x1, y1), IVec2::new(x16, y1), IVec2::new(x16, y12), IVec2::new(x4, y12), IVec2::new(x4, y3)]; + } + + // left of edge case: `outConnector` point lying on vertical grid lines more than 4 units to left of `inConnector` point + if 4 * grid_spacing < in_x - out_x { + return vec![IVec2::new(x1, y1), IVec2::new(x17, y1), IVec2::new(x17, y12), IVec2::new(x4, y12), IVec2::new(x4, y3)]; + }; + + // right of edge case: `outConnector` point lying on the vertical grid lines more than 5 units to right of `inConnector` point + if 6 * grid_spacing > in_x - out_x { + return vec![IVec2::new(x1, y1), IVec2::new(x18, y1), IVec2::new(x18, y12), IVec2::new(x4, y12), IVec2::new(x4, y3)]; + }; + } + + // Both horizontal - use horizontal middle point + // When `inConnector` point is one of the two closest diagonally opposite points + if 0 <= in_x - out_x && in_x - out_x <= grid_spacing && in_y - out_y >= -grid_spacing && in_y - out_y <= grid_spacing { + return vec![IVec2::new(x19, y1), IVec2::new(x19, y3), IVec2::new(x4, y3)]; + } + + // When `inConnector` point lies on the horizontal line 1 unit above and below the `outConnector` point + if -grid_spacing <= out_y - in_y && out_y - in_y <= grid_spacing && out_x > in_x { + // Horizontal line above `out_y` + if in_y < out_y { + return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y13), IVec2::new(x3, y13), IVec2::new(x3, y3), IVec2::new(x4, y3)]; + }; + + // Horizontal line below `out_y` + return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y14), IVec2::new(x3, y14), IVec2::new(x3, y3), IVec2::new(x4, y3)]; + } + + // `outConnector` point to the right of `inConnector` point + if out_x > in_x - grid_spacing { + return vec![ + IVec2::new(x1, y1), + IVec2::new(x18, y1), + IVec2::new(x18, y15), + IVec2::new(x5, y15), + IVec2::new(x5, y3), + IVec2::new(x4, y3), + ]; + }; + + // When `inConnector` point lies on the vertical grid line two units to the right of `outConnector` point + if grid_spacing <= in_x - out_x && in_x - out_x <= 2 * grid_spacing { + return vec![IVec2::new(x1, y1), IVec2::new(x18, y1), IVec2::new(x18, y3), IVec2::new(x4, y3)]; + }; + + vec![IVec2::new(x1, y1), IVec2::new(x20, y1), IVec2::new(x20, y3), IVec2::new(x4, y3)] +} + +fn straight_wire_to_bezpath(locations: Vec) -> BezPath { + if locations.is_empty() { + return BezPath::new(); + } + + let to_point = |location: IVec2| Point::new(location.x as f64, location.y as f64); + + if locations.len() == 2 { + let p1 = to_point(locations[0]); + let p2 = to_point(locations[1]); + return Line::new(p1, p2).to_path(DEFAULT_ACCURACY); + } + + let corner_radius = 10; + + // Create path with rounded corners + let mut path = BezPath::new(); + path.move_to(to_point(locations[0])); + + for i in 1..(locations.len() - 1) { + let prev = locations[i - 1]; + let curr = locations[i]; + let next = locations[i + 1]; + + let corner_start = IVec2::new( + curr.x + + if curr.x == prev.x { + 0 + } else if prev.x > curr.x { + corner_radius + } else { + -corner_radius + }, + curr.y + + if curr.y == prev.y { + 0 + } else if prev.y > curr.y { + corner_radius + } else { + -corner_radius + }, + ); + + let corner_start_mid = IVec2::new( + curr.x + + if curr.x == prev.x { + 0 + } else if prev.x > curr.x { + corner_radius / 2 + } else { + -corner_radius / 2 + }, + curr.y + + if curr.y == prev.y { + 0 + } else { + match prev.y > curr.y { + true => corner_radius / 2, + false => -corner_radius / 2, + } + }, + ); + + let corner_end = IVec2::new( + curr.x + + if curr.x == next.x { + 0 + } else if next.x > curr.x { + corner_radius + } else { + -corner_radius + }, + curr.y + + if curr.y == next.y { + 0 + } else if next.y > curr.y { + corner_radius + } else { + -corner_radius + }, + ); + + let corner_end_mid = IVec2::new( + curr.x + + if curr.x == next.x { + 0 + } else if next.x > curr.x { + corner_radius / 2 + } else { + -corner_radius / 2 + }, + curr.y + + if curr.y == next.y { + 0 + } else if next.y > curr.y { + 10 / 2 + } else { + -corner_radius / 2 + }, + ); + + path.line_to(to_point(corner_start)); + path.curve_to(to_point(corner_start_mid), to_point(corner_end_mid), to_point(corner_end)); + } + path.line_to(to_point(*locations.last().unwrap())); + path +} diff --git a/node-graph/graph-ui/src/text.rs b/node-graph/graph-ui/src/text.rs new file mode 100644 index 0000000000..5873754bf2 --- /dev/null +++ b/node-graph/graph-ui/src/text.rs @@ -0,0 +1,86 @@ +use crate::metrics::{ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH, GRID_SIZE, TEXT_SIZE}; +use core_types::list::{ATTR_GEOMETRY_CACHE, List}; +use glam::DVec2; +use graphic_types::Vector; +use std::collections::HashMap; +use std::collections::hash_map::Entry; +use text_nodes::{FALLBACK_FONT_RESOURCE, TextToVectorError, TypesettingConfig}; +use vector_types::vector::GeometryCache; + +#[derive(Debug)] +pub struct Label { + pub outline: List, + pub width: f64, +} + +#[derive(Debug, Default)] +pub struct Labels(HashMap<(String, u64), Label>); + +impl Labels { + pub fn label(&mut self, text: &str, max_width: f64) -> Result<&Label, TextToVectorError> { + match self.0.entry((text.to_string(), max_width.to_bits())) { + Entry::Occupied(label) => Ok(label.into_mut()), + Entry::Vacant(label) => { + let text = ellipsized(text, max_width); + let (outline, width) = (outline(&text)?, label_width(&text)); + Ok(label.insert(Label { outline, width })) + } + } + } +} + +pub fn label_width(text: &str) -> f64 { + text_nodes::bounding_box(text, &FALLBACK_FONT_RESOURCE, typesetting(), false).x +} + +fn ellipsized(text: &str, max_width: f64) -> String { + if label_width(text) <= max_width { + return text.to_string(); + } + let cut = |end: usize| format!("{}…", &text[..end]); + let ends: Vec = text.char_indices().map(|(end, _)| end).collect(); + let fitting = ends.partition_point(|&end| label_width(&cut(end)) <= max_width); + cut(ends[fitting.saturating_sub(1)]) +} + +fn outline(text: &str) -> Result, TextToVectorError> { + text_nodes::to_path(text, &FALLBACK_FONT_RESOURCE, typesetting(), false).map(with_geometry_caches) +} + +fn with_geometry_caches(mut outline: List) -> List { + for index in 0..outline.len() { + outline.set_attribute(ATTR_GEOMETRY_CACHE, index, GeometryCache::default()); + } + outline +} + +pub fn paragraph_size(text: &str, line_height: f64, max_width: f64) -> DVec2 { + let unwrapped = text_nodes::bounding_box(text, &FALLBACK_FONT_RESOURCE, paragraph_typesetting(line_height, None), true); + let wrapped = text_nodes::bounding_box(text, &FALLBACK_FONT_RESOURCE, paragraph_typesetting(line_height, Some(max_width)), true); + DVec2::new(unwrapped.x.min(max_width), wrapped.y) +} + +pub fn error_text_size(text: &str) -> DVec2 { + paragraph_size(text, ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH) +} + +pub fn paragraph_outline(text: &str, line_height: f64, max_width: f64) -> Result, TextToVectorError> { + text_nodes::to_path(text, &FALLBACK_FONT_RESOURCE, paragraph_typesetting(line_height, Some(max_width)), false).map(with_geometry_caches) +} + +fn typesetting() -> TypesettingConfig { + TypesettingConfig { + font_size: TEXT_SIZE, + line_height_ratio: GRID_SIZE / TEXT_SIZE, + ..Default::default() + } +} + +fn paragraph_typesetting(line_height: f64, max_width: Option) -> TypesettingConfig { + TypesettingConfig { + font_size: TEXT_SIZE, + line_height_ratio: line_height / TEXT_SIZE, + max_width, + ..Default::default() + } +} diff --git a/node-graph/graph-ui/types/Cargo.toml b/node-graph/graph-ui/types/Cargo.toml new file mode 100644 index 0000000000..66dc419cae --- /dev/null +++ b/node-graph/graph-ui/types/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "graph-ui-types" +description = "The rows, scene and metrics of the node graph UI" +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 + +[features] +serde = ["dep:serde"] +wasm = ["dep:tsify", "dep:wasm-bindgen"] + +[dependencies] +# Local dependencies +core-types = { workspace = true } +dyn-any = { workspace = true } +graph-layout = { workspace = true } +graphene-hash = { workspace = true } +graphic-types = { workspace = true } + +# Workspace dependencies +glam = { workspace = true } +serde = { workspace = true, optional = true } +tsify = { workspace = true, optional = true } +wasm-bindgen = { workspace = true, optional = true } diff --git a/node-graph/graph-ui/types/src/card.rs b/node-graph/graph-ui/types/src/card.rs new file mode 100644 index 0000000000..012bcb9bc5 --- /dev/null +++ b/node-graph/graph-ui/types/src/card.rs @@ -0,0 +1,56 @@ +use crate::geometry::NodeShape; +use crate::replicated_map::Keyed; +use core_types::uuid::NodeId; +use graphene_hash::CacheHash; + +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub struct Card { + pub key: NodeId, + pub shape: NodeShape, + pub name: String, + pub icon: &'static str, + pub primary_input: Option, + pub primary_output: Option, + pub secondary_inputs: Vec, + pub secondary_outputs: Vec, + pub selection: Selection, + pub visible: bool, + pub previewed: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, CacheHash)] +pub enum Selection { + None, + Inactive, + Active, +} + +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub struct Connector { + pub index: u32, + pub name: String, + pub data_type: DataType, + pub connected: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, CacheHash)] +pub enum DataType { + General, + Number, + Artboard, + Graphic, + Raster, + Vector, + Color, + Gradient, + Typography, + Invalid, +} + +impl Keyed for Card { + type Key = NodeId; + + fn key(&self) -> NodeId { + self.key + } +} diff --git a/node-graph/graph-ui/types/src/dot.rs b/node-graph/graph-ui/types/src/dot.rs new file mode 100644 index 0000000000..0acbadd95f --- /dev/null +++ b/node-graph/graph-ui/types/src/dot.rs @@ -0,0 +1,23 @@ +use crate::card::DataType; +use crate::geometry::NodeShape; +use crate::replicated_map::Keyed; +use core_types::uuid::NodeId; +use graphene_hash::CacheHash; + +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub struct Dot { + pub key: NodeId, + pub shape: NodeShape, + pub data_type: DataType, + pub wired: bool, + pub selected: bool, + pub previewed: bool, +} + +impl Keyed for Dot { + type Key = NodeId; + + fn key(&self) -> NodeId { + self.key + } +} diff --git a/node-graph/graph-ui/types/src/error_badge.rs b/node-graph/graph-ui/types/src/error_badge.rs new file mode 100644 index 0000000000..137eb1614d --- /dev/null +++ b/node-graph/graph-ui/types/src/error_badge.rs @@ -0,0 +1,40 @@ +use crate::metrics::{ERROR_PADDING, ERROR_TAIL_LEFT, ERROR_TAIL_SIZE}; +use crate::replicated_map::Keyed; +use core_types::uuid::NodeId; +use glam::DVec2; +use graphene_hash::CacheHash; + +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub struct ErrorBadge { + pub key: NodeId, + pub text: String, +} + +impl Keyed for ErrorBadge { + type Key = NodeId; + + fn key(&self) -> NodeId { + self.key + } +} + +pub fn body(anchor: DVec2, text_size: DVec2) -> [DVec2; 2] { + let size = text_size + 2. * ERROR_PADDING; + [anchor - DVec2::Y * size.y, anchor + DVec2::X * size.x] +} + +pub fn text_top_left(anchor: DVec2, text_size: DVec2) -> DVec2 { + let [top_left, _] = body(anchor, text_size); + top_left + ERROR_PADDING +} + +pub fn tail(anchor: DVec2) -> [DVec2; 3] { + let top_left = anchor + DVec2::X * ERROR_TAIL_LEFT; + [top_left, top_left + DVec2::X * ERROR_TAIL_SIZE.x, top_left + DVec2::new(ERROR_TAIL_SIZE.x / 2., ERROR_TAIL_SIZE.y)] +} + +pub fn covers(anchor: DVec2, text_size: DVec2, point: DVec2) -> bool { + let [tail, ..] = tail(anchor); + let within = |[min, max]: [DVec2; 2]| min.cmple(point).all() && point.cmple(max).all(); + within(body(anchor, text_size)) || within([tail, tail + ERROR_TAIL_SIZE]) +} diff --git a/node-graph/graph-ui/types/src/geometry.rs b/node-graph/graph-ui/types/src/geometry.rs new file mode 100644 index 0000000000..841c192193 --- /dev/null +++ b/node-graph/graph-ui/types/src/geometry.rs @@ -0,0 +1,493 @@ +use crate::card::{Card, Connector}; +use crate::dot::Dot; +use crate::layer::Layer; +use crate::metrics::{ + CLICK_RADIUS, GRID_SIZE, INPUT_CONNECTOR_OFFSET, LAYER_BUTTON_SIZE, LAYER_CLICK_RADIUS, LAYER_DETAILS_MARGIN, LAYER_GRIP_WIDTH, LAYER_LEFT_MARGIN, LAYER_NAME_LEFT, LAYER_THUMBNAIL_IMAGE_INSET, + LAYER_THUMBNAIL_MARGIN, LAYER_THUMBNAIL_WIDTH, OUTPUT_CONNECTOR_OFFSET, PORT_CLICK_RADIUS, SIDE_PORT_HALF_HEIGHT, SIDE_PORT_INWARD_REACH, SIDE_PORT_OUTWARD_REACH, STACK_ANCHOR_DISTANCE, + STACK_CONNECTOR_SIZE, STACK_PORT_HALF_SIZE, WAYPOINT_GUTTER_OFFSET, WAYPOINT_GUTTER_RADIUS, WAYPOINT_HALF_SIZE, +}; +use crate::network_connector::{NetworkConnector, NetworkConnectorKey}; +use crate::placed::Placed; +use crate::replicated_map::ReplicatedMap; +use crate::scene::Rows; +use crate::wire::{InputKey, OutputKey, Wire}; +use core_types::uuid::NodeId; +use glam::{DVec2, IVec2, UVec2}; +use graph_layout::{CHAIN_WIDTH, NodeKind}; +use graphene_hash::CacheHash; +use std::ops::Range; +use std::sync::Arc; + +#[derive(Clone, Debug, Default, PartialEq, CacheHash)] +pub struct NodeShape { + pub size: UVec2, + pub exposed_inputs: Arc<[usize]>, + pub outputs: u32, + pub primary_output_hidden: bool, + pub name_width: f64, + pub locked: bool, +} + +impl NodeShape { + fn inputs(&self) -> u32 { + self.exposed_inputs.len() as u32 + } + + fn primary_input_hidden(&self) -> bool { + self.exposed_inputs.first().is_some_and(|first| *first != 0) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Part { + Body, + Input(u32), + Output(u32), + Visibility, + Lock, + Grip, + Name, +} + +#[derive(Clone, Copy, Debug)] +pub struct PartTarget { + pub min: DVec2, + pub max: DVec2, + pub corner_radius: f64, + pub part: Part, +} + +impl PartTarget { + fn around(center: DVec2, half_size: DVec2, corner_radius: f64, part: Part) -> Self { + Self { + min: center - half_size, + max: center + half_size, + corner_radius, + part, + } + } + + fn over([min, max]: [DVec2; 2], corner_radius: f64, part: Part) -> Self { + Self { min, max, corner_radius, part } + } + + pub fn input_port(center: DVec2, input: u32) -> Self { + Self { + min: center - DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT), + max: center + DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT), + corner_radius: PORT_CLICK_RADIUS, + part: Part::Input(input), + } + } + + pub fn output_port(center: DVec2, output: u32) -> Self { + Self { + min: center - DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT), + max: center + DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT), + corner_radius: PORT_CLICK_RADIUS, + part: Part::Output(output), + } + } + + pub fn overlaps(&self, min: DVec2, max: DVec2) -> bool { + if !min.cmplt(self.max).all() || !self.min.cmplt(max).all() { + return false; + } + + let radius = self.clamped_radius(); + let gap = (self.min + radius - max).max(min - (self.max - radius)).max(DVec2::ZERO); + gap == DVec2::ZERO || gap.length_squared() < radius * radius + } + + pub fn contains(&self, point: DVec2) -> bool { + if !point.cmpge(self.min).all() || !point.cmplt(self.max).all() { + return false; + } + + let radius = self.clamped_radius(); + let inner = point.clamp(self.min + radius, self.max - radius); + point.distance_squared(inner) <= radius * radius + } + + fn clamped_radius(&self) -> f64 { + self.corner_radius.min((self.max - self.min).min_element() / 2.) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, CacheHash)] +pub struct WireEnd { + pub position: DVec2, + pub vertical: bool, +} + +pub fn is_thick_wire([from, to]: [WireEnd; 2]) -> bool { + from.vertical && to.vertical +} + +#[derive(Clone, Debug)] +pub struct NodeGeometry { + pub cell: IVec2, + pub kind: NodeKind, + pub chain_length: u32, + pub shape: NodeShape, +} + +impl NodeGeometry { + pub fn body(&self) -> PartTarget { + match self.kind { + NodeKind::Waypoint => PartTarget::around(self.dot_center(), WAYPOINT_HALF_SIZE, WAYPOINT_HALF_SIZE.y, Part::Body), + NodeKind::Layer => PartTarget { + min: self.top_left() - DVec2::new(self.chain_width(), 0.), + max: self.top_left() + self.size(), + corner_radius: LAYER_CLICK_RADIUS, + part: Part::Body, + }, + NodeKind::Node => PartTarget::over(self.card_body(), CLICK_RADIUS, Part::Body), + } + } + + pub fn parts(&self, mut visit: impl FnMut(PartTarget)) { + match self.kind { + NodeKind::Waypoint => self.waypoint_ports(&mut visit), + NodeKind::Layer => self.layer_parts(&mut visit), + NodeKind::Node => self.node_ports(&mut visit), + } + visit(self.body()); + } + + pub fn input_end(&self, index: usize) -> Option { + let position = self.input_anchor(self.place_of_input(index)?)?; + let vertical = self.kind == NodeKind::Layer && index == 0; + Some(WireEnd { position, vertical }) + } + + pub fn output_end(&self, index: usize) -> Option { + let position = self.output_anchor(u32::try_from(index).ok()?)?; + let vertical = self.kind == NodeKind::Layer; + Some(WireEnd { position, vertical }) + } + + pub fn input_at(&self, place: u32) -> Option { + match self.kind { + NodeKind::Node => { + let row = place.checked_sub(self.input_rows().start)?; + self.shape.exposed_inputs.get(row as usize).copied() + } + NodeKind::Layer | NodeKind::Waypoint => Some(place as usize), + } + } + + pub fn error_badge_anchor(&self) -> DVec2 { + let offset = if self.kind == NodeKind::Layer { + DVec2::new(LAYER_LEFT_MARGIN, -GRID_SIZE / 2.) + } else { + DVec2::ZERO + }; + self.top_left() + offset + } + + fn place_of_input(&self, index: usize) -> Option { + let place = match self.kind { + NodeKind::Node => { + let row = self.shape.exposed_inputs.iter().position(|exposed| *exposed == index)?; + self.input_rows().start as usize + row + } + NodeKind::Layer | NodeKind::Waypoint => index, + }; + u32::try_from(place).ok() + } + + fn input_anchor(&self, place: u32) -> Option { + match (self.kind, place) { + (NodeKind::Waypoint, 0) => Some(self.dot_center()), + (NodeKind::Layer, 0) => Some(self.stack_input_anchor()), + (NodeKind::Layer, 1) if self.has_side_input() => Some(self.side_input_anchor()), + (NodeKind::Node, row) if self.input_rows().contains(&row) => Some(self.row_input_anchor(row)), + _ => None, + } + } + + fn output_anchor(&self, place: u32) -> Option { + match (self.kind, place) { + (NodeKind::Waypoint, 0) => Some(self.dot_center()), + (NodeKind::Layer, 0) => Some(self.stack_output_anchor()), + (NodeKind::Node, row) if self.output_rows().contains(&row) => Some(self.row_output_anchor(row)), + _ => None, + } + } + + fn card_body(&self) -> [DVec2; 2] { + let top_left = self.top_left() + DVec2::new(0., GRID_SIZE / 2.); + [top_left, top_left + self.size() - DVec2::new(0., GRID_SIZE)] + } + + fn layer_body(&self) -> [DVec2; 2] { + let top_left = self.top_left(); + let chain_width = self.chain_width(); + let left = if chain_width > 0. { -chain_width } else { LAYER_LEFT_MARGIN }; + [top_left + DVec2::X * left, top_left + self.size()] + } + + fn thumbnail_block(&self) -> [DVec2; 2] { + let left = self.top_left() + DVec2::X * LAYER_LEFT_MARGIN; + [left, left + DVec2::new(LAYER_THUMBNAIL_WIDTH, self.size().y)] + } + + fn visibility(&self) -> [DVec2; 2] { + let [_, max] = self.layer_body(); + let top_left = DVec2::new(max.x - LAYER_BUTTON_SIZE / 2., self.middle() - LAYER_BUTTON_SIZE / 2.); + [top_left, top_left + LAYER_BUTTON_SIZE] + } + + fn grip(&self) -> [DVec2; 2] { + let [right_of_grip, _] = self.lock().unwrap_or(self.visibility()); + [right_of_grip - DVec2::X * LAYER_GRIP_WIDTH, right_of_grip + DVec2::Y * LAYER_BUTTON_SIZE] + } + + fn lock(&self) -> Option<[DVec2; 2]> { + let [min, max] = self.visibility(); + self.shape.locked.then(|| [min - DVec2::X * LAYER_BUTTON_SIZE, max - DVec2::X * LAYER_BUTTON_SIZE]) + } + + fn dot_center(&self) -> DVec2 { + self.top_left() + DVec2::new(0., GRID_SIZE) + } + + fn waypoint_ports(&self, visit: &mut impl FnMut(PartTarget)) { + let center = self.dot_center(); + let gutter = |x_offset: f64, part| PartTarget::around(center + DVec2::new(x_offset, 0.), DVec2::splat(WAYPOINT_GUTTER_RADIUS), WAYPOINT_GUTTER_RADIUS, part); + visit(gutter(-WAYPOINT_GUTTER_OFFSET, Part::Input(0))); + visit(gutter(WAYPOINT_GUTTER_OFFSET, Part::Output(0))); + } + + fn node_ports(&self, visit: &mut impl FnMut(PartTarget)) { + for row in self.input_rows() { + visit(PartTarget::input_port(self.row_input_anchor(row), row)); + } + for row in self.output_rows() { + visit(PartTarget::output_port(self.row_output_anchor(row), row)); + } + } + + fn layer_parts(&self, visit: &mut impl FnMut(PartTarget)) { + visit(PartTarget::around(self.stack_input_anchor(), STACK_PORT_HALF_SIZE, PORT_CLICK_RADIUS, Part::Input(0))); + if self.has_side_input() { + visit(PartTarget::input_port(self.side_input_anchor(), 1)); + } + visit(PartTarget::around(self.stack_output_anchor(), STACK_PORT_HALF_SIZE, PORT_CLICK_RADIUS, Part::Output(0))); + + visit(PartTarget::over(self.visibility(), CLICK_RADIUS, Part::Visibility)); + if let Some(lock) = self.lock() { + visit(PartTarget::over(lock, CLICK_RADIUS, Part::Lock)); + } + + let [grip_min, grip_max] = self.grip(); + visit(PartTarget::over([grip_min, grip_max], 0., Part::Grip)); + + let name_left = self.top_left().x + LAYER_NAME_LEFT; + let name_right = (name_left + self.shape.name_width).min(grip_min.x); + if name_right > name_left { + visit(PartTarget { + min: DVec2::new(name_left, grip_min.y), + max: DVec2::new(name_right, grip_max.y), + corner_radius: CLICK_RADIUS, + part: Part::Name, + }); + } + } + + fn top_left(&self) -> DVec2 { + self.cell.as_dvec2() * GRID_SIZE + } + + fn size(&self) -> DVec2 { + self.shape.size.as_dvec2() * GRID_SIZE + } + + fn middle(&self) -> f64 { + self.top_left().y + self.size().y / 2. + } + + fn input_rows(&self) -> Range { + let first = u32::from(self.shape.primary_input_hidden()); + first..first + self.shape.inputs() + } + + fn output_rows(&self) -> Range { + u32::from(self.shape.primary_output_hidden)..self.shape.outputs + } + + fn row_input_anchor(&self, row: u32) -> DVec2 { + self.top_left() + DVec2::new(0., GRID_SIZE * (row as f64 + 1.)) + } + + fn row_output_anchor(&self, row: u32) -> DVec2 { + self.top_left() + DVec2::new(self.size().x, GRID_SIZE * (row as f64 + 1.)) + } + + fn stack_input_anchor(&self) -> DVec2 { + let [min, max] = self.thumbnail_block(); + DVec2::new((min.x + max.x) / 2., max.y + STACK_ANCHOR_DISTANCE) + } + + fn stack_output_anchor(&self) -> DVec2 { + let [min, max] = self.thumbnail_block(); + DVec2::new((min.x + max.x) / 2., min.y - STACK_ANCHOR_DISTANCE) + } + + fn side_input_anchor(&self) -> DVec2 { + DVec2::new(self.top_left().x, self.middle()) + } + + fn has_side_input(&self) -> bool { + self.shape.inputs() > 1 + } + + fn chain_width(&self) -> f64 { + if self.has_side_input() { + (self.chain_length as i32 * CHAIN_WIDTH + 1) as f64 * GRID_SIZE + } else { + 0. + } + } +} + +impl Placed { + fn geometry(&self) -> NodeGeometry { + NodeGeometry { + cell: self.cell, + kind: NodeKind::Node, + chain_length: 0, + shape: self.look.shape.clone(), + } + } + + pub fn body(&self) -> [DVec2; 2] { + self.geometry().card_body() + } + + pub fn rows(&self) -> u32 { + self.look.shape.size.y.saturating_sub(1) + } + + pub fn inputs(&self) -> impl Iterator { + let geometry = self.geometry(); + rows(&self.look.primary_input, &self.look.secondary_inputs).map(move |(row, input)| (geometry.row_input_anchor(row) + INPUT_CONNECTOR_OFFSET, input)) + } + + pub fn outputs(&self) -> impl Iterator { + let geometry = self.geometry(); + rows(&self.look.primary_output, &self.look.secondary_outputs).map(move |(row, output)| (geometry.row_output_anchor(row) + OUTPUT_CONNECTOR_OFFSET, output)) + } +} + +fn rows<'a>(primary: &'a Option, secondary: &'a [Connector]) -> impl Iterator { + primary.iter().map(|connector| (0, connector)).chain((1..).zip(secondary)) +} + +impl Placed { + fn geometry(&self) -> NodeGeometry { + NodeGeometry { + cell: self.cell, + kind: NodeKind::Layer, + chain_length: self.look.chain_length, + shape: self.look.shape.clone(), + } + } + + pub fn body(&self) -> [DVec2; 2] { + self.geometry().layer_body() + } + + pub fn left_input_wire(&self) -> Option { + let geometry = self.geometry(); + let [min, _] = geometry.layer_body(); + (self.look.has_left_input_wire && geometry.chain_width() > 0.).then(|| DVec2::new(min.x, geometry.middle())) + } + + pub fn thumbnail_block(&self) -> [DVec2; 2] { + self.geometry().thumbnail_block() + } + + pub fn thumbnail(&self) -> [DVec2; 2] { + let [min, max] = self.thumbnail_block(); + [min + DVec2::X * LAYER_THUMBNAIL_MARGIN, max - DVec2::X * LAYER_THUMBNAIL_MARGIN] + } + + pub fn thumbnail_image(&self) -> [DVec2; 2] { + let [min, max] = self.thumbnail(); + [min + LAYER_THUMBNAIL_IMAGE_INSET, max - LAYER_THUMBNAIL_IMAGE_INSET] + } + + pub fn stack_output(&self) -> DVec2 { + let [min, max] = self.thumbnail_block(); + DVec2::new((min.x + max.x - STACK_CONNECTOR_SIZE.x) / 2., min.y - STACK_CONNECTOR_SIZE.y) + } + + pub fn stack_input(&self) -> DVec2 { + let [min, max] = self.thumbnail_block(); + DVec2::new((min.x + max.x - STACK_CONNECTOR_SIZE.x) / 2., max.y) + } + + pub fn secondary_input_connector(&self) -> DVec2 { + self.geometry().side_input_anchor() + INPUT_CONNECTOR_OFFSET + } + + pub fn name_box(&self) -> [DVec2; 2] { + let geometry = self.geometry(); + let top_left = DVec2::new(geometry.top_left().x + LAYER_NAME_LEFT, geometry.middle() - GRID_SIZE / 2.); + [top_left, top_left + DVec2::new(geometry.size().x - LAYER_NAME_LEFT - LAYER_DETAILS_MARGIN, GRID_SIZE)] + } + + pub fn visibility(&self) -> [DVec2; 2] { + self.geometry().visibility() + } + + pub fn grip(&self) -> [DVec2; 2] { + self.geometry().grip() + } + + pub fn lock(&self) -> Option<[DVec2; 2]> { + self.geometry().lock() + } +} + +impl Placed { + fn geometry(&self) -> NodeGeometry { + NodeGeometry { + cell: self.cell, + kind: NodeKind::Waypoint, + chain_length: 0, + shape: self.look.shape.clone(), + } + } + + pub fn center(&self) -> DVec2 { + self.geometry().dot_center() + } +} + +impl Rows { + fn geometry(&self, node: &NodeId) -> Option { + let card = || self.cards.get(node).map(Placed::::geometry); + let layer = || self.layers.get(node).map(Placed::::geometry); + let dot = || self.dots.get(node).map(Placed::::geometry); + card().or_else(layer).or_else(dot) + } +} + +pub fn node_geometry(rows: &[&Rows], node: &NodeId) -> Option { + rows.iter().find_map(|rows| rows.geometry(node)) +} + +pub fn wire_ends(wire: &Wire, rows: &[&Rows], network_connectors: &ReplicatedMap) -> Option<[WireEnd; 2]> { + let from = match wire.from { + OutputKey::Node { node, index } => node_geometry(rows, &node)?.output_end(index)?, + OutputKey::Import(index) => network_connectors.get(&NetworkConnectorKey::Import(index))?.wire_end()?, + }; + let to = match wire.to { + InputKey::Node { node, index } => node_geometry(rows, &node)?.input_end(index)?, + InputKey::Export(index) => network_connectors.get(&NetworkConnectorKey::Export(index))?.wire_end()?, + }; + Some([from, to]) +} diff --git a/node-graph/graph-ui/types/src/highlights.rs b/node-graph/graph-ui/types/src/highlights.rs new file mode 100644 index 0000000000..6db05a9410 --- /dev/null +++ b/node-graph/graph-ui/types/src/highlights.rs @@ -0,0 +1,94 @@ +use crate::layer::LayerButton; +use crate::wire::{InputKey, OutputKey}; +use core_types::uuid::NodeId; +use dyn_any::DynAny; +use graphene_hash::CacheHash; + +#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)] +pub enum Highlight { + #[default] + None, + Hovered, + WireSource, + WireTarget, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)] +pub enum ConnectorKey { + Input(InputKey), + Output(OutputKey), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, CacheHash)] +pub enum NodePart { + Dot(NodeId), + DotOutput(NodeId), + Visibility(NodeId), + Lock(NodeId), + Grip(NodeId), + ErrorBadge(NodeId), +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash, DynAny)] +pub struct Highlights { + pub hovered_connector: Option, + pub dragged_from: Option, + pub snapped_to: Option, + pub hovered_part: Option, + pub pressed_part: Option, + pub clicked: bool, +} + +impl Highlights { + pub fn dot(&self, dot: NodeId) -> [Highlight; 2] { + let ends = [ + ConnectorKey::Input(InputKey::Node { node: dot, index: 0 }), + ConnectorKey::Output(OutputKey::Node { node: dot, index: 0 }), + ]; + let body = if self.snapped_to.is_some_and(|key| ends.contains(&key)) { + Highlight::WireTarget + } else if [self.hovered_part, self.pressed_part].contains(&Some(NodePart::Dot(dot))) { + Highlight::Hovered + } else { + Highlight::None + }; + let output = if self.dragged_from.is_some_and(|key| ends.contains(&key)) { + Highlight::WireSource + } else if self.hovered_part == Some(NodePart::DotOutput(dot)) { + Highlight::Hovered + } else { + Highlight::None + }; + [body, output] + } + + pub fn layer_button(&self, layer: NodeId) -> Option { + match self.hovered_part? { + NodePart::Visibility(node) if node == layer => Some(LayerButton::Visibility), + NodePart::Lock(node) if node == layer => Some(LayerButton::Lock), + NodePart::Grip(node) if node == layer => Some(LayerButton::Grip), + _ => None, + } + } + + pub fn connector(&self, key: ConnectorKey) -> Highlight { + let key = Some(key); + if key == self.snapped_to { + Highlight::WireTarget + } else if key == self.hovered_connector { + Highlight::Hovered + } else if key == self.dragged_from { + Highlight::WireSource + } else { + Highlight::None + } + } + + pub fn connectors(&self) -> impl Iterator { + [self.hovered_connector, self.dragged_from, self.snapped_to].into_iter().flatten() + } + + pub fn badge_hovered(&self, badge: NodeId) -> bool { + self.hovered_part == Some(NodePart::ErrorBadge(badge)) + } +} diff --git a/node-graph/graph-ui/types/src/inputs.rs b/node-graph/graph-ui/types/src/inputs.rs new file mode 100644 index 0000000000..a11b5829a1 --- /dev/null +++ b/node-graph/graph-ui/types/src/inputs.rs @@ -0,0 +1,71 @@ +use crate::error_badge::ErrorBadge; +use crate::highlights::Highlights; +use crate::network_connector::{NetworkConnector, NetworkConnectorKind}; +use crate::replicated_map::ReplicatedMap; +use crate::scene::Rows; +use crate::wire::{WireInProgress, WireStyle}; +use core_types::list::Item; +use core_types::registry::Any; +use core_types::uuid::NodeId; +use core_types::{ProtoNodeIdentifier, Type, item}; +use glam::DVec2; +use graphene_hash::CacheHash; +use graphic_types::Graphic; +use std::collections::BTreeMap; +use std::sync::Arc; + +pub const SETTLED: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-settled"); +pub const MOVING: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-moving"); +pub const NETWORK_CONNECTORS: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-network-connectors"); +pub const ERRORS: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-errors"); +pub const THUMBNAILS: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-thumbnails"); +pub const WIRE_IN_PROGRESS: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-wire-in-progress"); +pub const REORDER_BAR: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-reorder-bar"); +pub const BOX_SELECTION: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-box-selection"); +pub const FADE_ARTWORK: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-fade-artwork"); +pub const WIRE_STYLE: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-wire-style"); +pub const HIGHLIGHTS: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-highlights"); + +pub type Thumbnails = Arc>; + +macro_rules! tagged_graph_ui_value { + ($($identifier:ident($ty:ty)),* $(,)?) => { + #[derive(Clone, Debug, PartialEq, CacheHash)] + pub enum TaggedGraphUiValue { + $($identifier($ty),)* + } + + impl TaggedGraphUiValue { + pub fn to_dynany(self) -> Any { + match self { + $(Self::$identifier(x) => Box::new(Item::new_from_element(x)),)* + } + } + + pub fn to_any(self) -> Arc { + match self { + $(Self::$identifier(x) => Arc::new(Item::new_from_element(x)),)* + } + } + + pub fn ty(&self) -> Type { + match self { + $(Self::$identifier(_) => item!($ty),)* + } + } + } + }; +} + +tagged_graph_ui_value! { + Rows(Rows), + NetworkConnectors(ReplicatedMap), + Errors(ReplicatedMap), + Thumbnails(Thumbnails), + WireInProgress(Option), + ReorderBar(Option<(NetworkConnectorKind, DVec2)>), + BoxSelection(Option<[DVec2; 2]>), + FadeArtwork(f64), + WireStyle(WireStyle), + Highlights(Highlights), +} diff --git a/node-graph/graph-ui/types/src/layer.rs b/node-graph/graph-ui/types/src/layer.rs new file mode 100644 index 0000000000..44c57356ff --- /dev/null +++ b/node-graph/graph-ui/types/src/layer.rs @@ -0,0 +1,39 @@ +use crate::card::{Connector, Selection}; +use crate::geometry::NodeShape; +use crate::replicated_map::Keyed; +use core_types::uuid::NodeId; +use graphene_hash::CacheHash; + +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub struct Layer { + pub key: NodeId, + pub shape: NodeShape, + pub chain_length: u32, + pub name: String, + pub renaming: bool, + pub has_left_input_wire: bool, + pub primary_input: Option, + pub primary_output: Option, + pub secondary_input: Option, + pub primary_input_connected_to_layer: bool, + pub primary_output_connected_to_layer: bool, + pub visible: bool, + pub read_only: bool, + pub selection: Selection, + pub previewed: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, CacheHash)] +pub enum LayerButton { + Visibility, + Lock, + Grip, +} + +impl Keyed for Layer { + type Key = NodeId; + + fn key(&self) -> NodeId { + self.key + } +} diff --git a/node-graph/graph-ui/types/src/lib.rs b/node-graph/graph-ui/types/src/lib.rs new file mode 100644 index 0000000000..ca70b84bbe --- /dev/null +++ b/node-graph/graph-ui/types/src/lib.rs @@ -0,0 +1,31 @@ +use glam::{DAffine2, DVec2}; +use highlights::Highlights; +use network_connector::NetworkConnectorKind; +use wire::{WireInProgress, WireStyle}; + +pub use inputs::TaggedGraphUiValue; + +pub mod card; +pub mod dot; +pub mod error_badge; +pub mod geometry; +pub mod highlights; +pub mod inputs; +pub mod layer; +pub mod metrics; +pub mod network_connector; +pub mod placed; +pub mod replicated_map; +pub mod scene; +pub mod wire; + +#[derive(Clone, Copy, Debug)] +pub struct GraphUiConfig { + pub view: DAffine2, + pub fade_artwork: f64, + pub wire_in_progress: Option, + pub reorder_bar: Option<(NetworkConnectorKind, DVec2)>, + pub box_selection: Option<[DVec2; 2]>, + pub highlights: Highlights, + pub wire_style: WireStyle, +} diff --git a/node-graph/graph-ui/types/src/metrics.rs b/node-graph/graph-ui/types/src/metrics.rs new file mode 100644 index 0000000000..846cc9b3c9 --- /dev/null +++ b/node-graph/graph-ui/types/src/metrics.rs @@ -0,0 +1,80 @@ +use glam::DVec2; + +pub const GRID_SIZE: f64 = 24.; +pub const GRID_COLLAPSE_SPACING: f64 = 10.; +pub const TEXT_SIZE: f64 = 14.; +pub const BORDER_WIDTH: f64 = 1.; +pub const BORDER_DASHES: [f64; 2] = [3., 2.]; +pub const ICON_SIZE: f64 = 16.; + +pub const CARD_GRID_WIDTH: u32 = 5; +pub const CARD_RADIUS: f64 = 2.; +pub const CARD_ICON_LEFT: f64 = 8.; +pub const CARD_NAME_LEFT: f64 = 32.; +pub const CARD_NAME_MAX_WIDTH: f64 = 84.; +pub const CARD_ROW_PADDING: f64 = 8.; + +pub const CONNECTOR_SIZE: f64 = 8.; +pub const INPUT_CONNECTOR_LEFT: f64 = -3.; +pub const OUTPUT_CONNECTOR_RIGHT: f64 = 5.; +pub const INPUT_CONNECTOR_OFFSET: DVec2 = DVec2::new(INPUT_CONNECTOR_LEFT, -CONNECTOR_SIZE / 2.); +pub const OUTPUT_CONNECTOR_OFFSET: DVec2 = DVec2::new(OUTPUT_CONNECTOR_RIGHT - CONNECTOR_SIZE, -CONNECTOR_SIZE / 2.); +pub const CONNECTOR_GAP: f64 = 16.; +pub const HOVERED_CONNECTOR_SCALE: f64 = 1.3; +pub const HOVERED_CONNECTOR_RING: f64 = 4.; +pub const STACK_CONNECTOR_SIZE: DVec2 = DVec2::new(CONNECTOR_SIZE, 12.); + +pub const IMPORT_NAME_INSET: f64 = 8.; +pub const EXPORT_NAME_INSET: f64 = 9.; +pub const NETWORK_CONNECTOR_NAME_RAISE: f64 = 1.; +pub const NETWORK_CONNECTOR_SEPARATOR_OVERHANG: f64 = 4.; +pub const REORDER_BAR_SIZE: DVec2 = DVec2::new(50., 2.); + +pub const ERROR_PADDING: f64 = 8.; +pub const ERROR_LINE_HEIGHT: f64 = 18.; +pub const ERROR_MAX_WIDTH: f64 = 600.; +pub const ERROR_RADIUS: f64 = 4.; +pub const ERROR_TAIL_LEFT: f64 = 6.; +pub const ERROR_TAIL_SIZE: DVec2 = DVec2::new(12., 8.); + +pub const WIRE_WIDTH: f64 = 2.; +pub const LIST_WIRE_WIDTH: f64 = 4.; +pub const WIRE_DASHES: [f64; 2] = [3., 2.]; +pub const THICK_WIRE_WIDTH: f64 = 8.; + +pub const DOT_RADIUS: f64 = 5.; +pub const DOT_SELECTED_RING: f64 = 2.; +pub const DOT_PREVIEWED_RING_OFFSET: f64 = 2.; +pub const DOT_HOVERED_RING: f64 = 2.; +pub const DOT_OUTPUT_ARROW: DVec2 = DVec2::new(WAYPOINT_GUTTER_OFFSET - CONNECTOR_SIZE / 2., -CONNECTOR_SIZE / 2.); + +pub const LAYER_RADIUS: f64 = 8.; +pub const LAYER_LEFT_MARGIN: f64 = GRID_SIZE / 2.; +pub const LAYER_THUMBNAIL_WIDTH: f64 = 3. * GRID_SIZE; +pub const LAYER_THUMBNAIL_MARGIN: f64 = 1.; +pub const LAYER_THUMBNAIL_RADIUS: f64 = 2.; +pub const LAYER_THUMBNAIL_IMAGE_INSET: f64 = 2.; +pub const LAYER_DETAILS_MARGIN: f64 = 8.; +pub const LAYER_NAME_LEFT: f64 = LAYER_LEFT_MARGIN + LAYER_THUMBNAIL_WIDTH + LAYER_DETAILS_MARGIN; +pub const LAYER_BUTTON_SIZE: f64 = GRID_SIZE; +pub const LAYER_BUTTON_RADIUS: f64 = 2.; +pub const LAYER_GRIP_WIDTH: f64 = 8.; +pub const LAYER_GRIP_DOTS: DVec2 = DVec2::new(2.5, 9.5); +pub const LAYER_GRIP_DOT_COUNT: [u32; 2] = [2, 3]; +pub const LAYER_GRIP_DOT_SPACING: f64 = 3.; +pub const LAYER_GRIP_DOT_RADIUS: f64 = 0.5; +pub const LAYER_THUMBNAIL_GAP: DVec2 = DVec2::new(8., 2.); + +pub const CHECKER_CELL: f64 = 8.; +pub const CLICK_RADIUS: f64 = 3.; +pub const LAYER_CLICK_RADIUS: f64 = 10.; +pub const PORT_CLICK_RADIUS: f64 = 4.; +pub const SIDE_PORT_OUTWARD_REACH: f64 = 12.; +pub const SIDE_PORT_INWARD_REACH: f64 = 8.; +pub const SIDE_PORT_HALF_HEIGHT: f64 = GRID_SIZE / 2.; +pub const STACK_PORT_HALF_SIZE: DVec2 = DVec2::new(12., 8.); +pub const STACK_ANCHOR_DISTANCE: f64 = 8.; + +pub const WAYPOINT_HALF_SIZE: DVec2 = DVec2::new(15., 8.); +pub const WAYPOINT_GUTTER_OFFSET: f64 = 10.; +pub const WAYPOINT_GUTTER_RADIUS: f64 = 5.; diff --git a/node-graph/graph-ui/types/src/network_connector.rs b/node-graph/graph-ui/types/src/network_connector.rs new file mode 100644 index 0000000000..7e8ef7b6ee --- /dev/null +++ b/node-graph/graph-ui/types/src/network_connector.rs @@ -0,0 +1,111 @@ +use crate::card::Connector; +use crate::geometry::WireEnd; +use crate::metrics::{BORDER_WIDTH, EXPORT_NAME_INSET, GRID_SIZE, IMPORT_NAME_INSET, INPUT_CONNECTOR_OFFSET, NETWORK_CONNECTOR_NAME_RAISE, NETWORK_CONNECTOR_SEPARATOR_OVERHANG, REORDER_BAR_SIZE}; +use crate::replicated_map::Keyed; +use dyn_any::DynAny; +use glam::{DVec2, IVec2}; +use graphene_hash::CacheHash; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash, DynAny)] +pub enum NetworkConnectorKind { + Import, + Export, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum NetworkConnectorKey { + Import(usize), + Export(usize), +} + +impl NetworkConnectorKey { + pub fn new(kind: NetworkConnectorKind, index: usize) -> Self { + match kind { + NetworkConnectorKind::Import => Self::Import(index), + NetworkConnectorKind::Export => Self::Export(index), + } + } + + pub fn kind(self) -> NetworkConnectorKind { + match self { + Self::Import(_) => NetworkConnectorKind::Import, + Self::Export(_) => NetworkConnectorKind::Export, + } + } + + pub fn index(self) -> usize { + match self { + Self::Import(index) | Self::Export(index) => index, + } + } +} + +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub struct NetworkConnector { + pub key: NetworkConnectorKey, + pub position: IVec2, + pub connector: Option, + pub editable: bool, + pub renaming: bool, +} + +impl Keyed for NetworkConnector { + type Key = NetworkConnectorKey; + + fn key(&self) -> NetworkConnectorKey { + self.key + } +} + +impl NetworkConnector { + pub fn anchor(&self) -> DVec2 { + self.position.as_dvec2() + } + + pub(crate) fn wire_end(&self) -> Option { + let position = self.anchor(); + self.connector.is_some().then_some(WireEnd { position, vertical: false }) + } + + pub fn connector_top_left(&self) -> DVec2 { + self.anchor() + INPUT_CONNECTOR_OFFSET + } + + pub fn name_box(&self, width: f64) -> [DVec2; 2] { + network_connector_name_box(self.key.kind(), self.anchor(), width).map(|corner| corner - DVec2::Y * NETWORK_CONNECTOR_NAME_RAISE) + } + + pub fn separator(&self, name_width: f64) -> [DVec2; 2] { + let [name_min, name_max] = self.name_box(name_width); + let toward_the_line = if self.key.index() == 0 { GRID_SIZE } else { -GRID_SIZE }; + let top = self.anchor().y + toward_the_line - BORDER_WIDTH; + [ + DVec2::new(name_min.x - NETWORK_CONNECTOR_SEPARATOR_OVERHANG, top), + DVec2::new(name_max.x + NETWORK_CONNECTOR_SEPARATOR_OVERHANG, top + BORDER_WIDTH), + ] + } +} + +pub fn reorder_bar(kind: NetworkConnectorKind, anchor: DVec2) -> [DVec2; 2] { + let left = match kind { + NetworkConnectorKind::Import => anchor.x - IMPORT_NAME_INSET - REORDER_BAR_SIZE.x, + NetworkConnectorKind::Export => anchor.x + EXPORT_NAME_INSET, + }; + let top_left = DVec2::new(left, anchor.y - GRID_SIZE / 2.); + [top_left, top_left + REORDER_BAR_SIZE] +} + +pub fn network_connector_name_box(kind: NetworkConnectorKind, anchor: DVec2, width: f64) -> [DVec2; 2] { + let left = match kind { + NetworkConnectorKind::Import => anchor.x - IMPORT_NAME_INSET - width, + NetworkConnectorKind::Export => anchor.x + EXPORT_NAME_INSET, + }; + let top_left = DVec2::new(left, anchor.y - GRID_SIZE / 2.); + [top_left, top_left + DVec2::new(width, GRID_SIZE)] +} + +pub fn network_connector_row_offset(index: usize) -> f64 { + let rows = if index == 0 { 0 } else { index + 1 }; + rows as f64 * GRID_SIZE +} diff --git a/node-graph/graph-ui/types/src/placed.rs b/node-graph/graph-ui/types/src/placed.rs new file mode 100644 index 0000000000..0e6aee28dd --- /dev/null +++ b/node-graph/graph-ui/types/src/placed.rs @@ -0,0 +1,17 @@ +use crate::replicated_map::Keyed; +use glam::IVec2; +use graphene_hash::CacheHash; + +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub struct Placed { + pub cell: IVec2, + pub look: T, +} + +impl Keyed for Placed { + type Key = T::Key; + + fn key(&self) -> T::Key { + self.look.key() + } +} diff --git a/node-graph/graph-ui/types/src/replicated_map.rs b/node-graph/graph-ui/types/src/replicated_map.rs new file mode 100644 index 0000000000..c1c945cc53 --- /dev/null +++ b/node-graph/graph-ui/types/src/replicated_map.rs @@ -0,0 +1,185 @@ +use dyn_any::StaticType; +use graphene_hash::CacheHash; +use std::fmt::Debug; +use std::hash::{DefaultHasher, Hasher}; +use std::ops::Deref; +use std::sync::{Arc, OnceLock}; + +pub trait Keyed: Clone { + type Key: Ord + Clone + Debug; + + fn key(&self) -> Self::Key; +} + +#[derive(Clone, Debug)] +pub struct ReplicatedMap { + items: Arc>, + hash: Arc>, +} + +impl Default for ReplicatedMap { + fn default() -> Self { + Self { + items: Arc::default(), + hash: Arc::default(), + } + } +} + +impl PartialEq for ReplicatedMap { + fn eq(&self, other: &Self) -> bool { + self.items == other.items + } +} + +unsafe impl StaticType for ReplicatedMap { + type Static = Self; +} + +impl CacheHash for ReplicatedMap { + fn cache_hash(&self, state: &mut H) { + let hash = self.hash.get_or_init(|| { + let mut hasher = DefaultHasher::new(); + self.items.cache_hash(&mut hasher); + hasher.finish() + }); + state.write_u64(*hash); + } +} + +impl ReplicatedMap { + pub fn get(&self, key: &T::Key) -> Option<&T> { + self.position(key).ok().map(|index| &self.items[index]) + } + + pub fn iter(&self) -> std::slice::Iter<'_, T> { + self.items.iter() + } + + pub fn len(&self) -> usize { + self.items.len() + } + + pub fn is_empty(&self) -> bool { + self.items.is_empty() + } + + pub fn edit(self) -> ReplicatedMapEdit { + ReplicatedMapEdit { map: self, deltas: Vec::new() } + } + + pub fn apply(&mut self, deltas: impl IntoIterator>) { + for delta in deltas { + match delta { + ReplicatedMapDelta::Put(item) => self.put(item), + ReplicatedMapDelta::Remove(key) => { + let removed = self.remove(&key); + debug_assert!(removed, "a delta removes an item that its map never held"); + } + } + } + } + + fn position(&self, key: &T::Key) -> Result { + self.items.binary_search_by(|item| item.key().cmp(key)) + } + + fn items_mut(&mut self) -> &mut Vec { + self.hash = Arc::default(); + Arc::make_mut(&mut self.items) + } + + fn put(&mut self, item: T) { + match self.position(&item.key()) { + Ok(index) => self.items_mut()[index] = item, + Err(index) => self.items_mut().insert(index, item), + } + } + + fn remove(&mut self, key: &T::Key) -> bool { + let position = self.position(key); + if let Ok(index) = position { + self.items_mut().remove(index); + } + position.is_ok() + } +} + +impl<'a, T: Keyed> IntoIterator for &'a ReplicatedMap { + type Item = &'a T; + type IntoIter = std::slice::Iter<'a, T>; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +#[derive(Clone, Debug)] +pub enum ReplicatedMapDelta { + Put(T), + Remove(T::Key), +} + +#[derive(Debug)] +pub struct ReplicatedMapEdit { + map: ReplicatedMap, + deltas: Vec>, +} + +impl Deref for ReplicatedMapEdit { + type Target = ReplicatedMap; + + fn deref(&self) -> &Self::Target { + &self.map + } +} + +impl ReplicatedMapEdit { + pub fn put(&mut self, item: T) + where + T: PartialEq, + { + if self.map.get(&item.key()) == Some(&item) { + return; + } + self.map.put(item.clone()); + self.deltas.push(ReplicatedMapDelta::Put(item)); + } + + pub fn update(&mut self, key: &T::Key, change: impl FnOnce(&mut T)) -> bool { + let Ok(index) = self.map.position(key) else { return false }; + let item = &mut self.map.items_mut()[index]; + change(item); + debug_assert!(item.key() == *key, "an update must not change the key of its item"); + self.deltas.push(ReplicatedMapDelta::Put(item.clone())); + true + } + + pub fn remove(&mut self, key: &T::Key) -> bool { + let removed = self.map.remove(key); + if removed { + self.deltas.push(ReplicatedMapDelta::Remove(key.clone())); + } + removed + } + + pub fn replace_all(&mut self, items: impl IntoIterator) + where + T: PartialEq, + { + let mut items: Vec = items.into_iter().collect(); + items.sort_by_key(T::key); + debug_assert!(items.windows(2).all(|pair| pair[0].key() != pair[1].key()), "two items of a map share a key"); + + let removed = self.map.iter().rev().map(T::key).filter(|key| items.binary_search_by(|item| item.key().cmp(key)).is_err()); + self.deltas.extend(removed.map(ReplicatedMapDelta::Remove)); + let put = items.iter().filter(|item| self.map.get(&item.key()) != Some(item)); + self.deltas.extend(put.cloned().map(ReplicatedMapDelta::Put)); + + *self.map.items_mut() = items; + } + + pub fn finish(self) -> (ReplicatedMap, Vec>) { + (self.map, self.deltas) + } +} diff --git a/node-graph/graph-ui/types/src/scene.rs b/node-graph/graph-ui/types/src/scene.rs new file mode 100644 index 0000000000..c9ff222e53 --- /dev/null +++ b/node-graph/graph-ui/types/src/scene.rs @@ -0,0 +1,161 @@ +use crate::card::Card; +use crate::dot::Dot; +use crate::error_badge::ErrorBadge; +use crate::layer::Layer; +use crate::network_connector::NetworkConnector; +use crate::placed::Placed; +use crate::replicated_map::{ReplicatedMap, ReplicatedMapDelta, ReplicatedMapEdit}; +use crate::wire::Wire; +use dyn_any::DynAny; +use graphene_hash::CacheHash; + +#[derive(Clone, Debug, Default, PartialEq, CacheHash, DynAny)] +pub struct Rows { + pub cards: ReplicatedMap>, + pub layers: ReplicatedMap>, + pub dots: ReplicatedMap>, + pub wires: ReplicatedMap, +} + +impl Rows { + fn edit(self) -> RowsEdit { + RowsEdit { + cards: self.cards.edit(), + layers: self.layers.edit(), + dots: self.dots.edit(), + wires: self.wires.edit(), + } + } + + fn apply(&mut self, delta: RowsDelta) { + self.cards.apply(delta.cards); + self.layers.apply(delta.layers); + self.dots.apply(delta.dots); + self.wires.apply(delta.wires); + } +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct GraphUiScene { + settled: Rows, + moving: Rows, + network_connectors: ReplicatedMap, + errors: ReplicatedMap, +} + +impl GraphUiScene { + pub fn settled(&self) -> &Rows { + &self.settled + } + + pub fn moving(&self) -> &Rows { + &self.moving + } + + pub fn network_connectors(&self) -> &ReplicatedMap { + &self.network_connectors + } + + pub fn errors(&self) -> &ReplicatedMap { + &self.errors + } + + pub fn edit(self) -> GraphUiSceneEdit { + GraphUiSceneEdit { + settled: self.settled.edit(), + moving: self.moving.edit(), + network_connectors: self.network_connectors.edit(), + errors: self.errors.edit(), + } + } + + pub fn apply(&mut self, delta: GraphUiSceneDelta) { + self.settled.apply(delta.settled); + self.moving.apply(delta.moving); + self.network_connectors.apply(delta.network_connectors); + self.errors.apply(delta.errors); + } +} + +pub struct RowsEdit { + pub cards: ReplicatedMapEdit>, + pub layers: ReplicatedMapEdit>, + pub dots: ReplicatedMapEdit>, + pub wires: ReplicatedMapEdit, +} + +impl RowsEdit { + fn finish(self) -> (Rows, RowsDelta) { + let (cards, card_deltas) = self.cards.finish(); + let (layers, layer_deltas) = self.layers.finish(); + let (dots, dot_deltas) = self.dots.finish(); + let (wires, wire_deltas) = self.wires.finish(); + ( + Rows { cards, layers, dots, wires }, + RowsDelta { + cards: card_deltas, + layers: layer_deltas, + dots: dot_deltas, + wires: wire_deltas, + }, + ) + } +} + +pub struct GraphUiSceneEdit { + pub settled: RowsEdit, + pub moving: RowsEdit, + pub network_connectors: ReplicatedMapEdit, + pub errors: ReplicatedMapEdit, +} + +impl GraphUiSceneEdit { + pub fn finish(self) -> (GraphUiScene, GraphUiSceneDelta) { + let (settled, settled_delta) = self.settled.finish(); + let (moving, moving_delta) = self.moving.finish(); + let (network_connectors, network_connector_deltas) = self.network_connectors.finish(); + let (errors, error_deltas) = self.errors.finish(); + ( + GraphUiScene { + settled, + moving, + network_connectors, + errors, + }, + GraphUiSceneDelta { + settled: settled_delta, + moving: moving_delta, + network_connectors: network_connector_deltas, + errors: error_deltas, + }, + ) + } +} + +#[derive(Debug)] +struct RowsDelta { + cards: Vec>>, + layers: Vec>>, + dots: Vec>>, + wires: Vec>, +} + +impl RowsDelta { + fn is_empty(&self) -> bool { + self.cards.is_empty() && self.layers.is_empty() && self.dots.is_empty() && self.wires.is_empty() + } +} + +#[derive(Debug)] +pub struct GraphUiSceneDelta { + settled: RowsDelta, + moving: RowsDelta, + network_connectors: Vec>, + errors: Vec>, +} + +impl GraphUiSceneDelta { + pub fn is_empty(&self) -> bool { + self.settled.is_empty() && self.moving.is_empty() && self.network_connectors.is_empty() && self.errors.is_empty() + } +} diff --git a/node-graph/graph-ui/types/src/wire.rs b/node-graph/graph-ui/types/src/wire.rs new file mode 100644 index 0000000000..a737226cad --- /dev/null +++ b/node-graph/graph-ui/types/src/wire.rs @@ -0,0 +1,57 @@ +use crate::card::DataType; +use crate::geometry::WireEnd; +use crate::replicated_map::Keyed; +use core_types::uuid::NodeId; +use dyn_any::DynAny; +use graphene_hash::CacheHash; + +#[derive(Clone, Debug, PartialEq, CacheHash)] +pub struct Wire { + pub key: WireKey, + pub from: OutputKey, + pub to: InputKey, + pub data_type: DataType, + pub list: bool, + pub insertion_target: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)] +pub enum WireKey { + Input(InputKey), + Preview, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)] +pub enum OutputKey { + Node { node: NodeId, index: usize }, + Import(usize), +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)] +pub enum InputKey { + Node { node: NodeId, index: usize }, + Export(usize), +} + +impl Keyed for Wire { + type Key = WireKey; + + fn key(&self) -> WireKey { + self.key + } +} + +#[derive(Clone, Copy, Debug, PartialEq, CacheHash, DynAny)] +pub struct WireInProgress { + pub ends: [WireEnd; 2], + pub data_type: DataType, +} + +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Copy, Clone, Debug, PartialEq, Default, CacheHash, DynAny)] +pub enum WireStyle { + #[default] + Direct = 0, + GridAligned = 1, +}