From fffb9d20f79f699f4bd988ce4e69608472c6d794 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Tue, 17 Nov 2026 03:55:04 -0800 Subject: [PATCH 1/2] Fix CLI exports failing or misframing artwork with 'Merge' and 'Artboard' --- document/live/src/lib.rs | 8 +- editor/src/node_graph_executor/runtime.rs | 6 +- .../runtime/layer_path_tests.rs | 65 ++++++ .../node_graph_executor/runtime/thumbnails.rs | 4 +- node-graph/graphene-cli/src/dump.rs | 4 + node-graph/graphene-cli/src/lib.rs | 209 +++++++++++++++++- node-graph/graphene-cli/src/watch.rs | 9 +- .../interpreted-executor/src/layer_paths.rs | 166 +++++++------- node-graph/interpreted-executor/src/lib.rs | 1 + node-graph/nodes/graphic/src/graphic.rs | 9 +- 10 files changed, 382 insertions(+), 99 deletions(-) create mode 100644 editor/src/node_graph_executor/runtime/layer_path_tests.rs rename editor/src/node_graph_executor/runtime/layer_content.rs => node-graph/interpreted-executor/src/layer_paths.rs (67%) diff --git a/document/live/src/lib.rs b/document/live/src/lib.rs index 7652c11be44..33c289b17af 100644 --- a/document/live/src/lib.rs +++ b/document/live/src/lib.rs @@ -3,7 +3,7 @@ use document_container::AnyContainer; use document_container::backends::memory::MemoryBackend; use document_format::{GddV1, GddV1Layout}; -use document_graph_storage::{PeerId, UserId}; +use document_graph_storage::{NodeMetadataEntry, PeerId, UserId}; use graph_craft::application_io::resource::ResourceHash; use graph_craft::document::NodeNetwork; use peer_transport::{Room, SyncTarget}; @@ -97,10 +97,10 @@ impl LiveDocument { &mut self.gdd } - pub async fn network(&self) -> Result { + /// The document's runtime network, with the metadata of each of its nodes. + pub async fn network_with_metadata(&self) -> Result<(NodeNetwork, Vec), LiveError> { let declarations = self.gdd.declarations(&self.gdd).await; - let (network, _metadata) = self.gdd.registry().to_runtime_with_metadata(&declarations, self.gdd.blobs())?; - Ok(network) + Ok(self.gdd.registry().to_runtime_with_metadata(&declarations, self.gdd.blobs())?) } pub fn leave(&mut self) { diff --git a/editor/src/node_graph_executor/runtime.rs b/editor/src/node_graph_executor/runtime.rs index 3ad44a815b7..0a953d1daf1 100644 --- a/editor/src/node_graph_executor/runtime.rs +++ b/editor/src/node_graph_executor/runtime.rs @@ -19,6 +19,7 @@ use graphene_std::runtime::AsyncRuntime; use graphene_std::vector::style::RenderMode; use graphene_std::{Context, NodeError, Poll}; use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta}; +use interpreted_executor::layer_paths::write_layer_paths; use interpreted_executor::util::wrap_network_in_scope; use observer::Observer; pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue}; @@ -27,7 +28,8 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{Receiver, Sender}; use thumbnails::Thumbnails; -mod layer_content; +#[cfg(test)] +mod layer_path_tests; mod observer; mod thumbnails; @@ -213,7 +215,7 @@ impl NodeRuntime { }; apply_previews(&mut network, &previewed); - layer_content::write_layer_paths(&mut network, &layers); + write_layer_paths(&mut network, &layers); self.observer.replace_all(observations); self.resources = resources; diff --git a/editor/src/node_graph_executor/runtime/layer_path_tests.rs b/editor/src/node_graph_executor/runtime/layer_path_tests.rs new file mode 100644 index 00000000000..080dc0a1bfc --- /dev/null +++ b/editor/src/node_graph_executor/runtime/layer_path_tests.rs @@ -0,0 +1,65 @@ +use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier; +use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier; +use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector}; +use crate::test_utils::test_prelude::*; +use graphene_std::graphic::extend; + +// A layer that ends in no Extend node has its path written onto its whole output, which gives the editor its click targets +#[tokio::test] +async fn a_node_shown_as_a_layer_is_traced_back_to() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let rectangle = DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER); + let rectangle = editor.create_node_by_name_at(rectangle, 0, 0).await; + editor + .handle_message(NodeGraphMessage::CreateWire { + output_connector: OutputConnector::node(rectangle, 0), + input_connector: InputConnector::Export(0), + }) + .await; + assert!(editor.active_document().metadata().click_targets.is_empty(), "A node not shown as a layer should have no click targets"); + + editor.handle_message(NodeGraphMessage::SetToNodeOrLayer { node_id: rectangle, is_layer: true }).await; + + let document = editor.active_document(); + let layer = LayerNodeIdentifier::new(rectangle, &document.network_interface); + let click_targets = document.metadata().click_targets(layer); + assert!( + click_targets.is_some_and(|click_targets| !click_targets.is_empty()), + "A node shown as a layer should have click targets" + ); +} + +// A layer that is itself an Extend node has its path written, from beside it, onto what it's given to add +#[tokio::test] +async fn an_extend_node_shown_as_a_layer_is_traced_back_to() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let extend = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(extend::IDENTIFIER), 0, 0).await; + let rectangle = DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER); + let (below, added) = (editor.create_node_by_name_at(rectangle.clone(), -10, 0).await, editor.create_node_by_name_at(rectangle, -10, 4).await); + for (rectangle, input) in [(below, InputConnector::node(extend, extend::BaseInput)), (added, InputConnector::node(extend, extend::NewInput))] { + editor + .handle_message(NodeGraphMessage::CreateWire { + output_connector: OutputConnector::node(rectangle, 0), + input_connector: input, + }) + .await; + } + editor + .handle_message(NodeGraphMessage::CreateWire { + output_connector: OutputConnector::node(extend, 0), + input_connector: InputConnector::Export(0), + }) + .await; + + editor.handle_message(NodeGraphMessage::SetToNodeOrLayer { node_id: extend, is_layer: true }).await; + + let document = editor.active_document(); + let layer = LayerNodeIdentifier::new(extend, &document.network_interface); + let click_targets = document.metadata().click_targets(layer); + assert!( + click_targets.is_some_and(|click_targets| !click_targets.is_empty()), + "An Extend node shown as a layer should have click targets for what it adds" + ); +} diff --git a/editor/src/node_graph_executor/runtime/thumbnails.rs b/editor/src/node_graph_executor/runtime/thumbnails.rs index 7a48079b0d9..747e3b3845c 100644 --- a/editor/src/node_graph_executor/runtime/thumbnails.rs +++ b/editor/src/node_graph_executor/runtime/thumbnails.rs @@ -1,5 +1,4 @@ use super::evaluated_output; -use super::layer_content::layer_content; use crate::messages::frontend::FrontendMessage; #[cfg(feature = "gpu")] use atlas::ThumbnailAtlasLayout; @@ -21,6 +20,7 @@ use graphene_std::transform::{Footprint, RenderQuality}; use graphene_std::vector::Vector; use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic}; use interpreted_executor::dynamic_executor::DynamicExecutor; +use interpreted_executor::layer_paths::layer_content; use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::Arc; @@ -467,11 +467,11 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] { #[cfg(test)] mod tests { use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, shipped_node_id}; - use crate::node_graph_executor::runtime::layer_content::layer_path_writer_id; use crate::test_utils::test_prelude::*; use glam::UVec2; use graph_craft::document::NodeId; use graphene_std::application_io::TimingInformation; + use interpreted_executor::layer_paths::layer_path_writer_id; async fn compile_and_run(editor: &mut EditorTestUtils) { let portfolio = editor.portfolio_message_handler_mut(); diff --git a/node-graph/graphene-cli/src/dump.rs b/node-graph/graphene-cli/src/dump.rs index d1ee3ed7421..73fd95dd9b4 100644 --- a/node-graph/graphene-cli/src/dump.rs +++ b/node-graph/graphene-cli/src/dump.rs @@ -2,6 +2,7 @@ use graph_craft::ProtoNodeIdentifier; use graph_craft::document::value::TaggedValue; use graph_craft::document::{NodeId, NodeNetwork}; use graph_craft::proto::{ConstructionArgs, ProtoNetwork, ProtoNode}; +use graphene_std::graphic::write_layer_path; use graphene_std::simplify_identifier_name; use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; use std::error::Error; @@ -57,6 +58,7 @@ enum Kind { Nullify, Expand, Scope, + LayerPath, } impl Kind { @@ -68,6 +70,7 @@ impl Kind { Kind::Nullify => "+nullify", Kind::Expand => "+expand", Kind::Scope => "+scope", + Kind::LayerPath => "+layer-path", } } } @@ -234,6 +237,7 @@ fn kind(proto: &ProtoNode, origin: &[NodeId], document: &Document) -> Kind { _ if appended && path.last() == Some(&NodeId(10)) => Kind::Nullify, _ if proto.original_location.auto_convert_index.is_some() => Kind::Convert, ConstructionArgs::Value(_) => Kind::Value, + _ if proto.identifier == write_layer_path::IDENTIFIER => Kind::LayerPath, _ if origin.is_empty() => Kind::Scope, _ if document[origin].1.as_ref() == Some(&proto.identifier) => Kind::Document, _ => Kind::Expand, diff --git a/node-graph/graphene-cli/src/lib.rs b/node-graph/graphene-cli/src/lib.rs index ec47ad1a1af..fcff551b3b1 100644 --- a/node-graph/graphene-cli/src/lib.rs +++ b/node-graph/graphene-cli/src/lib.rs @@ -5,16 +5,18 @@ pub mod dump; pub mod export; use document_format::GddV1; +use document_graph_storage::NodeMetadataEntry; use document_loader::{DocumentOrigin, LoadedDocument}; use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi}; -use graph_craft::document::{NetworkLocation, NodeId, NodeNetwork}; +use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NetworkLocation, NodeId, NodeNetwork}; use graph_craft::graphene_compiler::Compiler; use graph_craft::proto::ProtoNetwork; use graphene_std::application_io::ApplicationIo; use graphene_std::runtime::{AsyncRuntime, RuntimeHandle, Spawn, Task}; use interpreted_executor::dynamic_executor::DynamicExecutor; +use interpreted_executor::layer_paths::write_layer_paths; use interpreted_executor::util::wrap_network_in_scope; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::error::Error; use std::path::Path; use std::sync::atomic::{AtomicBool, Ordering}; @@ -24,6 +26,8 @@ use std::sync::{Arc, Mutex}; pub struct OpenedDocument { pub gdd: Option, pub network: NodeNetwork, + /// The path of every layer, which compiling writes onto what the layer renders so the artwork can be measured. + pub layers: Vec>, /// What `dump` shows for each node and network, when asked for. pub names: Option, String>>, } @@ -32,18 +36,98 @@ pub struct OpenedDocument { pub async fn open_document(path: &Path, with_names: bool) -> Result> { let LoadedDocument { network, origin } = document_loader::open_document(path).await?; - let (gdd, names) = match origin { - DocumentOrigin::Legacy(document_string) => (None, with_names.then(|| dump::legacy_names(&document_string))), + let (gdd, layers, names) = match origin { + DocumentOrigin::Legacy(document_string) => { + let layers = legacy_layer_paths(&network, &document_string); + (None, layers, with_names.then(|| dump::legacy_names(&document_string))) + } DocumentOrigin::Gdd { gdd, nodes, networks } => { + let layers = layer_paths(&network, &nodes); let names = with_names.then(|| { let references: HashMap<_, _> = networks.into_iter().filter_map(|network| Some((network.network, network.reference?))).collect(); let display_names: HashMap<_, _> = nodes.into_iter().filter_map(|node| Some(((node.network, node.local_id), node.display_name?))).collect(); instance_names(&network, &references, &display_names) }); - (Some(*gdd), names) + (Some(*gdd), layers, names) } }; - Ok(OpenedDocument { gdd, network, names }) + Ok(OpenedDocument { gdd, network, layers, names }) +} + +/// The path of every node its metadata marks as a layer, once for each instance of the networks holding it. +pub fn layer_paths(network: &NodeNetwork, node_metadata: &[NodeMetadataEntry]) -> Vec> { + let layers: HashSet<(NetworkLocation, NodeId)> = node_metadata.iter().filter(|node| node.is_layer).map(|node| (node.network, node.local_id)).collect(); + + instance_layer_paths( + network, + None, + |_, _, node| match node.implementation { + DocumentNodeImplementation::Definition(id) => Some(Some(id)), + _ => None, + }, + |location, node_id| layers.contains(&(*location, node_id)), + ) +} + +/// The path of every layer in a legacy document, read from its JSON text. +/// That describes the networks nodes hold inside their own metadata, and the ones they name in a table beside the document network's. +fn legacy_layer_paths(network: &NodeNetwork, document: &str) -> Vec> { + let Ok(document) = serde_json::from_str::(document) else { return Vec::new() }; + let document_network = &document["network_interface"]["network_metadata"]; + let definitions = &document_network["persistent_metadata"]["definitions"]; + + instance_layer_paths( + network, + legacy_node_metadata(document_network), + |node_metadata, node_id, node| match node.implementation { + DocumentNodeImplementation::Network(_) => Some(legacy_node_metadata(&node_metadata.get(&node_id).copied()?["network_metadata"])), + DocumentNodeImplementation::Definition(id) => Some(legacy_node_metadata(&definitions[id.0.to_string()])), + _ => None, + }, + |node_metadata, node_id| node_metadata.get(&node_id).is_some_and(|metadata| metadata["node_type_metadata"]["Layer"].is_object()), + ) +} + +/// The metadata of each node in a legacy document's network, by ID. +fn legacy_node_metadata(network_metadata: &serde_json::Value) -> HashMap { + let entries = network_metadata["persistent_metadata"]["node_metadata"].as_array().into_iter().flatten(); + entries.filter_map(|entry| Some((NodeId(entry[0].as_u64()?), &entry[1]["persistent_metadata"]))).collect() +} + +/// The path of every layer, once for each instance of the networks holding it, with a network's layers before those of the networks inside it as the editor orders them. +/// The walk carries the metadata of each network it enters, which `nested` finds for the network a node holds or names. +fn instance_layer_paths( + network: &NodeNetwork, + document_network_metadata: Metadata, + nested: impl Fn(&Metadata, NodeId, &DocumentNode) -> Option, + is_layer: impl Fn(&Metadata, NodeId) -> bool, +) -> Vec> { + let mut layer_paths = Vec::new(); + + // Each network is walked with the definitions enclosing it, so one that holds itself isn't entered again + let mut stack = vec![(Vec::new(), document_network_metadata, Vec::new())]; + while let Some((network_path, metadata, enclosing_definitions)) = stack.pop() { + let Some(walked) = network.nested_network(&network_path) else { continue }; + + for (node_id, node) in &walked.nodes { + let node_path = [network_path.as_slice(), &[*node_id]].concat(); + if is_layer(&metadata, *node_id) { + layer_paths.push(node_path.clone()); + } + + let definition = match node.implementation { + DocumentNodeImplementation::Definition(id) if enclosing_definitions.contains(&id) => continue, + DocumentNodeImplementation::Definition(id) => Some(id), + _ => None, + }; + if let Some(nested_metadata) = nested(&metadata, *node_id, node) { + let enclosing_definitions = enclosing_definitions.iter().copied().chain(definition).collect(); + stack.push((node_path, nested_metadata, enclosing_definitions)); + } + } + } + + layer_paths } /// The name of each node, keyed by the path the dump visits it at. @@ -89,7 +173,9 @@ pub async fn editor_api(gdd: Option<&GddV1>) -> (Arc, Arc (application_io, editor_api) } -pub fn compile_graph(network: NodeNetwork, editor_api: Arc, gdd: Option<&GddV1>, runtime: RuntimeHandle) -> Result> { +/// Compile `network`, writing the path of each of its `layers` onto what that layer renders. +pub fn compile_graph(mut network: NodeNetwork, layers: &[Vec], editor_api: Arc, gdd: Option<&GddV1>, runtime: RuntimeHandle) -> Result> { + write_layer_paths(&mut network, layers); let mut network = wrap_network_in_scope(network, editor_api, runtime); let preprocessor = preprocessor::Preprocessor::new(); @@ -117,7 +203,7 @@ pub async fn compile_document(document: OpenedDocument) -> Result DocumentNode { + DocumentNode { implementation, ..Default::default() } + } + + /// A network holding the nodes 3 and 4. + fn inner_network() -> NodeNetwork { + let nodes = [3, 4].map(|id| (NodeId(id), DocumentNode::default())); + NodeNetwork { + nodes: nodes.into_iter().collect(), + ..Default::default() + } + } + + fn node_metadata(network: NetworkLocation, local_id: u64, is_layer: bool) -> NodeMetadataEntry { + NodeMetadataEntry { + network, + local_id: NodeId(local_id), + position: None, + is_layer, + display_name: None, + locked: false, + pinned: false, + input_metadata: Vec::new(), + output_names: Vec::new(), + output_descriptions: Vec::new(), + } + } + + /// The paths found, checking each layer comes after the one holding it. + fn checked_and_sorted(mut layer_paths: Vec>) -> Vec> { + for (index, layer_path) in layer_paths.iter().enumerate() { + let holder = &layer_path[..layer_path.len() - 1]; + let holder_index = layer_paths.iter().position(|other| other == holder); + assert!( + holder_index.is_none_or(|holder_index| holder_index < index), + "Layer {layer_path:?} should come after the layer holding it" + ); + } + + layer_paths.sort(); + layer_paths + } + + /// The nodes 1 and 2, which both name the definition holding the nodes 3 and 4. + fn two_instances_of_a_definition() -> NodeNetwork { + NodeNetwork { + nodes: [1, 2].map(|id| (NodeId(id), node(DocumentNodeImplementation::Definition(DEFINITION)))).into_iter().collect(), + definitions: [(DEFINITION, inner_network())].into_iter().collect(), + ..Default::default() + } + } + + /// The layer paths when 1 and 3 are layers. + fn expected_instance_paths() -> Vec> { + vec![vec![NodeId(1)], vec![NodeId(1), NodeId(3)], vec![NodeId(2), NodeId(3)]] + } + + #[test] + fn a_layer_inside_a_definition_is_found_through_each_instance() { + let network = two_instances_of_a_definition(); + let metadata = [(None, 1, true), (None, 2, false), (Some(DEFINITION), 3, true), (Some(DEFINITION), 4, false)]; + let metadata: Vec<_> = metadata.into_iter().map(|(location, local_id, is_layer)| node_metadata(location, local_id, is_layer)).collect(); + + assert_eq!(checked_and_sorted(layer_paths(&network, &metadata)), expected_instance_paths()); + } + + // Current legacy JSON describes a definition's nodes in a table beside the document network's + #[test] + fn a_legacy_layer_inside_a_definition_is_found_through_each_instance() { + let network = two_instances_of_a_definition(); + let document = r#"{ "network_interface": { "network_metadata": { "persistent_metadata": { + "node_metadata": [[1, { "persistent_metadata": { "node_type_metadata": { "Layer": {} } } }], [2, { "persistent_metadata": { "node_type_metadata": { "Node": {} } } }]], + "definitions": { "9": { "persistent_metadata": { + "node_metadata": [[3, { "persistent_metadata": { "node_type_metadata": { "Layer": {} } } }], [4, { "persistent_metadata": { "node_type_metadata": { "Node": {} } } }]] + } } } + } } } }"#; + + assert_eq!(checked_and_sorted(legacy_layer_paths(&network, document)), expected_instance_paths()); + } + + // Older legacy JSON describes a network a node holds inside that node's own metadata + #[test] + fn a_legacy_layer_inside_a_held_network_is_found() { + let network = NodeNetwork { + nodes: [(NodeId(1), node(DocumentNodeImplementation::Network(inner_network())))].into_iter().collect(), + ..Default::default() + }; + let document = r#"{ "network_interface": { "network_metadata": { "persistent_metadata": { + "node_metadata": [[1, { "persistent_metadata": { + "node_type_metadata": { "Layer": {} }, + "network_metadata": { "persistent_metadata": { + "node_metadata": [[3, { "persistent_metadata": { "node_type_metadata": { "Layer": {} } } }], [4, { "persistent_metadata": { "node_type_metadata": { "Node": {} } } }]] + } } + } }]] + } } } }"#; + + assert_eq!(checked_and_sorted(legacy_layer_paths(&network, document)), vec![vec![NodeId(1)], vec![NodeId(1), NodeId(3)]]); + } +} diff --git a/node-graph/graphene-cli/src/watch.rs b/node-graph/graphene-cli/src/watch.rs index 0e447a27a0c..aa3eb80b391 100644 --- a/node-graph/graphene-cli/src/watch.rs +++ b/node-graph/graphene-cli/src/watch.rs @@ -2,7 +2,7 @@ use document_live::{Event, LiveDocument}; use graph_craft::application_io::resource::ResourceHash; use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi}; use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue, UVec2}; -use graphene_cli::{TokioSpawner, compile_graph, create_executor, editor_api, export}; +use graphene_cli::{TokioSpawner, compile_graph, create_executor, editor_api, export, layer_paths}; use graphene_std::application_io::{ApplicationIo, ExportFormat, RenderConfig}; use graphene_std::runtime::AsyncRuntime; use interpreted_executor::dynamic_executor::DynamicExecutor; @@ -124,11 +124,12 @@ impl Viewer { } fn recompile(&mut self) { - let network = match self.runtime.block_on(self.live.network()) { - Ok(network) => network, + let (network, nodes) = match self.runtime.block_on(self.live.network_with_metadata()) { + Ok(network_with_metadata) => network_with_metadata, Err(error) => return log::error!("Failed to build the runtime network: {error}"), }; - let proto = match compile_graph(network, self.editor_api.clone(), Some(self.live.document()), self.graph_runtime.handle()) { + let layers = layer_paths(&network, &nodes); + let proto = match compile_graph(network, &layers, self.editor_api.clone(), Some(self.live.document()), self.graph_runtime.handle()) { Ok(proto) => proto, Err(error) => return log::error!("Compile failed: {error}"), }; diff --git a/editor/src/node_graph_executor/runtime/layer_content.rs b/node-graph/interpreted-executor/src/layer_paths.rs similarity index 67% rename from editor/src/node_graph_executor/runtime/layer_content.rs rename to node-graph/interpreted-executor/src/layer_paths.rs index e33078d12a5..cc35ed17ab1 100644 --- a/editor/src/node_graph_executor/runtime/layer_content.rs +++ b/node-graph/interpreted-executor/src/layer_paths.rs @@ -1,10 +1,12 @@ +//! Writes each layer's path onto what it renders, so what's rendered can be traced back to its layer. + +use crate::node_registry::NODE_REGISTRY; use graph_craft::ProtoNodeIdentifier; use graph_craft::document::value::TaggedValue; use graph_craft::document::{DocumentNode, DocumentNodeImplementation, DocumentNodeMetadata, NodeId, NodeInput, NodeNetwork}; use graphene_std::NodeParameter; use graphene_std::graphic::{extend, write_layer_path}; use graphene_std::list::NodeIdPath; -use interpreted_executor::node_registry::NODE_REGISTRY; use std::collections::HashMap; use std::hash::{DefaultHasher, Hash, Hasher}; @@ -48,7 +50,7 @@ impl LayerContent { } } -/// Puts a node after each layer's content that writes the layer's path onto it, which is how the editor traces what's rendered back to its layer. +/// Puts a node after each layer's content that writes the layer's path onto it. /// A layer has none if its content may be of a type that can't carry the path. pub fn write_layer_paths(network: &mut NodeNetwork, layer_paths: &[Vec]) { let mut carries_layer_path = HashMap::new(); @@ -57,6 +59,13 @@ pub fn write_layer_paths(network: &mut NodeNetwork, layer_paths: &[Vec]) for layer_path in layer_paths { let Some((layer, parent_path)) = layer_path.split_last() else { continue }; let Some(content) = layer_content(layer_path, network) else { continue }; + + // An Extend node deeper inside the layer may be in a network other layers share, so the writer goes on the layer's whole output instead + let content = match content { + LayerContent::Added { network_path, extend } if network_path.len() > layer_path.len() => LayerContent::Output([network_path.as_slice(), &[extend]].concat()), + content => content, + }; + let Some(source) = content.source(network) else { continue }; if !source_can_carry_layer_path(source, network, &mut carries_layer_path) { continue; @@ -66,10 +75,7 @@ pub fn write_layer_paths(network: &mut NodeNetwork, layer_paths: &[Vec]) // The writer goes between the Extend node and what it's given to add, inside the layer or beside it if the layer is that node LayerContent::Added { network_path, extend } => { let writer = layer_path_writer_id(extend); - let (levels_up, layer_beside) = match network_path.len().checked_sub(layer_path.len()) { - Some(depth_inside_layer) => (depth_inside_layer + 1, Vec::new()), - None => (1, vec![*layer]), - }; + let layer_beside = if network_path.len() == layer_path.len() { Vec::new() } else { vec![*layer] }; let Some(holder) = network_mut(network, &network_path) else { continue }; let Some(added) = holder.nodes.get_mut(&extend).and_then(|node| node.inputs.get_mut(extend::NewInput::INDEX)) else { continue; @@ -81,7 +87,7 @@ pub fn write_layer_paths(network: &mut NodeNetwork, layer_paths: &[Vec]) } let content = std::mem::replace(added, NodeInput::node(writer, 0)); - holder.nodes.insert(writer, layer_path_writer(content, levels_up, layer_beside)); + holder.nodes.insert(writer, layer_path_writer(content, layer_beside)); } // The writer goes beside the layer, taking over everything its output feeds LayerContent::Output(_) => { @@ -95,7 +101,7 @@ pub fn write_layer_paths(network: &mut NodeNetwork, layer_paths: &[Vec]) let inputs = holder.nodes.values_mut().flat_map(|node| &mut node.inputs).chain(&mut holder.exports); inputs.filter(|input| **input == output).for_each(|input| *input = written.clone()); - holder.nodes.insert(writer, layer_path_writer(output, 1, vec![*layer])); + holder.nodes.insert(writer, layer_path_writer(output, vec![*layer])); } } } @@ -191,11 +197,10 @@ pub fn layer_path_writer_id(node_id: NodeId) -> NodeId { NodeId(hasher.finish()) } -fn layer_path_writer(content: NodeInput, levels_up: usize, layer_beside: Vec) -> DocumentNode { +fn layer_path_writer(content: NodeInput, layer_beside: Vec) -> DocumentNode { DocumentNode { inputs: vec![ content, - NodeInput::value(TaggedValue::Integer(levels_up as i64), false), NodeInput::value(TaggedValue::NodeIdPath(NodeIdPath::from(layer_beside)), false), NodeInput::Reflection(DocumentNodeMetadata::DocumentNodePath), ], @@ -207,70 +212,7 @@ fn layer_path_writer(content: NodeInput, levels_up: usize, layer_beside: Vec) -> DocumentNode { + DocumentNode { + inputs, + implementation: DocumentNodeImplementation::ProtoNode(identifier), + ..Default::default() + } + } + + fn definition_node(id: NetworkId) -> DocumentNode { + DocumentNode { + implementation: DocumentNodeImplementation::Definition(id), + ..Default::default() + } + } + + /// A network shaped like 'Merge', where an Extend node adds what the node beside it gives. + fn merge_like(added: DocumentNode) -> NodeNetwork { + let extend = proto_node(extend::IDENTIFIER, vec![NodeInput::value(TaggedValue::None, false), NodeInput::node(NodeId(2), 0)]); + NodeNetwork { + exports: vec![NodeInput::node(NodeId(1), 0)], + nodes: [(NodeId(1), extend), (NodeId(2), added)].into_iter().collect(), + ..Default::default() + } + } + + // One network is shared by a layer at the root and by a layer inside another layer, so the one writer inside it has to suit both + #[test] + fn a_network_shared_by_layers_at_different_depths_writes_each_layer_path() { + let (merge, group) = (NetworkId(1), NetworkId(2)); + let rectangle = proto_node(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER, Vec::new()); + let group_network = NodeNetwork { + exports: vec![NodeInput::node(NodeId(30), 0)], + nodes: [(NodeId(30), definition_node(merge))].into_iter().collect(), + ..Default::default() + }; + let network = NodeNetwork { + exports: vec![NodeInput::node(NodeId(10), 0)], + nodes: [(NodeId(10), definition_node(merge)), (NodeId(20), definition_node(group))].into_iter().collect(), + definitions: [(merge, merge_like(rectangle)), (group, group_network)].into_iter().collect(), + ..Default::default() + }; + + // The outer layer comes first in one order and last in the other + let orders = [ + [vec![NodeId(20)], vec![NodeId(10)], vec![NodeId(20), NodeId(30)]], + [vec![NodeId(10)], vec![NodeId(20), NodeId(30)], vec![NodeId(20)]], + ]; + let written = orders.map(|layer_paths| { + let mut network = network.clone(); + write_layer_paths(&mut network, &layer_paths); + network + }); + assert_eq!(written[0], written[1], "The order the layers are given in should not change what's written"); + + // The writer writes the path of the layer holding its network, whichever layer that is + let writer = &written[0].definitions[&merge].nodes[&layer_path_writer_id(NodeId(1))]; + assert_eq!(writer.inputs[1], NodeInput::value(TaggedValue::NodeIdPath(NodeIdPath::from(Vec::new())), false)); + } + + // Content that already writes its own layer path, like the 'Merge' networks of older documents, gets no second writer + #[test] + fn a_network_writing_its_own_layer_path_is_left_alone() { + let write_attribute = proto_node(graphene_std::graphic::write_attribute::IDENTIFIER, Vec::new()); + let mut network = NodeNetwork { + exports: vec![NodeInput::node(NodeId(10), 0)], + nodes: [(NodeId(10), definition_node(NetworkId(1)))].into_iter().collect(), + definitions: [(NetworkId(1), merge_like(write_attribute))].into_iter().collect(), + ..Default::default() + }; + let unchanged = network.clone(); + + write_layer_paths(&mut network, &[vec![NodeId(10)]]); + + assert_eq!(network, unchanged); + } } diff --git a/node-graph/interpreted-executor/src/lib.rs b/node-graph/interpreted-executor/src/lib.rs index 6b59d5ad987..050d8d3a55c 100644 --- a/node-graph/interpreted-executor/src/lib.rs +++ b/node-graph/interpreted-executor/src/lib.rs @@ -2,6 +2,7 @@ #![recursion_limit = "256"] pub mod dynamic_executor; +pub mod layer_paths; pub mod node_registry; pub mod util; diff --git a/node-graph/nodes/graphic/src/graphic.rs b/node-graph/nodes/graphic/src/graphic.rs index 57b0b879456..85aefbf08ce 100644 --- a/node-graph/nodes/graphic/src/graphic.rs +++ b/node-graph/nodes/graphic/src/graphic.rs @@ -595,15 +595,14 @@ fn path_of_subgraph(_: impl Ctx, node_path: Item) -> Item( _: impl Ctx, #[implementations(String, bool, f64, i64, DVec2, DAffine2, Vector, Graphic, Raster, Raster, Color, Gradient, Artboard, Stroke)] content: Item, - /// How many entries to drop from the end of this node's path, itself included, to reach the layer or else the network holding it. - levels_up: Item, - /// The layer's ID if the network holding it was reached, which is empty if the layer itself was. + /// The layer's ID if this node is beside the layer rather than inside it. layer_beside: Item, #[node_path] node_path: Item, ) -> Item { + // This node's path without its own ID is the path of the network holding it let node_path = node_path.into_element().0; - let kept = node_path.len().saturating_sub(levels_up.into_element().max(0) as usize); - let layer_path = node_path.into_iter().take(kept).chain(layer_beside.into_element().0).collect(); + let holder_path_length = node_path.len().saturating_sub(1); + let layer_path = node_path.into_iter().take(holder_path_length).chain(layer_beside.into_element().0).collect(); let mut content = content; content.set_attribute(ATTR_EDITOR_LAYER_PATH, NodeIdPath(layer_path)); From 1d7869263a72d4f78c952d667868de0443e70bfc Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Tue, 17 Nov 2026 04:12:31 -0800 Subject: [PATCH 2/2] Keep the 'Write Layer Path' node's inputs unchanged --- node-graph/interpreted-executor/src/layer_paths.rs | 6 +++++- node-graph/nodes/graphic/src/graphic.rs | 9 +++++---- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/node-graph/interpreted-executor/src/layer_paths.rs b/node-graph/interpreted-executor/src/layer_paths.rs index cc35ed17ab1..4eaefd7dc13 100644 --- a/node-graph/interpreted-executor/src/layer_paths.rs +++ b/node-graph/interpreted-executor/src/layer_paths.rs @@ -201,6 +201,8 @@ fn layer_path_writer(content: NodeInput, layer_beside: Vec) -> DocumentN DocumentNode { inputs: vec![ content, + // The writer is in the layer's own network or beside the layer, so dropping just its own ID reaches it + NodeInput::value(TaggedValue::Integer(1), false), NodeInput::value(TaggedValue::NodeIdPath(NodeIdPath::from(layer_beside)), false), NodeInput::Reflection(DocumentNodeMetadata::DocumentNodePath), ], @@ -289,7 +291,9 @@ mod tests { // The writer writes the path of the layer holding its network, whichever layer that is let writer = &written[0].definitions[&merge].nodes[&layer_path_writer_id(NodeId(1))]; - assert_eq!(writer.inputs[1], NodeInput::value(TaggedValue::NodeIdPath(NodeIdPath::from(Vec::new())), false)); + let (levels_up, layer_beside) = (&writer.inputs[1], &writer.inputs[2]); + assert_eq!(*levels_up, NodeInput::value(TaggedValue::Integer(1), false)); + assert_eq!(*layer_beside, NodeInput::value(TaggedValue::NodeIdPath(NodeIdPath::from(Vec::new())), false)); } // Content that already writes its own layer path, like the 'Merge' networks of older documents, gets no second writer diff --git a/node-graph/nodes/graphic/src/graphic.rs b/node-graph/nodes/graphic/src/graphic.rs index 85aefbf08ce..57b0b879456 100644 --- a/node-graph/nodes/graphic/src/graphic.rs +++ b/node-graph/nodes/graphic/src/graphic.rs @@ -595,14 +595,15 @@ fn path_of_subgraph(_: impl Ctx, node_path: Item) -> Item( _: impl Ctx, #[implementations(String, bool, f64, i64, DVec2, DAffine2, Vector, Graphic, Raster, Raster, Color, Gradient, Artboard, Stroke)] content: Item, - /// The layer's ID if this node is beside the layer rather than inside it. + /// How many entries to drop from the end of this node's path, itself included, to reach the layer or else the network holding it. + levels_up: Item, + /// The layer's ID if the network holding it was reached, which is empty if the layer itself was. layer_beside: Item, #[node_path] node_path: Item, ) -> Item { - // This node's path without its own ID is the path of the network holding it let node_path = node_path.into_element().0; - let holder_path_length = node_path.len().saturating_sub(1); - let layer_path = node_path.into_iter().take(holder_path_length).chain(layer_beside.into_element().0).collect(); + let kept = node_path.len().saturating_sub(levels_up.into_element().max(0) as usize); + let layer_path = node_path.into_iter().take(kept).chain(layer_beside.into_element().0).collect(); let mut content = content; content.set_attribute(ATTR_EDITOR_LAYER_PATH, NodeIdPath(layer_path));