mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c54608c12d | ||
|
|
c403654745 | ||
|
|
6c3232ee8c |
No files matched your search
Generated
+13
@@ -2534,6 +2534,18 @@ dependencies = [
|
|||||||
"smallvec",
|
"smallvec",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "graph-text"
|
||||||
|
version = "0.0.0"
|
||||||
|
dependencies = [
|
||||||
|
"convert_case 0.12.0",
|
||||||
|
"core-types",
|
||||||
|
"glam",
|
||||||
|
"log",
|
||||||
|
"proc-macro2",
|
||||||
|
"syn 3.0.9",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "graphene-animation"
|
name = "graphene-animation"
|
||||||
version = "0.0.0"
|
version = "0.0.0"
|
||||||
@@ -2664,6 +2676,7 @@ dependencies = [
|
|||||||
"futures",
|
"futures",
|
||||||
"glam",
|
"glam",
|
||||||
"graph-craft",
|
"graph-craft",
|
||||||
|
"graph-text",
|
||||||
"graphene-application-io",
|
"graphene-application-io",
|
||||||
"graphene-canvas-utils",
|
"graphene-canvas-utils",
|
||||||
"graphene-core",
|
"graphene-core",
|
||||||
|
|||||||
@@ -93,6 +93,7 @@ graphene-application-io = { path = "node-graph/libraries/application-io" }
|
|||||||
graphene-resource = { path = "node-graph/libraries/resources" }
|
graphene-resource = { path = "node-graph/libraries/resources" }
|
||||||
graphene-animation = { path = "node-graph/libraries/animation" }
|
graphene-animation = { path = "node-graph/libraries/animation" }
|
||||||
core-types = { path = "node-graph/libraries/core-types" }
|
core-types = { path = "node-graph/libraries/core-types" }
|
||||||
|
graph-text = { path = "node-graph/libraries/graph-text" }
|
||||||
raster-types = { path = "node-graph/libraries/raster-types" }
|
raster-types = { path = "node-graph/libraries/raster-types" }
|
||||||
vector-types = { path = "node-graph/libraries/vector-types" }
|
vector-types = { path = "node-graph/libraries/vector-types" }
|
||||||
graphic-types = { path = "node-graph/libraries/graphic-types" }
|
graphic-types = { path = "node-graph/libraries/graphic-types" }
|
||||||
|
|||||||
@@ -5,19 +5,16 @@ use super::node_inspector::{self, ParameterWidgetsInfo, SliderRange};
|
|||||||
use super::utility_types::{FrontendNodeType, InputTypeConstraint};
|
use super::utility_types::{FrontendNodeType, InputTypeConstraint};
|
||||||
use crate::messages::frontend::IconName;
|
use crate::messages::frontend::IconName;
|
||||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
use crate::messages::portfolio::document::utility_types::network_interface::{NodeNetworkInterface, NodeTemplate, NodeTemplateImplementation};
|
||||||
InputMetadata, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, Vec2InputSettings, WidgetOverride,
|
|
||||||
};
|
|
||||||
use crate::messages::portfolio::ingest::utility_types::TypeFilter;
|
use crate::messages::portfolio::ingest::utility_types::TypeFilter;
|
||||||
use crate::messages::prelude::{DocumentId, FontsMessage, FontsMessageHandler, Message, ResourceMessageHandler, Responses};
|
use crate::messages::prelude::{DocumentId, FontsMessage, FontsMessageHandler, Message, ResourceMessageHandler, Responses};
|
||||||
use crate::node_graph_executor::NodeGraphExecutor;
|
use crate::node_graph_executor::NodeGraphExecutor;
|
||||||
use glam::DVec2;
|
use glam::DVec2;
|
||||||
use graph_craft::ProtoNodeIdentifier;
|
use graph_craft::ProtoNodeIdentifier;
|
||||||
|
use graph_craft::concrete;
|
||||||
use graph_craft::document::value::*;
|
use graph_craft::document::value::*;
|
||||||
use graph_craft::document::*;
|
use graph_craft::document::*;
|
||||||
use graph_craft::{concrete, list};
|
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType};
|
||||||
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType};
|
|
||||||
use graphene_std::vector::Vector;
|
|
||||||
use graphene_std::*;
|
use graphene_std::*;
|
||||||
use std::collections::{HashMap, VecDeque};
|
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 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()?;
|
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 {
|
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");
|
log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override");
|
||||||
return None;
|
return None;
|
||||||
@@ -54,6 +56,8 @@ impl NodeInspectorContext<'_> {
|
|||||||
pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = 2;
|
pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = 2;
|
||||||
/// 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.
|
/// 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 = 3;
|
||||||
|
/// Input position of the clip parameter on the "Artboard" layer template.
|
||||||
|
pub const ARTBOARD_CLIP_INPUT_INDEX: usize = 5;
|
||||||
/// Input position of the control path parameter on the "Blend" network node template.
|
/// 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 = 4;
|
||||||
|
|
||||||
@@ -107,8 +111,7 @@ pub struct DocumentNodeDefinition {
|
|||||||
/// Used to create the [`DefinitionIdentifier::Network`] identifier.
|
/// Used to create the [`DefinitionIdentifier::Network`] identifier.
|
||||||
pub identifier: &'static str,
|
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.
|
/// The definition's position in its lineage, from `version(N)` on its `#[node]` or `#[graph]`. Instances store it next to their reference.
|
||||||
/// Instances store it next to their reference. Proto-node definitions take theirs from the node macro.
|
|
||||||
pub version: u32,
|
pub version: u32,
|
||||||
|
|
||||||
/// The default [`NodeTemplate`] this definition instantiates.
|
/// The default [`NodeTemplate`] this definition instantiates.
|
||||||
@@ -136,541 +139,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).
|
/// 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.
|
/// 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> {
|
fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||||
let custom = vec![
|
document_node_derive::derive_definitions()
|
||||||
DocumentNodeDefinition {
|
|
||||||
identifier: "Custom Node",
|
|
||||||
version: 1,
|
|
||||||
category: "Routing",
|
|
||||||
icon: Some("NodeCustomNode"),
|
|
||||||
node_template: NodeTemplate {
|
|
||||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
description: Cow::Borrowed("An empty node network you can use to create your own custom nodes."),
|
|
||||||
inspector: None,
|
|
||||||
},
|
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type NodeInspector = HashMap<String, Box<dyn Fn(NodeId, &mut NodeInspectorContext) -> Vec<LayoutGroup> + Send + Sync>>;
|
type NodeInspector = HashMap<String, Box<dyn Fn(NodeId, &mut NodeInspectorContext) -> Vec<LayoutGroup> + Send + Sync>>;
|
||||||
@@ -738,91 +209,10 @@ fn static_input_inspector() -> InputInspector {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
map.insert(
|
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(),
|
"optional_f64".to_string(),
|
||||||
Box::new(|node_id, index, context| {
|
Box::new(|node_id, index, context| {
|
||||||
let mut number_input = NumberInput::default();
|
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.field_metadata(&node_id, index, context.selection_network_path) {
|
||||||
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(unit) = field.unit {
|
if let Some(unit) = field.unit {
|
||||||
number_input = number_input.unit(unit);
|
number_input = number_input.unit(unit);
|
||||||
}
|
}
|
||||||
@@ -917,57 +307,6 @@ fn static_input_inspector() -> InputInspector {
|
|||||||
"type_choice".to_string(),
|
"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))])),
|
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(
|
map.insert(
|
||||||
"noise_inspector_scale".to_string(),
|
"noise_inspector_scale".to_string(),
|
||||||
Box::new(|node_id, index, context| {
|
Box::new(|node_id, index, context| {
|
||||||
@@ -1140,6 +479,7 @@ fn static_input_inspector() -> InputInspector {
|
|||||||
"Y",
|
"Y",
|
||||||
"",
|
"",
|
||||||
None,
|
None,
|
||||||
|
None,
|
||||||
false,
|
false,
|
||||||
mandelbrot_to_julia.is_some_and(|percent| percent >= 100.),
|
mandelbrot_to_julia.is_some_and(|percent| percent >= 100.),
|
||||||
)])
|
)])
|
||||||
@@ -1156,6 +496,7 @@ fn static_input_inspector() -> InputInspector {
|
|||||||
"Y",
|
"Y",
|
||||||
"",
|
"",
|
||||||
None,
|
None,
|
||||||
|
None,
|
||||||
false,
|
false,
|
||||||
mandelbrot_to_julia.is_some_and(|percent| percent <= 0.),
|
mandelbrot_to_julia.is_some_and(|percent| percent <= 0.),
|
||||||
)])
|
)])
|
||||||
@@ -1262,6 +603,7 @@ fn static_input_inspector() -> InputInspector {
|
|||||||
"Y",
|
"Y",
|
||||||
" px",
|
" px",
|
||||||
None,
|
None,
|
||||||
|
None,
|
||||||
false,
|
false,
|
||||||
false,
|
false,
|
||||||
)])
|
)])
|
||||||
@@ -1277,6 +619,7 @@ fn static_input_inspector() -> InputInspector {
|
|||||||
"H",
|
"H",
|
||||||
"x",
|
"x",
|
||||||
None,
|
None,
|
||||||
|
None,
|
||||||
false,
|
false,
|
||||||
false,
|
false,
|
||||||
)])
|
)])
|
||||||
@@ -1397,7 +740,7 @@ fn static_input_inspector() -> InputInspector {
|
|||||||
"vec2_uv".to_string(),
|
"vec2_uv".to_string(),
|
||||||
Box::new(|node_id, index, context| {
|
Box::new(|node_id, index, context| {
|
||||||
let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, 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
|
map
|
||||||
@@ -1645,6 +988,29 @@ mod test {
|
|||||||
use crate::test_utils::test_prelude::*;
|
use crate::test_utils::test_prelude::*;
|
||||||
use graph_craft::document::NodeId;
|
use graph_craft::document::NodeId;
|
||||||
|
|
||||||
|
// A graph text 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() {
|
||||||
|
let sources = graphene_std::registry::GRAPH_SOURCES.lock().unwrap().len();
|
||||||
|
let graphs = &*graphene_std::graph_text::GRAPHS;
|
||||||
|
assert!(!graphs.is_empty(), "the graphs in `graphene_std` should be registered");
|
||||||
|
assert_eq!(graphs.len(), sources, "every registered graph should resolve");
|
||||||
|
|
||||||
|
for graph in graphs {
|
||||||
|
assert!(resolve_network_node_type(graph.identifier).is_some(), "the '{}' graph should have a definition", graph.identifier);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn input_index_constants_match_the_graphs() {
|
||||||
|
use graphene_std::graph_text::import_index;
|
||||||
|
|
||||||
|
assert_eq!(import_index("Artboard", "location"), Some(super::ARTBOARD_LOCATION_INPUT_INDEX));
|
||||||
|
assert_eq!(import_index("Artboard", "dimensions"), Some(super::ARTBOARD_DIMENSIONS_INPUT_INDEX));
|
||||||
|
assert_eq!(import_index("Artboard", "clip"), Some(super::ARTBOARD_CLIP_INPUT_INDEX));
|
||||||
|
assert_eq!(import_index("Blend", "path"), Some(super::BLEND_PATH_INPUT_INDEX));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rasterize_defaults_to_a_1000_px_square_at_full_resolution() {
|
fn rasterize_defaults_to_a_1000_px_square_at_full_resolution() {
|
||||||
use glam::{DAffine2, UVec2};
|
use glam::{DAffine2, UVec2};
|
||||||
@@ -1785,21 +1151,36 @@ mod test_type_constraints {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn every_definition_default_value_satisfies_its_constraint() {
|
fn every_definition_default_value_satisfies_its_constraint() {
|
||||||
let mut violations = Vec::new();
|
// Checks a node's inputs against what its implementations accept, then each node inside it, whose values a subgraph's author writes too
|
||||||
for definition in super::DOCUMENT_NODE_TYPES.values() {
|
fn check(node_template: &NodeTemplate, name: &str, violations: &mut Vec<String>) {
|
||||||
let name = &definition.node_template.display_name;
|
let constraints = InputTypeConstraint::constraints_for_all_inputs(node_template, name);
|
||||||
let constraints = InputTypeConstraint::constraints_for_all_inputs(&definition.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()
|
if let Some(value) = input.as_value()
|
||||||
&& !constraint.accepts_default_value(&value.ty())
|
&& !constraint.accepts_default_value(&value.ty())
|
||||||
{
|
{
|
||||||
violations.push(format!("{name} input {index}: {} does not satisfy {constraint:?}", 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]
|
#[test]
|
||||||
@@ -1816,7 +1197,7 @@ mod test_type_constraints {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn single_protonode() {
|
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");
|
let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name");
|
||||||
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(glam::DVec2)]);
|
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(glam::DVec2)]);
|
||||||
assert!(!constraint[0].satisfies(&concrete!(String)));
|
assert!(!constraint[0].satisfies(&concrete!(String)));
|
||||||
@@ -1830,7 +1211,7 @@ mod test_type_constraints {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn single_protonode2() {
|
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");
|
let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name");
|
||||||
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(String)]);
|
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(String)]);
|
||||||
assert!(!constraint[0].satisfies(&concrete!(glam::DVec2)));
|
assert!(!constraint[0].satisfies(&concrete!(glam::DVec2)));
|
||||||
@@ -1839,8 +1220,8 @@ mod test_type_constraints {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn network() {
|
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 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_f_32_f_64_string::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 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 min_node = min_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]);
|
||||||
let inner_network = NodeNetworkTemplate {
|
let inner_network = NodeNetworkTemplate {
|
||||||
|
|||||||
+422
-30
@@ -1,11 +1,17 @@
|
|||||||
use super::DocumentNodeDefinition;
|
use super::DocumentNodeDefinition;
|
||||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
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::registry::*;
|
||||||
use graphene_std::*;
|
use graphene_std::*;
|
||||||
use std::collections::{HashMap, HashSet};
|
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();
|
let mut definitions_map = HashMap::new();
|
||||||
|
|
||||||
// Add the protonodes from the macro.
|
// Add the protonodes from the macro.
|
||||||
@@ -75,16 +81,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
|||||||
inputs,
|
inputs,
|
||||||
call_argument: input_type.clone(),
|
call_argument: input_type.clone(),
|
||||||
implementation: NodeTemplateImplementation::ProtoNode(id.clone()),
|
implementation: NodeTemplateImplementation::ProtoNode(id.clone()),
|
||||||
// TODO: Store information for input overrides in the node macro
|
input_metadata: input_metadata(fields),
|
||||||
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(),
|
|
||||||
output_names,
|
output_names,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
@@ -96,25 +93,241 @@ 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
|
add_graph_definitions(graph_text::GRAPHS.clone(), &mut definitions_map);
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
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 text 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 in graph text, 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 in graph text.
|
||||||
|
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();
|
||||||
|
|
||||||
|
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 = IVec2::from(node.position);
|
||||||
|
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
|
||||||
|
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).map_err(|reason| GraphDefinitionError::Invalid(format!("input {input_index} of its node {index}, '{name}', is invalid: {reason}")))?;
|
||||||
|
}
|
||||||
|
|
||||||
|
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::<Result<_, _>>()
|
||||||
|
.map_err(GraphDefinitionError::Invalid)?;
|
||||||
|
|
||||||
|
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.
|
||||||
|
/// A value must have the type of that default, if it has one.
|
||||||
|
fn graph_input(source: &GraphInputSource, default: &NodeInput) -> Result<NodeInput, String> {
|
||||||
|
Ok(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 value = graph_value(value);
|
||||||
|
if let NodeInput::Value { tagged_value, .. } = default
|
||||||
|
&& **tagged_value != TaggedValue::None
|
||||||
|
&& element_type(&tagged_value.ty()) != element_type(&value.ty())
|
||||||
|
{
|
||||||
|
return Err(format!("its value `{value:?}` doesn't have the input's type, `{:?}`", tagged_value.ty()));
|
||||||
|
}
|
||||||
|
NodeInput::value(value, 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.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn graph_value(value: &GraphValue) -> TaggedValue {
|
||||||
|
match value {
|
||||||
|
GraphValue::Integer(integer) => TaggedValue::Integer(*integer),
|
||||||
|
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>) {
|
fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
|
||||||
match &mut node_template.implementation {
|
match &mut node_template.implementation {
|
||||||
NodeTemplateImplementation::Network(network_template) => {
|
NodeTemplateImplementation::Network(network_template) => {
|
||||||
@@ -128,13 +341,192 @@ fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &
|
|||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// A display name, lock, or pin the network's author gave the node is kept
|
||||||
let definition_template = &definition.node_template;
|
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.input_metadata = definition_template.input_metadata.clone();
|
||||||
node_template.output_names = definition_template.output_names.clone();
|
node_template.output_names = definition_template.output_names.clone();
|
||||||
node_template.locked = definition_template.locked;
|
node_template.locked |= definition_template.locked;
|
||||||
node_template.pinned = definition_template.pinned;
|
node_template.pinned |= definition_template.pinned;
|
||||||
}
|
}
|
||||||
NodeTemplateImplementation::Definition(_) => {}
|
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",
|
||||||
|
identifier: "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,
|
||||||
|
path: identifier,
|
||||||
|
category: "Test",
|
||||||
|
icon: None,
|
||||||
|
description: "",
|
||||||
|
version: 1,
|
||||||
|
layer: false,
|
||||||
|
imports: vec![number_import()],
|
||||||
|
exports: vec![GraphExportMetadata {
|
||||||
|
name: "Out",
|
||||||
|
identifier: "out",
|
||||||
|
description: "",
|
||||||
|
source: GraphInputSource::Node { node: 0, output: 0 },
|
||||||
|
}],
|
||||||
|
nodes: vec![GraphNodeMetadata {
|
||||||
|
implementation,
|
||||||
|
inputs,
|
||||||
|
position: (0, 0),
|
||||||
|
layer: false,
|
||||||
|
display_name: None,
|
||||||
|
hidden: false,
|
||||||
|
locked: false,
|
||||||
|
pinned: false,
|
||||||
|
}],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), 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", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), 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", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), from_import());
|
||||||
|
let second = one_node_graph("Test Twin", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), 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 a_value_must_have_the_type_of_the_input_it_feeds() {
|
||||||
|
let number_input = NodeInput::value(TaggedValue::Number(0.), false);
|
||||||
|
let value = |value| GraphInputSource::Value { value, exposed: None };
|
||||||
|
|
||||||
|
assert!(graph_input(&value(GraphValue::Integer(3)), &number_input).is_err());
|
||||||
|
assert!(matches!(graph_input(&value(GraphValue::Number(3.)), &number_input), Ok(NodeInput::Value { .. })));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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", GraphNodeImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER), 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::graph_text::import_index("Artboard", "location").expect("Artboard should have a location import");
|
||||||
|
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, &[]));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -45,6 +45,11 @@ pub enum NodeGraphMessage {
|
|||||||
xy: Option<(i32, i32)>,
|
xy: Option<(i32, i32)>,
|
||||||
add_transaction: bool,
|
add_transaction: bool,
|
||||||
},
|
},
|
||||||
|
/// Adds a subgraph with nothing in it, at the given grid position or else in view, and selects it.
|
||||||
|
CreateEmptySubgraph {
|
||||||
|
node_id: Option<NodeId>,
|
||||||
|
xy: Option<(i32, i32)>,
|
||||||
|
},
|
||||||
CreateWire {
|
CreateWire {
|
||||||
output_connector: OutputConnector,
|
output_connector: OutputConnector,
|
||||||
input_connector: InputConnector,
|
input_connector: InputConnector,
|
||||||
@@ -383,6 +388,7 @@ impl NodeGraphMessage {
|
|||||||
| Self::SetImportExportDescriptionImpl { .. } => Some(breadcrumb_network_path),
|
| Self::SetImportExportDescriptionImpl { .. } => Some(breadcrumb_network_path),
|
||||||
Self::AddNodes { .. }
|
Self::AddNodes { .. }
|
||||||
| Self::CreateNodeFromContextMenu { .. }
|
| Self::CreateNodeFromContextMenu { .. }
|
||||||
|
| Self::CreateEmptySubgraph { .. }
|
||||||
| Self::CreateWire { .. }
|
| Self::CreateWire { .. }
|
||||||
| Self::CreateWires { .. }
|
| Self::CreateWires { .. }
|
||||||
| Self::ConnectUpstreamOutputToInput { .. }
|
| Self::ConnectUpstreamOutputToInput { .. }
|
||||||
|
|||||||
@@ -5,13 +5,14 @@ use crate::messages::input_mapper::utility_types::macros::{action_shortcut, acti
|
|||||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||||
use crate::messages::portfolio::document::document_message_handler::navigation_controls;
|
use crate::messages::portfolio::document::document_message_handler::navigation_controls;
|
||||||
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
|
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
|
||||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type, resolve_network_node_type};
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type};
|
||||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic};
|
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic};
|
||||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||||
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
|
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
|
||||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||||
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint, TransactionStatus,
|
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTemplate, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint,
|
||||||
|
TransactionStatus,
|
||||||
};
|
};
|
||||||
use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry};
|
use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry};
|
||||||
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
|
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
|
||||||
@@ -422,6 +423,23 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
|||||||
});
|
});
|
||||||
responses.add(NodeGraphMessage::SendGraph);
|
responses.add(NodeGraphMessage::SendGraph);
|
||||||
}
|
}
|
||||||
|
NodeGraphMessage::CreateEmptySubgraph { node_id, xy } => {
|
||||||
|
let node_id = node_id.unwrap_or_else(NodeId::new);
|
||||||
|
let (x, y) = xy.unwrap_or_else(|| {
|
||||||
|
network_interface
|
||||||
|
.node_graph_ptz(breadcrumb_network_path)
|
||||||
|
.map_or((0, 0), |ptz| ((-ptz.pan.x / GRID_SIZE as f64) as i32, (-ptz.pan.y / GRID_SIZE as f64) as i32))
|
||||||
|
});
|
||||||
|
|
||||||
|
responses.add(DocumentMessage::AddTransaction);
|
||||||
|
responses.add(NodeGraphMessage::InsertNode {
|
||||||
|
node_id,
|
||||||
|
node_template: Box::new(NodeTemplate::empty_subgraph()),
|
||||||
|
});
|
||||||
|
responses.add(NodeGraphMessage::ShiftNodePosition { node_id, x, y });
|
||||||
|
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] });
|
||||||
|
responses.add(NodeGraphMessage::SendGraph);
|
||||||
|
}
|
||||||
NodeGraphMessage::ConnectUpstreamOutputToInput { downstream_input, input_connector } => {
|
NodeGraphMessage::ConnectUpstreamOutputToInput { downstream_input, input_connector } => {
|
||||||
let Some(upstream_node) = network_interface.upstream_output_connector(&downstream_input, selection_network_path) else {
|
let Some(upstream_node) = network_interface.upstream_output_connector(&downstream_input, selection_network_path) else {
|
||||||
log::error!("Failed to find upstream node for downstream_input");
|
log::error!("Failed to find upstream node for downstream_input");
|
||||||
@@ -769,24 +787,19 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use the network interface to add a default node, then set the imports, exports, paste the nodes inside, and connect them to the imports/exports
|
// Add an empty subgraph, then set its imports and exports, paste the nodes inside, and connect them to the imports and exports
|
||||||
let encapsulating_node_id = NodeId::new();
|
let encapsulating_node_id = NodeId::new();
|
||||||
let mut default_node_template = resolve_network_node_type("Custom Node").expect("Custom Node should exist").default_node_template();
|
let mut subgraph_template = NodeTemplate::empty_subgraph();
|
||||||
let Some(center_of_selected_nodes) = network_interface.selected_nodes_bounding_box(breadcrumb_network_path).map(|[a, b]| (a + b) / 2.) else {
|
let Some(center_of_selected_nodes) = network_interface.selected_nodes_bounding_box(breadcrumb_network_path).map(|[a, b]| (a + b) / 2.) else {
|
||||||
log::error!("Could not get center of selected_nodes");
|
log::error!("Could not get center of selected_nodes");
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
let center_of_selected_nodes_grid_space = IVec2::new((center_of_selected_nodes.x / 24. + 0.5).floor() as i32, (center_of_selected_nodes.y / 24. + 0.5).floor() as i32);
|
let center_of_selected_nodes_grid_space = IVec2::new((center_of_selected_nodes.x / 24. + 0.5).floor() as i32, (center_of_selected_nodes.y / 24. + 0.5).floor() as i32);
|
||||||
default_node_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
|
subgraph_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
|
||||||
responses.add(DocumentMessage::AddTransaction);
|
responses.add(DocumentMessage::AddTransaction);
|
||||||
responses.add(NodeGraphMessage::InsertNode {
|
responses.add(NodeGraphMessage::InsertNode {
|
||||||
node_id: encapsulating_node_id,
|
node_id: encapsulating_node_id,
|
||||||
node_template: Box::new(default_node_template),
|
node_template: Box::new(subgraph_template),
|
||||||
});
|
|
||||||
responses.add(NodeGraphMessage::SetDisplayNameImpl {
|
|
||||||
node_id: encapsulating_node_id,
|
|
||||||
network_path: selection_network_path.to_vec(),
|
|
||||||
alias: "Untitled Node".to_string(),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
responses.add(DocumentMessage::EnterNestedNetwork { node_id: encapsulating_node_id });
|
responses.add(DocumentMessage::EnterNestedNetwork { node_id: encapsulating_node_id });
|
||||||
@@ -3426,6 +3439,13 @@ impl NodeGraphMessageHandler {
|
|||||||
})
|
})
|
||||||
.disabled(read_only)
|
.disabled(read_only)
|
||||||
.widget_instance(),
|
.widget_instance(),
|
||||||
|
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||||
|
TextButton::new("New Custom Node")
|
||||||
|
.tooltip_label("New Custom Node")
|
||||||
|
.tooltip_description("Add an empty subgraph, which can be entered to build a node of your own out of other nodes.")
|
||||||
|
.on_update(|_| NodeGraphMessage::CreateEmptySubgraph { node_id: None, xy: None }.into())
|
||||||
|
.disabled(read_only)
|
||||||
|
.widget_instance(),
|
||||||
//
|
//
|
||||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||||
//
|
//
|
||||||
|
|||||||
@@ -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.
|
/// 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(crate) struct ParameterOptions {
|
||||||
pub soft_min: Option<f64>,
|
pub soft_min: Option<f64>,
|
||||||
pub soft_max: Option<f64>,
|
pub soft_max: Option<f64>,
|
||||||
@@ -250,6 +250,50 @@ pub(crate) struct ParameterOptions {
|
|||||||
pub unit: Option<&'static str>,
|
pub unit: Option<&'static str>,
|
||||||
pub display_decimal_places: Option<u32>,
|
pub display_decimal_places: Option<u32>,
|
||||||
pub step: Option<f64>,
|
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.
|
/// 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,
|
unit,
|
||||||
display_decimal_places,
|
display_decimal_places,
|
||||||
step,
|
step,
|
||||||
|
labels,
|
||||||
|
integer,
|
||||||
|
blank_assist,
|
||||||
} = options;
|
} = options;
|
||||||
|
|
||||||
let mut number_input = NumberInput::default();
|
let mut number_input = NumberInput::default().is_integer(integer);
|
||||||
if slider {
|
if slider {
|
||||||
number_input = number_input.mode_range();
|
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
|
// 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| {
|
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(),
|
true => text_area_widget(default_info).into(),
|
||||||
false => text_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::<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::<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)),
|
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(¶meter_widgets_info);
|
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||||
|
|
||||||
let Some(input) = parameter_widgets_info.input() else {
|
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)
|
.label(x)
|
||||||
.unit(unit)
|
.unit(unit)
|
||||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
.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)
|
.is_integer(is_integer)
|
||||||
.disabled(disabled)
|
.disabled(disabled)
|
||||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), dvec2.y))))
|
.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)
|
.label(y)
|
||||||
.unit(unit)
|
.unit(unit)
|
||||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
.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)
|
.is_integer(is_integer)
|
||||||
.disabled(disabled)
|
.disabled(disabled)
|
||||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(dvec2.x, input.value.unwrap()))))
|
.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)
|
.label(x)
|
||||||
.unit(unit)
|
.unit(unit)
|
||||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
.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)
|
.is_integer(is_integer)
|
||||||
.disabled(disabled)
|
.disabled(disabled)
|
||||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), value))))
|
.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)
|
.label(y)
|
||||||
.unit(unit)
|
.unit(unit)
|
||||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
.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)
|
.is_integer(is_integer)
|
||||||
.disabled(disabled)
|
.disabled(disabled)
|
||||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(value, input.value.unwrap()))))
|
.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),
|
ParameterWidgetsInfo::new(node_id, SpacingInput, true, context),
|
||||||
NumberInput::default().label("H").min(0.).unit(" px"),
|
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]);
|
widgets.extend([spacing, angles]);
|
||||||
} else {
|
} 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);
|
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 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 {
|
let Some(implementation) = context.network_interface.implementation(&node_id, context.selection_network_path) else {
|
||||||
log::error!("Could not get implementation for node {node_id}");
|
log::error!("Could not get implementation for node {node_id}");
|
||||||
return Vec::new();
|
return Vec::new();
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut options = ParameterOptions::default();
|
|
||||||
let input_type = match implementation {
|
let input_type = match implementation {
|
||||||
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => 'early_return: {
|
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
|
// 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 proto_node_identifier = proto_node_identifier.clone();
|
||||||
|
|
||||||
let mut default_type = None;
|
if let Some(default) = field.and_then(|field| field.default_type) {
|
||||||
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 {
|
|
||||||
break 'early_return default;
|
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() };
|
let Some(input_type) = input_type else { return Vec::new() };
|
||||||
input_type.clone()
|
input_type.clone()
|
||||||
}
|
}
|
||||||
_ => context
|
_ => {
|
||||||
.network_interface
|
// 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
|
||||||
.input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
|
let declared_type = field.and_then(|field| field.default_type).map(|declared_type| match declared_type {
|
||||||
.compiled_nested_type()
|
Type::Item(element) => *element,
|
||||||
.cloned()
|
declared_type => declared_type,
|
||||||
.unwrap_or(concrete!(())),
|
});
|
||||||
|
|
||||||
|
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)
|
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::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::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::common_functionality::graph_modification_utils;
|
||||||
use crate::messages::tool::tool_messages::tool_prelude::NumberInputMode;
|
|
||||||
use deserialization::deserialize_node_persistent_metadata;
|
use deserialization::deserialize_node_persistent_metadata;
|
||||||
use glam::{DAffine2, DVec2, IVec2};
|
use glam::{DAffine2, DVec2, IVec2};
|
||||||
use graph_craft::Type;
|
use graph_craft::Type;
|
||||||
@@ -72,7 +71,7 @@ use graphene_std::vector::click_target::{ClickTarget, ClickTargetType, FreePoint
|
|||||||
use graphene_std::vector::{Vector, VectorModificationType};
|
use graphene_std::vector::{Vector, VectorModificationType};
|
||||||
use kurbo::BezPath;
|
use kurbo::BezPath;
|
||||||
use memo_network::MemoNetwork;
|
use memo_network::MemoNetwork;
|
||||||
use serde_json::{Value, json};
|
use serde_json::Value;
|
||||||
use std::collections::{HashMap, HashSet, VecDeque};
|
use std::collections::{HashMap, HashSet, VecDeque};
|
||||||
use std::hash::Hash;
|
use std::hash::Hash;
|
||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
|
|||||||
+3
-3
@@ -1,4 +1,4 @@
|
|||||||
use super::template::NodeTemplateImplementation;
|
use super::template::{NodeTemplate, NodeTemplateImplementation};
|
||||||
use super::{InputConnector, OutputConnector, catalog};
|
use super::{InputConnector, OutputConnector, catalog};
|
||||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{network_node_identifiers, resolve_network_node_type};
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::{network_node_identifiers, resolve_network_node_type};
|
||||||
use crate::messages::portfolio::document::storage_tests::test_support::round_trip_through_gdd;
|
use crate::messages::portfolio::document::storage_tests::test_support::round_trip_through_gdd;
|
||||||
@@ -308,7 +308,7 @@ async fn undoing_the_unlock_of_an_open_catalog_node_shows_it_read_only_again() {
|
|||||||
async fn undoing_the_creation_of_an_open_subgraph_leaves_it() {
|
async fn undoing_the_creation_of_an_open_subgraph_leaves_it() {
|
||||||
let mut editor = EditorTestUtils::create();
|
let mut editor = EditorTestUtils::create();
|
||||||
editor.new_document().await;
|
editor.new_document().await;
|
||||||
let subgraph = editor.create_node_by_name(DefinitionIdentifier::Network("Custom Node".to_string())).await;
|
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||||
editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await;
|
editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await;
|
||||||
assert_eq!(editor.active_document().breadcrumb_network_path(), [subgraph]);
|
assert_eq!(editor.active_document().breadcrumb_network_path(), [subgraph]);
|
||||||
|
|
||||||
@@ -349,7 +349,7 @@ async fn a_subgraph_holding_a_catalog_node_pastes_into_a_document_without_it() {
|
|||||||
let custom = NodeId::new();
|
let custom = NodeId::new();
|
||||||
let blend = NodeId::new();
|
let blend = NodeId::new();
|
||||||
let interface = &mut editor.active_document_mut().network_interface;
|
let interface = &mut editor.active_document_mut().network_interface;
|
||||||
interface.insert_node(custom, resolve_network_node_type("Custom Node").expect("Custom Node").default_node_template(), &[]);
|
interface.insert_node(custom, NodeTemplate::empty_subgraph(), &[]);
|
||||||
interface.insert_node(blend, resolve_network_node_type("Blend").expect("Blend").default_node_template(), &[custom]);
|
interface.insert_node(blend, resolve_network_node_type("Blend").expect("Blend").default_node_template(), &[custom]);
|
||||||
let DocumentNodeImplementation::Definition(shipped) = interface.document_node(&blend, &[custom]).expect("the Blend").implementation else {
|
let DocumentNodeImplementation::Definition(shipped) = interface.document_node(&blend, &[custom]).expect("the Blend").implementation else {
|
||||||
panic!("the Blend should name a table entry")
|
panic!("the Blend should name a table entry")
|
||||||
|
|||||||
+18
-6
@@ -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
|
// 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 source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
|
||||||
let shaken = editor
|
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;
|
.await;
|
||||||
let dot = editor.create_node_by_name_at(passthrough_definition(), 20, 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;
|
let consumer = editor.create_node_by_name_at(fill_definition(), 30, 0).await;
|
||||||
@@ -3119,7 +3119,7 @@ async fn imports_and_exports_keep_just_a_grid_cell_from_a_dot() {
|
|||||||
let mut editor = EditorTestUtils::create();
|
let mut editor = EditorTestUtils::create();
|
||||||
editor.new_document().await;
|
editor.new_document().await;
|
||||||
|
|
||||||
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||||
let path = [subgraph];
|
let path = [subgraph];
|
||||||
editor.enter_editable_network(subgraph).await;
|
editor.enter_editable_network(subgraph).await;
|
||||||
|
|
||||||
@@ -3506,7 +3506,7 @@ async fn a_press_right_after_dragging_a_wire_out_of_an_output_drags_another_wire
|
|||||||
|
|
||||||
/// Opens a new subgraph with one node inside, which is all that lies between its import and its export.
|
/// Opens a new subgraph with one node inside, which is all that lies between its import and its export.
|
||||||
async fn subgraph_holding_one_node(editor: &mut EditorTestUtils) -> (NodeId, NodeId) {
|
async fn subgraph_holding_one_node(editor: &mut EditorTestUtils) -> (NodeId, NodeId) {
|
||||||
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||||
editor.enter_editable_network(subgraph).await;
|
editor.enter_editable_network(subgraph).await;
|
||||||
editor.handle_message(NodeGraphMessage::AddImport).await;
|
editor.handle_message(NodeGraphMessage::AddImport).await;
|
||||||
editor.handle_message(NodeGraphMessage::AddPrimaryExport).await;
|
editor.handle_message(NodeGraphMessage::AddPrimaryExport).await;
|
||||||
@@ -4041,18 +4041,30 @@ async fn a_session_preview_of_a_removed_node_is_dropped() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_new_subgraph_is_its_own_definition() {
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
|
||||||
|
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||||
|
let network_interface = &editor.active_document().network_interface;
|
||||||
|
assert!(matches!(network_interface.implementation(&subgraph, &[]), Some(DocumentNodeImplementation::Definition(_))));
|
||||||
|
assert_eq!(network_interface.reference(&subgraph, &[]), None, "it shouldn't name a catalog definition");
|
||||||
|
assert_eq!(network_interface.display_name(&subgraph, &[]), "Subgraph");
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn cannot_preview_node_without_outputs() {
|
async fn cannot_preview_node_without_outputs() {
|
||||||
let mut editor = EditorTestUtils::create();
|
let mut editor = EditorTestUtils::create();
|
||||||
editor.new_document().await;
|
editor.new_document().await;
|
||||||
|
|
||||||
let custom_node = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||||
|
|
||||||
assert_eq!(network_interface.number_of_outputs(&custom_node, &[]), 0);
|
assert_eq!(network_interface.number_of_outputs(&subgraph, &[]), 0);
|
||||||
|
|
||||||
// Attempting to toggle preview on a node without outputs should not enable previewing
|
// Attempting to toggle preview on a node without outputs should not enable previewing
|
||||||
network_interface.toggle_preview(custom_node, &[]);
|
network_interface.toggle_preview(subgraph, &[]);
|
||||||
assert_eq!(network_interface.previewing(&[]), Previewing::No);
|
assert_eq!(network_interface.previewing(&[]), Previewing::No);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::ARTBOARD_CLIP_INPUT_INDEX;
|
||||||
use std::hash::{Hash, Hasher};
|
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 {
|
impl NodeNetworkInterface {
|
||||||
/// Runs a query against a resolved [`NetworkView`], logging any error at this message-boundary wrapper and mapping it to None.
|
/// 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> {
|
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> {
|
||||||
@@ -802,7 +800,7 @@ impl NodeNetworkInterface {
|
|||||||
self.query(network_path, "reference", |view| view.reference(node_id)).flatten()
|
self.query(network_path, "reference", |view| view.reference(node_id)).flatten()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The icon of the node's definition, or the Custom Node icon when its definition has none or can't be found.
|
/// The icon of the node's definition, or the generic subgraph icon when its definition has none or can't be found.
|
||||||
pub fn node_icon(&self, node_id: &NodeId, network_path: &[NodeId]) -> &'static str {
|
pub fn node_icon(&self, node_id: &NodeId, network_path: &[NodeId]) -> &'static str {
|
||||||
self.reference(node_id, network_path)
|
self.reference(node_id, network_path)
|
||||||
.and_then(|reference| resolve_document_node_type(&reference)?.icon)
|
.and_then(|reference| resolve_document_node_type(&reference)?.icon)
|
||||||
@@ -829,17 +827,26 @@ impl NodeNetworkInterface {
|
|||||||
self.view(network_path).ok().and_then(|view| view.persistent_input_metadata(node_id, index).ok())
|
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 {
|
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 {
|
self.field_metadata(node_id, index, network_path).is_some_and(|field| field.internal)
|
||||||
return false;
|
}
|
||||||
};
|
|
||||||
let Ok(node_metadata) = graphene_std::registry::NODE_METADATA.lock() else { return false };
|
|
||||||
|
|
||||||
node_metadata
|
/// The metadata the node macro records for a proto node's parameter, or graph text describes for a graph node's import.
|
||||||
.get(proto_node_identifier)
|
/// A graph node's input has it only while it still has that import's name, since an edited subgraph can reorder its imports.
|
||||||
.and_then(|metadata| metadata.fields.get(index))
|
pub fn field_metadata(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> Option<graphene_std::registry::FieldMetadata> {
|
||||||
.is_some_and(|field| field.internal)
|
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 field = graphene_std::graph_text::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.
|
/// 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.
|
||||||
@@ -875,16 +882,16 @@ impl NodeNetworkInterface {
|
|||||||
node.set_widget_override(index, widget_override);
|
node.set_widget_override(index, widget_override);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns the display name of the node. If the display name is empty, it will return "Untitled Node" or "Untitled Layer" depending on the node type.
|
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
|
||||||
pub fn display_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
pub fn display_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
||||||
self.query(network_path, "display_name", |view| Ok(view.display_name(node_id)))
|
self.query(network_path, "display_name", |view| Ok(view.display_name(node_id)))
|
||||||
.unwrap_or_else(|| "Custom Node".to_string())
|
.unwrap_or_else(|| "Subgraph".to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The uneditable name in the Inspector which represents the function name of the node implementation.
|
/// The uneditable name in the Inspector which represents the function name of the node implementation.
|
||||||
pub fn implementation_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
pub fn implementation_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
||||||
self.query(network_path, "implementation_name", |view| Ok(view.implementation_name(node_id)))
|
self.query(network_path, "implementation_name", |view| Ok(view.implementation_name(node_id)))
|
||||||
.unwrap_or_else(|| "Custom Node".to_string())
|
.unwrap_or_else(|| "Subgraph".to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_locked(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
|
pub fn is_locked(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
|
||||||
|
|||||||
@@ -38,6 +38,14 @@ pub struct NodeTemplate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl NodeTemplate {
|
impl NodeTemplate {
|
||||||
|
/// A new subgraph with nothing in it, which names no definition since it becomes its own entry in the document's definitions table.
|
||||||
|
pub fn empty_subgraph() -> Self {
|
||||||
|
Self {
|
||||||
|
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The input slot named by the given parameter symbol, mirroring [`DocumentNode::input`].
|
/// The input slot named by the given parameter symbol, mirroring [`DocumentNode::input`].
|
||||||
pub fn input<P: graphene_std::NodeParameter>(&self, _parameter: P) -> Option<&NodeInput> {
|
pub fn input<P: graphene_std::NodeParameter>(&self, _parameter: P) -> Option<&NodeInput> {
|
||||||
self.inputs.get(P::INDEX)
|
self.inputs.get(P::INDEX)
|
||||||
|
|||||||
@@ -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)]
|
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
pub enum WidgetOverride {
|
pub enum WidgetOverride {
|
||||||
None,
|
None,
|
||||||
Hidden,
|
Hidden,
|
||||||
String(String),
|
String(String),
|
||||||
Number(NumberInputSettings),
|
|
||||||
Vec2(Vec2InputSettings),
|
|
||||||
Custom(String),
|
Custom(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -948,40 +908,6 @@ impl InputPersistentMetadata {
|
|||||||
self.input_data.insert("string_inspector".to_string(), Value::String(string_inspector));
|
self.input_data.insert("string_inspector".to_string(), Value::String(string_inspector));
|
||||||
self.widget_override = Some("string".to_string());
|
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) => {
|
WidgetOverride::Custom(lambda_name) => {
|
||||||
self.widget_override = Some(lambda_name);
|
self.widget_override = Some(lambda_name);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -169,7 +169,7 @@ impl<'a, 'p> NetworkView<'a, 'p> {
|
|||||||
.ok()
|
.ok()
|
||||||
.flatten()
|
.flatten()
|
||||||
.map(|identifier| identifier.implementation_name_from_identifier())
|
.map(|identifier| identifier.implementation_name_from_identifier())
|
||||||
.unwrap_or("Custom Node".to_string())
|
.unwrap_or("Subgraph".to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
|
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
|
||||||
|
|||||||
@@ -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.
|
// 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 {
|
NodeReplacement {
|
||||||
node: graphene_std::math_nodes::vec_2_value::IDENTIFIER,
|
node: graphene_std::math_nodes::vec2_value::IDENTIFIER,
|
||||||
aliases: &[
|
aliases: &[
|
||||||
"graphene_math_nodes::Vec2ValueNode",
|
"graphene_math_nodes::Vec2ValueNode",
|
||||||
"graphene_core::ops::ConstructVector2",
|
"graphene_core::ops::ConstructVector2",
|
||||||
@@ -484,7 +484,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
NodeReplacement {
|
NodeReplacement {
|
||||||
node: graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER,
|
node: graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER,
|
||||||
aliases: &["math_nodes::CombineVec2Node"],
|
aliases: &["math_nodes::CombineVec2Node"],
|
||||||
},
|
},
|
||||||
// ================================
|
// ================================
|
||||||
@@ -1295,7 +1295,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The "Transform" wrapper network was replaced with the `transform` proto node directly. Convert old `Network("Transform")` instances to the proto node, forwarding the 5 user-facing inputs (Value, Translation, Rotation, Scale, Skew) and dropping the legacy migration sentinels (Origin Offset, Scale Appearance) at indices 5 and 6 if present.
|
// The "Transform" wrapper network was replaced with the `transform` proto node directly. Convert old `Network("Transform")` instances to the proto node, forwarding the 5 user-facing inputs (Value, Translation, Rotation, Scale, Skew) and dropping the legacy migration sentinels (Origin Offset, Scale Appearance) at indices 5 and 6 if present.
|
||||||
// Some old documents store it as a Custom Node subgraph with no reference, where a Monitor feeds the Transform proto node. Those are converted the same way.
|
// Some old documents store it as a subgraph with no reference, where a Monitor feeds the Transform proto node. Those are converted the same way.
|
||||||
// Pre-pass for the same reason as the Brush migration above: replacing the outer Transform's network impl orphans its child paths.
|
// Pre-pass for the same reason as the Brush migration above: replacing the outer Transform's network impl orphans its child paths.
|
||||||
let transform_layers: Vec<(NodeId, Vec<NodeId>, usize)> = document
|
let transform_layers: Vec<(NodeId, Vec<NodeId>, usize)> = document
|
||||||
.network_interface
|
.network_interface
|
||||||
@@ -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.
|
// 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.
|
// 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 = [
|
let split_wrapper_replacements = [
|
||||||
("Split Vec2", 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::vec_2_to_numbers::IDENTIFIER),
|
("Split Vector2", graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER),
|
||||||
("Split Channels", graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER),
|
("Split Channels", graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER),
|
||||||
];
|
];
|
||||||
for (old_reference, new_identifier) in split_wrapper_replacements {
|
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 DocumentNodeImplementation::ProtoNode(protonode_id) = &node.implementation else { return None };
|
||||||
let name = protonode_id.as_str().split('<').next().unwrap_or_default();
|
let name = protonode_id.as_str().split('<').next().unwrap_or_default();
|
||||||
if EXTRACT_XY.contains(&name) {
|
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) {
|
} else if EXTRACT_CHANNEL.contains(&name) {
|
||||||
Some((*node_id, path, graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER, "Extract Channel"))
|
Some((*node_id, path, graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER, "Extract Channel"))
|
||||||
} else {
|
} else {
|
||||||
@@ -1771,6 +1771,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
|||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
|
migrate_custom_node_subgraphs(document);
|
||||||
|
|
||||||
// Apply upgrades to each unmodified node, except those inside the read-only built-in subgraphs
|
// Apply upgrades to each unmodified node, except those inside the read-only built-in subgraphs
|
||||||
let nodes = document
|
let nodes = document
|
||||||
.network_interface
|
.network_interface
|
||||||
@@ -2854,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,
|
// 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)
|
// 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 {
|
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_vec_2::IDENTIFIER);
|
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();
|
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);
|
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||||
|
|
||||||
@@ -4045,6 +4047,25 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
|
|||||||
Some(())
|
Some(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Gives each subgraph made from the removed Custom Node definition, from the catalog or by merging selected nodes, no reference and no default name, like one made with the New Custom Node button.
|
||||||
|
/// Instances can share a definitions table entry holding the reference, so all of them are found before any is changed.
|
||||||
|
fn migrate_custom_node_subgraphs(document: &mut DocumentMessageHandler) {
|
||||||
|
let custom_node = Some(DefinitionIdentifier::Network("Custom Node".into()));
|
||||||
|
let subgraphs: Vec<(NodeId, Vec<NodeId>)> = document
|
||||||
|
.network_interface
|
||||||
|
.document_network()
|
||||||
|
.recursive_nodes()
|
||||||
|
.filter(|(node_id, _, path)| document.network_interface.reference(node_id, path) == custom_node)
|
||||||
|
.map(|(node_id, _, path)| (*node_id, path))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
for (node_id, network_path) in subgraphs {
|
||||||
|
reset_default_display_name(document, &node_id, &network_path, "Custom Node");
|
||||||
|
reset_default_display_name(document, &node_id, &network_path, "Untitled Node");
|
||||||
|
document.network_interface.set_reference(&node_id, &network_path, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Splits each removed Math f(…) node by the kind of string it held, into Math Aggregate or Math Formula.
|
/// Splits each removed Math f(…) node by the kind of string it held, into Math Aggregate or Math Formula.
|
||||||
fn migrate_math_f_nodes(document: &mut DocumentMessageHandler) {
|
fn migrate_math_f_nodes(document: &mut DocumentMessageHandler) {
|
||||||
let math_f_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
let math_f_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||||
@@ -4597,6 +4618,45 @@ mod tests {
|
|||||||
assert!(errors.is_empty(), "opening the document logged errors: {errors:?}");
|
assert!(errors.is_empty(), "opening the document logged errors: {errors:?}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn opening_custom_node_subgraphs_drops_their_reference_and_default_names() {
|
||||||
|
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplateImplementation;
|
||||||
|
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||||
|
use crate::test_utils::test_prelude::*;
|
||||||
|
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||||
|
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
let from_catalog = editor.create_empty_subgraph_at(0, 0).await;
|
||||||
|
let document = editor.active_document_mut();
|
||||||
|
let Some(DocumentNodeImplementation::Definition(shared)) = document.network_interface.implementation(&from_catalog, &[]).cloned() else {
|
||||||
|
panic!("the subgraph should name a definitions table entry")
|
||||||
|
};
|
||||||
|
|
||||||
|
// A second instance of the same table entry, named as Merge Selected Nodes named the subgraphs it made
|
||||||
|
let from_merging = NodeId::new();
|
||||||
|
let instance = NodeTemplate {
|
||||||
|
implementation: NodeTemplateImplementation::Definition(shared),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
document.network_interface.insert_node(from_merging, instance, &[]);
|
||||||
|
document.network_interface.set_reference(&from_catalog, &[], Some("Custom Node".into()));
|
||||||
|
document.network_interface.set_display_name(&from_catalog, "Custom Node".into(), &[]);
|
||||||
|
document.network_interface.set_display_name(&from_merging, "Untitled Node".into(), &[]);
|
||||||
|
let serialized = document.serialize_document();
|
||||||
|
|
||||||
|
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||||
|
let interface = &opened.network_interface;
|
||||||
|
for node_id in [from_catalog, from_merging] {
|
||||||
|
assert!(
|
||||||
|
matches!(interface.implementation(&node_id, &[]), Some(DocumentNodeImplementation::Definition(_))),
|
||||||
|
"the subgraph should still exist"
|
||||||
|
);
|
||||||
|
assert_eq!(interface.reference(&node_id, &[]), None);
|
||||||
|
assert_eq!(interface.display_name(&node_id, &[]), "Subgraph");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn a_rasterize_node_on_the_export_compiles() {
|
async fn a_rasterize_node_on_the_export_compiles() {
|
||||||
use crate::test_utils::test_prelude::*;
|
use crate::test_utils::test_prelude::*;
|
||||||
@@ -5083,7 +5143,11 @@ mod tests {
|
|||||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||||
panic!("Blend should be a network node")
|
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.implementation = NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::floor::IDENTIFIER);
|
||||||
count_conversion.inputs = vec![NodeInput::import(item!(f64), 1)];
|
count_conversion.inputs = vec![NodeInput::import(item!(f64), 1)];
|
||||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||||
@@ -5100,7 +5164,7 @@ mod tests {
|
|||||||
panic!("Blend should stay a network node")
|
panic!("Blend should stay a network node")
|
||||||
};
|
};
|
||||||
assert_eq!(
|
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)
|
DocumentNodeImplementation::ProtoNode(graphene_std::math_nodes::as_number::IDENTIFIER)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -5117,7 +5181,11 @@ mod tests {
|
|||||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||||
panic!("Blend should be a network node")
|
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);
|
edited_subtract.inputs[1] = NodeInput::value(TaggedValue::Number(42.), false);
|
||||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||||
|
|
||||||
@@ -5127,7 +5195,7 @@ mod tests {
|
|||||||
let (DocumentNodeImplementation::Definition(definition), Some(inner)) = (implementation, document.network_interface.document_network().implementation_network(implementation)) else {
|
let (DocumentNodeImplementation::Definition(definition), Some(inner)) = (implementation, document.network_interface.document_network().implementation_network(implementation)) else {
|
||||||
panic!("Blend should stay a network node")
|
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.)));
|
assert_eq!(inner.nodes[&edited_subtract].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::Number(42.)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -5209,8 +5277,15 @@ mod tests {
|
|||||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||||
panic!("Regex Find should be a network node")
|
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);
|
let inner_node_id = |identifier: graphene_std::ProtoNodeIdentifier| {
|
||||||
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 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, &[]);
|
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||||
|
|
||||||
migrate(&mut document);
|
migrate(&mut document);
|
||||||
@@ -5224,9 +5299,9 @@ mod tests {
|
|||||||
let Some(inner) = document.network_interface.document_network().implementation_network(&node.implementation) else {
|
let Some(inner) = document.network_interface.document_network().implementation_network(&node.implementation) else {
|
||||||
panic!("Regex Find should stay a network node")
|
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!(
|
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))
|
Some(TaggedValue::Integer(0))
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -398,7 +398,8 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
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 crate::test_utils::test_prelude::*;
|
||||||
use glam::UVec2;
|
use glam::UVec2;
|
||||||
use graph_craft::document::NodeId;
|
use graph_craft::document::NodeId;
|
||||||
@@ -429,8 +430,20 @@ mod tests {
|
|||||||
editor.draw_rect(0., 0., 10., 10.).await;
|
editor.draw_rect(0., 0., 10., 10.).await;
|
||||||
let layer = editor.get_selected_layer().await.expect("The drawn rectangle should be selected").to_node();
|
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;
|
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!(merge_content.is_some(), "The Merge layer's content should be compiled");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
editor.runtime.thumbnails.sources.get(&layer).copied(),
|
editor.runtime.thumbnails.sources.get(&layer).copied(),
|
||||||
|
|||||||
@@ -423,6 +423,17 @@ impl EditorTestUtils {
|
|||||||
self.create_node(node_type, Some((x, y))).await
|
self.create_node(node_type, Some((x, y))).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Adds an empty subgraph at the grid position, as the graph's New Custom Node button does.
|
||||||
|
pub async fn create_empty_subgraph_at(&mut self, x: i32, y: i32) -> NodeId {
|
||||||
|
let node_id = NodeId::new();
|
||||||
|
self.handle_message(NodeGraphMessage::CreateEmptySubgraph {
|
||||||
|
node_id: Some(node_id),
|
||||||
|
xy: Some((x, y)),
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
node_id
|
||||||
|
}
|
||||||
|
|
||||||
async fn create_node(&mut self, node_type: DefinitionIdentifier, xy: Option<(i32, i32)>) -> NodeId {
|
async fn create_node(&mut self, node_type: DefinitionIdentifier, xy: Option<(i32, i32)>) -> NodeId {
|
||||||
let node_id = NodeId::new();
|
let node_id = NodeId::new();
|
||||||
self.handle_message(NodeGraphMessage::CreateNodeFromContextMenu {
|
self.handle_message(NodeGraphMessage::CreateNodeFromContextMenu {
|
||||||
|
|||||||
+35
-2
@@ -32,7 +32,7 @@ pub struct DocumentNodeDefinition {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Only the definitions of nodes built from a nested network, such as the empty "Custom Node", 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 its graph text (see [Creating a node from a subgraph](#creating-a-node-from-a-subgraph)), keyed by its name.
|
||||||
|
|
||||||
## Inspector
|
## Inspector
|
||||||
|
|
||||||
@@ -127,7 +127,40 @@ fn opacity<T>(
|
|||||||
|
|
||||||
## Additional Macro Options
|
## 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 is written in graph text, a Rust-like syntax parsed at runtime by the `graph-text` crate. Built-in graphs are registered with the `core_types::graph!` macro, which only records the text and where it's written. This is the Load Image node as it exists in `node-graph/nodes/gstd/src/subgraphs.rs`:
|
||||||
|
|
||||||
|
```rs
|
||||||
|
graph! {
|
||||||
|
#![syntax(1)]
|
||||||
|
use graphene_std::platform_application_io::{bytes_to_image@1, load_resource@1};
|
||||||
|
|
||||||
|
/// Loads an image from a given URL.
|
||||||
|
#[category("Data: I/O"), icon("NodeLoadImage")]
|
||||||
|
fn load_image@1(
|
||||||
|
_,
|
||||||
|
/// The web address or local asset path of the image to load.
|
||||||
|
#[name("URL")]
|
||||||
|
url,
|
||||||
|
) -> (
|
||||||
|
/// The loaded image.
|
||||||
|
image,
|
||||||
|
) {
|
||||||
|
load_resource(url) >> bytes_to_image()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The text starts with its syntax version, `#![syntax(1)]`. The `use` section names each node by its identifier's module path and function name, at the declaration version it was written for, and `as` renames one. A graph's own version follows its name, like `load_image@1`. The graph's attributes are `category`, `icon`, `name`, and `layer`, and its name (or the title derived from its function name) is its catalog identifier, which documents store.
|
||||||
|
|
||||||
|
The function's parameters are the subgraph's imports, written without types, and `_` is a primary import that takes nothing. An import inherits its type, default, description, and widget settings from the inner parameter of its own name that it feeds, or else from the first one, and its attributes override those: `name`, `expose`, `default`, `widget`, `unit`, `hard`, `soft`, `range`, `step`, `display_decimal_places`, `multiline`, `progression`, `labels`, `integer`, and `blank_assist`. The exports are named in parentheses after `->`.
|
||||||
|
|
||||||
|
In the body, `let` binds a node, `>>` 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. A value has the type it's written with, so `1` is an integer and `1.` a number, and `#[exposed]` before an argument exposes its value. State methods after a call, each written once, set the node's display name (`.named("…")`) and flags (`.layer()`, `.hidden()`, `.locked()`, and `.pinned()`). Nodes are placed left of the node they feed, so positions are only written to adjust that, with `.offset(x, y)` or `.at(x, y)` in grid units. A graph's output name after a call or binding, like `.captures`, wires from that output instead of the primary one. The body ends with one value per export.
|
||||||
|
|
||||||
|
The `every_graph_resolves` test in `subgraphs.rs` reports any graph whose text doesn't resolve, with the place it's written. Every input a call leaves out keeps the default from the node's own definition.
|
||||||
|
|
||||||
## Executing a document `NodeNetwork`
|
## Executing a document `NodeNetwork`
|
||||||
|
|
||||||
|
|||||||
@@ -35,6 +35,8 @@ pub struct NodeFlags {
|
|||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct FieldMetadata {
|
pub struct FieldMetadata {
|
||||||
pub name: &'static str,
|
pub name: &'static str,
|
||||||
|
/// The parameter's name in the node function, which graph text uses to set it.
|
||||||
|
pub identifier: &'static str,
|
||||||
pub description: &'static str,
|
pub description: &'static str,
|
||||||
/// Whether the parameter is internal state of its node (named with a leading `_`), which is never exposed to the graph.
|
/// Whether the parameter is internal state of its node (named with a leading `_`), which is never exposed to the graph.
|
||||||
pub internal: bool,
|
pub internal: bool,
|
||||||
@@ -60,6 +62,12 @@ pub struct FieldMetadata {
|
|||||||
pub progression: bool,
|
pub progression: bool,
|
||||||
/// Whether the input must be fed by a value known at compile time, from `#[constant]`.
|
/// Whether the input must be fed by a value known at compile time, from `#[constant]`.
|
||||||
pub constant: bool,
|
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)]
|
#[derive(Clone, Debug)]
|
||||||
@@ -222,6 +230,146 @@ 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()));
|
pub static NODE_METADATA: LazyLock<Mutex<HashMap<ProtoNodeIdentifier, NodeMetadata>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||||
|
|
||||||
|
/// The graph text of every `graph!` invocation, in registration order.
|
||||||
|
pub static GRAPH_SOURCES: LazyLock<Mutex<Vec<GraphSource>>> = LazyLock::new(|| Mutex::new(Vec::new()));
|
||||||
|
|
||||||
|
/// The text of one `graph!` invocation and where it's written, for error messages.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct GraphSource {
|
||||||
|
/// The module the graph is defined in, which qualifies its name in `use` paths.
|
||||||
|
pub module_path: &'static str,
|
||||||
|
pub file: &'static str,
|
||||||
|
pub line: u32,
|
||||||
|
pub column: u32,
|
||||||
|
pub text: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Registers graph text as a built-in subgraph node, which the editor turns into a catalog definition.
|
||||||
|
///
|
||||||
|
/// Each invocation registers itself under a symbol named after its crate, line, and column, so two invocations at the
|
||||||
|
/// same line and column in different files of one crate fail to link.
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! graph {
|
||||||
|
($($source:tt)*) => {
|
||||||
|
const _: () = {
|
||||||
|
use $crate as gcore;
|
||||||
|
use gcore::ctor::ctor;
|
||||||
|
|
||||||
|
#[cfg_attr(not(target_family = "wasm"), ctor(unsafe, crate_path = gcore::ctor))]
|
||||||
|
#[unsafe(export_name = concat!("__node_registry_graph_", env!("CARGO_CRATE_NAME"), "_", line!(), "_", column!()))]
|
||||||
|
extern "C" fn register_graph() {
|
||||||
|
gcore::registry::GRAPH_SOURCES.lock().unwrap().push(gcore::registry::GraphSource {
|
||||||
|
module_path: module_path!(),
|
||||||
|
file: file!(),
|
||||||
|
line: line!(),
|
||||||
|
column: column!(),
|
||||||
|
text: stringify!($($source)*),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A node defined as a subgraph in graph text, 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,
|
||||||
|
/// The module path and function name that `use` paths in graph text name the graph by.
|
||||||
|
pub path: &'static str,
|
||||||
|
pub category: &'static str,
|
||||||
|
pub icon: Option<&'static str>,
|
||||||
|
pub description: &'static str,
|
||||||
|
/// The declaration version from `fn name@N`, starting at 1.
|
||||||
|
pub version: u32,
|
||||||
|
/// Whether a new instance starts as a layer, from `#[layer]`.
|
||||||
|
pub layer: bool,
|
||||||
|
/// The subgraph's imports, which become the inputs of each instance, described like a proto node's parameters.
|
||||||
|
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,
|
||||||
|
/// The export's name in graph text, which chooses it as an output.
|
||||||
|
pub identifier: &'static str,
|
||||||
|
pub description: &'static str,
|
||||||
|
pub source: GraphInputSource,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A node inside a subgraph defined in graph text.
|
||||||
|
#[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 position in grid units.
|
||||||
|
pub position: (i32, i32),
|
||||||
|
pub layer: bool,
|
||||||
|
pub display_name: Option<&'static str>,
|
||||||
|
pub hidden: bool,
|
||||||
|
pub locked: bool,
|
||||||
|
pub pinned: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a node inside a subgraph is an instance of.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub enum GraphNodeImplementation {
|
||||||
|
ProtoNode(ProtoNodeIdentifier),
|
||||||
|
/// Another subgraph node, named by its identifier.
|
||||||
|
Graph(&'static str),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What feeds an input, or an export, of a subgraph defined in graph text.
|
||||||
|
#[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 graph text, whose type is set by how it's written.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub enum GraphValue {
|
||||||
|
/// A number written without a fractional part.
|
||||||
|
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())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// All multi-output proto nodes (those returning a [`Destructure`] struct), keyed by their identifier.
|
/// 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.
|
/// 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(|| {
|
pub static MULTI_OUTPUT_NODES: LazyLock<HashMap<ProtoNodeIdentifier, DestructureMetadata>> = LazyLock::new(|| {
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
[package]
|
||||||
|
name = "graph-text"
|
||||||
|
description = "Parses the graph text format, which defines subgraph nodes in a Rust-like syntax"
|
||||||
|
version.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
authors.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
readme.workspace = true
|
||||||
|
homepage.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
# Local dependencies
|
||||||
|
core-types = { workspace = true }
|
||||||
|
|
||||||
|
# Workspace dependencies
|
||||||
|
syn = { workspace = true }
|
||||||
|
proc-macro2 = { workspace = true }
|
||||||
|
glam = { workspace = true }
|
||||||
|
convert_case = { workspace = true }
|
||||||
|
log = { workspace = true }
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
//! The default placement of a graph's nodes, relative to the nodes they feed.
|
||||||
|
|
||||||
|
/// How far apart, in grid units, a node is placed from the node it feeds.
|
||||||
|
const COLUMN_WIDTH: i32 = 7;
|
||||||
|
|
||||||
|
/// A node's wires and its written placement, as the layout reads them.
|
||||||
|
pub struct LayoutNode {
|
||||||
|
/// The node feeding the primary input.
|
||||||
|
pub primary: Option<usize>,
|
||||||
|
/// The nodes feeding the other inputs, in the order they're written.
|
||||||
|
pub secondaries: Vec<usize>,
|
||||||
|
/// The absolute position from `.at(x, y)`, which replaces the default one.
|
||||||
|
pub at: Option<(i32, i32)>,
|
||||||
|
/// The nudge from `.offset(x, y)`, added to the default position.
|
||||||
|
pub offset: (i32, i32),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Places each node in the column left of the first node it feeds. A node feeding a primary input shares that node's row,
|
||||||
|
/// and one feeding another input goes in a new row below everything placed so far. Each export's node starts a new row.
|
||||||
|
pub fn layout(nodes: &[LayoutNode], roots: &[usize]) -> Vec<(i32, i32)> {
|
||||||
|
let mut placement = Placement {
|
||||||
|
nodes,
|
||||||
|
positions: vec![None; nodes.len()],
|
||||||
|
bottom: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
for &root in roots {
|
||||||
|
let row = placement.next_row();
|
||||||
|
placement.place(root, 0, row);
|
||||||
|
}
|
||||||
|
for node in 0..nodes.len() {
|
||||||
|
let row = placement.next_row();
|
||||||
|
placement.place(node, 0, row);
|
||||||
|
}
|
||||||
|
|
||||||
|
placement.positions.into_iter().map(Option::unwrap_or_default).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Placement<'a> {
|
||||||
|
nodes: &'a [LayoutNode],
|
||||||
|
positions: Vec<Option<(i32, i32)>>,
|
||||||
|
/// The lowest row used so far.
|
||||||
|
bottom: Option<i32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Placement<'_> {
|
||||||
|
fn next_row(&self) -> i32 {
|
||||||
|
self.bottom.map_or(0, |bottom| bottom + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn place(&mut self, node: usize, x: i32, y: i32) {
|
||||||
|
if self.positions[node].is_some() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let LayoutNode { primary, secondaries, at, offset } = &self.nodes[node];
|
||||||
|
let (x, y) = at.unwrap_or((x + offset.0, y + offset.1));
|
||||||
|
self.positions[node] = Some((x, y));
|
||||||
|
self.bottom = Some(self.bottom.map_or(y, |bottom| bottom.max(y)));
|
||||||
|
|
||||||
|
if let Some(primary) = primary {
|
||||||
|
self.place(*primary, x - COLUMN_WIDTH, y);
|
||||||
|
}
|
||||||
|
for &secondary in secondaries {
|
||||||
|
let row = self.next_row();
|
||||||
|
self.place(secondary, x - COLUMN_WIDTH, row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn node(primary: Option<usize>, secondaries: Vec<usize>) -> LayoutNode {
|
||||||
|
LayoutNode {
|
||||||
|
primary,
|
||||||
|
secondaries,
|
||||||
|
at: None,
|
||||||
|
offset: (0, 0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn chains_run_left_and_side_inputs_go_below() {
|
||||||
|
// Merge: `base >> as_graphic() >> extend(new = content >> into_group())`
|
||||||
|
let nodes = [node(None, vec![]), node(None, vec![]), node(Some(0), vec![1])];
|
||||||
|
assert_eq!(layout(&nodes, &[2]), [(-7, 0), (-7, 1), (0, 0)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn written_placement_moves_a_node_and_its_upstream() {
|
||||||
|
let mut offset = node(None, vec![]);
|
||||||
|
offset.offset = (0, 2);
|
||||||
|
let mut at = node(Some(0), vec![]);
|
||||||
|
at.at = Some((10, -4));
|
||||||
|
|
||||||
|
assert_eq!(layout(&[offset, at], &[1]), [(3, -2), (10, -4)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn each_export_and_unexported_node_starts_a_new_row() {
|
||||||
|
let nodes = [node(None, vec![]), node(None, vec![]), node(None, vec![])];
|
||||||
|
assert_eq!(layout(&nodes, &[0, 1]), [(0, 0), (0, 1), (0, 2)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
//! Graph text, which defines a subgraph node in a Rust-like syntax that is parsed at runtime.
|
||||||
|
//!
|
||||||
|
//! Built-in graphs are written in `core_types::graph!` invocations, which register their text at startup.
|
||||||
|
|
||||||
|
mod layout;
|
||||||
|
mod resolve;
|
||||||
|
mod syntax;
|
||||||
|
|
||||||
|
use core_types::ProtoNodeIdentifier;
|
||||||
|
use core_types::registry::{GRAPH_SOURCES, GraphMetadata, GraphSource, NODE_METADATA, NodeMetadata};
|
||||||
|
use resolve::{Context, ResolveError};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::fmt;
|
||||||
|
use std::sync::LazyLock;
|
||||||
|
pub use syntax::SYNTAX_VERSION;
|
||||||
|
|
||||||
|
/// Every registered graph that resolves, in registration order. Resolved on first access, which must happen after
|
||||||
|
/// startup registration of the nodes and graphs completes. Each graph that fails is left out and its error logged.
|
||||||
|
pub static GRAPHS: LazyLock<Vec<GraphMetadata>> = LazyLock::new(|| {
|
||||||
|
let sources = GRAPH_SOURCES.lock().map(|sources| sources.clone()).unwrap_or_default();
|
||||||
|
let Ok(proto_nodes) = NODE_METADATA.lock() else {
|
||||||
|
log::error!("The node metadata is poisoned, so no graph resolves");
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
|
||||||
|
let (graphs, errors) = resolve_sources(&sources, &proto_nodes);
|
||||||
|
for error in errors {
|
||||||
|
log::error!("{error}");
|
||||||
|
}
|
||||||
|
graphs
|
||||||
|
});
|
||||||
|
|
||||||
|
/// The position of a registered graph's import, by the graph's identifier and the import's name.
|
||||||
|
pub fn import_index(graph: &str, import: &str) -> Option<usize> {
|
||||||
|
GRAPHS.iter().find(|metadata| metadata.identifier == graph)?.imports.iter().position(|field| field.identifier == import)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An error in graph text, with the place it's written.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct GraphTextError {
|
||||||
|
pub message: String,
|
||||||
|
pub file: &'static str,
|
||||||
|
pub line: u32,
|
||||||
|
pub column: u32,
|
||||||
|
/// The graph text from the error onward, which locates it within the text.
|
||||||
|
pub excerpt: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for GraphTextError {
|
||||||
|
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(formatter, "{}:{}:{}: {} (at `{}`)", self.file, self.line, self.column, self.message, self.excerpt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GraphTextError {
|
||||||
|
fn new(source: &GraphSource, error: syn::Error) -> Vec<Self> {
|
||||||
|
error
|
||||||
|
.into_iter()
|
||||||
|
.map(|error| {
|
||||||
|
let start = error.span().start();
|
||||||
|
let excerpt = source
|
||||||
|
.text
|
||||||
|
.lines()
|
||||||
|
.nth(start.line.saturating_sub(1))
|
||||||
|
.map(|line| line.chars().skip(start.column).take(40).collect::<String>())
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
Self {
|
||||||
|
message: error.to_string(),
|
||||||
|
file: source.file,
|
||||||
|
line: source.line,
|
||||||
|
column: source.column,
|
||||||
|
excerpt: excerpt.trim().to_string(),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses and resolves graph sources. A graph using another one resolves once that one has, whatever the order.
|
||||||
|
pub fn resolve_sources(sources: &[GraphSource], proto_nodes: &HashMap<ProtoNodeIdentifier, NodeMetadata>) -> (Vec<GraphMetadata>, Vec<GraphTextError>) {
|
||||||
|
let mut errors = Vec::new();
|
||||||
|
|
||||||
|
let mut pending = Vec::new();
|
||||||
|
for source in sources {
|
||||||
|
match syn::parse_str::<syntax::Source>(source.text) {
|
||||||
|
Ok(parsed) => pending.push((source, parsed, None)),
|
||||||
|
Err(error) => errors.extend(GraphTextError::new(source, error)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut graphs = Vec::new();
|
||||||
|
loop {
|
||||||
|
let pending_count = pending.len();
|
||||||
|
|
||||||
|
let mut still_pending = Vec::new();
|
||||||
|
for (source, parsed, _) in pending {
|
||||||
|
let context = Context { proto_nodes, graphs: &graphs };
|
||||||
|
match resolve::resolve(&parsed, source.module_path, &context) {
|
||||||
|
Ok(graph) => graphs.push(graph),
|
||||||
|
Err(ResolveError::Invalid(error)) => errors.extend(GraphTextError::new(source, error)),
|
||||||
|
Err(ResolveError::Unresolved(error)) => still_pending.push((source, parsed, Some(error))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pending = still_pending;
|
||||||
|
|
||||||
|
if pending.is_empty() || pending.len() == pending_count {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (source, _, error) in pending {
|
||||||
|
if let Some(error) = error {
|
||||||
|
errors.extend(GraphTextError::new(source, error));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
(graphs, errors)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,749 @@
|
|||||||
|
//! Resolves parsed graph text against the registered nodes and graphs, producing the graph's `GraphMetadata`.
|
||||||
|
|
||||||
|
use crate::layout::{LayoutNode, layout};
|
||||||
|
use crate::syntax::{Attribute, Expression, GraphItem, Import, Source, StateKind, Use, ValueKind, doc_comment};
|
||||||
|
use convert_case::{Case, Casing};
|
||||||
|
use core_types::registry::{
|
||||||
|
FieldMetadata, GraphExportMetadata, GraphInputSource, GraphMetadata, GraphNodeImplementation, GraphNodeMetadata, GraphValue, NodeMetadata, RegistryValueSource, RegistryWidgetOverride,
|
||||||
|
};
|
||||||
|
use core_types::{ProtoNodeIdentifier, Type, concrete, generic};
|
||||||
|
use proc_macro2::Span;
|
||||||
|
use std::collections::{HashMap, HashSet};
|
||||||
|
use syn::ext::IdentExt;
|
||||||
|
use syn::parse::{ParseStream, Parser};
|
||||||
|
use syn::{Error, Ident, LitBool, LitInt, LitStr, Token};
|
||||||
|
|
||||||
|
/// The registered nodes and the graphs resolved so far, which graph text can use.
|
||||||
|
pub struct Context<'a> {
|
||||||
|
pub proto_nodes: &'a HashMap<ProtoNodeIdentifier, NodeMetadata>,
|
||||||
|
pub graphs: &'a [GraphMetadata],
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum ResolveError {
|
||||||
|
/// A used name matches nothing yet, which may be a graph that resolves later.
|
||||||
|
Unresolved(Error),
|
||||||
|
Invalid(Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<Error> for ResolveError {
|
||||||
|
fn from(error: Error) -> Self {
|
||||||
|
Self::Invalid(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a used name refers to.
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
enum Target<'a> {
|
||||||
|
ProtoNode(&'a ProtoNodeIdentifier, &'a NodeMetadata),
|
||||||
|
Graph(&'a GraphMetadata),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Target<'a> {
|
||||||
|
fn parameters(&self) -> &'a [FieldMetadata] {
|
||||||
|
match self {
|
||||||
|
Self::ProtoNode(_, metadata) => &metadata.fields,
|
||||||
|
Self::Graph(graph) => &graph.imports,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn implementation(&self) -> GraphNodeImplementation {
|
||||||
|
match self {
|
||||||
|
Self::ProtoNode(identifier, _) => GraphNodeImplementation::ProtoNode((*identifier).clone()),
|
||||||
|
Self::Graph(graph) => GraphNodeImplementation::Graph(graph.identifier),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What feeds an input or export while the body is read.
|
||||||
|
#[derive(Clone)]
|
||||||
|
enum Feed {
|
||||||
|
/// A node's output, chosen by name, or else its primary output.
|
||||||
|
Node {
|
||||||
|
node: usize,
|
||||||
|
output: Option<usize>,
|
||||||
|
},
|
||||||
|
Import(usize),
|
||||||
|
Value {
|
||||||
|
value: GraphValue,
|
||||||
|
exposed: Option<bool>,
|
||||||
|
},
|
||||||
|
Scope(String),
|
||||||
|
NodePath,
|
||||||
|
SourceId,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Node<'a> {
|
||||||
|
target: Target<'a>,
|
||||||
|
name: Ident,
|
||||||
|
inputs: Vec<(usize, Feed)>,
|
||||||
|
states: Vec<StateKind>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Resolver<'a> {
|
||||||
|
context: &'a Context<'a>,
|
||||||
|
graph_path: String,
|
||||||
|
uses: HashMap<String, &'a Use>,
|
||||||
|
used: HashSet<String>,
|
||||||
|
imports: &'a [Import],
|
||||||
|
bindings: HashMap<String, Feed>,
|
||||||
|
nodes: Vec<Node<'a>>,
|
||||||
|
/// The parameters of the inner inputs each import feeds, in the order they're written.
|
||||||
|
import_consumers: Vec<Vec<FieldMetadata>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolves a parsed graph text, given the module path its graph is defined in.
|
||||||
|
pub fn resolve(source: &Source, module_path: &str, context: &Context) -> Result<GraphMetadata, ResolveError> {
|
||||||
|
let graph = &source.graph;
|
||||||
|
let graph_path = format!("{module_path}::{}", graph.name);
|
||||||
|
|
||||||
|
let mut uses = HashMap::new();
|
||||||
|
for entry in &source.uses {
|
||||||
|
let local_name = entry.local_name();
|
||||||
|
if uses.insert(local_name.to_string(), entry).is_some() {
|
||||||
|
return Err(Error::new(local_name.span(), format!("`{local_name}` is used twice. Rename one with `as`")).into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut resolver = Resolver {
|
||||||
|
context,
|
||||||
|
graph_path,
|
||||||
|
uses,
|
||||||
|
used: HashSet::new(),
|
||||||
|
imports: &graph.imports,
|
||||||
|
bindings: HashMap::new(),
|
||||||
|
nodes: Vec::new(),
|
||||||
|
import_consumers: vec![Vec::new(); graph.imports.len()],
|
||||||
|
};
|
||||||
|
|
||||||
|
for binding in &graph.bindings {
|
||||||
|
let name = binding.name.to_string();
|
||||||
|
if resolver.bindings.contains_key(&name) || resolver.import_index(&binding.name).is_some() {
|
||||||
|
return Err(Error::new(binding.name.span(), format!("`{name}` is already the name of a binding or import")).into());
|
||||||
|
}
|
||||||
|
let feed = resolver.read(&binding.value)?;
|
||||||
|
resolver.bindings.insert(name, feed);
|
||||||
|
}
|
||||||
|
|
||||||
|
let export_feeds = resolver.read_exports(&graph.result, graph.exports.len())?;
|
||||||
|
|
||||||
|
if let Some(unused) = source.uses.iter().find(|entry| !resolver.used.contains(&entry.local_name().to_string())) {
|
||||||
|
return Err(Error::new(unused.local_name().span(), format!("`{}` is used but never called", unused.local_name())).into());
|
||||||
|
}
|
||||||
|
|
||||||
|
resolver.build(graph, module_path, export_feeds)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Resolver<'a> {
|
||||||
|
fn import_index(&self, name: &Ident) -> Option<usize> {
|
||||||
|
self.imports.iter().position(|import| import.name.as_ref() == Some(name))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read(&mut self, expression: &'a Expression) -> Result<Feed, ResolveError> {
|
||||||
|
match expression {
|
||||||
|
Expression::Name(name) => {
|
||||||
|
if let Some(feed) = self.bindings.get(&name.to_string()) {
|
||||||
|
return Ok(feed.clone());
|
||||||
|
}
|
||||||
|
if let Some(index) = self.import_index(name) {
|
||||||
|
return Ok(Feed::Import(index));
|
||||||
|
}
|
||||||
|
Err(Error::new(name.span(), format!("`{name}` isn't a binding or import. Call a node with parentheses, like `{name}()`")).into())
|
||||||
|
}
|
||||||
|
Expression::Value(value) => Ok(Feed::Value {
|
||||||
|
value: match &value.kind {
|
||||||
|
ValueKind::Integer(integer) => GraphValue::Integer(*integer),
|
||||||
|
ValueKind::Number(number) => GraphValue::Number(*number),
|
||||||
|
ValueKind::Bool(boolean) => GraphValue::Bool(*boolean),
|
||||||
|
ValueKind::String(string) => GraphValue::String(string.clone()),
|
||||||
|
ValueKind::Vec2(x, y) => GraphValue::vec2(*x, *y),
|
||||||
|
},
|
||||||
|
exposed: None,
|
||||||
|
}),
|
||||||
|
Expression::Call(call) => self.read_call(call),
|
||||||
|
Expression::Feed { upstream, downstream, span } => {
|
||||||
|
let upstream_feed = self.read(upstream)?;
|
||||||
|
let Feed::Node { node, output } = self.read(downstream)? else {
|
||||||
|
return Err(Error::new(downstream.span(), "The right side of `>>` is a node, like `fill()`, or a binding naming one").into());
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Feed::Node { node: upstream_node, .. } = upstream_feed
|
||||||
|
&& self.is_fed_by(upstream_node, node)
|
||||||
|
{
|
||||||
|
return Err(Error::new(*span, "This wire makes a loop, since the node on the right already feeds the left side").into());
|
||||||
|
}
|
||||||
|
|
||||||
|
let entry = &self.nodes[node];
|
||||||
|
if entry.target.parameters().is_empty() {
|
||||||
|
return Err(Error::new(entry.name.span(), format!("`{}` has no parameters, so `>>` has no input to feed", entry.name)).into());
|
||||||
|
}
|
||||||
|
if entry.inputs.iter().any(|(index, _)| *index == 0) {
|
||||||
|
let primary = &entry.target.parameters()[0];
|
||||||
|
let message = format!("The primary input of `{}`, `{}`, is already fed, so `>>` can't feed it too", entry.name, primary.identifier);
|
||||||
|
return Err(Error::new(*span, message).into());
|
||||||
|
}
|
||||||
|
|
||||||
|
self.connect(node, 0, upstream_feed);
|
||||||
|
Ok(Feed::Node { node, output })
|
||||||
|
}
|
||||||
|
Expression::Output { node, output } => {
|
||||||
|
let Feed::Node { node, output: None } = self.read(node)? else {
|
||||||
|
return Err(Error::new(output.span(), "Only a node has outputs to choose from, and only one can be chosen").into());
|
||||||
|
};
|
||||||
|
let Target::Graph(graph) = self.nodes[node].target else {
|
||||||
|
return Err(Error::new(output.span(), "Only a graph's outputs can be chosen by name").into());
|
||||||
|
};
|
||||||
|
let name = output.unraw().to_string();
|
||||||
|
let Some(index) = graph.exports.iter().position(|export| export.identifier == name) else {
|
||||||
|
return Err(Error::new(output.span(), format!("`{}` has no output named `{name}`", self.nodes[node].name)).into());
|
||||||
|
};
|
||||||
|
Ok(Feed::Node { node, output: Some(index) })
|
||||||
|
}
|
||||||
|
Expression::Tuple { span, .. } => Err(Error::new(*span, "A tuple only gives a graph's exports, as its final expression").into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_exports(&mut self, result: &'a Expression, export_count: usize) -> Result<Vec<Feed>, ResolveError> {
|
||||||
|
let values: Vec<&Expression> = match result {
|
||||||
|
Expression::Tuple { elements, .. } => elements.iter().collect(),
|
||||||
|
single => vec![single],
|
||||||
|
};
|
||||||
|
if values.len() != export_count {
|
||||||
|
return Err(Error::new(result.span(), format!("The graph names {export_count} exports, but ends with {} values", values.len())).into());
|
||||||
|
}
|
||||||
|
|
||||||
|
values
|
||||||
|
.into_iter()
|
||||||
|
.map(|value| match self.read(value)? {
|
||||||
|
Feed::Import(_) | Feed::Scope(_) => Err(Error::new(value.span(), "An export can't come straight from an import or scope yet, so pass it through a node first").into()),
|
||||||
|
feed => Ok(feed),
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `node` is `source` or feeds it through any chain of wires.
|
||||||
|
fn is_fed_by(&self, node: usize, source: usize) -> bool {
|
||||||
|
let mut visited = vec![false; self.nodes.len()];
|
||||||
|
let mut stack = vec![node];
|
||||||
|
|
||||||
|
while let Some(current) = stack.pop() {
|
||||||
|
if current == source {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if std::mem::replace(&mut visited[current], true) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
stack.extend(self.nodes[current].inputs.iter().filter_map(|(_, feed)| match feed {
|
||||||
|
Feed::Node { node, .. } => Some(*node),
|
||||||
|
_ => None,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
fn connect(&mut self, node: usize, input: usize, feed: Feed) {
|
||||||
|
if let Feed::Import(import) = feed {
|
||||||
|
let parameter = self.nodes[node].target.parameters()[input].clone();
|
||||||
|
self.import_consumers[import].push(parameter);
|
||||||
|
}
|
||||||
|
self.nodes[node].inputs.push((input, feed));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_call(&mut self, call: &'a crate::syntax::Call) -> Result<Feed, ResolveError> {
|
||||||
|
let name = call.name.to_string();
|
||||||
|
if let Some(feed) = self.read_value_helper(call)? {
|
||||||
|
return Ok(feed);
|
||||||
|
}
|
||||||
|
|
||||||
|
let target = self.target(&call.name)?;
|
||||||
|
self.used.insert(name);
|
||||||
|
|
||||||
|
let mut inputs = Vec::new();
|
||||||
|
for argument in &call.arguments {
|
||||||
|
let parameter = match (&argument.parameter, &argument.value) {
|
||||||
|
(Some(parameter), _) => parameter,
|
||||||
|
(None, Expression::Name(shorthand)) => shorthand,
|
||||||
|
(None, value) => return Err(Error::new(value.span(), "Name each argument, like `weight = 6`, or write a bare name for the shorthand").into()),
|
||||||
|
};
|
||||||
|
|
||||||
|
let Some(index) = target.parameters().iter().position(|field| parameter == field.identifier) else {
|
||||||
|
return Err(Error::new(parameter.span(), format!("`{}` has no parameter named `{parameter}`", call.name)).into());
|
||||||
|
};
|
||||||
|
if inputs.iter().any(|(existing, _)| *existing == index) {
|
||||||
|
return Err(Error::new(parameter.span(), format!("`{parameter}` is already set in this call")).into());
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut feed = self.read(&argument.value)?;
|
||||||
|
for attribute in &argument.attributes {
|
||||||
|
if attribute.name != "exposed" {
|
||||||
|
return Err(Error::new(attribute.name.span(), format!("Unknown argument attribute `#[{}]`", attribute.name)).into());
|
||||||
|
}
|
||||||
|
attribute.flag()?;
|
||||||
|
let Feed::Value { exposed, .. } = &mut feed else {
|
||||||
|
return Err(Error::new(attribute.name.span(), "Only a value can be exposed").into());
|
||||||
|
};
|
||||||
|
*exposed = Some(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
inputs.push((index, feed));
|
||||||
|
}
|
||||||
|
|
||||||
|
self.nodes.push(Node {
|
||||||
|
target,
|
||||||
|
name: call.name.clone(),
|
||||||
|
inputs: Vec::new(),
|
||||||
|
states: call.states.iter().map(|state| state.kind.clone()).collect(),
|
||||||
|
});
|
||||||
|
let node = self.nodes.len() - 1;
|
||||||
|
for (index, feed) in inputs {
|
||||||
|
self.connect(node, index, feed);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Feed::Node { node, output: None })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads a call to `rgb`, `rgba`, `scope`, or `reflect`, which build values and input sources rather than nodes.
|
||||||
|
fn read_value_helper(&self, call: &crate::syntax::Call) -> Result<Option<Feed>, ResolveError> {
|
||||||
|
let name = call.name.to_string();
|
||||||
|
if !matches!(name.as_str(), "rgb" | "rgba" | "scope" | "reflect") {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
let [argument] = call.arguments.as_slice() else {
|
||||||
|
return Err(Error::new(call.name.span(), format!("`{name}(...)` takes one argument")).into());
|
||||||
|
};
|
||||||
|
if let Some(state) = call.states.first() {
|
||||||
|
return Err(Error::new(state.span, format!("`{name}(...)` is a value, so it has no node state")).into());
|
||||||
|
}
|
||||||
|
if argument.parameter.is_some() || !argument.attributes.is_empty() {
|
||||||
|
return Err(Error::new(call.name.span(), format!("`{name}(...)` takes a plain argument")).into());
|
||||||
|
}
|
||||||
|
|
||||||
|
let value = &argument.value;
|
||||||
|
let feed = match (name.as_str(), value) {
|
||||||
|
("rgb", Expression::Value(crate::syntax::Value { kind: ValueKind::Integer(hex), .. })) if (0..=0xFF_FFFF).contains(hex) => Feed::Value {
|
||||||
|
value: GraphValue::rgb(*hex as u32),
|
||||||
|
exposed: None,
|
||||||
|
},
|
||||||
|
("rgb", _) => return Err(Error::new(value.span(), "`rgb(...)` takes six hex digits, like `rgb(0xE85D75)`. Use `rgba(...)` to give an alpha too").into()),
|
||||||
|
("rgba", Expression::Value(crate::syntax::Value { kind: ValueKind::Integer(hex), .. })) if (0..=0xFFFF_FFFF).contains(hex) => Feed::Value {
|
||||||
|
value: GraphValue::rgba(*hex as u32),
|
||||||
|
exposed: None,
|
||||||
|
},
|
||||||
|
("rgba", _) => return Err(Error::new(value.span(), "`rgba(...)` takes eight hex digits, like `rgba(0xE85D75FF)`").into()),
|
||||||
|
("scope", Expression::Value(crate::syntax::Value { kind: ValueKind::String(key), .. })) => Feed::Scope(key.clone()),
|
||||||
|
("scope", _) => return Err(Error::new(value.span(), "`scope(...)` takes the scope's key as a string").into()),
|
||||||
|
(_, Expression::Name(reflected)) if reflected == "NodePath" => Feed::NodePath,
|
||||||
|
(_, Expression::Name(reflected)) if reflected == "SourceId" => Feed::SourceId,
|
||||||
|
_ => return Err(Error::new(value.span(), "Reflect `NodePath` or `SourceId`").into()),
|
||||||
|
};
|
||||||
|
Ok(Some(feed))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The node or graph a called name refers to, through the `use` section.
|
||||||
|
fn target(&self, name: &Ident) -> Result<Target<'a>, ResolveError> {
|
||||||
|
let Some(entry) = self.uses.get(&name.to_string()) else {
|
||||||
|
return Err(Error::new(name.span(), format!("`{name}` isn't used. Add it to the `use` section, like `use path::{name}@1;`")).into());
|
||||||
|
};
|
||||||
|
let module_path = entry.module_path();
|
||||||
|
|
||||||
|
let proto_identifier = ProtoNodeIdentifier::with_owned_string(format!("{module_path}::{}Node", entry.name.to_string().to_case(Case::Pascal)));
|
||||||
|
if let Some((identifier, metadata)) = self.context.proto_nodes.get_key_value(&proto_identifier) {
|
||||||
|
check_version(entry, metadata.version)?;
|
||||||
|
return Ok(Target::ProtoNode(identifier, metadata));
|
||||||
|
}
|
||||||
|
|
||||||
|
let graph_path = format!("{module_path}::{}", entry.name);
|
||||||
|
if graph_path == self.graph_path {
|
||||||
|
return Err(Error::new(name.span(), "A graph can't contain itself").into());
|
||||||
|
}
|
||||||
|
if let Some(graph) = self.context.graphs.iter().find(|graph| graph.path == graph_path) {
|
||||||
|
check_version(entry, graph.version)?;
|
||||||
|
return Ok(Target::Graph(graph));
|
||||||
|
}
|
||||||
|
|
||||||
|
Err(ResolveError::Unresolved(Error::new(entry.name.span(), format!("No node or graph is named `{graph_path}`"))))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build(self, graph: &GraphItem, module_path: &str, export_feeds: Vec<Feed>) -> Result<GraphMetadata, ResolveError> {
|
||||||
|
let attributes = GraphAttributes::read(&graph.attributes)?;
|
||||||
|
|
||||||
|
let imports = graph
|
||||||
|
.imports
|
||||||
|
.iter()
|
||||||
|
.zip(&self.import_consumers)
|
||||||
|
.enumerate()
|
||||||
|
.map(|(index, (import, consumers))| import_metadata(index, import, consumers))
|
||||||
|
.collect::<syn::Result<Vec<_>>>()?;
|
||||||
|
let import_types: Vec<Type> = imports.iter().map(import_wire_type).collect();
|
||||||
|
|
||||||
|
let source = |feed: &Feed| match feed {
|
||||||
|
Feed::Node { node, output } => GraphInputSource::Node {
|
||||||
|
node: *node,
|
||||||
|
output: output.unwrap_or(0),
|
||||||
|
},
|
||||||
|
Feed::Import(index) => GraphInputSource::Import {
|
||||||
|
index: *index,
|
||||||
|
ty: import_types[*index].clone(),
|
||||||
|
},
|
||||||
|
Feed::Value { value, exposed } => GraphInputSource::Value {
|
||||||
|
value: value.clone(),
|
||||||
|
exposed: *exposed,
|
||||||
|
},
|
||||||
|
Feed::Scope(key) => GraphInputSource::Scope(leak(key.clone())),
|
||||||
|
Feed::NodePath => GraphInputSource::NodePath,
|
||||||
|
Feed::SourceId => GraphInputSource::SourceId,
|
||||||
|
};
|
||||||
|
|
||||||
|
let layout_nodes: Vec<LayoutNode> = self
|
||||||
|
.nodes
|
||||||
|
.iter()
|
||||||
|
.map(|node| {
|
||||||
|
let upstream = |input: &(usize, Feed)| match input.1 {
|
||||||
|
Feed::Node { node, .. } => Some(node),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
LayoutNode {
|
||||||
|
primary: node.inputs.iter().filter(|input| input.0 == 0).find_map(upstream),
|
||||||
|
secondaries: node.inputs.iter().filter(|input| input.0 != 0).filter_map(upstream).collect(),
|
||||||
|
at: node.states.iter().find_map(|state| match state {
|
||||||
|
StateKind::At(x, y) => Some((*x, *y)),
|
||||||
|
_ => None,
|
||||||
|
}),
|
||||||
|
offset: node
|
||||||
|
.states
|
||||||
|
.iter()
|
||||||
|
.find_map(|state| match state {
|
||||||
|
StateKind::Offset(x, y) => Some((*x, *y)),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.unwrap_or_default(),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let roots: Vec<usize> = export_feeds
|
||||||
|
.iter()
|
||||||
|
.filter_map(|feed| match feed {
|
||||||
|
Feed::Node { node, .. } => Some(*node),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let positions = layout(&layout_nodes, &roots);
|
||||||
|
|
||||||
|
let nodes = self
|
||||||
|
.nodes
|
||||||
|
.iter()
|
||||||
|
.zip(positions)
|
||||||
|
.map(|(node, position)| GraphNodeMetadata {
|
||||||
|
implementation: node.target.implementation(),
|
||||||
|
inputs: node.inputs.iter().map(|(index, feed)| (*index, source(feed))).collect(),
|
||||||
|
position,
|
||||||
|
layer: node.states.contains(&StateKind::Layer),
|
||||||
|
display_name: node.states.iter().find_map(|state| match state {
|
||||||
|
StateKind::Named(name) => Some(leak(name.clone())),
|
||||||
|
_ => None,
|
||||||
|
}),
|
||||||
|
hidden: node.states.contains(&StateKind::Hidden),
|
||||||
|
locked: node.states.contains(&StateKind::Locked),
|
||||||
|
pinned: node.states.contains(&StateKind::Pinned),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let exports = graph
|
||||||
|
.exports
|
||||||
|
.iter()
|
||||||
|
.zip(&export_feeds)
|
||||||
|
.map(|(export, feed)| {
|
||||||
|
let mut name = None;
|
||||||
|
for attribute in &export.attributes {
|
||||||
|
match attribute.name.to_string().as_str() {
|
||||||
|
"doc" => {}
|
||||||
|
"name" => set_once(&mut name, attribute, attribute.string()?)?,
|
||||||
|
other => return Err(Error::new(attribute.name.span(), format!("Unknown export attribute `#[{other}]`"))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(GraphExportMetadata {
|
||||||
|
name: leak(name.unwrap_or_else(|| derived_display_name(&export.name))),
|
||||||
|
identifier: leak(export.name.unraw().to_string()),
|
||||||
|
description: leak(doc_comment(&export.attributes)),
|
||||||
|
source: source(feed),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect::<syn::Result<Vec<_>>>()?;
|
||||||
|
|
||||||
|
let identifier = attributes.display_name.unwrap_or_else(|| graph.name.unraw().to_string().to_case(Case::Pascal).to_case(Case::Title));
|
||||||
|
|
||||||
|
Ok(GraphMetadata {
|
||||||
|
identifier: leak(identifier),
|
||||||
|
path: leak(format!("{module_path}::{}", graph.name)),
|
||||||
|
category: leak(attributes.category),
|
||||||
|
icon: attributes.icon.map(leak),
|
||||||
|
description: leak(doc_comment(&graph.attributes)),
|
||||||
|
version: graph.version,
|
||||||
|
layer: attributes.layer,
|
||||||
|
imports,
|
||||||
|
exports,
|
||||||
|
nodes,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_version(entry: &Use, version: u32) -> syn::Result<()> {
|
||||||
|
if entry.version == version {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
Err(Error::new(entry.name.span(), format!("`{}` is at version {version}, not {}", entry.name, entry.version)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Strings in the registry's metadata live for the whole program, which holds for graphs resolved once at startup.
|
||||||
|
fn leak(string: String) -> &'static str {
|
||||||
|
Box::leak(string.into_boxed_str())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The display name an identifier derives, in Title Case.
|
||||||
|
fn derived_display_name(ident: &Ident) -> String {
|
||||||
|
ident.unraw().to_string().to_case(Case::Title).trim().to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn set_once<T>(slot: &mut Option<T>, attribute: &Attribute, value: T) -> syn::Result<()> {
|
||||||
|
if slot.is_some() {
|
||||||
|
return Err(Error::new(attribute.name.span(), format!("Multiple `{}` attributes are not allowed", attribute.name)));
|
||||||
|
}
|
||||||
|
*slot = Some(value);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
struct GraphAttributes {
|
||||||
|
category: String,
|
||||||
|
icon: Option<String>,
|
||||||
|
display_name: Option<String>,
|
||||||
|
layer: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GraphAttributes {
|
||||||
|
fn read(attributes: &[Attribute]) -> syn::Result<Self> {
|
||||||
|
let (mut category, mut icon, mut display_name, mut layer) = (None, None, None, None);
|
||||||
|
|
||||||
|
for attribute in attributes {
|
||||||
|
match attribute.name.to_string().as_str() {
|
||||||
|
"doc" => {}
|
||||||
|
"category" => set_once(&mut category, attribute, attribute.string()?)?,
|
||||||
|
"icon" => set_once(&mut icon, attribute, attribute.string()?)?,
|
||||||
|
"name" => set_once(&mut display_name, attribute, attribute.string()?)?,
|
||||||
|
"layer" => {
|
||||||
|
attribute.flag()?;
|
||||||
|
set_once(&mut layer, attribute, true)?;
|
||||||
|
}
|
||||||
|
other => {
|
||||||
|
return Err(Error::new(
|
||||||
|
attribute.name.span(),
|
||||||
|
format!("Unknown graph attribute `#[{other}]`. Expected `category(\"…\")`, `icon(\"…\")`, `name(\"…\")`, or `layer`"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let Some(category) = category else {
|
||||||
|
return Err(Error::new(Span::call_site(), "A graph needs a category, like `#[category(\"Vector: Deform\")]`"));
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
category,
|
||||||
|
icon,
|
||||||
|
display_name,
|
||||||
|
layer: layer.unwrap_or_default(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A parameter description with nothing set, which an import starts from when it feeds no input.
|
||||||
|
pub(crate) fn blank_field() -> FieldMetadata {
|
||||||
|
FieldMetadata {
|
||||||
|
name: "",
|
||||||
|
identifier: "",
|
||||||
|
description: "",
|
||||||
|
internal: false,
|
||||||
|
exposed: false,
|
||||||
|
widget_override: RegistryWidgetOverride::None,
|
||||||
|
value_source: RegistryValueSource::None,
|
||||||
|
default_colors: None,
|
||||||
|
default_type: None,
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An import's parameter description, inherited from an inner input it feeds and overridden by its own attributes.
|
||||||
|
/// That input is the one whose parameter has the import's name, or else the first one fed.
|
||||||
|
fn import_metadata(index: usize, import: &Import, consumers: &[FieldMetadata]) -> syn::Result<FieldMetadata> {
|
||||||
|
let Some(name) = &import.name else {
|
||||||
|
if let Some(attribute) = import.attributes.first() {
|
||||||
|
return Err(Error::new(attribute.name.span(), "An unused primary import takes no attributes"));
|
||||||
|
}
|
||||||
|
return Ok(FieldMetadata {
|
||||||
|
default_type: Some(concrete!(())),
|
||||||
|
..blank_field()
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
let identifier = name.unraw().to_string();
|
||||||
|
let inherited = consumers.iter().find(|consumer| consumer.identifier == identifier).or(consumers.first());
|
||||||
|
let mut field = FieldMetadata {
|
||||||
|
identifier: leak(identifier.clone()),
|
||||||
|
exposed: false,
|
||||||
|
internal: index > 0 && identifier.starts_with('_'),
|
||||||
|
constant: false,
|
||||||
|
..inherited.cloned().unwrap_or_else(blank_field)
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut display_name = None;
|
||||||
|
let mut seen = HashSet::new();
|
||||||
|
for attribute in &import.attributes {
|
||||||
|
let attribute_name = attribute.name.to_string();
|
||||||
|
if attribute_name != "doc" && !seen.insert(attribute_name.clone()) {
|
||||||
|
return Err(Error::new(attribute.name.span(), format!("Multiple `{attribute_name}` attributes are not allowed")));
|
||||||
|
}
|
||||||
|
apply_import_attribute(&mut field, &mut display_name, attribute)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
field.name = leak(display_name.unwrap_or_else(|| derived_display_name(name)));
|
||||||
|
let description = doc_comment(&import.attributes);
|
||||||
|
if !description.is_empty() {
|
||||||
|
field.description = leak(description);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(field)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply_import_attribute(field: &mut FieldMetadata, display_name: &mut Option<String>, attribute: &Attribute) -> syn::Result<()> {
|
||||||
|
let arguments = || attribute.list();
|
||||||
|
|
||||||
|
match attribute.name.to_string().as_str() {
|
||||||
|
"doc" => {}
|
||||||
|
"name" => *display_name = Some(attribute.string()?),
|
||||||
|
"expose" => {
|
||||||
|
attribute.flag()?;
|
||||||
|
field.exposed = true;
|
||||||
|
}
|
||||||
|
"default" => {
|
||||||
|
let tokens = arguments()?;
|
||||||
|
field.default_type = default_type(&tokens, field.default_type.take());
|
||||||
|
field.value_source = RegistryValueSource::Default(leak(tokens.to_string()));
|
||||||
|
field.default_colors = None;
|
||||||
|
}
|
||||||
|
"widget" => {
|
||||||
|
field.widget_override = (|input: ParseStream| {
|
||||||
|
let kind: Ident = input.parse()?;
|
||||||
|
let text = || -> syn::Result<&'static str> {
|
||||||
|
input.parse::<Token![=]>()?;
|
||||||
|
Ok(leak(input.parse::<LitStr>()?.value()))
|
||||||
|
};
|
||||||
|
match kind.to_string().as_str() {
|
||||||
|
"Hidden" => Ok(RegistryWidgetOverride::Hidden),
|
||||||
|
"String" => Ok(RegistryWidgetOverride::String(text()?)),
|
||||||
|
"Custom" => Ok(RegistryWidgetOverride::Custom(text()?)),
|
||||||
|
_ => Err(Error::new(kind.span(), "A widget is `Hidden`, `String = \"…\"`, or `Custom = \"…\"`")),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.parse2(arguments()?)?;
|
||||||
|
}
|
||||||
|
"unit" => field.unit = Some(leak(attribute.string()?)),
|
||||||
|
"hard" => (field.number_hard_min, field.number_hard_max) = parse_bounds.parse2(arguments()?)?,
|
||||||
|
"soft" => (field.number_soft_min, field.number_soft_max) = parse_bounds.parse2(arguments()?)?,
|
||||||
|
"range" => {
|
||||||
|
attribute.flag()?;
|
||||||
|
field.number_mode_range = true;
|
||||||
|
}
|
||||||
|
"step" => field.number_step = Some(parse_number.parse2(arguments()?)?),
|
||||||
|
"display_decimal_places" => field.number_display_decimal_places = Some(syn::parse2::<LitInt>(arguments()?)?.base10_parse()?),
|
||||||
|
"multiline" => {
|
||||||
|
attribute.flag()?;
|
||||||
|
field.multiline = true;
|
||||||
|
}
|
||||||
|
"progression" => {
|
||||||
|
attribute.flag()?;
|
||||||
|
field.progression = true;
|
||||||
|
}
|
||||||
|
"integer" => {
|
||||||
|
attribute.flag()?;
|
||||||
|
field.integer = true;
|
||||||
|
}
|
||||||
|
"labels" => {
|
||||||
|
field.labels = Some(
|
||||||
|
(|input: ParseStream| {
|
||||||
|
let x: LitStr = input.parse()?;
|
||||||
|
input.parse::<Token![,]>()?;
|
||||||
|
let y: LitStr = input.parse()?;
|
||||||
|
Ok((leak(x.value()), leak(y.value())))
|
||||||
|
})
|
||||||
|
.parse2(arguments()?)?,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
"blank_assist" => field.blank_assist = syn::parse2::<LitBool>(arguments()?)?.value,
|
||||||
|
other => return Err(Error::new(attribute.name.span(), format!("Unknown import attribute `#[{other}]`"))),
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The type a `#[default(...)]` is parsed as: a literal's own type, or else the bare element of the inherited type.
|
||||||
|
fn default_type(tokens: &proc_macro2::TokenStream, inherited: Option<Type>) -> Option<Type> {
|
||||||
|
if let Ok(literal) = syn::parse2::<crate::syntax::Value>(tokens.clone()) {
|
||||||
|
return Some(match literal.kind {
|
||||||
|
ValueKind::Integer(_) => concrete!(i64),
|
||||||
|
ValueKind::Number(_) => concrete!(f64),
|
||||||
|
ValueKind::Bool(_) => concrete!(bool),
|
||||||
|
ValueKind::String(_) => concrete!(String),
|
||||||
|
ValueKind::Vec2(..) => concrete!(glam::DVec2),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
match inherited {
|
||||||
|
Some(Type::Item(element)) => Some(*element),
|
||||||
|
other => other,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The type an import's wire records, ranked as an `Item` when its default is a bare element.
|
||||||
|
fn import_wire_type(field: &FieldMetadata) -> Type {
|
||||||
|
match &field.default_type {
|
||||||
|
Some(ty @ (Type::Item(_) | Type::List(_) | Type::Fn(..) | Type::Generic(_))) => ty.clone(),
|
||||||
|
Some(unit) if *unit == concrete!(()) => unit.clone(),
|
||||||
|
Some(element) => Type::Item(Box::new(element.clone())),
|
||||||
|
None => generic!(T),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_number(input: ParseStream) -> syn::Result<f64> {
|
||||||
|
let negative = input.peek(Token![-]);
|
||||||
|
if negative {
|
||||||
|
input.parse::<Token![-]>()?;
|
||||||
|
}
|
||||||
|
let magnitude: f64 = match input.parse::<syn::Lit>()? {
|
||||||
|
syn::Lit::Int(integer) => integer.base10_parse()?,
|
||||||
|
syn::Lit::Float(float) => float.base10_parse()?,
|
||||||
|
other => return Err(Error::new(other.span(), "Expected a number")),
|
||||||
|
};
|
||||||
|
Ok(if negative { -magnitude } else { magnitude })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads `a..b`, where either end may be left out.
|
||||||
|
fn parse_bounds(input: ParseStream) -> syn::Result<(Option<f64>, Option<f64>)> {
|
||||||
|
let start = if input.peek(Token![..]) { None } else { Some(parse_number(input)?) };
|
||||||
|
input.parse::<Token![..]>()?;
|
||||||
|
let end = if input.is_empty() { None } else { Some(parse_number(input)?) };
|
||||||
|
Ok((start, end))
|
||||||
|
}
|
||||||
@@ -0,0 +1,780 @@
|
|||||||
|
//! The grammar of graph text, parsed with syn from the tokens of a `graph!` invocation or a clipboard string.
|
||||||
|
|
||||||
|
use proc_macro2::{Span, TokenStream};
|
||||||
|
use syn::ext::IdentExt;
|
||||||
|
use syn::parse::{Parse, ParseStream};
|
||||||
|
use syn::punctuated::Punctuated;
|
||||||
|
use syn::spanned::Spanned;
|
||||||
|
use syn::{Error, Ident, Lit, LitInt, LitStr, Token, braced, bracketed, parenthesized};
|
||||||
|
|
||||||
|
/// The syntax version this parser reads, from the `#![syntax(N)]` header.
|
||||||
|
pub const SYNTAX_VERSION: u32 = 1;
|
||||||
|
|
||||||
|
/// A whole graph text: its header, its `use` section, and the graph it defines.
|
||||||
|
pub struct Source {
|
||||||
|
pub uses: Vec<Use>,
|
||||||
|
pub graph: GraphItem,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One node or graph named by the `use` section, like `math_nodes::add@1`.
|
||||||
|
pub struct Use {
|
||||||
|
pub module: Vec<Ident>,
|
||||||
|
pub name: Ident,
|
||||||
|
pub version: u32,
|
||||||
|
pub alias: Option<Ident>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Use {
|
||||||
|
/// The name the body calls it by.
|
||||||
|
pub fn local_name(&self) -> &Ident {
|
||||||
|
self.alias.as_ref().unwrap_or(&self.name)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn module_path(&self) -> String {
|
||||||
|
self.module.iter().map(Ident::to_string).collect::<Vec<_>>().join("::")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An attribute item like `category("Graphic")`, `layer`, or `doc = "…"`. One `#[...]` can hold several, separated by commas.
|
||||||
|
pub struct Attribute {
|
||||||
|
pub name: Ident,
|
||||||
|
pub arguments: AttributeArguments,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum AttributeArguments {
|
||||||
|
None,
|
||||||
|
List(TokenStream),
|
||||||
|
Value(Lit),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Attribute {
|
||||||
|
/// The parenthesized arguments, or an error naming the attribute if it has none.
|
||||||
|
pub fn list(&self) -> syn::Result<TokenStream> {
|
||||||
|
match &self.arguments {
|
||||||
|
AttributeArguments::List(tokens) => Ok(tokens.clone()),
|
||||||
|
_ => Err(Error::new(self.name.span(), format!("`{}` takes arguments in parentheses", self.name))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An error unless the attribute is written without arguments.
|
||||||
|
pub fn flag(&self) -> syn::Result<()> {
|
||||||
|
match &self.arguments {
|
||||||
|
AttributeArguments::None => Ok(()),
|
||||||
|
_ => Err(Error::new(self.name.span(), format!("`{}` takes no arguments", self.name))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn string(&self) -> syn::Result<String> {
|
||||||
|
syn::parse2::<LitStr>(self.list()?).map(|literal| literal.value())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct GraphItem {
|
||||||
|
pub attributes: Vec<Attribute>,
|
||||||
|
pub name: Ident,
|
||||||
|
pub version: u32,
|
||||||
|
pub imports: Vec<Import>,
|
||||||
|
pub exports: Vec<Export>,
|
||||||
|
pub bindings: Vec<Binding>,
|
||||||
|
/// The final expression, which gives one value per export.
|
||||||
|
pub result: Expression,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Import {
|
||||||
|
pub attributes: Vec<Attribute>,
|
||||||
|
/// The import's name, or `None` for an unused primary import written `_`.
|
||||||
|
pub name: Option<Ident>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Export {
|
||||||
|
pub attributes: Vec<Attribute>,
|
||||||
|
pub name: Ident,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Binding {
|
||||||
|
pub name: Ident,
|
||||||
|
pub value: Expression,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum Expression {
|
||||||
|
Name(Ident),
|
||||||
|
Value(Value),
|
||||||
|
Call(Call),
|
||||||
|
/// `upstream >> downstream`, which feeds the upstream into the downstream node's primary input.
|
||||||
|
Feed {
|
||||||
|
upstream: Box<Expression>,
|
||||||
|
downstream: Box<Expression>,
|
||||||
|
span: Span,
|
||||||
|
},
|
||||||
|
/// A node's output chosen by name, like `.captures`.
|
||||||
|
Output {
|
||||||
|
node: Box<Expression>,
|
||||||
|
output: Ident,
|
||||||
|
},
|
||||||
|
Tuple {
|
||||||
|
elements: Vec<Expression>,
|
||||||
|
span: Span,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Expression {
|
||||||
|
pub fn span(&self) -> Span {
|
||||||
|
match self {
|
||||||
|
Self::Name(name) => name.span(),
|
||||||
|
Self::Value(value) => value.span,
|
||||||
|
Self::Call(call) => call.name.span(),
|
||||||
|
Self::Feed { span, .. } | Self::Tuple { span, .. } => *span,
|
||||||
|
Self::Output { output, .. } => output.span(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Value {
|
||||||
|
pub kind: ValueKind,
|
||||||
|
pub span: Span,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub enum ValueKind {
|
||||||
|
Integer(i64),
|
||||||
|
Number(f64),
|
||||||
|
Bool(bool),
|
||||||
|
String(String),
|
||||||
|
Vec2(f64, f64),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Call {
|
||||||
|
pub name: Ident,
|
||||||
|
pub arguments: Vec<Argument>,
|
||||||
|
pub states: Vec<State>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Argument {
|
||||||
|
pub attributes: Vec<Attribute>,
|
||||||
|
/// The parameter set by `parameter = value`, or `None` for a positional argument, which for a node is the shorthand `name`.
|
||||||
|
pub parameter: Option<Ident>,
|
||||||
|
pub value: Expression,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A node state method after a call, like `.offset(0, 2)`.
|
||||||
|
pub struct State {
|
||||||
|
pub kind: StateKind,
|
||||||
|
pub span: Span,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq)]
|
||||||
|
pub enum StateKind {
|
||||||
|
At(i32, i32),
|
||||||
|
Offset(i32, i32),
|
||||||
|
Named(String),
|
||||||
|
Hidden,
|
||||||
|
Locked,
|
||||||
|
Pinned,
|
||||||
|
Layer,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Parse for Source {
|
||||||
|
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||||
|
parse_header(input)?;
|
||||||
|
|
||||||
|
let mut uses = Vec::new();
|
||||||
|
while input.peek(Token![use]) {
|
||||||
|
uses.extend(parse_use(input)?);
|
||||||
|
}
|
||||||
|
|
||||||
|
let graph = input.parse()?;
|
||||||
|
if !input.is_empty() {
|
||||||
|
return Err(input.error("Graph text defines one graph"));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Self { uses, graph })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads `#![syntax(N)]`, which every graph text starts with.
|
||||||
|
fn parse_header(input: ParseStream) -> syn::Result<()> {
|
||||||
|
if !(input.peek(Token![#]) && input.peek2(Token![!])) {
|
||||||
|
return Err(input.error(format!("Graph text starts with its syntax version, like `#![syntax({SYNTAX_VERSION})]`")));
|
||||||
|
}
|
||||||
|
input.parse::<Token![#]>()?;
|
||||||
|
input.parse::<Token![!]>()?;
|
||||||
|
|
||||||
|
let content;
|
||||||
|
bracketed!(content in input);
|
||||||
|
let name: Ident = content.parse()?;
|
||||||
|
if name != "syntax" {
|
||||||
|
return Err(Error::new(name.span(), "The header is `#![syntax(N)]`"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let arguments;
|
||||||
|
parenthesized!(arguments in content);
|
||||||
|
let literal: LitInt = arguments.parse()?;
|
||||||
|
let version: u32 = literal.base10_parse()?;
|
||||||
|
if version != SYNTAX_VERSION {
|
||||||
|
return Err(Error::new(literal.span(), format!("Syntax version {version} isn't supported, only {SYNTAX_VERSION} is")));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads `use path::name@N;` or `use path::{a@N, b@N as c};`.
|
||||||
|
fn parse_use(input: ParseStream) -> syn::Result<Vec<Use>> {
|
||||||
|
let use_token: Token![use] = input.parse()?;
|
||||||
|
|
||||||
|
let mut module = Vec::new();
|
||||||
|
let entries = loop {
|
||||||
|
if input.peek(syn::token::Brace) {
|
||||||
|
let content;
|
||||||
|
braced!(content in input);
|
||||||
|
break Punctuated::<UseEntry, Token![,]>::parse_terminated(&content)?.into_iter().collect::<Vec<_>>();
|
||||||
|
}
|
||||||
|
|
||||||
|
let segment: Ident = input.parse()?;
|
||||||
|
if input.peek(Token![::]) {
|
||||||
|
input.parse::<Token![::]>()?;
|
||||||
|
module.push(segment);
|
||||||
|
} else {
|
||||||
|
break vec![UseEntry::parse_after_name(segment, input)?];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
input.parse::<Token![;]>()?;
|
||||||
|
|
||||||
|
if module.is_empty() {
|
||||||
|
return Err(Error::new(use_token.span, "Name a node by its full path, like `use math_nodes::add@1;`"));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(entries
|
||||||
|
.into_iter()
|
||||||
|
.map(|entry| Use {
|
||||||
|
module: module.clone(),
|
||||||
|
name: entry.name,
|
||||||
|
version: entry.version,
|
||||||
|
alias: entry.alias,
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
struct UseEntry {
|
||||||
|
name: Ident,
|
||||||
|
version: u32,
|
||||||
|
alias: Option<Ident>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl UseEntry {
|
||||||
|
fn parse_after_name(name: Ident, input: ParseStream) -> syn::Result<Self> {
|
||||||
|
let version = parse_version(input)?;
|
||||||
|
let alias = if input.peek(Token![as]) {
|
||||||
|
input.parse::<Token![as]>()?;
|
||||||
|
Some(input.parse()?)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
Ok(Self { name, version, alias })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Parse for UseEntry {
|
||||||
|
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||||
|
let name = input.parse()?;
|
||||||
|
Self::parse_after_name(name, input)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads `@N`, the version a node or graph is declared or used at.
|
||||||
|
fn parse_version(input: ParseStream) -> syn::Result<u32> {
|
||||||
|
if !input.peek(Token![@]) {
|
||||||
|
return Err(input.error("Give the version, like `@1`"));
|
||||||
|
}
|
||||||
|
input.parse::<Token![@]>()?;
|
||||||
|
|
||||||
|
let literal: LitInt = input.parse()?;
|
||||||
|
if !literal.suffix().is_empty() {
|
||||||
|
return Err(Error::new(literal.span(), "Write the version without a type suffix"));
|
||||||
|
}
|
||||||
|
let version: u32 = literal.base10_parse()?;
|
||||||
|
if version == 0 {
|
||||||
|
return Err(Error::new(literal.span(), "Versions start at 1"));
|
||||||
|
}
|
||||||
|
Ok(version)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads any number of `#[...]` groups, each holding comma-separated attribute items.
|
||||||
|
fn parse_attributes(input: ParseStream) -> syn::Result<Vec<Attribute>> {
|
||||||
|
let mut attributes = Vec::new();
|
||||||
|
|
||||||
|
while input.peek(Token![#]) && !input.peek2(Token![!]) {
|
||||||
|
input.parse::<Token![#]>()?;
|
||||||
|
let content;
|
||||||
|
bracketed!(content in input);
|
||||||
|
|
||||||
|
while !content.is_empty() {
|
||||||
|
let name = content.call(Ident::parse_any)?;
|
||||||
|
let arguments = if content.peek(syn::token::Paren) {
|
||||||
|
let arguments;
|
||||||
|
parenthesized!(arguments in content);
|
||||||
|
AttributeArguments::List(arguments.parse()?)
|
||||||
|
} else if content.peek(Token![=]) {
|
||||||
|
content.parse::<Token![=]>()?;
|
||||||
|
AttributeArguments::Value(content.parse()?)
|
||||||
|
} else {
|
||||||
|
AttributeArguments::None
|
||||||
|
};
|
||||||
|
attributes.push(Attribute { name, arguments });
|
||||||
|
|
||||||
|
if content.is_empty() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
content.parse::<Token![,]>()?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(attributes)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `///` lines among the attributes, each trimmed and joined by line breaks.
|
||||||
|
pub fn doc_comment(attributes: &[Attribute]) -> String {
|
||||||
|
attributes
|
||||||
|
.iter()
|
||||||
|
.filter(|attribute| attribute.name == "doc")
|
||||||
|
.filter_map(|attribute| match &attribute.arguments {
|
||||||
|
AttributeArguments::Value(Lit::Str(text)) => Some(text.value().trim().to_string()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join("\n")
|
||||||
|
.trim()
|
||||||
|
.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Parse for GraphItem {
|
||||||
|
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||||
|
let attributes = parse_attributes(input)?;
|
||||||
|
input.parse::<Token![fn]>()?;
|
||||||
|
let name: Ident = input.parse()?;
|
||||||
|
let version = parse_version(input)?;
|
||||||
|
|
||||||
|
let parameters;
|
||||||
|
parenthesized!(parameters in input);
|
||||||
|
let imports = Punctuated::<Import, Token![,]>::parse_terminated(¶meters)?.into_iter().collect();
|
||||||
|
|
||||||
|
input.parse::<Token![->]>()?;
|
||||||
|
let exports: Vec<Export> = if input.peek(syn::token::Paren) {
|
||||||
|
let content;
|
||||||
|
parenthesized!(content in input);
|
||||||
|
Punctuated::<Export, Token![,]>::parse_terminated(&content)?.into_iter().collect()
|
||||||
|
} else {
|
||||||
|
vec![input.parse()?]
|
||||||
|
};
|
||||||
|
if exports.is_empty() {
|
||||||
|
return Err(Error::new(name.span(), "Name at least one export, like `-> (out)`"));
|
||||||
|
}
|
||||||
|
|
||||||
|
let body;
|
||||||
|
braced!(body in input);
|
||||||
|
let mut bindings = Vec::new();
|
||||||
|
while body.peek(Token![let]) {
|
||||||
|
bindings.push(body.parse()?);
|
||||||
|
}
|
||||||
|
|
||||||
|
if body.is_empty() {
|
||||||
|
return Err(Error::new(name.span(), "A graph ends its body with one value per export"));
|
||||||
|
}
|
||||||
|
let result = parse_expression(&body)?;
|
||||||
|
if body.peek(Token![;]) {
|
||||||
|
return Err(body.error("The graph ends with its exports, written without a semicolon"));
|
||||||
|
}
|
||||||
|
if !body.is_empty() {
|
||||||
|
return Err(body.error("Each statement in a graph is a `let` binding, followed by the exports it ends with"));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
attributes,
|
||||||
|
name,
|
||||||
|
version,
|
||||||
|
imports,
|
||||||
|
exports,
|
||||||
|
bindings,
|
||||||
|
result,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Parse for Import {
|
||||||
|
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||||
|
let attributes = parse_attributes(input)?;
|
||||||
|
let name = if input.peek(Token![_]) {
|
||||||
|
input.parse::<Token![_]>()?;
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(input.parse()?)
|
||||||
|
};
|
||||||
|
if input.peek(Token![:]) {
|
||||||
|
return Err(input.error("Imports take no type, since it's inferred from the inputs they feed"));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Self { attributes, name })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Parse for Export {
|
||||||
|
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||||
|
let attributes = parse_attributes(input)?;
|
||||||
|
let name = input.call(Ident::parse_any)?;
|
||||||
|
Ok(Self { attributes, name })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Parse for Binding {
|
||||||
|
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||||
|
input.parse::<Token![let]>()?;
|
||||||
|
let name = input.parse()?;
|
||||||
|
input.parse::<Token![=]>()?;
|
||||||
|
let value = parse_expression(input)?;
|
||||||
|
input.parse::<Token![;]>()?;
|
||||||
|
Ok(Self { name, value })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Parse for Expression {
|
||||||
|
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||||
|
parse_expression(input)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads a chain of `>>`, which binds loosest and groups from the left.
|
||||||
|
fn parse_expression(input: ParseStream) -> syn::Result<Expression> {
|
||||||
|
let mut expression = parse_postfix(input)?;
|
||||||
|
|
||||||
|
while input.peek(Token![>>]) {
|
||||||
|
let token: Token![>>] = input.parse()?;
|
||||||
|
let downstream = parse_postfix(input)?;
|
||||||
|
expression = Expression::Feed {
|
||||||
|
upstream: Box::new(expression),
|
||||||
|
downstream: Box::new(downstream),
|
||||||
|
span: token.span(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(expression)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads a primary expression followed by node state methods and output choices.
|
||||||
|
fn parse_postfix(input: ParseStream) -> syn::Result<Expression> {
|
||||||
|
let mut expression = parse_primary(input)?;
|
||||||
|
|
||||||
|
while input.peek(Token![.]) && !input.peek(Token![..]) {
|
||||||
|
input.parse::<Token![.]>()?;
|
||||||
|
let name = input.call(Ident::parse_any)?;
|
||||||
|
|
||||||
|
if !input.peek(syn::token::Paren) {
|
||||||
|
if matches!(expression, Expression::Output { .. }) {
|
||||||
|
return Err(Error::new(name.span(), "An output is already chosen here"));
|
||||||
|
}
|
||||||
|
expression = Expression::Output {
|
||||||
|
node: Box::new(expression),
|
||||||
|
output: name,
|
||||||
|
};
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let arguments;
|
||||||
|
parenthesized!(arguments in input);
|
||||||
|
let call = match &mut expression {
|
||||||
|
Expression::Call(call) => call,
|
||||||
|
Expression::Output { .. } => {
|
||||||
|
return Err(Error::new(name.span(), "Node state goes before the output it chooses, like `regex_find().at(0, 0).captures`"));
|
||||||
|
}
|
||||||
|
_ => return Err(Error::new(name.span(), "Node state goes directly after the call it modifies, not on a binding")),
|
||||||
|
};
|
||||||
|
|
||||||
|
let state = parse_state(&name, &arguments)?;
|
||||||
|
if call.states.iter().any(|existing| std::mem::discriminant(&existing.kind) == std::mem::discriminant(&state.kind)) {
|
||||||
|
return Err(Error::new(name.span(), format!("`.{name}()` is already set on this node")));
|
||||||
|
}
|
||||||
|
call.states.push(state);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(expression)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_state(name: &Ident, arguments: ParseStream) -> syn::Result<State> {
|
||||||
|
let method = name.to_string();
|
||||||
|
let no_arguments = || match arguments.is_empty() {
|
||||||
|
true => Ok(()),
|
||||||
|
false => Err(arguments.error(format!("`.{method}()` takes no arguments"))),
|
||||||
|
};
|
||||||
|
let coordinates = || -> syn::Result<(i32, i32)> {
|
||||||
|
let x = parse_grid_coordinate(arguments)?;
|
||||||
|
arguments.parse::<Token![,]>()?;
|
||||||
|
let y = parse_grid_coordinate(arguments)?;
|
||||||
|
if !arguments.is_empty() {
|
||||||
|
return Err(arguments.error("Give two coordinates in grid units"));
|
||||||
|
}
|
||||||
|
Ok((x, y))
|
||||||
|
};
|
||||||
|
|
||||||
|
let kind = match method.as_str() {
|
||||||
|
"at" => {
|
||||||
|
let (x, y) = coordinates()?;
|
||||||
|
StateKind::At(x, y)
|
||||||
|
}
|
||||||
|
"offset" => {
|
||||||
|
let (x, y) = coordinates()?;
|
||||||
|
StateKind::Offset(x, y)
|
||||||
|
}
|
||||||
|
"named" => {
|
||||||
|
let display_name: LitStr = arguments.parse()?;
|
||||||
|
StateKind::Named(display_name.value())
|
||||||
|
}
|
||||||
|
"hidden" => no_arguments().map(|_| StateKind::Hidden)?,
|
||||||
|
"locked" => no_arguments().map(|_| StateKind::Locked)?,
|
||||||
|
"pinned" => no_arguments().map(|_| StateKind::Pinned)?,
|
||||||
|
"layer" => no_arguments().map(|_| StateKind::Layer)?,
|
||||||
|
_ => {
|
||||||
|
return Err(Error::new(
|
||||||
|
name.span(),
|
||||||
|
format!("Unknown node state `.{method}()`. Parameters go inside the call's parentheses, like `node({method} = ...)`"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(State { kind, span: name.span() })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_grid_coordinate(input: ParseStream) -> syn::Result<i32> {
|
||||||
|
let negative = input.peek(Token![-]);
|
||||||
|
if negative {
|
||||||
|
input.parse::<Token![-]>()?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let literal: LitInt = input.parse().map_err(|error| Error::new(error.span(), "Positions are integers in grid units"))?;
|
||||||
|
if !literal.suffix().is_empty() {
|
||||||
|
return Err(Error::new(literal.span(), "Write the position without a type suffix"));
|
||||||
|
}
|
||||||
|
let magnitude: i32 = literal.base10_parse()?;
|
||||||
|
Ok(if negative { -magnitude } else { magnitude })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_primary(input: ParseStream) -> syn::Result<Expression> {
|
||||||
|
let span = input.span();
|
||||||
|
|
||||||
|
if input.peek(syn::token::Paren) {
|
||||||
|
let content;
|
||||||
|
parenthesized!(content in input);
|
||||||
|
let elements = Punctuated::<Expression, Token![,]>::parse_terminated(&content)?;
|
||||||
|
if elements.is_empty() {
|
||||||
|
return Err(Error::new(span, "Empty parentheses aren't part of the graph syntax"));
|
||||||
|
}
|
||||||
|
if elements.len() == 1 && !elements.trailing_punct() {
|
||||||
|
return Ok(elements.into_iter().next().expect("there is one element"));
|
||||||
|
}
|
||||||
|
return Ok(Expression::Tuple {
|
||||||
|
elements: elements.into_iter().collect(),
|
||||||
|
span,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if input.peek(syn::token::Bracket) {
|
||||||
|
let content;
|
||||||
|
bracketed!(content in input);
|
||||||
|
let numbers = Punctuated::<Value, Token![,]>::parse_terminated(&content)?;
|
||||||
|
let components: Vec<f64> = numbers
|
||||||
|
.iter()
|
||||||
|
.filter_map(|number| match number.kind {
|
||||||
|
ValueKind::Number(number) => Some(number),
|
||||||
|
ValueKind::Integer(integer) => Some(integer as f64),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let [x, y] = components.as_slice() else {
|
||||||
|
return Err(Error::new(span, "A value array is a two-number Vec2, like `[1., 2.]`"));
|
||||||
|
};
|
||||||
|
return Ok(Expression::Value(Value { kind: ValueKind::Vec2(*x, *y), span }));
|
||||||
|
}
|
||||||
|
|
||||||
|
if input.peek(Lit) || input.peek(Token![-]) {
|
||||||
|
return input.parse().map(Expression::Value);
|
||||||
|
}
|
||||||
|
|
||||||
|
if input.peek(Ident) {
|
||||||
|
let name: Ident = input.parse()?;
|
||||||
|
if !input.peek(syn::token::Paren) {
|
||||||
|
return Ok(Expression::Name(name));
|
||||||
|
}
|
||||||
|
|
||||||
|
let content;
|
||||||
|
parenthesized!(content in input);
|
||||||
|
let arguments = Punctuated::<Argument, Token![,]>::parse_terminated(&content)?.into_iter().collect();
|
||||||
|
return Ok(Expression::Call(Call { name, arguments, states: Vec::new() }));
|
||||||
|
}
|
||||||
|
|
||||||
|
Err(input.error("This isn't part of the graph syntax"))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Parse for Value {
|
||||||
|
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||||
|
let span = input.span();
|
||||||
|
let negative = input.peek(Token![-]);
|
||||||
|
if negative {
|
||||||
|
input.parse::<Token![-]>()?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let literal: Lit = input.parse()?;
|
||||||
|
let kind = match &literal {
|
||||||
|
Lit::Int(integer) => {
|
||||||
|
if !integer.suffix().is_empty() {
|
||||||
|
return Err(Error::new(integer.span(), "Write the integer without a type suffix. Its type is `i64`"));
|
||||||
|
}
|
||||||
|
let value: i64 = integer.base10_parse()?;
|
||||||
|
ValueKind::Integer(if negative { -value } else { value })
|
||||||
|
}
|
||||||
|
Lit::Float(float) => {
|
||||||
|
if !float.suffix().is_empty() {
|
||||||
|
return Err(Error::new(float.span(), "Write the number without a type suffix. Its type is `f64`"));
|
||||||
|
}
|
||||||
|
let value: f64 = float.base10_parse()?;
|
||||||
|
ValueKind::Number(if negative { -value } else { value })
|
||||||
|
}
|
||||||
|
Lit::Bool(boolean) if !negative => ValueKind::Bool(boolean.value),
|
||||||
|
Lit::Str(string) if !negative => ValueKind::String(string.value()),
|
||||||
|
_ if negative => return Err(Error::new(literal.span(), "Only a number can be negated")),
|
||||||
|
_ => return Err(Error::new(literal.span(), "Unsupported literal")),
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(Self { kind, span })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Parse for Argument {
|
||||||
|
fn parse(input: ParseStream) -> syn::Result<Self> {
|
||||||
|
let attributes = parse_attributes(input)?;
|
||||||
|
|
||||||
|
let parameter = if input.peek(Ident) && input.peek2(Token![=]) && !input.peek2(Token![==]) {
|
||||||
|
let parameter = input.parse()?;
|
||||||
|
input.parse::<Token![=]>()?;
|
||||||
|
Some(parameter)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
let value = parse_expression(input)?;
|
||||||
|
|
||||||
|
Ok(Self { attributes, parameter, value })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn parse(text: &str) -> syn::Result<Source> {
|
||||||
|
syn::parse_str(text)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn error_message(text: &str) -> String {
|
||||||
|
match parse(text) {
|
||||||
|
Ok(_) => panic!("the graph text should be rejected"),
|
||||||
|
Err(error) => error.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reads_the_header_uses_and_graph() {
|
||||||
|
let source = parse(
|
||||||
|
r#"
|
||||||
|
#![syntax(1)]
|
||||||
|
use graphic_nodes::graphic::{as_graphic@1, extend@2 as append};
|
||||||
|
use graphic_nodes::graphic::into_group@1;
|
||||||
|
|
||||||
|
/// Merges content.
|
||||||
|
#[category("Graphic"), layer]
|
||||||
|
fn merge@3(base, #[expose] content) -> (out) {
|
||||||
|
let grouped = content >> into_group();
|
||||||
|
base >> as_graphic() >> append(new = grouped)
|
||||||
|
}
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.expect("the graph text should parse");
|
||||||
|
|
||||||
|
let uses: Vec<String> = source.uses.iter().map(|entry| format!("{}::{}@{}", entry.module_path(), entry.local_name(), entry.version)).collect();
|
||||||
|
assert_eq!(
|
||||||
|
uses,
|
||||||
|
["graphic_nodes::graphic::as_graphic@1", "graphic_nodes::graphic::append@2", "graphic_nodes::graphic::into_group@1"]
|
||||||
|
);
|
||||||
|
|
||||||
|
let graph = &source.graph;
|
||||||
|
assert_eq!(graph.name, "merge");
|
||||||
|
assert_eq!(graph.version, 3);
|
||||||
|
assert_eq!(doc_comment(&graph.attributes), "Merges content.");
|
||||||
|
assert_eq!(graph.imports.len(), 2);
|
||||||
|
assert_eq!(graph.bindings.len(), 1);
|
||||||
|
assert!(matches!(graph.result, Expression::Feed { .. }));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reads_state_values_and_outputs() {
|
||||||
|
let source = parse(
|
||||||
|
r#"
|
||||||
|
#![syntax(1)]
|
||||||
|
use a::b::{f@1, g@1};
|
||||||
|
fn state@1(_, x) -> (match, other) {
|
||||||
|
let node = f(#[exposed] flag = false, offset = -2.5, size = [1, -2.], count = 3, label = "text", x).named("N").offset(0, -2).hidden();
|
||||||
|
(node.match, node >> g())
|
||||||
|
}
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.expect("the graph text should parse");
|
||||||
|
|
||||||
|
let graph = &source.graph;
|
||||||
|
assert!(graph.imports[0].name.is_none());
|
||||||
|
assert_eq!(graph.exports[0].name, "match");
|
||||||
|
|
||||||
|
let Expression::Call(call) = &graph.bindings[0].value else {
|
||||||
|
panic!("the binding should be a call")
|
||||||
|
};
|
||||||
|
let kinds: Vec<StateKind> = call.states.iter().map(|state| state.kind.clone()).collect();
|
||||||
|
assert!(kinds == [StateKind::Named("N".into()), StateKind::Offset(0, -2), StateKind::Hidden]);
|
||||||
|
assert!(matches!(call.arguments[1].value, Expression::Value(Value { kind: ValueKind::Number(-2.5), .. })));
|
||||||
|
assert!(matches!(call.arguments[2].value, Expression::Value(Value { kind: ValueKind::Vec2(1., -2.), .. })));
|
||||||
|
assert!(matches!(call.arguments[3].value, Expression::Value(Value { kind: ValueKind::Integer(3), .. })));
|
||||||
|
assert!(call.arguments[5].parameter.is_none());
|
||||||
|
|
||||||
|
let Expression::Tuple { elements, .. } = &graph.result else {
|
||||||
|
panic!("the result should be a tuple")
|
||||||
|
};
|
||||||
|
assert!(matches!(&elements[0], Expression::Output { output, .. } if output == "match"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_text_without_a_supported_header() {
|
||||||
|
assert!(error_message("fn a@1() -> (out) { b() }").contains("starts with its syntax version"));
|
||||||
|
assert!(error_message("#![syntax(2)] fn a@1() -> (out) { b() }").contains("isn't supported"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_unversioned_and_unqualified_names() {
|
||||||
|
assert!(error_message("#![syntax(1)] use a::b; fn a@1() -> (out) { b() }").contains("Give the version"));
|
||||||
|
assert!(error_message("#![syntax(1)] use b@1; fn a@1() -> (out) { b() }").contains("full path"));
|
||||||
|
assert!(error_message("#![syntax(1)] fn a() -> (out) { b() }").contains("Give the version"));
|
||||||
|
assert!(error_message("#![syntax(1)] fn a@0() -> (out) { b() }").contains("start at 1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_typed_imports_and_suffixed_literals() {
|
||||||
|
assert!(error_message("#![syntax(1)] fn a@1(x: Item<f64>) -> (out) { b(x) }").contains("take no type"));
|
||||||
|
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b(c = 1_u32) }").contains("without a type suffix"));
|
||||||
|
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b(c = 1.5_f32) }").contains("without a type suffix"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_misplaced_state() {
|
||||||
|
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { let n = b(); n.hidden() }").contains("not on a binding"));
|
||||||
|
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b().out.hidden() }").contains("before the output"));
|
||||||
|
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b().hidden().hidden() }").contains("already set"));
|
||||||
|
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b().weight(2) }").contains("Unknown node state"));
|
||||||
|
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b().at(1.5, 2) }").contains("integers in grid units"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_a_semicolon_after_the_exports() {
|
||||||
|
assert!(error_message("#![syntax(1)] fn a@1() -> (out) { b(); }").contains("without a semicolon"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,324 @@
|
|||||||
|
use super::*;
|
||||||
|
use crate::resolve::blank_field;
|
||||||
|
use core_types::registry::{FieldMetadata, GraphInputSource, GraphNodeImplementation, GraphValue, NodeFlags, RegistryValueSource};
|
||||||
|
use core_types::{Type, concrete};
|
||||||
|
|
||||||
|
fn parameter(identifier: &'static str, default_type: Type) -> FieldMetadata {
|
||||||
|
FieldMetadata {
|
||||||
|
name: identifier,
|
||||||
|
identifier,
|
||||||
|
description: "From the node.",
|
||||||
|
default_type: Some(default_type),
|
||||||
|
..blank_field()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn proto_node(fields: Vec<FieldMetadata>) -> NodeMetadata {
|
||||||
|
NodeMetadata {
|
||||||
|
display_name: "",
|
||||||
|
category: "",
|
||||||
|
icon: None,
|
||||||
|
fields,
|
||||||
|
description: "",
|
||||||
|
inspector: None,
|
||||||
|
context_features: Vec::new(),
|
||||||
|
flags: NodeFlags::default(),
|
||||||
|
version: 1,
|
||||||
|
output_fields: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `test_nodes::Group(content)`, `test_nodes::Extend(base, new)`, and `test_nodes::Scale(value, factor, label)`.
|
||||||
|
fn proto_nodes() -> HashMap<ProtoNodeIdentifier, NodeMetadata> {
|
||||||
|
let list = || Type::List(Box::new(concrete!(f64)));
|
||||||
|
let number = || Type::Item(Box::new(concrete!(f64)));
|
||||||
|
|
||||||
|
let mut factor = parameter("factor", number());
|
||||||
|
factor.unit = Some(" px");
|
||||||
|
factor.value_source = RegistryValueSource::Default("2.");
|
||||||
|
|
||||||
|
HashMap::from([
|
||||||
|
(ProtoNodeIdentifier::new("test_nodes::GroupNode"), proto_node(vec![parameter("content", list())])),
|
||||||
|
(
|
||||||
|
ProtoNodeIdentifier::new("test_nodes::ExtendNode"),
|
||||||
|
proto_node(vec![parameter("base", list()), parameter("new", list())]),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
ProtoNodeIdentifier::new("test_nodes::ScaleNode"),
|
||||||
|
proto_node(vec![parameter("value", number()), factor, parameter("label", Type::Item(Box::new(concrete!(String))))]),
|
||||||
|
),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn source(text: &'static str) -> GraphSource {
|
||||||
|
GraphSource {
|
||||||
|
module_path: "test_graphs",
|
||||||
|
file: "test_graphs.rs",
|
||||||
|
line: 1,
|
||||||
|
column: 1,
|
||||||
|
text,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resolve_texts(texts: &[&'static str]) -> (Vec<GraphMetadata>, Vec<GraphTextError>) {
|
||||||
|
let sources: Vec<GraphSource> = texts.iter().map(|text| source(text)).collect();
|
||||||
|
resolve_sources(&sources, &proto_nodes())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resolve_one(text: &'static str) -> GraphMetadata {
|
||||||
|
let (mut graphs, errors) = resolve_texts(&[text]);
|
||||||
|
assert!(errors.is_empty(), "the graph should resolve: {}", errors.iter().map(ToString::to_string).collect::<Vec<_>>().join("\n"));
|
||||||
|
graphs.remove(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn error_message(text: &'static str) -> String {
|
||||||
|
let (graphs, errors) = resolve_texts(&[text]);
|
||||||
|
assert!(graphs.is_empty(), "the graph should be rejected");
|
||||||
|
errors.iter().map(ToString::to_string).collect::<Vec<_>>().join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
const MERGE: &str = r#"
|
||||||
|
#![syntax(1)]
|
||||||
|
use test_nodes::{extend@1, group@1};
|
||||||
|
|
||||||
|
/// Merges content.
|
||||||
|
#[category("Test"), layer]
|
||||||
|
fn merge@1(
|
||||||
|
/// The stack below.
|
||||||
|
base,
|
||||||
|
#[expose]
|
||||||
|
content,
|
||||||
|
) -> (out) {
|
||||||
|
base >> extend(new = content >> group())
|
||||||
|
}
|
||||||
|
"#;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolves_nodes_wires_and_layout() {
|
||||||
|
let graph = resolve_one(MERGE);
|
||||||
|
|
||||||
|
assert_eq!(graph.identifier, "Merge");
|
||||||
|
assert_eq!(graph.path, "test_graphs::merge");
|
||||||
|
assert_eq!(graph.description, "Merges content.");
|
||||||
|
assert!(graph.layer);
|
||||||
|
|
||||||
|
let implementations: Vec<_> = graph.nodes.iter().map(|node| node.implementation.clone()).collect();
|
||||||
|
assert_eq!(
|
||||||
|
implementations,
|
||||||
|
[
|
||||||
|
GraphNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test_nodes::GroupNode")),
|
||||||
|
GraphNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test_nodes::ExtendNode")),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert!(matches!(
|
||||||
|
graph.nodes[1].inputs.as_slice(),
|
||||||
|
[(1, GraphInputSource::Node { node: 0, output: 0 }), (0, GraphInputSource::Import { index: 0, .. })]
|
||||||
|
));
|
||||||
|
assert!(matches!(graph.exports[0].source, GraphInputSource::Node { node: 1, output: 0 }));
|
||||||
|
|
||||||
|
let positions: Vec<_> = graph.nodes.iter().map(|node| node.position).collect();
|
||||||
|
assert_eq!(positions, [(-7, 1), (0, 0)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn imports_inherit_from_the_input_they_feed_unless_overridden() {
|
||||||
|
let graph = resolve_one(
|
||||||
|
r#"
|
||||||
|
#![syntax(1)]
|
||||||
|
use test_nodes::scale@1;
|
||||||
|
|
||||||
|
#[category("Test")]
|
||||||
|
fn scaled@1(value, factor, #[unit("%")] #[default(10)] other) -> (out) {
|
||||||
|
let first = value >> scale(factor);
|
||||||
|
first >> scale(factor = other)
|
||||||
|
}
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
|
||||||
|
let [value, factor, other] = graph.imports.as_slice() else {
|
||||||
|
panic!("the graph should have three imports")
|
||||||
|
};
|
||||||
|
assert_eq!(value.name, "Value");
|
||||||
|
assert_eq!(factor.unit, Some(" px"));
|
||||||
|
assert_eq!(factor.description, "From the node.");
|
||||||
|
assert!(matches!(factor.value_source, RegistryValueSource::Default("2.")));
|
||||||
|
|
||||||
|
assert_eq!(other.unit, Some("%"));
|
||||||
|
assert!(matches!(other.value_source, RegistryValueSource::Default("10")));
|
||||||
|
assert_eq!(other.default_type, Some(concrete!(i64)));
|
||||||
|
assert!(matches!(&graph.nodes[1].inputs[0].1, GraphInputSource::Import { index: 2, ty } if *ty == Type::Item(Box::new(concrete!(i64)))));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_import_inherits_from_the_parameter_of_its_own_name_first() {
|
||||||
|
let graph = resolve_one(
|
||||||
|
r#"
|
||||||
|
#![syntax(1)]
|
||||||
|
use test_nodes::scale@1;
|
||||||
|
|
||||||
|
#[category("Test")]
|
||||||
|
fn scaled@1(value, label) -> (out) {
|
||||||
|
let first = value >> scale(factor = 1., label = value);
|
||||||
|
first >> scale(label)
|
||||||
|
}
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(graph.imports[0].default_type, Some(Type::Item(Box::new(concrete!(f64)))));
|
||||||
|
assert_eq!(graph.imports[1].default_type, Some(Type::Item(Box::new(concrete!(String)))));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn values_keep_the_type_they_are_written_with() {
|
||||||
|
let graph = resolve_one(
|
||||||
|
r#"
|
||||||
|
#![syntax(1)]
|
||||||
|
use test_nodes::scale@1;
|
||||||
|
|
||||||
|
#[category("Test")]
|
||||||
|
fn values@1(value) -> (out) {
|
||||||
|
value >> scale(factor = 2, #[exposed] label = "text")
|
||||||
|
}
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
|
||||||
|
let inputs = &graph.nodes[0].inputs;
|
||||||
|
assert!(matches!(
|
||||||
|
&inputs[0].1,
|
||||||
|
GraphInputSource::Value {
|
||||||
|
value: GraphValue::Integer(2),
|
||||||
|
exposed: None
|
||||||
|
}
|
||||||
|
));
|
||||||
|
assert!(matches!(&inputs[1].1, GraphInputSource::Value { value: GraphValue::String(text), exposed: Some(true) } if text == "text"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_graph_resolves_after_a_graph_it_uses_and_chooses_its_outputs_by_name() {
|
||||||
|
let outer = r#"
|
||||||
|
#![syntax(1)]
|
||||||
|
use test_graphs::pair@1;
|
||||||
|
use test_nodes::group@1;
|
||||||
|
|
||||||
|
#[category("Test")]
|
||||||
|
fn outer@1(content) -> (out) {
|
||||||
|
content >> pair().second >> group()
|
||||||
|
}
|
||||||
|
"#;
|
||||||
|
let pair = r#"
|
||||||
|
#![syntax(1)]
|
||||||
|
use test_nodes::group@1;
|
||||||
|
|
||||||
|
#[category("Test")]
|
||||||
|
fn pair@1(content) -> (first, second) {
|
||||||
|
let grouped = content >> group();
|
||||||
|
(grouped, grouped >> group())
|
||||||
|
}
|
||||||
|
"#;
|
||||||
|
|
||||||
|
let (graphs, errors) = resolve_texts(&[outer, pair]);
|
||||||
|
assert!(errors.is_empty(), "both graphs should resolve");
|
||||||
|
|
||||||
|
let outer = graphs.iter().find(|graph| graph.identifier == "Outer").expect("the outer graph should resolve");
|
||||||
|
assert_eq!(outer.nodes[0].implementation, GraphNodeImplementation::Graph("Pair"));
|
||||||
|
assert!(matches!(outer.nodes[1].inputs[0].1, GraphInputSource::Node { node: 0, output: 1 }));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_names_that_dont_resolve() {
|
||||||
|
let unknown_parameter = error_message(
|
||||||
|
r#"
|
||||||
|
#![syntax(1)]
|
||||||
|
use test_nodes::group@1;
|
||||||
|
#[category("Test")]
|
||||||
|
fn bad@1(content) -> (out) { content >> group(weight = 2) }
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
assert!(unknown_parameter.contains("`group` has no parameter named `weight`"), "{unknown_parameter}");
|
||||||
|
|
||||||
|
let unknown_node = error_message(
|
||||||
|
r#"
|
||||||
|
#![syntax(1)]
|
||||||
|
use test_nodes::missing@1;
|
||||||
|
#[category("Test")]
|
||||||
|
fn bad@1(content) -> (out) { content >> missing() }
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
assert!(unknown_node.contains("No node or graph is named `test_nodes::missing`"), "{unknown_node}");
|
||||||
|
|
||||||
|
let not_used = error_message(
|
||||||
|
r#"
|
||||||
|
#![syntax(1)]
|
||||||
|
#[category("Test")]
|
||||||
|
fn bad@1(content) -> (out) { content >> group() }
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
assert!(not_used.contains("`group` isn't used"), "{not_used}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_wrong_versions_and_unused_entries() {
|
||||||
|
let wrong_version = error_message(
|
||||||
|
r#"
|
||||||
|
#![syntax(1)]
|
||||||
|
use test_nodes::group@2;
|
||||||
|
#[category("Test")]
|
||||||
|
fn bad@1(content) -> (out) { content >> group() }
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
assert!(wrong_version.contains("is at version 1, not 2"), "{wrong_version}");
|
||||||
|
|
||||||
|
let unused = error_message(
|
||||||
|
r#"
|
||||||
|
#![syntax(1)]
|
||||||
|
use test_nodes::{extend@1, group@1};
|
||||||
|
#[category("Test")]
|
||||||
|
fn bad@1(content) -> (out) { content >> group() }
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
assert!(unused.contains("`extend` is used but never called"), "{unused}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_wiring_mistakes() {
|
||||||
|
let primary_twice = error_message(
|
||||||
|
r#"
|
||||||
|
#![syntax(1)]
|
||||||
|
use test_nodes::group@1;
|
||||||
|
#[category("Test")]
|
||||||
|
fn bad@1(content) -> (out) { content >> group(content) }
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
assert!(primary_twice.contains("is already fed"), "{primary_twice}");
|
||||||
|
|
||||||
|
let looped = error_message(
|
||||||
|
r#"
|
||||||
|
#![syntax(1)]
|
||||||
|
use test_nodes::group@1;
|
||||||
|
#[category("Test")]
|
||||||
|
fn bad@1(content) -> (out) {
|
||||||
|
let node = group();
|
||||||
|
node >> node
|
||||||
|
}
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
assert!(looped.contains("makes a loop"), "{looped}");
|
||||||
|
|
||||||
|
let export_from_import = error_message(
|
||||||
|
r#"
|
||||||
|
#![syntax(1)]
|
||||||
|
#[category("Test")]
|
||||||
|
fn bad@1(content) -> (out) { content }
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
assert!(export_from_import.contains("straight from an import"), "{export_from_import}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn errors_name_where_the_graph_is_written() {
|
||||||
|
let (_, errors) = resolve_texts(&["#![syntax(1)] #[category(\"Test\")] fn bad@1(content) -> (out) { content >> missing() }"]);
|
||||||
|
let error = errors.first().expect("the graph should be rejected");
|
||||||
|
|
||||||
|
assert_eq!((error.file, error.line, error.column), ("test_graphs.rs", 1, 1));
|
||||||
|
assert!(error.excerpt.starts_with("missing()"), "{}", error.excerpt);
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ use convert_case::{Case, Casing};
|
|||||||
use proc_macro2::TokenStream as TokenStream2;
|
use proc_macro2::TokenStream as TokenStream2;
|
||||||
use quote::{ToTokens, format_ident, quote, quote_spanned};
|
use quote::{ToTokens, format_ident, quote, quote_spanned};
|
||||||
use std::sync::atomic::AtomicU64;
|
use std::sync::atomic::AtomicU64;
|
||||||
|
use syn::ext::IdentExt;
|
||||||
use syn::punctuated::Punctuated;
|
use syn::punctuated::Punctuated;
|
||||||
use syn::spanned::Spanned;
|
use syn::spanned::Spanned;
|
||||||
use syn::token::Comma;
|
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();
|
let data_field_names: Vec<_> = data_fields.iter().map(|f| &f.pat_ident.ident).collect();
|
||||||
|
|
||||||
// Only regular fields have input names/descriptions (for UI)
|
// Only regular fields have input names/descriptions (for UI)
|
||||||
let input_names: Vec<_> = regular_fields
|
let input_names: Vec<_> = regular_fields.iter().map(|field| parameter_display_name(field)).collect();
|
||||||
.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();
|
|
||||||
|
|
||||||
// The primary input is not a parameter, so generators can name their unused one `_primary` without it becoming internal
|
// 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
|
let input_internal = regular_field_names
|
||||||
@@ -174,56 +167,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
|||||||
})
|
})
|
||||||
.collect();
|
.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
|
let default_types: Vec<_> = regular_fields
|
||||||
.iter()
|
.iter()
|
||||||
.enumerate()
|
.enumerate()
|
||||||
@@ -270,64 +213,12 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
|||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
let bound_values = |select: fn(&RegularParsedField) -> &Option<NumberBound>| -> Vec<_> {
|
// Only regular fields have UI metadata (data fields are internal state)
|
||||||
regular_fields
|
let field_metadata: 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
|
|
||||||
.iter()
|
.iter()
|
||||||
.map(|field| match field.ty.regular() {
|
.zip(&input_internal)
|
||||||
Some(RegularParsedField { number_mode_range, .. }) => quote!(#number_mode_range),
|
.zip(&default_types)
|
||||||
None => quote!(false),
|
.map(|((field, internal), default_type)| field_metadata_tokens(field, *internal, default_type, core_types))
|
||||||
})
|
|
||||||
.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)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
// Only eval regular fields (data fields are accessed directly as self.field_name)
|
// 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)]),
|
Some(cfg) => quote!(#[cfg(#cfg)]),
|
||||||
None => quote!(),
|
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, ¶meter_idents, core_types, &identifier, &cfg);
|
||||||
|
|
||||||
let mapped_node_impl = match (&mapped_struct_where_clause, &mapped_eval_impl) {
|
let mapped_node_impl = match (&mapped_struct_where_clause, &mapped_eval_impl) {
|
||||||
(Some(mapped_where_clause), Some(mapped_eval)) => quote! {
|
(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::{Node, NodeIOTypes, concrete, fn_type, ProtoNodeIdentifier, WasmNotSync, NodeIO, ContextFeature};
|
||||||
use gcore::value::ClonedNode;
|
use gcore::value::ClonedNode;
|
||||||
use gcore::ops::TypeNode;
|
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 gcore::ctor::ctor;
|
||||||
|
|
||||||
// Use the types specified in the implementation
|
// Use the types specified in the implementation
|
||||||
@@ -1056,31 +948,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
|||||||
},
|
},
|
||||||
version: #version,
|
version: #version,
|
||||||
output_fields: #output_fields,
|
output_fields: #output_fields,
|
||||||
fields: vec![
|
fields: vec![#(#field_metadata,)*],
|
||||||
#(
|
|
||||||
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,
|
|
||||||
},
|
|
||||||
)*
|
|
||||||
],
|
|
||||||
};
|
};
|
||||||
NODE_METADATA.lock().unwrap().insert(#identifier(), metadata);
|
NODE_METADATA.lock().unwrap().insert(#identifier(), metadata);
|
||||||
}
|
}
|
||||||
@@ -1088,6 +956,132 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The display name an identifier derives, in Title Case.
|
||||||
|
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.
|
||||||
|
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.
|
||||||
|
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.
|
||||||
|
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.
|
||||||
|
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 identifier = field.pat_ident.ident.unraw().to_string();
|
||||||
|
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| ®ular.number_soft_min);
|
||||||
|
let number_soft_max = bound(|regular| ®ular.number_soft_max);
|
||||||
|
let number_hard_min = bound(|regular| ®ular.number_hard_min);
|
||||||
|
let number_hard_max = bound(|regular| ®ular.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,
|
||||||
|
identifier: #identifier,
|
||||||
|
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).
|
/// 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>> {
|
fn color_constant_paths(tokens: &TokenStream2) -> Option<Vec<ExprPath>> {
|
||||||
use syn::parse::Parser;
|
use syn::parse::Parser;
|
||||||
@@ -1108,26 +1102,23 @@ fn color_constant_paths(tokens: &TokenStream2) -> Option<Vec<ExprPath>> {
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Generates the per-parameter symbol types used to reference this node's inputs.
|
/// Generates the module named after the node's function, holding its identifier and a symbol for each parameter.
|
||||||
fn generate_node_input_references(parsed: &ParsedNodeFn, field_idents: &[&PatIdent], core_types: &TokenStream2, identifier: &Ident, cfg: &TokenStream2) -> TokenStream2 {
|
/// The inputs the compiler fills in come after the parameters and get no symbol.
|
||||||
let inputs_module_name = format_ident!("{}", parsed.struct_name.to_string().to_case(Case::Snake));
|
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();
|
// Every parameter gets a plain unit struct: the symbol used across the codebase to name this input
|
||||||
if !parsed.attributes.flags.skip_impl {
|
let generated_input_accessor = parameter_idents.iter().enumerate().map(|(input_index, input_ident)| {
|
||||||
for (input_index, input_ident) in field_idents.iter().enumerate() {
|
// TODO: figure out a better name that doesn't conflict with so many types
|
||||||
// TODO: figure out a better name that doesn't conflict with so many types
|
let struct_name = symbol_name(&input_ident.ident, "Input");
|
||||||
let struct_name = format_ident!("{}Input", input_ident.ident.to_string().to_case(Case::Pascal));
|
quote! {
|
||||||
|
pub struct #struct_name;
|
||||||
// Every parameter gets a plain unit struct: the symbol used across the codebase to name this input
|
impl #core_types::NodeParameter for #struct_name {
|
||||||
generated_input_accessor.push(quote! {
|
const NODE_IDENTIFIER: #core_types::ProtoNodeIdentifier = #inputs_module_name::IDENTIFIER;
|
||||||
pub struct #struct_name;
|
const INDEX: usize = #input_index;
|
||||||
impl #core_types::NodeParameter for #struct_name {
|
}
|
||||||
const NODE_IDENTIFIER: #core_types::ProtoNodeIdentifier = #inputs_module_name::IDENTIFIER;
|
|
||||||
const INDEX: usize = #input_index;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
|
|
||||||
quote! {
|
quote! {
|
||||||
#cfg
|
#cfg
|
||||||
|
|||||||
@@ -137,6 +137,10 @@ pub struct ParsedField {
|
|||||||
pub progression: bool,
|
pub progression: bool,
|
||||||
pub constant: bool,
|
pub constant: bool,
|
||||||
pub is_data_field: 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 {
|
impl ParsedField {
|
||||||
@@ -170,6 +174,9 @@ impl ParsedField {
|
|||||||
progression: false,
|
progression: false,
|
||||||
constant: false,
|
constant: false,
|
||||||
is_data_field: false,
|
is_data_field: false,
|
||||||
|
labels: None,
|
||||||
|
integer: false,
|
||||||
|
blank_assist: true,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -978,6 +985,22 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
|||||||
})
|
})
|
||||||
.transpose()?;
|
.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 (is_node, node_input_type, node_output_type) = parse_node_type(&ty);
|
||||||
let description = attrs
|
let description = attrs
|
||||||
.iter()
|
.iter()
|
||||||
@@ -1036,6 +1059,9 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
|||||||
progression,
|
progression,
|
||||||
constant,
|
constant,
|
||||||
is_data_field,
|
is_data_field,
|
||||||
|
labels,
|
||||||
|
integer,
|
||||||
|
blank_assist,
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
let implementations = extract_attribute(attrs, "implementations")
|
let implementations = extract_attribute(attrs, "implementations")
|
||||||
@@ -1088,6 +1114,9 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
|||||||
progression,
|
progression,
|
||||||
constant,
|
constant,
|
||||||
is_data_field,
|
is_data_field,
|
||||||
|
labels,
|
||||||
|
integer,
|
||||||
|
blank_assist,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1387,6 +1416,9 @@ mod tests {
|
|||||||
progression: false,
|
progression: false,
|
||||||
constant: false,
|
constant: false,
|
||||||
is_data_field: false,
|
is_data_field: false,
|
||||||
|
labels: None,
|
||||||
|
integer: false,
|
||||||
|
blank_assist: true,
|
||||||
}],
|
}],
|
||||||
body: TokenStream2::new(),
|
body: TokenStream2::new(),
|
||||||
description: String::from("Multi\nLine\n"),
|
description: String::from("Multi\nLine\n"),
|
||||||
@@ -1449,6 +1481,9 @@ mod tests {
|
|||||||
progression: false,
|
progression: false,
|
||||||
constant: false,
|
constant: false,
|
||||||
is_data_field: false,
|
is_data_field: false,
|
||||||
|
labels: None,
|
||||||
|
integer: false,
|
||||||
|
blank_assist: true,
|
||||||
},
|
},
|
||||||
ParsedField {
|
ParsedField {
|
||||||
pat_ident: pat_ident("translate"),
|
pat_ident: pat_ident("translate"),
|
||||||
@@ -1473,6 +1508,9 @@ mod tests {
|
|||||||
progression: false,
|
progression: false,
|
||||||
constant: false,
|
constant: false,
|
||||||
is_data_field: false,
|
is_data_field: false,
|
||||||
|
labels: None,
|
||||||
|
integer: false,
|
||||||
|
blank_assist: true,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
body: TokenStream2::new(),
|
body: TokenStream2::new(),
|
||||||
@@ -1536,6 +1574,9 @@ mod tests {
|
|||||||
progression: false,
|
progression: false,
|
||||||
constant: false,
|
constant: false,
|
||||||
is_data_field: false,
|
is_data_field: false,
|
||||||
|
labels: None,
|
||||||
|
integer: false,
|
||||||
|
blank_assist: true,
|
||||||
}],
|
}],
|
||||||
body: TokenStream2::new(),
|
body: TokenStream2::new(),
|
||||||
description: "Test\n".into(),
|
description: "Test\n".into(),
|
||||||
@@ -1602,6 +1643,9 @@ mod tests {
|
|||||||
progression: false,
|
progression: false,
|
||||||
constant: false,
|
constant: false,
|
||||||
is_data_field: false,
|
is_data_field: false,
|
||||||
|
labels: None,
|
||||||
|
integer: false,
|
||||||
|
blank_assist: true,
|
||||||
}],
|
}],
|
||||||
body: TokenStream2::new(),
|
body: TokenStream2::new(),
|
||||||
description: String::new(),
|
description: String::new(),
|
||||||
@@ -1671,6 +1715,9 @@ mod tests {
|
|||||||
progression: false,
|
progression: false,
|
||||||
constant: false,
|
constant: false,
|
||||||
is_data_field: false,
|
is_data_field: false,
|
||||||
|
labels: None,
|
||||||
|
integer: false,
|
||||||
|
blank_assist: true,
|
||||||
}],
|
}],
|
||||||
body: TokenStream2::new(),
|
body: TokenStream2::new(),
|
||||||
description: String::new(),
|
description: String::new(),
|
||||||
@@ -1765,6 +1812,9 @@ mod tests {
|
|||||||
progression: false,
|
progression: false,
|
||||||
constant: false,
|
constant: false,
|
||||||
is_data_field: false,
|
is_data_field: false,
|
||||||
|
labels: None,
|
||||||
|
integer: false,
|
||||||
|
blank_assist: true,
|
||||||
}],
|
}],
|
||||||
body: TokenStream2::new(),
|
body: TokenStream2::new(),
|
||||||
description: String::new(),
|
description: String::new(),
|
||||||
|
|||||||
@@ -1,22 +1,21 @@
|
|||||||
use crate::parsing::{Implementation, NodeOutputTier, NodeParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField, output_payload, output_tier};
|
use crate::parsing::{Implementation, NodeOutputTier, NodeParsedField, ParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField, output_payload, output_tier};
|
||||||
use proc_macro_error3::{abort_if_dirty, emit_error};
|
use proc_macro_error3::{abort_if_dirty, emit_error};
|
||||||
use quote::quote;
|
use quote::quote;
|
||||||
use syn::spanned::Spanned;
|
use syn::spanned::Spanned;
|
||||||
use syn::{GenericParam, Type};
|
use syn::{GenericParam, Ident, Type};
|
||||||
|
|
||||||
pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
|
pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
|
||||||
let validators: &[fn(&ParsedNodeFn)] = &[
|
let validators: &[fn(&ParsedNodeFn)] = &[
|
||||||
// Add more validators here as needed
|
// Add more validators here as needed
|
||||||
validate_implementations_for_generics,
|
validate_implementations_for_generics,
|
||||||
validate_implementations_row_counts,
|
validate_implementations_row_counts,
|
||||||
validate_primary_input_expose,
|
|parsed| validate_parameters(&parsed.fields),
|
||||||
validate_min_max,
|
|
||||||
validate_range_slider_bounds,
|
|
||||||
validate_no_item_parameters,
|
validate_no_item_parameters,
|
||||||
validate_element_wise,
|
validate_element_wise,
|
||||||
validate_ranked_inputs,
|
validate_ranked_inputs,
|
||||||
validate_async,
|
validate_async,
|
||||||
validate_non_parameters_trail,
|
validate_non_parameters_trail,
|
||||||
|
|parsed| validate_name_isnt_a_value_helper(&parsed.fn_name),
|
||||||
];
|
];
|
||||||
|
|
||||||
for validator in validators {
|
for validator in validators {
|
||||||
@@ -28,6 +27,23 @@ pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The calls graph text reads as values or input sources rather than as nodes, so no node can share one's name.
|
||||||
|
const VALUE_HELPERS: &[&str] = &["rgb", "rgba", "scope", "reflect"];
|
||||||
|
|
||||||
|
/// Graph text reads a call to a value helper like `rgb(...)` as a value, so a node of that name couldn't be called there.
|
||||||
|
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) {
|
fn validate_no_item_parameters(parsed: &ParsedNodeFn) {
|
||||||
if parsed.attributes.flags.skip_impl {
|
if parsed.attributes.flags.skip_impl {
|
||||||
return;
|
return;
|
||||||
@@ -291,8 +307,15 @@ fn is_unit_type(ty: &Type) -> bool {
|
|||||||
matches!(ty, Type::Tuple(tuple) if tuple.elems.is_empty())
|
matches!(ty, Type::Tuple(tuple) if tuple.elems.is_empty())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn validate_min_max(parsed: &ParsedNodeFn) {
|
/// The checks on a node's parameters, where the first is the primary input.
|
||||||
for field in &parsed.fields {
|
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 {
|
if let Some(RegularParsedField {
|
||||||
number_hard_max,
|
number_hard_max,
|
||||||
number_hard_min,
|
number_hard_min,
|
||||||
@@ -351,8 +374,8 @@ fn validate_min_max(parsed: &ParsedNodeFn) {
|
|||||||
|
|
||||||
/// A `#[range]` slider needs a defined extent on both ends. The extent comes from `#[soft]` when present,
|
/// 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.
|
/// 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) {
|
fn validate_range_slider_bounds(fields: &[ParsedField]) {
|
||||||
for field in &parsed.fields {
|
for field in fields {
|
||||||
if let Some(RegularParsedField {
|
if let Some(RegularParsedField {
|
||||||
number_mode_range: true,
|
number_mode_range: true,
|
||||||
number_soft_min,
|
number_soft_min,
|
||||||
@@ -384,8 +407,8 @@ fn validate_range_slider_bounds(parsed: &ParsedNodeFn) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn validate_primary_input_expose(parsed: &ParsedNodeFn) {
|
fn validate_primary_input_expose(fields: &[ParsedField]) {
|
||||||
if let Some(field) = parsed.fields.first()
|
if let Some(field) = fields.first()
|
||||||
&& let Some(RegularParsedField { exposed: true, .. }) = field.ty.regular()
|
&& let Some(RegularParsedField { exposed: true, .. }) = field.ty.regular()
|
||||||
{
|
{
|
||||||
let pat_ident = &field.pat_ident;
|
let pat_ident = &field.pat_ident;
|
||||||
@@ -394,7 +417,7 @@ fn validate_primary_input_expose(parsed: &ParsedNodeFn) {
|
|||||||
"Unnecessary #[expose] attribute on primary input `{}`. Primary inputs are always exposed.",
|
"Unnecessary #[expose] attribute on primary input `{}`. Primary inputs are always exposed.",
|
||||||
pat_ident.ident;
|
pat_ident.ident;
|
||||||
help = "You can safely remove the #[expose] attribute from this field.";
|
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 +485,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.
|
/// 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) {
|
fn validate_non_parameters_trail(parsed: &ParsedNodeFn) {
|
||||||
if let Some((span, message)) = non_parameter_order_violation(parsed) {
|
if let Some((span, message)) = non_parameter_order_violation(parsed) {
|
||||||
emit_error!(span, "{}", message);
|
emit_error!(span, "{}", message);
|
||||||
@@ -475,7 +498,7 @@ fn non_parameter_order_violation(parsed: &ParsedNodeFn) -> Option<(proc_macro2::
|
|||||||
|
|
||||||
let (parameter, non_parameter) = (¶meter.pat_ident, &non_parameter.pat_ident.ident);
|
let (parameter, non_parameter) = (¶meter.pat_ident, &non_parameter.pat_ident.ident);
|
||||||
let message = format!(
|
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
|
parameter.ident
|
||||||
);
|
);
|
||||||
Some((parameter.span(), message))
|
Some((parameter.span(), message))
|
||||||
@@ -727,6 +750,25 @@ mod tests {
|
|||||||
assert_eq!(only_non_parameters, None);
|
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> {
|
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");
|
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()
|
implementations_row_count_violations(&parsed).into_iter().map(|(_, message)| message).collect()
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ dyn-any = { workspace = true }
|
|||||||
graph-craft = { workspace = true }
|
graph-craft = { workspace = true }
|
||||||
wgpu-executor = { workspace = true }
|
wgpu-executor = { workspace = true }
|
||||||
core-types = { workspace = true }
|
core-types = { workspace = true }
|
||||||
|
graph-text = { workspace = true }
|
||||||
vector-types = { workspace = true }
|
vector-types = { workspace = true }
|
||||||
graphic-types = { workspace = true }
|
graphic-types = { workspace = true }
|
||||||
raster-kernels = { workspace = true }
|
raster-kernels = { workspace = true }
|
||||||
|
|||||||
@@ -5,10 +5,12 @@ pub mod render_background;
|
|||||||
pub mod render_cache;
|
pub mod render_cache;
|
||||||
pub mod render_node;
|
pub mod render_node;
|
||||||
pub mod render_pixel_preview;
|
pub mod render_pixel_preview;
|
||||||
|
mod subgraphs;
|
||||||
pub mod text;
|
pub mod text;
|
||||||
pub use blending_nodes;
|
pub use blending_nodes;
|
||||||
pub use brush_nodes as brush;
|
pub use brush_nodes as brush;
|
||||||
pub use core_types::*;
|
pub use core_types::*;
|
||||||
|
pub use graph_text;
|
||||||
pub use graphene_application_io as application_io;
|
pub use graphene_application_io as application_io;
|
||||||
pub use graphene_core;
|
pub use graphene_core;
|
||||||
pub use graphene_core::debug;
|
pub use graphene_core::debug;
|
||||||
|
|||||||
@@ -0,0 +1,169 @@
|
|||||||
|
use core_types::graph;
|
||||||
|
|
||||||
|
graph! {
|
||||||
|
#![syntax(1)]
|
||||||
|
use graphic_nodes::graphic::{as_graphic@1, extend@1, into_group@1};
|
||||||
|
|
||||||
|
/// Merges the provided content as a new item in the layer's compositing stack.
|
||||||
|
#[category("Graphic"), icon("NodeMerge"), layer]
|
||||||
|
fn merge@1(
|
||||||
|
/// The stack of layers below this one, which the content is placed above.
|
||||||
|
base,
|
||||||
|
/// The artwork this layer adds to the stack as a single item.
|
||||||
|
#[expose]
|
||||||
|
content,
|
||||||
|
) -> (
|
||||||
|
/// The stack of layers with this layer's content placed on top.
|
||||||
|
out,
|
||||||
|
) {
|
||||||
|
base >> as_graphic() >> extend(new = content >> into_group())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
graph! {
|
||||||
|
#![syntax(1)]
|
||||||
|
use graphic_nodes::artboard::create_artboard@1;
|
||||||
|
use graphic_nodes::graphic::extend@1;
|
||||||
|
|
||||||
|
/// Creates a new Artboard which can be used as a working surface.
|
||||||
|
#[category("Graphic"), icon("NodeArtboard"), layer]
|
||||||
|
fn artboard@1(
|
||||||
|
/// The stack of artboards below this one, which this artboard is placed above.
|
||||||
|
base,
|
||||||
|
#[expose]
|
||||||
|
content,
|
||||||
|
#[labels("X", "Y")]
|
||||||
|
#[integer]
|
||||||
|
location,
|
||||||
|
#[labels("W", "H")]
|
||||||
|
#[integer]
|
||||||
|
#[default(1920., 1080.)]
|
||||||
|
dimensions,
|
||||||
|
#[widget(Custom = "artboard_background")]
|
||||||
|
#[default(Color::WHITE)]
|
||||||
|
background,
|
||||||
|
clip,
|
||||||
|
) -> (
|
||||||
|
/// The stack of artboards with this artboard placed on top.
|
||||||
|
out,
|
||||||
|
) {
|
||||||
|
base >> extend(new = create_artboard(content, location, dimensions, background, clip))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
graph! {
|
||||||
|
#![syntax(1)]
|
||||||
|
use core_types::vector::{morph@1, path_is_closed@1, separate_paths@1, read_index@1};
|
||||||
|
use graphene_core::vector::count@1;
|
||||||
|
use math_nodes::{add@1, as_number@1, divide@1, floor@1, max@1, modulo@1, multiply@1, subtract@1, switch@1};
|
||||||
|
use repeat_nodes::repeat_nodes::repeat@1;
|
||||||
|
|
||||||
|
/// Creates a series of intermediate shapes that gradually transition between vector objects, optionally along a control path.
|
||||||
|
#[category("Vector: Deform"), icon("NodeBlend")]
|
||||||
|
fn blend@1(
|
||||||
|
/// The vector objects to create intermediate shapes between.
|
||||||
|
content,
|
||||||
|
/// The number of shapes spanning from the first object to the last, repeated for each subpath of the control path.
|
||||||
|
#[default(10)]
|
||||||
|
count,
|
||||||
|
/// Flip the stacking order of the shapes, so the ones nearest the first object are on top.
|
||||||
|
reverse,
|
||||||
|
/// What changes evenly from one shape to the next, which sets how the intermediate shapes are spaced.
|
||||||
|
distribution,
|
||||||
|
/// An optional control path with one anchor point per object. Curved segments shape the trajectory of the blend instead of traveling straight.
|
||||||
|
path,
|
||||||
|
) -> (
|
||||||
|
/// The blended shapes, from the first object to the last.
|
||||||
|
out,
|
||||||
|
) {
|
||||||
|
let shapes_per_path = count >> as_number() >> max(other_value = 1.);
|
||||||
|
let path_count = path >> separate_paths() >> count() >> max(other_value = 1.);
|
||||||
|
|
||||||
|
let index = read_index();
|
||||||
|
let path_index = index >> divide(denominator = shapes_per_path) >> floor();
|
||||||
|
let local_index = index >> modulo(modulus = shapes_per_path);
|
||||||
|
|
||||||
|
let open_spacing = shapes_per_path >> subtract(subtrahend = 1.) >> max(other_value = 1.);
|
||||||
|
let spacing = path >> path_is_closed(index = path_index) >> switch(if_true = shapes_per_path, if_false = open_spacing);
|
||||||
|
|
||||||
|
let fraction = local_index >> divide(denominator = spacing) >> multiply(multiplicand = 0.9999999999);
|
||||||
|
let progression = path_index >> add(addend = fraction);
|
||||||
|
|
||||||
|
let total = shapes_per_path >> multiply(multiplicand = path_count);
|
||||||
|
content >> morph(progression, distribution, path) >> repeat(count = total, reverse)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
graph! {
|
||||||
|
#![syntax(1)]
|
||||||
|
use core_types::vector::{as_vector@1, extract_transform@1, points_to_polyline@1};
|
||||||
|
use graphene_core::vector::{combine_paths@1, read_vector@1};
|
||||||
|
use graphic_nodes::graphic::{flatten_vector@1, map@1};
|
||||||
|
use transform_nodes::transform_nodes::decompose_translation@1;
|
||||||
|
|
||||||
|
/// 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.
|
||||||
|
#[category("Vector: Path"), icon("NodeOriginsToPolyline"), name("Origins to Polyline")]
|
||||||
|
fn origins_to_polyline@1(
|
||||||
|
/// The vector objects to connect in order by their origins.
|
||||||
|
vector,
|
||||||
|
) -> (
|
||||||
|
/// An open polyline with an anchor point at the origin of each object.
|
||||||
|
vector,
|
||||||
|
) {
|
||||||
|
let origin = read_vector() >> extract_transform() >> decompose_translation() >> as_vector();
|
||||||
|
vector >> flatten_vector() >> map(mapped = origin) >> combine_paths() >> points_to_polyline(closed = false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
graph! {
|
||||||
|
#![syntax(1)]
|
||||||
|
use graphene_std::platform_application_io::{bytes_to_image@1, load_resource@1};
|
||||||
|
|
||||||
|
/// Loads an image from a given URL.
|
||||||
|
#[category("Data: I/O"), icon("NodeLoadImage")]
|
||||||
|
fn load_image@1(
|
||||||
|
_,
|
||||||
|
/// The web address or local asset path of the image to load.
|
||||||
|
#[name("URL")]
|
||||||
|
url,
|
||||||
|
) -> (
|
||||||
|
/// The loaded image.
|
||||||
|
image,
|
||||||
|
) {
|
||||||
|
load_resource(url) >> bytes_to_image()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
graph! {
|
||||||
|
#![syntax(1)]
|
||||||
|
use graphic_nodes::graphic::{item_at_index@1, remove_at_index@1};
|
||||||
|
use text_nodes::regex::regex_find@1 as find;
|
||||||
|
|
||||||
|
/// 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.
|
||||||
|
#[category("String: Regex"), icon("NodeRegexFind")]
|
||||||
|
fn regex_find@1(string, pattern, match_index, case_insensitive, multiline) -> (
|
||||||
|
/// The whole portion of the string matching the pattern, or empty if there is no match.
|
||||||
|
match,
|
||||||
|
/// The text matched by each capture group in the pattern, in order.
|
||||||
|
captures,
|
||||||
|
) {
|
||||||
|
let found = string >> find(pattern, match_index, case_insensitive, multiline);
|
||||||
|
(found >> item_at_index(index = 0), found >> remove_at_index(index = 0))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use core_types::registry::{GRAPH_SOURCES, NODE_METADATA};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_graph_resolves() {
|
||||||
|
let sources = GRAPH_SOURCES.lock().unwrap().clone();
|
||||||
|
let (graphs, errors) = graph_text::resolve_sources(&sources, &NODE_METADATA.lock().unwrap());
|
||||||
|
|
||||||
|
let messages: Vec<String> = errors.iter().map(ToString::to_string).collect();
|
||||||
|
assert!(messages.is_empty(), "every graph should resolve:\n{}", messages.join("\n"));
|
||||||
|
assert_eq!(graphs.len(), sources.len());
|
||||||
|
assert!(graphs.iter().any(|graph| graph.identifier == "Merge"), "the graphs should be registered at startup");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -416,7 +416,8 @@ pub fn node_inputs(fields: &[registry::FieldMetadata], first_node_io: &NodeIOTyp
|
|||||||
return NodeInput::value(TaggedValue::None, true);
|
return NodeInput::value(TaggedValue::None, true);
|
||||||
};
|
};
|
||||||
let ty = ty.clone().normalize_rank();
|
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 {
|
match &field.value_source {
|
||||||
RegistryValueSource::None => {}
|
RegistryValueSource::None => {}
|
||||||
@@ -543,7 +544,7 @@ mod destructure_tests {
|
|||||||
fn vec2_to_numbers_network() -> NodeNetwork {
|
fn vec2_to_numbers_network() -> NodeNetwork {
|
||||||
let vec2_to_numbers = DocumentNode {
|
let vec2_to_numbers = DocumentNode {
|
||||||
inputs: vec![NodeInput::value(TaggedValue::DVec2(DVec2::new(3., 5.)), false)],
|
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()
|
..Default::default()
|
||||||
};
|
};
|
||||||
multi_output_into_add_network(vec2_to_numbers, [1, 2])
|
multi_output_into_add_network(vec2_to_numbers, [1, 2])
|
||||||
@@ -561,7 +562,7 @@ mod destructure_tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn multi_output_node_expands_into_generated_destructure_network() {
|
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
|
let destructure = registry::MULTI_OUTPUT_NODES
|
||||||
.get(&vec2_to_numbers_identifier)
|
.get(&vec2_to_numbers_identifier)
|
||||||
.expect("Vec2 to Numbers should be registered as a multi-output node");
|
.expect("Vec2 to Numbers should be registered as a multi-output node");
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ pub const OMIT_HIDDEN: bool = true;
|
|||||||
pub fn category_description(category: &str) -> &str {
|
pub fn category_description(category: &str) -> &str {
|
||||||
match category {
|
match category {
|
||||||
"Value" => "Nodes in this category supply data values of common types such as numbers, colors, gradients, booleans, and strings.",
|
"Value" => "Nodes in this category supply data values of common types such as numbers, colors, gradients, booleans, and strings.",
|
||||||
"Routing" => "Nodes in this category direct how data flows through the graph, such as switching between inputs, repeating steps on a result, wrapping nodes into a custom subgraph, and caching results.",
|
"Routing" => "Nodes in this category direct how data flows through the graph, such as switching between inputs, repeating steps on a result, and caching results.",
|
||||||
"Transform" => "Nodes in this category move, rotate, scale, and skew graphical content, read and combine the transformation matrices that place it, and arrange items by packing them into rows or columns.",
|
"Transform" => "Nodes in this category move, rotate, scale, and skew graphical content, read and combine the transformation matrices that place it, and arrange items by packing them into rows or columns.",
|
||||||
"Graphic" => "Nodes in this category compose graphical content of any kind, such as merging layers, making artboards and groups, blending and clipping, repeating and mirroring copies, and flattening nested groups.",
|
"Graphic" => "Nodes in this category compose graphical content of any kind, such as merging layers, making artboards and groups, blending and clipping, repeating and mirroring copies, and flattening nested groups.",
|
||||||
"Vector: Style" => "Nodes in this category apply fill and stroke styles to alter the appearance of vector graphics.",
|
"Vector: Style" => "Nodes in this category apply fill and stroke styles to alter the appearance of vector graphics.",
|
||||||
|
|||||||
@@ -219,7 +219,7 @@ Writing to any other node fails, since another anchor's run may be editing it.
|
|||||||
|
|
||||||
### Network definitions
|
### 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 in graph text 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 after the graph's name, like `fn artboard@2`, when instances saved before your change would load wrongly, and register a migration from the old version with the `network` prefix:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
rename!(network "Artboard"@1 => @2);
|
rename!(network "Artboard"@1 => @2);
|
||||||
|
|||||||
Reference in new issue
Block a user