diff --git a/Cargo.lock b/Cargo.lock index a38ba972d97..1fa818831f4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2653,6 +2653,7 @@ dependencies = [ "bytemuck", "core-types", "dyn-any", + "futures", "glam", "graph-craft", "graphene-application-io", diff --git a/document/migrations/nodes/src/graphene_std/renames.rs b/document/migrations/nodes/src/graphene_std/renames.rs index ea33fa64c13..1e1383c822d 100644 --- a/document/migrations/nodes/src/graphene_std/renames.rs +++ b/document/migrations/nodes/src/graphene_std/renames.rs @@ -8,3 +8,6 @@ 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); diff --git a/editor/src/node_graph_executor/runtime.rs b/editor/src/node_graph_executor/runtime.rs index c2ca1d67f1a..35881fae126 100644 --- a/editor/src/node_graph_executor/runtime.rs +++ b/editor/src/node_graph_executor/runtime.rs @@ -390,7 +390,6 @@ impl NodeRuntime { None }; - self.resolve_deferred_images(&mut result).await; self.respond(request.execution_id, result, observations).await; texture } @@ -451,7 +450,6 @@ impl NodeRuntime { let (buffer, width, height) = self.read_back(texture.clone()).await.to_flat_u8(); *data = RenderOutputType::Buffer { data: buffer, width, height }; } - self.resolve_deferred_images(&mut result).await; let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref()); self.respond(request.execution_id, result, observations).await; } @@ -537,32 +535,6 @@ impl NodeRuntime { observer.evaluate(&self.executor, self.old_graph.as_ref()).remove(&())?.data } - /// Puts what the GPU rendered for an SVG result into it, in place of the placeholders standing in for each: - /// the maps of effects' coverages its filters take, and the images of content with effects SVG filters can't carry out. - async fn resolve_deferred_images(&self, result: &mut ExecutionResult) { - let Some(RenderOutput { - data: RenderOutputType::Svg { - svg, - image_data, - effect_maps, - deferred_images, - }, - .. - }) = result.render_output() - else { - return; - }; - if effect_maps.is_empty() && deferred_images.is_empty() { - return; - } - let Some(executor) = self.editor_api.application_io.as_ref().and_then(|application_io| application_io.gpu_executor()) else { - return; - }; - - executor.resolve_effect_maps(svg, std::mem::take(effect_maps)).await; - executor.resolve_deferred_svg_images(svg, image_data, std::mem::take(deferred_images)).await; - } - async fn read_back(&self, texture: Texture) -> Raster { let application_io = self.editor_api.application_io.as_ref().unwrap(); let executor = application_io.gpu_executor().expect("GPU executor should be available when we receive a texture"); @@ -1091,6 +1063,44 @@ mod tests { } } + #[tokio::test] + async fn an_svg_export_draws_effects_svg_filters_cannot_carry_out_as_images_the_gpu_renders() { + use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier; + use graphene_std::blending_nodes::effects::drop_shadow; + use graphene_std::raster_nodes::adjustments::black_and_white; + + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + editor.draw_rect(0., 0., 100., 100.).await; + + // 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 + let layer = editor.active_document().metadata().all_layers().next().unwrap(); + for node in [drop_shadow::IDENTIFIER, black_and_white::IDENTIFIER] { + let node_type = DefinitionIdentifier::ProtoNode(node); + editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await; + } + + // The export waits for the render node to read the image back into the SVG + send_export(&mut editor, FileType::Svg); + let mut saved = None; + for _ in 0..100 { + editor.runtime.update(); + editor.runtime.run().await; + saved = editor.dispatch(Message::Wake).into_iter().find_map(|message| match message { + FrontendMessage::TriggerSaveFile { content, .. } => Some(content), + _ => None, + }); + if saved.is_some() { + break; + } + } + let Some(saved) = saved else { panic!("the export never finished") }; + + let svg = String::from_utf8(saved.into_vec()).expect("the export should be SVG text"); + assert!(svg.contains("data:image/png;base64,"), "the image should be embedded: {svg}"); + assert!(!svg.contains("deferred-image"), "the markup standing in for the image should be replaced: {svg}"); + } + #[tokio::test] async fn exporting_a_graph_that_fails_to_compile_says_it_failed() { let mut editor = editor().await; diff --git a/node-graph/graph-craft/src/document/value.rs b/node-graph/graph-craft/src/document/value.rs index 0a24d7c6c01..98722d7e4e9 100644 --- a/node-graph/graph-craft/src/document/value.rs +++ b/node-graph/graph-craft/src/document/value.rs @@ -18,7 +18,6 @@ use graphic_types::vector_types::vector::style::DashPattern; use graphic_types::vector_types::vector::style::{Gradient, GradientRamp}; use graphic_types::vector_types::vector::{self, ReferencePoint}; use graphic_types::{Artboard, Graphic, Vector}; -use rendering::deferred_image::{DeferredImagePlacement, EffectMapPlacement}; use rendering::{CanvasImage, RenderMetadata}; use std::fmt::Display; use std::hash::Hash; @@ -921,12 +920,6 @@ pub enum RenderOutputType { svg: String, /// The images the SVG draws to canvases, by the canvas ID their placeholders name. image_data: Vec<(u64, CanvasImage)>, - /// Maps of effects' coverages the GPU rendered for the SVG's filters, which go in place of their placeholders once read back. - #[serde(skip)] - effect_maps: Vec<(EffectMapPlacement, graphene_application_io::Texture)>, - /// 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. - #[serde(skip)] - deferred_images: Vec<(DeferredImagePlacement, graphene_application_io::Texture)>, }, #[cfg(target_family = "wasm")] CanvasFrame { canvas_id: u64, resolution: DVec2 }, @@ -942,22 +935,9 @@ impl CacheHash for RenderOutputType { width.cache_hash(state); height.cache_hash(state); } - Self::Svg { - svg, - image_data, - effect_maps, - deferred_images, - } => { + Self::Svg { svg, image_data } => { svg.cache_hash(state); image_data.cache_hash(state); - for (placement, texture) in effect_maps { - placement.id.cache_hash(state); - texture.hash(state); - } - for (placement, texture) in deferred_images { - placement.id.cache_hash(state); - texture.hash(state); - } } #[cfg(target_family = "wasm")] Self::CanvasFrame { canvas_id, resolution } => { diff --git a/node-graph/graphene-cli/src/export.rs b/node-graph/graphene-cli/src/export.rs index 57a0117bba7..0c5afef95e9 100644 --- a/node-graph/graphene-cli/src/export.rs +++ b/node-graph/graphene-cli/src/export.rs @@ -189,16 +189,7 @@ pub(crate) async fn render_frame( // Execute the graph and extract its output match execute_until_settled(executor, runtime, spawner, render_config).await? { TaggedValue::RenderOutput(output) => match output.data { - RenderOutputType::Svg { - mut svg, - mut image_data, - effect_maps, - deferred_images, - } => { - wgpu_executor.resolve_effect_maps(&mut svg, effect_maps).await; - wgpu_executor.resolve_deferred_svg_images(&mut svg, &mut image_data, deferred_images).await; - Ok(RenderedFrame::Svg(svg)) - } + RenderOutputType::Svg { svg, .. } => Ok(RenderedFrame::Svg(svg)), RenderOutputType::Texture(texture) => { // Convert GPU texture to CPU buffer let gpu_raster = Raster::::new_gpu(texture); diff --git a/node-graph/interpreted-executor/src/util.rs b/node-graph/interpreted-executor/src/util.rs index afac28c095d..80900615a20 100644 --- a/node-graph/interpreted-executor/src/util.rs +++ b/node-graph/interpreted-executor/src/util.rs @@ -1,6 +1,6 @@ use graph_craft::application_io::PlatformEditorApi; use graph_craft::document::value::TaggedValue; -use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork}; +use graph_craft::document::{DocumentNode, DocumentNodeImplementation, DocumentNodeMetadata, NodeInput, NodeNetwork}; use graph_craft::generic; use graph_craft::{concrete, item}; use graphene_std::Context; @@ -42,7 +42,12 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc) { for (placement, texture) in maps { - let map: Raster = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, self.clone()).await; - substitute_effect_map(svg, &placement, &map); + match self.read_back(Raster::new_gpu(texture)).await { + Ok(map) => substitute_effect_map(svg, &placement, &map), + Err(error) => log::error!("Failed to read back a map of an effect's coverage for an SVG filter: {error}"), + } } } @@ -55,10 +57,13 @@ impl WgpuExecutor { } /// Reads back the images of deferred content, putting each in `svg` in place of the markup standing in for its content. + /// Content with an image that fails to read back keeps its markup. pub async fn resolve_deferred_svg_images(&self, svg: &mut String, image_data: &mut Vec<(u64, CanvasImage)>, images: Vec<(DeferredImagePlacement, Texture)>) { for (placement, texture) in images { - let image: Raster = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, self.clone()).await; - substitute_deferred_image(svg, image_data, &placement, &image); + match self.read_back(Raster::new_gpu(texture)).await { + Ok(image) => substitute_deferred_image(svg, image_data, &placement, &image), + Err(error) => log::error!("Failed to read back an image of content with effects SVG can't express: {error}"), + } } } } diff --git a/node-graph/libraries/wgpu-executor/src/texture_conversion.rs b/node-graph/libraries/wgpu-executor/src/texture_conversion.rs index 05c516038fb..3ca4b0904cc 100644 --- a/node-graph/libraries/wgpu-executor/src/texture_conversion.rs +++ b/node-graph/libraries/wgpu-executor/src/texture_conversion.rs @@ -213,20 +213,27 @@ impl ConvertAsync>, WgpuExecutor> for List> { } } -/// Converts single GPU raster to CPU by downloading texture data -impl ConvertAsync, WgpuExecutor> for Raster { - async fn convert(self, _: Footprint, executor: WgpuExecutor) -> Raster { - let device = &executor.context().device; - let queue = &executor.context().queue; +impl WgpuExecutor { + /// Downloads the raster's texture data, or gives the error mapping its buffer for reading failed with. + pub(crate) async fn read_back(&self, raster: Raster) -> Result, wgpu::BufferAsyncError> { + let device = &self.context().device; + let queue = &self.context().queue; let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("single_texture_download_encoder"), }); - let converter = RasterGpuToRasterCpuConverter::new(&executor, &mut encoder, self); + let converter = RasterGpuToRasterCpuConverter::new(self, &mut encoder, raster); queue.submit([encoder.finish()]); - converter.convert(device).await.expect("Failed to download texture data") + converter.convert(device).await + } +} + +/// Converts single GPU raster to CPU by downloading texture data +impl ConvertAsync, WgpuExecutor> for Raster { + async fn convert(self, _: Footprint, executor: WgpuExecutor) -> Raster { + executor.read_back(self).await.expect("Failed to download texture data") } } diff --git a/node-graph/nodes/gstd/Cargo.toml b/node-graph/nodes/gstd/Cargo.toml index 332f3651b00..4ee802994db 100644 --- a/node-graph/nodes/gstd/Cargo.toml +++ b/node-graph/nodes/gstd/Cargo.toml @@ -63,6 +63,7 @@ vectorize-nodes = { workspace = true } # Workspace dependencies log = { workspace = true } +futures = { workspace = true } glam = { workspace = true } node-macro = { workspace = true } reqwest = { workspace = true } diff --git a/node-graph/nodes/gstd/src/render_background.rs b/node-graph/nodes/gstd/src/render_background.rs index c3e34265fbb..59c24d88894 100644 --- a/node-graph/nodes/gstd/src/render_background.rs +++ b/node-graph/nodes/gstd/src/render_background.rs @@ -51,8 +51,6 @@ fn render_background( RenderOutputType::Svg { svg: foreground_svg, image_data: foreground_images, - effect_maps, - deferred_images, } => { let mut render = SvgRender::new(); @@ -116,12 +114,7 @@ fn render_background( let svg = format!("{}{}", background.svg, foreground_svg); let image_data = foreground_images; - RenderOutputType::Svg { - svg, - image_data, - effect_maps, - deferred_images, - } + RenderOutputType::Svg { svg, image_data } } _ => unreachable!("Render background node received unsupported render output type"), }; diff --git a/node-graph/nodes/gstd/src/render_node.rs b/node-graph/nodes/gstd/src/render_node.rs index 2d91196762a..751a4ec8bc3 100644 --- a/node-graph/nodes/gstd/src/render_node.rs +++ b/node-graph/nodes/gstd/src/render_node.rs @@ -1,14 +1,17 @@ use core_types::list::{Item, List}; +use core_types::runtime::Runtime; use core_types::transform::{Footprint, Transform}; -use core_types::{CloneVarArgs, ExtractAll, ExtractVarArgs}; -use core_types::{Color, Context, Ctx, ExtractFootprint, Interrupt, NodeError, OwnedContextImpl, WasmNotSend}; +use core_types::{CacheHash, CloneVarArgs, ExtractAll, ExtractVarArgs, Poll, RuntimeHandle, SourceId}; +use core_types::{Color, Context, Ctx, ExtractFootprint, Interrupt, OwnedContextImpl, WasmNotSend}; +use futures::future::{AbortHandle, Abortable}; use graph_craft::document::value::{RenderOutput, RenderOutputType}; use graphene_application_io::{ExportFormat, RenderConfig}; use graphic_types::raster_types::{CPU, Raster}; use graphic_types::{Artboard, Graphic, Vector}; use rendering::vello_scene_builder::VelloSceneBuilder; -use rendering::{Render, RenderMetadata, RenderOutputType as RenderOutputTypeRequest, RenderParams, SvgRender, SvgRenderOutput}; -use std::sync::Arc; +use rendering::{CanvasImage, Render, RenderMetadata, RenderOutputType as RenderOutputTypeRequest, RenderParams, SvgRender, SvgRenderOutput}; +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use vector_types::Gradient; use wgpu_executor::WgpuExecutor; @@ -70,12 +73,120 @@ fn render_intermediate( Ok(Item::new_from_element(intermediate)) } -#[node_macro::node(category(""), version(2))] +/// The latest SVG render that needs maps and images from the GPU, kept across the render node's evaluations while a task reads them back. +/// A render of other content or for another view replaces it, cancelling the readback still underway for the one it replaced. +#[derive(Clone, Default)] +pub struct SvgReadbackSlot(Arc>>); + +impl std::fmt::Debug for SvgReadbackSlot { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("SvgReadbackSlot").finish_non_exhaustive() + } +} + +/// An SVG with its placeholders filled in, and the images it draws to canvases. +type FinishedSvg = (String, Vec<(u64, CanvasImage)>); + +struct SvgReadback { + /// A hash of the SVG with its placeholders and the view it's rendered for. + key: u64, + /// The SVG with the maps and images in place of their placeholders, once read back. + finished: Option, + /// Cancels the readback, which ends along with the render it belongs to. + task: AbortHandle, +} + +impl Drop for SvgReadback { + fn drop(&mut self) { + self.task.abort(); + } +} + +impl SvgReadbackSlot { + fn lock(&self) -> MutexGuard<'_, Option> { + // A lock poisoned by a panic elsewhere still guards a usable slot + self.0.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Drops the latest render, cancelling its readback if it's underway. + fn clear(&self) { + *self.lock() = None; + } + + /// Whether the render `key` names has a readback, and if so, the finished SVG once it has landed. + fn readback(&self, key: u64) -> Option> { + self.lock().as_ref().filter(|readback| readback.key == key).map(|readback| readback.finished.clone()) + } + + /// The SVG `output` with the maps and images the GPU renders for it in place of their placeholders, partial with the placeholders while a task reads them back. + /// The task landing evaluates the render node again through its `source`. Without a GPU, the placeholders stay and leave those effects out. + fn poll(&self, output: SvgRenderOutput, footprint: Footprint, executor: impl FnOnce() -> Option, runtime: &RuntimeHandle, source: SourceId) -> Poll { + let image_data: Vec<_> = output.image_data.into_iter().collect(); + let unfinished = |svg, image_data| RenderOutputType::Svg { svg, image_data }; + + if output.effect_maps.is_empty() && output.deferred_images.is_empty() { + self.clear(); + return Poll::Final(unfinished(output.svg, image_data)); + } + + // Evaluations of one render reuse its cached intermediate SVG, and the IDs generated for it set the key apart from other renders + let mut hasher = DefaultHasher::new(); + output.svg.hash(&mut hasher); + footprint.cache_hash(&mut hasher); + let key = hasher.finish(); + + match self.readback(key) { + Some(Some((svg, image_data))) => return Poll::Final(RenderOutputType::Svg { svg, image_data }), + Some(None) => return Poll::Partial(unfinished(output.svg, image_data)), + None => {} + } + + let Some(executor) = executor() else { return Poll::Final(unfinished(output.svg, image_data)) }; + let effect_maps = executor.render_effect_maps(&output.effect_maps, footprint); + let deferred_images = executor.render_deferred_svg_images(&output.deferred_images, footprint); + if effect_maps.is_empty() && deferred_images.is_empty() { + self.clear(); + return Poll::Final(unfinished(output.svg, image_data)); + } + + let (task, registration) = AbortHandle::new_pair(); + *self.lock() = Some(SvgReadback { key, finished: None, task }); + + let (mut svg, mut finished_image_data) = (output.svg.clone(), image_data.clone()); + let readback = async move { + executor.resolve_effect_maps(&mut svg, effect_maps).await; + executor.resolve_deferred_svg_images(&mut svg, &mut finished_image_data, deferred_images).await; + (svg, finished_image_data) + }; + let slot = self.clone(); + runtime.spawn( + source, + Box::pin(async move { + if let Ok(finished) = Abortable::new(readback, registration).await + && let Some(readback) = slot.lock().as_mut().filter(|readback| readback.key == key) + { + readback.finished = Some(finished); + } + }), + ); + + // A spawner that runs the task right away has already finished it + match self.readback(key).flatten() { + Some((svg, image_data)) => Poll::Final(RenderOutputType::Svg { svg, image_data }), + None => Poll::Partial(unfinished(output.svg, image_data)), + } + } +} + +#[node_macro::node(category(""), version(3))] fn render( ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, data: Item, #[scope(crate::platform_application_io::wgpu_executor::IDENTIFIER)] executor: impl Node, Output = Item>, -) -> Result, Interrupt> { + #[scope("runtime")] runtime: Item, + #[source_id] source: Item, + #[data] svg_readback: SvgReadbackSlot, +) -> Poll> { let footprint = ctx.footprint(); let render_params = ctx .vararg(0) @@ -99,27 +210,23 @@ fn render( let output = SvgRenderOutput::from(render); assert!(output.svg_defs.is_empty()); - // 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 - let (effect_maps, deferred_images) = match output.effect_maps.is_empty() && output.deferred_images.is_empty() { - true => (Vec::new(), Vec::new()), - false => match executor.eval(Context::default()) { - Ok(executor) => ( - executor.element().render_effect_maps(&output.effect_maps, *footprint), - executor.element().render_deferred_svg_images(&output.deferred_images, *footprint), - ), - Err(_) => (Vec::new(), Vec::new()), - }, - }; - - RenderOutputType::Svg { - svg: output.svg, - image_data: output.image_data.into_iter().collect(), - effect_maps, - deferred_images, - } + let executor = || executor.eval(&Context::default()).value().map(Item::into_element); + svg_readback.poll(output, *footprint, executor, runtime.element(), *source.element()) } (RenderOutputTypeRequest::Vello, RenderIntermediateType::Vello(data)) => { - let executor = executor.eval(Context::default())?.into_element(); + // The latest SVG render isn't needed anymore, and a finished one holds a whole SVG export + svg_readback.clear(); + + let (executor, executor_partial, executor_error) = match executor.eval(&Context::default()) { + Poll::Final(executor) => (executor.into_element(), false, None), + Poll::Partial(executor) => (executor.into_element(), true, None), + Poll::Fallback(boxed) => { + let (executor, error) = *boxed; + (executor.into_element(), false, Some(error)) + } + Poll::Pending => return Poll::Pending, + Poll::Error(error) => return Poll::Error(error), + }; let mut draw = |scene: &mut VelloSceneBuilder| data.render_to_vello(scene, Default::default(), &render_params); let texture = match executor.render_vello(footprint.resolution, footprint.transform, &mut draw) { @@ -128,15 +235,24 @@ fn render( Err(error) => { log::error!("Failed to render Vello scene: {error}"); let limit = glam::UVec2::splat(executor.context().device.limits().max_texture_dimension_2d); - executor.render_vello(footprint.resolution.min(limit), footprint.transform, &mut |_| {}).map_err(NodeError::new)? + match executor.render_vello(footprint.resolution.min(limit), footprint.transform, &mut |_| {}) { + Ok(texture) => texture, + Err(error) => return Poll::error(error), + } } }; - RenderOutputType::Texture(texture) + + let texture = RenderOutputType::Texture(texture); + match (executor_partial, executor_error) { + (true, _) => Poll::Partial(texture), + (false, Some(error)) => Poll::Fallback(Box::new((texture, error))), + (false, None) => Poll::Final(texture), + } } _ => unreachable!("Render node did not receive its requested data type"), }; - Ok(Item::new_from_element(RenderOutput { data, metadata })) + data.map(|data| Item::new_from_element(RenderOutput { data, metadata })) } #[node_macro::node(category(""))] @@ -191,3 +307,125 @@ fn create_context( result.element_mut().metadata.apply_transform(glam::DAffine2::from_scale(glam::DVec2::splat(1. / render_config.scale))); Ok(result) } + +#[cfg(test)] +mod tests { + use super::*; + use core_types::ATTR_TRANSFORM; + use core_types::runtime::{AsyncRuntime, Spawn, Task}; + use glam::{DAffine2, DVec2, UVec2}; + use graphic_types::raster_types::Image; + use graphic_types::{Adjustment, Effect, EffectOperation, stamp_effect}; + + /// Holds the tasks the runtime spawns until a test runs them. + #[derive(Default)] + struct HeldTasks(Mutex>); + + impl Spawn for HeldTasks { + fn spawn(&self, task: Task) { + self.0.lock().unwrap().push(task); + } + } + + impl HeldTasks { + fn take(&self) -> Vec { + std::mem::take(&mut *self.0.lock().unwrap()) + } + } + + /// An SVG of an orange square casting a shadow, then drained of its color by Vibrance, which no SVG filter can carry out after the shadow. + fn deferred_svg() -> SvgRenderOutput { + let shadow = EffectOperation::DropShadow { + color: Color::BLACK, + angle: 180., + distance: 4., + spread: 0., + size: 0., + contour: Default::default(), + knockout: true, + }; + let mut item = + Item::new_from_element(Raster::new_cpu(Image::new(2, 2, Color::from_gamma_srgb_channels(1., 0.5, 0., 1.)))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(10.))); + stamp_effect(&mut item, Effect::new(&shadow)); + stamp_effect(&mut item, Effect::new(&EffectOperation::Adjustment(Adjustment::Vibrance { vibrance: 0., saturation: -100. }))); + + let mut render = SvgRender::new(); + let render_params = RenderParams { + for_export: true, + ..Default::default() + }; + List::new_from_item(item).render_svg(&mut render, &render_params); + SvgRenderOutput::from(render) + } + + /// The same render's output again, as another evaluation of the render node gets it. + fn again(output: &SvgRenderOutput) -> SvgRenderOutput { + SvgRenderOutput { + svg: output.svg.clone(), + svg_defs: output.svg_defs.clone(), + image_data: output.image_data.clone(), + effect_maps: output.effect_maps.clone(), + deferred_images: output.deferred_images.clone(), + } + } + + /// A view of the document at the identity transform, `size` pixels across. + fn view(size: u32) -> Footprint { + Footprint { + transform: DAffine2::IDENTITY, + resolution: UVec2::splat(size), + ..Default::default() + } + } + + #[test] + fn an_svg_render_is_partial_until_its_readback_lands() { + let Some(executor) = futures::executor::block_on(WgpuExecutor::new()) else { return }; + let tasks = Arc::new(HeldTasks::default()); + let runtime = AsyncRuntime::new(tasks.clone()); + let slot = SvgReadbackSlot::default(); + let output = deferred_svg(); + let poll = || slot.poll(again(&output), view(32), || Some(executor.clone()), &runtime.handle(), SourceId(1)); + + // Until the readback lands, the SVG keeps its placeholders, and evaluating the same render again doesn't read it back again + for _ in 0..2 { + let Poll::Partial(RenderOutputType::Svg { svg, .. }) = poll() else { + panic!("expected a partial SVG") + }; + assert!(svg.contains("deferred-image"), "{svg}"); + } + let spawned = tasks.take(); + assert_eq!(spawned.len(), 1, "the readback should be spawned once"); + + spawned.into_iter().for_each(futures::executor::block_on); + let Poll::Final(RenderOutputType::Svg { svg, .. }) = poll() else { + panic!("expected a finished SVG") + }; + assert!(svg.contains("data:image/png;base64,") && !svg.contains("deferred-image"), "{svg}"); + } + + #[test] + fn a_render_for_another_view_cancels_the_readback_of_the_one_it_replaces() { + let Some(executor) = futures::executor::block_on(WgpuExecutor::new()) else { return }; + let tasks = Arc::new(HeldTasks::default()); + let runtime = AsyncRuntime::new(tasks.clone()); + let slot = SvgReadbackSlot::default(); + let output = deferred_svg(); + let poll = |size| slot.poll(again(&output), view(size), || Some(executor.clone()), &runtime.handle(), SourceId(1)); + + assert!(matches!(poll(32), Poll::Partial(_))); + assert!(matches!(poll(64), Poll::Partial(_))); + let spawned = tasks.take(); + assert_eq!(spawned.len(), 2); + + // The first view's readback, cancelled, leaves nothing finished, so that view reads back anew + let mut spawned = spawned.into_iter(); + futures::executor::block_on(spawned.next().unwrap()); + assert!(matches!(poll(32), Poll::Partial(_)), "the cancelled readback shouldn't finish its view"); + assert_eq!(tasks.take().len(), 1, "the first view should be read back anew"); + + // The second view's readback was cancelled in turn by the first view replacing it + futures::executor::block_on(spawned.next().unwrap()); + assert!(matches!(poll(64), Poll::Partial(_)), "the second view should be read back anew too"); + } +}