Compare commits

...
Author SHA1 Message Date
Timon 13bb1687b9 Add the graph-ui crate, which draws the node graph with Graphene 2026-12-06 17:57:47 +00:00
Timon 674221fbc3 Add transient nodes that are exempt from versions and migration checks (#5098)
* Add the transient node attribute for nodes that are never saved

* Refuse to save transient nodes

* Leave transient nodes out of the migration checks and the corpus coverage

* Mark the render chain, scope and resource nodes as transient

* Document the transient attribute
2026-12-06 17:23:44 +00:00
Dennis Kobert 1300b4f92a Identify conversion nodes via node macro annotations (#5083)
Flag adapter nodes and register them by identifier
2026-12-06 13:57:52 +00:00
Timon c0778752ab Fix running out of GPU memory from textures allocated outside the shared texture cache (#5070)
* Give the Vello renderer the executor and pool textures with mip levels

* Take split and grown render targets from the texture pool (fixup #4821, #5063)

* Take the premultiplied render target from the texture pool (fixup #4807)

* Premultiply textures drawn as images into texture pool copies (fixup #4807)

* Take effect textures from the texture pool (fixup #4976, #5023)

* Park generator tiles in the texture pool (fixup #5008, #5009, #5010)

* Park image uploads and adjusted copies in the texture pool (fixup #4807, #4855, #4908, #4997, #5037)

* Park adjustment uploads in the texture pool (fixup #4997)

* Take effect row textures and Mandelbrot reference orbits from the texture pool (fixup #5010)

* Review
2026-12-06 13:49:37 +00:00
Timon 27cded81af Utilize executor multi-output capabilities in runtime (#5084)
* Free executor nodes once no output reaches them, and let an export keep its output instead of blocking the runtime

* Answer an export on a channel of its own, so the viewport's answers stay in order

* Render a copy's SVG as an export of the copied layers' own network

* Record in the executor which paths' types changed, to be taken with take_type_changes

* Prepare every network in the node graph executor, and send the runtime the thumbnail sources instead of the previews and layers
2026-12-06 13:48:46 +00:00
d5fdb12320 Desktop: Fix rendering getting stuck on stale WGPU surfaces (#4966)
Reconfigure WGPU surface and request redraw on Outdated

Co-authored-by: Carlos Ferrabone <[email protected]>
Co-authored-by: Timon <[email protected]>
2026-12-06 13:42:47 +00:00
79 changed files with 5194 additions and 1019 deletions

No files matched your search

Generated
+39
View File
@@ -2498,6 +2498,7 @@ dependencies = [
"futures", "futures",
"glam", "glam",
"graph-craft", "graph-craft",
"graph-ui-types",
"graphene-animation", "graphene-animation",
"graphene-application-io", "graphene-application-io",
"graphene-canvas-utils", "graphene-canvas-utils",
@@ -2535,6 +2536,44 @@ dependencies = [
"smallvec", "smallvec",
] ]
[[package]]
name = "graph-ui"
version = "0.0.0"
dependencies = [
"core-types",
"glam",
"graph-craft",
"graph-ui-icons",
"graph-ui-types",
"graphene-std",
"graphic-types",
"node-macro",
"rendering",
"svg-convert",
"text-nodes",
"vector-types",
"vello_gpu",
]
[[package]]
name = "graph-ui-icons"
version = "0.0.0"
[[package]]
name = "graph-ui-types"
version = "0.0.0"
dependencies = [
"core-types",
"dyn-any",
"glam",
"graph-layout",
"graphene-hash",
"graphic-types",
"serde",
"tsify",
"wasm-bindgen",
]
[[package]] [[package]]
name = "graphene-animation" name = "graphene-animation"
version = "0.0.0" version = "0.0.0"
+6
View File
@@ -34,6 +34,9 @@ members = [
"node-graph/libraries/*", "node-graph/libraries/*",
"node-graph/nodes/*", "node-graph/nodes/*",
"node-graph/graph-craft", "node-graph/graph-craft",
"node-graph/graph-ui",
"node-graph/graph-ui/icons",
"node-graph/graph-ui/types",
"node-graph/graphene-cli", "node-graph/graphene-cli",
"node-graph/nodes/gstd", "node-graph/nodes/gstd",
"node-graph/interpreted-executor", "node-graph/interpreted-executor",
@@ -112,6 +115,9 @@ vectorize-nodes = { path = "node-graph/nodes/vectorize" }
math-nodes = { path = "node-graph/nodes/math" } math-nodes = { path = "node-graph/nodes/math" }
path-bool-nodes = { path = "node-graph/nodes/path-bool" } path-bool-nodes = { path = "node-graph/nodes/path-bool" }
graph-craft = { path = "node-graph/graph-craft" } graph-craft = { path = "node-graph/graph-craft" }
graph-ui = { path = "node-graph/graph-ui" }
graph-ui-icons = { path = "node-graph/graph-ui/icons" }
graph-ui-types = { path = "node-graph/graph-ui/types" }
document-format = { path = "document/format" } document-format = { path = "document/format" }
document-graph-storage = { path = "document/graph-storage", default-features = false } document-graph-storage = { path = "document/graph-storage", default-features = false }
document-container = { path = "document/container" } document-container = { path = "document/container" }
+5 -2
View File
@@ -234,7 +234,11 @@ impl RenderState {
WgpuCurrentSurfaceTexture::Suboptimal(t) => (t, true), WgpuCurrentSurfaceTexture::Suboptimal(t) => (t, true),
WgpuCurrentSurfaceTexture::Occluded => return Ok(()), WgpuCurrentSurfaceTexture::Occluded => return Ok(()),
WgpuCurrentSurfaceTexture::Lost => return Err(RenderError::SurfaceLost), WgpuCurrentSurfaceTexture::Lost => return Err(RenderError::SurfaceLost),
WgpuCurrentSurfaceTexture::Outdated => return Err(RenderError::SurfaceOutdated), WgpuCurrentSurfaceTexture::Outdated => {
self.surface.configure(&self.executor.context().device, &self.config);
window.request_redraw();
return Ok(());
}
WgpuCurrentSurfaceTexture::Timeout => return Err(RenderError::SurfaceTimeout), WgpuCurrentSurfaceTexture::Timeout => return Err(RenderError::SurfaceTimeout),
WgpuCurrentSurfaceTexture::Validation => return Err(RenderError::SurfaceValidation), WgpuCurrentSurfaceTexture::Validation => return Err(RenderError::SurfaceValidation),
}; };
@@ -327,7 +331,6 @@ impl RenderState {
pub(crate) enum RenderError { pub(crate) enum RenderError {
OutdatedUITextureError, OutdatedUITextureError,
SurfaceLost, SurfaceLost,
SurfaceOutdated,
SurfaceTimeout, SurfaceTimeout,
SurfaceValidation, SurfaceValidation,
} }
+7 -1
View File
@@ -44,6 +44,8 @@ pub enum ConversionError {
IndexOverflow(usize), IndexOverflow(usize),
#[error("Node ID {0} is used by more than one node in the document")] #[error("Node ID {0} is used by more than one node in the document")]
DuplicateNodeId(u64), DuplicateNodeId(u64),
#[error("The transient node {0} cannot be saved")]
TransientNode(String),
} }
/// Graph-only conversion (no editor metadata). Use [`Registry::from_runtime_with_metadata`] for /// Graph-only conversion (no editor metadata). Use [`Registry::from_runtime_with_metadata`] for
@@ -559,7 +561,11 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
} }
// Nodes the binary doesn't register, such as in tests, are at their first version // Nodes the binary doesn't register, such as in tests, are at their first version
let version = NODE_METADATA.lock().ok().and_then(|metadata| metadata.get(identifier).map(|metadata| metadata.version)).unwrap_or(1); let registered = NODE_METADATA.lock().ok().and_then(|metadata| metadata.get(identifier).map(|node| (node.version, node.flags)));
let (version, flags) = registered.unwrap_or((1, Default::default()));
if flags.transient {
return Err(ConversionError::TransientNode(identifier_str));
}
let EncodedDeclaration { id, hash, bytes, proto } = let EncodedDeclaration { id, hash, bytes, proto } =
EncodedDeclaration::new(identifier_str.clone(), version).map_err(|error| ConversionError::SerializationError(format!("proto-node {identifier_str}: {error}")))?; EncodedDeclaration::new(identifier_str.clone(), version).map_err(|error| ConversionError::SerializationError(format!("proto-node {identifier_str}: {error}")))?;
@@ -657,6 +657,41 @@ fn a_node_id_used_in_two_networks_is_rejected() {
assert!(matches!(result, Err(crate::from_runtime::ConversionError::DuplicateNodeId(_))), "a reused node ID must not be stored"); assert!(matches!(result, Err(crate::from_runtime::ConversionError::DuplicateNodeId(_))), "a reused node ID must not be stored");
} }
#[test]
fn a_transient_node_is_rejected() {
use core_types::registry::{NODE_METADATA, NodeFlags, NodeMetadata};
let identifier = ProtoNodeIdentifier::new("test::TransientNode");
let metadata = NodeMetadata {
display_name: "Transient",
category: "",
icon: None,
fields: Vec::new(),
description: "",
inspector: None,
context_features: Vec::new(),
flags: NodeFlags {
transient: true,
..Default::default()
},
version: 1,
output_fields: None,
};
NODE_METADATA.lock().unwrap().insert(identifier.clone(), metadata);
let mut network = create_simple_network();
network.nodes.insert(
NodeId(100),
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(identifier),
..Default::default()
},
);
let result = Registry::convert_from_runtime(&network, &crate::NoMetadata, &Default::default(), PeerId(0));
assert!(matches!(result, Err(crate::from_runtime::ConversionError::TransientNode(_))));
}
/// A node input referencing a node in a different network can't be remapped to a valid local runtime /// A node input referencing a node in a different network can't be remapped to a valid local runtime
/// ID, so conversion must reject it rather than emit a dangling reference. /// ID, so conversion must reject it rather than emit a dangling reference.
#[test] #[test]
@@ -1,3 +1 @@
//! Migrations of the nodes in `graphene_std`. //! Migrations of the nodes in `graphene_std`.
mod renames;
@@ -1,13 +0,0 @@
//! Nodes that only moved to a new identifier, or changed version with stored nodes staying as they are.
use migration_core::rename;
// Version 2 moves these nodes' parameters ahead of their scope inputs, and only the compiler inserts them, so no stored node has version 1's order
rename!("graphene_std::platform_application_io::ResourceNode"@1 => @2);
rename!("graphene_std::render_background::RenderBackgroundNode"@1 => @2);
rename!("graphene_std::render_cache::RenderOutputCacheNode"@1 => @2);
rename!("graphene_std::render_node::RenderNode"@1 => @2);
rename!("graphene_std::render_pixel_preview::RenderPixelPreviewNode"@1 => @2);
// Version 3 adds the scope and source ID inputs the render node spawns its readbacks with, which the compiler inserts along with the node
rename!("graphene_std::render_node::RenderNode"@2 => @3);
+15 -2
View File
@@ -16,7 +16,7 @@ pub(crate) fn check_against(workspace: &Path, baseline: &str) -> Result<(), Stri
let baseline_nodes = extract_baseline(workspace, baseline, &directory).and_then(|()| find_nodes(&directory.join(NODE_CRATES))); let baseline_nodes = extract_baseline(workspace, baseline, &directory).and_then(|()| find_nodes(&directory.join(NODE_CRATES)));
// Removal failing only leaves a temporary directory behind // Removal failing only leaves a temporary directory behind
let _ = std::fs::remove_dir_all(&directory); let _ = std::fs::remove_dir_all(&directory);
let baseline_nodes = baseline_nodes?; let baseline_nodes: Vec<NodeSource> = baseline_nodes?.into_iter().filter(|node| !node.transient).collect();
let problems = api_problems(&baseline_nodes, &current, &migrations); let problems = api_problems(&baseline_nodes, &current, &migrations);
if !problems.is_empty() { if !problems.is_empty() {
@@ -71,7 +71,7 @@ fn api_problems(baseline: &[NodeSource], current: &[NodeSource], migrations: &[M
// Moving a module keeps the function and its API, which is what a rename looks like // Moving a module keeps the function and its API, which is what a rename looks like
let moved = current let moved = current
.iter() .iter()
.find(|new| !baseline_identifiers.contains(&new.identifier.as_str()) && new.function == old.function && new.signature == old.signature); .find(|new| !new.transient && !baseline_identifiers.contains(&new.identifier.as_str()) && new.function == old.function && new.signature == old.signature);
problems.push(match moved { problems.push(match moved {
Some(new) => format!( Some(new) => format!(
"`{identifier}`@{version} disappeared and looks moved to `{}`. Set `version({})` on it and run `cargo run migration rename {identifier}@{version} {}`", "`{identifier}`@{version} disappeared and looks moved to `{}`. Set `version({})` on it and run `cargo run migration rename {identifier}@{version} {}`",
@@ -83,6 +83,9 @@ fn api_problems(baseline: &[NodeSource], current: &[NodeSource], migrations: &[M
}); });
continue; continue;
}; };
if new.transient {
continue;
}
if new.version < version { if new.version < version {
problems.push(format!("`{identifier}` went back from version {version} to {}", new.version)); problems.push(format!("`{identifier}` went back from version {version} to {}", new.version));
@@ -123,6 +126,7 @@ mod tests {
NodeSource { NodeSource {
identifier: identifier.to_string(), identifier: identifier.to_string(),
version, version,
transient: false,
function: identifier.rsplit("::").next().unwrap_or(identifier).to_string(), function: identifier.rsplit("::").next().unwrap_or(identifier).to_string(),
file: PathBuf::from("lib.rs"), file: PathBuf::from("lib.rs"),
signature: signature.to_string(), signature: signature.to_string(),
@@ -168,6 +172,15 @@ mod tests {
assert!(problems[0].contains("disappeared without a migration"), "{}", problems[0]); assert!(problems[0].contains("disappeared without a migration"), "{}", problems[0]);
} }
#[test]
fn a_node_turned_transient_needs_no_migration() {
let transient = NodeSource {
transient: true,
..node("a::b", 1, "(x: f64, y: f64)")
};
assert!(api_problems(&[node("a::b", 2, "(x: f64)")], &[transient], &[]).is_empty());
}
#[test] #[test]
fn a_bump_needs_a_migration_from_the_baseline_version() { fn a_bump_needs_a_migration_from_the_baseline_version() {
let bumped = [node("a::b", 3, "(x: f64)")]; let bumped = [node("a::b", 3, "(x: f64)")];
+1
View File
@@ -117,6 +117,7 @@ fn check(workspace: &Path) -> Result<(), String> {
let nodes: Vec<lineage::Declaration> = nodes::find_nodes(&workspace.join(scaffold::NODE_CRATES))? let nodes: Vec<lineage::Declaration> = nodes::find_nodes(&workspace.join(scaffold::NODE_CRATES))?
.into_iter() .into_iter()
.filter(|node| !node.transient)
.map(|node| (node.identifier, node.version)) .map(|node| (node.identifier, node.version))
.collect(); .collect();
let migrations = lineage::find_all_migrations(workspace, &scaffold::MIGRATION_CRATES)?; let migrations = lineage::find_all_migrations(workspace, &scaffold::MIGRATION_CRATES)?;
+24
View File
@@ -10,6 +10,7 @@ pub(crate) struct NodeSource {
/// function name with a `Node` suffix. /// function name with a `Node` suffix.
pub identifier: String, pub identifier: String,
pub version: u32, pub version: u32,
pub transient: bool,
pub function: String, pub function: String,
pub file: PathBuf, pub file: PathBuf,
/// The parameters and output as written, without their attributes or `#[data]` fields. Comparing it tells whether stored inputs still fit. /// The parameters and output as written, without their attributes or `#[data]` fields. Comparing it tells whether stored inputs still fit.
@@ -119,7 +120,9 @@ fn node_source(function: &syn::ItemFn, file: &Path, module_path: &[String]) -> O
let mut path = module_path.join("::"); let mut path = module_path.join("::");
let mut version = 1; let mut version = 1;
let mut transient = false;
for argument in arguments { for argument in arguments {
transient |= argument.path().is_ident("transient");
let syn::Meta::List(list) = argument else { continue }; let syn::Meta::List(list) = argument else { continue };
if list.path.is_ident("path") { if list.path.is_ident("path") {
path = list.tokens.to_string().replace(' ', ""); path = list.tokens.to_string().replace(' ', "");
@@ -147,6 +150,7 @@ fn node_source(function: &syn::ItemFn, file: &Path, module_path: &[String]) -> O
Some(NodeSource { Some(NodeSource {
identifier: format!("{path}::{}Node", function_name.to_case(Case::Pascal)), identifier: format!("{path}::{}Node", function_name.to_case(Case::Pascal)),
version, version,
transient,
function: function_name, function: function_name,
file: file.to_path_buf(), file: file.to_path_buf(),
signature, signature,
@@ -171,4 +175,24 @@ mod tests {
assert!(!node.signature.contains("cache"), "{}", node.signature); assert!(!node.signature.contains("cache"), "{}", node.signature);
assert!(node.signature.contains("image"), "{}", node.signature); assert!(node.signature.contains("image"), "{}", node.signature);
} }
#[test]
fn the_transient_attribute_is_read() {
let transient: syn::ItemFn = syn::parse_quote! {
#[node_macro::node(transient, memoize)]
fn draw(_: impl Ctx) -> List<Vector> {
List::new()
}
};
let saved: syn::ItemFn = syn::parse_quote! {
#[node_macro::node(category(""), memoize)]
fn draw(_: impl Ctx) -> List<Vector> {
List::new()
}
};
let node = |function| node_source(function, Path::new("lib.rs"), &["drawing".to_string()]).expect("the function is a node");
assert!(node(&transient).transient);
assert!(!node(&saved).transient);
}
} }
+1 -1
View File
@@ -13,7 +13,7 @@ pub(crate) const MIGRATION_CRATES: [&str; 2] = [MIGRATIONS, "document/migrations
/// `new` scaffolds every step missing between a node's newest migration and its version, `new <identifier>` does so for one node, /// `new` scaffolds every step missing between a node's newest migration and its version, `new <identifier>` does so for one node,
/// `new <old>@<version> <identifier>` replaces a node by another, and `rename <old>@<version> <identifier>` registers a finished rename. /// `new <old>@<version> <identifier>` replaces a node by another, and `rename <old>@<version> <identifier>` registers a finished rename.
pub(crate) fn scaffold(workspace: &Path, command: &str, arguments: &[String]) -> Result<(), String> { pub(crate) fn scaffold(workspace: &Path, command: &str, arguments: &[String]) -> Result<(), String> {
let nodes = find_nodes(&workspace.join(NODE_CRATES))?; let nodes: Vec<NodeSource> = find_nodes(&workspace.join(NODE_CRATES))?.into_iter().filter(|node| !node.transient).collect();
let migrations = workspace.join(MIGRATIONS); let migrations = workspace.join(MIGRATIONS);
match (command, arguments) { match (command, arguments) {
@@ -665,6 +665,18 @@ mod test {
assert!(rectangle < polygon && polygon < ellipse, "The first drawn layer should be painted first: {svg}"); assert!(rectangle < polygon && polygon < ellipse, "The first drawn layer should be painted first: {svg}");
} }
#[cfg_attr(miri, ignore)]
#[tokio::test]
async fn copied_svg_leaves_out_the_layers_that_are_not_copied() {
let mut editor = create_editor_with_three_layers().await;
let top = editor.active_document().metadata().all_layers().next().expect("the document has layers").to_node();
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![top] }).await;
let clipboard = copy_layers_to_clipboard(&mut editor).await;
let svg = copied_svg(&clipboard).expect("the copied layer should render an SVG");
assert_eq!(svg.matches("<path").count(), 1, "only the copied layer should be drawn: {svg}");
}
/// - paste /// - paste
/// - assert that ellipse was copied /// - assert that ellipse was copied
#[tokio::test] #[tokio::test]
@@ -997,7 +997,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
artboard_name, artboard_name,
artboard_count, artboard_count,
}; };
let result = self.executor.submit_document_export(document, document_id, export_config); let result = self.executor.submit_document_export(document, export_config);
if let Err(description) = result { if let Err(description) = result {
responses.add(DialogMessage::DisplayDialogError { responses.add(DialogMessage::DisplayDialogError {
@@ -1124,18 +1124,14 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
} }
} }
PortfolioMessage::SubmitClipboardSvg { id } => { PortfolioMessage::SubmitClipboardSvg { id } => {
let layers = self.active_document().map(|document| { let Some(document) = self.active_document_id.and_then(|document_id| self.documents.get(&document_id)) else {
let selected = document.partition_selection().layers; responses.add(ClipboardMessage::Rendered { id, svg: None });
let mut layers = document return;
.metadata() };
.all_layers() let selected = document.partition_selection().layers;
.filter(|layer| selected.contains(layer)) let mut layers = document.metadata().all_layers().filter(|layer| selected.contains(layer)).collect::<Vec<_>>();
.map(|layer| layer.to_node()) layers.reverse();
.collect::<Vec<_>>(); responses.add(self.executor.submit_clipboard_svg(document, id, &layers));
layers.reverse();
layers
});
responses.add(self.executor.submit_clipboard_svg(self.active_document_id, id, layers.unwrap_or_default()));
} }
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => { PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open; self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
+205 -130
View File
@@ -1,23 +1,28 @@
use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage, RenderStatus}; use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage, RenderStatus};
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::node_graph::utility_types::NodeEvaluationError; use crate::messages::portfolio::document::node_graph::utility_types::NodeEvaluationError;
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::network_interface::{InputConnector, NodeNetworkInterface}; use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface, RootNode};
use crate::messages::prelude::*; use crate::messages::prelude::*;
use glam::{DAffine2, DVec2, UVec2}; use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue}; use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork}; use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
use graph_craft::list;
use graph_craft::proto::GraphErrors; use graph_craft::proto::GraphErrors;
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation}; use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
use graphene_std::bounds::RenderBoundingBox; use graphene_std::bounds::RenderBoundingBox;
use graphene_std::color::SRGBA8; use graphene_std::color::SRGBA8;
use graphene_std::list::{Item, List}; use graphene_std::list::{Item, List};
use graphene_std::math::quad::Quad;
use graphene_std::raster::{CPU, Raster}; use graphene_std::raster::{CPU, Raster};
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box}; use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
use graphene_std::transform::Footprint; use graphene_std::transform::Footprint;
use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, path, paths_from_list_row_attributes}; use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, path, paths_from_list_row_attributes};
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic, NodeParameter}; use graphene_std::{ATTR_TRANSFORM, Artboard, ContextOverrides, Graphic, NodeParameter};
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta; use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
use interpreted_executor::layer_paths::{layer_content, write_layer_paths};
use std::any::Any; use std::any::Any;
use std::sync::Arc; use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender}; use std::sync::mpsc::{Receiver, Sender};
@@ -97,7 +102,8 @@ impl std::fmt::Display for EvaluationErrors {
#[derive(serde::Serialize, serde::Deserialize)] #[derive(serde::Serialize, serde::Deserialize)]
pub struct CompilationResponse { pub struct CompilationResponse {
result: Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)>, result: Result<(), String>,
resolved_types: ResolvedDocumentNodeTypesDelta,
node_graph_errors: GraphErrors, node_graph_errors: GraphErrors,
node_graph_warnings: GraphErrors, node_graph_warnings: GraphErrors,
} }
@@ -112,19 +118,24 @@ pub enum NodeGraphUpdate {
}, },
/// The latest result of each observation, sent outside an execution after one of them changed. /// The latest result of each observation, sent outside an execution after one of them changed.
Observations(HashMap<ObservationKey, InspectResult>), Observations(HashMap<ObservationKey, InspectResult>),
ClipboardSvg { Export {
id: u64, id: u64,
svg: Option<String>, result: Box<ExecutionResult>,
}, },
} }
#[derive(Debug)] #[derive(Debug)]
pub struct NodeGraphExecutor { pub struct NodeGraphExecutor {
sender: Sender<GraphRuntimeRequest>, sender: Sender<GraphRuntimeRequest>,
receiver: Receiver<NodeGraphUpdate>, receiver: Receiver<NodeGraphUpdate>,
current_execution_id: u64, current_execution_id: u64,
futures: VecDeque<(u64, ExecutionContext)>, futures: VecDeque<(u64, ExecutionContext)>,
pending: Option<(u64, ExecutionContext)>, pending: Option<(u64, ExecutionContext)>,
current_export_id: u64,
exports: HashMap<u64, ExportTarget>,
node_graph_hash: u64, node_graph_hash: u64,
/// The document whose network the graph runtime was last sent. /// The document whose network the graph runtime was last sent.
node_graph_document: Option<DocumentId>, node_graph_document: Option<DocumentId>,
@@ -146,9 +157,14 @@ pub struct NodeGraphExecutor {
gradient_migration_attempted: HashSet<DocumentId>, gradient_migration_attempted: HashSet<DocumentId>,
} }
#[derive(Debug)]
enum ExportTarget {
File(ExportConfig),
Clipboard(u64),
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
struct ExecutionContext { struct ExecutionContext {
export_config: Option<ExportConfig>,
document_id: DocumentId, document_id: DocumentId,
/// The view the render was asked for, which the footprints it reports back are measured in. /// The view the render was asked for, which the footprints it reports back are measured in.
document_to_viewport: DAffine2, document_to_viewport: DAffine2,
@@ -183,6 +199,8 @@ impl NodeGraphExecutor {
futures: Default::default(), futures: Default::default(),
pending: None, pending: None,
current_execution_id: 0, current_execution_id: 0,
current_export_id: 0,
exports: HashMap::new(),
node_graph_hash: 0, node_graph_hash: 0,
node_graph_document: None, node_graph_document: None,
previous_node_to_inspect: Vec::new(), previous_node_to_inspect: Vec::new(),
@@ -211,6 +229,21 @@ impl NodeGraphExecutor {
execution_id execution_id
} }
fn queue_export(&mut self, network: NodeNetwork, resources: ResourceRegistry, render_config: RenderConfig, target: ExportTarget) -> Result<(), String> {
let id = self.current_export_id;
self.current_export_id += 1;
let request = GraphRuntimeRequest::Export {
id,
render_config,
network,
resources,
};
self.sender.send(request).map_err(|e| e.to_string())?;
self.exports.insert(id, target);
Ok(())
}
pub fn submit_overlays(&self, context: crate::messages::portfolio::document::overlays::utility_types::OverlayContext) { pub fn submit_overlays(&self, context: crate::messages::portfolio::document::overlays::utility_types::OverlayContext) {
if let Err(error) = self.sender.send(GraphRuntimeRequest::RenderOverlays(context)) { if let Err(error) = self.sender.send(GraphRuntimeRequest::RenderOverlays(context)) {
log::error!("Failed to send the overlays: {error}"); log::error!("Failed to send the overlays: {error}");
@@ -229,13 +262,29 @@ impl NodeGraphExecutor {
.expect("Failed to send the context overrides"); .expect("Failed to send the context overrides");
} }
pub fn submit_clipboard_svg(&self, document_id: Option<DocumentId>, id: u64, layers: Vec<NodeId>) -> Message { pub fn submit_clipboard_svg(&mut self, document: &DocumentMessageHandler, id: u64, layers: &[LayerNodeIdentifier]) -> Message {
if document_id.is_none() || self.node_graph_document != document_id { let no_svg = ClipboardMessage::Rendered { id, svg: None }.into();
return ClipboardMessage::Rendered { id, svg: None }.into(); let Some((network, [min, max])) = copied_layers(&document.network_interface, layers) else {
} return no_svg;
};
self.sender.send(GraphRuntimeRequest::ClipboardSvg { id, layers }).expect("Failed to send runtime request"); let viewport = Footprint {
Message::NoOp resolution: (max - min).round().as_uvec2(),
transform: DAffine2::from_translation(-min),
..Default::default()
};
let render_config = RenderConfig {
viewport,
scale: 1.,
export_format: ExportFormat::Svg,
for_export: true,
..Default::default()
};
match self.queue_export(network, document.resources.registry.clone(), render_config, ExportTarget::Clipboard(id)) {
Ok(()) => Message::NoOp,
Err(_) => no_svg,
}
} }
pub fn submit_thumbnails_in_view(&self, document: &DocumentMessageHandler, document_id: DocumentId) { pub fn submit_thumbnails_in_view(&self, document: &DocumentMessageHandler, document_id: DocumentId) {
@@ -260,9 +309,11 @@ impl NodeGraphExecutor {
let graph_hash = document.network_interface.network_hash().wrapping_add(document.resources.resolved_hash()); let graph_hash = document.network_interface.network_hash().wrapping_add(document.resources.resolved_hash());
if graph_hash != self.node_graph_hash || self.node_graph_document != Some(document_id) || ignore_hash { if graph_hash != self.node_graph_hash || self.node_graph_document != Some(document_id) || ignore_hash {
let network = document.network_interface.document_network().clone(); let mut network = document.network_interface.document_network().clone();
let previewed = document.network_interface.previewed_nodes(); let previewed = document.network_interface.previewed_nodes();
let layers = document.network_interface.layer_paths(); let layers = document.network_interface.layer_paths();
prepare_network(&mut network, &previewed, &layers);
let thumbnails = thumbnail_sources(&network, &layers);
self.node_graph_hash = graph_hash; self.node_graph_hash = graph_hash;
self.node_graph_document = Some(document_id); self.node_graph_document = Some(document_id);
@@ -272,8 +323,7 @@ impl NodeGraphExecutor {
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { .send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network, network,
resources, resources,
previewed, thumbnails,
layers,
observations: self.observations(&document.network_interface), observations: self.observations(&document.network_interface),
})) }))
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
@@ -337,7 +387,6 @@ impl NodeGraphExecutor {
self.futures.push_back(( self.futures.push_back((
execution_id, execution_id,
ExecutionContext { ExecutionContext {
export_config: None,
document_id, document_id,
document_to_viewport: viewport.transform, document_to_viewport: viewport.transform,
measure_fill: None, measure_fill: None,
@@ -404,7 +453,6 @@ impl NodeGraphExecutor {
self.futures.push_back(( self.futures.push_back((
execution_id, execution_id,
ExecutionContext { ExecutionContext {
export_config: None,
document_id, document_id,
document_to_viewport: viewport.transform, document_to_viewport: viewport.transform,
measure_fill: None, measure_fill: None,
@@ -415,10 +463,9 @@ impl NodeGraphExecutor {
} }
/// Evaluates a node graph for export /// Evaluates a node graph for export
pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, export_config: ExportConfig) -> Result<(), String> { pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, export_config: ExportConfig) -> Result<(), String> {
let network = document.network_interface.document_network().clone(); let mut network = document.network_interface.document_network().clone();
let previewed = document.network_interface.previewed_nodes(); prepare_network(&mut network, &document.network_interface.previewed_nodes(), &document.network_interface.layer_paths());
let resources = document.resources.registry.clone();
let export_format = if export_config.file_type == FileType::Svg { let export_format = if export_config.file_type == FileType::Svg {
graphene_std::application_io::ExportFormat::Svg graphene_std::application_io::ExportFormat::Svg
@@ -452,34 +499,12 @@ impl NodeGraphExecutor {
time: Default::default(), time: Default::default(),
pointer: DVec2::ZERO, pointer: DVec2::ZERO,
export_format, export_format,
// The viewport's render mode is only a way of viewing the artwork, which exports show as it is
render_mode: graphene_std::vector::style::RenderMode::Normal, render_mode: graphene_std::vector::style::RenderMode::Normal,
for_export: true, for_export: true,
for_eyedropper: false, for_eyedropper: false,
}; };
// Execute the node graph self.queue_export(network, document.resources.registry.clone(), render_config, ExportTarget::File(export_config))
self.sender
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
previewed,
layers: document.network_interface.layer_paths(),
observations: self.observations(&document.network_interface),
}))
.map_err(|e| e.to_string())?;
let execution_id = self.queue_execution(render_config);
self.futures.push_back((
execution_id,
ExecutionContext {
export_config: Some(export_config),
document_id,
document_to_viewport: viewport.transform,
measure_fill: None,
},
));
Ok(())
} }
/// Applies the graph runtime's responses to the active document, giving back the layers whose thumbnails the runtime dropped meanwhile. /// Applies the graph runtime's responses to the active document, giving back the layers whose thumbnails the runtime dropped meanwhile.
@@ -491,8 +516,8 @@ impl NodeGraphExecutor {
} }
let mut all_dropped_thumbnails = Vec::new(); let mut all_dropped_thumbnails = Vec::new();
let mut results = self.receiver.try_iter().collect::<Vec<_>>().into_iter(); let results = self.receiver.try_iter().collect::<Vec<_>>();
for response in results.by_ref() { for response in results {
match response { match response {
NodeGraphUpdate::ExecutionResponse(execution_response) => { NodeGraphUpdate::ExecutionResponse(execution_response) => {
let ExecutionResponse { let ExecutionResponse {
@@ -516,7 +541,7 @@ impl NodeGraphExecutor {
let execution_context = if self.futures.front().is_some_and(|&(queued_execution_id, _)| queued_execution_id == execution_id) { let execution_context = if self.futures.front().is_some_and(|&(queued_execution_id, _)| queued_execution_id == execution_id) {
let (_, execution_context) = self.futures.pop_front().expect("the front was just checked"); let (_, execution_context) = self.futures.pop_front().expect("the front was just checked");
if execution_context.export_config.is_none() && execution_context.measure_fill.is_none() { if execution_context.measure_fill.is_none() {
self.pending = Some((execution_id, execution_context.clone())); self.pending = Some((execution_id, execution_context.clone()));
} }
execution_context execution_context
@@ -571,7 +596,7 @@ impl NodeGraphExecutor {
responses.add(OverlaysMessage::Draw); responses.add(OverlaysMessage::Draw);
// A pending graph keeps the last frame, and the errors shown with it // A pending graph keeps the last frame, and the errors shown with it
if execution_context.export_config.is_none() && !matches!(result, ExecutionResult::Pending) { if !matches!(result, ExecutionResult::Pending) {
let errors = match &result { let errors = match &result {
ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => { ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => {
let in_document = |path: &&[NodeId]| { let in_document = |path: &&[NodeId]| {
@@ -644,11 +669,8 @@ impl NodeGraphExecutor {
log::error!("Node graph evaluation failed:\n{message}"); log::error!("Node graph evaluation failed:\n{message}");
} }
if execution_context.export_config.is_some() {
responses.add(export_failure_dialog(message));
}
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }); responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
break; continue;
} }
}; };
@@ -666,10 +688,8 @@ impl NodeGraphExecutor {
} }
document.network_interface.update_vector_modify(path_contents(&observations)); document.network_interface.update_vector_modify(path_contents(&observations));
match (node_graph_output, execution_context.export_config) { if let Some(node_graph_output) = node_graph_output {
(Some(node_graph_output), Some(export_config)) => self.process_export(node_graph_output, export_config, document, responses), self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, render_status, responses);
(Some(node_graph_output), None) => self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, render_status, responses),
(None, _) => {}
} }
responses.add(DeferMessage::TriggerGraphRun { responses.add(DeferMessage::TriggerGraphRun {
execution_id, execution_id,
@@ -691,49 +711,42 @@ impl NodeGraphExecutor {
node_graph_errors, node_graph_errors,
node_graph_warnings, node_graph_warnings,
result, result,
resolved_types,
} = execution_response; } = execution_response;
// TODO: Eventually remove this document upgrade code // TODO: Eventually remove this document upgrade code
// The migration's temporary redirected-export compilations must not push types or a graph view to the frontend // The migration's temporary redirected-export compilations must not push types or a graph view to the frontend
if self.gradient_migration.is_some() { if self.gradient_migration.is_some() {
if let Err((_, e)) = &result { if let Err(e) = &result {
log::trace!("Gradient migration measurement compile: {e}"); log::trace!("Gradient migration measurement compile: {e}");
} }
continue; continue;
} }
let type_delta = match result { if let Err(e) = &result {
Err((incomplete_delta, e)) => { // Clear the click targets while the graph is in an un-renderable state
// Clear the click targets while the graph is in an un-renderable state
document.network_interface.update_click_targets(HashMap::new(), HashSet::new()); document.network_interface.update_click_targets(HashMap::new(), HashSet::new());
document.network_interface.update_outlines(HashMap::new()); document.network_interface.update_outlines(HashMap::new());
document.network_interface.update_vector_modify(HashMap::new()); document.network_interface.update_vector_modify(HashMap::new());
// The graph only shows errors tied to nodes, so the console gets the others // The graph only shows errors tied to nodes, so the console gets the others
if node_graph_errors.is_empty() { if node_graph_errors.is_empty() {
log::error!("The node graph failed to compile:\n{e}"); log::error!("The node graph failed to compile:\n{e}");
} else { } else {
log::trace!("{e}"); log::trace!("{e}");
}
responses.add(NodeGraphMessage::UpdateTypes {
resolved_types: incomplete_delta,
node_graph_errors,
node_graph_warnings,
});
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
break;
} }
Ok(result) => result, }
};
responses.add(NodeGraphMessage::UpdateTypes { responses.add(NodeGraphMessage::UpdateTypes {
resolved_types: type_delta, resolved_types,
node_graph_errors, node_graph_errors,
node_graph_warnings, node_graph_warnings,
}); });
if result.is_err() {
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
}
} }
NodeGraphUpdate::EyedropperPreview(raster) => { NodeGraphUpdate::EyedropperPreview(raster) => {
let (data, width, height) = raster.to_flat_u8(); let (data, width, height) = raster.to_flat_u8();
@@ -756,33 +769,7 @@ impl NodeGraphExecutor {
Self::receive_thumbnails(document, thumbnails, responses); Self::receive_thumbnails(document, thumbnails, responses);
} }
} }
NodeGraphUpdate::ClipboardSvg { id, svg } => responses.add(ClipboardMessage::Rendered { id, svg }), NodeGraphUpdate::Export { id: export_id, result } => self.receive_export(export_id, *result, document, responses),
}
}
// An error leaves the later responses unapplied, but the runtime still dropped and rendered their thumbnails
for response in results {
match response {
NodeGraphUpdate::ExecutionResponse(execution_response) => {
let execution_context = self.execution_context(execution_response.execution_id);
if execution_context.is_some_and(|context| context.document_id == document_id) {
document.layers_in_view.forget_thumbnails(&execution_response.dropped_thumbnails, responses);
}
if matches!(execution_response.result, ExecutionResult::Uncompiled) && execution_context.is_some_and(|context| context.export_config.is_some()) {
responses.add(export_failure_dialog(None));
}
all_dropped_thumbnails.extend(execution_response.dropped_thumbnails);
}
NodeGraphUpdate::Thumbnails {
responses: thumbnails,
document_id: thumbnails_document,
} if thumbnails_document == document_id => {
Self::receive_thumbnails(document, thumbnails, responses);
}
NodeGraphUpdate::ClipboardSvg { id, svg } => responses.add(ClipboardMessage::Rendered { id, svg }),
_ => {}
} }
} }
@@ -798,15 +785,6 @@ impl NodeGraphExecutor {
} }
} }
/// What an execution was submitted for, while it's still queued or pending.
fn execution_context(&self, execution_id: u64) -> Option<&ExecutionContext> {
self.futures
.iter()
.chain(&self.pending)
.find(|(queued_execution_id, _)| *queued_execution_id == execution_id)
.map(|(_, execution_context)| execution_context)
}
// TODO: Eventually remove this document upgrade code // TODO: Eventually remove this document upgrade code
/// Kick off the one-time pre-pass converting legacy bounding-box gradients to absolute space, or no-op if already running. /// Kick off the one-time pre-pass converting legacy bounding-box gradients to absolute space, or no-op if already running.
/// Returns false when the render should proceed normally instead: the pass already ran this session, so any entries still /// Returns false when the render should proceed normally instead: the pass already ran this session, so any entries still
@@ -876,6 +854,10 @@ impl NodeGraphExecutor {
return; return;
} }
let layers = document.network_interface.layer_paths();
prepare_network(&mut network, &[], &layers);
let thumbnails = thumbnail_sources(&network, &layers);
let resources = document.resources.registry.clone(); let resources = document.resources.registry.clone();
let fill_measurement = Observation { let fill_measurement = Observation {
node_path: full_path, node_path: full_path,
@@ -887,8 +869,7 @@ impl NodeGraphExecutor {
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { .send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network, network,
resources, resources,
previewed: Vec::new(), thumbnails,
layers: document.network_interface.layer_paths(),
observations: HashMap::from([(ObservationKey::FillMeasurement, fill_measurement)]), observations: HashMap::from([(ObservationKey::FillMeasurement, fill_measurement)]),
})) }))
.is_err() .is_err()
@@ -920,7 +901,6 @@ impl NodeGraphExecutor {
self.futures.push_back(( self.futures.push_back((
execution_id, execution_id,
ExecutionContext { ExecutionContext {
export_config: None,
document_id, document_id,
document_to_viewport: viewport.transform, document_to_viewport: viewport.transform,
measure_fill: Some((network_path, fill_node_id, gradient)), measure_fill: Some((network_path, fill_node_id, gradient)),
@@ -1080,6 +1060,51 @@ impl NodeGraphExecutor {
responses.add(FrontendMessage::UpdateRenderStatus { status: render_status }); responses.add(FrontendMessage::UpdateRenderStatus { status: render_status });
} }
fn receive_export(&mut self, export_id: u64, result: ExecutionResult, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
let Some(target) = self.exports.remove(&export_id) else { return };
let failure = match (result, &target) {
(ExecutionResult::Value(value) | ExecutionResult::Fallback(value, _), _) => {
return match target {
ExportTarget::File(export_config) => self.process_export(value, export_config, document, responses),
ExportTarget::Clipboard(id) => {
let svg = match value {
TaggedValue::RenderOutput(RenderOutput {
data: RenderOutputType::Svg { svg, .. },
..
}) => Some(svg),
_ => None,
};
responses.add(ClipboardMessage::Rendered { id, svg });
}
};
}
(ExecutionResult::Error(errors), _) => Some(errors.to_string()),
(ExecutionResult::Panic(payload), _) => {
let message = payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::<String>().map(String::as_str));
Some(format!("Panicked: {}", message.unwrap_or("no message")))
}
(ExecutionResult::Pending | ExecutionResult::Partial(_) | ExecutionResult::Uncompiled, _) => None,
};
if let Some(message) = &failure {
log::error!("Node graph evaluation failed:\n{message}");
}
match target {
ExportTarget::File(_) => responses.add(DialogMessage::DisplayDialogError {
title: "Unable to export document".to_string(),
description: failure.unwrap_or_else(|| "The node graph has errors that prevent it from rendering.".to_string()),
}),
ExportTarget::Clipboard(id) => {
responses.add(ClipboardMessage::Rendered { id, svg: None });
if let Some(description) = failure {
let title = "Unable to copy as SVG".to_string();
responses.add(DialogMessage::DisplayDialogError { title, description });
}
}
}
}
fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) { fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
let ExportConfig { let ExportConfig {
file_type, file_type,
@@ -1179,6 +1204,61 @@ pub(crate) fn redirect_export_chain(network: &mut NodeNetwork, full_path: &[Node
} }
} }
fn prepare_network(network: &mut NodeNetwork, previewed: &[(Vec<NodeId>, RootNode)], layers: &[Vec<NodeId>]) {
apply_previews(network, previewed);
write_layer_paths(network, layers);
}
/// Replaces each network's primary export with its previewed node.
pub(crate) fn apply_previews(network: &mut NodeNetwork, previewed: &[(Vec<NodeId>, RootNode)]) {
for (network_path, previewed) in previewed {
let Some(nested) = network.nested_network_mut(network_path) else { continue };
let Some(export) = nested.exports.first_mut() else { continue };
*export = NodeInput::node(previewed.node_id, previewed.output_index);
}
}
/// The node giving the content each layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
fn thumbnail_sources(network: &NodeNetwork, layers: &[Vec<NodeId>]) -> Vec<(NodeId, Vec<NodeId>)> {
// O(layers * depth)
let source = |layer: &Vec<NodeId>| Some((*layer.last()?, layer_content(layer, network)?.source(network)?));
layers.iter().filter_map(source).collect()
}
fn copied_layers(interface: &NodeNetworkInterface, layers: &[LayerNodeIdentifier]) -> Option<(NodeNetwork, [DVec2; 2])> {
let metadata = interface.document_metadata();
let is_artboard = |layer: &LayerNodeIdentifier| interface.is_artboard(&layer.to_node(), &[]);
let stack = match layers.iter().filter(|layer| is_artboard(layer)).count() {
0 if layers.iter().all(|layer| interface.is_merge(&layer.to_node(), &[])) => list!(Graphic),
artboards if artboards == layers.len() => list!(Artboard),
_ => return None,
};
let mut network = interface.document_network().clone();
prepare_network(&mut network, &interface.previewed_nodes(), &interface.layer_paths());
let mut below = NodeInput::type_default(stack, true);
let mut bounds = None;
for &layer in layers {
let mut node = network.nodes.get(&layer.to_node())?.clone();
*node.inputs.first_mut()? = below;
let copy = NodeId::new();
network.nodes.insert(copy, node);
below = NodeInput::node(copy, 0);
let from_document = match metadata.upstream_footprints.contains_key(&layer.to_node()) {
true => metadata.downstream_transform_to_document(layer).inverse(),
false => DAffine2::IDENTITY,
};
let in_document = metadata.bounding_box_document_with_stroke_and_effects(layer);
let own = in_document.map(|bounds| (from_document * Quad::from_box(bounds)).bounding_box());
bounds = [bounds, own].into_iter().flatten().reduce(Quad::combine_bounds);
}
network.exports = vec![below];
Some((network, bounds?))
}
// TODO: Eventually remove this document upgrade code // TODO: Eventually remove this document upgrade code
/// Turn a measured fill node's evaluated geometry into a `[0,1]² -> bounding box` affine plus the geometry's item transform. /// Turn a measured fill node's evaluated geometry into a `[0,1]² -> bounding box` affine plus the geometry's item transform.
fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2, DAffine2)> { fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2, DAffine2)> {
@@ -1200,14 +1280,6 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
None None
} }
/// Says why an export saved nothing, given the evaluation's error, or else the graph's failure to compile.
fn export_failure_dialog(evaluation_error: Option<String>) -> DialogMessage {
DialogMessage::DisplayDialogError {
title: "Unable to export document".to_string(),
description: evaluation_error.unwrap_or_else(|| "The node graph has errors that prevent it from rendering.".to_string()),
}
}
fn path_content_observations(network_interface: &NodeNetworkInterface) -> impl Iterator<Item = (ObservationKey, Observation)> { fn path_content_observations(network_interface: &NodeNetworkInterface) -> impl Iterator<Item = (ObservationKey, Observation)> {
let path_nodes = network_interface.node_paths_with_reference(&DefinitionIdentifier::ProtoNode(path::IDENTIFIER)); let path_nodes = network_interface.node_paths_with_reference(&DefinitionIdentifier::ProtoNode(path::IDENTIFIER));
@@ -1273,14 +1345,17 @@ mod test {
network.inline_definitions().map_err(|error| error.to_string())?; network.inline_definitions().map_err(|error| error.to_string())?;
let instrumented = Instrumented::new(&network); let instrumented = Instrumented::new(&network);
let layers = document.network_interface.layer_paths();
prepare_network(&mut network, &[], &layers);
let thumbnails = thumbnail_sources(&network, &layers);
let resources = document.resources.registry.clone(); let resources = document.resources.registry.clone();
self.sender self.sender
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { .send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network, network,
resources, resources,
previewed: Vec::new(), thumbnails,
layers: document.network_interface.layer_paths(),
observations: self.observations(&document.network_interface), observations: self.observations(&document.network_interface),
})) }))
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
@@ -18,8 +18,8 @@ async fn compile_and_run(editor: &mut EditorTestUtils) {
editor.dispatch(Message::Wake); editor.dispatch(Message::Wake);
} }
/// The proto node IDs compiled for the document node paths that pass `keep`. The executor keeps the nodes an update drops /// The proto node IDs compiled for the document node paths that pass `keep`. The runtime keeps the output of the network
/// for one more update, so a first update clears those of the graph before it. /// an update replaces for one more update, so a first update clears the nodes of the graph before it.
async fn compiled_ids(editor: &mut EditorTestUtils, keep: impl Fn(&[NodeId]) -> bool) -> HashSet<NodeId> { async fn compiled_ids(editor: &mut EditorTestUtils, keep: impl Fn(&[NodeId]) -> bool) -> HashSet<NodeId> {
compile_and_run(editor).await; compile_and_run(editor).await;
compile_and_run(editor).await; compile_and_run(editor).await;
File diff suppressed because it is too large. Load diff
@@ -3,7 +3,7 @@ use crate::messages::frontend::FrontendMessage;
use atlas::ThumbnailAtlasLayout; use atlas::ThumbnailAtlasLayout;
use glam::{DAffine2, DVec2, UVec2}; use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::PlatformEditorApi; use graph_craft::application_io::PlatformEditorApi;
use graph_craft::document::{NodeId, NodeNetwork}; use graph_craft::document::NodeId;
use graphene_std::application_io::{ApplicationIo, Texture}; use graphene_std::application_io::{ApplicationIo, Texture};
use graphene_std::bounds::RenderBoundingBox; use graphene_std::bounds::RenderBoundingBox;
use graphene_std::gradient::Gradient; use graphene_std::gradient::Gradient;
@@ -12,12 +12,11 @@ use graphene_std::ops::ConvertAsync;
#[cfg(all(target_family = "wasm", feature = "wasm"))] #[cfg(all(target_family = "wasm", feature = "wasm"))]
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasHandle}; use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasHandle};
use graphene_std::raster_types::{CPU, GPU, Raster}; use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender}; use graphene_std::renderer::Render;
use graphene_std::transform::{Footprint, RenderQuality}; use graphene_std::transform::Footprint;
use graphene_std::vector::Vector; use graphene_std::vector::Vector;
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic}; use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic};
use interpreted_executor::dynamic_executor::DynamicExecutor; use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::layer_paths::layer_content;
use std::collections::{HashMap, HashSet, VecDeque}; use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::Arc; use std::sync::Arc;
@@ -83,12 +82,9 @@ impl Thumbnails {
} }
/// Finds the proto node giving each layer's content in the newly compiled graph, marking the layers whose proto node changed as stale. /// Finds the proto node giving each layer's content in the newly compiled graph, marking the layers whose proto node changed as stale.
pub fn update_sources(&mut self, layer_paths: &[Vec<NodeId>], network: &NodeNetwork, executor: &DynamicExecutor) { pub fn update_sources(&mut self, layers: &[(NodeId, Vec<NodeId>)], executor: &DynamicExecutor) {
// O(layers * depth) let source_map = executor.tree().source_map();
let sources: HashMap<NodeId, NodeId> = layer_paths let sources: HashMap<NodeId, NodeId> = layers.iter().filter_map(|(layer, source)| Some((*layer, source_map.get(source.as_slice())?.0))).collect();
.iter()
.filter_map(|layer_path| Some((*layer_path.last()?, thumbnail_source(layer_path, network, executor)?)))
.collect();
// A proto node's ID hashes everything upstream of it, so a layer whose source kept its ID shows the same content // A proto node's ID hashes everything upstream of it, so a layer whose source kept its ID shows the same content
let changed = sources.iter().filter(|(layer, source)| self.sources.get(layer) != Some(source)); let changed = sources.iter().filter(|(layer, source)| self.sources.get(layer) != Some(source));
@@ -276,11 +272,11 @@ impl ThumbnailContent {
} }
} }
/// The area the content covers once rendered, counting the effects drawn through maps and images only if they're `maps_resolved`, which the clipboard's SVG leaves out. /// The area the content covers once rendered, counting the effects drawn through maps and images.
fn content_bounds(&self, maps_resolved: bool) -> RenderBoundingBox { fn content_bounds(&self) -> RenderBoundingBox {
match self { match self {
// Text-aware bounds, which the `BoundingBox` trait can't give `Graphic::TextList` content, with the effects' reach // Text-aware bounds, which the `BoundingBox` trait can't give `Graphic::TextList` content, with the effects' reach
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics, maps_resolved), Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics, true),
// The clipping rectangles rather than the content, since the renderer clips content to them // The clipping rectangles rather than the content, since the renderer clips content to them
Self::Artboards(artboards) => artboard_clip_bounds(artboards), Self::Artboards(artboards) => artboard_clip_bounds(artboards),
Self::Text(text) => graphene_std::renderer::text_list_bounding_box(text, DAffine2::IDENTITY), Self::Text(text) => graphene_std::renderer::text_list_bounding_box(text, DAffine2::IDENTITY),
@@ -289,7 +285,7 @@ impl ThumbnailContent {
/// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio. /// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio.
fn bounds(&self) -> [DVec2; 2] { fn bounds(&self) -> [DVec2; 2] {
let bounds = match self.content_bounds(true) { let bounds = match self.content_bounds() {
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => bounds, RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => bounds,
_ => [DVec2::ZERO, DVec2::ONE], _ => [DVec2::ZERO, DVec2::ONE],
}; };
@@ -297,45 +293,6 @@ impl ThumbnailContent {
} }
} }
/// Renders what each of these document layers adds, painted in the given order, as one SVG framed to their combined bounds, or `None` if they render nothing.
pub fn layers_svg(layers: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<String> {
let contents: Vec<ThumbnailContent> = layers
.iter()
.filter_map(|&layer| ThumbnailContent::evaluate(executor, thumbnail_source(&[layer], network, executor)?))
.collect();
let bounds = contents
.iter()
.filter_map(|content| match content.content_bounds(false) {
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => Some(bounds),
_ => None,
})
.reduce(|[min, max], [other_min, other_max]| [min.min(other_min), max.max(other_max)])?;
let render_params = RenderParams {
footprint: Footprint::from_bounds(bounds, RenderQuality::Full),
thumbnail: true,
..Default::default()
};
let mut render = SvgRender::new();
for content in &contents {
content.graphic().render_svg(&mut render, &render_params);
}
if render.svg.is_empty() {
return None;
}
render.format_svg(bounds[0], bounds[1]);
Some(render.svg.to_svg_string())
}
/// The proto node giving the content a layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
fn thumbnail_source(layer_path: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<NodeId> {
let source = layer_content(layer_path, network)?.source(network)?;
executor.tree().source_map().get(source.as_slice()).map(|(id, _)| *id)
}
/// Converts the other kinds of graphical content into a graphic. /// Converts the other kinds of graphical content into a graphic.
fn into_graphic(output: graphene_std::registry::Any) -> Option<Graphic> { fn into_graphic(output: graphene_std::registry::Any) -> Option<Graphic> {
macro_rules! downcast_into_graphic { macro_rules! downcast_into_graphic {
+1
View File
@@ -41,6 +41,7 @@ raster-nodes = { workspace = true, features = ["serde"] }
vector-nodes = { workspace = true, features = ["serde"] } vector-nodes = { workspace = true, features = ["serde"] }
graphic-types = { workspace = true, features = ["serde"] } graphic-types = { workspace = true, features = ["serde"] }
text-nodes = { workspace = true, features = ["serde"] } text-nodes = { workspace = true, features = ["serde"] }
graph-ui-types = { workspace = true }
# Workspace dependencies # Workspace dependencies
log = { workspace = true } log = { workspace = true }
@@ -110,6 +110,8 @@ macro_rules! tagged_value {
Runtime(RuntimeHandle), Runtime(RuntimeHandle),
#[serde(skip)] #[serde(skip)]
EditorApi(Arc<PlatformEditorApi>), EditorApi(Arc<PlatformEditorApi>),
#[serde(skip)]
GraphUi(graph_ui_types::TaggedGraphUiValue),
/// Only used by the `resource` node, should never be serialized /// Only used by the `resource` node, should never be serialized
#[serde(skip)] #[serde(skip)]
ResourceHash(ResourceHash), ResourceHash(ResourceHash),
@@ -144,6 +146,7 @@ macro_rules! tagged_value {
Self::Runtime(runtime) => runtime.cache_hash(state), Self::Runtime(runtime) => runtime.cache_hash(state),
Self::RenderOutput(x) => x.cache_hash(state), Self::RenderOutput(x) => x.cache_hash(state),
Self::EditorApi(x) => x.cache_hash(state), Self::EditorApi(x) => x.cache_hash(state),
Self::GraphUi(x) => x.cache_hash(state),
Self::ResourceHash(x) => x.cache_hash(state), Self::ResourceHash(x) => x.cache_hash(state),
} }
} }
@@ -208,6 +211,7 @@ macro_rules! tagged_value {
Self::SourceId(source) => Box::new(Item::new_from_element(source)), Self::SourceId(source) => Box::new(Item::new_from_element(source)),
Self::Runtime(runtime) => Box::new(Item::new_from_element(runtime)), Self::Runtime(runtime) => Box::new(Item::new_from_element(runtime)),
Self::EditorApi(x) => Box::new(Item::new_from_element(x)), Self::EditorApi(x) => Box::new(Item::new_from_element(x)),
Self::GraphUi(x) => x.to_dynany(),
Self::ResourceHash(x) => Box::new(Item::new_from_element(x)), Self::ResourceHash(x) => Box::new(Item::new_from_element(x)),
} }
} }
@@ -268,6 +272,7 @@ macro_rules! tagged_value {
Self::SourceId(source) => Arc::new(Item::new_from_element(source)), Self::SourceId(source) => Arc::new(Item::new_from_element(source)),
Self::Runtime(runtime) => Arc::new(Item::new_from_element(runtime)), Self::Runtime(runtime) => Arc::new(Item::new_from_element(runtime)),
Self::EditorApi(x) => Arc::new(Item::new_from_element(x)), Self::EditorApi(x) => Arc::new(Item::new_from_element(x)),
Self::GraphUi(x) => x.to_any(),
Self::ResourceHash(x) => Arc::new(Item::new_from_element(x)), Self::ResourceHash(x) => Arc::new(Item::new_from_element(x)),
} }
} }
@@ -300,6 +305,7 @@ macro_rules! tagged_value {
Self::SourceId(_) => item!(SourceId), Self::SourceId(_) => item!(SourceId),
Self::Runtime(_) => item!(RuntimeHandle), Self::Runtime(_) => item!(RuntimeHandle),
Self::EditorApi(_) => item!(Arc<PlatformEditorApi>), Self::EditorApi(_) => item!(Arc<PlatformEditorApi>),
Self::GraphUi(x) => x.ty(),
Self::ResourceHash(_) => item!(ResourceHash), Self::ResourceHash(_) => item!(ResourceHash),
}; };
@@ -458,6 +464,7 @@ macro_rules! tagged_value {
Self::SourceId(source) => format!("SourceId({source:?})"), Self::SourceId(source) => format!("SourceId({source:?})"),
Self::Runtime(_) => "Runtime".to_string(), Self::Runtime(_) => "Runtime".to_string(),
Self::EditorApi(_) => "PlatformEditorApi".to_string(), Self::EditorApi(_) => "PlatformEditorApi".to_string(),
Self::GraphUi(_) => "GraphUi".to_string(),
Self::ResourceHash(hash) => format!("ResourceHash({hash:?})"), Self::ResourceHash(hash) => format!("ResourceHash({hash:?})"),
} }
} }
+36
View File
@@ -0,0 +1,36 @@
[package]
name = "graph-ui"
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
[features]
serde = ["graph-ui-types/serde"]
wasm = ["graph-ui-types/wasm"]
[dependencies]
# Local dependencies
core-types = { workspace = true }
graph-craft = { workspace = true }
graph-ui-icons = { workspace = true }
graph-ui-types = { workspace = true }
graphene-std = { workspace = true }
graphic-types = { workspace = true }
node-macro = { workspace = true }
rendering = { workspace = true }
svg-convert = { workspace = true }
text-nodes = { workspace = true }
vector-types = { workspace = true }
# Workspace dependencies
glam = { workspace = true }
vello_gpu = { workspace = true }
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "graph-ui-icons"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
+39
View File
@@ -0,0 +1,39 @@
// TODO(Timon): Replace with generalized icon crate
use std::fmt::Write;
use std::path::PathBuf;
const FOLDERS: [&str; 2] = ["16x16-nodes", "16x16-ui-general"];
fn main() {
let root = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("../../..");
let assets = root.join("branding/assets");
let mut sources = Vec::new();
println!("cargo:rerun-if-changed={}", assets.display());
if assets.is_dir() {
for folder in FOLDERS {
for entry in std::fs::read_dir(assets.join(folder)).unwrap() {
let path = entry.unwrap().path();
if path.extension().is_some_and(|extension| extension == "svg") {
sources.push((icon_name(&path.file_stem().unwrap().to_string_lossy()), path));
}
}
}
} else {
println!("cargo:warning=No branding folder, icons will be missing");
}
sources.sort();
let mut table = String::from("static SOURCES: &[(&str, &str)] = &[\n");
for (name, path) in &sources {
writeln!(table, "\t({name:?}, include_str!({:?})),", path.display().to_string()).unwrap();
}
table.push_str("];\n");
std::fs::write(PathBuf::from(std::env::var("OUT_DIR").unwrap()).join("icons.rs"), table).unwrap();
}
fn icon_name(file_stem: &str) -> String {
let capitalized = |word: &str| word[..1].to_uppercase() + &word[1..];
file_stem.split('-').filter(|word| !word.is_empty()).map(capitalized).collect()
}
+8
View File
@@ -0,0 +1,8 @@
// TODO(Timon): Replace with generalized icon crate
include!(concat!(env!("OUT_DIR"), "/icons.rs"));
pub fn svg(name: &str) -> Option<&'static str> {
let index = SOURCES.binary_search_by_key(&name, |&(name, _)| name).ok()?;
Some(SOURCES[index].1)
}
+266
View File
@@ -0,0 +1,266 @@
use crate::metrics::{BORDER_DASHES, BORDER_WIDTH};
use glam::DVec2;
use std::f64::consts::{FRAC_PI_2, PI};
use std::ops::Range;
use vello_gpu::kurbo::{Arc, BezPath, CubicBez, Line, ParamCurve, PathEl, PathSeg, Point, QuadBez};
const MEASURE_TOLERANCE: f64 = 0.5;
const MEASURE_DEPTH: u32 = 20;
const ARC_TOLERANCE: f64 = 0.1;
struct Measured {
distance: f64,
segment: usize,
t: f64,
}
pub(crate) fn dashed(path: &BezPath, [dash, gap]: [f64; 2]) -> BezPath {
let mut dashes = BezPath::new();
for contour in contours(path) {
let measured = measure(&contour);
let Some(length) = measured.last().map(|last| last.distance) else { continue };
let mut distance = 0.;
for (index, interval) in [dash, gap].into_iter().cycle().enumerate() {
if distance >= length {
break;
}
if index % 2 == 0 {
piece(&contour, &measured, distance..(distance + interval).min(length), &mut dashes);
}
distance += interval;
}
}
dashes
}
fn contours(path: &BezPath) -> Vec<Vec<PathSeg>> {
let mut contours: Vec<Vec<PathSeg>> = Vec::new();
let (mut start, mut last) = (Point::ZERO, Point::ZERO);
for element in path.elements() {
let segment = match *element {
PathEl::MoveTo(point) => {
contours.push(Vec::new());
(start, last) = (point, point);
continue;
}
PathEl::LineTo(point) => PathSeg::Line(Line::new(last, point)),
PathEl::QuadTo(control, point) => PathSeg::Cubic(QuadBez::new(last, control, point).raise()),
PathEl::CurveTo(first, second, point) => PathSeg::Cubic(CubicBez::new(last, first, second, point)),
PathEl::ClosePath => PathSeg::Line(Line::new(last, start)),
};
last = segment.end();
if let Some(contour) = contours.last_mut() {
contour.push(segment);
}
}
contours
}
fn measure(contour: &[PathSeg]) -> Vec<Measured> {
let mut measured = Vec::new();
let mut distance = 0.;
for (segment, piece) in contour.iter().enumerate() {
distance = match piece {
PathSeg::Cubic(cubic) => measure_cubic(*cubic, distance, 0_f64..1., MEASURE_DEPTH, segment, &mut measured),
_ => chord(piece.start(), piece.end(), distance, segment, 1., &mut measured),
};
}
measured
}
fn measure_cubic(cubic: CubicBez, distance: f64, range: Range<f64>, depth: u32, segment: usize, measured: &mut Vec<Measured>) -> f64 {
let strays = |control: Point, fraction: f64| {
let on_chord = cubic.p0.lerp(cubic.p3, fraction);
(control.x - on_chord.x).abs().max((control.y - on_chord.y).abs()) > MEASURE_TOLERANCE
};
if depth == 0 || !(strays(cubic.p1, 1. / 3.) || strays(cubic.p2, 2. / 3.)) {
return chord(cubic.p0, cubic.p3, distance, segment, range.end, measured);
}
let (first, second) = cubic.subdivide();
let middle = (range.start + range.end) / 2.;
let distance = measure_cubic(first, distance, range.start..middle, depth - 1, segment, measured);
measure_cubic(second, distance, middle..range.end, depth - 1, segment, measured)
}
fn chord(from: Point, to: Point, distance: f64, segment: usize, t: f64, measured: &mut Vec<Measured>) -> f64 {
let next = distance + from.distance(to);
if next > distance {
measured.push(Measured { distance: next, segment, t });
}
next
}
fn at(measured: &[Measured], distance: f64) -> (usize, f64) {
let index = measured.partition_point(|entry| entry.distance < distance).min(measured.len() - 1);
let entry = &measured[index];
let (start_distance, start_t) = match index.checked_sub(1).map(|previous| &measured[previous]) {
Some(previous) if previous.segment == entry.segment => (previous.distance, previous.t),
Some(previous) => (previous.distance, 0.),
None => (0., 0.),
};
(entry.segment, start_t + (entry.t - start_t) * (distance - start_distance) / (entry.distance - start_distance))
}
fn piece(contour: &[PathSeg], measured: &[Measured], range: Range<f64>, dashes: &mut BezPath) {
let (start_segment, start_t) = at(measured, range.start);
let (end_segment, end_t) = at(measured, range.end);
dashes.move_to(contour[start_segment].eval(start_t));
let mut push = |segment: usize, range: Range<f64>| match contour[segment].subsegment(range) {
PathSeg::Line(line) => dashes.line_to(line.p1),
PathSeg::Quad(quad) => dashes.quad_to(quad.p1, quad.p2),
PathSeg::Cubic(cubic) => dashes.curve_to(cubic.p1, cubic.p2, cubic.p3),
};
if start_segment == end_segment {
push(start_segment, start_t..end_t);
return;
}
push(start_segment, start_t..1.);
for segment in start_segment + 1..end_segment {
push(segment, 0. ..1.);
}
push(end_segment, 0. ..end_t);
}
enum BorderPart {
Line(DVec2, DVec2),
Corner(DVec2, f64),
}
pub(crate) fn border(min: DVec2, max: DVec2, radius: f64, gaps: &[[DVec2; 2]], dashed: bool) -> BezPath {
let inset = BORDER_WIDTH / 2.;
let arc_radius = radius - inset;
let corner_length = flattened_arc_length(radius, [0., FRAC_PI_2]);
let [left, top] = (min + inset).to_array();
let [right, bottom] = (max - inset).to_array();
let parts = [
BorderPart::Line(DVec2::new(left + arc_radius, top), DVec2::new(right - arc_radius, top)),
BorderPart::Corner(DVec2::new(right - arc_radius, top + arc_radius), -FRAC_PI_2),
BorderPart::Line(DVec2::new(right, top + arc_radius), DVec2::new(right, bottom - arc_radius)),
BorderPart::Corner(DVec2::new(right - arc_radius, bottom - arc_radius), 0.),
BorderPart::Line(DVec2::new(right - arc_radius, bottom), DVec2::new(left + arc_radius, bottom)),
BorderPart::Corner(DVec2::new(left + arc_radius, bottom - arc_radius), FRAC_PI_2),
BorderPart::Line(DVec2::new(left, bottom - arc_radius), DVec2::new(left, top + arc_radius)),
BorderPart::Corner(DVec2::new(left + arc_radius, top + arc_radius), PI),
];
let length = |part: &BorderPart| match part {
BorderPart::Line(from, to) => from.distance(*to),
BorderPart::Corner(..) => corner_length,
};
let point = |part: &BorderPart, fraction: f64| match *part {
BorderPart::Line(from, to) => from.lerp(to, fraction),
BorderPart::Corner(center, start_angle) => center + arc_radius * DVec2::from_angle(start_angle + fraction * FRAC_PI_2),
};
let starts: Vec<f64> = parts.iter().scan(0., |start, part| Some(std::mem::replace(start, *start + length(part)))).collect();
let perimeter: f64 = parts.iter().map(length).sum();
let mut left_out: Vec<[f64; 2]> = parts
.iter()
.zip(&starts)
.flat_map(|(part, &start)| {
let straight = matches!(part, BorderPart::Line(..));
let inside = gaps.iter().filter_map(move |&gap| fractions_inside(|fraction| point(part, fraction), straight, gap));
inside.map(move |[from, to]| [start + from * length(part), start + to * length(part)])
})
.collect();
left_out.sort_by(|a, b| a[0].total_cmp(&b[0]));
let shown = if dashed {
let [dash, gap] = BORDER_DASHES;
let length = perimeter.floor();
let fewer = (length / (dash + gap)).floor();
let gaps = [fewer, fewer + 1.].map(|count| (length - count * dash) / count);
let (count, gap) = if gaps[1] > 0. && (gaps[1] - gap).abs() <= (gaps[0] - gap).abs() {
(fewer + 1., gaps[1])
} else {
(fewer, gaps[0])
};
(0..count as usize).map(|index| [index as f64 * (dash + gap), index as f64 * (dash + gap) + dash]).collect()
} else {
vec![[0., perimeter]]
};
let visible = shown.into_iter().flat_map(|[mut from, to]| {
let mut pieces = Vec::new();
for &[gap_from, gap_to] in &left_out {
if gap_from < to && gap_to > from {
pieces.extend((gap_from > from).then_some([from, gap_from]));
from = from.max(gap_to);
}
}
pieces.extend((from < to).then_some([from, to]));
pieces
});
let mut border = BezPath::new();
for [from, to] in visible {
let mut started = false;
for (part, start) in parts.iter().zip(&starts) {
if length(part) == 0. {
continue;
}
let [a, b] = [from, to].map(|at| ((at - start) / length(part)).clamp(0., 1.));
if b <= a {
continue;
}
if !started {
border.move_to(<(f64, f64)>::from(point(part, a)));
started = true;
}
match *part {
BorderPart::Line(..) => border.line_to(<(f64, f64)>::from(point(part, b))),
BorderPart::Corner(center, start_angle) => {
border.extend(Arc::new(<(f64, f64)>::from(center), (arc_radius, arc_radius), start_angle + a * FRAC_PI_2, (b - a) * FRAC_PI_2, 0.).append_iter(ARC_TOLERANCE))
}
}
}
}
border
}
fn flattened_arc_length(radius: f64, [from, to]: [f64; 2]) -> f64 {
let point = |angle: f64| radius * DVec2::from_angle(angle);
let middle = (from + to) / 2.;
let bulge = point(middle) - (point(from) + point(to)) / 2.;
if bulge.abs().max_element() > MEASURE_TOLERANCE {
flattened_arc_length(radius, [from, middle]) + flattened_arc_length(radius, [middle, to])
} else {
point(from).distance(point(to))
}
}
fn fractions_inside(point: impl Fn(f64) -> DVec2, straight: bool, [low, high]: [DVec2; 2]) -> Option<[f64; 2]> {
let mut range = [0_f64, 1_f64];
for axis in 0..2 {
let value = |fraction: f64| point(fraction)[axis];
let [start, end] = [value(0.), value(1.)];
if start.min(end) > high[axis] || start.max(end) < low[axis] {
return None;
}
if start == end {
continue;
}
let fraction_at = |bound: f64| {
if (bound - start) * (end - start) <= 0. {
return 0.;
}
if (bound - end) * (end - start) >= 0. {
return 1.;
}
if straight {
return (bound - start) / (end - start);
}
let [mut before, mut after] = [0_f64, 1_f64];
for _ in 0..f64::MANTISSA_DIGITS {
let middle = (before + after) / 2.;
if (value(middle) - bound) * (end - start) < 0. {
before = middle;
} else {
after = middle;
}
}
after
};
let [a, b] = [fraction_at(low[axis]), fraction_at(high[axis])];
range = [range[0].max(a.min(b)), range[1].min(a.max(b))];
}
(range[0] < range[1]).then_some(range)
}
+90
View File
@@ -0,0 +1,90 @@
// TODO(Timon): Replace with generalized icon crate
use crate::card::DataType;
use crate::look::data_type_colors;
use crate::metrics::ICON_SIZE;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::color::SRGBA8;
use core_types::list::List;
use glam::DAffine2;
use graphic_types::{IntoGraphicList, Vector};
use std::collections::HashMap;
use std::fmt::Write;
use std::sync::{LazyLock, Mutex};
use svg_convert::Options;
#[derive(Clone)]
pub struct Icon {
pub(crate) shapes: List<Vector>,
pub(crate) overflows: bool,
}
type Converted = HashMap<SRGBA8, HashMap<String, Option<Icon>>>;
static CONVERTED: LazyLock<Mutex<Converted>> = LazyLock::new(Mutex::default);
pub fn icon(name: &str, current: SRGBA8) -> Option<Icon> {
let mut converted = CONVERTED.lock().unwrap();
let converted = converted.entry(current).or_default();
if let Some(icon) = converted.get(name) {
return icon.clone();
}
let icon = graph_ui_icons::svg(name).and_then(|svg| convert(svg, current));
converted.insert(name.to_string(), icon.clone());
icon
}
fn convert(svg: &str, current: SRGBA8) -> Option<Icon> {
let mut style_sheet = format!("svg {{ fill: {}; }}", hex_color(current));
for (class, _) in svg.split("class=\"").skip(1).filter_map(|rest| rest.split_once('"')) {
write!(style_sheet, " .{class} {{ fill: {}; }}", hex_color(class_color(class)?)).unwrap();
}
let options = Options {
style_sheet: Some(style_sheet),
..Options::default()
};
let shapes: List<Vector> = svg_convert::convert(svg, &options).ok()?.into_flattened_list();
let overflows = match shapes.bounding_box(DAffine2::IDENTITY, false) {
RenderBoundingBox::Rectangle([min, max]) => min.min_element() < 0. || max.max_element() > ICON_SIZE,
RenderBoundingBox::Infinite => true,
RenderBoundingBox::None => false,
};
Some(Icon { shapes, overflows })
}
fn hex_color(color: SRGBA8) -> String {
format!("#{:02x}{:02x}{:02x}", color.red, color.green, color.blue)
}
fn class_color(class: &str) -> Option<SRGBA8> {
let token = class.strip_prefix("color-")?;
let Some(mix) = token.strip_prefix("mix-") else { return token_color(token) };
let (pair, percent) = mix.rsplit_once('-')?;
let percent: u16 = percent.parse().ok().filter(|&percent| percent <= 100)?;
let (a, b) = pair.match_indices('-').find_map(|(index, _)| Some((token_color(&pair[..index])?, token_color(&pair[index + 1..])?)))?;
let mix = |a: u8, b: u8| ((u16::from(a) * (100 - percent) + u16::from(b) * percent + 50) / 100) as u8;
Some(SRGBA8::new_opaque(mix(a.red, b.red), mix(a.green, b.green), mix(a.blue, b.blue)))
}
fn token_color(token: &str) -> Option<SRGBA8> {
if let Some((digit, _)) = token.split_once('-').filter(|(digit, _)| digit.len() == 1) {
let value = u8::from_str_radix(digit, 16).ok()? * 0x11;
return Some(SRGBA8::new_opaque(value, value, value));
}
let (name, dim) = token.strip_suffix("-dim").map_or((token, false), |name| (name, true));
let data_type = match name {
"general" => DataType::General,
"number" => DataType::Number,
"artboard" => DataType::Artboard,
"graphic" => DataType::Graphic,
"raster" => DataType::Raster,
"vector" => DataType::Vector,
"color" => DataType::Color,
"gradient" => DataType::Gradient,
"typography" => DataType::Typography,
_ => return None,
};
let [bright, dimmed] = data_type_colors(data_type);
Some(if dim { dimmed } else { bright })
}
+12
View File
@@ -0,0 +1,12 @@
use graph_ui_types::inputs;
pub use graph_ui_types::{GraphUiConfig, card, dot, error_badge, geometry, highlights, layer, metrics, network_connector, placed, replicated_map, scene, wire};
pub use network::{network, render_config};
pub use text::{error_text_size, label_width};
mod dashes;
pub mod icons;
mod look;
mod network;
pub mod nodes;
pub mod router;
mod text;
+155
View File
@@ -0,0 +1,155 @@
use crate::card::{Connector, DataType};
use crate::highlights::Highlight;
use crate::icons;
use crate::metrics::{CHECKER_CELL, HOVERED_CONNECTOR_RING, HOVERED_CONNECTOR_SCALE, ICON_SIZE};
use core_types::Color;
use core_types::color::SRGBA8;
use core_types::list::{Item, List};
use core_types::transform::ApplyTransform;
use glam::{DAffine2, DVec2};
use graphic_types::{CoverPlacement, Coverage, Graphic, Vector, stamp_coverage};
use std::sync::LazyLock;
use vector_types::vector::algorithms::shapes::rounded_rectangle_bezpath;
use vector_types::vector::style::{Stroke, StrokeJoin};
use vello_gpu::kurbo::{Affine, BezPath, Rect, Shape};
pub(crate) const CARD_OPACITY: f32 = 0.33;
pub(crate) const GRID_DOT_OPACITY: f32 = 0.2;
pub(crate) const BACKDROP: SRGBA8 = SRGBA8::new_opaque(0x22, 0x22, 0x22);
pub(crate) const SELECTED_DOT_RING_OPACITY: f32 = 0.5;
pub(crate) const BORDER: SRGBA8 = SRGBA8::new_opaque(0x55, 0x55, 0x55);
pub(crate) const PREVIEWED_BORDER: SRGBA8 = SRGBA8::new_opaque(0xee, 0xee, 0xee);
pub(crate) const TEXT: SRGBA8 = SRGBA8::new_opaque(0xee, 0xee, 0xee);
pub(crate) const LAYER_IN_INACTIVE_SELECTION: SRGBA8 = SRGBA8::new_opaque(0x55, 0x55, 0x55);
pub(crate) const LAYER_IN_ACTIVE_SELECTION: SRGBA8 = SRGBA8::new_opaque(0x66, 0x66, 0x66);
pub(crate) const HIDDEN_CARD: SRGBA8 = SRGBA8::new_opaque(0x44, 0x44, 0x44);
pub(crate) const HIDDEN_TEXT: SRGBA8 = SRGBA8::new_opaque(0xaa, 0xaa, 0xaa);
pub(crate) const SEPARATOR: SRGBA8 = SRGBA8::new_opaque(0x88, 0x88, 0x88);
pub(crate) const HOVERED_BUTTON: SRGBA8 = SRGBA8::new_opaque(0x55, 0x55, 0x55);
pub(crate) const DISABLED_ICON: SRGBA8 = SRGBA8::new_opaque(0x88, 0x88, 0x88);
pub(crate) const BOX_SELECTION: SRGBA8 = SRGBA8::new_opaque(0x00, 0xa8, 0xff);
pub(crate) const BOX_SELECTION_FILL_OPACITY: f32 = 0.05;
pub(crate) const ERROR_RED: SRGBA8 = SRGBA8::new_opaque(0xd6, 0x53, 0x6e);
pub(crate) const ERROR_TEXT: SRGBA8 = SRGBA8::new_opaque(0x22, 0x22, 0x22);
pub(crate) const ERROR_OPACITY: f64 = 0.5;
pub(crate) const WIRE_SPLIT: SRGBA8 = SRGBA8::new_opaque(0x44, 0x44, 0x44);
pub(crate) const THUMBNAIL_BACKGROUND: SRGBA8 = SRGBA8::new_opaque(0x22, 0x22, 0x22);
const CHECKER_LIGHT: SRGBA8 = SRGBA8::new_opaque(0xff, 0xff, 0xff);
const CHECKER_DARK: SRGBA8 = SRGBA8::new_opaque(0xcc, 0xcc, 0xcc);
pub(crate) const CIRCLE_TOLERANCE: f64 = 1e-3;
pub(crate) static CONNECTOR_OUTLINE: LazyLock<BezPath> = LazyLock::new(|| parsed("M0,6.306A1.474,1.474,0,0,0,2.356,7.724L7.028,5.248c1.3-.687,1.3-1.809,0-2.5L2.356.276A1.474,1.474,0,0,0,0,1.694Z"));
pub(crate) static STACK_OUTPUT_OUTLINE: LazyLock<BezPath> = LazyLock::new(|| parsed("M0,6.953l2.521,-1.694a2.649,2.649,0,0,1,2.959,0l2.52,1.694v5.047h-8z"));
pub(crate) static STACK_INPUT_OUTLINE: LazyLock<BezPath> = LazyLock::new(|| parsed("M0,0H8V8L5.479,6.319a2.666,2.666,0,0,0-2.959,0L0,8Z"));
pub(crate) static STACK_OUTPUT_WIRE_END: LazyLock<BezPath> = LazyLock::new(|| {
parsed(
"M0,4.5 C0,4.5 0,-3.5 0,-3.5 C0,-3.5 3,-3.5 3,-3.5 C3,-3.5 3,2.565 3,2.565 C2.834,2.632 2.673,2.717 2.52,2.819 C2.52,2.819 0,4.5 0,4.5 Z\
M5,2.566 C5,2.566 5,-3.5 5,-3.5 C5,-3.5 8,-3.5 8,-3.5 C8,-3.5 8,4.5 8,4.5 C8,4.5 5.479,2.819 5.479,2.819 C5.326,2.717 5.166,2.633 5,2.566 Z",
)
});
pub(crate) static STACK_INPUT_WIRE_END: LazyLock<BezPath> = LazyLock::new(|| {
parsed(
"M2.512,9.26 C2.673,9.157 2.834,9.072 3,9 C3,9 3,16 3,16 C3,16 0,16 0,16 C0,16 0,10.95 0,10.95 C0,10.95 2.512,9.26 2.512,9.26 Z\
M5,16 C5,16 5,9 5,9 C5.166,9.073 5.327,9.158 5.48,9.26 C5.48,9.26 8,10.95 8,10.95 C8,10.95 8,16 8,16 C8,16 5,16 5,16 Z",
)
});
fn parsed(path_data: &str) -> BezPath {
BezPath::from_svg(path_data).expect("A connector outline is valid path data")
}
pub(crate) fn data_type_colors(data_type: DataType) -> [SRGBA8; 2] {
let colors = match data_type {
DataType::General => [0xcfcfcf, 0x8a8a8a],
DataType::Number => [0xc9a699, 0x886b60],
DataType::Artboard => [0xfbf9eb, 0xb9b9a9],
DataType::Graphic => [0x68c587, 0x37754c],
DataType::Raster => [0xe4bb72, 0x9a7b43],
DataType::Vector => [0x65bbe5, 0x417892],
DataType::Color => [0xce6ea7, 0x924071],
DataType::Gradient => [0xaf81eb, 0x6c489b],
DataType::Typography => [0xeea7a7, 0x955252],
DataType::Invalid => [0xd6536e, 0xa7324a],
};
colors.map(|color| {
let [_, red, green, blue] = u32::to_be_bytes(color);
SRGBA8::new_opaque(red, green, blue)
})
}
pub(crate) fn connector(outline: &BezPath, top_left: DVec2, connector: &Connector, highlight: Highlight) -> List<Vector> {
drawn_connector(outline, top_left, connector.data_type, connector.connected, highlight)
}
pub(crate) fn drawn_connector(outline: &BezPath, top_left: DVec2, data_type: DataType, connected: bool, highlight: Highlight) -> List<Vector> {
let [bright, dim] = data_type_colors(data_type);
match highlight {
Highlight::None => List::new_from_item(outlined(outline, top_left, if connected { bright } else { dim })),
Highlight::WireSource => List::new_from_item(outlined(outline, top_left, bright)),
Highlight::Hovered | Highlight::WireTarget => {
let grown = Affine::translate((top_left.x, top_left.y)) * Affine::scale_about(HOVERED_CONNECTOR_SCALE, outline.bounding_box().center()) * outline.clone();
let grown = Vector::item_from_bezpath(&grown);
let ring = Stroke {
join: StrokeJoin::Round,
..Stroke::new(HOVERED_CONNECTOR_RING * HOVERED_CONNECTOR_SCALE)
};
List::from_iter([painted(grown.clone(), Coverage::new_stroke(&ring), dim.into()), painted(grown, Coverage::new_fill(), bright.into())])
}
}
}
pub(crate) fn outlined(outline: &BezPath, top_left: DVec2, color: SRGBA8) -> Item<Vector> {
let mut outline = Vector::item_from_bezpath(outline);
outline.left_apply_transform(&DAffine2::from_translation(top_left));
painted(outline, Coverage::new_fill(), color.into())
}
pub(crate) fn rounded_rect(min: DVec2, max: DVec2, radii: [f64; 4]) -> Item<Vector> {
Vector::item_from_bezpath(&rounded_rectangle_bezpath(min, max, radii))
}
pub(crate) fn icon(name: &str, top_left: DVec2, current: SRGBA8) -> List<Vector> {
let Some(icon) = icons::icon(name, current) else { return List::new() };
let mut graphic = icon.shapes;
if icon.overflows {
let mut clip = rounded_rect(DVec2::ZERO, DVec2::splat(ICON_SIZE), [0.; 4]);
stamp_coverage(&mut clip, Coverage::new_fill(), Graphic::VectorList(graphic), CoverPlacement::Above);
graphic = List::new_from_item(clip);
}
graphic.left_apply_transform(&DAffine2::from_translation(top_left));
graphic
}
pub(crate) fn text(outline: &List<Vector>, top_left: DVec2, color: SRGBA8) -> List<Vector> {
let glyphs = outline.clone().into_iter();
let mut glyphs: List<Vector> = glyphs.map(|glyph| painted(glyph, Coverage::new_fill(), color.into())).collect();
glyphs.left_apply_transform(&DAffine2::from_translation(top_left));
glyphs
}
pub(crate) fn checkerboard(min: DVec2, max: DVec2) -> List<Vector> {
let mut dark = BezPath::new();
let cells = ((max - min) / CHECKER_CELL).ceil().as_uvec2();
for (column, row) in (0..cells.y)
.flat_map(|row| (0..cells.x).map(move |column| (column, row)))
.filter(|(column, row)| (column + row) % 2 == 1)
{
let cell_min = min + DVec2::new(column as f64, row as f64) * CHECKER_CELL;
let cell_max = (cell_min + CHECKER_CELL).min(max);
dark.extend(Rect::new(cell_min.x, cell_min.y, cell_max.x, cell_max.y).path_elements(0.));
}
let light = painted(rounded_rect(min, max, [0.; 4]), Coverage::new_fill(), CHECKER_LIGHT.into());
List::from_iter([light, painted(Vector::item_from_bezpath(&dark), Coverage::new_fill(), CHECKER_DARK.into())])
}
pub(crate) fn painted(mut item: Item<Vector>, coverage: Coverage, color: Color) -> Item<Vector> {
stamp_coverage(&mut item, coverage, Graphic::from(color), CoverPlacement::Above);
item
}
pub(crate) fn image(content: Graphic, unit_square_to_place: DAffine2) -> Item<Vector> {
let mut image = rounded_rect(DVec2::ZERO, DVec2::ONE, [0.; 4]);
image.left_apply_transform(&unit_square_to_place);
stamp_coverage(&mut image, Coverage::new_fill(), content, CoverPlacement::Above);
image
}
+155
View File
@@ -0,0 +1,155 @@
use crate::GraphUiConfig;
use crate::inputs::{self, TaggedGraphUiValue, Thumbnails};
use crate::nodes::{
draw_backdrop, draw_box_selection, draw_cards, draw_dots, draw_errors, draw_grid, draw_highlights, draw_layers, draw_loose_wires, draw_moving, draw_network_connectors, draw_raised,
draw_reorder_bar, draw_thick_wires, draw_thumbnails, draw_wires, texture_layer,
};
use crate::scene::GraphUiScene;
use core_types::registry::{FieldMetadata, NODE_METADATA, RegistryValueSource};
use core_types::transform::Footprint;
use core_types::{ContextFeatures, NodeCompileMetadata, ProtoNodeIdentifier};
use glam::DAffine2;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, DocumentNodeMetadata, NodeId, NodeInput, NodeNetwork};
use graphene_std::application_io::{ExportFormat, RenderConfig};
use graphene_std::graphic::extend;
use graphene_std::ops::passthrough;
use graphene_std::platform_application_io::wgpu_executor;
use graphene_std::render_cache::render_output_cache;
use graphene_std::render_node::{create_context, render, render_intermediate};
use std::sync::Arc;
pub fn network(scene: &GraphUiScene, config: &GraphUiConfig, thumbnails: &Thumbnails) -> NodeNetwork {
let layers = scene.settled().layers.iter().chain(&scene.moving().layers);
let layer_thumbnails = layers.filter_map(|layer| Some((layer.look.key, thumbnails.get(&layer.look.key)?.clone())));
let values = [
(inputs::SETTLED, TaggedGraphUiValue::Rows(scene.settled().clone())),
(inputs::MOVING, TaggedGraphUiValue::Rows(scene.moving().clone())),
(inputs::NETWORK_CONNECTORS, TaggedGraphUiValue::NetworkConnectors(scene.network_connectors().clone())),
(inputs::ERRORS, TaggedGraphUiValue::Errors(scene.errors().clone())),
(inputs::THUMBNAILS, TaggedGraphUiValue::Thumbnails(Arc::new(layer_thumbnails.collect()))),
(inputs::WIRE_IN_PROGRESS, TaggedGraphUiValue::WireInProgress(config.wire_in_progress)),
(inputs::REORDER_BAR, TaggedGraphUiValue::ReorderBar(config.reorder_bar)),
(inputs::BOX_SELECTION, TaggedGraphUiValue::BoxSelection(config.box_selection)),
(inputs::FADE_ARTWORK, TaggedGraphUiValue::FadeArtwork(config.fade_artwork)),
(inputs::WIRE_STYLE, TaggedGraphUiValue::WireStyle(config.wire_style)),
(inputs::HIGHLIGHTS, TaggedGraphUiValue::Highlights(config.highlights)),
];
let mut network = NodeNetwork::default();
for (scope, value) in values {
let ty = value.ty();
let id = add(&mut network, node(passthrough::IDENTIFIER, vec![NodeInput::value(TaggedValue::GraphUi(value), false)]));
network.scope_injections.insert(scope.as_str().to_string(), (id, ty));
}
let [backdrop, above @ ..] = [
drawn(&mut network, draw_backdrop::IDENTIFIER),
drawn(&mut network, draw_grid::IDENTIFIER),
tiled(&mut network, draw_thick_wires::IDENTIFIER, [draw_layers::IDENTIFIER]),
drawn(&mut network, draw_thumbnails::IDENTIFIER),
drawn(&mut network, draw_loose_wires::IDENTIFIER),
tiled(&mut network, draw_wires::IDENTIFIER, [draw_cards::IDENTIFIER, draw_dots::IDENTIFIER, draw_raised::IDENTIFIER]),
drawn(&mut network, draw_moving::IDENTIFIER),
drawn(&mut network, draw_errors::IDENTIFIER),
drawn(&mut network, draw_network_connectors::IDENTIFIER),
drawn(&mut network, draw_highlights::IDENTIFIER),
drawn(&mut network, draw_reorder_bar::IDENTIFIER),
drawn(&mut network, draw_box_selection::IDENTIFIER),
];
let stack = stacked(&mut network, backdrop, above);
let frame = rendered(&mut network, stack);
// INDEX is never read; it forces a nullification and cache pair onto the render's wire, so its memo keys on the footprint and the render params only
let compile_metadata = Some(NodeCompileMetadata {
extract: ContextFeatures::VARARGS | ContextFeatures::INDEX,
inject: ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
..Default::default()
});
let create_context = DocumentNode {
compile_metadata,
..node(create_context::IDENTIFIER, vec![NodeInput::node(frame, 0)])
};
let output = add(&mut network, create_context);
network.exports.push(NodeInput::node(output, 0));
network
}
pub fn render_config(view: DAffine2, request: RenderConfig) -> RenderConfig {
let translation = (view.translation * request.scale).round() / request.scale;
let viewport = Footprint {
transform: DAffine2 { translation, ..view },
resolution: request.viewport.resolution,
..Default::default()
};
RenderConfig {
viewport,
scale: request.scale,
time: request.time,
export_format: ExportFormat::Raster,
..Default::default()
}
}
fn node(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> DocumentNode {
DocumentNode {
implementation: DocumentNodeImplementation::ProtoNode(identifier),
inputs,
..Default::default()
}
}
fn add(network: &mut NodeNetwork, node: DocumentNode) -> NodeId {
let id = NodeId(u64::MAX - network.nodes.len() as u64);
network.nodes.insert(id, node);
id
}
fn drawn(network: &mut NodeNetwork, identifier: ProtoNodeIdentifier) -> NodeId {
let scope = |field: &FieldMetadata| match &field.value_source {
RegistryValueSource::Scope(scope) => Ok(NodeInput::scope(*scope)),
source => Err(format!("The parameter {} of the drawing node {identifier} of the node graph reads {source:?}, not a scope", field.name)),
};
let scopes = NODE_METADATA
.lock()
.unwrap()
.get(&identifier)
.map(|metadata| metadata.fields.iter().map(scope).collect::<Result<Vec<_>, _>>());
let scopes = scopes.unwrap_or_else(|| panic!("The drawing node {identifier} of the node graph is not registered"));
let scopes = scopes.unwrap_or_else(|not_a_scope| panic!("{not_a_scope}"));
add(network, node(identifier, scopes))
}
fn stacked(network: &mut NodeNetwork, bottom: NodeId, above: impl IntoIterator<Item = NodeId>) -> NodeId {
let over = |below, layer| add(network, node(extend::IDENTIFIER, vec![NodeInput::node(below, 0), NodeInput::node(layer, 0)]));
above.into_iter().fold(bottom, over)
}
fn rendered(network: &mut NodeNetwork, content: NodeId) -> NodeId {
let intermediate = add(network, node(render_intermediate::IDENTIFIER, vec![NodeInput::node(content, 0)]));
let inputs = vec![
NodeInput::node(intermediate, 0),
NodeInput::scope(wgpu_executor::IDENTIFIER),
NodeInput::scope("runtime"),
NodeInput::Reflection(DocumentNodeMetadata::SourceId),
];
add(network, node(render::IDENTIFIER, inputs))
}
fn tiled(network: &mut NodeNetwork, first: ProtoNodeIdentifier, rest: impl IntoIterator<Item = ProtoNodeIdentifier>) -> NodeId {
let bottom = drawn(network, first);
let above: Vec<NodeId> = rest.into_iter().map(|identifier| drawn(network, identifier)).collect();
let bands = stacked(network, bottom, above);
let region = rendered(network, bands);
// The cache's signature names the time and the pointer, which would put both into its key; it reads only the footprint and the render params
let compile_metadata = Some(NodeCompileMetadata {
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
inject: ContextFeatures::VARARGS,
..Default::default()
});
let cache = DocumentNode {
compile_metadata,
..node(render_output_cache::IDENTIFIER, vec![NodeInput::node(region, 0), NodeInput::scope(wgpu_executor::IDENTIFIER)])
};
let cached = add(network, cache);
add(network, node(texture_layer::IDENTIFIER, vec![NodeInput::node(cached, 0)]))
}
+627
View File
@@ -0,0 +1,627 @@
use crate::card::{Card, Connector, DataType, Selection};
use crate::dashes::{border, dashed};
use crate::dot::Dot;
use crate::error_badge::{self, ErrorBadge};
use crate::geometry::{WireEnd, is_thick_wire, node_geometry, wire_ends};
use crate::highlights::{ConnectorKey, Highlight, Highlights};
use crate::inputs::{self, Thumbnails};
use crate::layer::{Layer, LayerButton};
use crate::look::{
BACKDROP, BORDER, BOX_SELECTION, BOX_SELECTION_FILL_OPACITY, CARD_OPACITY, CIRCLE_TOLERANCE, CONNECTOR_OUTLINE, DISABLED_ICON, ERROR_OPACITY, ERROR_RED, ERROR_TEXT, GRID_DOT_OPACITY, HIDDEN_CARD,
HIDDEN_TEXT, HOVERED_BUTTON, LAYER_IN_ACTIVE_SELECTION, LAYER_IN_INACTIVE_SELECTION, PREVIEWED_BORDER, SELECTED_DOT_RING_OPACITY, SEPARATOR, STACK_INPUT_OUTLINE, STACK_INPUT_WIRE_END,
STACK_OUTPUT_OUTLINE, STACK_OUTPUT_WIRE_END, TEXT, THUMBNAIL_BACKGROUND, WIRE_SPLIT, checkerboard, connector, data_type_colors, drawn_connector, icon, image, outlined, painted, rounded_rect,
text,
};
use crate::metrics::{
BORDER_WIDTH, CARD_ICON_LEFT, CARD_NAME_LEFT, CARD_NAME_MAX_WIDTH, CARD_RADIUS, CARD_ROW_PADDING, CONNECTOR_GAP, CONNECTOR_SIZE, DOT_HOVERED_RING, DOT_OUTPUT_ARROW, DOT_PREVIEWED_RING_OFFSET,
DOT_RADIUS, DOT_SELECTED_RING, ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH, ERROR_RADIUS, GRID_COLLAPSE_SPACING, GRID_SIZE, HOVERED_CONNECTOR_SCALE, ICON_SIZE, LAYER_BUTTON_RADIUS, LAYER_BUTTON_SIZE,
LAYER_GRIP_DOT_COUNT, LAYER_GRIP_DOT_RADIUS, LAYER_GRIP_DOT_SPACING, LAYER_GRIP_DOTS, LAYER_RADIUS, LAYER_THUMBNAIL_GAP, LAYER_THUMBNAIL_RADIUS, LIST_WIRE_WIDTH, THICK_WIRE_WIDTH, WIRE_DASHES,
WIRE_WIDTH,
};
use crate::network_connector::{self, NetworkConnector, NetworkConnectorKey, NetworkConnectorKind};
use crate::placed::Placed;
use crate::replicated_map::ReplicatedMap;
use crate::router::{build_thick_wire_center_line, route};
use crate::scene::Rows;
use crate::text::{Labels, error_text_size, paragraph_outline};
use crate::wire::{InputKey, OutputKey, Wire, WireInProgress, WireKey, WireStyle};
use core_types::color::SRGBA8;
use core_types::list::{ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPREAD, ATTR_OPACITY, Item, List};
use core_types::transform::ApplyTransform;
use core_types::{Color, Ctx, ExtractFootprint, ExtractVarArgs, Poll};
use glam::{DAffine2, DVec2};
use graph_craft::document::value::{RenderOutput, RenderOutputType};
use graphic_types::raster_types::Raster;
use graphic_types::{CoverPlacement, Coverage, Graphic, Vector, stamp_coverage};
use rendering::RenderParams;
use std::collections::{BTreeMap, BTreeSet};
use text_nodes::TextToVectorError;
use vector_types::vector::style::Stroke;
use vector_types::{Gradient, GradientInterpolation, GradientSpread, GradientStop};
use vello_gpu::kurbo::{BezPath, Circle, Rect, Shape, flatten};
const GRID_DOT_ROUNDING_BIAS: f64 = 1. / 64.;
const WIRE_FLATTENING_TOLERANCE: f64 = 0.02;
#[node_macro::node(transient)]
fn draw_backdrop(ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, #[scope(inputs::FADE_ARTWORK)] fade_artwork: Item<f64>) -> List<Vector> {
let (view, scale) = view_and_device_scale(&ctx);
let viewport_size = ctx.footprint().resolution.as_dvec2() / scale;
let opacity = fade_artwork.into_element() as f32;
let mut backdrop = painted(rounded_rect(DVec2::ZERO, viewport_size, [0.; 4]), Coverage::new_fill(), Color::from(BACKDROP).with_alpha(opacity));
backdrop.left_apply_transform(&view.inverse());
List::new_from_item(backdrop)
}
fn view_and_device_scale(ctx: &(impl ExtractFootprint + ExtractVarArgs)) -> (DAffine2, f64) {
let render_params: Option<&RenderParams> = ctx.vararg(0).ok().and_then(|render_params| render_params.downcast_ref());
let scale = render_params.expect("The render params are the first vararg").scale;
(DAffine2::from_scale(DVec2::splat(1. / scale)) * ctx.footprint().transform, scale)
}
#[node_macro::node(transient)]
fn draw_grid(ctx: impl Ctx + ExtractFootprint + ExtractVarArgs) -> List<Vector> {
let (view, scale) = view_and_device_scale(&ctx);
let viewport_size = ctx.footprint().resolution.as_dvec2() / scale;
let mut dots = grid_dots(view, viewport_size, scale);
dots.left_apply_transform(&view.inverse());
dots
}
fn grid_dots(view: DAffine2, viewport_size: DVec2, scale: f64) -> List<Vector> {
let zoom = view.matrix2.x_axis.length();
let mut spacing = zoom * GRID_SIZE;
if !spacing.is_finite() || spacing <= 0. {
return List::new();
}
while spacing < GRID_COLLAPSE_SPACING {
spacing *= 2.;
}
let radius = ((1. + (zoom - 0.5 + 0.001).floor() / 2.) * scale).ceil() as u32;
let period = spacing * scale;
let origin = (view.translation * scale - radius as f64).rem_euclid(DVec2::splat(period)) - period - GRID_DOT_ROUNDING_BIAS;
let dot_color = Color::WHITE.with_alpha(GRID_DOT_OPACITY);
let stop = |column: u32, color| GradientStop {
position: column as f64 / period,
midpoint: 0.5,
color,
};
let mut dots = List::new();
for ([top, bottom], runs) in disc_columns(radius) {
let mut bands = BezPath::new();
for row in 0..=((viewport_size.y * scale - origin.y) / period).ceil() as u32 {
let y = (origin.y + row as f64 * period).round();
bands.extend(Rect::new(0., (y + top as f64) / scale, viewport_size.x, (y + bottom as f64) / scale).path_elements(0.));
}
let start = runs[0][0];
let stops = runs.iter().flat_map(|&[left, right]| [stop(left - start, dot_color), stop(right - start, Color::TRANSPARENT)]);
let mut columns = Item::new_from_element(Gradient::new(stops));
columns.set_attribute(ATTR_GRADIENT_SPREAD, GradientSpread::Repeat);
columns.set_attribute(ATTR_GRADIENT_INTERPOLATION, GradientInterpolation::Stepped);
columns.left_apply_transform(&DAffine2::from_scale_angle_translation(DVec2::splat(spacing), 0., DVec2::new((origin.x + start as f64) / scale, 0.)));
let mut group = Vector::item_from_bezpath(&bands);
stamp_coverage(&mut group, Coverage::new_fill(), Graphic::Gradient(columns), CoverPlacement::Above);
dots.push(group);
}
dots
}
fn disc_columns(radius: u32) -> BTreeMap<[u32; 2], Vec<[u32; 2]>> {
let lit = |column: u32, row: u32| (DVec2::new(column as f64, row as f64) + 0.5 - radius as f64).length() < radius as f64;
let mut runs_by_rows = BTreeMap::<[u32; 2], Vec<[u32; 2]>>::new();
for column in 0..2 * radius {
let top = (0..radius).take_while(|&row| !lit(column, row)).count() as u32;
let runs = runs_by_rows.entry([top, 2 * radius - top]).or_default();
match runs.last_mut() {
Some(run) if run[1] == column => run[1] += 1,
_ => runs.push([column, column + 1]),
}
}
runs_by_rows
}
#[node_macro::node(transient, memoize)]
fn draw_layers(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item<Rows>) -> Result<List<Vector>, TextToVectorError> {
layers(rows.element())
}
fn layers(rows: &Rows) -> Result<List<Vector>, TextToVectorError> {
let mut labels = Labels::default();
let mut graphic = List::new();
for layer in &rows.layers {
graphic.extend(draw_layer(layer, &mut labels)?);
}
Ok(graphic)
}
fn draw_layer(layer: &Placed<Layer>, labels: &mut Labels) -> Result<List<Vector>, TextToVectorError> {
let mut graphic = List::new();
let [min, max] = layer.body();
let fill = match (layer.look.selection, layer.look.visible) {
(Selection::Active, _) => LAYER_IN_ACTIVE_SELECTION.into(),
(Selection::Inactive, _) => LAYER_IN_INACTIVE_SELECTION.into(),
(Selection::None, true) => Color::BLACK,
(Selection::None, false) => HIDDEN_CARD.into(),
};
graphic.push(painted(rounded_rect(min, max, [LAYER_RADIUS; 4]), Coverage::new_fill(), fill.with_alpha(CARD_OPACITY)));
if !layer.look.renaming {
let [name, name_end] = layer.name_box();
let text_color = if layer.look.visible { TEXT } else { HIDDEN_TEXT };
graphic.extend(text(&labels.label(&layer.look.name, name_end.x - name.x)?.outline, name, text_color));
}
let [thumbnail_min, thumbnail_max] = layer.thumbnail();
let thumbnail = rounded_rect(thumbnail_min, thumbnail_max, [LAYER_THUMBNAIL_RADIUS; 4]);
graphic.push(painted(thumbnail, Coverage::new_fill(), THUMBNAIL_BACKGROUND.into()));
let thumbnail_border = Vector::item_from_bezpath(&border(thumbnail_min, thumbnail_max, LAYER_THUMBNAIL_RADIUS, &[], false));
graphic.push(painted(thumbnail_border, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), BORDER.into()));
let [image_min, image_max] = layer.thumbnail_image();
graphic.extend(checkerboard(image_min, image_max));
if let Some(output) = &layer.look.primary_output {
graphic.extend(stack_output(layer, output, Highlight::None));
}
match &layer.look.primary_input {
Some(input) => graphic.extend(stack_input(layer, input, Highlight::None)),
None => graphic.push(outlined(&STACK_INPUT_OUTLINE, layer.stack_input(), data_type_colors(DataType::General)[1])),
}
let [block_min, block_max] = layer.thumbnail_block();
let mut gaps = vec![[block_min - LAYER_THUMBNAIL_GAP, block_max + LAYER_THUMBNAIL_GAP], layer.visibility()];
gaps.extend(layer.left_input_wire().map(|wire| [wire - CONNECTOR_GAP / 2., wire + CONNECTOR_GAP / 2.]));
let border = Vector::item_from_bezpath(&border(min, max, LAYER_RADIUS, &gaps, layer.look.previewed));
let border_color = if layer.look.previewed { PREVIEWED_BORDER } else { BORDER };
graphic.push(painted(border, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), border_color.into()));
Ok(graphic)
}
fn stack_output(layer: &Placed<Layer>, output: &Connector, highlight: Highlight) -> List<Vector> {
let mut graphic = connector(&STACK_OUTPUT_OUTLINE, layer.stack_output(), output, highlight);
if output.connected && layer.look.primary_output_connected_to_layer && highlight != Highlight::WireSource {
graphic.push(outlined(&STACK_OUTPUT_WIRE_END, layer.stack_output(), data_type_colors(output.data_type)[1]));
}
graphic
}
fn stack_input(layer: &Placed<Layer>, input: &Connector, highlight: Highlight) -> List<Vector> {
let mut graphic = connector(&STACK_INPUT_OUTLINE, layer.stack_input(), input, highlight);
if input.connected && layer.look.primary_input_connected_to_layer && highlight != Highlight::WireSource {
graphic.push(outlined(&STACK_INPUT_WIRE_END, layer.stack_input(), data_type_colors(input.data_type)[1]));
}
graphic
}
#[node_macro::node(transient)]
fn draw_thumbnails(_: impl Ctx, #[scope(inputs::THUMBNAILS)] thumbnails: Item<Thumbnails>, #[scope(inputs::SETTLED)] rows: Item<Rows>) -> List<Vector> {
layer_thumbnails(thumbnails.element(), rows.element())
}
fn layer_thumbnails(thumbnails: &Thumbnails, rows: &Rows) -> List<Vector> {
let thumbnails = thumbnails.iter().filter_map(|(key, thumbnail)| Some((rows.layers.get(key)?, thumbnail)));
thumbnails
.map(|(layer, thumbnail)| {
let [min, max] = layer.thumbnail_image();
image(thumbnail.clone(), DAffine2::from_scale_angle_translation(max - min, 0., min))
})
.collect()
}
#[node_macro::node(transient)]
fn texture_layer(ctx: impl Ctx + ExtractFootprint, rendered: Item<RenderOutput>) -> Poll<List<Vector>> {
let RenderOutputType::Texture(texture) = rendered.into_element().data else {
return Poll::error("A layer of the node graph was not rendered into a texture");
};
let footprint = ctx.footprint();
let viewport = footprint.transform.inverse() * DAffine2::from_scale(footprint.resolution.as_dvec2());
let texture = Graphic::RasterGPU(Item::new_from_element(Raster::new_gpu(texture)));
Poll::Final(List::new_from_item(image(texture, viewport)))
}
#[node_macro::node(transient, memoize)]
fn draw_raised(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item<Rows>) -> List<Vector> {
raised(rows.element())
}
fn raised(rows: &Rows) -> List<Vector> {
let raised_parts_of_layers = rows.layers.iter().flat_map(draw_raised_parts_of_layer);
raised_parts_of_layers.chain(rows.cards.iter().flat_map(draw_connectors_of_card)).collect()
}
fn draw_raised_parts_of_layer(layer: &Placed<Layer>) -> List<Vector> {
let mut graphic = List::new();
if let Some(input) = &layer.look.secondary_input {
graphic.extend(connector(&CONNECTOR_OUTLINE, layer.secondary_input_connector(), input, Highlight::None));
}
graphic.extend(grip(layer, false));
for (_, place, icons) in layer_buttons(layer) {
graphic.extend(layer_button(layer, place, icons, false, false));
}
graphic
}
fn grip(layer: &Placed<Layer>, hovered: bool) -> List<Vector> {
let grip_color = match (hovered, layer.look.selection != Selection::None) {
(true, _) => Some(Color::WHITE),
(false, true) => Some(TEXT.into()),
(false, false) => None,
};
let Some(grip_color) = grip_color else { return List::new() };
let [grip, _] = layer.grip();
let mut dots = BezPath::new();
let [columns, rows] = LAYER_GRIP_DOT_COUNT;
for (column, row) in (0..rows).flat_map(|row| (0..columns).map(move |column| (column, row))) {
let center = grip + LAYER_GRIP_DOTS + DVec2::new(column as f64, row as f64) * LAYER_GRIP_DOT_SPACING;
dots.extend(Circle::new((center.x, center.y), LAYER_GRIP_DOT_RADIUS).path_elements(CIRCLE_TOLERANCE));
}
List::new_from_item(painted(Vector::item_from_bezpath(&dots), Coverage::new_fill(), grip_color))
}
fn layer_buttons(layer: &Placed<Layer>) -> impl Iterator<Item = (LayerButton, [DVec2; 2], [&'static str; 2])> {
let lock = layer.lock().map(|lock| (LayerButton::Lock, lock, ["PadlockLocked", "PadlockUnlocked"]));
let eye = if layer.look.visible { ["EyeVisible", "EyeHide"] } else { ["EyeHidden", "EyeShow"] };
lock.into_iter().chain([(LayerButton::Visibility, layer.visibility(), eye)])
}
fn layer_button(layer: &Placed<Layer>, [min, max]: [DVec2; 2], [resting, hover]: [&str; 2], hovered: bool, clicked: bool) -> List<Vector> {
let mut graphic = List::new();
if hovered {
graphic.push(painted(rounded_rect(min, max, [LAYER_BUTTON_RADIUS; 4]), Coverage::new_fill(), HOVERED_BUTTON.into()));
}
let name = if hovered && !clicked { hover } else { resting };
graphic.extend(icon(name, min + (LAYER_BUTTON_SIZE - ICON_SIZE) / 2., if layer.look.read_only { DISABLED_ICON } else { TEXT }));
graphic
}
fn draw_connectors_of_card(card: &Placed<Card>) -> List<Vector> {
card.inputs()
.chain(card.outputs())
.flat_map(|(top_left, input_or_output)| connector(&CONNECTOR_OUTLINE, top_left, input_or_output, Highlight::None))
.collect()
}
#[node_macro::node(transient, memoize)]
fn draw_thick_wires(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item<Rows>, #[scope(inputs::WIRE_STYLE)] wire_style: Item<WireStyle>) -> List<Vector> {
settled_wires(rows.element(), wire_style.into_element(), true)
}
#[node_macro::node(transient, memoize)]
fn draw_wires(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item<Rows>, #[scope(inputs::WIRE_STYLE)] wire_style: Item<WireStyle>) -> List<Vector> {
settled_wires(rows.element(), wire_style.into_element(), false)
}
fn settled_wires(rows: &Rows, wire_style: WireStyle, thick: bool) -> List<Vector> {
let settled = [rows];
let no_imports_or_exports = ReplicatedMap::default();
let wires = wires_with_ends(&rows.wires, &settled, &no_imports_or_exports).filter(|(_, ends)| is_thick_wire(*ends) == thick);
wires.flat_map(|(wire, ends)| draw_wire(wire, ends, wire_style)).collect()
}
#[node_macro::node(transient, memoize)]
fn draw_loose_wires(
_: impl Ctx,
#[scope(inputs::MOVING)] moving: Item<Rows>,
#[scope(inputs::SETTLED)] settled: Item<Rows>,
#[scope(inputs::NETWORK_CONNECTORS)] network_connectors: Item<ReplicatedMap<NetworkConnector>>,
#[scope(inputs::WIRE_IN_PROGRESS)] wire_in_progress: Item<Option<WireInProgress>>,
#[scope(inputs::WIRE_STYLE)] wire_style: Item<WireStyle>,
) -> List<Vector> {
let wire_style = wire_style.into_element();
let rows = [moving.element(), settled.element()];
let loose = wires_with_ends(&moving.element().wires, &rows, network_connectors.element());
let mut graphic = wire_in_progress.into_element().map_or_else(List::new, draw_wire_in_progress);
graphic.extend(loose.flat_map(|(wire, ends)| draw_wire(wire, ends, wire_style)).collect());
graphic
}
fn wires_with_ends<'a>(wires: &'a ReplicatedMap<Wire>, rows: &'a [&'a Rows], network_connectors: &'a ReplicatedMap<NetworkConnector>) -> impl Iterator<Item = (&'a Wire, [WireEnd; 2])> {
wires.iter().filter_map(move |wire| Some((wire, wire_ends(wire, rows, network_connectors)?)))
}
fn draw_wire(wire: &Wire, ends: [WireEnd; 2], wire_style: WireStyle) -> List<Vector> {
let [bright, dim] = data_type_colors(wire.data_type);
let previewed = wire.key == WireKey::Preview;
let color = if previewed || wire.insertion_target { bright } else { dim };
let stroke = |path: &BezPath, width: f64, color: SRGBA8| painted(Vector::item_from_bezpath(path), Coverage::new_stroke(&Stroke::new(width)), color.into());
let drawn = |path: &BezPath| if previewed { flattened(&dashed(path, WIRE_DASHES)) } else { flattened(path) };
let path = drawn(&route(ends, wire_style));
if is_thick_wire(ends) {
let center_line = build_thick_wire_center_line(ends, wire_style);
List::from_iter([stroke(&path, THICK_WIRE_WIDTH, color), stroke(&drawn(&center_line), WIRE_WIDTH, WIRE_SPLIT)])
} else if wire.list {
List::from_iter([stroke(&path, LIST_WIRE_WIDTH, color), stroke(&path, WIRE_WIDTH, WIRE_SPLIT)])
} else {
List::new_from_item(stroke(&path, WIRE_WIDTH, color))
}
}
fn draw_wire_in_progress(wire: WireInProgress) -> List<Vector> {
let path = route(wire.ends, WireStyle::Direct);
if path.elements().len() != 4 {
return List::new();
}
let [_, dim] = data_type_colors(wire.data_type);
let path = flattened(&path);
List::new_from_item(painted(Vector::item_from_bezpath(&path), Coverage::new_stroke(&Stroke::new(WIRE_WIDTH)), dim.into()))
}
fn flattened(path: &BezPath) -> BezPath {
let mut lines = BezPath::new();
flatten(path, WIRE_FLATTENING_TOLERANCE, |element| lines.push(element));
lines
}
#[node_macro::node(transient, memoize)]
fn draw_cards(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item<Rows>) -> Result<List<Vector>, TextToVectorError> {
cards(rows.element())
}
fn cards(rows: &Rows) -> Result<List<Vector>, TextToVectorError> {
let mut labels = Labels::default();
let mut graphic = List::new();
for card in &rows.cards {
graphic.extend(draw_card(card, &mut labels)?);
}
Ok(graphic)
}
fn draw_card(card: &Placed<Card>, labels: &mut Labels) -> Result<List<Vector>, TextToVectorError> {
let mut graphic = List::new();
let [min, max] = card.body();
let (card_color, text_color) = if card.look.visible { (Color::BLACK, TEXT) } else { (HIDDEN_CARD.into(), HIDDEN_TEXT) };
let body = rounded_rect(min, max, [CARD_RADIUS; 4]);
graphic.push(painted(body, Coverage::new_fill(), card_color.with_alpha(CARD_OPACITY)));
let (header_tint, rows_tint) = match card.look.selection {
Selection::None => (0.05, 0.),
Selection::Inactive => (0.15, 0.1),
Selection::Active => (0.2, 0.15),
};
let header_bottom = if card.rows() == 1 { CARD_RADIUS } else { 0. };
let header = rounded_rect(min, DVec2::new(max.x, min.y + GRID_SIZE), [CARD_RADIUS, CARD_RADIUS, header_bottom, header_bottom]);
graphic.push(painted(header, Coverage::new_fill(), Color::WHITE.with_alpha(header_tint)));
if card.look.selection != Selection::None && card.rows() > 1 {
let rows = rounded_rect(DVec2::new(min.x, min.y + GRID_SIZE), max, [0., 0., CARD_RADIUS, CARD_RADIUS]);
graphic.push(painted(rows, Coverage::new_fill(), Color::WHITE.with_alpha(rows_tint)));
}
graphic.extend(icon(card.look.icon, min + DVec2::new(CARD_ICON_LEFT, (GRID_SIZE - ICON_SIZE) / 2.), text_color));
let name = labels.label(&card.look.name, CARD_NAME_MAX_WIDTH)?;
graphic.extend(text(&name.outline, min + DVec2::new(CARD_NAME_LEFT, 0.), text_color));
let width = max.x - min.x;
for row in 1..card.rows() as usize {
let (input, output) = (card.look.secondary_inputs.get(row - 1), card.look.secondary_outputs.get(row - 1));
let Some(connector) = input.or(output) else { continue };
let name = labels.label(&connector.name, width - 2. * CARD_ROW_PADDING)?;
let left = if input.is_some() { CARD_ROW_PADDING } else { width - CARD_ROW_PADDING - name.width };
graphic.extend(text(&name.outline, min + DVec2::new(left, row as f64 * GRID_SIZE), text_color));
}
let border_color = if card.look.previewed { PREVIEWED_BORDER } else { BORDER };
let gap = |edge: f64, (top_left, _): (DVec2, &Connector)| {
let center = DVec2::new(edge, top_left.y + CONNECTOR_SIZE / 2.);
[center - CONNECTOR_GAP / 2., center + CONNECTOR_GAP / 2.]
};
let gaps: Vec<[DVec2; 2]> = card.inputs().map(|input| gap(min.x, input)).chain(card.outputs().map(|output| gap(max.x, output))).collect();
let border = Vector::item_from_bezpath(&border(min, max, CARD_RADIUS, &gaps, card.look.previewed));
graphic.push(painted(border, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), border_color.into()));
Ok(graphic)
}
#[node_macro::node(transient, memoize)]
fn draw_dots(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item<Rows>) -> List<Vector> {
dots(rows.element())
}
fn dots(rows: &Rows) -> List<Vector> {
rows.dots.iter().flat_map(|dot| draw_dot(dot, [Highlight::None; 2])).collect()
}
#[node_macro::node(transient, memoize)]
fn draw_moving(_: impl Ctx, #[scope(inputs::MOVING)] moving: Item<Rows>, #[scope(inputs::THUMBNAILS)] thumbnails: Item<Thumbnails>) -> Result<List<Vector>, TextToVectorError> {
let moving = moving.element();
let mut graphic = layers(moving)?;
graphic.extend(layer_thumbnails(thumbnails.element(), moving));
graphic.extend(cards(moving)?);
graphic.extend(dots(moving));
graphic.extend(raised(moving));
Ok(graphic)
}
fn draw_dot(dot: &Placed<Dot>, [highlight, output_highlight]: [Highlight; 2]) -> List<Vector> {
let [wired, unwired] = data_type_colors(dot.look.data_type);
let center = dot.center();
let grown = matches!(highlight, Highlight::Hovered | Highlight::WireTarget);
let scale = if grown { HOVERED_CONNECTOR_SCALE } else { 1. };
let circle = |radius: f64| Vector::item_from_bezpath(&Circle::new((center.x, center.y), radius * scale).to_path(CIRCLE_TOLERANCE));
let output_shown = output_highlight != Highlight::None;
let fill = if dot.look.wired && !output_shown { wired } else { unwired };
let mut graphic = List::new_from_item(painted(circle(DOT_RADIUS), Coverage::new_fill(), fill.into()));
let resting = [highlight, output_highlight] == [Highlight::None; 2];
if grown {
let offset = if dot.look.previewed { DOT_PREVIEWED_RING_OFFSET } else { 0. };
let ring = circle(DOT_RADIUS + offset + DOT_HOVERED_RING / 2.);
graphic.push(painted(ring, Coverage::new_stroke(&Stroke::new(DOT_HOVERED_RING * scale)), unwired.into()));
} else if resting && dot.look.previewed {
let radius = DOT_RADIUS + DOT_PREVIEWED_RING_OFFSET + BORDER_WIDTH;
let ring = Vector::item_from_bezpath(&border(center - radius, center + radius, radius, &[], true));
graphic.push(painted(ring, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), wired.into()));
} else if resting && dot.look.selected {
let ring = circle(DOT_RADIUS + DOT_SELECTED_RING / 2.);
graphic.push(painted(ring, Coverage::new_stroke(&Stroke::new(DOT_SELECTED_RING)), Color::WHITE.with_alpha(SELECTED_DOT_RING_OPACITY)));
}
if output_shown {
graphic.extend(drawn_connector(&CONNECTOR_OUTLINE, center + DOT_OUTPUT_ARROW, dot.look.data_type, true, output_highlight));
}
graphic
}
#[node_macro::node(transient, memoize)]
fn draw_errors(
_: impl Ctx,
#[scope(inputs::ERRORS)] errors: Item<ReplicatedMap<ErrorBadge>>,
#[scope(inputs::MOVING)] moving: Item<Rows>,
#[scope(inputs::SETTLED)] settled: Item<Rows>,
) -> Result<List<Vector>, TextToVectorError> {
let rows = [moving.element(), settled.element()];
badges_with_anchors(errors.element().iter(), rows).map(|(error, anchor)| draw_error(error, anchor, false)).collect()
}
fn badges_with_anchors<'a>(errors: impl Iterator<Item = &'a ErrorBadge>, rows: [&'a Rows; 2]) -> impl Iterator<Item = (&'a ErrorBadge, DVec2)> {
errors.filter_map(move |error| Some((error, node_geometry(&rows, &error.key)?.error_badge_anchor())))
}
fn draw_error(error: &ErrorBadge, anchor: DVec2, hovered: bool) -> Result<Item<Vector>, TextToVectorError> {
let text_size = error_text_size(&error.text);
let [min, max] = error_badge::body(anchor, text_size);
let mut badge = List::new_from_item(painted(rounded_rect(min, max, [ERROR_RADIUS; 4]), Coverage::new_fill(), ERROR_RED.into()));
let corners = error_badge::tail(anchor);
let mut tail = BezPath::new();
tail.move_to((corners[0].x, corners[0].y));
for corner in &corners[1..] {
tail.line_to((corner.x, corner.y));
}
tail.close_path();
badge.push(painted(Vector::item_from_bezpath(&tail), Coverage::new_fill(), ERROR_RED.into()));
let outline = paragraph_outline(&error.text, ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH)?;
badge.extend(text(&outline, error_badge::text_top_left(anchor, text_size), ERROR_TEXT));
let mut grouped = rounded_rect(min, corners.into_iter().fold(max, DVec2::max), [0.; 4]);
stamp_coverage(&mut grouped, Coverage::new_fill(), Graphic::VectorList(badge), CoverPlacement::Above);
if !hovered {
grouped.set_attribute(ATTR_OPACITY, ERROR_OPACITY);
}
Ok(grouped)
}
#[node_macro::node(transient, memoize)]
fn draw_network_connectors(_: impl Ctx, #[scope(inputs::NETWORK_CONNECTORS)] network_connectors: Item<ReplicatedMap<NetworkConnector>>) -> Result<List<Vector>, TextToVectorError> {
let mut labels = Labels::default();
let mut graphic = List::new();
for row in network_connectors.element() {
graphic.extend(draw_network_connector(row, &mut labels)?);
}
Ok(graphic)
}
fn draw_network_connector(row: &NetworkConnector, labels: &mut Labels) -> Result<List<Vector>, TextToVectorError> {
let mut graphic = row_connector(row, Highlight::None);
let Some(entry) = &row.connector else { return Ok(graphic) };
let name = labels.label(&entry.name, f64::INFINITY)?;
if !row.renaming {
let [top_left, _] = row.name_box(name.width);
graphic.extend(text(&name.outline, top_left, TEXT));
}
if row.editable && row.key.index() < 2 {
let [min, max] = row.separator(name.width);
graphic.push(painted(rounded_rect(min, max, [0.; 4]), Coverage::new_fill(), SEPARATOR.into()));
}
Ok(graphic)
}
fn row_connector(row: &NetworkConnector, highlight: Highlight) -> List<Vector> {
match &row.connector {
Some(entry) => connector(&CONNECTOR_OUTLINE, row.connector_top_left(), entry, highlight),
None => drawn_connector(&CONNECTOR_OUTLINE, row.connector_top_left(), DataType::General, false, highlight),
}
}
#[node_macro::node(transient, memoize)]
fn draw_highlights(
_: impl Ctx,
#[scope(inputs::HIGHLIGHTS)] highlights: Item<Highlights>,
#[scope(inputs::MOVING)] moving: Item<Rows>,
#[scope(inputs::SETTLED)] settled: Item<Rows>,
#[scope(inputs::NETWORK_CONNECTORS)] network_connectors: Item<ReplicatedMap<NetworkConnector>>,
#[scope(inputs::ERRORS)] errors: Item<ReplicatedMap<ErrorBadge>>,
) -> Result<List<Vector>, TextToVectorError> {
let highlights = highlights.into_element();
let rows = [moving.element(), settled.element()];
let mut graphic = List::new();
for dot in rows.iter().flat_map(|rows| &rows.dots) {
let looks = highlights.dot(dot.look.key);
if looks != [Highlight::None; 2] {
graphic.extend(draw_dot(dot, looks));
}
}
let connectors: BTreeSet<ConnectorKey> = highlights.connectors().collect();
for key in connectors {
if let Some(drawn) = highlighted_connector(key, highlights.connector(key), rows, network_connectors.element()) {
graphic.extend(drawn);
}
}
for layer in rows.iter().flat_map(|rows| &rows.layers) {
match highlights.layer_button(layer.look.key) {
Some(LayerButton::Grip) => graphic.extend(grip(layer, true)),
Some(hovered) if !layer.look.read_only => {
for (_, place, icons) in layer_buttons(layer).filter(|(button, ..)| *button == hovered) {
graphic.extend(layer_button(layer, place, icons, true, highlights.clicked));
}
}
_ => {}
}
}
let hovered = errors.element().iter().filter(|error| highlights.badge_hovered(error.key));
for (error, anchor) in badges_with_anchors(hovered, rows) {
graphic.push(draw_error(error, anchor, true)?);
}
Ok(graphic)
}
fn highlighted_connector(key: ConnectorKey, highlight: Highlight, rows: [&Rows; 2], network_connectors: &ReplicatedMap<NetworkConnector>) -> Option<List<Vector>> {
let card = |node| rows.into_iter().find_map(|rows| rows.cards.get(&node));
let layer = |node| rows.into_iter().find_map(|rows| rows.layers.get(&node));
let indexed = |index: usize| move |found: &&Connector| found.index as usize == index;
let on_card = |(top_left, found): (DVec2, &Connector)| connector(&CONNECTOR_OUTLINE, top_left, found, highlight);
match key {
ConnectorKey::Input(InputKey::Node { node, index }) => {
if let Some(card) = card(node) {
return card.inputs().find(|(_, input)| indexed(index)(input)).map(on_card);
}
let layer = layer(node)?;
if let Some(input) = layer.look.primary_input.as_ref().filter(indexed(index)) {
return Some(stack_input(layer, input, highlight));
}
let input = layer.look.secondary_input.as_ref().filter(indexed(index))?;
Some(connector(&CONNECTOR_OUTLINE, layer.secondary_input_connector(), input, highlight))
}
ConnectorKey::Output(OutputKey::Node { node, index }) => {
if let Some(card) = card(node) {
return card.outputs().find(|(_, output)| indexed(index)(output)).map(on_card);
}
let layer = layer(node)?;
layer.look.primary_output.as_ref().filter(indexed(index)).map(|output| stack_output(layer, output, highlight))
}
ConnectorKey::Input(InputKey::Export(index)) => Some(row_connector(network_connectors.get(&NetworkConnectorKey::Export(index))?, highlight)),
ConnectorKey::Output(OutputKey::Import(index)) => Some(row_connector(network_connectors.get(&NetworkConnectorKey::Import(index))?, highlight)),
}
}
#[node_macro::node(transient)]
fn draw_reorder_bar(_: impl Ctx, #[scope(inputs::REORDER_BAR)] reorder_bar: Item<Option<(NetworkConnectorKind, DVec2)>>) -> List<Vector> {
let Some((kind, anchor)) = reorder_bar.into_element() else { return List::new() };
let [min, max] = network_connector::reorder_bar(kind, anchor);
List::new_from_item(painted(rounded_rect(min, max, [0.; 4]), Coverage::new_fill(), Color::WHITE))
}
#[node_macro::node(transient)]
fn draw_box_selection(ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, #[scope(inputs::BOX_SELECTION)] box_selection: Item<Option<[DVec2; 2]>>) -> List<Vector> {
let Some([start, end]) = box_selection.into_element() else { return List::new() };
let min = start.min(end);
let max = min + (end - start).abs() + 2. * BORDER_WIDTH;
let fill = painted(rounded_rect(min, max, [0.; 4]), Coverage::new_fill(), Color::from(BOX_SELECTION).with_alpha(BOX_SELECTION_FILL_OPACITY));
let [inner_min, inner_max] = [min + BORDER_WIDTH / 2., max - BORDER_WIDTH / 2.];
let outline = Rect::new(inner_min.x, inner_min.y, inner_max.x, inner_max.y).to_path(0.);
let border = painted(Vector::item_from_bezpath(&outline), Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), BOX_SELECTION.into());
let (view, _) = view_and_device_scale(&ctx);
let mut selection = List::from_iter([fill, border]);
selection.left_apply_transform(&view.inverse());
selection
}
+521
View File
@@ -0,0 +1,521 @@
use crate::geometry::{WireEnd, is_thick_wire};
use crate::metrics::GRID_SIZE;
use crate::wire::WireStyle;
use glam::{DVec2, IVec2};
use graphene_std::vector::misc::dvec2_to_point;
use vello_gpu::kurbo::{BezPath, DEFAULT_ACCURACY, Line, ParamCurve, Point, Shape, Vec2};
pub fn route(ends: [WireEnd; 2], wire_style: WireStyle) -> BezPath {
let [output_position, input_position] = ends.map(|end| end.position);
let [vertical_out, vertical_in] = ends.map(|end| end.vertical);
let (output_position, input_position) = if is_thick_wire(ends) {
if thick_wire_spans_single_cell(output_position, input_position) {
return BezPath::new();
}
let trim = 3. * (input_position.y - output_position.y).signum();
(output_position + DVec2::new(0., trim), input_position - DVec2::new(0., trim))
} else {
(output_position, input_position)
};
match wire_style {
WireStyle::Direct => {
let horizontal_gap = (output_position.x - input_position.x).abs();
let vertical_gap = (output_position.y - input_position.y).abs();
let curve_length = GRID_SIZE;
let curve_falloff_rate = curve_length * std::f64::consts::TAU;
let horizontal_curve_amount = -(2_f64.powf((-10. * horizontal_gap) / curve_falloff_rate)) + 1.;
let vertical_curve_amount = -(2_f64.powf((-10. * vertical_gap) / curve_falloff_rate)) + 1.;
let horizontal_curve = horizontal_curve_amount * curve_length;
let vertical_curve = vertical_curve_amount * curve_length;
let locations = [
output_position,
DVec2::new(
if vertical_out { output_position.x } else { output_position.x + horizontal_curve },
if vertical_out { output_position.y - vertical_curve } else { output_position.y },
),
DVec2::new(
if vertical_in { input_position.x } else { input_position.x - horizontal_curve },
if vertical_in { input_position.y + vertical_curve } else { input_position.y },
),
DVec2::new(input_position.x, input_position.y),
];
let smoothing = 0.5;
let delta01 = DVec2::new((locations[1].x - locations[0].x) * smoothing, (locations[1].y - locations[0].y) * smoothing);
let delta23 = DVec2::new((locations[3].x - locations[2].x) * smoothing, (locations[3].y - locations[2].y) * smoothing);
let mut wire = BezPath::new();
wire.move_to(dvec2_to_point(locations[0]));
wire.line_to(dvec2_to_point(locations[1]));
wire.curve_to(dvec2_to_point(locations[1] + delta01), dvec2_to_point(locations[2] - delta23), dvec2_to_point(locations[2]));
wire.line_to(dvec2_to_point(locations[3]));
wire
}
WireStyle::GridAligned => {
let locations = straight_wire_path(output_position, input_position, vertical_out, vertical_in);
straight_wire_to_bezpath(locations)
}
}
}
fn thick_wire_spans_single_cell(output_position: DVec2, input_position: DVec2) -> bool {
(output_position.x - input_position.x).abs() < 1. && (output_position.y - input_position.y).abs() <= GRID_SIZE
}
/// The center line that cleaves a thick layer-stack wire, following its path. Its ends reach past the wire (1.5px toward the
/// output connector and 2px toward the input) so the color runs through the full cleaved connector slots.
pub(crate) fn build_thick_wire_center_line(ends: [WireEnd; 2], wire_style: WireStyle) -> BezPath {
let [output_position, input_position] = ends.map(|end| end.position);
if thick_wire_spans_single_cell(output_position, input_position) {
return BezPath::new();
}
let wire = route(ends, wire_style);
let (Some(start), Some(end)) = (wire.segments().next().map(|segment| segment.start()), wire.segments().last().map(|segment| segment.end())) else {
return BezPath::new();
};
// The 8px wire trims 3px at each end, so the center line reaches further out to trim 1.5px and 1px instead
let sign = (input_position.y - output_position.y).signum();
let mut center_line = BezPath::new();
center_line.move_to(start - Vec2::new(0., 1.5 * sign));
center_line.line_to(start);
for element in wire.elements().iter().skip(1) {
center_line.push(*element);
}
center_line.line_to(end + Vec2::new(0., 2. * sign));
center_line
}
fn straight_wire_path(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool) -> Vec<IVec2> {
let grid_spacing = GRID_SIZE as i32;
let line_width = 2;
let in_x = input_position.x.floor() as i32;
let in_y = input_position.y.floor() as i32;
let out_x = output_position.x.floor() as i32;
let out_y = output_position.y.floor() as i32;
let mid_x = (in_x + out_x).div_euclid(2) + (in_x + out_x).div_euclid(2).rem_euclid(grid_spacing);
let mid_y = (in_y + out_y).div_euclid(2) + (in_y + out_y).div_euclid(2).rem_euclid(grid_spacing);
let mid_y_alternate = in_y - in_y.rem_euclid(grid_spacing);
let x1 = out_x;
let x2 = out_x + grid_spacing;
let x3 = in_x - 2 * grid_spacing;
let x4 = in_x;
let x5 = in_x - 2 * grid_spacing + line_width;
let x6 = out_x + grid_spacing + line_width;
let x7 = out_x + 2 * grid_spacing + line_width;
let x8 = in_x + line_width;
let x9 = out_x + 2 * grid_spacing;
let x10 = mid_x + line_width;
let x11 = out_x - grid_spacing;
let x12 = out_x - 4 * grid_spacing;
let x13 = mid_x;
let x14 = in_x + grid_spacing;
let x15 = in_x - 4 * grid_spacing;
let x16 = in_x + 8 * grid_spacing;
let x17 = mid_x - 2 * line_width;
let x18 = out_x + grid_spacing - 2 * line_width;
let x19 = out_x - 2 * line_width;
let x20 = mid_x - line_width;
let y1 = out_y;
let y2 = out_y - grid_spacing;
let y3 = in_y;
let y4 = out_y - grid_spacing + 5 * line_width + 1;
let y5 = in_y - 2 * grid_spacing;
let y6 = out_y + 4 * line_width;
let y7 = out_y + 5 * line_width;
let y8 = out_y - 2 * grid_spacing + 5 * line_width + 1;
let y9 = out_y + 6 * line_width;
let y10 = in_y + 2 * grid_spacing;
let y111 = in_y + grid_spacing + 6 * line_width + 1;
let y12 = in_y + grid_spacing - 5 * line_width + 1;
let y13 = in_y - grid_spacing;
let y14 = in_y + grid_spacing;
let y15 = mid_y;
let y16 = mid_y_alternate;
let wire1 = vec![IVec2::new(x1, y1), IVec2::new(x1, y4), IVec2::new(x5, y4), IVec2::new(x5, y3), IVec2::new(x4, y3)];
let wire2 = vec![IVec2::new(x1, y1), IVec2::new(x1, y16), IVec2::new(x3, y16), IVec2::new(x3, y3), IVec2::new(x4, y3)];
let wire3 = vec![
IVec2::new(x1, y1),
IVec2::new(x1, y4),
IVec2::new(x12, y4),
IVec2::new(x12, y10),
IVec2::new(x3, y10),
IVec2::new(x3, y3),
IVec2::new(x4, y3),
];
let wire4 = vec![
IVec2::new(x1, y1),
IVec2::new(x1, y4),
IVec2::new(x13, y4),
IVec2::new(x13, y10),
IVec2::new(x3, y10),
IVec2::new(x3, y3),
IVec2::new(x4, y3),
];
// `outConnector` point and `inConnector` point lying on the same horizontal grid line and `outConnector` point lies to the right of `inConnector` point
if out_y == in_y && out_x > in_x && (vertical_out || !vertical_in) {
return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y2), IVec2::new(x3, y2), IVec2::new(x3, y3), IVec2::new(x4, y3)];
};
// Handle straight lines
if out_y == in_y || (out_x == in_x && vertical_out) {
return vec![IVec2::new(x1, y1), IVec2::new(x4, y3)];
};
// Handle standard right-angle paths
// Start vertical, then horizontal
// `outConnector` point lies to the left of `inConnector` point
if vertical_out && in_x > out_x {
// `outConnector` point lies above `inConnector` point
if out_y < in_y {
// `outConnector` point lies on the vertical grid line 4 units to the left of `inConnector` point point
if -4 * grid_spacing <= out_x - in_x && out_x - in_x < -3 * grid_spacing {
return wire1;
};
// `outConnector` point lying on vertical grid lines 3 and 2 units to the left of `inConnector` point
if -3 * grid_spacing <= out_x - in_x && out_x - in_x <= -grid_spacing {
if -2 * grid_spacing <= out_y - in_y && out_y - in_y <= -grid_spacing {
return vec![IVec2::new(x1, y1), IVec2::new(x1, y2), IVec2::new(x2, y2), IVec2::new(x2, y3), IVec2::new(x4, y3)];
};
if -grid_spacing <= out_y - in_y && out_y - in_y <= 0 {
return vec![IVec2::new(x1, y1), IVec2::new(x1, y4), IVec2::new(x6, y4), IVec2::new(x6, y3), IVec2::new(x4, y3)];
};
return vec![
IVec2::new(x1, y1),
IVec2::new(x1, y4),
IVec2::new(x7, y4),
IVec2::new(x7, y5),
IVec2::new(x3, y5),
IVec2::new(x3, y3),
IVec2::new(x4, y3),
];
}
// `outConnector` point lying on vertical grid line 1 units to the left of `inConnector` point
if -grid_spacing < out_x - in_x && out_x - in_x <= 0 {
// `outConnector` point lying on horizontal grid line 1 unit above `inConnector` point
if -2 * grid_spacing <= out_y - in_y && out_y - in_y <= -grid_spacing {
return vec![IVec2::new(x1, y6), IVec2::new(x2, y6), IVec2::new(x8, y3)];
};
// `outConnector` point lying on the same horizontal grid line as `inConnector` point
if -grid_spacing <= out_y - in_y && out_y - in_y <= 0 {
return vec![IVec2::new(x1, y7), IVec2::new(x4, y3)];
};
return vec![
IVec2::new(x1, y1),
IVec2::new(x1, y2),
IVec2::new(x9, y2),
IVec2::new(x9, y5),
IVec2::new(x3, y5),
IVec2::new(x3, y3),
IVec2::new(x4, y3),
];
}
return vec![IVec2::new(x1, y1), IVec2::new(x1, y4), IVec2::new(x10, y4), IVec2::new(x10, y3), IVec2::new(x4, y3)];
}
// `outConnector` point lies below `inConnector` point
// `outConnector` point lying on vertical grid line 1 unit to the left of `inConnector` point
if -grid_spacing <= out_x - in_x && out_x - in_x <= 0 {
// `outConnector` point lying on the horizontal grid lines 1 and 2 units below the `inConnector` point
if 0 <= out_y - in_y && out_y - in_y <= 2 * grid_spacing {
return vec![IVec2::new(x1, y6), IVec2::new(x11, y6), IVec2::new(x11, y3), IVec2::new(x4, y3)];
};
return wire2;
}
return vec![IVec2::new(x1, y1), IVec2::new(x1, y3), IVec2::new(x4, y3)];
}
// `outConnector` point lies to the right of `inConnector` point
if vertical_out && in_x <= out_x {
// `outConnector` point lying on any horizontal grid line above `inConnector` point
if out_y < in_y {
// `outConnector` point lying on horizontal grid line 1 unit above `inConnector` point
if -2 * grid_spacing < out_y - in_y && out_y - in_y <= -grid_spacing {
return wire1;
};
// `outConnector` point lying on the same horizontal grid line as `inConnector` point
if -grid_spacing < out_y - in_y && out_y - in_y <= 0 {
return vec![IVec2::new(x1, y1), IVec2::new(x1, y8), IVec2::new(x5, y8), IVec2::new(x5, y3), IVec2::new(x4, y3)];
};
// `outConnector` point lying on vertical grid lines 1 and 2 units to the right of `inConnector` point
if grid_spacing <= out_x - in_x && out_x - in_x <= 3 * grid_spacing {
return vec![
IVec2::new(x1, y1),
IVec2::new(x1, y4),
IVec2::new(x9, y4),
IVec2::new(x9, y5),
IVec2::new(x3, y5),
IVec2::new(x3, y3),
IVec2::new(x4, y3),
];
}
return vec![
IVec2::new(x1, y1),
IVec2::new(x1, y4),
IVec2::new(x10, y4),
IVec2::new(x10, y5),
IVec2::new(x5, y5),
IVec2::new(x5, y3),
IVec2::new(x4, y3),
];
}
// `outConnector` point lies below `inConnector` point
if out_y - in_y <= grid_spacing {
// `outConnector` point lies on the horizontal grid line 1 unit below the `inConnector` Point
if 0 <= out_x - in_x && out_x - in_x <= 13 * grid_spacing {
return vec![IVec2::new(x1, y9), IVec2::new(x3, y9), IVec2::new(x3, y3), IVec2::new(x4, y3)];
};
if 13 < out_x - in_x && out_x - in_x <= 18 * grid_spacing {
return wire3;
};
return wire4;
}
// `outConnector` point lies on the horizontal grid line 2 units below `outConnector` point
if grid_spacing <= out_y - in_y && out_y - in_y <= 2 * grid_spacing {
if 0 <= out_x - in_x && out_x - in_x <= 13 * grid_spacing {
return vec![IVec2::new(x1, y7), IVec2::new(x5, y7), IVec2::new(x5, y3), IVec2::new(x4, y3)];
};
if 13 < out_x - in_x && out_x - in_x <= 18 * grid_spacing {
return wire3;
};
return wire4;
}
// 0 to 4 units below the `outConnector` Point
if out_y - in_y <= 4 * grid_spacing {
return wire1;
};
return wire2;
}
// Start horizontal, then vertical
if vertical_in {
// when `outConnector` lies below `inConnector`
if out_y > in_y {
// `out_x` lies to the left of `in_x`
if out_x < in_x {
return vec![IVec2::new(x1, y1), IVec2::new(x4, y1), IVec2::new(x4, y3)];
};
// `out_x` lies to the right of `in_x`
if out_y - in_y <= grid_spacing {
// `outConnector` point directly below `inConnector` point
if 0 <= out_x - in_x && out_x - in_x <= grid_spacing {
return vec![IVec2::new(x1, y1), IVec2::new(x14, y1), IVec2::new(x14, y2), IVec2::new(x4, y2), IVec2::new(x4, y3)];
};
// `outConnector` point lies below `inConnector` point and strictly to the right of `inConnector` point
return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y111), IVec2::new(x4, y111), IVec2::new(x4, y3)];
}
return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y2), IVec2::new(x4, y2), IVec2::new(x4, y3)];
}
// `out_y` lies on or above the `in_y` point
if -6 * grid_spacing < in_x - out_x && in_x - out_x < 4 * grid_spacing {
// edge case: `outConnector` point lying on vertical grid lines ranging from 4 units to left to 5 units to right of `inConnector` point
if -grid_spacing < in_x - out_x && in_x - out_x < 4 * grid_spacing {
return vec![
IVec2::new(x1, y1),
IVec2::new(x2, y1),
IVec2::new(x2, y2),
IVec2::new(x15, y2),
IVec2::new(x15, y12),
IVec2::new(x4, y12),
IVec2::new(x4, y3),
];
}
return vec![IVec2::new(x1, y1), IVec2::new(x16, y1), IVec2::new(x16, y12), IVec2::new(x4, y12), IVec2::new(x4, y3)];
}
// left of edge case: `outConnector` point lying on vertical grid lines more than 4 units to left of `inConnector` point
if 4 * grid_spacing < in_x - out_x {
return vec![IVec2::new(x1, y1), IVec2::new(x17, y1), IVec2::new(x17, y12), IVec2::new(x4, y12), IVec2::new(x4, y3)];
};
// right of edge case: `outConnector` point lying on the vertical grid lines more than 5 units to right of `inConnector` point
if 6 * grid_spacing > in_x - out_x {
return vec![IVec2::new(x1, y1), IVec2::new(x18, y1), IVec2::new(x18, y12), IVec2::new(x4, y12), IVec2::new(x4, y3)];
};
}
// Both horizontal - use horizontal middle point
// When `inConnector` point is one of the two closest diagonally opposite points
if 0 <= in_x - out_x && in_x - out_x <= grid_spacing && in_y - out_y >= -grid_spacing && in_y - out_y <= grid_spacing {
return vec![IVec2::new(x19, y1), IVec2::new(x19, y3), IVec2::new(x4, y3)];
}
// When `inConnector` point lies on the horizontal line 1 unit above and below the `outConnector` point
if -grid_spacing <= out_y - in_y && out_y - in_y <= grid_spacing && out_x > in_x {
// Horizontal line above `out_y`
if in_y < out_y {
return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y13), IVec2::new(x3, y13), IVec2::new(x3, y3), IVec2::new(x4, y3)];
};
// Horizontal line below `out_y`
return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y14), IVec2::new(x3, y14), IVec2::new(x3, y3), IVec2::new(x4, y3)];
}
// `outConnector` point to the right of `inConnector` point
if out_x > in_x - grid_spacing {
return vec![
IVec2::new(x1, y1),
IVec2::new(x18, y1),
IVec2::new(x18, y15),
IVec2::new(x5, y15),
IVec2::new(x5, y3),
IVec2::new(x4, y3),
];
};
// When `inConnector` point lies on the vertical grid line two units to the right of `outConnector` point
if grid_spacing <= in_x - out_x && in_x - out_x <= 2 * grid_spacing {
return vec![IVec2::new(x1, y1), IVec2::new(x18, y1), IVec2::new(x18, y3), IVec2::new(x4, y3)];
};
vec![IVec2::new(x1, y1), IVec2::new(x20, y1), IVec2::new(x20, y3), IVec2::new(x4, y3)]
}
fn straight_wire_to_bezpath(locations: Vec<IVec2>) -> BezPath {
if locations.is_empty() {
return BezPath::new();
}
let to_point = |location: IVec2| Point::new(location.x as f64, location.y as f64);
if locations.len() == 2 {
let p1 = to_point(locations[0]);
let p2 = to_point(locations[1]);
return Line::new(p1, p2).to_path(DEFAULT_ACCURACY);
}
let corner_radius = 10;
// Create path with rounded corners
let mut path = BezPath::new();
path.move_to(to_point(locations[0]));
for i in 1..(locations.len() - 1) {
let prev = locations[i - 1];
let curr = locations[i];
let next = locations[i + 1];
let corner_start = IVec2::new(
curr.x
+ if curr.x == prev.x {
0
} else if prev.x > curr.x {
corner_radius
} else {
-corner_radius
},
curr.y
+ if curr.y == prev.y {
0
} else if prev.y > curr.y {
corner_radius
} else {
-corner_radius
},
);
let corner_start_mid = IVec2::new(
curr.x
+ if curr.x == prev.x {
0
} else if prev.x > curr.x {
corner_radius / 2
} else {
-corner_radius / 2
},
curr.y
+ if curr.y == prev.y {
0
} else {
match prev.y > curr.y {
true => corner_radius / 2,
false => -corner_radius / 2,
}
},
);
let corner_end = IVec2::new(
curr.x
+ if curr.x == next.x {
0
} else if next.x > curr.x {
corner_radius
} else {
-corner_radius
},
curr.y
+ if curr.y == next.y {
0
} else if next.y > curr.y {
corner_radius
} else {
-corner_radius
},
);
let corner_end_mid = IVec2::new(
curr.x
+ if curr.x == next.x {
0
} else if next.x > curr.x {
corner_radius / 2
} else {
-corner_radius / 2
},
curr.y
+ if curr.y == next.y {
0
} else if next.y > curr.y {
10 / 2
} else {
-corner_radius / 2
},
);
path.line_to(to_point(corner_start));
path.curve_to(to_point(corner_start_mid), to_point(corner_end_mid), to_point(corner_end));
}
path.line_to(to_point(*locations.last().unwrap()));
path
}
+86
View File
@@ -0,0 +1,86 @@
use crate::metrics::{ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH, GRID_SIZE, TEXT_SIZE};
use core_types::list::{ATTR_GEOMETRY_CACHE, List};
use glam::DVec2;
use graphic_types::Vector;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use text_nodes::{FALLBACK_FONT_RESOURCE, TextToVectorError, TypesettingConfig};
use vector_types::vector::GeometryCache;
#[derive(Debug)]
pub struct Label {
pub outline: List<Vector>,
pub width: f64,
}
#[derive(Debug, Default)]
pub struct Labels(HashMap<(String, u64), Label>);
impl Labels {
pub fn label(&mut self, text: &str, max_width: f64) -> Result<&Label, TextToVectorError> {
match self.0.entry((text.to_string(), max_width.to_bits())) {
Entry::Occupied(label) => Ok(label.into_mut()),
Entry::Vacant(label) => {
let text = ellipsized(text, max_width);
let (outline, width) = (outline(&text)?, label_width(&text));
Ok(label.insert(Label { outline, width }))
}
}
}
}
pub fn label_width(text: &str) -> f64 {
text_nodes::bounding_box(text, &FALLBACK_FONT_RESOURCE, typesetting(), false).x
}
fn ellipsized(text: &str, max_width: f64) -> String {
if label_width(text) <= max_width {
return text.to_string();
}
let cut = |end: usize| format!("{}…", &text[..end]);
let ends: Vec<usize> = text.char_indices().map(|(end, _)| end).collect();
let fitting = ends.partition_point(|&end| label_width(&cut(end)) <= max_width);
cut(ends[fitting.saturating_sub(1)])
}
fn outline(text: &str) -> Result<List<Vector>, TextToVectorError> {
text_nodes::to_path(text, &FALLBACK_FONT_RESOURCE, typesetting(), false).map(with_geometry_caches)
}
fn with_geometry_caches(mut outline: List<Vector>) -> List<Vector> {
for index in 0..outline.len() {
outline.set_attribute(ATTR_GEOMETRY_CACHE, index, GeometryCache::default());
}
outline
}
pub fn paragraph_size(text: &str, line_height: f64, max_width: f64) -> DVec2 {
let unwrapped = text_nodes::bounding_box(text, &FALLBACK_FONT_RESOURCE, paragraph_typesetting(line_height, None), true);
let wrapped = text_nodes::bounding_box(text, &FALLBACK_FONT_RESOURCE, paragraph_typesetting(line_height, Some(max_width)), true);
DVec2::new(unwrapped.x.min(max_width), wrapped.y)
}
pub fn error_text_size(text: &str) -> DVec2 {
paragraph_size(text, ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH)
}
pub fn paragraph_outline(text: &str, line_height: f64, max_width: f64) -> Result<List<Vector>, TextToVectorError> {
text_nodes::to_path(text, &FALLBACK_FONT_RESOURCE, paragraph_typesetting(line_height, Some(max_width)), false).map(with_geometry_caches)
}
fn typesetting() -> TypesettingConfig {
TypesettingConfig {
font_size: TEXT_SIZE,
line_height_ratio: GRID_SIZE / TEXT_SIZE,
..Default::default()
}
}
fn paragraph_typesetting(line_height: f64, max_width: Option<f64>) -> TypesettingConfig {
TypesettingConfig {
font_size: TEXT_SIZE,
line_height_ratio: line_height / TEXT_SIZE,
max_width,
..Default::default()
}
}
+33
View File
@@ -0,0 +1,33 @@
[package]
name = "graph-ui-types"
description = "The rows, scene and metrics of the node graph UI"
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
[features]
serde = ["dep:serde"]
wasm = ["dep:tsify", "dep:wasm-bindgen"]
[dependencies]
# Local dependencies
core-types = { workspace = true }
dyn-any = { workspace = true }
graph-layout = { workspace = true }
graphene-hash = { workspace = true }
graphic-types = { workspace = true }
# Workspace dependencies
glam = { workspace = true }
serde = { workspace = true, optional = true }
tsify = { workspace = true, optional = true }
wasm-bindgen = { workspace = true, optional = true }
+56
View File
@@ -0,0 +1,56 @@
use crate::geometry::NodeShape;
use crate::replicated_map::Keyed;
use core_types::uuid::NodeId;
use graphene_hash::CacheHash;
#[derive(Clone, Debug, PartialEq, CacheHash)]
pub struct Card {
pub key: NodeId,
pub shape: NodeShape,
pub name: String,
pub icon: &'static str,
pub primary_input: Option<Connector>,
pub primary_output: Option<Connector>,
pub secondary_inputs: Vec<Connector>,
pub secondary_outputs: Vec<Connector>,
pub selection: Selection,
pub visible: bool,
pub previewed: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
pub enum Selection {
None,
Inactive,
Active,
}
#[derive(Clone, Debug, PartialEq, CacheHash)]
pub struct Connector {
pub index: u32,
pub name: String,
pub data_type: DataType,
pub connected: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
pub enum DataType {
General,
Number,
Artboard,
Graphic,
Raster,
Vector,
Color,
Gradient,
Typography,
Invalid,
}
impl Keyed for Card {
type Key = NodeId;
fn key(&self) -> NodeId {
self.key
}
}
+23
View File
@@ -0,0 +1,23 @@
use crate::card::DataType;
use crate::geometry::NodeShape;
use crate::replicated_map::Keyed;
use core_types::uuid::NodeId;
use graphene_hash::CacheHash;
#[derive(Clone, Debug, PartialEq, CacheHash)]
pub struct Dot {
pub key: NodeId,
pub shape: NodeShape,
pub data_type: DataType,
pub wired: bool,
pub selected: bool,
pub previewed: bool,
}
impl Keyed for Dot {
type Key = NodeId;
fn key(&self) -> NodeId {
self.key
}
}
@@ -0,0 +1,40 @@
use crate::metrics::{ERROR_PADDING, ERROR_TAIL_LEFT, ERROR_TAIL_SIZE};
use crate::replicated_map::Keyed;
use core_types::uuid::NodeId;
use glam::DVec2;
use graphene_hash::CacheHash;
#[derive(Clone, Debug, PartialEq, CacheHash)]
pub struct ErrorBadge {
pub key: NodeId,
pub text: String,
}
impl Keyed for ErrorBadge {
type Key = NodeId;
fn key(&self) -> NodeId {
self.key
}
}
pub fn body(anchor: DVec2, text_size: DVec2) -> [DVec2; 2] {
let size = text_size + 2. * ERROR_PADDING;
[anchor - DVec2::Y * size.y, anchor + DVec2::X * size.x]
}
pub fn text_top_left(anchor: DVec2, text_size: DVec2) -> DVec2 {
let [top_left, _] = body(anchor, text_size);
top_left + ERROR_PADDING
}
pub fn tail(anchor: DVec2) -> [DVec2; 3] {
let top_left = anchor + DVec2::X * ERROR_TAIL_LEFT;
[top_left, top_left + DVec2::X * ERROR_TAIL_SIZE.x, top_left + DVec2::new(ERROR_TAIL_SIZE.x / 2., ERROR_TAIL_SIZE.y)]
}
pub fn covers(anchor: DVec2, text_size: DVec2, point: DVec2) -> bool {
let [tail, ..] = tail(anchor);
let within = |[min, max]: [DVec2; 2]| min.cmple(point).all() && point.cmple(max).all();
within(body(anchor, text_size)) || within([tail, tail + ERROR_TAIL_SIZE])
}
+493
View File
@@ -0,0 +1,493 @@
use crate::card::{Card, Connector};
use crate::dot::Dot;
use crate::layer::Layer;
use crate::metrics::{
CLICK_RADIUS, GRID_SIZE, INPUT_CONNECTOR_OFFSET, LAYER_BUTTON_SIZE, LAYER_CLICK_RADIUS, LAYER_DETAILS_MARGIN, LAYER_GRIP_WIDTH, LAYER_LEFT_MARGIN, LAYER_NAME_LEFT, LAYER_THUMBNAIL_IMAGE_INSET,
LAYER_THUMBNAIL_MARGIN, LAYER_THUMBNAIL_WIDTH, OUTPUT_CONNECTOR_OFFSET, PORT_CLICK_RADIUS, SIDE_PORT_HALF_HEIGHT, SIDE_PORT_INWARD_REACH, SIDE_PORT_OUTWARD_REACH, STACK_ANCHOR_DISTANCE,
STACK_CONNECTOR_SIZE, STACK_PORT_HALF_SIZE, WAYPOINT_GUTTER_OFFSET, WAYPOINT_GUTTER_RADIUS, WAYPOINT_HALF_SIZE,
};
use crate::network_connector::{NetworkConnector, NetworkConnectorKey};
use crate::placed::Placed;
use crate::replicated_map::ReplicatedMap;
use crate::scene::Rows;
use crate::wire::{InputKey, OutputKey, Wire};
use core_types::uuid::NodeId;
use glam::{DVec2, IVec2, UVec2};
use graph_layout::{CHAIN_WIDTH, NodeKind};
use graphene_hash::CacheHash;
use std::ops::Range;
use std::sync::Arc;
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
pub struct NodeShape {
pub size: UVec2,
pub exposed_inputs: Arc<[usize]>,
pub outputs: u32,
pub primary_output_hidden: bool,
pub name_width: f64,
pub locked: bool,
}
impl NodeShape {
fn inputs(&self) -> u32 {
self.exposed_inputs.len() as u32
}
fn primary_input_hidden(&self) -> bool {
self.exposed_inputs.first().is_some_and(|first| *first != 0)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Part {
Body,
Input(u32),
Output(u32),
Visibility,
Lock,
Grip,
Name,
}
#[derive(Clone, Copy, Debug)]
pub struct PartTarget {
pub min: DVec2,
pub max: DVec2,
pub corner_radius: f64,
pub part: Part,
}
impl PartTarget {
fn around(center: DVec2, half_size: DVec2, corner_radius: f64, part: Part) -> Self {
Self {
min: center - half_size,
max: center + half_size,
corner_radius,
part,
}
}
fn over([min, max]: [DVec2; 2], corner_radius: f64, part: Part) -> Self {
Self { min, max, corner_radius, part }
}
pub fn input_port(center: DVec2, input: u32) -> Self {
Self {
min: center - DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
max: center + DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
corner_radius: PORT_CLICK_RADIUS,
part: Part::Input(input),
}
}
pub fn output_port(center: DVec2, output: u32) -> Self {
Self {
min: center - DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
max: center + DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
corner_radius: PORT_CLICK_RADIUS,
part: Part::Output(output),
}
}
pub fn overlaps(&self, min: DVec2, max: DVec2) -> bool {
if !min.cmplt(self.max).all() || !self.min.cmplt(max).all() {
return false;
}
let radius = self.clamped_radius();
let gap = (self.min + radius - max).max(min - (self.max - radius)).max(DVec2::ZERO);
gap == DVec2::ZERO || gap.length_squared() < radius * radius
}
pub fn contains(&self, point: DVec2) -> bool {
if !point.cmpge(self.min).all() || !point.cmplt(self.max).all() {
return false;
}
let radius = self.clamped_radius();
let inner = point.clamp(self.min + radius, self.max - radius);
point.distance_squared(inner) <= radius * radius
}
fn clamped_radius(&self) -> f64 {
self.corner_radius.min((self.max - self.min).min_element() / 2.)
}
}
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
pub struct WireEnd {
pub position: DVec2,
pub vertical: bool,
}
pub fn is_thick_wire([from, to]: [WireEnd; 2]) -> bool {
from.vertical && to.vertical
}
#[derive(Clone, Debug)]
pub struct NodeGeometry {
pub cell: IVec2,
pub kind: NodeKind,
pub chain_length: u32,
pub shape: NodeShape,
}
impl NodeGeometry {
pub fn body(&self) -> PartTarget {
match self.kind {
NodeKind::Waypoint => PartTarget::around(self.dot_center(), WAYPOINT_HALF_SIZE, WAYPOINT_HALF_SIZE.y, Part::Body),
NodeKind::Layer => PartTarget {
min: self.top_left() - DVec2::new(self.chain_width(), 0.),
max: self.top_left() + self.size(),
corner_radius: LAYER_CLICK_RADIUS,
part: Part::Body,
},
NodeKind::Node => PartTarget::over(self.card_body(), CLICK_RADIUS, Part::Body),
}
}
pub fn parts(&self, mut visit: impl FnMut(PartTarget)) {
match self.kind {
NodeKind::Waypoint => self.waypoint_ports(&mut visit),
NodeKind::Layer => self.layer_parts(&mut visit),
NodeKind::Node => self.node_ports(&mut visit),
}
visit(self.body());
}
pub fn input_end(&self, index: usize) -> Option<WireEnd> {
let position = self.input_anchor(self.place_of_input(index)?)?;
let vertical = self.kind == NodeKind::Layer && index == 0;
Some(WireEnd { position, vertical })
}
pub fn output_end(&self, index: usize) -> Option<WireEnd> {
let position = self.output_anchor(u32::try_from(index).ok()?)?;
let vertical = self.kind == NodeKind::Layer;
Some(WireEnd { position, vertical })
}
pub fn input_at(&self, place: u32) -> Option<usize> {
match self.kind {
NodeKind::Node => {
let row = place.checked_sub(self.input_rows().start)?;
self.shape.exposed_inputs.get(row as usize).copied()
}
NodeKind::Layer | NodeKind::Waypoint => Some(place as usize),
}
}
pub fn error_badge_anchor(&self) -> DVec2 {
let offset = if self.kind == NodeKind::Layer {
DVec2::new(LAYER_LEFT_MARGIN, -GRID_SIZE / 2.)
} else {
DVec2::ZERO
};
self.top_left() + offset
}
fn place_of_input(&self, index: usize) -> Option<u32> {
let place = match self.kind {
NodeKind::Node => {
let row = self.shape.exposed_inputs.iter().position(|exposed| *exposed == index)?;
self.input_rows().start as usize + row
}
NodeKind::Layer | NodeKind::Waypoint => index,
};
u32::try_from(place).ok()
}
fn input_anchor(&self, place: u32) -> Option<DVec2> {
match (self.kind, place) {
(NodeKind::Waypoint, 0) => Some(self.dot_center()),
(NodeKind::Layer, 0) => Some(self.stack_input_anchor()),
(NodeKind::Layer, 1) if self.has_side_input() => Some(self.side_input_anchor()),
(NodeKind::Node, row) if self.input_rows().contains(&row) => Some(self.row_input_anchor(row)),
_ => None,
}
}
fn output_anchor(&self, place: u32) -> Option<DVec2> {
match (self.kind, place) {
(NodeKind::Waypoint, 0) => Some(self.dot_center()),
(NodeKind::Layer, 0) => Some(self.stack_output_anchor()),
(NodeKind::Node, row) if self.output_rows().contains(&row) => Some(self.row_output_anchor(row)),
_ => None,
}
}
fn card_body(&self) -> [DVec2; 2] {
let top_left = self.top_left() + DVec2::new(0., GRID_SIZE / 2.);
[top_left, top_left + self.size() - DVec2::new(0., GRID_SIZE)]
}
fn layer_body(&self) -> [DVec2; 2] {
let top_left = self.top_left();
let chain_width = self.chain_width();
let left = if chain_width > 0. { -chain_width } else { LAYER_LEFT_MARGIN };
[top_left + DVec2::X * left, top_left + self.size()]
}
fn thumbnail_block(&self) -> [DVec2; 2] {
let left = self.top_left() + DVec2::X * LAYER_LEFT_MARGIN;
[left, left + DVec2::new(LAYER_THUMBNAIL_WIDTH, self.size().y)]
}
fn visibility(&self) -> [DVec2; 2] {
let [_, max] = self.layer_body();
let top_left = DVec2::new(max.x - LAYER_BUTTON_SIZE / 2., self.middle() - LAYER_BUTTON_SIZE / 2.);
[top_left, top_left + LAYER_BUTTON_SIZE]
}
fn grip(&self) -> [DVec2; 2] {
let [right_of_grip, _] = self.lock().unwrap_or(self.visibility());
[right_of_grip - DVec2::X * LAYER_GRIP_WIDTH, right_of_grip + DVec2::Y * LAYER_BUTTON_SIZE]
}
fn lock(&self) -> Option<[DVec2; 2]> {
let [min, max] = self.visibility();
self.shape.locked.then(|| [min - DVec2::X * LAYER_BUTTON_SIZE, max - DVec2::X * LAYER_BUTTON_SIZE])
}
fn dot_center(&self) -> DVec2 {
self.top_left() + DVec2::new(0., GRID_SIZE)
}
fn waypoint_ports(&self, visit: &mut impl FnMut(PartTarget)) {
let center = self.dot_center();
let gutter = |x_offset: f64, part| PartTarget::around(center + DVec2::new(x_offset, 0.), DVec2::splat(WAYPOINT_GUTTER_RADIUS), WAYPOINT_GUTTER_RADIUS, part);
visit(gutter(-WAYPOINT_GUTTER_OFFSET, Part::Input(0)));
visit(gutter(WAYPOINT_GUTTER_OFFSET, Part::Output(0)));
}
fn node_ports(&self, visit: &mut impl FnMut(PartTarget)) {
for row in self.input_rows() {
visit(PartTarget::input_port(self.row_input_anchor(row), row));
}
for row in self.output_rows() {
visit(PartTarget::output_port(self.row_output_anchor(row), row));
}
}
fn layer_parts(&self, visit: &mut impl FnMut(PartTarget)) {
visit(PartTarget::around(self.stack_input_anchor(), STACK_PORT_HALF_SIZE, PORT_CLICK_RADIUS, Part::Input(0)));
if self.has_side_input() {
visit(PartTarget::input_port(self.side_input_anchor(), 1));
}
visit(PartTarget::around(self.stack_output_anchor(), STACK_PORT_HALF_SIZE, PORT_CLICK_RADIUS, Part::Output(0)));
visit(PartTarget::over(self.visibility(), CLICK_RADIUS, Part::Visibility));
if let Some(lock) = self.lock() {
visit(PartTarget::over(lock, CLICK_RADIUS, Part::Lock));
}
let [grip_min, grip_max] = self.grip();
visit(PartTarget::over([grip_min, grip_max], 0., Part::Grip));
let name_left = self.top_left().x + LAYER_NAME_LEFT;
let name_right = (name_left + self.shape.name_width).min(grip_min.x);
if name_right > name_left {
visit(PartTarget {
min: DVec2::new(name_left, grip_min.y),
max: DVec2::new(name_right, grip_max.y),
corner_radius: CLICK_RADIUS,
part: Part::Name,
});
}
}
fn top_left(&self) -> DVec2 {
self.cell.as_dvec2() * GRID_SIZE
}
fn size(&self) -> DVec2 {
self.shape.size.as_dvec2() * GRID_SIZE
}
fn middle(&self) -> f64 {
self.top_left().y + self.size().y / 2.
}
fn input_rows(&self) -> Range<u32> {
let first = u32::from(self.shape.primary_input_hidden());
first..first + self.shape.inputs()
}
fn output_rows(&self) -> Range<u32> {
u32::from(self.shape.primary_output_hidden)..self.shape.outputs
}
fn row_input_anchor(&self, row: u32) -> DVec2 {
self.top_left() + DVec2::new(0., GRID_SIZE * (row as f64 + 1.))
}
fn row_output_anchor(&self, row: u32) -> DVec2 {
self.top_left() + DVec2::new(self.size().x, GRID_SIZE * (row as f64 + 1.))
}
fn stack_input_anchor(&self) -> DVec2 {
let [min, max] = self.thumbnail_block();
DVec2::new((min.x + max.x) / 2., max.y + STACK_ANCHOR_DISTANCE)
}
fn stack_output_anchor(&self) -> DVec2 {
let [min, max] = self.thumbnail_block();
DVec2::new((min.x + max.x) / 2., min.y - STACK_ANCHOR_DISTANCE)
}
fn side_input_anchor(&self) -> DVec2 {
DVec2::new(self.top_left().x, self.middle())
}
fn has_side_input(&self) -> bool {
self.shape.inputs() > 1
}
fn chain_width(&self) -> f64 {
if self.has_side_input() {
(self.chain_length as i32 * CHAIN_WIDTH + 1) as f64 * GRID_SIZE
} else {
0.
}
}
}
impl Placed<Card> {
fn geometry(&self) -> NodeGeometry {
NodeGeometry {
cell: self.cell,
kind: NodeKind::Node,
chain_length: 0,
shape: self.look.shape.clone(),
}
}
pub fn body(&self) -> [DVec2; 2] {
self.geometry().card_body()
}
pub fn rows(&self) -> u32 {
self.look.shape.size.y.saturating_sub(1)
}
pub fn inputs(&self) -> impl Iterator<Item = (DVec2, &Connector)> {
let geometry = self.geometry();
rows(&self.look.primary_input, &self.look.secondary_inputs).map(move |(row, input)| (geometry.row_input_anchor(row) + INPUT_CONNECTOR_OFFSET, input))
}
pub fn outputs(&self) -> impl Iterator<Item = (DVec2, &Connector)> {
let geometry = self.geometry();
rows(&self.look.primary_output, &self.look.secondary_outputs).map(move |(row, output)| (geometry.row_output_anchor(row) + OUTPUT_CONNECTOR_OFFSET, output))
}
}
fn rows<'a>(primary: &'a Option<Connector>, secondary: &'a [Connector]) -> impl Iterator<Item = (u32, &'a Connector)> {
primary.iter().map(|connector| (0, connector)).chain((1..).zip(secondary))
}
impl Placed<Layer> {
fn geometry(&self) -> NodeGeometry {
NodeGeometry {
cell: self.cell,
kind: NodeKind::Layer,
chain_length: self.look.chain_length,
shape: self.look.shape.clone(),
}
}
pub fn body(&self) -> [DVec2; 2] {
self.geometry().layer_body()
}
pub fn left_input_wire(&self) -> Option<DVec2> {
let geometry = self.geometry();
let [min, _] = geometry.layer_body();
(self.look.has_left_input_wire && geometry.chain_width() > 0.).then(|| DVec2::new(min.x, geometry.middle()))
}
pub fn thumbnail_block(&self) -> [DVec2; 2] {
self.geometry().thumbnail_block()
}
pub fn thumbnail(&self) -> [DVec2; 2] {
let [min, max] = self.thumbnail_block();
[min + DVec2::X * LAYER_THUMBNAIL_MARGIN, max - DVec2::X * LAYER_THUMBNAIL_MARGIN]
}
pub fn thumbnail_image(&self) -> [DVec2; 2] {
let [min, max] = self.thumbnail();
[min + LAYER_THUMBNAIL_IMAGE_INSET, max - LAYER_THUMBNAIL_IMAGE_INSET]
}
pub fn stack_output(&self) -> DVec2 {
let [min, max] = self.thumbnail_block();
DVec2::new((min.x + max.x - STACK_CONNECTOR_SIZE.x) / 2., min.y - STACK_CONNECTOR_SIZE.y)
}
pub fn stack_input(&self) -> DVec2 {
let [min, max] = self.thumbnail_block();
DVec2::new((min.x + max.x - STACK_CONNECTOR_SIZE.x) / 2., max.y)
}
pub fn secondary_input_connector(&self) -> DVec2 {
self.geometry().side_input_anchor() + INPUT_CONNECTOR_OFFSET
}
pub fn name_box(&self) -> [DVec2; 2] {
let geometry = self.geometry();
let top_left = DVec2::new(geometry.top_left().x + LAYER_NAME_LEFT, geometry.middle() - GRID_SIZE / 2.);
[top_left, top_left + DVec2::new(geometry.size().x - LAYER_NAME_LEFT - LAYER_DETAILS_MARGIN, GRID_SIZE)]
}
pub fn visibility(&self) -> [DVec2; 2] {
self.geometry().visibility()
}
pub fn grip(&self) -> [DVec2; 2] {
self.geometry().grip()
}
pub fn lock(&self) -> Option<[DVec2; 2]> {
self.geometry().lock()
}
}
impl Placed<Dot> {
fn geometry(&self) -> NodeGeometry {
NodeGeometry {
cell: self.cell,
kind: NodeKind::Waypoint,
chain_length: 0,
shape: self.look.shape.clone(),
}
}
pub fn center(&self) -> DVec2 {
self.geometry().dot_center()
}
}
impl Rows {
fn geometry(&self, node: &NodeId) -> Option<NodeGeometry> {
let card = || self.cards.get(node).map(Placed::<Card>::geometry);
let layer = || self.layers.get(node).map(Placed::<Layer>::geometry);
let dot = || self.dots.get(node).map(Placed::<Dot>::geometry);
card().or_else(layer).or_else(dot)
}
}
pub fn node_geometry(rows: &[&Rows], node: &NodeId) -> Option<NodeGeometry> {
rows.iter().find_map(|rows| rows.geometry(node))
}
pub fn wire_ends(wire: &Wire, rows: &[&Rows], network_connectors: &ReplicatedMap<NetworkConnector>) -> Option<[WireEnd; 2]> {
let from = match wire.from {
OutputKey::Node { node, index } => node_geometry(rows, &node)?.output_end(index)?,
OutputKey::Import(index) => network_connectors.get(&NetworkConnectorKey::Import(index))?.wire_end()?,
};
let to = match wire.to {
InputKey::Node { node, index } => node_geometry(rows, &node)?.input_end(index)?,
InputKey::Export(index) => network_connectors.get(&NetworkConnectorKey::Export(index))?.wire_end()?,
};
Some([from, to])
}
@@ -0,0 +1,94 @@
use crate::layer::LayerButton;
use crate::wire::{InputKey, OutputKey};
use core_types::uuid::NodeId;
use dyn_any::DynAny;
use graphene_hash::CacheHash;
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
pub enum Highlight {
#[default]
None,
Hovered,
WireSource,
WireTarget,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)]
pub enum ConnectorKey {
Input(InputKey),
Output(OutputKey),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, CacheHash)]
pub enum NodePart {
Dot(NodeId),
DotOutput(NodeId),
Visibility(NodeId),
Lock(NodeId),
Grip(NodeId),
ErrorBadge(NodeId),
}
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash, DynAny)]
pub struct Highlights {
pub hovered_connector: Option<ConnectorKey>,
pub dragged_from: Option<ConnectorKey>,
pub snapped_to: Option<ConnectorKey>,
pub hovered_part: Option<NodePart>,
pub pressed_part: Option<NodePart>,
pub clicked: bool,
}
impl Highlights {
pub fn dot(&self, dot: NodeId) -> [Highlight; 2] {
let ends = [
ConnectorKey::Input(InputKey::Node { node: dot, index: 0 }),
ConnectorKey::Output(OutputKey::Node { node: dot, index: 0 }),
];
let body = if self.snapped_to.is_some_and(|key| ends.contains(&key)) {
Highlight::WireTarget
} else if [self.hovered_part, self.pressed_part].contains(&Some(NodePart::Dot(dot))) {
Highlight::Hovered
} else {
Highlight::None
};
let output = if self.dragged_from.is_some_and(|key| ends.contains(&key)) {
Highlight::WireSource
} else if self.hovered_part == Some(NodePart::DotOutput(dot)) {
Highlight::Hovered
} else {
Highlight::None
};
[body, output]
}
pub fn layer_button(&self, layer: NodeId) -> Option<LayerButton> {
match self.hovered_part? {
NodePart::Visibility(node) if node == layer => Some(LayerButton::Visibility),
NodePart::Lock(node) if node == layer => Some(LayerButton::Lock),
NodePart::Grip(node) if node == layer => Some(LayerButton::Grip),
_ => None,
}
}
pub fn connector(&self, key: ConnectorKey) -> Highlight {
let key = Some(key);
if key == self.snapped_to {
Highlight::WireTarget
} else if key == self.hovered_connector {
Highlight::Hovered
} else if key == self.dragged_from {
Highlight::WireSource
} else {
Highlight::None
}
}
pub fn connectors(&self) -> impl Iterator<Item = ConnectorKey> {
[self.hovered_connector, self.dragged_from, self.snapped_to].into_iter().flatten()
}
pub fn badge_hovered(&self, badge: NodeId) -> bool {
self.hovered_part == Some(NodePart::ErrorBadge(badge))
}
}
+71
View File
@@ -0,0 +1,71 @@
use crate::error_badge::ErrorBadge;
use crate::highlights::Highlights;
use crate::network_connector::{NetworkConnector, NetworkConnectorKind};
use crate::replicated_map::ReplicatedMap;
use crate::scene::Rows;
use crate::wire::{WireInProgress, WireStyle};
use core_types::list::Item;
use core_types::registry::Any;
use core_types::uuid::NodeId;
use core_types::{ProtoNodeIdentifier, Type, item};
use glam::DVec2;
use graphene_hash::CacheHash;
use graphic_types::Graphic;
use std::collections::BTreeMap;
use std::sync::Arc;
pub const SETTLED: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-settled");
pub const MOVING: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-moving");
pub const NETWORK_CONNECTORS: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-network-connectors");
pub const ERRORS: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-errors");
pub const THUMBNAILS: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-thumbnails");
pub const WIRE_IN_PROGRESS: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-wire-in-progress");
pub const REORDER_BAR: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-reorder-bar");
pub const BOX_SELECTION: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-box-selection");
pub const FADE_ARTWORK: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-fade-artwork");
pub const WIRE_STYLE: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-wire-style");
pub const HIGHLIGHTS: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-highlights");
pub type Thumbnails = Arc<BTreeMap<NodeId, Graphic>>;
macro_rules! tagged_graph_ui_value {
($($identifier:ident($ty:ty)),* $(,)?) => {
#[derive(Clone, Debug, PartialEq, CacheHash)]
pub enum TaggedGraphUiValue {
$($identifier($ty),)*
}
impl TaggedGraphUiValue {
pub fn to_dynany(self) -> Any {
match self {
$(Self::$identifier(x) => Box::new(Item::new_from_element(x)),)*
}
}
pub fn to_any(self) -> Arc<dyn std::any::Any + Send + Sync> {
match self {
$(Self::$identifier(x) => Arc::new(Item::new_from_element(x)),)*
}
}
pub fn ty(&self) -> Type {
match self {
$(Self::$identifier(_) => item!($ty),)*
}
}
}
};
}
tagged_graph_ui_value! {
Rows(Rows),
NetworkConnectors(ReplicatedMap<NetworkConnector>),
Errors(ReplicatedMap<ErrorBadge>),
Thumbnails(Thumbnails),
WireInProgress(Option<WireInProgress>),
ReorderBar(Option<(NetworkConnectorKind, DVec2)>),
BoxSelection(Option<[DVec2; 2]>),
FadeArtwork(f64),
WireStyle(WireStyle),
Highlights(Highlights),
}
+39
View File
@@ -0,0 +1,39 @@
use crate::card::{Connector, Selection};
use crate::geometry::NodeShape;
use crate::replicated_map::Keyed;
use core_types::uuid::NodeId;
use graphene_hash::CacheHash;
#[derive(Clone, Debug, PartialEq, CacheHash)]
pub struct Layer {
pub key: NodeId,
pub shape: NodeShape,
pub chain_length: u32,
pub name: String,
pub renaming: bool,
pub has_left_input_wire: bool,
pub primary_input: Option<Connector>,
pub primary_output: Option<Connector>,
pub secondary_input: Option<Connector>,
pub primary_input_connected_to_layer: bool,
pub primary_output_connected_to_layer: bool,
pub visible: bool,
pub read_only: bool,
pub selection: Selection,
pub previewed: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
pub enum LayerButton {
Visibility,
Lock,
Grip,
}
impl Keyed for Layer {
type Key = NodeId;
fn key(&self) -> NodeId {
self.key
}
}
+31
View File
@@ -0,0 +1,31 @@
use glam::{DAffine2, DVec2};
use highlights::Highlights;
use network_connector::NetworkConnectorKind;
use wire::{WireInProgress, WireStyle};
pub use inputs::TaggedGraphUiValue;
pub mod card;
pub mod dot;
pub mod error_badge;
pub mod geometry;
pub mod highlights;
pub mod inputs;
pub mod layer;
pub mod metrics;
pub mod network_connector;
pub mod placed;
pub mod replicated_map;
pub mod scene;
pub mod wire;
#[derive(Clone, Copy, Debug)]
pub struct GraphUiConfig {
pub view: DAffine2,
pub fade_artwork: f64,
pub wire_in_progress: Option<WireInProgress>,
pub reorder_bar: Option<(NetworkConnectorKind, DVec2)>,
pub box_selection: Option<[DVec2; 2]>,
pub highlights: Highlights,
pub wire_style: WireStyle,
}
+80
View File
@@ -0,0 +1,80 @@
use glam::DVec2;
pub const GRID_SIZE: f64 = 24.;
pub const GRID_COLLAPSE_SPACING: f64 = 10.;
pub const TEXT_SIZE: f64 = 14.;
pub const BORDER_WIDTH: f64 = 1.;
pub const BORDER_DASHES: [f64; 2] = [3., 2.];
pub const ICON_SIZE: f64 = 16.;
pub const CARD_GRID_WIDTH: u32 = 5;
pub const CARD_RADIUS: f64 = 2.;
pub const CARD_ICON_LEFT: f64 = 8.;
pub const CARD_NAME_LEFT: f64 = 32.;
pub const CARD_NAME_MAX_WIDTH: f64 = 84.;
pub const CARD_ROW_PADDING: f64 = 8.;
pub const CONNECTOR_SIZE: f64 = 8.;
pub const INPUT_CONNECTOR_LEFT: f64 = -3.;
pub const OUTPUT_CONNECTOR_RIGHT: f64 = 5.;
pub const INPUT_CONNECTOR_OFFSET: DVec2 = DVec2::new(INPUT_CONNECTOR_LEFT, -CONNECTOR_SIZE / 2.);
pub const OUTPUT_CONNECTOR_OFFSET: DVec2 = DVec2::new(OUTPUT_CONNECTOR_RIGHT - CONNECTOR_SIZE, -CONNECTOR_SIZE / 2.);
pub const CONNECTOR_GAP: f64 = 16.;
pub const HOVERED_CONNECTOR_SCALE: f64 = 1.3;
pub const HOVERED_CONNECTOR_RING: f64 = 4.;
pub const STACK_CONNECTOR_SIZE: DVec2 = DVec2::new(CONNECTOR_SIZE, 12.);
pub const IMPORT_NAME_INSET: f64 = 8.;
pub const EXPORT_NAME_INSET: f64 = 9.;
pub const NETWORK_CONNECTOR_NAME_RAISE: f64 = 1.;
pub const NETWORK_CONNECTOR_SEPARATOR_OVERHANG: f64 = 4.;
pub const REORDER_BAR_SIZE: DVec2 = DVec2::new(50., 2.);
pub const ERROR_PADDING: f64 = 8.;
pub const ERROR_LINE_HEIGHT: f64 = 18.;
pub const ERROR_MAX_WIDTH: f64 = 600.;
pub const ERROR_RADIUS: f64 = 4.;
pub const ERROR_TAIL_LEFT: f64 = 6.;
pub const ERROR_TAIL_SIZE: DVec2 = DVec2::new(12., 8.);
pub const WIRE_WIDTH: f64 = 2.;
pub const LIST_WIRE_WIDTH: f64 = 4.;
pub const WIRE_DASHES: [f64; 2] = [3., 2.];
pub const THICK_WIRE_WIDTH: f64 = 8.;
pub const DOT_RADIUS: f64 = 5.;
pub const DOT_SELECTED_RING: f64 = 2.;
pub const DOT_PREVIEWED_RING_OFFSET: f64 = 2.;
pub const DOT_HOVERED_RING: f64 = 2.;
pub const DOT_OUTPUT_ARROW: DVec2 = DVec2::new(WAYPOINT_GUTTER_OFFSET - CONNECTOR_SIZE / 2., -CONNECTOR_SIZE / 2.);
pub const LAYER_RADIUS: f64 = 8.;
pub const LAYER_LEFT_MARGIN: f64 = GRID_SIZE / 2.;
pub const LAYER_THUMBNAIL_WIDTH: f64 = 3. * GRID_SIZE;
pub const LAYER_THUMBNAIL_MARGIN: f64 = 1.;
pub const LAYER_THUMBNAIL_RADIUS: f64 = 2.;
pub const LAYER_THUMBNAIL_IMAGE_INSET: f64 = 2.;
pub const LAYER_DETAILS_MARGIN: f64 = 8.;
pub const LAYER_NAME_LEFT: f64 = LAYER_LEFT_MARGIN + LAYER_THUMBNAIL_WIDTH + LAYER_DETAILS_MARGIN;
pub const LAYER_BUTTON_SIZE: f64 = GRID_SIZE;
pub const LAYER_BUTTON_RADIUS: f64 = 2.;
pub const LAYER_GRIP_WIDTH: f64 = 8.;
pub const LAYER_GRIP_DOTS: DVec2 = DVec2::new(2.5, 9.5);
pub const LAYER_GRIP_DOT_COUNT: [u32; 2] = [2, 3];
pub const LAYER_GRIP_DOT_SPACING: f64 = 3.;
pub const LAYER_GRIP_DOT_RADIUS: f64 = 0.5;
pub const LAYER_THUMBNAIL_GAP: DVec2 = DVec2::new(8., 2.);
pub const CHECKER_CELL: f64 = 8.;
pub const CLICK_RADIUS: f64 = 3.;
pub const LAYER_CLICK_RADIUS: f64 = 10.;
pub const PORT_CLICK_RADIUS: f64 = 4.;
pub const SIDE_PORT_OUTWARD_REACH: f64 = 12.;
pub const SIDE_PORT_INWARD_REACH: f64 = 8.;
pub const SIDE_PORT_HALF_HEIGHT: f64 = GRID_SIZE / 2.;
pub const STACK_PORT_HALF_SIZE: DVec2 = DVec2::new(12., 8.);
pub const STACK_ANCHOR_DISTANCE: f64 = 8.;
pub const WAYPOINT_HALF_SIZE: DVec2 = DVec2::new(15., 8.);
pub const WAYPOINT_GUTTER_OFFSET: f64 = 10.;
pub const WAYPOINT_GUTTER_RADIUS: f64 = 5.;
@@ -0,0 +1,111 @@
use crate::card::Connector;
use crate::geometry::WireEnd;
use crate::metrics::{BORDER_WIDTH, EXPORT_NAME_INSET, GRID_SIZE, IMPORT_NAME_INSET, INPUT_CONNECTOR_OFFSET, NETWORK_CONNECTOR_NAME_RAISE, NETWORK_CONNECTOR_SEPARATOR_OVERHANG, REORDER_BAR_SIZE};
use crate::replicated_map::Keyed;
use dyn_any::DynAny;
use glam::{DVec2, IVec2};
use graphene_hash::CacheHash;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash, DynAny)]
pub enum NetworkConnectorKind {
Import,
Export,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum NetworkConnectorKey {
Import(usize),
Export(usize),
}
impl NetworkConnectorKey {
pub fn new(kind: NetworkConnectorKind, index: usize) -> Self {
match kind {
NetworkConnectorKind::Import => Self::Import(index),
NetworkConnectorKind::Export => Self::Export(index),
}
}
pub fn kind(self) -> NetworkConnectorKind {
match self {
Self::Import(_) => NetworkConnectorKind::Import,
Self::Export(_) => NetworkConnectorKind::Export,
}
}
pub fn index(self) -> usize {
match self {
Self::Import(index) | Self::Export(index) => index,
}
}
}
#[derive(Clone, Debug, PartialEq, CacheHash)]
pub struct NetworkConnector {
pub key: NetworkConnectorKey,
pub position: IVec2,
pub connector: Option<Connector>,
pub editable: bool,
pub renaming: bool,
}
impl Keyed for NetworkConnector {
type Key = NetworkConnectorKey;
fn key(&self) -> NetworkConnectorKey {
self.key
}
}
impl NetworkConnector {
pub fn anchor(&self) -> DVec2 {
self.position.as_dvec2()
}
pub(crate) fn wire_end(&self) -> Option<WireEnd> {
let position = self.anchor();
self.connector.is_some().then_some(WireEnd { position, vertical: false })
}
pub fn connector_top_left(&self) -> DVec2 {
self.anchor() + INPUT_CONNECTOR_OFFSET
}
pub fn name_box(&self, width: f64) -> [DVec2; 2] {
network_connector_name_box(self.key.kind(), self.anchor(), width).map(|corner| corner - DVec2::Y * NETWORK_CONNECTOR_NAME_RAISE)
}
pub fn separator(&self, name_width: f64) -> [DVec2; 2] {
let [name_min, name_max] = self.name_box(name_width);
let toward_the_line = if self.key.index() == 0 { GRID_SIZE } else { -GRID_SIZE };
let top = self.anchor().y + toward_the_line - BORDER_WIDTH;
[
DVec2::new(name_min.x - NETWORK_CONNECTOR_SEPARATOR_OVERHANG, top),
DVec2::new(name_max.x + NETWORK_CONNECTOR_SEPARATOR_OVERHANG, top + BORDER_WIDTH),
]
}
}
pub fn reorder_bar(kind: NetworkConnectorKind, anchor: DVec2) -> [DVec2; 2] {
let left = match kind {
NetworkConnectorKind::Import => anchor.x - IMPORT_NAME_INSET - REORDER_BAR_SIZE.x,
NetworkConnectorKind::Export => anchor.x + EXPORT_NAME_INSET,
};
let top_left = DVec2::new(left, anchor.y - GRID_SIZE / 2.);
[top_left, top_left + REORDER_BAR_SIZE]
}
pub fn network_connector_name_box(kind: NetworkConnectorKind, anchor: DVec2, width: f64) -> [DVec2; 2] {
let left = match kind {
NetworkConnectorKind::Import => anchor.x - IMPORT_NAME_INSET - width,
NetworkConnectorKind::Export => anchor.x + EXPORT_NAME_INSET,
};
let top_left = DVec2::new(left, anchor.y - GRID_SIZE / 2.);
[top_left, top_left + DVec2::new(width, GRID_SIZE)]
}
pub fn network_connector_row_offset(index: usize) -> f64 {
let rows = if index == 0 { 0 } else { index + 1 };
rows as f64 * GRID_SIZE
}
+17
View File
@@ -0,0 +1,17 @@
use crate::replicated_map::Keyed;
use glam::IVec2;
use graphene_hash::CacheHash;
#[derive(Clone, Debug, PartialEq, CacheHash)]
pub struct Placed<T> {
pub cell: IVec2,
pub look: T,
}
impl<T: Keyed> Keyed for Placed<T> {
type Key = T::Key;
fn key(&self) -> T::Key {
self.look.key()
}
}
@@ -0,0 +1,185 @@
use dyn_any::StaticType;
use graphene_hash::CacheHash;
use std::fmt::Debug;
use std::hash::{DefaultHasher, Hasher};
use std::ops::Deref;
use std::sync::{Arc, OnceLock};
pub trait Keyed: Clone {
type Key: Ord + Clone + Debug;
fn key(&self) -> Self::Key;
}
#[derive(Clone, Debug)]
pub struct ReplicatedMap<T: Keyed> {
items: Arc<Vec<T>>,
hash: Arc<OnceLock<u64>>,
}
impl<T: Keyed> Default for ReplicatedMap<T> {
fn default() -> Self {
Self {
items: Arc::default(),
hash: Arc::default(),
}
}
}
impl<T: Keyed + PartialEq> PartialEq for ReplicatedMap<T> {
fn eq(&self, other: &Self) -> bool {
self.items == other.items
}
}
unsafe impl<T: Keyed + 'static> StaticType for ReplicatedMap<T> {
type Static = Self;
}
impl<T: Keyed + CacheHash> CacheHash for ReplicatedMap<T> {
fn cache_hash<H: Hasher>(&self, state: &mut H) {
let hash = self.hash.get_or_init(|| {
let mut hasher = DefaultHasher::new();
self.items.cache_hash(&mut hasher);
hasher.finish()
});
state.write_u64(*hash);
}
}
impl<T: Keyed> ReplicatedMap<T> {
pub fn get(&self, key: &T::Key) -> Option<&T> {
self.position(key).ok().map(|index| &self.items[index])
}
pub fn iter(&self) -> std::slice::Iter<'_, T> {
self.items.iter()
}
pub fn len(&self) -> usize {
self.items.len()
}
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
pub fn edit(self) -> ReplicatedMapEdit<T> {
ReplicatedMapEdit { map: self, deltas: Vec::new() }
}
pub fn apply(&mut self, deltas: impl IntoIterator<Item = ReplicatedMapDelta<T>>) {
for delta in deltas {
match delta {
ReplicatedMapDelta::Put(item) => self.put(item),
ReplicatedMapDelta::Remove(key) => {
let removed = self.remove(&key);
debug_assert!(removed, "a delta removes an item that its map never held");
}
}
}
}
fn position(&self, key: &T::Key) -> Result<usize, usize> {
self.items.binary_search_by(|item| item.key().cmp(key))
}
fn items_mut(&mut self) -> &mut Vec<T> {
self.hash = Arc::default();
Arc::make_mut(&mut self.items)
}
fn put(&mut self, item: T) {
match self.position(&item.key()) {
Ok(index) => self.items_mut()[index] = item,
Err(index) => self.items_mut().insert(index, item),
}
}
fn remove(&mut self, key: &T::Key) -> bool {
let position = self.position(key);
if let Ok(index) = position {
self.items_mut().remove(index);
}
position.is_ok()
}
}
impl<'a, T: Keyed> IntoIterator for &'a ReplicatedMap<T> {
type Item = &'a T;
type IntoIter = std::slice::Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
#[derive(Clone, Debug)]
pub enum ReplicatedMapDelta<T: Keyed> {
Put(T),
Remove(T::Key),
}
#[derive(Debug)]
pub struct ReplicatedMapEdit<T: Keyed> {
map: ReplicatedMap<T>,
deltas: Vec<ReplicatedMapDelta<T>>,
}
impl<T: Keyed> Deref for ReplicatedMapEdit<T> {
type Target = ReplicatedMap<T>;
fn deref(&self) -> &Self::Target {
&self.map
}
}
impl<T: Keyed> ReplicatedMapEdit<T> {
pub fn put(&mut self, item: T)
where
T: PartialEq,
{
if self.map.get(&item.key()) == Some(&item) {
return;
}
self.map.put(item.clone());
self.deltas.push(ReplicatedMapDelta::Put(item));
}
pub fn update(&mut self, key: &T::Key, change: impl FnOnce(&mut T)) -> bool {
let Ok(index) = self.map.position(key) else { return false };
let item = &mut self.map.items_mut()[index];
change(item);
debug_assert!(item.key() == *key, "an update must not change the key of its item");
self.deltas.push(ReplicatedMapDelta::Put(item.clone()));
true
}
pub fn remove(&mut self, key: &T::Key) -> bool {
let removed = self.map.remove(key);
if removed {
self.deltas.push(ReplicatedMapDelta::Remove(key.clone()));
}
removed
}
pub fn replace_all(&mut self, items: impl IntoIterator<Item = T>)
where
T: PartialEq,
{
let mut items: Vec<T> = items.into_iter().collect();
items.sort_by_key(T::key);
debug_assert!(items.windows(2).all(|pair| pair[0].key() != pair[1].key()), "two items of a map share a key");
let removed = self.map.iter().rev().map(T::key).filter(|key| items.binary_search_by(|item| item.key().cmp(key)).is_err());
self.deltas.extend(removed.map(ReplicatedMapDelta::Remove));
let put = items.iter().filter(|item| self.map.get(&item.key()) != Some(item));
self.deltas.extend(put.cloned().map(ReplicatedMapDelta::Put));
*self.map.items_mut() = items;
}
pub fn finish(self) -> (ReplicatedMap<T>, Vec<ReplicatedMapDelta<T>>) {
(self.map, self.deltas)
}
}
+161
View File
@@ -0,0 +1,161 @@
use crate::card::Card;
use crate::dot::Dot;
use crate::error_badge::ErrorBadge;
use crate::layer::Layer;
use crate::network_connector::NetworkConnector;
use crate::placed::Placed;
use crate::replicated_map::{ReplicatedMap, ReplicatedMapDelta, ReplicatedMapEdit};
use crate::wire::Wire;
use dyn_any::DynAny;
use graphene_hash::CacheHash;
#[derive(Clone, Debug, Default, PartialEq, CacheHash, DynAny)]
pub struct Rows {
pub cards: ReplicatedMap<Placed<Card>>,
pub layers: ReplicatedMap<Placed<Layer>>,
pub dots: ReplicatedMap<Placed<Dot>>,
pub wires: ReplicatedMap<Wire>,
}
impl Rows {
fn edit(self) -> RowsEdit {
RowsEdit {
cards: self.cards.edit(),
layers: self.layers.edit(),
dots: self.dots.edit(),
wires: self.wires.edit(),
}
}
fn apply(&mut self, delta: RowsDelta) {
self.cards.apply(delta.cards);
self.layers.apply(delta.layers);
self.dots.apply(delta.dots);
self.wires.apply(delta.wires);
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct GraphUiScene {
settled: Rows,
moving: Rows,
network_connectors: ReplicatedMap<NetworkConnector>,
errors: ReplicatedMap<ErrorBadge>,
}
impl GraphUiScene {
pub fn settled(&self) -> &Rows {
&self.settled
}
pub fn moving(&self) -> &Rows {
&self.moving
}
pub fn network_connectors(&self) -> &ReplicatedMap<NetworkConnector> {
&self.network_connectors
}
pub fn errors(&self) -> &ReplicatedMap<ErrorBadge> {
&self.errors
}
pub fn edit(self) -> GraphUiSceneEdit {
GraphUiSceneEdit {
settled: self.settled.edit(),
moving: self.moving.edit(),
network_connectors: self.network_connectors.edit(),
errors: self.errors.edit(),
}
}
pub fn apply(&mut self, delta: GraphUiSceneDelta) {
self.settled.apply(delta.settled);
self.moving.apply(delta.moving);
self.network_connectors.apply(delta.network_connectors);
self.errors.apply(delta.errors);
}
}
pub struct RowsEdit {
pub cards: ReplicatedMapEdit<Placed<Card>>,
pub layers: ReplicatedMapEdit<Placed<Layer>>,
pub dots: ReplicatedMapEdit<Placed<Dot>>,
pub wires: ReplicatedMapEdit<Wire>,
}
impl RowsEdit {
fn finish(self) -> (Rows, RowsDelta) {
let (cards, card_deltas) = self.cards.finish();
let (layers, layer_deltas) = self.layers.finish();
let (dots, dot_deltas) = self.dots.finish();
let (wires, wire_deltas) = self.wires.finish();
(
Rows { cards, layers, dots, wires },
RowsDelta {
cards: card_deltas,
layers: layer_deltas,
dots: dot_deltas,
wires: wire_deltas,
},
)
}
}
pub struct GraphUiSceneEdit {
pub settled: RowsEdit,
pub moving: RowsEdit,
pub network_connectors: ReplicatedMapEdit<NetworkConnector>,
pub errors: ReplicatedMapEdit<ErrorBadge>,
}
impl GraphUiSceneEdit {
pub fn finish(self) -> (GraphUiScene, GraphUiSceneDelta) {
let (settled, settled_delta) = self.settled.finish();
let (moving, moving_delta) = self.moving.finish();
let (network_connectors, network_connector_deltas) = self.network_connectors.finish();
let (errors, error_deltas) = self.errors.finish();
(
GraphUiScene {
settled,
moving,
network_connectors,
errors,
},
GraphUiSceneDelta {
settled: settled_delta,
moving: moving_delta,
network_connectors: network_connector_deltas,
errors: error_deltas,
},
)
}
}
#[derive(Debug)]
struct RowsDelta {
cards: Vec<ReplicatedMapDelta<Placed<Card>>>,
layers: Vec<ReplicatedMapDelta<Placed<Layer>>>,
dots: Vec<ReplicatedMapDelta<Placed<Dot>>>,
wires: Vec<ReplicatedMapDelta<Wire>>,
}
impl RowsDelta {
fn is_empty(&self) -> bool {
self.cards.is_empty() && self.layers.is_empty() && self.dots.is_empty() && self.wires.is_empty()
}
}
#[derive(Debug)]
pub struct GraphUiSceneDelta {
settled: RowsDelta,
moving: RowsDelta,
network_connectors: Vec<ReplicatedMapDelta<NetworkConnector>>,
errors: Vec<ReplicatedMapDelta<ErrorBadge>>,
}
impl GraphUiSceneDelta {
pub fn is_empty(&self) -> bool {
self.settled.is_empty() && self.moving.is_empty() && self.network_connectors.is_empty() && self.errors.is_empty()
}
}
+57
View File
@@ -0,0 +1,57 @@
use crate::card::DataType;
use crate::geometry::WireEnd;
use crate::replicated_map::Keyed;
use core_types::uuid::NodeId;
use dyn_any::DynAny;
use graphene_hash::CacheHash;
#[derive(Clone, Debug, PartialEq, CacheHash)]
pub struct Wire {
pub key: WireKey,
pub from: OutputKey,
pub to: InputKey,
pub data_type: DataType,
pub list: bool,
pub insertion_target: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)]
pub enum WireKey {
Input(InputKey),
Preview,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)]
pub enum OutputKey {
Node { node: NodeId, index: usize },
Import(usize),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)]
pub enum InputKey {
Node { node: NodeId, index: usize },
Export(usize),
}
impl Keyed for Wire {
type Key = WireKey;
fn key(&self) -> WireKey {
self.key
}
}
#[derive(Clone, Copy, Debug, PartialEq, CacheHash, DynAny)]
pub struct WireInProgress {
pub ends: [WireEnd; 2],
pub data_type: DataType,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Copy, Clone, Debug, PartialEq, Default, CacheHash, DynAny)]
pub enum WireStyle {
#[default]
Direct = 0,
GridAligned = 1,
}
+1 -1
View File
@@ -128,7 +128,7 @@ pub async fn compile_document(document: OpenedDocument) -> Result<CompiledDocume
impl CompiledDocument { impl CompiledDocument {
pub fn into_renderer(self) -> Result<Renderer, Box<dyn Error>> { pub fn into_renderer(self) -> Result<Renderer, Box<dyn Error>> {
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(self.proto_network).map_err(|(_, errors)| { let output = executor.insert(self.proto_network).map_err(|errors| {
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect(); let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
messages.join("\n") messages.join("\n")
})?; })?;
+3 -3
View File
@@ -133,13 +133,13 @@ impl Viewer {
Err(error) => return log::error!("Compile failed: {error}"), Err(error) => return log::error!("Compile failed: {error}"),
}; };
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
match executor.update(proto) { match executor.insert(proto) {
Ok((output, _)) => { Ok(output) => {
self.graph_runtime.update_sources(executor.sources()); self.graph_runtime.update_sources(executor.sources());
log::info!("Document compiled"); log::info!("Document compiled");
self.executor = Some((executor, output)); self.executor = Some((executor, output));
} }
Err((_, errors)) => { Err(errors) => {
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect(); let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
log::error!("Executor creation failed: {}", messages.join("\n")); log::error!("Executor creation failed: {}", messages.join("\n"));
} }
@@ -18,7 +18,7 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, OutputHandle, ProtoNetwork
preprocessor.preprocess(&mut network, &|_| None).unwrap(); preprocessor.preprocess(&mut network, &|_| None).unwrap();
let proto_network = compile(network); let proto_network = compile(network);
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(proto_network.clone()).unwrap(); let output = executor.insert(proto_network.clone()).unwrap();
(executor, output, proto_network) (executor, output, proto_network)
} }
@@ -73,7 +73,7 @@ impl Session {
let mut network = wrap_network_with_render_node_in_scope(document, self.editor_api.clone(), self.runtime.handle()); let mut network = wrap_network_with_render_node_in_scope(document, self.editor_api.clone(), self.runtime.handle());
self.preprocessor.preprocess(&mut network, &|_| None).expect("Failed to preprocess the document"); self.preprocessor.preprocess(&mut network, &|_| None).expect("Failed to preprocess the document");
let proto_network = Compiler {}.compile_single(network).expect("Failed to compile the document").network; let proto_network = Compiler {}.compile_single(network).expect("Failed to compile the document").network;
(self.output, _) = self.executor.update(proto_network).expect("Failed to update the executor"); self.output = self.executor.insert(proto_network).expect("Failed to update the executor");
let render_config = RenderConfig { let render_config = RenderConfig {
viewport: Footprint { viewport: Footprint {
@@ -16,7 +16,7 @@ fn update_executor<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
c.bench_function(name, |b| { c.bench_function(name, |b| {
b.iter_batched( b.iter_batched(
|| (executor.clone(), proto_network.clone()), || (executor.clone(), proto_network.clone()),
|(mut executor, network)| executor.update(std::hint::black_box(network)), |(mut executor, network)| executor.insert(std::hint::black_box(network)),
criterion::BatchSize::SmallInput, criterion::BatchSize::SmallInput,
) )
}); });
@@ -36,7 +36,7 @@ fn run_once<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
let proto_network = compile(network); let proto_network = compile(network);
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(proto_network).unwrap(); let output = executor.insert(proto_network).unwrap();
let footprint = Footprint::default(); let footprint = Footprint::default();
c.bench_function(name, |b| b.iter(|| executor.execute(&output, footprint))); c.bench_function(name, |b| b.iter(|| executor.execute(&output, footprint)));
@@ -13,7 +13,7 @@ fn update_executor(c: &mut Criterion) {
let (_, _, proto_network) = setup_network(name); let (_, _, proto_network) = setup_network(name);
(DynamicExecutor::default(), proto_network) (DynamicExecutor::default(), proto_network)
}, },
|(mut executor, network)| executor.update(std::hint::black_box(network)), |(mut executor, network)| executor.insert(std::hint::black_box(network)),
criterion::BatchSize::SmallInput, criterion::BatchSize::SmallInput,
) )
}); });
@@ -15,7 +15,7 @@ fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_update_executor)] #[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_update_executor)]
pub fn update_executor(setup: (DynamicExecutor, ProtoNetwork)) -> DynamicExecutor { pub fn update_executor(setup: (DynamicExecutor, ProtoNetwork)) -> DynamicExecutor {
let (mut executor, network) = setup; let (mut executor, network) = setup;
let _ = black_box(executor.update(black_box(network))); let _ = black_box(executor.insert(black_box(network)));
// Return the executor so its teardown happens outside the measured section // Return the executor so its teardown happens outside the measured section
executor executor
@@ -19,8 +19,7 @@ pub struct DynamicExecutor {
typing_context: TypingContext, typing_context: TypingContext,
/// The outputs of the networks, kept alive by the executor as long as there are handles to them. /// The outputs of the networks, kept alive by the executor as long as there are handles to them.
outputs: Vec<Weak<NodeId>>, outputs: Vec<Weak<NodeId>>,
// Kept for one more update, so a node that comes back is reused type_deltas: TypeDeltaCollector,
orphaned_nodes: HashSet<NodeId>,
} }
#[derive(Clone, Debug, Default)] #[derive(Clone, Debug, Default)]
@@ -38,7 +37,7 @@ impl Default for DynamicExecutor {
tree: Default::default(), tree: Default::default(),
typing_context: TypingContext::new(&node_registry::NODE_REGISTRY), typing_context: TypingContext::new(&node_registry::NODE_REGISTRY),
outputs: Vec::new(), outputs: Vec::new(),
orphaned_nodes: HashSet::new(), type_deltas: Default::default(),
} }
} }
} }
@@ -64,19 +63,37 @@ impl DynamicExecutor {
/// Adds the [`ProtoNetwork`] to the existing [`BorrowTree`], reusing nodes where possible. /// Adds the [`ProtoNetwork`] to the existing [`BorrowTree`], reusing nodes where possible.
#[cfg_attr(debug_assertions, inline(never))] #[cfg_attr(debug_assertions, inline(never))]
pub fn update(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> { pub fn insert(&mut self, proto_network: ProtoNetwork) -> Result<OutputHandle, GraphErrors> {
let (output, add) = self.insert_nodes(proto_network)?; let output = self.insert_nodes(proto_network)?;
let remove = self.free_orphaned_nodes(); self.free_orphaned_nodes();
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove })) Ok(output)
} }
pub fn update_without_freeing(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> { pub fn replace(&mut self, output: OutputHandle, proto_network: ProtoNetwork) -> Result<OutputHandle, GraphErrors> {
let (output, add) = self.insert_nodes(proto_network)?; let inserted = self.insert_nodes(proto_network)?;
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() })) let Some(replaced) = Arc::into_inner(output.0) else { return Ok(inserted) };
let live: Vec<NodeId> = self.outputs.iter().filter_map(Weak::upgrade).map(|output| *output).collect();
let mut pending = vec![replaced];
while let Some(node) = pending.pop() {
let Some((container, _, inputs)) = self.tree.nodes.get(&node) else { continue };
if Arc::strong_count(container) > 1 || live.contains(&node) {
continue;
}
pending.extend(inputs.iter());
if let Some(path) = self.tree.free_node(node) {
self.type_deltas.remove(path);
}
self.typing_context.remove_inference(node);
}
Ok(inserted)
} }
fn insert_nodes(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, Vec<(Path, NodeTypes)>), (ResolvedDocumentNodeTypesDelta, GraphErrors)> { pub fn take_type_deltas(&mut self) -> Option<ResolvedDocumentNodeTypesDelta> {
self.typing_context.update(&proto_network).map_err(|e| { self.type_deltas.take()
}
fn insert_nodes(&mut self, proto_network: ProtoNetwork) -> Result<OutputHandle, GraphErrors> {
self.typing_context.update(&proto_network).inspect_err(|_| {
// If there is an error then get types that have been resolved before the error // If there is an error then get types that have been resolved before the error
let add = proto_network let add = proto_network
.nodes .nodes
@@ -94,11 +111,13 @@ impl DynamicExecutor {
) )
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
(ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }, e) self.type_deltas.add(add);
})?; })?;
let output = proto_network.output; let output = proto_network.output;
let add = self.tree.update(proto_network, &self.typing_context).map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
let add = self.tree.update(proto_network, &self.typing_context)?;
self.outputs.retain(|output| output.strong_count() > 0); self.outputs.retain(|output| output.strong_count() > 0);
let held = self.outputs.iter().filter_map(Weak::upgrade).find(|held| **held == output); let held = self.outputs.iter().filter_map(Weak::upgrade).find(|held| **held == output);
let output = held.unwrap_or_else(|| { let output = held.unwrap_or_else(|| {
@@ -107,11 +126,11 @@ impl DynamicExecutor {
output output
}); });
let add = self.document_node_types(add.into_iter()).collect(); self.type_deltas.add(self.tree.node_types(add.into_iter()));
Ok((OutputHandle(output), add)) Ok(OutputHandle(output))
} }
fn free_orphaned_nodes(&mut self) -> Vec<Path> { fn free_orphaned_nodes(&mut self) {
let mut kept = HashSet::new(); let mut kept = HashSet::new();
let mut pending: Vec<NodeId> = self.outputs.iter().filter_map(Weak::upgrade).map(|output| *output).collect(); let mut pending: Vec<NodeId> = self.outputs.iter().filter_map(Weak::upgrade).map(|output| *output).collect();
while let Some(node) = pending.pop() { while let Some(node) = pending.pop() {
@@ -121,19 +140,14 @@ impl DynamicExecutor {
pending.extend(inputs.iter()); pending.extend(inputs.iter());
} }
} }
let orphaned = self.tree.nodes.keys().filter(|node| !kept.contains(node)).copied().collect(); let orphaned: Vec<NodeId> = self.tree.nodes.keys().filter(|node| !kept.contains(node)).copied().collect();
let old_to_remove = core::mem::replace(&mut self.orphaned_nodes, orphaned); for node_id in orphaned {
let mut remove = Vec::with_capacity(old_to_remove.len() - self.orphaned_nodes.len().min(old_to_remove.len())); let path = self.tree.free_node(node_id);
for node_id in old_to_remove { self.typing_context.remove_inference(node_id);
if self.orphaned_nodes.contains(&node_id) { if let Some(path) = path {
let path = self.tree.free_node(node_id); self.type_deltas.remove(path);
self.typing_context.remove_inference(node_id);
if let Some(path) = path {
remove.push(path);
}
} }
} }
remove
} }
pub fn execute<I: 'static + WasmNotSend>(&self, output: &OutputHandle, input: I) -> Result<Poll<TaggedValue>, Box<dyn Error>> { pub fn execute<I: 'static + WasmNotSend>(&self, output: &OutputHandle, input: I) -> Result<Poll<TaggedValue>, Box<dyn Error>> {
@@ -153,7 +167,7 @@ impl DynamicExecutor {
} }
pub fn document_node_types<'a>(&'a self, nodes: impl Iterator<Item = Path> + 'a) -> impl Iterator<Item = (Path, NodeTypes)> + 'a { pub fn document_node_types<'a>(&'a self, nodes: impl Iterator<Item = Path> + 'a) -> impl Iterator<Item = (Path, NodeTypes)> + 'a {
nodes.flat_map(|id| self.tree.source_map().get(&id).map(|(_, b)| (id, b.clone()))) self.tree.node_types(nodes)
// TODO: https://github.com/GraphiteEditor/Graphite/issues/1767 // TODO: https://github.com/GraphiteEditor/Graphite/issues/1767
// TODO: Non exposed inputs are not added to the inputs_source_map, so they are not included in the resolved_document_node_types. The type is still available in the typing_context. This only affects the UI-only "Import" node. // TODO: Non exposed inputs are not added to the inputs_source_map, so they are not included in the resolved_document_node_types. The type is still available in the typing_context. This only affects the UI-only "Import" node.
} }
@@ -559,6 +573,39 @@ impl BorrowTree {
pub fn source_map(&self) -> &HashMap<Path, (NodeId, NodeTypes)> { pub fn source_map(&self) -> &HashMap<Path, (NodeId, NodeTypes)> {
&self.source_map &self.source_map
} }
pub fn node_types<'a>(&'a self, nodes: impl Iterator<Item = Path> + 'a) -> impl Iterator<Item = (Path, NodeTypes)> + 'a {
nodes.flat_map(|id| self.source_map().get(&id).map(|(_, b)| (id, b.clone())))
}
}
#[derive(Clone, Default)]
struct TypeDeltaCollector {
changes: HashMap<Path, Option<NodeTypes>>,
}
impl TypeDeltaCollector {
fn add(&mut self, types: impl IntoIterator<Item = (Path, NodeTypes)>) {
self.changes.extend(types.into_iter().map(|(path, types)| (path, Some(types))));
}
fn remove(&mut self, path: Path) {
self.changes.insert(path, None);
}
fn take(&mut self) -> Option<ResolvedDocumentNodeTypesDelta> {
if self.changes.is_empty() {
return None;
}
let mut delta = ResolvedDocumentNodeTypesDelta::default();
for (path, types) in self.changes.drain() {
match types {
Some(types) => delta.add.push((path, types)),
None => delta.remove.push(path),
}
}
Some(delta)
}
} }
#[cfg(test)] #[cfg(test)]
@@ -876,7 +876,7 @@ fn error_traced_through(indices: &[usize]) -> NodeError {
#[test] #[test]
fn a_trace_leads_to_the_node_that_raised_the_error() { fn a_trace_leads_to_the_node_that_raised_the_error() {
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap(); let output = executor.insert(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
assert!(executor.trace_error(output.node(), &error_traced_through(&[])).is_empty()); assert!(executor.trace_error(output.node(), &error_traced_through(&[])).is_empty());
assert_eq!(*executor.trace_error(output.node(), &error_traced_through(&[0])), [NodeId(0)]); assert_eq!(*executor.trace_error(output.node(), &error_traced_through(&[0])), [NodeId(0)]);
@@ -899,7 +899,7 @@ fn a_trace_steps_over_the_index_of_a_promotion_adapter() {
nodes: vec![(NodeId(0), value_node), (NodeId(1), box_corners_node)], nodes: vec![(NodeId(0), value_node), (NodeId(1), box_corners_node)],
}; };
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(network).unwrap(); let output = executor.insert(network).unwrap();
assert_eq!(*executor.trace_error(output.node(), &error_traced_through(&[0, 0])), [NodeId(0)]); assert_eq!(*executor.trace_error(output.node(), &error_traced_through(&[0, 0])), [NodeId(0)]);
} }
@@ -936,7 +936,7 @@ fn chained_fallbacks_both_reach_the_root() {
.concat(), .concat(),
}; };
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(network).unwrap(); let output = executor.insert(network).unwrap();
let context: Context = None; let context: Context = None;
let Ok(Poll::Fallback(boxed)) = executor.execute(&output, context) else { let Ok(Poll::Fallback(boxed)) = executor.execute(&output, context) else {
@@ -966,7 +966,7 @@ fn an_error_after_a_fallback_keeps_both() {
.concat(), .concat(),
}; };
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(network).unwrap(); let output = executor.insert(network).unwrap();
let context: Context = None; let context: Context = None;
let Ok(Poll::Error(error)) = executor.execute(&output, context) else { let Ok(Poll::Error(error)) = executor.execute(&output, context) else {
@@ -995,7 +995,7 @@ fn a_node_error_names_the_node_that_raised_it() {
.concat(), .concat(),
}; };
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(network).expect("The Throw Error nodes should resolve"); let output = executor.insert(network).expect("The Throw Error nodes should resolve");
let context: Context = None; let context: Context = None;
let Ok(Poll::Error(error)) = executor.execute(&output, context) else { let Ok(Poll::Error(error)) = executor.execute(&output, context) else {
@@ -1050,7 +1050,7 @@ fn handled_error_network(handler: ProtoNodeIdentifier, handler_inputs: &[u64], k
.concat(), .concat(),
}; };
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(network).expect("The error handling nodes should resolve"); let output = executor.insert(network).expect("The error handling nodes should resolve");
(executor, output) (executor, output)
} }
@@ -1190,16 +1190,6 @@ fn source_network(node: u64) -> ProtoNetwork {
} }
} }
#[test]
fn update_without_freeing_keeps_the_nodes_the_network_leaves_out() {
let mut executor = DynamicExecutor::default();
executor.update(source_network(0)).unwrap();
executor.update_without_freeing(source_network(1)).unwrap();
executor.update_without_freeing(source_network(1)).unwrap();
assert!(executor.tree().get(NodeId(0)).is_some());
}
#[test] #[test]
fn networks_are_executed_side_by_side_by_their_handles() { fn networks_are_executed_side_by_side_by_their_handles() {
let network = |node: u64| ProtoNetwork { let network = |node: u64| ProtoNetwork {
@@ -1208,8 +1198,8 @@ fn networks_are_executed_side_by_side_by_their_handles() {
nodes: vec![value_node(node, TaggedValue::Number(node as f64))], nodes: vec![value_node(node, TaggedValue::Number(node as f64))],
}; };
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (first, _) = executor.update(network(0)).unwrap(); let first = executor.insert(network(0)).unwrap();
let (second, _) = executor.update(network(1)).unwrap(); let second = executor.insert(network(1)).unwrap();
let context: Context = None; let context: Context = None;
assert_eq!(executor.execute(&first, context.clone()).unwrap(), Poll::Final(TaggedValue::Number(0.))); assert_eq!(executor.execute(&first, context.clone()).unwrap(), Poll::Final(TaggedValue::Number(0.)));
@@ -1219,9 +1209,9 @@ fn networks_are_executed_side_by_side_by_their_handles() {
#[test] #[test]
fn an_output_that_is_already_held_shares_its_handle() { fn an_output_that_is_already_held_shares_its_handle() {
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (first, _) = executor.update(source_network(0)).unwrap(); let first = executor.insert(source_network(0)).unwrap();
let (second, _) = executor.update(source_network(0)).unwrap(); let second = executor.insert(source_network(0)).unwrap();
let (other, _) = executor.update(source_network(1)).unwrap(); let other = executor.insert(source_network(1)).unwrap();
assert!(Arc::ptr_eq(&first.0, &second.0)); assert!(Arc::ptr_eq(&first.0, &second.0));
assert!(!Arc::ptr_eq(&first.0, &other.0)); assert!(!Arc::ptr_eq(&first.0, &other.0));
@@ -1230,28 +1220,123 @@ fn an_output_that_is_already_held_shares_its_handle() {
#[test] #[test]
fn a_handle_keeps_its_output_and_the_nodes_that_feed_it() { fn a_handle_keeps_its_output_and_the_nodes_that_feed_it() {
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap(); let output = executor.insert(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
let kept = |executor: &DynamicExecutor| [0, 1].map(|node| executor.tree().get(NodeId(node)).is_some()); let kept = |executor: &DynamicExecutor| [0, 1].map(|node| executor.tree().get(NodeId(node)).is_some());
for _ in 0..3 { for _ in 0..3 {
executor.update(source_network(2)).unwrap(); executor.insert(source_network(2)).unwrap();
} }
assert_eq!(kept(&executor), [true; 2]); assert_eq!(kept(&executor), [true; 2]);
drop(output); drop(output);
executor.update(source_network(2)).unwrap(); executor.insert(source_network(2)).unwrap();
assert_eq!(kept(&executor), [true; 2], "orphaned for one more update");
executor.update(source_network(2)).unwrap();
assert_eq!(kept(&executor), [false; 2]); assert_eq!(kept(&executor), [false; 2]);
} }
#[test] #[test]
fn a_source_is_listed_for_as_long_as_its_node_lives() { fn a_source_is_listed_for_as_long_as_its_node_lives() {
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
executor.update(source_network(0)).unwrap(); let output = executor.insert(source_network(0)).unwrap();
let listed = |executor: &DynamicExecutor| executor.sources().any(|source| *source == SourceId(0));
for _ in 0..3 { executor.insert(source_network(1)).unwrap();
executor.update(source_network(1)).unwrap(); assert!(listed(&executor));
assert_eq!(executor.sources().any(|source| *source == SourceId(0)), executor.tree().get(NodeId(0)).is_some());
drop(output);
executor.insert(source_network(1)).unwrap();
assert!(!listed(&executor));
}
fn changed_paths(executor: &mut DynamicExecutor) -> Option<[Vec<u64>; 2]> {
let changes = executor.take_type_deltas()?;
let added = changes.add.iter().map(|(path, _)| path[0].0);
let removed = changes.remove.iter().map(|path| path[0].0);
let mut paths = [added.collect::<Vec<_>>(), removed.collect()];
paths.iter_mut().for_each(|paths| paths.sort_unstable());
Some(paths)
}
#[test]
fn take_type_deltas_gives_the_paths_inserted_and_freed_since_the_last_take() {
let mut executor = DynamicExecutor::default();
let held = [executor.insert(source_network(0)).unwrap(), executor.insert(source_network(1)).unwrap()];
assert_eq!(changed_paths(&mut executor), Some([vec![0, 1], vec![]]));
assert_eq!(changed_paths(&mut executor), None);
drop(held);
executor.insert(source_network(2)).unwrap();
assert_eq!(changed_paths(&mut executor), Some([vec![2], vec![0, 1]]));
}
#[test]
fn a_path_freed_and_inserted_again_between_two_takes_is_given_with_its_types() {
let mut executor = DynamicExecutor::default();
executor.insert(source_network(0)).unwrap();
executor.take_type_deltas();
executor.insert(source_network(1)).unwrap();
executor.insert(source_network(0)).unwrap();
let path: Path = [NodeId(0)].into();
let types = executor.tree().source_map()[&path].1.clone();
assert_eq!(executor.take_type_deltas().unwrap().add, [(path, types)]);
}
#[test]
fn a_path_typed_before_a_type_error_is_given() {
let mut executor = DynamicExecutor::default();
executor.insert(bounding_box_network(TaggedValue::Number(1.))).unwrap_err();
assert_eq!(changed_paths(&mut executor), Some([vec![0], vec![]]));
}
#[test]
fn replace_frees_what_only_the_replaced_output_reached() {
let mut executor = DynamicExecutor::default();
let replaced = executor.insert(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
executor.replace(replaced, source_network(2)).unwrap();
for node in [NodeId(0), NodeId(1)] {
assert!(executor.tree().get(node).is_none());
assert!(executor.typing_context.type_of(node).is_none());
}
let delta = executor.take_type_deltas().unwrap();
let mut removed: Vec<_> = delta.remove.iter().map(|path| path.to_vec()).collect();
removed.sort();
assert_eq!(removed, [vec![NodeId(0)], vec![NodeId(1)]]);
assert_eq!(executor.tree().source_map().keys().map(|path| path.to_vec()).collect::<Vec<_>>(), [vec![NodeId(2)]]);
}
#[test]
fn replace_keeps_what_the_new_network_or_another_output_still_reaches() {
let content = TaggedValue::TypeDefault(item!(Vector));
let value_network = |(output, node)| ProtoNetwork {
inputs: vec![],
output,
nodes: vec![(output, node)],
};
let mut executor = DynamicExecutor::default();
let _document = executor.insert(value_network(value_node(0, content.clone()))).unwrap();
let replaced = executor.insert(offset_points_network(content)).unwrap();
executor.replace(replaced, value_network(value_node(1, TaggedValue::Number(10.)))).unwrap();
assert_eq!([0, 1, 2, 3].map(|node| executor.tree().get(NodeId(node)).is_some()), [true, true, false, false]);
}
#[test]
fn replace_frees_nothing_while_the_replaced_handle_is_held_elsewhere() {
let mut executor = DynamicExecutor::default();
let held = executor.insert(source_network(0)).unwrap();
executor.replace(held.clone(), source_network(1)).unwrap();
assert!(executor.tree().get(NodeId(0)).is_some());
}
#[test]
fn repeated_replacing_keeps_the_node_count_and_the_source_map_size_constant() {
let mut executor = DynamicExecutor::default();
let mut output = executor.insert(source_network(0)).unwrap();
for node in 1..=4 {
output = executor.replace(output, source_network(node)).unwrap();
assert_eq!([executor.tree().nodes.len(), executor.tree().source_map().len()], [1, 1]);
} }
} }
+1 -1
View File
@@ -49,6 +49,6 @@ mod tests {
let compiler = Compiler {}; let compiler = Compiler {};
let protograph = compiler.compile_single(network).expect("Graph should be generated").network; let protograph = compiler.compile_single(network).expect("Graph should be generated").network;
let _exec = DynamicExecutor::default().update(protograph).map(|_e| panic!("The network should not type check ")).unwrap_err(); let _exec = DynamicExecutor::default().insert(protograph).map(|_e| panic!("The network should not type check ")).unwrap_err();
} }
} }
@@ -155,14 +155,24 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
) )
}; };
} }
// Keeps an adapter row under the identifier the preprocessor names it by and repeats it under the adapter node's own identifier,
// which the new compiler selects by signature
macro_rules! also_under_own_identifier {
($module:ident, $row:expr) => {{
let row: (ProtoNodeIdentifier, NodeConstructor, NodeIOTypes) = $row;
let own = (graphene_core::ops::$module::IDENTIFIER, row.1, row.2.clone());
[row, own]
}};
}
// A conversion row registered under the same `input_adapter<$element>` identifier so a convertible-but-not-identical // A conversion row registered under the same `input_adapter<$element>` identifier so a convertible-but-not-identical
// ranked wire can feed an `Item<$element>` connector, converting each element via `Into` // ranked wire can feed an `Item<$element>` connector, converting each element via `Into`
macro_rules! input_adapter_row { macro_rules! input_adapter_row {
(from_element: $from:ty, element: $element:ty) => {{ (from_element: $from:ty, element: $element:ty) => {{
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![ let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
input_adapter_row!(node: IntoItemNode, from: Item<$from>, to: Item<$element>, element: $element), also_under_own_identifier!(into_item, input_adapter_row!(node: IntoItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
input_adapter_row!(node: IntoListNode, from: List<$from>, to: List<$element>, element: $element), also_under_own_identifier!(into_list, input_adapter_row!(node: IntoListNode, from: List<$from>, to: List<$element>, element: $element)),
]; ]
.concat();
entries entries
}}; }};
(node: $node:ident, from: $from:ty, to: $to:ty, element: $element:ty) => { (node: $node:ident, from: $from:ty, to: $to:ty, element: $element:ty) => {
@@ -254,7 +264,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new(); let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
$( $(
entries.extend(input_adapter_node!(element: $element)); entries.extend(input_adapter_node!(element: $element));
entries.push(item_to_list_node!(element: $element)); entries.extend(also_under_own_identifier!(item_to_list, item_to_list_node!(element: $element)));
)* )*
entries entries
}}; }};
@@ -359,9 +369,10 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
// Type-erased rows for the `ListDyn` connectors (`Read Attribute`, `Count`): any `List` wire erases its element type // Type-erased rows for the `ListDyn` connectors (`Read Attribute`, `Count`): any `List` wire erases its element type
macro_rules! list_dyn_rows { macro_rules! list_dyn_rows {
($($element:ty),* $(,)?) => {{ ($($element:ty),* $(,)?) => {{
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![ let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
$(input_adapter_node!(name: "input_adapter", from: List<$element>, to: ListDyn, element: ListDyn),)* $(also_under_own_identifier!(into, input_adapter_node!(name: "input_adapter", from: List<$element>, to: ListDyn, element: ListDyn)),)*
]; ]
.concat();
entries entries
}}; }};
} }
@@ -394,8 +405,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
($($element:ty),* $(,)?) => {{ ($($element:ty),* $(,)?) => {{
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new(); let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
$( $(
entries.push(bundle_node!(element: $element)); entries.extend(also_under_own_identifier!(bundle, bundle_node!(element: $element)));
entries.push(unbundle_node!(element: $element)); entries.extend(also_under_own_identifier!(unbundle, unbundle_node!(element: $element)));
)* )*
entries entries
}}; }};
@@ -455,10 +466,11 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
// Each item moves inside its matching variant, attributes and all, rather than mapping only its element. // Each item moves inside its matching variant, attributes and all, rather than mapping only its element.
macro_rules! embed_adapter_row { macro_rules! embed_adapter_row {
(from_element: $from:ty, element: $element:ty) => {{ (from_element: $from:ty, element: $element:ty) => {{
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![ let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
input_adapter_row!(node: EmbedItemNode, from: Item<$from>, to: Item<$element>, element: $element), also_under_own_identifier!(embed_item, input_adapter_row!(node: EmbedItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
input_adapter_row!(node: EmbedListNode, from: List<$from>, to: List<$element>, element: $element), also_under_own_identifier!(embed_list, input_adapter_row!(node: EmbedListNode, from: List<$from>, to: List<$element>, element: $element)),
]; ]
.concat();
entries entries
}}; }};
} }
@@ -475,10 +487,11 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
// The `Convert`-based counterpart of `input_adapter_row!`, for casts the std `Into` trait cannot express // The `Convert`-based counterpart of `input_adapter_row!`, for casts the std `Into` trait cannot express
macro_rules! convert_adapter_node { macro_rules! convert_adapter_node {
(from_element: $from:ty, element: $element:ty) => {{ (from_element: $from:ty, element: $element:ty) => {{
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![ let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
input_adapter_row!(node: ConvertItemNode, from: Item<$from>, to: Item<$element>, element: $element), also_under_own_identifier!(convert_item, input_adapter_row!(node: ConvertItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
input_adapter_row!(node: ConvertListNode, from: List<$from>, to: List<$element>, element: $element), also_under_own_identifier!(convert_list, input_adapter_row!(node: ConvertListNode, from: List<$from>, to: List<$element>, element: $element)),
]; ]
.concat();
entries entries
}}; }};
} }
@@ -500,13 +513,19 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
// The sanctioned attribute value conversions: an Item wire's elements box per cell, while a List wire boxes whole as one value // The sanctioned attribute value conversions: an Item wire's elements box per cell, while a List wire boxes whole as one value
macro_rules! attribute_value_node { macro_rules! attribute_value_node {
(Item<$element:ty>) => { (Item<$element:ty>) => {
input_adapter_row!(node: ItemToAttributeValueNode, from: Item<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn) also_under_own_identifier!(
item_to_attribute_value,
input_adapter_row!(node: ItemToAttributeValueNode, from: Item<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
)
}; };
(List<$element:ty>) => { (List<$element:ty>) => {
input_adapter_row!(node: ListToAttributeValueNode, from: List<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn) also_under_own_identifier!(
list_to_attribute_value,
input_adapter_row!(node: ListToAttributeValueNode, from: List<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
)
}; };
} }
let attribute_value_rows: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![ let attribute_value_rows: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
attribute_value_node!(Item<f64>), attribute_value_node!(Item<f64>),
attribute_value_node!(Item<i64>), attribute_value_node!(Item<i64>),
attribute_value_node!(Item<bool>), attribute_value_node!(Item<bool>),
@@ -531,7 +550,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
attribute_value_node!(List<Raster<GPU>>), attribute_value_node!(List<Raster<GPU>>),
attribute_value_node!(List<Graphic>), attribute_value_node!(List<Graphic>),
attribute_value_node!(List<Artboard>), attribute_value_node!(List<Artboard>),
]; ]
.concat();
node_types.extend(attribute_value_rows); node_types.extend(attribute_value_rows);
// Whole-List Transform companion rows: a rank-1 content wire composes the matrix onto every item // Whole-List Transform companion rows: a rank-1 content wire composes the matrix onto every item
macro_rules! transform_list_node { macro_rules! transform_list_node {
@@ -29,6 +29,18 @@ pub struct NodeFlags {
pub forwards_input: bool, pub forwards_input: bool,
pub inject_scope: bool, pub inject_scope: bool,
pub asynchronous: bool, pub asynchronous: bool,
/// Whether type resolution may insert this node on an edge, from `#[node_macro::node(adapter(...))]`.
pub adapter: Option<AdapterKind>,
pub transient: bool,
}
/// How an adapter node changes the wire it is inserted on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AdapterKind {
/// Converts the wire's element into another element type.
Conversion,
/// Changes the wire's rank, like raising an `Item` onto a `List`.
Rank,
} }
// Translation struct between macro and definition // Translation struct between macro and definition
@@ -84,9 +84,7 @@ impl WgpuExecutor {
let view = vello_gpu::kurbo::Affine::new(view.to_cols_array()); let view = vello_gpu::kurbo::Affine::new(view.to_cols_array());
let mut canvas = self.inner.document_canvas.lock().unwrap_or_else(PoisonError::into_inner); let mut canvas = self.inner.document_canvas.lock().unwrap_or_else(PoisonError::into_inner);
self.inner self.inner.vello_renderer.render(self, &mut canvas, draw, view, size, &texture)?;
.vello_renderer
.render(&mut canvas, &self.context().device, &self.context().queue, draw, view, size, &texture)?;
Ok(texture) Ok(texture)
} }
@@ -95,7 +93,7 @@ impl WgpuExecutor {
pub fn render_vello_scene_on_canvas(&self, canvas: &mut VelloCanvas, scene: VelloSceneBuilder) -> Result<Texture> { pub fn render_vello_scene_on_canvas(&self, canvas: &mut VelloCanvas, scene: VelloSceneBuilder) -> Result<Texture> {
let texture = self.request_texture(UVec2::new(scene.width() as u32, scene.height() as u32)); let texture = self.request_texture(UVec2::new(scene.width() as u32, scene.height() as u32));
self.inner.vello_renderer.render_scene(canvas, &self.context().device, &self.context().queue, scene, &texture); self.inner.vello_renderer.render_scene(self, canvas, scene, &texture);
Ok(texture) Ok(texture)
} }
@@ -165,7 +163,11 @@ impl WgpuExecutor {
} }
pub fn request_texture_with_format(&self, size: UVec2, format: wgpu::TextureFormat) -> Texture { pub fn request_texture_with_format(&self, size: UVec2, format: wgpu::TextureFormat) -> Texture {
self.inner.texture_cache.lock().unwrap().request_texture(&self.context().device, size, format) self.request_texture_with_mips(size, format, 1)
}
pub fn request_texture_with_mips(&self, size: UVec2, format: wgpu::TextureFormat, mip_level_count: u32) -> Texture {
self.inner.texture_cache.lock().unwrap().request_texture(self.context(), size, format, mip_level_count)
} }
pub fn create_buffer(&self, desc: &wgpu::BufferDescriptor) -> Buffer { pub fn create_buffer(&self, desc: &wgpu::BufferDescriptor) -> Buffer {
@@ -1,3 +1,4 @@
use crate::WgpuContext;
use glam::UVec2; use glam::UVec2;
use raster_types::Texture; use raster_types::Texture;
use std::collections::VecDeque; use std::collections::VecDeque;
@@ -16,24 +17,23 @@ impl TextureCache {
} }
} }
pub fn request_texture(&mut self, device: &wgpu::Device, size: UVec2, format: wgpu::TextureFormat) -> Texture { pub fn request_texture(&mut self, context: &WgpuContext, size: UVec2, format: wgpu::TextureFormat, mip_level_count: u32) -> Texture {
let size = size.max(UVec2::ONE); let size = size.max(UVec2::ONE);
if let Some(pos) = self if let Some(pos) = self.textures.iter().position(|texture| {
.textures UVec2::new(texture.width(), texture.height()) == size && texture.format() == format && texture.mip_level_count() == mip_level_count && !texture.is_shared() && !texture.is_weakly_shared()
.iter() }) {
.position(|texture| UVec2::new(texture.width(), texture.height()) == size && texture.format() == format && !texture.is_shared() && !texture.is_weakly_shared())
{
let entry = self.textures.remove(pos).unwrap(); let entry = self.textures.remove(pos).unwrap();
let texture = entry.clone(); let texture = entry.clone();
self.textures.push_back(entry); self.textures.push_back(entry);
return texture; return texture;
} }
let incoming_bytes = size.x as u64 * size.y as u64 * format.block_copy_size(None).unwrap_or(4) as u64; self.evict_until_fits(memory_size_estimate(size, format, mip_level_count));
self.evict_until_fits(incoming_bytes);
let texture: Texture = device let usage = wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT;
let texture: Texture = context
.device
.create_texture(&wgpu::TextureDescriptor { .create_texture(&wgpu::TextureDescriptor {
label: Some(&format!("cached_{}x{}", size.x, size.y)), label: Some(&format!("cached_{}x{}", size.x, size.y)),
size: wgpu::Extent3d { size: wgpu::Extent3d {
@@ -41,11 +41,11 @@ impl TextureCache {
height: size.y, height: size.y,
depth_or_array_layers: 1, depth_or_array_layers: 1,
}, },
mip_level_count: 1, mip_level_count,
sample_count: 1, sample_count: 1,
dimension: wgpu::TextureDimension::D2, dimension: wgpu::TextureDimension::D2,
format, format,
usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT, usage: usage & context.adapter.get_texture_format_features(format).allowed_usages,
view_formats: &[], view_formats: &[],
}) })
.into(); .into();
@@ -83,12 +83,20 @@ impl TextureCache {
} }
} }
fn memory_size_estimate(size: UVec2, format: wgpu::TextureFormat, mip_level_count: u32) -> u64 {
let texel_bytes = format.block_copy_size(None).unwrap_or(4) as u64;
(0..mip_level_count)
.map(|level| (size >> level).max(UVec2::ONE))
.map(|level_size| level_size.x as u64 * level_size.y as u64 * texel_bytes)
.sum()
}
trait TextureMemoryCostEstimateExt { trait TextureMemoryCostEstimateExt {
fn memory_size_estimate(&self) -> u64; fn memory_size_estimate(&self) -> u64;
} }
impl TextureMemoryCostEstimateExt for wgpu::Texture { impl TextureMemoryCostEstimateExt for wgpu::Texture {
fn memory_size_estimate(&self) -> u64 { fn memory_size_estimate(&self) -> u64 {
self.width() as u64 * self.height() as u64 * self.format().block_copy_size(None).unwrap_or(4) as u64 memory_size_estimate(UVec2::new(self.width(), self.height()), self.format(), self.mip_level_count())
} }
} }
@@ -2,10 +2,13 @@
//! from `vello_adjustments.wgsl`, while the kinds that compilers struggle to build inside its loop each get a shader and pass of their own. Steps read their //! from `vello_adjustments.wgsl`, while the kinds that compilers struggle to build inside its loop each get a shader and pass of their own. Steps read their
//! settings from a texture, so changing those recompiles nothing. //! settings from a texture, so changing those recompiles nothing.
use crate::WgpuExecutor;
use crate::vello_effects::{WORKING_FORMAT, pass_pipeline}; use crate::vello_effects::{WORKING_FORMAT, pass_pipeline};
use core_types::graphene_hash::CacheHash; use core_types::graphene_hash::CacheHash;
use glam::UVec2;
use graphic_types::Adjustment; use graphic_types::Adjustment;
use raster_kernels::adjustment_steps::{AdjustmentSteps, StepKind, shader_constants}; use raster_kernels::adjustment_steps::{AdjustmentSteps, StepKind, shader_constants};
use raster_types::{Texture, TextureWeakRef};
use std::cmp::Reverse; use std::cmp::Reverse;
use std::collections::HashMap; use std::collections::HashMap;
use std::ops::Range; use std::ops::Range;
@@ -22,11 +25,8 @@ const STANDALONE_KINDS: [StepKind; 2] = [StepKind::GradientMap, StepKind::ColorL
/// How many runs of adjustments keep their encoded and uploaded steps past the render that last used them. Their tables are kept apart. /// How many runs of adjustments keep their encoded and uploaded steps past the render that last used them. Their tables are kept apart.
const MAX_CACHED_RUNS: usize = 8; const MAX_CACHED_RUNS: usize = 8;
/// How many bytes of tables stay uploaded past the render that last used them, the least recently used making way first. /// The most texels a run's tables span (128 MiB), past which they are resampled to fit. That's half of the largest buffer wgpu allocates by default,
const TABLE_CACHE_BYTES: u64 = 256 << 20; /// which an upload passes through.
/// The most texels a run's tables span (128 MiB), past which they are resampled to fit. That's half of what the cache keeps and of the largest buffer
/// wgpu allocates by default, which an upload passes through.
const MAX_TABLE_TEXELS: usize = 1 << 23; const MAX_TABLE_TEXELS: usize = 1 << 23;
/// The format each pass of a run split across several hands its result on to the next in, where the GPU can render into it, so the split rounds nothing. /// The format each pass of a run split across several hands its result on to the next in, where the GPU can render into it, so the split rounds nothing.
@@ -344,15 +344,15 @@ fn texels_texture_descriptor(label: &'static str, width: u32, height: u32) -> wg
} }
/// A texture holding `texels` in rows as wide as the GPU allows, the last padded out, or `None` if they need more rows than it allows too. /// A texture holding `texels` in rows as wide as the GPU allows, the last padded out, or `None` if they need more rows than it allows too.
fn upload_texels(device: &wgpu::Device, queue: &wgpu::Queue, label: &'static str, texels: &[[f32; 4]]) -> Option<wgpu::Texture> { fn upload_texels(executor: &WgpuExecutor, queue: &wgpu::Queue, texels: &[[f32; 4]]) -> Option<Texture> {
let max_dimension = device.limits().max_texture_dimension_2d as usize; let max_dimension = executor.context().device.limits().max_texture_dimension_2d as usize;
let width = texels.len().clamp(1, max_dimension); let width = texels.len().clamp(1, max_dimension);
let height = texels.len().div_ceil(width).max(1); let height = texels.len().div_ceil(width).max(1);
if height > max_dimension { if height > max_dimension {
return None; return None;
} }
let texture = device.create_texture(&texels_texture_descriptor(label, width as u32, height as u32)); let texture = executor.request_texture_with_format(UVec2::new(width as u32, height as u32), wgpu::TextureFormat::Rgba32Float);
let write_rows = |first_row: usize, rows: usize, data: &[[f32; 4]]| { let write_rows = |first_row: usize, rows: usize, data: &[[f32; 4]]| {
let texture_rows = wgpu::TexelCopyTextureInfo { let texture_rows = wgpu::TexelCopyTextureInfo {
texture: &texture, texture: &texture,
@@ -397,12 +397,12 @@ pub(crate) struct PreparedPass {
/// The shader and the uploaded steps of each pass carrying out a run with these `steps`, each pass's texels starting with its step count, /// The shader and the uploaded steps of each pass carrying out a run with these `steps`, each pass's texels starting with its step count,
/// or `None` if any holds more than the GPU can read. /// or `None` if any holds more than the GPU can read.
fn upload_passes(device: &wgpu::Device, queue: &wgpu::Queue, steps: &AdjustmentSteps) -> Option<Vec<(AdjustmentShader, wgpu::Texture)>> { fn upload_passes(executor: &WgpuExecutor, queue: &wgpu::Queue, steps: &AdjustmentSteps) -> Option<Vec<(AdjustmentShader, Texture)>> {
(pass_steps(steps.kinds()).into_iter()) (pass_steps(steps.kinds()).into_iter())
.map(|pass| { .map(|pass| {
let shader = AdjustmentShader::for_pass(&steps.kinds()[pass.clone()]); let shader = AdjustmentShader::for_pass(&steps.kinds()[pass.clone()]);
let texels: Vec<[f32; 4]> = std::iter::once([pass.len() as f32, 0., 0., 0.]).chain(steps.step_texels(pass).iter().copied()).collect(); let texels: Vec<[f32; 4]> = std::iter::once([pass.len() as f32, 0., 0., 0.]).chain(steps.step_texels(pass).iter().copied()).collect();
upload_texels(device, queue, "vello_adjustments_steps", &texels).map(|texture| (shader, texture)) upload_texels(executor, queue, &texels).map(|texture| (shader, texture))
}) })
.collect() .collect()
} }
@@ -419,15 +419,14 @@ pub(crate) struct AdjustmentUploads {
struct CachedRun { struct CachedRun {
hash: u64, hash: u64,
steps: AdjustmentSteps, steps: AdjustmentSteps,
passes: Option<Vec<(AdjustmentShader, wgpu::Texture)>>, passes: Option<Vec<(AdjustmentShader, TextureWeakRef)>>,
last_used: u64, last_used: u64,
} }
/// The tables of a run as uploaded, shared by every run reading the same ones, or `None` in place of the upload for tables too large for the GPU even resampled. /// The tables of a run as uploaded, shared by every run reading the same ones, or `None` in place of the upload for tables too large for the GPU even resampled.
struct CachedTables { struct CachedTables {
key: u64, key: u64,
uploaded: Option<wgpu::Texture>, uploaded: Option<TextureWeakRef>,
bytes: u64,
last_used: u64, last_used: u64,
} }
@@ -438,70 +437,95 @@ pub(crate) fn adjustment_run_hash(run: &[&Adjustment]) -> u64 {
std::hash::Hasher::finish(&hasher) std::hash::Hasher::finish(&hasher)
} }
fn downgrade_passes(passes: &[(AdjustmentShader, Texture)]) -> Vec<(AdjustmentShader, TextureWeakRef)> {
passes.iter().map(|(shader, texture)| (*shader, texture.downgrade())).collect()
}
impl AdjustmentUploads { impl AdjustmentUploads {
/// What each pass carrying out `run` reads in turn, encoding and uploading only what no recent render has. A run that changes no color /// What each pass carrying out `run` reads in turn, encoding and uploading only what no recent render has, with the uploads it reads added to `held`.
/// or that holds more than the GPU can read takes no passes. Only the 64-bit hashes of the runs and of the tables' content tell them apart. /// A run that changes no color or that holds more than the GPU can read takes no passes. Only the 64-bit hashes of the runs and of the tables' content tell them apart.
pub(crate) fn prepare(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, run: &[&Adjustment], render_count: u64) -> Vec<PreparedPass> { pub(crate) fn prepare(&mut self, executor: &WgpuExecutor, queue: &wgpu::Queue, run: &[&Adjustment], render_count: u64, held: &mut Vec<Texture>) -> Vec<PreparedPass> {
let hash = adjustment_run_hash(run); let hash = adjustment_run_hash(run);
let mut uploaded = None;
let index = self.runs.iter().position(|cached| cached.hash == hash).unwrap_or_else(|| { let index = self.runs.iter().position(|cached| cached.hash == hash).unwrap_or_else(|| {
let steps = AdjustmentSteps::encode(run); let steps = AdjustmentSteps::encode(run);
let passes = upload_passes(device, queue, &steps); uploaded = upload_passes(executor, queue, &steps);
if passes.is_none() { if uploaded.is_none() {
log::error!("Adjustments hold more settings than the GPU can read, so they're left out"); log::error!("Adjustments hold more settings than the GPU can read, so they're left out");
} }
self.runs.push(CachedRun { self.runs.push(CachedRun {
hash, hash,
steps, steps,
passes, passes: uploaded.as_deref().map(downgrade_passes),
last_used: render_count, last_used: render_count,
}); });
self.runs.len() - 1 self.runs.len() - 1
}); });
let cached_run = &mut self.runs[index]; let cached_run = &mut self.runs[index];
cached_run.last_used = render_count; cached_run.last_used = render_count;
let Some(passes) = cached_run.passes.clone() else { return Vec::new() }; let Some(cached_passes) = &cached_run.passes else { return Vec::new() };
let parked = cached_passes.iter().map(|(shader, texture)| Some((*shader, texture.upgrade()?))).collect();
let passes = match uploaded.or(parked) {
Some(passes) => passes,
None => {
let Some(passes) = upload_passes(executor, queue, &cached_run.steps) else { return Vec::new() };
cached_run.passes = Some(downgrade_passes(&passes));
passes
}
};
if passes.is_empty() { if passes.is_empty() {
return Vec::new(); return Vec::new();
} }
let tables = match cached_run.steps.table_key() { let tables = match cached_run.steps.table_key() {
Some(key) => { Some(key) => {
let index = self.tables.iter().position(|cached| cached.key == key).unwrap_or_else(|| { let index = self.tables.iter().position(|cached| cached.key == key);
// As many texels as one texture holds and one upload carries let parked = index.map(|index| self.tables[index].uploaded.as_ref().map(TextureWeakRef::upgrade));
let limits = device.limits(); let tables = match parked {
let max_dimension = limits.max_texture_dimension_2d as usize; // Failed to upload
let max_uploaded = (limits.max_buffer_size / size_of::<[f32; 4]>() as u64) as usize; Some(None) => return Vec::new(),
let texels = cached_run.steps.table_texels(MAX_TABLE_TEXELS.min(max_dimension * max_dimension).min(max_uploaded)); // Parked
Some(Some(Some(tables))) => Some(tables),
// Not parked
Some(Some(None)) | None => {
// As many texels as one texture holds and one upload carries
let limits = executor.context().device.limits();
let max_dimension = limits.max_texture_dimension_2d as usize;
let max_uploaded = (limits.max_buffer_size / size_of::<[f32; 4]>() as u64) as usize;
let texels = cached_run.steps.table_texels(MAX_TABLE_TEXELS.min(max_dimension * max_dimension).min(max_uploaded));
let uploaded = upload_texels(device, queue, "vello_adjustments_tables", &texels); let uploaded = upload_texels(executor, queue, &texels);
if uploaded.is_none() { if uploaded.is_none() {
log::error!("Adjustments read lookup tables holding more data than the GPU can read, so they're left out"); log::error!("Adjustments read lookup tables holding more data than the GPU can read, so they're left out");
}
let cached = CachedTables {
key,
uploaded: uploaded.as_ref().map(Texture::downgrade),
last_used: render_count,
};
match index {
Some(index) => self.tables[index] = cached,
None => self.tables.push(cached),
}
uploaded
} }
};
self.tables.push(CachedTables { let Some(tables) = tables else { return Vec::new() };
key, if let Some(index) = index {
bytes: uploaded self.tables[index].last_used = render_count;
.as_ref() }
.map_or(0, |texture| u64::from(texture.width()) * u64::from(texture.height()) * size_of::<[f32; 4]>() as u64), Some(tables)
uploaded,
last_used: render_count,
});
self.tables.len() - 1
});
let cached_tables = &mut self.tables[index];
cached_tables.last_used = render_count;
let Some(uploaded) = cached_tables.uploaded.clone() else { return Vec::new() };
Some(uploaded)
} }
None => None, None => None,
}; };
held.extend(passes.iter().map(|(_, steps)| steps.clone()).chain(tables.clone()));
(passes.into_iter()) (passes.into_iter())
.map(|(shader, steps)| PreparedPass { .map(|(shader, steps)| PreparedPass {
shader, shader,
steps, steps: (*steps).clone(),
tables: tables.clone(), tables: tables.as_ref().map(|tables| (**tables).clone()),
}) })
.collect() .collect()
} }
@@ -513,13 +537,7 @@ impl AdjustmentUploads {
let used_this_render = self.runs.iter().take_while(|cached| cached.last_used == render_count).count(); let used_this_render = self.runs.iter().take_while(|cached| cached.last_used == render_count).count();
self.runs.truncate(used_this_render.max(MAX_CACHED_RUNS)); self.runs.truncate(used_this_render.max(MAX_CACHED_RUNS));
// Tables are kept within a byte budget instead, since one can take up hundreds of megabytes self.tables.retain(|cached| cached.uploaded.as_ref().is_none_or(|tables| tables.upgrade().is_some()));
self.tables.sort_by_key(|cached| Reverse(cached.last_used));
let mut kept_bytes = 0;
self.tables.retain(|cached| {
kept_bytes += cached.bytes;
cached.last_used == render_count || kept_bytes <= TABLE_CACHE_BYTES
});
} }
#[cfg(test)] #[cfg(test)]
@@ -1,5 +1,6 @@
//! The GPU passes that carry out an item's effects on its content, between rendering the content offscreen and drawing the result back. //! The GPU passes that carry out an item's effects on its content, between rendering the content offscreen and drawing the result back.
use crate::WgpuExecutor;
use crate::vello_adjustments::{AdjustmentShaders, AdjustmentUploads, PassEncodings, PreparedPass}; use crate::vello_adjustments::{AdjustmentShaders, AdjustmentUploads, PassEncodings, PreparedPass};
use bytemuck::{Pod, Zeroable}; use bytemuck::{Pod, Zeroable};
use core_types::Color; use core_types::Color;
@@ -14,6 +15,7 @@ use graphic_types::resampling::{DisplacementField, EffectFrame, FrameWarp, Halft
use graphic_types::{Adjustment, BevelDirection, BevelStyle, BevelTechnique, EffectOperation, Effects, GlowSource, GlowTechnique}; use graphic_types::{Adjustment, BevelDirection, BevelStyle, BevelTechnique, EffectOperation, Effects, GlowSource, GlowTechnique};
use raster_kernels::effect_kernels::{BlurKernel, MAX_DIRECT_BOX_RADIUS, NEGLIGIBLE_LENGTH, chamfer_passes}; use raster_kernels::effect_kernels::{BlurKernel, MAX_DIRECT_BOX_RADIUS, NEGLIGIBLE_LENGTH, chamfer_passes};
use raster_kernels::resample_kernels::MotionBlurShear; use raster_kernels::resample_kernels::MotionBlurShear;
use raster_types::Texture;
use std::collections::HashMap; use std::collections::HashMap;
use std::sync::{Mutex, PoisonError}; use std::sync::{Mutex, PoisonError};
use vello_gpu::kurbo::Affine; use vello_gpu::kurbo::Affine;
@@ -50,9 +52,6 @@ const GRADIENT_SAMPLES: u32 = GRADIENT_TABLE_SIZE as u32;
const PARAMETER_TAPS: usize = 81; const PARAMETER_TAPS: usize = 81;
const _: () = assert!(PARAMETER_TAPS > 2 * raster_kernels::effect_kernels::MAX_KERNEL_REACH.div_ceil(2)); const _: () = assert!(PARAMETER_TAPS > 2 * raster_kernels::effect_kernels::MAX_KERNEL_REACH.div_ceil(2));
/// How many renders a pooled texture survives unused before it is freed.
const UNUSED_TEXTURE_RENDER_LIMIT: u64 = 3;
/// The shader's parameters, laid out to match its `Parameters` struct. /// The shader's parameters, laid out to match its `Parameters` struct.
#[repr(C)] #[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)] #[derive(Clone, Copy, Pod, Zeroable)]
@@ -275,7 +274,7 @@ impl EffectPasses {
#[expect(clippy::too_many_arguments)] #[expect(clippy::too_many_arguments)]
pub(crate) fn apply( pub(crate) fn apply(
&self, &self,
device: &wgpu::Device, executor: &WgpuExecutor,
queue: &wgpu::Queue, queue: &wgpu::Queue,
textures: &mut EffectTextures, textures: &mut EffectTextures,
content: &wgpu::Texture, content: &wgpu::Texture,
@@ -289,8 +288,10 @@ impl EffectPasses {
backdrop: Option<(&wgpu::Texture, Affine)>, backdrop: Option<(&wgpu::Texture, Affine)>,
capture: Option<EffectCapture>, capture: Option<EffectCapture>,
) -> Vec<(wgpu::Texture, BlendMode)> { ) -> Vec<(wgpu::Texture, BlendMode)> {
let device = &executor.context().device;
let mut recorder = PassRecorder { let mut recorder = PassRecorder {
passes: self, passes: self,
executor,
device, device,
queue, queue,
encoder: device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_effects") }), encoder: device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_effects") }),
@@ -1012,7 +1013,7 @@ impl EffectPasses {
// The content at full strength is read only by an operation after the run, or shown as the result where no fill fades it // The content at full strength is read only by an operation after the run, or shown as the result where no fill fades it
let full_is_read = filled.is_none() || position + run.len() < operations.len(); let full_is_read = filled.is_none() || position + run.len() < operations.len();
let prepared_passes = recorder.textures.prepare_adjustments(device, queue, &run); let prepared_passes = recorder.textures.prepare_adjustments(recorder.executor, queue, &run);
// Each pass but the last hands its result on in the chained format, so splitting the run rounds nothing // Each pass but the last hands its result on in the chained format, so splitting the run rounds nothing
for (index, prepared) in prepared_passes.iter().enumerate() { for (index, prepared) in prepared_passes.iter().enumerate() {
@@ -1243,7 +1244,7 @@ impl EffectPasses {
#[expect(clippy::too_many_arguments)] #[expect(clippy::too_many_arguments)]
pub(crate) fn adjust_image( pub(crate) fn adjust_image(
&self, &self,
device: &wgpu::Device, executor: &WgpuExecutor,
queue: &wgpu::Queue, queue: &wgpu::Queue,
textures: &mut EffectTextures, textures: &mut EffectTextures,
image: &wgpu::Texture, image: &wgpu::Texture,
@@ -1252,8 +1253,10 @@ impl EffectPasses {
target: &wgpu::Texture, target: &wgpu::Texture,
) { ) {
let size = UVec2::new(image.width(), image.height()); let size = UVec2::new(image.width(), image.height());
let device = &executor.context().device;
let mut recorder = PassRecorder { let mut recorder = PassRecorder {
passes: self, passes: self,
executor,
device, device,
queue, queue,
encoder: device.create_command_encoder(&wgpu::CommandEncoderDescriptor { encoder: device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
@@ -1285,19 +1288,20 @@ impl EffectPasses {
} }
chained.into_iter().for_each(|texture| recorder.textures.release(texture)); chained.into_iter().for_each(|texture| recorder.textures.release(texture));
self.record_mipmaps(device, &mut recorder.encoder, recorder.textures, target); self.record_mipmaps(executor, &mut recorder.encoder, recorder.textures, target);
queue.submit([recorder.encoder.finish()]); queue.submit([recorder.encoder.finish()]);
} }
/// Records the averaging of each of `texture`'s smaller mip levels from the one above it, like the levels of an uploaded image. /// Records the averaging of each of `texture`'s smaller mip levels from the one above it, like the levels of an uploaded image.
/// Each is halved into a pooled texture and copied into place, since WebGL sets the levels read for a whole texture, so none is drawn into while another is read. /// Each is halved into a pooled texture and copied into place, since WebGL sets the levels read for a whole texture, so none is drawn into while another is read.
pub(crate) fn record_mipmaps(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, textures: &mut EffectTextures, texture: &wgpu::Texture) { pub(crate) fn record_mipmaps(&self, executor: &WgpuExecutor, encoder: &mut wgpu::CommandEncoder, textures: &mut EffectTextures, texture: &wgpu::Texture) {
let device = &executor.context().device;
let format = texture.format(); let format = texture.format();
let mut above: Option<wgpu::Texture> = None; let mut above: Option<wgpu::Texture> = None;
for index in 1..texture.mip_level_count() { for index in 1..texture.mip_level_count() {
let level_size = UVec2::new(texture.width() >> index, texture.height() >> index).max(UVec2::ONE); let level_size = UVec2::new(texture.width() >> index, texture.height() >> index).max(UVec2::ONE);
let level = textures.acquire(device, level_size, format); let level = textures.acquire(executor, level_size, format);
// The first level reads the top one through a view of every level // The first level reads the top one through a view of every level
let source = above.as_ref().unwrap_or(texture).create_view(&wgpu::TextureViewDescriptor::default()); let source = above.as_ref().unwrap_or(texture).create_view(&wgpu::TextureViewDescriptor::default());
@@ -1450,6 +1454,7 @@ fn premultiplied_gamma_channels(color: Color) -> [f32; 4] {
/// Records the passes of one effects group, whose images all share one size. /// Records the passes of one effects group, whose images all share one size.
struct PassRecorder<'a> { struct PassRecorder<'a> {
passes: &'a EffectPasses, passes: &'a EffectPasses,
executor: &'a WgpuExecutor,
device: &'a wgpu::Device, device: &'a wgpu::Device,
queue: &'a wgpu::Queue, queue: &'a wgpu::Queue,
encoder: wgpu::CommandEncoder, encoder: wgpu::CommandEncoder,
@@ -1470,7 +1475,7 @@ impl PassRecorder<'_> {
content: Option<&wgpu::Texture>, content: Option<&wgpu::Texture>,
parameters: Parameters, parameters: Parameters,
) -> wgpu::Texture { ) -> wgpu::Texture {
let target = self.textures.acquire(self.device, size, format); let target = self.textures.acquire(self.executor, size, format);
let view = |texture: &wgpu::Texture| texture.create_view(&wgpu::TextureViewDescriptor::default()); let view = |texture: &wgpu::Texture| texture.create_view(&wgpu::TextureViewDescriptor::default());
let (source, secondary, content) = (view(source), secondary.map(view), content.map(view)); let (source, secondary, content) = (view(source), secondary.map(view), content.map(view));
@@ -1618,7 +1623,7 @@ impl PassRecorder<'_> {
fn gradient_glow_tint(&mut self, paint: &GlowFill, strength: &wgpu::Texture, content: &wgpu::Texture, fades: bool, grain: Option<&styles::GlowGrain>) -> Option<wgpu::Texture> { fn gradient_glow_tint(&mut self, paint: &GlowFill, strength: &wgpu::Texture, content: &wgpu::Texture, fades: bool, grain: Option<&styles::GlowGrain>) -> Option<wgpu::Texture> {
let (samples, opacity) = paint.gradient_samples(GRADIENT_SAMPLES as usize)?; let (samples, opacity) = paint.gradient_samples(GRADIENT_SAMPLES as usize)?;
let samples: Vec<half::f16> = samples.into_iter().flatten().map(half::f16::from_f32).collect(); let samples: Vec<half::f16> = samples.into_iter().flatten().map(half::f16::from_f32).collect();
let samples = self.row_texture("vello_effects_gradient", wgpu::TextureFormat::Rgba16Float, GRADIENT_SAMPLES, bytemuck::cast_slice(&samples)); let samples = self.row_texture(wgpu::TextureFormat::Rgba16Float, GRADIENT_SAMPLES, bytemuck::cast_slice(&samples));
let parameters = Parameters { let parameters = Parameters {
values: [if fades { 1. } else { 0. }, GRADIENT_GLOW_FADE as f32, opacity, grain.map_or(0., |grain| grain.amounts[0] as f32)], values: [if fades { 1. } else { 0. }, GRADIENT_GLOW_FADE as f32, opacity, grain.map_or(0., |grain| grain.amounts[0] as f32)],
@@ -1673,27 +1678,17 @@ impl PassRecorder<'_> {
let samples: Vec<half::f16> = (0..CONTOUR_SAMPLES) let samples: Vec<half::f16> = (0..CONTOUR_SAMPLES)
.map(|index| half::f16::from_f64(contour.evaluate(index as f64 / (CONTOUR_SAMPLES - 1) as f64).clamp(0., 1.))) .map(|index| half::f16::from_f64(contour.evaluate(index as f64 / (CONTOUR_SAMPLES - 1) as f64).clamp(0., 1.)))
.collect(); .collect();
self.row_texture("vello_effects_contour", COVERAGE_FORMAT, CONTOUR_SAMPLES, bytemuck::cast_slice(&samples)) self.row_texture(COVERAGE_FORMAT, CONTOUR_SAMPLES, bytemuck::cast_slice(&samples))
} }
/// A texture one row of `width` texels tall holding `data` in the `format`, for shaders to interpolate between its samples. /// A texture one row of `width` texels tall holding `data` in the `format`, for shaders to interpolate between its samples.
/// It's made fresh rather than pooled, since its upload runs ahead of the passes recorded before it that a pooled texture may still serve. fn row_texture(&mut self, format: wgpu::TextureFormat, width: u32, data: &[u8]) -> wgpu::Texture {
fn row_texture(&mut self, label: &str, format: wgpu::TextureFormat, width: u32, data: &[u8]) -> wgpu::Texture {
let extent = wgpu::Extent3d { let extent = wgpu::Extent3d {
width, width,
height: 1, height: 1,
depth_or_array_layers: 1, depth_or_array_layers: 1,
}; };
let texture = self.device.create_texture(&wgpu::TextureDescriptor { let texture = self.executor.request_texture_with_format(UVec2::new(width, 1), format);
label: Some(label),
size: extent,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
self.queue.write_texture( self.queue.write_texture(
wgpu::TexelCopyTextureInfo { wgpu::TexelCopyTextureInfo {
texture: &texture, texture: &texture,
@@ -1709,7 +1704,9 @@ impl PassRecorder<'_> {
}, },
extent, extent,
); );
texture let row = (*texture).clone();
self.textures.held.push(texture);
row
} }
/// The coverage (or tinted image) of what lies beneath, hidden behind the full-strength content where a `fill` below 1 (times the Blend If weight if any) fades the content that shows over it. /// The coverage (or tinted image) of what lies beneath, hidden behind the full-strength content where a `fill` below 1 (times the Blend If weight if any) fades the content that shows over it.
@@ -1918,7 +1915,7 @@ impl PassRecorder<'_> {
/// The image (of any format a shader can load from) with a pass of adjustments carried out on it into a texture of `format`, reading what was `prepared` for the pass, /// The image (of any format a shader can load from) with a pass of adjustments carried out on it into a texture of `format`, reading what was `prepared` for the pass,
/// in the `encodings` of its source and result. /// in the `encodings` of its source and result.
fn adjust(&mut self, image: &wgpu::Texture, prepared: &PreparedPass, format: wgpu::TextureFormat, encodings: PassEncodings) -> wgpu::Texture { fn adjust(&mut self, image: &wgpu::Texture, prepared: &PreparedPass, format: wgpu::TextureFormat, encodings: PassEncodings) -> wgpu::Texture {
let target = self.textures.acquire(self.device, self.size, format); let target = self.textures.acquire(self.executor, self.size, format);
let view = |texture: &wgpu::Texture| texture.create_view(&wgpu::TextureViewDescriptor::default()); let view = |texture: &wgpu::Texture| texture.create_view(&wgpu::TextureViewDescriptor::default());
self.adjust_into(&view(&target), format, &view(image), prepared, encodings); self.adjust_into(&view(&target), format, &view(image), prepared, encodings);
@@ -2014,11 +2011,11 @@ impl PassRecorder<'_> {
} }
} }
/// Textures for the effect passes and the content they work on, kept between renders for reuse at the same sizes. /// Textures for the effect passes and the content they work on, taken from the texture pool and held until the render ends.
#[derive(Default)] #[derive(Default)]
pub(crate) struct EffectTextures { pub(crate) struct EffectTextures {
/// Each unused texture with the render it was last used in. held: Vec<Texture>,
free: Vec<(wgpu::Texture, u64)>, released: Vec<wgpu::Texture>,
/// The uploads of recent runs of adjustments. /// The uploads of recent runs of adjustments.
adjustments: AdjustmentUploads, adjustments: AdjustmentUploads,
render_count: u64, render_count: u64,
@@ -2029,43 +2026,32 @@ pub(crate) struct EffectTextures {
impl EffectTextures { impl EffectTextures {
/// What each pass carrying out a run of adjustments reads, as [`AdjustmentUploads::prepare`] gives it. /// What each pass carrying out a run of adjustments reads, as [`AdjustmentUploads::prepare`] gives it.
pub(crate) fn prepare_adjustments(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, run: &[&Adjustment]) -> Vec<PreparedPass> { pub(crate) fn prepare_adjustments(&mut self, executor: &WgpuExecutor, queue: &wgpu::Queue, run: &[&Adjustment]) -> Vec<PreparedPass> {
self.adjustments.prepare(device, queue, run, self.render_count) self.adjustments.prepare(executor, queue, run, self.render_count, &mut self.held)
} }
pub(crate) fn acquire(&mut self, device: &wgpu::Device, size: UVec2, format: wgpu::TextureFormat) -> wgpu::Texture { pub(crate) fn acquire(&mut self, executor: &WgpuExecutor, size: UVec2, format: wgpu::TextureFormat) -> wgpu::Texture {
let size = size.max(UVec2::ONE); let size = size.max(UVec2::ONE);
let matches = |texture: &wgpu::Texture| texture.width() == size.x && texture.height() == size.y && texture.format() == format; let matches = |texture: &wgpu::Texture| texture.width() == size.x && texture.height() == size.y && texture.format() == format;
if let Some(index) = self.free.iter().position(|(texture, _)| matches(texture)) { if let Some(index) = self.released.iter().position(matches) {
return self.free.swap_remove(index).0; return self.released.swap_remove(index);
} }
device.create_texture(&wgpu::TextureDescriptor { let texture = executor.request_texture_with_format(size, format);
label: Some("vello_effects_texture"), let acquired = (*texture).clone();
size: wgpu::Extent3d { self.held.push(texture);
width: size.x, acquired
height: size.y,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
})
} }
/// Returns a texture to the pool once the passes recorded so far are done with it, since later passes are recorded and submitted after them. /// Returns a texture to the pool once the passes recorded so far are done with it, since later passes are recorded and submitted after them.
pub(crate) fn release(&mut self, texture: wgpu::Texture) { pub(crate) fn release(&mut self, texture: wgpu::Texture) {
self.free.push((texture, self.render_count)); self.released.push(texture);
} }
/// Frees the textures no recent render has used.
pub(crate) fn finish_render(&mut self) { pub(crate) fn finish_render(&mut self) {
let render_count = self.render_count; self.released.clear();
self.free.retain(|(_, last_used)| render_count - last_used < UNUSED_TEXTURE_RENDER_LIMIT); self.held.clear();
self.adjustments.finish_render(render_count); self.adjustments.finish_render(self.render_count);
self.render_count += 1; self.render_count += 1;
} }
@@ -2108,7 +2094,10 @@ mod tests {
use core_types::list::Item; use core_types::list::Item;
use graphic_types::vector_types::Gradient; use graphic_types::vector_types::Gradient;
let Some(context) = futures::executor::block_on(crate::WgpuContext::for_tests()) else { return }; let Some(executor) = futures::executor::block_on(crate::WgpuContext::for_tests()).and_then(crate::WgpuExecutor::with_context) else {
return;
};
let context = executor.context();
let passes = EffectPasses::new(&context.device, &context.adapter); let passes = EffectPasses::new(&context.device, &context.adapter);
if !passes.renders_working_formats { if !passes.renders_working_formats {
return; return;
@@ -2146,12 +2135,12 @@ mod tests {
let effects = Effects::from_operations(operations); let effects = Effects::from_operations(operations);
let mut textures = EffectTextures::default(); let mut textures = EffectTextures::default();
let content = textures.acquire(&context.device, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm); let content = textures.acquire(&executor, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
let queue = context.queue.lock(); let queue = context.queue.lock();
let apply = |textures: &mut EffectTextures, effects: &Effects| { let apply = |textures: &mut EffectTextures, effects: &Effects| {
textures.drawn_passes.clear(); textures.drawn_passes.clear();
let layers = EffectLayers::plan(effects, BlendMode::Normal, 1., false); let layers = EffectLayers::plan(effects, BlendMode::Normal, 1., false);
let results = passes.apply(&context.device, &queue, textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None); let results = passes.apply(&executor, &queue, textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
results.into_iter().for_each(|(result, _)| textures.release(result)); results.into_iter().for_each(|(result, _)| textures.release(result));
}; };
let draw = |textures: &mut EffectTextures| { let draw = |textures: &mut EffectTextures| {
@@ -2173,7 +2162,7 @@ mod tests {
textures.drawn_passes.clear(); textures.drawn_passes.clear();
let effects = Effects::from_operations(operations); let effects = Effects::from_operations(operations);
let layers = EffectLayers::plan(&effects, BlendMode::Normal, fill, false); let layers = EffectLayers::plan(&effects, BlendMode::Normal, fill, false);
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None, None); let results = passes.apply(&executor, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None, None);
results.into_iter().for_each(|(result, _)| textures.release(result)); results.into_iter().for_each(|(result, _)| textures.release(result));
textures.drawn_passes.clone() textures.drawn_passes.clone()
}; };
@@ -2204,7 +2193,10 @@ mod tests {
fn effects_blending_normally_at_a_full_fill_take_no_more_passes_when_layered() { fn effects_blending_normally_at_a_full_fill_take_no_more_passes_when_layered() {
use graphic_types::effects::EffectKind; use graphic_types::effects::EffectKind;
let Some(context) = futures::executor::block_on(crate::WgpuContext::for_tests()) else { return }; let Some(executor) = futures::executor::block_on(crate::WgpuContext::for_tests()).and_then(crate::WgpuExecutor::with_context) else {
return;
};
let context = executor.context();
let passes = EffectPasses::new(&context.device, &context.adapter); let passes = EffectPasses::new(&context.device, &context.adapter);
if !passes.renders_working_formats { if !passes.renders_working_formats {
return; return;
@@ -2212,12 +2204,12 @@ mod tests {
let effects = Effects::from_operations([EffectOperation::default_for(EffectKind::DropShadow), EffectOperation::default_for(EffectKind::InnerShadow)]); let effects = Effects::from_operations([EffectOperation::default_for(EffectKind::DropShadow), EffectOperation::default_for(EffectKind::InnerShadow)]);
let mut textures = EffectTextures::default(); let mut textures = EffectTextures::default();
let content = textures.acquire(&context.device, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm); let content = textures.acquire(&executor, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
let queue = context.queue.lock(); let queue = context.queue.lock();
let mut drawn = |layered: bool| { let mut drawn = |layered: bool| {
textures.drawn_passes.clear(); textures.drawn_passes.clear();
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., layered); let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., layered);
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None); let results = passes.apply(&executor, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
results.into_iter().for_each(|(result, _)| textures.release(result)); results.into_iter().for_each(|(result, _)| textures.release(result));
textures.drawn_passes.clone() textures.drawn_passes.clone()
}; };
@@ -2228,7 +2220,10 @@ mod tests {
fn a_bevel_without_a_gloss_contour_or_texture_lights_its_highlight_and_shadow_directly() { fn a_bevel_without_a_gloss_contour_or_texture_lights_its_highlight_and_shadow_directly() {
use graphic_types::effects::EffectKind; use graphic_types::effects::EffectKind;
let Some(context) = futures::executor::block_on(crate::WgpuContext::for_tests()) else { return }; let Some(executor) = futures::executor::block_on(crate::WgpuContext::for_tests()).and_then(crate::WgpuExecutor::with_context) else {
return;
};
let context = executor.context();
let passes = EffectPasses::new(&context.device, &context.adapter); let passes = EffectPasses::new(&context.device, &context.adapter);
if !passes.renders_working_formats { if !passes.renders_working_formats {
return; return;
@@ -2236,10 +2231,10 @@ mod tests {
let effects = Effects::from_operations([EffectOperation::default_for(EffectKind::BevelAndEmboss)]); let effects = Effects::from_operations([EffectOperation::default_for(EffectKind::BevelAndEmboss)]);
let mut textures = EffectTextures::default(); let mut textures = EffectTextures::default();
let content = textures.acquire(&context.device, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm); let content = textures.acquire(&executor, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
let queue = context.queue.lock(); let queue = context.queue.lock();
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false); let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false);
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None); let results = passes.apply(&executor, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None, None);
results.into_iter().for_each(|(result, _)| textures.release(result)); results.into_iter().for_each(|(result, _)| textures.release(result));
let drawn = |label: &str| textures.drawn_passes.iter().filter(|&&drawn| drawn == label).count(); let drawn = |label: &str| textures.drawn_passes.iter().filter(|&&drawn| drawn == label).count();
@@ -2248,7 +2243,10 @@ mod tests {
#[test] #[test]
fn a_table_stays_uploaded_while_the_settings_beside_it_change() { fn a_table_stays_uploaded_while_the_settings_beside_it_change() {
let Some(context) = futures::executor::block_on(crate::WgpuContext::for_tests()) else { return }; let Some(executor) = futures::executor::block_on(crate::WgpuContext::for_tests()).and_then(crate::WgpuExecutor::with_context) else {
return;
};
let context = executor.context();
let queue = context.queue.lock(); let queue = context.queue.lock();
let lookup = Adjustment::ColorLookup { let lookup = Adjustment::ColorLookup {
@@ -2258,7 +2256,7 @@ mod tests {
let prepare = |textures: &mut EffectTextures, posterize_levels| { let prepare = |textures: &mut EffectTextures, posterize_levels| {
let posterize = Adjustment::Posterize { levels: posterize_levels }; let posterize = Adjustment::Posterize { levels: posterize_levels };
// Color Lookup's pass and then Posterize's, which share the run's tables // Color Lookup's pass and then Posterize's, which share the run's tables
let mut prepared = textures.prepare_adjustments(&context.device, &queue, &[&lookup, &posterize]); let mut prepared = textures.prepare_adjustments(&executor, &queue, &[&lookup, &posterize]);
prepared.pop().map(|prepared| (prepared.steps, prepared.tables)) prepared.pop().map(|prepared| (prepared.steps, prepared.tables))
}; };
@@ -2270,11 +2268,13 @@ mod tests {
panic!("The run reads its table") panic!("The run reads its table")
}; };
assert!(first_steps == again_steps && first_table == again_table); assert!(first_steps == again_steps && first_table == again_table);
let Some((other_steps, _)) = prepare(&mut textures, 5) else { panic!("The run reads its table") };
assert!(other_steps != first_steps);
for levels in 5..20 { for levels in 5..20 {
let Some((steps, Some(table))) = prepare(&mut textures, levels) else { let Some((_, Some(table))) = prepare(&mut textures, levels) else {
panic!("The run reads its table") panic!("The run reads its table")
}; };
assert!(steps != first_steps && table == first_table); assert!(table == first_table);
textures.finish_render(); textures.finish_render();
} }
@@ -86,7 +86,7 @@ impl PassRecorder<'_> {
}) })
.map(half::f16::from_f32) .map(half::f16::from_f32)
.collect(); .collect();
let table = self.row_texture("vello_effects_masked_radius_blur", wgpu::TextureFormat::Rgba16Float, 256, bytemuck::cast_slice(&blends)); let table = self.row_texture(wgpu::TextureFormat::Rgba16Float, 256, bytemuck::cast_slice(&blends));
let interpolation = self.run("masked_radius_blur_interpolation", WORKING_FORMAT, self.size, luminance, Some(&table), None, Parameters::default()); let interpolation = self.run("masked_radius_blur_interpolation", WORKING_FORMAT, self.size, luminance, Some(&table), None, Parameters::default());
if full_is_read && let Some(blurred) = self.masked_radius_blur_image(full.as_ref().unwrap_or(content), &interpolation, levels, linear) { if full_is_read && let Some(blurred) = self.masked_radius_blur_image(full.as_ref().unwrap_or(content), &interpolation, levels, linear) {
@@ -74,7 +74,7 @@ impl PassRecorder<'_> {
return band; return band;
}; };
let samples: Vec<half::f16> = samples.into_iter().flatten().map(half::f16::from_f32).collect(); let samples: Vec<half::f16> = samples.into_iter().flatten().map(half::f16::from_f32).collect();
let samples = self.row_texture("vello_effects_gradient", wgpu::TextureFormat::Rgba16Float, GRADIENT_SAMPLES, bytemuck::cast_slice(&samples)); let samples = self.row_texture(wgpu::TextureFormat::Rgba16Float, GRADIENT_SAMPLES, bytemuck::cast_slice(&samples));
let parameters = Parameters { let parameters = Parameters {
amount: opacity, amount: opacity,
@@ -40,7 +40,7 @@ impl PassRecorder<'_> {
let vertices = 12 * (columns + rows) + 24 + 6 * columns * rows; let vertices = 12 * (columns + rows) + 24 + 6 * columns * rows;
let format = texture.format(); let format = texture.format();
let warped = self.textures.acquire(self.device, self.size, format); let warped = self.textures.acquire(self.executor, self.size, format);
let view = |texture: &wgpu::Texture| texture.create_view(&wgpu::TextureViewDescriptor::default()); let view = |texture: &wgpu::Texture| texture.create_view(&wgpu::TextureViewDescriptor::default());
let reading = self.passes.bind_group(self.device, self.size, &view(&texture), None, None, parameters); let reading = self.passes.bind_group(self.device, self.size, &view(&texture), None, None, parameters);
let mesh = (self.passes).pipeline_with(self.device, "warp_vertex", "warp_effect", format, Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING)); let mesh = (self.passes).pipeline_with(self.device, "warp_vertex", "warp_effect", format, Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING));
@@ -1,12 +1,14 @@
//! The GPU pass that renders tiles of generators' patterns, matching the CPU's renders of them. //! The GPU pass that renders tiles of generators' patterns, matching the CPU's renders of them.
use crate::WgpuExecutor;
use crate::vello_render::TEXTURE_FORMAT; use crate::vello_render::TEXTURE_FORMAT;
use bytemuck::{Pod, Zeroable}; use bytemuck::{Pod, Zeroable};
use glam::DVec2; use glam::{DVec2, UVec2};
use graphic_types::generator::{ use graphic_types::generator::{
CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior, NoiseSettings, NoiseType, CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior, NoiseSettings, NoiseType,
}; };
use raster_kernels::mandelbrot::{MandelbrotSetup, ReferenceOrbit, resolves_in_32_bits}; use raster_kernels::mandelbrot::{MandelbrotSetup, ReferenceOrbit, resolves_in_32_bits};
use raster_types::Texture;
use std::iter::zip; use std::iter::zip;
use std::sync::OnceLock; use std::sync::OnceLock;
use wgpu::util::DeviceExt; use wgpu::util::DeviceExt;
@@ -270,7 +272,7 @@ impl Tile {
} }
/// The texture holding a reference orbit's values and their raisings for the Mandelbrot shader, in rows of `REFERENCE_ROW_LENGTH`, or one empty texel without one. /// The texture holding a reference orbit's values and their raisings for the Mandelbrot shader, in rows of `REFERENCE_ROW_LENGTH`, or one empty texel without one.
fn reference_texture(device: &wgpu::Device, queue: &wgpu::Queue, reference: Option<&ReferenceOrbit>) -> wgpu::Texture { fn reference_texture(executor: &WgpuExecutor, queue: &wgpu::Queue, reference: Option<&ReferenceOrbit>) -> Texture {
let (values, raised_values) = reference.map_or((&[][..], &[][..]), |reference| (&reference.values[..], &reference.raised_values[..])); let (values, raised_values) = reference.map_or((&[][..], &[][..]), |reference| (&reference.values[..], &reference.raised_values[..]));
let (width, height) = (values.len().clamp(1, REFERENCE_ROW_LENGTH), values.len().div_ceil(REFERENCE_ROW_LENGTH).max(1)); let (width, height) = (values.len().clamp(1, REFERENCE_ROW_LENGTH), values.len().div_ceil(REFERENCE_ROW_LENGTH).max(1));
@@ -279,25 +281,18 @@ fn reference_texture(device: &wgpu::Device, queue: &wgpu::Queue, reference: Opti
*texel = [value.x, value.y, raised.x, raised.y]; *texel = [value.x, value.y, raised.x, raised.y];
} }
device.create_texture_with_data( let texture = executor.request_texture_with_format(UVec2::new(width as u32, height as u32), wgpu::TextureFormat::Rgba32Float);
queue, queue.write_texture(
&wgpu::TextureDescriptor { texture.as_image_copy(),
label: Some("vello_generator_reference_orbit"),
size: wgpu::Extent3d {
width: width as u32,
height: height as u32,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba32Float,
usage: wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
},
wgpu::util::TextureDataOrder::LayerMajor,
bytemuck::cast_slice(&texels), bytemuck::cast_slice(&texels),
) wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(width as u32 * size_of::<[f32; 4]>() as u32),
rows_per_image: Some(height as u32),
},
texture.size(),
);
texture
} }
/// The pipelines of the pass, one for each shader. /// The pipelines of the pass, one for each shader.
@@ -386,26 +381,24 @@ impl GeneratorPasses {
} }
/// A texture for square tiles `pixels` across to be rendered into, with the mip levels they're drawn from. /// A texture for square tiles `pixels` across to be rendered into, with the mip levels they're drawn from.
pub(crate) fn tile_texture(device: &wgpu::Device, pixels: u32) -> wgpu::Texture { pub(crate) fn tile_texture(executor: &WgpuExecutor, pixels: u32) -> Texture {
device.create_texture(&wgpu::TextureDescriptor { executor.request_texture_with_mips(UVec2::splat(pixels), TEXTURE_FORMAT, TILE_MIP_LEVELS)
label: Some("vello_generator_tile"),
size: wgpu::Extent3d {
width: pixels,
height: pixels,
depth_or_array_layers: 1,
},
mip_level_count: TILE_MIP_LEVELS,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: TEXTURE_FORMAT,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
})
} }
/// Records the rendering of a square tile of `pattern` into the top mip level of `texture`, with its top left corner at `corner` of the pattern's space and pixels `texel` units across. /// Records the rendering of a square tile of `pattern` into the top mip level of `texture`, with its top left corner at `corner` of the pattern's space and pixels `texel` units across.
#[allow(clippy::too_many_arguments)] #[allow(clippy::too_many_arguments)]
pub(crate) fn render_tile(&self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, texture: &wgpu::Texture, pattern: &GeneratorPattern, corner: DVec2, texel: f64) { pub(crate) fn render_tile(
&self,
executor: &WgpuExecutor,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
held: &mut Vec<Texture>,
texture: &wgpu::Texture,
pattern: &GeneratorPattern,
corner: DVec2,
texel: f64,
) {
let device = &executor.context().device;
let tile = Tile::new(pattern, corner, texel, texture.width()); let tile = Tile::new(pattern, corner, texel, texture.width());
let (pipeline, bind_group_layout) = self.pipeline(device, tile.shader); let (pipeline, bind_group_layout) = self.pipeline(device, tile.shader);
@@ -414,7 +407,12 @@ impl GeneratorPasses {
contents: &tile.parameters, contents: &tile.parameters,
usage: wgpu::BufferUsages::UNIFORM, usage: wgpu::BufferUsages::UNIFORM,
}); });
let reference_view = (tile.shader == Shader::Mandelbrot).then(|| reference_texture(device, queue, tile.reference.as_ref()).create_view(&wgpu::TextureViewDescriptor::default())); let reference_view = (tile.shader == Shader::Mandelbrot).then(|| {
let reference = reference_texture(executor, queue, tile.reference.as_ref());
let view = reference.create_view(&wgpu::TextureViewDescriptor::default());
held.push(reference);
view
});
let mut entries = vec![wgpu::BindGroupEntry { let mut entries = vec![wgpu::BindGroupEntry {
binding: 0, binding: 0,
resource: buffer.as_entire_binding(), resource: buffer.as_entire_binding(),
@@ -1,3 +1,4 @@
use crate::WgpuExecutor;
use crate::vello_adjustments::adjustment_run_hash; use crate::vello_adjustments::adjustment_run_hash;
use crate::vello_effects::{EffectPasses, EffectTextures}; use crate::vello_effects::{EffectPasses, EffectTextures};
use crate::vello_generators::GeneratorPasses; use crate::vello_generators::GeneratorPasses;
@@ -5,7 +6,7 @@ use core_types::blending::BlendMode;
use glam::{DAffine2, UVec2}; use glam::{DAffine2, UVec2};
use graphic_types::effect_layers::EffectLayers; use graphic_types::effect_layers::EffectLayers;
use graphic_types::effects::EffectCapture; use graphic_types::effects::EffectCapture;
use graphic_types::raster_types::{CPU, Image, Raster, WeakCPU}; use graphic_types::raster_types::{CPU, Image, Raster, Texture, TextureWeakRef, WeakCPU};
use graphic_types::{Adjustment, Effects}; use graphic_types::{Adjustment, Effects};
use rendering::vello_scene_builder::{EffectsRenderer, GeneratorTile, SceneImage, VelloSceneBuilder, image_downscale_factor, image_texture_size}; use rendering::vello_scene_builder::{EffectsRenderer, GeneratorTile, SceneImage, VelloSceneBuilder, image_downscale_factor, image_texture_size};
use std::collections::HashMap; use std::collections::HashMap;
@@ -25,12 +26,6 @@ pub(crate) const TEXTURE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba
/// 16-bit unorm comes first for holding every 8-bit level exactly, unlike half floats. /// 16-bit unorm comes first for holding every 8-bit level exactly, unlike half floats.
const PRECISE_FORMATS: &[wgpu::TextureFormat] = &[wgpu::TextureFormat::Rgba16Unorm, wgpu::TextureFormat::Rgba16Float]; const PRECISE_FORMATS: &[wgpu::TextureFormat] = &[wgpu::TextureFormat::Rgba16Unorm, wgpu::TextureFormat::Rgba16Float];
/// How many renders a GPU texture's premultiplied copy survives without being drawn before it is freed.
const UNUSED_IMAGE_RENDER_LIMIT: u64 = 60;
/// About the most tiles of generators kept between renders, past which the least recently drawn are freed. Tiles drawn in the same render are kept or freed together.
const MAX_CACHED_GENERATOR_TILES: usize = 256;
/// How many times a render with too much content for Vello GPU is halved, reaching areas 1/4096 the size of the original. /// How many times a render with too much content for Vello GPU is halved, reaching areas 1/4096 the size of the original.
const MAX_SPLIT_DEPTH: u32 = 12; const MAX_SPLIT_DEPTH: u32 = 12;
@@ -54,8 +49,6 @@ pub(crate) struct VelloRenderer {
pub struct VelloCanvas { pub struct VelloCanvas {
/// Scenes to draw into, one for each depth of effects groups nested in a render, reused between renders to keep their allocations. /// Scenes to draw into, one for each depth of effects groups nested in a render, reused between renders to keep their allocations.
spare_scenes: Vec<vello_gpu::Scene>, spare_scenes: Vec<vello_gpu::Scene>,
/// The premultiplied texture Vello GPU renders into before conversion to straight alpha, kept while the render size stays the same.
premultiplied_target: Option<wgpu::Texture>,
images: ImageTextures, images: ImageTextures,
effect_textures: EffectTextures, effect_textures: EffectTextures,
} }
@@ -71,8 +64,7 @@ enum TargetAlpha {
struct RenderContext<'a> { struct RenderContext<'a> {
renderer: &'a VelloRenderer, renderer: &'a VelloRenderer,
canvas: &'a mut VelloCanvas, canvas: &'a mut VelloCanvas,
device: &'a wgpu::Device, executor: &'a WgpuExecutor,
queue: &'a Queue,
} }
impl VelloRenderer { impl VelloRenderer {
@@ -121,12 +113,10 @@ impl VelloRenderer {
/// Renders the scene `draw` draws on `canvas`, with its content placed by `view`, into `target` (an `Rgba8Unorm` texture of `size` with straight alpha). /// Renders the scene `draw` draws on `canvas`, with its content placed by `view`, into `target` (an `Rgba8Unorm` texture of `size` with straight alpha).
/// A render with more content than Vello GPU can hold calls `draw` again for each part it splits into. /// A render with more content than Vello GPU can hold calls `draw` again for each part it splits into.
#[expect(clippy::too_many_arguments)]
pub(crate) fn render( pub(crate) fn render(
&self, &self,
executor: &WgpuExecutor,
canvas: &mut VelloCanvas, canvas: &mut VelloCanvas,
device: &wgpu::Device,
queue: &Queue,
draw: &mut dyn FnMut(&mut VelloSceneBuilder), draw: &mut dyn FnMut(&mut VelloSceneBuilder),
view: Affine, view: Affine,
size: UVec2, size: UVec2,
@@ -137,12 +127,7 @@ impl VelloRenderer {
} }
canvas.images.render_count += 1; canvas.images.render_count += 1;
let mut context = RenderContext { let mut context = RenderContext { renderer: self, canvas, executor };
renderer: self,
canvas,
device,
queue,
};
context.render_area(draw, view, size, target, TargetAlpha::Straight); context.render_area(draw, view, size, target, TargetAlpha::Straight);
canvas.images.free_unused(); canvas.images.free_unused();
canvas.effect_textures.finish_render(); canvas.effect_textures.finish_render();
@@ -152,25 +137,30 @@ impl VelloRenderer {
/// Renders a `scene` drawn beforehand on `canvas` into `target` (an `Rgba8Unorm` texture of the scene's size with straight alpha). /// Renders a `scene` drawn beforehand on `canvas` into `target` (an `Rgba8Unorm` texture of the scene's size with straight alpha).
/// Unlike [`Self::render`], it can't split the scene, so one with more content than Vello GPU can hold renders transparent. /// Unlike [`Self::render`], it can't split the scene, so one with more content than Vello GPU can hold renders transparent.
pub(crate) fn render_scene(&self, canvas: &mut VelloCanvas, device: &wgpu::Device, queue: &Queue, scene: VelloSceneBuilder, target: &wgpu::Texture) { pub(crate) fn render_scene(&self, executor: &WgpuExecutor, canvas: &mut VelloCanvas, scene: VelloSceneBuilder, target: &wgpu::Texture) {
canvas.images.render_count += 1; canvas.images.render_count += 1;
let max_texture_size = scene.max_texture_size(); let max_texture_size = scene.max_texture_size();
let mut context = RenderContext { let mut context = RenderContext { renderer: self, canvas, executor };
renderer: self,
canvas,
device,
queue,
};
let (scene, images) = scene.finish(); let (scene, images) = scene.finish();
if let Err(error) = context.submit(&scene, images, max_texture_size, target, TargetAlpha::Straight, true) { if let Err(error) = context.submit(&scene, images, max_texture_size, target, TargetAlpha::Straight, true) {
log::error!("Vello GPU failed to render: {error}"); log::error!("Vello GPU failed to render: {error}");
clear(device, queue, target); clear(&executor.context().device, &executor.context().queue, target);
} }
canvas.images.free_unused(); canvas.images.free_unused();
canvas.effect_textures.finish_render(); canvas.effect_textures.finish_render();
} }
} }
impl<'a> RenderContext<'a> {
fn device(&self) -> &'a wgpu::Device {
&self.executor.context().device
}
fn queue(&self) -> &'a Queue {
&self.executor.context().queue
}
}
impl RenderContext<'_> { impl RenderContext<'_> {
/// Renders the scene `draw` draws into `target`, a texture of `size`, splitting its area into halves while it holds more content than one render can. /// Renders the scene `draw` draws into `target`, a texture of `size`, splitting its area into halves while it holds more content than one render can.
fn render_area(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, target: &wgpu::Texture, target_alpha: TargetAlpha) { fn render_area(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, target: &wgpu::Texture, target_alpha: TargetAlpha) {
@@ -182,7 +172,7 @@ impl RenderContext<'_> {
/// Renders each half of the area of `target`, a texture of `size`, after rendering it whole failed with `error`, splitting again each half that still holds too much. /// Renders each half of the area of `target`, a texture of `size`, after rendering it whole failed with `error`, splitting again each half that still holds too much.
#[expect(clippy::too_many_arguments)] #[expect(clippy::too_many_arguments)]
fn render_halves(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, target: &wgpu::Texture, target_alpha: TargetAlpha, error: RenderError, split_depth: u32) { fn render_halves(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, target: &wgpu::Texture, target_alpha: TargetAlpha, error: RenderError, split_depth: u32) {
let (device, queue) = (self.device, self.queue); let (device, queue) = (self.device(), self.queue());
// Each half covers less of the scene, so it has less content and smaller layers to hold // Each half covers less of the scene, so it has less content and smaller layers to hold
let too_much_to_hold = matches!( let too_much_to_hold = matches!(
@@ -203,14 +193,9 @@ impl RenderContext<'_> {
let top = size.y / 2; let top = size.y / 2;
[(UVec2::ZERO, UVec2::new(size.x, top)), (UVec2::new(0, top), UVec2::new(size.x, size.y - top))] [(UVec2::ZERO, UVec2::new(size.x, top)), (UVec2::new(0, top), UVec2::new(size.x, size.y - top))]
}; };
let executor = self.executor;
let halves = halves.map(|(offset, half_size)| { let halves = halves.map(|(offset, half_size)| {
let half_target = create_texture( let half_target = executor.request_texture_with_format(half_size, target.format());
device,
"vello_gpu_split_target",
half_size,
target.format(),
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,
);
let half_view = Affine::translate((-(offset.x as f64), -(offset.y as f64))) * view; let half_view = Affine::translate((-(offset.x as f64), -(offset.y as f64))) * view;
let rendered = self.render_once(draw, half_view, half_size, &half_target, target_alpha); let rendered = self.render_once(draw, half_view, half_size, &half_target, target_alpha);
(offset, half_size, half_view, half_target, rendered) (offset, half_size, half_view, half_target, rendered)
@@ -254,7 +239,7 @@ impl RenderContext<'_> {
/// Renders the scene `draw` draws into `target`, a texture of `size`, in a single Vello GPU render. /// Renders the scene `draw` draws into `target`, a texture of `size`, in a single Vello GPU render.
fn render_once(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, target: &wgpu::Texture, target_alpha: TargetAlpha) -> Result<(), RenderError> { fn render_once(&mut self, draw: &mut dyn FnMut(&mut VelloSceneBuilder), view: Affine, size: UVec2, target: &wgpu::Texture, target_alpha: TargetAlpha) -> Result<(), RenderError> {
let max_texture_size = self.device.limits().max_texture_dimension_2d; let max_texture_size = self.device().limits().max_texture_dimension_2d;
let max_size = max_texture_size.min(u16::MAX as u32); let max_size = max_texture_size.min(u16::MAX as u32);
let (mut scene, mut images, apron) = self.draw_scene(draw, view, size, max_texture_size, largest_apron(size, max_size)); let (mut scene, mut images, apron) = self.draw_scene(draw, view, size, max_texture_size, largest_apron(size, max_size));
@@ -266,17 +251,11 @@ impl RenderContext<'_> {
let grown_view = Affine::translate((apron as f64, apron as f64)) * view; let grown_view = Affine::translate((apron as f64, apron as f64)) * view;
let (scene, images, _) = self.draw_scene(draw, grown_view, grown_size, max_texture_size, 0); let (scene, images, _) = self.draw_scene(draw, grown_view, grown_size, max_texture_size, 0);
let grown_target = create_texture( let grown_target = self.executor.request_texture_with_format(grown_size, target.format());
self.device,
"vello_gpu_grown_target",
grown_size,
target.format(),
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC,
);
let rendered = self.submit(&scene, images, max_texture_size, &grown_target, target_alpha, true); let rendered = self.submit(&scene, images, max_texture_size, &grown_target, target_alpha, true);
self.canvas.spare_scenes.push(scene); self.canvas.spare_scenes.push(scene);
let mut encoder = self.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_gpu_grown_copy") }); let mut encoder = self.device().create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_gpu_grown_copy") });
encoder.copy_texture_to_texture( encoder.copy_texture_to_texture(
wgpu::TexelCopyTextureInfo { wgpu::TexelCopyTextureInfo {
origin: wgpu::Origin3d { x: apron, y: apron, z: 0 }, origin: wgpu::Origin3d { x: apron, y: apron, z: 0 },
@@ -289,7 +268,7 @@ impl RenderContext<'_> {
depth_or_array_layers: 1, depth_or_array_layers: 1,
}, },
); );
self.queue.submit([encoder.finish()]); self.queue().submit([encoder.finish()]);
return rendered; return rendered;
} }
@@ -334,23 +313,34 @@ impl RenderContext<'_> {
/// Renders a drawn scene, with the images it draws, into `target`, a texture of the scene's size, in a single Vello GPU render. /// Renders a drawn scene, with the images it draws, into `target`, a texture of the scene's size, in a single Vello GPU render.
/// The effects results it draws are freed for reuse after it, even if it fails when `release_failed`. /// The effects results it draws are freed for reuse after it, even if it fails when `release_failed`.
fn submit(&mut self, scene: &vello_gpu::Scene, images: Vec<SceneImage>, max_texture_size: u32, target: &wgpu::Texture, target_alpha: TargetAlpha, release_failed: bool) -> Result<(), RenderError> { fn submit(&mut self, scene: &vello_gpu::Scene, images: Vec<SceneImage>, max_texture_size: u32, target: &wgpu::Texture, target_alpha: TargetAlpha, release_failed: bool) -> Result<(), RenderError> {
let device = self.device; let device = self.device();
let (width, height) = (scene.width(), scene.height()); let (width, height) = (scene.width(), scene.height());
let size = UVec2::new(width as u32, height as u32); let size = UVec2::new(width as u32, height as u32);
// Locked from here to the submission, so drawing a scene doesn't hold up other uses of the queue // Locked from here to the submission, so drawing a scene doesn't hold up other uses of the queue
let queue = self.queue.lock(); let queue = self.queue().lock();
// Each render submits its own encoder, since Vello GPU stages its uploads for the next submission // Each render submits its own encoder, since Vello GPU stages its uploads for the next submission
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_gpu_render") }); let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("vello_gpu_render") });
// Supply the textures of the images the scene draws, under the IDs it drew them with // Supply the textures of the images the scene draws, under the IDs it drew them with
let mut texture_bindings = TextureBindings::new(); let mut texture_bindings = TextureBindings::new();
let mut held = Vec::new();
for (id, image) in images.iter().enumerate() { for (id, image) in images.iter().enumerate() {
let view = self let view = match image {
.canvas SceneImage::Texture(source) => {
.images let premultiplied = self.executor.request_texture(UVec2::new(source.width(), source.height()));
.prepare(device, &queue, &mut encoder, &mut self.canvas.effect_textures, self.renderer, image, max_texture_size); let view = premultiplied.create_view(&wgpu::TextureViewDescriptor::default());
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
self.renderer.alpha_conversion.premultiply(device, &mut encoder, &source_view, source.format().is_srgb(), &view);
held.push(premultiplied);
Some(view)
}
_ => self
.canvas
.images
.prepare(self.executor, &queue, &mut encoder, &mut self.canvas.effect_textures, self.renderer, image, max_texture_size, &mut held),
};
// Adjustments draw a copy of the texture they're carried out on // Adjustments draw a copy of the texture they're carried out on
let view = match image { let view = match image {
@@ -358,7 +348,7 @@ impl RenderContext<'_> {
let effects = (&self.renderer.effect_passes, &mut self.canvas.effect_textures); let effects = (&self.renderer.effect_passes, &mut self.canvas.effect_textures);
self.canvas self.canvas
.images .images
.prepare_adjusted(device, &queue, effects, raster, adjustments, max_texture_size, self.renderer.precise_format) .prepare_adjusted(self.executor, &queue, effects, raster, adjustments, max_texture_size, self.renderer.precise_format, &mut held)
}), }),
_ => view, _ => view,
}; };
@@ -370,21 +360,10 @@ impl RenderContext<'_> {
// Vello GPU renders premultiplied, which is converted to straight alpha unless the target wants it premultiplied // Vello GPU renders premultiplied, which is converted to straight alpha unless the target wants it premultiplied
let target_view = target.create_view(&wgpu::TextureViewDescriptor::default()); let target_view = target.create_view(&wgpu::TextureViewDescriptor::default());
let premultiplied_view = match (target_alpha, &self.canvas.premultiplied_target) { let premultiplied_target = (target_alpha == TargetAlpha::Straight).then(|| self.executor.request_texture(size));
(TargetAlpha::Premultiplied, _) => target_view.clone(), let premultiplied_view = match &premultiplied_target {
(TargetAlpha::Straight, Some(texture)) if texture.width() == size.x && texture.height() == size.y => texture.create_view(&wgpu::TextureViewDescriptor::default()), Some(texture) => texture.create_view(&wgpu::TextureViewDescriptor::default()),
(TargetAlpha::Straight, _) => { None => target_view.clone(),
let texture = create_texture(
device,
"vello_gpu_premultiplied_target",
size,
TEXTURE_FORMAT,
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
);
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
self.canvas.premultiplied_target = Some(texture);
view
}
}; };
let target_init = TargetInit::Clear(ClearSettings::Viewport { color: peniko::Color::TRANSPARENT }); let target_init = TargetInit::Clear(ClearSettings::Viewport { color: peniko::Color::TRANSPARENT });
@@ -445,24 +424,24 @@ impl EffectsRenderer for RenderContext<'_> {
draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder), draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder),
draw: &mut dyn FnMut(&mut VelloSceneBuilder), draw: &mut dyn FnMut(&mut VelloSceneBuilder),
) -> Vec<(wgpu::Texture, BlendMode)> { ) -> Vec<(wgpu::Texture, BlendMode)> {
let content_texture = self.canvas.effect_textures.acquire(self.device, size, self.renderer.precise_format); let content_texture = self.canvas.effect_textures.acquire(self.executor, size, self.renderer.precise_format);
self.render_area(draw, view, size, &content_texture, TargetAlpha::Premultiplied); self.render_area(draw, view, size, &content_texture, TargetAlpha::Premultiplied);
// The effects' drawn paints, each rendered over the same pixels as the content // The effects' drawn paints, each rendered over the same pixels as the content
let paint_count = effects.operations().map(|operation| operation.drawn_paints().count()).sum(); let paint_count = effects.operations().map(|operation| operation.drawn_paints().count()).sum();
let paint_textures: Vec<wgpu::Texture> = (0..paint_count) let paint_textures: Vec<wgpu::Texture> = (0..paint_count)
.map(|index| { .map(|index| {
let paint_texture = self.canvas.effect_textures.acquire(self.device, size, self.renderer.precise_format); let paint_texture = self.canvas.effect_textures.acquire(self.executor, size, self.renderer.precise_format);
self.render_area(&mut |scene| draw_paint(index, scene), view, size, &paint_texture, TargetAlpha::Premultiplied); self.render_area(&mut |scene| draw_paint(index, scene), view, size, &paint_texture, TargetAlpha::Premultiplied);
paint_texture paint_texture
}) })
.collect(); .collect();
let queue = self.queue().lock();
let effect_textures = &mut self.canvas.effect_textures; let effect_textures = &mut self.canvas.effect_textures;
let queue = self.queue.lock();
let effect_passes = &self.renderer.effect_passes; let effect_passes = &self.renderer.effect_passes;
let results = effect_passes.apply( let results = effect_passes.apply(
self.device, self.executor,
&queue, &queue,
effect_textures, effect_textures,
&content_texture, &content_texture,
@@ -484,7 +463,7 @@ impl EffectsRenderer for RenderContext<'_> {
fn render_backdrop(&mut self, scene: &vello_gpu::Scene, images: &[SceneImage], max_texture_size: u32) -> Option<wgpu::Texture> { fn render_backdrop(&mut self, scene: &vello_gpu::Scene, images: &[SceneImage], max_texture_size: u32) -> Option<wgpu::Texture> {
let size = UVec2::new(scene.width() as u32, scene.height() as u32); let size = UVec2::new(scene.width() as u32, scene.height() as u32);
let backdrop = self.canvas.effect_textures.acquire(self.device, size, self.renderer.precise_format); let backdrop = self.canvas.effect_textures.acquire(self.executor, size, self.renderer.precise_format);
// A failed render leaves the scene to go on drawing what it drew, so the results it draws stay in use // A failed render leaves the scene to go on drawing what it drew, so the results it draws stay in use
match self.submit(scene, images.to_vec(), max_texture_size, &backdrop, TargetAlpha::Premultiplied, false) { match self.submit(scene, images.to_vec(), max_texture_size, &backdrop, TargetAlpha::Premultiplied, false) {
@@ -515,122 +494,117 @@ fn clear(device: &wgpu::Device, queue: &Queue, target: &wgpu::Texture) {
queue.submit([encoder.finish()]); queue.submit([encoder.finish()]);
} }
/// Identifies the pixels behind an image texture: a blob of CPU pixels, a GPU texture, or a tile of a generator's pattern. /// Identifies the pixels behind an image texture: a blob of CPU pixels or a CPU raster.
#[derive(Clone, PartialEq, Eq, Hash)] #[derive(Clone, PartialEq, Eq, Hash)]
enum ImageKey { enum ImageKey {
Blob(u64), Blob(u64),
Raster(u64), Raster(u64),
Texture(wgpu::Texture),
GeneratorTile(GeneratorTile),
} }
/// A premultiplied copy of an image's pixels that Vello GPU samples as an external texture. /// A premultiplied copy of an image's pixels that Vello GPU samples as an external texture.
struct ImageTexture { struct ImageTexture {
texture: wgpu::Texture, texture: TextureWeakRef,
last_used: u64, last_used: u64,
/// The CPU raster pixels copied into the texture, which is freed once they're gone since they can't be drawn again. /// The CPU raster pixels copied into the texture, which is freed once they're gone since they can't be drawn again.
raster: Option<WeakCPU>, raster: Option<WeakCPU>,
/// Copies with runs of adjustments carried out on them, one for each run the image is drawn with. /// Copies with runs of adjustments carried out on them, one for each run the image is drawn with.
adjusted: Vec<AdjustedTexture>, adjusted: Vec<AdjustedTexture>,
/// The raster's straight linear colors in 32-bit floats that adjustments are carried out from, kept while any adjusted copy is. /// The raster's straight linear colors in 32-bit floats that adjustments are carried out from, kept while any adjusted copy is.
adjustment_source: Option<wgpu::Texture>, adjustment_source: Option<TextureWeakRef>,
} }
/// A copy of an image's texture with a run of adjustments carried out on it, made over in place for another run. /// A copy of an image's texture with a run of adjustments carried out on it, made over for another run.
struct AdjustedTexture { struct AdjustedTexture {
texture: wgpu::Texture, texture: TextureWeakRef,
/// The hash of the run carried out on it, or `None` until one is. run_hash: u64,
run_hash: Option<u64>,
last_used: u64, last_used: u64,
} }
/// The textures of the images recent renders drew, each freed once it goes unused for long enough. /// The textures of the images recent renders drew, parked in the texture pool between renders.
#[derive(Default)] #[derive(Default)]
struct ImageTextures { struct ImageTextures {
textures: HashMap<ImageKey, ImageTexture>, textures: HashMap<ImageKey, ImageTexture>,
/// The textures of the generator tiles the last render freed, for its next render's new tiles to take over, as when changing a generator's settings replaces every tile. generator_tiles: HashMap<GeneratorTile, TextureWeakRef>,
spare_generator_tiles: Vec<wgpu::Texture>,
render_count: u64, render_count: u64,
} }
impl ImageTextures { impl ImageTextures {
/// A view of the premultiplied texture for `image`, uploading CPU pixels or rendering a generator's tile the first time they're drawn. /// A view of the premultiplied texture for `image`, uploading CPU pixels or rendering a generator's tile the first time they're drawn.
/// GPU textures are converted again at every render since the texture cache hands their textures out again with new contents.
#[expect(clippy::too_many_arguments)] #[expect(clippy::too_many_arguments)]
fn prepare( fn prepare(
&mut self, &mut self,
device: &wgpu::Device, executor: &WgpuExecutor,
queue: &wgpu::Queue, queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder, encoder: &mut wgpu::CommandEncoder,
effect_textures: &mut EffectTextures, effect_textures: &mut EffectTextures,
renderer: &VelloRenderer, renderer: &VelloRenderer,
image: &SceneImage, image: &SceneImage,
max_texture_size: u32, max_texture_size: u32,
held: &mut Vec<Texture>,
) -> Option<wgpu::TextureView> { ) -> Option<wgpu::TextureView> {
let key = match image { let key = match image {
SceneImage::Pixels(data) => ImageKey::Blob(data.data.id()), SceneImage::Pixels(data) => ImageKey::Blob(data.data.id()),
SceneImage::Raster { raster, .. } => ImageKey::Raster(raster.buffer_id()), SceneImage::Raster { raster, .. } => ImageKey::Raster(raster.buffer_id()),
SceneImage::Texture(texture) => ImageKey::Texture((**texture).clone()), SceneImage::GeneratorTile { pattern, tile } => {
SceneImage::GeneratorTile { tile, .. } => ImageKey::GeneratorTile(*tile), let texture = match self.generator_tiles.get(tile).and_then(TextureWeakRef::upgrade) {
Some(texture) => texture,
None => {
let texture = GeneratorPasses::tile_texture(executor, GeneratorTile::SAMPLES);
let (corner, texel) = tile.corner_and_texel();
renderer.generator_passes.render_tile(executor, queue, encoder, held, &texture, pattern, corner, texel);
renderer.effect_passes.record_mipmaps(executor, encoder, effect_textures, &texture);
self.generator_tiles.insert(*tile, texture.downgrade());
texture
}
};
let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
held.push(texture);
return Some(view);
}
// Effects results are premultiplied already // Effects results are premultiplied already
SceneImage::Rendered(texture) => return Some(texture.create_view(&wgpu::TextureViewDescriptor::default())), SceneImage::Rendered(texture) => return Some(texture.create_view(&wgpu::TextureViewDescriptor::default())),
SceneImage::Texture(_) => return None,
}; };
if !self.textures.contains_key(&key) { let texture = match self.textures.get(&key).and_then(|image_texture| image_texture.texture.upgrade()) {
let texture = match image { Some(texture) => texture,
SceneImage::Pixels(data) => { None => {
if data.format != peniko::ImageFormat::Rgba8 { let texture = match image {
log::error!("Unsupported image format {:?}", data.format); SceneImage::Pixels(data) => {
return None; if data.format != peniko::ImageFormat::Rgba8 {
log::error!("Unsupported image format {:?}", data.format);
return None;
}
upload_pixels(executor, queue, data.data.data(), data.width, data.height, data.alpha_type, max_texture_size)?
} }
SceneImage::Raster { raster, .. } => {
let (pixels, width, height) = raster.to_flat_u8();
upload_pixels(executor, queue, &pixels, width, height, peniko::ImageAlphaType::Alpha, max_texture_size)?
}
SceneImage::Rendered(_) | SceneImage::Texture(_) | SceneImage::GeneratorTile { .. } => return None,
};
let raster = match image {
SceneImage::Raster { raster, .. } => Some(raster.downgrade()),
SceneImage::Pixels(_) | SceneImage::Texture(_) | SceneImage::Rendered(_) | SceneImage::GeneratorTile { .. } => None,
};
self.textures.insert(
key.clone(),
ImageTexture {
texture: texture.downgrade(),
last_used: 0,
raster,
adjusted: Vec::new(),
adjustment_source: None,
},
);
texture
}
};
upload_pixels(device, queue, data.data.data(), data.width, data.height, data.alpha_type, max_texture_size)? self.textures.get_mut(&key)?.last_used = self.render_count;
} let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
SceneImage::Raster { raster, .. } => { held.push(texture);
let (pixels, width, height) = raster.to_flat_u8();
upload_pixels(device, queue, &pixels, width, height, peniko::ImageAlphaType::Alpha, max_texture_size)?
}
SceneImage::GeneratorTile { pattern, tile } => {
let texture = (self.spare_generator_tiles.pop()).unwrap_or_else(|| GeneratorPasses::tile_texture(device, GeneratorTile::SAMPLES));
let (corner, texel) = tile.corner_and_texel();
renderer.generator_passes.render_tile(device, queue, encoder, &texture, pattern, corner, texel);
renderer.effect_passes.record_mipmaps(device, encoder, effect_textures, &texture);
texture
}
SceneImage::Rendered(_) => return None,
SceneImage::Texture(texture) => create_texture(
device,
"vello_gpu_premultiplied_image",
UVec2::new(texture.width(), texture.height()),
TEXTURE_FORMAT,
wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
),
};
let raster = match image {
SceneImage::Raster { raster, .. } => Some(raster.downgrade()),
SceneImage::Pixels(_) | SceneImage::Texture(_) | SceneImage::Rendered(_) | SceneImage::GeneratorTile { .. } => None,
};
self.textures.insert(
key.clone(),
ImageTexture {
texture,
last_used: 0,
raster,
adjusted: Vec::new(),
adjustment_source: None,
},
);
}
let image_texture = self.textures.get_mut(&key)?;
image_texture.last_used = self.render_count;
let view = image_texture.texture.create_view(&wgpu::TextureViewDescriptor::default());
if let SceneImage::Texture(source) = image {
let source_view = source.create_view(&wgpu::TextureViewDescriptor::default());
renderer.alpha_conversion.premultiply(device, encoder, &source_view, source.format().is_srgb(), &view);
}
Some(view) Some(view)
} }
@@ -638,30 +612,38 @@ impl ImageTextures {
#[expect(clippy::too_many_arguments)] #[expect(clippy::too_many_arguments)]
fn prepare_adjusted( fn prepare_adjusted(
&mut self, &mut self,
device: &wgpu::Device, executor: &WgpuExecutor,
queue: &wgpu::Queue, queue: &wgpu::Queue,
effects: (&EffectPasses, &mut EffectTextures), effects: (&EffectPasses, &mut EffectTextures),
raster: &Raster<CPU>, raster: &Raster<CPU>,
run: &[Adjustment], run: &[Adjustment],
max_texture_size: u32, max_texture_size: u32,
precise_format: wgpu::TextureFormat, precise_format: wgpu::TextureFormat,
held: &mut Vec<Texture>,
) -> Option<wgpu::TextureView> { ) -> Option<wgpu::TextureView> {
let (effect_passes, effect_textures) = effects; let (effect_passes, effect_textures) = effects;
let run: Vec<&Adjustment> = run.iter().collect(); let run: Vec<&Adjustment> = run.iter().collect();
let run_hash = adjustment_run_hash(&run); let run_hash = adjustment_run_hash(&run);
let render_count = self.render_count; let render_count = self.render_count;
let image_texture = self.textures.get_mut(&ImageKey::Raster(raster.buffer_id()))?; let image_texture = self.textures.get_mut(&ImageKey::Raster(raster.buffer_id()))?;
let image = image_texture.texture.upgrade()?;
// A run seen before has its copy // A run seen before has its copy
if let Some(copy) = image_texture.adjusted.iter_mut().find(|copy| copy.run_hash == Some(run_hash)) { let seen = (image_texture.adjusted.iter_mut()).find(|copy| copy.run_hash == run_hash).and_then(|copy| {
copy.last_used = render_count; copy.last_used = render_count;
return Some(copy.texture.create_view(&wgpu::TextureViewDescriptor::default())); copy.texture.upgrade()
});
if let Some(copy) = seen {
let view = copy.create_view(&wgpu::TextureViewDescriptor::default());
held.push(copy);
return Some(view);
} }
image_texture.adjusted.retain(|copy| copy.run_hash != run_hash);
// A run that changes no color draws the texture itself // A run that changes no color draws the texture itself
let prepared = effect_textures.prepare_adjustments(device, queue, &run); let prepared = effect_textures.prepare_adjustments(executor, queue, &run);
if prepared.is_empty() { if prepared.is_empty() {
return Some(image_texture.texture.create_view(&wgpu::TextureViewDescriptor::default())); return Some(image.create_view(&wgpu::TextureViewDescriptor::default()));
} }
// A new run takes over the copy longest unused, as when dragging a slider makes a new run every render // A new run takes over the copy longest unused, as when dragging a slider makes a new run every render
@@ -669,85 +651,59 @@ impl ImageTextures {
.filter(|(_, copy)| copy.last_used < render_count) .filter(|(_, copy)| copy.last_used < render_count)
.min_by_key(|(_, copy)| copy.last_used) .min_by_key(|(_, copy)| copy.last_used)
.map(|(index, _)| index); .map(|(index, _)| index);
let index = match reusable { if let Some(index) = reusable {
Some(index) => index, image_texture.adjusted.swap_remove(index);
None => { }
let texture = device.create_texture(&wgpu::TextureDescriptor { let copy = executor.request_texture_with_mips(UVec2::new(image.width(), image.height()), precise_format, image.mip_level_count());
label: Some("vello_gpu_adjusted_image"),
size: image_texture.texture.size(),
mip_level_count: image_texture.texture.mip_level_count(),
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: precise_format,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
image_texture.adjusted.push(AdjustedTexture {
texture,
run_hash: None,
last_used: render_count,
});
image_texture.adjusted.len() - 1
}
};
// Adjusting the raster's own colors, rather than its 8-bit premultiplied texture, keeps faint colors from banding and steps landing as on the CPU // Adjusting the raster's own colors, rather than its 8-bit premultiplied texture, keeps faint colors from banding and steps landing as on the CPU
if image_texture.adjustment_source.is_none() { let source = match image_texture.adjustment_source.as_ref().and_then(TextureWeakRef::upgrade) {
image_texture.adjustment_source = upload_adjustment_source(device, queue, raster.data(), max_texture_size); Some(source) => Some(source),
} None => {
let (source, straight_linear) = match &image_texture.adjustment_source { let source = upload_adjustment_source(executor, queue, raster.data(), max_texture_size);
image_texture.adjustment_source = source.as_ref().map(Texture::downgrade);
source
}
};
let (source, straight_linear) = match &source {
Some(source) => (source, true), Some(source) => (source, true),
None => (&image_texture.texture, false), None => (&image, false),
}; };
let copy = &mut image_texture.adjusted[index]; effect_passes.adjust_image(executor, queue, effect_textures, source, straight_linear, &prepared, &copy);
effect_passes.adjust_image(device, queue, effect_textures, source, straight_linear, &prepared, &copy.texture); image_texture.adjusted.push(AdjustedTexture {
copy.run_hash = Some(run_hash); texture: copy.downgrade(),
copy.last_used = render_count; run_hash,
last_used: render_count,
});
Some(copy.texture.create_view(&wgpu::TextureViewDescriptor::default())) let view = copy.create_view(&wgpu::TextureViewDescriptor::default());
held.push(copy);
Some(view)
} }
fn free_unused(&mut self) { fn free_unused(&mut self) {
let render_count = self.render_count; let render_count = self.render_count;
let in_use = |last_used: u64| render_count - last_used < UNUSED_IMAGE_RENDER_LIMIT;
let kept = |key: &ImageKey, image_texture: &ImageTexture| match key { let kept = |key: &ImageKey, image_texture: &ImageTexture| match key {
// CPU pixels get a new blob ID at every render, so a blob this render didn't draw is unlikely to return // CPU pixels get a new blob ID at every render, so a blob this render didn't draw is unlikely to return
ImageKey::Blob(_) => image_texture.last_used == render_count, ImageKey::Blob(_) => image_texture.last_used == render_count,
ImageKey::Raster(_) => image_texture.last_used == render_count || (in_use(image_texture.last_used) && image_texture.raster.as_ref().is_some_and(WeakCPU::is_alive)), ImageKey::Raster(_) => image_texture.last_used == render_count || image_texture.raster.as_ref().is_some_and(WeakCPU::is_alive),
ImageKey::Texture(_) | ImageKey::GeneratorTile(_) => in_use(image_texture.last_used),
}; };
// Spares this render didn't take over are freed, and the tiles it freed become the next render's spares self.textures.retain(|key, image_texture| kept(key, image_texture) && image_texture.texture.upgrade().is_some());
self.spare_generator_tiles.clear(); self.generator_tiles.retain(|_, texture| texture.upgrade().is_some());
let unused = self.textures.extract_if(|key, image_texture| !kept(key, image_texture));
let unused_tiles = unused.filter(|(key, _)| matches!(key, ImageKey::GeneratorTile(_))).map(|(_, image_texture)| image_texture.texture);
self.spare_generator_tiles.extend(unused_tiles);
self.textures.values_mut().for_each(|image_texture| { self.textures.values_mut().for_each(|image_texture| {
image_texture.adjusted.retain(|copy| in_use(copy.last_used)); image_texture.adjusted.retain(|copy| copy.texture.upgrade().is_some());
if image_texture.adjusted.is_empty() { if image_texture.adjusted.is_empty() {
image_texture.adjustment_source = None; image_texture.adjustment_source = None;
} }
}); });
// Panning and zooming across a generator leaves tiles behind faster than they go unused for long, so the least recent beyond a limit are freed too
let mut tile_ages: Vec<u64> = (self.textures.iter())
.filter(|(key, _)| matches!(key, ImageKey::GeneratorTile(_)))
.map(|(_, image_texture)| image_texture.last_used)
.collect();
if tile_ages.len() > MAX_CACHED_GENERATOR_TILES {
let excess = tile_ages.len() - MAX_CACHED_GENERATOR_TILES;
let (_, &mut oldest_kept, _) = tile_ages.select_nth_unstable(excess);
let least_recent = (self.textures).extract_if(|key, image_texture| matches!(key, ImageKey::GeneratorTile(_)) && image_texture.last_used < oldest_kept);
self.spare_generator_tiles.extend(least_recent.map(|(_, image_texture)| image_texture.texture));
}
} }
} }
/// Uploads CPU pixels as a premultiplied texture, downscaling them by a whole factor if they exceed `max_texture_size`. /// Uploads CPU pixels as a premultiplied texture, downscaling them by a whole factor if they exceed `max_texture_size`.
fn upload_pixels(device: &wgpu::Device, queue: &wgpu::Queue, pixels: &[u8], width: u32, height: u32, alpha_type: peniko::ImageAlphaType, max_texture_size: u32) -> Option<wgpu::Texture> { fn upload_pixels(executor: &WgpuExecutor, queue: &wgpu::Queue, pixels: &[u8], width: u32, height: u32, alpha_type: peniko::ImageAlphaType, max_texture_size: u32) -> Option<Texture> {
if width == 0 || height == 0 { if width == 0 || height == 0 {
return None; return None;
} }
@@ -776,20 +732,7 @@ fn upload_pixels(device: &wgpu::Device, queue: &wgpu::Queue, pixels: &[u8], widt
// Each mipmap level halves the one before it, so a minified image averages its pixels rather than skipping over them // Each mipmap level halves the one before it, so a minified image averages its pixels rather than skipping over them
let level_count = texture_width.max(texture_height).ilog2() + 1; let level_count = texture_width.max(texture_height).ilog2() + 1;
let texture = device.create_texture(&wgpu::TextureDescriptor { let texture = executor.request_texture_with_mips(UVec2::new(texture_width, texture_height), TEXTURE_FORMAT, level_count);
label: Some("vello_gpu_image"),
size: wgpu::Extent3d {
width: texture_width,
height: texture_height,
depth_or_array_layers: 1,
},
mip_level_count: level_count,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: TEXTURE_FORMAT,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let (mut level_pixels, mut level_width, mut level_height) = (pixels, texture_width, texture_height); let (mut level_pixels, mut level_width, mut level_height) = (pixels, texture_width, texture_height);
for level in 0..level_count { for level in 0..level_count {
@@ -880,7 +823,7 @@ fn box_downscale<Channel: Copy + Into<f32>>(pixels: &[Channel], width: u32, heig
/// Uploads a raster's straight linear colors as one level of 32-bit floats, the size [`upload_pixels`] makes them, so adjustments read the CPU's exact values. /// Uploads a raster's straight linear colors as one level of 32-bit floats, the size [`upload_pixels`] makes them, so adjustments read the CPU's exact values.
/// A raster too large for one texture is averaged down to fit on premultiplied gamma-encoded channels, as [`upload_pixels`] averages them. /// A raster too large for one texture is averaged down to fit on premultiplied gamma-encoded channels, as [`upload_pixels`] averages them.
fn upload_adjustment_source(device: &wgpu::Device, queue: &wgpu::Queue, image: &Image<core_types::Color>, max_texture_size: u32) -> Option<wgpu::Texture> { fn upload_adjustment_source(executor: &WgpuExecutor, queue: &wgpu::Queue, image: &Image<core_types::Color>, max_texture_size: u32) -> Option<Texture> {
let (width, height) = (image.width, image.height); let (width, height) = (image.width, image.height);
if width == 0 || height == 0 { if width == 0 || height == 0 {
return None; return None;
@@ -917,16 +860,7 @@ fn upload_adjustment_source(device: &wgpu::Device, queue: &wgpu::Queue, image: &
height: texture_height, height: texture_height,
depth_or_array_layers: 1, depth_or_array_layers: 1,
}; };
let texture = device.create_texture(&wgpu::TextureDescriptor { let texture = executor.request_texture_with_format(UVec2::new(texture_width, texture_height), format);
label: Some("vello_gpu_adjustment_source"),
size,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
queue.write_texture( queue.write_texture(
wgpu::TexelCopyTextureInfo { wgpu::TexelCopyTextureInfo {
texture: &texture, texture: &texture,
@@ -965,23 +899,6 @@ fn clear_texture(encoder: &mut wgpu::CommandEncoder, view: &wgpu::TextureView) {
}); });
} }
fn create_texture(device: &wgpu::Device, label: &str, size: UVec2, format: wgpu::TextureFormat, usage: wgpu::TextureUsages) -> wgpu::Texture {
device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d {
width: size.x.max(1),
height: size.y.max(1),
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage,
view_formats: &[],
})
}
/// Full-target passes converting between straight and premultiplied alpha. /// Full-target passes converting between straight and premultiplied alpha.
struct AlphaConversion { struct AlphaConversion {
bind_group_layout: wgpu::BindGroupLayout, bind_group_layout: wgpu::BindGroupLayout,
@@ -1647,7 +1647,7 @@ fn gpu_effect_texels(effects: &graphic_types::Effects, texels: &[[half::f16; 4]]
let mut textures = crate::vello_effects::EffectTextures::default(); let mut textures = crate::vello_effects::EffectTextures::default();
let layers = graphic_types::effect_layers::EffectLayers::plan(effects, BlendMode::Normal, 1., false); let layers = graphic_types::effect_layers::EffectLayers::plan(effects, BlendMode::Normal, 1., false);
let results = effect_passes.apply(device, &queue, &mut textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &paints, None, None); let results = effect_passes.apply(executor, &queue, &mut textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &paints, None, None);
let (result, _) = results.into_iter().next()?; let (result, _) = results.into_iter().next()?;
drop(queue); drop(queue);
@@ -4369,7 +4369,7 @@ fn gpu_adjusted_texels(run: &[graphic_types::Adjustment], texels: &[[half::f16;
let effects = Effects::from_operations(run.iter().cloned().map(EffectOperation::Adjustment)); let effects = Effects::from_operations(run.iter().cloned().map(EffectOperation::Adjustment));
let mut textures = crate::vello_effects::EffectTextures::default(); let mut textures = crate::vello_effects::EffectTextures::default();
let layers = graphic_types::effect_layers::EffectLayers::plan(&effects, core_types::blending::BlendMode::Normal, fill, false); let layers = graphic_types::effect_layers::EffectLayers::plan(&effects, core_types::blending::BlendMode::Normal, fill, false);
let results = effect_passes.apply(device, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None, None); let results = effect_passes.apply(executor, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None, None);
let (adjusted, _) = results.into_iter().next().expect("the adjustments draw one layer"); let (adjusted, _) = results.into_iter().next().expect("the adjustments draw one layer");
drop(queue); drop(queue);
@@ -6366,8 +6366,10 @@ fn generator_tile_pixels(pattern: &graphic_types::generator::GeneratorPattern, c
let queue = executor.context().queue.lock(); let queue = executor.context().queue.lock();
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("generator_tile_test") }); let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("generator_tile_test") });
(executor.inner.vello_renderer.generator_passes).render_tile(device, &queue, &mut encoder, &texture, pattern, corner, texel); let mut held = Vec::new();
(executor.inner.vello_renderer.generator_passes).render_tile(executor, &queue, &mut encoder, &mut held, &texture, pattern, corner, texel);
queue.submit([encoder.finish()]); queue.submit([encoder.finish()]);
drop(held);
drop(queue); drop(queue);
let bytes = executor.read_texture_pixels(&texture).expect("Failed to read back the tile"); let bytes = executor.read_texture_pixels(&texture).expect("Failed to read back the tile");
@@ -6423,7 +6425,7 @@ fn generator_tiles_are_reused_across_a_pan() {
let Some(executor) = executor() else { return }; let Some(executor) = executor() else { return };
let _turn = take_turn(); let _turn = take_turn();
let max_texture_size = executor.context().device.limits().max_texture_dimension_2d; let max_texture_size = executor.context().device.limits().max_texture_dimension_2d;
let tiles = |canvas: &crate::VelloCanvas| canvas.images.textures.len(); let tiles = |canvas: &crate::VelloCanvas| canvas.images.generator_tiles.len();
// A pattern drawn two pixels to a unit, in tiles of 256 pixels, panned by part of a tile // A pattern drawn two pixels to a unit, in tiles of 256 pixels, panned by part of a tile
let mut canvas = crate::VelloCanvas::default(); let mut canvas = crate::VelloCanvas::default();
@@ -6442,44 +6444,6 @@ fn generator_tiles_are_reused_across_a_pan() {
assert!(panned < first, "panning renders only the tiles newly in view, not all {first} again (rendered {panned})"); assert!(panned < first, "panning renders only the tiles newly in view, not all {first} again (rendered {panned})");
} }
#[test]
fn new_generator_tiles_take_over_the_textures_of_freed_ones() {
use graphic_types::generator::{GeneratorPattern, NoiseSettings};
let Some(executor) = executor() else { return };
let _turn = take_turn();
let max_texture_size = executor.context().device.limits().max_texture_dimension_2d;
let tile_textures = |canvas: &crate::VelloCanvas| -> Vec<wgpu::Texture> {
(canvas.images.textures.iter())
.filter(|(key, _)| matches!(key, super::ImageKey::GeneratorTile(_)))
.map(|(_, image_texture)| image_texture.texture.clone())
.collect()
};
let mut canvas = crate::VelloCanvas::default();
let draw = |canvas: &mut crate::VelloCanvas, seed: i64| {
let mut scene = VelloSceneBuilder::new(512, 512, Affine::IDENTITY, max_texture_size);
scene.draw_generator(&GeneratorPattern::Noise(NoiseSettings { seed, ..noise_settings() }), Affine::scale(2.));
executor.render_vello_scene_on_canvas(canvas, scene).unwrap();
};
// The first pattern's tiles, freed once another is drawn for long enough
draw(&mut canvas, 1);
let freed = tile_textures(&canvas);
for _ in 0..super::UNUSED_IMAGE_RENDER_LIMIT {
draw(&mut canvas, 2);
}
// The textures in use since the first pattern was freed are the second's and the third's, which takes over the first's
let second = tile_textures(&canvas);
draw(&mut canvas, 3);
let third: Vec<_> = tile_textures(&canvas).into_iter().filter(|texture| !second.contains(texture)).collect();
assert!(
third.len() == freed.len() && third.iter().all(|texture| freed.contains(texture)),
"the third pattern's tiles render into the textures of the first's"
);
}
/// An effect stamped on content at `placement` the way its node stamps it, with displacement maps lined up with the content where it lies. /// An effect stamped on content at `placement` the way its node stamps it, with displacement maps lined up with the content where it lies.
fn stamped_at(operation: &graphic_types::EffectOperation, placement: DAffine2) -> graphic_types::Effect { fn stamped_at(operation: &graphic_types::EffectOperation, placement: DAffine2) -> graphic_types::Effect {
let mut operation = operation.clone(); let mut operation = operation.clone();
+10 -4
View File
@@ -28,10 +28,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
} = parsed; } = parsed;
let core_types = crate_ident.gcore()?; let core_types = crate_ident.gcore()?;
let category = attributes let category = attributes.category.as_ref().map(syn::LitStr::value).unwrap_or_default();
.category
.as_ref()
.expect("The 'category' attribute is required and should be checked during parsing, but was not found during codegen");
let mod_name = format_ident!("_{}_mod", mod_name); let mod_name = format_ident!("_{}_mod", mod_name);
let display_name = match &attributes.display_name.as_ref() { let display_name = match &attributes.display_name.as_ref() {
@@ -838,8 +835,15 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
footprint_invariant, footprint_invariant,
forwards_input, forwards_input,
inject_scope, inject_scope,
adapter,
transient,
.. ..
} = attributes.flags; } = attributes.flags;
let adapter = match adapter {
Some(AdapterKind::Conversion) => quote!(Some(gcore::registry::AdapterKind::Conversion)),
Some(AdapterKind::Rank) => quote!(Some(gcore::registry::AdapterKind::Rank)),
None => quote!(None),
};
let asynchronous = parsed.is_async; let asynchronous = parsed.is_async;
let version = attributes.version.unwrap_or(1); let version = attributes.version.unwrap_or(1);
// A node returning a `Destructure` struct records its fields as output connectors // A node returning a `Destructure` struct records its fields as output connectors
@@ -1053,6 +1057,8 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
forwards_input: #forwards_input, forwards_input: #forwards_input,
inject_scope: #inject_scope, inject_scope: #inject_scope,
asynchronous: #asynchronous, asynchronous: #asynchronous,
adapter: #adapter,
transient: #transient,
}, },
version: #version, version: #version,
output_fields: #output_fields, output_fields: #output_fields,
+80 -12
View File
@@ -52,8 +52,18 @@ pub(crate) struct NodeFlags {
pub(crate) skip_impl: bool, pub(crate) skip_impl: bool,
/// Whether the node refuses placeholder data. /// Whether the node refuses placeholder data.
pub(crate) no_partial: bool, pub(crate) no_partial: bool,
pub(crate) transient: bool,
/// Set on the `Destructure` derive's generated extractor nodes, which take the struct rather than an `Item` or `List`. Not parsed from source. /// Set on the `Destructure` derive's generated extractor nodes, which take the struct rather than an `Item` or `List`. Not parsed from source.
pub(crate) destructure_extractor: bool, pub(crate) destructure_extractor: bool,
/// Whether type resolution may insert this node on an edge, and how it changes the wire.
pub(crate) adapter: Option<AdapterKind>,
}
/// Mirrors `core_types::registry::AdapterKind`, which this proc-macro crate cannot depend on.
#[derive(Debug, Clone, Copy)]
pub(crate) enum AdapterKind {
Conversion,
Rank,
} }
#[derive(Debug, Default, Clone)] #[derive(Debug, Default, Clone)]
@@ -557,6 +567,25 @@ impl Parse for NodeFnAttributes {
// Example usage: // Example usage:
// #[node_macro::node(..., forwards_input, ...)] // #[node_macro::node(..., forwards_input, ...)]
"forwards_input" => set_flag(&mut flags.forwards_input, meta, "forwards_input")?, "forwards_input" => set_flag(&mut flags.forwards_input, meta, "forwards_input")?,
// Marks the node as an adapter that type resolution may insert on an edge, either converting the wire's element type or changing its rank.
//
// Example usage:
// #[node_macro::node(..., adapter(conversion), ...)]
// #[node_macro::node(..., adapter(rank), ...)]
"adapter" => {
let meta = meta.require_list()?;
if flags.adapter.is_some() {
return Err(Error::new_spanned(meta, "Multiple 'adapter' attributes are not allowed"));
}
let kind: Ident = meta
.parse_args()
.map_err(|_| Error::new_spanned(meta, "Expected 'conversion' or 'rank' for 'adapter', e.g., adapter(rank)"))?;
flags.adapter = Some(match kind.to_string().as_str() {
"conversion" => AdapterKind::Conversion,
"rank" => AdapterKind::Rank,
_ => return Err(Error::new_spanned(kind, "Expected 'conversion' or 'rank' for 'adapter', e.g., adapter(rank)")),
});
}
// Instructs the preprocessor to make this node available as a scope. // Instructs the preprocessor to make this node available as a scope.
// Other nodes can then access it with `#[scope(node::IDENTIFIER)]`. // Other nodes can then access it with `#[scope(node::IDENTIFIER)]`.
// //
@@ -598,13 +627,19 @@ impl Parse for NodeFnAttributes {
// Example usage: // Example usage:
// #[node_macro::node(..., no_partial, ...)] // #[node_macro::node(..., no_partial, ...)]
"no_partial" => set_flag(&mut flags.no_partial, meta, "no_partial")?, "no_partial" => set_flag(&mut flags.no_partial, meta, "no_partial")?,
// Marks a node that only code inserts into networks at runtime, so users never place it and documents never store it.
// It replaces 'category', keeps the node out of the node catalog, and exempts it from versions and migrations.
//
// Example usage:
// #[node_macro::node(transient, ...)]
"transient" => set_flag(&mut flags.transient, meta, "transient")?,
_ => { _ => {
return Err(Error::new_spanned( return Err(Error::new_spanned(
meta, meta,
indoc!( indoc!(
r#" r#"
Unsupported attribute in `node`. Unsupported attribute in `node`.
Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'memoize', 'footprint_invariant', 'forwards_input', 'inject_scope', 'placeholder', 'no_partial', and 'version'. Supported attributes are 'category', 'name', 'icon', 'path', 'skip_impl', 'inspector', 'cfg', 'memoize', 'footprint_invariant', 'forwards_input', 'adapter', 'inject_scope', 'placeholder', 'no_partial', 'transient', and 'version'.
Example usage: Example usage:
#[node_macro::node(..., name("Test Node"), ...)] #[node_macro::node(..., name("Test Node"), ...)]
"# "#
@@ -614,17 +649,28 @@ impl Parse for NodeFnAttributes {
} }
} }
if category.is_none() { match (&category, flags.transient) {
return Err(Error::new_spanned( (Some(category), true) => {
nested, return Err(Error::new_spanned(category, "The attributes 'transient' and 'category' cannot be combined"));
indoc!( }
r#" (None, false) => {
The attribute 'category' is required. return Err(Error::new_spanned(
Example usage: nested,
#[node_macro::node(..., category("Value"), ...)] indoc!(
"#, r#"
), One of the attributes 'category' or 'transient' is required.
)); Example usage:
#[node_macro::node(..., category("Value"), ...)]
"#,
),
));
}
_ => {}
}
if flags.transient
&& let Some(version) = nested.iter().find(|meta| meta.path().is_ident("version"))
{
return Err(Error::new_spanned(version, "The attributes 'transient' and 'version' cannot be combined"));
} }
Ok(NodeFnAttributes { Ok(NodeFnAttributes {
@@ -1738,6 +1784,28 @@ mod tests {
assert!(error_message.contains("Versions start at 1")); assert!(error_message.contains("Versions start at 1"));
} }
#[test]
fn test_transient() {
let input = quote!(
fn add(a: f64, b: f64) -> f64 {
a + b
}
);
let transient = parse_node_fn(quote!(transient, memoize), input.clone()).unwrap();
assert!(transient.attributes.flags.transient);
assert_eq!(transient.attributes.category, None);
let error_message = parse_node_fn(quote!(transient, category("Math: Arithmetic")), input.clone()).unwrap_err().to_string();
assert!(error_message.contains("'transient' and 'category' cannot be combined"));
let error_message = parse_node_fn(quote!(transient, version(2)), input.clone()).unwrap_err().to_string();
assert!(error_message.contains("'transient' and 'version' cannot be combined"));
let error_message = parse_node_fn(quote!(memoize), input).unwrap_err().to_string();
assert!(error_message.contains("One of the attributes 'category' or 'transient' is required"));
}
#[test] #[test]
fn test_async_node() { fn test_async_node() {
let attr = quote!(category("IO")); let attr = quote!(category("IO"));
@@ -64,7 +64,7 @@ fn basic_brush(
Ok(List::new_from_item(Item::new_from_element(raster).with_attribute(ATTR_TRANSFORM, transform))) Ok(List::new_from_item(Item::new_from_element(raster).with_attribute(ATTR_TRANSFORM, transform)))
} }
#[node_macro::node(category(""), inject_scope)] #[node_macro::node(transient, inject_scope)]
fn basic_brush_pipeline( fn basic_brush_pipeline(
_ctx: impl Ctx, _ctx: impl Ctx,
#[scope(ProtoNodeIdentifier::new("graphene_std::platform_application_io::WgpuExecutorNode"))] executor: Item<WgpuExecutor>, #[scope(ProtoNodeIdentifier::new("graphene_std::platform_application_io::WgpuExecutorNode"))] executor: Item<WgpuExecutor>,
+12 -12
View File
@@ -13,19 +13,19 @@ fn passthrough<'i, T: 'i + Send>(_: impl Ctx, content: T) -> T {
} }
/// Shifts a whole wire value onto a connector's type through the std `Into` trait, serving the whole-`List` erasure onto `ListDyn` under the input adapter identifier. /// Shifts a whole wire value onto a connector's type through the std `Into` trait, serving the whole-`List` erasure onto `ListDyn` under the input adapter identifier.
#[node_macro::node(category("_Adapters"), skip_impl)] #[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
fn into<'i, T: 'i + Send + Into<O>, O: 'i + Send>(_: impl Ctx, value: T, _out_ty: PhantomData<O>) -> O { fn into<'i, T: 'i + Send + Into<O>, O: 'i + Send>(_: impl Ctx, value: T, _out_ty: PhantomData<O>) -> O {
value.into() value.into()
} }
/// Raises an `Item` wire onto a `List` connector as its one-element list. /// Raises an `Item` wire onto a `List` connector as its one-element list.
#[node_macro::node(category("_Adapters"), skip_impl)] #[node_macro::node(category("_Adapters"), skip_impl, adapter(rank))]
fn item_to_list<'i, T: 'i + Send>(_: impl Ctx, value: Item<T>) -> List<T> { fn item_to_list<'i, T: 'i + Send>(_: impl Ctx, value: Item<T>) -> List<T> {
value.into() value.into()
} }
/// Boxes a ranked wire's element into a type-erased attribute value, carrying the cell's attributes through the wire. /// Boxes a ranked wire's element into a type-erased attribute value, carrying the cell's attributes through the wire.
#[node_macro::node(category("_Adapters"), skip_impl)] #[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
fn item_to_attribute_value<'i, T: 'i + Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static>( fn item_to_attribute_value<'i, T: 'i + Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static>(
_: impl Ctx, _: impl Ctx,
value: Item<T>, value: Item<T>,
@@ -36,7 +36,7 @@ fn item_to_attribute_value<'i, T: 'i + Clone + Send + Sync + Default + std::fmt:
} }
/// Boxes a whole `List` wire as one type-erased attribute value, for attributes whose per-item value is itself a collection. /// Boxes a whole `List` wire as one type-erased attribute value, for attributes whose per-item value is itself a collection.
#[node_macro::node(category("_Adapters"), skip_impl)] #[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
fn list_to_attribute_value<'i, T: 'i + Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static>( fn list_to_attribute_value<'i, T: 'i + Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static>(
_: impl Ctx, _: impl Ctx,
value: T, value: T,
@@ -46,27 +46,27 @@ fn list_to_attribute_value<'i, T: 'i + Clone + Send + Sync + Default + std::fmt:
} }
/// Wraps a whole `List` onto the wire as one rank-0 `Item<Bundle<T>>` so an entire collection can feed a connector that carries it as one opaque cell. /// Wraps a whole `List` onto the wire as one rank-0 `Item<Bundle<T>>` so an entire collection can feed a connector that carries it as one opaque cell.
#[node_macro::node(category("_Adapters"), skip_impl)] #[node_macro::node(category("_Adapters"), skip_impl, adapter(rank))]
fn bundle<'i, T: 'i + Send>(_: impl Ctx, value: List<T>) -> Item<Bundle<T>> { fn bundle<'i, T: 'i + Send>(_: impl Ctx, value: List<T>) -> Item<Bundle<T>> {
Item::new_from_element(Bundle(value)) Item::new_from_element(Bundle(value))
} }
/// Unwraps a `Bundle` wire back into the whole `List` it carries, restoring the collection after it passed through a connector as one opaque cell. /// Unwraps a `Bundle` wire back into the whole `List` it carries, restoring the collection after it passed through a connector as one opaque cell.
#[node_macro::node(category("_Adapters"), skip_impl)] #[node_macro::node(category("_Adapters"), skip_impl, adapter(rank))]
fn unbundle<'i, T: 'i + Send>(_: impl Ctx, value: Item<Bundle<T>>) -> List<T> { fn unbundle<'i, T: 'i + Send>(_: impl Ctx, value: Item<Bundle<T>>) -> List<T> {
value.into_element().0 value.into_element().0
} }
/// Converts an `Item` wire's element to a different element type it can produce through the std `Into` trait, /// Converts an `Item` wire's element to a different element type it can produce through the std `Into` trait,
/// letting a convertible wire feed an `Item` connector whose element type it does not match by identity. /// letting a convertible wire feed an `Item` connector whose element type it does not match by identity.
#[node_macro::node(category("_Adapters"), skip_impl)] #[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
fn into_item<'i, T: 'i + Send + Into<E>, E: 'i + Send>(_: impl Ctx, value: Item<T>, _element_ty: PhantomData<E>) -> Item<E> { fn into_item<'i, T: 'i + Send + Into<E>, E: 'i + Send>(_: impl Ctx, value: Item<T>, _element_ty: PhantomData<E>) -> Item<E> {
let (value, attributes) = value.into_parts(); let (value, attributes) = value.into_parts();
Item::from_parts(value.into(), attributes) Item::from_parts(value.into(), attributes)
} }
/// The `List` counterpart of `into_item`, converting every element to a different element type it can produce. /// The `List` counterpart of `into_item`, converting every element to a different element type it can produce.
#[node_macro::node(category("_Adapters"), skip_impl)] #[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
fn into_list<'i, T: 'i + Send + Clone + Into<E>, E: 'i + Send>(_: impl Ctx, value: List<T>, _element_ty: PhantomData<E>) -> List<E> { fn into_list<'i, T: 'i + Send + Clone + Into<E>, E: 'i + Send>(_: impl Ctx, value: List<T>, _element_ty: PhantomData<E>) -> List<E> {
value value
.into_iter() .into_iter()
@@ -79,19 +79,19 @@ fn into_list<'i, T: 'i + Send + Clone + Into<E>, E: 'i + Send>(_: impl Ctx, valu
/// Moves a whole `Item` wire inside an element type like `Graphic` that embeds ranked values as its variants. /// Moves a whole `Item` wire inside an element type like `Graphic` that embeds ranked values as its variants.
/// The attributes describe the element they arrived with, so they travel inside it and the fresh envelope starts empty. /// The attributes describe the element they arrived with, so they travel inside it and the fresh envelope starts empty.
#[node_macro::node(category("_Adapters"), skip_impl)] #[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
fn embed_item<'i, T: 'i + Send, E: 'i + Send + From<Item<T>>>(_: impl Ctx, value: Item<T>, _element_ty: PhantomData<E>) -> Item<E> { fn embed_item<'i, T: 'i + Send, E: 'i + Send + From<Item<T>>>(_: impl Ctx, value: Item<T>, _element_ty: PhantomData<E>) -> Item<E> {
Item::new_from_element(value.into()) Item::new_from_element(value.into())
} }
/// The `List` counterpart of `embed_item`, each item moving whole inside its own embedding element. /// The `List` counterpart of `embed_item`, each item moving whole inside its own embedding element.
#[node_macro::node(category("_Adapters"), skip_impl)] #[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
fn embed_list<'i, T: 'i + Send + Clone, E: 'i + Send + From<Item<T>>>(_: impl Ctx, value: List<T>, _element_ty: PhantomData<E>) -> List<E> { fn embed_list<'i, T: 'i + Send + Clone, E: 'i + Send + From<Item<T>>>(_: impl Ctx, value: List<T>, _element_ty: PhantomData<E>) -> List<E> {
value.into_iter().map(|item| Item::new_from_element(E::from(item))).collect() value.into_iter().map(|item| Item::new_from_element(E::from(item))).collect()
} }
/// The [`Convert`]-based counterpart of `into_item`, casting an `Item` wire's element to a connector's numeric element type. /// The [`Convert`]-based counterpart of `into_item`, casting an `Item` wire's element to a connector's numeric element type.
#[node_macro::node(category("_Adapters"), skip_impl)] #[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
fn convert_item<'i, T: 'i + Send + Convert<E, ()>, E: 'i + Send>(ctx: impl Ctx + ExtractFootprint, value: Item<T>, _element_ty: PhantomData<E>) -> Item<E> { fn convert_item<'i, T: 'i + Send + Convert<E, ()>, E: 'i + Send>(ctx: impl Ctx + ExtractFootprint, value: Item<T>, _element_ty: PhantomData<E>) -> Item<E> {
let footprint = *ctx.try_footprint().unwrap_or(&Footprint::DEFAULT); let footprint = *ctx.try_footprint().unwrap_or(&Footprint::DEFAULT);
let (value, attributes) = value.into_parts(); let (value, attributes) = value.into_parts();
@@ -100,7 +100,7 @@ fn convert_item<'i, T: 'i + Send + Convert<E, ()>, E: 'i + Send>(ctx: impl Ctx +
} }
/// The `List` counterpart of `convert_item`, casting every element to the connector's numeric element type. /// The `List` counterpart of `convert_item`, casting every element to the connector's numeric element type.
#[node_macro::node(category("_Adapters"), skip_impl)] #[node_macro::node(category("_Adapters"), skip_impl, adapter(conversion))]
fn convert_list<'i, T: 'i + Send + Clone + Convert<E, ()>, E: 'i + Send + Clone>(ctx: impl Ctx + ExtractFootprint, value: List<T>, _element_ty: PhantomData<E>) -> List<E> { fn convert_list<'i, T: 'i + Send + Clone + Convert<E, ()>, E: 'i + Send + Clone>(ctx: impl Ctx + ExtractFootprint, value: List<T>, _element_ty: PhantomData<E>) -> List<E> {
let footprint = *ctx.try_footprint().unwrap_or(&Footprint::DEFAULT); let footprint = *ctx.try_footprint().unwrap_or(&Footprint::DEFAULT);
@@ -274,7 +274,7 @@ fn pending_raster(_data: &List<Graphic>, _footprint: &Item<Footprint>, _executor
List::new() List::new()
} }
#[node_macro::node(category(""), inject_scope)] #[node_macro::node(transient, inject_scope)]
fn editor_api(_: impl Ctx, #[scope("editor-api")] editor_api: Item<Arc<PlatformEditorApi>>) -> Item<Arc<PlatformEditorApi>> { fn editor_api(_: impl Ctx, #[scope("editor-api")] editor_api: Item<Arc<PlatformEditorApi>>) -> Item<Arc<PlatformEditorApi>> {
editor_api editor_api
} }
@@ -283,7 +283,7 @@ fn editor_api(_: impl Ctx, #[scope("editor-api")] editor_api: Item<Arc<PlatformE
#[error("Application IO is unavailable")] #[error("Application IO is unavailable")]
pub struct ApplicationIoError; pub struct ApplicationIoError;
#[node_macro::node(category(""), inject_scope)] #[node_macro::node(transient, inject_scope)]
fn application_io(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: Item<Arc<PlatformEditorApi>>) -> Result<Item<Arc<PlatformApplicationIo>>, ApplicationIoError> { fn application_io(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: Item<Arc<PlatformEditorApi>>) -> Result<Item<Arc<PlatformApplicationIo>>, ApplicationIoError> {
editor_api.into_element().application_io.clone().map(Item::new_from_element).ok_or(ApplicationIoError) editor_api.into_element().application_io.clone().map(Item::new_from_element).ok_or(ApplicationIoError)
} }
@@ -292,7 +292,7 @@ fn application_io(_: impl Ctx, #[scope(editor_api::IDENTIFIER)] editor_api: Item
#[error("Resource {0} was not found")] #[error("Resource {0} was not found")]
pub struct ResourceError(ResourceHash); pub struct ResourceError(ResourceHash);
#[node_macro::node(category(""), version(2), placeholder = pending_stored_resource)] #[node_macro::node(transient, placeholder = pending_stored_resource)]
async fn resource( async fn resource(
_: impl Ctx, _: impl Ctx,
/// The content hash identifying which stored resource to load. /// The content hash identifying which stored resource to load.
@@ -314,12 +314,12 @@ fn pending_stored_resource(_hash: &Item<ResourceHash>, _application_io: &Item<Ar
#[error("Resource {0} is missing")] #[error("Resource {0} is missing")]
pub struct MissingResourceError(ResourceId); pub struct MissingResourceError(ResourceId);
#[node_macro::node(category(""))] #[node_macro::node(transient)]
fn missing_resource(_: impl Ctx, id: Item<ResourceId>) -> Result<Item<Resource>, (Item<Resource>, MissingResourceError)> { fn missing_resource(_: impl Ctx, id: Item<ResourceId>) -> Result<Item<Resource>, (Item<Resource>, MissingResourceError)> {
Err((Item::new_from_element(Resource::empty()), MissingResourceError(id.into_element()))) Err((Item::new_from_element(Resource::empty()), MissingResourceError(id.into_element())))
} }
#[node_macro::node(category(""), inject_scope)] #[node_macro::node(transient, inject_scope)]
fn wgpu_executor(_: impl Ctx, #[scope(application_io::IDENTIFIER)] application_io: Item<Arc<PlatformApplicationIo>>) -> Result<Item<::wgpu_executor::WgpuExecutor>, ::wgpu_executor::NoGpuError> { fn wgpu_executor(_: impl Ctx, #[scope(application_io::IDENTIFIER)] application_io: Item<Arc<PlatformApplicationIo>>) -> Result<Item<::wgpu_executor::WgpuExecutor>, ::wgpu_executor::NoGpuError> {
application_io.element().gpu_executor().cloned().map(Item::new_from_element).ok_or(::wgpu_executor::NoGpuError) application_io.element().gpu_executor().cloned().map(Item::new_from_element).ok_or(::wgpu_executor::NoGpuError)
} }
@@ -11,7 +11,7 @@ use rendering::{RenderParams, SvgRender, SvgRenderOutput};
use std::fmt::Write; use std::fmt::Write;
use wgpu_executor::{Buffer, WgpuExecutor, WgpuPipeline, WgpuPipelineCache}; use wgpu_executor::{Buffer, WgpuExecutor, WgpuPipeline, WgpuPipelineCache};
#[node_macro::node(category(""), version(2))] #[node_macro::node(transient)]
fn render_background( fn render_background(
ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, ctx: impl Ctx + ExtractFootprint + ExtractVarArgs,
data: Item<RenderOutput>, data: Item<RenderOutput>,
@@ -122,7 +122,7 @@ fn render_background(
Ok(Item::new_from_element(RenderOutput { data, metadata })) Ok(Item::new_from_element(RenderOutput { data, metadata }))
} }
#[node_macro::node(category(""), inject_scope)] #[node_macro::node(transient, inject_scope)]
fn composite_background_pipeline( fn composite_background_pipeline(
_ctx: impl Ctx, _ctx: impl Ctx,
#[scope(crate::platform_application_io::wgpu_executor::IDENTIFIER)] executor: Item<WgpuExecutor>, #[scope(crate::platform_application_io::wgpu_executor::IDENTIFIER)] executor: Item<WgpuExecutor>,
+1 -1
View File
@@ -330,7 +330,7 @@ fn split_oversized_region(region: RenderRegion, max_region_size: u32) -> Vec<Ren
result result
} }
#[node_macro::node(category(""), version(2))] #[node_macro::node(transient)]
fn render_output_cache( fn render_output_cache(
ctx: impl Ctx + ExtractAll + CloneVarArgs + ExtractRealTime + ExtractAnimationTime + ExtractPointerPosition + Sync, ctx: impl Ctx + ExtractAll + CloneVarArgs + ExtractRealTime + ExtractAnimationTime + ExtractPointerPosition + Sync,
data: impl Node<Context<'static>, Output = Item<RenderOutput>> + Send + Sync, data: impl Node<Context<'static>, Output = Item<RenderOutput>> + Send + Sync,
+3 -3
View File
@@ -30,7 +30,7 @@ pub struct RenderIntermediate {
pub(crate) metadata: RenderMetadata, pub(crate) metadata: RenderMetadata,
} }
#[node_macro::node(category(""))] #[node_macro::node(transient)]
fn render_intermediate<T: 'static + Render + WasmNotSend + Send + Sync>( fn render_intermediate<T: 'static + Render + WasmNotSend + Send + Sync>(
ctx: impl Ctx + ExtractVarArgs + ExtractAll + CloneVarArgs, ctx: impl Ctx + ExtractVarArgs + ExtractAll + CloneVarArgs,
#[implementations( #[implementations(
@@ -83,7 +83,7 @@ fn render_intermediate<T: 'static + Render + WasmNotSend + Send + Sync>(
Ok(Item::new_from_element(intermediate)) Ok(Item::new_from_element(intermediate))
} }
#[node_macro::node(category(""), version(3))] #[node_macro::node(transient)]
fn render( fn render(
ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, ctx: impl Ctx + ExtractFootprint + ExtractVarArgs,
data: Item<RenderIntermediate>, data: Item<RenderIntermediate>,
@@ -175,7 +175,7 @@ fn render(
data.map(|data| Item::new_from_element(RenderOutput { data, metadata })) data.map(|data| Item::new_from_element(RenderOutput { data, metadata }))
} }
#[node_macro::node(category(""))] #[node_macro::node(transient)]
fn create_context( fn create_context(
// The executor boundary supplies the render config as the sole vararg (see `wrap_network_with_render_node_in_scope()`) // The executor boundary supplies the render config as the sole vararg (see `wrap_network_with_render_node_in_scope()`)
ctx: impl Ctx + ExtractAll + CloneVarArgs + Sync, ctx: impl Ctx + ExtractAll + CloneVarArgs + Sync,
@@ -8,7 +8,7 @@ use rendering::{RenderOutputType as RenderOutputTypeRequest, RenderParams};
use vector_types::vector::style::RenderMode; use vector_types::vector::style::RenderMode;
use wgpu_executor::{WgpuExecutor, WgpuPipeline, WgpuPipelineCache}; use wgpu_executor::{WgpuExecutor, WgpuPipeline, WgpuPipelineCache};
#[node_macro::node(category(""), version(2))] #[node_macro::node(transient)]
fn render_pixel_preview( fn render_pixel_preview(
ctx: impl Ctx + ExtractAll + CloneVarArgs + Sync, ctx: impl Ctx + ExtractAll + CloneVarArgs + Sync,
data: impl Node<Context<'static>, Output = Item<RenderOutput>> + Send + Sync, data: impl Node<Context<'static>, Output = Item<RenderOutput>> + Send + Sync,
@@ -79,7 +79,7 @@ fn render_pixel_preview(
Ok(Item::new_from_element(result)) Ok(Item::new_from_element(result))
} }
#[node_macro::node(category(""), inject_scope)] #[node_macro::node(transient, inject_scope)]
fn pixel_preview_pipeline( fn pixel_preview_pipeline(
_ctx: impl Ctx, _ctx: impl Ctx,
#[scope(crate::platform_application_io::wgpu_executor::IDENTIFIER)] executor: Item<WgpuExecutor>, #[scope(crate::platform_application_io::wgpu_executor::IDENTIFIER)] executor: Item<WgpuExecutor>,
+4 -2
View File
@@ -206,6 +206,8 @@ impl Preprocessor {
forwards_input, forwards_input,
inject_scope, inject_scope,
asynchronous, asynchronous,
adapter: _,
transient: _,
}, },
output_fields, output_fields,
context_features, context_features,
@@ -552,7 +554,7 @@ mod destructure_tests {
fn assert_execution_result(network: NodeNetwork, expected: TaggedValue) { fn assert_execution_result(network: NodeNetwork, expected: TaggedValue) {
let proto_network = Compiler {}.compile_single(network).expect("Compilation should succeed").network; let proto_network = Compiler {}.compile_single(network).expect("Compilation should succeed").network;
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(proto_network).expect("The executor should type check and build"); let output = executor.insert(proto_network).expect("The executor should type check and build");
let context: core_types::Context = None; let context: core_types::Context = None;
let result = executor.tree().eval_tagged_value(output.node(), &context).expect("Execution should succeed"); let result = executor.tree().eval_tagged_value(output.node(), &context).expect("Execution should succeed");
@@ -932,7 +934,7 @@ mod tests {
let proto_network = Compiler {}.compile_single(network).unwrap().network; let proto_network = Compiler {}.compile_single(network).unwrap().network;
let mut executor = DynamicExecutor::default(); let mut executor = DynamicExecutor::default();
let (output, _) = executor.update(proto_network).unwrap(); let output = executor.insert(proto_network).unwrap();
let context: core_types::Context = None; let context: core_types::Context = None;
let Ok(core_types::Poll::Fallback(boxed)) = executor.execute(&output, context) else { let Ok(core_types::Poll::Fallback(boxed)) = executor.execute(&output, context) else {
panic!("The color lookup should evaluate with an error"); panic!("The color lookup should evaluate with an error");
+2 -1
View File
@@ -21,7 +21,8 @@ pub(crate) async fn coverage(corpus: &Corpus, list_uncovered: bool, include_hidd
} }
let metadata = NODE_METADATA.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let metadata = NODE_METADATA.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let counted: Vec<_> = metadata.iter().filter(|(_, metadata)| include_hidden || !is_hidden_category(metadata.category)).collect(); let saved = metadata.iter().filter(|(_, metadata)| !metadata.flags.transient);
let counted: Vec<_> = saved.filter(|(_, metadata)| include_hidden || !is_hidden_category(metadata.category)).collect();
let mut uncovered: Vec<_> = counted.iter().filter(|(identifier, _)| !used.contains(identifier.as_str())).collect(); let mut uncovered: Vec<_> = counted.iter().filter(|(identifier, _)| !used.contains(identifier.as_str())).collect();
let total = counted.len(); let total = counted.len();