Compare commits

..
Author SHA1 Message Date
Timon d27468144e Add the graph-ui crate, which draws the node graph with Graphene 2026-12-01 13:31:02 +00:00
26 changed files with 4997 additions and 0 deletions

No files matched your search

Generated
+29
View File
@@ -2535,6 +2535,35 @@ dependencies = [
"smallvec",
]
[[package]]
name = "graph-ui"
version = "0.0.0"
dependencies = [
"core-types",
"dyn-any",
"futures",
"glam",
"graph-craft",
"graph-ui-icons",
"graphene-application-io",
"graphene-hash",
"graphene-std",
"graphic-types",
"interpreted-executor",
"node-macro",
"preprocessor",
"rendering",
"svg-convert",
"text-nodes",
"vector-types",
"vello_gpu",
"wgpu-executor",
]
[[package]]
name = "graph-ui-icons"
version = "0.0.0"
[[package]]
name = "graphene-animation"
version = "0.0.0"
+4
View File
@@ -34,6 +34,8 @@ members = [
"node-graph/libraries/*",
"node-graph/nodes/*",
"node-graph/graph-craft",
"node-graph/graph-ui",
"node-graph/graph-ui/icons",
"node-graph/graphene-cli",
"node-graph/nodes/gstd",
"node-graph/interpreted-executor",
@@ -112,6 +114,8 @@ 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" }
document-format = { path = "document/format" }
document-graph-storage = { path = "document/graph-storage", default-features = false }
document-container = { path = "document/container" }
+44
View File
@@ -0,0 +1,44 @@
[package]
name = "graph-ui"
description = "The node graph UI of Graphite, drawn by Graphene"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[dependencies]
# Local dependencies
core-types = { workspace = true }
dyn-any = { workspace = true }
graph-craft = { workspace = true }
graph-ui-icons = { workspace = true }
graphene-application-io = { workspace = true }
graphene-hash = { 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 }
wgpu-executor = { workspace = true }
# Workspace dependencies
glam = { workspace = true }
vello_gpu = { workspace = true }
[dev-dependencies]
# Local dependencies
interpreted-executor = { workspace = true }
preprocessor = { workspace = true }
# Workspace dependencies
futures = { workspace = true }
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "graph-ui-icons"
description = "The icons of the node graph UI of Graphite, as SVG sources"
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
+39
View File
@@ -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()
}
+24
View File
@@ -0,0 +1,24 @@
// 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)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_icons_are_found_by_the_names_the_frontend_gives_them() {
let icons_ts = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../frontend/src/icons.ts")).unwrap();
let imported = icons_ts.lines().filter_map(|line| line.strip_prefix("import ")?.split_once(" from \"/../branding/assets/"));
let names = imported
.filter(|(_, path)| path.starts_with("16x16-nodes/") || path.starts_with("16x16-ui-general/"))
.map(|(name, _)| name);
let missing: Vec<_> = names.filter(|name| svg(name).is_none()).collect();
assert!(SOURCES.is_empty() || missing.is_empty(), "{missing:?}");
}
}
+126
View File
@@ -0,0 +1,126 @@
use crate::metrics::{CONNECTOR_SIZE, GRID_SIZE, INPUT_CONNECTOR_LEFT, NODE_WIDTH, OUTPUT_CONNECTOR_RIGHT};
use crate::replicated_map::Keyed;
use core_types::uuid::NodeId;
use glam::{DVec2, IVec2};
use graphene_hash::CacheHash;
#[derive(Clone, Debug, PartialEq, CacheHash)]
pub struct Card {
pub key: NodeId,
pub cell: IVec2,
pub name: String,
pub icon: String,
pub primary_input: Option<Connector>,
pub primary_output: Option<Connector>,
pub secondary_inputs: Vec<Connector>,
pub secondary_outputs: Vec<Connector>,
pub selection: Selection,
pub visible: bool,
pub previewed: bool,
pub glide: DVec2,
}
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
pub enum Selection {
None,
Inactive,
Active,
}
#[derive(Clone, Debug, PartialEq, CacheHash)]
pub struct Connector {
pub name: String,
pub data_type: DataType,
pub connected: bool,
pub highlight: Highlight,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
pub enum Highlight {
#[default]
None,
Hovered,
WireSource,
WireTarget,
}
#[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
}
}
impl Card {
pub fn rows(&self) -> usize {
1 + self.secondary_inputs.len().max(self.secondary_outputs.len())
}
pub fn body(&self) -> [DVec2; 2] {
let top_left = (self.cell.as_dvec2() + DVec2::new(0., 0.5)) * GRID_SIZE + self.glide;
[top_left, top_left + DVec2::new(NODE_WIDTH, self.rows() as f64 * GRID_SIZE)]
}
pub fn inputs(&self) -> impl Iterator<Item = (DVec2, &Connector)> {
self.connectors(&self.primary_input, &self.secondary_inputs, INPUT_CONNECTOR_LEFT)
}
pub fn outputs(&self) -> impl Iterator<Item = (DVec2, &Connector)> {
self.connectors(&self.primary_output, &self.secondary_outputs, NODE_WIDTH + OUTPUT_CONNECTOR_RIGHT - CONNECTOR_SIZE)
}
fn connectors<'a>(&self, primary: &'a Option<Connector>, secondary: &'a [Connector], left: f64) -> impl Iterator<Item = (DVec2, &'a Connector)> {
let [top_left, _] = self.body();
let rows = primary
.iter()
.map(|connector| (0, connector))
.chain(secondary.iter().enumerate().map(|(index, connector)| (index + 1, connector)));
rows.map(move |(row, connector)| (top_left + DVec2::new(left, row as f64 * GRID_SIZE + (GRID_SIZE - CONNECTOR_SIZE) / 2.), connector))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::{card, connector};
#[test]
fn a_node_body_is_five_cells_wide_and_starts_half_a_cell_below_its_cell() {
let mut card = Card {
cell: IVec2::new(2, -1),
primary_output: Some(connector("Shape")),
..card(0)
};
assert_eq!(card.body(), [DVec2::new(48., -12.), DVec2::new(168., 12.)]);
card.secondary_inputs = vec![connector("Width"), connector("Height")];
card.secondary_outputs = vec![connector("Area")];
assert_eq!(card.body(), [DVec2::new(48., -12.), DVec2::new(168., 60.)], "a row for each secondary input");
let top_left = |(top_left, _): (DVec2, &Connector)| top_left;
assert_eq!(card.inputs().map(top_left).collect::<Vec<_>>(), [DVec2::new(45., 20.), DVec2::new(45., 44.)], "no primary input");
assert_eq!(card.outputs().map(top_left).collect::<Vec<_>>(), [DVec2::new(165., -4.), DVec2::new(165., 20.)]);
}
#[test]
fn a_gliding_card_is_drawn_its_glide_away() {
let glide = DVec2::new(3., -4.);
let gliding = Card { glide, ..card(0) };
assert_eq!(gliding.body(), card(0).body().map(|corner| corner + glide));
}
}
+349
View File
@@ -0,0 +1,349 @@
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<Vec<PathSeg>> {
let mut contours: Vec<Vec<PathSeg>> = 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<Measured> {
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<f64>, depth: u32, segment: usize, measured: &mut Vec<Measured>) -> 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<Measured>) -> 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<f64>, 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<f64>| 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<f64> = 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)
}
#[cfg(test)]
mod tests {
use super::*;
use vello_gpu::kurbo::Shape;
#[test]
fn dashes_start_at_the_start_of_each_contour_and_are_cut_at_its_end() {
let mut path = BezPath::new();
path.move_to((0., 0.));
path.line_to((12., 0.));
path.move_to((0., 10.));
path.line_to((4., 10.));
let starts: Vec<Point> = dashed(&path, [3., 2.])
.elements()
.iter()
.filter_map(|element| if let PathEl::MoveTo(point) = element { Some(*point) } else { None })
.collect();
assert_eq!(starts, [(0., 0.), (5., 0.), (10., 0.), (0., 10.)].map(Point::from));
let ends: Vec<Point> = dashed(&path, [3., 2.])
.elements()
.iter()
.filter_map(|element| if let PathEl::LineTo(point) = element { Some(*point) } else { None })
.collect();
assert_eq!(ends, [(3., 0.), (8., 0.), (12., 0.), (3., 10.)].map(Point::from));
}
#[test]
fn a_curve_is_measured_along_chords_that_stray_from_it_by_at_most_half_a_pixel() {
let mut path = BezPath::new();
path.move_to((0., 0.));
path.curve_to((0., 100.), (100., 100.), (100., 0.));
let measured = measure(&contours(&path)[0]);
let measured_length = measured.last().unwrap().distance;
let length = vello_gpu::kurbo::ParamCurveArclen::arclen(&CubicBez::new((0., 0.), (0., 100.), (100., 100.), (100., 0.)), 1e-9);
assert!(measured_length < length && length - measured_length < 1., "{measured_length} {length}");
assert!(measured.windows(2).all(|pair| pair[0].t < pair[1].t), "the chords follow the curve");
}
#[test]
fn the_dashes_of_a_border_follow_its_outer_edge_with_flattened_corners_and_the_gap_nearest_two_pixels() {
let starts = |path: &BezPath| {
path.elements()
.iter()
.filter_map(|element| if let PathEl::MoveTo(point) = element { Some(*point) } else { None })
.collect::<Vec<_>>()
};
let layer = starts(&border(DVec2::ZERO, DVec2::new(912., 48.), 8., &[], true));
let on_top = layer.iter().filter(|point| point.y == 0.5).map(|point| point.x);
assert!(
on_top.clone().all(|x| ((x - 8.) / 5. - ((x - 8.) / 5.).round()).abs() < 1e-9),
"the dashes along the top of a layer are five pixels apart"
);
assert_eq!(on_top.count(), 180);
assert_eq!(layer.len(), 381);
assert_eq!(
starts(&border(DVec2::ZERO, DVec2::new(120., 72.), 2., &[], true)).len(),
76,
"a node card, its corners measured as chords"
);
}
#[test]
fn a_border_is_left_out_inside_its_gaps_corners_included() {
let [min, max] = [DVec2::ZERO, DVec2::new(100., 48.)];
let starts = |path: &BezPath| path.elements().iter().filter(|element| matches!(element, PathEl::MoveTo(_))).count();
assert_eq!(starts(&border(min, max, 8., &[], false)), 1);
let left = [DVec2::new(-8., -2.), DVec2::new(30., 50.)];
let right = [DVec2::new(88., 12.), DVec2::new(112., 36.)];
let cut = border(min, max, 8., &[left, right], false);
assert_eq!(starts(&cut), 2, "the right gap splits what the left gap leaves");
let bounds = cut.bounding_box();
assert!((bounds.x0 - 30.).abs() < 1e-9 && bounds.x1 == 99.5, "{bounds:?}");
let on_the_right = cut.elements().iter().filter_map(|element| element.end_point()).filter(|point| point.x == 99.5);
assert!(
on_the_right.clone().all(|point| !(12.001..=35.999).contains(&point.y)),
"the right gap leaves out the middle of the right side"
);
assert!(on_the_right.clone().any(|point| (point.y - 12.).abs() < 1e-9) && on_the_right.clone().any(|point| (point.y - 36.).abs() < 1e-9));
}
}
+47
View File
@@ -0,0 +1,47 @@
use crate::card::{DataType, Highlight};
use crate::metrics::GRID_SIZE;
use crate::replicated_map::Keyed;
use core_types::uuid::NodeId;
use glam::{DVec2, IVec2};
use graphene_hash::CacheHash;
#[derive(Clone, Debug, PartialEq, CacheHash)]
pub struct Dot {
pub key: NodeId,
pub cell: IVec2,
pub data_type: DataType,
pub wired: bool,
pub selected: bool,
pub previewed: bool,
pub highlight: Highlight,
pub output_highlight: Highlight,
pub glide: DVec2,
}
impl Keyed for Dot {
type Key = NodeId;
fn key(&self) -> NodeId {
self.key
}
}
impl Dot {
pub fn center(&self) -> DVec2 {
(self.cell.as_dvec2() + DVec2::Y) * GRID_SIZE + self.glide
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::dot;
#[test]
fn a_dot_sits_on_the_left_edge_of_its_cell_a_cell_down() {
let dot = Dot { cell: IVec2::new(2, -1), ..dot(0) };
assert_eq!(dot.center(), DVec2::new(48., 0.));
let gliding = Dot { glide: DVec2::new(3., -4.), ..dot };
assert_eq!(gliding.center(), DVec2::new(51., -4.), "a gliding dot is drawn its glide away");
}
}
+105
View File
@@ -0,0 +1,105 @@
use crate::metrics::{ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH, ERROR_PADDING, ERROR_TAIL_LEFT, ERROR_TAIL_SIZE, GRID_SIZE, LAYER_LEFT_MARGIN};
use crate::replicated_map::Keyed;
use crate::text;
use core_types::uuid::NodeId;
use glam::{DVec2, IVec2};
use graphene_hash::CacheHash;
#[derive(Clone, Debug, PartialEq, CacheHash)]
pub struct ErrorBadge {
pub key: NodeId,
pub cell: IVec2,
pub on_layer: bool,
pub text: String,
pub hovered: bool,
pub glide: DVec2,
}
impl Keyed for ErrorBadge {
type Key = NodeId;
fn key(&self) -> NodeId {
self.key
}
}
impl ErrorBadge {
fn anchor(&self) -> DVec2 {
let offset = if self.on_layer { DVec2::new(LAYER_LEFT_MARGIN, -GRID_SIZE / 2.) } else { DVec2::ZERO };
self.cell.as_dvec2() * GRID_SIZE + offset + self.glide
}
pub fn text_size(&self) -> DVec2 {
text::paragraph_size(&self.text, ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH)
}
pub fn body(&self, text_size: DVec2) -> [DVec2; 2] {
let bottom_left = self.anchor();
let size = text_size + 2. * ERROR_PADDING;
[bottom_left - DVec2::Y * size.y, bottom_left + DVec2::X * size.x]
}
pub fn text_top_left(&self, text_size: DVec2) -> DVec2 {
let [top_left, _] = self.body(text_size);
top_left + ERROR_PADDING
}
pub fn tail(&self) -> [DVec2; 3] {
let top_left = self.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(&self, point: DVec2, text_size: DVec2) -> bool {
let [tail, ..] = self.tail();
let within = |[min, max]: [DVec2; 2]| min.cmple(point).all() && point.cmple(max).all();
within(self.body(text_size)) || within([tail, tail + ERROR_TAIL_SIZE])
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::badge;
#[test]
fn a_badge_stands_half_a_cell_above_its_card_or_above_the_thumbnail_of_its_layer() {
let badge = ErrorBadge {
cell: IVec2::new(13, 22),
..badge(0, "")
};
assert_eq!(badge.anchor(), DVec2::new(312., 528.));
let on_layer = ErrorBadge { on_layer: true, ..badge };
assert_eq!(on_layer.anchor(), DVec2::new(324., 516.));
}
#[test]
fn a_badge_grows_up_and_right_from_its_anchor_with_its_tail_below() {
let badge = ErrorBadge {
cell: IVec2::new(2, 1),
..badge(0, "")
};
let text_size = DVec2::new(100., 36.);
assert_eq!(badge.body(text_size), [DVec2::new(48., -28.), DVec2::new(164., 24.)]);
assert_eq!(badge.text_top_left(text_size), DVec2::new(56., -20.), "the text is padded");
assert_eq!(badge.tail(), [DVec2::new(54., 24.), DVec2::new(66., 24.), DVec2::new(60., 32.)]);
let glide = DVec2::new(3., -4.);
let gliding = ErrorBadge { glide, ..badge.clone() };
assert_eq!(gliding.body(text_size), badge.body(text_size).map(|corner| corner + glide), "a gliding badge is drawn its glide away");
assert_eq!(gliding.tail(), badge.tail().map(|corner| corner + glide), "its tail glides with it");
}
#[test]
fn a_badge_covers_its_box_and_the_box_around_its_tail() {
let badge = ErrorBadge {
cell: IVec2::new(2, 1),
..badge(0, "Error")
};
let text_size = badge.text_size();
let covers = |point| badge.covers(point, text_size);
let [min, max] = badge.body(text_size);
assert!(covers(min) && covers(max - 1.) && covers((min + max) / 2.), "the box");
assert!(covers(DVec2::new(55., 31.)), "beside the tip of the tail, inside the box around it");
assert!(!covers(DVec2::new(52., 30.)), "left of the tail");
assert!(!covers(max + 1.), "beyond the box");
}
}
+146
View File
@@ -0,0 +1,146 @@
// 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<Vector>,
pub(crate) overflows: bool,
}
type Converted = HashMap<SRGBA8, HashMap<String, Option<Icon>>>;
static CONVERTED: LazyLock<Mutex<Converted>> = LazyLock::new(Mutex::default);
pub fn icon(name: &str, current: SRGBA8) -> Option<Icon> {
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<Icon> {
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<Vector> = 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<SRGBA8> {
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<SRGBA8> {
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 })
}
#[cfg(test)]
mod tests {
use super::*;
use core_types::list::ATTR_APPEARANCE;
use graphic_types::{Appearance, Cover, Graphic};
const CURRENT: SRGBA8 = SRGBA8::new_opaque(0x12, 0x34, 0x56);
fn icon(shapes: &str) -> Option<Icon> {
convert(&format!(r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">{shapes}</svg>"#), CURRENT)
}
fn hex(color: Option<SRGBA8>) -> Option<String> {
color.map(|color| format!("{:02x}{:02x}{:02x}", color.red, color.green, color.blue))
}
fn fills(icon: &Icon) -> Vec<Option<String>> {
let fill = |index| match icon.shapes.attribute::<Appearance>(ATTR_APPEARANCE, index)?.first_paint_of(Cover::Fill)? {
Graphic::Color(color) => hex(Some(SRGBA8::from(*color.element()))),
_ => None,
};
(0..icon.shapes.len()).map(fill).collect()
}
#[test]
fn a_color_class_names_its_color() {
assert_eq!(hex(class_color("color-8-uppergray")).as_deref(), Some("888888"));
assert_eq!(hex(class_color("color-number-dim")).as_deref(), Some("886b60"));
assert_eq!(hex(class_color("color-mix-gradient-gradient-dim-85")).as_deref(), Some("7651a7"));
assert_eq!(hex(class_color("color-mix-raster-dim-7-middlegray-50")).as_deref(), Some("89795d"));
assert_eq!(class_color("color-sepia"), None);
assert_eq!(class_color("color-mix-general-sepia-50"), None);
}
#[test]
fn an_icon_is_its_shapes_in_document_order_filled_with_their_class_colors_or_the_current_color() {
let icon = icon(r#"<path class="color-number" d="M2,2L14,2L14,14Z" /><circle cx="8" cy="8" r="2" />"#).unwrap();
assert_eq!(fills(&icon), [Some("c9a699".to_string()), hex(Some(CURRENT))]);
}
#[test]
fn an_icon_overflows_when_a_shape_reaches_past_its_box() {
assert!(!icon(r#"<rect x="2" y="2" width="12" height="12" />"#).unwrap().overflows);
assert!(icon(r#"<path d="M14,2L17,2L17,5L14,5Z" />"#).unwrap().overflows);
assert!(
icon(r#"<rect transform="translate(4)" x="2" y="2" width="12" height="12" />"#).unwrap().overflows,
"moved out by its transform"
);
}
#[test]
fn an_icon_with_an_unknown_color_class_is_left_out() {
assert!(icon(r#"<path class="color-sepia" d="M2,2L14,2Z" />"#).is_none());
}
}
+175
View File
@@ -0,0 +1,175 @@
use crate::card::{Connector, Selection};
use crate::metrics::{
CONNECTOR_SIZE, GRID_SIZE, INPUT_CONNECTOR_LEFT, LAYER_BUTTON_SIZE, LAYER_DETAILS_MARGIN, LAYER_GRIP_WIDTH, LAYER_HEIGHT, LAYER_LEFT_MARGIN, LAYER_NAME_LEFT, LAYER_THUMBNAIL_IMAGE_INSET,
LAYER_THUMBNAIL_MARGIN, LAYER_THUMBNAIL_WIDTH, STACK_CONNECTOR_SIZE,
};
use crate::replicated_map::Keyed;
use core_types::uuid::NodeId;
use glam::{DVec2, IVec2};
use graphene_hash::CacheHash;
#[derive(Clone, Debug, PartialEq, CacheHash)]
pub struct Layer {
pub key: NodeId,
pub cell: IVec2,
pub name: String,
pub renaming: bool,
pub width: u32,
pub chain_width: u32,
pub has_left_input_wire: bool,
pub primary_input: Option<Connector>,
pub primary_output: Option<Connector>,
pub secondary_input: Option<Connector>,
pub primary_input_connected_to_layer: bool,
pub primary_output_connected_to_layer: bool,
pub visible: bool,
pub locked: bool,
pub read_only: bool,
pub selection: Selection,
pub previewed: bool,
pub hovered_button: Option<LayerButton>,
pub hovered_button_clicked: bool,
pub glide: DVec2,
}
#[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
}
}
impl Layer {
fn top_left(&self) -> DVec2 {
self.cell.as_dvec2() * GRID_SIZE + self.glide
}
pub fn body(&self) -> [DVec2; 2] {
let top_left = self.top_left();
let left = if self.chain_width > 0 { -(self.chain_width as f64) * GRID_SIZE } else { LAYER_LEFT_MARGIN };
[top_left + DVec2::X * left, top_left + DVec2::new(self.width as f64 * GRID_SIZE, LAYER_HEIGHT)]
}
pub fn left_input_wire(&self) -> Option<DVec2> {
let [min, _] = self.body();
(self.has_left_input_wire && self.chain_width > 0).then(|| DVec2::new(min.x, min.y + LAYER_HEIGHT / 2.))
}
pub fn thumbnail_block(&self) -> [DVec2; 2] {
let left = self.top_left() + DVec2::X * LAYER_LEFT_MARGIN;
[left, left + DVec2::new(LAYER_THUMBNAIL_WIDTH, LAYER_HEIGHT)]
}
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.top_left() + DVec2::new(INPUT_CONNECTOR_LEFT, (LAYER_HEIGHT - CONNECTOR_SIZE) / 2.)
}
pub fn name_box(&self) -> [DVec2; 2] {
let top_left = self.top_left() + DVec2::new(LAYER_NAME_LEFT, (LAYER_HEIGHT - GRID_SIZE) / 2.);
[top_left, top_left + DVec2::new(self.name_width(), GRID_SIZE)]
}
pub fn name_width(&self) -> f64 {
self.width as f64 * GRID_SIZE - LAYER_NAME_LEFT - LAYER_DETAILS_MARGIN
}
pub fn visibility(&self) -> [DVec2; 2] {
let [_, max] = self.body();
let top_left = DVec2::new(max.x - LAYER_BUTTON_SIZE / 2., self.top_left().y + (LAYER_HEIGHT - LAYER_BUTTON_SIZE) / 2.);
[top_left, top_left + LAYER_BUTTON_SIZE]
}
pub 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]
}
pub fn lock(&self) -> Option<[DVec2; 2]> {
let [min, max] = self.visibility();
self.locked.then(|| [min - DVec2::X * LAYER_BUTTON_SIZE, max - DVec2::X * LAYER_BUTTON_SIZE])
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::layer;
#[test]
fn a_layer_spans_its_width_from_half_a_cell_into_its_cell() {
let layer = Layer {
cell: IVec2::new(2, -1),
has_left_input_wire: true,
..layer(0)
};
assert_eq!(layer.body(), [DVec2::new(60., -24.), DVec2::new(240., 24.)]);
assert_eq!(layer.thumbnail_block(), [DVec2::new(60., -24.), DVec2::new(132., 24.)]);
assert_eq!(layer.thumbnail(), [DVec2::new(61., -24.), DVec2::new(131., 24.)], "a pixel in from each side of its block");
assert_eq!(
layer.thumbnail_image(),
[DVec2::new(63., -22.), DVec2::new(129., 22.)],
"two pixels in from the thumbnail, at its aspect ratio"
);
assert_eq!(
layer.name_box(),
[DVec2::new(140., -12.), DVec2::new(232., 12.)],
"the name follows the thumbnail and ends a margin short of the right edge"
);
assert_eq!(layer.stack_output(), DVec2::new(92., -36.), "the stack connectors are centred above and below the thumbnail");
assert_eq!(layer.stack_input(), DVec2::new(92., 24.));
assert_eq!(layer.secondary_input_connector(), DVec2::new(45., -4.), "the input on the left side sits where a node's would");
assert_eq!(
layer.visibility(),
[DVec2::new(228., -12.), DVec2::new(252., 12.)],
"the visibility button is centred on the right edge"
);
assert_eq!(layer.left_input_wire(), None, "no chain for a wire to enter");
let gliding = Layer {
glide: DVec2::new(3., -4.),
..layer.clone()
};
assert_eq!(
gliding.visibility(),
layer.visibility().map(|corner| corner + DVec2::new(3., -4.)),
"a gliding layer is drawn its glide away"
);
assert_eq!(layer.lock(), None, "an unlocked layer has no lock button");
let locked = Layer { locked: true, ..layer.clone() };
assert_eq!(locked.lock(), Some([DVec2::new(204., -12.), DVec2::new(228., 12.)]), "the lock button is left of the visibility button");
assert_eq!(layer.grip(), [DVec2::new(220., -12.), DVec2::new(228., 12.)], "the grip is left of the visibility button");
assert_eq!(locked.grip(), [DVec2::new(196., -12.), DVec2::new(204., 12.)], "the grip is left of the lock button");
let chained = Layer { chain_width: 8, ..layer };
assert_eq!(chained.body(), [DVec2::new(-144., -24.), DVec2::new(240., 24.)], "the chain reaches left of the cell");
assert_eq!(chained.thumbnail_block()[0], DVec2::new(60., -24.), "the thumbnail stays where it is");
assert_eq!(chained.left_input_wire(), Some(DVec2::new(-144., 0.)));
}
}
+43
View File
@@ -0,0 +1,43 @@
use core_types::uuid::NodeId;
use glam::{DAffine2, DVec2};
use graphene_hash::CacheHash;
use graphic_types::Graphic;
use network_connector::NetworkConnectorKind;
use scene::GraphUiScene;
use std::collections::BTreeMap;
use std::sync::Arc;
use wire::WireInProgress;
pub mod card;
mod dashes;
pub mod dot;
pub mod error_badge;
pub mod icons;
pub mod layer;
mod look;
pub mod metrics;
pub mod network_connector;
pub mod nodes;
pub mod render;
pub mod replicated_map;
pub mod scene;
#[cfg(test)]
mod test_utils;
mod text;
pub mod wire;
#[derive(CacheHash)]
pub struct GraphUi {
pub scene: GraphUiScene,
pub config: GraphUiConfig,
pub thumbnails: Arc<BTreeMap<NodeId, Graphic>>,
}
#[derive(Clone, Copy, Debug, CacheHash)]
pub struct GraphUiConfig {
pub view: DAffine2,
pub fade_artwork: f64,
pub wire_in_progress: Option<WireInProgress>,
pub reorder_bar: Option<(NetworkConnectorKind, DVec2)>,
pub box_selection: Option<[DVec2; 2]>,
}
+147
View File
@@ -0,0 +1,147 @@
use crate::card::{Connector, DataType, 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<BezPath> = 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<BezPath> = 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<BezPath> = 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<BezPath> = 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<BezPath> = 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) -> List<Vector> {
drawn_connector(outline, top_left, connector.data_type, connector.connected, connector.highlight)
}
pub(crate) fn drawn_connector(outline: &BezPath, top_left: DVec2, data_type: DataType, connected: bool, highlight: Highlight) -> List<Vector> {
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<Vector> {
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> {
Vector::item_from_bezpath(&rounded_rectangle_bezpath(min, max, radii))
}
pub(crate) fn icon(name: &str, top_left: DVec2, current: SRGBA8) -> List<Vector> {
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<Vector>, top_left: DVec2, color: SRGBA8) -> List<Vector> {
let glyphs = outline.clone().into_iter();
let mut glyphs: List<Vector> = 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<Vector> {
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<Vector>, coverage: Coverage, color: Color) -> Item<Vector> {
stamp_coverage(&mut item, coverage, Graphic::from(color), CoverPlacement::Above);
item
}
+67
View File
@@ -0,0 +1,67 @@
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 NODE_WIDTH: f64 = 5. * GRID_SIZE;
pub const NODE_RADIUS: f64 = 2.;
pub const NODE_ICON_LEFT: f64 = 8.;
pub const NODE_NAME_LEFT: f64 = 32.;
pub const NODE_NAME_MAX_WIDTH: f64 = 84.;
pub const NODE_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 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_EXPORT_CONNECTOR: DVec2 = DVec2::new(INPUT_CONNECTOR_LEFT, -CONNECTOR_SIZE / 2.);
pub const IMPORT_NAME_INSET: f64 = 8.;
pub const EXPORT_NAME_INSET: f64 = 9.;
pub const IMPORT_EXPORT_NAME_RAISE: f64 = 1.;
pub const IMPORT_EXPORT_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(6., -4.);
pub const LAYER_HEIGHT: f64 = 2. * GRID_SIZE;
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 CHECKER_CELL: f64 = 8.;
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.);
@@ -0,0 +1,117 @@
use crate::card::{Connector, Highlight};
use crate::metrics::{BORDER_WIDTH, EXPORT_NAME_INSET, GRID_SIZE, IMPORT_EXPORT_CONNECTOR, IMPORT_EXPORT_NAME_RAISE, IMPORT_EXPORT_SEPARATOR_OVERHANG, IMPORT_NAME_INSET, REORDER_BAR_SIZE};
use crate::replicated_map::Keyed;
use glam::{DVec2, IVec2};
use graphene_hash::CacheHash;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)]
pub enum NetworkConnectorKind {
Import,
Export,
}
#[derive(Clone, Debug, PartialEq, CacheHash)]
pub struct NetworkConnector {
pub kind: NetworkConnectorKind,
pub index: usize,
pub position: IVec2,
pub connector: Option<Connector>,
pub add_highlight: Highlight,
pub editable: bool,
pub renaming: bool,
pub glide: DVec2,
}
impl Keyed for NetworkConnector {
type Key = (NetworkConnectorKind, usize);
fn key(&self) -> (NetworkConnectorKind, usize) {
(self.kind, self.index)
}
}
impl NetworkConnector {
pub fn anchor(&self) -> DVec2 {
self.position.as_dvec2() + self.glide
}
pub fn connector_top_left(&self) -> DVec2 {
self.anchor() + IMPORT_EXPORT_CONNECTOR
}
pub fn name_box(&self, width: f64) -> [DVec2; 2] {
let anchor = self.anchor();
let left = match self.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. - IMPORT_EXPORT_NAME_RAISE);
[top_left, top_left + DVec2::new(width, GRID_SIZE)]
}
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.index == 0 { GRID_SIZE } else { -GRID_SIZE };
let top = self.anchor().y + toward_the_line - BORDER_WIDTH;
[
DVec2::new(name_min.x - IMPORT_EXPORT_SEPARATOR_OVERHANG, top),
DVec2::new(name_max.x + IMPORT_EXPORT_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 import_export_row_offset(index: usize) -> f64 {
let rows = if index == 0 { 0 } else { index + 1 };
rows as f64 * GRID_SIZE
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::network_connector;
#[test]
fn the_name_of_an_import_ends_left_of_its_connector_and_the_name_of_an_export_starts_right_of_it() {
let primary = NetworkConnector {
position: IVec2::new(48, -24),
..network_connector(NetworkConnectorKind::Import, 0)
};
let secondary = NetworkConnector {
position: IVec2::new(48, 24),
..network_connector(NetworkConnectorKind::Import, 1)
};
assert_eq!(secondary.connector_top_left(), DVec2::new(45., 20.), "the connector box beside the anchor");
let gliding = NetworkConnector {
glide: DVec2::new(3., -4.),
..secondary.clone()
};
assert_eq!(gliding.anchor(), DVec2::new(51., 20.), "a gliding import is drawn its glide away");
assert_eq!(primary.name_box(30.), [DVec2::new(10., -37.), DVec2::new(40., -13.)], "an import's name ends left of its connector");
let export = NetworkConnector {
kind: NetworkConnectorKind::Export,
..primary.clone()
};
assert_eq!(export.name_box(30.), [DVec2::new(57., -37.), DVec2::new(87., -13.)], "an export's name starts right of its connector");
assert_eq!(primary.separator(30.), [DVec2::new(6., -1.), DVec2::new(44., 0.)], "the line under the primary name");
assert_eq!(secondary.separator(20.), [DVec2::new(16., -1.), DVec2::new(44., 0.)], "the line over the next name, the same line");
assert_eq!(
reorder_bar(NetworkConnectorKind::Import, secondary.anchor()),
[DVec2::new(-10., 12.), DVec2::new(40., 14.)],
"the bar where an import would be dropped, above its row"
);
assert_eq!(
reorder_bar(NetworkConnectorKind::Export, primary.anchor()),
[DVec2::new(57., -36.), DVec2::new(107., -34.)],
"the bar where an export would be dropped"
);
}
}
+816
View File
@@ -0,0 +1,816 @@
use crate::card::{Card, Connector, DataType, Highlight, Selection};
use crate::dashes::{border, dashed};
use crate::dot::Dot;
use crate::error_badge::ErrorBadge;
use crate::layer::{Layer, LayerButton};
use crate::look::{
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, outlined, painted, rounded_rect, text,
};
use crate::metrics::{
BORDER_WIDTH, 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, NODE_ICON_LEFT, NODE_NAME_LEFT, NODE_NAME_MAX_WIDTH, NODE_RADIUS, NODE_ROW_PADDING, NODE_WIDTH, THICK_WIRE_WIDTH,
WIRE_DASHES, WIRE_WIDTH,
};
use crate::network_connector::{NetworkConnector, reorder_bar};
use crate::render::{graph_ui, render_config};
use crate::replicated_map::{Keyed, ReplicatedMap};
use crate::text::{Labels, Paragraphs};
use crate::wire::{Wire, WireKey};
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, ExtractVarArgs};
use glam::{DAffine2, DVec2, IVec2};
use graphic_types::{CoverPlacement, Coverage, Graphic, Vector, stamp_coverage};
use std::collections::{BTreeMap, HashSet};
use std::convert::Infallible;
use std::sync::{Arc, Mutex, PoisonError};
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;
fn rows<T: Keyed + 'static>(ctx: &impl ExtractVarArgs, index: usize) -> &ReplicatedMap<T> {
ctx.vararg(index).ok().and_then(|rows| rows.downcast_ref()).expect("A scene band is given the rows it draws")
}
#[node_macro::node(category(""))]
fn draw_grid(ctx: impl Ctx + ExtractVarArgs) -> List<Vector> {
let render_config = render_config(&ctx);
let viewport_size = render_config.viewport.resolution.as_dvec2() / render_config.scale;
grid_dots(graph_ui(&ctx).config.view, viewport_size, render_config.scale)
}
fn grid_dots(view: DAffine2, viewport_size: DVec2, scale: f64) -> List<Vector> {
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
}
type Cache<Row, Texts = ()> = Arc<Mutex<RowCache<Row, Texts>>>;
#[derive(Debug)]
struct RowCache<Row: Keyed, Texts> {
drawn: BTreeMap<Row::Key, (Row, List<Vector>)>,
labels: Texts,
}
impl<Row: Keyed, Texts: Default> Default for RowCache<Row, Texts> {
fn default() -> Self {
Self {
drawn: BTreeMap::new(),
labels: Texts::default(),
}
}
}
fn draw_changed_rows<'a, Row: Keyed + Placed + PartialEq + 'a, Texts, Error>(
rows: impl IntoIterator<Item = &'a Row>,
cache: &mut RowCache<Row, Texts>,
draw: impl Fn(&Row, &mut Texts) -> Result<List<Vector>, Error>,
) -> Result<List<Vector>, Error> {
let mut kept = BTreeMap::new();
let mut graphic = List::new();
for row in rows {
let entry = match cache.drawn.remove(&row.key()).map(|(drawn, drawing)| (drawn.placed_at(row.place()), drawing)) {
Some(entry) if entry.0 == *row => entry,
_ => {
let at_origin = row.clone().placed_at(Default::default());
let drawing = draw(&at_origin, &mut cache.labels)?;
(at_origin, drawing)
}
};
let mut placed = entry.1.clone();
let offset = row.offset();
if offset != DVec2::ZERO {
placed.left_apply_transform(&DAffine2::from_translation(offset));
}
graphic.extend(placed);
kept.insert(row.key(), entry);
}
cache.drawn = kept;
Ok(graphic)
}
fn draw_rows<'a, Row: Keyed + Placed + PartialEq + 'a>(rows: impl IntoIterator<Item = &'a Row>, cache: &Cache<Row>, draw: impl Fn(&Row) -> List<Vector>) -> List<Vector> {
let Ok(graphic) = draw_changed_rows(rows, &mut cache.lock().unwrap_or_else(PoisonError::into_inner), |row, _| Ok::<_, Infallible>(draw(row)));
graphic
}
trait Placed: Clone {
fn place(&self) -> (IVec2, DVec2) {
Default::default()
}
fn placed_at(self, _place: (IVec2, DVec2)) -> Self {
self
}
fn offset(&self) -> DVec2 {
let (cell, glide) = self.place();
cell.as_dvec2() * GRID_SIZE + glide
}
}
impl Placed for Wire {}
impl Placed for Card {
fn place(&self) -> (IVec2, DVec2) {
(self.cell, self.glide)
}
fn placed_at(self, (cell, glide): (IVec2, DVec2)) -> Self {
Self { cell, glide, ..self }
}
}
impl Placed for Layer {
fn place(&self) -> (IVec2, DVec2) {
(self.cell, self.glide)
}
fn placed_at(self, (cell, glide): (IVec2, DVec2)) -> Self {
Self { cell, glide, ..self }
}
}
impl Placed for Dot {
fn place(&self) -> (IVec2, DVec2) {
(self.cell, self.glide)
}
fn placed_at(self, (cell, glide): (IVec2, DVec2)) -> Self {
Self { cell, glide, ..self }
}
}
impl Placed for ErrorBadge {
fn place(&self) -> (IVec2, DVec2) {
(self.cell, self.glide)
}
fn placed_at(self, (cell, glide): (IVec2, DVec2)) -> Self {
Self { cell, glide, ..self }
}
}
impl Placed for NetworkConnector {
fn place(&self) -> (IVec2, DVec2) {
(self.position, self.glide)
}
fn placed_at(self, (position, glide): (IVec2, DVec2)) -> Self {
Self { position, glide, ..self }
}
fn offset(&self) -> DVec2 {
self.position.as_dvec2() + self.glide
}
}
#[node_macro::node(category(""), memoize)]
fn draw_layers(ctx: impl Ctx + ExtractVarArgs, #[data] cache: Cache<Layer, Labels>) -> Result<List<Vector>, TextToVectorError> {
let layers = rows::<Layer>(&ctx, 0);
let mut cache = cache.lock().unwrap_or_else(PoisonError::into_inner);
let graphic = draw_changed_rows(layers, &mut cache, draw_layer)?;
let shown: HashSet<&str> = layers.iter().map(|layer| layer.name.as_str()).collect();
cache.labels.retain(|text| shown.contains(text));
Ok(graphic)
}
fn draw_layer(layer: &Layer, labels: &mut Labels) -> Result<List<Vector>, TextToVectorError> {
let mut graphic = List::new();
let [min, max] = layer.body();
let fill = match (layer.selection, layer.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.renaming {
let [name, _] = layer.name_box();
let text_color = if layer.visible { TEXT } else { HIDDEN_TEXT };
graphic.extend(text(&labels.label(&layer.name, layer.name_width())?.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.primary_output {
graphic.extend(connector(&STACK_OUTPUT_OUTLINE, layer.stack_output(), output));
if output.connected && layer.primary_output_connected_to_layer {
graphic.push(outlined(&STACK_OUTPUT_WIRE_END, layer.stack_output(), data_type_colors(output.data_type)[1]));
}
}
match &layer.primary_input {
Some(input) => {
graphic.extend(connector(&STACK_INPUT_OUTLINE, layer.stack_input(), input));
if input.connected && layer.primary_input_connected_to_layer {
graphic.push(outlined(&STACK_INPUT_WIRE_END, layer.stack_input(), data_type_colors(input.data_type)[1]));
}
}
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.previewed));
let border_color = if layer.previewed { PREVIEWED_BORDER } else { BORDER };
graphic.push(painted(border, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), border_color.into()));
Ok(graphic)
}
#[node_macro::node(category(""))]
fn draw_thumbnails(ctx: impl Ctx + ExtractVarArgs) -> List<Vector> {
let graph_ui = graph_ui(&ctx);
let thumbnails = graph_ui.thumbnails.iter().filter_map(|(key, thumbnail)| Some((graph_ui.scene.layers().get(key)?, thumbnail)));
thumbnails
.map(|(layer, thumbnail)| {
let [min, max] = layer.thumbnail_image();
let mut image = rounded_rect(DVec2::ZERO, DVec2::ONE, [0.; 4]);
image.left_apply_transform(&DAffine2::from_scale_angle_translation(max - min, 0., min));
stamp_coverage(&mut image, Coverage::new_fill(), thumbnail.clone(), CoverPlacement::Above);
image
})
.collect()
}
#[node_macro::node(category(""), memoize)]
fn draw_raised(ctx: impl Ctx + ExtractVarArgs, #[data] layers: Cache<Layer>, #[data] cards: Cache<Card>) -> List<Vector> {
let mut graphic = draw_rows(rows::<Layer>(&ctx, 0), layers, draw_raised_parts_of_layer);
graphic.extend(draw_rows(rows::<Card>(&ctx, 1), cards, draw_connectors_of_card));
graphic
}
fn draw_raised_parts_of_layer(layer: &Layer) -> List<Vector> {
let mut graphic = List::new();
if let Some(input) = &layer.secondary_input {
graphic.extend(connector(&CONNECTOR_OUTLINE, layer.secondary_input_connector(), input));
}
let hovered = |button| layer.hovered_button == Some(button);
let grip_color = match (hovered(LayerButton::Grip), layer.selection != Selection::None) {
(true, _) => Some(Color::WHITE),
(false, true) => Some(TEXT.into()),
(false, false) => None,
};
if let Some(grip_color) = grip_color {
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));
}
graphic.push(painted(Vector::item_from_bezpath(&dots), Coverage::new_fill(), grip_color));
}
let mut button = |[min, max]: [DVec2; 2], which: LayerButton, [resting, hover]: [&str; 2]| {
let hovered = hovered(which) && !layer.read_only;
if hovered {
graphic.push(painted(rounded_rect(min, max, [LAYER_BUTTON_RADIUS; 4]), Coverage::new_fill(), HOVERED_BUTTON.into()));
}
let name = if hovered && !layer.hovered_button_clicked { hover } else { resting };
graphic.extend(icon(name, min + (LAYER_BUTTON_SIZE - ICON_SIZE) / 2., if layer.read_only { DISABLED_ICON } else { TEXT }));
};
if let Some(lock) = layer.lock() {
button(lock, LayerButton::Lock, ["PadlockLocked", "PadlockUnlocked"]);
}
let eye = if layer.visible { ["EyeVisible", "EyeHide"] } else { ["EyeHidden", "EyeShow"] };
button(layer.visibility(), LayerButton::Visibility, eye);
graphic
}
fn draw_connectors_of_card(card: &Card) -> List<Vector> {
card.inputs()
.chain(card.outputs())
.flat_map(|(top_left, input_or_output)| connector(&CONNECTOR_OUTLINE, top_left, input_or_output))
.collect()
}
#[node_macro::node(category(""), memoize)]
fn draw_thick_wires(ctx: impl Ctx + ExtractVarArgs, #[data] cache: Cache<Wire>) -> List<Vector> {
draw_rows(rows::<Wire>(&ctx, 0).iter().filter(|wire| wire.thick), cache, draw_wire)
}
#[node_macro::node(category(""), memoize)]
fn draw_wires(ctx: impl Ctx + ExtractVarArgs, #[data] cache: Cache<Wire>) -> List<Vector> {
draw_rows(rows::<Wire>(&ctx, 0).iter().filter(|wire| !wire.thick), cache, draw_wire)
}
fn draw_wire(wire: &Wire) -> List<Vector> {
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(&wire.path);
if wire.thick {
List::from_iter([stroke(&path, THICK_WIRE_WIDTH, color), stroke(&drawn(&wire.center_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))
}
}
#[node_macro::node(category(""))]
fn draw_wire_in_progress(ctx: impl Ctx + ExtractVarArgs) -> List<Vector> {
let Some(wire) = graph_ui(&ctx).config.wire_in_progress else { return List::new() };
let [_, dim] = data_type_colors(wire.data_type);
let path = flattened(&BezPath::from_vec(wire.path.to_vec()));
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(category(""), memoize)]
fn draw_cards(ctx: impl Ctx + ExtractVarArgs, #[data] cache: Cache<Card, Labels>) -> Result<List<Vector>, TextToVectorError> {
let cards = rows::<Card>(&ctx, 0);
let mut cache = cache.lock().unwrap_or_else(PoisonError::into_inner);
let graphic = draw_changed_rows(cards, &mut cache, draw_card)?;
let shown: HashSet<&str> = cards.iter().flat_map(texts).collect();
cache.labels.retain(|text| shown.contains(text));
Ok(graphic)
}
fn draw_card(card: &Card, labels: &mut Labels) -> Result<List<Vector>, TextToVectorError> {
let mut graphic = List::new();
let [min, max] = card.body();
let (card_color, text_color) = if card.visible { (Color::BLACK, TEXT) } else { (HIDDEN_CARD.into(), HIDDEN_TEXT) };
let body = rounded_rect(min, max, [NODE_RADIUS; 4]);
graphic.push(painted(body, Coverage::new_fill(), card_color.with_alpha(CARD_OPACITY)));
let (header_tint, rows_tint) = match card.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 { NODE_RADIUS } else { 0. };
let header = rounded_rect(min, DVec2::new(max.x, min.y + GRID_SIZE), [NODE_RADIUS, NODE_RADIUS, header_bottom, header_bottom]);
graphic.push(painted(header, Coverage::new_fill(), Color::WHITE.with_alpha(header_tint)));
if card.selection != Selection::None && card.rows() > 1 {
let rows = rounded_rect(DVec2::new(min.x, min.y + GRID_SIZE), max, [0., 0., NODE_RADIUS, NODE_RADIUS]);
graphic.push(painted(rows, Coverage::new_fill(), Color::WHITE.with_alpha(rows_tint)));
}
graphic.extend(icon(&card.icon, min + DVec2::new(NODE_ICON_LEFT, (GRID_SIZE - ICON_SIZE) / 2.), text_color));
let name = labels.label(&card.name, NODE_NAME_MAX_WIDTH)?;
graphic.extend(text(&name.outline, min + DVec2::new(NODE_NAME_LEFT, 0.), text_color));
for row in 1..card.rows() {
let (input, output) = (card.secondary_inputs.get(row - 1), card.secondary_outputs.get(row - 1));
let Some(connector) = input.or(output) else { continue };
let name = labels.label(&connector.name, NODE_WIDTH - 2. * NODE_ROW_PADDING)?;
let left = if input.is_some() { NODE_ROW_PADDING } else { NODE_WIDTH - NODE_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.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, NODE_RADIUS, &gaps, card.previewed));
graphic.push(painted(border, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), border_color.into()));
Ok(graphic)
}
fn texts(card: &Card) -> impl Iterator<Item = &str> {
let connectors = card.secondary_inputs.iter().chain(&card.secondary_outputs);
std::iter::once(card.name.as_str()).chain(connectors.map(|connector| connector.name.as_str()))
}
#[node_macro::node(category(""), memoize)]
fn draw_dots(ctx: impl Ctx + ExtractVarArgs, #[data] cache: Cache<Dot>) -> List<Vector> {
draw_rows(rows::<Dot>(&ctx, 0), cache, draw_dot)
}
fn draw_dot(dot: &Dot) -> List<Vector> {
let [wired, unwired] = data_type_colors(dot.data_type);
let center = dot.center();
let grown = matches!(dot.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 = dot.output_highlight != Highlight::None;
let fill = if dot.wired && !output_shown { wired } else { unwired };
let mut graphic = List::new_from_item(painted(circle(DOT_RADIUS), Coverage::new_fill(), fill.into()));
if grown {
let offset = if dot.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 dot.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 dot.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.data_type, true, dot.output_highlight));
}
graphic
}
#[node_macro::node(category(""), memoize)]
fn draw_errors(ctx: impl Ctx + ExtractVarArgs, #[data] cache: Cache<ErrorBadge, Paragraphs>) -> Result<List<Vector>, TextToVectorError> {
let badges = rows::<ErrorBadge>(&ctx, 0);
let errors = badges.iter();
let mut cache = cache.lock().unwrap_or_else(PoisonError::into_inner);
let graphic = draw_changed_rows(errors.clone().filter(|error| !error.hovered).chain(errors.filter(|error| error.hovered)), &mut cache, draw_error)?;
let shown: HashSet<&str> = badges.iter().map(|error| error.text.as_str()).collect();
cache.labels.retain(|text| shown.contains(text));
Ok(graphic)
}
fn draw_error(error: &ErrorBadge, paragraphs: &mut Paragraphs) -> Result<List<Vector>, TextToVectorError> {
let paragraph = paragraphs.paragraph(&error.text, ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH)?;
let [min, max] = error.body(paragraph.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.tail();
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()));
badge.extend(text(&paragraph.outline, error.text_top_left(paragraph.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 !error.hovered {
grouped.set_attribute(ATTR_OPACITY, ERROR_OPACITY);
}
Ok(List::new_from_item(grouped))
}
#[node_macro::node(category(""), memoize)]
fn draw_network_connectors(ctx: impl Ctx + ExtractVarArgs, #[data] cache: Cache<NetworkConnector, Labels>) -> Result<List<Vector>, TextToVectorError> {
let network_connectors = rows::<NetworkConnector>(&ctx, 0);
let mut cache = cache.lock().unwrap_or_else(PoisonError::into_inner);
let graphic = draw_changed_rows(network_connectors, &mut cache, draw_network_connector)?;
let connectors = network_connectors.iter().filter_map(|row| row.connector.as_ref());
let shown: HashSet<&str> = connectors.map(|connector| connector.name.as_str()).collect();
cache.labels.retain(|text| shown.contains(text));
Ok(graphic)
}
fn draw_network_connector(row: &NetworkConnector, labels: &mut Labels) -> Result<List<Vector>, TextToVectorError> {
let Some(entry) = &row.connector else {
return Ok(drawn_connector(&CONNECTOR_OUTLINE, row.connector_top_left(), DataType::General, false, row.add_highlight));
};
let mut graphic = connector(&CONNECTOR_OUTLINE, row.connector_top_left(), entry);
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.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)
}
#[node_macro::node(category(""))]
fn draw_reorder_bar(ctx: impl Ctx + ExtractVarArgs) -> List<Vector> {
let Some((kind, anchor)) = graph_ui(&ctx).config.reorder_bar else { return List::new() };
let [min, max] = reorder_bar(kind, anchor);
List::new_from_item(painted(rounded_rect(min, max, [0.; 4]), Coverage::new_fill(), Color::WHITE))
}
#[node_macro::node(category(""))]
fn draw_box_selection(ctx: impl Ctx + ExtractVarArgs) -> List<Vector> {
let Some([start, end]) = graph_ui(&ctx).config.box_selection 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());
List::from_iter([fill, border])
}
#[cfg(test)]
mod tests {
use super::*;
use crate::network_connector::NetworkConnectorKind;
use crate::render::rows_context;
use crate::scene::GraphUiScene;
use crate::test_utils::{badge, card, connector, dot, layer, network_connector, wire};
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::uuid::NodeId;
use vello_gpu::kurbo::PathEl;
fn bounds(graphic: &List<Vector>) -> RenderBoundingBox {
graphic.bounding_box(DAffine2::IDENTITY, false)
}
#[test]
fn a_card_that_only_moved_to_another_cell_keeps_its_vectors_and_is_drawn_at_that_cell() {
let cache = Default::default();
let draw = |scene: GraphUiScene| draw_cards(rows_context(scene.cards()), &cache).unwrap();
let mut edit = GraphUiScene::default().edit();
edit.cards.put(Card {
name: "Path".to_string(),
cell: IVec2::new(2, 1),
..card(0)
});
let (scene, _) = edit.finish();
draw(scene.clone());
let drawn = cache.lock().unwrap().drawn[&NodeId(0)].1.elements_witness();
let mut edit = scene.edit();
edit.cards.update(&NodeId(0), |card| card.cell = IVec2::new(-3, 5));
let (scene, _) = edit.finish();
let moved = draw(scene.clone());
assert!(drawn.matches(&cache.lock().unwrap().drawn[&NodeId(0)].1), "a moved card keeps its vectors");
let in_place = draw_card(scene.cards().get(&NodeId(0)).unwrap(), &mut Labels::default()).unwrap();
assert_eq!(bounds(&moved), bounds(&in_place), "a moved card is drawn at its new cell");
}
#[test]
fn a_gliding_layer_keeps_its_vectors_and_is_drawn_its_glide_away() {
let cache = Default::default();
let draw = |scene: GraphUiScene| draw_layers(rows_context(scene.layers()), &cache).unwrap();
let mut edit = GraphUiScene::default().edit();
edit.layers.put(Layer {
name: "Path".to_string(),
cell: IVec2::new(2, 1),
..layer(0)
});
let (scene, _) = edit.finish();
draw(scene.clone());
let drawn = cache.lock().unwrap().drawn[&NodeId(0)].1.elements_witness();
let mut edit = scene.edit();
edit.layers.update(&NodeId(0), |layer| layer.glide = DVec2::new(-7.25, 3.5));
let (scene, _) = edit.finish();
let gliding = draw(scene.clone());
assert!(drawn.matches(&cache.lock().unwrap().drawn[&NodeId(0)].1), "a gliding layer keeps its vectors");
let in_place = draw_layer(scene.layers().get(&NodeId(0)).unwrap(), &mut Labels::default()).unwrap();
assert_eq!(bounds(&gliding), bounds(&in_place), "a gliding layer is drawn its glide away");
}
#[test]
fn a_dot_whose_look_changed_is_drawn_again_while_a_dot_that_only_moved_keeps_its_vectors() {
let cache = Default::default();
let draw = |scene: GraphUiScene| draw_dots(rows_context(scene.dots()), &cache);
let mut edit = GraphUiScene::default().edit();
edit.dots.replace_all([dot(0), dot(1)]);
let (scene, _) = edit.finish();
draw(scene.clone());
let witness = |key| cache.lock().unwrap().drawn[&NodeId(key)].1.elements_witness();
let [moved, changed] = [witness(0), witness(1)];
let mut edit = scene.edit();
edit.dots.update(&NodeId(0), |dot| dot.cell = IVec2::new(4, -2));
edit.dots.update(&NodeId(1), |dot| {
dot.cell = IVec2::new(4, 2);
dot.selected = true;
});
let (scene, _) = edit.finish();
let drawn = draw(scene.clone());
let cache = cache.lock().unwrap();
assert!(moved.matches(&cache.drawn[&NodeId(0)].1), "a dot that only moved keeps its vectors");
assert!(!changed.matches(&cache.drawn[&NodeId(1)].1), "a dot whose look changed is drawn again");
let in_place: List<Vector> = scene.dots().iter().flat_map(draw_dot).collect();
assert_eq!(bounds(&drawn), bounds(&in_place), "both dots are drawn at their new cells");
}
#[test]
fn only_the_cards_that_changed_are_drawn_again() {
let cache = Default::default();
let draw = |scene: GraphUiScene| draw_cards(rows_context(scene.cards()), &cache).unwrap();
let mut edit = GraphUiScene::default().edit();
edit.cards.replace_all([card(0), card(1), card(2)]);
let (scene, _) = edit.finish();
draw(scene.clone());
let witness = |key| cache.lock().unwrap().drawn[&NodeId(key)].1.elements_witness();
let [unchanged, changed] = [witness(0), witness(1)];
let mut edit = scene.edit();
edit.cards.update(&NodeId(1), |card| card.selection = Selection::Active);
edit.cards.remove(&NodeId(2));
draw(edit.finish().0);
let cache = cache.lock().unwrap();
assert!(unchanged.matches(&cache.drawn[&NodeId(0)].1), "an unchanged card keeps its vectors");
assert!(!changed.matches(&cache.drawn[&NodeId(1)].1), "a changed card is drawn again");
assert!(!cache.drawn.contains_key(&NodeId(2)), "a removed card is forgotten");
}
#[test]
fn the_label_of_a_text_is_forgotten_once_no_card_shows_it() {
let named = |key, name: &str| Card { name: name.to_string(), ..card(key) };
let cache = Default::default();
let draw = |cards: Vec<Card>| {
let mut edit = GraphUiScene::default().edit();
edit.cards.replace_all(cards);
draw_cards(rows_context(edit.finish().0.cards()), &cache).unwrap();
};
draw(vec![named(0, "Path"), named(1, "Fill")]);
let label = |text| cache.lock().unwrap().labels.label(text, NODE_NAME_MAX_WIDTH).unwrap().outline.elements_witness();
let [path, fill] = [label("Path"), label("Fill")];
draw(vec![named(0, "Path")]);
let mut cache = cache.lock().unwrap();
assert!(
path.matches(&cache.labels.label("Path", NODE_NAME_MAX_WIDTH).unwrap().outline),
"the label of a text still shown is kept"
);
assert!(
!fill.matches(&cache.labels.label("Fill", NODE_NAME_MAX_WIDTH).unwrap().outline),
"the label of a text no card shows is laid out again"
);
}
#[test]
fn the_label_of_a_text_is_forgotten_once_no_layer_shows_it() {
let named = |key, name: &str| Layer { name: name.to_string(), ..layer(key) };
let cache = Default::default();
let draw = |layers: Vec<Layer>| {
let mut edit = GraphUiScene::default().edit();
edit.layers.replace_all(layers);
draw_layers(rows_context(edit.finish().0.layers()), &cache).unwrap();
};
draw(vec![named(0, "Path"), named(1, "Fill")]);
let max_width = layer(0).name_width();
let label = |text| cache.lock().unwrap().labels.label(text, max_width).unwrap().outline.elements_witness();
let [path, fill] = [label("Path"), label("Fill")];
draw(vec![named(0, "Path")]);
let mut cache = cache.lock().unwrap();
assert!(path.matches(&cache.labels.label("Path", max_width).unwrap().outline), "the label of a text still shown is kept");
assert!(
!fill.matches(&cache.labels.label("Fill", max_width).unwrap().outline),
"the label of a text no layer shows is laid out again"
);
}
#[test]
fn the_label_of_a_text_is_forgotten_once_no_import_or_export_shows_it() {
let named = |kind, name: &str| NetworkConnector {
connector: Some(connector(name)),
..network_connector(kind, 0)
};
let cache = Default::default();
let draw = |rows: Vec<NetworkConnector>| {
let mut edit = GraphUiScene::default().edit();
edit.network_connectors.replace_all(rows);
draw_network_connectors(rows_context(edit.finish().0.network_connectors()), &cache).unwrap();
};
draw(vec![named(NetworkConnectorKind::Import, "Path"), named(NetworkConnectorKind::Export, "Fill")]);
let label = |text| cache.lock().unwrap().labels.label(text, f64::INFINITY).unwrap().outline.elements_witness();
let [path, fill] = [label("Path"), label("Fill")];
draw(vec![named(NetworkConnectorKind::Import, "Path")]);
let mut cache = cache.lock().unwrap();
assert!(path.matches(&cache.labels.label("Path", f64::INFINITY).unwrap().outline), "the label of a text still shown is kept");
assert!(
!fill.matches(&cache.labels.label("Fill", f64::INFINITY).unwrap().outline),
"the label of a text no import or export shows is laid out again"
);
}
#[test]
fn the_paragraph_of_an_error_is_forgotten_once_no_badge_shows_it() {
let cache = Default::default();
let draw = |badges: Vec<ErrorBadge>| {
let mut edit = GraphUiScene::default().edit();
edit.errors.replace_all(badges);
draw_errors(rows_context(edit.finish().0.errors()), &cache).unwrap();
};
draw(vec![badge(0, "Failed"), badge(1, "Missing input")]);
let paragraph = |text| cache.lock().unwrap().labels.paragraph(text, ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH).unwrap().outline.elements_witness();
let [failed, missing] = [paragraph("Failed"), paragraph("Missing input")];
draw(vec![badge(0, "Failed")]);
let mut cache = cache.lock().unwrap();
assert!(
failed.matches(&cache.labels.paragraph("Failed", ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH).unwrap().outline),
"the paragraph of a text still shown is kept"
);
assert!(
!missing.matches(&cache.labels.paragraph("Missing input", ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH).unwrap().outline),
"the paragraph of a text no badge shows is laid out again"
);
}
#[test]
fn the_column_groups_of_a_grid_dot_light_each_pixel_of_its_disc_once() {
for (radius, groups, pixels) in [(1, 1, 4), (2, 2, 12), (3, 2, 32), (4, 3, 52)] {
let disc: Vec<[u32; 2]> = (0..2 * radius)
.flat_map(|row| (0..2 * radius).map(move |column| [column, row]))
.filter(|&[column, row]| (column as f64 + 0.5 - radius as f64).hypot(row as f64 + 0.5 - radius as f64) < radius as f64)
.collect();
let columns = disc_columns(radius);
let mut lit: Vec<[u32; 2]> = columns
.iter()
.flat_map(|(&[top, bottom], runs)| (top..bottom).flat_map(move |row| runs.iter().flat_map(move |&[left, right]| (left..right).map(move |column| [column, row]))))
.collect();
lit.sort_by_key(|&[column, row]| [row, column]);
assert_eq!((columns.len(), disc.len()), (groups, pixels), "the groups and pixels of the disc at radius {radius}");
assert_eq!(lit, disc, "every pixel of the disc at radius {radius} is lit by exactly one group");
}
}
#[test]
fn only_the_wires_that_changed_are_drawn_again() {
let key = |node| WireKey::Input { node: NodeId(node), index: 0 };
let at = |node, y: f64| Wire {
path: BezPath::from_vec(vec![PathEl::MoveTo((0., y).into()), PathEl::LineTo((48., y).into())]),
..wire(key(node))
};
let cache = Default::default();
let draw = |scene: GraphUiScene| draw_wires(rows_context(scene.wires()), &cache);
let mut edit = GraphUiScene::default().edit();
edit.wires.replace_all([at(0, 0.), at(1, 24.)]);
let (scene, _) = edit.finish();
draw(scene.clone());
let witness = |node| cache.lock().unwrap().drawn[&key(node)].1.elements_witness();
let [unchanged, changed] = [witness(0), witness(1)];
let mut edit = scene.edit();
edit.wires.put(at(1, 48.));
draw(edit.finish().0);
let cache = cache.lock().unwrap();
assert!(unchanged.matches(&cache.drawn[&key(0)].1), "the other wire keeps its vectors");
assert!(!changed.matches(&cache.drawn[&key(1)].1), "the changed wire is drawn again");
}
}
+129
View File
@@ -0,0 +1,129 @@
use crate::look::{BACKDROP, painted, rounded_rect};
use crate::replicated_map::{Keyed, ReplicatedMap};
use crate::{GraphUi, nodes};
use core_types::list::{Item, List};
use core_types::{CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, ExtractVarArgs, Interrupt, NodeError, OwnedContextImpl, ProtoNodeIdentifier};
use glam::{DAffine2, DVec2};
use graph_craft::document::value::{RenderOutput, RenderOutputType};
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
use graphene_application_io::RenderConfig;
use graphic_types::{Coverage, Vector};
use rendering::vello_scene_builder::VelloSceneBuilder;
use rendering::{Render, RenderParams};
use std::error::Error;
use wgpu_executor::WgpuExecutor;
const BANDS: [ProtoNodeIdentifier; 13] = [
nodes::draw_grid::IDENTIFIER,
nodes::draw_thick_wires::IDENTIFIER,
nodes::draw_layers::IDENTIFIER,
nodes::draw_thumbnails::IDENTIFIER,
nodes::draw_wires::IDENTIFIER,
nodes::draw_wire_in_progress::IDENTIFIER,
nodes::draw_cards::IDENTIFIER,
nodes::draw_dots::IDENTIFIER,
nodes::draw_raised::IDENTIFIER,
nodes::draw_errors::IDENTIFIER,
nodes::draw_network_connectors::IDENTIFIER,
nodes::draw_reorder_bar::IDENTIFIER,
nodes::draw_box_selection::IDENTIFIER,
];
pub fn network() -> NodeNetwork {
let node = |identifier, inputs| DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(identifier),
inputs,
..Default::default()
};
let mut network = NodeNetwork::default();
let root = NodeId(BANDS.len() as u64);
let mut inputs = Vec::new();
for (band, identifier) in (0..).map(NodeId).zip(BANDS) {
network.nodes.insert(band, node(identifier, Vec::new()));
inputs.push(NodeInput::node(band, 0));
}
inputs.push(NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER));
network.nodes.insert(root, node(render_graph_ui::IDENTIFIER, inputs));
network.exports.push(NodeInput::node(root, 0));
network
}
#[node_macro::node(category(""))]
fn render_graph_ui(
ctx: impl Ctx + ExtractVarArgs + ExtractAll + CloneVarArgs,
grid: impl Node<Context<'static>, Output = List<Vector>>,
thick_wires: impl Node<Context<'static>, Output = List<Vector>>,
layers: impl Node<Context<'static>, Output = List<Vector>>,
thumbnails: impl Node<Context<'static>, Output = List<Vector>>,
wires: impl Node<Context<'static>, Output = List<Vector>>,
wire_in_progress: impl Node<Context<'static>, Output = List<Vector>>,
cards: impl Node<Context<'static>, Output = List<Vector>>,
dots: impl Node<Context<'static>, Output = List<Vector>>,
raised: impl Node<Context<'static>, Output = List<Vector>>,
errors: impl Node<Context<'static>, Output = List<Vector>>,
imports_exports: impl Node<Context<'static>, Output = List<Vector>>,
reorder_bar: impl Node<Context<'static>, Output = List<Vector>>,
box_selection: impl Node<Context<'static>, Output = List<Vector>>,
#[scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER)] executor: impl Node<Context<'static>, Output = Item<WgpuExecutor>>,
) -> Result<Item<RenderOutput>, Interrupt> {
let render_config = *render_config(&ctx);
let context = OwnedContextImpl::from(ctx).into_context();
let graph_ui = graph_ui(&context);
let viewport_size = render_config.viewport.resolution.as_dvec2() / render_config.scale;
let opacity = graph_ui.config.fade_artwork as f32;
let backdrop = painted(rounded_rect(DVec2::ZERO, viewport_size, [0.; 4]), Coverage::new_fill(), Color::from(BACKDROP).with_alpha(opacity));
let mut drawn = vec![(List::new_from_item(backdrop), DAffine2::IDENTITY)];
let scene = &graph_ui.scene;
let wire_rows = rows_context(scene.wires());
let raised_rows = OwnedContextImpl::default()
.with_varargs([Box::new(scene.layers().clone()), Box::new(scene.cards().clone())])
.into_context();
let bands = [
(grid.eval(&context)?, DAffine2::IDENTITY),
(thick_wires.eval(&wire_rows)?, graph_ui.config.view),
(layers.eval(&rows_context(scene.layers()))?, graph_ui.config.view),
(thumbnails.eval(&context)?, graph_ui.config.view),
(wires.eval(&wire_rows)?, graph_ui.config.view),
(wire_in_progress.eval(&context)?, graph_ui.config.view),
(cards.eval(&rows_context(scene.cards()))?, graph_ui.config.view),
(dots.eval(&rows_context(scene.dots()))?, graph_ui.config.view),
(raised.eval(&raised_rows)?, graph_ui.config.view),
(errors.eval(&rows_context(scene.errors()))?, graph_ui.config.view),
(imports_exports.eval(&rows_context(scene.network_connectors()))?, graph_ui.config.view),
(reorder_bar.eval(&context)?, graph_ui.config.view),
(box_selection.eval(&context)?, DAffine2::IDENTITY),
];
drawn.extend(bands);
let executor = executor.eval(&Context::default())?.into_element();
let data = raster_frame(&executor, &drawn, &render_config).map_err(NodeError::new)?;
Ok(Item::new_from_element(RenderOutput { data, metadata: Default::default() }))
}
fn raster_frame(executor: &WgpuExecutor, drawn: &[(List<Vector>, DAffine2)], render_config: &RenderConfig) -> Result<RenderOutputType, Box<dyn Error + Send + Sync>> {
let viewport = DAffine2::from_scale(DVec2::splat(render_config.scale));
let mut draw = |scene: &mut VelloSceneBuilder| {
for (band, transform) in drawn {
band.render_to_vello(scene, viewport * *transform, &RenderParams::default());
}
};
let texture = executor.render_vello(render_config.viewport.resolution, DAffine2::IDENTITY, &mut draw)?;
Ok(RenderOutputType::Texture(texture))
}
pub fn context(render_config: RenderConfig, graph_ui: GraphUi) -> OwnedContextImpl {
OwnedContextImpl::default().with_varargs([Box::new(render_config), Box::new(graph_ui)])
}
pub fn rows_context<T: Keyed + CacheHash + Send + Sync + 'static>(rows: &ReplicatedMap<T>) -> Context<'static> {
OwnedContextImpl::default().with_vararg(Box::new(rows.clone())).into_context()
}
pub(crate) fn render_config(ctx: &impl ExtractVarArgs) -> &RenderConfig {
ctx.vararg(0).ok().and_then(|config| config.downcast_ref()).expect("The render config is the first vararg")
}
pub(crate) fn graph_ui(ctx: &impl ExtractVarArgs) -> &GraphUi {
ctx.vararg(1).ok().and_then(|graph_ui| graph_ui.downcast_ref()).expect("The graph UI is the second vararg")
}
+332
View File
@@ -0,0 +1,332 @@
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<T: Keyed> {
items: Arc<Vec<T>>,
hash: Arc<OnceLock<u64>>,
}
impl<T: Keyed> Default for ReplicatedMap<T> {
fn default() -> Self {
Self {
items: Arc::default(),
hash: Arc::default(),
}
}
}
impl<T: Keyed + PartialEq> PartialEq for ReplicatedMap<T> {
fn eq(&self, other: &Self) -> bool {
self.items == other.items
}
}
impl<T: Keyed + CacheHash> CacheHash for ReplicatedMap<T> {
fn cache_hash<H: Hasher>(&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<T: Keyed> ReplicatedMap<T> {
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<T> {
ReplicatedMapEdit { map: self, deltas: Vec::new() }
}
pub fn apply(&mut self, deltas: impl IntoIterator<Item = ReplicatedMapDelta<T>>) {
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<usize, usize> {
self.items.binary_search_by(|item| item.key().cmp(key))
}
fn items_mut(&mut self) -> &mut Vec<T> {
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<T> {
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<T: Keyed> {
Put(T),
Remove(T::Key),
}
#[derive(Debug)]
pub struct ReplicatedMapEdit<T: Keyed> {
map: ReplicatedMap<T>,
deltas: Vec<ReplicatedMapDelta<T>>,
}
impl<T: Keyed> Deref for ReplicatedMapEdit<T> {
type Target = ReplicatedMap<T>;
fn deref(&self) -> &Self::Target {
&self.map
}
}
impl<T: Keyed> ReplicatedMapEdit<T> {
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<Item = T>)
where
T: PartialEq,
{
let mut items: Vec<T> = 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<T>, Vec<ReplicatedMapDelta<T>>) {
(self.map, self.deltas)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
struct Item {
key: u8,
value: u8,
}
impl Keyed for Item {
type Key = u8;
fn key(&self) -> u8 {
self.key
}
}
fn item(key: u8, value: u8) -> Item {
Item { key, value }
}
fn map(items: &[Item]) -> ReplicatedMap<Item> {
let mut edit = ReplicatedMap::default().edit();
edit.replace_all(items.iter().copied());
edit.finish().0
}
fn small_maps() -> Vec<Vec<Item>> {
let choices = [None, Some(0), Some(1)];
let mut maps = Vec::new();
for a in choices {
for b in choices {
for c in choices {
maps.push([a, b, c].into_iter().zip(0..).filter_map(|(value, key)| Some(item(key, value?))).collect());
}
}
}
maps
}
fn hash(map: &ReplicatedMap<Item>) -> u64 {
let mut hasher = DefaultHasher::new();
map.cache_hash(&mut hasher);
hasher.finish()
}
#[test]
fn a_copy_that_applies_the_deltas_of_an_edit_holds_the_same_items() {
for old in small_maps() {
for new in small_maps() {
let mut copy = map(&old);
let mut edit = map(&old).edit();
edit.replace_all(new.iter().copied());
let (replaced, deltas) = edit.finish();
assert_eq!(replaced, map(&new));
assert_eq!(deltas.is_empty(), old == new, "{old:?} to {new:?}");
copy.apply(deltas);
assert_eq!(copy, replaced, "{old:?} to {new:?}");
let mut copy = map(&old);
let mut edit = map(&old).edit();
for item in &old {
assert!(edit.remove(&item.key));
}
for item in new.iter().rev() {
edit.put(*item);
}
let (rebuilt, deltas) = edit.finish();
assert_eq!(rebuilt, map(&new));
copy.apply(deltas);
assert_eq!(copy, rebuilt, "{old:?} to {new:?}");
}
}
}
#[test]
fn items_are_held_in_key_order_and_found_by_key() {
let mut edit = ReplicatedMap::default().edit();
edit.put(item(2, 0));
edit.put(item(0, 0));
edit.put(item(1, 0));
edit.put(item(0, 1));
assert_eq!(edit.get(&0), Some(&item(0, 1)), "an edit reads what it has done so far");
let (map, _) = edit.finish();
assert_eq!(map.iter().copied().collect::<Vec<_>>(), [item(0, 1), item(1, 0), item(2, 0)]);
assert_eq!(map.get(&1), Some(&item(1, 0)));
assert_eq!(map.get(&3), None);
assert_eq!(map.len(), 3);
}
#[test]
fn a_put_of_the_item_already_held_records_no_delta() {
let mut edit = map(&[item(0, 0)]).edit();
edit.put(item(0, 0));
assert!(edit.finish().1.is_empty());
}
#[test]
fn an_update_changes_the_item_in_the_copy_too() {
let mut copy = map(&[item(0, 0), item(1, 0)]);
let mut edit = copy.clone().edit();
assert!(edit.update(&1, |item| item.value = 1));
assert!(!edit.update(&2, |item| item.value = 1));
assert!(!edit.remove(&2));
let (updated, deltas) = edit.finish();
assert_eq!(updated, map(&[item(0, 0), item(1, 1)]));
copy.apply(deltas);
assert_eq!(copy, updated);
}
#[test]
fn an_edit_leaves_other_holders_of_the_set_as_they_were() {
let held = map(&[item(0, 0)]);
let mut edit = held.clone().edit();
edit.put(item(1, 0));
edit.remove(&0);
assert_eq!(held, map(&[item(0, 0)]));
}
#[test]
fn the_hash_follows_the_items() {
let a = map(&[item(0, 0), item(1, 0)]);
let held = a.clone();
assert!(a.hash.get().is_none(), "nothing asked for the hash yet");
assert_eq!(hash(&a), hash(&map(&[item(1, 0), item(0, 0)])));
assert!(a.hash.get().is_some());
assert!(held.hash.get().is_some(), "a clone made before shares the hash");
let mut edit = a.clone().edit();
edit.update(&1, |item| item.value = 1);
let (b, deltas) = edit.finish();
assert!(b.hash.get().is_none(), "a change empties the hash");
assert_ne!(hash(&a), hash(&b));
let mut copy = a.clone();
copy.apply(deltas);
assert!(copy.hash.get().is_none());
assert_eq!(hash(&copy), hash(&b));
let mut edit = b.edit();
edit.update(&1, |item| item.value = 0);
assert_eq!(hash(&edit.finish().0), hash(&a), "the same items again hash the same");
}
}
+161
View File
@@ -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::replicated_map::{ReplicatedMap, ReplicatedMapDelta, ReplicatedMapEdit};
use crate::wire::Wire;
use graphene_hash::CacheHash;
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
pub struct GraphUiScene {
cards: ReplicatedMap<Card>,
layers: ReplicatedMap<Layer>,
dots: ReplicatedMap<Dot>,
wires: ReplicatedMap<Wire>,
network_connectors: ReplicatedMap<NetworkConnector>,
errors: ReplicatedMap<ErrorBadge>,
}
impl GraphUiScene {
pub fn cards(&self) -> &ReplicatedMap<Card> {
&self.cards
}
pub fn layers(&self) -> &ReplicatedMap<Layer> {
&self.layers
}
pub fn dots(&self) -> &ReplicatedMap<Dot> {
&self.dots
}
pub fn wires(&self) -> &ReplicatedMap<Wire> {
&self.wires
}
pub fn network_connectors(&self) -> &ReplicatedMap<NetworkConnector> {
&self.network_connectors
}
pub fn errors(&self) -> &ReplicatedMap<ErrorBadge> {
&self.errors
}
pub fn edit(self) -> GraphUiSceneEdit {
GraphUiSceneEdit {
cards: self.cards.edit(),
layers: self.layers.edit(),
dots: self.dots.edit(),
wires: self.wires.edit(),
network_connectors: self.network_connectors.edit(),
errors: self.errors.edit(),
}
}
pub fn apply(&mut self, delta: GraphUiSceneDelta) {
self.cards.apply(delta.cards);
self.layers.apply(delta.layers);
self.dots.apply(delta.dots);
self.wires.apply(delta.wires);
self.network_connectors.apply(delta.network_connectors);
self.errors.apply(delta.errors);
}
}
pub struct GraphUiSceneEdit {
pub cards: ReplicatedMapEdit<Card>,
pub layers: ReplicatedMapEdit<Layer>,
pub dots: ReplicatedMapEdit<Dot>,
pub wires: ReplicatedMapEdit<Wire>,
pub network_connectors: ReplicatedMapEdit<NetworkConnector>,
pub errors: ReplicatedMapEdit<ErrorBadge>,
}
impl GraphUiSceneEdit {
pub fn finish(self) -> (GraphUiScene, GraphUiSceneDelta) {
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();
let (network_connectors, network_connector_deltas) = self.network_connectors.finish();
let (errors, error_deltas) = self.errors.finish();
(
GraphUiScene {
cards,
layers,
dots,
wires,
network_connectors,
errors,
},
GraphUiSceneDelta {
cards: card_deltas,
layers: layer_deltas,
dots: dot_deltas,
wires: wire_deltas,
network_connectors: network_connector_deltas,
errors: error_deltas,
},
)
}
}
#[derive(Debug)]
pub struct GraphUiSceneDelta {
cards: Vec<ReplicatedMapDelta<Card>>,
layers: Vec<ReplicatedMapDelta<Layer>>,
dots: Vec<ReplicatedMapDelta<Dot>>,
wires: Vec<ReplicatedMapDelta<Wire>>,
network_connectors: Vec<ReplicatedMapDelta<NetworkConnector>>,
errors: Vec<ReplicatedMapDelta<ErrorBadge>>,
}
impl GraphUiSceneDelta {
pub fn is_empty(&self) -> bool {
self.cards.is_empty() && self.layers.is_empty() && self.dots.is_empty() && self.wires.is_empty() && self.network_connectors.is_empty() && self.errors.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::network_connector::NetworkConnectorKind;
use crate::test_utils::{badge, card, connector, dot, layer, network_connector, wire};
use crate::wire::WireKey;
use core_types::uuid::NodeId;
use glam::IVec2;
#[test]
fn a_copy_that_applies_the_delta_of_an_edit_equals_the_edited_scene() {
let mut edit = GraphUiScene::default().edit();
edit.cards.replace_all([card(0), card(1)]);
let (scene, _) = edit.finish();
let mut copy = scene.clone();
let mut edit = scene.edit();
edit.cards.put(card(2));
edit.cards.update(&NodeId(0), |card| card.cell = IVec2::ONE);
edit.cards.remove(&NodeId(1));
edit.layers.put(layer(4));
edit.dots.put(dot(3));
edit.wires.put(wire(WireKey::Input { node: NodeId(2), index: 0 }));
edit.network_connectors.put(network_connector(NetworkConnectorKind::Import, 0));
edit.network_connectors.put(NetworkConnector {
connector: Some(connector("Canvas")),
..network_connector(NetworkConnectorKind::Export, 0)
});
edit.errors.put(badge(2, "An error"));
let (edited, delta) = edit.finish();
assert!(!delta.is_empty());
copy.apply(delta);
assert_eq!(copy, edited);
let mut edit = copy.edit();
edit.errors.remove(&NodeId(2));
assert!(!edit.finish().1.is_empty(), "a change to one map is a delta");
assert!(edited.edit().finish().1.is_empty(), "an edit that changes nothing has no deltas");
}
}
+110
View File
@@ -0,0 +1,110 @@
use crate::card::{Card, Connector, DataType, Highlight, Selection};
use crate::dot::Dot;
use crate::error_badge::ErrorBadge;
use crate::layer::Layer;
use crate::network_connector::{NetworkConnector, NetworkConnectorKind};
use crate::wire::{Wire, WireKey};
use core_types::uuid::NodeId;
use glam::{DVec2, IVec2};
use vello_gpu::kurbo::BezPath;
pub(crate) fn card(key: u64) -> Card {
Card {
key: NodeId(key),
cell: IVec2::ZERO,
name: String::new(),
icon: String::new(),
primary_input: None,
primary_output: None,
secondary_inputs: Vec::new(),
secondary_outputs: Vec::new(),
selection: Selection::None,
visible: true,
previewed: false,
glide: DVec2::ZERO,
}
}
pub(crate) fn layer(key: u64) -> Layer {
Layer {
key: NodeId(key),
cell: IVec2::ZERO,
name: String::new(),
renaming: false,
width: 8,
chain_width: 0,
has_left_input_wire: false,
primary_input: None,
primary_output: None,
secondary_input: None,
primary_input_connected_to_layer: false,
primary_output_connected_to_layer: false,
visible: true,
locked: false,
read_only: false,
selection: Selection::None,
previewed: false,
hovered_button: None,
hovered_button_clicked: false,
glide: DVec2::ZERO,
}
}
pub(crate) fn dot(key: u64) -> Dot {
Dot {
key: NodeId(key),
cell: IVec2::ZERO,
data_type: DataType::General,
wired: false,
selected: false,
previewed: false,
highlight: Highlight::None,
output_highlight: Highlight::None,
glide: DVec2::ZERO,
}
}
pub(crate) fn wire(key: WireKey) -> Wire {
Wire {
key,
path: BezPath::new(),
data_type: DataType::General,
thick: false,
center_line: BezPath::new(),
list: false,
insertion_target: false,
}
}
pub(crate) fn network_connector(kind: NetworkConnectorKind, index: usize) -> NetworkConnector {
NetworkConnector {
kind,
index,
position: IVec2::ZERO,
connector: None,
add_highlight: Highlight::None,
editable: false,
renaming: false,
glide: DVec2::ZERO,
}
}
pub(crate) fn badge(key: u64, text: &str) -> ErrorBadge {
ErrorBadge {
key: NodeId(key),
cell: IVec2::ZERO,
on_layer: false,
text: text.to_string(),
hovered: false,
glide: DVec2::ZERO,
}
}
pub(crate) fn connector(name: &str) -> Connector {
Connector {
name: name.to_string(),
data_type: DataType::General,
connected: false,
highlight: Highlight::None,
}
}
+172
View File
@@ -0,0 +1,172 @@
use crate::metrics::{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<Vector>,
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)?, width(&text));
Ok(label.insert(Label { outline, width }))
}
}
}
pub fn retain(&mut self, mut shown: impl FnMut(&str) -> bool) {
self.0.retain(|(text, _), _| shown(text));
}
}
#[derive(Debug)]
pub struct Paragraph {
pub outline: List<Vector>,
pub size: DVec2,
}
#[derive(Debug, Default)]
pub struct Paragraphs(HashMap<(String, u64, u64), Paragraph>);
impl Paragraphs {
pub fn paragraph(&mut self, text: &str, line_height: f64, max_width: f64) -> Result<&Paragraph, TextToVectorError> {
match self.0.entry((text.to_string(), line_height.to_bits(), max_width.to_bits())) {
Entry::Occupied(paragraph) => Ok(paragraph.into_mut()),
Entry::Vacant(paragraph) => {
let (outline, size) = (paragraph_outline(text, line_height, max_width)?, paragraph_size(text, line_height, max_width));
Ok(paragraph.insert(Paragraph { outline, size }))
}
}
}
pub fn retain(&mut self, mut shown: impl FnMut(&str) -> bool) {
self.0.retain(|(text, ..), _| shown(text));
}
}
fn width(text: &str) -> f64 {
text_nodes::bounding_box(text, &FALLBACK_FONT_RESOURCE, typesetting(), false).x
}
fn ellipsized(text: &str, max_width: f64) -> String {
if width(text) <= max_width {
return text.to_string();
}
let cut = |end: usize| format!("{}…", &text[..end]);
let ends: Vec<usize> = text.char_indices().map(|(end, _)| end).collect();
let fitting = ends.partition_point(|&end| width(&cut(end)) <= max_width);
cut(ends[fitting.saturating_sub(1)])
}
fn outline(text: &str) -> Result<List<Vector>, TextToVectorError> {
text_nodes::to_path(text, &FALLBACK_FONT_RESOURCE, typesetting(), false).map(with_geometry_caches)
}
fn with_geometry_caches(mut outline: List<Vector>) -> List<Vector> {
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)
}
fn paragraph_outline(text: &str, line_height: f64, max_width: f64) -> Result<List<Vector>, 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<f64>) -> TypesettingConfig {
TypesettingConfig {
font_size: TEXT_SIZE,
line_height_ratio: line_height / TEXT_SIZE,
max_width,
..Default::default()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::look::{TEXT, text};
use core_types::list::ATTR_PATHS;
use std::sync::Arc;
#[test]
fn text_too_wide_is_cut_where_one_more_character_would_not_fit() {
let name = "A Node With a Very Long Name";
assert_eq!(ellipsized(name, 1000.), name);
let cut = ellipsized(name, 84.);
let kept = cut.trim_end_matches('…');
assert!(kept.len() < name.len() && width(&cut) <= 84., "{cut}");
assert!(width(&format!("{}…", &name[..kept.len() + 1])) > 84., "{cut}");
assert_eq!(ellipsized(name, 0.), "…");
}
#[test]
fn a_paragraph_keeps_its_line_breaks_and_wraps_where_it_would_get_too_wide() {
let line = "These input types are incompatible:";
let one_line = paragraph_size(line, 18., 600.);
assert_eq!(one_line, DVec2::new(width(line), 18.), "as wide as its text, a line high");
assert_eq!(
paragraph_size(&format!("{line}\n\nNext"), 18., 600.),
DVec2::new(width(line), 54.),
"an empty line between the paragraphs"
);
let long = [line; 20].join(" ");
let wrapped = paragraph_size(&long, 18., 600.);
assert_eq!(wrapped.x, 600., "as wide as it may be once it wraps");
assert!(wrapped.y >= 18. * (width(&long) / 600.).ceil(), "{wrapped}");
}
#[test]
fn a_label_is_laid_out_once_until_its_text_is_no_longer_shown() {
let mut labels = Labels::default();
let path = labels.label("Path", 84.).unwrap().outline.elements_witness();
labels.label("Fill", 84.).unwrap();
assert!(path.matches(&labels.label("Path", 84.).unwrap().outline), "the second label of a text is the first");
assert!(!path.matches(&labels.label("Path", 104.).unwrap().outline), "a label of another width is its own");
labels.retain(|text| text == "Fill");
assert!(!path.matches(&labels.label("Path", 84.).unwrap().outline), "a forgotten label is laid out again");
}
#[test]
fn the_contours_of_a_label_are_extracted_once_for_every_place_it_is_drawn() {
let outline = Labels::default().label("Path", 84.).unwrap().outline.clone();
let contours = |top_left| {
let drawn = text(&outline, top_left, TEXT);
let cache = drawn.attribute::<GeometryCache>(ATTR_GEOMETRY_CACHE, 0).cloned().unwrap_or_default();
cache.contours(drawn.element(0).unwrap(), drawn.attribute(ATTR_PATHS, 0).unwrap())
};
assert!(Arc::ptr_eq(&contours(DVec2::ZERO), &contours(DVec2::ONE)));
}
}
+37
View File
@@ -0,0 +1,37 @@
use crate::card::DataType;
use crate::replicated_map::Keyed;
use core_types::uuid::NodeId;
use graphene_hash::CacheHash;
use vello_gpu::kurbo::{BezPath, PathEl};
#[derive(Clone, Debug, PartialEq, CacheHash)]
pub struct Wire {
pub key: WireKey,
pub path: BezPath,
pub data_type: DataType,
pub thick: bool,
pub center_line: BezPath,
pub list: bool,
pub insertion_target: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)]
pub enum WireKey {
Input { node: NodeId, index: usize },
Export(usize),
Preview,
}
impl Keyed for Wire {
type Key = WireKey;
fn key(&self) -> WireKey {
self.key
}
}
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
pub struct WireInProgress {
pub path: [PathEl; 4],
pub data_type: DataType,
}
+182
View File
@@ -0,0 +1,182 @@
mod render;
mod timing;
use core_types::color::SRGBA8;
use core_types::list::Item;
use core_types::uuid::NodeId;
use core_types::{Context, ProtoNodeIdentifier};
use glam::{DAffine2, DVec2, IVec2, UVec2};
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
use graph_craft::item;
use graph_craft::proto::ProtoNetwork;
use graph_ui::card::{Card, Connector, DataType, Highlight, Selection};
use graph_ui::error_badge::ErrorBadge;
use graph_ui::layer::Layer;
use graph_ui::network_connector::{NetworkConnector, NetworkConnectorKind};
use graph_ui::wire::{Wire, WireKey};
use graph_ui::{GraphUi, GraphUiConfig};
use graphene_std::application_io::RenderConfig;
use graphic_types::Graphic;
use graphic_types::raster_types::Raster;
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
use rendering::to_peniko::ToPenikoColor;
use rendering::vello_scene_builder::VelloSceneBuilder;
use std::sync::Arc;
use vello_gpu::kurbo::{Affine, BezPath, Rect};
use vello_gpu::peniko::Fill;
use wgpu_executor::WgpuExecutor;
const ARTWORK: SRGBA8 = SRGBA8::new_opaque(0x30, 0x60, 0x90);
fn gpu() -> WgpuExecutor {
futures::executor::block_on(WgpuExecutor::new()).expect("rendering needs a GPU adapter, such as lavapipe through `VK_ADD_DRIVER_FILES`")
}
fn node(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> DocumentNode {
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(identifier),
inputs,
..Default::default()
}
}
fn nested(network: NodeNetwork) -> DocumentNode {
DocumentNode {
implementation: DocumentNodeImplementation::Network(network),
..Default::default()
}
}
fn network(gpu: &WgpuExecutor, nodes: impl IntoIterator<Item = DocumentNode>) -> NodeNetwork {
let editor_api = Arc::new(PlatformEditorApi {
application_io: Some(Arc::new(PlatformApplicationIo::new_with_executor(gpu.clone()))),
});
let editor_api = node(graphene_std::ops::passthrough::IDENTIFIER, vec![NodeInput::value(TaggedValue::EditorApi(editor_api), false)]);
let nodes: Vec<DocumentNode> = [editor_api].into_iter().chain(nodes).collect();
NodeNetwork {
exports: vec![NodeInput::node(NodeId(nodes.len() as u64 - 1), 0)],
nodes: nodes.into_iter().enumerate().map(|(id, node)| (NodeId(id as u64), node)).collect(),
scope_injections: [("editor-api".to_string(), (NodeId(0), item!(Arc<PlatformEditorApi>)))].into_iter().collect(),
..Default::default()
}
}
fn compiled(mut network: NodeNetwork) -> ProtoNetwork {
preprocessor::Preprocessor::new().preprocess(&mut network, &|_| None).unwrap();
graph_craft::util::compile(network)
}
fn executor(network: NodeNetwork) -> (DynamicExecutor, OutputHandle) {
let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(compiled(network)).unwrap();
(executor, output)
}
fn config(view: DAffine2, fade_artwork: f64) -> GraphUiConfig {
GraphUiConfig {
view,
fade_artwork,
wire_in_progress: None,
reorder_bar: None,
box_selection: None,
}
}
fn context(render_config: RenderConfig, graph_ui: GraphUi) -> Context<'static> {
graph_ui::render::context(render_config, graph_ui).into_context()
}
fn thumbnail(gpu: &WgpuExecutor, painted: Rect, color: SRGBA8) -> Graphic {
let mut paint = |scene: &mut VelloSceneBuilder| scene.fill(Fill::NonZero, Affine::IDENTITY, color.to_peniko_color(), None, &painted);
let texture = gpu.render_vello(UVec2::new(72, 48), DAffine2::IDENTITY, &mut paint).unwrap();
Graphic::RasterGPU(Item::new_from_element(Raster::new_gpu(texture)))
}
fn card(key: u64, (x, y): (i32, i32), name: &str) -> Card {
Card {
key: NodeId(key),
cell: IVec2::new(x, y),
name: name.to_string(),
icon: "NodeCustomNode".to_string(),
primary_input: None,
primary_output: None,
secondary_inputs: Vec::new(),
secondary_outputs: Vec::new(),
selection: Selection::None,
visible: true,
previewed: false,
glide: DVec2::ZERO,
}
}
fn layer(key: u64, (x, y): (i32, i32), name: &str) -> Layer {
Layer {
key: NodeId(key),
cell: IVec2::new(x, y),
name: name.to_string(),
renaming: false,
width: 8,
chain_width: 0,
has_left_input_wire: false,
primary_input: None,
primary_output: None,
secondary_input: None,
primary_input_connected_to_layer: false,
primary_output_connected_to_layer: false,
visible: true,
locked: false,
read_only: false,
selection: Selection::None,
previewed: false,
hovered_button: None,
hovered_button_clicked: false,
glide: DVec2::ZERO,
}
}
fn wire(key: WireKey, path: BezPath, data_type: DataType) -> Wire {
Wire {
key,
path,
data_type,
thick: false,
center_line: BezPath::new(),
list: false,
insertion_target: false,
}
}
fn network_connector(kind: NetworkConnectorKind, index: usize, (x, y): (i32, i32), connector: Option<Connector>) -> NetworkConnector {
NetworkConnector {
kind,
index,
position: IVec2::new(x, y),
connector,
add_highlight: Highlight::None,
editable: false,
renaming: false,
glide: DVec2::ZERO,
}
}
fn badge(key: u64, (x, y): (i32, i32), text: &str) -> ErrorBadge {
ErrorBadge {
key: NodeId(key),
cell: IVec2::new(x, y),
on_layer: false,
text: text.to_string(),
hovered: false,
glide: DVec2::ZERO,
}
}
fn connector(name: &str, data_type: DataType) -> Connector {
Connector {
name: name.to_string(),
data_type,
connected: false,
highlight: Highlight::None,
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,490 @@
use super::{ARTWORK, badge, config, connector, context, executor, gpu, layer, nested, network, network_connector, node, thumbnail, wire};
use core_types::list::List;
use core_types::uuid::NodeId;
use core_types::{Context, OwnedContextImpl, Poll};
use glam::{DAffine2, DVec2, IVec2, UVec2};
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_ui::GraphUi;
use graph_ui::card::{Card, Connector, DataType, Highlight, Selection};
use graph_ui::error_badge::ErrorBadge;
use graph_ui::layer::Layer;
use graph_ui::network_connector::{NetworkConnector, NetworkConnectorKind};
use graph_ui::render::rows_context;
use graph_ui::replicated_map::ReplicatedMap;
use graph_ui::scene::{GraphUiScene, GraphUiSceneEdit};
use graph_ui::wire::{Wire, WireKey};
use graphene_std::application_io::{ExportFormat, RenderConfig};
use graphene_std::transform::Footprint;
use graphic_types::{Graphic, Vector};
use rendering::vello_scene_builder::VelloSceneBuilder;
use rendering::{Render, RenderParams};
use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use vello_gpu::kurbo::{Affine, BezPath, Rect};
const CARDS: usize = 300;
const LAYERS: usize = 60;
const ERRORS: usize = 10;
const GLIDING: usize = 5;
const COLUMNS: usize = 20;
const SAMPLES: usize = 21;
const RESOLUTION: UVec2 = UVec2::new(1920, 1080);
const NAMES: [&str; 10] = [
"Transform",
"Fill",
"Stroke",
"Boolean Operation",
"Copy to Points",
"Sample Polyline",
"Morph",
"Blend Shapes",
"Image Color Palette",
"Rectangle",
];
const ICONS: [&str; 10] = [
"NodeTransform",
"NodeFill",
"NodeStroke",
"NodeBooleanOperation",
"NodeRepeatOnPoints",
"NodeSamplePolyline",
"NodeMorph",
"NodeBlend",
"NodeImageColorPalette",
"NodeRectangle",
];
const ERROR: &str = "These input types are incompatible:\n• Input 2:\n…found: Color\n…expected: Number\n\nThis is not a supported arrangement of types for the node.";
const ROWS: [(&str, DataType); 8] = [
("Translation", DataType::General),
("Rotation", DataType::Number),
("Scale", DataType::General),
("Color", DataType::Color),
("Width", DataType::Number),
("Opacity", DataType::Number),
("Gradient", DataType::Gradient),
("Separation Disk Diameter", DataType::Number),
];
fn selection(index: usize) -> Selection {
if index.is_multiple_of(7) { Selection::Active } else { Selection::None }
}
fn connector_from((name, data_type): (&str, DataType), connected: bool) -> Connector {
Connector {
connected,
..connector(name, data_type)
}
}
fn card(index: usize) -> Card {
Card {
icon: ICONS[index % ICONS.len()].to_string(),
primary_input: Some(connector_from(("Content", DataType::Vector), true)),
primary_output: Some(connector_from(("Out", DataType::Vector), !index.is_multiple_of(4))),
secondary_inputs: (0..2 + index % 3)
.map(|row| connector_from(ROWS[(index + row) % ROWS.len()], (index + row).is_multiple_of(3)))
.collect(),
secondary_outputs: if index.is_multiple_of(5) {
vec![connector_from(("Area", DataType::Number), false)]
} else {
Vec::new()
},
selection: selection(index),
visible: !index.is_multiple_of(11),
previewed: index == 0,
..super::card(index as u64, ((index % COLUMNS) as i32 * 7, (index / COLUMNS) as i32 * 6), NAMES[index % NAMES.len()])
}
}
fn nth_layer(index: usize) -> Layer {
Layer {
width: 8 + (index % 3) as u32,
chain_width: if index.is_multiple_of(2) { 8 } else { 0 },
has_left_input_wire: index.is_multiple_of(4),
primary_input: Some(connector_from(("", DataType::Graphic), !index.is_multiple_of(10))),
primary_output: Some(connector_from(("", DataType::Graphic), true)),
secondary_input: Some(connector_from(("", DataType::Vector), index.is_multiple_of(2))),
primary_input_connected_to_layer: !index.is_multiple_of(10),
primary_output_connected_to_layer: !index.is_multiple_of(10),
visible: !index.is_multiple_of(11),
locked: index.is_multiple_of(13),
selection: selection(index),
previewed: index == 1,
..layer((CARDS + index) as u64, ((index % 10) as i32 * 14 + 3, (index / 10) as i32 * 6 + 3), NAMES[index % NAMES.len()])
}
}
fn unnamed(mut card: Card) -> Card {
card.name.clear();
let connectors = card
.primary_input
.iter_mut()
.chain(&mut card.primary_output)
.chain(&mut card.secondary_inputs)
.chain(&mut card.secondary_outputs);
connectors.for_each(|connector| connector.name.clear());
card
}
fn scene(cards: impl IntoIterator<Item = Card>) -> GraphUiScene {
let mut edit = GraphUiScene::default().edit();
edit.cards.replace_all(cards);
edit.finish().0
}
fn rewire(edit: &mut GraphUiSceneEdit) {
let wires = wires(&edit.cards);
edit.wires.replace_all(wires);
}
fn wires(cards: &ReplicatedMap<Card>) -> Vec<Wire> {
cards.iter().zip(cards.iter().skip(1)).map(|(from, to)| wire_between(from, to)).collect()
}
fn wire_between(from: &Card, to: &Card) -> Wire {
let center = |(top_left, _): (DVec2, &Connector)| top_left + 4.;
let [start, end] = [from.outputs().next(), to.inputs().next()].map(|connector| connector.map(center).expect("every card has a primary input and output"));
let point = |point: DVec2| (point.x, point.y);
let mut path = BezPath::new();
path.move_to(point(start));
path.line_to(point(start + DVec2::X * 12.));
path.curve_to(point(start + DVec2::X * 48.), point(end - DVec2::X * 48.), point(end - DVec2::X * 12.));
path.line_to(point(end));
Wire {
list: to.key.0.is_multiple_of(4),
..wire(WireKey::Input { node: to.key, index: 0 }, path, DataType::Vector)
}
}
fn network_connectors(cells_down: i32) -> Vec<NetworkConnector> {
let column = |kind, x| {
let place = move |row: usize| (x, (cells_down + row as i32) * 24);
let named = ROWS[..4].iter().enumerate().map(move |(index, &row)| NetworkConnector {
editable: true,
..network_connector(kind, index, place(if index == 0 { 0 } else { index + 1 }), Some(connector_from(row, true)))
});
named.chain([network_connector(kind, 4, place(6), None)])
};
column(NetworkConnectorKind::Import, -96).chain(column(NetworkConnectorKind::Export, COLUMNS as i32 * 7 * 24)).collect()
}
fn error(index: usize) -> ErrorBadge {
let card = card(index * 31 % CARDS);
badge(card.key.0, card.cell.into(), ERROR)
}
fn full_scene() -> GraphUiScene {
let mut edit = scene((0..CARDS).map(card)).edit();
edit.layers.replace_all((0..LAYERS).map(nth_layer));
edit.network_connectors.replace_all(network_connectors(0));
edit.errors.replace_all((0..ERRORS).map(error));
rewire(&mut edit);
edit.finish().0
}
fn moved(card: &Card, offset: IVec2) -> Card {
Card {
cell: card.cell + offset,
..card.clone()
}
}
fn reselected(card: &Card) -> Card {
let selection = match card.selection {
Selection::None => Selection::Inactive,
Selection::Inactive => Selection::Active,
Selection::Active => Selection::None,
};
Card { selection, ..card.clone() }
}
fn median(mut times: Vec<Duration>) -> Duration {
times.sort();
times[times.len() / 2]
}
fn ms(time: Duration) -> f64 {
time.as_secs_f64() * 1000.
}
#[test]
#[ignore = "prints timings"]
fn time_a_pan_a_card_change_and_a_rebuild_of_300_cards() {
let gpu = gpu();
let (render_graph_ui, graph_ui_output) = executor(network(&gpu, [nested(graph_ui::render::network())]));
let (draw_cards, cards_output) = executor(network(&gpu, [node(graph_ui::nodes::draw_cards::IDENTIFIER, vec![])]));
let (draw_wires, wires_output) = executor(network(&gpu, [node(graph_ui::nodes::draw_wires::IDENTIFIER, vec![])]));
let (draw_grid, grid_output) = executor(network(&gpu, [node(graph_ui::nodes::draw_grid::IDENTIFIER, vec![])]));
let (draw_thumbnails, thumbnails_output) = executor(network(&gpu, [node(graph_ui::nodes::draw_thumbnails::IDENTIFIER, vec![])]));
let render_config = RenderConfig {
viewport: Footprint {
resolution: RESOLUTION,
..Default::default()
},
scale: 1.,
export_format: ExportFormat::Raster,
..Default::default()
};
let view = |sample: usize| DAffine2::from_scale_angle_translation(DVec2::splat(0.5), 0., DVec2::new(100. + sample as f64, 0.));
let mut editor_scene = full_scene();
let mut runtime_scene = editor_scene.clone();
let thumbnails: Arc<BTreeMap<NodeId, Graphic>> = Arc::new(editor_scene.layers().iter().map(|layer| (layer.key, thumbnail(&gpu, Rect::new(12., 0., 60., 48.), ARTWORK))).collect());
let mut render = |change: &mut dyn FnMut(&mut GraphUiSceneEdit), view: DAffine2| {
let mut edit = std::mem::take(&mut editor_scene).edit();
change(&mut edit);
let (scene, delta) = edit.finish();
editor_scene = scene;
let start = Instant::now();
runtime_scene.apply(delta);
let graph_ui = GraphUi {
scene: runtime_scene.clone(),
config: config(view, 0.5),
thumbnails: thumbnails.clone(),
};
let context = context(render_config, graph_ui);
let output = render_graph_ui.tree().eval_tagged_value(graph_ui_output.node(), &context).unwrap();
let time = start.elapsed();
let Poll::Final(TaggedValue::RenderOutput(RenderOutput {
data: RenderOutputType::Texture(texture),
..
})) = output
else {
panic!("{output:?}")
};
gpu.read_texture_pixels(&texture).unwrap();
time
};
render(&mut |_| {}, view(0));
let pan = median((1..=SAMPLES).map(|sample| render(&mut |_| {}, view(sample))).collect());
let interface_pan = median(
(1..=SAMPLES)
.map(|sample| render(&mut |edit| edit.network_connectors.replace_all(network_connectors(sample as i32 % 2)), view(sample)))
.collect(),
);
let card_change = median(
(0..SAMPLES)
.map(|sample| {
let key = NodeId((sample * 37 % CARDS) as u64);
render(
&mut |edit| {
edit.cards.update(&key, |card| *card = reselected(&moved(card, IVec2::Y)));
rewire(edit);
},
view(0),
)
})
.collect(),
);
let highlight = |card: &mut Card, highlight| card.primary_output.as_mut().expect("every card has a primary output").highlight = highlight;
let mut hovered = None;
let hover_move = median(
(0..SAMPLES)
.map(|sample| {
let key = NodeId((sample * 37 % CARDS) as u64);
let left = hovered.replace(key);
render(
&mut |edit| {
if let Some(left) = left {
edit.cards.update(&left, |card| highlight(card, Highlight::None));
}
edit.cards.update(&key, |card| highlight(card, Highlight::Hovered));
},
view(0),
)
})
.collect(),
);
let glide_frame = median(
(0..SAMPLES)
.map(|sample| {
let glide = DVec2::new(-24. * 0.6_f64.powi(sample as i32 % 8 + 1), 0.);
render(
&mut |edit| {
for index in 0..GLIDING {
edit.cards.update(&NodeId((index * 61 % CARDS) as u64), |card| card.glide = glide);
}
rewire(edit);
},
view(0),
)
})
.collect(),
);
let mut every_card = |changed: fn(&Card, IVec2) -> Card| {
median(
(0..SAMPLES)
.map(|sample| {
let offset = if sample % 2 == 0 { IVec2::X } else { -IVec2::X };
render(
&mut |edit| {
let cards: Vec<Card> = edit.cards.iter().map(|card| changed(card, offset)).collect();
edit.cards.replace_all(cards);
rewire(edit);
},
view(0),
)
})
.collect(),
)
};
let rebuild = every_card(|card, offset| reselected(&moved(card, offset)));
let every_card_moved = every_card(moved);
let draw = |card_at: fn(usize) -> Card| {
let cards: Vec<Card> = (0..CARDS).map(card_at).collect();
let scenes = [scene(cards.clone()), scene(cards.iter().map(reselected))];
let times = (0..SAMPLES).map(|sample| {
let context = rows_context(scenes[sample % 2].cards());
let start = Instant::now();
draw_cards.tree().eval::<Context, List<Vector>>(cards_output.node(), &context).expect("the cards are drawn");
start.elapsed()
});
median(times.collect())
};
let drawn = draw(card);
let drawn_unnamed = draw(|index| unnamed(card(index)));
let text = drawn.saturating_sub(drawn_unnamed);
let wired = |cards: Vec<Card>| {
let mut edit = scene(cards).edit();
rewire(&mut edit);
edit.finish().0
};
let cards: Vec<Card> = (0..CARDS).map(card).collect();
let scenes = [wired(cards.clone()), wired(cards.iter().map(|card| moved(card, IVec2::X)).collect())];
let wires_drawn = median(
(0..SAMPLES)
.map(|sample| {
let context = rows_context(scenes[sample % 2].wires());
let start = Instant::now();
draw_wires.tree().eval::<Context, List<Vector>>(wires_output.node(), &context).expect("the wires are drawn");
start.elapsed()
})
.collect(),
);
let grid = |zoom: f64, scale: f64| {
let resolution = (RESOLUTION.as_dvec2() * scale).as_uvec2();
let render_config = RenderConfig {
viewport: Footprint { resolution, ..render_config.viewport },
scale,
..render_config
};
let times = (1..=SAMPLES).map(|sample| {
let graph_ui = GraphUi {
scene: GraphUiScene::default(),
config: config(DAffine2::from_scale_angle_translation(DVec2::splat(zoom), 0., DVec2::new(100. + sample as f64, 0.)), 0.5),
thumbnails: Default::default(),
};
let context = context(render_config, graph_ui);
let mut scene = VelloSceneBuilder::new(resolution.x as u16, resolution.y as u16, Affine::IDENTITY, resolution.x);
let start = Instant::now();
let dots = draw_grid.tree().eval::<Context, List<Vector>>(grid_output.node(), &context).expect("the grid is drawn");
let drawn = start.elapsed();
dots.render_to_vello(&mut scene, DAffine2::from_scale(DVec2::splat(scale)), &RenderParams::default());
(drawn, start.elapsed() - drawn)
});
let (drawn, encoded): (Vec<Duration>, Vec<Duration>) = times.unzip();
(median(drawn), median(encoded))
};
let grids = [1., 2.].map(|scale| (scale, grid(0.5, scale), grid(1., scale)));
let times = (1..=SAMPLES).map(|sample| {
let graph_ui = GraphUi {
scene: editor_scene.clone(),
config: config(view(sample), 0.5),
thumbnails: thumbnails.clone(),
};
let context = context(render_config, graph_ui);
let mut scene = VelloSceneBuilder::new(RESOLUTION.x as u16, RESOLUTION.y as u16, Affine::IDENTITY, RESOLUTION.x);
let start = Instant::now();
let drawn = draw_thumbnails
.tree()
.eval::<Context, List<Vector>>(thumbnails_output.node(), &context)
.expect("the thumbnails are drawn");
let elapsed = start.elapsed();
drawn.render_to_vello(&mut scene, view(sample), &RenderParams::default());
(elapsed, start.elapsed() - elapsed)
});
let (thumbnails_drawn, thumbnails_encoded): (Vec<Duration>, Vec<Duration>) = times.unzip();
let scene = full_scene();
let raised_rows = OwnedContextImpl::default()
.with_varargs([Box::new(scene.layers().clone()), Box::new(scene.cards().clone())])
.into_context();
let scene_bands = [
("cards", graph_ui::nodes::draw_cards::IDENTIFIER, rows_context(scene.cards())),
("raised", graph_ui::nodes::draw_raised::IDENTIFIER, raised_rows),
("layers", graph_ui::nodes::draw_layers::IDENTIFIER, rows_context(scene.layers())),
("wires", graph_ui::nodes::draw_wires::IDENTIFIER, rows_context(scene.wires())),
("errors", graph_ui::nodes::draw_errors::IDENTIFIER, rows_context(scene.errors())),
("imports/exports", graph_ui::nodes::draw_network_connectors::IDENTIFIER, rows_context(scene.network_connectors())),
]
.map(|(name, band, rows)| {
let (band, output) = executor(network(&gpu, [node(band, Vec::new())]));
(name, band.tree().eval::<Context, List<Vector>>(output.node(), &rows).expect("the band is drawn"))
});
let encoded = |band: &List<Vector>, zoom: f64, left: f64| {
let times = (1..=SAMPLES).map(|sample| {
let view = DAffine2::from_scale_angle_translation(DVec2::splat(zoom), 0., DVec2::new(left + sample as f64, 0.));
let mut scene = VelloSceneBuilder::new(RESOLUTION.x as u16, RESOLUTION.y as u16, Affine::IDENTITY, RESOLUTION.x);
let start = Instant::now();
band.render_to_vello(&mut scene, view, &RenderParams::default());
start.elapsed()
});
median(times.collect())
};
let band_encodes = [0.5, 1.].map(|zoom| {
let bands = scene_bands.iter().map(|(name, band)| (*name, band.len(), encoded(band, zoom, 100.), encoded(band, zoom, -100_000.)));
(zoom, bands.collect::<Vec<_>>())
});
let profile = if cfg!(debug_assertions) { "dev" } else { "release" };
println!(
"{CARDS} cards, each wired to the next, {LAYERS} layers, four imports and four exports and {ERRORS} error badges at {}x{}, {profile} profile, CPU time without the GPU wait, median of {SAMPLES}",
RESOLUTION.x, RESOLUTION.y
);
println!("pan step (view change only): {:.3} ms", ms(pan));
println!("pan step that moves the imports and exports a cell: {:.3} ms", ms(interface_pan));
println!("one-card change (one card moved and reselected, so drawn again, and its two wires): {:.3} ms", ms(card_change));
println!("hover moving from one card to another: {:.3} ms", ms(hover_move));
println!("glide frame of {GLIDING} cards and their wires: {:.3} ms", ms(glide_frame));
println!("full rebuild (every card and wire changed): {:.3} ms", ms(rebuild));
println!("every card only moved a cell (placed again, not drawn again), every wire changed: {:.3} ms", ms(every_card_moved));
println!("draw_cards alone, every card drawn again: {:.3} ms, with every name empty: {:.3} ms", ms(drawn), ms(drawn_unnamed));
println!("draw_wires alone, every wire drawn again: {:.3} ms", ms(wires_drawn));
println!(
"text (width, ellipsized, outline), the difference: {:.3} ms, {:.0}% of draw_cards, {:.0}% of a one-card change",
ms(text),
100. * text.as_secs_f64() / drawn.as_secs_f64(),
100. * text.as_secs_f64() / card_change.as_secs_f64()
);
for (scale, (drawn, encoded), (drawn_at_1, encoded_at_1)) in grids {
println!(
"grid alone at zoom 0.5 and device scale {scale}: draw_grid {:.3} ms + Vello encode {:.3} ms (at zoom 1: {:.3} ms + {:.3} ms)",
ms(drawn),
ms(encoded),
ms(drawn_at_1),
ms(encoded_at_1)
);
}
println!(
"thumbnails alone, one on each of the {LAYERS} layers: draw_thumbnails {:.3} ms + Vello encode {:.3} ms",
ms(median(thumbnails_drawn)),
ms(median(thumbnails_encoded))
);
for (zoom, bands) in band_encodes {
println!("Vello encode alone of each scene band at zoom {zoom}, on screen and with every item panned off screen (the bookkeeping before the cull):");
for (name, items, on_screen, off_screen) in &bands {
println!(" {name} ({items} items): {:.3} ms on screen, {:.3} ms off screen", ms(*on_screen), ms(*off_screen));
}
let on_screen: Duration = bands.iter().map(|(_, _, on_screen, _)| *on_screen).sum();
let off_screen: Duration = bands.iter().map(|(_, _, _, off_screen)| *off_screen).sum();
println!(" all six: {:.3} ms on screen, {:.3} ms off screen", ms(on_screen), ms(off_screen));
}
}