Compare commits

..
50 changed files with 937 additions and 5525 deletions

No files matched your search

Generated
-29
View File
@@ -2535,35 +2535,6 @@ 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,8 +34,6 @@ 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",
@@ -114,8 +112,6 @@ 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" }
@@ -4,5 +4,6 @@ mod mandelbrot_v1;
mod mandelbrot_v2;
mod mix_colors_from_mix_node;
mod noise_pattern_v1;
mod noise_pattern_v2;
mod pattern_square;
mod renames;
@@ -0,0 +1,185 @@
use migration_core::attr::node::VISIBLE;
use migration_core::attr::node::ui::POSITION;
use migration_core::{Attributes, CHAIN_WIDTH, Downstream, NewNode, Node, NodeInput, OutputConnector, Position, decl, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
Bool(bool),
}
/// 'Noise Pattern' writes its value as the gray at that gamma-encoded level rather than as linear light, so whatever read it reads it through a
/// 'Gamma Correction' at its default gamma of 2.2, which turns the new gray back into about the old one.
#[migration("raster_nodes::std_nodes::NoisePatternNode"@2 => @3)]
pub fn noise_pattern_v2(node: &Node, downstream: &mut Downstream, attributes: &mut Attributes) {
let consumers = downstream.consumers(0);
if consumers.is_empty() {
return;
}
let gamma_correction = downstream.add_node(NewNode {
declaration: decl!("raster_nodes::adjustments::GammaCorrectionNode"@1),
inputs: vec![NodeInput::Node { id: node.id(), index: 0 }, literal(Tagged::Number(2.2)), literal(Tagged::Bool(false))],
});
for consumer in consumers {
downstream.connect(OutputConnector { node: gamma_correction, output: 0 }, consumer);
}
// A disabled pattern passes its primary input through, so its Gamma Correction is disabled too
if !node.attributes().get_or(VISIBLE, true) {
attributes.set(gamma_correction, VISIBLE, &false);
}
// The Gamma Correction takes the pattern's place, with the pattern before it
if let Some(stored) = node.attributes().get_typed::<Position>(POSITION) {
attributes.set(gamma_correction, POSITION, &stored);
}
attributes.set(node.id(), POSITION, &Position::Relative([-CHAIN_WIDTH, 0]));
}
#[cfg(test)]
mod tests {
use super::*;
use document_graph_storage::{Implementation, Network, NetworkId, NodeId, ROOT_NETWORK, TimeStamp};
use migration_core::Declaration;
use migration_core::attr::node::ui::IS_LAYER;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
const NOISE_PATTERN: Declaration = decl!("raster_nodes::std_nodes::NoisePatternNode"@2);
const GAMMA_CORRECTION: Declaration = decl!("raster_nodes::adjustments::GammaCorrectionNode"@1);
const CONSUMER: Declaration = decl!("migration_testing::consumer"@1);
fn contract() -> SourceContract {
SourceContract::new(15, |random, _| literal(Tagged::Number(random.below(10) as f64)))
}
fn noise_inputs() -> Vec<NodeInput> {
(0..15).map(|slot| literal(Tagged::Number(slot as f64))).collect()
}
fn wire(id: NodeId) -> NodeInput {
NodeInput::Node { id, index: 0 }
}
#[test]
fn rewrites_history() {
check_commutation(&NoisePatternV2, &contract());
check_undo(&NoisePatternV2, &contract());
}
#[test]
fn every_reader_reads_the_pattern_through_one_gamma_correction() {
let mut fixture = Fixture::new(&NoisePatternV2);
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
let both_slots = fixture.add(CONSUMER, vec![wire(noise), wire(noise)]);
let second_slot = fixture.add(CONSUMER, vec![literal(Tagged::Number(0.)), wire(noise)]);
fixture.export(wire(noise));
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
assert_eq!(fixture.declaration_of(&migrated, noise), Some(decl!("raster_nodes::std_nodes::NoisePatternNode"@3)));
assert_eq!(fixture.inputs(&migrated, noise), noise_inputs());
let NodeInput::Node { id: gamma_correction, .. } = fixture.inputs(&migrated, second_slot)[1] else {
panic!("the consumer should read a node")
};
assert_eq!(fixture.declaration_of(&migrated, gamma_correction), Some(GAMMA_CORRECTION));
assert_eq!(fixture.inputs(&migrated, gamma_correction), [wire(noise), literal(Tagged::Number(2.2)), literal(Tagged::Bool(false))]);
assert_eq!(fixture.inputs(&migrated, both_slots), [wire(gamma_correction), wire(gamma_correction)]);
assert_eq!(fixture.inputs(&migrated, second_slot)[0], literal(Tagged::Number(0.)));
assert_eq!(migrated.networks[&ROOT_NETWORK].exports[0].target, Some(wire(gamma_correction)));
assert_eq!(migrated.node_instances.len(), 4);
}
#[test]
fn a_disabled_pattern_is_read_through_a_disabled_gamma_correction() {
let visibility_of_gamma_correction = |visible: bool| {
let mut fixture = Fixture::new(&NoisePatternV2);
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
if !visible {
let attributes = fixture.registry.node_instances.get_mut(&noise).unwrap().attributes_mut();
attributes.set_serialized(VISIBLE, &false, TimeStamp::ORIGIN).unwrap();
}
let consumer = fixture.add(CONSUMER, vec![wire(noise)]);
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
let NodeInput::Node { id: gamma_correction, .. } = fixture.inputs(&migrated, consumer)[0] else {
panic!("the consumer should read a node")
};
migrated.node_instances[&gamma_correction].attributes().get_typed::<bool>(VISIBLE)
};
// Visible is the default, so only a disabled pattern writes it
assert_eq!(visibility_of_gamma_correction(false), Some(false));
assert_eq!(visibility_of_gamma_correction(true), None);
}
#[test]
fn an_unread_pattern_gains_no_gamma_correction() {
let mut fixture = Fixture::new(&NoisePatternV2);
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
assert_eq!(fixture.declaration_of(&migrated, noise), Some(decl!("raster_nodes::std_nodes::NoisePatternNode"@3)));
assert_eq!(migrated.node_instances.len(), 1);
}
#[test]
fn a_pattern_in_a_subgraph_is_read_through_a_gamma_correction_inside_it() {
let mut fixture = Fixture::new(&NoisePatternV2);
// A custom subgraph exporting the pattern, read by the root network's export
let (subgraph, instance) = (NetworkId(100), NodeId(100));
fixture.registry.networks.insert(subgraph, Network::default());
let instance_node = document_graph_storage::Node::new(ROOT_NETWORK, Implementation::Network(subgraph), 0);
fixture.registry.node_instances.insert(instance, instance_node);
let noise = fixture.add_in(subgraph, NOISE_PATTERN, noise_inputs());
fixture.export_from(subgraph, wire(noise));
fixture.export(wire(instance));
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
let Some(NodeInput::Node { id: gamma_correction, .. }) = migrated.networks[&subgraph].exports[0].target else {
panic!("the subgraph's export should read a node")
};
assert_eq!(fixture.declaration_of(&migrated, gamma_correction), Some(GAMMA_CORRECTION));
assert_eq!(migrated.node_instances[&gamma_correction].network(), subgraph);
assert_eq!(fixture.inputs(&migrated, gamma_correction)[0], wire(noise));
assert_eq!(migrated.networks[&ROOT_NETWORK].exports[0].target, Some(wire(instance)));
}
/// The positions of the pattern and its Gamma Correction after migrating a pattern at `position`, read by a layer's chain or by another node.
fn placed_gamma_correction(position: Position, read_by_layer: bool) -> [Option<Position>; 2] {
let mut fixture = Fixture::new(&NoisePatternV2);
let noise = fixture.add(NOISE_PATTERN, noise_inputs());
let attributes = fixture.registry.node_instances.get_mut(&noise).unwrap().attributes_mut();
attributes.set_serialized(POSITION, &position, TimeStamp::ORIGIN).unwrap();
let (reader, slot) = if read_by_layer {
let layer = fixture.add(decl!("graphic_nodes::layer"@1), vec![literal(Tagged::Number(0.)), wire(noise)]);
let attributes = fixture.registry.node_instances.get_mut(&layer).unwrap().attributes_mut();
attributes.set_serialized(IS_LAYER, &true, TimeStamp::ORIGIN).unwrap();
(layer, 1)
} else {
(fixture.add(CONSUMER, vec![wire(noise)]), 0)
};
let migrated = fixture.migrate(&NoisePatternV2).unwrap();
let NodeInput::Node { id: gamma_correction, .. } = fixture.inputs(&migrated, reader)[slot] else {
panic!("slot {slot} of the reader should read a node")
};
assert_eq!(fixture.declaration_of(&migrated, gamma_correction), Some(GAMMA_CORRECTION));
[noise, gamma_correction].map(|node| migrated.node_instances[&node].attributes().get_typed::<Position>(POSITION))
}
#[test]
fn the_gamma_correction_takes_the_place_of_a_chained_or_placed_pattern() {
let chained = Position::Relative([-CHAIN_WIDTH, 0]);
for (position, read_by_layer) in [(chained, true), (Position::Absolute([5, 5]), false)] {
assert_eq!(placed_gamma_correction(position, read_by_layer), [Some(chained), Some(position)]);
}
}
}
@@ -2687,6 +2687,7 @@ impl DocumentMessageHandler {
fn finish_remote_reconcile(&mut self, reconciled: Reconciled, resources_changed: bool, open_network_transform: Option<DAffine2>, responses: &mut VecDeque<Message>) {
for path in self.network_interface.paths_reaching(&reconciled.networks) {
self.network_interface.unload_import_export_ports(&path);
self.network_interface.unload_all_nodes_bounding_box(&path);
self.network_interface.unload_outward_wires(&path);
}
self.network_interface.load_structure();
@@ -807,6 +807,9 @@ fn import_usvg_node(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node,
// Set positions for all imported descendants in a single O(n) pass
let parent_pos = modify_inputs.network_interface.position(&layer.to_node(), &[]).unwrap_or(IVec2::ZERO);
set_import_child_positions(modify_inputs.network_interface, layer, parent_pos, &child_extents_svg_order, &group_extents_map);
// Invalidate caches once after all positions are set
modify_inputs.network_interface.unload_all_nodes_bounding_box(&[]);
}
usvg::Node::Path(path) => {
import_usvg_path(modify_inputs, node, path, layer, gradient_info);
@@ -24,12 +24,14 @@ use crate::messages::tool::common_functionality::utility_functions::{make_path_e
use crate::messages::tool::tool_messages::tool_prelude::{Key, MouseMotion};
use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo};
use crate::messages::viewport::Position;
use glam::{DVec2, IVec2};
use glam::{DAffine2, DVec2, IVec2};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput};
use graphene_std::math::math_ext::QuadExt;
use graphene_std::vector::algorithms::bezpath_algorithms::bezpath_is_inside_bezpath;
use graphene_std::*;
use kurbo::{DEFAULT_ACCURACY, Shape};
use renderer::Quad;
#[derive(Debug, ExtractField)]
pub struct NodeGraphMessageContext<'a> {
@@ -2537,13 +2539,13 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
HashSet::new()
};
let all_nodes = network_metadata.persistent_metadata.node_metadata.keys().cloned().collect::<Vec<_>>();
let [selection_min, selection_max] = [box_selection_start.min(box_selection_end_graph), box_selection_start.max(box_selection_end_graph)];
for node_id in all_nodes {
let Some(body) = network_interface.with_layout(selection_network_path, |layout| layout.body(&node_id)).flatten() else {
log::error!("Could not get the body of node {node_id}");
let Some(click_targets) = network_interface.node_click_targets(&node_id, selection_network_path) else {
log::error!("Could not get transient metadata for node {node_id}");
continue;
};
if body.overlaps(selection_min, selection_max) {
let quad = Quad::from_box([box_selection_start, box_selection_end_graph]);
if click_targets.node_click_target.intersect_path(|| quad.to_lines(), DAffine2::IDENTITY) {
if alt {
nodes.remove(&node_id);
} else {
@@ -1,7 +1,7 @@
//! Times laying out the demo artworks, building their click targets, and hit testing them, as the editor does on demand.
use super::test_support::open_demo;
use crate::messages::portfolio::document::utility_types::network_interface::{GlideOffsets, InputConnector, OutputConnector, Part};
use crate::messages::portfolio::document::utility_types::network_interface::{GlideOffsets, InputConnector, OutputConnector};
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use glam::DVec2;
use graphene_std::uuid::NodeId;
@@ -20,32 +20,20 @@ const DEMOS: [&str; 8] = [
const REPETITIONS: u32 = 200;
#[test]
fn wire_anchors_lie_on_the_ports_of_every_demo_node() {
fn wire_anchors_match_the_ports_of_every_demo_node() {
for demo in DEMOS {
let document = open_demo(demo);
let interface = &document.network_interface;
for node_id in interface.document_network().nodes.keys() {
// A redirect dot's wires attach at its center, between the gutters they're grabbed from
let body = interface.node_bounding_box(node_id, &[]).expect("every node has a body");
let is_redirect_dot = interface.is_redirect_dot(node_id, &[]);
let on_port = |wanted: Part, anchor: Option<DVec2>| {
let port = interface.find_node_part(node_id, &[], |part, target| (part == wanted).then_some(*target));
match (port, anchor) {
(Some(_), Some(anchor)) if is_redirect_dot => anchor == (body[0] + body[1]) / 2.,
(Some(port), Some(anchor)) => port.contains(anchor),
(None, None) => true,
_ => false,
}
};
let ports = interface.compute_node_ports(node_id, &[]).expect("every node has ports");
for index in 0..interface.number_of_inputs(node_id, &[]) {
let anchor = interface.input_position(&InputConnector::node_at_index(*node_id, index), &[]);
assert!(on_port(Part::Input(index as u32), anchor), "{demo}: input {index} of node {node_id} attaches at {anchor:?}");
let input = InputConnector::node_at_index(*node_id, index);
assert_eq!(interface.input_position(&input, &[]), ports.input_port_position(index), "{demo}: input {index} of node {node_id}");
}
for index in 0..interface.number_of_outputs(node_id, &[]) {
let anchor = interface.output_position(&OutputConnector::node(*node_id, index), &[]);
assert!(on_port(Part::Output(index as u32), anchor), "{demo}: output {index} of node {node_id} attaches at {anchor:?}");
let output = OutputConnector::node(*node_id, index);
assert_eq!(interface.output_position(&output, &[]), ports.output_port_position(index), "{demo}: output {index} of node {node_id}");
}
}
}
@@ -72,7 +60,7 @@ fn time_the_layout_click_targets_and_hit_tests() {
let start = Instant::now();
for _ in 0..REPETITIONS {
for node_id in &node_ids {
std::hint::black_box(interface.find_node_part(node_id, &[], |_, target| std::hint::black_box(target).part.eq(&Part::Name).then_some(())));
std::hint::black_box(interface.node_click_targets(node_id, &[]));
}
}
let all_click_targets = start.elapsed() / REPETITIONS;
@@ -35,6 +35,7 @@ fn store_drawn_positions_as_absolute(interface: &mut NodeNetworkInterface, posit
if let Some(mut node) = interface.node_mut(NodeLocator::new(*node_id, network_path)) {
node.set_absolute_position(*position);
}
interface.invalidate_positions(network_path);
}
}
@@ -171,14 +172,14 @@ fn the_layout_kept_after_a_drag_matches_the_network_as_stored() {
interface.finish_drag(&[]);
let kept = interface.positions(node_ids.iter().copied(), &[]);
let Some((laid_out, graph)) = interface.layout_graph(&[]) else {
let Some((_, indices, graph)) = interface.layout_graph(&[]) else {
panic!("the root network is laid out")
};
let fresh = graph_layout::Layout::new(&graph);
for (other, position) in kept {
assert_eq!(
Some(position),
laid_out.indices.get(&other).map(|index| fresh.node(*index).position),
indices.get(&other).map(|index| fresh.node(*index).position),
"After dragging {node_id} by {offset}, node {other} should be where the stored network places it"
);
}
@@ -22,7 +22,6 @@ mod layout;
mod layout_pass;
mod memo_network;
mod mutations;
mod node_parts;
mod queries;
mod reconcile;
mod resolved_types;
@@ -37,7 +36,6 @@ mod view;
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
pub use layout_pass::NetworkLayout;
pub use node_parts::{Part, PartTarget};
pub use reconcile::{ReconcileError, Reconciled};
use store::Guarded;
pub use store::NodeLocator;
@@ -88,15 +88,34 @@ impl NodeNetworkInterface {
*network_metadata.transient_metadata.glide_offsets.borrow_mut() = glide_offsets;
}
/// Reads the import/export ports through &self, building them again first if the layout they were placed by has changed.
pub(crate) fn with_import_export_ports<R>(&self, network_path: &[NodeId], read: impl FnOnce(&Ports) -> R) -> Option<R> {
let generation = self.with_layout(network_path, NetworkLayout::generation)?;
let cache = &self.network_metadata(network_path)?.transient_metadata.import_export_ports;
if cache.with_loaded(|(placed_by, _)| *placed_by != generation) == Some(true) {
cache.unload();
}
pub fn import_export_ports(&mut self, network_path: &[NodeId]) -> Option<&Ports> {
self.load_import_export_ports(network_path);
cache.with_loaded_or(|| Some((generation, self.compute_import_export_ports(network_path)?)), |(_, ports)| read(ports))
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in import_export_ports");
return None;
};
let Some(ports) = transient.import_export_ports.get_loaded_mut() else {
log::error!("Could not load import export ports in import_export_ports");
return None;
};
Some(ports)
}
/// Reads the import/export ports through &self, loading them first if needed.
pub(crate) fn with_import_export_ports<R>(&self, network_path: &[NodeId], read: impl FnOnce(&Ports) -> R) -> Option<R> {
self.network_metadata(network_path)?
.transient_metadata
.import_export_ports
.with_loaded_or(|| self.compute_import_export_ports(network_path), read)
}
pub fn load_import_export_ports(&self, network_path: &[NodeId]) {
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in load_import_export_ports");
return;
};
network_metadata.transient_metadata.import_export_ports.ensure_loaded(|| self.compute_import_export_ports(network_path));
}
pub(crate) fn unload_import_export_ports(&mut self, network_path: &[NodeId]) {
@@ -107,13 +126,78 @@ impl NodeNetworkInterface {
transient.import_export_ports.unload();
}
/// The combined bounds of every node in the network, in node graph space.
pub fn all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
self.with_layout(network_path, NetworkLayout::bounds)
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in all_nodes_bounding_box");
return None;
};
let bounding_box = network_metadata
.transient_metadata
.all_nodes_bounding_box
.with_loaded_or(|| self.compute_all_nodes_bounding_box(network_path), |bounds| *bounds);
if bounding_box.is_none() {
log::error!("Could not load all nodes bounding box in all_nodes_bounding_box");
}
bounding_box
}
/// The combined bounds of every node in the network, in node graph space.
fn compute_all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
let network_metadata = self.network_metadata(network_path)?;
let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect::<Vec<_>>();
Some(
nodes
.iter()
.filter_map(|node_id| self.node_bounding_box(node_id, network_path))
.reduce(Quad::combine_bounds)
.unwrap_or([DVec2::new(0., 0.), DVec2::new(0., 0.)]),
)
}
pub fn unload_all_nodes_bounding_box(&mut self, network_path: &[NodeId]) {
let Some(transient) = self.network_transient_mut(network_path) else {
log::error!("Could not get nested network_metadata in unload_all_nodes_bounding_box");
return;
};
transient.all_nodes_bounding_box.unload();
transient.import_export_clearance.unload();
self.unload_import_export_ports(network_path);
}
pub(crate) fn import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> {
self.with_layout(network_path, NetworkLayout::clearance)
let Some(network_metadata) = self.network_metadata(network_path) else {
log::error!("Could not get nested network_metadata in import_export_clearance");
return None;
};
network_metadata
.transient_metadata
.import_export_clearance
.with_loaded_or(|| self.compute_import_export_clearance(network_path), |clearance| *clearance)
}
/// The horizontal extents of the nodes in the network, with the redirect dots measured by their centers apart from the rest.
fn compute_import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> {
let network_metadata = self.network_metadata(network_path)?;
let widen = |span: Option<[f64; 2]>, left: f64, right: f64| Some(span.map_or([left, right], |[min, max]| [min.min(left), max.max(right)]));
let mut clearance = ImportExportClearance::default();
for node_id in network_metadata.persistent_metadata.node_metadata.keys() {
let Some([top_left, bottom_right]) = self.node_bounding_box(node_id, network_path) else {
continue;
};
if self.is_redirect_dot(node_id, network_path) {
let center = (top_left.x + bottom_right.x) / 2.;
clearance.dot_centers = widen(clearance.dot_centers, center, center);
} else {
clearance.node_sides = widen(clearance.node_sides, top_left.x, bottom_right.x);
}
}
Some(clearance)
}
pub fn outward_wires(&mut self, network_path: &[NodeId]) -> Option<&HashMap<OutputConnector, Vec<InputConnector>>> {
@@ -280,10 +364,6 @@ impl NodeNetworkInterface {
}
pub fn layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<u32> {
self.layer_width_and_name_width(node_id, network_path).map(|(layer_width, _)| layer_width)
}
pub(super) fn layer_width_and_name_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<(u32, f64)> {
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
log::error!("Could not get nested node_metadata in layer_width");
return None;
@@ -296,7 +376,7 @@ impl NodeNetworkInterface {
node_metadata
.transient_metadata
.layer_width
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |widths| *widths)
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |layer_width| *layer_width)
}
/// Unloads layer width if the node is a layer.
@@ -469,10 +549,17 @@ impl NodeNetworkInterface {
}
/// The node's body, ports, and handles, built where it is drawn now.
/// The box around the node's body where it sits in its grid cell, in node graph space.
pub fn node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<DocumentNodeClickTargets> {
self.compute_node_click_targets(node_id, network_path)
}
pub(crate) fn with_node_click_targets<R>(&self, node_id: &NodeId, network_path: &[NodeId], read: impl FnOnce(&DocumentNodeClickTargets) -> R) -> Option<R> {
self.compute_node_click_targets(node_id, network_path).as_ref().map(read)
}
pub fn node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
let body = self.with_layout(network_path, |layout| layout.body(node_id)).flatten()?;
Some([body.min, body.max])
self.with_node_click_targets(node_id, network_path, |click_targets| click_targets.node_click_target.bounding_box())
.flatten()
}
}
@@ -330,6 +330,7 @@ async fn a_relative_node_follows_its_readers_until_it_loses_the_last_one() {
}
let relative = NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Relative(IVec2::new(-7, 3))));
network_interface.node_mut(NodeLocator::new(node, &[])).expect("the node exists").set_node_type(relative);
network_interface.invalidate_positions(&[]);
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(13, 7)));
@@ -46,6 +46,193 @@ impl NodeNetworkInterface {
(!hidden && output_index < self.number_of_outputs(node_id, network_path)).then_some(top_left + DVec2::new(5. * grid, grid * (output_index as f64 + 1.)))
}
pub(crate) fn compute_node_ports(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<Ports> {
let Some(node_position) = self.position(node_id, network_path) else {
log::error!("Could not get node position in compute_node_ports for node {node_id}");
return None;
};
let document_node = self.document_node(node_id, network_path)?;
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
let mut ports = Ports::new();
if self.is_redirect_dot(node_id, network_path) {
ports.insert_dot_ports(node_top_left + DVec2::new(0., GRID_SIZE as f64));
} else if !self.is_layer(node_id, network_path) {
let mut input_row_count = 0;
for (input_index, input) in document_node.inputs.iter().enumerate() {
if input.is_exposed() {
ports.insert_node_input(input_index, input_row_count, node_top_left);
}
if input_index == 0 || input.is_exposed() {
input_row_count += 1;
}
}
let start_index = if self.hidden_primary_output(node_id, network_path) { 1 } else { 0 };
for output_index in start_index..self.number_of_outputs(node_id, network_path) {
ports.insert_node_output(output_index, node_top_left);
}
} else {
ports.insert_layer_input(0, node_top_left);
if document_node.inputs.iter().filter(|input| input.is_exposed()).count() > 1 {
ports.insert_layer_input(1, node_top_left);
}
ports.insert_layer_output(node_top_left);
}
Some(ports)
}
/// The node body, its ports, and for a layer its visibility, lock, grip and name handles, all in node graph space.
pub(super) fn compute_node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<DocumentNodeClickTargets> {
let Some(node_position) = self.position(node_id, network_path) else {
log::error!("Could not get node position in compute_node_click_targets for node {node_id}");
return None;
};
let node_metadata = self.node_metadata(node_id, network_path)?;
let port_click_targets = self.compute_node_ports(node_id, network_path)?;
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
// A redirect dot is centered on the grid point at the connector height of an ordinary node's first row.
// Its body also covers the gutters beside it holding its ports, so every press near it moves the dot unless it lands on an available port.
if self.is_redirect_dot(node_id, network_path) {
const DOT_HALF_WIDTH: f64 = 15.;
const DOT_HALF_HEIGHT: f64 = 8.;
let center = node_top_left + DVec2::new(0., GRID_SIZE as f64);
let path = rounded_rectangle_path(
center - DVec2::new(DOT_HALF_WIDTH, DOT_HALF_HEIGHT),
center + DVec2::new(DOT_HALF_WIDTH, DOT_HALF_HEIGHT),
[DOT_HALF_HEIGHT; 4],
);
return Some(DocumentNodeClickTargets {
node_click_target: ClickTarget::new_with_path(path, 0.),
port_click_targets,
node_type_metadata: NodeTypeClickTargets::Node,
});
}
let document_node_click_targets = if !node_metadata.persistent_metadata.is_layer() {
let height = self.displayed_row_count(node_id, network_path) as u32 * GRID_SIZE;
let width = 5 * GRID_SIZE;
// Offset down by half a grid so the click target sits below the top connector strip.
let node_click_target_top_left = node_top_left + DVec2::new(0., HALF_GRID_SIZE as f64);
let node_click_target_bottom_right = node_click_target_top_left + DVec2::new(width as f64, height as f64);
let radius = 3.;
let path = rounded_rectangle_path(node_click_target_top_left, node_click_target_bottom_right, [radius; 4]);
let node_click_target = ClickTarget::new_with_path(path, 0.);
DocumentNodeClickTargets {
node_click_target,
port_click_targets,
node_type_metadata: NodeTypeClickTargets::Node,
}
} else {
let layer_width_cells = self.layer_width(node_id, network_path).unwrap_or_else(|| {
log::error!("Could not get layer width in compute_node_click_targets");
0
});
let width = layer_width_cells * GRID_SIZE;
let height = LAYER_GRID_HEIGHT * GRID_SIZE;
let locked = self.is_locked(node_id, network_path);
// The layer is `2 * GRID_SIZE` tall, so its vertical center sits one grid unit below `node_top_left.y`.
// Visibility/lock buttons fill a 1-grid-cell square (so half-extents of HALF_GRID_SIZE each side of center).
const LAYER_VERTICAL_CENTER: f64 = GRID_SIZE as f64;
const ICON_HALF_EXTENT: f64 = HALF_GRID_SIZE as f64;
let visibility_offset = node_top_left + DVec2::new(width as f64, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + visibility_offset,
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + visibility_offset,
[3.; 4],
);
let visibility_click_target = ClickTarget::new_with_path(path, 0.);
// Update lock button click target, positioned one grid unit to the left of the visibility button (only when locked)
let lock_click_target = if locked {
let lock_offset = node_top_left + DVec2::new(width as f64 - GRID_SIZE as f64, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + lock_offset,
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + lock_offset,
[3.; 4],
);
Some(ClickTarget::new_with_path(path, 0.))
} else {
None
};
// The grip sits to the left of the leftmost icon, 8px wide but spanning the full layer-vertical-center band
const GRIP_WIDTH: f64 = 8.;
let icons_width = if locked { GRID_SIZE as f64 } else { 0. };
let grip_offset_right_edge = node_top_left + DVec2::new(width as f64 - ICON_HALF_EXTENT - icons_width, LAYER_VERTICAL_CENTER);
let path = rounded_rectangle_path(
DVec2::new(-GRIP_WIDTH, -ICON_HALF_EXTENT) + grip_offset_right_edge,
DVec2::new(0., ICON_HALF_EXTENT) + grip_offset_right_edge,
[0.; 4],
);
let grip_click_target = ClickTarget::new_with_path(path, 0.);
// The double-click rename target is sized to the text bounds, not the surrounding `.details` area,
// so the rest of the layer still drills into the subgraph on double-click
/// `.layer` margin-left (= 12), for chain layers the negative margin-left and positive padding-left cancel out, keeping content at this same offset
const LAYER_LEFT_MARGIN: f64 = HALF_GRID_SIZE as f64;
/// `.thumbnail` (70px) + its 1px side margins (= 72)
const THUMBNAIL_BLOCK_WIDTH: f64 = 3. * GRID_SIZE as f64;
/// `.details` margin-left
const DETAILS_LEFT_MARGIN: f64 = 8.;
const NAME_LEFT_OFFSET: f64 = LAYER_LEFT_MARGIN + THUMBNAIL_BLOCK_WIDTH + DETAILS_LEFT_MARGIN;
/// Distance from layer's right edge to visibility's left edge (= 12)
const VISIBILITY_INSET_FROM_LAYER_RIGHT: f64 = HALF_GRID_SIZE as f64;
const FONT_SIZE: f64 = 14.;
let display_name = self.display_name(node_id, network_path);
let name_click_target = if display_name.is_empty() {
None
} else {
let name_left = node_top_left.x + NAME_LEFT_OFFSET;
let icons_reserve = VISIBILITY_INSET_FROM_LAYER_RIGHT + icons_width + GRIP_WIDTH;
let name_right_max = node_top_left.x + width as f64 - icons_reserve;
let name_width = text_width(&display_name, FONT_SIZE);
let name_right = (name_left + name_width).min(name_right_max);
if name_right > name_left {
// The 1-grid-tall name strip is centered vertically in the 2-grid-tall layer.
let name_top = node_top_left.y + HALF_GRID_SIZE as f64;
let name_bottom = node_top_left.y + GRID_SIZE as f64 + HALF_GRID_SIZE as f64;
let path = rounded_rectangle_path(DVec2::new(name_left, name_top), DVec2::new(name_right, name_bottom), [3.; 4]);
Some(ClickTarget::new_with_path(path, 0.))
} else {
None
}
};
// The layer click target spans the layer and its chain background
let chain_width_grid_spaces = self.chain_width(node_id, network_path);
let node_bottom_right = node_top_left + DVec2::new(width as f64, height as f64);
let chain_top_left = node_top_left - DVec2::new((chain_width_grid_spaces * GRID_SIZE) as f64, 0.);
const CORNER_RADIUS: f64 = 10.;
let path = rounded_rectangle_path(chain_top_left, node_bottom_right, [CORNER_RADIUS; 4]);
let node_click_target = ClickTarget::new_with_path(path, 0.);
DocumentNodeClickTargets {
node_click_target,
port_click_targets,
node_type_metadata: NodeTypeClickTargets::Layer(Box::new(LayerClickTargets {
visibility_click_target,
lock_click_target,
grip_click_target,
name_click_target,
})),
}
};
Some(document_node_click_targets)
}
/// The areas covered by the names beside each import and export port, which can be dragged to reorder them or right-clicked for a menu.
/// Laid out as the frontend draws them, just past the connector.
pub fn import_export_name_bounds(&self, network_path: &[NodeId]) -> Vec<(ImportOrExport, [DVec2; 2])> {
@@ -152,9 +339,9 @@ impl NodeNetworkInterface {
Some((1..row_count).find(|&row| first_row_center + import_export_row_offset(row) > y).unwrap_or(row_count))
}
/// The width of a layer in grid units, which covers its thumbnail, its name and its icons, and the width of its name. Cached
/// The width of a layer in grid units, which covers its thumbnail, its name and its icons. Cached
/// because measuring the name's text is slow.
pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> (u32, f64) {
pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> u32 {
const GAP_WIDTH: f64 = 8.;
const FONT_SIZE: f64 = 14.;
let left_thumbnail_padding = GRID_SIZE as f64 / 2.;
@@ -169,7 +356,7 @@ impl NodeNetworkInterface {
let icon_overhang_width = GRID_SIZE as f64 / 2.;
let layer_width_pixels = left_thumbnail_padding + thumbnail_width + GAP_WIDTH + text_width + grip_padding + grip_width + lock_icon_width + icon_overhang_width;
(((layer_width_pixels / 24.).ceil() as u32).max(8), text_width)
((layer_width_pixels / 24.).ceil() as u32).max(8)
}
pub fn import_export_position(&self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> {
let Some(all_nodes_bounding_box) = self.all_nodes_bounding_box(network_path) else {
@@ -48,24 +48,6 @@ impl NodeNetworkInterface {
Some(&mut navigation.node_graph_ptz)
}
/// The first of the node's parts, its body last, that `find` picks something from. Each part is given in node graph space where the node sits in its
/// grid cell, and an input by its index rather than the row a node draws it in.
pub(crate) fn find_node_part<R>(&self, node_id: &NodeId, network_path: &[NodeId], mut find: impl FnMut(Part, &PartTarget) -> Option<R>) -> Option<R> {
let rows_are_inputs = self.is_layer(node_id, network_path) || self.is_redirect_dot(node_id, network_path);
let inputs = &self.document_node(node_id, network_path)?.inputs;
self.with_layout(network_path, |layout| {
layout.find_part(node_id, |target| {
let part = match target.part {
Part::Input(row) if !rows_are_inputs => Part::Input(input_in_row(inputs, row as usize)? as u32),
part => part,
};
find(part, target)
})
})
.flatten()
}
/// The node drawn topmost at `click`, in viewport space. Only the nodes whose reach covers it build their exact click targets.
pub fn node_from_click(&self, click: DVec2, network_path: &[NodeId]) -> Option<NodeId> {
let Some(network_metadata) = self.network_metadata(network_path) else {
@@ -76,13 +58,16 @@ impl NodeNetworkInterface {
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
// Each node is pressed where it's drawn, even while gliding into its grid cell
let glide_offsets = self.glide_offsets(network_path);
let reaching = self.nodes_reaching(point, network_path);
let clicked_nodes = self.with_layout(network_path, |layout| {
reaching
.into_iter()
.filter(|node_id| layout.body(node_id).is_some_and(|body| body.contains(point - glide_offsets.node(node_id))))
.collect::<Vec<_>>()
})?;
let clicked_nodes = self
.nodes_reaching(point, network_path)
.iter()
.filter(|node_id| {
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
transient_node_metadata.node_click_target.intersect_point_no_stroke(point - glide_offsets.node(node_id))
}) == Some(true)
})
.cloned()
.collect::<Vec<_>>();
// Redirect dots are drawn above nodes, which are drawn above layer chains, so the topmost clicked one is found in that order
let drawing_layer = |node_id: &NodeId| {
if self.is_redirect_dot(node_id, network_path) {
@@ -105,18 +90,25 @@ impl NodeNetworkInterface {
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
let glide_offsets = self.glide_offsets(network_path);
let wanted = match click_target_type {
LayerClickTargetTypes::Visibility => Part::Visibility,
LayerClickTargetTypes::Lock => Part::Lock,
LayerClickTargetTypes::Grip => Part::Grip,
LayerClickTargetTypes::Name => Part::Name,
};
self.nodes_reaching(point, network_path).into_iter().find(|node_id| {
let point = point - glide_offsets.node(node_id);
self.find_node_part(node_id, network_path, |part, target| (part == wanted && target.contains(point)).then_some(()))
.is_some()
})
self.nodes_reaching(point, network_path)
.iter()
.filter_map(|node_id| {
let point = point - glide_offsets.node(node_id);
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
if let NodeTypeClickTargets::Layer(layer) = &transient_node_metadata.node_type_metadata {
match click_target_type {
LayerClickTargetTypes::Visibility => layer.visibility_click_target.intersect_point_no_stroke(point).then_some(*node_id),
LayerClickTargetTypes::Lock => layer.lock_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)),
LayerClickTargetTypes::Grip => layer.grip_click_target.intersect_point_no_stroke(point).then_some(*node_id),
LayerClickTargetTypes::Name => layer.name_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)),
}
} else {
None
}
})
.flatten()
})
.next()
}
/// The dimmed connector for adding an import (or else export) under `point`, given in node graph space, as the index it adds with its center.
@@ -202,11 +194,13 @@ impl NodeNetworkInterface {
.iter()
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
.filter_map(|node_id| {
let point = point - glide_offsets.node(node_id);
self.find_node_part(node_id, network_path, |part, target| match part {
Part::Input(index) if target.contains(point) => Some(InputConnector::node_at_index(*node_id, index as usize)),
_ => None,
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
transient_node_metadata
.port_click_targets
.clicked_input_port_from_point(point - glide_offsets.node(node_id))
.map(|port| InputConnector::node_at_index(*node_id, port))
})
.flatten()
})
.find(|input_connector| !self.is_wired_dot_input(input_connector, network_path))
.or_else(|| {
@@ -233,11 +227,13 @@ impl NodeNetworkInterface {
.iter()
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
.filter_map(|node_id| {
let point = point - glide_offsets.node(node_id);
self.find_node_part(node_id, network_path, |part, target| match part {
Part::Output(index) if target.contains(point) => Some(OutputConnector::node(*node_id, index as usize)),
_ => None,
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
transient_node_metadata
.port_click_targets
.clicked_output_port_from_point(point - glide_offsets.node(node_id))
.map(|output_index| OutputConnector::node(*node_id, output_index))
})
.flatten()
})
.next()
.or_else(|| {
@@ -355,17 +351,3 @@ impl NodeNetworkInterface {
(layer_widths, chain_widths, has_left_input_wire)
}
}
/// The input drawn in `row` of a node, where the primary input's row is drawn even while it has no port.
fn input_in_row(inputs: &[NodeInput], row: usize) -> Option<usize> {
let mut current_row = 0;
for (index, input) in inputs.iter().enumerate() {
if input.is_exposed() && current_row == row {
return Some(index);
}
if index == 0 || input.is_exposed() {
current_row += 1;
}
}
None
}
@@ -6,6 +6,10 @@
use super::*;
impl NodeNetworkInterface {
pub(crate) fn invalidate_positions(&mut self, network_path: &[NodeId]) {
self.unload_all_nodes_bounding_box(network_path);
}
/// Unloads the network's import and export ports.
pub(crate) fn invalidate_import_export(&mut self, network_path: &[NodeId]) {
self.unload_import_export_ports(network_path);
@@ -13,5 +17,6 @@ impl NodeNetworkInterface {
pub(crate) fn invalidate_node_appearance(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
self.try_unload_layer_width(node_id, network_path);
self.unload_all_nodes_bounding_box(network_path);
}
}
@@ -52,6 +52,7 @@ impl NodeNetworkInterface {
}
self.transaction_modified();
self.invalidate_positions(network_path);
}
/// Converts every node another node reads in all networks, whether absolute, chained, or stacked, to a position relative to the left of its readers, level with the highest.
@@ -144,6 +145,7 @@ impl NodeNetworkInterface {
}
self.transaction_modified();
self.invalidate_positions(network_path);
}
/// Sets the position of a layer to a stack position
@@ -157,6 +159,8 @@ impl NodeNetworkInterface {
} else if node.set_stack_position(y_offset) {
self.transaction_modified();
}
self.invalidate_positions(network_path);
}
/// Sets the position of a node to a stack position without changing its y offset
@@ -367,6 +371,7 @@ impl NodeNetworkInterface {
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { return };
if node.shift_absolute_position(position - current_position) {
self.transaction_modified();
self.invalidate_positions(network_path);
}
}
@@ -1,9 +1,7 @@
use super::node_parts::{NodeShape, PartTarget, PlacedNode};
use super::*;
use glam::UVec2;
use graph_layout::{Drag, Graph, Layout, Node, NodeIndex, NodeKind, Placement, Wire};
use std::cell::RefCell;
use std::sync::atomic::{AtomicU64, Ordering};
const REACH_MARGIN: f64 = 16.;
@@ -11,53 +9,13 @@ const REACH_MARGIN: f64 = 16.;
#[derive(Debug, Clone)]
pub struct NetworkLayout {
revision: u64,
generation: u64,
node_ids: Vec<NodeId>,
indices: HashMap<NodeId, NodeIndex>,
graph: Graph,
shapes: Vec<NodeShape>,
layout: Layout,
bounds: [DVec2; 2],
clearance: ImportExportClearance,
}
/// Counts every layout made, so whatever is derived from one can tell when it was replaced, even without a new revision.
static LAYOUT_GENERATIONS: AtomicU64 = AtomicU64::new(0);
impl NetworkLayout {
fn new(revision: u64, laid_out: LaidOutNodes, graph: Graph, layout: Layout) -> Self {
let LaidOutNodes { node_ids, indices, shapes } = laid_out;
let mut network_layout = Self {
revision,
generation: LAYOUT_GENERATIONS.fetch_add(1, Ordering::Relaxed),
node_ids,
indices,
graph,
shapes,
layout,
bounds: [DVec2::ZERO; 2],
clearance: ImportExportClearance::default(),
};
network_layout.measure_bounds_and_clearance();
network_layout
}
fn into_parts(self) -> (LaidOutNodes, Graph, Layout) {
let Self {
node_ids,
indices,
shapes,
graph,
layout,
..
} = self;
(LaidOutNodes { node_ids, indices, shapes }, graph, layout)
}
pub fn generation(&self) -> u64 {
self.generation
}
pub fn position(&self, node_id: &NodeId) -> Option<IVec2> {
Some(self.node(node_id)?.position)
}
@@ -95,33 +53,6 @@ impl NetworkLayout {
self.node(layer).map_or(0, |node| node.chain_length)
}
/// The combined bounds of every node's body in node graph space, or a point at the origin for an empty network.
pub fn bounds(&self) -> [DVec2; 2] {
self.bounds
}
/// What the imports and exports keep their distance from horizontally.
pub(crate) fn clearance(&self) -> ImportExportClearance {
self.clearance
}
/// The node's body where it sits in its grid cell, in node graph space.
pub fn body(&self, node_id: &NodeId) -> Option<PartTarget> {
Some(self.placed(*self.indices.get(node_id)?).body())
}
/// The first of the node's parts, its body last, that `find` picks something from.
pub fn find_part<R>(&self, node_id: &NodeId, mut find: impl FnMut(&PartTarget) -> Option<R>) -> Option<R> {
let placed = self.placed(*self.indices.get(node_id)?);
let mut found = None;
placed.parts(|target| {
if found.is_none() {
found = find(&target);
}
});
found
}
/// Whether `point`, in node graph space, lies within the box around everything the node draws.
pub fn reaches(&self, node_id: &NodeId, point: DVec2) -> bool {
let Some(index) = self.indices.get(node_id) else { return false };
@@ -131,38 +62,6 @@ impl NetworkLayout {
point.cmpge(min).all() && point.cmplt(max).all()
}
fn placed(&self, index: NodeIndex) -> PlacedNode<'_> {
let node_layout = self.layout.node(index);
PlacedNode {
node: &self.graph[index],
shape: &self.shapes[index.index()],
position: node_layout.position,
chain_length: node_layout.chain_length,
}
}
/// Measures the combined bounds of the node bodies, and the horizontal extents the imports and exports keep clear of, with redirect dots measured by their centers.
fn measure_bounds_and_clearance(&mut self) {
let widen = |span: Option<[f64; 2]>, left: f64, right: f64| Some(span.map_or([left, right], |[min, max]| [min.min(left), max.max(right)]));
let mut bounds: Option<[DVec2; 2]> = None;
let mut clearance = ImportExportClearance::default();
for index in (0..self.graph.nodes.len()).map(|index| NodeIndex::from(index as u32)) {
let body = self.placed(index).body();
bounds = Some(bounds.map_or([body.min, body.max], |[min, max]| [min.min(body.min), max.max(body.max)]));
if self.graph[index].kind == NodeKind::Waypoint {
let center = (body.min.x + body.max.x) / 2.;
clearance.dot_centers = widen(clearance.dot_centers, center, center);
} else {
clearance.node_sides = widen(clearance.node_sides, body.min.x, body.max.x);
}
}
self.bounds = bounds.unwrap_or_default();
self.clearance = clearance;
}
fn node(&self, node_id: &NodeId) -> Option<graph_layout::NodeLayout> {
Some(self.layout.node(*self.indices.get(node_id)?))
}
@@ -187,14 +86,12 @@ struct DragOrigin {
keep_upstream: bool,
node_ids: Vec<NodeId>,
indices: HashMap<NodeId, NodeIndex>,
shapes: Vec<NodeShape>,
start: Graph,
drag: Drag,
}
impl DragOrigin {
fn new(laid_out: LaidOutNodes, start: Graph, start_layout: Layout, dragged: &[NodeId], keep_upstream: bool, revision: u64) -> Self {
let LaidOutNodes { node_ids, indices, shapes } = laid_out;
fn new(node_ids: Vec<NodeId>, indices: HashMap<NodeId, NodeIndex>, start: Graph, start_layout: Layout, dragged: &[NodeId], keep_upstream: bool, revision: u64) -> Self {
let dragged = dragged.iter().filter_map(|node_id| indices.get(node_id).copied()).collect();
Self {
revision,
@@ -202,7 +99,6 @@ impl DragOrigin {
drag: Drag::new(start.clone(), start_layout, dragged, keep_upstream),
node_ids,
indices,
shapes,
start,
}
}
@@ -258,6 +154,7 @@ impl NodeNetworkInterface {
}
}
transient.layout.unload();
self.invalidate_positions(network_path);
}
/// Moves the selected nodes `offset` grid cells from where they are drawn, the same way as a drag.
@@ -281,14 +178,9 @@ impl NodeNetworkInterface {
.filter(|((before, after), _)| before.placement != after.placement)
.map(|((_, after), node_id)| (*node_id, after.placement))
.collect();
let laid_out = LaidOutNodes {
node_ids: std::mem::take(&mut origin.node_ids),
indices: std::mem::take(&mut origin.indices),
shapes: std::mem::take(&mut origin.shapes),
};
(moved_placements, laid_out, moved)
(moved_placements, std::mem::take(&mut origin.node_ids), std::mem::take(&mut origin.indices), moved)
});
let Some((moved_placements, laid_out, graph)) = finished else { return };
let Some((moved_placements, node_ids, indices, graph)) = finished else { return };
let mut stored_all = true;
for (node_id, placement) in moved_placements {
@@ -297,7 +189,13 @@ impl NodeNetworkInterface {
if stored_all && let Some(network_metadata) = self.network_metadata(network_path) {
let layout = Layout::new(&graph);
network_metadata.transient_metadata.layout.store(NetworkLayout::new(store::revision(), laid_out, graph, layout));
network_metadata.transient_metadata.layout.store(NetworkLayout {
revision: store::revision(),
layout,
graph,
node_ids,
indices,
});
}
}
@@ -310,15 +208,16 @@ impl NodeNetworkInterface {
let transient = self.network_transient_mut(network_path)?;
let drag = transient.drag.take()?;
transient.layout.unload();
self.invalidate_positions(network_path);
Some(drag)
}
fn with_drag_origin<R>(&self, drag: &DragPreview, network_path: &[NodeId], revision: u64, read: impl FnOnce(&mut DragOrigin) -> R) -> Option<R> {
let mut origin = drag.origin.borrow_mut();
if origin.as_ref().is_none_or(|origin| (origin.revision, origin.keep_upstream) != (revision, drag.keep_upstream)) {
let (laid_out, start) = self.layout_graph(network_path)?;
let (node_ids, indices, start) = self.layout_graph(network_path)?;
let start_layout = Layout::new(&start);
*origin = Some(DragOrigin::new(laid_out, start, start_layout, &drag.dragged, drag.keep_upstream, revision));
*origin = Some(DragOrigin::new(node_ids, indices, start, start_layout, &drag.dragged, drag.keep_upstream, revision));
}
origin.as_mut().map(read)
}
@@ -328,8 +227,8 @@ impl NodeNetworkInterface {
let cache = &self.network_metadata(network_path)?.transient_metadata.layout;
let cached = cache.with_loaded(|cached| (cached.revision == revision).then(|| cached.clone())).flatten()?;
let (laid_out, graph, layout) = cached.into_parts();
Some(DragOrigin::new(laid_out, graph, layout, dragged, keep_upstream, revision))
let NetworkLayout { node_ids, indices, graph, layout, .. } = cached;
Some(DragOrigin::new(node_ids, indices, graph, layout, dragged, keep_upstream, revision))
}
fn store_placement(&mut self, node_id: &NodeId, placement: Placement, network_path: &[NodeId]) -> bool {
@@ -347,38 +246,40 @@ impl NodeNetworkInterface {
};
if node.set_node_type(node_type) {
self.transaction_modified();
self.invalidate_positions(network_path);
}
true
}
fn lay_out(&self, network_path: &[NodeId], revision: u64) -> Option<NetworkLayout> {
let (laid_out, graph, layout) = match &self.network_metadata(network_path)?.transient_metadata.drag {
let (node_ids, indices, graph, layout) = match &self.network_metadata(network_path)?.transient_metadata.drag {
Some(drag) => self.with_drag_origin(drag, network_path, revision, |origin| {
let (graph, mut layout) = origin.drag.moved(drag.offset);
layout.snap_chains(&graph);
let laid_out = LaidOutNodes {
node_ids: origin.node_ids.clone(),
indices: origin.indices.clone(),
shapes: origin.shapes.clone(),
};
(laid_out, graph, layout)
(origin.node_ids.clone(), origin.indices.clone(), graph, layout)
})?,
None => {
let (laid_out, graph) = self.layout_graph(network_path)?;
let (node_ids, indices, graph) = self.layout_graph(network_path)?;
let layout = Layout::new(&graph);
(laid_out, graph, layout)
(node_ids, indices, graph, layout)
}
};
Some(NetworkLayout::new(revision, laid_out, graph, layout))
Some(NetworkLayout {
revision,
layout,
graph,
node_ids,
indices,
})
}
pub(crate) fn layout_graph(&self, network_path: &[NodeId]) -> Option<(LaidOutNodes, Graph)> {
pub(crate) fn layout_graph(&self, network_path: &[NodeId]) -> Option<(Vec<NodeId>, HashMap<NodeId, NodeIndex>, Graph)> {
let network = self.nested_network(network_path)?;
let node_ids: Vec<NodeId> = network.nodes.keys().copied().collect();
let indices: HashMap<NodeId, NodeIndex> = node_ids.iter().enumerate().map(|(index, node_id)| (*node_id, NodeIndex::from(index as u32))).collect();
let (nodes, shapes) = node_ids.iter().map(|node_id| self.layout_node(node_id, network_path)).collect::<Option<(Vec<_>, Vec<_>)>>()?;
let nodes = node_ids.iter().map(|node_id| self.layout_node(node_id, network_path)).collect::<Option<Vec<_>>>()?;
let wires = node_ids
.iter()
.enumerate()
@@ -396,10 +297,10 @@ impl NodeNetworkInterface {
})
.collect();
Some((LaidOutNodes { node_ids, indices, shapes }, Graph { nodes, wires }))
Some((node_ids, indices, Graph { nodes, wires }))
}
fn layout_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<(Node, NodeShape)> {
fn layout_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<Node> {
let metadata = self.node_metadata(node_id, network_path)?;
let (placement, is_layer) = match &metadata.persistent_metadata.node_type_metadata {
NodeTypePersistentMetadata::Layer(layer) => match layer.position {
@@ -413,40 +314,17 @@ impl NodeNetworkInterface {
};
let is_redirect_dot = self.is_redirect_dot(node_id, network_path);
let (layer_width, name_width) = if is_layer {
self.layer_width_and_name_width(node_id, network_path).unwrap_or_default()
} else {
(0, 0.)
};
let (kind, size) = match (is_layer, is_redirect_dot) {
(true, _) => (NodeKind::Layer, UVec2::new(layer_width, LAYER_GRID_HEIGHT)),
(true, _) => (NodeKind::Layer, UVec2::new(self.layer_width(node_id, network_path).unwrap_or_default(), LAYER_GRID_HEIGHT)),
(false, true) => (NodeKind::Waypoint, UVec2::new(5, self.node_height(node_id, network_path))),
(false, false) => (NodeKind::Node, UVec2::new(5, self.node_height(node_id, network_path))),
};
let primary_output_hidden = self.hidden_primary_output(node_id, network_path);
let node = Node {
Some(Node {
placement,
kind,
size: size.as_ivec2(),
chainable: !is_redirect_dot && !primary_output_hidden,
chainable: !is_redirect_dot && !self.hidden_primary_output(node_id, network_path),
held: false,
};
let shape = NodeShape {
inputs: self.number_of_displayed_inputs(node_id, network_path) as u32,
outputs: self.number_of_outputs(node_id, network_path) as u32,
primary_input_hidden: self.document_node(node_id, network_path)?.inputs.first().is_some_and(|input| !input.is_exposed()),
primary_output_hidden,
name_width,
locked: self.is_locked(node_id, network_path),
};
Some((node, shape))
})
}
}
/// The nodes of a network in the order the layout indexes them, with what each draws beyond its size in the layout.
pub(crate) struct LaidOutNodes {
pub(crate) node_ids: Vec<NodeId>,
pub(crate) indices: HashMap<NodeId, NodeIndex>,
shapes: Vec<NodeShape>,
}
@@ -94,9 +94,11 @@ impl NodeNetworkInterface {
self.set_to_node_or_layer(&parent_id, &encapsulating_path, false);
}
// Update the outward wires for all nodes in the encapsulating network
// Update the outward wires and bounding box for all nodes in the encapsulating network
if let Some(encapsulating_transient) = self.network_transient_mut(&encapsulating_path) {
encapsulating_transient.outward_wires.unload();
encapsulating_transient.all_nodes_bounding_box.unload();
encapsulating_transient.import_export_clearance.unload();
}
// An export inserted as the first or second output of a node in the document network may have affected the document metadata structure
@@ -139,6 +141,7 @@ impl NodeNetworkInterface {
// Update the metadata for the encapsulating node
self.unload_outward_wires(encapsulating_network_path);
self.unload_all_nodes_bounding_box(encapsulating_network_path);
affects_document_structure |= encapsulating_network_path.is_empty() && inserted_index <= 1;
}
if affects_document_structure {
@@ -176,6 +179,7 @@ impl NodeNetworkInterface {
fn finish_signature_edit(&mut self, parent_id: NodeId, encapsulating_network_path: &[NodeId], network_path: &[NodeId]) {
// Update the metadata for the encapsulating node
self.unload_outward_wires(encapsulating_network_path);
self.unload_all_nodes_bounding_box(encapsulating_network_path);
if !self.is_eligible_to_be_layer(&parent_id, encapsulating_network_path) && self.is_layer(&parent_id, encapsulating_network_path) {
self.set_to_node_or_layer(&parent_id, encapsulating_network_path, false);
}
@@ -568,7 +572,8 @@ impl NodeNetworkInterface {
/// Lightweight version of `set_input` for bulk import operations.
/// Directly sets the input without `is_acyclic` checks, `load_structure`, position conversions,
/// or per-node cache invalidation. Call `load_structure` once after all import wiring is complete.
/// or per-node cache invalidation. Call `load_structure`, `unload_all_nodes_click_targets`, and
/// `unload_all_nodes_bounding_box` once after all import wiring is complete.
pub fn set_input_for_import(&mut self, input_connector: &InputConnector, new_input: NodeInput, network_path: &[NodeId]) {
if matches!(input_connector, InputConnector::Export(_)) && matches!(new_input, NodeInput::Import { .. }) {
log::error!("Cannot connect a network to an export, see https://github.com/GraphiteEditor/Graphite/issues/1762");
@@ -668,6 +673,8 @@ impl NodeNetworkInterface {
(NodeInput::Value { exposed: old_exposed, .. }, NodeInput::Value { exposed: new_exposed, .. }) => match input_connector {
// Exposing or hiding a value input changes the node's port count
InputConnector::Node { node_id, .. } if old_exposed != new_exposed => {
self.unload_all_nodes_bounding_box(network_path);
// A nested network draws its interior ports from the encapsulating node's inputs
if matches!(self.implementation(node_id, network_path), Some(DocumentNodeImplementation::Definition(_))) {
let nested_path = [network_path, &[*node_id]].concat();
@@ -897,6 +904,7 @@ impl NodeNetworkInterface {
self.transaction_modified();
}
self.unload_all_nodes_bounding_box(network_path);
self.unload_outward_wires(network_path);
}
@@ -919,6 +927,7 @@ impl NodeNetworkInterface {
}
self.transaction_modified();
self.unload_all_nodes_bounding_box(network_path);
previous_entry
}
@@ -1083,6 +1092,7 @@ impl NodeNetworkInterface {
outward_wires.retain(|output, _| output.node_id().is_none_or(|node_id| !removed_nodes.contains(&node_id)));
}
self.unload_all_nodes_bounding_box(network_path);
let Some(selected_nodes) = self.selected_nodes_mut(network_path) else {
log::error!("Could not get selected nodes in NodeGraphMessage::DeleteNodes");
return;
@@ -1355,6 +1365,7 @@ impl NodeNetworkInterface {
transient.layer_width.unload();
self.transaction_modified();
self.unload_all_nodes_bounding_box(network_path);
self.invalidate_import_export(network_path);
self.load_structure();
}
@@ -1,231 +0,0 @@
//! The areas of a laid out node that react to the pointer, in node graph pixels. A hit test scans each node's reach, a box around
//! everything the node draws, and builds the exact parts of only the nodes it lands in.
use crate::consts::{GRID_SIZE, HALF_GRID_SIZE};
use glam::{DVec2, IVec2};
use graph_layout::{CHAIN_WIDTH, Node, NodeKind};
const GRID: f64 = GRID_SIZE as f64;
const HALF_GRID: f64 = HALF_GRID_SIZE as f64;
/// How far a port on a node's side reaches outward, away from the node, and inward over it.
const SIDE_PORT_OUTWARD_REACH: f64 = 12.;
const SIDE_PORT_INWARD_REACH: f64 = 8.;
const SIDE_PORT_HALF_HEIGHT: f64 = 12.;
const STACK_PORT_HALF_SIZE: DVec2 = DVec2::new(12., 8.);
/// A waypoint's body also covers the gutters beside it, so a press near it moves it unless it lands on a port.
const WAYPOINT_HALF_SIZE: DVec2 = DVec2::new(15., 8.);
/// A waypoint's wires attach at its center but are grabbed from a round gutter on either side of it.
const WAYPOINT_GUTTER_OFFSET: f64 = 10.;
const WAYPOINT_GUTTER_RADIUS: f64 = 5.;
const GRIP_WIDTH: f64 = 8.;
const NAME_LEFT_OFFSET: f64 = HALF_GRID + 3. * GRID + 8.;
/// What a node draws beyond the size the layout gives it.
#[derive(Clone, Copy, Debug, Default)]
pub struct NodeShape {
/// How many inputs have a port, which doesn't count a hidden primary input.
pub inputs: u32,
pub outputs: u32,
/// Whether a node's primary input has no port, though its row is still drawn.
pub primary_input_hidden: bool,
pub primary_output_hidden: bool,
/// The width of a layer's name in pixels.
pub name_width: f64,
pub locked: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Part {
Body,
/// The input drawn in this grid row of a node, or a layer's stack input at 0 and side input at 1.
Input(u32),
Output(u32),
Visibility,
Lock,
Grip,
Name,
}
/// A rounded rectangle of a node that reacts to the pointer.
#[derive(Clone, Copy, Debug)]
pub struct PartTarget {
pub min: DVec2,
pub max: DVec2,
pub corner_radius: f64,
pub part: Part,
}
impl PartTarget {
fn around(center: DVec2, half_size: DVec2, corner_radius: f64, part: Part) -> Self {
Self {
min: center - half_size,
max: center + half_size,
corner_radius,
part,
}
}
/// A port on the left side of a node, reaching further out than over the node.
fn input_port(center: DVec2, input: u32) -> Self {
Self {
min: center - DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
max: center + DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
corner_radius: 4.,
part: Part::Input(input),
}
}
/// A port on the right side of a node, reaching further out than over the node.
fn output_port(center: DVec2, output: u32) -> Self {
Self {
min: center - DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
max: center + DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
corner_radius: 4.,
part: Part::Output(output),
}
}
/// Whether the rounded rectangle shares any area with the box from `min` to `max`.
pub fn overlaps(&self, min: DVec2, max: DVec2) -> bool {
if !min.cmplt(self.max).all() || !self.min.cmplt(max).all() {
return false;
}
let radius = self.clamped_radius();
let gap = (self.min + radius - max).max(min - (self.max - radius)).max(DVec2::ZERO);
gap == DVec2::ZERO || gap.length_squared() < radius * radius
}
/// Whether `point` is inside the rounded rectangle.
pub fn contains(&self, point: DVec2) -> bool {
if !point.cmpge(self.min).all() || !point.cmplt(self.max).all() {
return false;
}
let radius = self.clamped_radius();
let inner = point.clamp(self.min + radius, self.max - radius);
point.distance_squared(inner) <= radius * radius
}
fn clamped_radius(&self) -> f64 {
self.corner_radius.min((self.max - self.min).min_element() / 2.)
}
}
/// A node as drawn at `position`, in grid cells, with the chain it is drawn beside if it is a layer.
#[derive(Clone, Copy, Debug)]
pub struct PlacedNode<'a> {
pub node: &'a Node,
pub shape: &'a NodeShape,
pub position: IVec2,
pub chain_length: u32,
}
impl PlacedNode<'_> {
/// The body: a layer with its chain span, a node below its top connector strip, or the pill around a waypoint.
pub fn body(&self) -> PartTarget {
let top_left = self.top_left();
let size = self.node.size.as_dvec2() * GRID;
match self.node.kind {
NodeKind::Waypoint => PartTarget::around(top_left + DVec2::new(0., GRID), WAYPOINT_HALF_SIZE, WAYPOINT_HALF_SIZE.y, Part::Body),
NodeKind::Layer => PartTarget {
min: top_left - DVec2::new(self.chain_width(), 0.),
max: top_left + size,
corner_radius: 10.,
part: Part::Body,
},
NodeKind::Node => {
let body_top_left = top_left + DVec2::new(0., HALF_GRID);
PartTarget {
min: body_top_left,
max: body_top_left + size - DVec2::new(0., GRID),
corner_radius: 3.,
part: Part::Body,
}
}
}
}
/// Calls `visit` with each part, the body last.
pub fn parts(&self, mut visit: impl FnMut(PartTarget)) {
match self.node.kind {
NodeKind::Waypoint => self.waypoint_ports(&mut visit),
NodeKind::Layer => self.layer_parts(&mut visit),
NodeKind::Node => self.node_ports(&mut visit),
}
visit(self.body());
}
fn waypoint_ports(&self, visit: &mut impl FnMut(PartTarget)) {
let center = self.top_left() + DVec2::new(0., GRID);
let gutter = |x_offset: f64, part| PartTarget::around(center + DVec2::new(x_offset, 0.), DVec2::splat(WAYPOINT_GUTTER_RADIUS), WAYPOINT_GUTTER_RADIUS, part);
visit(gutter(-WAYPOINT_GUTTER_OFFSET, Part::Input(0)));
visit(gutter(WAYPOINT_GUTTER_OFFSET, Part::Output(0)));
}
fn node_ports(&self, visit: &mut impl FnMut(PartTarget)) {
let top_left = self.top_left();
let width = self.node.size.x as f64 * GRID;
let row_center = |row: u32| GRID * (row as f64 + 1.);
let first_input_row = u32::from(self.shape.primary_input_hidden);
for row in first_input_row..first_input_row + self.shape.inputs {
visit(PartTarget::input_port(top_left + DVec2::new(0., row_center(row)), row));
}
for output in u32::from(self.shape.primary_output_hidden)..self.shape.outputs {
visit(PartTarget::output_port(top_left + DVec2::new(width, row_center(output)), output));
}
}
fn layer_parts(&self, visit: &mut impl FnMut(PartTarget)) {
let top_left = self.top_left();
let size = self.node.size.as_dvec2() * GRID;
visit(PartTarget::around(top_left + DVec2::new(2. * GRID, size.y + 8.), STACK_PORT_HALF_SIZE, 4., Part::Input(0)));
if self.has_side_input() {
visit(PartTarget::input_port(top_left + DVec2::new(0., GRID), 1));
}
visit(PartTarget::around(top_left + DVec2::new(2. * GRID, -8.), STACK_PORT_HALF_SIZE, 4., Part::Output(0)));
let icon_half_size = DVec2::splat(HALF_GRID);
visit(PartTarget::around(top_left + DVec2::new(size.x, GRID), icon_half_size, 3., Part::Visibility));
if self.shape.locked {
visit(PartTarget::around(top_left + DVec2::new(size.x - GRID, GRID), icon_half_size, 3., Part::Lock));
}
let icons_width = if self.shape.locked { GRID } else { 0. };
let grip_right = top_left.x + size.x - HALF_GRID - icons_width;
let handle_top = top_left.y + HALF_GRID;
let handle_bottom = top_left.y + GRID + HALF_GRID;
visit(PartTarget {
min: DVec2::new(grip_right - GRIP_WIDTH, handle_top),
max: DVec2::new(grip_right, handle_bottom),
corner_radius: 0.,
part: Part::Grip,
});
let name_left = top_left.x + NAME_LEFT_OFFSET;
let name_right = (name_left + self.shape.name_width).min(grip_right - GRIP_WIDTH);
if name_right > name_left {
visit(PartTarget {
min: DVec2::new(name_left, handle_top),
max: DVec2::new(name_right, handle_bottom),
corner_radius: 3.,
part: Part::Name,
});
}
}
fn top_left(&self) -> DVec2 {
self.position.as_dvec2() * GRID
}
fn has_side_input(&self) -> bool {
self.shape.inputs > 1
}
fn chain_width(&self) -> f64 {
if self.has_side_input() { (self.chain_length as i32 * CHAIN_WIDTH + 1) as f64 * GRID } else { 0. }
}
}
@@ -14,6 +14,16 @@ pub fn rounded_rectangle_path(corner1: DVec2, corner2: DVec2, radii: [f64; 4]) -
kurbo::RoundedRect::from_rect(rect, kurbo::RoundedRectRadii::new(top_left, top_right, bottom_right, bottom_left)).to_path(DEFAULT_ACCURACY)
}
/// Ellipse inscribed in the box spanning the two opposite corners.
pub fn ellipse_path(corner1: DVec2, corner2: DVec2) -> BezPath {
let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2));
let mut path = kurbo::Ellipse::new(rect.center(), (rect.width() / 2., rect.height() / 2.), 0.).to_path(DEFAULT_ACCURACY);
// Kurbo emits the ellipse as an unclosed 360 degree arc, but hit testing only fills explicitly closed contours
path.close_path();
path
}
/// A copy of a node from a layer's chain, which can be inserted into a chain in this or another document.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ChainNodeCopy {
@@ -277,6 +287,13 @@ pub(crate) fn side_port_bounds(center: DVec2, is_input: bool) -> [DVec2; 2] {
[center - DVec2::new(left_reach, HALF_HEIGHT), center + DVec2::new(right_reach, HALF_HEIGHT)]
}
/// The corners of the click target for a layer's top output or bottom input, which reaches only 8 px toward the connector it faces in a stack.
fn stack_port_bounds(center: DVec2) -> [DVec2; 2] {
const HALF_SIZE: DVec2 = DVec2::new(12., 8.);
[center - HALF_SIZE, center + HALF_SIZE]
}
pub(crate) fn port_click_target([corner1, corner2]: [DVec2; 2]) -> ClickTarget {
const CORNER_RADIUS: f64 = 4.;
@@ -319,15 +336,51 @@ impl Ports {
}
pub(crate) fn insert_input_port_at_center(&mut self, input_index: usize, center: DVec2) {
self.input_ports.push((input_index, port_click_target(side_port_bounds(center, true))));
self.insert_custom_input_port(input_index, port_click_target(side_port_bounds(center, true)));
self.input_anchors.push((input_index, center));
}
pub(crate) fn insert_custom_input_port(&mut self, input_index: usize, click_target: ClickTarget) {
self.input_ports.push((input_index, click_target));
}
pub(crate) fn insert_output_port_at_center(&mut self, output_index: usize, center: DVec2) {
self.output_ports.push((output_index, port_click_target(side_port_bounds(center, false))));
self.insert_custom_output_port(output_index, port_click_target(side_port_bounds(center, false)));
self.output_anchors.push((output_index, center));
}
pub(crate) fn insert_custom_output_port(&mut self, output_index: usize, click_target: ClickTarget) {
self.output_ports.push((output_index, click_target));
}
pub(crate) fn insert_node_input(&mut self, input_index: usize, row_index: usize, node_top_left: DVec2) {
// The center of the click target is always 24 px down from the top left corner of the node
let center = node_top_left + DVec2::new(0., 24. + 24. * row_index as f64);
self.insert_input_port_at_center(input_index, center);
}
pub(crate) fn insert_node_output(&mut self, output_index: usize, node_top_left: DVec2) {
// The center of the click target is always 24 px down from the top left corner of the node
let center = node_top_left + DVec2::new(5. * 24., 24. + 24. * output_index as f64);
self.insert_output_port_at_center(output_index, center);
}
pub(crate) fn insert_layer_input(&mut self, input_index: usize, node_top_left: DVec2) {
// The primary input sits beneath the layer's thumbnail, and the secondary input on its left side
if input_index == 0 {
let center = node_top_left + DVec2::new(2. * 24., 24. * 2. + 8.);
self.insert_custom_input_port(input_index, port_click_target(stack_port_bounds(center)));
} else {
self.insert_input_port_at_center(input_index, node_top_left + DVec2::new(0., 24. * 1.));
}
}
pub(crate) fn insert_layer_output(&mut self, node_top_left: DVec2) {
// The center of the click target is 8 px above the layer, over its thumbnail
let center = node_top_left + DVec2::new(2. * 24., -8.);
self.insert_custom_output_port(0, port_click_target(stack_port_bounds(center)));
}
pub fn clicked_input_port_from_point(&self, point: DVec2) -> Option<usize> {
self.input_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
}
@@ -336,12 +389,37 @@ impl Ports {
self.output_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
}
/// Adds the input and output of a redirect dot. Its wires both attach at its center, but they're grabbed from the gutters on either side of its body.
pub(crate) fn insert_dot_ports(&mut self, center: DVec2) {
const GUTTER_OFFSET: f64 = 10.;
const GUTTER_RADIUS: f64 = 5.;
let gutter = |x_offset: f64| {
let gutter_center = center + DVec2::new(x_offset, 0.);
ClickTarget::new_with_path(ellipse_path(gutter_center - DVec2::splat(GUTTER_RADIUS), gutter_center + DVec2::splat(GUTTER_RADIUS)), 0.)
};
self.insert_custom_input_port(0, gutter(-GUTTER_OFFSET));
self.insert_custom_output_port(0, gutter(GUTTER_OFFSET));
self.input_anchors.push((0, center));
self.output_anchors.push((0, center));
}
pub fn input_port_position(&self, index: usize) -> Option<DVec2> {
self.input_anchors.iter().find(|(port_index, _)| *port_index == index).map(|(_, anchor)| *anchor)
if let Some((_, anchor)) = self.input_anchors.iter().find(|(port_index, _)| *port_index == index) {
return Some(*anchor);
}
self.input_ports
.iter()
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
}
pub fn output_port_position(&self, index: usize) -> Option<DVec2> {
self.output_anchors.iter().find(|(port_index, _)| *port_index == index).map(|(_, anchor)| *anchor)
if let Some((_, anchor)) = self.output_anchors.iter().find(|(port_index, _)| *port_index == index) {
return Some(*anchor);
}
self.output_ports
.iter()
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
}
}
@@ -657,12 +735,16 @@ impl<T> TransientCache<T> {
#[derive(Debug, Default, Clone)]
pub struct NodeNetworkTransientMetadata {
pub selected_nodes: SelectedNodes,
/// Cache for the bounding box around all nodes in node graph space.
pub(crate) all_nodes_bounding_box: TransientCache<[DVec2; 2]>,
/// Cache for what the imports and exports keep their distance from, unloaded along with `all_nodes_bounding_box`.
pub(crate) import_export_clearance: TransientCache<ImportExportClearance>,
/// Cache for all outward wire connections
pub(crate) outward_wires: TransientCache<HashMap<OutputConnector, Vec<InputConnector>>>,
pub(crate) layout: TransientCache<NetworkLayout>,
pub(crate) drag: Option<super::layout_pass::DragPreview>,
/// The import and export connector click targets, with the generation of the layout they were placed by.
pub(crate) import_export_ports: TransientCache<(u64, Ports)>,
/// All export connector click targets
pub(crate) import_export_ports: TransientCache<Ports>,
/// How far whatever is gliding into the place it just moved to is drawn from that place, which hit tests account for.
pub(crate) glide_offsets: std::cell::RefCell<GlideOffsets>,
@@ -1079,8 +1161,40 @@ impl From<LegacyNodePosition> for NodePosition {
/// Cached metadata that should be calculated when creating a node, and should be recalculated when modifying a node property that affects one of the cached fields.
#[derive(Debug, Default, Clone)]
pub struct DocumentNodeTransientMetadata {
/// Width in grid units from the left edge of the layer's thumbnail to its left end, and the measured width of its name, cached since text measurement is slow. Only loaded for layers.
pub(crate) layer_width: TransientCache<(u32, f64)>,
/// Width in grid units from the left edge of the layer's thumbnail to its left end, cached since text measurement is slow. Only loaded for layers.
pub(crate) layer_width: TransientCache<u32>,
}
#[derive(Debug, Clone)]
pub struct DocumentNodeClickTargets {
/// In order to keep the displayed position of the node in sync with the click target, the displayed position of a node is derived from the top left of the click target
/// Ensure node_click_target is kept in sync when modifying a node property that changes its size. Currently this is alias, inputs, is_layer, and metadata
pub node_click_target: ClickTarget,
/// Stores all port click targets in node graph space.
pub port_click_targets: Ports,
// Click targets that are specific to either nodes or layers, which are chosen states for displaying as a left-to-right node or bottom-to-top layer.
pub node_type_metadata: NodeTypeClickTargets,
}
#[derive(Debug, Clone)]
pub enum NodeTypeClickTargets {
Layer(Box<LayerClickTargets>),
Node, // No transient click targets are stored exclusively for nodes
}
/// All fields in TransientLayerMetadata should automatically be updated by using the network interface API
#[derive(Debug, Clone)]
pub struct LayerClickTargets {
/// Cache for all visibility buttons. Should be automatically updated when update_click_target is called
pub visibility_click_target: ClickTarget,
/// Cache for the lock icon button, only present when the layer is locked.
pub lock_click_target: Option<ClickTarget>,
/// Cache for the grip icon, which is next to the visibility button.
pub grip_click_target: ClickTarget,
/// Cache for the layer's display-name text bounds. Used to detect double-click rename and
/// to skip the drill-into-subgraph behavior when the click lands on the name itself.
/// `None` for layers whose display name is empty.
pub name_click_target: Option<ClickTarget>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -1901,8 +1901,13 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
continue;
};
// The noise settings follow the Clip toggle, in the same order as the current inputs after the primary one
// The primary input comes before the Clip toggle where there is one, and the noise settings follow it in the current inputs' order
if let Some(clip_index) = clip_index {
if *clip_index == 1
&& let Some(primary) = old_inputs.first()
{
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), primary.clone(), network_path);
}
for (offset, input) in old_inputs.iter().skip(clip_index + 1).enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1 + offset), input.clone(), network_path);
}
@@ -1914,6 +1919,11 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
if *reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) {
move_mandelbrot_to_old_origin(document, node_id, network_path);
}
// Only a Noise Pattern old enough to have the Clip toggle is surely from before it wrote gamma-encoded grays
if *reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) {
read_noise_through_gamma_correction(document, node_id, network_path);
}
}
// Parameters that historically accepted fractional numbers are now integers (the polygon and star "Sides", the index,
@@ -1986,6 +1996,9 @@ fn fill_square_with_pattern(document: &mut DocumentMessageHandler, pattern_node_
.and_then(|wires| wires.get(&OutputConnector::node(*pattern_node_id, 0)))
.cloned()
.unwrap_or_default();
if downstream_consumers.is_empty() {
return Some(());
}
let was_in_chain = document.network_interface.is_chain(pattern_node_id, network_path);
let template = |identifier| resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier)).map(|definition| definition.default_node_template());
@@ -2087,6 +2100,48 @@ fn move_mandelbrot_to_old_origin(document: &mut DocumentMessageHandler, mandelbr
Some(())
}
/// Keeps an old Noise Pattern's look now that it writes its value as the gray at that gamma-encoded level rather than as linear light,
/// with a Gamma Correction at its default gamma of 2.2 turning the new gray back into about the old one wherever the pattern was read.
fn read_noise_through_gamma_correction(document: &mut DocumentMessageHandler, noise_node_id: &NodeId, network_path: &[NodeId]) -> Option<()> {
let downstream_consumers: Vec<InputConnector> = document
.network_interface
.outward_wires(network_path)
.and_then(|wires| wires.get(&OutputConnector::node(*noise_node_id, 0)))
.cloned()
.unwrap_or_default();
if downstream_consumers.is_empty() {
return Some(());
}
let was_in_chain = document.network_interface.is_chain(noise_node_id, network_path);
let position = document.network_interface.position(noise_node_id, network_path);
let gamma_correction_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::adjustments::gamma_correction::IDENTIFIER))?.default_node_template();
let gamma_correction_id = NodeId::new();
document.network_interface.insert_node(gamma_correction_id, gamma_correction_template, network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(gamma_correction_id, 0), NodeInput::node(*noise_node_id, 0), network_path);
for consumer in &downstream_consumers {
document.network_interface.set_input(consumer, NodeInput::node(gamma_correction_id, 0), network_path);
}
// A disabled pattern passes its primary input through, so its Gamma Correction is disabled too
if !document.network_interface.is_visible(noise_node_id, network_path) {
document.network_interface.set_visibility(&gamma_correction_id, network_path, false);
}
// The Gamma Correction takes the pattern's place, and the pattern moves before it
if was_in_chain {
document.network_interface.force_set_upstream_to_chain(&gamma_correction_id, network_path);
} else if let Some(position) = position {
document.network_interface.set_absolute_position(&gamma_correction_id, position, network_path);
document.network_interface.set_absolute_position(noise_node_id, position + IVec2::new(-7, 0), network_path);
}
Some(())
}
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
let NodeInput::Value { tagged_value, exposed } = input else { return None };
@@ -6411,6 +6466,9 @@ mod tests {
assert_eq!(value(read, 1), Some(TaggedValue::DVec2(DVec2::new(2. / 3., 0.5))));
read = upstream(read, 0).expect("the origin transform should read the pattern");
}
if pattern == noise {
read = upstream(read, 0).expect("the Gamma Correction should read the pattern");
}
assert_eq!(read, pattern);
}
@@ -6424,6 +6482,130 @@ mod tests {
);
}
// Noise Pattern once wrote its value as linear light, so whatever read an old one reads it through a Gamma Correction giving back about the old gray
#[tokio::test]
async fn old_noise_patterns_are_read_through_a_gamma_correction() {
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use crate::test_utils::test_prelude::*;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graphene_std::raster_nodes::adjustments::gamma_correction;
use graphene_std::raster_nodes::std_nodes::noise_pattern;
use graphene_std::transform_nodes::transform;
let proto = |identifier| DefinitionIdentifier::ProtoNode(identifier);
let mut editor = EditorTestUtils::create();
editor.new_document().await;
// Old patterns read by two nodes and the export, in a layer's chain, disabled, and unread, plus a current one in the new look
let read_thrice = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 0).await;
let readers = [
editor.create_node_by_name_at(proto(transform::IDENTIFIER), 10, 0).await,
editor.create_node_by_name_at(proto(transform::IDENTIFIER), 10, 5).await,
];
let chained = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 15, 20).await;
let layer = editor.create_node_by_name_at(DefinitionIdentifier::Network("Merge".into()), 20, 20).await;
let disabled = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 30).await;
let disabled_reader = editor.create_node_by_name_at(proto(transform::IDENTIFIER), 10, 30).await;
let disabled_primary = editor.create_node_by_name_at(proto(transform::IDENTIFIER), -10, 30).await;
let unread = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 40).await;
let unread_clipped = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 45).await;
let current = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 0, 50).await;
let current_reader = editor.create_node_by_name_at(proto(transform::IDENTIFIER), 10, 50).await;
let interface = &mut editor.active_document_mut().network_interface;
for reader in readers {
interface.set_input(&InputConnector::node_at_index(reader, 0), NodeInput::node(read_thrice, 0), &[]);
}
interface.create_wire(&OutputConnector::primary_output(read_thrice), &InputConnector::Export(0), &[]);
interface.set_to_node_or_layer(&layer, &[], true);
interface.create_wire(&OutputConnector::primary_output(chained), &InputConnector::layer_secondary_input(layer), &[]);
interface.set_input(&InputConnector::node_at_index(disabled_reader, 0), NodeInput::node(disabled, 0), &[]);
interface.set_input(&InputConnector::node_at_index(disabled, 0), NodeInput::node(disabled_primary, 0), &[]);
interface.set_visibility(&disabled, &[], false);
interface.set_input(&InputConnector::node_at_index(current_reader, 0), NodeInput::node(current, 0), &[]);
assert!(interface.is_chain(&chained, &[]), "the pattern should be in the layer's chain: fixture is wrong");
// A pattern exported from a subgraph
let subgraph = editor.create_empty_subgraph_at(0, 60).await;
editor.enter_editable_network(subgraph).await;
editor.handle_message(NodeGraphMessage::AddPrimaryExport).await;
let nested = editor.create_node_by_name_at(proto(noise_pattern::IDENTIFIER), 10, 0).await;
editor
.handle_message(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(nested),
input_connector: InputConnector::Export(0),
})
.await;
// Save the old patterns as an older editor did, with their Clip toggle off except on one of the unread ones
let document = editor.active_document_mut();
let old_patterns = [
(read_thrice, vec![], false),
(chained, vec![], false),
(disabled, vec![], false),
(unread, vec![], false),
(unread_clipped, vec![], true),
(nested, vec![subgraph], false),
];
for (node_id, network_path, clip) in old_patterns {
let mut inputs = document.network_interface.document_node(&node_id, &network_path).unwrap().inputs.clone();
inputs.insert(1, NodeInput::value(TaggedValue::Bool(clip), false));
let mut legacy = NodeTemplate { inputs, ..Default::default() };
legacy.normalize_input_metadata();
document.network_interface.replace_inputs(&node_id, &network_path, &mut legacy);
}
let serialized = document.serialize_document();
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
let interface = &opened.network_interface;
let upstream = |connector: InputConnector, network_path: &[NodeId]| interface.upstream_output_connector(&connector, network_path).and_then(|output| output.node_id());
// The Gamma Correction a reader of `pattern` reads instead, at the default gamma and reading the pattern
let gamma_correction_between = |pattern: NodeId, reader: InputConnector, network_path: &[NodeId]| {
let inserted = upstream(reader, network_path).expect("the reader should read a node");
assert_eq!(interface.reference(&inserted, network_path), Some(proto(gamma_correction::IDENTIFIER)));
let node = interface.document_node(&inserted, network_path).unwrap();
assert_eq!(node.input_value(gamma_correction::GammaInput), Some(&TaggedValue::Number(2.2)));
assert_eq!(node.input_value(gamma_correction::InverseInput), Some(&TaggedValue::Bool(false)));
assert_eq!(upstream(InputConnector::node_at_index(inserted, 0), network_path), Some(pattern));
inserted
};
// Every reader of the pattern read three times shares one Gamma Correction, which takes the pattern's place with the pattern before it
let shared = gamma_correction_between(read_thrice, InputConnector::Export(0), &[]);
for reader in readers {
assert_eq!(upstream(InputConnector::node_at_index(reader, 0), &[]), Some(shared));
}
let position = |node_id: NodeId| interface.position(&node_id, &[]).expect("the node should have a position");
assert_eq!(position(read_thrice) + IVec2::new(7, 0), position(shared));
let in_chain = gamma_correction_between(chained, InputConnector::layer_secondary_input(layer), &[]);
assert!(interface.is_chain(&in_chain, &[]) && interface.is_chain(&chained, &[]), "the layer's chain should hold both");
// Only a disabled pattern's Gamma Correction is disabled too, and the pattern keeps the primary input it passes through
let behind_disabled = gamma_correction_between(disabled, InputConnector::node_at_index(disabled_reader, 0), &[]);
assert!(!interface.is_visible(&behind_disabled, &[]) && interface.is_visible(&shared, &[]));
assert_eq!(upstream(InputConnector::node_at_index(disabled, 0), &[]), Some(disabled_primary));
gamma_correction_between(nested, InputConnector::Export(0), &[subgraph]);
assert_eq!(upstream(InputConnector::node_at_index(current_reader, 0), &[]), Some(current));
// Unread patterns gain nothing reading them, clipped or not
let read = |pattern: NodeId| interface.document_network().nodes.values().any(|node| node.inputs.iter().any(|input| input.as_node() == Some(pattern)));
assert!(!read(unread) && !read(unread_clipped));
// Reopening the upgraded document, as restoring an autosave does, inserts no more
let gamma_corrections = |document: &DocumentMessageHandler| {
let implementation = DocumentNodeImplementation::ProtoNode(gamma_correction::IDENTIFIER);
let nodes = document.network_interface.document_network().recursive_nodes();
nodes.filter(|(_, node, _)| node.implementation == implementation).count()
};
assert_eq!(gamma_corrections(&opened), 4);
let reopened = load_legacy_document(opened.serialize_document(), &HashMapResourceStorage::new(), false).expect("the upgraded document should open");
assert_eq!(gamma_corrections(&reopened), 4);
}
// The demo draws its patterns through layers and adjustments, which must all take the generators the patterns now are
#[tokio::test]
async fn marbled_mandelbrot_renders_after_migration() {
-44
View File
@@ -1,44 +0,0 @@
[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
@@ -1,15 +0,0 @@
[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
@@ -1,39 +0,0 @@
// 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
@@ -1,24 +0,0 @@
// 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
@@ -1,126 +0,0 @@
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
@@ -1,349 +0,0 @@
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
@@ -1,47 +0,0 @@
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
@@ -1,105 +0,0 @@
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
@@ -1,146 +0,0 @@
// 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
@@ -1,175 +0,0 @@
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
@@ -1,43 +0,0 @@
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
@@ -1,147 +0,0 @@
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
@@ -1,67 +0,0 @@
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.);
@@ -1,117 +0,0 @@
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
@@ -1,816 +0,0 @@
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
@@ -1,129 +0,0 @@
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
@@ -1,332 +0,0 @@
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
@@ -1,161 +0,0 @@
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
@@ -1,110 +0,0 @@
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
@@ -1,172 +0,0 @@
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
@@ -1,37 +0,0 @@
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
@@ -1,182 +0,0 @@
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
@@ -1,490 +0,0 @@
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));
}
}
@@ -24,7 +24,7 @@ pub fn render_pattern(pattern: &GeneratorPattern, area: [DVec2; 2], width: u32,
let interior_test = setup.has_interior_test() && resolves_in_32_bits(plane_area, plane_texel);
fill_rows(&mut image.data, width as usize, |y, row| {
row.iter_mut().enumerate().for_each(|(x, pixel)| {
*pixel = mandelbrot_gray(setup.sample(setup.plane_point(pixel_center(x, y)), reference.as_ref(), interior_test));
*pixel = pattern_gray(setup.sample(setup.plane_point(pixel_center(x, y)), reference.as_ref(), interior_test));
});
});
}
@@ -60,18 +60,18 @@ pub fn pattern_sampler(pattern: &GeneratorPattern) -> impl Fn(DVec2) -> Color +
};
move |point| match &sampler {
Sampler::Noise(noise) => Color::from_luminance(noise.sample(point)),
Sampler::Mandelbrot(setup) => mandelbrot_gray(setup.sample(setup.plane_point(point), None, false)),
Sampler::Noise(noise) => pattern_gray(noise.sample(point)),
Sampler::Mandelbrot(setup) => pattern_gray(setup.sample(setup.plane_point(point), None, false)),
}
}
/// The Mandelbrot brightness as a gray, gamma-encoded so a Gradient Map takes it as the position along its gradient.
fn mandelbrot_gray(brightness: f32) -> Color {
let value = brightness.clamp(0., 1.);
/// A pattern's value from 0 to 1 as the gray at that gamma-encoded level, so middle values show as middle gray and a Gradient Map takes the value as the position along its gradient.
fn pattern_gray(value: f32) -> Color {
let value = value.clamp(0., 1.);
Color::from_gamma_srgb_channels(value, value, value, 1.)
}
/// Samples a noise pattern's luminance, from 0 to 1, at positions in its space.
/// Samples a noise pattern's value, from 0 to 1, at positions in its space.
struct NoiseSampler {
noise: fastnoise_lite::FastNoiseLite,
white_noise_seed: Option<i32>,
@@ -221,6 +221,18 @@ mod tests {
}
}
#[test]
fn pattern_values_show_as_the_gray_at_that_level() {
for value in [0., 0.25, 0.5, 0.75, 1.] {
let [red, green, blue, alpha] = pattern_gray(value).to_gamma_srgb_channels();
assert!([red, green, blue].iter().all(|channel| (channel - value).abs() < 1e-5) && alpha == 1., "{value} shows as {red}");
}
// Values out of range clamp
assert_eq!(pattern_gray(1.5).to_gamma_srgb_channels()[0], 1.);
assert_eq!(pattern_gray(-0.5).to_gamma_srgb_channels()[0], 0.);
}
#[test]
fn white_noise_is_the_same_wherever_and_however_finely_it_is_sampled() {
let white_noise = |seed| {
@@ -8,10 +8,7 @@ fn vertex(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> {
return vec4<f32>(corner * 2. - 1., 0., 1.);
}
// Clamped to the range the CPU encodes, which takes NaN as 0
fn linear_to_srgb(unclamped: f32) -> f32 {
let linear = select(0., min(unclamped, 1.), unclamped >= 0.);
let low = linear * 12.92;
let high = 1.055 * pow(linear, 1. / 2.4) - 0.055;
return select(high, low, linear <= 0.0031308);
// A value from 0 to 1 written directly as the gray's gamma-encoded level, clamped to the range the CPU encodes, which takes NaN as 0
fn gray_level(unclamped: f32) -> f32 {
return select(0., min(unclamped, 1.), unclamped >= 0.);
}
@@ -17,7 +17,7 @@ fn generate(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
if parameters.domain_warp != 0u {
fnlDomainWarp2D(parameters.noise, &x, &y);
}
let luminance = (fnlGetNoise2D(parameters.noise, x, y) + 1.) * 0.5;
let value = (fnlGetNoise2D(parameters.noise, x, y) + 1.) * 0.5;
return vec4<f32>(vec3<f32>(linear_to_srgb(luminance)), 1.);
return vec4<f32>(vec3<f32>(gray_level(value)), 1.);
}
@@ -21,9 +21,9 @@ fn generate(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
let hash = pcg3d(vec3<u32>(bitcast<vec2<u32>>(cell), bitcast<u32>(parameters.noise.seed)));
// The top 24 bits, which an f32 holds exactly
let luminance = f32(hash.x >> 8u) / 16777216.;
let value = f32(hash.x >> 8u) / 16777216.;
return vec4<f32>(vec3<f32>(linear_to_srgb(luminance)), 1.);
return vec4<f32>(vec3<f32>(gray_level(value)), 1.);
}
// PCG3D from Jarzynski and Olano's "Hash Functions for GPU Rendering", which spreads every input bit across the result
+1 -1
View File
@@ -200,7 +200,7 @@ fn image(
}
/// Generates customizable procedural noise patterns.
#[node_macro::node(category("Raster"), icon("NodeNoisePattern"), version(2))]
#[node_macro::node(category("Raster"), icon("NodeNoisePattern"), version(3))]
#[allow(clippy::too_many_arguments)]
fn noise_pattern(
_: impl Ctx,