Skip to content

Commit 920bdc8

Browse files
Make the render node finish SVG renders without caller post-processing (#5000)
* Make the render node finish SVG renders without caller post-processing * Remove read_back from the wgpu executor * Cancel the SVG readback when the render node is dropped * Move the SVG readback slot into a render node submodule --------- Co-authored-by: Timon <me@timon.zip>
1 parent 23f3a03 commit 920bdc8

10 files changed

Lines changed: 328 additions & 95 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎document/migrations/nodes/src/graphene_std/renames.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,6 @@ rename!("graphene_std::render_background::RenderBackgroundNode"@1 => @2);
88
rename!("graphene_std::render_cache::RenderOutputCacheNode"@1 => @2);
99
rename!("graphene_std::render_node::RenderNode"@1 => @2);
1010
rename!("graphene_std::render_pixel_preview::RenderPixelPreviewNode"@1 => @2);
11+
12+
// Version 3 adds the scope and source ID inputs the render node spawns its readbacks with, which the compiler inserts along with the node
13+
rename!("graphene_std::render_node::RenderNode"@2 => @3);

‎editor/src/node_graph_executor/runtime.rs‎

Lines changed: 38 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -390,7 +390,6 @@ impl NodeRuntime {
390390
None
391391
};
392392

393-
self.resolve_deferred_images(&mut result).await;
394393
self.respond(request.execution_id, result, observations).await;
395394
texture
396395
}
@@ -451,7 +450,6 @@ impl NodeRuntime {
451450
let (buffer, width, height) = self.read_back(texture.clone()).await.to_flat_u8();
452451
*data = RenderOutputType::Buffer { data: buffer, width, height };
453452
}
454-
self.resolve_deferred_images(&mut result).await;
455453
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
456454
self.respond(request.execution_id, result, observations).await;
457455
}
@@ -537,32 +535,6 @@ impl NodeRuntime {
537535
observer.evaluate(&self.executor, self.old_graph.as_ref()).remove(&())?.data
538536
}
539537

540-
/// Puts what the GPU rendered for an SVG result into it, in place of the placeholders standing in for each:
541-
/// the maps of effects' coverages its filters take, and the images of content with effects SVG filters can't carry out.
542-
async fn resolve_deferred_images(&self, result: &mut ExecutionResult) {
543-
let Some(RenderOutput {
544-
data: RenderOutputType::Svg {
545-
svg,
546-
image_data,
547-
effect_maps,
548-
deferred_images,
549-
},
550-
..
551-
}) = result.render_output()
552-
else {
553-
return;
554-
};
555-
if effect_maps.is_empty() && deferred_images.is_empty() {
556-
return;
557-
}
558-
let Some(executor) = self.editor_api.application_io.as_ref().and_then(|application_io| application_io.gpu_executor()) else {
559-
return;
560-
};
561-
562-
executor.resolve_effect_maps(svg, std::mem::take(effect_maps)).await;
563-
executor.resolve_deferred_svg_images(svg, image_data, std::mem::take(deferred_images)).await;
564-
}
565-
566538
async fn read_back(&self, texture: Texture) -> Raster<CPU> {
567539
let application_io = self.editor_api.application_io.as_ref().unwrap();
568540
let executor = application_io.gpu_executor().expect("GPU executor should be available when we receive a texture");
@@ -1091,6 +1063,44 @@ mod tests {
10911063
}
10921064
}
10931065

