Compare commits

...
20 changed files with 3081 additions and 1040 deletions

No files matched your search

@@ -5,19 +5,16 @@ use super::node_inspector::{self, ParameterWidgetsInfo, SliderRange};
use super::utility_types::{FrontendNodeType, InputTypeConstraint};
use crate::messages::frontend::IconName;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::utility_types::network_interface::{
InputMetadata, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, Vec2InputSettings, WidgetOverride,
};
use crate::messages::portfolio::document::utility_types::network_interface::{NodeNetworkInterface, NodeTemplate, NodeTemplateImplementation};
use crate::messages::portfolio::ingest::utility_types::TypeFilter;
use crate::messages::prelude::{DocumentId, FontsMessage, FontsMessageHandler, Message, ResourceMessageHandler, Responses};
use crate::node_graph_executor::NodeGraphExecutor;
use glam::DVec2;
use graph_craft::ProtoNodeIdentifier;
use graph_craft::concrete;
use graph_craft::document::value::*;
use graph_craft::document::*;
use graph_craft::{concrete, list};
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType};
use graphene_std::vector::Vector;
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType};
use graphene_std::*;
use std::collections::{HashMap, VecDeque};
@@ -40,6 +37,11 @@ impl NodeInspectorContext<'_> {
let input_inspector_row = self.network_interface.persistent_input_metadata(node_id, index, self.selection_network_path)?;
let widget_override = input_inspector_row.widget_override.clone()?;
// Older documents store number and Vec2 widget settings this way, but they come from the definition's parameter
if matches!(widget_override.as_str(), "number" | "vec2") {
return None;
}
let Some(widget_override_lambda) = INPUT_OVERRIDES.get(&widget_override) else {
log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override");
return None;
@@ -51,11 +53,11 @@ impl NodeInspectorContext<'_> {
}
/// Input position of the location parameter on the "Artboard" layer template, which follows the two layer-shaped inputs (stack and content) and maps through to the inner Create Artboard proto node.
pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = 2;
pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = graphene_std::subgraphs::artboard::LocationInput::INDEX;
/// Input position of the dimensions parameter on the "Artboard" layer template, which follows the two layer-shaped inputs (stack and content) and maps through to the inner Create Artboard proto node.
pub const ARTBOARD_DIMENSIONS_INPUT_INDEX: usize = 3;
pub const ARTBOARD_DIMENSIONS_INPUT_INDEX: usize = graphene_std::subgraphs::artboard::DimensionsInput::INDEX;
/// Input position of the control path parameter on the "Blend" network node template.
pub const BLEND_PATH_INPUT_INDEX: usize = 4;
pub const BLEND_PATH_INPUT_INDEX: usize = graphene_std::subgraphs::blend::PathInput::INDEX;
/// The key used to access definitions for a network node or proto node.
/// For proto nodes, this is their [`ProtoNodeIdentifier`].
@@ -107,8 +109,7 @@ pub struct DocumentNodeDefinition {
/// Used to create the [`DefinitionIdentifier::Network`] identifier.
pub identifier: &'static str,
/// The definition's position in its lineage. Bump it, with a `network` migration, when a change would load existing instances wrongly.
/// Instances store it next to their reference. Proto-node definitions take theirs from the node macro.
/// The definition's position in its lineage, from `version(N)` on its `#[node]` or `#[graph]`. Instances store it next to their reference.
pub version: u32,
/// The default [`NodeTemplate`] this definition instantiates.
@@ -136,529 +137,9 @@ static DOCUMENT_NODE_TYPES: once_cell::sync::Lazy<HashMap<DefinitionIdentifier,
/// Defines the "signature" or "header file"-like metadata for the document nodes, but not the implementation (which is defined in the node registry).
/// The [`DocumentNode`] is the instance while these [`DocumentNodeDefinition`]s are the "classes" or "blueprints" from which the instances are built.
/// Only the position can be set for protonodes within a definition. The rest of the metadata comes from the node macro in NODE_METADATA
/// A proto node within a definition takes its input and output metadata from the node macro in NODE_METADATA, and its display name too unless the definition gives one.
fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
let custom = vec![
DocumentNodeDefinition {
identifier: "Merge",
version: 1,
category: "Graphic",
icon: Some("NodeMerge"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(NodeId(2), 0)],
nodes: [
// Primary (bottom) input type coercion
NodeTemplate {
inputs: vec![NodeInput::import(generic!(T), 0)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::as_graphic::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -2)),
..Default::default()
},
// Secondary (left) input type coercion
NodeTemplate {
inputs: vec![NodeInput::import(generic!(T), 1)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::into_group::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -1)),
..Default::default()
},
NodeTemplate {
call_argument: generic!(T),
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -2)),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![NodeInput::type_default(list!(Graphic), true), NodeInput::type_default(list!(Graphic), true)],
input_metadata: vec![
("Base", "The stack of layers below this one, which the content is placed above.").into(),
("Content", "The artwork this layer adds to the stack as a single item.").into(),
],
output_names: vec!["Out".to_string()],
output_descriptions: vec!["The stack of layers with this layer's content placed on top.".to_string()],
node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)),
..Default::default()
},
description: Cow::Borrowed("Merges the provided content as a new item in the layer's compositing stack."),
inspector: None,
},
DocumentNodeDefinition {
identifier: "Artboard",
version: 1,
category: "Graphic",
icon: Some("NodeArtboard"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [
NodeTemplate {
call_argument: generic!(T),
implementation: NodeTemplateImplementation::ProtoNode(artboard::create_artboard::IDENTIFIER),
inputs: vec![
NodeInput::import(Type::Fn(concrete!(Context).into(), generic!(T).into()), 1),
NodeInput::import(item!(TaggedValue), 2),
NodeInput::import(item!(TaggedValue), 3),
NodeInput::import(item!(TaggedValue), 4),
NodeInput::import(item!(TaggedValue), 5),
],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -3)),
..Default::default()
},
NodeTemplate {
inputs: vec![
NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(list!(Artboard))), 0),
NodeInput::node(NodeId(0), 0),
],
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -4)),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![
NodeInput::type_default(list!(Artboard), true),
NodeInput::type_default(list!(Graphic), true),
NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false),
NodeInput::value(TaggedValue::DVec2(DVec2::new(1920., 1080.)), false),
NodeInput::value(TaggedValue::Color(Color::WHITE), false),
NodeInput::value(TaggedValue::Bool(true), false),
],
input_metadata: vec![
("Base", "The stack of artboards below this one, which this artboard is placed above.").into(),
("Content", "Graphics to include within the artboard.").into(),
InputMetadata::with_name_description_override(
"Location",
"Coordinate of the top-left corner of the artboard within the document.",
WidgetOverride::Vec2(Vec2InputSettings {
x: "X".to_string(),
y: "Y".to_string(),
unit: " px".to_string(),
is_integer: true,
..Default::default()
}),
),
InputMetadata::with_name_description_override(
"Dimensions",
"Width and height of the artboard within the document.",
WidgetOverride::Vec2(Vec2InputSettings {
x: "W".to_string(),
y: "H".to_string(),
unit: " px".to_string(),
is_integer: true,
..Default::default()
}),
),
InputMetadata::with_name_description_override("Background", "Color of the artboard background.", WidgetOverride::Custom("artboard_background".to_string())),
("Clip", "Whether to cut off the contained content that extends outside the artboard, or keep it visible.").into(),
],
output_names: vec!["Out".to_string()],
output_descriptions: vec!["The stack of artboards with this artboard placed on top.".to_string()],
node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)),
..Default::default()
},
description: Cow::Borrowed("Creates a new Artboard which can be used as a working surface."),
inspector: None,
},
DocumentNodeDefinition {
identifier: "Blend",
version: 1,
category: "Vector: Deform",
icon: Some("NodeBlend"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(NodeId(16), 0)],
nodes: [
// 0: Separate Paths (split the vector into its individual paths)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(vector::separate_paths::IDENTIFIER),
inputs: vec![NodeInput::import(generic!(T), 4)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 0)),
..Default::default()
},
// 1: Count (number of subpaths)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(vector::count::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(0), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 2)),
..Default::default()
},
// 2: Max (clamp subpath count to at least 1 for empty path case)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 2)),
..Default::default()
},
// 3: As Number (the integer count enters the network's decimal math)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER),
inputs: vec![NodeInput::import(item!(i64), 1)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 13)),
..Default::default()
},
// 4: Multiply (total_instances = count × subpath_count)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(2), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 1)),
..Default::default()
},
// 5: Subtract (count - 1, open subpath denominator)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::subtract::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 14)),
..Default::default()
},
// 6: Read Index (current repetition index)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(context::read_index::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::Integer(0), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 7)),
..Default::default()
},
// 7: Divide (index / count)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::divide::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::node(NodeId(17), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 10)),
..Default::default()
},
// 8: Floor (floor(index / count) = subpath index)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(7), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 4)),
..Default::default()
},
// 9: Modulo (index % count = local index within subpath)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::modulo::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Bool(true), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 7)),
..Default::default()
},
// 10: Path Is Closed (check if current subpath is closed)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(vector::path_is_closed::IDENTIFIER),
inputs: vec![NodeInput::import(generic!(T), 4), NodeInput::node(NodeId(8), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 2)),
..Default::default()
},
// 11: Switch (closed → count, open → max(count - 1, 1) as denominator)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::switch::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(10), 0), NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(18), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 12)),
..Default::default()
},
// 12: Divide (local_index / denominator = within-subpath fraction)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::divide::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(9), 0), NodeInput::node(NodeId(11), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 7)),
..Default::default()
},
// 13: Multiply (fraction × 0.9999999999 to avoid overflowing to the next subpath)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::Number(0.9999999999), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 7)),
..Default::default()
},
// 14: Add (subpath_index + clamped fraction = progression)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::add::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(8), 0), NodeInput::node(NodeId(13), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(37, 4)),
..Default::default()
},
// 15: Morph (content, progression, reverse, distribution, path)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(vector::morph::IDENTIFIER),
inputs: vec![
NodeInput::import(generic!(T), 0),
NodeInput::node(NodeId(14), 0),
NodeInput::value(TaggedValue::Bool(false), false),
NodeInput::import(item!(vector::misc::InterpolationDistribution), 3),
NodeInput::import(item!(Vector), 4),
],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(44, 3)),
..Default::default()
},
// 16: Repeat
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(repeat_nodes::repeat::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(15), 0), NodeInput::node(NodeId(4), 0), NodeInput::import(generic!(T), 2)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(51, 0)),
..Default::default()
},
// 17: Max (clamp count to at least 1)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 13)),
..Default::default()
},
// 18: Max (clamp open-path denominator to at least 1 to avoid division by zero when count = 1)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::Number(1.), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 14)),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![
NodeInput::type_default(list!(Vector), true),
NodeInput::value(TaggedValue::Integer(10), false),
NodeInput::value(TaggedValue::Bool(Default::default()), false),
NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false),
NodeInput::type_default(item!(Vector), false),
],
input_metadata: vec![
("Content", "The vector objects to create intermediate shapes between.").into(),
(
"Count",
"The number of shapes spanning from the first object to the last, repeated for each subpath of the control path.",
)
.into(),
("Reverse", "Flip the stacking order of the shapes, so the ones nearest the first object are on top.").into(),
("Distribution", "What changes evenly from one shape to the next, which sets how the intermediate shapes are spaced.").into(),
(
"Path",
"An optional control path with one anchor point per object. Curved segments shape the trajectory of the blend instead of traveling straight.",
)
.into(),
],
output_names: vec!["Out".to_string()],
output_descriptions: vec!["The blended shapes, from the first object to the last.".to_string()],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
description: Cow::Borrowed("Creates a series of intermediate shapes that gradually transition between vector objects, optionally along a control path."),
inspector: None,
},
DocumentNodeDefinition {
identifier: "Origins to Polyline",
version: 1,
category: "Vector: Path",
icon: Some("NodeOriginsToPolyline"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(NodeId(7), 0)],
nodes: [
// 0: Read Vector
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(context::read_vector::IDENTIFIER),
inputs: vec![NodeInput::value(TaggedValue::None, false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 1)),
..Default::default()
},
// 1: Extract Transform
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(transform_nodes::extract_transform::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(0), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 1)),
..Default::default()
},
// 2: Decompose Translation
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(transform_nodes::decompose_translation::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(1), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 1)),
..Default::default()
},
// 3: As Vector (auto-converts the decomposed translation into a single-anchor List<Vector>)
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(vector::as_vector::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(2), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 1)),
..Default::default()
},
// 4: Flatten Vector
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(graphic_nodes::graphic::flatten_vector::IDENTIFIER),
inputs: vec![NodeInput::import(generic!(T), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 0)),
..Default::default()
},
// 5: Map
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(graphic::map::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(4), 0), NodeInput::node(NodeId(3), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(28, 0)),
..Default::default()
},
// 6: Combine Paths
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(vector::combine_paths::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(5), 0)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(35, 0)),
..Default::default()
},
// 7: Points to Polyline
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(vector::points_to_polyline::IDENTIFIER),
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::value(TaggedValue::Bool(false), false)],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(42, 0)),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![NodeInput::type_default(list!(Vector), true)],
input_metadata: vec![("Vector", "The vector objects to connect in order by their origins.").into()],
output_names: vec!["Vector".to_string()],
output_descriptions: vec!["An open polyline with an anchor point at the origin of each object.".to_string()],
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
description: Cow::Borrowed("Connects the origins of vector objects in order with an open polyline, such as to make a control path for the **Blend** and **Morph** nodes."),
inspector: None,
},
DocumentNodeDefinition {
identifier: "Load Image",
version: 1,
category: "Data: I/O",
icon: Some("NodeLoadImage"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [
NodeTemplate {
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::import(item!(String), 1)],
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0)],
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::bytes_to_image::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::String(String::new()), false)],
input_metadata: vec![
("Empty", "Has no effect, since the image is loaded from the URL.").into(),
("URL", "The web address or local asset path of the image to load.").into(),
],
output_names: vec!["Image".to_string()],
output_descriptions: vec!["The loaded image.".to_string()],
..Default::default()
},
description: Cow::Borrowed("Loads an image from a given URL."),
inspector: None,
},
DocumentNodeDefinition {
identifier: "Regex Find",
version: 1,
category: "String: Regex",
icon: Some("NodeRegexFind"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![
// Primary output: the whole match (String)
NodeInput::node(NodeId(1), 0),
// Secondary output: capture groups (List<String>), each item carries `start`/`end`/`name` attributes from `regex_find`
NodeInput::node(NodeId(2), 0),
],
nodes: [
// Node 0: regex_find proto node — returns List<String> of [whole_match, ...capture_groups]
NodeTemplate {
inputs: vec![
NodeInput::import(item!(String), 0),
NodeInput::import(item!(String), 1),
NodeInput::import(item!(i64), 2),
NodeInput::import(item!(bool), 3),
NodeInput::import(item!(bool), 4),
],
implementation: NodeTemplateImplementation::ProtoNode(text_nodes::regex::regex_find::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
..Default::default()
},
// Node 1: item_at_index at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them)
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::item_at_index::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 0)),
..Default::default()
},
// Node 2: remove_at_index at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::remove_at_index::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 2)),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![
NodeInput::value(TaggedValue::String(String::new()), true),
NodeInput::value(TaggedValue::String(String::new()), false),
NodeInput::value(TaggedValue::Integer(0), false),
NodeInput::value(TaggedValue::Bool(false), false),
NodeInput::value(TaggedValue::Bool(false), false),
],
input_metadata: vec![
("String", "The string to search within.").into(),
("Pattern", "The regular expression pattern to search for.").into(),
(
"Match Index",
"Which non-overlapping occurrence of the pattern to return, starting from 0 for the first match. Negative indices count backwards from the last match.",
)
.into(),
("Case Insensitive", "Match letters regardless of case.").into(),
("Multiline", "Make `^` and `$` match the start and end of each line, not just the whole string.").into(),
],
output_names: vec!["Match".to_string(), "Captures".to_string()],
output_descriptions: vec![
"The whole portion of the string matching the pattern, or empty if there is no match.".to_string(),
"The text matched by each capture group in the pattern, in order.".to_string(),
],
..Default::default()
},
description: Cow::Borrowed(
r#"Finds a portion of the string matching a regular expression pattern. With "Match Index" at its default 0, it selects the first non-overlapping occurrence, but others may be selected. Capture groups, if any, are produced as a list in the "Captures" output."#,
),
inspector: None,
},
];
document_node_derive::post_process_nodes(custom)
document_node_derive::derive_definitions()
}
type NodeInspector = HashMap<String, Box<dyn Fn(NodeId, &mut NodeInspectorContext) -> Vec<LayoutGroup> + Send + Sync>>;
@@ -726,91 +207,10 @@ fn static_input_inspector() -> InputInspector {
}),
);
map.insert(
"number".to_string(),
Box::new(|node_id, index, context| {
let mut number_input = NumberInput::default();
if let Some(unit) = context
.network_interface
.input_data(&node_id, index, "unit", context.selection_network_path)
.and_then(|value| value.as_str())
{
number_input = number_input.unit(unit);
}
if let Some(min) = context
.network_interface
.input_data(&node_id, index, "min", context.selection_network_path)
.and_then(|value| value.as_f64())
{
number_input = number_input.min(min);
}
if let Some(max) = context
.network_interface
.input_data(&node_id, index, "max", context.selection_network_path)
.and_then(|value| value.as_f64())
{
number_input = number_input.max(max);
}
if let Some(step) = context
.network_interface
.input_data(&node_id, index, "step", context.selection_network_path)
.and_then(|value| value.as_f64())
{
number_input = number_input.step(step);
}
if let Some(mode) = context.network_interface.input_data(&node_id, index, "mode", context.selection_network_path).map(|value| {
let mode: NumberInputMode = serde_json::from_value(value.clone()).unwrap();
mode
}) {
number_input = number_input.mode(mode);
}
if let Some(range_min) = context
.network_interface
.input_data(&node_id, index, "range_min", context.selection_network_path)
.and_then(|value| value.as_f64())
{
number_input = number_input.range_min(Some(range_min));
}
if let Some(range_max) = context
.network_interface
.input_data(&node_id, index, "range_max", context.selection_network_path)
.and_then(|value| value.as_f64())
{
number_input = number_input.range_max(Some(range_max));
}
if let Some(is_integer) = context
.network_interface
.input_data(&node_id, index, "is_integer", context.selection_network_path)
.and_then(|value| value.as_bool())
{
number_input = number_input.is_integer(is_integer);
}
let blank_assist = context
.network_interface
.input_data(&node_id, index, "blank_assist", context.selection_network_path)
.and_then(|value| value.as_bool())
.unwrap_or_else(|| {
log::error!("Could not get blank assist when displaying number input for node {node_id}, index {index}");
true
});
Ok(vec![LayoutGroup::row(node_inspector::number_widget(
ParameterWidgetsInfo::at_index(node_id, index, blank_assist, context),
number_input,
))])
}),
);
map.insert(
// The custom number input settings are only available on proto nodes
"optional_f64".to_string(),
Box::new(|node_id, index, context| {
let mut number_input = NumberInput::default();
// The field is cloned so the lock is released before building the row below, which locks the node metadata again
if let Some(field) = context
.network_interface
.implementation(&node_id, context.selection_network_path)
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().unwrap().get(proto_node_identifier)?.fields.get(index).cloned())
{
if let Some(field) = context.network_interface.field_metadata(&node_id, index, context.selection_network_path) {
if let Some(unit) = field.unit {
number_input = number_input.unit(unit);
}
@@ -905,57 +305,6 @@ fn static_input_inspector() -> InputInspector {
"type_choice".to_string(),
Box::new(|node_id, index, context| Ok(vec![node_inspector::type_choice_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context))])),
);
map.insert(
"vec2".to_string(),
Box::new(|node_id, index, context| {
let x = context
.network_interface
.input_data(&node_id, index, "x", context.selection_network_path)
.and_then(|value| value.as_str())
.unwrap_or_else(|| {
log::error!("Could not get x for vec2 input");
""
})
.to_string();
let y = context
.network_interface
.input_data(&node_id, index, "y", context.selection_network_path)
.and_then(|value| value.as_str())
.unwrap_or_else(|| {
log::error!("Could not get y for vec2 input");
""
})
.to_string();
let unit = context
.network_interface
.input_data(&node_id, index, "unit", context.selection_network_path)
.and_then(|value| value.as_str())
.unwrap_or_else(|| {
log::error!("Could not get unit for vec2 input");
""
})
.to_string();
let min = context
.network_interface
.input_data(&node_id, index, "min", context.selection_network_path)
.and_then(|value| value.as_f64());
let is_integer = context
.network_interface
.input_data(&node_id, index, "is_integer", context.selection_network_path)
.and_then(|value| value.as_bool())
.unwrap_or_default();
Ok(vec![node_inspector::vec2_widget(
ParameterWidgetsInfo::at_index(node_id, index, true, context),
&x,
&y,
&unit,
min,
is_integer,
false,
)])
}),
);
map.insert(
"noise_inspector_scale".to_string(),
Box::new(|node_id, index, context| {
@@ -1128,6 +477,7 @@ fn static_input_inspector() -> InputInspector {
"Y",
"",
None,
None,
false,
mandelbrot_to_julia.is_some_and(|percent| percent >= 100.),
)])
@@ -1144,6 +494,7 @@ fn static_input_inspector() -> InputInspector {
"Y",
"",
None,
None,
false,
mandelbrot_to_julia.is_some_and(|percent| percent <= 0.),
)])
@@ -1250,6 +601,7 @@ fn static_input_inspector() -> InputInspector {
"Y",
" px",
None,
None,
false,
false,
)])
@@ -1265,6 +617,7 @@ fn static_input_inspector() -> InputInspector {
"H",
"x",
None,
None,
false,
false,
)])
@@ -1385,7 +738,7 @@ fn static_input_inspector() -> InputInspector {
"vec2_uv".to_string(),
Box::new(|node_id, index, context| {
let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, false, false)])
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, None, false, false)])
}),
);
map
@@ -1633,6 +986,18 @@ mod test {
use crate::test_utils::test_prelude::*;
use graph_craft::document::NodeId;
// A `#[graph]` node with an inner node that has no definition is left out of the catalog with only a logged error
#[test]
fn every_registered_graph_has_a_definition() {
// Released before resolving, since building the catalog locks the registry too
let identifiers: Vec<&str> = graphene_std::registry::GRAPH_METADATA.lock().unwrap().iter().map(|graph| graph.identifier).collect();
assert!(!identifiers.is_empty(), "the `#[graph]` nodes in `graphene_std::subgraphs` should be registered");
for identifier in identifiers {
assert!(resolve_network_node_type(identifier).is_some(), "the '{identifier}' graph should have a definition");
}
}
#[test]
fn rasterize_defaults_to_a_1000_px_square_at_full_resolution() {
use glam::{DAffine2, UVec2};
@@ -1773,21 +1138,36 @@ mod test_type_constraints {
#[test]
fn every_definition_default_value_satisfies_its_constraint() {
let mut violations = Vec::new();
for definition in super::DOCUMENT_NODE_TYPES.values() {
let name = &definition.node_template.display_name;
let constraints = InputTypeConstraint::constraints_for_all_inputs(&definition.node_template, name);
// Checks a node's inputs against what its implementations accept, then each node inside it, whose values a subgraph's author writes too
fn check(node_template: &NodeTemplate, name: &str, violations: &mut Vec<String>) {
let constraints = InputTypeConstraint::constraints_for_all_inputs(node_template, name);
for (index, (constraint, input)) in constraints.iter().zip(&definition.node_template.inputs).enumerate() {
for (index, (constraint, input)) in constraints.iter().zip(&node_template.inputs).enumerate() {
if let Some(value) = input.as_value()
&& !constraint.accepts_default_value(&value.ty())
{
violations.push(format!("{name} input {index}: {} does not satisfy {constraint:?}", value.ty()));
}
let takes_nothing = matches!(constraint, InputTypeConstraint::Limited(types) if !types.is_empty() && types.iter().all(|ty| ty == "()"));
if takes_nothing && matches!(input, NodeInput::Node { .. } | NodeInput::Import { .. }) {
violations.push(format!("{name} input {index}: a wire feeds it, but it takes nothing"));
}
}
if let NodeTemplateImplementation::Network(network) = &node_template.implementation {
for (node_id, inner) in &network.nodes {
check(inner, &format!("{name}, node {node_id}"), violations);
}
}
}
assert!(violations.is_empty(), "Default values rejected by their input constraints:\n{}", violations.join("\n"));
let mut violations = Vec::new();
for definition in super::DOCUMENT_NODE_TYPES.values() {
check(&definition.node_template, &definition.node_template.display_name, &mut violations);
}
assert!(violations.is_empty(), "Values rejected by their input constraints:\n{}", violations.join("\n"));
}
#[test]
@@ -1804,7 +1184,7 @@ mod test_type_constraints {
#[test]
fn single_protonode() {
let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_dvec_2::IDENTIFIER).expect("test node to exist");
let node_type = resolve_proto_node_type(test_node_accept_f32_f64_dvec2::IDENTIFIER).expect("test node to exist");
let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name");
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(glam::DVec2)]);
assert!(!constraint[0].satisfies(&concrete!(String)));
@@ -1818,7 +1198,7 @@ mod test_type_constraints {
#[test]
fn single_protonode2() {
let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_string::IDENTIFIER).expect("test node to exist");
let node_type = resolve_proto_node_type(test_node_accept_f32_f64_string::IDENTIFIER).expect("test node to exist");
let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name");
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(String)]);
assert!(!constraint[0].satisfies(&concrete!(glam::DVec2)));
@@ -1827,8 +1207,8 @@ mod test_type_constraints {
#[test]
fn network() {
let atan_definition = resolve_proto_node_type(test_node_accept_f_32_f_64_dvec_2::IDENTIFIER).expect("test node to exist");
let min_definition = resolve_proto_node_type(test_node_accept_f_32_f_64_string::IDENTIFIER).expect("test node to exist");
let atan_definition = resolve_proto_node_type(test_node_accept_f32_f64_dvec2::IDENTIFIER).expect("test node to exist");
let min_definition = resolve_proto_node_type(test_node_accept_f32_f64_string::IDENTIFIER).expect("test node to exist");
let atan_node = atan_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]);
let min_node = min_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]);
let inner_network = NodeNetworkTemplate {
@@ -1,11 +1,17 @@
use super::DocumentNodeDefinition;
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputMetadata, NodeTemplate, NodeTemplateImplementation, WidgetOverride};
use crate::messages::portfolio::document::utility_types::network_interface::{
InputMetadata, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, WidgetOverride,
};
use glam::IVec2;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graphene_std::registry::*;
use graphene_std::*;
use std::collections::{HashMap, HashSet};
pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
/// Generates every definition, from the node macro's metadata for proto nodes and the graph macro's for built-in subgraphs.
pub(super) fn derive_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
let mut definitions_map = HashMap::new();
// Add the protonodes from the macro.
@@ -75,16 +81,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
inputs,
call_argument: input_type.clone(),
implementation: NodeTemplateImplementation::ProtoNode(id.clone()),
// TODO: Store information for input overrides in the node macro
input_metadata: fields
.iter()
.map(|f| match f.widget_override {
RegistryWidgetOverride::None => (f.name, f.description).into(),
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Hidden),
RegistryWidgetOverride::String(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::String(str.to_string())),
RegistryWidgetOverride::Custom(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Custom(str.to_string())),
})
.collect(),
input_metadata: input_metadata(fields),
output_names,
..Default::default()
},
@@ -96,25 +93,242 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
);
}
// Add the hand-written network nodes to the map and add the metadata for their internal protonodes
for mut network_node in custom {
fill_proto_node_metadata(&mut network_node.node_template, &definitions_map);
// Set the reference to the node identifier
if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation {
network_template.reference = Some(network_node.identifier.to_string());
// If it is not a merge node, then set the display name to the identifier/reference
if network_node.identifier != "Merge" {
network_node.node_template.display_name = network_node.identifier.to_string();
}
}
definitions_map.insert(DefinitionIdentifier::Network(network_node.identifier.to_string()), network_node);
}
let graphs = GRAPH_METADATA.lock().unwrap().clone();
add_graph_definitions(graphs, &mut definitions_map);
definitions_map
}
/// Recursively fills each nested proto node's editor metadata from its definition, preserving only the authored position.
/// The name, description, and any widget override of each parameter, for a proto node's fields or a graph's imports.
/// The rest of a parameter's widget settings are read from its field when the Inspector draws it.
fn input_metadata(fields: &[FieldMetadata]) -> Vec<InputMetadata> {
fields
.iter()
.map(|field| {
let (name, description) = (field.name, field.description);
match field.widget_override {
RegistryWidgetOverride::None => (name, description).into(),
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(name, description, WidgetOverride::Hidden),
RegistryWidgetOverride::String(text) => InputMetadata::with_name_description_override(name, description, WidgetOverride::String(text.to_string())),
RegistryWidgetOverride::Custom(key) => InputMetadata::with_name_description_override(name, description, WidgetOverride::Custom(key.to_string())),
}
})
.collect()
}
/// Why a `#[graph]` node has no definition yet, or can't have one.
enum GraphDefinitionError {
/// A node inside it has no definition, which may be another graph not yet added.
MissingNode(String),
/// The graph's wiring is invalid, so it's left out of the catalog.
Invalid(String),
}
/// Adds the nodes defined as subgraphs by `#[graph]`, each once the definitions of the nodes inside it exist.
fn add_graph_definitions(graphs: Vec<GraphMetadata>, definitions_map: &mut HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
// Every graph sharing an identifier is left out, so the catalog doesn't depend on registration order
let mut identifier_counts = HashMap::new();
for graph in &graphs {
*identifier_counts.entry(graph.identifier).or_insert(0) += 1;
}
let mut rejected = HashSet::new();
let mut pending_graphs: Vec<(GraphMetadata, String)> = graphs
.into_iter()
.filter(|graph| {
let taken = identifier_counts[graph.identifier] > 1;
if taken {
log::error!("The '{}' graph has no definition, since another graph has the same identifier", graph.identifier);
rejected.insert(graph.identifier);
}
!taken
})
.map(|graph| (graph, String::new()))
.collect();
loop {
let pending_count = pending_graphs.len();
let mut ready = Vec::new();
pending_graphs.retain_mut(|(graph, missing)| {
// A graph built on a left-out graph is left out too, rather than embedding another definition of that name
let rejected_inner_graph = graph.nodes.iter().find_map(|node| match node.implementation {
GraphNodeImplementation::Graph(identifier) if rejected.contains(identifier) => Some(identifier),
_ => None,
});
if let Some(inner_graph) = rejected_inner_graph {
log::error!("The '{}' graph has no definition, since the '{inner_graph}' graph inside it has none", graph.identifier);
rejected.insert(graph.identifier);
return false;
}
match graph_definition(graph, definitions_map) {
Ok(definition) => {
ready.push(definition);
false
}
Err(GraphDefinitionError::MissingNode(missing_node)) => {
*missing = missing_node;
true
}
Err(GraphDefinitionError::Invalid(reason)) => {
log::error!("The '{}' graph has no definition, since {reason}", graph.identifier);
rejected.insert(graph.identifier);
false
}
}
});
for definition in ready {
let definition = prepare_network_definition(definition, definitions_map);
definitions_map.insert(DefinitionIdentifier::Network(definition.identifier.to_string()), definition);
}
if pending_graphs.is_empty() || pending_graphs.len() == pending_count {
break;
}
}
for (graph, missing_node) in pending_graphs {
log::error!("The '{}' graph has no definition, since the '{missing_node}' node inside it has none", graph.identifier);
}
}
/// Fills a network definition's nested proto node metadata and points its network at the definition.
fn prepare_network_definition(mut network_node: DocumentNodeDefinition, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> DocumentNodeDefinition {
fill_proto_node_metadata(&mut network_node.node_template, definitions_map);
// Set the reference to the node identifier
if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation {
network_template.reference = Some(network_node.identifier.to_string());
// If it is not a merge node, then set the display name to the identifier/reference
if network_node.identifier != "Merge" {
network_node.node_template.display_name = network_node.identifier.to_string();
}
}
network_node
}
/// Builds the catalog definition of a node defined as a subgraph by `#[graph]`.
fn graph_definition(graph: &GraphMetadata, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> Result<DocumentNodeDefinition, GraphDefinitionError> {
let mut nodes = HashMap::new();
for (index, node) in graph.nodes.iter().enumerate() {
// Start from the node's own definition, so each input the graph leaves out matches a new instance of it
let (identifier, name) = match &node.implementation {
GraphNodeImplementation::ProtoNode(identifier) => (DefinitionIdentifier::ProtoNode(identifier.clone()), identifier.as_str().to_string()),
GraphNodeImplementation::Graph(identifier) => (DefinitionIdentifier::Network(identifier.to_string()), identifier.to_string()),
};
let Some(definition) = definitions_map.get(&identifier) else {
return Err(GraphDefinitionError::MissingNode(name));
};
let mut template = definition.default_node_template();
if let Some(call_argument) = &node.call_argument {
template.call_argument = call_argument.clone();
}
template.visible = !node.hidden;
template.locked = node.locked;
template.pinned = node.pinned;
if let Some(display_name) = node.display_name {
template.display_name = display_name.to_string();
}
let position = node.position.map_or(IVec2::ZERO, |(x, y)| IVec2::new(x, y));
template.node_type_metadata = if node.layer {
NodeTypePersistentMetadata::layer(position)
} else {
NodeTypePersistentMetadata::node(position)
};
for (input_index, source) in &node.inputs {
let Some(input) = template.inputs.get_mut(*input_index) else {
return Err(GraphDefinitionError::Invalid(format!("its node {index}, '{name}', has no input {input_index} for it to set")));
};
// An input the compiler fills in can't be set, which the macro already prevents for the graphs it builds
if matches!(input, NodeInput::Scope(_) | NodeInput::Reflection(_)) {
return Err(GraphDefinitionError::Invalid(format!(
"it sets input {input_index} of its node {index}, '{name}', which the compiler fills in"
)));
}
*input = graph_input(source, input);
}
nodes.insert(NodeId(index as u64), template);
}
// Each import starts from its `#[default(...)]` or else its type, as a proto node's parameter does
let inputs = preprocessor::node_inputs(&graph.imports, &NodeIOTypes::empty());
let exports = graph.exports.iter().map(|export| graph_input(&export.source, &NodeInput::value(TaggedValue::None, false))).collect();
Ok(DocumentNodeDefinition {
identifier: graph.identifier,
version: graph.version,
category: graph.category,
icon: graph.icon,
description: Cow::Borrowed(graph.description),
inspector: None,
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate { exports, nodes, ..Default::default() }),
inputs,
input_metadata: input_metadata(&graph.imports),
output_names: graph.exports.iter().map(|export| export.name.to_string()).collect(),
output_descriptions: graph.exports.iter().map(|export| export.description.to_string()).collect(),
node_type_metadata: if graph.layer {
NodeTypePersistentMetadata::layer(IVec2::ZERO)
} else {
NodeTypePersistentMetadata::node(IVec2::ZERO)
},
..Default::default()
},
})
}
/// The input a graph definition writes, where `default` is what the node's own definition starts that input with.
fn graph_input(source: &GraphInputSource, default: &NodeInput) -> NodeInput {
match source {
GraphInputSource::Node { node, output } => NodeInput::node(NodeId(*node as u64), *output),
GraphInputSource::Import { index, ty } => NodeInput::import(ty.clone(), *index),
GraphInputSource::Value { value, exposed } => {
let ty = match default {
NodeInput::Value { tagged_value, .. } => tagged_value.ty(),
NodeInput::Import { import_type, .. } => import_type.clone(),
_ => generic!(T),
};
NodeInput::value(graph_value(value, &ty), exposed.unwrap_or(default.is_exposed()))
}
GraphInputSource::Scope(key) => NodeInput::scope(*key),
GraphInputSource::NodePath => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath),
GraphInputSource::SourceId => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
}
}
/// The type of the elements a wire of this type carries, past any `Item`, `List`, or lazy wrapping.
fn element_type(ty: &Type) -> &Type {
let mut element = ty;
while let Type::Item(inner) | Type::List(inner) | Type::Fn(_, inner) = element {
element = inner;
}
element
}
/// Converts a value written in a graph definition to the type of the input it feeds.
fn graph_value(value: &GraphValue, ty: &Type) -> TaggedValue {
// An integer literal feeds an integer input as an integer, and any other as a number
let is_integer = *element_type(ty) == concrete!(i64);
match value {
GraphValue::Integer(integer) if is_integer => TaggedValue::Integer(*integer),
GraphValue::Integer(integer) => TaggedValue::Number(*integer as f64),
GraphValue::Number(number) => TaggedValue::Number(*number),
GraphValue::Bool(boolean) => TaggedValue::Bool(*boolean),
GraphValue::String(string) => TaggedValue::String(string.clone()),
GraphValue::Vec2(vec2) => TaggedValue::DVec2(*vec2),
GraphValue::Color(color) => TaggedValue::Color(*color),
}
}
/// Recursively gives each nested proto node its definition's input and output metadata, and its display name if the network's author gave none.
fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
match &mut node_template.implementation {
NodeTemplateImplementation::Network(network_template) => {
@@ -128,13 +342,190 @@ fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &
return;
};
// A display name, lock, or pin the network's author gave the node is kept
let definition_template = &definition.node_template;
node_template.display_name = definition_template.display_name.clone();
if node_template.display_name.is_empty() {
node_template.display_name = definition_template.display_name.clone();
}
node_template.input_metadata = definition_template.input_metadata.clone();
node_template.output_names = definition_template.output_names.clone();
node_template.locked = definition_template.locked;
node_template.pinned = definition_template.pinned;
node_template.locked |= definition_template.locked;
node_template.pinned |= definition_template.pinned;
}
NodeTemplateImplementation::Definition(_) => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
fn number_import() -> FieldMetadata {
FieldMetadata {
name: "Value",
description: "",
internal: false,
exposed: true,
widget_override: RegistryWidgetOverride::None,
value_source: RegistryValueSource::None,
default_colors: None,
default_type: Some(Type::Item(Box::new(concrete!(f64)))),
number_soft_min: None,
number_soft_max: None,
number_hard_min: None,
number_hard_max: None,
number_mode_range: false,
number_display_decimal_places: None,
number_step: None,
unit: None,
multiline: false,
progression: false,
constant: false,
labels: None,
integer: false,
blank_assist: true,
}
}
/// A graph exporting one node, which is fed by the given inputs.
fn one_node_graph(identifier: &'static str, implementation: GraphNodeImplementation, inputs: Vec<(usize, GraphInputSource)>) -> GraphMetadata {
GraphMetadata {
identifier,
category: "Test",
icon: None,
description: "",
version: 1,
layer: false,
imports: vec![number_import()],
exports: vec![GraphExportMetadata {
name: "Out",
description: "",
source: GraphInputSource::Node { node: 0, output: 0 },
}],
nodes: vec![GraphNodeMetadata {
implementation,
inputs,
position: None,
layer: false,
display_name: None,
hidden: false,
locked: false,
pinned: false,
call_argument: None,
}],
}
}
fn from_import() -> Vec<(usize, GraphInputSource)> {
let ty = Type::Item(Box::new(concrete!(f64)));
vec![(0, GraphInputSource::Import { index: 0, ty })]
}
/// The definitions a test graph builds on: only the As Number proto node.
fn proto_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
let identifier = DefinitionIdentifier::ProtoNode(math_nodes::as_number::IDENTIFIER);
let definition = resolve_document_node_type(&identifier).expect("As Number should have a definition").clone();
HashMap::from([(identifier, definition)])
}
fn has_graph(definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>, identifier: &str) -> bool {
definitions_map.contains_key(&DefinitionIdentifier::Network(identifier.to_string()))
}
#[test]
fn a_graph_resolves_when_registered_before_a_graph_inside_it() {
let outer = one_node_graph("Test Outer", GraphNodeImplementation::Graph("Test Inner"), from_import());
let inner = one_node_graph("Test Inner", math_nodes::as_number::IDENTIFIER.into(), from_import());
let mut definitions_map = proto_definitions();
add_graph_definitions(vec![outer, inner], &mut definitions_map);
assert!(has_graph(&definitions_map, "Test Inner"));
assert!(has_graph(&definitions_map, "Test Outer"));
}
#[test]
fn a_graph_setting_an_input_its_node_lacks_is_left_out() {
let mut inputs = from_import();
inputs.push((
100,
GraphInputSource::Value {
value: GraphValue::Number(1.),
exposed: None,
},
));
let graph = one_node_graph("Test Missing Input", math_nodes::as_number::IDENTIFIER.into(), inputs);
let mut definitions_map = proto_definitions();
add_graph_definitions(vec![graph], &mut definitions_map);
assert!(!has_graph(&definitions_map, "Test Missing Input"));
}
#[test]
fn graphs_sharing_an_identifier_and_graphs_built_on_them_are_left_out() {
let first = one_node_graph("Test Twin", math_nodes::as_number::IDENTIFIER.into(), from_import());
let second = one_node_graph("Test Twin", math_nodes::as_number::IDENTIFIER.into(), from_import());
let dependent = one_node_graph("Test Dependent", GraphNodeImplementation::Graph("Test Twin"), from_import());
let mut definitions_map = proto_definitions();
add_graph_definitions(vec![first, second, dependent], &mut definitions_map);
assert!(!has_graph(&definitions_map, "Test Twin"));
assert!(!has_graph(&definitions_map, "Test Dependent"));
}
#[test]
fn an_integer_value_takes_the_type_of_the_input_it_feeds() {
let integer = Type::Item(Box::new(concrete!(i64)));
let number = Type::Item(Box::new(concrete!(f64)));
assert!(matches!(graph_value(&GraphValue::Integer(3), &integer), TaggedValue::Integer(3)));
assert!(matches!(graph_value(&GraphValue::Integer(3), &number), TaggedValue::Number(value) if value == 3.));
}
#[test]
fn imports_start_from_their_default_or_type() {
let unit_primary = FieldMetadata {
default_type: Some(concrete!(())),
..number_import()
};
let with_default = FieldMetadata {
value_source: RegistryValueSource::Default("2.5"),
..number_import()
};
let graph = GraphMetadata {
imports: vec![unit_primary, with_default],
..one_node_graph("Test Defaults", math_nodes::as_number::IDENTIFIER.into(), from_import())
};
let mut definitions_map = proto_definitions();
add_graph_definitions(vec![graph], &mut definitions_map);
let inputs = &definitions_map[&DefinitionIdentifier::Network("Test Defaults".to_string())].node_template.inputs;
// A `()` primary has nothing to connect, and an exposed parameter's default is parsed by its type
assert!(!inputs[0].is_exposed());
assert!(matches!(inputs[1].as_value(), Some(TaggedValue::Number(value)) if *value == 2.5));
assert!(inputs[1].is_exposed());
}
#[test]
fn a_graph_nodes_widget_settings_come_from_its_import() {
use crate::messages::prelude::DocumentMessageHandler;
let node_id = NodeId(1);
let mut document = DocumentMessageHandler::default();
let artboard = resolve_document_node_type(&DefinitionIdentifier::Network("Artboard".into())).expect("Artboard should exist");
document.network_interface.insert_node(node_id, artboard.default_node_template(), &[]);
let location = graphene_std::subgraphs::artboard::LocationInput::INDEX;
let field = document
.network_interface
.field_metadata(&node_id, location, &[])
.expect("the location input should have its import's settings");
assert_eq!(field.labels, Some(("X", "Y")));
assert!(field.integer);
assert!(!document.network_interface.is_internal_input(&node_id, location, &[]));
}
}
@@ -238,7 +238,7 @@ pub fn start_widgets(parameter_widgets_info: &ParameterWidgetsInfo) -> Vec<Widge
}
/// The presentation of a parameter's widget, sourced from the node's field metadata: numeric bounds, widget modes, and unit of measure.
#[derive(Clone, Copy, Default)]
#[derive(Clone, Copy)]
pub(crate) struct ParameterOptions {
pub soft_min: Option<f64>,
pub soft_max: Option<f64>,
@@ -250,6 +250,50 @@ pub(crate) struct ParameterOptions {
pub unit: Option<&'static str>,
pub display_decimal_places: Option<u32>,
pub step: Option<f64>,
pub labels: Option<(&'static str, &'static str)>,
pub integer: bool,
pub blank_assist: bool,
}
impl Default for ParameterOptions {
fn default() -> Self {
Self {
soft_min: None,
soft_max: None,
hard_min: None,
hard_max: None,
slider: false,
multiline: false,
progression: false,
unit: None,
display_decimal_places: None,
step: None,
labels: None,
integer: false,
blank_assist: true,
}
}
}
impl ParameterOptions {
/// The options a proto node's field or a graph's import gives its widget.
pub(crate) fn from_field(field: &graphene_std::registry::FieldMetadata) -> Self {
Self {
soft_min: field.number_soft_min,
soft_max: field.number_soft_max,
hard_min: field.number_hard_min,
hard_max: field.number_hard_max,
slider: field.number_mode_range,
multiline: field.multiline,
progression: field.progression,
unit: field.unit,
display_decimal_places: field.number_display_decimal_places,
step: field.number_step,
labels: field.labels,
integer: field.integer,
blank_assist: field.blank_assist,
}
}
}
/// The values a range slider's two ends map to linearly and the one its double-click restores, if known.
@@ -303,9 +347,12 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
unit,
display_decimal_places,
step,
labels,
integer,
blank_assist,
} = options;
let mut number_input = NumberInput::default();
let mut number_input = NumberInput::default().is_integer(integer);
if slider {
number_input = number_input.mode_range();
}
@@ -348,7 +395,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
}
};
let default_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
let default_info = ParameterWidgetsInfo::at_index(node_id, index, blank_assist, context);
// A type with no widget can only be supplied through the graph, labeled with a placeholder row
let unsupported_widgets = |default_info: ParameterWidgetsInfo, type_label: String| {
@@ -392,7 +439,10 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
true => text_area_widget(default_info).into(),
false => text_widget(default_info).into(),
},
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false, false),
Some(x) if id_is::<DVec2>(x) => {
let (x_label, y_label) = labels.unwrap_or(("X", "Y"));
vec2_widget(default_info, x_label, y_label, unit.unwrap_or(""), hard_min, hard_max, integer, false)
}
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
@@ -894,7 +944,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
}
}
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, max: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
let mut widgets = start_widgets(&parameter_widgets_info);
let Some(input) = parameter_widgets_info.input() else {
@@ -909,7 +959,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.label(x)
.unit(unit)
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
.is_integer(is_integer)
.disabled(disabled)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), dvec2.y))))
@@ -920,7 +970,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.label(y)
.unit(unit)
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
.is_integer(is_integer)
.disabled(disabled)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(dvec2.x, input.value.unwrap()))))
@@ -935,7 +985,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.label(x)
.unit(unit)
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
.is_integer(is_integer)
.disabled(disabled)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), value))))
@@ -946,7 +996,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
.label(y)
.unit(unit)
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
.is_integer(is_integer)
.disabled(disabled)
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(value, input.value.unwrap()))))
@@ -2788,10 +2838,10 @@ pub(crate) fn grid_inspector(node_id: NodeId, context: &mut NodeInspectorContext
ParameterWidgetsInfo::new(node_id, SpacingInput, true, context),
NumberInput::default().label("H").min(0.).unit(" px"),
));
let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, false, false);
let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, None, false, false);
widgets.extend([spacing, angles]);
} else {
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), false, false);
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), None, false, false);
widgets.push(spacing);
}
}
@@ -3254,40 +3304,20 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
}
let row = context.call_widget_override(&node_id, input_index).unwrap_or_else(|| {
let field = context.network_interface.field_metadata(&node_id, input_index, context.selection_network_path);
let options = field.as_ref().map(ParameterOptions::from_field).unwrap_or_default();
let Some(implementation) = context.network_interface.implementation(&node_id, context.selection_network_path) else {
log::error!("Could not get implementation for node {node_id}");
return Vec::new();
};
let mut options = ParameterOptions::default();
let input_type = match implementation {
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => 'early_return: {
// Clone to end the `network_interface` borrow held via `implementation`, freeing the mutable borrow `input_type` needs below
let proto_node_identifier = proto_node_identifier.clone();
let mut default_type = None;
if let Some(field) = graphene_std::registry::NODE_METADATA
.lock()
.unwrap()
.get(&proto_node_identifier)
.and_then(|metadata| metadata.fields.get(input_index))
{
options = ParameterOptions {
soft_min: field.number_soft_min,
soft_max: field.number_soft_max,
hard_min: field.number_hard_min,
hard_max: field.number_hard_max,
slider: field.number_mode_range,
multiline: field.multiline,
progression: field.progression,
unit: field.unit,
display_decimal_places: field.number_display_decimal_places,
step: field.number_step,
};
default_type = field.default_type.clone();
}
if let Some(default) = default_type {
if let Some(default) = field.and_then(|field| field.default_type) {
break 'early_return default;
}
@@ -3303,12 +3333,21 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
let Some(input_type) = input_type else { return Vec::new() };
input_type.clone()
}
_ => context
.network_interface
.input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
.compiled_nested_type()
.cloned()
.unwrap_or(concrete!(())),
_ => {
// A graph import's declared type still picks its widget while its wire's type is unresolved, such as during an error inside the subgraph
let declared_type = field.and_then(|field| field.default_type).map(|declared_type| match declared_type {
Type::Item(element) => *element,
declared_type => declared_type,
});
context
.network_interface
.input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
.compiled_nested_type()
.cloned()
.or(declared_type)
.unwrap_or(concrete!(()))
}
};
inspector_row_from_type(node_id, input_index, &input_type, options, context).unwrap_or_else(|value| value)
@@ -57,7 +57,6 @@ use crate::messages::portfolio::document::utility_types::network_interface::reso
use crate::messages::portfolio::document::utility_types::text_metrics::text_width;
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire};
use crate::messages::tool::common_functionality::graph_modification_utils;
use crate::messages::tool::tool_messages::tool_prelude::NumberInputMode;
use deserialization::deserialize_node_persistent_metadata;
use glam::{DAffine2, DVec2, IVec2};
use graph_craft::Type;
@@ -72,7 +71,7 @@ use graphene_std::vector::click_target::{ClickTarget, ClickTargetType, FreePoint
use graphene_std::vector::{Vector, VectorModificationType};
use kurbo::BezPath;
use memo_network::MemoNetwork;
use serde_json::{Value, json};
use serde_json::Value;
use std::collections::{HashMap, HashSet, VecDeque};
use std::hash::Hash;
use std::ops::Deref;
@@ -2614,7 +2614,7 @@ async fn shaking_a_node_spliced_in_by_a_secondary_input_keeps_the_dot_on_its_wir
// Numbers to Vec2 hides its primary input, so it takes the flow by its first exposed input instead
let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
let shaken = editor
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER), 10, 0)
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER), 10, 0)
.await;
let dot = editor.create_node_by_name_at(passthrough_definition(), 20, 0).await;
let consumer = editor.create_node_by_name_at(fill_definition(), 30, 0).await;
@@ -1,9 +1,6 @@
use super::*;
use std::hash::{Hash, Hasher};
/// Index of the Artboard definition's Clip input, which must match the input order authored in document_node_definitions.rs.
pub(crate) const ARTBOARD_CLIP_INPUT_INDEX: usize = 5;
impl NodeNetworkInterface {
/// Runs a query against a resolved [`NetworkView`], logging any error at this message-boundary wrapper and mapping it to None.
pub(crate) fn query<'a, 'p, T>(&'a self, network_path: &'p [NodeId], caller: &str, query: impl FnOnce(NetworkView<'a, 'p>) -> Result<T, NetworkError>) -> Option<T> {
@@ -829,17 +826,27 @@ impl NodeNetworkInterface {
self.view(network_path).ok().and_then(|view| view.persistent_input_metadata(node_id, index).ok())
}
/// Whether the input is internal state of its proto node (named with a leading `_`), which is never exposed to the graph.
/// Whether the input is internal state of its node (named with a leading `_`), which is never exposed to the graph.
pub fn is_internal_input(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> bool {
let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) else {
return false;
};
let Ok(node_metadata) = graphene_std::registry::NODE_METADATA.lock() else { return false };
self.field_metadata(node_id, index, network_path).is_some_and(|field| field.internal)
}
node_metadata
.get(proto_node_identifier)
.and_then(|metadata| metadata.fields.get(index))
.is_some_and(|field| field.internal)
/// The metadata the node macro records for a proto node's parameter, or the `#[graph]` macro for a graph node's import.
/// A graph node's input has it only while it still has that import's name, since an edited subgraph can reorder its imports.
pub fn field_metadata(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> Option<graphene_std::registry::FieldMetadata> {
if let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) {
let node_metadata = graphene_std::registry::NODE_METADATA.lock().ok()?;
return node_metadata.get(proto_node_identifier)?.fields.get(index).cloned();
}
let Some(DefinitionIdentifier::Network(identifier)) = self.reference(node_id, network_path) else {
return None;
};
let input_name = self.persistent_input_metadata(node_id, index, network_path)?.input_name.clone();
let graphs = graphene_std::registry::GRAPH_METADATA.lock().ok()?;
let field = graphs.iter().find(|graph| graph.identifier == identifier)?.imports.get(index)?;
(field.name == input_name).then(|| field.clone())
}
/// The description stored for a node's output, or else for a proto node, the doc comment on its field in the struct a multi-output node returns.
@@ -1079,7 +1086,7 @@ impl NodeNetworkInterface {
/// Whether the artboard layer clips the content inside it to its bounds.
fn artboard_clips_content(&self, artboard: LayerNodeIdentifier) -> bool {
self.document_node(&artboard.to_node(), &[])
.and_then(|artboard| artboard.inputs.get(ARTBOARD_CLIP_INPUT_INDEX))
.and_then(|artboard| artboard.inputs.get(graphene_std::subgraphs::artboard::ClipInput::INDEX))
.is_some_and(|clip_input| matches!(clip_input, NodeInput::Value { tagged_value, .. } if tagged_value.clone().deref() == &TaggedValue::Bool(true)))
}
@@ -867,51 +867,11 @@ impl PartialEq for DocumentNodeMetadata {
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct NumberInputSettings {
pub unit: Option<String>,
pub min: Option<f64>,
pub max: Option<f64>,
pub step: Option<f64>,
pub mode: NumberInputMode,
pub range_min: Option<f64>,
pub range_max: Option<f64>,
pub is_integer: bool,
pub blank_assist: bool,
}
impl Default for NumberInputSettings {
fn default() -> Self {
NumberInputSettings {
unit: None,
min: None,
max: None,
step: None,
mode: NumberInputMode::default(),
range_min: None,
range_max: None,
is_integer: false,
blank_assist: true,
}
}
}
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct Vec2InputSettings {
pub x: String,
pub y: String,
pub unit: String,
pub min: Option<f64>,
pub is_integer: bool,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum WidgetOverride {
None,
Hidden,
String(String),
Number(NumberInputSettings),
Vec2(Vec2InputSettings),
Custom(String),
}
@@ -948,40 +908,6 @@ impl InputPersistentMetadata {
self.input_data.insert("string_inspector".to_string(), Value::String(string_inspector));
self.widget_override = Some("string".to_string());
}
WidgetOverride::Number(mut number_inspector) => {
if let Some(unit) = number_inspector.unit.take() {
self.input_data.insert("unit".to_string(), json!(unit));
}
if let Some(min) = number_inspector.min.take() {
self.input_data.insert("min".to_string(), json!(min));
}
if let Some(max) = number_inspector.max.take() {
self.input_data.insert("max".to_string(), json!(max));
}
if let Some(step) = number_inspector.step.take() {
self.input_data.insert("step".to_string(), json!(step));
}
if let Some(range_min) = number_inspector.range_min.take() {
self.input_data.insert("range_min".to_string(), json!(range_min));
}
if let Some(range_max) = number_inspector.range_max.take() {
self.input_data.insert("range_max".to_string(), json!(range_max));
}
self.input_data.insert("mode".to_string(), json!(number_inspector.mode));
self.input_data.insert("is_integer".to_string(), Value::Bool(number_inspector.is_integer));
self.input_data.insert("blank_assist".to_string(), Value::Bool(number_inspector.blank_assist));
self.widget_override = Some("number".to_string());
}
WidgetOverride::Vec2(vec2_inspector) => {
self.input_data.insert("x".to_string(), json!(vec2_inspector.x));
self.input_data.insert("y".to_string(), json!(vec2_inspector.y));
self.input_data.insert("unit".to_string(), json!(vec2_inspector.unit));
self.input_data.insert("is_integer".to_string(), Value::Bool(vec2_inspector.is_integer));
if let Some(min) = vec2_inspector.min {
self.input_data.insert("min".to_string(), json!(min));
}
self.widget_override = Some("vec2".to_string());
}
WidgetOverride::Custom(lambda_name) => {
self.widget_override = Some(lambda_name);
}
@@ -472,9 +472,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
],
},
// The old 'Vec2 Value' node took separate X and Y inputs, a role now filled by 'Numbers to Vec2', while the new 'Vec2 Value' node takes a single vec2 input.
// Old references (including these older aliases) are remapped here to `vec_2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Numbers to Vec2' node.
// Old references (including these older aliases) are remapped here to `vec2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Numbers to Vec2' node.
NodeReplacement {
node: graphene_std::math_nodes::vec_2_value::IDENTIFIER,
node: graphene_std::math_nodes::vec2_value::IDENTIFIER,
aliases: &[
"graphene_math_nodes::Vec2ValueNode",
"graphene_core::ops::ConstructVector2",
@@ -484,7 +484,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
],
},
NodeReplacement {
node: graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER,
node: graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER,
aliases: &["math_nodes::CombineVec2Node"],
},
// ================================
@@ -1576,8 +1576,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
// A wrapper saved before these gained a hidden primary output had each field one output lower, so its wires shift up by one.
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: replacing the outer network impl orphans its child paths.
let split_wrapper_replacements = [
("Split Vec2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
("Split Vector2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
("Split Vec2", graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER),
("Split Vector2", graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER),
("Split Channels", graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER),
];
for (old_reference, new_identifier) in split_wrapper_replacements {
@@ -1641,7 +1641,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
let DocumentNodeImplementation::ProtoNode(protonode_id) = &node.implementation else { return None };
let name = protonode_id.as_str().split('<').next().unwrap_or_default();
if EXTRACT_XY.contains(&name) {
Some((*node_id, path, graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER, "Extract XY"))
Some((*node_id, path, graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER, "Extract XY"))
} else if EXTRACT_CHANNEL.contains(&name) {
Some((*node_id, path, graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER, "Extract Channel"))
} else {
@@ -2856,8 +2856,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
// Convert the old 'Vec2 Value' node, identified by its leftover 3-input shape with separate X and Y inputs,
// into the 'Numbers to Vec2' node which now fills that role (the new 'Vec2 Value' node instead takes a single vec2 input)
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::vec_2_value::IDENTIFIER) && inputs_count == 3 {
let numbers_to_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER);
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::vec2_value::IDENTIFIER) && inputs_count == 3 {
let numbers_to_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER);
let mut node_template = resolve_document_node_type(&numbers_to_vec2_reference)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
@@ -5143,7 +5143,11 @@ mod tests {
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
panic!("Blend should be a network node")
};
let count_conversion = network_template.nodes.get_mut(&NodeId(3)).expect("Blend should have a count conversion node");
let (&count_conversion_id, count_conversion) = network_template
.nodes
.iter_mut()
.find(|(_, node)| node.inputs.iter().any(|input| matches!(input, NodeInput::Import { import_index: 1, .. })))
.expect("Blend should have a count conversion node");
count_conversion.implementation = NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::floor::IDENTIFIER);
count_conversion.inputs = vec![NodeInput::import(item!(f64), 1)];
document.network_interface.insert_node(node_id, node_template, &[]);
@@ -5160,7 +5164,7 @@ mod tests {
panic!("Blend should stay a network node")
};
assert_eq!(
inner.nodes[&shipped_node_id("Blend", NodeId(3))].implementation,
inner.nodes[&shipped_node_id("Blend", count_conversion_id)].implementation,
DocumentNodeImplementation::ProtoNode(graphene_std::math_nodes::as_number::IDENTIFIER)
);
}
@@ -5177,7 +5181,11 @@ mod tests {
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
panic!("Blend should be a network node")
};
let edited_subtract = network_template.nodes.get_mut(&NodeId(5)).expect("Blend should have an open-path denominator node");
let (&edited_subtract_id, edited_subtract) = network_template
.nodes
.iter_mut()
.find(|(_, node)| node.implementation == NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::subtract::IDENTIFIER))
.expect("Blend should have an open-path denominator node");
edited_subtract.inputs[1] = NodeInput::value(TaggedValue::Number(42.), false);
document.network_interface.insert_node(node_id, node_template, &[]);
@@ -5187,7 +5195,7 @@ mod tests {
let (DocumentNodeImplementation::Definition(definition), Some(inner)) = (implementation, document.network_interface.document_network().implementation_network(implementation)) else {
panic!("Blend should stay a network node")
};
let edited_subtract = derived_node_id(*definition, NodeId(5));
let edited_subtract = derived_node_id(*definition, edited_subtract_id);
assert_eq!(inner.nodes[&edited_subtract].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::Number(42.)));
}
@@ -5269,8 +5277,15 @@ mod tests {
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
panic!("Regex Find should be a network node")
};
network_template.nodes.get_mut(&NodeId(0)).expect("Regex Find should have a find node").inputs[2] = NodeInput::import(item!(f64), 2);
network_template.nodes.get_mut(&NodeId(1)).expect("Regex Find should have an item-at-index node").inputs[1] = NodeInput::value(TaggedValue::Number(0.), false);
let inner_node_id = |identifier: graphene_std::ProtoNodeIdentifier| {
let implementation = NodeTemplateImplementation::ProtoNode(identifier);
network_template.nodes.iter().find(|(_, node)| node.implementation == implementation).map(|(&id, _)| id)
};
let find_id = inner_node_id(graphene_std::text_nodes::regex::regex_find::IDENTIFIER).expect("Regex Find should have a find node");
let item_at_index_id = inner_node_id(graphene_std::graphic::item_at_index::IDENTIFIER).expect("Regex Find should have an item-at-index node");
network_template.nodes.get_mut(&find_id).expect("the find node should exist").inputs[2] = NodeInput::import(item!(f64), 2);
network_template.nodes.get_mut(&item_at_index_id).expect("the item-at-index node should exist").inputs[1] = NodeInput::value(TaggedValue::Number(0.), false);
document.network_interface.insert_node(node_id, node_template, &[]);
migrate(&mut document);
@@ -5284,9 +5299,9 @@ mod tests {
let Some(inner) = document.network_interface.document_network().implementation_network(&node.implementation) else {
panic!("Regex Find should stay a network node")
};
assert_eq!(inner.nodes[&shipped_node_id("Regex Find", NodeId(0))].inputs.get(2), Some(&NodeInput::import(item!(i64), 2)));
assert_eq!(inner.nodes[&shipped_node_id("Regex Find", find_id)].inputs.get(2), Some(&NodeInput::import(item!(i64), 2)));
assert_eq!(
inner.nodes[&shipped_node_id("Regex Find", NodeId(1))].inputs.get(1).and_then(|input| input.as_value()).cloned(),
inner.nodes[&shipped_node_id("Regex Find", item_at_index_id)].inputs.get(1).and_then(|input| input.as_value()).cloned(),
Some(TaggedValue::Integer(0))
);
}
@@ -398,7 +398,8 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
#[cfg(test)]
mod tests {
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, shipped_node_id};
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, NodeTemplateImplementation, shipped_node_id};
use crate::test_utils::test_prelude::*;
use glam::UVec2;
use graph_craft::document::NodeId;
@@ -429,8 +430,20 @@ mod tests {
editor.draw_rect(0., 0., 10., 10.).await;
let layer = editor.get_selected_layer().await.expect("The drawn rectangle should be selected").to_node();
// The node adding Merge's content to the stack
let Some(NodeTemplateImplementation::Network(merge_network)) = resolve_network_node_type("Merge").map(|merge| &merge.node_template.implementation) else {
panic!("Merge should be a network node")
};
let Some((&extend_id, _)) = merge_network
.nodes
.iter()
.find(|(_, node)| node.implementation == NodeTemplateImplementation::ProtoNode(graphene_std::graphic::extend::IDENTIFIER))
else {
panic!("Merge should extend the stack with its content")
};
compile_and_run(&mut editor).await;
let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", NodeId(2)))]);
let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", extend_id))]);
assert!(merge_content.is_some(), "The Merge layer's content should be compiled");
assert_eq!(
editor.runtime.thumbnails.sources.get(&layer).copied(),
+24 -2
View File
@@ -32,7 +32,7 @@ pub struct DocumentNodeDefinition {
}
```
Only the definitions of built-in nodes made from a nested network are written by hand in that file. A node implemented as a single proto-node has its definition generated from the metadata the `node` macro records about its function signature (see [Creating a new node](#creating-a-new-node)), keyed by the proto-node identifier, which for the Opacity node is `graphene_std::blending_nodes::opacity::IDENTIFIER`.
None of these definitions are written by hand. A node implemented as a single proto-node has its definition generated from the metadata the `node` macro records about its function signature (see [Creating a new node](#creating-a-new-node)), keyed by the proto-node identifier, which for the Opacity node is `graphene_std::blending_nodes::opacity::IDENTIFIER`. A built-in node made from a subgraph has its definition generated from the `graph` macro (see [Creating a node from a subgraph](#creating-a-node-from-a-subgraph)), keyed by its name.
## Inspector
@@ -127,7 +127,29 @@ fn opacity<T>(
## Additional Macro Options
The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, `range`, `unit`, `multiline`, and `progression` attributes to influence how the Inspector widgets are generated. The `#[unit("...")]` attribute appends a suffix like `%` or ` px` to a number's widget, while `#[multiline]` gives a `String` the text area widget and `#[progression]` splits a number into its whole and fractional parts. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`.
The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, `range`, `step`, `display_decimal_places`, `unit`, `integer`, `labels`, `blank_assist`, `multiline`, and `progression` attributes to influence how the Inspector widgets are generated. The `#[unit("...")]` attribute appends a suffix like `%` or ` px` to a number's widget, `#[display_decimal_places(2)]` sets how many decimal places a number's widget shows, `#[integer]` makes a number or Vec2 widget take only integers, `#[labels("W", "H")]` names a Vec2 widget's two fields, and `#[blank_assist(false)]` drops the space a widget leaves for its assist area. `#[multiline]` gives a `String` the text area widget and `#[progression]` splits a number into its whole and fractional parts. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`.
## Creating a node from a subgraph
A node built from other nodes uses the `graph` macro, which registers the subgraph as a catalog definition. It takes `category`, `icon`, `name`, and `version` as `node` does, plus `layer` for a node that starts as a layer. Unlike a proto node's, a graph's name (or the title derived from its function name) is also its catalog identifier, which documents store. The function's parameters are the subgraph's imports, which are parsed like a proto node's parameters and take the same value and widget attributes. On an import, `#[hard]` bounds the Inspector widget without clamping a value wired into it. `out!(...)` names the exports. In the body, `>>` feeds its left side into the primary input of the node on its right, every other parameter is named in the call, and a bare name feeds the binding or import of that name into the parameter of the same name. State methods after a call, each written once, set the node's position in grid units (`.at(x, y)`), its display name (`.named("…")`), its flags (`.layer()`, `.hidden()`, `.locked()`, and `.pinned()`), and its call argument (`.call_argument::<Footprint>()`, or `impl Any` for a generic one). An output's name after the call or a binding, like `.captures`, wires from that output instead of the primary one, and goes after any state methods. The body ends with one value per export, as a final expression or with `return`. This is the Load Image node as it exists in `node-graph/nodes/gstd/src/subgraphs.rs`:
```rs
/// Loads an image from a given URL.
#[node_macro::graph(category("Data: I/O"), icon("NodeLoadImage"))]
pub fn load_image(
_: (),
/// The web address or local asset path of the image to load.
#[name("URL")]
url: Item<String>,
) -> out!(
/// The loaded image.
image,
) {
load_resource(url).at(0, 0) >> bytes_to_image().at(7, 0)
}
```
Each node, parameter, and output name resolves through the module the `node` or `graph` macro generates for that node, named after its function, so a misspelled one is reported where it's written. The module's `PARAMETER_COUNT` lets the macro reject `>>` into a node with no parameters. Proto nodes don't name their outputs in that module, so only a graph's outputs can be chosen by name. Every input a call leaves out keeps the default from the node's own definition.
## Executing a document `NodeNetwork`
@@ -60,6 +60,12 @@ pub struct FieldMetadata {
pub progression: bool,
/// Whether the input must be fed by a value known at compile time, from `#[constant]`.
pub constant: bool,
/// The X and Y labels of a Vec2 parameter's widget, from `#[labels("W", "H")]`.
pub labels: Option<(&'static str, &'static str)>,
/// Whether a number or Vec2 parameter's widget only takes integers, from `#[integer]`. Integer types always do.
pub integer: bool,
/// Whether the widget leaves room for the assist area beside it, which `#[blank_assist(false)]` turns off.
pub blank_assist: bool,
}
#[derive(Clone, Debug)]
@@ -222,6 +228,167 @@ pub static NODE_REGISTRY: NodeRegistry = LazyLock::new(|| Mutex::new(HashMap::ne
pub static NODE_METADATA: LazyLock<Mutex<HashMap<ProtoNodeIdentifier, NodeMetadata>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
/// Every node defined as a subgraph by the `#[graph]` macro, in registration order.
pub static GRAPH_METADATA: LazyLock<Mutex<Vec<GraphMetadata>>> = LazyLock::new(|| Mutex::new(Vec::new()));
/// A node defined as a subgraph by `#[graph]`, which the editor turns into a catalog definition alongside the proto nodes.
#[derive(Clone, Debug)]
pub struct GraphMetadata {
/// The definition's identifier and display name.
pub identifier: &'static str,
pub category: &'static str,
pub icon: Option<&'static str>,
pub description: &'static str,
/// The declaration version from `#[graph(version(N))]`, starting at 1.
pub version: u32,
/// Whether a new instance starts as a layer, from `#[graph(layer)]`.
pub layer: bool,
/// The subgraph's imports, which become the inputs of each instance, described like a proto node's parameters.
/// Each one's `default_type` is the type it was declared with.
pub imports: Vec<FieldMetadata>,
pub exports: Vec<GraphExportMetadata>,
/// The nodes inside the subgraph, where each node's position in this list is its ID.
pub nodes: Vec<GraphNodeMetadata>,
}
#[derive(Clone, Debug)]
pub struct GraphExportMetadata {
pub name: &'static str,
pub description: &'static str,
pub source: GraphInputSource,
}
/// A node inside a subgraph defined by `#[graph]`.
#[derive(Clone, Debug)]
pub struct GraphNodeMetadata {
pub implementation: GraphNodeImplementation,
/// The inputs the definition sets, by index. Every other input keeps the default from the node's own definition.
pub inputs: Vec<(usize, GraphInputSource)>,
/// The absolute position in grid units, from `.at(x, y)`.
pub position: Option<(i32, i32)>,
/// From `.layer()`.
pub layer: bool,
/// From `.named("…")`.
pub display_name: Option<&'static str>,
/// From `.hidden()`.
pub hidden: bool,
/// From `.locked()`.
pub locked: bool,
/// From `.pinned()`.
pub pinned: bool,
/// From `.call_argument::<T>()`.
pub call_argument: Option<Type>,
}
/// What a node inside a subgraph is an instance of.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GraphNodeImplementation {
ProtoNode(ProtoNodeIdentifier),
/// Another node defined by `#[graph]`, named by its identifier.
Graph(&'static str),
}
impl From<ProtoNodeIdentifier> for GraphNodeImplementation {
fn from(identifier: ProtoNodeIdentifier) -> Self {
Self::ProtoNode(identifier)
}
}
impl From<&'static str> for GraphNodeImplementation {
fn from(identifier: &'static str) -> Self {
Self::Graph(identifier)
}
}
/// What feeds an input, or an export, of a subgraph defined by `#[graph]`.
#[derive(Clone, Debug)]
pub enum GraphInputSource {
/// The output of another node in the subgraph, by its position in [`GraphMetadata::nodes`].
Node { node: usize, output: usize },
/// One of the subgraph's imports, with the type its wire records.
Import { index: usize, ty: Type },
/// A value. Without an exposure, the input keeps the one from the node's own definition.
Value { value: GraphValue, exposed: Option<bool> },
/// A scope input, from `scope("…")`.
Scope(&'static str),
/// The document path of the node, from `reflect(NodePath)`.
NodePath,
/// The source ID of the node, from `reflect(SourceId)`.
SourceId,
}
/// A value written in a subgraph definition. The editor converts it to the type of the input it feeds.
#[derive(Clone, Debug, PartialEq)]
pub enum GraphValue {
/// A number written without a fractional part, which feeds an integer input as an integer and any other as a number.
Integer(i64),
Number(f64),
Bool(bool),
String(String),
Vec2(glam::DVec2),
Color(Color),
}
impl GraphValue {
pub fn vec2(x: f64, y: f64) -> Self {
Self::Vec2(glam::DVec2::new(x, y))
}
/// An opaque color from `rgb(0xRRGGBB)`.
pub fn rgb(hex: u32) -> Self {
let [_, red, green, blue] = hex.to_be_bytes();
Self::Color(crate::color::SRGBA8::new(red, green, blue, 255).into())
}
/// A color with alpha from `rgba(0xRRGGBBAA)`.
pub fn rgba(hex: u32) -> Self {
let [red, green, blue, alpha] = hex.to_be_bytes();
Self::Color(crate::color::SRGBA8::new(red, green, blue, alpha).into())
}
}
impl From<&str> for GraphValue {
fn from(value: &str) -> Self {
Self::String(value.to_string())
}
}
impl From<String> for GraphValue {
fn from(value: String) -> Self {
Self::String(value)
}
}
impl From<bool> for GraphValue {
fn from(value: bool) -> Self {
Self::Bool(value)
}
}
impl From<f64> for GraphValue {
fn from(value: f64) -> Self {
Self::Number(value)
}
}
impl From<i64> for GraphValue {
fn from(value: i64) -> Self {
Self::Integer(value)
}
}
impl From<glam::DVec2> for GraphValue {
fn from(value: glam::DVec2) -> Self {
Self::Vec2(value)
}
}
impl From<Color> for GraphValue {
fn from(value: Color) -> Self {
Self::Color(value)
}
}
/// All multi-output proto nodes (those returning a [`Destructure`] struct), keyed by their identifier.
/// Snapshotted on first access, which must happen after startup registration of the node metadata completes.
pub static MULTI_OUTPUT_NODES: LazyLock<HashMap<ProtoNodeIdentifier, DestructureMetadata>> = LazyLock::new(|| {
+155 -161
View File
@@ -3,6 +3,7 @@ use convert_case::{Case, Casing};
use proc_macro2::TokenStream as TokenStream2;
use quote::{ToTokens, format_ident, quote, quote_spanned};
use std::sync::atomic::AtomicU64;
use syn::ext::IdentExt;
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::token::Comma;
@@ -112,15 +113,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
let data_field_names: Vec<_> = data_fields.iter().map(|f| &f.pat_ident.ident).collect();
// Only regular fields have input names/descriptions (for UI)
let input_names: Vec<_> = regular_fields
.iter()
.map(|f| &f.name)
.zip(regular_field_names.iter())
.map(|zipped| match zipped {
(Some(name), _) => name.value(),
(_, name) => name.to_string().to_case(Case::Title),
})
.collect();
let input_names: Vec<_> = regular_fields.iter().map(|field| parameter_display_name(field)).collect();
// The primary input is not a parameter, so generators can name their unused one `_primary` without it becoming internal
let input_internal = regular_field_names
@@ -174,56 +167,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
})
.collect();
// Only regular fields have UI metadata (data fields are internal state)
let widget_override: Vec<_> = regular_fields
.iter()
.map(|field| match &field.widget_override {
ParsedWidgetOverride::None => quote!(RegistryWidgetOverride::None),
ParsedWidgetOverride::Hidden => quote!(RegistryWidgetOverride::Hidden),
ParsedWidgetOverride::String(lit_str) => quote!(RegistryWidgetOverride::String(#lit_str)),
ParsedWidgetOverride::Custom(lit_str) => quote!(RegistryWidgetOverride::Custom(#lit_str)),
})
.collect();
let value_sources: Vec<_> = regular_fields
.iter()
.map(|field| match field.ty.value_source() {
ParsedValueSource::Default(data) => {
// Check if the data is a string literal by parsing the token stream
let data_str = data.to_string();
if data_str.starts_with('"') && data_str.ends_with('"') && data_str.len() >= 2 {
quote!(RegistryValueSource::Default(#data))
} else {
quote!(RegistryValueSource::Default(stringify!(#data)))
}
}
ParsedValueSource::Scope(data) => {
if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(_), .. }) = data.as_ref() {
quote!(RegistryValueSource::Scope(#data))
} else {
quote!(RegistryValueSource::Scope(#data.as_static_str()))
}
}
ParsedValueSource::SourceId => quote!(RegistryValueSource::SourceId),
ParsedValueSource::NodePath => quote!(RegistryValueSource::NodePath),
_ => quote!(RegistryValueSource::None),
})
.collect();
let default_colors: Vec<_> = regular_fields
.iter()
.map(|field| match field.ty.regular() {
Some(RegularParsedField {
value_source: ParsedValueSource::Default(data),
..
}) => match color_constant_paths(data) {
Some(paths) => quote!(Some(&[#(#paths),*])),
None => quote!(None),
},
_ => quote!(None),
})
.collect();
let default_types: Vec<_> = regular_fields
.iter()
.enumerate()
@@ -270,64 +213,12 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
})
.collect();
let bound_values = |select: fn(&RegularParsedField) -> &Option<NumberBound>| -> Vec<_> {
regular_fields
.iter()
.map(|field| match field.ty.regular() {
Some(regular) => select(regular).as_ref().map_or(quote!(None), |bound| quote!(Some(#bound))),
None => quote!(None),
})
.collect()
};
let number_soft_min_values = bound_values(|field| &field.number_soft_min);
let number_soft_max_values = bound_values(|field| &field.number_soft_max);
let number_hard_min_values = bound_values(|field| &field.number_hard_min);
let number_hard_max_values = bound_values(|field| &field.number_hard_max);
let number_mode_range_values: Vec<_> = regular_fields
// Only regular fields have UI metadata (data fields are internal state)
let field_metadata: Vec<_> = regular_fields
.iter()
.map(|field| match field.ty.regular() {
Some(RegularParsedField { number_mode_range, .. }) => quote!(#number_mode_range),
None => quote!(false),
})
.collect();
let number_display_decimal_places: Vec<_> = regular_fields
.iter()
.map(|field| field.number_display_decimal_places.as_ref().map_or(quote!(None), |i| quote!(Some(#i))))
.collect();
let number_step: Vec<_> = regular_fields.iter().map(|field| field.number_step.as_ref().map_or(quote!(None), |i| quote!(Some(#i)))).collect();
let unit_suffix: Vec<_> = regular_fields.iter().map(|field| field.unit.as_ref().map_or(quote!(None), |i| quote!(Some(#i)))).collect();
let multiline: Vec<_> = regular_fields
.iter()
.map(|field| {
let multiline = field.multiline;
quote!(#multiline)
})
.collect();
let progression: Vec<_> = regular_fields
.iter()
.map(|field| {
let progression = field.progression;
quote!(#progression)
})
.collect();
let constant: Vec<_> = regular_fields
.iter()
.map(|field| {
let constant = field.constant;
quote!(#constant)
})
.collect();
let exposed: Vec<_> = regular_fields
.iter()
.map(|field| match field.ty.regular() {
Some(RegularParsedField { exposed, .. }) => quote!(#exposed),
None => {
let exposed = !field.is_environment();
quote!(#exposed)
}
})
.zip(&input_internal)
.zip(&default_types)
.map(|((field, internal), default_type)| field_metadata_tokens(field, *internal, default_type, core_types))
.collect();
// Only eval regular fields (data fields are accessed directly as self.field_name)
@@ -858,7 +749,8 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
Some(cfg) => quote!(#[cfg(#cfg)]),
None => quote!(),
};
let node_input_accessor = generate_node_input_references(parsed, &field_idents, core_types, &identifier, &cfg);
let parameter_idents: Vec<_> = regular_fields.iter().filter(|field| !field.is_environment()).map(|field| &field.pat_ident).collect();
let node_input_accessor = generate_node_input_references(parsed, &parameter_idents, core_types, &identifier, &cfg);
let mapped_node_impl = match (&mapped_struct_where_clause, &mapped_eval_impl) {
(Some(mapped_where_clause), Some(mapped_eval)) => quote! {
@@ -1009,7 +901,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
use gcore::{Node, NodeIOTypes, concrete, fn_type, ProtoNodeIdentifier, WasmNotSync, NodeIO, ContextFeature};
use gcore::value::ClonedNode;
use gcore::ops::TypeNode;
use gcore::registry::{NodeMetadata, FieldMetadata, NODE_REGISTRY, NODE_METADATA, DynAnyNode, DowncastBothNode, TypeErasedBox, PanicNode, RegistryValueSource, RegistryWidgetOverride};
use gcore::registry::{NodeMetadata, NODE_REGISTRY, NODE_METADATA, DynAnyNode, DowncastBothNode, TypeErasedBox, PanicNode};
use gcore::ctor::ctor;
// Use the types specified in the implementation
@@ -1056,31 +948,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
},
version: #version,
output_fields: #output_fields,
fields: vec![
#(
FieldMetadata {
name: #input_names,
widget_override: #widget_override,
description: #input_descriptions,
internal: #input_internal,
exposed: #exposed,
value_source: #value_sources,
default_colors: #default_colors,
default_type: #default_types,
number_soft_min: #number_soft_min_values,
number_soft_max: #number_soft_max_values,
number_hard_min: #number_hard_min_values,
number_hard_max: #number_hard_max_values,
number_mode_range: #number_mode_range_values,
number_display_decimal_places: #number_display_decimal_places,
number_step: #number_step,
unit: #unit_suffix,
multiline: #multiline,
progression: #progression,
constant: #constant,
},
)*
],
fields: vec![#(#field_metadata,)*],
};
NODE_METADATA.lock().unwrap().insert(#identifier(), metadata);
}
@@ -1088,6 +956,131 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
})
}
/// The display name an identifier derives, in Title Case.
pub(crate) fn derived_display_name(ident: &Ident) -> String {
// A lone `_` comes out of the case conversion as a space
ident.unraw().to_string().to_case(Case::Title).trim().to_string()
}
/// The name a parameter shows in the UI: its `#[name("…")]`, or else its identifier in Title Case.
pub(crate) fn parameter_display_name(field: &ParsedField) -> String {
match &field.name {
Some(name) => name.value(),
None => derived_display_name(&field.pat_ident.ident),
}
}
/// The symbol naming a parameter or output in a node's module, like `CountInput` for the `count` parameter.
pub(crate) fn symbol_name(ident: &Ident, suffix: &str) -> Ident {
format_ident!("{}{suffix}", ident.unraw().to_string().to_case(Case::Pascal), span = ident.span())
}
/// Generated code for `Some(value)` or `None`, by full path so no name in the author's module can stand in for either.
pub(crate) fn option_tokens(value: Option<TokenStream2>) -> TokenStream2 {
match value {
Some(value) => quote!(::core::option::Option::Some(#value)),
None => quote!(::core::option::Option::None),
}
}
/// The registry's `FieldMetadata` for a parameter, shared by proto node fields and graph imports, which differ only in
/// how they work out whether it's internal state and which type its default is built from.
pub(crate) fn field_metadata_tokens(field: &ParsedField, internal: bool, default_type: &TokenStream2, core_types: &TokenStream2) -> TokenStream2 {
let registry = quote!(#core_types::registry);
let name = parameter_display_name(field);
let description = &field.description;
let exposed = match field.ty.regular() {
Some(regular) => regular.exposed,
None => !field.is_environment(),
};
let widget_override = match &field.widget_override {
ParsedWidgetOverride::None => quote!(#registry::RegistryWidgetOverride::None),
ParsedWidgetOverride::Hidden => quote!(#registry::RegistryWidgetOverride::Hidden),
ParsedWidgetOverride::String(text) => quote!(#registry::RegistryWidgetOverride::String(#text)),
ParsedWidgetOverride::Custom(key) => quote!(#registry::RegistryWidgetOverride::Custom(#key)),
};
// A string literal default keeps its contents, and any other expression is stringified for the editor to parse by type
let value_source = match field.ty.value_source() {
ParsedValueSource::Default(data) => {
let data_string = data.to_string();
if data_string.starts_with('"') && data_string.ends_with('"') && data_string.len() >= 2 {
quote!(#registry::RegistryValueSource::Default(#data))
} else {
quote!(#registry::RegistryValueSource::Default(::core::stringify!(#data)))
}
}
ParsedValueSource::Scope(data) => {
if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(_), .. }) = data.as_ref() {
quote!(#registry::RegistryValueSource::Scope(#data))
} else {
quote!(#registry::RegistryValueSource::Scope(#data.as_static_str()))
}
}
ParsedValueSource::SourceId => quote!(#registry::RegistryValueSource::SourceId),
ParsedValueSource::NodePath => quote!(#registry::RegistryValueSource::NodePath),
ParsedValueSource::None => quote!(#registry::RegistryValueSource::None),
};
let default_colors = match field.ty.regular() {
Some(RegularParsedField {
value_source: ParsedValueSource::Default(data),
..
}) => option_tokens(color_constant_paths(data).map(|paths| quote!(&[#(#paths),*]))),
_ => option_tokens(None),
};
let regular = field.ty.regular();
let bound = |select: fn(&RegularParsedField) -> &Option<NumberBound>| option_tokens(regular.and_then(|regular| select(regular).as_ref()).map(ToTokens::to_token_stream));
let number_soft_min = bound(|regular| &regular.number_soft_min);
let number_soft_max = bound(|regular| &regular.number_soft_max);
let number_hard_min = bound(|regular| &regular.number_hard_min);
let number_hard_max = bound(|regular| &regular.number_hard_max);
let number_mode_range = regular.is_some_and(|regular| regular.number_mode_range);
let number_display_decimal_places = option_tokens(field.number_display_decimal_places.as_ref().map(ToTokens::to_token_stream));
let number_step = option_tokens(field.number_step.as_ref().map(ToTokens::to_token_stream));
let unit = option_tokens(field.unit.as_ref().map(ToTokens::to_token_stream));
let labels = option_tokens(field.labels.as_ref().map(|(x, y)| quote!((#x, #y))));
let ParsedField {
multiline,
progression,
constant,
integer,
blank_assist,
..
} = field;
quote! {
#registry::FieldMetadata {
name: #name,
description: #description,
internal: #internal,
exposed: #exposed,
widget_override: #widget_override,
value_source: #value_source,
default_colors: #default_colors,
default_type: #default_type,
number_soft_min: #number_soft_min,
number_soft_max: #number_soft_max,
number_hard_min: #number_hard_min,
number_hard_max: #number_hard_max,
number_mode_range: #number_mode_range,
number_display_decimal_places: #number_display_decimal_places,
number_step: #number_step,
unit: #unit,
multiline: #multiline,
progression: #progression,
constant: #constant,
labels: #labels,
integer: #integer,
blank_assist: #blank_assist,
}
}
}
/// The `Color::*` constant paths making up a default expression, when it consists solely of them (the form used by color and gradient parameter defaults).
fn color_constant_paths(tokens: &TokenStream2) -> Option<Vec<ExprPath>> {
use syn::parse::Parser;
@@ -1108,26 +1101,25 @@ fn color_constant_paths(tokens: &TokenStream2) -> Option<Vec<ExprPath>> {
.collect()
}
/// Generates the per-parameter symbol types used to reference this node's inputs.
fn generate_node_input_references(parsed: &ParsedNodeFn, field_idents: &[&PatIdent], core_types: &TokenStream2, identifier: &Ident, cfg: &TokenStream2) -> TokenStream2 {
let inputs_module_name = format_ident!("{}", parsed.struct_name.to_string().to_case(Case::Snake));
/// Generates the module named after the node's function, holding its identifier, its parameter count, and a symbol for each parameter.
/// The inputs the compiler fills in come after the parameters and get no symbol, so a graph can't name one.
fn generate_node_input_references(parsed: &ParsedNodeFn, parameter_idents: &[&PatIdent], core_types: &TokenStream2, identifier: &Ident, cfg: &TokenStream2) -> TokenStream2 {
let inputs_module_name = &parsed.fn_name;
let mut generated_input_accessor = Vec::new();
if !parsed.attributes.flags.skip_impl {
for (input_index, input_ident) in field_idents.iter().enumerate() {
// TODO: figure out a better name that doesn't conflict with so many types
let struct_name = format_ident!("{}Input", input_ident.ident.to_string().to_case(Case::Pascal));
// Every parameter gets a plain unit struct: the symbol used across the codebase to name this input
generated_input_accessor.push(quote! {
pub struct #struct_name;
impl #core_types::NodeParameter for #struct_name {
const NODE_IDENTIFIER: #core_types::ProtoNodeIdentifier = #inputs_module_name::IDENTIFIER;
const INDEX: usize = #input_index;
}
});
// Every parameter gets a plain unit struct: the symbol used across the codebase to name this input
let generated_input_accessor = parameter_idents.iter().enumerate().map(|(input_index, input_ident)| {
// TODO: figure out a better name that doesn't conflict with so many types
let struct_name = symbol_name(&input_ident.ident, "Input");
quote! {
pub struct #struct_name;
impl #core_types::NodeParameter for #struct_name {
const NODE_IDENTIFIER: #core_types::ProtoNodeIdentifier = #inputs_module_name::IDENTIFIER;
const INDEX: usize = #input_index;
}
}
}
});
let parameter_count = parameter_idents.len();
quote! {
#cfg
@@ -1136,6 +1128,8 @@ fn generate_node_input_references(parsed: &ParsedNodeFn, field_idents: &[&PatIde
/// The `ProtoNodeIdentifier` of this node without any generics attached to it
pub const IDENTIFIER: #core_types::ProtoNodeIdentifier = #identifier();
/// How many parameters this node has, which come before the inputs the compiler fills in.
pub const PARAMETER_COUNT: usize = #parameter_count;
#(#generated_input_accessor)*
}
}
File diff suppressed because it is too large. Load diff
+33
View File
@@ -5,6 +5,7 @@ mod codegen;
mod crate_ident;
mod derive_choice_type;
mod destructure;
mod graph;
mod parsing;
mod validation;
@@ -16,6 +17,38 @@ pub fn node(attr: TokenStream, item: TokenStream) -> TokenStream {
parsing::new_node_fn(attr.into(), item.into()).unwrap_or_else(|err| err.to_compile_error()).into()
}
/// Defines a node as a subgraph of other nodes, the way `#[node]` defines a proto node.
///
/// The function's parameters are the subgraph's imports, parsed like a proto node's parameters, so they take the same
/// value and widget attributes. On an import, `#[hard]` bounds the widget without clamping a wired value.
/// `out!(...)` names its exports. The body binds nodes with `let`, wires them with `>>` (which feeds its left side
/// into the primary input of the node on its right), and ends with `return`, giving one value per export. Every
/// parameter is named in a call, and a bare name feeds the binding or import of that name to the parameter of the same
/// name. Node state goes in methods after the call, each written once: `.at(x, y)`, `.layer()`, `.hidden()`, `.locked()`,
/// `.pinned()`, `.named("…")`, and `.call_argument::<Footprint>()`. After those, an output's name like `.captures` wires from that
/// output of the node, which also works on a binding.
///
/// ```ignore
/// /// Outlines its content.
/// #[node_macro::graph(category("Vector: Style"))]
/// pub fn outlined(
/// content: List<Graphic>,
/// /// Outline thickness.
/// #[unit(" px")]
/// width: Item<f64>,
/// ) -> out!(
/// /// The outlined content.
/// out,
/// ) {
/// return content >> stroke(weight = width).at(7, 0);
/// }
/// ```
#[proc_macro_error]
#[proc_macro_attribute]
pub fn graph(attr: TokenStream, item: TokenStream) -> TokenStream {
graph::new_graph_fn(attr.into(), item.into()).unwrap_or_else(|err| err.to_compile_error()).into()
}
/// Derives `Destructure` for a struct returned by a multi-output node, making each of its `Item<T>` or `List<T>` fields an output connector.
///
/// A node function returning such a struct (rather than an `Item` or `List`) becomes a multi-output node. The preprocessor
+54 -3
View File
@@ -137,6 +137,10 @@ pub struct ParsedField {
pub progression: bool,
pub constant: bool,
pub is_data_field: bool,
/// The X and Y labels of a Vec2 widget, from `#[labels("W", "H")]`.
pub labels: Option<(LitStr, LitStr)>,
pub integer: bool,
pub blank_assist: bool,
}
impl ParsedField {
@@ -170,6 +174,9 @@ impl ParsedField {
progression: false,
constant: false,
is_data_field: false,
labels: None,
integer: false,
blank_assist: true,
}
}
@@ -319,8 +326,8 @@ impl ToTokens for NumberBound {
/// Unlike a Rust range there is no `..=` form, `..` is purely this attribute DSL's bounds operator.
#[derive(Clone, Debug)]
pub struct NumberRange {
start: Option<NumberBound>,
end: Option<NumberBound>,
pub(crate) start: Option<NumberBound>,
pub(crate) end: Option<NumberBound>,
}
impl Parse for NumberRange {
@@ -819,7 +826,8 @@ fn parse_node_implementations<T: Parse>(attr: &Attribute, name: &Ident) -> syn::
})
}
fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Result<ParsedField> {
/// Parses a parameter and its attributes, for a proto node's field or a graph's import.
pub(crate) fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Result<ParsedField> {
let ident = &pat_ident.ident;
// Checks for the #[data] attribute, indicating that this is a data field rather than an input parameter to the node.
@@ -978,6 +986,22 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
})
.transpose()?;
// `#[labels("W", "H")]` names a Vec2 widget's two fields, and `#[integer]` makes a number or Vec2 widget take only integers
let labels = extract_attribute(attrs, "labels")
.map(|attr| {
let labels: Vec<LitStr> = attr.parse_args_with(Punctuated::<LitStr, Comma>::parse_terminated)?.into_iter().collect();
let [x, y] = <[LitStr; 2]>::try_from(labels).map_err(|_| Error::new_spanned(attr, "Give a Vec2 widget two labels, like `#[labels(\"W\", \"H\")]`"))?;
Ok::<_, Error>((x, y))
})
.transpose()?;
let integer = extract_attribute(attrs, "integer").is_some();
// `#[blank_assist(false)]` drops the space a widget leaves for the assist area beside it
let blank_assist = extract_attribute(attrs, "blank_assist")
.map(|attr| attr.parse_args::<syn::LitBool>().map(|enabled| enabled.value))
.transpose()?
.unwrap_or(true);
let (is_node, node_input_type, node_output_type) = parse_node_type(&ty);
let description = attrs
.iter()
@@ -1036,6 +1060,9 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
progression,
constant,
is_data_field,
labels,
integer,
blank_assist,
})
} else {
let implementations = extract_attribute(attrs, "implementations")
@@ -1088,6 +1115,9 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
progression,
constant,
is_data_field,
labels,
integer,
blank_assist,
})
}
}
@@ -1387,6 +1417,9 @@ mod tests {
progression: false,
constant: false,
is_data_field: false,
labels: None,
integer: false,
blank_assist: true,
}],
body: TokenStream2::new(),
description: String::from("Multi\nLine\n"),
@@ -1449,6 +1482,9 @@ mod tests {
progression: false,
constant: false,
is_data_field: false,
labels: None,
integer: false,
blank_assist: true,
},
ParsedField {
pat_ident: pat_ident("translate"),
@@ -1473,6 +1509,9 @@ mod tests {
progression: false,
constant: false,
is_data_field: false,
labels: None,
integer: false,
blank_assist: true,
},
],
body: TokenStream2::new(),
@@ -1536,6 +1575,9 @@ mod tests {
progression: false,
constant: false,
is_data_field: false,
labels: None,
integer: false,
blank_assist: true,
}],
body: TokenStream2::new(),
description: "Test\n".into(),
@@ -1602,6 +1644,9 @@ mod tests {
progression: false,
constant: false,
is_data_field: false,
labels: None,
integer: false,
blank_assist: true,
}],
body: TokenStream2::new(),
description: String::new(),
@@ -1671,6 +1716,9 @@ mod tests {
progression: false,
constant: false,
is_data_field: false,
labels: None,
integer: false,
blank_assist: true,
}],
body: TokenStream2::new(),
description: String::new(),
@@ -1765,6 +1813,9 @@ mod tests {
progression: false,
constant: false,
is_data_field: false,
labels: None,
integer: false,
blank_assist: true,
}],
body: TokenStream2::new(),
description: String::new(),
+54 -14
View File
@@ -1,22 +1,22 @@
use crate::parsing::{Implementation, NodeOutputTier, NodeParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField, output_payload, output_tier};
use crate::graph::VALUE_HELPERS;
use crate::parsing::{Implementation, NodeOutputTier, NodeParsedField, ParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField, output_payload, output_tier};
use proc_macro_error3::{abort_if_dirty, emit_error};
use quote::quote;
use syn::spanned::Spanned;
use syn::{GenericParam, Type};
use syn::{GenericParam, Ident, Type};
pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
let validators: &[fn(&ParsedNodeFn)] = &[
// Add more validators here as needed
validate_implementations_for_generics,
validate_implementations_row_counts,
validate_primary_input_expose,
validate_min_max,
validate_range_slider_bounds,
|parsed| validate_parameters(&parsed.fields),
validate_no_item_parameters,
validate_element_wise,
validate_ranked_inputs,
validate_async,
validate_non_parameters_trail,
|parsed| validate_name_isnt_a_value_helper(&parsed.fn_name),
];
for validator in validators {
@@ -28,6 +28,20 @@ pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
Ok(())
}
/// A graph body reads a call to a value helper like `rgb(...)` as a value, so a node or graph of that name couldn't be called there.
pub(crate) fn validate_name_isnt_a_value_helper(name: &Ident) {
if let Some(message) = value_helper_name_violation(name) {
emit_error!(name.span(), "{}", message);
}
}
fn value_helper_name_violation(name: &Ident) -> Option<String> {
let name = name.to_string();
VALUE_HELPERS
.contains(&name.as_str())
.then(|| format!("A node can't be named `{name}`, since graphs use that name for a value helper"))
}
fn validate_no_item_parameters(parsed: &ParsedNodeFn) {
if parsed.attributes.flags.skip_impl {
return;
@@ -291,8 +305,15 @@ fn is_unit_type(ty: &Type) -> bool {
matches!(ty, Type::Tuple(tuple) if tuple.elems.is_empty())
}
fn validate_min_max(parsed: &ParsedNodeFn) {
for field in &parsed.fields {
/// The checks on a node's parameters, shared by proto node fields and graph imports, where the first is the primary input.
pub(crate) fn validate_parameters(fields: &[ParsedField]) {
validate_primary_input_expose(fields);
validate_min_max(fields);
validate_range_slider_bounds(fields);
}
fn validate_min_max(fields: &[ParsedField]) {
for field in fields {
if let Some(RegularParsedField {
number_hard_max,
number_hard_min,
@@ -351,8 +372,8 @@ fn validate_min_max(parsed: &ParsedNodeFn) {
/// A `#[range]` slider needs a defined extent on both ends. The extent comes from `#[soft]` when present,
/// otherwise it falls back to `#[hard]`, so each end must be covered by at least one of the two attributes.
fn validate_range_slider_bounds(parsed: &ParsedNodeFn) {
for field in &parsed.fields {
fn validate_range_slider_bounds(fields: &[ParsedField]) {
for field in fields {
if let Some(RegularParsedField {
number_mode_range: true,
number_soft_min,
@@ -384,8 +405,8 @@ fn validate_range_slider_bounds(parsed: &ParsedNodeFn) {
}
}
fn validate_primary_input_expose(parsed: &ParsedNodeFn) {
if let Some(field) = parsed.fields.first()
fn validate_primary_input_expose(fields: &[ParsedField]) {
if let Some(field) = fields.first()
&& let Some(RegularParsedField { exposed: true, .. }) = field.ty.regular()
{
let pat_ident = &field.pat_ident;
@@ -394,7 +415,7 @@ fn validate_primary_input_expose(parsed: &ParsedNodeFn) {
"Unnecessary #[expose] attribute on primary input `{}`. Primary inputs are always exposed.",
pat_ident.ident;
help = "You can safely remove the #[expose] attribute from this field.";
note = "The function's second argument, `{}`, is the node's primary input and it's always exposed by default", pat_ident.ident
note = "`{}` is the node's primary input, which is always exposed by default", pat_ident.ident
);
}
}
@@ -462,7 +483,7 @@ fn validate_async(parsed: &ParsedNodeFn) {
}
/// The arguments that aren't parameters, which are `#[data]` state and the inputs the compiler fills in, go after the parameters.
/// That keeps the primary input at index 0, where the editor's chain flow and other nodes feeding the primary input expect it.
/// That keeps the primary input at index 0, where the editor's chain flow and a graph's `>>` expect it.
fn validate_non_parameters_trail(parsed: &ParsedNodeFn) {
if let Some((span, message)) = non_parameter_order_violation(parsed) {
emit_error!(span, "{}", message);
@@ -475,7 +496,7 @@ fn non_parameter_order_violation(parsed: &ParsedNodeFn) -> Option<(proc_macro2::
let (parameter, non_parameter) = (&parameter.pat_ident, &non_parameter.pat_ident.ident);
let message = format!(
"The parameter `{}` comes after `{non_parameter}`, which isn't a parameter. Move `{non_parameter}` after the parameters: `#[data]` state and the inputs the compiler fills in (`#[scope]`, `#[source_id]`, and `#[node_path]`) go last, so the primary input is always the node's first input, which is the one the editor's chain flow feeds.",
"The parameter `{}` comes after `{non_parameter}`, which isn't a parameter. Move `{non_parameter}` after the parameters: `#[data]` state and the inputs the compiler fills in (`#[scope]`, `#[source_id]`, and `#[node_path]`) go last, so the primary input is always the node's first input, which is the one the editor's chain flow and a graph's `>>` feed.",
parameter.ident
);
Some((parameter.span(), message))
@@ -727,6 +748,25 @@ mod tests {
assert_eq!(only_non_parameters, None);
}
#[test]
fn a_node_named_like_a_value_helper_is_rejected() {
let named = |input: TokenStream| value_helper_name_violation(&parse_node_fn(quote::quote!(category("Test")), input).expect("The test node fn should parse").fn_name);
let message = named(quote::quote!(
fn rgb(_: impl Ctx, value: Item<f64>) -> Item<f64> {
value
}
));
assert!(message.is_some_and(|message| message.contains("can't be named `rgb`")));
let other = named(quote::quote!(
fn tint(_: impl Ctx, value: Item<f64>) -> Item<f64> {
value
}
));
assert_eq!(other, None);
}
fn row_count_violations(input: TokenStream) -> Vec<String> {
let parsed = parse_node_fn(quote::quote!(category("Test")), input).expect("The test node fn should parse");
implementations_row_count_violations(&parsed).into_iter().map(|(_, message)| message).collect()
+1
View File
@@ -5,6 +5,7 @@ pub mod render_background;
pub mod render_cache;
pub mod render_node;
pub mod render_pixel_preview;
pub mod subgraphs;
pub mod text;
pub use blending_nodes;
pub use brush_nodes as brush;
+218
View File
@@ -0,0 +1,218 @@
use crate::artboard::create_artboard;
use crate::context::{read_index, read_vector};
use crate::graphic::{as_graphic, extend, flatten_vector, into_group, item_at_index, map, remove_at_index};
use crate::platform_application_io::{bytes_to_image, load_resource};
use crate::vector::misc::InterpolationDistribution;
use crate::vector::{as_vector, combine_paths, count, morph, path_is_closed, points_to_polyline, separate_paths};
use crate::{Artboard, Color, Graphic, Vector};
use glam::DVec2;
use math_nodes::{add, as_number, divide, floor, max, modulo, multiply, subtract, switch};
use repeat_nodes::repeat;
use transform_nodes::{decompose_translation, extract_transform};
/// Merges the provided content as a new item in the layer's compositing stack.
#[node_macro::graph(category("Graphic"), icon("NodeMerge"), layer)]
pub fn merge(
/// The stack of layers below this one, which the content is placed above.
base: List<Graphic>,
/// The artwork this layer adds to the stack as a single item.
#[expose]
content: List<Graphic>,
) -> out!(
/// The stack of layers with this layer's content placed on top.
out,
) {
let grouped = content >> into_group().at(-7, -1);
base >> as_graphic().at(-7, -2) >> extend(new = grouped).at(0, -2)
}
/// Creates a new Artboard which can be used as a working surface.
#[node_macro::graph(category("Graphic"), icon("NodeArtboard"), layer)]
pub fn artboard(
/// The stack of artboards below this one, which this artboard is placed above.
base: List<Artboard>,
/// Graphics to include within the artboard.
#[expose]
content: List<Graphic>,
/// Coordinate of the top-left corner of the artboard within the document.
#[labels("X", "Y")]
#[unit(" px")]
#[integer]
location: Item<DVec2>,
/// Width and height of the artboard within the document.
#[labels("W", "H")]
#[unit(" px")]
#[integer]
#[default(1920., 1080.)]
dimensions: Item<DVec2>,
/// Color of the artboard background.
#[widget(ParsedWidgetOverride::Custom = "artboard_background")]
#[default(Color::WHITE)]
background: Item<Color>,
/// Whether to cut off the contained content that extends outside the artboard, or keep it visible.
#[default(true)]
clip: Item<bool>,
) -> out!(
/// The stack of artboards with this artboard placed on top.
out,
) {
let board = create_artboard(content, location, dimensions, background, clip).at(-7, -3);
base >> extend(new = board).at(0, -4)
}
/// Creates a series of intermediate shapes that gradually transition between vector objects, optionally along a control path.
#[node_macro::graph(category("Vector: Deform"), icon("NodeBlend"))]
pub fn blend(
/// The vector objects to create intermediate shapes between.
content: List<Vector>,
/// The number of shapes spanning from the first object to the last, repeated for each subpath of the control path.
#[default(10)]
count: Item<i64>,
/// Flip the stacking order of the shapes, so the ones nearest the first object are on top.
reverse: Item<bool>,
/// What changes evenly from one shape to the next, which sets how the intermediate shapes are spaced.
distribution: Item<InterpolationDistribution>,
/// An optional control path with one anchor point per object. Curved segments shape the trajectory of the blend instead of traveling straight.
path: Item<Vector>,
) -> out!(
/// The blended shapes, from the first object to the last.
out,
) {
// Each clamps to at least 1, which also covers an empty control path
let shapes_per_path = count >> as_number().at(2, 13) >> max(other_value = 1).at(9, 13);
let path_count = path >> separate_paths().at(2, 0) >> count().at(2, 2) >> max(other_value = 1).at(9, 2);
// Split the repetition index into which subpath it's on and where along that subpath
let index = read_index().at(2, 7);
let path_index = index >> divide(denominator = shapes_per_path).at(16, 10) >> floor().at(23, 4);
let local_index = index >> modulo(modulus = shapes_per_path).at(16, 7);
// A closed subpath spaces its shapes by the count, and an open one by one fewer (at least 1) so its last shape lands on the end
let open_spacing = shapes_per_path >> subtract(subtrahend = 1).at(16, 14) >> max(other_value = 1).at(23, 14);
let spacing = path >> path_is_closed(index = path_index).at(30, 2) >> switch(if_true = shapes_per_path, if_false = open_spacing).at(30, 12);
// Scaling just below 1 keeps the last shape from overflowing into the next subpath
let fraction = local_index >> divide(denominator = spacing).at(23, 7) >> multiply(multiplicand = 0.9999999999).at(30, 7);
let progression = path_index >> add(addend = fraction).at(37, 4);
let total = shapes_per_path >> multiply(multiplicand = path_count).at(16, 1);
content >> morph(progression, distribution, path).at(44, 3) >> repeat(count = total, reverse).at(51, 0)
}
/// Connects the origins of vector objects in order with an open polyline, such as to make a control path for the **Blend** and **Morph** nodes.
#[node_macro::graph(category("Vector: Path"), icon("NodeOriginsToPolyline"), name("Origins to Polyline"))]
pub fn origins_to_polyline(
/// The vector objects to connect in order by their origins.
vector: List<Vector>,
) -> out!(
/// An open polyline with an anchor point at the origin of each object.
vector,
) {
// Each object's origin, read from the item being mapped, as a single-anchor vector
let origin = read_vector().at(0, 1) >> extract_transform().at(7, 1) >> decompose_translation().at(14, 1) >> as_vector().at(21, 1);
vector >> flatten_vector().at(21, 0) >> map(mapped = origin).at(28, 0) >> combine_paths().at(35, 0) >> points_to_polyline(closed = false).at(42, 0)
}
/// Loads an image from a given URL.
#[node_macro::graph(category("Data: I/O"), icon("NodeLoadImage"))]
pub fn load_image(
_: (),
/// The web address or local asset path of the image to load.
#[name("URL")]
url: Item<String>,
) -> out!(
/// The loaded image.
image,
) {
load_resource(url).at(0, 0) >> bytes_to_image().at(7, 0)
}
/// Finds a portion of the string matching a regular expression pattern. With "Match Index" at its default 0, it selects the first non-overlapping occurrence, but others may be selected. Capture groups, if any, are produced as a list in the "Captures" output.
#[node_macro::graph(category("String: Regex"), icon("NodeRegexFind"))]
pub fn regex_find(
/// The string to search within.
string: Item<String>,
/// The regular expression pattern to search for.
pattern: Item<String>,
/// Which non-overlapping occurrence of the pattern to return, starting from 0 for the first match. Negative indices count backwards from the last match.
match_index: Item<i64>,
/// Match letters regardless of case.
case_insensitive: Item<bool>,
/// Make `^` and `$` match the start and end of each line, not just the whole string.
multiline: Item<bool>,
) -> out!(
/// The whole portion of the string matching the pattern, or empty if there is no match.
r#match,
/// The text matched by each capture group in the pattern, in order.
captures,
) {
// The whole match, then each capture group, where each item carries `start`, `end`, and `name` attributes
let found = string >> text_nodes::regex::regex_find(pattern, match_index, case_insensitive, multiline).at(0, 0);
let whole_match = found >> item_at_index(index = 0).at(8, 0);
let capture_groups = found >> remove_at_index(index = 0).at(8, 2);
(whole_match, capture_groups)
}
#[cfg(test)]
mod tests {
use super::*;
use core_types::registry::GraphInputSource;
/// Finds the capture groups of a pattern.
#[node_macro::graph(category("Test"))]
fn regex_captures(string: Item<String>, pattern: Item<String>) -> out!(captures) {
return string >> regex_find(pattern).captures;
}
#[test]
fn an_output_chosen_by_name_wires_from_that_output() {
let graph = _regex_captures_graph_metadata();
assert!(matches!(graph.exports[0].source, GraphInputSource::Node { node: 0, output: 1 }));
}
/// Puts its content on a board, setting every piece of node state.
#[node_macro::graph(category("Test"))]
fn boarded(content: List<Graphic>) -> out!(out) {
return create_artboard(content, background = rgb(0x102030), clip = exposed(false))
.named("Board")
.hidden()
.locked()
.pinned()
.layer()
.call_argument::<impl Any>()
.at(3, -4);
}
#[test]
fn node_state_and_values_reach_the_metadata() {
use core_types::NodeParameter;
use core_types::registry::GraphValue;
let graph = _boarded_graph_metadata();
let node = &graph.nodes[0];
assert_eq!(node.display_name, Some("Board"));
assert!(node.hidden && node.locked && node.pinned && node.layer);
assert_eq!(node.position, Some((3, -4)));
assert!(matches!(node.call_argument, Some(core_types::Type::Generic(_))));
let source = |index: usize| &node.inputs.iter().find(|(input_index, _)| *input_index == index).expect("the input should be set").1;
assert!(matches!(source(create_artboard::ContentInput::INDEX), GraphInputSource::Import { index: 0, .. }));
assert!(matches!(
source(create_artboard::BackgroundInput::INDEX),
GraphInputSource::Value {
value: GraphValue::Color(_),
exposed: None
}
));
assert!(matches!(
source(create_artboard::ClipInput::INDEX),
GraphInputSource::Value {
value: GraphValue::Bool(false),
exposed: Some(true)
}
));
}
}
+4 -3
View File
@@ -416,7 +416,8 @@ pub fn node_inputs(fields: &[registry::FieldMetadata], first_node_io: &NodeIOTyp
return NodeInput::value(TaggedValue::None, true);
};
let ty = ty.clone().normalize_rank();
let exposed = if index == 0 { ty != fn_type!(Context, ()) } else { field.exposed };
// A `()` primary has nothing to connect, whether it's a proto node's lazy input or a graph's import
let exposed = if index == 0 { ty != fn_type!(Context, ()) && ty != concrete!(()) } else { field.exposed };
match &field.value_source {
RegistryValueSource::None => {}
@@ -543,7 +544,7 @@ mod destructure_tests {
fn vec2_to_numbers_network() -> NodeNetwork {
let vec2_to_numbers = DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::DVec2(DVec2::new(3., 5.)), false)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER),
..Default::default()
};
multi_output_into_add_network(vec2_to_numbers, [1, 2])
@@ -561,7 +562,7 @@ mod destructure_tests {
#[test]
fn multi_output_node_expands_into_generated_destructure_network() {
let vec2_to_numbers_identifier = graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER;
let vec2_to_numbers_identifier = graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER;
let destructure = registry::MULTI_OUTPUT_NODES
.get(&vec2_to_numbers_identifier)
.expect("Vec2 to Numbers should be registered as a multi-output node");
@@ -219,7 +219,7 @@ Writing to any other node fails, since another anchor's run may be editing it.
### Network definitions
Some built-in nodes, like Merge and Artboard, are subgraphs. Each instance holds its own copy of a network defined in `document_node_definitions.rs`, and stores the definition's identifier and `version` next to it. Bump `version` on the `DocumentNodeDefinition` when instances saved before your change would load wrongly, and register a migration from the old version with the `network` prefix:
Some built-in nodes, like Merge and Artboard, are subgraphs. Each is defined by a `#[graph]` function in `node-graph/nodes/gstd/src/subgraphs.rs`, and instances store the definition's identifier and `version` next to their copy of its network. Bump the version with `#[graph(..., version(N))]` when instances saved before your change would load wrongly, and register a migration from the old version with the `network` prefix:
```rust
rename!(network "Artboard"@1 => @2);