Compare commits

...
18 changed files with 263 additions and 65 deletions

No files matched your search

Generated
+3
View File
@@ -4549,6 +4549,7 @@ dependencies = [
"graphene-std",
"interpreted-executor",
"log",
"wgpu-executor",
]
[[package]]
@@ -7159,6 +7160,8 @@ dependencies = [
"futures",
"glam",
"graphene-application-io",
"graphic-types",
"log",
"node-macro",
"raster-types",
"rendering",
+1 -1
View File
@@ -377,7 +377,7 @@ impl NodeRuntime {
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
let c = Compiler {};
let proto_network = match c.compile_single(scoped_network) {
let proto_network = match c.compile_single(scoped_network, Some(self.executor.typing_context_mut())) {
Ok(network) => network,
Err(e) => return Err((ResolvedDocumentNodeTypesDelta::default(), e)),
};
@@ -1,12 +1,15 @@
use criterion::{Criterion, black_box, criterion_group, criterion_main};
use criterion::{Criterion, criterion_group, criterion_main};
use graph_craft::util::DEMO_ART;
use std::hint::black_box;
fn compile_to_proto(c: &mut Criterion) {
use graph_craft::util::{compile, load_from_name};
let mut c = c.benchmark_group("Compile Network cold");
for name in DEMO_ART {
let network = load_from_name(name);
c.bench_function(name, |b| b.iter_batched(|| network.clone(), |network| compile(black_box(network)), criterion::BatchSize::SmallInput));
c.bench_function(name, |b| {
b.iter_batched(|| network.clone(), |network| compile(black_box(network), None), criterion::BatchSize::SmallInput)
});
}
}
@@ -5,7 +5,7 @@ use iai_callgrind::{library_benchmark, library_benchmark_group, main};
#[library_benchmark]
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = load_from_name)]
pub fn compile_to_proto(_input: NodeNetwork) {
std::hint::black_box(compile(_input));
std::hint::black_box(compile(_input, None));
}
library_benchmark_group!(name = compile_group; benchmarks = compile_to_proto);
@@ -1,11 +1,11 @@
use crate::document::NodeNetwork;
use crate::proto::{LocalFuture, ProtoNetwork};
use crate::proto::{LocalFuture, ProtoNetwork, TypingContext};
use std::error::Error;
pub struct Compiler {}
impl Compiler {
pub fn compile(&self, mut network: NodeNetwork) -> impl Iterator<Item = Result<ProtoNetwork, String>> {
pub fn compile(&self, mut network: NodeNetwork, mut ty: Option<&mut TypingContext>) -> impl Iterator<Item = Result<ProtoNetwork, String>> {
let node_ids = network.nodes.keys().copied().collect::<Vec<_>>();
network.populate_dependants();
for id in node_ids {
@@ -17,14 +17,14 @@ impl Compiler {
let proto_networks = network.into_proto_networks();
proto_networks.map(move |mut proto_network| {
proto_network.insert_context_nullification_nodes()?;
proto_network.generate_stable_node_ids();
proto_network.insert_context_nullification_nodes(ty.as_deref_mut())?;
// proto_network.generate_stable_node_ids();
Ok(proto_network)
})
}
pub fn compile_single(&self, network: NodeNetwork) -> Result<ProtoNetwork, String> {
pub fn compile_single(&self, network: NodeNetwork, ty: Option<&mut TypingContext>) -> Result<ProtoNetwork, String> {
assert_eq!(network.exports.len(), 1, "Graph with multiple outputs not yet handled");
let Some(proto_network) = self.compile(network).next() else {
let Some(proto_network) = self.compile(network, ty).next() else {
return Err("Failed to convert graph into proto graph".to_string());
};
proto_network
+90 -42
View File
@@ -211,6 +211,26 @@ enum NodeState {
Visited,
}
struct NodeList<'a> {
vec: Vec<(NodeId, ProtoNode)>,
ty: Option<&'a mut TypingContext>,
id_mapping: Vec<usize>,
}
impl<'a> NodeList<'a> {
fn push_node(&mut self, node: ProtoNode, old_node_idx: Option<usize>) -> Result<(NodeId, Option<Type>), GraphErrors> {
let node_id = node.stable_node_id().unwrap();
let out_ty = if let Some(ty) = &mut self.ty { Some(ty.infer(node_id, &node)?.return_value) } else { None };
// log::debug!("{old_node_idx:?}, {node_id:?}, {node:?}, {:?}", self.id_mapping);
if let Some(old_node_idx) = old_node_idx {
assert_eq!(old_node_idx, self.id_mapping.len());
self.id_mapping.push(self.vec.len());
}
self.vec.push((node_id, node));
Ok((node_id, out_ty))
}
}
impl ProtoNetwork {
fn check_ref(&self, ref_id: &NodeId, id: &NodeId) {
debug_assert!(
@@ -296,33 +316,44 @@ impl ProtoNetwork {
/// Inserts context nullification nodes to optimize caching.
/// This analysis is performed after topological sorting to ensure proper dependency tracking.
pub fn insert_context_nullification_nodes(&mut self) -> Result<(), String> {
pub fn insert_context_nullification_nodes(&mut self, ty: Option<&mut TypingContext>) -> Result<(), String> {
// Perform topological sort once
self.reorder_ids()?;
self.find_context_dependencies(self.output);
let mut new_order = NodeList {
vec: Vec::with_capacity(self.nodes.len() + 20),
ty,
id_mapping: Vec::with_capacity(self.nodes.len()),
};
let mut results = Vec::with_capacity(self.nodes.len());
for node_id in 0..self.nodes.len() {
self.find_context_dependencies(NodeId(node_id as u64), &mut new_order, &mut results).map_err(|e| format!("{e:?}"))?;
}
// Perform topological sort a second time to integrate the new nodes
self.reorder_ids()?;
self.nodes = new_order.vec;
self.output = results[self.output.0 as usize].1;
// log::debug!("{:?}", self.nodes);
// log::debug!("{:}", self);
// // Perform topological sort a second time to integrate the new nodes
// self.reorder_ids()?;
Ok(())
}
fn insert_context_nullification_node(&mut self, node_id: NodeId, context_deps: ContextFeatures) -> NodeId {
let (_, node) = &self.nodes[node_id.0 as usize];
fn insert_context_nullification_node(&mut self, old_node_id: NodeId, new_node_id: NodeId, context_deps: ContextFeatures, new_nodes: &mut NodeList) -> Result<NodeId, GraphErrors> {
let (_, node) = &self.nodes[old_node_id.0 as usize];
let mut path = node.original_location.path.clone();
// log::debug!("Inserting context nullification after {:?} with context features: {:?}", node.identifier, context_deps);
// Add a path extension with a placeholder value which should not conflict with existing paths
if let Some(p) = path.as_mut() {
p.push(NodeId(10))
}
let memo_node_id = NodeId(self.nodes.len() as u64);
self.nodes.push((
memo_node_id,
let (memo_node_id, _) = new_nodes.push_node(
ProtoNode {
construction_args: ConstructionArgs::Nodes(vec![node_id]),
construction_args: ConstructionArgs::Nodes(vec![new_node_id]),
call_argument: concrete!(Context),
identifier: graphene_core::memo::memo::IDENTIFIER,
original_location: OriginalLocation {
@@ -331,12 +362,10 @@ impl ProtoNetwork {
},
..Default::default()
},
));
None,
)?;
let nullification_value_node_id = NodeId(self.nodes.len() as u64);
self.nodes.push((
nullification_value_node_id,
let (nullification_value_node_id, _) = new_nodes.push_node(
ProtoNode {
construction_args: ConstructionArgs::Value(MemoHash::new(TaggedValue::ContextFeatures(context_deps))),
call_argument: concrete!(Context),
@@ -347,10 +376,9 @@ impl ProtoNetwork {
},
..Default::default()
},
));
let nullification_node_id = NodeId(self.nodes.len() as u64);
self.nodes.push((
nullification_node_id,
None,
)?;
let (nullification_node_id, _) = new_nodes.push_node(
ProtoNode {
construction_args: ConstructionArgs::Nodes(vec![memo_node_id, nullification_value_node_id]),
call_argument: concrete!(Context),
@@ -361,11 +389,12 @@ impl ProtoNetwork {
},
..Default::default()
},
));
nullification_node_id
None,
)?;
Ok(nullification_node_id)
}
fn find_context_dependencies(&mut self, id: NodeId) -> (ContextFeatures, Option<NodeId>) {
fn find_context_dependencies(&mut self, id: NodeId, new_order: &mut NodeList, results: &mut Vec<(ContextFeatures, NodeId, Option<Type>, bool)>) -> Result<(), GraphErrors> {
let mut branch_dependencies = Vec::new();
let mut combined_deps = ContextFeatures::default();
let node_index = id.0 as usize;
@@ -373,18 +402,32 @@ impl ProtoNetwork {
let context_features = self.nodes[node_index].1.context_features;
let mut inputs = match &self.nodes[node_index].1.construction_args {
// We pretend like we have already placed context modification nodes after ourselves because value nodes don't need to be cached
ConstructionArgs::Value(_) => return (context_features.extract, Some(id)),
ConstructionArgs::Nodes(items) => items.clone(),
ConstructionArgs::Inline(_) => return (context_features.extract, Some(id)),
// We pretend like we have already placed context modification nodes after ourselves because value nodes don't need to be cached
_ => {
let (stable_id, ty) = new_order.push_node(self.nodes[node_index].1.clone(), Some(node_index))?;
results.push((context_features.extract, stable_id, ty, true));
return Ok(());
}
};
// Filter out identity nodes
if self.nodes[node_index].1.identifier == ProtoNodeIdentifier::new("graphene_core::ops::IdentityNode") {
// TODO: make cleaner
let previous_id = new_order.id_mapping[inputs[0].0 as usize];
new_order.id_mapping.push(previous_id);
// Replicate the results from the input node
results.push(results[inputs[0].0 as usize].clone());
// new_order.push_node(previous.1, Some(node_index))?;
return Ok(());
}
// Compute the dependencies for each branch and combine all of them
for &node in &inputs {
let branch = self.find_context_dependencies(node);
let branch = &results[node.0 as usize];
branch_dependencies.push(branch);
combined_deps |= branch.0;
branch_dependencies.push(branch);
}
let mut new_deps = combined_deps;
@@ -393,15 +436,17 @@ impl ProtoNetwork {
// Add requirements we have
new_deps |= context_features.extract;
// If we either introduce new dependencies, we can cache all children which don't yet need that dependency
let we_introduce_new_deps = !combined_deps.contains(new_deps);
// If we introduce new dependencies, we can cache all children which don't yet need that dependency
let we_introduce_new_deps = !combined_deps.contains(new_deps) && !new_deps.is_empty();
// log::debug!("combined_deps: {combined_deps:?} new_deps: {new_deps:?}, context_features: {context_features:?}");
// For diverging branches, we can add a cache node for all branches which don't reqire all dependencies
for (child_node, (deps, new_id)) in inputs.iter_mut().zip(branch_dependencies.into_iter()) {
if let Some(new_id) = new_id {
*child_node = new_id;
} else if we_introduce_new_deps || deps != combined_deps {
*child_node = self.insert_context_nullification_node(*child_node, deps);
for (child_node, (deps, new_id, out_ty, already_placed_nullification)) in inputs.iter_mut().zip(branch_dependencies.into_iter()) {
let old_child_id = *child_node;
*child_node = *new_id;
if !*already_placed_nullification && (we_introduce_new_deps || *deps != combined_deps) {
// log::debug!("already_placed: {already_placed_nullification} we_introduce_new_deps {we_introduce_new_deps} deps: {deps:?} combined_deps: {combined_deps:?}");
*child_node = self.insert_context_nullification_node(old_child_id, *new_id, *deps, new_order)?;
}
}
self.nodes[node_index].1.construction_args = ConstructionArgs::Nodes(inputs);
@@ -415,13 +460,18 @@ impl ProtoNetwork {
// Do we satisfy any existing dependencies?
let we_supply_existing_deps = !combined_deps.difference(remaining_deps_from_children).is_empty();
let mut new_id = None;
if we_supply_existing_deps {
// TODO: replace with mem take
let (stable_id, out_ty) = new_order.push_node(self.nodes[node_index].1.clone(), Some(node_index))?;
let mut new_id = stable_id;
if we_supply_existing_deps && node_index != self.nodes.len() - 1 {
// log::debug!("we supply existing deps");
// Our set of context dependencies has shrunk so we can add a cache node after the current node
new_id = Some(self.insert_context_nullification_node(id, new_deps));
new_id = self.insert_context_nullification_node(id, stable_id, new_deps, new_order)?;
}
(new_deps, new_id)
results.push((new_deps, new_id, out_ty, we_supply_existing_deps));
Ok(())
}
/// Update all of the references to a node ID in the graph with a new ID named `compose_node_id`.
@@ -936,9 +986,7 @@ mod test {
#[test]
fn stable_node_id_generation() {
let mut construction_network = test_network();
construction_network
.insert_context_nullification_nodes()
.expect("Error when calling 'insert_context_nullification_nodes' on 'construction_network.");
construction_network.reorder_ids().unwrap();
construction_network.generate_stable_node_ids();
assert_eq!(construction_network.nodes[0].1.identifier.name.as_ref(), "value");
let ids: Vec<_> = construction_network.nodes.iter().map(|(id, _)| *id).collect();
+3 -3
View File
@@ -1,6 +1,6 @@
use crate::document::NodeNetwork;
use crate::graphene_compiler::Compiler;
use crate::proto::ProtoNetwork;
use crate::proto::{ProtoNetwork, TypingContext};
pub fn load_network(document_string: &str) -> NodeNetwork {
let document: serde_json::Value = serde_json::from_str(document_string).expect("Failed to parse document");
@@ -8,9 +8,9 @@ pub fn load_network(document_string: &str) -> NodeNetwork {
serde_json::from_str::<NodeNetwork>(&document).expect("Failed to parse document")
}
pub fn compile(network: NodeNetwork) -> ProtoNetwork {
pub fn compile(network: NodeNetwork, ty: Option<&mut TypingContext>) -> ProtoNetwork {
let compiler = Compiler {};
compiler.compile_single(network).unwrap()
compiler.compile_single(network, ty).unwrap()
}
pub fn load_from_name(name: &str) -> NodeNetwork {
+3 -2
View File
@@ -5,7 +5,7 @@ use fern::colors::{Color, ColoredLevelConfig};
use futures::executor::block_on;
use graph_craft::document::*;
use graph_craft::graphene_compiler::Compiler;
use graph_craft::proto::ProtoNetwork;
use graph_craft::proto::{ProtoNetwork, TypingContext};
use graph_craft::util::load_network;
use graph_craft::wasm_application_io::EditorPreferences;
use graphene_std::application_io::{ApplicationIo, NodeGraphUpdateMessage, NodeGraphUpdateSender};
@@ -231,7 +231,8 @@ fn compile_graph(document_string: String, editor_api: Arc<WasmEditorApi>) -> Res
let wrapped_network = wrap_network_in_scope(network.clone(), editor_api);
let compiler = Compiler {};
compiler.compile_single(wrapped_network).map_err(|x| x.into())
let mut ty = TypingContext::new(&interpreted_executor::node_registry::NODE_REGISTRY);
compiler.compile_single(wrapped_network, Some(&mut ty)).map_err(|x| x.into())
}
fn create_executor(proto_network: ProtoNetwork) -> Result<DynamicExecutor, Box<dyn Error>> {
@@ -116,6 +116,10 @@ impl DynamicExecutor {
self.typing_context.type_of(self.output).map(|node_io| node_io.call_argument.clone())
}
pub fn typing_context_mut(&mut self) -> &mut TypingContext {
&mut self.typing_context
}
pub fn tree(&self) -> &BorrowTree {
&self.tree
}
+3 -1
View File
@@ -6,6 +6,7 @@ pub mod util;
mod tests {
use core_types::*;
use futures::executor::block_on;
use graph_craft::proto::TypingContext;
use graphene_core::ops::identity;
#[test]
@@ -45,7 +46,8 @@ mod tests {
use graph_craft::graphene_compiler::Compiler;
let compiler = Compiler {};
let protograph = compiler.compile_single(network).expect("Graph should be generated");
let mut ty = TypingContext::new(&crate::node_registry::NODE_REGISTRY);
let protograph = compiler.compile_single(network, &mut ty).expect("Graph should be generated");
let _exec = block_on(DynamicExecutor::new(protograph)).map(|_e| panic!("The network should not type check ")).unwrap_err();
}
@@ -4,7 +4,6 @@ use graph_craft::document::DocumentNode;
use graph_craft::document::value::RenderOutput;
use graph_craft::proto::{NodeConstructor, TypeErasedBox};
use graphene_std::Artboard;
use graphene_std::Context;
use graphene_std::Graphic;
use graphene_std::any::DynAnyNode;
use graphene_std::application_io::{ImageTexture, SurfaceFrame};
@@ -25,6 +24,7 @@ use graphene_std::vector::Vector;
use graphene_std::wasm_application_io::WasmEditorApi;
#[cfg(feature = "gpu")]
use graphene_std::wasm_application_io::WasmSurfaceHandle;
use graphene_std::{Context, ContextFeatures};
use graphene_std::{Cow, ProtoNodeIdentifier};
use graphene_std::{NodeIO, NodeIOTypes};
use graphene_std::{fn_type_fut, future};
@@ -45,9 +45,9 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
// ==========
into_node!(from: Table<Graphic>, to: Table<Graphic>),
into_node!(from: Table<Vector>, to: Table<Vector>),
into_node!(from: Table<Raster<CPU>>, to: Table<Raster<CPU>>),
#[cfg(feature = "gpu")]
into_node!(from: Table<Raster<GPU>>, to: Table<Raster<GPU>>),
// into_node!(from: Table<Raster<CPU>>, to: Table<Raster<CPU>>),
// #[cfg(feature = "gpu")]
// into_node!(from: Table<Raster<GPU>>, to: Table<Raster<GPU>>),
convert_node!(from: Table<Vector>, to: Table<Graphic>),
convert_node!(from: Table<Raster<CPU>>, to: Table<Graphic>),
#[cfg(feature = "gpu")]
@@ -69,6 +69,14 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
convert_node!(from: Table<Raster<GPU>>, to: Table<Raster<GPU>>, converter: &WgpuExecutor),
#[cfg(feature = "gpu")]
convert_node!(from: Table<Raster<GPU>>, to: Table<Raster<CPU>>, converter: &WgpuExecutor),
#[cfg(feature = "gpu")]
convert_node!(from: Table<Vector>, to: Table<Raster<GPU>>, converter: &WgpuExecutor),
#[cfg(feature = "gpu")]
convert_node!(from: Table<Graphic>, to: Table<Raster<GPU>>, converter: &WgpuExecutor),
#[cfg(feature = "gpu")]
convert_node!(from: Table<GradientStops>, to: Table<Raster<GPU>>, converter: &WgpuExecutor),
#[cfg(feature = "gpu")]
convert_node!(from: Table<Color>, to: Table<Raster<GPU>>, converter: &WgpuExecutor),
// =============
// MONITOR NODES
// =============
@@ -145,6 +153,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
#[cfg(feature = "gpu")]
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => &WasmEditorApi, Context => graphene_std::ContextFeatures]),
#[cfg(feature = "gpu")]
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => &WgpuExecutor, Context => graphene_std::ContextFeatures]),
#[cfg(feature = "gpu")]
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Arc<WasmSurfaceHandle>, Context => graphene_std::ContextFeatures]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => RenderIntermediate, Context => graphene_std::ContextFeatures]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => WgpuSurface, Context => graphene_std::ContextFeatures]),
@@ -186,6 +196,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
#[cfg(feature = "gpu")]
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => WgpuSurface]),
#[cfg(feature = "gpu")]
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => &WgpuExecutor]),
#[cfg(feature = "gpu")]
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => Table<Raster<GPU>>]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => Option<f64>]),
async_node!(graphene_core::memo::MemoNode<_, _>, input: Context, fn_params: [Context => Color]),
@@ -22,6 +22,5 @@ kurbo = { workspace = true }
vector-types = { workspace = true }
graphic-types = { workspace = true }
# Workspace dependencies
vello = { workspace = true }
@@ -7,6 +7,7 @@ license = "MIT OR Apache-2.0"
[dependencies]
# Local dependencies
core-types = { workspace = true }
graphic-types = { workspace = true }
raster-types = { workspace = true, features = ["wgpu"] }
graphene-application-io = { workspace = true, features = ["wgpu"] }
rendering = { workspace = true }
@@ -22,3 +23,4 @@ web-sys = { workspace = true }
winit = { workspace = true }
vello = { workspace = true }
bytemuck = { workspace = true }
log = { workspace = true }
@@ -1,6 +1,7 @@
mod context;
pub mod shader_runtime;
pub mod texture_conversion;
pub mod vector_to_raster;
use crate::shader_runtime::ShaderRuntime;
use anyhow::Result;
@@ -0,0 +1,110 @@
use crate::WgpuExecutor;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::ops::Convert;
use core_types::table::Table;
use core_types::transform::Footprint;
use core_types::Color;
use glam::{DAffine2, DVec2, UVec2};
use graphic_types::raster_types::{GPU, Raster};
use graphic_types::vector_types::GradientStops;
use graphic_types::{Artboard, Graphic, Vector};
use rendering::{Render, RenderOutputType, RenderParams};
use wgpu::{CommandEncoderDescriptor, TextureFormat, TextureViewDescriptor};
macro_rules! impl_convert {
($ty:ty) => {
/// Converts Table<T> to Table<Raster<GPU>> by rendering each item to Vello scene and then to texture
impl<'i> Convert<Table<Raster<GPU>>, &'i WgpuExecutor> for Table<$ty> {
async fn convert(self, footprint: Footprint, executor: &'i WgpuExecutor) -> Table<Raster<GPU>> {
// Create render parameters for Vello rendering
let render_params = RenderParams {
render_mode: graphic_types::vector_types::vector::style::RenderMode::Normal,
hide_artboards: false,
for_export: false,
render_output_type: RenderOutputType::Vello,
footprint,
..Default::default()
};
let vector = &self;
let bounding_box = vector.bounding_box(DAffine2::IDENTITY, true);
// TODO: Add cases for infinite bounding boxes
let RenderBoundingBox::Rectangle(rect) = bounding_box else {
panic!("did not find valid bounding box")
};
// Create a Vello scene for this vector
let mut scene = vello::Scene::new();
let mut context = crate::RenderContext::default();
let viewport_bounds = footprint.viewport_bounds_in_local_space();
let image_bounds = core_types::math::bbox::AxisAlignedBbox { start: rect[0], end: rect[1] };
let intersection = viewport_bounds.intersect(&image_bounds);
let size = intersection.size();
let offset = (intersection.start - image_bounds.start).max(DVec2::ZERO) + image_bounds.start;
// If the image would not be visible, return an empty image
if size.x <= 0. || size.y <= 0. {
return Table::new();
}
let scale = footprint.scale();
let width = (size.x * scale.x) as u32;
let height = (size.y * scale.y) as u32;
// Render the scene to a GPU texture
let resolution = UVec2::new(width, height);
let background = core_types::Color::TRANSPARENT;
let render_transform = DAffine2::from_scale(scale) * DAffine2::from_translation(-offset);
// Render the vector to the Vello scene with the row's transform
vector.render_to_vello(&mut scene, render_transform, &mut context, &render_params);
// Use async rendering to get the texture
let texture = executor
.render_vello_scene_to_texture(&scene, resolution, &context, background)
.await
.expect("Failed to render Vello scene to texture");
let device = &executor.context.device;
let queue = &executor.context.queue;
let mut encoder = device.create_command_encoder(&CommandEncoderDescriptor::default());
let blitter = wgpu::util::TextureBlitter::new(device, TextureFormat::Rgba8UnormSrgb);
let view = texture.create_view(&TextureViewDescriptor::default());
let new_texture = device.create_texture(&wgpu::wgt::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: texture.width(),
height: texture.height(),
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
format: TextureFormat::Rgba8UnormSrgb,
view_formats: &[],
});
let new_view = new_texture.create_view(&TextureViewDescriptor::default());
blitter.copy(device, &mut encoder, &view, &new_view);
let command_buffer = encoder.finish();
queue.submit([command_buffer]);
let mut table = Table::new_from_element(Raster::new_gpu(new_texture));
*(table.get_mut(0).as_mut().unwrap().transform) = DAffine2::from_translation(offset) * DAffine2::from_scale(size);
texture.destroy();
table
}
}
};
}
impl_convert!(Vector);
impl_convert!(Graphic);
impl_convert!(Artboard);
impl_convert!(GradientStops);
impl_convert!(Color);
+2
View File
@@ -9,6 +9,7 @@ use graphene_application_io::{ApplicationIo, ExportFormat, ImageTexture, RenderC
use graphic_types::Artboard;
use graphic_types::Graphic;
use graphic_types::Vector;
use graphic_types::raster_types::GPU;
use graphic_types::raster_types::Image;
use graphic_types::raster_types::{CPU, Raster};
use rendering::{Render, RenderOutputType as RenderOutputTypeRequest, RenderParams, RenderSvgSegmentList, SvgRender, format_transform_matrix};
@@ -40,6 +41,7 @@ async fn render_intermediate<'a: 'n, T: 'static + Render + WasmNotSend + Send +
Context -> Table<Graphic>,
Context -> Table<Vector>,
Context -> Table<Raster<CPU>>,
Context -> Table<Raster<GPU>>,
Context -> Table<Color>,
Context -> Table<GradientStops>,
)]
+1
View File
@@ -11,5 +11,6 @@ log = { workspace = true }
# Workspace dependencies
graphene-std = { workspace = true, features = ["gpu"] }
wgpu-executor = { workspace = true }
graph-craft = { workspace = true }
interpreted-executor = { workspace = true }
+12 -2
View File
@@ -8,6 +8,7 @@ use graph_craft::{ProtoNodeIdentifier, concrete};
use graphene_std::registry::*;
use graphene_std::*;
use std::collections::{HashMap, HashSet};
use wgpu_executor::WgpuExecutor;
pub fn expand_network(network: &mut NodeNetwork, substitutions: &HashMap<ProtoNodeIdentifier, DocumentNode>) {
if network.generated {
@@ -76,12 +77,20 @@ pub fn generate_node_substitutions() -> HashMap<ProtoNodeIdentifier, DocumentNod
name: format!("graphene_core::ops::ConvertNode<{}>", input_ty.clone()).into(),
};
let mut context_features = ContextDependencies::default();
let proto_node = if into_node_registry.keys().any(|ident: &ProtoNodeIdentifier| ident.name.as_ref() == into_node_identifier.name.as_ref()) {
generated_nodes += 1;
into_node_identifier
} else if into_node_registry.keys().any(|ident| ident.name.as_ref() == convert_node_identifier.name.as_ref()) {
} else if let Some(impls) = into_node_registry.get(&convert_node_identifier) {
generated_nodes += 1;
inputs.push(NodeInput::value(TaggedValue::None, false));
let converter = match impls.keys().next() {
Some(node_io) if node_io.inputs[1].nested_type() == &concrete!(&WgpuExecutor) => {
context_features.extract |= ContextFeatures::FOOTPRINT;
NodeInput::scope("wgpu-executor")
}
_ => NodeInput::value(TaggedValue::None, false),
};
inputs.push(converter);
convert_node_identifier
} else {
identity_node.clone()
@@ -93,6 +102,7 @@ pub fn generate_node_substitutions() -> HashMap<ProtoNodeIdentifier, DocumentNod
implementation: DocumentNodeImplementation::ProtoNode(proto_node),
visible: true,
original_location,
context_features,
..Default::default()
}
}