1066+
#[tokio::test]
1067+
async fn an_svg_export_draws_effects_svg_filters_cannot_carry_out_as_images_the_gpu_renders() {
1068+
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
1069+
use graphene_std::blending_nodes::effects::drop_shadow;
1070+
use graphene_std::raster_nodes::adjustments::black_and_white;
1071+
1072+
let mut editor = EditorTestUtils::create();
1073+
editor.new_document().await;
1074+
editor.draw_rect(0., 0., 100., 100.).await;
1075+
1076+
// Following a shadow, Black & White can't fold into the paints, and no SVG filter mixes the channels as it does, so the rectangle is drawn as an image the GPU renders of it
1077+
let layer = editor.active_document().metadata().all_layers().next().unwrap();
1078+
for node in [drop_shadow::IDENTIFIER, black_and_white::IDENTIFIER] {
1079+
let node_type = DefinitionIdentifier::ProtoNode(node);
1080+
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
1081+
}
1082+
1083+
// The export waits for the render node to read the image back into the SVG
1084+
send_export(&mut editor, FileType::Svg);
1085+
let mut saved = None;
1086+
for _ in 0..100 {
1087+
editor.runtime.update();
1088+
editor.runtime.run().await;
1089+
saved = editor.dispatch(Message::Wake).into_iter().find_map(|message| match message {
1090+
FrontendMessage::TriggerSaveFile { content, .. } => Some(content),
1091+
_ => None,
1092+
});
1093+
if saved.is_some() {
1094+
break;
1095+
}
1096+
}
1097+
let Some(saved) = saved else { panic!("the export never finished") };
1098+
1099+
let svg = String::from_utf8(saved.into_vec()).expect("the export should be SVG text");
1100+
assert!(svg.contains("data:image/png;base64,"), "the image should be embedded: {svg}");
1101+
assert!(!svg.contains("deferred-image"), "the markup standing in for the image should be replaced: {svg}");
1102+
}
1103+
10941104
#[tokio::test]
10951105
async fn exporting_a_graph_that_fails_to_compile_says_it_failed() {
10961106
let mut editor = editor().await;

‎node-graph/graph-craft/src/document/value.rs‎

Lines changed: 1 addition & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ use graphic_types::vector_types::vector::style::DashPattern;
1818
use graphic_types::vector_types::vector::style::{Gradient, GradientRamp};
1919
use graphic_types::vector_types::vector::{self, ReferencePoint};
2020
use graphic_types::{Artboard, Graphic, Vector};
21-
use rendering::deferred_image::{DeferredImagePlacement, EffectMapPlacement};
2221
use rendering::{CanvasImage, RenderMetadata};
2322
use std::fmt::Display;
2423
use std::hash::Hash;
@@ -921,12 +920,6 @@ pub enum RenderOutputType {
921920
svg: String,
922921
/// The images the SVG draws to canvases, by the canvas ID their placeholders name.
923922
image_data: Vec<(u64, CanvasImage)>,
924-
/// Maps of effects' coverages the GPU rendered for the SVG's filters, which go in place of their placeholders once read back.
925-
#[serde(skip)]
926-
effect_maps: Vec<(EffectMapPlacement, graphene_application_io::Texture)>,
927-
/// Images the GPU rendered of content with effects SVG filters can't carry out, which go in place of the markup standing in for that content once read back.
928-
#[serde(skip)]
929-
deferred_images: Vec<(DeferredImagePlacement, graphene_application_io::Texture)>,
930923
},
931924
#[cfg(target_family = "wasm")]
932925
CanvasFrame { canvas_id: u64, resolution: DVec2 },
@@ -942,22 +935,9 @@ impl CacheHash for RenderOutputType {
942935
width.cache_hash(state);
943936
height.cache_hash(state);
944937
}
945-
Self::Svg {
946-
svg,
947-
image_data,
948-
effect_maps,
949-
deferred_images,
950-
} => {
938+
Self::Svg { svg, image_data } => {
951939
svg.cache_hash(state);
952940
image_data.cache_hash(state);
953-
for (placement, texture) in effect_maps {
954-
placement.id.cache_hash(state);
955-
texture.hash(state);
956-
}
957-
for (placement, texture) in deferred_images {
958-
placement.id.cache_hash(state);
959-
texture.hash(state);
960-
}
961941
}
962942
#[cfg(target_family = "wasm")]
963943
Self::CanvasFrame { canvas_id, resolution } => {

‎node-graph/graphene-cli/src/export.rs‎

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -189,16 +189,7 @@ pub(crate) async fn render_frame(
189189
// Execute the graph and extract its output
190190
match execute_until_settled(executor, runtime, spawner, render_config).await? {
191191
TaggedValue::RenderOutput(output) => match output.data {
192-
RenderOutputType::Svg {
193-
mut svg,
194-
mut image_data,
195-
effect_maps,
196-
deferred_images,
197-
} => {
198-
wgpu_executor.resolve_effect_maps(&mut svg, effect_maps).await;
199-
wgpu_executor.resolve_deferred_svg_images(&mut svg, &mut image_data, deferred_images).await;
200-
Ok(RenderedFrame::Svg(svg))
201-
}
192+
RenderOutputType::Svg { svg, .. } => Ok(RenderedFrame::Svg(svg)),
202193
RenderOutputType::Texture(texture) => {
203194
// Convert GPU texture to CPU buffer
204195
let gpu_raster = Raster::<GPU>::new_gpu(texture);

‎node-graph/interpreted-executor/src/util.rs‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use graph_craft::application_io::PlatformEditorApi;
22
use graph_craft::document::value::TaggedValue;
3-
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
3+
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, DocumentNodeMetadata, NodeInput, NodeNetwork};
44
use graph_craft::generic;
55
use graph_craft::{concrete, item};
66
use graphene_std::Context;
@@ -42,7 +42,12 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
4242
},
4343
DocumentNode {
4444
call_argument: concrete!(Context),
45-
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER)],
45+
inputs: vec![
46+
NodeInput::node(NodeId(0), 0),
47+
NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER),
48+
NodeInput::scope("runtime"),
49+
NodeInput::Reflection(DocumentNodeMetadata::SourceId),
50+
],
4651
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render::IDENTIFIER),
4752
compile_metadata: Some(graphene_std::NodeCompileMetadata {
4853
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,

‎node-graph/nodes/gstd/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ vectorize-nodes = { workspace = true }
6363

6464
# Workspace dependencies
6565
log = { workspace = true }
66+
futures = { workspace = true }
6667
glam = { workspace = true }
6768
node-macro = { workspace = true }
6869
reqwest = { workspace = true }

‎node-graph/nodes/gstd/src/render_background.rs‎

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -51,8 +51,6 @@ fn render_background(
5151
RenderOutputType::Svg {
5252
svg: foreground_svg,
5353
image_data: foreground_images,
54-
effect_maps,
55-
deferred_images,
5654
} => {
5755
let mut render = SvgRender::new();
5856

@@ -116,12 +114,7 @@ fn render_background(
116114
let svg = format!("{}{}", background.svg, foreground_svg);
117115
let image_data = foreground_images;
118116

119-
RenderOutputType::Svg {
120-
svg,
121-
image_data,
122-
effect_maps,
123-
deferred_images,
124-
}
117+
RenderOutputType::Svg { svg, image_data }
125118
}
126119
_ => unreachable!("Render background node received unsupported render output type"),
127120
};

‎node-graph/nodes/gstd/src/render_node.rs‎

Lines changed: 37 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
1+
mod svg_readback;
2+
13
use core_types::list::{Item, List};
24
use core_types::transform::{Footprint, Transform};
3-
use core_types::{CloneVarArgs, ExtractAll, ExtractVarArgs};
4-
use core_types::{Color, Context, Ctx, ExtractFootprint, Interrupt, NodeError, OwnedContextImpl, WasmNotSend};
5+
use core_types::{CloneVarArgs, ExtractAll, ExtractVarArgs, Poll, RuntimeHandle, SourceId};
6+
use core_types::{Color, Context, Ctx, ExtractFootprint, Interrupt, OwnedContextImpl, WasmNotSend};
57
use graph_craft::document::value::{RenderOutput, RenderOutputType};
68
use graphene_application_io::{ExportFormat, RenderConfig};
79
use graphic_types::raster_types::{CPU, Raster};
810
use graphic_types::{Artboard, Graphic, Vector};
911
use rendering::vello_scene_builder::VelloSceneBuilder;
1012
use rendering::{Render, RenderMetadata, RenderOutputType as RenderOutputTypeRequest, RenderParams, SvgRender, SvgRenderOutput};
1113
use std::sync::Arc;
14+
use svg_readback::SvgReadbackSlot;
1215
use vector_types::Gradient;
1316
use wgpu_executor::WgpuExecutor;
1417

@@ -70,12 +73,15 @@ fn render_intermediate<T: 'static + Render + WasmNotSend + Send + Sync>(
7073
Ok(Item::new_from_element(intermediate))
7174
}
7275

73-
#[node_macro::node(category(""), version(2))]
76+
#[node_macro::node(category(""), version(3))]
7477
fn render(
7578
ctx: impl Ctx + ExtractFootprint + ExtractVarArgs,
7679
data: Item<RenderIntermediate>,
7780
#[scope(crate::platform_application_io::wgpu_executor::IDENTIFIER)] executor: impl Node<Context<'static>, Output = Item<WgpuExecutor>>,
78-
) -> Result<Item<RenderOutput>, Interrupt> {
81+
#[scope("runtime")] runtime: Item<RuntimeHandle>,
82+
#[source_id] source: Item<SourceId>,
83+
#[data] svg_readback: SvgReadbackSlot,
84+
) -> Poll<Item<RenderOutput>> {
7985
let footprint = ctx.footprint();
8086
let render_params = ctx
8187
.vararg(0)
@@ -99,27 +105,23 @@ fn render(
99105
let output = SvgRenderOutput::from(render);
100106
assert!(output.svg_defs.is_empty());
101107

102-
// Without a GPU, the filters' maps and the images of content with effects SVG filters can't carry out keep their placeholders, which leave those effects out
103-
let (effect_maps, deferred_images) = match output.effect_maps.is_empty() && output.deferred_images.is_empty() {
104-
true => (Vec::new(), Vec::new()),
105-
false => match executor.eval(Context::default()) {
106-
Ok(executor) => (
107-
executor.element().render_effect_maps(&output.effect_maps, *footprint),
108-
executor.element().render_deferred_svg_images(&output.deferred_images, *footprint),
109-
),
110-
Err(_) => (Vec::new(), Vec::new()),
111-
},
112-
};
113-
114-
RenderOutputType::Svg {
115-
svg: output.svg,
116-
image_data: output.image_data.into_iter().collect(),
117-
effect_maps,
118-
deferred_images,
119-
}
108+
let executor = executor.eval(&Context::default()).value().map(Item::into_element);
109+
svg_readback.poll(output, *footprint, executor, runtime.element(), *source.element())
120110
}
121111
(RenderOutputTypeRequest::Vello, RenderIntermediateType::Vello(data)) => {
122-
let executor = executor.eval(Context::default())?.into_element();
112+
// The latest SVG render isn't needed anymore, and a finished one holds a whole SVG export
113+
svg_readback.clear();
114+
115+
let (executor, executor_partial, executor_error) = match executor.eval(&Context::default()) {
116+
Poll::Final(executor) => (executor.into_element(), false, None),
117+
Poll::Partial(executor) => (executor.into_element(), true, None),
118+
Poll::Fallback(boxed) => {
119+
let (executor, error) = *boxed;
120+
(executor.into_element(), false, Some(error))
121+
}
122+
Poll::Pending => return Poll::Pending,
123+
Poll::Error(error) => return Poll::Error(error),
124+
};
123125

124126
let mut draw = |scene: &mut VelloSceneBuilder| data.render_to_vello(scene, Default::default(), &render_params);
125127
let texture = match executor.render_vello(footprint.resolution, footprint.transform, &mut draw) {
@@ -128,15 +130,24 @@ fn render(
128130
Err(error) => {
129131
log::error!("Failed to render Vello scene: {error}");
130132
let limit = glam::UVec2::splat(executor.context().device.limits().max_texture_dimension_2d);
131-
executor.render_vello(footprint.resolution.min(limit), footprint.transform, &mut |_| {}).map_err(NodeError::new)?
133+
match executor.render_vello(footprint.resolution.min(limit), footprint.transform, &mut |_| {}) {
134+
Ok(texture) => texture,
135+
Err(error) => return Poll::error(error),
136+
}
132137
}
133138
};
134-
RenderOutputType::Texture(texture)
139+
140+
let texture = RenderOutputType::Texture(texture);
141+
match (executor_partial, executor_error) {
142+
(true, _) => Poll::Partial(texture),
143+
(false, Some(error)) => Poll::Fallback(Box::new((texture, error))),
144+
(false, None) => Poll::Final(texture),
145+
}
135146
}
136147
_ => unreachable!("Render node did not receive its requested data type"),
137148
};
138149

139-
Ok(Item::new_from_element(RenderOutput { data, metadata }))
150+
data.map(|data| Item::new_from_element(RenderOutput { data, metadata }))
140151
}
141152

142153
#[node_macro::node(category(""))]

0 commit comments

Comments
 (0)