diff --git a/editor/src/node_graph_executor.rs b/editor/src/node_graph_executor.rs index 34c8720baf..318e753e98 100644 --- a/editor/src/node_graph_executor.rs +++ b/editor/src/node_graph_executor.rs @@ -506,16 +506,11 @@ impl NodeGraphExecutor { } = *execution_response; all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied()); - while let Some(&(queued_execution_id, _)) = self.futures.front() { - if queued_execution_id < execution_id { - self.futures.pop_front(); - } else { - break; - } - } + self.futures + .retain(|(queued_execution_id, execution_context)| *queued_execution_id >= execution_id || execution_context.export_config.is_some()); - 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 = if let Some(index) = self.futures.iter().position(|&(queued_execution_id, _)| queued_execution_id == execution_id) { + let (_, execution_context) = self.futures.remove(index).expect("the index was just found"); if execution_context.export_config.is_none() && execution_context.measure_fill.is_none() { self.pending = Some((execution_id, execution_context.clone())); } @@ -636,17 +631,18 @@ impl NodeGraphExecutor { let node_graph_output = match node_graph_output { Ok(output) => output, Err(message) => { + if let Some(message) = &message { + log::error!("Node graph evaluation failed:\n{message}"); + } + if execution_context.export_config.is_some() { + responses.add(export_failure_dialog(message)); + continue; + } + // 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_outlines(HashMap::new()); document.network_interface.update_vector_modify(HashMap::new()); - if let Some(message) = &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 }); break; } @@ -772,6 +768,8 @@ impl NodeGraphExecutor { if matches!(execution_response.result, ExecutionResult::Uncompiled) && execution_context.is_some_and(|context| context.export_config.is_some()) { responses.add(export_failure_dialog(None)); } + self.futures + .retain(|(execution_id, execution_context)| *execution_id != execution_response.execution_id || execution_context.export_config.is_none()); all_dropped_thumbnails.extend(execution_response.dropped_thumbnails); } diff --git a/editor/src/node_graph_executor/recompile_tests.rs b/editor/src/node_graph_executor/recompile_tests.rs index c395f3b7bf..faaf1f31ea 100644 --- a/editor/src/node_graph_executor/recompile_tests.rs +++ b/editor/src/node_graph_executor/recompile_tests.rs @@ -18,8 +18,8 @@ async fn compile_and_run(editor: &mut EditorTestUtils) { 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 -/// for one more update, so a first update clears those of the graph before it. +/// The proto node IDs compiled for the document node paths that pass `keep`. The runtime keeps the output of the network +/// 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 { compile_and_run(editor).await; compile_and_run(editor).await; diff --git a/editor/src/node_graph_executor/runtime.rs b/editor/src/node_graph_executor/runtime.rs index ff91d41604..a058c089b0 100644 --- a/editor/src/node_graph_executor/runtime.rs +++ b/editor/src/node_graph_executor/runtime.rs @@ -43,25 +43,33 @@ pub struct NodeRuntime { pub(super) executor: DynamicExecutor, #[cfg(not(test))] executor: DynamicExecutor, - output: OutputHandle, + receiver: Receiver, sender: Sender, + editor_wake: Wake, dirty: Arc, + + output: Option, + previous: Option, + pending: Option, - pending_export: Option, + pending_exports: Vec<(ExecutionRequest, OutputHandle)>, pending_eyedropper: Option, pending_thumbnails: Option, + + viewport_artwork: Option, + /// The network the executor last compiled successfully, with previews applied. old_graph: Option, - /// Whether the latest network failed to compile, leaving the executor with an older one that mustn't be shown in its place. - compile_failed: bool, - async_runtime: Option, + async_runtime: Option, editor_api: Arc, resources: ResourceRegistry, + node_graph_errors: GraphErrors, node_graph_warnings: GraphErrors, + thumbnails: Thumbnails, observer: Observer, /// Whether an observation changed since its results were last sent. @@ -69,13 +77,9 @@ pub struct NodeRuntime { preprocessor: preprocessor::Preprocessor, - /// Cached surface for Wasm viewport rendering (reused across frames) - #[cfg(all(target_family = "wasm", feature = "wasm"))] - wasm_canvas_cache: CanvasSurfaceHandle, - /// The viewport's latest artwork. - viewport_artwork: Option, /// The layers from the render of the viewport's latest artwork. rendered_layers: RenderedLayers, + /// The latest overlays, rendered again over each new artwork. overlays: Option, /// Whether the overlays or the artwork changed since the overlays were last rendered. @@ -83,6 +87,10 @@ pub struct NodeRuntime { overlays_canvas: VelloCanvas, /// The latest rendered overlays. overlays_texture: Option, + + /// Cached surface for Wasm viewport rendering (reused across frames) + #[cfg(all(target_family = "wasm", feature = "wasm"))] + wasm_canvas_cache: CanvasSurfaceHandle, } /// What the viewport shows beneath its overlays. @@ -149,20 +157,26 @@ impl NodeRuntime { pub fn new(receiver: Receiver, sender: Sender, editor_wake: Wake) -> Self { Self { executor: DynamicExecutor::default(), - output: OutputHandle::default(), + receiver, sender, + editor_wake, dirty: Default::default(), + + output: None, + previous: None, + pending: None, - pending_export: None, + pending_exports: Vec::new(), pending_eyedropper: None, pending_thumbnails: None, - old_graph: None, - compile_failed: false, - resources: ResourceRegistry::default(), - async_runtime: None, + viewport_artwork: None, + + old_graph: None, + + async_runtime: None, editor_api: PlatformEditorApi { #[cfg(not(test))] application_io: None, @@ -171,41 +185,71 @@ impl NodeRuntime { application_io: Some(PlatformApplicationIo::default().into()), } .into(), + resources: ResourceRegistry::default(), node_graph_errors: Vec::new(), node_graph_warnings: Vec::new(), + thumbnails: Thumbnails::new(), observer: Observer::default(), observations_changed: false, preprocessor: preprocessor::Preprocessor::new(), - #[cfg(all(target_family = "wasm", feature = "wasm"))] - wasm_canvas_cache: CanvasSurfaceHandle::new(), - viewport_artwork: None, rendered_layers: RenderedLayers::default(), + overlays: None, overlays_stale: false, overlays_canvas: VelloCanvas::default(), overlays_texture: None, + + #[cfg(all(target_family = "wasm", feature = "wasm"))] + wasm_canvas_cache: CanvasSurfaceHandle::new(), } } pub fn update(&mut self) { - if self.pending_export.is_some() { - return; - } - - let mut graph = None; - for request in self.receiver.try_iter() { + while let Ok(request) = self.receiver.try_recv() { match request { - GraphRuntimeRequest::GraphUpdate(update) => graph = Some(update), - GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_eyedropper => self.pending_eyedropper = Some(request), - GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_export => { - self.pending_export = Some(request); - self.dirty.store(true, Ordering::Release); - break; + GraphRuntimeRequest::GraphUpdate(GraphUpdate { + mut network, + resources, + previewed, + layers, + observations, + }) => { + apply_previews(&mut network, &previewed); + write_layer_paths(&mut network, &layers); + self.observer.replace_all(observations); + self.resources = resources; + + self.node_graph_errors.clear(); + self.node_graph_warnings.clear(); + let result = self.update_network(network.clone()); + if result.is_ok() { + self.thumbnails.update_sources(&layers, &network, &self.executor); + self.old_graph = Some(network); + } + + let node_graph_errors = self.node_graph_errors.clone(); + let node_graph_warnings = self.node_graph_warnings.clone(); + + self.sender + .send(NodeGraphUpdate::CompilationResponse(CompilationResponse { + result, + node_graph_errors, + node_graph_warnings, + })) + .expect("Failed to send response"); } + GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_eyedropper => self.pending_eyedropper = Some(request), + GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_export => match self.output.clone() { + Some(output) => { + self.pending_exports.push((request, output)); + self.dirty.store(true, Ordering::Release); + } + None => self.send_result(request.execution_id, ExecutionResult::Uncompiled), + }, GraphRuntimeRequest::ExecutionRequest(request) => { self.pending = Some(request); self.dirty.store(true, Ordering::Release); @@ -214,15 +258,10 @@ impl NodeRuntime { self.thumbnails.set_in_view(layers); self.pending_thumbnails = Some(document_id); } - // A graph update applied after this loop would otherwise replace this with what it observed before - GraphRuntimeRequest::Observe { key, observation } => match (&mut graph, observation) { - (Some(update), Some(observation)) => _ = update.observations.insert(key, observation), - (Some(update), None) => _ = update.observations.remove(&key), - (None, observation) => { - self.observer.set(key, observation); - self.observations_changed = true; - } - }, + GraphRuntimeRequest::Observe { key, observation } => { + self.observer.set(key, observation); + self.observations_changed = true; + } GraphRuntimeRequest::ClipboardSvg { id, layers } => { let svg = self.old_graph.as_ref().and_then(|network| thumbnails::layers_svg(&layers, network, &self.executor)); self.sender.send(NodeGraphUpdate::ClipboardSvg { id, svg }).expect("Failed to send response"); @@ -233,82 +272,47 @@ impl NodeRuntime { } } } - - let Some(GraphUpdate { - mut network, - resources, - previewed, - layers, - observations, - }) = graph - else { - return; - }; - - apply_previews(&mut network, &previewed); - write_layer_paths(&mut network, &layers); - self.observer.replace_all(observations); - self.resources = resources; - - self.node_graph_errors.clear(); - self.node_graph_warnings.clear(); - let result = self.update_network(network.clone()); - self.compile_failed = result.is_err(); - if result.is_ok() { - self.thumbnails.update_sources(&layers, &network, &self.executor); - self.old_graph = Some(network); - } - let node_graph_errors = self.node_graph_errors.clone(); - let node_graph_warnings = self.node_graph_warnings.clone(); - - self.sender - .send(NodeGraphUpdate::CompilationResponse(CompilationResponse { - result, - node_graph_errors, - node_graph_warnings, - })) - .expect("Failed to send response"); } pub async fn run(&mut self) -> Option { let dirty = self.dirty.swap(false, Ordering::Acquire); let mut texture = None; - if let Some(export) = self.pending_export { - if dirty { - self.run_export(export).await; + if dirty { + for (request, output) in std::mem::take(&mut self.pending_exports) { + self.run_export(request, output).await; } - } else { - let viewport = if dirty { self.pending } else { None }; + } - if let Some(document_id) = self.pending_thumbnails.take() - && viewport.is_none() - && !self.compile_failed - { - let mut responses = VecDeque::new(); - self.thumbnails.render_stale(&self.executor, &self.editor_api, &mut responses).await; - if !responses.is_empty() { - self.sender.send(NodeGraphUpdate::Thumbnails { responses, document_id }).expect("Failed to send response"); - } - } + let viewport = if dirty { self.pending } else { None }; - if std::mem::take(&mut self.observations_changed) && viewport.is_none() { - let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref()); - self.sender.send(NodeGraphUpdate::Observations(observations)).expect("Failed to send response"); + if let Some(document_id) = self.pending_thumbnails.take() + && viewport.is_none() + && self.output.is_some() + { + let mut responses = VecDeque::new(); + self.thumbnails.render_stale(&self.executor, &self.editor_api, &mut responses).await; + if !responses.is_empty() { + self.sender.send(NodeGraphUpdate::Thumbnails { responses, document_id }).expect("Failed to send response"); } + } - if let Some(eyedropper) = self.pending_eyedropper.take() { - self.run_eyedropper(eyedropper).await; - } + if std::mem::take(&mut self.observations_changed) && viewport.is_none() { + let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref()); + self.sender.send(NodeGraphUpdate::Observations(observations)).expect("Failed to send response"); + } - if let Some(viewport) = viewport { - self.run_viewport(viewport).await; - } + if let Some(eyedropper) = self.pending_eyedropper.take() { + self.run_eyedropper(eyedropper).await; + } - // Overlays that changed without new artwork are drawn over the artwork already shown - if self.overlays_stale { - texture = self.composite_viewport_frame(); - } + if let Some(viewport) = viewport { + self.run_viewport(viewport).await; + } + + // Overlays that changed without new artwork are drawn over the artwork already shown + if self.overlays_stale { + texture = self.composite_viewport_frame(); } (self.editor_wake)(); @@ -318,7 +322,11 @@ impl NodeRuntime { async fn run_viewport(&mut self, request: ExecutionRequest) { self.thumbnails.set_scale(request.render_config.scale); - let Some(mut result) = self.evaluate(request) else { return }; + let result = match self.output.clone() { + Some(output) => self.evaluate(&output, request), + None => Some(ExecutionResult::Uncompiled), + }; + let Some(mut result) = result else { return }; let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref()); if let Some(RenderOutput { data, metadata }) = result.render_output() { @@ -378,15 +386,14 @@ impl NodeRuntime { Some(frame) } - async fn run_export(&mut self, request: ExecutionRequest) { - let result = self.evaluate(request); - if matches!(result, Some(ExecutionResult::Pending)) { + async fn run_export(&mut self, request: ExecutionRequest, output: OutputHandle) { + let result = self.evaluate(&output, request); + if matches!(result, Some(ExecutionResult::Pending | ExecutionResult::Partial(_))) { + self.pending_exports.push((request, output)); return; } - self.pending_export = None; let Some(mut result) = result else { return }; - self.dirty.store(true, Ordering::Release); if let Some(RenderOutput { data, .. }) = result.render_output() && let RenderOutputType::Texture(texture) = data @@ -405,7 +412,8 @@ impl NodeRuntime { request.render_config.pointer = viewport.render_config.pointer; } - if let Some(mut result) = self.evaluate(request) + if let Some(output) = self.output.clone() + && let Some(mut result) = self.evaluate(&output, request) && let Some(RenderOutput { data: RenderOutputType::Texture(texture), .. @@ -416,11 +424,7 @@ impl NodeRuntime { } } - fn evaluate(&mut self, request: ExecutionRequest) -> Option { - if self.compile_failed { - return Some(ExecutionResult::Uncompiled); - } - + fn evaluate(&mut self, output: &OutputHandle, request: ExecutionRequest) -> Option { let ExecutionRequest { execution_id, mut render_config } = request; // Render via the SVG pipeline even though raster was requested if SVG Preview render mode is active @@ -429,39 +433,46 @@ impl NodeRuntime { } let context = render_config.into_context_with_generations(self.async_runtime().snapshot()); - let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.execute(&self.output, context))) { + let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.execute(output, context))) { Ok(Ok(Poll::Pending)) => ExecutionResult::Pending, - Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending, Ok(Ok(Poll::Partial(value))) => ExecutionResult::Partial(value), Ok(Ok(Poll::Final(value))) => ExecutionResult::Value(value), Ok(Ok(Poll::Fallback(boxed))) => { let (value, error) = *boxed; - ExecutionResult::Fallback(value, self.resolve_errors(&error)) + ExecutionResult::Fallback(value, self.resolve_errors(output, &error)) } - Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(&error)), + Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(output, &error)), Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error.to_string()).error()), NodeErrorTrace::default())]))), Err(payload) => { - let response = ExecutionResponse { - execution_id, - result: ExecutionResult::Panic(payload), - responses: VecDeque::new(), - dropped_thumbnails: Vec::new(), - observations: HashMap::new(), - #[cfg(all(target_family = "wasm", feature = "wasm"))] - viewport_canvas_info: None, - }; - self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response"); + self.send_result(execution_id, ExecutionResult::Panic(payload)); return None; } }; Some(result) } + fn send_result(&self, execution_id: u64, result: ExecutionResult) { + let response = ExecutionResponse { + execution_id, + result, + responses: VecDeque::new(), + dropped_thumbnails: Vec::new(), + observations: HashMap::new(), + #[cfg(all(target_family = "wasm", feature = "wasm"))] + viewport_canvas_info: None, + }; + self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response"); + } + async fn respond(&mut self, request: ExecutionRequest, result: ExecutionResult, observations: HashMap) { let mut responses = VecDeque::new(); // While the graph fails to compile, thumbnails stay stale to render once it compiles, not from the last network that did - let dropped_thumbnails = if self.compile_failed { Vec::new() } else { self.update_thumbnails(&mut responses).await }; + let dropped_thumbnails = if self.output.is_none() || request.render_config.for_export { + Vec::new() + } else { + self.update_thumbnails(&mut responses).await + }; #[cfg(all(target_family = "wasm", feature = "wasm"))] let mut result = result; @@ -507,6 +518,10 @@ impl NodeRuntime { } fn update_network(&mut self, graph: NodeNetwork) -> Result { + if let Some(output) = self.output.take() { + self.previous = Some(output); + } + let mut scoped_network = wrap_network_with_render_node_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle()); if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) { @@ -530,7 +545,7 @@ impl NodeRuntime { assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?"); let updated = self.executor.update(proto_network).map(|(output, types)| { - self.output = output; + self.output = Some(output); types }); let result = updated.map_err(|(types, e)| { @@ -541,7 +556,7 @@ impl NodeRuntime { result } - fn resolve_errors(&self, error: &NodeError) -> EvaluationErrors { + fn resolve_errors(&self, output: &OutputHandle, error: &NodeError) -> EvaluationErrors { let source_map = self.executor.tree().source_map(); let paths = |node: NodeId| -> NodePaths { let mut paths: Vec<_> = source_map.iter().filter(|(_, (id, _))| *id == node).map(|(path, _)| path.clone()).collect(); @@ -549,7 +564,7 @@ impl NodeRuntime { paths.into() }; let mut errors = Vec::new(); - let output = self.output.node(); + let output = output.node(); let mut pending = vec![(vec![paths(output)], output, error)]; while let Some((mut trace, node, error)) = pending.pop() { let passed = self.executor.trace_error(node, error); @@ -744,11 +759,50 @@ mod tests { }); } + async fn run(editor: &mut EditorTestUtils) -> Option { + editor.runtime.update(); + editor.runtime.run().await + } + /// The ID of the viewport request the runtime evaluates, which only changes once it has read a newer one. fn last_request(editor: &EditorTestUtils) -> Option { editor.runtime.pending.map(|request| request.execution_id) } + fn respond_to_last_request(editor: &mut EditorTestUtils, result: ExecutionResult) -> Vec { + let response = ExecutionResponse { + execution_id: last_request(editor).unwrap(), + result, + responses: VecDeque::new(), + dropped_thumbnails: Vec::new(), + observations: HashMap::new(), + }; + editor.runtime.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).unwrap(); + editor.dispatch(Message::Wake) + } + + fn failed(messages: &[FrontendMessage]) -> bool { + messages.iter().any(|message| matches!(message, FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error })) + } + + fn drawn_in(messages: &[FrontendMessage]) -> Option<&str> { + messages.iter().find_map(|message| match message { + FrontendMessage::UpdateDocumentArtwork { svg } => Some(svg.as_str()), + _ => None, + }) + } + + fn empty_svg() -> RenderOutputType { + RenderOutputType::Svg { + svg: String::new(), + image_data: Vec::new(), + } + } + + fn rendered(data: RenderOutputType) -> TaggedValue { + TaggedValue::RenderOutput(RenderOutput { data, metadata: Default::default() }) + } + #[tokio::test] async fn only_update_reads_the_channel() { let mut editor = editor().await; @@ -1032,28 +1086,63 @@ mod tests { assert!(shows_dialog, "the export should show why it saved nothing"); } - #[tokio::test] - async fn an_export_goes_ahead_of_what_was_sent_after_it() { - let mut editor = editor().await; - let last = last_request(&editor); - send_export(&mut editor, FileType::Svg); - send_update(&mut editor); + fn rectangle_node(editor: &EditorTestUtils) -> NodeId { + use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier; + use graphene_std::vector::generator_nodes::rectangle; - editor.runtime.update(); - assert!(editor.runtime.pending_export.is_some()); - assert_eq!(last_request(&editor), last, "the request sent after the export was read ahead of it"); + let interface = &editor.active_document().network_interface; + let nodes = interface.document_network().nodes.keys().copied(); + let reference = Some(DefinitionIdentifier::ProtoNode(rectangle::IDENTIFIER)); + nodes.into_iter().find(|node_id| interface.reference(node_id, &[]) == reference).unwrap() + } - editor.runtime.run().await; - assert!(exported(&mut editor)); - - editor.runtime.update(); - assert_ne!(last_request(&editor), last); - editor.runtime.run().await; - assert!(evaluated(&mut editor), "the request sent after the export was lost"); + fn set_layer_visible(editor: &mut EditorTestUtils, visible: bool) { + let layer = editor.active_document().metadata().all_layers().next().unwrap().to_node(); + editor.active_document_mut().network_interface.set_visibility(&layer, &[], visible); } #[tokio::test] - async fn a_parked_export_holds_back_everything_sent_after_it() { + async fn an_export_shows_the_network_it_was_sent_with_whatever_was_sent_after_it() { + let mut editor = editor().await; + + set_layer_visible(&mut editor, false); + send_export(&mut editor, FileType::Svg); + set_layer_visible(&mut editor, true); + send_update(&mut editor); + + editor.runtime.update(); + editor.runtime.run().await; + let messages = editor.dispatch(Message::Wake); + let exported = messages.iter().find_map(|message| match message { + FrontendMessage::TriggerSaveFile { content, .. } => Some(String::from_utf8(content.clone().into_vec()).unwrap()), + _ => None, + }); + assert!(exported.is_some_and(|svg| !svg.contains("