Render thumbnails with Vello (#4805)

This commit is contained in:
Dennis Kobert authored and GitHub committed 2026-10-26 11:33:36 +00:00
1 parent a566448ae2
commit 7e6e4276d1
22 files changed
+698 -381

No files matched your search

Generated
+1
View File
@@ -2446,6 +2446,7 @@ dependencies = [
"usvg",
"vello_gpu",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
"wgpu-executor",
"zip",
+2 -1
View File
@@ -15,7 +15,7 @@ workspace = true
[features]
default = ["gpu"]
wasm = ["graphene-std/wasm", "interpreted-executor/wasm", "dep:wasm-bindgen"]
wasm = ["graphene-std/wasm", "interpreted-executor/wasm", "dep:wasm-bindgen", "dep:wasm-bindgen-futures"]
gpu = ["interpreted-executor/gpu", "dep:wgpu-executor"]
[dependencies]
@@ -64,6 +64,7 @@ wgpu-executor = { workspace = true, optional = true }
# Optional workspace dependencies
wasm-bindgen = { workspace = true, optional = true }
wasm-bindgen-futures = { workspace = true, optional = true }
[target.'cfg(not(target_family = "wasm"))'.dependencies]
tokio = { workspace = true }
@@ -332,6 +332,19 @@ pub enum FrontendMessage {
ClearNodeThumbnails {
ids: Vec<NodeId>,
},
UpdateNodeThumbnailPixels {
id: NodeId,
width: u32,
height: u32,
pixels: serde_bytes::ByteBuf,
},
UpdateNodeThumbnailCanvases {
id: NodeId,
#[serde(rename = "layersPanelCanvasId")]
layers_panel_canvas_id: u64,
#[serde(rename = "nodeGraphCanvasId")]
node_graph_canvas_id: u64,
},
UpdateOpenDocumentsList {
#[serde(rename = "openDocuments")]
open_documents: Vec<DocumentInfo>,
@@ -10,8 +10,8 @@ pub struct LayersInView {
layers_panel: HashSet<NodeId>,
/// The nodes in view in the node graph while it's open.
node_graph: HashSet<NodeId>,
/// The latest thumbnail of each layer, as rendered by the graph runtime.
thumbnails: HashMap<NodeId, String>,
/// The message with the latest thumbnail of each layer, as rendered by the graph runtime.
thumbnails: HashMap<NodeId, FrontendMessage>,
/// The layers whose latest thumbnail the frontend has.
thumbnails_sent: HashSet<NodeId>,
}
@@ -40,10 +40,17 @@ impl LayersInView {
responses.add(PortfolioMessage::SubmitThumbnailsInView);
}
/// Keeps a layer's newly rendered thumbnail, sending it to the frontend only if the layer is in view.
pub fn receive_thumbnail(&mut self, layer: NodeId, thumbnail: String, responses: &mut VecDeque<Message>) {
pub fn thumbnail_layer(message: &FrontendMessage) -> Option<NodeId> {
match message {
FrontendMessage::UpdateNodeThumbnail { id, .. } | FrontendMessage::UpdateNodeThumbnailCanvases { id, .. } | FrontendMessage::UpdateNodeThumbnailPixels { id, .. } => Some(*id),
_ => None,
}
}
/// Keeps the message with a layer's newly rendered thumbnail, sending it to the frontend only if the layer is in view.
pub fn receive_thumbnail(&mut self, layer: NodeId, thumbnail: FrontendMessage, responses: &mut VecDeque<Message>) {
if self.in_view(&layer) {
responses.add(FrontendMessage::UpdateNodeThumbnail { id: layer, value: thumbnail.clone() });
responses.add(thumbnail.clone());
self.thumbnails_sent.insert(layer);
} else {
// Out of view, the frontend's copy is now stale until the layer comes back into view
@@ -84,7 +91,7 @@ impl LayersInView {
}
let Some(thumbnail) = self.thumbnails.get(&layer) else { continue };
responses.add(FrontendMessage::UpdateNodeThumbnail { id: layer, value: thumbnail.clone() });
responses.add(thumbnail.clone());
self.thumbnails_sent.insert(layer);
}
}
@@ -94,6 +101,10 @@ impl LayersInView {
mod tests {
use super::*;
fn svg_thumbnail(layer: NodeId, svg: &str) -> FrontendMessage {
FrontendMessage::UpdateNodeThumbnail { id: layer, value: svg.to_string() }
}
fn thumbnails_sent(responses: VecDeque<Message>) -> Vec<(NodeId, String)> {
responses
.into_iter()
@@ -110,8 +121,8 @@ mod tests {
let mut layers_in_view = LayersInView::default();
let mut responses = VecDeque::new();
layers_in_view.receive_thumbnail(layer, "first".to_string(), &mut responses);
layers_in_view.receive_thumbnail(layer, "latest".to_string(), &mut responses);
layers_in_view.receive_thumbnail(layer, svg_thumbnail(layer, "first"), &mut responses);
layers_in_view.receive_thumbnail(layer, svg_thumbnail(layer, "latest"), &mut responses);
assert!(thumbnails_sent(responses).is_empty(), "out of view, a thumbnail isn't sent");
let mut responses = VecDeque::new();
@@ -130,12 +141,12 @@ mod tests {
let mut responses = VecDeque::new();
layers_in_view.set_layers_panel(HashSet::from([layer]), &mut responses);
layers_in_view.receive_thumbnail(layer, "in view".to_string(), &mut responses);
layers_in_view.receive_thumbnail(layer, svg_thumbnail(layer, "in view"), &mut responses);
assert_eq!(thumbnails_sent(responses), vec![(layer, "in view".to_string())], "in view, a thumbnail is sent as it's received");
let mut responses = VecDeque::new();
layers_in_view.set_layers_panel(HashSet::new(), &mut responses);
layers_in_view.receive_thumbnail(layer, "changed".to_string(), &mut responses);
layers_in_view.receive_thumbnail(layer, svg_thumbnail(layer, "changed"), &mut responses);
layers_in_view.set_layers_panel(HashSet::from([layer]), &mut responses);
assert_eq!(thumbnails_sent(responses), vec![(layer, "changed".to_string())]);
}
@@ -147,7 +158,7 @@ mod tests {
let mut responses = VecDeque::new();
layers_in_view.set_layers_panel(HashSet::from([layer]), &mut responses);
layers_in_view.receive_thumbnail(layer, "before".to_string(), &mut responses);
layers_in_view.receive_thumbnail(layer, svg_thumbnail(layer, "before"), &mut responses);
let mut responses = VecDeque::new();
layers_in_view.forget_thumbnails(&[layer, other_documents_layer], &mut responses);
@@ -163,7 +174,7 @@ mod tests {
assert!(thumbnails_sent(responses).is_empty(), "a forgotten thumbnail isn't sent again");
let mut responses = VecDeque::new();
layers_in_view.receive_thumbnail(layer, "after".to_string(), &mut responses);
layers_in_view.receive_thumbnail(layer, svg_thumbnail(layer, "after"), &mut responses);
assert_eq!(thumbnails_sent(responses), vec![(layer, "after".to_string())], "rendered anew, it's sent as before");
}
}
+8 -6
View File
@@ -1,5 +1,6 @@
use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage, RenderStatus};
use crate::messages::portfolio::document::node_graph::utility_types::NodeEvaluationError;
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
use crate::messages::prelude::*;
use glam::{DAffine2, DVec2, UVec2};
@@ -497,14 +498,14 @@ impl NodeGraphExecutor {
// Thumbnails reach the frontend only for the layers it shows in view
for response in existing_responses {
match response {
FrontendMessage::UpdateNodeThumbnail { id, value } => {
match LayersInView::thumbnail_layer(&response) {
Some(layer) => {
// A render finishing after a switch to another document has thumbnails of the previous one's layers
if execution_context.document_id == document_id {
document.layers_in_view.receive_thumbnail(id, value, responses);
document.layers_in_view.receive_thumbnail(layer, response, responses);
}
}
response => responses.add(response),
None => responses.add(response),
}
}
document.network_interface.update_vector_modify(vector_modify);
@@ -616,8 +617,9 @@ impl NodeGraphExecutor {
fn receive_thumbnails(document: &mut DocumentMessageHandler, thumbnails: VecDeque<FrontendMessage>, responses: &mut VecDeque<Message>) {
for thumbnail in thumbnails {
if let FrontendMessage::UpdateNodeThumbnail { id, value } = thumbnail {
document.layers_in_view.receive_thumbnail(id, value, responses);
match LayersInView::thumbnail_layer(&thumbnail) {
Some(layer) => document.layers_in_view.receive_thumbnail(layer, thumbnail, responses),
None => responses.add(thumbnail),
}
}
}
+19 -207
View File
@@ -1,7 +1,7 @@
use super::*;
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use crate::task::{Spawn, Spawner, Task};
use glam::{DAffine2, DVec2, UVec2};
use glam::{DVec2, UVec2};
use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::concrete;
@@ -11,24 +11,24 @@ use graph_craft::graphene_compiler::{CompiledNetwork, Compiler};
use graph_craft::proto::GraphErrors;
use graphene_hash::CacheHash;
use graphene_std::application_io::{ApplicationIo, ExportFormat, RenderConfig, Texture};
use graphene_std::bounds::RenderBoundingBox;
use graphene_std::list::{Item, List};
use graphene_std::memo::IORecord;
use graphene_std::ops::ConvertAsync;
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle};
use graphene_std::raster_types::Raster;
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender, SvgSegment};
use graphene_std::runtime::AsyncRuntime;
use graphene_std::transform::RenderQuality;
use graphene_std::vector::style::RenderMode;
use graphene_std::vector::{Vector, VectorGeometry, paths_from_list_row_attributes};
use graphene_std::{Artboard, Context, ContextFeatures, ContextOverrides, Graphic, NodeError, OwnedContextImpl, Poll};
use graphene_std::{Context, ContextFeatures, ContextOverrides, NodeError, OwnedContextImpl, Poll};
use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::util::wrap_network_in_scope;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Sender};
use thumbnails::Thumbnails;
mod thumbnails;
/// Persistent data between graph executions. It's updated via message passing from the editor thread with [`GraphRuntimeRequest`]`.
/// Some of these fields are put into a [`PlatformEditorApi`] which is passed to the final compiled graph network upon each execution.
@@ -53,17 +53,13 @@ pub struct NodeRuntime {
node_graph_errors: GraphErrors,
node_graph_warnings: GraphErrors,
monitor_nodes: Vec<(Vec<NodeId>, NodeId)>,
stale_thumbnails: HashSet<Vec<NodeId>>,
thumbnails_in_view: HashSet<NodeId>,
thumbnails: Thumbnails,
/// The node the Data panel inspects.
inspect_state: Option<InspectState>,
preprocessor: preprocessor::Preprocessor,
// TODO: Remove, it doesn't need to be persisted anymore
/// The current renders of the thumbnails for layer nodes.
thumbnail_renders: HashMap<NodeId, Vec<SvgSegment>>,
vector_modify: HashMap<NodeId, VectorGeometry>,
vector_evaluations: HashMap<NodeId, (NodeId, u64)>,
@@ -138,12 +134,10 @@ impl NodeRuntime {
node_graph_errors: Vec::new(),
node_graph_warnings: Vec::new(),
monitor_nodes: Vec::new(),
stale_thumbnails: HashSet::new(),
thumbnails_in_view: HashSet::new(),
thumbnails: Thumbnails::new(),
preprocessor: preprocessor::Preprocessor::new(),
thumbnail_renders: Default::default(),
vector_modify: Default::default(),
vector_evaluations: Default::default(),
inspect_state: None,
@@ -204,10 +198,10 @@ impl NodeRuntime {
// Without an execution to render them along with, the thumbnails that came into view are rendered on their own
if let Some((layers, document_id)) = thumbnails_in_view {
self.thumbnails_in_view = layers;
self.thumbnails.set_in_view(layers);
if execution.is_none() && graph.is_none() {
let mut responses = VecDeque::new();
self.render_stale_thumbnails(&mut responses);
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");
}
@@ -268,6 +262,7 @@ impl NodeRuntime {
}
GraphRuntimeRequest::ExecutionRequest(request @ ExecutionRequest { execution_id, mut render_config, .. }) => {
if !render_config.for_export && !render_config.for_eyedropper {
self.thumbnails.set_scale(render_config.scale, &self.monitor_nodes);
self.pending = Some(request);
}
if render_config.for_export {
@@ -315,7 +310,11 @@ impl NodeRuntime {
}
let mut responses = VecDeque::new();
let dropped_thumbnails = if !render_config.for_eyedropper { self.process_monitor_nodes(&mut responses) } else { Vec::new() };
let dropped_thumbnails = if !render_config.for_eyedropper {
self.process_monitor_nodes(&mut responses).await
} else {
Vec::new()
};
let inspect_result = self.inspect_state.as_mut().map(|state| state.access(&self.executor));
@@ -422,12 +421,7 @@ impl NodeRuntime {
.filter(|(_, node)| node.identifier == graphene_std::memo::monitor::IDENTIFIER)
.map(|(id, node)| (node.original_location.path.clone().unwrap_or_default(), *id))
.collect();
// A proto node's ID hashes everything upstream of it, so a monitor node whose ID stayed the same records the same output
let changed_monitors = self.monitor_nodes.iter().filter(|(path, id)| previous_monitor_ids.get(path) != Some(id));
self.stale_thumbnails.extend(changed_monitors.map(|(path, _)| path.clone()));
let current_monitors: HashSet<&Vec<NodeId>> = self.monitor_nodes.iter().map(|(path, _)| path).collect();
self.stale_thumbnails.retain(|path| current_monitors.contains(path));
self.thumbnails.update_monitors(&previous_monitor_ids, &self.monitor_nodes);
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
let result = self.executor.update(proto_network).map_err(|(types, e)| {
@@ -471,16 +465,8 @@ impl NodeRuntime {
}
/// Updates state data, giving back the layers whose thumbnails were dropped because they're no longer monitored.
fn process_monitor_nodes(&mut self, responses: &mut VecDeque<FrontendMessage>) -> Vec<NodeId> {
// TODO: Consider optimizing this since it's currently O(m*n^2), with a sort it could be made O(m * n*log(n))
let mut dropped_thumbnails = Vec::new();
self.thumbnail_renders.retain(|id, _| {
let monitored = self.monitor_nodes.iter().any(|(monitor_node_path, _)| monitor_node_path.contains(id));
if !monitored {
dropped_thumbnails.push(*id);
}
monitored
});
async fn process_monitor_nodes(&mut self, responses: &mut VecDeque<FrontendMessage>) -> Vec<NodeId> {
let dropped_thumbnails = self.thumbnails.drop_unmonitored(&self.monitor_nodes);
for (monitor_node_path, _) in &self.monitor_nodes {
let Some(parent_network_node_id) = monitor_parent_node(monitor_node_path) else {
@@ -513,108 +499,10 @@ impl NodeRuntime {
self.vector_evaluations.insert(parent_network_node_id, (content_node, context_hash));
}
self.render_stale_thumbnails(responses);
self.thumbnails.render_stale(&self.executor, &self.editor_api, responses).await;
dropped_thumbnails
}
/// Renders the thumbnails of the layers in view whose content changed since they were last rendered, keeping the others stale until they come into view.
fn render_stale_thumbnails(&mut self, responses: &mut VecDeque<FrontendMessage>) {
for monitor_node_path in std::mem::take(&mut self.stale_thumbnails) {
let Some(parent_network_node_id) = monitor_parent_node(&monitor_node_path) else { continue };
if records_vector(&self.executor, &monitor_node_path) {
continue;
}
if !self.thumbnails_in_view.contains(&parent_network_node_id) {
self.stale_thumbnails.insert(monitor_node_path);
continue;
}
match thumbnail_content(&self.executor, &monitor_node_path) {
// Text-aware bounds, since the `BoundingBox` trait can't lay out `Graphic::TextList` content
Some(ThumbnailContent::Graphics(graphics)) => {
let bounds = graphene_std::renderer::graphic_list_bounding_box(&graphics, DAffine2::IDENTITY);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &graphics, bounds, responses);
}
// Artboard thumbnail bounds come from the clipping rectangles, not the content union, since the renderer
// clips content to those rectangles so anything outside isn't visible
Some(ThumbnailContent::Artboards(artboards)) => {
let bounds = artboard_clip_bounds(&artboards);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &artboards, bounds, responses);
}
// Bounds need text layout, which the `BoundingBox` trait can't do for a bare `String`
Some(ThumbnailContent::Text(text)) => {
let bounds = graphene_std::renderer::text_list_bounding_box(&text, DAffine2::IDENTITY);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &text, bounds, responses);
}
// Content that isn't ready yet, or wasn't evaluated since the graph changed, is tried again on the next pass
None => {
self.stale_thumbnails.insert(monitor_node_path);
}
}
}
}
/// If this is `Graphic` data, regenerate click targets and thumbnails for the layers in the graph, modifying the state and updating the UI.
fn render_thumbnail(
thumbnail_renders: &mut HashMap<NodeId, Vec<SvgSegment>>,
parent_network_node_id: NodeId,
graphic: &impl Render,
bounds: RenderBoundingBox,
responses: &mut VecDeque<FrontendMessage>,
) {
// Skip thumbnails if the layer is too complex (for performance)
if graphic.render_complexity() > 1000 {
let old = thumbnail_renders.insert(parent_network_node_id, Vec::new());
if old.is_none_or(|v| !v.is_empty()) {
responses.push_back(FrontendMessage::UpdateNodeThumbnail {
id: parent_network_node_id,
value: "<svg viewBox=\"0 0 10 10\" data-tooltip-description=\"Dense thumbnail omitted for performance.\"><line x1=\"0\" y1=\"10\" x2=\"10\" y2=\"0\" stroke=\"red\" /></svg>"
.to_string(),
});
}
return;
}
// Fall back to a 1×1 rectangle if no caller offered finite bounds, then aspect-correct to the panel's 3:2 ratio
let raw_bounds = match bounds {
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => bounds,
_ => [DVec2::ZERO, DVec2::ONE],
};
let bounds = expand_to_thumbnail_aspect(raw_bounds);
let new_thumbnail_svg = {
let footprint = Footprint {
transform: DAffine2::from_translation(DVec2::new(bounds[0].x, bounds[0].y)),
resolution: UVec2::new((bounds[1].x - bounds[0].x).abs() as u32, (bounds[1].y - bounds[0].y).abs() as u32),
quality: RenderQuality::Full,
};
// Render the thumbnail from a `Graphic` into an SVG string
let render_params = RenderParams {
footprint,
thumbnail: true,
..Default::default()
};
let mut render = SvgRender::new();
graphic.render_svg(&mut render, &render_params);
// And give the SVG a viewbox and outer <svg>...</svg> wrapper tag
render.format_svg(bounds[0], bounds[1]);
render.svg
};
// Update frontend thumbnail
let old_thumbnail_svg = thumbnail_renders.entry(parent_network_node_id).or_default();
if old_thumbnail_svg != &new_thumbnail_svg {
responses.push_back(FrontendMessage::UpdateNodeThumbnail {
id: parent_network_node_id,
value: new_thumbnail_svg.to_svg_string(),
});
*old_thumbnail_svg = new_thumbnail_svg;
}
}
}
/// The layer a monitor node belongs to, since monitor nodes sit within the network of the document node they monitor.
@@ -660,82 +548,6 @@ fn context_hash(context: &Context) -> u64 {
std::hash::Hasher::finish(&hasher)
}
/// The time thumbnails are evaluated at, so they don't depend on the playhead.
const THUMBNAIL_TIME: f64 = 0.;
enum ThumbnailContent {
Graphics(List<Graphic>),
Artboards(List<Artboard>),
Text(List<String>),
}
/// Evaluates the content a monitor node watches again from its last context, normalized so thumbnails don't depend on the view or playhead.
fn thumbnail_content(executor: &DynamicExecutor, monitor_node_path: &[NodeId]) -> Option<ThumbnailContent> {
let tree = executor.tree();
let content_node = tree.input_node(monitor_node_path, 0).ok()?;
let context = tree.last_context(content_node).ok()??;
// Replacing a feature the content doesn't read would only miss its caches
let reads = tree.context_features(content_node);
let footprint = reads.contains(ContextFeatures::FOOTPRINT).then_some(Footprint::BOUNDLESS);
let time = reads.intersects(ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME).then_some(THUMBNAIL_TIME);
let normalized: Context = context.map(|context| Arc::new(context.with_replaced_footprint_and_time(footprint, time)));
let output = evaluated_output(tree.evaluate(content_node, &normalized).ok()?)?;
let content = if output.is::<List<Graphic>>() {
ThumbnailContent::Graphics(*output.downcast().ok()?)
} else if output.is::<Item<Graphic>>() {
ThumbnailContent::Graphics(List::new_from_item(*output.downcast().ok()?))
} else if output.is::<List<Artboard>>() {
ThumbnailContent::Artboards(*output.downcast().ok()?)
} else if output.is::<Item<Artboard>>() {
ThumbnailContent::Artboards(List::new_from_item(*output.downcast().ok()?))
} else if output.is::<List<String>>() {
ThumbnailContent::Text(*output.downcast().ok()?)
} else if output.is::<Item<String>>() {
ThumbnailContent::Text(List::new_from_item(*output.downcast().ok()?))
} else {
log::warn!("Failed to downcast the content of monitor node {monitor_node_path:?} for its thumbnail");
return None;
};
Some(content)
}
/// Returns the union of the artboards' clipping rectangles, used as the thumbnail bounds for an artboard layer so the
/// framing matches what's actually visible after clipping rather than the unclipped content extents.
fn artboard_clip_bounds(artboards: &List<Artboard>) -> RenderBoundingBox {
let mut combined: Option<[DVec2; 2]> = None;
for index in 0..artboards.len() {
let location: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_LOCATION, index);
let dimensions: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_DIMENSIONS, index);
let bounds = [location, location + dimensions];
combined = Some(match combined {
Some(existing) => [existing[0].min(bounds[0]), existing[1].max(bounds[1])],
None => bounds,
});
}
match combined {
Some(bounds) => RenderBoundingBox::Rectangle(bounds),
None => RenderBoundingBox::None,
}
}
/// Expands an AABB outward (centered) to match the Layers panel thumbnail's 3:2 aspect ratio, padding the smaller axis
/// so the input's extent is always preserved.
fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
const THUMBNAIL_ASPECT_RATIO: f64 = 1.5;
let size = bounds[1] - bounds[0];
let center = (bounds[0] + bounds[1]) / 2.;
let (width, height) = if size.x >= size.y * THUMBNAIL_ASPECT_RATIO {
(size.x, size.x / THUMBNAIL_ASPECT_RATIO)
} else {
(size.y * THUMBNAIL_ASPECT_RATIO, size.y)
};
let half = DVec2::new(width, height) / 2.;
[center - half, center + half]
}
impl NodeRuntime {
pub(crate) fn replace_application_io(&mut self, application_io: PlatformApplicationIo) {
self.editor_api = PlatformEditorApi {
@@ -0,0 +1,395 @@
use super::{evaluated_output, monitor_parent_node, records_vector};
use crate::messages::frontend::FrontendMessage;
#[cfg(feature = "gpu")]
use atlas::ThumbnailAtlasLayout;
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::document::NodeId;
#[cfg(feature = "gpu")]
use graphene_std::application_io::{ApplicationIo, Texture};
use graphene_std::bounds::RenderBoundingBox;
use graphene_std::list::{Item, List};
#[cfg(feature = "gpu")]
use graphene_std::ops::ConvertAsync;
#[cfg(all(target_family = "wasm", feature = "wasm"))]
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasHandle};
#[cfg(feature = "gpu")]
use graphene_std::raster_types::Raster;
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
use graphene_std::transform::{Footprint, RenderQuality};
use graphene_std::{Artboard, Context, ContextFeatures, Graphic};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::Arc;
#[cfg(feature = "gpu")]
mod atlas;
/// The time thumbnails are evaluated at, so they don't depend on the playhead.
const THUMBNAIL_TIME: f64 = 0.;
/// The size in pixels of a thumbnail rendered at this device pixel ratio.
#[cfg_attr(
not(any(feature = "gpu", all(target_family = "wasm", feature = "wasm"))),
expect(dead_code, reason = "Only thumbnails rendered with Vello or drawn into canvases have a fixed size")
)]
fn cell_size(scale: f64) -> UVec2 {
/// The size thumbnails are shown at in the node graph, in CSS pixels.
const CELL_SIZE: DVec2 = DVec2::new(72., 48.);
(CELL_SIZE * scale).round().as_uvec2().max(UVec2::ONE)
}
/// The thumbnails of the layers, rendered from the content their monitor nodes watch when it changes while they're in view.
#[derive(Default)]
pub struct Thumbnails {
/// The monitor nodes whose content changed since their layer's thumbnail was last rendered.
stale: HashSet<Vec<NodeId>>,
/// The layers whose thumbnails the frontend shows, the only ones rendered.
in_view: HashSet<NodeId>,
/// The device pixel ratio thumbnails are rendered at.
scale: f64,
#[cfg(all(target_family = "wasm", feature = "wasm"))]
canvases: HashMap<NodeId, ThumbnailCanvases>,
/// The layers whose thumbnails were sent to a page that can't show the runtime's canvases.
#[cfg(not(all(target_family = "wasm", feature = "wasm")))]
sent: HashSet<NodeId>,
}
/// A layer's thumbnail is shown in both the Layers panel and the node graph, but a canvas element can only be in one place.
#[cfg(all(target_family = "wasm", feature = "wasm"))]
struct ThumbnailCanvases {
layers_panel: CanvasHandle,
node_graph: CanvasHandle,
}
impl Thumbnails {
pub fn new() -> Self {
Self { scale: 1., ..Default::default() }
}
pub fn set_in_view(&mut self, layers: HashSet<NodeId>) {
self.in_view = layers;
}
/// Thumbnails rendered at another device pixel ratio are rendered again.
pub fn set_scale(&mut self, scale: f64, monitor_nodes: &[(Vec<NodeId>, NodeId)]) {
if scale != self.scale {
self.stale.extend(monitor_nodes.iter().map(|(path, _)| path.clone()));
}
self.scale = scale;
}
/// Marks the thumbnails of the monitor nodes whose proto node ID changed as stale.
pub fn update_monitors(&mut self, previous_monitor_ids: &HashMap<Vec<NodeId>, NodeId>, monitor_nodes: &[(Vec<NodeId>, NodeId)]) {
// A proto node's ID hashes everything upstream of it, so a monitor node whose ID stayed the same records the same output
let changed_monitors = monitor_nodes.iter().filter(|(path, id)| previous_monitor_ids.get(path) != Some(id));
self.stale.extend(changed_monitors.map(|(path, _)| path.clone()));
let current_monitors: HashSet<&Vec<NodeId>> = monitor_nodes.iter().map(|(path, _)| path).collect();
self.stale.retain(|path| current_monitors.contains(path));
}
/// Forgets the thumbnails of the layers no longer monitored, giving them back so the frontend can clear them.
pub fn drop_unmonitored(&mut self, monitor_nodes: &[(Vec<NodeId>, NodeId)]) -> Vec<NodeId> {
// TODO: Consider optimizing this since it's currently O(m*n^2), with a sort it could be made O(m * n*log(n))
let mut dropped = Vec::new();
let mut keep_monitored = |id: &NodeId| {
let monitored = monitor_nodes.iter().any(|(monitor_node_path, _)| monitor_node_path.contains(id));
if !monitored && !dropped.contains(id) {
dropped.push(*id);
}
monitored
};
#[cfg(all(target_family = "wasm", feature = "wasm"))]
self.canvases.retain(|id, _| keep_monitored(id));
#[cfg(not(all(target_family = "wasm", feature = "wasm")))]
self.sent.retain(|id| keep_monitored(id));
dropped
}
/// Renders the thumbnails of the layers in view whose content changed since they were last rendered, keeping the others stale until they come into view.
pub async fn render_stale(&mut self, executor: &DynamicExecutor, editor_api: &PlatformEditorApi, responses: &mut VecDeque<FrontendMessage>) {
let mut contents = HashMap::new();
for monitor_node_path in std::mem::take(&mut self.stale) {
let Some(layer) = monitor_parent_node(&monitor_node_path) else { continue };
if records_vector(executor, &monitor_node_path) {
continue;
}
if !self.in_view.contains(&layer) {
self.stale.insert(monitor_node_path);
continue;
}
let Some(content) = ThumbnailContent::evaluate(executor, &monitor_node_path) else {
self.stale.insert(monitor_node_path);
continue;
};
contents.insert(layer, content);
}
if contents.is_empty() {
return;
}
if !self.render_with_vello(&contents, editor_api, responses).await {
for (layer, content) in &contents {
self.render_svg(*layer, content, responses).await;
}
}
}
/// Renders the thumbnails into atlases with Vello and shows them, giving false if Vello is unavailable.
#[cfg(feature = "gpu")]
async fn render_with_vello(&mut self, contents: &HashMap<NodeId, ThumbnailContent>, editor_api: &PlatformEditorApi, responses: &mut VecDeque<FrontendMessage>) -> bool {
let Some(executor) = editor_api.application_io.as_ref().and_then(|application_io| application_io.gpu_executor()) else {
return false;
};
let mut layers = contents.keys().copied().collect::<Vec<_>>();
layers.sort_unstable();
let max_texture_size = executor.context().device.limits().max_texture_dimension_2d;
let cells_per_atlas = atlas::max_cells_per_atlas(cell_size(self.scale), max_texture_size);
for layers in layers.chunks(cells_per_atlas) {
let layout = ThumbnailAtlasLayout::new(layers.to_vec(), self.scale);
let texture = executor.vello_scene(layout.size(), DAffine2::IDENTITY).and_then(|mut scene| {
atlas::draw_atlas(&mut scene, &layout, contents);
executor.render_vello_scene(scene)
});
let texture = match texture {
Ok(texture) => texture,
Err(error) => {
log::error!("Failed to render the thumbnails of layers {layers:?}: {error}");
return false;
}
};
self.show_atlas(&layout, texture, executor, responses).await;
}
true
}
#[cfg(not(feature = "gpu"))]
async fn render_with_vello(&mut self, _contents: &HashMap<NodeId, ThumbnailContent>, _editor_api: &PlatformEditorApi, _responses: &mut VecDeque<FrontendMessage>) -> bool {
false
}
/// Reads the atlas back and draws each cell into the canvases the layer's rows show.
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
async fn show_atlas(&mut self, layout: &ThumbnailAtlasLayout, atlas: Texture, executor: &wgpu_executor::WgpuExecutor, responses: &mut VecDeque<FrontendMessage>) {
let raster = Raster::new_gpu(atlas).convert(Footprint::BOUNDLESS, executor.clone()).await;
let (pixels, _, _) = raster.to_flat_u8();
for (index, &layer) in layout.layers.iter().enumerate() {
let cell_pixels = layout.cell_pixels(&pixels, index);
let Ok(image) = web_sys::ImageData::new_with_u8_clamped_array_and_sh(wasm_bindgen::Clamped(&cell_pixels), layout.cell_size.x, layout.cell_size.y) else {
continue;
};
let canvases = self.canvases(layer);
for canvas in [&mut canvases.layers_panel, &mut canvases.node_graph] {
canvas.set_resolution(layout.cell_size);
let _ = canvas.context().put_image_data(&image, 0, 0);
}
responses.push_back(canvases.update_message(layer));
}
}
/// Reads the atlas back for a page that can't show the runtime's canvases, like the desktop app's, and sends each layer its cell's pixels.
#[cfg(all(feature = "gpu", not(all(target_family = "wasm", feature = "wasm"))))]
async fn show_atlas(&mut self, layout: &ThumbnailAtlasLayout, atlas: Texture, executor: &wgpu_executor::WgpuExecutor, responses: &mut VecDeque<FrontendMessage>) {
let raster = Raster::new_gpu(atlas).convert(Footprint::BOUNDLESS, executor.clone()).await;
let (pixels, _, _) = raster.to_flat_u8();
for (index, &layer) in layout.layers.iter().enumerate() {
self.sent.insert(layer);
responses.push_back(FrontendMessage::UpdateNodeThumbnailPixels {
id: layer,
width: layout.cell_size.x,
height: layout.cell_size.y,
pixels: atlas::encode_transparent_runs(&layout.cell_pixels(&pixels, index)).into(),
});
}
}
async fn render_svg(&mut self, layer: NodeId, content: &ThumbnailContent, responses: &mut VecDeque<FrontendMessage>) {
let bounds = content.bounds();
let footprint = Footprint {
transform: DAffine2::from_translation(bounds[0]),
resolution: (bounds[1] - bounds[0]).abs().as_uvec2(),
quality: RenderQuality::Full,
};
let render_params = RenderParams {
footprint,
thumbnail: true,
..Default::default()
};
let mut render = SvgRender::new();
content.graphic().render_svg(&mut render, &render_params);
render.format_svg(bounds[0], bounds[1]);
self.show_svg(layer, render.svg.to_svg_string(), responses).await;
}
/// Draws the SVG into the canvases the layer's rows show, so the browser rasterizes it once rather than keeping it in the page.
#[cfg(all(target_family = "wasm", feature = "wasm"))]
async fn show_svg(&mut self, layer: NodeId, svg: String, responses: &mut VecDeque<FrontendMessage>) {
use base64::Engine;
let size = cell_size(self.scale);
// An SVG drawn as an image needs an intrinsic size, which the thumbnail's only gives as a view box
let svg = svg.replacen("<svg ", &format!("<svg width=\"{}\" height=\"{}\" ", size.x, size.y), 1);
let mut url = String::from("data:image/svg+xml;base64,");
base64::engine::general_purpose::STANDARD.encode_string(svg, &mut url);
let Ok(image) = web_sys::HtmlImageElement::new() else { return };
image.set_src(&url);
if let Err(error) = wasm_bindgen_futures::JsFuture::from(image.decode()).await {
log::error!("Failed to decode the thumbnail of layer {layer:?}: {error:?}");
return;
}
let canvases = self.canvases(layer);
for canvas in [&mut canvases.layers_panel, &mut canvases.node_graph] {
canvas.set_resolution(size);
let context = canvas.context();
context.clear_rect(0., 0., size.x as f64, size.y as f64);
let _ = context.draw_image_with_html_image_element_and_dw_and_dh(&image, 0., 0., size.x as f64, size.y as f64);
}
responses.push_back(canvases.update_message(layer));
}
#[cfg(not(all(target_family = "wasm", feature = "wasm")))]
async fn show_svg(&mut self, layer: NodeId, svg: String, responses: &mut VecDeque<FrontendMessage>) {
self.sent.insert(layer);
responses.push_back(FrontendMessage::UpdateNodeThumbnail { id: layer, value: svg });
}
#[cfg(all(target_family = "wasm", feature = "wasm"))]
fn canvases(&mut self, layer: NodeId) -> &mut ThumbnailCanvases {
self.canvases.entry(layer).or_insert_with(|| ThumbnailCanvases {
layers_panel: CanvasHandle::new(),
node_graph: CanvasHandle::new(),
})
}
}
#[cfg(all(target_family = "wasm", feature = "wasm"))]
impl ThumbnailCanvases {
fn update_message(&mut self, layer: NodeId) -> FrontendMessage {
FrontendMessage::UpdateNodeThumbnailCanvases {
id: layer,
layers_panel_canvas_id: self.layers_panel.id(),
node_graph_canvas_id: self.node_graph.id(),
}
}
}
enum ThumbnailContent {
Graphics(List<Graphic>),
Artboards(List<Artboard>),
Text(List<String>),
}
impl ThumbnailContent {
/// Evaluates the content a monitor node watches again from its last context, normalized so thumbnails don't depend on the view or playhead.
fn evaluate(executor: &DynamicExecutor, monitor_node_path: &[NodeId]) -> Option<Self> {
let tree = executor.tree();
let content_node = tree.input_node(monitor_node_path, 0).ok()?;
let context = tree.last_context(content_node).ok()??;
// Replacing a feature the content doesn't read would only miss its caches
let reads = tree.context_features(content_node);
let footprint = reads.contains(ContextFeatures::FOOTPRINT).then_some(Footprint::BOUNDLESS);
let time = reads.intersects(ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME).then_some(THUMBNAIL_TIME);
let normalized: Context = context.map(|context| Arc::new(context.with_replaced_footprint_and_time(footprint, time)));
let output = evaluated_output(tree.evaluate(content_node, &normalized).ok()?)?;
let content = if output.is::<List<Graphic>>() {
Self::Graphics(*output.downcast().ok()?)
} else if output.is::<Item<Graphic>>() {
Self::Graphics(List::new_from_item(*output.downcast().ok()?))
} else if output.is::<List<Artboard>>() {
Self::Artboards(*output.downcast().ok()?)
} else if output.is::<Item<Artboard>>() {
Self::Artboards(List::new_from_item(*output.downcast().ok()?))
} else if output.is::<List<String>>() {
Self::Text(*output.downcast().ok()?)
} else if output.is::<Item<String>>() {
Self::Text(List::new_from_item(*output.downcast().ok()?))
} else {
log::warn!("Failed to downcast the content of monitor node {monitor_node_path:?} for its thumbnail");
return None;
};
Some(content)
}
fn graphic(&self) -> &dyn Render {
match self {
Self::Graphics(graphics) => graphics,
Self::Artboards(artboards) => artboards,
Self::Text(text) => text,
}
}
/// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio.
fn bounds(&self) -> [DVec2; 2] {
let bounds = match self {
// Text-aware bounds, since the `BoundingBox` trait can't lay out `Graphic::TextList` content
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_bounding_box(graphics, DAffine2::IDENTITY),
// The clipping rectangles rather than the content, since the renderer clips content to them
Self::Artboards(artboards) => artboard_clip_bounds(artboards),
Self::Text(text) => graphene_std::renderer::text_list_bounding_box(text, DAffine2::IDENTITY),
};
let bounds = match bounds {
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => bounds,
_ => [DVec2::ZERO, DVec2::ONE],
};
expand_to_thumbnail_aspect(bounds)
}
}
/// Returns the union of the artboards' clipping rectangles, used as the thumbnail bounds for an artboard layer so the
/// framing matches what's actually visible after clipping rather than the unclipped content extents.
fn artboard_clip_bounds(artboards: &List<Artboard>) -> RenderBoundingBox {
let mut combined: Option<[DVec2; 2]> = None;
for index in 0..artboards.len() {
let location: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_LOCATION, index);
let dimensions: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_DIMENSIONS, index);
let bounds = [location, location + dimensions];
combined = Some(match combined {
Some(existing) => [existing[0].min(bounds[0]), existing[1].max(bounds[1])],
None => bounds,
});
}
match combined {
Some(bounds) => RenderBoundingBox::Rectangle(bounds),
None => RenderBoundingBox::None,
}
}
/// Expands an AABB outward (centered) to match the Layers panel thumbnail's 3:2 aspect ratio, padding the smaller axis
/// so the input's extent is always preserved.
fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
const THUMBNAIL_ASPECT_RATIO: f64 = 1.5;
let size = bounds[1] - bounds[0];
let center = (bounds[0] + bounds[1]) / 2.;
let (width, height) = if size.x >= size.y * THUMBNAIL_ASPECT_RATIO {
(size.x, size.x / THUMBNAIL_ASPECT_RATIO)
} else {
(size.y * THUMBNAIL_ASPECT_RATIO, size.y)
};
let half = DVec2::new(width, height) / 2.;
[center - half, center + half]
}
@@ -0,0 +1,138 @@
use super::{ThumbnailContent, cell_size};
use glam::{DAffine2, UVec2};
use graph_craft::document::NodeId;
use graphene_std::renderer::vello_scene_builder::VelloSceneBuilder;
use graphene_std::renderer::{RenderOutputType, RenderParams};
use graphene_std::transform::Footprint;
use std::collections::HashMap;
use vello_gpu::kurbo::{Affine, Rect};
use vello_gpu::peniko::Fill;
/// The most cells an atlas can hold within the maximum texture size, since its rows are at most as many as its columns.
pub fn max_cells_per_atlas(cell_size: UVec2, max_texture_size: u32) -> usize {
let columns = (max_texture_size / cell_size.max_element()).max(1) as usize;
columns * columns
}
/// The thumbnails of the layers in view, in equally sized cells filling the atlas row by row.
pub struct ThumbnailAtlasLayout {
pub cell_size: UVec2,
columns: u32,
pub layers: Vec<NodeId>,
}
impl ThumbnailAtlasLayout {
pub fn new(layers: Vec<NodeId>, scale: f64) -> Self {
let columns = (layers.len() as f64).sqrt().ceil().max(1.) as u32;
Self {
cell_size: cell_size(scale),
columns,
layers,
}
}
pub fn size(&self) -> UVec2 {
let rows = (self.layers.len() as u32).div_ceil(self.columns).max(1);
UVec2::new(self.columns, rows) * self.cell_size
}
pub fn cell_origin(&self, index: usize) -> UVec2 {
let index = index as u32;
UVec2::new(index % self.columns, index / self.columns) * self.cell_size
}
pub fn cell_pixels(&self, atlas_pixels: &[u8], index: usize) -> Vec<u8> {
let atlas_row_length = self.size().x as usize * 4;
let row_length = self.cell_size.x as usize * 4;
let origin = self.cell_origin(index).as_usizevec2();
(origin.y..origin.y + self.cell_size.y as usize)
.filter_map(|row| {
let start = row * atlas_row_length + origin.x * 4;
atlas_pixels.get(start..start + row_length)
})
.flatten()
.copied()
.collect()
}
}
/// Draws the content of each layer in the layout centered within its cell.
pub fn draw_atlas(scene: &mut VelloSceneBuilder, layout: &ThumbnailAtlasLayout, contents: &HashMap<NodeId, ThumbnailContent>) {
let render_params = RenderParams {
footprint: Footprint::BOUNDLESS,
render_output_type: RenderOutputType::Vello,
thumbnail: true,
..Default::default()
};
let cell_size = layout.cell_size.as_dvec2();
for (index, layer) in layout.layers.iter().enumerate() {
let Some(content) = contents.get(layer) else { continue };
let origin = layout.cell_origin(index).as_dvec2();
let [min, max] = content.bounds();
let transform = DAffine2::from_translation(origin) * DAffine2::from_scale(cell_size / (max - min)) * DAffine2::from_translation(-min);
// The clip also limits content filling the whole scene, like a background, to the cell
let cell = Rect::new(origin.x, origin.y, origin.x + cell_size.x, origin.y + cell_size.y);
scene.push_clip_layer(Fill::NonZero, Affine::IDENTITY, &cell);
content.graphic().render_to_vello(scene, transform, &render_params);
scene.pop_layer();
}
}
/// The RGBA pixels with runs of fully transparent ones left out, which most of a thumbnail's margins are.
/// Encoded as pairs of little-endian `u32` counts of skipped and kept pixels, each pair followed by the kept pixels' bytes.
#[cfg(not(all(target_family = "wasm", feature = "wasm")))]
pub fn encode_transparent_runs(pixels: &[u8]) -> Vec<u8> {
let (pixels, _) = pixels.as_chunks::<4>();
let mut encoded = Vec::new();
let mut index = 0;
while index < pixels.len() {
let skipped = pixels[index..].iter().take_while(|pixel| pixel[3] == 0).count();
let kept_start = index + skipped;
let kept = pixels[kept_start..].iter().take_while(|pixel| pixel[3] != 0).count();
encoded.extend_from_slice(&(skipped as u32).to_le_bytes());
encoded.extend_from_slice(&(kept as u32).to_le_bytes());
for pixel in &pixels[kept_start..kept_start + kept] {
encoded.extend_from_slice(pixel);
}
index = kept_start + kept;
}
encoded
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn a_cell_is_copied_out_of_the_atlas_row_by_row() {
let layout = ThumbnailAtlasLayout {
cell_size: UVec2::new(1, 2),
columns: 2,
layers: vec![NodeId(1), NodeId(2)],
};
// Each pixel's red channel numbers it in reading order
let atlas_pixels = (0..4).flat_map(|pixel| [pixel, 0, 0, 255]).collect::<Vec<u8>>();
assert_eq!(layout.cell_pixels(&atlas_pixels, 1), [[1, 0, 0, 255], [3, 0, 0, 255]].concat());
}
#[test]
fn transparent_runs_are_left_out_and_opaque_pixels_kept() {
let transparent = [9, 9, 9, 0];
let red = [255, 0, 0, 255];
let pixels = [transparent, transparent, red, red, transparent, red].concat();
let pair = |skipped: u32, kept: u32| [skipped.to_le_bytes(), kept.to_le_bytes()].concat();
let expected = [pair(2, 2), red.to_vec(), red.to_vec(), pair(1, 1), red.to_vec()].concat();
assert_eq!(encode_transparent_runs(&pixels), expected);
}
}
+9 -3
View File
@@ -2,6 +2,8 @@
import { getContext, onMount, onDestroy, tick } from "svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import ThumbnailCanvas from "/src/components/views/ThumbnailCanvas.svelte";
import ThumbnailImage from "/src/components/views/ThumbnailImage.svelte";
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
@@ -87,6 +89,7 @@
const editor = getContext<EditorWrapper>("editor");
const nodeGraph = getContext<NodeGraphStore>("nodeGraph");
const thumbnailImages = nodeGraph.thumbnailImagesStore;
const tooltip = getContext<TooltipStore>("tooltip");
const portfolio = getContext<PortfolioStore>("portfolio");
@@ -1228,8 +1231,10 @@
/>
{/if}
<div class="thumbnail">
{#if $nodeGraph.thumbnails.has(listing.id)}
{@html $nodeGraph.thumbnails.get(listing.id)}
{#if $nodeGraph.thumbnailCanvases.has(listing.id)}
<ThumbnailCanvas canvasId={$nodeGraph.thumbnailCanvases.get(listing.id)?.layersPanelCanvasId} />
{:else if $thumbnailImages.has(listing.id)}
<ThumbnailImage image={$thumbnailImages.get(listing.id)} />
{/if}
</div>
<div class="layer-name-and-chain" class:editing={listing.editingName} style:--chain-width={`${chainFullWidth(inlineSlots.length, slots.length > 0)}px`}>
@@ -1661,7 +1666,8 @@
background-position: var(--color-transparent-checkered-background-position-mini);
background-repeat: var(--color-transparent-checkered-background-repeat);
svg {
canvas {
display: block;
width: 100%;
height: 100%;
}
+8 -3
View File
@@ -5,6 +5,8 @@
import NodeCatalog from "/src/components/floating-menus/NodeCatalog.svelte";
import FloatingMenu from "/src/components/layout/FloatingMenu.svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import ThumbnailCanvas from "/src/components/views/ThumbnailCanvas.svelte";
import ThumbnailImage from "/src/components/views/ThumbnailImage.svelte";
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
import TextButton from "/src/components/widgets/buttons/TextButton.svelte";
import TextAreaInput from "/src/components/widgets/inputs/TextAreaInput.svelte";
@@ -26,6 +28,7 @@
const nodeGraphTransform = nodeGraph.transformStore;
const nodeGraphImportsExports = nodeGraph.importsExportsStore;
const visibleNodes = nodeGraph.visibleNodesStore;
const thumbnailImages = nodeGraph.thumbnailImagesStore;
const nodeGraphWires = nodeGraph.wiresStore;
const wireInsertionPreview = nodeGraph.wireInsertionPreviewStore;
const nodeGlideOffsets = nodeGraph.glideOffsetsStore;
@@ -800,8 +803,10 @@
data-node={node.id}
>
<div class="thumbnail">
{#if $nodeGraph.thumbnails.has(node.id)}
{@html $nodeGraph.thumbnails.get(node.id)}
{#if $nodeGraph.thumbnailCanvases.has(node.id)}
<ThumbnailCanvas canvasId={$nodeGraph.thumbnailCanvases.get(node.id)?.nodeGraphCanvasId} />
{:else if $thumbnailImages.has(node.id)}
<ThumbnailImage image={$thumbnailImages.get(node.id)} />
{/if}
<!-- Layer stacking top output -->
{#if node.primaryOutput}
@@ -1572,7 +1577,7 @@
}
&::before,
svg:not(.connector) {
canvas {
pointer-events: none;
position: absolute;
margin: auto;
@@ -0,0 +1,18 @@
<script lang="ts">
import { afterUpdate } from "svelte";
export let canvasId: number | undefined;
let container: HTMLDivElement | undefined;
// The graph runtime draws the thumbnail into this canvas, which is moved here rather than copied
afterUpdate(() => {
const canvas = canvasId !== undefined ? window.imageCanvases[String(canvasId)] : undefined;
if (!container || !canvas || canvas.parentElement === container) return;
// eslint-disable-next-line svelte/no-dom-manipulating
container.replaceChildren(canvas);
});
</script>
<div bind:this={container} style:display="contents"></div>
@@ -0,0 +1,14 @@
<script lang="ts">
import { afterUpdate } from "svelte";
export let image: ImageData | undefined;
let canvas: HTMLCanvasElement | undefined;
// After the update, since resizing the canvas clears it
afterUpdate(() => {
if (image) canvas?.getContext("2d")?.putImageData(image, 0, 0);
});
</script>
<canvas bind:this={canvas} width={image?.width} height={image?.height}></canvas>
+49 -8
View File
@@ -1,4 +1,4 @@
import { writable } from "svelte/store";
import { get, writable } from "svelte/store";
import type { Writable } from "svelte/store";
import type { IconName } from "/src/icons";
import type { SubscriptionsRouter } from "/src/subscriptions-router";
@@ -9,6 +9,8 @@ export type NodeGraphStore = ReturnType<typeof createNodeGraphStore>;
export type NodeGraphTransform = { scale: number; x: number; y: number };
export type ThumbnailCanvases = { layersPanelCanvasId: number; nodeGraphCanvasId: number };
type NodeGraphStoreState = {
box: BoxSelection | undefined;
clickTargets: FrontendClickTargets | undefined;
@@ -25,7 +27,7 @@ type NodeGraphStoreState = {
nodeDescriptions: Map<string, string>;
nodeIcons: Map<string, IconName>;
nodeTypes: FrontendNodeType[];
thumbnails: Map<bigint, string>;
thumbnailCanvases: Map<bigint, ThumbnailCanvases>;
selected: bigint[];
inSelectedNetwork: boolean;
reorderImportIndex: number | undefined;
@@ -47,7 +49,7 @@ const initialState: NodeGraphStoreState = {
nodeDescriptions: new Map(),
nodeIcons: new Map(),
nodeTypes: [],
thumbnails: new Map(),
thumbnailCanvases: new Map(),
selected: [],
inSelectedNetwork: true,
reorderImportIndex: undefined,
@@ -56,6 +58,26 @@ const initialState: NodeGraphStoreState = {
let subscriptionsRouter: SubscriptionsRouter | undefined = undefined;
// Undoes the graph runtime's encoding of thumbnail pixels: pairs of little-endian u32 counts of skipped transparent pixels and kept pixels, each followed by the kept pixels' RGBA bytes
function decodeTransparentRuns(encoded: Uint8Array, width: number, height: number): ImageData {
const pixels = new Uint8ClampedArray(width * height * 4);
const view = new DataView(encoded.buffer, encoded.byteOffset, encoded.byteLength);
let read = 0;
let pixel = 0;
while (read + 8 <= encoded.byteLength) {
pixel += view.getUint32(read, true);
const kept = view.getUint32(read + 4, true);
read += 8;
pixels.set(encoded.subarray(read, read + kept * 4), pixel * 4);
read += kept * 4;
pixel += kept;
}
return new ImageData(pixels, width, height);
}
// Store state persisted across HMR to maintain reactive subscriptions in the component tree
const store: Writable<NodeGraphStoreState> = import.meta.hot?.data?.store || writable<NodeGraphStoreState>(initialState);
if (import.meta.hot) import.meta.hot.data.store = store;
@@ -69,6 +91,10 @@ if (import.meta.hot) import.meta.hot.data.transformStore = transformStore;
const importsExportsStore: Writable<MessageBody<"UpdateImportsExports"> | undefined> = import.meta.hot?.data?.importsExportsStore || writable(undefined);
if (import.meta.hot) import.meta.hot.data.importsExportsStore = importsExportsStore;
// Kept apart from the node graph state so a thumbnail update doesn't re-render every node
const thumbnailImagesStore: Writable<Map<bigint, ImageData>> = import.meta.hot?.data?.thumbnailImagesStore || writable(new Map());
if (import.meta.hot) import.meta.hot.data.thumbnailImagesStore = thumbnailImagesStore;
// Separate visible nodes store so viewport culling changes don't trigger full node re-renders
const visibleNodesStore: Writable<Set<bigint>> = import.meta.hot?.data?.visibleNodesStore || writable(new Set());
if (import.meta.hot) import.meta.hot.data.visibleNodesStore = visibleNodesStore;
@@ -243,18 +269,32 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
transformStore.set({ scale: data.scale, x: data.translation[0], y: data.translation[1] });
});
subscriptions.subscribeFrontendMessage("UpdateNodeThumbnail", (data) => {
subscriptions.subscribeFrontendMessage("UpdateNodeThumbnailCanvases", (data) => {
const { id, ...canvases } = data;
const current = get(store).thumbnailCanvases.get(id);
if (current?.layersPanelCanvasId === canvases.layersPanelCanvasId && current?.nodeGraphCanvasId === canvases.nodeGraphCanvasId) return;
update((state) => {
state.thumbnails.set(data.id, data.value);
state.thumbnailCanvases.set(id, canvases);
return state;
});
});
subscriptions.subscribeFrontendMessage("UpdateNodeThumbnailPixels", (data) => {
const image = decodeTransparentRuns(data.pixels, data.width, data.height);
thumbnailImagesStore.update((images) => images.set(data.id, image));
});
subscriptions.subscribeFrontendMessage("ClearNodeThumbnails", (data) => {
update((state) => {
data.ids.forEach((id) => state.thumbnails.delete(id));
data.ids.forEach((id) => state.thumbnailCanvases.delete(id));
return state;
});
thumbnailImagesStore.update((images) => {
data.ids.forEach((id) => images.delete(id));
return images;
});
});
subscriptions.subscribeFrontendMessage("UpdateWirePathInProgress", (data) => {
@@ -266,7 +306,7 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
});
});
return { subscribe, transformStore, importsExportsStore, visibleNodesStore, wiresStore, wireInsertionPreviewStore, glideOffsetsStore };
return { subscribe, transformStore, importsExportsStore, visibleNodesStore, thumbnailImagesStore, wiresStore, wireInsertionPreviewStore, glideOffsetsStore };
}
export function destroyNodeGraphStore() {
@@ -292,7 +332,8 @@ export function destroyNodeGraphStore() {
subscriptions.unsubscribeFrontendMessage("ClearAllNodeGraphWires");
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphSelection");
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphTransform");
subscriptions.unsubscribeFrontendMessage("UpdateNodeThumbnail");
subscriptions.unsubscribeFrontendMessage("UpdateNodeThumbnailCanvases");
subscriptions.unsubscribeFrontendMessage("UpdateNodeThumbnailPixels");
subscriptions.unsubscribeFrontendMessage("ClearNodeThumbnails");
subscriptions.unsubscribeFrontendMessage("UpdateWirePathInProgress");
}
@@ -3,7 +3,6 @@ pub use cache::BrushCache;
use core_types::CacheHash;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::render_complexity::RenderComplexity;
use dyn_any::DynAny;
use glam::{DAffine2, DVec2, Vec2};
use std::f32::consts::{PI, TAU};
@@ -118,12 +117,6 @@ impl BoundingBox for Stroke {
}
}
impl RenderComplexity for Stroke {
fn render_complexity(&self) -> usize {
self.len()
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Sample {
pub position: DVec2,
@@ -13,7 +13,6 @@ pub mod none;
pub mod ops;
pub mod poll;
pub mod registry;
pub mod render_complexity;
pub mod runtime;
pub mod transfer_curve;
pub mod transform;
@@ -1,50 +0,0 @@
// Raster types moved to raster-types crate
use crate::Color;
use crate::list::{Item, List};
pub trait RenderComplexity {
fn render_complexity(&self) -> usize {
0
}
/// The complexity of an item's element. A type with content that partly rides its item's attributes overrides
/// this to read them, and the rest defer to the element alone.
fn render_complexity_in_item(item: &Item<Self>) -> usize
where
Self: Sized,
{
item.element().render_complexity()
}
/// As [`Self::render_complexity_in_item`], for the element at one index of a list.
fn render_complexity_in_list(list: &List<Self>, index: usize) -> usize
where
Self: Sized,
{
list.element(index).map_or(0, Self::render_complexity)
}
}
impl<T: RenderComplexity> RenderComplexity for Item<T> {
fn render_complexity(&self) -> usize {
T::render_complexity_in_item(self)
}
}
impl<T: RenderComplexity> RenderComplexity for List<T> {
fn render_complexity(&self) -> usize {
(0..self.len()).map(|index| T::render_complexity_in_list(self, index)).fold(0, usize::saturating_add)
}
}
impl RenderComplexity for Color {
fn render_complexity(&self) -> usize {
1
}
}
impl RenderComplexity for String {
fn render_complexity(&self) -> usize {
self.chars().count()
}
}
@@ -2,7 +2,6 @@ use crate::graphic::Graphic;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::graphene_hash::CacheHash;
use core_types::list::List;
use core_types::render_complexity::RenderComplexity;
use dyn_any::DynAny;
use glam::DAffine2;
@@ -53,9 +52,3 @@ impl BoundingBox for Artboard {
self.0.thumbnail_bounding_box(transform, include_stroke)
}
}
impl RenderComplexity for Artboard {
fn render_complexity(&self) -> usize {
self.0.render_complexity()
}
}
@@ -6,7 +6,6 @@ use core_types::list::{ATTR_APPEARANCE, ATTR_PAINT, Item, ItemAttributeValues, L
use core_types::math::quad::Quad;
use core_types::none;
use core_types::ops::FromAnchorPosition;
use core_types::render_complexity::RenderComplexity;
use core_types::transform::Transform;
use core_types::{ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_GRADIENT_SPREAD, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
use dyn_any::DynAny;
@@ -866,29 +865,6 @@ impl BoundingBox for Graphic {
}
}
impl RenderComplexity for Graphic {
fn render_complexity(&self) -> usize {
match self {
Self::None(_) | Self::NoneList(_) => 0,
Self::Graphic(item) => item.render_complexity(),
Self::Vector(item) => item.render_complexity(),
Self::RasterCPU(item) => item.render_complexity(),
Self::RasterGPU(item) => item.render_complexity(),
Self::Color(item) => item.render_complexity(),
Self::Gradient(item) => item.render_complexity(),
Self::Text(item) => item.render_complexity(),
Self::GraphicList(list) => list.render_complexity(),
Self::VectorList(list) => list.render_complexity(),
Self::RasterCPUList(list) => list.render_complexity(),
Self::RasterGPUList(list) => list.render_complexity(),
Self::ColorList(list) => list.render_complexity(),
Self::GradientList(list) => list.render_complexity(),
Self::TextList(list) => list.render_complexity(),
Self::StrokeList(list) => list.render_complexity(),
}
}
}
// Node definitions moved to graphic-nodes crate
pub trait AtIndex {
@@ -297,17 +297,3 @@ where
self.bounding_box(transform, include_stroke)
}
}
// RenderComplexity trait implementations
impl core_types::render_complexity::RenderComplexity for Raster<CPU> {
fn render_complexity(&self) -> usize {
(self.width * self.height / 500) as usize
}
}
impl core_types::render_complexity::RenderComplexity for Raster<GPU> {
fn render_complexity(&self) -> usize {
// GPU textures currently can't have a thumbnail
usize::MAX
}
}
@@ -13,7 +13,6 @@ use core_types::list::ATTR_APPEARANCE;
use core_types::list::{ATTR_GEOMETRY_CACHE, ATTR_PATHS};
use core_types::list::{Item, List, NodeIdPath};
use core_types::math::quad::Quad;
use core_types::render_complexity::RenderComplexity;
use core_types::transform::Footprint;
use core_types::uuid::{NodeId, generate_uuid};
use core_types::{
@@ -781,7 +780,7 @@ pub struct Background {
}
// TODO: Rename to "Graphical"
pub trait Render: BoundingBox + RenderComplexity {
pub trait Render: BoundingBox {
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams);
fn render_to_vello(&self, scene: &mut VelloSceneBuilder, transform: DAffine2, _render_params: &RenderParams);
@@ -1,7 +1,6 @@
use core_types::Color;
use core_types::color::SRGBA8;
use core_types::list::{ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_MIDPOINT, ATTR_POSITION, Item, List};
use core_types::render_complexity::RenderComplexity;
use dyn_any::DynAny;
use glam::{DAffine2, DVec2};
@@ -320,12 +319,6 @@ impl From<Vec<Color>> for Gradient {
}
}
impl RenderComplexity for Gradient {
fn render_complexity(&self) -> usize {
1
}
}
/// Controls accuracy vs. number of samples tradeoff. 2/255 means the linear approximation will
/// deviate by no more than 2 gradations of 8-bit color from the theoretically perfect curve.
const SAMPLE_THRESHOLD: f64 = 2. / 255.;
@@ -11,7 +11,6 @@ use super::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use super::vector_attributes::{PointId, SegmentId};
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::list::{ATTR_GEOMETRY_CACHE, ATTR_ID, ATTR_PATHS, ATTR_SMOOTH, Item, List};
use core_types::render_complexity::RenderComplexity;
use dyn_any::DynAny;
use glam::{DAffine2, DVec2};
use kurbo::{Affine, BezPath, PathSeg, Rect, Shape};
@@ -956,23 +955,6 @@ impl BoundingBox for Vector {
}
}
impl RenderComplexity for Vector {
fn render_complexity_in_item(item: &Item<Self>) -> usize {
segment_count(paths_from_item_attributes(item))
}
fn render_complexity_in_list(list: &List<Self>, index: usize) -> usize {
segment_count(paths_from_list_row_attributes(list, index))
}
}
/// How many segments the paths draw, which is what their vector costs to render.
fn segment_count(paths: Option<&List<Path>>) -> usize {
let Some(paths) = paths else { return 0 };
paths.iter_element_values().zip(curve_types_of(paths)).map(|(path, curve_type)| path.segment_count(curve_type)).sum()
}
// Note: BoundingBox for List<Vector> is handled by blanket impl in core-types
#[cfg(test)]
@@ -992,17 +974,6 @@ mod tests {
<Vector as core_types::ops::FromAnchorPosition>::from_anchor_position(position)
}
// A layer is too dense for a thumbnail by the segments it draws, whatever handles those bring to the pool
#[test]
fn render_complexity_counts_segments() {
let (vector, paths) = Vector::from_bezpath(&ellipse_bezpath(DVec2::NEG_ONE, DVec2::ONE));
assert_eq!(vector.0.len(), 12);
let item = Item::new_from_element(vector).with_attribute(ATTR_PATHS, paths);
assert_eq!(item.render_complexity(), 4);
assert_eq!(List::new_from_item(item).render_complexity(), 4);
}
// Bezpaths appended together come out as they do appended one at a time, IDs included, with the spans each one added counted
#[test]
fn bezpaths_appended_together_match_one_at_a_time() {